@drawbridge/drawbridge-utils 0.0.27 → 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,179 @@
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
+ // transactions.js
20
+ var transactions_exports = {};
21
+ __export(transactions_exports, {
22
+ InsufficientCreditsError: () => InsufficientCreditsError,
23
+ credit: () => credit,
24
+ debit: () => debit
25
+ });
26
+ module.exports = __toCommonJS(transactions_exports);
27
+ var recordTransaction = async ({
28
+ db,
29
+ authenticated,
30
+ userId,
31
+ category,
32
+ tags,
33
+ amount,
34
+ balance,
35
+ provider,
36
+ stripeInvoiceId,
37
+ stripeEventId
38
+ }) => {
39
+ await db.create({
40
+ authenticated,
41
+ collection: "transactions",
42
+ data: {
43
+ userId,
44
+ billable: {
45
+ item: "ai"
46
+ },
47
+ category,
48
+ tags,
49
+ amount,
50
+ balance,
51
+ ...provider && { provider },
52
+ ...stripeInvoiceId && { stripeInvoiceId },
53
+ ...stripeEventId && { stripeEventId }
54
+ }
55
+ });
56
+ };
57
+ var credit = async ({
58
+ db,
59
+ authenticated,
60
+ userId,
61
+ amount,
62
+ category,
63
+ tags = [],
64
+ stripeInvoiceId,
65
+ stripeEventId
66
+ }) => {
67
+ var _a, _b, _c;
68
+ if (!Number.isInteger(amount) || amount <= 0) {
69
+ throw new Error(`credit() requires a positive integer amount, got ${amount}`);
70
+ }
71
+ const result = await db.update({
72
+ authenticated,
73
+ collection: "users",
74
+ query: {
75
+ id: userId
76
+ },
77
+ data: {
78
+ $inc: {
79
+ "balance.ai": amount
80
+ }
81
+ }
82
+ });
83
+ const after = ((_b = (_a = result == null ? void 0 : result.value) == null ? void 0 : _a.balance) == null ? void 0 : _b.ai) ?? ((_c = result == null ? void 0 : result.balance) == null ? void 0 : _c.ai);
84
+ if (typeof after !== "number") {
85
+ throw new Error(`credit() could not read updated balance for user ${userId}`);
86
+ }
87
+ const before = after - amount;
88
+ await recordTransaction({
89
+ db,
90
+ authenticated,
91
+ userId,
92
+ category,
93
+ tags,
94
+ amount,
95
+ balance: {
96
+ before,
97
+ after
98
+ },
99
+ stripeInvoiceId,
100
+ stripeEventId
101
+ });
102
+ return {
103
+ balance: {
104
+ before,
105
+ after
106
+ }
107
+ };
108
+ };
109
+ var InsufficientCreditsError = class extends Error {
110
+ constructor(message = "Insufficient AI credits") {
111
+ super(message);
112
+ this.name = "InsufficientCreditsError";
113
+ this.status = 402;
114
+ }
115
+ };
116
+ var debit = async ({
117
+ db,
118
+ authenticated,
119
+ userId,
120
+ amount,
121
+ category,
122
+ tags = [],
123
+ provider,
124
+ stripeInvoiceId,
125
+ stripeEventId
126
+ }) => {
127
+ var _a, _b, _c;
128
+ if (!Number.isInteger(amount) || amount <= 0) {
129
+ throw new Error(`debit() requires a positive integer amount, got ${amount}`);
130
+ }
131
+ const result = await db.update({
132
+ authenticated,
133
+ collection: "users",
134
+ query: {
135
+ id: userId,
136
+ "balance.ai": {
137
+ $gte: amount
138
+ }
139
+ },
140
+ data: {
141
+ $inc: {
142
+ "balance.ai": -amount
143
+ }
144
+ }
145
+ });
146
+ const after = ((_b = (_a = result == null ? void 0 : result.value) == null ? void 0 : _a.balance) == null ? void 0 : _b.ai) ?? ((_c = result == null ? void 0 : result.balance) == null ? void 0 : _c.ai);
147
+ if (typeof after !== "number") {
148
+ throw new InsufficientCreditsError();
149
+ }
150
+ const before = after + amount;
151
+ await recordTransaction({
152
+ db,
153
+ authenticated,
154
+ userId,
155
+ category,
156
+ tags,
157
+ amount: -amount,
158
+ balance: {
159
+ before,
160
+ after
161
+ },
162
+ provider,
163
+ stripeInvoiceId,
164
+ stripeEventId
165
+ });
166
+ return {
167
+ amount: -amount,
168
+ balance: {
169
+ before,
170
+ after
171
+ }
172
+ };
173
+ };
174
+ // Annotate the CommonJS export names for ESM import in node:
175
+ 0 && (module.exports = {
176
+ InsufficientCreditsError,
177
+ credit,
178
+ debit
179
+ });
@@ -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,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
@@ -2,6 +2,7 @@
2
2
  "type": "module",
3
3
  "dependencies": {
4
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.27"
106
+ "version": "0.0.28"
96
107
  }