@symbo.ls/sdk 3.2.3 → 3.2.7

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
@@ -1,2266 +0,0 @@
1
- import { BaseService } from "./BaseService.js";
2
- import environment from "../config/environment.js";
3
- import { getTokenManager } from "../utils/TokenManager.js";
4
- class CoreService extends BaseService {
5
- constructor(config) {
6
- super(config);
7
- this._client = null;
8
- this._initialized = false;
9
- this._apiUrl = null;
10
- this._tokenManager = null;
11
- }
12
- init({ context }) {
13
- try {
14
- const { appKey, authToken } = context || this._context;
15
- this._apiUrl = environment.apiUrl;
16
- if (!this._apiUrl) {
17
- throw new Error("Core service base URL not configured");
18
- }
19
- this._tokenManager = getTokenManager({
20
- apiUrl: this._apiUrl,
21
- onTokenRefresh: (tokens) => {
22
- this.updateContext({ authToken: tokens.accessToken });
23
- },
24
- onTokenExpired: () => {
25
- this.updateContext({ authToken: null });
26
- },
27
- onTokenError: (error) => {
28
- console.error("Token management error:", error);
29
- }
30
- });
31
- if (authToken && !this._tokenManager.hasTokens()) {
32
- this._tokenManager.setTokens({ access_token: authToken });
33
- }
34
- this._info = {
35
- config: {
36
- apiUrl: this._apiUrl,
37
- appKey: appKey ? `${appKey.substr(0, 4)}...${appKey.substr(-4)}` : null,
38
- hasToken: Boolean(authToken)
39
- }
40
- };
41
- this._initialized = true;
42
- this._setReady();
43
- } catch (error) {
44
- this._setError(error);
45
- throw error;
46
- }
47
- }
48
- // Helper to check if method requires initialization
49
- _requiresInit(methodName) {
50
- const noInitMethods = /* @__PURE__ */ new Set([
51
- "register",
52
- "login",
53
- "googleAuth",
54
- "googleAuthCallback",
55
- "githubAuth",
56
- "requestPasswordReset",
57
- "confirmPasswordReset",
58
- "confirmRegistration",
59
- "verifyEmail",
60
- "listPublicProjects",
61
- "getPublicProject",
62
- "getHealthStatus"
63
- ]);
64
- return !noInitMethods.has(methodName);
65
- }
66
- // Override _requireReady to be more flexible
67
- _requireReady(methodName) {
68
- if (this._requiresInit(methodName) && !this._initialized) {
69
- throw new Error("Core service not initialized");
70
- }
71
- }
72
- // Debug method to check token status
73
- getTokenDebugInfo() {
74
- if (!this._tokenManager) {
75
- return {
76
- tokenManagerExists: false,
77
- error: "TokenManager not initialized"
78
- };
79
- }
80
- const tokenStatus = this._tokenManager.getTokenStatus();
81
- const { tokens } = this._tokenManager;
82
- return {
83
- tokenManagerExists: true,
84
- tokenStatus,
85
- hasAccessToken: Boolean(tokens.accessToken),
86
- hasRefreshToken: Boolean(tokens.refreshToken),
87
- accessTokenPreview: tokens.accessToken ? `${tokens.accessToken.substring(0, 20)}...` : null,
88
- expiresAt: tokens.expiresAt,
89
- timeToExpiry: tokenStatus.timeToExpiry,
90
- authHeader: this._tokenManager.getAuthHeader()
91
- };
92
- }
93
- // Helper method to check if user is authenticated
94
- isAuthenticated() {
95
- if (!this._tokenManager) {
96
- return false;
97
- }
98
- return this._tokenManager.hasTokens();
99
- }
100
- // Helper method to check if user has valid tokens
101
- hasValidTokens() {
102
- if (!this._tokenManager) {
103
- return false;
104
- }
105
- return this._tokenManager.hasTokens() && this._tokenManager.isAccessTokenValid();
106
- }
107
- // Helper method to make HTTP requests
108
- async _request(endpoint, options = {}) {
109
- const url = `${this._apiUrl}/core${endpoint}`;
110
- const defaultHeaders = {};
111
- if (!(options.body instanceof FormData)) {
112
- defaultHeaders["Content-Type"] = "application/json";
113
- }
114
- if (this._requiresInit(options.methodName) && this._tokenManager) {
115
- try {
116
- const validToken = await this._tokenManager.ensureValidToken();
117
- if (validToken) {
118
- const authHeader = this._tokenManager.getAuthHeader();
119
- if (authHeader) {
120
- defaultHeaders.Authorization = authHeader;
121
- }
122
- }
123
- } catch (error) {
124
- console.warn("Token management failed, proceeding without authentication:", error);
125
- }
126
- } else if (this._requiresInit(options.methodName)) {
127
- const { authToken } = this._context;
128
- if (authToken) {
129
- defaultHeaders.Authorization = `Bearer ${authToken}`;
130
- }
131
- }
132
- try {
133
- const response = await fetch(url, {
134
- ...options,
135
- headers: {
136
- ...defaultHeaders,
137
- ...options.headers
138
- }
139
- });
140
- if (!response.ok) {
141
- let error = { message: `HTTP ${response.status}: ${response.statusText}` };
142
- try {
143
- error = await response.json();
144
- } catch {
145
- }
146
- throw new Error(error.message || error.error || "Request failed");
147
- }
148
- return response.status === 204 ? null : response.json();
149
- } catch (error) {
150
- throw new Error(`Request failed: ${error.message}`);
151
- }
152
- }
153
- // ==================== AUTH METHODS ====================
154
- async register(userData) {
155
- try {
156
- const response = await this._request("/auth/register", {
157
- method: "POST",
158
- body: JSON.stringify(userData),
159
- methodName: "register"
160
- });
161
- if (response.success) {
162
- return response.data;
163
- }
164
- throw new Error(response.message);
165
- } catch (error) {
166
- throw new Error(`Registration failed: ${error.message}`);
167
- }
168
- }
169
- async login(email, password) {
170
- var _a;
171
- try {
172
- const response = await this._request("/auth/login", {
173
- method: "POST",
174
- body: JSON.stringify({ email, password }),
175
- methodName: "login"
176
- });
177
- if (response.success && response.data && response.data.tokens) {
178
- const { tokens } = response.data;
179
- const tokenData = {
180
- access_token: tokens.accessToken,
181
- refresh_token: tokens.refreshToken,
182
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
183
- token_type: "Bearer"
184
- };
185
- if (this._tokenManager) {
186
- this._tokenManager.setTokens(tokenData);
187
- }
188
- this.updateContext({ authToken: tokens.accessToken });
189
- }
190
- if (response.success) {
191
- return response.data;
192
- }
193
- throw new Error(response.message);
194
- } catch (error) {
195
- throw new Error(`Login failed: ${error.message}`);
196
- }
197
- }
198
- async logout() {
199
- this._requireReady("logout");
200
- try {
201
- await this._request("/auth/logout", {
202
- method: "POST",
203
- methodName: "logout"
204
- });
205
- if (this._tokenManager) {
206
- this._tokenManager.clearTokens();
207
- }
208
- this.updateContext({ authToken: null });
209
- } catch (error) {
210
- if (this._tokenManager) {
211
- this._tokenManager.clearTokens();
212
- }
213
- this.updateContext({ authToken: null });
214
- throw new Error(`Logout failed: ${error.message}`);
215
- }
216
- }
217
- async refreshToken(refreshToken) {
218
- try {
219
- const response = await this._request("/auth/refresh", {
220
- method: "POST",
221
- body: JSON.stringify({ refreshToken }),
222
- methodName: "refreshToken"
223
- });
224
- if (response.success) {
225
- return response.data;
226
- }
227
- throw new Error(response.message);
228
- } catch (error) {
229
- throw new Error(`Token refresh failed: ${error.message}`);
230
- }
231
- }
232
- async googleAuth(idToken) {
233
- var _a;
234
- try {
235
- const response = await this._request("/auth/google", {
236
- method: "POST",
237
- body: JSON.stringify({ idToken }),
238
- methodName: "googleAuth"
239
- });
240
- if (response.success && response.data && response.data.tokens) {
241
- const { tokens } = response.data;
242
- const tokenData = {
243
- access_token: tokens.accessToken,
244
- refresh_token: tokens.refreshToken,
245
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
246
- token_type: "Bearer"
247
- };
248
- if (this._tokenManager) {
249
- this._tokenManager.setTokens(tokenData);
250
- }
251
- this.updateContext({ authToken: tokens.accessToken });
252
- }
253
- if (response.success) {
254
- return response.data;
255
- }
256
- throw new Error(response.message);
257
- } catch (error) {
258
- throw new Error(`Google auth failed: ${error.message}`);
259
- }
260
- }
261
- async githubAuth(code) {
262
- var _a;
263
- try {
264
- const response = await this._request("/auth/github", {
265
- method: "POST",
266
- body: JSON.stringify({ code }),
267
- methodName: "githubAuth"
268
- });
269
- if (response.success && response.data && response.data.tokens) {
270
- const { tokens } = response.data;
271
- const tokenData = {
272
- access_token: tokens.accessToken,
273
- refresh_token: tokens.refreshToken,
274
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
275
- token_type: "Bearer"
276
- };
277
- if (this._tokenManager) {
278
- this._tokenManager.setTokens(tokenData);
279
- }
280
- this.updateContext({ authToken: tokens.accessToken });
281
- }
282
- if (response.success) {
283
- return response.data;
284
- }
285
- throw new Error(response.message);
286
- } catch (error) {
287
- throw new Error(`GitHub auth failed: ${error.message}`);
288
- }
289
- }
290
- async googleAuthCallback(code, redirectUri) {
291
- var _a;
292
- try {
293
- const response = await this._request("/auth/google/callback", {
294
- method: "POST",
295
- body: JSON.stringify({ code, redirectUri }),
296
- methodName: "googleAuthCallback"
297
- });
298
- if (response.success && response.data && response.data.tokens) {
299
- const { tokens } = response.data;
300
- const tokenData = {
301
- access_token: tokens.accessToken,
302
- refresh_token: tokens.refreshToken,
303
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
304
- token_type: "Bearer"
305
- };
306
- if (this._tokenManager) {
307
- this._tokenManager.setTokens(tokenData);
308
- }
309
- this.updateContext({ authToken: tokens.accessToken });
310
- }
311
- if (response.success) {
312
- return response.data;
313
- }
314
- throw new Error(response.message);
315
- } catch (error) {
316
- throw new Error(`Google auth callback failed: ${error.message}`);
317
- }
318
- }
319
- async requestPasswordReset(email) {
320
- try {
321
- const response = await this._request("/auth/request-password-reset", {
322
- method: "POST",
323
- body: JSON.stringify({ email }),
324
- methodName: "requestPasswordReset"
325
- });
326
- if (response.success) {
327
- return response.data;
328
- }
329
- throw new Error(response.message);
330
- } catch (error) {
331
- throw new Error(`Password reset request failed: ${error.message}`);
332
- }
333
- }
334
- async confirmPasswordReset(token, password) {
335
- try {
336
- const response = await this._request("/auth/reset-password-confirm", {
337
- method: "POST",
338
- body: JSON.stringify({ token, password }),
339
- methodName: "confirmPasswordReset"
340
- });
341
- if (response.success) {
342
- return response.data;
343
- }
344
- throw new Error(response.message);
345
- } catch (error) {
346
- throw new Error(`Password reset confirmation failed: ${error.message}`);
347
- }
348
- }
349
- async confirmRegistration(token) {
350
- try {
351
- const response = await this._request("/auth/register-confirmation", {
352
- method: "POST",
353
- body: JSON.stringify({ token }),
354
- methodName: "confirmRegistration"
355
- });
356
- if (response.success) {
357
- return response.data;
358
- }
359
- throw new Error(response.message);
360
- } catch (error) {
361
- throw new Error(`Registration confirmation failed: ${error.message}`);
362
- }
363
- }
364
- async requestPasswordChange() {
365
- this._requireReady("requestPasswordChange");
366
- try {
367
- const response = await this._request("/auth/request-password-change", {
368
- method: "POST",
369
- methodName: "requestPasswordChange"
370
- });
371
- if (response.success) {
372
- return response.data;
373
- }
374
- throw new Error(response.message);
375
- } catch (error) {
376
- throw new Error(`Password change request failed: ${error.message}`);
377
- }
378
- }
379
- async confirmPasswordChange(currentPassword, newPassword, code) {
380
- this._requireReady("confirmPasswordChange");
381
- try {
382
- const response = await this._request("/auth/confirm-password-change", {
383
- method: "POST",
384
- body: JSON.stringify({ currentPassword, newPassword, code }),
385
- methodName: "confirmPasswordChange"
386
- });
387
- if (response.success) {
388
- return response.data;
389
- }
390
- throw new Error(response.message);
391
- } catch (error) {
392
- throw new Error(`Password change confirmation failed: ${error.message}`);
393
- }
394
- }
395
- async getMe() {
396
- this._requireReady("getMe");
397
- try {
398
- const response = await this._request("/auth/me", {
399
- method: "GET",
400
- methodName: "getMe"
401
- });
402
- if (response.success) {
403
- return response.data;
404
- }
405
- throw new Error(response.message);
406
- } catch (error) {
407
- throw new Error(`Failed to get user profile: ${error.message}`);
408
- }
409
- }
410
- /**
411
- * Get stored authentication state (backward compatibility method)
412
- * Replaces AuthService.getStoredAuthState()
413
- */
414
- async getStoredAuthState() {
415
- try {
416
- if (!this._tokenManager) {
417
- return {
418
- userId: false,
419
- authToken: false
420
- };
421
- }
422
- const tokenStatus = this._tokenManager.getTokenStatus();
423
- if (!tokenStatus.hasTokens) {
424
- return {
425
- userId: false,
426
- authToken: false
427
- };
428
- }
429
- if (!tokenStatus.isValid && tokenStatus.hasRefreshToken) {
430
- try {
431
- await this._tokenManager.ensureValidToken();
432
- } catch (error) {
433
- console.warn("[CoreService] Token refresh failed:", error.message);
434
- if (error.message.includes("401") || error.message.includes("403") || error.message.includes("invalid") || error.message.includes("expired")) {
435
- this._tokenManager.clearTokens();
436
- return {
437
- userId: false,
438
- authToken: false,
439
- error: `Authentication failed: ${error.message}`
440
- };
441
- }
442
- return {
443
- userId: false,
444
- authToken: this._tokenManager.getAccessToken(),
445
- error: `Network error during token refresh: ${error.message}`,
446
- hasTokens: true
447
- };
448
- }
449
- }
450
- const currentAccessToken = this._tokenManager.getAccessToken();
451
- if (!currentAccessToken) {
452
- return {
453
- userId: false,
454
- authToken: false
455
- };
456
- }
457
- try {
458
- const currentUser = await this.getMe();
459
- return {
460
- userId: currentUser.user.id,
461
- authToken: currentAccessToken,
462
- ...currentUser,
463
- error: null
464
- };
465
- } catch (error) {
466
- console.warn("[CoreService] Failed to get user data:", error.message);
467
- if (error.message.includes("401") || error.message.includes("403")) {
468
- this._tokenManager.clearTokens();
469
- return {
470
- userId: false,
471
- authToken: false,
472
- error: `Authentication failed: ${error.message}`
473
- };
474
- }
475
- return {
476
- userId: false,
477
- authToken: currentAccessToken,
478
- error: `Failed to get user data: ${error.message}`,
479
- hasTokens: true
480
- };
481
- }
482
- } catch (error) {
483
- console.error("[CoreService] Unexpected error in getStoredAuthState:", error);
484
- return {
485
- userId: false,
486
- authToken: false,
487
- error: `Failed to get stored auth state: ${error.message}`
488
- };
489
- }
490
- }
491
- // ==================== USER METHODS ====================
492
- async getUserProfile() {
493
- this._requireReady("getUserProfile");
494
- try {
495
- const response = await this._request("/users/profile", {
496
- method: "GET",
497
- methodName: "getUserProfile"
498
- });
499
- if (response.success) {
500
- return response.data;
501
- }
502
- throw new Error(response.message);
503
- } catch (error) {
504
- throw new Error(`Failed to get user profile: ${error.message}`);
505
- }
506
- }
507
- async updateUserProfile(profileData) {
508
- this._requireReady("updateUserProfile");
509
- try {
510
- const response = await this._request("/users/profile", {
511
- method: "PATCH",
512
- body: JSON.stringify(profileData),
513
- methodName: "updateUserProfile"
514
- });
515
- if (response.success) {
516
- return response.data;
517
- }
518
- throw new Error(response.message);
519
- } catch (error) {
520
- throw new Error(`Failed to update user profile: ${error.message}`);
521
- }
522
- }
523
- async getUserProjects() {
524
- this._requireReady("getUserProjects");
525
- try {
526
- const response = await this._request("/users/projects", {
527
- method: "GET",
528
- methodName: "getUserProjects"
529
- });
530
- if (response.success) {
531
- return response.data.map((project) => ({
532
- ...project,
533
- ...project.icon && { icon: { src: `${this._apiUrl}/core/files/public/${project.icon.id}/download`, ...project.icon } }
534
- }));
535
- }
536
- throw new Error(response.message);
537
- } catch (error) {
538
- throw new Error(`Failed to get user projects: ${error.message}`);
539
- }
540
- }
541
- async getUser(userId) {
542
- this._requireReady("getUser");
543
- if (!userId) {
544
- throw new Error("User ID is required");
545
- }
546
- try {
547
- const response = await this._request(`/users/${userId}`, {
548
- method: "GET",
549
- methodName: "getUser"
550
- });
551
- if (response.success) {
552
- return response.data;
553
- }
554
- throw new Error(response.message);
555
- } catch (error) {
556
- throw new Error(`Failed to get user: ${error.message}`);
557
- }
558
- }
559
- async getUserByEmail(email) {
560
- this._requireReady("getUserByEmail");
561
- if (!email) {
562
- throw new Error("Email is required");
563
- }
564
- try {
565
- const response = await this._request("/auth/user", {
566
- method: "GET",
567
- headers: {
568
- "X-User-Email": email
569
- },
570
- methodName: "getUserByEmail"
571
- });
572
- if (response.success) {
573
- return response.data;
574
- }
575
- throw new Error(response.message);
576
- } catch (error) {
577
- throw new Error(`Failed to get user by email: ${error.message}`);
578
- }
579
- }
580
- // ==================== PROJECT METHODS ====================
581
- async createProject(projectData) {
582
- this._requireReady("createProject");
583
- try {
584
- const response = await this._request("/projects", {
585
- method: "POST",
586
- body: JSON.stringify(projectData),
587
- methodName: "createProject"
588
- });
589
- if (response.success) {
590
- return response.data;
591
- }
592
- throw new Error(response.message);
593
- } catch (error) {
594
- throw new Error(`Failed to create project: ${error.message}`);
595
- }
596
- }
597
- async getProjects(params = {}) {
598
- this._requireReady("getProjects");
599
- try {
600
- const queryParams = new URLSearchParams();
601
- Object.keys(params).forEach((key) => {
602
- if (params[key] != null) {
603
- queryParams.append(key, params[key]);
604
- }
605
- });
606
- const queryString = queryParams.toString();
607
- const url = `/projects${queryString ? `?${queryString}` : ""}`;
608
- const response = await this._request(url, {
609
- method: "GET",
610
- methodName: "getProjects"
611
- });
612
- if (response.success) {
613
- return response;
614
- }
615
- throw new Error(response.message);
616
- } catch (error) {
617
- throw new Error(`Failed to get projects: ${error.message}`);
618
- }
619
- }
620
- /**
621
- * Alias for getProjects for consistency with API naming
622
- */
623
- async listProjects(params = {}) {
624
- return await this.getProjects(params);
625
- }
626
- /**
627
- * List only public projects (no authentication required)
628
- */
629
- async listPublicProjects(params = {}) {
630
- try {
631
- const queryParams = new URLSearchParams();
632
- Object.keys(params).forEach((key) => {
633
- if (params[key] != null) {
634
- queryParams.append(key, params[key]);
635
- }
636
- });
637
- const queryString = queryParams.toString();
638
- const url = `/projects/public${queryString ? `?${queryString}` : ""}`;
639
- const response = await this._request(url, {
640
- method: "GET",
641
- methodName: "listPublicProjects"
642
- });
643
- if (response.success) {
644
- return response.data;
645
- }
646
- throw new Error(response.message);
647
- } catch (error) {
648
- throw new Error(`Failed to list public projects: ${error.message}`);
649
- }
650
- }
651
- async getProject(projectId) {
652
- this._requireReady("getProject");
653
- if (!projectId) {
654
- throw new Error("Project ID is required");
655
- }
656
- try {
657
- const response = await this._request(`/projects/${projectId}`, {
658
- method: "GET",
659
- methodName: "getProject"
660
- });
661
- if (response.success) {
662
- const iconSrc = response.data.icon ? `${this._apiUrl}/core/files/public/${response.data.icon.id}/download` : null;
663
- return {
664
- ...response.data,
665
- icon: { src: iconSrc, ...response.data.icon }
666
- };
667
- }
668
- throw new Error(response.message);
669
- } catch (error) {
670
- throw new Error(`Failed to get project: ${error.message}`);
671
- }
672
- }
673
- /**
674
- * Get a public project by ID (no authentication required)
675
- * Corresponds to router.get('/public/:projectId', ProjectController.getPublicProject)
676
- */
677
- async getPublicProject(projectId) {
678
- if (!projectId) {
679
- throw new Error("Project ID is required");
680
- }
681
- try {
682
- const response = await this._request(`/projects/public/${projectId}`, {
683
- method: "GET",
684
- methodName: "getPublicProject"
685
- });
686
- if (response.success) {
687
- const iconSrc = response.data.icon ? `${this._apiUrl}/core/files/public/${response.data.icon.id}/download` : null;
688
- return {
689
- ...response.data,
690
- icon: { src: iconSrc, ...response.data.icon }
691
- };
692
- }
693
- throw new Error(response.message);
694
- } catch (error) {
695
- throw new Error(`Failed to get public project: ${error.message}`);
696
- }
697
- }
698
- async getProjectByKey(key) {
699
- this._requireReady("getProjectByKey");
700
- if (!key) {
701
- throw new Error("Project key is required");
702
- }
703
- try {
704
- const response = await this._request(`/projects/check-key/${key}`, {
705
- method: "GET",
706
- methodName: "getProjectByKey"
707
- });
708
- if (response.success) {
709
- return response.data;
710
- }
711
- throw new Error(response.message);
712
- } catch (error) {
713
- throw new Error(`Failed to get project by key: ${error.message}`);
714
- }
715
- }
716
- async updateProject(projectId, data) {
717
- this._requireReady("updateProject");
718
- if (!projectId) {
719
- throw new Error("Project ID is required");
720
- }
721
- try {
722
- const response = await this._request(`/projects/${projectId}`, {
723
- method: "PATCH",
724
- body: JSON.stringify(data),
725
- methodName: "updateProject"
726
- });
727
- if (response.success) {
728
- return response.data;
729
- }
730
- throw new Error(response.message);
731
- } catch (error) {
732
- throw new Error(`Failed to update project: ${error.message}`);
733
- }
734
- }
735
- async updateProjectComponents(projectId, components) {
736
- this._requireReady("updateProjectComponents");
737
- if (!projectId) {
738
- throw new Error("Project ID is required");
739
- }
740
- try {
741
- const response = await this._request(`/projects/${projectId}/components`, {
742
- method: "PATCH",
743
- body: JSON.stringify({ components }),
744
- methodName: "updateProjectComponents"
745
- });
746
- if (response.success) {
747
- return response.data;
748
- }
749
- throw new Error(response.message);
750
- } catch (error) {
751
- throw new Error(`Failed to update project components: ${error.message}`);
752
- }
753
- }
754
- async updateProjectSettings(projectId, settings) {
755
- this._requireReady("updateProjectSettings");
756
- if (!projectId) {
757
- throw new Error("Project ID is required");
758
- }
759
- try {
760
- const response = await this._request(`/projects/${projectId}/settings`, {
761
- method: "PATCH",
762
- body: JSON.stringify({ settings }),
763
- methodName: "updateProjectSettings"
764
- });
765
- if (response.success) {
766
- return response.data;
767
- }
768
- throw new Error(response.message);
769
- } catch (error) {
770
- throw new Error(`Failed to update project settings: ${error.message}`);
771
- }
772
- }
773
- async updateProjectName(projectId, name) {
774
- this._requireReady("updateProjectName");
775
- if (!projectId) {
776
- throw new Error("Project ID is required");
777
- }
778
- try {
779
- const response = await this._request(`/projects/${projectId}`, {
780
- method: "PATCH",
781
- body: JSON.stringify({ name }),
782
- methodName: "updateProjectName"
783
- });
784
- if (response.success) {
785
- return response.data;
786
- }
787
- throw new Error(response.message);
788
- } catch (error) {
789
- throw new Error(`Failed to update project name: ${error.message}`);
790
- }
791
- }
792
- async updateProjectPackage(projectId, pkg) {
793
- this._requireReady("updateProjectPackage");
794
- if (!projectId) {
795
- throw new Error("Project ID is required");
796
- }
797
- try {
798
- const response = await this._request(`/projects/${projectId}/tier`, {
799
- method: "PATCH",
800
- body: JSON.stringify({ tier: pkg }),
801
- methodName: "updateProjectPackage"
802
- });
803
- if (response.success) {
804
- return response.data;
805
- }
806
- throw new Error(response.message);
807
- } catch (error) {
808
- throw new Error(`Failed to update project package: ${error.message}`);
809
- }
810
- }
811
- async duplicateProject(projectId, newName, newKey, targetUserId) {
812
- this._requireReady("duplicateProject");
813
- if (!projectId) {
814
- throw new Error("Project ID is required");
815
- }
816
- try {
817
- const response = await this._request(`/projects/${projectId}/duplicate`, {
818
- method: "POST",
819
- body: JSON.stringify({ name: newName, key: newKey, targetUserId }),
820
- methodName: "duplicateProject"
821
- });
822
- if (response.success) {
823
- return response.data;
824
- }
825
- throw new Error(response.message);
826
- } catch (error) {
827
- throw new Error(`Failed to duplicate project: ${error.message}`);
828
- }
829
- }
830
- async removeProject(projectId) {
831
- this._requireReady("removeProject");
832
- if (!projectId) {
833
- throw new Error("Project ID is required");
834
- }
835
- try {
836
- const response = await this._request(`/projects/${projectId}`, {
837
- method: "DELETE",
838
- methodName: "removeProject"
839
- });
840
- if (response.success) {
841
- return response.data;
842
- }
843
- throw new Error(response.message);
844
- } catch (error) {
845
- throw new Error(`Failed to remove project: ${error.message}`);
846
- }
847
- }
848
- async checkProjectKeyAvailability(key) {
849
- this._requireReady("checkProjectKeyAvailability");
850
- if (!key) {
851
- throw new Error("Project key is required");
852
- }
853
- try {
854
- const response = await this._request(`/projects/check-key/${key}`, {
855
- method: "GET",
856
- methodName: "checkProjectKeyAvailability"
857
- });
858
- if (response.success) {
859
- return response.data;
860
- }
861
- throw new Error(response.message);
862
- } catch (error) {
863
- throw new Error(`Failed to check project key availability: ${error.message}`);
864
- }
865
- }
866
- // ==================== PROJECT MEMBER METHODS ====================
867
- async getProjectMembers(projectId) {
868
- this._requireReady("getProjectMembers");
869
- if (!projectId) {
870
- throw new Error("Project ID is required");
871
- }
872
- try {
873
- const response = await this._request(`/projects/${projectId}/members`, {
874
- method: "GET",
875
- methodName: "getProjectMembers"
876
- });
877
- if (response.success) {
878
- return response.data;
879
- }
880
- throw new Error(response.message);
881
- } catch (error) {
882
- throw new Error(`Failed to get project members: ${error.message}`);
883
- }
884
- }
885
- async inviteMember(projectId, email, role = "guest", options = {}) {
886
- this._requireReady("inviteMember");
887
- if (!projectId || !email || !role) {
888
- throw new Error("Project ID, email, and role are required");
889
- }
890
- const { name, callbackUrl } = options;
891
- const defaultCallbackUrl = typeof window === "undefined" ? "https://app.symbols.com/accept-invite" : `${window.location.origin}/accept-invite`;
892
- try {
893
- const requestBody = {
894
- email,
895
- role,
896
- callbackUrl: callbackUrl || defaultCallbackUrl
897
- };
898
- if (name) {
899
- requestBody.name = name;
900
- }
901
- const response = await this._request(`/projects/${projectId}/invite`, {
902
- method: "POST",
903
- body: JSON.stringify(requestBody),
904
- methodName: "inviteMember"
905
- });
906
- if (response.success) {
907
- return response.data;
908
- }
909
- throw new Error(response.message);
910
- } catch (error) {
911
- throw new Error(`Failed to invite member: ${error.message}`);
912
- }
913
- }
914
- async acceptInvite(token) {
915
- this._requireReady("acceptInvite");
916
- if (!token) {
917
- throw new Error("Invitation token is required");
918
- }
919
- try {
920
- const response = await this._request("/projects/accept-invite", {
921
- method: "POST",
922
- body: JSON.stringify({ token }),
923
- methodName: "acceptInvite"
924
- });
925
- if (response.success) {
926
- return response.data;
927
- }
928
- throw new Error(response.message);
929
- } catch (error) {
930
- throw new Error(`Failed to accept invite: ${error.message}`);
931
- }
932
- }
933
- async updateMemberRole(projectId, memberId, role) {
934
- this._requireReady("updateMemberRole");
935
- if (!projectId || !memberId || !role) {
936
- throw new Error("Project ID, member ID, and role are required");
937
- }
938
- try {
939
- const response = await this._request(`/projects/${projectId}/members/${memberId}`, {
940
- method: "PATCH",
941
- body: JSON.stringify({ role }),
942
- methodName: "updateMemberRole"
943
- });
944
- if (response.success) {
945
- return response.data;
946
- }
947
- throw new Error(response.message);
948
- } catch (error) {
949
- throw new Error(`Failed to update member role: ${error.message}`);
950
- }
951
- }
952
- async removeMember(projectId, memberId) {
953
- this._requireReady("removeMember");
954
- if (!projectId || !memberId) {
955
- throw new Error("Project ID and member ID are required");
956
- }
957
- try {
958
- const response = await this._request(`/projects/${projectId}/members/${memberId}`, {
959
- method: "DELETE",
960
- methodName: "removeMember"
961
- });
962
- if (response.success) {
963
- return response.data;
964
- }
965
- throw new Error(response.message);
966
- } catch (error) {
967
- throw new Error(`Failed to remove member: ${error.message}`);
968
- }
969
- }
970
- // ==================== PROJECT LIBRARY METHODS ====================
971
- async getAvailableLibraries(params = {}) {
972
- this._requireReady("getAvailableLibraries");
973
- const queryParams = new URLSearchParams(params).toString();
974
- try {
975
- const response = await this._request(`/projects/libraries/available?${queryParams}`, {
976
- method: "GET",
977
- methodName: "getAvailableLibraries"
978
- });
979
- if (response.success) {
980
- return response.data;
981
- }
982
- throw new Error(response.message);
983
- } catch (error) {
984
- throw new Error(`Failed to get available libraries: ${error.message}`);
985
- }
986
- }
987
- async getProjectLibraries(projectId) {
988
- this._requireReady("getProjectLibraries");
989
- if (!projectId) {
990
- throw new Error("Project ID is required");
991
- }
992
- try {
993
- const response = await this._request(`/projects/${projectId}/libraries`, {
994
- method: "GET",
995
- methodName: "getProjectLibraries"
996
- });
997
- if (response.success) {
998
- return response.data;
999
- }
1000
- throw new Error(response.message);
1001
- } catch (error) {
1002
- throw new Error(`Failed to get project libraries: ${error.message}`);
1003
- }
1004
- }
1005
- async addProjectLibraries(projectId, libraryIds) {
1006
- this._requireReady("addProjectLibraries");
1007
- if (!projectId || !libraryIds) {
1008
- throw new Error("Project ID and library IDs are required");
1009
- }
1010
- try {
1011
- const response = await this._request(`/projects/${projectId}/libraries`, {
1012
- method: "POST",
1013
- body: JSON.stringify({ libraryIds }),
1014
- methodName: "addProjectLibraries"
1015
- });
1016
- if (response.success) {
1017
- return response.data;
1018
- }
1019
- throw new Error(response.message);
1020
- } catch (error) {
1021
- throw new Error(`Failed to add project libraries: ${error.message}`);
1022
- }
1023
- }
1024
- async removeProjectLibraries(projectId, libraryIds) {
1025
- this._requireReady("removeProjectLibraries");
1026
- if (!projectId || !libraryIds) {
1027
- throw new Error("Project ID and library IDs are required");
1028
- }
1029
- try {
1030
- const response = await this._request(`/projects/${projectId}/libraries`, {
1031
- method: "DELETE",
1032
- body: JSON.stringify({ libraryIds }),
1033
- methodName: "removeProjectLibraries"
1034
- });
1035
- if (response.success) {
1036
- return response.data;
1037
- }
1038
- throw new Error(response.message);
1039
- } catch (error) {
1040
- throw new Error(`Failed to remove project libraries: ${error.message}`);
1041
- }
1042
- }
1043
- // ==================== FILE METHODS ====================
1044
- async uploadFile(file, options = {}) {
1045
- this._requireReady("uploadFile");
1046
- if (!file) {
1047
- throw new Error("File is required for upload");
1048
- }
1049
- const formData = new FormData();
1050
- formData.append("file", file);
1051
- if (options.projectId) {
1052
- formData.append("projectId", options.projectId);
1053
- }
1054
- if (options.tags) {
1055
- formData.append("tags", JSON.stringify(options.tags));
1056
- }
1057
- if (options.visibility) {
1058
- formData.append("visibility", options.visibility || "public");
1059
- }
1060
- if (options.metadata) {
1061
- formData.append("metadata", JSON.stringify(options.metadata));
1062
- }
1063
- try {
1064
- const response = await this._request("/files/upload", {
1065
- method: "POST",
1066
- body: formData,
1067
- headers: {},
1068
- // Let browser set Content-Type for FormData
1069
- methodName: "uploadFile"
1070
- });
1071
- if (!response.success) {
1072
- throw new Error(response.message);
1073
- }
1074
- return {
1075
- id: response.data.id,
1076
- src: `${this._apiUrl}/core/files/public/${response.data.id}/download`,
1077
- success: true,
1078
- message: response.message
1079
- };
1080
- } catch (error) {
1081
- throw new Error(`File upload failed: ${error.message}`);
1082
- }
1083
- }
1084
- async updateProjectIcon(projectId, iconFile) {
1085
- this._requireReady("updateProjectIcon");
1086
- if (!projectId || !iconFile) {
1087
- throw new Error("Project ID and icon file are required");
1088
- }
1089
- const formData = new FormData();
1090
- formData.append("icon", iconFile);
1091
- formData.append("projectId", projectId);
1092
- try {
1093
- const response = await this._request("/files/upload-project-icon", {
1094
- method: "POST",
1095
- body: formData,
1096
- headers: {},
1097
- // Let browser set Content-Type for FormData
1098
- methodName: "updateProjectIcon"
1099
- });
1100
- if (response.success) {
1101
- return response.data;
1102
- }
1103
- throw new Error(response.message);
1104
- } catch (error) {
1105
- throw new Error(`Failed to update project icon: ${error.message}`);
1106
- }
1107
- }
1108
- // ==================== PAYMENT METHODS ====================
1109
- async checkout(options = {}) {
1110
- this._requireReady("checkout");
1111
- const {
1112
- projectId,
1113
- seats = 1,
1114
- price = "starter_monthly",
1115
- successUrl = `${window.location.origin}/success`,
1116
- cancelUrl = `${window.location.origin}/pricing`
1117
- } = options;
1118
- if (!projectId) {
1119
- throw new Error("Project ID is required for checkout");
1120
- }
1121
- try {
1122
- const response = await this._request("/payments/checkout", {
1123
- method: "POST",
1124
- body: JSON.stringify({
1125
- projectId,
1126
- seats,
1127
- price,
1128
- successUrl,
1129
- cancelUrl
1130
- }),
1131
- methodName: "checkout"
1132
- });
1133
- if (response.success) {
1134
- return response.data;
1135
- }
1136
- throw new Error(response.message);
1137
- } catch (error) {
1138
- throw new Error(`Failed to checkout: ${error.message}`);
1139
- }
1140
- }
1141
- async getSubscriptionStatus(projectId) {
1142
- this._requireReady("getSubscriptionStatus");
1143
- if (!projectId) {
1144
- throw new Error("Project ID is required");
1145
- }
1146
- try {
1147
- const response = await this._request(`/payments/subscription/${projectId}`, {
1148
- method: "GET",
1149
- methodName: "getSubscriptionStatus"
1150
- });
1151
- if (response.success) {
1152
- return response.data;
1153
- }
1154
- throw new Error(response.message);
1155
- } catch (error) {
1156
- throw new Error(`Failed to get subscription status: ${error.message}`);
1157
- }
1158
- }
1159
- // ==================== DNS METHODS ====================
1160
- async createDnsRecord(domain, options = {}) {
1161
- this._requireReady("createDnsRecord");
1162
- if (!domain) {
1163
- throw new Error("Domain is required");
1164
- }
1165
- try {
1166
- const response = await this._request("/dns/records", {
1167
- method: "POST",
1168
- body: JSON.stringify({ domain, ...options }),
1169
- methodName: "createDnsRecord"
1170
- });
1171
- if (response.success) {
1172
- return response.data;
1173
- }
1174
- throw new Error(response.message);
1175
- } catch (error) {
1176
- throw new Error(`Failed to create DNS record: ${error.message}`);
1177
- }
1178
- }
1179
- async getDnsRecord(domain) {
1180
- this._requireReady("getDnsRecord");
1181
- if (!domain) {
1182
- throw new Error("Domain is required");
1183
- }
1184
- try {
1185
- const response = await this._request(`/dns/records/${domain}`, {
1186
- method: "GET",
1187
- methodName: "getDnsRecord"
1188
- });
1189
- if (response.success) {
1190
- return response.data;
1191
- }
1192
- throw new Error(response.message);
1193
- } catch (error) {
1194
- throw new Error(`Failed to get DNS record: ${error.message}`);
1195
- }
1196
- }
1197
- async removeDnsRecord(domain) {
1198
- this._requireReady("removeDnsRecord");
1199
- if (!domain) {
1200
- throw new Error("Domain is required");
1201
- }
1202
- try {
1203
- const response = await this._request(`/dns/records/${domain}`, {
1204
- method: "DELETE",
1205
- methodName: "removeDnsRecord"
1206
- });
1207
- if (response.success) {
1208
- return response.data;
1209
- }
1210
- throw new Error(response.message);
1211
- } catch (error) {
1212
- throw new Error(`Failed to remove DNS record: ${error.message}`);
1213
- }
1214
- }
1215
- async setProjectDomains(projectKey, customDomain, hasCustomDomainAccess = false) {
1216
- this._requireReady("setProjectDomains");
1217
- if (!projectKey) {
1218
- throw new Error("Project key is required");
1219
- }
1220
- try {
1221
- const response = await this._request("/dns/project-domains", {
1222
- method: "POST",
1223
- body: JSON.stringify({
1224
- projectKey,
1225
- customDomain,
1226
- hasCustomDomainAccess
1227
- }),
1228
- methodName: "setProjectDomains"
1229
- });
1230
- if (response.success) {
1231
- return response.data;
1232
- }
1233
- throw new Error(response.message);
1234
- } catch (error) {
1235
- throw new Error(`Failed to set project domains: ${error.message}`);
1236
- }
1237
- }
1238
- // ==================== UTILITY METHODS ====================
1239
- async getHealthStatus() {
1240
- try {
1241
- const response = await this._request("/health", {
1242
- method: "GET",
1243
- methodName: "getHealthStatus"
1244
- });
1245
- if (response.success) {
1246
- return response.data;
1247
- }
1248
- throw new Error(response.message);
1249
- } catch (error) {
1250
- throw new Error(`Failed to get health status: ${error.message}`);
1251
- }
1252
- }
1253
- // ==================== PROJECT DATA METHODS (SYMSTORY REPLACEMENT) ====================
1254
- /**
1255
- * Apply changes to a project, creating a new version
1256
- * Replaces: SymstoryService.updateData()
1257
- */
1258
- async applyProjectChanges(projectId, changes, options = {}) {
1259
- this._requireReady("applyProjectChanges");
1260
- if (!projectId) {
1261
- throw new Error("Project ID is required");
1262
- }
1263
- if (!Array.isArray(changes)) {
1264
- throw new Error("Changes must be an array");
1265
- }
1266
- const {
1267
- message,
1268
- branch = "main",
1269
- type = "patch"
1270
- } = options;
1271
- try {
1272
- const response = await this._request(`/projects/${projectId}/changes`, {
1273
- method: "POST",
1274
- body: JSON.stringify({
1275
- changes,
1276
- message,
1277
- branch,
1278
- type
1279
- }),
1280
- methodName: "applyProjectChanges"
1281
- });
1282
- if (response.success) {
1283
- return response.data;
1284
- }
1285
- throw new Error(response.message);
1286
- } catch (error) {
1287
- throw new Error(`Failed to apply project changes: ${error.message}`);
1288
- }
1289
- }
1290
- /**
1291
- * Get current project data for a specific branch
1292
- * Replaces: SymstoryService.getData()
1293
- */
1294
- async getProjectData(projectId, options = {}) {
1295
- this._requireReady("getProjectData");
1296
- if (!projectId) {
1297
- throw new Error("Project ID is required");
1298
- }
1299
- const {
1300
- branch = "main",
1301
- version = "latest",
1302
- includeHistory = false
1303
- } = options;
1304
- const queryParams = new URLSearchParams({
1305
- branch,
1306
- version,
1307
- includeHistory: includeHistory.toString()
1308
- }).toString();
1309
- try {
1310
- const response = await this._request(`/projects/${projectId}/data?${queryParams}`, {
1311
- method: "GET",
1312
- methodName: "getProjectData"
1313
- });
1314
- if (response.success) {
1315
- return response.data;
1316
- }
1317
- throw new Error(response.message);
1318
- } catch (error) {
1319
- throw new Error(`Failed to get project data: ${error.message}`);
1320
- }
1321
- }
1322
- /**
1323
- * Get project versions with pagination
1324
- */
1325
- async getProjectVersions(projectId, options = {}) {
1326
- this._requireReady("getProjectVersions");
1327
- if (!projectId) {
1328
- throw new Error("Project ID is required");
1329
- }
1330
- const {
1331
- branch = "main",
1332
- page = 1,
1333
- limit = 50
1334
- } = options;
1335
- const queryParams = new URLSearchParams({
1336
- branch,
1337
- page: page.toString(),
1338
- limit: limit.toString()
1339
- }).toString();
1340
- try {
1341
- const response = await this._request(`/projects/${projectId}/versions?${queryParams}`, {
1342
- method: "GET",
1343
- methodName: "getProjectVersions"
1344
- });
1345
- if (response.success) {
1346
- return response.data;
1347
- }
1348
- throw new Error(response.message);
1349
- } catch (error) {
1350
- throw new Error(`Failed to get project versions: ${error.message}`);
1351
- }
1352
- }
1353
- /**
1354
- * Restore project to a previous version
1355
- * Replaces: SymstoryService.restoreVersion()
1356
- */
1357
- async restoreProjectVersion(projectId, version, options = {}) {
1358
- this._requireReady("restoreProjectVersion");
1359
- if (!projectId) {
1360
- throw new Error("Project ID is required");
1361
- }
1362
- if (!version) {
1363
- throw new Error("Version is required");
1364
- }
1365
- const {
1366
- message,
1367
- branch = "main",
1368
- type = "patch"
1369
- } = options;
1370
- try {
1371
- const response = await this._request(`/projects/${projectId}/restore`, {
1372
- method: "POST",
1373
- body: JSON.stringify({
1374
- version,
1375
- message,
1376
- branch,
1377
- type
1378
- }),
1379
- methodName: "restoreProjectVersion"
1380
- });
1381
- if (response.success) {
1382
- return response.data;
1383
- }
1384
- throw new Error(response.message);
1385
- } catch (error) {
1386
- throw new Error(`Failed to restore project version: ${error.message}`);
1387
- }
1388
- }
1389
- /**
1390
- * Helper method to update a single item in the project
1391
- * Convenience wrapper around applyProjectChanges
1392
- */
1393
- async updateProjectItem(projectId, path, value, options = {}) {
1394
- const changes = [["update", path, value]];
1395
- const message = options.message || `Updated ${Array.isArray(path) ? path.join(".") : path}`;
1396
- return await this.applyProjectChanges(projectId, changes, {
1397
- ...options,
1398
- message
1399
- });
1400
- }
1401
- /**
1402
- * Helper method to delete an item from the project
1403
- * Convenience wrapper around applyProjectChanges
1404
- */
1405
- async deleteProjectItem(projectId, path, options = {}) {
1406
- const changes = [["delete", path]];
1407
- const message = options.message || `Deleted ${Array.isArray(path) ? path.join(".") : path}`;
1408
- return await this.applyProjectChanges(projectId, changes, {
1409
- ...options,
1410
- message
1411
- });
1412
- }
1413
- /**
1414
- * Helper method to set a value in the project (alias for update)
1415
- * Convenience wrapper around applyProjectChanges
1416
- */
1417
- async setProjectValue(projectId, path, value, options = {}) {
1418
- const changes = [["set", path, value]];
1419
- const message = options.message || `Set ${Array.isArray(path) ? path.join(".") : path}`;
1420
- return await this.applyProjectChanges(projectId, changes, {
1421
- ...options,
1422
- message
1423
- });
1424
- }
1425
- /**
1426
- * Helper method to add multiple items to the project
1427
- * Convenience wrapper around applyProjectChanges
1428
- */
1429
- async addProjectItems(projectId, items, options = {}) {
1430
- const changes = items.map((item) => {
1431
- const [type, data] = item;
1432
- const { value, ...schema } = data;
1433
- return [
1434
- ["update", [type, data.key], value],
1435
- ["update", ["schema", type, data.key], schema]
1436
- ];
1437
- }).flat();
1438
- const message = options.message || `Added ${items.length} items`;
1439
- return await this.applyProjectChanges(projectId, changes, {
1440
- ...options,
1441
- message
1442
- });
1443
- }
1444
- /**
1445
- * Helper method to get specific data from project by path
1446
- * Convenience wrapper that gets project data and extracts specific path
1447
- */
1448
- async getProjectItemByPath(projectId, path, options = {}) {
1449
- const projectData = await this.getProjectData(projectId, options);
1450
- if (!(projectData == null ? void 0 : projectData.data)) {
1451
- return null;
1452
- }
1453
- let current = projectData.data;
1454
- const pathArray = Array.isArray(path) ? path : [path];
1455
- for (const segment of pathArray) {
1456
- if (current && typeof current === "object" && segment in current) {
1457
- current = current[segment];
1458
- } else {
1459
- return null;
1460
- }
1461
- }
1462
- return current;
1463
- }
1464
- // ==================== PULL REQUEST METHODS ====================
1465
- /**
1466
- * Create a new pull request
1467
- */
1468
- async createPullRequest(projectId, pullRequestData) {
1469
- this._requireReady("createPullRequest");
1470
- if (!projectId) {
1471
- throw new Error("Project ID is required");
1472
- }
1473
- if (!pullRequestData.source || !pullRequestData.target || !pullRequestData.title) {
1474
- throw new Error("Source branch, target branch, and title are required");
1475
- }
1476
- try {
1477
- const response = await this._request(`/projects/${projectId}/pull-requests`, {
1478
- method: "POST",
1479
- body: JSON.stringify(pullRequestData),
1480
- methodName: "createPullRequest"
1481
- });
1482
- if (response.success) {
1483
- return response.data;
1484
- }
1485
- throw new Error(response.message);
1486
- } catch (error) {
1487
- throw new Error(`Failed to create pull request: ${error.message}`);
1488
- }
1489
- }
1490
- /**
1491
- * List pull requests for a project with filtering options
1492
- */
1493
- async listPullRequests(projectId, options = {}) {
1494
- this._requireReady("listPullRequests");
1495
- if (!projectId) {
1496
- throw new Error("Project ID is required");
1497
- }
1498
- const {
1499
- status = "open",
1500
- source,
1501
- target,
1502
- page = 1,
1503
- limit = 20
1504
- } = options;
1505
- const queryParams = new URLSearchParams({
1506
- status,
1507
- page: page.toString(),
1508
- limit: limit.toString()
1509
- });
1510
- if (source) {
1511
- queryParams.append("source", source);
1512
- }
1513
- if (target) {
1514
- queryParams.append("target", target);
1515
- }
1516
- try {
1517
- const response = await this._request(`/projects/${projectId}/pull-requests?${queryParams.toString()}`, {
1518
- method: "GET",
1519
- methodName: "listPullRequests"
1520
- });
1521
- if (response.success) {
1522
- return response.data;
1523
- }
1524
- throw new Error(response.message);
1525
- } catch (error) {
1526
- throw new Error(`Failed to list pull requests: ${error.message}`);
1527
- }
1528
- }
1529
- /**
1530
- * Get detailed information about a specific pull request
1531
- */
1532
- async getPullRequest(projectId, prId) {
1533
- this._requireReady("getPullRequest");
1534
- if (!projectId) {
1535
- throw new Error("Project ID is required");
1536
- }
1537
- if (!prId) {
1538
- throw new Error("Pull request ID is required");
1539
- }
1540
- try {
1541
- const response = await this._request(`/projects/${projectId}/pull-requests/${prId}`, {
1542
- method: "GET",
1543
- methodName: "getPullRequest"
1544
- });
1545
- if (response.success) {
1546
- return response.data;
1547
- }
1548
- throw new Error(response.message);
1549
- } catch (error) {
1550
- throw new Error(`Failed to get pull request: ${error.message}`);
1551
- }
1552
- }
1553
- /**
1554
- * Submit a review for a pull request
1555
- */
1556
- async reviewPullRequest(projectId, prId, reviewData) {
1557
- this._requireReady("reviewPullRequest");
1558
- if (!projectId) {
1559
- throw new Error("Project ID is required");
1560
- }
1561
- if (!prId) {
1562
- throw new Error("Pull request ID is required");
1563
- }
1564
- const validStatuses = ["approved", "requested_changes", "feedback"];
1565
- if (reviewData.status && !validStatuses.includes(reviewData.status)) {
1566
- throw new Error(`Invalid review status. Must be one of: ${validStatuses.join(", ")}`);
1567
- }
1568
- try {
1569
- const response = await this._request(`/projects/${projectId}/pull-requests/${prId}/review`, {
1570
- method: "POST",
1571
- body: JSON.stringify(reviewData),
1572
- methodName: "reviewPullRequest"
1573
- });
1574
- if (response.success) {
1575
- return response.data;
1576
- }
1577
- throw new Error(response.message);
1578
- } catch (error) {
1579
- throw new Error(`Failed to review pull request: ${error.message}`);
1580
- }
1581
- }
1582
- /**
1583
- * Add a comment to an existing review thread
1584
- */
1585
- async addPullRequestComment(projectId, prId, commentData) {
1586
- this._requireReady("addPullRequestComment");
1587
- if (!projectId) {
1588
- throw new Error("Project ID is required");
1589
- }
1590
- if (!prId) {
1591
- throw new Error("Pull request ID is required");
1592
- }
1593
- if (!commentData.value) {
1594
- throw new Error("Comment value is required");
1595
- }
1596
- try {
1597
- const response = await this._request(`/projects/${projectId}/pull-requests/${prId}/comment`, {
1598
- method: "POST",
1599
- body: JSON.stringify(commentData),
1600
- methodName: "addPullRequestComment"
1601
- });
1602
- if (response.success) {
1603
- return response.data;
1604
- }
1605
- throw new Error(response.message);
1606
- } catch (error) {
1607
- throw new Error(`Failed to add pull request comment: ${error.message}`);
1608
- }
1609
- }
1610
- /**
1611
- * Merge an approved pull request
1612
- */
1613
- async mergePullRequest(projectId, prId) {
1614
- this._requireReady("mergePullRequest");
1615
- if (!projectId) {
1616
- throw new Error("Project ID is required");
1617
- }
1618
- if (!prId) {
1619
- throw new Error("Pull request ID is required");
1620
- }
1621
- try {
1622
- const response = await this._request(`/projects/${projectId}/pull-requests/${prId}/merge`, {
1623
- method: "POST",
1624
- methodName: "mergePullRequest"
1625
- });
1626
- if (response.success) {
1627
- return response.data;
1628
- }
1629
- throw new Error(response.message);
1630
- } catch (error) {
1631
- if (error.message.includes("conflicts") || error.message.includes("409")) {
1632
- throw new Error(`Pull request has merge conflicts: ${error.message}`);
1633
- }
1634
- throw new Error(`Failed to merge pull request: ${error.message}`);
1635
- }
1636
- }
1637
- /**
1638
- * Get the diff/changes for a pull request
1639
- */
1640
- async getPullRequestDiff(projectId, prId) {
1641
- this._requireReady("getPullRequestDiff");
1642
- if (!projectId) {
1643
- throw new Error("Project ID is required");
1644
- }
1645
- if (!prId) {
1646
- throw new Error("Pull request ID is required");
1647
- }
1648
- try {
1649
- const response = await this._request(`/projects/${projectId}/pull-requests/${prId}/diff`, {
1650
- method: "GET",
1651
- methodName: "getPullRequestDiff"
1652
- });
1653
- if (response.success) {
1654
- return response.data;
1655
- }
1656
- throw new Error(response.message);
1657
- } catch (error) {
1658
- throw new Error(`Failed to get pull request diff: ${error.message}`);
1659
- }
1660
- }
1661
- /**
1662
- * Helper method to create a pull request with validation
1663
- */
1664
- async createPullRequestWithValidation(projectId, data) {
1665
- const { source, target, title, description, changes } = data;
1666
- if (source === target) {
1667
- throw new Error("Source and target branches cannot be the same");
1668
- }
1669
- if (!title || title.trim().length === 0) {
1670
- throw new Error("Pull request title cannot be empty");
1671
- }
1672
- if (title.length > 200) {
1673
- throw new Error("Pull request title cannot exceed 200 characters");
1674
- }
1675
- const pullRequestData = {
1676
- source: source.trim(),
1677
- target: target.trim(),
1678
- title: title.trim(),
1679
- ...description && { description: description.trim() },
1680
- ...changes && { changes }
1681
- };
1682
- return await this.createPullRequest(projectId, pullRequestData);
1683
- }
1684
- /**
1685
- * Helper method to approve a pull request
1686
- */
1687
- async approvePullRequest(projectId, prId, comment = "") {
1688
- const reviewData = {
1689
- status: "approved",
1690
- ...comment && {
1691
- threads: [{
1692
- comment,
1693
- type: "praise"
1694
- }]
1695
- }
1696
- };
1697
- return await this.reviewPullRequest(projectId, prId, reviewData);
1698
- }
1699
- /**
1700
- * Helper method to request changes on a pull request
1701
- */
1702
- async requestPullRequestChanges(projectId, prId, threads = []) {
1703
- if (!threads || threads.length === 0) {
1704
- throw new Error("Must provide specific feedback when requesting changes");
1705
- }
1706
- const reviewData = {
1707
- status: "requested_changes",
1708
- threads
1709
- };
1710
- return await this.reviewPullRequest(projectId, prId, reviewData);
1711
- }
1712
- /**
1713
- * Helper method to get pull requests by status
1714
- */
1715
- async getOpenPullRequests(projectId, options = {}) {
1716
- return await this.listPullRequests(projectId, { ...options, status: "open" });
1717
- }
1718
- async getClosedPullRequests(projectId, options = {}) {
1719
- return await this.listPullRequests(projectId, { ...options, status: "closed" });
1720
- }
1721
- async getMergedPullRequests(projectId, options = {}) {
1722
- return await this.listPullRequests(projectId, { ...options, status: "merged" });
1723
- }
1724
- /**
1725
- * Helper method to check if a pull request is canMerge
1726
- */
1727
- async isPullRequestMergeable(projectId, prId) {
1728
- var _a;
1729
- try {
1730
- const prData = await this.getPullRequest(projectId, prId);
1731
- return ((_a = prData == null ? void 0 : prData.data) == null ? void 0 : _a.canMerge) || false;
1732
- } catch (error) {
1733
- throw new Error(`Failed to check pull request mergeability: ${error.message}`);
1734
- }
1735
- }
1736
- /**
1737
- * Helper method to get pull request status summary
1738
- */
1739
- async getPullRequestStatusSummary(projectId, prId) {
1740
- var _a, _b, _c;
1741
- try {
1742
- const prData = await this.getPullRequest(projectId, prId);
1743
- const pr = prData == null ? void 0 : prData.data;
1744
- if (!pr) {
1745
- throw new Error("Pull request not found");
1746
- }
1747
- return {
1748
- status: pr.status,
1749
- reviewStatus: pr.reviewStatus,
1750
- canMerge: pr.canMerge,
1751
- hasConflicts: !pr.canMerge,
1752
- reviewCount: ((_a = pr.reviews) == null ? void 0 : _a.length) || 0,
1753
- approvedReviews: ((_b = pr.reviews) == null ? void 0 : _b.filter((r) => r.status === "approved").length) || 0,
1754
- changesRequested: ((_c = pr.reviews) == null ? void 0 : _c.filter((r) => r.status === "requested_changes").length) || 0
1755
- };
1756
- } catch (error) {
1757
- throw new Error(`Failed to get pull request status summary: ${error.message}`);
1758
- }
1759
- }
1760
- // ==================== BRANCH MANAGEMENT METHODS ====================
1761
- /**
1762
- * Get all branches for a project
1763
- */
1764
- async listBranches(projectId) {
1765
- this._requireReady("listBranches");
1766
- if (!projectId) {
1767
- throw new Error("Project ID is required");
1768
- }
1769
- try {
1770
- const response = await this._request(`/projects/${projectId}/branches`, {
1771
- method: "GET",
1772
- methodName: "listBranches"
1773
- });
1774
- if (response.success) {
1775
- return response.data;
1776
- }
1777
- throw new Error(response.message);
1778
- } catch (error) {
1779
- throw new Error(`Failed to list branches: ${error.message}`);
1780
- }
1781
- }
1782
- /**
1783
- * Create a new branch from an existing branch
1784
- */
1785
- async createBranch(projectId, branchData) {
1786
- this._requireReady("createBranch");
1787
- if (!projectId) {
1788
- throw new Error("Project ID is required");
1789
- }
1790
- if (!branchData.name) {
1791
- throw new Error("Branch name is required");
1792
- }
1793
- const { name, source = "main" } = branchData;
1794
- try {
1795
- const response = await this._request(`/projects/${projectId}/branches`, {
1796
- method: "POST",
1797
- body: JSON.stringify({ name, source }),
1798
- methodName: "createBranch"
1799
- });
1800
- if (response.success) {
1801
- return response.data;
1802
- }
1803
- throw new Error(response.message);
1804
- } catch (error) {
1805
- throw new Error(`Failed to create branch: ${error.message}`);
1806
- }
1807
- }
1808
- /**
1809
- * Delete a branch (cannot delete main branch)
1810
- */
1811
- async deleteBranch(projectId, branchName) {
1812
- this._requireReady("deleteBranch");
1813
- if (!projectId) {
1814
- throw new Error("Project ID is required");
1815
- }
1816
- if (!branchName) {
1817
- throw new Error("Branch name is required");
1818
- }
1819
- if (branchName === "main") {
1820
- throw new Error("Cannot delete main branch");
1821
- }
1822
- try {
1823
- const response = await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}`, {
1824
- method: "DELETE",
1825
- methodName: "deleteBranch"
1826
- });
1827
- if (response.success) {
1828
- return response.data;
1829
- }
1830
- throw new Error(response.message);
1831
- } catch (error) {
1832
- throw new Error(`Failed to delete branch: ${error.message}`);
1833
- }
1834
- }
1835
- /**
1836
- * Rename a branch (cannot rename main branch)
1837
- */
1838
- async renameBranch(projectId, branchName, newName) {
1839
- this._requireReady("renameBranch");
1840
- if (!projectId) {
1841
- throw new Error("Project ID is required");
1842
- }
1843
- if (!branchName) {
1844
- throw new Error("Current branch name is required");
1845
- }
1846
- if (!newName) {
1847
- throw new Error("New branch name is required");
1848
- }
1849
- if (branchName === "main") {
1850
- throw new Error("Cannot rename main branch");
1851
- }
1852
- try {
1853
- const response = await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}/rename`, {
1854
- method: "POST",
1855
- body: JSON.stringify({ newName }),
1856
- methodName: "renameBranch"
1857
- });
1858
- if (response.success) {
1859
- return response.data;
1860
- }
1861
- throw new Error(response.message);
1862
- } catch (error) {
1863
- throw new Error(`Failed to rename branch: ${error.message}`);
1864
- }
1865
- }
1866
- /**
1867
- * Get changes/diff for a branch compared to another version
1868
- */
1869
- async getBranchChanges(projectId, branchName = "main", options = {}) {
1870
- this._requireReady("getBranchChanges");
1871
- if (!projectId) {
1872
- throw new Error("Project ID is required");
1873
- }
1874
- if (!branchName) {
1875
- throw new Error("Branch name is required");
1876
- }
1877
- const { versionId, versionValue, target } = options;
1878
- const queryParams = new URLSearchParams();
1879
- if (versionId) {
1880
- queryParams.append("versionId", versionId);
1881
- }
1882
- if (versionValue) {
1883
- queryParams.append("versionValue", versionValue);
1884
- }
1885
- if (target) {
1886
- queryParams.append("target", target);
1887
- }
1888
- const queryString = queryParams.toString();
1889
- const url = `/projects/${projectId}/branches/${encodeURIComponent(branchName)}/changes${queryString ? `?${queryString}` : ""}`;
1890
- try {
1891
- const response = await this._request(url, {
1892
- method: "GET",
1893
- methodName: "getBranchChanges"
1894
- });
1895
- if (response.success) {
1896
- return response.data;
1897
- }
1898
- throw new Error(response.message);
1899
- } catch (error) {
1900
- throw new Error(`Failed to get branch changes: ${error.message}`);
1901
- }
1902
- }
1903
- /**
1904
- * Merge changes between branches (preview or commit)
1905
- */
1906
- async mergeBranch(projectId, branchName, mergeData = {}) {
1907
- this._requireReady("mergeBranch");
1908
- if (!projectId) {
1909
- throw new Error("Project ID is required");
1910
- }
1911
- if (!branchName) {
1912
- throw new Error("Source branch name is required");
1913
- }
1914
- const {
1915
- target = "main",
1916
- message,
1917
- type = "patch",
1918
- commit = false,
1919
- changes
1920
- } = mergeData;
1921
- const requestBody = {
1922
- target,
1923
- type,
1924
- commit,
1925
- ...message && { message },
1926
- ...changes && { changes }
1927
- };
1928
- try {
1929
- const response = await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}/merge`, {
1930
- method: "POST",
1931
- body: JSON.stringify(requestBody),
1932
- methodName: "mergeBranch"
1933
- });
1934
- if (response.success) {
1935
- return response.data;
1936
- }
1937
- throw new Error(response.message);
1938
- } catch (error) {
1939
- if (error.message.includes("conflicts") || error.message.includes("409")) {
1940
- throw new Error(`Merge conflicts detected: ${error.message}`);
1941
- }
1942
- throw new Error(`Failed to merge branch: ${error.message}`);
1943
- }
1944
- }
1945
- /**
1946
- * Reset a branch to a clean state
1947
- */
1948
- async resetBranch(projectId, branchName) {
1949
- this._requireReady("resetBranch");
1950
- if (!projectId) {
1951
- throw new Error("Project ID is required");
1952
- }
1953
- if (!branchName) {
1954
- throw new Error("Branch name is required");
1955
- }
1956
- try {
1957
- const response = await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}/reset`, {
1958
- method: "POST",
1959
- methodName: "resetBranch"
1960
- });
1961
- if (response.success) {
1962
- return response.data;
1963
- }
1964
- throw new Error(response.message);
1965
- } catch (error) {
1966
- throw new Error(`Failed to reset branch: ${error.message}`);
1967
- }
1968
- }
1969
- /**
1970
- * Publish a specific version as the live version
1971
- */
1972
- async publishVersion(projectId, publishData) {
1973
- this._requireReady("publishVersion");
1974
- if (!projectId) {
1975
- throw new Error("Project ID is required");
1976
- }
1977
- if (!publishData.version) {
1978
- throw new Error("Version is required");
1979
- }
1980
- const { version, branch = "main" } = publishData;
1981
- try {
1982
- const response = await this._request(`/projects/${projectId}/publish`, {
1983
- method: "POST",
1984
- body: JSON.stringify({ version, branch }),
1985
- methodName: "publishVersion"
1986
- });
1987
- if (response.success) {
1988
- return response.data;
1989
- }
1990
- throw new Error(response.message);
1991
- } catch (error) {
1992
- throw new Error(`Failed to publish version: ${error.message}`);
1993
- }
1994
- }
1995
- // ==================== BRANCH HELPER METHODS ====================
1996
- /**
1997
- * Helper method to create a branch with validation
1998
- */
1999
- async createBranchWithValidation(projectId, name, source = "main") {
2000
- if (!name || name.trim().length === 0) {
2001
- throw new Error("Branch name cannot be empty");
2002
- }
2003
- if (name.includes(" ")) {
2004
- throw new Error("Branch name cannot contain spaces");
2005
- }
2006
- if (name === "main") {
2007
- throw new Error('Cannot create a branch named "main"');
2008
- }
2009
- const sanitizedName = name.trim().toLowerCase().replace(/[^a-z0-9-_]/gu, "-");
2010
- return await this.createBranch(projectId, {
2011
- name: sanitizedName,
2012
- source
2013
- });
2014
- }
2015
- /**
2016
- * Helper method to check if a branch exists
2017
- */
2018
- async branchExists(projectId, branchName) {
2019
- var _a;
2020
- try {
2021
- const branches = await this.listBranches(projectId);
2022
- return ((_a = branches == null ? void 0 : branches.data) == null ? void 0 : _a.includes(branchName)) || false;
2023
- } catch (error) {
2024
- throw new Error(`Failed to check if branch exists: ${error.message}`);
2025
- }
2026
- }
2027
- /**
2028
- * Helper method to preview merge without committing
2029
- */
2030
- async previewMerge(projectId, sourceBranch, targetBranch = "main") {
2031
- return await this.mergeBranch(projectId, sourceBranch, {
2032
- target: targetBranch,
2033
- commit: false
2034
- });
2035
- }
2036
- /**
2037
- * Helper method to commit merge after preview
2038
- */
2039
- async commitMerge(projectId, sourceBranch, options = {}) {
2040
- const {
2041
- target = "main",
2042
- message = `Merge ${sourceBranch} into ${target}`,
2043
- type = "patch",
2044
- changes
2045
- } = options;
2046
- return await this.mergeBranch(projectId, sourceBranch, {
2047
- target,
2048
- message,
2049
- type,
2050
- commit: true,
2051
- changes
2052
- });
2053
- }
2054
- /**
2055
- * Helper method to create a feature branch from main
2056
- */
2057
- async createFeatureBranch(projectId, featureName) {
2058
- const branchName = `feature/${featureName.toLowerCase().replace(/[^a-z0-9-]/gu, "-")}`;
2059
- return await this.createBranch(projectId, {
2060
- name: branchName,
2061
- source: "main"
2062
- });
2063
- }
2064
- /**
2065
- * Helper method to create a hotfix branch from main
2066
- */
2067
- async createHotfixBranch(projectId, hotfixName) {
2068
- const branchName = `hotfix/${hotfixName.toLowerCase().replace(/[^a-z0-9-]/gu, "-")}`;
2069
- return await this.createBranch(projectId, {
2070
- name: branchName,
2071
- source: "main"
2072
- });
2073
- }
2074
- /**
2075
- * Helper method to get branch status summary
2076
- */
2077
- async getBranchStatus(projectId, branchName) {
2078
- var _a, _b, _c;
2079
- try {
2080
- const [branches, changes] = await Promise.all([
2081
- this.listBranches(projectId),
2082
- this.getBranchChanges(projectId, branchName).catch(() => null)
2083
- ]);
2084
- const exists = ((_a = branches == null ? void 0 : branches.data) == null ? void 0 : _a.includes(branchName)) || false;
2085
- const hasChanges = ((_b = changes == null ? void 0 : changes.data) == null ? void 0 : _b.length) > 0;
2086
- return {
2087
- exists,
2088
- hasChanges,
2089
- changeCount: ((_c = changes == null ? void 0 : changes.data) == null ? void 0 : _c.length) || 0,
2090
- canDelete: exists && branchName !== "main",
2091
- canRename: exists && branchName !== "main"
2092
- };
2093
- } catch (error) {
2094
- throw new Error(`Failed to get branch status: ${error.message}`);
2095
- }
2096
- }
2097
- /**
2098
- * Helper method to safely delete a branch with confirmation
2099
- */
2100
- async deleteBranchSafely(projectId, branchName, options = {}) {
2101
- const { force = false } = options;
2102
- if (!force) {
2103
- const status = await this.getBranchStatus(projectId, branchName);
2104
- if (!status.exists) {
2105
- throw new Error(`Branch '${branchName}' does not exist`);
2106
- }
2107
- if (!status.canDelete) {
2108
- throw new Error(`Branch '${branchName}' cannot be deleted`);
2109
- }
2110
- if (status.hasChanges) {
2111
- throw new Error(`Branch '${branchName}' has uncommitted changes. Use force option to delete anyway.`);
2112
- }
2113
- }
2114
- return await this.deleteBranch(projectId, branchName);
2115
- }
2116
- // ==================== ADMIN METHODS ====================
2117
- /**
2118
- * Get admin users list with comprehensive filtering and search capabilities
2119
- * Requires admin or super_admin global role
2120
- */
2121
- async getAdminUsers(params = {}) {
2122
- this._requireReady("getAdminUsers");
2123
- const {
2124
- emails,
2125
- ids,
2126
- query,
2127
- status,
2128
- page = 1,
2129
- limit = 50,
2130
- sort = { field: "createdAt", order: "desc" }
2131
- } = params;
2132
- const queryParams = new URLSearchParams();
2133
- if (emails) {
2134
- queryParams.append("emails", emails);
2135
- }
2136
- if (ids) {
2137
- queryParams.append("ids", ids);
2138
- }
2139
- if (query) {
2140
- queryParams.append("query", query);
2141
- }
2142
- if (status) {
2143
- queryParams.append("status", status);
2144
- }
2145
- if (page) {
2146
- queryParams.append("page", page.toString());
2147
- }
2148
- if (limit) {
2149
- queryParams.append("limit", limit.toString());
2150
- }
2151
- if (sort && sort.field) {
2152
- queryParams.append("sort[field]", sort.field);
2153
- queryParams.append("sort[order]", sort.order || "desc");
2154
- }
2155
- const queryString = queryParams.toString();
2156
- const url = `/users/admin/users${queryString ? `?${queryString}` : ""}`;
2157
- try {
2158
- const response = await this._request(url, {
2159
- method: "GET",
2160
- methodName: "getAdminUsers"
2161
- });
2162
- if (response.success) {
2163
- return response.data;
2164
- }
2165
- throw new Error(response.message);
2166
- } catch (error) {
2167
- throw new Error(`Failed to get admin users: ${error.message}`);
2168
- }
2169
- }
2170
- /**
2171
- * Assign projects to a specific user
2172
- * Requires admin or super_admin global role
2173
- */
2174
- async assignProjectsToUser(userId, options = {}) {
2175
- this._requireReady("assignProjectsToUser");
2176
- if (!userId) {
2177
- throw new Error("User ID is required");
2178
- }
2179
- const {
2180
- projectIds,
2181
- role = "guest"
2182
- } = options;
2183
- const requestBody = {
2184
- userId,
2185
- role
2186
- };
2187
- if (projectIds && Array.isArray(projectIds)) {
2188
- requestBody.projectIds = projectIds;
2189
- }
2190
- try {
2191
- const response = await this._request("/assign-projects", {
2192
- method: "POST",
2193
- body: JSON.stringify(requestBody),
2194
- methodName: "assignProjectsToUser"
2195
- });
2196
- if (response.success) {
2197
- return response.data;
2198
- }
2199
- throw new Error(response.message);
2200
- } catch (error) {
2201
- throw new Error(`Failed to assign projects to user: ${error.message}`);
2202
- }
2203
- }
2204
- /**
2205
- * Helper method for admin users search
2206
- */
2207
- async searchAdminUsers(searchQuery, options = {}) {
2208
- return await this.getAdminUsers({
2209
- query: searchQuery,
2210
- ...options
2211
- });
2212
- }
2213
- /**
2214
- * Helper method to get admin users by email list
2215
- */
2216
- async getAdminUsersByEmails(emails, options = {}) {
2217
- const emailList = Array.isArray(emails) ? emails.join(",") : emails;
2218
- return await this.getAdminUsers({
2219
- emails: emailList,
2220
- ...options
2221
- });
2222
- }
2223
- /**
2224
- * Helper method to get admin users by ID list
2225
- */
2226
- async getAdminUsersByIds(ids, options = {}) {
2227
- const idList = Array.isArray(ids) ? ids.join(",") : ids;
2228
- return await this.getAdminUsers({
2229
- ids: idList,
2230
- ...options
2231
- });
2232
- }
2233
- /**
2234
- * Helper method to assign specific projects to a user with a specific role
2235
- */
2236
- async assignSpecificProjectsToUser(userId, projectIds, role = "guest") {
2237
- if (!Array.isArray(projectIds) || projectIds.length === 0) {
2238
- throw new Error("Project IDs must be a non-empty array");
2239
- }
2240
- return await this.assignProjectsToUser(userId, {
2241
- projectIds,
2242
- role
2243
- });
2244
- }
2245
- /**
2246
- * Helper method to assign all projects to a user with a specific role
2247
- */
2248
- async assignAllProjectsToUser(userId, role = "guest") {
2249
- return await this.assignProjectsToUser(userId, {
2250
- role
2251
- });
2252
- }
2253
- // Cleanup
2254
- destroy() {
2255
- if (this._tokenManager) {
2256
- this._tokenManager.destroy();
2257
- this._tokenManager = null;
2258
- }
2259
- this._client = null;
2260
- this._initialized = false;
2261
- this._setReady(false);
2262
- }
2263
- }
2264
- export {
2265
- CoreService
2266
- };