@oxog/devinspector 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/LICENSE +0 -0
  3. package/README.md +85 -28
  4. package/dist/chunk-LNBLBFDA.js +92 -0
  5. package/dist/chunk-LNBLBFDA.js.map +1 -0
  6. package/dist/chunk-PPIEWSZ7.js +32 -0
  7. package/dist/chunk-PPIEWSZ7.js.map +1 -0
  8. package/dist/console-monitor-LBNXAQQ4.js +571 -0
  9. package/dist/console-monitor-LBNXAQQ4.js.map +1 -0
  10. package/dist/devinspector.umd.js +1782 -1074
  11. package/dist/devinspector.umd.js.map +1 -1
  12. package/dist/devinspector.umd.min.js +6 -1
  13. package/dist/devinspector.umd.min.js.map +1 -1
  14. package/dist/dom-monitor-IGQZTXMH.js +19 -0
  15. package/dist/dom-monitor-IGQZTXMH.js.map +1 -0
  16. package/dist/error-monitor-XDNRO4KS.js +423 -0
  17. package/dist/error-monitor-XDNRO4KS.js.map +1 -0
  18. package/dist/index.cjs +5918 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.cts +582 -0
  21. package/dist/index.d.ts +582 -0
  22. package/dist/index.js +1983 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/inspector-ui-AFTUEVWA.js +1240 -0
  25. package/dist/inspector-ui-AFTUEVWA.js.map +1 -0
  26. package/dist/network-monitor-HUSRKEXE.js +841 -0
  27. package/dist/network-monitor-HUSRKEXE.js.map +1 -0
  28. package/dist/performance-monitor-66DQJGOJ.js +544 -0
  29. package/dist/performance-monitor-66DQJGOJ.js.map +1 -0
  30. package/dist/state-monitor-PS5Q7NWY.js +19 -0
  31. package/dist/state-monitor-PS5Q7NWY.js.map +1 -0
  32. package/dist/storage-monitor-QW634CEJ.js +19 -0
  33. package/dist/storage-monitor-QW634CEJ.js.map +1 -0
  34. package/package.json +51 -38
  35. package/dist/devinspector.cjs.js +0 -5494
  36. package/dist/devinspector.cjs.js.map +0 -1
  37. package/dist/devinspector.esm.js +0 -5482
  38. package/dist/devinspector.esm.js.map +0 -1
  39. package/dist/types/clean-inspector.d.ts +0 -52
  40. package/dist/types/core/event-emitter.d.ts +0 -21
  41. package/dist/types/core/inspector.d.ts +0 -121
  42. package/dist/types/core/plugin-system.d.ts +0 -60
  43. package/dist/types/core/storage.d.ts +0 -52
  44. package/dist/types/core/utils.d.ts +0 -34
  45. package/dist/types/enhanced-inspector.d.ts +0 -56
  46. package/dist/types/enhanced-simple.d.ts +0 -46
  47. package/dist/types/index-simple.d.ts +0 -11
  48. package/dist/types/index.d.ts +0 -19
  49. package/dist/types/monitors/console/console-interceptor.d.ts +0 -36
  50. package/dist/types/monitors/console/console-monitor.d.ts +0 -26
  51. package/dist/types/monitors/console/log-formatter.d.ts +0 -8
  52. package/dist/types/monitors/dom/dom-monitor.d.ts +0 -8
  53. package/dist/types/monitors/error/error-monitor.d.ts +0 -28
  54. package/dist/types/monitors/error/error-tracker.d.ts +0 -55
  55. package/dist/types/monitors/error/source-map-support.d.ts +0 -15
  56. package/dist/types/monitors/network/fetch-interceptor.d.ts +0 -45
  57. package/dist/types/monitors/network/network-monitor.d.ts +0 -47
  58. package/dist/types/monitors/network/websocket-monitor.d.ts +0 -44
  59. package/dist/types/monitors/network/xhr-interceptor.d.ts +0 -25
  60. package/dist/types/monitors/performance/fps-monitor.d.ts +0 -24
  61. package/dist/types/monitors/performance/long-task-detector.d.ts +0 -25
  62. package/dist/types/monitors/performance/memory-monitor.d.ts +0 -30
  63. package/dist/types/monitors/performance/metrics-collector.d.ts +0 -45
  64. package/dist/types/monitors/performance/performance-monitor.d.ts +0 -34
  65. package/dist/types/monitors/state/state-monitor.d.ts +0 -8
  66. package/dist/types/monitors/storage/storage-monitor.d.ts +0 -8
  67. package/dist/types/simple-index.d.ts +0 -3
  68. package/dist/types/simple-inspector.d.ts +0 -24
  69. package/dist/types/ui/components/floating-widget.d.ts +0 -21
  70. package/dist/types/ui/components/main-panel.d.ts +0 -38
  71. package/dist/types/ui/inspector-ui.d.ts +0 -29
  72. package/dist/types/ui/styles.d.ts +0 -1
@@ -0,0 +1,841 @@
1
+ import {
2
+ generateId
3
+ } from "./chunk-LNBLBFDA.js";
4
+
5
+ // src/monitors/network/fetch-interceptor.ts
6
+ var MAX_BODY_PREVIEW = 64 * 1024;
7
+ var FetchInterceptor = class {
8
+ constructor(handlers = {}) {
9
+ this.requestMap = /* @__PURE__ */ new Map();
10
+ this.installed = null;
11
+ this.originalFetch = window.fetch;
12
+ this.handlers = handlers;
13
+ }
14
+ install() {
15
+ const self = this;
16
+ if (this.installed || typeof this.originalFetch !== "function") return;
17
+ const instrumented = async function(input, init) {
18
+ var _a, _b, _c, _d;
19
+ const id = generateId();
20
+ const startTime = performance.now();
21
+ let url;
22
+ let method;
23
+ let headers = {};
24
+ let body;
25
+ if (typeof Request !== "undefined" && input instanceof Request) {
26
+ url = input.url;
27
+ method = input.method;
28
+ input.headers.forEach((value, key) => {
29
+ headers[key] = value;
30
+ });
31
+ try {
32
+ body = await self.extractBody(input);
33
+ } catch (e) {
34
+ body = "[Body unavailable - request already used]";
35
+ }
36
+ } else {
37
+ url = input.toString();
38
+ method = (init == null ? void 0 : init.method) || "GET";
39
+ if (init == null ? void 0 : init.headers) {
40
+ if (init.headers instanceof Headers) {
41
+ init.headers.forEach((value, key) => {
42
+ headers[key] = value;
43
+ });
44
+ } else if (Array.isArray(init.headers)) {
45
+ init.headers.forEach(([key, value]) => {
46
+ headers[key] = value;
47
+ });
48
+ } else {
49
+ headers = init.headers;
50
+ }
51
+ }
52
+ body = init == null ? void 0 : init.body;
53
+ }
54
+ const request = {
55
+ id,
56
+ method,
57
+ url,
58
+ headers,
59
+ body: self.sanitizeBody(body),
60
+ timestamp: Date.now(),
61
+ type: "fetch"
62
+ };
63
+ self.requestMap.set(id, request);
64
+ (_b = (_a = self.handlers).onRequest) == null ? void 0 : _b.call(_a, request);
65
+ let response;
66
+ try {
67
+ response = await self.originalFetch.apply(this != null ? this : window, [input, init]);
68
+ } catch (error) {
69
+ const networkError = {
70
+ id,
71
+ message: (error == null ? void 0 : error.message) || "Network request failed",
72
+ stack: error == null ? void 0 : error.stack,
73
+ timestamp: Date.now()
74
+ };
75
+ (_d = (_c = self.handlers).onError) == null ? void 0 : _d.call(_c, networkError);
76
+ self.requestMap.delete(id);
77
+ throw error;
78
+ }
79
+ const duration = performance.now() - startTime;
80
+ void self.reportResponse(id, response, duration);
81
+ return response;
82
+ };
83
+ this.installed = instrumented;
84
+ window.fetch = instrumented;
85
+ }
86
+ async reportResponse(id, response, duration) {
87
+ var _a, _b;
88
+ try {
89
+ const responseHeaders = {};
90
+ response.headers.forEach((value, key) => {
91
+ responseHeaders[key] = value;
92
+ });
93
+ let responseBody;
94
+ try {
95
+ responseBody = response.bodyUsed ? "[Body already read]" : await this.extractResponseBody(response.clone());
96
+ } catch (e) {
97
+ responseBody = "[Unable to read response]";
98
+ }
99
+ (_b = (_a = this.handlers).onResponse) == null ? void 0 : _b.call(_a, {
100
+ id,
101
+ status: response.status,
102
+ statusText: response.statusText,
103
+ headers: responseHeaders,
104
+ body: responseBody,
105
+ size: this.calculateSize(responseBody, responseHeaders),
106
+ duration,
107
+ timestamp: Date.now(),
108
+ fromCache: this.isFromCache(response, duration)
109
+ });
110
+ } catch (e) {
111
+ } finally {
112
+ this.requestMap.delete(id);
113
+ }
114
+ }
115
+ uninstall() {
116
+ if (this.installed && window.fetch === this.installed) {
117
+ window.fetch = this.originalFetch;
118
+ }
119
+ this.installed = null;
120
+ this.requestMap.clear();
121
+ }
122
+ async extractBody(request) {
123
+ try {
124
+ const contentType = request.headers.get("content-type") || "";
125
+ if (request.bodyUsed) {
126
+ return "[Body already read]";
127
+ }
128
+ const cloned = request.clone();
129
+ if (contentType.includes("application/json")) {
130
+ return await this.readPreview(cloned, true);
131
+ } else if (contentType.includes("text/")) {
132
+ return await this.readPreview(cloned, false);
133
+ } else if (contentType.includes("application/x-www-form-urlencoded")) {
134
+ return await this.readPreview(cloned, false);
135
+ } else if (contentType.includes("multipart/form-data")) {
136
+ return "[FormData]";
137
+ }
138
+ return "[Binary data]";
139
+ } catch (error) {
140
+ return "[Unable to read body]";
141
+ }
142
+ }
143
+ /** Reads at most MAX_BODY_PREVIEW bytes from a cloned body, then cancels the clone. */
144
+ async readCapped(body) {
145
+ const stream = body.body;
146
+ if (!stream || typeof stream.getReader !== "function") {
147
+ const text2 = await body.text();
148
+ return text2.length > MAX_BODY_PREVIEW ? { text: text2.slice(0, MAX_BODY_PREVIEW), truncated: true } : { text: text2, truncated: false };
149
+ }
150
+ const reader = stream.getReader();
151
+ const decoder = new TextDecoder();
152
+ let text = "";
153
+ let received = 0;
154
+ try {
155
+ for (; ; ) {
156
+ const { done, value } = await reader.read();
157
+ if (done) return { text: text + decoder.decode(), truncated: false };
158
+ received += value.byteLength;
159
+ text += decoder.decode(value, { stream: true });
160
+ if (received >= MAX_BODY_PREVIEW) return { text: text.slice(0, MAX_BODY_PREVIEW), truncated: true };
161
+ }
162
+ } finally {
163
+ reader.cancel().catch(() => void 0);
164
+ }
165
+ }
166
+ async readPreview(body, asJson) {
167
+ const { text, truncated } = await this.readCapped(body);
168
+ if (truncated) return `${text}... [truncated]`;
169
+ if (asJson) {
170
+ try {
171
+ return JSON.parse(text);
172
+ } catch (e) {
173
+ return text;
174
+ }
175
+ }
176
+ return text;
177
+ }
178
+ async extractResponseBody(response) {
179
+ var _a, _b;
180
+ try {
181
+ const contentType = response.headers.get("content-type") || "";
182
+ if (contentType.includes("text/event-stream")) {
183
+ (_a = response.body) == null ? void 0 : _a.cancel().catch(() => void 0);
184
+ return "[Event stream]";
185
+ }
186
+ if (contentType.includes("application/json")) {
187
+ return await this.readPreview(response, true);
188
+ } else if (contentType.includes("text/")) {
189
+ return await this.readPreview(response, false);
190
+ } else if (contentType.includes("image/")) {
191
+ return "[Image data]";
192
+ } else if (contentType.includes("video/")) {
193
+ return "[Video data]";
194
+ } else if (contentType.includes("audio/")) {
195
+ return "[Audio data]";
196
+ }
197
+ const length = response.headers.get("content-length");
198
+ (_b = response.body) == null ? void 0 : _b.cancel().catch(() => void 0);
199
+ return length ? `[Binary data: ${length} bytes]` : "[Binary data]";
200
+ } catch (error) {
201
+ return "[Unable to read response]";
202
+ }
203
+ }
204
+ sanitizeBody(body) {
205
+ if (!body) return void 0;
206
+ if (typeof body === "string") {
207
+ return body.length > 1e4 ? body.substring(0, 1e4) + "..." : body;
208
+ }
209
+ if (body instanceof FormData) {
210
+ const entries = {};
211
+ body.forEach((value, key) => {
212
+ if (value instanceof File) {
213
+ entries[key] = `[File: ${value.name}, ${value.size} bytes]`;
214
+ } else {
215
+ entries[key] = value;
216
+ }
217
+ });
218
+ return { type: "FormData", entries };
219
+ }
220
+ if (body instanceof ArrayBuffer) {
221
+ return `[ArrayBuffer: ${body.byteLength} bytes]`;
222
+ }
223
+ if (body instanceof Blob) {
224
+ return `[Blob: ${body.size} bytes, type: ${body.type}]`;
225
+ }
226
+ if (body instanceof URLSearchParams) {
227
+ return body.toString();
228
+ }
229
+ return body;
230
+ }
231
+ calculateSize(body, headers) {
232
+ const contentLength = headers["content-length"];
233
+ if (contentLength) {
234
+ return parseInt(contentLength, 10);
235
+ }
236
+ if (typeof body === "string") {
237
+ return new Blob([body]).size;
238
+ }
239
+ if (body && typeof body === "object") {
240
+ try {
241
+ return new Blob([JSON.stringify(body)]).size;
242
+ } catch (e) {
243
+ return 0;
244
+ }
245
+ }
246
+ return 0;
247
+ }
248
+ isFromCache(response, duration) {
249
+ if (duration < 5) return true;
250
+ const cacheControl = response.headers.get("cache-control");
251
+ const etag = response.headers.get("etag");
252
+ const lastModified = response.headers.get("last-modified");
253
+ return !!(cacheControl || etag || lastModified);
254
+ }
255
+ };
256
+
257
+ // src/monitors/network/xhr-interceptor.ts
258
+ var XHRInterceptor = class {
259
+ constructor(handlers = {}) {
260
+ this.installed = null;
261
+ this.handlers = handlers;
262
+ this.originalOpen = XMLHttpRequest.prototype.open;
263
+ this.originalSend = XMLHttpRequest.prototype.send;
264
+ this.originalSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
265
+ }
266
+ install() {
267
+ if (this.installed || typeof XMLHttpRequest === "undefined") return;
268
+ const self = this;
269
+ XMLHttpRequest.prototype.open = function(method, url, async = true, username, password) {
270
+ this._devinspectorId = generateId();
271
+ this._devinspectorMethod = method;
272
+ this._devinspectorUrl = url.toString();
273
+ this._devinspectorRequestHeaders = {};
274
+ return self.originalOpen.apply(this, [method, url, async, username, password]);
275
+ };
276
+ XMLHttpRequest.prototype.setRequestHeader = function(name, value) {
277
+ if (this._devinspectorRequestHeaders) {
278
+ this._devinspectorRequestHeaders[name] = value;
279
+ }
280
+ return self.originalSetRequestHeader.apply(this, [name, value]);
281
+ };
282
+ XMLHttpRequest.prototype.send = function(body) {
283
+ var _a, _b;
284
+ this._devinspectorStartTime = performance.now();
285
+ this._devinspectorRequestBody = self.sanitizeBody(body);
286
+ const request = {
287
+ id: this._devinspectorId,
288
+ method: this._devinspectorMethod,
289
+ url: this._devinspectorUrl,
290
+ headers: this._devinspectorRequestHeaders || {},
291
+ body: this._devinspectorRequestBody,
292
+ timestamp: Date.now(),
293
+ type: "xhr"
294
+ };
295
+ (_b = (_a = self.handlers).onRequest) == null ? void 0 : _b.call(_a, request);
296
+ if (this.upload && self.handlers.onProgress) {
297
+ this.upload.addEventListener("progress", (event) => {
298
+ if (event.lengthComputable) {
299
+ self.handlers.onProgress({
300
+ id: this._devinspectorId,
301
+ loaded: event.loaded,
302
+ total: event.total
303
+ });
304
+ }
305
+ });
306
+ }
307
+ if (self.handlers.onProgress) {
308
+ this.addEventListener("progress", (event) => {
309
+ if (event.lengthComputable) {
310
+ self.handlers.onProgress({
311
+ id: this._devinspectorId,
312
+ loaded: event.loaded,
313
+ total: event.total
314
+ });
315
+ }
316
+ });
317
+ }
318
+ this.addEventListener("load", function() {
319
+ var _a2, _b2;
320
+ const duration = performance.now() - this._devinspectorStartTime;
321
+ const responseHeaders = self.parseResponseHeaders(this.getAllResponseHeaders());
322
+ const responseBody = self.extractResponseBody(this);
323
+ const size = self.calculateSize(responseBody, responseHeaders);
324
+ const response = {
325
+ id: this._devinspectorId,
326
+ status: this.status,
327
+ statusText: this.statusText,
328
+ headers: responseHeaders,
329
+ body: responseBody,
330
+ size,
331
+ duration,
332
+ timestamp: Date.now(),
333
+ fromCache: duration < 5
334
+ };
335
+ (_b2 = (_a2 = self.handlers).onResponse) == null ? void 0 : _b2.call(_a2, response);
336
+ });
337
+ this.addEventListener("error", function() {
338
+ var _a2, _b2;
339
+ const error = {
340
+ id: this._devinspectorId,
341
+ message: "Network request failed",
342
+ timestamp: Date.now()
343
+ };
344
+ (_b2 = (_a2 = self.handlers).onError) == null ? void 0 : _b2.call(_a2, error);
345
+ });
346
+ this.addEventListener("timeout", function() {
347
+ var _a2, _b2;
348
+ const error = {
349
+ id: this._devinspectorId,
350
+ message: `Request timeout after ${this.timeout}ms`,
351
+ timestamp: Date.now()
352
+ };
353
+ (_b2 = (_a2 = self.handlers).onError) == null ? void 0 : _b2.call(_a2, error);
354
+ });
355
+ this.addEventListener("abort", function() {
356
+ var _a2, _b2;
357
+ const error = {
358
+ id: this._devinspectorId,
359
+ message: "Request aborted",
360
+ timestamp: Date.now()
361
+ };
362
+ (_b2 = (_a2 = self.handlers).onError) == null ? void 0 : _b2.call(_a2, error);
363
+ });
364
+ return self.originalSend.apply(this, [body]);
365
+ };
366
+ this.installed = {
367
+ open: XMLHttpRequest.prototype.open,
368
+ send: XMLHttpRequest.prototype.send,
369
+ setRequestHeader: XMLHttpRequest.prototype.setRequestHeader
370
+ };
371
+ }
372
+ uninstall() {
373
+ if (!this.installed) return;
374
+ const proto = XMLHttpRequest.prototype;
375
+ if (proto.open === this.installed.open) proto.open = this.originalOpen;
376
+ if (proto.send === this.installed.send) proto.send = this.originalSend;
377
+ if (proto.setRequestHeader === this.installed.setRequestHeader) proto.setRequestHeader = this.originalSetRequestHeader;
378
+ this.installed = null;
379
+ }
380
+ sanitizeBody(body) {
381
+ if (!body) return void 0;
382
+ if (typeof body === "string") {
383
+ return body.length > 1e4 ? body.substring(0, 1e4) + "..." : body;
384
+ }
385
+ if (body instanceof FormData) {
386
+ const entries = {};
387
+ body.forEach((value, key) => {
388
+ if (value instanceof File) {
389
+ entries[key] = `[File: ${value.name}, ${value.size} bytes]`;
390
+ } else {
391
+ entries[key] = value;
392
+ }
393
+ });
394
+ return { type: "FormData", entries };
395
+ }
396
+ if (body instanceof ArrayBuffer) {
397
+ return `[ArrayBuffer: ${body.byteLength} bytes]`;
398
+ }
399
+ if (body instanceof Blob) {
400
+ return `[Blob: ${body.size} bytes, type: ${body.type}]`;
401
+ }
402
+ if (body instanceof Document) {
403
+ return "[Document]";
404
+ }
405
+ return body;
406
+ }
407
+ parseResponseHeaders(headersString) {
408
+ const headers = {};
409
+ if (!headersString) return headers;
410
+ const lines = headersString.trim().split(/[\r\n]+/);
411
+ lines.forEach((line) => {
412
+ const parts = line.split(": ");
413
+ const key = parts.shift();
414
+ if (key) {
415
+ headers[key] = parts.join(": ");
416
+ }
417
+ });
418
+ return headers;
419
+ }
420
+ extractResponseBody(xhr) {
421
+ try {
422
+ const contentType = xhr.getResponseHeader("content-type") || "";
423
+ if (xhr.responseType === "json" && xhr.response) {
424
+ return xhr.response;
425
+ }
426
+ if (xhr.responseType === "arraybuffer" && xhr.response) {
427
+ return `[ArrayBuffer: ${xhr.response.byteLength} bytes]`;
428
+ }
429
+ if (xhr.responseType === "blob" && xhr.response) {
430
+ return `[Blob: ${xhr.response.size} bytes, type: ${xhr.response.type}]`;
431
+ }
432
+ if (xhr.responseType === "document") {
433
+ return "[Document]";
434
+ }
435
+ if (xhr.responseText) {
436
+ if (contentType.includes("application/json")) {
437
+ try {
438
+ return JSON.parse(xhr.responseText);
439
+ } catch (e) {
440
+ return xhr.responseText;
441
+ }
442
+ }
443
+ return xhr.responseText.length > 1e4 ? xhr.responseText.substring(0, 1e4) + "..." : xhr.responseText;
444
+ }
445
+ return null;
446
+ } catch (error) {
447
+ return "[Unable to read response]";
448
+ }
449
+ }
450
+ calculateSize(body, headers) {
451
+ const contentLength = headers["content-length"];
452
+ if (contentLength) {
453
+ return parseInt(contentLength, 10);
454
+ }
455
+ if (typeof body === "string") {
456
+ return new Blob([body]).size;
457
+ }
458
+ if (body && typeof body === "object") {
459
+ try {
460
+ return new Blob([JSON.stringify(body)]).size;
461
+ } catch (e) {
462
+ return 0;
463
+ }
464
+ }
465
+ return 0;
466
+ }
467
+ };
468
+
469
+ // src/monitors/network/websocket-monitor.ts
470
+ var WebSocketMonitor = class {
471
+ constructor(handlers = {}) {
472
+ this.connections = /* @__PURE__ */ new Map();
473
+ this.installed = null;
474
+ this.originalWebSocket = window.WebSocket;
475
+ this.handlers = handlers;
476
+ }
477
+ install() {
478
+ const self = this;
479
+ const OriginalWebSocket = this.originalWebSocket;
480
+ if (typeof OriginalWebSocket !== "function" || this.installed) return;
481
+ const MonitoredWebSocket = function(url, protocols) {
482
+ var _a, _b;
483
+ const ws = new OriginalWebSocket(url, protocols);
484
+ const connectionId = generateId();
485
+ ws._devinspectorId = connectionId;
486
+ ws._devinspectorUrl = url.toString();
487
+ ws._devinspectorProtocols = protocols;
488
+ const connection = {
489
+ id: connectionId,
490
+ url: url.toString(),
491
+ protocols,
492
+ timestamp: Date.now(),
493
+ readyState: ws.readyState,
494
+ status: "connecting"
495
+ };
496
+ self.connections.set(connectionId, connection);
497
+ (_b = (_a = self.handlers).onConnection) == null ? void 0 : _b.call(_a, connection);
498
+ ws.addEventListener("open", function() {
499
+ var _a2, _b2;
500
+ const conn = self.connections.get(connectionId);
501
+ if (conn) {
502
+ conn.status = "open";
503
+ conn.readyState = this.readyState;
504
+ (_b2 = (_a2 = self.handlers).onStatusChange) == null ? void 0 : _b2.call(_a2, {
505
+ connectionId,
506
+ status: "open"
507
+ });
508
+ }
509
+ });
510
+ ws.addEventListener("close", function(event) {
511
+ var _a2, _b2;
512
+ const conn = self.connections.get(connectionId);
513
+ if (conn) {
514
+ conn.status = "closed";
515
+ conn.readyState = this.readyState;
516
+ (_b2 = (_a2 = self.handlers).onStatusChange) == null ? void 0 : _b2.call(_a2, {
517
+ connectionId,
518
+ status: "closed"
519
+ });
520
+ }
521
+ self.connections.delete(connectionId);
522
+ });
523
+ ws.addEventListener("error", function(event) {
524
+ var _a2, _b2;
525
+ const error = {
526
+ id: generateId(),
527
+ connectionId,
528
+ message: "WebSocket error occurred",
529
+ timestamp: Date.now()
530
+ };
531
+ (_b2 = (_a2 = self.handlers).onError) == null ? void 0 : _b2.call(_a2, error);
532
+ });
533
+ ws.addEventListener("message", function(event) {
534
+ var _a2, _b2;
535
+ const message = {
536
+ id: generateId(),
537
+ connectionId,
538
+ type: "received",
539
+ data: self.parseMessageData(event.data),
540
+ timestamp: Date.now(),
541
+ size: self.calculateMessageSize(event.data)
542
+ };
543
+ (_b2 = (_a2 = self.handlers).onMessage) == null ? void 0 : _b2.call(_a2, message);
544
+ });
545
+ const originalSend = ws.send.bind(ws);
546
+ ws.send = function(data) {
547
+ var _a2, _b2;
548
+ const message = {
549
+ id: generateId(),
550
+ connectionId,
551
+ type: "sent",
552
+ data: self.parseMessageData(data),
553
+ timestamp: Date.now(),
554
+ size: self.calculateMessageSize(data)
555
+ };
556
+ (_b2 = (_a2 = self.handlers).onMessage) == null ? void 0 : _b2.call(_a2, message);
557
+ return originalSend(data);
558
+ };
559
+ const originalClose = ws.close.bind(ws);
560
+ ws.close = function(code, reason) {
561
+ var _a2, _b2;
562
+ const conn = self.connections.get(connectionId);
563
+ if (conn) {
564
+ conn.status = "closing";
565
+ conn.readyState = this.readyState;
566
+ (_b2 = (_a2 = self.handlers).onStatusChange) == null ? void 0 : _b2.call(_a2, {
567
+ connectionId,
568
+ status: "closing"
569
+ });
570
+ }
571
+ return originalClose(code, reason);
572
+ };
573
+ return ws;
574
+ };
575
+ Object.setPrototypeOf(MonitoredWebSocket, OriginalWebSocket);
576
+ MonitoredWebSocket.prototype = OriginalWebSocket.prototype;
577
+ this.installed = MonitoredWebSocket;
578
+ window.WebSocket = MonitoredWebSocket;
579
+ }
580
+ uninstall() {
581
+ if (this.installed && window.WebSocket === this.installed) {
582
+ window.WebSocket = this.originalWebSocket;
583
+ }
584
+ this.installed = null;
585
+ this.connections.clear();
586
+ }
587
+ parseMessageData(data) {
588
+ if (typeof data === "string") {
589
+ try {
590
+ return JSON.parse(data);
591
+ } catch (e) {
592
+ return data.length > 1e4 ? data.substring(0, 1e4) + "..." : data;
593
+ }
594
+ }
595
+ if (data instanceof ArrayBuffer) {
596
+ return `[ArrayBuffer: ${data.byteLength} bytes]`;
597
+ }
598
+ if (data instanceof Blob) {
599
+ return `[Blob: ${data.size} bytes, type: ${data.type}]`;
600
+ }
601
+ if (ArrayBuffer.isView(data)) {
602
+ return `[ArrayBufferView: ${data.byteLength} bytes]`;
603
+ }
604
+ return data;
605
+ }
606
+ calculateMessageSize(data) {
607
+ if (typeof data === "string") {
608
+ return new Blob([data]).size;
609
+ }
610
+ if (data instanceof ArrayBuffer) {
611
+ return data.byteLength;
612
+ }
613
+ if (data instanceof Blob) {
614
+ return data.size;
615
+ }
616
+ if (ArrayBuffer.isView(data)) {
617
+ return data.byteLength;
618
+ }
619
+ return 0;
620
+ }
621
+ getActiveConnections() {
622
+ return Array.from(this.connections.values());
623
+ }
624
+ getConnection(id) {
625
+ return this.connections.get(id);
626
+ }
627
+ };
628
+
629
+ // src/monitors/network/network-monitor.ts
630
+ var MAX_WEBSOCKET_MESSAGES = 500;
631
+ var NetworkMonitor = class {
632
+ constructor(inspector) {
633
+ this.beaconInterceptor = null;
634
+ this.beaconOriginal = null;
635
+ this.entries = /* @__PURE__ */ new Map();
636
+ this.isActive = false;
637
+ this.inspector = inspector;
638
+ this.fetchInterceptor = new FetchInterceptor({
639
+ onRequest: this.handleRequest.bind(this, "fetch"),
640
+ onResponse: this.handleResponse.bind(this),
641
+ onError: this.handleError.bind(this)
642
+ });
643
+ this.xhrInterceptor = new XHRInterceptor({
644
+ onRequest: this.handleRequest.bind(this, "xhr"),
645
+ onResponse: this.handleResponse.bind(this),
646
+ onError: this.handleError.bind(this),
647
+ onProgress: this.handleProgress.bind(this)
648
+ });
649
+ this.websocketMonitor = new WebSocketMonitor({
650
+ onConnection: this.handleWebSocketConnection.bind(this),
651
+ onMessage: this.handleWebSocketMessage.bind(this),
652
+ onStatusChange: this.handleWebSocketStatusChange.bind(this),
653
+ onError: this.handleWebSocketError.bind(this)
654
+ });
655
+ }
656
+ start() {
657
+ if (this.isActive) return;
658
+ this.fetchInterceptor.install();
659
+ this.xhrInterceptor.install();
660
+ this.websocketMonitor.install();
661
+ this.installBeaconInterceptor();
662
+ this.isActive = true;
663
+ }
664
+ stop() {
665
+ if (!this.isActive) return;
666
+ this.fetchInterceptor.uninstall();
667
+ this.xhrInterceptor.uninstall();
668
+ this.websocketMonitor.uninstall();
669
+ this.uninstallBeaconInterceptor();
670
+ this.isActive = false;
671
+ }
672
+ handleRequest(type, request) {
673
+ const entry = {
674
+ id: request.id,
675
+ type,
676
+ request,
677
+ timestamp: request.timestamp
678
+ };
679
+ this.track(request.id, entry);
680
+ const storage = this.inspector.getStorage("network");
681
+ storage.push(entry);
682
+ this.inspector.getEvents().emit("network:request", {
683
+ ...request,
684
+ type
685
+ });
686
+ }
687
+ handleResponse(response) {
688
+ var _a, _b, _c, _d;
689
+ const entry = this.entries.get(response.id);
690
+ if (!entry) return;
691
+ entry.response = response;
692
+ entry.duration = response.duration;
693
+ entry.status = response.status;
694
+ entry.size = response.size;
695
+ this.inspector.getEvents().emit("network:response", response);
696
+ if (response.duration > 3e3) {
697
+ (_d = (_c = this.inspector.getConfig()).onPerformanceIssue) == null ? void 0 : _d.call(_c, {
698
+ type: "slow-network",
699
+ message: `Slow network request: ${(_a = entry.request) == null ? void 0 : _a.url}`,
700
+ duration: response.duration,
701
+ url: (_b = entry.request) == null ? void 0 : _b.url
702
+ });
703
+ }
704
+ }
705
+ handleError(error) {
706
+ const entry = this.entries.get(error.id);
707
+ if (!entry) return;
708
+ entry.error = error;
709
+ this.inspector.getEvents().emit("network:error", error);
710
+ }
711
+ handleProgress(progress) {
712
+ this.inspector.getEvents().emit("network:progress", progress);
713
+ }
714
+ handleWebSocketConnection(connection) {
715
+ const entry = {
716
+ id: connection.id,
717
+ type: "websocket",
718
+ websocket: {
719
+ connection,
720
+ messages: [],
721
+ errors: []
722
+ },
723
+ timestamp: connection.timestamp
724
+ };
725
+ this.track(connection.id, entry);
726
+ const storage = this.inspector.getStorage("network");
727
+ storage.push(entry);
728
+ this.inspector.getEvents().emit("network:websocket:connection", connection);
729
+ }
730
+ handleWebSocketMessage(message) {
731
+ const entry = this.entries.get(message.connectionId);
732
+ if (!entry || !entry.websocket) return;
733
+ entry.websocket.messages.push(message);
734
+ if (entry.websocket.messages.length > MAX_WEBSOCKET_MESSAGES) entry.websocket.messages.shift();
735
+ this.inspector.getEvents().emit("network:websocket:message", message);
736
+ }
737
+ handleWebSocketStatusChange(status) {
738
+ var _a;
739
+ const entry = this.entries.get(status.connectionId);
740
+ if (!entry || !((_a = entry.websocket) == null ? void 0 : _a.connection)) return;
741
+ entry.websocket.connection.status = status.status;
742
+ this.inspector.getEvents().emit("network:websocket:status", status);
743
+ }
744
+ handleWebSocketError(error) {
745
+ const entry = this.entries.get(error.connectionId);
746
+ if (!entry || !entry.websocket) return;
747
+ entry.websocket.errors.push(error);
748
+ if (entry.websocket.errors.length > MAX_WEBSOCKET_MESSAGES) entry.websocket.errors.shift();
749
+ this.inspector.getEvents().emit("network:websocket:error", error);
750
+ }
751
+ /** Remembers an in-flight entry; the map is bounded like the network storage. */
752
+ track(id, entry) {
753
+ this.entries.set(id, entry);
754
+ const max = Math.max(1, this.inspector.getConfig().maxNetworkEntries);
755
+ while (this.entries.size > max) {
756
+ const oldest = this.entries.keys().next().value;
757
+ this.entries.delete(oldest);
758
+ }
759
+ }
760
+ installBeaconInterceptor() {
761
+ if (typeof navigator === "undefined" || typeof navigator.sendBeacon !== "function") return;
762
+ const originalSendBeacon = navigator.sendBeacon.bind(navigator);
763
+ const self = this;
764
+ const instrumented = function(url, data) {
765
+ const id = self.generateId();
766
+ const request = {
767
+ id,
768
+ method: "POST",
769
+ url,
770
+ headers: {},
771
+ body: self.sanitizeBeaconData(data),
772
+ timestamp: Date.now(),
773
+ type: "beacon"
774
+ };
775
+ self.handleRequest("beacon", request);
776
+ const result = originalSendBeacon(url, data);
777
+ setTimeout(() => {
778
+ const response = {
779
+ id,
780
+ status: result ? 204 : 0,
781
+ statusText: result ? "No Content" : "Failed",
782
+ headers: {},
783
+ size: 0,
784
+ duration: 0,
785
+ timestamp: Date.now()
786
+ };
787
+ self.handleResponse(response);
788
+ }, 0);
789
+ return result;
790
+ };
791
+ this.beaconOriginal = navigator.sendBeacon;
792
+ this.beaconInterceptor = instrumented;
793
+ navigator.sendBeacon = instrumented;
794
+ }
795
+ uninstallBeaconInterceptor() {
796
+ if (this.beaconInterceptor && navigator.sendBeacon === this.beaconInterceptor) {
797
+ navigator.sendBeacon = this.beaconOriginal;
798
+ }
799
+ this.beaconInterceptor = null;
800
+ this.beaconOriginal = null;
801
+ }
802
+ sanitizeBeaconData(data) {
803
+ if (!data) return void 0;
804
+ if (typeof data === "string") {
805
+ return data.length > 1e3 ? data.substring(0, 1e3) + "..." : data;
806
+ }
807
+ if (data instanceof FormData) {
808
+ const entries = {};
809
+ data.forEach((value, key) => {
810
+ entries[key] = value instanceof File ? `[File: ${value.name}]` : value;
811
+ });
812
+ return { type: "FormData", entries };
813
+ }
814
+ if (data instanceof Blob) {
815
+ return `[Blob: ${data.size} bytes]`;
816
+ }
817
+ if (data instanceof ArrayBuffer) {
818
+ return `[ArrayBuffer: ${data.byteLength} bytes]`;
819
+ }
820
+ return data;
821
+ }
822
+ generateId() {
823
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
824
+ }
825
+ getEntries() {
826
+ return Array.from(this.entries.values());
827
+ }
828
+ clearEntries() {
829
+ this.entries.clear();
830
+ }
831
+ getEntry(id) {
832
+ return this.entries.get(id);
833
+ }
834
+ filterEntries(predicate) {
835
+ return Array.from(this.entries.values()).filter(predicate);
836
+ }
837
+ };
838
+ export {
839
+ NetworkMonitor
840
+ };
841
+ //# sourceMappingURL=network-monitor-HUSRKEXE.js.map