@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
@@ -1,2827 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
-
5
- // src/services/BaseService.js
6
- var BaseService = class {
7
- constructor({ context, options } = {}) {
8
- this._context = context || {};
9
- this._options = options || {};
10
- this._ready = false;
11
- this._error = null;
12
- }
13
- // Initialize service
14
- init() {
15
- throw new Error("init() must be implemented by service");
16
- }
17
- // Update context
18
- updateContext(context) {
19
- this._context = { ...this._context, ...context };
20
- }
21
- // Get service status
22
- getStatus() {
23
- return {
24
- ready: this._ready,
25
- error: this._error,
26
- context: { ...this._context }
27
- };
28
- }
29
- // Check if service is ready
30
- isReady() {
31
- return this._ready;
32
- }
33
- // Protected helper methods
34
- _setReady(ready = true) {
35
- this._ready = ready;
36
- this._error = null;
37
- }
38
- _setError(error) {
39
- this._ready = false;
40
- this._error = error;
41
- }
42
- _requireAuth() {
43
- if (!this._context.authToken) {
44
- throw new Error("Authentication required");
45
- }
46
- }
47
- _requireReady() {
48
- if (!this.isReady()) {
49
- throw new Error("Service not initialized");
50
- }
51
- }
52
- };
53
-
54
- // src/config/environment.js
55
- import { isDevelopment } from "@domql/utils";
56
- var CONFIG = {
57
- // Common defaults for all environments
58
- common: {
59
- // NOTE: Google client id for google auth, need to configure URLs for each environment in Google console
60
- googleClientId: "686286207466-bvd2fqs31rlm64fgich7rtpnc8ns2tqg.apps.googleusercontent.com",
61
- // Feature toggles that apply across all environments by default
62
- features: {
63
- newUserOnboarding: true,
64
- betaFeatures: false
65
- }
66
- },
67
- // Environment-specific configurations
68
- local: {
69
- // local
70
- socketUrl: "http://localhost:8080",
71
- // For socket api
72
- apiUrl: "http://localhost:8080",
73
- // For server api
74
- basedEnv: "development",
75
- // For based api
76
- basedProject: "platform-v2-sm",
77
- // For based api
78
- basedOrg: "symbols",
79
- // For based api
80
- githubClientId: "Ov23liHxyWFBxS8f1gnF",
81
- // For github api
82
- // Environment-specific feature toggles (override common)
83
- features: {
84
- betaFeatures: true
85
- // Enable beta features in local dev
86
- }
87
- },
88
- development: {
89
- socketUrl: "https://dev.api.symbols.app",
90
- apiUrl: "https://dev.api.symbols.app",
91
- githubClientId: "Ov23liHxyWFBxS8f1gnF"
92
- },
93
- testing: {
94
- socketUrl: "https://test.api.symbols.app",
95
- apiUrl: "https://test.api.symbols.app",
96
- basedEnv: "testing",
97
- basedProject: "platform-v2-sm",
98
- basedOrg: "symbols",
99
- githubClientId: "Ov23liHxyWFBxS8f1gnF"
100
- },
101
- upcoming: {
102
- socketUrl: "https://upcoming.api.symbols.app",
103
- apiUrl: "https://upcoming.api.symbols.app",
104
- githubClientId: "Ov23liWF7NvdZ056RV5J"
105
- },
106
- staging: {
107
- socketUrl: "https://staging.api.symbols.app",
108
- apiUrl: "https://staging.api.symbols.app",
109
- basedEnv: "staging",
110
- basedProject: "platform-v2-sm",
111
- basedOrg: "symbols",
112
- githubClientId: "Ov23ligwZDQVD0VfuWNa"
113
- },
114
- production: {
115
- socketUrl: "https://api.symbols.app",
116
- apiUrl: "https://api.symbols.app",
117
- basedEnv: "production",
118
- basedProject: "platform-v2-sm",
119
- basedOrg: "symbols",
120
- githubClientId: "Ov23liFAlOEIXtX3dBtR"
121
- }
122
- };
123
- var getEnvironment = () => {
124
- const env = process.env.SYMBOLS_APP_ENV || process.env.NODE_ENV;
125
- if (!CONFIG[env]) {
126
- throw new Error(`Unknown environment "${env}"`);
127
- }
128
- return env;
129
- };
130
- var getConfig = () => {
131
- try {
132
- const env = getEnvironment();
133
- const envConfig = { ...CONFIG.common, ...CONFIG[env] };
134
- const finalConfig = {
135
- ...envConfig,
136
- socketUrl: process.env.SYMBOLS_APP_SOCKET_URL || envConfig.socketUrl,
137
- apiUrl: process.env.SYMBOLS_APP_API_URL || envConfig.apiUrl,
138
- basedEnv: process.env.SYMBOLS_APP_BASED_ENV || envConfig.basedEnv,
139
- basedProject: process.env.SYMBOLS_APP_BASED_PROJECT || envConfig.basedProject,
140
- basedOrg: process.env.SYMBOLS_APP_BASED_ORG || envConfig.basedOrg,
141
- githubClientId: process.env.SYMBOLS_APP_GITHUB_CLIENT_ID || envConfig.githubClientId,
142
- isDevelopment: isDevelopment(env),
143
- isTesting: env === "testing",
144
- isStaging: env === "staging",
145
- isProduction: env === "production"
146
- // Store all environment variables for potential future use
147
- };
148
- const requiredFields = [
149
- "socketUrl",
150
- "apiUrl",
151
- "githubClientId",
152
- "googleClientId"
153
- ];
154
- const missingFields = requiredFields.filter((field) => !finalConfig[field]);
155
- if (missingFields.length > 0) {
156
- console.error(
157
- `Missing required configuration: ${missingFields.join(", ")}`
158
- );
159
- }
160
- if (finalConfig.isDevelopment) {
161
- console.log(
162
- "environment in SDK:",
163
- env || process.env.NODE_ENV || process.env.NODE_ENV
164
- );
165
- console.log(finalConfig);
166
- }
167
- return finalConfig;
168
- } catch (error) {
169
- console.error("Failed to load environment configuration:", error);
170
- return {
171
- ...CONFIG.development
172
- };
173
- }
174
- };
175
- var environment_default = getConfig();
176
-
177
- // src/utils/TokenManager.js
178
- var TokenManager = class {
179
- constructor(options = {}) {
180
- /**
181
- * Memory storage fallback for server-side rendering
182
- */
183
- __publicField(this, "_memoryStorage", {
184
- _data: {},
185
- getItem: (key) => this._memoryStorage._data[key] || null,
186
- setItem: (key, value) => {
187
- this._memoryStorage._data[key] = value;
188
- },
189
- removeItem: (key) => {
190
- delete this._memoryStorage._data[key];
191
- },
192
- clear: () => {
193
- this._memoryStorage._data = {};
194
- }
195
- });
196
- this.config = {
197
- storagePrefix: "symbols_",
198
- storageType: "localStorage",
199
- // 'localStorage' | 'sessionStorage' | 'memory'
200
- refreshBuffer: 60 * 1e3,
201
- // Refresh 1 minute before expiry
202
- maxRetries: 3,
203
- apiUrl: options.apiUrl || "/api",
204
- onTokenRefresh: options.onTokenRefresh || null,
205
- onTokenExpired: options.onTokenExpired || null,
206
- onTokenError: options.onTokenError || null,
207
- ...options
208
- };
209
- this.tokens = {
210
- accessToken: null,
211
- refreshToken: null,
212
- expiresAt: null,
213
- expiresIn: null
214
- };
215
- this.refreshPromise = null;
216
- this.refreshTimeout = null;
217
- this.retryCount = 0;
218
- this.loadTokens();
219
- }
220
- /**
221
- * Storage keys
222
- */
223
- get storageKeys() {
224
- return {
225
- accessToken: `${this.config.storagePrefix}access_token`,
226
- refreshToken: `${this.config.storagePrefix}refresh_token`,
227
- expiresAt: `${this.config.storagePrefix}expires_at`,
228
- expiresIn: `${this.config.storagePrefix}expires_in`
229
- };
230
- }
231
- /**
232
- * Get storage instance based on configuration
233
- */
234
- get storage() {
235
- if (typeof window === "undefined") {
236
- return this._memoryStorage;
237
- }
238
- switch (this.config.storageType) {
239
- case "sessionStorage":
240
- return window.sessionStorage;
241
- case "memory":
242
- return this._memoryStorage;
243
- default:
244
- return window.localStorage;
245
- }
246
- }
247
- /**
248
- * Set tokens and persist to storage
249
- */
250
- setTokens(tokenData) {
251
- const {
252
- access_token: accessToken,
253
- refresh_token: refreshToken,
254
- expires_in: expiresIn,
255
- token_type: tokenType = "Bearer"
256
- } = tokenData;
257
- if (!accessToken) {
258
- throw new Error("Access token is required");
259
- }
260
- const now = Date.now();
261
- const expiresAt = expiresIn ? now + expiresIn * 1e3 : null;
262
- this.tokens = {
263
- accessToken,
264
- refreshToken: refreshToken || this.tokens.refreshToken,
265
- expiresAt,
266
- expiresIn,
267
- tokenType
268
- };
269
- this.saveTokens();
270
- this.scheduleRefresh();
271
- if (this.config.onTokenRefresh) {
272
- this.config.onTokenRefresh(this.tokens);
273
- }
274
- return this.tokens;
275
- }
276
- /**
277
- * Get current access token
278
- */
279
- getAccessToken() {
280
- return this.tokens.accessToken;
281
- }
282
- /**
283
- * Get current refresh token
284
- */
285
- getRefreshToken() {
286
- return this.tokens.refreshToken;
287
- }
288
- /**
289
- * Get authorization header value
290
- */
291
- getAuthHeader() {
292
- const token = this.getAccessToken();
293
- if (!token) {
294
- return null;
295
- }
296
- return `${this.tokens.tokenType || "Bearer"} ${token}`;
297
- }
298
- /**
299
- * Check if access token is valid and not expired
300
- */
301
- isAccessTokenValid() {
302
- if (!this.tokens.accessToken) {
303
- return false;
304
- }
305
- if (!this.tokens.expiresAt) {
306
- return true;
307
- }
308
- const now = Date.now();
309
- const isValid = now < this.tokens.expiresAt - this.config.refreshBuffer;
310
- if (!isValid) {
311
- console.log("[TokenManager] Access token is expired or near expiry:", {
312
- now: new Date(now).toISOString(),
313
- expiresAt: new Date(this.tokens.expiresAt).toISOString(),
314
- refreshBuffer: this.config.refreshBuffer
315
- });
316
- }
317
- return isValid;
318
- }
319
- /**
320
- * Check if access token exists and is not expired (without refresh buffer)
321
- */
322
- isAccessTokenActuallyValid() {
323
- if (!this.tokens.accessToken) {
324
- return false;
325
- }
326
- if (!this.tokens.expiresAt) {
327
- return true;
328
- }
329
- const now = Date.now();
330
- return now < this.tokens.expiresAt;
331
- }
332
- /**
333
- * Check if tokens exist (regardless of expiry)
334
- */
335
- hasTokens() {
336
- return Boolean(this.tokens.accessToken);
337
- }
338
- /**
339
- * Check if refresh token exists
340
- */
341
- hasRefreshToken() {
342
- return Boolean(this.tokens.refreshToken);
343
- }
344
- /**
345
- * Automatically refresh tokens if needed
346
- */
347
- async ensureValidToken() {
348
- if (!this.hasTokens()) {
349
- return null;
350
- }
351
- if (this.isAccessTokenValid()) {
352
- return this.getAccessToken();
353
- }
354
- if (!this.hasRefreshToken()) {
355
- this.clearTokens();
356
- if (this.config.onTokenExpired) {
357
- this.config.onTokenExpired();
358
- }
359
- return null;
360
- }
361
- try {
362
- await this.refreshTokens();
363
- return this.getAccessToken();
364
- } catch (error) {
365
- this.clearTokens();
366
- if (this.config.onTokenError) {
367
- this.config.onTokenError(error);
368
- }
369
- throw error;
370
- }
371
- }
372
- /**
373
- * Refresh access token using refresh token
374
- */
375
- async refreshTokens() {
376
- if (this.refreshPromise) {
377
- return this.refreshPromise;
378
- }
379
- if (!this.hasRefreshToken()) {
380
- throw new Error("No refresh token available");
381
- }
382
- if (this.retryCount >= this.config.maxRetries) {
383
- throw new Error("Max refresh retries exceeded");
384
- }
385
- this.refreshPromise = this._performRefresh();
386
- try {
387
- const result = await this.refreshPromise;
388
- this.retryCount = 0;
389
- return result;
390
- } catch (error) {
391
- this.retryCount++;
392
- throw error;
393
- } finally {
394
- this.refreshPromise = null;
395
- }
396
- }
397
- /**
398
- * Perform the actual token refresh request
399
- */
400
- async _performRefresh() {
401
- var _a;
402
- const refreshToken = this.getRefreshToken();
403
- const response = await fetch(`${this.config.apiUrl}/core/auth/refresh`, {
404
- method: "POST",
405
- headers: {
406
- "Content-Type": "application/json"
407
- },
408
- body: JSON.stringify({ refreshToken })
409
- });
410
- if (!response.ok) {
411
- const errorData = await response.json().catch(() => ({}));
412
- throw new Error(errorData.message || `Token refresh failed: ${response.status}`);
413
- }
414
- const responseData = await response.json();
415
- if (responseData.success && responseData.data && responseData.data.tokens) {
416
- const { tokens } = responseData.data;
417
- const tokenData = {
418
- access_token: tokens.accessToken,
419
- refresh_token: tokens.refreshToken,
420
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
421
- token_type: "Bearer"
422
- };
423
- return this.setTokens(tokenData);
424
- }
425
- return this.setTokens(responseData);
426
- }
427
- /**
428
- * Schedule automatic token refresh
429
- */
430
- scheduleRefresh() {
431
- if (this.refreshTimeout) {
432
- clearTimeout(this.refreshTimeout);
433
- this.refreshTimeout = null;
434
- }
435
- if (!this.tokens.expiresAt || !this.hasRefreshToken()) {
436
- return;
437
- }
438
- const now = Date.now();
439
- const refreshTime = this.tokens.expiresAt - this.config.refreshBuffer;
440
- const delay = Math.max(0, refreshTime - now);
441
- this.refreshTimeout = setTimeout(async () => {
442
- try {
443
- await this.refreshTokens();
444
- } catch (error) {
445
- console.error("Automatic token refresh failed:", error);
446
- if (this.config.onTokenError) {
447
- this.config.onTokenError(error);
448
- }
449
- }
450
- }, delay);
451
- }
452
- /**
453
- * Save tokens to storage
454
- */
455
- saveTokens() {
456
- try {
457
- const { storage } = this;
458
- const keys = this.storageKeys;
459
- if (this.tokens.accessToken) {
460
- storage.setItem(keys.accessToken, this.tokens.accessToken);
461
- }
462
- if (this.tokens.refreshToken) {
463
- storage.setItem(keys.refreshToken, this.tokens.refreshToken);
464
- }
465
- if (this.tokens.expiresAt) {
466
- storage.setItem(keys.expiresAt, this.tokens.expiresAt.toString());
467
- }
468
- if (this.tokens.expiresIn) {
469
- storage.setItem(keys.expiresIn, this.tokens.expiresIn.toString());
470
- }
471
- } catch (error) {
472
- console.error("[TokenManager] Error saving tokens to storage:", error);
473
- }
474
- }
475
- /**
476
- * Load tokens from storage
477
- */
478
- loadTokens() {
479
- try {
480
- const { storage } = this;
481
- const keys = this.storageKeys;
482
- const accessToken = storage.getItem(keys.accessToken);
483
- const refreshToken = storage.getItem(keys.refreshToken);
484
- const expiresAt = storage.getItem(keys.expiresAt);
485
- const expiresIn = storage.getItem(keys.expiresIn);
486
- if (accessToken) {
487
- this.tokens = {
488
- accessToken,
489
- refreshToken,
490
- expiresAt: expiresAt ? parseInt(expiresAt, 10) : null,
491
- expiresIn: expiresIn ? parseInt(expiresIn, 10) : null,
492
- tokenType: "Bearer"
493
- };
494
- this.scheduleRefresh();
495
- }
496
- } catch (error) {
497
- console.error("[TokenManager] Error loading tokens from storage:", error);
498
- this.tokens = {
499
- accessToken: null,
500
- refreshToken: null,
501
- expiresAt: null,
502
- expiresIn: null
503
- };
504
- }
505
- }
506
- /**
507
- * Clear all tokens
508
- */
509
- clearTokens() {
510
- this.tokens = {
511
- accessToken: null,
512
- refreshToken: null,
513
- expiresAt: null,
514
- expiresIn: null
515
- };
516
- const { storage } = this;
517
- const keys = this.storageKeys;
518
- Object.values(keys).forEach((key) => {
519
- storage.removeItem(key);
520
- });
521
- if (this.refreshTimeout) {
522
- clearTimeout(this.refreshTimeout);
523
- this.refreshTimeout = null;
524
- }
525
- this.retryCount = 0;
526
- }
527
- /**
528
- * Get token status information
529
- */
530
- getTokenStatus() {
531
- const hasTokens = this.hasTokens();
532
- const isValid = this.isAccessTokenValid();
533
- const { expiresAt } = this.tokens;
534
- const timeToExpiry = expiresAt ? expiresAt - Date.now() : null;
535
- return {
536
- hasTokens,
537
- isValid,
538
- hasRefreshToken: this.hasRefreshToken(),
539
- expiresAt,
540
- timeToExpiry,
541
- willExpireSoon: timeToExpiry ? timeToExpiry < this.config.refreshBuffer : false
542
- };
543
- }
544
- /**
545
- * Cleanup resources
546
- */
547
- destroy() {
548
- if (this.refreshTimeout) {
549
- clearTimeout(this.refreshTimeout);
550
- this.refreshTimeout = null;
551
- }
552
- this.refreshPromise = null;
553
- }
554
- };
555
- var defaultTokenManager = null;
556
- var getTokenManager = (options) => {
557
- if (!defaultTokenManager) {
558
- defaultTokenManager = new TokenManager(options);
559
- }
560
- return defaultTokenManager;
561
- };
562
-
563
- // src/services/CoreService.js
564
- var CoreService = class extends BaseService {
565
- constructor(config) {
566
- super(config);
567
- this._client = null;
568
- this._initialized = false;
569
- this._apiUrl = null;
570
- this._tokenManager = null;
571
- }
572
- init({ context }) {
573
- try {
574
- const { appKey, authToken } = context || this._context;
575
- this._apiUrl = environment_default.apiUrl;
576
- if (!this._apiUrl) {
577
- throw new Error("Core service base URL not configured");
578
- }
579
- this._tokenManager = getTokenManager({
580
- apiUrl: this._apiUrl,
581
- onTokenRefresh: (tokens) => {
582
- this.updateContext({ authToken: tokens.accessToken });
583
- },
584
- onTokenExpired: () => {
585
- this.updateContext({ authToken: null });
586
- },
587
- onTokenError: (error) => {
588
- console.error("Token management error:", error);
589
- }
590
- });
591
- if (authToken && !this._tokenManager.hasTokens()) {
592
- this._tokenManager.setTokens({ access_token: authToken });
593
- }
594
- this._info = {
595
- config: {
596
- apiUrl: this._apiUrl,
597
- appKey: appKey ? `${appKey.substr(0, 4)}...${appKey.substr(-4)}` : null,
598
- hasToken: Boolean(authToken)
599
- }
600
- };
601
- this._initialized = true;
602
- this._setReady();
603
- } catch (error) {
604
- this._setError(error);
605
- throw error;
606
- }
607
- }
608
- // Helper to check if method requires initialization
609
- _requiresInit(methodName) {
610
- const noInitMethods = /* @__PURE__ */ new Set([
611
- "register",
612
- "login",
613
- "googleAuth",
614
- "googleAuthCallback",
615
- "githubAuth",
616
- "requestPasswordReset",
617
- "confirmPasswordReset",
618
- "confirmRegistration",
619
- "verifyEmail",
620
- "listPublicProjects",
621
- "getPublicProject",
622
- "getHealthStatus"
623
- ]);
624
- return !noInitMethods.has(methodName);
625
- }
626
- // Override _requireReady to be more flexible
627
- _requireReady(methodName) {
628
- if (this._requiresInit(methodName) && !this._initialized) {
629
- throw new Error("Core service not initialized");
630
- }
631
- }
632
- // Debug method to check token status
633
- getTokenDebugInfo() {
634
- if (!this._tokenManager) {
635
- return {
636
- tokenManagerExists: false,
637
- error: "TokenManager not initialized"
638
- };
639
- }
640
- const tokenStatus = this._tokenManager.getTokenStatus();
641
- const { tokens } = this._tokenManager;
642
- return {
643
- tokenManagerExists: true,
644
- tokenStatus,
645
- hasAccessToken: Boolean(tokens.accessToken),
646
- hasRefreshToken: Boolean(tokens.refreshToken),
647
- accessTokenPreview: tokens.accessToken ? `${tokens.accessToken.substring(0, 20)}...` : null,
648
- expiresAt: tokens.expiresAt,
649
- timeToExpiry: tokenStatus.timeToExpiry,
650
- authHeader: this._tokenManager.getAuthHeader()
651
- };
652
- }
653
- // Helper method to check if user is authenticated
654
- isAuthenticated() {
655
- if (!this._tokenManager) {
656
- return false;
657
- }
658
- return this._tokenManager.hasTokens();
659
- }
660
- // Helper method to check if user has valid tokens
661
- hasValidTokens() {
662
- if (!this._tokenManager) {
663
- return false;
664
- }
665
- return this._tokenManager.hasTokens() && this._tokenManager.isAccessTokenValid();
666
- }
667
- // Helper method to make HTTP requests
668
- async _request(endpoint, options = {}) {
669
- const url = `${this._apiUrl}/core${endpoint}`;
670
- const defaultHeaders = {};
671
- if (!(options.body instanceof FormData)) {
672
- defaultHeaders["Content-Type"] = "application/json";
673
- }
674
- if (this._requiresInit(options.methodName) && this._tokenManager) {
675
- try {
676
- const validToken = await this._tokenManager.ensureValidToken();
677
- if (validToken) {
678
- const authHeader = this._tokenManager.getAuthHeader();
679
- if (authHeader) {
680
- defaultHeaders.Authorization = authHeader;
681
- }
682
- }
683
- } catch (error) {
684
- console.warn("Token management failed, proceeding without authentication:", error);
685
- }
686
- } else if (this._requiresInit(options.methodName)) {
687
- const { authToken } = this._context;
688
- if (authToken) {
689
- defaultHeaders.Authorization = `Bearer ${authToken}`;
690
- }
691
- }
692
- try {
693
- const response = await fetch(url, {
694
- ...options,
695
- headers: {
696
- ...defaultHeaders,
697
- ...options.headers
698
- }
699
- });
700
- if (!response.ok) {
701
- let error = { message: `HTTP ${response.status}: ${response.statusText}` };
702
- try {
703
- error = await response.json();
704
- } catch {
705
- }
706
- throw new Error(error.message || error.error || "Request failed");
707
- }
708
- return response.status === 204 ? null : response.json();
709
- } catch (error) {
710
- throw new Error(`Request failed: ${error.message}`);
711
- }
712
- }
713
- // ==================== AUTH METHODS ====================
714
- async register(userData) {
715
- try {
716
- const response = await this._request("/auth/register", {
717
- method: "POST",
718
- body: JSON.stringify(userData),
719
- methodName: "register"
720
- });
721
- if (response.success) {
722
- return response.data;
723
- }
724
- throw new Error(response.message);
725
- } catch (error) {
726
- throw new Error(`Registration failed: ${error.message}`);
727
- }
728
- }
729
- async login(email, password) {
730
- var _a;
731
- try {
732
- const response = await this._request("/auth/login", {
733
- method: "POST",
734
- body: JSON.stringify({ email, password }),
735
- methodName: "login"
736
- });
737
- if (response.success && response.data && response.data.tokens) {
738
- const { tokens } = response.data;
739
- const tokenData = {
740
- access_token: tokens.accessToken,
741
- refresh_token: tokens.refreshToken,
742
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
743
- token_type: "Bearer"
744
- };
745
- if (this._tokenManager) {
746
- this._tokenManager.setTokens(tokenData);
747
- }
748
- this.updateContext({ authToken: tokens.accessToken });
749
- }
750
- if (response.success) {
751
- return response.data;
752
- }
753
- throw new Error(response.message);
754
- } catch (error) {
755
- throw new Error(`Login failed: ${error.message}`);
756
- }
757
- }
758
- async logout() {
759
- this._requireReady("logout");
760
- try {
761
- await this._request("/auth/logout", {
762
- method: "POST",
763
- methodName: "logout"
764
- });
765
- if (this._tokenManager) {
766
- this._tokenManager.clearTokens();
767
- }
768
- this.updateContext({ authToken: null });
769
- } catch (error) {
770
- if (this._tokenManager) {
771
- this._tokenManager.clearTokens();
772
- }
773
- this.updateContext({ authToken: null });
774
- throw new Error(`Logout failed: ${error.message}`);
775
- }
776
- }
777
- async refreshToken(refreshToken) {
778
- try {
779
- const response = await this._request("/auth/refresh", {
780
- method: "POST",
781
- body: JSON.stringify({ refreshToken }),
782
- methodName: "refreshToken"
783
- });
784
- if (response.success) {
785
- return response.data;
786
- }
787
- throw new Error(response.message);
788
- } catch (error) {
789
- throw new Error(`Token refresh failed: ${error.message}`);
790
- }
791
- }
792
- async googleAuth(idToken) {
793
- var _a;
794
- try {
795
- const response = await this._request("/auth/google", {
796
- method: "POST",
797
- body: JSON.stringify({ idToken }),
798
- methodName: "googleAuth"
799
- });
800
- if (response.success && response.data && response.data.tokens) {
801
- const { tokens } = response.data;
802
- const tokenData = {
803
- access_token: tokens.accessToken,
804
- refresh_token: tokens.refreshToken,
805
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
806
- token_type: "Bearer"
807
- };
808
- if (this._tokenManager) {
809
- this._tokenManager.setTokens(tokenData);
810
- }
811
- this.updateContext({ authToken: tokens.accessToken });
812
- }
813
- if (response.success) {
814
- return response.data;
815
- }
816
- throw new Error(response.message);
817
- } catch (error) {
818
- throw new Error(`Google auth failed: ${error.message}`);
819
- }
820
- }
821
- async githubAuth(code) {
822
- var _a;
823
- try {
824
- const response = await this._request("/auth/github", {
825
- method: "POST",
826
- body: JSON.stringify({ code }),
827
- methodName: "githubAuth"
828
- });
829
- if (response.success && response.data && response.data.tokens) {
830
- const { tokens } = response.data;
831
- const tokenData = {
832
- access_token: tokens.accessToken,
833
- refresh_token: tokens.refreshToken,
834
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
835
- token_type: "Bearer"
836
- };
837
- if (this._tokenManager) {
838
- this._tokenManager.setTokens(tokenData);
839
- }
840
- this.updateContext({ authToken: tokens.accessToken });
841
- }
842
- if (response.success) {
843
- return response.data;
844
- }
845
- throw new Error(response.message);
846
- } catch (error) {
847
- throw new Error(`GitHub auth failed: ${error.message}`);
848
- }
849
- }
850
- async googleAuthCallback(code, redirectUri) {
851
- var _a;
852
- try {
853
- const response = await this._request("/auth/google/callback", {
854
- method: "POST",
855
- body: JSON.stringify({ code, redirectUri }),
856
- methodName: "googleAuthCallback"
857
- });
858
- if (response.success && response.data && response.data.tokens) {
859
- const { tokens } = response.data;
860
- const tokenData = {
861
- access_token: tokens.accessToken,
862
- refresh_token: tokens.refreshToken,
863
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
864
- token_type: "Bearer"
865
- };
866
- if (this._tokenManager) {
867
- this._tokenManager.setTokens(tokenData);
868
- }
869
- this.updateContext({ authToken: tokens.accessToken });
870
- }
871
- if (response.success) {
872
- return response.data;
873
- }
874
- throw new Error(response.message);
875
- } catch (error) {
876
- throw new Error(`Google auth callback failed: ${error.message}`);
877
- }
878
- }
879
- async requestPasswordReset(email) {
880
- try {
881
- const response = await this._request("/auth/request-password-reset", {
882
- method: "POST",
883
- body: JSON.stringify({ email }),
884
- methodName: "requestPasswordReset"
885
- });
886
- if (response.success) {
887
- return response.data;
888
- }
889
- throw new Error(response.message);
890
- } catch (error) {
891
- throw new Error(`Password reset request failed: ${error.message}`);
892
- }
893
- }
894
- async confirmPasswordReset(token, password) {
895
- try {
896
- const response = await this._request("/auth/reset-password-confirm", {
897
- method: "POST",
898
- body: JSON.stringify({ token, password }),
899
- methodName: "confirmPasswordReset"
900
- });
901
- if (response.success) {
902
- return response.data;
903
- }
904
- throw new Error(response.message);
905
- } catch (error) {
906
- throw new Error(`Password reset confirmation failed: ${error.message}`);
907
- }
908
- }
909
- async confirmRegistration(token) {
910
- try {
911
- const response = await this._request("/auth/register-confirmation", {
912
- method: "POST",
913
- body: JSON.stringify({ token }),
914
- methodName: "confirmRegistration"
915
- });
916
- if (response.success) {
917
- return response.data;
918
- }
919
- throw new Error(response.message);
920
- } catch (error) {
921
- throw new Error(`Registration confirmation failed: ${error.message}`);
922
- }
923
- }
924
- async requestPasswordChange() {
925
- this._requireReady("requestPasswordChange");
926
- try {
927
- const response = await this._request("/auth/request-password-change", {
928
- method: "POST",
929
- methodName: "requestPasswordChange"
930
- });
931
- if (response.success) {
932
- return response.data;
933
- }
934
- throw new Error(response.message);
935
- } catch (error) {
936
- throw new Error(`Password change request failed: ${error.message}`);
937
- }
938
- }
939
- async confirmPasswordChange(currentPassword, newPassword, code) {
940
- this._requireReady("confirmPasswordChange");
941
- try {
942
- const response = await this._request("/auth/confirm-password-change", {
943
- method: "POST",
944
- body: JSON.stringify({ currentPassword, newPassword, code }),
945
- methodName: "confirmPasswordChange"
946
- });
947
- if (response.success) {
948
- return response.data;
949
- }
950
- throw new Error(response.message);
951
- } catch (error) {
952
- throw new Error(`Password change confirmation failed: ${error.message}`);
953
- }
954
- }
955
- async getMe() {
956
- this._requireReady("getMe");
957
- try {
958
- const response = await this._request("/auth/me", {
959
- method: "GET",
960
- methodName: "getMe"
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 get user profile: ${error.message}`);
968
- }
969
- }
970
- /**
971
- * Get stored authentication state (backward compatibility method)
972
- * Replaces AuthService.getStoredAuthState()
973
- */
974
- async getStoredAuthState() {
975
- try {
976
- if (!this._tokenManager) {
977
- return {
978
- userId: false,
979
- authToken: false
980
- };
981
- }
982
- const tokenStatus = this._tokenManager.getTokenStatus();
983
- if (!tokenStatus.hasTokens) {
984
- return {
985
- userId: false,
986
- authToken: false
987
- };
988
- }
989
- if (!tokenStatus.isValid && tokenStatus.hasRefreshToken) {
990
- try {
991
- await this._tokenManager.ensureValidToken();
992
- } catch (error) {
993
- console.warn("[CoreService] Token refresh failed:", error.message);
994
- if (error.message.includes("401") || error.message.includes("403") || error.message.includes("invalid") || error.message.includes("expired")) {
995
- this._tokenManager.clearTokens();
996
- return {
997
- userId: false,
998
- authToken: false,
999
- error: `Authentication failed: ${error.message}`
1000
- };
1001
- }
1002
- return {
1003
- userId: false,
1004
- authToken: this._tokenManager.getAccessToken(),
1005
- error: `Network error during token refresh: ${error.message}`,
1006
- hasTokens: true
1007
- };
1008
- }
1009
- }
1010
- const currentAccessToken = this._tokenManager.getAccessToken();
1011
- if (!currentAccessToken) {
1012
- return {
1013
- userId: false,
1014
- authToken: false
1015
- };
1016
- }
1017
- try {
1018
- const currentUser = await this.getMe();
1019
- return {
1020
- userId: currentUser.user.id,
1021
- authToken: currentAccessToken,
1022
- ...currentUser,
1023
- error: null
1024
- };
1025
- } catch (error) {
1026
- console.warn("[CoreService] Failed to get user data:", error.message);
1027
- if (error.message.includes("401") || error.message.includes("403")) {
1028
- this._tokenManager.clearTokens();
1029
- return {
1030
- userId: false,
1031
- authToken: false,
1032
- error: `Authentication failed: ${error.message}`
1033
- };
1034
- }
1035
- return {
1036
- userId: false,
1037
- authToken: currentAccessToken,
1038
- error: `Failed to get user data: ${error.message}`,
1039
- hasTokens: true
1040
- };
1041
- }
1042
- } catch (error) {
1043
- console.error("[CoreService] Unexpected error in getStoredAuthState:", error);
1044
- return {
1045
- userId: false,
1046
- authToken: false,
1047
- error: `Failed to get stored auth state: ${error.message}`
1048
- };
1049
- }
1050
- }
1051
- // ==================== USER METHODS ====================
1052
- async getUserProfile() {
1053
- this._requireReady("getUserProfile");
1054
- try {
1055
- const response = await this._request("/users/profile", {
1056
- method: "GET",
1057
- methodName: "getUserProfile"
1058
- });
1059
- if (response.success) {
1060
- return response.data;
1061
- }
1062
- throw new Error(response.message);
1063
- } catch (error) {
1064
- throw new Error(`Failed to get user profile: ${error.message}`);
1065
- }
1066
- }
1067
- async updateUserProfile(profileData) {
1068
- this._requireReady("updateUserProfile");
1069
- try {
1070
- const response = await this._request("/users/profile", {
1071
- method: "PATCH",
1072
- body: JSON.stringify(profileData),
1073
- methodName: "updateUserProfile"
1074
- });
1075
- if (response.success) {
1076
- return response.data;
1077
- }
1078
- throw new Error(response.message);
1079
- } catch (error) {
1080
- throw new Error(`Failed to update user profile: ${error.message}`);
1081
- }
1082
- }
1083
- async getUserProjects() {
1084
- this._requireReady("getUserProjects");
1085
- try {
1086
- const response = await this._request("/users/projects", {
1087
- method: "GET",
1088
- methodName: "getUserProjects"
1089
- });
1090
- if (response.success) {
1091
- return response.data.map((project) => ({
1092
- ...project,
1093
- ...project.icon && { icon: { src: `${this._apiUrl}/core/files/public/${project.icon.id}/download`, ...project.icon } }
1094
- }));
1095
- }
1096
- throw new Error(response.message);
1097
- } catch (error) {
1098
- throw new Error(`Failed to get user projects: ${error.message}`);
1099
- }
1100
- }
1101
- async getUser(userId) {
1102
- this._requireReady("getUser");
1103
- if (!userId) {
1104
- throw new Error("User ID is required");
1105
- }
1106
- try {
1107
- const response = await this._request(`/users/${userId}`, {
1108
- method: "GET",
1109
- methodName: "getUser"
1110
- });
1111
- if (response.success) {
1112
- return response.data;
1113
- }
1114
- throw new Error(response.message);
1115
- } catch (error) {
1116
- throw new Error(`Failed to get user: ${error.message}`);
1117
- }
1118
- }
1119
- async getUserByEmail(email) {
1120
- this._requireReady("getUserByEmail");
1121
- if (!email) {
1122
- throw new Error("Email is required");
1123
- }
1124
- try {
1125
- const response = await this._request("/auth/user", {
1126
- method: "GET",
1127
- headers: {
1128
- "X-User-Email": email
1129
- },
1130
- methodName: "getUserByEmail"
1131
- });
1132
- if (response.success) {
1133
- return response.data;
1134
- }
1135
- throw new Error(response.message);
1136
- } catch (error) {
1137
- throw new Error(`Failed to get user by email: ${error.message}`);
1138
- }
1139
- }
1140
- // ==================== PROJECT METHODS ====================
1141
- async createProject(projectData) {
1142
- this._requireReady("createProject");
1143
- try {
1144
- const response = await this._request("/projects", {
1145
- method: "POST",
1146
- body: JSON.stringify(projectData),
1147
- methodName: "createProject"
1148
- });
1149
- if (response.success) {
1150
- return response.data;
1151
- }
1152
- throw new Error(response.message);
1153
- } catch (error) {
1154
- throw new Error(`Failed to create project: ${error.message}`);
1155
- }
1156
- }
1157
- async getProjects(params = {}) {
1158
- this._requireReady("getProjects");
1159
- try {
1160
- const queryParams = new URLSearchParams();
1161
- Object.keys(params).forEach((key) => {
1162
- if (params[key] != null) {
1163
- queryParams.append(key, params[key]);
1164
- }
1165
- });
1166
- const queryString = queryParams.toString();
1167
- const url = `/projects${queryString ? `?${queryString}` : ""}`;
1168
- const response = await this._request(url, {
1169
- method: "GET",
1170
- methodName: "getProjects"
1171
- });
1172
- if (response.success) {
1173
- return response;
1174
- }
1175
- throw new Error(response.message);
1176
- } catch (error) {
1177
- throw new Error(`Failed to get projects: ${error.message}`);
1178
- }
1179
- }
1180
- /**
1181
- * Alias for getProjects for consistency with API naming
1182
- */
1183
- async listProjects(params = {}) {
1184
- return await this.getProjects(params);
1185
- }
1186
- /**
1187
- * List only public projects (no authentication required)
1188
- */
1189
- async listPublicProjects(params = {}) {
1190
- try {
1191
- const queryParams = new URLSearchParams();
1192
- Object.keys(params).forEach((key) => {
1193
- if (params[key] != null) {
1194
- queryParams.append(key, params[key]);
1195
- }
1196
- });
1197
- const queryString = queryParams.toString();
1198
- const url = `/projects/public${queryString ? `?${queryString}` : ""}`;
1199
- const response = await this._request(url, {
1200
- method: "GET",
1201
- methodName: "listPublicProjects"
1202
- });
1203
- if (response.success) {
1204
- return response.data;
1205
- }
1206
- throw new Error(response.message);
1207
- } catch (error) {
1208
- throw new Error(`Failed to list public projects: ${error.message}`);
1209
- }
1210
- }
1211
- async getProject(projectId) {
1212
- this._requireReady("getProject");
1213
- if (!projectId) {
1214
- throw new Error("Project ID is required");
1215
- }
1216
- try {
1217
- const response = await this._request(`/projects/${projectId}`, {
1218
- method: "GET",
1219
- methodName: "getProject"
1220
- });
1221
- if (response.success) {
1222
- const iconSrc = response.data.icon ? `${this._apiUrl}/core/files/public/${response.data.icon.id}/download` : null;
1223
- return {
1224
- ...response.data,
1225
- icon: { src: iconSrc, ...response.data.icon }
1226
- };
1227
- }
1228
- throw new Error(response.message);
1229
- } catch (error) {
1230
- throw new Error(`Failed to get project: ${error.message}`);
1231
- }
1232
- }
1233
- /**
1234
- * Get a public project by ID (no authentication required)
1235
- * Corresponds to router.get('/public/:projectId', ProjectController.getPublicProject)
1236
- */
1237
- async getPublicProject(projectId) {
1238
- if (!projectId) {
1239
- throw new Error("Project ID is required");
1240
- }
1241
- try {
1242
- const response = await this._request(`/projects/public/${projectId}`, {
1243
- method: "GET",
1244
- methodName: "getPublicProject"
1245
- });
1246
- if (response.success) {
1247
- const iconSrc = response.data.icon ? `${this._apiUrl}/core/files/public/${response.data.icon.id}/download` : null;
1248
- return {
1249
- ...response.data,
1250
- icon: { src: iconSrc, ...response.data.icon }
1251
- };
1252
- }
1253
- throw new Error(response.message);
1254
- } catch (error) {
1255
- throw new Error(`Failed to get public project: ${error.message}`);
1256
- }
1257
- }
1258
- async getProjectByKey(key) {
1259
- this._requireReady("getProjectByKey");
1260
- if (!key) {
1261
- throw new Error("Project key is required");
1262
- }
1263
- try {
1264
- const response = await this._request(`/projects/check-key/${key}`, {
1265
- method: "GET",
1266
- methodName: "getProjectByKey"
1267
- });
1268
- if (response.success) {
1269
- return response.data;
1270
- }
1271
- throw new Error(response.message);
1272
- } catch (error) {
1273
- throw new Error(`Failed to get project by key: ${error.message}`);
1274
- }
1275
- }
1276
- async updateProject(projectId, data) {
1277
- this._requireReady("updateProject");
1278
- if (!projectId) {
1279
- throw new Error("Project ID is required");
1280
- }
1281
- try {
1282
- const response = await this._request(`/projects/${projectId}`, {
1283
- method: "PATCH",
1284
- body: JSON.stringify(data),
1285
- methodName: "updateProject"
1286
- });
1287
- if (response.success) {
1288
- return response.data;
1289
- }
1290
- throw new Error(response.message);
1291
- } catch (error) {
1292
- throw new Error(`Failed to update project: ${error.message}`);
1293
- }
1294
- }
1295
- async updateProjectComponents(projectId, components) {
1296
- this._requireReady("updateProjectComponents");
1297
- if (!projectId) {
1298
- throw new Error("Project ID is required");
1299
- }
1300
- try {
1301
- const response = await this._request(`/projects/${projectId}/components`, {
1302
- method: "PATCH",
1303
- body: JSON.stringify({ components }),
1304
- methodName: "updateProjectComponents"
1305
- });
1306
- if (response.success) {
1307
- return response.data;
1308
- }
1309
- throw new Error(response.message);
1310
- } catch (error) {
1311
- throw new Error(`Failed to update project components: ${error.message}`);
1312
- }
1313
- }
1314
- async updateProjectSettings(projectId, settings) {
1315
- this._requireReady("updateProjectSettings");
1316
- if (!projectId) {
1317
- throw new Error("Project ID is required");
1318
- }
1319
- try {
1320
- const response = await this._request(`/projects/${projectId}/settings`, {
1321
- method: "PATCH",
1322
- body: JSON.stringify({ settings }),
1323
- methodName: "updateProjectSettings"
1324
- });
1325
- if (response.success) {
1326
- return response.data;
1327
- }
1328
- throw new Error(response.message);
1329
- } catch (error) {
1330
- throw new Error(`Failed to update project settings: ${error.message}`);
1331
- }
1332
- }
1333
- async updateProjectName(projectId, name) {
1334
- this._requireReady("updateProjectName");
1335
- if (!projectId) {
1336
- throw new Error("Project ID is required");
1337
- }
1338
- try {
1339
- const response = await this._request(`/projects/${projectId}`, {
1340
- method: "PATCH",
1341
- body: JSON.stringify({ name }),
1342
- methodName: "updateProjectName"
1343
- });
1344
- if (response.success) {
1345
- return response.data;
1346
- }
1347
- throw new Error(response.message);
1348
- } catch (error) {
1349
- throw new Error(`Failed to update project name: ${error.message}`);
1350
- }
1351
- }
1352
- async updateProjectPackage(projectId, pkg) {
1353
- this._requireReady("updateProjectPackage");
1354
- if (!projectId) {
1355
- throw new Error("Project ID is required");
1356
- }
1357
- try {
1358
- const response = await this._request(`/projects/${projectId}/tier`, {
1359
- method: "PATCH",
1360
- body: JSON.stringify({ tier: pkg }),
1361
- methodName: "updateProjectPackage"
1362
- });
1363
- if (response.success) {
1364
- return response.data;
1365
- }
1366
- throw new Error(response.message);
1367
- } catch (error) {
1368
- throw new Error(`Failed to update project package: ${error.message}`);
1369
- }
1370
- }
1371
- async duplicateProject(projectId, newName, newKey, targetUserId) {
1372
- this._requireReady("duplicateProject");
1373
- if (!projectId) {
1374
- throw new Error("Project ID is required");
1375
- }
1376
- try {
1377
- const response = await this._request(`/projects/${projectId}/duplicate`, {
1378
- method: "POST",
1379
- body: JSON.stringify({ name: newName, key: newKey, targetUserId }),
1380
- methodName: "duplicateProject"
1381
- });
1382
- if (response.success) {
1383
- return response.data;
1384
- }
1385
- throw new Error(response.message);
1386
- } catch (error) {
1387
- throw new Error(`Failed to duplicate project: ${error.message}`);
1388
- }
1389
- }
1390
- async removeProject(projectId) {
1391
- this._requireReady("removeProject");
1392
- if (!projectId) {
1393
- throw new Error("Project ID is required");
1394
- }
1395
- try {
1396
- const response = await this._request(`/projects/${projectId}`, {
1397
- method: "DELETE",
1398
- methodName: "removeProject"
1399
- });
1400
- if (response.success) {
1401
- return response.data;
1402
- }
1403
- throw new Error(response.message);
1404
- } catch (error) {
1405
- throw new Error(`Failed to remove project: ${error.message}`);
1406
- }
1407
- }
1408
- async checkProjectKeyAvailability(key) {
1409
- this._requireReady("checkProjectKeyAvailability");
1410
- if (!key) {
1411
- throw new Error("Project key is required");
1412
- }
1413
- try {
1414
- const response = await this._request(`/projects/check-key/${key}`, {
1415
- method: "GET",
1416
- methodName: "checkProjectKeyAvailability"
1417
- });
1418
- if (response.success) {
1419
- return response.data;
1420
- }
1421
- throw new Error(response.message);
1422
- } catch (error) {
1423
- throw new Error(`Failed to check project key availability: ${error.message}`);
1424
- }
1425
- }
1426
- // ==================== PROJECT MEMBER METHODS ====================
1427
- async getProjectMembers(projectId) {
1428
- this._requireReady("getProjectMembers");
1429
- if (!projectId) {
1430
- throw new Error("Project ID is required");
1431
- }
1432
- try {
1433
- const response = await this._request(`/projects/${projectId}/members`, {
1434
- method: "GET",
1435
- methodName: "getProjectMembers"
1436
- });
1437
- if (response.success) {
1438
- return response.data;
1439
- }
1440
- throw new Error(response.message);
1441
- } catch (error) {
1442
- throw new Error(`Failed to get project members: ${error.message}`);
1443
- }
1444
- }
1445
- async inviteMember(projectId, email, role = "guest", options = {}) {
1446
- this._requireReady("inviteMember");
1447
- if (!projectId || !email || !role) {
1448
- throw new Error("Project ID, email, and role are required");
1449
- }
1450
- const { name, callbackUrl } = options;
1451
- const defaultCallbackUrl = typeof window === "undefined" ? "https://app.symbols.com/accept-invite" : `${window.location.origin}/accept-invite`;
1452
- try {
1453
- const requestBody = {
1454
- email,
1455
- role,
1456
- callbackUrl: callbackUrl || defaultCallbackUrl
1457
- };
1458
- if (name) {
1459
- requestBody.name = name;
1460
- }
1461
- const response = await this._request(`/projects/${projectId}/invite`, {
1462
- method: "POST",
1463
- body: JSON.stringify(requestBody),
1464
- methodName: "inviteMember"
1465
- });
1466
- if (response.success) {
1467
- return response.data;
1468
- }
1469
- throw new Error(response.message);
1470
- } catch (error) {
1471
- throw new Error(`Failed to invite member: ${error.message}`);
1472
- }
1473
- }
1474
- async acceptInvite(token) {
1475
- this._requireReady("acceptInvite");
1476
- if (!token) {
1477
- throw new Error("Invitation token is required");
1478
- }
1479
- try {
1480
- const response = await this._request("/projects/accept-invite", {
1481
- method: "POST",
1482
- body: JSON.stringify({ token }),
1483
- methodName: "acceptInvite"
1484
- });
1485
- if (response.success) {
1486
- return response.data;
1487
- }
1488
- throw new Error(response.message);
1489
- } catch (error) {
1490
- throw new Error(`Failed to accept invite: ${error.message}`);
1491
- }
1492
- }
1493
- async updateMemberRole(projectId, memberId, role) {
1494
- this._requireReady("updateMemberRole");
1495
- if (!projectId || !memberId || !role) {
1496
- throw new Error("Project ID, member ID, and role are required");
1497
- }
1498
- try {
1499
- const response = await this._request(`/projects/${projectId}/members/${memberId}`, {
1500
- method: "PATCH",
1501
- body: JSON.stringify({ role }),
1502
- methodName: "updateMemberRole"
1503
- });
1504
- if (response.success) {
1505
- return response.data;
1506
- }
1507
- throw new Error(response.message);
1508
- } catch (error) {
1509
- throw new Error(`Failed to update member role: ${error.message}`);
1510
- }
1511
- }
1512
- async removeMember(projectId, memberId) {
1513
- this._requireReady("removeMember");
1514
- if (!projectId || !memberId) {
1515
- throw new Error("Project ID and member ID are required");
1516
- }
1517
- try {
1518
- const response = await this._request(`/projects/${projectId}/members/${memberId}`, {
1519
- method: "DELETE",
1520
- methodName: "removeMember"
1521
- });
1522
- if (response.success) {
1523
- return response.data;
1524
- }
1525
- throw new Error(response.message);
1526
- } catch (error) {
1527
- throw new Error(`Failed to remove member: ${error.message}`);
1528
- }
1529
- }
1530
- // ==================== PROJECT LIBRARY METHODS ====================
1531
- async getAvailableLibraries(params = {}) {
1532
- this._requireReady("getAvailableLibraries");
1533
- const queryParams = new URLSearchParams(params).toString();
1534
- try {
1535
- const response = await this._request(`/projects/libraries/available?${queryParams}`, {
1536
- method: "GET",
1537
- methodName: "getAvailableLibraries"
1538
- });
1539
- if (response.success) {
1540
- return response.data;
1541
- }
1542
- throw new Error(response.message);
1543
- } catch (error) {
1544
- throw new Error(`Failed to get available libraries: ${error.message}`);
1545
- }
1546
- }
1547
- async getProjectLibraries(projectId) {
1548
- this._requireReady("getProjectLibraries");
1549
- if (!projectId) {
1550
- throw new Error("Project ID is required");
1551
- }
1552
- try {
1553
- const response = await this._request(`/projects/${projectId}/libraries`, {
1554
- method: "GET",
1555
- methodName: "getProjectLibraries"
1556
- });
1557
- if (response.success) {
1558
- return response.data;
1559
- }
1560
- throw new Error(response.message);
1561
- } catch (error) {
1562
- throw new Error(`Failed to get project libraries: ${error.message}`);
1563
- }
1564
- }
1565
- async addProjectLibraries(projectId, libraryIds) {
1566
- this._requireReady("addProjectLibraries");
1567
- if (!projectId || !libraryIds) {
1568
- throw new Error("Project ID and library IDs are required");
1569
- }
1570
- try {
1571
- const response = await this._request(`/projects/${projectId}/libraries`, {
1572
- method: "POST",
1573
- body: JSON.stringify({ libraryIds }),
1574
- methodName: "addProjectLibraries"
1575
- });
1576
- if (response.success) {
1577
- return response.data;
1578
- }
1579
- throw new Error(response.message);
1580
- } catch (error) {
1581
- throw new Error(`Failed to add project libraries: ${error.message}`);
1582
- }
1583
- }
1584
- async removeProjectLibraries(projectId, libraryIds) {
1585
- this._requireReady("removeProjectLibraries");
1586
- if (!projectId || !libraryIds) {
1587
- throw new Error("Project ID and library IDs are required");
1588
- }
1589
- try {
1590
- const response = await this._request(`/projects/${projectId}/libraries`, {
1591
- method: "DELETE",
1592
- body: JSON.stringify({ libraryIds }),
1593
- methodName: "removeProjectLibraries"
1594
- });
1595
- if (response.success) {
1596
- return response.data;
1597
- }
1598
- throw new Error(response.message);
1599
- } catch (error) {
1600
- throw new Error(`Failed to remove project libraries: ${error.message}`);
1601
- }
1602
- }
1603
- // ==================== FILE METHODS ====================
1604
- async uploadFile(file, options = {}) {
1605
- this._requireReady("uploadFile");
1606
- if (!file) {
1607
- throw new Error("File is required for upload");
1608
- }
1609
- const formData = new FormData();
1610
- formData.append("file", file);
1611
- if (options.projectId) {
1612
- formData.append("projectId", options.projectId);
1613
- }
1614
- if (options.tags) {
1615
- formData.append("tags", JSON.stringify(options.tags));
1616
- }
1617
- if (options.visibility) {
1618
- formData.append("visibility", options.visibility || "public");
1619
- }
1620
- if (options.metadata) {
1621
- formData.append("metadata", JSON.stringify(options.metadata));
1622
- }
1623
- try {
1624
- const response = await this._request("/files/upload", {
1625
- method: "POST",
1626
- body: formData,
1627
- headers: {},
1628
- // Let browser set Content-Type for FormData
1629
- methodName: "uploadFile"
1630
- });
1631
- if (!response.success) {
1632
- throw new Error(response.message);
1633
- }
1634
- return {
1635
- id: response.data.id,
1636
- src: `${this._apiUrl}/core/files/public/${response.data.id}/download`,
1637
- success: true,
1638
- message: response.message
1639
- };
1640
- } catch (error) {
1641
- throw new Error(`File upload failed: ${error.message}`);
1642
- }
1643
- }
1644
- async updateProjectIcon(projectId, iconFile) {
1645
- this._requireReady("updateProjectIcon");
1646
- if (!projectId || !iconFile) {
1647
- throw new Error("Project ID and icon file are required");
1648
- }
1649
- const formData = new FormData();
1650
- formData.append("icon", iconFile);
1651
- formData.append("projectId", projectId);
1652
- try {
1653
- const response = await this._request("/files/upload-project-icon", {
1654
- method: "POST",
1655
- body: formData,
1656
- headers: {},
1657
- // Let browser set Content-Type for FormData
1658
- methodName: "updateProjectIcon"
1659
- });
1660
- if (response.success) {
1661
- return response.data;
1662
- }
1663
- throw new Error(response.message);
1664
- } catch (error) {
1665
- throw new Error(`Failed to update project icon: ${error.message}`);
1666
- }
1667
- }
1668
- // ==================== PAYMENT METHODS ====================
1669
- async checkout(options = {}) {
1670
- this._requireReady("checkout");
1671
- const {
1672
- projectId,
1673
- seats = 1,
1674
- price = "starter_monthly",
1675
- successUrl = `${window.location.origin}/success`,
1676
- cancelUrl = `${window.location.origin}/pricing`
1677
- } = options;
1678
- if (!projectId) {
1679
- throw new Error("Project ID is required for checkout");
1680
- }
1681
- try {
1682
- const response = await this._request("/payments/checkout", {
1683
- method: "POST",
1684
- body: JSON.stringify({
1685
- projectId,
1686
- seats,
1687
- price,
1688
- successUrl,
1689
- cancelUrl
1690
- }),
1691
- methodName: "checkout"
1692
- });
1693
- if (response.success) {
1694
- return response.data;
1695
- }
1696
- throw new Error(response.message);
1697
- } catch (error) {
1698
- throw new Error(`Failed to checkout: ${error.message}`);
1699
- }
1700
- }
1701
- async getSubscriptionStatus(projectId) {
1702
- this._requireReady("getSubscriptionStatus");
1703
- if (!projectId) {
1704
- throw new Error("Project ID is required");
1705
- }
1706
- try {
1707
- const response = await this._request(`/payments/subscription/${projectId}`, {
1708
- method: "GET",
1709
- methodName: "getSubscriptionStatus"
1710
- });
1711
- if (response.success) {
1712
- return response.data;
1713
- }
1714
- throw new Error(response.message);
1715
- } catch (error) {
1716
- throw new Error(`Failed to get subscription status: ${error.message}`);
1717
- }
1718
- }
1719
- // ==================== DNS METHODS ====================
1720
- async createDnsRecord(domain, options = {}) {
1721
- this._requireReady("createDnsRecord");
1722
- if (!domain) {
1723
- throw new Error("Domain is required");
1724
- }
1725
- try {
1726
- const response = await this._request("/dns/records", {
1727
- method: "POST",
1728
- body: JSON.stringify({ domain, ...options }),
1729
- methodName: "createDnsRecord"
1730
- });
1731
- if (response.success) {
1732
- return response.data;
1733
- }
1734
- throw new Error(response.message);
1735
- } catch (error) {
1736
- throw new Error(`Failed to create DNS record: ${error.message}`);
1737
- }
1738
- }
1739
- async getDnsRecord(domain) {
1740
- this._requireReady("getDnsRecord");
1741
- if (!domain) {
1742
- throw new Error("Domain is required");
1743
- }
1744
- try {
1745
- const response = await this._request(`/dns/records/${domain}`, {
1746
- method: "GET",
1747
- methodName: "getDnsRecord"
1748
- });
1749
- if (response.success) {
1750
- return response.data;
1751
- }
1752
- throw new Error(response.message);
1753
- } catch (error) {
1754
- throw new Error(`Failed to get DNS record: ${error.message}`);
1755
- }
1756
- }
1757
- async removeDnsRecord(domain) {
1758
- this._requireReady("removeDnsRecord");
1759
- if (!domain) {
1760
- throw new Error("Domain is required");
1761
- }
1762
- try {
1763
- const response = await this._request(`/dns/records/${domain}`, {
1764
- method: "DELETE",
1765
- methodName: "removeDnsRecord"
1766
- });
1767
- if (response.success) {
1768
- return response.data;
1769
- }
1770
- throw new Error(response.message);
1771
- } catch (error) {
1772
- throw new Error(`Failed to remove DNS record: ${error.message}`);
1773
- }
1774
- }
1775
- async setProjectDomains(projectKey, customDomain, hasCustomDomainAccess = false) {
1776
- this._requireReady("setProjectDomains");
1777
- if (!projectKey) {
1778
- throw new Error("Project key is required");
1779
- }
1780
- try {
1781
- const response = await this._request("/dns/project-domains", {
1782
- method: "POST",
1783
- body: JSON.stringify({
1784
- projectKey,
1785
- customDomain,
1786
- hasCustomDomainAccess
1787
- }),
1788
- methodName: "setProjectDomains"
1789
- });
1790
- if (response.success) {
1791
- return response.data;
1792
- }
1793
- throw new Error(response.message);
1794
- } catch (error) {
1795
- throw new Error(`Failed to set project domains: ${error.message}`);
1796
- }
1797
- }
1798
- // ==================== UTILITY METHODS ====================
1799
- async getHealthStatus() {
1800
- try {
1801
- const response = await this._request("/health", {
1802
- method: "GET",
1803
- methodName: "getHealthStatus"
1804
- });
1805
- if (response.success) {
1806
- return response.data;
1807
- }
1808
- throw new Error(response.message);
1809
- } catch (error) {
1810
- throw new Error(`Failed to get health status: ${error.message}`);
1811
- }
1812
- }
1813
- // ==================== PROJECT DATA METHODS (SYMSTORY REPLACEMENT) ====================
1814
- /**
1815
- * Apply changes to a project, creating a new version
1816
- * Replaces: SymstoryService.updateData()
1817
- */
1818
- async applyProjectChanges(projectId, changes, options = {}) {
1819
- this._requireReady("applyProjectChanges");
1820
- if (!projectId) {
1821
- throw new Error("Project ID is required");
1822
- }
1823
- if (!Array.isArray(changes)) {
1824
- throw new Error("Changes must be an array");
1825
- }
1826
- const {
1827
- message,
1828
- branch = "main",
1829
- type = "patch"
1830
- } = options;
1831
- try {
1832
- const response = await this._request(`/projects/${projectId}/changes`, {
1833
- method: "POST",
1834
- body: JSON.stringify({
1835
- changes,
1836
- message,
1837
- branch,
1838
- type
1839
- }),
1840
- methodName: "applyProjectChanges"
1841
- });
1842
- if (response.success) {
1843
- return response.data;
1844
- }
1845
- throw new Error(response.message);
1846
- } catch (error) {
1847
- throw new Error(`Failed to apply project changes: ${error.message}`);
1848
- }
1849
- }
1850
- /**
1851
- * Get current project data for a specific branch
1852
- * Replaces: SymstoryService.getData()
1853
- */
1854
- async getProjectData(projectId, options = {}) {
1855
- this._requireReady("getProjectData");
1856
- if (!projectId) {
1857
- throw new Error("Project ID is required");
1858
- }
1859
- const {
1860
- branch = "main",
1861
- version = "latest",
1862
- includeHistory = false
1863
- } = options;
1864
- const queryParams = new URLSearchParams({
1865
- branch,
1866
- version,
1867
- includeHistory: includeHistory.toString()
1868
- }).toString();
1869
- try {
1870
- const response = await this._request(`/projects/${projectId}/data?${queryParams}`, {
1871
- method: "GET",
1872
- methodName: "getProjectData"
1873
- });
1874
- if (response.success) {
1875
- return response.data;
1876
- }
1877
- throw new Error(response.message);
1878
- } catch (error) {
1879
- throw new Error(`Failed to get project data: ${error.message}`);
1880
- }
1881
- }
1882
- /**
1883
- * Get project versions with pagination
1884
- */
1885
- async getProjectVersions(projectId, options = {}) {
1886
- this._requireReady("getProjectVersions");
1887
- if (!projectId) {
1888
- throw new Error("Project ID is required");
1889
- }
1890
- const {
1891
- branch = "main",
1892
- page = 1,
1893
- limit = 50
1894
- } = options;
1895
- const queryParams = new URLSearchParams({
1896
- branch,
1897
- page: page.toString(),
1898
- limit: limit.toString()
1899
- }).toString();
1900
- try {
1901
- const response = await this._request(`/projects/${projectId}/versions?${queryParams}`, {
1902
- method: "GET",
1903
- methodName: "getProjectVersions"
1904
- });
1905
- if (response.success) {
1906
- return response.data;
1907
- }
1908
- throw new Error(response.message);
1909
- } catch (error) {
1910
- throw new Error(`Failed to get project versions: ${error.message}`);
1911
- }
1912
- }
1913
- /**
1914
- * Restore project to a previous version
1915
- * Replaces: SymstoryService.restoreVersion()
1916
- */
1917
- async restoreProjectVersion(projectId, version, options = {}) {
1918
- this._requireReady("restoreProjectVersion");
1919
- if (!projectId) {
1920
- throw new Error("Project ID is required");
1921
- }
1922
- if (!version) {
1923
- throw new Error("Version is required");
1924
- }
1925
- const {
1926
- message,
1927
- branch = "main",
1928
- type = "patch"
1929
- } = options;
1930
- try {
1931
- const response = await this._request(`/projects/${projectId}/restore`, {
1932
- method: "POST",
1933
- body: JSON.stringify({
1934
- version,
1935
- message,
1936
- branch,
1937
- type
1938
- }),
1939
- methodName: "restoreProjectVersion"
1940
- });
1941
- if (response.success) {
1942
- return response.data;
1943
- }
1944
- throw new Error(response.message);
1945
- } catch (error) {
1946
- throw new Error(`Failed to restore project version: ${error.message}`);
1947
- }
1948
- }
1949
- /**
1950
- * Helper method to update a single item in the project
1951
- * Convenience wrapper around applyProjectChanges
1952
- */
1953
- async updateProjectItem(projectId, path, value, options = {}) {
1954
- const changes = [["update", path, value]];
1955
- const message = options.message || `Updated ${Array.isArray(path) ? path.join(".") : path}`;
1956
- return await this.applyProjectChanges(projectId, changes, {
1957
- ...options,
1958
- message
1959
- });
1960
- }
1961
- /**
1962
- * Helper method to delete an item from the project
1963
- * Convenience wrapper around applyProjectChanges
1964
- */
1965
- async deleteProjectItem(projectId, path, options = {}) {
1966
- const changes = [["delete", path]];
1967
- const message = options.message || `Deleted ${Array.isArray(path) ? path.join(".") : path}`;
1968
- return await this.applyProjectChanges(projectId, changes, {
1969
- ...options,
1970
- message
1971
- });
1972
- }
1973
- /**
1974
- * Helper method to set a value in the project (alias for update)
1975
- * Convenience wrapper around applyProjectChanges
1976
- */
1977
- async setProjectValue(projectId, path, value, options = {}) {
1978
- const changes = [["set", path, value]];
1979
- const message = options.message || `Set ${Array.isArray(path) ? path.join(".") : path}`;
1980
- return await this.applyProjectChanges(projectId, changes, {
1981
- ...options,
1982
- message
1983
- });
1984
- }
1985
- /**
1986
- * Helper method to add multiple items to the project
1987
- * Convenience wrapper around applyProjectChanges
1988
- */
1989
- async addProjectItems(projectId, items, options = {}) {
1990
- const changes = items.map((item) => {
1991
- const [type, data] = item;
1992
- const { value, ...schema } = data;
1993
- return [
1994
- ["update", [type, data.key], value],
1995
- ["update", ["schema", type, data.key], schema]
1996
- ];
1997
- }).flat();
1998
- const message = options.message || `Added ${items.length} items`;
1999
- return await this.applyProjectChanges(projectId, changes, {
2000
- ...options,
2001
- message
2002
- });
2003
- }
2004
- /**
2005
- * Helper method to get specific data from project by path
2006
- * Convenience wrapper that gets project data and extracts specific path
2007
- */
2008
- async getProjectItemByPath(projectId, path, options = {}) {
2009
- const projectData = await this.getProjectData(projectId, options);
2010
- if (!(projectData == null ? void 0 : projectData.data)) {
2011
- return null;
2012
- }
2013
- let current = projectData.data;
2014
- const pathArray = Array.isArray(path) ? path : [path];
2015
- for (const segment of pathArray) {
2016
- if (current && typeof current === "object" && segment in current) {
2017
- current = current[segment];
2018
- } else {
2019
- return null;
2020
- }
2021
- }
2022
- return current;
2023
- }
2024
- // ==================== PULL REQUEST METHODS ====================
2025
- /**
2026
- * Create a new pull request
2027
- */
2028
- async createPullRequest(projectId, pullRequestData) {
2029
- this._requireReady("createPullRequest");
2030
- if (!projectId) {
2031
- throw new Error("Project ID is required");
2032
- }
2033
- if (!pullRequestData.source || !pullRequestData.target || !pullRequestData.title) {
2034
- throw new Error("Source branch, target branch, and title are required");
2035
- }
2036
- try {
2037
- const response = await this._request(`/projects/${projectId}/pull-requests`, {
2038
- method: "POST",
2039
- body: JSON.stringify(pullRequestData),
2040
- methodName: "createPullRequest"
2041
- });
2042
- if (response.success) {
2043
- return response.data;
2044
- }
2045
- throw new Error(response.message);
2046
- } catch (error) {
2047
- throw new Error(`Failed to create pull request: ${error.message}`);
2048
- }
2049
- }
2050
- /**
2051
- * List pull requests for a project with filtering options
2052
- */
2053
- async listPullRequests(projectId, options = {}) {
2054
- this._requireReady("listPullRequests");
2055
- if (!projectId) {
2056
- throw new Error("Project ID is required");
2057
- }
2058
- const {
2059
- status = "open",
2060
- source,
2061
- target,
2062
- page = 1,
2063
- limit = 20
2064
- } = options;
2065
- const queryParams = new URLSearchParams({
2066
- status,
2067
- page: page.toString(),
2068
- limit: limit.toString()
2069
- });
2070
- if (source) {
2071
- queryParams.append("source", source);
2072
- }
2073
- if (target) {
2074
- queryParams.append("target", target);
2075
- }
2076
- try {
2077
- const response = await this._request(`/projects/${projectId}/pull-requests?${queryParams.toString()}`, {
2078
- method: "GET",
2079
- methodName: "listPullRequests"
2080
- });
2081
- if (response.success) {
2082
- return response.data;
2083
- }
2084
- throw new Error(response.message);
2085
- } catch (error) {
2086
- throw new Error(`Failed to list pull requests: ${error.message}`);
2087
- }
2088
- }
2089
- /**
2090
- * Get detailed information about a specific pull request
2091
- */
2092
- async getPullRequest(projectId, prId) {
2093
- this._requireReady("getPullRequest");
2094
- if (!projectId) {
2095
- throw new Error("Project ID is required");
2096
- }
2097
- if (!prId) {
2098
- throw new Error("Pull request ID is required");
2099
- }
2100
- try {
2101
- const response = await this._request(`/projects/${projectId}/pull-requests/${prId}`, {
2102
- method: "GET",
2103
- methodName: "getPullRequest"
2104
- });
2105
- if (response.success) {
2106
- return response.data;
2107
- }
2108
- throw new Error(response.message);
2109
- } catch (error) {
2110
- throw new Error(`Failed to get pull request: ${error.message}`);
2111
- }
2112
- }
2113
- /**
2114
- * Submit a review for a pull request
2115
- */
2116
- async reviewPullRequest(projectId, prId, reviewData) {
2117
- this._requireReady("reviewPullRequest");
2118
- if (!projectId) {
2119
- throw new Error("Project ID is required");
2120
- }
2121
- if (!prId) {
2122
- throw new Error("Pull request ID is required");
2123
- }
2124
- const validStatuses = ["approved", "requested_changes", "feedback"];
2125
- if (reviewData.status && !validStatuses.includes(reviewData.status)) {
2126
- throw new Error(`Invalid review status. Must be one of: ${validStatuses.join(", ")}`);
2127
- }
2128
- try {
2129
- const response = await this._request(`/projects/${projectId}/pull-requests/${prId}/review`, {
2130
- method: "POST",
2131
- body: JSON.stringify(reviewData),
2132
- methodName: "reviewPullRequest"
2133
- });
2134
- if (response.success) {
2135
- return response.data;
2136
- }
2137
- throw new Error(response.message);
2138
- } catch (error) {
2139
- throw new Error(`Failed to review pull request: ${error.message}`);
2140
- }
2141
- }
2142
- /**
2143
- * Add a comment to an existing review thread
2144
- */
2145
- async addPullRequestComment(projectId, prId, commentData) {
2146
- this._requireReady("addPullRequestComment");
2147
- if (!projectId) {
2148
- throw new Error("Project ID is required");
2149
- }
2150
- if (!prId) {
2151
- throw new Error("Pull request ID is required");
2152
- }
2153
- if (!commentData.value) {
2154
- throw new Error("Comment value is required");
2155
- }
2156
- try {
2157
- const response = await this._request(`/projects/${projectId}/pull-requests/${prId}/comment`, {
2158
- method: "POST",
2159
- body: JSON.stringify(commentData),
2160
- methodName: "addPullRequestComment"
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 add pull request comment: ${error.message}`);
2168
- }
2169
- }
2170
- /**
2171
- * Merge an approved pull request
2172
- */
2173
- async mergePullRequest(projectId, prId) {
2174
- this._requireReady("mergePullRequest");
2175
- if (!projectId) {
2176
- throw new Error("Project ID is required");
2177
- }
2178
- if (!prId) {
2179
- throw new Error("Pull request ID is required");
2180
- }
2181
- try {
2182
- const response = await this._request(`/projects/${projectId}/pull-requests/${prId}/merge`, {
2183
- method: "POST",
2184
- methodName: "mergePullRequest"
2185
- });
2186
- if (response.success) {
2187
- return response.data;
2188
- }
2189
- throw new Error(response.message);
2190
- } catch (error) {
2191
- if (error.message.includes("conflicts") || error.message.includes("409")) {
2192
- throw new Error(`Pull request has merge conflicts: ${error.message}`);
2193
- }
2194
- throw new Error(`Failed to merge pull request: ${error.message}`);
2195
- }
2196
- }
2197
- /**
2198
- * Get the diff/changes for a pull request
2199
- */
2200
- async getPullRequestDiff(projectId, prId) {
2201
- this._requireReady("getPullRequestDiff");
2202
- if (!projectId) {
2203
- throw new Error("Project ID is required");
2204
- }
2205
- if (!prId) {
2206
- throw new Error("Pull request ID is required");
2207
- }
2208
- try {
2209
- const response = await this._request(`/projects/${projectId}/pull-requests/${prId}/diff`, {
2210
- method: "GET",
2211
- methodName: "getPullRequestDiff"
2212
- });
2213
- if (response.success) {
2214
- return response.data;
2215
- }
2216
- throw new Error(response.message);
2217
- } catch (error) {
2218
- throw new Error(`Failed to get pull request diff: ${error.message}`);
2219
- }
2220
- }
2221
- /**
2222
- * Helper method to create a pull request with validation
2223
- */
2224
- async createPullRequestWithValidation(projectId, data) {
2225
- const { source, target, title, description, changes } = data;
2226
- if (source === target) {
2227
- throw new Error("Source and target branches cannot be the same");
2228
- }
2229
- if (!title || title.trim().length === 0) {
2230
- throw new Error("Pull request title cannot be empty");
2231
- }
2232
- if (title.length > 200) {
2233
- throw new Error("Pull request title cannot exceed 200 characters");
2234
- }
2235
- const pullRequestData = {
2236
- source: source.trim(),
2237
- target: target.trim(),
2238
- title: title.trim(),
2239
- ...description && { description: description.trim() },
2240
- ...changes && { changes }
2241
- };
2242
- return await this.createPullRequest(projectId, pullRequestData);
2243
- }
2244
- /**
2245
- * Helper method to approve a pull request
2246
- */
2247
- async approvePullRequest(projectId, prId, comment = "") {
2248
- const reviewData = {
2249
- status: "approved",
2250
- ...comment && {
2251
- threads: [{
2252
- comment,
2253
- type: "praise"
2254
- }]
2255
- }
2256
- };
2257
- return await this.reviewPullRequest(projectId, prId, reviewData);
2258
- }
2259
- /**
2260
- * Helper method to request changes on a pull request
2261
- */
2262
- async requestPullRequestChanges(projectId, prId, threads = []) {
2263
- if (!threads || threads.length === 0) {
2264
- throw new Error("Must provide specific feedback when requesting changes");
2265
- }
2266
- const reviewData = {
2267
- status: "requested_changes",
2268
- threads
2269
- };
2270
- return await this.reviewPullRequest(projectId, prId, reviewData);
2271
- }
2272
- /**
2273
- * Helper method to get pull requests by status
2274
- */
2275
- async getOpenPullRequests(projectId, options = {}) {
2276
- return await this.listPullRequests(projectId, { ...options, status: "open" });
2277
- }
2278
- async getClosedPullRequests(projectId, options = {}) {
2279
- return await this.listPullRequests(projectId, { ...options, status: "closed" });
2280
- }
2281
- async getMergedPullRequests(projectId, options = {}) {
2282
- return await this.listPullRequests(projectId, { ...options, status: "merged" });
2283
- }
2284
- /**
2285
- * Helper method to check if a pull request is canMerge
2286
- */
2287
- async isPullRequestMergeable(projectId, prId) {
2288
- var _a;
2289
- try {
2290
- const prData = await this.getPullRequest(projectId, prId);
2291
- return ((_a = prData == null ? void 0 : prData.data) == null ? void 0 : _a.canMerge) || false;
2292
- } catch (error) {
2293
- throw new Error(`Failed to check pull request mergeability: ${error.message}`);
2294
- }
2295
- }
2296
- /**
2297
- * Helper method to get pull request status summary
2298
- */
2299
- async getPullRequestStatusSummary(projectId, prId) {
2300
- var _a, _b, _c;
2301
- try {
2302
- const prData = await this.getPullRequest(projectId, prId);
2303
- const pr = prData == null ? void 0 : prData.data;
2304
- if (!pr) {
2305
- throw new Error("Pull request not found");
2306
- }
2307
- return {
2308
- status: pr.status,
2309
- reviewStatus: pr.reviewStatus,
2310
- canMerge: pr.canMerge,
2311
- hasConflicts: !pr.canMerge,
2312
- reviewCount: ((_a = pr.reviews) == null ? void 0 : _a.length) || 0,
2313
- approvedReviews: ((_b = pr.reviews) == null ? void 0 : _b.filter((r) => r.status === "approved").length) || 0,
2314
- changesRequested: ((_c = pr.reviews) == null ? void 0 : _c.filter((r) => r.status === "requested_changes").length) || 0
2315
- };
2316
- } catch (error) {
2317
- throw new Error(`Failed to get pull request status summary: ${error.message}`);
2318
- }
2319
- }
2320
- // ==================== BRANCH MANAGEMENT METHODS ====================
2321
- /**
2322
- * Get all branches for a project
2323
- */
2324
- async listBranches(projectId) {
2325
- this._requireReady("listBranches");
2326
- if (!projectId) {
2327
- throw new Error("Project ID is required");
2328
- }
2329
- try {
2330
- const response = await this._request(`/projects/${projectId}/branches`, {
2331
- method: "GET",
2332
- methodName: "listBranches"
2333
- });
2334
- if (response.success) {
2335
- return response.data;
2336
- }
2337
- throw new Error(response.message);
2338
- } catch (error) {
2339
- throw new Error(`Failed to list branches: ${error.message}`);
2340
- }
2341
- }
2342
- /**
2343
- * Create a new branch from an existing branch
2344
- */
2345
- async createBranch(projectId, branchData) {
2346
- this._requireReady("createBranch");
2347
- if (!projectId) {
2348
- throw new Error("Project ID is required");
2349
- }
2350
- if (!branchData.name) {
2351
- throw new Error("Branch name is required");
2352
- }
2353
- const { name, source = "main" } = branchData;
2354
- try {
2355
- const response = await this._request(`/projects/${projectId}/branches`, {
2356
- method: "POST",
2357
- body: JSON.stringify({ name, source }),
2358
- methodName: "createBranch"
2359
- });
2360
- if (response.success) {
2361
- return response.data;
2362
- }
2363
- throw new Error(response.message);
2364
- } catch (error) {
2365
- throw new Error(`Failed to create branch: ${error.message}`);
2366
- }
2367
- }
2368
- /**
2369
- * Delete a branch (cannot delete main branch)
2370
- */
2371
- async deleteBranch(projectId, branchName) {
2372
- this._requireReady("deleteBranch");
2373
- if (!projectId) {
2374
- throw new Error("Project ID is required");
2375
- }
2376
- if (!branchName) {
2377
- throw new Error("Branch name is required");
2378
- }
2379
- if (branchName === "main") {
2380
- throw new Error("Cannot delete main branch");
2381
- }
2382
- try {
2383
- const response = await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}`, {
2384
- method: "DELETE",
2385
- methodName: "deleteBranch"
2386
- });
2387
- if (response.success) {
2388
- return response.data;
2389
- }
2390
- throw new Error(response.message);
2391
- } catch (error) {
2392
- throw new Error(`Failed to delete branch: ${error.message}`);
2393
- }
2394
- }
2395
- /**
2396
- * Rename a branch (cannot rename main branch)
2397
- */
2398
- async renameBranch(projectId, branchName, newName) {
2399
- this._requireReady("renameBranch");
2400
- if (!projectId) {
2401
- throw new Error("Project ID is required");
2402
- }
2403
- if (!branchName) {
2404
- throw new Error("Current branch name is required");
2405
- }
2406
- if (!newName) {
2407
- throw new Error("New branch name is required");
2408
- }
2409
- if (branchName === "main") {
2410
- throw new Error("Cannot rename main branch");
2411
- }
2412
- try {
2413
- const response = await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}/rename`, {
2414
- method: "POST",
2415
- body: JSON.stringify({ newName }),
2416
- methodName: "renameBranch"
2417
- });
2418
- if (response.success) {
2419
- return response.data;
2420
- }
2421
- throw new Error(response.message);
2422
- } catch (error) {
2423
- throw new Error(`Failed to rename branch: ${error.message}`);
2424
- }
2425
- }
2426
- /**
2427
- * Get changes/diff for a branch compared to another version
2428
- */
2429
- async getBranchChanges(projectId, branchName = "main", options = {}) {
2430
- this._requireReady("getBranchChanges");
2431
- if (!projectId) {
2432
- throw new Error("Project ID is required");
2433
- }
2434
- if (!branchName) {
2435
- throw new Error("Branch name is required");
2436
- }
2437
- const { versionId, versionValue, target } = options;
2438
- const queryParams = new URLSearchParams();
2439
- if (versionId) {
2440
- queryParams.append("versionId", versionId);
2441
- }
2442
- if (versionValue) {
2443
- queryParams.append("versionValue", versionValue);
2444
- }
2445
- if (target) {
2446
- queryParams.append("target", target);
2447
- }
2448
- const queryString = queryParams.toString();
2449
- const url = `/projects/${projectId}/branches/${encodeURIComponent(branchName)}/changes${queryString ? `?${queryString}` : ""}`;
2450
- try {
2451
- const response = await this._request(url, {
2452
- method: "GET",
2453
- methodName: "getBranchChanges"
2454
- });
2455
- if (response.success) {
2456
- return response.data;
2457
- }
2458
- throw new Error(response.message);
2459
- } catch (error) {
2460
- throw new Error(`Failed to get branch changes: ${error.message}`);
2461
- }
2462
- }
2463
- /**
2464
- * Merge changes between branches (preview or commit)
2465
- */
2466
- async mergeBranch(projectId, branchName, mergeData = {}) {
2467
- this._requireReady("mergeBranch");
2468
- if (!projectId) {
2469
- throw new Error("Project ID is required");
2470
- }
2471
- if (!branchName) {
2472
- throw new Error("Source branch name is required");
2473
- }
2474
- const {
2475
- target = "main",
2476
- message,
2477
- type = "patch",
2478
- commit = false,
2479
- changes
2480
- } = mergeData;
2481
- const requestBody = {
2482
- target,
2483
- type,
2484
- commit,
2485
- ...message && { message },
2486
- ...changes && { changes }
2487
- };
2488
- try {
2489
- const response = await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}/merge`, {
2490
- method: "POST",
2491
- body: JSON.stringify(requestBody),
2492
- methodName: "mergeBranch"
2493
- });
2494
- if (response.success) {
2495
- return response.data;
2496
- }
2497
- throw new Error(response.message);
2498
- } catch (error) {
2499
- if (error.message.includes("conflicts") || error.message.includes("409")) {
2500
- throw new Error(`Merge conflicts detected: ${error.message}`);
2501
- }
2502
- throw new Error(`Failed to merge branch: ${error.message}`);
2503
- }
2504
- }
2505
- /**
2506
- * Reset a branch to a clean state
2507
- */
2508
- async resetBranch(projectId, branchName) {
2509
- this._requireReady("resetBranch");
2510
- if (!projectId) {
2511
- throw new Error("Project ID is required");
2512
- }
2513
- if (!branchName) {
2514
- throw new Error("Branch name is required");
2515
- }
2516
- try {
2517
- const response = await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}/reset`, {
2518
- method: "POST",
2519
- methodName: "resetBranch"
2520
- });
2521
- if (response.success) {
2522
- return response.data;
2523
- }
2524
- throw new Error(response.message);
2525
- } catch (error) {
2526
- throw new Error(`Failed to reset branch: ${error.message}`);
2527
- }
2528
- }
2529
- /**
2530
- * Publish a specific version as the live version
2531
- */
2532
- async publishVersion(projectId, publishData) {
2533
- this._requireReady("publishVersion");
2534
- if (!projectId) {
2535
- throw new Error("Project ID is required");
2536
- }
2537
- if (!publishData.version) {
2538
- throw new Error("Version is required");
2539
- }
2540
- const { version, branch = "main" } = publishData;
2541
- try {
2542
- const response = await this._request(`/projects/${projectId}/publish`, {
2543
- method: "POST",
2544
- body: JSON.stringify({ version, branch }),
2545
- methodName: "publishVersion"
2546
- });
2547
- if (response.success) {
2548
- return response.data;
2549
- }
2550
- throw new Error(response.message);
2551
- } catch (error) {
2552
- throw new Error(`Failed to publish version: ${error.message}`);
2553
- }
2554
- }
2555
- // ==================== BRANCH HELPER METHODS ====================
2556
- /**
2557
- * Helper method to create a branch with validation
2558
- */
2559
- async createBranchWithValidation(projectId, name, source = "main") {
2560
- if (!name || name.trim().length === 0) {
2561
- throw new Error("Branch name cannot be empty");
2562
- }
2563
- if (name.includes(" ")) {
2564
- throw new Error("Branch name cannot contain spaces");
2565
- }
2566
- if (name === "main") {
2567
- throw new Error('Cannot create a branch named "main"');
2568
- }
2569
- const sanitizedName = name.trim().toLowerCase().replace(/[^a-z0-9-_]/gu, "-");
2570
- return await this.createBranch(projectId, {
2571
- name: sanitizedName,
2572
- source
2573
- });
2574
- }
2575
- /**
2576
- * Helper method to check if a branch exists
2577
- */
2578
- async branchExists(projectId, branchName) {
2579
- var _a;
2580
- try {
2581
- const branches = await this.listBranches(projectId);
2582
- return ((_a = branches == null ? void 0 : branches.data) == null ? void 0 : _a.includes(branchName)) || false;
2583
- } catch (error) {
2584
- throw new Error(`Failed to check if branch exists: ${error.message}`);
2585
- }
2586
- }
2587
- /**
2588
- * Helper method to preview merge without committing
2589
- */
2590
- async previewMerge(projectId, sourceBranch, targetBranch = "main") {
2591
- return await this.mergeBranch(projectId, sourceBranch, {
2592
- target: targetBranch,
2593
- commit: false
2594
- });
2595
- }
2596
- /**
2597
- * Helper method to commit merge after preview
2598
- */
2599
- async commitMerge(projectId, sourceBranch, options = {}) {
2600
- const {
2601
- target = "main",
2602
- message = `Merge ${sourceBranch} into ${target}`,
2603
- type = "patch",
2604
- changes
2605
- } = options;
2606
- return await this.mergeBranch(projectId, sourceBranch, {
2607
- target,
2608
- message,
2609
- type,
2610
- commit: true,
2611
- changes
2612
- });
2613
- }
2614
- /**
2615
- * Helper method to create a feature branch from main
2616
- */
2617
- async createFeatureBranch(projectId, featureName) {
2618
- const branchName = `feature/${featureName.toLowerCase().replace(/[^a-z0-9-]/gu, "-")}`;
2619
- return await this.createBranch(projectId, {
2620
- name: branchName,
2621
- source: "main"
2622
- });
2623
- }
2624
- /**
2625
- * Helper method to create a hotfix branch from main
2626
- */
2627
- async createHotfixBranch(projectId, hotfixName) {
2628
- const branchName = `hotfix/${hotfixName.toLowerCase().replace(/[^a-z0-9-]/gu, "-")}`;
2629
- return await this.createBranch(projectId, {
2630
- name: branchName,
2631
- source: "main"
2632
- });
2633
- }
2634
- /**
2635
- * Helper method to get branch status summary
2636
- */
2637
- async getBranchStatus(projectId, branchName) {
2638
- var _a, _b, _c;
2639
- try {
2640
- const [branches, changes] = await Promise.all([
2641
- this.listBranches(projectId),
2642
- this.getBranchChanges(projectId, branchName).catch(() => null)
2643
- ]);
2644
- const exists = ((_a = branches == null ? void 0 : branches.data) == null ? void 0 : _a.includes(branchName)) || false;
2645
- const hasChanges = ((_b = changes == null ? void 0 : changes.data) == null ? void 0 : _b.length) > 0;
2646
- return {
2647
- exists,
2648
- hasChanges,
2649
- changeCount: ((_c = changes == null ? void 0 : changes.data) == null ? void 0 : _c.length) || 0,
2650
- canDelete: exists && branchName !== "main",
2651
- canRename: exists && branchName !== "main"
2652
- };
2653
- } catch (error) {
2654
- throw new Error(`Failed to get branch status: ${error.message}`);
2655
- }
2656
- }
2657
- /**
2658
- * Helper method to safely delete a branch with confirmation
2659
- */
2660
- async deleteBranchSafely(projectId, branchName, options = {}) {
2661
- const { force = false } = options;
2662
- if (!force) {
2663
- const status = await this.getBranchStatus(projectId, branchName);
2664
- if (!status.exists) {
2665
- throw new Error(`Branch '${branchName}' does not exist`);
2666
- }
2667
- if (!status.canDelete) {
2668
- throw new Error(`Branch '${branchName}' cannot be deleted`);
2669
- }
2670
- if (status.hasChanges) {
2671
- throw new Error(`Branch '${branchName}' has uncommitted changes. Use force option to delete anyway.`);
2672
- }
2673
- }
2674
- return await this.deleteBranch(projectId, branchName);
2675
- }
2676
- // ==================== ADMIN METHODS ====================
2677
- /**
2678
- * Get admin users list with comprehensive filtering and search capabilities
2679
- * Requires admin or super_admin global role
2680
- */
2681
- async getAdminUsers(params = {}) {
2682
- this._requireReady("getAdminUsers");
2683
- const {
2684
- emails,
2685
- ids,
2686
- query,
2687
- status,
2688
- page = 1,
2689
- limit = 50,
2690
- sort = { field: "createdAt", order: "desc" }
2691
- } = params;
2692
- const queryParams = new URLSearchParams();
2693
- if (emails) {
2694
- queryParams.append("emails", emails);
2695
- }
2696
- if (ids) {
2697
- queryParams.append("ids", ids);
2698
- }
2699
- if (query) {
2700
- queryParams.append("query", query);
2701
- }
2702
- if (status) {
2703
- queryParams.append("status", status);
2704
- }
2705
- if (page) {
2706
- queryParams.append("page", page.toString());
2707
- }
2708
- if (limit) {
2709
- queryParams.append("limit", limit.toString());
2710
- }
2711
- if (sort && sort.field) {
2712
- queryParams.append("sort[field]", sort.field);
2713
- queryParams.append("sort[order]", sort.order || "desc");
2714
- }
2715
- const queryString = queryParams.toString();
2716
- const url = `/users/admin/users${queryString ? `?${queryString}` : ""}`;
2717
- try {
2718
- const response = await this._request(url, {
2719
- method: "GET",
2720
- methodName: "getAdminUsers"
2721
- });
2722
- if (response.success) {
2723
- return response.data;
2724
- }
2725
- throw new Error(response.message);
2726
- } catch (error) {
2727
- throw new Error(`Failed to get admin users: ${error.message}`);
2728
- }
2729
- }
2730
- /**
2731
- * Assign projects to a specific user
2732
- * Requires admin or super_admin global role
2733
- */
2734
- async assignProjectsToUser(userId, options = {}) {
2735
- this._requireReady("assignProjectsToUser");
2736
- if (!userId) {
2737
- throw new Error("User ID is required");
2738
- }
2739
- const {
2740
- projectIds,
2741
- role = "guest"
2742
- } = options;
2743
- const requestBody = {
2744
- userId,
2745
- role
2746
- };
2747
- if (projectIds && Array.isArray(projectIds)) {
2748
- requestBody.projectIds = projectIds;
2749
- }
2750
- try {
2751
- const response = await this._request("/assign-projects", {
2752
- method: "POST",
2753
- body: JSON.stringify(requestBody),
2754
- methodName: "assignProjectsToUser"
2755
- });
2756
- if (response.success) {
2757
- return response.data;
2758
- }
2759
- throw new Error(response.message);
2760
- } catch (error) {
2761
- throw new Error(`Failed to assign projects to user: ${error.message}`);
2762
- }
2763
- }
2764
- /**
2765
- * Helper method for admin users search
2766
- */
2767
- async searchAdminUsers(searchQuery, options = {}) {
2768
- return await this.getAdminUsers({
2769
- query: searchQuery,
2770
- ...options
2771
- });
2772
- }
2773
- /**
2774
- * Helper method to get admin users by email list
2775
- */
2776
- async getAdminUsersByEmails(emails, options = {}) {
2777
- const emailList = Array.isArray(emails) ? emails.join(",") : emails;
2778
- return await this.getAdminUsers({
2779
- emails: emailList,
2780
- ...options
2781
- });
2782
- }
2783
- /**
2784
- * Helper method to get admin users by ID list
2785
- */
2786
- async getAdminUsersByIds(ids, options = {}) {
2787
- const idList = Array.isArray(ids) ? ids.join(",") : ids;
2788
- return await this.getAdminUsers({
2789
- ids: idList,
2790
- ...options
2791
- });
2792
- }
2793
- /**
2794
- * Helper method to assign specific projects to a user with a specific role
2795
- */
2796
- async assignSpecificProjectsToUser(userId, projectIds, role = "guest") {
2797
- if (!Array.isArray(projectIds) || projectIds.length === 0) {
2798
- throw new Error("Project IDs must be a non-empty array");
2799
- }
2800
- return await this.assignProjectsToUser(userId, {
2801
- projectIds,
2802
- role
2803
- });
2804
- }
2805
- /**
2806
- * Helper method to assign all projects to a user with a specific role
2807
- */
2808
- async assignAllProjectsToUser(userId, role = "guest") {
2809
- return await this.assignProjectsToUser(userId, {
2810
- role
2811
- });
2812
- }
2813
- // Cleanup
2814
- destroy() {
2815
- if (this._tokenManager) {
2816
- this._tokenManager.destroy();
2817
- this._tokenManager = null;
2818
- }
2819
- this._client = null;
2820
- this._initialized = false;
2821
- this._setReady(false);
2822
- }
2823
- };
2824
- export {
2825
- CoreService
2826
- };
2827
- // @preserve-env