@nehorai/credits 1.7.0 → 2.0.0

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.
Files changed (44) hide show
  1. package/README.md +226 -2
  2. package/dist/adapters/index.cjs +298 -40
  3. package/dist/adapters/index.cjs.map +1 -1
  4. package/dist/adapters/index.d.cts +2 -2
  5. package/dist/adapters/index.d.ts +2 -2
  6. package/dist/adapters/index.js +298 -40
  7. package/dist/adapters/index.js.map +1 -1
  8. package/dist/core/index.cjs +696 -74
  9. package/dist/core/index.cjs.map +1 -1
  10. package/dist/core/index.d.cts +583 -5
  11. package/dist/core/index.d.ts +583 -5
  12. package/dist/core/index.js +648 -74
  13. package/dist/core/index.js.map +1 -1
  14. package/dist/index.cjs +1762 -365
  15. package/dist/index.cjs.map +1 -1
  16. package/dist/index.d.cts +41 -6
  17. package/dist/index.d.ts +41 -6
  18. package/dist/index.js +1706 -365
  19. package/dist/index.js.map +1 -1
  20. package/dist/repository/index.cjs +1399 -183
  21. package/dist/repository/index.cjs.map +1 -1
  22. package/dist/repository/index.d.cts +141 -15
  23. package/dist/repository/index.d.ts +141 -15
  24. package/dist/repository/index.js +1392 -183
  25. package/dist/repository/index.js.map +1 -1
  26. package/dist/sdk/index.cjs +23 -1
  27. package/dist/sdk/index.cjs.map +1 -1
  28. package/dist/sdk/index.d.cts +2 -2
  29. package/dist/sdk/index.d.ts +2 -2
  30. package/dist/sdk/index.js +23 -1
  31. package/dist/sdk/index.js.map +1 -1
  32. package/dist/service/index.cjs +480 -104
  33. package/dist/service/index.cjs.map +1 -1
  34. package/dist/service/index.d.cts +68 -10
  35. package/dist/service/index.d.ts +68 -10
  36. package/dist/service/index.js +480 -104
  37. package/dist/service/index.js.map +1 -1
  38. package/dist/types-BmG5Omzj.d.ts +646 -0
  39. package/dist/types-C8hZMe8a.d.cts +646 -0
  40. package/dist/{types-CjLj3GW5.d.cts → types-DJ8yqaVr.d.cts} +39 -1
  41. package/dist/{types-CjLj3GW5.d.ts → types-DJ8yqaVr.d.ts} +39 -1
  42. package/package.json +1 -1
  43. package/dist/types-DFe5BoJY.d.cts +0 -329
  44. package/dist/types-_bSybQnb.d.ts +0 -329
@@ -259,57 +259,315 @@ function getOperationLabel(operationType) {
259
259
  }
260
260
  initializeConfig();
261
261
 
262
- // src/core/operations.ts
263
- async function commitReservationWithJournal(repository, userId, reservationId) {
262
+ // src/core/errors.ts
263
+ var CreditErrorCode = {
264
+ INSUFFICIENT_CREDITS: "INSUFFICIENT_CREDITS",
265
+ RESERVATION_NOT_FOUND: "RESERVATION_NOT_FOUND",
266
+ RESERVATION_EXPIRED: "RESERVATION_EXPIRED",
267
+ RESERVATION_ALREADY_PROCESSED: "RESERVATION_ALREADY_PROCESSED",
268
+ USER_NOT_FOUND: "USER_NOT_FOUND",
269
+ INVALID_OPERATION_TYPE: "INVALID_OPERATION_TYPE",
270
+ CONFIGURATION_ERROR: "CONFIGURATION_ERROR",
271
+ DATABASE_ERROR: "DATABASE_ERROR",
272
+ /** Caller reused an idempotency key with a different immutable payload. */
273
+ IDEMPOTENCY_CONFLICT: "IDEMPOTENCY_CONFLICT",
274
+ /**
275
+ * Retryable infrastructure failure — serialization/deadlock, lock timeout,
276
+ * connection loss, pool exhaustion. Distinct from `DATABASE_ERROR`, which is
277
+ * a deterministic failure that will fail again identically on retry.
278
+ */
279
+ TRANSIENT_ERROR: "TRANSIENT_ERROR",
280
+ /** The configured repository adapter does not implement the requested V2 method. */
281
+ UNSUPPORTED_OPERATION: "UNSUPPORTED_OPERATION",
282
+ /** Amount was not a finite positive number. */
283
+ INVALID_AMOUNT: "INVALID_AMOUNT",
284
+ /** Idempotency key was supplied but empty or whitespace-only. */
285
+ INVALID_IDEMPOTENCY_KEY: "INVALID_IDEMPOTENCY_KEY",
286
+ /**
287
+ * A persisted reservation holds a status this library does not define, so no
288
+ * transition can reason about it. Quarantined rather than cast; nothing moved.
289
+ */
290
+ CORRUPT_RESERVATION_STATUS: "CORRUPT_RESERVATION_STATUS",
291
+ /**
292
+ * A persisted reservation does not record that its hold was placed
293
+ * atomically, so the credits it claims are not known to be reserved. Moving
294
+ * it would spend another hold's coverage; nothing moved.
295
+ */
296
+ UNBACKED_RESERVATION: "UNBACKED_RESERVATION"
297
+ };
298
+ var CreditError = class _CreditError extends Error {
299
+ code;
300
+ details;
301
+ constructor(message, code, details) {
302
+ super(message);
303
+ this.name = "CreditError";
304
+ this.code = code;
305
+ this.details = details;
306
+ if (Error.captureStackTrace) {
307
+ Error.captureStackTrace(this, _CreditError);
308
+ }
309
+ }
310
+ /**
311
+ * Convert to JSON-serializable object
312
+ */
313
+ toJSON() {
314
+ return {
315
+ name: this.name,
316
+ code: this.code,
317
+ message: this.message,
318
+ ...this.details && { details: this.details }
319
+ };
320
+ }
321
+ };
322
+ function isCreditError(error) {
323
+ return error instanceof CreditError;
324
+ }
325
+ function isInsufficientCreditsError(error) {
326
+ if (isCreditError(error)) {
327
+ return error.code === CreditErrorCode.INSUFFICIENT_CREDITS;
328
+ }
329
+ if (error instanceof Error) {
330
+ return error.message.toLowerCase().includes("insufficient credits");
331
+ }
332
+ return false;
333
+ }
334
+ function createInsufficientCreditsError(required, available) {
335
+ return new CreditError(
336
+ `Insufficient credits: available ${available}, required ${required}`,
337
+ CreditErrorCode.INSUFFICIENT_CREDITS,
338
+ { required, available, shortfall: sumAmounts(required, -available) }
339
+ );
340
+ }
341
+ function createReservationNotFoundError(reservationId) {
342
+ return new CreditError(
343
+ `Reservation ${reservationId} not found`,
344
+ CreditErrorCode.RESERVATION_NOT_FOUND,
345
+ { reservationId }
346
+ );
347
+ }
348
+ function createReservationAlreadyProcessedError(reservationId, status) {
349
+ return new CreditError(
350
+ `Reservation ${reservationId} has already been ${status}`,
351
+ CreditErrorCode.RESERVATION_ALREADY_PROCESSED,
352
+ { reservationId, status }
353
+ );
354
+ }
355
+ function createUnsupportedOperationError(operation, hint) {
356
+ return new CreditError(
357
+ hint ? `Repository does not support ${operation}. ${hint}` : `Repository does not support ${operation}`,
358
+ CreditErrorCode.UNSUPPORTED_OPERATION,
359
+ { operation, ...hint ? { hint } : {} }
360
+ );
361
+ }
362
+
363
+ // src/core/amount.ts
364
+ var CREDIT_AMOUNT_SCALE = 2;
365
+ var CREDIT_AMOUNT_MAX = 999999999999e-2;
366
+ var MAX_CENTS = 999999999999;
367
+ function toCents(value) {
368
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
369
+ const cents = Math.round(value * 100);
370
+ if (!Number.isSafeInteger(cents)) return null;
371
+ return value === cents / 100 ? cents : null;
372
+ }
373
+ function sumAmounts(...values) {
374
+ let cents = 0;
375
+ for (const value of values) {
376
+ const valueCents = toCents(value);
377
+ if (valueCents === null) return floatSum(values);
378
+ cents += valueCents;
379
+ }
380
+ return Number.isSafeInteger(cents) ? cents / 100 : floatSum(values);
381
+ }
382
+ function floatSum(values) {
383
+ let total = 0;
384
+ for (const value of values) total += value;
385
+ return total;
386
+ }
387
+ function isValidCreditAmount(value) {
388
+ if (typeof value !== "number") return false;
389
+ const cents = toCents(value);
390
+ return cents !== null && cents > 0 && cents <= MAX_CENTS;
391
+ }
392
+ function assertValidCreditAmount(value, context) {
393
+ if (isValidCreditAmount(value)) return;
394
+ throw new CreditError(
395
+ creditAmountReason(value),
396
+ CreditErrorCode.INVALID_AMOUNT,
397
+ { amount: value, max: CREDIT_AMOUNT_MAX, scale: CREDIT_AMOUNT_SCALE, ...context }
398
+ );
399
+ }
400
+ function creditAmountReason(value) {
401
+ if (typeof value !== "number") {
402
+ return `Credit amount must be a number (got ${typeof value})`;
403
+ }
404
+ if (!Number.isFinite(value)) {
405
+ return `Credit amount must be finite (got ${String(value)})`;
406
+ }
407
+ if (value <= 0) {
408
+ return `Credit amount must be greater than zero (got ${value})`;
409
+ }
410
+ if (value > CREDIT_AMOUNT_MAX) {
411
+ return `Credit amount ${value} exceeds the maximum of ${CREDIT_AMOUNT_MAX}`;
412
+ }
413
+ return `Credit amount ${value} is not exact to ${CREDIT_AMOUNT_SCALE} decimal places`;
414
+ }
415
+
416
+ // src/repository/types.ts
417
+ function supportsCreditsV2(repository) {
418
+ return typeof repository.reserveCreditsV2 === "function" && typeof repository.commitReservationV2 === "function" && typeof repository.releaseReservationV2 === "function" && typeof repository.expireReservationV2 === "function";
419
+ }
420
+
421
+ // src/repository/flow.ts
422
+ async function reserveThroughRepository(repository, input) {
423
+ const v2 = supportsCreditsV2(repository);
424
+ if (!v2 && input.idempotencyKey !== void 0) {
425
+ throw createUnsupportedOperationError(
426
+ "reserveCredits with an idempotencyKey",
427
+ "This repository does not implement the V2 boundary, so it cannot enforce idempotency keys. Use a V2 repository (check with supportsCreditsV2) or omit the key and accept at-least-once holds."
428
+ );
429
+ }
430
+ assertValidCreditAmount(input.amount, { userId: input.userId });
431
+ if (v2) {
432
+ return repository.reserveCreditsV2(input);
433
+ }
434
+ try {
435
+ const reservation = await repository.reserveCreditsAtomic(
436
+ input.userId,
437
+ input.amount,
438
+ input.operationType,
439
+ input.expiresAt
440
+ );
441
+ return { outcome: "created", reservation };
442
+ } catch (error) {
443
+ if (!isInsufficientCreditsError(error)) throw error;
444
+ const credits = await repository.getUserCredits(input.userId);
445
+ const available = credits ? sumAmounts(credits.balance, credits.bonusCredits, -credits.reserved) : 0;
446
+ return {
447
+ outcome: "insufficient",
448
+ available,
449
+ required: input.amount,
450
+ shortfall: Math.max(sumAmounts(input.amount, -available), 0)
451
+ };
452
+ }
453
+ }
454
+ async function commitThroughRepository(repository, userId, reservationId, options) {
455
+ if (supportsCreditsV2(repository)) {
456
+ return repository.commitReservationV2(userId, reservationId, options);
457
+ }
264
458
  const reservation = await repository.getReservation(userId, reservationId);
265
- if (!reservation) {
266
- throw new Error(`Reservation ${reservationId} not found`);
459
+ if (!reservation) return { outcome: "not_found", reservationId };
460
+ if (reservation.status !== "reserved") {
461
+ return {
462
+ outcome: "already_terminal",
463
+ reservation,
464
+ terminalStatus: reservation.status
465
+ };
267
466
  }
268
467
  await repository.commitReservationAtomic(userId, reservationId);
269
468
  const credits = await repository.getUserCredits(userId);
270
- if (credits) {
271
- await repository.createJournalEntry({
272
- userId,
273
- entryType: "debit",
274
- amount: reservation.amount,
275
- balanceAfter: credits.balance,
276
- source: "operation_commit",
277
- referenceId: reservationId,
278
- referenceType: "reservation",
279
- description: `Committed ${reservation.amount} credits for ${getOperationLabel(reservation.operationType)}`,
280
- metadata: {
281
- operationType: reservation.operationType
282
- }
283
- });
284
- }
469
+ const balanceAfter = credits ? sumAmounts(credits.balance, credits.bonusCredits) : 0;
470
+ const entry = await repository.createJournalEntry({
471
+ userId,
472
+ entryType: "debit",
473
+ amount: reservation.amount,
474
+ balanceAfter,
475
+ source: "operation_commit",
476
+ referenceId: reservationId,
477
+ referenceType: "reservation",
478
+ description: options?.description ?? `Committed ${reservation.amount} credits for ${getOperationLabel(reservation.operationType)}`,
479
+ // Deterministic fields last: they carry the identity of the event, and a
480
+ // caller who happens to send an `operationType` or an `amount` must not
481
+ // relabel what actually moved.
482
+ metadata: {
483
+ ...options?.metadata,
484
+ operationType: reservation.operationType,
485
+ amount: reservation.amount
486
+ }
487
+ });
488
+ return {
489
+ outcome: "committed",
490
+ reservation: { ...reservation, status: "committed" },
491
+ amount: reservation.amount,
492
+ balanceAfter,
493
+ journalEntryId: entry.id
494
+ };
285
495
  }
286
- async function releaseReservationWithJournal(repository, userId, reservationId) {
496
+ async function releaseThroughRepository(repository, userId, reservationId, options) {
497
+ if (supportsCreditsV2(repository)) {
498
+ return repository.releaseReservationV2(userId, reservationId, options);
499
+ }
287
500
  const reservation = await repository.getReservation(userId, reservationId);
501
+ if (!reservation) {
502
+ await repository.releaseReservationAtomic(userId, reservationId);
503
+ return { outcome: "not_found", reservationId };
504
+ }
505
+ if (reservation.status !== "reserved") {
506
+ await repository.releaseReservationAtomic(userId, reservationId).catch(() => void 0);
507
+ return {
508
+ outcome: "already_terminal",
509
+ reservation,
510
+ terminalStatus: reservation.status
511
+ };
512
+ }
288
513
  await repository.releaseReservationAtomic(userId, reservationId);
289
- if (reservation?.status === "reserved") {
290
- const credits = await repository.getUserCredits(userId);
291
- if (credits) {
292
- await repository.createJournalEntry({
293
- userId,
294
- entryType: "credit",
295
- amount: 0,
296
- // No actual credits returned (they were reserved, not spent)
297
- balanceAfter: credits.balance,
298
- source: "operation_release",
299
- referenceId: reservationId,
300
- referenceType: "reservation",
301
- description: `Released ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,
302
- metadata: {
303
- operationType: reservation.operationType,
304
- amount: reservation.amount
305
- }
306
- });
514
+ const credits = await repository.getUserCredits(userId);
515
+ const entry = await repository.createJournalEntry({
516
+ userId,
517
+ entryType: "credit",
518
+ // No credits changed hands — the hold just moved back into "available".
519
+ amount: 0,
520
+ balanceAfter: credits ? sumAmounts(credits.balance, credits.bonusCredits) : 0,
521
+ source: "operation_release",
522
+ referenceId: reservationId,
523
+ referenceType: "reservation",
524
+ description: options?.description ?? `Released ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,
525
+ metadata: {
526
+ ...options?.metadata,
527
+ operationType: reservation.operationType,
528
+ amount: reservation.amount
307
529
  }
530
+ });
531
+ return {
532
+ outcome: "released",
533
+ reservation: { ...reservation, status: "released" },
534
+ amount: reservation.amount,
535
+ journalEntryId: entry.id
536
+ };
537
+ }
538
+
539
+ // src/core/operations.ts
540
+ async function commitReservationWithJournal(repository, userId, reservationId) {
541
+ const outcome = await commitThroughRepository(repository, userId, reservationId);
542
+ if (outcome.outcome === "not_found") {
543
+ throw createReservationNotFoundError(reservationId);
544
+ }
545
+ if (outcome.outcome === "already_terminal" && outcome.terminalStatus !== "committed") {
546
+ throw createReservationAlreadyProcessedError(reservationId, outcome.terminalStatus);
308
547
  }
309
548
  }
310
- async function reserveCreditsForOperation(repository, userId, amount, operationType, expiryMs = 5 * 60 * 1e3) {
549
+ async function releaseReservationWithJournal(repository, userId, reservationId) {
550
+ await releaseThroughRepository(repository, userId, reservationId);
551
+ }
552
+ async function reserveCreditsForOperation(repository, userId, amount, operationType, expiryMs = 5 * 60 * 1e3, idempotencyKey) {
311
553
  const expiresAt = new Date(Date.now() + expiryMs);
312
- return repository.reserveCreditsAtomic(userId, amount, operationType, expiresAt);
554
+ const outcome = await reserveThroughRepository(repository, {
555
+ userId,
556
+ amount,
557
+ operationType,
558
+ expiresAt,
559
+ idempotencyKey
560
+ });
561
+ if (outcome.outcome === "created" || outcome.outcome === "replayed") {
562
+ return outcome.reservation;
563
+ }
564
+ if (outcome.outcome === "insufficient") {
565
+ throw createInsufficientCreditsError(outcome.required, outcome.available);
566
+ }
567
+ throw createReservationAlreadyProcessedError(
568
+ outcome.existing.id,
569
+ outcome.existing.status
570
+ );
313
571
  }
314
572
 
315
573
  // src/adapters/generic.ts