@ai-billing/core 0.0.1-alpha.2 → 0.0.1-alpha.4
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 +183 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +89 -7
- package/dist/index.d.ts +89 -7
- package/dist/index.js +173 -6
- package/dist/index.js.map +1 -1
- package/package.json +16 -14
- package/dist/stripe/index.cjs +0 -35
- package/dist/stripe/index.cjs.map +0 -1
- package/dist/stripe/index.d.cts +0 -4
- package/dist/stripe/index.d.ts +0 -4
- package/dist/stripe/index.js +0 -10
- package/dist/stripe/index.js.map +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
"use strict";
|
|
1
2
|
var __defProp = Object.defineProperty;
|
|
2
3
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
4
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
5
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
6
|
var __export = (target, all) => {
|
|
6
|
-
for (var
|
|
7
|
-
__defProp(target,
|
|
7
|
+
for (var name3 in all)
|
|
8
|
+
__defProp(target, name3, { get: all[name3], enumerable: true });
|
|
8
9
|
};
|
|
9
10
|
var __copyProps = (to, from, except, desc) => {
|
|
10
11
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
@@ -19,17 +20,190 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
19
20
|
// src/index.ts
|
|
20
21
|
var index_exports = {};
|
|
21
22
|
__export(index_exports, {
|
|
22
|
-
|
|
23
|
-
|
|
23
|
+
AIBillingError: () => AIBillingError,
|
|
24
|
+
AiBillingDestinationError: () => AiBillingDestinationError,
|
|
25
|
+
AiBillingExtractorError: () => AiBillingExtractorError,
|
|
26
|
+
consoleDestination: () => consoleDestination,
|
|
27
|
+
createDestination: () => createDestination,
|
|
28
|
+
createV3BillingMiddleware: () => createV3BillingMiddleware
|
|
24
29
|
});
|
|
25
30
|
module.exports = __toCommonJS(index_exports);
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
31
|
+
|
|
32
|
+
// src/ai-sdk/language-model-middleware/v3/language-model-v3-base-billing-middleware.ts
|
|
33
|
+
function createV3BillingMiddleware(options) {
|
|
34
|
+
const { buildEvent, destinations, defaultTags, waitUntil, onError } = options;
|
|
35
|
+
const processEvent = async ({
|
|
36
|
+
model,
|
|
37
|
+
params,
|
|
38
|
+
usage,
|
|
39
|
+
providerMetadata,
|
|
40
|
+
responseId
|
|
41
|
+
}) => {
|
|
42
|
+
try {
|
|
43
|
+
const rawHeader = params.headers?.["x-ai-billing-tags"];
|
|
44
|
+
const headerTags = rawHeader ? JSON.parse(rawHeader) : {};
|
|
45
|
+
const tags = {
|
|
46
|
+
...defaultTags ?? {},
|
|
47
|
+
...headerTags
|
|
48
|
+
};
|
|
49
|
+
const event = await buildEvent({
|
|
50
|
+
responseId,
|
|
51
|
+
model,
|
|
52
|
+
usage,
|
|
53
|
+
providerMetadata,
|
|
54
|
+
tags
|
|
55
|
+
});
|
|
56
|
+
if (event) {
|
|
57
|
+
await Promise.allSettled(
|
|
58
|
+
destinations.map((d) => Promise.resolve(d(event)))
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
} catch (err) {
|
|
62
|
+
if (onError) onError(err);
|
|
63
|
+
else console.error("[ai-billing] Core Error:", err);
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
return {
|
|
67
|
+
specificationVersion: "v3",
|
|
68
|
+
wrapGenerate: async ({ doGenerate, model, params }) => {
|
|
69
|
+
const result = await doGenerate();
|
|
70
|
+
const promise = processEvent({
|
|
71
|
+
model,
|
|
72
|
+
params,
|
|
73
|
+
usage: result.usage,
|
|
74
|
+
providerMetadata: result.providerMetadata,
|
|
75
|
+
responseId: result.response?.id
|
|
76
|
+
});
|
|
77
|
+
if (waitUntil) waitUntil(promise);
|
|
78
|
+
return result;
|
|
79
|
+
},
|
|
80
|
+
wrapStream: async ({ doStream, model, params }) => {
|
|
81
|
+
const { stream, ...rest } = await doStream();
|
|
82
|
+
let responseId;
|
|
83
|
+
let usage;
|
|
84
|
+
let providerMetadata;
|
|
85
|
+
const billedStream = stream.pipeThrough(
|
|
86
|
+
new TransformStream({
|
|
87
|
+
transform(chunk, controller) {
|
|
88
|
+
if (chunk.type === "text-start") responseId = chunk.id;
|
|
89
|
+
if (chunk.type === "response-metadata" && !responseId) {
|
|
90
|
+
responseId = chunk.id;
|
|
91
|
+
}
|
|
92
|
+
if (chunk.type === "finish") {
|
|
93
|
+
usage = chunk.usage;
|
|
94
|
+
providerMetadata = chunk.providerMetadata;
|
|
95
|
+
}
|
|
96
|
+
controller.enqueue(chunk);
|
|
97
|
+
},
|
|
98
|
+
flush() {
|
|
99
|
+
const promise = processEvent({
|
|
100
|
+
model,
|
|
101
|
+
params,
|
|
102
|
+
usage,
|
|
103
|
+
providerMetadata,
|
|
104
|
+
responseId
|
|
105
|
+
});
|
|
106
|
+
if (waitUntil) waitUntil(promise);
|
|
107
|
+
}
|
|
108
|
+
})
|
|
109
|
+
);
|
|
110
|
+
return { ...rest, stream: billedStream };
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// src/error/ai-billing-error.ts
|
|
116
|
+
var marker = "ai-billing.error";
|
|
117
|
+
var symbol = Symbol.for(marker);
|
|
118
|
+
var AIBillingError = class _AIBillingError extends Error {
|
|
119
|
+
[symbol] = true;
|
|
120
|
+
cause;
|
|
121
|
+
constructor({
|
|
122
|
+
name: name3,
|
|
123
|
+
message,
|
|
124
|
+
cause
|
|
125
|
+
}) {
|
|
126
|
+
super(message);
|
|
127
|
+
this.name = name3;
|
|
128
|
+
this.cause = cause;
|
|
129
|
+
}
|
|
130
|
+
static isInstance(error) {
|
|
131
|
+
return _AIBillingError.hasMarker(error, marker);
|
|
132
|
+
}
|
|
133
|
+
static hasMarker(error, markerString) {
|
|
134
|
+
const markerSymbol = Symbol.for(markerString);
|
|
135
|
+
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
|
|
136
|
+
}
|
|
29
137
|
};
|
|
138
|
+
|
|
139
|
+
// src/error/extractor-error.ts
|
|
140
|
+
var name = "AiBillingExtractorError";
|
|
141
|
+
var marker2 = `ai-billing.error.${name}`;
|
|
142
|
+
var symbol2 = Symbol.for(marker2);
|
|
143
|
+
var AiBillingExtractorError = class extends AIBillingError {
|
|
144
|
+
[symbol2] = true;
|
|
145
|
+
constructor({
|
|
146
|
+
message = `Failed to extract billing data.`,
|
|
147
|
+
cause
|
|
148
|
+
}) {
|
|
149
|
+
super({ name, message, cause });
|
|
150
|
+
}
|
|
151
|
+
static isInstance(error) {
|
|
152
|
+
return AIBillingError.hasMarker(error, marker2);
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
// src/error/destination-error.ts
|
|
157
|
+
var name2 = "AiBillingDestinationError";
|
|
158
|
+
var marker3 = `ai-billing.error.${name2}`;
|
|
159
|
+
var symbol3 = Symbol.for(marker3);
|
|
160
|
+
var AiBillingDestinationError = class extends AIBillingError {
|
|
161
|
+
[symbol3] = true;
|
|
162
|
+
destinationId;
|
|
163
|
+
constructor({
|
|
164
|
+
destinationId,
|
|
165
|
+
message = `Failed to process billing data for destination: '${destinationId}'.`,
|
|
166
|
+
cause
|
|
167
|
+
}) {
|
|
168
|
+
super({ name: name2, message, cause });
|
|
169
|
+
this.destinationId = destinationId;
|
|
170
|
+
}
|
|
171
|
+
static isInstance(error) {
|
|
172
|
+
return AIBillingError.hasMarker(error, marker3);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
// src/destination/base-destination.ts
|
|
177
|
+
function createDestination(destinationId, handler) {
|
|
178
|
+
return async (event) => {
|
|
179
|
+
try {
|
|
180
|
+
await handler(event);
|
|
181
|
+
} catch (error) {
|
|
182
|
+
throw new AiBillingDestinationError({
|
|
183
|
+
destinationId,
|
|
184
|
+
cause: error
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// src/destination/console-destination.ts
|
|
191
|
+
function consoleDestination() {
|
|
192
|
+
return createDestination("console-logger", (event) => {
|
|
193
|
+
console.dir(event, {
|
|
194
|
+
depth: null,
|
|
195
|
+
colors: true,
|
|
196
|
+
compact: false
|
|
197
|
+
});
|
|
198
|
+
});
|
|
199
|
+
}
|
|
30
200
|
// Annotate the CommonJS export names for ESM import in node:
|
|
31
201
|
0 && (module.exports = {
|
|
32
|
-
|
|
33
|
-
|
|
202
|
+
AIBillingError,
|
|
203
|
+
AiBillingDestinationError,
|
|
204
|
+
AiBillingExtractorError,
|
|
205
|
+
consoleDestination,
|
|
206
|
+
createDestination,
|
|
207
|
+
createV3BillingMiddleware
|
|
34
208
|
});
|
|
35
209
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["declare const __PACKAGE_VERSION__: string;\n\nexport const version = __PACKAGE_VERSION__;\n\nexport type BillingProvider = 'stripe' | 'lemonsqueezy' | 'polar';\n\nexport interface BillingConfig {\n apiKey: string;\n provider: BillingProvider;\n}\n\nexport const initializeBilling = (config: BillingConfig) => {\n return `ai-billing core v${version} initialized for ${config.provider}`;\n};\n\n// comment for release test\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEO,IAAM,UAAU;AAShB,IAAM,oBAAoB,CAAC,WAA0B;AAC1D,SAAO,oBAAoB,OAAO,oBAAoB,OAAO,QAAQ;AACvE;","names":[]}
|
|
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,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;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"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,9 +1,91 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { LanguageModelV3, LanguageModelV3Usage, SharedV3ProviderMetadata, LanguageModelV3Middleware } from '@ai-sdk/provider';
|
|
2
|
+
|
|
3
|
+
type Destination<TTags = DefaultTags> = (event: BillingEvent<TTags>) => Promise<void> | void;
|
|
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
|
+
interface Usage {
|
|
12
|
+
readonly subProviderId?: string;
|
|
13
|
+
readonly inputTokens: number;
|
|
14
|
+
readonly outputTokens: number;
|
|
15
|
+
readonly totalTokens: number;
|
|
16
|
+
readonly reasoningTokens?: number;
|
|
17
|
+
readonly cacheReadTokens?: number;
|
|
18
|
+
readonly cacheWriteTokens?: number;
|
|
19
|
+
readonly requestCount?: number;
|
|
20
|
+
readonly rawProviderCost?: number;
|
|
21
|
+
}
|
|
22
|
+
interface BillingEvent<TTags = DefaultTags> {
|
|
23
|
+
readonly generationId: string;
|
|
24
|
+
readonly modelId: string;
|
|
25
|
+
readonly provider: string;
|
|
26
|
+
readonly usage: Usage;
|
|
27
|
+
readonly cost: Cost;
|
|
28
|
+
readonly tags: TTags;
|
|
29
|
+
}
|
|
30
|
+
type EventBuilder<TPayload, TTags = DefaultTags> = (payload: TPayload) => Promise<BillingEvent<TTags> | null> | BillingEvent<TTags> | null;
|
|
31
|
+
|
|
32
|
+
type DefaultTags = Record<string, unknown>;
|
|
33
|
+
interface BaseBillingMiddlewareOptions<TTags = DefaultTags> {
|
|
34
|
+
destinations: Destination<TTags>[];
|
|
35
|
+
defaultTags?: TTags;
|
|
36
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
37
|
+
onError?: (error: unknown) => void;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface BuildV3EventPayload<TTags> {
|
|
41
|
+
responseId: string | undefined;
|
|
42
|
+
model: LanguageModelV3;
|
|
43
|
+
usage: LanguageModelV3Usage | undefined;
|
|
44
|
+
providerMetadata: SharedV3ProviderMetadata | undefined;
|
|
45
|
+
tags: TTags;
|
|
46
|
+
}
|
|
47
|
+
interface BillingMiddlewareV3Options<TTags> extends BaseBillingMiddlewareOptions<TTags> {
|
|
48
|
+
buildEvent: EventBuilder<BuildV3EventPayload<TTags>, TTags>;
|
|
49
|
+
}
|
|
50
|
+
declare function createV3BillingMiddleware<TTags>(options: BillingMiddlewareV3Options<TTags>): LanguageModelV3Middleware;
|
|
51
|
+
|
|
52
|
+
declare function createDestination<TTags>(destinationId: string, handler: (event: BillingEvent<TTags>) => Promise<void> | void): Destination<TTags>;
|
|
53
|
+
|
|
54
|
+
declare function consoleDestination<TTags>(): Destination<TTags>;
|
|
55
|
+
|
|
56
|
+
declare const symbol$2: unique symbol;
|
|
57
|
+
declare class AIBillingError extends Error {
|
|
58
|
+
private readonly [symbol$2];
|
|
59
|
+
readonly cause?: unknown;
|
|
60
|
+
constructor({ name, message, cause, }: {
|
|
61
|
+
name: string;
|
|
62
|
+
message: string;
|
|
63
|
+
cause?: unknown;
|
|
64
|
+
});
|
|
65
|
+
static isInstance(error: unknown): error is AIBillingError;
|
|
66
|
+
protected static hasMarker(error: unknown, markerString: string): boolean;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
declare const symbol$1: unique symbol;
|
|
70
|
+
declare class AiBillingExtractorError extends AIBillingError {
|
|
71
|
+
private readonly [symbol$1];
|
|
72
|
+
constructor({ message, cause, }: {
|
|
73
|
+
message?: string;
|
|
74
|
+
cause?: unknown;
|
|
75
|
+
});
|
|
76
|
+
static isInstance(error: unknown): error is AiBillingExtractorError;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
declare const symbol: unique symbol;
|
|
80
|
+
declare class AiBillingDestinationError extends AIBillingError {
|
|
81
|
+
private readonly [symbol];
|
|
82
|
+
readonly destinationId?: string;
|
|
83
|
+
constructor({ destinationId, message, cause, }: {
|
|
84
|
+
destinationId?: string;
|
|
85
|
+
message?: string;
|
|
86
|
+
cause?: unknown;
|
|
87
|
+
});
|
|
88
|
+
static isInstance(error: unknown): error is AiBillingDestinationError;
|
|
6
89
|
}
|
|
7
|
-
declare const initializeBilling: (config: BillingConfig) => string;
|
|
8
90
|
|
|
9
|
-
export { type
|
|
91
|
+
export { AIBillingError, AiBillingDestinationError, AiBillingExtractorError, type BaseBillingMiddlewareOptions, type BillingEvent, type BillingMiddlewareV3Options, type BuildV3EventPayload, type Cost, type CostUnit, type DefaultTags, type Destination, type EventBuilder, type Usage, consoleDestination, createDestination, createV3BillingMiddleware };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,9 +1,91 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { LanguageModelV3, LanguageModelV3Usage, SharedV3ProviderMetadata, LanguageModelV3Middleware } from '@ai-sdk/provider';
|
|
2
|
+
|
|
3
|
+
type Destination<TTags = DefaultTags> = (event: BillingEvent<TTags>) => Promise<void> | void;
|
|
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
|
+
interface Usage {
|
|
12
|
+
readonly subProviderId?: string;
|
|
13
|
+
readonly inputTokens: number;
|
|
14
|
+
readonly outputTokens: number;
|
|
15
|
+
readonly totalTokens: number;
|
|
16
|
+
readonly reasoningTokens?: number;
|
|
17
|
+
readonly cacheReadTokens?: number;
|
|
18
|
+
readonly cacheWriteTokens?: number;
|
|
19
|
+
readonly requestCount?: number;
|
|
20
|
+
readonly rawProviderCost?: number;
|
|
21
|
+
}
|
|
22
|
+
interface BillingEvent<TTags = DefaultTags> {
|
|
23
|
+
readonly generationId: string;
|
|
24
|
+
readonly modelId: string;
|
|
25
|
+
readonly provider: string;
|
|
26
|
+
readonly usage: Usage;
|
|
27
|
+
readonly cost: Cost;
|
|
28
|
+
readonly tags: TTags;
|
|
29
|
+
}
|
|
30
|
+
type EventBuilder<TPayload, TTags = DefaultTags> = (payload: TPayload) => Promise<BillingEvent<TTags> | null> | BillingEvent<TTags> | null;
|
|
31
|
+
|
|
32
|
+
type DefaultTags = Record<string, unknown>;
|
|
33
|
+
interface BaseBillingMiddlewareOptions<TTags = DefaultTags> {
|
|
34
|
+
destinations: Destination<TTags>[];
|
|
35
|
+
defaultTags?: TTags;
|
|
36
|
+
waitUntil?: (promise: Promise<unknown>) => void;
|
|
37
|
+
onError?: (error: unknown) => void;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface BuildV3EventPayload<TTags> {
|
|
41
|
+
responseId: string | undefined;
|
|
42
|
+
model: LanguageModelV3;
|
|
43
|
+
usage: LanguageModelV3Usage | undefined;
|
|
44
|
+
providerMetadata: SharedV3ProviderMetadata | undefined;
|
|
45
|
+
tags: TTags;
|
|
46
|
+
}
|
|
47
|
+
interface BillingMiddlewareV3Options<TTags> extends BaseBillingMiddlewareOptions<TTags> {
|
|
48
|
+
buildEvent: EventBuilder<BuildV3EventPayload<TTags>, TTags>;
|
|
49
|
+
}
|
|
50
|
+
declare function createV3BillingMiddleware<TTags>(options: BillingMiddlewareV3Options<TTags>): LanguageModelV3Middleware;
|
|
51
|
+
|
|
52
|
+
declare function createDestination<TTags>(destinationId: string, handler: (event: BillingEvent<TTags>) => Promise<void> | void): Destination<TTags>;
|
|
53
|
+
|
|
54
|
+
declare function consoleDestination<TTags>(): Destination<TTags>;
|
|
55
|
+
|
|
56
|
+
declare const symbol$2: unique symbol;
|
|
57
|
+
declare class AIBillingError extends Error {
|
|
58
|
+
private readonly [symbol$2];
|
|
59
|
+
readonly cause?: unknown;
|
|
60
|
+
constructor({ name, message, cause, }: {
|
|
61
|
+
name: string;
|
|
62
|
+
message: string;
|
|
63
|
+
cause?: unknown;
|
|
64
|
+
});
|
|
65
|
+
static isInstance(error: unknown): error is AIBillingError;
|
|
66
|
+
protected static hasMarker(error: unknown, markerString: string): boolean;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
declare const symbol$1: unique symbol;
|
|
70
|
+
declare class AiBillingExtractorError extends AIBillingError {
|
|
71
|
+
private readonly [symbol$1];
|
|
72
|
+
constructor({ message, cause, }: {
|
|
73
|
+
message?: string;
|
|
74
|
+
cause?: unknown;
|
|
75
|
+
});
|
|
76
|
+
static isInstance(error: unknown): error is AiBillingExtractorError;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
declare const symbol: unique symbol;
|
|
80
|
+
declare class AiBillingDestinationError extends AIBillingError {
|
|
81
|
+
private readonly [symbol];
|
|
82
|
+
readonly destinationId?: string;
|
|
83
|
+
constructor({ destinationId, message, cause, }: {
|
|
84
|
+
destinationId?: string;
|
|
85
|
+
message?: string;
|
|
86
|
+
cause?: unknown;
|
|
87
|
+
});
|
|
88
|
+
static isInstance(error: unknown): error is AiBillingDestinationError;
|
|
6
89
|
}
|
|
7
|
-
declare const initializeBilling: (config: BillingConfig) => string;
|
|
8
90
|
|
|
9
|
-
export { type
|
|
91
|
+
export { AIBillingError, AiBillingDestinationError, AiBillingExtractorError, type BaseBillingMiddlewareOptions, type BillingEvent, type BillingMiddlewareV3Options, type BuildV3EventPayload, type Cost, type CostUnit, type DefaultTags, type Destination, type EventBuilder, type Usage, consoleDestination, createDestination, createV3BillingMiddleware };
|
package/dist/index.js
CHANGED
|
@@ -1,10 +1,177 @@
|
|
|
1
|
-
// src/
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
// src/ai-sdk/language-model-middleware/v3/language-model-v3-base-billing-middleware.ts
|
|
2
|
+
function createV3BillingMiddleware(options) {
|
|
3
|
+
const { buildEvent, destinations, defaultTags, waitUntil, onError } = options;
|
|
4
|
+
const processEvent = async ({
|
|
5
|
+
model,
|
|
6
|
+
params,
|
|
7
|
+
usage,
|
|
8
|
+
providerMetadata,
|
|
9
|
+
responseId
|
|
10
|
+
}) => {
|
|
11
|
+
try {
|
|
12
|
+
const rawHeader = params.headers?.["x-ai-billing-tags"];
|
|
13
|
+
const headerTags = rawHeader ? JSON.parse(rawHeader) : {};
|
|
14
|
+
const tags = {
|
|
15
|
+
...defaultTags ?? {},
|
|
16
|
+
...headerTags
|
|
17
|
+
};
|
|
18
|
+
const event = await buildEvent({
|
|
19
|
+
responseId,
|
|
20
|
+
model,
|
|
21
|
+
usage,
|
|
22
|
+
providerMetadata,
|
|
23
|
+
tags
|
|
24
|
+
});
|
|
25
|
+
if (event) {
|
|
26
|
+
await Promise.allSettled(
|
|
27
|
+
destinations.map((d) => Promise.resolve(d(event)))
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
} catch (err) {
|
|
31
|
+
if (onError) onError(err);
|
|
32
|
+
else console.error("[ai-billing] Core Error:", err);
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
return {
|
|
36
|
+
specificationVersion: "v3",
|
|
37
|
+
wrapGenerate: async ({ doGenerate, model, params }) => {
|
|
38
|
+
const result = await doGenerate();
|
|
39
|
+
const promise = processEvent({
|
|
40
|
+
model,
|
|
41
|
+
params,
|
|
42
|
+
usage: result.usage,
|
|
43
|
+
providerMetadata: result.providerMetadata,
|
|
44
|
+
responseId: result.response?.id
|
|
45
|
+
});
|
|
46
|
+
if (waitUntil) waitUntil(promise);
|
|
47
|
+
return result;
|
|
48
|
+
},
|
|
49
|
+
wrapStream: async ({ doStream, model, params }) => {
|
|
50
|
+
const { stream, ...rest } = await doStream();
|
|
51
|
+
let responseId;
|
|
52
|
+
let usage;
|
|
53
|
+
let providerMetadata;
|
|
54
|
+
const billedStream = stream.pipeThrough(
|
|
55
|
+
new TransformStream({
|
|
56
|
+
transform(chunk, controller) {
|
|
57
|
+
if (chunk.type === "text-start") responseId = chunk.id;
|
|
58
|
+
if (chunk.type === "response-metadata" && !responseId) {
|
|
59
|
+
responseId = chunk.id;
|
|
60
|
+
}
|
|
61
|
+
if (chunk.type === "finish") {
|
|
62
|
+
usage = chunk.usage;
|
|
63
|
+
providerMetadata = chunk.providerMetadata;
|
|
64
|
+
}
|
|
65
|
+
controller.enqueue(chunk);
|
|
66
|
+
},
|
|
67
|
+
flush() {
|
|
68
|
+
const promise = processEvent({
|
|
69
|
+
model,
|
|
70
|
+
params,
|
|
71
|
+
usage,
|
|
72
|
+
providerMetadata,
|
|
73
|
+
responseId
|
|
74
|
+
});
|
|
75
|
+
if (waitUntil) waitUntil(promise);
|
|
76
|
+
}
|
|
77
|
+
})
|
|
78
|
+
);
|
|
79
|
+
return { ...rest, stream: billedStream };
|
|
80
|
+
}
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// src/error/ai-billing-error.ts
|
|
85
|
+
var marker = "ai-billing.error";
|
|
86
|
+
var symbol = Symbol.for(marker);
|
|
87
|
+
var AIBillingError = class _AIBillingError extends Error {
|
|
88
|
+
[symbol] = true;
|
|
89
|
+
cause;
|
|
90
|
+
constructor({
|
|
91
|
+
name: name3,
|
|
92
|
+
message,
|
|
93
|
+
cause
|
|
94
|
+
}) {
|
|
95
|
+
super(message);
|
|
96
|
+
this.name = name3;
|
|
97
|
+
this.cause = cause;
|
|
98
|
+
}
|
|
99
|
+
static isInstance(error) {
|
|
100
|
+
return _AIBillingError.hasMarker(error, marker);
|
|
101
|
+
}
|
|
102
|
+
static hasMarker(error, markerString) {
|
|
103
|
+
const markerSymbol = Symbol.for(markerString);
|
|
104
|
+
return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
|
|
105
|
+
}
|
|
5
106
|
};
|
|
107
|
+
|
|
108
|
+
// src/error/extractor-error.ts
|
|
109
|
+
var name = "AiBillingExtractorError";
|
|
110
|
+
var marker2 = `ai-billing.error.${name}`;
|
|
111
|
+
var symbol2 = Symbol.for(marker2);
|
|
112
|
+
var AiBillingExtractorError = class extends AIBillingError {
|
|
113
|
+
[symbol2] = true;
|
|
114
|
+
constructor({
|
|
115
|
+
message = `Failed to extract billing data.`,
|
|
116
|
+
cause
|
|
117
|
+
}) {
|
|
118
|
+
super({ name, message, cause });
|
|
119
|
+
}
|
|
120
|
+
static isInstance(error) {
|
|
121
|
+
return AIBillingError.hasMarker(error, marker2);
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
// src/error/destination-error.ts
|
|
126
|
+
var name2 = "AiBillingDestinationError";
|
|
127
|
+
var marker3 = `ai-billing.error.${name2}`;
|
|
128
|
+
var symbol3 = Symbol.for(marker3);
|
|
129
|
+
var AiBillingDestinationError = class extends AIBillingError {
|
|
130
|
+
[symbol3] = true;
|
|
131
|
+
destinationId;
|
|
132
|
+
constructor({
|
|
133
|
+
destinationId,
|
|
134
|
+
message = `Failed to process billing data for destination: '${destinationId}'.`,
|
|
135
|
+
cause
|
|
136
|
+
}) {
|
|
137
|
+
super({ name: name2, message, cause });
|
|
138
|
+
this.destinationId = destinationId;
|
|
139
|
+
}
|
|
140
|
+
static isInstance(error) {
|
|
141
|
+
return AIBillingError.hasMarker(error, marker3);
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
// src/destination/base-destination.ts
|
|
146
|
+
function createDestination(destinationId, handler) {
|
|
147
|
+
return async (event) => {
|
|
148
|
+
try {
|
|
149
|
+
await handler(event);
|
|
150
|
+
} catch (error) {
|
|
151
|
+
throw new AiBillingDestinationError({
|
|
152
|
+
destinationId,
|
|
153
|
+
cause: error
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// src/destination/console-destination.ts
|
|
160
|
+
function consoleDestination() {
|
|
161
|
+
return createDestination("console-logger", (event) => {
|
|
162
|
+
console.dir(event, {
|
|
163
|
+
depth: null,
|
|
164
|
+
colors: true,
|
|
165
|
+
compact: false
|
|
166
|
+
});
|
|
167
|
+
});
|
|
168
|
+
}
|
|
6
169
|
export {
|
|
7
|
-
|
|
8
|
-
|
|
170
|
+
AIBillingError,
|
|
171
|
+
AiBillingDestinationError,
|
|
172
|
+
AiBillingExtractorError,
|
|
173
|
+
consoleDestination,
|
|
174
|
+
createDestination,
|
|
175
|
+
createV3BillingMiddleware
|
|
9
176
|
};
|
|
10
177
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts"],"sourcesContent":["declare const __PACKAGE_VERSION__: string;\n\nexport const version = __PACKAGE_VERSION__;\n\nexport type BillingProvider = 'stripe' | 'lemonsqueezy' | 'polar';\n\nexport interface BillingConfig {\n apiKey: string;\n provider: BillingProvider;\n}\n\nexport const initializeBilling = (config: BillingConfig) => {\n return `ai-billing core v${version} initialized for ${config.provider}`;\n};\n\n// comment for release test\n"],"mappings":";AAEO,IAAM,UAAU;AAShB,IAAM,oBAAoB,CAAC,WAA0B;AAC1D,SAAO,oBAAoB,OAAO,oBAAoB,OAAO,QAAQ;AACvE;","names":[]}
|
|
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;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,MAMqB;AACnB,QAAI;AACF,YAAM,YAAY,OAAO,UAAU,mBAAmB;AACtD,YAAM,aAAa,YAAY,KAAK,MAAM,SAAS,IAAI,CAAC;AAExD,YAAM,OAAO;AAAA,QACX,GAAI,eAAe,CAAC;AAAA,QACpB,GAAG;AAAA,MACL;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,UAAW,WAAU,OAAO;AAChC,aAAO;AAAA,IACT;AAAA,IAEA,YAAY,OAAO,EAAE,UAAU,OAAO,OAA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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-billing/core",
|
|
3
|
-
"version": "0.0.1-alpha.
|
|
3
|
+
"version": "0.0.1-alpha.4",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"repository": {
|
|
@@ -20,16 +20,6 @@
|
|
|
20
20
|
"types": "./dist/index.d.cts",
|
|
21
21
|
"default": "./dist/index.cjs"
|
|
22
22
|
}
|
|
23
|
-
},
|
|
24
|
-
"./stripe": {
|
|
25
|
-
"import": {
|
|
26
|
-
"types": "./dist/stripe/index.d.ts",
|
|
27
|
-
"default": "./dist/stripe/index.js"
|
|
28
|
-
},
|
|
29
|
-
"require": {
|
|
30
|
-
"types": "./dist/stripe/index.d.cts",
|
|
31
|
-
"default": "./dist/stripe/index.cjs"
|
|
32
|
-
}
|
|
33
23
|
}
|
|
34
24
|
},
|
|
35
25
|
"publishConfig": {
|
|
@@ -39,12 +29,24 @@
|
|
|
39
29
|
"dist"
|
|
40
30
|
],
|
|
41
31
|
"devDependencies": {
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
32
|
+
"@ai-sdk/provider": "^3.0.8",
|
|
33
|
+
"tsup": "^8.5.1",
|
|
34
|
+
"typescript": "5.9.2",
|
|
35
|
+
"vitest": "4.1.1",
|
|
36
|
+
"@edge-runtime/vm": "^5.0.0",
|
|
37
|
+
"@ai-billing/testing": "0.0.1-alpha.0",
|
|
38
|
+
"@ai-billing/typescript-config": "0.0.1-alpha.0"
|
|
39
|
+
},
|
|
40
|
+
"peerDependencies": {
|
|
41
|
+
"@ai-sdk/provider": "^3.0.8"
|
|
42
|
+
},
|
|
43
|
+
"engines": {
|
|
44
|
+
"node": ">=20.0.0"
|
|
45
45
|
},
|
|
46
46
|
"scripts": {
|
|
47
47
|
"build": "tsup",
|
|
48
|
+
"check-types": "tsc --noEmit",
|
|
49
|
+
"lint": "oxlint",
|
|
48
50
|
"dev": "tsup --watch",
|
|
49
51
|
"test": "vitest run",
|
|
50
52
|
"test:watch": "vitest"
|
package/dist/stripe/index.cjs
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
-
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
-
var __export = (target, all) => {
|
|
6
|
-
for (var name in all)
|
|
7
|
-
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
-
};
|
|
9
|
-
var __copyProps = (to, from, except, desc) => {
|
|
10
|
-
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
-
for (let key of __getOwnPropNames(from))
|
|
12
|
-
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
-
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
-
}
|
|
15
|
-
return to;
|
|
16
|
-
};
|
|
17
|
-
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
-
|
|
19
|
-
// src/stripe/index.ts
|
|
20
|
-
var index_exports = {};
|
|
21
|
-
__export(index_exports, {
|
|
22
|
-
initializeStripeBilling: () => initializeStripeBilling,
|
|
23
|
-
version: () => version
|
|
24
|
-
});
|
|
25
|
-
module.exports = __toCommonJS(index_exports);
|
|
26
|
-
var version = "0.0.1-alpha.2";
|
|
27
|
-
var initializeStripeBilling = () => {
|
|
28
|
-
return `ai-billing core v${version} initialized for stripe`;
|
|
29
|
-
};
|
|
30
|
-
// Annotate the CommonJS export names for ESM import in node:
|
|
31
|
-
0 && (module.exports = {
|
|
32
|
-
initializeStripeBilling,
|
|
33
|
-
version
|
|
34
|
-
});
|
|
35
|
-
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/stripe/index.ts"],"sourcesContent":["declare const __PACKAGE_VERSION__: string;\n\nexport const version = __PACKAGE_VERSION__;\n\nexport const initializeStripeBilling = () => {\n return `ai-billing core v${version} initialized for stripe`;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEO,IAAM,UAAU;AAEhB,IAAM,0BAA0B,MAAM;AAC3C,SAAO,oBAAoB,OAAO;AACpC;","names":[]}
|
package/dist/stripe/index.d.cts
DELETED
package/dist/stripe/index.d.ts
DELETED
package/dist/stripe/index.js
DELETED
package/dist/stripe/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/stripe/index.ts"],"sourcesContent":["declare const __PACKAGE_VERSION__: string;\n\nexport const version = __PACKAGE_VERSION__;\n\nexport const initializeStripeBilling = () => {\n return `ai-billing core v${version} initialized for stripe`;\n};\n"],"mappings":";AAEO,IAAM,UAAU;AAEhB,IAAM,0BAA0B,MAAM;AAC3C,SAAO,oBAAoB,OAAO;AACpC;","names":[]}
|