blinker-sdk 1.0.1 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +226 -147
  2. package/dist/blinker.min.js +452 -1
  3. package/dist/capture/deduplication.d.ts +26 -0
  4. package/dist/capture/deduplication.d.ts.map +1 -0
  5. package/dist/capture/errorHandler.d.ts +5 -0
  6. package/dist/capture/errorHandler.d.ts.map +1 -0
  7. package/dist/capture/index.d.ts +4 -0
  8. package/dist/capture/index.d.ts.map +1 -0
  9. package/dist/capture/types.d.ts +13 -0
  10. package/dist/capture/types.d.ts.map +1 -0
  11. package/dist/context/SessionManager.d.ts +16 -0
  12. package/dist/context/SessionManager.d.ts.map +1 -0
  13. package/dist/context/UserContext.d.ts +19 -0
  14. package/dist/context/UserContext.d.ts.map +1 -0
  15. package/dist/context/index.d.ts +4 -0
  16. package/dist/context/index.d.ts.map +1 -0
  17. package/dist/context/types.d.ts +18 -0
  18. package/dist/context/types.d.ts.map +1 -0
  19. package/dist/core/Blinker.d.ts +45 -0
  20. package/dist/core/Blinker.d.ts.map +1 -0
  21. package/dist/core/config.d.ts +29 -0
  22. package/dist/core/config.d.ts.map +1 -0
  23. package/dist/core/index.d.ts +4 -0
  24. package/dist/core/index.d.ts.map +1 -0
  25. package/dist/core/types.d.ts +54 -0
  26. package/dist/core/types.d.ts.map +1 -0
  27. package/dist/filters/FilterEngine.d.ts +9 -0
  28. package/dist/filters/FilterEngine.d.ts.map +1 -0
  29. package/dist/filters/defaults.d.ts +3 -0
  30. package/dist/filters/defaults.d.ts.map +1 -0
  31. package/dist/filters/index.d.ts +4 -0
  32. package/dist/filters/index.d.ts.map +1 -0
  33. package/dist/filters/types.d.ts +8 -0
  34. package/dist/filters/types.d.ts.map +1 -0
  35. package/dist/index.cjs.js +2192 -266
  36. package/dist/index.d.ts +7 -32
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.esm.js +2192 -266
  39. package/dist/queue/EventQueue.d.ts +21 -0
  40. package/dist/queue/EventQueue.d.ts.map +1 -0
  41. package/dist/queue/index.d.ts +4 -0
  42. package/dist/queue/index.d.ts.map +1 -0
  43. package/dist/queue/storage.d.ts +16 -0
  44. package/dist/queue/storage.d.ts.map +1 -0
  45. package/dist/queue/types.d.ts +21 -0
  46. package/dist/queue/types.d.ts.map +1 -0
  47. package/dist/sampling/RateLimiter.d.ts +12 -0
  48. package/dist/sampling/RateLimiter.d.ts.map +1 -0
  49. package/dist/sampling/Sampler.d.ts +16 -0
  50. package/dist/sampling/Sampler.d.ts.map +1 -0
  51. package/dist/sampling/index.d.ts +4 -0
  52. package/dist/sampling/index.d.ts.map +1 -0
  53. package/dist/sampling/types.d.ts +10 -0
  54. package/dist/sampling/types.d.ts.map +1 -0
  55. package/dist/transport/index.d.ts +3 -0
  56. package/dist/transport/index.d.ts.map +1 -0
  57. package/dist/transport/sender.d.ts +4 -0
  58. package/dist/transport/sender.d.ts.map +1 -0
  59. package/dist/transport/types.d.ts +12 -0
  60. package/dist/transport/types.d.ts.map +1 -0
  61. package/dist/utils/browser.d.ts +10 -0
  62. package/dist/utils/browser.d.ts.map +1 -0
  63. package/dist/utils/hash.d.ts +4 -0
  64. package/dist/utils/hash.d.ts.map +1 -0
  65. package/dist/utils/index.d.ts +4 -0
  66. package/dist/utils/index.d.ts.map +1 -0
  67. package/dist/utils/logger.d.ts +9 -0
  68. package/dist/utils/logger.d.ts.map +1 -0
  69. package/dist/widget/Avatar.d.ts +20 -0
  70. package/dist/widget/Avatar.d.ts.map +1 -0
  71. package/dist/widget/Dialog.d.ts +25 -0
  72. package/dist/widget/Dialog.d.ts.map +1 -0
  73. package/dist/widget/QuestionEngine.d.ts +7 -0
  74. package/dist/widget/QuestionEngine.d.ts.map +1 -0
  75. package/dist/widget/Widget.d.ts +28 -0
  76. package/dist/widget/Widget.d.ts.map +1 -0
  77. package/dist/widget/index.d.ts +8 -0
  78. package/dist/widget/index.d.ts.map +1 -0
  79. package/dist/widget/styles.d.ts +5 -0
  80. package/dist/widget/styles.d.ts.map +1 -0
  81. package/dist/widget/types.d.ts +46 -0
  82. package/dist/widget/types.d.ts.map +1 -0
  83. package/package.json +1 -1
  84. package/dist/Blinker.d.ts +0 -65
  85. package/dist/Blinker.d.ts.map +0 -1
  86. package/dist/errorHandler.d.ts +0 -19
  87. package/dist/errorHandler.d.ts.map +0 -1
  88. package/dist/sender.d.ts +0 -11
  89. package/dist/sender.d.ts.map +0 -1
  90. package/dist/types.d.ts +0 -92
  91. package/dist/types.d.ts.map +0 -1
package/dist/index.cjs.js CHANGED
@@ -22,372 +22,2298 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  Blinker: () => Blinker,
24
24
  DEFAULT_FILTERS: () => DEFAULT_FILTERS,
25
+ DEFAULT_WIDGET_CONFIG: () => DEFAULT_WIDGET_CONFIG,
26
+ SDK_VERSION: () => SDK_VERSION,
25
27
  blinker: () => blinker,
26
28
  default: () => index_default
27
29
  });
28
30
  module.exports = __toCommonJS(index_exports);
29
31
 
30
- // src/sender.ts
31
- async function sendEvent(api, token, event, debug = false) {
32
- const endpoint = `${api.replace(/\/$/, "")}/events`;
32
+ // src/core/config.ts
33
+ var BLINKER_API = "https://api.blinker.live";
34
+ var SDK_VERSION = "2.0.1";
35
+ var STORAGE_KEYS = {
36
+ EVENT_QUEUE: "blinker_event_queue",
37
+ SESSION: "blinker_session",
38
+ USER_CONTEXT: "blinker_user_context"
39
+ };
40
+ var DEFAULTS = {
41
+ endpoint: BLINKER_API,
42
+ enabled: true,
43
+ captureErrors: true,
44
+ captureRejections: true,
45
+ enableBatching: true,
46
+ batchSize: 10,
47
+ flushInterval: 5e3,
48
+ enableOfflineStorage: true,
49
+ maxStoredEvents: 100,
50
+ enableDeduplication: true,
51
+ deduplicationWindow: 6e4,
52
+ maxEventsPerMinute: 100,
53
+ sampleRate: 1,
54
+ debug: false
55
+ };
56
+ var TIMING = {
57
+ OFFLINE_RETRY_TIMEOUT: 3e4,
58
+ MIN_FLUSH_INTERVAL: 1e3,
59
+ MAX_FLUSH_INTERVAL: 6e4
60
+ };
61
+
62
+ // src/filters/defaults.ts
63
+ var DEFAULT_FILTERS = {
64
+ ignoreHttpCodes: [401, 403],
65
+ ignoreErrorTypes: [],
66
+ ignoreMessagePatterns: [
67
+ "ResizeObserver loop",
68
+ "Script error",
69
+ "ResizeObserver loop completed"
70
+ ],
71
+ captureAll: false
72
+ };
73
+
74
+ // src/utils/logger.ts
75
+ var PREFIX = "[Blinker]";
76
+ function createLogger(debug) {
77
+ const noop = () => {
78
+ };
79
+ if (!debug) {
80
+ return {
81
+ log: noop,
82
+ warn: noop,
83
+ error: noop
84
+ };
85
+ }
86
+ return {
87
+ log: (...args) => console.log(PREFIX, ...args),
88
+ warn: (...args) => console.warn(PREFIX, ...args),
89
+ error: (...args) => console.error(PREFIX, ...args)
90
+ };
91
+ }
92
+ var globalLogger = createLogger(false);
93
+ function setGlobalLogger(debug) {
94
+ globalLogger = createLogger(debug);
95
+ }
96
+ function getLogger() {
97
+ return globalLogger;
98
+ }
99
+
100
+ // src/filters/FilterEngine.ts
101
+ var FilterEngine = class {
102
+ constructor(userFilters) {
103
+ var _a, _b, _c, _d;
104
+ this.filters = {
105
+ ignoreHttpCodes: (_a = userFilters == null ? void 0 : userFilters.ignoreHttpCodes) != null ? _a : DEFAULT_FILTERS.ignoreHttpCodes,
106
+ ignoreErrorTypes: (_b = userFilters == null ? void 0 : userFilters.ignoreErrorTypes) != null ? _b : DEFAULT_FILTERS.ignoreErrorTypes,
107
+ ignoreMessagePatterns: (_c = userFilters == null ? void 0 : userFilters.ignoreMessagePatterns) != null ? _c : DEFAULT_FILTERS.ignoreMessagePatterns,
108
+ captureAll: (_d = userFilters == null ? void 0 : userFilters.captureAll) != null ? _d : DEFAULT_FILTERS.captureAll
109
+ };
110
+ }
111
+ shouldCapture(message, errorType, httpCode) {
112
+ const logger = getLogger();
113
+ if (this.filters.captureAll) {
114
+ return true;
115
+ }
116
+ if (httpCode !== void 0 && this.filters.ignoreHttpCodes.includes(httpCode)) {
117
+ logger.log("Event filtered out by HTTP code:", httpCode);
118
+ return false;
119
+ }
120
+ if (errorType && this.filters.ignoreErrorTypes.includes(errorType)) {
121
+ logger.log("Event filtered out by error type:", errorType);
122
+ return false;
123
+ }
124
+ for (const pattern of this.filters.ignoreMessagePatterns) {
125
+ if (message.toLowerCase().includes(pattern.toLowerCase())) {
126
+ logger.log("Event filtered out by message pattern:", pattern);
127
+ return false;
128
+ }
129
+ }
130
+ if (httpCode === void 0) {
131
+ const httpCodeMatch = message.match(/(?:HTTP\s*|status[:\s]*)?(\d{3})(?:\s|$|:)/i);
132
+ if (httpCodeMatch) {
133
+ const extractedCode = parseInt(httpCodeMatch[1], 10);
134
+ if (extractedCode >= 100 && extractedCode < 600) {
135
+ if (this.filters.ignoreHttpCodes.includes(extractedCode)) {
136
+ logger.log("Event filtered out by extracted HTTP code:", extractedCode);
137
+ return false;
138
+ }
139
+ }
140
+ }
141
+ }
142
+ return true;
143
+ }
144
+ getFilters() {
145
+ return { ...this.filters };
146
+ }
147
+ updateFilters(newFilters) {
148
+ var _a, _b, _c, _d;
149
+ this.filters = {
150
+ ignoreHttpCodes: (_a = newFilters.ignoreHttpCodes) != null ? _a : this.filters.ignoreHttpCodes,
151
+ ignoreErrorTypes: (_b = newFilters.ignoreErrorTypes) != null ? _b : this.filters.ignoreErrorTypes,
152
+ ignoreMessagePatterns: (_c = newFilters.ignoreMessagePatterns) != null ? _c : this.filters.ignoreMessagePatterns,
153
+ captureAll: (_d = newFilters.captureAll) != null ? _d : this.filters.captureAll
154
+ };
155
+ }
156
+ };
157
+
158
+ // src/utils/browser.ts
159
+ function isBrowser() {
160
+ return typeof window !== "undefined";
161
+ }
162
+ function isLocalStorageAvailable() {
163
+ if (!isBrowser()) return false;
164
+ try {
165
+ const testKey = "__blinker_test__";
166
+ localStorage.setItem(testKey, "test");
167
+ localStorage.removeItem(testKey);
168
+ return true;
169
+ } catch (e) {
170
+ return false;
171
+ }
172
+ }
173
+ function isSessionStorageAvailable() {
174
+ if (!isBrowser()) return false;
175
+ try {
176
+ const testKey = "__blinker_test__";
177
+ sessionStorage.setItem(testKey, "test");
178
+ sessionStorage.removeItem(testKey);
179
+ return true;
180
+ } catch (e) {
181
+ return false;
182
+ }
183
+ }
184
+ function isOnline() {
185
+ var _a;
186
+ if (!isBrowser()) return true;
187
+ return (_a = navigator.onLine) != null ? _a : true;
188
+ }
189
+ function getCurrentUrl() {
190
+ if (!isBrowser()) return void 0;
191
+ return window.location.href;
192
+ }
193
+ function getCurrentPath() {
194
+ if (!isBrowser()) return "unknown";
195
+ return window.location.pathname;
196
+ }
197
+ function getUserAgent() {
198
+ if (!isBrowser()) return void 0;
199
+ return navigator.userAgent;
200
+ }
201
+ function getReferrer() {
202
+ if (!isBrowser()) return void 0;
203
+ return document.referrer || void 0;
204
+ }
205
+
206
+ // src/queue/storage.ts
207
+ var OfflineStorage = class {
208
+ constructor(maxEvents = 100) {
209
+ this.storageKey = STORAGE_KEYS.EVENT_QUEUE;
210
+ this.maxEvents = maxEvents;
211
+ this.available = isLocalStorageAvailable();
212
+ }
213
+ isAvailable() {
214
+ return this.available;
215
+ }
216
+ store(event) {
217
+ if (!this.available) return false;
218
+ const logger = getLogger();
219
+ try {
220
+ const events = this.getAll();
221
+ const storedEvent = {
222
+ event,
223
+ storedAt: (/* @__PURE__ */ new Date()).toISOString(),
224
+ retries: 0
225
+ };
226
+ events.push(storedEvent);
227
+ while (events.length > this.maxEvents) {
228
+ events.shift();
229
+ }
230
+ localStorage.setItem(this.storageKey, JSON.stringify(events));
231
+ logger.log(`Event stored offline. Total stored: ${events.length}`);
232
+ return true;
233
+ } catch (error) {
234
+ logger.error("Failed to store event offline:", error);
235
+ return false;
236
+ }
237
+ }
238
+ storeMany(eventsToStore) {
239
+ if (!this.available || eventsToStore.length === 0) return 0;
240
+ const logger = getLogger();
241
+ let stored = 0;
242
+ try {
243
+ const events = this.getAll();
244
+ for (const event of eventsToStore) {
245
+ const storedEvent = {
246
+ event,
247
+ storedAt: (/* @__PURE__ */ new Date()).toISOString(),
248
+ retries: 0
249
+ };
250
+ events.push(storedEvent);
251
+ stored++;
252
+ }
253
+ while (events.length > this.maxEvents) {
254
+ events.shift();
255
+ }
256
+ localStorage.setItem(this.storageKey, JSON.stringify(events));
257
+ logger.log(`Stored ${stored} events offline. Total stored: ${events.length}`);
258
+ return stored;
259
+ } catch (error) {
260
+ logger.error("Failed to store events offline:", error);
261
+ return stored;
262
+ }
263
+ }
264
+ getAll() {
265
+ if (!this.available) return [];
266
+ try {
267
+ const data = localStorage.getItem(this.storageKey);
268
+ if (!data) return [];
269
+ return JSON.parse(data);
270
+ } catch (e) {
271
+ return [];
272
+ }
273
+ }
274
+ retrieveAll() {
275
+ if (!this.available) return [];
276
+ const logger = getLogger();
277
+ try {
278
+ const stored = this.getAll();
279
+ if (stored.length === 0) return [];
280
+ localStorage.removeItem(this.storageKey);
281
+ logger.log(`Retrieved ${stored.length} stored events`);
282
+ return stored.map((s) => s.event);
283
+ } catch (error) {
284
+ logger.error("Failed to retrieve stored events:", error);
285
+ return [];
286
+ }
287
+ }
288
+ count() {
289
+ return this.getAll().length;
290
+ }
291
+ clear() {
292
+ if (!this.available) return;
293
+ try {
294
+ localStorage.removeItem(this.storageKey);
295
+ } catch (e) {
296
+ }
297
+ }
298
+ };
299
+
300
+ // src/transport/sender.ts
301
+ async function sendBatch(apiUrl, token, events) {
302
+ const logger = getLogger();
303
+ const endpoint = `${apiUrl.replace(/\/$/, "")}/events`;
304
+ if (events.length === 0) {
305
+ return { success: true, count: 0 };
306
+ }
33
307
  const sendRequest = async () => {
34
308
  try {
309
+ const body = events.length === 1 ? formatEventForApi(events[0]) : { events: events.map(formatEventForApi) };
35
310
  const response = await fetch(endpoint, {
36
311
  method: "POST",
37
312
  headers: {
38
313
  "Content-Type": "application/json",
39
314
  "x-blinker-token": token
40
315
  },
41
- body: JSON.stringify({
42
- type: event.type,
43
- message: event.message,
44
- payload: event.payload || {},
45
- timestamp: event.timestamp,
46
- url: event.url,
47
- userAgent: event.userAgent
48
- })
316
+ body: JSON.stringify(body)
49
317
  });
50
318
  if (!response.ok) {
51
319
  const errorText = await response.text().catch(() => "Unknown error");
52
- if (debug) {
53
- console.error(`[Blinker] Failed to send event: ${response.status} - ${errorText}`);
54
- }
320
+ logger.error(`Failed to send events: ${response.status} - ${errorText}`);
55
321
  return { success: false, error: `HTTP ${response.status}: ${errorText}` };
56
322
  }
57
- if (debug) {
58
- console.log(`[Blinker] Event sent successfully:`, event.type);
59
- }
60
- return { success: true };
323
+ logger.log(`Events sent successfully: ${events.length} event(s)`);
324
+ return { success: true, count: events.length };
61
325
  } catch (error) {
62
326
  const errorMessage = error instanceof Error ? error.message : "Unknown error";
63
- if (debug) {
64
- console.error(`[Blinker] Error sending event:`, errorMessage);
65
- }
327
+ logger.error("Error sending events:", errorMessage);
66
328
  return { success: false, error: errorMessage };
67
329
  }
68
- };
69
- const result = await sendRequest();
70
- if (!result.success && typeof navigator !== "undefined" && !navigator.onLine) {
71
- if (debug) {
72
- console.log(`[Blinker] Offline, waiting for connection to retry...`);
73
- }
74
- const waitForOnline = new Promise((resolve) => {
75
- const timeout = setTimeout(() => resolve(false), 3e4);
76
- const onlineHandler = () => {
77
- clearTimeout(timeout);
78
- if (typeof window !== "undefined") {
79
- window.removeEventListener("online", onlineHandler);
80
- }
81
- resolve(true);
82
- };
83
- if (typeof window !== "undefined") {
84
- window.addEventListener("online", onlineHandler);
85
- } else {
86
- resolve(false);
87
- }
88
- });
89
- const isOnline = await waitForOnline;
90
- if (isOnline) {
91
- if (debug) {
92
- console.log(`[Blinker] Back online, retrying...`);
93
- }
94
- return sendRequest();
330
+ };
331
+ const result = await sendRequest();
332
+ if (!result.success && isBrowser() && !isOnline()) {
333
+ logger.log("Offline, waiting for connection to retry...");
334
+ const isBackOnline = await waitForOnline(TIMING.OFFLINE_RETRY_TIMEOUT);
335
+ if (isBackOnline) {
336
+ logger.log("Back online, retrying...");
337
+ return sendRequest();
338
+ }
339
+ }
340
+ return result;
341
+ }
342
+ function formatEventForApi(event) {
343
+ return {
344
+ type: event.type,
345
+ message: event.message,
346
+ payload: event.payload || {},
347
+ timestamp: event.timestamp,
348
+ url: event.url,
349
+ userAgent: event.userAgent,
350
+ sessionId: event.sessionId,
351
+ userId: event.userId,
352
+ userTraits: event.userTraits,
353
+ context: event.context,
354
+ count: event.count
355
+ };
356
+ }
357
+ function waitForOnline(timeout) {
358
+ return new Promise((resolve) => {
359
+ if (!isBrowser()) {
360
+ resolve(false);
361
+ return;
362
+ }
363
+ const timeoutId = setTimeout(() => resolve(false), timeout);
364
+ const onlineHandler = () => {
365
+ clearTimeout(timeoutId);
366
+ window.removeEventListener("online", onlineHandler);
367
+ resolve(true);
368
+ };
369
+ window.addEventListener("online", onlineHandler);
370
+ });
371
+ }
372
+
373
+ // src/queue/EventQueue.ts
374
+ var EventQueue = class {
375
+ constructor(token, config) {
376
+ this.queue = [];
377
+ this.flushTimer = null;
378
+ this.isFlushing = false;
379
+ this.handleOnline = () => {
380
+ const logger = getLogger();
381
+ logger.log("Back online, flushing stored events");
382
+ this.flush();
383
+ };
384
+ var _a, _b, _c, _d, _e, _f;
385
+ this.token = token;
386
+ this.config = {
387
+ endpoint: (_a = config == null ? void 0 : config.endpoint) != null ? _a : DEFAULTS.endpoint,
388
+ enableBatching: (_b = config == null ? void 0 : config.enableBatching) != null ? _b : DEFAULTS.enableBatching,
389
+ batchSize: (_c = config == null ? void 0 : config.batchSize) != null ? _c : DEFAULTS.batchSize,
390
+ flushInterval: Math.max(
391
+ TIMING.MIN_FLUSH_INTERVAL,
392
+ Math.min((_d = config == null ? void 0 : config.flushInterval) != null ? _d : DEFAULTS.flushInterval, TIMING.MAX_FLUSH_INTERVAL)
393
+ ),
394
+ enableOfflineStorage: (_e = config == null ? void 0 : config.enableOfflineStorage) != null ? _e : DEFAULTS.enableOfflineStorage,
395
+ maxStoredEvents: (_f = config == null ? void 0 : config.maxStoredEvents) != null ? _f : DEFAULTS.maxStoredEvents,
396
+ onError: config == null ? void 0 : config.onError
397
+ };
398
+ this.storage = new OfflineStorage(this.config.maxStoredEvents);
399
+ if (this.config.enableBatching) {
400
+ this.startFlushTimer();
401
+ }
402
+ if (isBrowser() && this.config.enableOfflineStorage) {
403
+ window.addEventListener("online", this.handleOnline);
404
+ }
405
+ }
406
+ async add(event) {
407
+ const logger = getLogger();
408
+ if (!this.config.enableBatching) {
409
+ return this.sendImmediately([event]);
410
+ }
411
+ this.queue.push(event);
412
+ logger.log(`Event queued. Queue size: ${this.queue.length}`);
413
+ if (this.queue.length >= this.config.batchSize) {
414
+ return this.flush();
415
+ }
416
+ return { success: true };
417
+ }
418
+ async flush() {
419
+ const logger = getLogger();
420
+ if (this.isFlushing) {
421
+ logger.log("Flush already in progress, skipping");
422
+ return { success: true };
423
+ }
424
+ const events = [...this.queue];
425
+ this.queue = [];
426
+ if (this.config.enableOfflineStorage && isOnline()) {
427
+ const storedEvents = this.storage.retrieveAll();
428
+ if (storedEvents.length > 0) {
429
+ events.unshift(...storedEvents);
430
+ logger.log(`Including ${storedEvents.length} stored offline events`);
431
+ }
432
+ }
433
+ if (events.length === 0) {
434
+ return { success: true, count: 0 };
435
+ }
436
+ this.isFlushing = true;
437
+ try {
438
+ const result = await this.sendImmediately(events);
439
+ if (!result.success && this.config.enableOfflineStorage && !isOnline()) {
440
+ logger.log("Send failed while offline, storing events");
441
+ this.storage.storeMany(events);
442
+ }
443
+ return result;
444
+ } finally {
445
+ this.isFlushing = false;
446
+ }
447
+ }
448
+ async sendImmediately(events) {
449
+ const logger = getLogger();
450
+ if (!isOnline() && this.config.enableOfflineStorage) {
451
+ logger.log("Offline, storing events for later");
452
+ const stored = this.storage.storeMany(events);
453
+ return { success: true, count: stored };
454
+ }
455
+ const result = await sendBatch(this.config.endpoint, this.token, events);
456
+ if (!result.success && this.config.onError) {
457
+ this.config.onError(result.error || "Unknown error sending events");
458
+ }
459
+ return result;
460
+ }
461
+ getStats() {
462
+ const queueSize = this.queue.length;
463
+ const storedSize = this.storage.count();
464
+ return {
465
+ queueSize,
466
+ storedSize,
467
+ totalPending: queueSize + storedSize
468
+ };
469
+ }
470
+ size() {
471
+ return this.queue.length;
472
+ }
473
+ startFlushTimer() {
474
+ if (this.flushTimer) return;
475
+ this.flushTimer = setInterval(() => {
476
+ if (this.queue.length > 0) {
477
+ this.flush();
478
+ }
479
+ }, this.config.flushInterval);
480
+ }
481
+ stopFlushTimer() {
482
+ if (this.flushTimer) {
483
+ clearInterval(this.flushTimer);
484
+ this.flushTimer = null;
485
+ }
486
+ }
487
+ destroy() {
488
+ this.stopFlushTimer();
489
+ if (isBrowser()) {
490
+ window.removeEventListener("online", this.handleOnline);
491
+ }
492
+ if (this.queue.length > 0 && isOnline()) {
493
+ this.flush();
494
+ } else if (this.queue.length > 0 && this.config.enableOfflineStorage) {
495
+ this.storage.storeMany(this.queue);
496
+ }
497
+ this.queue = [];
498
+ }
499
+ };
500
+
501
+ // src/utils/hash.ts
502
+ function simpleHash(str) {
503
+ let hash = 5381;
504
+ for (let i = 0; i < str.length; i++) {
505
+ hash = (hash << 5) + hash ^ str.charCodeAt(i);
506
+ }
507
+ return (hash >>> 0).toString(16);
508
+ }
509
+ function generateErrorFingerprint(message, stack) {
510
+ let input = message;
511
+ if (stack) {
512
+ const stackLines = stack.split("\n").slice(1, 4);
513
+ const cleanedStack = stackLines.map((line) => line.replace(/:\d+:\d+\)?$/, "").trim()).join("|");
514
+ input += "|" + cleanedStack;
515
+ }
516
+ return simpleHash(input);
517
+ }
518
+ function generateUniqueId() {
519
+ const timestamp = Date.now().toString(36);
520
+ const randomPart = Math.random().toString(36).substring(2, 10);
521
+ return `${timestamp}-${randomPart}`;
522
+ }
523
+
524
+ // src/context/SessionManager.ts
525
+ var SessionManager = class {
526
+ constructor() {
527
+ this.session = null;
528
+ this.storageKey = STORAGE_KEYS.SESSION;
529
+ this.storageAvailable = isSessionStorageAvailable();
530
+ this.initSession();
531
+ }
532
+ initSession() {
533
+ const logger = getLogger();
534
+ if (this.storageAvailable) {
535
+ try {
536
+ const stored = sessionStorage.getItem(this.storageKey);
537
+ if (stored) {
538
+ this.session = JSON.parse(stored);
539
+ logger.log("Session restored:", this.session.id);
540
+ return;
541
+ }
542
+ } catch (e) {
543
+ }
544
+ }
545
+ this.session = {
546
+ id: generateUniqueId(),
547
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
548
+ pageViews: 0,
549
+ lastActivityAt: (/* @__PURE__ */ new Date()).toISOString()
550
+ };
551
+ this.persist();
552
+ logger.log("New session created:", this.session.id);
553
+ }
554
+ getSessionId() {
555
+ var _a, _b;
556
+ return (_b = (_a = this.session) == null ? void 0 : _a.id) != null ? _b : generateUniqueId();
557
+ }
558
+ getSession() {
559
+ if (!this.session) {
560
+ this.initSession();
561
+ }
562
+ return { ...this.session };
563
+ }
564
+ recordPageView() {
565
+ if (this.session) {
566
+ this.session.pageViews++;
567
+ this.session.lastActivityAt = (/* @__PURE__ */ new Date()).toISOString();
568
+ this.persist();
569
+ }
570
+ }
571
+ touch() {
572
+ if (this.session) {
573
+ this.session.lastActivityAt = (/* @__PURE__ */ new Date()).toISOString();
574
+ this.persist();
575
+ }
576
+ }
577
+ getDuration() {
578
+ if (!this.session) return 0;
579
+ const start = new Date(this.session.startedAt).getTime();
580
+ return Date.now() - start;
581
+ }
582
+ persist() {
583
+ if (!this.storageAvailable || !this.session) return;
584
+ try {
585
+ sessionStorage.setItem(this.storageKey, JSON.stringify(this.session));
586
+ } catch (e) {
587
+ }
588
+ }
589
+ endSession() {
590
+ if (this.storageAvailable) {
591
+ try {
592
+ sessionStorage.removeItem(this.storageKey);
593
+ } catch (e) {
594
+ }
595
+ }
596
+ this.session = null;
597
+ }
598
+ };
599
+
600
+ // src/context/UserContext.ts
601
+ var UserContext = class {
602
+ constructor(sessionManager) {
603
+ this.user = null;
604
+ this.customContext = {};
605
+ this.sessionManager = sessionManager;
606
+ }
607
+ identify(userId, traits) {
608
+ const logger = getLogger();
609
+ this.user = {
610
+ userId,
611
+ traits: traits ? { ...traits } : void 0,
612
+ identifiedAt: (/* @__PURE__ */ new Date()).toISOString()
613
+ };
614
+ logger.log("User identified:", userId);
615
+ }
616
+ getUserId() {
617
+ var _a;
618
+ return (_a = this.user) == null ? void 0 : _a.userId;
619
+ }
620
+ getUserTraits() {
621
+ var _a;
622
+ return ((_a = this.user) == null ? void 0 : _a.traits) ? { ...this.user.traits } : void 0;
623
+ }
624
+ isIdentified() {
625
+ return this.user !== null;
626
+ }
627
+ setContext(key, value) {
628
+ const logger = getLogger();
629
+ this.customContext[key] = value;
630
+ logger.log("Context set:", key);
631
+ }
632
+ getContextValue(key) {
633
+ return this.customContext[key];
634
+ }
635
+ getCustomContext() {
636
+ return { ...this.customContext };
637
+ }
638
+ getEventContext() {
639
+ var _a, _b;
640
+ return {
641
+ sessionId: this.sessionManager.getSessionId(),
642
+ userId: (_a = this.user) == null ? void 0 : _a.userId,
643
+ userTraits: ((_b = this.user) == null ? void 0 : _b.traits) ? { ...this.user.traits } : void 0,
644
+ custom: { ...this.customContext }
645
+ };
646
+ }
647
+ clearIdentity() {
648
+ const logger = getLogger();
649
+ this.user = null;
650
+ logger.log("User identity cleared");
651
+ }
652
+ clearAll() {
653
+ const logger = getLogger();
654
+ this.user = null;
655
+ this.customContext = {};
656
+ logger.log("All context cleared");
657
+ }
658
+ };
659
+
660
+ // src/sampling/RateLimiter.ts
661
+ var MINUTE_MS = 60 * 1e3;
662
+ var RateLimiter = class {
663
+ constructor(maxEventsPerMinute) {
664
+ this.maxPerMinute = maxEventsPerMinute != null ? maxEventsPerMinute : DEFAULTS.maxEventsPerMinute;
665
+ this.state = {
666
+ count: 0,
667
+ windowStart: Date.now(),
668
+ dropped: 0
669
+ };
670
+ }
671
+ allow() {
672
+ const logger = getLogger();
673
+ if (this.maxPerMinute === 0) {
674
+ return true;
675
+ }
676
+ const now = Date.now();
677
+ if (now - this.state.windowStart >= MINUTE_MS) {
678
+ if (this.state.dropped > 0) {
679
+ logger.warn(`Rate limit: ${this.state.dropped} events dropped in last minute`);
680
+ }
681
+ this.state = {
682
+ count: 0,
683
+ windowStart: now,
684
+ dropped: 0
685
+ };
686
+ }
687
+ if (this.state.count < this.maxPerMinute) {
688
+ this.state.count++;
689
+ return true;
690
+ }
691
+ this.state.dropped++;
692
+ if (this.state.dropped === 1) {
693
+ logger.warn(`Rate limit reached: ${this.maxPerMinute} events/minute`);
694
+ }
695
+ return false;
696
+ }
697
+ getState() {
698
+ return { ...this.state };
699
+ }
700
+ getRemaining() {
701
+ if (this.maxPerMinute === 0) return Infinity;
702
+ if (Date.now() - this.state.windowStart >= MINUTE_MS) {
703
+ return this.maxPerMinute;
704
+ }
705
+ return Math.max(0, this.maxPerMinute - this.state.count);
706
+ }
707
+ reset() {
708
+ this.state = {
709
+ count: 0,
710
+ windowStart: Date.now(),
711
+ dropped: 0
712
+ };
713
+ }
714
+ setLimit(maxEventsPerMinute) {
715
+ this.maxPerMinute = maxEventsPerMinute;
716
+ }
717
+ };
718
+
719
+ // src/sampling/Sampler.ts
720
+ var Sampler = class {
721
+ constructor(sampleRate) {
722
+ this.sampled = 0;
723
+ this.dropped = 0;
724
+ this.sampleRate = Math.max(0, Math.min(1, sampleRate != null ? sampleRate : DEFAULTS.sampleRate));
725
+ }
726
+ shouldSample(isError = false) {
727
+ const logger = getLogger();
728
+ if (isError) {
729
+ this.sampled++;
730
+ return true;
731
+ }
732
+ if (this.sampleRate >= 1) {
733
+ this.sampled++;
734
+ return true;
735
+ }
736
+ if (this.sampleRate <= 0) {
737
+ this.dropped++;
738
+ return false;
739
+ }
740
+ if (Math.random() < this.sampleRate) {
741
+ this.sampled++;
742
+ return true;
743
+ }
744
+ this.dropped++;
745
+ logger.log("Event sampled out");
746
+ return false;
747
+ }
748
+ getStats() {
749
+ return {
750
+ sampled: this.sampled,
751
+ dropped: this.dropped,
752
+ rate: this.sampleRate
753
+ };
754
+ }
755
+ setRate(rate) {
756
+ this.sampleRate = Math.max(0, Math.min(1, rate));
757
+ }
758
+ getRate() {
759
+ return this.sampleRate;
760
+ }
761
+ resetStats() {
762
+ this.sampled = 0;
763
+ this.dropped = 0;
764
+ }
765
+ };
766
+
767
+ // src/capture/deduplication.ts
768
+ var Deduplicator = class {
769
+ constructor(enabled, windowMs) {
770
+ this.entries = /* @__PURE__ */ new Map();
771
+ this.cleanupTimer = null;
772
+ this.enabled = enabled != null ? enabled : DEFAULTS.enableDeduplication;
773
+ this.windowMs = windowMs != null ? windowMs : DEFAULTS.deduplicationWindow;
774
+ if (this.enabled) {
775
+ this.startCleanup();
776
+ }
777
+ }
778
+ check(message, stack) {
779
+ const fingerprint = generateErrorFingerprint(message, stack);
780
+ if (!this.enabled) {
781
+ return {
782
+ shouldSend: true,
783
+ fingerprint,
784
+ count: 1,
785
+ isDuplicate: false
786
+ };
787
+ }
788
+ const logger = getLogger();
789
+ const now = Date.now();
790
+ const existing = this.entries.get(fingerprint);
791
+ if (existing) {
792
+ if (now - existing.firstSeen < this.windowMs) {
793
+ existing.count++;
794
+ existing.lastSeen = now;
795
+ logger.log(`Duplicate error detected (count: ${existing.count}):`, message.substring(0, 50));
796
+ return {
797
+ shouldSend: false,
798
+ fingerprint,
799
+ count: existing.count,
800
+ isDuplicate: true
801
+ };
802
+ }
803
+ this.entries.delete(fingerprint);
804
+ }
805
+ this.entries.set(fingerprint, {
806
+ fingerprint,
807
+ firstSeen: now,
808
+ count: 1,
809
+ lastSeen: now
810
+ });
811
+ return {
812
+ shouldSend: true,
813
+ fingerprint,
814
+ count: 1,
815
+ isDuplicate: false
816
+ };
817
+ }
818
+ getCount(fingerprint) {
819
+ var _a, _b;
820
+ return (_b = (_a = this.entries.get(fingerprint)) == null ? void 0 : _a.count) != null ? _b : 1;
821
+ }
822
+ flush() {
823
+ const duplicates = Array.from(this.entries.values()).filter((e) => e.count > 1);
824
+ this.entries.clear();
825
+ return duplicates;
826
+ }
827
+ startCleanup() {
828
+ this.cleanupTimer = setInterval(() => {
829
+ this.cleanup();
830
+ }, this.windowMs);
831
+ }
832
+ cleanup() {
833
+ const now = Date.now();
834
+ const logger = getLogger();
835
+ let removed = 0;
836
+ for (const [fingerprint, entry] of this.entries) {
837
+ if (now - entry.firstSeen >= this.windowMs) {
838
+ this.entries.delete(fingerprint);
839
+ removed++;
840
+ }
841
+ }
842
+ if (removed > 0) {
843
+ logger.log(`Deduplication cleanup: removed ${removed} expired entries`);
844
+ }
845
+ }
846
+ destroy() {
847
+ if (this.cleanupTimer) {
848
+ clearInterval(this.cleanupTimer);
849
+ this.cleanupTimer = null;
850
+ }
851
+ this.entries.clear();
852
+ }
853
+ getStats() {
854
+ return {
855
+ entries: this.entries.size,
856
+ enabled: this.enabled,
857
+ windowMs: this.windowMs
858
+ };
859
+ }
860
+ };
861
+
862
+ // src/capture/errorHandler.ts
863
+ var originalOnError = null;
864
+ var originalOnUnhandledRejection = null;
865
+ var isSetup = false;
866
+ function setupErrorHandlers(callback, options = {}) {
867
+ const { captureErrors = true, captureRejections = true } = options;
868
+ const logger = getLogger();
869
+ if (isSetup) {
870
+ logger.warn("Error handlers already set up");
871
+ return;
872
+ }
873
+ if (!isBrowser()) {
874
+ logger.log("Not in browser environment, skipping error handlers");
875
+ return;
876
+ }
877
+ if (captureErrors) {
878
+ originalOnError = window.onerror;
879
+ window.onerror = function(message, source, lineno, colno, error) {
880
+ const errorMessage = typeof message === "string" ? message : message.type || "Unknown error";
881
+ const payload = {
882
+ source,
883
+ lineno,
884
+ colno,
885
+ stack: error == null ? void 0 : error.stack,
886
+ errorType: error == null ? void 0 : error.name
887
+ };
888
+ logger.log("Captured error:", errorMessage);
889
+ callback("error", errorMessage, payload);
890
+ if (typeof originalOnError === "function") {
891
+ return originalOnError.call(window, message, source, lineno, colno, error);
892
+ }
893
+ return false;
894
+ };
895
+ }
896
+ if (captureRejections) {
897
+ originalOnUnhandledRejection = window.onunhandledrejection;
898
+ window.onunhandledrejection = function(event) {
899
+ let message = "Unhandled Rejection";
900
+ const payload = {};
901
+ const reason = event.reason;
902
+ if (reason instanceof Error) {
903
+ message = reason.message || message;
904
+ payload.stack = reason.stack;
905
+ payload.errorType = reason.name;
906
+ } else if (typeof reason === "string") {
907
+ message = reason;
908
+ } else if (reason !== void 0 && reason !== null) {
909
+ try {
910
+ message = JSON.stringify(reason);
911
+ } catch (e) {
912
+ message = String(reason);
913
+ }
914
+ }
915
+ logger.log("Captured unhandled rejection:", message);
916
+ callback("error", message, payload);
917
+ if (typeof originalOnUnhandledRejection === "function") {
918
+ originalOnUnhandledRejection.call(window, event);
919
+ }
920
+ };
921
+ }
922
+ isSetup = true;
923
+ logger.log("Error handlers set up");
924
+ }
925
+ function teardownErrorHandlers() {
926
+ const logger = getLogger();
927
+ if (!isBrowser()) {
928
+ return;
929
+ }
930
+ if (originalOnError !== void 0) {
931
+ window.onerror = originalOnError;
932
+ }
933
+ if (originalOnUnhandledRejection !== void 0) {
934
+ window.onunhandledrejection = originalOnUnhandledRejection;
935
+ }
936
+ originalOnError = null;
937
+ originalOnUnhandledRejection = null;
938
+ isSetup = false;
939
+ logger.log("Error handlers torn down");
940
+ }
941
+
942
+ // src/widget/types.ts
943
+ var DEFAULT_WIDGET_CONFIG = {
944
+ enabled: false,
945
+ theme: {
946
+ primary: "#6366f1",
947
+ background: "#ffffff",
948
+ text: "#1f2937",
949
+ accent: "#10b981"
950
+ },
951
+ messages: {
952
+ greeting: "Opa! Algo n\xE3o saiu como esperado.",
953
+ subtext: "Pode nos ajudar a entender o que aconteceu?",
954
+ thankYou: "Valeu! J\xE1 estamos olhando isso.",
955
+ buttonSend: "Enviar",
956
+ buttonSkip: "Agora n\xE3o"
957
+ },
958
+ position: "bottom-right",
959
+ delay: 2e3,
960
+ maxShowsPerSession: 2,
961
+ cooldownMinutes: 30
962
+ };
963
+
964
+ // src/widget/Avatar.ts
965
+ var Avatar = class {
966
+ constructor(theme, onClick) {
967
+ this.element = null;
968
+ this.pupilLeft = null;
969
+ this.pupilRight = null;
970
+ this.mouseTrackingEnabled = true;
971
+ this.theme = theme;
972
+ this.onClick = onClick;
973
+ this.handleMouseMove = this.handleMouseMove.bind(this);
974
+ }
975
+ create() {
976
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
977
+ svg.setAttribute("viewBox", "0 0 100 100");
978
+ svg.setAttribute("class", "blinker-avatar");
979
+ svg.innerHTML = this.getSVGContent();
980
+ svg.addEventListener("click", this.onClick);
981
+ svg.addEventListener("mouseenter", () => this.setState("hover"));
982
+ svg.addEventListener("mouseleave", () => this.setState("idle"));
983
+ this.element = svg;
984
+ this.pupilLeft = svg.querySelector(".blinker-pupil-left");
985
+ this.pupilRight = svg.querySelector(".blinker-pupil-right");
986
+ document.addEventListener("mousemove", this.handleMouseMove);
987
+ return svg;
988
+ }
989
+ getSVGContent() {
990
+ return `
991
+ <defs>
992
+ <linearGradient id="blinker-body-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
993
+ <stop offset="0%" style="stop-color:${this.theme.primary};stop-opacity:1" />
994
+ <stop offset="100%" style="stop-color:${this.adjustColor(this.theme.primary, -30)};stop-opacity:1" />
995
+ </linearGradient>
996
+ <filter id="blinker-shadow" x="-20%" y="-20%" width="140%" height="140%">
997
+ <feDropShadow dx="0" dy="4" stdDeviation="4" flood-opacity="0.2"/>
998
+ </filter>
999
+ </defs>
1000
+
1001
+ <!-- Glow effect -->
1002
+ <ellipse class="blinker-avatar-glow" cx="50" cy="85" rx="25" ry="8" />
1003
+
1004
+ <!-- Body -->
1005
+ <g class="blinker-avatar-body" filter="url(#blinker-shadow)">
1006
+ <!-- Main body shape - rounded rectangle with personality -->
1007
+ <path d="
1008
+ M 25 30
1009
+ Q 25 15, 50 15
1010
+ Q 75 15, 75 30
1011
+ L 75 65
1012
+ Q 75 85, 50 85
1013
+ Q 25 85, 25 65
1014
+ Z
1015
+ " fill="url(#blinker-body-gradient)" />
1016
+
1017
+ <!-- Antenna/Top detail -->
1018
+ <circle cx="50" cy="12" r="4" fill="${this.theme.primary}" />
1019
+ <line x1="50" y1="16" x2="50" y2="22" stroke="${this.theme.primary}" stroke-width="3" stroke-linecap="round" />
1020
+ </g>
1021
+
1022
+ <!-- Face -->
1023
+ <g class="blinker-avatar-face">
1024
+ <!-- Left eye container -->
1025
+ <ellipse class="blinker-avatar-eye blinker-avatar-eye-left" cx="38" cy="42" rx="10" ry="11" />
1026
+ <!-- Right eye container -->
1027
+ <ellipse class="blinker-avatar-eye blinker-avatar-eye-right" cx="62" cy="42" rx="10" ry="11" />
1028
+
1029
+ <!-- Left pupil -->
1030
+ <circle class="blinker-avatar-pupil blinker-pupil-left" cx="38" cy="43" r="5" />
1031
+ <!-- Right pupil -->
1032
+ <circle class="blinker-avatar-pupil blinker-pupil-right" cx="62" cy="43" r="5" />
1033
+
1034
+ <!-- Eye shine -->
1035
+ <circle cx="35" cy="40" r="2" fill="white" opacity="0.8" />
1036
+ <circle cx="59" cy="40" r="2" fill="white" opacity="0.8" />
1037
+
1038
+ <!-- Mouth -->
1039
+ <path class="blinker-avatar-mouth" d="M 40 60 Q 50 68, 60 60" />
1040
+ </g>
1041
+
1042
+ <!-- Decorative elements -->
1043
+ <circle cx="30" cy="55" r="3" fill="${this.theme.primary}" opacity="0.3" />
1044
+ <circle cx="70" cy="55" r="3" fill="${this.theme.primary}" opacity="0.3" />
1045
+ `;
1046
+ }
1047
+ handleMouseMove(e) {
1048
+ if (!this.mouseTrackingEnabled || !this.element || !this.pupilLeft || !this.pupilRight) return;
1049
+ const rect = this.element.getBoundingClientRect();
1050
+ const centerX = rect.left + rect.width / 2;
1051
+ const centerY = rect.top + rect.height / 2;
1052
+ const deltaX = (e.clientX - centerX) / 50;
1053
+ const deltaY = (e.clientY - centerY) / 50;
1054
+ const maxOffset = 3;
1055
+ const offsetX = Math.max(-maxOffset, Math.min(maxOffset, deltaX));
1056
+ const offsetY = Math.max(-maxOffset, Math.min(maxOffset, deltaY));
1057
+ this.pupilLeft.setAttribute("transform", `translate(${offsetX}, ${offsetY})`);
1058
+ this.pupilRight.setAttribute("transform", `translate(${offsetX}, ${offsetY})`);
1059
+ }
1060
+ setState(state) {
1061
+ if (!this.element) return;
1062
+ this.element.classList.remove("idle", "hover", "minimized", "talking");
1063
+ this.element.classList.add(state);
1064
+ }
1065
+ setMinimized(minimized) {
1066
+ if (!this.element) return;
1067
+ if (minimized) {
1068
+ this.element.classList.add("minimized");
1069
+ this.mouseTrackingEnabled = false;
1070
+ } else {
1071
+ this.element.classList.remove("minimized");
1072
+ this.mouseTrackingEnabled = true;
1073
+ }
1074
+ }
1075
+ updateTheme(theme) {
1076
+ this.theme = theme;
1077
+ if (this.element) {
1078
+ this.element.innerHTML = this.getSVGContent();
1079
+ this.pupilLeft = this.element.querySelector(".blinker-pupil-left");
1080
+ this.pupilRight = this.element.querySelector(".blinker-pupil-right");
1081
+ }
1082
+ }
1083
+ adjustColor(hex, amount) {
1084
+ const num = parseInt(hex.replace("#", ""), 16);
1085
+ const r = Math.max(0, Math.min(255, (num >> 16) + amount));
1086
+ const g = Math.max(0, Math.min(255, (num >> 8 & 255) + amount));
1087
+ const b = Math.max(0, Math.min(255, (num & 255) + amount));
1088
+ return `#${(r << 16 | g << 8 | b).toString(16).padStart(6, "0")}`;
1089
+ }
1090
+ getElement() {
1091
+ return this.element;
1092
+ }
1093
+ destroy() {
1094
+ document.removeEventListener("mousemove", this.handleMouseMove);
1095
+ if (this.element) {
1096
+ this.element.removeEventListener("click", this.onClick);
1097
+ this.element.remove();
1098
+ this.element = null;
1099
+ }
1100
+ }
1101
+ };
1102
+
1103
+ // src/widget/Dialog.ts
1104
+ var Dialog = class {
1105
+ constructor(config, onSubmit, onClose) {
1106
+ this.overlay = null;
1107
+ this.dialog = null;
1108
+ this.questions = [];
1109
+ this.answers = {};
1110
+ this.errorId = "";
1111
+ this.state = "questions";
1112
+ this.config = config;
1113
+ this.onSubmit = onSubmit;
1114
+ this.onClose = onClose;
1115
+ }
1116
+ open(errorId, questions) {
1117
+ this.errorId = errorId;
1118
+ this.questions = questions;
1119
+ this.answers = {};
1120
+ this.state = "questions";
1121
+ this.render();
1122
+ }
1123
+ close() {
1124
+ if (this.overlay) {
1125
+ this.overlay.remove();
1126
+ this.overlay = null;
1127
+ }
1128
+ if (this.dialog) {
1129
+ this.dialog.remove();
1130
+ this.dialog = null;
1131
+ }
1132
+ this.onClose();
1133
+ }
1134
+ render() {
1135
+ this.close();
1136
+ this.overlay = document.createElement("div");
1137
+ this.overlay.className = "blinker-dialog-overlay";
1138
+ this.overlay.addEventListener("click", () => this.close());
1139
+ this.dialog = document.createElement("div");
1140
+ this.dialog.className = `blinker-dialog ${this.config.position}`;
1141
+ this.dialog.innerHTML = this.state === "questions" ? this.getQuestionsHTML() : this.getThankYouHTML();
1142
+ document.body.appendChild(this.overlay);
1143
+ document.body.appendChild(this.dialog);
1144
+ this.attachEventListeners();
1145
+ }
1146
+ getQuestionsHTML() {
1147
+ const { messages } = this.config;
1148
+ return `
1149
+ <div class="blinker-dialog-header">
1150
+ <svg class="blinker-dialog-avatar" viewBox="0 0 100 100">
1151
+ <defs>
1152
+ <linearGradient id="dialog-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
1153
+ <stop offset="0%" style="stop-color:${this.config.theme.primary}" />
1154
+ <stop offset="100%" style="stop-color:${this.adjustColor(this.config.theme.primary, -30)}" />
1155
+ </linearGradient>
1156
+ </defs>
1157
+ <path d="M 25 30 Q 25 15, 50 15 Q 75 15, 75 30 L 75 65 Q 75 85, 50 85 Q 25 85, 25 65 Z" fill="url(#dialog-gradient)" />
1158
+ <ellipse cx="38" cy="42" rx="10" ry="11" fill="${this.config.theme.background}" />
1159
+ <ellipse cx="62" cy="42" rx="10" ry="11" fill="${this.config.theme.background}" />
1160
+ <circle cx="38" cy="43" r="5" fill="${this.config.theme.text}" />
1161
+ <circle cx="62" cy="43" r="5" fill="${this.config.theme.text}" />
1162
+ <path d="M 40 60 Q 50 68, 60 60" stroke="${this.config.theme.background}" stroke-width="2" fill="none" stroke-linecap="round" />
1163
+ </svg>
1164
+ <div class="blinker-dialog-title">
1165
+ <p class="blinker-dialog-greeting">${messages.greeting}</p>
1166
+ <p class="blinker-dialog-subtext">${messages.subtext}</p>
1167
+ </div>
1168
+ <button class="blinker-dialog-close" aria-label="Fechar">
1169
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1170
+ <path d="M18 6L6 18M6 6l12 12" />
1171
+ </svg>
1172
+ </button>
1173
+ </div>
1174
+ <div class="blinker-dialog-body">
1175
+ ${this.questions.map((q) => this.getQuestionHTML(q)).join("")}
1176
+ </div>
1177
+ <div class="blinker-dialog-footer">
1178
+ <button class="blinker-btn blinker-btn-secondary" data-action="skip">
1179
+ ${messages.buttonSkip}
1180
+ </button>
1181
+ <button class="blinker-btn blinker-btn-primary" data-action="submit">
1182
+ ${messages.buttonSend}
1183
+ </button>
1184
+ </div>
1185
+ `;
1186
+ }
1187
+ getQuestionHTML(question) {
1188
+ var _a;
1189
+ const required = question.required ? " *" : "";
1190
+ switch (question.type) {
1191
+ case "text":
1192
+ return `
1193
+ <div class="blinker-question" data-question-id="${question.id}">
1194
+ <label class="blinker-question-label">${question.text}${required}</label>
1195
+ <textarea
1196
+ class="blinker-question-input blinker-question-textarea"
1197
+ placeholder="Digite sua resposta..."
1198
+ data-question-id="${question.id}"
1199
+ ></textarea>
1200
+ </div>
1201
+ `;
1202
+ case "select":
1203
+ return `
1204
+ <div class="blinker-question" data-question-id="${question.id}">
1205
+ <label class="blinker-question-label">${question.text}${required}</label>
1206
+ <select class="blinker-question-input blinker-question-select" data-question-id="${question.id}">
1207
+ <option value="">Selecione...</option>
1208
+ ${(_a = question.options) == null ? void 0 : _a.map((opt) => `<option value="${opt}">${opt}</option>`).join("")}
1209
+ </select>
1210
+ </div>
1211
+ `;
1212
+ case "boolean":
1213
+ return `
1214
+ <div class="blinker-question" data-question-id="${question.id}">
1215
+ <label class="blinker-question-label">${question.text}${required}</label>
1216
+ <div class="blinker-question-boolean">
1217
+ <button type="button" data-question-id="${question.id}" data-value="true">Sim</button>
1218
+ <button type="button" data-question-id="${question.id}" data-value="false">N\xE3o</button>
1219
+ </div>
1220
+ </div>
1221
+ `;
1222
+ default:
1223
+ return "";
1224
+ }
1225
+ }
1226
+ getThankYouHTML() {
1227
+ return `
1228
+ <div class="blinker-thank-you">
1229
+ <svg class="blinker-thank-you-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1230
+ <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
1231
+ <polyline points="22 4 12 14.01 9 11.01" />
1232
+ </svg>
1233
+ <p class="blinker-thank-you-text">${this.config.messages.thankYou}</p>
1234
+ </div>
1235
+ `;
1236
+ }
1237
+ attachEventListeners() {
1238
+ if (!this.dialog) return;
1239
+ const closeBtn = this.dialog.querySelector(".blinker-dialog-close");
1240
+ closeBtn == null ? void 0 : closeBtn.addEventListener("click", () => this.close());
1241
+ const submitBtn = this.dialog.querySelector('[data-action="submit"]');
1242
+ submitBtn == null ? void 0 : submitBtn.addEventListener("click", () => this.handleSubmit());
1243
+ const skipBtn = this.dialog.querySelector('[data-action="skip"]');
1244
+ skipBtn == null ? void 0 : skipBtn.addEventListener("click", () => this.close());
1245
+ const textareas = this.dialog.querySelectorAll("textarea");
1246
+ textareas.forEach((textarea) => {
1247
+ textarea.addEventListener("input", (e) => {
1248
+ const target = e.target;
1249
+ const questionId = target.dataset.questionId;
1250
+ if (questionId) {
1251
+ this.answers[questionId] = target.value;
1252
+ }
1253
+ });
1254
+ });
1255
+ const selects = this.dialog.querySelectorAll("select");
1256
+ selects.forEach((select) => {
1257
+ select.addEventListener("change", (e) => {
1258
+ const target = e.target;
1259
+ const questionId = target.dataset.questionId;
1260
+ if (questionId) {
1261
+ this.answers[questionId] = target.value;
1262
+ }
1263
+ });
1264
+ });
1265
+ const booleanBtns = this.dialog.querySelectorAll(".blinker-question-boolean button");
1266
+ booleanBtns.forEach((btn) => {
1267
+ btn.addEventListener("click", (e) => {
1268
+ const target = e.target;
1269
+ const questionId = target.dataset.questionId;
1270
+ const value = target.dataset.value === "true";
1271
+ if (questionId) {
1272
+ this.answers[questionId] = value;
1273
+ const container = target.parentElement;
1274
+ container == null ? void 0 : container.querySelectorAll("button").forEach((b) => b.classList.remove("selected"));
1275
+ target.classList.add("selected");
1276
+ }
1277
+ });
1278
+ });
1279
+ }
1280
+ handleSubmit() {
1281
+ var _a;
1282
+ const requiredQuestions = this.questions.filter((q) => q.required);
1283
+ const missingRequired = requiredQuestions.some((q) => {
1284
+ const answer = this.answers[q.id];
1285
+ return answer === void 0 || answer === "";
1286
+ });
1287
+ if (missingRequired) {
1288
+ const firstRequired = requiredQuestions.find((q) => !this.answers[q.id]);
1289
+ if (firstRequired) {
1290
+ const input = (_a = this.dialog) == null ? void 0 : _a.querySelector(`[data-question-id="${firstRequired.id}"]`);
1291
+ if (input instanceof HTMLElement) {
1292
+ input.focus();
1293
+ input.style.borderColor = "#ef4444";
1294
+ setTimeout(() => {
1295
+ input.style.borderColor = "";
1296
+ }, 2e3);
1297
+ }
1298
+ }
1299
+ return;
1300
+ }
1301
+ const feedback = {
1302
+ errorId: this.errorId,
1303
+ answers: { ...this.answers },
1304
+ submittedAt: (/* @__PURE__ */ new Date()).toISOString()
1305
+ };
1306
+ this.onSubmit(feedback);
1307
+ this.state = "thankyou";
1308
+ this.render();
1309
+ setTimeout(() => {
1310
+ this.close();
1311
+ }, 2500);
1312
+ }
1313
+ updateConfig(config) {
1314
+ this.config = config;
1315
+ }
1316
+ adjustColor(hex, amount) {
1317
+ const num = parseInt(hex.replace("#", ""), 16);
1318
+ const r = Math.max(0, Math.min(255, (num >> 16) + amount));
1319
+ const g = Math.max(0, Math.min(255, (num >> 8 & 255) + amount));
1320
+ const b = Math.max(0, Math.min(255, (num & 255) + amount));
1321
+ return `#${(r << 16 | g << 8 | b).toString(16).padStart(6, "0")}`;
1322
+ }
1323
+ isOpen() {
1324
+ return this.dialog !== null;
1325
+ }
1326
+ };
1327
+
1328
+ // src/widget/QuestionEngine.ts
1329
+ var BASE_QUESTIONS = [
1330
+ {
1331
+ id: "what_doing",
1332
+ text: "O que voc\xEA estava tentando fazer?",
1333
+ type: "text",
1334
+ required: true
1335
+ }
1336
+ ];
1337
+ var QUESTION_RULES = [
1338
+ {
1339
+ id: "server_error",
1340
+ condition: (e) => e.httpCode !== void 0 && e.httpCode >= 500,
1341
+ priority: 10,
1342
+ questions: [
1343
+ {
1344
+ id: "form_filled",
1345
+ text: "Voc\xEA preencheu algum formul\xE1rio antes disso?",
1346
+ type: "boolean"
1347
+ },
1348
+ {
1349
+ id: "data_lost",
1350
+ text: "Voc\xEA perdeu algum dado importante?",
1351
+ type: "boolean"
1352
+ }
1353
+ ]
1354
+ },
1355
+ {
1356
+ id: "network_error",
1357
+ condition: (e) => e.message.toLowerCase().includes("network") || e.message.toLowerCase().includes("fetch") || e.message.toLowerCase().includes("failed to fetch") || e.errorType === "TypeError" && e.message.includes("fetch"),
1358
+ priority: 9,
1359
+ questions: [
1360
+ {
1361
+ id: "internet_working",
1362
+ text: "Sua internet est\xE1 funcionando normalmente?",
1363
+ type: "boolean"
1364
+ },
1365
+ {
1366
+ id: "using_vpn",
1367
+ text: "Voc\xEA est\xE1 usando VPN ou proxy?",
1368
+ type: "boolean"
1369
+ }
1370
+ ]
1371
+ },
1372
+ {
1373
+ id: "timeout_error",
1374
+ condition: (e) => e.message.toLowerCase().includes("timeout") || e.message.toLowerCase().includes("timed out"),
1375
+ priority: 8,
1376
+ questions: [
1377
+ {
1378
+ id: "page_slow",
1379
+ text: "A p\xE1gina estava lenta antes do erro?",
1380
+ type: "boolean"
1381
+ },
1382
+ {
1383
+ id: "first_time",
1384
+ text: "\xC9 a primeira vez que isso acontece?",
1385
+ type: "boolean"
1386
+ }
1387
+ ]
1388
+ },
1389
+ {
1390
+ id: "auth_error",
1391
+ condition: (e) => e.httpCode === 401 || e.httpCode === 403 || e.message.toLowerCase().includes("unauthorized") || e.message.toLowerCase().includes("forbidden"),
1392
+ priority: 7,
1393
+ questions: [
1394
+ {
1395
+ id: "logged_in",
1396
+ text: "Voc\xEA estava logado no sistema?",
1397
+ type: "boolean"
1398
+ },
1399
+ {
1400
+ id: "session_expired",
1401
+ text: "Ficou muito tempo sem usar o sistema?",
1402
+ type: "boolean"
1403
+ }
1404
+ ]
1405
+ },
1406
+ {
1407
+ id: "not_found",
1408
+ condition: (e) => e.httpCode === 404,
1409
+ priority: 6,
1410
+ questions: [
1411
+ {
1412
+ id: "how_arrived",
1413
+ text: "Como voc\xEA chegou nessa p\xE1gina?",
1414
+ type: "select",
1415
+ options: ["Digitei o link", "Cliquei em um bot\xE3o", "Usei o menu", "Outro"]
1416
+ }
1417
+ ]
1418
+ },
1419
+ {
1420
+ id: "validation_error",
1421
+ condition: (e) => e.httpCode === 400 || e.httpCode === 422 || e.message.toLowerCase().includes("validation") || e.message.toLowerCase().includes("invalid"),
1422
+ priority: 5,
1423
+ questions: [
1424
+ {
1425
+ id: "what_filled",
1426
+ text: "O que voc\xEA preencheu no formul\xE1rio?",
1427
+ type: "text"
1428
+ },
1429
+ {
1430
+ id: "special_chars",
1431
+ text: "Usou caracteres especiais ou emojis?",
1432
+ type: "boolean"
1433
+ }
1434
+ ]
1435
+ },
1436
+ {
1437
+ id: "ui_error",
1438
+ condition: (e) => e.errorType === "TypeError" || e.message.toLowerCase().includes("undefined") || e.message.toLowerCase().includes("null"),
1439
+ priority: 4,
1440
+ questions: [
1441
+ {
1442
+ id: "clicked_what",
1443
+ text: "Voc\xEA clicou em algo espec\xEDfico?",
1444
+ type: "text"
1445
+ },
1446
+ {
1447
+ id: "page_loaded",
1448
+ text: "A p\xE1gina tinha carregado completamente?",
1449
+ type: "boolean"
1450
+ }
1451
+ ]
1452
+ },
1453
+ {
1454
+ id: "load_error",
1455
+ condition: (e) => e.message.toLowerCase().includes("chunk") || e.message.toLowerCase().includes("loading") || e.message.toLowerCase().includes("script"),
1456
+ priority: 3,
1457
+ questions: [
1458
+ {
1459
+ id: "refreshed",
1460
+ text: "Voc\xEA tentou atualizar a p\xE1gina?",
1461
+ type: "boolean"
1462
+ },
1463
+ {
1464
+ id: "browser",
1465
+ text: "Qual navegador voc\xEA est\xE1 usando?",
1466
+ type: "select",
1467
+ options: ["Chrome", "Firefox", "Safari", "Edge", "Outro"]
1468
+ }
1469
+ ]
1470
+ }
1471
+ ];
1472
+ var FALLBACK_QUESTIONS = [
1473
+ {
1474
+ id: "happened_before",
1475
+ text: "Isso j\xE1 aconteceu antes?",
1476
+ type: "boolean"
1477
+ },
1478
+ {
1479
+ id: "additional_info",
1480
+ text: "Algo mais que possa nos ajudar?",
1481
+ type: "text",
1482
+ required: false
1483
+ }
1484
+ ];
1485
+ var QuestionEngine = class {
1486
+ inferQuestions(message, payload) {
1487
+ const context = {
1488
+ message,
1489
+ type: "error",
1490
+ httpCode: payload == null ? void 0 : payload.httpCode,
1491
+ errorType: payload == null ? void 0 : payload.errorType,
1492
+ stack: payload == null ? void 0 : payload.stack
1493
+ };
1494
+ const matchedRules = QUESTION_RULES.filter((rule) => rule.condition(context)).sort((a, b) => b.priority - a.priority);
1495
+ const questions = [...BASE_QUESTIONS];
1496
+ const addedIds = new Set(questions.map((q) => q.id));
1497
+ for (const rule of matchedRules.slice(0, 2)) {
1498
+ for (const question of rule.questions) {
1499
+ if (!addedIds.has(question.id)) {
1500
+ questions.push(question);
1501
+ addedIds.add(question.id);
1502
+ }
1503
+ }
1504
+ }
1505
+ if (questions.length < 3) {
1506
+ for (const question of FALLBACK_QUESTIONS) {
1507
+ if (!addedIds.has(question.id) && questions.length < 4) {
1508
+ questions.push(question);
1509
+ addedIds.add(question.id);
1510
+ }
1511
+ }
1512
+ }
1513
+ return questions.slice(0, 4);
1514
+ }
1515
+ shouldShowWidget(message, payload, backendDecision) {
1516
+ if (backendDecision !== void 0) {
1517
+ return backendDecision;
1518
+ }
1519
+ if ((payload == null ? void 0 : payload.httpCode) !== void 0) {
1520
+ if (payload.httpCode >= 500) return true;
1521
+ if (payload.httpCode === 400 || payload.httpCode === 422) return true;
1522
+ }
1523
+ const criticalPatterns = [
1524
+ "unexpected",
1525
+ "critical",
1526
+ "fatal",
1527
+ "crash",
1528
+ "failed to",
1529
+ "cannot read",
1530
+ "cannot access",
1531
+ "undefined is not",
1532
+ "null is not"
1533
+ ];
1534
+ const lowerMessage = message.toLowerCase();
1535
+ return criticalPatterns.some((pattern) => lowerMessage.includes(pattern));
1536
+ }
1537
+ };
1538
+
1539
+ // src/widget/styles.ts
1540
+ function injectStyles(theme) {
1541
+ if (document.getElementById("blinker-widget-styles")) return;
1542
+ const styles = document.createElement("style");
1543
+ styles.id = "blinker-widget-styles";
1544
+ styles.textContent = getStyles(theme);
1545
+ document.head.appendChild(styles);
1546
+ }
1547
+ function removeStyles() {
1548
+ const styles = document.getElementById("blinker-widget-styles");
1549
+ if (styles) styles.remove();
1550
+ }
1551
+ function updateStyles(theme) {
1552
+ const styles = document.getElementById("blinker-widget-styles");
1553
+ if (styles) {
1554
+ styles.textContent = getStyles(theme);
1555
+ }
1556
+ }
1557
+ function getStyles(theme) {
1558
+ return `
1559
+ @keyframes blinker-breathe {
1560
+ 0%, 100% { transform: scale(1); }
1561
+ 50% { transform: scale(1.05); }
1562
+ }
1563
+
1564
+ @keyframes blinker-pulse {
1565
+ 0%, 100% { opacity: 1; }
1566
+ 50% { opacity: 0.7; }
1567
+ }
1568
+
1569
+ @keyframes blinker-float {
1570
+ 0%, 100% { transform: translateY(0); }
1571
+ 50% { transform: translateY(-5px); }
1572
+ }
1573
+
1574
+ @keyframes blinker-fade-in {
1575
+ from { opacity: 0; transform: scale(0.8) translateY(20px); }
1576
+ to { opacity: 1; transform: scale(1) translateY(0); }
1577
+ }
1578
+
1579
+ @keyframes blinker-fade-out {
1580
+ from { opacity: 1; transform: scale(1) translateY(0); }
1581
+ to { opacity: 0; transform: scale(0.8) translateY(20px); }
1582
+ }
1583
+
1584
+ @keyframes blinker-slide-up {
1585
+ from { opacity: 0; transform: translateY(30px); }
1586
+ to { opacity: 1; transform: translateY(0); }
1587
+ }
1588
+
1589
+ @keyframes blinker-eye-blink {
1590
+ 0%, 45%, 55%, 100% { transform: scaleY(1); }
1591
+ 50% { transform: scaleY(0.1); }
1592
+ }
1593
+
1594
+ @keyframes blinker-glow {
1595
+ 0%, 100% { filter: drop-shadow(0 0 8px ${theme.primary}40); }
1596
+ 50% { filter: drop-shadow(0 0 15px ${theme.primary}60); }
1597
+ }
1598
+
1599
+ .blinker-widget-container {
1600
+ position: fixed;
1601
+ z-index: 999999;
1602
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
1603
+ }
1604
+
1605
+ .blinker-widget-container.bottom-right {
1606
+ bottom: 20px;
1607
+ right: 20px;
1608
+ }
1609
+
1610
+ .blinker-widget-container.bottom-left {
1611
+ bottom: 20px;
1612
+ left: 20px;
1613
+ }
1614
+
1615
+ .blinker-avatar {
1616
+ width: 60px;
1617
+ height: 60px;
1618
+ cursor: pointer;
1619
+ animation: blinker-float 3s ease-in-out infinite, blinker-glow 2s ease-in-out infinite;
1620
+ transition: transform 0.3s ease;
1621
+ }
1622
+
1623
+ .blinker-avatar:hover {
1624
+ transform: scale(1.1);
1625
+ }
1626
+
1627
+ .blinker-avatar.minimized {
1628
+ width: 40px;
1629
+ height: 40px;
1630
+ }
1631
+
1632
+ .blinker-avatar-body {
1633
+ fill: ${theme.primary};
1634
+ animation: blinker-breathe 4s ease-in-out infinite;
1635
+ transform-origin: center;
1636
+ }
1637
+
1638
+ .blinker-avatar-eye {
1639
+ fill: ${theme.background};
1640
+ animation: blinker-eye-blink 4s ease-in-out infinite;
1641
+ transform-origin: center;
1642
+ }
1643
+
1644
+ .blinker-avatar-eye-left {
1645
+ animation-delay: 0.1s;
1646
+ }
1647
+
1648
+ .blinker-avatar-pupil {
1649
+ fill: ${theme.text};
1650
+ transition: transform 0.1s ease;
1651
+ }
1652
+
1653
+ .blinker-avatar-mouth {
1654
+ stroke: ${theme.background};
1655
+ stroke-width: 2;
1656
+ fill: none;
1657
+ stroke-linecap: round;
1658
+ }
1659
+
1660
+ .blinker-avatar-glow {
1661
+ fill: ${theme.primary};
1662
+ opacity: 0.3;
1663
+ animation: blinker-pulse 2s ease-in-out infinite;
1664
+ }
1665
+
1666
+ .blinker-dialog-overlay {
1667
+ position: fixed;
1668
+ top: 0;
1669
+ left: 0;
1670
+ right: 0;
1671
+ bottom: 0;
1672
+ background: rgba(0, 0, 0, 0.3);
1673
+ z-index: 999998;
1674
+ animation: blinker-fade-in 0.3s ease;
1675
+ }
1676
+
1677
+ .blinker-dialog {
1678
+ position: fixed;
1679
+ z-index: 999999;
1680
+ width: 340px;
1681
+ max-width: calc(100vw - 40px);
1682
+ background: ${theme.background};
1683
+ border-radius: 16px;
1684
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
1685
+ animation: blinker-slide-up 0.4s ease;
1686
+ overflow: hidden;
95
1687
  }
96
- }
97
- return result;
1688
+
1689
+ .blinker-dialog.bottom-right {
1690
+ bottom: 90px;
1691
+ right: 20px;
1692
+ }
1693
+
1694
+ .blinker-dialog.bottom-left {
1695
+ bottom: 90px;
1696
+ left: 20px;
1697
+ }
1698
+
1699
+ .blinker-dialog-header {
1700
+ padding: 20px 20px 0;
1701
+ display: flex;
1702
+ align-items: flex-start;
1703
+ gap: 12px;
1704
+ }
1705
+
1706
+ .blinker-dialog-avatar {
1707
+ width: 40px;
1708
+ height: 40px;
1709
+ flex-shrink: 0;
1710
+ }
1711
+
1712
+ .blinker-dialog-title {
1713
+ flex: 1;
1714
+ }
1715
+
1716
+ .blinker-dialog-greeting {
1717
+ font-size: 16px;
1718
+ font-weight: 600;
1719
+ color: ${theme.text};
1720
+ margin: 0 0 4px;
1721
+ }
1722
+
1723
+ .blinker-dialog-subtext {
1724
+ font-size: 13px;
1725
+ color: ${theme.text}99;
1726
+ margin: 0;
1727
+ }
1728
+
1729
+ .blinker-dialog-close {
1730
+ background: none;
1731
+ border: none;
1732
+ padding: 4px;
1733
+ cursor: pointer;
1734
+ color: ${theme.text}66;
1735
+ border-radius: 6px;
1736
+ transition: all 0.2s;
1737
+ }
1738
+
1739
+ .blinker-dialog-close:hover {
1740
+ background: ${theme.text}10;
1741
+ color: ${theme.text};
1742
+ }
1743
+
1744
+ .blinker-dialog-body {
1745
+ padding: 20px;
1746
+ }
1747
+
1748
+ .blinker-question {
1749
+ margin-bottom: 16px;
1750
+ }
1751
+
1752
+ .blinker-question:last-child {
1753
+ margin-bottom: 0;
1754
+ }
1755
+
1756
+ .blinker-question-label {
1757
+ display: block;
1758
+ font-size: 14px;
1759
+ font-weight: 500;
1760
+ color: ${theme.text};
1761
+ margin-bottom: 8px;
1762
+ }
1763
+
1764
+ .blinker-question-input {
1765
+ width: 100%;
1766
+ padding: 10px 12px;
1767
+ border: 1px solid ${theme.text}20;
1768
+ border-radius: 8px;
1769
+ font-size: 14px;
1770
+ color: ${theme.text};
1771
+ background: ${theme.background};
1772
+ transition: border-color 0.2s, box-shadow 0.2s;
1773
+ box-sizing: border-box;
1774
+ }
1775
+
1776
+ .blinker-question-input:focus {
1777
+ outline: none;
1778
+ border-color: ${theme.primary};
1779
+ box-shadow: 0 0 0 3px ${theme.primary}20;
1780
+ }
1781
+
1782
+ .blinker-question-input::placeholder {
1783
+ color: ${theme.text}50;
1784
+ }
1785
+
1786
+ .blinker-question-textarea {
1787
+ resize: vertical;
1788
+ min-height: 80px;
1789
+ }
1790
+
1791
+ .blinker-question-select {
1792
+ appearance: none;
1793
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23666' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
1794
+ background-repeat: no-repeat;
1795
+ background-position: right 12px center;
1796
+ padding-right: 36px;
1797
+ }
1798
+
1799
+ .blinker-question-boolean {
1800
+ display: flex;
1801
+ gap: 8px;
1802
+ }
1803
+
1804
+ .blinker-question-boolean button {
1805
+ flex: 1;
1806
+ padding: 10px;
1807
+ border: 1px solid ${theme.text}20;
1808
+ border-radius: 8px;
1809
+ background: ${theme.background};
1810
+ color: ${theme.text};
1811
+ font-size: 14px;
1812
+ cursor: pointer;
1813
+ transition: all 0.2s;
1814
+ }
1815
+
1816
+ .blinker-question-boolean button:hover {
1817
+ border-color: ${theme.primary};
1818
+ }
1819
+
1820
+ .blinker-question-boolean button.selected {
1821
+ background: ${theme.primary};
1822
+ border-color: ${theme.primary};
1823
+ color: white;
1824
+ }
1825
+
1826
+ .blinker-dialog-footer {
1827
+ padding: 16px 20px 20px;
1828
+ display: flex;
1829
+ gap: 8px;
1830
+ }
1831
+
1832
+ .blinker-btn {
1833
+ flex: 1;
1834
+ padding: 12px 16px;
1835
+ border-radius: 8px;
1836
+ font-size: 14px;
1837
+ font-weight: 500;
1838
+ cursor: pointer;
1839
+ transition: all 0.2s;
1840
+ border: none;
1841
+ }
1842
+
1843
+ .blinker-btn-primary {
1844
+ background: ${theme.accent};
1845
+ color: white;
1846
+ }
1847
+
1848
+ .blinker-btn-primary:hover {
1849
+ filter: brightness(1.1);
1850
+ }
1851
+
1852
+ .blinker-btn-primary:disabled {
1853
+ opacity: 0.5;
1854
+ cursor: not-allowed;
1855
+ }
1856
+
1857
+ .blinker-btn-secondary {
1858
+ background: ${theme.text}10;
1859
+ color: ${theme.text}99;
1860
+ }
1861
+
1862
+ .blinker-btn-secondary:hover {
1863
+ background: ${theme.text}20;
1864
+ }
1865
+
1866
+ .blinker-thank-you {
1867
+ text-align: center;
1868
+ padding: 40px 20px;
1869
+ }
1870
+
1871
+ .blinker-thank-you-icon {
1872
+ width: 48px;
1873
+ height: 48px;
1874
+ margin: 0 auto 16px;
1875
+ color: ${theme.accent};
1876
+ }
1877
+
1878
+ .blinker-thank-you-text {
1879
+ font-size: 16px;
1880
+ color: ${theme.text};
1881
+ margin: 0;
1882
+ }
1883
+ `;
98
1884
  }
99
1885
 
100
- // src/errorHandler.ts
101
- var originalOnError = null;
102
- var originalOnUnhandledRejection = null;
103
- var isSetup = false;
104
- function setupErrorHandlers(callback, options = {}) {
105
- const { captureErrors = true, captureRejections = true, debug = false } = options;
106
- if (isSetup) {
107
- if (debug) {
108
- console.warn("[Blinker] Error handlers already set up");
1886
+ // src/widget/Widget.ts
1887
+ var STORAGE_KEY = "blinker_widget_state";
1888
+ var Widget = class {
1889
+ constructor(config) {
1890
+ this.container = null;
1891
+ this.avatar = null;
1892
+ this.dialog = null;
1893
+ this.onFeedbackSubmit = null;
1894
+ this.config = { ...DEFAULT_WIDGET_CONFIG, ...config };
1895
+ this.state = this.loadState();
1896
+ this.questionEngine = new QuestionEngine();
1897
+ }
1898
+ init(onFeedbackSubmit) {
1899
+ if (!this.config.enabled) return;
1900
+ if (typeof document === "undefined") return;
1901
+ this.onFeedbackSubmit = onFeedbackSubmit || null;
1902
+ injectStyles(this.config.theme);
1903
+ this.createContainer();
1904
+ }
1905
+ createContainer() {
1906
+ if (this.container) return;
1907
+ this.container = document.createElement("div");
1908
+ this.container.className = `blinker-widget-container ${this.config.position}`;
1909
+ document.body.appendChild(this.container);
1910
+ this.avatar = new Avatar(this.config.theme, () => this.handleAvatarClick());
1911
+ const avatarElement = this.avatar.create();
1912
+ this.container.appendChild(avatarElement);
1913
+ this.dialog = new Dialog(
1914
+ this.config,
1915
+ (feedback) => this.handleFeedbackSubmit(feedback),
1916
+ () => this.handleDialogClose()
1917
+ );
1918
+ this.hide();
1919
+ }
1920
+ show(errorId, message, payload, backendDecision) {
1921
+ if (!this.config.enabled) return;
1922
+ if (!this.container || !this.avatar) return;
1923
+ const shouldShow = this.questionEngine.shouldShowWidget(message, payload, backendDecision);
1924
+ if (!shouldShow) return;
1925
+ if (!this.canShowWidget()) return;
1926
+ const questions = this.questionEngine.inferQuestions(message, payload);
1927
+ this.state.currentErrorId = errorId;
1928
+ this.state.questions = questions;
1929
+ this.state.isVisible = true;
1930
+ this.state.showCount++;
1931
+ this.state.lastShowTime = Date.now();
1932
+ this.saveState();
1933
+ this.container.style.display = "block";
1934
+ this.avatar.setMinimized(false);
1935
+ }
1936
+ hide() {
1937
+ if (!this.container) return;
1938
+ this.state.isVisible = false;
1939
+ this.state.isDialogOpen = false;
1940
+ this.container.style.display = "none";
1941
+ }
1942
+ handleAvatarClick() {
1943
+ var _a;
1944
+ if (!this.dialog || !this.state.currentErrorId) return;
1945
+ if (this.state.isDialogOpen) {
1946
+ this.dialog.close();
1947
+ } else {
1948
+ this.state.isDialogOpen = true;
1949
+ this.dialog.open(this.state.currentErrorId, this.state.questions);
1950
+ (_a = this.avatar) == null ? void 0 : _a.setMinimized(true);
109
1951
  }
110
- return;
111
1952
  }
112
- if (typeof window === "undefined") {
113
- if (debug) {
114
- console.log("[Blinker] Not in browser environment, skipping error handlers");
1953
+ handleFeedbackSubmit(feedback) {
1954
+ if (this.onFeedbackSubmit) {
1955
+ this.onFeedbackSubmit(feedback);
115
1956
  }
116
- return;
117
1957
  }
118
- if (captureErrors) {
119
- originalOnError = window.onerror;
120
- window.onerror = function(message, source, lineno, colno, error) {
121
- const errorMessage = typeof message === "string" ? message : message.type || "Unknown error";
122
- const payload = {
123
- source,
124
- lineno,
125
- colno,
126
- stack: error == null ? void 0 : error.stack,
127
- errorType: error == null ? void 0 : error.name
128
- };
129
- if (debug) {
130
- console.log("[Blinker] Captured error:", errorMessage);
131
- }
132
- callback("error", errorMessage, payload);
133
- if (typeof originalOnError === "function") {
134
- return originalOnError.call(window, message, source, lineno, colno, error);
135
- }
136
- return false;
137
- };
1958
+ handleDialogClose() {
1959
+ var _a;
1960
+ this.state.isDialogOpen = false;
1961
+ (_a = this.avatar) == null ? void 0 : _a.setMinimized(false);
1962
+ setTimeout(() => {
1963
+ this.hide();
1964
+ }, 500);
138
1965
  }
139
- if (captureRejections) {
140
- originalOnUnhandledRejection = window.onunhandledrejection;
141
- window.onunhandledrejection = function(event) {
142
- let message = "Unhandled Rejection";
143
- const payload = {};
144
- const reason = event.reason;
145
- if (reason instanceof Error) {
146
- message = reason.message || message;
147
- payload.stack = reason.stack;
148
- payload.errorType = reason.name;
149
- } else if (typeof reason === "string") {
150
- message = reason;
151
- } else if (reason !== void 0 && reason !== null) {
152
- try {
153
- message = JSON.stringify(reason);
154
- } catch (e) {
155
- message = String(reason);
156
- }
157
- }
158
- if (debug) {
159
- console.log("[Blinker] Captured unhandled rejection:", message);
160
- }
161
- callback("error", message, payload);
162
- if (typeof originalOnUnhandledRejection === "function") {
163
- originalOnUnhandledRejection.call(window, event);
1966
+ canShowWidget() {
1967
+ if (this.state.showCount >= this.config.maxShowsPerSession) {
1968
+ return false;
1969
+ }
1970
+ if (this.state.lastShowTime) {
1971
+ const cooldownMs = this.config.cooldownMinutes * 60 * 1e3;
1972
+ const timeSinceLastShow = Date.now() - this.state.lastShowTime;
1973
+ if (timeSinceLastShow < cooldownMs) {
1974
+ return false;
164
1975
  }
1976
+ }
1977
+ return true;
1978
+ }
1979
+ loadState() {
1980
+ const defaultState = {
1981
+ isVisible: false,
1982
+ isMinimized: false,
1983
+ isDialogOpen: false,
1984
+ currentErrorId: null,
1985
+ questions: [],
1986
+ showCount: 0,
1987
+ lastShowTime: null
165
1988
  };
1989
+ if (typeof sessionStorage === "undefined") return defaultState;
1990
+ try {
1991
+ const stored = sessionStorage.getItem(STORAGE_KEY);
1992
+ if (stored) {
1993
+ const parsed = JSON.parse(stored);
1994
+ return {
1995
+ ...defaultState,
1996
+ showCount: parsed.showCount || 0,
1997
+ lastShowTime: parsed.lastShowTime || null
1998
+ };
1999
+ }
2000
+ } catch (e) {
2001
+ }
2002
+ return defaultState;
166
2003
  }
167
- isSetup = true;
168
- }
169
- function teardownErrorHandlers() {
170
- if (typeof window === "undefined") {
171
- return;
2004
+ saveState() {
2005
+ if (typeof sessionStorage === "undefined") return;
2006
+ try {
2007
+ sessionStorage.setItem(STORAGE_KEY, JSON.stringify({
2008
+ showCount: this.state.showCount,
2009
+ lastShowTime: this.state.lastShowTime
2010
+ }));
2011
+ } catch (e) {
2012
+ }
172
2013
  }
173
- if (originalOnError !== void 0) {
174
- window.onerror = originalOnError;
2014
+ updateConfig(config) {
2015
+ var _a, _b;
2016
+ this.config = { ...this.config, ...config };
2017
+ if (config.theme) {
2018
+ updateStyles(this.config.theme);
2019
+ (_a = this.avatar) == null ? void 0 : _a.updateTheme(this.config.theme);
2020
+ }
2021
+ (_b = this.dialog) == null ? void 0 : _b.updateConfig(this.config);
175
2022
  }
176
- if (originalOnUnhandledRejection !== void 0) {
177
- window.onunhandledrejection = originalOnUnhandledRejection;
2023
+ getConfig() {
2024
+ return { ...this.config };
2025
+ }
2026
+ isVisible() {
2027
+ return this.state.isVisible;
2028
+ }
2029
+ isDialogOpen() {
2030
+ return this.state.isDialogOpen;
2031
+ }
2032
+ destroy() {
2033
+ var _a, _b;
2034
+ (_a = this.avatar) == null ? void 0 : _a.destroy();
2035
+ (_b = this.dialog) == null ? void 0 : _b.close();
2036
+ if (this.container) {
2037
+ this.container.remove();
2038
+ this.container = null;
2039
+ }
2040
+ removeStyles();
2041
+ this.avatar = null;
2042
+ this.dialog = null;
178
2043
  }
179
- originalOnError = null;
180
- originalOnUnhandledRejection = null;
181
- isSetup = false;
182
- }
183
-
184
- // src/Blinker.ts
185
- var BLINKER_API = "https://api.blinker.live";
186
- var DEFAULT_FILTERS = {
187
- // Auth/permission errors are usually expected behavior, not bugs
188
- ignoreHttpCodes: [401, 403],
189
- // All JS error types are captured by default
190
- ignoreErrorTypes: [],
191
- // Common benign browser errors that aren't actionable
192
- ignoreMessagePatterns: [
193
- "ResizeObserver loop",
194
- // Common benign browser error
195
- "Script error",
196
- // Cross-origin script errors (no useful info)
197
- "ResizeObserver loop completed"
198
- // Another variant of ResizeObserver
199
- ],
200
- // By default, respect the filters
201
- captureAll: false
202
2044
  };
2045
+
2046
+ // src/core/Blinker.ts
203
2047
  var Blinker = class {
204
2048
  constructor() {
205
2049
  this.config = null;
206
2050
  this.initialized = false;
207
- this.filters = { ...DEFAULT_FILTERS };
2051
+ this.filterEngine = null;
2052
+ this.queue = null;
2053
+ this.sessionManager = null;
2054
+ this.userContext = null;
2055
+ this.rateLimiter = null;
2056
+ this.sampler = null;
2057
+ this.deduplicator = null;
2058
+ this.widget = null;
2059
+ }
2060
+ get version() {
2061
+ return SDK_VERSION;
208
2062
  }
209
- /**
210
- * Initialize the Blinker SDK
211
- * @param config Configuration options
212
- */
213
2063
  init(config) {
214
- var _a, _b, _c, _d, _e, _f, _g, _h;
2064
+ var _a, _b, _c, _d;
215
2065
  if (this.initialized) {
216
- if (config.debug) {
217
- console.warn("[Blinker] SDK already initialized");
218
- }
2066
+ const logger2 = getLogger();
2067
+ logger2.warn("SDK already initialized");
219
2068
  return;
220
2069
  }
221
2070
  if (!config.token) {
222
2071
  throw new Error("[Blinker] Token is required");
223
2072
  }
2073
+ const enabled = (_a = config.enabled) != null ? _a : DEFAULTS.enabled;
2074
+ if (!enabled) {
2075
+ setGlobalLogger((_b = config.debug) != null ? _b : false);
2076
+ const logger2 = getLogger();
2077
+ logger2.log("SDK disabled via config");
2078
+ this.config = { ...DEFAULTS, ...config };
2079
+ return;
2080
+ }
224
2081
  this.config = {
225
- captureErrors: true,
226
- captureRejections: true,
227
- debug: false,
2082
+ ...DEFAULTS,
228
2083
  ...config
229
2084
  };
230
- this.filters = {
231
- ignoreHttpCodes: (_b = (_a = config.filters) == null ? void 0 : _a.ignoreHttpCodes) != null ? _b : DEFAULT_FILTERS.ignoreHttpCodes,
232
- ignoreErrorTypes: (_d = (_c = config.filters) == null ? void 0 : _c.ignoreErrorTypes) != null ? _d : DEFAULT_FILTERS.ignoreErrorTypes,
233
- ignoreMessagePatterns: (_f = (_e = config.filters) == null ? void 0 : _e.ignoreMessagePatterns) != null ? _f : DEFAULT_FILTERS.ignoreMessagePatterns,
234
- captureAll: (_h = (_g = config.filters) == null ? void 0 : _g.captureAll) != null ? _h : DEFAULT_FILTERS.captureAll
235
- };
236
- if (this.config.debug) {
237
- console.log("[Blinker] Filters configured:", this.filters);
238
- }
2085
+ setGlobalLogger((_c = this.config.debug) != null ? _c : false);
2086
+ const logger = getLogger();
2087
+ this.filterEngine = new FilterEngine(config.filters);
2088
+ logger.log("Filter engine initialized");
2089
+ this.queue = new EventQueue(config.token, {
2090
+ endpoint: this.config.endpoint,
2091
+ enableBatching: this.config.enableBatching,
2092
+ batchSize: this.config.batchSize,
2093
+ flushInterval: this.config.flushInterval,
2094
+ enableOfflineStorage: this.config.enableOfflineStorage,
2095
+ maxStoredEvents: this.config.maxStoredEvents,
2096
+ onError: this.config.onError
2097
+ });
2098
+ logger.log("Event queue initialized");
2099
+ this.sessionManager = new SessionManager();
2100
+ this.userContext = new UserContext(this.sessionManager);
2101
+ logger.log("Context managers initialized");
2102
+ this.rateLimiter = new RateLimiter(this.config.maxEventsPerMinute);
2103
+ this.sampler = new Sampler(this.config.sampleRate);
2104
+ logger.log("Sampling modules initialized");
2105
+ this.deduplicator = new Deduplicator(
2106
+ this.config.enableDeduplication,
2107
+ this.config.deduplicationWindow
2108
+ );
2109
+ logger.log("Deduplicator initialized");
239
2110
  if (this.config.captureErrors || this.config.captureRejections) {
240
2111
  setupErrorHandlers(
241
- (type, message, payload) => {
242
- var _a2;
243
- if (this.shouldCapture(message, payload == null ? void 0 : payload.errorType)) {
244
- this.track(type, message, payload);
245
- } else if ((_a2 = this.config) == null ? void 0 : _a2.debug) {
246
- console.log("[Blinker] Error filtered out:", message);
247
- }
248
- },
2112
+ (type, message, payload) => this.handleCapturedError(type, message, payload),
249
2113
  {
250
2114
  captureErrors: this.config.captureErrors,
251
- captureRejections: this.config.captureRejections,
252
- debug: this.config.debug
2115
+ captureRejections: this.config.captureRejections
253
2116
  }
254
2117
  );
2118
+ logger.log("Error handlers set up");
255
2119
  }
256
- this.initialized = true;
257
- if (this.config.debug) {
258
- console.log("[Blinker] SDK initialized successfully");
2120
+ if ((_d = this.config.widget) == null ? void 0 : _d.enabled) {
2121
+ this.widget = new Widget(this.config.widget);
2122
+ this.widget.init((feedback) => this.handleWidgetFeedback(feedback));
2123
+ logger.log("Widget initialized");
259
2124
  }
2125
+ this.initialized = true;
2126
+ logger.log("SDK initialized successfully");
260
2127
  }
261
- /**
262
- * Check if an error should be captured based on filter settings
263
- * @param message Error message
264
- * @param errorType Optional JS error type (e.g., 'TypeError')
265
- * @param httpCode Optional HTTP status code
266
- * @returns true if the error should be captured, false if filtered out
267
- */
268
- shouldCapture(message, errorType, httpCode) {
269
- if (this.filters.captureAll) {
270
- return true;
271
- }
272
- if (httpCode !== void 0 && this.filters.ignoreHttpCodes.includes(httpCode)) {
273
- return false;
274
- }
275
- if (errorType && this.filters.ignoreErrorTypes.includes(errorType)) {
276
- return false;
2128
+ handleCapturedError(type, message, payload) {
2129
+ var _a, _b, _c, _d, _e;
2130
+ if (!((_a = this.filterEngine) == null ? void 0 : _a.shouldCapture(message, payload.errorType, payload.httpCode))) {
2131
+ return;
277
2132
  }
278
- for (const pattern of this.filters.ignoreMessagePatterns) {
279
- if (message.toLowerCase().includes(pattern.toLowerCase())) {
280
- return false;
281
- }
2133
+ const dedupResult = (_b = this.deduplicator) == null ? void 0 : _b.check(message, payload.stack);
2134
+ if (dedupResult && !dedupResult.shouldSend) {
2135
+ return;
282
2136
  }
283
- if (httpCode === void 0) {
284
- const httpCodeMatch = message.match(/(?:HTTP\s*|status[:\s]*)?(\d{3})(?:\s|$|:)/i);
285
- if (httpCodeMatch) {
286
- const extractedCode = parseInt(httpCodeMatch[1], 10);
287
- if (extractedCode >= 100 && extractedCode < 600) {
288
- if (this.filters.ignoreHttpCodes.includes(extractedCode)) {
289
- return false;
290
- }
291
- }
292
- }
2137
+ const errorId = generateUniqueId();
2138
+ this.track(type, message, {
2139
+ ...payload,
2140
+ errorId,
2141
+ count: dedupResult == null ? void 0 : dedupResult.count
2142
+ });
2143
+ if (this.widget && ((_d = (_c = this.config) == null ? void 0 : _c.widget) == null ? void 0 : _d.enabled)) {
2144
+ setTimeout(() => {
2145
+ var _a2;
2146
+ (_a2 = this.widget) == null ? void 0 : _a2.show(errorId, message, payload);
2147
+ }, (_e = this.config.widget.delay) != null ? _e : 2e3);
293
2148
  }
294
- return true;
295
2149
  }
296
- /**
297
- * Track a custom event
298
- * @param type Event type (e.g., 'click', 'pageview', 'custom')
299
- * @param message Event message or description
300
- * @param payload Optional additional data
301
- */
2150
+ handleWidgetFeedback(feedback) {
2151
+ const logger = getLogger();
2152
+ logger.log("Widget feedback received:", feedback.errorId);
2153
+ this.track("feedback", "User feedback submitted", {
2154
+ errorId: feedback.errorId,
2155
+ answers: feedback.answers,
2156
+ submittedAt: feedback.submittedAt
2157
+ });
2158
+ }
302
2159
  track(type, message, payload) {
303
- var _a;
304
- if (!this.initialized || !this.config) {
305
- if ((_a = this.config) == null ? void 0 : _a.debug) {
306
- console.warn("[Blinker] SDK not initialized. Call blinker.init() first.");
307
- }
2160
+ var _a, _b, _c;
2161
+ if (!this.config) {
308
2162
  return Promise.resolve({ success: false, error: "SDK not initialized" });
309
2163
  }
310
- const event = {
2164
+ if (!this.config.enabled) {
2165
+ return Promise.resolve({ success: true, error: "SDK disabled" });
2166
+ }
2167
+ if (!this.initialized) {
2168
+ return Promise.resolve({ success: false, error: "SDK not initialized" });
2169
+ }
2170
+ const logger = getLogger();
2171
+ const isError = type === "error";
2172
+ if (!((_a = this.rateLimiter) == null ? void 0 : _a.allow())) {
2173
+ logger.log("Event dropped due to rate limit");
2174
+ return Promise.resolve({ success: false, error: "Rate limited" });
2175
+ }
2176
+ if (!((_b = this.sampler) == null ? void 0 : _b.shouldSample(isError))) {
2177
+ return Promise.resolve({ success: true, error: "Sampled out" });
2178
+ }
2179
+ const context = (_c = this.userContext) == null ? void 0 : _c.getEventContext();
2180
+ let event = {
2181
+ id: generateUniqueId(),
311
2182
  type,
312
2183
  message,
313
2184
  payload,
314
2185
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
315
- url: typeof window !== "undefined" ? window.location.href : void 0,
316
- userAgent: typeof navigator !== "undefined" ? navigator.userAgent : void 0
2186
+ url: getCurrentUrl(),
2187
+ userAgent: getUserAgent(),
2188
+ sessionId: context == null ? void 0 : context.sessionId,
2189
+ userId: context == null ? void 0 : context.userId,
2190
+ userTraits: context == null ? void 0 : context.userTraits,
2191
+ context: context == null ? void 0 : context.custom
317
2192
  };
318
- return sendEvent(BLINKER_API, this.config.token, event, this.config.debug);
2193
+ if (this.config.onBeforeSend) {
2194
+ event = this.config.onBeforeSend(event);
2195
+ if (!event) {
2196
+ logger.log("Event filtered by onBeforeSend");
2197
+ return Promise.resolve({ success: true, error: "Filtered by onBeforeSend" });
2198
+ }
2199
+ }
2200
+ logger.log("Tracking event:", type, message.substring(0, 50));
2201
+ return this.queue.add(event);
319
2202
  }
320
- /**
321
- * Track an error manually
322
- * @param error Error object or message
323
- * @param additionalPayload Optional additional data (can include httpCode for filtering)
324
- */
325
2203
  captureError(error, additionalPayload) {
326
- var _a;
2204
+ var _a, _b;
327
2205
  const message = error instanceof Error ? error.message : error;
328
2206
  const errorType = error instanceof Error ? error.name : void 0;
2207
+ const stack = error instanceof Error ? error.stack : void 0;
329
2208
  const httpCode = additionalPayload == null ? void 0 : additionalPayload.httpCode;
330
- if (!this.shouldCapture(message, errorType, httpCode)) {
331
- if ((_a = this.config) == null ? void 0 : _a.debug) {
332
- console.log("[Blinker] Error filtered out:", { message, errorType, httpCode });
333
- }
334
- return Promise.resolve({ success: true, error: "Filtered out by settings" });
2209
+ if (!((_a = this.filterEngine) == null ? void 0 : _a.shouldCapture(message, errorType, httpCode))) {
2210
+ return Promise.resolve({ success: true, error: "Filtered out" });
2211
+ }
2212
+ const dedupResult = (_b = this.deduplicator) == null ? void 0 : _b.check(message, stack);
2213
+ if (dedupResult && !dedupResult.shouldSend) {
2214
+ return Promise.resolve({ success: true, error: "Deduplicated" });
335
2215
  }
336
2216
  const payload = {
337
- ...additionalPayload
2217
+ ...additionalPayload,
2218
+ errorType,
2219
+ stack,
2220
+ count: dedupResult == null ? void 0 : dedupResult.count
338
2221
  };
339
- if (error instanceof Error) {
340
- payload.stack = error.stack;
341
- payload.errorType = error.name;
342
- }
343
2222
  return this.track("error", message, payload);
344
2223
  }
345
- /**
346
- * Track a page view
347
- * @param pageName Optional page name (defaults to current URL path)
348
- * @param additionalPayload Optional additional data
349
- */
350
2224
  trackPageView(pageName, additionalPayload) {
351
- const page = pageName || (typeof window !== "undefined" ? window.location.pathname : "unknown");
2225
+ var _a;
2226
+ const page = pageName || getCurrentPath();
2227
+ (_a = this.sessionManager) == null ? void 0 : _a.recordPageView();
352
2228
  return this.track("pageview", page, {
353
2229
  ...additionalPayload,
354
- referrer: typeof document !== "undefined" ? document.referrer : void 0
2230
+ referrer: getReferrer()
355
2231
  });
356
2232
  }
357
- /**
358
- * Check if SDK is initialized
359
- */
2233
+ identify(userId, traits) {
2234
+ var _a;
2235
+ (_a = this.userContext) == null ? void 0 : _a.identify(userId, traits);
2236
+ }
2237
+ setContext(key, value) {
2238
+ var _a;
2239
+ (_a = this.userContext) == null ? void 0 : _a.setContext(key, value);
2240
+ }
2241
+ getContext() {
2242
+ var _a, _b;
2243
+ return (_b = (_a = this.userContext) == null ? void 0 : _a.getCustomContext()) != null ? _b : {};
2244
+ }
2245
+ clearContext() {
2246
+ var _a;
2247
+ (_a = this.userContext) == null ? void 0 : _a.clearAll();
2248
+ }
2249
+ getSessionId() {
2250
+ var _a, _b;
2251
+ return (_b = (_a = this.sessionManager) == null ? void 0 : _a.getSessionId()) != null ? _b : "";
2252
+ }
2253
+ getSession() {
2254
+ var _a, _b;
2255
+ return (_b = (_a = this.sessionManager) == null ? void 0 : _a.getSession()) != null ? _b : null;
2256
+ }
2257
+ async flush() {
2258
+ var _a;
2259
+ await ((_a = this.queue) == null ? void 0 : _a.flush());
2260
+ }
2261
+ getQueueSize() {
2262
+ var _a, _b;
2263
+ return (_b = (_a = this.queue) == null ? void 0 : _a.size()) != null ? _b : 0;
2264
+ }
360
2265
  isInitialized() {
361
2266
  return this.initialized;
362
2267
  }
363
- /**
364
- * Get current configuration (without token for security)
365
- */
366
2268
  getConfig() {
367
2269
  if (!this.config) return null;
368
2270
  const { token: _token, ...safeConfig } = this.config;
369
2271
  return safeConfig;
370
2272
  }
371
- /**
372
- * Destroy the SDK instance
373
- * Removes error handlers and resets state
374
- */
375
- destroy() {
2273
+ getFilters() {
2274
+ var _a, _b;
2275
+ return (_b = (_a = this.filterEngine) == null ? void 0 : _a.getFilters()) != null ? _b : { ...DEFAULT_FILTERS };
2276
+ }
2277
+ showWidget(errorId, message, payload) {
2278
+ var _a;
2279
+ (_a = this.widget) == null ? void 0 : _a.show(errorId, message, payload);
2280
+ }
2281
+ hideWidget() {
2282
+ var _a;
2283
+ (_a = this.widget) == null ? void 0 : _a.hide();
2284
+ }
2285
+ getWidgetConfig() {
2286
+ var _a, _b;
2287
+ return (_b = (_a = this.widget) == null ? void 0 : _a.getConfig()) != null ? _b : null;
2288
+ }
2289
+ updateWidgetConfig(config) {
376
2290
  var _a;
377
- const wasDebug = (_a = this.config) == null ? void 0 : _a.debug;
2291
+ (_a = this.widget) == null ? void 0 : _a.updateConfig(config);
2292
+ }
2293
+ isWidgetVisible() {
2294
+ var _a, _b;
2295
+ return (_b = (_a = this.widget) == null ? void 0 : _a.isVisible()) != null ? _b : false;
2296
+ }
2297
+ destroy() {
2298
+ var _a, _b, _c, _d;
2299
+ const logger = getLogger();
2300
+ (_a = this.queue) == null ? void 0 : _a.destroy();
378
2301
  teardownErrorHandlers();
2302
+ (_b = this.deduplicator) == null ? void 0 : _b.destroy();
2303
+ (_c = this.sessionManager) == null ? void 0 : _c.endSession();
2304
+ (_d = this.widget) == null ? void 0 : _d.destroy();
379
2305
  this.config = null;
380
2306
  this.initialized = false;
381
- this.filters = { ...DEFAULT_FILTERS };
382
- if (wasDebug) {
383
- console.log("[Blinker] SDK destroyed");
384
- }
385
- }
386
- /**
387
- * Get current filter settings
388
- */
389
- getFilters() {
390
- return { ...this.filters };
2307
+ this.filterEngine = null;
2308
+ this.queue = null;
2309
+ this.sessionManager = null;
2310
+ this.userContext = null;
2311
+ this.rateLimiter = null;
2312
+ this.sampler = null;
2313
+ this.deduplicator = null;
2314
+ this.widget = null;
2315
+ logger.log("SDK destroyed");
2316
+ setGlobalLogger(false);
391
2317
  }
392
2318
  };
393
2319