@zhongxiaobing/monitor 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,690 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
21
+
22
+ // src/index.ts
23
+ var index_exports = {};
24
+ __export(index_exports, {
25
+ Monitor: () => Monitor,
26
+ blankScreenPlugin: () => blankScreenPlugin,
27
+ errorPlugin: () => errorPlugin,
28
+ initMonitor: () => initMonitor,
29
+ networkPlugin: () => networkPlugin
30
+ });
31
+ module.exports = __toCommonJS(index_exports);
32
+
33
+ // ../monitor-shared/src/utils/uuid.ts
34
+ function createEventId() {
35
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
36
+ return crypto.randomUUID();
37
+ }
38
+ return `evt_${Date.now()}_${Math.random().toString(16).slice(2)}`;
39
+ }
40
+
41
+ // ../monitor-shared/src/utils/error.ts
42
+ function normalizeError(error) {
43
+ if (error instanceof Error) {
44
+ return {
45
+ name: error.name,
46
+ message: error.message,
47
+ stack: error.stack
48
+ };
49
+ }
50
+ if (typeof error === "string") {
51
+ return {
52
+ message: error
53
+ };
54
+ }
55
+ if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") {
56
+ const maybeError = error;
57
+ return {
58
+ name: typeof maybeError.name === "string" ? maybeError.name : void 0,
59
+ message: maybeError.message,
60
+ stack: typeof maybeError.stack === "string" ? maybeError.stack : void 0
61
+ };
62
+ }
63
+ return {
64
+ message: "Unknown error"
65
+ };
66
+ }
67
+
68
+ // ../monitor-shared/src/utils/browser.ts
69
+ function getLocationInfo() {
70
+ return {
71
+ url: window.location.href,
72
+ pathname: window.location.pathname,
73
+ title: document.title,
74
+ userAgent: navigator.userAgent
75
+ };
76
+ }
77
+
78
+ // ../monitor-transport/src/queue.ts
79
+ var EventQueue = class {
80
+ constructor() {
81
+ __publicField(this, "events", []);
82
+ }
83
+ add(event) {
84
+ this.events.push(event);
85
+ }
86
+ drain() {
87
+ const current = [...this.events];
88
+ this.events = [];
89
+ return current;
90
+ }
91
+ size() {
92
+ return this.events.length;
93
+ }
94
+ };
95
+
96
+ // ../monitor-transport/src/sender.ts
97
+ async function sendEvents(dsn, events) {
98
+ if (!events.length) return;
99
+ if (navigator.sendBeacon) {
100
+ const blob = new Blob([JSON.stringify({ events })], {
101
+ type: "application/json"
102
+ });
103
+ navigator.sendBeacon(dsn, blob);
104
+ return;
105
+ }
106
+ await fetch(dsn, {
107
+ method: "POST",
108
+ headers: {
109
+ "Content-Type": "application/json"
110
+ },
111
+ body: JSON.stringify({ events }),
112
+ keepalive: true
113
+ });
114
+ }
115
+
116
+ // ../monitor-core/src/context.ts
117
+ function createBaseContext(options) {
118
+ const locationInfo = getLocationInfo();
119
+ return {
120
+ appId: options.appId,
121
+ appName: options.appName,
122
+ env: options.env,
123
+ release: options.release,
124
+ ...locationInfo
125
+ };
126
+ }
127
+
128
+ // ../monitor-core/src/plugin-system.ts
129
+ function setupPlugins(plugins, api, options) {
130
+ const disposers = [];
131
+ for (const plugin of plugins) {
132
+ const disposer = plugin.setup({ api, options });
133
+ if (typeof disposer === "function") {
134
+ disposers.push(disposer);
135
+ }
136
+ }
137
+ return () => {
138
+ for (const dispose of disposers) {
139
+ dispose();
140
+ }
141
+ };
142
+ }
143
+
144
+ // ../monitor-core/src/monitor.ts
145
+ var Monitor = class {
146
+ constructor(options) {
147
+ __publicField(this, "queue", new EventQueue());
148
+ __publicField(this, "options");
149
+ __publicField(this, "context");
150
+ __publicField(this, "disposePlugins", null);
151
+ var _a;
152
+ this.options = options;
153
+ this.context = createBaseContext(options);
154
+ this.disposePlugins = setupPlugins((_a = options.plugins) != null ? _a : [], this, options);
155
+ }
156
+ emit(event) {
157
+ const mergedEvent = {
158
+ ...this.context,
159
+ ...event,
160
+ appId: event.appId || this.context.appId,
161
+ appName: event.appName || this.context.appName,
162
+ env: event.env || this.context.env,
163
+ release: event.release || this.context.release,
164
+ url: event.url || this.context.url,
165
+ pathname: event.pathname || this.context.pathname,
166
+ title: event.title || this.context.title,
167
+ userAgent: event.userAgent || this.context.userAgent,
168
+ eventId: event.eventId || createEventId(),
169
+ timestamp: event.timestamp || Date.now()
170
+ };
171
+ const finalEvent = this.options.beforeSend ? this.options.beforeSend(mergedEvent) : mergedEvent;
172
+ if (!finalEvent) return;
173
+ this.queue.add(finalEvent);
174
+ void this.flush();
175
+ }
176
+ captureException(error, extra) {
177
+ const normalized = normalizeError(error);
178
+ const event = {
179
+ eventId: "",
180
+ eventType: "exception",
181
+ appId: "",
182
+ env: "",
183
+ url: "",
184
+ pathname: "",
185
+ title: "",
186
+ timestamp: 0,
187
+ userAgent: "",
188
+ extra,
189
+ error: {
190
+ name: normalized.name,
191
+ message: normalized.message,
192
+ stack: normalized.stack,
193
+ source: "react"
194
+ }
195
+ };
196
+ this.emit(event);
197
+ }
198
+ async flush() {
199
+ const events = this.queue.drain();
200
+ await sendEvents(this.options.dsn, events);
201
+ }
202
+ destroy() {
203
+ var _a;
204
+ (_a = this.disposePlugins) == null ? void 0 : _a.call(this);
205
+ this.disposePlugins = null;
206
+ }
207
+ };
208
+ function initMonitor(options) {
209
+ return new Monitor(options);
210
+ }
211
+
212
+ // ../monitor-plugin-error/src/normalize.ts
213
+ function createExceptionEvent({
214
+ error,
215
+ source
216
+ }) {
217
+ const normalized = normalizeError(error);
218
+ return {
219
+ eventId: "",
220
+ eventType: "exception",
221
+ appId: "",
222
+ env: "",
223
+ url: "",
224
+ pathname: "",
225
+ title: "",
226
+ timestamp: 0,
227
+ userAgent: "",
228
+ error: {
229
+ name: normalized.name,
230
+ message: normalized.message,
231
+ stack: normalized.stack,
232
+ source
233
+ }
234
+ };
235
+ }
236
+
237
+ // ../monitor-plugin-error/src/unhandledrejection.ts
238
+ function registerUnhandledRejection(api) {
239
+ const handler = (event) => {
240
+ const exceptionEvent = createExceptionEvent({
241
+ error: event.reason,
242
+ source: "unhandledrejection"
243
+ });
244
+ api.emit(exceptionEvent);
245
+ };
246
+ window.addEventListener("unhandledrejection", handler);
247
+ return () => {
248
+ window.removeEventListener("unhandledrejection", handler);
249
+ };
250
+ }
251
+
252
+ // ../monitor-plugin-error/src/onerror.ts
253
+ function registerWindowOnError(api) {
254
+ const handler = (message, _source, _lineno, _colno, error) => {
255
+ const targetError = error != null ? error : message;
256
+ const event = createExceptionEvent({
257
+ error: targetError,
258
+ source: "window.onerror"
259
+ });
260
+ api.emit(event);
261
+ return false;
262
+ };
263
+ window.onerror = handler;
264
+ return () => {
265
+ if (window.onerror === handler) {
266
+ window.onerror = null;
267
+ }
268
+ };
269
+ }
270
+
271
+ // ../monitor-plugin-error/src/index.ts
272
+ function errorPlugin(options = {}) {
273
+ const {
274
+ captureOnError = true,
275
+ captureUnhandledRejection = true
276
+ } = options;
277
+ return {
278
+ name: "error-plugin",
279
+ setup({ api }) {
280
+ const disposers = [];
281
+ if (captureOnError) {
282
+ disposers.push(registerWindowOnError(api));
283
+ }
284
+ if (captureUnhandledRejection) {
285
+ disposers.push(registerUnhandledRejection(api));
286
+ }
287
+ return () => {
288
+ for (const dispose of disposers) {
289
+ dispose();
290
+ }
291
+ };
292
+ }
293
+ };
294
+ }
295
+
296
+ // ../monitor-plugin-network/src/normalize.ts
297
+ function createHttpErrorEvent({
298
+ url,
299
+ method,
300
+ status,
301
+ duration,
302
+ responseMessage
303
+ }) {
304
+ return {
305
+ eventId: "",
306
+ eventType: "http_error",
307
+ appId: "",
308
+ env: "",
309
+ url: "",
310
+ pathname: "",
311
+ title: "",
312
+ timestamp: 0,
313
+ userAgent: "",
314
+ request: {
315
+ url,
316
+ method,
317
+ status,
318
+ duration,
319
+ success: false,
320
+ source: "fetch"
321
+ },
322
+ response: {
323
+ message: responseMessage
324
+ }
325
+ };
326
+ }
327
+
328
+ // ../monitor-plugin-network/src/url.ts
329
+ function resolveUrlObject(url) {
330
+ return new URL(url, window.location.origin);
331
+ }
332
+ function isMonitorRequest(requestUrl, dsn) {
333
+ try {
334
+ const request = resolveUrlObject(requestUrl);
335
+ const target = resolveUrlObject(dsn);
336
+ return request.origin === target.origin && request.pathname === target.pathname;
337
+ } catch {
338
+ return requestUrl === dsn;
339
+ }
340
+ }
341
+
342
+ // ../monitor-plugin-network/src/patch-fetch.ts
343
+ function patchFetch(api, sdkOptions, options) {
344
+ if (typeof window === "undefined" || typeof window.fetch !== "function") {
345
+ return () => {
346
+ };
347
+ }
348
+ const originalFetch = window.fetch.bind(window);
349
+ const {
350
+ capture5xx = true,
351
+ captureNetworkError = true
352
+ } = options;
353
+ window.fetch = async (input, init) => {
354
+ const method = ((init == null ? void 0 : init.method) || "GET").toUpperCase();
355
+ const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
356
+ if (isMonitorRequest(requestUrl, sdkOptions.dsn)) {
357
+ return originalFetch(input, init);
358
+ }
359
+ const startedAt = Date.now();
360
+ try {
361
+ const response = await originalFetch(input, init);
362
+ const duration = Date.now() - startedAt;
363
+ if (capture5xx && response.status >= 500) {
364
+ api.emit(
365
+ createHttpErrorEvent({
366
+ url: requestUrl,
367
+ method,
368
+ status: response.status,
369
+ duration,
370
+ responseMessage: response.statusText
371
+ })
372
+ );
373
+ }
374
+ return response;
375
+ } catch (error) {
376
+ const duration = Date.now() - startedAt;
377
+ if (captureNetworkError) {
378
+ api.emit(
379
+ createHttpErrorEvent({
380
+ url: requestUrl,
381
+ method,
382
+ duration,
383
+ responseMessage: error instanceof Error ? error.message : "Fetch request failed"
384
+ })
385
+ );
386
+ }
387
+ throw error;
388
+ }
389
+ };
390
+ return () => {
391
+ window.fetch = originalFetch;
392
+ };
393
+ }
394
+
395
+ // ../monitor-plugin-network/src/index.ts
396
+ function networkPlugin(options = {}) {
397
+ return {
398
+ name: "network-plugin",
399
+ setup({ api, options: sdkOptions }) {
400
+ const disposeFetch = patchFetch(api, sdkOptions, options);
401
+ return () => {
402
+ disposeFetch();
403
+ };
404
+ }
405
+ };
406
+ }
407
+
408
+ // ../monitor-plugin-blank-screen/src/dedupe.ts
409
+ function normalizeScore(score) {
410
+ return score.toFixed(1);
411
+ }
412
+ function createDedupeKey(input) {
413
+ return [input.pathname, input.trigger, normalizeScore(input.score)].join("|");
414
+ }
415
+ function createBlankScreenDedupe(windowMs) {
416
+ const cache = /* @__PURE__ */ new Map();
417
+ function shouldReport(input) {
418
+ const now = Date.now();
419
+ const key = createDedupeKey(input);
420
+ const lastReportedAt = cache.get(key);
421
+ if (!lastReportedAt || now - lastReportedAt > windowMs) {
422
+ cache.set(key, now);
423
+ return true;
424
+ }
425
+ return false;
426
+ }
427
+ function cleanup() {
428
+ const now = Date.now();
429
+ for (const [key, timestamp] of cache.entries()) {
430
+ if (now - timestamp > windowMs) {
431
+ cache.delete(key);
432
+ }
433
+ }
434
+ }
435
+ return {
436
+ shouldReport,
437
+ cleanup
438
+ };
439
+ }
440
+
441
+ // ../monitor-plugin-blank-screen/src/root.ts
442
+ function getRootElement(rootSelector) {
443
+ if (rootSelector) {
444
+ const customRoot = document.querySelector(rootSelector);
445
+ if (customRoot) {
446
+ return customRoot;
447
+ }
448
+ }
449
+ const appRoot = document.querySelector("#app");
450
+ if (appRoot) {
451
+ return appRoot;
452
+ }
453
+ const reactRoot = document.querySelector("#root");
454
+ if (reactRoot) {
455
+ return reactRoot;
456
+ }
457
+ return document.body;
458
+ }
459
+
460
+ // ../monitor-plugin-blank-screen/src/sampler.ts
461
+ var DEFAULT_SAMPLE_POINTS = [
462
+ [0.5, 0.5],
463
+ [0.2, 0.2],
464
+ [0.5, 0.2],
465
+ [0.8, 0.2],
466
+ [0.2, 0.5],
467
+ [0.8, 0.5],
468
+ [0.2, 0.8],
469
+ [0.5, 0.8],
470
+ [0.8, 0.8]
471
+ ];
472
+ function getSamplePoints(samplePoints) {
473
+ return (samplePoints == null ? void 0 : samplePoints.length) ? samplePoints : DEFAULT_SAMPLE_POINTS;
474
+ }
475
+ function sampleElements(points) {
476
+ const width = window.innerWidth;
477
+ const height = window.innerHeight;
478
+ return points.map(([xRatio, yRatio]) => {
479
+ const x = Math.floor(width * xRatio);
480
+ const y = Math.floor(height * yRatio);
481
+ const element = document.elementFromPoint(x, y);
482
+ return {
483
+ x,
484
+ y,
485
+ element
486
+ };
487
+ });
488
+ }
489
+
490
+ // ../monitor-plugin-blank-screen/src/score.ts
491
+ function matchesIgnoreSelectors(element, ignoreSelectors) {
492
+ return ignoreSelectors.some((selector) => {
493
+ try {
494
+ return element.matches(selector) || !!element.closest(selector);
495
+ } catch {
496
+ return false;
497
+ }
498
+ });
499
+ }
500
+ function isContainerElement(element, rootElement) {
501
+ const tagName = element.tagName.toLowerCase();
502
+ if (tagName === "html" || tagName === "body") {
503
+ return true;
504
+ }
505
+ if (element === rootElement) {
506
+ return true;
507
+ }
508
+ return false;
509
+ }
510
+ function getElementSummary(element) {
511
+ if (!element) return "null";
512
+ const tagName = element.tagName.toLowerCase();
513
+ const id = element.id ? `#${element.id}` : "";
514
+ const className = typeof element.className === "string" && element.className.trim() ? `.${element.className.trim().split(/\s+/).join(".")}` : "";
515
+ return `${tagName}${id}${className}`;
516
+ }
517
+ function calculateBlankScore(sampledElements, rootElement, ignoreSelectors) {
518
+ let blankCount = 0;
519
+ const domSummary = sampledElements.map(({ element }) => {
520
+ if (!element) {
521
+ blankCount += 1;
522
+ return "null";
523
+ }
524
+ if (matchesIgnoreSelectors(element, ignoreSelectors)) {
525
+ blankCount += 1;
526
+ return `${getElementSummary(element)}(ignored)`;
527
+ }
528
+ if (isContainerElement(element, rootElement)) {
529
+ blankCount += 1;
530
+ return `${getElementSummary(element)}(container)`;
531
+ }
532
+ return getElementSummary(element);
533
+ });
534
+ return {
535
+ score: sampledElements.length ? blankCount / sampledElements.length : 0,
536
+ domSummary
537
+ };
538
+ }
539
+
540
+ // ../monitor-plugin-blank-screen/src/detect.ts
541
+ function runBlankScreenCheck(options) {
542
+ const {
543
+ rootSelector,
544
+ scoreThreshold = 0.8,
545
+ samplePoints,
546
+ ignoreSelectors = []
547
+ } = options;
548
+ const rootElement = getRootElement(rootSelector);
549
+ const points = getSamplePoints(samplePoints);
550
+ const sampledElements = sampleElements(points);
551
+ const { score, domSummary } = calculateBlankScore(
552
+ sampledElements,
553
+ rootElement,
554
+ ignoreSelectors
555
+ );
556
+ if (score < scoreThreshold) {
557
+ return null;
558
+ }
559
+ return {
560
+ score,
561
+ rootSelector,
562
+ domSummary
563
+ };
564
+ }
565
+
566
+ // ../monitor-plugin-blank-screen/src/normalize.ts
567
+ function createBlankScreenEvent({
568
+ score,
569
+ rootSelector,
570
+ domSummary,
571
+ trigger
572
+ }) {
573
+ return {
574
+ eventId: "",
575
+ eventType: "blank_screen",
576
+ appId: "",
577
+ env: "",
578
+ url: "",
579
+ pathname: "",
580
+ title: "",
581
+ timestamp: 0,
582
+ userAgent: "",
583
+ blankScreen: {
584
+ score,
585
+ rootSelector,
586
+ domSummary,
587
+ readyState: document.readyState,
588
+ trigger
589
+ }
590
+ };
591
+ }
592
+
593
+ // ../monitor-plugin-blank-screen/src/route-change.ts
594
+ function registerRouteChangeListener(onRouteChange) {
595
+ const originalPushState = history.pushState;
596
+ const originalReplaceState = history.replaceState;
597
+ const handleRouteChange = () => {
598
+ onRouteChange();
599
+ };
600
+ history.pushState = function(...args) {
601
+ const result = originalPushState.apply(this, args);
602
+ handleRouteChange();
603
+ return result;
604
+ };
605
+ history.replaceState = function(...args) {
606
+ const result = originalReplaceState.apply(this, args);
607
+ handleRouteChange();
608
+ return result;
609
+ };
610
+ window.addEventListener("popstate", handleRouteChange);
611
+ window.addEventListener("hashchange", handleRouteChange);
612
+ return () => {
613
+ history.pushState = originalPushState;
614
+ history.replaceState = originalReplaceState;
615
+ window.removeEventListener("popstate", handleRouteChange);
616
+ window.removeEventListener("hashchange", handleRouteChange);
617
+ };
618
+ }
619
+
620
+ // ../monitor-plugin-blank-screen/src/index.ts
621
+ function blankScreenPlugin(options = {}) {
622
+ const {
623
+ delayMs = 3e3,
624
+ detectOnRouteChange = true,
625
+ routeChangeDelayMs = 2e3,
626
+ dedupeWindowMs = 1e4
627
+ } = options;
628
+ return {
629
+ name: "blank-screen-plugin",
630
+ setup({ api }) {
631
+ if (typeof window === "undefined" || typeof document === "undefined") {
632
+ return;
633
+ }
634
+ const dedupe = createBlankScreenDedupe(dedupeWindowMs);
635
+ const emitIfNeeded = (trigger) => {
636
+ dedupe.cleanup();
637
+ const result = runBlankScreenCheck(options);
638
+ if (!result) {
639
+ return;
640
+ }
641
+ const pathname = window.location.pathname;
642
+ const shouldReport = dedupe.shouldReport({
643
+ pathname,
644
+ trigger,
645
+ score: result.score
646
+ });
647
+ if (!shouldReport) {
648
+ return;
649
+ }
650
+ api.emit(
651
+ createBlankScreenEvent({
652
+ score: result.score,
653
+ rootSelector: result.rootSelector,
654
+ domSummary: result.domSummary,
655
+ trigger
656
+ })
657
+ );
658
+ };
659
+ const initialTimer = window.setTimeout(() => {
660
+ emitIfNeeded("initial");
661
+ }, delayMs);
662
+ let routeTimer = null;
663
+ const disposeRouteChange = detectOnRouteChange ? registerRouteChangeListener(() => {
664
+ if (routeTimer !== null) {
665
+ window.clearTimeout(routeTimer);
666
+ }
667
+ routeTimer = window.setTimeout(() => {
668
+ emitIfNeeded("route_change");
669
+ }, routeChangeDelayMs);
670
+ }) : () => {
671
+ };
672
+ return () => {
673
+ window.clearTimeout(initialTimer);
674
+ if (routeTimer !== null) {
675
+ window.clearTimeout(routeTimer);
676
+ }
677
+ disposeRouteChange();
678
+ };
679
+ }
680
+ };
681
+ }
682
+ // Annotate the CommonJS export names for ESM import in node:
683
+ 0 && (module.exports = {
684
+ Monitor,
685
+ blankScreenPlugin,
686
+ errorPlugin,
687
+ initMonitor,
688
+ networkPlugin
689
+ });
690
+ //# sourceMappingURL=index.js.map