@grainql/analytics-web 2.7.1 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +36 -3
  2. package/dist/cjs/consent.d.ts +38 -7
  3. package/dist/cjs/consent.d.ts.map +1 -1
  4. package/dist/cjs/consent.js +82 -23
  5. package/dist/cjs/consent.js.map +1 -1
  6. package/dist/cjs/debug-agent.d.ts +171 -0
  7. package/dist/cjs/debug-agent.d.ts.map +1 -0
  8. package/dist/cjs/debug-agent.js +1219 -0
  9. package/dist/cjs/debug-agent.js.map +1 -0
  10. package/dist/cjs/id-manager.d.ts +66 -0
  11. package/dist/cjs/id-manager.d.ts.map +1 -0
  12. package/dist/cjs/id-manager.js +212 -0
  13. package/dist/cjs/id-manager.js.map +1 -0
  14. package/dist/cjs/index.d.ts +26 -8
  15. package/dist/cjs/index.d.ts.map +1 -1
  16. package/dist/cjs/index.js.map +1 -1
  17. package/dist/cjs/interaction-tracking.d.ts +6 -0
  18. package/dist/cjs/interaction-tracking.d.ts.map +1 -1
  19. package/dist/cjs/interaction-tracking.js +55 -5
  20. package/dist/cjs/interaction-tracking.js.map +1 -1
  21. package/dist/cjs/page-tracking.d.ts +6 -0
  22. package/dist/cjs/page-tracking.d.ts.map +1 -1
  23. package/dist/cjs/page-tracking.js +23 -2
  24. package/dist/cjs/page-tracking.js.map +1 -1
  25. package/dist/cjs/react/hooks/useConsent.d.ts +18 -2
  26. package/dist/cjs/react/hooks/useConsent.d.ts.map +1 -1
  27. package/dist/cjs/react/hooks/useConsent.js +52 -1
  28. package/dist/cjs/react/hooks/useConsent.js.map +1 -1
  29. package/dist/consent.d.ts +38 -7
  30. package/dist/consent.d.ts.map +1 -1
  31. package/dist/consent.js +82 -23
  32. package/dist/debug-agent.d.ts +171 -0
  33. package/dist/debug-agent.d.ts.map +1 -0
  34. package/dist/debug-agent.js +1219 -0
  35. package/dist/esm/consent.d.ts +38 -7
  36. package/dist/esm/consent.d.ts.map +1 -1
  37. package/dist/esm/consent.js +82 -23
  38. package/dist/esm/consent.js.map +1 -1
  39. package/dist/esm/debug-agent.d.ts +171 -0
  40. package/dist/esm/debug-agent.d.ts.map +1 -0
  41. package/dist/esm/debug-agent.js +1215 -0
  42. package/dist/esm/debug-agent.js.map +1 -0
  43. package/dist/esm/id-manager.d.ts +66 -0
  44. package/dist/esm/id-manager.d.ts.map +1 -0
  45. package/dist/esm/id-manager.js +208 -0
  46. package/dist/esm/id-manager.js.map +1 -0
  47. package/dist/esm/index.d.ts +26 -8
  48. package/dist/esm/index.d.ts.map +1 -1
  49. package/dist/esm/index.js.map +1 -1
  50. package/dist/esm/interaction-tracking.d.ts +6 -0
  51. package/dist/esm/interaction-tracking.d.ts.map +1 -1
  52. package/dist/esm/interaction-tracking.js +55 -5
  53. package/dist/esm/interaction-tracking.js.map +1 -1
  54. package/dist/esm/page-tracking.d.ts +6 -0
  55. package/dist/esm/page-tracking.d.ts.map +1 -1
  56. package/dist/esm/page-tracking.js +23 -2
  57. package/dist/esm/page-tracking.js.map +1 -1
  58. package/dist/esm/react/hooks/useConsent.d.ts +18 -2
  59. package/dist/esm/react/hooks/useConsent.d.ts.map +1 -1
  60. package/dist/esm/react/hooks/useConsent.js +49 -1
  61. package/dist/esm/react/hooks/useConsent.js.map +1 -1
  62. package/dist/id-manager.d.ts +66 -0
  63. package/dist/id-manager.d.ts.map +1 -0
  64. package/dist/id-manager.js +212 -0
  65. package/dist/index.d.ts +26 -8
  66. package/dist/index.d.ts.map +1 -1
  67. package/dist/index.global.dev.js +1635 -86
  68. package/dist/index.global.dev.js.map +4 -4
  69. package/dist/index.global.js +506 -2
  70. package/dist/index.global.js.map +4 -4
  71. package/dist/index.js +171 -44
  72. package/dist/index.mjs +172 -45
  73. package/dist/interaction-tracking.d.ts +6 -0
  74. package/dist/interaction-tracking.d.ts.map +1 -1
  75. package/dist/interaction-tracking.js +55 -5
  76. package/dist/page-tracking.d.ts +6 -0
  77. package/dist/page-tracking.d.ts.map +1 -1
  78. package/dist/page-tracking.js +23 -2
  79. package/dist/react/hooks/useConsent.d.ts +18 -2
  80. package/dist/react/hooks/useConsent.d.ts.map +1 -1
  81. package/dist/react/hooks/useConsent.js +52 -1
  82. package/dist/react/hooks/useConsent.mjs +49 -1
  83. package/package.json +1 -1
@@ -0,0 +1,1215 @@
1
+ /**
2
+ * Debug Agent for Visual Event Tracking
3
+ * Provides a toolbar and element inspection mode for creating event trackers
4
+ */
5
+ export class DebugAgent {
6
+ constructor(tracker, sessionId, tenantId, apiUrl, config = {}) {
7
+ this.isDestroyed = false;
8
+ // UI state
9
+ this.isInspectMode = false;
10
+ this.showTrackers = false;
11
+ this.selectedElement = null;
12
+ this.toolbarElement = null;
13
+ this.panelElement = null;
14
+ this.highlightElement = null;
15
+ this.existingTrackers = [];
16
+ this.trackerHighlights = [];
17
+ // Dragging state
18
+ this.isDragging = false;
19
+ this.dragStartX = 0;
20
+ this.dragStartY = 0;
21
+ this.toolbarStartX = 0;
22
+ this.toolbarStartY = 0;
23
+ // Event listeners
24
+ this.mouseMoveListener = null;
25
+ this.clickListener = null;
26
+ this.dragMoveListener = null;
27
+ this.dragEndListener = null;
28
+ /**
29
+ * Handle ESC key to exit inspect mode
30
+ */
31
+ this.handleEscapeKey = (e) => {
32
+ if (e.key === 'Escape' && this.isInspectMode) {
33
+ this.disableInspectMode();
34
+ }
35
+ };
36
+ this.tracker = tracker;
37
+ this.sessionId = sessionId;
38
+ this.tenantId = tenantId;
39
+ this.apiUrl = apiUrl;
40
+ this.config = {
41
+ debug: config.debug ?? false,
42
+ };
43
+ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
44
+ this.initialize();
45
+ }
46
+ }
47
+ /**
48
+ * Initialize the debug agent
49
+ */
50
+ async initialize() {
51
+ this.log('Initializing debug agent');
52
+ await this.loadExistingTrackers();
53
+ this.showToolbar();
54
+ this.createHighlightElement();
55
+ // Show trackers by default
56
+ this.showTrackers = true;
57
+ this.showTrackerHighlights();
58
+ this.showTrackersList();
59
+ }
60
+ /**
61
+ * Load existing trackers from API
62
+ */
63
+ async loadExistingTrackers() {
64
+ try {
65
+ const url = `${this.apiUrl}/v1/tenant/${encodeURIComponent(this.tenantId)}/trackers`;
66
+ const response = await fetch(url);
67
+ if (response.ok) {
68
+ this.existingTrackers = await response.json();
69
+ this.log('Loaded trackers:', this.existingTrackers);
70
+ }
71
+ }
72
+ catch (error) {
73
+ this.log('Failed to load trackers:', error);
74
+ this.existingTrackers = [];
75
+ }
76
+ }
77
+ /**
78
+ * Show the debug toolbar
79
+ */
80
+ showToolbar() {
81
+ if (this.toolbarElement)
82
+ return;
83
+ const toolbar = document.createElement('div');
84
+ toolbar.id = 'grain-debug-toolbar';
85
+ toolbar.innerHTML = `
86
+ <style>
87
+ #grain-debug-toolbar {
88
+ position: fixed;
89
+ bottom: 20px;
90
+ right: 20px;
91
+ background: repeating-linear-gradient(
92
+ 45deg,
93
+ #fbbf24,
94
+ #fbbf24 10px,
95
+ #1e293b 10px,
96
+ #1e293b 20px
97
+ );
98
+ border: 2px solid #1e293b;
99
+ border-radius: 12px;
100
+ padding: 6px;
101
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2), 0 2px 8px rgba(0, 0, 0, 0.1);
102
+ z-index: 999999;
103
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
104
+ font-size: 13px;
105
+ }
106
+
107
+ .grain-toolbar-inner {
108
+ display: flex;
109
+ align-items: center;
110
+ gap: 12px;
111
+ background: white;
112
+ border-radius: 6px;
113
+ padding: 8px 12px;
114
+ }
115
+
116
+ #grain-debug-toolbar.dragging {
117
+ cursor: move;
118
+ user-select: none;
119
+ }
120
+
121
+ .grain-toolbar-header {
122
+ display: flex;
123
+ align-items: center;
124
+ cursor: move;
125
+ user-select: none;
126
+ padding: 6px 10px;
127
+ background: #1e293b;
128
+ border-radius: 4px;
129
+ margin-right: 4px;
130
+ }
131
+
132
+ .grain-toolbar-title {
133
+ font-size: 11px;
134
+ font-weight: 700;
135
+ letter-spacing: 1.2px;
136
+ text-transform: uppercase;
137
+ color: #fbbf24;
138
+ }
139
+
140
+ .grain-toolbar-body {
141
+ display: flex;
142
+ align-items: center;
143
+ gap: 10px;
144
+ flex: 1;
145
+ }
146
+
147
+ .grain-toolbar-stats {
148
+ display: flex;
149
+ gap: 12px;
150
+ padding: 6px 10px;
151
+ background: #f8fafc;
152
+ border-radius: 4px;
153
+ margin-right: 4px;
154
+ }
155
+
156
+ .grain-stat {
157
+ display: flex;
158
+ align-items: baseline;
159
+ gap: 6px;
160
+ }
161
+
162
+ .grain-stat-value {
163
+ font-size: 18px;
164
+ font-weight: 700;
165
+ color: #1e293b;
166
+ }
167
+
168
+ .grain-stat-label {
169
+ font-size: 11px;
170
+ color: #64748b;
171
+ font-weight: 500;
172
+ }
173
+
174
+ .grain-toolbar-actions {
175
+ display: flex;
176
+ gap: 8px;
177
+ align-items: center;
178
+ }
179
+
180
+ #grain-debug-toolbar button {
181
+ background: white;
182
+ border: 1.5px solid #e2e8f0;
183
+ color: #475569;
184
+ padding: 8px 14px;
185
+ border-radius: 8px;
186
+ cursor: pointer;
187
+ font-size: 12px;
188
+ font-weight: 600;
189
+ transition: all 0.2s;
190
+ display: flex;
191
+ align-items: center;
192
+ justify-content: center;
193
+ gap: 6px;
194
+ white-space: nowrap;
195
+ }
196
+
197
+ #grain-debug-toolbar button:hover {
198
+ background: #f8fafc;
199
+ border-color: #cbd5e1;
200
+ transform: translateY(-1px);
201
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
202
+ }
203
+
204
+ #grain-debug-toolbar button.active {
205
+ background: #fbbf24;
206
+ color: #1e293b;
207
+ border-color: #fbbf24;
208
+ box-shadow: 0 2px 8px rgba(251, 191, 36, 0.3);
209
+ }
210
+
211
+ #grain-debug-toolbar button.danger {
212
+ background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
213
+ border-color: #ef4444;
214
+ color: white;
215
+ }
216
+
217
+ #grain-debug-toolbar button.danger:hover {
218
+ transform: translateY(-1px);
219
+ box-shadow: 0 2px 8px rgba(239, 68, 68, 0.25);
220
+ }
221
+
222
+ .grain-debug-highlight {
223
+ position: absolute;
224
+ pointer-events: none;
225
+ border: 2px solid #10b981;
226
+ background: rgba(16, 185, 129, 0.1);
227
+ z-index: 999998;
228
+ transition: all 0.1s;
229
+ }
230
+
231
+ .grain-tracker-highlight {
232
+ position: absolute;
233
+ pointer-events: none;
234
+ border: 2px solid #6366f1;
235
+ background: rgba(99, 102, 241, 0.08);
236
+ z-index: 999997;
237
+ transition: opacity 0.2s;
238
+ }
239
+
240
+ .grain-tracker-label {
241
+ position: absolute;
242
+ top: -28px;
243
+ left: 0;
244
+ background: #6366f1;
245
+ color: white;
246
+ padding: 4px 10px;
247
+ border-radius: 6px;
248
+ font-size: 11px;
249
+ font-weight: 600;
250
+ white-space: nowrap;
251
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
252
+ pointer-events: none;
253
+ }
254
+
255
+ .grain-tracker-label::after {
256
+ content: '';
257
+ position: absolute;
258
+ bottom: -4px;
259
+ left: 10px;
260
+ width: 0;
261
+ height: 0;
262
+ border-left: 4px solid transparent;
263
+ border-right: 4px solid transparent;
264
+ border-top: 4px solid #6366f1;
265
+ }
266
+
267
+ .grain-trackers-list {
268
+ position: fixed;
269
+ bottom: 80px;
270
+ right: 20px;
271
+ background: white;
272
+ border: 1.5px solid #e2e8f0;
273
+ border-radius: 10px;
274
+ padding: 12px;
275
+ max-height: 400px;
276
+ width: 320px;
277
+ overflow-y: auto;
278
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1), 0 2px 8px rgba(0, 0, 0, 0.06);
279
+ z-index: 999998;
280
+ }
281
+
282
+ .grain-tracker-item {
283
+ padding: 10px;
284
+ background: #f8fafc;
285
+ border-radius: 8px;
286
+ margin-bottom: 8px;
287
+ cursor: pointer;
288
+ transition: all 0.2s;
289
+ }
290
+
291
+ .grain-tracker-item:hover {
292
+ background: #f1f5f9;
293
+ transform: translateX(4px);
294
+ }
295
+
296
+ .grain-tracker-item:last-child {
297
+ margin-bottom: 0;
298
+ }
299
+
300
+ .grain-tracker-name {
301
+ font-weight: 600;
302
+ color: #1e293b;
303
+ font-size: 13px;
304
+ margin-bottom: 4px;
305
+ }
306
+
307
+ .grain-tracker-details {
308
+ font-size: 11px;
309
+ color: #64748b;
310
+ display: flex;
311
+ gap: 8px;
312
+ align-items: center;
313
+ }
314
+
315
+ .grain-tracker-type {
316
+ background: #dbeafe;
317
+ color: #1e40af;
318
+ padding: 2px 6px;
319
+ border-radius: 4px;
320
+ font-weight: 600;
321
+ text-transform: uppercase;
322
+ font-size: 9px;
323
+ letter-spacing: 0.5px;
324
+ }
325
+ </style>
326
+ <div class="grain-toolbar-inner">
327
+ <div class="grain-toolbar-header" id="grain-toolbar-handle">
328
+ <div class="grain-toolbar-title">Grain Debug</div>
329
+ </div>
330
+ <div class="grain-toolbar-body">
331
+ <div class="grain-toolbar-stats">
332
+ <div class="grain-stat">
333
+ <div class="grain-stat-value">${this.existingTrackers.length}</div>
334
+ <div class="grain-stat-label">trackers</div>
335
+ </div>
336
+ <div class="grain-stat">
337
+ <div class="grain-stat-value">${this.existingTrackers.filter(t => t.isEnabled).length}</div>
338
+ <div class="grain-stat-label">active</div>
339
+ </div>
340
+ </div>
341
+ <div class="grain-toolbar-actions">
342
+ <button id="grain-debug-inspect" type="button">
343
+ + New
344
+ </button>
345
+ <button id="grain-debug-trackers" class="active" type="button">
346
+ Hide
347
+ </button>
348
+ <button id="grain-debug-end" class="danger" type="button">
349
+ End Session
350
+ </button>
351
+ </div>
352
+ </div>
353
+ </div>
354
+ <div id="grain-trackers-list-container"></div>
355
+ `;
356
+ document.body.appendChild(toolbar);
357
+ this.toolbarElement = toolbar;
358
+ // Setup dragging
359
+ const handle = toolbar.querySelector('#grain-toolbar-handle');
360
+ if (handle) {
361
+ handle.addEventListener('mousedown', (e) => this.startDrag(e));
362
+ }
363
+ // Add event listeners
364
+ const inspectBtn = toolbar.querySelector('#grain-debug-inspect');
365
+ const trackersBtn = toolbar.querySelector('#grain-debug-trackers');
366
+ const endBtn = toolbar.querySelector('#grain-debug-end');
367
+ if (inspectBtn) {
368
+ inspectBtn.addEventListener('click', () => this.toggleInspectMode());
369
+ }
370
+ if (trackersBtn) {
371
+ trackersBtn.addEventListener('click', () => this.toggleTrackerView());
372
+ }
373
+ if (endBtn) {
374
+ endBtn.addEventListener('click', () => this.endDebug());
375
+ }
376
+ this.log('Toolbar shown');
377
+ }
378
+ /**
379
+ * Create highlight element for hovering
380
+ */
381
+ createHighlightElement() {
382
+ if (this.highlightElement)
383
+ return;
384
+ const highlight = document.createElement('div');
385
+ highlight.className = 'grain-debug-highlight';
386
+ highlight.style.display = 'none';
387
+ document.body.appendChild(highlight);
388
+ this.highlightElement = highlight;
389
+ }
390
+ /**
391
+ * Start dragging the toolbar
392
+ */
393
+ startDrag(e) {
394
+ if (!this.toolbarElement)
395
+ return;
396
+ this.isDragging = true;
397
+ this.dragStartX = e.clientX;
398
+ this.dragStartY = e.clientY;
399
+ const rect = this.toolbarElement.getBoundingClientRect();
400
+ this.toolbarStartX = rect.left;
401
+ this.toolbarStartY = rect.top;
402
+ this.toolbarElement.classList.add('dragging');
403
+ this.dragMoveListener = (e) => this.onDrag(e);
404
+ this.dragEndListener = () => this.endDrag();
405
+ document.addEventListener('mousemove', this.dragMoveListener);
406
+ document.addEventListener('mouseup', this.dragEndListener);
407
+ }
408
+ /**
409
+ * Handle drag movement
410
+ */
411
+ onDrag(e) {
412
+ if (!this.isDragging || !this.toolbarElement)
413
+ return;
414
+ const deltaX = e.clientX - this.dragStartX;
415
+ const deltaY = e.clientY - this.dragStartY;
416
+ const newX = this.toolbarStartX + deltaX;
417
+ const newY = this.toolbarStartY + deltaY;
418
+ // Keep toolbar within viewport
419
+ const maxX = window.innerWidth - this.toolbarElement.offsetWidth;
420
+ const maxY = window.innerHeight - this.toolbarElement.offsetHeight;
421
+ const clampedX = Math.max(0, Math.min(newX, maxX));
422
+ const clampedY = Math.max(0, Math.min(newY, maxY));
423
+ this.toolbarElement.style.left = `${clampedX}px`;
424
+ this.toolbarElement.style.top = `${clampedY}px`;
425
+ this.toolbarElement.style.right = 'auto';
426
+ this.toolbarElement.style.bottom = 'auto';
427
+ }
428
+ /**
429
+ * End dragging
430
+ */
431
+ endDrag() {
432
+ if (!this.isDragging)
433
+ return;
434
+ this.isDragging = false;
435
+ if (this.toolbarElement) {
436
+ this.toolbarElement.classList.remove('dragging');
437
+ }
438
+ if (this.dragMoveListener) {
439
+ document.removeEventListener('mousemove', this.dragMoveListener);
440
+ this.dragMoveListener = null;
441
+ }
442
+ if (this.dragEndListener) {
443
+ document.removeEventListener('mouseup', this.dragEndListener);
444
+ this.dragEndListener = null;
445
+ }
446
+ }
447
+ /**
448
+ * Toggle tracker view
449
+ */
450
+ toggleTrackerView() {
451
+ this.showTrackers = !this.showTrackers;
452
+ const trackersBtn = document.querySelector('#grain-debug-trackers');
453
+ if (trackersBtn) {
454
+ trackersBtn.textContent = this.showTrackers ? 'Hide' : 'View';
455
+ trackersBtn.classList.toggle('active', this.showTrackers);
456
+ }
457
+ if (this.showTrackers) {
458
+ this.showTrackerHighlights();
459
+ this.showTrackersList();
460
+ }
461
+ else {
462
+ this.hideTrackerHighlights();
463
+ this.hideTrackersList();
464
+ }
465
+ }
466
+ /**
467
+ * Show tracker highlights on page
468
+ */
469
+ showTrackerHighlights() {
470
+ this.hideTrackerHighlights();
471
+ for (const tracker of this.existingTrackers) {
472
+ if (!tracker.isEnabled)
473
+ continue;
474
+ try {
475
+ const element = this.findElementBySelector(tracker.selector);
476
+ if (!element)
477
+ continue;
478
+ const rect = element.getBoundingClientRect();
479
+ const highlight = document.createElement('div');
480
+ highlight.className = 'grain-tracker-highlight';
481
+ const label = document.createElement('div');
482
+ label.className = 'grain-tracker-label';
483
+ label.textContent = tracker.name;
484
+ highlight.style.top = `${rect.top + window.scrollY}px`;
485
+ highlight.style.left = `${rect.left + window.scrollX}px`;
486
+ highlight.style.width = `${rect.width}px`;
487
+ highlight.style.height = `${rect.height}px`;
488
+ highlight.appendChild(label);
489
+ document.body.appendChild(highlight);
490
+ this.trackerHighlights.push(highlight);
491
+ }
492
+ catch (error) {
493
+ this.log('Failed to highlight tracker:', tracker.name, error);
494
+ }
495
+ }
496
+ }
497
+ /**
498
+ * Hide tracker highlights
499
+ */
500
+ hideTrackerHighlights() {
501
+ for (const highlight of this.trackerHighlights) {
502
+ highlight.remove();
503
+ }
504
+ this.trackerHighlights = [];
505
+ }
506
+ /**
507
+ * Show trackers list
508
+ */
509
+ showTrackersList() {
510
+ // Check if list already exists
511
+ let list = document.querySelector('.grain-trackers-list');
512
+ if (this.existingTrackers.length === 0) {
513
+ if (list)
514
+ list.remove();
515
+ return;
516
+ }
517
+ if (!list) {
518
+ list = document.createElement('div');
519
+ list.className = 'grain-trackers-list';
520
+ document.body.appendChild(list);
521
+ }
522
+ list.innerHTML = `
523
+ ${this.existingTrackers.map(tracker => `
524
+ <div class="grain-tracker-item" data-tracker-id="${tracker.trackerId}">
525
+ <div class="grain-tracker-name">${tracker.name}</div>
526
+ <div class="grain-tracker-details">
527
+ <span class="grain-tracker-type">${tracker.type}</span>
528
+ <span>${tracker.urlScope}</span>
529
+ ${!tracker.isEnabled ? '<span style="color: #ef4444;">• Disabled</span>' : ''}
530
+ </div>
531
+ </div>
532
+ `).join('')}
533
+ `;
534
+ // Add click handlers to scroll to elements
535
+ list.querySelectorAll('.grain-tracker-item').forEach(item => {
536
+ item.addEventListener('click', () => {
537
+ const trackerId = item.getAttribute('data-tracker-id');
538
+ const tracker = this.existingTrackers.find(t => t.trackerId === trackerId);
539
+ if (tracker) {
540
+ this.scrollToTracker(tracker);
541
+ }
542
+ });
543
+ });
544
+ }
545
+ /**
546
+ * Hide trackers list
547
+ */
548
+ hideTrackersList() {
549
+ const list = document.querySelector('.grain-trackers-list');
550
+ if (list) {
551
+ list.remove();
552
+ }
553
+ }
554
+ /**
555
+ * Scroll to and highlight a tracker element
556
+ */
557
+ scrollToTracker(tracker) {
558
+ try {
559
+ const element = this.findElementBySelector(tracker.selector);
560
+ if (element) {
561
+ element.scrollIntoView({ behavior: 'smooth', block: 'center' });
562
+ // Flash the highlight
563
+ const highlight = this.trackerHighlights.find(h => {
564
+ const rect = element.getBoundingClientRect();
565
+ const hRect = h.getBoundingClientRect();
566
+ return Math.abs(hRect.top - rect.top) < 5;
567
+ });
568
+ if (highlight) {
569
+ highlight.style.opacity = '0';
570
+ setTimeout(() => {
571
+ highlight.style.opacity = '1';
572
+ }, 100);
573
+ setTimeout(() => {
574
+ highlight.style.opacity = '0';
575
+ }, 300);
576
+ setTimeout(() => {
577
+ highlight.style.opacity = '1';
578
+ }, 500);
579
+ }
580
+ }
581
+ }
582
+ catch (error) {
583
+ this.log('Failed to scroll to tracker:', error);
584
+ }
585
+ }
586
+ /**
587
+ * Find element by XPath selector
588
+ */
589
+ findElementBySelector(selector) {
590
+ try {
591
+ const result = document.evaluate(selector, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
592
+ return result.singleNodeValue;
593
+ }
594
+ catch (error) {
595
+ this.log('Failed to find element:', error);
596
+ return null;
597
+ }
598
+ }
599
+ /**
600
+ * Toggle inspect mode
601
+ */
602
+ toggleInspectMode() {
603
+ if (this.isInspectMode) {
604
+ this.disableInspectMode();
605
+ }
606
+ else {
607
+ this.enableInspectMode();
608
+ }
609
+ }
610
+ /**
611
+ * Enable element inspection mode
612
+ */
613
+ enableInspectMode() {
614
+ if (this.isInspectMode)
615
+ return;
616
+ this.log('Enabling inspect mode');
617
+ this.isInspectMode = true;
618
+ // Update button state
619
+ const inspectBtn = document.querySelector('#grain-debug-inspect');
620
+ if (inspectBtn) {
621
+ inspectBtn.classList.add('active');
622
+ inspectBtn.textContent = 'Click Element';
623
+ }
624
+ // Add event listeners
625
+ this.mouseMoveListener = (e) => this.handleMouseMove(e);
626
+ this.clickListener = (e) => this.handleElementClick(e);
627
+ document.addEventListener('mousemove', this.mouseMoveListener, true);
628
+ document.addEventListener('click', this.clickListener, true);
629
+ // Add ESC key listener to exit inspect mode
630
+ document.addEventListener('keydown', this.handleEscapeKey);
631
+ }
632
+ /**
633
+ * Disable element inspection mode
634
+ */
635
+ disableInspectMode() {
636
+ if (!this.isInspectMode)
637
+ return;
638
+ this.log('Disabling inspect mode');
639
+ this.isInspectMode = false;
640
+ // Update button state
641
+ const inspectBtn = document.querySelector('#grain-debug-inspect');
642
+ if (inspectBtn) {
643
+ inspectBtn.classList.remove('active');
644
+ inspectBtn.textContent = '+ New';
645
+ }
646
+ // Remove event listeners
647
+ if (this.mouseMoveListener) {
648
+ document.removeEventListener('mousemove', this.mouseMoveListener, true);
649
+ this.mouseMoveListener = null;
650
+ }
651
+ if (this.clickListener) {
652
+ document.removeEventListener('click', this.clickListener, true);
653
+ this.clickListener = null;
654
+ }
655
+ document.removeEventListener('keydown', this.handleEscapeKey);
656
+ // Hide highlight
657
+ if (this.highlightElement) {
658
+ this.highlightElement.style.display = 'none';
659
+ }
660
+ }
661
+ /**
662
+ * Handle mouse move to highlight hovered element
663
+ */
664
+ handleMouseMove(e) {
665
+ if (!this.isInspectMode || !this.highlightElement)
666
+ return;
667
+ // Ignore if hovering over toolbar, panel, or tracker list
668
+ const target = e.target;
669
+ if (target.closest('#grain-debug-toolbar') ||
670
+ target.closest('#grain-debug-panel') ||
671
+ target.closest('.grain-trackers-list')) {
672
+ this.highlightElement.style.display = 'none';
673
+ return;
674
+ }
675
+ // Get element rect
676
+ const element = e.target;
677
+ const rect = element.getBoundingClientRect();
678
+ // Position highlight
679
+ this.highlightElement.style.display = 'block';
680
+ this.highlightElement.style.top = `${rect.top + window.scrollY}px`;
681
+ this.highlightElement.style.left = `${rect.left + window.scrollX}px`;
682
+ this.highlightElement.style.width = `${rect.width}px`;
683
+ this.highlightElement.style.height = `${rect.height}px`;
684
+ }
685
+ /**
686
+ * Handle element click to show creation panel
687
+ */
688
+ handleElementClick(e) {
689
+ if (!this.isInspectMode)
690
+ return;
691
+ const target = e.target;
692
+ // If clicking toolbar or tracker list, exit inspect mode and allow normal click
693
+ if (target.closest('#grain-debug-toolbar') || target.closest('.grain-trackers-list')) {
694
+ this.disableInspectMode();
695
+ return;
696
+ }
697
+ // If clicking panel, prevent default but don't do anything
698
+ if (target.closest('#grain-debug-panel')) {
699
+ e.preventDefault();
700
+ e.stopPropagation();
701
+ return;
702
+ }
703
+ // Otherwise, select the element
704
+ e.preventDefault();
705
+ e.stopPropagation();
706
+ this.selectedElement = target;
707
+ this.disableInspectMode();
708
+ this.showCreationPanel(target);
709
+ }
710
+ /**
711
+ * Show tracker creation panel
712
+ */
713
+ showCreationPanel(element) {
714
+ // Remove existing panel if any
715
+ if (this.panelElement) {
716
+ this.panelElement.remove();
717
+ }
718
+ const panel = document.createElement('div');
719
+ panel.id = 'grain-debug-panel';
720
+ // Extract element info
721
+ const tagName = element.tagName.toLowerCase();
722
+ const elementId = element.id;
723
+ const elementText = element.textContent?.trim().substring(0, 50) || '';
724
+ const xpath = this.getXPathForElement(element);
725
+ panel.innerHTML = `
726
+ <style>
727
+ #grain-debug-panel {
728
+ position: fixed;
729
+ top: 50%;
730
+ left: 50%;
731
+ transform: translate(-50%, -50%);
732
+ background: repeating-linear-gradient(
733
+ 45deg,
734
+ #fbbf24,
735
+ #fbbf24 10px,
736
+ #1e293b 10px,
737
+ #1e293b 20px
738
+ );
739
+ border: 2px solid #1e293b;
740
+ border-radius: 16px;
741
+ padding: 6px;
742
+ width: 420px;
743
+ max-width: 90vw;
744
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.25), 0 8px 24px rgba(0, 0, 0, 0.15);
745
+ z-index: 1000000;
746
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
747
+ }
748
+
749
+ .grain-panel-inner {
750
+ background: white;
751
+ border-radius: 10px;
752
+ overflow: hidden;
753
+ }
754
+
755
+ .grain-panel-header {
756
+ background: #1e293b;
757
+ padding: 14px 18px;
758
+ color: white;
759
+ }
760
+
761
+ .grain-panel-header h3 {
762
+ margin: 0 0 4px 0;
763
+ font-size: 16px;
764
+ font-weight: 700;
765
+ letter-spacing: 0.5px;
766
+ color: #fbbf24;
767
+ text-transform: uppercase;
768
+ }
769
+
770
+ .grain-panel-header p {
771
+ margin: 0;
772
+ font-size: 12px;
773
+ opacity: 0.85;
774
+ color: white;
775
+ }
776
+
777
+ .grain-panel-body {
778
+ padding: 18px;
779
+ }
780
+
781
+ #grain-debug-panel .element-preview {
782
+ background: #f8fafc;
783
+ border: 1.5px solid #e2e8f0;
784
+ border-radius: 8px;
785
+ padding: 10px 12px;
786
+ margin-bottom: 16px;
787
+ font-size: 11px;
788
+ color: #475569;
789
+ }
790
+
791
+ #grain-debug-panel .element-preview div {
792
+ margin-bottom: 4px;
793
+ }
794
+
795
+ #grain-debug-panel .element-preview div:last-child {
796
+ margin-bottom: 0;
797
+ }
798
+
799
+ #grain-debug-panel .element-preview strong {
800
+ color: #1e293b;
801
+ font-weight: 600;
802
+ }
803
+
804
+ #grain-debug-panel label {
805
+ display: block;
806
+ color: #1e293b;
807
+ font-size: 12px;
808
+ font-weight: 600;
809
+ margin-bottom: 6px;
810
+ }
811
+
812
+ #grain-debug-panel input,
813
+ #grain-debug-panel select {
814
+ width: 100%;
815
+ background: white;
816
+ border: 1.5px solid #e2e8f0;
817
+ border-radius: 8px;
818
+ padding: 9px 12px;
819
+ color: #1e293b;
820
+ font-size: 13px;
821
+ margin-bottom: 14px;
822
+ box-sizing: border-box;
823
+ transition: all 0.2s;
824
+ }
825
+
826
+ #grain-debug-panel input:focus,
827
+ #grain-debug-panel select:focus {
828
+ outline: none;
829
+ border-color: #fbbf24;
830
+ box-shadow: 0 0 0 3px rgba(251, 191, 36, 0.1);
831
+ }
832
+
833
+ #grain-debug-panel .button-group {
834
+ display: flex;
835
+ gap: 8px;
836
+ margin-top: 18px;
837
+ }
838
+
839
+ #grain-debug-panel button {
840
+ flex: 1;
841
+ padding: 10px 16px;
842
+ border: none;
843
+ border-radius: 8px;
844
+ font-size: 13px;
845
+ font-weight: 600;
846
+ cursor: pointer;
847
+ transition: all 0.2s;
848
+ }
849
+
850
+ #grain-debug-panel button.primary {
851
+ background: #fbbf24;
852
+ color: #1e293b;
853
+ box-shadow: 0 2px 8px rgba(251, 191, 36, 0.3);
854
+ }
855
+
856
+ #grain-debug-panel button.primary:hover {
857
+ background: #f59e0b;
858
+ transform: translateY(-1px);
859
+ box-shadow: 0 4px 12px rgba(251, 191, 36, 0.4);
860
+ }
861
+
862
+ #grain-debug-panel button.secondary {
863
+ background: white;
864
+ border: 1.5px solid #e2e8f0;
865
+ color: #475569;
866
+ }
867
+
868
+ #grain-debug-panel button.secondary:hover {
869
+ background: #f8fafc;
870
+ border-color: #cbd5e1;
871
+ }
872
+
873
+ #grain-debug-panel .url-pattern-input {
874
+ display: none;
875
+ }
876
+
877
+ #grain-debug-panel .url-pattern-input.visible {
878
+ display: block;
879
+ }
880
+ </style>
881
+ <div class="grain-panel-inner">
882
+ <div class="grain-panel-header">
883
+ <h3>Create Tracker</h3>
884
+ <p>Set up automatic tracking for this element</p>
885
+ </div>
886
+ <div class="grain-panel-body">
887
+ <div class="element-preview">
888
+ <div><strong>Element:</strong> ${tagName}${elementId ? `#${elementId}` : ''}</div>
889
+ ${elementText ? `<div><strong>Text:</strong> ${elementText}</div>` : ''}
890
+ </div>
891
+ <div>
892
+ <label>Event Name</label>
893
+ <input type="text" id="grain-event-name" placeholder="e.g., signup_button_click" value="" />
894
+ </div>
895
+ <div>
896
+ <label>Type</label>
897
+ <select id="grain-event-type">
898
+ <option value="metric">Metric</option>
899
+ <option value="conversion">Conversion</option>
900
+ </select>
901
+ </div>
902
+ <div>
903
+ <label>URL Scope</label>
904
+ <select id="grain-url-scope">
905
+ <option value="all">All Pages</option>
906
+ <option value="contains" selected>This Page</option>
907
+ <option value="equals">Exact URL</option>
908
+ </select>
909
+ </div>
910
+ <div class="url-pattern-input visible" id="grain-url-pattern-container">
911
+ <label>URL Pattern</label>
912
+ <input type="text" id="grain-url-pattern" placeholder="e.g., /pricing" value="${window.location.pathname}" />
913
+ </div>
914
+ <div class="button-group">
915
+ <button type="button" class="secondary" id="grain-cancel">Cancel</button>
916
+ <button type="button" class="primary" id="grain-create">✓ Create</button>
917
+ </div>
918
+ </div>
919
+ </div>
920
+ `;
921
+ document.body.appendChild(panel);
922
+ this.panelElement = panel;
923
+ // Auto-generate event name suggestion
924
+ const eventNameInput = panel.querySelector('#grain-event-name');
925
+ if (eventNameInput) {
926
+ const suggestedName = this.generateEventName(element);
927
+ eventNameInput.value = suggestedName;
928
+ eventNameInput.select();
929
+ }
930
+ // Handle URL scope change
931
+ const urlScopeSelect = panel.querySelector('#grain-url-scope');
932
+ const urlPatternContainer = panel.querySelector('#grain-url-pattern-container');
933
+ const urlPatternInput = panel.querySelector('#grain-url-pattern');
934
+ if (urlScopeSelect && urlPatternContainer) {
935
+ urlScopeSelect.addEventListener('change', () => {
936
+ if (urlScopeSelect.value === 'all') {
937
+ urlPatternContainer.classList.remove('visible');
938
+ }
939
+ else {
940
+ urlPatternContainer.classList.add('visible');
941
+ if (urlPatternInput && !urlPatternInput.value) {
942
+ urlPatternInput.value = window.location.pathname;
943
+ }
944
+ }
945
+ });
946
+ }
947
+ // Handle buttons
948
+ const cancelBtn = panel.querySelector('#grain-cancel');
949
+ const createBtn = panel.querySelector('#grain-create');
950
+ if (cancelBtn) {
951
+ cancelBtn.addEventListener('click', () => this.hideCreationPanel());
952
+ }
953
+ if (createBtn) {
954
+ createBtn.addEventListener('click', () => this.handleCreateTracker(xpath));
955
+ }
956
+ }
957
+ /**
958
+ * Generate suggested event name from element
959
+ */
960
+ generateEventName(element) {
961
+ const tagName = element.tagName.toLowerCase();
962
+ const elementId = element.id;
963
+ const elementText = element.textContent?.trim().toLowerCase().replace(/\s+/g, '_').substring(0, 30) || '';
964
+ // Try to generate meaningful name
965
+ if (elementId) {
966
+ return `${elementId}_click`;
967
+ }
968
+ else if (elementText) {
969
+ return `${elementText}_click`;
970
+ }
971
+ else if (tagName === 'button') {
972
+ return 'button_click';
973
+ }
974
+ else if (tagName === 'a') {
975
+ return 'link_click';
976
+ }
977
+ else {
978
+ return `${tagName}_click`;
979
+ }
980
+ }
981
+ /**
982
+ * Handle tracker creation
983
+ */
984
+ async handleCreateTracker(selector) {
985
+ if (!this.panelElement)
986
+ return;
987
+ const eventNameInput = this.panelElement.querySelector('#grain-event-name');
988
+ const eventTypeSelect = this.panelElement.querySelector('#grain-event-type');
989
+ const urlScopeSelect = this.panelElement.querySelector('#grain-url-scope');
990
+ const urlPatternInput = this.panelElement.querySelector('#grain-url-pattern');
991
+ if (!eventNameInput || !eventTypeSelect || !urlScopeSelect)
992
+ return;
993
+ const eventName = eventNameInput.value.trim();
994
+ const eventType = eventTypeSelect.value;
995
+ const urlScope = urlScopeSelect.value;
996
+ const urlPattern = urlPatternInput?.value.trim() || undefined;
997
+ // Validate
998
+ if (!eventName) {
999
+ alert('Please enter an event name');
1000
+ return;
1001
+ }
1002
+ if (!eventName.match(/^[a-zA-Z0-9_-]+$/)) {
1003
+ alert('Event name can only contain letters, numbers, underscores, and hyphens');
1004
+ return;
1005
+ }
1006
+ if ((urlScope === 'contains' || urlScope === 'equals') && !urlPattern) {
1007
+ alert('Please enter a URL pattern');
1008
+ return;
1009
+ }
1010
+ try {
1011
+ // Show loading state
1012
+ const createBtn = this.panelElement.querySelector('#grain-create');
1013
+ if (createBtn) {
1014
+ createBtn.textContent = 'Creating...';
1015
+ createBtn.disabled = true;
1016
+ }
1017
+ // Create tracker
1018
+ await this.createTracker(eventName, eventType, selector, urlScope, urlPattern);
1019
+ // Success
1020
+ this.hideCreationPanel();
1021
+ this.showSuccessMessage(`Tracker "${eventName}" created successfully!`);
1022
+ // Reload trackers and update UI
1023
+ await this.loadExistingTrackers();
1024
+ this.updateToolbarStats();
1025
+ if (this.showTrackers) {
1026
+ this.showTrackerHighlights();
1027
+ this.showTrackersList();
1028
+ }
1029
+ this.log('Tracker created:', eventName);
1030
+ }
1031
+ catch (error) {
1032
+ alert('Failed to create tracker. Please try again.');
1033
+ this.log('Failed to create tracker:', error);
1034
+ // Reset button
1035
+ const createBtn = this.panelElement.querySelector('#grain-create');
1036
+ if (createBtn) {
1037
+ createBtn.textContent = 'Create Tracker';
1038
+ createBtn.disabled = false;
1039
+ }
1040
+ }
1041
+ }
1042
+ /**
1043
+ * Create tracker via API
1044
+ */
1045
+ async createTracker(name, type, selector, urlScope, urlPattern) {
1046
+ const url = `${this.apiUrl}/v1/tenant/${encodeURIComponent(this.tenantId)}/debug-sessions/${this.sessionId}/trackers`;
1047
+ const response = await fetch(url, {
1048
+ method: 'POST',
1049
+ headers: {
1050
+ 'Content-Type': 'application/json',
1051
+ },
1052
+ body: JSON.stringify({
1053
+ name,
1054
+ type,
1055
+ selector,
1056
+ urlScope,
1057
+ urlPattern,
1058
+ }),
1059
+ });
1060
+ if (!response.ok) {
1061
+ throw new Error(`Failed to create tracker: ${response.status}`);
1062
+ }
1063
+ }
1064
+ /**
1065
+ * Hide creation panel
1066
+ */
1067
+ hideCreationPanel() {
1068
+ if (this.panelElement) {
1069
+ this.panelElement.remove();
1070
+ this.panelElement = null;
1071
+ }
1072
+ this.selectedElement = null;
1073
+ }
1074
+ /**
1075
+ * Show success message
1076
+ */
1077
+ showSuccessMessage(message) {
1078
+ const toast = document.createElement('div');
1079
+ toast.style.cssText = `
1080
+ position: fixed;
1081
+ top: 20px;
1082
+ left: 50%;
1083
+ transform: translateX(-50%) translateY(-20px);
1084
+ background: linear-gradient(135deg, #10b981 0%, #059669 100%);
1085
+ color: white;
1086
+ padding: 14px 24px;
1087
+ border-radius: 12px;
1088
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1089
+ font-size: 14px;
1090
+ font-weight: 600;
1091
+ box-shadow: 0 12px 32px rgba(16, 185, 129, 0.3), 0 4px 12px rgba(0, 0, 0, 0.15);
1092
+ z-index: 1000000;
1093
+ display: flex;
1094
+ align-items: center;
1095
+ gap: 10px;
1096
+ animation: slideDown 0.3s ease-out forwards;
1097
+ `;
1098
+ toast.innerHTML = `
1099
+ <style>
1100
+ @keyframes slideDown {
1101
+ to {
1102
+ transform: translateX(-50%) translateY(0);
1103
+ }
1104
+ }
1105
+ </style>
1106
+ <span style="font-size: 18px;">✓</span>
1107
+ <span>${message}</span>
1108
+ `;
1109
+ document.body.appendChild(toast);
1110
+ setTimeout(() => {
1111
+ toast.style.animation = 'slideDown 0.3s ease-in reverse';
1112
+ setTimeout(() => {
1113
+ toast.remove();
1114
+ }, 300);
1115
+ }, 2700);
1116
+ }
1117
+ /**
1118
+ * End debug session
1119
+ */
1120
+ async endDebug() {
1121
+ try {
1122
+ // Call end session API
1123
+ const url = `${this.apiUrl}/v1/tenant/${encodeURIComponent(this.tenantId)}/debug-sessions/${this.sessionId}/end`;
1124
+ await fetch(url, {
1125
+ method: 'POST',
1126
+ headers: {
1127
+ 'Content-Type': 'application/json',
1128
+ },
1129
+ });
1130
+ }
1131
+ catch (error) {
1132
+ this.log('Failed to end debug session:', error);
1133
+ }
1134
+ // Clean up and reload page
1135
+ this.destroy();
1136
+ // Remove debug params from URL and reload
1137
+ const url = new URL(window.location.href);
1138
+ url.searchParams.delete('grain_debug');
1139
+ url.searchParams.delete('grain_session');
1140
+ window.location.href = url.toString();
1141
+ }
1142
+ /**
1143
+ * Get XPath for element
1144
+ */
1145
+ getXPathForElement(element) {
1146
+ if (element.id) {
1147
+ return `//*[@id="${element.id}"]`;
1148
+ }
1149
+ const parts = [];
1150
+ let current = element;
1151
+ while (current && current.nodeType === Node.ELEMENT_NODE) {
1152
+ let index = 0;
1153
+ let sibling = current;
1154
+ while (sibling) {
1155
+ if (sibling.nodeType === Node.ELEMENT_NODE && sibling.tagName === current.tagName) {
1156
+ index++;
1157
+ }
1158
+ sibling = sibling.previousElementSibling;
1159
+ }
1160
+ const tagName = current.tagName.toLowerCase();
1161
+ const pathIndex = index > 1 ? `[${index}]` : '';
1162
+ parts.unshift(`${tagName}${pathIndex}`);
1163
+ current = current.parentElement;
1164
+ }
1165
+ return parts.length ? `/${parts.join('/')}` : '';
1166
+ }
1167
+ /**
1168
+ * Log debug messages
1169
+ */
1170
+ log(...args) {
1171
+ if (this.config.debug) {
1172
+ console.log('[DebugAgent]', ...args);
1173
+ }
1174
+ }
1175
+ /**
1176
+ * Update toolbar stats
1177
+ */
1178
+ updateToolbarStats() {
1179
+ if (!this.toolbarElement)
1180
+ return;
1181
+ const totalStat = this.toolbarElement.querySelector('.grain-stat:nth-child(1) .grain-stat-value');
1182
+ const activeStat = this.toolbarElement.querySelector('.grain-stat:nth-child(2) .grain-stat-value');
1183
+ if (totalStat) {
1184
+ totalStat.textContent = String(this.existingTrackers.length);
1185
+ }
1186
+ if (activeStat) {
1187
+ activeStat.textContent = String(this.existingTrackers.filter(t => t.isEnabled).length);
1188
+ }
1189
+ }
1190
+ /**
1191
+ * Destroy the debug agent
1192
+ */
1193
+ destroy() {
1194
+ if (this.isDestroyed)
1195
+ return;
1196
+ this.log('Destroying debug agent');
1197
+ this.isDestroyed = true;
1198
+ this.disableInspectMode();
1199
+ this.hideTrackerHighlights();
1200
+ this.endDrag();
1201
+ if (this.toolbarElement) {
1202
+ this.toolbarElement.remove();
1203
+ this.toolbarElement = null;
1204
+ }
1205
+ if (this.panelElement) {
1206
+ this.panelElement.remove();
1207
+ this.panelElement = null;
1208
+ }
1209
+ if (this.highlightElement) {
1210
+ this.highlightElement.remove();
1211
+ this.highlightElement = null;
1212
+ }
1213
+ }
1214
+ }
1215
+ //# sourceMappingURL=debug-agent.js.map