miaoda-react-devkit 0.1.1-beta.8 → 0.1.1-beta.9

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.cjs CHANGED
@@ -30,18 +30,14 @@ __export(src_exports, {
30
30
  DEFAULT_PGREST_WHITELIST_CODES: () => DEFAULT_PGREST_WHITELIST_CODES,
31
31
  SentryCapture: () => SentryCapture,
32
32
  createNoopSubscriber: () => createNoopSubscriber,
33
- createPostMessageSubscriber: () => createPostMessageSubscriber
33
+ createPostMessageSubscriber: () => createPostMessageSubscriber,
34
+ createSentryEventSubscriber: () => createSentryEventSubscriber
34
35
  });
35
36
  module.exports = __toCommonJS(src_exports);
36
37
 
37
38
  // src/capture/console.ts
38
39
  var import_core = require("@sentry/core");
39
- var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
40
- "Sentry initialized successfully",
41
- "[vite] ",
42
- "Download the React DevTools for a better development experience"
43
- ];
44
- function serializeArg(arg) {
40
+ function formatConsoleArg(arg) {
45
41
  if (typeof arg === "string") return arg;
46
42
  if (arg instanceof Error) return arg.message;
47
43
  try {
@@ -50,9 +46,17 @@ function serializeArg(arg) {
50
46
  return String(arg);
51
47
  }
52
48
  }
49
+ function formatConsoleArgs(args) {
50
+ return args.map(formatConsoleArg).join(" ");
51
+ }
52
+ var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
53
+ "Sentry initialized successfully",
54
+ "[vite] ",
55
+ "Download the React DevTools for a better development experience"
56
+ ];
53
57
  function shouldFilterConsole(args, keywords) {
54
58
  if (keywords.length === 0) return false;
55
- const text = args.map(serializeArg).join(" ");
59
+ const text = formatConsoleArgs(args);
56
60
  return keywords.some((kw) => text.includes(kw));
57
61
  }
58
62
  function shouldFilterConsoleMessage(message, keywords) {
@@ -68,9 +72,20 @@ function createConsoleObserver(keywords, subscribers) {
68
72
  for (const sub of subscribers) sub.onConsole(info);
69
73
  });
70
74
  },
71
- beforeBreadcrumb(breadcrumb, _hint) {
75
+ beforeBreadcrumb(breadcrumb, hint) {
72
76
  if (breadcrumb.category === "console" && breadcrumb.message != null) {
73
77
  if (shouldFilterConsoleMessage(breadcrumb.message, keywords)) return null;
78
+ const h = hint;
79
+ const consoleType = h?.level ?? "log";
80
+ const stacks = (h?.input ?? []).filter((arg) => arg instanceof Error && arg.stack != null).map((err) => err.stack);
81
+ const originalMessage = breadcrumb.message;
82
+ breadcrumb.message = `[${consoleType}]${originalMessage}`;
83
+ breadcrumb.data = {
84
+ ...breadcrumb.data ?? {},
85
+ consoleType,
86
+ message: originalMessage,
87
+ ...stacks.length > 0 ? { stack: stacks.join("\n\n") } : {}
88
+ };
74
89
  }
75
90
  return breadcrumb;
76
91
  }
@@ -116,6 +131,16 @@ function getFetchRequestArgBody(fetchArgs = []) {
116
131
  return fetchArgs[1].body;
117
132
  }
118
133
 
134
+ // src/utils.ts
135
+ function stripUrlOrigin(url) {
136
+ try {
137
+ const u = new URL(url);
138
+ return u.pathname + u.search + u.hash;
139
+ } catch {
140
+ return url;
141
+ }
142
+ }
143
+
119
144
  // src/capture/pgrest.ts
120
145
  var DEFAULT_PGREST_URL_PATTERNS = [/\/rest\/v1\//];
121
146
  var DEFAULT_PGREST_WHITELIST_CODES = [
@@ -194,6 +219,10 @@ function parseAuthErrorBody(body) {
194
219
 
195
220
  // src/capture/network.ts
196
221
  var BODY_TRUNCATE_LIMIT = 2e3;
222
+ function calcDuration(hint) {
223
+ if (hint?.startTimestamp == null || hint?.endTimestamp == null) return void 0;
224
+ return Math.round((hint.endTimestamp - hint.startTimestamp) * 1e3);
225
+ }
197
226
  var DEFAULT_IGNORE_URLS = [
198
227
  /\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|map)(\?.*)?$/,
199
228
  /\.chunk\./,
@@ -243,7 +272,15 @@ function handleXhrBreadcrumb(breadcrumb, hint, handler) {
243
272
  breadcrumb.data["requestBody"] = requestBody;
244
273
  breadcrumb.data["responseBody"] = responseBody;
245
274
  }
246
- void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError });
275
+ const duration = calcDuration(hint);
276
+ const relativeUrl = stripUrlOrigin(url);
277
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
278
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
279
+ breadcrumb.message = `XHR ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
280
+ if (breadcrumb.data) {
281
+ breadcrumb.data["duration"] = duration;
282
+ }
283
+ void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError, duration });
247
284
  }
248
285
  async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
249
286
  const data = breadcrumb.data;
@@ -253,19 +290,24 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
253
290
  const isError = hint?.data != null;
254
291
  const response = hint?.response;
255
292
  const cause = hint?.data instanceof Error ? hint.data : void 0;
256
- const fetchArgs = hint?.input;
257
- const reqBody = getFetchRequestArgBody(fetchArgs ?? []);
293
+ const reqBody = getFetchRequestArgBody(hint?.input ?? []);
258
294
  const [rawRequestBody] = getBodyString(reqBody);
259
295
  const requestBody = rawRequestBody != null ? truncateBody(rawRequestBody) : void 0;
296
+ const duration = calcDuration(hint);
297
+ const relativeUrl = stripUrlOrigin(url);
298
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
299
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
300
+ breadcrumb.message = `Fetch ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
260
301
  if (breadcrumb.data) {
261
302
  breadcrumb.data["requestBody"] = requestBody;
303
+ breadcrumb.data["duration"] = duration;
262
304
  }
263
305
  const contentType = response?.headers?.get("content-type") ?? "";
264
306
  if (isStreamByContentType(contentType)) {
265
307
  if (breadcrumb.data) {
266
308
  breadcrumb.data["responseBody"] = "[streaming response - not captured]";
267
309
  }
268
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause });
310
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause, duration });
269
311
  return;
270
312
  }
271
313
  let responseBody;
@@ -285,7 +327,7 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
285
327
  if (breadcrumb.data) {
286
328
  breadcrumb.data["responseBody"] = responseBody;
287
329
  }
288
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause });
330
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause, duration });
289
331
  }
290
332
  function createNetworkObserver(opts, subscribers) {
291
333
  const shouldIgnore = createUrlMatcher(opts.ignoreUrls);
@@ -365,10 +407,11 @@ function createNetworkObserver(opts, subscribers) {
365
407
  const fetchHandler = makeHandler("fetch");
366
408
  client.on("beforeAddBreadcrumb", (breadcrumb, hint) => {
367
409
  const url = breadcrumb.data?.url ?? "";
368
- if (shouldIgnore(url)) return;
369
410
  if (breadcrumb.category === "xhr") {
411
+ if (shouldIgnore(url)) return;
370
412
  handleXhrBreadcrumb(breadcrumb, hint, xhrHandler);
371
413
  } else if (breadcrumb.category === "fetch") {
414
+ if (shouldIgnore(url)) return;
372
415
  void handleFetchBreadcrumb(breadcrumb, hint, fetchHandler);
373
416
  }
374
417
  });
@@ -464,7 +507,7 @@ var PostMessageSubscriber = class {
464
507
  // postMessage 场景不需要上报 network 日志
465
508
  onNetworkRequest(_info) {
466
509
  }
467
- onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody }) {
510
+ onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody, precedingBreadcrumbs }) {
468
511
  const urlPath = extractUrlPath(url);
469
512
  const code = pgRestError.code;
470
513
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [PgRest:${code}]`;
@@ -487,12 +530,13 @@ var PostMessageSubscriber = class {
487
530
  pgRestCode: code,
488
531
  pgRestDetails: pgRestError.details ?? void 0,
489
532
  pgRestHint: pgRestError.hint ?? void 0,
490
- requestType: type
533
+ requestType: type,
534
+ precedingBreadcrumbs
491
535
  }
492
536
  };
493
537
  this.send(msg, "*");
494
538
  }
495
- onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody }) {
539
+ onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody, precedingBreadcrumbs }) {
496
540
  const urlPath = extractUrlPath(url);
497
541
  const code = authError.code;
498
542
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [Auth:${code}]`;
@@ -514,7 +558,8 @@ var PostMessageSubscriber = class {
514
558
  responseBody,
515
559
  authCode: code,
516
560
  authRequestId: authError.requestId ?? void 0,
517
- requestType: type
561
+ requestType: type,
562
+ precedingBreadcrumbs
518
563
  }
519
564
  };
520
565
  this.send(msg, "*");
@@ -539,6 +584,75 @@ function createNoopSubscriber() {
539
584
  }
540
585
  };
541
586
  }
587
+
588
+ // src/subscribers/sentryEventSubscriber.ts
589
+ var import_core4 = require("@sentry/core");
590
+ function toSentryLevel(consoleLevel) {
591
+ switch (consoleLevel) {
592
+ case "error":
593
+ return "error";
594
+ case "warn":
595
+ return "warning";
596
+ case "debug":
597
+ return "debug";
598
+ case "info":
599
+ return "info";
600
+ default:
601
+ return "log";
602
+ }
603
+ }
604
+ var SentryEventSubscriber = class {
605
+ constructor(opts = {}) {
606
+ __publicField(this, "captureAllNetworkRequests");
607
+ this.captureAllNetworkRequests = opts.captureAllNetworkRequests ?? true;
608
+ }
609
+ onConsole(info) {
610
+ const { level, args } = info;
611
+ const formattedMessage = formatConsoleArgs(args);
612
+ const sentryLevel = toSentryLevel(level);
613
+ (0, import_core4.captureEvent)({
614
+ message: `[${level}]${formattedMessage}`,
615
+ level: sentryLevel,
616
+ // 按 level + 消息内容前 100 字符分组,同一类日志聚合为同一个 Issue
617
+ fingerprint: ["console", level, formattedMessage.slice(0, 100)],
618
+ tags: {
619
+ type: "console"
620
+ },
621
+ extra: { consoleType: level, args }
622
+ });
623
+ }
624
+ // Sentry 已自动捕获 JS 错误,不重复上报
625
+ onError(_info) {
626
+ }
627
+ onNetworkRequest(info) {
628
+ const { type, method, url, statusCode, requestBody, responseBody, isError, duration } = info;
629
+ const shouldCapture = this.captureAllNetworkRequests || isError || statusCode != null && statusCode >= 400;
630
+ if (!shouldCapture) return;
631
+ const urlPath = stripUrlOrigin(url);
632
+ const requestTypeLabel = type === "xhr" ? "XHR" : "Fetch";
633
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
634
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
635
+ const message = `${requestTypeLabel} ${method} ${urlPath} -> ${statusStr}${durationStr}`;
636
+ const level = isError ? "error" : statusCode != null && statusCode >= 400 ? "warning" : "info";
637
+ (0, import_core4.captureEvent)({
638
+ message,
639
+ level,
640
+ // 按 method + url 路径固定分组,同一接口的多次报错聚合为同一个 Issue
641
+ fingerprint: ["network", method, urlPath],
642
+ tags: {
643
+ type: "network"
644
+ },
645
+ extra: { url, method, statusCode, duration, requestBody, responseBody }
646
+ });
647
+ }
648
+ onPgRestWhitelistError(_info) {
649
+ }
650
+ onAuthWhitelistError(_info) {
651
+ }
652
+ };
653
+ function createSentryEventSubscriber(opts) {
654
+ return new SentryEventSubscriber(opts);
655
+ }
542
656
  // Annotate the CommonJS export names for ESM import in node:
543
657
  0 && (module.exports = {
544
658
  DEFAULT_AUTH_URL_PATTERNS,
@@ -549,5 +663,6 @@ function createNoopSubscriber() {
549
663
  DEFAULT_PGREST_WHITELIST_CODES,
550
664
  SentryCapture,
551
665
  createNoopSubscriber,
552
- createPostMessageSubscriber
666
+ createPostMessageSubscriber,
667
+ createSentryEventSubscriber
553
668
  });
package/dist/index.d.cts CHANGED
@@ -91,6 +91,11 @@ interface INetworkRequestInfo {
91
91
  * XHR 网络失败时 Sentry hint 中不携带 Error 对象,此字段为 undefined。
92
92
  */
93
93
  cause?: Error;
94
+ /**
95
+ * 请求持续时间(毫秒),由 hint.startTimestamp / hint.endTimestamp 计算。
96
+ * 无法获取时间信息时为 undefined。
97
+ */
98
+ duration?: number;
94
99
  }
95
100
  /**
96
101
  * 捕获到 PostgREST 白名单错误时的事件数据。
@@ -237,6 +242,7 @@ interface GlobalErrorMessage {
237
242
  /** AuthWhitelistError 专属字段 */
238
243
  authCode?: string;
239
244
  authRequestId?: string;
245
+ precedingBreadcrumbs?: Breadcrumb[];
240
246
  };
241
247
  }
242
248
  type PostMessageFn = (message: GlobalErrorMessage, targetOrigin: string) => void;
@@ -294,4 +300,36 @@ declare function createPostMessageSubscriber(send?: PostMessageFn): ICaptureSubs
294
300
  /** 创建一个什么都不做的订阅者,方便测试时按需 spy 或替换单个方法。 */
295
301
  declare function createNoopSubscriber(): ICaptureSubscriber;
296
302
 
297
- export { DEFAULT_AUTH_URL_PATTERNS, DEFAULT_AUTH_WHITELIST_CODES, DEFAULT_CONSOLE_FILTER_KEYWORDS, DEFAULT_IGNORE_URLS, DEFAULT_PGREST_URL_PATTERNS, DEFAULT_PGREST_WHITELIST_CODES, type GlobalErrorMessage, type IAuthErrorBody, type IAuthWhitelistErrorInfo, type ICaptureSubscriber, type IConsoleCaptureInfo, type IErrorCaptureInfo, type INetworkRequestInfo, type IPgRestErrorBody, type IPgRestWhitelistErrorInfo, type ISentryCaptureOptions, type PostMessageFn, SentryCapture, createNoopSubscriber, createPostMessageSubscriber };
303
+ /**
304
+ * 通过 Sentry.captureEvent 为每条 console 日志和网络请求创建独立 Sentry Event 的订阅者。
305
+ *
306
+ * - console.* → 一条 Sentry Event,level 与 console 级别对应
307
+ * - 网络请求 → 一条 Sentry Event,message 格式为 "Fetch POST /path -> 409 (32ms)"
308
+ *
309
+ * onError 不处理,Sentry 已自动捕获并上报 JS 错误,无需重复 captureEvent。
310
+ */
311
+
312
+ interface ISentryEventSubscriberOptions {
313
+ /**
314
+ * 是否为所有网络请求(包括 2xx/3xx)创建 Sentry Event。
315
+ * 默认 true(与 vite-plugin-monitor 旧版行为一致)。
316
+ * 设为 false 时仅为 4xx、5xx 以及网络层失败创建 Event。
317
+ */
318
+ captureAllNetworkRequests?: boolean;
319
+ }
320
+ /**
321
+ * 为每条 console 日志和网络请求创建独立 Sentry Event 的订阅者。
322
+ *
323
+ * @example
324
+ * ```ts
325
+ * const capture = new SentryCapture({
326
+ * consoleFilterKeywords: DEFAULT_CONSOLE_FILTER_KEYWORDS,
327
+ * ignoreUrls: DEFAULT_IGNORE_URLS,
328
+ * });
329
+ * capture.addSubscriber(createSentryEventSubscriber());
330
+ * capture.addSubscriber(createPostMessageSubscriber());
331
+ * ```
332
+ */
333
+ declare function createSentryEventSubscriber(opts?: ISentryEventSubscriberOptions): ICaptureSubscriber;
334
+
335
+ export { DEFAULT_AUTH_URL_PATTERNS, DEFAULT_AUTH_WHITELIST_CODES, DEFAULT_CONSOLE_FILTER_KEYWORDS, DEFAULT_IGNORE_URLS, DEFAULT_PGREST_URL_PATTERNS, DEFAULT_PGREST_WHITELIST_CODES, type GlobalErrorMessage, type IAuthErrorBody, type IAuthWhitelistErrorInfo, type ICaptureSubscriber, type IConsoleCaptureInfo, type IErrorCaptureInfo, type INetworkRequestInfo, type IPgRestErrorBody, type IPgRestWhitelistErrorInfo, type ISentryCaptureOptions, type ISentryEventSubscriberOptions, type PostMessageFn, SentryCapture, createNoopSubscriber, createPostMessageSubscriber, createSentryEventSubscriber };
package/dist/index.d.ts CHANGED
@@ -91,6 +91,11 @@ interface INetworkRequestInfo {
91
91
  * XHR 网络失败时 Sentry hint 中不携带 Error 对象,此字段为 undefined。
92
92
  */
93
93
  cause?: Error;
94
+ /**
95
+ * 请求持续时间(毫秒),由 hint.startTimestamp / hint.endTimestamp 计算。
96
+ * 无法获取时间信息时为 undefined。
97
+ */
98
+ duration?: number;
94
99
  }
95
100
  /**
96
101
  * 捕获到 PostgREST 白名单错误时的事件数据。
@@ -237,6 +242,7 @@ interface GlobalErrorMessage {
237
242
  /** AuthWhitelistError 专属字段 */
238
243
  authCode?: string;
239
244
  authRequestId?: string;
245
+ precedingBreadcrumbs?: Breadcrumb[];
240
246
  };
241
247
  }
242
248
  type PostMessageFn = (message: GlobalErrorMessage, targetOrigin: string) => void;
@@ -294,4 +300,36 @@ declare function createPostMessageSubscriber(send?: PostMessageFn): ICaptureSubs
294
300
  /** 创建一个什么都不做的订阅者,方便测试时按需 spy 或替换单个方法。 */
295
301
  declare function createNoopSubscriber(): ICaptureSubscriber;
296
302
 
297
- export { DEFAULT_AUTH_URL_PATTERNS, DEFAULT_AUTH_WHITELIST_CODES, DEFAULT_CONSOLE_FILTER_KEYWORDS, DEFAULT_IGNORE_URLS, DEFAULT_PGREST_URL_PATTERNS, DEFAULT_PGREST_WHITELIST_CODES, type GlobalErrorMessage, type IAuthErrorBody, type IAuthWhitelistErrorInfo, type ICaptureSubscriber, type IConsoleCaptureInfo, type IErrorCaptureInfo, type INetworkRequestInfo, type IPgRestErrorBody, type IPgRestWhitelistErrorInfo, type ISentryCaptureOptions, type PostMessageFn, SentryCapture, createNoopSubscriber, createPostMessageSubscriber };
303
+ /**
304
+ * 通过 Sentry.captureEvent 为每条 console 日志和网络请求创建独立 Sentry Event 的订阅者。
305
+ *
306
+ * - console.* → 一条 Sentry Event,level 与 console 级别对应
307
+ * - 网络请求 → 一条 Sentry Event,message 格式为 "Fetch POST /path -> 409 (32ms)"
308
+ *
309
+ * onError 不处理,Sentry 已自动捕获并上报 JS 错误,无需重复 captureEvent。
310
+ */
311
+
312
+ interface ISentryEventSubscriberOptions {
313
+ /**
314
+ * 是否为所有网络请求(包括 2xx/3xx)创建 Sentry Event。
315
+ * 默认 true(与 vite-plugin-monitor 旧版行为一致)。
316
+ * 设为 false 时仅为 4xx、5xx 以及网络层失败创建 Event。
317
+ */
318
+ captureAllNetworkRequests?: boolean;
319
+ }
320
+ /**
321
+ * 为每条 console 日志和网络请求创建独立 Sentry Event 的订阅者。
322
+ *
323
+ * @example
324
+ * ```ts
325
+ * const capture = new SentryCapture({
326
+ * consoleFilterKeywords: DEFAULT_CONSOLE_FILTER_KEYWORDS,
327
+ * ignoreUrls: DEFAULT_IGNORE_URLS,
328
+ * });
329
+ * capture.addSubscriber(createSentryEventSubscriber());
330
+ * capture.addSubscriber(createPostMessageSubscriber());
331
+ * ```
332
+ */
333
+ declare function createSentryEventSubscriber(opts?: ISentryEventSubscriberOptions): ICaptureSubscriber;
334
+
335
+ export { DEFAULT_AUTH_URL_PATTERNS, DEFAULT_AUTH_WHITELIST_CODES, DEFAULT_CONSOLE_FILTER_KEYWORDS, DEFAULT_IGNORE_URLS, DEFAULT_PGREST_URL_PATTERNS, DEFAULT_PGREST_WHITELIST_CODES, type GlobalErrorMessage, type IAuthErrorBody, type IAuthWhitelistErrorInfo, type ICaptureSubscriber, type IConsoleCaptureInfo, type IErrorCaptureInfo, type INetworkRequestInfo, type IPgRestErrorBody, type IPgRestWhitelistErrorInfo, type ISentryCaptureOptions, type ISentryEventSubscriberOptions, type PostMessageFn, SentryCapture, createNoopSubscriber, createPostMessageSubscriber, createSentryEventSubscriber };
package/dist/index.js CHANGED
@@ -4,12 +4,7 @@ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "sy
4
4
 
5
5
  // src/capture/console.ts
6
6
  import { addConsoleInstrumentationHandler } from "@sentry/core";
7
- var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
8
- "Sentry initialized successfully",
9
- "[vite] ",
10
- "Download the React DevTools for a better development experience"
11
- ];
12
- function serializeArg(arg) {
7
+ function formatConsoleArg(arg) {
13
8
  if (typeof arg === "string") return arg;
14
9
  if (arg instanceof Error) return arg.message;
15
10
  try {
@@ -18,9 +13,17 @@ function serializeArg(arg) {
18
13
  return String(arg);
19
14
  }
20
15
  }
16
+ function formatConsoleArgs(args) {
17
+ return args.map(formatConsoleArg).join(" ");
18
+ }
19
+ var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
20
+ "Sentry initialized successfully",
21
+ "[vite] ",
22
+ "Download the React DevTools for a better development experience"
23
+ ];
21
24
  function shouldFilterConsole(args, keywords) {
22
25
  if (keywords.length === 0) return false;
23
- const text = args.map(serializeArg).join(" ");
26
+ const text = formatConsoleArgs(args);
24
27
  return keywords.some((kw) => text.includes(kw));
25
28
  }
26
29
  function shouldFilterConsoleMessage(message, keywords) {
@@ -36,9 +39,20 @@ function createConsoleObserver(keywords, subscribers) {
36
39
  for (const sub of subscribers) sub.onConsole(info);
37
40
  });
38
41
  },
39
- beforeBreadcrumb(breadcrumb, _hint) {
42
+ beforeBreadcrumb(breadcrumb, hint) {
40
43
  if (breadcrumb.category === "console" && breadcrumb.message != null) {
41
44
  if (shouldFilterConsoleMessage(breadcrumb.message, keywords)) return null;
45
+ const h = hint;
46
+ const consoleType = h?.level ?? "log";
47
+ const stacks = (h?.input ?? []).filter((arg) => arg instanceof Error && arg.stack != null).map((err) => err.stack);
48
+ const originalMessage = breadcrumb.message;
49
+ breadcrumb.message = `[${consoleType}]${originalMessage}`;
50
+ breadcrumb.data = {
51
+ ...breadcrumb.data ?? {},
52
+ consoleType,
53
+ message: originalMessage,
54
+ ...stacks.length > 0 ? { stack: stacks.join("\n\n") } : {}
55
+ };
42
56
  }
43
57
  return breadcrumb;
44
58
  }
@@ -84,6 +98,16 @@ function getFetchRequestArgBody(fetchArgs = []) {
84
98
  return fetchArgs[1].body;
85
99
  }
86
100
 
101
+ // src/utils.ts
102
+ function stripUrlOrigin(url) {
103
+ try {
104
+ const u = new URL(url);
105
+ return u.pathname + u.search + u.hash;
106
+ } catch {
107
+ return url;
108
+ }
109
+ }
110
+
87
111
  // src/capture/pgrest.ts
88
112
  var DEFAULT_PGREST_URL_PATTERNS = [/\/rest\/v1\//];
89
113
  var DEFAULT_PGREST_WHITELIST_CODES = [
@@ -162,6 +186,10 @@ function parseAuthErrorBody(body) {
162
186
 
163
187
  // src/capture/network.ts
164
188
  var BODY_TRUNCATE_LIMIT = 2e3;
189
+ function calcDuration(hint) {
190
+ if (hint?.startTimestamp == null || hint?.endTimestamp == null) return void 0;
191
+ return Math.round((hint.endTimestamp - hint.startTimestamp) * 1e3);
192
+ }
165
193
  var DEFAULT_IGNORE_URLS = [
166
194
  /\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|map)(\?.*)?$/,
167
195
  /\.chunk\./,
@@ -211,7 +239,15 @@ function handleXhrBreadcrumb(breadcrumb, hint, handler) {
211
239
  breadcrumb.data["requestBody"] = requestBody;
212
240
  breadcrumb.data["responseBody"] = responseBody;
213
241
  }
214
- void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError });
242
+ const duration = calcDuration(hint);
243
+ const relativeUrl = stripUrlOrigin(url);
244
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
245
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
246
+ breadcrumb.message = `XHR ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
247
+ if (breadcrumb.data) {
248
+ breadcrumb.data["duration"] = duration;
249
+ }
250
+ void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError, duration });
215
251
  }
216
252
  async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
217
253
  const data = breadcrumb.data;
@@ -221,19 +257,24 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
221
257
  const isError = hint?.data != null;
222
258
  const response = hint?.response;
223
259
  const cause = hint?.data instanceof Error ? hint.data : void 0;
224
- const fetchArgs = hint?.input;
225
- const reqBody = getFetchRequestArgBody(fetchArgs ?? []);
260
+ const reqBody = getFetchRequestArgBody(hint?.input ?? []);
226
261
  const [rawRequestBody] = getBodyString(reqBody);
227
262
  const requestBody = rawRequestBody != null ? truncateBody(rawRequestBody) : void 0;
263
+ const duration = calcDuration(hint);
264
+ const relativeUrl = stripUrlOrigin(url);
265
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
266
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
267
+ breadcrumb.message = `Fetch ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
228
268
  if (breadcrumb.data) {
229
269
  breadcrumb.data["requestBody"] = requestBody;
270
+ breadcrumb.data["duration"] = duration;
230
271
  }
231
272
  const contentType = response?.headers?.get("content-type") ?? "";
232
273
  if (isStreamByContentType(contentType)) {
233
274
  if (breadcrumb.data) {
234
275
  breadcrumb.data["responseBody"] = "[streaming response - not captured]";
235
276
  }
236
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause });
277
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause, duration });
237
278
  return;
238
279
  }
239
280
  let responseBody;
@@ -253,7 +294,7 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
253
294
  if (breadcrumb.data) {
254
295
  breadcrumb.data["responseBody"] = responseBody;
255
296
  }
256
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause });
297
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause, duration });
257
298
  }
258
299
  function createNetworkObserver(opts, subscribers) {
259
300
  const shouldIgnore = createUrlMatcher(opts.ignoreUrls);
@@ -333,10 +374,11 @@ function createNetworkObserver(opts, subscribers) {
333
374
  const fetchHandler = makeHandler("fetch");
334
375
  client.on("beforeAddBreadcrumb", (breadcrumb, hint) => {
335
376
  const url = breadcrumb.data?.url ?? "";
336
- if (shouldIgnore(url)) return;
337
377
  if (breadcrumb.category === "xhr") {
378
+ if (shouldIgnore(url)) return;
338
379
  handleXhrBreadcrumb(breadcrumb, hint, xhrHandler);
339
380
  } else if (breadcrumb.category === "fetch") {
381
+ if (shouldIgnore(url)) return;
340
382
  void handleFetchBreadcrumb(breadcrumb, hint, fetchHandler);
341
383
  }
342
384
  });
@@ -432,7 +474,7 @@ var PostMessageSubscriber = class {
432
474
  // postMessage 场景不需要上报 network 日志
433
475
  onNetworkRequest(_info) {
434
476
  }
435
- onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody }) {
477
+ onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody, precedingBreadcrumbs }) {
436
478
  const urlPath = extractUrlPath(url);
437
479
  const code = pgRestError.code;
438
480
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [PgRest:${code}]`;
@@ -455,12 +497,13 @@ var PostMessageSubscriber = class {
455
497
  pgRestCode: code,
456
498
  pgRestDetails: pgRestError.details ?? void 0,
457
499
  pgRestHint: pgRestError.hint ?? void 0,
458
- requestType: type
500
+ requestType: type,
501
+ precedingBreadcrumbs
459
502
  }
460
503
  };
461
504
  this.send(msg, "*");
462
505
  }
463
- onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody }) {
506
+ onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody, precedingBreadcrumbs }) {
464
507
  const urlPath = extractUrlPath(url);
465
508
  const code = authError.code;
466
509
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [Auth:${code}]`;
@@ -482,7 +525,8 @@ var PostMessageSubscriber = class {
482
525
  responseBody,
483
526
  authCode: code,
484
527
  authRequestId: authError.requestId ?? void 0,
485
- requestType: type
528
+ requestType: type,
529
+ precedingBreadcrumbs
486
530
  }
487
531
  };
488
532
  this.send(msg, "*");
@@ -507,6 +551,75 @@ function createNoopSubscriber() {
507
551
  }
508
552
  };
509
553
  }
554
+
555
+ // src/subscribers/sentryEventSubscriber.ts
556
+ import { captureEvent } from "@sentry/core";
557
+ function toSentryLevel(consoleLevel) {
558
+ switch (consoleLevel) {
559
+ case "error":
560
+ return "error";
561
+ case "warn":
562
+ return "warning";
563
+ case "debug":
564
+ return "debug";
565
+ case "info":
566
+ return "info";
567
+ default:
568
+ return "log";
569
+ }
570
+ }
571
+ var SentryEventSubscriber = class {
572
+ constructor(opts = {}) {
573
+ __publicField(this, "captureAllNetworkRequests");
574
+ this.captureAllNetworkRequests = opts.captureAllNetworkRequests ?? true;
575
+ }
576
+ onConsole(info) {
577
+ const { level, args } = info;
578
+ const formattedMessage = formatConsoleArgs(args);
579
+ const sentryLevel = toSentryLevel(level);
580
+ captureEvent({
581
+ message: `[${level}]${formattedMessage}`,
582
+ level: sentryLevel,
583
+ // 按 level + 消息内容前 100 字符分组,同一类日志聚合为同一个 Issue
584
+ fingerprint: ["console", level, formattedMessage.slice(0, 100)],
585
+ tags: {
586
+ type: "console"
587
+ },
588
+ extra: { consoleType: level, args }
589
+ });
590
+ }
591
+ // Sentry 已自动捕获 JS 错误,不重复上报
592
+ onError(_info) {
593
+ }
594
+ onNetworkRequest(info) {
595
+ const { type, method, url, statusCode, requestBody, responseBody, isError, duration } = info;
596
+ const shouldCapture = this.captureAllNetworkRequests || isError || statusCode != null && statusCode >= 400;
597
+ if (!shouldCapture) return;
598
+ const urlPath = stripUrlOrigin(url);
599
+ const requestTypeLabel = type === "xhr" ? "XHR" : "Fetch";
600
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
601
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
602
+ const message = `${requestTypeLabel} ${method} ${urlPath} -> ${statusStr}${durationStr}`;
603
+ const level = isError ? "error" : statusCode != null && statusCode >= 400 ? "warning" : "info";
604
+ captureEvent({
605
+ message,
606
+ level,
607
+ // 按 method + url 路径固定分组,同一接口的多次报错聚合为同一个 Issue
608
+ fingerprint: ["network", method, urlPath],
609
+ tags: {
610
+ type: "network"
611
+ },
612
+ extra: { url, method, statusCode, duration, requestBody, responseBody }
613
+ });
614
+ }
615
+ onPgRestWhitelistError(_info) {
616
+ }
617
+ onAuthWhitelistError(_info) {
618
+ }
619
+ };
620
+ function createSentryEventSubscriber(opts) {
621
+ return new SentryEventSubscriber(opts);
622
+ }
510
623
  export {
511
624
  DEFAULT_AUTH_URL_PATTERNS,
512
625
  DEFAULT_AUTH_WHITELIST_CODES,
@@ -516,5 +629,6 @@ export {
516
629
  DEFAULT_PGREST_WHITELIST_CODES,
517
630
  SentryCapture,
518
631
  createNoopSubscriber,
519
- createPostMessageSubscriber
632
+ createPostMessageSubscriber,
633
+ createSentryEventSubscriber
520
634
  };
@@ -7,12 +7,7 @@ import * as RealSentry from "@sentry/react";
7
7
 
8
8
  // src/capture/console.ts
9
9
  import { addConsoleInstrumentationHandler } from "@sentry/core";
10
- var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
11
- "Sentry initialized successfully",
12
- "[vite] ",
13
- "Download the React DevTools for a better development experience"
14
- ];
15
- function serializeArg(arg) {
10
+ function formatConsoleArg(arg) {
16
11
  if (typeof arg === "string") return arg;
17
12
  if (arg instanceof Error) return arg.message;
18
13
  try {
@@ -21,9 +16,17 @@ function serializeArg(arg) {
21
16
  return String(arg);
22
17
  }
23
18
  }
19
+ function formatConsoleArgs(args) {
20
+ return args.map(formatConsoleArg).join(" ");
21
+ }
22
+ var DEFAULT_CONSOLE_FILTER_KEYWORDS = [
23
+ "Sentry initialized successfully",
24
+ "[vite] ",
25
+ "Download the React DevTools for a better development experience"
26
+ ];
24
27
  function shouldFilterConsole(args, keywords) {
25
28
  if (keywords.length === 0) return false;
26
- const text = args.map(serializeArg).join(" ");
29
+ const text = formatConsoleArgs(args);
27
30
  return keywords.some((kw) => text.includes(kw));
28
31
  }
29
32
  function shouldFilterConsoleMessage(message, keywords) {
@@ -39,9 +42,20 @@ function createConsoleObserver(keywords, subscribers) {
39
42
  for (const sub of subscribers) sub.onConsole(info);
40
43
  });
41
44
  },
42
- beforeBreadcrumb(breadcrumb, _hint) {
45
+ beforeBreadcrumb(breadcrumb, hint) {
43
46
  if (breadcrumb.category === "console" && breadcrumb.message != null) {
44
47
  if (shouldFilterConsoleMessage(breadcrumb.message, keywords)) return null;
48
+ const h = hint;
49
+ const consoleType = h?.level ?? "log";
50
+ const stacks = (h?.input ?? []).filter((arg) => arg instanceof Error && arg.stack != null).map((err) => err.stack);
51
+ const originalMessage = breadcrumb.message;
52
+ breadcrumb.message = `[${consoleType}]${originalMessage}`;
53
+ breadcrumb.data = {
54
+ ...breadcrumb.data ?? {},
55
+ consoleType,
56
+ message: originalMessage,
57
+ ...stacks.length > 0 ? { stack: stacks.join("\n\n") } : {}
58
+ };
45
59
  }
46
60
  return breadcrumb;
47
61
  }
@@ -87,6 +101,16 @@ function getFetchRequestArgBody(fetchArgs = []) {
87
101
  return fetchArgs[1].body;
88
102
  }
89
103
 
104
+ // src/utils.ts
105
+ function stripUrlOrigin(url) {
106
+ try {
107
+ const u = new URL(url);
108
+ return u.pathname + u.search + u.hash;
109
+ } catch {
110
+ return url;
111
+ }
112
+ }
113
+
90
114
  // src/capture/pgrest.ts
91
115
  var DEFAULT_PGREST_URL_PATTERNS = [/\/rest\/v1\//];
92
116
  var DEFAULT_PGREST_WHITELIST_CODES = [
@@ -165,6 +189,10 @@ function parseAuthErrorBody(body) {
165
189
 
166
190
  // src/capture/network.ts
167
191
  var BODY_TRUNCATE_LIMIT = 2e3;
192
+ function calcDuration(hint) {
193
+ if (hint?.startTimestamp == null || hint?.endTimestamp == null) return void 0;
194
+ return Math.round((hint.endTimestamp - hint.startTimestamp) * 1e3);
195
+ }
168
196
  var DEFAULT_IGNORE_URLS = [
169
197
  /\.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot|map)(\?.*)?$/,
170
198
  /\.chunk\./,
@@ -214,7 +242,15 @@ function handleXhrBreadcrumb(breadcrumb, hint, handler) {
214
242
  breadcrumb.data["requestBody"] = requestBody;
215
243
  breadcrumb.data["responseBody"] = responseBody;
216
244
  }
217
- void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError });
245
+ const duration = calcDuration(hint);
246
+ const relativeUrl = stripUrlOrigin(url);
247
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
248
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
249
+ breadcrumb.message = `XHR ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
250
+ if (breadcrumb.data) {
251
+ breadcrumb.data["duration"] = duration;
252
+ }
253
+ void handler({ type: "xhr", method, url, statusCode, requestBody, responseBody, isError, duration });
218
254
  }
219
255
  async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
220
256
  const data = breadcrumb.data;
@@ -224,19 +260,24 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
224
260
  const isError = hint?.data != null;
225
261
  const response = hint?.response;
226
262
  const cause = hint?.data instanceof Error ? hint.data : void 0;
227
- const fetchArgs = hint?.input;
228
- const reqBody = getFetchRequestArgBody(fetchArgs ?? []);
263
+ const reqBody = getFetchRequestArgBody(hint?.input ?? []);
229
264
  const [rawRequestBody] = getBodyString(reqBody);
230
265
  const requestBody = rawRequestBody != null ? truncateBody(rawRequestBody) : void 0;
266
+ const duration = calcDuration(hint);
267
+ const relativeUrl = stripUrlOrigin(url);
268
+ const statusStr = statusCode != null ? String(statusCode) : "failed";
269
+ const durationStr = duration != null ? ` (${duration}ms)` : "";
270
+ breadcrumb.message = `Fetch ${method} ${relativeUrl} -> ${statusStr}${durationStr}`;
231
271
  if (breadcrumb.data) {
232
272
  breadcrumb.data["requestBody"] = requestBody;
273
+ breadcrumb.data["duration"] = duration;
233
274
  }
234
275
  const contentType = response?.headers?.get("content-type") ?? "";
235
276
  if (isStreamByContentType(contentType)) {
236
277
  if (breadcrumb.data) {
237
278
  breadcrumb.data["responseBody"] = "[streaming response - not captured]";
238
279
  }
239
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause });
280
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody: "[streaming response - not captured]", isError, cause, duration });
240
281
  return;
241
282
  }
242
283
  let responseBody;
@@ -256,7 +297,7 @@ async function handleFetchBreadcrumb(breadcrumb, hint, handler) {
256
297
  if (breadcrumb.data) {
257
298
  breadcrumb.data["responseBody"] = responseBody;
258
299
  }
259
- await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause });
300
+ await handler({ type: "fetch", method, url, statusCode, requestBody, responseBody, isError, cause, duration });
260
301
  }
261
302
  function createNetworkObserver(opts, subscribers) {
262
303
  const shouldIgnore = createUrlMatcher(opts.ignoreUrls);
@@ -336,10 +377,11 @@ function createNetworkObserver(opts, subscribers) {
336
377
  const fetchHandler = makeHandler("fetch");
337
378
  client.on("beforeAddBreadcrumb", (breadcrumb, hint) => {
338
379
  const url = breadcrumb.data?.url ?? "";
339
- if (shouldIgnore(url)) return;
340
380
  if (breadcrumb.category === "xhr") {
381
+ if (shouldIgnore(url)) return;
341
382
  handleXhrBreadcrumb(breadcrumb, hint, xhrHandler);
342
383
  } else if (breadcrumb.category === "fetch") {
384
+ if (shouldIgnore(url)) return;
343
385
  void handleFetchBreadcrumb(breadcrumb, hint, fetchHandler);
344
386
  }
345
387
  });
@@ -435,7 +477,7 @@ var PostMessageSubscriber = class {
435
477
  // postMessage 场景不需要上报 network 日志
436
478
  onNetworkRequest(_info) {
437
479
  }
438
- onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody }) {
480
+ onPgRestWhitelistError({ type, method, url, statusCode, pgRestError, requestBody, responseBody, precedingBreadcrumbs }) {
439
481
  const urlPath = extractUrlPath(url);
440
482
  const code = pgRestError.code;
441
483
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [PgRest:${code}]`;
@@ -458,12 +500,13 @@ var PostMessageSubscriber = class {
458
500
  pgRestCode: code,
459
501
  pgRestDetails: pgRestError.details ?? void 0,
460
502
  pgRestHint: pgRestError.hint ?? void 0,
461
- requestType: type
503
+ requestType: type,
504
+ precedingBreadcrumbs
462
505
  }
463
506
  };
464
507
  this.send(msg, "*");
465
508
  }
466
- onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody }) {
509
+ onAuthWhitelistError({ type, method, url, statusCode, authError, requestBody, responseBody, precedingBreadcrumbs }) {
467
510
  const urlPath = extractUrlPath(url);
468
511
  const code = authError.code;
469
512
  const errorMessage = `${method} ${urlPath} -> ${statusCode} [Auth:${code}]`;
@@ -485,7 +528,8 @@ var PostMessageSubscriber = class {
485
528
  responseBody,
486
529
  authCode: code,
487
530
  authRequestId: authError.requestId ?? void 0,
488
- requestType: type
531
+ requestType: type,
532
+ precedingBreadcrumbs
489
533
  }
490
534
  };
491
535
  this.send(msg, "*");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "miaoda-react-devkit",
3
- "version": "0.1.1-beta.8",
3
+ "version": "0.1.1-beta.9",
4
4
  "description": "React admin 应用开发工具集",
5
5
  "license": "MIT",
6
6
  "type": "module",