@ai-billing/core 0.0.1-alpha.6 → 0.0.1-alpha.7
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.
- package/dist/index.cjs +58 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +27 -13
- package/dist/index.d.ts +27 -13
- package/dist/index.js +53 -5
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -4,8 +4,8 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
|
4
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
6
|
var __export = (target, all) => {
|
|
7
|
-
for (var
|
|
8
|
-
__defProp(target,
|
|
7
|
+
for (var name4 in all)
|
|
8
|
+
__defProp(target, name4, { get: all[name4], enumerable: true });
|
|
9
9
|
};
|
|
10
10
|
var __copyProps = (to, from, except, desc) => {
|
|
11
11
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
@@ -21,9 +21,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
AIBillingError: () => AIBillingError,
|
|
24
|
+
AiBillingCostError: () => AiBillingCostError,
|
|
24
25
|
AiBillingDestinationError: () => AiBillingDestinationError,
|
|
25
26
|
AiBillingExtractorError: () => AiBillingExtractorError,
|
|
26
27
|
consoleDestination: () => consoleDestination,
|
|
28
|
+
convertCostUnit: () => convertCostUnit,
|
|
29
|
+
costToNumber: () => costToNumber,
|
|
27
30
|
createDestination: () => createDestination,
|
|
28
31
|
createV3BillingMiddleware: () => createV3BillingMiddleware
|
|
29
32
|
});
|
|
@@ -40,11 +43,10 @@ function createV3BillingMiddleware(options) {
|
|
|
40
43
|
responseId
|
|
41
44
|
}) => {
|
|
42
45
|
try {
|
|
43
|
-
const
|
|
44
|
-
const headerTags = rawHeader ? JSON.parse(rawHeader) : {};
|
|
46
|
+
const requestTags = params.providerOptions?.["ai-billing-tags"];
|
|
45
47
|
const tags = {
|
|
46
48
|
...defaultTags ?? {},
|
|
47
|
-
...
|
|
49
|
+
...requestTags ?? {}
|
|
48
50
|
};
|
|
49
51
|
const event = await buildEvent({
|
|
50
52
|
responseId,
|
|
@@ -119,12 +121,12 @@ var AIBillingError = class _AIBillingError extends Error {
|
|
|
119
121
|
[symbol] = true;
|
|
120
122
|
cause;
|
|
121
123
|
constructor({
|
|
122
|
-
name:
|
|
124
|
+
name: name4,
|
|
123
125
|
message,
|
|
124
126
|
cause
|
|
125
127
|
}) {
|
|
126
128
|
super(message);
|
|
127
|
-
this.name =
|
|
129
|
+
this.name = name4;
|
|
128
130
|
this.cause = cause;
|
|
129
131
|
}
|
|
130
132
|
static isInstance(error) {
|
|
@@ -173,6 +175,20 @@ var AiBillingDestinationError = class extends AIBillingError {
|
|
|
173
175
|
}
|
|
174
176
|
};
|
|
175
177
|
|
|
178
|
+
// src/error/cost-error.ts
|
|
179
|
+
var name3 = "AiBillingCostError";
|
|
180
|
+
var marker4 = `ai-billing.error.${name3}`;
|
|
181
|
+
var symbol4 = Symbol.for(marker4);
|
|
182
|
+
var AiBillingCostError = class extends AIBillingError {
|
|
183
|
+
[symbol4] = true;
|
|
184
|
+
constructor({ message, cause }) {
|
|
185
|
+
super({ name: name3, message, cause });
|
|
186
|
+
}
|
|
187
|
+
static isInstance(error) {
|
|
188
|
+
return AIBillingError.hasMarker(error, marker4);
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
|
|
176
192
|
// src/destination/base-destination.ts
|
|
177
193
|
function createDestination(destinationId, handler) {
|
|
178
194
|
return async (event) => {
|
|
@@ -197,12 +213,47 @@ function consoleDestination() {
|
|
|
197
213
|
});
|
|
198
214
|
});
|
|
199
215
|
}
|
|
216
|
+
|
|
217
|
+
// src/cost/convert-cost.ts
|
|
218
|
+
var getNanos = (cost) => {
|
|
219
|
+
switch (cost.unit) {
|
|
220
|
+
case "base":
|
|
221
|
+
return Math.round(cost.amount * 1e9);
|
|
222
|
+
case "cents":
|
|
223
|
+
return Math.round(cost.amount * 1e7);
|
|
224
|
+
case "micros":
|
|
225
|
+
return Math.round(cost.amount * 1e3);
|
|
226
|
+
case "nanos":
|
|
227
|
+
return Math.round(cost.amount);
|
|
228
|
+
default:
|
|
229
|
+
throw new AiBillingCostError({
|
|
230
|
+
message: `Failed to process cost. Unknown CostUnit: '${String(cost.unit)}'.`
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
var costToNumber = (cost, targetUnit) => {
|
|
235
|
+
const nanos = getNanos(cost);
|
|
236
|
+
if (targetUnit === "nanos") return nanos;
|
|
237
|
+
if (targetUnit === "micros") return nanos / 1e3;
|
|
238
|
+
if (targetUnit === "cents") return nanos / 1e7;
|
|
239
|
+
return nanos / 1e9;
|
|
240
|
+
};
|
|
241
|
+
var convertCostUnit = (cost, targetUnit) => {
|
|
242
|
+
return {
|
|
243
|
+
amount: costToNumber(cost, targetUnit),
|
|
244
|
+
currency: cost.currency,
|
|
245
|
+
unit: targetUnit
|
|
246
|
+
};
|
|
247
|
+
};
|
|
200
248
|
// Annotate the CommonJS export names for ESM import in node:
|
|
201
249
|
0 && (module.exports = {
|
|
202
250
|
AIBillingError,
|
|
251
|
+
AiBillingCostError,
|
|
203
252
|
AiBillingDestinationError,
|
|
204
253
|
AiBillingExtractorError,
|
|
205
254
|
consoleDestination,
|
|
255
|
+
convertCostUnit,
|
|
256
|
+
costToNumber,
|
|
206
257
|
createDestination,
|
|
207
258
|
createV3BillingMiddleware
|
|
208
259
|
});
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/ai-sdk/language-model-middleware/v3/language-model-v3-base-billing-middleware.ts","../src/error/ai-billing-error.ts","../src/error/extractor-error.ts","../src/error/destination-error.ts","../src/destination/base-destination.ts","../src/destination/console-destination.ts"],"sourcesContent":["export * from './types/index.js';\nexport * from './ai-sdk/index.js';\nexport * from './destination/index.js';\nexport * from './error/index.js';\n","import type {\n LanguageModelV3,\n LanguageModelV3CallOptions,\n LanguageModelV3Usage,\n LanguageModelV3GenerateResult,\n LanguageModelV3StreamPart,\n LanguageModelV3Middleware,\n SharedV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport type {\n BaseBillingMiddlewareOptions,\n EventBuilder,\n} from '../../../types/index.js';\n\nexport interface BuildV3EventPayload<TTags> {\n responseId: string | undefined;\n model: LanguageModelV3;\n usage: LanguageModelV3Usage | undefined;\n providerMetadata: SharedV3ProviderMetadata | undefined;\n tags: TTags;\n}\n\nexport interface BillingMiddlewareV3Options<\n TTags,\n> extends BaseBillingMiddlewareOptions<TTags> {\n buildEvent: EventBuilder<BuildV3EventPayload<TTags>, TTags>;\n}\n\nexport function createV3BillingMiddleware<TTags>(\n options: BillingMiddlewareV3Options<TTags>,\n): LanguageModelV3Middleware {\n const { buildEvent, destinations, defaultTags, waitUntil, onError } = options;\n\n const processEvent = async ({\n model,\n params,\n usage,\n providerMetadata,\n responseId,\n }: {\n model: LanguageModelV3;\n params: LanguageModelV3CallOptions;\n usage: LanguageModelV3Usage | undefined;\n providerMetadata: SharedV3ProviderMetadata | undefined;\n responseId: string | undefined;\n }): Promise<void> => {\n try {\n const rawHeader = params.headers?.['x-ai-billing-tags'];\n const headerTags = rawHeader ? JSON.parse(rawHeader) : {};\n\n const tags = {\n ...(defaultTags ?? {}),\n ...headerTags,\n } as TTags;\n\n const event = await buildEvent({\n responseId,\n model,\n usage,\n providerMetadata,\n tags,\n });\n\n if (event) {\n await Promise.allSettled(\n destinations.map(d => Promise.resolve(d(event))),\n );\n }\n } catch (err) {\n if (onError) onError(err);\n else console.error('[ai-billing] Core Error:', err);\n }\n };\n\n return {\n specificationVersion: 'v3',\n\n wrapGenerate: async ({ doGenerate, model, params }) => {\n const result: LanguageModelV3GenerateResult = await doGenerate();\n\n const promise = processEvent({\n model,\n params,\n usage: result.usage,\n providerMetadata: result.providerMetadata,\n responseId: result.response?.id,\n });\n\n if (waitUntil) waitUntil(promise);\n return result;\n },\n\n wrapStream: async ({ doStream, model, params }) => {\n const { stream, ...rest } = await doStream();\n\n let responseId: string | undefined;\n let usage: LanguageModelV3Usage | undefined;\n let providerMetadata: SharedV3ProviderMetadata | undefined;\n\n const billedStream = stream.pipeThrough(\n new TransformStream<\n LanguageModelV3StreamPart,\n LanguageModelV3StreamPart\n >({\n transform(chunk, controller) {\n if (chunk.type === 'text-start') responseId = chunk.id;\n if (chunk.type === 'response-metadata' && !responseId) {\n responseId = chunk.id;\n }\n if (chunk.type === 'finish') {\n usage = chunk.usage;\n providerMetadata = chunk.providerMetadata;\n }\n controller.enqueue(chunk);\n },\n flush() {\n const promise = processEvent({\n model,\n params,\n usage,\n providerMetadata,\n responseId,\n });\n if (waitUntil) waitUntil(promise);\n },\n }),\n );\n\n return { ...rest, stream: billedStream };\n },\n };\n}\n","const marker = 'ai-billing.error';\nconst symbol = Symbol.for(marker);\n\nexport class AIBillingError extends Error {\n private readonly [symbol] = true;\n\n readonly cause?: unknown;\n\n constructor({\n name,\n message,\n cause,\n }: {\n name: string;\n message: string;\n cause?: unknown;\n }) {\n super(message);\n this.name = name;\n this.cause = cause;\n }\n\n static isInstance(error: unknown): error is AIBillingError {\n return AIBillingError.hasMarker(error, marker);\n }\n\n protected static hasMarker(error: unknown, markerString: string): boolean {\n const markerSymbol = Symbol.for(markerString);\n return (\n error != null &&\n typeof error === 'object' &&\n markerSymbol in error &&\n typeof error[markerSymbol] === 'boolean' &&\n error[markerSymbol] === true\n );\n }\n}\n","import { AIBillingError } from './ai-billing-error.js';\n\nconst name = 'AiBillingExtractorError';\nconst marker = `ai-billing.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class AiBillingExtractorError extends AIBillingError {\n private readonly [symbol] = true;\n\n constructor({\n message = `Failed to extract billing data.`,\n cause,\n }: {\n message?: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n }\n\n static isInstance(error: unknown): error is AiBillingExtractorError {\n return AIBillingError.hasMarker(error, marker);\n }\n}\n","import { AIBillingError } from './ai-billing-error.js';\n\nconst name = 'AiBillingDestinationError';\nconst marker = `ai-billing.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class AiBillingDestinationError extends AIBillingError {\n private readonly [symbol] = true;\n\n readonly destinationId?: string;\n\n constructor({\n destinationId,\n message = `Failed to process billing data for destination: '${destinationId}'.`,\n cause,\n }: {\n destinationId?: string;\n message?: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n this.destinationId = destinationId;\n }\n\n static isInstance(error: unknown): error is AiBillingDestinationError {\n return AIBillingError.hasMarker(error, marker);\n }\n}\n","import type { Destination, BillingEvent } from '../types/index.js';\nimport { AiBillingDestinationError } from '../error/index.js';\n\nexport function createDestination<TTags>(\n destinationId: string,\n handler: (event: BillingEvent<TTags>) => Promise<void> | void,\n): Destination<TTags> {\n return async (event: BillingEvent<TTags>) => {\n try {\n await handler(event);\n } catch (error) {\n throw new AiBillingDestinationError({\n destinationId,\n cause: error,\n });\n }\n };\n}\n","import { createDestination } from './base-destination.js';\nimport type { Destination } from '../types/index.js';\n\nexport function consoleDestination<TTags>(): Destination<TTags> {\n return createDestination<TTags>('console-logger', event => {\n console.dir(event, {\n depth: null,\n colors: true,\n compact: false,\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC4BO,SAAS,0BACd,SAC2B;AAC3B,QAAM,EAAE,YAAY,cAAc,aAAa,WAAW,QAAQ,IAAI;AAEtE,QAAM,eAAe,OAAO;AAAA,IAC1B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,MAMqB;AACnB,QAAI;AACF,YAAM,YAAY,OAAO,UAAU,mBAAmB;AACtD,YAAM,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,UAAS,oBAAoBD,KAAI;AACvC,IAAME,UAAS,OAAO,IAAID,OAAM;AAEzB,IAAM,4BAAN,cAAwC,eAAe;AAAA,EAC5D,CAAkBC,OAAM,IAAI;AAAA,EAEnB;AAAA,EAET,YAAY;AAAA,IACV;AAAA,IACA,UAAU,oDAAoD,aAAa;AAAA,IAC3E;AAAA,EACF,GAIG;AACD,UAAM,EAAE,MAAAF,OAAM,SAAS,MAAM,CAAC;AAC9B,SAAK,gBAAgB;AAAA,EACvB;AAAA,EAEA,OAAO,WAAW,OAAoD;AACpE,WAAO,eAAe,UAAU,OAAOC,OAAM;AAAA,EAC/C;AACF;;;ACxBO,SAAS,kBACd,eACA,SACoB;AACpB,SAAO,OAAO,UAA+B;AAC3C,QAAI;AACF,YAAM,QAAQ,KAAK;AAAA,IACrB,SAAS,OAAO;AACd,YAAM,IAAI,0BAA0B;AAAA,QAClC;AAAA,QACA,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF;AACF;;;ACdO,SAAS,qBAAgD;AAC9D,SAAO,kBAAyB,kBAAkB,WAAS;AACzD,YAAQ,IAAI,OAAO;AAAA,MACjB,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,SAAS;AAAA,IACX,CAAC;AAAA,EACH,CAAC;AACH;","names":["name","marker","symbol","name","marker","symbol"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/ai-sdk/language-model-middleware/v3/language-model-v3-base-billing-middleware.ts","../src/error/ai-billing-error.ts","../src/error/extractor-error.ts","../src/error/destination-error.ts","../src/error/cost-error.ts","../src/destination/base-destination.ts","../src/destination/console-destination.ts","../src/cost/convert-cost.ts"],"sourcesContent":["export * from './types/index.js';\nexport * from './ai-sdk/index.js';\nexport * from './destination/index.js';\nexport * from './error/index.js';\nexport * from './cost/index.js';\n","import type {\n LanguageModelV3,\n LanguageModelV3CallOptions,\n LanguageModelV3Usage,\n LanguageModelV3GenerateResult,\n LanguageModelV3StreamPart,\n LanguageModelV3Middleware,\n SharedV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport type {\n BaseBillingMiddlewareOptions,\n EventBuilder,\n} from '../../../types/index.js';\n\nexport interface BuildV3EventPayload<TTags> {\n responseId: string | undefined;\n model: LanguageModelV3;\n usage: LanguageModelV3Usage | undefined;\n providerMetadata: SharedV3ProviderMetadata | undefined;\n tags: TTags;\n}\n\nexport interface BillingMiddlewareV3Options<\n TTags,\n> extends BaseBillingMiddlewareOptions<TTags> {\n buildEvent: EventBuilder<BuildV3EventPayload<TTags>, TTags>;\n}\n\nexport function createV3BillingMiddleware<TTags>(\n options: BillingMiddlewareV3Options<TTags>,\n): LanguageModelV3Middleware {\n const { buildEvent, destinations, defaultTags, waitUntil, onError } = options;\n\n const processEvent = async ({\n model,\n params,\n usage,\n providerMetadata,\n responseId,\n }: {\n model: LanguageModelV3;\n params: LanguageModelV3CallOptions;\n usage: LanguageModelV3Usage | undefined;\n providerMetadata: SharedV3ProviderMetadata | undefined;\n responseId: string | undefined;\n }): Promise<void> => {\n try {\n const requestTags = params.providerOptions?.['ai-billing-tags'];\n\n const tags = {\n ...(defaultTags ?? {}),\n ...(requestTags ?? {}),\n } as TTags;\n\n const event = await buildEvent({\n responseId,\n model,\n usage,\n providerMetadata,\n tags,\n });\n\n if (event) {\n await Promise.allSettled(\n destinations.map(d => Promise.resolve(d(event))),\n );\n }\n } catch (err) {\n if (onError) onError(err);\n else console.error('[ai-billing] Core Error:', err);\n }\n };\n\n return {\n specificationVersion: 'v3',\n\n wrapGenerate: async ({ doGenerate, model, params }) => {\n const result: LanguageModelV3GenerateResult = await doGenerate();\n\n const promise = processEvent({\n model,\n params,\n usage: result.usage,\n providerMetadata: result.providerMetadata,\n responseId: result.response?.id,\n });\n\n if (waitUntil) waitUntil(promise);\n return result;\n },\n\n wrapStream: async ({ doStream, model, params }) => {\n const { stream, ...rest } = await doStream();\n\n let responseId: string | undefined;\n let usage: LanguageModelV3Usage | undefined;\n let providerMetadata: SharedV3ProviderMetadata | undefined;\n\n const billedStream = stream.pipeThrough(\n new TransformStream<\n LanguageModelV3StreamPart,\n LanguageModelV3StreamPart\n >({\n transform(chunk, controller) {\n if (chunk.type === 'text-start') responseId = chunk.id;\n if (chunk.type === 'response-metadata' && !responseId) {\n responseId = chunk.id;\n }\n if (chunk.type === 'finish') {\n usage = chunk.usage;\n providerMetadata = chunk.providerMetadata;\n }\n controller.enqueue(chunk);\n },\n flush() {\n const promise = processEvent({\n model,\n params,\n usage,\n providerMetadata,\n responseId,\n });\n if (waitUntil) waitUntil(promise);\n },\n }),\n );\n\n return { ...rest, stream: billedStream };\n },\n };\n}\n","const marker = 'ai-billing.error';\nconst symbol = Symbol.for(marker);\n\nexport class AIBillingError extends Error {\n private readonly [symbol] = true;\n\n readonly cause?: unknown;\n\n constructor({\n name,\n message,\n cause,\n }: {\n name: string;\n message: string;\n cause?: unknown;\n }) {\n super(message);\n this.name = name;\n this.cause = cause;\n }\n\n static isInstance(error: unknown): error is AIBillingError {\n return AIBillingError.hasMarker(error, marker);\n }\n\n protected static hasMarker(error: unknown, markerString: string): boolean {\n const markerSymbol = Symbol.for(markerString);\n return (\n error != null &&\n typeof error === 'object' &&\n markerSymbol in error &&\n typeof error[markerSymbol] === 'boolean' &&\n error[markerSymbol] === true\n );\n }\n}\n","import { AIBillingError } from './ai-billing-error.js';\n\nconst name = 'AiBillingExtractorError';\nconst marker = `ai-billing.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class AiBillingExtractorError extends AIBillingError {\n private readonly [symbol] = true;\n\n constructor({\n message = `Failed to extract billing data.`,\n cause,\n }: {\n message?: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n }\n\n static isInstance(error: unknown): error is AiBillingExtractorError {\n return AIBillingError.hasMarker(error, marker);\n }\n}\n","import { AIBillingError } from './ai-billing-error.js';\n\nconst name = 'AiBillingDestinationError';\nconst marker = `ai-billing.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class AiBillingDestinationError extends AIBillingError {\n private readonly [symbol] = true;\n\n readonly destinationId?: string;\n\n constructor({\n destinationId,\n message = `Failed to process billing data for destination: '${destinationId}'.`,\n cause,\n }: {\n destinationId?: string;\n message?: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n this.destinationId = destinationId;\n }\n\n static isInstance(error: unknown): error is AiBillingDestinationError {\n return AIBillingError.hasMarker(error, marker);\n }\n}\n","import { AIBillingError } from './ai-billing-error.js';\n\nconst name = 'AiBillingCostError';\nconst marker = `ai-billing.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class AiBillingCostError extends AIBillingError {\n private readonly [symbol] = true;\n\n constructor({ message, cause }: { message: string; cause?: unknown }) {\n super({ name, message, cause });\n }\n\n static isInstance(error: unknown): error is AiBillingCostError {\n return AIBillingError.hasMarker(error, marker);\n }\n}\n","import type { Destination, BillingEvent } from '../types/index.js';\nimport { AiBillingDestinationError } from '../error/index.js';\n\nexport function createDestination<TTags>(\n destinationId: string,\n handler: (event: BillingEvent<TTags>) => Promise<void> | void,\n): Destination<TTags> {\n return async (event: BillingEvent<TTags>) => {\n try {\n await handler(event);\n } catch (error) {\n throw new AiBillingDestinationError({\n destinationId,\n cause: error,\n });\n }\n };\n}\n","import { createDestination } from './base-destination.js';\nimport type { Destination } from '../types/index.js';\n\nexport function consoleDestination<TTags>(): Destination<TTags> {\n return createDestination<TTags>('console-logger', event => {\n console.dir(event, {\n depth: null,\n colors: true,\n compact: false,\n });\n });\n}\n","import { AiBillingCostError } from '../index.js';\nimport type { Cost, CostUnit } from '../index.js';\n\nconst getNanos = (cost: Cost): number => {\n switch (cost.unit) {\n case 'base':\n return Math.round(cost.amount * 1_000_000_000);\n case 'cents':\n return Math.round(cost.amount * 10_000_000);\n case 'micros':\n return Math.round(cost.amount * 1_000);\n case 'nanos':\n return Math.round(cost.amount);\n default:\n throw new AiBillingCostError({\n message: `Failed to process cost. Unknown CostUnit: '${String(cost.unit)}'.`,\n });\n }\n};\n\nexport const costToNumber = (cost: Cost, targetUnit: CostUnit): number => {\n const nanos = getNanos(cost);\n\n if (targetUnit === 'nanos') return nanos;\n if (targetUnit === 'micros') return nanos / 1_000;\n if (targetUnit === 'cents') return nanos / 10_000_000;\n return nanos / 1_000_000_000; // base\n};\n\nexport const convertCostUnit = (cost: Cost, targetUnit: CostUnit): Cost => {\n return {\n amount: costToNumber(cost, targetUnit),\n currency: cost.currency,\n unit: targetUnit,\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC4BO,SAAS,0BACd,SAC2B;AAC3B,QAAM,EAAE,YAAY,cAAc,aAAa,WAAW,QAAQ,IAAI;AAEtE,QAAM,eAAe,OAAO;AAAA,IAC1B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,MAMqB;AACnB,QAAI;AACF,YAAM,cAAc,OAAO,kBAAkB,iBAAiB;AAE9D,YAAM,OAAO;AAAA,QACX,GAAI,eAAe,CAAC;AAAA,QACpB,GAAI,eAAe,CAAC;AAAA,MACtB;AAEA,YAAM,QAAQ,MAAM,WAAW;AAAA,QAC7B;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AAED,UAAI,OAAO;AACT,cAAM,QAAQ;AAAA,UACZ,aAAa,IAAI,OAAK,QAAQ,QAAQ,EAAE,KAAK,CAAC,CAAC;AAAA,QACjD;AAAA,MACF;AAAA,IACF,SAAS,KAAK;AACZ,UAAI,QAAS,SAAQ,GAAG;AAAA,UACnB,SAAQ,MAAM,4BAA4B,GAAG;AAAA,IACpD;AAAA,EACF;AAEA,SAAO;AAAA,IACL,sBAAsB;AAAA,IAEtB,cAAc,OAAO,EAAE,YAAY,OAAO,OAAO,MAAM;AACrD,YAAM,SAAwC,MAAM,WAAW;AAE/D,YAAM,UAAU,aAAa;AAAA,QAC3B;AAAA,QACA;AAAA,QACA,OAAO,O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M;AAAA,EACR;AACF;","names":["name","marker","symbol","name","marker","symbol","name","marker","symbol"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -2,12 +2,6 @@ import { LanguageModelV3, LanguageModelV3Usage, SharedV3ProviderMetadata, Langua
|
|
|
2
2
|
|
|
3
3
|
type Destination<TTags = DefaultTags> = (event: BillingEvent<TTags>) => Promise<void> | void;
|
|
4
4
|
|
|
5
|
-
type CostUnit = 'base' | 'cents' | 'millicents' | 'microcents';
|
|
6
|
-
interface Cost {
|
|
7
|
-
readonly amount: number;
|
|
8
|
-
readonly currency: string;
|
|
9
|
-
readonly unit: CostUnit;
|
|
10
|
-
}
|
|
11
5
|
interface Usage {
|
|
12
6
|
readonly subProviderId?: string;
|
|
13
7
|
readonly inputTokens: number;
|
|
@@ -37,6 +31,13 @@ interface BaseBillingMiddlewareOptions<TTags = DefaultTags> {
|
|
|
37
31
|
onError?: (error: unknown) => void;
|
|
38
32
|
}
|
|
39
33
|
|
|
34
|
+
type CostUnit = 'base' | 'cents' | 'micros' | 'nanos';
|
|
35
|
+
interface Cost {
|
|
36
|
+
readonly amount: number;
|
|
37
|
+
readonly currency: string;
|
|
38
|
+
readonly unit: CostUnit;
|
|
39
|
+
}
|
|
40
|
+
|
|
40
41
|
interface BuildV3EventPayload<TTags> {
|
|
41
42
|
responseId: string | undefined;
|
|
42
43
|
model: LanguageModelV3;
|
|
@@ -53,9 +54,9 @@ declare function createDestination<TTags>(destinationId: string, handler: (event
|
|
|
53
54
|
|
|
54
55
|
declare function consoleDestination<TTags>(): Destination<TTags>;
|
|
55
56
|
|
|
56
|
-
declare const symbol$
|
|
57
|
+
declare const symbol$3: unique symbol;
|
|
57
58
|
declare class AIBillingError extends Error {
|
|
58
|
-
private readonly [symbol$
|
|
59
|
+
private readonly [symbol$3];
|
|
59
60
|
readonly cause?: unknown;
|
|
60
61
|
constructor({ name, message, cause, }: {
|
|
61
62
|
name: string;
|
|
@@ -66,9 +67,9 @@ declare class AIBillingError extends Error {
|
|
|
66
67
|
protected static hasMarker(error: unknown, markerString: string): boolean;
|
|
67
68
|
}
|
|
68
69
|
|
|
69
|
-
declare const symbol$
|
|
70
|
+
declare const symbol$2: unique symbol;
|
|
70
71
|
declare class AiBillingExtractorError extends AIBillingError {
|
|
71
|
-
private readonly [symbol$
|
|
72
|
+
private readonly [symbol$2];
|
|
72
73
|
constructor({ message, cause, }: {
|
|
73
74
|
message?: string;
|
|
74
75
|
cause?: unknown;
|
|
@@ -76,9 +77,9 @@ declare class AiBillingExtractorError extends AIBillingError {
|
|
|
76
77
|
static isInstance(error: unknown): error is AiBillingExtractorError;
|
|
77
78
|
}
|
|
78
79
|
|
|
79
|
-
declare const symbol: unique symbol;
|
|
80
|
+
declare const symbol$1: unique symbol;
|
|
80
81
|
declare class AiBillingDestinationError extends AIBillingError {
|
|
81
|
-
private readonly [symbol];
|
|
82
|
+
private readonly [symbol$1];
|
|
82
83
|
readonly destinationId?: string;
|
|
83
84
|
constructor({ destinationId, message, cause, }: {
|
|
84
85
|
destinationId?: string;
|
|
@@ -88,4 +89,17 @@ declare class AiBillingDestinationError extends AIBillingError {
|
|
|
88
89
|
static isInstance(error: unknown): error is AiBillingDestinationError;
|
|
89
90
|
}
|
|
90
91
|
|
|
91
|
-
|
|
92
|
+
declare const symbol: unique symbol;
|
|
93
|
+
declare class AiBillingCostError extends AIBillingError {
|
|
94
|
+
private readonly [symbol];
|
|
95
|
+
constructor({ message, cause }: {
|
|
96
|
+
message: string;
|
|
97
|
+
cause?: unknown;
|
|
98
|
+
});
|
|
99
|
+
static isInstance(error: unknown): error is AiBillingCostError;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
declare const costToNumber: (cost: Cost, targetUnit: CostUnit) => number;
|
|
103
|
+
declare const convertCostUnit: (cost: Cost, targetUnit: CostUnit) => Cost;
|
|
104
|
+
|
|
105
|
+
export { AIBillingError, AiBillingCostError, AiBillingDestinationError, AiBillingExtractorError, type BaseBillingMiddlewareOptions, type BillingEvent, type BillingMiddlewareV3Options, type BuildV3EventPayload, type Cost, type CostUnit, type DefaultTags, type Destination, type EventBuilder, type Usage, consoleDestination, convertCostUnit, costToNumber, createDestination, createV3BillingMiddleware };
|
package/dist/index.d.ts
CHANGED
|
@@ -2,12 +2,6 @@ import { LanguageModelV3, LanguageModelV3Usage, SharedV3ProviderMetadata, Langua
|
|
|
2
2
|
|
|
3
3
|
type Destination<TTags = DefaultTags> = (event: BillingEvent<TTags>) => Promise<void> | void;
|
|
4
4
|
|
|
5
|
-
type CostUnit = 'base' | 'cents' | 'millicents' | 'microcents';
|
|
6
|
-
interface Cost {
|
|
7
|
-
readonly amount: number;
|
|
8
|
-
readonly currency: string;
|
|
9
|
-
readonly unit: CostUnit;
|
|
10
|
-
}
|
|
11
5
|
interface Usage {
|
|
12
6
|
readonly subProviderId?: string;
|
|
13
7
|
readonly inputTokens: number;
|
|
@@ -37,6 +31,13 @@ interface BaseBillingMiddlewareOptions<TTags = DefaultTags> {
|
|
|
37
31
|
onError?: (error: unknown) => void;
|
|
38
32
|
}
|
|
39
33
|
|
|
34
|
+
type CostUnit = 'base' | 'cents' | 'micros' | 'nanos';
|
|
35
|
+
interface Cost {
|
|
36
|
+
readonly amount: number;
|
|
37
|
+
readonly currency: string;
|
|
38
|
+
readonly unit: CostUnit;
|
|
39
|
+
}
|
|
40
|
+
|
|
40
41
|
interface BuildV3EventPayload<TTags> {
|
|
41
42
|
responseId: string | undefined;
|
|
42
43
|
model: LanguageModelV3;
|
|
@@ -53,9 +54,9 @@ declare function createDestination<TTags>(destinationId: string, handler: (event
|
|
|
53
54
|
|
|
54
55
|
declare function consoleDestination<TTags>(): Destination<TTags>;
|
|
55
56
|
|
|
56
|
-
declare const symbol$
|
|
57
|
+
declare const symbol$3: unique symbol;
|
|
57
58
|
declare class AIBillingError extends Error {
|
|
58
|
-
private readonly [symbol$
|
|
59
|
+
private readonly [symbol$3];
|
|
59
60
|
readonly cause?: unknown;
|
|
60
61
|
constructor({ name, message, cause, }: {
|
|
61
62
|
name: string;
|
|
@@ -66,9 +67,9 @@ declare class AIBillingError extends Error {
|
|
|
66
67
|
protected static hasMarker(error: unknown, markerString: string): boolean;
|
|
67
68
|
}
|
|
68
69
|
|
|
69
|
-
declare const symbol$
|
|
70
|
+
declare const symbol$2: unique symbol;
|
|
70
71
|
declare class AiBillingExtractorError extends AIBillingError {
|
|
71
|
-
private readonly [symbol$
|
|
72
|
+
private readonly [symbol$2];
|
|
72
73
|
constructor({ message, cause, }: {
|
|
73
74
|
message?: string;
|
|
74
75
|
cause?: unknown;
|
|
@@ -76,9 +77,9 @@ declare class AiBillingExtractorError extends AIBillingError {
|
|
|
76
77
|
static isInstance(error: unknown): error is AiBillingExtractorError;
|
|
77
78
|
}
|
|
78
79
|
|
|
79
|
-
declare const symbol: unique symbol;
|
|
80
|
+
declare const symbol$1: unique symbol;
|
|
80
81
|
declare class AiBillingDestinationError extends AIBillingError {
|
|
81
|
-
private readonly [symbol];
|
|
82
|
+
private readonly [symbol$1];
|
|
82
83
|
readonly destinationId?: string;
|
|
83
84
|
constructor({ destinationId, message, cause, }: {
|
|
84
85
|
destinationId?: string;
|
|
@@ -88,4 +89,17 @@ declare class AiBillingDestinationError extends AIBillingError {
|
|
|
88
89
|
static isInstance(error: unknown): error is AiBillingDestinationError;
|
|
89
90
|
}
|
|
90
91
|
|
|
91
|
-
|
|
92
|
+
declare const symbol: unique symbol;
|
|
93
|
+
declare class AiBillingCostError extends AIBillingError {
|
|
94
|
+
private readonly [symbol];
|
|
95
|
+
constructor({ message, cause }: {
|
|
96
|
+
message: string;
|
|
97
|
+
cause?: unknown;
|
|
98
|
+
});
|
|
99
|
+
static isInstance(error: unknown): error is AiBillingCostError;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
declare const costToNumber: (cost: Cost, targetUnit: CostUnit) => number;
|
|
103
|
+
declare const convertCostUnit: (cost: Cost, targetUnit: CostUnit) => Cost;
|
|
104
|
+
|
|
105
|
+
export { AIBillingError, AiBillingCostError, AiBillingDestinationError, AiBillingExtractorError, type BaseBillingMiddlewareOptions, type BillingEvent, type BillingMiddlewareV3Options, type BuildV3EventPayload, type Cost, type CostUnit, type DefaultTags, type Destination, type EventBuilder, type Usage, consoleDestination, convertCostUnit, costToNumber, createDestination, createV3BillingMiddleware };
|
package/dist/index.js
CHANGED
|
@@ -9,11 +9,10 @@ function createV3BillingMiddleware(options) {
|
|
|
9
9
|
responseId
|
|
10
10
|
}) => {
|
|
11
11
|
try {
|
|
12
|
-
const
|
|
13
|
-
const headerTags = rawHeader ? JSON.parse(rawHeader) : {};
|
|
12
|
+
const requestTags = params.providerOptions?.["ai-billing-tags"];
|
|
14
13
|
const tags = {
|
|
15
14
|
...defaultTags ?? {},
|
|
16
|
-
...
|
|
15
|
+
...requestTags ?? {}
|
|
17
16
|
};
|
|
18
17
|
const event = await buildEvent({
|
|
19
18
|
responseId,
|
|
@@ -88,12 +87,12 @@ var AIBillingError = class _AIBillingError extends Error {
|
|
|
88
87
|
[symbol] = true;
|
|
89
88
|
cause;
|
|
90
89
|
constructor({
|
|
91
|
-
name:
|
|
90
|
+
name: name4,
|
|
92
91
|
message,
|
|
93
92
|
cause
|
|
94
93
|
}) {
|
|
95
94
|
super(message);
|
|
96
|
-
this.name =
|
|
95
|
+
this.name = name4;
|
|
97
96
|
this.cause = cause;
|
|
98
97
|
}
|
|
99
98
|
static isInstance(error) {
|
|
@@ -142,6 +141,20 @@ var AiBillingDestinationError = class extends AIBillingError {
|
|
|
142
141
|
}
|
|
143
142
|
};
|
|
144
143
|
|
|
144
|
+
// src/error/cost-error.ts
|
|
145
|
+
var name3 = "AiBillingCostError";
|
|
146
|
+
var marker4 = `ai-billing.error.${name3}`;
|
|
147
|
+
var symbol4 = Symbol.for(marker4);
|
|
148
|
+
var AiBillingCostError = class extends AIBillingError {
|
|
149
|
+
[symbol4] = true;
|
|
150
|
+
constructor({ message, cause }) {
|
|
151
|
+
super({ name: name3, message, cause });
|
|
152
|
+
}
|
|
153
|
+
static isInstance(error) {
|
|
154
|
+
return AIBillingError.hasMarker(error, marker4);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
|
|
145
158
|
// src/destination/base-destination.ts
|
|
146
159
|
function createDestination(destinationId, handler) {
|
|
147
160
|
return async (event) => {
|
|
@@ -166,11 +179,46 @@ function consoleDestination() {
|
|
|
166
179
|
});
|
|
167
180
|
});
|
|
168
181
|
}
|
|
182
|
+
|
|
183
|
+
// src/cost/convert-cost.ts
|
|
184
|
+
var getNanos = (cost) => {
|
|
185
|
+
switch (cost.unit) {
|
|
186
|
+
case "base":
|
|
187
|
+
return Math.round(cost.amount * 1e9);
|
|
188
|
+
case "cents":
|
|
189
|
+
return Math.round(cost.amount * 1e7);
|
|
190
|
+
case "micros":
|
|
191
|
+
return Math.round(cost.amount * 1e3);
|
|
192
|
+
case "nanos":
|
|
193
|
+
return Math.round(cost.amount);
|
|
194
|
+
default:
|
|
195
|
+
throw new AiBillingCostError({
|
|
196
|
+
message: `Failed to process cost. Unknown CostUnit: '${String(cost.unit)}'.`
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
var costToNumber = (cost, targetUnit) => {
|
|
201
|
+
const nanos = getNanos(cost);
|
|
202
|
+
if (targetUnit === "nanos") return nanos;
|
|
203
|
+
if (targetUnit === "micros") return nanos / 1e3;
|
|
204
|
+
if (targetUnit === "cents") return nanos / 1e7;
|
|
205
|
+
return nanos / 1e9;
|
|
206
|
+
};
|
|
207
|
+
var convertCostUnit = (cost, targetUnit) => {
|
|
208
|
+
return {
|
|
209
|
+
amount: costToNumber(cost, targetUnit),
|
|
210
|
+
currency: cost.currency,
|
|
211
|
+
unit: targetUnit
|
|
212
|
+
};
|
|
213
|
+
};
|
|
169
214
|
export {
|
|
170
215
|
AIBillingError,
|
|
216
|
+
AiBillingCostError,
|
|
171
217
|
AiBillingDestinationError,
|
|
172
218
|
AiBillingExtractorError,
|
|
173
219
|
consoleDestination,
|
|
220
|
+
convertCostUnit,
|
|
221
|
+
costToNumber,
|
|
174
222
|
createDestination,
|
|
175
223
|
createV3BillingMiddleware
|
|
176
224
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ai-sdk/language-model-middleware/v3/language-model-v3-base-billing-middleware.ts","../src/error/ai-billing-error.ts","../src/error/extractor-error.ts","../src/error/destination-error.ts","../src/destination/base-destination.ts","../src/destination/console-destination.ts"],"sourcesContent":["import type {\n LanguageModelV3,\n LanguageModelV3CallOptions,\n LanguageModelV3Usage,\n LanguageModelV3GenerateResult,\n LanguageModelV3StreamPart,\n LanguageModelV3Middleware,\n SharedV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport type {\n BaseBillingMiddlewareOptions,\n EventBuilder,\n} from '../../../types/index.js';\n\nexport interface BuildV3EventPayload<TTags> {\n responseId: string | undefined;\n model: LanguageModelV3;\n usage: LanguageModelV3Usage | undefined;\n providerMetadata: SharedV3ProviderMetadata | undefined;\n tags: TTags;\n}\n\nexport interface BillingMiddlewareV3Options<\n TTags,\n> extends BaseBillingMiddlewareOptions<TTags> {\n buildEvent: EventBuilder<BuildV3EventPayload<TTags>, TTags>;\n}\n\nexport function createV3BillingMiddleware<TTags>(\n options: BillingMiddlewareV3Options<TTags>,\n): LanguageModelV3Middleware {\n const { buildEvent, destinations, defaultTags, waitUntil, onError } = options;\n\n const processEvent = async ({\n model,\n params,\n usage,\n providerMetadata,\n responseId,\n }: {\n model: LanguageModelV3;\n params: LanguageModelV3CallOptions;\n usage: LanguageModelV3Usage | undefined;\n providerMetadata: SharedV3ProviderMetadata | undefined;\n responseId: string | undefined;\n }): Promise<void> => {\n try {\n const rawHeader = params.headers?.['x-ai-billing-tags'];\n const headerTags = rawHeader ? JSON.parse(rawHeader) : {};\n\n const tags = {\n ...(defaultTags ?? {}),\n ...headerTags,\n } as TTags;\n\n const event = await buildEvent({\n responseId,\n model,\n usage,\n providerMetadata,\n tags,\n });\n\n if (event) {\n await Promise.allSettled(\n destinations.map(d => Promise.resolve(d(event))),\n );\n }\n } catch (err) {\n if (onError) onError(err);\n else console.error('[ai-billing] Core Error:', err);\n }\n };\n\n return {\n specificationVersion: 'v3',\n\n wrapGenerate: async ({ doGenerate, model, params }) => {\n const result: LanguageModelV3GenerateResult = await doGenerate();\n\n const promise = processEvent({\n model,\n params,\n usage: result.usage,\n providerMetadata: result.providerMetadata,\n responseId: result.response?.id,\n });\n\n if (waitUntil) waitUntil(promise);\n return result;\n },\n\n wrapStream: async ({ doStream, model, params }) => {\n const { stream, ...rest } = await doStream();\n\n let responseId: string | undefined;\n let usage: LanguageModelV3Usage | undefined;\n let providerMetadata: SharedV3ProviderMetadata | undefined;\n\n const billedStream = stream.pipeThrough(\n new TransformStream<\n LanguageModelV3StreamPart,\n LanguageModelV3StreamPart\n >({\n transform(chunk, controller) {\n if (chunk.type === 'text-start') responseId = chunk.id;\n if (chunk.type === 'response-metadata' && !responseId) {\n responseId = chunk.id;\n }\n if (chunk.type === 'finish') {\n usage = chunk.usage;\n providerMetadata = chunk.providerMetadata;\n }\n controller.enqueue(chunk);\n },\n flush() {\n const promise = processEvent({\n model,\n params,\n usage,\n providerMetadata,\n responseId,\n });\n if (waitUntil) waitUntil(promise);\n },\n }),\n );\n\n return { ...rest, stream: billedStream };\n },\n };\n}\n","const marker = 'ai-billing.error';\nconst symbol = Symbol.for(marker);\n\nexport class AIBillingError extends Error {\n private readonly [symbol] = true;\n\n readonly cause?: unknown;\n\n constructor({\n name,\n message,\n cause,\n }: {\n name: string;\n message: string;\n cause?: unknown;\n }) {\n super(message);\n this.name = name;\n this.cause = cause;\n }\n\n static isInstance(error: unknown): error is AIBillingError {\n return AIBillingError.hasMarker(error, marker);\n }\n\n protected static hasMarker(error: unknown, markerString: string): boolean {\n const markerSymbol = Symbol.for(markerString);\n return (\n error != null &&\n typeof error === 'object' &&\n markerSymbol in error &&\n typeof error[markerSymbol] === 'boolean' &&\n error[markerSymbol] === true\n );\n }\n}\n","import { AIBillingError } from './ai-billing-error.js';\n\nconst name = 'AiBillingExtractorError';\nconst marker = `ai-billing.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class AiBillingExtractorError extends AIBillingError {\n private readonly [symbol] = true;\n\n constructor({\n message = `Failed to extract billing data.`,\n cause,\n }: {\n message?: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n }\n\n static isInstance(error: unknown): error is AiBillingExtractorError {\n return AIBillingError.hasMarker(error, marker);\n }\n}\n","import { AIBillingError } from './ai-billing-error.js';\n\nconst name = 'AiBillingDestinationError';\nconst marker = `ai-billing.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class AiBillingDestinationError extends AIBillingError {\n private readonly [symbol] = true;\n\n readonly destinationId?: string;\n\n constructor({\n destinationId,\n message = `Failed to process billing data for destination: '${destinationId}'.`,\n cause,\n }: {\n destinationId?: string;\n message?: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n this.destinationId = destinationId;\n }\n\n static isInstance(error: unknown): error is AiBillingDestinationError {\n return AIBillingError.hasMarker(error, marker);\n }\n}\n","import type { Destination, BillingEvent } from '../types/index.js';\nimport { AiBillingDestinationError } from '../error/index.js';\n\nexport function createDestination<TTags>(\n destinationId: string,\n handler: (event: BillingEvent<TTags>) => Promise<void> | void,\n): Destination<TTags> {\n return async (event: BillingEvent<TTags>) => {\n try {\n await handler(event);\n } catch (error) {\n throw new AiBillingDestinationError({\n destinationId,\n cause: error,\n });\n }\n };\n}\n","import { createDestination } from './base-destination.js';\nimport type { Destination } from '../types/index.js';\n\nexport function consoleDestination<TTags>(): Destination<TTags> {\n return createDestination<TTags>('console-logger', event => {\n console.dir(event, {\n depth: null,\n colors: true,\n compact: false,\n });\n });\n}\n"],"mappings":";AA4BO,SAAS,0BACd,SAC2B;AAC3B,QAAM,EAAE,YAAY,cAAc,aAAa,WAAW,QAAQ,IAAI;AAEtE,QAAM,eAAe,OAAO;AAAA,IAC1B;AAAA,IACA;A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EA,OAAO,WAAW,OAAkD;AAClE,WAAO,eAAe,UAAU,OAAOD,OAAM;AAAA,EAC/C;AACF;;;ACpBA,IAAME,QAAO;AACb,IAAMC,UAAS,oBAAoBD,KAAI;AACvC,IAAME,UAAS,OAAO,IAAID,OAAM;AAEzB,IAAM,4BAAN,cAAwC,eAAe;AAAA,EAC5D,CAAkBC,OAAM,IAAI;AAAA,EAEnB;AAAA,EAET,YAAY;AAAA,IACV;AAAA,IACA,UAAU,oDAAoD,aAAa;AAAA,IAC3E;AAAA,EACF,GAIG;AACD,UAAM,EAAE,MAAAF,OAAM,SAAS,MAAM,CAAC;AAC9B,SAAK,gBAAgB;AAAA,EACvB;AAAA,EAEA,OAAO,WAAW,OAAoD;AACpE,WAAO,eAAe,UAAU,OAAOC,OAAM;AAAA,EAC/C;AACF;;;ACxBO,SAAS,kBACd,eACA,SACoB;AACpB,SAAO,OAAO,UAA+B;AAC3C,QAAI;AACF,YAAM,QAAQ,KAAK;AAAA,IACrB,SAAS,OAAO;AACd,YAAM,IAAI,0BAA0B;AAAA,QAClC;AAAA,QACA,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF;AACF;;;ACdO,SAAS,qBAAgD;AAC9D,SAAO,kBAAyB,kBAAkB,WAAS;AACzD,YAAQ,IAAI,OAAO;AAAA,MACjB,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,SAAS;AAAA,IACX,CAAC;AAAA,EACH,CAAC;AACH;","names":["name","marker","symbol","name","marker","symbol"]}
|
|
1
|
+
{"version":3,"sources":["../src/ai-sdk/language-model-middleware/v3/language-model-v3-base-billing-middleware.ts","../src/error/ai-billing-error.ts","../src/error/extractor-error.ts","../src/error/destination-error.ts","../src/error/cost-error.ts","../src/destination/base-destination.ts","../src/destination/console-destination.ts","../src/cost/convert-cost.ts"],"sourcesContent":["import type {\n LanguageModelV3,\n LanguageModelV3CallOptions,\n LanguageModelV3Usage,\n LanguageModelV3GenerateResult,\n LanguageModelV3StreamPart,\n LanguageModelV3Middleware,\n SharedV3ProviderMetadata,\n} from '@ai-sdk/provider';\nimport type {\n BaseBillingMiddlewareOptions,\n EventBuilder,\n} from '../../../types/index.js';\n\nexport interface BuildV3EventPayload<TTags> {\n responseId: string | undefined;\n model: LanguageModelV3;\n usage: LanguageModelV3Usage | undefined;\n providerMetadata: SharedV3ProviderMetadata | undefined;\n tags: TTags;\n}\n\nexport interface BillingMiddlewareV3Options<\n TTags,\n> extends BaseBillingMiddlewareOptions<TTags> {\n buildEvent: EventBuilder<BuildV3EventPayload<TTags>, TTags>;\n}\n\nexport function createV3BillingMiddleware<TTags>(\n options: BillingMiddlewareV3Options<TTags>,\n): LanguageModelV3Middleware {\n const { buildEvent, destinations, defaultTags, waitUntil, onError } = options;\n\n const processEvent = async ({\n model,\n params,\n usage,\n providerMetadata,\n responseId,\n }: {\n model: LanguageModelV3;\n params: LanguageModelV3CallOptions;\n usage: LanguageModelV3Usage | undefined;\n providerMetadata: SharedV3ProviderMetadata | undefined;\n responseId: string | undefined;\n }): Promise<void> => {\n try {\n const requestTags = params.providerOptions?.['ai-billing-tags'];\n\n const tags = {\n ...(defaultTags ?? {}),\n ...(requestTags ?? {}),\n } as TTags;\n\n const event = await buildEvent({\n responseId,\n model,\n usage,\n providerMetadata,\n tags,\n });\n\n if (event) {\n await Promise.allSettled(\n destinations.map(d => Promise.resolve(d(event))),\n );\n }\n } catch (err) {\n if (onError) onError(err);\n else console.error('[ai-billing] Core Error:', err);\n }\n };\n\n return {\n specificationVersion: 'v3',\n\n wrapGenerate: async ({ doGenerate, model, params }) => {\n const result: LanguageModelV3GenerateResult = await doGenerate();\n\n const promise = processEvent({\n model,\n params,\n usage: result.usage,\n providerMetadata: result.providerMetadata,\n responseId: result.response?.id,\n });\n\n if (waitUntil) waitUntil(promise);\n return result;\n },\n\n wrapStream: async ({ doStream, model, params }) => {\n const { stream, ...rest } = await doStream();\n\n let responseId: string | undefined;\n let usage: LanguageModelV3Usage | undefined;\n let providerMetadata: SharedV3ProviderMetadata | undefined;\n\n const billedStream = stream.pipeThrough(\n new TransformStream<\n LanguageModelV3StreamPart,\n LanguageModelV3StreamPart\n >({\n transform(chunk, controller) {\n if (chunk.type === 'text-start') responseId = chunk.id;\n if (chunk.type === 'response-metadata' && !responseId) {\n responseId = chunk.id;\n }\n if (chunk.type === 'finish') {\n usage = chunk.usage;\n providerMetadata = chunk.providerMetadata;\n }\n controller.enqueue(chunk);\n },\n flush() {\n const promise = processEvent({\n model,\n params,\n usage,\n providerMetadata,\n responseId,\n });\n if (waitUntil) waitUntil(promise);\n },\n }),\n );\n\n return { ...rest, stream: billedStream };\n },\n };\n}\n","const marker = 'ai-billing.error';\nconst symbol = Symbol.for(marker);\n\nexport class AIBillingError extends Error {\n private readonly [symbol] = true;\n\n readonly cause?: unknown;\n\n constructor({\n name,\n message,\n cause,\n }: {\n name: string;\n message: string;\n cause?: unknown;\n }) {\n super(message);\n this.name = name;\n this.cause = cause;\n }\n\n static isInstance(error: unknown): error is AIBillingError {\n return AIBillingError.hasMarker(error, marker);\n }\n\n protected static hasMarker(error: unknown, markerString: string): boolean {\n const markerSymbol = Symbol.for(markerString);\n return (\n error != null &&\n typeof error === 'object' &&\n markerSymbol in error &&\n typeof error[markerSymbol] === 'boolean' &&\n error[markerSymbol] === true\n );\n }\n}\n","import { AIBillingError } from './ai-billing-error.js';\n\nconst name = 'AiBillingExtractorError';\nconst marker = `ai-billing.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class AiBillingExtractorError extends AIBillingError {\n private readonly [symbol] = true;\n\n constructor({\n message = `Failed to extract billing data.`,\n cause,\n }: {\n message?: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n }\n\n static isInstance(error: unknown): error is AiBillingExtractorError {\n return AIBillingError.hasMarker(error, marker);\n }\n}\n","import { AIBillingError } from './ai-billing-error.js';\n\nconst name = 'AiBillingDestinationError';\nconst marker = `ai-billing.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class AiBillingDestinationError extends AIBillingError {\n private readonly [symbol] = true;\n\n readonly destinationId?: string;\n\n constructor({\n destinationId,\n message = `Failed to process billing data for destination: '${destinationId}'.`,\n cause,\n }: {\n destinationId?: string;\n message?: string;\n cause?: unknown;\n }) {\n super({ name, message, cause });\n this.destinationId = destinationId;\n }\n\n static isInstance(error: unknown): error is AiBillingDestinationError {\n return AIBillingError.hasMarker(error, marker);\n }\n}\n","import { AIBillingError } from './ai-billing-error.js';\n\nconst name = 'AiBillingCostError';\nconst marker = `ai-billing.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class AiBillingCostError extends AIBillingError {\n private readonly [symbol] = true;\n\n constructor({ message, cause }: { message: string; cause?: unknown }) {\n super({ name, message, cause });\n }\n\n static isInstance(error: unknown): error is AiBillingCostError {\n return AIBillingError.hasMarker(error, marker);\n }\n}\n","import type { Destination, BillingEvent } from '../types/index.js';\nimport { AiBillingDestinationError } from '../error/index.js';\n\nexport function createDestination<TTags>(\n destinationId: string,\n handler: (event: BillingEvent<TTags>) => Promise<void> | void,\n): Destination<TTags> {\n return async (event: BillingEvent<TTags>) => {\n try {\n await handler(event);\n } catch (error) {\n throw new AiBillingDestinationError({\n destinationId,\n cause: error,\n });\n }\n };\n}\n","import { createDestination } from './base-destination.js';\nimport type { Destination } from '../types/index.js';\n\nexport function consoleDestination<TTags>(): Destination<TTags> {\n return createDestination<TTags>('console-logger', event => {\n console.dir(event, {\n depth: null,\n colors: true,\n compact: false,\n });\n });\n}\n","import { AiBillingCostError } from '../index.js';\nimport type { Cost, CostUnit } from '../index.js';\n\nconst getNanos = (cost: Cost): number => {\n switch (cost.unit) {\n case 'base':\n return Math.round(cost.amount * 1_000_000_000);\n case 'cents':\n return Math.round(cost.amount * 10_000_000);\n case 'micros':\n return Math.round(cost.amount * 1_000);\n case 'nanos':\n return Math.round(cost.amount);\n default:\n throw new AiBillingCostError({\n message: `Failed to process cost. Unknown CostUnit: '${String(cost.unit)}'.`,\n });\n }\n};\n\nexport const costToNumber = (cost: Cost, targetUnit: CostUnit): number => {\n const nanos = getNanos(cost);\n\n if (targetUnit === 'nanos') return nanos;\n if (targetUnit === 'micros') return nanos / 1_000;\n if (targetUnit === 'cents') return nanos / 10_000_000;\n return nanos / 1_000_000_000; // base\n};\n\nexport const convertCostUnit = (cost: Cost, targetUnit: CostUnit): Cost => {\n return {\n amount: costToNumber(cost, targetUnit),\n currency: cost.currency,\n unit: targetUnit,\n };\n};\n"],"mappings":";AA4BO,SAAS,0BACd,SAC2B;AAC3B,QAAM,EAAE,YAAY,cAAc,aAAa,WAAW,QAAQ,IAAI;AAEtE,QAAM,eAAe,OAAO;AAAA,IAC1B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,MAMqB;AACnB,QAAI;AACF,YAAM,cAAc,OAAO,kBAAkB,iBAAiB;AAE9D,YAAM,OAAO;AAAA,QACX,GAAI,eAAe,CAAC;AAAA,QACpB,GAAI,eAAe,CAAC;AAAA,MACtB;AAEA,YAAM,QAAQ,MAAM,WAAW;AAAA,QAC7B;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AAED,UAAI,OAAO;AACT,cAAM,QAAQ;AAAA,UACZ,aAAa,IAAI,OAAK,QAAQ,QAAQ,EAAE,KAAK,CAAC,CAAC;AAAA,QACjD;AAAA,MACF;AAAA,IACF,SAAS,KAAK;AACZ,UAAI,QAAS,SAAQ,GAAG;AAAA,UACnB,SAAQ,MAAM,4BAA4B,GAAG;AAAA,IACpD;AAAA,EACF;AAEA,SAAO;AAAA,IACL,sBAAsB;AAAA,IAEtB,cAAc,OAAO,EAAE,YAAY,OAAO,OAAO,MAAM;AACrD,YAAM,SAAwC,MAAM,WAAW;AAE/D,YAAM,UAAU,aAAa;AAAA,QAC3B;AAAA,QACA;AAAA,QACA,OAAO,OAAO;AAAA,QACd,kBAAkB,OAAO;AAAA,QACzB,YAAY,OAAO,UAAU;AAAA,MAC/B,CAAC;AAED,UAAI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C;AACF;;;ACbO,SAAS,kBACd,eACA,SACoB;AACpB,SAAO,OAAO,UAA+B;AAC3C,QAAI;AACF,YAAM,QAAQ,KAAK;AAAA,IACrB,SAAS,OAAO;AACd,YAAM,IAAI,0BAA0B;AAAA,QAClC;AAAA,QACA,OAAO;AAAA,MACT,CAAC;AAAA,IACH;AAAA,EACF;AACF;;;ACdO,SAAS,qBAAgD;AAC9D,SAAO,kBAAyB,kBAAkB,WAAS;AACzD,YAAQ,IAAI,OAAO;AAAA,MACjB,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,SAAS;AAAA,IACX,CAAC;AAAA,EACH,CAAC;AACH;;;ACRA,IAAM,WAAW,CAAC,SAAuB;AACvC,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AACH,aAAO,KAAK,MAAM,KAAK,SAAS,GAAa;AAAA,IAC/C,KAAK;AACH,aAAO,KAAK,MAAM,KAAK,SAAS,GAAU;AAAA,IAC5C,KAAK;AACH,aAAO,KAAK,MAAM,KAAK,SAAS,GAAK;AAAA,IACvC,KAAK;AACH,aAAO,KAAK,MAAM,KAAK,MAAM;AAAA,IAC/B;AACE,YAAM,IAAI,mBAAmB;AAAA,QAC3B,SAAS,8CAA8C,OAAO,KAAK,IAAI,CAAC;AAAA,MAC1E,CAAC;AAAA,EACL;AACF;AAEO,IAAM,eAAe,CAAC,MAAY,eAAiC;AACxE,QAAM,QAAQ,SAAS,IAAI;AAE3B,MAAI,eAAe,QAAS,QAAO;AACnC,MAAI,eAAe,SAAU,QAAO,QAAQ;AAC5C,MAAI,eAAe,QAAS,QAAO,QAAQ;AAC3C,SAAO,QAAQ;AACjB;AAEO,IAAM,kBAAkB,CAAC,MAAY,eAA+B;AACzE,SAAO;AAAA,IACL,QAAQ,aAAa,MAAM,UAAU;AAAA,IACrC,UAAU,KAAK;AAAA,IACf,MAAM;AAAA,EACR;AACF;","names":["name","marker","symbol","name","marker","symbol","name","marker","symbol"]}
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-billing/core",
|
|
3
|
-
"version": "0.0.1-alpha.
|
|
3
|
+
"version": "0.0.1-alpha.7",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
8
|
-
"url": "https://github.com/narevai/ai-billing.git",
|
|
8
|
+
"url": "git+https://github.com/narevai/ai-billing.git",
|
|
9
9
|
"directory": "packages/core"
|
|
10
10
|
},
|
|
11
11
|
"main": "./dist/index.js",
|