@oxog/devinspector 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +0 -0
  3. package/README.md +85 -28
  4. package/dist/chunk-LNBLBFDA.js +92 -0
  5. package/dist/chunk-LNBLBFDA.js.map +1 -0
  6. package/dist/chunk-PPIEWSZ7.js +32 -0
  7. package/dist/chunk-PPIEWSZ7.js.map +1 -0
  8. package/dist/console-monitor-LBNXAQQ4.js +571 -0
  9. package/dist/console-monitor-LBNXAQQ4.js.map +1 -0
  10. package/dist/devinspector.umd.js +1782 -1074
  11. package/dist/devinspector.umd.js.map +1 -1
  12. package/dist/devinspector.umd.min.js +6 -1
  13. package/dist/devinspector.umd.min.js.map +1 -1
  14. package/dist/dom-monitor-IGQZTXMH.js +19 -0
  15. package/dist/dom-monitor-IGQZTXMH.js.map +1 -0
  16. package/dist/error-monitor-XDNRO4KS.js +423 -0
  17. package/dist/error-monitor-XDNRO4KS.js.map +1 -0
  18. package/dist/index.cjs +5918 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.cts +582 -0
  21. package/dist/index.d.ts +582 -0
  22. package/dist/index.js +1983 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/inspector-ui-AFTUEVWA.js +1240 -0
  25. package/dist/inspector-ui-AFTUEVWA.js.map +1 -0
  26. package/dist/network-monitor-HUSRKEXE.js +841 -0
  27. package/dist/network-monitor-HUSRKEXE.js.map +1 -0
  28. package/dist/performance-monitor-66DQJGOJ.js +544 -0
  29. package/dist/performance-monitor-66DQJGOJ.js.map +1 -0
  30. package/dist/state-monitor-PS5Q7NWY.js +19 -0
  31. package/dist/state-monitor-PS5Q7NWY.js.map +1 -0
  32. package/dist/storage-monitor-QW634CEJ.js +19 -0
  33. package/dist/storage-monitor-QW634CEJ.js.map +1 -0
  34. package/package.json +51 -38
  35. package/dist/devinspector.cjs.js +0 -5494
  36. package/dist/devinspector.cjs.js.map +0 -1
  37. package/dist/devinspector.esm.js +0 -5482
  38. package/dist/devinspector.esm.js.map +0 -1
  39. package/dist/types/clean-inspector.d.ts +0 -52
  40. package/dist/types/core/event-emitter.d.ts +0 -21
  41. package/dist/types/core/inspector.d.ts +0 -121
  42. package/dist/types/core/plugin-system.d.ts +0 -60
  43. package/dist/types/core/storage.d.ts +0 -52
  44. package/dist/types/core/utils.d.ts +0 -34
  45. package/dist/types/enhanced-inspector.d.ts +0 -56
  46. package/dist/types/enhanced-simple.d.ts +0 -46
  47. package/dist/types/index-simple.d.ts +0 -11
  48. package/dist/types/index.d.ts +0 -19
  49. package/dist/types/monitors/console/console-interceptor.d.ts +0 -36
  50. package/dist/types/monitors/console/console-monitor.d.ts +0 -26
  51. package/dist/types/monitors/console/log-formatter.d.ts +0 -8
  52. package/dist/types/monitors/dom/dom-monitor.d.ts +0 -8
  53. package/dist/types/monitors/error/error-monitor.d.ts +0 -28
  54. package/dist/types/monitors/error/error-tracker.d.ts +0 -55
  55. package/dist/types/monitors/error/source-map-support.d.ts +0 -15
  56. package/dist/types/monitors/network/fetch-interceptor.d.ts +0 -45
  57. package/dist/types/monitors/network/network-monitor.d.ts +0 -47
  58. package/dist/types/monitors/network/websocket-monitor.d.ts +0 -44
  59. package/dist/types/monitors/network/xhr-interceptor.d.ts +0 -25
  60. package/dist/types/monitors/performance/fps-monitor.d.ts +0 -24
  61. package/dist/types/monitors/performance/long-task-detector.d.ts +0 -25
  62. package/dist/types/monitors/performance/memory-monitor.d.ts +0 -30
  63. package/dist/types/monitors/performance/metrics-collector.d.ts +0 -45
  64. package/dist/types/monitors/performance/performance-monitor.d.ts +0 -34
  65. package/dist/types/monitors/state/state-monitor.d.ts +0 -8
  66. package/dist/types/monitors/storage/storage-monitor.d.ts +0 -8
  67. package/dist/types/simple-index.d.ts +0 -3
  68. package/dist/types/simple-inspector.d.ts +0 -24
  69. package/dist/types/ui/components/floating-widget.d.ts +0 -21
  70. package/dist/types/ui/components/main-panel.d.ts +0 -38
  71. package/dist/types/ui/inspector-ui.d.ts +0 -29
  72. package/dist/types/ui/styles.d.ts +0 -1
@@ -1,750 +1,1351 @@
1
1
  /**
2
- * @oxog/devinspector v1.2.0
3
- * (c) 2025 Ersin Koc <ersinkoc@gmail.com>
2
+ * @oxog/devinspector v1.3.0
3
+ * (c) Ersin Koc <ersinkoc@gmail.com>
4
4
  * Released under the MIT License
5
5
  */
6
6
  (function (global, factory) {
7
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
8
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
9
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.DevInspector = {}));
10
- })(this, (function (exports) { 'use strict';
7
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
8
+ typeof define === 'function' && define.amd ? define(factory) :
9
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.DevInspector = factory());
10
+ })(this, (function () { 'use strict';
11
11
 
12
12
  /**
13
- * Enhanced DevInspector - Beautiful Modern UI (Simplified for Build)
14
- * @version 1.1.0
13
+ * Helpers shared by every inspector variant.
15
14
  */
16
- class EnhancedDevInspector {
17
- constructor() {
18
- this.data = {
19
- network: [],
20
- console: [],
21
- performance: { fps: 0, memory: null },
22
- errors: []
15
+ /**
16
+ * Reads `process.env.NODE_ENV` without assuming `process` exists.
17
+ *
18
+ * The expression is written out literally so bundlers (webpack DefinePlugin,
19
+ * Vite, esbuild `define`, Rollup replace) substitute it at build time. In a
20
+ * browser without such substitution, `process` is undefined and the access
21
+ * throws, which is caught here.
22
+ */
23
+ function readNodeEnv() {
24
+ try {
25
+ return process.env.NODE_ENV;
26
+ }
27
+ catch (_a) {
28
+ return undefined;
29
+ }
30
+ }
31
+ /** Default for the `enabled` option: on everywhere except production builds. */
32
+ function defaultEnabled() {
33
+ return readNodeEnv() !== 'production';
34
+ }
35
+ /** True when a DOM is available (browser, jsdom), false during SSR/Node. */
36
+ function hasDom() {
37
+ return typeof window !== 'undefined' && typeof document !== 'undefined';
38
+ }
39
+ const HTML_ESCAPES = {
40
+ '&': '&amp;',
41
+ '<': '&lt;',
42
+ '>': '&gt;',
43
+ '"': '&quot;',
44
+ "'": '&#39;',
45
+ '`': '&#96;',
46
+ };
47
+ /** Escapes a value for use in HTML text or a quoted attribute. */
48
+ function escapeHtml(value) {
49
+ return String(value).replace(/[&<>"'`]/g, ch => HTML_ESCAPES[ch]);
50
+ }
51
+
52
+ class EventEmitter {
53
+ constructor(options = {}) {
54
+ var _a, _b;
55
+ this.events = new Map();
56
+ this.maxListeners = (_a = options.maxListeners) !== null && _a !== void 0 ? _a : 10;
57
+ this.captureRejections = (_b = options.captureRejections) !== null && _b !== void 0 ? _b : false;
58
+ }
59
+ on(event, listener) {
60
+ if (!this.events.has(event)) {
61
+ this.events.set(event, new Set());
62
+ }
63
+ const listeners = this.events.get(event);
64
+ // Warn when exceeding max listeners (not when equal to max)
65
+ if (listeners.size > this.maxListeners) {
66
+ console.warn(`MaxListenersExceededWarning: Possible EventEmitter memory leak detected. ${listeners.size} ${String(event)} listeners added.`);
67
+ }
68
+ listeners.add(listener);
69
+ return () => {
70
+ listeners.delete(listener);
71
+ if (listeners.size === 0) {
72
+ this.events.delete(event);
73
+ }
74
+ };
75
+ }
76
+ once(event, listener) {
77
+ const wrappedListener = (data) => {
78
+ unsubscribe();
79
+ listener(data);
80
+ };
81
+ const unsubscribe = this.on(event, wrappedListener);
82
+ return unsubscribe;
83
+ }
84
+ emit(event, ...args) {
85
+ const listeners = this.events.get(event);
86
+ if (!listeners || listeners.size === 0) {
87
+ return false;
88
+ }
89
+ const data = args[0];
90
+ listeners.forEach(listener => {
91
+ try {
92
+ listener(data);
93
+ }
94
+ catch (error) {
95
+ if (this.captureRejections) {
96
+ // Use type assertion for recursive error emit
97
+ this.emit('error', error);
98
+ }
99
+ else {
100
+ console.error(`Error in event listener for "${String(event)}":`, error);
101
+ }
102
+ }
103
+ });
104
+ return true;
105
+ }
106
+ off(event, listener) {
107
+ if (!listener) {
108
+ this.events.delete(event);
109
+ return;
110
+ }
111
+ const listeners = this.events.get(event);
112
+ if (listeners) {
113
+ listeners.delete(listener);
114
+ if (listeners.size === 0) {
115
+ this.events.delete(event);
116
+ }
117
+ }
118
+ }
119
+ removeAllListeners(event) {
120
+ if (event) {
121
+ this.events.delete(event);
122
+ }
123
+ else {
124
+ this.events.clear();
125
+ }
126
+ }
127
+ listenerCount(event) {
128
+ const listeners = this.events.get(event);
129
+ return listeners ? listeners.size : 0;
130
+ }
131
+ eventNames() {
132
+ return Array.from(this.events.keys());
133
+ }
134
+ setMaxListeners(n) {
135
+ this.maxListeners = n;
136
+ }
137
+ getMaxListeners() {
138
+ return this.maxListeners;
139
+ }
140
+ }
141
+
142
+ class PluginSystem {
143
+ constructor(context) {
144
+ this.plugins = new Map();
145
+ this.activePlugins = new Set();
146
+ this.installingPlugins = new Set();
147
+ this.context = context;
148
+ }
149
+ async register(plugin) {
150
+ if (this.plugins.has(plugin.name)) {
151
+ throw new Error(`Plugin "${plugin.name}" is already registered`);
152
+ }
153
+ if (this.installingPlugins.has(plugin.name)) {
154
+ throw new Error(`Plugin "${plugin.name}" is currently being installed`);
155
+ }
156
+ this.installingPlugins.add(plugin.name);
157
+ try {
158
+ await plugin.install(this.context);
159
+ this.plugins.set(plugin.name, plugin);
160
+ this.activePlugins.add(plugin.name);
161
+ if (plugin.enable) {
162
+ plugin.enable();
163
+ }
164
+ this.context.events.emit('plugin:registered', {
165
+ name: plugin.name,
166
+ version: plugin.version
167
+ });
168
+ }
169
+ catch (error) {
170
+ this.installingPlugins.delete(plugin.name);
171
+ throw new Error(`Failed to install plugin "${plugin.name}": ${error}`);
172
+ }
173
+ this.installingPlugins.delete(plugin.name);
174
+ }
175
+ async unregister(pluginName) {
176
+ const plugin = this.plugins.get(pluginName);
177
+ if (!plugin) {
178
+ throw new Error(`Plugin "${pluginName}" is not registered`);
179
+ }
180
+ if (plugin.disable) {
181
+ plugin.disable();
182
+ }
183
+ if (plugin.uninstall) {
184
+ await plugin.uninstall();
185
+ }
186
+ this.plugins.delete(pluginName);
187
+ this.activePlugins.delete(pluginName);
188
+ this.context.events.emit('plugin:unregistered', {
189
+ name: pluginName
190
+ });
191
+ }
192
+ enable(pluginName) {
193
+ const plugin = this.plugins.get(pluginName);
194
+ if (!plugin) {
195
+ throw new Error(`Plugin "${pluginName}" is not registered`);
196
+ }
197
+ if (this.activePlugins.has(pluginName)) {
198
+ return;
199
+ }
200
+ if (plugin.enable) {
201
+ plugin.enable();
202
+ }
203
+ this.activePlugins.add(pluginName);
204
+ this.context.events.emit('plugin:enabled', {
205
+ name: pluginName
206
+ });
207
+ }
208
+ disable(pluginName) {
209
+ const plugin = this.plugins.get(pluginName);
210
+ if (!plugin) {
211
+ throw new Error(`Plugin "${pluginName}" is not registered`);
212
+ }
213
+ if (!this.activePlugins.has(pluginName)) {
214
+ return;
215
+ }
216
+ if (plugin.disable) {
217
+ plugin.disable();
218
+ }
219
+ this.activePlugins.delete(pluginName);
220
+ this.context.events.emit('plugin:disabled', {
221
+ name: pluginName
222
+ });
223
+ }
224
+ get(pluginName) {
225
+ return this.plugins.get(pluginName);
226
+ }
227
+ has(pluginName) {
228
+ return this.plugins.has(pluginName);
229
+ }
230
+ isActive(pluginName) {
231
+ return this.activePlugins.has(pluginName);
232
+ }
233
+ getAll() {
234
+ return Array.from(this.plugins.values());
235
+ }
236
+ getActive() {
237
+ return Array.from(this.activePlugins).map(name => this.plugins.get(name));
238
+ }
239
+ getMetadata(pluginName) {
240
+ const plugin = this.plugins.get(pluginName);
241
+ if (!plugin) {
242
+ return undefined;
243
+ }
244
+ return {
245
+ name: plugin.name,
246
+ version: plugin.version,
247
+ description: plugin.description
23
248
  };
249
+ }
250
+ getAllMetadata() {
251
+ return this.getAll().map(plugin => ({
252
+ name: plugin.name,
253
+ version: plugin.version,
254
+ description: plugin.description
255
+ }));
256
+ }
257
+ }
258
+ class BasePlugin {
259
+ async install(context) {
260
+ this.context = context;
261
+ await this.onInstall();
262
+ }
263
+ async uninstall() {
264
+ await this.onUninstall();
265
+ this.context = undefined;
266
+ }
267
+ enable() {
268
+ this.onEnable();
269
+ }
270
+ disable() {
271
+ this.onDisable();
272
+ }
273
+ onUninstall() { }
274
+ onEnable() { }
275
+ onDisable() { }
276
+ get inspector() {
277
+ var _a;
278
+ return (_a = this.context) === null || _a === void 0 ? void 0 : _a.inspector;
279
+ }
280
+ get events() {
281
+ var _a;
282
+ if (!((_a = this.context) === null || _a === void 0 ? void 0 : _a.events)) {
283
+ throw new Error('Events not available - plugin not installed');
284
+ }
285
+ return this.context.events;
286
+ }
287
+ get storage() {
288
+ var _a;
289
+ return (_a = this.context) === null || _a === void 0 ? void 0 : _a.storage;
290
+ }
291
+ get config() {
292
+ var _a;
293
+ return (_a = this.context) === null || _a === void 0 ? void 0 : _a.config;
294
+ }
295
+ }
296
+
297
+ /** Package version, kept in sync with package.json (checked by tests). */
298
+ const VERSION = '1.3.0';
299
+
300
+ /**
301
+ * DevInspector - the default inspector: floating widget plus a panel with
302
+ * Network, Console, Performance and Errors tabs.
303
+ *
304
+ * Everything it patches (window.fetch, XMLHttpRequest.prototype.open/send,
305
+ * console methods) is restored by destroy(). Captured data is kept in bounded
306
+ * buffers and every captured value is HTML-escaped before it is rendered.
307
+ */
308
+ const CONSOLE_METHODS = ['log', 'info', 'warn', 'error', 'debug'];
309
+ const MAX_MESSAGE_LENGTH = 10000;
310
+ const MAX_METRIC_ENTRIES = 500;
311
+ const ASSET_PATTERN = /\.(?:css|js|mjs|map|png|jpe?g|gif|svg|webp|avif|ico|woff2?|ttf|otf|eot)(?:[?#]|$)/i;
312
+ const POSITIONS = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
313
+ const PALETTES = {
314
+ dark: { bg: '#1a1a1a', header: '#262626', toolbar: '#1e1e1e', border: '#333', row: '#2a2a2a', text: '#e4e4e7', muted: '#9ca3af', code: '#0f0f0f' },
315
+ light: { bg: '#ffffff', header: '#f3f4f6', toolbar: '#f9fafb', border: '#d1d5db', row: '#e5e7eb', text: '#111827', muted: '#4b5563', code: '#f3f4f6' },
316
+ };
317
+ let idCounter = 0;
318
+ function nextId() {
319
+ idCounter = (idCounter + 1) % Number.MAX_SAFE_INTEGER;
320
+ return `${Date.now().toString(36)}-${idCounter.toString(36)}`;
321
+ }
322
+ function limit(value, fallback) {
323
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
324
+ }
325
+ function normalizeCombo(combo) {
326
+ if (typeof combo !== 'string')
327
+ return '';
328
+ const parts = combo.toLowerCase().split('+').map(part => part.trim()).filter(Boolean);
329
+ const key = parts.filter(part => !['ctrl', 'control', 'alt', 'shift', 'meta', 'cmd'].includes(part));
330
+ if (key.length !== 1)
331
+ return '';
332
+ const has = (...names) => names.some(name => parts.includes(name));
333
+ return [has('ctrl', 'control') && 'ctrl', has('alt') && 'alt', has('shift') && 'shift', has('meta', 'cmd') && 'meta', key[0]]
334
+ .filter(Boolean)
335
+ .join('+');
336
+ }
337
+ function eventCombo(event) {
338
+ if (typeof event.key !== 'string')
339
+ return '';
340
+ return [event.ctrlKey && 'ctrl', event.altKey && 'alt', event.shiftKey && 'shift', event.metaKey && 'meta', event.key.toLowerCase()]
341
+ .filter(Boolean)
342
+ .join('+');
343
+ }
344
+ function truncate(text) {
345
+ return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}… (${text.length - MAX_MESSAGE_LENGTH} more characters)` : text;
346
+ }
347
+ function stringifyArg(arg) {
348
+ if (typeof arg === 'string')
349
+ return arg;
350
+ if (arg instanceof Error)
351
+ return arg.stack || `${arg.name}: ${arg.message}`;
352
+ if (arg !== null && typeof arg === 'object') {
353
+ const seen = new WeakSet();
354
+ try {
355
+ const json = JSON.stringify(arg, (_key, value) => {
356
+ if (typeof value === 'bigint')
357
+ return `${value}n`;
358
+ if (value !== null && typeof value === 'object') {
359
+ if (seen.has(value))
360
+ return '[Circular]';
361
+ seen.add(value);
362
+ }
363
+ return value;
364
+ }, 2);
365
+ return json === undefined ? String(arg) : json;
366
+ }
367
+ catch (_a) {
368
+ try {
369
+ return String(arg);
370
+ }
371
+ catch (_b) {
372
+ return '[object]';
373
+ }
374
+ }
375
+ }
376
+ try {
377
+ return String(arg);
378
+ }
379
+ catch (_c) {
380
+ return '[unprintable]';
381
+ }
382
+ }
383
+ function requestUrl(input) {
384
+ if (typeof input === 'string')
385
+ return input;
386
+ if (input && typeof input === 'object') {
387
+ const candidate = input;
388
+ if (typeof candidate.url === 'string')
389
+ return candidate.url; // Request
390
+ if (typeof candidate.href === 'string')
391
+ return candidate.href; // URL / Location
392
+ }
393
+ return String(input);
394
+ }
395
+ function requestMethod(input, init) {
396
+ const fromInit = init && typeof init === 'object' ? init.method : undefined;
397
+ if (typeof fromInit === 'string' && fromInit)
398
+ return fromInit.toUpperCase();
399
+ const fromRequest = input && typeof input === 'object' ? input.method : undefined;
400
+ if (typeof fromRequest === 'string' && fromRequest)
401
+ return fromRequest.toUpperCase();
402
+ return 'GET';
403
+ }
404
+ class EnhancedDevInspector {
405
+ constructor(config = {}) {
406
+ var _a;
407
+ this.events = new EventEmitter({ maxListeners: 100 });
408
+ this.network = [];
409
+ this.consoleEntries = [];
410
+ this.errors = [];
411
+ this.metrics = [];
412
+ this.performanceStats = { fps: 0, memory: null };
24
413
  this.isRecording = true;
25
- this.widget = null;
26
- this.panel = null;
27
414
  this.isVisible = false;
28
415
  this.isMinimized = false;
416
+ this.destroyed = false;
417
+ this.capturing = false;
418
+ this.renderQueued = false;
29
419
  this.activeTab = 'network';
30
- this.selectedRequest = null;
31
- this.init();
420
+ this.selectedRequestId = null;
421
+ this.widget = null;
422
+ this.panel = null;
423
+ this.patches = [];
424
+ this.cleanups = [];
425
+ this.rafId = null;
426
+ this.marks = new Map();
427
+ this.xhrState = new WeakMap();
428
+ this.config = EnhancedDevInspector.resolveConfig(config !== null && config !== void 0 ? config : {});
429
+ this.active = this.config.enabled && hasDom();
430
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
431
+ const self = this;
432
+ this.pluginSystem = new PluginSystem({
433
+ inspector: this,
434
+ storage: {
435
+ get network() {
436
+ return self.getEntries('network');
437
+ },
438
+ get console() {
439
+ return self.getEntries('console');
440
+ },
441
+ get errors() {
442
+ return self.getEntries('errors');
443
+ },
444
+ get metrics() {
445
+ return self.getEntries('metrics');
446
+ },
447
+ },
448
+ events: this.events,
449
+ config: this.config,
450
+ });
451
+ if (!this.active)
452
+ return;
453
+ EnhancedDevInspector.instances.push(this);
454
+ if (this.config.features.network) {
455
+ this.interceptFetch();
456
+ this.interceptXHR();
457
+ }
458
+ if (this.config.features.console)
459
+ this.interceptConsole();
460
+ if (this.config.features.errors)
461
+ this.interceptErrors();
462
+ this.setupHotkeys();
463
+ this.mountWhenReady();
464
+ for (const plugin of (_a = config.plugins) !== null && _a !== void 0 ? _a : []) {
465
+ this.use(plugin).catch(error => this.reportInternal('Failed to register plugin', error));
466
+ }
467
+ this.events.emit('inspector:ready');
468
+ }
469
+ /** The most recently created inspector that is still alive, if any. */
470
+ static getInstance() {
471
+ const { instances } = EnhancedDevInspector;
472
+ return instances.length > 0 ? instances[instances.length - 1] : null;
32
473
  }
33
- init() {
34
- this.createFloatingButton();
35
- this.createMainPanel();
36
- this.setupInterceptors();
37
- this.setupEventListeners();
474
+ static resolveConfig(config) {
475
+ var _a, _b, _c, _d, _e;
476
+ const features = (_a = config.features) !== null && _a !== void 0 ? _a : {};
477
+ const theme = config.theme === 'light' || config.theme === 'dark' ? config.theme : 'auto';
478
+ const prefersDark = (() => {
479
+ try {
480
+ return typeof window !== 'undefined' && typeof window.matchMedia === 'function'
481
+ ? window.matchMedia('(prefers-color-scheme: dark)').matches
482
+ : true;
483
+ }
484
+ catch (_a) {
485
+ return true;
486
+ }
487
+ })();
488
+ const hotkeys = (_b = config.hotkeys) !== null && _b !== void 0 ? _b : {};
489
+ return {
490
+ enabled: typeof config.enabled === 'boolean' ? config.enabled : defaultEnabled(),
491
+ position: POSITIONS.includes(config.position) ? config.position : 'bottom-right',
492
+ theme: theme === 'auto' ? (prefersDark ? 'dark' : 'light') : theme,
493
+ hotkeys: {
494
+ toggle: normalizeCombo((_c = hotkeys.toggle) !== null && _c !== void 0 ? _c : 'ctrl+shift+d'),
495
+ minimize: normalizeCombo((_d = hotkeys.minimize) !== null && _d !== void 0 ? _d : 'ctrl+shift+m'),
496
+ },
497
+ features: {
498
+ network: features.network !== false,
499
+ console: features.console !== false,
500
+ performance: features.performance !== false,
501
+ errors: features.errors !== false,
502
+ },
503
+ maxNetworkEntries: limit(config.maxNetworkEntries, 1000),
504
+ maxConsoleEntries: limit(config.maxConsoleEntries, 500),
505
+ maxErrorEntries: limit(config.maxErrorEntries, 100),
506
+ captureStackTraces: config.captureStackTraces !== false,
507
+ hideAssets: ((_e = config.networkFilters) === null || _e === void 0 ? void 0 : _e.hideAssets) === true,
508
+ slowRequestThreshold: limit(config.slowRequestThreshold, 3000),
509
+ onError: typeof config.onError === 'function' ? config.onError : undefined,
510
+ onPerformanceIssue: typeof config.onPerformanceIssue === 'function' ? config.onPerformanceIssue : undefined,
511
+ };
38
512
  }
39
- createFloatingButton() {
40
- this.widget = document.createElement('div');
41
- this.widget.innerHTML = '🔍';
42
- this.widget.style.cssText = `
43
- position: fixed;
44
- bottom: 24px;
45
- right: 24px;
46
- width: 56px;
47
- height: 56px;
48
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
49
- border-radius: 50%;
50
- display: flex;
51
- align-items: center;
52
- justify-content: center;
53
- cursor: pointer;
54
- z-index: 999999;
55
- color: white;
56
- font-size: 24px;
57
- box-shadow: 0 8px 32px rgba(102, 126, 234, 0.4);
58
- transition: all 0.3s ease;
59
- `;
60
- this.widget.addEventListener('click', () => this.toggle());
61
- this.widget.addEventListener('mouseenter', () => {
62
- this.widget.style.transform = 'scale(1.1)';
63
- });
64
- this.widget.addEventListener('mouseleave', () => {
65
- this.widget.style.transform = 'scale(1)';
66
- });
67
- document.body.appendChild(this.widget);
513
+ // ---------------------------------------------------------------------------
514
+ // Public API
515
+ // ---------------------------------------------------------------------------
516
+ /** True when the inspector is running (enabled, in a browser, not destroyed). */
517
+ get isEnabled() {
518
+ return this.active && !this.destroyed;
68
519
  }
69
- createMainPanel() {
70
- this.panel = document.createElement('div');
71
- this.panel.style.cssText = `
72
- position: fixed;
73
- bottom: 24px;
74
- right: 24px;
75
- width: 480px;
76
- height: 650px;
77
- background: #1a1a1a;
78
- border: 1px solid #333;
79
- border-radius: 12px;
80
- display: none;
81
- flex-direction: column;
82
- z-index: 999998;
83
- box-shadow: 0 24px 64px rgba(0, 0, 0, 0.8);
84
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
85
- font-size: 13px;
86
- color: #e4e4e7;
87
- overflow: hidden;
88
- `;
89
- this.renderPanel();
90
- document.body.appendChild(this.panel);
520
+ show() {
521
+ if (!this.isEnabled)
522
+ return;
523
+ this.isVisible = true;
524
+ if (this.panel)
525
+ this.panel.style.display = 'flex';
526
+ if (this.widget)
527
+ this.widget.style.display = 'none';
528
+ this.render();
529
+ this.startPerformanceLoop();
530
+ this.events.emit('inspector:show');
91
531
  }
92
- renderPanel() {
93
- if (!this.panel)
532
+ hide() {
533
+ if (!this.isEnabled)
534
+ return;
535
+ this.isVisible = false;
536
+ if (this.panel)
537
+ this.panel.style.display = 'none';
538
+ if (this.widget)
539
+ this.widget.style.display = 'flex';
540
+ this.stopPerformanceLoop();
541
+ this.events.emit('inspector:hide');
542
+ }
543
+ toggle() {
544
+ if (this.isVisible)
545
+ this.hide();
546
+ else
547
+ this.show();
548
+ }
549
+ /** Collapses the panel to its header (or expands it again). */
550
+ minimize() {
551
+ if (!this.isEnabled)
94
552
  return;
95
- this.panel.innerHTML = `
96
- <div style="
97
- display: flex;
98
- align-items: center;
99
- justify-content: space-between;
100
- padding: 12px 16px;
101
- background: linear-gradient(135deg, #2a2a2a 0%, #1e1e1e 100%);
102
- border-bottom: 1px solid #333;
103
- ">
104
- <div style="display: flex; align-items: center; gap: 8px;">
105
- <div style="
106
- width: 8px;
107
- height: 8px;
108
- background: ${this.isRecording ? '#ef4444' : '#6b7280'};
109
- border-radius: 50%;
110
- "></div>
111
- <span style="font-weight: 600; font-size: 14px;">DevInspector v1.1.0</span>
112
- </div>
113
- <div style="display: flex; gap: 4px;">
114
- <button class="minimize-btn" style="
115
- padding: 6px; background: none; border: none; color: #9ca3af; cursor: pointer;
116
- border-radius: 4px;
117
- ">−</button>
118
- <button class="close-btn" style="
119
- padding: 6px; background: none; border: none; color: #9ca3af; cursor: pointer;
120
- border-radius: 4px;
121
- ">×</button>
122
- </div>
123
- </div>
124
-
125
- ${!this.isMinimized ? `
126
- <div style="display: flex; background: #262626; border-bottom: 1px solid #333;">
127
- ${this.renderTabs()}
128
- </div>
129
- <div style="flex: 1; overflow: hidden;">
130
- ${this.renderTabContent()}
131
- </div>
132
- ` : ''}
133
- `;
134
- this.attachEventListeners();
553
+ this.isMinimized = !this.isMinimized;
554
+ if (this.panel)
555
+ this.panel.style.height = this.isMinimized ? '48px' : '650px';
556
+ this.render();
557
+ this.events.emit('inspector:minimize', this.isMinimized);
558
+ }
559
+ clear(type = 'all') {
560
+ if (type === 'network' || type === 'all') {
561
+ this.network = [];
562
+ this.selectedRequestId = null;
563
+ }
564
+ if (type === 'console' || type === 'all')
565
+ this.consoleEntries = [];
566
+ if (type === 'errors' || type === 'all')
567
+ this.errors = [];
568
+ if (type === 'metrics' || type === 'all')
569
+ this.metrics = [];
570
+ this.scheduleRender();
571
+ }
572
+ /** Pauses or resumes capturing. Patched APIs keep working either way. */
573
+ toggleRecording() {
574
+ this.isRecording = !this.isRecording;
575
+ this.scheduleRender();
576
+ return this.isRecording;
135
577
  }
136
- renderTabs() {
137
- const tabs = [
138
- { id: 'network', label: 'Network', count: this.data.network.length },
139
- { id: 'console', label: 'Console', count: this.data.console.length },
140
- { id: 'performance', label: 'Performance' },
141
- { id: 'errors', label: 'Errors', count: this.data.errors.length }
142
- ];
143
- return tabs.map(tab => `
144
- <button data-tab="${tab.id}" style="
145
- padding: 12px 16px;
146
- background: ${this.activeTab === tab.id ? '#1a1a1a' : 'transparent'};
147
- border: none;
148
- color: ${this.activeTab === tab.id ? '#3b82f6' : '#9ca3af'};
149
- cursor: pointer;
150
- border-bottom: 2px solid ${this.activeTab === tab.id ? '#3b82f6' : 'transparent'};
151
- ">
152
- ${tab.label}
153
- ${tab.count !== undefined ? `<span style="
154
- background: #374151; color: white; padding: 2px 6px; border-radius: 10px;
155
- font-size: 11px; margin-left: 6px;
156
- ">${tab.count}</span>` : ''}
157
- </button>
158
- `).join('');
159
- }
160
- renderTabContent() {
161
- switch (this.activeTab) {
162
- case 'network': return this.renderNetworkTab();
163
- case 'console': return this.renderConsoleTab();
164
- case 'performance': return this.renderPerformanceTab();
165
- case 'errors': return this.renderErrorsTab();
166
- default: return '';
167
- }
168
- }
169
- renderNetworkTab() {
170
- return `
171
- <div style="display: flex; flex-direction: column; height: 100%;">
172
- <div style="padding: 12px; border-bottom: 1px solid #333; background: #1e1e1e;">
173
- <button class="clear-network" style="
174
- padding: 6px 12px; background: #374151; border: none; color: white;
175
- cursor: pointer; border-radius: 6px; margin-right: 8px;
176
- ">Clear</button>
177
- <button class="toggle-recording" style="
178
- padding: 6px 12px; border: none; color: white; cursor: pointer; border-radius: 6px;
179
- background: ${this.isRecording ? '#ef4444' : '#22c55e'};
180
- ">${this.isRecording ? 'Pause' : 'Resume'}</button>
181
- <span style="float: right; color: #6b7280; font-size: 12px; line-height: 32px;">
182
- ${this.data.network.length} requests
183
- </span>
184
- </div>
185
- <div style="flex: 1; overflow-y: auto;">
186
- ${this.data.network.length === 0 ? `
187
- <div style="display: flex; align-items: center; justify-content: center; height: 200px; color: #6b7280;">
188
- No network activity
189
- </div>
190
- ` : this.data.network.map(req => this.renderNetworkRequest(req)).join('')}
191
- </div>
192
- ${this.selectedRequest ? this.renderRequestDetails() : ''}
193
- </div>
194
- `;
578
+ get recording() {
579
+ return this.isRecording;
580
+ }
581
+ getEntries(type) {
582
+ switch (type) {
583
+ case 'network':
584
+ return this.network.map(entry => ({ ...entry }));
585
+ case 'console':
586
+ return this.consoleEntries.map(entry => ({ ...entry }));
587
+ case 'errors':
588
+ return this.errors.map(entry => ({ ...entry }));
589
+ default:
590
+ return this.metrics.map(entry => ({ ...entry }));
591
+ }
592
+ }
593
+ /** Records a custom metric and emits `performance:metric`. */
594
+ track(name, data) {
595
+ if (!this.isEnabled)
596
+ return;
597
+ const entry = { id: nextId(), name: String(name), data, timestamp: Date.now() };
598
+ this.pushBounded(this.metrics, entry, MAX_METRIC_ENTRIES);
599
+ this.emitSafely('performance:metric', entry);
600
+ this.scheduleRender();
195
601
  }
196
- renderNetworkRequest(req) {
602
+ markStart(name) {
197
603
  var _a;
198
- const statusColor = this.getStatusColor(req.status);
199
- const methodColor = this.getMethodColor(req.method);
200
- return `
201
- <div class="network-request" data-id="${req.id}" style="
202
- padding: 12px 16px; border-bottom: 1px solid #2a2a2a; cursor: pointer;
203
- ${((_a = this.selectedRequest) === null || _a === void 0 ? void 0 : _a.id) === req.id ? 'background: #1e3a8a;' : ''}
204
- ">
205
- <div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
206
- <div style="display: flex; gap: 8px;">
207
- <span style="
208
- background: ${methodColor}; color: white; padding: 2px 6px; border-radius: 4px;
209
- font-size: 11px; font-weight: 600;
210
- ">${req.method}</span>
211
- <span style="color: ${statusColor}; font-weight: 600;">${req.status}</span>
212
- <span style="color: #6b7280;">${req.duration || '-'}ms</span>
213
- </div>
214
- <span style="color: #6b7280; font-size: 11px;">
215
- ${req.timestamp.toLocaleTimeString()}
216
- </span>
217
- </div>
218
- <div style="color: #d1d5db; font-size: 12px; word-break: break-all;">
219
- ${req.url}
220
- </div>
221
- </div>
222
- `;
604
+ if (!this.isEnabled)
605
+ return;
606
+ this.marks.set(String(name), performance.now());
607
+ try {
608
+ (_a = performance.mark) === null || _a === void 0 ? void 0 : _a.call(performance, `devinspector-${name}-start`);
609
+ }
610
+ catch (_b) {
611
+ // User Timing is optional; the duration is measured with performance.now().
612
+ }
223
613
  }
224
- renderConsoleTab() {
225
- return `
226
- <div style="display: flex; flex-direction: column; height: 100%;">
227
- <div style="padding: 12px; border-bottom: 1px solid #333; background: #1e1e1e;">
228
- <button class="clear-console" style="
229
- padding: 6px 12px; background: #374151; border: none; color: white;
230
- cursor: pointer; border-radius: 6px;
231
- ">Clear</button>
232
- <span style="float: right; color: #6b7280; font-size: 12px; line-height: 32px;">
233
- ${this.data.console.length} logs
234
- </span>
235
- </div>
236
- <div style="flex: 1; overflow-y: auto; font-family: monospace;">
237
- ${this.data.console.length === 0 ? `
238
- <div style="display: flex; align-items: center; justify-content: center; height: 200px; color: #6b7280;">
239
- No console logs
240
- </div>
241
- ` : this.data.console.map(log => `
242
- <div style="padding: 8px 16px; border-bottom: 1px solid #2a2a2a; font-size: 12px;">
243
- <span style="color: ${this.getConsoleLevelColor(log.level)}; text-transform: uppercase; font-weight: 600;">
244
- [${log.level}]
245
- </span>
246
- <span style="color: #6b7280; margin: 0 8px;">${log.timestamp.toLocaleTimeString()}</span>
247
- <span style="color: ${this.getConsoleLevelColor(log.level)};">${log.message}</span>
248
- </div>
249
- `).join('')}
250
- </div>
251
- </div>
252
- `;
614
+ /** Ends a measurement started with markStart() and returns its duration in ms. */
615
+ markEnd(name) {
616
+ var _a, _b;
617
+ if (!this.isEnabled)
618
+ return undefined;
619
+ const key = String(name);
620
+ const start = this.marks.get(key);
621
+ if (start === undefined)
622
+ return undefined;
623
+ this.marks.delete(key);
624
+ const duration = performance.now() - start;
625
+ try {
626
+ (_a = performance.mark) === null || _a === void 0 ? void 0 : _a.call(performance, `devinspector-${key}-end`);
627
+ (_b = performance.measure) === null || _b === void 0 ? void 0 : _b.call(performance, `devinspector-${key}`, `devinspector-${key}-start`, `devinspector-${key}-end`);
628
+ }
629
+ catch (_c) {
630
+ // See markStart().
631
+ }
632
+ const entry = { id: nextId(), name: key, duration, timestamp: Date.now() };
633
+ this.pushBounded(this.metrics, entry, MAX_METRIC_ENTRIES);
634
+ this.emitSafely('performance:mark', entry);
635
+ this.scheduleRender();
636
+ return duration;
253
637
  }
254
- renderPerformanceTab() {
255
- return `
256
- <div style="padding: 20px;">
257
- <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px;">
258
- <div style="
259
- background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%);
260
- border-radius: 12px; padding: 20px; text-align: center;
261
- ">
262
- <div style="font-size: 32px; font-weight: 700; color: #60a5fa;">${this.data.performance.fps}</div>
263
- <div style="font-size: 12px; color: #bfdbfe; margin-top: 4px;">FPS</div>
264
- </div>
265
- <div style="
266
- background: linear-gradient(135deg, #166534 0%, #16a34a 100%);
267
- border-radius: 12px; padding: 20px; text-align: center;
268
- ">
269
- <div style="font-size: 32px; font-weight: 700; color: #4ade80;">
270
- ${this.data.performance.memory ? this.data.performance.memory.used + ' MB' : 'N/A'}
271
- </div>
272
- <div style="font-size: 12px; color: #bbf7d0; margin-top: 4px;">Memory</div>
273
- </div>
274
- </div>
275
- <div style="background: #262626; border-radius: 12px; padding: 20px;">
276
- <h4 style="margin: 0 0 16px 0;">Performance Metrics</h4>
277
- <div style="color: #9ca3af;">
278
- Performance monitoring active...
279
- </div>
280
- </div>
281
- </div>
282
- `;
638
+ /** Installs a plugin. Resolves once the plugin's install() has finished. */
639
+ use(plugin) {
640
+ if (this.destroyed)
641
+ return Promise.reject(new Error('DevInspector has been destroyed'));
642
+ return this.pluginSystem.register(plugin);
283
643
  }
284
- renderErrorsTab() {
285
- return `
286
- <div style="display: flex; flex-direction: column; height: 100%;">
287
- <div style="padding: 12px; border-bottom: 1px solid #333; background: #1e1e1e;">
288
- <button class="clear-errors" style="
289
- padding: 6px 12px; background: #374151; border: none; color: white;
290
- cursor: pointer; border-radius: 6px;
291
- ">Clear</button>
292
- <span style="float: right; color: #6b7280; font-size: 12px; line-height: 32px;">
293
- ${this.data.errors.length} errors
294
- </span>
295
- </div>
296
- <div style="flex: 1; overflow-y: auto;">
297
- ${this.data.errors.length === 0 ? `
298
- <div style="display: flex; align-items: center; justify-content: center; height: 200px; color: #6b7280;">
299
- No errors recorded
300
- </div>
301
- ` : this.data.errors.map(error => `
302
- <div style="padding: 16px; border-bottom: 1px solid #2a2a2a;">
303
- <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
304
- <span style="color: #ef4444; font-weight: 600;">${error.type}</span>
305
- <span style="color: #6b7280; font-size: 11px;">${error.timestamp.toLocaleTimeString()}</span>
306
- </div>
307
- <div style="color: #fca5a5; margin-bottom: 8px;">${error.message}</div>
308
- ${error.stack ? `<pre style="
309
- background: #0f0f0f; padding: 8px; border-radius: 4px; font-size: 11px;
310
- color: #9ca3af; overflow-x: auto; white-space: pre-wrap;
311
- ">${error.stack}</pre>` : ''}
312
- </div>
313
- `).join('')}
314
- </div>
315
- </div>
316
- `;
644
+ on(event, listener) {
645
+ return this.events.on(event, listener);
317
646
  }
318
- renderRequestDetails() {
319
- if (!this.selectedRequest)
320
- return '';
321
- return `
322
- <div style="border-top: 1px solid #333; height: 200px; overflow-y: auto; background: #1e1e1e;">
323
- <div style="padding: 12px; border-bottom: 1px solid #333; display: flex; justify-content: space-between;">
324
- <h4 style="margin: 0;">Request Details</h4>
325
- <button class="close-details" style="background: none; border: none; color: #6b7280; cursor: pointer;">×</button>
326
- </div>
327
- <div style="padding: 16px; font-size: 12px;">
328
- <div style="margin-bottom: 12px;">
329
- <strong>URL:</strong> ${this.selectedRequest.url}
330
- </div>
331
- <div style="margin-bottom: 12px;">
332
- <strong>Method:</strong> ${this.selectedRequest.method}
333
- </div>
334
- <div style="margin-bottom: 12px;">
335
- <strong>Status:</strong> ${this.selectedRequest.status}
336
- </div>
337
- <div>
338
- <strong>Duration:</strong> ${this.selectedRequest.duration || '-'}ms
339
- </div>
340
- </div>
341
- </div>
342
- `;
647
+ once(event, listener) {
648
+ return this.events.once(event, listener);
343
649
  }
344
- getStatusColor(status) {
345
- if (status === 'error' || status === 'pending')
346
- return '#6b7280';
347
- const statusNum = typeof status === 'string' ? parseInt(status) : status;
348
- if (statusNum >= 200 && statusNum < 300)
349
- return '#22c55e';
350
- if (statusNum >= 300 && statusNum < 400)
351
- return '#f59e0b';
352
- if (statusNum >= 400)
353
- return '#ef4444';
354
- return '#6b7280';
650
+ off(event, listener) {
651
+ this.events.off(event, listener);
355
652
  }
356
- getMethodColor(method) {
357
- const colors = {
358
- GET: '#22c55e',
359
- POST: '#3b82f6',
360
- PUT: '#f59e0b',
361
- DELETE: '#ef4444',
362
- PATCH: '#8b5cf6'
363
- };
364
- return colors[method] || '#6b7280';
365
- }
366
- getConsoleLevelColor(level) {
367
- const colors = {
368
- log: '#d1d5db',
369
- info: '#60a5fa',
370
- warn: '#fbbf24',
371
- error: '#f87171',
372
- debug: '#a78bfa'
653
+ /** Serialisable snapshot of everything captured so far. */
654
+ export() {
655
+ return {
656
+ version: VERSION,
657
+ timestamp: Date.now(),
658
+ data: {
659
+ network: this.getEntries('network'),
660
+ console: this.getEntries('console'),
661
+ errors: this.getEntries('errors'),
662
+ metrics: this.getEntries('metrics'),
663
+ },
373
664
  };
374
- return colors[level] || '#d1d5db';
375
665
  }
376
- attachEventListeners() {
377
- var _a, _b, _c, _d, _e;
378
- if (!this.panel)
379
- return;
380
- // Header buttons
381
- const minimizeBtn = this.panel.querySelector('.minimize-btn');
382
- const closeBtn = this.panel.querySelector('.close-btn');
383
- minimizeBtn === null || minimizeBtn === void 0 ? void 0 : minimizeBtn.addEventListener('click', () => this.minimize());
384
- closeBtn === null || closeBtn === void 0 ? void 0 : closeBtn.addEventListener('click', () => this.hide());
385
- // Tab buttons
386
- this.panel.querySelectorAll('[data-tab]').forEach(btn => {
387
- btn.addEventListener('click', (e) => {
388
- this.activeTab = e.target.getAttribute('data-tab');
389
- this.renderPanel();
666
+ /**
667
+ * Loads a snapshot produced by export(), replacing the current data. Entries
668
+ * are validated field by field and trimmed to the configured limits.
669
+ */
670
+ import(snapshot) {
671
+ const data = snapshot && typeof snapshot === 'object' ? snapshot.data : undefined;
672
+ if (!data || typeof data !== 'object')
673
+ throw new TypeError('DevInspector.import() expects an object produced by export()');
674
+ const source = data;
675
+ const list = (value) => Array.isArray(value) ? value.filter((item) => !!item && typeof item === 'object') : [];
676
+ const str = (value, fallback = '') => (typeof value === 'string' ? value : fallback);
677
+ const num = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined);
678
+ this.network = list(source.network)
679
+ .slice(0, this.config.maxNetworkEntries)
680
+ .map(item => {
681
+ var _a;
682
+ return ({
683
+ id: str(item.id, nextId()),
684
+ type: item.type === 'xhr' ? 'xhr' : 'fetch',
685
+ url: str(item.url),
686
+ method: str(item.method, 'GET'),
687
+ status: typeof item.status === 'number' ? item.status : item.status === 'pending' ? 'pending' : 'error',
688
+ timestamp: (_a = num(item.timestamp)) !== null && _a !== void 0 ? _a : Date.now(),
689
+ duration: num(item.duration),
690
+ error: typeof item.error === 'string' ? item.error : undefined,
691
+ });
692
+ });
693
+ this.consoleEntries = list(source.console)
694
+ .slice(0, this.config.maxConsoleEntries)
695
+ .map(item => {
696
+ var _a;
697
+ return ({
698
+ id: str(item.id, nextId()),
699
+ level: CONSOLE_METHODS.includes(item.level) ? item.level : 'log',
700
+ message: truncate(str(item.message)),
701
+ timestamp: (_a = num(item.timestamp)) !== null && _a !== void 0 ? _a : Date.now(),
390
702
  });
391
703
  });
392
- // Action buttons
393
- (_a = this.panel.querySelector('.clear-network')) === null || _a === void 0 ? void 0 : _a.addEventListener('click', () => this.clear('network'));
394
- (_b = this.panel.querySelector('.toggle-recording')) === null || _b === void 0 ? void 0 : _b.addEventListener('click', () => this.toggleRecording());
395
- (_c = this.panel.querySelector('.clear-console')) === null || _c === void 0 ? void 0 : _c.addEventListener('click', () => this.clear('console'));
396
- (_d = this.panel.querySelector('.clear-errors')) === null || _d === void 0 ? void 0 : _d.addEventListener('click', () => this.clear('errors'));
397
- (_e = this.panel.querySelector('.close-details')) === null || _e === void 0 ? void 0 : _e.addEventListener('click', () => {
398
- this.selectedRequest = null;
399
- this.renderPanel();
704
+ this.errors = list(source.errors)
705
+ .slice(0, this.config.maxErrorEntries)
706
+ .map(item => {
707
+ var _a;
708
+ return ({
709
+ id: str(item.id, nextId()),
710
+ type: item.type === 'Promise Rejection' ? 'Promise Rejection' : 'JavaScript Error',
711
+ message: truncate(str(item.message)),
712
+ timestamp: (_a = num(item.timestamp)) !== null && _a !== void 0 ? _a : Date.now(),
713
+ stack: typeof item.stack === 'string' ? truncate(item.stack) : undefined,
714
+ });
400
715
  });
401
- // Network request selection
402
- this.panel.querySelectorAll('.network-request').forEach(req => {
403
- req.addEventListener('click', (e) => {
404
- const id = e.currentTarget.getAttribute('data-id');
405
- this.selectedRequest = this.data.network.find(r => r.id === id) || null;
406
- this.renderPanel();
716
+ this.metrics = list(source.metrics)
717
+ .slice(0, MAX_METRIC_ENTRIES)
718
+ .map(item => {
719
+ var _a;
720
+ return ({
721
+ id: str(item.id, nextId()),
722
+ name: str(item.name),
723
+ data: item.data,
724
+ duration: num(item.duration),
725
+ timestamp: (_a = num(item.timestamp)) !== null && _a !== void 0 ? _a : Date.now(),
407
726
  });
408
727
  });
728
+ this.selectedRequestId = null;
729
+ this.scheduleRender();
409
730
  }
410
- setupEventListeners() {
411
- document.addEventListener('keydown', (e) => {
412
- if (e.ctrlKey && e.shiftKey && e.key === 'D') {
413
- e.preventDefault();
414
- this.toggle();
731
+ /**
732
+ * Removes the UI, restores every patched API, detaches listeners, stops the
733
+ * frame loop and uninstalls plugins. Safe to call more than once.
734
+ */
735
+ destroy() {
736
+ var _a, _b;
737
+ if (this.destroyed)
738
+ return;
739
+ this.destroyed = true;
740
+ for (const patch of this.patches.reverse()) {
741
+ // Only restore when nobody has wrapped our replacement since; otherwise the
742
+ // replacement stays in place but passes straight through (destroyed flag).
743
+ if (patch.target[patch.key] === patch.replacement)
744
+ patch.target[patch.key] = patch.original;
745
+ }
746
+ this.patches = [];
747
+ for (const cleanup of this.cleanups.splice(0)) {
748
+ try {
749
+ cleanup();
415
750
  }
416
- });
751
+ catch (_c) {
752
+ // Listener removal cannot meaningfully fail; ignore.
753
+ }
754
+ }
755
+ this.stopPerformanceLoop();
756
+ (_a = this.widget) === null || _a === void 0 ? void 0 : _a.remove();
757
+ (_b = this.panel) === null || _b === void 0 ? void 0 : _b.remove();
758
+ this.widget = null;
759
+ this.panel = null;
760
+ for (const plugin of this.pluginSystem.getAll()) {
761
+ this.pluginSystem.unregister(plugin.name).catch(error => this.reportInternal(`Failed to uninstall plugin "${plugin.name}"`, error));
762
+ }
763
+ this.emitSafely('inspector:destroy', undefined);
764
+ this.events.removeAllListeners();
765
+ this.network = [];
766
+ this.consoleEntries = [];
767
+ this.errors = [];
768
+ this.metrics = [];
769
+ this.marks.clear();
770
+ EnhancedDevInspector.instances = EnhancedDevInspector.instances.filter(instance => instance !== this);
771
+ }
772
+ // ---------------------------------------------------------------------------
773
+ // Capture
774
+ // ---------------------------------------------------------------------------
775
+ get capturingAllowed() {
776
+ return !this.destroyed && this.isRecording && !this.capturing;
777
+ }
778
+ /** Runs capture code with re-entrancy protection; capture failures never reach the page. */
779
+ capture(fn) {
780
+ if (!this.capturingAllowed)
781
+ return;
782
+ this.capturing = true;
783
+ try {
784
+ fn();
785
+ }
786
+ catch (error) {
787
+ this.reportInternal('Capture failed', error);
788
+ }
789
+ finally {
790
+ this.capturing = false;
791
+ }
792
+ }
793
+ emitSafely(event, data) {
794
+ this.events.emit(event, data);
795
+ }
796
+ pushBounded(list, entry, max) {
797
+ list.unshift(entry);
798
+ if (list.length > max)
799
+ list.length = max;
800
+ }
801
+ patch(target, key, replacement) {
802
+ const original = target[key];
803
+ target[key] = replacement;
804
+ this.patches.push({ target, key, original, replacement });
417
805
  }
418
- setupInterceptors() {
419
- this.interceptFetch();
420
- this.interceptXHR();
421
- this.interceptConsole();
422
- this.interceptErrors();
423
- this.setupPerformanceMonitoring();
806
+ listen(target, type, handler) {
807
+ target.addEventListener(type, handler);
808
+ this.cleanups.push(() => target.removeEventListener(type, handler));
809
+ }
810
+ addNetworkEntry(entry) {
811
+ this.pushBounded(this.network, entry, this.config.maxNetworkEntries);
812
+ this.emitSafely('network:request', { ...entry });
813
+ this.scheduleRender();
814
+ }
815
+ finishNetworkEntry(entry, status, duration, error) {
816
+ entry.status = status;
817
+ entry.duration = Math.round(duration);
818
+ if (error !== undefined)
819
+ entry.error = error;
820
+ this.emitSafely(status === 'error' ? 'network:error' : 'network:response', { ...entry });
821
+ if (duration > this.config.slowRequestThreshold) {
822
+ const issue = { type: 'slow-network', message: `Slow network request: ${entry.url}`, url: entry.url, duration: entry.duration };
823
+ this.emitSafely('performance:issue', issue);
824
+ this.callUser(this.config.onPerformanceIssue, issue);
825
+ }
826
+ this.scheduleRender();
424
827
  }
425
828
  interceptFetch() {
426
- const originalFetch = window.fetch;
427
- window.fetch = async (input, init) => {
428
- if (!this.isRecording)
429
- return originalFetch(input, init);
430
- const requestId = Math.random().toString(36).substr(2, 9);
431
- const startTime = performance.now();
432
- const url = typeof input === 'string' ? input : input.toString();
433
- const options = init || {};
434
- const request = {
435
- id: requestId,
436
- url: url,
437
- method: options.method || 'GET',
438
- status: 'pending',
439
- timestamp: new Date()
440
- };
441
- this.data.network.unshift(request);
442
- this.renderPanel();
829
+ const originalFetch = typeof window.fetch === 'function' ? window.fetch : null;
830
+ if (!originalFetch)
831
+ return;
832
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
833
+ const self = this;
834
+ const instrumentedFetch = function (...args) {
835
+ let entry = null;
836
+ const start = performance.now();
837
+ self.capture(() => {
838
+ entry = { id: nextId(), type: 'fetch', url: requestUrl(args[0]), method: requestMethod(args[0], args[1]), status: 'pending', timestamp: Date.now() };
839
+ self.addNetworkEntry(entry);
840
+ });
841
+ if (!entry)
842
+ return Reflect.apply(originalFetch, this, args);
843
+ const tracked = entry;
844
+ let result;
443
845
  try {
444
- const response = await originalFetch(input, init);
445
- const endTime = performance.now();
446
- const index = this.data.network.findIndex(r => r.id === requestId);
447
- if (index !== -1) {
448
- this.data.network[index] = {
449
- ...request,
450
- status: response.status,
451
- duration: Math.round(endTime - startTime)
452
- };
453
- this.renderPanel();
454
- }
455
- return response;
846
+ // Call through with the caller's receiver and arguments untouched.
847
+ result = Reflect.apply(originalFetch, this, args);
456
848
  }
457
849
  catch (error) {
458
- const endTime = performance.now();
459
- const index = this.data.network.findIndex(r => r.id === requestId);
460
- if (index !== -1) {
461
- this.data.network[index] = {
462
- ...request,
463
- status: 'error',
464
- error: error.message,
465
- duration: Math.round(endTime - startTime)
466
- };
467
- this.renderPanel();
468
- }
850
+ self.capture(() => self.finishNetworkEntry(tracked, 'error', performance.now() - start, error instanceof Error ? error.message : String(error)));
469
851
  throw error;
470
852
  }
853
+ return Promise.resolve(result).then(response => {
854
+ self.capture(() => self.finishNetworkEntry(tracked, response.status, performance.now() - start));
855
+ return response;
856
+ }, (error) => {
857
+ self.capture(() => self.finishNetworkEntry(tracked, 'error', performance.now() - start, error instanceof Error ? error.message : String(error)));
858
+ throw error;
859
+ });
471
860
  };
861
+ this.patch(window, 'fetch', instrumentedFetch);
472
862
  }
473
863
  interceptXHR() {
474
- const originalXHR = window.XMLHttpRequest;
864
+ const XHR = typeof XMLHttpRequest === 'function' ? XMLHttpRequest : null;
865
+ if (!XHR)
866
+ return;
867
+ const proto = XHR.prototype;
868
+ const originalOpen = proto.open;
869
+ const originalSend = proto.send;
475
870
  // eslint-disable-next-line @typescript-eslint/no-this-alias
476
871
  const self = this;
477
- window.XMLHttpRequest = function () {
478
- const xhr = new originalXHR();
479
- const requestId = Math.random().toString(36).substr(2, 9);
480
- let startTime;
481
- const originalOpen = xhr.open;
482
- const originalSend = xhr.send;
483
- xhr.open = function (method, url, ...args) {
484
- if (self.isRecording) {
485
- const request = {
486
- id: requestId,
487
- url,
488
- method,
489
- status: 'pending',
490
- timestamp: new Date()
491
- };
492
- self.data.network.unshift(request);
493
- self.renderPanel();
494
- }
495
- return originalOpen.apply(this, [method, url, ...args]);
496
- };
497
- xhr.send = function (...args) {
498
- if (self.isRecording) {
499
- startTime = performance.now();
500
- xhr.addEventListener('loadend', () => {
501
- const endTime = performance.now();
502
- const index = self.data.network.findIndex(r => r.id === requestId);
503
- if (index !== -1) {
504
- self.data.network[index] = {
505
- ...self.data.network[index],
506
- status: xhr.status,
507
- duration: Math.round(endTime - startTime)
508
- };
509
- self.renderPanel();
510
- }
511
- });
512
- }
513
- return originalSend.apply(this, args);
514
- };
515
- return xhr;
872
+ // Patch the prototype rather than replacing the constructor, so
873
+ // `instanceof XMLHttpRequest` and constants such as XMLHttpRequest.DONE keep working.
874
+ const open = function (...args) {
875
+ if (!self.destroyed) {
876
+ self.xhrState.set(this, { method: typeof args[0] === 'string' ? args[0].toUpperCase() : 'GET', url: requestUrl(args[1]) });
877
+ }
878
+ return Reflect.apply(originalOpen, this, args);
879
+ };
880
+ const send = function (...args) {
881
+ const state = self.xhrState.get(this);
882
+ if (state)
883
+ self.capture(() => self.trackXhr(this, state));
884
+ return Reflect.apply(originalSend, this, args);
885
+ };
886
+ this.patch(proto, 'open', open);
887
+ this.patch(proto, 'send', send);
888
+ }
889
+ trackXhr(xhr, state) {
890
+ const entry = { id: nextId(), type: 'xhr', url: state.url, method: state.method, status: 'pending', timestamp: Date.now() };
891
+ state.entry = entry;
892
+ state.start = performance.now();
893
+ state.failure = undefined;
894
+ const fail = (reason) => () => {
895
+ state.failure = reason;
896
+ };
897
+ const onError = fail('Network error');
898
+ const onAbort = fail('Request aborted');
899
+ const onTimeout = fail('Request timed out');
900
+ const onLoadEnd = () => {
901
+ var _a;
902
+ xhr.removeEventListener('error', onError);
903
+ xhr.removeEventListener('abort', onAbort);
904
+ xhr.removeEventListener('timeout', onTimeout);
905
+ xhr.removeEventListener('loadend', onLoadEnd);
906
+ if (state.entry !== entry || this.destroyed)
907
+ return;
908
+ const duration = performance.now() - ((_a = state.start) !== null && _a !== void 0 ? _a : performance.now());
909
+ const failed = state.failure !== undefined || xhr.status === 0;
910
+ this.capture(() => { var _a; return this.finishNetworkEntry(entry, failed ? 'error' : xhr.status, duration, failed ? (_a = state.failure) !== null && _a !== void 0 ? _a : 'Network error' : undefined); });
516
911
  };
912
+ xhr.addEventListener('error', onError);
913
+ xhr.addEventListener('abort', onAbort);
914
+ xhr.addEventListener('timeout', onTimeout);
915
+ xhr.addEventListener('loadend', onLoadEnd);
916
+ this.addNetworkEntry(entry);
517
917
  }
518
918
  interceptConsole() {
519
- const levels = ['log', 'warn', 'error', 'info', 'debug'];
520
- levels.forEach(level => {
919
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
920
+ const self = this;
921
+ for (const level of CONSOLE_METHODS) {
521
922
  const original = console[level];
522
- console[level] = (...args) => {
523
- if (this.isRecording) {
524
- const log = {
525
- id: Math.random().toString(36).substr(2, 9),
923
+ if (typeof original !== 'function')
924
+ continue;
925
+ const wrapper = function (...args) {
926
+ // The real console runs first and its result (and any exception) is passed through.
927
+ const result = Reflect.apply(original, this === undefined ? console : this, args);
928
+ self.capture(() => {
929
+ const entry = {
930
+ id: nextId(),
526
931
  level,
527
- message: args.map(arg => {
528
- if (typeof arg === 'object') {
529
- try {
530
- return JSON.stringify(arg, null, 2);
531
- }
532
- catch (_a) {
533
- return String(arg);
534
- }
535
- }
536
- return String(arg);
537
- }).join(' '),
538
- timestamp: new Date()
932
+ message: truncate(args.map(stringifyArg).join(' ')),
933
+ timestamp: Date.now(),
539
934
  };
540
- this.data.console.unshift(log);
541
- if (this.data.console.length > 500) {
542
- this.data.console = this.data.console.slice(0, 500);
543
- }
544
- this.renderPanel();
545
- }
546
- original.apply(console, args);
935
+ self.pushBounded(self.consoleEntries, entry, self.config.maxConsoleEntries);
936
+ self.emitSafely('console:log', { ...entry });
937
+ self.scheduleRender();
938
+ });
939
+ return result;
547
940
  };
548
- });
941
+ this.patch(console, level, wrapper);
942
+ }
549
943
  }
550
944
  interceptErrors() {
551
- window.addEventListener('error', (event) => {
552
- var _a;
553
- if (!this.isRecording)
554
- return;
555
- const error = {
556
- id: Math.random().toString(36).substr(2, 9),
557
- type: 'JavaScript Error',
558
- message: event.message,
559
- timestamp: new Date(),
560
- stack: (_a = event.error) === null || _a === void 0 ? void 0 : _a.stack
561
- };
562
- this.data.errors.unshift(error);
563
- this.renderPanel();
945
+ const record = (entry, error) => {
946
+ this.pushBounded(this.errors, entry, this.config.maxErrorEntries);
947
+ this.emitSafely('error:uncaught', { ...entry });
948
+ this.callUser(this.config.onError, error);
949
+ this.scheduleRender();
950
+ };
951
+ this.listen(window, 'error', (event) => {
952
+ this.capture(() => {
953
+ var _a;
954
+ const error = event.error instanceof Error ? event.error : new Error(String((_a = event.message) !== null && _a !== void 0 ? _a : 'Unknown error'));
955
+ record({
956
+ id: nextId(),
957
+ type: 'JavaScript Error',
958
+ message: truncate(String(event.message || error.message)),
959
+ timestamp: Date.now(),
960
+ stack: this.config.captureStackTraces && error.stack ? truncate(error.stack) : undefined,
961
+ filename: typeof event.filename === 'string' && event.filename ? event.filename : undefined,
962
+ lineno: typeof event.lineno === 'number' ? event.lineno : undefined,
963
+ colno: typeof event.colno === 'number' ? event.colno : undefined,
964
+ }, error);
965
+ });
564
966
  });
565
- window.addEventListener('unhandledrejection', (event) => {
566
- var _a;
567
- if (!this.isRecording)
568
- return;
569
- const error = {
570
- id: Math.random().toString(36).substr(2, 9),
571
- type: 'Promise Rejection',
572
- message: ((_a = event.reason) === null || _a === void 0 ? void 0 : _a.message) || String(event.reason),
573
- timestamp: new Date()
574
- };
575
- this.data.errors.unshift(error);
576
- this.renderPanel();
967
+ this.listen(window, 'unhandledrejection', (event) => {
968
+ this.capture(() => {
969
+ const reason = event.reason;
970
+ const error = reason instanceof Error ? reason : new Error(stringifyArg(reason));
971
+ record({
972
+ id: nextId(),
973
+ type: 'Promise Rejection',
974
+ message: truncate(error.message),
975
+ timestamp: Date.now(),
976
+ stack: this.config.captureStackTraces && reason instanceof Error && reason.stack ? truncate(reason.stack) : undefined,
977
+ }, error);
978
+ });
577
979
  });
578
980
  }
579
- setupPerformanceMonitoring() {
580
- let lastTime = performance.now();
581
- let frames = 0;
582
- const measurePerformance = () => {
583
- frames++;
584
- const currentTime = performance.now();
585
- if (currentTime >= lastTime + 1000) {
586
- this.data.performance.fps = Math.round(frames * 1000 / (currentTime - lastTime));
587
- frames = 0;
588
- lastTime = currentTime;
589
- if (performance.memory) {
590
- const memory = performance.memory;
591
- this.data.performance.memory = {
592
- used: Math.round(memory.usedJSHeapSize / 1048576),
593
- total: Math.round(memory.totalJSHeapSize / 1048576),
594
- limit: Math.round(memory.jsHeapSizeLimit / 1048576)
595
- };
596
- }
597
- if (this.isVisible && this.activeTab === 'performance') {
598
- this.renderPanel();
599
- }
981
+ setupHotkeys() {
982
+ const { toggle, minimize } = this.config.hotkeys;
983
+ if (!toggle && !minimize)
984
+ return;
985
+ this.listen(document, 'keydown', (event) => {
986
+ const combo = eventCombo(event);
987
+ if (toggle && combo === toggle) {
988
+ event.preventDefault();
989
+ this.toggle();
600
990
  }
601
- requestAnimationFrame(measurePerformance);
602
- };
603
- measurePerformance();
604
- }
605
- show() {
606
- if (this.panel) {
607
- this.panel.style.display = 'flex';
608
- this.isVisible = true;
609
- if (this.widget)
610
- this.widget.style.display = 'none';
611
- }
612
- }
613
- hide() {
614
- if (this.panel) {
615
- this.panel.style.display = 'none';
616
- this.isVisible = false;
617
- if (this.widget)
618
- this.widget.style.display = 'flex';
619
- }
620
- }
621
- toggle() {
622
- this.isVisible ? this.hide() : this.show();
623
- }
624
- minimize() {
625
- this.isMinimized = !this.isMinimized;
626
- if (this.panel) {
627
- this.panel.style.height = this.isMinimized ? '60px' : '650px';
628
- this.renderPanel();
629
- }
630
- }
631
- clear(type) {
632
- if (type === 'network') {
633
- this.data.network = [];
634
- this.selectedRequest = null;
635
- }
636
- else if (type === 'console') {
637
- this.data.console = [];
638
- }
639
- else if (type === 'errors') {
640
- this.data.errors = [];
641
- }
642
- this.renderPanel();
643
- }
644
- toggleRecording() {
645
- this.isRecording = !this.isRecording;
646
- this.renderPanel();
647
- }
648
- destroy() {
649
- if (this.widget && this.widget.parentNode) {
650
- this.widget.parentNode.removeChild(this.widget);
651
- }
652
- if (this.panel && this.panel.parentNode) {
653
- this.panel.parentNode.removeChild(this.panel);
654
- }
655
- }
656
- }
657
- // Auto-initialize if in browser
658
- if (typeof window !== 'undefined') {
659
- window.EnhancedDevInspector = EnhancedDevInspector;
660
- }
661
-
662
- class EventEmitter {
663
- constructor(options = {}) {
664
- var _a, _b;
665
- this.events = new Map();
666
- this.maxListeners = (_a = options.maxListeners) !== null && _a !== void 0 ? _a : 10;
667
- this.captureRejections = (_b = options.captureRejections) !== null && _b !== void 0 ? _b : false;
668
- }
669
- on(event, listener) {
670
- if (!this.events.has(event)) {
671
- this.events.set(event, new Set());
672
- }
673
- const listeners = this.events.get(event);
674
- if (listeners.size >= this.maxListeners) {
675
- console.warn(`MaxListenersExceededWarning: Possible EventEmitter memory leak detected. ${listeners.size} ${String(event)} listeners added.`);
676
- }
677
- listeners.add(listener);
678
- return () => {
679
- listeners.delete(listener);
680
- if (listeners.size === 0) {
681
- this.events.delete(event);
991
+ else if (minimize && combo === minimize) {
992
+ event.preventDefault();
993
+ if (!this.isVisible)
994
+ this.show();
995
+ this.minimize();
682
996
  }
683
- };
684
- }
685
- once(event, listener) {
686
- const wrappedListener = (data) => {
687
- unsubscribe();
688
- listener(data);
689
- };
690
- const unsubscribe = this.on(event, wrappedListener);
691
- return unsubscribe;
997
+ });
692
998
  }
693
- emit(event, ...args) {
694
- const listeners = this.events.get(event);
695
- if (!listeners || listeners.size === 0) {
696
- return false;
999
+ /** Calls a user callback; a throwing callback is reported but never breaks capture. */
1000
+ callUser(callback, value) {
1001
+ if (!callback)
1002
+ return;
1003
+ try {
1004
+ callback(value);
697
1005
  }
698
- const data = args[0];
699
- listeners.forEach(listener => {
700
- try {
701
- listener(data);
1006
+ catch (error) {
1007
+ this.reportInternal('A DevInspector callback threw', error);
1008
+ }
1009
+ }
1010
+ reportInternal(message, error) {
1011
+ // Use the unpatched console so internal problems are visible but never captured.
1012
+ const patched = this.patches.find(patch => patch.target === console && patch.key === 'error');
1013
+ const log = (patched ? patched.original : console.error);
1014
+ try {
1015
+ log.call(console, `[DevInspector] ${message}:`, error);
1016
+ }
1017
+ catch (_a) {
1018
+ // Nothing else we can do.
1019
+ }
1020
+ }
1021
+ // ---------------------------------------------------------------------------
1022
+ // Performance loop (runs only while the panel is visible)
1023
+ // ---------------------------------------------------------------------------
1024
+ startPerformanceLoop() {
1025
+ if (!this.config.features.performance || this.rafId !== null || typeof requestAnimationFrame !== 'function')
1026
+ return;
1027
+ let last = performance.now();
1028
+ let frames = 0;
1029
+ const tick = () => {
1030
+ if (this.destroyed || !this.isVisible) {
1031
+ this.rafId = null;
1032
+ return;
702
1033
  }
703
- catch (error) {
704
- if (this.captureRejections) {
705
- // Use type assertion for recursive error emit
706
- this.emit('error', error);
707
- }
708
- else {
709
- console.error(`Error in event listener for "${String(event)}":`, error);
1034
+ frames++;
1035
+ const now = performance.now();
1036
+ if (now - last >= 1000) {
1037
+ this.performanceStats.fps = Math.round((frames * 1000) / (now - last));
1038
+ frames = 0;
1039
+ last = now;
1040
+ const memory = performance.memory;
1041
+ if (memory) {
1042
+ this.performanceStats.memory = {
1043
+ used: Math.round(memory.usedJSHeapSize / 1048576),
1044
+ total: Math.round(memory.totalJSHeapSize / 1048576),
1045
+ limit: Math.round(memory.jsHeapSizeLimit / 1048576),
1046
+ };
710
1047
  }
1048
+ if (this.activeTab === 'performance')
1049
+ this.scheduleRender();
711
1050
  }
712
- });
713
- return true;
714
- }
715
- off(event, listener) {
716
- if (!listener) {
717
- this.events.delete(event);
1051
+ this.rafId = requestAnimationFrame(tick);
1052
+ };
1053
+ this.rafId = requestAnimationFrame(tick);
1054
+ }
1055
+ stopPerformanceLoop() {
1056
+ if (this.rafId !== null && typeof cancelAnimationFrame === 'function')
1057
+ cancelAnimationFrame(this.rafId);
1058
+ this.rafId = null;
1059
+ }
1060
+ // ---------------------------------------------------------------------------
1061
+ // UI
1062
+ // ---------------------------------------------------------------------------
1063
+ mountWhenReady() {
1064
+ if (document.body) {
1065
+ this.mount();
718
1066
  return;
719
1067
  }
720
- const listeners = this.events.get(event);
721
- if (listeners) {
722
- listeners.delete(listener);
723
- if (listeners.size === 0) {
724
- this.events.delete(event);
1068
+ const onReady = () => {
1069
+ if (!this.destroyed && !this.widget)
1070
+ this.mount();
1071
+ };
1072
+ this.listen(document, 'DOMContentLoaded', onReady);
1073
+ }
1074
+ get colors() {
1075
+ return PALETTES[this.config.theme];
1076
+ }
1077
+ placement(offset) {
1078
+ const [vertical, horizontal] = this.config.position.split('-');
1079
+ return `${vertical}: ${offset}px; ${horizontal}: ${offset}px;`;
1080
+ }
1081
+ mount() {
1082
+ const widget = document.createElement('div');
1083
+ widget.className = 'devinspector-widget';
1084
+ widget.setAttribute('role', 'button');
1085
+ widget.setAttribute('aria-label', 'Open DevInspector');
1086
+ widget.title = 'DevInspector';
1087
+ widget.textContent = '🔍';
1088
+ widget.style.cssText = `position: fixed; ${this.placement(24)} width: 56px; height: 56px;
1089
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 50%;
1090
+ display: flex; align-items: center; justify-content: center; cursor: pointer; z-index: 999999;
1091
+ color: white; font-size: 24px; box-shadow: 0 8px 32px rgba(102, 126, 234, 0.4); user-select: none;`;
1092
+ widget.addEventListener('click', () => this.toggle());
1093
+ const panel = document.createElement('div');
1094
+ panel.className = 'devinspector-panel';
1095
+ panel.style.cssText = `position: fixed; ${this.placement(24)} width: 480px; max-width: calc(100vw - 48px);
1096
+ height: 650px; max-height: calc(100vh - 48px); background: ${this.colors.bg}; border: 1px solid ${this.colors.border};
1097
+ border-radius: 12px; display: none; flex-direction: column; z-index: 999998; box-shadow: 0 24px 64px rgba(0, 0, 0, 0.5);
1098
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 13px;
1099
+ color: ${this.colors.text}; overflow: hidden;`;
1100
+ // One delegated listener survives every re-render (no per-render listener churn).
1101
+ panel.addEventListener('click', event => this.handlePanelClick(event));
1102
+ this.widget = widget;
1103
+ this.panel = panel;
1104
+ document.body.appendChild(widget);
1105
+ document.body.appendChild(panel);
1106
+ this.render();
1107
+ }
1108
+ handlePanelClick(event) {
1109
+ var _a, _b;
1110
+ const target = event.target;
1111
+ const actionable = (_a = target === null || target === void 0 ? void 0 : target.closest) === null || _a === void 0 ? void 0 : _a.call(target, '[data-action]');
1112
+ if (!actionable)
1113
+ return;
1114
+ const action = actionable.getAttribute('data-action');
1115
+ switch (action) {
1116
+ case 'minimize':
1117
+ this.minimize();
1118
+ break;
1119
+ case 'close':
1120
+ this.hide();
1121
+ break;
1122
+ case 'tab': {
1123
+ const tab = actionable.getAttribute('data-tab');
1124
+ if (['network', 'console', 'performance', 'errors'].includes(tab)) {
1125
+ this.activeTab = tab;
1126
+ this.render();
1127
+ }
1128
+ break;
725
1129
  }
1130
+ case 'clear':
1131
+ this.clear((_b = actionable.getAttribute('data-target')) !== null && _b !== void 0 ? _b : 'all');
1132
+ break;
1133
+ case 'toggle-recording':
1134
+ this.toggleRecording();
1135
+ break;
1136
+ case 'select-request':
1137
+ this.selectedRequestId = actionable.getAttribute('data-id');
1138
+ this.render();
1139
+ break;
1140
+ case 'close-details':
1141
+ this.selectedRequestId = null;
1142
+ this.render();
1143
+ break;
726
1144
  }
727
1145
  }
728
- removeAllListeners(event) {
729
- if (event) {
730
- this.events.delete(event);
1146
+ /** Coalesces renders triggered by bursts of captured events into one microtask. */
1147
+ scheduleRender() {
1148
+ if (this.renderQueued || !this.panel || !this.isVisible)
1149
+ return;
1150
+ this.renderQueued = true;
1151
+ queueMicrotask(() => {
1152
+ this.renderQueued = false;
1153
+ if (!this.destroyed)
1154
+ this.render();
1155
+ });
1156
+ }
1157
+ render() {
1158
+ if (!this.panel || !this.isVisible)
1159
+ return;
1160
+ const c = this.colors;
1161
+ const button = (action, label, extra = '', background = '#374151') => `<button type="button" data-action="${action}" ${extra} style="padding: 6px 12px; background: ${background}; border: none; color: white; cursor: pointer; border-radius: 6px; margin-right: 8px;">${label}</button>`;
1162
+ const tabs = [
1163
+ { id: 'network', label: 'Network', count: this.network.length },
1164
+ { id: 'console', label: 'Console', count: this.consoleEntries.length },
1165
+ { id: 'performance', label: 'Performance' },
1166
+ { id: 'errors', label: 'Errors', count: this.errors.length },
1167
+ ];
1168
+ const header = `
1169
+ <div style="display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; background: ${c.header}; border-bottom: 1px solid ${c.border};">
1170
+ <div style="display: flex; align-items: center; gap: 8px;">
1171
+ <span style="width: 8px; height: 8px; border-radius: 50%; background: ${this.isRecording ? '#ef4444' : '#6b7280'};"></span>
1172
+ <span style="font-weight: 600; font-size: 14px;">DevInspector v${escapeHtml(VERSION)}</span>
1173
+ </div>
1174
+ <div style="display: flex; gap: 4px;">
1175
+ <button type="button" data-action="minimize" aria-label="Minimize" style="padding: 6px; background: none; border: none; color: ${c.muted}; cursor: pointer;">−</button>
1176
+ <button type="button" data-action="close" aria-label="Close" style="padding: 6px; background: none; border: none; color: ${c.muted}; cursor: pointer;">×</button>
1177
+ </div>
1178
+ </div>`;
1179
+ if (this.isMinimized) {
1180
+ this.panel.innerHTML = header;
1181
+ return;
731
1182
  }
732
- else {
733
- this.events.clear();
1183
+ const tabBar = tabs
1184
+ .map(tab => `<button type="button" data-action="tab" data-tab="${tab.id}" style="padding: 12px 16px; border: none; cursor: pointer;
1185
+ background: ${this.activeTab === tab.id ? c.bg : 'transparent'}; color: ${this.activeTab === tab.id ? '#3b82f6' : c.muted};
1186
+ border-bottom: 2px solid ${this.activeTab === tab.id ? '#3b82f6' : 'transparent'};">${tab.label}${tab.count !== undefined
1187
+ ? ` <span style="background: #374151; color: white; padding: 2px 6px; border-radius: 10px; font-size: 11px; margin-left: 4px;">${tab.count}</span>`
1188
+ : ''}</button>`)
1189
+ .join('');
1190
+ let content = '';
1191
+ switch (this.activeTab) {
1192
+ case 'network':
1193
+ content = this.renderNetwork(button);
1194
+ break;
1195
+ case 'console':
1196
+ content = this.renderConsole(button);
1197
+ break;
1198
+ case 'performance':
1199
+ content = this.renderPerformance(button);
1200
+ break;
1201
+ case 'errors':
1202
+ content = this.renderErrors(button);
1203
+ break;
734
1204
  }
1205
+ this.panel.innerHTML = `${header}
1206
+ <div style="display: flex; background: ${c.header}; border-bottom: 1px solid ${c.border};">${tabBar}</div>
1207
+ <div style="flex: 1; min-height: 0; display: flex; flex-direction: column;">${content}</div>`;
735
1208
  }
736
- listenerCount(event) {
737
- const listeners = this.events.get(event);
738
- return listeners ? listeners.size : 0;
1209
+ toolbar(buttons, summary) {
1210
+ const c = this.colors;
1211
+ return `<div style="padding: 12px; border-bottom: 1px solid ${c.border}; background: ${c.toolbar}; display: flex; align-items: center;">
1212
+ ${buttons}<span style="margin-left: auto; color: ${c.muted}; font-size: 12px;">${summary}</span></div>`;
739
1213
  }
740
- eventNames() {
741
- return Array.from(this.events.keys());
1214
+ empty(text) {
1215
+ return `<div style="display: flex; align-items: center; justify-content: center; height: 200px; color: ${this.colors.muted};">${text}</div>`;
742
1216
  }
743
- setMaxListeners(n) {
744
- this.maxListeners = n;
1217
+ renderNetwork(button) {
1218
+ var _a;
1219
+ const c = this.colors;
1220
+ const visible = this.config.hideAssets ? this.network.filter(entry => !ASSET_PATTERN.test(entry.url)) : this.network;
1221
+ const rows = visible
1222
+ .map(entry => {
1223
+ var _a;
1224
+ const selected = entry.id === this.selectedRequestId;
1225
+ return `<div data-action="select-request" data-id="${escapeHtml(entry.id)}" style="padding: 10px 16px; border-bottom: 1px solid ${c.row}; cursor: pointer; ${selected ? 'background: rgba(59, 130, 246, 0.25);' : ''}">
1226
+ <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
1227
+ <div style="display: flex; gap: 8px;">
1228
+ <span style="background: ${methodColor(entry.method)}; color: white; padding: 2px 6px; border-radius: 4px; font-size: 11px; font-weight: 600;">${escapeHtml(entry.method)}</span>
1229
+ <span style="color: ${statusColor(entry.status)}; font-weight: 600;">${escapeHtml(entry.status)}</span>
1230
+ <span style="color: ${c.muted};">${(_a = entry.duration) !== null && _a !== void 0 ? _a : '-'}ms</span>
1231
+ </div>
1232
+ <span style="color: ${c.muted}; font-size: 11px;">${escapeHtml(new Date(entry.timestamp).toLocaleTimeString())}</span>
1233
+ </div>
1234
+ <div style="font-size: 12px; word-break: break-all;">${escapeHtml(entry.url)}</div>
1235
+ </div>`;
1236
+ })
1237
+ .join('');
1238
+ const selected = this.selectedRequestId ? this.network.find(entry => entry.id === this.selectedRequestId) : undefined;
1239
+ const details = selected
1240
+ ? `<div style="border-top: 1px solid ${c.border}; max-height: 200px; overflow-y: auto; background: ${c.toolbar}; padding: 12px 16px; font-size: 12px;">
1241
+ <div style="display: flex; justify-content: space-between; margin-bottom: 8px;"><strong>Request details</strong>
1242
+ <button type="button" data-action="close-details" aria-label="Close details" style="background: none; border: none; color: ${c.muted}; cursor: pointer;">×</button></div>
1243
+ <div><strong>URL:</strong> ${escapeHtml(selected.url)}</div>
1244
+ <div><strong>Method:</strong> ${escapeHtml(selected.method)}</div>
1245
+ <div><strong>Type:</strong> ${escapeHtml(selected.type)}</div>
1246
+ <div><strong>Status:</strong> ${escapeHtml(selected.status)}</div>
1247
+ <div><strong>Duration:</strong> ${(_a = selected.duration) !== null && _a !== void 0 ? _a : '-'}ms</div>
1248
+ ${selected.error ? `<div><strong>Error:</strong> ${escapeHtml(selected.error)}</div>` : ''}
1249
+ </div>`
1250
+ : '';
1251
+ return `${this.toolbar(button('clear', 'Clear', 'data-target="network"') +
1252
+ button('toggle-recording', this.isRecording ? 'Pause' : 'Resume', '', this.isRecording ? '#ef4444' : '#22c55e'), `${visible.length} requests`)}
1253
+ <div style="flex: 1; overflow-y: auto;">${rows || this.empty('No network activity')}</div>${details}`;
1254
+ }
1255
+ renderConsole(button) {
1256
+ const c = this.colors;
1257
+ const rows = this.consoleEntries
1258
+ .map(entry => `<div style="padding: 8px 16px; border-bottom: 1px solid ${c.row}; font-size: 12px;">
1259
+ <span style="color: ${levelColor(entry.level)}; text-transform: uppercase; font-weight: 600;">[${escapeHtml(entry.level)}]</span>
1260
+ <span style="color: ${c.muted}; margin: 0 8px;">${escapeHtml(new Date(entry.timestamp).toLocaleTimeString())}</span>
1261
+ <span style="white-space: pre-wrap; word-break: break-word;">${escapeHtml(entry.message)}</span>
1262
+ </div>`)
1263
+ .join('');
1264
+ return `${this.toolbar(button('clear', 'Clear', 'data-target="console"'), `${this.consoleEntries.length} logs`)}
1265
+ <div style="flex: 1; overflow-y: auto; font-family: monospace;">${rows || this.empty('No console logs')}</div>`;
1266
+ }
1267
+ renderPerformance(button) {
1268
+ const c = this.colors;
1269
+ const { fps, memory } = this.performanceStats;
1270
+ const rows = this.metrics
1271
+ .slice(0, 100)
1272
+ .map(metric => `<div style="padding: 6px 0; border-bottom: 1px solid ${c.row}; font-size: 12px;">
1273
+ <strong>${escapeHtml(metric.name)}</strong>
1274
+ ${metric.duration !== undefined ? `<span style="color: ${c.muted};"> ${metric.duration.toFixed(1)}ms</span>` : ''}
1275
+ ${metric.data !== undefined ? `<span style="color: ${c.muted};"> ${escapeHtml(truncate(stringifyArg(metric.data)))}</span>` : ''}
1276
+ </div>`)
1277
+ .join('');
1278
+ return `${this.toolbar(button('clear', 'Clear', 'data-target="metrics"'), `${this.metrics.length} metrics`)}
1279
+ <div style="flex: 1; overflow-y: auto; padding: 16px;">
1280
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px;">
1281
+ <div style="background: #1e3a8a; border-radius: 12px; padding: 16px; text-align: center;">
1282
+ <div style="font-size: 28px; font-weight: 700; color: #93c5fd;">${this.config.features.performance ? fps : '-'}</div>
1283
+ <div style="font-size: 12px; color: #bfdbfe;">FPS</div>
1284
+ </div>
1285
+ <div style="background: #166534; border-radius: 12px; padding: 16px; text-align: center;">
1286
+ <div style="font-size: 28px; font-weight: 700; color: #86efac;">${memory ? `${memory.used} MB` : 'N/A'}</div>
1287
+ <div style="font-size: 12px; color: #bbf7d0;">Memory</div>
1288
+ </div>
1289
+ </div>
1290
+ ${rows || `<div style="color: ${c.muted};">Use track(), markStart() and markEnd() to record metrics.</div>`}
1291
+ </div>`;
1292
+ }
1293
+ renderErrors(button) {
1294
+ const c = this.colors;
1295
+ const rows = this.errors
1296
+ .map(error => `<div style="padding: 12px 16px; border-bottom: 1px solid ${c.row};">
1297
+ <div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
1298
+ <span style="color: #ef4444; font-weight: 600;">${escapeHtml(error.type)}</span>
1299
+ <span style="color: ${c.muted}; font-size: 11px;">${escapeHtml(new Date(error.timestamp).toLocaleTimeString())}</span>
1300
+ </div>
1301
+ <div style="color: #f87171; margin-bottom: 6px; word-break: break-word;">${escapeHtml(error.message)}</div>
1302
+ ${error.stack ? `<pre style="background: ${c.code}; padding: 8px; border-radius: 4px; font-size: 11px; color: ${c.muted}; overflow-x: auto; white-space: pre-wrap;">${escapeHtml(error.stack)}</pre>` : ''}
1303
+ </div>`)
1304
+ .join('');
1305
+ return `${this.toolbar(button('clear', 'Clear', 'data-target="errors"'), `${this.errors.length} errors`)}
1306
+ <div style="flex: 1; overflow-y: auto;">${rows || this.empty('No errors recorded')}</div>`;
745
1307
  }
746
- getMaxListeners() {
747
- return this.maxListeners;
1308
+ }
1309
+ EnhancedDevInspector.instances = [];
1310
+ function statusColor(status) {
1311
+ if (typeof status !== 'number')
1312
+ return '#6b7280';
1313
+ if (status >= 200 && status < 300)
1314
+ return '#22c55e';
1315
+ if (status >= 300 && status < 400)
1316
+ return '#f59e0b';
1317
+ if (status >= 400)
1318
+ return '#ef4444';
1319
+ return '#6b7280';
1320
+ }
1321
+ function methodColor(method) {
1322
+ switch (method) {
1323
+ case 'GET':
1324
+ return '#16a34a';
1325
+ case 'POST':
1326
+ return '#2563eb';
1327
+ case 'PUT':
1328
+ return '#d97706';
1329
+ case 'DELETE':
1330
+ return '#dc2626';
1331
+ case 'PATCH':
1332
+ return '#7c3aed';
1333
+ default:
1334
+ return '#6b7280';
1335
+ }
1336
+ }
1337
+ function levelColor(level) {
1338
+ switch (level) {
1339
+ case 'info':
1340
+ return '#60a5fa';
1341
+ case 'warn':
1342
+ return '#fbbf24';
1343
+ case 'error':
1344
+ return '#f87171';
1345
+ case 'debug':
1346
+ return '#a78bfa';
1347
+ default:
1348
+ return 'inherit';
748
1349
  }
749
1350
  }
750
1351
 
@@ -885,7 +1486,11 @@
885
1486
  data
886
1487
  };
887
1488
  if (this.storage.has(key)) {
888
- this.accessOrder = this.accessOrder.filter(k => k !== key);
1489
+ // Optimize: use splice instead of filter to avoid creating new array
1490
+ const index = this.accessOrder.indexOf(key);
1491
+ if (index > -1) {
1492
+ this.accessOrder.splice(index, 1);
1493
+ }
889
1494
  }
890
1495
  else if (this.storage.size >= this.maxSize) {
891
1496
  const evictKey = this.accessOrder.shift();
@@ -902,237 +1507,90 @@
902
1507
  }
903
1508
  get(key) {
904
1509
  const entry = this.storage.get(key);
905
- if (entry && !this.isExpired(entry)) {
906
- this.updateAccessOrder(key);
907
- return entry.data;
908
- }
909
- else if (entry) {
910
- this.delete(key);
911
- }
912
- return undefined;
913
- }
914
- has(key) {
915
- const entry = this.storage.get(key);
916
- if (entry && !this.isExpired(entry)) {
917
- return true;
918
- }
919
- else if (entry) {
920
- this.delete(key);
921
- }
922
- return false;
923
- }
924
- delete(key) {
925
- const entry = this.storage.get(key);
926
- if (entry) {
927
- if (this.onEvict) {
928
- this.onEvict(entry);
929
- }
930
- this.storage.delete(key);
931
- this.accessOrder = this.accessOrder.filter(k => k !== key);
932
- return true;
933
- }
934
- return false;
935
- }
936
- clear() {
937
- if (this.onEvict) {
938
- this.storage.forEach(entry => this.onEvict(entry));
939
- }
940
- this.storage.clear();
941
- this.accessOrder = [];
942
- }
943
- getSize() {
944
- return this.storage.size;
945
- }
946
- getAllKeys() {
947
- return Array.from(this.storage.keys());
948
- }
949
- getAllValues() {
950
- return Array.from(this.storage.values())
951
- .filter(entry => !this.isExpired(entry))
952
- .map(entry => entry.data);
953
- }
954
- updateAccessOrder(key) {
955
- this.accessOrder = this.accessOrder.filter(k => k !== key);
956
- this.accessOrder.push(key);
957
- }
958
- isExpired(entry) {
959
- if (!this.ttl)
960
- return false;
961
- return Date.now() - entry.timestamp > this.ttl;
962
- }
963
- removeExpired() {
964
- let removedCount = 0;
965
- const expiredKeys = [];
966
- this.storage.forEach((entry, key) => {
967
- if (this.isExpired(entry)) {
968
- expiredKeys.push(key);
969
- }
970
- });
971
- expiredKeys.forEach(key => {
972
- if (this.delete(key)) {
973
- removedCount++;
974
- }
975
- });
976
- return removedCount;
977
- }
978
- }
979
-
980
- class PluginSystem {
981
- constructor(context) {
982
- this.plugins = new Map();
983
- this.activePlugins = new Set();
984
- this.installingPlugins = new Set();
985
- this.context = context;
986
- }
987
- async register(plugin) {
988
- if (this.plugins.has(plugin.name)) {
989
- throw new Error(`Plugin "${plugin.name}" is already registered`);
990
- }
991
- if (this.installingPlugins.has(plugin.name)) {
992
- throw new Error(`Plugin "${plugin.name}" is currently being installed`);
993
- }
994
- this.installingPlugins.add(plugin.name);
995
- try {
996
- await plugin.install(this.context);
997
- this.plugins.set(plugin.name, plugin);
998
- this.activePlugins.add(plugin.name);
999
- if (plugin.enable) {
1000
- plugin.enable();
1001
- }
1002
- this.context.events.emit('plugin:registered', {
1003
- name: plugin.name,
1004
- version: plugin.version
1005
- });
1006
- }
1007
- catch (error) {
1008
- this.installingPlugins.delete(plugin.name);
1009
- throw new Error(`Failed to install plugin "${plugin.name}": ${error}`);
1010
- }
1011
- this.installingPlugins.delete(plugin.name);
1012
- }
1013
- async unregister(pluginName) {
1014
- const plugin = this.plugins.get(pluginName);
1015
- if (!plugin) {
1016
- throw new Error(`Plugin "${pluginName}" is not registered`);
1017
- }
1018
- if (plugin.disable) {
1019
- plugin.disable();
1020
- }
1021
- if (plugin.uninstall) {
1022
- await plugin.uninstall();
1023
- }
1024
- this.plugins.delete(pluginName);
1025
- this.activePlugins.delete(pluginName);
1026
- this.context.events.emit('plugin:unregistered', {
1027
- name: pluginName
1028
- });
1029
- }
1030
- enable(pluginName) {
1031
- const plugin = this.plugins.get(pluginName);
1032
- if (!plugin) {
1033
- throw new Error(`Plugin "${pluginName}" is not registered`);
1034
- }
1035
- if (this.activePlugins.has(pluginName)) {
1036
- return;
1037
- }
1038
- if (plugin.enable) {
1039
- plugin.enable();
1040
- }
1041
- this.activePlugins.add(pluginName);
1042
- this.context.events.emit('plugin:enabled', {
1043
- name: pluginName
1044
- });
1045
- }
1046
- disable(pluginName) {
1047
- const plugin = this.plugins.get(pluginName);
1048
- if (!plugin) {
1049
- throw new Error(`Plugin "${pluginName}" is not registered`);
1050
- }
1051
- if (!this.activePlugins.has(pluginName)) {
1052
- return;
1510
+ if (entry && !this.isExpired(entry)) {
1511
+ this.updateAccessOrder(key);
1512
+ return entry.data;
1053
1513
  }
1054
- if (plugin.disable) {
1055
- plugin.disable();
1514
+ else if (entry) {
1515
+ this.delete(key);
1056
1516
  }
1057
- this.activePlugins.delete(pluginName);
1058
- this.context.events.emit('plugin:disabled', {
1059
- name: pluginName
1060
- });
1061
- }
1062
- get(pluginName) {
1063
- return this.plugins.get(pluginName);
1064
- }
1065
- has(pluginName) {
1066
- return this.plugins.has(pluginName);
1067
- }
1068
- isActive(pluginName) {
1069
- return this.activePlugins.has(pluginName);
1070
- }
1071
- getAll() {
1072
- return Array.from(this.plugins.values());
1073
- }
1074
- getActive() {
1075
- return Array.from(this.activePlugins).map(name => this.plugins.get(name));
1517
+ return undefined;
1076
1518
  }
1077
- getMetadata(pluginName) {
1078
- const plugin = this.plugins.get(pluginName);
1079
- if (!plugin) {
1080
- return undefined;
1519
+ has(key) {
1520
+ const entry = this.storage.get(key);
1521
+ if (entry && !this.isExpired(entry)) {
1522
+ return true;
1081
1523
  }
1082
- return {
1083
- name: plugin.name,
1084
- version: plugin.version,
1085
- description: plugin.description
1086
- };
1087
- }
1088
- getAllMetadata() {
1089
- return this.getAll().map(plugin => ({
1090
- name: plugin.name,
1091
- version: plugin.version,
1092
- description: plugin.description
1093
- }));
1524
+ else if (entry) {
1525
+ this.delete(key);
1526
+ }
1527
+ return false;
1094
1528
  }
1095
- }
1096
- class BasePlugin {
1097
- async install(context) {
1098
- this.context = context;
1099
- await this.onInstall();
1529
+ delete(key) {
1530
+ const entry = this.storage.get(key);
1531
+ if (entry) {
1532
+ if (this.onEvict) {
1533
+ this.onEvict(entry);
1534
+ }
1535
+ this.storage.delete(key);
1536
+ this.accessOrder = this.accessOrder.filter(k => k !== key);
1537
+ return true;
1538
+ }
1539
+ return false;
1100
1540
  }
1101
- async uninstall() {
1102
- await this.onUninstall();
1103
- this.context = undefined;
1541
+ clear() {
1542
+ if (this.onEvict) {
1543
+ this.storage.forEach(entry => this.onEvict(entry));
1544
+ }
1545
+ this.storage.clear();
1546
+ this.accessOrder = [];
1104
1547
  }
1105
- enable() {
1106
- this.onEnable();
1548
+ getSize() {
1549
+ return this.storage.size;
1107
1550
  }
1108
- disable() {
1109
- this.onDisable();
1551
+ getAllKeys() {
1552
+ return Array.from(this.storage.keys());
1110
1553
  }
1111
- onUninstall() { }
1112
- onEnable() { }
1113
- onDisable() { }
1114
- get inspector() {
1115
- var _a;
1116
- return (_a = this.context) === null || _a === void 0 ? void 0 : _a.inspector;
1554
+ getAllValues() {
1555
+ return Array.from(this.storage.values())
1556
+ .filter(entry => !this.isExpired(entry))
1557
+ .map(entry => entry.data);
1117
1558
  }
1118
- get events() {
1119
- var _a;
1120
- if (!((_a = this.context) === null || _a === void 0 ? void 0 : _a.events)) {
1121
- throw new Error('Events not available - plugin not installed');
1559
+ updateAccessOrder(key) {
1560
+ // Optimize: use splice instead of filter to avoid creating new array
1561
+ const index = this.accessOrder.indexOf(key);
1562
+ if (index > -1) {
1563
+ this.accessOrder.splice(index, 1);
1122
1564
  }
1123
- return this.context.events;
1565
+ this.accessOrder.push(key);
1124
1566
  }
1125
- get storage() {
1126
- var _a;
1127
- return (_a = this.context) === null || _a === void 0 ? void 0 : _a.storage;
1567
+ isExpired(entry) {
1568
+ if (!this.ttl)
1569
+ return false;
1570
+ return Date.now() - entry.timestamp > this.ttl;
1128
1571
  }
1129
- get config() {
1130
- var _a;
1131
- return (_a = this.context) === null || _a === void 0 ? void 0 : _a.config;
1572
+ removeExpired() {
1573
+ let removedCount = 0;
1574
+ const expiredKeys = [];
1575
+ this.storage.forEach((entry, key) => {
1576
+ if (this.isExpired(entry)) {
1577
+ expiredKeys.push(key);
1578
+ }
1579
+ });
1580
+ expiredKeys.forEach(key => {
1581
+ if (this.delete(key)) {
1582
+ removedCount++;
1583
+ }
1584
+ });
1585
+ return removedCount;
1132
1586
  }
1133
1587
  }
1134
1588
 
1135
- class DevInspector {
1589
+ /**
1590
+ * @deprecated The original, asynchronously initialised inspector. It is kept for
1591
+ * backwards compatibility; use the default export (`DevInspector`) instead.
1592
+ */
1593
+ let DevInspector$1 = class DevInspector {
1136
1594
  constructor(config = {}) {
1137
1595
  this.isVisible = false;
1138
1596
  this.isMinimized = false;
@@ -1140,6 +1598,8 @@
1140
1598
  this.ui = null;
1141
1599
  this.initialized = false;
1142
1600
  this.cleanupFunctions = [];
1601
+ this.initPromise = null;
1602
+ this.destroyed = false;
1143
1603
  if (DevInspector.instance) {
1144
1604
  console.warn('DevInspector instance already exists. Returning existing instance.');
1145
1605
  return DevInspector.instance;
@@ -1159,7 +1619,7 @@
1159
1619
  ttl: 60 * 60 * 1000 // 1 hour
1160
1620
  });
1161
1621
  this.errorStorage = new CircularStorage({
1162
- maxSize: 100,
1622
+ maxSize: this.config.maxErrorEntries,
1163
1623
  onEvict: (entry) => this.events.emit('error:evict', entry)
1164
1624
  });
1165
1625
  this.pluginSystem = new PluginSystem({
@@ -1179,9 +1639,8 @@
1179
1639
  DevInspector.instance = this;
1180
1640
  }
1181
1641
  mergeConfig(config) {
1182
- var _a;
1183
1642
  const defaultConfig = {
1184
- enabled: typeof process !== 'undefined' && ((_a = process.env) === null || _a === void 0 ? void 0 : _a.NODE_ENV) !== 'production',
1643
+ enabled: defaultEnabled(),
1185
1644
  position: 'bottom-right',
1186
1645
  theme: 'auto',
1187
1646
  hotkeys: {
@@ -1207,6 +1666,8 @@
1207
1666
  },
1208
1667
  onError: () => { },
1209
1668
  onPerformanceIssue: () => { },
1669
+ maxErrorEntries: 100,
1670
+ slowRequestThreshold: 3000,
1210
1671
  workerUrl: undefined,
1211
1672
  remoteConfig: null
1212
1673
  };
@@ -1218,21 +1679,38 @@
1218
1679
  networkFilters: { ...defaultConfig.networkFilters, ...config.networkFilters }
1219
1680
  };
1220
1681
  }
1221
- async init() {
1222
- if (this.initialized)
1682
+ init() {
1683
+ // Share one initialisation between the constructor and show(), so monitors
1684
+ // are never installed twice.
1685
+ if (!this.initPromise)
1686
+ this.initPromise = this.runInit();
1687
+ return this.initPromise;
1688
+ }
1689
+ async runInit() {
1690
+ var _a, _b;
1691
+ if (this.initialized || this.destroyed || !hasDom())
1223
1692
  return;
1224
1693
  try {
1225
1694
  await this.loadMonitors();
1695
+ if (this.destroyed)
1696
+ return this.teardown();
1226
1697
  await this.loadUI();
1698
+ if (this.destroyed)
1699
+ return this.teardown();
1227
1700
  await this.registerPlugins();
1701
+ if (this.destroyed)
1702
+ return this.teardown();
1228
1703
  this.setupHotkeys();
1229
1704
  this.setupErrorHandlers();
1230
1705
  this.initialized = true;
1231
1706
  this.events.emit('inspector:ready');
1232
1707
  }
1233
1708
  catch (error) {
1709
+ // Undo whatever was installed before the failure.
1710
+ this.teardown();
1711
+ this.initPromise = null;
1234
1712
  console.error('Failed to initialize DevInspector:', error);
1235
- this.config.onError(error);
1713
+ (_b = (_a = this.config).onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
1236
1714
  }
1237
1715
  }
1238
1716
  async loadMonitors() {
@@ -1354,8 +1832,18 @@
1354
1832
  }
1355
1833
  show() {
1356
1834
  var _a;
1835
+ if (this.destroyed)
1836
+ return;
1357
1837
  if (!this.initialized) {
1358
- this.init().then(() => this.show());
1838
+ this.init().then(() => {
1839
+ // Only retry show() once init has actually succeeded (no retry loop on failure).
1840
+ if (this.initialized && !this.destroyed)
1841
+ this.show();
1842
+ }).catch(err => {
1843
+ var _a, _b;
1844
+ console.error('Failed to show inspector:', err);
1845
+ (_b = (_a = this.config).onError) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1846
+ });
1359
1847
  return;
1360
1848
  }
1361
1849
  this.isVisible = true;
@@ -1383,14 +1871,27 @@
1383
1871
  this.show();
1384
1872
  }
1385
1873
  }
1386
- destroy() {
1874
+ teardown() {
1387
1875
  var _a;
1388
- this.monitors.forEach(monitor => { var _a; return (_a = monitor.stop) === null || _a === void 0 ? void 0 : _a.call(monitor); });
1876
+ this.monitors.forEach(monitor => {
1877
+ var _a;
1878
+ try {
1879
+ (_a = monitor.stop) === null || _a === void 0 ? void 0 : _a.call(monitor);
1880
+ }
1881
+ catch (error) {
1882
+ console.error('DevInspector: failed to stop a monitor', error);
1883
+ }
1884
+ });
1389
1885
  this.monitors.clear();
1390
1886
  (_a = this.ui) === null || _a === void 0 ? void 0 : _a.destroy();
1391
1887
  this.ui = null;
1392
1888
  this.cleanupFunctions.forEach(cleanup => cleanup());
1393
1889
  this.cleanupFunctions = [];
1890
+ }
1891
+ destroy() {
1892
+ // A destroy() during the asynchronous init is honoured once init resumes.
1893
+ this.destroyed = true;
1894
+ this.teardown();
1394
1895
  this.events.emit('inspector:destroy');
1395
1896
  this.events.removeAllListeners();
1396
1897
  DevInspector.instance = null;
@@ -1414,8 +1915,8 @@
1414
1915
  console.warn(`Failed to measure ${name}:`, error);
1415
1916
  }
1416
1917
  }
1417
- use(plugin) {
1418
- this.pluginSystem.register(plugin);
1918
+ async use(plugin) {
1919
+ await this.pluginSystem.register(plugin);
1419
1920
  }
1420
1921
  export() {
1421
1922
  return {
@@ -1463,21 +1964,31 @@
1463
1964
  static getInstance() {
1464
1965
  return DevInspector.instance;
1465
1966
  }
1466
- }
1467
- DevInspector.instance = null;
1967
+ };
1968
+ DevInspector$1.instance = null;
1468
1969
 
1970
+ /**
1971
+ * @deprecated A static demo panel that does not monitor anything. Use the
1972
+ * default export (`DevInspector`) instead.
1973
+ */
1469
1974
  class SimpleDevInspector {
1470
1975
  constructor(config = {}) {
1471
1976
  this.widget = null;
1472
1977
  this.panel = null;
1473
1978
  this.isVisible = false;
1979
+ this.onKeydown = (e) => {
1980
+ if (e.ctrlKey && e.shiftKey && (e.key === 'D' || e.key === 'd')) {
1981
+ e.preventDefault();
1982
+ this.toggle();
1983
+ }
1984
+ };
1474
1985
  this.config = {
1475
- enabled: true,
1986
+ enabled: defaultEnabled(),
1476
1987
  position: 'bottom-right',
1477
1988
  theme: 'dark',
1478
1989
  ...config
1479
1990
  };
1480
- if (this.config.enabled) {
1991
+ if (this.config.enabled && hasDom()) {
1481
1992
  this.init();
1482
1993
  }
1483
1994
  }
@@ -1513,7 +2024,7 @@
1513
2024
  document.body.appendChild(this.widget);
1514
2025
  }
1515
2026
  createPanel() {
1516
- var _a, _b;
2027
+ var _a, _b, _c;
1517
2028
  this.panel = document.createElement('div');
1518
2029
  const bgColor = this.config.theme === 'dark' ? '#1e1e1e' : '#ffffff';
1519
2030
  const textColor = this.config.theme === 'dark' ? '#cccccc' : '#333333';
@@ -1538,7 +2049,7 @@
1538
2049
  this.panel.innerHTML = `
1539
2050
  <div style="padding: 10px; background: ${this.config.theme === 'dark' ? '#2d2d30' : '#f5f5f5'}; border-bottom: 1px solid ${borderColor}; display: flex; justify-content: space-between; align-items: center;">
1540
2051
  <span style="font-weight: bold;">DevInspector v1.0.0</span>
1541
- <button onclick="this.closest('.devinspector-panel').style.display='none'" style="background: #f44336; border: none; color: white; width: 20px; height: 20px; border-radius: 3px; cursor: pointer;">×</button>
2052
+ <button type="button" class="devinspector-close" style="background: #f44336; border: none; color: white; width: 20px; height: 20px; border-radius: 3px; cursor: pointer;">×</button>
1542
2053
  </div>
1543
2054
  <div style="display: flex; background: ${this.config.theme === 'dark' ? '#2d2d30' : '#f5f5f5'}; border-bottom: 1px solid ${borderColor};">
1544
2055
  <button style="padding: 8px 16px; background: #007acc; border: none; color: white; cursor: pointer;">Network</button>
@@ -1573,6 +2084,8 @@
1573
2084
  </div>
1574
2085
  `;
1575
2086
  this.panel.className = 'devinspector-panel';
2087
+ // No inline handlers, so the panel works under a Content Security Policy.
2088
+ (_c = this.panel.querySelector('.devinspector-close')) === null || _c === void 0 ? void 0 : _c.addEventListener('click', () => this.hide());
1576
2089
  document.body.appendChild(this.panel);
1577
2090
  }
1578
2091
  setupEventListeners() {
@@ -1580,12 +2093,7 @@
1580
2093
  this.widget.addEventListener('click', () => this.toggle());
1581
2094
  }
1582
2095
  // Keyboard shortcuts
1583
- document.addEventListener('keydown', (e) => {
1584
- if (e.ctrlKey && e.shiftKey && e.key === 'D') {
1585
- e.preventDefault();
1586
- this.toggle();
1587
- }
1588
- });
2096
+ document.addEventListener('keydown', this.onKeydown);
1589
2097
  }
1590
2098
  show() {
1591
2099
  if (this.panel) {
@@ -1600,9 +2108,14 @@
1600
2108
  }
1601
2109
  }
1602
2110
  toggle() {
1603
- this.isVisible ? this.hide() : this.show();
2111
+ if (this.isVisible)
2112
+ this.hide();
2113
+ else
2114
+ this.show();
1604
2115
  }
1605
2116
  destroy() {
2117
+ if (hasDom())
2118
+ document.removeEventListener('keydown', this.onKeydown);
1606
2119
  if (this.widget && this.widget.parentNode) {
1607
2120
  this.widget.parentNode.removeChild(this.widget);
1608
2121
  }
@@ -1629,11 +2142,35 @@
1629
2142
  }
1630
2143
 
1631
2144
  /**
1632
- * DevInspector - Professional Developer Debugging Tool
1633
- * @version 1.1.0
1634
- * @description Zero-dependency framework-agnostic debugging tool with beautiful modern UI
2145
+ * DevInspector - developer debugging panel for web applications.
2146
+ */
2147
+ // Default inspector
2148
+
2149
+ var api = /*#__PURE__*/Object.freeze({
2150
+ __proto__: null,
2151
+ BasePlugin: BasePlugin,
2152
+ CircularStorage: CircularStorage,
2153
+ DevInspector: EnhancedDevInspector,
2154
+ EnhancedDevInspector: EnhancedDevInspector,
2155
+ EventEmitter: EventEmitter,
2156
+ IndexedStorage: IndexedStorage,
2157
+ OriginalDevInspector: DevInspector$1,
2158
+ SimpleDevInspector: SimpleDevInspector,
2159
+ VERSION: VERSION,
2160
+ default: EnhancedDevInspector
2161
+ });
2162
+
2163
+ /**
2164
+ * Entry for the browser bundles (dist/devinspector.umd*.js). The global
2165
+ * `DevInspector` is the inspector class itself, so `new DevInspector()` works
2166
+ * from a script tag; every named export is also available as a static
2167
+ * property (e.g. `DevInspector.BasePlugin`).
1635
2168
  */
1636
- // Enhanced UI version (new default)
2169
+ const DevInspector = EnhancedDevInspector;
2170
+ for (const [key, value] of Object.entries(api)) {
2171
+ if (!(key in DevInspector))
2172
+ Object.defineProperty(DevInspector, key, { value, enumerable: true });
2173
+ }
1637
2174
 
1638
2175
  function throttle(func, wait, options = {}) {
1639
2176
  let timeout = null;
@@ -1678,7 +2215,7 @@
1678
2215
  };
1679
2216
  }
1680
2217
  function generateId() {
1681
- return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
2218
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
1682
2219
  }
1683
2220
  function safeStringify(obj, indent) {
1684
2221
  const seen = new WeakSet();
@@ -1703,7 +2240,7 @@
1703
2240
  }, indent);
1704
2241
  }
1705
2242
  function getStackTrace(error) {
1706
- const stack = (new Error()).stack || '';
2243
+ const stack = (error || new Error()).stack || '';
1707
2244
  return stack
1708
2245
  .split('\n')
1709
2246
  .slice(1)
@@ -1724,30 +2261,41 @@
1724
2261
  };
1725
2262
  }
1726
2263
 
2264
+ /** Largest request/response body preview kept per entry (bytes). */
2265
+ const MAX_BODY_PREVIEW = 64 * 1024;
1727
2266
  class FetchInterceptor {
1728
2267
  constructor(handlers = {}) {
1729
2268
  this.requestMap = new Map();
2269
+ this.installed = null;
1730
2270
  this.originalFetch = window.fetch;
1731
2271
  this.handlers = handlers;
1732
2272
  }
1733
2273
  install() {
1734
2274
  // eslint-disable-next-line @typescript-eslint/no-this-alias
1735
2275
  const self = this;
1736
- window.fetch = async function (input, init) {
1737
- var _a, _b, _c, _d, _e, _f;
2276
+ if (this.installed || typeof this.originalFetch !== 'function')
2277
+ return;
2278
+ const instrumented = async function (input, init) {
2279
+ var _a, _b, _c, _d;
1738
2280
  const id = generateId();
1739
2281
  const startTime = performance.now();
1740
2282
  let url;
1741
2283
  let method;
1742
2284
  let headers = {};
1743
2285
  let body;
1744
- if (input instanceof Request) {
2286
+ if (typeof Request !== 'undefined' && input instanceof Request) {
1745
2287
  url = input.url;
1746
2288
  method = input.method;
1747
2289
  input.headers.forEach((value, key) => {
1748
2290
  headers[key] = value;
1749
2291
  });
1750
- body = await self.extractBody(input);
2292
+ // Try to extract body, but handle cases where request is locked/used
2293
+ try {
2294
+ body = await self.extractBody(input);
2295
+ }
2296
+ catch (e) {
2297
+ body = '[Body unavailable - request already used]';
2298
+ }
1751
2299
  }
1752
2300
  else {
1753
2301
  url = input.toString();
@@ -1780,46 +2328,69 @@
1780
2328
  };
1781
2329
  self.requestMap.set(id, request);
1782
2330
  (_b = (_a = self.handlers).onRequest) === null || _b === void 0 ? void 0 : _b.call(_a, request);
2331
+ let response;
1783
2332
  try {
1784
- const response = await self.originalFetch.apply(window, [input, init]);
1785
- const duration = performance.now() - startTime;
1786
- const responseHeaders = {};
1787
- response.headers.forEach((value, key) => {
1788
- responseHeaders[key] = value;
1789
- });
1790
- const clonedResponse = response.clone();
1791
- const responseBody = await self.extractResponseBody(clonedResponse);
1792
- const size = self.calculateSize(responseBody, responseHeaders);
1793
- const networkResponse = {
1794
- id,
1795
- status: response.status,
1796
- statusText: response.statusText,
1797
- headers: responseHeaders,
1798
- body: responseBody,
1799
- size,
1800
- duration,
1801
- timestamp: Date.now(),
1802
- fromCache: self.isFromCache(response, duration)
1803
- };
1804
- (_d = (_c = self.handlers).onResponse) === null || _d === void 0 ? void 0 : _d.call(_c, networkResponse);
1805
- self.requestMap.delete(id);
1806
- return response;
2333
+ response = await self.originalFetch.apply(this !== null && this !== void 0 ? this : window, [input, init]);
1807
2334
  }
1808
2335
  catch (error) {
1809
2336
  const networkError = {
1810
2337
  id,
1811
- message: error.message || 'Network request failed',
1812
- stack: error.stack,
2338
+ message: (error === null || error === void 0 ? void 0 : error.message) || 'Network request failed',
2339
+ stack: error === null || error === void 0 ? void 0 : error.stack,
1813
2340
  timestamp: Date.now()
1814
2341
  };
1815
- (_f = (_e = self.handlers).onError) === null || _f === void 0 ? void 0 : _f.call(_e, networkError);
2342
+ (_d = (_c = self.handlers).onError) === null || _d === void 0 ? void 0 : _d.call(_c, networkError);
1816
2343
  self.requestMap.delete(id);
1817
2344
  throw error;
1818
2345
  }
2346
+ // Hand the response to the caller right away. The body preview is read from
2347
+ // a clone in the background (capped), so streaming responses (SSE, long
2348
+ // polling, large downloads) are never held back by the inspector.
2349
+ const duration = performance.now() - startTime;
2350
+ void self.reportResponse(id, response, duration);
2351
+ return response;
1819
2352
  };
2353
+ this.installed = instrumented;
2354
+ window.fetch = instrumented;
2355
+ }
2356
+ async reportResponse(id, response, duration) {
2357
+ var _a, _b;
2358
+ try {
2359
+ const responseHeaders = {};
2360
+ response.headers.forEach((value, key) => {
2361
+ responseHeaders[key] = value;
2362
+ });
2363
+ let responseBody;
2364
+ try {
2365
+ responseBody = response.bodyUsed ? '[Body already read]' : await this.extractResponseBody(response.clone());
2366
+ }
2367
+ catch (_c) {
2368
+ responseBody = '[Unable to read response]';
2369
+ }
2370
+ (_b = (_a = this.handlers).onResponse) === null || _b === void 0 ? void 0 : _b.call(_a, {
2371
+ id,
2372
+ status: response.status,
2373
+ statusText: response.statusText,
2374
+ headers: responseHeaders,
2375
+ body: responseBody,
2376
+ size: this.calculateSize(responseBody, responseHeaders),
2377
+ duration,
2378
+ timestamp: Date.now(),
2379
+ fromCache: this.isFromCache(response, duration)
2380
+ });
2381
+ }
2382
+ catch (_d) {
2383
+ // A failing handler must not surface as an unhandled rejection in the page.
2384
+ }
2385
+ finally {
2386
+ this.requestMap.delete(id);
2387
+ }
1820
2388
  }
1821
2389
  uninstall() {
1822
- window.fetch = this.originalFetch;
2390
+ if (this.installed && window.fetch === this.installed) {
2391
+ window.fetch = this.originalFetch;
2392
+ }
2393
+ this.installed = null;
1823
2394
  this.requestMap.clear();
1824
2395
  }
1825
2396
  async extractBody(request) {
@@ -1830,13 +2401,13 @@
1830
2401
  }
1831
2402
  const cloned = request.clone();
1832
2403
  if (contentType.includes('application/json')) {
1833
- return await cloned.json();
2404
+ return await this.readPreview(cloned, true);
1834
2405
  }
1835
2406
  else if (contentType.includes('text/')) {
1836
- return await cloned.text();
2407
+ return await this.readPreview(cloned, false);
1837
2408
  }
1838
2409
  else if (contentType.includes('application/x-www-form-urlencoded')) {
1839
- return await cloned.text();
2410
+ return await this.readPreview(cloned, false);
1840
2411
  }
1841
2412
  else if (contentType.includes('multipart/form-data')) {
1842
2413
  return '[FormData]';
@@ -1847,14 +2418,59 @@
1847
2418
  return '[Unable to read body]';
1848
2419
  }
1849
2420
  }
2421
+ /** Reads at most MAX_BODY_PREVIEW bytes from a cloned body, then cancels the clone. */
2422
+ async readCapped(body) {
2423
+ const stream = body.body;
2424
+ if (!stream || typeof stream.getReader !== 'function') {
2425
+ const text = await body.text();
2426
+ return text.length > MAX_BODY_PREVIEW ? { text: text.slice(0, MAX_BODY_PREVIEW), truncated: true } : { text, truncated: false };
2427
+ }
2428
+ const reader = stream.getReader();
2429
+ const decoder = new TextDecoder();
2430
+ let text = '';
2431
+ let received = 0;
2432
+ try {
2433
+ for (;;) {
2434
+ const { done, value } = await reader.read();
2435
+ if (done)
2436
+ return { text: text + decoder.decode(), truncated: false };
2437
+ received += value.byteLength;
2438
+ text += decoder.decode(value, { stream: true });
2439
+ if (received >= MAX_BODY_PREVIEW)
2440
+ return { text: text.slice(0, MAX_BODY_PREVIEW), truncated: true };
2441
+ }
2442
+ }
2443
+ finally {
2444
+ reader.cancel().catch(() => undefined);
2445
+ }
2446
+ }
2447
+ async readPreview(body, asJson) {
2448
+ const { text, truncated } = await this.readCapped(body);
2449
+ if (truncated)
2450
+ return `${text}... [truncated]`;
2451
+ if (asJson) {
2452
+ try {
2453
+ return JSON.parse(text);
2454
+ }
2455
+ catch (_a) {
2456
+ return text;
2457
+ }
2458
+ }
2459
+ return text;
2460
+ }
1850
2461
  async extractResponseBody(response) {
2462
+ var _a, _b;
1851
2463
  try {
1852
2464
  const contentType = response.headers.get('content-type') || '';
2465
+ if (contentType.includes('text/event-stream')) {
2466
+ (_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel().catch(() => undefined);
2467
+ return '[Event stream]';
2468
+ }
1853
2469
  if (contentType.includes('application/json')) {
1854
- return await response.json();
2470
+ return await this.readPreview(response, true);
1855
2471
  }
1856
2472
  else if (contentType.includes('text/')) {
1857
- return await response.text();
2473
+ return await this.readPreview(response, false);
1858
2474
  }
1859
2475
  else if (contentType.includes('image/')) {
1860
2476
  return '[Image data]';
@@ -1865,8 +2481,9 @@
1865
2481
  else if (contentType.includes('audio/')) {
1866
2482
  return '[Audio data]';
1867
2483
  }
1868
- const blob = await response.blob();
1869
- return `[Binary data: ${blob.size} bytes]`;
2484
+ const length = response.headers.get('content-length');
2485
+ (_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel().catch(() => undefined);
2486
+ return length ? `[Binary data: ${length} bytes]` : '[Binary data]';
1870
2487
  }
1871
2488
  catch (error) {
1872
2489
  return '[Unable to read response]';
@@ -1933,12 +2550,15 @@
1933
2550
 
1934
2551
  class XHRInterceptor {
1935
2552
  constructor(handlers = {}) {
2553
+ this.installed = null;
1936
2554
  this.handlers = handlers;
1937
2555
  this.originalOpen = XMLHttpRequest.prototype.open;
1938
2556
  this.originalSend = XMLHttpRequest.prototype.send;
1939
2557
  this.originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
1940
2558
  }
1941
2559
  install() {
2560
+ if (this.installed || typeof XMLHttpRequest === 'undefined')
2561
+ return;
1942
2562
  // eslint-disable-next-line @typescript-eslint/no-this-alias
1943
2563
  const self = this;
1944
2564
  XMLHttpRequest.prototype.open = function (method, url, async = true, username, password) {
@@ -2044,11 +2664,24 @@
2044
2664
  });
2045
2665
  return self.originalSend.apply(this, [body]);
2046
2666
  };
2667
+ this.installed = {
2668
+ open: XMLHttpRequest.prototype.open,
2669
+ send: XMLHttpRequest.prototype.send,
2670
+ setRequestHeader: XMLHttpRequest.prototype.setRequestHeader
2671
+ };
2047
2672
  }
2048
2673
  uninstall() {
2049
- XMLHttpRequest.prototype.open = this.originalOpen;
2050
- XMLHttpRequest.prototype.send = this.originalSend;
2051
- XMLHttpRequest.prototype.setRequestHeader = this.originalSetRequestHeader;
2674
+ if (!this.installed)
2675
+ return;
2676
+ const proto = XMLHttpRequest.prototype;
2677
+ // Only restore methods that nobody has wrapped since we installed ours.
2678
+ if (proto.open === this.installed.open)
2679
+ proto.open = this.originalOpen;
2680
+ if (proto.send === this.installed.send)
2681
+ proto.send = this.originalSend;
2682
+ if (proto.setRequestHeader === this.installed.setRequestHeader)
2683
+ proto.setRequestHeader = this.originalSetRequestHeader;
2684
+ this.installed = null;
2052
2685
  }
2053
2686
  sanitizeBody(body) {
2054
2687
  if (!body)
@@ -2099,10 +2732,10 @@
2099
2732
  if (xhr.responseType === 'json' && xhr.response) {
2100
2733
  return xhr.response;
2101
2734
  }
2102
- if (xhr.responseType === 'arraybuffer') {
2735
+ if (xhr.responseType === 'arraybuffer' && xhr.response) {
2103
2736
  return `[ArrayBuffer: ${xhr.response.byteLength} bytes]`;
2104
2737
  }
2105
- if (xhr.responseType === 'blob') {
2738
+ if (xhr.responseType === 'blob' && xhr.response) {
2106
2739
  return `[Blob: ${xhr.response.size} bytes, type: ${xhr.response.type}]`;
2107
2740
  }
2108
2741
  if (xhr.responseType === 'document') {
@@ -2150,6 +2783,7 @@
2150
2783
  class WebSocketMonitor {
2151
2784
  constructor(handlers = {}) {
2152
2785
  this.connections = new Map();
2786
+ this.installed = null;
2153
2787
  this.originalWebSocket = window.WebSocket;
2154
2788
  this.handlers = handlers;
2155
2789
  }
@@ -2157,7 +2791,9 @@
2157
2791
  // eslint-disable-next-line @typescript-eslint/no-this-alias
2158
2792
  const self = this;
2159
2793
  const OriginalWebSocket = this.originalWebSocket;
2160
- window.WebSocket = function (url, protocols) {
2794
+ if (typeof OriginalWebSocket !== 'function' || this.installed)
2795
+ return;
2796
+ const MonitoredWebSocket = function (url, protocols) {
2161
2797
  var _a, _b;
2162
2798
  const ws = new OriginalWebSocket(url, protocols);
2163
2799
  const connectionId = generateId();
@@ -2259,17 +2895,19 @@
2259
2895
  };
2260
2896
  return ws;
2261
2897
  };
2262
- // Copy static properties
2263
- Object.setPrototypeOf(window.WebSocket, OriginalWebSocket);
2264
- Object.setPrototypeOf(window.WebSocket.prototype, OriginalWebSocket.prototype);
2265
- // Copy constants
2266
- window.WebSocket.CONNECTING = OriginalWebSocket.CONNECTING;
2267
- window.WebSocket.OPEN = OriginalWebSocket.OPEN;
2268
- window.WebSocket.CLOSING = OriginalWebSocket.CLOSING;
2269
- window.WebSocket.CLOSED = OriginalWebSocket.CLOSED;
2898
+ // Inherit statics (CONNECTING, OPEN, ...) and share the prototype so that
2899
+ // `ws instanceof WebSocket` keeps working. The constants are read-only on the
2900
+ // native constructor, so they must not be assigned (that throws in strict mode).
2901
+ Object.setPrototypeOf(MonitoredWebSocket, OriginalWebSocket);
2902
+ MonitoredWebSocket.prototype = OriginalWebSocket.prototype;
2903
+ this.installed = MonitoredWebSocket;
2904
+ window.WebSocket = MonitoredWebSocket;
2270
2905
  }
2271
2906
  uninstall() {
2272
- window.WebSocket = this.originalWebSocket;
2907
+ if (this.installed && window.WebSocket === this.installed) {
2908
+ window.WebSocket = this.originalWebSocket;
2909
+ }
2910
+ this.installed = null;
2273
2911
  this.connections.clear();
2274
2912
  }
2275
2913
  parseMessageData(data) {
@@ -2317,8 +2955,12 @@
2317
2955
  }
2318
2956
  }
2319
2957
 
2958
+ /** Messages (and errors) remembered per WebSocket connection. */
2959
+ const MAX_WEBSOCKET_MESSAGES = 500;
2320
2960
  class NetworkMonitor {
2321
2961
  constructor(inspector) {
2962
+ this.beaconInterceptor = null;
2963
+ this.beaconOriginal = null;
2322
2964
  this.entries = new Map();
2323
2965
  this.isActive = false;
2324
2966
  this.inspector = inspector;
@@ -2365,7 +3007,7 @@
2365
3007
  request,
2366
3008
  timestamp: request.timestamp
2367
3009
  };
2368
- this.entries.set(request.id, entry);
3010
+ this.track(request.id, entry);
2369
3011
  const storage = this.inspector.getStorage('network');
2370
3012
  storage.push(entry);
2371
3013
  this.inspector.getEvents().emit('network:request', {
@@ -2382,8 +3024,7 @@
2382
3024
  entry.duration = response.duration;
2383
3025
  entry.status = response.status;
2384
3026
  entry.size = response.size;
2385
- const storage = this.inspector.getStorage('network');
2386
- storage.push(entry);
3027
+ // The entry object is already in storage (pushed on request); it is updated in place.
2387
3028
  this.inspector.getEvents().emit('network:response', response);
2388
3029
  // Check for performance issues
2389
3030
  if (response.duration > 3000) {
@@ -2400,8 +3041,6 @@
2400
3041
  if (!entry)
2401
3042
  return;
2402
3043
  entry.error = error;
2403
- const storage = this.inspector.getStorage('network');
2404
- storage.push(entry);
2405
3044
  this.inspector.getEvents().emit('network:error', error);
2406
3045
  }
2407
3046
  handleProgress(progress) {
@@ -2418,7 +3057,7 @@
2418
3057
  },
2419
3058
  timestamp: connection.timestamp
2420
3059
  };
2421
- this.entries.set(connection.id, entry);
3060
+ this.track(connection.id, entry);
2422
3061
  const storage = this.inspector.getStorage('network');
2423
3062
  storage.push(entry);
2424
3063
  this.inspector.getEvents().emit('network:websocket:connection', connection);
@@ -2428,6 +3067,8 @@
2428
3067
  if (!entry || !entry.websocket)
2429
3068
  return;
2430
3069
  entry.websocket.messages.push(message);
3070
+ if (entry.websocket.messages.length > MAX_WEBSOCKET_MESSAGES)
3071
+ entry.websocket.messages.shift();
2431
3072
  this.inspector.getEvents().emit('network:websocket:message', message);
2432
3073
  }
2433
3074
  handleWebSocketStatusChange(status) {
@@ -2443,15 +3084,26 @@
2443
3084
  if (!entry || !entry.websocket)
2444
3085
  return;
2445
3086
  entry.websocket.errors.push(error);
3087
+ if (entry.websocket.errors.length > MAX_WEBSOCKET_MESSAGES)
3088
+ entry.websocket.errors.shift();
2446
3089
  this.inspector.getEvents().emit('network:websocket:error', error);
2447
3090
  }
3091
+ /** Remembers an in-flight entry; the map is bounded like the network storage. */
3092
+ track(id, entry) {
3093
+ this.entries.set(id, entry);
3094
+ const max = Math.max(1, this.inspector.getConfig().maxNetworkEntries);
3095
+ while (this.entries.size > max) {
3096
+ const oldest = this.entries.keys().next().value;
3097
+ this.entries.delete(oldest);
3098
+ }
3099
+ }
2448
3100
  installBeaconInterceptor() {
2449
- if (!navigator.sendBeacon)
3101
+ if (typeof navigator === 'undefined' || typeof navigator.sendBeacon !== 'function')
2450
3102
  return;
2451
3103
  const originalSendBeacon = navigator.sendBeacon.bind(navigator);
2452
3104
  // eslint-disable-next-line @typescript-eslint/no-this-alias
2453
3105
  const self = this;
2454
- navigator.sendBeacon = function (url, data) {
3106
+ const instrumented = function (url, data) {
2455
3107
  const id = self.generateId();
2456
3108
  const request = {
2457
3109
  id,
@@ -2479,12 +3131,16 @@
2479
3131
  }, 0);
2480
3132
  return result;
2481
3133
  };
2482
- this.beaconInterceptor = originalSendBeacon;
3134
+ this.beaconOriginal = navigator.sendBeacon;
3135
+ this.beaconInterceptor = instrumented;
3136
+ navigator.sendBeacon = instrumented;
2483
3137
  }
2484
3138
  uninstallBeaconInterceptor() {
2485
- if (this.beaconInterceptor && navigator.sendBeacon) {
2486
- navigator.sendBeacon = this.beaconInterceptor;
3139
+ if (this.beaconInterceptor && navigator.sendBeacon === this.beaconInterceptor) {
3140
+ navigator.sendBeacon = this.beaconOriginal;
2487
3141
  }
3142
+ this.beaconInterceptor = null;
3143
+ this.beaconOriginal = null;
2488
3144
  }
2489
3145
  sanitizeBeaconData(data) {
2490
3146
  if (!data)
@@ -2510,7 +3166,7 @@
2510
3166
  return data;
2511
3167
  }
2512
3168
  generateId() {
2513
- return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
3169
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
2514
3170
  }
2515
3171
  getEntries() {
2516
3172
  return Array.from(this.entries.values());
@@ -2537,6 +3193,8 @@
2537
3193
  this.groupLevel = 0;
2538
3194
  this.counters = new Map();
2539
3195
  this.timers = new Map();
3196
+ this.wrappers = new Map();
3197
+ this.handling = false;
2540
3198
  this.handlers = handlers;
2541
3199
  this.captureStackTraces = captureStackTraces;
2542
3200
  }
@@ -2547,16 +3205,24 @@
2547
3205
  'count', 'countReset', 'time', 'timeEnd', 'timeLog',
2548
3206
  'assert', 'dir', 'dirxml', 'profile', 'profileEnd'
2549
3207
  ];
3208
+ if (this.originalMethods.size > 0)
3209
+ return;
2550
3210
  methods.forEach(method => {
3211
+ if (typeof console[method] !== 'function')
3212
+ return;
2551
3213
  this.originalMethods.set(method, console[method]);
2552
3214
  this.interceptMethod(method);
2553
3215
  });
2554
3216
  }
2555
3217
  uninstall() {
2556
3218
  this.originalMethods.forEach((original, method) => {
2557
- console[method] = original;
3219
+ // Leave methods alone that someone else has wrapped since; ours pass through once uninstalled.
3220
+ if (console[method] === this.wrappers.get(method)) {
3221
+ console[method] = original;
3222
+ }
2558
3223
  });
2559
3224
  this.originalMethods.clear();
3225
+ this.wrappers.clear();
2560
3226
  this.counters.clear();
2561
3227
  this.timers.clear();
2562
3228
  this.groupLevel = 0;
@@ -2565,60 +3231,78 @@
2565
3231
  // eslint-disable-next-line @typescript-eslint/no-this-alias
2566
3232
  const self = this;
2567
3233
  const original = this.originalMethods.get(method);
2568
- console[method] = function (...args) {
2569
- var _a, _b, _c, _d;
3234
+ const wrapper = function (...args) {
2570
3235
  // Call original method first
2571
- original.apply(console, args);
2572
- // Handle special methods
2573
- switch (method) {
2574
- case 'clear':
2575
- (_b = (_a = self.handlers).onClear) === null || _b === void 0 ? void 0 : _b.call(_a);
2576
- return;
2577
- case 'group':
2578
- case 'groupCollapsed':
2579
- self.groupLevel++;
2580
- break;
2581
- case 'groupEnd':
2582
- self.groupLevel = Math.max(0, self.groupLevel - 1);
2583
- break;
2584
- case 'count':
2585
- self.handleCount(args[0]);
2586
- return;
2587
- case 'countReset':
2588
- self.counters.delete(args[0] || 'default');
2589
- return;
2590
- case 'time':
2591
- self.timers.set(args[0] || 'default', performance.now());
2592
- return;
2593
- case 'timeEnd':
2594
- self.handleTimeEnd(args[0], 'timeEnd');
2595
- return;
2596
- case 'timeLog':
2597
- self.handleTimeEnd(args[0], 'timeLog');
2598
- break;
2599
- case 'assert':
2600
- if (args[0])
2601
- return; // Don't log if assertion passes
2602
- args = args.slice(1); // Remove condition
2603
- break;
3236
+ const result = original.apply(console, args);
3237
+ // Uninstalled (but still wrapped by someone else), or logging from inside one
3238
+ // of our own handlers: pass through without capturing, which also prevents
3239
+ // infinite recursion when a 'console:log' listener logs.
3240
+ if (self.handling || !self.wrappers.has(method))
3241
+ return result;
3242
+ self.handling = true;
3243
+ try {
3244
+ self.capture(method, args);
2604
3245
  }
2605
- // Create log entry
2606
- const entry = {
2607
- id: generateId(),
2608
- level: method,
2609
- args: args,
2610
- formattedArgs: self.formatArgs(args),
2611
- timestamp: Date.now(),
2612
- groupLevel: self.groupLevel
2613
- };
2614
- // Capture stack trace if enabled
2615
- if (self.captureStackTraces && (method === 'error' || method === 'warn' || method === 'trace')) {
2616
- const stack = getStackTrace();
2617
- entry.stack = stack.slice(1); // Remove this interceptor from stack
2618
- entry.source = self.extractSourceFromStack(stack[1]);
3246
+ finally {
3247
+ self.handling = false;
2619
3248
  }
2620
- (_d = (_c = self.handlers).onLog) === null || _d === void 0 ? void 0 : _d.call(_c, entry);
3249
+ return result;
3250
+ };
3251
+ this.wrappers.set(method, wrapper);
3252
+ console[method] = wrapper;
3253
+ }
3254
+ capture(method, args) {
3255
+ var _a, _b, _c, _d;
3256
+ // Handle special methods
3257
+ switch (method) {
3258
+ case 'clear':
3259
+ (_b = (_a = this.handlers).onClear) === null || _b === void 0 ? void 0 : _b.call(_a);
3260
+ return;
3261
+ case 'group':
3262
+ case 'groupCollapsed':
3263
+ this.groupLevel++;
3264
+ break;
3265
+ case 'groupEnd':
3266
+ this.groupLevel = Math.max(0, this.groupLevel - 1);
3267
+ break;
3268
+ case 'count':
3269
+ this.handleCount(args[0]);
3270
+ return;
3271
+ case 'countReset':
3272
+ this.counters.delete(args[0] || 'default');
3273
+ return;
3274
+ case 'time':
3275
+ this.timers.set(args[0] || 'default', performance.now());
3276
+ return;
3277
+ case 'timeEnd':
3278
+ this.handleTimeEnd(args[0], 'timeEnd');
3279
+ return;
3280
+ case 'timeLog':
3281
+ this.handleTimeEnd(args[0], 'timeLog');
3282
+ break;
3283
+ case 'assert':
3284
+ if (args[0])
3285
+ return; // Don't log if assertion passes
3286
+ args = args.slice(1); // Remove condition
3287
+ break;
3288
+ }
3289
+ // Create log entry
3290
+ const entry = {
3291
+ id: generateId(),
3292
+ level: method,
3293
+ args: args,
3294
+ formattedArgs: this.formatArgs(args),
3295
+ timestamp: Date.now(),
3296
+ groupLevel: this.groupLevel
2621
3297
  };
3298
+ // Capture stack trace if enabled
3299
+ if (this.captureStackTraces && (method === 'error' || method === 'warn' || method === 'trace')) {
3300
+ // Drop the getStackTrace, capture and console wrapper frames so the first frame is the caller.
3301
+ const stack = getStackTrace().slice(3);
3302
+ entry.stack = stack;
3303
+ entry.source = this.extractSourceFromStack(stack[0]);
3304
+ }
3305
+ (_d = (_c = this.handlers).onLog) === null || _d === void 0 ? void 0 : _d.call(_c, entry);
2622
3306
  }
2623
3307
  handleCount(label) {
2624
3308
  var _a, _b;
@@ -2972,7 +3656,7 @@
2972
3656
  this.executeCommand(command);
2973
3657
  });
2974
3658
  }
2975
- executeCommand(command) {
3659
+ async executeCommand(command) {
2976
3660
  var _a;
2977
3661
  // Add to history
2978
3662
  this.commandHistory.push(command);
@@ -2989,8 +3673,12 @@
2989
3673
  this.handleLog(commandEntry);
2990
3674
  // Execute the command
2991
3675
  try {
2992
- // Create a function to evaluate the command in global scope
2993
- const result = (0, eval)(command);
3676
+ // SECURITY WARNING: Executing arbitrary code. This should only be used in development.
3677
+ // Use Function constructor instead of eval for better security and scope control
3678
+ // Note: This still allows code execution - ensure this feature is properly controlled
3679
+ const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor;
3680
+ const executionFn = new AsyncFunction('return (' + command + ')');
3681
+ const result = await executionFn.call(window);
2994
3682
  if (result !== undefined) {
2995
3683
  const resultEntry = {
2996
3684
  id: `result-${Date.now()}`,
@@ -3026,7 +3714,7 @@
3026
3714
  this.historyIndex = Math.max(0, this.historyIndex - 1);
3027
3715
  }
3028
3716
  else {
3029
- this.historyIndex = Math.min(this.commandHistory.length - 1, this.historyIndex + 1);
3717
+ this.historyIndex = Math.min(this.commandHistory.length, this.historyIndex + 1);
3030
3718
  }
3031
3719
  return this.commandHistory[this.historyIndex];
3032
3720
  }
@@ -3387,6 +4075,7 @@
3387
4075
  constructor(callback, threshold = 50) {
3388
4076
  this.observer = null;
3389
4077
  this.idCounter = 0;
4078
+ this.fallbackRunning = false;
3390
4079
  this.callback = callback;
3391
4080
  this.threshold = threshold;
3392
4081
  }
@@ -3412,6 +4101,7 @@
3412
4101
  var _a;
3413
4102
  (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
3414
4103
  this.observer = null;
4104
+ this.fallbackRunning = false;
3415
4105
  }
3416
4106
  handleLongTask(entry) {
3417
4107
  const longTaskEntry = entry; // PerformanceLongTaskTiming
@@ -3433,6 +4123,7 @@
3433
4123
  }
3434
4124
  fallbackDetection() {
3435
4125
  // Fallback detection using requestAnimationFrame
4126
+ this.fallbackRunning = true;
3436
4127
  let lastTime = performance.now();
3437
4128
  const check = () => {
3438
4129
  const currentTime = performance.now();
@@ -3451,7 +4142,7 @@
3451
4142
  this.callback(task);
3452
4143
  }
3453
4144
  lastTime = currentTime;
3454
- if (this.observer === null) {
4145
+ if (this.fallbackRunning) {
3455
4146
  requestAnimationFrame(check);
3456
4147
  }
3457
4148
  };
@@ -4220,8 +4911,12 @@
4220
4911
  this.isDragging = false;
4221
4912
  this.dragOffset = { x: 0, y: 0 };
4222
4913
  this.errorCount = 0;
4914
+ this.eventUnsubscribers = [];
4223
4915
  this.inspector = inspector;
4224
4916
  this.element = this.createElement();
4917
+ // Bind event handlers for proper cleanup later
4918
+ this.boundMouseMove = this.handleMouseMove.bind(this);
4919
+ this.boundMouseUp = this.handleMouseUp.bind(this);
4225
4920
  this.setupEventListeners();
4226
4921
  this.updatePosition();
4227
4922
  }
@@ -4242,22 +4937,25 @@
4242
4937
  });
4243
4938
  // Drag functionality
4244
4939
  this.element.addEventListener('mousedown', this.handleMouseDown.bind(this));
4245
- document.addEventListener('mousemove', this.handleMouseMove.bind(this));
4246
- document.addEventListener('mouseup', this.handleMouseUp.bind(this));
4247
- // Error tracking
4248
- this.inspector.on('error:caught', () => {
4940
+ document.addEventListener('mousemove', this.boundMouseMove);
4941
+ document.addEventListener('mouseup', this.boundMouseUp);
4942
+ // Error tracking - store unsubscribe functions for cleanup
4943
+ const unsubErrorCaught = this.inspector.on('error:caught', () => {
4249
4944
  this.errorCount++;
4250
4945
  this.updateAppearance();
4251
4946
  });
4252
- this.inspector.on('error:uncaught', () => {
4947
+ this.eventUnsubscribers.push(unsubErrorCaught);
4948
+ const unsubErrorUncaught = this.inspector.on('error:uncaught', () => {
4253
4949
  this.errorCount++;
4254
4950
  this.updateAppearance();
4255
4951
  });
4952
+ this.eventUnsubscribers.push(unsubErrorUncaught);
4256
4953
  // Clear error count when inspector is opened
4257
- this.inspector.on('inspector:show', () => {
4954
+ const unsubInspectorShow = this.inspector.on('inspector:show', () => {
4258
4955
  this.errorCount = 0;
4259
4956
  this.updateAppearance();
4260
4957
  });
4958
+ this.eventUnsubscribers.push(unsubInspectorShow);
4261
4959
  }
4262
4960
  handleMouseDown(e) {
4263
4961
  e.preventDefault();
@@ -4308,7 +5006,9 @@
4308
5006
  top: centerY,
4309
5007
  bottom: windowHeight - centerY
4310
5008
  };
4311
- const closestEdge = Object.keys(distances).reduce((a, b) => distances[a] < distances[b] ? a : b);
5009
+ // Find closest edge using type-safe approach
5010
+ const closestEdge = Object.entries(distances)
5011
+ .reduce((a, b) => a[1] < b[1] ? a : b)[0];
4312
5012
  // Animate to edge
4313
5013
  const margin = 20;
4314
5014
  switch (closestEdge) {
@@ -4378,6 +5078,12 @@
4378
5078
  this.element.style.display = 'none';
4379
5079
  }
4380
5080
  destroy() {
5081
+ // Remove document event listeners to prevent memory leaks
5082
+ document.removeEventListener('mousemove', this.boundMouseMove);
5083
+ document.removeEventListener('mouseup', this.boundMouseUp);
5084
+ // Unsubscribe from all inspector events
5085
+ this.eventUnsubscribers.forEach(unsubscribe => unsubscribe());
5086
+ this.eventUnsubscribers = [];
4381
5087
  if (this.element.parentNode) {
4382
5088
  this.element.parentNode.removeChild(this.element);
4383
5089
  }
@@ -4394,6 +5100,9 @@
4394
5100
  this.isDragging = false;
4395
5101
  this.dragOffset = { x: 0, y: 0 };
4396
5102
  this.isResizing = false;
5103
+ this.badgeUpdateInterval = null;
5104
+ this.boundMouseMove = (event) => this.handleMouseMove(event);
5105
+ this.boundMouseUp = () => this.handleMouseUp();
4397
5106
  this.inspector = inspector;
4398
5107
  this.element = this.createElement();
4399
5108
  this.setupEventListeners();
@@ -4451,8 +5160,8 @@
4451
5160
  });
4452
5161
  // Header dragging
4453
5162
  this.headerElement.addEventListener('mousedown', this.handleHeaderMouseDown.bind(this));
4454
- document.addEventListener('mousemove', this.handleMouseMove.bind(this));
4455
- document.addEventListener('mouseup', this.handleMouseUp.bind(this));
5163
+ document.addEventListener('mousemove', this.boundMouseMove);
5164
+ document.addEventListener('mouseup', this.boundMouseUp);
4456
5165
  // Resizing
4457
5166
  const resizer = this.element.querySelector('.devinspector-resizer');
4458
5167
  resizer.addEventListener('mousedown', this.handleResizerMouseDown.bind(this));
@@ -4467,7 +5176,7 @@
4467
5176
  }
4468
5177
  });
4469
5178
  // Update badge counts periodically
4470
- setInterval(() => this.updateBadges(), 1000);
5179
+ this.badgeUpdateInterval = window.setInterval(() => this.updateBadges(), 1000);
4471
5180
  }
4472
5181
  handleHeaderMouseDown(e) {
4473
5182
  if (e.target.closest('.devinspector-control'))
@@ -4550,10 +5259,13 @@
4550
5259
  const tab = document.createElement('button');
4551
5260
  tab.className = 'devinspector-tab';
4552
5261
  tab.dataset.tabId = config.id;
4553
- tab.innerHTML = `
4554
- ${config.label}
4555
- ${config.badge ? '<span class="devinspector-tab-badge">0</span>' : ''}
4556
- `;
5262
+ tab.textContent = config.label;
5263
+ if (config.badge) {
5264
+ const badge = document.createElement('span');
5265
+ badge.className = 'devinspector-tab-badge';
5266
+ badge.textContent = '0';
5267
+ tab.appendChild(badge);
5268
+ }
4557
5269
  this.tabsElement.appendChild(tab);
4558
5270
  // Create panel element
4559
5271
  const panel = document.createElement('div');
@@ -4572,12 +5284,12 @@
4572
5284
  return;
4573
5285
  this.tabs.delete(tabId);
4574
5286
  // Remove tab element
4575
- const tab = this.tabsElement.querySelector(`[data-tab-id="${tabId}"]`);
5287
+ const tab = Array.from(this.tabsElement.querySelectorAll('.devinspector-tab')).find(el => el.dataset.tabId === tabId);
4576
5288
  if (tab) {
4577
5289
  tab.remove();
4578
5290
  }
4579
5291
  // Remove panel element
4580
- const panel = this.bodyElement.querySelector(`[data-panel-id="${tabId}"]`);
5292
+ const panel = Array.from(this.bodyElement.querySelectorAll('.devinspector-panel')).find(el => el.dataset.panelId === tabId);
4581
5293
  if (panel) {
4582
5294
  panel.remove();
4583
5295
  }
@@ -4611,7 +5323,7 @@
4611
5323
  this.tabs.forEach((config, tabId) => {
4612
5324
  if (config.badge) {
4613
5325
  const count = config.badge();
4614
- const tab = this.tabsElement.querySelector(`[data-tab-id="${tabId}"]`);
5326
+ const tab = Array.from(this.tabsElement.querySelectorAll('.devinspector-tab')).find(el => el.dataset.tabId === tabId);
4615
5327
  const badge = tab === null || tab === void 0 ? void 0 : tab.querySelector('.devinspector-tab-badge');
4616
5328
  if (badge) {
4617
5329
  badge.textContent = count.toString();
@@ -4634,6 +5346,13 @@
4634
5346
  this.element.classList.add('minimized');
4635
5347
  }
4636
5348
  destroy() {
5349
+ // Clear badge update interval to prevent memory leak
5350
+ if (this.badgeUpdateInterval !== null) {
5351
+ clearInterval(this.badgeUpdateInterval);
5352
+ this.badgeUpdateInterval = null;
5353
+ }
5354
+ document.removeEventListener('mousemove', this.boundMouseMove);
5355
+ document.removeEventListener('mouseup', this.boundMouseUp);
4637
5356
  if (this.element.parentNode) {
4638
5357
  this.element.parentNode.removeChild(this.element);
4639
5358
  }
@@ -5215,9 +5934,8 @@
5215
5934
  injectStyles() {
5216
5935
  this.styleElement = document.createElement('style');
5217
5936
  const theme = this.inspector.getConfig().theme;
5218
- const resolvedTheme = theme === 'auto' ?
5219
- (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') :
5220
- theme;
5937
+ const prefersDark = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-color-scheme: dark)').matches;
5938
+ const resolvedTheme = theme === 'auto' ? (prefersDark ? 'dark' : 'light') : theme;
5221
5939
  this.styleElement.textContent = createStyles(resolvedTheme);
5222
5940
  document.head.appendChild(this.styleElement);
5223
5941
  }
@@ -5376,7 +6094,7 @@
5376
6094
  entry.dataset.requestId = request.id;
5377
6095
  entry.innerHTML = `
5378
6096
  <div style="display: flex; justify-content: space-between; align-items: center;">
5379
- <span>${request.method} ${request.url}</span>
6097
+ <span>${escapeHtml(request.method)} ${escapeHtml(request.url)}</span>
5380
6098
  <span class="devinspector-status info">Pending</span>
5381
6099
  </div>
5382
6100
  <div class="devinspector-timestamp">${new Date(request.timestamp).toLocaleTimeString()}</div>
@@ -5384,7 +6102,7 @@
5384
6102
  list.appendChild(entry);
5385
6103
  }
5386
6104
  updateNetworkEntry(panel, response) {
5387
- const entry = panel.querySelector(`[data-request-id="${response.id}"]`);
6105
+ const entry = Array.from(panel.querySelectorAll('[data-request-id]')).find(el => el.dataset.requestId === String(response.id));
5388
6106
  if (!entry)
5389
6107
  return;
5390
6108
  const status = entry.querySelector('.devinspector-status');
@@ -5403,10 +6121,10 @@
5403
6121
  placeholder.remove();
5404
6122
  }
5405
6123
  const consoleEntry = document.createElement('div');
5406
- consoleEntry.className = `devinspector-console-entry ${entry.level}`;
6124
+ consoleEntry.className = `devinspector-console-entry ${String(entry.level).replace(/[^a-zA-Z]/g, '')}`;
5407
6125
  consoleEntry.innerHTML = `
5408
- <span class="devinspector-console-level">${entry.level}</span>
5409
- <span class="devinspector-console-content">${this.formatConsoleArgs(entry.formattedArgs)}</span>
6126
+ <span class="devinspector-console-level">${escapeHtml(entry.level)}</span>
6127
+ <span class="devinspector-console-content">${escapeHtml(this.formatConsoleArgs(entry.formattedArgs))}</span>
5410
6128
  <span class="devinspector-timestamp">${new Date(entry.timestamp).toLocaleTimeString()}</span>
5411
6129
  `;
5412
6130
  list.appendChild(consoleEntry);
@@ -5424,9 +6142,9 @@
5424
6142
  const errorEntry = document.createElement('div');
5425
6143
  errorEntry.className = 'devinspector-error-group';
5426
6144
  errorEntry.innerHTML = `
5427
- <div class="devinspector-error-message">${error.message}</div>
6145
+ <div class="devinspector-error-message">${escapeHtml(error.message)}</div>
5428
6146
  <div class="devinspector-timestamp">${new Date(error.timestamp).toLocaleTimeString()}</div>
5429
- ${error.stack ? `<pre class="devinspector-error-stack">${error.stack.join('\n')}</pre>` : ''}
6147
+ ${error.stack ? `<pre class="devinspector-error-stack">${escapeHtml(Array.isArray(error.stack) ? error.stack.join('\n') : error.stack)}</pre>` : ''}
5430
6148
  `;
5431
6149
  list.appendChild(errorEntry);
5432
6150
  }
@@ -5484,17 +6202,7 @@
5484
6202
  DevInspectorUI: DevInspectorUI
5485
6203
  });
5486
6204
 
5487
- exports.BasePlugin = BasePlugin;
5488
- exports.CircularStorage = CircularStorage;
5489
- exports.DevInspector = EnhancedDevInspector;
5490
- exports.EnhancedDevInspector = EnhancedDevInspector;
5491
- exports.EventEmitter = EventEmitter;
5492
- exports.IndexedStorage = IndexedStorage;
5493
- exports.OriginalDevInspector = DevInspector;
5494
- exports.SimpleDevInspector = SimpleDevInspector;
5495
- exports.default = EnhancedDevInspector;
5496
-
5497
- Object.defineProperty(exports, '__esModule', { value: true });
6205
+ return DevInspector;
5498
6206
 
5499
6207
  }));
5500
6208
  //# sourceMappingURL=devinspector.umd.js.map