@oxog/devinspector 1.2.0 → 1.4.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 (77) hide show
  1. package/CHANGELOG.md +60 -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-VZORB655.js +32 -0
  7. package/dist/chunk-VZORB655.js.map +1 -0
  8. package/dist/console-monitor-AVTNZCED.js +571 -0
  9. package/dist/console-monitor-AVTNZCED.js.map +1 -0
  10. package/dist/devinspector.umd.cjs +6218 -0
  11. package/dist/devinspector.umd.cjs.map +1 -0
  12. package/dist/devinspector.umd.d.cts +4 -0
  13. package/dist/devinspector.umd.js +1794 -1076
  14. package/dist/devinspector.umd.js.map +1 -1
  15. package/dist/devinspector.umd.min.cjs +7 -0
  16. package/dist/devinspector.umd.min.cjs.map +1 -0
  17. package/dist/devinspector.umd.min.js +6 -1
  18. package/dist/devinspector.umd.min.js.map +1 -1
  19. package/dist/dom-monitor-JHJVZYS4.js +19 -0
  20. package/dist/dom-monitor-JHJVZYS4.js.map +1 -0
  21. package/dist/error-monitor-3CRFREH3.js +424 -0
  22. package/dist/error-monitor-3CRFREH3.js.map +1 -0
  23. package/dist/index.cjs +5945 -0
  24. package/dist/index.cjs.map +1 -0
  25. package/dist/index.d.cts +582 -0
  26. package/dist/index.d.ts +582 -0
  27. package/dist/index.js +1983 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/inspector-ui-475ZNEHC.js +1241 -0
  30. package/dist/inspector-ui-475ZNEHC.js.map +1 -0
  31. package/dist/network-monitor-WNRL2JI7.js +841 -0
  32. package/dist/network-monitor-WNRL2JI7.js.map +1 -0
  33. package/dist/performance-monitor-UKQFA7ZR.js +544 -0
  34. package/dist/performance-monitor-UKQFA7ZR.js.map +1 -0
  35. package/dist/state-monitor-JGJLBAD7.js +19 -0
  36. package/dist/state-monitor-JGJLBAD7.js.map +1 -0
  37. package/dist/storage-monitor-3NPTWRTY.js +19 -0
  38. package/dist/storage-monitor-3NPTWRTY.js.map +1 -0
  39. package/package.json +78 -38
  40. package/dist/devinspector.cjs.js +0 -5494
  41. package/dist/devinspector.cjs.js.map +0 -1
  42. package/dist/devinspector.esm.js +0 -5482
  43. package/dist/devinspector.esm.js.map +0 -1
  44. package/dist/types/clean-inspector.d.ts +0 -52
  45. package/dist/types/core/event-emitter.d.ts +0 -21
  46. package/dist/types/core/inspector.d.ts +0 -121
  47. package/dist/types/core/plugin-system.d.ts +0 -60
  48. package/dist/types/core/storage.d.ts +0 -52
  49. package/dist/types/core/utils.d.ts +0 -34
  50. package/dist/types/enhanced-inspector.d.ts +0 -56
  51. package/dist/types/enhanced-simple.d.ts +0 -46
  52. package/dist/types/index-simple.d.ts +0 -11
  53. package/dist/types/index.d.ts +0 -19
  54. package/dist/types/monitors/console/console-interceptor.d.ts +0 -36
  55. package/dist/types/monitors/console/console-monitor.d.ts +0 -26
  56. package/dist/types/monitors/console/log-formatter.d.ts +0 -8
  57. package/dist/types/monitors/dom/dom-monitor.d.ts +0 -8
  58. package/dist/types/monitors/error/error-monitor.d.ts +0 -28
  59. package/dist/types/monitors/error/error-tracker.d.ts +0 -55
  60. package/dist/types/monitors/error/source-map-support.d.ts +0 -15
  61. package/dist/types/monitors/network/fetch-interceptor.d.ts +0 -45
  62. package/dist/types/monitors/network/network-monitor.d.ts +0 -47
  63. package/dist/types/monitors/network/websocket-monitor.d.ts +0 -44
  64. package/dist/types/monitors/network/xhr-interceptor.d.ts +0 -25
  65. package/dist/types/monitors/performance/fps-monitor.d.ts +0 -24
  66. package/dist/types/monitors/performance/long-task-detector.d.ts +0 -25
  67. package/dist/types/monitors/performance/memory-monitor.d.ts +0 -30
  68. package/dist/types/monitors/performance/metrics-collector.d.ts +0 -45
  69. package/dist/types/monitors/performance/performance-monitor.d.ts +0 -34
  70. package/dist/types/monitors/state/state-monitor.d.ts +0 -8
  71. package/dist/types/monitors/storage/storage-monitor.d.ts +0 -8
  72. package/dist/types/simple-index.d.ts +0 -3
  73. package/dist/types/simple-inspector.d.ts +0 -24
  74. package/dist/types/ui/components/floating-widget.d.ts +0 -21
  75. package/dist/types/ui/components/main-panel.d.ts +0 -38
  76. package/dist/types/ui/inspector-ui.d.ts +0 -29
  77. package/dist/types/ui/styles.d.ts +0 -1
@@ -1,750 +1,1357 @@
1
1
  /**
2
- * @oxog/devinspector v1.2.0
3
- * (c) 2025 Ersin Koc <ersinkoc@gmail.com>
2
+ * @oxog/devinspector v1.4.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);
23
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
+ // eslint-disable-next-line preserve-caught-error, @typescript-eslint/restrict-template-expressions -- 1.x message format, no `cause`
172
+ throw new Error(`Failed to install plugin "${plugin.name}": ${error}`);
173
+ }
174
+ this.installingPlugins.delete(plugin.name);
175
+ }
176
+ async unregister(pluginName) {
177
+ const plugin = this.plugins.get(pluginName);
178
+ if (!plugin) {
179
+ throw new Error(`Plugin "${pluginName}" is not registered`);
180
+ }
181
+ if (plugin.disable) {
182
+ plugin.disable();
183
+ }
184
+ if (plugin.uninstall) {
185
+ await plugin.uninstall();
186
+ }
187
+ this.plugins.delete(pluginName);
188
+ this.activePlugins.delete(pluginName);
189
+ this.context.events.emit('plugin:unregistered', {
190
+ name: pluginName
191
+ });
192
+ }
193
+ enable(pluginName) {
194
+ const plugin = this.plugins.get(pluginName);
195
+ if (!plugin) {
196
+ throw new Error(`Plugin "${pluginName}" is not registered`);
197
+ }
198
+ if (this.activePlugins.has(pluginName)) {
199
+ return;
200
+ }
201
+ if (plugin.enable) {
202
+ plugin.enable();
203
+ }
204
+ this.activePlugins.add(pluginName);
205
+ this.context.events.emit('plugin:enabled', {
206
+ name: pluginName
207
+ });
208
+ }
209
+ disable(pluginName) {
210
+ const plugin = this.plugins.get(pluginName);
211
+ if (!plugin) {
212
+ throw new Error(`Plugin "${pluginName}" is not registered`);
213
+ }
214
+ if (!this.activePlugins.has(pluginName)) {
215
+ return;
216
+ }
217
+ if (plugin.disable) {
218
+ plugin.disable();
219
+ }
220
+ this.activePlugins.delete(pluginName);
221
+ this.context.events.emit('plugin:disabled', {
222
+ name: pluginName
223
+ });
224
+ }
225
+ get(pluginName) {
226
+ return this.plugins.get(pluginName);
227
+ }
228
+ has(pluginName) {
229
+ return this.plugins.has(pluginName);
230
+ }
231
+ isActive(pluginName) {
232
+ return this.activePlugins.has(pluginName);
233
+ }
234
+ getAll() {
235
+ return Array.from(this.plugins.values());
236
+ }
237
+ getActive() {
238
+ return Array.from(this.activePlugins).map(name => this.plugins.get(name));
239
+ }
240
+ getMetadata(pluginName) {
241
+ const plugin = this.plugins.get(pluginName);
242
+ if (!plugin) {
243
+ return undefined;
244
+ }
245
+ return {
246
+ name: plugin.name,
247
+ version: plugin.version,
248
+ description: plugin.description
249
+ };
250
+ }
251
+ getAllMetadata() {
252
+ return this.getAll().map(plugin => ({
253
+ name: plugin.name,
254
+ version: plugin.version,
255
+ description: plugin.description
256
+ }));
257
+ }
258
+ }
259
+ class BasePlugin {
260
+ async install(context) {
261
+ this.context = context;
262
+ await this.onInstall();
263
+ }
264
+ async uninstall() {
265
+ await this.onUninstall();
266
+ this.context = undefined;
267
+ }
268
+ enable() {
269
+ this.onEnable();
270
+ }
271
+ disable() {
272
+ this.onDisable();
273
+ }
274
+ onUninstall() { }
275
+ onEnable() { }
276
+ onDisable() { }
277
+ get inspector() {
278
+ var _a;
279
+ return (_a = this.context) === null || _a === void 0 ? void 0 : _a.inspector;
280
+ }
281
+ get events() {
282
+ var _a;
283
+ if (!((_a = this.context) === null || _a === void 0 ? void 0 : _a.events)) {
284
+ throw new Error('Events not available - plugin not installed');
285
+ }
286
+ return this.context.events;
287
+ }
288
+ get storage() {
289
+ var _a;
290
+ return (_a = this.context) === null || _a === void 0 ? void 0 : _a.storage;
291
+ }
292
+ get config() {
293
+ var _a;
294
+ return (_a = this.context) === null || _a === void 0 ? void 0 : _a.config;
295
+ }
296
+ }
297
+
298
+ /** Package version, kept in sync with package.json (checked by tests). */
299
+ const VERSION = '1.4.0';
300
+
301
+ /**
302
+ * DevInspector - the default inspector: floating widget plus a panel with
303
+ * Network, Console, Performance and Errors tabs.
304
+ *
305
+ * Everything it patches (window.fetch, XMLHttpRequest.prototype.open/send,
306
+ * console methods) is restored by destroy(). Captured data is kept in bounded
307
+ * buffers and every captured value is HTML-escaped before it is rendered.
308
+ */
309
+ const CONSOLE_METHODS = ['log', 'info', 'warn', 'error', 'debug'];
310
+ const MAX_MESSAGE_LENGTH = 10000;
311
+ const MAX_METRIC_ENTRIES = 500;
312
+ const ASSET_PATTERN = /\.(?:css|js|mjs|map|png|jpe?g|gif|svg|webp|avif|ico|woff2?|ttf|otf|eot)(?:[?#]|$)/i;
313
+ const POSITIONS = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
314
+ const PALETTES = {
315
+ dark: { bg: '#1a1a1a', header: '#262626', toolbar: '#1e1e1e', border: '#333', row: '#2a2a2a', text: '#e4e4e7', muted: '#9ca3af', code: '#0f0f0f' },
316
+ light: { bg: '#ffffff', header: '#f3f4f6', toolbar: '#f9fafb', border: '#d1d5db', row: '#e5e7eb', text: '#111827', muted: '#4b5563', code: '#f3f4f6' },
317
+ };
318
+ let idCounter = 0;
319
+ function nextId() {
320
+ idCounter = (idCounter + 1) % Number.MAX_SAFE_INTEGER;
321
+ return `${Date.now().toString(36)}-${idCounter.toString(36)}`;
322
+ }
323
+ function limit(value, fallback) {
324
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
325
+ }
326
+ function normalizeCombo(combo) {
327
+ if (typeof combo !== 'string')
328
+ return '';
329
+ const parts = combo.toLowerCase().split('+').map(part => part.trim()).filter(Boolean);
330
+ const key = parts.filter(part => !['ctrl', 'control', 'alt', 'shift', 'meta', 'cmd'].includes(part));
331
+ if (key.length !== 1)
332
+ return '';
333
+ const has = (...names) => names.some(name => parts.includes(name));
334
+ return [has('ctrl', 'control') && 'ctrl', has('alt') && 'alt', has('shift') && 'shift', has('meta', 'cmd') && 'meta', key[0]]
335
+ .filter(Boolean)
336
+ .join('+');
337
+ }
338
+ function eventCombo(event) {
339
+ if (typeof event.key !== 'string')
340
+ return '';
341
+ return [event.ctrlKey && 'ctrl', event.altKey && 'alt', event.shiftKey && 'shift', event.metaKey && 'meta', event.key.toLowerCase()]
342
+ .filter(Boolean)
343
+ .join('+');
344
+ }
345
+ function truncate(text) {
346
+ return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}… (${text.length - MAX_MESSAGE_LENGTH} more characters)` : text;
347
+ }
348
+ function stringifyArg(arg) {
349
+ if (typeof arg === 'string')
350
+ return arg;
351
+ if (arg instanceof Error)
352
+ return arg.stack || `${arg.name}: ${arg.message}`;
353
+ if (arg !== null && typeof arg === 'object') {
354
+ const seen = new WeakSet();
355
+ try {
356
+ const json = JSON.stringify(arg, (_key, value) => {
357
+ if (typeof value === 'bigint')
358
+ return `${value}n`;
359
+ if (value !== null && typeof value === 'object') {
360
+ if (seen.has(value))
361
+ return '[Circular]';
362
+ seen.add(value);
363
+ }
364
+ return value;
365
+ }, 2);
366
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string -- fallback for values JSON cannot represent
367
+ return json === undefined ? String(arg) : json;
368
+ }
369
+ catch (_a) {
370
+ try {
371
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string -- last-resort text for unserialisable objects
372
+ return String(arg);
373
+ }
374
+ catch (_b) {
375
+ return '[object]';
376
+ }
377
+ }
378
+ }
379
+ try {
380
+ return String(arg);
381
+ }
382
+ catch (_c) {
383
+ return '[unprintable]';
384
+ }
385
+ }
386
+ function requestUrl(input) {
387
+ if (typeof input === 'string')
388
+ return input;
389
+ if (input && typeof input === 'object') {
390
+ const candidate = input;
391
+ if (typeof candidate.url === 'string')
392
+ return candidate.url; // Request
393
+ if (typeof candidate.href === 'string')
394
+ return candidate.href; // URL / Location
395
+ }
396
+ return String(input);
397
+ }
398
+ function requestMethod(input, init) {
399
+ const fromInit = init && typeof init === 'object' ? init.method : undefined;
400
+ if (typeof fromInit === 'string' && fromInit)
401
+ return fromInit.toUpperCase();
402
+ const fromRequest = input && typeof input === 'object' ? input.method : undefined;
403
+ if (typeof fromRequest === 'string' && fromRequest)
404
+ return fromRequest.toUpperCase();
405
+ return 'GET';
406
+ }
407
+ class EnhancedDevInspector {
408
+ constructor(config = {}) {
409
+ var _a;
410
+ this.events = new EventEmitter({ maxListeners: 100 });
411
+ this.network = [];
412
+ this.consoleEntries = [];
413
+ this.errors = [];
414
+ this.metrics = [];
415
+ this.performanceStats = { fps: 0, memory: null };
24
416
  this.isRecording = true;
25
- this.widget = null;
26
- this.panel = null;
27
417
  this.isVisible = false;
28
418
  this.isMinimized = false;
419
+ this.destroyed = false;
420
+ this.capturing = false;
421
+ this.renderQueued = false;
29
422
  this.activeTab = 'network';
30
- this.selectedRequest = null;
31
- this.init();
423
+ this.selectedRequestId = null;
424
+ this.widget = null;
425
+ this.panel = null;
426
+ this.patches = [];
427
+ this.cleanups = [];
428
+ this.rafId = null;
429
+ this.marks = new Map();
430
+ this.xhrState = new WeakMap();
431
+ this.config = EnhancedDevInspector.resolveConfig(config !== null && config !== void 0 ? config : {});
432
+ this.active = this.config.enabled && hasDom();
433
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
434
+ const self = this;
435
+ this.pluginSystem = new PluginSystem({
436
+ inspector: this,
437
+ storage: {
438
+ get network() {
439
+ return self.getEntries('network');
440
+ },
441
+ get console() {
442
+ return self.getEntries('console');
443
+ },
444
+ get errors() {
445
+ return self.getEntries('errors');
446
+ },
447
+ get metrics() {
448
+ return self.getEntries('metrics');
449
+ },
450
+ },
451
+ events: this.events,
452
+ config: this.config,
453
+ });
454
+ if (!this.active)
455
+ return;
456
+ EnhancedDevInspector.instances.push(this);
457
+ if (this.config.features.network) {
458
+ this.interceptFetch();
459
+ this.interceptXHR();
460
+ }
461
+ if (this.config.features.console)
462
+ this.interceptConsole();
463
+ if (this.config.features.errors)
464
+ this.interceptErrors();
465
+ this.setupHotkeys();
466
+ this.mountWhenReady();
467
+ for (const plugin of (_a = config.plugins) !== null && _a !== void 0 ? _a : []) {
468
+ this.use(plugin).catch(error => this.reportInternal('Failed to register plugin', error));
469
+ }
470
+ this.events.emit('inspector:ready');
471
+ }
472
+ /** The most recently created inspector that is still alive, if any. */
473
+ static getInstance() {
474
+ const { instances } = EnhancedDevInspector;
475
+ return instances.length > 0 ? instances[instances.length - 1] : null;
32
476
  }
33
- init() {
34
- this.createFloatingButton();
35
- this.createMainPanel();
36
- this.setupInterceptors();
37
- this.setupEventListeners();
477
+ static resolveConfig(config) {
478
+ var _a, _b, _c, _d, _e;
479
+ const features = (_a = config.features) !== null && _a !== void 0 ? _a : {};
480
+ const theme = config.theme === 'light' || config.theme === 'dark' ? config.theme : 'auto';
481
+ const prefersDark = (() => {
482
+ try {
483
+ return typeof window !== 'undefined' && typeof window.matchMedia === 'function'
484
+ ? window.matchMedia('(prefers-color-scheme: dark)').matches
485
+ : true;
486
+ }
487
+ catch (_a) {
488
+ return true;
489
+ }
490
+ })();
491
+ const hotkeys = (_b = config.hotkeys) !== null && _b !== void 0 ? _b : {};
492
+ return {
493
+ enabled: typeof config.enabled === 'boolean' ? config.enabled : defaultEnabled(),
494
+ position: POSITIONS.includes(config.position) ? config.position : 'bottom-right',
495
+ theme: theme === 'auto' ? (prefersDark ? 'dark' : 'light') : theme,
496
+ hotkeys: {
497
+ toggle: normalizeCombo((_c = hotkeys.toggle) !== null && _c !== void 0 ? _c : 'ctrl+shift+d'),
498
+ minimize: normalizeCombo((_d = hotkeys.minimize) !== null && _d !== void 0 ? _d : 'ctrl+shift+m'),
499
+ },
500
+ features: {
501
+ network: features.network !== false,
502
+ console: features.console !== false,
503
+ performance: features.performance !== false,
504
+ errors: features.errors !== false,
505
+ },
506
+ maxNetworkEntries: limit(config.maxNetworkEntries, 1000),
507
+ maxConsoleEntries: limit(config.maxConsoleEntries, 500),
508
+ maxErrorEntries: limit(config.maxErrorEntries, 100),
509
+ captureStackTraces: config.captureStackTraces !== false,
510
+ hideAssets: ((_e = config.networkFilters) === null || _e === void 0 ? void 0 : _e.hideAssets) === true,
511
+ slowRequestThreshold: limit(config.slowRequestThreshold, 3000),
512
+ onError: typeof config.onError === 'function' ? config.onError : undefined,
513
+ onPerformanceIssue: typeof config.onPerformanceIssue === 'function' ? config.onPerformanceIssue : undefined,
514
+ };
38
515
  }
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);
516
+ // ---------------------------------------------------------------------------
517
+ // Public API
518
+ // ---------------------------------------------------------------------------
519
+ /** True when the inspector is running (enabled, in a browser, not destroyed). */
520
+ get isEnabled() {
521
+ return this.active && !this.destroyed;
68
522
  }
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);
523
+ show() {
524
+ if (!this.isEnabled)
525
+ return;
526
+ this.isVisible = true;
527
+ if (this.panel)
528
+ this.panel.style.display = 'flex';
529
+ if (this.widget)
530
+ this.widget.style.display = 'none';
531
+ this.render();
532
+ this.startPerformanceLoop();
533
+ this.events.emit('inspector:show');
534
+ }
535
+ hide() {
536
+ if (!this.isEnabled)
537
+ return;
538
+ this.isVisible = false;
539
+ if (this.panel)
540
+ this.panel.style.display = 'none';
541
+ if (this.widget)
542
+ this.widget.style.display = 'flex';
543
+ this.stopPerformanceLoop();
544
+ this.events.emit('inspector:hide');
545
+ }
546
+ toggle() {
547
+ if (this.isVisible)
548
+ this.hide();
549
+ else
550
+ this.show();
91
551
  }
92
- renderPanel() {
93
- if (!this.panel)
552
+ /** Collapses the panel to its header (or expands it again). */
553
+ minimize() {
554
+ if (!this.isEnabled)
94
555
  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();
556
+ this.isMinimized = !this.isMinimized;
557
+ if (this.panel)
558
+ this.panel.style.height = this.isMinimized ? '48px' : '650px';
559
+ this.render();
560
+ this.events.emit('inspector:minimize', this.isMinimized);
561
+ }
562
+ clear(type = 'all') {
563
+ if (type === 'network' || type === 'all') {
564
+ this.network = [];
565
+ this.selectedRequestId = null;
566
+ }
567
+ if (type === 'console' || type === 'all')
568
+ this.consoleEntries = [];
569
+ if (type === 'errors' || type === 'all')
570
+ this.errors = [];
571
+ if (type === 'metrics' || type === 'all')
572
+ this.metrics = [];
573
+ this.scheduleRender();
574
+ }
575
+ /** Pauses or resumes capturing. Patched APIs keep working either way. */
576
+ toggleRecording() {
577
+ this.isRecording = !this.isRecording;
578
+ this.scheduleRender();
579
+ return this.isRecording;
135
580
  }
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
- `;
581
+ get recording() {
582
+ return this.isRecording;
583
+ }
584
+ getEntries(type) {
585
+ switch (type) {
586
+ case 'network':
587
+ return this.network.map(entry => ({ ...entry }));
588
+ case 'console':
589
+ return this.consoleEntries.map(entry => ({ ...entry }));
590
+ case 'errors':
591
+ return this.errors.map(entry => ({ ...entry }));
592
+ default:
593
+ return this.metrics.map(entry => ({ ...entry }));
594
+ }
595
+ }
596
+ /** Records a custom metric and emits `performance:metric`. */
597
+ track(name, data) {
598
+ if (!this.isEnabled)
599
+ return;
600
+ const entry = { id: nextId(), name: String(name), data, timestamp: Date.now() };
601
+ this.pushBounded(this.metrics, entry, MAX_METRIC_ENTRIES);
602
+ this.emitSafely('performance:metric', entry);
603
+ this.scheduleRender();
195
604
  }
196
- renderNetworkRequest(req) {
605
+ markStart(name) {
197
606
  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
- `;
607
+ if (!this.isEnabled)
608
+ return;
609
+ this.marks.set(String(name), performance.now());
610
+ try {
611
+ (_a = performance.mark) === null || _a === void 0 ? void 0 : _a.call(performance, `devinspector-${name}-start`);
612
+ }
613
+ catch (_b) {
614
+ // User Timing is optional; the duration is measured with performance.now().
615
+ }
223
616
  }
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
- `;
617
+ /** Ends a measurement started with markStart() and returns its duration in ms. */
618
+ markEnd(name) {
619
+ var _a, _b;
620
+ if (!this.isEnabled)
621
+ return undefined;
622
+ const key = String(name);
623
+ const start = this.marks.get(key);
624
+ if (start === undefined)
625
+ return undefined;
626
+ this.marks.delete(key);
627
+ const duration = performance.now() - start;
628
+ try {
629
+ (_a = performance.mark) === null || _a === void 0 ? void 0 : _a.call(performance, `devinspector-${key}-end`);
630
+ (_b = performance.measure) === null || _b === void 0 ? void 0 : _b.call(performance, `devinspector-${key}`, `devinspector-${key}-start`, `devinspector-${key}-end`);
631
+ }
632
+ catch (_c) {
633
+ // See markStart().
634
+ }
635
+ const entry = { id: nextId(), name: key, duration, timestamp: Date.now() };
636
+ this.pushBounded(this.metrics, entry, MAX_METRIC_ENTRIES);
637
+ this.emitSafely('performance:mark', entry);
638
+ this.scheduleRender();
639
+ return duration;
253
640
  }
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
- `;
641
+ /** Installs a plugin. Resolves once the plugin's install() has finished. */
642
+ use(plugin) {
643
+ if (this.destroyed)
644
+ return Promise.reject(new Error('DevInspector has been destroyed'));
645
+ return this.pluginSystem.register(plugin);
283
646
  }
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
- `;
647
+ on(event, listener) {
648
+ return this.events.on(event, listener);
317
649
  }
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
- `;
650
+ once(event, listener) {
651
+ return this.events.once(event, listener);
343
652
  }
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';
653
+ off(event, listener) {
654
+ this.events.off(event, listener);
355
655
  }
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'
656
+ /** Serialisable snapshot of everything captured so far. */
657
+ export() {
658
+ return {
659
+ version: VERSION,
660
+ timestamp: Date.now(),
661
+ data: {
662
+ network: this.getEntries('network'),
663
+ console: this.getEntries('console'),
664
+ errors: this.getEntries('errors'),
665
+ metrics: this.getEntries('metrics'),
666
+ },
373
667
  };
374
- return colors[level] || '#d1d5db';
375
668
  }
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();
669
+ /**
670
+ * Loads a snapshot produced by export(), replacing the current data. Entries
671
+ * are validated field by field and trimmed to the configured limits.
672
+ */
673
+ import(snapshot) {
674
+ const data = snapshot && typeof snapshot === 'object' ? snapshot.data : undefined;
675
+ if (!data || typeof data !== 'object')
676
+ throw new TypeError('DevInspector.import() expects an object produced by export()');
677
+ const source = data;
678
+ const list = (value) => Array.isArray(value) ? value.filter((item) => !!item && typeof item === 'object') : [];
679
+ const str = (value, fallback = '') => (typeof value === 'string' ? value : fallback);
680
+ const num = (value) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined);
681
+ this.network = list(source.network)
682
+ .slice(0, this.config.maxNetworkEntries)
683
+ .map(item => {
684
+ var _a;
685
+ return ({
686
+ id: str(item.id, nextId()),
687
+ type: item.type === 'xhr' ? 'xhr' : 'fetch',
688
+ url: str(item.url),
689
+ method: str(item.method, 'GET'),
690
+ status: typeof item.status === 'number' ? item.status : item.status === 'pending' ? 'pending' : 'error',
691
+ timestamp: (_a = num(item.timestamp)) !== null && _a !== void 0 ? _a : Date.now(),
692
+ duration: num(item.duration),
693
+ error: typeof item.error === 'string' ? item.error : undefined,
390
694
  });
391
695
  });
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();
696
+ this.consoleEntries = list(source.console)
697
+ .slice(0, this.config.maxConsoleEntries)
698
+ .map(item => {
699
+ var _a;
700
+ return ({
701
+ id: str(item.id, nextId()),
702
+ level: CONSOLE_METHODS.includes(item.level) ? item.level : 'log',
703
+ message: truncate(str(item.message)),
704
+ timestamp: (_a = num(item.timestamp)) !== null && _a !== void 0 ? _a : Date.now(),
705
+ });
706
+ });
707
+ this.errors = list(source.errors)
708
+ .slice(0, this.config.maxErrorEntries)
709
+ .map(item => {
710
+ var _a;
711
+ return ({
712
+ id: str(item.id, nextId()),
713
+ type: item.type === 'Promise Rejection' ? 'Promise Rejection' : 'JavaScript Error',
714
+ message: truncate(str(item.message)),
715
+ timestamp: (_a = num(item.timestamp)) !== null && _a !== void 0 ? _a : Date.now(),
716
+ stack: typeof item.stack === 'string' ? truncate(item.stack) : undefined,
717
+ });
400
718
  });
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();
719
+ this.metrics = list(source.metrics)
720
+ .slice(0, MAX_METRIC_ENTRIES)
721
+ .map(item => {
722
+ var _a;
723
+ return ({
724
+ id: str(item.id, nextId()),
725
+ name: str(item.name),
726
+ data: item.data,
727
+ duration: num(item.duration),
728
+ timestamp: (_a = num(item.timestamp)) !== null && _a !== void 0 ? _a : Date.now(),
407
729
  });
408
730
  });
731
+ this.selectedRequestId = null;
732
+ this.scheduleRender();
409
733
  }
410
- setupEventListeners() {
411
- document.addEventListener('keydown', (e) => {
412
- if (e.ctrlKey && e.shiftKey && e.key === 'D') {
413
- e.preventDefault();
414
- this.toggle();
734
+ /**
735
+ * Removes the UI, restores every patched API, detaches listeners, stops the
736
+ * frame loop and uninstalls plugins. Safe to call more than once.
737
+ */
738
+ destroy() {
739
+ var _a, _b;
740
+ if (this.destroyed)
741
+ return;
742
+ this.destroyed = true;
743
+ for (const patch of this.patches.reverse()) {
744
+ // Only restore when nobody has wrapped our replacement since; otherwise the
745
+ // replacement stays in place but passes straight through (destroyed flag).
746
+ if (patch.target[patch.key] === patch.replacement)
747
+ patch.target[patch.key] = patch.original;
748
+ }
749
+ this.patches = [];
750
+ for (const cleanup of this.cleanups.splice(0)) {
751
+ try {
752
+ cleanup();
415
753
  }
416
- });
754
+ catch (_c) {
755
+ // Listener removal cannot meaningfully fail; ignore.
756
+ }
757
+ }
758
+ this.stopPerformanceLoop();
759
+ (_a = this.widget) === null || _a === void 0 ? void 0 : _a.remove();
760
+ (_b = this.panel) === null || _b === void 0 ? void 0 : _b.remove();
761
+ this.widget = null;
762
+ this.panel = null;
763
+ for (const plugin of this.pluginSystem.getAll()) {
764
+ this.pluginSystem.unregister(plugin.name).catch(error => this.reportInternal(`Failed to uninstall plugin "${plugin.name}"`, error));
765
+ }
766
+ this.emitSafely('inspector:destroy', undefined);
767
+ this.events.removeAllListeners();
768
+ this.network = [];
769
+ this.consoleEntries = [];
770
+ this.errors = [];
771
+ this.metrics = [];
772
+ this.marks.clear();
773
+ EnhancedDevInspector.instances = EnhancedDevInspector.instances.filter(instance => instance !== this);
774
+ }
775
+ // ---------------------------------------------------------------------------
776
+ // Capture
777
+ // ---------------------------------------------------------------------------
778
+ get capturingAllowed() {
779
+ return !this.destroyed && this.isRecording && !this.capturing;
780
+ }
781
+ /** Runs capture code with re-entrancy protection; capture failures never reach the page. */
782
+ capture(fn) {
783
+ if (!this.capturingAllowed)
784
+ return;
785
+ this.capturing = true;
786
+ try {
787
+ fn();
788
+ }
789
+ catch (error) {
790
+ this.reportInternal('Capture failed', error);
791
+ }
792
+ finally {
793
+ this.capturing = false;
794
+ }
795
+ }
796
+ emitSafely(event, data) {
797
+ this.events.emit(event, data);
798
+ }
799
+ pushBounded(list, entry, max) {
800
+ list.unshift(entry);
801
+ if (list.length > max)
802
+ list.length = max;
417
803
  }
418
- setupInterceptors() {
419
- this.interceptFetch();
420
- this.interceptXHR();
421
- this.interceptConsole();
422
- this.interceptErrors();
423
- this.setupPerformanceMonitoring();
804
+ patch(target, key, replacement) {
805
+ const original = target[key];
806
+ target[key] = replacement;
807
+ this.patches.push({ target, key, original, replacement });
808
+ }
809
+ listen(target, type, handler) {
810
+ target.addEventListener(type, handler);
811
+ this.cleanups.push(() => target.removeEventListener(type, handler));
812
+ }
813
+ addNetworkEntry(entry) {
814
+ this.pushBounded(this.network, entry, this.config.maxNetworkEntries);
815
+ this.emitSafely('network:request', { ...entry });
816
+ this.scheduleRender();
817
+ }
818
+ finishNetworkEntry(entry, status, duration, error) {
819
+ entry.status = status;
820
+ entry.duration = Math.round(duration);
821
+ if (error !== undefined)
822
+ entry.error = error;
823
+ this.emitSafely(status === 'error' ? 'network:error' : 'network:response', { ...entry });
824
+ if (duration > this.config.slowRequestThreshold) {
825
+ const issue = { type: 'slow-network', message: `Slow network request: ${entry.url}`, url: entry.url, duration: entry.duration };
826
+ this.emitSafely('performance:issue', issue);
827
+ this.callUser(this.config.onPerformanceIssue, issue);
828
+ }
829
+ this.scheduleRender();
424
830
  }
425
831
  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();
832
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- called through Reflect.apply with the caller's receiver
833
+ const originalFetch = typeof window.fetch === 'function' ? window.fetch : null;
834
+ if (!originalFetch)
835
+ return;
836
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
837
+ const self = this;
838
+ const instrumentedFetch = function (...args) {
839
+ let entry = null;
840
+ const start = performance.now();
841
+ self.capture(() => {
842
+ entry = { id: nextId(), type: 'fetch', url: requestUrl(args[0]), method: requestMethod(args[0], args[1]), status: 'pending', timestamp: Date.now() };
843
+ self.addNetworkEntry(entry);
844
+ });
845
+ if (!entry)
846
+ return Reflect.apply(originalFetch, this, args);
847
+ const tracked = entry;
848
+ let result;
443
849
  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;
850
+ // Call through with the caller's receiver and arguments untouched.
851
+ result = Reflect.apply(originalFetch, this, args);
456
852
  }
457
853
  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
- }
854
+ self.capture(() => self.finishNetworkEntry(tracked, 'error', performance.now() - start, error instanceof Error ? error.message : String(error)));
469
855
  throw error;
470
856
  }
857
+ return Promise.resolve(result).then(response => {
858
+ self.capture(() => self.finishNetworkEntry(tracked, response.status, performance.now() - start));
859
+ return response;
860
+ }, (error) => {
861
+ self.capture(() => self.finishNetworkEntry(tracked, 'error', performance.now() - start, error instanceof Error ? error.message : String(error)));
862
+ throw error;
863
+ });
471
864
  };
865
+ this.patch(window, 'fetch', instrumentedFetch);
472
866
  }
473
867
  interceptXHR() {
474
- const originalXHR = window.XMLHttpRequest;
868
+ const XHR = typeof XMLHttpRequest === 'function' ? XMLHttpRequest : null;
869
+ if (!XHR)
870
+ return;
871
+ const proto = XHR.prototype;
872
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- re-applied to each request through Reflect.apply
873
+ const originalOpen = proto.open;
874
+ // eslint-disable-next-line @typescript-eslint/unbound-method -- re-applied to each request through Reflect.apply
875
+ const originalSend = proto.send;
475
876
  // eslint-disable-next-line @typescript-eslint/no-this-alias
476
877
  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;
878
+ // Patch the prototype rather than replacing the constructor, so
879
+ // `instanceof XMLHttpRequest` and constants such as XMLHttpRequest.DONE keep working.
880
+ const open = function (...args) {
881
+ if (!self.destroyed) {
882
+ self.xhrState.set(this, { method: typeof args[0] === 'string' ? args[0].toUpperCase() : 'GET', url: requestUrl(args[1]) });
883
+ }
884
+ return Reflect.apply(originalOpen, this, args);
885
+ };
886
+ const send = function (...args) {
887
+ const state = self.xhrState.get(this);
888
+ if (state)
889
+ self.capture(() => self.trackXhr(this, state));
890
+ return Reflect.apply(originalSend, this, args);
891
+ };
892
+ this.patch(proto, 'open', open);
893
+ this.patch(proto, 'send', send);
894
+ }
895
+ trackXhr(xhr, state) {
896
+ const entry = { id: nextId(), type: 'xhr', url: state.url, method: state.method, status: 'pending', timestamp: Date.now() };
897
+ state.entry = entry;
898
+ state.start = performance.now();
899
+ state.failure = undefined;
900
+ const fail = (reason) => () => {
901
+ state.failure = reason;
902
+ };
903
+ const onError = fail('Network error');
904
+ const onAbort = fail('Request aborted');
905
+ const onTimeout = fail('Request timed out');
906
+ const onLoadEnd = () => {
907
+ var _a;
908
+ xhr.removeEventListener('error', onError);
909
+ xhr.removeEventListener('abort', onAbort);
910
+ xhr.removeEventListener('timeout', onTimeout);
911
+ xhr.removeEventListener('loadend', onLoadEnd);
912
+ if (state.entry !== entry || this.destroyed)
913
+ return;
914
+ const duration = performance.now() - ((_a = state.start) !== null && _a !== void 0 ? _a : performance.now());
915
+ const failed = state.failure !== undefined || xhr.status === 0;
916
+ 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
917
  };
918
+ xhr.addEventListener('error', onError);
919
+ xhr.addEventListener('abort', onAbort);
920
+ xhr.addEventListener('timeout', onTimeout);
921
+ xhr.addEventListener('loadend', onLoadEnd);
922
+ this.addNetworkEntry(entry);
517
923
  }
518
924
  interceptConsole() {
519
- const levels = ['log', 'warn', 'error', 'info', 'debug'];
520
- levels.forEach(level => {
925
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
926
+ const self = this;
927
+ for (const level of CONSOLE_METHODS) {
521
928
  const original = console[level];
522
- console[level] = (...args) => {
523
- if (this.isRecording) {
524
- const log = {
525
- id: Math.random().toString(36).substr(2, 9),
929
+ if (typeof original !== 'function')
930
+ continue;
931
+ const wrapper = function (...args) {
932
+ // The real console runs first and its result (and any exception) is passed through.
933
+ const result = Reflect.apply(original, this === undefined ? console : this, args);
934
+ self.capture(() => {
935
+ const entry = {
936
+ id: nextId(),
526
937
  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()
938
+ message: truncate(args.map(stringifyArg).join(' ')),
939
+ timestamp: Date.now(),
539
940
  };
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);
941
+ self.pushBounded(self.consoleEntries, entry, self.config.maxConsoleEntries);
942
+ self.emitSafely('console:log', { ...entry });
943
+ self.scheduleRender();
944
+ });
945
+ return result;
547
946
  };
548
- });
947
+ this.patch(console, level, wrapper);
948
+ }
549
949
  }
550
950
  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();
951
+ const record = (entry, error) => {
952
+ this.pushBounded(this.errors, entry, this.config.maxErrorEntries);
953
+ this.emitSafely('error:uncaught', { ...entry });
954
+ this.callUser(this.config.onError, error);
955
+ this.scheduleRender();
956
+ };
957
+ this.listen(window, 'error', (event) => {
958
+ this.capture(() => {
959
+ var _a;
960
+ const error = event.error instanceof Error ? event.error : new Error(String((_a = event.message) !== null && _a !== void 0 ? _a : 'Unknown error'));
961
+ record({
962
+ id: nextId(),
963
+ type: 'JavaScript Error',
964
+ message: truncate(String(event.message || error.message)),
965
+ timestamp: Date.now(),
966
+ stack: this.config.captureStackTraces && error.stack ? truncate(error.stack) : undefined,
967
+ filename: typeof event.filename === 'string' && event.filename ? event.filename : undefined,
968
+ lineno: typeof event.lineno === 'number' ? event.lineno : undefined,
969
+ colno: typeof event.colno === 'number' ? event.colno : undefined,
970
+ }, error);
971
+ });
564
972
  });
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();
973
+ this.listen(window, 'unhandledrejection', (event) => {
974
+ this.capture(() => {
975
+ const reason = event.reason;
976
+ const error = reason instanceof Error ? reason : new Error(stringifyArg(reason));
977
+ record({
978
+ id: nextId(),
979
+ type: 'Promise Rejection',
980
+ message: truncate(error.message),
981
+ timestamp: Date.now(),
982
+ stack: this.config.captureStackTraces && reason instanceof Error && reason.stack ? truncate(reason.stack) : undefined,
983
+ }, error);
984
+ });
577
985
  });
578
986
  }
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
- }
987
+ setupHotkeys() {
988
+ const { toggle, minimize } = this.config.hotkeys;
989
+ if (!toggle && !minimize)
990
+ return;
991
+ this.listen(document, 'keydown', (event) => {
992
+ const combo = eventCombo(event);
993
+ if (toggle && combo === toggle) {
994
+ event.preventDefault();
995
+ this.toggle();
600
996
  }
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);
997
+ else if (minimize && combo === minimize) {
998
+ event.preventDefault();
999
+ if (!this.isVisible)
1000
+ this.show();
1001
+ this.minimize();
682
1002
  }
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;
1003
+ });
692
1004
  }
693
- emit(event, ...args) {
694
- const listeners = this.events.get(event);
695
- if (!listeners || listeners.size === 0) {
696
- return false;
1005
+ /** Calls a user callback; a throwing callback is reported but never breaks capture. */
1006
+ callUser(callback, value) {
1007
+ if (!callback)
1008
+ return;
1009
+ try {
1010
+ callback(value);
697
1011
  }
698
- const data = args[0];
699
- listeners.forEach(listener => {
700
- try {
701
- listener(data);
1012
+ catch (error) {
1013
+ this.reportInternal('A DevInspector callback threw', error);
1014
+ }
1015
+ }
1016
+ reportInternal(message, error) {
1017
+ // Use the unpatched console so internal problems are visible but never captured.
1018
+ const patched = this.patches.find(patch => patch.target === console && patch.key === 'error');
1019
+ const log = (patched ? patched.original : console.error);
1020
+ try {
1021
+ log.call(console, `[DevInspector] ${message}:`, error);
1022
+ }
1023
+ catch (_a) {
1024
+ // Nothing else we can do.
1025
+ }
1026
+ }
1027
+ // ---------------------------------------------------------------------------
1028
+ // Performance loop (runs only while the panel is visible)
1029
+ // ---------------------------------------------------------------------------
1030
+ startPerformanceLoop() {
1031
+ if (!this.config.features.performance || this.rafId !== null || typeof requestAnimationFrame !== 'function')
1032
+ return;
1033
+ let last = performance.now();
1034
+ let frames = 0;
1035
+ const tick = () => {
1036
+ if (this.destroyed || !this.isVisible) {
1037
+ this.rafId = null;
1038
+ return;
702
1039
  }
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);
1040
+ frames++;
1041
+ const now = performance.now();
1042
+ if (now - last >= 1000) {
1043
+ this.performanceStats.fps = Math.round((frames * 1000) / (now - last));
1044
+ frames = 0;
1045
+ last = now;
1046
+ const memory = performance.memory;
1047
+ if (memory) {
1048
+ this.performanceStats.memory = {
1049
+ used: Math.round(memory.usedJSHeapSize / 1048576),
1050
+ total: Math.round(memory.totalJSHeapSize / 1048576),
1051
+ limit: Math.round(memory.jsHeapSizeLimit / 1048576),
1052
+ };
710
1053
  }
1054
+ if (this.activeTab === 'performance')
1055
+ this.scheduleRender();
711
1056
  }
712
- });
713
- return true;
714
- }
715
- off(event, listener) {
716
- if (!listener) {
717
- this.events.delete(event);
1057
+ this.rafId = requestAnimationFrame(tick);
1058
+ };
1059
+ this.rafId = requestAnimationFrame(tick);
1060
+ }
1061
+ stopPerformanceLoop() {
1062
+ if (this.rafId !== null && typeof cancelAnimationFrame === 'function')
1063
+ cancelAnimationFrame(this.rafId);
1064
+ this.rafId = null;
1065
+ }
1066
+ // ---------------------------------------------------------------------------
1067
+ // UI
1068
+ // ---------------------------------------------------------------------------
1069
+ mountWhenReady() {
1070
+ if (document.body) {
1071
+ this.mount();
718
1072
  return;
719
1073
  }
720
- const listeners = this.events.get(event);
721
- if (listeners) {
722
- listeners.delete(listener);
723
- if (listeners.size === 0) {
724
- this.events.delete(event);
1074
+ const onReady = () => {
1075
+ if (!this.destroyed && !this.widget)
1076
+ this.mount();
1077
+ };
1078
+ this.listen(document, 'DOMContentLoaded', onReady);
1079
+ }
1080
+ get colors() {
1081
+ return PALETTES[this.config.theme];
1082
+ }
1083
+ placement(offset) {
1084
+ const [vertical, horizontal] = this.config.position.split('-');
1085
+ return `${vertical}: ${offset}px; ${horizontal}: ${offset}px;`;
1086
+ }
1087
+ mount() {
1088
+ const widget = document.createElement('div');
1089
+ widget.className = 'devinspector-widget';
1090
+ widget.setAttribute('role', 'button');
1091
+ widget.setAttribute('aria-label', 'Open DevInspector');
1092
+ widget.title = 'DevInspector';
1093
+ widget.textContent = '🔍';
1094
+ widget.style.cssText = `position: fixed; ${this.placement(24)} width: 56px; height: 56px;
1095
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 50%;
1096
+ display: flex; align-items: center; justify-content: center; cursor: pointer; z-index: 999999;
1097
+ color: white; font-size: 24px; box-shadow: 0 8px 32px rgba(102, 126, 234, 0.4); user-select: none;`;
1098
+ widget.addEventListener('click', () => this.toggle());
1099
+ const panel = document.createElement('div');
1100
+ panel.className = 'devinspector-panel';
1101
+ panel.style.cssText = `position: fixed; ${this.placement(24)} width: 480px; max-width: calc(100vw - 48px);
1102
+ height: 650px; max-height: calc(100vh - 48px); background: ${this.colors.bg}; border: 1px solid ${this.colors.border};
1103
+ border-radius: 12px; display: none; flex-direction: column; z-index: 999998; box-shadow: 0 24px 64px rgba(0, 0, 0, 0.5);
1104
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 13px;
1105
+ color: ${this.colors.text}; overflow: hidden;`;
1106
+ // One delegated listener survives every re-render (no per-render listener churn).
1107
+ panel.addEventListener('click', event => this.handlePanelClick(event));
1108
+ this.widget = widget;
1109
+ this.panel = panel;
1110
+ document.body.appendChild(widget);
1111
+ document.body.appendChild(panel);
1112
+ this.render();
1113
+ }
1114
+ handlePanelClick(event) {
1115
+ var _a, _b;
1116
+ const target = event.target;
1117
+ const actionable = (_a = target === null || target === void 0 ? void 0 : target.closest) === null || _a === void 0 ? void 0 : _a.call(target, '[data-action]');
1118
+ if (!actionable)
1119
+ return;
1120
+ const action = actionable.getAttribute('data-action');
1121
+ switch (action) {
1122
+ case 'minimize':
1123
+ this.minimize();
1124
+ break;
1125
+ case 'close':
1126
+ this.hide();
1127
+ break;
1128
+ case 'tab': {
1129
+ const tab = actionable.getAttribute('data-tab');
1130
+ if (['network', 'console', 'performance', 'errors'].includes(tab)) {
1131
+ this.activeTab = tab;
1132
+ this.render();
1133
+ }
1134
+ break;
725
1135
  }
1136
+ case 'clear':
1137
+ this.clear((_b = actionable.getAttribute('data-target')) !== null && _b !== void 0 ? _b : 'all');
1138
+ break;
1139
+ case 'toggle-recording':
1140
+ this.toggleRecording();
1141
+ break;
1142
+ case 'select-request':
1143
+ this.selectedRequestId = actionable.getAttribute('data-id');
1144
+ this.render();
1145
+ break;
1146
+ case 'close-details':
1147
+ this.selectedRequestId = null;
1148
+ this.render();
1149
+ break;
726
1150
  }
727
1151
  }
728
- removeAllListeners(event) {
729
- if (event) {
730
- this.events.delete(event);
1152
+ /** Coalesces renders triggered by bursts of captured events into one microtask. */
1153
+ scheduleRender() {
1154
+ if (this.renderQueued || !this.panel || !this.isVisible)
1155
+ return;
1156
+ this.renderQueued = true;
1157
+ queueMicrotask(() => {
1158
+ this.renderQueued = false;
1159
+ if (!this.destroyed)
1160
+ this.render();
1161
+ });
1162
+ }
1163
+ render() {
1164
+ if (!this.panel || !this.isVisible)
1165
+ return;
1166
+ const c = this.colors;
1167
+ 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>`;
1168
+ const tabs = [
1169
+ { id: 'network', label: 'Network', count: this.network.length },
1170
+ { id: 'console', label: 'Console', count: this.consoleEntries.length },
1171
+ { id: 'performance', label: 'Performance' },
1172
+ { id: 'errors', label: 'Errors', count: this.errors.length },
1173
+ ];
1174
+ const header = `
1175
+ <div style="display: flex; align-items: center; justify-content: space-between; padding: 12px 16px; background: ${c.header}; border-bottom: 1px solid ${c.border};">
1176
+ <div style="display: flex; align-items: center; gap: 8px;">
1177
+ <span style="width: 8px; height: 8px; border-radius: 50%; background: ${this.isRecording ? '#ef4444' : '#6b7280'};"></span>
1178
+ <span style="font-weight: 600; font-size: 14px;">DevInspector v${escapeHtml(VERSION)}</span>
1179
+ </div>
1180
+ <div style="display: flex; gap: 4px;">
1181
+ <button type="button" data-action="minimize" aria-label="Minimize" style="padding: 6px; background: none; border: none; color: ${c.muted}; cursor: pointer;">−</button>
1182
+ <button type="button" data-action="close" aria-label="Close" style="padding: 6px; background: none; border: none; color: ${c.muted}; cursor: pointer;">×</button>
1183
+ </div>
1184
+ </div>`;
1185
+ if (this.isMinimized) {
1186
+ this.panel.innerHTML = header;
1187
+ return;
731
1188
  }
732
- else {
733
- this.events.clear();
1189
+ const tabBar = tabs
1190
+ .map(tab => `<button type="button" data-action="tab" data-tab="${tab.id}" style="padding: 12px 16px; border: none; cursor: pointer;
1191
+ background: ${this.activeTab === tab.id ? c.bg : 'transparent'}; color: ${this.activeTab === tab.id ? '#3b82f6' : c.muted};
1192
+ border-bottom: 2px solid ${this.activeTab === tab.id ? '#3b82f6' : 'transparent'};">${tab.label}${tab.count !== undefined
1193
+ ? ` <span style="background: #374151; color: white; padding: 2px 6px; border-radius: 10px; font-size: 11px; margin-left: 4px;">${tab.count}</span>`
1194
+ : ''}</button>`)
1195
+ .join('');
1196
+ let content = '';
1197
+ switch (this.activeTab) {
1198
+ case 'network':
1199
+ content = this.renderNetwork(button);
1200
+ break;
1201
+ case 'console':
1202
+ content = this.renderConsole(button);
1203
+ break;
1204
+ case 'performance':
1205
+ content = this.renderPerformance(button);
1206
+ break;
1207
+ case 'errors':
1208
+ content = this.renderErrors(button);
1209
+ break;
734
1210
  }
1211
+ this.panel.innerHTML = `${header}
1212
+ <div style="display: flex; background: ${c.header}; border-bottom: 1px solid ${c.border};">${tabBar}</div>
1213
+ <div style="flex: 1; min-height: 0; display: flex; flex-direction: column;">${content}</div>`;
735
1214
  }
736
- listenerCount(event) {
737
- const listeners = this.events.get(event);
738
- return listeners ? listeners.size : 0;
1215
+ toolbar(buttons, summary) {
1216
+ const c = this.colors;
1217
+ return `<div style="padding: 12px; border-bottom: 1px solid ${c.border}; background: ${c.toolbar}; display: flex; align-items: center;">
1218
+ ${buttons}<span style="margin-left: auto; color: ${c.muted}; font-size: 12px;">${summary}</span></div>`;
739
1219
  }
740
- eventNames() {
741
- return Array.from(this.events.keys());
1220
+ empty(text) {
1221
+ return `<div style="display: flex; align-items: center; justify-content: center; height: 200px; color: ${this.colors.muted};">${text}</div>`;
742
1222
  }
743
- setMaxListeners(n) {
744
- this.maxListeners = n;
1223
+ renderNetwork(button) {
1224
+ var _a;
1225
+ const c = this.colors;
1226
+ const visible = this.config.hideAssets ? this.network.filter(entry => !ASSET_PATTERN.test(entry.url)) : this.network;
1227
+ const rows = visible
1228
+ .map(entry => {
1229
+ var _a;
1230
+ const selected = entry.id === this.selectedRequestId;
1231
+ 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);' : ''}">
1232
+ <div style="display: flex; justify-content: space-between; margin-bottom: 4px;">
1233
+ <div style="display: flex; gap: 8px;">
1234
+ <span style="background: ${methodColor(entry.method)}; color: white; padding: 2px 6px; border-radius: 4px; font-size: 11px; font-weight: 600;">${escapeHtml(entry.method)}</span>
1235
+ <span style="color: ${statusColor(entry.status)}; font-weight: 600;">${escapeHtml(entry.status)}</span>
1236
+ <span style="color: ${c.muted};">${(_a = entry.duration) !== null && _a !== void 0 ? _a : '-'}ms</span>
1237
+ </div>
1238
+ <span style="color: ${c.muted}; font-size: 11px;">${escapeHtml(new Date(entry.timestamp).toLocaleTimeString())}</span>
1239
+ </div>
1240
+ <div style="font-size: 12px; word-break: break-all;">${escapeHtml(entry.url)}</div>
1241
+ </div>`;
1242
+ })
1243
+ .join('');
1244
+ const selected = this.selectedRequestId ? this.network.find(entry => entry.id === this.selectedRequestId) : undefined;
1245
+ const details = selected
1246
+ ? `<div style="border-top: 1px solid ${c.border}; max-height: 200px; overflow-y: auto; background: ${c.toolbar}; padding: 12px 16px; font-size: 12px;">
1247
+ <div style="display: flex; justify-content: space-between; margin-bottom: 8px;"><strong>Request details</strong>
1248
+ <button type="button" data-action="close-details" aria-label="Close details" style="background: none; border: none; color: ${c.muted}; cursor: pointer;">×</button></div>
1249
+ <div><strong>URL:</strong> ${escapeHtml(selected.url)}</div>
1250
+ <div><strong>Method:</strong> ${escapeHtml(selected.method)}</div>
1251
+ <div><strong>Type:</strong> ${escapeHtml(selected.type)}</div>
1252
+ <div><strong>Status:</strong> ${escapeHtml(selected.status)}</div>
1253
+ <div><strong>Duration:</strong> ${(_a = selected.duration) !== null && _a !== void 0 ? _a : '-'}ms</div>
1254
+ ${selected.error ? `<div><strong>Error:</strong> ${escapeHtml(selected.error)}</div>` : ''}
1255
+ </div>`
1256
+ : '';
1257
+ return `${this.toolbar(button('clear', 'Clear', 'data-target="network"') +
1258
+ button('toggle-recording', this.isRecording ? 'Pause' : 'Resume', '', this.isRecording ? '#ef4444' : '#22c55e'), `${visible.length} requests`)}
1259
+ <div style="flex: 1; overflow-y: auto;">${rows || this.empty('No network activity')}</div>${details}`;
1260
+ }
1261
+ renderConsole(button) {
1262
+ const c = this.colors;
1263
+ const rows = this.consoleEntries
1264
+ .map(entry => `<div style="padding: 8px 16px; border-bottom: 1px solid ${c.row}; font-size: 12px;">
1265
+ <span style="color: ${levelColor(entry.level)}; text-transform: uppercase; font-weight: 600;">[${escapeHtml(entry.level)}]</span>
1266
+ <span style="color: ${c.muted}; margin: 0 8px;">${escapeHtml(new Date(entry.timestamp).toLocaleTimeString())}</span>
1267
+ <span style="white-space: pre-wrap; word-break: break-word;">${escapeHtml(entry.message)}</span>
1268
+ </div>`)
1269
+ .join('');
1270
+ return `${this.toolbar(button('clear', 'Clear', 'data-target="console"'), `${this.consoleEntries.length} logs`)}
1271
+ <div style="flex: 1; overflow-y: auto; font-family: monospace;">${rows || this.empty('No console logs')}</div>`;
1272
+ }
1273
+ renderPerformance(button) {
1274
+ const c = this.colors;
1275
+ const { fps, memory } = this.performanceStats;
1276
+ const rows = this.metrics
1277
+ .slice(0, 100)
1278
+ .map(metric => `<div style="padding: 6px 0; border-bottom: 1px solid ${c.row}; font-size: 12px;">
1279
+ <strong>${escapeHtml(metric.name)}</strong>
1280
+ ${metric.duration !== undefined ? `<span style="color: ${c.muted};"> ${metric.duration.toFixed(1)}ms</span>` : ''}
1281
+ ${metric.data !== undefined ? `<span style="color: ${c.muted};"> ${escapeHtml(truncate(stringifyArg(metric.data)))}</span>` : ''}
1282
+ </div>`)
1283
+ .join('');
1284
+ return `${this.toolbar(button('clear', 'Clear', 'data-target="metrics"'), `${this.metrics.length} metrics`)}
1285
+ <div style="flex: 1; overflow-y: auto; padding: 16px;">
1286
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px;">
1287
+ <div style="background: #1e3a8a; border-radius: 12px; padding: 16px; text-align: center;">
1288
+ <div style="font-size: 28px; font-weight: 700; color: #93c5fd;">${this.config.features.performance ? fps : '-'}</div>
1289
+ <div style="font-size: 12px; color: #bfdbfe;">FPS</div>
1290
+ </div>
1291
+ <div style="background: #166534; border-radius: 12px; padding: 16px; text-align: center;">
1292
+ <div style="font-size: 28px; font-weight: 700; color: #86efac;">${memory ? `${memory.used} MB` : 'N/A'}</div>
1293
+ <div style="font-size: 12px; color: #bbf7d0;">Memory</div>
1294
+ </div>
1295
+ </div>
1296
+ ${rows || `<div style="color: ${c.muted};">Use track(), markStart() and markEnd() to record metrics.</div>`}
1297
+ </div>`;
1298
+ }
1299
+ renderErrors(button) {
1300
+ const c = this.colors;
1301
+ const rows = this.errors
1302
+ .map(error => `<div style="padding: 12px 16px; border-bottom: 1px solid ${c.row};">
1303
+ <div style="display: flex; justify-content: space-between; margin-bottom: 6px;">
1304
+ <span style="color: #ef4444; font-weight: 600;">${escapeHtml(error.type)}</span>
1305
+ <span style="color: ${c.muted}; font-size: 11px;">${escapeHtml(new Date(error.timestamp).toLocaleTimeString())}</span>
1306
+ </div>
1307
+ <div style="color: #f87171; margin-bottom: 6px; word-break: break-word;">${escapeHtml(error.message)}</div>
1308
+ ${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>` : ''}
1309
+ </div>`)
1310
+ .join('');
1311
+ return `${this.toolbar(button('clear', 'Clear', 'data-target="errors"'), `${this.errors.length} errors`)}
1312
+ <div style="flex: 1; overflow-y: auto;">${rows || this.empty('No errors recorded')}</div>`;
745
1313
  }
746
- getMaxListeners() {
747
- return this.maxListeners;
1314
+ }
1315
+ EnhancedDevInspector.instances = [];
1316
+ function statusColor(status) {
1317
+ if (typeof status !== 'number')
1318
+ return '#6b7280';
1319
+ if (status >= 200 && status < 300)
1320
+ return '#22c55e';
1321
+ if (status >= 300 && status < 400)
1322
+ return '#f59e0b';
1323
+ if (status >= 400)
1324
+ return '#ef4444';
1325
+ return '#6b7280';
1326
+ }
1327
+ function methodColor(method) {
1328
+ switch (method) {
1329
+ case 'GET':
1330
+ return '#16a34a';
1331
+ case 'POST':
1332
+ return '#2563eb';
1333
+ case 'PUT':
1334
+ return '#d97706';
1335
+ case 'DELETE':
1336
+ return '#dc2626';
1337
+ case 'PATCH':
1338
+ return '#7c3aed';
1339
+ default:
1340
+ return '#6b7280';
1341
+ }
1342
+ }
1343
+ function levelColor(level) {
1344
+ switch (level) {
1345
+ case 'info':
1346
+ return '#60a5fa';
1347
+ case 'warn':
1348
+ return '#fbbf24';
1349
+ case 'error':
1350
+ return '#f87171';
1351
+ case 'debug':
1352
+ return '#a78bfa';
1353
+ default:
1354
+ return 'inherit';
748
1355
  }
749
1356
  }
750
1357
 
@@ -885,7 +1492,11 @@
885
1492
  data
886
1493
  };
887
1494
  if (this.storage.has(key)) {
888
- this.accessOrder = this.accessOrder.filter(k => k !== key);
1495
+ // Optimize: use splice instead of filter to avoid creating new array
1496
+ const index = this.accessOrder.indexOf(key);
1497
+ if (index > -1) {
1498
+ this.accessOrder.splice(index, 1);
1499
+ }
889
1500
  }
890
1501
  else if (this.storage.size >= this.maxSize) {
891
1502
  const evictKey = this.accessOrder.shift();
@@ -903,236 +1514,89 @@
903
1514
  get(key) {
904
1515
  const entry = this.storage.get(key);
905
1516
  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;
1517
+ this.updateAccessOrder(key);
1518
+ return entry.data;
1053
1519
  }
1054
- if (plugin.disable) {
1055
- plugin.disable();
1520
+ else if (entry) {
1521
+ this.delete(key);
1056
1522
  }
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));
1523
+ return undefined;
1076
1524
  }
1077
- getMetadata(pluginName) {
1078
- const plugin = this.plugins.get(pluginName);
1079
- if (!plugin) {
1080
- return undefined;
1525
+ has(key) {
1526
+ const entry = this.storage.get(key);
1527
+ if (entry && !this.isExpired(entry)) {
1528
+ return true;
1081
1529
  }
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
- }));
1530
+ else if (entry) {
1531
+ this.delete(key);
1532
+ }
1533
+ return false;
1094
1534
  }
1095
- }
1096
- class BasePlugin {
1097
- async install(context) {
1098
- this.context = context;
1099
- await this.onInstall();
1535
+ delete(key) {
1536
+ const entry = this.storage.get(key);
1537
+ if (entry) {
1538
+ if (this.onEvict) {
1539
+ this.onEvict(entry);
1540
+ }
1541
+ this.storage.delete(key);
1542
+ this.accessOrder = this.accessOrder.filter(k => k !== key);
1543
+ return true;
1544
+ }
1545
+ return false;
1100
1546
  }
1101
- async uninstall() {
1102
- await this.onUninstall();
1103
- this.context = undefined;
1547
+ clear() {
1548
+ if (this.onEvict) {
1549
+ this.storage.forEach(entry => this.onEvict(entry));
1550
+ }
1551
+ this.storage.clear();
1552
+ this.accessOrder = [];
1104
1553
  }
1105
- enable() {
1106
- this.onEnable();
1554
+ getSize() {
1555
+ return this.storage.size;
1107
1556
  }
1108
- disable() {
1109
- this.onDisable();
1557
+ getAllKeys() {
1558
+ return Array.from(this.storage.keys());
1110
1559
  }
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;
1560
+ getAllValues() {
1561
+ return Array.from(this.storage.values())
1562
+ .filter(entry => !this.isExpired(entry))
1563
+ .map(entry => entry.data);
1117
1564
  }
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');
1565
+ updateAccessOrder(key) {
1566
+ // Optimize: use splice instead of filter to avoid creating new array
1567
+ const index = this.accessOrder.indexOf(key);
1568
+ if (index > -1) {
1569
+ this.accessOrder.splice(index, 1);
1122
1570
  }
1123
- return this.context.events;
1571
+ this.accessOrder.push(key);
1124
1572
  }
1125
- get storage() {
1126
- var _a;
1127
- return (_a = this.context) === null || _a === void 0 ? void 0 : _a.storage;
1573
+ isExpired(entry) {
1574
+ if (!this.ttl)
1575
+ return false;
1576
+ return Date.now() - entry.timestamp > this.ttl;
1128
1577
  }
1129
- get config() {
1130
- var _a;
1131
- return (_a = this.context) === null || _a === void 0 ? void 0 : _a.config;
1578
+ removeExpired() {
1579
+ let removedCount = 0;
1580
+ const expiredKeys = [];
1581
+ this.storage.forEach((entry, key) => {
1582
+ if (this.isExpired(entry)) {
1583
+ expiredKeys.push(key);
1584
+ }
1585
+ });
1586
+ expiredKeys.forEach(key => {
1587
+ if (this.delete(key)) {
1588
+ removedCount++;
1589
+ }
1590
+ });
1591
+ return removedCount;
1132
1592
  }
1133
1593
  }
1134
1594
 
1135
- class DevInspector {
1595
+ /**
1596
+ * @deprecated The original, asynchronously initialised inspector. It is kept for
1597
+ * backwards compatibility; use the default export (`DevInspector`) instead.
1598
+ */
1599
+ let DevInspector$1 = class DevInspector {
1136
1600
  constructor(config = {}) {
1137
1601
  this.isVisible = false;
1138
1602
  this.isMinimized = false;
@@ -1140,6 +1604,8 @@
1140
1604
  this.ui = null;
1141
1605
  this.initialized = false;
1142
1606
  this.cleanupFunctions = [];
1607
+ this.initPromise = null;
1608
+ this.destroyed = false;
1143
1609
  if (DevInspector.instance) {
1144
1610
  console.warn('DevInspector instance already exists. Returning existing instance.');
1145
1611
  return DevInspector.instance;
@@ -1159,7 +1625,7 @@
1159
1625
  ttl: 60 * 60 * 1000 // 1 hour
1160
1626
  });
1161
1627
  this.errorStorage = new CircularStorage({
1162
- maxSize: 100,
1628
+ maxSize: this.config.maxErrorEntries,
1163
1629
  onEvict: (entry) => this.events.emit('error:evict', entry)
1164
1630
  });
1165
1631
  this.pluginSystem = new PluginSystem({
@@ -1174,14 +1640,13 @@
1174
1640
  config: this.config
1175
1641
  });
1176
1642
  if (this.config.enabled) {
1177
- this.init();
1643
+ void this.init();
1178
1644
  }
1179
1645
  DevInspector.instance = this;
1180
1646
  }
1181
1647
  mergeConfig(config) {
1182
- var _a;
1183
1648
  const defaultConfig = {
1184
- enabled: typeof process !== 'undefined' && ((_a = process.env) === null || _a === void 0 ? void 0 : _a.NODE_ENV) !== 'production',
1649
+ enabled: defaultEnabled(),
1185
1650
  position: 'bottom-right',
1186
1651
  theme: 'auto',
1187
1652
  hotkeys: {
@@ -1207,6 +1672,8 @@
1207
1672
  },
1208
1673
  onError: () => { },
1209
1674
  onPerformanceIssue: () => { },
1675
+ maxErrorEntries: 100,
1676
+ slowRequestThreshold: 3000,
1210
1677
  workerUrl: undefined,
1211
1678
  remoteConfig: null
1212
1679
  };
@@ -1218,21 +1685,38 @@
1218
1685
  networkFilters: { ...defaultConfig.networkFilters, ...config.networkFilters }
1219
1686
  };
1220
1687
  }
1221
- async init() {
1222
- if (this.initialized)
1688
+ init() {
1689
+ // Share one initialisation between the constructor and show(), so monitors
1690
+ // are never installed twice.
1691
+ if (!this.initPromise)
1692
+ this.initPromise = this.runInit();
1693
+ return this.initPromise;
1694
+ }
1695
+ async runInit() {
1696
+ var _a, _b;
1697
+ if (this.initialized || this.destroyed || !hasDom())
1223
1698
  return;
1224
1699
  try {
1225
1700
  await this.loadMonitors();
1701
+ if (this.destroyed)
1702
+ return this.teardown();
1226
1703
  await this.loadUI();
1704
+ if (this.destroyed)
1705
+ return this.teardown();
1227
1706
  await this.registerPlugins();
1707
+ if (this.destroyed)
1708
+ return this.teardown();
1228
1709
  this.setupHotkeys();
1229
1710
  this.setupErrorHandlers();
1230
1711
  this.initialized = true;
1231
1712
  this.events.emit('inspector:ready');
1232
1713
  }
1233
1714
  catch (error) {
1715
+ // Undo whatever was installed before the failure.
1716
+ this.teardown();
1717
+ this.initPromise = null;
1234
1718
  console.error('Failed to initialize DevInspector:', error);
1235
- this.config.onError(error);
1719
+ (_b = (_a = this.config).onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
1236
1720
  }
1237
1721
  }
1238
1722
  async loadMonitors() {
@@ -1354,8 +1838,18 @@
1354
1838
  }
1355
1839
  show() {
1356
1840
  var _a;
1841
+ if (this.destroyed)
1842
+ return;
1357
1843
  if (!this.initialized) {
1358
- this.init().then(() => this.show());
1844
+ this.init().then(() => {
1845
+ // Only retry show() once init has actually succeeded (no retry loop on failure).
1846
+ if (this.initialized && !this.destroyed)
1847
+ this.show();
1848
+ }).catch(err => {
1849
+ var _a, _b;
1850
+ console.error('Failed to show inspector:', err);
1851
+ (_b = (_a = this.config).onError) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1852
+ });
1359
1853
  return;
1360
1854
  }
1361
1855
  this.isVisible = true;
@@ -1383,14 +1877,27 @@
1383
1877
  this.show();
1384
1878
  }
1385
1879
  }
1386
- destroy() {
1880
+ teardown() {
1387
1881
  var _a;
1388
- this.monitors.forEach(monitor => { var _a; return (_a = monitor.stop) === null || _a === void 0 ? void 0 : _a.call(monitor); });
1882
+ this.monitors.forEach(monitor => {
1883
+ var _a;
1884
+ try {
1885
+ (_a = monitor.stop) === null || _a === void 0 ? void 0 : _a.call(monitor);
1886
+ }
1887
+ catch (error) {
1888
+ console.error('DevInspector: failed to stop a monitor', error);
1889
+ }
1890
+ });
1389
1891
  this.monitors.clear();
1390
1892
  (_a = this.ui) === null || _a === void 0 ? void 0 : _a.destroy();
1391
1893
  this.ui = null;
1392
1894
  this.cleanupFunctions.forEach(cleanup => cleanup());
1393
1895
  this.cleanupFunctions = [];
1896
+ }
1897
+ destroy() {
1898
+ // A destroy() during the asynchronous init is honoured once init resumes.
1899
+ this.destroyed = true;
1900
+ this.teardown();
1394
1901
  this.events.emit('inspector:destroy');
1395
1902
  this.events.removeAllListeners();
1396
1903
  DevInspector.instance = null;
@@ -1414,8 +1921,8 @@
1414
1921
  console.warn(`Failed to measure ${name}:`, error);
1415
1922
  }
1416
1923
  }
1417
- use(plugin) {
1418
- this.pluginSystem.register(plugin);
1924
+ async use(plugin) {
1925
+ await this.pluginSystem.register(plugin);
1419
1926
  }
1420
1927
  export() {
1421
1928
  return {
@@ -1463,21 +1970,31 @@
1463
1970
  static getInstance() {
1464
1971
  return DevInspector.instance;
1465
1972
  }
1466
- }
1467
- DevInspector.instance = null;
1973
+ };
1974
+ DevInspector$1.instance = null;
1468
1975
 
1976
+ /**
1977
+ * @deprecated A static demo panel that does not monitor anything. Use the
1978
+ * default export (`DevInspector`) instead.
1979
+ */
1469
1980
  class SimpleDevInspector {
1470
1981
  constructor(config = {}) {
1471
1982
  this.widget = null;
1472
1983
  this.panel = null;
1473
1984
  this.isVisible = false;
1985
+ this.onKeydown = (e) => {
1986
+ if (e.ctrlKey && e.shiftKey && (e.key === 'D' || e.key === 'd')) {
1987
+ e.preventDefault();
1988
+ this.toggle();
1989
+ }
1990
+ };
1474
1991
  this.config = {
1475
- enabled: true,
1992
+ enabled: defaultEnabled(),
1476
1993
  position: 'bottom-right',
1477
1994
  theme: 'dark',
1478
1995
  ...config
1479
1996
  };
1480
- if (this.config.enabled) {
1997
+ if (this.config.enabled && hasDom()) {
1481
1998
  this.init();
1482
1999
  }
1483
2000
  }
@@ -1513,7 +2030,7 @@
1513
2030
  document.body.appendChild(this.widget);
1514
2031
  }
1515
2032
  createPanel() {
1516
- var _a, _b;
2033
+ var _a, _b, _c;
1517
2034
  this.panel = document.createElement('div');
1518
2035
  const bgColor = this.config.theme === 'dark' ? '#1e1e1e' : '#ffffff';
1519
2036
  const textColor = this.config.theme === 'dark' ? '#cccccc' : '#333333';
@@ -1538,7 +2055,7 @@
1538
2055
  this.panel.innerHTML = `
1539
2056
  <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
2057
  <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>
2058
+ <button type="button" class="devinspector-close" style="background: #f44336; border: none; color: white; width: 20px; height: 20px; border-radius: 3px; cursor: pointer;">×</button>
1542
2059
  </div>
1543
2060
  <div style="display: flex; background: ${this.config.theme === 'dark' ? '#2d2d30' : '#f5f5f5'}; border-bottom: 1px solid ${borderColor};">
1544
2061
  <button style="padding: 8px 16px; background: #007acc; border: none; color: white; cursor: pointer;">Network</button>
@@ -1573,6 +2090,8 @@
1573
2090
  </div>
1574
2091
  `;
1575
2092
  this.panel.className = 'devinspector-panel';
2093
+ // No inline handlers, so the panel works under a Content Security Policy.
2094
+ (_c = this.panel.querySelector('.devinspector-close')) === null || _c === void 0 ? void 0 : _c.addEventListener('click', () => this.hide());
1576
2095
  document.body.appendChild(this.panel);
1577
2096
  }
1578
2097
  setupEventListeners() {
@@ -1580,12 +2099,7 @@
1580
2099
  this.widget.addEventListener('click', () => this.toggle());
1581
2100
  }
1582
2101
  // Keyboard shortcuts
1583
- document.addEventListener('keydown', (e) => {
1584
- if (e.ctrlKey && e.shiftKey && e.key === 'D') {
1585
- e.preventDefault();
1586
- this.toggle();
1587
- }
1588
- });
2102
+ document.addEventListener('keydown', this.onKeydown);
1589
2103
  }
1590
2104
  show() {
1591
2105
  if (this.panel) {
@@ -1600,9 +2114,14 @@
1600
2114
  }
1601
2115
  }
1602
2116
  toggle() {
1603
- this.isVisible ? this.hide() : this.show();
2117
+ if (this.isVisible)
2118
+ this.hide();
2119
+ else
2120
+ this.show();
1604
2121
  }
1605
2122
  destroy() {
2123
+ if (hasDom())
2124
+ document.removeEventListener('keydown', this.onKeydown);
1606
2125
  if (this.widget && this.widget.parentNode) {
1607
2126
  this.widget.parentNode.removeChild(this.widget);
1608
2127
  }
@@ -1629,11 +2148,35 @@
1629
2148
  }
1630
2149
 
1631
2150
  /**
1632
- * DevInspector - Professional Developer Debugging Tool
1633
- * @version 1.1.0
1634
- * @description Zero-dependency framework-agnostic debugging tool with beautiful modern UI
2151
+ * DevInspector - developer debugging panel for web applications.
2152
+ */
2153
+ // Default inspector
2154
+
2155
+ var api = /*#__PURE__*/Object.freeze({
2156
+ __proto__: null,
2157
+ BasePlugin: BasePlugin,
2158
+ CircularStorage: CircularStorage,
2159
+ DevInspector: EnhancedDevInspector,
2160
+ EnhancedDevInspector: EnhancedDevInspector,
2161
+ EventEmitter: EventEmitter,
2162
+ IndexedStorage: IndexedStorage,
2163
+ OriginalDevInspector: DevInspector$1,
2164
+ SimpleDevInspector: SimpleDevInspector,
2165
+ VERSION: VERSION,
2166
+ default: EnhancedDevInspector
2167
+ });
2168
+
2169
+ /**
2170
+ * Entry for the browser bundles (dist/devinspector.umd*.js). The global
2171
+ * `DevInspector` is the inspector class itself, so `new DevInspector()` works
2172
+ * from a script tag; every named export is also available as a static
2173
+ * property (e.g. `DevInspector.BasePlugin`).
1635
2174
  */
1636
- // Enhanced UI version (new default)
2175
+ const DevInspector = EnhancedDevInspector;
2176
+ for (const [key, value] of Object.entries(api)) {
2177
+ if (!(key in DevInspector))
2178
+ Object.defineProperty(DevInspector, key, { value, enumerable: true });
2179
+ }
1637
2180
 
1638
2181
  function throttle(func, wait, options = {}) {
1639
2182
  let timeout = null;
@@ -1678,7 +2221,7 @@
1678
2221
  };
1679
2222
  }
1680
2223
  function generateId() {
1681
- return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
2224
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
1682
2225
  }
1683
2226
  function safeStringify(obj, indent) {
1684
2227
  const seen = new WeakSet();
@@ -1703,7 +2246,7 @@
1703
2246
  }, indent);
1704
2247
  }
1705
2248
  function getStackTrace(error) {
1706
- const stack = (new Error()).stack || '';
2249
+ const stack = (error || new Error()).stack || '';
1707
2250
  return stack
1708
2251
  .split('\n')
1709
2252
  .slice(1)
@@ -1724,32 +2267,44 @@
1724
2267
  };
1725
2268
  }
1726
2269
 
2270
+ /** Largest request/response body preview kept per entry (bytes). */
2271
+ const MAX_BODY_PREVIEW = 64 * 1024;
1727
2272
  class FetchInterceptor {
1728
2273
  constructor(handlers = {}) {
1729
2274
  this.requestMap = new Map();
2275
+ this.installed = null;
1730
2276
  this.originalFetch = window.fetch;
1731
2277
  this.handlers = handlers;
1732
2278
  }
1733
2279
  install() {
1734
2280
  // eslint-disable-next-line @typescript-eslint/no-this-alias
1735
2281
  const self = this;
1736
- window.fetch = async function (input, init) {
1737
- var _a, _b, _c, _d, _e, _f;
2282
+ if (this.installed || typeof this.originalFetch !== 'function')
2283
+ return;
2284
+ const instrumented = async function (input, init) {
2285
+ var _a, _b, _c, _d;
1738
2286
  const id = generateId();
1739
2287
  const startTime = performance.now();
1740
2288
  let url;
1741
2289
  let method;
1742
2290
  let headers = {};
1743
2291
  let body;
1744
- if (input instanceof Request) {
2292
+ if (typeof Request !== 'undefined' && input instanceof Request) {
1745
2293
  url = input.url;
1746
2294
  method = input.method;
1747
2295
  input.headers.forEach((value, key) => {
1748
2296
  headers[key] = value;
1749
2297
  });
1750
- body = await self.extractBody(input);
2298
+ // Try to extract body, but handle cases where request is locked/used
2299
+ try {
2300
+ body = await self.extractBody(input);
2301
+ }
2302
+ catch (e) {
2303
+ body = '[Body unavailable - request already used]';
2304
+ }
1751
2305
  }
1752
2306
  else {
2307
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string -- a URL object here
1753
2308
  url = input.toString();
1754
2309
  method = (init === null || init === void 0 ? void 0 : init.method) || 'GET';
1755
2310
  if (init === null || init === void 0 ? void 0 : init.headers) {
@@ -1780,46 +2335,69 @@
1780
2335
  };
1781
2336
  self.requestMap.set(id, request);
1782
2337
  (_b = (_a = self.handlers).onRequest) === null || _b === void 0 ? void 0 : _b.call(_a, request);
2338
+ let response;
1783
2339
  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;
2340
+ response = await self.originalFetch.apply(this !== null && this !== void 0 ? this : window, [input, init]);
1807
2341
  }
1808
2342
  catch (error) {
1809
2343
  const networkError = {
1810
2344
  id,
1811
- message: error.message || 'Network request failed',
1812
- stack: error.stack,
2345
+ message: (error === null || error === void 0 ? void 0 : error.message) || 'Network request failed',
2346
+ stack: error === null || error === void 0 ? void 0 : error.stack,
1813
2347
  timestamp: Date.now()
1814
2348
  };
1815
- (_f = (_e = self.handlers).onError) === null || _f === void 0 ? void 0 : _f.call(_e, networkError);
2349
+ (_d = (_c = self.handlers).onError) === null || _d === void 0 ? void 0 : _d.call(_c, networkError);
1816
2350
  self.requestMap.delete(id);
1817
2351
  throw error;
1818
2352
  }
2353
+ // Hand the response to the caller right away. The body preview is read from
2354
+ // a clone in the background (capped), so streaming responses (SSE, long
2355
+ // polling, large downloads) are never held back by the inspector.
2356
+ const duration = performance.now() - startTime;
2357
+ void self.reportResponse(id, response, duration);
2358
+ return response;
1819
2359
  };
2360
+ this.installed = instrumented;
2361
+ window.fetch = instrumented;
2362
+ }
2363
+ async reportResponse(id, response, duration) {
2364
+ var _a, _b;
2365
+ try {
2366
+ const responseHeaders = {};
2367
+ response.headers.forEach((value, key) => {
2368
+ responseHeaders[key] = value;
2369
+ });
2370
+ let responseBody;
2371
+ try {
2372
+ responseBody = response.bodyUsed ? '[Body already read]' : await this.extractResponseBody(response.clone());
2373
+ }
2374
+ catch (_c) {
2375
+ responseBody = '[Unable to read response]';
2376
+ }
2377
+ (_b = (_a = this.handlers).onResponse) === null || _b === void 0 ? void 0 : _b.call(_a, {
2378
+ id,
2379
+ status: response.status,
2380
+ statusText: response.statusText,
2381
+ headers: responseHeaders,
2382
+ body: responseBody,
2383
+ size: this.calculateSize(responseBody, responseHeaders),
2384
+ duration,
2385
+ timestamp: Date.now(),
2386
+ fromCache: this.isFromCache(response, duration)
2387
+ });
2388
+ }
2389
+ catch (_d) {
2390
+ // A failing handler must not surface as an unhandled rejection in the page.
2391
+ }
2392
+ finally {
2393
+ this.requestMap.delete(id);
2394
+ }
1820
2395
  }
1821
2396
  uninstall() {
1822
- window.fetch = this.originalFetch;
2397
+ if (this.installed && window.fetch === this.installed) {
2398
+ window.fetch = this.originalFetch;
2399
+ }
2400
+ this.installed = null;
1823
2401
  this.requestMap.clear();
1824
2402
  }
1825
2403
  async extractBody(request) {
@@ -1830,13 +2408,13 @@
1830
2408
  }
1831
2409
  const cloned = request.clone();
1832
2410
  if (contentType.includes('application/json')) {
1833
- return await cloned.json();
2411
+ return await this.readPreview(cloned, true);
1834
2412
  }
1835
2413
  else if (contentType.includes('text/')) {
1836
- return await cloned.text();
2414
+ return await this.readPreview(cloned, false);
1837
2415
  }
1838
2416
  else if (contentType.includes('application/x-www-form-urlencoded')) {
1839
- return await cloned.text();
2417
+ return await this.readPreview(cloned, false);
1840
2418
  }
1841
2419
  else if (contentType.includes('multipart/form-data')) {
1842
2420
  return '[FormData]';
@@ -1847,14 +2425,59 @@
1847
2425
  return '[Unable to read body]';
1848
2426
  }
1849
2427
  }
2428
+ /** Reads at most MAX_BODY_PREVIEW bytes from a cloned body, then cancels the clone. */
2429
+ async readCapped(body) {
2430
+ const stream = body.body;
2431
+ if (!stream || typeof stream.getReader !== 'function') {
2432
+ const text = await body.text();
2433
+ return text.length > MAX_BODY_PREVIEW ? { text: text.slice(0, MAX_BODY_PREVIEW), truncated: true } : { text, truncated: false };
2434
+ }
2435
+ const reader = stream.getReader();
2436
+ const decoder = new TextDecoder();
2437
+ let text = '';
2438
+ let received = 0;
2439
+ try {
2440
+ for (;;) {
2441
+ const { done, value } = await reader.read();
2442
+ if (done)
2443
+ return { text: text + decoder.decode(), truncated: false };
2444
+ received += value.byteLength;
2445
+ text += decoder.decode(value, { stream: true });
2446
+ if (received >= MAX_BODY_PREVIEW)
2447
+ return { text: text.slice(0, MAX_BODY_PREVIEW), truncated: true };
2448
+ }
2449
+ }
2450
+ finally {
2451
+ reader.cancel().catch(() => undefined);
2452
+ }
2453
+ }
2454
+ async readPreview(body, asJson) {
2455
+ const { text, truncated } = await this.readCapped(body);
2456
+ if (truncated)
2457
+ return `${text}... [truncated]`;
2458
+ if (asJson) {
2459
+ try {
2460
+ return JSON.parse(text);
2461
+ }
2462
+ catch (_a) {
2463
+ return text;
2464
+ }
2465
+ }
2466
+ return text;
2467
+ }
1850
2468
  async extractResponseBody(response) {
2469
+ var _a, _b;
1851
2470
  try {
1852
2471
  const contentType = response.headers.get('content-type') || '';
2472
+ if (contentType.includes('text/event-stream')) {
2473
+ (_a = response.body) === null || _a === void 0 ? void 0 : _a.cancel().catch(() => undefined);
2474
+ return '[Event stream]';
2475
+ }
1853
2476
  if (contentType.includes('application/json')) {
1854
- return await response.json();
2477
+ return await this.readPreview(response, true);
1855
2478
  }
1856
2479
  else if (contentType.includes('text/')) {
1857
- return await response.text();
2480
+ return await this.readPreview(response, false);
1858
2481
  }
1859
2482
  else if (contentType.includes('image/')) {
1860
2483
  return '[Image data]';
@@ -1865,8 +2488,9 @@
1865
2488
  else if (contentType.includes('audio/')) {
1866
2489
  return '[Audio data]';
1867
2490
  }
1868
- const blob = await response.blob();
1869
- return `[Binary data: ${blob.size} bytes]`;
2491
+ const length = response.headers.get('content-length');
2492
+ (_b = response.body) === null || _b === void 0 ? void 0 : _b.cancel().catch(() => undefined);
2493
+ return length ? `[Binary data: ${length} bytes]` : '[Binary data]';
1870
2494
  }
1871
2495
  catch (error) {
1872
2496
  return '[Unable to read response]';
@@ -1933,12 +2557,15 @@
1933
2557
 
1934
2558
  class XHRInterceptor {
1935
2559
  constructor(handlers = {}) {
2560
+ this.installed = null;
1936
2561
  this.handlers = handlers;
1937
2562
  this.originalOpen = XMLHttpRequest.prototype.open;
1938
2563
  this.originalSend = XMLHttpRequest.prototype.send;
1939
2564
  this.originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
1940
2565
  }
1941
2566
  install() {
2567
+ if (this.installed || typeof XMLHttpRequest === 'undefined')
2568
+ return;
1942
2569
  // eslint-disable-next-line @typescript-eslint/no-this-alias
1943
2570
  const self = this;
1944
2571
  XMLHttpRequest.prototype.open = function (method, url, async = true, username, password) {
@@ -2044,11 +2671,24 @@
2044
2671
  });
2045
2672
  return self.originalSend.apply(this, [body]);
2046
2673
  };
2674
+ this.installed = {
2675
+ open: XMLHttpRequest.prototype.open,
2676
+ send: XMLHttpRequest.prototype.send,
2677
+ setRequestHeader: XMLHttpRequest.prototype.setRequestHeader
2678
+ };
2047
2679
  }
2048
2680
  uninstall() {
2049
- XMLHttpRequest.prototype.open = this.originalOpen;
2050
- XMLHttpRequest.prototype.send = this.originalSend;
2051
- XMLHttpRequest.prototype.setRequestHeader = this.originalSetRequestHeader;
2681
+ if (!this.installed)
2682
+ return;
2683
+ const proto = XMLHttpRequest.prototype;
2684
+ // Only restore methods that nobody has wrapped since we installed ours.
2685
+ if (proto.open === this.installed.open)
2686
+ proto.open = this.originalOpen;
2687
+ if (proto.send === this.installed.send)
2688
+ proto.send = this.originalSend;
2689
+ if (proto.setRequestHeader === this.installed.setRequestHeader)
2690
+ proto.setRequestHeader = this.originalSetRequestHeader;
2691
+ this.installed = null;
2052
2692
  }
2053
2693
  sanitizeBody(body) {
2054
2694
  if (!body)
@@ -2099,10 +2739,10 @@
2099
2739
  if (xhr.responseType === 'json' && xhr.response) {
2100
2740
  return xhr.response;
2101
2741
  }
2102
- if (xhr.responseType === 'arraybuffer') {
2742
+ if (xhr.responseType === 'arraybuffer' && xhr.response) {
2103
2743
  return `[ArrayBuffer: ${xhr.response.byteLength} bytes]`;
2104
2744
  }
2105
- if (xhr.responseType === 'blob') {
2745
+ if (xhr.responseType === 'blob' && xhr.response) {
2106
2746
  return `[Blob: ${xhr.response.size} bytes, type: ${xhr.response.type}]`;
2107
2747
  }
2108
2748
  if (xhr.responseType === 'document') {
@@ -2150,6 +2790,7 @@
2150
2790
  class WebSocketMonitor {
2151
2791
  constructor(handlers = {}) {
2152
2792
  this.connections = new Map();
2793
+ this.installed = null;
2153
2794
  this.originalWebSocket = window.WebSocket;
2154
2795
  this.handlers = handlers;
2155
2796
  }
@@ -2157,7 +2798,9 @@
2157
2798
  // eslint-disable-next-line @typescript-eslint/no-this-alias
2158
2799
  const self = this;
2159
2800
  const OriginalWebSocket = this.originalWebSocket;
2160
- window.WebSocket = function (url, protocols) {
2801
+ if (typeof OriginalWebSocket !== 'function' || this.installed)
2802
+ return;
2803
+ const MonitoredWebSocket = function (url, protocols) {
2161
2804
  var _a, _b;
2162
2805
  const ws = new OriginalWebSocket(url, protocols);
2163
2806
  const connectionId = generateId();
@@ -2259,17 +2902,19 @@
2259
2902
  };
2260
2903
  return ws;
2261
2904
  };
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;
2905
+ // Inherit statics (CONNECTING, OPEN, ...) and share the prototype so that
2906
+ // `ws instanceof WebSocket` keeps working. The constants are read-only on the
2907
+ // native constructor, so they must not be assigned (that throws in strict mode).
2908
+ Object.setPrototypeOf(MonitoredWebSocket, OriginalWebSocket);
2909
+ MonitoredWebSocket.prototype = OriginalWebSocket.prototype;
2910
+ this.installed = MonitoredWebSocket;
2911
+ window.WebSocket = MonitoredWebSocket;
2270
2912
  }
2271
2913
  uninstall() {
2272
- window.WebSocket = this.originalWebSocket;
2914
+ if (this.installed && window.WebSocket === this.installed) {
2915
+ window.WebSocket = this.originalWebSocket;
2916
+ }
2917
+ this.installed = null;
2273
2918
  this.connections.clear();
2274
2919
  }
2275
2920
  parseMessageData(data) {
@@ -2317,8 +2962,12 @@
2317
2962
  }
2318
2963
  }
2319
2964
 
2965
+ /** Messages (and errors) remembered per WebSocket connection. */
2966
+ const MAX_WEBSOCKET_MESSAGES = 500;
2320
2967
  class NetworkMonitor {
2321
2968
  constructor(inspector) {
2969
+ this.beaconInterceptor = null;
2970
+ this.beaconOriginal = null;
2322
2971
  this.entries = new Map();
2323
2972
  this.isActive = false;
2324
2973
  this.inspector = inspector;
@@ -2365,7 +3014,7 @@
2365
3014
  request,
2366
3015
  timestamp: request.timestamp
2367
3016
  };
2368
- this.entries.set(request.id, entry);
3017
+ this.track(request.id, entry);
2369
3018
  const storage = this.inspector.getStorage('network');
2370
3019
  storage.push(entry);
2371
3020
  this.inspector.getEvents().emit('network:request', {
@@ -2382,8 +3031,7 @@
2382
3031
  entry.duration = response.duration;
2383
3032
  entry.status = response.status;
2384
3033
  entry.size = response.size;
2385
- const storage = this.inspector.getStorage('network');
2386
- storage.push(entry);
3034
+ // The entry object is already in storage (pushed on request); it is updated in place.
2387
3035
  this.inspector.getEvents().emit('network:response', response);
2388
3036
  // Check for performance issues
2389
3037
  if (response.duration > 3000) {
@@ -2400,8 +3048,6 @@
2400
3048
  if (!entry)
2401
3049
  return;
2402
3050
  entry.error = error;
2403
- const storage = this.inspector.getStorage('network');
2404
- storage.push(entry);
2405
3051
  this.inspector.getEvents().emit('network:error', error);
2406
3052
  }
2407
3053
  handleProgress(progress) {
@@ -2418,7 +3064,7 @@
2418
3064
  },
2419
3065
  timestamp: connection.timestamp
2420
3066
  };
2421
- this.entries.set(connection.id, entry);
3067
+ this.track(connection.id, entry);
2422
3068
  const storage = this.inspector.getStorage('network');
2423
3069
  storage.push(entry);
2424
3070
  this.inspector.getEvents().emit('network:websocket:connection', connection);
@@ -2428,6 +3074,8 @@
2428
3074
  if (!entry || !entry.websocket)
2429
3075
  return;
2430
3076
  entry.websocket.messages.push(message);
3077
+ if (entry.websocket.messages.length > MAX_WEBSOCKET_MESSAGES)
3078
+ entry.websocket.messages.shift();
2431
3079
  this.inspector.getEvents().emit('network:websocket:message', message);
2432
3080
  }
2433
3081
  handleWebSocketStatusChange(status) {
@@ -2443,15 +3091,26 @@
2443
3091
  if (!entry || !entry.websocket)
2444
3092
  return;
2445
3093
  entry.websocket.errors.push(error);
3094
+ if (entry.websocket.errors.length > MAX_WEBSOCKET_MESSAGES)
3095
+ entry.websocket.errors.shift();
2446
3096
  this.inspector.getEvents().emit('network:websocket:error', error);
2447
3097
  }
3098
+ /** Remembers an in-flight entry; the map is bounded like the network storage. */
3099
+ track(id, entry) {
3100
+ this.entries.set(id, entry);
3101
+ const max = Math.max(1, this.inspector.getConfig().maxNetworkEntries);
3102
+ while (this.entries.size > max) {
3103
+ const oldest = this.entries.keys().next().value;
3104
+ this.entries.delete(oldest);
3105
+ }
3106
+ }
2448
3107
  installBeaconInterceptor() {
2449
- if (!navigator.sendBeacon)
3108
+ if (typeof navigator === 'undefined' || typeof navigator.sendBeacon !== 'function')
2450
3109
  return;
2451
3110
  const originalSendBeacon = navigator.sendBeacon.bind(navigator);
2452
3111
  // eslint-disable-next-line @typescript-eslint/no-this-alias
2453
3112
  const self = this;
2454
- navigator.sendBeacon = function (url, data) {
3113
+ const instrumented = function (url, data) {
2455
3114
  const id = self.generateId();
2456
3115
  const request = {
2457
3116
  id,
@@ -2479,12 +3138,16 @@
2479
3138
  }, 0);
2480
3139
  return result;
2481
3140
  };
2482
- this.beaconInterceptor = originalSendBeacon;
3141
+ this.beaconOriginal = navigator.sendBeacon;
3142
+ this.beaconInterceptor = instrumented;
3143
+ navigator.sendBeacon = instrumented;
2483
3144
  }
2484
3145
  uninstallBeaconInterceptor() {
2485
- if (this.beaconInterceptor && navigator.sendBeacon) {
2486
- navigator.sendBeacon = this.beaconInterceptor;
3146
+ if (this.beaconInterceptor && navigator.sendBeacon === this.beaconInterceptor) {
3147
+ navigator.sendBeacon = this.beaconOriginal;
2487
3148
  }
3149
+ this.beaconInterceptor = null;
3150
+ this.beaconOriginal = null;
2488
3151
  }
2489
3152
  sanitizeBeaconData(data) {
2490
3153
  if (!data)
@@ -2510,7 +3173,7 @@
2510
3173
  return data;
2511
3174
  }
2512
3175
  generateId() {
2513
- return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
3176
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
2514
3177
  }
2515
3178
  getEntries() {
2516
3179
  return Array.from(this.entries.values());
@@ -2537,6 +3200,8 @@
2537
3200
  this.groupLevel = 0;
2538
3201
  this.counters = new Map();
2539
3202
  this.timers = new Map();
3203
+ this.wrappers = new Map();
3204
+ this.handling = false;
2540
3205
  this.handlers = handlers;
2541
3206
  this.captureStackTraces = captureStackTraces;
2542
3207
  }
@@ -2547,16 +3212,24 @@
2547
3212
  'count', 'countReset', 'time', 'timeEnd', 'timeLog',
2548
3213
  'assert', 'dir', 'dirxml', 'profile', 'profileEnd'
2549
3214
  ];
3215
+ if (this.originalMethods.size > 0)
3216
+ return;
2550
3217
  methods.forEach(method => {
3218
+ if (typeof console[method] !== 'function')
3219
+ return;
2551
3220
  this.originalMethods.set(method, console[method]);
2552
3221
  this.interceptMethod(method);
2553
3222
  });
2554
3223
  }
2555
3224
  uninstall() {
2556
3225
  this.originalMethods.forEach((original, method) => {
2557
- console[method] = original;
3226
+ // Leave methods alone that someone else has wrapped since; ours pass through once uninstalled.
3227
+ if (console[method] === this.wrappers.get(method)) {
3228
+ console[method] = original;
3229
+ }
2558
3230
  });
2559
3231
  this.originalMethods.clear();
3232
+ this.wrappers.clear();
2560
3233
  this.counters.clear();
2561
3234
  this.timers.clear();
2562
3235
  this.groupLevel = 0;
@@ -2565,60 +3238,78 @@
2565
3238
  // eslint-disable-next-line @typescript-eslint/no-this-alias
2566
3239
  const self = this;
2567
3240
  const original = this.originalMethods.get(method);
2568
- console[method] = function (...args) {
2569
- var _a, _b, _c, _d;
3241
+ const wrapper = function (...args) {
2570
3242
  // 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;
3243
+ const result = original.apply(console, args);
3244
+ // Uninstalled (but still wrapped by someone else), or logging from inside one
3245
+ // of our own handlers: pass through without capturing, which also prevents
3246
+ // infinite recursion when a 'console:log' listener logs.
3247
+ if (self.handling || !self.wrappers.has(method))
3248
+ return result;
3249
+ self.handling = true;
3250
+ try {
3251
+ self.capture(method, args);
2604
3252
  }
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]);
3253
+ finally {
3254
+ self.handling = false;
2619
3255
  }
2620
- (_d = (_c = self.handlers).onLog) === null || _d === void 0 ? void 0 : _d.call(_c, entry);
3256
+ return result;
3257
+ };
3258
+ this.wrappers.set(method, wrapper);
3259
+ console[method] = wrapper;
3260
+ }
3261
+ capture(method, args) {
3262
+ var _a, _b, _c, _d;
3263
+ // Handle special methods
3264
+ switch (method) {
3265
+ case 'clear':
3266
+ (_b = (_a = this.handlers).onClear) === null || _b === void 0 ? void 0 : _b.call(_a);
3267
+ return;
3268
+ case 'group':
3269
+ case 'groupCollapsed':
3270
+ this.groupLevel++;
3271
+ break;
3272
+ case 'groupEnd':
3273
+ this.groupLevel = Math.max(0, this.groupLevel - 1);
3274
+ break;
3275
+ case 'count':
3276
+ this.handleCount(args[0]);
3277
+ return;
3278
+ case 'countReset':
3279
+ this.counters.delete(args[0] || 'default');
3280
+ return;
3281
+ case 'time':
3282
+ this.timers.set(args[0] || 'default', performance.now());
3283
+ return;
3284
+ case 'timeEnd':
3285
+ this.handleTimeEnd(args[0], 'timeEnd');
3286
+ return;
3287
+ case 'timeLog':
3288
+ this.handleTimeEnd(args[0], 'timeLog');
3289
+ break;
3290
+ case 'assert':
3291
+ if (args[0])
3292
+ return; // Don't log if assertion passes
3293
+ args = args.slice(1); // Remove condition
3294
+ break;
3295
+ }
3296
+ // Create log entry
3297
+ const entry = {
3298
+ id: generateId(),
3299
+ level: method,
3300
+ args: args,
3301
+ formattedArgs: this.formatArgs(args),
3302
+ timestamp: Date.now(),
3303
+ groupLevel: this.groupLevel
2621
3304
  };
3305
+ // Capture stack trace if enabled
3306
+ if (this.captureStackTraces && (method === 'error' || method === 'warn' || method === 'trace')) {
3307
+ // Drop the getStackTrace, capture and console wrapper frames so the first frame is the caller.
3308
+ const stack = getStackTrace().slice(3);
3309
+ entry.stack = stack;
3310
+ entry.source = this.extractSourceFromStack(stack[0]);
3311
+ }
3312
+ (_d = (_c = this.handlers).onLog) === null || _d === void 0 ? void 0 : _d.call(_c, entry);
2622
3313
  }
2623
3314
  handleCount(label) {
2624
3315
  var _a, _b;
@@ -2969,10 +3660,10 @@
2969
3660
  setupCommandExecution() {
2970
3661
  // This would be called by the UI to execute commands
2971
3662
  this.inspector.on('console:execute', (command) => {
2972
- this.executeCommand(command);
3663
+ void this.executeCommand(command);
2973
3664
  });
2974
3665
  }
2975
- executeCommand(command) {
3666
+ async executeCommand(command) {
2976
3667
  var _a;
2977
3668
  // Add to history
2978
3669
  this.commandHistory.push(command);
@@ -2989,8 +3680,12 @@
2989
3680
  this.handleLog(commandEntry);
2990
3681
  // Execute the command
2991
3682
  try {
2992
- // Create a function to evaluate the command in global scope
2993
- const result = (0, eval)(command);
3683
+ // SECURITY WARNING: Executing arbitrary code. This should only be used in development.
3684
+ // Use Function constructor instead of eval for better security and scope control
3685
+ // Note: This still allows code execution - ensure this feature is properly controlled
3686
+ const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor;
3687
+ const executionFn = new AsyncFunction('return (' + command + ')');
3688
+ const result = await executionFn.call(window);
2994
3689
  if (result !== undefined) {
2995
3690
  const resultEntry = {
2996
3691
  id: `result-${Date.now()}`,
@@ -3026,7 +3721,7 @@
3026
3721
  this.historyIndex = Math.max(0, this.historyIndex - 1);
3027
3722
  }
3028
3723
  else {
3029
- this.historyIndex = Math.min(this.commandHistory.length - 1, this.historyIndex + 1);
3724
+ this.historyIndex = Math.min(this.commandHistory.length, this.historyIndex + 1);
3030
3725
  }
3031
3726
  return this.commandHistory[this.historyIndex];
3032
3727
  }
@@ -3387,6 +4082,7 @@
3387
4082
  constructor(callback, threshold = 50) {
3388
4083
  this.observer = null;
3389
4084
  this.idCounter = 0;
4085
+ this.fallbackRunning = false;
3390
4086
  this.callback = callback;
3391
4087
  this.threshold = threshold;
3392
4088
  }
@@ -3412,6 +4108,7 @@
3412
4108
  var _a;
3413
4109
  (_a = this.observer) === null || _a === void 0 ? void 0 : _a.disconnect();
3414
4110
  this.observer = null;
4111
+ this.fallbackRunning = false;
3415
4112
  }
3416
4113
  handleLongTask(entry) {
3417
4114
  const longTaskEntry = entry; // PerformanceLongTaskTiming
@@ -3433,6 +4130,7 @@
3433
4130
  }
3434
4131
  fallbackDetection() {
3435
4132
  // Fallback detection using requestAnimationFrame
4133
+ this.fallbackRunning = true;
3436
4134
  let lastTime = performance.now();
3437
4135
  const check = () => {
3438
4136
  const currentTime = performance.now();
@@ -3451,7 +4149,7 @@
3451
4149
  this.callback(task);
3452
4150
  }
3453
4151
  lastTime = currentTime;
3454
- if (this.observer === null) {
4152
+ if (this.fallbackRunning) {
3455
4153
  requestAnimationFrame(check);
3456
4154
  }
3457
4155
  };
@@ -3717,7 +4415,7 @@
3717
4415
  lineno = error.lineno;
3718
4416
  colno = error.colno;
3719
4417
  if (error.error) {
3720
- stack = error.error.stack ? error.error.stack.split('\n').map(line => line.trim()) : [];
4418
+ stack = error.error.stack ? error.error.stack.split('\n').map((line) => line.trim()) : [];
3721
4419
  errorObject = error.error;
3722
4420
  }
3723
4421
  }
@@ -4036,6 +4734,7 @@
4036
4734
  this.errorTracker.trackError(event, 'unhandledRejection');
4037
4735
  };
4038
4736
  this.inspector = inspector;
4737
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises -- 1.x behaviour: the tracker does not await the handler
4039
4738
  this.errorTracker = new ErrorTracker(this.handleError.bind(this));
4040
4739
  this.sourceMapSupport = new SourceMapSupport();
4041
4740
  }
@@ -4058,6 +4757,7 @@
4058
4757
  // Install error handler
4059
4758
  window.onerror = (message, source, lineno, colno, error) => {
4060
4759
  const errorEvent = new ErrorEvent('error', {
4760
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string -- onerror passes a string or an Event
4061
4761
  message: String(message),
4062
4762
  filename: source,
4063
4763
  lineno,
@@ -4220,8 +4920,12 @@
4220
4920
  this.isDragging = false;
4221
4921
  this.dragOffset = { x: 0, y: 0 };
4222
4922
  this.errorCount = 0;
4923
+ this.eventUnsubscribers = [];
4223
4924
  this.inspector = inspector;
4224
4925
  this.element = this.createElement();
4926
+ // Bind event handlers for proper cleanup later
4927
+ this.boundMouseMove = this.handleMouseMove.bind(this);
4928
+ this.boundMouseUp = this.handleMouseUp.bind(this);
4225
4929
  this.setupEventListeners();
4226
4930
  this.updatePosition();
4227
4931
  }
@@ -4242,22 +4946,25 @@
4242
4946
  });
4243
4947
  // Drag functionality
4244
4948
  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', () => {
4949
+ document.addEventListener('mousemove', this.boundMouseMove);
4950
+ document.addEventListener('mouseup', this.boundMouseUp);
4951
+ // Error tracking - store unsubscribe functions for cleanup
4952
+ const unsubErrorCaught = this.inspector.on('error:caught', () => {
4249
4953
  this.errorCount++;
4250
4954
  this.updateAppearance();
4251
4955
  });
4252
- this.inspector.on('error:uncaught', () => {
4956
+ this.eventUnsubscribers.push(unsubErrorCaught);
4957
+ const unsubErrorUncaught = this.inspector.on('error:uncaught', () => {
4253
4958
  this.errorCount++;
4254
4959
  this.updateAppearance();
4255
4960
  });
4961
+ this.eventUnsubscribers.push(unsubErrorUncaught);
4256
4962
  // Clear error count when inspector is opened
4257
- this.inspector.on('inspector:show', () => {
4963
+ const unsubInspectorShow = this.inspector.on('inspector:show', () => {
4258
4964
  this.errorCount = 0;
4259
4965
  this.updateAppearance();
4260
4966
  });
4967
+ this.eventUnsubscribers.push(unsubInspectorShow);
4261
4968
  }
4262
4969
  handleMouseDown(e) {
4263
4970
  e.preventDefault();
@@ -4308,7 +5015,9 @@
4308
5015
  top: centerY,
4309
5016
  bottom: windowHeight - centerY
4310
5017
  };
4311
- const closestEdge = Object.keys(distances).reduce((a, b) => distances[a] < distances[b] ? a : b);
5018
+ // Find closest edge using type-safe approach
5019
+ const closestEdge = Object.entries(distances)
5020
+ .reduce((a, b) => a[1] < b[1] ? a : b)[0];
4312
5021
  // Animate to edge
4313
5022
  const margin = 20;
4314
5023
  switch (closestEdge) {
@@ -4378,6 +5087,12 @@
4378
5087
  this.element.style.display = 'none';
4379
5088
  }
4380
5089
  destroy() {
5090
+ // Remove document event listeners to prevent memory leaks
5091
+ document.removeEventListener('mousemove', this.boundMouseMove);
5092
+ document.removeEventListener('mouseup', this.boundMouseUp);
5093
+ // Unsubscribe from all inspector events
5094
+ this.eventUnsubscribers.forEach(unsubscribe => unsubscribe());
5095
+ this.eventUnsubscribers = [];
4381
5096
  if (this.element.parentNode) {
4382
5097
  this.element.parentNode.removeChild(this.element);
4383
5098
  }
@@ -4394,6 +5109,9 @@
4394
5109
  this.isDragging = false;
4395
5110
  this.dragOffset = { x: 0, y: 0 };
4396
5111
  this.isResizing = false;
5112
+ this.badgeUpdateInterval = null;
5113
+ this.boundMouseMove = (event) => this.handleMouseMove(event);
5114
+ this.boundMouseUp = () => this.handleMouseUp();
4397
5115
  this.inspector = inspector;
4398
5116
  this.element = this.createElement();
4399
5117
  this.setupEventListeners();
@@ -4451,8 +5169,8 @@
4451
5169
  });
4452
5170
  // Header dragging
4453
5171
  this.headerElement.addEventListener('mousedown', this.handleHeaderMouseDown.bind(this));
4454
- document.addEventListener('mousemove', this.handleMouseMove.bind(this));
4455
- document.addEventListener('mouseup', this.handleMouseUp.bind(this));
5172
+ document.addEventListener('mousemove', this.boundMouseMove);
5173
+ document.addEventListener('mouseup', this.boundMouseUp);
4456
5174
  // Resizing
4457
5175
  const resizer = this.element.querySelector('.devinspector-resizer');
4458
5176
  resizer.addEventListener('mousedown', this.handleResizerMouseDown.bind(this));
@@ -4467,7 +5185,7 @@
4467
5185
  }
4468
5186
  });
4469
5187
  // Update badge counts periodically
4470
- setInterval(() => this.updateBadges(), 1000);
5188
+ this.badgeUpdateInterval = window.setInterval(() => this.updateBadges(), 1000);
4471
5189
  }
4472
5190
  handleHeaderMouseDown(e) {
4473
5191
  if (e.target.closest('.devinspector-control'))
@@ -4550,10 +5268,13 @@
4550
5268
  const tab = document.createElement('button');
4551
5269
  tab.className = 'devinspector-tab';
4552
5270
  tab.dataset.tabId = config.id;
4553
- tab.innerHTML = `
4554
- ${config.label}
4555
- ${config.badge ? '<span class="devinspector-tab-badge">0</span>' : ''}
4556
- `;
5271
+ tab.textContent = config.label;
5272
+ if (config.badge) {
5273
+ const badge = document.createElement('span');
5274
+ badge.className = 'devinspector-tab-badge';
5275
+ badge.textContent = '0';
5276
+ tab.appendChild(badge);
5277
+ }
4557
5278
  this.tabsElement.appendChild(tab);
4558
5279
  // Create panel element
4559
5280
  const panel = document.createElement('div');
@@ -4572,12 +5293,12 @@
4572
5293
  return;
4573
5294
  this.tabs.delete(tabId);
4574
5295
  // Remove tab element
4575
- const tab = this.tabsElement.querySelector(`[data-tab-id="${tabId}"]`);
5296
+ const tab = Array.from(this.tabsElement.querySelectorAll('.devinspector-tab')).find(el => el.dataset.tabId === tabId);
4576
5297
  if (tab) {
4577
5298
  tab.remove();
4578
5299
  }
4579
5300
  // Remove panel element
4580
- const panel = this.bodyElement.querySelector(`[data-panel-id="${tabId}"]`);
5301
+ const panel = Array.from(this.bodyElement.querySelectorAll('.devinspector-panel')).find(el => el.dataset.panelId === tabId);
4581
5302
  if (panel) {
4582
5303
  panel.remove();
4583
5304
  }
@@ -4611,7 +5332,7 @@
4611
5332
  this.tabs.forEach((config, tabId) => {
4612
5333
  if (config.badge) {
4613
5334
  const count = config.badge();
4614
- const tab = this.tabsElement.querySelector(`[data-tab-id="${tabId}"]`);
5335
+ const tab = Array.from(this.tabsElement.querySelectorAll('.devinspector-tab')).find(el => el.dataset.tabId === tabId);
4615
5336
  const badge = tab === null || tab === void 0 ? void 0 : tab.querySelector('.devinspector-tab-badge');
4616
5337
  if (badge) {
4617
5338
  badge.textContent = count.toString();
@@ -4634,6 +5355,13 @@
4634
5355
  this.element.classList.add('minimized');
4635
5356
  }
4636
5357
  destroy() {
5358
+ // Clear badge update interval to prevent memory leak
5359
+ if (this.badgeUpdateInterval !== null) {
5360
+ clearInterval(this.badgeUpdateInterval);
5361
+ this.badgeUpdateInterval = null;
5362
+ }
5363
+ document.removeEventListener('mousemove', this.boundMouseMove);
5364
+ document.removeEventListener('mouseup', this.boundMouseUp);
4637
5365
  if (this.element.parentNode) {
4638
5366
  this.element.parentNode.removeChild(this.element);
4639
5367
  }
@@ -5206,6 +5934,7 @@
5206
5934
  this.floatingWidget = new FloatingWidget(inspector);
5207
5935
  this.mainPanel = new MainPanel(inspector);
5208
5936
  }
5937
+ // eslint-disable-next-line @typescript-eslint/require-await -- async by contract: callers await init()
5209
5938
  async init() {
5210
5939
  this.injectStyles();
5211
5940
  this.setupTabs();
@@ -5215,9 +5944,8 @@
5215
5944
  injectStyles() {
5216
5945
  this.styleElement = document.createElement('style');
5217
5946
  const theme = this.inspector.getConfig().theme;
5218
- const resolvedTheme = theme === 'auto' ?
5219
- (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') :
5220
- theme;
5947
+ const prefersDark = typeof window.matchMedia === 'function' && window.matchMedia('(prefers-color-scheme: dark)').matches;
5948
+ const resolvedTheme = theme === 'auto' ? (prefersDark ? 'dark' : 'light') : theme;
5221
5949
  this.styleElement.textContent = createStyles(resolvedTheme);
5222
5950
  document.head.appendChild(this.styleElement);
5223
5951
  }
@@ -5376,7 +6104,7 @@
5376
6104
  entry.dataset.requestId = request.id;
5377
6105
  entry.innerHTML = `
5378
6106
  <div style="display: flex; justify-content: space-between; align-items: center;">
5379
- <span>${request.method} ${request.url}</span>
6107
+ <span>${escapeHtml(request.method)} ${escapeHtml(request.url)}</span>
5380
6108
  <span class="devinspector-status info">Pending</span>
5381
6109
  </div>
5382
6110
  <div class="devinspector-timestamp">${new Date(request.timestamp).toLocaleTimeString()}</div>
@@ -5384,7 +6112,7 @@
5384
6112
  list.appendChild(entry);
5385
6113
  }
5386
6114
  updateNetworkEntry(panel, response) {
5387
- const entry = panel.querySelector(`[data-request-id="${response.id}"]`);
6115
+ const entry = Array.from(panel.querySelectorAll('[data-request-id]')).find(el => el.dataset.requestId === String(response.id));
5388
6116
  if (!entry)
5389
6117
  return;
5390
6118
  const status = entry.querySelector('.devinspector-status');
@@ -5403,10 +6131,10 @@
5403
6131
  placeholder.remove();
5404
6132
  }
5405
6133
  const consoleEntry = document.createElement('div');
5406
- consoleEntry.className = `devinspector-console-entry ${entry.level}`;
6134
+ consoleEntry.className = `devinspector-console-entry ${String(entry.level).replace(/[^a-zA-Z]/g, '')}`;
5407
6135
  consoleEntry.innerHTML = `
5408
- <span class="devinspector-console-level">${entry.level}</span>
5409
- <span class="devinspector-console-content">${this.formatConsoleArgs(entry.formattedArgs)}</span>
6136
+ <span class="devinspector-console-level">${escapeHtml(entry.level)}</span>
6137
+ <span class="devinspector-console-content">${escapeHtml(this.formatConsoleArgs(entry.formattedArgs))}</span>
5410
6138
  <span class="devinspector-timestamp">${new Date(entry.timestamp).toLocaleTimeString()}</span>
5411
6139
  `;
5412
6140
  list.appendChild(consoleEntry);
@@ -5424,9 +6152,9 @@
5424
6152
  const errorEntry = document.createElement('div');
5425
6153
  errorEntry.className = 'devinspector-error-group';
5426
6154
  errorEntry.innerHTML = `
5427
- <div class="devinspector-error-message">${error.message}</div>
6155
+ <div class="devinspector-error-message">${escapeHtml(error.message)}</div>
5428
6156
  <div class="devinspector-timestamp">${new Date(error.timestamp).toLocaleTimeString()}</div>
5429
- ${error.stack ? `<pre class="devinspector-error-stack">${error.stack.join('\n')}</pre>` : ''}
6157
+ ${error.stack ? `<pre class="devinspector-error-stack">${escapeHtml(Array.isArray(error.stack) ? error.stack.join('\n') : error.stack)}</pre>` : ''}
5430
6158
  `;
5431
6159
  list.appendChild(errorEntry);
5432
6160
  }
@@ -5484,17 +6212,7 @@
5484
6212
  DevInspectorUI: DevInspectorUI
5485
6213
  });
5486
6214
 
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 });
6215
+ return DevInspector;
5498
6216
 
5499
6217
  }));
5500
6218
  //# sourceMappingURL=devinspector.umd.js.map