@neetru/sdk 3.7.0 → 3.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +75 -0
  2. package/README.md +66 -1
  3. package/dist/ai.cjs +221 -177
  4. package/dist/ai.d.cts +1 -1
  5. package/dist/ai.d.ts +1 -1
  6. package/dist/ai.mjs +221 -177
  7. package/dist/auth.cjs +1051 -868
  8. package/dist/auth.d.cts +1 -1
  9. package/dist/auth.d.ts +1 -1
  10. package/dist/auth.mjs +1048 -865
  11. package/dist/catalog.cjs +164 -97
  12. package/dist/catalog.d.cts +1 -1
  13. package/dist/catalog.d.ts +1 -1
  14. package/dist/catalog.mjs +164 -97
  15. package/dist/checkout.cjs +182 -115
  16. package/dist/checkout.d.cts +1 -1
  17. package/dist/checkout.d.ts +1 -1
  18. package/dist/checkout.mjs +181 -114
  19. package/dist/db-react.d.cts +1 -1
  20. package/dist/db-react.d.ts +1 -1
  21. package/dist/db.cjs +437 -345
  22. package/dist/db.d.cts +1 -1
  23. package/dist/db.d.ts +1 -1
  24. package/dist/db.mjs +455 -363
  25. package/dist/entitlements.cjs +17 -10
  26. package/dist/entitlements.d.cts +1 -1
  27. package/dist/entitlements.d.ts +1 -1
  28. package/dist/entitlements.mjs +17 -10
  29. package/dist/errors.cjs +15 -8
  30. package/dist/errors.d.cts +24 -3
  31. package/dist/errors.d.ts +24 -3
  32. package/dist/errors.mjs +14 -7
  33. package/dist/firestore-compat.d.cts +1 -1
  34. package/dist/firestore-compat.d.ts +1 -1
  35. package/dist/index.cjs +1544 -1190
  36. package/dist/index.d.cts +177 -3
  37. package/dist/index.d.ts +177 -3
  38. package/dist/index.mjs +1676 -1329
  39. package/dist/mobile.cjs +400 -181
  40. package/dist/mobile.d.cts +59 -4
  41. package/dist/mobile.d.ts +59 -4
  42. package/dist/mobile.mjs +400 -181
  43. package/dist/mocks.cjs +9 -2
  44. package/dist/mocks.d.cts +1 -1
  45. package/dist/mocks.d.ts +1 -1
  46. package/dist/mocks.mjs +9 -2
  47. package/dist/notifications.cjs +197 -130
  48. package/dist/notifications.d.cts +1 -1
  49. package/dist/notifications.d.ts +1 -1
  50. package/dist/notifications.mjs +196 -129
  51. package/dist/react.cjs +303 -282
  52. package/dist/react.d.cts +1 -1
  53. package/dist/react.d.ts +1 -1
  54. package/dist/react.mjs +295 -274
  55. package/dist/support.cjs +299 -229
  56. package/dist/support.d.cts +8 -4
  57. package/dist/support.d.ts +8 -4
  58. package/dist/support.mjs +298 -228
  59. package/dist/telemetry.cjs +234 -167
  60. package/dist/telemetry.d.cts +1 -1
  61. package/dist/telemetry.d.ts +1 -1
  62. package/dist/telemetry.mjs +234 -167
  63. package/dist/{types-Dx0IrOSF.d.ts → types-BYPk_3HR.d.ts} +104 -17
  64. package/dist/{types-Bx4kTLmk.d.cts → types-yv3EDKg2.d.cts} +104 -17
  65. package/dist/usage.cjs +183 -116
  66. package/dist/usage.d.cts +1 -1
  67. package/dist/usage.d.ts +1 -1
  68. package/dist/usage.mjs +183 -116
  69. package/dist/webhooks.cjs +215 -148
  70. package/dist/webhooks.d.cts +1 -1
  71. package/dist/webhooks.d.ts +1 -1
  72. package/dist/webhooks.mjs +212 -145
  73. package/package.json +2 -1
package/dist/ai.cjs CHANGED
@@ -14,102 +14,146 @@ var u = class t extends Error {
14
14
  * para um `NeetruDbErrorCode` mais específico (recuperável vs não).
15
15
  */
16
16
  reason;
17
- constructor(e, r, s, n, i) {
18
- super(r), this.name = "NeetruError", this.code = e, this.status = s, this.requestId = n, this.reason = i, Object.setPrototypeOf(this, t.prototype);
17
+ /**
18
+ * 3.8.0: `x-correlation-id` da requisição que falhou. O SDK gera um UUID por
19
+ * chamada (ou usa o que o chamador passou) e manda no header; o Core grava o
20
+ * mesmo id nos logs/auditoria — cite-o ao abrir um ticket de suporte.
21
+ * `undefined` em erros que acontecem antes de qualquer requisição.
22
+ */
23
+ correlationId;
24
+ constructor(e, i, r, n, o, s) {
25
+ super(i), this.name = "NeetruError", this.code = e, this.status = r, this.requestId = n, this.reason = o, this.correlationId = s, Object.setPrototypeOf(this, t.prototype);
19
26
  }
20
27
  };
21
28
 
29
+ // src/correlation.ts
30
+ var w = "x-correlation-id";
31
+ var V = /^[A-Za-z0-9._:\-]+$/;
32
+ function E(t) {
33
+ return typeof t == "string" && t.length > 0 && t.length <= 128 && V.test(t);
34
+ }
35
+ function J() {
36
+ let t = globalThis.crypto;
37
+ try {
38
+ if (t && typeof t.randomUUID == "function") return t.randomUUID();
39
+ } catch {
40
+ }
41
+ let e = new Uint8Array(16), i = false;
42
+ try {
43
+ t && typeof t.getRandomValues == "function" && (t.getRandomValues(e), i = !0);
44
+ } catch {
45
+ i = false;
46
+ }
47
+ if (!i)
48
+ for (let n = 0; n < e.length; n++) e[n] = Math.floor(Math.random() * 256);
49
+ e[6] = e[6] & 15 | 64, e[8] = e[8] & 63 | 128;
50
+ let r = Array.from(e, (n) => n.toString(16).padStart(2, "0")).join("");
51
+ return `${r.slice(0, 8)}-${r.slice(8, 12)}-${r.slice(12, 16)}-${r.slice(16, 20)}-${r.slice(20)}`;
52
+ }
53
+ function x(t, e) {
54
+ let i, r = {};
55
+ for (let [o, s] of Object.entries(t)) {
56
+ if (o.toLowerCase() === w) {
57
+ E(s) && (i = s);
58
+ continue;
59
+ }
60
+ r[o] = s;
61
+ }
62
+ let n = i ?? (E(e) ? e : void 0) ?? J();
63
+ return r[w] = n, { headers: r, correlationId: n };
64
+ }
65
+
22
66
  // src/http.ts
23
- var z = {
67
+ var Y = {
24
68
  // SDK major 3.x requer Core ≥ 2026.05.1 (suporte a X-Neetru-Version header,
25
69
  // runTransaction write-after-read, verifyWebhookRequest, webhooks 3.0+)
26
70
  3: "2026.05.1"
27
71
  };
28
- function b(t) {
72
+ function A(t) {
29
73
  return t.split("+")[0] ?? t;
30
74
  }
31
- function B(t, e) {
32
- let r = b(t).split(".").map(Number), s = b(e).split(".").map(Number), n = Math.max(r.length, s.length);
33
- for (let i = 0; i < n; i++) {
34
- let a = r[i] ?? 0, o = s[i] ?? 0;
35
- if (a !== o) return a - o;
75
+ function Z(t, e) {
76
+ let i = A(t).split(".").map(Number), r = A(e).split(".").map(Number), n = Math.max(i.length, r.length);
77
+ for (let o = 0; o < n; o++) {
78
+ let s = i[o] ?? 0, c = r[o] ?? 0;
79
+ if (s !== c) return s - c;
36
80
  }
37
81
  return 0;
38
82
  }
39
- function G() {
83
+ function Q() {
40
84
  try {
41
- return "3.7.0";
85
+ return "3.8.1";
42
86
  } catch {
43
87
  return;
44
88
  }
45
89
  }
46
- function J() {
47
- let t = G();
90
+ function ee() {
91
+ let t = Q();
48
92
  return t ? parseInt(t.split(".")[0] ?? "3", 10) : 3;
49
93
  }
50
- var w = /* @__PURE__ */ new Set();
51
- function E(t) {
94
+ var R = /* @__PURE__ */ new Set();
95
+ function k(t) {
52
96
  if (!t) return;
53
- let e = J(), r = z[e];
54
- if (!r) return;
55
- let s = b(t);
56
- if (B(s, r) < 0) {
57
- let n = `${e}:${s}`;
58
- w.has(n) || (w.add(n), console.warn(
59
- `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${t}" \xE9 anterior ao m\xEDnimo recomendado "${r}" para SDK major ${e}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
97
+ let e = ee(), i = Y[e];
98
+ if (!i) return;
99
+ let r = A(t);
100
+ if (Z(r, i) < 0) {
101
+ let n = `${e}:${r}`;
102
+ R.has(n) || (R.add(n), console.warn(
103
+ `[Neetru SDK] Aten\xE7\xE3o: Core vers\xE3o "${t}" \xE9 anterior ao m\xEDnimo recomendado "${i}" para SDK major ${e}. Alguns recursos podem n\xE3o funcionar corretamente. Atualize o Core para a vers\xE3o mais recente.`
60
104
  ));
61
105
  }
62
106
  }
63
- function x(t) {
107
+ function T(t) {
64
108
  return t === 401 ? "unauthorized" : t === 403 ? "forbidden" : t === 404 ? "not_found" : t === 409 ? "conflict" : t === 410 ? "gone" : t === 422 || t === 400 ? "validation_failed" : t === 429 ? "rate_limited" : t >= 500 ? "server_error" : "unknown";
65
109
  }
66
110
 
67
111
  // src/validators.ts
68
- var k = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
69
- function A(t, e) {
70
- if (typeof e != "string" || !k.test(e))
112
+ var S = /^[a-z0-9][a-z0-9_-]{0,62}$/i;
113
+ function b(t, e) {
114
+ if (typeof e != "string" || !S.test(e))
71
115
  throw new u(
72
116
  "validation_failed",
73
- `${t} must match ${k.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
117
+ `${t} must match ${S.source} (lowercase alphanumeric, _, -; first char must be alphanumeric; max 63 chars)`
74
118
  );
75
119
  }
76
120
 
77
121
  // src/ai.ts
78
- var V = "/api/sdk/v1/ai/chat", T = 12e4, _ = 32768, R = 32, v = 4194304, S = 2048, Y = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, Z = /^https:\/\/[^\s]+$/, Q = /* @__PURE__ */ new Set(["low", "high", "auto"]), ee = /* @__PURE__ */ new Set(["system", "user", "assistant"]), M = 100, j = 128, C = 32768, N = 0, I = 2, O = 200, P = 20, $ = 12 * 1024 * 1024, q = 5e4, F = 16, D = 500, te = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), ne = /^[a-zA-Z0-9_-]+$/;
79
- function c(t) {
122
+ var te = "/api/sdk/v1/ai/chat", v = 12e4, _ = 32768, C = 32, I = 4194304, M = 2048, ne = /^data:image\/(?:png|jpe?g|gif|webp);base64,[A-Za-z0-9+/]+={0,2}$/, re = /^https:\/\/[^\s]+$/, ie = /* @__PURE__ */ new Set(["low", "high", "auto"]), oe = /* @__PURE__ */ new Set(["system", "user", "assistant"]), j = 100, N = 128, O = 32768, $ = 0, P = 2, D = 200, q = 20, F = 12 * 1024 * 1024, L = 5e4, U = 16, H = 500, se = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]), ae = /^[a-zA-Z0-9_-]+$/;
123
+ function a(t) {
80
124
  throw new u("validation_failed", t);
81
125
  }
82
- function re(t) {
126
+ function ce(t) {
83
127
  if (t.length === 0 || t.length % 4 !== 0) return false;
84
128
  let e = t.endsWith("==") ? 2 : t.endsWith("=") ? 1 : 0;
85
129
  return !(e > 0 ? t.slice(0, t.length - e) : t).includes("=");
86
130
  }
87
- function se(t) {
131
+ function ue(t) {
88
132
  let e = t.indexOf(",");
89
133
  if (e === -1) return 0;
90
- let r = t.slice(e + 1), s = r.endsWith("==") ? 2 : r.endsWith("=") ? 1 : 0;
91
- return Math.max(0, Math.floor(r.length * 3 / 4) - s);
134
+ let i = t.slice(e + 1), r = i.endsWith("==") ? 2 : i.endsWith("=") ? 1 : 0;
135
+ return Math.max(0, Math.floor(i.length * 3 / 4) - r);
92
136
  }
93
- function ie(t) {
94
- let e = 0, r = 0, s = 0;
137
+ function de(t) {
138
+ let e = 0, i = 0, r = 0;
95
139
  for (let n of t) {
96
- let i = n?.content;
97
- if (Array.isArray(i))
98
- for (let a of i) {
99
- if (e++, e > O)
100
- return `ai: total content parts exceeds ${O} per request`;
101
- if (a && typeof a == "object" && a.type === "image_url") {
102
- if (r++, r > P)
103
- return `ai: total images exceeds ${P} per request`;
104
- let o = a.image_url?.url;
105
- if (typeof o == "string" && o.startsWith("data:") && (s += se(o), s > $))
106
- return `ai: aggregate image bytes exceeds ${$} per request`;
140
+ let o = n?.content;
141
+ if (Array.isArray(o))
142
+ for (let s of o) {
143
+ if (e++, e > D)
144
+ return `ai: total content parts exceeds ${D} per request`;
145
+ if (s && typeof s == "object" && s.type === "image_url") {
146
+ if (i++, i > q)
147
+ return `ai: total images exceeds ${q} per request`;
148
+ let c = s.image_url?.url;
149
+ if (typeof c == "string" && c.startsWith("data:") && (r += ue(c), r > F))
150
+ return `ai: aggregate image bytes exceeds ${F} per request`;
107
151
  }
108
152
  }
109
153
  }
110
154
  return null;
111
155
  }
112
- function oe(t) {
156
+ function le(t) {
113
157
  if (t === void 0) return null;
114
158
  if (t === null || typeof t != "object")
115
159
  return "ai: responseFormat json_schema.schema must be an object";
@@ -120,144 +164,144 @@ function oe(t) {
120
164
  return "ai: responseFormat json_schema.schema is not serializable";
121
165
  }
122
166
  if (e === void 0) return "ai: responseFormat json_schema.schema is invalid";
123
- if (e.length > q)
124
- return `ai: responseFormat json_schema.schema exceeds ${q} serialized chars`;
125
- let r = 0, s = (n, i) => {
126
- if (i > F)
127
- return `ai: responseFormat json_schema.schema exceeds max depth ${F}`;
167
+ if (e.length > L)
168
+ return `ai: responseFormat json_schema.schema exceeds ${L} serialized chars`;
169
+ let i = 0, r = (n, o) => {
170
+ if (o > U)
171
+ return `ai: responseFormat json_schema.schema exceeds max depth ${U}`;
128
172
  if (Array.isArray(n)) {
129
- for (let a of n) {
130
- let o = s(a, i + 1);
131
- if (o) return o;
173
+ for (let s of n) {
174
+ let c = r(s, o + 1);
175
+ if (c) return c;
132
176
  }
133
177
  return null;
134
178
  }
135
179
  if (n && typeof n == "object")
136
- for (let a of Object.getOwnPropertyNames(n)) {
137
- if (te.has(a))
138
- return `ai: responseFormat json_schema.schema has forbidden key: ${a}`;
139
- if (r++, r > D)
140
- return `ai: responseFormat json_schema.schema exceeds ${D} keys`;
141
- let o = s(n[a], i + 1);
142
- if (o) return o;
180
+ for (let s of Object.getOwnPropertyNames(n)) {
181
+ if (se.has(s))
182
+ return `ai: responseFormat json_schema.schema has forbidden key: ${s}`;
183
+ if (i++, i > H)
184
+ return `ai: responseFormat json_schema.schema exceeds ${H} keys`;
185
+ let c = r(n[s], o + 1);
186
+ if (c) return c;
143
187
  }
144
188
  return null;
145
189
  };
146
- return s(t, 0);
190
+ return r(t, 0);
147
191
  }
148
- function ae(t) {
149
- (typeof t != "string" || t.length === 0) && c("ai: image_url.url must be a non-empty string");
192
+ function fe(t) {
193
+ (typeof t != "string" || t.length === 0) && a("ai: image_url.url must be a non-empty string");
150
194
  let e = t;
151
195
  if (e.startsWith("data:")) {
152
- e.length > v && c(`ai: image_url.url (data:) exceeds ${v} chars`), Y.test(e) || c("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
153
- let r = e.slice(e.indexOf(",") + 1);
154
- re(r) || c("ai: image_url.url data: has invalid base64 (length/padding)");
196
+ e.length > I && a(`ai: image_url.url (data:) exceeds ${I} chars`), ne.test(e) || a("ai: image_url.url data: must be data:image/<png|jpeg|jpg|gif|webp>;base64,<...>");
197
+ let i = e.slice(e.indexOf(",") + 1);
198
+ ce(i) || a("ai: image_url.url data: has invalid base64 (length/padding)");
155
199
  return;
156
200
  }
157
201
  if (e.startsWith("https://")) {
158
- e.length > S && c(`ai: image_url.url (https:) exceeds ${S} chars`), Z.test(e) || c("ai: image_url.url https: is invalid");
202
+ e.length > M && a(`ai: image_url.url (https:) exceeds ${M} chars`), re.test(e) || a("ai: image_url.url https: is invalid");
159
203
  return;
160
204
  }
161
- c("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
205
+ a("ai: image_url.url must be a data:image/...;base64 or https:// URL (other schemes are rejected)");
162
206
  }
163
- function ce(t, e) {
207
+ function me(t, e) {
164
208
  if (typeof t == "string") {
165
- t.length === 0 && c("ai: message content string must be non-empty"), t.length > _ && c(`ai: message content exceeds ${_} chars`);
209
+ t.length === 0 && a("ai: message content string must be non-empty"), t.length > _ && a(`ai: message content exceeds ${_} chars`);
166
210
  return;
167
211
  }
168
- (!Array.isArray(t) || t.length === 0) && c("ai: message content must be a non-empty string or array of parts"), t.length > R && c(`ai: message content has more than ${R} parts`);
169
- for (let r of t) {
170
- (!r || typeof r != "object") && c("ai: each content part must be an object");
171
- let s = r.type;
172
- if (s === "text") {
173
- let n = r.text;
174
- (typeof n != "string" || n.length === 0) && c("ai: text part must have non-empty { text: string }"), n.length > _ && c(`ai: text part exceeds ${_} chars`);
175
- } else if (s === "image_url") {
176
- e !== "user" && c(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
177
- let n = r.image_url;
178
- (!n || typeof n != "object") && c("ai: image_url part must have { image_url: { url } }"), ae(n.url);
179
- let i = n.detail;
180
- i !== void 0 && (typeof i != "string" || !Q.has(i)) && c("ai: image_url.detail must be 'low' | 'high' | 'auto'");
212
+ (!Array.isArray(t) || t.length === 0) && a("ai: message content must be a non-empty string or array of parts"), t.length > C && a(`ai: message content has more than ${C} parts`);
213
+ for (let i of t) {
214
+ (!i || typeof i != "object") && a("ai: each content part must be an object");
215
+ let r = i.type;
216
+ if (r === "text") {
217
+ let n = i.text;
218
+ (typeof n != "string" || n.length === 0) && a("ai: text part must have non-empty { text: string }"), n.length > _ && a(`ai: text part exceeds ${_} chars`);
219
+ } else if (r === "image_url") {
220
+ e !== "user" && a(`ai: image_url is only allowed in role 'user' messages (got '${e}')`);
221
+ let n = i.image_url;
222
+ (!n || typeof n != "object") && a("ai: image_url part must have { image_url: { url } }"), fe(n.url);
223
+ let o = n.detail;
224
+ o !== void 0 && (typeof o != "string" || !ie.has(o)) && a("ai: image_url.detail must be 'low' | 'high' | 'auto'");
181
225
  } else
182
- c("ai: content part type must be 'text' or 'image_url'");
226
+ a("ai: content part type must be 'text' or 'image_url'");
183
227
  }
184
228
  }
185
- function ue(t) {
186
- (!t || typeof t != "object") && c("ai: responseFormat must be an object");
229
+ function pe(t) {
230
+ (!t || typeof t != "object") && a("ai: responseFormat must be an object");
187
231
  let e = t.type;
188
232
  if (!(e === "text" || e === "json_object")) {
189
233
  if (e === "json_schema") {
190
- let r = t.json_schema;
191
- (!r || typeof r != "object") && c("ai: responseFormat json_schema requires { json_schema: { name } }");
192
- let s = r, n = s.name;
193
- if ((typeof n != "string" || n.length === 0) && c("ai: responseFormat json_schema.name is required"), n.length > 64 && c("ai: responseFormat json_schema.name exceeds 64 chars"), ne.test(n) || c("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), s.description !== void 0 && (typeof s.description != "string" && c("ai: responseFormat json_schema.description must be a string"), s.description.length > 1e3 && c("ai: responseFormat json_schema.description exceeds 1000 chars")), s.strict !== void 0 && typeof s.strict != "boolean" && c("ai: responseFormat json_schema.strict must be a boolean"), s.schema !== void 0) {
194
- let i = oe(s.schema);
195
- i && c(i);
234
+ let i = t.json_schema;
235
+ (!i || typeof i != "object") && a("ai: responseFormat json_schema requires { json_schema: { name } }");
236
+ let r = i, n = r.name;
237
+ if ((typeof n != "string" || n.length === 0) && a("ai: responseFormat json_schema.name is required"), n.length > 64 && a("ai: responseFormat json_schema.name exceeds 64 chars"), ae.test(n) || a("ai: responseFormat json_schema.name must match a-zA-Z0-9_-"), r.description !== void 0 && (typeof r.description != "string" && a("ai: responseFormat json_schema.description must be a string"), r.description.length > 1e3 && a("ai: responseFormat json_schema.description exceeds 1000 chars")), r.strict !== void 0 && typeof r.strict != "boolean" && a("ai: responseFormat json_schema.strict must be a boolean"), r.schema !== void 0) {
238
+ let o = le(r.schema);
239
+ o && a(o);
196
240
  }
197
241
  return;
198
242
  }
199
- c("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
243
+ a("ai: responseFormat.type must be 'text' | 'json_object' | 'json_schema'");
200
244
  }
201
245
  }
202
- function U(t, e, r) {
246
+ function K(t, e, i) {
203
247
  if (!e || typeof e != "object")
204
248
  throw new u("validation_failed", "ai: options object is required");
205
249
  if (typeof e.model != "string" || e.model.length === 0)
206
250
  throw new u("validation_failed", "ai: model is required");
207
- if (e.model.length > j)
208
- throw new u("validation_failed", `ai: model exceeds ${j} chars`);
251
+ if (e.model.length > N)
252
+ throw new u("validation_failed", `ai: model exceeds ${N} chars`);
209
253
  if (!Array.isArray(e.messages) || e.messages.length === 0)
210
254
  throw new u("validation_failed", "ai: messages must be a non-empty array");
211
- if (e.messages.length > M)
212
- throw new u("validation_failed", `ai: messages exceeds ${M} per request`);
213
- for (let o of e.messages) {
214
- if (!o || typeof o != "object" || typeof o.role != "string" || !ee.has(o.role))
255
+ if (e.messages.length > j)
256
+ throw new u("validation_failed", `ai: messages exceeds ${j} per request`);
257
+ for (let c of e.messages) {
258
+ if (!c || typeof c != "object" || typeof c.role != "string" || !oe.has(c.role))
215
259
  throw new u(
216
260
  "validation_failed",
217
261
  "ai: each message role must be 'system' | 'user' | 'assistant'"
218
262
  );
219
- ce(o.content, o.role);
263
+ me(c.content, c.role);
220
264
  }
221
- let s = ie(e.messages);
222
- if (s) throw new u("validation_failed", s);
223
- let n = e.productId ?? t.productId, i = e.tenantId ?? t.tenantId;
265
+ let r = de(e.messages);
266
+ if (r) throw new u("validation_failed", r);
267
+ let n = e.productId ?? t.productId, o = e.tenantId ?? t.tenantId;
224
268
  if (!n)
225
269
  throw new u(
226
270
  "validation_failed",
227
271
  "ai: productId required (pass to options or set on createNeetruClient)"
228
272
  );
229
- if (!i)
273
+ if (!o)
230
274
  throw new u(
231
275
  "validation_failed",
232
276
  "ai: tenantId required (pass to options or set on createNeetruClient)"
233
277
  );
234
- A("productId", n), A("tenantId", i);
235
- let a = {
278
+ b("productId", n), b("tenantId", o);
279
+ let s = {
236
280
  productId: n,
237
- tenantId: i,
281
+ tenantId: o,
238
282
  model: e.model,
239
283
  messages: e.messages,
240
- stream: r
284
+ stream: i
241
285
  };
242
286
  if (e.maxTokens !== void 0) {
243
- if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > C)
287
+ if (!Number.isInteger(e.maxTokens) || e.maxTokens <= 0 || e.maxTokens > O)
244
288
  throw new u(
245
289
  "validation_failed",
246
- `ai: maxTokens must be a positive integer <= ${C}`
290
+ `ai: maxTokens must be a positive integer <= ${O}`
247
291
  );
248
- a.maxTokens = e.maxTokens;
292
+ s.maxTokens = e.maxTokens;
249
293
  }
250
294
  if (e.temperature !== void 0) {
251
- if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < N || e.temperature > I)
295
+ if (typeof e.temperature != "number" || !Number.isFinite(e.temperature) || e.temperature < $ || e.temperature > P)
252
296
  throw new u(
253
297
  "validation_failed",
254
- `ai: temperature must be a finite number between ${N} and ${I}`
298
+ `ai: temperature must be a finite number between ${$} and ${P}`
255
299
  );
256
- a.temperature = e.temperature;
300
+ s.temperature = e.temperature;
257
301
  }
258
- return e.responseFormat !== void 0 && (ue(e.responseFormat), a.responseFormat = e.responseFormat), a;
302
+ return e.responseFormat !== void 0 && (pe(e.responseFormat), s.responseFormat = e.responseFormat), s;
259
303
  }
260
- async function X(t) {
304
+ async function B(t) {
261
305
  try {
262
306
  let e = await t.text();
263
307
  return e ? JSON.parse(e) : void 0;
@@ -265,129 +309,129 @@ async function X(t) {
265
309
  return;
266
310
  }
267
311
  }
268
- function de(t, e) {
269
- let r = t.replace(/\/+$/, ""), s = e.startsWith("/") ? e : `/${e}`;
270
- return `${r}${s}`;
312
+ function ge(t, e) {
313
+ let i = t.replace(/\/+$/, ""), r = e.startsWith("/") ? e : `/${e}`;
314
+ return `${i}${r}`;
271
315
  }
272
- async function L(t, e, r, s) {
316
+ async function X(t, e, i, r) {
273
317
  if (!t.apiKey)
274
318
  throw new u(
275
319
  "missing_api_key",
276
320
  "ai requires an apiKey. Pass it to createNeetruClient({ apiKey }) or set NEETRU_API_KEY env var."
277
321
  );
278
- let n = de(t.baseUrl, V), a = { method: "POST", headers: {
322
+ let n = ge(t.baseUrl, te), { headers: o, correlationId: s } = x({
279
323
  "content-type": "application/json",
280
- accept: s ? "text/event-stream" : "application/json",
324
+ accept: r ? "text/event-stream" : "application/json",
281
325
  authorization: `Bearer ${t.apiKey}`
282
- }, body: JSON.stringify(e) };
283
- s ? r && (a.signal = r) : a.signal = r ?? AbortSignal.timeout(T);
284
- let o;
326
+ }), c = { method: "POST", headers: o, body: JSON.stringify(e) };
327
+ r ? i && (c.signal = i) : c.signal = i ?? AbortSignal.timeout(v);
328
+ let l;
285
329
  try {
286
- o = await t.fetch(n, a);
330
+ l = await t.fetch(n, c);
287
331
  } catch (d) {
288
- let f = d instanceof DOMException && d.name === "TimeoutError" ? `Network error: timeout after ${T / 1e3}s` : d instanceof DOMException && d.name === "AbortError" ? "Network error: request aborted" : `Network error: ${d instanceof Error ? d.message : "fetch failed"}`;
289
- throw new u("network_error", f);
332
+ let m = d instanceof DOMException && d.name === "TimeoutError" ? `Network error: timeout after ${v / 1e3}s` : d instanceof DOMException && d.name === "AbortError" ? "Network error: request aborted" : `Network error: ${d instanceof Error ? d.message : "fetch failed"}`;
333
+ throw new u("network_error", m, void 0, void 0, void 0, s);
290
334
  }
291
- let g = o.headers.get("x-request-id") ?? o.headers.get("x-correlation-id") ?? void 0;
292
- if (!o.ok) {
293
- let d = await X(o), f = x(o.status), m = `HTTP ${o.status}`;
335
+ let y = l.headers.get("x-request-id") ?? l.headers.get("x-correlation-id") ?? void 0;
336
+ if (!l.ok) {
337
+ let d = await B(l), m = T(l.status), g = `HTTP ${l.status}`;
294
338
  if (d && typeof d == "object" && "error" in d) {
295
- let l = d.error;
296
- typeof l == "string" ? m = l : l && typeof l == "object" && (typeof l.code == "string" && (f = l.code), typeof l.message == "string" && (m = l.message));
339
+ let f = d.error;
340
+ typeof f == "string" ? g = f : f && typeof f == "object" && (typeof f.code == "string" && (m = f.code), typeof f.message == "string" && (g = f.message));
297
341
  }
298
- throw new u(f, m, o.status, g);
342
+ throw new u(m, g, l.status, y, void 0, s);
299
343
  }
300
- let h = o.headers.get("x-neetru-version");
301
- return h && E(h), o;
344
+ let p = l.headers.get("x-neetru-version");
345
+ return p && k(p), l;
302
346
  }
303
- function H(t) {
347
+ function z(t) {
304
348
  return {
305
349
  provider: t.headers.get("x-neetru-provider") ?? "",
306
350
  usageWarning: t.headers.get("x-neetru-ai-usage-warning") === "1"
307
351
  };
308
352
  }
309
- function K(t) {
353
+ function W(t) {
310
354
  let e = [];
311
- for (let s of t.split(`
355
+ for (let r of t.split(`
312
356
  `)) {
313
- let n = s.replace(/\r$/, "");
357
+ let n = r.replace(/\r$/, "");
314
358
  if (n.startsWith("data:")) {
315
- let i = n.slice(5);
316
- i.startsWith(" ") && (i = i.slice(1)), e.push(i);
359
+ let o = n.slice(5);
360
+ o.startsWith(" ") && (o = o.slice(1)), e.push(o);
317
361
  }
318
362
  }
319
363
  if (e.length === 0) return null;
320
- let r = e.join(`
364
+ let i = e.join(`
321
365
  `);
322
- if (r === "[DONE]") return { done: true };
366
+ if (i === "[DONE]") return { done: true };
323
367
  try {
324
- let n = JSON.parse(r)?.choices?.[0]?.delta?.content;
368
+ let n = JSON.parse(i)?.choices?.[0]?.delta?.content;
325
369
  return typeof n == "string" && n.length > 0 ? { content: n } : null;
326
370
  } catch {
327
371
  return null;
328
372
  }
329
373
  }
330
- function ye(t) {
374
+ function ke(t) {
331
375
  return {
332
376
  async chat(e) {
333
- let r = U(t, e, false), s = await L(t, r, e.signal, false), { provider: n, usageWarning: i } = H(s), a = await X(s);
334
- if (!a || a.ok !== true || !Array.isArray(a.choices))
377
+ let i = K(t, e, false), r = await X(t, i, e.signal, false), { provider: n, usageWarning: o } = z(r), s = await B(r);
378
+ if (!s || s.ok !== true || !Array.isArray(s.choices))
335
379
  throw new u("invalid_response", "ai.chat response missing ok/choices");
336
380
  return {
337
- choices: a.choices,
338
- usage: a.usage ?? { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
339
- model: a.model ?? e.model,
340
- provider: a.provider ?? n ?? "",
341
- usageWarning: i
381
+ choices: s.choices,
382
+ usage: s.usage ?? { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
383
+ model: s.model ?? e.model,
384
+ provider: s.provider ?? n ?? "",
385
+ usageWarning: o
342
386
  };
343
387
  },
344
388
  stream(e) {
345
- let r = U(t, e, true), s = L(t, r, e.signal, true), n = s.then(H);
389
+ let i = K(t, e, true), r = X(t, i, e.signal, true), n = r.then(z);
346
390
  n.catch(() => {
347
391
  });
348
- async function* i() {
349
- let o = (await s).body;
350
- if (!o)
392
+ async function* o() {
393
+ let c = (await r).body;
394
+ if (!c)
351
395
  throw new u("invalid_response", "ai.stream: response has no body");
352
- let g = o.getReader(), h = new TextDecoder(), d = "";
396
+ let l = c.getReader(), y = new TextDecoder(), p = "";
353
397
  try {
354
398
  for (; ; ) {
355
- let { done: m, value: l } = await g.read();
399
+ let { done: m, value: g } = await l.read();
356
400
  if (m) break;
357
- d += h.decode(l, { stream: !0 });
358
- let y;
359
- for (; (y = d.indexOf(`
401
+ p += y.decode(g, { stream: !0 });
402
+ let f;
403
+ for (; (f = p.indexOf(`
360
404
 
361
405
  `)) !== -1; ) {
362
- let W = d.slice(0, y);
363
- d = d.slice(y + 2);
364
- let p = K(W);
365
- if (p && "done" in p) return;
366
- p && "content" in p && (yield p.content);
406
+ let G = p.slice(0, f);
407
+ p = p.slice(f + 2);
408
+ let h = W(G);
409
+ if (h && "done" in h) return;
410
+ h && "content" in h && (yield h.content);
367
411
  }
368
412
  }
369
- let f = d.trim();
370
- if (f) {
371
- let m = K(f);
413
+ let d = p.trim();
414
+ if (d) {
415
+ let m = W(d);
372
416
  m && "content" in m && (yield m.content);
373
417
  }
374
418
  } finally {
375
419
  try {
376
- g.releaseLock();
420
+ l.releaseLock();
377
421
  } catch {
378
422
  }
379
423
  try {
380
- await o.cancel();
424
+ await c.cancel();
381
425
  } catch {
382
426
  }
383
427
  }
384
428
  }
385
429
  return {
386
430
  meta: n,
387
- [Symbol.asyncIterator]: i
431
+ [Symbol.asyncIterator]: o
388
432
  };
389
433
  }
390
434
  };
391
435
  }
392
436
 
393
- exports.createAiNamespace = ye;
437
+ exports.createAiNamespace = ke;
package/dist/ai.d.cts CHANGED
@@ -1,3 +1,3 @@
1
- export { A as AiChatChoice, a as AiChatMessage, b as AiChatOptions, c as AiChatResult, d as AiChatUsage, e as AiContentPart, f as AiImageUrlPart, g as AiNamespace, h as AiResponseFormat, i as AiStreamHandle, j as AiStreamMeta, k as AiTextPart, aJ as createAiNamespace } from './types-Bx4kTLmk.cjs';
1
+ export { A as AiChatChoice, a as AiChatMessage, b as AiChatOptions, c as AiChatResult, d as AiChatUsage, e as AiContentPart, f as AiImageUrlPart, g as AiNamespace, h as AiResponseFormat, i as AiStreamHandle, j as AiStreamMeta, k as AiTextPart, aK as createAiNamespace } from './types-yv3EDKg2.cjs';
2
2
  import 'drizzle-orm/node-postgres';
3
3
  import './errors.cjs';
package/dist/ai.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export { A as AiChatChoice, a as AiChatMessage, b as AiChatOptions, c as AiChatResult, d as AiChatUsage, e as AiContentPart, f as AiImageUrlPart, g as AiNamespace, h as AiResponseFormat, i as AiStreamHandle, j as AiStreamMeta, k as AiTextPart, aJ as createAiNamespace } from './types-Dx0IrOSF.js';
1
+ export { A as AiChatChoice, a as AiChatMessage, b as AiChatOptions, c as AiChatResult, d as AiChatUsage, e as AiContentPart, f as AiImageUrlPart, g as AiNamespace, h as AiResponseFormat, i as AiStreamHandle, j as AiStreamMeta, k as AiTextPart, aK as createAiNamespace } from './types-BYPk_3HR.js';
2
2
  import 'drizzle-orm/node-postgres';
3
3
  import './errors.js';