@commentkit/comment-kit 0.0.0-stage → 0.6.2

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