humanbehavior-js 0.4.15 → 0.4.17

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 (89) hide show
  1. package/dist/cjs/wizard/index.cjs +6 -8
  2. package/dist/cjs/wizard/index.cjs.map +1 -1
  3. package/dist/cli/ai-auto-install.js +6 -8
  4. package/dist/cli/ai-auto-install.js.map +1 -1
  5. package/dist/esm/wizard/index.js +6 -8
  6. package/dist/esm/wizard/index.js.map +1 -1
  7. package/package/WIZARD_USAGE_GUIDE.md +381 -0
  8. package/package/canvas-recording-demo.html +143 -0
  9. package/package/clean-console-demo.html +39 -0
  10. package/package/dist/cjs/angular/index.cjs +14354 -0
  11. package/package/dist/cjs/angular/index.cjs.map +1 -0
  12. package/package/dist/cjs/index.cjs +14323 -0
  13. package/package/dist/cjs/index.cjs.map +1 -0
  14. package/package/dist/cjs/install-wizard.cjs +1530 -0
  15. package/package/dist/cjs/install-wizard.cjs.map +1 -0
  16. package/package/dist/cjs/react/index.cjs +14478 -0
  17. package/package/dist/cjs/react/index.cjs.map +1 -0
  18. package/package/dist/cjs/remix/index.cjs +14452 -0
  19. package/package/dist/cjs/remix/index.cjs.map +1 -0
  20. package/package/dist/cjs/svelte/index.cjs +14308 -0
  21. package/package/dist/cjs/svelte/index.cjs.map +1 -0
  22. package/package/dist/cjs/vue/index.cjs +14317 -0
  23. package/package/dist/cjs/vue/index.cjs.map +1 -0
  24. package/package/dist/cjs/wizard/index.cjs +3446 -0
  25. package/package/dist/cjs/wizard/index.cjs.map +1 -0
  26. package/package/dist/cli/ai-auto-install.cjs +57161 -0
  27. package/package/dist/cli/ai-auto-install.cjs.map +1 -0
  28. package/package/dist/cli/ai-auto-install.js +1969 -0
  29. package/package/dist/cli/ai-auto-install.js.map +1 -0
  30. package/package/dist/cli/auto-install.cjs +56352 -0
  31. package/package/dist/cli/auto-install.cjs.map +1 -0
  32. package/package/dist/cli/auto-install.js +1957 -0
  33. package/package/dist/cli/auto-install.js.map +1 -0
  34. package/package/dist/esm/angular/index.js +14350 -0
  35. package/package/dist/esm/angular/index.js.map +1 -0
  36. package/package/dist/esm/index.js +14309 -0
  37. package/package/dist/esm/index.js.map +1 -0
  38. package/package/dist/esm/install-wizard.js +1507 -0
  39. package/package/dist/esm/install-wizard.js.map +1 -0
  40. package/package/dist/esm/react/index.js +14472 -0
  41. package/package/dist/esm/react/index.js.map +1 -0
  42. package/package/dist/esm/remix/index.js +14448 -0
  43. package/package/dist/esm/remix/index.js.map +1 -0
  44. package/package/dist/esm/svelte/index.js +14306 -0
  45. package/package/dist/esm/svelte/index.js.map +1 -0
  46. package/package/dist/esm/vue/index.js +14315 -0
  47. package/package/dist/esm/vue/index.js.map +1 -0
  48. package/package/dist/esm/wizard/index.js +3415 -0
  49. package/package/dist/esm/wizard/index.js.map +1 -0
  50. package/package/dist/index.min.js +2 -0
  51. package/package/dist/index.min.js.map +1 -0
  52. package/package/dist/types/angular/index.d.ts +267 -0
  53. package/package/dist/types/index.d.ts +373 -0
  54. package/package/dist/types/install-wizard.d.ts +156 -0
  55. package/package/dist/types/react/index.d.ts +255 -0
  56. package/package/dist/types/remix/index.d.ts +246 -0
  57. package/package/dist/types/svelte/index.d.ts +232 -0
  58. package/package/dist/types/vue/index.d.ts +15 -0
  59. package/package/dist/types/wizard/index.d.ts +523 -0
  60. package/package/package.json +105 -0
  61. package/package/readme.md +281 -0
  62. package/package/rollup.config.js +422 -0
  63. package/package/simple-demo.html +26 -0
  64. package/package/simple-spa.html +838 -0
  65. package/package/src/angular/index.ts +79 -0
  66. package/package/src/api.ts +376 -0
  67. package/package/src/index.ts +28 -0
  68. package/package/src/react/AutoInstallWizard.tsx +557 -0
  69. package/package/src/react/browser.ts +8 -0
  70. package/package/src/react/index.tsx +308 -0
  71. package/package/src/redact.ts +521 -0
  72. package/package/src/remix/index.ts +16 -0
  73. package/package/src/svelte/index.ts +14 -0
  74. package/package/src/tracker.ts +1319 -0
  75. package/package/src/types/clack.d.ts +31 -0
  76. package/package/src/utils/logger.ts +144 -0
  77. package/package/src/vue/index.ts +29 -0
  78. package/package/src/wizard/README.md +114 -0
  79. package/package/src/wizard/ai/ai-install-wizard.ts +897 -0
  80. package/package/src/wizard/ai/manual-framework-wizard.ts +238 -0
  81. package/package/src/wizard/cli/ai-auto-install.ts +243 -0
  82. package/package/src/wizard/cli/auto-install.ts +224 -0
  83. package/package/src/wizard/core/install-wizard.ts +1744 -0
  84. package/package/src/wizard/index.ts +23 -0
  85. package/package/src/wizard/services/centralized-ai-service.ts +668 -0
  86. package/package/src/wizard/services/remote-ai-service.ts +240 -0
  87. package/package/tsconfig.json +24 -0
  88. package/package.json +1 -1
  89. package/src/wizard/cli/ai-auto-install.ts +4 -6
@@ -0,0 +1,838 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>HumanBehavior SDK - Simple SPA Demo</title>
7
+ <style>
8
+ body {
9
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
10
+ margin: 0;
11
+ padding: 20px;
12
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
13
+ min-height: 100vh;
14
+ color: white;
15
+ }
16
+
17
+ .container {
18
+ max-width: 800px;
19
+ margin: 0 auto;
20
+ background: rgba(255, 255, 255, 0.1);
21
+ backdrop-filter: blur(10px);
22
+ border-radius: 20px;
23
+ padding: 40px;
24
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
25
+ }
26
+
27
+ h1 {
28
+ text-align: center;
29
+ margin-bottom: 30px;
30
+ font-size: 2.5em;
31
+ text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
32
+ }
33
+
34
+ .nav {
35
+ display: flex;
36
+ justify-content: center;
37
+ gap: 20px;
38
+ margin-bottom: 40px;
39
+ }
40
+
41
+ .nav button {
42
+ background: rgba(255, 255, 255, 0.2);
43
+ border: 2px solid rgba(255, 255, 255, 0.3);
44
+ color: white;
45
+ padding: 12px 24px;
46
+ border-radius: 25px;
47
+ cursor: pointer;
48
+ font-size: 16px;
49
+ transition: all 0.3s ease;
50
+ backdrop-filter: blur(5px);
51
+ }
52
+
53
+ .nav button:hover {
54
+ background: rgba(255, 255, 255, 0.3);
55
+ transform: translateY(-2px);
56
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
57
+ }
58
+
59
+ .nav button.active {
60
+ background: rgba(255, 255, 255, 0.4);
61
+ border-color: rgba(255, 255, 255, 0.6);
62
+ }
63
+
64
+ .content {
65
+ background: rgba(255, 255, 255, 0.1);
66
+ border-radius: 15px;
67
+ padding: 30px;
68
+ min-height: 400px;
69
+ backdrop-filter: blur(5px);
70
+ }
71
+
72
+ .button {
73
+ background: linear-gradient(45deg, #ff6b6b, #ee5a24);
74
+ color: white;
75
+ border: none;
76
+ padding: 12px 24px;
77
+ border-radius: 25px;
78
+ cursor: pointer;
79
+ font-size: 16px;
80
+ margin: 10px;
81
+ transition: all 0.3s ease;
82
+ }
83
+
84
+ .button:hover {
85
+ transform: translateY(-2px);
86
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
87
+ }
88
+
89
+ .button.secondary {
90
+ background: linear-gradient(45deg, #4834d4, #686de0);
91
+ }
92
+
93
+ .button.success {
94
+ background: linear-gradient(45deg, #00b894, #00cec9);
95
+ }
96
+
97
+ .status {
98
+ background: rgba(0, 0, 0, 0.2);
99
+ border-radius: 10px;
100
+ padding: 15px;
101
+ margin: 20px 0;
102
+ font-family: monospace;
103
+ font-size: 14px;
104
+ }
105
+
106
+ .logs {
107
+ background: rgba(0, 0, 0, 0.3);
108
+ border-radius: 10px;
109
+ padding: 15px;
110
+ margin: 20px 0;
111
+ max-height: 200px;
112
+ overflow-y: auto;
113
+ font-family: monospace;
114
+ font-size: 12px;
115
+ }
116
+
117
+ .fade-in {
118
+ animation: fadeIn 0.5s ease-in;
119
+ }
120
+
121
+ @keyframes fadeIn {
122
+ from { opacity: 0; transform: translateY(20px); }
123
+ to { opacity: 1; transform: translateY(0); }
124
+ }
125
+ </style>
126
+ </head>
127
+ <body>
128
+ <div class="container">
129
+ <h1>HumanBehavior SDK - Simple SPA Demo</h1>
130
+
131
+ <div class="nav">
132
+ <button class="nav-btn active" data-page="home">🏠 Home</button>
133
+ <button class="nav-btn" data-page="about">ℹ️ About</button>
134
+ <button class="nav-btn" data-page="demo">🎯 Demo</button>
135
+ <button class="nav-btn" data-page="status">📊 Status</button>
136
+ </div>
137
+
138
+ <div id="content" class="content fade-in">
139
+ <!-- Content will be loaded here -->
140
+ </div>
141
+ </div>
142
+
143
+ <!-- Load the HumanBehavior SDK -->
144
+ <script src="dist/index.min.js"></script>
145
+
146
+ <script>
147
+ // Global tracker instance
148
+ let tracker = null;
149
+ let currentPage = 'home';
150
+
151
+ // Page content definitions
152
+ const pages = {
153
+ home: {
154
+ title: '🏠 Home',
155
+ content: `
156
+ <h2>Welcome to HumanBehavior SDK Demo</h2>
157
+ <p>This is a single-page application that demonstrates session continuity across page navigations.</p>
158
+
159
+ <div class="status">
160
+ <strong>Session Info:</strong><br>
161
+ Session ID: <span id="sessionId">Loading...</span><br>
162
+ End User ID: <span id="endUserId">Loading...</span><br>
163
+ User Type: <span id="userType">Loading...</span><br>
164
+ Current URL: <span id="currentUrl">Loading...</span>
165
+ </div>
166
+
167
+ <h3>Test Actions</h3>
168
+ <button class="button" onclick="trackCustomEvent('home_button_click', {page: 'home'})">
169
+ Track Custom Event
170
+ </button>
171
+ <button class="button secondary" onclick="testConsoleLog()">
172
+ Test Console Log
173
+ </button>
174
+ <button class="button success" onclick="testConsoleError()">
175
+ Test Console Error
176
+ </button>
177
+
178
+ <div class="logs" id="logs">
179
+ <div>Logs will appear here...</div>
180
+ </div>
181
+ `
182
+ },
183
+
184
+ about: {
185
+ title: 'ℹ️ About',
186
+ content: `
187
+ <h2>About This Demo</h2>
188
+ <p>This single-page application demonstrates how the HumanBehavior SDK maintains session continuity across page navigations.</p>
189
+
190
+ <h3>Key Features</h3>
191
+ <ul>
192
+ <li><strong>Session Continuity:</strong> The tracker never reinitializes when navigating between pages</li>
193
+ <li><strong>URL Tracking:</strong> All navigation events are captured and sent to the server</li>
194
+ <li><strong>Event Recording:</strong> User interactions, console logs, and custom events are all tracked</li>
195
+ <li><strong>Real-time Updates:</strong> Session information updates in real-time</li>
196
+ </ul>
197
+
198
+ <div class="status">
199
+ <strong>Current Session:</strong><br>
200
+ Session ID: <span id="sessionId-about">Loading...</span><br>
201
+ User Type: <span id="userType-about">Loading...</span><br>
202
+ Page Load Time: <span id="pageLoadTime">Loading...</span>
203
+ </div>
204
+
205
+ <button class="button" onclick="trackCustomEvent('about_page_viewed', {section: 'about'})">
206
+ Track About Page View
207
+ </button>
208
+ <button class="button secondary" onclick="showUserInfo()">
209
+ Show Detailed User Info
210
+ </button>
211
+ `
212
+ },
213
+
214
+ demo: {
215
+ title: '🎯 Interactive Demo',
216
+ content: `
217
+ <h2>Interactive Demo</h2>
218
+ <p>Test various tracking features and see them in action.</p>
219
+
220
+ <h3>Form Interaction</h3>
221
+ <form onsubmit="handleFormSubmit(event)">
222
+ <input type="text" id="demoInput" placeholder="Type something..." style="padding: 10px; border-radius: 5px; border: none; margin: 10px; width: 200px;">
223
+ <button type="submit" class="button">Submit Form</button>
224
+ </form>
225
+
226
+ <h3>Custom Events</h3>
227
+ <button class="button" onclick="trackCustomEvent('demo_button_1', {button: 'demo1'})">Demo Button 1</button>
228
+ <button class="button secondary" onclick="trackCustomEvent('demo_button_2', {button: 'demo2'})">Demo Button 2</button>
229
+ <button class="button success" onclick="trackCustomEvent('demo_button_3', {button: 'demo3'})">Demo Button 3</button>
230
+
231
+ <h3>User Authentication Test</h3>
232
+ <button class="button" onclick="testUserAuthentication()">
233
+ Test User Authentication
234
+ </button>
235
+ <p style="font-size: 12px; color: #666; margin-top: 5px;">
236
+ Tests the new behavior where endUserId stays the same but posthogName gets updated with email
237
+ </p>
238
+
239
+ <h3>Real User Authentication</h3>
240
+ <form onsubmit="handleAuthSubmit(event)" style="background: rgba(255,255,255,0.1); padding: 20px; border-radius: 10px; margin: 15px 0;">
241
+ <div style="margin-bottom: 15px;">
242
+ <label for="authEmail" style="display: block; margin-bottom: 5px; font-weight: 600;">Email:</label>
243
+ <input type="email" id="authEmail" placeholder="your.email@example.com" required
244
+ style="width: 100%; padding: 10px; border-radius: 5px; border: none; background: rgba(255,255,255,0.9);">
245
+ </div>
246
+
247
+ <div style="margin-bottom: 15px;">
248
+ <label for="authName" style="display: block; margin-bottom: 5px; font-weight: 600;">Name:</label>
249
+ <input type="text" id="authName" placeholder="Your Name" required
250
+ style="width: 100%; padding: 10px; border-radius: 5px; border: none; background: rgba(255,255,255,0.9);">
251
+ </div>
252
+
253
+ <div style="margin-bottom: 15px;">
254
+ <label for="authPlan" style="display: block; margin-bottom: 5px; font-weight: 600;">Plan:</label>
255
+ <select id="authPlan" style="width: 100%; padding: 10px; border-radius: 5px; border: none; background: rgba(255,255,255,0.9);">
256
+ <option value="free">Free</option>
257
+ <option value="basic">Basic</option>
258
+ <option value="premium">Premium</option>
259
+ <option value="enterprise">Enterprise</option>
260
+ </select>
261
+ </div>
262
+
263
+ <div style="margin-bottom: 15px;">
264
+ <label for="authCompany" style="display: block; margin-bottom: 5px; font-weight: 600;">Company (Optional):</label>
265
+ <input type="text" id="authCompany" placeholder="Your Company"
266
+ style="width: 100%; padding: 10px; border-radius: 5px; border: none; background: rgba(255,255,255,0.9);">
267
+ </div>
268
+
269
+ <button type="submit" class="button success" style="width: 100%;">
270
+ 🔐 Authenticate User
271
+ </button>
272
+ </form>
273
+
274
+ <div style="margin-top: 15px; display: flex; gap: 10px;">
275
+ <button class="button secondary" onclick="showAuthStatus()" style="flex: 1;">
276
+ 📊 Show Auth Status
277
+ </button>
278
+ </div>
279
+
280
+ <div id="authResult" style="margin-top: 15px; padding: 10px; border-radius: 5px; display: none;"></div>
281
+
282
+ <div class="logs" id="demoLogs">
283
+ <div>Demo events will appear here...</div>
284
+ </div>
285
+ `
286
+ },
287
+
288
+ status: {
289
+ title: '📊 Session Status',
290
+ content: `
291
+ <h2>Session Status & Debug Info</h2>
292
+
293
+ <div class="status">
294
+ <strong>Tracker Status:</strong><br>
295
+ Initialized: <span id="trackerInitialized">Loading...</span><br>
296
+ Session ID: <span id="sessionId-status">Loading...</span><br>
297
+ End User ID: <span id="endUserId-status">Loading...</span><br>
298
+ User Type: <span id="userType-status">Loading...</span><br>
299
+ Current URL: <span id="currentUrl-status">Loading...</span><br>
300
+ Connection Status: <span id="connectionStatus">Loading...</span>
301
+ </div>
302
+
303
+ <h3>Actions</h3>
304
+ <button class="button" onclick="viewLogs()">View Logs</button>
305
+ <button class="button secondary" onclick="testConnection()">Test Connection</button>
306
+ <button class="button success" onclick="clearLogs()">Clear Logs</button>
307
+
308
+ <div class="logs" id="statusLogs">
309
+ <div>Status logs will appear here...</div>
310
+ </div>
311
+ `
312
+ }
313
+ };
314
+
315
+ // Initialize the application
316
+ async function initApp() {
317
+ try {
318
+ console.log('Starting SPA initialization...');
319
+
320
+ // Check if SDK is loaded
321
+ if (typeof HumanBehaviorTracker === 'undefined') {
322
+ throw new Error('HumanBehaviorTracker SDK not loaded. Check if dist/index.js exists.');
323
+ }
324
+
325
+ // Initialize HumanBehavior tracker
326
+ console.log('Initializing tracker...');
327
+ tracker = HumanBehaviorTracker.init('13c3e029-ca45-4a3c-a33b-f5dcb297e31c', {
328
+ logLevel: 'debug',
329
+ redactFields: ['password', 'credit_card']
330
+ });
331
+
332
+ console.log('Tracker created, waiting for initialization...');
333
+
334
+ // Wait for tracker to initialize with timeout
335
+ if (tracker.initializationPromise) {
336
+ try {
337
+ await Promise.race([
338
+ tracker.initializationPromise,
339
+ new Promise((_, reject) =>
340
+ setTimeout(() => reject(new Error('Initialization timeout')), 10000)
341
+ )
342
+ ]);
343
+ console.log('Tracker initialized successfully');
344
+ } catch (initError) {
345
+ console.warn('Tracker initialization failed or timed out:', initError);
346
+ addLog('Tracker initialization warning: ' + initError.message);
347
+ // Continue anyway - tracker might still work
348
+ }
349
+ } else {
350
+ console.log('No initialization promise, continuing...');
351
+ }
352
+
353
+ // Set up navigation
354
+ setupNavigation();
355
+
356
+ // Load initial page
357
+ loadPage('home');
358
+
359
+ // Update status periodically
360
+ setInterval(updateStatus, 2000);
361
+
362
+ console.log('SPA App initialized successfully');
363
+ addLog('SPA App initialized successfully');
364
+
365
+ } catch (error) {
366
+ console.error('Failed to initialize SPA app:', error);
367
+ addLog('Error initializing app: ' + error.message);
368
+
369
+ // Show error in content
370
+ document.getElementById('content').innerHTML = `
371
+ <h2>Initialization Error</h2>
372
+ <p>Failed to initialize the HumanBehavior SDK:</p>
373
+ <div class="status">
374
+ <strong>Error:</strong> ${error.message}<br>
375
+ <strong>Stack:</strong> ${error.stack}
376
+ </div>
377
+ <button class="button" onclick="location.reload()">Reload Page</button>
378
+ `;
379
+ }
380
+ }
381
+
382
+ // Set up client-side navigation
383
+ function setupNavigation() {
384
+ const navButtons = document.querySelectorAll('.nav-btn');
385
+
386
+ navButtons.forEach(button => {
387
+ button.addEventListener('click', () => {
388
+ const page = button.dataset.page;
389
+ navigateToPage(page);
390
+ });
391
+ });
392
+
393
+ // Handle browser back/forward buttons
394
+ window.addEventListener('popstate', (event) => {
395
+ const page = event.state?.page || 'home';
396
+ loadPage(page);
397
+ updateActiveNavButton(page);
398
+ });
399
+ }
400
+
401
+ // Navigate to a page
402
+ function navigateToPage(page) {
403
+ if (page === currentPage) return;
404
+
405
+ console.log(`Navigating from ${currentPage} to ${page}`);
406
+
407
+ // Update URL without page reload
408
+ history.pushState({ page }, pages[page].title, `#${page}`);
409
+
410
+ // Load the page content
411
+ loadPage(page);
412
+
413
+ // Update active nav button
414
+ updateActiveNavButton(page);
415
+
416
+ // Track navigation event
417
+ if (tracker && tracker.trackNavigationEvent) {
418
+ try {
419
+ tracker.trackNavigationEvent('spa_navigation', currentPage, page);
420
+ } catch (error) {
421
+ console.error('Failed to track navigation:', error);
422
+ }
423
+ }
424
+
425
+ currentPage = page;
426
+ }
427
+
428
+ // Load page content
429
+ function loadPage(page) {
430
+ const contentDiv = document.getElementById('content');
431
+ const pageData = pages[page];
432
+
433
+ if (!pageData) {
434
+ contentDiv.innerHTML = '<h2>Page not found</h2>';
435
+ return;
436
+ }
437
+
438
+ // Add fade-in animation
439
+ contentDiv.classList.remove('fade-in');
440
+ void contentDiv.offsetWidth; // Trigger reflow
441
+ contentDiv.classList.add('fade-in');
442
+
443
+ contentDiv.innerHTML = pageData.content;
444
+
445
+ // Update page title
446
+ document.title = `HumanBehavior SDK - ${pageData.title}`;
447
+
448
+ // Track page view
449
+ if (tracker && tracker.trackPageView) {
450
+ try {
451
+ tracker.trackPageView();
452
+ } catch (error) {
453
+ console.error('Failed to track pageview:', error);
454
+ }
455
+ }
456
+
457
+ addLog(`Navigated to ${page} page`);
458
+ }
459
+
460
+ // Update active navigation button
461
+ function updateActiveNavButton(page) {
462
+ document.querySelectorAll('.nav-btn').forEach(btn => {
463
+ btn.classList.remove('active');
464
+ });
465
+ const activeButton = document.querySelector(`[data-page="${page}"]`);
466
+ if (activeButton) {
467
+ activeButton.classList.add('active');
468
+ }
469
+ }
470
+
471
+ // Update status information
472
+ function updateStatus() {
473
+ if (!tracker) return;
474
+
475
+ try {
476
+ // Update session info
477
+ const sessionIdElements = document.querySelectorAll('#sessionId, #sessionId-about, #sessionId-status');
478
+ const sessionId = tracker.getSessionId ? tracker.getSessionId() : 'Not available';
479
+ sessionIdElements.forEach(el => {
480
+ if (el) el.textContent = sessionId;
481
+ });
482
+
483
+ const endUserIdElements = document.querySelectorAll('#endUserId, #endUserId-status');
484
+ const endUserId = tracker.endUserId || 'Not set';
485
+ endUserIdElements.forEach(el => {
486
+ if (el) el.textContent = endUserId;
487
+ });
488
+
489
+ // Update user type (preexisting vs new)
490
+ const userTypeElements = document.querySelectorAll('#userType, #userType-about, #userType-status');
491
+ let userType = 'Unknown';
492
+ if (tracker.isPreexistingUser) {
493
+ try {
494
+ const isPreexisting = tracker.isPreexistingUser();
495
+ userType = isPreexisting ? '🔄 Preexisting User' : '🆕 New User';
496
+ } catch (error) {
497
+ console.warn('Error checking preexisting user:', error);
498
+ userType = 'Error';
499
+ }
500
+ }
501
+ userTypeElements.forEach(el => {
502
+ if (el) el.textContent = userType;
503
+ });
504
+
505
+ const currentUrlElements = document.querySelectorAll('#currentUrl, #currentUrl-status');
506
+ const currentUrl = window.location.href;
507
+ currentUrlElements.forEach(el => {
508
+ if (el) el.textContent = currentUrl;
509
+ });
510
+
511
+ const trackerInitialized = document.getElementById('trackerInitialized');
512
+ if (trackerInitialized) {
513
+ trackerInitialized.textContent = tracker.initialized ? 'Yes' : 'No';
514
+ }
515
+
516
+ const connectionStatus = document.getElementById('connectionStatus');
517
+ if (connectionStatus && tracker.getConnectionStatus) {
518
+ try {
519
+ const status = tracker.getConnectionStatus();
520
+ connectionStatus.textContent = status.blocked ? 'Blocked' : 'Connected';
521
+ } catch (error) {
522
+ console.warn('Error getting connection status:', error);
523
+ connectionStatus.textContent = 'Error';
524
+ }
525
+ }
526
+
527
+ const pageLoadTime = document.getElementById('pageLoadTime');
528
+ if (pageLoadTime) {
529
+ pageLoadTime.textContent = new Date().toLocaleTimeString();
530
+ }
531
+ } catch (error) {
532
+ console.error('Error updating status:', error);
533
+ // Don't let status update errors crash the app
534
+ }
535
+ }
536
+
537
+ // Track custom events
538
+ async function trackCustomEvent(eventName, properties = {}) {
539
+ if (!tracker) {
540
+ addLog('Tracker not available');
541
+ return;
542
+ }
543
+
544
+ try {
545
+ if (tracker.customEvent) {
546
+ await tracker.customEvent(eventName, properties);
547
+ addLog(`Custom event tracked: ${eventName}`, properties);
548
+ } else {
549
+ addLog('customEvent method not available');
550
+ }
551
+ } catch (error) {
552
+ console.error('Error tracking custom event:', error);
553
+ addLog('Error tracking custom event: ' + error.message);
554
+ }
555
+ }
556
+
557
+ // Test user authentication (new behavior)
558
+ async function testUserAuthentication() {
559
+ if (!tracker) {
560
+ addLog('Tracker not available');
561
+ return;
562
+ }
563
+
564
+ try {
565
+ const originalEndUserId = tracker.getSessionId();
566
+ addLog(`Original endUserId: ${originalEndUserId}`);
567
+
568
+ // Simulate user sign-in
569
+ const userId = await tracker.addUserInfo({
570
+ userId: 'user123@example.com',
571
+ userProperties: {
572
+ email: 'user123@example.com',
573
+ name: 'John Doe',
574
+ plan: 'premium',
575
+ signupDate: new Date().toISOString()
576
+ }
577
+ });
578
+
579
+ const newEndUserId = tracker.getSessionId();
580
+ addLog(`New endUserId: ${newEndUserId}`);
581
+ addLog(`endUserId changed: ${originalEndUserId !== newEndUserId ? 'YES (BAD)' : 'NO (GOOD)'}`);
582
+ addLog(`User authenticated: ${userId}`);
583
+
584
+ // The endUserId should stay the same, but posthogName will be updated with email
585
+ addLog('✅ endUserId maintained for session continuity');
586
+ addLog('✅ posthogName will be updated with email for UI display');
587
+
588
+ } catch (error) {
589
+ console.error('Error testing user authentication:', error);
590
+ addLog('Error testing user authentication: ' + error.message);
591
+ }
592
+ }
593
+
594
+ // Test console logging
595
+ function testConsoleLog() {
596
+ console.log('This is a test console log message');
597
+ addLog('Console log test executed');
598
+ }
599
+
600
+ function testConsoleError() {
601
+ console.error('This is a test console error message');
602
+ addLog('Console error test executed');
603
+ }
604
+
605
+ // Handle form submission
606
+ function handleFormSubmit(event) {
607
+ event.preventDefault();
608
+ const input = document.getElementById('demoInput');
609
+ const value = input.value;
610
+
611
+ trackCustomEvent('form_submitted', { value: value });
612
+ addLog(`Form submitted with value: ${value}`);
613
+
614
+ input.value = '';
615
+ }
616
+
617
+ // Handle authentication form submission
618
+ async function handleAuthSubmit(event) {
619
+ event.preventDefault();
620
+ const email = document.getElementById('authEmail').value;
621
+ const name = document.getElementById('authName').value;
622
+ const plan = document.getElementById('authPlan').value;
623
+ const company = document.getElementById('authCompany').value;
624
+
625
+ if (!email || !name) {
626
+ alert('Email and Name are required for authentication.');
627
+ return;
628
+ }
629
+
630
+ try {
631
+ const userId = await tracker.addUserInfo({
632
+ userId: email, // Use email as userId
633
+ userProperties: {
634
+ email: email,
635
+ name: name,
636
+ plan: plan,
637
+ company: company,
638
+ signupDate: new Date().toISOString()
639
+ }
640
+ });
641
+
642
+ const newEndUserId = tracker.getSessionId();
643
+ addLog(`New endUserId after authentication: ${newEndUserId}`);
644
+ addLog(`endUserId changed: ${tracker.getSessionId() !== newEndUserId ? 'YES (BAD)' : 'NO (GOOD)'}`);
645
+ addLog(`User authenticated: ${userId}`);
646
+
647
+ const authResultDiv = document.getElementById('authResult');
648
+ authResultDiv.style.display = 'block';
649
+ authResultDiv.innerHTML = `
650
+ <strong>Authentication Successful!</strong><br>
651
+ New End User ID: ${newEndUserId}<br>
652
+ Original End User ID: ${tracker.getSessionId()}<br>
653
+ endUserId changed: ${tracker.getSessionId() !== newEndUserId ? 'YES (BAD)' : 'NO (GOOD)'}
654
+ `;
655
+ authResultDiv.style.color = 'green';
656
+
657
+ } catch (error) {
658
+ console.error('Error authenticating user:', error);
659
+ addLog('Error authenticating user: ' + error.message);
660
+
661
+ const authResultDiv = document.getElementById('authResult');
662
+ authResultDiv.style.display = 'block';
663
+ authResultDiv.innerHTML = `
664
+ <strong>Authentication Failed!</strong><br>
665
+ Error: ${error.message}
666
+ `;
667
+ authResultDiv.style.color = 'red';
668
+ }
669
+ }
670
+
671
+ // View logs
672
+ function viewLogs() {
673
+ if (tracker && tracker.viewLogs) {
674
+ tracker.viewLogs();
675
+ } else {
676
+ addLog('viewLogs method not available');
677
+ }
678
+ }
679
+
680
+ // Test connection
681
+ async function testConnection() {
682
+ if (!tracker) {
683
+ addLog('Tracker not available');
684
+ return;
685
+ }
686
+
687
+ try {
688
+ if (tracker.testConnection) {
689
+ const result = await tracker.testConnection();
690
+ addLog(`Connection test: ${result.success ? 'Success' : 'Failed'}`, result);
691
+ } else {
692
+ addLog('testConnection method not available');
693
+ }
694
+ } catch (error) {
695
+ addLog(`Connection test error: ${error.message}`);
696
+ }
697
+ }
698
+
699
+ // Clear logs
700
+ function clearLogs() {
701
+ const logElements = document.querySelectorAll('.logs');
702
+ logElements.forEach(el => {
703
+ el.innerHTML = '<div>Logs cleared...</div>';
704
+ });
705
+ }
706
+
707
+ // Show detailed user information
708
+ function showUserInfo() {
709
+ if (!tracker) {
710
+ addLog('Tracker not available');
711
+ return;
712
+ }
713
+
714
+ try {
715
+ const userInfo = tracker.getUserInfo ? tracker.getUserInfo() : null;
716
+ if (userInfo) {
717
+ const infoText = ` <strong>Detailed User Information:</strong><br>
718
+ End User ID: ${userInfo.endUserId || 'Not set'}<br>
719
+ Session ID: ${userInfo.sessionId}<br>
720
+ Is Preexisting User: ${userInfo.isPreexistingUser ? 'Yes' : 'No'}<br>
721
+ Initialized: ${userInfo.initialized ? 'Yes' : 'No'}<br>
722
+ <br>
723
+ <strong>Cookie Check:</strong><br>
724
+ End User Cookie: ${tracker.getCookie ? tracker.getCookie(`human_behavior_end_user_id_13c3e029-ca45-4a3c-a33b-f5dcb297e31c`) : 'Method not available'}<br>
725
+ Session Cookie: ${tracker.getCookie ? tracker.getCookie('human_behavior_session_id') : 'Method not available'}
726
+ `;
727
+
728
+ // Show in an alert or add to logs
729
+ addLog('Detailed user info displayed', userInfo);
730
+ alert(infoText);
731
+ } else {
732
+ addLog('getUserInfo method not available');
733
+ }
734
+ } catch (error) {
735
+ addLog(`Error getting user info: ${error.message}`);
736
+ }
737
+ }
738
+
739
+ // Show current authentication status
740
+ function showAuthStatus() {
741
+ if (!tracker) {
742
+ addLog('Tracker not available');
743
+ return;
744
+ }
745
+ try {
746
+ const userInfo = tracker.getUserInfo ? tracker.getUserInfo() : null;
747
+ const userAttributes = tracker.getUserAttributes ? tracker.getUserAttributes() : {};
748
+
749
+ if (userInfo) {
750
+ const statusText = `
751
+ <strong>Current Authentication Status:</strong><br>
752
+ End User ID: ${userInfo.endUserId || 'Not set'}<br>
753
+ Session ID: ${userInfo.sessionId}<br>
754
+ Is Preexisting User: ${userInfo.isPreexistingUser ? 'Yes' : 'No'}<br>
755
+ Initialized: ${userInfo.initialized ? 'Yes' : 'No'}<br>
756
+ <br>
757
+ <strong>User Attributes:</strong><br>
758
+ ${Object.keys(userAttributes).length > 0 ?
759
+ Object.entries(userAttributes).map(([key, value]) => `${key}: ${value}`).join('<br>') :
760
+ 'No user attributes set'
761
+ }
762
+ <br><br>
763
+ <strong>Cookie Check:</strong><br>
764
+ End User Cookie: ${tracker.getCookie ? tracker.getCookie(`human_behavior_end_user_id_13c3e029-ca45-4a3c-a33b-f5dcb297e31c`) : 'Method not available'}<br>
765
+ Session Cookie: ${tracker.getCookie ? tracker.getCookie('human_behavior_session_id') : 'Method not available'}
766
+ `;
767
+ addLog('Authentication status displayed', { userInfo, userAttributes });
768
+ alert(statusText);
769
+ } else {
770
+ addLog('getUserInfo method not available for status');
771
+ }
772
+ } catch (error) {
773
+ addLog(`Error getting authentication status: ${error.message}`);
774
+ }
775
+ }
776
+
777
+ // Add log message
778
+ function addLog(message, data = null) {
779
+ const logElements = document.querySelectorAll('.logs');
780
+ const timestamp = new Date().toLocaleTimeString();
781
+ const logEntry = `<div>[${timestamp}] ${message}${data ? ' - ' + JSON.stringify(data) : ''}</div>`;
782
+
783
+ logElements.forEach(el => {
784
+ el.innerHTML += logEntry;
785
+ el.scrollTop = el.scrollHeight;
786
+ });
787
+
788
+ // Also log to console
789
+ console.log(`[${timestamp}] ${message}`, data);
790
+ }
791
+
792
+ // Initialize the app when the page loads
793
+ document.addEventListener('DOMContentLoaded', initApp);
794
+
795
+ // Add global error handler to prevent page from going blank
796
+ window.addEventListener('error', function(event) {
797
+ console.error('Global error caught:', event.error);
798
+ addLog('Global error: ' + event.error.message);
799
+
800
+ // Prevent the page from going blank by showing error content
801
+ const contentDiv = document.getElementById('content');
802
+ if (contentDiv && contentDiv.innerHTML.trim() === '') {
803
+ contentDiv.innerHTML = `
804
+ <h2>Application Error</h2>
805
+ <p>An error occurred but the application is still running:</p>
806
+ <div class="status">
807
+ <strong>Error:</strong> ${event.error.message}<br>
808
+ <strong>File:</strong> ${event.filename}<br>
809
+ <strong>Line:</strong> ${event.lineno}
810
+ </div>
811
+ <button class="button" onclick="loadPage('home')">Go to Home</button>
812
+ <button class="button secondary" onclick="location.reload()">Reload Page</button>
813
+ `;
814
+ }
815
+ });
816
+
817
+ // Add unhandled promise rejection handler
818
+ window.addEventListener('unhandledrejection', function(event) {
819
+ console.error('Unhandled promise rejection:', event.reason);
820
+ addLog('Unhandled promise rejection: ' + event.reason);
821
+ event.preventDefault(); // Prevent the default browser behavior
822
+ });
823
+
824
+ // Add periodic health check
825
+ setInterval(() => {
826
+ try {
827
+ const contentDiv = document.getElementById('content');
828
+ if (contentDiv && contentDiv.innerHTML.trim() === '') {
829
+ console.warn('Content div is empty, attempting to restore...');
830
+ loadPage('home');
831
+ }
832
+ } catch (error) {
833
+ console.error('Health check error:', error);
834
+ }
835
+ }, 5000); // Check every 5 seconds
836
+ </script>
837
+ </body>
838
+ </html>