@symbo.ls/sdk 3.1.2 → 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 (187) hide show
  1. package/README.md +143 -2
  2. package/dist/cjs/config/environment.js +98 -30
  3. package/dist/cjs/index.js +144 -24
  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 +743 -0
  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 +64 -16
  23. package/dist/cjs/state/RootStateManager.js +65 -0
  24. package/dist/cjs/state/rootEventBus.js +74 -0
  25. package/dist/cjs/utils/CollabClient.js +223 -0
  26. package/dist/cjs/utils/TokenManager.js +78 -30
  27. package/dist/cjs/utils/changePreprocessor.js +199 -0
  28. package/dist/cjs/utils/jsonDiff.js +145 -0
  29. package/dist/cjs/utils/ordering.js +309 -0
  30. package/dist/cjs/utils/services.js +301 -103
  31. package/dist/cjs/utils/validation.js +0 -3
  32. package/dist/esm/config/environment.js +98 -30
  33. package/dist/esm/index.js +49505 -8718
  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 +26895 -0
  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 +49062 -8569
  53. package/dist/esm/state/RootStateManager.js +90 -0
  54. package/dist/esm/state/rootEventBus.js +56 -0
  55. package/dist/esm/utils/CollabClient.js +18889 -0
  56. package/dist/esm/utils/TokenManager.js +78 -30
  57. package/dist/esm/utils/changePreprocessor.js +542 -0
  58. package/dist/esm/utils/jsonDiff.js +7011 -0
  59. package/dist/esm/utils/ordering.js +291 -0
  60. package/dist/esm/utils/services.js +301 -103
  61. package/dist/esm/utils/validation.js +116 -50
  62. package/dist/node/config/environment.js +98 -30
  63. package/dist/node/index.js +175 -32
  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 +724 -0
  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 +64 -16
  83. package/dist/node/state/RootStateManager.js +36 -0
  84. package/dist/node/state/rootEventBus.js +55 -0
  85. package/dist/node/utils/CollabClient.js +194 -0
  86. package/dist/node/utils/TokenManager.js +78 -30
  87. package/dist/node/utils/changePreprocessor.js +180 -0
  88. package/dist/node/utils/jsonDiff.js +116 -0
  89. package/dist/node/utils/ordering.js +290 -0
  90. package/dist/node/utils/services.js +301 -103
  91. package/dist/node/utils/validation.js +0 -3
  92. package/package.json +39 -21
  93. package/src/config/environment.js +99 -28
  94. package/src/index.js +181 -36
  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 +900 -0
  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 +80 -13
  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 +76 -0
  148. package/src/state/rootEventBus.js +67 -0
  149. package/src/utils/CollabClient.js +248 -0
  150. package/src/utils/TokenManager.js +88 -33
  151. package/src/utils/changePreprocessor.js +239 -0
  152. package/src/utils/jsonDiff.js +144 -0
  153. package/src/utils/ordering.js +271 -0
  154. package/src/utils/services.js +326 -107
  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 -1751
  159. package/dist/cjs/services/SocketIOService.js +0 -307
  160. package/dist/cjs/services/SocketService.js +0 -161
  161. package/dist/cjs/services/SymstoryService.js +0 -571
  162. package/dist/cjs/utils/basedQuerys.js +0 -181
  163. package/dist/cjs/utils/symstoryClient.js +0 -259
  164. package/dist/esm/services/AIService.js +0 -185
  165. package/dist/esm/services/BasedService.js +0 -5278
  166. package/dist/esm/services/CoreService.js +0 -2264
  167. package/dist/esm/services/SocketIOService.js +0 -470
  168. package/dist/esm/services/SocketService.js +0 -191
  169. package/dist/esm/services/SymstoryService.js +0 -7041
  170. package/dist/esm/utils/basedQuerys.js +0 -163
  171. package/dist/esm/utils/symstoryClient.js +0 -370
  172. package/dist/node/services/AIService.js +0 -136
  173. package/dist/node/services/BasedService.js +0 -1156
  174. package/dist/node/services/CoreService.js +0 -1722
  175. package/dist/node/services/SocketIOService.js +0 -278
  176. package/dist/node/services/SocketService.js +0 -142
  177. package/dist/node/services/SymstoryService.js +0 -542
  178. package/dist/node/utils/basedQuerys.js +0 -162
  179. package/dist/node/utils/symstoryClient.js +0 -230
  180. package/src/services/AIService.js +0 -150
  181. package/src/services/BasedService.js +0 -1301
  182. package/src/services/CoreService.js +0 -1943
  183. package/src/services/SocketIOService.js +0 -334
  184. package/src/services/SocketService.js +0 -168
  185. package/src/services/SymstoryService.js +0 -649
  186. package/src/utils/basedQuerys.js +0 -164
  187. package/src/utils/symstoryClient.js +0 -252
@@ -0,0 +1,724 @@
1
+ import { BaseService } from "./BaseService.js";
2
+ import { CollabClient } from "../utils/CollabClient.js";
3
+ import { RootStateManager } from "../state/RootStateManager.js";
4
+ import { rootBus } from "../state/rootEventBus.js";
5
+ import { validateParams } from "../utils/validation.js";
6
+ import { deepStringifyFunctions } from "@domql/utils";
7
+ import { preprocessChanges } from "../utils/changePreprocessor.js";
8
+ const FUNCTION_META_KEYS = ["node", "__ref", "__element", "parent", "parse"];
9
+ function stringifyFunctionsForTransport(value, seen = /* @__PURE__ */ new WeakMap()) {
10
+ if (value === null || typeof value !== "object") {
11
+ return typeof value === "function" ? value.toString() : value;
12
+ }
13
+ if (seen.has(value)) {
14
+ return seen.get(value);
15
+ }
16
+ const clone = Array.isArray(value) ? [] : {};
17
+ seen.set(value, clone);
18
+ if (Array.isArray(value)) {
19
+ for (let i = 0; i < value.length; i++) {
20
+ clone[i] = stringifyFunctionsForTransport(value[i], seen);
21
+ }
22
+ return clone;
23
+ }
24
+ const keys = Object.keys(value);
25
+ for (let i = 0; i < keys.length; i++) {
26
+ const key = keys[i];
27
+ if (!FUNCTION_META_KEYS.includes(key)) {
28
+ clone[key] = stringifyFunctionsForTransport(value[key], seen);
29
+ }
30
+ }
31
+ return clone;
32
+ }
33
+ class CollabService extends BaseService {
34
+ constructor(config) {
35
+ super(config);
36
+ this._client = null;
37
+ this._stateManager = null;
38
+ this._connected = false;
39
+ this._connecting = false;
40
+ this._connectPromise = null;
41
+ this._connectionMeta = null;
42
+ this._pendingConnectReject = null;
43
+ this._undoStack = [];
44
+ this._redoStack = [];
45
+ this._isUndoRedo = false;
46
+ this._pendingOps = [];
47
+ this._onSocketConnect = this._onSocketConnect.bind(this);
48
+ this._onSocketDisconnect = this._onSocketDisconnect.bind(this);
49
+ this._onSocketError = this._onSocketError.bind(this);
50
+ }
51
+ init({ context }) {
52
+ super.init({ context });
53
+ if (context == null ? void 0 : context.state) {
54
+ try {
55
+ this._stateManager = new RootStateManager(context.state);
56
+ } catch (err) {
57
+ this._setError(err);
58
+ throw err;
59
+ }
60
+ }
61
+ this._setReady();
62
+ }
63
+ /**
64
+ * Overridden to re-initialise the state manager once the root state becomes
65
+ * available via a subsequent SDK `updateContext()` call.
66
+ */
67
+ updateContext(context = {}) {
68
+ super.updateContext(context);
69
+ if (context.state) {
70
+ this._stateManager = new RootStateManager(context.state);
71
+ }
72
+ }
73
+ /**
74
+ * Ensure that the state manager exists. This is called right before any
75
+ * operation that requires access to the root state (e.g. `connect()`).
76
+ * Throws an explicit error if the root state is still missing so that the
77
+ * caller can react accordingly.
78
+ */
79
+ _ensureStateManager() {
80
+ var _a, _b;
81
+ if (!this._stateManager) {
82
+ if (!((_a = this._context) == null ? void 0 : _a.state)) {
83
+ throw new Error("[CollabService] Cannot operate without root state");
84
+ }
85
+ this._stateManager = new RootStateManager(this._context.state);
86
+ }
87
+ const root = (_b = this._stateManager) == null ? void 0 : _b.root;
88
+ if (root && !root.__element) {
89
+ root.__element = {
90
+ /**
91
+ * Very small subset of the DOMQL `call` API that we rely on inside the
92
+ * CollabService for browser notifications and data helpers.
93
+ * In a Node.js test context we simply log or return fallbacks.
94
+ */
95
+ call: (method, ...args) => {
96
+ switch (method) {
97
+ case "openNotification": {
98
+ const [payload = {}] = args;
99
+ const { type = "info", title = "", message = "" } = payload;
100
+ const logger = type === "error" ? console.error : console.log;
101
+ logger(`[Notification] ${title}${message ? ` \u2013 ${message}` : ""}`);
102
+ return;
103
+ }
104
+ case "deepStringifyFunctions": {
105
+ return deepStringifyFunctions(...args);
106
+ }
107
+ default:
108
+ return {};
109
+ }
110
+ }
111
+ };
112
+ }
113
+ }
114
+ /* ---------- Connection Management ---------- */
115
+ async connect(options = {}) {
116
+ if (this._connectPromise) {
117
+ return this._connectPromise;
118
+ }
119
+ this._connectPromise = (async () => {
120
+ var _a;
121
+ this._connecting = true;
122
+ this._connected = false;
123
+ this._ensureStateManager();
124
+ const mergedOptions = {
125
+ ...this._context,
126
+ ...options
127
+ };
128
+ let { authToken: jwt } = mergedOptions;
129
+ const { projectId, branch = "main", pro } = mergedOptions;
130
+ if (!jwt && this._tokenManager) {
131
+ try {
132
+ jwt = await this._tokenManager.ensureValidToken();
133
+ } catch (error) {
134
+ console.warn(
135
+ "[CollabService] Failed to obtain auth token from token manager",
136
+ error
137
+ );
138
+ }
139
+ if (!jwt && typeof this._tokenManager.getAccessToken === "function") {
140
+ jwt = this._tokenManager.getAccessToken();
141
+ }
142
+ }
143
+ if (!jwt) {
144
+ throw new Error("[CollabService] Cannot connect without auth token");
145
+ }
146
+ this._context = {
147
+ ...this._context,
148
+ authToken: jwt,
149
+ projectId,
150
+ branch,
151
+ pro
152
+ };
153
+ if (!projectId) {
154
+ const state = (_a = this._stateManager) == null ? void 0 : _a.root;
155
+ const el = state.__element;
156
+ el.call("openNotification", {
157
+ type: "error",
158
+ title: "projectId is required",
159
+ message: "projectId is required for CollabService connection"
160
+ });
161
+ throw new Error("projectId is required for CollabService connection");
162
+ }
163
+ if (this._client) {
164
+ await this.disconnect();
165
+ }
166
+ this._client = new CollabClient({
167
+ jwt,
168
+ projectId,
169
+ branch,
170
+ live: Boolean(pro)
171
+ });
172
+ const { socket } = this._client;
173
+ try {
174
+ await new Promise((resolve, reject) => {
175
+ if (!socket) {
176
+ reject(new Error("[CollabService] Socket instance missing"));
177
+ return;
178
+ }
179
+ if (socket.connected) {
180
+ resolve();
181
+ return;
182
+ }
183
+ const cleanup = () => {
184
+ socket.off("connect", handleConnect);
185
+ socket.off("connect_error", handleError);
186
+ socket.off("error", handleError);
187
+ socket.off("disconnect", handleDisconnect);
188
+ if (this._pendingConnectReject === handleError) {
189
+ this._pendingConnectReject = null;
190
+ }
191
+ };
192
+ const handleConnect = () => {
193
+ cleanup();
194
+ resolve();
195
+ };
196
+ const handleError = (error) => {
197
+ cleanup();
198
+ reject(
199
+ error instanceof Error ? error : new Error(String(error || "Unknown connection error"))
200
+ );
201
+ };
202
+ const handleDisconnect = (reason) => {
203
+ handleError(
204
+ reason instanceof Error ? reason : new Error(
205
+ `[CollabService] Socket disconnected before connect: ${reason || "unknown"}`
206
+ )
207
+ );
208
+ };
209
+ this._pendingConnectReject = handleError;
210
+ socket.once("connect", handleConnect);
211
+ socket.once("connect_error", handleError);
212
+ socket.once("error", handleError);
213
+ socket.once("disconnect", handleDisconnect);
214
+ });
215
+ } catch (error) {
216
+ socket == null ? void 0 : socket.disconnect();
217
+ this._client = null;
218
+ this._connectionMeta = null;
219
+ throw error;
220
+ }
221
+ this._attachSocketLifecycleListeners();
222
+ if (socket == null ? void 0 : socket.connected) {
223
+ this._onSocketConnect();
224
+ }
225
+ socket == null ? void 0 : socket.on("ops", ({ changes }) => {
226
+ console.log(`ops event`);
227
+ this._stateManager.applyChanges(changes, { fromSocket: true });
228
+ });
229
+ socket == null ? void 0 : socket.on("commit", ({ version }) => {
230
+ if (version) {
231
+ this._stateManager.setVersion(version);
232
+ }
233
+ rootBus.emit("checkpoint:done", { version, origin: "auto" });
234
+ });
235
+ socket == null ? void 0 : socket.on("clients", this._handleClientsEvent.bind(this));
236
+ socket == null ? void 0 : socket.on("bundle:done", this._handleBundleDoneEvent.bind(this));
237
+ socket == null ? void 0 : socket.on("bundle:error", this._handleBundleErrorEvent.bind(this));
238
+ if (this._pendingOps.length) {
239
+ console.log(
240
+ `[CollabService] Flushing ${this._pendingOps.length} offline operation batch(es)`
241
+ );
242
+ this._pendingOps.forEach(
243
+ ({ changes, granularChanges, orders, options: opOptions }) => {
244
+ const { message } = opOptions || {};
245
+ const ts = Date.now();
246
+ const payload = {
247
+ changes,
248
+ granularChanges,
249
+ orders,
250
+ ts
251
+ };
252
+ if (message) {
253
+ payload.message = message;
254
+ }
255
+ this.socket.emit("ops", payload);
256
+ }
257
+ );
258
+ this._pendingOps.length = 0;
259
+ }
260
+ await this._client.ready;
261
+ this._connectionMeta = {
262
+ projectId,
263
+ branch,
264
+ live: Boolean(pro)
265
+ };
266
+ return this.getConnectionInfo();
267
+ })();
268
+ try {
269
+ return await this._connectPromise;
270
+ } finally {
271
+ this._connecting = false;
272
+ this._connectPromise = null;
273
+ }
274
+ }
275
+ disconnect() {
276
+ var _a;
277
+ if ((_a = this._client) == null ? void 0 : _a.socket) {
278
+ if (this._pendingConnectReject) {
279
+ this._pendingConnectReject(
280
+ new Error("[CollabService] Connection attempt aborted")
281
+ );
282
+ this._pendingConnectReject = null;
283
+ }
284
+ this._detachSocketLifecycleListeners();
285
+ if (typeof this._client.dispose === "function") {
286
+ this._client.dispose();
287
+ } else {
288
+ this._client.socket.disconnect();
289
+ }
290
+ }
291
+ this._client = null;
292
+ this._connected = false;
293
+ this._connecting = false;
294
+ this._connectionMeta = null;
295
+ this._pendingConnectReject = null;
296
+ console.log("[CollabService] Disconnected");
297
+ }
298
+ isConnected() {
299
+ var _a, _b;
300
+ return Boolean(this._connected && ((_b = (_a = this._client) == null ? void 0 : _a.socket) == null ? void 0 : _b.connected));
301
+ }
302
+ getConnectionInfo() {
303
+ var _a, _b, _c;
304
+ return {
305
+ connected: this.isConnected(),
306
+ connecting: this._connecting,
307
+ projectId: ((_a = this._connectionMeta) == null ? void 0 : _a.projectId) ?? null,
308
+ branch: ((_b = this._connectionMeta) == null ? void 0 : _b.branch) ?? null,
309
+ live: ((_c = this._connectionMeta) == null ? void 0 : _c.live) ?? null,
310
+ pendingOps: this._pendingOps.length,
311
+ undoStackSize: this.getUndoStackSize(),
312
+ redoStackSize: this.getRedoStackSize()
313
+ };
314
+ }
315
+ /* convenient shortcuts */
316
+ get ydoc() {
317
+ var _a;
318
+ return (_a = this._client) == null ? void 0 : _a.ydoc;
319
+ }
320
+ get socket() {
321
+ var _a;
322
+ return (_a = this._client) == null ? void 0 : _a.socket;
323
+ }
324
+ toggleLive(f) {
325
+ var _a;
326
+ (_a = this._client) == null ? void 0 : _a.toggleLive(f);
327
+ }
328
+ sendCursor(d) {
329
+ var _a;
330
+ (_a = this._client) == null ? void 0 : _a.sendCursor(d);
331
+ }
332
+ sendPresence(d) {
333
+ var _a;
334
+ (_a = this._client) == null ? void 0 : _a.sendPresence(d);
335
+ }
336
+ /* ---------- data helpers ---------- */
337
+ updateData(tuples, options = {}) {
338
+ var _a, _b;
339
+ this._ensureStateManager();
340
+ const { isUndo = false, isRedo = false } = options;
341
+ if (!isUndo && !isRedo && !this._isUndoRedo) {
342
+ this._trackForUndo(tuples, options);
343
+ }
344
+ const root = (_a = this._stateManager) == null ? void 0 : _a.root;
345
+ const { granularChanges: processedTuples, orders } = preprocessChanges(
346
+ root,
347
+ tuples,
348
+ options
349
+ );
350
+ if (options.append && options.append.length) {
351
+ processedTuples.push(...options.append);
352
+ }
353
+ this._stateManager.applyChanges(tuples, { ...options });
354
+ const stringifiedGranularTuples = stringifyFunctionsForTransport(processedTuples);
355
+ const stringifiedTuples = stringifyFunctionsForTransport(tuples);
356
+ const { message } = options;
357
+ if (!this.isConnected()) {
358
+ console.warn("[CollabService] Not connected, queuing real-time update");
359
+ this._pendingOps.push({
360
+ changes: stringifiedTuples,
361
+ granularChanges: stringifiedGranularTuples,
362
+ orders,
363
+ options
364
+ });
365
+ return;
366
+ }
367
+ if ((_b = this.socket) == null ? void 0 : _b.connected) {
368
+ const ts = Date.now();
369
+ const payload = {
370
+ changes: stringifiedTuples,
371
+ granularChanges: stringifiedGranularTuples,
372
+ orders,
373
+ ts
374
+ };
375
+ if (message) {
376
+ payload.message = message;
377
+ }
378
+ this.socket.emit("ops", payload);
379
+ }
380
+ return { success: true };
381
+ }
382
+ _trackForUndo(tuples, options) {
383
+ var _a;
384
+ const undoOperations = tuples.map((tuple) => {
385
+ const [action, path] = tuple;
386
+ const currentValue = this._getValueAtPath(path);
387
+ if (action === "delete") {
388
+ return ["update", path, currentValue];
389
+ }
390
+ if (typeof currentValue !== "undefined") {
391
+ return ["update", path, currentValue];
392
+ }
393
+ return ["delete", path];
394
+ });
395
+ this._undoStack.push({
396
+ operations: undoOperations,
397
+ originalOperations: tuples,
398
+ options,
399
+ timestamp: Date.now()
400
+ });
401
+ this._redoStack.length = 0;
402
+ const maxUndoSteps = ((_a = this._options) == null ? void 0 : _a.maxUndoSteps) || 50;
403
+ if (this._undoStack.length > maxUndoSteps) {
404
+ this._undoStack.shift();
405
+ }
406
+ }
407
+ _getValueAtPath(path) {
408
+ var _a;
409
+ const state = (_a = this._stateManager) == null ? void 0 : _a.root;
410
+ if (!state || !state.getByPath) {
411
+ return null;
412
+ }
413
+ try {
414
+ return state.getByPath(path);
415
+ } catch (error) {
416
+ console.warn("[CollabService] Could not get value at path:", path, error);
417
+ return null;
418
+ }
419
+ }
420
+ undo() {
421
+ var _a;
422
+ if (!this._undoStack.length) {
423
+ const state = (_a = this._stateManager) == null ? void 0 : _a.root;
424
+ const el = state.__element;
425
+ el.call("openNotification", {
426
+ type: "error",
427
+ title: "Nothing to undo"
428
+ });
429
+ throw new Error("Nothing to undo");
430
+ }
431
+ if (!this.isConnected()) {
432
+ console.warn("[CollabService] Not connected, cannot undo");
433
+ return;
434
+ }
435
+ const undoItem = this._undoStack.pop();
436
+ const { operations, originalOperations, options } = undoItem;
437
+ this._redoStack.push({
438
+ operations: originalOperations,
439
+ originalOperations: operations,
440
+ options,
441
+ timestamp: Date.now()
442
+ });
443
+ this._isUndoRedo = true;
444
+ try {
445
+ this.updateData(operations, {
446
+ ...options,
447
+ isUndo: true,
448
+ message: `Undo: ${options.message || "operation"}`
449
+ });
450
+ } finally {
451
+ this._isUndoRedo = false;
452
+ }
453
+ return operations;
454
+ }
455
+ redo() {
456
+ var _a;
457
+ if (!this._redoStack.length) {
458
+ const state = (_a = this._stateManager) == null ? void 0 : _a.root;
459
+ const el = state.__element;
460
+ el.call("openNotification", {
461
+ type: "error",
462
+ title: "Nothing to redo"
463
+ });
464
+ throw new Error("Nothing to redo");
465
+ }
466
+ if (!this.isConnected()) {
467
+ console.warn("[CollabService] Not connected, cannot redo");
468
+ return;
469
+ }
470
+ const redoItem = this._redoStack.pop();
471
+ const { operations, originalOperations, options } = redoItem;
472
+ this._undoStack.push({
473
+ operations: originalOperations,
474
+ originalOperations: operations,
475
+ options,
476
+ timestamp: Date.now()
477
+ });
478
+ this._isUndoRedo = true;
479
+ try {
480
+ this.updateData(operations, {
481
+ ...options,
482
+ isRedo: true,
483
+ message: `Redo: ${options.message || "operation"}`
484
+ });
485
+ } finally {
486
+ this._isUndoRedo = false;
487
+ }
488
+ return operations;
489
+ }
490
+ /* ---------- Undo/Redo State ---------- */
491
+ canUndo() {
492
+ return this._undoStack.length > 0;
493
+ }
494
+ canRedo() {
495
+ return this._redoStack.length > 0;
496
+ }
497
+ getUndoStackSize() {
498
+ return this._undoStack.length;
499
+ }
500
+ getRedoStackSize() {
501
+ return this._redoStack.length;
502
+ }
503
+ clearUndoHistory() {
504
+ this._undoStack.length = 0;
505
+ this._redoStack.length = 0;
506
+ }
507
+ addItem(type, data, opts = {}) {
508
+ try {
509
+ validateParams.type(type);
510
+ validateParams.data(data, type);
511
+ const { value, ...schema } = data;
512
+ const tuples = [
513
+ ["update", [type, data.key], value],
514
+ ["update", ["schema", type, data.key], schema || {}]
515
+ ];
516
+ const updatedOpts = { ...opts, skipComponentsChangedEvent: true };
517
+ return this.updateData(tuples, updatedOpts);
518
+ } catch (error) {
519
+ throw new Error(`Failed to add item: ${error.message}`, { cause: error });
520
+ }
521
+ }
522
+ addMultipleItems(items, opts = {}) {
523
+ var _a;
524
+ const tuples = [];
525
+ try {
526
+ items.forEach(([type, data]) => {
527
+ validateParams.type(type);
528
+ validateParams.data(data, type);
529
+ const { value, ...schema } = data;
530
+ tuples.push(
531
+ ["update", [type, data.key], value],
532
+ ["update", ["schema", type, data.key], schema]
533
+ );
534
+ });
535
+ this.updateData([...tuples, ...opts.append || []], {
536
+ message: `Created ${tuples.length} items`,
537
+ ...opts
538
+ });
539
+ return tuples;
540
+ } catch (error) {
541
+ const state = (_a = this._stateManager) == null ? void 0 : _a.root;
542
+ const el = state.__element;
543
+ el.call("openNotification", {
544
+ type: "error",
545
+ title: "Failed to add item",
546
+ message: error.message
547
+ });
548
+ throw new Error(`Failed to add item: ${error.message}`, { cause: error });
549
+ }
550
+ }
551
+ updateItem(type, data, opts = {}) {
552
+ var _a;
553
+ try {
554
+ validateParams.type(type);
555
+ validateParams.data(data, type);
556
+ const { value, ...schema } = data;
557
+ const tuples = [
558
+ ["update", [type, data.key], value],
559
+ ["update", ["schema", type, data.key], schema]
560
+ ];
561
+ return this.updateData(tuples, opts);
562
+ } catch (error) {
563
+ const state = (_a = this._stateManager) == null ? void 0 : _a.root;
564
+ const el = state.__element;
565
+ el.call("openNotification", {
566
+ type: "error",
567
+ title: "Failed to update item",
568
+ message: error.message
569
+ });
570
+ throw new Error(`Failed to update item: ${error.message}`, {
571
+ cause: error
572
+ });
573
+ }
574
+ }
575
+ deleteItem(type, key, opts = {}) {
576
+ var _a;
577
+ try {
578
+ validateParams.type(type);
579
+ validateParams.key(key, type);
580
+ const tuples = [
581
+ ["delete", [type, key]],
582
+ ["delete", ["schema", type, key]],
583
+ ...opts.append || []
584
+ ];
585
+ return this.updateData(tuples, {
586
+ message: `Deleted ${key} from ${type}`,
587
+ ...opts
588
+ });
589
+ } catch (error) {
590
+ const state = (_a = this._stateManager) == null ? void 0 : _a.root;
591
+ const el = state.__element;
592
+ el.call("openNotification", {
593
+ type: "error",
594
+ title: "Failed to delete item",
595
+ message: error.message
596
+ });
597
+ throw new Error(`Failed to delete item: ${error.message}`, {
598
+ cause: error
599
+ });
600
+ }
601
+ }
602
+ /* ---------- socket event helpers ---------- */
603
+ /**
604
+ * Handle "clients" or "presence" events coming from the collab socket.
605
+ * The backend sends the full `clients` object which we directly patch to
606
+ * the root state, mimicking the legacy SocketService behaviour so that
607
+ * existing UI components keep working unmodified.
608
+ */
609
+ _handleClientsEvent(data = {}) {
610
+ var _a;
611
+ const root = (_a = this._stateManager) == null ? void 0 : _a.root;
612
+ if (root && typeof root.replace === "function") {
613
+ root.clients = data;
614
+ }
615
+ rootBus.emit("clients:updated", data);
616
+ }
617
+ /* ---------- Dependency bundling events ---------- */
618
+ _handleBundleDoneEvent({
619
+ project,
620
+ ticket,
621
+ dependencies = {},
622
+ schema = {}
623
+ } = {}) {
624
+ var _a;
625
+ console.info("[CollabService] Bundle done", { project, ticket });
626
+ try {
627
+ this._ensureStateManager();
628
+ const { dependencies: schemaDependencies = {} } = schema || {};
629
+ const tuples = [
630
+ ["update", ["dependencies"], dependencies],
631
+ ["update", ["schema", "dependencies"], schemaDependencies]
632
+ ];
633
+ this._stateManager.applyChanges(tuples, {
634
+ fromSocket: true,
635
+ preventFetchDeps: true,
636
+ preventUpdate: ["Iframe"]
637
+ });
638
+ } catch (err) {
639
+ console.error("[CollabService] Failed to update deps after bundle", err);
640
+ }
641
+ const root = (_a = this._stateManager) == null ? void 0 : _a.root;
642
+ const el = root == null ? void 0 : root.__element;
643
+ if (el == null ? void 0 : el.call) {
644
+ el.call("openNotification", {
645
+ type: "success",
646
+ title: "Dependencies ready",
647
+ message: `Project ${project} dependencies have been bundled successfully.`
648
+ });
649
+ }
650
+ rootBus.emit("bundle:done", { project, ticket });
651
+ }
652
+ _handleBundleErrorEvent({ project, ticket, error } = {}) {
653
+ var _a;
654
+ console.error("[CollabService] Bundle error", { project, ticket, error });
655
+ const root = (_a = this._stateManager) == null ? void 0 : _a.root;
656
+ const el = root == null ? void 0 : root.__element;
657
+ if (el == null ? void 0 : el.call) {
658
+ el.call("openNotification", {
659
+ type: "error",
660
+ title: "Dependency bundle failed",
661
+ message: error || `An error occurred while bundling dependencies for project ${project}.`
662
+ });
663
+ }
664
+ rootBus.emit("bundle:error", { project, ticket, error });
665
+ }
666
+ /* ---------- Manual checkpoint ---------- */
667
+ _attachSocketLifecycleListeners() {
668
+ var _a;
669
+ const socket = (_a = this._client) == null ? void 0 : _a.socket;
670
+ if (!socket) {
671
+ return;
672
+ }
673
+ socket.on("connect", this._onSocketConnect);
674
+ socket.on("disconnect", this._onSocketDisconnect);
675
+ socket.on("connect_error", this._onSocketError);
676
+ }
677
+ _detachSocketLifecycleListeners() {
678
+ var _a;
679
+ const socket = (_a = this._client) == null ? void 0 : _a.socket;
680
+ if (!socket) {
681
+ return;
682
+ }
683
+ socket.off("connect", this._onSocketConnect);
684
+ socket.off("disconnect", this._onSocketDisconnect);
685
+ socket.off("connect_error", this._onSocketError);
686
+ }
687
+ _onSocketConnect() {
688
+ this._connected = true;
689
+ }
690
+ _onSocketDisconnect(reason) {
691
+ this._connected = false;
692
+ if (reason && reason !== "io client disconnect") {
693
+ console.warn("[CollabService] Socket disconnected", reason);
694
+ }
695
+ }
696
+ _onSocketError(error) {
697
+ console.warn("[CollabService] Socket connection error", error);
698
+ }
699
+ /**
700
+ * Manually request a checkpoint / commit of buffered operations on the server.
701
+ * Resolves with the new version number once the backend confirms via the
702
+ * regular "commit" event.
703
+ */
704
+ checkpoint() {
705
+ if (!this.isConnected()) {
706
+ console.warn("[CollabService] Not connected, cannot request checkpoint");
707
+ return Promise.reject(new Error("Not connected"));
708
+ }
709
+ return new Promise((resolve) => {
710
+ var _a, _b;
711
+ const handler = ({ version }) => {
712
+ var _a2;
713
+ (_a2 = this.socket) == null ? void 0 : _a2.off("commit", handler);
714
+ rootBus.emit("checkpoint:done", { version, origin: "manual" });
715
+ resolve(version);
716
+ };
717
+ (_a = this.socket) == null ? void 0 : _a.once("commit", handler);
718
+ (_b = this.socket) == null ? void 0 : _b.emit("checkpoint");
719
+ });
720
+ }
721
+ }
722
+ export {
723
+ CollabService
724
+ };