@drawbridge/drawbridge-utils 0.0.26 → 0.0.28

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.
@@ -0,0 +1,208 @@
1
+ // Generic ledger primitives — authoritative balance for user.balance.ai lives
2
+ // in Mongo, and every change to that balance is recorded in the `transactions`
3
+ // collection. Domain-specific helpers (e.g., LLM pricing in ./ai.js) call into
4
+ // credit/debit with pre-computed amounts.
5
+ //
6
+ // import { credit, debit } from '@drawbridge/drawbridge-utils/transactions';
7
+ //
8
+ // await credit({ db, authenticated, userId, amount: 500,
9
+ // category: 'promotional', tags: [ 'welcome' ] });
10
+ //
11
+ // await debit({ db, authenticated, userId, amount: 9,
12
+ // category: 'usage', tags: [ 'google', 'gemini-2.5-flash' ],
13
+ // provider: { name, model, tokens, snapshot } });
14
+ //
15
+ // `db` is the wrapper returned by @drawbridge/mongodb — credit/debit duck-type
16
+ // against its `.create`, `.update` interface so this module has no hard dep.
17
+
18
+ // Internal: write a transactions row. The user.balance.ai update happens in the
19
+ // callers (credit/debit) so we can keep the atomic gate-and-decrement contract.
20
+ const recordTransaction = async ({
21
+ db,
22
+ authenticated,
23
+ userId,
24
+ category,
25
+ tags,
26
+ amount,
27
+ balance,
28
+ provider,
29
+ stripeInvoiceId,
30
+ stripeEventId
31
+ }) => {
32
+
33
+ await db.create({
34
+ authenticated,
35
+ collection : 'transactions',
36
+ data : {
37
+ userId,
38
+ billable : {
39
+ item : 'ai'
40
+ },
41
+ category,
42
+ tags,
43
+ amount,
44
+ balance,
45
+ ...( provider && { provider }),
46
+ ...( stripeInvoiceId && { stripeInvoiceId }),
47
+ ...( stripeEventId && { stripeEventId })
48
+ }
49
+ });
50
+
51
+ };
52
+
53
+ // Additive: grant credits to a user. Used by welcome flow, top-up webhook,
54
+ // admin promo, refunds. If stripeEventId is provided, the unique sparse index
55
+ // on the transactions collection makes the insert idempotent against webhook
56
+ // retries — second call no-ops at the Mongo layer.
57
+ const credit = async ({
58
+ db,
59
+ authenticated,
60
+ userId,
61
+ amount,
62
+ category,
63
+ tags = [],
64
+ stripeInvoiceId,
65
+ stripeEventId
66
+ }) => {
67
+
68
+ if( !Number.isInteger( amount ) || amount <= 0 ){
69
+
70
+ throw new Error( `credit() requires a positive integer amount, got ${ amount }` );
71
+
72
+ }
73
+
74
+ const result = await db.update({
75
+ authenticated,
76
+ collection : 'users',
77
+ query : {
78
+ id : userId
79
+ },
80
+ data : {
81
+ $inc : {
82
+ 'balance.ai' : amount
83
+ }
84
+ }
85
+ });
86
+
87
+ const after = result?.value?.balance?.ai ?? result?.balance?.ai;
88
+
89
+ if( typeof after !== 'number' ){
90
+
91
+ throw new Error( `credit() could not read updated balance for user ${ userId }` );
92
+
93
+ }
94
+
95
+ const before = after - amount;
96
+
97
+ await recordTransaction({
98
+ db,
99
+ authenticated,
100
+ userId,
101
+ category,
102
+ tags,
103
+ amount,
104
+ balance : {
105
+ before,
106
+ after
107
+ },
108
+ stripeInvoiceId,
109
+ stripeEventId
110
+ });
111
+
112
+ return {
113
+ balance : {
114
+ before,
115
+ after
116
+ }
117
+ };
118
+
119
+ };
120
+
121
+ // Subtractive: atomic gate-and-decrement against the user's balance. The
122
+ // $gte filter ensures concurrent calls can't drive balance negative — exactly
123
+ // one of N parallel requests with overlapping cost will succeed; the rest
124
+ // throw InsufficientCreditsError. Callers (e.g., ai.js) pre-compute `amount`
125
+ // from their domain-specific pricing.
126
+ class InsufficientCreditsError extends Error {
127
+
128
+ constructor( message = 'Insufficient AI credits' ){
129
+
130
+ super( message );
131
+ this.name = 'InsufficientCreditsError';
132
+ this.status = 402;
133
+
134
+ }
135
+
136
+ }
137
+
138
+ const debit = async ({
139
+ db,
140
+ authenticated,
141
+ userId,
142
+ amount,
143
+ category,
144
+ tags = [],
145
+ provider,
146
+ stripeInvoiceId,
147
+ stripeEventId
148
+ }) => {
149
+
150
+ if( !Number.isInteger( amount ) || amount <= 0 ){
151
+
152
+ throw new Error( `debit() requires a positive integer amount, got ${ amount }` );
153
+
154
+ }
155
+
156
+ const result = await db.update({
157
+ authenticated,
158
+ collection : 'users',
159
+ query : {
160
+ id : userId,
161
+ 'balance.ai' : {
162
+ $gte : amount
163
+ }
164
+ },
165
+ data : {
166
+ $inc : {
167
+ 'balance.ai' : -amount
168
+ }
169
+ }
170
+ });
171
+
172
+ const after = result?.value?.balance?.ai ?? result?.balance?.ai;
173
+
174
+ if( typeof after !== 'number' ){
175
+
176
+ throw new InsufficientCreditsError();
177
+
178
+ }
179
+
180
+ const before = after + amount;
181
+
182
+ await recordTransaction({
183
+ db,
184
+ authenticated,
185
+ userId,
186
+ category,
187
+ tags,
188
+ amount : -amount,
189
+ balance : {
190
+ before,
191
+ after
192
+ },
193
+ provider,
194
+ stripeInvoiceId,
195
+ stripeEventId
196
+ });
197
+
198
+ return {
199
+ amount : -amount,
200
+ balance : {
201
+ before,
202
+ after
203
+ }
204
+ };
205
+
206
+ };
207
+
208
+ export { InsufficientCreditsError, credit, debit };
@@ -0,0 +1,10 @@
1
+ import {
2
+ InsufficientCreditsError,
3
+ credit,
4
+ debit
5
+ } from "./chunk-RC5E56UB.js";
6
+ export {
7
+ InsufficientCreditsError,
8
+ credit,
9
+ debit
10
+ };
package/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "type": "module",
3
3
  "dependencies": {
4
- "@drawbridge/drawbridge-agents": "0.0.9",
4
+ "@drawbridge/drawbridge-agents": "0.0.10",
5
+ "@google/genai": "1.30.0",
5
6
  "axios": "1.16.0",
6
7
  "currency-codes": "2.2.0",
7
8
  "nanoid": "3.3.8",
@@ -16,6 +17,11 @@
16
17
  "import": "./dist/index.js",
17
18
  "require": "./dist/index.cjs"
18
19
  },
20
+ "./ai": {
21
+ "types": "./dist/ai.d.ts",
22
+ "import": "./dist/ai.js",
23
+ "require": "./dist/ai.cjs"
24
+ },
19
25
  "./encrypt": {
20
26
  "types": "./dist/encrypt.d.ts",
21
27
  "import": "./dist/encrypt.js",
@@ -75,6 +81,11 @@
75
81
  "types": "./dist/token.d.ts",
76
82
  "import": "./dist/token.js",
77
83
  "require": "./dist/token.cjs"
84
+ },
85
+ "./transactions": {
86
+ "types": "./dist/transactions.d.ts",
87
+ "import": "./dist/transactions.js",
88
+ "require": "./dist/transactions.cjs"
78
89
  }
79
90
  },
80
91
  "files": [
@@ -92,5 +103,5 @@
92
103
  "build": "tsup && npm publish"
93
104
  },
94
105
  "types": "dist/index.d.ts",
95
- "version": "0.0.26"
106
+ "version": "0.0.28"
96
107
  }