@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,40 +0,0 @@
1
- /**
2
- * Shared utilities for credit repository implementations
3
- *
4
- * These are pure functions with no server-only dependencies,
5
- * making them safe to use in any repository implementation.
6
- */
7
- /**
8
- * Generate a unique ID
9
- * Uses timestamp + random string for uniqueness
10
- */
11
- export function generateId() {
12
- return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
13
- }
14
- /**
15
- * Convert date-like value to Date object
16
- * Handles: Date, string, Firestore Timestamp
17
- */
18
- export function toDate(value) {
19
- if (value instanceof Date)
20
- return value;
21
- if (typeof value === "string")
22
- return new Date(value);
23
- // Handle Firestore Timestamp
24
- if (typeof value === "object" && value !== null && "toDate" in value) {
25
- return value.toDate();
26
- }
27
- return new Date();
28
- }
29
- /**
30
- * Get the first day of next month
31
- * Used for calculating monthly reset dates
32
- */
33
- export function getNextMonthlyReset(from = new Date()) {
34
- const next = new Date(from);
35
- next.setMonth(next.getMonth() + 1);
36
- next.setDate(1);
37
- next.setHours(0, 0, 0, 0);
38
- return next;
39
- }
40
- //# sourceMappingURL=utils.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/repository/utils.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH;;;GAGG;AACH,MAAM,UAAU,UAAU;IACxB,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;AACxE,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,MAAM,CAAC,KAA8B;IACnD,IAAI,KAAK,YAAY,IAAI;QAAE,OAAO,KAAK,CAAC;IACxC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC;IACtD,6BAA6B;IAC7B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,QAAQ,IAAI,KAAK,EAAE,CAAC;QACrE,OAAQ,KAAgC,CAAC,MAAM,EAAE,CAAC;IACpD,CAAC;IACD,OAAO,IAAI,IAAI,EAAE,CAAC;AACpB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAa,IAAI,IAAI,EAAE;IACzD,MAAM,IAAI,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;IAC5B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC;IACnC,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAChB,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC1B,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -1,146 +0,0 @@
1
- /**
2
- * AdminCreditsClient - Admin REST API client for the credits system
3
- *
4
- * Provides administrative access to the credits system for managing
5
- * user credits, configurations, and subscriptions.
6
- *
7
- * @example
8
- * ```typescript
9
- * const adminClient = new AdminCreditsClient({
10
- * baseUrl: process.env.CREDITS_API_URL,
11
- * apiKey: process.env.CREDITS_ADMIN_API_KEY,
12
- * });
13
- *
14
- * // Add credits to a user
15
- * await adminClient.addCredits("user-123", 100, "Support credit grant");
16
- *
17
- * // Update subscription tier
18
- * await adminClient.updateSubscription("user-123", "premium", "2027-01-01T00:00:00Z");
19
- *
20
- * // Update operation costs
21
- * await adminClient.updateCosts({
22
- * story_generation: 8,
23
- * image_generation: 12,
24
- * });
25
- * ```
26
- */
27
- import type { AdminCreditsClientConfig, UserCredits } from "./types.js";
28
- /**
29
- * Credits configuration returned by the API
30
- */
31
- export interface CreditsConfig {
32
- operationCosts: Record<string, number>;
33
- tierConfigs: Record<string, {
34
- monthlyLimit: number;
35
- features: string[];
36
- }>;
37
- }
38
- /**
39
- * Response from listing users
40
- */
41
- export interface ListUsersResponse {
42
- users: Array<{
43
- userId: string;
44
- balance: number;
45
- bonusCredits?: number;
46
- tier: string;
47
- monthlyUsed?: number;
48
- }>;
49
- hasMore: boolean;
50
- total?: number;
51
- }
52
- /**
53
- * Options for listing users
54
- */
55
- export interface ListUsersOptions {
56
- page?: number;
57
- limit?: number;
58
- tier?: string;
59
- search?: string;
60
- }
61
- export declare class AdminCreditsClient {
62
- private readonly baseUrl;
63
- private readonly apiKey;
64
- private readonly fetchFn;
65
- constructor(config: AdminCreditsClientConfig);
66
- /**
67
- * Make an authenticated admin request to the API
68
- */
69
- private request;
70
- /**
71
- * Get a specific user's credits
72
- *
73
- * @param userId - ID of the user
74
- * @returns User's credit information
75
- * @throws AuthorizationError if API key is invalid
76
- */
77
- getUserCredits(userId: string): Promise<UserCredits>;
78
- /**
79
- * Add credits to a user's account
80
- *
81
- * Credits are added to bonusCredits, which don't expire on monthly reset.
82
- *
83
- * @param userId - ID of the user
84
- * @param amount - Amount of credits to add
85
- * @param description - Reason for adding credits
86
- * @throws AuthorizationError if API key is invalid
87
- */
88
- addCredits(userId: string, amount: number, description: string): Promise<void>;
89
- /**
90
- * Update a user's subscription tier
91
- *
92
- * @param userId - ID of the user
93
- * @param tier - New subscription tier
94
- * @param expiresAt - Optional expiration date (ISO 8601)
95
- * @throws AuthorizationError if API key is invalid
96
- */
97
- updateSubscription(userId: string, tier: string, expiresAt?: string): Promise<void>;
98
- /**
99
- * Get the current credits configuration
100
- *
101
- * @returns Credits system configuration
102
- * @throws AuthorizationError if API key is invalid
103
- */
104
- getConfig(): Promise<CreditsConfig>;
105
- /**
106
- * Update operation costs
107
- *
108
- * @param costs - New operation costs (operation type -> cost)
109
- * @throws AuthorizationError if API key is invalid
110
- */
111
- updateCosts(costs: Record<string, number>): Promise<void>;
112
- /**
113
- * List all users with their credits
114
- *
115
- * @param options - Pagination and filtering options
116
- * @returns Paginated list of users
117
- * @throws AuthorizationError if API key is invalid
118
- */
119
- listUsers(options?: ListUsersOptions): Promise<ListUsersResponse>;
120
- /**
121
- * Deduct credits from a user's account
122
- *
123
- * @param userId - ID of the user
124
- * @param amount - Amount of credits to deduct
125
- * @param description - Reason for deducting credits
126
- * @throws AuthorizationError if API key is invalid
127
- */
128
- deductCredits(userId: string, amount: number, description: string): Promise<void>;
129
- /**
130
- * Get usage statistics for a user
131
- *
132
- * @param userId - ID of the user
133
- * @param options - Optional date range
134
- * @returns Usage statistics
135
- * @throws AuthorizationError if API key is invalid
136
- */
137
- getUserStats(userId: string, options?: {
138
- startDate?: string;
139
- endDate?: string;
140
- }): Promise<{
141
- totalCreditsUsed: number;
142
- operationBreakdown: Record<string, number>;
143
- successRate: number;
144
- }>;
145
- }
146
- //# sourceMappingURL=admin-client.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"admin-client.d.ts","sourceRoot":"","sources":["../../src/sdk/admin-client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH,OAAO,KAAK,EAAE,wBAAwB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAGxE;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,WAAW,EAAE,MAAM,CACjB,MAAM,EACN;QACE,YAAY,EAAE,MAAM,CAA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AM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAO/D;;;;;;OAMG;IACG,SAAS,CAAC,OAAO,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAWvE;;;;;;;OAOG;IACG,aAAa,CACjB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,WAAW,EAAE,MAAM,GAClB,OAAO,CAAC,IAAI,CAAC;IAUhB;;;;;;;OAOG;IACG,YAAY,CAChB,MAAM,EAAE,MAAM,EACd,OAAO,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,GACjD,OAAO,CAAC;QACT,gBAAgB,EAAE,MAAM,CAAC;QACzB,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC3C,WAAW,EAAE,MAAM,CAAC;KACrB,CAAC;CAYH"}
@@ -1,196 +0,0 @@
1
- /**
2
- * AdminCreditsClient - Admin REST API client for the credits system
3
- *
4
- * Provides administrative access to the credits system for managing
5
- * user credits, configurations, and subscriptions.
6
- *
7
- * @example
8
- * ```typescript
9
- * const adminClient = new AdminCreditsClient({
10
- * baseUrl: process.env.CREDITS_API_URL,
11
- * apiKey: process.env.CREDITS_ADMIN_API_KEY,
12
- * });
13
- *
14
- * // Add credits to a user
15
- * await adminClient.addCredits("user-123", 100, "Support credit grant");
16
- *
17
- * // Update subscription tier
18
- * await adminClient.updateSubscription("user-123", "premium", "2027-01-01T00:00:00Z");
19
- *
20
- * // Update operation costs
21
- * await adminClient.updateCosts({
22
- * story_generation: 8,
23
- * image_generation: 12,
24
- * });
25
- * ```
26
- */
27
- import { parseApiError, NetworkError } from "./errors.js";
28
- export class AdminCreditsClient {
29
- baseUrl;
30
- apiKey;
31
- fetchFn;
32
- constructor(config) {
33
- // Ensure baseUrl doesn't have trailing slash
34
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
35
- this.apiKey = config.apiKey;
36
- this.fetchFn = config.fetch ?? fetch;
37
- }
38
- /**
39
- * Make an authenticated admin request to the API
40
- */
41
- async request(path, options = {}) {
42
- const { method = "GET", body, params } = options;
43
- // Build URL with query params
44
- let url = `${this.baseUrl}${path}`;
45
- if (params) {
46
- const searchParams = new URLSearchParams();
47
- for (const [key, value] of Object.entries(params)) {
48
- if (value !== undefined) {
49
- searchParams.set(key, String(value));
50
- }
51
- }
52
- const queryString = searchParams.toString();
53
- if (queryString) {
54
- url += `?${queryString}`;
55
- }
56
- }
57
- // Build headers with admin API key
58
- const headers = {
59
- "Content-Type": "application/json",
60
- "x-api-key": this.apiKey,
61
- };
62
- // Make the request
63
- let response;
64
- try {
65
- response = await this.fetchFn(url, {
66
- method,
67
- headers,
68
- body: body ? JSON.stringify(body) : undefined,
69
- });
70
- }
71
- catch (error) {
72
- throw new NetworkError(error instanceof Error ? error.message : "Network request failed", error instanceof Error ? error : undefined);
73
- }
74
- // Parse response
75
- const responseBody = (await response.json());
76
- // Handle errors
77
- if (!response.ok) {
78
- throw parseApiError(response.status, responseBody);
79
- }
80
- // Return data
81
- return responseBody.data;
82
- }
83
- /**
84
- * Get a specific user's credits
85
- *
86
- * @param userId - ID of the user
87
- * @returns User's credit information
88
- * @throws AuthorizationError if API key is invalid
89
- */
90
- async getUserCredits(userId) {
91
- return this.request(`/api/admin/credits/users/${userId}`);
92
- }
93
- /**
94
- * Add credits to a user's account
95
- *
96
- * Credits are added to bonusCredits, which don't expire on monthly reset.
97
- *
98
- * @param userId - ID of the user
99
- * @param amount - Amount of credits to add
100
- * @param description - Reason for adding credits
101
- * @throws AuthorizationError if API key is invalid
102
- */
103
- async addCredits(userId, amount, description) {
104
- await this.request(`/api/admin/credits/users/${userId}/add`, {
105
- method: "POST",
106
- body: { amount, description },
107
- });
108
- }
109
- /**
110
- * Update a user's subscription tier
111
- *
112
- * @param userId - ID of the user
113
- * @param tier - New subscription tier
114
- * @param expiresAt - Optional expiration date (ISO 8601)
115
- * @throws AuthorizationError if API key is invalid
116
- */
117
- async updateSubscription(userId, tier, expiresAt) {
118
- const body = { tier };
119
- if (expiresAt) {
120
- body.expiresAt = expiresAt;
121
- }
122
- await this.request(`/api/admin/credits/users/${userId}/subscription`, {
123
- method: "PUT",
124
- body,
125
- });
126
- }
127
- /**
128
- * Get the current credits configuration
129
- *
130
- * @returns Credits system configuration
131
- * @throws AuthorizationError if API key is invalid
132
- */
133
- async getConfig() {
134
- return this.request("/api/admin/credits/config");
135
- }
136
- /**
137
- * Update operation costs
138
- *
139
- * @param costs - New operation costs (operation type -> cost)
140
- * @throws AuthorizationError if API key is invalid
141
- */
142
- async updateCosts(costs) {
143
- await this.request("/api/admin/credits/config/costs", {
144
- method: "PUT",
145
- body: { operationCosts: costs },
146
- });
147
- }
148
- /**
149
- * List all users with their credits
150
- *
151
- * @param options - Pagination and filtering options
152
- * @returns Paginated list of users
153
- * @throws AuthorizationError if API key is invalid
154
- */
155
- async listUsers(options) {
156
- return this.request("/api/admin/credits/users", {
157
- params: {
158
- page: options?.page,
159
- limit: options?.limit,
160
- tier: options?.tier,
161
- search: options?.search,
162
- },
163
- });
164
- }
165
- /**
166
- * Deduct credits from a user's account
167
- *
168
- * @param userId - ID of the user
169
- * @param amount - Amount of credits to deduct
170
- * @param description - Reason for deducting credits
171
- * @throws AuthorizationError if API key is invalid
172
- */
173
- async deductCredits(userId, amount, description) {
174
- await this.request(`/api/admin/credits/users/${userId}/deduct`, {
175
- method: "POST",
176
- body: { amount, description },
177
- });
178
- }
179
- /**
180
- * Get usage statistics for a user
181
- *
182
- * @param userId - ID of the user
183
- * @param options - Optional date range
184
- * @returns Usage statistics
185
- * @throws AuthorizationError if API key is invalid
186
- */
187
- async getUserStats(userId, options) {
188
- return this.request(`/api/admin/credits/users/${userId}/stats`, {
189
- params: {
190
- startDate: options?.startDate,
191
- endDate: options?.endDate,
192
- },
193
- });
194
- }
195
- }
196
- //# sourceMappingURL=admin-client.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AAE,WAAW,EAAE;SAC9B,CACF,CAAC;IACJ,CAAC;IAED;;;;;;;OAOG;IACH,KAAK,CAAC,YAAY,CAChB,MAAc,EACd,OAAkD;QAMlD,OAAO,IAAI,CAAC,OAAO,CAIhB,4BAA4B,MAAM,QAAQ,EAAE;YAC7C,MAAM,EAAE;gBACN,SAAS,EAAE,OAAO,EAAE,SAAS;gBAC7B,OAAO,EAAE,OAAO,EAAE,OAAO;aAC1B;SACF,CAAC,CAAC;IACL,CAAC;CACF"}
@@ -1,144 +0,0 @@
1
- /**
2
- * CreditsClient - REST API client for the credits system
3
- *
4
- * Provides a type-safe interface for consuming credits API endpoints
5
- * from external services or other applications.
6
- *
7
- * @example
8
- * ```typescript
9
- * const client = new CreditsClient({
10
- * baseUrl: process.env.CREDITS_API_URL,
11
- * getAuthToken: async () => session.accessToken,
12
- * });
13
- *
14
- * // Check if user has sufficient credits
15
- * const check = await client.checkAvailability("story_generation");
16
- * if (!check.hasCredits) {
17
- * console.log("Insufficient credits");
18
- * return;
19
- * }
20
- *
21
- * // Two-phase commit pattern
22
- * const reservation = await client.reserve("story_generation");
23
- * try {
24
- * const result = await doExpensiveWork();
25
- * await client.commit(reservation.reservationId);
26
- * return result;
27
- * } catch (error) {
28
- * await client.release(reservation.reservationId);
29
- * throw error;
30
- * }
31
- * ```
32
- */
33
- import type { CreditsClientConfig, UserCredits, CreditCheckResult, ReservationResult, UsageHistoryResponse, PaginationOptions } from "./types.js";
34
- export declare class CreditsClient {
35
- private readonly baseUrl;
36
- private readonly getAuthToken?;
37
- private readonly fetchFn;
38
- constructor(config: CreditsClientConfig);
39
- /**
40
- * Make an authenticated request to the API
41
- */
42
- private request;
43
- /**
44
- * Get the current user's credit balance
45
- *
46
- * @returns User's credit information
47
- * @throws AuthenticationError if not authenticated
48
- */
49
- getBalance(): Promise<UserCredits>;
50
- /**
51
- * Check if the user has sufficient credits for an operation
52
- *
53
- * @param operationType - Type of operation to check
54
- * @param customCost - Optional custom cost to check against
55
- * @returns Credit availability status
56
- * @throws AuthenticationError if not authenticated
57
- */
58
- checkAvailability(operationType: string, customCost?: number): Promise<CreditCheckResult>;
59
- /**
60
- * Reserve credits for an operation
61
- *
62
- * This is the first step in the two-phase commit pattern.
63
- * Reserved credits are held for 5 minutes before expiring.
64
- *
65
- * @param operationType - Type of operation
66
- * @param options - Optional reservation options
67
- * @returns Reservation details including ID and expiry
68
- * @throws InsufficientCreditsError if not enough credits
69
- * @throws AuthenticationError if not authenticated
70
- */
71
- reserve(operationType: string, options?: {
72
- customCost?: number;
73
- resourceId?: string;
74
- resourceType?: string;
75
- }): Promise<ReservationResult>;
76
- /**
77
- * Commit a reservation (deduct credits)
78
- *
79
- * This is the second step in the two-phase commit pattern.
80
- * Call this after your operation succeeds.
81
- *
82
- * @param reservationId - ID of the reservation to commit
83
- * @throws ReservationNotFoundError if reservation doesn't exist
84
- * @throws ReservationExpiredError if reservation has expired
85
- * @throws AuthenticationError if not authenticated
86
- */
87
- commit(reservationId: string): Promise<void>;
88
- /**
89
- * Release a reservation (refund credits)
90
- *
91
- * Call this if your operation fails after reserving credits.
92
- *
93
- * @param reservationId - ID of the reservation to release
94
- * @throws ReservationNotFoundError if reservation doesn't exist
95
- * @throws AuthenticationError if not authenticated
96
- */
97
- release(reservationId: string): Promise<void>;
98
- /**
99
- * Get usage history for the current user
100
- *
101
- * @param options - Optional pagination options
102
- * @returns Paginated list of usage entries
103
- * @throws AuthenticationError if not authenticated
104
- */
105
- getHistory(options?: PaginationOptions): Promise<UsageHistoryResponse>;
106
- /**
107
- * Get the available credits (balance + bonus - reserved)
108
- *
109
- * Convenience method that calculates available credits from balance.
110
- *
111
- * @returns Number of available credits
112
- * @throws AuthenticationError if not authenticated
113
- */
114
- getAvailableCredits(): Promise<number>;
115
- /**
116
- * Execute an operation with automatic credit handling
117
- *
118
- * This is a convenience method that handles the full two-phase commit
119
- * pattern automatically.
120
- *
121
- * @param operationType - Type of operation
122
- * @param operation - The operation to execute
123
- * @param options - Optional reservation options
124
- * @returns Result of the operation
125
- * @throws InsufficientCreditsError if not enough credits
126
- * @throws AuthenticationError if not authenticated
127
- *
128
- * @example
129
- * ```typescript
130
- * const result = await client.withCredits(
131
- * "story_generation",
132
- * async () => {
133
- * return generateStory(data);
134
- * }
135
- * );
136
- * ```
137
- */
138
- withCredits<T>(operationType: string, operation: () => Promise<T>, options?: {
139
- customCost?: number;
140
- resourceId?: string;
141
- resourceType?: string;
142
- }): Promise<T>;
143
- }
144
- //# sourceMappingURL=client.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/sdk/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,KAAK,EACV,mBAAmB,EACnB,WAAW,EACX,iBAAiB,EACjB,iBAAiB,EACjB,oBAAoB,EACpB,iBAAiB,EAClB,MAAM,YAAY,CAAC;AAGpB,qBAAa,aAAa;IACxB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAwB;IACtD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAe;gBAE3B,MAAM,EAAE,mBAAmB;IAOvC;;OAEG;YACW,OAAO;IAwErB;;;;;OAKG;IACG,UAAU,IAAI,OAAO,CAAC,WAAW,CAAC;IAIxC;;;;;;;OAOG;IACG,iBAAiB,CACrB,aAAa,EAAE,MAAM,EACrB,UAAU,CAAC,EAAE,MAAM,GAClB,OAAO,CAAC,iBAAiB,CAAC;IAS7B;;;;;;;;;;;OAWG;IACG,OAAO,CACX,aAAa,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE;QACR,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,UAAU,CAAC,EAAE,MAAM,CAAC;QACpB,YAAY,CAAC,EAAE,MAAM,CAAC;KACvB,GACA,OAAO,CAAC,iBAAiB,CAAC;IAU7B;;;;;;;;;;OAUG;IACG,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