@commentkit/comment-kit 0.7.7 → 1.0.0-beta.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.
Files changed (109) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +108 -762
  3. package/SECURITY.md +19 -14
  4. package/dist/npm/THIRD_PARTY_NOTICES.txt +73 -0
  5. package/dist/npm/chunks/anchor-DT-Ynhh1.js +270 -0
  6. package/dist/npm/chunks/client-D1vrh_5G.js +590 -0
  7. package/dist/{shared/capture-colors-D0uLr-vZ.js → npm/chunks/colors-CX-IPjvb.js} +2 -0
  8. package/dist/npm/chunks/html2canvas-_mjSRP3G.js +4011 -0
  9. package/dist/npm/chunks/mount-Ce1MZrcm.js +2485 -0
  10. package/dist/{shared/pusher-CnhQgAvF.js → npm/chunks/pusher-DRKlokR8.js} +224 -222
  11. package/dist/npm/chunks/realtime-5SvAvTUU.js +23 -0
  12. package/dist/npm/chunks/rolldown-runtime-VHNaYcLd.js +13 -0
  13. package/dist/npm/chunks/src-DJjfvVsa.js +330 -0
  14. package/dist/npm/element.js +24 -0
  15. package/dist/npm/headless.js +3 -0
  16. package/dist/npm/index.js +3 -0
  17. package/dist/npm/react.js +17 -0
  18. package/dist/npm/svelte.js +8 -0
  19. package/dist/npm/types/adapters/react.d.ts +9 -0
  20. package/dist/npm/types/adapters/svelte.d.ts +9 -0
  21. package/dist/npm/types/adapters/vue.d.ts +46 -0
  22. package/dist/npm/types/anchor/index.d.ts +49 -0
  23. package/dist/npm/types/core/api.d.ts +29 -0
  24. package/dist/npm/types/core/auth.d.ts +48 -0
  25. package/dist/npm/types/core/client.d.ts +100 -0
  26. package/dist/npm/types/core/store.d.ts +7 -0
  27. package/dist/npm/types/core/types.d.ts +278 -0
  28. package/dist/npm/types/element.d.ts +10 -0
  29. package/dist/npm/types/headless.d.ts +7 -0
  30. package/dist/npm/types/index.d.ts +30 -0
  31. package/dist/npm/vue.js +32 -0
  32. package/package.json +65 -173
  33. package/dist/THIRD_PARTY_NOTICES.txt +0 -284
  34. package/dist/angular.es.js +0 -321
  35. package/dist/comment-kit.es.js +0 -218
  36. package/dist/demo.es.js +0 -483
  37. package/dist/headless.es.js +0 -4
  38. package/dist/preact.es.js +0 -117
  39. package/dist/qwik.es.js +0 -1
  40. package/dist/qwik.qwik.mjs +0 -114
  41. package/dist/react.es.js +0 -98
  42. package/dist/shared/ShadowRootContext-DD6a0QaI.js +0 -11
  43. package/dist/shared/annotation-icons-Dh-bmNYK.js +0 -172
  44. package/dist/shared/annotation-toolbar-zeiCmKIr.js +0 -1086
  45. package/dist/shared/attachment-refresh-DAacLaRu.js +0 -94
  46. package/dist/shared/bridge-CJoGYngu.js +0 -177
  47. package/dist/shared/button-D4GHW6oZ.js +0 -474
  48. package/dist/shared/button-group-BVR7iT-S.js +0 -91
  49. package/dist/shared/capture-privacy-CiOrcAlt.js +0 -101
  50. package/dist/shared/comment-drawing-canvas-Btc12IsS.js +0 -124
  51. package/dist/shared/comment-icon-D8JTCEJ7.js +0 -607
  52. package/dist/shared/comment-image-lightbox--QpbcAtH.js +0 -190
  53. package/dist/shared/comment-images-content-C_r4SHM-.js +0 -214
  54. package/dist/shared/comment-kit-core-CmLUFujd.js +0 -3682
  55. package/dist/shared/comment-kit-ui-BHwYuSIi.js +0 -19391
  56. package/dist/shared/comment-screenshot-annotator-zJZyO-XM.js +0 -151
  57. package/dist/shared/comment-screenshot-overlay-CoKTYB0J.js +0 -205
  58. package/dist/shared/comment-shortcut-groups-CfEmkitU.js +0 -153
  59. package/dist/shared/createReactComponent-BZHeRbD0.js +0 -45
  60. package/dist/shared/dev-export-panel-Cnt6oCZU.js +0 -207
  61. package/dist/shared/dev-grab-B85jo9AS.js +0 -197
  62. package/dist/shared/dist-D9A5k-N4.js +0 -617
  63. package/dist/shared/dom-Bhf4WFtY.js +0 -223
  64. package/dist/shared/element-selector-Cng84xC7.js +0 -902
  65. package/dist/shared/error-boundary-D3PD74vI.js +0 -21
  66. package/dist/shared/errors-Bu5ajEmB.js +0 -22
  67. package/dist/shared/icons-nzMOLzrm.js +0 -266
  68. package/dist/shared/input-UPtAj0M6.js +0 -111
  69. package/dist/shared/mount-ui-Dz7FB_Ak.js +0 -208
  70. package/dist/shared/realtime-recovery-BjlV-ewc.js +0 -162
  71. package/dist/shared/realtime-yGLX4wMK.js +0 -334
  72. package/dist/shared/request-activity-DQrAUwfA.js +0 -11
  73. package/dist/shared/screenshot-B5-hwpmt.js +0 -199
  74. package/dist/shared/separator-UhJb0Row.js +0 -3955
  75. package/dist/shared/shadow-root-B58ZI2yz.js +0 -133
  76. package/dist/shared/styles-CnYsLS2f.js +0 -2
  77. package/dist/shared/text-B4HHZNaa.js +0 -23
  78. package/dist/shared/token-session-D92MYbNu.js +0 -25
  79. package/dist/shared/useLabelableId-8n0QmH8N.js +0 -154
  80. package/dist/shared/useRender-Uxk1OPK-.js +0 -5
  81. package/dist/shared/useValueChanged-DKq5cMot.js +0 -92
  82. package/dist/shared/validation-3wbbbuX0.js +0 -70
  83. package/dist/shared/websocket-manager-KhH4hL0Q.js +0 -381
  84. package/dist/solid.es.js +0 -98
  85. package/dist/svelte.es.js +0 -130
  86. package/dist/types/adapters/bridge.d.ts +0 -122
  87. package/dist/types/angular/index.d.ts +0 -145
  88. package/dist/types/core/agent-context.d.ts +0 -17
  89. package/dist/types/core/api-client.d.ts +0 -155
  90. package/dist/types/core/comment-kit-core.d.ts +0 -254
  91. package/dist/types/core/local-demo.d.ts +0 -60
  92. package/dist/types/core/types.d.ts +0 -770
  93. package/dist/types/core/websocket-manager.d.ts +0 -125
  94. package/dist/types/core/write-access.d.ts +0 -11
  95. package/dist/types/demo.d.ts +0 -17
  96. package/dist/types/headless.d.ts +0 -8
  97. package/dist/types/index.d.ts +0 -87
  98. package/dist/types/preact/index.d.ts +0 -25
  99. package/dist/types/qwik/index.d.ts +0 -73
  100. package/dist/types/react/client.d.ts +0 -31
  101. package/dist/types/react/index.d.ts +0 -4
  102. package/dist/types/solid/index.d.ts +0 -37
  103. package/dist/types/svelte/index.d.ts +0 -55
  104. package/dist/types/utils/dom.d.ts +0 -59
  105. package/dist/types/utils/event-emitter.d.ts +0 -11
  106. package/dist/types/vue/index.d.ts +0 -87
  107. package/dist/vue.es.js +0 -148
  108. package/docs/api-reference.md +0 -405
  109. package/docs/local-demo.md +0 -60
@@ -1,3682 +0,0 @@
1
- import { a as e, c as t, d as n, f as r, l as i, n as a, o, p as s, r as c, s as l, t as u, u as d } from "./validation-3wbbbuX0.js";
2
- import { t as f } from "./request-activity-DQrAUwfA.js";
3
- import { n as p, o as m } from "./dom-Bhf4WFtY.js";
4
- import { n as h, t as g } from "./capture-privacy-CiOrcAlt.js";
5
- import { a as _, n as v, r as y, t as ee } from "./text-B4HHZNaa.js";
6
- var b = "https://api.commentkit.dev/api", te = 3e4, ne = 10485760, re = 10, ie = 1e4, ae = 5e3, oe = 254, se = 6, ce = 4096, le = [
7
- ".png",
8
- ".jpg",
9
- ".jpeg",
10
- ".gif",
11
- ".webp"
12
- ], ue = [
13
- "image/png",
14
- "image/jpeg",
15
- "image/gif",
16
- "image/webp"
17
- ], de = /@\[([^\]]+)\]\(([^)]+)\)/g, x = {
18
- invalid_api_key: "Authentication failed. Please check your API key.",
19
- missing_api_key: "Authentication failed. Please check your API key.",
20
- origin_not_allowed: "This domain is not allowed to use this project's API key.",
21
- invalid_email: "A valid email address is required.",
22
- invalid_otp: "A valid OTP code is required.",
23
- invalid_token: "A valid invite token is required.",
24
- network_error: "Unable to connect to servers. Please check your connection.",
25
- timeout: "Request timed out. Please try again.",
26
- rate_limit: "Too many requests. Please wait before trying again.",
27
- unauthorized: "You are not authorized to perform this action.",
28
- not_found: "The requested resource was not found.",
29
- validation_error: "Invalid input. Please check your data.",
30
- invalid_response: "Invalid server response.",
31
- auth_failed: "Sign-in failed. Please check your email and try again.",
32
- otp_cooldown: "A code was sent recently — please wait a minute before requesting another.",
33
- otp_not_found: "No verification code found. Request a new one.",
34
- mfa_invalid: "Incorrect authenticator or recovery code. Try again.",
35
- mfa_expired: "This sign-in attempt expired. Start again with your email.",
36
- mfa_max_attempts: "Too many incorrect codes. Start again with your email.",
37
- otp_expired: "That verification code has expired. Request a new one.",
38
- otp_max_attempts: "Too many incorrect attempts. Request a new code.",
39
- otp_invalid: "Incorrect verification code. Please try again.",
40
- invalid_invite: "This invite link is invalid or has expired.",
41
- email_mismatch: "This invite was issued for a different email address.",
42
- quota_exceeded: "This project has reached its plan limit."
43
- };
44
- function fe(e, t) {
45
- let n = {};
46
- return e.content !== void 0 && (n.content = e.content), e.status !== void 0 && (n.status = e.status), e.priority !== void 0 && (n.priority = e.priority), e.description !== void 0 && (n.description = e.description), e.assignees !== void 0 && (n.assignees = e.assignees.map((e) => e.id)), e.checklistPatch !== void 0 && (n.checklist_patch = e.checklistPatch), e.checklist !== void 0 && (n.checklist = e.checklist.map((e) => ({
47
- ...e,
48
- id: /^\d+$/.test(e.id) ? Number(e.id) : null
49
- }))), e.textSelection !== void 0 && (n.text_selection = e.textSelection), e.drawingData !== void 0 && (n.drawing_data = e.drawingData), e.attachmentIds !== void 0 && (n.attachment_ids = e.attachmentIds.map((e) => typeof e == "number" ? e : Number(e)).filter((e) => Number.isInteger(e) && e > 0).slice(0, 20)), t && t.length > 0 && (n.mentions = t), n;
50
- }
51
- function pe(e) {
52
- return e === "localhost" || e === "127.0.0.1" || e === "[::1]" || e.endsWith(".localhost");
53
- }
54
- function me(e) {
55
- let t = (e || b).trim().replace(/\/+$/, "");
56
- try {
57
- let e = new URL(t);
58
- if (e.username || e.password || e.search || e.hash || a(t)) throw Error("ambiguous endpoint");
59
- if (e.protocol !== "https:" && e.protocol !== "http:") throw Error("unsupported protocol");
60
- if (e.protocol === "http:" && !pe(e.hostname)) throw Error("insecure protocol");
61
- } catch {
62
- throw new E("invalid_base_url", "Invalid API base URL", 400);
63
- }
64
- return t;
65
- }
66
- function S(e) {
67
- let t = String(e).trim();
68
- if (!t || a(t)) throw new E("invalid_id", "Invalid identifier", 400);
69
- return encodeURIComponent(t);
70
- }
71
- function C(e) {
72
- if (typeof e != "string" || a(e)) throw new E("invalid_email", "A valid email address is required", 400);
73
- let t = e.trim();
74
- if (!s(t, oe)) throw new E("invalid_email", "A valid email address is required", 400);
75
- return t;
76
- }
77
- function he(e) {
78
- if (a(e)) throw new E("invalid_otp", "A valid OTP code is required", 400);
79
- let t = e.trim();
80
- if (t.length !== se || /\s/.test(t)) throw new E("invalid_otp", "A valid OTP code is required", 400);
81
- return t;
82
- }
83
- function ge(e) {
84
- if (a(e)) throw new E("invalid_token", "A valid invite token is required", 400);
85
- let t = e.trim();
86
- if (t.length !== 64 || !/^[\w-]+$/.test(t)) throw new E("invalid_token", "A valid invite token is required", 400);
87
- return t;
88
- }
89
- function w(e, t, n = ie) {
90
- let r = e.trim();
91
- if (!r) throw new E("invalid_content", `${t} cannot be empty`, 400);
92
- if (r.length > n) throw new E("content_too_long", `${t} exceeds maximum length of ${n} characters`, 400);
93
- return r;
94
- }
95
- function _e(e, t) {
96
- let n = {};
97
- for (let [t, r] of Object.entries(o(e) ? e : {}).slice(0, 20)) /^[\w.-]{1,64}$/.test(t) && t !== "__proto__" && t !== "constructor" && t !== "prototype" && (typeof r == "string" ? n[t] = r.slice(0, 200) : typeof r == "number" || typeof r == "boolean" || r === null ? n[t] = r : Array.isArray(r) && (n[t] = r.filter((e) => typeof e == "string" || typeof e == "number" || typeof e == "boolean" || e === null).slice(0, 10).map((e) => typeof e == "string" ? e.slice(0, 200) : e)));
98
- if (o(t)) {
99
- let e = {};
100
- for (let n of [
101
- "type",
102
- "feature",
103
- "plan",
104
- "reason"
105
- ]) typeof t[n] == "string" && (e[n] = t[n].slice(0, 64));
106
- for (let n of ["current", "limit"]) typeof t[n] == "number" && Number.isFinite(t[n]) && (e[n] = t[n]);
107
- Object.keys(e).length && (n.quota = e);
108
- }
109
- return Object.keys(n).length > 0 ? n : void 0;
110
- }
111
- var ve = class {
112
- constructor(e) {
113
- this.projectId = null, this.channelProjectId = null, this.userEmail = null, this.authToken = null, this.authRevision = 0, this.pendingInvite = null, this.inviteRevision = 0, this.environment = null, this.onAuthExpired = null, this.baseUrl = me(e.baseUrl), this.apiKey = e.apiKey, this.projectId = e.projectId || null, this.channelProjectId = this.projectId, this.environment = e.environment || null;
114
- }
115
- setProject(e, t = e) {
116
- this.projectId !== String(e).trim() && (this.pendingInvite = null, this.inviteRevision++), this.projectId = String(e).trim(), this.channelProjectId = String(t).trim();
117
- }
118
- setUserEmail(e) {
119
- this.userEmail = e ? C(e) : null;
120
- }
121
- setAuthToken(e) {
122
- if (e && (a(e) || e.length > ce)) throw new E("invalid_token", "A valid auth token is required", 400);
123
- let t = e?.trim() || null;
124
- this.authToken = t, this.pendingInvite = null, this.inviteRevision++, this.authRevision++;
125
- }
126
- setEnvironment(e) {
127
- this.environment = e;
128
- }
129
- setOnAuthExpired(e) {
130
- this.onAuthExpired = e;
131
- }
132
- buildHeaders(e) {
133
- if (typeof this.apiKey != "string" || a(this.apiKey)) throw new E("invalid_api_key", "Authentication failed. Please check your API key.", 401);
134
- return {
135
- "X-API-Key": this.apiKey,
136
- ...this.userEmail ? { "X-User-Email": this.userEmail } : {},
137
- ...this.authToken ? { Authorization: `Bearer ${this.authToken}` } : {},
138
- ...e
139
- };
140
- }
141
- async executeRequest(e, t, n, r) {
142
- let i = this.authRevision, a = this.authToken, s = t.method && t.method !== "GET" ? f(this) : null, c = new AbortController(), l = setTimeout(() => c.abort(), te);
143
- try {
144
- let s = await fetch(e, {
145
- ...t,
146
- credentials: "omit",
147
- redirect: "manual",
148
- referrerPolicy: "no-referrer",
149
- signal: c.signal
150
- });
151
- if (s.type === "opaqueredirect" || s.status >= 300 && s.status < 400) throw new E("unexpected_redirect", "The API endpoint redirected. Check the configured API URL before retrying.", 400);
152
- let l = await this.parseResponseBody(s);
153
- if (!s.ok) {
154
- s.status === 401 && a && i === this.authRevision && (this.setAuthToken(null), this.onAuthExpired?.());
155
- let e = o(l) ? l : {}, t = typeof e.error == "string" ? e.error : s.status === 403 ? "unauthorized" : n;
156
- throw new E(t, x[t] ?? r, s.status, _e(e.details, e.quota));
157
- }
158
- return l;
159
- } catch (e) {
160
- if (e instanceof E) throw e;
161
- if (e instanceof DOMException && e.name === "AbortError") throw new E("timeout", "Request timed out. Please try again.", 408);
162
- if (e instanceof TypeError) throw new E("network_error", "Unable to connect to servers. Please check your connection.", 0);
163
- let t = new E("unknown_error", "An unexpected error occurred", 500);
164
- throw t.cause = e, t;
165
- } finally {
166
- clearTimeout(l), s?.();
167
- }
168
- }
169
- async parseResponseBody(e) {
170
- if (e.status === 204 || e.status === 205) return {};
171
- let t = e.headers?.get?.("content-type") ?? "";
172
- if (typeof e.text == "function") {
173
- let n = await e.text();
174
- if (!n) return {};
175
- if (t && !t.toLowerCase().includes("application/json")) {
176
- if (e.ok) throw new E("invalid_response", "Invalid server response", 502);
177
- return {};
178
- }
179
- try {
180
- return JSON.parse(n);
181
- } catch {
182
- if (e.ok) throw new E("invalid_response", "Invalid server response", 502);
183
- return {};
184
- }
185
- }
186
- if (typeof e.json == "function") try {
187
- return await e.json();
188
- } catch {
189
- if (e.ok) throw new E("invalid_response", "Invalid server response", 502);
190
- }
191
- return {};
192
- }
193
- async request(e, t = {}) {
194
- let n = `${this.baseUrl}${e}`, r = this.buildHeaders({
195
- "Content-Type": "application/json",
196
- ...t.headers
197
- });
198
- return this.executeRequest(n, {
199
- ...t,
200
- headers: r
201
- }, "request_failed", "An error occurred");
202
- }
203
- async requestFormData(e, t, n) {
204
- let r = `${this.baseUrl}${e}`, i = this.buildHeaders(n);
205
- return this.executeRequest(r, {
206
- method: "POST",
207
- headers: i,
208
- body: t
209
- }, "upload_failed", "Upload failed");
210
- }
211
- requireProjectId() {
212
- if (!this.projectId) throw new E("missing_project_id", "Project ID is required", 400);
213
- return this.projectId;
214
- }
215
- async validateApiKey() {
216
- return this.request("/auth/validate-key", {
217
- method: "POST",
218
- body: JSON.stringify({})
219
- });
220
- }
221
- async verifySession() {
222
- return this.request("/auth/me");
223
- }
224
- async authorizeChannel(e, t) {
225
- if (!this.authToken) throw new E("unauthorized", x.unauthorized, 401);
226
- if (!/^\d+\.\d+$/.test(e) || a(e) || e.length > 128 || !this.channelProjectId || t !== `presence-project.${this.channelProjectId}`) throw new E("invalid_channel", "Invalid realtime channel request.", 400);
227
- let n = this.authRevision, r = await this.request("/broadcasting/auth", {
228
- method: "POST",
229
- body: JSON.stringify({
230
- socket_id: e,
231
- channel_name: t
232
- })
233
- });
234
- if (n !== this.authRevision) throw new E("unauthorized", x.unauthorized, 401);
235
- if (!o(r) || typeof r.auth != "string" || !r.auth || typeof r.channel_data != "string") throw new E("invalid_response", x.invalid_response, 502);
236
- let i;
237
- try {
238
- i = JSON.parse(r.channel_data);
239
- } catch {
240
- throw new E("invalid_response", x.invalid_response, 502);
241
- }
242
- if (!o(i) || !i.user_id) throw new E("invalid_response", x.invalid_response, 502);
243
- return {
244
- auth: r.auth,
245
- channel_data: r.channel_data
246
- };
247
- }
248
- async requestOtp(e) {
249
- let t = C(e);
250
- return this.request("/auth/otp/request", {
251
- method: "POST",
252
- body: JSON.stringify({
253
- email: t,
254
- ...this.pendingInvite?.email === t ? { invitation_challenge: this.pendingInvite.challenge } : {}
255
- })
256
- });
257
- }
258
- async verifyOtp(e, t) {
259
- let n = C(e), r = he(t);
260
- return this.request("/auth/otp/verify", {
261
- method: "POST",
262
- body: JSON.stringify({
263
- email: n,
264
- otp: r
265
- })
266
- });
267
- }
268
- async verifyMfa(e, t) {
269
- if (typeof e != "string" || !/^[0-9]+\|[A-Za-z0-9]{64}$/.test(e) || typeof t != "string" || t.trim().length < 6 || t.trim().length > 100 || a(t)) throw new E("mfa_invalid", "A valid authenticator or recovery code is required.", 400);
270
- return this.request("/auth/mfa/verify", {
271
- method: "POST",
272
- body: JSON.stringify({
273
- challenge: e,
274
- code: t.trim()
275
- })
276
- });
277
- }
278
- async validateInvite(e, t) {
279
- let n = ge(e), r = C(t);
280
- this.pendingInvite = null;
281
- let i = ++this.inviteRevision, a = await this.request("/auth/validate-invite", {
282
- method: "POST",
283
- body: JSON.stringify({
284
- token: n,
285
- email: r
286
- })
287
- });
288
- return i === this.inviteRevision && a.success && a.invitationChallenge && (this.pendingInvite = {
289
- email: r,
290
- challenge: a.invitationChallenge
291
- }), a;
292
- }
293
- async getComments(e, t = "all", n = 1, r = 50, i, a, o) {
294
- let s = this.requireProjectId(), c = new URLSearchParams();
295
- e && c.append("page_path", e), t !== "all" && c.append("status", t), i && c.append("environment", i), a && c.append("branch", a);
296
- let l = Number.isFinite(n) ? Math.max(1, Math.floor(n)) : 1, u = Number.isFinite(r) ? Math.min(100, Math.max(1, Math.floor(r))) : 50;
297
- c.append("page", String(l)), c.append("limit", String(u)), o?.pagination && c.set("pagination", o.pagination), o?.view && c.set("view", o.view), o?.cursor && c.set("cursor", o.cursor), o?.search?.trim() && c.set("search", o.search.trim().slice(0, 200)), o?.priority && o.priority !== "all" && c.set("priority", o.priority), o?.user && c.set("user", o.user), o?.assignee && o.assignee !== "all" && c.set("assignee", o.assignee), o?.sort && c.set("sort", o.sort), o?.excludeComplete && c.set("exclude_complete", "1");
298
- let d = c.toString(), f = `/projects/${S(s)}/comments${d ? `?${d}` : ""}`, p = await this.request(f), m = p.comments ?? [];
299
- return {
300
- comments: m,
301
- pagination: p.pagination ?? {
302
- total: m.length,
303
- hasMore: m.length >= u,
304
- page: l,
305
- limit: u
306
- }
307
- };
308
- }
309
- async getComment(e, t) {
310
- let n = this.requireProjectId(), r = new URLSearchParams();
311
- t?.repliesLimit && r.set("replies_limit", String(Math.min(100, Math.max(1, Math.floor(t.repliesLimit))))), t?.repliesBefore && r.set("replies_before", t.repliesBefore);
312
- let i = r.size ? `?${r}` : "";
313
- return (await this.request(`/projects/${S(n)}/comments/${S(e)}${i}`)).comment;
314
- }
315
- idempotencyHeaders(e) {
316
- return typeof e == "string" && e.length > 0 && e.length <= 256 && !a(e) ? { "Idempotency-Key": e } : {};
317
- }
318
- async createComment(e, t, n, r, i = "medium", a, o, s, c) {
319
- let l = w(t, "Comment content"), u = this.requireProjectId(), d = s?.mentions ?? T(l);
320
- return (await this.request(`/projects/${S(u)}/comments`, {
321
- method: "POST",
322
- headers: this.idempotencyHeaders(c),
323
- body: JSON.stringify({
324
- type: e,
325
- position: n,
326
- page_url: r.url,
327
- page_path: r.path,
328
- page_title: r.title,
329
- environment: this.environment || void 0,
330
- branch: s?.branch,
331
- device_info: s?.deviceInfo,
332
- ...fe({
333
- content: l,
334
- priority: i,
335
- description: s?.description,
336
- assignees: s?.assignees,
337
- checklist: s?.checklist,
338
- textSelection: a,
339
- drawingData: o,
340
- attachmentIds: s?.attachmentIds
341
- }, d)
342
- })
343
- })).comment;
344
- }
345
- async updateComment(e, t) {
346
- let n = this.requireProjectId(), r = t.content === void 0 ? void 0 : w(t.content, "Comment content"), i = t.mentions ?? (r ? T(r) : void 0), a = fe({
347
- ...t,
348
- ...r === void 0 ? {} : { content: r }
349
- }, i);
350
- return (await this.request(`/projects/${S(n)}/comments/${S(e)}`, {
351
- method: "PUT",
352
- body: JSON.stringify(a)
353
- })).comment;
354
- }
355
- async deleteComment(e) {
356
- let t = this.requireProjectId();
357
- await this.request(`/projects/${S(t)}/comments/${S(e)}`, { method: "DELETE" });
358
- }
359
- async addReply(e, t, n, r) {
360
- let i = this.requireProjectId(), a = w(t, "Reply content", ae), o = r?.mentions ?? T(a);
361
- return (await this.request(`/projects/${S(i)}/comments/${S(e)}/replies`, {
362
- method: "POST",
363
- headers: this.idempotencyHeaders(n),
364
- body: JSON.stringify({
365
- content: a,
366
- attachment_ids: r?.attachmentIds,
367
- reply_to: r?.replyTo,
368
- ...o.length > 0 ? { mentions: o } : {}
369
- })
370
- })).reply;
371
- }
372
- async updateReply(e, t, n, r) {
373
- let i = this.requireProjectId(), a = w(n, "Reply content", ae);
374
- return (await this.request(`/projects/${S(i)}/comments/${S(e)}/replies/${S(t)}`, {
375
- method: "PUT",
376
- body: JSON.stringify({
377
- content: a,
378
- attachment_ids: r?.attachmentIds,
379
- mentions: r?.mentions,
380
- reply_to: r?.replyTo
381
- })
382
- })).reply;
383
- }
384
- async deleteReply(e, t) {
385
- let n = this.requireProjectId();
386
- await this.request(`/projects/${S(n)}/comments/${S(e)}/replies/${S(t)}`, { method: "DELETE" });
387
- }
388
- async resolveComment(e) {
389
- let t = this.requireProjectId();
390
- return (await this.request(`/projects/${S(t)}/comments/${S(e)}/resolve`, { method: "POST" })).comment;
391
- }
392
- async unresolveComment(e) {
393
- let t = this.requireProjectId();
394
- return (await this.request(`/projects/${S(t)}/comments/${S(e)}/unresolve`, { method: "POST" })).comment;
395
- }
396
- async markComplete(e) {
397
- let t = this.requireProjectId();
398
- return (await this.request(`/projects/${S(t)}/comments/${S(e)}/complete`, { method: "POST" })).comment;
399
- }
400
- async addReaction(e, t, n) {
401
- let r = this.requireProjectId();
402
- await this.request(`/projects/${S(r)}/comments/${S(e)}/reactions`, {
403
- method: "POST",
404
- body: JSON.stringify({
405
- emoji: t,
406
- ...n ? { reply_id: n } : {}
407
- })
408
- });
409
- }
410
- async removeReaction(e, t, n) {
411
- let r = this.requireProjectId();
412
- await this.request(`/projects/${S(r)}/comments/${S(e)}/reactions`, {
413
- method: "DELETE",
414
- body: JSON.stringify({
415
- emoji: t,
416
- ...n ? { reply_id: n } : {}
417
- })
418
- });
419
- }
420
- async updatePosition(e, t) {
421
- let n = this.requireProjectId();
422
- return (await this.request(`/projects/${S(n)}/comments/${S(e)}/position`, {
423
- method: "PUT",
424
- body: JSON.stringify({ position: t })
425
- })).comment;
426
- }
427
- async createHighlight(e, t, n, r = "medium", i, a) {
428
- return this.createComment("highlight", e, {
429
- x: 0,
430
- y: 0
431
- }, n, r, t, void 0, a, i);
432
- }
433
- async createDrawing(e, t, n, r, i, a) {
434
- return this.createComment("drawing", e, n, r, "medium", void 0, t, a, i);
435
- }
436
- validateFile(e, t = !1) {
437
- if (e.size > ne) throw new E("file_too_large", `File size (${Math.round(e.size / 1024 / 1024)}MB) exceeds maximum of ${ne / 1024 / 1024}MB`, 400);
438
- if (a(e.name) || e.name.includes("/") || e.name.includes("\\")) throw new E("invalid_filename", "Filename contains invalid characters", 400);
439
- if (t) {
440
- /* v8 ignore next -- pop() always returns a value since file has a name */
441
- let t = "." + (e.name.split(".").pop()?.toLowerCase() ?? "");
442
- if ((e.name.match(/\./g) || []).length > 1) throw new E("invalid_filename", "Filenames with multiple extensions are not allowed", 400);
443
- if (!ue.includes(e.type) || !le.includes(t)) throw new E("invalid_file_type", `Only image files are allowed (${le.join(", ")})`, 400);
444
- }
445
- if (u(e.name)) throw new E("invalid_file_type", "This file type is not allowed", 400);
446
- }
447
- async uploadFile(e, t, n) {
448
- this.validateFile(e, t === "screenshot" || t === "drawing");
449
- let r = this.requireProjectId(), i = new FormData();
450
- i.append("file", e), i.append("type", t === "attachment" ? "file" : t), n?.commentId && i.append("comment_id", n.commentId), n?.replyId && i.append("reply_id", n.replyId);
451
- let a = await this.requestFormData(`/projects/${S(r)}/files`, i);
452
- return {
453
- id: String(a.attachment.id),
454
- type: a.attachment.type,
455
- url: a.attachment.url,
456
- thumbnail: a.attachment.thumbnail,
457
- filename: a.attachment.filename,
458
- mimeType: a.attachment.mimeType,
459
- size: a.attachment.size
460
- };
461
- }
462
- async uploadScreenshot(e, t) {
463
- this.validateFile(e, !0);
464
- let n = w(t.content, "Screenshot comment"), r = this.requireProjectId(), i = new FormData();
465
- if (i.append("file", e), i.append("content", n), i.append("position_x", String(t.position.x)), i.append("position_y", String(t.position.y)), i.append("page_url", t.page.url), i.append("page_path", t.page.path), i.append("page_title", t.page.title), t.branch && i.append("branch", t.branch), t.deviceInfo) for (let [e, n] of Object.entries(t.deviceInfo)) n !== void 0 && i.append(`device_info[${e}]`, String(n));
466
- return (await this.requestFormData(`/projects/${S(r)}/screenshots`, i, this.idempotencyHeaders(t.idempotencyKey))).comment;
467
- }
468
- async uploadFiles(e, t) {
469
- if (e.length > re) throw new E("too_many_files", `Cannot upload more than ${re} files at once`, 400);
470
- let n = await Promise.allSettled(e.map((e) => {
471
- /* v8 ignore next -- pop() always returns a value since file has a name */
472
- let n = "." + (e.name.split(".").pop()?.toLowerCase() ?? ""), r = ue.includes(e.type) && le.includes(n);
473
- return this.uploadFile(e, r ? "screenshot" : "attachment", t);
474
- })), r = n.filter((e) => e.status === "fulfilled").map((e) => e.value.id), i = n.find((e) => e.status === "rejected");
475
- if (i) {
476
- let e = i.reason;
477
- throw e instanceof E ? new E(e.error, e.message, e.code, {
478
- ...e.details,
479
- uploadedIds: r
480
- }) : new E("upload_failed", "Upload failed", 0, { uploadedIds: r });
481
- }
482
- return r;
483
- }
484
- async getProjectContext() {
485
- let e = this.requireProjectId();
486
- return (await this.request(`/projects/${S(e)}/context`)).context;
487
- }
488
- async getProjectMembers() {
489
- let e = this.requireProjectId();
490
- return (await this.request(`/projects/${S(e)}/members`)).members ?? [];
491
- }
492
- };
493
- function T(e) {
494
- let t = [], n;
495
- for (de.lastIndex = 0; (n = de.exec(e)) !== null;) {
496
- let e = n[1]?.trim(), r = n[2]?.trim();
497
- e && r && /^[\w-]+$/.test(r) && t.push({
498
- name: e,
499
- userId: r,
500
- index: n.index
501
- });
502
- }
503
- return t;
504
- }
505
- function ye(e) {
506
- return `@[${e.name.replace(/\]/g, "")}](${e.id.replace(/\)/g, "")})`;
507
- }
508
- function be(e) {
509
- return e.replace(de, "@$1");
510
- }
511
- var E = class extends Error {
512
- constructor(e, t, n, r) {
513
- super(t), this.name = "ApiClientError", this.error = e, this.code = n, this.details = r;
514
- }
515
- isAuthError() {
516
- return this.code === 401 || this.error === "invalid_api_key";
517
- }
518
- isNetworkError() {
519
- return this.code === 0 || this.error === "network_error";
520
- }
521
- isRateLimitError() {
522
- return this.code === 429;
523
- }
524
- isPremiumFeatureError() {
525
- return this.code === 402;
526
- }
527
- }, D = null, xe = 0, Se = 3;
528
- function Ce() {
529
- return D || (D = (async () => {
530
- try {
531
- let e = await import("element-source");
532
- return typeof e?.resolveElementInfo == "function" ? e : null;
533
- } catch {
534
- return xe += 1, xe < Se && (D = null), null;
535
- }
536
- })(), D);
537
- }
538
- async function we(e) {
539
- let t = await Ce();
540
- if (!t) return null;
541
- try {
542
- return await t.resolveElementInfo(e);
543
- } catch {
544
- return null;
545
- }
546
- }
547
- var Te = 200, Ee = 500, De = 500, Oe = 2e3, ke = "application/x-commentkit-agent-context", Ae = "Address the UI feedback in this context.";
548
- function je(e) {
549
- return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
550
- }
551
- function Me(e) {
552
- return e === void 0 ? Te : !Number.isFinite(e) || e <= 0 ? 0 : Math.min(Ee, Math.floor(e));
553
- }
554
- function Ne(e) {
555
- return {
556
- id: e.id,
557
- name: e.name,
558
- email: e.email
559
- };
560
- }
561
- function Pe(e, t) {
562
- return e.page.path === t.path || e.page.url === t.url;
563
- }
564
- function Fe(e, t, n, r) {
565
- return !(!n.includeResolved && e.status !== "open" || n.currentPageOnly && !Pe(e, t) || r && !r.has(e.id));
566
- }
567
- function Ie(e) {
568
- let t = e.getBoundingClientRect();
569
- return {
570
- top: t.top,
571
- left: t.left,
572
- width: t.width,
573
- height: t.height
574
- };
575
- }
576
- function Le(e, t, n) {
577
- let r = n ? p(e.element ?? "", e.xpath) : null, i = {
578
- ...e.element ? { selector: e.element } : {},
579
- ...e.xpath ? { xpath: e.xpath } : {}
580
- };
581
- if (!r || g(r)) return {
582
- ...i,
583
- found: !1
584
- };
585
- let a = h(r), o = y(a.text, De), s = t ? y(a.html, Oe) : "", c = r.getAttribute("class"), l = r.getAttribute("role"), u = r.getAttribute("aria-label");
586
- return {
587
- ...i,
588
- found: !0,
589
- tagName: r.tagName.toLowerCase(),
590
- ...r.id ? { id: r.id } : {},
591
- ...c ? { className: c } : {},
592
- ...l ? { role: l } : {},
593
- ...u ? { ariaLabel: u } : {},
594
- ...o ? { text: o } : {},
595
- rect: Ie(r),
596
- ...s ? { htmlPreview: s } : {}
597
- };
598
- }
599
- function Re(e) {
600
- return {
601
- id: e.id,
602
- content: e.content,
603
- author: Ne(e.author),
604
- createdAt: e.createdAt,
605
- isEdited: e.isEdited,
606
- replyTo: e.replyTo,
607
- mentions: e.mentions,
608
- reactions: e.reactions,
609
- attachments: e.attachments?.map(O)
610
- };
611
- }
612
- function ze(e) {
613
- return e && e.length <= 4096 && !/[?#]/.test(e) && /^https?:\/\//i.test(e) && d(e) ? e : void 0;
614
- }
615
- function O(e) {
616
- let { id: t, type: n, filename: r, mimeType: i, size: a } = e, o = ze(e.url);
617
- return {
618
- id: t,
619
- type: n,
620
- filename: r,
621
- mimeType: i,
622
- size: a,
623
- ...o ? { url: o } : { inlineContentOmitted: !0 }
624
- };
625
- }
626
- function Be(e, t, n) {
627
- let r = e.attachments.map(O), i = r.find((e) => e.type === "screenshot" && e.url)?.url;
628
- return {
629
- id: e.id,
630
- type: e.type,
631
- status: e.status,
632
- priority: e.priority,
633
- content: e.content,
634
- author: Ne(e.author),
635
- createdAt: e.createdAt,
636
- updatedAt: e.updatedAt,
637
- environment: e.environment,
638
- branch: e.branch,
639
- deviceInfo: e.deviceInfo,
640
- description: e.description,
641
- assignees: e.assignees?.map(Ne),
642
- mentions: e.mentions,
643
- checklist: e.checklist,
644
- reactions: e.reactions,
645
- isEdited: e.isEdited,
646
- resolvedAt: e.resolvedAt,
647
- completedAt: e.completedAt,
648
- page: {
649
- ...e.page,
650
- url: _(e.page.url),
651
- path: _(e.page.path)
652
- },
653
- position: e.position,
654
- textSelection: e.textSelection,
655
- drawingData: e.drawingData,
656
- attachments: r,
657
- element: Le(e.position, t.includeHtml === !0, Pe(e, n)),
658
- ...i ? { screenshotUrl: i } : {},
659
- repliesCount: e.repliesCount ?? e.replies.length,
660
- replies: e.replies.map(Re)
661
- };
662
- }
663
- function Ve(e) {
664
- return {
665
- filePath: e.filePath,
666
- lineNumber: e.lineNumber,
667
- columnNumber: e.columnNumber,
668
- componentName: e.componentName
669
- };
670
- }
671
- function k(e, t = {}) {
672
- let n = m(), r = {
673
- url: n.url,
674
- path: n.path,
675
- title: n.title
676
- }, i = t.commentIds?.length ? new Set(t.commentIds) : null, a = Me(t.maxComments), o = e.comments.filter((e) => Fe(e, r, t, i)), s = o.slice(0, a).map((e) => Be(e, t, r));
677
- return {
678
- version: 1,
679
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
680
- instructions: v(t.instructions, 2e3) || Ae,
681
- page: {
682
- ...r,
683
- url: _(r.url),
684
- path: _(r.path)
685
- },
686
- comments: s,
687
- ...e.project ? { project: {
688
- id: e.project.id,
689
- name: e.project.name,
690
- slug: e.project.slug
691
- } } : {},
692
- scope: {
693
- activeBranch: e.activeBranch ?? null,
694
- currentPageOnly: t.currentPageOnly === !0,
695
- includeResolved: t.includeResolved === !0,
696
- loadedCommentCount: e.comments.length,
697
- matchingCommentCount: o.length,
698
- exportedCommentCount: s.length,
699
- hasMoreOnServer: e.pagination?.hasMore === !0,
700
- truncated: o.length > s.length
701
- },
702
- sourceResolved: !1
703
- };
704
- }
705
- async function He(e) {
706
- let t = !1, n = await Promise.all(e.comments.map(async (e) => {
707
- if (!e.element.found) return e;
708
- let n = p(e.element.selector ?? "", e.element.xpath);
709
- if (!n || g(n)) return e;
710
- let r = await we(n);
711
- if (!r || !r.source) return e;
712
- t = !0;
713
- let i = Ve(r.source), a = r.stack.map(Ve), o = r.componentName ?? void 0;
714
- return {
715
- ...e,
716
- element: {
717
- ...e.element,
718
- source: i,
719
- stack: a,
720
- ...o ? { componentName: o } : {}
721
- }
722
- };
723
- }));
724
- return {
725
- ...e,
726
- comments: n,
727
- sourceResolved: t
728
- };
729
- }
730
- function A(e) {
731
- let t = Ue(e);
732
- return [
733
- "# CommentKit Agent Context",
734
- "",
735
- v(e.instructions, 2e3),
736
- "",
737
- ee,
738
- "",
739
- `Comments: ${e.comments.length}`,
740
- ...e.scope?.truncated || e.scope?.hasMoreOnServer ? ["Incomplete snapshot: additional comments may be unloaded."] : [],
741
- "",
742
- "```json",
743
- JSON.stringify(t, null, 2).replace(/[<>&`]/g, (e) => `\\u${e.charCodeAt(0).toString(16).padStart(4, "0")}`),
744
- "```"
745
- ].join("\n");
746
- }
747
- function Ue(e) {
748
- let t = 2e3, n = (e) => e.length > t ? `${e.slice(0, t)}… [clipped]` : e;
749
- return {
750
- version: e.version,
751
- generatedAt: e.generatedAt,
752
- page: {
753
- title: e.page.title,
754
- path: _(e.page.path),
755
- url: _(e.page.url)
756
- },
757
- ...e.project ? { project: e.project } : {},
758
- scope: e.scope,
759
- comments: e.comments.map((e) => ({
760
- id: e.id,
761
- type: e.type,
762
- status: e.status,
763
- priority: e.priority,
764
- content: n(e.content),
765
- ...e.description ? { description: n(e.description) } : {},
766
- author: e.author.name,
767
- createdAt: e.createdAt,
768
- ...e.branch ? { branch: e.branch } : {},
769
- ...e.environment ? { environment: e.environment } : {},
770
- page: {
771
- title: e.page.title,
772
- path: _(e.page.path),
773
- url: _(e.page.url)
774
- },
775
- target: {
776
- selector: e.element.selector,
777
- xpath: e.element.xpath,
778
- ...e.element.text ? { text: y(e.element.text, 500) } : {},
779
- source: e.element.source,
780
- ...e.textSelection?.text ? { highlightedText: e.textSelection.text } : {},
781
- position: {
782
- x: e.position.x,
783
- y: e.position.y
784
- }
785
- },
786
- ...e.drawingData?.paths.length ? { drawing: {
787
- viewport: e.drawingData.viewport,
788
- pathCount: e.drawingData.paths.length,
789
- paths: e.drawingData.paths.slice(0, 12).map((e) => ({
790
- type: e.type,
791
- x: e.x,
792
- y: e.y,
793
- width: e.width,
794
- height: e.height,
795
- ...e.text ? { text: y(e.text, 200) } : {},
796
- ...e.d ? { bounds: We(e.d) } : {}
797
- })),
798
- ...e.drawingData.paths.length > 12 ? { omittedPaths: e.drawingData.paths.length - 12 } : {}
799
- } } : {},
800
- ...e.assignees?.length ? { assignees: e.assignees.map((e) => e.name) } : {},
801
- ...e.checklist?.length ? { checklist: e.checklist.map(({ label: e, done: t }) => ({
802
- label: e,
803
- done: t
804
- })) } : {},
805
- ...e.attachments?.length ? { attachments: e.attachments.map(O) } : {},
806
- replyCount: e.repliesCount ?? e.replies.length,
807
- ...(e.repliesCount ?? e.replies.length) > Math.min(12, e.replies.length) ? { omittedReplies: (e.repliesCount ?? e.replies.length) - Math.min(12, e.replies.length) } : {},
808
- replies: e.replies.slice(-12).map((e) => ({
809
- id: e.id,
810
- content: n(e.content),
811
- author: e.author.name,
812
- createdAt: e.createdAt,
813
- ...e.replyTo ? { replyTo: {
814
- type: e.replyTo.type,
815
- body: e.replyTo.body
816
- } } : {},
817
- ...e.attachments?.length ? { attachments: e.attachments.map(O) } : {}
818
- }))
819
- }))
820
- };
821
- }
822
- function We(e) {
823
- let t = [...e.matchAll(/[ML]\s*(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)/gi)];
824
- if (!t.length) return null;
825
- let n = t.map((e) => Number(e[1])), r = t.map((e) => Number(e[2]));
826
- return {
827
- x: Math.min(...n),
828
- y: Math.min(...r),
829
- width: Math.max(...n) - Math.min(...n),
830
- height: Math.max(...r) - Math.min(...r)
831
- };
832
- }
833
- function Ge(e) {
834
- return {
835
- version: e?.version ?? 1,
836
- generatedAt: e?.generatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
837
- commentCount: e?.comments.length ?? 0,
838
- context: e ? Ue(e) : null
839
- };
840
- }
841
- function Ke(e, t) {
842
- if (typeof document > "u" || !document.body || typeof document.execCommand != "function") return !1;
843
- let n = JSON.stringify(t), r = (t) => {
844
- t.preventDefault(), t.clipboardData?.setData("text/plain", e), t.clipboardData?.setData("text/html", `<meta charset="utf-8"><pre><code>${je(e)}</code></pre>`), t.clipboardData?.setData(ke, n);
845
- }, i = document.createElement("textarea");
846
- i.value = e, i.setAttribute("readonly", ""), i.setAttribute("aria-hidden", "true"), i.style.position = "fixed", i.style.left = "-9999px", document.addEventListener("copy", r), document.body.appendChild(i), i.select();
847
- try {
848
- return document.execCommand("copy");
849
- } finally {
850
- document.removeEventListener("copy", r), i.remove();
851
- }
852
- }
853
- async function qe(e, t) {
854
- if (typeof navigator > "u" || typeof navigator.clipboard?.write != "function" || typeof ClipboardItem > "u") return !1;
855
- try {
856
- let n = new Blob([`<meta charset="utf-8"><pre><code>${je(e)}</code></pre>`], { type: "text/html" }), r = new Blob([e], { type: "text/plain" }), i = t.type && t.type.startsWith("image/") ? t.type : "image/png";
857
- return await navigator.clipboard.write([new ClipboardItem({
858
- "text/plain": r,
859
- "text/html": n,
860
- [i]: t
861
- })]), !0;
862
- } catch {
863
- return !1;
864
- }
865
- }
866
- async function Je(e, t) {
867
- return t && await qe(e, t) ? !0 : (await Ye(e), !1);
868
- }
869
- async function Ye(e, t = null) {
870
- if (!Ke(e, Ge(t))) {
871
- if (typeof navigator < "u" && typeof navigator.clipboard?.writeText == "function") await navigator.clipboard.writeText(e);
872
- else throw Error("Clipboard is unavailable");
873
- }
874
- }
875
- function Xe(e, t, n = null) {
876
- let r = t.projectContext, i = n ?? (r?.permissions.canWriteComments === !1 ? r.permissions.writeRestriction ?? (r.organization?.plan === "none" ? "plan_required" : "feature_disabled") : null), a = i === "plan_required", o = !i && e.features?.comments !== !1;
877
- return {
878
- canWrite: o,
879
- canManageComments: o && (r?.permissions.canManageComments ?? !1),
880
- canTriage: o ? r?.permissions.canTriage : !1,
881
- canComplete: o && r?.permissions.canComplete !== !1,
882
- planRequired: a,
883
- message: o ? "" : a ? "This workspace is read-only. An active plan is required to add or change feedback. You can still read and export comments." : "Comment changes are disabled for this project. You can still read and export comments."
884
- };
885
- }
886
- function j() {
887
- for (let e of document.querySelectorAll("dialog:modal,[aria-modal=true]:is(dialog,[role$=dialog])")) if (e.getClientRects().length && getComputedStyle(e).visibility === "visible") return !0;
888
- return !1;
889
- }
890
- var Ze = 100, Qe = () => {};
891
- function $e(e) {
892
- return typeof e == "function";
893
- }
894
- var et = class {
895
- constructor() {
896
- this.listeners = /* @__PURE__ */ new Map(), this.onceWrappers = /* @__PURE__ */ new Map();
897
- }
898
- on(e, t) {
899
- if (!$e(t)) return console.warn(`[CommentKit] Ignoring non-function listener for '${String(e)}'`), Qe;
900
- let n = this.listeners.get(e);
901
- return n || (n = /* @__PURE__ */ new Set(), this.listeners.set(e, n)), !n.has(t) && n.size >= Ze && console.warn(`[CommentKit] Max listeners (${Ze}) reached for '${String(e)}' - possible memory leak`), n.add(t), () => this.off(e, t);
902
- }
903
- off(e, t) {
904
- if (!$e(t)) return;
905
- let n = this.listeners.get(e);
906
- if (n) {
907
- n.delete(t);
908
- let r = this.onceWrappers.get(e), i = r?.get(t);
909
- r && i && (n.delete(i), r.delete(t), r.size === 0 && this.onceWrappers.delete(e)), n.size === 0 && this.listeners.delete(e);
910
- }
911
- }
912
- emit(e, t) {
913
- let n = this.listeners.get(e);
914
- if (n) for (let r of Array.from(n)) try {
915
- r(t);
916
- } catch (t) {
917
- console.error(`[CommentKit] Error in '${e}' listener:`, t);
918
- }
919
- }
920
- once(e, t) {
921
- if (!$e(t)) return console.warn(`[CommentKit] Ignoring non-function listener for '${String(e)}'`), Qe;
922
- let n = (n) => {
923
- this.off(e, t), t(n);
924
- }, r = this.onceWrappers.get(e);
925
- return r || (r = /* @__PURE__ */ new Map(), this.onceWrappers.set(e, r)), r.set(t, n), this.on(e, n);
926
- }
927
- removeAllListeners(e) {
928
- e ? (this.listeners.delete(e), this.onceWrappers.delete(e)) : (this.listeners.clear(), this.onceWrappers.clear());
929
- }
930
- listenerCount(e) {
931
- return this.listeners.get(e)?.size ?? 0;
932
- }
933
- }, tt = Symbol(), M = Object.freeze({
934
- ID: 256,
935
- CONTENT: 1e4,
936
- REPLY_CONTENT: 5e3,
937
- NAME: 500,
938
- EMAIL: 254,
939
- PAGE: 2e3,
940
- SELECTOR: 2048,
941
- EMOJI: 32,
942
- COLOR: 128,
943
- DRAWING_PATH_DATA: 5e4,
944
- DRAWING_TEXT: 5e3,
945
- DRAWING_TYPE: 20,
946
- DRAWING_PATHS: 1e3,
947
- TEXT_SELECTION: 2e4,
948
- DESCRIPTION: 1e4,
949
- ASSIGNEES: 100,
950
- CHECKLIST_ITEMS: 100,
951
- CHECKLIST_LABEL: 500,
952
- ONLINE_USERS: 500,
953
- RENDERED_CURSORS: 24,
954
- CURSOR_EMITS_PER_SEC: 240,
955
- REACTION_COUNT: 1e6,
956
- PENDING_MUTATIONS: 1e3,
957
- RETRY_DELAY: 3e4
958
- }), nt = "commentkit:session:", rt = 4096;
959
- function it() {
960
- try {
961
- return typeof sessionStorage > "u" ? null : sessionStorage;
962
- } catch {
963
- return null;
964
- }
965
- }
966
- function N(e) {
967
- return `${nt}${e}`;
968
- }
969
- function at(e) {
970
- return o(e) && r(e.id, M.ID) && r(e.name, M.NAME) && typeof e.email == "string" && s(e.email, M.EMAIL);
971
- }
972
- function ot(e) {
973
- return o(e) && r(e.token, rt) && typeof e.email == "string" && s(e.email, M.EMAIL) && at(e.user);
974
- }
975
- function st(e, t) {
976
- if (!e) return;
977
- let n = it();
978
- if (n) try {
979
- n.setItem(N(e), JSON.stringify(t));
980
- } catch {}
981
- }
982
- function ct(e) {
983
- if (!e) return null;
984
- let t = it();
985
- if (!t) return null;
986
- try {
987
- let n = t.getItem(N(e));
988
- if (!n) return null;
989
- let r = JSON.parse(n);
990
- return ot(r) ? {
991
- token: r.token.trim(),
992
- email: r.email.trim(),
993
- user: {
994
- id: r.user.id.trim(),
995
- name: r.user.name.trim(),
996
- email: r.user.email.trim(),
997
- ...r.user.avatar ? { avatar: r.user.avatar } : {}
998
- }
999
- } : (t.removeItem(N(e)), null);
1000
- } catch {
1001
- return null;
1002
- }
1003
- }
1004
- function lt(e) {
1005
- if (!e) return;
1006
- let t = it();
1007
- if (t) try {
1008
- t.removeItem(N(e));
1009
- } catch {}
1010
- }
1011
- function ut(e, t) {
1012
- for (let n of e.getState().pendingMutations) e.emit("offline:failed", {
1013
- id: n.id,
1014
- error: {
1015
- error: "auth_cleared",
1016
- message: t,
1017
- code: 401
1018
- }
1019
- });
1020
- }
1021
- var dt = M.EMAIL, ft = M.NAME, pt = M.ID, mt = 4096, ht = 6;
1022
- function gt(e) {
1023
- if (typeof e != "string") return null;
1024
- let t = e.trim();
1025
- return s(t, dt) ? t : null;
1026
- }
1027
- function _t(e) {
1028
- return !a(e) && e.trim().length === ht;
1029
- }
1030
- function vt(e) {
1031
- return o(e) && r(e.id, pt) && r(e.name, ft) && typeof e.email == "string" && gt(e.email) !== null;
1032
- }
1033
- function yt(e) {
1034
- return o(e) && r(e.id, pt);
1035
- }
1036
- function P(e, t, n) {
1037
- return {
1038
- error: e,
1039
- message: t,
1040
- code: n
1041
- };
1042
- }
1043
- async function bt(e, t, n = () => !0) {
1044
- let r = gt(t);
1045
- if (!r) e.setState({
1046
- isLoading: !1,
1047
- otpStep: "idle",
1048
- otpEmail: null,
1049
- otpMfaChallenge: null
1050
- }), e.handleError(P("invalid_email", "A valid email address is required", 400));
1051
- else try {
1052
- e.setState({
1053
- isLoading: !0,
1054
- error: null,
1055
- otpStep: "requesting",
1056
- otpEmail: r,
1057
- otpMfaChallenge: null
1058
- });
1059
- let t = await e.apiClient.requestOtp(r);
1060
- if (!n()) return;
1061
- t.success ? (e.setState({
1062
- otpStep: "verifying",
1063
- isLoading: !1
1064
- }), e.emit("auth:otp-requested", {
1065
- email: r,
1066
- expiresIn: t.expiresIn
1067
- })) : (e.setState({
1068
- isLoading: !1,
1069
- otpStep: "idle",
1070
- otpEmail: null,
1071
- otpMfaChallenge: null
1072
- }), e.handleError(P("otp_failed", "Failed to send OTP. Please try again.", 500)));
1073
- } catch (t) {
1074
- if (!n()) return;
1075
- e.setState({
1076
- isLoading: !1,
1077
- otpStep: "idle",
1078
- otpEmail: null,
1079
- otpMfaChallenge: null
1080
- }), e.handleError(t);
1081
- }
1082
- }
1083
- async function xt(e, t, n) {
1084
- let { onAuthenticated: i, onWrongOtp: o, onSuccess: s, isCurrent: c = () => !0 } = typeof n == "function" ? { onAuthenticated: n } : n, { otpEmail: l, otpMfaChallenge: u, otpStep: d } = e.getState();
1085
- if (!l) {
1086
- e.handleError(P("no_email", "No OTP request in progress", 400));
1087
- return;
1088
- }
1089
- let f = d === "mfa";
1090
- if (!(f ? typeof t == "string" && !a(t) && t.trim().length >= 6 && t.trim().length <= 100 : _t(t)) || f && !u) e.setState({ isLoading: !1 }), e.handleError(P("invalid_otp", "Invalid or expired OTP code", 401));
1091
- else try {
1092
- e.setState({
1093
- isLoading: !0,
1094
- error: null
1095
- });
1096
- let n = f && u ? await e.apiClient.verifyMfa(u, t.trim()) : await e.apiClient.verifyOtp(l, t);
1097
- if (!c()) return;
1098
- if (!f && n.success && n.verified === !1 && n.mfaRequired === !0 && typeof n.challenge == "string" && /^[0-9]+\|[A-Za-z0-9]{64}$/.test(n.challenge)) {
1099
- e.setState({
1100
- otpStep: "mfa",
1101
- otpMfaChallenge: n.challenge,
1102
- isLoading: !1,
1103
- error: null
1104
- });
1105
- return;
1106
- }
1107
- if (n.verified && r(n.token, mt) && vt(n.user) && yt(n.project)) {
1108
- if (e.apiClient.setAuthToken(n.token), e.apiClient.setUserEmail(n.user.email), e.config.persistence !== "memory" && st(e.config.projectId, {
1109
- token: n.token,
1110
- email: n.user.email,
1111
- user: n.user
1112
- }), e.setState({
1113
- currentUser: n.user,
1114
- project: n.project,
1115
- isAuthenticated: !0,
1116
- isLoginModalVisible: !1,
1117
- isOverlayVisible: !0,
1118
- isLoading: !1,
1119
- otpStep: "idle",
1120
- otpEmail: null,
1121
- otpMfaChallenge: null
1122
- }), s?.(), e.emit("auth:otp-verified", n.user), !c() || (e.emit("auth:login", n.user), !c())) return;
1123
- await i();
1124
- } else e.setState({ isLoading: !1 }), o?.(), e.handleError(P("invalid_otp", "Invalid or expired OTP code", 401));
1125
- } catch (t) {
1126
- if (!c()) return;
1127
- e.setState({ isLoading: !1 }), e.handleError(t);
1128
- }
1129
- }
1130
- function St(e) {
1131
- e.setState({
1132
- otpStep: "idle",
1133
- otpEmail: null,
1134
- otpMfaChallenge: null,
1135
- error: null,
1136
- isLoading: !1
1137
- });
1138
- }
1139
- async function Ct(e, t = () => !0) {
1140
- let n = e.getState().otpEmail;
1141
- n && await bt(e, n, t);
1142
- }
1143
- function wt(e, t) {
1144
- ut(e, "Pending offline changes were discarded on logout"), lt(e.config.projectId), e.apiClient.setUserEmail(null), e.apiClient.setAuthToken(null), t(), e.setState({
1145
- isAuthenticated: !1,
1146
- currentUser: null,
1147
- comments: [],
1148
- activeTool: null,
1149
- selectedComment: null,
1150
- activeComment: null,
1151
- activeDrawing: null,
1152
- activeScreenshot: null,
1153
- onlineUsers: [],
1154
- isOverlayVisible: !1,
1155
- isCommentModeActive: !1,
1156
- isDrawingModeActive: !1,
1157
- isHighlightModeActive: !1,
1158
- isScreenshotModeActive: !1,
1159
- isSidebarVisible: !1,
1160
- otpStep: "idle",
1161
- otpEmail: null,
1162
- otpMfaChallenge: null,
1163
- pagination: null,
1164
- pendingMutations: [],
1165
- activities: [],
1166
- seenThreadIds: /* @__PURE__ */ new Set(),
1167
- panelView: "list",
1168
- connectionStatus: "disconnected",
1169
- error: null,
1170
- isLoading: !1
1171
- }), e.emit("auth:logout", void 0);
1172
- }
1173
- function Tt(e) {
1174
- ut(e, "Pending offline changes were discarded because the session expired"), lt(e.config.projectId), e.apiClient.setUserEmail(null), e.apiClient.setAuthToken(null), e.setState({
1175
- isAuthenticated: !1,
1176
- currentUser: null,
1177
- comments: [],
1178
- selectedComment: null,
1179
- activeComment: null,
1180
- activeDrawing: null,
1181
- activeScreenshot: null,
1182
- onlineUsers: [],
1183
- pendingMutations: [],
1184
- activities: [],
1185
- seenThreadIds: /* @__PURE__ */ new Set(),
1186
- panelView: "list",
1187
- connectionStatus: "disconnected",
1188
- isLoginModalVisible: !0,
1189
- otpStep: "idle",
1190
- otpEmail: null,
1191
- otpMfaChallenge: null,
1192
- error: "Your session has expired. Please sign in again.",
1193
- isLoading: !1
1194
- }), e.emit("error", {
1195
- error: "auth_expired",
1196
- message: "Session expired",
1197
- code: 401
1198
- });
1199
- }
1200
- function Et(e) {
1201
- e.setState({ isLoginModalVisible: !e.getState().isLoginModalVisible });
1202
- }
1203
- async function Dt(e, t, n, r = () => !0) {
1204
- let i = e.config.inviteToken;
1205
- if (!i) {
1206
- e.handleError(P("no_invite", "No invite token found", 400));
1207
- return;
1208
- }
1209
- let a = gt(t);
1210
- if (!a) e.setState({ isLoading: !1 }), e.handleError(P("invalid_email", "A valid email address is required", 400));
1211
- else try {
1212
- e.setState({
1213
- isLoading: !0,
1214
- error: null
1215
- });
1216
- let t = await e.apiClient.validateInvite(i, a);
1217
- if (t.success && t.accessScope !== "project" && e.config.inviteToken === i && (e.config.inviteToken = void 0), !r()) return;
1218
- t.success ? await n(a) : (e.setState({ isLoading: !1 }), e.handleError(P("invite_invalid", "Invite validation failed", 400)));
1219
- } catch (t) {
1220
- if (!r()) return;
1221
- e.setState({ isLoading: !1 }), e.handleError(t);
1222
- }
1223
- }
1224
- function F(e) {
1225
- return Object.freeze(e);
1226
- }
1227
- var Ot = Object.freeze({
1228
- auth: F([
1229
- "isAuthenticated",
1230
- "currentUser",
1231
- "project",
1232
- "projectContext",
1233
- "isLoginModalVisible",
1234
- "otpStep",
1235
- "otpEmail",
1236
- "otpMfaChallenge"
1237
- ]),
1238
- ui: F([
1239
- "isOverlayVisible",
1240
- "isSidebarVisible",
1241
- "isShortcutsOverlayVisible",
1242
- "activeTool",
1243
- "isCommentModeActive",
1244
- "isDrawingModeActive",
1245
- "isHighlightModeActive",
1246
- "isScreenshotModeActive",
1247
- "selectedComment",
1248
- "activeComment",
1249
- "activeDrawing",
1250
- "activeScreenshot",
1251
- "panelView",
1252
- "activities",
1253
- "isLoading",
1254
- "error"
1255
- ]),
1256
- comments: F([
1257
- "comments",
1258
- "pagination",
1259
- "seenThreadIds",
1260
- "activeBranch",
1261
- "commentQuery",
1262
- "loadingThreadId"
1263
- ]),
1264
- realtime: F([
1265
- "onlineUsers",
1266
- "connectionStatus",
1267
- "pendingMutations",
1268
- "isOnline"
1269
- ])
1270
- });
1271
- function kt() {
1272
- return typeof navigator < "u" && typeof navigator.onLine == "boolean" ? navigator.onLine : !0;
1273
- }
1274
- var At = 2e3;
1275
- function jt() {
1276
- return {
1277
- isAuthenticated: !1,
1278
- isOverlayVisible: !0,
1279
- isCommentModeActive: !1,
1280
- isDrawingModeActive: !1,
1281
- isHighlightModeActive: !1,
1282
- isScreenshotModeActive: !1,
1283
- isSidebarVisible: !1,
1284
- isLoginModalVisible: !1,
1285
- isShortcutsOverlayVisible: !1,
1286
- currentUser: null,
1287
- project: null,
1288
- projectContext: null,
1289
- activeBranch: null,
1290
- comments: [],
1291
- commentQuery: void 0,
1292
- loadingThreadId: null,
1293
- activeTool: null,
1294
- selectedComment: null,
1295
- activeComment: null,
1296
- activeDrawing: null,
1297
- activeScreenshot: null,
1298
- onlineUsers: [],
1299
- connectionStatus: "disconnected",
1300
- activities: [],
1301
- seenThreadIds: /* @__PURE__ */ new Set(),
1302
- panelView: "list",
1303
- isLoading: !1,
1304
- error: null,
1305
- otpStep: "idle",
1306
- otpEmail: null,
1307
- otpMfaChallenge: null,
1308
- pagination: null,
1309
- pendingMutations: [],
1310
- isOnline: kt()
1311
- };
1312
- }
1313
- function I(e) {
1314
- let t = e.config.branch ?? e.getState().activeBranch;
1315
- if (!(typeof t != "string" || t.length > 255 || a(t))) return t.trim() || void 0;
1316
- }
1317
- var L = M.ID, Mt = M.CONTENT, Nt = M.REPLY_CONTENT, Pt = M.SELECTOR, Ft = M.TEXT_SELECTION, It = M.DESCRIPTION, Lt = M.ASSIGNEES, Rt = M.CHECKLIST_ITEMS, zt = M.CHECKLIST_LABEL, Bt = M.DRAWING_PATHS, Vt = M.DRAWING_PATH_DATA, Ht = M.DRAWING_TEXT, Ut = M.REACTION_COUNT, Wt = M.EMOJI, Gt = /* @__PURE__ */ new Set([
1318
- "pin",
1319
- "highlight",
1320
- "drawing"
1321
- ]), Kt = /* @__PURE__ */ new Set([
1322
- "low",
1323
- "medium",
1324
- "high",
1325
- "urgent"
1326
- ]), qt = /* @__PURE__ */ new Set([
1327
- "open",
1328
- "resolved",
1329
- "complete"
1330
- ]), Jt = /* @__PURE__ */ new Set([
1331
- "path",
1332
- "line",
1333
- "rectangle",
1334
- "circle",
1335
- "text"
1336
- ]);
1337
- function R(e, t, n) {
1338
- e.handleError(new E(t, n, 400));
1339
- }
1340
- function z(e) {
1341
- return r(e, L);
1342
- }
1343
- function B(e, t = Mt) {
1344
- if (typeof e != "string") return null;
1345
- let n = e.trim();
1346
- return !n || n.length > t || c(n) ? null : n;
1347
- }
1348
- function V(e, t) {
1349
- if (e === void 0) return;
1350
- if (typeof e != "string") return null;
1351
- let n = e.trim();
1352
- return n.length > t || c(n) ? null : n;
1353
- }
1354
- function H(e) {
1355
- if (e === void 0) return;
1356
- if (typeof e != "string") return null;
1357
- let t = e.trim();
1358
- return !t || t.length > Pt || c(t) ? null : t;
1359
- }
1360
- function Yt(t) {
1361
- if (!o(t) || !e(t.x) || !e(t.y)) return null;
1362
- let n = H(t.element), r = H(t.xpath);
1363
- return n === null || r === null ? null : {
1364
- x: t.x,
1365
- y: t.y,
1366
- ...n === void 0 ? {} : { element: n },
1367
- ...r === void 0 ? {} : { xpath: r }
1368
- };
1369
- }
1370
- function Xt(e) {
1371
- if (!o(e)) return null;
1372
- let t = V(e.avatar, Pt), n = V(e.organizationId, L);
1373
- return !z(e.id) || typeof e.name != "string" || !e.name.trim() || e.name.length > M.NAME || c(e.name) || typeof e.email != "string" || !e.email.trim() || e.email.length > M.EMAIL || /\s/.test(e.email.trim()) || c(e.email) || t === null || n === null ? null : {
1374
- id: e.id.trim(),
1375
- name: e.name.trim(),
1376
- email: e.email.trim(),
1377
- ...t === void 0 ? {} : { avatar: t },
1378
- ...n === void 0 ? {} : { organizationId: n }
1379
- };
1380
- }
1381
- function Zt(e) {
1382
- if (e === void 0) return;
1383
- if (!Array.isArray(e) || e.length > Lt) return null;
1384
- let t = [];
1385
- for (let n of e) {
1386
- let e = Xt(n);
1387
- if (!e) return null;
1388
- t.push(e);
1389
- }
1390
- return t;
1391
- }
1392
- function Qt(e) {
1393
- if (e === void 0) return;
1394
- if (!Array.isArray(e) || e.length > Rt) return null;
1395
- let t = [];
1396
- for (let n of e) {
1397
- if (!o(n)) return null;
1398
- let e = B(n.label);
1399
- if (!z(n.id) || !e || typeof n.done != "boolean" || n.sortOrder !== void 0 && (typeof n.sortOrder != "number" || !Number.isFinite(n.sortOrder)) || e.length > zt) return null;
1400
- t.push({
1401
- id: n.id.trim(),
1402
- label: e,
1403
- done: n.done,
1404
- ...n.sortOrder === void 0 ? {} : { sortOrder: n.sortOrder }
1405
- });
1406
- }
1407
- return t;
1408
- }
1409
- function $t(e) {
1410
- if (e === void 0) return;
1411
- if (!o(e) || typeof e.text != "string") return null;
1412
- let t = e.text.trim(), n = H(e.element), r = H(e.xpath);
1413
- return !t || t.length > Ft || c(t) || typeof e.startOffset != "number" || typeof e.endOffset != "number" || !Number.isInteger(e.startOffset) || !Number.isInteger(e.endOffset) || e.startOffset < 0 || e.endOffset < e.startOffset || n === null || r === null || n === void 0 || r === void 0 ? null : {
1414
- text: t,
1415
- startOffset: e.startOffset,
1416
- endOffset: e.endOffset,
1417
- element: n,
1418
- xpath: r
1419
- };
1420
- }
1421
- function en(e) {
1422
- return typeof e == "string" && e.length > 0 && e.length <= M.COLOR && t(e);
1423
- }
1424
- function U(e) {
1425
- return e === void 0 || typeof e == "number" && Number.isFinite(e);
1426
- }
1427
- function tn(e) {
1428
- if (e === void 0) return;
1429
- if (!o(e) || e.type !== "svg" || !Array.isArray(e.paths) || e.paths.length > Bt || !o(e.viewport) || typeof e.viewport.width != "number" || typeof e.viewport.height != "number" || !Number.isFinite(e.viewport.width) || !Number.isFinite(e.viewport.height) || e.viewport.width <= 0 || e.viewport.height <= 0) return null;
1430
- let t = [];
1431
- for (let n of e.paths) {
1432
- if (!o(n) || !Jt.has(String(n.type))) return null;
1433
- let e = V(n.text, Ht);
1434
- if (!en(n.stroke) || !en(n.fill) || typeof n.strokeWidth != "number" || !Number.isFinite(n.strokeWidth) || n.strokeWidth < 0 || n.d !== void 0 && (typeof n.d != "string" || n.d.length > Vt || c(n.d)) || !U(n.x) || !U(n.y) || !U(n.width) || !U(n.height) || e === null) return null;
1435
- t.push({
1436
- type: n.type,
1437
- stroke: n.stroke,
1438
- strokeWidth: n.strokeWidth,
1439
- fill: n.fill,
1440
- ...n.d === void 0 ? {} : { d: n.d },
1441
- ...n.x === void 0 ? {} : { x: n.x },
1442
- ...n.y === void 0 ? {} : { y: n.y },
1443
- ...n.width === void 0 ? {} : { width: n.width },
1444
- ...n.height === void 0 ? {} : { height: n.height },
1445
- ...e === void 0 ? {} : { text: e }
1446
- });
1447
- }
1448
- return {
1449
- type: "svg",
1450
- paths: t,
1451
- viewport: {
1452
- width: e.viewport.width,
1453
- height: e.viewport.height
1454
- }
1455
- };
1456
- }
1457
- function nn(e) {
1458
- return o(e) && typeof e.browser == "string" && e.browser.length <= 255 && typeof e.os == "string" && e.os.length <= 255 && typeof e.windowSize == "string" && e.windowSize.length <= 64 && typeof e.devicePixelRatio == "number" && e.devicePixelRatio > 0 && e.devicePixelRatio <= 16 && (e.type === "desktop" || e.type === "mobile") && (e.deployment === void 0 || typeof e.deployment == "string" && e.deployment.length <= 255);
1459
- }
1460
- function rn(e) {
1461
- if (e === void 0) return;
1462
- if (!o(e)) return null;
1463
- let t = V(e.description, It), n = Zt(e.assignees), r = Qt(e.checklist);
1464
- if (t === null || n === null || r === null) return null;
1465
- let i = Array.isArray(e.files) ? e.files.filter((e) => typeof File < "u" && e instanceof File) : void 0, a = Array.isArray(e.attachmentIds) ? e.attachmentIds.map((e) => String(e).trim()).filter((e) => e.length > 0 && e.length <= L).slice(0, 20) : void 0;
1466
- return {
1467
- ...Array.isArray(e.mentions) ? { mentions: e.mentions.filter((e) => o(e) && z(e.userId) && typeof e.name == "string").slice(0, 100) } : {},
1468
- ...typeof e.branch == "string" && e.branch.trim() && e.branch.length <= 255 && !c(e.branch) ? { branch: e.branch.trim() } : {},
1469
- ...nn(e.deviceInfo) ? { deviceInfo: e.deviceInfo } : {},
1470
- ...t === void 0 ? {} : { description: t },
1471
- ...n === void 0 ? {} : { assignees: n },
1472
- ...r === void 0 ? {} : { checklist: r },
1473
- ...i && i.length > 0 ? { files: i } : {},
1474
- ...a && a.length > 0 ? { attachmentIds: a } : {}
1475
- };
1476
- }
1477
- function an(e) {
1478
- if (!o(e)) return null;
1479
- let t = {};
1480
- if ("content" in e) {
1481
- let n = B(e.content);
1482
- if (!n) return null;
1483
- t.content = n;
1484
- }
1485
- if ("status" in e) {
1486
- if (!qt.has(e.status)) return null;
1487
- t.status = e.status;
1488
- }
1489
- if ("priority" in e) {
1490
- if (!Kt.has(e.priority)) return null;
1491
- t.priority = e.priority;
1492
- }
1493
- if ("description" in e) {
1494
- let n = V(e.description, It);
1495
- if (n === null) return null;
1496
- t.description = n;
1497
- }
1498
- if (Array.isArray(e.mentions) && (t.mentions = e.mentions.filter((e) => o(e) && z(e.userId) && typeof e.name == "string").slice(0, 100)), "assignees" in e) {
1499
- let n = Zt(e.assignees);
1500
- if (n === null) return null;
1501
- t.assignees = n;
1502
- }
1503
- if ("checklistPatch" in e) {
1504
- let n = e.checklistPatch;
1505
- if ("checklist" in e || !o(n) || !z(n.id) || typeof n.done != "boolean") return null;
1506
- t.checklistPatch = {
1507
- id: n.id,
1508
- done: n.done
1509
- };
1510
- }
1511
- if ("checklist" in e) {
1512
- let n = Qt(e.checklist);
1513
- if (n === null) return null;
1514
- t.checklist = n;
1515
- }
1516
- if ("textSelection" in e) {
1517
- let n = $t(e.textSelection);
1518
- if (n === null) return null;
1519
- t.textSelection = n;
1520
- }
1521
- if ("drawingData" in e) {
1522
- let n = tn(e.drawingData);
1523
- if (n === null) return null;
1524
- t.drawingData = n;
1525
- }
1526
- if ("attachmentIds" in e) {
1527
- let n = e.attachmentIds;
1528
- if (!Array.isArray(n)) return null;
1529
- t.attachmentIds = n.map((e) => String(e).trim()).filter((e) => e.length > 0 && e.length <= L).slice(0, 20);
1530
- }
1531
- return Object.keys(t).length > 0 ? t : void 0;
1532
- }
1533
- function W(e) {
1534
- return `${e}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1535
- }
1536
- function G(e, t) {
1537
- return e.getState().comments.some((e) => e.id === t);
1538
- }
1539
- function K(e, t, n) {
1540
- if (e.getState().activeBranch && n.branch !== e.getState().activeBranch) {
1541
- e.setState({ comments: e.getState().comments.filter((e) => e.id !== t) });
1542
- return;
1543
- }
1544
- let r = e.getState().comments.filter((e) => e.id !== n.id), i = r.some((e) => e.id === t);
1545
- e.setState({ comments: i ? r.map((e) => e.id === t ? n : e) : [...r, n] });
1546
- }
1547
- function on(e, t, n, r) {
1548
- e.setState({ comments: e.getState().comments.map((e) => {
1549
- if (e.id !== t) return e;
1550
- let i = e.replies.filter((e) => e.id !== r.id), a = i.some((e) => e.id === n);
1551
- return {
1552
- ...e,
1553
- status: "open",
1554
- resolvedAt: void 0,
1555
- completedAt: void 0,
1556
- replies: a ? i.map((e) => e.id === n ? r : e) : [...i, r]
1557
- };
1558
- }) });
1559
- }
1560
- function q(e, t) {
1561
- return !t || t === e.status ? e : {
1562
- ...e,
1563
- status: t,
1564
- completedAt: void 0,
1565
- ...t === "complete" ? {} : { resolvedAt: void 0 }
1566
- };
1567
- }
1568
- function sn(e, t, n) {
1569
- return e.getState().comments.some((e) => e.id === t && e.replies.some((e) => e.id === n));
1570
- }
1571
- async function cn(e) {
1572
- let t = e.getState().activeBranch, n = e.getState().commentQuery;
1573
- e.setState({ isLoading: !0 });
1574
- try {
1575
- let r = await e.apiClient.getComments(n?.pagePath, n?.status ?? "all", 1, 50, void 0, t, {
1576
- ...n,
1577
- pagination: "cursor",
1578
- view: "summary"
1579
- });
1580
- if (t !== e.getState().activeBranch || e.isCurrent?.() === !1) return;
1581
- let i = e.getState().selectedComment?.id, a = i && r.comments.find((e) => e.id === i);
1582
- if (a && a.detailLoaded === !1) {
1583
- let n = await e.apiClient.getComment(a.id, { repliesLimit: 50 });
1584
- if (e.isCurrent?.() === !1 || t !== e.getState().activeBranch) return;
1585
- r.comments = r.comments.map((e) => e.id === n.id ? n : e);
1586
- }
1587
- e.setState({
1588
- comments: r.comments,
1589
- pagination: r.pagination
1590
- });
1591
- } catch (t) {
1592
- e.handleError(t);
1593
- } finally {
1594
- e.setState({ isLoading: !1 });
1595
- }
1596
- }
1597
- async function ln(e, t) {
1598
- let n = e.getState().activeBranch, r = e.getState().pagination, i = e.getState().commentQuery;
1599
- if (r && r.hasMore && !t.current) {
1600
- t.current = !0;
1601
- try {
1602
- e.setState({ isLoading: !0 });
1603
- let t = await e.apiClient.getComments(i?.pagePath, i?.status ?? "all", r.page + 1, r.limit, void 0, n, {
1604
- ...i,
1605
- pagination: "cursor",
1606
- view: "summary",
1607
- cursor: r.nextCursor
1608
- });
1609
- if (n !== e.getState().activeBranch || i !== e.getState().commentQuery || e.isCurrent?.() === !1) return;
1610
- let a = new Set(e.getState().comments.map((e) => e.id)), o = t.comments.filter((e) => !a.has(e.id));
1611
- e.setState({
1612
- comments: [...e.getState().comments, ...o],
1613
- pagination: t.pagination,
1614
- isLoading: !1
1615
- });
1616
- } catch (t) {
1617
- e.setState({ isLoading: !1 }), e.handleError(t);
1618
- } finally {
1619
- t.current = !1;
1620
- }
1621
- }
1622
- }
1623
- async function un(e, t, n) {
1624
- if (z(t)) {
1625
- e.setState({ loadingThreadId: t });
1626
- try {
1627
- let r = await e.apiClient.getComment(t, {
1628
- repliesLimit: 50,
1629
- ...n ? { repliesBefore: n } : {}
1630
- });
1631
- if (e.isCurrent?.() === !1 || e.getState().selectedComment?.id !== t) return;
1632
- let i = e.getState().comments.find((e) => e.id === t), a = n && i ? [...new Map([...r.replies, ...i.replies].map((e) => [e.id, e])).values()] : r.replies, o = n && i ? {
1633
- ...i,
1634
- detailLoaded: !0,
1635
- replies: a,
1636
- repliesPagination: r.repliesPagination,
1637
- repliesCount: Math.max(i.repliesCount ?? i.replies.length, r.repliesCount ?? r.replies.length)
1638
- } : {
1639
- ...r,
1640
- detailLoaded: !0,
1641
- replies: a
1642
- };
1643
- e.setState({
1644
- comments: e.getState().comments.map((e) => e.id === t ? o : e),
1645
- selectedComment: o
1646
- });
1647
- } catch (t) {
1648
- e.handleError(t);
1649
- } finally {
1650
- e.getState().loadingThreadId === t && e.setState({ loadingThreadId: null });
1651
- }
1652
- }
1653
- }
1654
- async function dn(e, t, n, r, i, a, o = "medium", s, c, l) {
1655
- let u = e.getState().currentUser;
1656
- if (!u) return;
1657
- let d = B(i), f = Yt(a), p = $t(s), h = tn(c), g = rn(l);
1658
- if (!Gt.has(r) || !d || !f || !Kt.has(o) || p === null || h === null || g === null) {
1659
- R(e, "invalid_comment", "Comment data is invalid");
1660
- return;
1661
- }
1662
- let _ = `create:${r}:${d.slice(0, 50)}:${f.x}:${f.y}`;
1663
- if (n.has(_)) return;
1664
- n.add(_);
1665
- let v = m(), y = g?.files ?? [], ee = y.map((e, t) => ({
1666
- id: W(`pending-att-${t}`),
1667
- type: e.type.startsWith("image/") ? "screenshot" : "file",
1668
- url: "",
1669
- filename: e.name,
1670
- size: e.size
1671
- })), b = W("temp"), te = {
1672
- id: b,
1673
- type: r,
1674
- content: d,
1675
- position: f,
1676
- status: "open",
1677
- priority: o,
1678
- author: u,
1679
- userId: u.id,
1680
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1681
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1682
- page: {
1683
- url: v.url,
1684
- path: v.path,
1685
- title: v.title
1686
- },
1687
- branch: g?.branch,
1688
- deviceInfo: g?.deviceInfo,
1689
- mentions: g?.mentions,
1690
- description: g?.description,
1691
- assignees: g?.assignees,
1692
- checklist: g?.checklist,
1693
- replies: [],
1694
- attachments: ee,
1695
- textSelection: p,
1696
- drawingData: h
1697
- };
1698
- e.setState({
1699
- comments: [...e.getState().comments, te],
1700
- activeComment: null,
1701
- activeTool: null,
1702
- isCommentModeActive: !1,
1703
- isDrawingModeActive: !1,
1704
- isHighlightModeActive: !1
1705
- });
1706
- try {
1707
- let { files: n, ...i } = g ?? {}, a = await e.apiClient.createComment(r, d, f, v, o, p, h, i, b);
1708
- if (e.isCurrent?.() === !1) return;
1709
- let s = a;
1710
- if (y.length > 0) try {
1711
- let t = (await Promise.all(y.map(async (t) => {
1712
- let n = "." + (t.name.split(".").pop()?.toLowerCase() ?? ""), r = t.type.startsWith("image/") && [
1713
- ".jpg",
1714
- ".jpeg",
1715
- ".png",
1716
- ".gif",
1717
- ".webp"
1718
- ].includes(n);
1719
- return e.apiClient.uploadFile(t, r ? "screenshot" : "attachment", { commentId: a.id });
1720
- }))).map((e) => ({
1721
- id: e.id,
1722
- type: e.type === "screenshot" || e.type === "drawing" ? e.type : "file",
1723
- url: e.url,
1724
- thumbnail: e.thumbnail,
1725
- filename: e.filename,
1726
- size: e.size
1727
- }));
1728
- s = {
1729
- ...a,
1730
- attachments: t
1731
- };
1732
- } catch (t) {
1733
- e.handleError(t), s = {
1734
- ...a,
1735
- attachments: a.attachments ?? []
1736
- };
1737
- }
1738
- K(e, b, s), e.emit("comment:created", s), t.addActivity({
1739
- type: "comment_created",
1740
- threadId: s.id,
1741
- message: "created a new comment"
1742
- });
1743
- } catch (n) {
1744
- t.shouldQueueMutation(n) && t.queueMutation("createComment", [
1745
- r,
1746
- d,
1747
- f,
1748
- o,
1749
- p,
1750
- h,
1751
- g ? {
1752
- description: g.description,
1753
- assignees: g.assignees,
1754
- mentions: g.mentions,
1755
- branch: g.branch,
1756
- deviceInfo: g.deviceInfo,
1757
- checklist: g.checklist,
1758
- attachmentIds: g.attachmentIds
1759
- } : void 0,
1760
- {
1761
- url: v.url,
1762
- path: v.path,
1763
- title: v.title
1764
- }
1765
- ], b) || (e.setState({ comments: e.getState().comments.filter((e) => e.id !== b) }), e.handleError(n));
1766
- } finally {
1767
- n.delete(_);
1768
- }
1769
- }
1770
- async function fn(e, t, n, r) {
1771
- if (!z(n)) return;
1772
- let i = an(r);
1773
- if (i === null) {
1774
- R(e, "invalid_comment_update", "Comment update data is invalid");
1775
- return;
1776
- }
1777
- if (i === void 0) return;
1778
- let a = e.getState().comments, o = a.find((e) => e.id === n);
1779
- if (!o) return;
1780
- let { checklistPatch: s, ...c } = i;
1781
- e.setState({ comments: a.map((e) => e.id === n ? {
1782
- ...q(e, i.status),
1783
- ...c,
1784
- ...s ? { checklist: e.checklist?.map((e) => e.id === s.id ? {
1785
- ...e,
1786
- done: s.done
1787
- } : e) } : {}
1788
- } : e) });
1789
- try {
1790
- let t = await e.apiClient.updateComment(n, i);
1791
- e.setState({ comments: e.getState().comments.map((e) => e.id === n ? t : e) }), e.emit("comment:updated", t);
1792
- } catch (r) {
1793
- t.shouldQueueMutation(r) && t.queueMutation("updateComment", [n, i]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n ? o : e) }), e.handleError(r));
1794
- }
1795
- }
1796
- async function pn(e, t, n) {
1797
- if (!z(n)) return;
1798
- let r = e.getState().comments, i = r.find((e) => e.id === n);
1799
- if (!i) return;
1800
- let a = e.getState().selectedComment;
1801
- e.setState({
1802
- comments: r.filter((e) => e.id !== n),
1803
- selectedComment: a?.id === n ? null : a
1804
- });
1805
- try {
1806
- await e.apiClient.deleteComment(n), e.emit("comment:deleted", { id: n });
1807
- } catch (r) {
1808
- if (!(t.shouldQueueMutation(r) && t.queueMutation("deleteComment", [n]))) {
1809
- let t = e.getState(), o = t.comments;
1810
- (!t.activeBranch || i.branch === t.activeBranch) && e.setState({
1811
- comments: o.some((e) => e.id === n) ? o : [...o, i],
1812
- selectedComment: t.selectedComment ?? a
1813
- }), e.handleError(r);
1814
- }
1815
- }
1816
- }
1817
- async function mn(e, t, n, r, i) {
1818
- let a = e.getState().currentUser;
1819
- if (!a || !z(n) || !G(e, n)) return;
1820
- let o = B(r, Nt);
1821
- if (!o) {
1822
- R(e, "invalid_reply", "Reply content is invalid");
1823
- return;
1824
- }
1825
- if (i?.replyTo && (!z(i.replyTo.id) || i.replyTo.id.startsWith("temp_") || !["comment", "reply"].includes(i.replyTo.type) || (i.replyTo.type === "comment" ? i.replyTo.id !== n : !sn(e, n, i.replyTo.id)))) {
1826
- R(e, "invalid_reply", "Reply target must belong to this thread");
1827
- return;
1828
- }
1829
- let s = e.getState().comments.find((e) => e.id === n), c = i?.replyTo?.type === "comment" ? s : s?.replies.find((e) => e.id === i?.replyTo?.id), l = W("temp_reply"), u = {
1830
- ...c && i?.replyTo ? { replyTo: {
1831
- ...i.replyTo,
1832
- authorName: c.author.name,
1833
- body: c.content
1834
- } } : {},
1835
- ...i?.mentions ? { mentions: i.mentions } : {},
1836
- id: l,
1837
- content: o,
1838
- author: a,
1839
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1840
- };
1841
- e.setState({ comments: e.getState().comments.map((e) => e.id === n ? {
1842
- ...e,
1843
- repliesCount: (e.repliesCount ?? e.replies.length) + 1,
1844
- replies: [...e.replies, u]
1845
- } : e) });
1846
- try {
1847
- on(e, n, l, await e.apiClient.addReply(n, o, l, ...i ? [i] : []));
1848
- let t = e.getState().comments.find((e) => e.id === n);
1849
- t && e.emit("comment:updated", t);
1850
- } catch (r) {
1851
- t.shouldQueueMutation(r) && t.queueMutation("addReply", i ? [
1852
- n,
1853
- o,
1854
- i
1855
- ] : [n, o], l) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n ? {
1856
- ...e,
1857
- repliesCount: Math.max(0, (e.repliesCount ?? e.replies.length) - 1),
1858
- replies: e.replies.filter((e) => e.id !== l)
1859
- } : e) }), e.handleError(r));
1860
- }
1861
- }
1862
- async function hn(e, t, n, r, i) {
1863
- if (!z(t) || !z(n) || !sn(e, t, n)) return;
1864
- let a = B(r, Nt);
1865
- if (!a) {
1866
- R(e, "invalid_reply", "Reply content is invalid");
1867
- return;
1868
- }
1869
- let o = e.getState().comments, s = o.find((e) => e.id === t)?.replies.find((e) => e.id === n);
1870
- e.setState({ comments: o.map((e) => e.id === t ? {
1871
- ...e,
1872
- replies: e.replies.map((e) => e.id === n ? {
1873
- ...e,
1874
- content: a,
1875
- isEdited: !0
1876
- } : e)
1877
- } : e) });
1878
- try {
1879
- let r = await e.apiClient.updateReply(t, n, a, ...i ? [i] : []);
1880
- e.setState({ comments: e.getState().comments.map((e) => e.id === t ? {
1881
- ...e,
1882
- replies: e.replies.map((e) => e.id === n ? r : e)
1883
- } : e) });
1884
- let o = e.getState().comments.find((e) => e.id === t);
1885
- o && e.emit("comment:updated", o);
1886
- } catch (r) {
1887
- e.setState({ comments: e.getState().comments.map((e) => e.id === t && s ? {
1888
- ...e,
1889
- replies: e.replies.map((e) => e.id === n ? s : e)
1890
- } : e) }), e.handleError(r);
1891
- }
1892
- }
1893
- async function gn(e, t, n) {
1894
- if (!z(t) || !z(n) || !sn(e, t, n)) return;
1895
- let r = e.getState().comments, i = r.find((e) => e.id === t)?.replies.find((e) => e.id === n);
1896
- e.setState({ comments: r.map((e) => e.id === t ? {
1897
- ...e,
1898
- repliesCount: Math.max(0, (e.repliesCount ?? e.replies.length) - 1),
1899
- replies: e.replies.filter((e) => e.id !== n)
1900
- } : e) });
1901
- try {
1902
- await e.apiClient.deleteReply(t, n);
1903
- let r = e.getState().comments.find((e) => e.id === t);
1904
- r && e.emit("comment:updated", r);
1905
- } catch (r) {
1906
- e.setState({ comments: e.getState().comments.map((e) => e.id === t && i && !e.replies.some((e) => e.id === n) ? {
1907
- ...e,
1908
- repliesCount: (e.repliesCount ?? e.replies.length) + 1,
1909
- replies: [...e.replies, i]
1910
- } : e) }), e.handleError(r);
1911
- }
1912
- }
1913
- async function _n(e, t, n) {
1914
- if (!z(n) || !G(e, n)) return;
1915
- let r = e.getState().comments, i = r.find((e) => e.id === n);
1916
- e.setState({ comments: r.map((e) => e.id === n ? q(e, "resolved") : e) });
1917
- try {
1918
- let r = await e.apiClient.resolveComment(n);
1919
- e.setState({ comments: e.getState().comments.map((e) => e.id === n ? r : e) }), e.emit("comment:resolved", r), e.emit("comment:updated", r), t.addActivity({
1920
- type: "comment_resolved",
1921
- threadId: n,
1922
- message: "resolved a comment"
1923
- });
1924
- } catch (r) {
1925
- t.shouldQueueMutation(r) && t.queueMutation("resolveComment", [n]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && i ? i : e) }), e.handleError(r));
1926
- }
1927
- }
1928
- async function vn(e, t, n) {
1929
- if (!z(n) || !G(e, n)) return;
1930
- let r = e.getState().comments, i = r.find((e) => e.id === n);
1931
- e.setState({ comments: r.map((e) => e.id === n ? q(e, "open") : e) });
1932
- try {
1933
- let t = await e.apiClient.unresolveComment(n);
1934
- e.setState({ comments: e.getState().comments.map((e) => e.id === n ? t : e) }), e.emit("comment:updated", t);
1935
- } catch (r) {
1936
- t.shouldQueueMutation(r) && t.queueMutation("unresolveComment", [n]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && i ? i : e) }), e.handleError(r));
1937
- }
1938
- }
1939
- async function yn(e, t, n) {
1940
- if (!z(n) || !G(e, n)) return;
1941
- let r = e.getState().comments, i = r.find((e) => e.id === n);
1942
- e.setState({ comments: r.map((e) => e.id === n ? q(e, "complete") : e) });
1943
- try {
1944
- let r = await e.apiClient.markComplete(n);
1945
- e.setState({ comments: e.getState().comments.map((e) => e.id === n ? r : e) }), e.emit("comment:completed", r), t.addActivity({
1946
- type: "comment_completed",
1947
- threadId: n,
1948
- message: "marked a comment as complete"
1949
- });
1950
- } catch (r) {
1951
- t.shouldQueueMutation(r) && t.queueMutation("completeComment", [n]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && i ? i : e) }), e.handleError(r));
1952
- }
1953
- }
1954
- async function bn(e, t, n, r, i) {
1955
- if (!z(n) || typeof r != "string") return;
1956
- let a = r.trim();
1957
- if (!a || a.length > Wt || c(a)) return;
1958
- let o = e.getState().comments.find((e) => e.id === n);
1959
- if (!o) return;
1960
- let s = i ? o.replies.find((e) => e.id === i) : o;
1961
- if (!s) return;
1962
- let l = (s.reactions ?? []).filter((e) => typeof e.emoji == "string" && e.emoji.length > 0 && e.emoji.length <= Wt && !c(e.emoji) && typeof e.count == "number" && Number.isInteger(e.count) && e.count >= 0 && e.count <= Ut), u = l.find((e) => e.emoji === a)?.reacted, d = [...l];
1963
- if (u) {
1964
- let e = d.findIndex((e) => e.emoji === a), t = d[e];
1965
- t.count <= 1 ? d.splice(e, 1) : d[e] = {
1966
- ...t,
1967
- count: t.count - 1,
1968
- reacted: !1
1969
- };
1970
- } else {
1971
- let e = d.findIndex((e) => e.emoji === a), t = e === -1 ? void 0 : d[e];
1972
- t ? d[e] = {
1973
- ...t,
1974
- count: Math.min(t.count + 1, Ut),
1975
- reacted: !0
1976
- } : d.push({
1977
- emoji: a,
1978
- count: 1,
1979
- reacted: !0
1980
- });
1981
- }
1982
- let f = e.getState().comments;
1983
- e.setState({ comments: f.map((e) => e.id === n ? i ? {
1984
- ...e,
1985
- replies: e.replies.map((e) => e.id === i ? {
1986
- ...e,
1987
- reactions: d
1988
- } : e)
1989
- } : {
1990
- ...e,
1991
- reactions: d
1992
- } : e) });
1993
- try {
1994
- u ? await e.apiClient.removeReaction(n, a, ...i ? [i] : []) : await e.apiClient.addReaction(n, a, ...i ? [i] : []);
1995
- let t = e.getState().comments.find((e) => e.id === n);
1996
- t && e.emit("comment:reaction", {
1997
- commentId: n,
1998
- emoji: a,
1999
- comment: t
2000
- });
2001
- } catch (r) {
2002
- t.shouldQueueMutation(r) && t.queueMutation("reactToComment", [
2003
- n,
2004
- a,
2005
- u ? "remove" : "add",
2006
- ...i ? [i] : []
2007
- ]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n ? i ? {
2008
- ...e,
2009
- replies: e.replies.map((e) => e.id === i ? {
2010
- ...e,
2011
- reactions: l
2012
- } : e)
2013
- } : {
2014
- ...e,
2015
- reactions: l
2016
- } : e) }), e.handleError(r));
2017
- }
2018
- }
2019
- async function xn(e, t, n, r, i) {
2020
- if (!z(n) || !G(e, n)) return;
2021
- let a = Yt({
2022
- x: r,
2023
- y: i
2024
- });
2025
- if (!a) {
2026
- R(e, "invalid_position", "Comment position is invalid");
2027
- return;
2028
- }
2029
- let o = e.getState().comments, s = o.find((e) => e.id === n);
2030
- e.setState({ comments: o.map((e) => e.id === n ? {
2031
- ...e,
2032
- position: a
2033
- } : e) });
2034
- try {
2035
- let t = await e.apiClient.updatePosition(n, a);
2036
- e.setState({ comments: e.getState().comments.map((e) => e.id === n ? t : e) }), e.emit("comment:position", {
2037
- commentId: n,
2038
- position: a
2039
- });
2040
- } catch (r) {
2041
- t.shouldQueueMutation(r) && t.queueMutation("updatePosition", [n, a]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && s ? {
2042
- ...e,
2043
- position: s.position
2044
- } : e) }), e.handleError(r));
2045
- }
2046
- }
2047
- function Sn(e, t) {
2048
- e.setState({ selectedComment: t });
2049
- }
2050
- async function Cn(e, t, n, r, i) {
2051
- let a = e.getState().currentUser;
2052
- if (!a) return;
2053
- let o = B(i), s = $t(r);
2054
- if (!o || s == null) {
2055
- R(e, "invalid_highlight", "Highlight data is invalid");
2056
- return;
2057
- }
2058
- let c = `highlight:${s.xpath}:${s.startOffset}:${o.slice(0, 50)}`;
2059
- if (n.has(c)) return;
2060
- n.add(c);
2061
- let l = m(), u = I(e), d = u ? { branch: u } : void 0, f = W("temp"), p = {
2062
- id: f,
2063
- type: "highlight",
2064
- ...u ? { branch: u } : {},
2065
- content: o,
2066
- position: {
2067
- x: 0,
2068
- y: 0
2069
- },
2070
- status: "open",
2071
- priority: "medium",
2072
- author: a,
2073
- userId: a.id,
2074
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2075
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2076
- page: {
2077
- url: l.url,
2078
- path: l.path,
2079
- title: l.title
2080
- },
2081
- replies: [],
2082
- attachments: [],
2083
- textSelection: s
2084
- };
2085
- e.setState({ comments: [...e.getState().comments, p] });
2086
- try {
2087
- let t = await e.apiClient.createHighlight(o, s, l, "medium", f, ...d ? [d] : []);
2088
- K(e, f, t), e.emit("comment:created", t);
2089
- } catch (n) {
2090
- t.shouldQueueMutation(n) && t.queueMutation("createHighlight", [
2091
- o,
2092
- s,
2093
- {
2094
- url: l.url,
2095
- path: l.path,
2096
- title: l.title
2097
- },
2098
- ...d ? [d] : []
2099
- ], f) || (e.setState({ comments: e.getState().comments.filter((e) => e.id !== f) }), e.handleError(n));
2100
- } finally {
2101
- n.delete(c);
2102
- }
2103
- }
2104
- async function wn(e, t, n, r, i, a) {
2105
- let o = e.getState().currentUser;
2106
- if (!o) return;
2107
- let s = B(a), c = Yt(i), l = tn(r);
2108
- if (!s || !c || l == null) {
2109
- R(e, "invalid_drawing", "Drawing comment data is invalid");
2110
- return;
2111
- }
2112
- let u = `drawing:${c.x}:${c.y}:${s.slice(0, 50)}`;
2113
- if (n.has(u)) return;
2114
- n.add(u);
2115
- let d = m(), f = I(e), p = f ? { branch: f } : void 0, h = W("temp"), g = {
2116
- id: h,
2117
- type: "drawing",
2118
- ...f ? { branch: f } : {},
2119
- content: s,
2120
- position: c,
2121
- status: "open",
2122
- priority: "medium",
2123
- author: o,
2124
- userId: o.id,
2125
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2126
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2127
- page: {
2128
- url: d.url,
2129
- path: d.path,
2130
- title: d.title
2131
- },
2132
- replies: [],
2133
- attachments: [],
2134
- drawingData: l
2135
- };
2136
- e.setState({ comments: [...e.getState().comments, g] });
2137
- try {
2138
- let t = await e.apiClient.createDrawing(s, l, c, d, h, ...p ? [p] : []);
2139
- K(e, h, t), e.emit("comment:created", t);
2140
- } catch (n) {
2141
- t.shouldQueueMutation(n) && t.queueMutation("createDrawing", [
2142
- s,
2143
- l,
2144
- c,
2145
- {
2146
- url: d.url,
2147
- path: d.path,
2148
- title: d.title
2149
- },
2150
- ...p ? [p] : []
2151
- ], h) || (e.setState({ comments: e.getState().comments.filter((e) => e.id !== h) }), e.handleError(n));
2152
- } finally {
2153
- n.delete(u);
2154
- }
2155
- }
2156
- var Tn = {
2157
- c: "comment",
2158
- e: "select",
2159
- d: "draw",
2160
- h: "highlight",
2161
- s: "screenshot"
2162
- };
2163
- function En(e) {
2164
- return typeof e.composedPath == "function" ? e.composedPath() : e.target ? [e.target] : [];
2165
- }
2166
- function J(e) {
2167
- return typeof Element < "u" && e instanceof Element;
2168
- }
2169
- function Dn(e) {
2170
- if (!J(e)) return !1;
2171
- let t = e.tagName.toLowerCase();
2172
- return t === "input" || t === "textarea" || t === "select" || e.isContentEditable || e.getAttribute("role") === "textbox";
2173
- }
2174
- function On(e) {
2175
- let t = e.activeElement;
2176
- for (; t?.shadowRoot?.activeElement;) t = t.shadowRoot.activeElement;
2177
- return t;
2178
- }
2179
- function kn(e) {
2180
- return En(e).some(Dn) ? !0 : typeof document > "u" ? !1 : Dn(On(document));
2181
- }
2182
- function An(e) {
2183
- return En(e).some((e) => J(e) && (e.hasAttribute("data-commentkit") || e.hasAttribute("data-commentkit-ui") || e.hasAttribute("data-commentkit-host")));
2184
- }
2185
- var jn = [
2186
- "popover",
2187
- "dialog",
2188
- "alert-dialog",
2189
- "sheet",
2190
- "dropdown-menu",
2191
- "dropdown-menu-sub",
2192
- "select",
2193
- "combobox"
2194
- ].map((e) => `[data-slot="${e}-content"][data-open]`).join(",");
2195
- function Mn(e) {
2196
- let t = En(e), n = t.find((e) => J(e) && e.hasAttribute("data-commentkit-host"));
2197
- if (J(n)) return !!n.shadowRoot?.querySelector(jn);
2198
- if (typeof document < "u" && (t[0] === document.body || t[0] === document.documentElement)) {
2199
- let e = document.querySelectorAll("[data-commentkit-host]");
2200
- return e.length === 1 && !!e[0]?.shadowRoot?.querySelector(jn);
2201
- }
2202
- return !1;
2203
- }
2204
- function Nn(e) {
2205
- return (e.ctrlKey || e.metaKey) && e.shiftKey && (e.key === "K" || e.key === "k" || e.code === "KeyK");
2206
- }
2207
- function Pn(e) {
2208
- let t = e.key.toLowerCase(), n = e.code.startsWith("Key") ? e.code.slice(3).toLowerCase() : "";
2209
- return Tn[t] ?? Tn[n] ?? null;
2210
- }
2211
- function Fn(e) {
2212
- e.preventDefault(), e.stopPropagation();
2213
- }
2214
- function In(e, t) {
2215
- if (e.isLoginModalVisible) t.toggleLoginModal();
2216
- else if (e.isShortcutsOverlayVisible) t.toggleShortcutsOverlay();
2217
- else if (e.activeComment) t.setState({ activeComment: null });
2218
- else if (e.selectedComment) t.selectComment(null);
2219
- else if (e.activeTool) t.setTool(null);
2220
- else if (e.isSidebarVisible) t.toggleSidebar();
2221
- else if (e.isOverlayVisible) t.toggleOverlay();
2222
- else return !1;
2223
- return !0;
2224
- }
2225
- function Ln(e, t) {
2226
- e.isAuthenticated ? t.toggleOverlay() : t.toggleLoginModal();
2227
- }
2228
- function Rn(e, t, n) {
2229
- if (e.defaultPrevented || e.repeat || e.isComposing) return;
2230
- let r = kn(e), i = An(e);
2231
- if (Nn(e)) {
2232
- if (r) return;
2233
- Fn(e), Ln(t, n);
2234
- } else if (e.key === "Escape") {
2235
- if (Mn(e) || r && !i) return;
2236
- In(t, n) && Fn(e);
2237
- } else if (t.isAuthenticated && (t.isOverlayVisible || t.activeTool !== null) && !r && !e.ctrlKey && !e.metaKey && !e.altKey) {
2238
- if (e.key === "?") {
2239
- Fn(e), n.toggleShortcutsOverlay();
2240
- return;
2241
- }
2242
- let r = Pn(e);
2243
- r && (Fn(e), n.setTool(t.activeTool === r ? null : r));
2244
- }
2245
- }
2246
- var zn = M.PENDING_MUTATIONS, Bn = M.RETRY_DELAY, Y = M.ID, Vn = M.CONTENT, Hn = M.REPLY_CONTENT, Un = M.SELECTOR, Wn = M.EMOJI, Gn = /* @__PURE__ */ new Set([
2247
- "createComment",
2248
- "createHighlight",
2249
- "createDrawing",
2250
- "updateComment",
2251
- "deleteComment",
2252
- "resolveComment",
2253
- "unresolveComment",
2254
- "completeComment",
2255
- "addReply",
2256
- "reactToComment",
2257
- "updatePosition"
2258
- ]), Kn = /* @__PURE__ */ new Set([
2259
- "pin",
2260
- "highlight",
2261
- "drawing"
2262
- ]), qn = /* @__PURE__ */ new Set([
2263
- "low",
2264
- "medium",
2265
- "high",
2266
- "urgent"
2267
- ]), Jn = /* @__PURE__ */ new Set(["add", "remove"]);
2268
- function Yn(t) {
2269
- return o(t) && e(t.x) && e(t.y) && n(t.element, Un) && n(t.xpath, Un);
2270
- }
2271
- function Xn(e) {
2272
- return typeof e == "string" && e.length <= M.PAGE && !a(e);
2273
- }
2274
- function Zn(e) {
2275
- return e === void 0 || o(e) && Xn(e.url) && Xn(e.path) && Xn(e.title);
2276
- }
2277
- function Qn(e) {
2278
- return typeof e == "string" && Gn.has(e);
2279
- }
2280
- function $n(e) {
2281
- return Number.isInteger(e) && Number(e) >= 0;
2282
- }
2283
- function er(e) {
2284
- return $n(e) ? Math.min(e, 5) : 0;
2285
- }
2286
- function tr(e) {
2287
- return e.isNetworkError() || e.code === 408 || e.isRateLimitError();
2288
- }
2289
- function nr(e) {
2290
- return e instanceof E ? tr(e) : !0;
2291
- }
2292
- function rr(e) {
2293
- return e instanceof E ? {
2294
- error: e.error,
2295
- message: e.message,
2296
- code: e.code,
2297
- ...e.details ? { details: e.details } : {}
2298
- } : {
2299
- error: "retry_failed",
2300
- message: "Operation failed after maximum retries",
2301
- code: 0
2302
- };
2303
- }
2304
- function ir(e = Date.now()) {
2305
- return `mutation_${e}_${typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : Math.random().toString(36).slice(2, 12)}`;
2306
- }
2307
- function ar(e) {
2308
- return Array.isArray(e) ? e.map((e) => ar(e)) : o(e) ? Object.fromEntries(Object.entries(e).map(([e, t]) => [e, ar(t)])) : e;
2309
- }
2310
- function or(e) {
2311
- try {
2312
- if (typeof structuredClone == "function") return structuredClone(e);
2313
- } catch {}
2314
- return ar(e);
2315
- }
2316
- function sr(e, t) {
2317
- switch (e) {
2318
- case "createComment": {
2319
- let [e, n, r, a, s, c, l, u] = t;
2320
- return t.length >= 3 && t.length <= 8 && Kn.has(String(e)) && i(n, Vn) && Yn(r) && (a === void 0 || qn.has(String(a))) && (s === void 0 || o(s)) && (c === void 0 || o(c)) && (l === void 0 || o(l)) && Zn(u);
2321
- }
2322
- case "createHighlight": {
2323
- let [e, n, r, a] = t;
2324
- return t.length >= 2 && t.length <= 4 && i(e, Vn) && o(n) && (a === void 0 || o(a)) && Zn(r);
2325
- }
2326
- case "createDrawing": {
2327
- let [e, n, r, a, s] = t;
2328
- return t.length >= 3 && t.length <= 5 && i(e, Vn) && o(n) && Yn(r) && (s === void 0 || o(s)) && Zn(a);
2329
- }
2330
- case "updateComment": return t.length === 2 && r(t[0], Y) && o(t[1]);
2331
- case "deleteComment":
2332
- case "resolveComment":
2333
- case "unresolveComment":
2334
- case "completeComment": return t.length === 1 && r(t[0], Y);
2335
- case "addReply": return (t.length === 2 || t.length === 3) && r(t[0], Y) && i(t[1], Hn) && (t[2] === void 0 || o(t[2]));
2336
- case "reactToComment": return t.length >= 2 && t.length <= 4 && r(t[0], Y) && r(t[1], Wn) && (t[2] === void 0 || Jn.has(String(t[2]))) && (t[3] === void 0 || r(t[3], Y));
2337
- case "updatePosition": return t.length === 2 && r(t[0], Y) && Yn(t[1]);
2338
- }
2339
- }
2340
- function cr(e) {
2341
- return o(e) ? r(e.id, Y) ? e.ownerId !== void 0 && !r(e.ownerId, Y) ? "Queued mutation has an invalid owner id" : Qn(e.type) ? Array.isArray(e.args) ? Number.isFinite(e.timestamp) ? $n(e.retries) ? n(e.tempId, Y) ? sr(e.type, e.args) ? null : "Queued mutation args are invalid" : "Queued mutation has an invalid temp id" : "Queued mutation has an invalid retry count" : "Queued mutation has an invalid timestamp" : "Queued mutation args must be an array" : "Queued mutation has an unsupported type" : "Queued mutation has an invalid id" : "Queued mutation must be an object";
2342
- }
2343
- function lr(e) {
2344
- let t = cr(e);
2345
- if (t) throw new E("invalid_mutation", t, 400);
2346
- }
2347
- var ur = "commentkit:offline-queue:";
2348
- function dr() {
2349
- try {
2350
- return typeof localStorage > "u" ? null : localStorage;
2351
- } catch {
2352
- return null;
2353
- }
2354
- }
2355
- function fr(e) {
2356
- return `${ur}${e}`;
2357
- }
2358
- function pr(e, t) {
2359
- if (!e) return;
2360
- let n = dr();
2361
- if (n) try {
2362
- t.length === 0 ? n.removeItem(fr(e)) : n.setItem(fr(e), JSON.stringify(t));
2363
- } catch {}
2364
- }
2365
- function mr(e) {
2366
- if (!e) return [];
2367
- let t = dr();
2368
- if (!t) return [];
2369
- try {
2370
- let n = t.getItem(fr(e));
2371
- if (!n) return [];
2372
- let r = JSON.parse(n);
2373
- if (!Array.isArray(r)) return [];
2374
- let i = [];
2375
- for (let e of r) {
2376
- if (i.length >= zn) break;
2377
- cr(e) === null && i.push(e);
2378
- }
2379
- return i;
2380
- } catch {
2381
- return [];
2382
- }
2383
- }
2384
- function X(e) {
2385
- Promise.resolve().then(e);
2386
- }
2387
- function hr(e, t) {
2388
- if (e.type !== t.type || e.ownerId !== t.ownerId) return !1;
2389
- if (t.type === "updateComment") {
2390
- let n = e.args[1]?.checklistPatch, r = t.args[1]?.checklistPatch;
2391
- if ((n || r) && n?.id !== r?.id) return !1;
2392
- }
2393
- return (t.type === "updatePosition" || t.type === "updateComment") && e.args[0] === t.args[0];
2394
- }
2395
- function gr(e, t) {
2396
- return t.type === "updateComment" && o(e.args[1]) ? {
2397
- ...t,
2398
- args: [t.args[0], {
2399
- ...e.args[1],
2400
- ...t.args[1]
2401
- }]
2402
- } : t;
2403
- }
2404
- function _r(e, t) {
2405
- let n = e.findIndex((e) => hr(e, t));
2406
- if (n !== -1) {
2407
- let r = [...e];
2408
- return r[n] = gr(r[n], t), r;
2409
- }
2410
- return e.length >= zn ? null : [...e, t];
2411
- }
2412
- function Z(e, t, n) {
2413
- e.emit("offline:failed", {
2414
- id: t,
2415
- error: n
2416
- });
2417
- }
2418
- function vr(e, t) {
2419
- return t.isAuthenticated && e.ownerId && e.ownerId === t.currentUser?.id ? null : {
2420
- error: "offline_identity_mismatch",
2421
- message: e.ownerId ? "Offline change belongs to a different signed-in user and was discarded." : "Offline change has no verified author and was discarded. Please submit it again.",
2422
- code: 403
2423
- };
2424
- }
2425
- function yr(e) {
2426
- let t = e.getState();
2427
- if (!t.isAuthenticated) return;
2428
- let n = t.pendingMutations.flatMap((e) => {
2429
- let n = vr(e, t);
2430
- return n ? [{
2431
- mutation: e,
2432
- error: n
2433
- }] : [];
2434
- });
2435
- if (n.length === 0) return;
2436
- let r = new Set(n.map(({ mutation: e }) => e.id));
2437
- e.setState({ pendingMutations: t.pendingMutations.filter((e) => !r.has(e.id)) });
2438
- for (let { mutation: t, error: r } of n) Z(e, t.id, r);
2439
- }
2440
- function br(e, t) {
2441
- return !e.isOnline || t instanceof E && tr(t);
2442
- }
2443
- function xr(e, t, i, a, o) {
2444
- let s = ir(), c = e.getState(), l = c.currentUser?.id;
2445
- if (!c.isAuthenticated || !r(l, Y)) return Z(e, s, {
2446
- error: "unauthenticated",
2447
- message: "Sign in before saving changes for offline replay.",
2448
- code: 401
2449
- }), !1;
2450
- if (!Qn(i) || !Array.isArray(a) || !sr(i, a) || !n(o, Y)) return Z(e, s, {
2451
- error: "invalid_mutation",
2452
- message: "Queued mutation args are invalid",
2453
- code: 400
2454
- }), !1;
2455
- let u = {
2456
- id: s,
2457
- ownerId: l,
2458
- type: i,
2459
- args: or(a),
2460
- timestamp: Date.now(),
2461
- retries: 0,
2462
- ...o === void 0 ? {} : { tempId: o }
2463
- }, d = _r(e.getState().pendingMutations, u);
2464
- return d ? (e.setState({ pendingMutations: d }), e.emit("offline:queued", u), e.getState().isOnline && X(t), !0) : (Z(e, s, {
2465
- error: "queue_full",
2466
- message: "Offline mutation queue is full",
2467
- code: 0
2468
- }), !1);
2469
- }
2470
- function Sr(e, t, n) {
2471
- if (t.current || e.getState().pendingMutations.length === 0) return;
2472
- let r = e.getState().pendingMutations[0];
2473
- if (!r) return;
2474
- let i = er(r.retries), a = Math.min(Bn, At * 2 ** i);
2475
- t.current = setTimeout(() => {
2476
- t.current = null, n();
2477
- }, a);
2478
- }
2479
- async function Cr(e, t, n, i) {
2480
- let a = e.getState();
2481
- if (!a.isOnline || a.pendingMutations.length === 0 || !a.isAuthenticated || t.current) return;
2482
- t.current = !0;
2483
- let o = e.getState().pendingMutations[0];
2484
- if (!o) {
2485
- t.current = !1;
2486
- return;
2487
- }
2488
- let s = cr(o), c = s ? {
2489
- error: "invalid_mutation",
2490
- message: s,
2491
- code: 400
2492
- } : vr(o, e.getState());
2493
- if (c) {
2494
- let i = e.getState().pendingMutations.filter((e) => e !== o);
2495
- e.setState({ pendingMutations: i }), Z(e, r(o.id, Y) ? o.id : "invalid", c), i.length > 0 && X(n), t.current = !1;
2496
- return;
2497
- }
2498
- e.emit("offline:retrying", {
2499
- id: o.id,
2500
- attempt: o.retries + 1
2501
- });
2502
- let l = i ?? ((t) => Dr(e, t));
2503
- try {
2504
- await l(o);
2505
- let r = e.getState().pendingMutations.filter((e) => e.id !== o.id);
2506
- e.setState({ pendingMutations: r }), e.emit("offline:completed", { id: o.id }), r.length > 0 ? X(n) : t.reconcileAfterDrain && (t.reconcileAfterDrain = !1, cn(e));
2507
- } catch (r) {
2508
- let i = {
2509
- ...o,
2510
- retries: er(o.retries) + 1
2511
- };
2512
- if (nr(r) && i.retries < 5) {
2513
- let t = e.getState().pendingMutations.map((e) => e.id === o.id ? i : e);
2514
- e.setState({ pendingMutations: t }), X(n);
2515
- } else {
2516
- let i = e.getState().pendingMutations.filter((e) => e.id !== o.id);
2517
- e.setState({ pendingMutations: i }), Z(e, o.id, rr(r)), i.length > 0 ? (t.reconcileAfterDrain = !0, X(n)) : (t.reconcileAfterDrain = !1, cn(e));
2518
- }
2519
- } finally {
2520
- t.current = !1;
2521
- }
2522
- }
2523
- function wr(e, t, n) {
2524
- let r = !1, i = e.getState().pendingMutations.map((e) => e.type !== "createComment" && e.type !== "createHighlight" && e.type !== "createDrawing" && e.args[0] === t ? (r = !0, {
2525
- ...e,
2526
- args: [n, ...e.args.slice(1)]
2527
- }) : e);
2528
- r && e.setState({ pendingMutations: i });
2529
- }
2530
- function Tr(e, t, n) {
2531
- let r = e.getState(), i = (e) => e === t || e === n;
2532
- e.setState({
2533
- comments: r.comments.filter((e) => !i(e.id)),
2534
- selectedComment: r.selectedComment && i(r.selectedComment.id) ? null : r.selectedComment,
2535
- activeComment: r.activeComment && i(r.activeComment.id) ? null : r.activeComment
2536
- });
2537
- }
2538
- function Q(e, t, n, r, i = !1) {
2539
- let a = e.getState(), o = a.comments.find((e) => e.id === r || e.id === n.id), s = n, c = (e) => {
2540
- s.status !== e && (s = {
2541
- ...s,
2542
- status: e,
2543
- completedAt: void 0,
2544
- ...e === "complete" ? {} : { resolvedAt: void 0 }
2545
- });
2546
- };
2547
- for (let i of a.pendingMutations) if (!(i.id === t.id || i.ownerId !== t.ownerId || i.args[0] !== r && i.args[0] !== n.id)) switch (i.type) {
2548
- case "deleteComment":
2549
- Tr(e, n.id, r);
2550
- return;
2551
- case "updateComment":
2552
- i.args[1].status && c(i.args[1].status);
2553
- {
2554
- let { checklistPatch: e, ...t } = i.args[1];
2555
- s = {
2556
- ...s,
2557
- ...t
2558
- }, e && (s.checklist = s.checklist?.map((t) => t.id === e.id ? {
2559
- ...t,
2560
- done: e.done
2561
- } : t));
2562
- }
2563
- break;
2564
- case "resolveComment":
2565
- c("resolved");
2566
- break;
2567
- case "unresolveComment":
2568
- c("open");
2569
- break;
2570
- case "completeComment":
2571
- c("complete");
2572
- break;
2573
- case "updatePosition":
2574
- s = {
2575
- ...s,
2576
- position: i.args[1]
2577
- };
2578
- break;
2579
- case "addReply": {
2580
- let e = o?.replies.find((e) => e.id === i.tempId);
2581
- e && !s.replies.some((t) => t.id === e.id) && (s = {
2582
- ...s,
2583
- replies: [...s.replies, e]
2584
- }), c("open");
2585
- break;
2586
- }
2587
- case "reactToComment": !i.args[3] && o && (s = {
2588
- ...s,
2589
- reactions: o.reactions
2590
- });
2591
- }
2592
- i ? K(e, r, s) : e.setState({ comments: a.comments.map((e) => e.id === r ? s : e) });
2593
- }
2594
- function Er(e, t, n, r) {
2595
- e.setState({ pendingMutations: e.getState().pendingMutations.map((e) => e.type === "reactToComment" && e.args[0] === t && e.args[3] === n ? {
2596
- ...e,
2597
- args: [...e.args.slice(0, 3), r]
2598
- } : e) });
2599
- }
2600
- async function Dr(e, t) {
2601
- lr(t);
2602
- let n = vr(t, e.getState());
2603
- if (n) throw new E(n.error, n.message, n.code);
2604
- switch (t.type) {
2605
- case "createComment": {
2606
- let [n, r, i, a, o, s, c, l] = t.args, u = await e.apiClient.createComment(n, r, i, l ?? m(), a, o, s, c, t.tempId);
2607
- u && t.tempId && (Q(e, t, u, t.tempId, !0), wr(e, t.tempId, u.id));
2608
- break;
2609
- }
2610
- case "createHighlight": {
2611
- let [n, r, i, a] = t.args, o = await e.apiClient.createHighlight(n, r, i ?? m(), "medium", t.tempId, ...a ? [a] : []);
2612
- o && t.tempId && (Q(e, t, o, t.tempId, !0), wr(e, t.tempId, o.id));
2613
- break;
2614
- }
2615
- case "createDrawing": {
2616
- let [n, r, i, a, o] = t.args, s = await e.apiClient.createDrawing(n, r, i, a ?? m(), t.tempId, ...o ? [o] : []);
2617
- s && t.tempId && (Q(e, t, s, t.tempId, !0), wr(e, t.tempId, s.id));
2618
- break;
2619
- }
2620
- case "updateComment": {
2621
- let [n, r] = t.args, i = await e.apiClient.updateComment(n, r);
2622
- i && Q(e, t, i, n);
2623
- break;
2624
- }
2625
- case "deleteComment": {
2626
- let [n] = t.args;
2627
- await e.apiClient.deleteComment(n), Tr(e, n);
2628
- break;
2629
- }
2630
- case "resolveComment": {
2631
- let [n] = t.args, r = await e.apiClient.resolveComment(n);
2632
- r && Q(e, t, r, n);
2633
- break;
2634
- }
2635
- case "unresolveComment": {
2636
- let [n] = t.args, r = await e.apiClient.unresolveComment(n);
2637
- r && Q(e, t, r, n);
2638
- break;
2639
- }
2640
- case "completeComment": {
2641
- let [n] = t.args, r = await e.apiClient.markComplete(n);
2642
- r && Q(e, t, r, n);
2643
- break;
2644
- }
2645
- case "addReply": {
2646
- let [n, r, i] = t.args, a = await e.apiClient.addReply(n, r, t.tempId, ...i ? [i] : []);
2647
- if (a && t.tempId) {
2648
- let r = e.getState().comments.find((e) => e.id === n), i = e.getState().pendingMutations.some((e) => e.type === "reactToComment" && e.ownerId === t.ownerId && e.args[0] === n && e.args[3] === t.tempId), o = r?.replies.find((e) => e.id === t.tempId);
2649
- on(e, n, t.tempId, i && o ? {
2650
- ...a,
2651
- reactions: o.reactions
2652
- } : a), Er(e, n, t.tempId, a.id);
2653
- let s = e.getState().comments.find((e) => e.id === n);
2654
- s && Q(e, t, s, n);
2655
- }
2656
- break;
2657
- }
2658
- case "reactToComment": {
2659
- let [n, r, i, a] = t.args, o;
2660
- o = i === "add" || i === "remove" ? i === "remove" : e.getState().comments.find((e) => e.id === n)?.reactions?.find((e) => e.emoji === r)?.reacted === !0, o ? await e.apiClient.removeReaction(n, r, ...a ? [a] : []) : await e.apiClient.addReaction(n, r, ...a ? [a] : []);
2661
- break;
2662
- }
2663
- case "updatePosition": {
2664
- let [n, r] = t.args, i = await e.apiClient.updatePosition(n, r);
2665
- i && Q(e, t, i, n);
2666
- break;
2667
- }
2668
- }
2669
- }
2670
- var $ = null;
2671
- async function Or() {
2672
- return $ || ($ = await import("./realtime-yGLX4wMK.js"), $);
2673
- }
2674
- var kr = typeof window < "u", Ar = /* @__PURE__ */ new Set([
2675
- "list",
2676
- "detail",
2677
- "settings",
2678
- "activity",
2679
- "dev-export"
2680
- ]), jr = /* @__PURE__ */ new Set([
2681
- "comment",
2682
- "draw",
2683
- "highlight",
2684
- "screenshot",
2685
- "select",
2686
- null
2687
- ]), Mr = 256, Nr = "0.7.7";
2688
- function Pr(e) {
2689
- let t = e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);
2690
- return t ? [
2691
- Number(t[1]),
2692
- Number(t[2] ?? 0),
2693
- Number(t[3] ?? 0)
2694
- ] : null;
2695
- }
2696
- function Fr(e) {
2697
- return /^v?\d+(?:\.\d+)?(?:\.\d+)?-/.test(e.trim());
2698
- }
2699
- function Ir(e, t) {
2700
- if (Fr(e)) return !1;
2701
- let n = Pr(e), r = Pr(t);
2702
- if (!n || !r) return !1;
2703
- for (let e = 0; e < 3; e++) {
2704
- let t = n[e] ?? 0, i = r[e] ?? 0;
2705
- if (t > i) return !0;
2706
- if (t < i) return !1;
2707
- }
2708
- return !1;
2709
- }
2710
- var Lr = class extends et {
2711
- get isProcessingQueue() {
2712
- return this.queueGuard.current;
2713
- }
2714
- set isProcessingQueue(e) {
2715
- this.queueGuard.current = e;
2716
- }
2717
- get isLoadingMore() {
2718
- return this.loadMoreGuard.current;
2719
- }
2720
- set isLoadingMore(e) {
2721
- this.loadMoreGuard.current = e;
2722
- }
2723
- get retryTimer() {
2724
- return this.retryTimerRef.current;
2725
- }
2726
- set retryTimer(e) {
2727
- this.retryTimerRef.current = e;
2728
- }
2729
- constructor(e, t) {
2730
- super(), this.wsManager = null, this.wsUnsubscribers = [], this.keyboardHandler = null, this.holdActivationHandler = null, this.holdBlurHandler = null, this.toggleHandler = null, this.mouseMoveHandler = null, this.hashChangeHandler = null, this.onlineHandler = null, this.offlineHandler = null, this.initialized = !1, this.destroyed = !1, this.sessionRevision = 0, this.writeRestriction = null, this.authRequestRevision = 0, this.commentsFetchRevision = 0, this.contextFetchRevision = 0, this.deepLinkRequest = null, this.reactionRequests = /* @__PURE__ */ new Map(), this.draftUploads = /* @__PURE__ */ new WeakMap(), this.attachmentRefreshes = /* @__PURE__ */ new Map(), this.screenshotProvider = null, this.bootRetryTimer = null, this.bootAttempts = 0, this.pendingStateUpdates = null, this.flushScheduled = !1, this.isFlushing = !1, this.queueGuard = { current: !1 }, this.activeMutations = /* @__PURE__ */ new Set(), this.sliceSubscribers = /* @__PURE__ */ new Map(), this.retryTimerRef = { current: null }, this.otpFailedAttempts = 0, this.otpCooldownUntil = 0, this.overlayBeforeTool = null, this.loadMoreGuard = { current: !1 }, this.offlinePersistUnsub = null, this.escapeBlockers = /* @__PURE__ */ new Set();
2731
- let { authToken: n, ...r } = e;
2732
- this.config = r, this.initialAuthToken = n, this.localDemo = t ?? null, this.localDemo && (this.config.features = {
2733
- comments: !0,
2734
- drawing: !1,
2735
- highlighting: !1,
2736
- screenshots: !1,
2737
- realtime: !1
2738
- }, this.config.ui = {
2739
- ...this.config.ui,
2740
- loadRemoteFonts: !1
2741
- }), kr && !this.config.environment && (this.config.environment = this.detectEnvironment()), this.apiClient = this.localDemo?.client ?? new ve(this.config), this.apiClient.setOnAuthExpired(() => this.handleAuthExpired()), this.state = jt(), this.state.activeBranch = typeof e.branch == "string" && e.branch.trim().length <= 255 && !a(e.branch) && e.branch.trim() || null, this.requiresShortcut() && (this.state.isOverlayVisible = !1), this.screenshotProvider = e.screenshotProvider || null, this.ctx = {
2742
- getState: () => this.getInternalState(),
2743
- setState: (e) => this.setState(e),
2744
- apiClient: this.apiClient,
2745
- emit: (e, t) => {
2746
- this.destroyed || this.emit(e, t);
2747
- },
2748
- handleError: (e) => this.handleError(e),
2749
- config: this.config,
2750
- isLocalDemo: !!this.localDemo
2751
- }, this.kbdCallbacks = {
2752
- toggleLoginModal: () => this.toggleLoginModal(),
2753
- toggleOverlay: () => this.toggleOverlay(),
2754
- toggleSidebar: () => this.toggleSidebar(),
2755
- toggleShortcutsOverlay: () => this.toggleShortcutsOverlay(),
2756
- setTool: (e) => this.setTool(e),
2757
- selectComment: (e) => this.selectComment(e),
2758
- setState: (e) => this.setState(e)
2759
- }, this.commentCb = {
2760
- shouldQueueMutation: (e) => this.shouldQueueMutation(e),
2761
- queueMutation: (e, t, n) => this.queueMutation(e, t, n),
2762
- addActivity: (e) => this.addActivity(e)
2763
- }, this.realtimeRefs = {
2764
- wsManager: this.wsManager,
2765
- wsUnsubscribers: this.wsUnsubscribers,
2766
- mouseMoveHandler: this.mouseMoveHandler
2767
- }, this.localDemo && (this.restoreDemoState(), this.localDemo.subscribe((e) => {
2768
- e !== "persist" && this.restoreDemoState();
2769
- })), e.enabled !== !1 && kr && Promise.resolve().then(() => this.boot()).catch((e) => this.handleError(e));
2770
- /* v8 ignore stop */
2771
- }
2772
- isLocalDemo() {
2773
- return this.localDemo !== null;
2774
- }
2775
- restoreDemoState() {
2776
- if (!this.localDemo || this.destroyed) return;
2777
- let e = this.localDemo.getSession().expired, t = this.getInternalState().activeBranch ?? null;
2778
- this.overlayBeforeTool = null, this.setState({
2779
- ...jt(),
2780
- currentUser: e ? null : { ...this.localDemo.user },
2781
- isAuthenticated: !e,
2782
- isOverlayVisible: !e,
2783
- isOnline: !0,
2784
- activeBranch: t,
2785
- comments: this.localDemo.getComments().filter((e) => !t || e.branch === t),
2786
- project: {
2787
- id: "local-demo",
2788
- slug: "local-demo",
2789
- name: "Private browser demo",
2790
- url: window.location.origin,
2791
- features: {
2792
- comments: !0,
2793
- drawing: !1,
2794
- highlighting: !1,
2795
- screenshots: !1,
2796
- realtime: !1
2797
- },
2798
- limits: {
2799
- maxMembers: 1,
2800
- retentionDays: 1
2801
- }
2802
- }
2803
- });
2804
- }
2805
- startLocalDemo() {
2806
- this.localDemo && !this.destroyed && (this.localDemo.activate(), this.setState({
2807
- isOverlayVisible: !0,
2808
- isSidebarVisible: !1,
2809
- isLoginModalVisible: !1,
2810
- error: null
2811
- }), this.setTool("comment"));
2812
- }
2813
- detectEnvironment() {
2814
- let e = window.location.hostname;
2815
- return e === "localhost" || e === "127.0.0.1" || e === "[::1]" || e.endsWith(".localhost") ? "development" : e.endsWith(".vercel.app") || e.endsWith(".netlify.app") || e.endsWith(".pages.dev") || e.includes("-preview.") || e.endsWith("-preview") || /-preview-\d/.test(e) ? "preview" : e.startsWith("staging.") || e.startsWith("stage.") || e.includes(".staging.") || e.endsWith(".staging") ? "staging" : "production";
2816
- }
2817
- async boot() {
2818
- if (this.destroyed) return;
2819
- this.keyboardHandler = this.handleKeyboardShortcuts.bind(this), window.addEventListener("keydown", this.keyboardHandler, !0);
2820
- let e = this.config.ui?.activation;
2821
- e?.mode === "hold" && e.key && (this.holdActivationHandler = (e) => {
2822
- if (this.destroyed || !this.matchesHoldKey(e)) return;
2823
- let t = this.getInternalState().activeTool;
2824
- e.type === "keydown" && !t && !j() ? this.setTool("select") : e.type === "keyup" && t === "select" && this.setTool(null);
2825
- }, window.addEventListener("keydown", this.holdActivationHandler), window.addEventListener("keyup", this.holdActivationHandler), this.holdBlurHandler = () => {
2826
- this.destroyed || this.getInternalState().activeTool === "select" && this.setTool(null);
2827
- }, window.addEventListener("blur", this.holdBlurHandler)), this.toggleHandler = () => this.handleToggleRequest(), window.addEventListener("commentkit:toggle-overlay", this.toggleHandler), this.hashChangeHandler = () => this.handleDeepLink(), window.addEventListener("hashchange", this.hashChangeHandler), this.handleDeepLink(), !this.localDemo && (this.onlineHandler = () => {
2828
- this.destroyed || (this.setState({ isOnline: !0 }), this.processOfflineQueue());
2829
- }, this.offlineHandler = () => {
2830
- this.destroyed || this.setState({ isOnline: !1 });
2831
- }, window.addEventListener("online", this.onlineHandler), window.addEventListener("offline", this.offlineHandler), this.autoDetectInviteToken(), this.config.apiKey && await this.initialize());
2832
- }
2833
- autoDetectInviteToken() {
2834
- try {
2835
- let e = new URLSearchParams(window.location.search), t = e.get("ck_invite");
2836
- if (!t) return;
2837
- /^[\w-]{64}$/.test(t) && (this.config.inviteToken = t), e.delete("ck_invite");
2838
- let n = e.toString(), r = window.location.pathname + (n ? `?${n}` : "") + window.location.hash;
2839
- window.history.replaceState(window.history.state, "", r);
2840
- } catch {}
2841
- }
2842
- async initialize() {
2843
- if (!(this.initialized || this.destroyed)) {
2844
- this.initialized = !0, this.bootAttempts += 1;
2845
- try {
2846
- this.setState({
2847
- isLoading: !0,
2848
- error: null
2849
- });
2850
- let e = await this.apiClient.validateApiKey();
2851
- if (this.destroyed) return;
2852
- if (!e.valid) {
2853
- this.handleError({
2854
- error: "invalid_api_key",
2855
- message: "Invalid API key",
2856
- code: 401
2857
- });
2858
- return;
2859
- }
2860
- e.project?.id && (this.config.projectId = String(e.project.id), this.hydrateOfflineQueue());
2861
- let t = e.project?.slug ?? e.project?.id;
2862
- if (t && this.apiClient.setProject(String(t), this.config.projectId), e.project?.features && (this.config.features = e.project.features), e.project?.reverb && e.project.features?.realtime) {
2863
- let t = e.project.reverb;
2864
- this.config.reverb = {
2865
- key: t.key,
2866
- host: t.host,
2867
- port: t.port ?? 443,
2868
- scheme: t.scheme ?? "wss"
2869
- };
2870
- }
2871
- let n = e.project?.sdkLatestVersion;
2872
- n && Ir(n, "0.7.7") && (console.warn(`[CommentKit] You are using v${Nr}. Update to v${n}: npm update @commentkit/comment-kit`), this.emit("sdk:outdated", {
2873
- current: Nr,
2874
- latest: n
2875
- })), this.setState({
2876
- project: e.project,
2877
- isLoading: !1
2878
- }), await this.restorePersistedSession();
2879
- } catch (e) {
2880
- if (this.initialized = !1, this.handleError(e), this.bootAttempts < 3 && !this.destroyed) {
2881
- let e = 2e3 * 2 ** (this.bootAttempts - 1);
2882
- this.bootRetryTimer = setTimeout(() => {
2883
- this.bootRetryTimer = null, this.initialize();
2884
- }, e);
2885
- }
2886
- }
2887
- }
2888
- }
2889
- setState(e) {
2890
- this.destroyed || (e.activeTool === null && e.isOverlayVisible === void 0 && this.overlayBeforeTool !== null && (e = {
2891
- ...e,
2892
- isOverlayVisible: this.overlayBeforeTool
2893
- }, this.overlayBeforeTool = null), this.pendingStateUpdates ? Object.assign(this.pendingStateUpdates, e) : this.pendingStateUpdates = { ...e }, this.flushScheduled || (this.flushScheduled = !0, Promise.resolve().then(() => this.flushState())));
2894
- }
2895
- getInternalState() {
2896
- return this.localDemo?.checkExpiry(), this.pendingStateUpdates ? {
2897
- ...this.state,
2898
- ...this.pendingStateUpdates
2899
- } : this.state;
2900
- }
2901
- cloneStateSnapshot(e) {
2902
- return {
2903
- ...e,
2904
- currentUser: e.currentUser ? structuredClone(e.currentUser) : null,
2905
- project: e.project ? structuredClone(e.project) : null,
2906
- projectContext: e.projectContext ? structuredClone(e.projectContext) : null,
2907
- comments: structuredClone(e.comments),
2908
- commentQuery: e.commentQuery ? { ...e.commentQuery } : void 0,
2909
- selectedComment: e.selectedComment ? structuredClone(e.selectedComment) : null,
2910
- activeComment: e.activeComment ? structuredClone(e.activeComment) : null,
2911
- activeDrawing: e.activeDrawing ? structuredClone(e.activeDrawing) : null,
2912
- activeScreenshot: e.activeScreenshot ? {
2913
- ...e.activeScreenshot,
2914
- dimensions: { ...e.activeScreenshot.dimensions }
2915
- } : null,
2916
- onlineUsers: structuredClone(e.onlineUsers),
2917
- pendingMutations: structuredClone(e.pendingMutations),
2918
- activities: structuredClone(e.activities),
2919
- seenThreadIds: new Set(e.seenThreadIds),
2920
- pagination: e.pagination ? { ...e.pagination } : null
2921
- };
2922
- }
2923
- flushState() {
2924
- if (this.destroyed) {
2925
- this.pendingStateUpdates = null, this.flushScheduled = !1;
2926
- return;
2927
- }
2928
- if (this.isFlushing) return;
2929
- this.flushScheduled = !1;
2930
- let e = this.pendingStateUpdates;
2931
- if (!e) return;
2932
- this.pendingStateUpdates = null;
2933
- let t = this.state;
2934
- this.state = {
2935
- ...t,
2936
- ...e
2937
- }, this.isFlushing = !0;
2938
- try {
2939
- this.notifySubscribers(e, t);
2940
- } finally {
2941
- this.isFlushing = !1;
2942
- }
2943
- this.pendingStateUpdates && !this.flushScheduled && (this.flushScheduled = !0, Promise.resolve().then(() => this.flushState()));
2944
- }
2945
- notifySubscribers(e, t) {
2946
- e.activeTool !== void 0 && e.activeTool !== t.activeTool && this.emit("tool:changed", e.activeTool), e.isOverlayVisible !== void 0 && e.isOverlayVisible !== t.isOverlayVisible && this.emit("overlay:toggled", e.isOverlayVisible), e.isSidebarVisible !== void 0 && e.isSidebarVisible !== t.isSidebarVisible && this.emit("sidebar:toggled", e.isSidebarVisible), e.isLoginModalVisible !== void 0 && e.isLoginModalVisible !== t.isLoginModalVisible && this.emit("loginmodal:toggled", e.isLoginModalVisible), e.isShortcutsOverlayVisible !== void 0 && e.isShortcutsOverlayVisible !== t.isShortcutsOverlayVisible && this.emit("shortcuts:toggled", e.isShortcutsOverlayVisible), e.connectionStatus !== void 0 && e.connectionStatus !== t.connectionStatus && this.emit("connection:changed", e.connectionStatus);
2947
- let n = Object.keys(e);
2948
- for (let [e, t] of this.sliceSubscribers) {
2949
- let r = Ot[e];
2950
- if (n.some((e) => r.includes(e))) for (let n of t) try {
2951
- n(this.state);
2952
- } catch (t) {
2953
- console.error(`[CommentKit] Error in ${e} slice subscriber:`, t);
2954
- }
2955
- }
2956
- this.emit("state:changed", this.state);
2957
- }
2958
- flushStateSync() {
2959
- this.pendingStateUpdates && !this.isFlushing && this.flushState();
2960
- }
2961
- getState() {
2962
- return this.localDemo?.checkExpiry(), this.flushStateSync(), this.cloneStateSnapshot(this.state);
2963
- }
2964
- getFeatures() {
2965
- let e = this.canWriteComments();
2966
- return {
2967
- comments: e,
2968
- drawing: e && (this.config.features?.drawing ?? !0),
2969
- highlighting: e && (this.config.features?.highlighting ?? !0),
2970
- screenshots: e && (this.config.features?.screenshots ?? !0),
2971
- realtime: this.config.features?.realtime ?? !0
2972
- };
2973
- }
2974
- canWriteComments() {
2975
- return this.getWriteAccess().canWrite;
2976
- }
2977
- getWriteAccess() {
2978
- return Xe(this.config, this.getInternalState(), this.writeRestriction);
2979
- }
2980
- requireCommentWrite() {
2981
- let e = this.getWriteAccess();
2982
- return e.canWrite ? !0 : (this.handleError({
2983
- error: e.planRequired ? "plan_required" : "feature_disabled",
2984
- message: e.message,
2985
- code: e.planRequired ? 402 : 403
2986
- }), !1);
2987
- }
2988
- getConfig() {
2989
- return {
2990
- apiKey: this.config.apiKey,
2991
- ...this.config.baseUrl !== void 0 && { baseUrl: this.config.baseUrl },
2992
- ...this.config.enabled !== void 0 && { enabled: this.config.enabled },
2993
- screenshotProvider: this.config.screenshotProvider,
2994
- branch: this.config.branch,
2995
- persistence: this.config.persistence,
2996
- realtime: this.config.realtime ? { ...this.config.realtime } : void 0,
2997
- ui: this.config.ui ? { ...this.config.ui } : void 0
2998
- };
2999
- }
3000
- async validateInvite(e) {
3001
- if (this.destroyed || this.localDemo) return;
3002
- let t = this.beginAuthRequest();
3003
- return Dt(this.ctx, e, (e) => bt(this.ctx, e, t), t);
3004
- }
3005
- onSlice(e, t) {
3006
- if (!Ot[e] || typeof t != "function" || this.destroyed) return () => {};
3007
- let n = this.sliceSubscribers.get(e);
3008
- return n || (n = /* @__PURE__ */ new Set(), this.sliceSubscribers.set(e, n)), n.add(t), () => n.delete(t);
3009
- }
3010
- select(e, t) {
3011
- if (typeof e != "function" || typeof t != "function" || this.destroyed) return () => {};
3012
- let n;
3013
- try {
3014
- n = e(this.getInternalState());
3015
- } catch (e) {
3016
- return this.handleError(e), () => {};
3017
- }
3018
- return this.on("state:changed", (r) => {
3019
- try {
3020
- let i = e(r);
3021
- i !== n && (n = i, t(i));
3022
- } catch (e) {
3023
- this.handleError(e);
3024
- }
3025
- });
3026
- }
3027
- handleError(e) {
3028
- if (this.destroyed) return;
3029
- let t = e && typeof e == "object" ? e : null, n = typeof t?.message == "string" && t.message ? t.message : String(e ?? "Unknown error"), r = {
3030
- error: typeof t?.error == "string" && t.error ? t.error : "unknown",
3031
- message: n,
3032
- code: typeof t?.code == "number" && Number.isFinite(t.code) ? t.code : 0,
3033
- ...t?.details && typeof t.details == "object" ? { details: t.details } : {}
3034
- }, i = r.details?.quota, a = i && typeof i == "object" ? i : null, o = r.error === "quota_exceeded" && a?.type === "feature" && a.feature === "comments";
3035
- if (r.code === 402 && (r.error === "plan_required" || o)) {
3036
- this.writeRestriction = r.error === "plan_required" || a?.reason === "plan_required" || !a?.reason && a?.plan === "none" ? "plan_required" : "feature_disabled";
3037
- let e = this.getInternalState().projectContext;
3038
- e && this.setState({ projectContext: {
3039
- ...e,
3040
- permissions: {
3041
- ...e.permissions,
3042
- canWriteComments: !1,
3043
- writeRestriction: this.writeRestriction,
3044
- canManageComments: !1
3045
- }
3046
- } });
3047
- let t = this.getInternalState().activeTool;
3048
- t !== null && t !== "select" && this.setTool(null);
3049
- }
3050
- console.error("[CommentKit]", r.message), this.setState({
3051
- error: r.message,
3052
- isLoading: !1
3053
- }), this.emit("error", r);
3054
- }
3055
- async restorePersistedSession() {
3056
- this.config.persistence === "memory" && lt(this.config.projectId);
3057
- let e = this.initialAuthToken === void 0 ? this.config.persistence === "memory" ? void 0 : ct(this.config.projectId)?.token : this.initialAuthToken;
3058
- if (this.initialAuthToken = void 0, e === void 0) return;
3059
- let t = () => !this.destroyed && this.authRequestRevision === 0;
3060
- try {
3061
- let { verifyAndRestoreToken: n } = await import("./token-session-D92MYbNu.js");
3062
- await n(this.ctx, e, t, this.config.persistence !== "memory") && await this.afterAuthenticated();
3063
- } catch {
3064
- t() && this.handleAuthExpired();
3065
- }
3066
- }
3067
- async afterAuthenticated(e) {
3068
- this.destroyed || (this.sessionRevision++, this.draftUploads = /* @__PURE__ */ new WeakMap(), e && e !== this.getInternalState().currentUser?.id && this.setState({
3069
- comments: [],
3070
- selectedComment: null,
3071
- projectContext: null,
3072
- activities: [],
3073
- seenThreadIds: /* @__PURE__ */ new Set()
3074
- }), yr(this.ctx), this.getFeatures().realtime && this.initializeWebSocket(), await Promise.all([this.loadComments(), this.reloadProjectContext()]), this.handleDeepLink(), this.getInternalState().pendingMutations.length > 0 && this.scheduleRetry());
3075
- }
3076
- beginAuthRequest() {
3077
- let e = ++this.authRequestRevision;
3078
- return () => !this.destroyed && e === this.authRequestRevision;
3079
- }
3080
- async login(e) {
3081
- if (!(this.destroyed || this.localDemo)) return this.config.inviteToken ? this.validateInvite(e) : bt(this.ctx, e, this.beginAuthRequest());
3082
- }
3083
- async verifyOtp(e) {
3084
- if (this.destroyed || this.localDemo) return;
3085
- let t = Date.now();
3086
- if (t < this.otpCooldownUntil) {
3087
- let e = Math.ceil((this.otpCooldownUntil - t) / 1e3);
3088
- this.handleError({
3089
- error: "otp_throttled",
3090
- message: `Too many attempts. Please wait ${e}s and try again.`,
3091
- code: 429
3092
- });
3093
- return;
3094
- }
3095
- let n = this.getInternalState().currentUser?.id;
3096
- return xt(this.ctx, e, {
3097
- isCurrent: this.beginAuthRequest(),
3098
- onAuthenticated: async () => {
3099
- await this.afterAuthenticated(n);
3100
- },
3101
- onSuccess: () => {
3102
- this.config.inviteToken = void 0, this.otpFailedAttempts = 0, this.otpCooldownUntil = 0;
3103
- },
3104
- onWrongOtp: () => {
3105
- if (this.otpFailedAttempts += 1, this.otpFailedAttempts >= 3) {
3106
- let e = Math.min(3e4, 2e3 * 2 ** (this.otpFailedAttempts - 3));
3107
- this.otpCooldownUntil = Date.now() + e;
3108
- }
3109
- }
3110
- });
3111
- }
3112
- cancelOtp() {
3113
- this.destroyed || (this.authRequestRevision++, St(this.ctx));
3114
- }
3115
- async resendOtp() {
3116
- if (this.destroyed || this.localDemo) return;
3117
- let e = this.getInternalState().otpEmail;
3118
- return this.config.inviteToken && e ? this.validateInvite(e) : Ct(this.ctx, this.beginAuthRequest());
3119
- }
3120
- logout() {
3121
- this.destroyed || (this.authRequestRevision++, this.localDemo ? (this.setTool(null), this.setState({
3122
- isOverlayVisible: !1,
3123
- isSidebarVisible: !1
3124
- })) : (this.sessionRevision++, this.draftUploads = /* @__PURE__ */ new WeakMap(), this.writeRestriction = null, this.setState({ projectContext: null }), this.overlayBeforeTool = null, wt(this.ctx, () => {
3125
- this.disconnectRealtime(!0);
3126
- })));
3127
- }
3128
- handleAuthExpired() {
3129
- this.destroyed || (this.authRequestRevision++, this.sessionRevision++, this.draftUploads = /* @__PURE__ */ new WeakMap(), this.writeRestriction = null, this.setState({ projectContext: null }), this.overlayBeforeTool = null, this.disconnectRealtime(!0), Tt(this.ctx));
3130
- }
3131
- toggleLoginModal() {
3132
- this.destroyed || this.localDemo || (this.getInternalState().isLoginModalVisible && this.cancelOtp(), Et(this.ctx));
3133
- }
3134
- requiresShortcut() {
3135
- return this.localDemo ? !0 : this.config.environment !== "development";
3136
- }
3137
- toggleOverlay() {
3138
- if (this.destroyed) return;
3139
- let e = !this.getInternalState().isOverlayVisible;
3140
- this.overlayBeforeTool = null, this.setState({
3141
- isOverlayVisible: e,
3142
- ...!e && {
3143
- selectedComment: null,
3144
- activeComment: null
3145
- }
3146
- });
3147
- }
3148
- toggleSidebar() {
3149
- this.destroyed || this.setState({ isSidebarVisible: !this.getInternalState().isSidebarVisible });
3150
- }
3151
- setTool(e) {
3152
- if (this.destroyed || !jr.has(e) || this.localDemo && e !== null && e !== "comment" && e !== "select") return;
3153
- let t = this.getInternalState();
3154
- if (e !== null && e !== "select" && !this.requireCommentWrite()) return;
3155
- if (!t.isAuthenticated && e !== "select" && e !== null) {
3156
- this.toggleLoginModal();
3157
- return;
3158
- }
3159
- let n;
3160
- e === null ? (n = this.overlayBeforeTool ?? t.isOverlayVisible, this.overlayBeforeTool = null) : (this.overlayBeforeTool === null && (this.overlayBeforeTool = t.isOverlayVisible), n = !1), this.setState({
3161
- activeTool: e,
3162
- isCommentModeActive: e === "comment",
3163
- isDrawingModeActive: e === "draw",
3164
- isHighlightModeActive: e === "highlight",
3165
- isScreenshotModeActive: e === "screenshot",
3166
- isOverlayVisible: n,
3167
- selectedComment: null,
3168
- activeComment: null,
3169
- activeDrawing: null,
3170
- activeScreenshot: null
3171
- });
3172
- }
3173
- operationContext(e) {
3174
- this.localDemo?.refresh();
3175
- let t = this.localDemo?.getRevision(), n = this.sessionRevision, r = () => !this.destroyed && n === this.sessionRevision && t === this.localDemo?.getRevision();
3176
- return {
3177
- ...this.ctx,
3178
- isCurrent: r,
3179
- setState: (e) => {
3180
- r() && this.ctx.setState(e);
3181
- },
3182
- emit: (t, n) => {
3183
- r() && (e && (t === "comment:created" || t === "comment:updated") && (e.result = {
3184
- status: "confirmed",
3185
- commentId: n.id
3186
- }), this.ctx.emit(t, n));
3187
- },
3188
- handleError: (e) => {
3189
- r() && this.ctx.handleError(e);
3190
- }
3191
- };
3192
- }
3193
- operationCallbacks(e) {
3194
- let t = this.localDemo?.getRevision(), n = this.sessionRevision, r = () => !this.destroyed && n === this.sessionRevision && t === this.localDemo?.getRevision();
3195
- return {
3196
- ...this.commentCb,
3197
- queueMutation: (...t) => {
3198
- let n = r() && this.commentCb.queueMutation(...t);
3199
- return n && e && r() && (e.result = {
3200
- status: "queued",
3201
- commentId: t[2]
3202
- }), n;
3203
- },
3204
- addActivity: (e) => {
3205
- r() && this.commentCb.addActivity(e);
3206
- }
3207
- };
3208
- }
3209
- commentsRequestContext(e) {
3210
- let t = this.operationContext();
3211
- return {
3212
- ...t,
3213
- isCurrent: () => e === this.commentsFetchRevision && !!t.isCurrent?.(),
3214
- setState: (n) => {
3215
- e === this.commentsFetchRevision && t.setState(n);
3216
- },
3217
- handleError: (n) => {
3218
- e === this.commentsFetchRevision && t.handleError(n);
3219
- }
3220
- };
3221
- }
3222
- async loadComments() {
3223
- return cn(this.commentsRequestContext(++this.commentsFetchRevision));
3224
- }
3225
- async loadMoreComments() {
3226
- this.destroyed || await ln(this.commentsRequestContext(this.commentsFetchRevision), this.loadMoreGuard);
3227
- }
3228
- async setCommentQuery(e) {
3229
- if (this.destroyed || !this.getInternalState().isAuthenticated || this.localDemo) return;
3230
- let t = {
3231
- ...e,
3232
- search: e.search?.trim().slice(0, 200) || void 0
3233
- };
3234
- if (JSON.stringify(t) !== JSON.stringify(this.getInternalState().commentQuery)) return this.setState({
3235
- commentQuery: t,
3236
- pagination: null,
3237
- selectedComment: null
3238
- }), this.loadComments();
3239
- }
3240
- async loadEarlierReplies() {
3241
- let e = this.getInternalState(), t = e.comments.find((t) => t.id === e.selectedComment?.id);
3242
- if (!(this.destroyed || e.loadingThreadId || !t?.repliesPagination?.nextCursor)) return un(this.operationContext(), t.id, t.repliesPagination.nextCursor);
3243
- }
3244
- async reloadComments() {
3245
- if (!this.destroyed) return this.loadComments();
3246
- }
3247
- async refreshAttachmentUrl(e) {
3248
- if (this.destroyed || this.localDemo || !this.getInternalState().isAuthenticated || typeof e != "string" || !e || e.length > 256 || a(e)) return null;
3249
- let t = (t) => [...t.attachments ?? [], ...t.replies.flatMap((e) => e.attachments ?? [])].find((t) => t.id === e), n = this.getInternalState().comments.find((e) => t(e));
3250
- if (!n) return null;
3251
- let r = this.sessionRevision, i = this.commentsFetchRevision, o = `${r}:${i}:${n.id}`, s = () => !this.destroyed && r === this.sessionRevision && i === this.commentsFetchRevision && this.getInternalState().isAuthenticated, c = this.attachmentRefreshes.get(o);
3252
- c || (c = (async () => {
3253
- try {
3254
- let e = await this.apiClient.getComment(n.id);
3255
- if (!s() || e?.id !== n.id || !Array.isArray(e.replies)) return null;
3256
- let t = this.getInternalState(), r = t.comments.find((e) => e.id === n.id);
3257
- if (!r) return null;
3258
- let i = (e, t) => e?.map((e) => {
3259
- let n = t?.find((t) => t.id === e.id);
3260
- return n && l(n.url, !0) ? {
3261
- ...e,
3262
- url: n.url,
3263
- ...l(n.thumbnail, !0) ? { thumbnail: n.thumbnail } : {}
3264
- } : e;
3265
- }), a = {
3266
- ...r,
3267
- attachments: i(r.attachments, e.attachments) ?? [],
3268
- replies: r.replies.map((t) => ({
3269
- ...t,
3270
- attachments: i(t.attachments, e.replies.find((e) => e.id === t.id)?.attachments)
3271
- }))
3272
- };
3273
- return this.setState({
3274
- comments: t.comments.map((e) => e.id === n.id ? a : e),
3275
- ...t.selectedComment?.id === n.id ? { selectedComment: a } : {}
3276
- }), e;
3277
- } catch (e) {
3278
- return s() && this.handleError(e), null;
3279
- } finally {
3280
- this.attachmentRefreshes.get(o) === c && this.attachmentRefreshes.delete(o);
3281
- }
3282
- })(), this.attachmentRefreshes.set(o, c));
3283
- let u = await c;
3284
- if (!s() || !u) return null;
3285
- let d = this.getInternalState().comments.find((e) => e.id === n.id);
3286
- if (!d || !t(d)) return null;
3287
- let f = t(u)?.url;
3288
- return l(f, !0) ? f : null;
3289
- }
3290
- async reloadProjectContext() {
3291
- if (this.destroyed || this.localDemo || !this.getInternalState().isAuthenticated) return;
3292
- let e = this.operationContext(), t = this.sessionRevision, n = ++this.contextFetchRevision;
3293
- try {
3294
- let r = await this.apiClient.getProjectContext();
3295
- if (this.destroyed || t !== this.sessionRevision || n !== this.contextFetchRevision) return;
3296
- if (r?.project && Array.isArray(r.members)) {
3297
- let t = this.canWriteComments();
3298
- if (r.permissions.canWriteComments !== void 0 && (this.writeRestriction = null), e.setState({ projectContext: r }), r.permissions.canWriteComments === !1) {
3299
- let e = this.getInternalState().activeTool;
3300
- e !== null && e !== "select" && this.setTool(null);
3301
- }
3302
- !t && this.canWriteComments() && this.getInternalState().isOnline && this.scheduleRetry();
3303
- }
3304
- } catch (t) {
3305
- n === this.contextFetchRevision && t.code !== 404 && e.handleError(t);
3306
- }
3307
- }
3308
- async setBranch(e) {
3309
- if (this.destroyed || e !== null && (typeof e != "string" || !e.trim() || e.length > 255 || a(e))) return;
3310
- let t = e?.trim() ?? null;
3311
- (this.getInternalState().activeBranch ?? null) !== t && (this.setState({
3312
- activeBranch: t,
3313
- selectedComment: null,
3314
- panelView: "list",
3315
- comments: [],
3316
- pagination: null
3317
- }), await this.loadComments());
3318
- }
3319
- async uploadDraftFiles(e) {
3320
- if (this.destroyed || this.localDemo || !this.getInternalState().isAuthenticated) throw Error("Sign in to attach files.");
3321
- if (!this.requireCommentWrite()) throw Error("This workspace is read-only.");
3322
- if (!Array.isArray(e) || e.length > 10) throw Error("Attach up to 10 files.");
3323
- let t = this.sessionRevision, n = [], r = this.draftUploads;
3324
- for (let i of e) {
3325
- let e = r.get(i);
3326
- e || (e = this.apiClient.uploadFile(i, /^image\/(jpeg|png|gif|webp)$/.test(i.type) ? "screenshot" : "attachment").then((e) => e.id), r.set(i, e));
3327
- try {
3328
- n.push(await e);
3329
- } catch (e) {
3330
- throw r.delete(i), !this.destroyed && t === this.sessionRevision && this.handleError(e), e;
3331
- }
3332
- if (this.destroyed || t !== this.sessionRevision) throw Error("Your session changed. Please sign in again.");
3333
- }
3334
- return n;
3335
- }
3336
- async createComment(e, t, n, r = "medium", i, a, o) {
3337
- if (this.destroyed || !this.requireCommentWrite()) return;
3338
- if (this.localDemo && (e !== "pin" || o?.files?.length || o?.attachmentIds?.length)) {
3339
- this.handleError({
3340
- error: "demo_unavailable",
3341
- message: "Files and drawings are unavailable in the private browser demo.",
3342
- code: 400
3343
- });
3344
- return;
3345
- }
3346
- let s = o?.[tt];
3347
- return dn(this.operationContext(s), this.operationCallbacks(s), this.activeMutations, e, t, n, r, i, a, {
3348
- ...o,
3349
- branch: o?.branch ?? I(this.ctx)
3350
- });
3351
- }
3352
- async updateComment(e, t) {
3353
- if (!this.destroyed && this.requireCommentWrite()) return fn(this.operationContext(), this.operationCallbacks(), e, t);
3354
- }
3355
- async deleteComment(e) {
3356
- if (!this.destroyed && this.requireCommentWrite()) return pn(this.operationContext(), this.operationCallbacks(), e);
3357
- }
3358
- async addReply(e, t, n) {
3359
- if (this.destroyed || !this.requireCommentWrite()) return;
3360
- let { [tt]: r, ...i } = n ?? {};
3361
- return mn(this.operationContext(r), this.operationCallbacks(r), e, t, n ? i : void 0);
3362
- }
3363
- async updateReply(e, t, n, r) {
3364
- if (!this.destroyed && this.requireCommentWrite()) return hn(this.operationContext(), e, t, n, r);
3365
- }
3366
- async deleteReply(e, t) {
3367
- if (!this.destroyed && this.requireCommentWrite()) return gn(this.operationContext(), e, t);
3368
- }
3369
- requireThreadStatus(e, t = !1) {
3370
- let n = this.getInternalState();
3371
- if (n.projectContext?.permissions?.accessScope !== "project") return !0;
3372
- let r = n.comments.find((t) => t.id === e)?.author.id === n.currentUser?.id;
3373
- return !t && r ? !0 : (this.handleError({
3374
- error: "forbidden",
3375
- message: t ? "Only workspace members can mark feedback complete." : "You can only resolve or reopen your own feedback.",
3376
- code: 403
3377
- }), !1);
3378
- }
3379
- async resolveComment(e) {
3380
- if (!this.destroyed && this.requireCommentWrite() && this.requireThreadStatus(e)) return _n(this.operationContext(), this.operationCallbacks(), e);
3381
- }
3382
- async unresolveComment(e) {
3383
- if (!this.destroyed && this.requireCommentWrite() && this.requireThreadStatus(e)) return vn(this.operationContext(), this.operationCallbacks(), e);
3384
- }
3385
- selectComment(e) {
3386
- this.destroyed || (Sn(this.operationContext(), e), e?.detailLoaded === !1 && !this.localDemo && un(this.operationContext(), e.id));
3387
- }
3388
- async completeComment(e) {
3389
- if (!this.destroyed && this.requireCommentWrite() && this.requireThreadStatus(e, !0)) return yn(this.operationContext(), this.operationCallbacks(), e);
3390
- }
3391
- async reactToComment(e, t, n) {
3392
- if (this.destroyed || !this.requireCommentWrite()) return;
3393
- let r = `${e}:${n ?? "parent"}`, i = this.sessionRevision, a = async () => {
3394
- !this.destroyed && i === this.sessionRevision && this.requireCommentWrite() && await bn(this.operationContext(), this.operationCallbacks(), e, t, n);
3395
- }, o = this.reactionRequests.get(r), s = o ? o.then(a, a) : a();
3396
- this.reactionRequests.set(r, s);
3397
- try {
3398
- await s;
3399
- } finally {
3400
- this.reactionRequests.get(r) === s && this.reactionRequests.delete(r);
3401
- }
3402
- }
3403
- async updateCommentPosition(e, t, n) {
3404
- if (!this.destroyed && this.requireCommentWrite()) return xn(this.operationContext(), this.operationCallbacks(), e, t, n);
3405
- }
3406
- hydrateOfflineQueue() {
3407
- if (this.config.persistence === "memory") return;
3408
- let e = mr(this.config.projectId);
3409
- if (e.length > 0) {
3410
- let t = this.getInternalState().pendingMutations, n = new Set(t.map((e) => e.id)), r = [...t, ...e.filter((e) => !n.has(e.id))];
3411
- this.setState({ pendingMutations: r }), yr(this.ctx), this.getInternalState().isOnline && this.scheduleRetry();
3412
- }
3413
- this.offlinePersistUnsub?.(), this.offlinePersistUnsub = this.select((e) => e.pendingMutations, (e) => pr(this.config.projectId, e));
3414
- }
3415
- shouldQueueMutation(e) {
3416
- return !this.localDemo && br(this.getInternalState(), e);
3417
- }
3418
- queueMutation(e, t, n) {
3419
- return xr(this.ctx, () => this.scheduleRetry(), e, t, n);
3420
- }
3421
- scheduleRetry() {
3422
- Sr(this.ctx, this.retryTimerRef, () => this.processOfflineQueue());
3423
- }
3424
- async processOfflineQueue() {
3425
- this.canWriteComments() && await Cr(this.operationContext(), this.queueGuard, () => this.scheduleRetry(), (e) => this.executeMutation(e));
3426
- }
3427
- async executeMutation(e) {
3428
- let t = this.operationContext();
3429
- try {
3430
- await Dr(t, e);
3431
- } catch (e) {
3432
- throw e instanceof E && e.code === 402 && t.handleError(e), e;
3433
- }
3434
- }
3435
- getPendingMutationCount() {
3436
- return this.getInternalState().pendingMutations.length;
3437
- }
3438
- clearError() {
3439
- this.destroyed || this.getInternalState().error == null || this.setState({ error: null });
3440
- }
3441
- retryConnection() {
3442
- !this.destroyed && this.getInternalState().isAuthenticated && (this.wsManager ? this.wsManager.reconnect() : this.initializeWebSocket());
3443
- }
3444
- markThreadSeen(e) {
3445
- if (this.destroyed || typeof e != "string" || !e.trim() || e.length > Mr) return;
3446
- let t = new Set(this.getInternalState().seenThreadIds);
3447
- if (t.add(e), t.size > 1e3) {
3448
- let e = Array.from(t);
3449
- t.clear();
3450
- for (let n of e.slice(-1e3)) t.add(n);
3451
- }
3452
- this.setState({ seenThreadIds: t });
3453
- }
3454
- isThreadNew(e) {
3455
- return typeof e != "string" || !e.trim() ? !1 : !this.getInternalState().seenThreadIds.has(e);
3456
- }
3457
- setPanelView(e) {
3458
- !this.destroyed && Ar.has(e) && this.setState({ panelView: e });
3459
- }
3460
- toggleShortcutsOverlay() {
3461
- this.destroyed || this.setState({ isShortcutsOverlayVisible: !this.getInternalState().isShortcutsOverlayVisible });
3462
- }
3463
- addActivity(e) {
3464
- if (this.destroyed) return;
3465
- let t = this.getInternalState(), n = t.currentUser;
3466
- if (!n) return;
3467
- let r = {
3468
- id: `activity-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
3469
- user: {
3470
- id: n.id,
3471
- name: n.name,
3472
- avatarUrl: n.avatar
3473
- },
3474
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3475
- read: !1,
3476
- ...e
3477
- }, i = [r, ...t.activities].slice(0, 500);
3478
- this.setState({ activities: i }), this.emit("activity:new", r);
3479
- }
3480
- markAllActivitiesRead() {
3481
- if (this.destroyed) return;
3482
- let e = this.getInternalState();
3483
- this.setState({ activities: e.activities.map((e) => ({
3484
- ...e,
3485
- read: !0
3486
- })) });
3487
- }
3488
- getUnreadActivityCount() {
3489
- return this.getInternalState().activities.filter((e) => !e.read).length;
3490
- }
3491
- handleDeepLink() {
3492
- if (this.destroyed) return;
3493
- let e = window.location.hash, t = e.match(/^#comment-(.+)$/);
3494
- if (!t?.[1]) return;
3495
- let n = t[1];
3496
- this.emit("deeplink:navigate", { commentId: n });
3497
- let r = this.getInternalState().comments.find((e) => e.id === n);
3498
- if (r) this.selectComment(r), this.setState({
3499
- isSidebarVisible: !0,
3500
- panelView: "detail"
3501
- });
3502
- else if (this.getInternalState().isAuthenticated && n.length <= 256 && this.deepLinkRequest !== e) {
3503
- this.deepLinkRequest = e;
3504
- let t = this.sessionRevision;
3505
- this.apiClient.getComment(n, { repliesLimit: 50 }).then(async (r) => {
3506
- if (this.destroyed || t !== this.sessionRevision || window.location.hash !== e || r.id !== n) return;
3507
- let i = this.getInternalState().activeBranch;
3508
- i && i !== r.branch && await this.setBranch(r.branch ?? null), !(this.destroyed || t !== this.sessionRevision || window.location.hash !== e) && (this.setState({
3509
- comments: [...this.getInternalState().comments.filter((e) => e.id !== r.id), r],
3510
- selectedComment: r,
3511
- isSidebarVisible: !0,
3512
- panelView: "detail"
3513
- }), this.markThreadSeen(r.id));
3514
- }).catch((n) => {
3515
- !this.destroyed && t === this.sessionRevision && window.location.hash === e && this.handleError(n);
3516
- }).finally(() => {
3517
- this.deepLinkRequest === e && (this.deepLinkRequest = null);
3518
- });
3519
- }
3520
- }
3521
- async createHighlight(e, t) {
3522
- if (!this.destroyed && this.requireCommentWrite()) return Cn(this.operationContext(), this.operationCallbacks(), this.activeMutations, e, t);
3523
- }
3524
- async createDrawing(e, t, n) {
3525
- if (!this.destroyed && this.requireCommentWrite()) return wn(this.operationContext(), this.operationCallbacks(), this.activeMutations, e, t, n);
3526
- }
3527
- setActiveDrawing(e) {
3528
- this.destroyed || this.setState({ activeDrawing: e });
3529
- }
3530
- sendDrawingStroke(e) {
3531
- !this.destroyed && this.requireCommentWrite() && this.wsManager?.sendDrawingStroke(e);
3532
- }
3533
- async captureScreenshot(e) {
3534
- if (this.destroyed) return null;
3535
- let { captureScreenshot: t } = await import("./screenshot-B5-hwpmt.js");
3536
- return this.destroyed ? null : t(this.ctx, this.screenshotProvider, e);
3537
- }
3538
- async uploadScreenshot(e, t, n) {
3539
- if (this.destroyed || !this.requireCommentWrite()) return null;
3540
- let r = this.operationContext(), { uploadScreenshot: i } = await import("./screenshot-B5-hwpmt.js");
3541
- return this.destroyed || r.isCurrent?.() === !1 || !this.requireCommentWrite() ? null : i(r, e, t, n);
3542
- }
3543
- setActiveScreenshot(e) {
3544
- this.destroyed || this.setState({ activeScreenshot: e });
3545
- }
3546
- async uploadFiles(e, t) {
3547
- if (this.destroyed || !this.requireCommentWrite()) return [];
3548
- let n = this.operationContext(), { uploadFiles: r } = await import("./screenshot-B5-hwpmt.js");
3549
- return this.destroyed || n.isCurrent?.() === !1 || !this.requireCommentWrite() ? [] : r(n, e, t);
3550
- }
3551
- requireAgentExport() {
3552
- if (this.getInternalState().projectContext?.permissions.canExportAgentContext === !1) throw new E("forbidden", "Agent handoff is available to workspace members.", 403);
3553
- }
3554
- getAgentContext(e) {
3555
- return this.requireAgentExport(), k(this.getInternalState(), e);
3556
- }
3557
- async getAgentContextAsync(e) {
3558
- this.requireAgentExport();
3559
- let t = this.getInternalState(), n = k(t, e);
3560
- if (!this.localDemo && t.isAuthenticated) {
3561
- let r = new Set(n.comments.map((e) => e.id)), i = t.comments.filter((e) => r.has(e.id) && e.detailLoaded === !1), a = /* @__PURE__ */ new Map(), o = this.sessionRevision;
3562
- for (let e = 0; e < i.length; e += 4) {
3563
- let t = await Promise.all(i.slice(e, e + 4).map((e) => this.apiClient.getComment(e.id, { repliesLimit: 12 })));
3564
- if (this.destroyed || o !== this.sessionRevision || !this.getInternalState().isAuthenticated) throw new E("unauthorized", "Sign in again to copy feedback.", 401);
3565
- for (let e of t) a.set(e.id, e);
3566
- }
3567
- a.size && (n = k({
3568
- ...t,
3569
- comments: t.comments.map((e) => a.get(e.id) ?? e)
3570
- }, e));
3571
- }
3572
- let r = this.localDemo?.getRevision(), i = await He(n);
3573
- return this.localDemo?.checkExpiry(), this.localDemo && r !== this.localDemo.getRevision() ? k(this.getInternalState(), e) : i;
3574
- }
3575
- formatAgentContext(e) {
3576
- return A(this.getAgentContext(e));
3577
- }
3578
- async formatAgentContextAsync(e) {
3579
- return A(await this.getAgentContextAsync(e));
3580
- }
3581
- async copyAgentContext(e) {
3582
- if (this.destroyed) return "";
3583
- let t = await this.getAgentContextAsync(e), n = A(t);
3584
- return await Ye(n, t), this.emit("agent:context-copied", {
3585
- commentCount: t.comments.length,
3586
- sourceResolved: t.sourceResolved
3587
- }), n;
3588
- }
3589
- async grabElement(e, t) {
3590
- if (this.destroyed) return null;
3591
- this.requireAgentExport();
3592
- let { grabElement: n } = await import("./dev-grab-B85jo9AS.js");
3593
- if (this.destroyed) return null;
3594
- this.requireAgentExport();
3595
- let r = await n(e, this.ctx, this.screenshotProvider, t);
3596
- return this.destroyed ? null : (r && this.emit("agent:element-grabbed", {
3597
- source: r.element.source?.filePath ?? null,
3598
- componentName: r.element.componentName ?? null
3599
- }), r);
3600
- }
3601
- async grabElements(e, t) {
3602
- if (this.destroyed) return null;
3603
- this.requireAgentExport();
3604
- let { grabElements: n } = await import("./dev-grab-B85jo9AS.js");
3605
- if (this.destroyed) return null;
3606
- this.requireAgentExport();
3607
- let r = await n(e, this.ctx, this.screenshotProvider, t);
3608
- return this.destroyed ? null : (r && this.emit("agent:elements-grabbed", { count: r.results.length }), r);
3609
- }
3610
- async getProjectMembers() {
3611
- if (this.destroyed) return [];
3612
- try {
3613
- return await this.apiClient.getProjectMembers();
3614
- } catch (e) {
3615
- return this.handleError(e), [];
3616
- }
3617
- }
3618
- handleToggleRequest() {
3619
- this.destroyed || j() || Ln(this.getInternalState(), this.kbdCallbacks);
3620
- }
3621
- handleKeyboardShortcuts(e) {
3622
- if (!(this.destroyed || j())) {
3623
- if (e.key === "Escape") {
3624
- if (this.escapeBlockers.size > 0) return;
3625
- let t = e.composedPath()[0];
3626
- if (t instanceof Element && t.getRootNode() === document && t.closest("[data-commentkit-ui], [data-commentkit-ignore]")) return;
3627
- }
3628
- Rn(e, this.getInternalState(), this.kbdCallbacks);
3629
- }
3630
- }
3631
- matchesHoldKey(e) {
3632
- let t = this.config.ui?.activation?.key;
3633
- return t ? t === "Alt" ? e.key === "Alt" || e.code === "AltLeft" || e.code === "AltRight" : t === "Meta" ? e.key === "Meta" || e.code === "MetaLeft" || e.code === "MetaRight" : t === "Control" ? e.key === "Control" || e.code === "ControlLeft" || e.code === "ControlRight" : t === "Shift" ? e.key === "Shift" || e.code === "ShiftLeft" || e.code === "ShiftRight" : !1 : !1;
3634
- }
3635
- blockEscape() {
3636
- let e = Symbol();
3637
- return this.escapeBlockers.add(e), () => {
3638
- this.escapeBlockers.delete(e);
3639
- };
3640
- }
3641
- initializeWebSocket() {
3642
- this.destroyed || this.localDemo || Or().then((e) => {
3643
- this.destroyed || this.getInternalState().isAuthenticated && (this.syncRealtimeRefs(), e.initializeWebSocket(this.ctx, this.realtimeRefs, {
3644
- capture: () => this.commentsRequestContext(this.commentsFetchRevision),
3645
- subscribe: (e) => this.on("state:changed", e)
3646
- }), this.syncFromRealtimeRefs());
3647
- }).catch((e) => {
3648
- this.ctx.handleError(e);
3649
- });
3650
- }
3651
- getOnlineUsers() {
3652
- /* v8 ignore next -- onlineUsers is always initialized as array */
3653
- return structuredClone(this.getInternalState().onlineUsers || []);
3654
- }
3655
- syncRealtimeRefs() {
3656
- this.realtimeRefs.wsManager = this.wsManager, this.realtimeRefs.wsUnsubscribers = this.wsUnsubscribers, this.realtimeRefs.mouseMoveHandler = this.mouseMoveHandler;
3657
- }
3658
- syncFromRealtimeRefs() {
3659
- this.wsManager = this.realtimeRefs.wsManager, this.wsUnsubscribers = this.realtimeRefs.wsUnsubscribers, this.mouseMoveHandler = this.realtimeRefs.mouseMoveHandler;
3660
- }
3661
- removeMouseMoveListener() {
3662
- $ && (this.syncRealtimeRefs(), $.removeMouseMoveListener(this.realtimeRefs), this.syncFromRealtimeRefs());
3663
- }
3664
- disconnectRealtime(e) {
3665
- for (let e of this.wsUnsubscribers) try {
3666
- e();
3667
- } catch (e) {
3668
- console.error("[CommentKit] Error during realtime cleanup:", e);
3669
- }
3670
- if (this.wsUnsubscribers = [], this.wsManager) {
3671
- try {
3672
- e && this.wsManager.sendCursorLeave();
3673
- } catch {}
3674
- this.wsManager.destroy(), this.wsManager = null;
3675
- }
3676
- this.removeMouseMoveListener(), this.syncRealtimeRefs();
3677
- }
3678
- destroy() {
3679
- this.destroyed || (this.destroyed = !0, this.initialAuthToken = void 0, kr && (this.keyboardHandler && window.removeEventListener("keydown", this.keyboardHandler, !0), this.holdActivationHandler && (window.removeEventListener("keydown", this.holdActivationHandler), window.removeEventListener("keyup", this.holdActivationHandler)), this.holdBlurHandler && window.removeEventListener("blur", this.holdBlurHandler), this.toggleHandler && window.removeEventListener("commentkit:toggle-overlay", this.toggleHandler), this.hashChangeHandler && window.removeEventListener("hashchange", this.hashChangeHandler), this.onlineHandler && window.removeEventListener("online", this.onlineHandler), this.offlineHandler && window.removeEventListener("offline", this.offlineHandler)), this.pendingStateUpdates = null, this.flushScheduled = !1, this.activeMutations.clear(), this.offlinePersistUnsub?.(), this.offlinePersistUnsub = null, this.retryTimer &&= (clearTimeout(this.retryTimer), null), this.bootRetryTimer &&= (clearTimeout(this.bootRetryTimer), null), this.disconnectRealtime(!0), this.localDemo?.destroy(), this.sliceSubscribers.clear(), this.removeAllListeners());
3680
- }
3681
- };
3682
- export { ve as _, vt as a, T as b, tt as c, Xe as d, Je as f, we as g, A as h, yt as i, et as l, k as m, Nr as n, st as o, Ye as p, I as r, M as s, Lr as t, j as u, E as v, be as x, ye as y };