@commentkit/comment-kit 0.7.6 → 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 +30 -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-BUaiCkDJ.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-RSrb0Nku.js +0 -1086
  45. package/dist/shared/attachment-refresh-CSTYwRW-.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-DUROnio5.js +0 -77
  50. package/dist/shared/comment-drawing-canvas-DbuXP54N.js +0 -124
  51. package/dist/shared/comment-icon-D8JTCEJ7.js +0 -607
  52. package/dist/shared/comment-image-lightbox-zlIGEVA-.js +0 -190
  53. package/dist/shared/comment-images-content-aYbJb79_.js +0 -214
  54. package/dist/shared/comment-kit-core-B0k7XsMz.js +0 -3680
  55. package/dist/shared/comment-kit-ui-BXLJcZYQ.js +0 -19391
  56. package/dist/shared/comment-screenshot-annotator-ChWwYJzO.js +0 -151
  57. package/dist/shared/comment-screenshot-overlay-Bufg3rHz.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-DAZenvgD.js +0 -207
  61. package/dist/shared/dev-grab-O8q25zar.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-CYkwzfEr.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-BKaWBhKq.js +0 -208
  70. package/dist/shared/realtime-C0Z8dXXH.js +0 -334
  71. package/dist/shared/realtime-recovery-BjlV-ewc.js +0 -162
  72. package/dist/shared/request-activity-DQrAUwfA.js +0 -11
  73. package/dist/shared/screenshot-B-ZfFItT.js +0 -199
  74. package/dist/shared/separator-UhJb0Row.js +0 -3955
  75. package/dist/shared/shadow-root-Cd3SLHyj.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-DplW5QDx.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-798cRDyL.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,3680 +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-DUROnio5.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), s = a;
1708
- if (y.length > 0) try {
1709
- let t = (await Promise.all(y.map(async (t) => {
1710
- let n = "." + (t.name.split(".").pop()?.toLowerCase() ?? ""), r = t.type.startsWith("image/") && [
1711
- ".jpg",
1712
- ".jpeg",
1713
- ".png",
1714
- ".gif",
1715
- ".webp"
1716
- ].includes(n);
1717
- return e.apiClient.uploadFile(t, r ? "screenshot" : "attachment", { commentId: a.id });
1718
- }))).map((e) => ({
1719
- id: e.id,
1720
- type: e.type === "screenshot" || e.type === "drawing" ? e.type : "file",
1721
- url: e.url,
1722
- thumbnail: e.thumbnail,
1723
- filename: e.filename,
1724
- size: e.size
1725
- }));
1726
- s = {
1727
- ...a,
1728
- attachments: t
1729
- };
1730
- } catch (t) {
1731
- e.handleError(t), s = {
1732
- ...a,
1733
- attachments: a.attachments ?? []
1734
- };
1735
- }
1736
- K(e, b, s), e.emit("comment:created", s), t.addActivity({
1737
- type: "comment_created",
1738
- threadId: s.id,
1739
- message: "created a new comment"
1740
- });
1741
- } catch (n) {
1742
- t.shouldQueueMutation(n) && t.queueMutation("createComment", [
1743
- r,
1744
- d,
1745
- f,
1746
- o,
1747
- p,
1748
- h,
1749
- g ? {
1750
- description: g.description,
1751
- assignees: g.assignees,
1752
- mentions: g.mentions,
1753
- branch: g.branch,
1754
- deviceInfo: g.deviceInfo,
1755
- checklist: g.checklist,
1756
- attachmentIds: g.attachmentIds
1757
- } : void 0,
1758
- {
1759
- url: v.url,
1760
- path: v.path,
1761
- title: v.title
1762
- }
1763
- ], b) || (e.setState({ comments: e.getState().comments.filter((e) => e.id !== b) }), e.handleError(n));
1764
- } finally {
1765
- n.delete(_);
1766
- }
1767
- }
1768
- async function fn(e, t, n, r) {
1769
- if (!z(n)) return;
1770
- let i = an(r);
1771
- if (i === null) {
1772
- R(e, "invalid_comment_update", "Comment update data is invalid");
1773
- return;
1774
- }
1775
- if (i === void 0) return;
1776
- let a = e.getState().comments, o = a.find((e) => e.id === n);
1777
- if (!o) return;
1778
- let { checklistPatch: s, ...c } = i;
1779
- e.setState({ comments: a.map((e) => e.id === n ? {
1780
- ...q(e, i.status),
1781
- ...c,
1782
- ...s ? { checklist: e.checklist?.map((e) => e.id === s.id ? {
1783
- ...e,
1784
- done: s.done
1785
- } : e) } : {}
1786
- } : e) });
1787
- try {
1788
- let t = await e.apiClient.updateComment(n, i);
1789
- e.setState({ comments: e.getState().comments.map((e) => e.id === n ? t : e) }), e.emit("comment:updated", t);
1790
- } catch (r) {
1791
- t.shouldQueueMutation(r) && t.queueMutation("updateComment", [n, i]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n ? o : e) }), e.handleError(r));
1792
- }
1793
- }
1794
- async function pn(e, t, n) {
1795
- if (!z(n)) return;
1796
- let r = e.getState().comments, i = r.find((e) => e.id === n);
1797
- if (!i) return;
1798
- let a = e.getState().selectedComment;
1799
- e.setState({
1800
- comments: r.filter((e) => e.id !== n),
1801
- selectedComment: a?.id === n ? null : a
1802
- });
1803
- try {
1804
- await e.apiClient.deleteComment(n), e.emit("comment:deleted", { id: n });
1805
- } catch (r) {
1806
- if (!(t.shouldQueueMutation(r) && t.queueMutation("deleteComment", [n]))) {
1807
- let t = e.getState(), o = t.comments;
1808
- (!t.activeBranch || i.branch === t.activeBranch) && e.setState({
1809
- comments: o.some((e) => e.id === n) ? o : [...o, i],
1810
- selectedComment: t.selectedComment ?? a
1811
- }), e.handleError(r);
1812
- }
1813
- }
1814
- }
1815
- async function mn(e, t, n, r, i) {
1816
- let a = e.getState().currentUser;
1817
- if (!a || !z(n) || !G(e, n)) return;
1818
- let o = B(r, Nt);
1819
- if (!o) {
1820
- R(e, "invalid_reply", "Reply content is invalid");
1821
- return;
1822
- }
1823
- 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)))) {
1824
- R(e, "invalid_reply", "Reply target must belong to this thread");
1825
- return;
1826
- }
1827
- 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 = {
1828
- ...c && i?.replyTo ? { replyTo: {
1829
- ...i.replyTo,
1830
- authorName: c.author.name,
1831
- body: c.content
1832
- } } : {},
1833
- ...i?.mentions ? { mentions: i.mentions } : {},
1834
- id: l,
1835
- content: o,
1836
- author: a,
1837
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1838
- };
1839
- e.setState({ comments: e.getState().comments.map((e) => e.id === n ? {
1840
- ...e,
1841
- repliesCount: (e.repliesCount ?? e.replies.length) + 1,
1842
- replies: [...e.replies, u]
1843
- } : e) });
1844
- try {
1845
- on(e, n, l, await e.apiClient.addReply(n, o, l, ...i ? [i] : []));
1846
- let t = e.getState().comments.find((e) => e.id === n);
1847
- t && e.emit("comment:updated", t);
1848
- } catch (r) {
1849
- t.shouldQueueMutation(r) && t.queueMutation("addReply", i ? [
1850
- n,
1851
- o,
1852
- i
1853
- ] : [n, o], l) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n ? {
1854
- ...e,
1855
- repliesCount: Math.max(0, (e.repliesCount ?? e.replies.length) - 1),
1856
- replies: e.replies.filter((e) => e.id !== l)
1857
- } : e) }), e.handleError(r));
1858
- }
1859
- }
1860
- async function hn(e, t, n, r, i) {
1861
- if (!z(t) || !z(n) || !sn(e, t, n)) return;
1862
- let a = B(r, Nt);
1863
- if (!a) {
1864
- R(e, "invalid_reply", "Reply content is invalid");
1865
- return;
1866
- }
1867
- let o = e.getState().comments, s = o.find((e) => e.id === t)?.replies.find((e) => e.id === n);
1868
- e.setState({ comments: o.map((e) => e.id === t ? {
1869
- ...e,
1870
- replies: e.replies.map((e) => e.id === n ? {
1871
- ...e,
1872
- content: a,
1873
- isEdited: !0
1874
- } : e)
1875
- } : e) });
1876
- try {
1877
- let r = await e.apiClient.updateReply(t, n, a, ...i ? [i] : []);
1878
- e.setState({ comments: e.getState().comments.map((e) => e.id === t ? {
1879
- ...e,
1880
- replies: e.replies.map((e) => e.id === n ? r : e)
1881
- } : e) });
1882
- let o = e.getState().comments.find((e) => e.id === t);
1883
- o && e.emit("comment:updated", o);
1884
- } catch (r) {
1885
- e.setState({ comments: e.getState().comments.map((e) => e.id === t && s ? {
1886
- ...e,
1887
- replies: e.replies.map((e) => e.id === n ? s : e)
1888
- } : e) }), e.handleError(r);
1889
- }
1890
- }
1891
- async function gn(e, t, n) {
1892
- if (!z(t) || !z(n) || !sn(e, t, n)) return;
1893
- let r = e.getState().comments, i = r.find((e) => e.id === t)?.replies.find((e) => e.id === n);
1894
- e.setState({ comments: r.map((e) => e.id === t ? {
1895
- ...e,
1896
- repliesCount: Math.max(0, (e.repliesCount ?? e.replies.length) - 1),
1897
- replies: e.replies.filter((e) => e.id !== n)
1898
- } : e) });
1899
- try {
1900
- await e.apiClient.deleteReply(t, n);
1901
- let r = e.getState().comments.find((e) => e.id === t);
1902
- r && e.emit("comment:updated", r);
1903
- } catch (r) {
1904
- e.setState({ comments: e.getState().comments.map((e) => e.id === t && i && !e.replies.some((e) => e.id === n) ? {
1905
- ...e,
1906
- repliesCount: (e.repliesCount ?? e.replies.length) + 1,
1907
- replies: [...e.replies, i]
1908
- } : e) }), e.handleError(r);
1909
- }
1910
- }
1911
- async function _n(e, t, n) {
1912
- if (!z(n) || !G(e, n)) return;
1913
- let r = e.getState().comments, i = r.find((e) => e.id === n);
1914
- e.setState({ comments: r.map((e) => e.id === n ? q(e, "resolved") : e) });
1915
- try {
1916
- let r = await e.apiClient.resolveComment(n);
1917
- 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({
1918
- type: "comment_resolved",
1919
- threadId: n,
1920
- message: "resolved a comment"
1921
- });
1922
- } catch (r) {
1923
- t.shouldQueueMutation(r) && t.queueMutation("resolveComment", [n]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && i ? i : e) }), e.handleError(r));
1924
- }
1925
- }
1926
- async function vn(e, t, n) {
1927
- if (!z(n) || !G(e, n)) return;
1928
- let r = e.getState().comments, i = r.find((e) => e.id === n);
1929
- e.setState({ comments: r.map((e) => e.id === n ? q(e, "open") : e) });
1930
- try {
1931
- let t = await e.apiClient.unresolveComment(n);
1932
- e.setState({ comments: e.getState().comments.map((e) => e.id === n ? t : e) }), e.emit("comment:updated", t);
1933
- } catch (r) {
1934
- t.shouldQueueMutation(r) && t.queueMutation("unresolveComment", [n]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && i ? i : e) }), e.handleError(r));
1935
- }
1936
- }
1937
- async function yn(e, t, n) {
1938
- if (!z(n) || !G(e, n)) return;
1939
- let r = e.getState().comments, i = r.find((e) => e.id === n);
1940
- e.setState({ comments: r.map((e) => e.id === n ? q(e, "complete") : e) });
1941
- try {
1942
- let r = await e.apiClient.markComplete(n);
1943
- e.setState({ comments: e.getState().comments.map((e) => e.id === n ? r : e) }), e.emit("comment:completed", r), t.addActivity({
1944
- type: "comment_completed",
1945
- threadId: n,
1946
- message: "marked a comment as complete"
1947
- });
1948
- } catch (r) {
1949
- t.shouldQueueMutation(r) && t.queueMutation("completeComment", [n]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && i ? i : e) }), e.handleError(r));
1950
- }
1951
- }
1952
- async function bn(e, t, n, r, i) {
1953
- if (!z(n) || typeof r != "string") return;
1954
- let a = r.trim();
1955
- if (!a || a.length > Wt || c(a)) return;
1956
- let o = e.getState().comments.find((e) => e.id === n);
1957
- if (!o) return;
1958
- let s = i ? o.replies.find((e) => e.id === i) : o;
1959
- if (!s) return;
1960
- 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];
1961
- if (u) {
1962
- let e = d.findIndex((e) => e.emoji === a), t = d[e];
1963
- t.count <= 1 ? d.splice(e, 1) : d[e] = {
1964
- ...t,
1965
- count: t.count - 1,
1966
- reacted: !1
1967
- };
1968
- } else {
1969
- let e = d.findIndex((e) => e.emoji === a), t = e === -1 ? void 0 : d[e];
1970
- t ? d[e] = {
1971
- ...t,
1972
- count: Math.min(t.count + 1, Ut),
1973
- reacted: !0
1974
- } : d.push({
1975
- emoji: a,
1976
- count: 1,
1977
- reacted: !0
1978
- });
1979
- }
1980
- let f = e.getState().comments;
1981
- e.setState({ comments: f.map((e) => e.id === n ? i ? {
1982
- ...e,
1983
- replies: e.replies.map((e) => e.id === i ? {
1984
- ...e,
1985
- reactions: d
1986
- } : e)
1987
- } : {
1988
- ...e,
1989
- reactions: d
1990
- } : e) });
1991
- try {
1992
- u ? await e.apiClient.removeReaction(n, a, ...i ? [i] : []) : await e.apiClient.addReaction(n, a, ...i ? [i] : []);
1993
- let t = e.getState().comments.find((e) => e.id === n);
1994
- t && e.emit("comment:reaction", {
1995
- commentId: n,
1996
- emoji: a,
1997
- comment: t
1998
- });
1999
- } catch (r) {
2000
- t.shouldQueueMutation(r) && t.queueMutation("reactToComment", [
2001
- n,
2002
- a,
2003
- u ? "remove" : "add",
2004
- ...i ? [i] : []
2005
- ]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n ? i ? {
2006
- ...e,
2007
- replies: e.replies.map((e) => e.id === i ? {
2008
- ...e,
2009
- reactions: l
2010
- } : e)
2011
- } : {
2012
- ...e,
2013
- reactions: l
2014
- } : e) }), e.handleError(r));
2015
- }
2016
- }
2017
- async function xn(e, t, n, r, i) {
2018
- if (!z(n) || !G(e, n)) return;
2019
- let a = Yt({
2020
- x: r,
2021
- y: i
2022
- });
2023
- if (!a) {
2024
- R(e, "invalid_position", "Comment position is invalid");
2025
- return;
2026
- }
2027
- let o = e.getState().comments, s = o.find((e) => e.id === n);
2028
- e.setState({ comments: o.map((e) => e.id === n ? {
2029
- ...e,
2030
- position: a
2031
- } : e) });
2032
- try {
2033
- let t = await e.apiClient.updatePosition(n, a);
2034
- e.setState({ comments: e.getState().comments.map((e) => e.id === n ? t : e) }), e.emit("comment:position", {
2035
- commentId: n,
2036
- position: a
2037
- });
2038
- } catch (r) {
2039
- t.shouldQueueMutation(r) && t.queueMutation("updatePosition", [n, a]) || (e.setState({ comments: e.getState().comments.map((e) => e.id === n && s ? {
2040
- ...e,
2041
- position: s.position
2042
- } : e) }), e.handleError(r));
2043
- }
2044
- }
2045
- function Sn(e, t) {
2046
- e.setState({ selectedComment: t });
2047
- }
2048
- async function Cn(e, t, n, r, i) {
2049
- let a = e.getState().currentUser;
2050
- if (!a) return;
2051
- let o = B(i), s = $t(r);
2052
- if (!o || s == null) {
2053
- R(e, "invalid_highlight", "Highlight data is invalid");
2054
- return;
2055
- }
2056
- let c = `highlight:${s.xpath}:${s.startOffset}:${o.slice(0, 50)}`;
2057
- if (n.has(c)) return;
2058
- n.add(c);
2059
- let l = m(), u = I(e), d = u ? { branch: u } : void 0, f = W("temp"), p = {
2060
- id: f,
2061
- type: "highlight",
2062
- ...u ? { branch: u } : {},
2063
- content: o,
2064
- position: {
2065
- x: 0,
2066
- y: 0
2067
- },
2068
- status: "open",
2069
- priority: "medium",
2070
- author: a,
2071
- userId: a.id,
2072
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2073
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2074
- page: {
2075
- url: l.url,
2076
- path: l.path,
2077
- title: l.title
2078
- },
2079
- replies: [],
2080
- attachments: [],
2081
- textSelection: s
2082
- };
2083
- e.setState({ comments: [...e.getState().comments, p] });
2084
- try {
2085
- let t = await e.apiClient.createHighlight(o, s, l, "medium", f, ...d ? [d] : []);
2086
- K(e, f, t), e.emit("comment:created", t);
2087
- } catch (n) {
2088
- t.shouldQueueMutation(n) && t.queueMutation("createHighlight", [
2089
- o,
2090
- s,
2091
- {
2092
- url: l.url,
2093
- path: l.path,
2094
- title: l.title
2095
- },
2096
- ...d ? [d] : []
2097
- ], f) || (e.setState({ comments: e.getState().comments.filter((e) => e.id !== f) }), e.handleError(n));
2098
- } finally {
2099
- n.delete(c);
2100
- }
2101
- }
2102
- async function wn(e, t, n, r, i, a) {
2103
- let o = e.getState().currentUser;
2104
- if (!o) return;
2105
- let s = B(a), c = Yt(i), l = tn(r);
2106
- if (!s || !c || l == null) {
2107
- R(e, "invalid_drawing", "Drawing comment data is invalid");
2108
- return;
2109
- }
2110
- let u = `drawing:${c.x}:${c.y}:${s.slice(0, 50)}`;
2111
- if (n.has(u)) return;
2112
- n.add(u);
2113
- let d = m(), f = I(e), p = f ? { branch: f } : void 0, h = W("temp"), g = {
2114
- id: h,
2115
- type: "drawing",
2116
- ...f ? { branch: f } : {},
2117
- content: s,
2118
- position: c,
2119
- status: "open",
2120
- priority: "medium",
2121
- author: o,
2122
- userId: o.id,
2123
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2124
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
2125
- page: {
2126
- url: d.url,
2127
- path: d.path,
2128
- title: d.title
2129
- },
2130
- replies: [],
2131
- attachments: [],
2132
- drawingData: l
2133
- };
2134
- e.setState({ comments: [...e.getState().comments, g] });
2135
- try {
2136
- let t = await e.apiClient.createDrawing(s, l, c, d, h, ...p ? [p] : []);
2137
- K(e, h, t), e.emit("comment:created", t);
2138
- } catch (n) {
2139
- t.shouldQueueMutation(n) && t.queueMutation("createDrawing", [
2140
- s,
2141
- l,
2142
- c,
2143
- {
2144
- url: d.url,
2145
- path: d.path,
2146
- title: d.title
2147
- },
2148
- ...p ? [p] : []
2149
- ], h) || (e.setState({ comments: e.getState().comments.filter((e) => e.id !== h) }), e.handleError(n));
2150
- } finally {
2151
- n.delete(u);
2152
- }
2153
- }
2154
- var Tn = {
2155
- c: "comment",
2156
- e: "select",
2157
- d: "draw",
2158
- h: "highlight",
2159
- s: "screenshot"
2160
- };
2161
- function En(e) {
2162
- return typeof e.composedPath == "function" ? e.composedPath() : e.target ? [e.target] : [];
2163
- }
2164
- function J(e) {
2165
- return typeof Element < "u" && e instanceof Element;
2166
- }
2167
- function Dn(e) {
2168
- if (!J(e)) return !1;
2169
- let t = e.tagName.toLowerCase();
2170
- return t === "input" || t === "textarea" || t === "select" || e.isContentEditable || e.getAttribute("role") === "textbox";
2171
- }
2172
- function On(e) {
2173
- let t = e.activeElement;
2174
- for (; t?.shadowRoot?.activeElement;) t = t.shadowRoot.activeElement;
2175
- return t;
2176
- }
2177
- function kn(e) {
2178
- return En(e).some(Dn) ? !0 : typeof document > "u" ? !1 : Dn(On(document));
2179
- }
2180
- function An(e) {
2181
- return En(e).some((e) => J(e) && (e.hasAttribute("data-commentkit") || e.hasAttribute("data-commentkit-ui") || e.hasAttribute("data-commentkit-host")));
2182
- }
2183
- var jn = [
2184
- "popover",
2185
- "dialog",
2186
- "alert-dialog",
2187
- "sheet",
2188
- "dropdown-menu",
2189
- "dropdown-menu-sub",
2190
- "select",
2191
- "combobox"
2192
- ].map((e) => `[data-slot="${e}-content"][data-open]`).join(",");
2193
- function Mn(e) {
2194
- let t = En(e), n = t.find((e) => J(e) && e.hasAttribute("data-commentkit-host"));
2195
- if (J(n)) return !!n.shadowRoot?.querySelector(jn);
2196
- if (typeof document < "u" && (t[0] === document.body || t[0] === document.documentElement)) {
2197
- let e = document.querySelectorAll("[data-commentkit-host]");
2198
- return e.length === 1 && !!e[0]?.shadowRoot?.querySelector(jn);
2199
- }
2200
- return !1;
2201
- }
2202
- function Nn(e) {
2203
- return (e.ctrlKey || e.metaKey) && e.shiftKey && (e.key === "K" || e.key === "k" || e.code === "KeyK");
2204
- }
2205
- function Pn(e) {
2206
- let t = e.key.toLowerCase(), n = e.code.startsWith("Key") ? e.code.slice(3).toLowerCase() : "";
2207
- return Tn[t] ?? Tn[n] ?? null;
2208
- }
2209
- function Fn(e) {
2210
- e.preventDefault(), e.stopPropagation();
2211
- }
2212
- function In(e, t) {
2213
- if (e.isLoginModalVisible) t.toggleLoginModal();
2214
- else if (e.isShortcutsOverlayVisible) t.toggleShortcutsOverlay();
2215
- else if (e.activeComment) t.setState({ activeComment: null });
2216
- else if (e.selectedComment) t.selectComment(null);
2217
- else if (e.activeTool) t.setTool(null);
2218
- else if (e.isSidebarVisible) t.toggleSidebar();
2219
- else if (e.isOverlayVisible) t.toggleOverlay();
2220
- else return !1;
2221
- return !0;
2222
- }
2223
- function Ln(e, t) {
2224
- e.isAuthenticated ? t.toggleOverlay() : t.toggleLoginModal();
2225
- }
2226
- function Rn(e, t, n) {
2227
- if (e.defaultPrevented || e.repeat || e.isComposing) return;
2228
- let r = kn(e), i = An(e);
2229
- if (Nn(e)) {
2230
- if (r) return;
2231
- Fn(e), Ln(t, n);
2232
- } else if (e.key === "Escape") {
2233
- if (Mn(e) || r && !i) return;
2234
- In(t, n) && Fn(e);
2235
- } else if (t.isAuthenticated && (t.isOverlayVisible || t.activeTool !== null) && !r && !e.ctrlKey && !e.metaKey && !e.altKey) {
2236
- if (e.key === "?") {
2237
- Fn(e), n.toggleShortcutsOverlay();
2238
- return;
2239
- }
2240
- let r = Pn(e);
2241
- r && (Fn(e), n.setTool(t.activeTool === r ? null : r));
2242
- }
2243
- }
2244
- 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([
2245
- "createComment",
2246
- "createHighlight",
2247
- "createDrawing",
2248
- "updateComment",
2249
- "deleteComment",
2250
- "resolveComment",
2251
- "unresolveComment",
2252
- "completeComment",
2253
- "addReply",
2254
- "reactToComment",
2255
- "updatePosition"
2256
- ]), Kn = /* @__PURE__ */ new Set([
2257
- "pin",
2258
- "highlight",
2259
- "drawing"
2260
- ]), qn = /* @__PURE__ */ new Set([
2261
- "low",
2262
- "medium",
2263
- "high",
2264
- "urgent"
2265
- ]), Jn = /* @__PURE__ */ new Set(["add", "remove"]);
2266
- function Yn(t) {
2267
- return o(t) && e(t.x) && e(t.y) && n(t.element, Un) && n(t.xpath, Un);
2268
- }
2269
- function Xn(e) {
2270
- return typeof e == "string" && e.length <= M.PAGE && !a(e);
2271
- }
2272
- function Zn(e) {
2273
- return e === void 0 || o(e) && Xn(e.url) && Xn(e.path) && Xn(e.title);
2274
- }
2275
- function Qn(e) {
2276
- return typeof e == "string" && Gn.has(e);
2277
- }
2278
- function $n(e) {
2279
- return Number.isInteger(e) && Number(e) >= 0;
2280
- }
2281
- function er(e) {
2282
- return $n(e) ? Math.min(e, 5) : 0;
2283
- }
2284
- function tr(e) {
2285
- return e.isNetworkError() || e.code === 408 || e.isRateLimitError();
2286
- }
2287
- function nr(e) {
2288
- return e instanceof E ? tr(e) : !0;
2289
- }
2290
- function rr(e) {
2291
- return e instanceof E ? {
2292
- error: e.error,
2293
- message: e.message,
2294
- code: e.code,
2295
- ...e.details ? { details: e.details } : {}
2296
- } : {
2297
- error: "retry_failed",
2298
- message: "Operation failed after maximum retries",
2299
- code: 0
2300
- };
2301
- }
2302
- function ir(e = Date.now()) {
2303
- return `mutation_${e}_${typeof globalThis.crypto?.randomUUID == "function" ? globalThis.crypto.randomUUID() : Math.random().toString(36).slice(2, 12)}`;
2304
- }
2305
- function ar(e) {
2306
- return Array.isArray(e) ? e.map((e) => ar(e)) : o(e) ? Object.fromEntries(Object.entries(e).map(([e, t]) => [e, ar(t)])) : e;
2307
- }
2308
- function or(e) {
2309
- try {
2310
- if (typeof structuredClone == "function") return structuredClone(e);
2311
- } catch {}
2312
- return ar(e);
2313
- }
2314
- function sr(e, t) {
2315
- switch (e) {
2316
- case "createComment": {
2317
- let [e, n, r, a, s, c, l, u] = t;
2318
- 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);
2319
- }
2320
- case "createHighlight": {
2321
- let [e, n, r, a] = t;
2322
- return t.length >= 2 && t.length <= 4 && i(e, Vn) && o(n) && (a === void 0 || o(a)) && Zn(r);
2323
- }
2324
- case "createDrawing": {
2325
- let [e, n, r, a, s] = t;
2326
- return t.length >= 3 && t.length <= 5 && i(e, Vn) && o(n) && Yn(r) && (s === void 0 || o(s)) && Zn(a);
2327
- }
2328
- case "updateComment": return t.length === 2 && r(t[0], Y) && o(t[1]);
2329
- case "deleteComment":
2330
- case "resolveComment":
2331
- case "unresolveComment":
2332
- case "completeComment": return t.length === 1 && r(t[0], Y);
2333
- case "addReply": return (t.length === 2 || t.length === 3) && r(t[0], Y) && i(t[1], Hn) && (t[2] === void 0 || o(t[2]));
2334
- 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));
2335
- case "updatePosition": return t.length === 2 && r(t[0], Y) && Yn(t[1]);
2336
- }
2337
- }
2338
- function cr(e) {
2339
- 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";
2340
- }
2341
- function lr(e) {
2342
- let t = cr(e);
2343
- if (t) throw new E("invalid_mutation", t, 400);
2344
- }
2345
- var ur = "commentkit:offline-queue:";
2346
- function dr() {
2347
- try {
2348
- return typeof localStorage > "u" ? null : localStorage;
2349
- } catch {
2350
- return null;
2351
- }
2352
- }
2353
- function fr(e) {
2354
- return `${ur}${e}`;
2355
- }
2356
- function pr(e, t) {
2357
- if (!e) return;
2358
- let n = dr();
2359
- if (n) try {
2360
- t.length === 0 ? n.removeItem(fr(e)) : n.setItem(fr(e), JSON.stringify(t));
2361
- } catch {}
2362
- }
2363
- function mr(e) {
2364
- if (!e) return [];
2365
- let t = dr();
2366
- if (!t) return [];
2367
- try {
2368
- let n = t.getItem(fr(e));
2369
- if (!n) return [];
2370
- let r = JSON.parse(n);
2371
- if (!Array.isArray(r)) return [];
2372
- let i = [];
2373
- for (let e of r) {
2374
- if (i.length >= zn) break;
2375
- cr(e) === null && i.push(e);
2376
- }
2377
- return i;
2378
- } catch {
2379
- return [];
2380
- }
2381
- }
2382
- function X(e) {
2383
- Promise.resolve().then(e);
2384
- }
2385
- function hr(e, t) {
2386
- if (e.type !== t.type || e.ownerId !== t.ownerId) return !1;
2387
- if (t.type === "updateComment") {
2388
- let n = e.args[1]?.checklistPatch, r = t.args[1]?.checklistPatch;
2389
- if ((n || r) && n?.id !== r?.id) return !1;
2390
- }
2391
- return (t.type === "updatePosition" || t.type === "updateComment") && e.args[0] === t.args[0];
2392
- }
2393
- function gr(e, t) {
2394
- return t.type === "updateComment" && o(e.args[1]) ? {
2395
- ...t,
2396
- args: [t.args[0], {
2397
- ...e.args[1],
2398
- ...t.args[1]
2399
- }]
2400
- } : t;
2401
- }
2402
- function _r(e, t) {
2403
- let n = e.findIndex((e) => hr(e, t));
2404
- if (n !== -1) {
2405
- let r = [...e];
2406
- return r[n] = gr(r[n], t), r;
2407
- }
2408
- return e.length >= zn ? null : [...e, t];
2409
- }
2410
- function Z(e, t, n) {
2411
- e.emit("offline:failed", {
2412
- id: t,
2413
- error: n
2414
- });
2415
- }
2416
- function vr(e, t) {
2417
- return t.isAuthenticated && e.ownerId && e.ownerId === t.currentUser?.id ? null : {
2418
- error: "offline_identity_mismatch",
2419
- 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.",
2420
- code: 403
2421
- };
2422
- }
2423
- function yr(e) {
2424
- let t = e.getState();
2425
- if (!t.isAuthenticated) return;
2426
- let n = t.pendingMutations.flatMap((e) => {
2427
- let n = vr(e, t);
2428
- return n ? [{
2429
- mutation: e,
2430
- error: n
2431
- }] : [];
2432
- });
2433
- if (n.length === 0) return;
2434
- let r = new Set(n.map(({ mutation: e }) => e.id));
2435
- e.setState({ pendingMutations: t.pendingMutations.filter((e) => !r.has(e.id)) });
2436
- for (let { mutation: t, error: r } of n) Z(e, t.id, r);
2437
- }
2438
- function br(e, t) {
2439
- return !e.isOnline || t instanceof E && tr(t);
2440
- }
2441
- function xr(e, t, i, a, o) {
2442
- let s = ir(), c = e.getState(), l = c.currentUser?.id;
2443
- if (!c.isAuthenticated || !r(l, Y)) return Z(e, s, {
2444
- error: "unauthenticated",
2445
- message: "Sign in before saving changes for offline replay.",
2446
- code: 401
2447
- }), !1;
2448
- if (!Qn(i) || !Array.isArray(a) || !sr(i, a) || !n(o, Y)) return Z(e, s, {
2449
- error: "invalid_mutation",
2450
- message: "Queued mutation args are invalid",
2451
- code: 400
2452
- }), !1;
2453
- let u = {
2454
- id: s,
2455
- ownerId: l,
2456
- type: i,
2457
- args: or(a),
2458
- timestamp: Date.now(),
2459
- retries: 0,
2460
- ...o === void 0 ? {} : { tempId: o }
2461
- }, d = _r(e.getState().pendingMutations, u);
2462
- return d ? (e.setState({ pendingMutations: d }), e.emit("offline:queued", u), e.getState().isOnline && X(t), !0) : (Z(e, s, {
2463
- error: "queue_full",
2464
- message: "Offline mutation queue is full",
2465
- code: 0
2466
- }), !1);
2467
- }
2468
- function Sr(e, t, n) {
2469
- if (t.current || e.getState().pendingMutations.length === 0) return;
2470
- let r = e.getState().pendingMutations[0];
2471
- if (!r) return;
2472
- let i = er(r.retries), a = Math.min(Bn, At * 2 ** i);
2473
- t.current = setTimeout(() => {
2474
- t.current = null, n();
2475
- }, a);
2476
- }
2477
- async function Cr(e, t, n, i) {
2478
- let a = e.getState();
2479
- if (!a.isOnline || a.pendingMutations.length === 0 || !a.isAuthenticated || t.current) return;
2480
- t.current = !0;
2481
- let o = e.getState().pendingMutations[0];
2482
- if (!o) {
2483
- t.current = !1;
2484
- return;
2485
- }
2486
- let s = cr(o), c = s ? {
2487
- error: "invalid_mutation",
2488
- message: s,
2489
- code: 400
2490
- } : vr(o, e.getState());
2491
- if (c) {
2492
- let i = e.getState().pendingMutations.filter((e) => e !== o);
2493
- e.setState({ pendingMutations: i }), Z(e, r(o.id, Y) ? o.id : "invalid", c), i.length > 0 && X(n), t.current = !1;
2494
- return;
2495
- }
2496
- e.emit("offline:retrying", {
2497
- id: o.id,
2498
- attempt: o.retries + 1
2499
- });
2500
- let l = i ?? ((t) => Dr(e, t));
2501
- try {
2502
- await l(o);
2503
- let r = e.getState().pendingMutations.filter((e) => e.id !== o.id);
2504
- e.setState({ pendingMutations: r }), e.emit("offline:completed", { id: o.id }), r.length > 0 ? X(n) : t.reconcileAfterDrain && (t.reconcileAfterDrain = !1, cn(e));
2505
- } catch (r) {
2506
- let i = {
2507
- ...o,
2508
- retries: er(o.retries) + 1
2509
- };
2510
- if (nr(r) && i.retries < 5) {
2511
- let t = e.getState().pendingMutations.map((e) => e.id === o.id ? i : e);
2512
- e.setState({ pendingMutations: t }), X(n);
2513
- } else {
2514
- let i = e.getState().pendingMutations.filter((e) => e.id !== o.id);
2515
- e.setState({ pendingMutations: i }), Z(e, o.id, rr(r)), i.length > 0 ? (t.reconcileAfterDrain = !0, X(n)) : (t.reconcileAfterDrain = !1, cn(e));
2516
- }
2517
- } finally {
2518
- t.current = !1;
2519
- }
2520
- }
2521
- function wr(e, t, n) {
2522
- let r = !1, i = e.getState().pendingMutations.map((e) => e.type !== "createComment" && e.type !== "createHighlight" && e.type !== "createDrawing" && e.args[0] === t ? (r = !0, {
2523
- ...e,
2524
- args: [n, ...e.args.slice(1)]
2525
- }) : e);
2526
- r && e.setState({ pendingMutations: i });
2527
- }
2528
- function Tr(e, t, n) {
2529
- let r = e.getState(), i = (e) => e === t || e === n;
2530
- e.setState({
2531
- comments: r.comments.filter((e) => !i(e.id)),
2532
- selectedComment: r.selectedComment && i(r.selectedComment.id) ? null : r.selectedComment,
2533
- activeComment: r.activeComment && i(r.activeComment.id) ? null : r.activeComment
2534
- });
2535
- }
2536
- function Q(e, t, n, r, i = !1) {
2537
- let a = e.getState(), o = a.comments.find((e) => e.id === r || e.id === n.id), s = n, c = (e) => {
2538
- s.status !== e && (s = {
2539
- ...s,
2540
- status: e,
2541
- completedAt: void 0,
2542
- ...e === "complete" ? {} : { resolvedAt: void 0 }
2543
- });
2544
- };
2545
- 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) {
2546
- case "deleteComment":
2547
- Tr(e, n.id, r);
2548
- return;
2549
- case "updateComment":
2550
- i.args[1].status && c(i.args[1].status);
2551
- {
2552
- let { checklistPatch: e, ...t } = i.args[1];
2553
- s = {
2554
- ...s,
2555
- ...t
2556
- }, e && (s.checklist = s.checklist?.map((t) => t.id === e.id ? {
2557
- ...t,
2558
- done: e.done
2559
- } : t));
2560
- }
2561
- break;
2562
- case "resolveComment":
2563
- c("resolved");
2564
- break;
2565
- case "unresolveComment":
2566
- c("open");
2567
- break;
2568
- case "completeComment":
2569
- c("complete");
2570
- break;
2571
- case "updatePosition":
2572
- s = {
2573
- ...s,
2574
- position: i.args[1]
2575
- };
2576
- break;
2577
- case "addReply": {
2578
- let e = o?.replies.find((e) => e.id === i.tempId);
2579
- e && !s.replies.some((t) => t.id === e.id) && (s = {
2580
- ...s,
2581
- replies: [...s.replies, e]
2582
- }), c("open");
2583
- break;
2584
- }
2585
- case "reactToComment": !i.args[3] && o && (s = {
2586
- ...s,
2587
- reactions: o.reactions
2588
- });
2589
- }
2590
- i ? K(e, r, s) : e.setState({ comments: a.comments.map((e) => e.id === r ? s : e) });
2591
- }
2592
- function Er(e, t, n, r) {
2593
- e.setState({ pendingMutations: e.getState().pendingMutations.map((e) => e.type === "reactToComment" && e.args[0] === t && e.args[3] === n ? {
2594
- ...e,
2595
- args: [...e.args.slice(0, 3), r]
2596
- } : e) });
2597
- }
2598
- async function Dr(e, t) {
2599
- lr(t);
2600
- let n = vr(t, e.getState());
2601
- if (n) throw new E(n.error, n.message, n.code);
2602
- switch (t.type) {
2603
- case "createComment": {
2604
- 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);
2605
- u && t.tempId && (Q(e, t, u, t.tempId, !0), wr(e, t.tempId, u.id));
2606
- break;
2607
- }
2608
- case "createHighlight": {
2609
- let [n, r, i, a] = t.args, o = await e.apiClient.createHighlight(n, r, i ?? m(), "medium", t.tempId, ...a ? [a] : []);
2610
- o && t.tempId && (Q(e, t, o, t.tempId, !0), wr(e, t.tempId, o.id));
2611
- break;
2612
- }
2613
- case "createDrawing": {
2614
- let [n, r, i, a, o] = t.args, s = await e.apiClient.createDrawing(n, r, i, a ?? m(), t.tempId, ...o ? [o] : []);
2615
- s && t.tempId && (Q(e, t, s, t.tempId, !0), wr(e, t.tempId, s.id));
2616
- break;
2617
- }
2618
- case "updateComment": {
2619
- let [n, r] = t.args, i = await e.apiClient.updateComment(n, r);
2620
- i && Q(e, t, i, n);
2621
- break;
2622
- }
2623
- case "deleteComment": {
2624
- let [n] = t.args;
2625
- await e.apiClient.deleteComment(n), Tr(e, n);
2626
- break;
2627
- }
2628
- case "resolveComment": {
2629
- let [n] = t.args, r = await e.apiClient.resolveComment(n);
2630
- r && Q(e, t, r, n);
2631
- break;
2632
- }
2633
- case "unresolveComment": {
2634
- let [n] = t.args, r = await e.apiClient.unresolveComment(n);
2635
- r && Q(e, t, r, n);
2636
- break;
2637
- }
2638
- case "completeComment": {
2639
- let [n] = t.args, r = await e.apiClient.markComplete(n);
2640
- r && Q(e, t, r, n);
2641
- break;
2642
- }
2643
- case "addReply": {
2644
- let [n, r, i] = t.args, a = await e.apiClient.addReply(n, r, t.tempId, ...i ? [i] : []);
2645
- if (a && t.tempId) {
2646
- 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);
2647
- on(e, n, t.tempId, i && o ? {
2648
- ...a,
2649
- reactions: o.reactions
2650
- } : a), Er(e, n, t.tempId, a.id);
2651
- let s = e.getState().comments.find((e) => e.id === n);
2652
- s && Q(e, t, s, n);
2653
- }
2654
- break;
2655
- }
2656
- case "reactToComment": {
2657
- let [n, r, i, a] = t.args, o;
2658
- 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] : []);
2659
- break;
2660
- }
2661
- case "updatePosition": {
2662
- let [n, r] = t.args, i = await e.apiClient.updatePosition(n, r);
2663
- i && Q(e, t, i, n);
2664
- break;
2665
- }
2666
- }
2667
- }
2668
- var $ = null;
2669
- async function Or() {
2670
- return $ || ($ = await import("./realtime-C0Z8dXXH.js"), $);
2671
- }
2672
- var kr = typeof window < "u", Ar = /* @__PURE__ */ new Set([
2673
- "list",
2674
- "detail",
2675
- "settings",
2676
- "activity",
2677
- "dev-export"
2678
- ]), jr = /* @__PURE__ */ new Set([
2679
- "comment",
2680
- "draw",
2681
- "highlight",
2682
- "screenshot",
2683
- "select",
2684
- null
2685
- ]), Mr = 256, Nr = "0.7.6";
2686
- function Pr(e) {
2687
- let t = e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:[-+].*)?$/);
2688
- return t ? [
2689
- Number(t[1]),
2690
- Number(t[2] ?? 0),
2691
- Number(t[3] ?? 0)
2692
- ] : null;
2693
- }
2694
- function Fr(e) {
2695
- return /^v?\d+(?:\.\d+)?(?:\.\d+)?-/.test(e.trim());
2696
- }
2697
- function Ir(e, t) {
2698
- if (Fr(e)) return !1;
2699
- let n = Pr(e), r = Pr(t);
2700
- if (!n || !r) return !1;
2701
- for (let e = 0; e < 3; e++) {
2702
- let t = n[e] ?? 0, i = r[e] ?? 0;
2703
- if (t > i) return !0;
2704
- if (t < i) return !1;
2705
- }
2706
- return !1;
2707
- }
2708
- var Lr = class extends et {
2709
- get isProcessingQueue() {
2710
- return this.queueGuard.current;
2711
- }
2712
- set isProcessingQueue(e) {
2713
- this.queueGuard.current = e;
2714
- }
2715
- get isLoadingMore() {
2716
- return this.loadMoreGuard.current;
2717
- }
2718
- set isLoadingMore(e) {
2719
- this.loadMoreGuard.current = e;
2720
- }
2721
- get retryTimer() {
2722
- return this.retryTimerRef.current;
2723
- }
2724
- set retryTimer(e) {
2725
- this.retryTimerRef.current = e;
2726
- }
2727
- constructor(e, t) {
2728
- 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();
2729
- let { authToken: n, ...r } = e;
2730
- this.config = r, this.initialAuthToken = n, this.localDemo = t ?? null, this.localDemo && (this.config.features = {
2731
- comments: !0,
2732
- drawing: !1,
2733
- highlighting: !1,
2734
- screenshots: !1,
2735
- realtime: !1
2736
- }, this.config.ui = {
2737
- ...this.config.ui,
2738
- loadRemoteFonts: !1
2739
- }), 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 = {
2740
- getState: () => this.getInternalState(),
2741
- setState: (e) => this.setState(e),
2742
- apiClient: this.apiClient,
2743
- emit: (e, t) => {
2744
- this.destroyed || this.emit(e, t);
2745
- },
2746
- handleError: (e) => this.handleError(e),
2747
- config: this.config,
2748
- isLocalDemo: !!this.localDemo
2749
- }, this.kbdCallbacks = {
2750
- toggleLoginModal: () => this.toggleLoginModal(),
2751
- toggleOverlay: () => this.toggleOverlay(),
2752
- toggleSidebar: () => this.toggleSidebar(),
2753
- toggleShortcutsOverlay: () => this.toggleShortcutsOverlay(),
2754
- setTool: (e) => this.setTool(e),
2755
- selectComment: (e) => this.selectComment(e),
2756
- setState: (e) => this.setState(e)
2757
- }, this.commentCb = {
2758
- shouldQueueMutation: (e) => this.shouldQueueMutation(e),
2759
- queueMutation: (e, t, n) => this.queueMutation(e, t, n),
2760
- addActivity: (e) => this.addActivity(e)
2761
- }, this.realtimeRefs = {
2762
- wsManager: this.wsManager,
2763
- wsUnsubscribers: this.wsUnsubscribers,
2764
- mouseMoveHandler: this.mouseMoveHandler
2765
- }, this.localDemo && (this.restoreDemoState(), this.localDemo.subscribe((e) => {
2766
- e !== "persist" && this.restoreDemoState();
2767
- })), e.enabled !== !1 && kr && Promise.resolve().then(() => this.boot()).catch((e) => this.handleError(e));
2768
- /* v8 ignore stop */
2769
- }
2770
- isLocalDemo() {
2771
- return this.localDemo !== null;
2772
- }
2773
- restoreDemoState() {
2774
- if (!this.localDemo || this.destroyed) return;
2775
- let e = this.localDemo.getSession().expired, t = this.getInternalState().activeBranch ?? null;
2776
- this.overlayBeforeTool = null, this.setState({
2777
- ...jt(),
2778
- currentUser: e ? null : { ...this.localDemo.user },
2779
- isAuthenticated: !e,
2780
- isOverlayVisible: !e,
2781
- isOnline: !0,
2782
- activeBranch: t,
2783
- comments: this.localDemo.getComments().filter((e) => !t || e.branch === t),
2784
- project: {
2785
- id: "local-demo",
2786
- slug: "local-demo",
2787
- name: "Private browser demo",
2788
- url: window.location.origin,
2789
- features: {
2790
- comments: !0,
2791
- drawing: !1,
2792
- highlighting: !1,
2793
- screenshots: !1,
2794
- realtime: !1
2795
- },
2796
- limits: {
2797
- maxMembers: 1,
2798
- retentionDays: 1
2799
- }
2800
- }
2801
- });
2802
- }
2803
- startLocalDemo() {
2804
- this.localDemo && !this.destroyed && (this.localDemo.activate(), this.setState({
2805
- isOverlayVisible: !0,
2806
- isSidebarVisible: !1,
2807
- isLoginModalVisible: !1,
2808
- error: null
2809
- }), this.setTool("comment"));
2810
- }
2811
- detectEnvironment() {
2812
- let e = window.location.hostname;
2813
- 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";
2814
- }
2815
- async boot() {
2816
- if (this.destroyed) return;
2817
- this.keyboardHandler = this.handleKeyboardShortcuts.bind(this), window.addEventListener("keydown", this.keyboardHandler, !0);
2818
- let e = this.config.ui?.activation;
2819
- e?.mode === "hold" && e.key && (this.holdActivationHandler = (e) => {
2820
- if (this.destroyed || !this.matchesHoldKey(e)) return;
2821
- let t = this.getInternalState().activeTool;
2822
- e.type === "keydown" && !t && !j() ? this.setTool("select") : e.type === "keyup" && t === "select" && this.setTool(null);
2823
- }, window.addEventListener("keydown", this.holdActivationHandler), window.addEventListener("keyup", this.holdActivationHandler), this.holdBlurHandler = () => {
2824
- this.destroyed || this.getInternalState().activeTool === "select" && this.setTool(null);
2825
- }, 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 = () => {
2826
- this.destroyed || (this.setState({ isOnline: !0 }), this.processOfflineQueue());
2827
- }, this.offlineHandler = () => {
2828
- this.destroyed || this.setState({ isOnline: !1 });
2829
- }, window.addEventListener("online", this.onlineHandler), window.addEventListener("offline", this.offlineHandler), this.autoDetectInviteToken(), this.config.apiKey && await this.initialize());
2830
- }
2831
- autoDetectInviteToken() {
2832
- try {
2833
- let e = new URLSearchParams(window.location.search), t = e.get("ck_invite");
2834
- if (!t) return;
2835
- /^[\w-]{64}$/.test(t) && (this.config.inviteToken = t), e.delete("ck_invite");
2836
- let n = e.toString(), r = window.location.pathname + (n ? `?${n}` : "") + window.location.hash;
2837
- window.history.replaceState(window.history.state, "", r);
2838
- } catch {}
2839
- }
2840
- async initialize() {
2841
- if (!(this.initialized || this.destroyed)) {
2842
- this.initialized = !0, this.bootAttempts += 1;
2843
- try {
2844
- this.setState({
2845
- isLoading: !0,
2846
- error: null
2847
- });
2848
- let e = await this.apiClient.validateApiKey();
2849
- if (this.destroyed) return;
2850
- if (!e.valid) {
2851
- this.handleError({
2852
- error: "invalid_api_key",
2853
- message: "Invalid API key",
2854
- code: 401
2855
- });
2856
- return;
2857
- }
2858
- e.project?.id && (this.config.projectId = String(e.project.id), this.hydrateOfflineQueue());
2859
- let t = e.project?.slug ?? e.project?.id;
2860
- 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) {
2861
- let t = e.project.reverb;
2862
- this.config.reverb = {
2863
- key: t.key,
2864
- host: t.host,
2865
- port: t.port ?? 443,
2866
- scheme: t.scheme ?? "wss"
2867
- };
2868
- }
2869
- let n = e.project?.sdkLatestVersion;
2870
- n && Ir(n, "0.7.6") && (console.warn(`[CommentKit] You are using v${Nr}. Update to v${n}: npm update @commentkit/comment-kit`), this.emit("sdk:outdated", {
2871
- current: Nr,
2872
- latest: n
2873
- })), this.setState({
2874
- project: e.project,
2875
- isLoading: !1
2876
- }), await this.restorePersistedSession();
2877
- } catch (e) {
2878
- if (this.initialized = !1, this.handleError(e), this.bootAttempts < 3 && !this.destroyed) {
2879
- let e = 2e3 * 2 ** (this.bootAttempts - 1);
2880
- this.bootRetryTimer = setTimeout(() => {
2881
- this.bootRetryTimer = null, this.initialize();
2882
- }, e);
2883
- }
2884
- }
2885
- }
2886
- }
2887
- setState(e) {
2888
- this.destroyed || (e.activeTool === null && e.isOverlayVisible === void 0 && this.overlayBeforeTool !== null && (e = {
2889
- ...e,
2890
- isOverlayVisible: this.overlayBeforeTool
2891
- }, this.overlayBeforeTool = null), this.pendingStateUpdates ? Object.assign(this.pendingStateUpdates, e) : this.pendingStateUpdates = { ...e }, this.flushScheduled || (this.flushScheduled = !0, Promise.resolve().then(() => this.flushState())));
2892
- }
2893
- getInternalState() {
2894
- return this.localDemo?.checkExpiry(), this.pendingStateUpdates ? {
2895
- ...this.state,
2896
- ...this.pendingStateUpdates
2897
- } : this.state;
2898
- }
2899
- cloneStateSnapshot(e) {
2900
- return {
2901
- ...e,
2902
- currentUser: e.currentUser ? structuredClone(e.currentUser) : null,
2903
- project: e.project ? structuredClone(e.project) : null,
2904
- projectContext: e.projectContext ? structuredClone(e.projectContext) : null,
2905
- comments: structuredClone(e.comments),
2906
- commentQuery: e.commentQuery ? { ...e.commentQuery } : void 0,
2907
- selectedComment: e.selectedComment ? structuredClone(e.selectedComment) : null,
2908
- activeComment: e.activeComment ? structuredClone(e.activeComment) : null,
2909
- activeDrawing: e.activeDrawing ? structuredClone(e.activeDrawing) : null,
2910
- activeScreenshot: e.activeScreenshot ? {
2911
- ...e.activeScreenshot,
2912
- dimensions: { ...e.activeScreenshot.dimensions }
2913
- } : null,
2914
- onlineUsers: structuredClone(e.onlineUsers),
2915
- pendingMutations: structuredClone(e.pendingMutations),
2916
- activities: structuredClone(e.activities),
2917
- seenThreadIds: new Set(e.seenThreadIds),
2918
- pagination: e.pagination ? { ...e.pagination } : null
2919
- };
2920
- }
2921
- flushState() {
2922
- if (this.destroyed) {
2923
- this.pendingStateUpdates = null, this.flushScheduled = !1;
2924
- return;
2925
- }
2926
- if (this.isFlushing) return;
2927
- this.flushScheduled = !1;
2928
- let e = this.pendingStateUpdates;
2929
- if (!e) return;
2930
- this.pendingStateUpdates = null;
2931
- let t = this.state;
2932
- this.state = {
2933
- ...t,
2934
- ...e
2935
- }, this.isFlushing = !0;
2936
- try {
2937
- this.notifySubscribers(e, t);
2938
- } finally {
2939
- this.isFlushing = !1;
2940
- }
2941
- this.pendingStateUpdates && !this.flushScheduled && (this.flushScheduled = !0, Promise.resolve().then(() => this.flushState()));
2942
- }
2943
- notifySubscribers(e, t) {
2944
- 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);
2945
- let n = Object.keys(e);
2946
- for (let [e, t] of this.sliceSubscribers) {
2947
- let r = Ot[e];
2948
- if (n.some((e) => r.includes(e))) for (let n of t) try {
2949
- n(this.state);
2950
- } catch (t) {
2951
- console.error(`[CommentKit] Error in ${e} slice subscriber:`, t);
2952
- }
2953
- }
2954
- this.emit("state:changed", this.state);
2955
- }
2956
- flushStateSync() {
2957
- this.pendingStateUpdates && !this.isFlushing && this.flushState();
2958
- }
2959
- getState() {
2960
- return this.localDemo?.checkExpiry(), this.flushStateSync(), this.cloneStateSnapshot(this.state);
2961
- }
2962
- getFeatures() {
2963
- let e = this.canWriteComments();
2964
- return {
2965
- comments: e,
2966
- drawing: e && (this.config.features?.drawing ?? !0),
2967
- highlighting: e && (this.config.features?.highlighting ?? !0),
2968
- screenshots: e && (this.config.features?.screenshots ?? !0),
2969
- realtime: this.config.features?.realtime ?? !0
2970
- };
2971
- }
2972
- canWriteComments() {
2973
- return this.getWriteAccess().canWrite;
2974
- }
2975
- getWriteAccess() {
2976
- return Xe(this.config, this.getInternalState(), this.writeRestriction);
2977
- }
2978
- requireCommentWrite() {
2979
- let e = this.getWriteAccess();
2980
- return e.canWrite ? !0 : (this.handleError({
2981
- error: e.planRequired ? "plan_required" : "feature_disabled",
2982
- message: e.message,
2983
- code: e.planRequired ? 402 : 403
2984
- }), !1);
2985
- }
2986
- getConfig() {
2987
- return {
2988
- apiKey: this.config.apiKey,
2989
- ...this.config.baseUrl !== void 0 && { baseUrl: this.config.baseUrl },
2990
- ...this.config.enabled !== void 0 && { enabled: this.config.enabled },
2991
- screenshotProvider: this.config.screenshotProvider,
2992
- branch: this.config.branch,
2993
- persistence: this.config.persistence,
2994
- realtime: this.config.realtime ? { ...this.config.realtime } : void 0,
2995
- ui: this.config.ui ? { ...this.config.ui } : void 0
2996
- };
2997
- }
2998
- async validateInvite(e) {
2999
- if (this.destroyed || this.localDemo) return;
3000
- let t = this.beginAuthRequest();
3001
- return Dt(this.ctx, e, (e) => bt(this.ctx, e, t), t);
3002
- }
3003
- onSlice(e, t) {
3004
- if (!Ot[e] || typeof t != "function" || this.destroyed) return () => {};
3005
- let n = this.sliceSubscribers.get(e);
3006
- return n || (n = /* @__PURE__ */ new Set(), this.sliceSubscribers.set(e, n)), n.add(t), () => n.delete(t);
3007
- }
3008
- select(e, t) {
3009
- if (typeof e != "function" || typeof t != "function" || this.destroyed) return () => {};
3010
- let n;
3011
- try {
3012
- n = e(this.getInternalState());
3013
- } catch (e) {
3014
- return this.handleError(e), () => {};
3015
- }
3016
- return this.on("state:changed", (r) => {
3017
- try {
3018
- let i = e(r);
3019
- i !== n && (n = i, t(i));
3020
- } catch (e) {
3021
- this.handleError(e);
3022
- }
3023
- });
3024
- }
3025
- handleError(e) {
3026
- if (this.destroyed) return;
3027
- let t = e && typeof e == "object" ? e : null, n = typeof t?.message == "string" && t.message ? t.message : String(e ?? "Unknown error"), r = {
3028
- error: typeof t?.error == "string" && t.error ? t.error : "unknown",
3029
- message: n,
3030
- code: typeof t?.code == "number" && Number.isFinite(t.code) ? t.code : 0,
3031
- ...t?.details && typeof t.details == "object" ? { details: t.details } : {}
3032
- }, i = r.details?.quota, a = i && typeof i == "object" ? i : null, o = r.error === "quota_exceeded" && a?.type === "feature" && a.feature === "comments";
3033
- if (r.code === 402 && (r.error === "plan_required" || o)) {
3034
- this.writeRestriction = r.error === "plan_required" || a?.reason === "plan_required" || !a?.reason && a?.plan === "none" ? "plan_required" : "feature_disabled";
3035
- let e = this.getInternalState().projectContext;
3036
- e && this.setState({ projectContext: {
3037
- ...e,
3038
- permissions: {
3039
- ...e.permissions,
3040
- canWriteComments: !1,
3041
- writeRestriction: this.writeRestriction,
3042
- canManageComments: !1
3043
- }
3044
- } });
3045
- let t = this.getInternalState().activeTool;
3046
- t !== null && t !== "select" && this.setTool(null);
3047
- }
3048
- console.error("[CommentKit]", r.message), this.setState({
3049
- error: r.message,
3050
- isLoading: !1
3051
- }), this.emit("error", r);
3052
- }
3053
- async restorePersistedSession() {
3054
- this.config.persistence === "memory" && lt(this.config.projectId);
3055
- let e = this.initialAuthToken === void 0 ? this.config.persistence === "memory" ? void 0 : ct(this.config.projectId)?.token : this.initialAuthToken;
3056
- if (this.initialAuthToken = void 0, e === void 0) return;
3057
- let t = () => !this.destroyed && this.authRequestRevision === 0;
3058
- try {
3059
- let { verifyAndRestoreToken: n } = await import("./token-session-DplW5QDx.js");
3060
- await n(this.ctx, e, t, this.config.persistence !== "memory") && await this.afterAuthenticated();
3061
- } catch {
3062
- t() && this.handleAuthExpired();
3063
- }
3064
- }
3065
- async afterAuthenticated(e) {
3066
- this.destroyed || (this.sessionRevision++, this.draftUploads = /* @__PURE__ */ new WeakMap(), e && e !== this.getInternalState().currentUser?.id && this.setState({
3067
- comments: [],
3068
- selectedComment: null,
3069
- projectContext: null,
3070
- activities: [],
3071
- seenThreadIds: /* @__PURE__ */ new Set()
3072
- }), yr(this.ctx), this.getFeatures().realtime && this.initializeWebSocket(), await Promise.all([this.loadComments(), this.reloadProjectContext()]), this.handleDeepLink(), this.getInternalState().pendingMutations.length > 0 && this.scheduleRetry());
3073
- }
3074
- beginAuthRequest() {
3075
- let e = ++this.authRequestRevision;
3076
- return () => !this.destroyed && e === this.authRequestRevision;
3077
- }
3078
- async login(e) {
3079
- if (!(this.destroyed || this.localDemo)) return this.config.inviteToken ? this.validateInvite(e) : bt(this.ctx, e, this.beginAuthRequest());
3080
- }
3081
- async verifyOtp(e) {
3082
- if (this.destroyed || this.localDemo) return;
3083
- let t = Date.now();
3084
- if (t < this.otpCooldownUntil) {
3085
- let e = Math.ceil((this.otpCooldownUntil - t) / 1e3);
3086
- this.handleError({
3087
- error: "otp_throttled",
3088
- message: `Too many attempts. Please wait ${e}s and try again.`,
3089
- code: 429
3090
- });
3091
- return;
3092
- }
3093
- let n = this.getInternalState().currentUser?.id;
3094
- return xt(this.ctx, e, {
3095
- isCurrent: this.beginAuthRequest(),
3096
- onAuthenticated: async () => {
3097
- await this.afterAuthenticated(n);
3098
- },
3099
- onSuccess: () => {
3100
- this.config.inviteToken = void 0, this.otpFailedAttempts = 0, this.otpCooldownUntil = 0;
3101
- },
3102
- onWrongOtp: () => {
3103
- if (this.otpFailedAttempts += 1, this.otpFailedAttempts >= 3) {
3104
- let e = Math.min(3e4, 2e3 * 2 ** (this.otpFailedAttempts - 3));
3105
- this.otpCooldownUntil = Date.now() + e;
3106
- }
3107
- }
3108
- });
3109
- }
3110
- cancelOtp() {
3111
- this.destroyed || (this.authRequestRevision++, St(this.ctx));
3112
- }
3113
- async resendOtp() {
3114
- if (this.destroyed || this.localDemo) return;
3115
- let e = this.getInternalState().otpEmail;
3116
- return this.config.inviteToken && e ? this.validateInvite(e) : Ct(this.ctx, this.beginAuthRequest());
3117
- }
3118
- logout() {
3119
- this.destroyed || (this.authRequestRevision++, this.localDemo ? (this.setTool(null), this.setState({
3120
- isOverlayVisible: !1,
3121
- isSidebarVisible: !1
3122
- })) : (this.sessionRevision++, this.draftUploads = /* @__PURE__ */ new WeakMap(), this.writeRestriction = null, this.setState({ projectContext: null }), this.overlayBeforeTool = null, wt(this.ctx, () => {
3123
- this.disconnectRealtime(!0);
3124
- })));
3125
- }
3126
- handleAuthExpired() {
3127
- 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));
3128
- }
3129
- toggleLoginModal() {
3130
- this.destroyed || this.localDemo || (this.getInternalState().isLoginModalVisible && this.cancelOtp(), Et(this.ctx));
3131
- }
3132
- requiresShortcut() {
3133
- return this.localDemo ? !0 : this.config.environment !== "development";
3134
- }
3135
- toggleOverlay() {
3136
- if (this.destroyed) return;
3137
- let e = !this.getInternalState().isOverlayVisible;
3138
- this.overlayBeforeTool = null, this.setState({
3139
- isOverlayVisible: e,
3140
- ...!e && {
3141
- selectedComment: null,
3142
- activeComment: null
3143
- }
3144
- });
3145
- }
3146
- toggleSidebar() {
3147
- this.destroyed || this.setState({ isSidebarVisible: !this.getInternalState().isSidebarVisible });
3148
- }
3149
- setTool(e) {
3150
- if (this.destroyed || !jr.has(e) || this.localDemo && e !== null && e !== "comment" && e !== "select") return;
3151
- let t = this.getInternalState();
3152
- if (e !== null && e !== "select" && !this.requireCommentWrite()) return;
3153
- if (!t.isAuthenticated && e !== "select" && e !== null) {
3154
- this.toggleLoginModal();
3155
- return;
3156
- }
3157
- let n;
3158
- e === null ? (n = this.overlayBeforeTool ?? t.isOverlayVisible, this.overlayBeforeTool = null) : (this.overlayBeforeTool === null && (this.overlayBeforeTool = t.isOverlayVisible), n = !1), this.setState({
3159
- activeTool: e,
3160
- isCommentModeActive: e === "comment",
3161
- isDrawingModeActive: e === "draw",
3162
- isHighlightModeActive: e === "highlight",
3163
- isScreenshotModeActive: e === "screenshot",
3164
- isOverlayVisible: n,
3165
- selectedComment: null,
3166
- activeComment: null,
3167
- activeDrawing: null,
3168
- activeScreenshot: null
3169
- });
3170
- }
3171
- operationContext(e) {
3172
- this.localDemo?.refresh();
3173
- let t = this.localDemo?.getRevision(), n = this.sessionRevision, r = () => !this.destroyed && n === this.sessionRevision && t === this.localDemo?.getRevision();
3174
- return {
3175
- ...this.ctx,
3176
- isCurrent: r,
3177
- setState: (e) => {
3178
- r() && this.ctx.setState(e);
3179
- },
3180
- emit: (t, n) => {
3181
- r() && (e && (t === "comment:created" || t === "comment:updated") && (e.result = {
3182
- status: "confirmed",
3183
- commentId: n.id
3184
- }), this.ctx.emit(t, n));
3185
- },
3186
- handleError: (e) => {
3187
- r() && this.ctx.handleError(e);
3188
- }
3189
- };
3190
- }
3191
- operationCallbacks(e) {
3192
- let t = this.localDemo?.getRevision(), n = this.sessionRevision, r = () => !this.destroyed && n === this.sessionRevision && t === this.localDemo?.getRevision();
3193
- return {
3194
- ...this.commentCb,
3195
- queueMutation: (...t) => {
3196
- let n = r() && this.commentCb.queueMutation(...t);
3197
- return n && e && r() && (e.result = {
3198
- status: "queued",
3199
- commentId: t[2]
3200
- }), n;
3201
- },
3202
- addActivity: (e) => {
3203
- r() && this.commentCb.addActivity(e);
3204
- }
3205
- };
3206
- }
3207
- commentsRequestContext(e) {
3208
- let t = this.operationContext();
3209
- return {
3210
- ...t,
3211
- isCurrent: () => e === this.commentsFetchRevision && !!t.isCurrent?.(),
3212
- setState: (n) => {
3213
- e === this.commentsFetchRevision && t.setState(n);
3214
- },
3215
- handleError: (n) => {
3216
- e === this.commentsFetchRevision && t.handleError(n);
3217
- }
3218
- };
3219
- }
3220
- async loadComments() {
3221
- return cn(this.commentsRequestContext(++this.commentsFetchRevision));
3222
- }
3223
- async loadMoreComments() {
3224
- this.destroyed || await ln(this.commentsRequestContext(this.commentsFetchRevision), this.loadMoreGuard);
3225
- }
3226
- async setCommentQuery(e) {
3227
- if (this.destroyed || !this.getInternalState().isAuthenticated || this.localDemo) return;
3228
- let t = {
3229
- ...e,
3230
- search: e.search?.trim().slice(0, 200) || void 0
3231
- };
3232
- if (JSON.stringify(t) !== JSON.stringify(this.getInternalState().commentQuery)) return this.setState({
3233
- commentQuery: t,
3234
- pagination: null,
3235
- selectedComment: null
3236
- }), this.loadComments();
3237
- }
3238
- async loadEarlierReplies() {
3239
- let e = this.getInternalState(), t = e.comments.find((t) => t.id === e.selectedComment?.id);
3240
- if (!(this.destroyed || e.loadingThreadId || !t?.repliesPagination?.nextCursor)) return un(this.operationContext(), t.id, t.repliesPagination.nextCursor);
3241
- }
3242
- async reloadComments() {
3243
- if (!this.destroyed) return this.loadComments();
3244
- }
3245
- async refreshAttachmentUrl(e) {
3246
- if (this.destroyed || this.localDemo || !this.getInternalState().isAuthenticated || typeof e != "string" || !e || e.length > 256 || a(e)) return null;
3247
- let t = (t) => [...t.attachments ?? [], ...t.replies.flatMap((e) => e.attachments ?? [])].find((t) => t.id === e), n = this.getInternalState().comments.find((e) => t(e));
3248
- if (!n) return null;
3249
- 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);
3250
- c || (c = (async () => {
3251
- try {
3252
- let e = await this.apiClient.getComment(n.id);
3253
- if (!s() || e?.id !== n.id || !Array.isArray(e.replies)) return null;
3254
- let t = this.getInternalState(), r = t.comments.find((e) => e.id === n.id);
3255
- if (!r) return null;
3256
- let i = (e, t) => e?.map((e) => {
3257
- let n = t?.find((t) => t.id === e.id);
3258
- return n && l(n.url, !0) ? {
3259
- ...e,
3260
- url: n.url,
3261
- ...l(n.thumbnail, !0) ? { thumbnail: n.thumbnail } : {}
3262
- } : e;
3263
- }), a = {
3264
- ...r,
3265
- attachments: i(r.attachments, e.attachments) ?? [],
3266
- replies: r.replies.map((t) => ({
3267
- ...t,
3268
- attachments: i(t.attachments, e.replies.find((e) => e.id === t.id)?.attachments)
3269
- }))
3270
- };
3271
- return this.setState({
3272
- comments: t.comments.map((e) => e.id === n.id ? a : e),
3273
- ...t.selectedComment?.id === n.id ? { selectedComment: a } : {}
3274
- }), e;
3275
- } catch (e) {
3276
- return s() && this.handleError(e), null;
3277
- } finally {
3278
- this.attachmentRefreshes.get(o) === c && this.attachmentRefreshes.delete(o);
3279
- }
3280
- })(), this.attachmentRefreshes.set(o, c));
3281
- let u = await c;
3282
- if (!s() || !u) return null;
3283
- let d = this.getInternalState().comments.find((e) => e.id === n.id);
3284
- if (!d || !t(d)) return null;
3285
- let f = t(u)?.url;
3286
- return l(f, !0) ? f : null;
3287
- }
3288
- async reloadProjectContext() {
3289
- if (this.destroyed || this.localDemo || !this.getInternalState().isAuthenticated) return;
3290
- let e = this.operationContext(), t = this.sessionRevision, n = ++this.contextFetchRevision;
3291
- try {
3292
- let r = await this.apiClient.getProjectContext();
3293
- if (this.destroyed || t !== this.sessionRevision || n !== this.contextFetchRevision) return;
3294
- if (r?.project && Array.isArray(r.members)) {
3295
- let t = this.canWriteComments();
3296
- if (r.permissions.canWriteComments !== void 0 && (this.writeRestriction = null), e.setState({ projectContext: r }), r.permissions.canWriteComments === !1) {
3297
- let e = this.getInternalState().activeTool;
3298
- e !== null && e !== "select" && this.setTool(null);
3299
- }
3300
- !t && this.canWriteComments() && this.getInternalState().isOnline && this.scheduleRetry();
3301
- }
3302
- } catch (t) {
3303
- n === this.contextFetchRevision && t.code !== 404 && e.handleError(t);
3304
- }
3305
- }
3306
- async setBranch(e) {
3307
- if (this.destroyed || e !== null && (typeof e != "string" || !e.trim() || e.length > 255 || a(e))) return;
3308
- let t = e?.trim() ?? null;
3309
- (this.getInternalState().activeBranch ?? null) !== t && (this.setState({
3310
- activeBranch: t,
3311
- selectedComment: null,
3312
- panelView: "list",
3313
- comments: [],
3314
- pagination: null
3315
- }), await this.loadComments());
3316
- }
3317
- async uploadDraftFiles(e) {
3318
- if (this.destroyed || this.localDemo || !this.getInternalState().isAuthenticated) throw Error("Sign in to attach files.");
3319
- if (!this.requireCommentWrite()) throw Error("This workspace is read-only.");
3320
- if (!Array.isArray(e) || e.length > 10) throw Error("Attach up to 10 files.");
3321
- let t = this.sessionRevision, n = [], r = this.draftUploads;
3322
- for (let i of e) {
3323
- let e = r.get(i);
3324
- e || (e = this.apiClient.uploadFile(i, /^image\/(jpeg|png|gif|webp)$/.test(i.type) ? "screenshot" : "attachment").then((e) => e.id), r.set(i, e));
3325
- try {
3326
- n.push(await e);
3327
- } catch (e) {
3328
- throw r.delete(i), !this.destroyed && t === this.sessionRevision && this.handleError(e), e;
3329
- }
3330
- if (this.destroyed || t !== this.sessionRevision) throw Error("Your session changed. Please sign in again.");
3331
- }
3332
- return n;
3333
- }
3334
- async createComment(e, t, n, r = "medium", i, a, o) {
3335
- if (this.destroyed || !this.requireCommentWrite()) return;
3336
- if (this.localDemo && (e !== "pin" || o?.files?.length || o?.attachmentIds?.length)) {
3337
- this.handleError({
3338
- error: "demo_unavailable",
3339
- message: "Files and drawings are unavailable in the private browser demo.",
3340
- code: 400
3341
- });
3342
- return;
3343
- }
3344
- let s = o?.[tt];
3345
- return dn(this.operationContext(s), this.operationCallbacks(s), this.activeMutations, e, t, n, r, i, a, {
3346
- ...o,
3347
- branch: o?.branch ?? I(this.ctx)
3348
- });
3349
- }
3350
- async updateComment(e, t) {
3351
- if (!this.destroyed && this.requireCommentWrite()) return fn(this.operationContext(), this.operationCallbacks(), e, t);
3352
- }
3353
- async deleteComment(e) {
3354
- if (!this.destroyed && this.requireCommentWrite()) return pn(this.operationContext(), this.operationCallbacks(), e);
3355
- }
3356
- async addReply(e, t, n) {
3357
- if (this.destroyed || !this.requireCommentWrite()) return;
3358
- let { [tt]: r, ...i } = n ?? {};
3359
- return mn(this.operationContext(r), this.operationCallbacks(r), e, t, n ? i : void 0);
3360
- }
3361
- async updateReply(e, t, n, r) {
3362
- if (!this.destroyed && this.requireCommentWrite()) return hn(this.operationContext(), e, t, n, r);
3363
- }
3364
- async deleteReply(e, t) {
3365
- if (!this.destroyed && this.requireCommentWrite()) return gn(this.operationContext(), e, t);
3366
- }
3367
- requireThreadStatus(e, t = !1) {
3368
- let n = this.getInternalState();
3369
- if (n.projectContext?.permissions?.accessScope !== "project") return !0;
3370
- let r = n.comments.find((t) => t.id === e)?.author.id === n.currentUser?.id;
3371
- return !t && r ? !0 : (this.handleError({
3372
- error: "forbidden",
3373
- message: t ? "Only workspace members can mark feedback complete." : "You can only resolve or reopen your own feedback.",
3374
- code: 403
3375
- }), !1);
3376
- }
3377
- async resolveComment(e) {
3378
- if (!this.destroyed && this.requireCommentWrite() && this.requireThreadStatus(e)) return _n(this.operationContext(), this.operationCallbacks(), e);
3379
- }
3380
- async unresolveComment(e) {
3381
- if (!this.destroyed && this.requireCommentWrite() && this.requireThreadStatus(e)) return vn(this.operationContext(), this.operationCallbacks(), e);
3382
- }
3383
- selectComment(e) {
3384
- this.destroyed || (Sn(this.operationContext(), e), e?.detailLoaded === !1 && !this.localDemo && un(this.operationContext(), e.id));
3385
- }
3386
- async completeComment(e) {
3387
- if (!this.destroyed && this.requireCommentWrite() && this.requireThreadStatus(e, !0)) return yn(this.operationContext(), this.operationCallbacks(), e);
3388
- }
3389
- async reactToComment(e, t, n) {
3390
- if (this.destroyed || !this.requireCommentWrite()) return;
3391
- let r = `${e}:${n ?? "parent"}`, i = this.sessionRevision, a = async () => {
3392
- !this.destroyed && i === this.sessionRevision && this.requireCommentWrite() && await bn(this.operationContext(), this.operationCallbacks(), e, t, n);
3393
- }, o = this.reactionRequests.get(r), s = o ? o.then(a, a) : a();
3394
- this.reactionRequests.set(r, s);
3395
- try {
3396
- await s;
3397
- } finally {
3398
- this.reactionRequests.get(r) === s && this.reactionRequests.delete(r);
3399
- }
3400
- }
3401
- async updateCommentPosition(e, t, n) {
3402
- if (!this.destroyed && this.requireCommentWrite()) return xn(this.operationContext(), this.operationCallbacks(), e, t, n);
3403
- }
3404
- hydrateOfflineQueue() {
3405
- if (this.config.persistence === "memory") return;
3406
- let e = mr(this.config.projectId);
3407
- if (e.length > 0) {
3408
- let t = this.getInternalState().pendingMutations, n = new Set(t.map((e) => e.id)), r = [...t, ...e.filter((e) => !n.has(e.id))];
3409
- this.setState({ pendingMutations: r }), yr(this.ctx), this.getInternalState().isOnline && this.scheduleRetry();
3410
- }
3411
- this.offlinePersistUnsub?.(), this.offlinePersistUnsub = this.select((e) => e.pendingMutations, (e) => pr(this.config.projectId, e));
3412
- }
3413
- shouldQueueMutation(e) {
3414
- return !this.localDemo && br(this.getInternalState(), e);
3415
- }
3416
- queueMutation(e, t, n) {
3417
- return xr(this.ctx, () => this.scheduleRetry(), e, t, n);
3418
- }
3419
- scheduleRetry() {
3420
- Sr(this.ctx, this.retryTimerRef, () => this.processOfflineQueue());
3421
- }
3422
- async processOfflineQueue() {
3423
- this.canWriteComments() && await Cr(this.operationContext(), this.queueGuard, () => this.scheduleRetry(), (e) => this.executeMutation(e));
3424
- }
3425
- async executeMutation(e) {
3426
- let t = this.operationContext();
3427
- try {
3428
- await Dr(t, e);
3429
- } catch (e) {
3430
- throw e instanceof E && e.code === 402 && t.handleError(e), e;
3431
- }
3432
- }
3433
- getPendingMutationCount() {
3434
- return this.getInternalState().pendingMutations.length;
3435
- }
3436
- clearError() {
3437
- this.destroyed || this.getInternalState().error == null || this.setState({ error: null });
3438
- }
3439
- retryConnection() {
3440
- !this.destroyed && this.getInternalState().isAuthenticated && (this.wsManager ? this.wsManager.reconnect() : this.initializeWebSocket());
3441
- }
3442
- markThreadSeen(e) {
3443
- if (this.destroyed || typeof e != "string" || !e.trim() || e.length > Mr) return;
3444
- let t = new Set(this.getInternalState().seenThreadIds);
3445
- if (t.add(e), t.size > 1e3) {
3446
- let e = Array.from(t);
3447
- t.clear();
3448
- for (let n of e.slice(-1e3)) t.add(n);
3449
- }
3450
- this.setState({ seenThreadIds: t });
3451
- }
3452
- isThreadNew(e) {
3453
- return typeof e != "string" || !e.trim() ? !1 : !this.getInternalState().seenThreadIds.has(e);
3454
- }
3455
- setPanelView(e) {
3456
- !this.destroyed && Ar.has(e) && this.setState({ panelView: e });
3457
- }
3458
- toggleShortcutsOverlay() {
3459
- this.destroyed || this.setState({ isShortcutsOverlayVisible: !this.getInternalState().isShortcutsOverlayVisible });
3460
- }
3461
- addActivity(e) {
3462
- if (this.destroyed) return;
3463
- let t = this.getInternalState(), n = t.currentUser;
3464
- if (!n) return;
3465
- let r = {
3466
- id: `activity-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
3467
- user: {
3468
- id: n.id,
3469
- name: n.name,
3470
- avatarUrl: n.avatar
3471
- },
3472
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3473
- read: !1,
3474
- ...e
3475
- }, i = [r, ...t.activities].slice(0, 500);
3476
- this.setState({ activities: i }), this.emit("activity:new", r);
3477
- }
3478
- markAllActivitiesRead() {
3479
- if (this.destroyed) return;
3480
- let e = this.getInternalState();
3481
- this.setState({ activities: e.activities.map((e) => ({
3482
- ...e,
3483
- read: !0
3484
- })) });
3485
- }
3486
- getUnreadActivityCount() {
3487
- return this.getInternalState().activities.filter((e) => !e.read).length;
3488
- }
3489
- handleDeepLink() {
3490
- if (this.destroyed) return;
3491
- let e = window.location.hash, t = e.match(/^#comment-(.+)$/);
3492
- if (!t?.[1]) return;
3493
- let n = t[1];
3494
- this.emit("deeplink:navigate", { commentId: n });
3495
- let r = this.getInternalState().comments.find((e) => e.id === n);
3496
- if (r) this.selectComment(r), this.setState({
3497
- isSidebarVisible: !0,
3498
- panelView: "detail"
3499
- });
3500
- else if (this.getInternalState().isAuthenticated && n.length <= 256 && this.deepLinkRequest !== e) {
3501
- this.deepLinkRequest = e;
3502
- let t = this.sessionRevision;
3503
- this.apiClient.getComment(n, { repliesLimit: 50 }).then(async (r) => {
3504
- if (this.destroyed || t !== this.sessionRevision || window.location.hash !== e || r.id !== n) return;
3505
- let i = this.getInternalState().activeBranch;
3506
- i && i !== r.branch && await this.setBranch(r.branch ?? null), !(this.destroyed || t !== this.sessionRevision || window.location.hash !== e) && (this.setState({
3507
- comments: [...this.getInternalState().comments.filter((e) => e.id !== r.id), r],
3508
- selectedComment: r,
3509
- isSidebarVisible: !0,
3510
- panelView: "detail"
3511
- }), this.markThreadSeen(r.id));
3512
- }).catch((n) => {
3513
- !this.destroyed && t === this.sessionRevision && window.location.hash === e && this.handleError(n);
3514
- }).finally(() => {
3515
- this.deepLinkRequest === e && (this.deepLinkRequest = null);
3516
- });
3517
- }
3518
- }
3519
- async createHighlight(e, t) {
3520
- if (!this.destroyed && this.requireCommentWrite()) return Cn(this.operationContext(), this.operationCallbacks(), this.activeMutations, e, t);
3521
- }
3522
- async createDrawing(e, t, n) {
3523
- if (!this.destroyed && this.requireCommentWrite()) return wn(this.operationContext(), this.operationCallbacks(), this.activeMutations, e, t, n);
3524
- }
3525
- setActiveDrawing(e) {
3526
- this.destroyed || this.setState({ activeDrawing: e });
3527
- }
3528
- sendDrawingStroke(e) {
3529
- !this.destroyed && this.requireCommentWrite() && this.wsManager?.sendDrawingStroke(e);
3530
- }
3531
- async captureScreenshot(e) {
3532
- if (this.destroyed) return null;
3533
- let { captureScreenshot: t } = await import("./screenshot-B-ZfFItT.js");
3534
- return this.destroyed ? null : t(this.ctx, this.screenshotProvider, e);
3535
- }
3536
- async uploadScreenshot(e, t, n) {
3537
- if (this.destroyed || !this.requireCommentWrite()) return null;
3538
- let r = this.operationContext(), { uploadScreenshot: i } = await import("./screenshot-B-ZfFItT.js");
3539
- return this.destroyed || r.isCurrent?.() === !1 || !this.requireCommentWrite() ? null : i(r, e, t, n);
3540
- }
3541
- setActiveScreenshot(e) {
3542
- this.destroyed || this.setState({ activeScreenshot: e });
3543
- }
3544
- async uploadFiles(e, t) {
3545
- if (this.destroyed || !this.requireCommentWrite()) return [];
3546
- let n = this.operationContext(), { uploadFiles: r } = await import("./screenshot-B-ZfFItT.js");
3547
- return this.destroyed || n.isCurrent?.() === !1 || !this.requireCommentWrite() ? [] : r(n, e, t);
3548
- }
3549
- requireAgentExport() {
3550
- if (this.getInternalState().projectContext?.permissions.canExportAgentContext === !1) throw new E("forbidden", "Agent handoff is available to workspace members.", 403);
3551
- }
3552
- getAgentContext(e) {
3553
- return this.requireAgentExport(), k(this.getInternalState(), e);
3554
- }
3555
- async getAgentContextAsync(e) {
3556
- this.requireAgentExport();
3557
- let t = this.getInternalState(), n = k(t, e);
3558
- if (!this.localDemo && t.isAuthenticated) {
3559
- 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;
3560
- for (let e = 0; e < i.length; e += 4) {
3561
- let t = await Promise.all(i.slice(e, e + 4).map((e) => this.apiClient.getComment(e.id, { repliesLimit: 12 })));
3562
- if (this.destroyed || o !== this.sessionRevision || !this.getInternalState().isAuthenticated) throw new E("unauthorized", "Sign in again to copy feedback.", 401);
3563
- for (let e of t) a.set(e.id, e);
3564
- }
3565
- a.size && (n = k({
3566
- ...t,
3567
- comments: t.comments.map((e) => a.get(e.id) ?? e)
3568
- }, e));
3569
- }
3570
- let r = this.localDemo?.getRevision(), i = await He(n);
3571
- return this.localDemo?.checkExpiry(), this.localDemo && r !== this.localDemo.getRevision() ? k(this.getInternalState(), e) : i;
3572
- }
3573
- formatAgentContext(e) {
3574
- return A(this.getAgentContext(e));
3575
- }
3576
- async formatAgentContextAsync(e) {
3577
- return A(await this.getAgentContextAsync(e));
3578
- }
3579
- async copyAgentContext(e) {
3580
- if (this.destroyed) return "";
3581
- let t = await this.getAgentContextAsync(e), n = A(t);
3582
- return await Ye(n, t), this.emit("agent:context-copied", {
3583
- commentCount: t.comments.length,
3584
- sourceResolved: t.sourceResolved
3585
- }), n;
3586
- }
3587
- async grabElement(e, t) {
3588
- if (this.destroyed) return null;
3589
- this.requireAgentExport();
3590
- let { grabElement: n } = await import("./dev-grab-O8q25zar.js");
3591
- if (this.destroyed) return null;
3592
- this.requireAgentExport();
3593
- let r = await n(e, this.ctx, this.screenshotProvider, t);
3594
- return this.destroyed ? null : (r && this.emit("agent:element-grabbed", {
3595
- source: r.element.source?.filePath ?? null,
3596
- componentName: r.element.componentName ?? null
3597
- }), r);
3598
- }
3599
- async grabElements(e, t) {
3600
- if (this.destroyed) return null;
3601
- this.requireAgentExport();
3602
- let { grabElements: n } = await import("./dev-grab-O8q25zar.js");
3603
- if (this.destroyed) return null;
3604
- this.requireAgentExport();
3605
- let r = await n(e, this.ctx, this.screenshotProvider, t);
3606
- return this.destroyed ? null : (r && this.emit("agent:elements-grabbed", { count: r.results.length }), r);
3607
- }
3608
- async getProjectMembers() {
3609
- if (this.destroyed) return [];
3610
- try {
3611
- return await this.apiClient.getProjectMembers();
3612
- } catch (e) {
3613
- return this.handleError(e), [];
3614
- }
3615
- }
3616
- handleToggleRequest() {
3617
- this.destroyed || j() || Ln(this.getInternalState(), this.kbdCallbacks);
3618
- }
3619
- handleKeyboardShortcuts(e) {
3620
- if (!(this.destroyed || j())) {
3621
- if (e.key === "Escape") {
3622
- if (this.escapeBlockers.size > 0) return;
3623
- let t = e.composedPath()[0];
3624
- if (t instanceof Element && t.getRootNode() === document && t.closest("[data-commentkit-ui], [data-commentkit-ignore]")) return;
3625
- }
3626
- Rn(e, this.getInternalState(), this.kbdCallbacks);
3627
- }
3628
- }
3629
- matchesHoldKey(e) {
3630
- let t = this.config.ui?.activation?.key;
3631
- 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;
3632
- }
3633
- blockEscape() {
3634
- let e = Symbol();
3635
- return this.escapeBlockers.add(e), () => {
3636
- this.escapeBlockers.delete(e);
3637
- };
3638
- }
3639
- initializeWebSocket() {
3640
- this.destroyed || this.localDemo || Or().then((e) => {
3641
- this.destroyed || this.getInternalState().isAuthenticated && (this.syncRealtimeRefs(), e.initializeWebSocket(this.ctx, this.realtimeRefs, {
3642
- capture: () => this.commentsRequestContext(this.commentsFetchRevision),
3643
- subscribe: (e) => this.on("state:changed", e)
3644
- }), this.syncFromRealtimeRefs());
3645
- }).catch((e) => {
3646
- this.ctx.handleError(e);
3647
- });
3648
- }
3649
- getOnlineUsers() {
3650
- /* v8 ignore next -- onlineUsers is always initialized as array */
3651
- return structuredClone(this.getInternalState().onlineUsers || []);
3652
- }
3653
- syncRealtimeRefs() {
3654
- this.realtimeRefs.wsManager = this.wsManager, this.realtimeRefs.wsUnsubscribers = this.wsUnsubscribers, this.realtimeRefs.mouseMoveHandler = this.mouseMoveHandler;
3655
- }
3656
- syncFromRealtimeRefs() {
3657
- this.wsManager = this.realtimeRefs.wsManager, this.wsUnsubscribers = this.realtimeRefs.wsUnsubscribers, this.mouseMoveHandler = this.realtimeRefs.mouseMoveHandler;
3658
- }
3659
- removeMouseMoveListener() {
3660
- $ && (this.syncRealtimeRefs(), $.removeMouseMoveListener(this.realtimeRefs), this.syncFromRealtimeRefs());
3661
- }
3662
- disconnectRealtime(e) {
3663
- for (let e of this.wsUnsubscribers) try {
3664
- e();
3665
- } catch (e) {
3666
- console.error("[CommentKit] Error during realtime cleanup:", e);
3667
- }
3668
- if (this.wsUnsubscribers = [], this.wsManager) {
3669
- try {
3670
- e && this.wsManager.sendCursorLeave();
3671
- } catch {}
3672
- this.wsManager.destroy(), this.wsManager = null;
3673
- }
3674
- this.removeMouseMoveListener(), this.syncRealtimeRefs();
3675
- }
3676
- destroy() {
3677
- 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());
3678
- }
3679
- };
3680
- 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 };