@nehorai/credits 1.2.0 → 1.3.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 (139) hide show
  1. package/LICENSE +21 -0
  2. package/dist/adapters/index.cjs +463 -0
  3. package/dist/adapters/index.cjs.map +1 -0
  4. package/dist/adapters/index.d.cts +66 -0
  5. package/dist/adapters/index.d.ts +66 -3
  6. package/dist/adapters/index.js +435 -1
  7. package/dist/adapters/index.js.map +1 -1
  8. package/dist/auth/index.cjs +96 -0
  9. package/dist/auth/index.cjs.map +1 -0
  10. package/dist/auth/{api-key.d.ts → index.d.cts} +9 -6
  11. package/dist/auth/index.d.ts +37 -5
  12. package/dist/auth/index.js +65 -7
  13. package/dist/auth/index.js.map +1 -1
  14. package/dist/core/index.cjs +522 -0
  15. package/dist/core/index.cjs.map +1 -0
  16. package/dist/core/index.d.cts +119 -0
  17. package/dist/core/index.d.ts +115 -25
  18. package/dist/core/index.js +475 -27
  19. package/dist/core/index.js.map +1 -1
  20. package/dist/{core/deferred.d.ts → deferred-C7rrRfkm.d.cts} +7 -6
  21. package/dist/{core/deferred.js → deferred-C7rrRfkm.d.ts} +23 -29
  22. package/dist/index.cjs +2506 -0
  23. package/dist/index.cjs.map +1 -0
  24. package/dist/index.d.cts +437 -0
  25. package/dist/index.d.ts +429 -50
  26. package/dist/index.js +2399 -63
  27. package/dist/index.js.map +1 -1
  28. package/dist/repository/index.cjs +816 -0
  29. package/dist/repository/index.cjs.map +1 -0
  30. package/dist/repository/{memory/index.d.ts → index.d.cts} +35 -5
  31. package/dist/repository/index.d.ts +97 -7
  32. package/dist/repository/index.js +783 -10
  33. package/dist/repository/index.js.map +1 -1
  34. package/dist/sdk/index.cjs +608 -0
  35. package/dist/sdk/index.cjs.map +1 -0
  36. package/dist/sdk/index.d.cts +495 -0
  37. package/dist/sdk/index.d.ts +491 -9
  38. package/dist/sdk/index.js +568 -12
  39. package/dist/sdk/index.js.map +1 -1
  40. package/dist/service/index.cjs +670 -0
  41. package/dist/service/index.cjs.map +1 -0
  42. package/dist/service/{credits-service.d.ts → index.d.cts} +9 -7
  43. package/dist/service/index.d.ts +141 -3
  44. package/dist/service/index.js +641 -1
  45. package/dist/service/index.js.map +1 -1
  46. package/dist/{core/types.d.ts → types-BBxIWHK2.d.cts} +25 -24
  47. package/dist/types-BBxIWHK2.d.ts +277 -0
  48. package/dist/types-D1vdeBcA.d.cts +305 -0
  49. package/dist/{auth/types.d.ts → types-OZU3I5OM.d.cts} +5 -4
  50. package/dist/types-OZU3I5OM.d.ts +32 -0
  51. package/dist/{repository/types.d.ts → types-aJsyv8df.d.ts} +35 -13
  52. package/package.json +21 -19
  53. package/dist/adapters/generic.d.ts +0 -18
  54. package/dist/adapters/generic.d.ts.map +0 -1
  55. package/dist/adapters/generic.js +0 -151
  56. package/dist/adapters/generic.js.map +0 -1
  57. package/dist/adapters/index.d.ts.map +0 -1
  58. package/dist/adapters/types.d.ts +0 -45
  59. package/dist/adapters/types.d.ts.map +0 -1
  60. package/dist/adapters/types.js +0 -8
  61. package/dist/adapters/types.js.map +0 -1
  62. package/dist/auth/api-key.d.ts.map +0 -1
  63. package/dist/auth/api-key.js +0 -94
  64. package/dist/auth/api-key.js.map +0 -1
  65. package/dist/auth/index.d.ts.map +0 -1
  66. package/dist/auth/types.d.ts.map +0 -1
  67. package/dist/auth/types.js +0 -2
  68. package/dist/auth/types.js.map +0 -1
  69. package/dist/config/costs.d.ts +0 -56
  70. package/dist/config/costs.d.ts.map +0 -1
  71. package/dist/config/costs.js +0 -71
  72. package/dist/config/costs.js.map +0 -1
  73. package/dist/config/index.d.ts +0 -184
  74. package/dist/config/index.d.ts.map +0 -1
  75. package/dist/config/index.js +0 -342
  76. package/dist/config/index.js.map +0 -1
  77. package/dist/config/provider.d.ts +0 -12
  78. package/dist/config/provider.d.ts.map +0 -1
  79. package/dist/config/provider.js +0 -14
  80. package/dist/config/provider.js.map +0 -1
  81. package/dist/core/deferred.d.ts.map +0 -1
  82. package/dist/core/deferred.js.map +0 -1
  83. package/dist/core/errors.d.ts +0 -78
  84. package/dist/core/errors.d.ts.map +0 -1
  85. package/dist/core/errors.js +0 -110
  86. package/dist/core/errors.js.map +0 -1
  87. package/dist/core/index.d.ts.map +0 -1
  88. package/dist/core/operations.d.ts +0 -36
  89. package/dist/core/operations.d.ts.map +0 -1
  90. package/dist/core/operations.js +0 -88
  91. package/dist/core/operations.js.map +0 -1
  92. package/dist/core/types.d.ts.map +0 -1
  93. package/dist/core/types.js +0 -82
  94. package/dist/core/types.js.map +0 -1
  95. package/dist/index.d.ts.map +0 -1
  96. package/dist/notifications/index.d.ts +0 -76
  97. package/dist/notifications/index.d.ts.map +0 -1
  98. package/dist/notifications/index.js +0 -174
  99. package/dist/notifications/index.js.map +0 -1
  100. package/dist/repository/index.d.ts.map +0 -1
  101. package/dist/repository/memory/index.d.ts.map +0 -1
  102. package/dist/repository/memory/index.js +0 -518
  103. package/dist/repository/memory/index.js.map +0 -1
  104. package/dist/repository/types.d.ts.map +0 -1
  105. package/dist/repository/types.js +0 -39
  106. package/dist/repository/types.js.map +0 -1
  107. package/dist/repository/utils.d.ts +0 -22
  108. package/dist/repository/utils.d.ts.map +0 -1
  109. package/dist/repository/utils.js +0 -40
  110. package/dist/repository/utils.js.map +0 -1
  111. package/dist/sdk/admin-client.d.ts +0 -146
  112. package/dist/sdk/admin-client.d.ts.map +0 -1
  113. package/dist/sdk/admin-client.js +0 -196
  114. package/dist/sdk/admin-client.js.map +0 -1
  115. package/dist/sdk/client.d.ts +0 -144
  116. package/dist/sdk/client.d.ts.map +0 -1
  117. package/dist/sdk/client.js +0 -247
  118. package/dist/sdk/client.js.map +0 -1
  119. package/dist/sdk/errors.d.ts +0 -91
  120. package/dist/sdk/errors.d.ts.map +0 -1
  121. package/dist/sdk/errors.js +0 -185
  122. package/dist/sdk/errors.js.map +0 -1
  123. package/dist/sdk/index.d.ts.map +0 -1
  124. package/dist/sdk/types.d.ts +0 -110
  125. package/dist/sdk/types.d.ts.map +0 -1
  126. package/dist/sdk/types.js +0 -20
  127. package/dist/sdk/types.js.map +0 -1
  128. package/dist/service/credits-service.d.ts.map +0 -1
  129. package/dist/service/credits-service.js +0 -368
  130. package/dist/service/credits-service.js.map +0 -1
  131. package/dist/service/index.d.ts.map +0 -1
  132. package/dist/utils/error-utils.d.ts +0 -48
  133. package/dist/utils/error-utils.d.ts.map +0 -1
  134. package/dist/utils/error-utils.js +0 -57
  135. package/dist/utils/error-utils.js.map +0 -1
  136. package/dist/utils/index.d.ts +0 -54
  137. package/dist/utils/index.d.ts.map +0 -1
  138. package/dist/utils/index.js +0 -72
  139. package/dist/utils/index.js.map +0 -1
@@ -1,28 +1,476 @@
1
- /**
2
- * Credits system core - framework agnostic
3
- *
4
- * This module provides the core credits functionality without any
5
- * framework-specific dependencies (no Next.js, no React, no Firebase types).
6
- *
7
- * Use this module when:
8
- * - Building non-Next.js applications
9
- * - Creating the TypeScript SDK
10
- * - Copy-pasting the credits system to other projects
11
- *
12
- * @example
13
- * ```typescript
14
- * import {
15
- * calculateAvailableCredits,
16
- * CreditError,
17
- * CreditErrorCode,
18
- * genericDeferred,
19
- * } from '@nehorai/credits/core';
20
- * ```
21
- */
22
- // ==================== Type Utilities ====================
23
- export { calculateAvailableCredits, toPortableTimestamp, toDate, } from "./types.js";
24
- export { CreditError, CreditErrorCode, isCreditError, isInsufficientCreditsError, createInsufficientCreditsError, createReservationNotFoundError, createReservationExpiredError, createReservationAlreadyProcessedError, createUserNotFoundError, createInvalidOperationTypeError, } from "./errors.js";
25
- export { genericDeferred, synchronousDeferred, noopDeferred, createDeferredExecutor, } from "./deferred.js";
26
- // ==================== Operations ====================
27
- export { commitReservationWithJournal, releaseReservationWithJournal, reserveCreditsForOperation, } from "./operations.js";
1
+ // src/core/types.ts
2
+ function calculateAvailableCredits(balance, bonusCredits, reserved) {
3
+ return balance + bonusCredits - reserved;
4
+ }
5
+ function toPortableTimestamp(value) {
6
+ if (!value) {
7
+ return (/* @__PURE__ */ new Date()).toISOString();
8
+ }
9
+ if (typeof value === "string") {
10
+ return value;
11
+ }
12
+ if (value instanceof Date) {
13
+ return value.toISOString();
14
+ }
15
+ if (typeof value === "object" && value !== null && "toDate" in value && typeof value.toDate === "function") {
16
+ return value.toDate().toISOString();
17
+ }
18
+ return (/* @__PURE__ */ new Date()).toISOString();
19
+ }
20
+ function toDate(value) {
21
+ if (value instanceof Date) {
22
+ return value;
23
+ }
24
+ if (typeof value === "string") {
25
+ return new Date(value);
26
+ }
27
+ if (typeof value === "object" && value !== null && "toDate" in value && typeof value.toDate === "function") {
28
+ return value.toDate();
29
+ }
30
+ return /* @__PURE__ */ new Date();
31
+ }
32
+
33
+ // src/core/errors.ts
34
+ var CreditErrorCode = {
35
+ INSUFFICIENT_CREDITS: "INSUFFICIENT_CREDITS",
36
+ RESERVATION_NOT_FOUND: "RESERVATION_NOT_FOUND",
37
+ RESERVATION_EXPIRED: "RESERVATION_EXPIRED",
38
+ RESERVATION_ALREADY_PROCESSED: "RESERVATION_ALREADY_PROCESSED",
39
+ USER_NOT_FOUND: "USER_NOT_FOUND",
40
+ INVALID_OPERATION_TYPE: "INVALID_OPERATION_TYPE",
41
+ CONFIGURATION_ERROR: "CONFIGURATION_ERROR",
42
+ DATABASE_ERROR: "DATABASE_ERROR"
43
+ };
44
+ var CreditError = class _CreditError extends Error {
45
+ code;
46
+ details;
47
+ constructor(message, code, details) {
48
+ super(message);
49
+ this.name = "CreditError";
50
+ this.code = code;
51
+ this.details = details;
52
+ if (Error.captureStackTrace) {
53
+ Error.captureStackTrace(this, _CreditError);
54
+ }
55
+ }
56
+ /**
57
+ * Convert to JSON-serializable object
58
+ */
59
+ toJSON() {
60
+ return {
61
+ name: this.name,
62
+ code: this.code,
63
+ message: this.message,
64
+ ...this.details && { details: this.details }
65
+ };
66
+ }
67
+ };
68
+ function isCreditError(error) {
69
+ return error instanceof CreditError;
70
+ }
71
+ function isInsufficientCreditsError(error) {
72
+ if (isCreditError(error)) {
73
+ return error.code === CreditErrorCode.INSUFFICIENT_CREDITS;
74
+ }
75
+ if (error instanceof Error) {
76
+ return error.message.toLowerCase().includes("insufficient credits");
77
+ }
78
+ return false;
79
+ }
80
+ function createInsufficientCreditsError(required, available) {
81
+ return new CreditError(
82
+ `Insufficient credits: available ${available}, required ${required}`,
83
+ CreditErrorCode.INSUFFICIENT_CREDITS,
84
+ { required, available, shortfall: required - available }
85
+ );
86
+ }
87
+ function createReservationNotFoundError(reservationId) {
88
+ return new CreditError(
89
+ `Reservation ${reservationId} not found`,
90
+ CreditErrorCode.RESERVATION_NOT_FOUND,
91
+ { reservationId }
92
+ );
93
+ }
94
+ function createReservationExpiredError(reservationId) {
95
+ return new CreditError(
96
+ `Reservation ${reservationId} has expired`,
97
+ CreditErrorCode.RESERVATION_EXPIRED,
98
+ { reservationId }
99
+ );
100
+ }
101
+ function createReservationAlreadyProcessedError(reservationId, status) {
102
+ return new CreditError(
103
+ `Reservation ${reservationId} has already been ${status}`,
104
+ CreditErrorCode.RESERVATION_ALREADY_PROCESSED,
105
+ { reservationId, status }
106
+ );
107
+ }
108
+ function createUserNotFoundError(userId) {
109
+ return new CreditError(
110
+ `User ${userId} not found`,
111
+ CreditErrorCode.USER_NOT_FOUND,
112
+ { userId }
113
+ );
114
+ }
115
+ function createInvalidOperationTypeError(operationType, validTypes) {
116
+ return new CreditError(
117
+ `Invalid operation type: ${operationType}. Valid types: ${validTypes.join(", ")}`,
118
+ CreditErrorCode.INVALID_OPERATION_TYPE,
119
+ { operationType, validTypes }
120
+ );
121
+ }
122
+
123
+ // src/core/deferred.ts
124
+ var genericDeferred = {
125
+ defer(fn) {
126
+ const scheduler = typeof setImmediate !== "undefined" ? setImmediate : setTimeout;
127
+ scheduler(() => {
128
+ fn().catch((error) => {
129
+ console.error("[Credits] Deferred task error:", error);
130
+ });
131
+ });
132
+ }
133
+ };
134
+ var synchronousDeferred = {
135
+ defer(fn) {
136
+ fn().catch((error) => {
137
+ console.error("[Credits] Deferred task error:", error);
138
+ });
139
+ }
140
+ };
141
+ function createDeferredExecutor(schedule) {
142
+ return {
143
+ defer: schedule
144
+ };
145
+ }
146
+ var noopDeferred = {
147
+ defer(_fn) {
148
+ }
149
+ };
150
+
151
+ // src/config/index.ts
152
+ import { z } from "zod";
153
+
154
+ // src/config/provider.ts
155
+ var configProvider = null;
156
+ function getConfigProvider() {
157
+ return configProvider;
158
+ }
159
+
160
+ // src/config/index.ts
161
+ var tierConfigSchema = z.object({
162
+ tier: z.enum(["free", "basic", "premium", "unlimited"]),
163
+ monthlyCredits: z.number().min(0),
164
+ priceUsd: z.number().min(0),
165
+ features: z.array(z.string())
166
+ });
167
+ var creditSystemConfigSchema = z.object({
168
+ /**
169
+ * Operation costs in credits
170
+ * Keys are operation type names (any non-empty string)
171
+ * Values are positive numbers representing credit cost
172
+ */
173
+ operationCosts: z.record(
174
+ z.string().min(1),
175
+ z.number().positive()
176
+ ),
177
+ /**
178
+ * Display labels for operation types (English canonical labels).
179
+ * Falls back to auto-generating from snake_case keys if not provided.
180
+ */
181
+ operationLabels: z.record(
182
+ z.string().min(1),
183
+ z.string().min(1)
184
+ ).optional().default({}),
185
+ /**
186
+ * Tier configurations
187
+ */
188
+ tierConfigs: z.record(
189
+ z.enum(["free", "basic", "premium", "unlimited"]),
190
+ tierConfigSchema
191
+ ),
192
+ /**
193
+ * Reservation expiry time in milliseconds
194
+ */
195
+ reservationExpiryMs: z.number().positive().default(5 * 60 * 1e3),
196
+ /**
197
+ * Default credits for new users (free tier)
198
+ */
199
+ defaultFreeCredits: z.number().positive().default(25),
200
+ /**
201
+ * Grace period in days after subscription expires before downgrade
202
+ */
203
+ subscriptionGracePeriodDays: z.number().min(0).default(3),
204
+ /**
205
+ * Low balance notification threshold
206
+ */
207
+ lowBalanceThreshold: z.number().min(0).default(10),
208
+ /**
209
+ * Cooldown in hours between low balance notifications
210
+ */
211
+ lowBalanceNotificationCooldownHours: z.number().positive().default(24),
212
+ /**
213
+ * Feature flags for optional features
214
+ */
215
+ features: z.object({
216
+ journalEntries: z.boolean().default(true),
217
+ notifications: z.boolean().default(true),
218
+ subscriptionExpiry: z.boolean().default(true),
219
+ usageHistory: z.boolean().default(true)
220
+ }).default({
221
+ journalEntries: true,
222
+ notifications: true,
223
+ subscriptionExpiry: true,
224
+ usageHistory: true
225
+ })
226
+ });
227
+ var DEFAULT_CONFIG = {
228
+ operationCosts: {
229
+ story_generation: 5,
230
+ conversation: 2,
231
+ image_generation: 10,
232
+ template_generation: 10
233
+ },
234
+ operationLabels: {
235
+ story_generation: "Story generation",
236
+ conversation: "Conversation",
237
+ image_generation: "Image generation",
238
+ template_generation: "Template generation"
239
+ },
240
+ tierConfigs: {
241
+ free: {
242
+ tier: "free",
243
+ monthlyCredits: 25,
244
+ priceUsd: 0,
245
+ features: [
246
+ "25 credits per month",
247
+ "Basic story generation",
248
+ "Standard image quality"
249
+ ]
250
+ },
251
+ basic: {
252
+ tier: "basic",
253
+ monthlyCredits: 200,
254
+ priceUsd: 9.99,
255
+ features: [
256
+ "200 credits per month",
257
+ "All story features",
258
+ "High quality images",
259
+ "Priority support"
260
+ ]
261
+ },
262
+ premium: {
263
+ tier: "premium",
264
+ monthlyCredits: 500,
265
+ priceUsd: 19.99,
266
+ features: [
267
+ "500 credits per month",
268
+ "All features",
269
+ "Highest quality images",
270
+ "Early access to new features",
271
+ "Priority support"
272
+ ]
273
+ },
274
+ unlimited: {
275
+ tier: "unlimited",
276
+ monthlyCredits: 0,
277
+ // 0 = unlimited
278
+ priceUsd: 49.99,
279
+ features: [
280
+ "Unlimited credits",
281
+ "All features",
282
+ "Highest quality images",
283
+ "Early access to new features",
284
+ "Dedicated support"
285
+ ]
286
+ }
287
+ },
288
+ reservationExpiryMs: 5 * 60 * 1e3,
289
+ // 5 minutes
290
+ defaultFreeCredits: 25,
291
+ subscriptionGracePeriodDays: 3,
292
+ lowBalanceThreshold: 10,
293
+ lowBalanceNotificationCooldownHours: 24,
294
+ features: {
295
+ journalEntries: true,
296
+ notifications: true,
297
+ subscriptionExpiry: true,
298
+ usageHistory: true
299
+ }
300
+ };
301
+ var currentConfig = DEFAULT_CONFIG;
302
+ function loadConfigFromEnv() {
303
+ const envConfig = {};
304
+ const operationCostsEnv = process.env.CREDITS_OPERATION_COSTS;
305
+ if (operationCostsEnv) {
306
+ try {
307
+ const parsed = JSON.parse(operationCostsEnv);
308
+ if (typeof parsed === "object" && parsed !== null) {
309
+ envConfig.operationCosts = {
310
+ ...DEFAULT_CONFIG.operationCosts,
311
+ ...parsed
312
+ };
313
+ }
314
+ } catch {
315
+ console.warn("[Credits Config] Failed to parse CREDITS_OPERATION_COSTS env var as JSON");
316
+ }
317
+ }
318
+ const reservationExpiry = process.env.CREDITS_RESERVATION_EXPIRY_MS;
319
+ if (reservationExpiry) {
320
+ envConfig.reservationExpiryMs = parseInt(reservationExpiry, 10);
321
+ }
322
+ const defaultCredits = process.env.CREDITS_DEFAULT_FREE;
323
+ if (defaultCredits) {
324
+ envConfig.defaultFreeCredits = parseInt(defaultCredits, 10);
325
+ }
326
+ const gracePeriod = process.env.CREDITS_GRACE_PERIOD_DAYS;
327
+ if (gracePeriod) {
328
+ envConfig.subscriptionGracePeriodDays = parseInt(gracePeriod, 10);
329
+ }
330
+ const lowBalanceThreshold = process.env.CREDITS_LOW_BALANCE_THRESHOLD;
331
+ if (lowBalanceThreshold) {
332
+ envConfig.lowBalanceThreshold = parseInt(lowBalanceThreshold, 10);
333
+ }
334
+ const featuresEnv = process.env.CREDITS_FEATURES;
335
+ if (featuresEnv) {
336
+ try {
337
+ const features = JSON.parse(featuresEnv);
338
+ envConfig.features = {
339
+ ...DEFAULT_CONFIG.features,
340
+ ...features
341
+ };
342
+ } catch {
343
+ console.warn("[Credits Config] Failed to parse CREDITS_FEATURES env var");
344
+ }
345
+ }
346
+ return envConfig;
347
+ }
348
+ function initializeConfig(overrides) {
349
+ const envConfig = loadConfigFromEnv();
350
+ const mergedConfig = {
351
+ ...DEFAULT_CONFIG,
352
+ ...envConfig,
353
+ ...overrides,
354
+ operationCosts: {
355
+ ...DEFAULT_CONFIG.operationCosts,
356
+ ...envConfig.operationCosts,
357
+ ...overrides?.operationCosts
358
+ },
359
+ operationLabels: {
360
+ ...DEFAULT_CONFIG.operationLabels,
361
+ ...envConfig.operationLabels,
362
+ ...overrides?.operationLabels
363
+ },
364
+ tierConfigs: {
365
+ ...DEFAULT_CONFIG.tierConfigs,
366
+ ...envConfig.tierConfigs,
367
+ ...overrides?.tierConfigs
368
+ },
369
+ features: {
370
+ ...DEFAULT_CONFIG.features,
371
+ ...envConfig.features,
372
+ ...overrides?.features
373
+ }
374
+ };
375
+ const result = creditSystemConfigSchema.safeParse(mergedConfig);
376
+ if (!result.success) {
377
+ console.error("[Credits Config] Invalid configuration:", result.error.issues);
378
+ throw new Error("Invalid credit system configuration");
379
+ }
380
+ currentConfig = result.data;
381
+ return currentConfig;
382
+ }
383
+ function getConfig() {
384
+ const provider = getConfigProvider();
385
+ if (provider) {
386
+ return provider.getConfig();
387
+ }
388
+ return currentConfig;
389
+ }
390
+ function snakeCaseToTitleCase(str) {
391
+ return str.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
392
+ }
393
+ function getOperationLabel(operationType) {
394
+ const labels = getConfig().operationLabels;
395
+ if (labels && operationType in labels) {
396
+ return labels[operationType];
397
+ }
398
+ return snakeCaseToTitleCase(operationType);
399
+ }
400
+ initializeConfig();
401
+
402
+ // src/core/operations.ts
403
+ async function commitReservationWithJournal(repository, userId, reservationId) {
404
+ const reservation = await repository.getReservation(userId, reservationId);
405
+ if (!reservation) {
406
+ throw new Error(`Reservation ${reservationId} not found`);
407
+ }
408
+ await repository.commitReservationAtomic(userId, reservationId);
409
+ const credits = await repository.getUserCredits(userId);
410
+ if (credits) {
411
+ await repository.createJournalEntry({
412
+ userId,
413
+ entryType: "debit",
414
+ amount: reservation.amount,
415
+ balanceAfter: credits.balance,
416
+ source: "operation_commit",
417
+ referenceId: reservationId,
418
+ referenceType: "reservation",
419
+ description: `Committed ${reservation.amount} credits for ${getOperationLabel(reservation.operationType)}`,
420
+ metadata: {
421
+ operationType: reservation.operationType
422
+ }
423
+ });
424
+ }
425
+ }
426
+ async function releaseReservationWithJournal(repository, userId, reservationId) {
427
+ const reservation = await repository.getReservation(userId, reservationId);
428
+ await repository.releaseReservationAtomic(userId, reservationId);
429
+ if (reservation?.status === "reserved") {
430
+ const credits = await repository.getUserCredits(userId);
431
+ if (credits) {
432
+ await repository.createJournalEntry({
433
+ userId,
434
+ entryType: "credit",
435
+ amount: 0,
436
+ // No actual credits returned (they were reserved, not spent)
437
+ balanceAfter: credits.balance,
438
+ source: "operation_release",
439
+ referenceId: reservationId,
440
+ referenceType: "reservation",
441
+ description: `Released ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,
442
+ metadata: {
443
+ operationType: reservation.operationType,
444
+ amount: reservation.amount
445
+ }
446
+ });
447
+ }
448
+ }
449
+ }
450
+ async function reserveCreditsForOperation(repository, userId, amount, operationType, expiryMs = 5 * 60 * 1e3) {
451
+ const expiresAt = new Date(Date.now() + expiryMs);
452
+ return repository.reserveCreditsAtomic(userId, amount, operationType, expiresAt);
453
+ }
454
+ export {
455
+ CreditError,
456
+ CreditErrorCode,
457
+ calculateAvailableCredits,
458
+ commitReservationWithJournal,
459
+ createDeferredExecutor,
460
+ createInsufficientCreditsError,
461
+ createInvalidOperationTypeError,
462
+ createReservationAlreadyProcessedError,
463
+ createReservationExpiredError,
464
+ createReservationNotFoundError,
465
+ createUserNotFoundError,
466
+ genericDeferred,
467
+ isCreditError,
468
+ isInsufficientCreditsError,
469
+ noopDeferred,
470
+ releaseReservationWithJournal,
471
+ reserveCreditsForOperation,
472
+ synchronousDeferred,
473
+ toDate,
474
+ toPortableTimestamp
475
+ };
28
476
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/core/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AA0BH,2DAA2D;AAC3D,OAAO,EACL,yBAAyB,EACzB,mBAAmB,EACnB,MAAM,GACP,MAAM,YAAY,CAAC;AAKpB,OAAO,EACL,WAAW,EACX,eAAe,EACf,aAAa,EACb,0BAA0B,EAC1B,8BAA8B,EAC9B,8BAA8B,EAC9B,6BAA6B,EAC7B,sCAAsC,EACtC,uBAAuB,EACvB,+BAA+B,GAChC,MAAM,aAAa,CAAC;AAKrB,OAAO,EACL,eAAe,EACf,mBAAmB,EACnB,YAAY,EACZ,sBAAsB,GACvB,MAAM,eAAe,CAAC;AAEvB,uDAAuD;AACvD,OAAO,EACL,4BAA4B,EAC5B,6BAA6B,EAC7B,0BAA0B,GAC3B,MAAM,iBAAiB,CAAC"}
1
+ {"version":3,"sources":["../../src/core/types.ts","../../src/core/errors.ts","../../src/core/deferred.ts","../../src/config/index.ts","../../src/config/provider.ts","../../src/core/operations.ts"],"sourcesContent":["/**\n * Portable credits types - framework and database agnostic\n *\n * These types use standard JavaScript types (string, Date) instead of\n * Firebase-specific types (Timestamp). This makes the credits system\n * portable to other environments without Firebase dependencies.\n *\n * Note: Firestore Timestamp is handled by the credits-firestore adapter.\n */\n\n// ==================== Utility Functions ====================\n\n/**\n * Calculate available credits from balance, bonus, and reserved amounts.\n *\n * Available = balance + bonusCredits - reserved\n *\n * @param balance - Regular monthly credits\n * @param bonusCredits - Purchased/admin credits\n * @param reserved - Credits locked for in-flight operations\n * @returns Available credits for new operations\n */\nexport function calculateAvailableCredits(\n balance: number,\n bonusCredits: number,\n reserved: number\n): number {\n return balance + bonusCredits - reserved;\n}\n\n/**\n * Convert various timestamp formats to ISO string.\n *\n * Handles:\n * - Date objects\n * - ISO string (returned as-is)\n * - Timestamp-like objects with toDate() method (Firebase)\n * - undefined/null (returns current time)\n *\n * @param value - Value to convert\n * @returns ISO 8601 string\n */\nexport function toPortableTimestamp(value: unknown): string {\n if (!value) {\n return new Date().toISOString();\n }\n\n if (typeof value === \"string\") {\n return value;\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"toDate\" in value &&\n typeof (value as { toDate: () => Date }).toDate === \"function\"\n ) {\n return (value as { toDate: () => Date }).toDate().toISOString();\n }\n\n return new Date().toISOString();\n}\n\n/**\n * Convert various timestamp formats to Date object.\n *\n * Handles:\n * - Date objects (returned as-is)\n * - ISO string\n * - Timestamp-like objects with toDate() method (Firebase)\n * - Invalid values (returns current date)\n *\n * @param value - Value to convert\n * @returns Date object\n */\nexport function toDate(value: unknown): Date {\n if (value instanceof Date) {\n return value;\n }\n\n if (typeof value === \"string\") {\n return new Date(value);\n }\n\n if (\n typeof value === \"object\" &&\n value !== null &&\n \"toDate\" in value &&\n typeof (value as { toDate: () => Date }).toDate === \"function\"\n ) {\n return (value as { toDate: () => Date }).toDate();\n }\n\n return new Date();\n}\n\n// ==================== Subscription Types ====================\n\n/**\n * Subscription tiers for the credits system\n */\nexport type SubscriptionTier = \"free\" | \"basic\" | \"premium\" | \"unlimited\";\n\n// ==================== Operation Types ====================\n\n/**\n * Operation types for cost tracking (provider-agnostic)\n *\n * Dynamic string type - any operation configured in the system is valid.\n */\nexport type CreditOperationType = string;\n\n/**\n * AI providers\n */\nexport type AIProviderType = \"gemini\";\n\n/**\n * Resource type for usage logging\n */\nexport type ResourceType = string;\n\n// ==================== User Credits ====================\n\n/**\n * Portable user credits balance\n *\n * Uses ISO string timestamps instead of Firebase Timestamp.\n * This type is safe for JSON serialization and works across frameworks.\n */\nexport interface PortableUserCredits {\n userId: string;\n /** Current available balance (monthly credits, reset each month) */\n balance: number;\n /** Bonus credits from purchases/admin (never reset, persist until used) */\n bonusCredits: number;\n /** Credits currently reserved for in-flight operations */\n reserved: number;\n /** User's subscription tier */\n tier: SubscriptionTier;\n /** Monthly credit limit based on tier (0 = unlimited) */\n monthlyLimit: number;\n /** Credits used this month (resets monthly) */\n monthlyUsed: number;\n /** When monthly credits reset (start of next month) - ISO 8601 */\n monthlyResetAt: string;\n /** Subscription expiry (null/undefined for free tier) - ISO 8601 or null */\n subscriptionExpiresAt?: string | null;\n /** Creation timestamp - ISO 8601 */\n createdAt: string;\n /** Last update timestamp - ISO 8601 */\n updatedAt: string;\n}\n\n// ==================== Reservation Types ====================\n\n/**\n * Credit reservation status for two-phase commit\n */\nexport type ReservationStatus = \"reserved\" | \"committed\" | \"released\" | \"expired\";\n\n/**\n * Portable credit reservation\n *\n * Used for two-phase commit to prevent double-spending.\n */\nexport interface PortableReservation {\n id: string;\n userId: string;\n /** Amount of credits reserved */\n amount: number;\n /** Operation type for tracking */\n operationType: CreditOperationType;\n /** Current status of reservation */\n status: ReservationStatus;\n /** When reservation was created - ISO 8601 */\n createdAt: string;\n /** When reservation expires (for cleanup) - ISO 8601 */\n expiresAt: string;\n /** When reservation was committed/released - ISO 8601 or undefined */\n completedAt?: string;\n}\n\n// ==================== Result Types ====================\n\n/**\n * Result of a credit check operation\n */\nexport interface CreditCheckResult {\n /** Whether user has sufficient credits */\n hasCredits: boolean;\n /** Current balance (balance + bonusCredits) */\n balance: number;\n /** Required credits for operation */\n required: number;\n /** Shortfall if insufficient */\n shortfall: number;\n}\n\n/**\n * Result of monthly reset operation\n */\nexport interface MonthlyResetResult {\n /** Whether the reset was performed */\n wasReset: boolean;\n /** The user credits after the operation */\n credits: PortableUserCredits;\n}\n\n/**\n * Result of subscription expiry check\n */\nexport interface SubscriptionExpiryResult {\n /** Whether the subscription was downgraded */\n wasDowngraded: boolean;\n /** Whether user is in grace period */\n inGracePeriod: boolean;\n /** Days remaining in grace period (0 if not in grace) */\n graceDaysRemaining: number;\n /** The user credits after the operation */\n credits: PortableUserCredits;\n}\n\n// ==================== Transaction Types ====================\n\n/**\n * Credit transaction type\n */\nexport type TransactionType = \"purchase\" | \"subscription\" | \"bonus\" | \"refund\" | \"adjustment\";\n\n/**\n * Portable credit transaction\n */\nexport interface PortableTransaction {\n id: string;\n userId: string;\n type: TransactionType;\n /** Amount of credits (positive for additions, negative for deductions) */\n amount: number;\n description: string;\n /** Reference to payment provider */\n paymentRef?: string;\n previousBalance: number;\n newBalance: number;\n createdAt: string;\n}\n\n// ==================== Journal Types ====================\n\n/**\n * Source of a credit journal entry\n */\nexport type CreditSource =\n | \"operation_commit\"\n | \"operation_release\"\n | \"purchase\"\n | \"subscription_grant\"\n | \"subscription_upgrade\"\n | \"subscription_downgrade\"\n | \"monthly_reset\"\n | \"bonus\"\n | \"refund\"\n | \"admin_adjustment\"\n | \"expiry\"\n | \"reservation_expired\";\n\n/**\n * Type of reference for a journal entry\n */\nexport type JournalReferenceType =\n | \"reservation\"\n | \"transaction\"\n | \"adjustment\"\n | \"reset\"\n | \"subscription\";\n\n/**\n * Portable credit journal entry for audit trail\n */\nexport interface PortableJournalEntry {\n id: string;\n userId: string;\n /** Type of entry - debit decreases balance, credit increases balance */\n entryType: \"debit\" | \"credit\";\n /** Amount of credits involved */\n amount: number;\n /** Balance after this entry */\n balanceAfter: number;\n /** Source of the credit change */\n source: CreditSource;\n /** Reference ID (e.g., reservationId, transactionId) */\n referenceId: string;\n /** Type of reference */\n referenceType: JournalReferenceType;\n /** Human-readable description */\n description: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** When this entry was created - ISO 8601 */\n createdAt: string;\n}\n\n// ==================== Usage Types ====================\n\n/**\n * Portable usage log entry\n */\nexport interface PortableUsageLog {\n id: string;\n userId: string;\n operationType: CreditOperationType;\n provider: AIProviderType;\n creditsUsed: number;\n success: boolean;\n errorMessage?: string;\n resourceId?: string;\n resourceType?: ResourceType;\n requestId?: string;\n metadata?: Record<string, unknown>;\n createdAt: string;\n}\n\n/**\n * User-friendly usage history entry\n */\nexport interface UsageHistoryEntry {\n id: string;\n /** Type of entry for display */\n type: \"usage\" | \"purchase\" | \"bonus\" | \"reset\" | \"refund\" | \"adjustment\";\n /** Positive = earned, Negative = spent */\n creditsChange: number;\n /** Balance after this entry */\n balanceAfter: number;\n /** Human-readable description */\n description: string;\n /** When this occurred - ISO 8601 */\n createdAt: string;\n}\n\n/**\n * Paginated usage history response\n */\nexport interface UsageHistoryResponse {\n entries: UsageHistoryEntry[];\n pagination: {\n total: number;\n limit: number;\n offset: number;\n hasMore: boolean;\n };\n}\n\n// ==================== Tier Configuration ====================\n\n/**\n * Tier configuration for credit limits and pricing\n */\nexport interface TierConfig {\n tier: SubscriptionTier;\n monthlyCredits: number;\n priceUsd: number;\n features: string[];\n}\n\n// ==================== Options Types ====================\n\n/**\n * Options for withCredits HOF\n */\nexport interface WithCreditsOptions {\n /** Operation type for cost lookup */\n operationType: CreditOperationType;\n /** AI provider (defaults to \"gemini\") */\n provider?: AIProviderType;\n /** Custom cost override (use with caution) */\n customCost?: number;\n /** Resource ID for usage logging */\n resourceId?: string;\n /** Resource type for usage logging */\n resourceType?: ResourceType;\n}\n\n// ==================== Constants ====================\n","/**\n * Credit system error classes - framework agnostic\n *\n * Provides typed error handling for credit operations.\n * These errors can be used across different environments.\n */\n\n/**\n * Error codes for credit operations\n */\nexport const CreditErrorCode = {\n INSUFFICIENT_CREDITS: \"INSUFFICIENT_CREDITS\",\n RESERVATION_NOT_FOUND: \"RESERVATION_NOT_FOUND\",\n RESERVATION_EXPIRED: \"RESERVATION_EXPIRED\",\n RESERVATION_ALREADY_PROCESSED: \"RESERVATION_ALREADY_PROCESSED\",\n USER_NOT_FOUND: \"USER_NOT_FOUND\",\n INVALID_OPERATION_TYPE: \"INVALID_OPERATION_TYPE\",\n CONFIGURATION_ERROR: \"CONFIGURATION_ERROR\",\n DATABASE_ERROR: \"DATABASE_ERROR\",\n} as const;\n\nexport type CreditErrorCodeType = (typeof CreditErrorCode)[keyof typeof CreditErrorCode];\n\n/**\n * Custom error class for credit operations\n *\n * Provides structured error information including:\n * - Error code for programmatic handling\n * - Human-readable message\n * - Optional details for debugging\n */\nexport class CreditError extends Error {\n public readonly code: CreditErrorCodeType;\n public readonly details?: Record<string, unknown>;\n\n constructor(\n message: string,\n code: CreditErrorCodeType,\n details?: Record<string, unknown>\n ) {\n super(message);\n this.name = \"CreditError\";\n this.code = code;\n this.details = details;\n\n // Maintains proper stack trace for where error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, CreditError);\n }\n }\n\n /**\n * Convert to JSON-serializable object\n */\n toJSON(): { name: string; code: string; message: string; details?: Record<string, unknown> } {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n ...(this.details && { details: this.details }),\n };\n }\n}\n\n/**\n * Type guard to check if an error is a CreditError\n */\nexport function isCreditError(error: unknown): error is CreditError {\n return error instanceof CreditError;\n}\n\n/**\n * Check if an error represents insufficient credits\n *\n * Works with both CreditError and regular Error instances.\n * Useful for handling errors from different sources.\n */\nexport function isInsufficientCreditsError(error: unknown): boolean {\n if (isCreditError(error)) {\n return error.code === CreditErrorCode.INSUFFICIENT_CREDITS;\n }\n\n if (error instanceof Error) {\n return error.message.toLowerCase().includes(\"insufficient credits\");\n }\n\n return false;\n}\n\n/**\n * Create an insufficient credits error\n */\nexport function createInsufficientCreditsError(\n required: number,\n available: number\n): CreditError {\n return new CreditError(\n `Insufficient credits: available ${available}, required ${required}`,\n CreditErrorCode.INSUFFICIENT_CREDITS,\n { required, available, shortfall: required - available }\n );\n}\n\n/**\n * Create a reservation not found error\n */\nexport function createReservationNotFoundError(reservationId: string): CreditError {\n return new CreditError(\n `Reservation ${reservationId} not found`,\n CreditErrorCode.RESERVATION_NOT_FOUND,\n { reservationId }\n );\n}\n\n/**\n * Create a reservation expired error\n */\nexport function createReservationExpiredError(reservationId: string): CreditError {\n return new CreditError(\n `Reservation ${reservationId} has expired`,\n CreditErrorCode.RESERVATION_EXPIRED,\n { reservationId }\n );\n}\n\n/**\n * Create a reservation already processed error\n */\nexport function createReservationAlreadyProcessedError(\n reservationId: string,\n status: string\n): CreditError {\n return new CreditError(\n `Reservation ${reservationId} has already been ${status}`,\n CreditErrorCode.RESERVATION_ALREADY_PROCESSED,\n { reservationId, status }\n );\n}\n\n/**\n * Create a user not found error\n */\nexport function createUserNotFoundError(userId: string): CreditError {\n return new CreditError(\n `User ${userId} not found`,\n CreditErrorCode.USER_NOT_FOUND,\n { userId }\n );\n}\n\n/**\n * Create an invalid operation type error\n */\nexport function createInvalidOperationTypeError(\n operationType: string,\n validTypes: string[]\n): CreditError {\n return new CreditError(\n `Invalid operation type: ${operationType}. Valid types: ${validTypes.join(\", \")}`,\n CreditErrorCode.INVALID_OPERATION_TYPE,\n { operationType, validTypes }\n );\n}\n","/**\n * Deferred execution abstraction - framework agnostic\n *\n * Provides a way to schedule work to run after the current operation completes.\n * Different frameworks can provide their own implementations:\n * - Next.js: uses `after()` from `next/server`\n * - Generic: uses `setImmediate()` or `setTimeout()`\n * - Testing: can use synchronous execution\n */\n\n/**\n * Interface for deferred execution\n *\n * Implementations should schedule the function to run asynchronously\n * without blocking the current operation.\n */\nexport interface DeferredExecutor {\n /**\n * Schedule a function to run asynchronously\n *\n * The function should be executed after the current operation completes.\n * Errors should be caught and logged, not propagated.\n *\n * @param fn - Async function to execute\n */\n defer(fn: () => Promise<void>): void;\n}\n\n/**\n * Generic deferred executor using setImmediate/setTimeout\n *\n * Works in Node.js and browser environments.\n * Suitable for non-framework environments or testing.\n */\nexport const genericDeferred: DeferredExecutor = {\n defer(fn: () => Promise<void>): void {\n // Use setImmediate in Node.js, setTimeout as fallback\n const scheduler = typeof setImmediate !== \"undefined\" ? setImmediate : setTimeout;\n scheduler(() => {\n fn().catch((error) => {\n console.error(\"[Credits] Deferred task error:\", error);\n });\n });\n },\n};\n\n/**\n * Synchronous deferred executor\n *\n * Executes the function immediately (fire-and-forget).\n * Useful for testing or when deferred execution isn't needed.\n */\nexport const synchronousDeferred: DeferredExecutor = {\n defer(fn: () => Promise<void>): void {\n fn().catch((error) => {\n console.error(\"[Credits] Deferred task error:\", error);\n });\n },\n};\n\n/**\n * Create a custom deferred executor\n *\n * Allows frameworks to provide their own scheduling mechanism.\n *\n * @example\n * ```typescript\n * // Next.js adapter\n * import { after } from 'next/server';\n *\n * const nextJsDeferred = createDeferredExecutor((fn) => after(fn));\n * ```\n *\n * @param schedule - Function that schedules async work\n * @returns DeferredExecutor instance\n */\nexport function createDeferredExecutor(\n schedule: (fn: () => Promise<void>) => void\n): DeferredExecutor {\n return {\n defer: schedule,\n };\n}\n\n/**\n * No-op deferred executor\n *\n * Discards deferred work. Useful when you want to disable\n * background tasks (e.g., in certain test scenarios).\n */\nexport const noopDeferred: DeferredExecutor = {\n defer(_fn: () => Promise<void>): void {\n // Intentionally do nothing\n },\n};\n","import { z } from \"zod\";\nimport type { SubscriptionTier, TierConfig } from \"../core/types.js\";\nimport { getConfigProvider } from \"./provider.js\";\n\n/**\n * Schema for tier configuration\n */\nconst tierConfigSchema = z.object({\n tier: z.enum([\"free\", \"basic\", \"premium\", \"unlimited\"]),\n monthlyCredits: z.number().min(0),\n priceUsd: z.number().min(0),\n features: z.array(z.string()),\n});\n\n/**\n * Schema for credit system configuration\n */\nconst creditSystemConfigSchema = z.object({\n /**\n * Operation costs in credits\n * Keys are operation type names (any non-empty string)\n * Values are positive numbers representing credit cost\n */\n operationCosts: z.record(\n z.string().min(1),\n z.number().positive()\n ),\n\n /**\n * Display labels for operation types (English canonical labels).\n * Falls back to auto-generating from snake_case keys if not provided.\n */\n operationLabels: z.record(\n z.string().min(1),\n z.string().min(1)\n ).optional().default({}),\n\n /**\n * Tier configurations\n */\n tierConfigs: z.record(\n z.enum([\"free\", \"basic\", \"premium\", \"unlimited\"]),\n tierConfigSchema\n ),\n\n /**\n * Reservation expiry time in milliseconds\n */\n reservationExpiryMs: z.number().positive().default(5 * 60 * 1000),\n\n /**\n * Default credits for new users (free tier)\n */\n defaultFreeCredits: z.number().positive().default(25),\n\n /**\n * Grace period in days after subscription expires before downgrade\n */\n subscriptionGracePeriodDays: z.number().min(0).default(3),\n\n /**\n * Low balance notification threshold\n */\n lowBalanceThreshold: z.number().min(0).default(10),\n\n /**\n * Cooldown in hours between low balance notifications\n */\n lowBalanceNotificationCooldownHours: z.number().positive().default(24),\n\n /**\n * Feature flags for optional features\n */\n features: z.object({\n journalEntries: z.boolean().default(true),\n notifications: z.boolean().default(true),\n subscriptionExpiry: z.boolean().default(true),\n usageHistory: z.boolean().default(true),\n }).default({\n journalEntries: true,\n notifications: true,\n subscriptionExpiry: true,\n usageHistory: true,\n }),\n});\n\n/**\n * Credit system configuration type\n */\nexport type CreditSystemConfig = z.infer<typeof creditSystemConfigSchema>;\n\n/**\n * Default configuration\n */\nconst DEFAULT_CONFIG: CreditSystemConfig = {\n operationCosts: {\n story_generation: 5,\n conversation: 2,\n image_generation: 10,\n template_generation: 10,\n },\n operationLabels: {\n story_generation: \"Story generation\",\n conversation: \"Conversation\",\n image_generation: \"Image generation\",\n template_generation: \"Template generation\",\n },\n tierConfigs: {\n free: {\n tier: \"free\",\n monthlyCredits: 25,\n priceUsd: 0,\n features: [\n \"25 credits per month\",\n \"Basic story generation\",\n \"Standard image quality\",\n ],\n },\n basic: {\n tier: \"basic\",\n monthlyCredits: 200,\n priceUsd: 9.99,\n features: [\n \"200 credits per month\",\n \"All story features\",\n \"High quality images\",\n \"Priority support\",\n ],\n },\n premium: {\n tier: \"premium\",\n monthlyCredits: 500,\n priceUsd: 19.99,\n features: [\n \"500 credits per month\",\n \"All features\",\n \"Highest quality images\",\n \"Early access to new features\",\n \"Priority support\",\n ],\n },\n unlimited: {\n tier: \"unlimited\",\n monthlyCredits: 0, // 0 = unlimited\n priceUsd: 49.99,\n features: [\n \"Unlimited credits\",\n \"All features\",\n \"Highest quality images\",\n \"Early access to new features\",\n \"Dedicated support\",\n ],\n },\n },\n reservationExpiryMs: 5 * 60 * 1000, // 5 minutes\n defaultFreeCredits: 25,\n subscriptionGracePeriodDays: 3,\n lowBalanceThreshold: 10,\n lowBalanceNotificationCooldownHours: 24,\n features: {\n journalEntries: true,\n notifications: true,\n subscriptionExpiry: true,\n usageHistory: true,\n },\n};\n\n/**\n * Current configuration (can be overridden)\n */\nlet currentConfig: CreditSystemConfig = DEFAULT_CONFIG;\n\n/**\n * Load configuration from environment variables\n * Can be extended to load from other sources (file, remote config, etc.)\n *\n * Operation costs are loaded from CREDITS_OPERATION_COSTS as JSON:\n * CREDITS_OPERATION_COSTS={\"story_generation\":5,\"image_generation\":10}\n */\nexport function loadConfigFromEnv(): Partial<CreditSystemConfig> {\n const envConfig: Partial<CreditSystemConfig> = {};\n\n // Load operation costs from env as JSON\n const operationCostsEnv = process.env.CREDITS_OPERATION_COSTS;\n if (operationCostsEnv) {\n try {\n const parsed = JSON.parse(operationCostsEnv);\n if (typeof parsed === \"object\" && parsed !== null) {\n envConfig.operationCosts = {\n ...DEFAULT_CONFIG.operationCosts,\n ...parsed,\n };\n }\n } catch {\n console.warn(\"[Credits Config] Failed to parse CREDITS_OPERATION_COSTS env var as JSON\");\n }\n }\n\n // Load other settings from env\n const reservationExpiry = process.env.CREDITS_RESERVATION_EXPIRY_MS;\n if (reservationExpiry) {\n envConfig.reservationExpiryMs = parseInt(reservationExpiry, 10);\n }\n\n const defaultCredits = process.env.CREDITS_DEFAULT_FREE;\n if (defaultCredits) {\n envConfig.defaultFreeCredits = parseInt(defaultCredits, 10);\n }\n\n const gracePeriod = process.env.CREDITS_GRACE_PERIOD_DAYS;\n if (gracePeriod) {\n envConfig.subscriptionGracePeriodDays = parseInt(gracePeriod, 10);\n }\n\n const lowBalanceThreshold = process.env.CREDITS_LOW_BALANCE_THRESHOLD;\n if (lowBalanceThreshold) {\n envConfig.lowBalanceThreshold = parseInt(lowBalanceThreshold, 10);\n }\n\n // Load feature flags\n const featuresEnv = process.env.CREDITS_FEATURES;\n if (featuresEnv) {\n try {\n const features = JSON.parse(featuresEnv);\n envConfig.features = {\n ...DEFAULT_CONFIG.features,\n ...features,\n };\n } catch {\n console.warn(\"[Credits Config] Failed to parse CREDITS_FEATURES env var\");\n }\n }\n\n return envConfig;\n}\n\n/**\n * Initialize configuration\n * Merges default config with environment overrides\n */\nexport function initializeConfig(overrides?: Partial<CreditSystemConfig>): CreditSystemConfig {\n const envConfig = loadConfigFromEnv();\n\n const mergedConfig = {\n ...DEFAULT_CONFIG,\n ...envConfig,\n ...overrides,\n operationCosts: {\n ...DEFAULT_CONFIG.operationCosts,\n ...envConfig.operationCosts,\n ...overrides?.operationCosts,\n },\n operationLabels: {\n ...DEFAULT_CONFIG.operationLabels,\n ...envConfig.operationLabels,\n ...overrides?.operationLabels,\n },\n tierConfigs: {\n ...DEFAULT_CONFIG.tierConfigs,\n ...envConfig.tierConfigs,\n ...overrides?.tierConfigs,\n },\n features: {\n ...DEFAULT_CONFIG.features,\n ...envConfig.features,\n ...overrides?.features,\n },\n };\n\n // Validate configuration\n const result = creditSystemConfigSchema.safeParse(mergedConfig);\n if (!result.success) {\n console.error(\"[Credits Config] Invalid configuration:\", result.error.issues);\n throw new Error(\"Invalid credit system configuration\");\n }\n\n currentConfig = result.data;\n return currentConfig;\n}\n\n/**\n * Get the current configuration.\n * If an external provider is registered, delegates to it.\n * Otherwise falls back to the local currentConfig.\n */\nexport function getConfig(): CreditSystemConfig {\n const provider = getConfigProvider();\n if (provider) {\n return provider.getConfig();\n }\n return currentConfig;\n}\n\n/**\n * Get all valid operation types from configuration\n * Returns the keys of the operationCosts object\n */\nexport function getValidOperationTypes(): string[] {\n return Object.keys(getConfig().operationCosts);\n}\n\n/**\n * Check if an operation type is valid (configured in the system)\n * @param type - The operation type to check\n * @returns true if the operation type is configured\n */\nexport function isValidOperationType(type: string): boolean {\n return type in getConfig().operationCosts;\n}\n\n/**\n * Get operation cost from configuration\n * @throws Error if the operation type is not configured\n */\nexport function getConfigOperationCost(operationType: string): number {\n const cost = getConfig().operationCosts[operationType];\n if (cost === undefined) {\n throw new Error(\n `Unknown operation type: ${operationType}. Valid types: ${getValidOperationTypes().join(\", \")}`\n );\n }\n return cost;\n}\n\n/**\n * Get tier configuration from configuration\n */\nexport function getConfigTierConfig(tier: SubscriptionTier): TierConfig {\n return getConfig().tierConfigs[tier]!;\n}\n\n/**\n * Get monthly limit for a tier from configuration\n * Returns Infinity for unlimited tier\n */\nexport function getConfigMonthlyLimit(tier: SubscriptionTier): number {\n const config = getConfig().tierConfigs[tier]!;\n return config.monthlyCredits === 0 ? Infinity : config.monthlyCredits;\n}\n\n/**\n * Check if a feature is enabled\n */\nexport function isFeatureEnabled(feature: keyof CreditSystemConfig[\"features\"]): boolean {\n return getConfig().features[feature];\n}\n\n/**\n * Convert a snake_case string to Title Case.\n * E.g., \"story_generation\" -> \"Story Generation\"\n */\nfunction snakeCaseToTitleCase(str: string): string {\n return str\n .replace(/_/g, \" \")\n .replace(/\\b\\w/g, (c) => c.toUpperCase());\n}\n\n/**\n * Get the display label for an operation type.\n * Falls back to converting snake_case to Title Case if no label is configured.\n */\nexport function getOperationLabel(operationType: string): string {\n const labels = getConfig().operationLabels;\n if (labels && operationType in labels) {\n return labels[operationType];\n }\n return snakeCaseToTitleCase(operationType);\n}\n\n/**\n * Get all operation labels as a record.\n * For any operation in operationCosts that lacks a label, generates one from the key.\n */\nexport function getOperationLabels(): Record<string, string> {\n const config = getConfig();\n const result: Record<string, string> = {};\n for (const key of Object.keys(config.operationCosts)) {\n result[key] = config.operationLabels?.[key]\n ?? snakeCaseToTitleCase(key);\n }\n return result;\n}\n\n/**\n * Reset configuration to defaults (for testing)\n */\nexport function resetConfig(): void {\n currentConfig = DEFAULT_CONFIG;\n}\n\n// Initialize configuration on module load\ninitializeConfig();\n","import type { CreditSystemConfig } from \"./index.js\";\n\n/** Interface for external config providers (e.g. Firestore-backed) */\nexport interface ICreditConfigProvider {\n getConfig(): CreditSystemConfig;\n}\n\nlet configProvider: ICreditConfigProvider | null = null;\n\n/** Register an external config provider. Called once at app startup. */\nexport function registerConfigProvider(provider: ICreditConfigProvider): void {\n configProvider = provider;\n}\n\n/** Get the registered provider, or null if none registered. */\nexport function getConfigProvider(): ICreditConfigProvider | null {\n return configProvider;\n}\n\n/** Clear registered provider (for testing). */\nexport function clearConfigProvider(): void {\n configProvider = null;\n}\n","/**\n * Core credit operations - framework agnostic\n *\n * Contains the business logic for credit operations that can be\n * used by any adapter or service implementation.\n */\n\nimport type { ICreditRepository } from \"../repository/types.js\";\nimport type { PortableReservation } from \"./types.js\";\nimport { getOperationLabel } from \"../config/index.js\";\n\n/**\n * Commit a reservation with journal entry\n *\n * @param repository - The credit repository\n * @param userId - User ID\n * @param reservationId - Reservation to commit\n */\nexport async function commitReservationWithJournal(\n repository: ICreditRepository,\n userId: string,\n reservationId: string\n): Promise<void> {\n // Get the reservation to know the amount\n const reservation = await repository.getReservation(userId, reservationId);\n if (!reservation) {\n throw new Error(`Reservation ${reservationId} not found`);\n }\n\n // Commit the reservation atomically\n await repository.commitReservationAtomic(userId, reservationId);\n\n // Create journal entry\n const credits = await repository.getUserCredits(userId);\n if (credits) {\n await repository.createJournalEntry({\n userId,\n entryType: \"debit\",\n amount: reservation.amount,\n balanceAfter: credits.balance,\n source: \"operation_commit\",\n referenceId: reservationId,\n referenceType: \"reservation\",\n description: `Committed ${reservation.amount} credits for ${getOperationLabel(reservation.operationType)}`,\n metadata: {\n operationType: reservation.operationType,\n },\n });\n }\n}\n\n/**\n * Release a reservation with journal entry\n *\n * @param repository - The credit repository\n * @param userId - User ID\n * @param reservationId - Reservation to release\n */\nexport async function releaseReservationWithJournal(\n repository: ICreditRepository,\n userId: string,\n reservationId: string\n): Promise<void> {\n // Get the reservation to check its state\n const reservation = await repository.getReservation(userId, reservationId);\n\n // Release the reservation atomically\n await repository.releaseReservationAtomic(userId, reservationId);\n\n // Create journal entry only if reservation was in reserved state\n if (reservation?.status === \"reserved\") {\n const credits = await repository.getUserCredits(userId);\n if (credits) {\n await repository.createJournalEntry({\n userId,\n entryType: \"credit\",\n amount: 0, // No actual credits returned (they were reserved, not spent)\n balanceAfter: credits.balance,\n source: \"operation_release\",\n referenceId: reservationId,\n referenceType: \"reservation\",\n description: `Released ${reservation.amount} reserved credits for ${getOperationLabel(reservation.operationType)}`,\n metadata: {\n operationType: reservation.operationType,\n amount: reservation.amount,\n },\n });\n }\n }\n}\n\n/**\n * Reserve credits for an operation\n *\n * @param repository - The credit repository\n * @param userId - User ID\n * @param amount - Credits to reserve\n * @param operationType - Type of operation\n * @param expiryMs - Reservation expiry time in milliseconds\n * @returns The reservation\n */\nexport async function reserveCreditsForOperation(\n repository: ICreditRepository,\n userId: string,\n amount: number,\n operationType: string,\n expiryMs: number = 5 * 60 * 1000\n): Promise<PortableReservation> {\n const expiresAt = new Date(Date.now() + expiryMs);\n return repository.reserveCreditsAtomic(userId, amount, operationType, expiresAt);\n}\n"],"mappings":";AAsBO,SAAS,0BACd,SACA,cACA,UACQ;AACR,SAAO,UAAU,eAAe;AAClC;AAcO,SAAS,oBAAoB,OAAwB;AAC1D,MAAI,CAAC,OAAO;AACV,YAAO,oBAAI,KAAK,GAAE,YAAY;AAAA,EAChC;AAEA,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO;AAAA,EACT;AAEA,MAAI,iBAAiB,MAAM;AACzB,WAAO,MAAM,YAAY;AAAA,EAC3B;AAEA,MACE,OAAO,UAAU,YACjB,UAAU,QACV,YAAY,SACZ,OAAQ,MAAiC,WAAW,YACpD;AACA,WAAQ,MAAiC,OAAO,EAAE,YAAY;AAAA,EAChE;AAEA,UAAO,oBAAI,KAAK,GAAE,YAAY;AAChC;AAcO,SAAS,OAAO,OAAsB;AAC3C,MAAI,iBAAiB,MAAM;AACzB,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,UAAU,UAAU;AAC7B,WAAO,IAAI,KAAK,KAAK;AAAA,EACvB;AAEA,MACE,OAAO,UAAU,YACjB,UAAU,QACV,YAAY,SACZ,OAAQ,MAAiC,WAAW,YACpD;AACA,WAAQ,MAAiC,OAAO;AAAA,EAClD;AAEA,SAAO,oBAAI,KAAK;AAClB;;;ACxFO,IAAM,kBAAkB;AAAA,EAC7B,sBAAsB;AAAA,EACtB,uBAAuB;AAAA,EACvB,qBAAqB;AAAA,EACrB,+BAA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AAQ,aAAa;AAG9D,QAAM,UAAU,MAAM,WAAW,eAAe,MAAM;AACtD,MAAI,SAAS;AACX,UAAM,WAAW,mBAAmB;AAAA,MAClC;AAAA,MACA,WAAW;AAAA,MACX,QAAQ,YAAY;AAAA,MACpB,cAAc,QAAQ;AAAA,MACtB,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,eAAe;AAAA,MACf,aAAa,aAAa,YAAY,MAAM,gBAAgB,kBAAkB,YAAY,aAAa,CAAC;AAAA,MACxG,UAAU;AAAA,QACR,eAAe,YAAY;AAAA,MAC7B;AAAA,IACF,CAAC;AAAA,EACH;AACF;AASA,eAAsB,8BACpB,YACA,QACA,eACe;AAEf,QAAM,cAAc,MAAM,WAAW,eAAe,QAAQ,aAAa;AAGzE,QAAM,WAAW,yBAAyB,QAAQ,aAAa;AAG/D,MAAI,aAAa,WAAW,YAAY;AACtC,UAAM,UAAU,MAAM,WAAW,eAAe,MAAM;AACtD,QAAI,SAAS;AACX,YAAM,WAAW,mBAAmB;AAAA,QAClC;AAAA,QACA,WAAW;AAAA,QACX,QAAQ;AAAA;AAAA,QACR,cAAc,QAAQ;AAAA,QACtB,QAAQ;AAAA,QACR,aAAa;AAAA,QACb,eAAe;AAAA,QACf,aAAa,YAAY,YAAY,MAAM,yBAAyB,kBAAkB,YAAY,aAAa,CAAC;AAAA,QAChH,UAAU;AAAA,UACR,eAAe,YAAY;AAAA,UAC3B,QAAQ,YAAY;AAAA,QACtB;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAYA,eAAsB,2BACpB,YACA,QACA,QACA,eACA,WAAmB,IAAI,KAAK,KACE;AAC9B,QAAM,YAAY,IAAI,KAAK,KAAK,IAAI,IAAI,QAAQ;AAChD,SAAO,WAAW,qBAAqB,QAAQ,QAAQ,eAAe,SAAS;AACjF;","names":[]}
@@ -13,7 +13,7 @@
13
13
  * Implementations should schedule the function to run asynchronously
14
14
  * without blocking the current operation.
15
15
  */
16
- export interface DeferredExecutor {
16
+ interface DeferredExecutor {
17
17
  /**
18
18
  * Schedule a function to run asynchronously
19
19
  *
@@ -30,14 +30,14 @@ export interface DeferredExecutor {
30
30
  * Works in Node.js and browser environments.
31
31
  * Suitable for non-framework environments or testing.
32
32
  */
33
- export declare const genericDeferred: DeferredExecutor;
33
+ declare const genericDeferred: DeferredExecutor;
34
34
  /**
35
35
  * Synchronous deferred executor
36
36
  *
37
37
  * Executes the function immediately (fire-and-forget).
38
38
  * Useful for testing or when deferred execution isn't needed.
39
39
  */
40
- export declare const synchronousDeferred: DeferredExecutor;
40
+ declare const synchronousDeferred: DeferredExecutor;
41
41
  /**
42
42
  * Create a custom deferred executor
43
43
  *
@@ -54,12 +54,13 @@ export declare const synchronousDeferred: DeferredExecutor;
54
54
  * @param schedule - Function that schedules async work
55
55
  * @returns DeferredExecutor instance
56
56
  */
57
- export declare function createDeferredExecutor(schedule: (fn: () => Promise<void>) => void): DeferredExecutor;
57
+ declare function createDeferredExecutor(schedule: (fn: () => Promise<void>) => void): DeferredExecutor;
58
58
  /**
59
59
  * No-op deferred executor
60
60
  *
61
61
  * Discards deferred work. Useful when you want to disable
62
62
  * background tasks (e.g., in certain test scenarios).
63
63
  */
64
- export declare const noopDeferred: DeferredExecutor;
65
- //# sourceMappingURL=deferred.d.ts.map
64
+ declare const noopDeferred: DeferredExecutor;
65
+
66
+ export { type DeferredExecutor as D, createDeferredExecutor as c, genericDeferred as g, noopDeferred as n, synchronousDeferred as s };