@symbo.ls/sdk 2.34.35 → 3.1.1

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 (187) hide show
  1. package/README.md +13 -315
  2. package/dist/cjs/config/environment.js +50 -124
  3. package/dist/cjs/index.js +22 -169
  4. package/dist/cjs/services/AIService.js +155 -0
  5. package/dist/cjs/services/AuthService.js +277 -751
  6. package/dist/cjs/services/BaseService.js +6 -158
  7. package/dist/cjs/services/BasedService.js +679 -0
  8. package/dist/cjs/services/SocketIOService.js +309 -0
  9. package/dist/cjs/services/SocketService.js +161 -0
  10. package/dist/cjs/services/SymstoryService.js +485 -0
  11. package/dist/cjs/services/index.js +16 -64
  12. package/dist/cjs/utils/basedQuerys.js +61 -0
  13. package/dist/cjs/utils/permission.js +4 -4
  14. package/dist/cjs/utils/services.js +80 -301
  15. package/dist/cjs/utils/symstoryClient.js +228 -0
  16. package/dist/cjs/utils/validation.js +3 -0
  17. package/dist/esm/config/environment.js +50 -124
  18. package/dist/esm/index.js +11282 -49789
  19. package/dist/esm/services/AIService.js +185 -0
  20. package/dist/esm/services/AuthService.js +358 -1506
  21. package/dist/esm/services/BaseService.js +6 -757
  22. package/dist/esm/services/BasedService.js +4651 -0
  23. package/dist/esm/services/SocketIOService.js +467 -0
  24. package/dist/esm/services/SocketService.js +191 -0
  25. package/dist/esm/services/SymstoryService.js +6849 -0
  26. package/dist/esm/services/index.js +11188 -49352
  27. package/dist/esm/utils/basedQuerys.js +43 -0
  28. package/dist/esm/utils/permission.js +4 -4
  29. package/dist/esm/utils/services.js +80 -301
  30. package/dist/esm/utils/symstoryClient.js +334 -0
  31. package/dist/esm/utils/validation.js +26 -93
  32. package/dist/node/config/environment.js +50 -124
  33. package/dist/node/index.js +26 -202
  34. package/dist/node/services/AIService.js +136 -0
  35. package/dist/node/services/AuthService.js +278 -751
  36. package/dist/node/services/BaseService.js +6 -148
  37. package/dist/node/services/BasedService.js +650 -0
  38. package/dist/node/services/SocketIOService.js +280 -0
  39. package/dist/node/services/SocketService.js +142 -0
  40. package/dist/node/services/SymstoryService.js +456 -0
  41. package/dist/node/services/index.js +16 -64
  42. package/dist/node/utils/basedQuerys.js +42 -0
  43. package/dist/node/utils/permission.js +4 -4
  44. package/dist/node/utils/services.js +80 -301
  45. package/dist/node/utils/symstoryClient.js +199 -0
  46. package/dist/node/utils/validation.js +3 -0
  47. package/package.json +21 -43
  48. package/src/config/environment.js +50 -126
  49. package/src/index.js +24 -208
  50. package/src/services/AIService.js +150 -0
  51. package/src/services/AuthService.js +298 -893
  52. package/src/services/BaseService.js +6 -166
  53. package/src/services/BasedService.js +722 -0
  54. package/src/services/SocketIOService.js +356 -0
  55. package/src/services/SocketService.js +168 -0
  56. package/src/services/SymstoryService.js +563 -0
  57. package/src/services/index.js +13 -80
  58. package/src/utils/basedQuerys.js +41 -0
  59. package/src/utils/permission.js +4 -4
  60. package/src/utils/services.js +83 -325
  61. package/src/utils/symstoryClient.js +218 -0
  62. package/src/utils/validation.js +3 -0
  63. package/dist/cjs/services/AdminService.js +0 -351
  64. package/dist/cjs/services/BranchService.js +0 -484
  65. package/dist/cjs/services/CollabService.js +0 -743
  66. package/dist/cjs/services/DnsService.js +0 -340
  67. package/dist/cjs/services/FeatureFlagService.js +0 -175
  68. package/dist/cjs/services/FileService.js +0 -201
  69. package/dist/cjs/services/IntegrationService.js +0 -538
  70. package/dist/cjs/services/MetricsService.js +0 -62
  71. package/dist/cjs/services/PaymentService.js +0 -271
  72. package/dist/cjs/services/PlanService.js +0 -426
  73. package/dist/cjs/services/ProjectService.js +0 -1207
  74. package/dist/cjs/services/PullRequestService.js +0 -503
  75. package/dist/cjs/services/ScreenshotService.js +0 -304
  76. package/dist/cjs/services/SubscriptionService.js +0 -396
  77. package/dist/cjs/services/TrackingService.js +0 -661
  78. package/dist/cjs/services/WaitlistService.js +0 -148
  79. package/dist/cjs/state/RootStateManager.js +0 -65
  80. package/dist/cjs/state/rootEventBus.js +0 -74
  81. package/dist/cjs/utils/CollabClient.js +0 -223
  82. package/dist/cjs/utils/TokenManager.js +0 -422
  83. package/dist/cjs/utils/changePreprocessor.js +0 -199
  84. package/dist/cjs/utils/jsonDiff.js +0 -145
  85. package/dist/cjs/utils/ordering.js +0 -309
  86. package/dist/esm/services/AdminService.js +0 -1132
  87. package/dist/esm/services/BranchService.js +0 -1265
  88. package/dist/esm/services/CollabService.js +0 -26838
  89. package/dist/esm/services/DnsService.js +0 -1121
  90. package/dist/esm/services/FeatureFlagService.js +0 -956
  91. package/dist/esm/services/FileService.js +0 -982
  92. package/dist/esm/services/IntegrationService.js +0 -1319
  93. package/dist/esm/services/MetricsService.js +0 -843
  94. package/dist/esm/services/PaymentService.js +0 -1052
  95. package/dist/esm/services/PlanService.js +0 -1207
  96. package/dist/esm/services/ProjectService.js +0 -2526
  97. package/dist/esm/services/PullRequestService.js +0 -1284
  98. package/dist/esm/services/ScreenshotService.js +0 -1085
  99. package/dist/esm/services/SubscriptionService.js +0 -1177
  100. package/dist/esm/services/TrackingService.js +0 -18343
  101. package/dist/esm/services/WaitlistService.js +0 -929
  102. package/dist/esm/state/RootStateManager.js +0 -90
  103. package/dist/esm/state/rootEventBus.js +0 -56
  104. package/dist/esm/utils/CollabClient.js +0 -18901
  105. package/dist/esm/utils/TokenManager.js +0 -408
  106. package/dist/esm/utils/changePreprocessor.js +0 -542
  107. package/dist/esm/utils/jsonDiff.js +0 -7011
  108. package/dist/esm/utils/ordering.js +0 -291
  109. package/dist/node/services/AdminService.js +0 -332
  110. package/dist/node/services/BranchService.js +0 -465
  111. package/dist/node/services/CollabService.js +0 -724
  112. package/dist/node/services/DnsService.js +0 -321
  113. package/dist/node/services/FeatureFlagService.js +0 -156
  114. package/dist/node/services/FileService.js +0 -182
  115. package/dist/node/services/IntegrationService.js +0 -519
  116. package/dist/node/services/MetricsService.js +0 -43
  117. package/dist/node/services/PaymentService.js +0 -252
  118. package/dist/node/services/PlanService.js +0 -407
  119. package/dist/node/services/ProjectService.js +0 -1188
  120. package/dist/node/services/PullRequestService.js +0 -484
  121. package/dist/node/services/ScreenshotService.js +0 -285
  122. package/dist/node/services/SubscriptionService.js +0 -377
  123. package/dist/node/services/TrackingService.js +0 -632
  124. package/dist/node/services/WaitlistService.js +0 -129
  125. package/dist/node/state/RootStateManager.js +0 -36
  126. package/dist/node/state/rootEventBus.js +0 -55
  127. package/dist/node/utils/CollabClient.js +0 -194
  128. package/dist/node/utils/TokenManager.js +0 -403
  129. package/dist/node/utils/changePreprocessor.js +0 -180
  130. package/dist/node/utils/jsonDiff.js +0 -116
  131. package/dist/node/utils/ordering.js +0 -290
  132. package/src/services/AdminService.js +0 -374
  133. package/src/services/BranchService.js +0 -536
  134. package/src/services/CollabService.js +0 -900
  135. package/src/services/DnsService.js +0 -366
  136. package/src/services/FeatureFlagService.js +0 -174
  137. package/src/services/FileService.js +0 -213
  138. package/src/services/IntegrationService.js +0 -548
  139. package/src/services/MetricsService.js +0 -40
  140. package/src/services/PaymentService.js +0 -287
  141. package/src/services/PlanService.js +0 -468
  142. package/src/services/ProjectService.js +0 -1366
  143. package/src/services/PullRequestService.js +0 -537
  144. package/src/services/ScreenshotService.js +0 -258
  145. package/src/services/SubscriptionService.js +0 -425
  146. package/src/services/TrackingService.js +0 -853
  147. package/src/services/WaitlistService.js +0 -130
  148. package/src/services/tests/BranchService/createBranch.test.js +0 -153
  149. package/src/services/tests/BranchService/deleteBranch.test.js +0 -173
  150. package/src/services/tests/BranchService/getBranchChanges.test.js +0 -146
  151. package/src/services/tests/BranchService/listBranches.test.js +0 -87
  152. package/src/services/tests/BranchService/mergeBranch.test.js +0 -210
  153. package/src/services/tests/BranchService/publishVersion.test.js +0 -183
  154. package/src/services/tests/BranchService/renameBranch.test.js +0 -240
  155. package/src/services/tests/BranchService/resetBranch.test.js +0 -152
  156. package/src/services/tests/FeatureFlagService/adminFeatureFlags.test.js +0 -67
  157. package/src/services/tests/FeatureFlagService/getFeatureFlags.test.js +0 -75
  158. package/src/services/tests/FileService/createFileFormData.test.js +0 -74
  159. package/src/services/tests/FileService/getFileUrl.test.js +0 -69
  160. package/src/services/tests/FileService/updateProjectIcon.test.js +0 -109
  161. package/src/services/tests/FileService/uploadDocument.test.js +0 -36
  162. package/src/services/tests/FileService/uploadFile.test.js +0 -78
  163. package/src/services/tests/FileService/uploadFileWithValidation.test.js +0 -114
  164. package/src/services/tests/FileService/uploadImage.test.js +0 -36
  165. package/src/services/tests/FileService/uploadMultipleFiles.test.js +0 -111
  166. package/src/services/tests/FileService/validateFile.test.js +0 -63
  167. package/src/services/tests/PlanService/createPlan.test.js +0 -104
  168. package/src/services/tests/PlanService/createPlanWithValidation.test.js +0 -523
  169. package/src/services/tests/PlanService/deletePlan.test.js +0 -92
  170. package/src/services/tests/PlanService/getActivePlans.test.js +0 -123
  171. package/src/services/tests/PlanService/getAdminPlans.test.js +0 -84
  172. package/src/services/tests/PlanService/getPlan.test.js +0 -50
  173. package/src/services/tests/PlanService/getPlanByKey.test.js +0 -109
  174. package/src/services/tests/PlanService/getPlanWithValidation.test.js +0 -85
  175. package/src/services/tests/PlanService/getPlans.test.js +0 -53
  176. package/src/services/tests/PlanService/getPlansByPriceRange.test.js +0 -109
  177. package/src/services/tests/PlanService/getPlansWithValidation.test.js +0 -48
  178. package/src/services/tests/PlanService/initializePlans.test.js +0 -75
  179. package/src/services/tests/PlanService/updatePlan.test.js +0 -111
  180. package/src/services/tests/PlanService/updatePlanWithValidation.test.js +0 -556
  181. package/src/state/RootStateManager.js +0 -76
  182. package/src/state/rootEventBus.js +0 -67
  183. package/src/utils/CollabClient.js +0 -248
  184. package/src/utils/TokenManager.js +0 -479
  185. package/src/utils/changePreprocessor.js +0 -239
  186. package/src/utils/jsonDiff.js +0 -144
  187. package/src/utils/ordering.js +0 -271
@@ -1,258 +0,0 @@
1
- import { BaseService } from './BaseService.js'
2
-
3
- export class ScreenshotService extends BaseService {
4
- constructor (config) {
5
- super(config)
6
- this._debounceTimers = new Map()
7
- this._inflightRefreshes = new Map()
8
- }
9
-
10
- // ==================== PROJECT-LEVEL OPERATIONS ====================
11
-
12
- async createScreenshotProject (payload) {
13
- this._requireReady('createScreenshotProject')
14
- try {
15
- const response = await this._request('/screenshots/projects', {
16
- method: 'POST',
17
- body: JSON.stringify(payload),
18
- methodName: 'createScreenshotProject'
19
- })
20
- if (response.success) {return response}
21
- throw new Error(response.message)
22
- } catch (error) {
23
- throw new Error(`Failed to create screenshot project: ${error.message}`, { cause: error })
24
- }
25
- }
26
-
27
- async getProjectScreenshots (projectKey, params = {}) {
28
- this._requireReady('getProjectScreenshots')
29
- if (!projectKey) {throw new Error('projectKey is required')}
30
- const { type = 'all', status, limit = 50, offset = 0 } = params
31
- const qs = new URLSearchParams()
32
- if (type) {qs.set('type', type)}
33
- if (status) {qs.set('status', status)}
34
- if (limit != null) {qs.set('limit', String(limit))}
35
- if (offset != null) {qs.set('offset', String(offset))}
36
- try {
37
- const response = await this._request(
38
- `/screenshots/projects/${encodeURIComponent(projectKey)}${qs.toString() ? `?${qs.toString()}` : ''}`,
39
- { method: 'GET', methodName: 'getProjectScreenshots' }
40
- )
41
- if (response.success) {return response}
42
- throw new Error(response.message)
43
- } catch (error) {
44
- throw new Error(`Failed to get project screenshots: ${error.message}`, { cause: error })
45
- }
46
- }
47
-
48
- async reprocessProjectScreenshots (projectKey, body = {}) {
49
- this._requireReady('reprocessProjectScreenshots')
50
- if (!projectKey) {throw new Error('projectKey is required')}
51
- try {
52
- const response = await this._request(
53
- `/screenshots/projects/${encodeURIComponent(projectKey)}/reprocess`,
54
- { method: 'POST', body: JSON.stringify(body), methodName: 'reprocessProjectScreenshots' }
55
- )
56
- if (response.success) {return response}
57
- throw new Error(response.message)
58
- } catch (error) {
59
- throw new Error(`Failed to reprocess screenshots: ${error.message}`, { cause: error })
60
- }
61
- }
62
-
63
- async recreateProjectScreenshots (projectKey, body = {}) {
64
- this._requireReady('recreateProjectScreenshots')
65
- if (!projectKey) {throw new Error('projectKey is required')}
66
- try {
67
- const response = await this._request(
68
- `/screenshots/projects/${encodeURIComponent(projectKey)}/recreate`,
69
- { method: 'POST', body: JSON.stringify(body), methodName: 'recreateProjectScreenshots' }
70
- )
71
- if (response.success) {return response}
72
- throw new Error(response.message)
73
- } catch (error) {
74
- throw new Error(`Failed to recreate screenshots: ${error.message}`, { cause: error })
75
- }
76
- }
77
-
78
- async deleteProjectScreenshots (projectKey) {
79
- this._requireReady('deleteProjectScreenshots')
80
- if (!projectKey) {throw new Error('projectKey is required')}
81
- try {
82
- const response = await this._request(
83
- `/screenshots/projects/${encodeURIComponent(projectKey)}`,
84
- { method: 'DELETE', methodName: 'deleteProjectScreenshots' }
85
- )
86
- if (response.success) {return response}
87
- throw new Error(response.message)
88
- } catch (error) {
89
- throw new Error(`Failed to delete project screenshots: ${error.message}`, { cause: error })
90
- }
91
- }
92
-
93
- // ==================== THUMBNAIL ====================
94
-
95
- async getThumbnailCandidate (projectKey, options = {}) {
96
- this._requireReady('getThumbnailCandidate')
97
- if (!projectKey) {throw new Error('projectKey is required')}
98
- const { includeData = false } = options
99
- const qs = new URLSearchParams()
100
- if (includeData) {qs.set('include_data', 'true')}
101
- try {
102
- const response = await this._request(
103
- `/screenshots/projects/${encodeURIComponent(projectKey)}/thumbnail/candidate${qs.toString() ? `?${qs.toString()}` : ''}`,
104
- { method: 'GET', methodName: 'getThumbnailCandidate' }
105
- )
106
- if (response.success) {return response}
107
- throw new Error(response.message)
108
- } catch (error) {
109
- throw new Error(`Failed to get thumbnail candidate: ${error.message}`, { cause: error })
110
- }
111
- }
112
-
113
- async updateProjectThumbnail (projectKey, body = {}) {
114
- this._requireReady('updateProjectThumbnail')
115
- if (!projectKey) {throw new Error('projectKey is required')}
116
- try {
117
- const response = await this._request(
118
- `/screenshots/projects/${encodeURIComponent(projectKey)}/thumbnail`,
119
- { method: 'POST', body: JSON.stringify(body), methodName: 'updateProjectThumbnail' }
120
- )
121
- if (response.success) {return response}
122
- throw new Error(response.message)
123
- } catch (error) {
124
- throw new Error(`Failed to update project thumbnail: ${error.message}`, { cause: error })
125
- }
126
- }
127
-
128
- // ==================== INDIVIDUAL SHOTS ====================
129
-
130
- async getPageScreenshot (screenshotId, format = 'json') {
131
- this._requireReady('getPageScreenshot')
132
- if (!screenshotId) {throw new Error('screenshotId is required')}
133
- const qs = new URLSearchParams()
134
- if (format) {qs.set('format', format)}
135
- try {
136
- return await this._request(
137
- `/screenshots/pages/${encodeURIComponent(screenshotId)}${qs.toString() ? `?${qs.toString()}` : ''}`,
138
- { method: 'GET', methodName: 'getPageScreenshot' }
139
- )
140
- } catch (error) {
141
- throw new Error(`Failed to get page screenshot: ${error.message}`, { cause: error })
142
- }
143
- }
144
-
145
- async getComponentScreenshot (screenshotId, format = 'json') {
146
- this._requireReady('getComponentScreenshot')
147
- if (!screenshotId) {throw new Error('screenshotId is required')}
148
- const qs = new URLSearchParams()
149
- if (format) {qs.set('format', format)}
150
- try {
151
- return await this._request(
152
- `/screenshots/components/${encodeURIComponent(screenshotId)}${qs.toString() ? `?${qs.toString()}` : ''}`,
153
- { method: 'GET', methodName: 'getComponentScreenshot' }
154
- )
155
- } catch (error) {
156
- throw new Error(`Failed to get component screenshot: ${error.message}`, { cause: error })
157
- }
158
- }
159
-
160
- async getScreenshotByKey (projectKey, type, key, format = 'json') {
161
- this._requireReady('getScreenshotByKey')
162
- if (!projectKey) {throw new Error('projectKey is required')}
163
- if (!type || !['component', 'page'].includes(String(type))) {
164
- throw new Error("type must be 'component' or 'page'")
165
- }
166
- if (!key) {throw new Error('key is required')}
167
- const qs = new URLSearchParams()
168
- if (format) {qs.set('format', format)}
169
- const sub = type === 'component' ? 'components' : 'pages'
170
- try {
171
- return await this._request(
172
- `/screenshots/projects/${encodeURIComponent(projectKey)}/${sub}/${encodeURIComponent(key)}${qs.toString() ? `?${qs.toString()}` : ''}`,
173
- { method: 'GET', methodName: 'getScreenshotByKey' }
174
- )
175
- } catch (error) {
176
- throw new Error(`Failed to get screenshot by key: ${error.message}`, { cause: error })
177
- }
178
- }
179
-
180
- async getQueueStatistics () {
181
- this._requireReady('getQueueStatistics')
182
- try {
183
- const response = await this._request('/screenshots/queue/stats', {
184
- method: 'GET',
185
- methodName: 'getQueueStatistics'
186
- })
187
- if (response.success) {return response}
188
- throw new Error(response.message)
189
- } catch (error) {
190
- throw new Error(`Failed to get queue statistics: ${error.message}`, { cause: error })
191
- }
192
- }
193
-
194
- // ==================== COMBINATION/DEBOUNCED ====================
195
-
196
- /**
197
- * Debounced thumbnail refresh that recreates screenshots and then updates thumbnail.
198
- * Subsequent calls within debounce window reset the timer.
199
- */
200
- async refreshThumbnail (projectKey, options = {}) {
201
- this._requireReady('refreshThumbnail')
202
- if (!projectKey) {throw new Error('projectKey is required')}
203
-
204
- const {
205
- debounceMs = 15000,
206
- waitAfterRecreateMs = 20000,
207
- recreate = {
208
- process_pages: true,
209
- process_components: false,
210
- process_descriptions: false,
211
- force: false,
212
- priority: 5
213
- },
214
- thumbnail = {
215
- strategy: 'auto',
216
- force: true
217
- }
218
- } = options
219
-
220
- // Clear existing debounce timer if present
221
- const existingTimer = this._debounceTimers.get(projectKey)
222
- if (existingTimer) {
223
- clearTimeout(existingTimer)
224
- }
225
-
226
- // Wrap execution in a promise we store, so callers can await the outcome
227
- const executionPromise = await new Promise(resolve => {
228
- const timer = setTimeout(async () => {
229
- try {
230
- // Step 1: queue screenshot recreation (non-blocking server-side)
231
- await this.recreateProjectScreenshots(projectKey, recreate)
232
-
233
- // Step 2: wait for some time to allow processing to progress
234
- await new Promise(resolveDelay => { setTimeout(resolveDelay, waitAfterRecreateMs) })
235
-
236
- // Step 3: update thumbnail using best candidate
237
- const result = await this.updateProjectThumbnail(projectKey, thumbnail)
238
- resolve(result)
239
- } catch (e) {
240
- // Resolve with error object but do not throw to avoid unhandled rejections
241
- resolve({ success: false, error: e?.message || String(e) })
242
- } finally {
243
- this._debounceTimers.delete(projectKey)
244
- this._inflightRefreshes.delete(projectKey)
245
- }
246
- }, debounceMs)
247
-
248
- this._debounceTimers.set(projectKey, timer)
249
- })
250
-
251
- this._inflightRefreshes.set(projectKey, executionPromise)
252
- return executionPromise
253
- }
254
- }
255
-
256
- export default ScreenshotService
257
-
258
-
@@ -1,425 +0,0 @@
1
- import { BaseService } from './BaseService.js'
2
-
3
- export class SubscriptionService extends BaseService {
4
- // ==================== SUBSCRIPTION METHODS ====================
5
-
6
- /**
7
- * Create a new subscription checkout session
8
- */
9
- async createSubscription (subscriptionData) {
10
- this._requireReady('createSubscription')
11
- if (!subscriptionData || typeof subscriptionData !== 'object') {
12
- throw new Error('Subscription data is required')
13
- }
14
-
15
- const { projectId, planId, pricingKey = 'monthly', seats = 1, successUrl, cancelUrl } = subscriptionData
16
-
17
- if (!projectId) {
18
- throw new Error('Project ID is required')
19
- }
20
- if (!planId) {
21
- throw new Error('Plan ID is required')
22
- }
23
-
24
- try {
25
- const response = await this._request('/subscriptions', {
26
- method: 'POST',
27
- body: JSON.stringify({
28
- projectId,
29
- planId,
30
- pricingKey,
31
- seats,
32
- successUrl,
33
- cancelUrl
34
- }),
35
- methodName: 'createSubscription'
36
- })
37
- if (response.success) {
38
- return response.data
39
- }
40
- throw new Error(response.message)
41
- } catch (error) {
42
- throw new Error(`Failed to create subscription: ${error.message}`, { cause: error })
43
- }
44
- }
45
-
46
- /**
47
- * Get subscription status and usage for a project
48
- */
49
- async getProjectStatus (projectId) {
50
- this._requireReady('getProjectStatus')
51
- if (!projectId) {
52
- throw new Error('Project ID is required')
53
- }
54
-
55
- try {
56
- const response = await this._request(`/subscriptions/project/${projectId}`, {
57
- method: 'GET',
58
- methodName: 'getProjectStatus'
59
- })
60
- if (response.success) {
61
- return response.data
62
- }
63
- throw new Error(response.message)
64
- } catch (error) {
65
- throw new Error(`Failed to get project subscription status: ${error.message}`, { cause: error })
66
- }
67
- }
68
-
69
- /**
70
- * Get usage data for a subscription
71
- */
72
- async getUsage (subscriptionId) {
73
- this._requireReady('getUsage')
74
- if (!subscriptionId) {
75
- throw new Error('Subscription ID is required')
76
- }
77
-
78
- try {
79
- const response = await this._request(`/subscriptions/${subscriptionId}/usage`, {
80
- method: 'GET',
81
- methodName: 'getUsage'
82
- })
83
- if (response.success) {
84
- return response.data
85
- }
86
- throw new Error(response.message)
87
- } catch (error) {
88
- throw new Error(`Failed to get subscription usage: ${error.message}`, { cause: error })
89
- }
90
- }
91
-
92
- /**
93
- * Cancel a subscription
94
- */
95
- async cancelSubscription (subscriptionId) {
96
- this._requireReady('cancelSubscription')
97
- if (!subscriptionId) {
98
- throw new Error('Subscription ID is required')
99
- }
100
-
101
- try {
102
- const response = await this._request(`/subscriptions/${subscriptionId}/cancel`, {
103
- method: 'POST',
104
- methodName: 'cancelSubscription'
105
- })
106
- if (response.success) {
107
- return response.data
108
- }
109
- throw new Error(response.message)
110
- } catch (error) {
111
- throw new Error(`Failed to cancel subscription: ${error.message}`, { cause: error })
112
- }
113
- }
114
-
115
- /**
116
- * List invoices for a subscription
117
- */
118
- async listInvoices (subscriptionId, options = {}) {
119
- this._requireReady('listInvoices')
120
- if (!subscriptionId) {
121
- throw new Error('Subscription ID is required')
122
- }
123
-
124
- const { page = 1, limit = 20, status, startingAfter } = options
125
-
126
- try {
127
- const queryParams = new URLSearchParams()
128
- if (page) {queryParams.append('page', page.toString())}
129
- if (limit) {queryParams.append('limit', limit.toString())}
130
- if (status) {queryParams.append('status', status)}
131
- if (startingAfter) {queryParams.append('startingAfter', startingAfter)}
132
-
133
- const queryString = queryParams.toString()
134
- const url = `/subscriptions/${subscriptionId}/invoices${queryString ? `?${queryString}` : ''}`
135
-
136
- const response = await this._request(url, {
137
- method: 'GET',
138
- methodName: 'listInvoices'
139
- })
140
- if (response.success) {
141
- return response.data
142
- }
143
- throw new Error(response.message)
144
- } catch (error) {
145
- throw new Error(`Failed to list invoices: ${error.message}`, { cause: error })
146
- }
147
- }
148
-
149
- /**
150
- * Get customer portal URL for a subscription
151
- */
152
- async getPortalUrl (subscriptionId, returnUrl) {
153
- this._requireReady('getPortalUrl')
154
- if (!subscriptionId) {
155
- throw new Error('Subscription ID is required')
156
- }
157
-
158
- try {
159
- const queryParams = new URLSearchParams()
160
- if (returnUrl) {queryParams.append('returnUrl', returnUrl)}
161
-
162
- const queryString = queryParams.toString()
163
- const url = `/subscriptions/${subscriptionId}/portal${queryString ? `?${queryString}` : ''}`
164
-
165
- const response = await this._request(url, {
166
- method: 'GET',
167
- methodName: 'getPortalUrl'
168
- })
169
- if (response.success) {
170
- return response.data
171
- }
172
- throw new Error(response.message)
173
- } catch (error) {
174
- throw new Error(`Failed to get portal URL: ${error.message}`, { cause: error })
175
- }
176
- }
177
-
178
- // ==================== SUBSCRIPTION HELPER METHODS ====================
179
-
180
- /**
181
- * Helper method to create subscription with validation
182
- */
183
- async createSubscriptionWithValidation (subscriptionData) {
184
- if (!subscriptionData || typeof subscriptionData !== 'object') {
185
- throw new Error('Subscription data must be a valid object')
186
- }
187
-
188
- // Basic validation for required fields
189
- const requiredFields = ['projectId', 'planId']
190
- for (const field of requiredFields) {
191
- if (!subscriptionData[field]) {
192
- throw new Error(`Required field '${field}' is missing`)
193
- }
194
- }
195
-
196
- // Validate seats is a positive integer
197
- if (subscriptionData.seats != null) {
198
- if (!Number.isInteger(subscriptionData.seats) || subscriptionData.seats < 1) {
199
- throw new Error('Seats must be a positive integer')
200
- }
201
- }
202
-
203
- // Validate pricingKey
204
- if (subscriptionData.pricingKey && !['monthly', 'yearly'].includes(subscriptionData.pricingKey)) {
205
- throw new Error('Pricing key must be either "monthly" or "yearly"')
206
- }
207
-
208
- return await this.createSubscription(subscriptionData)
209
- }
210
-
211
- /**
212
- * Helper method to check if project has active subscription
213
- */
214
- async hasActiveSubscription (projectId) {
215
- try {
216
- const status = await this.getProjectStatus(projectId)
217
- return status.hasSubscription === true
218
- } catch (error) {
219
- throw new Error(`Failed to check subscription status: ${error.message}`, { cause: error })
220
- }
221
- }
222
-
223
- /**
224
- * Helper method to get subscription details for a project
225
- */
226
- async getProjectSubscription (projectId) {
227
- try {
228
- const status = await this.getProjectStatus(projectId)
229
- if (!status.hasSubscription) {
230
- return null
231
- }
232
- return status.subscription
233
- } catch (error) {
234
- throw new Error(`Failed to get project subscription: ${error.message}`, { cause: error })
235
- }
236
- }
237
-
238
- /**
239
- * Helper method to get usage with limits for a project
240
- */
241
- async getProjectUsage (projectId) {
242
- try {
243
- const status = await this.getProjectStatus(projectId)
244
- if (!status.hasSubscription) {
245
- return null
246
- }
247
- return status.usage
248
- } catch (error) {
249
- throw new Error(`Failed to get project usage: ${error.message}`, { cause: error })
250
- }
251
- }
252
-
253
- /**
254
- * Helper method to get invoices with pagination
255
- */
256
- async getInvoicesWithPagination (subscriptionId, options = {}) {
257
- try {
258
- const result = await this.listInvoices(subscriptionId, options)
259
- return {
260
- invoices: result.data || [],
261
- pagination: result.pagination || {}
262
- }
263
- } catch (error) {
264
- throw new Error(`Failed to get invoices with pagination: ${error.message}`, { cause: error })
265
- }
266
- }
267
-
268
- /**
269
- * Helper method to check if subscription is active
270
- */
271
- async isSubscriptionActive (subscriptionId) {
272
- try {
273
- const usage = await this.getUsage(subscriptionId)
274
- // This would depend on the actual response structure
275
- // You might need to adjust based on your backend response
276
- return usage && usage.subscription && usage.subscription.status === 'active'
277
- } catch (error) {
278
- throw new Error(`Failed to check subscription status: ${error.message}`, { cause: error })
279
- }
280
- }
281
-
282
- /**
283
- * Helper method to get subscription limits
284
- */
285
- async getSubscriptionLimits (subscriptionId) {
286
- try {
287
- const usage = await this.getUsage(subscriptionId)
288
- return usage.limits || {}
289
- } catch (error) {
290
- throw new Error(`Failed to get subscription limits: ${error.message}`, { cause: error })
291
- }
292
- }
293
-
294
- /**
295
- * Change subscription (unified endpoint for all pricing changes)
296
- */
297
- async changeSubscription (changeData) {
298
- this._requireReady('changeSubscription')
299
- if (!changeData || typeof changeData !== 'object') {
300
- throw new Error('Change data is required')
301
- }
302
-
303
- const { subscriptionId, planId, pricingKey, seats = 1, projectId, successUrl, cancelUrl } = changeData
304
-
305
- if (!subscriptionId) {
306
- throw new Error('Subscription ID is required')
307
- }
308
- if (!pricingKey) {
309
- throw new Error('Pricing key is required')
310
- }
311
-
312
- try {
313
- const response = await this._request(`/subscriptions/${subscriptionId}/change`, {
314
- method: 'POST',
315
- body: JSON.stringify({
316
- planId,
317
- pricingKey,
318
- seats,
319
- projectId,
320
- successUrl,
321
- cancelUrl
322
- }),
323
- methodName: 'changeSubscription'
324
- })
325
- if (response.success) {
326
- return response.data
327
- }
328
- throw new Error(response.message)
329
- } catch (error) {
330
- throw new Error(`Failed to change subscription: ${error.message}`, { cause: error })
331
- }
332
- }
333
-
334
- /**
335
- * Downgrade subscription to free plan
336
- */
337
- async downgrade (downgradeData) {
338
- this._requireReady('downgrade')
339
- if (!downgradeData || typeof downgradeData !== 'object') {
340
- throw new Error('Downgrade data is required')
341
- }
342
-
343
- const { subscriptionId, reason } = downgradeData
344
-
345
- if (!subscriptionId) {
346
- throw new Error('Subscription ID is required')
347
- }
348
-
349
- try {
350
- const response = await this._request(`/subscriptions/${subscriptionId}/downgrade`, {
351
- method: 'POST',
352
- body: JSON.stringify({
353
- reason
354
- }),
355
- methodName: 'downgrade'
356
- })
357
- if (response.success) {
358
- return response.data
359
- }
360
- throw new Error(response.message)
361
- } catch (error) {
362
- throw new Error(`Failed to downgrade subscription: ${error.message}`, { cause: error })
363
- }
364
- }
365
-
366
- /**
367
- * Helper method to change subscription with validation
368
- */
369
- async changeSubscriptionWithValidation (changeData) {
370
- if (!changeData || typeof changeData !== 'object') {
371
- throw new Error('Change data must be a valid object')
372
- }
373
-
374
- // Basic validation for required fields
375
- const requiredFields = ['subscriptionId', 'pricingKey']
376
- for (const field of requiredFields) {
377
- if (!changeData[field]) {
378
- throw new Error(`Required field '${field}' is missing`)
379
- }
380
- }
381
-
382
- // Validate seats is a positive integer if provided
383
- if (changeData.seats != null) {
384
- if (!Number.isInteger(changeData.seats) || changeData.seats < 1) {
385
- throw new Error('Seats must be a positive integer')
386
- }
387
- }
388
-
389
- // Validate subscriptionId is a string
390
- if (typeof changeData.subscriptionId !== 'string') {
391
- throw new Error('Subscription ID must be a valid string')
392
- }
393
-
394
- // Validate planId is a string if provided
395
- if (changeData.planId && typeof changeData.planId !== 'string') {
396
- throw new Error('Plan ID must be a valid string')
397
- }
398
-
399
- return await this.changeSubscription(changeData)
400
- }
401
-
402
- /**
403
- * Helper method to downgrade subscription with validation
404
- */
405
- async downgradeWithValidation (downgradeData) {
406
- if (!downgradeData || typeof downgradeData !== 'object') {
407
- throw new Error('Downgrade data must be a valid object')
408
- }
409
-
410
- // Validate subscriptionId is required and is a string
411
- if (!downgradeData.subscriptionId) {
412
- throw new Error('Subscription ID is required')
413
- }
414
- if (typeof downgradeData.subscriptionId !== 'string') {
415
- throw new Error('Subscription ID must be a valid string')
416
- }
417
-
418
- // Validate reason is a string if provided
419
- if (downgradeData.reason && typeof downgradeData.reason !== 'string') {
420
- throw new Error('Reason must be a valid string')
421
- }
422
-
423
- return await this.downgrade(downgradeData)
424
- }
425
- }