@commentkit/comment-kit 0.0.0-stage → 0.6.1

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