vibezcheck 0.1.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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -0
  3. package/dist/ai-sdk/index.d.mts +34 -0
  4. package/dist/ai-sdk/index.d.ts +34 -0
  5. package/dist/ai-sdk/index.js +982 -0
  6. package/dist/ai-sdk/index.js.map +1 -0
  7. package/dist/ai-sdk/index.mjs +944 -0
  8. package/dist/ai-sdk/index.mjs.map +1 -0
  9. package/dist/auth/index.d.mts +59 -0
  10. package/dist/auth/index.d.ts +59 -0
  11. package/dist/auth/index.js +129 -0
  12. package/dist/auth/index.js.map +1 -0
  13. package/dist/auth/index.mjs +90 -0
  14. package/dist/auth/index.mjs.map +1 -0
  15. package/dist/billing/index.d.mts +48 -0
  16. package/dist/billing/index.d.ts +48 -0
  17. package/dist/billing/index.js +128 -0
  18. package/dist/billing/index.js.map +1 -0
  19. package/dist/billing/index.mjs +90 -0
  20. package/dist/billing/index.mjs.map +1 -0
  21. package/dist/client-MJ3tl7bz.d.mts +44 -0
  22. package/dist/client-txrE0D_D.d.ts +44 -0
  23. package/dist/customers/index.d.mts +49 -0
  24. package/dist/customers/index.d.ts +49 -0
  25. package/dist/customers/index.js +158 -0
  26. package/dist/customers/index.js.map +1 -0
  27. package/dist/customers/index.mjs +119 -0
  28. package/dist/customers/index.mjs.map +1 -0
  29. package/dist/index.d.mts +92 -0
  30. package/dist/index.d.ts +92 -0
  31. package/dist/index.js +1458 -0
  32. package/dist/index.js.map +1 -0
  33. package/dist/index.mjs +1386 -0
  34. package/dist/index.mjs.map +1 -0
  35. package/dist/meter/index.d.mts +131 -0
  36. package/dist/meter/index.d.ts +131 -0
  37. package/dist/meter/index.js +895 -0
  38. package/dist/meter/index.js.map +1 -0
  39. package/dist/meter/index.mjs +843 -0
  40. package/dist/meter/index.mjs.map +1 -0
  41. package/dist/pricing/index.d.mts +40 -0
  42. package/dist/pricing/index.d.ts +40 -0
  43. package/dist/pricing/index.js +178 -0
  44. package/dist/pricing/index.js.map +1 -0
  45. package/dist/pricing/index.mjs +146 -0
  46. package/dist/pricing/index.mjs.map +1 -0
  47. package/dist/types-CSrSmsd1.d.mts +159 -0
  48. package/dist/types-CSrSmsd1.d.ts +159 -0
  49. package/package.json +131 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,1386 @@
1
+ // src/index.ts
2
+ import Stripe5 from "stripe";
3
+
4
+ // src/meter/client.ts
5
+ import Stripe from "stripe";
6
+
7
+ // src/meter/batcher.ts
8
+ var MeterBatcher = class {
9
+ queue = [];
10
+ timer = null;
11
+ isFlushing = false;
12
+ maxBatchSize;
13
+ flushIntervalMs;
14
+ stripeClient;
15
+ eventName;
16
+ onUsageCallback;
17
+ onErrorCallback;
18
+ debug;
19
+ // In-memory ledger for local stats
20
+ totalRequests = 0;
21
+ totalTokens = 0;
22
+ totalInputTokens = 0;
23
+ totalOutputTokens = 0;
24
+ totalReasoningTokens = 0;
25
+ totalCostUSD = 0;
26
+ byModel = {};
27
+ constructor(options = {}) {
28
+ this.stripeClient = options.stripe;
29
+ this.eventName = options.eventName || "token-billing-tokens";
30
+ this.maxBatchSize = options.batching?.maxBatchSize ?? 50;
31
+ this.flushIntervalMs = options.batching?.flushIntervalMs ?? 50;
32
+ this.onUsageCallback = options.onUsage;
33
+ this.onErrorCallback = options.onError;
34
+ this.debug = options.debug ?? false;
35
+ }
36
+ /**
37
+ * Enqueue a usage event for batch dispatching
38
+ */
39
+ enqueue(event) {
40
+ this.recordInLedger(event);
41
+ if (this.onUsageCallback) {
42
+ try {
43
+ const res = this.onUsageCallback(event);
44
+ if (res instanceof Promise) {
45
+ res.catch((err) => {
46
+ if (this.debug) console.error("[vibezcheck] Error in onUsage callback:", err);
47
+ });
48
+ }
49
+ } catch (err) {
50
+ if (this.debug) console.error("[vibezcheck] Error in onUsage callback:", err);
51
+ }
52
+ }
53
+ if (!this.stripeClient) {
54
+ if (this.debug) {
55
+ console.log(
56
+ `[vibezcheck:local] \u{1F4CA} ${event.model} | Tokens: ${event.usage.totalTokens} | Cost: $${event.cost.totalUSD.toFixed(6)}`
57
+ );
58
+ }
59
+ return;
60
+ }
61
+ this.queue.push(event);
62
+ if (this.queue.length >= this.maxBatchSize) {
63
+ this.flush().catch((err) => {
64
+ if (this.debug) console.error("[vibezcheck] Batch flush error:", err);
65
+ });
66
+ } else if (!this.timer) {
67
+ this.timer = setTimeout(() => {
68
+ this.timer = null;
69
+ this.flush().catch((err) => {
70
+ if (this.debug) console.error("[vibezcheck] Debounce flush error:", err);
71
+ });
72
+ }, this.flushIntervalMs);
73
+ }
74
+ }
75
+ /**
76
+ * Immediately flush all queued events to Stripe
77
+ */
78
+ async flush() {
79
+ if (this.timer) {
80
+ clearTimeout(this.timer);
81
+ this.timer = null;
82
+ }
83
+ if (this.queue.length === 0 || !this.stripeClient || this.isFlushing) {
84
+ return;
85
+ }
86
+ this.isFlushing = true;
87
+ const eventsToSend = [...this.queue];
88
+ this.queue = [];
89
+ try {
90
+ await this.sendEventsToStripe(eventsToSend);
91
+ } catch (error) {
92
+ const err = error instanceof Error ? error : new Error(String(error));
93
+ if (this.debug) {
94
+ console.error("[vibezcheck] Failed to send meter events to Stripe:", err);
95
+ }
96
+ if (this.onErrorCallback) {
97
+ this.onErrorCallback(err, eventsToSend);
98
+ }
99
+ } finally {
100
+ this.isFlushing = false;
101
+ if (this.queue.length > 0) {
102
+ this.flush().catch(() => {
103
+ });
104
+ }
105
+ }
106
+ }
107
+ /**
108
+ * Sends events to Stripe Billing Meter Events API
109
+ */
110
+ async sendEventsToStripe(events) {
111
+ if (!this.stripeClient) return;
112
+ for (const event of events) {
113
+ const customerId = event.customerId;
114
+ if (!customerId) {
115
+ continue;
116
+ }
117
+ const timestamp = event.timestamp || (/* @__PURE__ */ new Date()).toISOString();
118
+ const model = `${event.provider}/${event.model}`;
119
+ if (event.usage.inputTokens > 0) {
120
+ try {
121
+ await this.stripeClient.v2.billing.meterEvents.create({
122
+ event_name: this.eventName,
123
+ timestamp,
124
+ payload: {
125
+ stripe_customer_id: customerId,
126
+ value: event.usage.inputTokens.toString(),
127
+ model,
128
+ token_type: "input",
129
+ cached_tokens: (event.usage.cachedTokens ?? 0).toString(),
130
+ ...event.metadata ? event.metadata : {}
131
+ }
132
+ });
133
+ } catch (e) {
134
+ if (this.debug) console.warn("[vibezcheck] Input meter event error:", e);
135
+ }
136
+ }
137
+ if (event.usage.outputTokens > 0) {
138
+ try {
139
+ await this.stripeClient.v2.billing.meterEvents.create({
140
+ event_name: this.eventName,
141
+ timestamp,
142
+ payload: {
143
+ stripe_customer_id: customerId,
144
+ value: event.usage.outputTokens.toString(),
145
+ model,
146
+ token_type: "output",
147
+ reasoning_tokens: (event.usage.reasoningTokens ?? 0).toString(),
148
+ visible_tokens: (event.usage.visibleOutputTokens ?? event.usage.outputTokens).toString(),
149
+ ...event.metadata ? event.metadata : {}
150
+ }
151
+ });
152
+ } catch (e) {
153
+ if (this.debug) console.warn("[vibezcheck] Output meter event error:", e);
154
+ }
155
+ }
156
+ }
157
+ }
158
+ /**
159
+ * Updates internal in-memory ledger
160
+ */
161
+ recordInLedger(event) {
162
+ this.totalRequests += 1;
163
+ this.totalTokens += event.usage.totalTokens;
164
+ this.totalInputTokens += event.usage.inputTokens;
165
+ this.totalOutputTokens += event.usage.outputTokens;
166
+ this.totalReasoningTokens += event.usage.reasoningTokens ?? 0;
167
+ this.totalCostUSD += event.cost.totalUSD;
168
+ const modelKey = event.model;
169
+ if (!this.byModel[modelKey]) {
170
+ this.byModel[modelKey] = { requests: 0, tokens: 0, costUSD: 0 };
171
+ }
172
+ this.byModel[modelKey].requests += 1;
173
+ this.byModel[modelKey].tokens += event.usage.totalTokens;
174
+ this.byModel[modelKey].costUSD += event.cost.totalUSD;
175
+ }
176
+ /**
177
+ * Get in-memory usage summary
178
+ */
179
+ getSummary() {
180
+ return {
181
+ totalRequests: this.totalRequests,
182
+ totalTokens: this.totalTokens,
183
+ totalInputTokens: this.totalInputTokens,
184
+ totalOutputTokens: this.totalOutputTokens,
185
+ totalReasoningTokens: this.totalReasoningTokens,
186
+ totalCostUSD: Number(this.totalCostUSD.toFixed(6)),
187
+ byModel: { ...this.byModel }
188
+ };
189
+ }
190
+ /**
191
+ * Reset in-memory ledger
192
+ */
193
+ resetLedger() {
194
+ this.totalRequests = 0;
195
+ this.totalTokens = 0;
196
+ this.totalInputTokens = 0;
197
+ this.totalOutputTokens = 0;
198
+ this.totalReasoningTokens = 0;
199
+ this.totalCostUSD = 0;
200
+ this.byModel = {};
201
+ }
202
+ };
203
+
204
+ // src/meter/extractors/openai.ts
205
+ function extractOpenAIResponseUsage(response) {
206
+ if (!response || typeof response !== "object") return null;
207
+ if ("choices" in response && "usage" in response && response.usage) {
208
+ const rawUsage = response.usage;
209
+ const model = response.model || "gpt-4o";
210
+ const inputTokens = rawUsage.prompt_tokens ?? 0;
211
+ const outputTokens = rawUsage.completion_tokens ?? 0;
212
+ const reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens ?? 0;
213
+ const cachedTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? 0;
214
+ return {
215
+ model,
216
+ provider: "openai",
217
+ usage: {
218
+ inputTokens,
219
+ outputTokens,
220
+ totalTokens: inputTokens + outputTokens,
221
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
222
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
223
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
224
+ }
225
+ };
226
+ }
227
+ if ("data" in response && "usage" in response && response.usage && "model" in response) {
228
+ const rawUsage = response.usage;
229
+ const inputTokens = rawUsage.prompt_tokens ?? 0;
230
+ return {
231
+ model: response.model || "text-embedding-3-small",
232
+ provider: "openai",
233
+ usage: {
234
+ inputTokens,
235
+ outputTokens: 0,
236
+ totalTokens: inputTokens
237
+ }
238
+ };
239
+ }
240
+ if ("status" in response && "usage" in response && response.usage) {
241
+ const rawUsage = response.usage;
242
+ const model = response.model || "gpt-5.6-sol";
243
+ const inputTokens = rawUsage.input_tokens ?? rawUsage.prompt_tokens ?? 0;
244
+ const outputTokens = rawUsage.output_tokens ?? rawUsage.completion_tokens ?? 0;
245
+ const reasoningTokens = rawUsage.output_token_details?.reasoning_tokens ?? rawUsage.completion_tokens_details?.reasoning_tokens ?? 0;
246
+ const cachedTokens = rawUsage.input_token_details?.cached_tokens ?? rawUsage.prompt_tokens_details?.cached_tokens ?? 0;
247
+ return {
248
+ model,
249
+ provider: "openai",
250
+ usage: {
251
+ inputTokens,
252
+ outputTokens,
253
+ totalTokens: inputTokens + outputTokens,
254
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
255
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
256
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
257
+ }
258
+ };
259
+ }
260
+ return null;
261
+ }
262
+ function inspectOpenAIStreamChunk(chunk) {
263
+ if (!chunk || typeof chunk !== "object") return {};
264
+ const model = chunk.model;
265
+ if (chunk.usage) {
266
+ const rawUsage = chunk.usage;
267
+ const inputTokens = rawUsage.prompt_tokens ?? rawUsage.input_tokens ?? 0;
268
+ const outputTokens = rawUsage.completion_tokens ?? rawUsage.output_tokens ?? 0;
269
+ const reasoningTokens = rawUsage.completion_tokens_details?.reasoning_tokens ?? rawUsage.output_token_details?.reasoning_tokens ?? 0;
270
+ const cachedTokens = rawUsage.prompt_tokens_details?.cached_tokens ?? rawUsage.input_token_details?.cached_tokens ?? 0;
271
+ return {
272
+ model,
273
+ usage: {
274
+ inputTokens,
275
+ outputTokens,
276
+ totalTokens: inputTokens + outputTokens,
277
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
278
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
279
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
280
+ }
281
+ };
282
+ }
283
+ if (chunk.type === "response.completed" || chunk.type === "response.done") {
284
+ if (chunk.response?.usage) {
285
+ const rawUsage = chunk.response.usage;
286
+ const inputTokens = rawUsage.input_tokens ?? 0;
287
+ const outputTokens = rawUsage.output_tokens ?? 0;
288
+ const reasoningTokens = rawUsage.output_token_details?.reasoning_tokens ?? 0;
289
+ const cachedTokens = rawUsage.input_token_details?.cached_tokens ?? 0;
290
+ return {
291
+ model: chunk.response.model || model,
292
+ usage: {
293
+ inputTokens,
294
+ outputTokens,
295
+ totalTokens: inputTokens + outputTokens,
296
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
297
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
298
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
299
+ }
300
+ };
301
+ }
302
+ }
303
+ return { model };
304
+ }
305
+
306
+ // src/meter/extractors/anthropic.ts
307
+ function extractAnthropicResponseUsage(response) {
308
+ if (!response || typeof response !== "object") return null;
309
+ if (response.type === "message" || "content" in response && "usage" in response) {
310
+ const rawUsage = response.usage || {};
311
+ const model = response.model || "claude-3-7-sonnet";
312
+ const inputTokens = rawUsage.input_tokens ?? 0;
313
+ const outputTokens = rawUsage.output_tokens ?? 0;
314
+ const cachedTokens = rawUsage.cache_read_input_tokens ?? 0;
315
+ const cacheWriteTokens = rawUsage.cache_creation_input_tokens ?? 0;
316
+ let reasoningTokens = void 0;
317
+ if (Array.isArray(response.content)) {
318
+ const thinkingBlocks = response.content.filter((b) => b.type === "thinking");
319
+ if (thinkingBlocks.length > 0) {
320
+ reasoningTokens = rawUsage.thinking_tokens ?? void 0;
321
+ }
322
+ }
323
+ return {
324
+ model,
325
+ provider: "anthropic",
326
+ usage: {
327
+ inputTokens,
328
+ outputTokens,
329
+ totalTokens: inputTokens + outputTokens,
330
+ reasoningTokens,
331
+ visibleOutputTokens: reasoningTokens !== void 0 ? Math.max(0, outputTokens - reasoningTokens) : outputTokens,
332
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0,
333
+ cacheWriteTokens: cacheWriteTokens > 0 ? cacheWriteTokens : void 0
334
+ }
335
+ };
336
+ }
337
+ return null;
338
+ }
339
+ var AnthropicStreamAccumulator = class {
340
+ model = "claude-3-7-sonnet";
341
+ inputTokens = 0;
342
+ outputTokens = 0;
343
+ cachedTokens = 0;
344
+ cacheWriteTokens = 0;
345
+ reasoningTokens = 0;
346
+ processEvent(event) {
347
+ if (!event || typeof event !== "object") return;
348
+ if (event.type === "message_start" && event.message) {
349
+ if (event.message.model) {
350
+ this.model = event.message.model;
351
+ }
352
+ if (event.message.usage) {
353
+ this.inputTokens = event.message.usage.input_tokens ?? 0;
354
+ this.cachedTokens = event.message.usage.cache_read_input_tokens ?? 0;
355
+ this.cacheWriteTokens = event.message.usage.cache_creation_input_tokens ?? 0;
356
+ }
357
+ }
358
+ if (event.type === "message_delta" && event.usage) {
359
+ this.outputTokens = event.usage.output_tokens ?? 0;
360
+ if (event.usage.thinking_tokens) {
361
+ this.reasoningTokens = event.usage.thinking_tokens;
362
+ }
363
+ }
364
+ if (event.type === "content_block_start" && event.content_block?.type === "thinking") {
365
+ }
366
+ }
367
+ getUsage() {
368
+ return {
369
+ model: this.model,
370
+ provider: "anthropic",
371
+ usage: {
372
+ inputTokens: this.inputTokens,
373
+ outputTokens: this.outputTokens,
374
+ totalTokens: this.inputTokens + this.outputTokens,
375
+ reasoningTokens: this.reasoningTokens > 0 ? this.reasoningTokens : void 0,
376
+ visibleOutputTokens: this.reasoningTokens > 0 ? Math.max(0, this.outputTokens - this.reasoningTokens) : this.outputTokens,
377
+ cachedTokens: this.cachedTokens > 0 ? this.cachedTokens : void 0,
378
+ cacheWriteTokens: this.cacheWriteTokens > 0 ? this.cacheWriteTokens : void 0
379
+ }
380
+ };
381
+ }
382
+ };
383
+
384
+ // src/meter/extractors/gemini.ts
385
+ function extractGeminiResponseUsage(response, fallbackModel = "gemini-3.7-flash") {
386
+ if (!response || typeof response !== "object") return null;
387
+ const usageMetadata = response.usageMetadata || response.response?.usageMetadata;
388
+ if (usageMetadata) {
389
+ const inputTokens = usageMetadata.promptTokenCount ?? 0;
390
+ const baseOutputTokens = usageMetadata.candidatesTokenCount ?? 0;
391
+ const thoughtsTokenCount = usageMetadata.thoughtsTokenCount ?? usageMetadata.reasoningTokenCount ?? 0;
392
+ const cachedTokens = usageMetadata.cachedContentTokenCount ?? 0;
393
+ const totalOutput = baseOutputTokens + thoughtsTokenCount;
394
+ const model = response.model || response.response?.model || fallbackModel;
395
+ return {
396
+ model,
397
+ provider: "google",
398
+ usage: {
399
+ inputTokens,
400
+ outputTokens: totalOutput,
401
+ totalTokens: inputTokens + totalOutput,
402
+ reasoningTokens: thoughtsTokenCount > 0 ? thoughtsTokenCount : void 0,
403
+ visibleOutputTokens: baseOutputTokens,
404
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
405
+ }
406
+ };
407
+ }
408
+ return null;
409
+ }
410
+
411
+ // src/meter/extractors/generic.ts
412
+ function extractGenericResponseUsage(response, fallbackModel = "generic-llm", fallbackProvider = "generic") {
413
+ if (!response || typeof response !== "object") return null;
414
+ const usage = response.usage || response.token_usage || response.usageMetadata;
415
+ if (usage) {
416
+ const inputTokens = usage.prompt_tokens ?? usage.input_tokens ?? usage.promptTokenCount ?? usage.prompt_eval_count ?? 0;
417
+ const outputTokens = usage.completion_tokens ?? usage.output_tokens ?? usage.candidatesTokenCount ?? usage.eval_count ?? 0;
418
+ const reasoningTokens = usage.reasoning_tokens ?? usage.thoughtsTokenCount ?? usage.completion_tokens_details?.reasoning_tokens ?? 0;
419
+ const cachedTokens = usage.prompt_tokens_details?.cached_tokens ?? usage.cached_tokens ?? usage.cachedContentTokenCount ?? 0;
420
+ const model = response.model || fallbackModel;
421
+ const provider = response.provider || fallbackProvider;
422
+ return {
423
+ model,
424
+ provider,
425
+ usage: {
426
+ inputTokens,
427
+ outputTokens,
428
+ totalTokens: inputTokens + outputTokens,
429
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
430
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
431
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
432
+ }
433
+ };
434
+ }
435
+ return null;
436
+ }
437
+
438
+ // src/meter/extractors/index.ts
439
+ function detectAndExtractUsage(response, fallbackModel, fallbackProvider) {
440
+ if (!response || typeof response !== "object") return null;
441
+ const openaiResult = extractOpenAIResponseUsage(response);
442
+ if (openaiResult) return openaiResult;
443
+ const anthropicResult = extractAnthropicResponseUsage(response);
444
+ if (anthropicResult) return anthropicResult;
445
+ const geminiResult = extractGeminiResponseUsage(response, fallbackModel);
446
+ if (geminiResult) return geminiResult;
447
+ const genericResult = extractGenericResponseUsage(response, fallbackModel, fallbackProvider);
448
+ if (genericResult) return genericResult;
449
+ return null;
450
+ }
451
+
452
+ // src/pricing/table.ts
453
+ var MODEL_PRICING_TABLE = {
454
+ // --- OpenAI ---
455
+ "gpt-5.6-sol": { inputPer1M: 4, outputPer1M: 20, cachedInputPer1M: 0.4 },
456
+ "gpt-5.6-terra": { inputPer1M: 2, outputPer1M: 12, cachedInputPer1M: 0.2 },
457
+ "gpt-5.6-luna": { inputPer1M: 0.2, outputPer1M: 1.2, cachedInputPer1M: 0.02 },
458
+ "gpt-5": { inputPer1M: 4, outputPer1M: 20, cachedInputPer1M: 0.4 },
459
+ "gpt-5-mini": { inputPer1M: 0.2, outputPer1M: 1.2, cachedInputPer1M: 0.02 },
460
+ "o1": { inputPer1M: 15, outputPer1M: 60, cachedInputPer1M: 7.5 },
461
+ "o1-mini": { inputPer1M: 1.1, outputPer1M: 4.4, cachedInputPer1M: 0.55 },
462
+ "o3": { inputPer1M: 15, outputPer1M: 60, cachedInputPer1M: 7.5 },
463
+ "o3-mini": { inputPer1M: 1.1, outputPer1M: 4.4, cachedInputPer1M: 0.55 },
464
+ "gpt-4o": { inputPer1M: 2.5, outputPer1M: 10, cachedInputPer1M: 1.25 },
465
+ "gpt-4o-mini": { inputPer1M: 0.15, outputPer1M: 0.6, cachedInputPer1M: 0.075 },
466
+ "gpt-4.1": { inputPer1M: 2, outputPer1M: 8, cachedInputPer1M: 1 },
467
+ "gpt-4.1-nano": { inputPer1M: 0.1, outputPer1M: 0.4, cachedInputPer1M: 0.05 },
468
+ "text-embedding-3-small": { inputPer1M: 0.02, outputPer1M: 0 },
469
+ "text-embedding-3-large": { inputPer1M: 0.13, outputPer1M: 0 },
470
+ // --- Anthropic ---
471
+ "claude-3-7-sonnet": { inputPer1M: 0.59, outputPer1M: 2.93, cachedInputPer1M: 0.3 },
472
+ "claude-sonnet-5": { inputPer1M: 2, outputPer1M: 10, cachedInputPer1M: 0.3 },
473
+ "claude-3-5-sonnet": { inputPer1M: 3, outputPer1M: 15, cachedInputPer1M: 0.3 },
474
+ "claude-3-5-haiku": { inputPer1M: 0.8, outputPer1M: 4, cachedInputPer1M: 0.08 },
475
+ "haiku-4.5": { inputPer1M: 1, outputPer1M: 5, cachedInputPer1M: 0.1 },
476
+ "claude-opus-5": { inputPer1M: 5, outputPer1M: 25, cachedInputPer1M: 1.5 },
477
+ "claude-3-opus": { inputPer1M: 15, outputPer1M: 75, cachedInputPer1M: 1.5 },
478
+ // --- Google Gemini ---
479
+ "gemini-3.7-flash": { inputPer1M: 0.75, outputPer1M: 3.75, cachedInputPer1M: 0.18 },
480
+ "gemini-3.1-pro": { inputPer1M: 2, outputPer1M: 12, cachedInputPer1M: 0.5 },
481
+ "gemini-3.5-flash": { inputPer1M: 1.5, outputPer1M: 9, cachedInputPer1M: 0.38 },
482
+ "gemini-3.1-flash-lite": { inputPer1M: 0.25, outputPer1M: 1.5, cachedInputPer1M: 0.06 },
483
+ "gemini-2.0-flash": { inputPer1M: 0.1, outputPer1M: 0.4, cachedInputPer1M: 0.025 },
484
+ "gemini-1.5-pro": { inputPer1M: 1.25, outputPer1M: 5, cachedInputPer1M: 0.3125 },
485
+ "gemini-1.5-flash": { inputPer1M: 0.075, outputPer1M: 0.3, cachedInputPer1M: 0.01875 },
486
+ // --- xAI Grok ---
487
+ "grok-4.6": { inputPer1M: 3, outputPer1M: 15 },
488
+ "grok-2": { inputPer1M: 2, outputPer1M: 10 },
489
+ "grok-2-vision": { inputPer1M: 2, outputPer1M: 10 },
490
+ "grok-beta": { inputPer1M: 5, outputPer1M: 15 },
491
+ // --- Mistral ---
492
+ "mistral-large-3": { inputPer1M: 2, outputPer1M: 6 },
493
+ "mistral-large-latest": { inputPer1M: 2, outputPer1M: 6 },
494
+ "codestral-latest": { inputPer1M: 0.3, outputPer1M: 0.9 },
495
+ "mistral-small-latest": { inputPer1M: 0.2, outputPer1M: 0.6 },
496
+ "ministral-8b-latest": { inputPer1M: 0.1, outputPer1M: 0.1 },
497
+ // --- Groq LPUs ---
498
+ "llama-3.3-70b-versatile": { inputPer1M: 0.59, outputPer1M: 0.79 },
499
+ "llama-3.1-8b-instant": { inputPer1M: 0.05, outputPer1M: 0.08 },
500
+ "deepseek-r1-distill-llama-70b": { inputPer1M: 0.75, outputPer1M: 0.99 },
501
+ "qwen-2.5-32b": { inputPer1M: 0.29, outputPer1M: 0.39 },
502
+ // --- DeepSeek ---
503
+ "deepseek-v4-pro": { inputPer1M: 0.66, outputPer1M: 1.98, cachedInputPer1M: 0.15 },
504
+ "deepseek-v4-flash": { inputPer1M: 0.22, outputPer1M: 0.66, cachedInputPer1M: 0.05 },
505
+ "deepseek-chat": { inputPer1M: 0.22, outputPer1M: 0.66, cachedInputPer1M: 0.05 },
506
+ "deepseek-reasoner": { inputPer1M: 0.66, outputPer1M: 1.98, cachedInputPer1M: 0.15 },
507
+ // --- Cohere ---
508
+ "command-r-plus": { inputPer1M: 2.5, outputPer1M: 10 },
509
+ "command-r": { inputPer1M: 0.15, outputPer1M: 0.6 }
510
+ };
511
+ var customPricingRegistry = {};
512
+ function normalizeModelKey(rawModel) {
513
+ if (!rawModel) return "unknown";
514
+ let model = rawModel.toLowerCase().trim();
515
+ if (model.includes("/")) {
516
+ model = model.split("/")[1] || model;
517
+ }
518
+ model = model.replace(/-\d{8}$/, "");
519
+ model = model.replace(/-\d{4}-\d{2}-\d{2}$/, "");
520
+ return model;
521
+ }
522
+ function getModelPricing(modelName) {
523
+ const normalized = normalizeModelKey(modelName);
524
+ if (customPricingRegistry[normalized]) {
525
+ return customPricingRegistry[normalized];
526
+ }
527
+ if (customPricingRegistry[modelName]) {
528
+ return customPricingRegistry[modelName];
529
+ }
530
+ if (MODEL_PRICING_TABLE[normalized]) {
531
+ return MODEL_PRICING_TABLE[normalized];
532
+ }
533
+ if (MODEL_PRICING_TABLE[modelName]) {
534
+ return MODEL_PRICING_TABLE[modelName];
535
+ }
536
+ return {
537
+ inputPer1M: 1,
538
+ outputPer1M: 3,
539
+ cachedInputPer1M: 0.5
540
+ };
541
+ }
542
+ function registerModelPricing(modelName, rates) {
543
+ const normalized = normalizeModelKey(modelName);
544
+ customPricingRegistry[normalized] = rates;
545
+ customPricingRegistry[modelName] = rates;
546
+ }
547
+
548
+ // src/pricing/calculator.ts
549
+ function calculateCost(params) {
550
+ const rates = getModelPricing(params.model);
551
+ const inputTokens = params.inputTokens ?? 0;
552
+ const outputTokens = params.outputTokens ?? 0;
553
+ const reasoningTokens = params.reasoningTokens ?? 0;
554
+ const cachedTokens = params.cachedTokens ?? 0;
555
+ const regularInputTokens = Math.max(0, inputTokens - cachedTokens);
556
+ const regularInputCost = regularInputTokens / 1e6 * rates.inputPer1M;
557
+ const cachedRate = rates.cachedInputPer1M ?? rates.inputPer1M * 0.5;
558
+ const cachedInputCost = cachedTokens / 1e6 * cachedRate;
559
+ const inputCostUSD = regularInputCost + cachedInputCost;
560
+ const outputCostUSD = outputTokens / 1e6 * rates.outputPer1M;
561
+ const reasoningRate = rates.reasoningPer1M ?? rates.outputPer1M;
562
+ const reasoningCostUSD = reasoningTokens / 1e6 * reasoningRate;
563
+ const standardCacheCost = cachedTokens / 1e6 * rates.inputPer1M;
564
+ const cachedDiscountUSD = Math.max(0, standardCacheCost - cachedInputCost);
565
+ const totalUSD = inputCostUSD + outputCostUSD;
566
+ const markup = params.markupMultiplier ?? 1;
567
+ const retailUSD = markup !== 1 ? totalUSD * markup : void 0;
568
+ return {
569
+ inputCostUSD: Number(inputCostUSD.toFixed(8)),
570
+ outputCostUSD: Number(outputCostUSD.toFixed(8)),
571
+ reasoningCostUSD: reasoningTokens > 0 ? Number(reasoningCostUSD.toFixed(8)) : void 0,
572
+ cachedDiscountUSD: cachedTokens > 0 ? Number(cachedDiscountUSD.toFixed(8)) : void 0,
573
+ totalUSD: Number(totalUSD.toFixed(8)),
574
+ retailUSD: retailUSD ? Number(retailUSD.toFixed(8)) : void 0,
575
+ currency: rates.currency || "USD"
576
+ };
577
+ }
578
+ function calculateUsageCost(model, usage, markupMultiplier) {
579
+ return calculateCost({
580
+ model,
581
+ inputTokens: usage.inputTokens,
582
+ outputTokens: usage.outputTokens,
583
+ reasoningTokens: usage.reasoningTokens,
584
+ cachedTokens: usage.cachedTokens,
585
+ cacheWriteTokens: usage.cacheWriteTokens,
586
+ markupMultiplier
587
+ });
588
+ }
589
+
590
+ // src/meter/stream.ts
591
+ function wrapOpenAIStream(stream, options, onComplete) {
592
+ let detectedModel = options.model || "gpt-4o";
593
+ let finalUsage = null;
594
+ const wrappedAsyncIterable = {
595
+ async *[Symbol.asyncIterator]() {
596
+ try {
597
+ for await (const chunk of stream) {
598
+ const inspected = inspectOpenAIStreamChunk(chunk);
599
+ if (inspected.model) {
600
+ detectedModel = inspected.model;
601
+ }
602
+ if (inspected.usage) {
603
+ finalUsage = inspected.usage;
604
+ }
605
+ yield chunk;
606
+ }
607
+ } finally {
608
+ if (finalUsage) {
609
+ const cost = calculateUsageCost(detectedModel, finalUsage);
610
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
611
+ const event = {
612
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
613
+ model: detectedModel,
614
+ provider: "openai",
615
+ usage: finalUsage,
616
+ cost,
617
+ customerId,
618
+ metadata: options.metadata
619
+ };
620
+ onComplete(event);
621
+ if (options.onUsage) {
622
+ options.onUsage(event);
623
+ }
624
+ }
625
+ }
626
+ }
627
+ };
628
+ return wrappedAsyncIterable;
629
+ }
630
+ function wrapAnthropicStream(stream, options, onComplete) {
631
+ const accumulator = new AnthropicStreamAccumulator();
632
+ const wrappedAsyncIterable = {
633
+ async *[Symbol.asyncIterator]() {
634
+ try {
635
+ for await (const event of stream) {
636
+ accumulator.processEvent(event);
637
+ yield event;
638
+ }
639
+ } finally {
640
+ const extracted = accumulator.getUsage();
641
+ const model = options.model || extracted.model;
642
+ const cost = calculateUsageCost(model, extracted.usage);
643
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
644
+ const usageEvent = {
645
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
646
+ model,
647
+ provider: "anthropic",
648
+ usage: extracted.usage,
649
+ cost,
650
+ customerId,
651
+ metadata: options.metadata
652
+ };
653
+ onComplete(usageEvent);
654
+ if (options.onUsage) {
655
+ options.onUsage(usageEvent);
656
+ }
657
+ }
658
+ }
659
+ };
660
+ return wrappedAsyncIterable;
661
+ }
662
+ function wrapGeminiStream(result, options, onComplete) {
663
+ if (!result || !result.stream) return result;
664
+ const originalStream = result.stream;
665
+ const model = options.model || "gemini-3.7-flash";
666
+ let lastChunkWithUsage = null;
667
+ const wrappedStream = (async function* () {
668
+ try {
669
+ for await (const chunk of originalStream) {
670
+ if (chunk.usageMetadata) {
671
+ lastChunkWithUsage = chunk;
672
+ }
673
+ yield chunk;
674
+ }
675
+ } finally {
676
+ if (lastChunkWithUsage) {
677
+ const extracted = extractGeminiResponseUsage(lastChunkWithUsage, model);
678
+ if (extracted) {
679
+ const cost = calculateUsageCost(extracted.model, extracted.usage);
680
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
681
+ const event = {
682
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
683
+ model: extracted.model,
684
+ provider: "google",
685
+ usage: extracted.usage,
686
+ cost,
687
+ customerId,
688
+ metadata: options.metadata
689
+ };
690
+ onComplete(event);
691
+ if (options.onUsage) {
692
+ options.onUsage(event);
693
+ }
694
+ }
695
+ }
696
+ }
697
+ })();
698
+ return {
699
+ ...result,
700
+ stream: wrappedStream
701
+ };
702
+ }
703
+ function wrapUniversalStream(stream, options = {}, onComplete) {
704
+ if (!stream || typeof stream !== "object") return stream;
705
+ if ("stream" in stream && "response" in stream) {
706
+ return wrapGeminiStream(stream, options, onComplete);
707
+ }
708
+ if (Symbol.asyncIterator in stream) {
709
+ if (options.provider === "anthropic") {
710
+ return wrapAnthropicStream(stream, options, onComplete);
711
+ }
712
+ return wrapOpenAIStream(stream, options, onComplete);
713
+ }
714
+ return stream;
715
+ }
716
+
717
+ // src/meter/client.ts
718
+ var VibezMeter = class {
719
+ batcher;
720
+ stripeClient;
721
+ markupMultiplier;
722
+ constructor(options = {}) {
723
+ this.markupMultiplier = options.markupMultiplier;
724
+ if (options.stripe) {
725
+ this.stripeClient = options.stripe;
726
+ } else if (options.apiKey || process.env.STRIPE_SECRET_KEY) {
727
+ const key = options.apiKey || process.env.STRIPE_SECRET_KEY;
728
+ this.stripeClient = new Stripe(key, {
729
+ appInfo: {
730
+ name: "vibezcheck",
731
+ version: "0.1.0",
732
+ url: "https://vibezcheck.xyz"
733
+ }
734
+ });
735
+ }
736
+ this.batcher = new MeterBatcher({
737
+ ...options,
738
+ stripe: this.stripeClient
739
+ });
740
+ }
741
+ /**
742
+ * Track token usage from a non-streaming response object (OpenAI, Anthropic, Gemini, etc.)
743
+ */
744
+ trackUsage(response, options = {}) {
745
+ const extracted = detectAndExtractUsage(response, options.model, options.provider);
746
+ if (!extracted) {
747
+ return null;
748
+ }
749
+ const model = options.model || extracted.model;
750
+ const cost = calculateUsageCost(model, extracted.usage, this.markupMultiplier);
751
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
752
+ const event = {
753
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
754
+ model,
755
+ provider: extracted.provider,
756
+ usage: extracted.usage,
757
+ cost,
758
+ customerId,
759
+ metadata: options.metadata
760
+ };
761
+ this.batcher.enqueue(event);
762
+ return event;
763
+ }
764
+ /**
765
+ * Wrap any LLM stream (OpenAI, Anthropic, Gemini) with zero added latency
766
+ */
767
+ wrapStream(stream, options = {}) {
768
+ return wrapUniversalStream(stream, options, (event) => {
769
+ this.batcher.enqueue(event);
770
+ });
771
+ }
772
+ /**
773
+ * Directly record token usage manually
774
+ */
775
+ recordUsage(options) {
776
+ const inputTokens = options.inputTokens ?? 0;
777
+ const outputTokens = options.outputTokens ?? 0;
778
+ const reasoningTokens = options.reasoningTokens;
779
+ const cachedTokens = options.cachedTokens;
780
+ const usage = {
781
+ inputTokens,
782
+ outputTokens,
783
+ totalTokens: inputTokens + outputTokens,
784
+ reasoningTokens,
785
+ visibleOutputTokens: reasoningTokens !== void 0 ? Math.max(0, outputTokens - reasoningTokens) : outputTokens,
786
+ cachedTokens
787
+ };
788
+ const cost = calculateUsageCost(options.model, usage, this.markupMultiplier);
789
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
790
+ const event = {
791
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
792
+ model: options.model,
793
+ provider: options.provider || "custom",
794
+ usage,
795
+ cost,
796
+ customerId,
797
+ metadata: options.metadata
798
+ };
799
+ this.batcher.enqueue(event);
800
+ return event;
801
+ }
802
+ /**
803
+ * Flush pending events to Stripe (vital for Serverless & Edge environments)
804
+ */
805
+ async flush() {
806
+ await this.batcher.flush();
807
+ }
808
+ /**
809
+ * Get in-memory aggregated usage statistics
810
+ */
811
+ getUsageSummary() {
812
+ return this.batcher.getSummary();
813
+ }
814
+ /**
815
+ * Reset in-memory ledger
816
+ */
817
+ resetSummary() {
818
+ this.batcher.resetLedger();
819
+ }
820
+ };
821
+ function createMeter(options = {}) {
822
+ return new VibezMeter(options);
823
+ }
824
+
825
+ // src/ai-sdk/with-billing.ts
826
+ function withBilling(model, options = {}) {
827
+ if (!model || typeof model !== "object") {
828
+ return model;
829
+ }
830
+ const meter = options.meter || createMeter({
831
+ apiKey: options.stripeApiKey,
832
+ eventName: options.eventName
833
+ });
834
+ const customerId = typeof options.customer === "string" ? options.customer : options.customer?.id || options.customerId;
835
+ const modelId = model.modelId || "unknown-model";
836
+ const provider = model.provider?.replace(/^@ai-sdk\//, "") || "ai-sdk";
837
+ const handleUsage = (rawUsage) => {
838
+ if (!rawUsage) return;
839
+ const inputTokens = rawUsage.promptTokens ?? rawUsage.inputTokens ?? 0;
840
+ const outputTokens = rawUsage.completionTokens ?? rawUsage.outputTokens ?? 0;
841
+ const reasoningTokens = rawUsage.reasoningTokens ?? rawUsage.completionTokensDetails?.reasoningTokens ?? rawUsage.outputTokenDetails?.reasoningTokens ?? 0;
842
+ const cachedTokens = rawUsage.promptTokensDetails?.cachedTokens ?? rawUsage.inputTokenDetails?.cachedTokens ?? 0;
843
+ const usage = {
844
+ inputTokens,
845
+ outputTokens,
846
+ totalTokens: inputTokens + outputTokens,
847
+ reasoningTokens: reasoningTokens > 0 ? reasoningTokens : void 0,
848
+ visibleOutputTokens: Math.max(0, outputTokens - reasoningTokens),
849
+ cachedTokens: cachedTokens > 0 ? cachedTokens : void 0
850
+ };
851
+ const cost = calculateUsageCost(modelId, usage);
852
+ const event = {
853
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
854
+ model: modelId,
855
+ provider,
856
+ usage,
857
+ cost,
858
+ customerId,
859
+ metadata: options.metadata
860
+ };
861
+ meter.recordUsage({
862
+ model: modelId,
863
+ provider,
864
+ inputTokens,
865
+ outputTokens,
866
+ reasoningTokens: usage.reasoningTokens,
867
+ cachedTokens: usage.cachedTokens,
868
+ customerId,
869
+ metadata: options.metadata
870
+ });
871
+ if (options.onUsage) {
872
+ options.onUsage(event);
873
+ }
874
+ };
875
+ return new Proxy(model, {
876
+ get(target, prop, receiver) {
877
+ const originalValue = Reflect.get(target, prop, receiver);
878
+ if (prop === "doGenerate" && typeof originalValue === "function") {
879
+ return async function(...args) {
880
+ const result = await originalValue.apply(target, args);
881
+ if (result && result.usage) {
882
+ handleUsage(result.usage);
883
+ }
884
+ return result;
885
+ };
886
+ }
887
+ if (prop === "doStream" && typeof originalValue === "function") {
888
+ return async function(...args) {
889
+ const result = await originalValue.apply(target, args);
890
+ if (!result || !result.stream) {
891
+ return result;
892
+ }
893
+ const originalStream = result.stream;
894
+ if (typeof originalStream.getReader === "function") {
895
+ const reader = originalStream.getReader();
896
+ const transformedStream = new ReadableStream({
897
+ async start(controller) {
898
+ try {
899
+ while (true) {
900
+ const { done, value } = await reader.read();
901
+ if (done) {
902
+ controller.close();
903
+ break;
904
+ }
905
+ if (value && typeof value === "object") {
906
+ if (value.type === "finish" && value.usage) {
907
+ handleUsage(value.usage);
908
+ }
909
+ }
910
+ controller.enqueue(value);
911
+ }
912
+ } catch (err) {
913
+ controller.error(err);
914
+ }
915
+ }
916
+ });
917
+ return {
918
+ ...result,
919
+ stream: transformedStream
920
+ };
921
+ }
922
+ if (Symbol.asyncIterator in originalStream) {
923
+ const wrappedAsyncIterable = {
924
+ async *[Symbol.asyncIterator]() {
925
+ for await (const chunk of originalStream) {
926
+ if (chunk && typeof chunk === "object") {
927
+ if (chunk.type === "finish" && chunk.usage) {
928
+ handleUsage(chunk.usage);
929
+ }
930
+ }
931
+ yield chunk;
932
+ }
933
+ }
934
+ };
935
+ return {
936
+ ...result,
937
+ stream: wrappedAsyncIterable
938
+ };
939
+ }
940
+ return result;
941
+ };
942
+ }
943
+ return originalValue;
944
+ }
945
+ });
946
+ }
947
+ var meteredModel = withBilling;
948
+
949
+ // src/customers/manager.ts
950
+ import Stripe2 from "stripe";
951
+
952
+ // src/customers/cache.ts
953
+ var CustomerCache = class {
954
+ cache = /* @__PURE__ */ new Map();
955
+ defaultTtlMs;
956
+ constructor(defaultTtlMs = 1e3 * 60 * 60) {
957
+ this.defaultTtlMs = defaultTtlMs;
958
+ }
959
+ get(key) {
960
+ const entry = this.cache.get(key);
961
+ if (!entry) return null;
962
+ if (Date.now() > entry.expiresAt) {
963
+ this.cache.delete(key);
964
+ return null;
965
+ }
966
+ return entry.customerId;
967
+ }
968
+ set(key, customerId, ttlMs) {
969
+ const expiresAt = Date.now() + (ttlMs ?? this.defaultTtlMs);
970
+ this.cache.set(key, { customerId, expiresAt });
971
+ }
972
+ delete(key) {
973
+ this.cache.delete(key);
974
+ }
975
+ clear() {
976
+ this.cache.clear();
977
+ }
978
+ };
979
+
980
+ // src/customers/manager.ts
981
+ var CustomerManager = class {
982
+ stripe;
983
+ cache;
984
+ constructor(options = {}) {
985
+ if (options.stripe) {
986
+ this.stripe = options.stripe;
987
+ } else {
988
+ const apiKey = options.apiKey || process.env.STRIPE_SECRET_KEY;
989
+ if (!apiKey) {
990
+ throw new Error("[vibezcheck] Stripe API key required for customer management.");
991
+ }
992
+ this.stripe = new Stripe2(apiKey);
993
+ }
994
+ this.cache = new CustomerCache(options.cacheTtlMs);
995
+ }
996
+ /**
997
+ * Retrieves existing Stripe Customer or automatically provisions a new one
998
+ */
999
+ async getOrCreate(params) {
1000
+ const cacheKey = params.userId || params.email;
1001
+ if (cacheKey) {
1002
+ const cachedId = this.cache.get(cacheKey);
1003
+ if (cachedId) {
1004
+ return {
1005
+ id: cachedId,
1006
+ isNew: false,
1007
+ customer: { id: cachedId }
1008
+ };
1009
+ }
1010
+ }
1011
+ if (params.userId) {
1012
+ try {
1013
+ const searchResult = await this.stripe.customers.search({
1014
+ query: `metadata['vibez_user_id']:'${params.userId}'`,
1015
+ limit: 1
1016
+ });
1017
+ if (searchResult.data.length > 0) {
1018
+ const customer = searchResult.data[0];
1019
+ if (cacheKey) this.cache.set(cacheKey, customer.id);
1020
+ if (params.email) this.cache.set(params.email, customer.id);
1021
+ return { id: customer.id, isNew: false, customer };
1022
+ }
1023
+ } catch {
1024
+ }
1025
+ }
1026
+ if (params.email) {
1027
+ const listResult = await this.stripe.customers.list({
1028
+ email: params.email,
1029
+ limit: 1
1030
+ });
1031
+ if (listResult.data.length > 0) {
1032
+ const customer = listResult.data[0];
1033
+ if (cacheKey) this.cache.set(cacheKey, customer.id);
1034
+ if (params.userId) this.cache.set(params.userId, customer.id);
1035
+ return { id: customer.id, isNew: false, customer };
1036
+ }
1037
+ }
1038
+ const newCustomer = await this.stripe.customers.create({
1039
+ email: params.email,
1040
+ name: params.name,
1041
+ metadata: {
1042
+ vibez_user_id: params.userId,
1043
+ created_by: "vibezcheck",
1044
+ ...params.metadata || {}
1045
+ }
1046
+ });
1047
+ if (cacheKey) this.cache.set(cacheKey, newCustomer.id);
1048
+ if (params.userId) this.cache.set(params.userId, newCustomer.id);
1049
+ if (params.email) this.cache.set(params.email, newCustomer.id);
1050
+ return { id: newCustomer.id, isNew: true, customer: newCustomer };
1051
+ }
1052
+ /**
1053
+ * Clears in-memory resolution cache
1054
+ */
1055
+ clearCache() {
1056
+ this.cache.clear();
1057
+ }
1058
+ };
1059
+ function createCustomerManager(options = {}) {
1060
+ return new CustomerManager(options);
1061
+ }
1062
+
1063
+ // src/auth/keys.ts
1064
+ import * as crypto from "crypto";
1065
+ import Stripe3 from "stripe";
1066
+ var ApiKeyAuth = class {
1067
+ stripe;
1068
+ constructor(stripe) {
1069
+ this.stripe = stripe;
1070
+ }
1071
+ /**
1072
+ * Hashes a raw API key using SHA-256
1073
+ */
1074
+ hashKey(rawKey) {
1075
+ return crypto.createHash("sha256").update(rawKey).digest("hex");
1076
+ }
1077
+ /**
1078
+ * Generates a new secure vz_live_... API key
1079
+ */
1080
+ async createApiKey(params) {
1081
+ const randomBytes2 = crypto.randomBytes(24).toString("hex");
1082
+ const apiKey = `vz_live_${randomBytes2}`;
1083
+ const keyId = `key_${crypto.randomBytes(8).toString("hex")}`;
1084
+ const keyHash = this.hashKey(apiKey);
1085
+ const record = {
1086
+ keyId,
1087
+ keyHash,
1088
+ customerId: params.customerId,
1089
+ userId: params.userId,
1090
+ name: params.name,
1091
+ scopes: params.scopes,
1092
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1093
+ };
1094
+ if (this.stripe && params.customerId) {
1095
+ try {
1096
+ await this.stripe.customers.update(params.customerId, {
1097
+ metadata: {
1098
+ [`vibez_key_${keyId}`]: JSON.stringify({
1099
+ hash: keyHash,
1100
+ name: params.name,
1101
+ scopes: params.scopes,
1102
+ created: record.createdAt
1103
+ })
1104
+ }
1105
+ });
1106
+ } catch {
1107
+ }
1108
+ }
1109
+ return { apiKey, keyId, record };
1110
+ }
1111
+ /**
1112
+ * Validates a raw key against an expected hash
1113
+ */
1114
+ verifyKeyHash(rawKey, expectedHash) {
1115
+ const computedHash = this.hashKey(rawKey);
1116
+ return crypto.timingSafeEqual(Buffer.from(computedHash), Buffer.from(expectedHash));
1117
+ }
1118
+ };
1119
+ function createApiKeyAuth(options = {}) {
1120
+ let stripeClient = options.stripe;
1121
+ if (!stripeClient && (options.apiKey || process.env.STRIPE_SECRET_KEY)) {
1122
+ stripeClient = new Stripe3(options.apiKey || process.env.STRIPE_SECRET_KEY);
1123
+ }
1124
+ return new ApiKeyAuth(stripeClient);
1125
+ }
1126
+
1127
+ // src/auth/verify.ts
1128
+ function extractAuthToken(reqOrHeader) {
1129
+ if (!reqOrHeader) return null;
1130
+ let authHeader = null;
1131
+ if (typeof reqOrHeader === "string") {
1132
+ authHeader = reqOrHeader;
1133
+ } else if ("headers" in reqOrHeader && typeof reqOrHeader.headers?.get === "function") {
1134
+ authHeader = reqOrHeader.headers.get("authorization") || reqOrHeader.headers.get("x-api-key");
1135
+ } else if (typeof reqOrHeader.get === "function") {
1136
+ authHeader = reqOrHeader.get("authorization") || reqOrHeader.get("x-api-key");
1137
+ } else if (typeof reqOrHeader === "object") {
1138
+ const raw = reqOrHeader["authorization"] || reqOrHeader["Authorization"] || reqOrHeader["x-api-key"] || reqOrHeader["X-API-Key"];
1139
+ authHeader = Array.isArray(raw) ? raw[0] : raw;
1140
+ }
1141
+ if (!authHeader) return null;
1142
+ if (authHeader.startsWith("Bearer ")) {
1143
+ return authHeader.substring(7).trim();
1144
+ }
1145
+ return authHeader.trim();
1146
+ }
1147
+
1148
+ // src/billing/sessions.ts
1149
+ import Stripe4 from "stripe";
1150
+ var BillingHelper = class {
1151
+ stripe;
1152
+ constructor(options = {}) {
1153
+ if (options.stripe) {
1154
+ this.stripe = options.stripe;
1155
+ } else {
1156
+ const apiKey = options.apiKey || process.env.STRIPE_SECRET_KEY;
1157
+ if (!apiKey) {
1158
+ throw new Error("[vibezcheck] Stripe API key required for billing operations.");
1159
+ }
1160
+ this.stripe = new Stripe4(apiKey);
1161
+ }
1162
+ }
1163
+ /**
1164
+ * Creates a Stripe Customer Portal session URL where users can manage cards, view usage & invoices
1165
+ */
1166
+ async createPortalSession(params) {
1167
+ const session = await this.stripe.billingPortal.sessions.create({
1168
+ customer: params.customerId,
1169
+ return_url: params.returnUrl
1170
+ });
1171
+ return session.url;
1172
+ }
1173
+ /**
1174
+ * Creates a Stripe Checkout session to subscribe a customer to a metered pricing tier
1175
+ */
1176
+ async createCheckoutSession(params) {
1177
+ const session = await this.stripe.checkout.sessions.create({
1178
+ customer: params.customerId,
1179
+ customer_email: !params.customerId ? params.customerEmail : void 0,
1180
+ line_items: [
1181
+ {
1182
+ price: params.priceId,
1183
+ quantity: 1
1184
+ }
1185
+ ],
1186
+ mode: params.mode || "subscription",
1187
+ success_url: `${params.returnUrl}?session_id={CHECKOUT_SESSION_ID}&status=success`,
1188
+ cancel_url: `${params.returnUrl}?status=cancelled`,
1189
+ metadata: params.metadata
1190
+ });
1191
+ if (!session.url) {
1192
+ throw new Error("[vibezcheck] Failed to generate checkout session URL.");
1193
+ }
1194
+ return session.url;
1195
+ }
1196
+ /**
1197
+ * Creates a Checkout session for topping up prepaid credit wallet balance
1198
+ */
1199
+ async createTopUpSession(params) {
1200
+ const session = await this.stripe.checkout.sessions.create({
1201
+ customer: params.customerId,
1202
+ line_items: [
1203
+ {
1204
+ price_data: {
1205
+ currency: params.currency || "usd",
1206
+ unit_amount: params.amountCents,
1207
+ product_data: {
1208
+ name: "AI Token Credits Top-Up",
1209
+ description: `Add $${(params.amountCents / 100).toFixed(2)} in AI inference credits`
1210
+ }
1211
+ },
1212
+ quantity: 1
1213
+ }
1214
+ ],
1215
+ mode: "payment",
1216
+ success_url: `${params.returnUrl}?status=success&amount=${params.amountCents}`,
1217
+ cancel_url: `${params.returnUrl}?status=cancelled`,
1218
+ metadata: {
1219
+ type: "vibezcheck_topup",
1220
+ customerId: params.customerId,
1221
+ amountCents: params.amountCents.toString()
1222
+ }
1223
+ });
1224
+ if (!session.url) {
1225
+ throw new Error("[vibezcheck] Failed to generate top-up checkout URL.");
1226
+ }
1227
+ return session.url;
1228
+ }
1229
+ };
1230
+ function createBillingHelper(options = {}) {
1231
+ return new BillingHelper(options);
1232
+ }
1233
+
1234
+ // src/meter/index.ts
1235
+ var defaultMeter = createMeter();
1236
+ function wrapStream(stream, options) {
1237
+ return defaultMeter.wrapStream(stream, options);
1238
+ }
1239
+ function trackTokens(response, options) {
1240
+ return defaultMeter.trackUsage(response, options);
1241
+ }
1242
+
1243
+ // src/index.ts
1244
+ var VibezCheckClient = class {
1245
+ meter;
1246
+ customers;
1247
+ auth;
1248
+ billing;
1249
+ stripeClient;
1250
+ constructor(config = {}) {
1251
+ const apiKey = config.apiKey || process.env.STRIPE_SECRET_KEY;
1252
+ if (apiKey) {
1253
+ this.stripeClient = config.stripe || new Stripe5(apiKey);
1254
+ }
1255
+ this.meter = new VibezMeter({
1256
+ ...config,
1257
+ stripe: this.stripeClient
1258
+ });
1259
+ if (this.stripeClient) {
1260
+ this.customers = new CustomerManager({ stripe: this.stripeClient });
1261
+ this.auth = new ApiKeyAuth(this.stripeClient);
1262
+ this.billing = new BillingHelper({ stripe: this.stripeClient });
1263
+ }
1264
+ }
1265
+ /**
1266
+ * 1-Line Zero-Latency Stream Wrapper for OpenAI, Anthropic, Gemini, etc.
1267
+ */
1268
+ wrapStream(stream, options) {
1269
+ return this.meter.wrapStream(stream, options);
1270
+ }
1271
+ /**
1272
+ * Track token usage from a non-streaming response object
1273
+ */
1274
+ track(response, options) {
1275
+ return this.meter.trackUsage(response, options);
1276
+ }
1277
+ /**
1278
+ * 1-Line Wrapper for Vercel AI SDK LanguageModel
1279
+ */
1280
+ withBilling(model, options) {
1281
+ return withBilling(model, {
1282
+ ...options,
1283
+ meter: this.meter
1284
+ });
1285
+ }
1286
+ /**
1287
+ * 1-Line Universal Stream Responder for API Routes (Next.js, Express, Hono)
1288
+ */
1289
+ async stream(params) {
1290
+ const OpenAI = (await import("openai")).default;
1291
+ const openai = new OpenAI();
1292
+ const responseStream = await openai.chat.completions.create({
1293
+ model: params.model,
1294
+ messages: params.messages,
1295
+ stream: true,
1296
+ stream_options: { include_usage: true },
1297
+ temperature: params.temperature
1298
+ });
1299
+ const meteredStream = this.wrapStream(responseStream, {
1300
+ customer: params.customer,
1301
+ model: params.model
1302
+ });
1303
+ const encoder = new TextEncoder();
1304
+ const readable = new ReadableStream({
1305
+ async start(controller) {
1306
+ try {
1307
+ for await (const chunk of meteredStream) {
1308
+ const text = chunk.choices?.[0]?.delta?.content || "";
1309
+ if (text) {
1310
+ controller.enqueue(encoder.encode(text));
1311
+ }
1312
+ }
1313
+ controller.close();
1314
+ } catch (err) {
1315
+ controller.error(err);
1316
+ }
1317
+ }
1318
+ });
1319
+ return new Response(readable, {
1320
+ headers: {
1321
+ "Content-Type": "text/plain; charset=utf-8",
1322
+ "Transfer-Encoding": "chunked"
1323
+ }
1324
+ });
1325
+ }
1326
+ /**
1327
+ * Flush pending meter events (vital for serverless runtimes)
1328
+ */
1329
+ async flush() {
1330
+ await this.meter.flush();
1331
+ }
1332
+ /**
1333
+ * In-memory usage statistics
1334
+ */
1335
+ getUsageSummary() {
1336
+ return this.meter.getUsageSummary();
1337
+ }
1338
+ };
1339
+ function createVibezCheck(config = {}) {
1340
+ return new VibezCheckClient(config);
1341
+ }
1342
+ var vibezcheck = createVibezCheck;
1343
+ var vibescheck = createVibezCheck;
1344
+ var vibez = createVibezCheck();
1345
+ var vibes = vibez;
1346
+ export {
1347
+ AnthropicStreamAccumulator,
1348
+ ApiKeyAuth,
1349
+ BillingHelper,
1350
+ CustomerCache,
1351
+ CustomerManager,
1352
+ MODEL_PRICING_TABLE,
1353
+ MeterBatcher,
1354
+ VibezCheckClient,
1355
+ VibezMeter,
1356
+ calculateCost,
1357
+ calculateUsageCost,
1358
+ createApiKeyAuth,
1359
+ createBillingHelper,
1360
+ createCustomerManager,
1361
+ createMeter,
1362
+ createVibezCheck,
1363
+ detectAndExtractUsage,
1364
+ extractAnthropicResponseUsage,
1365
+ extractAuthToken,
1366
+ extractGeminiResponseUsage,
1367
+ extractGenericResponseUsage,
1368
+ extractOpenAIResponseUsage,
1369
+ getModelPricing,
1370
+ inspectOpenAIStreamChunk,
1371
+ meteredModel,
1372
+ normalizeModelKey,
1373
+ registerModelPricing,
1374
+ trackTokens,
1375
+ vibes,
1376
+ vibescheck,
1377
+ vibez,
1378
+ vibezcheck,
1379
+ withBilling,
1380
+ wrapAnthropicStream,
1381
+ wrapGeminiStream,
1382
+ wrapOpenAIStream,
1383
+ wrapStream,
1384
+ wrapUniversalStream
1385
+ };
1386
+ //# sourceMappingURL=index.mjs.map