@aswin.dev/core 0.7.0
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.
- package/LICENSE +56 -0
- package/README.md +64 -0
- package/dist/cloud/index.d.ts +487 -0
- package/dist/cloud/index.js +2853 -0
- package/dist/cloud/index.js.map +1 -0
- package/dist/editor-Cp6y4tLN.d.ts +52 -0
- package/dist/index.d.ts +85 -0
- package/dist/index.js +645 -0
- package/dist/index.js.map +1 -0
- package/package.json +64 -0
|
@@ -0,0 +1,2853 @@
|
|
|
1
|
+
// src/cloud/auth.ts
|
|
2
|
+
import { SdkError } from "@aswin.dev/types";
|
|
3
|
+
var AuthManager = class _AuthManager {
|
|
4
|
+
static DEFAULT_BASE_URL = "https://templatical.com";
|
|
5
|
+
accessToken = null;
|
|
6
|
+
expiresAt = null;
|
|
7
|
+
_projectId = null;
|
|
8
|
+
_tenantId = null;
|
|
9
|
+
_tenantSlug = null;
|
|
10
|
+
_testEmailConfig = null;
|
|
11
|
+
_userConfig = null;
|
|
12
|
+
url;
|
|
13
|
+
baseUrl;
|
|
14
|
+
requestOptions;
|
|
15
|
+
onError;
|
|
16
|
+
refreshPromise = null;
|
|
17
|
+
static REFRESH_THRESHOLD_MS = 60 * 1e3;
|
|
18
|
+
constructor(config) {
|
|
19
|
+
this.url = config.url;
|
|
20
|
+
this.baseUrl = (config.baseUrl ?? _AuthManager.DEFAULT_BASE_URL).replace(
|
|
21
|
+
/\/$/,
|
|
22
|
+
""
|
|
23
|
+
);
|
|
24
|
+
this.requestOptions = config.requestOptions ?? {};
|
|
25
|
+
this.onError = config.onError;
|
|
26
|
+
}
|
|
27
|
+
resolveUrl(path) {
|
|
28
|
+
if (path.startsWith("http://") || path.startsWith("https://")) {
|
|
29
|
+
return path;
|
|
30
|
+
}
|
|
31
|
+
const normalizedPath = path.startsWith("/") ? path : `/${path}`;
|
|
32
|
+
return `${this.baseUrl}${normalizedPath}`;
|
|
33
|
+
}
|
|
34
|
+
get projectId() {
|
|
35
|
+
if (!this._projectId) {
|
|
36
|
+
throw new Error("Project ID not available. Call initialize() first.");
|
|
37
|
+
}
|
|
38
|
+
return this._projectId;
|
|
39
|
+
}
|
|
40
|
+
get tenantId() {
|
|
41
|
+
if (!this._tenantId) {
|
|
42
|
+
throw new Error("Tenant ID not available. Call initialize() first.");
|
|
43
|
+
}
|
|
44
|
+
return this._tenantId;
|
|
45
|
+
}
|
|
46
|
+
get tenantSlug() {
|
|
47
|
+
if (!this._tenantSlug) {
|
|
48
|
+
throw new Error("Tenant slug not available. Call initialize() first.");
|
|
49
|
+
}
|
|
50
|
+
return this._tenantSlug;
|
|
51
|
+
}
|
|
52
|
+
get testEmailConfig() {
|
|
53
|
+
return this._testEmailConfig;
|
|
54
|
+
}
|
|
55
|
+
get userConfig() {
|
|
56
|
+
return this._userConfig;
|
|
57
|
+
}
|
|
58
|
+
get accessTokenValue() {
|
|
59
|
+
return this.accessToken;
|
|
60
|
+
}
|
|
61
|
+
async initialize() {
|
|
62
|
+
await this.ensureToken();
|
|
63
|
+
}
|
|
64
|
+
async ensureToken() {
|
|
65
|
+
if (this.accessToken && !this.isTokenExpiringSoon()) {
|
|
66
|
+
return this.accessToken;
|
|
67
|
+
}
|
|
68
|
+
return this.refreshToken();
|
|
69
|
+
}
|
|
70
|
+
isTokenExpiringSoon() {
|
|
71
|
+
if (!this.expiresAt) {
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
const timeUntilExpiry = this.expiresAt.getTime() - Date.now();
|
|
75
|
+
return timeUntilExpiry < _AuthManager.REFRESH_THRESHOLD_MS;
|
|
76
|
+
}
|
|
77
|
+
async refreshToken() {
|
|
78
|
+
if (this.refreshPromise) {
|
|
79
|
+
return this.refreshPromise;
|
|
80
|
+
}
|
|
81
|
+
this.refreshPromise = this.performRefresh();
|
|
82
|
+
try {
|
|
83
|
+
const token = await this.refreshPromise;
|
|
84
|
+
return token;
|
|
85
|
+
} finally {
|
|
86
|
+
this.refreshPromise = null;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async performRefresh() {
|
|
90
|
+
try {
|
|
91
|
+
const method = this.requestOptions.method ?? "POST";
|
|
92
|
+
const headers = {
|
|
93
|
+
Accept: "application/json",
|
|
94
|
+
...this.requestOptions.headers
|
|
95
|
+
};
|
|
96
|
+
const fetchOptions = {
|
|
97
|
+
method,
|
|
98
|
+
headers,
|
|
99
|
+
credentials: this.requestOptions.credentials ?? "include"
|
|
100
|
+
};
|
|
101
|
+
if (method === "POST" && this.requestOptions.body) {
|
|
102
|
+
headers["Content-Type"] = "application/json";
|
|
103
|
+
fetchOptions.body = JSON.stringify(this.requestOptions.body);
|
|
104
|
+
}
|
|
105
|
+
const response = await fetch(this.url, fetchOptions);
|
|
106
|
+
if (!response.ok) {
|
|
107
|
+
throw new SdkError(
|
|
108
|
+
`Token refresh failed: ${response.status}`,
|
|
109
|
+
response.status
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
const data = await response.json();
|
|
113
|
+
if (!data.token || !data.expires_at || !data.project_id || !data.tenant) {
|
|
114
|
+
throw new Error(
|
|
115
|
+
"Invalid token response: missing token, expires_at, project_id, or tenant"
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
this.accessToken = data.token;
|
|
119
|
+
this.expiresAt = new Date(data.expires_at * 1e3);
|
|
120
|
+
this._projectId = data.project_id;
|
|
121
|
+
this._tenantSlug = data.tenant;
|
|
122
|
+
if (data.test_email?.allowed_emails && data.test_email?.signature) {
|
|
123
|
+
this._testEmailConfig = {
|
|
124
|
+
allowedEmails: data.test_email.allowed_emails,
|
|
125
|
+
signature: data.test_email.signature
|
|
126
|
+
};
|
|
127
|
+
} else {
|
|
128
|
+
this._testEmailConfig = null;
|
|
129
|
+
}
|
|
130
|
+
if (data.user?.id && data.user?.name && data.user?.signature) {
|
|
131
|
+
this._userConfig = {
|
|
132
|
+
id: data.user.id,
|
|
133
|
+
name: data.user.name,
|
|
134
|
+
signature: data.user.signature
|
|
135
|
+
};
|
|
136
|
+
} else {
|
|
137
|
+
this._userConfig = null;
|
|
138
|
+
}
|
|
139
|
+
return this.accessToken;
|
|
140
|
+
} catch (error) {
|
|
141
|
+
const wrappedError = error instanceof Error ? error : new Error("Token refresh failed", { cause: error });
|
|
142
|
+
this.onError?.(wrappedError);
|
|
143
|
+
throw wrappedError;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
async authenticatedFetch(url, options = {}) {
|
|
147
|
+
const token = await this.ensureToken();
|
|
148
|
+
const resolvedUrl = this.resolveUrl(url);
|
|
149
|
+
const makeRequest = async (authToken) => {
|
|
150
|
+
return fetch(resolvedUrl, {
|
|
151
|
+
...options,
|
|
152
|
+
headers: {
|
|
153
|
+
...options.headers,
|
|
154
|
+
Authorization: `Bearer ${authToken}`
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
};
|
|
158
|
+
let response = await makeRequest(token);
|
|
159
|
+
if (response.status === 401) {
|
|
160
|
+
const newToken = await this.refreshToken();
|
|
161
|
+
response = await makeRequest(newToken);
|
|
162
|
+
}
|
|
163
|
+
return response;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
function createSdkAuthManager(config, onError) {
|
|
167
|
+
if (config.mode === "direct") {
|
|
168
|
+
const baseUrl = (config.baseUrl ?? "https://templatical.com").replace(
|
|
169
|
+
/\/$/,
|
|
170
|
+
""
|
|
171
|
+
);
|
|
172
|
+
return new AuthManager({
|
|
173
|
+
url: `${baseUrl}/api/v1/auth/token`,
|
|
174
|
+
baseUrl: config.baseUrl,
|
|
175
|
+
requestOptions: {
|
|
176
|
+
method: "POST",
|
|
177
|
+
headers: {
|
|
178
|
+
"Content-Type": "application/json"
|
|
179
|
+
},
|
|
180
|
+
body: {
|
|
181
|
+
client_id: config.clientId,
|
|
182
|
+
client_secret: config.clientSecret,
|
|
183
|
+
tenant: config.tenant,
|
|
184
|
+
client_type: "sdk"
|
|
185
|
+
}
|
|
186
|
+
},
|
|
187
|
+
onError
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
return new AuthManager({
|
|
191
|
+
url: config.url,
|
|
192
|
+
baseUrl: config.baseUrl,
|
|
193
|
+
requestOptions: config.requestOptions,
|
|
194
|
+
onError
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// src/cloud/api.ts
|
|
199
|
+
import { SdkError as SdkError2 } from "@aswin.dev/types";
|
|
200
|
+
|
|
201
|
+
// src/cloud/url-builder.ts
|
|
202
|
+
function buildUrl(template, params) {
|
|
203
|
+
return template.replace(
|
|
204
|
+
/\{(\w+)\}/g,
|
|
205
|
+
(_, key) => encodeURIComponent(params[key] ?? "")
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
var BASE = "/api/v1/projects/{project}/tenants/{tenant}";
|
|
209
|
+
var TEMPLATE = `${BASE}/templates/{template}`;
|
|
210
|
+
var AI = `${TEMPLATE}/ai`;
|
|
211
|
+
var MEDIA = `${BASE}/media`;
|
|
212
|
+
var FOLDERS = `${MEDIA}/folders`;
|
|
213
|
+
var MODULES = `${BASE}/saved-modules`;
|
|
214
|
+
var API_ROUTES = {
|
|
215
|
+
health: "/api/v1/health",
|
|
216
|
+
"projects.config": `${BASE}/config`,
|
|
217
|
+
"broadcasting.auth": `${BASE}/broadcasting/auth`,
|
|
218
|
+
"templates.store": `${BASE}/templates`,
|
|
219
|
+
"templates.show": `${TEMPLATE}`,
|
|
220
|
+
"templates.update": `${TEMPLATE}`,
|
|
221
|
+
"templates.destroy": `${TEMPLATE}`,
|
|
222
|
+
"templates.export": `${TEMPLATE}/export`,
|
|
223
|
+
"templates.importFromBeefree": `${BASE}/templates/import/from-beefree`,
|
|
224
|
+
"templates.sendTestEmail": `${TEMPLATE}/send-test-email`,
|
|
225
|
+
"snapshots.index": `${TEMPLATE}/snapshots`,
|
|
226
|
+
"snapshots.store": `${TEMPLATE}/snapshots`,
|
|
227
|
+
"snapshots.show": `${TEMPLATE}/snapshots/{snapshot}`,
|
|
228
|
+
"snapshots.restore": `${TEMPLATE}/snapshots/{snapshot}/restore`,
|
|
229
|
+
"comments.index": `${TEMPLATE}/comments`,
|
|
230
|
+
"comments.store": `${TEMPLATE}/comments`,
|
|
231
|
+
"comments.update": `${TEMPLATE}/comments/{comment}`,
|
|
232
|
+
"comments.destroy": `${TEMPLATE}/comments/{comment}`,
|
|
233
|
+
"comments.resolve": `${TEMPLATE}/comments/{comment}/resolve`,
|
|
234
|
+
"ai.generate": `${AI}/generate`,
|
|
235
|
+
"ai.conversationMessages": `${AI}/conversation-messages`,
|
|
236
|
+
"ai.suggestions": `${AI}/suggestions`,
|
|
237
|
+
"ai.rewriteText": `${AI}/rewrite-text`,
|
|
238
|
+
"ai.score": `${AI}/score`,
|
|
239
|
+
"ai.fixFinding": `${AI}/fix-finding`,
|
|
240
|
+
"ai.generateFromDesign": `${AI}/generate-from-design`,
|
|
241
|
+
"media.upload": `${MEDIA}/upload`,
|
|
242
|
+
"media.browse": `${MEDIA}/browse`,
|
|
243
|
+
"media.delete": `${MEDIA}/delete`,
|
|
244
|
+
"media.move": `${MEDIA}/move`,
|
|
245
|
+
"media.update": `${MEDIA}/{media}`,
|
|
246
|
+
"media.replace": `${MEDIA}/{media}/replace`,
|
|
247
|
+
"media.checkUsage": `${MEDIA}/check-usage`,
|
|
248
|
+
"media.frequentlyUsed": `${MEDIA}/frequently-used`,
|
|
249
|
+
"media.importFromUrl": `${MEDIA}/import-from-url`,
|
|
250
|
+
"folders.index": `${FOLDERS}`,
|
|
251
|
+
"folders.store": `${FOLDERS}`,
|
|
252
|
+
"folders.update": `${FOLDERS}/{mediaFolder}`,
|
|
253
|
+
"folders.destroy": `${FOLDERS}/{mediaFolder}`,
|
|
254
|
+
"savedModules.index": `${MODULES}`,
|
|
255
|
+
"savedModules.store": `${MODULES}`,
|
|
256
|
+
"savedModules.update": `${MODULES}/{savedModule}`,
|
|
257
|
+
"savedModules.destroy": `${MODULES}/{savedModule}`
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
// src/cloud/api.ts
|
|
261
|
+
var ApiClient = class {
|
|
262
|
+
constructor(authManager) {
|
|
263
|
+
this.authManager = authManager;
|
|
264
|
+
}
|
|
265
|
+
authManager;
|
|
266
|
+
get projectId() {
|
|
267
|
+
return this.authManager.projectId;
|
|
268
|
+
}
|
|
269
|
+
get tenantSlug() {
|
|
270
|
+
return this.authManager.tenantSlug;
|
|
271
|
+
}
|
|
272
|
+
get baseParams() {
|
|
273
|
+
return { project: this.projectId, tenant: this.tenantSlug };
|
|
274
|
+
}
|
|
275
|
+
async request(path, options = {}) {
|
|
276
|
+
const response = await this.authManager.authenticatedFetch(path, {
|
|
277
|
+
...options,
|
|
278
|
+
headers: {
|
|
279
|
+
"Content-Type": "application/json",
|
|
280
|
+
Accept: "application/json",
|
|
281
|
+
...options.headers
|
|
282
|
+
}
|
|
283
|
+
});
|
|
284
|
+
if (!response.ok) {
|
|
285
|
+
const error = await response.json().catch(() => ({
|
|
286
|
+
message: `HTTP error ${response.status}`
|
|
287
|
+
}));
|
|
288
|
+
const errorMessage = this.extractFirstValidationError(error);
|
|
289
|
+
throw new SdkError2(errorMessage, response.status);
|
|
290
|
+
}
|
|
291
|
+
if (response.status === 204) {
|
|
292
|
+
return void 0;
|
|
293
|
+
}
|
|
294
|
+
const json = await response.json();
|
|
295
|
+
return json.data;
|
|
296
|
+
}
|
|
297
|
+
extractFirstValidationError(error) {
|
|
298
|
+
if (error.errors) {
|
|
299
|
+
const firstField = Object.keys(error.errors)[0];
|
|
300
|
+
if (firstField && error.errors[firstField]?.length > 0) {
|
|
301
|
+
return error.errors[firstField][0];
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return error.message;
|
|
305
|
+
}
|
|
306
|
+
async createTemplate(content) {
|
|
307
|
+
return this.request(
|
|
308
|
+
buildUrl(API_ROUTES["templates.store"], this.baseParams),
|
|
309
|
+
{
|
|
310
|
+
method: "POST",
|
|
311
|
+
body: JSON.stringify({ content })
|
|
312
|
+
}
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
async getTemplate(id) {
|
|
316
|
+
return this.request(
|
|
317
|
+
buildUrl(API_ROUTES["templates.show"], {
|
|
318
|
+
...this.baseParams,
|
|
319
|
+
template: id
|
|
320
|
+
})
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
async updateTemplate(id, content) {
|
|
324
|
+
return this.request(
|
|
325
|
+
buildUrl(API_ROUTES["templates.update"], {
|
|
326
|
+
...this.baseParams,
|
|
327
|
+
template: id
|
|
328
|
+
}),
|
|
329
|
+
{
|
|
330
|
+
method: "PUT",
|
|
331
|
+
body: JSON.stringify({ content })
|
|
332
|
+
}
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
async createSnapshot(templateId, content) {
|
|
336
|
+
return this.request(
|
|
337
|
+
buildUrl(API_ROUTES["snapshots.store"], {
|
|
338
|
+
...this.baseParams,
|
|
339
|
+
template: templateId
|
|
340
|
+
}),
|
|
341
|
+
{
|
|
342
|
+
method: "POST",
|
|
343
|
+
body: JSON.stringify({ content })
|
|
344
|
+
}
|
|
345
|
+
);
|
|
346
|
+
}
|
|
347
|
+
async deleteTemplate(id) {
|
|
348
|
+
return this.request(
|
|
349
|
+
buildUrl(API_ROUTES["templates.destroy"], {
|
|
350
|
+
...this.baseParams,
|
|
351
|
+
template: id
|
|
352
|
+
}),
|
|
353
|
+
{
|
|
354
|
+
method: "DELETE"
|
|
355
|
+
}
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
async getSnapshots(templateId) {
|
|
359
|
+
return this.request(
|
|
360
|
+
buildUrl(API_ROUTES["snapshots.index"], {
|
|
361
|
+
...this.baseParams,
|
|
362
|
+
template: templateId
|
|
363
|
+
})
|
|
364
|
+
);
|
|
365
|
+
}
|
|
366
|
+
async restoreSnapshot(templateId, snapshotId) {
|
|
367
|
+
return this.request(
|
|
368
|
+
buildUrl(API_ROUTES["snapshots.restore"], {
|
|
369
|
+
...this.baseParams,
|
|
370
|
+
template: templateId,
|
|
371
|
+
snapshot: snapshotId
|
|
372
|
+
}),
|
|
373
|
+
{
|
|
374
|
+
method: "POST"
|
|
375
|
+
}
|
|
376
|
+
);
|
|
377
|
+
}
|
|
378
|
+
async exportTemplate(templateId, fontsPayload) {
|
|
379
|
+
const body = fontsPayload ? JSON.stringify({
|
|
380
|
+
custom_fonts: fontsPayload.customFonts,
|
|
381
|
+
default_fallback: fontsPayload.defaultFallback
|
|
382
|
+
}) : void 0;
|
|
383
|
+
return this.request(
|
|
384
|
+
buildUrl(API_ROUTES["templates.export"], {
|
|
385
|
+
...this.baseParams,
|
|
386
|
+
template: templateId
|
|
387
|
+
}),
|
|
388
|
+
{
|
|
389
|
+
method: "POST",
|
|
390
|
+
body
|
|
391
|
+
}
|
|
392
|
+
);
|
|
393
|
+
}
|
|
394
|
+
async sendTestEmail(templateId, payload) {
|
|
395
|
+
await this.request(
|
|
396
|
+
buildUrl(API_ROUTES["templates.sendTestEmail"], {
|
|
397
|
+
...this.baseParams,
|
|
398
|
+
template: templateId
|
|
399
|
+
}),
|
|
400
|
+
{
|
|
401
|
+
method: "POST",
|
|
402
|
+
body: JSON.stringify(payload)
|
|
403
|
+
}
|
|
404
|
+
);
|
|
405
|
+
}
|
|
406
|
+
commentsUrl(templateId, commentId) {
|
|
407
|
+
if (commentId) {
|
|
408
|
+
return buildUrl(API_ROUTES["comments.update"], {
|
|
409
|
+
...this.baseParams,
|
|
410
|
+
template: templateId,
|
|
411
|
+
comment: commentId
|
|
412
|
+
});
|
|
413
|
+
}
|
|
414
|
+
return buildUrl(API_ROUTES["comments.index"], {
|
|
415
|
+
...this.baseParams,
|
|
416
|
+
template: templateId
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
async getComments(templateId) {
|
|
420
|
+
return this.request(this.commentsUrl(templateId));
|
|
421
|
+
}
|
|
422
|
+
async createComment(templateId, data, headers) {
|
|
423
|
+
return this.request(this.commentsUrl(templateId), {
|
|
424
|
+
method: "POST",
|
|
425
|
+
body: JSON.stringify(data),
|
|
426
|
+
headers
|
|
427
|
+
});
|
|
428
|
+
}
|
|
429
|
+
async updateComment(templateId, commentId, data, headers) {
|
|
430
|
+
return this.request(this.commentsUrl(templateId, commentId), {
|
|
431
|
+
method: "PUT",
|
|
432
|
+
body: JSON.stringify(data),
|
|
433
|
+
headers
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
async deleteComment(templateId, commentId, data, headers) {
|
|
437
|
+
return this.request(this.commentsUrl(templateId, commentId), {
|
|
438
|
+
method: "DELETE",
|
|
439
|
+
body: JSON.stringify(data),
|
|
440
|
+
headers
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
async resolveComment(templateId, commentId, data, headers) {
|
|
444
|
+
return this.request(
|
|
445
|
+
buildUrl(API_ROUTES["comments.resolve"], {
|
|
446
|
+
...this.baseParams,
|
|
447
|
+
template: templateId,
|
|
448
|
+
comment: commentId
|
|
449
|
+
}),
|
|
450
|
+
{
|
|
451
|
+
method: "POST",
|
|
452
|
+
body: JSON.stringify(data),
|
|
453
|
+
headers
|
|
454
|
+
}
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
async fetchConfig() {
|
|
458
|
+
return this.request(
|
|
459
|
+
buildUrl(API_ROUTES["projects.config"], this.baseParams)
|
|
460
|
+
);
|
|
461
|
+
}
|
|
462
|
+
async listModules(search) {
|
|
463
|
+
const url = buildUrl(API_ROUTES["savedModules.index"], this.baseParams);
|
|
464
|
+
const query = search ? `?search=${encodeURIComponent(search)}` : "";
|
|
465
|
+
return this.request(`${url}${query}`);
|
|
466
|
+
}
|
|
467
|
+
async createModule(data) {
|
|
468
|
+
return this.request(
|
|
469
|
+
buildUrl(API_ROUTES["savedModules.store"], this.baseParams),
|
|
470
|
+
{
|
|
471
|
+
method: "POST",
|
|
472
|
+
body: JSON.stringify(data)
|
|
473
|
+
}
|
|
474
|
+
);
|
|
475
|
+
}
|
|
476
|
+
async updateModule(id, data) {
|
|
477
|
+
return this.request(
|
|
478
|
+
buildUrl(API_ROUTES["savedModules.update"], {
|
|
479
|
+
...this.baseParams,
|
|
480
|
+
savedModule: id
|
|
481
|
+
}),
|
|
482
|
+
{
|
|
483
|
+
method: "PUT",
|
|
484
|
+
body: JSON.stringify(data)
|
|
485
|
+
}
|
|
486
|
+
);
|
|
487
|
+
}
|
|
488
|
+
async deleteModule(id) {
|
|
489
|
+
return this.request(
|
|
490
|
+
buildUrl(API_ROUTES["savedModules.destroy"], {
|
|
491
|
+
...this.baseParams,
|
|
492
|
+
savedModule: id
|
|
493
|
+
}),
|
|
494
|
+
{
|
|
495
|
+
method: "DELETE"
|
|
496
|
+
}
|
|
497
|
+
);
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
// src/cloud/websocket-client.ts
|
|
502
|
+
function resolveWebSocketConfig(serverConfig) {
|
|
503
|
+
return {
|
|
504
|
+
host: serverConfig.host,
|
|
505
|
+
port: serverConfig.port,
|
|
506
|
+
appKey: serverConfig.app_key
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
var WebSocketClient = class {
|
|
510
|
+
pusher = null;
|
|
511
|
+
authManager;
|
|
512
|
+
config;
|
|
513
|
+
onError;
|
|
514
|
+
constructor(options) {
|
|
515
|
+
this.authManager = options.authManager;
|
|
516
|
+
this.config = options.config;
|
|
517
|
+
this.onError = options.onError;
|
|
518
|
+
}
|
|
519
|
+
async connect() {
|
|
520
|
+
if (this.pusher) {
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
let Pusher;
|
|
524
|
+
try {
|
|
525
|
+
({ default: Pusher } = await import("pusher-js"));
|
|
526
|
+
} catch {
|
|
527
|
+
throw new Error(
|
|
528
|
+
"Cloud features require the optional peer dependency 'pusher-js'. Install it with: npm install pusher-js"
|
|
529
|
+
);
|
|
530
|
+
}
|
|
531
|
+
const { host, port, appKey } = this.config;
|
|
532
|
+
const authEndpoint = this.authManager.resolveUrl(
|
|
533
|
+
buildUrl(API_ROUTES["broadcasting.auth"], {
|
|
534
|
+
project: this.authManager.projectId,
|
|
535
|
+
tenant: this.authManager.tenantSlug
|
|
536
|
+
})
|
|
537
|
+
);
|
|
538
|
+
this.pusher = new Pusher(appKey, {
|
|
539
|
+
wsHost: host,
|
|
540
|
+
wsPort: port,
|
|
541
|
+
wssPort: port,
|
|
542
|
+
forceTLS: true,
|
|
543
|
+
disableStats: true,
|
|
544
|
+
enabledTransports: ["ws", "wss"],
|
|
545
|
+
cluster: "",
|
|
546
|
+
channelAuthorization: {
|
|
547
|
+
transport: "ajax",
|
|
548
|
+
endpoint: authEndpoint,
|
|
549
|
+
headers: {
|
|
550
|
+
Authorization: `Bearer ${this.authManager.accessTokenValue}`,
|
|
551
|
+
Accept: "application/json"
|
|
552
|
+
},
|
|
553
|
+
params: {
|
|
554
|
+
user_id: this.authManager.userConfig?.id ?? "",
|
|
555
|
+
user_name: this.authManager.userConfig?.name ?? "",
|
|
556
|
+
user_signature: this.authManager.userConfig?.signature ?? ""
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
});
|
|
560
|
+
this.pusher.connection.bind("error", (error) => {
|
|
561
|
+
this.onError?.(
|
|
562
|
+
error instanceof Error ? error : new Error("WebSocket connection error")
|
|
563
|
+
);
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
subscribePresence(channelName) {
|
|
567
|
+
if (!this.pusher) {
|
|
568
|
+
throw new Error("WebSocketClient not connected. Call connect() first.");
|
|
569
|
+
}
|
|
570
|
+
return this.pusher.subscribe(channelName);
|
|
571
|
+
}
|
|
572
|
+
unsubscribe(channelName) {
|
|
573
|
+
this.pusher?.unsubscribe(channelName);
|
|
574
|
+
}
|
|
575
|
+
getChannel(channelName) {
|
|
576
|
+
return this.pusher?.channel(channelName);
|
|
577
|
+
}
|
|
578
|
+
disconnect() {
|
|
579
|
+
if (this.pusher) {
|
|
580
|
+
this.pusher.disconnect();
|
|
581
|
+
this.pusher = null;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
getSocketId() {
|
|
585
|
+
return this.pusher?.connection.socket_id ?? null;
|
|
586
|
+
}
|
|
587
|
+
get isConnected() {
|
|
588
|
+
return this.pusher?.connection.state === "connected";
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
|
|
592
|
+
// src/cloud/mcp-operation-handler.ts
|
|
593
|
+
function handleOperation(editor, payload) {
|
|
594
|
+
const { operation, data } = payload;
|
|
595
|
+
switch (operation) {
|
|
596
|
+
case "add_block":
|
|
597
|
+
editor.addBlock(
|
|
598
|
+
data.block,
|
|
599
|
+
data.section_id,
|
|
600
|
+
data.column_index,
|
|
601
|
+
data.index
|
|
602
|
+
);
|
|
603
|
+
break;
|
|
604
|
+
case "update_block":
|
|
605
|
+
editor.updateBlock(
|
|
606
|
+
data.block_id,
|
|
607
|
+
data.updates
|
|
608
|
+
);
|
|
609
|
+
break;
|
|
610
|
+
case "delete_block":
|
|
611
|
+
editor.removeBlock(data.block_id);
|
|
612
|
+
break;
|
|
613
|
+
case "move_block":
|
|
614
|
+
editor.moveBlock(
|
|
615
|
+
data.block_id,
|
|
616
|
+
data.index,
|
|
617
|
+
data.section_id,
|
|
618
|
+
data.column_index
|
|
619
|
+
);
|
|
620
|
+
break;
|
|
621
|
+
case "update_settings":
|
|
622
|
+
editor.updateSettings(data.updates);
|
|
623
|
+
break;
|
|
624
|
+
case "set_content":
|
|
625
|
+
editor.setContent(data.content);
|
|
626
|
+
break;
|
|
627
|
+
case "update_block_style":
|
|
628
|
+
editor.updateBlock(
|
|
629
|
+
data.block_id,
|
|
630
|
+
{
|
|
631
|
+
styles: data.styles
|
|
632
|
+
}
|
|
633
|
+
);
|
|
634
|
+
break;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
// src/cloud/editor.ts
|
|
639
|
+
import { SdkError as SdkError3 } from "@aswin.dev/types";
|
|
640
|
+
import {
|
|
641
|
+
createDefaultTemplateContent,
|
|
642
|
+
normalizeTemplateContentPages
|
|
643
|
+
} from "@aswin.dev/types";
|
|
644
|
+
import { computed, reactive, readonly } from "vue";
|
|
645
|
+
function useEditor(options) {
|
|
646
|
+
const api = new ApiClient(options.authManager);
|
|
647
|
+
const state = reactive({
|
|
648
|
+
template: null,
|
|
649
|
+
content: normalizeTemplateContentPages(
|
|
650
|
+
createDefaultTemplateContent(
|
|
651
|
+
options.defaultFontFamily,
|
|
652
|
+
options.templateDefaults
|
|
653
|
+
)
|
|
654
|
+
),
|
|
655
|
+
selectedBlockId: null,
|
|
656
|
+
viewport: "desktop",
|
|
657
|
+
darkMode: false,
|
|
658
|
+
previewMode: false,
|
|
659
|
+
isDirty: false,
|
|
660
|
+
isSaving: false,
|
|
661
|
+
isLoading: false,
|
|
662
|
+
uiTheme: "auto"
|
|
663
|
+
});
|
|
664
|
+
const content = computed({
|
|
665
|
+
get: () => state.content,
|
|
666
|
+
set: (value) => {
|
|
667
|
+
state.content = normalizeTemplateContentPages(value);
|
|
668
|
+
state.isDirty = true;
|
|
669
|
+
}
|
|
670
|
+
});
|
|
671
|
+
const selectedBlock = computed(() => {
|
|
672
|
+
if (!state.selectedBlockId) return null;
|
|
673
|
+
return findBlockById(state.content.blocks, state.selectedBlockId);
|
|
674
|
+
});
|
|
675
|
+
const savedBlockIds = computed(() => {
|
|
676
|
+
const ids = /* @__PURE__ */ new Set();
|
|
677
|
+
const blocks = state.template?.content?.blocks;
|
|
678
|
+
if (!blocks) {
|
|
679
|
+
return ids;
|
|
680
|
+
}
|
|
681
|
+
for (const block of blocks) {
|
|
682
|
+
ids.add(block.id);
|
|
683
|
+
if (block.type === "section") {
|
|
684
|
+
for (const column of block.children) {
|
|
685
|
+
for (const child of column) {
|
|
686
|
+
ids.add(child.id);
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
return ids;
|
|
692
|
+
});
|
|
693
|
+
function findBlockById(blocks, id) {
|
|
694
|
+
for (const block of blocks) {
|
|
695
|
+
if (block.id === id) return block;
|
|
696
|
+
if (block.type === "section") {
|
|
697
|
+
for (const column of block.children) {
|
|
698
|
+
const found = findBlockById(column, id);
|
|
699
|
+
if (found) return found;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return null;
|
|
704
|
+
}
|
|
705
|
+
function findBlockParent(blocks, id, parent = { blocks }) {
|
|
706
|
+
for (let i = 0; i < blocks.length; i++) {
|
|
707
|
+
const block = blocks[i];
|
|
708
|
+
if (block.id === id) return parent;
|
|
709
|
+
if (block.type === "section") {
|
|
710
|
+
for (let colIdx = 0; colIdx < block.children.length; colIdx++) {
|
|
711
|
+
const result = findBlockParent(block.children[colIdx], id, {
|
|
712
|
+
blocks: block.children[colIdx],
|
|
713
|
+
sectionId: block.id,
|
|
714
|
+
columnIndex: colIdx
|
|
715
|
+
});
|
|
716
|
+
if (result) return result;
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
return null;
|
|
721
|
+
}
|
|
722
|
+
function isBlockLocked(blockId) {
|
|
723
|
+
return options.lockedBlocks?.value.has(blockId) ?? false;
|
|
724
|
+
}
|
|
725
|
+
function setContent(newContent, markDirty2 = true) {
|
|
726
|
+
state.content = normalizeTemplateContentPages(newContent);
|
|
727
|
+
if (markDirty2) {
|
|
728
|
+
state.isDirty = true;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
function selectBlock(blockId) {
|
|
732
|
+
if (blockId && isBlockLocked(blockId)) {
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
state.selectedBlockId = blockId;
|
|
736
|
+
}
|
|
737
|
+
function setViewport(viewport) {
|
|
738
|
+
state.viewport = viewport;
|
|
739
|
+
}
|
|
740
|
+
function setDarkMode(darkMode) {
|
|
741
|
+
state.darkMode = darkMode;
|
|
742
|
+
}
|
|
743
|
+
function setUiTheme(theme) {
|
|
744
|
+
state.uiTheme = theme;
|
|
745
|
+
}
|
|
746
|
+
function setPreviewMode(previewMode) {
|
|
747
|
+
state.previewMode = previewMode;
|
|
748
|
+
if (previewMode) {
|
|
749
|
+
state.selectedBlockId = null;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
function updateBlock(blockId, updates) {
|
|
753
|
+
if (isBlockLocked(blockId)) {
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
const block = findBlockById(state.content.blocks, blockId);
|
|
757
|
+
if (block) {
|
|
758
|
+
Object.assign(block, updates);
|
|
759
|
+
state.isDirty = true;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
function updateSettings(updates) {
|
|
763
|
+
state.content.settings = { ...state.content.settings, ...updates };
|
|
764
|
+
state.isDirty = true;
|
|
765
|
+
}
|
|
766
|
+
function addBlock(block, targetSectionId, columnIndex = 0, index) {
|
|
767
|
+
if (targetSectionId) {
|
|
768
|
+
const section = findBlockById(state.content.blocks, targetSectionId);
|
|
769
|
+
if (section && section.type === "section") {
|
|
770
|
+
section.children[columnIndex] = section.children[columnIndex] || [];
|
|
771
|
+
const targetArray = section.children[columnIndex];
|
|
772
|
+
if (index !== void 0 && index < targetArray.length) {
|
|
773
|
+
targetArray.splice(index, 0, block);
|
|
774
|
+
} else {
|
|
775
|
+
targetArray.push(block);
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
} else {
|
|
779
|
+
if (index !== void 0 && index < state.content.blocks.length) {
|
|
780
|
+
state.content.blocks.splice(index, 0, block);
|
|
781
|
+
} else {
|
|
782
|
+
state.content.blocks.push(block);
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
state.isDirty = true;
|
|
786
|
+
}
|
|
787
|
+
function removeBlock(blockId) {
|
|
788
|
+
if (isBlockLocked(blockId)) {
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
const parent = findBlockParent(state.content.blocks, blockId);
|
|
792
|
+
if (parent) {
|
|
793
|
+
const index = parent.blocks.findIndex((b) => b.id === blockId);
|
|
794
|
+
if (index !== -1) {
|
|
795
|
+
parent.blocks.splice(index, 1);
|
|
796
|
+
if (state.selectedBlockId === blockId) {
|
|
797
|
+
state.selectedBlockId = null;
|
|
798
|
+
}
|
|
799
|
+
state.isDirty = true;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
function moveBlock(blockId, newIndex, targetSectionId, columnIndex = 0) {
|
|
804
|
+
const parent = findBlockParent(state.content.blocks, blockId);
|
|
805
|
+
if (!parent) return;
|
|
806
|
+
const oldIndex = parent.blocks.findIndex((b) => b.id === blockId);
|
|
807
|
+
if (oldIndex === -1) return;
|
|
808
|
+
const [block] = parent.blocks.splice(oldIndex, 1);
|
|
809
|
+
if (targetSectionId) {
|
|
810
|
+
const section = findBlockById(state.content.blocks, targetSectionId);
|
|
811
|
+
if (section && section.type === "section") {
|
|
812
|
+
section.children[columnIndex] = section.children[columnIndex] || [];
|
|
813
|
+
section.children[columnIndex].splice(newIndex, 0, block);
|
|
814
|
+
}
|
|
815
|
+
} else {
|
|
816
|
+
state.content.blocks.splice(newIndex, 0, block);
|
|
817
|
+
}
|
|
818
|
+
state.isDirty = true;
|
|
819
|
+
}
|
|
820
|
+
async function create(content2) {
|
|
821
|
+
state.isLoading = true;
|
|
822
|
+
try {
|
|
823
|
+
if (content2) {
|
|
824
|
+
state.content = normalizeTemplateContentPages(content2);
|
|
825
|
+
}
|
|
826
|
+
const template = await api.createTemplate(state.content);
|
|
827
|
+
state.template = template;
|
|
828
|
+
state.isDirty = false;
|
|
829
|
+
return template;
|
|
830
|
+
} catch (error) {
|
|
831
|
+
options.onError?.(error);
|
|
832
|
+
throw error;
|
|
833
|
+
} finally {
|
|
834
|
+
state.isLoading = false;
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
async function load(templateId) {
|
|
838
|
+
state.isLoading = true;
|
|
839
|
+
try {
|
|
840
|
+
const template = await api.getTemplate(templateId);
|
|
841
|
+
state.template = template;
|
|
842
|
+
state.content = normalizeTemplateContentPages(template.content);
|
|
843
|
+
state.isDirty = false;
|
|
844
|
+
return template;
|
|
845
|
+
} catch (error) {
|
|
846
|
+
options.onError?.(error);
|
|
847
|
+
throw error;
|
|
848
|
+
} finally {
|
|
849
|
+
state.isLoading = false;
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
async function save() {
|
|
853
|
+
if (!state.template?.id) {
|
|
854
|
+
throw new SdkError3(
|
|
855
|
+
"No template loaded. Call create() or load() before saving."
|
|
856
|
+
);
|
|
857
|
+
}
|
|
858
|
+
state.isSaving = true;
|
|
859
|
+
try {
|
|
860
|
+
const template = await api.updateTemplate(
|
|
861
|
+
state.template.id,
|
|
862
|
+
state.content
|
|
863
|
+
);
|
|
864
|
+
state.template = template;
|
|
865
|
+
state.isDirty = false;
|
|
866
|
+
return template;
|
|
867
|
+
} catch (error) {
|
|
868
|
+
options.onError?.(error);
|
|
869
|
+
throw error;
|
|
870
|
+
} finally {
|
|
871
|
+
state.isSaving = false;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
async function createSnapshot() {
|
|
875
|
+
if (!state.template?.id) {
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
878
|
+
try {
|
|
879
|
+
await api.createSnapshot(state.template.id, state.content);
|
|
880
|
+
} catch (error) {
|
|
881
|
+
options.onError?.(error);
|
|
882
|
+
throw error;
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
function hasTemplate() {
|
|
886
|
+
return state.template?.id !== void 0;
|
|
887
|
+
}
|
|
888
|
+
function markDirty() {
|
|
889
|
+
state.isDirty = true;
|
|
890
|
+
}
|
|
891
|
+
function ensureCanvasPages() {
|
|
892
|
+
if (state.content.canvasPages?.length) {
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
const id = crypto.randomUUID();
|
|
896
|
+
const blocks = state.content.blocks;
|
|
897
|
+
state.content.canvasPages = [{ id, title: "Step 1", blocks }];
|
|
898
|
+
state.content.activeCanvasPageId = id;
|
|
899
|
+
state.content.blocks = blocks;
|
|
900
|
+
state.isDirty = true;
|
|
901
|
+
}
|
|
902
|
+
function switchCanvasPage(pageId) {
|
|
903
|
+
const pages = state.content.canvasPages;
|
|
904
|
+
if (!pages?.length) {
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
const page = pages.find((p) => p.id === pageId);
|
|
908
|
+
if (!page) {
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
state.selectedBlockId = null;
|
|
912
|
+
state.content.blocks = page.blocks;
|
|
913
|
+
state.content.activeCanvasPageId = pageId;
|
|
914
|
+
state.isDirty = true;
|
|
915
|
+
}
|
|
916
|
+
function addCanvasPage() {
|
|
917
|
+
ensureCanvasPages();
|
|
918
|
+
const pages = state.content.canvasPages;
|
|
919
|
+
const id = crypto.randomUUID();
|
|
920
|
+
const title = `Step ${pages.length + 1}`;
|
|
921
|
+
const newBlocks = [];
|
|
922
|
+
pages.push({ id, title, blocks: newBlocks });
|
|
923
|
+
switchCanvasPage(id);
|
|
924
|
+
}
|
|
925
|
+
function removeCanvasPage(pageId) {
|
|
926
|
+
const pages = state.content.canvasPages;
|
|
927
|
+
if (!pages || pages.length <= 1) {
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
930
|
+
const idx = pages.findIndex((p) => p.id === pageId);
|
|
931
|
+
if (idx === -1) {
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
pages.splice(idx, 1);
|
|
935
|
+
if (state.content.activeCanvasPageId === pageId) {
|
|
936
|
+
const next = pages[Math.min(idx, pages.length - 1)];
|
|
937
|
+
switchCanvasPage(next.id);
|
|
938
|
+
} else {
|
|
939
|
+
state.content.canvasPages = [...pages];
|
|
940
|
+
state.isDirty = true;
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
function renameCanvasPage(pageId, title) {
|
|
944
|
+
const pages = state.content.canvasPages;
|
|
945
|
+
if (!pages) {
|
|
946
|
+
return;
|
|
947
|
+
}
|
|
948
|
+
const page = pages.find((p) => p.id === pageId);
|
|
949
|
+
if (!page) {
|
|
950
|
+
return;
|
|
951
|
+
}
|
|
952
|
+
page.title = title.trim() || page.title;
|
|
953
|
+
state.isDirty = true;
|
|
954
|
+
}
|
|
955
|
+
function switchToNextCanvasPage() {
|
|
956
|
+
const pages = state.content.canvasPages;
|
|
957
|
+
if (!pages?.length) {
|
|
958
|
+
return false;
|
|
959
|
+
}
|
|
960
|
+
const activeId = state.content.activeCanvasPageId;
|
|
961
|
+
const idx = pages.findIndex((p) => p.id === activeId);
|
|
962
|
+
if (idx === -1 || idx >= pages.length - 1) {
|
|
963
|
+
return false;
|
|
964
|
+
}
|
|
965
|
+
switchCanvasPage(pages[idx + 1].id);
|
|
966
|
+
return true;
|
|
967
|
+
}
|
|
968
|
+
function switchToPreviousCanvasPage() {
|
|
969
|
+
const pages = state.content.canvasPages;
|
|
970
|
+
if (!pages?.length) {
|
|
971
|
+
return false;
|
|
972
|
+
}
|
|
973
|
+
const activeId = state.content.activeCanvasPageId;
|
|
974
|
+
const idx = pages.findIndex((p) => p.id === activeId);
|
|
975
|
+
if (idx <= 0) {
|
|
976
|
+
return false;
|
|
977
|
+
}
|
|
978
|
+
switchCanvasPage(pages[idx - 1].id);
|
|
979
|
+
return true;
|
|
980
|
+
}
|
|
981
|
+
return {
|
|
982
|
+
state: readonly(state),
|
|
983
|
+
content,
|
|
984
|
+
selectedBlock,
|
|
985
|
+
savedBlockIds,
|
|
986
|
+
isBlockLocked,
|
|
987
|
+
setContent,
|
|
988
|
+
selectBlock,
|
|
989
|
+
setViewport,
|
|
990
|
+
setDarkMode,
|
|
991
|
+
setUiTheme,
|
|
992
|
+
setPreviewMode,
|
|
993
|
+
updateBlock,
|
|
994
|
+
updateSettings,
|
|
995
|
+
addBlock,
|
|
996
|
+
removeBlock,
|
|
997
|
+
moveBlock,
|
|
998
|
+
create,
|
|
999
|
+
load,
|
|
1000
|
+
save,
|
|
1001
|
+
createSnapshot,
|
|
1002
|
+
hasTemplate,
|
|
1003
|
+
markDirty,
|
|
1004
|
+
ensureCanvasPages,
|
|
1005
|
+
switchCanvasPage,
|
|
1006
|
+
addCanvasPage,
|
|
1007
|
+
removeCanvasPage,
|
|
1008
|
+
renameCanvasPage,
|
|
1009
|
+
switchToNextCanvasPage,
|
|
1010
|
+
switchToPreviousCanvasPage
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
// src/cloud/ai-chat.ts
|
|
1015
|
+
import { ref } from "vue";
|
|
1016
|
+
var messageIdCounter = 0;
|
|
1017
|
+
function generateMessageId() {
|
|
1018
|
+
return `msg_${Date.now()}_${++messageIdCounter}`;
|
|
1019
|
+
}
|
|
1020
|
+
function useAiChat(options) {
|
|
1021
|
+
const { authManager, getTemplateId, onApply, onError } = options;
|
|
1022
|
+
const messages = ref([]);
|
|
1023
|
+
const isGenerating = ref(false);
|
|
1024
|
+
const isLoadingHistory = ref(false);
|
|
1025
|
+
const error = ref(null);
|
|
1026
|
+
const failedPrompt = ref(null);
|
|
1027
|
+
const conversationId = ref(null);
|
|
1028
|
+
const lastApplyMessageId = ref(null);
|
|
1029
|
+
const lastPreviousContent = ref(null);
|
|
1030
|
+
const lastAppliedContent = ref(null);
|
|
1031
|
+
const isLastChangeReverted = ref(false);
|
|
1032
|
+
const suggestions = ref([]);
|
|
1033
|
+
const isLoadingSuggestions = ref(false);
|
|
1034
|
+
function updateMessage(msgId, updates) {
|
|
1035
|
+
const idx = messages.value.findIndex((m) => m.id === msgId);
|
|
1036
|
+
if (idx === -1) {
|
|
1037
|
+
return;
|
|
1038
|
+
}
|
|
1039
|
+
const updated = { ...messages.value[idx], ...updates };
|
|
1040
|
+
messages.value = [
|
|
1041
|
+
...messages.value.slice(0, idx),
|
|
1042
|
+
updated,
|
|
1043
|
+
...messages.value.slice(idx + 1)
|
|
1044
|
+
];
|
|
1045
|
+
}
|
|
1046
|
+
async function loadConversation() {
|
|
1047
|
+
const templateId = getTemplateId();
|
|
1048
|
+
if (!templateId) {
|
|
1049
|
+
return;
|
|
1050
|
+
}
|
|
1051
|
+
isLoadingHistory.value = true;
|
|
1052
|
+
try {
|
|
1053
|
+
const url = buildUrl(API_ROUTES["ai.conversationMessages"], {
|
|
1054
|
+
project: authManager.projectId,
|
|
1055
|
+
tenant: authManager.tenantSlug,
|
|
1056
|
+
template: templateId
|
|
1057
|
+
});
|
|
1058
|
+
const response = await authManager.authenticatedFetch(url, {
|
|
1059
|
+
method: "GET",
|
|
1060
|
+
headers: {
|
|
1061
|
+
Accept: "application/json"
|
|
1062
|
+
}
|
|
1063
|
+
});
|
|
1064
|
+
if (!response.ok) {
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
const data = await response.json();
|
|
1068
|
+
if (data.conversation_id) {
|
|
1069
|
+
conversationId.value = data.conversation_id;
|
|
1070
|
+
}
|
|
1071
|
+
if (Array.isArray(data.data) && data.data.length > 0) {
|
|
1072
|
+
messages.value = data.data.map(
|
|
1073
|
+
(msg) => ({
|
|
1074
|
+
id: msg.id,
|
|
1075
|
+
role: msg.role,
|
|
1076
|
+
content: msg.content,
|
|
1077
|
+
timestamp: new Date(msg.created_at).getTime()
|
|
1078
|
+
})
|
|
1079
|
+
);
|
|
1080
|
+
}
|
|
1081
|
+
} catch {
|
|
1082
|
+
} finally {
|
|
1083
|
+
isLoadingHistory.value = false;
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
async function loadSuggestions(currentContent, mergeTags) {
|
|
1087
|
+
const templateId = getTemplateId();
|
|
1088
|
+
if (!templateId) {
|
|
1089
|
+
return;
|
|
1090
|
+
}
|
|
1091
|
+
isLoadingSuggestions.value = true;
|
|
1092
|
+
try {
|
|
1093
|
+
const url = buildUrl(API_ROUTES["ai.suggestions"], {
|
|
1094
|
+
project: authManager.projectId,
|
|
1095
|
+
tenant: authManager.tenantSlug,
|
|
1096
|
+
template: templateId
|
|
1097
|
+
});
|
|
1098
|
+
const response = await authManager.authenticatedFetch(url, {
|
|
1099
|
+
method: "POST",
|
|
1100
|
+
headers: {
|
|
1101
|
+
"Content-Type": "application/json",
|
|
1102
|
+
Accept: "text/event-stream"
|
|
1103
|
+
},
|
|
1104
|
+
body: JSON.stringify({
|
|
1105
|
+
current_content: currentContent,
|
|
1106
|
+
merge_tags: mergeTags.map((p) => ({
|
|
1107
|
+
label: p.label,
|
|
1108
|
+
value: p.value
|
|
1109
|
+
}))
|
|
1110
|
+
})
|
|
1111
|
+
});
|
|
1112
|
+
if (!response.ok) {
|
|
1113
|
+
return;
|
|
1114
|
+
}
|
|
1115
|
+
const reader = response.body?.getReader();
|
|
1116
|
+
if (!reader) {
|
|
1117
|
+
return;
|
|
1118
|
+
}
|
|
1119
|
+
const decoder = new TextDecoder();
|
|
1120
|
+
let buffer = "";
|
|
1121
|
+
while (true) {
|
|
1122
|
+
const { done, value } = await reader.read();
|
|
1123
|
+
if (done) {
|
|
1124
|
+
break;
|
|
1125
|
+
}
|
|
1126
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1127
|
+
const lines = buffer.split("\n");
|
|
1128
|
+
buffer = lines.pop() ?? "";
|
|
1129
|
+
for (const line of lines) {
|
|
1130
|
+
if (!line.startsWith("data: ")) {
|
|
1131
|
+
continue;
|
|
1132
|
+
}
|
|
1133
|
+
let event;
|
|
1134
|
+
try {
|
|
1135
|
+
event = JSON.parse(line.slice(6));
|
|
1136
|
+
} catch {
|
|
1137
|
+
continue;
|
|
1138
|
+
}
|
|
1139
|
+
if (event.type === "done" && Array.isArray(event.suggestions)) {
|
|
1140
|
+
suggestions.value = event.suggestions.slice(0, 3);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
} catch {
|
|
1145
|
+
} finally {
|
|
1146
|
+
isLoadingSuggestions.value = false;
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
async function sendPrompt(prompt, currentContent, mergeTags) {
|
|
1150
|
+
const templateId = getTemplateId();
|
|
1151
|
+
if (!templateId) {
|
|
1152
|
+
throw new Error("Template must be saved before using AI generation");
|
|
1153
|
+
}
|
|
1154
|
+
isGenerating.value = true;
|
|
1155
|
+
error.value = null;
|
|
1156
|
+
failedPrompt.value = null;
|
|
1157
|
+
suggestions.value = [];
|
|
1158
|
+
const userMsgId = generateMessageId();
|
|
1159
|
+
messages.value = [
|
|
1160
|
+
...messages.value,
|
|
1161
|
+
{
|
|
1162
|
+
id: userMsgId,
|
|
1163
|
+
role: "user",
|
|
1164
|
+
content: prompt,
|
|
1165
|
+
timestamp: Date.now()
|
|
1166
|
+
}
|
|
1167
|
+
];
|
|
1168
|
+
const assistantMsgId = generateMessageId();
|
|
1169
|
+
messages.value = [
|
|
1170
|
+
...messages.value,
|
|
1171
|
+
{
|
|
1172
|
+
id: assistantMsgId,
|
|
1173
|
+
role: "assistant",
|
|
1174
|
+
content: "",
|
|
1175
|
+
timestamp: Date.now()
|
|
1176
|
+
}
|
|
1177
|
+
];
|
|
1178
|
+
try {
|
|
1179
|
+
const url = buildUrl(API_ROUTES["ai.generate"], {
|
|
1180
|
+
project: authManager.projectId,
|
|
1181
|
+
tenant: authManager.tenantSlug,
|
|
1182
|
+
template: templateId
|
|
1183
|
+
});
|
|
1184
|
+
const response = await authManager.authenticatedFetch(url, {
|
|
1185
|
+
method: "POST",
|
|
1186
|
+
headers: {
|
|
1187
|
+
"Content-Type": "application/json",
|
|
1188
|
+
Accept: "text/event-stream"
|
|
1189
|
+
},
|
|
1190
|
+
body: JSON.stringify({
|
|
1191
|
+
prompt,
|
|
1192
|
+
current_content: currentContent,
|
|
1193
|
+
merge_tags: mergeTags.map((p) => ({
|
|
1194
|
+
label: p.label,
|
|
1195
|
+
value: p.value
|
|
1196
|
+
})),
|
|
1197
|
+
conversation_id: conversationId.value
|
|
1198
|
+
})
|
|
1199
|
+
});
|
|
1200
|
+
if (!response.ok) {
|
|
1201
|
+
const errorData = await response.json().catch(() => null);
|
|
1202
|
+
if (response.status === 403) {
|
|
1203
|
+
throw new Error("ai_generation_not_available");
|
|
1204
|
+
}
|
|
1205
|
+
throw new Error(errorData?.message || "Failed to generate template");
|
|
1206
|
+
}
|
|
1207
|
+
const reader = response.body?.getReader();
|
|
1208
|
+
if (!reader) {
|
|
1209
|
+
throw new Error("Failed to read stream");
|
|
1210
|
+
}
|
|
1211
|
+
const decoder = new TextDecoder();
|
|
1212
|
+
let buffer = "";
|
|
1213
|
+
let result = null;
|
|
1214
|
+
try {
|
|
1215
|
+
while (true) {
|
|
1216
|
+
const { done, value } = await reader.read();
|
|
1217
|
+
if (done) {
|
|
1218
|
+
break;
|
|
1219
|
+
}
|
|
1220
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1221
|
+
const lines = buffer.split("\n");
|
|
1222
|
+
buffer = lines.pop() ?? "";
|
|
1223
|
+
for (const line of lines) {
|
|
1224
|
+
if (!line.startsWith("data: ")) {
|
|
1225
|
+
continue;
|
|
1226
|
+
}
|
|
1227
|
+
const jsonStr = line.slice(6);
|
|
1228
|
+
let event;
|
|
1229
|
+
try {
|
|
1230
|
+
event = JSON.parse(jsonStr);
|
|
1231
|
+
} catch {
|
|
1232
|
+
continue;
|
|
1233
|
+
}
|
|
1234
|
+
if (event.type === "text") {
|
|
1235
|
+
updateMessage(assistantMsgId, {
|
|
1236
|
+
content: (messages.value.find((m) => m.id === assistantMsgId)?.content ?? "") + event.text
|
|
1237
|
+
});
|
|
1238
|
+
} else if (event.type === "error") {
|
|
1239
|
+
throw new Error(event.message || "Failed to generate template");
|
|
1240
|
+
} else if (event.type === "done") {
|
|
1241
|
+
if (event.conversation_id) {
|
|
1242
|
+
conversationId.value = event.conversation_id;
|
|
1243
|
+
}
|
|
1244
|
+
updateMessage(assistantMsgId, {
|
|
1245
|
+
content: event.text
|
|
1246
|
+
});
|
|
1247
|
+
result = event.content ?? null;
|
|
1248
|
+
if (result) {
|
|
1249
|
+
lastPreviousContent.value = currentContent;
|
|
1250
|
+
lastAppliedContent.value = result;
|
|
1251
|
+
lastApplyMessageId.value = assistantMsgId;
|
|
1252
|
+
isLastChangeReverted.value = false;
|
|
1253
|
+
onApply?.(result);
|
|
1254
|
+
} else {
|
|
1255
|
+
error.value = "ai_apply_failed";
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
} finally {
|
|
1261
|
+
reader.cancel().catch(() => {
|
|
1262
|
+
});
|
|
1263
|
+
}
|
|
1264
|
+
return result;
|
|
1265
|
+
} catch (err) {
|
|
1266
|
+
const wrappedError = err instanceof Error ? err : new Error("Failed to generate template", { cause: err });
|
|
1267
|
+
error.value = wrappedError.message;
|
|
1268
|
+
failedPrompt.value = prompt;
|
|
1269
|
+
onError?.(wrappedError);
|
|
1270
|
+
messages.value = messages.value.filter(
|
|
1271
|
+
(m) => m.id !== userMsgId && m.id !== assistantMsgId
|
|
1272
|
+
);
|
|
1273
|
+
return null;
|
|
1274
|
+
} finally {
|
|
1275
|
+
isGenerating.value = false;
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
function toggleLastRevert() {
|
|
1279
|
+
if (isLastChangeReverted.value) {
|
|
1280
|
+
if (lastAppliedContent.value) {
|
|
1281
|
+
onApply?.(lastAppliedContent.value);
|
|
1282
|
+
}
|
|
1283
|
+
isLastChangeReverted.value = false;
|
|
1284
|
+
} else {
|
|
1285
|
+
if (lastPreviousContent.value) {
|
|
1286
|
+
onApply?.(lastPreviousContent.value);
|
|
1287
|
+
}
|
|
1288
|
+
isLastChangeReverted.value = true;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
function clearChat() {
|
|
1292
|
+
messages.value = [];
|
|
1293
|
+
conversationId.value = null;
|
|
1294
|
+
error.value = null;
|
|
1295
|
+
lastApplyMessageId.value = null;
|
|
1296
|
+
lastPreviousContent.value = null;
|
|
1297
|
+
lastAppliedContent.value = null;
|
|
1298
|
+
isLastChangeReverted.value = false;
|
|
1299
|
+
}
|
|
1300
|
+
return {
|
|
1301
|
+
messages,
|
|
1302
|
+
isGenerating,
|
|
1303
|
+
isLoadingHistory,
|
|
1304
|
+
isLastChangeReverted,
|
|
1305
|
+
lastApplyMessageId,
|
|
1306
|
+
error,
|
|
1307
|
+
failedPrompt,
|
|
1308
|
+
suggestions,
|
|
1309
|
+
isLoadingSuggestions,
|
|
1310
|
+
sendPrompt,
|
|
1311
|
+
toggleLastRevert,
|
|
1312
|
+
loadConversation,
|
|
1313
|
+
loadSuggestions,
|
|
1314
|
+
clearChat
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
// src/cloud/ai-rewrite.ts
|
|
1319
|
+
import { ref as ref2 } from "vue";
|
|
1320
|
+
function useAiRewrite(options) {
|
|
1321
|
+
const { authManager, getTemplateId } = options;
|
|
1322
|
+
const isRewriting = ref2(false);
|
|
1323
|
+
const streamingText = ref2("");
|
|
1324
|
+
const previousContent = ref2(null);
|
|
1325
|
+
const rewrittenContent = ref2(null);
|
|
1326
|
+
const isReverted = ref2(false);
|
|
1327
|
+
const error = ref2(null);
|
|
1328
|
+
async function rewrite(content, instruction, mergeTags) {
|
|
1329
|
+
const templateId = getTemplateId();
|
|
1330
|
+
if (!templateId) {
|
|
1331
|
+
return null;
|
|
1332
|
+
}
|
|
1333
|
+
isRewriting.value = true;
|
|
1334
|
+
streamingText.value = "";
|
|
1335
|
+
error.value = null;
|
|
1336
|
+
try {
|
|
1337
|
+
const url = buildUrl(API_ROUTES["ai.rewriteText"], {
|
|
1338
|
+
project: authManager.projectId,
|
|
1339
|
+
tenant: authManager.tenantSlug,
|
|
1340
|
+
template: templateId
|
|
1341
|
+
});
|
|
1342
|
+
const response = await authManager.authenticatedFetch(url, {
|
|
1343
|
+
method: "POST",
|
|
1344
|
+
headers: {
|
|
1345
|
+
"Content-Type": "application/json",
|
|
1346
|
+
Accept: "text/event-stream"
|
|
1347
|
+
},
|
|
1348
|
+
body: JSON.stringify({
|
|
1349
|
+
content,
|
|
1350
|
+
instruction,
|
|
1351
|
+
merge_tags: mergeTags.map((p) => ({
|
|
1352
|
+
label: p.label,
|
|
1353
|
+
value: p.value
|
|
1354
|
+
}))
|
|
1355
|
+
})
|
|
1356
|
+
});
|
|
1357
|
+
if (!response.ok) {
|
|
1358
|
+
if (response.status === 403) {
|
|
1359
|
+
throw new Error("ai_generation_not_available");
|
|
1360
|
+
}
|
|
1361
|
+
const errorData = await response.json().catch(() => null);
|
|
1362
|
+
throw new Error(errorData?.message || "Failed to rewrite text");
|
|
1363
|
+
}
|
|
1364
|
+
const reader = response.body?.getReader();
|
|
1365
|
+
if (!reader) {
|
|
1366
|
+
throw new Error("Failed to read stream");
|
|
1367
|
+
}
|
|
1368
|
+
const decoder = new TextDecoder();
|
|
1369
|
+
let buffer = "";
|
|
1370
|
+
let result = null;
|
|
1371
|
+
while (true) {
|
|
1372
|
+
const { done, value } = await reader.read();
|
|
1373
|
+
if (done) {
|
|
1374
|
+
break;
|
|
1375
|
+
}
|
|
1376
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1377
|
+
const lines = buffer.split("\n");
|
|
1378
|
+
buffer = lines.pop() ?? "";
|
|
1379
|
+
for (const line of lines) {
|
|
1380
|
+
if (!line.startsWith("data: ")) {
|
|
1381
|
+
continue;
|
|
1382
|
+
}
|
|
1383
|
+
let event;
|
|
1384
|
+
try {
|
|
1385
|
+
event = JSON.parse(line.slice(6));
|
|
1386
|
+
} catch {
|
|
1387
|
+
continue;
|
|
1388
|
+
}
|
|
1389
|
+
if (event.type === "text") {
|
|
1390
|
+
streamingText.value += event.text;
|
|
1391
|
+
} else if (event.type === "error") {
|
|
1392
|
+
throw new Error(event.message || "Failed to rewrite text");
|
|
1393
|
+
} else if (event.type === "done") {
|
|
1394
|
+
result = event.content ?? null;
|
|
1395
|
+
if (result) {
|
|
1396
|
+
previousContent.value = content;
|
|
1397
|
+
rewrittenContent.value = result;
|
|
1398
|
+
isReverted.value = false;
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
return result;
|
|
1404
|
+
} catch (err) {
|
|
1405
|
+
error.value = err instanceof Error ? err.message : "Failed to rewrite text";
|
|
1406
|
+
return null;
|
|
1407
|
+
} finally {
|
|
1408
|
+
isRewriting.value = false;
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
function undo() {
|
|
1412
|
+
if (!previousContent.value) {
|
|
1413
|
+
return null;
|
|
1414
|
+
}
|
|
1415
|
+
isReverted.value = true;
|
|
1416
|
+
return previousContent.value;
|
|
1417
|
+
}
|
|
1418
|
+
function redo() {
|
|
1419
|
+
if (!rewrittenContent.value) {
|
|
1420
|
+
return null;
|
|
1421
|
+
}
|
|
1422
|
+
isReverted.value = false;
|
|
1423
|
+
return rewrittenContent.value;
|
|
1424
|
+
}
|
|
1425
|
+
function reset() {
|
|
1426
|
+
isRewriting.value = false;
|
|
1427
|
+
streamingText.value = "";
|
|
1428
|
+
previousContent.value = null;
|
|
1429
|
+
rewrittenContent.value = null;
|
|
1430
|
+
isReverted.value = false;
|
|
1431
|
+
error.value = null;
|
|
1432
|
+
}
|
|
1433
|
+
return {
|
|
1434
|
+
isRewriting,
|
|
1435
|
+
streamingText,
|
|
1436
|
+
previousContent,
|
|
1437
|
+
rewrittenContent,
|
|
1438
|
+
isReverted,
|
|
1439
|
+
error,
|
|
1440
|
+
rewrite,
|
|
1441
|
+
undo,
|
|
1442
|
+
redo,
|
|
1443
|
+
reset
|
|
1444
|
+
};
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
// src/cloud/ai-config.ts
|
|
1448
|
+
import { computed as computed2 } from "vue";
|
|
1449
|
+
function useAiConfig(config) {
|
|
1450
|
+
function isFeatureEnabled(feature) {
|
|
1451
|
+
if (config === false) {
|
|
1452
|
+
return false;
|
|
1453
|
+
}
|
|
1454
|
+
return config?.[feature] !== false;
|
|
1455
|
+
}
|
|
1456
|
+
const hasAnyMenuFeature = computed2(
|
|
1457
|
+
() => isFeatureEnabled("chat") || isFeatureEnabled("scoring") || isFeatureEnabled("designToTemplate")
|
|
1458
|
+
);
|
|
1459
|
+
return {
|
|
1460
|
+
isFeatureEnabled,
|
|
1461
|
+
hasAnyMenuFeature
|
|
1462
|
+
};
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
// src/cloud/template-scoring.ts
|
|
1466
|
+
import { ref as ref3 } from "vue";
|
|
1467
|
+
function useTemplateScoring(options) {
|
|
1468
|
+
const { authManager, getTemplateId } = options;
|
|
1469
|
+
const isScoring = ref3(false);
|
|
1470
|
+
const scoringResult = ref3(null);
|
|
1471
|
+
const error = ref3(null);
|
|
1472
|
+
const fixingFindingId = ref3(null);
|
|
1473
|
+
const fixStreamingText = ref3("");
|
|
1474
|
+
const fixError = ref3(null);
|
|
1475
|
+
async function score(content, mergeTags) {
|
|
1476
|
+
const templateId = getTemplateId();
|
|
1477
|
+
if (!templateId) {
|
|
1478
|
+
return null;
|
|
1479
|
+
}
|
|
1480
|
+
isScoring.value = true;
|
|
1481
|
+
error.value = null;
|
|
1482
|
+
scoringResult.value = null;
|
|
1483
|
+
try {
|
|
1484
|
+
const url = buildUrl(API_ROUTES["ai.score"], {
|
|
1485
|
+
project: authManager.projectId,
|
|
1486
|
+
tenant: authManager.tenantSlug,
|
|
1487
|
+
template: templateId
|
|
1488
|
+
});
|
|
1489
|
+
const response = await authManager.authenticatedFetch(url, {
|
|
1490
|
+
method: "POST",
|
|
1491
|
+
headers: {
|
|
1492
|
+
"Content-Type": "application/json",
|
|
1493
|
+
Accept: "text/event-stream"
|
|
1494
|
+
},
|
|
1495
|
+
body: JSON.stringify({
|
|
1496
|
+
current_content: content,
|
|
1497
|
+
merge_tags: mergeTags.map((p) => ({
|
|
1498
|
+
label: p.label,
|
|
1499
|
+
value: p.value
|
|
1500
|
+
}))
|
|
1501
|
+
})
|
|
1502
|
+
});
|
|
1503
|
+
if (!response.ok) {
|
|
1504
|
+
if (response.status === 403) {
|
|
1505
|
+
throw new Error("ai_generation_not_available");
|
|
1506
|
+
}
|
|
1507
|
+
const errorData = await response.json().catch(() => null);
|
|
1508
|
+
throw new Error(errorData?.message || "Failed to score template");
|
|
1509
|
+
}
|
|
1510
|
+
const reader = response.body?.getReader();
|
|
1511
|
+
if (!reader) {
|
|
1512
|
+
throw new Error("Failed to read stream");
|
|
1513
|
+
}
|
|
1514
|
+
const decoder = new TextDecoder();
|
|
1515
|
+
let buffer = "";
|
|
1516
|
+
let result = null;
|
|
1517
|
+
while (true) {
|
|
1518
|
+
const { done, value } = await reader.read();
|
|
1519
|
+
if (done) {
|
|
1520
|
+
break;
|
|
1521
|
+
}
|
|
1522
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1523
|
+
const lines = buffer.split("\n");
|
|
1524
|
+
buffer = lines.pop() ?? "";
|
|
1525
|
+
for (const line of lines) {
|
|
1526
|
+
if (!line.startsWith("data: ")) {
|
|
1527
|
+
continue;
|
|
1528
|
+
}
|
|
1529
|
+
let event;
|
|
1530
|
+
try {
|
|
1531
|
+
event = JSON.parse(line.slice(6));
|
|
1532
|
+
} catch {
|
|
1533
|
+
continue;
|
|
1534
|
+
}
|
|
1535
|
+
if (event.type === "error") {
|
|
1536
|
+
throw new Error(event.message || "Failed to score template");
|
|
1537
|
+
}
|
|
1538
|
+
if (event.type === "done") {
|
|
1539
|
+
result = event.result ?? null;
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
if (result) {
|
|
1544
|
+
for (const [category, categoryData] of Object.entries(
|
|
1545
|
+
result.categories
|
|
1546
|
+
)) {
|
|
1547
|
+
for (const finding of categoryData.findings) {
|
|
1548
|
+
finding.category = category;
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
}
|
|
1552
|
+
scoringResult.value = result;
|
|
1553
|
+
return result;
|
|
1554
|
+
} catch (err) {
|
|
1555
|
+
error.value = err instanceof Error ? err.message : "Failed to score template";
|
|
1556
|
+
return null;
|
|
1557
|
+
} finally {
|
|
1558
|
+
isScoring.value = false;
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
async function fixFinding(blockContent, finding, mergeTags) {
|
|
1562
|
+
const templateId = getTemplateId();
|
|
1563
|
+
if (!templateId) {
|
|
1564
|
+
return null;
|
|
1565
|
+
}
|
|
1566
|
+
fixingFindingId.value = finding.id;
|
|
1567
|
+
fixStreamingText.value = "";
|
|
1568
|
+
fixError.value = null;
|
|
1569
|
+
try {
|
|
1570
|
+
const url = buildUrl(API_ROUTES["ai.fixFinding"], {
|
|
1571
|
+
project: authManager.projectId,
|
|
1572
|
+
tenant: authManager.tenantSlug,
|
|
1573
|
+
template: templateId
|
|
1574
|
+
});
|
|
1575
|
+
const response = await authManager.authenticatedFetch(url, {
|
|
1576
|
+
method: "POST",
|
|
1577
|
+
headers: {
|
|
1578
|
+
"Content-Type": "application/json",
|
|
1579
|
+
Accept: "text/event-stream"
|
|
1580
|
+
},
|
|
1581
|
+
body: JSON.stringify({
|
|
1582
|
+
content: blockContent,
|
|
1583
|
+
finding: {
|
|
1584
|
+
id: finding.id,
|
|
1585
|
+
message: finding.message,
|
|
1586
|
+
suggestion: finding.suggestion,
|
|
1587
|
+
category: finding.category
|
|
1588
|
+
},
|
|
1589
|
+
merge_tags: mergeTags.map((p) => ({
|
|
1590
|
+
label: p.label,
|
|
1591
|
+
value: p.value
|
|
1592
|
+
}))
|
|
1593
|
+
})
|
|
1594
|
+
});
|
|
1595
|
+
if (!response.ok) {
|
|
1596
|
+
if (response.status === 403) {
|
|
1597
|
+
throw new Error("ai_generation_not_available");
|
|
1598
|
+
}
|
|
1599
|
+
const errorData = await response.json().catch(() => null);
|
|
1600
|
+
throw new Error(errorData?.message || "Failed to fix finding");
|
|
1601
|
+
}
|
|
1602
|
+
const reader = response.body?.getReader();
|
|
1603
|
+
if (!reader) {
|
|
1604
|
+
throw new Error("Failed to read stream");
|
|
1605
|
+
}
|
|
1606
|
+
const decoder = new TextDecoder();
|
|
1607
|
+
let buffer = "";
|
|
1608
|
+
let result = null;
|
|
1609
|
+
while (true) {
|
|
1610
|
+
const { done, value } = await reader.read();
|
|
1611
|
+
if (done) {
|
|
1612
|
+
break;
|
|
1613
|
+
}
|
|
1614
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1615
|
+
const lines = buffer.split("\n");
|
|
1616
|
+
buffer = lines.pop() ?? "";
|
|
1617
|
+
for (const line of lines) {
|
|
1618
|
+
if (!line.startsWith("data: ")) {
|
|
1619
|
+
continue;
|
|
1620
|
+
}
|
|
1621
|
+
let event;
|
|
1622
|
+
try {
|
|
1623
|
+
event = JSON.parse(line.slice(6));
|
|
1624
|
+
} catch {
|
|
1625
|
+
continue;
|
|
1626
|
+
}
|
|
1627
|
+
if (event.type === "text") {
|
|
1628
|
+
fixStreamingText.value += event.text;
|
|
1629
|
+
} else if (event.type === "error") {
|
|
1630
|
+
throw new Error(event.message || "Failed to fix finding");
|
|
1631
|
+
} else if (event.type === "done") {
|
|
1632
|
+
result = event.content ?? null;
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
}
|
|
1636
|
+
return result;
|
|
1637
|
+
} catch (err) {
|
|
1638
|
+
fixError.value = err instanceof Error ? err.message : "Failed to fix finding";
|
|
1639
|
+
return null;
|
|
1640
|
+
} finally {
|
|
1641
|
+
fixingFindingId.value = null;
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
function removeFinding(category, findingId) {
|
|
1645
|
+
if (!scoringResult.value) {
|
|
1646
|
+
return;
|
|
1647
|
+
}
|
|
1648
|
+
const cat = scoringResult.value.categories[category];
|
|
1649
|
+
if (!cat) {
|
|
1650
|
+
return;
|
|
1651
|
+
}
|
|
1652
|
+
cat.findings = cat.findings.filter((f) => f.id !== findingId);
|
|
1653
|
+
}
|
|
1654
|
+
function reset() {
|
|
1655
|
+
isScoring.value = false;
|
|
1656
|
+
scoringResult.value = null;
|
|
1657
|
+
error.value = null;
|
|
1658
|
+
fixingFindingId.value = null;
|
|
1659
|
+
fixStreamingText.value = "";
|
|
1660
|
+
fixError.value = null;
|
|
1661
|
+
}
|
|
1662
|
+
return {
|
|
1663
|
+
isScoring,
|
|
1664
|
+
scoringResult,
|
|
1665
|
+
error,
|
|
1666
|
+
fixingFindingId,
|
|
1667
|
+
fixStreamingText,
|
|
1668
|
+
fixError,
|
|
1669
|
+
score,
|
|
1670
|
+
fixFinding,
|
|
1671
|
+
removeFinding,
|
|
1672
|
+
reset
|
|
1673
|
+
};
|
|
1674
|
+
}
|
|
1675
|
+
|
|
1676
|
+
// src/cloud/design-reference.ts
|
|
1677
|
+
import { ref as ref4 } from "vue";
|
|
1678
|
+
function useDesignReference(options) {
|
|
1679
|
+
const { authManager, getTemplateId, onApply, onError } = options;
|
|
1680
|
+
const isGenerating = ref4(false);
|
|
1681
|
+
const error = ref4(null);
|
|
1682
|
+
async function generate(input) {
|
|
1683
|
+
const templateId = getTemplateId();
|
|
1684
|
+
if (!templateId) {
|
|
1685
|
+
throw new Error("Template must be saved before using design reference");
|
|
1686
|
+
}
|
|
1687
|
+
isGenerating.value = true;
|
|
1688
|
+
error.value = null;
|
|
1689
|
+
try {
|
|
1690
|
+
const formData = new FormData();
|
|
1691
|
+
if (input.prompt) {
|
|
1692
|
+
formData.append("prompt", input.prompt);
|
|
1693
|
+
}
|
|
1694
|
+
if (input.imageUpload) {
|
|
1695
|
+
formData.append("image_upload", input.imageUpload);
|
|
1696
|
+
}
|
|
1697
|
+
if (input.pdfUpload) {
|
|
1698
|
+
formData.append("pdf_upload", input.pdfUpload);
|
|
1699
|
+
}
|
|
1700
|
+
const url = buildUrl(API_ROUTES["ai.generateFromDesign"], {
|
|
1701
|
+
project: authManager.projectId,
|
|
1702
|
+
tenant: authManager.tenantSlug,
|
|
1703
|
+
template: templateId
|
|
1704
|
+
});
|
|
1705
|
+
const response = await authManager.authenticatedFetch(url, {
|
|
1706
|
+
method: "POST",
|
|
1707
|
+
headers: {
|
|
1708
|
+
Accept: "text/event-stream"
|
|
1709
|
+
},
|
|
1710
|
+
body: formData
|
|
1711
|
+
});
|
|
1712
|
+
if (!response.ok) {
|
|
1713
|
+
const errorData = await response.json().catch(() => null);
|
|
1714
|
+
if (response.status === 403) {
|
|
1715
|
+
throw new Error("ai_generation_not_available");
|
|
1716
|
+
}
|
|
1717
|
+
throw new Error(
|
|
1718
|
+
errorData?.message || "Failed to generate template from design"
|
|
1719
|
+
);
|
|
1720
|
+
}
|
|
1721
|
+
const reader = response.body?.getReader();
|
|
1722
|
+
if (!reader) {
|
|
1723
|
+
throw new Error("Failed to read stream");
|
|
1724
|
+
}
|
|
1725
|
+
const decoder = new TextDecoder();
|
|
1726
|
+
let buffer = "";
|
|
1727
|
+
let result = null;
|
|
1728
|
+
while (true) {
|
|
1729
|
+
const { done, value } = await reader.read();
|
|
1730
|
+
if (done) {
|
|
1731
|
+
break;
|
|
1732
|
+
}
|
|
1733
|
+
buffer += decoder.decode(value, { stream: true });
|
|
1734
|
+
const lines = buffer.split("\n");
|
|
1735
|
+
buffer = lines.pop() ?? "";
|
|
1736
|
+
for (const line of lines) {
|
|
1737
|
+
if (!line.startsWith("data: ")) {
|
|
1738
|
+
continue;
|
|
1739
|
+
}
|
|
1740
|
+
const jsonStr = line.slice(6);
|
|
1741
|
+
let event;
|
|
1742
|
+
try {
|
|
1743
|
+
event = JSON.parse(jsonStr);
|
|
1744
|
+
} catch {
|
|
1745
|
+
continue;
|
|
1746
|
+
}
|
|
1747
|
+
if (event.type === "error") {
|
|
1748
|
+
throw new Error(
|
|
1749
|
+
event.message || "Failed to generate template from design"
|
|
1750
|
+
);
|
|
1751
|
+
}
|
|
1752
|
+
if (event.type === "done") {
|
|
1753
|
+
result = event.content ?? null;
|
|
1754
|
+
if (result) {
|
|
1755
|
+
onApply?.(result);
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
return result;
|
|
1761
|
+
} catch (err) {
|
|
1762
|
+
const wrappedError = err instanceof Error ? err : new Error("Failed to generate template from design", {
|
|
1763
|
+
cause: err
|
|
1764
|
+
});
|
|
1765
|
+
error.value = wrappedError.message;
|
|
1766
|
+
onError?.(wrappedError);
|
|
1767
|
+
return null;
|
|
1768
|
+
} finally {
|
|
1769
|
+
isGenerating.value = false;
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
function reset() {
|
|
1773
|
+
isGenerating.value = false;
|
|
1774
|
+
error.value = null;
|
|
1775
|
+
}
|
|
1776
|
+
return {
|
|
1777
|
+
isGenerating,
|
|
1778
|
+
error,
|
|
1779
|
+
generate,
|
|
1780
|
+
reset
|
|
1781
|
+
};
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
// src/cloud/comments.ts
|
|
1785
|
+
import { computed as computed3, ref as ref5 } from "vue";
|
|
1786
|
+
function useComments(options) {
|
|
1787
|
+
const {
|
|
1788
|
+
authManager,
|
|
1789
|
+
getTemplateId,
|
|
1790
|
+
getSocketId,
|
|
1791
|
+
onComment,
|
|
1792
|
+
onError,
|
|
1793
|
+
hasCommentingFeature
|
|
1794
|
+
} = options;
|
|
1795
|
+
const api = new ApiClient(authManager);
|
|
1796
|
+
const comments = ref5([]);
|
|
1797
|
+
const isLoading = ref5(false);
|
|
1798
|
+
const isSubmitting = ref5(false);
|
|
1799
|
+
const isEnabled = computed3(() => {
|
|
1800
|
+
const featureAvailable = hasCommentingFeature?.() ?? false;
|
|
1801
|
+
return featureAvailable && authManager.userConfig !== null;
|
|
1802
|
+
});
|
|
1803
|
+
const totalCount = computed3(() => {
|
|
1804
|
+
let count = 0;
|
|
1805
|
+
for (const thread of comments.value) {
|
|
1806
|
+
count += 1 + (thread.replies?.length ?? 0);
|
|
1807
|
+
}
|
|
1808
|
+
return count;
|
|
1809
|
+
});
|
|
1810
|
+
const unresolvedCount = computed3(() => {
|
|
1811
|
+
return comments.value.filter((c) => !c.resolved_at).length;
|
|
1812
|
+
});
|
|
1813
|
+
const commentCountByBlock = computed3(() => {
|
|
1814
|
+
const map = /* @__PURE__ */ new Map();
|
|
1815
|
+
for (const thread of comments.value) {
|
|
1816
|
+
if (thread.block_id) {
|
|
1817
|
+
map.set(
|
|
1818
|
+
thread.block_id,
|
|
1819
|
+
(map.get(thread.block_id) ?? 0) + 1 + (thread.replies?.length ?? 0)
|
|
1820
|
+
);
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
return map;
|
|
1824
|
+
});
|
|
1825
|
+
function getUserPayload() {
|
|
1826
|
+
const user = authManager.userConfig;
|
|
1827
|
+
if (!user) {
|
|
1828
|
+
throw new Error("User config not available");
|
|
1829
|
+
}
|
|
1830
|
+
return {
|
|
1831
|
+
user_id: user.id,
|
|
1832
|
+
user_name: user.name,
|
|
1833
|
+
user_signature: user.signature
|
|
1834
|
+
};
|
|
1835
|
+
}
|
|
1836
|
+
function socketHeaders() {
|
|
1837
|
+
const socketId = getSocketId?.();
|
|
1838
|
+
if (!socketId) {
|
|
1839
|
+
return void 0;
|
|
1840
|
+
}
|
|
1841
|
+
return { "X-Socket-ID": socketId };
|
|
1842
|
+
}
|
|
1843
|
+
function emitEvent(type, comment) {
|
|
1844
|
+
onComment?.({ type, comment });
|
|
1845
|
+
}
|
|
1846
|
+
function findComment(commentId) {
|
|
1847
|
+
for (const thread of comments.value) {
|
|
1848
|
+
if (thread.id === commentId) {
|
|
1849
|
+
return thread;
|
|
1850
|
+
}
|
|
1851
|
+
for (const reply of thread.replies ?? []) {
|
|
1852
|
+
if (reply.id === commentId) {
|
|
1853
|
+
return reply;
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
}
|
|
1857
|
+
return null;
|
|
1858
|
+
}
|
|
1859
|
+
async function loadComments() {
|
|
1860
|
+
const templateId = getTemplateId();
|
|
1861
|
+
if (!templateId) {
|
|
1862
|
+
return;
|
|
1863
|
+
}
|
|
1864
|
+
isLoading.value = true;
|
|
1865
|
+
try {
|
|
1866
|
+
comments.value = await api.getComments(templateId);
|
|
1867
|
+
} catch (err) {
|
|
1868
|
+
const wrappedError = err instanceof Error ? err : new Error("Failed to load comments", { cause: err });
|
|
1869
|
+
onError?.(wrappedError);
|
|
1870
|
+
} finally {
|
|
1871
|
+
isLoading.value = false;
|
|
1872
|
+
}
|
|
1873
|
+
}
|
|
1874
|
+
async function addComment(body, blockId, parentId) {
|
|
1875
|
+
const templateId = getTemplateId();
|
|
1876
|
+
if (!templateId) {
|
|
1877
|
+
return null;
|
|
1878
|
+
}
|
|
1879
|
+
isSubmitting.value = true;
|
|
1880
|
+
try {
|
|
1881
|
+
const comment = await api.createComment(
|
|
1882
|
+
templateId,
|
|
1883
|
+
{
|
|
1884
|
+
body,
|
|
1885
|
+
block_id: blockId,
|
|
1886
|
+
parent_id: parentId,
|
|
1887
|
+
...getUserPayload()
|
|
1888
|
+
},
|
|
1889
|
+
socketHeaders()
|
|
1890
|
+
);
|
|
1891
|
+
if (parentId) {
|
|
1892
|
+
const parent = findComment(parentId);
|
|
1893
|
+
if (parent) {
|
|
1894
|
+
parent.replies = [...parent.replies ?? [], comment];
|
|
1895
|
+
}
|
|
1896
|
+
} else {
|
|
1897
|
+
comments.value = [...comments.value, comment];
|
|
1898
|
+
}
|
|
1899
|
+
emitEvent("created", comment);
|
|
1900
|
+
return comment;
|
|
1901
|
+
} catch (err) {
|
|
1902
|
+
const wrappedError = err instanceof Error ? err : new Error("Failed to create comment", { cause: err });
|
|
1903
|
+
onError?.(wrappedError);
|
|
1904
|
+
return null;
|
|
1905
|
+
} finally {
|
|
1906
|
+
isSubmitting.value = false;
|
|
1907
|
+
}
|
|
1908
|
+
}
|
|
1909
|
+
async function editComment(commentId, body) {
|
|
1910
|
+
const templateId = getTemplateId();
|
|
1911
|
+
if (!templateId) {
|
|
1912
|
+
return null;
|
|
1913
|
+
}
|
|
1914
|
+
isSubmitting.value = true;
|
|
1915
|
+
try {
|
|
1916
|
+
const updated = await api.updateComment(
|
|
1917
|
+
templateId,
|
|
1918
|
+
commentId,
|
|
1919
|
+
{
|
|
1920
|
+
body,
|
|
1921
|
+
...getUserPayload()
|
|
1922
|
+
},
|
|
1923
|
+
socketHeaders()
|
|
1924
|
+
);
|
|
1925
|
+
updateCommentInState(commentId, updated);
|
|
1926
|
+
emitEvent("updated", updated);
|
|
1927
|
+
return updated;
|
|
1928
|
+
} catch (err) {
|
|
1929
|
+
const wrappedError = err instanceof Error ? err : new Error("Failed to update comment", { cause: err });
|
|
1930
|
+
onError?.(wrappedError);
|
|
1931
|
+
return null;
|
|
1932
|
+
} finally {
|
|
1933
|
+
isSubmitting.value = false;
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
async function removeComment(commentId) {
|
|
1937
|
+
const templateId = getTemplateId();
|
|
1938
|
+
if (!templateId) {
|
|
1939
|
+
return false;
|
|
1940
|
+
}
|
|
1941
|
+
const comment = findComment(commentId);
|
|
1942
|
+
if (!comment) {
|
|
1943
|
+
return false;
|
|
1944
|
+
}
|
|
1945
|
+
const commentSnapshot = {
|
|
1946
|
+
...comment,
|
|
1947
|
+
replies: [...comment.replies ?? []]
|
|
1948
|
+
};
|
|
1949
|
+
isSubmitting.value = true;
|
|
1950
|
+
try {
|
|
1951
|
+
await api.deleteComment(
|
|
1952
|
+
templateId,
|
|
1953
|
+
commentId,
|
|
1954
|
+
getUserPayload(),
|
|
1955
|
+
socketHeaders()
|
|
1956
|
+
);
|
|
1957
|
+
if (comment.parent_id) {
|
|
1958
|
+
const parent = findComment(comment.parent_id);
|
|
1959
|
+
if (parent) {
|
|
1960
|
+
parent.replies = (parent.replies ?? []).filter(
|
|
1961
|
+
(r) => r.id !== commentId
|
|
1962
|
+
);
|
|
1963
|
+
}
|
|
1964
|
+
} else {
|
|
1965
|
+
comments.value = comments.value.filter((c) => c.id !== commentId);
|
|
1966
|
+
}
|
|
1967
|
+
emitEvent("deleted", commentSnapshot);
|
|
1968
|
+
return true;
|
|
1969
|
+
} catch (err) {
|
|
1970
|
+
const wrappedError = err instanceof Error ? err : new Error("Failed to delete comment", { cause: err });
|
|
1971
|
+
onError?.(wrappedError);
|
|
1972
|
+
return false;
|
|
1973
|
+
} finally {
|
|
1974
|
+
isSubmitting.value = false;
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
async function toggleResolve(commentId) {
|
|
1978
|
+
const templateId = getTemplateId();
|
|
1979
|
+
if (!templateId) {
|
|
1980
|
+
return null;
|
|
1981
|
+
}
|
|
1982
|
+
isSubmitting.value = true;
|
|
1983
|
+
try {
|
|
1984
|
+
const updated = await api.resolveComment(
|
|
1985
|
+
templateId,
|
|
1986
|
+
commentId,
|
|
1987
|
+
getUserPayload(),
|
|
1988
|
+
socketHeaders()
|
|
1989
|
+
);
|
|
1990
|
+
updateCommentInState(commentId, updated);
|
|
1991
|
+
const eventType = updated.resolved_at ? "resolved" : "unresolved";
|
|
1992
|
+
emitEvent(eventType, updated);
|
|
1993
|
+
return updated;
|
|
1994
|
+
} catch (err) {
|
|
1995
|
+
const wrappedError = err instanceof Error ? err : new Error("Failed to toggle comment resolution", { cause: err });
|
|
1996
|
+
onError?.(wrappedError);
|
|
1997
|
+
return null;
|
|
1998
|
+
} finally {
|
|
1999
|
+
isSubmitting.value = false;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
function applyRemoteCreate(comment) {
|
|
2003
|
+
if (comment.parent_id) {
|
|
2004
|
+
const parent = findComment(comment.parent_id);
|
|
2005
|
+
if (parent) {
|
|
2006
|
+
parent.replies = [...parent.replies ?? [], comment];
|
|
2007
|
+
}
|
|
2008
|
+
} else {
|
|
2009
|
+
comments.value = [...comments.value, comment];
|
|
2010
|
+
}
|
|
2011
|
+
emitEvent("created", comment);
|
|
2012
|
+
}
|
|
2013
|
+
function applyRemoteUpdate(comment) {
|
|
2014
|
+
updateCommentInState(comment.id, comment);
|
|
2015
|
+
emitEvent("updated", comment);
|
|
2016
|
+
}
|
|
2017
|
+
function applyRemoteDelete(commentId, parentId) {
|
|
2018
|
+
const comment = findComment(commentId);
|
|
2019
|
+
const snapshot = comment ? { ...comment, replies: [...comment.replies ?? []] } : null;
|
|
2020
|
+
if (parentId) {
|
|
2021
|
+
const parent = findComment(parentId);
|
|
2022
|
+
if (parent) {
|
|
2023
|
+
parent.replies = (parent.replies ?? []).filter(
|
|
2024
|
+
(r) => r.id !== commentId
|
|
2025
|
+
);
|
|
2026
|
+
}
|
|
2027
|
+
} else {
|
|
2028
|
+
comments.value = comments.value.filter((c) => c.id !== commentId);
|
|
2029
|
+
}
|
|
2030
|
+
if (snapshot) {
|
|
2031
|
+
emitEvent("deleted", snapshot);
|
|
2032
|
+
}
|
|
2033
|
+
}
|
|
2034
|
+
function updateCommentInState(commentId, updated) {
|
|
2035
|
+
for (let i = 0; i < comments.value.length; i++) {
|
|
2036
|
+
if (comments.value[i].id === commentId) {
|
|
2037
|
+
comments.value = [
|
|
2038
|
+
...comments.value.slice(0, i),
|
|
2039
|
+
{ ...updated, replies: comments.value[i].replies },
|
|
2040
|
+
...comments.value.slice(i + 1)
|
|
2041
|
+
];
|
|
2042
|
+
return;
|
|
2043
|
+
}
|
|
2044
|
+
const replies = comments.value[i].replies ?? [];
|
|
2045
|
+
for (let j = 0; j < replies.length; j++) {
|
|
2046
|
+
if (replies[j].id === commentId) {
|
|
2047
|
+
const newReplies = [
|
|
2048
|
+
...replies.slice(0, j),
|
|
2049
|
+
updated,
|
|
2050
|
+
...replies.slice(j + 1)
|
|
2051
|
+
];
|
|
2052
|
+
comments.value = [
|
|
2053
|
+
...comments.value.slice(0, i),
|
|
2054
|
+
{ ...comments.value[i], replies: newReplies },
|
|
2055
|
+
...comments.value.slice(i + 1)
|
|
2056
|
+
];
|
|
2057
|
+
return;
|
|
2058
|
+
}
|
|
2059
|
+
}
|
|
2060
|
+
}
|
|
2061
|
+
}
|
|
2062
|
+
return {
|
|
2063
|
+
comments,
|
|
2064
|
+
isLoading,
|
|
2065
|
+
isSubmitting,
|
|
2066
|
+
isEnabled,
|
|
2067
|
+
commentCountByBlock,
|
|
2068
|
+
totalCount,
|
|
2069
|
+
unresolvedCount,
|
|
2070
|
+
loadComments,
|
|
2071
|
+
addComment,
|
|
2072
|
+
editComment,
|
|
2073
|
+
removeComment,
|
|
2074
|
+
toggleResolve,
|
|
2075
|
+
applyRemoteCreate,
|
|
2076
|
+
applyRemoteUpdate,
|
|
2077
|
+
applyRemoteDelete
|
|
2078
|
+
};
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
// src/cloud/comment-listener.ts
|
|
2082
|
+
import { onScopeDispose, watch } from "vue";
|
|
2083
|
+
function useCommentListener(options) {
|
|
2084
|
+
const { comments, channel } = options;
|
|
2085
|
+
watch(channel, (newChannel, oldChannel) => {
|
|
2086
|
+
if (oldChannel) {
|
|
2087
|
+
oldChannel.unbind("comment-broadcast");
|
|
2088
|
+
}
|
|
2089
|
+
if (newChannel) {
|
|
2090
|
+
newChannel.bind(
|
|
2091
|
+
"comment-broadcast",
|
|
2092
|
+
(payload) => {
|
|
2093
|
+
handleCommentBroadcast(comments, payload);
|
|
2094
|
+
}
|
|
2095
|
+
);
|
|
2096
|
+
}
|
|
2097
|
+
});
|
|
2098
|
+
onScopeDispose(() => {
|
|
2099
|
+
channel.value?.unbind("comment-broadcast");
|
|
2100
|
+
});
|
|
2101
|
+
}
|
|
2102
|
+
function handleCommentBroadcast(comments, payload) {
|
|
2103
|
+
switch (payload.action) {
|
|
2104
|
+
case "comment_created":
|
|
2105
|
+
comments.applyRemoteCreate(payload.comment);
|
|
2106
|
+
break;
|
|
2107
|
+
case "comment_updated":
|
|
2108
|
+
comments.applyRemoteUpdate(payload.comment);
|
|
2109
|
+
break;
|
|
2110
|
+
case "comment_deleted":
|
|
2111
|
+
comments.applyRemoteDelete(payload.comment.id, payload.comment.parent_id);
|
|
2112
|
+
break;
|
|
2113
|
+
case "comment_resolved":
|
|
2114
|
+
case "comment_unresolved":
|
|
2115
|
+
comments.applyRemoteUpdate(payload.comment);
|
|
2116
|
+
break;
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
// src/cloud/collaboration.ts
|
|
2121
|
+
import { computed as computed4, onScopeDispose as onScopeDispose2, ref as ref6, watch as watch2 } from "vue";
|
|
2122
|
+
var COLLAB_EVENTS = [
|
|
2123
|
+
"pusher:member_added",
|
|
2124
|
+
"pusher:member_removed",
|
|
2125
|
+
"client-block_locked",
|
|
2126
|
+
"client-block_unlocked",
|
|
2127
|
+
"client-operation",
|
|
2128
|
+
"mcp-operation"
|
|
2129
|
+
];
|
|
2130
|
+
function unbindCollabEvents(channel) {
|
|
2131
|
+
for (const event of COLLAB_EVENTS) {
|
|
2132
|
+
channel.unbind(event);
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
var COLLABORATOR_COLORS = [
|
|
2136
|
+
"#3b82f6",
|
|
2137
|
+
"#ef4444",
|
|
2138
|
+
"#10b981",
|
|
2139
|
+
"#f59e0b",
|
|
2140
|
+
"#8b5cf6",
|
|
2141
|
+
"#ec4899",
|
|
2142
|
+
"#06b6d4",
|
|
2143
|
+
"#f97316",
|
|
2144
|
+
"#6366f1",
|
|
2145
|
+
"#14b8a6"
|
|
2146
|
+
];
|
|
2147
|
+
function useCollaboration(options) {
|
|
2148
|
+
const { authManager, editor, channel } = options;
|
|
2149
|
+
const collaborators = ref6([]);
|
|
2150
|
+
const lockedBlocks = ref6(/* @__PURE__ */ new Map());
|
|
2151
|
+
let colorIndex = 0;
|
|
2152
|
+
let isProcessingRemoteOperation = false;
|
|
2153
|
+
const myUserId = computed4(() => authManager.userConfig?.id ?? "");
|
|
2154
|
+
function assignColor() {
|
|
2155
|
+
const color = COLLABORATOR_COLORS[colorIndex % COLLABORATOR_COLORS.length];
|
|
2156
|
+
colorIndex++;
|
|
2157
|
+
return color;
|
|
2158
|
+
}
|
|
2159
|
+
function addCollaborator(member) {
|
|
2160
|
+
if (member.id === myUserId.value) {
|
|
2161
|
+
return void 0;
|
|
2162
|
+
}
|
|
2163
|
+
if (collaborators.value.some((c) => c.id === member.id)) {
|
|
2164
|
+
return void 0;
|
|
2165
|
+
}
|
|
2166
|
+
const collaborator = {
|
|
2167
|
+
id: member.id,
|
|
2168
|
+
name: member.name,
|
|
2169
|
+
color: assignColor(),
|
|
2170
|
+
selectedBlockId: null
|
|
2171
|
+
};
|
|
2172
|
+
collaborators.value = [...collaborators.value, collaborator];
|
|
2173
|
+
return collaborator;
|
|
2174
|
+
}
|
|
2175
|
+
function removeCollaborator(memberId) {
|
|
2176
|
+
const newLockedBlocks = new Map(lockedBlocks.value);
|
|
2177
|
+
for (const [blockId, collaborator] of newLockedBlocks) {
|
|
2178
|
+
if (collaborator.id === memberId) {
|
|
2179
|
+
newLockedBlocks.delete(blockId);
|
|
2180
|
+
}
|
|
2181
|
+
}
|
|
2182
|
+
lockedBlocks.value = newLockedBlocks;
|
|
2183
|
+
collaborators.value = collaborators.value.filter((c) => c.id !== memberId);
|
|
2184
|
+
}
|
|
2185
|
+
function handleBlockLocked(data) {
|
|
2186
|
+
const collaborator = collaborators.value.find((c) => c.id === data.userId);
|
|
2187
|
+
if (!collaborator) {
|
|
2188
|
+
return;
|
|
2189
|
+
}
|
|
2190
|
+
collaborators.value = collaborators.value.map(
|
|
2191
|
+
(c) => c.id === data.userId ? { ...c, selectedBlockId: data.blockId } : c
|
|
2192
|
+
);
|
|
2193
|
+
const newLockedBlocks = new Map(lockedBlocks.value);
|
|
2194
|
+
for (const [blockId, holder] of newLockedBlocks) {
|
|
2195
|
+
if (holder.id === data.userId) {
|
|
2196
|
+
newLockedBlocks.delete(blockId);
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
newLockedBlocks.set(data.blockId, {
|
|
2200
|
+
...collaborator,
|
|
2201
|
+
selectedBlockId: data.blockId
|
|
2202
|
+
});
|
|
2203
|
+
lockedBlocks.value = newLockedBlocks;
|
|
2204
|
+
if (editor.state.selectedBlockId === data.blockId) {
|
|
2205
|
+
editor.selectBlock(null);
|
|
2206
|
+
}
|
|
2207
|
+
}
|
|
2208
|
+
function handleBlockUnlocked(data) {
|
|
2209
|
+
const newLockedBlocks = new Map(lockedBlocks.value);
|
|
2210
|
+
const holder = newLockedBlocks.get(data.blockId);
|
|
2211
|
+
newLockedBlocks.delete(data.blockId);
|
|
2212
|
+
lockedBlocks.value = newLockedBlocks;
|
|
2213
|
+
if (holder) {
|
|
2214
|
+
collaborators.value = collaborators.value.map(
|
|
2215
|
+
(c) => c.id === holder.id ? { ...c, selectedBlockId: null } : c
|
|
2216
|
+
);
|
|
2217
|
+
}
|
|
2218
|
+
}
|
|
2219
|
+
function handleRemoteOperation(payload) {
|
|
2220
|
+
isProcessingRemoteOperation = true;
|
|
2221
|
+
try {
|
|
2222
|
+
handleOperation(editor, payload);
|
|
2223
|
+
} finally {
|
|
2224
|
+
isProcessingRemoteOperation = false;
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
function broadcastOperation(payload) {
|
|
2228
|
+
if (!channel.value || isProcessingRemoteOperation) {
|
|
2229
|
+
return;
|
|
2230
|
+
}
|
|
2231
|
+
channel.value.trigger("client-operation", payload);
|
|
2232
|
+
}
|
|
2233
|
+
function broadcastBlockLocked(blockId) {
|
|
2234
|
+
if (!channel.value) {
|
|
2235
|
+
return;
|
|
2236
|
+
}
|
|
2237
|
+
channel.value.trigger("client-block_locked", {
|
|
2238
|
+
blockId,
|
|
2239
|
+
userId: myUserId.value
|
|
2240
|
+
});
|
|
2241
|
+
}
|
|
2242
|
+
function broadcastBlockUnlocked(blockId) {
|
|
2243
|
+
if (!channel.value) {
|
|
2244
|
+
return;
|
|
2245
|
+
}
|
|
2246
|
+
channel.value.trigger("client-block_unlocked", { blockId });
|
|
2247
|
+
}
|
|
2248
|
+
watch2(
|
|
2249
|
+
() => editor.state.selectedBlockId,
|
|
2250
|
+
(newBlockId, oldBlockId) => {
|
|
2251
|
+
if (isProcessingRemoteOperation) {
|
|
2252
|
+
return;
|
|
2253
|
+
}
|
|
2254
|
+
if (oldBlockId) {
|
|
2255
|
+
broadcastBlockUnlocked(oldBlockId);
|
|
2256
|
+
}
|
|
2257
|
+
if (newBlockId) {
|
|
2258
|
+
broadcastBlockLocked(newBlockId);
|
|
2259
|
+
}
|
|
2260
|
+
}
|
|
2261
|
+
);
|
|
2262
|
+
watch2(channel, (newChannel, oldChannel) => {
|
|
2263
|
+
if (oldChannel) {
|
|
2264
|
+
unbindCollabEvents(oldChannel);
|
|
2265
|
+
}
|
|
2266
|
+
if (!newChannel) {
|
|
2267
|
+
collaborators.value = [];
|
|
2268
|
+
lockedBlocks.value = /* @__PURE__ */ new Map();
|
|
2269
|
+
colorIndex = 0;
|
|
2270
|
+
return;
|
|
2271
|
+
}
|
|
2272
|
+
const members = newChannel.members;
|
|
2273
|
+
if (members) {
|
|
2274
|
+
members.each((member) => {
|
|
2275
|
+
addCollaborator(member.info);
|
|
2276
|
+
});
|
|
2277
|
+
}
|
|
2278
|
+
newChannel.bind(
|
|
2279
|
+
"pusher:member_added",
|
|
2280
|
+
(member) => {
|
|
2281
|
+
const collaborator = addCollaborator(member.info);
|
|
2282
|
+
if (collaborator) {
|
|
2283
|
+
options.onCollaboratorJoined?.(collaborator);
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
);
|
|
2287
|
+
newChannel.bind(
|
|
2288
|
+
"pusher:member_removed",
|
|
2289
|
+
(member) => {
|
|
2290
|
+
const collaborator = collaborators.value.find(
|
|
2291
|
+
(c) => c.id === member.id
|
|
2292
|
+
);
|
|
2293
|
+
removeCollaborator(member.id);
|
|
2294
|
+
if (collaborator) {
|
|
2295
|
+
options.onCollaboratorLeft?.(collaborator);
|
|
2296
|
+
}
|
|
2297
|
+
}
|
|
2298
|
+
);
|
|
2299
|
+
newChannel.bind(
|
|
2300
|
+
"client-block_locked",
|
|
2301
|
+
(data) => {
|
|
2302
|
+
handleBlockLocked(data);
|
|
2303
|
+
const collaborator = collaborators.value.find(
|
|
2304
|
+
(c) => c.id === data.userId
|
|
2305
|
+
);
|
|
2306
|
+
if (collaborator) {
|
|
2307
|
+
options.onBlockLocked?.({
|
|
2308
|
+
blockId: data.blockId,
|
|
2309
|
+
collaborator
|
|
2310
|
+
});
|
|
2311
|
+
}
|
|
2312
|
+
}
|
|
2313
|
+
);
|
|
2314
|
+
newChannel.bind("client-block_unlocked", (data) => {
|
|
2315
|
+
const holder = lockedBlocks.value.get(data.blockId);
|
|
2316
|
+
handleBlockUnlocked(data);
|
|
2317
|
+
if (holder) {
|
|
2318
|
+
options.onBlockUnlocked?.({
|
|
2319
|
+
blockId: data.blockId,
|
|
2320
|
+
collaborator: holder
|
|
2321
|
+
});
|
|
2322
|
+
}
|
|
2323
|
+
});
|
|
2324
|
+
newChannel.bind("client-operation", (payload) => {
|
|
2325
|
+
handleRemoteOperation(payload);
|
|
2326
|
+
});
|
|
2327
|
+
newChannel.bind("mcp-operation", (payload) => {
|
|
2328
|
+
handleRemoteOperation(payload);
|
|
2329
|
+
});
|
|
2330
|
+
});
|
|
2331
|
+
onScopeDispose2(() => {
|
|
2332
|
+
if (channel.value) {
|
|
2333
|
+
unbindCollabEvents(channel.value);
|
|
2334
|
+
}
|
|
2335
|
+
});
|
|
2336
|
+
return {
|
|
2337
|
+
collaborators,
|
|
2338
|
+
lockedBlocks,
|
|
2339
|
+
_broadcastOperation: broadcastOperation,
|
|
2340
|
+
_isProcessingRemoteOperation: () => isProcessingRemoteOperation
|
|
2341
|
+
};
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
// src/cloud/collaboration-broadcast.ts
|
|
2345
|
+
function useCollaborationBroadcast(editor, collaboration) {
|
|
2346
|
+
const originalAddBlock = editor.addBlock;
|
|
2347
|
+
const originalUpdateBlock = editor.updateBlock;
|
|
2348
|
+
const originalRemoveBlock = editor.removeBlock;
|
|
2349
|
+
const originalMoveBlock = editor.moveBlock;
|
|
2350
|
+
const originalUpdateSettings = editor.updateSettings;
|
|
2351
|
+
const originalSetContent = editor.setContent;
|
|
2352
|
+
editor.addBlock = (block, targetSectionId, columnIndex) => {
|
|
2353
|
+
originalAddBlock(block, targetSectionId, columnIndex);
|
|
2354
|
+
collaboration._broadcastOperation({
|
|
2355
|
+
operation: "add_block",
|
|
2356
|
+
data: {
|
|
2357
|
+
block,
|
|
2358
|
+
section_id: targetSectionId,
|
|
2359
|
+
column_index: columnIndex
|
|
2360
|
+
},
|
|
2361
|
+
timestamp: Date.now()
|
|
2362
|
+
});
|
|
2363
|
+
};
|
|
2364
|
+
editor.updateBlock = (blockId, updates) => {
|
|
2365
|
+
originalUpdateBlock(blockId, updates);
|
|
2366
|
+
collaboration._broadcastOperation({
|
|
2367
|
+
operation: "update_block",
|
|
2368
|
+
data: { block_id: blockId, updates },
|
|
2369
|
+
timestamp: Date.now()
|
|
2370
|
+
});
|
|
2371
|
+
};
|
|
2372
|
+
editor.removeBlock = (blockId) => {
|
|
2373
|
+
originalRemoveBlock(blockId);
|
|
2374
|
+
collaboration._broadcastOperation({
|
|
2375
|
+
operation: "delete_block",
|
|
2376
|
+
data: { block_id: blockId },
|
|
2377
|
+
timestamp: Date.now()
|
|
2378
|
+
});
|
|
2379
|
+
};
|
|
2380
|
+
editor.moveBlock = (blockId, newIndex, targetSectionId, columnIndex) => {
|
|
2381
|
+
originalMoveBlock(blockId, newIndex, targetSectionId, columnIndex);
|
|
2382
|
+
collaboration._broadcastOperation({
|
|
2383
|
+
operation: "move_block",
|
|
2384
|
+
data: {
|
|
2385
|
+
block_id: blockId,
|
|
2386
|
+
index: newIndex,
|
|
2387
|
+
section_id: targetSectionId,
|
|
2388
|
+
column_index: columnIndex
|
|
2389
|
+
},
|
|
2390
|
+
timestamp: Date.now()
|
|
2391
|
+
});
|
|
2392
|
+
};
|
|
2393
|
+
editor.updateSettings = (updates) => {
|
|
2394
|
+
originalUpdateSettings(updates);
|
|
2395
|
+
collaboration._broadcastOperation({
|
|
2396
|
+
operation: "update_settings",
|
|
2397
|
+
data: { updates },
|
|
2398
|
+
timestamp: Date.now()
|
|
2399
|
+
});
|
|
2400
|
+
};
|
|
2401
|
+
editor.setContent = (content, markDirty) => {
|
|
2402
|
+
originalSetContent(content, markDirty);
|
|
2403
|
+
collaboration._broadcastOperation({
|
|
2404
|
+
operation: "set_content",
|
|
2405
|
+
data: { content },
|
|
2406
|
+
timestamp: Date.now()
|
|
2407
|
+
});
|
|
2408
|
+
};
|
|
2409
|
+
}
|
|
2410
|
+
|
|
2411
|
+
// src/cloud/web-socket.ts
|
|
2412
|
+
import { ref as ref7 } from "vue";
|
|
2413
|
+
function useWebSocket(options) {
|
|
2414
|
+
const { authManager, onError } = options;
|
|
2415
|
+
const channel = ref7(
|
|
2416
|
+
null
|
|
2417
|
+
);
|
|
2418
|
+
const isConnected = ref7(false);
|
|
2419
|
+
let wsClient = null;
|
|
2420
|
+
let channelName = null;
|
|
2421
|
+
async function connect(templateId, config) {
|
|
2422
|
+
if (wsClient) {
|
|
2423
|
+
return;
|
|
2424
|
+
}
|
|
2425
|
+
wsClient = new WebSocketClient({
|
|
2426
|
+
authManager,
|
|
2427
|
+
config,
|
|
2428
|
+
onError
|
|
2429
|
+
});
|
|
2430
|
+
await wsClient.connect();
|
|
2431
|
+
channelName = `presence-template.${templateId}`;
|
|
2432
|
+
const presenceChannel = wsClient.subscribePresence(channelName);
|
|
2433
|
+
presenceChannel.bind("pusher:subscription_succeeded", () => {
|
|
2434
|
+
isConnected.value = true;
|
|
2435
|
+
channel.value = presenceChannel;
|
|
2436
|
+
});
|
|
2437
|
+
presenceChannel.bind("pusher:subscription_error", (error) => {
|
|
2438
|
+
isConnected.value = false;
|
|
2439
|
+
channel.value = null;
|
|
2440
|
+
onError?.(
|
|
2441
|
+
error instanceof Error ? error : new Error("Failed to subscribe to template channel")
|
|
2442
|
+
);
|
|
2443
|
+
});
|
|
2444
|
+
}
|
|
2445
|
+
function disconnect() {
|
|
2446
|
+
if (channelName && wsClient) {
|
|
2447
|
+
wsClient.unsubscribe(channelName);
|
|
2448
|
+
}
|
|
2449
|
+
wsClient?.disconnect();
|
|
2450
|
+
wsClient = null;
|
|
2451
|
+
channelName = null;
|
|
2452
|
+
channel.value = null;
|
|
2453
|
+
isConnected.value = false;
|
|
2454
|
+
}
|
|
2455
|
+
function getSocketId() {
|
|
2456
|
+
return wsClient?.getSocketId() ?? null;
|
|
2457
|
+
}
|
|
2458
|
+
return {
|
|
2459
|
+
channel,
|
|
2460
|
+
isConnected,
|
|
2461
|
+
connect,
|
|
2462
|
+
disconnect,
|
|
2463
|
+
getSocketId
|
|
2464
|
+
};
|
|
2465
|
+
}
|
|
2466
|
+
|
|
2467
|
+
// src/cloud/saved-modules.ts
|
|
2468
|
+
import { ref as ref8 } from "vue";
|
|
2469
|
+
function useSavedModules(options) {
|
|
2470
|
+
const api = new ApiClient(options.authManager);
|
|
2471
|
+
const modules = ref8([]);
|
|
2472
|
+
const isLoading = ref8(false);
|
|
2473
|
+
async function loadModules(search) {
|
|
2474
|
+
isLoading.value = true;
|
|
2475
|
+
try {
|
|
2476
|
+
modules.value = await api.listModules(search);
|
|
2477
|
+
} catch (error) {
|
|
2478
|
+
options.onError?.(error);
|
|
2479
|
+
throw error;
|
|
2480
|
+
} finally {
|
|
2481
|
+
isLoading.value = false;
|
|
2482
|
+
}
|
|
2483
|
+
}
|
|
2484
|
+
async function createModule(name, content) {
|
|
2485
|
+
try {
|
|
2486
|
+
const module = await api.createModule({ name, content });
|
|
2487
|
+
modules.value = [module, ...modules.value];
|
|
2488
|
+
return module;
|
|
2489
|
+
} catch (error) {
|
|
2490
|
+
options.onError?.(error);
|
|
2491
|
+
throw error;
|
|
2492
|
+
}
|
|
2493
|
+
}
|
|
2494
|
+
async function updateModule(id, data) {
|
|
2495
|
+
try {
|
|
2496
|
+
const updated = await api.updateModule(id, data);
|
|
2497
|
+
modules.value = modules.value.map((m) => m.id === id ? updated : m);
|
|
2498
|
+
return updated;
|
|
2499
|
+
} catch (error) {
|
|
2500
|
+
options.onError?.(error);
|
|
2501
|
+
throw error;
|
|
2502
|
+
}
|
|
2503
|
+
}
|
|
2504
|
+
async function deleteModule(id) {
|
|
2505
|
+
try {
|
|
2506
|
+
await api.deleteModule(id);
|
|
2507
|
+
modules.value = modules.value.filter((m) => m.id !== id);
|
|
2508
|
+
} catch (error) {
|
|
2509
|
+
options.onError?.(error);
|
|
2510
|
+
throw error;
|
|
2511
|
+
}
|
|
2512
|
+
}
|
|
2513
|
+
return {
|
|
2514
|
+
modules,
|
|
2515
|
+
isLoading,
|
|
2516
|
+
loadModules,
|
|
2517
|
+
createModule,
|
|
2518
|
+
updateModule,
|
|
2519
|
+
deleteModule
|
|
2520
|
+
};
|
|
2521
|
+
}
|
|
2522
|
+
|
|
2523
|
+
// src/cloud/snapshots.ts
|
|
2524
|
+
import { ref as ref9 } from "vue";
|
|
2525
|
+
function useSnapshotHistory(options) {
|
|
2526
|
+
const api = new ApiClient(options.authManager);
|
|
2527
|
+
const snapshots = ref9([]);
|
|
2528
|
+
const isLoading = ref9(false);
|
|
2529
|
+
const isRestoring = ref9(false);
|
|
2530
|
+
async function loadSnapshots() {
|
|
2531
|
+
isLoading.value = true;
|
|
2532
|
+
try {
|
|
2533
|
+
snapshots.value = await api.getSnapshots(options.templateId);
|
|
2534
|
+
} catch (error) {
|
|
2535
|
+
options.onError?.(error);
|
|
2536
|
+
throw error;
|
|
2537
|
+
} finally {
|
|
2538
|
+
isLoading.value = false;
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
async function restoreSnapshot(snapshotId) {
|
|
2542
|
+
isRestoring.value = true;
|
|
2543
|
+
try {
|
|
2544
|
+
const template = await api.restoreSnapshot(
|
|
2545
|
+
options.templateId,
|
|
2546
|
+
snapshotId
|
|
2547
|
+
);
|
|
2548
|
+
options.onRestore?.(template);
|
|
2549
|
+
return template;
|
|
2550
|
+
} catch (error) {
|
|
2551
|
+
options.onError?.(error);
|
|
2552
|
+
throw error;
|
|
2553
|
+
} finally {
|
|
2554
|
+
isRestoring.value = false;
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
return {
|
|
2558
|
+
snapshots,
|
|
2559
|
+
isLoading,
|
|
2560
|
+
isRestoring,
|
|
2561
|
+
loadSnapshots,
|
|
2562
|
+
restoreSnapshot
|
|
2563
|
+
};
|
|
2564
|
+
}
|
|
2565
|
+
|
|
2566
|
+
// src/cloud/test-email.ts
|
|
2567
|
+
import { computed as computed5, ref as ref10, watch as watch3 } from "vue";
|
|
2568
|
+
function useTestEmail(options) {
|
|
2569
|
+
const {
|
|
2570
|
+
authManager,
|
|
2571
|
+
getTemplateId,
|
|
2572
|
+
save,
|
|
2573
|
+
exportHtml,
|
|
2574
|
+
onError,
|
|
2575
|
+
isAuthReady,
|
|
2576
|
+
onBeforeTestEmail
|
|
2577
|
+
} = options;
|
|
2578
|
+
const api = new ApiClient(authManager);
|
|
2579
|
+
const isSending = ref10(false);
|
|
2580
|
+
const error = ref10(null);
|
|
2581
|
+
const testEmailConfig = ref10(null);
|
|
2582
|
+
if (isAuthReady) {
|
|
2583
|
+
watch3(
|
|
2584
|
+
isAuthReady,
|
|
2585
|
+
(ready) => {
|
|
2586
|
+
if (ready) {
|
|
2587
|
+
testEmailConfig.value = authManager.testEmailConfig;
|
|
2588
|
+
}
|
|
2589
|
+
},
|
|
2590
|
+
{ immediate: true }
|
|
2591
|
+
);
|
|
2592
|
+
}
|
|
2593
|
+
const isEnabled = computed5(() => testEmailConfig.value !== null);
|
|
2594
|
+
const allowedEmails = computed5(
|
|
2595
|
+
() => testEmailConfig.value?.allowedEmails ?? []
|
|
2596
|
+
);
|
|
2597
|
+
async function sendTestEmail(recipient) {
|
|
2598
|
+
if (!testEmailConfig.value) {
|
|
2599
|
+
throw new Error("Test email is not enabled for this project");
|
|
2600
|
+
}
|
|
2601
|
+
const templateId = getTemplateId();
|
|
2602
|
+
if (!templateId) {
|
|
2603
|
+
throw new Error("Template must be saved before sending a test email");
|
|
2604
|
+
}
|
|
2605
|
+
isSending.value = true;
|
|
2606
|
+
error.value = null;
|
|
2607
|
+
try {
|
|
2608
|
+
await save();
|
|
2609
|
+
let { html } = await exportHtml(templateId);
|
|
2610
|
+
if (onBeforeTestEmail) {
|
|
2611
|
+
html = await onBeforeTestEmail(html);
|
|
2612
|
+
}
|
|
2613
|
+
await api.sendTestEmail(templateId, {
|
|
2614
|
+
recipient,
|
|
2615
|
+
html,
|
|
2616
|
+
allowed_emails: testEmailConfig.value.allowedEmails,
|
|
2617
|
+
signature: testEmailConfig.value.signature
|
|
2618
|
+
});
|
|
2619
|
+
} catch (err) {
|
|
2620
|
+
const wrappedError = err instanceof Error ? err : new Error("Failed to send test email", { cause: err });
|
|
2621
|
+
error.value = wrappedError.message;
|
|
2622
|
+
onError?.(wrappedError);
|
|
2623
|
+
throw wrappedError;
|
|
2624
|
+
} finally {
|
|
2625
|
+
isSending.value = false;
|
|
2626
|
+
}
|
|
2627
|
+
}
|
|
2628
|
+
return {
|
|
2629
|
+
isEnabled,
|
|
2630
|
+
allowedEmails,
|
|
2631
|
+
isSending,
|
|
2632
|
+
error,
|
|
2633
|
+
sendTestEmail
|
|
2634
|
+
};
|
|
2635
|
+
}
|
|
2636
|
+
|
|
2637
|
+
// src/cloud/export.ts
|
|
2638
|
+
function useExport(options) {
|
|
2639
|
+
const { authManager, getFontsConfig, canUseCustomFonts } = options;
|
|
2640
|
+
const api = new ApiClient(authManager);
|
|
2641
|
+
function getExportFontsPayload() {
|
|
2642
|
+
const fontsConfig = getFontsConfig?.();
|
|
2643
|
+
const customFontsAllowed = canUseCustomFonts?.() ?? true;
|
|
2644
|
+
return {
|
|
2645
|
+
customFonts: customFontsAllowed && fontsConfig?.customFonts ? fontsConfig.customFonts : [],
|
|
2646
|
+
defaultFallback: fontsConfig?.defaultFallback ?? "Arial, sans-serif"
|
|
2647
|
+
};
|
|
2648
|
+
}
|
|
2649
|
+
async function exportHtml(templateId) {
|
|
2650
|
+
const fontsPayload = getExportFontsPayload();
|
|
2651
|
+
const result = await api.exportTemplate(templateId, fontsPayload);
|
|
2652
|
+
return {
|
|
2653
|
+
html: result.html,
|
|
2654
|
+
mjml: result.mjml
|
|
2655
|
+
};
|
|
2656
|
+
}
|
|
2657
|
+
async function getMjmlSource(templateId) {
|
|
2658
|
+
const fontsPayload = getExportFontsPayload();
|
|
2659
|
+
const result = await api.exportTemplate(templateId, fontsPayload);
|
|
2660
|
+
return result.mjml;
|
|
2661
|
+
}
|
|
2662
|
+
return {
|
|
2663
|
+
exportHtml,
|
|
2664
|
+
getMjmlSource
|
|
2665
|
+
};
|
|
2666
|
+
}
|
|
2667
|
+
|
|
2668
|
+
// src/cloud/plan-config.ts
|
|
2669
|
+
import { computed as computed6, ref as ref11 } from "vue";
|
|
2670
|
+
function usePlanConfig(options) {
|
|
2671
|
+
const { authManager, onError } = options;
|
|
2672
|
+
const config = ref11(null);
|
|
2673
|
+
const isLoading = ref11(false);
|
|
2674
|
+
const apiClient = new ApiClient(authManager);
|
|
2675
|
+
const features = computed6(() => config.value?.features ?? null);
|
|
2676
|
+
function hasFeature(feature) {
|
|
2677
|
+
return config.value?.features[feature] ?? false;
|
|
2678
|
+
}
|
|
2679
|
+
async function fetchConfig() {
|
|
2680
|
+
if (isLoading.value) {
|
|
2681
|
+
return;
|
|
2682
|
+
}
|
|
2683
|
+
isLoading.value = true;
|
|
2684
|
+
try {
|
|
2685
|
+
config.value = await apiClient.fetchConfig();
|
|
2686
|
+
} catch (error) {
|
|
2687
|
+
onError?.(
|
|
2688
|
+
error instanceof Error ? error : new Error("Failed to fetch config", { cause: error })
|
|
2689
|
+
);
|
|
2690
|
+
} finally {
|
|
2691
|
+
isLoading.value = false;
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
return {
|
|
2695
|
+
config,
|
|
2696
|
+
isLoading,
|
|
2697
|
+
hasFeature,
|
|
2698
|
+
features,
|
|
2699
|
+
fetchConfig
|
|
2700
|
+
};
|
|
2701
|
+
}
|
|
2702
|
+
|
|
2703
|
+
// src/cloud/health-check.ts
|
|
2704
|
+
var WS_HANDSHAKE_TIMEOUT = 5e3;
|
|
2705
|
+
function resolveHealthUrl(options) {
|
|
2706
|
+
if (options.authManager) {
|
|
2707
|
+
return options.authManager.resolveUrl(API_ROUTES.health);
|
|
2708
|
+
}
|
|
2709
|
+
const base = (options.baseUrl ?? "https://templatical.com").replace(
|
|
2710
|
+
/\/$/,
|
|
2711
|
+
""
|
|
2712
|
+
);
|
|
2713
|
+
return `${base}${API_ROUTES.health}`;
|
|
2714
|
+
}
|
|
2715
|
+
async function checkApiAndAuth(url, authManager) {
|
|
2716
|
+
const start = performance.now();
|
|
2717
|
+
try {
|
|
2718
|
+
const response = authManager ? await authManager.authenticatedFetch(API_ROUTES.health, {
|
|
2719
|
+
method: "GET",
|
|
2720
|
+
headers: { Accept: "application/json" }
|
|
2721
|
+
}) : await fetch(url, {
|
|
2722
|
+
method: "GET",
|
|
2723
|
+
headers: { Accept: "application/json" }
|
|
2724
|
+
});
|
|
2725
|
+
const latency = Math.round(performance.now() - start);
|
|
2726
|
+
if (response.status === 401) {
|
|
2727
|
+
return {
|
|
2728
|
+
api: { ok: true, latency },
|
|
2729
|
+
auth: { ok: false, error: "HTTP 401" }
|
|
2730
|
+
};
|
|
2731
|
+
}
|
|
2732
|
+
if (!response.ok) {
|
|
2733
|
+
return {
|
|
2734
|
+
api: { ok: false, latency },
|
|
2735
|
+
auth: {
|
|
2736
|
+
ok: !authManager,
|
|
2737
|
+
error: authManager ? `HTTP ${response.status}` : void 0
|
|
2738
|
+
}
|
|
2739
|
+
};
|
|
2740
|
+
}
|
|
2741
|
+
const data = await response.json();
|
|
2742
|
+
return {
|
|
2743
|
+
api: { ok: data.status === "ok", latency },
|
|
2744
|
+
auth: { ok: true },
|
|
2745
|
+
wsConfig: data.websocket
|
|
2746
|
+
};
|
|
2747
|
+
} catch (error) {
|
|
2748
|
+
const latency = Math.round(performance.now() - start);
|
|
2749
|
+
return {
|
|
2750
|
+
api: { ok: false, latency },
|
|
2751
|
+
auth: {
|
|
2752
|
+
ok: !authManager,
|
|
2753
|
+
error: authManager ? error instanceof Error ? error.message : "Authentication check failed" : void 0
|
|
2754
|
+
}
|
|
2755
|
+
};
|
|
2756
|
+
}
|
|
2757
|
+
}
|
|
2758
|
+
async function checkWebSocket(wsConfig) {
|
|
2759
|
+
if (!wsConfig?.host || !wsConfig?.app_key) {
|
|
2760
|
+
return { ok: false, error: "WebSocket configuration not available" };
|
|
2761
|
+
}
|
|
2762
|
+
if (typeof WebSocket === "undefined") {
|
|
2763
|
+
return {
|
|
2764
|
+
ok: false,
|
|
2765
|
+
error: "WebSocket not supported in this environment"
|
|
2766
|
+
};
|
|
2767
|
+
}
|
|
2768
|
+
const protocol = wsConfig.port === 443 ? "wss" : "ws";
|
|
2769
|
+
const url = `${protocol}://${wsConfig.host}:${wsConfig.port}/app/${wsConfig.app_key}?protocol=7&client=js&version=8.4.0-rc2&flash=false`;
|
|
2770
|
+
return new Promise((resolve) => {
|
|
2771
|
+
let ws = null;
|
|
2772
|
+
const timeout = setTimeout(() => {
|
|
2773
|
+
ws?.close();
|
|
2774
|
+
resolve({ ok: false, error: "WebSocket connection timed out" });
|
|
2775
|
+
}, WS_HANDSHAKE_TIMEOUT);
|
|
2776
|
+
try {
|
|
2777
|
+
ws = new WebSocket(url);
|
|
2778
|
+
} catch (error) {
|
|
2779
|
+
clearTimeout(timeout);
|
|
2780
|
+
resolve({
|
|
2781
|
+
ok: false,
|
|
2782
|
+
error: error instanceof Error ? error.message : "WebSocket connection failed"
|
|
2783
|
+
});
|
|
2784
|
+
return;
|
|
2785
|
+
}
|
|
2786
|
+
ws.onopen = () => {
|
|
2787
|
+
clearTimeout(timeout);
|
|
2788
|
+
ws?.close();
|
|
2789
|
+
resolve({ ok: true });
|
|
2790
|
+
};
|
|
2791
|
+
ws.onerror = () => {
|
|
2792
|
+
clearTimeout(timeout);
|
|
2793
|
+
resolve({ ok: false, error: "WebSocket connection failed" });
|
|
2794
|
+
};
|
|
2795
|
+
});
|
|
2796
|
+
}
|
|
2797
|
+
async function performHealthCheck(options = {}) {
|
|
2798
|
+
const healthUrl = resolveHealthUrl(options);
|
|
2799
|
+
const result = await checkApiAndAuth(healthUrl, options.authManager);
|
|
2800
|
+
const wsResult = await checkWebSocket(result.wsConfig);
|
|
2801
|
+
return {
|
|
2802
|
+
api: result.api,
|
|
2803
|
+
websocket: wsResult,
|
|
2804
|
+
auth: result.auth,
|
|
2805
|
+
overall: result.api.ok && result.auth.ok
|
|
2806
|
+
};
|
|
2807
|
+
}
|
|
2808
|
+
|
|
2809
|
+
// src/cloud/mcp-listener.ts
|
|
2810
|
+
import { watch as watch4 } from "vue";
|
|
2811
|
+
function useMcpListener(options) {
|
|
2812
|
+
const { editor, channel, onOperation } = options;
|
|
2813
|
+
watch4(channel, (newChannel, oldChannel) => {
|
|
2814
|
+
if (oldChannel) {
|
|
2815
|
+
oldChannel.unbind("mcp-operation");
|
|
2816
|
+
}
|
|
2817
|
+
if (newChannel) {
|
|
2818
|
+
newChannel.bind("mcp-operation", (payload) => {
|
|
2819
|
+
handleOperation(editor, payload);
|
|
2820
|
+
onOperation?.(payload);
|
|
2821
|
+
});
|
|
2822
|
+
}
|
|
2823
|
+
});
|
|
2824
|
+
}
|
|
2825
|
+
export {
|
|
2826
|
+
API_ROUTES,
|
|
2827
|
+
ApiClient,
|
|
2828
|
+
AuthManager,
|
|
2829
|
+
WebSocketClient,
|
|
2830
|
+
buildUrl,
|
|
2831
|
+
createSdkAuthManager,
|
|
2832
|
+
handleOperation,
|
|
2833
|
+
performHealthCheck,
|
|
2834
|
+
resolveWebSocketConfig,
|
|
2835
|
+
useAiChat,
|
|
2836
|
+
useAiConfig,
|
|
2837
|
+
useAiRewrite,
|
|
2838
|
+
useCollaboration,
|
|
2839
|
+
useCollaborationBroadcast,
|
|
2840
|
+
useCommentListener,
|
|
2841
|
+
useComments,
|
|
2842
|
+
useDesignReference,
|
|
2843
|
+
useEditor,
|
|
2844
|
+
useExport,
|
|
2845
|
+
useMcpListener,
|
|
2846
|
+
usePlanConfig,
|
|
2847
|
+
useSavedModules,
|
|
2848
|
+
useSnapshotHistory,
|
|
2849
|
+
useTemplateScoring,
|
|
2850
|
+
useTestEmail,
|
|
2851
|
+
useWebSocket
|
|
2852
|
+
};
|
|
2853
|
+
//# sourceMappingURL=index.js.map
|