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