@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.
package/dist/index.d.cts CHANGED
@@ -313,6 +313,44 @@ const getPlanFeature = ( plan, key ) => {
313
313
 
314
314
  };
315
315
 
316
+ // Centralized $inc helper for the per-org usage doc. Replaces inline
317
+ // $inc-with-bypass-validation patterns in drawbridge-api + drawbridge-sync.
318
+ //
319
+ // MongoDB's $inc with 0 / NaN / undefined / null writes the value into the
320
+ // field (zeroing or NaN-ing it) instead of no-op'ing — so we filter the
321
+ // $inc object to keep only finite, non-zero values and callers don't have
322
+ // to remember the guard.
323
+ //
324
+ // `session` is forwarded when present so callers inside a transaction get
325
+ // atomic writes; standalone callers omit it.
326
+ const incrementUsageTotals = async ({ controller, usageId, $inc, session }) => {
327
+
328
+ if( ! usageId || ! $inc ) return;
329
+
330
+ const safeInc = Object.fromEntries(
331
+ Object.entries( $inc ).filter( ([ , value ]) => {
332
+
333
+ const number = Number( value );
334
+
335
+ return Number.isFinite( number ) && number !== 0;
336
+
337
+ })
338
+ );
339
+
340
+ if( Object.keys( safeInc ).length === 0 ) return;
341
+
342
+ return controller.update({
343
+ collection : 'usage',
344
+ data : { $inc : safeInc },
345
+ options : {
346
+ bypassDocumentValidation : true,
347
+ ...( session && { session })
348
+ },
349
+ query : { id : usageId }
350
+ });
351
+
352
+ };
353
+
316
354
  const percentage = ( value1, value2, decimals = 1 ) => ( ( ( ( value1 || 0 ) / ( value2 || 0 ) ) * 100 ) || 0 ).toFixed( decimals );
317
355
 
318
356
  const reducers = {
@@ -411,4 +449,4 @@ const currencies = data.map( ( item ) => ({
411
449
 
412
450
  const currency = ( val ) => code( val );
413
451
 
414
- export { bytesToGB, bytesToMB, capitalize, constants, currencies, currency, expiredPaymentMethod, formatCurrency, formatDateString, formatNumber, getPlanFeature, gigabyte, infinite, isInfinite, megabyte, nanoid, percentage, reducers, regex, shareUrls, urlRoot };
452
+ export { bytesToGB, bytesToMB, capitalize, constants, currencies, currency, expiredPaymentMethod, formatCurrency, formatDateString, formatNumber, getPlanFeature, gigabyte, incrementUsageTotals, infinite, isInfinite, megabyte, nanoid, percentage, reducers, regex, shareUrls, urlRoot };
package/dist/index.d.ts CHANGED
@@ -313,6 +313,44 @@ const getPlanFeature = ( plan, key ) => {
313
313
 
314
314
  };
315
315
 
316
+ // Centralized $inc helper for the per-org usage doc. Replaces inline
317
+ // $inc-with-bypass-validation patterns in drawbridge-api + drawbridge-sync.
318
+ //
319
+ // MongoDB's $inc with 0 / NaN / undefined / null writes the value into the
320
+ // field (zeroing or NaN-ing it) instead of no-op'ing — so we filter the
321
+ // $inc object to keep only finite, non-zero values and callers don't have
322
+ // to remember the guard.
323
+ //
324
+ // `session` is forwarded when present so callers inside a transaction get
325
+ // atomic writes; standalone callers omit it.
326
+ const incrementUsageTotals = async ({ controller, usageId, $inc, session }) => {
327
+
328
+ if( ! usageId || ! $inc ) return;
329
+
330
+ const safeInc = Object.fromEntries(
331
+ Object.entries( $inc ).filter( ([ , value ]) => {
332
+
333
+ const number = Number( value );
334
+
335
+ return Number.isFinite( number ) && number !== 0;
336
+
337
+ })
338
+ );
339
+
340
+ if( Object.keys( safeInc ).length === 0 ) return;
341
+
342
+ return controller.update({
343
+ collection : 'usage',
344
+ data : { $inc : safeInc },
345
+ options : {
346
+ bypassDocumentValidation : true,
347
+ ...( session && { session })
348
+ },
349
+ query : { id : usageId }
350
+ });
351
+
352
+ };
353
+
316
354
  const percentage = ( value1, value2, decimals = 1 ) => ( ( ( ( value1 || 0 ) / ( value2 || 0 ) ) * 100 ) || 0 ).toFixed( decimals );
317
355
 
318
356
  const reducers = {
@@ -411,4 +449,4 @@ const currencies = data.map( ( item ) => ({
411
449
 
412
450
  const currency = ( val ) => code( val );
413
451
 
414
- export { bytesToGB, bytesToMB, capitalize, constants, currencies, currency, expiredPaymentMethod, formatCurrency, formatDateString, formatNumber, getPlanFeature, gigabyte, infinite, isInfinite, megabyte, nanoid, percentage, reducers, regex, shareUrls, urlRoot };
452
+ export { bytesToGB, bytesToMB, capitalize, constants, currencies, currency, expiredPaymentMethod, formatCurrency, formatDateString, formatNumber, getPlanFeature, gigabyte, incrementUsageTotals, infinite, isInfinite, megabyte, nanoid, percentage, reducers, regex, shareUrls, urlRoot };
package/dist/index.js CHANGED
@@ -266,6 +266,25 @@ var getPlanFeature = (plan, key) => {
266
266
  message: granted ? feature : error
267
267
  };
268
268
  };
269
+ var incrementUsageTotals = async ({ controller, usageId, $inc, session }) => {
270
+ if (!usageId || !$inc) return;
271
+ const safeInc = Object.fromEntries(
272
+ Object.entries($inc).filter(([, value]) => {
273
+ const number = Number(value);
274
+ return Number.isFinite(number) && number !== 0;
275
+ })
276
+ );
277
+ if (Object.keys(safeInc).length === 0) return;
278
+ return controller.update({
279
+ collection: "usage",
280
+ data: { $inc: safeInc },
281
+ options: {
282
+ bypassDocumentValidation: true,
283
+ ...session && { session }
284
+ },
285
+ query: { id: usageId }
286
+ });
287
+ };
269
288
  var percentage = (value1, value2, decimals = 1) => ((value1 || 0) / (value2 || 0) * 100 || 0).toFixed(decimals);
270
289
  var reducers = {
271
290
  fields: (data2 = [], callback = () => ({})) => data2.reduce(
@@ -356,6 +375,7 @@ export {
356
375
  formatNumber,
357
376
  getPlanFeature,
358
377
  gigabyte,
378
+ incrementUsageTotals,
359
379
  infinite,
360
380
  isInfinite,
361
381
  megabyte,
@@ -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 };