@lark-apaas/client-toolkit 1.1.2 → 1.1.3-alpha.1

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.
@@ -1,10 +1,10 @@
1
1
  import { logger } from "./logger.js";
2
2
  function interceptGlobalError() {
3
3
  window.addEventListener('error', (event)=>{
4
- logger.error('global error', event);
4
+ logger.error(event.error);
5
5
  });
6
6
  window.addEventListener('unhandledrejection', (event)=>{
7
- logger.error('global unhandledrejection', event);
7
+ logger.error(event.reason);
8
8
  });
9
9
  }
10
10
  export { interceptGlobalError };
@@ -20,94 +20,73 @@ export declare const noCategoryLogSchema: z.ZodObject<{
20
20
  message: z.ZodUnknown;
21
21
  args: z.ZodArray<z.ZodUnknown>;
22
22
  }, z.core.$strip>;
23
+ export declare const logStackFrameSchema: z.ZodObject<{
24
+ functionName: z.ZodString;
25
+ fileName: z.ZodString;
26
+ lineNumber: z.ZodNumber;
27
+ columnNumber: z.ZodNumber;
28
+ }, z.core.$strip>;
23
29
  export declare const levelSchema: z.ZodEnum<{
30
+ success: "success";
24
31
  info: "info";
25
32
  warn: "warn";
26
33
  error: "error";
27
34
  debug: "debug";
28
35
  }>;
36
+ export declare const logMeta: z.ZodObject<{
37
+ stacktrace: z.ZodOptional<z.ZodArray<z.ZodObject<{
38
+ functionName: z.ZodString;
39
+ fileName: z.ZodString;
40
+ lineNumber: z.ZodNumber;
41
+ columnNumber: z.ZodNumber;
42
+ }, z.core.$strip>>>;
43
+ logTraceID: z.ZodOptional<z.ZodString>;
44
+ skipFrame: z.ZodOptional<z.ZodNumber>;
45
+ }, z.core.$strip>;
29
46
  export declare const selectedLogSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
30
- type: z.ZodLiteral<"networkRequest">;
31
- level: z.ZodEnum<{
32
- info: "info";
33
- warn: "warn";
34
- error: "error";
35
- debug: "debug";
36
- }>;
37
- id: z.ZodString;
38
- data: z.ZodObject<{
39
- method: z.ZodString;
40
- status: z.ZodInt;
41
- statusText: z.ZodString;
42
- path: z.ZodString;
43
- requestData: z.ZodOptional<z.ZodUnknown>;
44
- requestParams: z.ZodOptional<z.ZodUnknown>;
45
- responseData: z.ZodOptional<z.ZodUnknown>;
46
- traceID: z.ZodString;
47
- }, z.core.$strip>;
48
- }, z.core.$strip>, z.ZodObject<{
49
- type: z.ZodLiteral<"routerError">;
50
- level: z.ZodEnum<{
51
- info: "info";
52
- warn: "warn";
53
- error: "error";
54
- debug: "debug";
55
- }>;
56
- id: z.ZodString;
57
- data: z.ZodObject<{
58
- path: z.ZodString;
59
- }, z.core.$strip>;
60
- }, z.core.$strip>, z.ZodObject<{
61
- type: z.ZodLiteral<"renderError">;
62
- level: z.ZodEnum<{
63
- info: "info";
64
- warn: "warn";
65
- error: "error";
66
- debug: "debug";
67
- }>;
68
- id: z.ZodString;
69
- data: z.ZodObject<{
70
- message: z.ZodString;
71
- stack: z.ZodString;
72
- }, z.core.$strip>;
73
- }, z.core.$strip>, z.ZodObject<{
74
- type: z.ZodLiteral<"globalError">;
75
- level: z.ZodEnum<{
76
- info: "info";
77
- warn: "warn";
78
- error: "error";
79
- debug: "debug";
80
- }>;
81
- id: z.ZodString;
82
- data: z.ZodObject<{
83
- message: z.ZodString;
84
- stack: z.ZodString;
85
- }, z.core.$strip>;
86
- }, z.core.$strip>, z.ZodObject<{
87
- type: z.ZodLiteral<"unhandledRejectionError">;
47
+ type: z.ZodLiteral<"typedLogV2">;
88
48
  level: z.ZodEnum<{
49
+ success: "success";
89
50
  info: "info";
90
51
  warn: "warn";
91
52
  error: "error";
92
53
  debug: "debug";
93
54
  }>;
94
55
  id: z.ZodString;
95
- data: z.ZodObject<{
96
- message: z.ZodString;
97
- stack: z.ZodString;
56
+ args: z.ZodArray<z.ZodUnknown>;
57
+ meta: z.ZodObject<{
58
+ stacktrace: z.ZodOptional<z.ZodArray<z.ZodObject<{
59
+ functionName: z.ZodString;
60
+ fileName: z.ZodString;
61
+ lineNumber: z.ZodNumber;
62
+ columnNumber: z.ZodNumber;
63
+ }, z.core.$strip>>>;
64
+ logTraceID: z.ZodOptional<z.ZodString>;
65
+ skipFrame: z.ZodOptional<z.ZodNumber>;
98
66
  }, z.core.$strip>;
99
- }, z.core.$strip>, z.ZodObject<{
100
- type: z.ZodLiteral<"noCategory">;
67
+ }, z.core.$strip>], "type">;
68
+ export type LogLevel = 'debug' | 'info' | 'warn' | 'error' | 'success';
69
+ export declare const logWithMetaSchema: z.ZodObject<{
101
70
  level: z.ZodEnum<{
71
+ success: "success";
102
72
  info: "info";
103
73
  warn: "warn";
104
74
  error: "error";
105
75
  debug: "debug";
106
76
  }>;
107
- id: z.ZodString;
108
- data: z.ZodObject<{
109
- message: z.ZodUnknown;
110
- args: z.ZodArray<z.ZodUnknown>;
77
+ args: z.ZodArray<z.ZodUnknown>;
78
+ meta: z.ZodObject<{
79
+ stacktrace: z.ZodOptional<z.ZodArray<z.ZodObject<{
80
+ functionName: z.ZodString;
81
+ fileName: z.ZodString;
82
+ lineNumber: z.ZodNumber;
83
+ columnNumber: z.ZodNumber;
84
+ }, z.core.$strip>>>;
85
+ logTraceID: z.ZodOptional<z.ZodString>;
86
+ skipFrame: z.ZodOptional<z.ZodNumber>;
111
87
  }, z.core.$strip>;
112
- }, z.core.$strip>], "type">;
88
+ }, z.core.$strip>;
89
+ export type LogStackFrame = z.infer<typeof logStackFrameSchema>;
90
+ export type LogWithMeta = z.infer<typeof logWithMetaSchema>;
91
+ export type LogMeta = z.infer<typeof logMeta>;
113
92
  export type SelectedLog = z.infer<typeof selectedLogSchema>;
@@ -20,48 +20,36 @@ const noCategoryLogSchema = zod.object({
20
20
  message: zod.unknown(),
21
21
  args: zod.array(zod.unknown())
22
22
  });
23
+ const logStackFrameSchema = zod.object({
24
+ functionName: zod.string(),
25
+ fileName: zod.string(),
26
+ lineNumber: zod.number(),
27
+ columnNumber: zod.number()
28
+ });
23
29
  const levelSchema = zod["enum"]([
24
30
  'info',
25
31
  'warn',
26
32
  'error',
27
- 'debug'
33
+ 'debug',
34
+ 'success'
28
35
  ]);
36
+ const logMeta = zod.object({
37
+ stacktrace: zod.optional(zod.array(logStackFrameSchema)),
38
+ logTraceID: zod.optional(zod.string()),
39
+ skipFrame: zod.optional(zod.number())
40
+ });
29
41
  const selectedLogSchema = zod.discriminatedUnion('type', [
30
42
  zod.object({
31
- type: zod.literal('networkRequest'),
32
- level: levelSchema,
33
- id: zod.string(),
34
- data: networkRequestLogSchema
35
- }),
36
- zod.object({
37
- type: zod.literal('routerError'),
38
- level: levelSchema,
39
- id: zod.string(),
40
- data: routerErrorSchema
41
- }),
42
- zod.object({
43
- type: zod.literal('renderError'),
44
- level: levelSchema,
45
- id: zod.string(),
46
- data: genericErrorSchema
47
- }),
48
- zod.object({
49
- type: zod.literal('globalError'),
50
- level: levelSchema,
51
- id: zod.string(),
52
- data: genericErrorSchema
53
- }),
54
- zod.object({
55
- type: zod.literal('unhandledRejectionError'),
43
+ type: zod.literal('typedLogV2'),
56
44
  level: levelSchema,
57
45
  id: zod.string(),
58
- data: genericErrorSchema
59
- }),
60
- zod.object({
61
- type: zod.literal('noCategory'),
62
- level: levelSchema,
63
- id: zod.string(),
64
- data: noCategoryLogSchema
46
+ args: zod.array(zod.unknown()),
47
+ meta: logMeta
65
48
  })
66
49
  ]);
67
- export { genericErrorSchema, levelSchema, networkRequestLogSchema, noCategoryLogSchema, routerErrorSchema, selectedLogSchema };
50
+ const logWithMetaSchema = zod.object({
51
+ level: levelSchema,
52
+ args: zod.array(zod.unknown()),
53
+ meta: logMeta
54
+ });
55
+ export { genericErrorSchema, levelSchema, logMeta, logStackFrameSchema, logWithMetaSchema, networkRequestLogSchema, noCategoryLogSchema, routerErrorSchema, selectedLogSchema };
@@ -1,7 +1,10 @@
1
+ import { LogWithMeta } from './log-types';
1
2
  export type LogInterceptor = (originLogger: typeof logger) => typeof logger;
2
3
  export declare let logger: {
3
4
  debug(message: any, ...args: any[]): void;
4
5
  info(message: any, ...args: any[]): void;
5
6
  warn(message: any, ...args: any[]): void;
6
7
  error(message: any, ...args: any[]): void;
8
+ success(message: any, ...args: any[]): void;
9
+ log({ level, args }: LogWithMeta): void;
7
10
  };
@@ -51,6 +51,12 @@ let logger = {
51
51
  },
52
52
  error (message, ...args) {
53
53
  if (shouldLog('error')) console.error(...getFormattedPrefix('error'), message, ...args);
54
+ },
55
+ success (message, ...args) {
56
+ if (shouldLog('success')) console.log(...getFormattedPrefix('success'), message, ...args);
57
+ },
58
+ log ({ level, args }) {
59
+ if (shouldLog(level)) console.log(...getFormattedPrefix(level), ...args);
54
60
  }
55
61
  };
56
62
  for (const interceptor of interceptors)logger = interceptor(logger);
@@ -1,2 +1,5 @@
1
1
  import { type LogInterceptor } from './logger';
2
+ import { logStackFrameSchema } from './log-types';
3
+ import z from 'zod';
4
+ export declare function getStacktrace(): Promise<z.infer<typeof logStackFrameSchema>[]>;
2
5
  export declare const interceptors: LogInterceptor[];
@@ -1,8 +1,8 @@
1
1
  import { logger as external_logger_js_logger } from "./logger.js";
2
- import { SourceMapConsumer } from "source-map";
3
- import { normalizeBasePath } from "../utils/utils.js";
2
+ import { SourceMapConsumer as external_source_map_SourceMapConsumer } from "source-map";
3
+ import "../utils/utils.js";
4
4
  import { mappingText } from "./source-map-mappings-wasm.js";
5
- import { genericErrorSchema, networkRequestLogSchema, noCategoryLogSchema, routerErrorSchema } from "./log-types.js";
5
+ import stacktrace_js from "stacktrace-js";
6
6
  function hexToBuffer(hexString) {
7
7
  const hex = hexString.replace(/\s/g, '').toUpperCase();
8
8
  if (!/^[0-9A-F]+$/.test(hex)) throw new Error('Invalid hex string');
@@ -15,55 +15,39 @@ function hexToBuffer(hexString) {
15
15
  }
16
16
  return buffer;
17
17
  }
18
- SourceMapConsumer.initialize({
18
+ external_source_map_SourceMapConsumer.initialize({
19
19
  'lib/mappings.wasm': hexToBuffer(mappingText)
20
20
  });
21
- async function getSourceMap() {
22
- let sourceMapContent = '';
21
+ const mapStacktrace = (stacktrace)=>stacktrace.map((frame)=>({
22
+ functionName: frame.functionName || '',
23
+ fileName: frame.fileName || '',
24
+ lineNumber: frame.lineNumber || 0,
25
+ columnNumber: frame.columnNumber || 0
26
+ }));
27
+ async function sendSelectedLog(logWithoutID) {
23
28
  try {
24
- const basePath = normalizeBasePath(process.env.CLIENT_BASE_PATH);
25
- const res = await fetch(`${basePath}/main.js.map`);
26
- sourceMapContent = await res.text();
27
- } catch (e) {
28
- external_logger_js_logger.warn('get main.js.map error', e);
29
- }
30
- return sourceMapContent;
31
- }
32
- async function parseSourceMap(stack) {
33
- try {
34
- const sourceMapContent = await getSourceMap();
35
- if (!sourceMapContent) return stack;
36
- const consumer = await new SourceMapConsumer(JSON.parse(sourceMapContent));
37
- const lines = stack.split('\n');
38
- for(let i = 0; i < lines.length; i++){
39
- const line = lines[i];
40
- const match = line.match(/\((.*main\.js):(\d+):(\d+)\)/);
41
- if (match) {
42
- const [fullMatch, , lineNum, colNum] = match;
43
- const originalPosition = consumer.originalPositionFor({
44
- line: Number(lineNum),
45
- column: Number(colNum)
46
- });
47
- if (originalPosition.source) {
48
- let originalPositionStr = `(${originalPosition.source}:${originalPosition.line}:${originalPosition.column})`;
49
- originalPositionStr = originalPositionStr.replace('webpack://fullstack-nestjs-template/', '');
50
- lines[i] = line.replace(fullMatch, originalPositionStr);
51
- }
29
+ const log = {
30
+ ...logWithoutID,
31
+ id: crypto.randomUUID()
32
+ };
33
+ for(let i = 0; i < log.args.length; i++)if (log.args[i] instanceof Error) {
34
+ const error = log.args[i];
35
+ log.args[i] = {
36
+ message: error.message,
37
+ stack: error.stack
38
+ };
39
+ if (!log.meta.stacktrace) {
40
+ const stacktrace = await stacktrace_js.fromError(error);
41
+ log.meta.stacktrace = mapStacktrace(stacktrace);
52
42
  }
53
43
  }
54
- return lines.join('\n');
55
- } catch (e) {
56
- external_logger_js_logger.warn('recover code position error', e);
57
- return stack;
58
- }
59
- }
60
- function sendSelectedLog(log) {
61
- const logWithID = {
62
- ...log,
63
- id: crypto.randomUUID()
64
- };
65
- try {
66
- const logJSON = JSON.stringify(logWithID);
44
+ if (!log.meta.stacktrace) {
45
+ const frames = await getStacktrace();
46
+ log.meta.stacktrace = frames;
47
+ }
48
+ if (void 0 === log.meta.skipFrame) log.meta.skipFrame = 2;
49
+ const logJSON = JSON.stringify(log);
50
+ console.log(JSON.parse(logJSON));
67
51
  console.log(logJSON);
68
52
  if (window.parent !== window) try {
69
53
  window.parent.postMessage({
@@ -77,45 +61,48 @@ function sendSelectedLog(log) {
77
61
  external_logger_js_logger.warn('send selected log error', e);
78
62
  }
79
63
  }
80
- const comprehensiveInterceptor = (logger)=>({
64
+ async function getStacktrace() {
65
+ const stacktrace = await stacktrace_js.get();
66
+ const frames = mapStacktrace(stacktrace);
67
+ return frames;
68
+ }
69
+ async function sendTypedLogV2(logWithMeta) {
70
+ sendSelectedLog({
71
+ type: 'typedLogV2',
72
+ level: logWithMeta.level,
73
+ args: logWithMeta.args,
74
+ meta: logWithMeta.meta
75
+ });
76
+ }
77
+ const typedLogInterceptor = (logger)=>({
78
+ debug: (message, ...args)=>{
79
+ try {
80
+ logger.debug(message, ...args);
81
+ } catch (e) {
82
+ logger.warn('debug log error', e);
83
+ }
84
+ sendTypedLogV2({
85
+ level: 'debug',
86
+ args: [
87
+ message,
88
+ ...args
89
+ ],
90
+ meta: {}
91
+ });
92
+ },
81
93
  info: (message, ...args)=>{
82
94
  try {
83
95
  logger.info(message, ...args);
84
96
  } catch (e) {
85
97
  logger.warn('info log error', e);
86
98
  }
87
- if (message && 'object' == typeof message && 'HTTP Request' === message.type) return;
88
- if (message && 'object' == typeof message && 'HTTP Response' === message.type) {
89
- let requestData = message.data;
90
- if ('string' == typeof requestData) try {
91
- requestData = JSON.parse(requestData);
92
- } catch (e) {
93
- logger.warn('parse request data error', e);
94
- }
95
- const info = networkRequestLogSchema.safeParse({
96
- method: message.method || '',
97
- status: message.status || 0,
98
- statusText: message.statusText || '',
99
- path: message.url || '',
100
- requestData,
101
- requestParams: message.params,
102
- responseData: message.responseData,
103
- traceID: message.headers?.['X-Trace-ID'] || ''
104
- });
105
- if (info.success) sendSelectedLog({
106
- type: 'networkRequest',
107
- level: 'info',
108
- data: info.data
109
- });
110
- return;
111
- }
112
- sendSelectedLog({
113
- type: 'noCategory',
99
+ sendTypedLogV2({
114
100
  level: 'info',
115
- data: {
101
+ args: [
116
102
  message,
117
- args
118
- }
103
+ ...args
104
+ ],
105
+ meta: {}
119
106
  });
120
107
  },
121
108
  error: (message, ...args)=>{
@@ -124,103 +111,13 @@ const comprehensiveInterceptor = (logger)=>({
124
111
  } catch (e) {
125
112
  logger.warn('error log error', e);
126
113
  }
127
- if (message && 'object' == typeof message && 'HTTP Request' === message.type) return;
128
- if (message && 'object' == typeof message && 'HTTP Response' === message.type) {
129
- let requestData = message.data;
130
- if ('string' == typeof requestData) try {
131
- requestData = JSON.parse(requestData);
132
- } catch (e) {
133
- logger.warn('parse request data error', e);
134
- }
135
- const info = networkRequestLogSchema.safeParse({
136
- method: message.method || '',
137
- status: message.status || 0,
138
- statusText: message.statusText || '',
139
- path: message.url || '',
140
- requestData,
141
- requestParams: message.params,
142
- responseData: message.responseData,
143
- traceID: message.headers?.['X-Trace-ID'] || ''
144
- });
145
- if (info.success) sendSelectedLog({
146
- type: 'networkRequest',
147
- level: 'error',
148
- data: info.data
149
- });
150
- return;
151
- }
152
- if ('RenderError' === message) return void (async ()=>{
153
- const error = args[0];
154
- if (error && error instanceof Error) {
155
- const stack = await parseSourceMap(error.stack || '');
156
- sendSelectedLog({
157
- type: 'renderError',
158
- level: 'error',
159
- data: {
160
- message: error.message,
161
- stack
162
- }
163
- });
164
- }
165
- })();
166
- if ('404 Error: User attempted to access non-existent route:' === message) {
167
- const path = args[0] || '';
168
- const data = routerErrorSchema.safeParse({
169
- path
170
- });
171
- if (data.success) return void sendSelectedLog({
172
- level: 'error',
173
- type: 'routerError',
174
- data: data.data
175
- });
176
- }
177
- if ('global error' === message) {
178
- const error = args[0];
179
- if (error && error instanceof ErrorEvent) {
180
- const data = genericErrorSchema.safeParse({
181
- message: error?.error?.message || '',
182
- stack: error?.error?.stack || ''
183
- });
184
- if (data.success) return void (async ()=>{
185
- const stack = await parseSourceMap(data.data.stack || '');
186
- sendSelectedLog({
187
- type: 'globalError',
188
- level: 'error',
189
- data: {
190
- ...data.data,
191
- stack
192
- }
193
- });
194
- })();
195
- }
196
- }
197
- if ('global unhandledrejection' === message) {
198
- const error = args[0];
199
- if (error && error instanceof PromiseRejectionEvent) {
200
- const data = genericErrorSchema.safeParse({
201
- message: error?.reason?.message || '',
202
- stack: error?.reason?.stack || ''
203
- });
204
- if (data.success) return void (async ()=>{
205
- const stack = await parseSourceMap(data.data.stack || '');
206
- sendSelectedLog({
207
- type: 'unhandledRejectionError',
208
- level: 'error',
209
- data: {
210
- ...data.data,
211
- stack
212
- }
213
- });
214
- })();
215
- }
216
- }
217
- sendSelectedLog({
218
- type: 'noCategory',
114
+ sendTypedLogV2({
219
115
  level: 'error',
220
- data: noCategoryLogSchema.parse({
116
+ args: [
221
117
  message,
222
- args
223
- })
118
+ ...args
119
+ ],
120
+ meta: {}
224
121
  });
225
122
  },
226
123
  warn: (message, ...args)=>{
@@ -229,32 +126,48 @@ const comprehensiveInterceptor = (logger)=>({
229
126
  } catch (e) {
230
127
  logger.warn('warn log error', e);
231
128
  }
232
- sendSelectedLog({
233
- type: 'noCategory',
129
+ sendTypedLogV2({
234
130
  level: 'warn',
235
- data: {
131
+ args: [
236
132
  message,
237
- args
238
- }
133
+ ...args
134
+ ],
135
+ meta: {}
239
136
  });
240
137
  },
241
- debug: (message, ...args)=>{
138
+ success: (message, ...args)=>{
242
139
  try {
243
- logger.debug(message, ...args);
140
+ logger.success(message, ...args);
244
141
  } catch (e) {
245
- logger.warn('debug log error', e);
142
+ logger.warn('success log error', e);
246
143
  }
247
- sendSelectedLog({
248
- type: 'noCategory',
249
- level: 'debug',
250
- data: {
144
+ sendTypedLogV2({
145
+ level: 'success',
146
+ args: [
251
147
  message,
252
- args
253
- }
148
+ ...args
149
+ ],
150
+ meta: {}
151
+ });
152
+ },
153
+ log: ({ level, args, meta })=>{
154
+ try {
155
+ logger.log({
156
+ level,
157
+ args,
158
+ meta
159
+ });
160
+ } catch (e) {
161
+ logger.warn('log log error', e);
162
+ }
163
+ sendTypedLogV2({
164
+ level,
165
+ args,
166
+ meta: meta || {}
254
167
  });
255
168
  }
256
169
  });
257
170
  const interceptors = [
258
- comprehensiveInterceptor
171
+ typedLogInterceptor
259
172
  ];
260
- export { interceptors };
173
+ export { getStacktrace, interceptors };
package/lib/override.css CHANGED
@@ -1,13 +1,16 @@
1
- .ant-btn .ant-btn-icon {
2
- align-items: center;
3
- display: inline-flex;
4
- }
1
+ @layer base {
2
+ * {
3
+ border-color: var(--border);
4
+ outline-color: var(--ring);
5
5
 
6
- .ant-btn-icon {
7
- vertical-align: -.125em;
8
- }
6
+ @supports (color: color-mix(in lab, red, red)) {
7
+ outline-color: color-mix(in oklab, var(--ring) 50%, transparent);
8
+ }
9
+ }
9
10
 
10
- .ant-menu .ant-menu-item, .ant-menu > .ant-menu .ant-menu-item, .ant-dropdown-menu .ant-dropdown-menu-item, .ant-dropdown-menu .ant-dropdown-submenu-title, .ant-menu .ant-menu-submenu-title, .ant-menu > .ant-menu .ant-menu-submenu-title {
11
- color: inherit;
11
+ body {
12
+ background-color: var(--background);
13
+ color: var(--foreground);
14
+ }
12
15
  }
13
16
 
@@ -1,4 +1,4 @@
1
- import { type AxiosInstance } from 'axios';
1
+ import { AxiosInstance } from 'axios';
2
2
  /**
3
3
  * axios配置内容:拦截器、日志等
4
4
  */
@@ -1,59 +1,66 @@
1
1
  import axios from "axios";
2
2
  import { logger } from "../apis/logger.js";
3
- function getRequestLogInfo(config) {
4
- return {
5
- url: config?.url,
6
- method: config?.method?.toUpperCase(),
7
- params: config?.params,
8
- data: config?.data,
9
- headers: {
10
- ...config?.headers,
11
- 'X-Suda-Csrf-Token': config?.headers['X-Suda-Csrf-Token'] ? '[REDACTED]' : void 0,
12
- Authorization: config?.headers.Authorization ? '[REDACTED]' : void 0
3
+ import { getStacktrace } from "../logger/selected-logs.js";
4
+ async function logResponse(ok, response) {
5
+ const okToTextMap = {
6
+ success: 'API 请求成功:',
7
+ error: 'API 请求失败:'
8
+ };
9
+ const parts = [
10
+ okToTextMap[ok],
11
+ (response.config.url || '').split('?')[0],
12
+ ' - ',
13
+ Date.now() - response.config._startTime,
14
+ 'ms'
15
+ ];
16
+ const logTraceID = response.headers['x-log-trace-id'];
17
+ const args = [
18
+ '请求参数:',
19
+ response.config.data,
20
+ '返回数据:',
21
+ response.data,
22
+ '请求摘要:',
23
+ {
24
+ TraceID: logTraceID,
25
+ 状态: `${response.statusText}[状态码${response.status}]`,
26
+ 时间: `${new Date().toLocaleString()}`
13
27
  }
28
+ ];
29
+ const requestUUID = response.config._requestUUID;
30
+ const stacktrace = await requestStacktraceMap.get(requestUUID);
31
+ const logMeta = {
32
+ logTraceID
14
33
  };
34
+ if (stacktrace) logMeta.stacktrace = stacktrace;
35
+ logger.log({
36
+ level: ok,
37
+ args: [
38
+ parts.join(''),
39
+ ...args
40
+ ],
41
+ meta: {
42
+ logTraceID
43
+ }
44
+ });
15
45
  }
46
+ const requestStacktraceMap = new Map();
16
47
  function initAxiosConfig(axiosInstance) {
17
48
  if (!axiosInstance) axiosInstance = axios;
18
49
  axiosInstance.interceptors.request.use((config)=>{
50
+ const requestUUID = crypto.randomUUID();
51
+ const stacktrace = getStacktrace();
52
+ requestStacktraceMap.set(requestUUID, stacktrace);
53
+ config._requestUUID = requestUUID;
19
54
  config._startTime = Date.now();
20
55
  const csrfToken = window.csrfToken;
21
56
  if (csrfToken) config.headers['X-Suda-Csrf-Token'] = csrfToken;
22
- config.headers['X-Trace-ID'] = crypto.randomUUID();
23
- logger.info({
24
- type: 'HTTP Request',
25
- ...getRequestLogInfo(config)
26
- });
27
57
  return config;
28
- }, (error)=>{
29
- logger.error({
30
- type: 'HTTP Request',
31
- ...getRequestLogInfo(error.config),
32
- message: error.message,
33
- stack: error.stack
34
- });
35
- return Promise.reject(error);
36
- });
58
+ }, (error)=>Promise.reject(error));
37
59
  axiosInstance.interceptors.response.use((response)=>{
38
- logger.info({
39
- type: 'HTTP Response',
40
- ...getRequestLogInfo(response.config),
41
- status: response.status,
42
- statusText: response.statusText,
43
- responseData: response.data,
44
- responseTime: Date.now() - response.config._startTime
45
- });
60
+ logResponse('success', response);
46
61
  return response;
47
62
  }, (error)=>{
48
- logger.error({
49
- type: 'HTTP Response',
50
- ...getRequestLogInfo(error.config),
51
- status: error.response?.status,
52
- statusText: error.response?.statusText,
53
- message: error.message,
54
- responseData: error.response?.data,
55
- responseTime: Date.now() - error.config._startTime
56
- });
63
+ logResponse('error', error.response);
57
64
  return Promise.reject(error);
58
65
  });
59
66
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lark-apaas/client-toolkit",
3
- "version": "1.1.2",
3
+ "version": "1.1.3-alpha.01",
4
4
  "types": "./lib/index.d.ts",
5
5
  "main": "./lib/index.js",
6
6
  "files": [
@@ -92,6 +92,7 @@
92
92
  "sockjs-client": "^1.6.1",
93
93
  "sonner": "~2.0.0",
94
94
  "source-map": "^0.7.6",
95
+ "stacktrace-js": "^2.0.2",
95
96
  "tailwind-merge": "~2.0.0",
96
97
  "tailwind-variants": "0.3.1",
97
98
  "tailwindcss-animate": "^1.0.7",