@symbo.ls/sdk 3.2.3 → 3.2.6

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 (183) hide show
  1. package/README.md +141 -0
  2. package/dist/cjs/config/environment.js +94 -10
  3. package/dist/cjs/index.js +152 -12
  4. package/dist/cjs/services/AdminService.js +351 -0
  5. package/dist/cjs/services/AuthService.js +738 -305
  6. package/dist/cjs/services/BaseService.js +158 -6
  7. package/dist/cjs/services/BranchService.js +484 -0
  8. package/dist/cjs/services/CollabService.js +439 -116
  9. package/dist/cjs/services/DnsService.js +340 -0
  10. package/dist/cjs/services/FeatureFlagService.js +175 -0
  11. package/dist/cjs/services/FileService.js +201 -0
  12. package/dist/cjs/services/IntegrationService.js +538 -0
  13. package/dist/cjs/services/MetricsService.js +62 -0
  14. package/dist/cjs/services/PaymentService.js +271 -0
  15. package/dist/cjs/services/PlanService.js +426 -0
  16. package/dist/cjs/services/ProjectService.js +1207 -0
  17. package/dist/cjs/services/PullRequestService.js +503 -0
  18. package/dist/cjs/services/ScreenshotService.js +304 -0
  19. package/dist/cjs/services/SubscriptionService.js +396 -0
  20. package/dist/cjs/services/TrackingService.js +661 -0
  21. package/dist/cjs/services/WaitlistService.js +148 -0
  22. package/dist/cjs/services/index.js +60 -4
  23. package/dist/cjs/state/RootStateManager.js +2 -23
  24. package/dist/cjs/state/rootEventBus.js +9 -0
  25. package/dist/cjs/utils/CollabClient.js +78 -12
  26. package/dist/cjs/utils/TokenManager.js +16 -3
  27. package/dist/cjs/utils/changePreprocessor.js +199 -0
  28. package/dist/cjs/utils/jsonDiff.js +46 -4
  29. package/dist/cjs/utils/ordering.js +309 -0
  30. package/dist/cjs/utils/services.js +285 -128
  31. package/dist/cjs/utils/validation.js +0 -3
  32. package/dist/esm/config/environment.js +94 -10
  33. package/dist/esm/index.js +47862 -18248
  34. package/dist/esm/services/AdminService.js +1132 -0
  35. package/dist/esm/services/AuthService.js +1493 -386
  36. package/dist/esm/services/BaseService.js +757 -6
  37. package/dist/esm/services/BranchService.js +1265 -0
  38. package/dist/esm/services/CollabService.js +24956 -16089
  39. package/dist/esm/services/DnsService.js +1121 -0
  40. package/dist/esm/services/FeatureFlagService.js +956 -0
  41. package/dist/esm/services/FileService.js +982 -0
  42. package/dist/esm/services/IntegrationService.js +1319 -0
  43. package/dist/esm/services/MetricsService.js +843 -0
  44. package/dist/esm/services/PaymentService.js +1052 -0
  45. package/dist/esm/services/PlanService.js +1207 -0
  46. package/dist/esm/services/ProjectService.js +2526 -0
  47. package/dist/esm/services/PullRequestService.js +1284 -0
  48. package/dist/esm/services/ScreenshotService.js +1085 -0
  49. package/dist/esm/services/SubscriptionService.js +1177 -0
  50. package/dist/esm/services/TrackingService.js +18454 -0
  51. package/dist/esm/services/WaitlistService.js +929 -0
  52. package/dist/esm/services/index.js +47373 -18027
  53. package/dist/esm/state/RootStateManager.js +11 -23
  54. package/dist/esm/state/rootEventBus.js +9 -0
  55. package/dist/esm/utils/CollabClient.js +17526 -16120
  56. package/dist/esm/utils/TokenManager.js +16 -3
  57. package/dist/esm/utils/changePreprocessor.js +542 -0
  58. package/dist/esm/utils/jsonDiff.js +958 -43
  59. package/dist/esm/utils/ordering.js +291 -0
  60. package/dist/esm/utils/services.js +285 -128
  61. package/dist/esm/utils/validation.js +116 -50
  62. package/dist/node/config/environment.js +94 -10
  63. package/dist/node/index.js +183 -16
  64. package/dist/node/services/AdminService.js +332 -0
  65. package/dist/node/services/AuthService.js +742 -310
  66. package/dist/node/services/BaseService.js +148 -6
  67. package/dist/node/services/BranchService.js +465 -0
  68. package/dist/node/services/CollabService.js +439 -116
  69. package/dist/node/services/DnsService.js +321 -0
  70. package/dist/node/services/FeatureFlagService.js +156 -0
  71. package/dist/node/services/FileService.js +182 -0
  72. package/dist/node/services/IntegrationService.js +519 -0
  73. package/dist/node/services/MetricsService.js +43 -0
  74. package/dist/node/services/PaymentService.js +252 -0
  75. package/dist/node/services/PlanService.js +407 -0
  76. package/dist/node/services/ProjectService.js +1188 -0
  77. package/dist/node/services/PullRequestService.js +484 -0
  78. package/dist/node/services/ScreenshotService.js +285 -0
  79. package/dist/node/services/SubscriptionService.js +377 -0
  80. package/dist/node/services/TrackingService.js +632 -0
  81. package/dist/node/services/WaitlistService.js +129 -0
  82. package/dist/node/services/index.js +60 -4
  83. package/dist/node/state/RootStateManager.js +2 -23
  84. package/dist/node/state/rootEventBus.js +9 -0
  85. package/dist/node/utils/CollabClient.js +77 -11
  86. package/dist/node/utils/TokenManager.js +16 -3
  87. package/dist/node/utils/changePreprocessor.js +180 -0
  88. package/dist/node/utils/jsonDiff.js +46 -4
  89. package/dist/node/utils/ordering.js +290 -0
  90. package/dist/node/utils/services.js +285 -128
  91. package/dist/node/utils/validation.js +0 -3
  92. package/package.json +30 -18
  93. package/src/config/environment.js +95 -10
  94. package/src/index.js +190 -23
  95. package/src/services/AdminService.js +374 -0
  96. package/src/services/AuthService.js +874 -328
  97. package/src/services/BaseService.js +166 -6
  98. package/src/services/BranchService.js +536 -0
  99. package/src/services/CollabService.js +557 -148
  100. package/src/services/DnsService.js +366 -0
  101. package/src/services/FeatureFlagService.js +174 -0
  102. package/src/services/FileService.js +213 -0
  103. package/src/services/IntegrationService.js +548 -0
  104. package/src/services/MetricsService.js +40 -0
  105. package/src/services/PaymentService.js +287 -0
  106. package/src/services/PlanService.js +468 -0
  107. package/src/services/ProjectService.js +1366 -0
  108. package/src/services/PullRequestService.js +537 -0
  109. package/src/services/ScreenshotService.js +258 -0
  110. package/src/services/SubscriptionService.js +425 -0
  111. package/src/services/TrackingService.js +853 -0
  112. package/src/services/WaitlistService.js +130 -0
  113. package/src/services/index.js +79 -5
  114. package/src/services/tests/BranchService/createBranch.test.js +153 -0
  115. package/src/services/tests/BranchService/deleteBranch.test.js +173 -0
  116. package/src/services/tests/BranchService/getBranchChanges.test.js +146 -0
  117. package/src/services/tests/BranchService/listBranches.test.js +87 -0
  118. package/src/services/tests/BranchService/mergeBranch.test.js +210 -0
  119. package/src/services/tests/BranchService/publishVersion.test.js +183 -0
  120. package/src/services/tests/BranchService/renameBranch.test.js +240 -0
  121. package/src/services/tests/BranchService/resetBranch.test.js +152 -0
  122. package/src/services/tests/FeatureFlagService/adminFeatureFlags.test.js +67 -0
  123. package/src/services/tests/FeatureFlagService/getFeatureFlags.test.js +75 -0
  124. package/src/services/tests/FileService/createFileFormData.test.js +74 -0
  125. package/src/services/tests/FileService/getFileUrl.test.js +69 -0
  126. package/src/services/tests/FileService/updateProjectIcon.test.js +109 -0
  127. package/src/services/tests/FileService/uploadDocument.test.js +36 -0
  128. package/src/services/tests/FileService/uploadFile.test.js +78 -0
  129. package/src/services/tests/FileService/uploadFileWithValidation.test.js +114 -0
  130. package/src/services/tests/FileService/uploadImage.test.js +36 -0
  131. package/src/services/tests/FileService/uploadMultipleFiles.test.js +111 -0
  132. package/src/services/tests/FileService/validateFile.test.js +63 -0
  133. package/src/services/tests/PlanService/createPlan.test.js +104 -0
  134. package/src/services/tests/PlanService/createPlanWithValidation.test.js +523 -0
  135. package/src/services/tests/PlanService/deletePlan.test.js +92 -0
  136. package/src/services/tests/PlanService/getActivePlans.test.js +123 -0
  137. package/src/services/tests/PlanService/getAdminPlans.test.js +84 -0
  138. package/src/services/tests/PlanService/getPlan.test.js +50 -0
  139. package/src/services/tests/PlanService/getPlanByKey.test.js +109 -0
  140. package/src/services/tests/PlanService/getPlanWithValidation.test.js +85 -0
  141. package/src/services/tests/PlanService/getPlans.test.js +53 -0
  142. package/src/services/tests/PlanService/getPlansByPriceRange.test.js +109 -0
  143. package/src/services/tests/PlanService/getPlansWithValidation.test.js +48 -0
  144. package/src/services/tests/PlanService/initializePlans.test.js +75 -0
  145. package/src/services/tests/PlanService/updatePlan.test.js +111 -0
  146. package/src/services/tests/PlanService/updatePlanWithValidation.test.js +556 -0
  147. package/src/state/RootStateManager.js +37 -32
  148. package/src/state/rootEventBus.js +19 -0
  149. package/src/utils/CollabClient.js +99 -12
  150. package/src/utils/TokenManager.js +20 -3
  151. package/src/utils/changePreprocessor.js +239 -0
  152. package/src/utils/jsonDiff.js +40 -5
  153. package/src/utils/ordering.js +271 -0
  154. package/src/utils/services.js +306 -139
  155. package/src/utils/validation.js +0 -3
  156. package/dist/cjs/services/AIService.js +0 -155
  157. package/dist/cjs/services/BasedService.js +0 -1185
  158. package/dist/cjs/services/CoreService.js +0 -2295
  159. package/dist/cjs/services/SocketService.js +0 -309
  160. package/dist/cjs/services/SymstoryService.js +0 -571
  161. package/dist/cjs/utils/basedQuerys.js +0 -181
  162. package/dist/cjs/utils/symstoryClient.js +0 -259
  163. package/dist/esm/services/AIService.js +0 -185
  164. package/dist/esm/services/BasedService.js +0 -5262
  165. package/dist/esm/services/CoreService.js +0 -2827
  166. package/dist/esm/services/SocketService.js +0 -456
  167. package/dist/esm/services/SymstoryService.js +0 -7025
  168. package/dist/esm/utils/basedQuerys.js +0 -163
  169. package/dist/esm/utils/symstoryClient.js +0 -354
  170. package/dist/node/services/AIService.js +0 -136
  171. package/dist/node/services/BasedService.js +0 -1156
  172. package/dist/node/services/CoreService.js +0 -2266
  173. package/dist/node/services/SocketService.js +0 -280
  174. package/dist/node/services/SymstoryService.js +0 -542
  175. package/dist/node/utils/basedQuerys.js +0 -162
  176. package/dist/node/utils/symstoryClient.js +0 -230
  177. package/src/services/AIService.js +0 -150
  178. package/src/services/BasedService.js +0 -1302
  179. package/src/services/CoreService.js +0 -2548
  180. package/src/services/SocketService.js +0 -336
  181. package/src/services/SymstoryService.js +0 -649
  182. package/src/utils/basedQuerys.js +0 -164
  183. package/src/utils/symstoryClient.js +0 -252
@@ -0,0 +1,258 @@
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
+
@@ -0,0 +1,425 @@
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
+ }