capdebug 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2766 @@
1
+ import { registerPlugin, WebPlugin } from '@capacitor/core';
2
+
3
+ const DEFAULT_SENSITIVE_KEYS = new Set([
4
+ 'authorization',
5
+ 'cookie',
6
+ 'set-cookie',
7
+ 'password',
8
+ 'passwd',
9
+ 'pass',
10
+ 'token',
11
+ 'access_token',
12
+ 'accesstoken',
13
+ 'refresh_token',
14
+ 'refreshtoken',
15
+ 'api_key',
16
+ 'apikey',
17
+ 'secret',
18
+ 'client_secret',
19
+ 'clientsecret',
20
+ 'bearer',
21
+ 'private_key',
22
+ 'privatekey',
23
+ 'session_id',
24
+ 'sessionid',
25
+ 'jwt',
26
+ 'credit_card',
27
+ 'creditcard',
28
+ 'cvv',
29
+ 'ssn',
30
+ ]);
31
+ const MASK_VALUE = '********';
32
+ class DataSanitizer {
33
+ maskKeys;
34
+ maxDepth;
35
+ maxArrayLength;
36
+ constructor(options = {}) {
37
+ this.maskKeys = new Set([
38
+ ...DEFAULT_SENSITIVE_KEYS,
39
+ ...(options.customMaskKeys || []).map(k => k.toLowerCase().trim()),
40
+ ]);
41
+ this.maxDepth = options.maxDepth ?? 10;
42
+ this.maxArrayLength = options.maxArrayLength ?? 100;
43
+ }
44
+ isSensitiveKey(key) {
45
+ const normalized = key.toLowerCase().replace(/[-_]/g, '');
46
+ if (this.maskKeys.has(key.toLowerCase()) || this.maskKeys.has(normalized)) {
47
+ return true;
48
+ }
49
+ for (const sensitive of this.maskKeys) {
50
+ const cleanSensitive = sensitive.replace(/[-_]/g, '');
51
+ if (normalized.includes(cleanSensitive) && cleanSensitive.length >= 4) {
52
+ return true;
53
+ }
54
+ }
55
+ return false;
56
+ }
57
+ sanitize(value) {
58
+ const seen = new WeakSet();
59
+ return this.sanitizeRecursive(value, 0, seen);
60
+ }
61
+ sanitizeRecursive(value, depth, seen) {
62
+ if (value === null || value === undefined) {
63
+ return value;
64
+ }
65
+ if (depth > this.maxDepth) {
66
+ return '[Max Depth Reached]';
67
+ }
68
+ const type = typeof value;
69
+ if (type === 'string' || type === 'number' || type === 'boolean') {
70
+ return value;
71
+ }
72
+ if (type === 'bigint') {
73
+ return value.toString() + 'n';
74
+ }
75
+ if (type === 'symbol') {
76
+ return value.toString();
77
+ }
78
+ if (type === 'function') {
79
+ return `[Function: ${value.name || 'anonymous'}]`;
80
+ }
81
+ if (typeof value === 'object') {
82
+ // Check circular reference
83
+ if (seen.has(value)) {
84
+ return '[Circular Reference]';
85
+ }
86
+ seen.add(value);
87
+ // Error handling
88
+ if (value instanceof Error) {
89
+ return {
90
+ name: value.name,
91
+ message: value.message,
92
+ stack: value.stack,
93
+ ...value,
94
+ };
95
+ }
96
+ // Date handling
97
+ if (value instanceof Date) {
98
+ return value.toISOString();
99
+ }
100
+ // RegExp handling
101
+ if (value instanceof RegExp) {
102
+ return value.toString();
103
+ }
104
+ // DOM Node handling
105
+ if (typeof Element !== 'undefined' && value instanceof Element) {
106
+ const id = value.id ? `#${value.id}` : '';
107
+ const className = value.className ? `.${String(value.className).trim().replace(/\s+/g, '.')}` : '';
108
+ return `<${value.tagName.toLowerCase()}${id}${className}>`;
109
+ }
110
+ // Array handling
111
+ if (Array.isArray(value)) {
112
+ const arr = value.slice(0, this.maxArrayLength).map(item => this.sanitizeRecursive(item, depth + 1, seen));
113
+ if (value.length > this.maxArrayLength) {
114
+ arr.push(`[... ${value.length - this.maxArrayLength} more items]`);
115
+ }
116
+ return arr;
117
+ }
118
+ // Map handling
119
+ if (value instanceof Map) {
120
+ const entries = {};
121
+ for (const [k, v] of value.entries()) {
122
+ const keyStr = String(k);
123
+ entries[keyStr] = this.isSensitiveKey(keyStr)
124
+ ? MASK_VALUE
125
+ : this.sanitizeRecursive(v, depth + 1, seen);
126
+ }
127
+ return entries;
128
+ }
129
+ // Set handling
130
+ if (value instanceof Set) {
131
+ return Array.from(value).map(item => this.sanitizeRecursive(item, depth + 1, seen));
132
+ }
133
+ // Plain Object handling
134
+ const result = {};
135
+ const obj = value;
136
+ for (const [key, val] of Object.entries(obj)) {
137
+ if (this.isSensitiveKey(key)) {
138
+ result[key] = MASK_VALUE;
139
+ }
140
+ else {
141
+ result[key] = this.sanitizeRecursive(val, depth + 1, seen);
142
+ }
143
+ }
144
+ return result;
145
+ }
146
+ return String(value);
147
+ }
148
+ }
149
+ const defaultSanitizer = new DataSanitizer();
150
+ function sanitize(value, options) {
151
+ if (!options) {
152
+ return defaultSanitizer.sanitize(value);
153
+ }
154
+ return new DataSanitizer(options).sanitize(value);
155
+ }
156
+
157
+ class CapDebugStore {
158
+ buffer = [];
159
+ maxEvents;
160
+ paused = false;
161
+ listeners = new Set();
162
+ rafId = null;
163
+ customMaskKeys = [];
164
+ filterState = {
165
+ tab: 'all',
166
+ search: '',
167
+ level: 'all',
168
+ source: 'all',
169
+ };
170
+ constructor(maxEvents = 500, customMaskKeys = []) {
171
+ this.maxEvents = Math.max(1, maxEvents);
172
+ this.customMaskKeys = customMaskKeys;
173
+ }
174
+ setMaxEvents(max) {
175
+ this.maxEvents = Math.max(1, max);
176
+ if (this.buffer.length > this.maxEvents) {
177
+ this.buffer = this.buffer.slice(this.buffer.length - this.maxEvents);
178
+ this.notify();
179
+ }
180
+ }
181
+ setCustomMaskKeys(keys) {
182
+ this.customMaskKeys = keys;
183
+ }
184
+ add(event) {
185
+ if (this.paused) {
186
+ return null;
187
+ }
188
+ const sanitizedData = event.data !== undefined
189
+ ? sanitize(event.data, { customMaskKeys: this.customMaskKeys })
190
+ : undefined;
191
+ const fullEvent = {
192
+ id: event.id || this.generateId(),
193
+ timestamp: event.timestamp || Date.now(),
194
+ source: event.source || 'web',
195
+ type: event.type,
196
+ level: event.level || 'info',
197
+ message: event.message,
198
+ data: sanitizedData,
199
+ duration: event.duration,
200
+ platform: event.platform,
201
+ };
202
+ if (this.buffer.length >= this.maxEvents) {
203
+ this.buffer.shift(); // Evict oldest FIFO
204
+ }
205
+ this.buffer.push(fullEvent);
206
+ this.notify();
207
+ return fullEvent;
208
+ }
209
+ clear() {
210
+ this.buffer = [];
211
+ this.notify();
212
+ }
213
+ pause() {
214
+ this.paused = true;
215
+ this.notify();
216
+ }
217
+ resume() {
218
+ this.paused = false;
219
+ this.notify();
220
+ }
221
+ togglePause() {
222
+ this.paused = !this.paused;
223
+ this.notify();
224
+ return this.paused;
225
+ }
226
+ isPaused() {
227
+ return this.paused;
228
+ }
229
+ setFilter(partial) {
230
+ this.filterState = { ...this.filterState, ...partial };
231
+ this.notify();
232
+ }
233
+ getFilter() {
234
+ return this.filterState;
235
+ }
236
+ getAll() {
237
+ return [...this.buffer];
238
+ }
239
+ getCounts() {
240
+ const counts = {
241
+ all: this.buffer.length,
242
+ console: 0,
243
+ errors: 0,
244
+ events: 0,
245
+ native: 0,
246
+ device: 0,
247
+ network: 0,
248
+ bridge: 0,
249
+ };
250
+ for (const ev of this.buffer) {
251
+ if (ev.source === 'console')
252
+ counts.console++;
253
+ if (ev.level === 'error')
254
+ counts.errors++;
255
+ if (ev.source === 'web' || ev.source === 'system')
256
+ counts.events++;
257
+ if (ev.source === 'native')
258
+ counts.native++;
259
+ if (ev.source === 'network')
260
+ counts.network++;
261
+ if (ev.source === 'bridge')
262
+ counts.bridge++;
263
+ }
264
+ return counts;
265
+ }
266
+ getFiltered() {
267
+ const { tab, search, level, source } = this.filterState;
268
+ const query = search.trim().toLowerCase();
269
+ return this.buffer.filter(event => {
270
+ // 1. Tab filtering
271
+ if (tab === 'console' && event.source !== 'console')
272
+ return false;
273
+ if (tab === 'errors' && event.level !== 'error')
274
+ return false;
275
+ if (tab === 'events' && (event.source !== 'web' && event.source !== 'system'))
276
+ return false;
277
+ if (tab === 'native' && event.source !== 'native')
278
+ return false;
279
+ if (tab === 'network' && event.source !== 'network')
280
+ return false;
281
+ if (tab === 'bridge' && event.source !== 'bridge')
282
+ return false;
283
+ // 2. Level filter
284
+ if (level !== 'all' && event.level !== level)
285
+ return false;
286
+ // 3. Source filter
287
+ if (source !== 'all' && event.source !== source)
288
+ return false;
289
+ // 4. Search query
290
+ if (query) {
291
+ const typeMatch = event.type.toLowerCase().includes(query);
292
+ const msgMatch = event.message ? event.message.toLowerCase().includes(query) : false;
293
+ const sourceMatch = event.source.toLowerCase().includes(query);
294
+ if (typeMatch || msgMatch || sourceMatch)
295
+ return true;
296
+ if (event.data) {
297
+ try {
298
+ const dataStr = typeof event.data === 'string'
299
+ ? event.data.toLowerCase()
300
+ : JSON.stringify(event.data).toLowerCase();
301
+ return dataStr.includes(query);
302
+ }
303
+ catch {
304
+ return false;
305
+ }
306
+ }
307
+ return false;
308
+ }
309
+ return true;
310
+ });
311
+ }
312
+ exportJson() {
313
+ return JSON.stringify({
314
+ exportedAt: new Date().toISOString(),
315
+ totalEvents: this.buffer.length,
316
+ events: this.buffer,
317
+ }, null, 2);
318
+ }
319
+ subscribe(listener) {
320
+ this.listeners.add(listener);
321
+ listener(this.getFiltered(), this);
322
+ return () => {
323
+ this.listeners.delete(listener);
324
+ };
325
+ }
326
+ notify() {
327
+ if (typeof window !== 'undefined' && typeof window.requestAnimationFrame === 'function') {
328
+ if (this.rafId !== null) {
329
+ cancelAnimationFrame(this.rafId);
330
+ }
331
+ this.rafId = requestAnimationFrame(() => {
332
+ this.rafId = null;
333
+ this.dispatchToListeners();
334
+ });
335
+ }
336
+ else {
337
+ this.dispatchToListeners();
338
+ }
339
+ }
340
+ dispatchToListeners() {
341
+ const filtered = this.getFiltered();
342
+ for (const listener of this.listeners) {
343
+ try {
344
+ listener(filtered, this);
345
+ }
346
+ catch (err) {
347
+ // Prevent subscriber errors from halting store
348
+ }
349
+ }
350
+ }
351
+ generateId() {
352
+ return 'ev_' + Math.random().toString(36).substring(2, 9) + '_' + Date.now().toString(36);
353
+ }
354
+ }
355
+
356
+ class ConsoleCollector {
357
+ id = 'console';
358
+ running = false;
359
+ originalMethods = {};
360
+ start() {
361
+ if (this.running || typeof console === 'undefined')
362
+ return;
363
+ const methods = [
364
+ { method: 'log', level: 'info' },
365
+ { method: 'info', level: 'info' },
366
+ { method: 'warn', level: 'warn' },
367
+ { method: 'error', level: 'error' },
368
+ { method: 'debug', level: 'debug' },
369
+ ];
370
+ for (const { method, level } of methods) {
371
+ const original = console[method]?.bind(console);
372
+ this.originalMethods[method] = original;
373
+ console[method] = (...args) => {
374
+ // 1. Call original console method
375
+ if (original) {
376
+ try {
377
+ original(...args);
378
+ }
379
+ catch {
380
+ // ignore
381
+ }
382
+ }
383
+ // 2. Dispatch CapDebug event safely
384
+ try {
385
+ this.emitConsoleEvent(method, level, args);
386
+ }
387
+ catch {
388
+ // ignore to prevent crashing host application
389
+ }
390
+ };
391
+ }
392
+ this.running = true;
393
+ }
394
+ stop() {
395
+ if (!this.running || typeof console === 'undefined')
396
+ return;
397
+ for (const method of Object.keys(this.originalMethods)) {
398
+ const original = this.originalMethods[method];
399
+ if (original) {
400
+ console[method] = original;
401
+ }
402
+ }
403
+ this.originalMethods = {};
404
+ this.running = false;
405
+ }
406
+ emitConsoleEvent(method, level, args) {
407
+ if (typeof window === 'undefined')
408
+ return;
409
+ let message = '';
410
+ let data = undefined;
411
+ if (args.length === 1) {
412
+ const arg = args[0];
413
+ if (typeof arg === 'string' || typeof arg === 'number' || typeof arg === 'boolean') {
414
+ message = String(arg);
415
+ }
416
+ else if (arg instanceof Error) {
417
+ message = `${arg.name}: ${arg.message}`;
418
+ data = { name: arg.name, message: arg.message, stack: arg.stack };
419
+ }
420
+ else {
421
+ message = `[${typeof arg}]`;
422
+ data = arg;
423
+ }
424
+ }
425
+ else if (args.length > 1) {
426
+ // Multiple arguments
427
+ const first = args[0];
428
+ if (typeof first === 'string') {
429
+ message = first;
430
+ data = args.slice(1);
431
+ }
432
+ else {
433
+ message = args.map(a => (typeof a === 'object' && a !== null ? '[Object]' : String(a))).join(' ');
434
+ data = args;
435
+ }
436
+ }
437
+ window.dispatchEvent(new CustomEvent('capdebug', {
438
+ detail: {
439
+ source: 'console',
440
+ type: `console.${method}`,
441
+ level,
442
+ message,
443
+ data,
444
+ timestamp: Date.now(),
445
+ },
446
+ }));
447
+ }
448
+ }
449
+
450
+ class ErrorCollector {
451
+ id = 'error';
452
+ running = false;
453
+ errorHandler = null;
454
+ rejectionHandler = null;
455
+ start() {
456
+ if (this.running || typeof window === 'undefined')
457
+ return;
458
+ this.errorHandler = (event) => {
459
+ try {
460
+ const error = event.error;
461
+ const message = event.message || (error && error.message) || 'Uncaught Error';
462
+ const stack = error && error.stack ? error.stack : undefined;
463
+ window.dispatchEvent(new CustomEvent('capdebug', {
464
+ detail: {
465
+ source: 'web',
466
+ type: 'window.error',
467
+ level: 'error',
468
+ message,
469
+ data: {
470
+ filename: event.filename,
471
+ lineno: event.lineno,
472
+ colno: event.colno,
473
+ stack,
474
+ errorName: error?.name,
475
+ },
476
+ timestamp: Date.now(),
477
+ },
478
+ }));
479
+ }
480
+ catch {
481
+ // ignore
482
+ }
483
+ };
484
+ this.rejectionHandler = (event) => {
485
+ try {
486
+ const reason = event.reason;
487
+ let message = 'Unhandled Promise Rejection';
488
+ let stack = undefined;
489
+ let data = reason;
490
+ if (reason instanceof Error) {
491
+ message = `Unhandled Rejection: ${reason.message}`;
492
+ stack = reason.stack;
493
+ data = {
494
+ name: reason.name,
495
+ message: reason.message,
496
+ stack,
497
+ };
498
+ }
499
+ else if (typeof reason === 'string') {
500
+ message = `Unhandled Rejection: ${reason}`;
501
+ }
502
+ window.dispatchEvent(new CustomEvent('capdebug', {
503
+ detail: {
504
+ source: 'web',
505
+ type: 'unhandledrejection',
506
+ level: 'error',
507
+ message,
508
+ data: {
509
+ reason: data,
510
+ stack,
511
+ },
512
+ timestamp: Date.now(),
513
+ },
514
+ }));
515
+ }
516
+ catch {
517
+ // ignore
518
+ }
519
+ };
520
+ window.addEventListener('error', this.errorHandler);
521
+ window.addEventListener('unhandledrejection', this.rejectionHandler);
522
+ this.running = true;
523
+ }
524
+ stop() {
525
+ if (!this.running || typeof window === 'undefined')
526
+ return;
527
+ if (this.errorHandler) {
528
+ window.removeEventListener('error', this.errorHandler);
529
+ this.errorHandler = null;
530
+ }
531
+ if (this.rejectionHandler) {
532
+ window.removeEventListener('unhandledrejection', this.rejectionHandler);
533
+ this.rejectionHandler = null;
534
+ }
535
+ this.running = false;
536
+ }
537
+ }
538
+
539
+ class NetworkCollector {
540
+ id = 'network';
541
+ running = false;
542
+ originalFetch = null;
543
+ options;
544
+ constructor(options = {}) {
545
+ this.options = {
546
+ body: false,
547
+ ...options,
548
+ };
549
+ }
550
+ setOptions(options) {
551
+ this.options = { ...this.options, ...options };
552
+ }
553
+ start() {
554
+ if (this.running || typeof window === 'undefined' || !window.fetch)
555
+ return;
556
+ this.originalFetch = window.fetch;
557
+ const self = this;
558
+ window.fetch = async function (input, init) {
559
+ const startTime = performance.now();
560
+ const timestamp = Date.now();
561
+ let url = '';
562
+ let method = 'GET';
563
+ if (typeof input === 'string') {
564
+ url = input;
565
+ }
566
+ else if (input instanceof URL) {
567
+ url = input.toString();
568
+ }
569
+ else if (typeof Request !== 'undefined' && input instanceof Request) {
570
+ url = input.url;
571
+ method = input.method;
572
+ }
573
+ if (init && init.method) {
574
+ method = init.method.toUpperCase();
575
+ }
576
+ let requestHeaders = {};
577
+ if (init && init.headers) {
578
+ if (typeof Headers !== 'undefined' && init.headers instanceof Headers) {
579
+ init.headers.forEach((value, key) => {
580
+ requestHeaders[key] = value;
581
+ });
582
+ }
583
+ else if (Array.isArray(init.headers)) {
584
+ for (const [k, v] of init.headers) {
585
+ requestHeaders[k] = v;
586
+ }
587
+ }
588
+ else if (typeof init.headers === 'object') {
589
+ requestHeaders = { ...init.headers };
590
+ }
591
+ }
592
+ let requestBody = undefined;
593
+ if (self.options.body && init && init.body) {
594
+ try {
595
+ if (typeof init.body === 'string') {
596
+ try {
597
+ requestBody = JSON.parse(init.body);
598
+ }
599
+ catch {
600
+ requestBody = init.body;
601
+ }
602
+ }
603
+ else {
604
+ requestBody = '[Binary/Stream Body]';
605
+ }
606
+ }
607
+ catch {
608
+ requestBody = '[Unreadable Body]';
609
+ }
610
+ }
611
+ try {
612
+ const response = await self.originalFetch.call(this, input, init);
613
+ const duration = Math.round(performance.now() - startTime);
614
+ let level = 'info';
615
+ if (response.status >= 500) {
616
+ level = 'error';
617
+ }
618
+ else if (response.status >= 400) {
619
+ level = 'warn';
620
+ }
621
+ let responseBody = undefined;
622
+ if (self.options.body) {
623
+ try {
624
+ const clone = response.clone();
625
+ const contentType = clone.headers.get('content-type') || '';
626
+ if (contentType.includes('application/json')) {
627
+ responseBody = await clone.json();
628
+ }
629
+ else if (contentType.includes('text/')) {
630
+ responseBody = await clone.text();
631
+ }
632
+ }
633
+ catch {
634
+ responseBody = '[Could not clone response body]';
635
+ }
636
+ }
637
+ const responseHeaders = {};
638
+ response.headers.forEach((v, k) => {
639
+ responseHeaders[k] = v;
640
+ });
641
+ self.emitNetworkEvent({
642
+ type: `fetch ${method}`,
643
+ level,
644
+ message: `${method} ${url} → ${response.status} ${response.statusText} (${duration}ms)`,
645
+ duration,
646
+ timestamp,
647
+ data: {
648
+ method,
649
+ url,
650
+ status: response.status,
651
+ statusText: response.statusText,
652
+ ok: response.ok,
653
+ duration,
654
+ requestHeaders,
655
+ responseHeaders,
656
+ requestBody,
657
+ responseBody,
658
+ },
659
+ });
660
+ return response;
661
+ }
662
+ catch (err) {
663
+ const duration = Math.round(performance.now() - startTime);
664
+ self.emitNetworkEvent({
665
+ type: `fetch ${method}`,
666
+ level: 'error',
667
+ message: `${method} ${url} → Failed: ${err?.message || 'Network Error'} (${duration}ms)`,
668
+ duration,
669
+ timestamp,
670
+ data: {
671
+ method,
672
+ url,
673
+ error: err?.message || String(err),
674
+ duration,
675
+ requestHeaders,
676
+ requestBody,
677
+ },
678
+ });
679
+ throw err;
680
+ }
681
+ };
682
+ this.running = true;
683
+ }
684
+ stop() {
685
+ if (!this.running || typeof window === 'undefined')
686
+ return;
687
+ if (this.originalFetch) {
688
+ window.fetch = this.originalFetch;
689
+ this.originalFetch = null;
690
+ }
691
+ this.running = false;
692
+ }
693
+ emitNetworkEvent(detail) {
694
+ if (typeof window === 'undefined')
695
+ return;
696
+ try {
697
+ window.dispatchEvent(new CustomEvent('capdebug', {
698
+ detail: {
699
+ source: 'network',
700
+ ...detail,
701
+ },
702
+ }));
703
+ }
704
+ catch {
705
+ // ignore
706
+ }
707
+ }
708
+ }
709
+
710
+ class CustomEventCollector {
711
+ id = 'custom-event';
712
+ store;
713
+ running = false;
714
+ handler = null;
715
+ constructor(store) {
716
+ this.store = store;
717
+ }
718
+ start() {
719
+ if (this.running || typeof window === 'undefined')
720
+ return;
721
+ this.handler = (event) => {
722
+ const customEvent = event;
723
+ if (customEvent && customEvent.detail) {
724
+ const detail = customEvent.detail;
725
+ this.store.add({
726
+ id: detail.id,
727
+ timestamp: detail.timestamp || Date.now(),
728
+ source: detail.source || 'web',
729
+ type: detail.type || 'custom-event',
730
+ level: detail.level || 'info',
731
+ message: detail.message,
732
+ data: detail.data,
733
+ duration: detail.duration,
734
+ platform: detail.platform,
735
+ });
736
+ }
737
+ };
738
+ window.addEventListener('capdebug', this.handler);
739
+ this.running = true;
740
+ }
741
+ stop() {
742
+ if (!this.running || typeof window === 'undefined')
743
+ return;
744
+ if (this.handler) {
745
+ window.removeEventListener('capdebug', this.handler);
746
+ this.handler = null;
747
+ }
748
+ this.running = false;
749
+ }
750
+ }
751
+
752
+ class BrowserEventCollector {
753
+ id = 'browser-event';
754
+ running = false;
755
+ observedEvents = new Map();
756
+ start() {
757
+ this.running = true;
758
+ }
759
+ observe(eventName) {
760
+ if (!this.running || typeof window === 'undefined' || this.observedEvents.has(eventName))
761
+ return;
762
+ const listener = (event) => {
763
+ let data = {
764
+ type: event.type,
765
+ timeStamp: event.timeStamp,
766
+ };
767
+ if (event.type === 'visibilitychange' && typeof document !== 'undefined') {
768
+ data.visibilityState = document.visibilityState;
769
+ data.hidden = document.hidden;
770
+ }
771
+ else if (event.type === 'online' || event.type === 'offline') {
772
+ data.onLine = typeof navigator !== 'undefined' ? navigator.onLine : undefined;
773
+ }
774
+ window.dispatchEvent(new CustomEvent('capdebug', {
775
+ detail: {
776
+ source: 'system',
777
+ type: `event.${eventName}`,
778
+ level: 'info',
779
+ message: `Browser event fired: ${eventName}`,
780
+ data,
781
+ timestamp: Date.now(),
782
+ },
783
+ }));
784
+ };
785
+ const target = eventName === 'visibilitychange' && typeof document !== 'undefined'
786
+ ? document
787
+ : window;
788
+ target.addEventListener(eventName, listener);
789
+ this.observedEvents.set(eventName, listener);
790
+ }
791
+ unobserve(eventName) {
792
+ const listener = this.observedEvents.get(eventName);
793
+ if (!listener)
794
+ return;
795
+ const target = eventName === 'visibilitychange' && typeof document !== 'undefined'
796
+ ? document
797
+ : window;
798
+ target.removeEventListener(eventName, listener);
799
+ this.observedEvents.delete(eventName);
800
+ }
801
+ stop() {
802
+ for (const [eventName, listener] of this.observedEvents.entries()) {
803
+ const target = eventName === 'visibilitychange' && typeof document !== 'undefined'
804
+ ? document
805
+ : window;
806
+ target.removeEventListener(eventName, listener);
807
+ }
808
+ this.observedEvents.clear();
809
+ this.running = false;
810
+ }
811
+ }
812
+
813
+ class BridgeCollector {
814
+ id = 'bridge';
815
+ running = false;
816
+ start() {
817
+ if (this.running)
818
+ return;
819
+ // Reserved for non-intrusive Capacitor bridge telemetry
820
+ this.running = true;
821
+ }
822
+ stop() {
823
+ this.running = false;
824
+ }
825
+ emitBridgeCall(pluginName, methodName, options, duration) {
826
+ if (!this.running || typeof window === 'undefined')
827
+ return;
828
+ window.dispatchEvent(new CustomEvent('capdebug', {
829
+ detail: {
830
+ source: 'bridge',
831
+ type: `${pluginName}.${methodName}`,
832
+ level: 'debug',
833
+ message: `Bridge call: ${pluginName}.${methodName}`,
834
+ data: options,
835
+ duration,
836
+ timestamp: Date.now(),
837
+ },
838
+ }));
839
+ }
840
+ }
841
+
842
+ const VIEWER_STYLES = `
843
+ :host {
844
+ --cd-bg-base: #0d1117;
845
+ --cd-bg-surface: #161b22;
846
+ --cd-bg-surface-elevated: #21262d;
847
+ --cd-bg-hover: #30363d;
848
+ --cd-border: #30363d;
849
+ --cd-border-subtle: #21262d;
850
+
851
+ --cd-text-primary: #f0f6fc;
852
+ --cd-text-secondary: #8b949e;
853
+ --cd-text-muted: #6e7681;
854
+
855
+ --cd-color-brand: #58a6ff;
856
+ --cd-color-brand-rgb: 88, 166, 255;
857
+ --cd-color-info: #38bdf8;
858
+ --cd-color-warn: #fbbf24;
859
+ --cd-color-error: #f87171;
860
+ --cd-color-debug: #c084fc;
861
+ --cd-color-success: #34d399;
862
+
863
+ --cd-font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
864
+ --cd-font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, Consolas, monospace;
865
+
866
+ --cd-z-index: 2147483647;
867
+
868
+ all: initial;
869
+ font-family: var(--cd-font-sans);
870
+ font-size: 13px;
871
+ line-height: 1.4;
872
+ color: var(--cd-text-primary);
873
+ box-sizing: border-box;
874
+ }
875
+
876
+ *, *::before, *::after {
877
+ box-sizing: border-box;
878
+ }
879
+
880
+ /* Floating Trigger Button */
881
+ .cd-floating-btn {
882
+ position: fixed;
883
+ z-index: var(--cd-z-index);
884
+ display: flex;
885
+ align-items: center;
886
+ justify-content: center;
887
+ gap: 6px;
888
+ height: 38px;
889
+ padding: 0 12px;
890
+ background: rgba(22, 27, 34, 0.88);
891
+ backdrop-filter: blur(12px);
892
+ -webkit-backdrop-filter: blur(12px);
893
+ border: 1px solid rgba(240, 246, 252, 0.15);
894
+ border-radius: 9999px;
895
+ color: var(--cd-text-primary);
896
+ cursor: pointer;
897
+ user-select: none;
898
+ -webkit-user-select: none;
899
+ touch-action: none;
900
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4), 0 2px 6px rgba(0, 0, 0, 0.3);
901
+ transition: transform 0.15s ease, background-color 0.2s ease, border-color 0.2s ease;
902
+ }
903
+
904
+ .cd-floating-btn:active {
905
+ transform: scale(0.94);
906
+ }
907
+
908
+ .cd-floating-btn.dragging {
909
+ opacity: 0.85;
910
+ transform: scale(1.05);
911
+ box-shadow: 0 12px 32px rgba(0, 0, 0, 0.6);
912
+ }
913
+
914
+ .cd-btn-logo {
915
+ display: flex;
916
+ align-items: center;
917
+ justify-content: center;
918
+ font-weight: 700;
919
+ font-size: 11px;
920
+ letter-spacing: 0.5px;
921
+ color: #38bdf8;
922
+ font-family: var(--cd-font-mono);
923
+ }
924
+
925
+ .cd-btn-badge {
926
+ display: none;
927
+ align-items: center;
928
+ justify-content: center;
929
+ min-width: 18px;
930
+ height: 18px;
931
+ padding: 0 5px;
932
+ font-size: 10px;
933
+ font-weight: 700;
934
+ font-family: var(--cd-font-mono);
935
+ background: var(--cd-color-error);
936
+ color: #ffffff;
937
+ border-radius: 9999px;
938
+ }
939
+
940
+ .cd-btn-badge.visible {
941
+ display: flex;
942
+ }
943
+
944
+ /* Backdrop */
945
+ .cd-backdrop {
946
+ position: fixed;
947
+ inset: 0;
948
+ z-index: calc(var(--cd-z-index) - 1);
949
+ background: rgba(0, 0, 0, 0.45);
950
+ backdrop-filter: blur(2px);
951
+ opacity: 0;
952
+ pointer-events: none;
953
+ transition: opacity 0.25s cubic-bezier(0.16, 1, 0.3, 1);
954
+ }
955
+
956
+ .cd-backdrop.open {
957
+ opacity: 1;
958
+ pointer-events: auto;
959
+ }
960
+
961
+ /* Main Drawer Panel */
962
+ .cd-panel {
963
+ position: fixed;
964
+ bottom: 0;
965
+ left: 0;
966
+ right: 0;
967
+ z-index: var(--cd-z-index);
968
+ height: 80vh;
969
+ max-height: 85vh;
970
+ background: var(--cd-bg-base);
971
+ border-top: 1px solid var(--cd-border);
972
+ border-top-left-radius: 16px;
973
+ border-top-right-radius: 16px;
974
+ box-shadow: 0 -10px 40px rgba(0, 0, 0, 0.6);
975
+ display: flex;
976
+ flex-direction: column;
977
+ transform: translateY(100%);
978
+ transition: transform 0.28s cubic-bezier(0.32, 0.72, 0, 1);
979
+ padding-bottom: env(safe-area-inset-bottom, 12px);
980
+ }
981
+
982
+ @media (min-width: 768px) {
983
+ .cd-panel {
984
+ bottom: 12px;
985
+ right: 12px;
986
+ left: auto;
987
+ width: 480px;
988
+ height: calc(100vh - 24px);
989
+ max-height: 880px;
990
+ border-radius: 16px;
991
+ border: 1px solid var(--cd-border);
992
+ transform: translateX(calc(100% + 24px));
993
+ padding-bottom: 0;
994
+ }
995
+ }
996
+
997
+ .cd-panel.open {
998
+ transform: translateY(0);
999
+ }
1000
+
1001
+ @media (min-width: 768px) {
1002
+ .cd-panel.open {
1003
+ transform: translateX(0);
1004
+ }
1005
+ }
1006
+
1007
+ /* Panel Header */
1008
+ .cd-header {
1009
+ display: flex;
1010
+ align-items: center;
1011
+ justify-content: space-between;
1012
+ padding: 10px 14px;
1013
+ border-bottom: 1px solid var(--cd-border);
1014
+ background: var(--cd-bg-surface);
1015
+ border-top-left-radius: 16px;
1016
+ border-top-right-radius: 16px;
1017
+ user-select: none;
1018
+ }
1019
+
1020
+ .cd-header-left {
1021
+ display: flex;
1022
+ align-items: center;
1023
+ gap: 8px;
1024
+ }
1025
+
1026
+ .cd-header-title {
1027
+ font-weight: 700;
1028
+ font-size: 13px;
1029
+ font-family: var(--cd-font-mono);
1030
+ color: var(--cd-text-primary);
1031
+ display: flex;
1032
+ align-items: center;
1033
+ gap: 6px;
1034
+ }
1035
+
1036
+ .cd-status-indicator {
1037
+ width: 8px;
1038
+ height: 8px;
1039
+ border-radius: 50%;
1040
+ background: var(--cd-color-success);
1041
+ }
1042
+
1043
+ .cd-status-indicator.paused {
1044
+ background: var(--cd-color-warn);
1045
+ }
1046
+
1047
+ .cd-header-actions {
1048
+ display: flex;
1049
+ align-items: center;
1050
+ gap: 6px;
1051
+ }
1052
+
1053
+ .cd-btn-icon {
1054
+ display: flex;
1055
+ align-items: center;
1056
+ justify-content: center;
1057
+ width: 28px;
1058
+ height: 28px;
1059
+ background: transparent;
1060
+ border: 1px solid transparent;
1061
+ border-radius: 6px;
1062
+ color: var(--cd-text-secondary);
1063
+ cursor: pointer;
1064
+ transition: all 0.15s ease;
1065
+ padding: 0;
1066
+ }
1067
+
1068
+ .cd-btn-icon:hover {
1069
+ background: var(--cd-bg-hover);
1070
+ color: var(--cd-text-primary);
1071
+ border-color: var(--cd-border);
1072
+ }
1073
+
1074
+ .cd-btn-icon.active {
1075
+ background: rgba(251, 191, 36, 0.15);
1076
+ color: var(--cd-color-warn);
1077
+ border-color: rgba(251, 191, 36, 0.3);
1078
+ }
1079
+
1080
+ /* Tabs Bar */
1081
+ .cd-tabs-bar {
1082
+ display: flex;
1083
+ align-items: center;
1084
+ gap: 4px;
1085
+ padding: 6px 10px;
1086
+ background: var(--cd-bg-surface);
1087
+ border-bottom: 1px solid var(--cd-border);
1088
+ overflow-x: auto;
1089
+ scrollbar-width: none;
1090
+ -webkit-overflow-scrolling: touch;
1091
+ }
1092
+
1093
+ .cd-tabs-bar::-webkit-scrollbar {
1094
+ display: none;
1095
+ }
1096
+
1097
+ .cd-tab {
1098
+ display: flex;
1099
+ align-items: center;
1100
+ gap: 6px;
1101
+ padding: 5px 10px;
1102
+ background: transparent;
1103
+ border: 1px solid transparent;
1104
+ border-radius: 6px;
1105
+ color: var(--cd-text-secondary);
1106
+ font-size: 12px;
1107
+ font-weight: 500;
1108
+ cursor: pointer;
1109
+ white-space: nowrap;
1110
+ transition: all 0.15s ease;
1111
+ }
1112
+
1113
+ .cd-tab:hover {
1114
+ background: var(--cd-bg-hover);
1115
+ color: var(--cd-text-primary);
1116
+ }
1117
+
1118
+ .cd-tab.active {
1119
+ background: var(--cd-bg-surface-elevated);
1120
+ border-color: var(--cd-border);
1121
+ color: var(--cd-text-primary);
1122
+ font-weight: 600;
1123
+ }
1124
+
1125
+ .cd-tab-badge {
1126
+ font-size: 10px;
1127
+ font-family: var(--cd-font-mono);
1128
+ padding: 1px 5px;
1129
+ background: var(--cd-bg-hover);
1130
+ border-radius: 10px;
1131
+ color: var(--cd-text-muted);
1132
+ }
1133
+
1134
+ .cd-tab.active .cd-tab-badge {
1135
+ background: rgba(88, 166, 255, 0.2);
1136
+ color: var(--cd-color-brand);
1137
+ }
1138
+
1139
+ /* Toolbar */
1140
+ .cd-toolbar {
1141
+ display: flex;
1142
+ align-items: center;
1143
+ gap: 8px;
1144
+ padding: 8px 12px;
1145
+ background: var(--cd-bg-base);
1146
+ border-bottom: 1px solid var(--cd-border-subtle);
1147
+ }
1148
+
1149
+ .cd-search-input {
1150
+ flex: 1;
1151
+ height: 28px;
1152
+ padding: 0 8px;
1153
+ background: var(--cd-bg-surface);
1154
+ border: 1px solid var(--cd-border);
1155
+ border-radius: 6px;
1156
+ color: var(--cd-text-primary);
1157
+ font-size: 12px;
1158
+ outline: none;
1159
+ transition: border-color 0.15s ease;
1160
+ }
1161
+
1162
+ .cd-search-input:focus {
1163
+ border-color: var(--cd-color-brand);
1164
+ }
1165
+
1166
+ .cd-search-input::placeholder {
1167
+ color: var(--cd-text-muted);
1168
+ }
1169
+
1170
+ .cd-level-filters {
1171
+ display: flex;
1172
+ align-items: center;
1173
+ gap: 4px;
1174
+ }
1175
+
1176
+ .cd-level-pill {
1177
+ padding: 3px 7px;
1178
+ border-radius: 4px;
1179
+ font-size: 11px;
1180
+ font-weight: 600;
1181
+ background: transparent;
1182
+ border: 1px solid var(--cd-border-subtle);
1183
+ color: var(--cd-text-muted);
1184
+ cursor: pointer;
1185
+ transition: all 0.12s ease;
1186
+ }
1187
+
1188
+ .cd-level-pill:hover {
1189
+ border-color: var(--cd-border);
1190
+ color: var(--cd-text-secondary);
1191
+ }
1192
+
1193
+ .cd-level-pill.active {
1194
+ background: var(--cd-bg-surface-elevated);
1195
+ border-color: var(--cd-border);
1196
+ color: var(--cd-text-primary);
1197
+ }
1198
+
1199
+ .cd-level-pill[data-level="error"].active {
1200
+ background: rgba(248, 113, 113, 0.15);
1201
+ border-color: rgba(248, 113, 113, 0.3);
1202
+ color: var(--cd-color-error);
1203
+ }
1204
+
1205
+ .cd-level-pill[data-level="warn"].active {
1206
+ background: rgba(251, 191, 36, 0.15);
1207
+ border-color: rgba(251, 191, 36, 0.3);
1208
+ color: var(--cd-color-warn);
1209
+ }
1210
+
1211
+ /* Event List */
1212
+ .cd-content {
1213
+ flex: 1;
1214
+ overflow-y: auto;
1215
+ position: relative;
1216
+ -webkit-overflow-scrolling: touch;
1217
+ }
1218
+
1219
+ .cd-event-list {
1220
+ display: flex;
1221
+ flex-direction: column;
1222
+ }
1223
+
1224
+ .cd-event-row {
1225
+ display: flex;
1226
+ align-items: flex-start;
1227
+ gap: 8px;
1228
+ padding: 8px 12px;
1229
+ border-bottom: 1px solid var(--cd-border-subtle);
1230
+ cursor: pointer;
1231
+ transition: background-color 0.12s ease;
1232
+ font-family: var(--cd-font-mono);
1233
+ font-size: 11.5px;
1234
+ }
1235
+
1236
+ .cd-event-row:hover {
1237
+ background: var(--cd-bg-surface);
1238
+ }
1239
+
1240
+ .cd-event-level-dot {
1241
+ width: 6px;
1242
+ height: 6px;
1243
+ border-radius: 50%;
1244
+ margin-top: 5px;
1245
+ flex-shrink: 0;
1246
+ background: var(--cd-text-muted);
1247
+ }
1248
+
1249
+ .cd-event-row[data-level="info"] .cd-event-level-dot { background: var(--cd-color-info); }
1250
+ .cd-event-row[data-level="warn"] .cd-event-level-dot { background: var(--cd-color-warn); }
1251
+ .cd-event-row[data-level="error"] .cd-event-level-dot { background: var(--cd-color-error); }
1252
+ .cd-event-row[data-level="debug"] .cd-event-level-dot { background: var(--cd-color-debug); }
1253
+
1254
+ .cd-event-time {
1255
+ color: var(--cd-text-muted);
1256
+ font-size: 10.5px;
1257
+ flex-shrink: 0;
1258
+ margin-top: 1px;
1259
+ }
1260
+
1261
+ .cd-event-source {
1262
+ padding: 1px 5px;
1263
+ border-radius: 3px;
1264
+ background: var(--cd-bg-surface-elevated);
1265
+ color: var(--cd-text-secondary);
1266
+ font-size: 10px;
1267
+ font-weight: 600;
1268
+ text-transform: uppercase;
1269
+ flex-shrink: 0;
1270
+ }
1271
+
1272
+ .cd-event-main {
1273
+ flex: 1;
1274
+ min-width: 0;
1275
+ display: flex;
1276
+ flex-direction: column;
1277
+ gap: 2px;
1278
+ }
1279
+
1280
+ .cd-event-type {
1281
+ font-weight: 600;
1282
+ color: var(--cd-text-primary);
1283
+ overflow: hidden;
1284
+ text-overflow: ellipsis;
1285
+ white-space: nowrap;
1286
+ }
1287
+
1288
+ .cd-event-msg {
1289
+ color: var(--cd-text-secondary);
1290
+ overflow: hidden;
1291
+ text-overflow: ellipsis;
1292
+ white-space: nowrap;
1293
+ font-size: 11px;
1294
+ }
1295
+
1296
+ .cd-event-duration {
1297
+ font-size: 10px;
1298
+ padding: 1px 4px;
1299
+ border-radius: 3px;
1300
+ background: rgba(88, 166, 255, 0.1);
1301
+ color: var(--cd-color-brand);
1302
+ flex-shrink: 0;
1303
+ }
1304
+
1305
+ .cd-empty-state {
1306
+ display: flex;
1307
+ flex-direction: column;
1308
+ align-items: center;
1309
+ justify-content: center;
1310
+ height: 200px;
1311
+ color: var(--cd-text-muted);
1312
+ gap: 8px;
1313
+ font-size: 12px;
1314
+ }
1315
+
1316
+ /* Detail Modal Overlay */
1317
+ .cd-detail-overlay {
1318
+ position: absolute;
1319
+ inset: 0;
1320
+ background: var(--cd-bg-base);
1321
+ z-index: 10;
1322
+ display: flex;
1323
+ flex-direction: column;
1324
+ transform: translateX(100%);
1325
+ transition: transform 0.22s cubic-bezier(0.16, 1, 0.3, 1);
1326
+ }
1327
+
1328
+ .cd-detail-overlay.open {
1329
+ transform: translateX(0);
1330
+ }
1331
+
1332
+ .cd-detail-header {
1333
+ display: flex;
1334
+ align-items: center;
1335
+ justify-content: space-between;
1336
+ padding: 10px 14px;
1337
+ border-bottom: 1px solid var(--cd-border);
1338
+ background: var(--cd-bg-surface);
1339
+ }
1340
+
1341
+ .cd-detail-back {
1342
+ display: flex;
1343
+ align-items: center;
1344
+ gap: 6px;
1345
+ background: transparent;
1346
+ border: none;
1347
+ color: var(--cd-color-brand);
1348
+ font-size: 12px;
1349
+ font-weight: 600;
1350
+ cursor: pointer;
1351
+ padding: 4px 6px;
1352
+ border-radius: 4px;
1353
+ }
1354
+
1355
+ .cd-detail-back:hover {
1356
+ background: var(--cd-bg-hover);
1357
+ }
1358
+
1359
+ .cd-detail-body {
1360
+ flex: 1;
1361
+ overflow-y: auto;
1362
+ padding: 14px;
1363
+ display: flex;
1364
+ flex-direction: column;
1365
+ gap: 14px;
1366
+ font-family: var(--cd-font-mono);
1367
+ font-size: 12px;
1368
+ }
1369
+
1370
+ .cd-meta-grid {
1371
+ display: grid;
1372
+ grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
1373
+ gap: 8px;
1374
+ padding: 10px;
1375
+ background: var(--cd-bg-surface);
1376
+ border: 1px solid var(--cd-border-subtle);
1377
+ border-radius: 8px;
1378
+ }
1379
+
1380
+ .cd-meta-item {
1381
+ display: flex;
1382
+ flex-direction: column;
1383
+ gap: 2px;
1384
+ }
1385
+
1386
+ .cd-meta-label {
1387
+ font-size: 10px;
1388
+ text-transform: uppercase;
1389
+ color: var(--cd-text-muted);
1390
+ font-weight: 600;
1391
+ }
1392
+
1393
+ .cd-meta-val {
1394
+ font-size: 11.5px;
1395
+ color: var(--cd-text-primary);
1396
+ word-break: break-all;
1397
+ }
1398
+
1399
+ .cd-section-title {
1400
+ font-size: 11px;
1401
+ text-transform: uppercase;
1402
+ color: var(--cd-text-muted);
1403
+ font-weight: 700;
1404
+ margin-top: 6px;
1405
+ display: flex;
1406
+ align-items: center;
1407
+ justify-content: space-between;
1408
+ }
1409
+
1410
+ .cd-msg-block {
1411
+ padding: 10px;
1412
+ background: var(--cd-bg-surface);
1413
+ border: 1px solid var(--cd-border-subtle);
1414
+ border-radius: 8px;
1415
+ color: var(--cd-text-primary);
1416
+ white-space: pre-wrap;
1417
+ word-break: break-word;
1418
+ line-height: 1.5;
1419
+ }
1420
+
1421
+ /* Device Tab View */
1422
+ .cd-device-view {
1423
+ padding: 14px;
1424
+ display: flex;
1425
+ flex-direction: column;
1426
+ gap: 14px;
1427
+ }
1428
+
1429
+ .cd-device-card {
1430
+ background: var(--cd-bg-surface);
1431
+ border: 1px solid var(--cd-border);
1432
+ border-radius: 8px;
1433
+ padding: 12px;
1434
+ display: flex;
1435
+ flex-direction: column;
1436
+ gap: 8px;
1437
+ }
1438
+
1439
+ .cd-device-card-header {
1440
+ display: flex;
1441
+ align-items: center;
1442
+ justify-content: space-between;
1443
+ font-weight: 700;
1444
+ font-size: 12px;
1445
+ color: var(--cd-color-brand);
1446
+ border-bottom: 1px solid var(--cd-border-subtle);
1447
+ padding-bottom: 6px;
1448
+ }
1449
+
1450
+ .cd-device-grid {
1451
+ display: grid;
1452
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
1453
+ gap: 8px;
1454
+ }
1455
+
1456
+ /* Collapsible JSON Viewer */
1457
+ .cd-json-tree {
1458
+ background: var(--cd-bg-surface);
1459
+ border: 1px solid var(--cd-border-subtle);
1460
+ border-radius: 8px;
1461
+ padding: 10px;
1462
+ font-family: var(--cd-font-mono);
1463
+ font-size: 11.5px;
1464
+ line-height: 1.5;
1465
+ overflow-x: auto;
1466
+ }
1467
+
1468
+ .cd-json-node {
1469
+ display: block;
1470
+ }
1471
+
1472
+ .cd-json-row {
1473
+ display: flex;
1474
+ align-items: flex-start;
1475
+ gap: 4px;
1476
+ padding: 1px 0;
1477
+ }
1478
+
1479
+ .cd-json-toggle {
1480
+ display: inline-flex;
1481
+ align-items: center;
1482
+ justify-content: center;
1483
+ width: 14px;
1484
+ height: 14px;
1485
+ cursor: pointer;
1486
+ user-select: none;
1487
+ color: var(--cd-text-muted);
1488
+ font-size: 9px;
1489
+ transition: transform 0.1s ease;
1490
+ }
1491
+
1492
+ .cd-json-toggle.collapsed {
1493
+ transform: rotate(-90deg);
1494
+ }
1495
+
1496
+ .cd-json-key {
1497
+ color: #7ee787;
1498
+ }
1499
+
1500
+ .cd-json-colon {
1501
+ color: var(--cd-text-muted);
1502
+ }
1503
+
1504
+ .cd-json-string {
1505
+ color: #a5d6ff;
1506
+ word-break: break-all;
1507
+ }
1508
+
1509
+ .cd-json-number {
1510
+ color: #79c0ff;
1511
+ }
1512
+
1513
+ .cd-json-boolean {
1514
+ color: #ff7b72;
1515
+ }
1516
+
1517
+ .cd-json-null {
1518
+ color: var(--cd-text-muted);
1519
+ font-style: italic;
1520
+ }
1521
+
1522
+ .cd-json-copy-btn {
1523
+ opacity: 0;
1524
+ padding: 1px 4px;
1525
+ font-size: 9px;
1526
+ background: var(--cd-bg-hover);
1527
+ border: 1px solid var(--cd-border);
1528
+ border-radius: 3px;
1529
+ color: var(--cd-text-secondary);
1530
+ cursor: pointer;
1531
+ margin-left: 6px;
1532
+ }
1533
+
1534
+ .cd-json-row:hover .cd-json-copy-btn {
1535
+ opacity: 1;
1536
+ }
1537
+
1538
+ .cd-json-children {
1539
+ padding-left: 14px;
1540
+ border-left: 1px solid var(--cd-border-subtle);
1541
+ margin-left: 6px;
1542
+ }
1543
+
1544
+ .cd-json-children.hidden {
1545
+ display: none;
1546
+ }
1547
+
1548
+ /* Small UI helpers */
1549
+ .cd-copy-btn-sm {
1550
+ background: var(--cd-bg-surface-elevated);
1551
+ border: 1px solid var(--cd-border);
1552
+ border-radius: 4px;
1553
+ color: var(--cd-text-secondary);
1554
+ font-size: 10px;
1555
+ padding: 3px 8px;
1556
+ cursor: pointer;
1557
+ transition: all 0.15s ease;
1558
+ }
1559
+
1560
+ .cd-copy-btn-sm:hover {
1561
+ background: var(--cd-bg-hover);
1562
+ color: var(--cd-text-primary);
1563
+ }
1564
+ `;
1565
+
1566
+ const STORAGE_KEY = 'capdebug_btn_pos';
1567
+ class FloatingButton {
1568
+ element;
1569
+ badgeElement;
1570
+ options;
1571
+ isDragging = false;
1572
+ hasMoved = false;
1573
+ startX = 0;
1574
+ startY = 0;
1575
+ initialLeft = 0;
1576
+ initialTop = 0;
1577
+ constructor(options = {}) {
1578
+ this.options = {
1579
+ position: 'right',
1580
+ persistPosition: true,
1581
+ ...options,
1582
+ };
1583
+ this.element = document.createElement('div');
1584
+ this.element.className = 'cd-floating-btn';
1585
+ this.element.setAttribute('role', 'button');
1586
+ this.element.setAttribute('aria-label', 'Open CapDebug');
1587
+ const logo = document.createElement('span');
1588
+ logo.className = 'cd-btn-logo';
1589
+ logo.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 4px"><path d="m8 2 1.88 1.88"/><path d="M14.12 3.88 16 2"/><path d="M9 7.13v-1a3.003 3.003 0 1 1 6 0v1"/><path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6"/><path d="M12 20v-9"/><path d="M6.53 9C4.6 8.8 3 7.1 3 5"/><path d="M6 13H2"/><path d="M3 21c0-2.1 1.7-3.9 3.8-4"/><path d="M20.97 5c0 2.1-1.6 3.8-3.5 4"/><path d="M22 13h-4"/><path d="M17.2 17c2.1.1 3.8 1.9 3.8 4"/></svg>CAP`;
1590
+ this.badgeElement = document.createElement('span');
1591
+ this.badgeElement.className = 'cd-btn-badge';
1592
+ this.badgeElement.textContent = '0';
1593
+ this.element.appendChild(logo);
1594
+ this.element.appendChild(this.badgeElement);
1595
+ this.initPosition();
1596
+ this.bindEvents();
1597
+ }
1598
+ getElement() {
1599
+ return this.element;
1600
+ }
1601
+ setErrorCount(count) {
1602
+ if (count > 0) {
1603
+ this.badgeElement.textContent = count > 99 ? '99+' : String(count);
1604
+ this.badgeElement.classList.add('visible');
1605
+ }
1606
+ else {
1607
+ this.badgeElement.classList.remove('visible');
1608
+ }
1609
+ }
1610
+ show() {
1611
+ this.element.style.display = 'flex';
1612
+ }
1613
+ hide() {
1614
+ this.element.style.display = 'none';
1615
+ }
1616
+ initPosition() {
1617
+ let savedPos = null;
1618
+ if (this.options.persistPosition && typeof localStorage !== 'undefined') {
1619
+ try {
1620
+ const stored = localStorage.getItem(STORAGE_KEY);
1621
+ if (stored) {
1622
+ savedPos = JSON.parse(stored);
1623
+ }
1624
+ }
1625
+ catch {
1626
+ // ignore
1627
+ }
1628
+ }
1629
+ const windowWidth = typeof window !== 'undefined' ? window.innerWidth : 400;
1630
+ const windowHeight = typeof window !== 'undefined' ? window.innerHeight : 800;
1631
+ let x = windowWidth - 76;
1632
+ let y = Math.max(80, windowHeight * 0.4);
1633
+ if (savedPos && typeof savedPos.x === 'number' && typeof savedPos.y === 'number') {
1634
+ x = Math.min(Math.max(10, savedPos.x), windowWidth - 76);
1635
+ y = Math.min(Math.max(60, savedPos.y), windowHeight - 60);
1636
+ }
1637
+ else if (typeof this.options.position === 'object') {
1638
+ x = this.options.position.x;
1639
+ y = this.options.position.y;
1640
+ }
1641
+ else if (this.options.position === 'left') {
1642
+ x = 12;
1643
+ }
1644
+ this.setPosition(x, y);
1645
+ }
1646
+ setPosition(x, y) {
1647
+ this.element.style.left = `${x}px`;
1648
+ this.element.style.top = `${y}px`;
1649
+ this.element.style.right = 'auto';
1650
+ this.element.style.bottom = 'auto';
1651
+ }
1652
+ bindEvents() {
1653
+ const onPointerDown = (e) => {
1654
+ this.isDragging = true;
1655
+ this.hasMoved = false;
1656
+ this.startX = e.clientX;
1657
+ this.startY = e.clientY;
1658
+ const rect = this.element.getBoundingClientRect();
1659
+ this.initialLeft = rect.left;
1660
+ this.initialTop = rect.top;
1661
+ this.element.classList.add('dragging');
1662
+ this.element.setPointerCapture(e.pointerId);
1663
+ };
1664
+ const onPointerMove = (e) => {
1665
+ if (!this.isDragging)
1666
+ return;
1667
+ const deltaX = e.clientX - this.startX;
1668
+ const deltaY = e.clientY - this.startY;
1669
+ if (Math.abs(deltaX) > 4 || Math.abs(deltaY) > 4) {
1670
+ this.hasMoved = true;
1671
+ }
1672
+ let newX = this.initialLeft + deltaX;
1673
+ let newY = this.initialTop + deltaY;
1674
+ const maxX = window.innerWidth - this.element.offsetWidth - 8;
1675
+ const maxY = window.innerHeight - this.element.offsetHeight - 8;
1676
+ newX = Math.max(8, Math.min(newX, maxX));
1677
+ newY = Math.max(40, Math.min(newY, maxY));
1678
+ this.setPosition(newX, newY);
1679
+ };
1680
+ const onPointerUp = (e) => {
1681
+ if (!this.isDragging)
1682
+ return;
1683
+ this.isDragging = false;
1684
+ this.element.classList.remove('dragging');
1685
+ try {
1686
+ this.element.releasePointerCapture(e.pointerId);
1687
+ }
1688
+ catch {
1689
+ // ignore
1690
+ }
1691
+ if (!this.hasMoved) {
1692
+ // Tap / Click action
1693
+ if (this.options.onClick) {
1694
+ this.options.onClick();
1695
+ }
1696
+ }
1697
+ else {
1698
+ // Snap to nearest edge (left or right)
1699
+ this.snapToEdge();
1700
+ }
1701
+ };
1702
+ this.element.addEventListener('pointerdown', onPointerDown);
1703
+ this.element.addEventListener('pointermove', onPointerMove);
1704
+ this.element.addEventListener('pointerup', onPointerUp);
1705
+ this.element.addEventListener('pointercancel', onPointerUp);
1706
+ }
1707
+ snapToEdge() {
1708
+ const rect = this.element.getBoundingClientRect();
1709
+ const windowWidth = window.innerWidth;
1710
+ const windowHeight = window.innerHeight;
1711
+ const snapLeft = 12;
1712
+ const snapRight = windowWidth - rect.width - 12;
1713
+ const targetX = rect.left + rect.width / 2 < windowWidth / 2 ? snapLeft : snapRight;
1714
+ const targetY = Math.max(50, Math.min(rect.top, windowHeight - rect.height - 50));
1715
+ this.element.style.transition = 'left 0.2s cubic-bezier(0.16, 1, 0.3, 1), top 0.2s cubic-bezier(0.16, 1, 0.3, 1)';
1716
+ this.setPosition(targetX, targetY);
1717
+ setTimeout(() => {
1718
+ this.element.style.transition = '';
1719
+ }, 200);
1720
+ if (this.options.persistPosition && typeof localStorage !== 'undefined') {
1721
+ try {
1722
+ localStorage.setItem(STORAGE_KEY, JSON.stringify({ x: targetX, y: targetY }));
1723
+ }
1724
+ catch {
1725
+ // ignore
1726
+ }
1727
+ }
1728
+ }
1729
+ }
1730
+
1731
+ class JsonViewer {
1732
+ static render(data, initialExpandedDepth = 2) {
1733
+ const container = document.createElement('div');
1734
+ container.className = 'cd-json-tree';
1735
+ if (data === undefined) {
1736
+ const undefinedSpan = document.createElement('span');
1737
+ undefinedSpan.className = 'cd-json-null';
1738
+ undefinedSpan.textContent = 'undefined';
1739
+ container.appendChild(undefinedSpan);
1740
+ return container;
1741
+ }
1742
+ const rootNode = JsonViewer.renderNode('', data, 0, initialExpandedDepth);
1743
+ container.appendChild(rootNode);
1744
+ return container;
1745
+ }
1746
+ static renderNode(key, value, depth, maxExpandedDepth) {
1747
+ const node = document.createElement('div');
1748
+ node.className = 'cd-json-node';
1749
+ const row = document.createElement('div');
1750
+ row.className = 'cd-json-row';
1751
+ const isObject = typeof value === 'object' && value !== null;
1752
+ const isArray = Array.isArray(value);
1753
+ // Toggle button for objects/arrays
1754
+ if (isObject) {
1755
+ const toggle = document.createElement('span');
1756
+ toggle.className = 'cd-json-toggle';
1757
+ toggle.innerHTML = '▼';
1758
+ row.appendChild(toggle);
1759
+ }
1760
+ else {
1761
+ const spacer = document.createElement('span');
1762
+ spacer.style.width = '14px';
1763
+ spacer.style.display = 'inline-block';
1764
+ row.appendChild(spacer);
1765
+ }
1766
+ // Key (if present)
1767
+ if (key !== '') {
1768
+ const keySpan = document.createElement('span');
1769
+ keySpan.className = 'cd-json-key';
1770
+ keySpan.textContent = typeof key === 'number' ? `[${key}]` : `"${key}"`;
1771
+ row.appendChild(keySpan);
1772
+ const colonSpan = document.createElement('span');
1773
+ colonSpan.className = 'cd-json-colon';
1774
+ colonSpan.textContent = ': ';
1775
+ row.appendChild(colonSpan);
1776
+ }
1777
+ // Value preview or primitive
1778
+ if (isObject) {
1779
+ const entries = isArray
1780
+ ? value.map((v, i) => [i, v])
1781
+ : Object.entries(value);
1782
+ const bracketOpen = isArray ? '[' : '{';
1783
+ const bracketClose = isArray ? ']' : '}';
1784
+ const previewSpan = document.createElement('span');
1785
+ previewSpan.className = 'cd-json-colon';
1786
+ previewSpan.textContent = `${bracketOpen} ${entries.length} ${isArray ? 'items' : 'keys'} ${bracketClose}`;
1787
+ row.appendChild(previewSpan);
1788
+ // Copy object JSON button
1789
+ const copyBtn = document.createElement('button');
1790
+ copyBtn.className = 'cd-json-copy-btn';
1791
+ copyBtn.textContent = 'copy';
1792
+ copyBtn.title = 'Copy branch JSON';
1793
+ copyBtn.addEventListener('click', e => {
1794
+ e.stopPropagation();
1795
+ JsonViewer.copyToClipboard(JSON.stringify(value, null, 2), copyBtn);
1796
+ });
1797
+ row.appendChild(copyBtn);
1798
+ node.appendChild(row);
1799
+ // Children container
1800
+ const childrenContainer = document.createElement('div');
1801
+ childrenContainer.className = 'cd-json-children';
1802
+ const isInitiallyExpanded = depth < maxExpandedDepth;
1803
+ if (!isInitiallyExpanded) {
1804
+ childrenContainer.classList.add('hidden');
1805
+ const toggle = row.querySelector('.cd-json-toggle');
1806
+ if (toggle)
1807
+ toggle.classList.add('collapsed');
1808
+ }
1809
+ for (const [childKey, childVal] of entries) {
1810
+ childrenContainer.appendChild(JsonViewer.renderNode(childKey, childVal, depth + 1, maxExpandedDepth));
1811
+ }
1812
+ node.appendChild(childrenContainer);
1813
+ // Toggle collapse on row or toggle click
1814
+ row.addEventListener('click', e => {
1815
+ if (e.target.tagName.toLowerCase() === 'button')
1816
+ return;
1817
+ const toggle = row.querySelector('.cd-json-toggle');
1818
+ const isHidden = childrenContainer.classList.toggle('hidden');
1819
+ if (toggle) {
1820
+ toggle.classList.toggle('collapsed', isHidden);
1821
+ }
1822
+ });
1823
+ }
1824
+ else {
1825
+ // Primitive value
1826
+ const valSpan = document.createElement('span');
1827
+ const valType = typeof value;
1828
+ if (value === null) {
1829
+ valSpan.className = 'cd-json-null';
1830
+ valSpan.textContent = 'null';
1831
+ }
1832
+ else if (valType === 'string') {
1833
+ valSpan.className = 'cd-json-string';
1834
+ valSpan.textContent = `"${value}"`;
1835
+ }
1836
+ else if (valType === 'number') {
1837
+ valSpan.className = 'cd-json-number';
1838
+ valSpan.textContent = String(value);
1839
+ }
1840
+ else if (valType === 'boolean') {
1841
+ valSpan.className = 'cd-json-boolean';
1842
+ valSpan.textContent = String(value);
1843
+ }
1844
+ else {
1845
+ valSpan.className = 'cd-json-null';
1846
+ valSpan.textContent = String(value);
1847
+ }
1848
+ row.appendChild(valSpan);
1849
+ // Copy primitive value button
1850
+ const copyBtn = document.createElement('button');
1851
+ copyBtn.className = 'cd-json-copy-btn';
1852
+ copyBtn.textContent = 'copy';
1853
+ copyBtn.title = 'Copy value';
1854
+ copyBtn.addEventListener('click', e => {
1855
+ e.stopPropagation();
1856
+ JsonViewer.copyToClipboard(String(value), copyBtn);
1857
+ });
1858
+ row.appendChild(copyBtn);
1859
+ node.appendChild(row);
1860
+ }
1861
+ return node;
1862
+ }
1863
+ static async copyToClipboard(text, triggerBtn) {
1864
+ try {
1865
+ if (navigator.clipboard && window.isSecureContext) {
1866
+ await navigator.clipboard.writeText(text);
1867
+ }
1868
+ else {
1869
+ const textarea = document.createElement('textarea');
1870
+ textarea.value = text;
1871
+ textarea.style.position = 'fixed';
1872
+ textarea.style.left = '-9999px';
1873
+ textarea.style.top = '-9999px';
1874
+ document.body.appendChild(textarea);
1875
+ textarea.focus();
1876
+ textarea.select();
1877
+ document.execCommand('copy');
1878
+ document.body.removeChild(textarea);
1879
+ }
1880
+ if (triggerBtn) {
1881
+ const originalText = triggerBtn.textContent;
1882
+ triggerBtn.textContent = 'copied!';
1883
+ triggerBtn.style.color = '#34d399';
1884
+ setTimeout(() => {
1885
+ triggerBtn.textContent = originalText;
1886
+ triggerBtn.style.color = '';
1887
+ }, 1500);
1888
+ }
1889
+ return true;
1890
+ }
1891
+ catch {
1892
+ return false;
1893
+ }
1894
+ }
1895
+ }
1896
+
1897
+ const CapDebugNative = registerPlugin('CapDebug', {
1898
+ web: () => Promise.resolve().then(function () { return web; }).then(m => new m.CapDebugWeb()),
1899
+ });
1900
+
1901
+ class DebugPanel {
1902
+ element;
1903
+ backdrop;
1904
+ store;
1905
+ options;
1906
+ isOpen = false;
1907
+ // Header UI
1908
+ statusIndicator;
1909
+ titleCountSpan;
1910
+ pauseBtn;
1911
+ // Tab elements
1912
+ tabElements = new Map();
1913
+ tabBadgeElements = new Map();
1914
+ // Search & Filter UI
1915
+ searchInput;
1916
+ levelPills = new Map();
1917
+ // Content
1918
+ contentContainer;
1919
+ eventListContainer;
1920
+ deviceViewContainer;
1921
+ // Detail Overlay
1922
+ detailOverlay;
1923
+ selectedEvent = null;
1924
+ // Device tab state
1925
+ isDeviceLoading = false;
1926
+ deviceData = null;
1927
+ constructor(store, options = {}) {
1928
+ this.store = store;
1929
+ this.options = {
1930
+ defaultTab: 'all',
1931
+ ...options,
1932
+ };
1933
+ this.backdrop = document.createElement('div');
1934
+ this.backdrop.className = 'cd-backdrop';
1935
+ this.element = document.createElement('div');
1936
+ this.element.className = 'cd-panel';
1937
+ this.buildUI();
1938
+ this.bindStore();
1939
+ if (this.options.defaultTab) {
1940
+ this.store.setFilter({ tab: this.options.defaultTab });
1941
+ }
1942
+ }
1943
+ getElement() {
1944
+ return this.element;
1945
+ }
1946
+ getBackdrop() {
1947
+ return this.backdrop;
1948
+ }
1949
+ open() {
1950
+ this.isOpen = true;
1951
+ this.element.classList.add('open');
1952
+ this.backdrop.classList.add('open');
1953
+ // If device tab is active, trigger lazy load
1954
+ if (this.store.getFilter().tab === 'device') {
1955
+ this.loadDeviceDiagnostics();
1956
+ }
1957
+ }
1958
+ close() {
1959
+ this.isOpen = false;
1960
+ this.element.classList.remove('open');
1961
+ this.backdrop.classList.remove('open');
1962
+ this.closeDetail();
1963
+ if (this.options.onClose) {
1964
+ this.options.onClose();
1965
+ }
1966
+ }
1967
+ toggle() {
1968
+ if (this.isOpen) {
1969
+ this.close();
1970
+ return false;
1971
+ }
1972
+ else {
1973
+ this.open();
1974
+ return true;
1975
+ }
1976
+ }
1977
+ isPanelOpen() {
1978
+ return this.isOpen;
1979
+ }
1980
+ buildUI() {
1981
+ this.backdrop.addEventListener('click', () => this.close());
1982
+ // 1. Header
1983
+ const header = document.createElement('div');
1984
+ header.className = 'cd-header';
1985
+ const headerLeft = document.createElement('div');
1986
+ headerLeft.className = 'cd-header-left';
1987
+ this.statusIndicator = document.createElement('div');
1988
+ this.statusIndicator.className = 'cd-status-indicator';
1989
+ this.statusIndicator.title = 'CapDebug Active';
1990
+ const headerTitle = document.createElement('div');
1991
+ headerTitle.className = 'cd-header-title';
1992
+ headerTitle.innerHTML = `<span>CapDebug</span>`;
1993
+ this.titleCountSpan = document.createElement('span');
1994
+ this.titleCountSpan.style.color = 'var(--cd-text-muted)';
1995
+ this.titleCountSpan.style.fontSize = '11px';
1996
+ this.titleCountSpan.textContent = '(0)';
1997
+ headerTitle.appendChild(this.titleCountSpan);
1998
+ headerLeft.appendChild(this.statusIndicator);
1999
+ headerLeft.appendChild(headerTitle);
2000
+ const headerActions = document.createElement('div');
2001
+ headerActions.className = 'cd-header-actions';
2002
+ // Pause/Resume Button
2003
+ this.pauseBtn = document.createElement('button');
2004
+ this.pauseBtn.className = 'cd-btn-icon';
2005
+ this.pauseBtn.title = 'Pause/Resume capture';
2006
+ this.pauseBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="6" y="4" width="4" height="16"/><rect x="14" y="4" width="4" height="16"/></svg>`;
2007
+ this.pauseBtn.addEventListener('click', () => {
2008
+ const isPaused = this.store.togglePause();
2009
+ this.updatePauseState(isPaused);
2010
+ });
2011
+ // Clear Button
2012
+ const clearBtn = document.createElement('button');
2013
+ clearBtn.className = 'cd-btn-icon';
2014
+ clearBtn.title = 'Clear events';
2015
+ clearBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/></svg>`;
2016
+ clearBtn.addEventListener('click', () => {
2017
+ this.store.clear();
2018
+ this.closeDetail();
2019
+ });
2020
+ // Export Button
2021
+ const exportBtn = document.createElement('button');
2022
+ exportBtn.className = 'cd-btn-icon';
2023
+ exportBtn.title = 'Export JSON to clipboard';
2024
+ exportBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>`;
2025
+ exportBtn.addEventListener('click', async () => {
2026
+ const json = this.store.exportJson();
2027
+ await JsonViewer.copyToClipboard(json, exportBtn);
2028
+ });
2029
+ // Close Button
2030
+ const closeBtn = document.createElement('button');
2031
+ closeBtn.className = 'cd-btn-icon';
2032
+ closeBtn.title = 'Close viewer';
2033
+ closeBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`;
2034
+ closeBtn.addEventListener('click', () => this.close());
2035
+ headerActions.appendChild(this.pauseBtn);
2036
+ headerActions.appendChild(clearBtn);
2037
+ headerActions.appendChild(exportBtn);
2038
+ headerActions.appendChild(closeBtn);
2039
+ header.appendChild(headerLeft);
2040
+ header.appendChild(headerActions);
2041
+ this.element.appendChild(header);
2042
+ // 2. Tabs Bar
2043
+ const tabsBar = document.createElement('div');
2044
+ tabsBar.className = 'cd-tabs-bar';
2045
+ const tabs = [
2046
+ { id: 'all', label: 'All' },
2047
+ { id: 'console', label: 'Console' },
2048
+ { id: 'errors', label: 'Errors' },
2049
+ { id: 'events', label: 'Events' },
2050
+ { id: 'native', label: 'Native' },
2051
+ { id: 'device', label: 'Device' },
2052
+ { id: 'network', label: 'Network' },
2053
+ { id: 'bridge', label: 'Bridge' },
2054
+ ];
2055
+ for (const { id, label } of tabs) {
2056
+ const tabBtn = document.createElement('button');
2057
+ tabBtn.className = 'cd-tab';
2058
+ if (id === this.options.defaultTab) {
2059
+ tabBtn.classList.add('active');
2060
+ }
2061
+ const labelSpan = document.createElement('span');
2062
+ labelSpan.textContent = label;
2063
+ const badgeSpan = document.createElement('span');
2064
+ badgeSpan.className = 'cd-tab-badge';
2065
+ badgeSpan.textContent = '0';
2066
+ tabBtn.appendChild(labelSpan);
2067
+ tabBtn.appendChild(badgeSpan);
2068
+ tabBtn.addEventListener('click', () => {
2069
+ this.selectTab(id);
2070
+ });
2071
+ this.tabElements.set(id, tabBtn);
2072
+ this.tabBadgeElements.set(id, badgeSpan);
2073
+ tabsBar.appendChild(tabBtn);
2074
+ }
2075
+ this.element.appendChild(tabsBar);
2076
+ // 3. Toolbar (Search & Level Filters)
2077
+ const toolbar = document.createElement('div');
2078
+ toolbar.className = 'cd-toolbar';
2079
+ this.searchInput = document.createElement('input');
2080
+ this.searchInput.className = 'cd-search-input';
2081
+ this.searchInput.type = 'text';
2082
+ this.searchInput.placeholder = 'Filter logs, types, payloads...';
2083
+ this.searchInput.addEventListener('input', () => {
2084
+ this.store.setFilter({ search: this.searchInput.value });
2085
+ });
2086
+ const levelFilters = document.createElement('div');
2087
+ levelFilters.className = 'cd-level-filters';
2088
+ const levels = ['all', 'error', 'warn', 'info', 'debug'];
2089
+ for (const lvl of levels) {
2090
+ const pill = document.createElement('button');
2091
+ pill.className = 'cd-level-pill';
2092
+ pill.setAttribute('data-level', lvl);
2093
+ pill.textContent = lvl === 'all' ? 'All' : lvl.toUpperCase();
2094
+ if (lvl === 'all')
2095
+ pill.classList.add('active');
2096
+ pill.addEventListener('click', () => {
2097
+ this.selectLevel(lvl);
2098
+ });
2099
+ this.levelPills.set(lvl, pill);
2100
+ levelFilters.appendChild(pill);
2101
+ }
2102
+ toolbar.appendChild(this.searchInput);
2103
+ toolbar.appendChild(levelFilters);
2104
+ this.element.appendChild(toolbar);
2105
+ // 4. Content Area
2106
+ this.contentContainer = document.createElement('div');
2107
+ this.contentContainer.className = 'cd-content';
2108
+ this.eventListContainer = document.createElement('div');
2109
+ this.eventListContainer.className = 'cd-event-list';
2110
+ this.deviceViewContainer = document.createElement('div');
2111
+ this.deviceViewContainer.className = 'cd-device-view';
2112
+ this.deviceViewContainer.style.display = 'none';
2113
+ this.contentContainer.appendChild(this.eventListContainer);
2114
+ this.contentContainer.appendChild(this.deviceViewContainer);
2115
+ this.element.appendChild(this.contentContainer);
2116
+ // 5. Detail Overlay
2117
+ this.buildDetailOverlay();
2118
+ }
2119
+ selectTab(tab) {
2120
+ for (const [id, el] of this.tabElements.entries()) {
2121
+ el.classList.toggle('active', id === tab);
2122
+ }
2123
+ this.store.setFilter({ tab });
2124
+ this.closeDetail();
2125
+ if (tab === 'device') {
2126
+ this.eventListContainer.style.display = 'none';
2127
+ this.deviceViewContainer.style.display = 'flex';
2128
+ this.loadDeviceDiagnostics();
2129
+ }
2130
+ else {
2131
+ this.eventListContainer.style.display = 'flex';
2132
+ this.deviceViewContainer.style.display = 'none';
2133
+ }
2134
+ }
2135
+ selectLevel(level) {
2136
+ for (const [lvl, pill] of this.levelPills.entries()) {
2137
+ pill.classList.toggle('active', lvl === level);
2138
+ }
2139
+ this.store.setFilter({ level });
2140
+ }
2141
+ updatePauseState(isPaused) {
2142
+ this.statusIndicator.classList.toggle('paused', isPaused);
2143
+ this.pauseBtn.classList.toggle('active', isPaused);
2144
+ this.pauseBtn.title = isPaused ? 'Resume capture' : 'Pause capture';
2145
+ }
2146
+ bindStore() {
2147
+ this.store.subscribe((events, store) => {
2148
+ this.renderEventList(events);
2149
+ this.renderCounts(store.getCounts());
2150
+ this.updatePauseState(store.isPaused());
2151
+ });
2152
+ }
2153
+ renderCounts(counts) {
2154
+ this.titleCountSpan.textContent = `(${counts.all})`;
2155
+ for (const [tab, badge] of this.tabBadgeElements.entries()) {
2156
+ if (tab === 'device') {
2157
+ badge.style.display = 'none';
2158
+ }
2159
+ else {
2160
+ const count = counts[tab] || 0;
2161
+ badge.textContent = count > 999 ? '999+' : String(count);
2162
+ }
2163
+ }
2164
+ }
2165
+ renderEventList(events) {
2166
+ if (this.store.getFilter().tab === 'device') {
2167
+ return;
2168
+ }
2169
+ this.eventListContainer.innerHTML = '';
2170
+ if (events.length === 0) {
2171
+ const empty = document.createElement('div');
2172
+ empty.className = 'cd-empty-state';
2173
+ empty.innerHTML = `
2174
+ <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
2175
+ <span>No events match current filter</span>
2176
+ `;
2177
+ this.eventListContainer.appendChild(empty);
2178
+ return;
2179
+ }
2180
+ // Render newest items at the top
2181
+ for (let i = events.length - 1; i >= 0; i--) {
2182
+ const event = events[i];
2183
+ const row = this.createEventRow(event);
2184
+ this.eventListContainer.appendChild(row);
2185
+ }
2186
+ }
2187
+ createEventRow(event) {
2188
+ const row = document.createElement('div');
2189
+ row.className = 'cd-event-row';
2190
+ row.setAttribute('data-level', event.level || 'info');
2191
+ const dot = document.createElement('div');
2192
+ dot.className = 'cd-event-level-dot';
2193
+ const time = document.createElement('div');
2194
+ time.className = 'cd-event-time';
2195
+ time.textContent = this.formatTime(event.timestamp);
2196
+ const source = document.createElement('div');
2197
+ source.className = 'cd-event-source';
2198
+ source.textContent = event.source;
2199
+ const main = document.createElement('div');
2200
+ main.className = 'cd-event-main';
2201
+ const type = document.createElement('div');
2202
+ type.className = 'cd-event-type';
2203
+ type.textContent = event.type;
2204
+ main.appendChild(type);
2205
+ if (event.message) {
2206
+ const msg = document.createElement('div');
2207
+ msg.className = 'cd-event-msg';
2208
+ msg.textContent = event.message;
2209
+ main.appendChild(msg);
2210
+ }
2211
+ row.appendChild(dot);
2212
+ row.appendChild(time);
2213
+ row.appendChild(source);
2214
+ row.appendChild(main);
2215
+ if (event.duration !== undefined) {
2216
+ const duration = document.createElement('div');
2217
+ duration.className = 'cd-event-duration';
2218
+ duration.textContent = `${event.duration}ms`;
2219
+ row.appendChild(duration);
2220
+ }
2221
+ row.addEventListener('click', () => {
2222
+ this.showDetail(event);
2223
+ });
2224
+ return row;
2225
+ }
2226
+ buildDetailOverlay() {
2227
+ this.detailOverlay = document.createElement('div');
2228
+ this.detailOverlay.className = 'cd-detail-overlay';
2229
+ const header = document.createElement('div');
2230
+ header.className = 'cd-detail-header';
2231
+ const backBtn = document.createElement('button');
2232
+ backBtn.className = 'cd-detail-back';
2233
+ backBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/></svg> Back`;
2234
+ backBtn.addEventListener('click', () => this.closeDetail());
2235
+ const copyAllBtn = document.createElement('button');
2236
+ copyAllBtn.className = 'cd-copy-btn-sm';
2237
+ copyAllBtn.textContent = 'Copy JSON';
2238
+ copyAllBtn.addEventListener('click', async () => {
2239
+ if (this.selectedEvent) {
2240
+ await JsonViewer.copyToClipboard(JSON.stringify(this.selectedEvent, null, 2), copyAllBtn);
2241
+ }
2242
+ });
2243
+ header.appendChild(backBtn);
2244
+ header.appendChild(copyAllBtn);
2245
+ this.detailOverlay.appendChild(header);
2246
+ const body = document.createElement('div');
2247
+ body.className = 'cd-detail-body';
2248
+ this.detailOverlay.appendChild(body);
2249
+ this.contentContainer.appendChild(this.detailOverlay);
2250
+ }
2251
+ showDetail(event) {
2252
+ this.selectedEvent = event;
2253
+ const body = this.detailOverlay.querySelector('.cd-detail-body');
2254
+ body.innerHTML = '';
2255
+ // 1. Meta Grid
2256
+ const metaGrid = document.createElement('div');
2257
+ metaGrid.className = 'cd-meta-grid';
2258
+ const addMeta = (label, value) => {
2259
+ if (value === undefined)
2260
+ return;
2261
+ const item = document.createElement('div');
2262
+ item.className = 'cd-meta-item';
2263
+ item.innerHTML = `
2264
+ <span class="cd-meta-label">${label}</span>
2265
+ <span class="cd-meta-val">${value}</span>
2266
+ `;
2267
+ metaGrid.appendChild(item);
2268
+ };
2269
+ addMeta('Type', event.type);
2270
+ addMeta('Source', event.source);
2271
+ addMeta('Level', event.level);
2272
+ addMeta('Time', `${this.formatTime(event.timestamp)} (${new Date(event.timestamp).toLocaleTimeString()})`);
2273
+ addMeta('ID', event.id);
2274
+ if (event.duration !== undefined)
2275
+ addMeta('Duration', `${event.duration}ms`);
2276
+ if (event.platform)
2277
+ addMeta('Platform', event.platform);
2278
+ body.appendChild(metaGrid);
2279
+ // 2. Message
2280
+ if (event.message) {
2281
+ const msgSection = document.createElement('div');
2282
+ msgSection.innerHTML = `<div class="cd-section-title">Message</div>`;
2283
+ const msgBlock = document.createElement('div');
2284
+ msgBlock.className = 'cd-msg-block';
2285
+ msgBlock.textContent = event.message;
2286
+ msgSection.appendChild(msgBlock);
2287
+ body.appendChild(msgSection);
2288
+ }
2289
+ // 3. Data Payload / JSON Viewer
2290
+ if (event.data !== undefined) {
2291
+ const dataSection = document.createElement('div');
2292
+ dataSection.innerHTML = `<div class="cd-section-title">Data Payload</div>`;
2293
+ const jsonTree = JsonViewer.render(event.data, 3);
2294
+ dataSection.appendChild(jsonTree);
2295
+ body.appendChild(dataSection);
2296
+ }
2297
+ this.detailOverlay.classList.add('open');
2298
+ }
2299
+ closeDetail() {
2300
+ this.selectedEvent = null;
2301
+ this.detailOverlay.classList.remove('open');
2302
+ }
2303
+ async loadDeviceDiagnostics() {
2304
+ if (this.isDeviceLoading)
2305
+ return;
2306
+ this.isDeviceLoading = true;
2307
+ this.deviceViewContainer.innerHTML = `
2308
+ <div class="cd-empty-state">
2309
+ <span>Querying native device diagnostics...</span>
2310
+ </div>
2311
+ `;
2312
+ try {
2313
+ const [device, memory, webView, app, network] = await Promise.allSettled([
2314
+ CapDebugNative.getDeviceInfo(),
2315
+ CapDebugNative.getMemoryInfo(),
2316
+ CapDebugNative.getWebViewInfo(),
2317
+ CapDebugNative.getAppInfo(),
2318
+ CapDebugNative.getNetworkInfo(),
2319
+ ]);
2320
+ this.deviceData = {
2321
+ device: device.status === 'fulfilled' ? device.value : { error: String(device.reason) },
2322
+ memory: memory.status === 'fulfilled' ? memory.value : { error: String(memory.reason) },
2323
+ webView: webView.status === 'fulfilled' ? webView.value : { error: String(webView.reason) },
2324
+ app: app.status === 'fulfilled' ? app.value : { error: String(app.reason) },
2325
+ network: network.status === 'fulfilled' ? network.value : { error: String(network.reason) },
2326
+ };
2327
+ // Emit native diagnostics event into the store as well
2328
+ this.store.add({
2329
+ source: 'native',
2330
+ type: 'device.diagnostics',
2331
+ level: 'info',
2332
+ message: 'Device diagnostics loaded',
2333
+ data: this.deviceData,
2334
+ });
2335
+ this.renderDeviceView();
2336
+ }
2337
+ catch (err) {
2338
+ this.deviceViewContainer.innerHTML = `
2339
+ <div class="cd-empty-state">
2340
+ <span style="color: var(--cd-color-error)">Failed to load diagnostics: ${err?.message || String(err)}</span>
2341
+ </div>
2342
+ `;
2343
+ }
2344
+ finally {
2345
+ this.isDeviceLoading = false;
2346
+ }
2347
+ }
2348
+ renderDeviceView() {
2349
+ if (!this.deviceData)
2350
+ return;
2351
+ this.deviceViewContainer.innerHTML = '';
2352
+ // Refresh action bar
2353
+ const topBar = document.createElement('div');
2354
+ topBar.style.display = 'flex';
2355
+ topBar.style.justifyContent = 'space-between';
2356
+ topBar.style.alignItems = 'center';
2357
+ const infoLabel = document.createElement('span');
2358
+ infoLabel.style.fontSize = '11px';
2359
+ infoLabel.style.color = 'var(--cd-text-muted)';
2360
+ infoLabel.textContent = `Diagnostic snapshot: ${new Date().toLocaleTimeString()}`;
2361
+ const refreshBtn = document.createElement('button');
2362
+ refreshBtn.className = 'cd-copy-btn-sm';
2363
+ refreshBtn.textContent = '↻ Refresh Live Data';
2364
+ refreshBtn.addEventListener('click', () => this.loadDeviceDiagnostics());
2365
+ topBar.appendChild(infoLabel);
2366
+ topBar.appendChild(refreshBtn);
2367
+ this.deviceViewContainer.appendChild(topBar);
2368
+ const sections = [
2369
+ { title: 'Device Information', data: this.deviceData.device },
2370
+ { title: 'Memory & Heap', data: this.deviceData.memory },
2371
+ { title: 'Application Info', data: this.deviceData.app },
2372
+ { title: 'WebView & User Agent', data: this.deviceData.webView },
2373
+ { title: 'Network State', data: this.deviceData.network },
2374
+ ];
2375
+ for (const { title, data } of sections) {
2376
+ const card = document.createElement('div');
2377
+ card.className = 'cd-device-card';
2378
+ const cardHeader = document.createElement('div');
2379
+ cardHeader.className = 'cd-device-card-header';
2380
+ cardHeader.textContent = title;
2381
+ card.appendChild(cardHeader);
2382
+ if (typeof data === 'object' && data !== null) {
2383
+ const grid = document.createElement('div');
2384
+ grid.className = 'cd-device-grid';
2385
+ for (const [k, v] of Object.entries(data)) {
2386
+ if (typeof v === 'object' && v !== null)
2387
+ continue;
2388
+ const item = document.createElement('div');
2389
+ item.className = 'cd-meta-item';
2390
+ item.innerHTML = `
2391
+ <span class="cd-meta-label">${k}</span>
2392
+ <span class="cd-meta-val">${v !== undefined && v !== null ? String(v) : '—'}</span>
2393
+ `;
2394
+ grid.appendChild(item);
2395
+ }
2396
+ card.appendChild(grid);
2397
+ // Render nested objects if present
2398
+ for (const [k, v] of Object.entries(data)) {
2399
+ if (typeof v === 'object' && v !== null) {
2400
+ const nestedSection = document.createElement('div');
2401
+ nestedSection.innerHTML = `<div style="font-size: 10px; color: var(--cd-text-muted); font-weight: 600; margin-top: 6px;">${k.toUpperCase()}</div>`;
2402
+ nestedSection.appendChild(JsonViewer.render(v, 2));
2403
+ card.appendChild(nestedSection);
2404
+ }
2405
+ }
2406
+ }
2407
+ else {
2408
+ card.textContent = String(data);
2409
+ }
2410
+ this.deviceViewContainer.appendChild(card);
2411
+ }
2412
+ }
2413
+ formatTime(timestamp) {
2414
+ const d = new Date(timestamp);
2415
+ const h = String(d.getHours()).padStart(2, '0');
2416
+ const m = String(d.getMinutes()).padStart(2, '0');
2417
+ const s = String(d.getSeconds()).padStart(2, '0');
2418
+ const ms = String(d.getMilliseconds()).padStart(3, '0');
2419
+ return `${h}:${m}:${s}.${ms}`;
2420
+ }
2421
+ }
2422
+
2423
+ class CapDebugViewerElement extends HTMLElement {
2424
+ static TAG = 'cap-debug-viewer';
2425
+ shadowRootNode;
2426
+ floatingButton = null;
2427
+ debugPanel = null;
2428
+ store = null;
2429
+ unsubscribeStore = null;
2430
+ constructor() {
2431
+ super();
2432
+ this.shadowRootNode = this.attachShadow({ mode: 'open' });
2433
+ }
2434
+ getStore() {
2435
+ return this.store;
2436
+ }
2437
+ init(store, options = {}) {
2438
+ this.store = store;
2439
+ // Inject isolated styles
2440
+ const styleEl = document.createElement('style');
2441
+ styleEl.textContent = VIEWER_STYLES;
2442
+ this.shadowRootNode.appendChild(styleEl);
2443
+ // Create Panel
2444
+ this.debugPanel = new DebugPanel(store, {
2445
+ defaultTab: options.defaultTab || 'all',
2446
+ onClose: () => {
2447
+ // Can handle panel close events if needed
2448
+ },
2449
+ });
2450
+ this.shadowRootNode.appendChild(this.debugPanel.getBackdrop());
2451
+ this.shadowRootNode.appendChild(this.debugPanel.getElement());
2452
+ // Create Floating Button (if enabled)
2453
+ if (options.button !== false) {
2454
+ this.floatingButton = new FloatingButton({
2455
+ position: options.position,
2456
+ persistPosition: options.persistPosition !== false,
2457
+ onClick: () => {
2458
+ this.toggle();
2459
+ },
2460
+ });
2461
+ this.shadowRootNode.appendChild(this.floatingButton.getElement());
2462
+ }
2463
+ // Subscribe to error counts for the button badge
2464
+ this.unsubscribeStore = store.subscribe((_events, s) => {
2465
+ const counts = s.getCounts();
2466
+ if (this.floatingButton) {
2467
+ this.floatingButton.setErrorCount(counts.errors);
2468
+ }
2469
+ });
2470
+ }
2471
+ show() {
2472
+ if (this.debugPanel) {
2473
+ this.debugPanel.open();
2474
+ }
2475
+ }
2476
+ hide() {
2477
+ if (this.debugPanel) {
2478
+ this.debugPanel.close();
2479
+ }
2480
+ }
2481
+ toggle() {
2482
+ if (this.debugPanel) {
2483
+ return this.debugPanel.toggle();
2484
+ }
2485
+ return false;
2486
+ }
2487
+ showButton() {
2488
+ if (this.floatingButton) {
2489
+ this.floatingButton.show();
2490
+ }
2491
+ }
2492
+ hideButton() {
2493
+ if (this.floatingButton) {
2494
+ this.floatingButton.hide();
2495
+ }
2496
+ }
2497
+ disconnectedCallback() {
2498
+ if (this.unsubscribeStore) {
2499
+ this.unsubscribeStore();
2500
+ this.unsubscribeStore = null;
2501
+ }
2502
+ }
2503
+ }
2504
+ function registerCustomElement() {
2505
+ if (typeof customElements !== 'undefined' && !customElements.get(CapDebugViewerElement.TAG)) {
2506
+ customElements.define(CapDebugViewerElement.TAG, CapDebugViewerElement);
2507
+ }
2508
+ }
2509
+
2510
+ class CapDebugManager {
2511
+ store;
2512
+ viewerElement = null;
2513
+ isMounted = false;
2514
+ customEventCollector;
2515
+ consoleCollector;
2516
+ errorCollector;
2517
+ networkCollector;
2518
+ browserEventCollector;
2519
+ bridgeCollector;
2520
+ constructor() {
2521
+ this.store = new CapDebugStore();
2522
+ this.customEventCollector = new CustomEventCollector(this.store);
2523
+ this.consoleCollector = new ConsoleCollector();
2524
+ this.errorCollector = new ErrorCollector();
2525
+ this.networkCollector = new NetworkCollector();
2526
+ this.browserEventCollector = new BrowserEventCollector();
2527
+ this.bridgeCollector = new BridgeCollector();
2528
+ }
2529
+ get native() {
2530
+ return CapDebugNative;
2531
+ }
2532
+ get currentStore() {
2533
+ return this.store;
2534
+ }
2535
+ /**
2536
+ * Mounts the CapDebug UI into the DOM and activates collectors.
2537
+ */
2538
+ mount(options = {}) {
2539
+ if (typeof window === 'undefined' || typeof document === 'undefined') {
2540
+ return;
2541
+ }
2542
+ if (this.isMounted) {
2543
+ this.unmount();
2544
+ }
2545
+ // Configure store
2546
+ if (options.maxEvents) {
2547
+ this.store.setMaxEvents(options.maxEvents);
2548
+ }
2549
+ if (options.customMaskKeys) {
2550
+ this.store.setCustomMaskKeys(options.customMaskKeys);
2551
+ }
2552
+ // 1. Start core CustomEvent bus listener
2553
+ this.customEventCollector.start();
2554
+ // 2. Start optional collectors
2555
+ if (options.console !== false) {
2556
+ this.consoleCollector.start();
2557
+ }
2558
+ if (options.errors !== false) {
2559
+ this.errorCollector.start();
2560
+ }
2561
+ if (options.network) {
2562
+ const netOpts = typeof options.network === 'object' ? options.network : {};
2563
+ this.networkCollector.setOptions(netOpts);
2564
+ this.networkCollector.start();
2565
+ }
2566
+ if (options.bridge) {
2567
+ this.bridgeCollector.start();
2568
+ }
2569
+ this.browserEventCollector.start();
2570
+ // 3. Register and create Web Component
2571
+ registerCustomElement();
2572
+ this.viewerElement = document.createElement(CapDebugViewerElement.TAG);
2573
+ this.viewerElement.init(this.store, options);
2574
+ document.body.appendChild(this.viewerElement);
2575
+ this.isMounted = true;
2576
+ }
2577
+ /**
2578
+ * Unmounts CapDebug UI and stops all collectors.
2579
+ */
2580
+ unmount() {
2581
+ if (!this.isMounted)
2582
+ return;
2583
+ if (this.viewerElement && this.viewerElement.parentNode) {
2584
+ this.viewerElement.parentNode.removeChild(this.viewerElement);
2585
+ this.viewerElement = null;
2586
+ }
2587
+ this.customEventCollector.stop();
2588
+ this.consoleCollector.stop();
2589
+ this.errorCollector.stop();
2590
+ this.networkCollector.stop();
2591
+ this.browserEventCollector.stop();
2592
+ this.bridgeCollector.stop();
2593
+ this.isMounted = false;
2594
+ }
2595
+ /**
2596
+ * Opens the debug viewer drawer.
2597
+ */
2598
+ show() {
2599
+ if (this.viewerElement) {
2600
+ this.viewerElement.show();
2601
+ }
2602
+ }
2603
+ /**
2604
+ * Closes the debug viewer drawer.
2605
+ */
2606
+ hide() {
2607
+ if (this.viewerElement) {
2608
+ this.viewerElement.hide();
2609
+ }
2610
+ }
2611
+ /**
2612
+ * Toggles the debug viewer drawer open/closed.
2613
+ */
2614
+ toggle() {
2615
+ if (this.viewerElement) {
2616
+ return this.viewerElement.toggle();
2617
+ }
2618
+ return false;
2619
+ }
2620
+ /**
2621
+ * Dispatches a debug event through the CustomEvent bus.
2622
+ */
2623
+ emit(event) {
2624
+ if (typeof window === 'undefined')
2625
+ return;
2626
+ window.dispatchEvent(new CustomEvent('capdebug', {
2627
+ detail: {
2628
+ id: event.id,
2629
+ timestamp: event.timestamp || Date.now(),
2630
+ source: event.source || 'web',
2631
+ type: event.type,
2632
+ level: event.level || 'info',
2633
+ message: event.message,
2634
+ data: event.data,
2635
+ duration: event.duration,
2636
+ platform: event.platform,
2637
+ },
2638
+ }));
2639
+ }
2640
+ /**
2641
+ * Clears all recorded events from the store.
2642
+ */
2643
+ clear() {
2644
+ this.store.clear();
2645
+ }
2646
+ /**
2647
+ * Pauses capturing new events.
2648
+ */
2649
+ pause() {
2650
+ this.store.pause();
2651
+ }
2652
+ /**
2653
+ * Resumes capturing events.
2654
+ */
2655
+ resume() {
2656
+ this.store.resume();
2657
+ }
2658
+ captureConsole() {
2659
+ this.consoleCollector.start();
2660
+ }
2661
+ releaseConsole() {
2662
+ this.consoleCollector.stop();
2663
+ }
2664
+ captureErrors() {
2665
+ this.errorCollector.start();
2666
+ }
2667
+ releaseErrors() {
2668
+ this.errorCollector.stop();
2669
+ }
2670
+ captureFetch(options) {
2671
+ if (options) {
2672
+ this.networkCollector.setOptions(options);
2673
+ }
2674
+ this.networkCollector.start();
2675
+ }
2676
+ releaseFetch() {
2677
+ this.networkCollector.stop();
2678
+ }
2679
+ observeEvent(eventName) {
2680
+ this.browserEventCollector.observe(eventName);
2681
+ }
2682
+ unobserveEvent(eventName) {
2683
+ this.browserEventCollector.unobserve(eventName);
2684
+ }
2685
+ }
2686
+ const CapDebug = new CapDebugManager();
2687
+
2688
+ function formatBytes(bytes) {
2689
+ if (bytes === 0)
2690
+ return '0 B';
2691
+ const k = 1024;
2692
+ const sizes = ['B', 'KB', 'MB', 'GB'];
2693
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
2694
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
2695
+ }
2696
+ class CapDebugWeb extends WebPlugin {
2697
+ async getDeviceInfo() {
2698
+ const nav = typeof navigator !== 'undefined' ? navigator : {};
2699
+ return {
2700
+ manufacturer: 'Web Browser',
2701
+ model: nav.userAgentData?.brands?.[0]?.brand || nav.appName || 'Browser',
2702
+ device: nav.platform || 'Web',
2703
+ systemVersion: nav.appVersion || 'Unknown',
2704
+ architecture: nav.userAgentData?.architecture || 'Unknown',
2705
+ availableProcessors: nav.hardwareConcurrency || 1,
2706
+ isEmulator: false,
2707
+ platform: 'web',
2708
+ };
2709
+ }
2710
+ async getMemoryInfo() {
2711
+ const perf = typeof window !== 'undefined' ? window.performance : null;
2712
+ const memory = perf && perf.memory ? perf.memory : null;
2713
+ if (memory) {
2714
+ return {
2715
+ appMemoryUsage: memory.usedJSHeapSize,
2716
+ appMemoryUsageFormatted: formatBytes(memory.usedJSHeapSize),
2717
+ totalHeap: memory.totalJSHeapSize,
2718
+ totalHeapFormatted: formatBytes(memory.totalJSHeapSize),
2719
+ maxHeap: memory.jsHeapSizeLimit,
2720
+ maxHeapFormatted: formatBytes(memory.jsHeapSizeLimit),
2721
+ freeHeap: memory.totalJSHeapSize - memory.usedJSHeapSize,
2722
+ freeHeapFormatted: formatBytes(memory.totalJSHeapSize - memory.usedJSHeapSize),
2723
+ lowMemory: false,
2724
+ };
2725
+ }
2726
+ return {
2727
+ appMemoryUsageFormatted: 'N/A (Browser non-Chrome)',
2728
+ lowMemory: false,
2729
+ };
2730
+ }
2731
+ async getWebViewInfo() {
2732
+ const nav = typeof navigator !== 'undefined' ? navigator : {};
2733
+ return {
2734
+ userAgent: nav.userAgent || 'Unknown',
2735
+ version: nav.appVersion || 'Unknown',
2736
+ packageName: typeof window !== 'undefined' ? window.location.hostname : 'localhost',
2737
+ debugEnabled: true,
2738
+ };
2739
+ }
2740
+ async getAppInfo() {
2741
+ return {
2742
+ applicationId: typeof window !== 'undefined' ? window.location.host : 'localhost',
2743
+ version: '1.0.0',
2744
+ versionName: '1.0.0 (Web)',
2745
+ versionCode: 1,
2746
+ buildType: typeof process !== 'undefined' && process.env?.NODE_ENV ? process.env.NODE_ENV : 'development',
2747
+ };
2748
+ }
2749
+ async getNetworkInfo() {
2750
+ const nav = typeof navigator !== 'undefined' ? navigator : {};
2751
+ const conn = nav.connection || nav.mozConnection || nav.webkitConnection;
2752
+ return {
2753
+ connected: nav.onLine ?? true,
2754
+ connectionType: conn ? conn.effectiveType || conn.type || 'unknown' : (nav.onLine ? 'online' : 'offline'),
2755
+ metered: conn ? conn.saveData ?? false : false,
2756
+ };
2757
+ }
2758
+ }
2759
+
2760
+ var web = /*#__PURE__*/Object.freeze({
2761
+ __proto__: null,
2762
+ CapDebugWeb: CapDebugWeb
2763
+ });
2764
+
2765
+ export { BridgeCollector, BrowserEventCollector, CapDebug, CapDebugManager, CapDebugNative, CapDebugStore, CapDebugViewerElement, ConsoleCollector, CustomEventCollector, DataSanitizer, ErrorCollector, JsonViewer, NetworkCollector, CapDebug as default, defaultSanitizer, registerCustomElement, sanitize };
2766
+ //# sourceMappingURL=plugin.mjs.map