@commentkit/comment-kit 0.0.0-stage → 0.6.2

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