@wutiange/log-listener-plugin 1.3.0-alpha.1 → 1.3.0-alpha.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (63) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +2 -2
  3. package/dist/server.d.ts +10 -0
  4. package/dist/server.js +45 -0
  5. package/dist/server.js.map +1 -0
  6. package/dist/src/HTTPInterceptor.d.ts +48 -0
  7. package/dist/src/HTTPInterceptor.js +202 -0
  8. package/dist/src/HTTPInterceptor.js.map +1 -0
  9. package/dist/src/logPlugin.d.ts +19 -20
  10. package/dist/src/logPlugin.js +108 -122
  11. package/dist/src/logPlugin.js.map +1 -1
  12. package/package.json +47 -47
  13. package/src/HTTPInterceptor.ts +319 -0
  14. package/src/__tests__/console.test.ts +25 -25
  15. package/src/common.ts +4 -4
  16. package/src/logPlugin.ts +238 -229
  17. package/src/server.ts +66 -66
  18. package/src/utils.ts +47 -47
  19. package/dist/packages/network-logger/Logger.d.ts +0 -28
  20. package/dist/packages/network-logger/Logger.js +0 -192
  21. package/dist/packages/network-logger/Logger.js.map +0 -1
  22. package/dist/packages/network-logger/NetworkRequestInfo.d.ts +0 -37
  23. package/dist/packages/network-logger/NetworkRequestInfo.js +0 -151
  24. package/dist/packages/network-logger/NetworkRequestInfo.js.map +0 -1
  25. package/dist/packages/network-logger/constant.d.ts +0 -2
  26. package/dist/packages/network-logger/constant.js +0 -6
  27. package/dist/packages/network-logger/constant.js.map +0 -1
  28. package/dist/packages/network-logger/types.d.ts +0 -14
  29. package/dist/packages/network-logger/types.js +0 -3
  30. package/dist/packages/network-logger/types.js.map +0 -1
  31. package/dist/packages/network-logger/utils/debounce.d.ts +0 -2
  32. package/dist/packages/network-logger/utils/debounce.js +0 -20
  33. package/dist/packages/network-logger/utils/debounce.js.map +0 -1
  34. package/dist/packages/network-logger/utils/extractHost.d.ts +0 -2
  35. package/dist/packages/network-logger/utils/extractHost.js +0 -9
  36. package/dist/packages/network-logger/utils/extractHost.js.map +0 -1
  37. package/dist/packages/network-logger/utils/fromEntries.d.ts +0 -2
  38. package/dist/packages/network-logger/utils/fromEntries.js +0 -8
  39. package/dist/packages/network-logger/utils/fromEntries.js.map +0 -1
  40. package/dist/packages/network-logger/utils/logger.d.ts +0 -1
  41. package/dist/packages/network-logger/utils/logger.js +0 -6
  42. package/dist/packages/network-logger/utils/logger.js.map +0 -1
  43. package/dist/src/CompatibilityManager.d.ts +0 -27
  44. package/dist/src/CompatibilityManager.js +0 -82
  45. package/dist/src/CompatibilityManager.js.map +0 -1
  46. package/dist/src/console.d.ts +0 -1
  47. package/dist/src/console.js +0 -20
  48. package/dist/src/console.js.map +0 -1
  49. package/dist/src/fetch.d.ts +0 -1
  50. package/dist/src/fetch.js +0 -48
  51. package/dist/src/fetch.js.map +0 -1
  52. package/dist/src/index.d.ts +0 -2
  53. package/dist/src/index.js +0 -8
  54. package/dist/src/index.js.map +0 -1
  55. package/packages/network-logger/Logger.ts +0 -274
  56. package/packages/network-logger/NetworkRequestInfo.ts +0 -161
  57. package/packages/network-logger/constant.ts +0 -3
  58. package/packages/network-logger/types.ts +0 -36
  59. package/packages/network-logger/utils/debounce.ts +0 -21
  60. package/packages/network-logger/utils/extractHost.ts +0 -7
  61. package/packages/network-logger/utils/fromEntries.ts +0 -7
  62. package/packages/network-logger/utils/logger.ts +0 -2
  63. package/src/CompatibilityManager.ts +0 -71
@@ -1,27 +0,0 @@
1
- import NetworkRequestInfo from "../packages/network-logger/NetworkRequestInfo";
2
- declare class CompatibilityManager {
3
- private static requestInfoObj;
4
- static interceptionToNetwork(data: NetworkRequestInfo[]): Promise<({
5
- headers: import("../packages/network-logger/types").Headers;
6
- body: string;
7
- requestId: string;
8
- statusCode: number;
9
- endTime: number;
10
- url?: undefined;
11
- id?: undefined;
12
- method?: undefined;
13
- createTime?: undefined;
14
- } | {
15
- url: string;
16
- id: string;
17
- method: import("../packages/network-logger/types").RequestMethod;
18
- headers: import("../packages/network-logger/types").Headers;
19
- body: string;
20
- createTime: number;
21
- requestId?: undefined;
22
- statusCode?: undefined;
23
- endTime?: undefined;
24
- })[]>;
25
- private static asyncSwapSendArr;
26
- }
27
- export default CompatibilityManager;
@@ -1,82 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- class CompatibilityManager {
13
- static interceptionToNetwork(data) {
14
- return __awaiter(this, void 0, void 0, function* () {
15
- const tempWillSendArr = [];
16
- if (Object.keys(CompatibilityManager.requestInfoObj).length === 0) {
17
- CompatibilityManager.requestInfoObj = data.reduce((e, c) => {
18
- if (c.endTime) {
19
- const startReq = c.copy();
20
- startReq.endTime = 0;
21
- tempWillSendArr.push(startReq, c);
22
- return e;
23
- }
24
- tempWillSendArr.push(c);
25
- return Object.assign(Object.assign({}, e), { [c.id]: c });
26
- }, {});
27
- }
28
- else {
29
- data.forEach(e => {
30
- const tempObj = CompatibilityManager.requestInfoObj;
31
- if (!(e.id in tempObj)) {
32
- if (!e.endTime) {
33
- tempWillSendArr.push(e);
34
- CompatibilityManager.requestInfoObj[e.id] = e;
35
- }
36
- else {
37
- const startReq = e.copy();
38
- startReq.endTime = 0;
39
- tempWillSendArr.push(startReq, e);
40
- }
41
- return;
42
- }
43
- if (e.id in tempObj && e.endTime) {
44
- tempWillSendArr.push(e);
45
- delete CompatibilityManager.requestInfoObj[e.id];
46
- return;
47
- }
48
- });
49
- }
50
- return CompatibilityManager.asyncSwapSendArr(tempWillSendArr);
51
- });
52
- }
53
- static asyncSwapSendArr(data) {
54
- return __awaiter(this, void 0, void 0, function* () {
55
- const asyncTempArr = yield Promise.all(data.map((e) => __awaiter(this, void 0, void 0, function* () {
56
- if (e.endTime) {
57
- return {
58
- headers: e.responseHeaders,
59
- body: yield e.getResponseBody(),
60
- requestId: e.id,
61
- statusCode: e.status,
62
- endTime: e.endTime,
63
- };
64
- }
65
- else {
66
- return {
67
- url: e.url,
68
- id: e.id,
69
- method: e.method,
70
- headers: e.requestHeaders,
71
- body: e.getRequestBody(),
72
- createTime: e.startTime,
73
- };
74
- }
75
- })));
76
- return asyncTempArr;
77
- });
78
- }
79
- }
80
- CompatibilityManager.requestInfoObj = {};
81
- exports.default = CompatibilityManager;
82
- //# sourceMappingURL=CompatibilityManager.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"CompatibilityManager.js","sourceRoot":"","sources":["../../src/CompatibilityManager.ts"],"names":[],"mappings":"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"}
@@ -1 +0,0 @@
1
- export {};
@@ -1,20 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const index_1 = __importDefault(require("./index"));
7
- const common = require('./common');
8
- console.log = (...data) => {
9
- index_1.default.log(...data);
10
- common.log(...data);
11
- };
12
- console.warn = (...data) => {
13
- index_1.default.warn(...data);
14
- common.warn(...data);
15
- };
16
- console.error = (...data) => {
17
- index_1.default.error(...data);
18
- common.error(...data);
19
- };
20
- //# sourceMappingURL=console.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"console.js","sourceRoot":"","sources":["../../src/console.ts"],"names":[],"mappings":";;;;;AAKA,oDAA6B;AAC7B,MAAM,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AACnC,OAAO,CAAC,GAAG,GAAG,CAAC,GAAG,IAAW,EAAE,EAAE;IAC/B,eAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;IACpB,MAAM,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,CAAC;AACtB,CAAC,CAAC;AAEF,OAAO,CAAC,IAAI,GAAG,CAAC,GAAG,IAAW,EAAE,EAAE;IAChC,eAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;IACrB,MAAM,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;AACvB,CAAC,CAAC;AAEF,OAAO,CAAC,KAAK,GAAG,CAAC,GAAG,IAAW,EAAE,EAAE;IACjC,eAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;IACtB,MAAM,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC;AACxB,CAAC,CAAC"}
@@ -1 +0,0 @@
1
- export {};
package/dist/src/fetch.js DELETED
@@ -1,48 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const index_1 = __importDefault(require("./index"));
16
- const utils_1 = require("./utils");
17
- const common = require('./common');
18
- global.fetch = (input, init) => __awaiter(void 0, void 0, void 0, function* () {
19
- const uniqueId = (Date.now() + Math.random()).toString(16);
20
- index_1.default.uniqueReq(uniqueId, input, init);
21
- let isFetchFinished = false;
22
- let isTimeout = false;
23
- const timeout = index_1.default.getTimeout();
24
- if (timeout !== null) {
25
- (0, utils_1.sleep)(timeout).then(() => {
26
- if (!isFetchFinished) {
27
- isTimeout = true;
28
- index_1.default.resTimeout(uniqueId);
29
- }
30
- });
31
- }
32
- try {
33
- const response = yield common.tempFetch(input, init);
34
- isFetchFinished = true;
35
- if (response instanceof Response && !isTimeout) {
36
- index_1.default.uniqueRes(uniqueId, response.clone());
37
- }
38
- return response;
39
- }
40
- catch (error) {
41
- isFetchFinished = true;
42
- if (!isTimeout) {
43
- index_1.default.resResponseError(uniqueId);
44
- }
45
- throw new Error(error);
46
- }
47
- });
48
- //# sourceMappingURL=fetch.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../../src/fetch.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAIA,oDAA6B;AAC7B,mCAA8B;AAE9B,MAAM,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;AAEnC,MAAM,CAAC,KAAK,GAAG,CAAO,KAAwB,EAAE,IAAkB,EAAE,EAAE;IACpE,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IAC3D,eAAM,CAAC,SAAS,CAAC,QAAQ,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;IACxC,IAAI,eAAe,GAAG,KAAK,CAAC;IAC5B,IAAI,SAAS,GAAG,KAAK,CAAC;IACtB,MAAM,OAAO,GAAG,eAAM,CAAC,UAAU,EAAE,CAAA;IACnC,IAAI,OAAO,KAAK,IAAI,EAAE,CAAC;QACrB,IAAA,aAAK,EAAC,OAAO,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE;YACvB,IAAI,CAAC,eAAe,EAAE,CAAC;gBACrB,SAAS,GAAG,IAAI,CAAC;gBACjB,eAAM,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;YAC9B,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IAED,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,MAAM,CAAC,SAAS,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACrD,eAAe,GAAG,IAAI,CAAC;QACvB,IAAI,QAAQ,YAAY,QAAQ,IAAI,CAAC,SAAS,EAAE,CAAC;YAC/C,eAAM,CAAC,SAAS,CAAC,QAAQ,EAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAC;QAC/C,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,eAAe,GAAG,IAAI,CAAC;QACvB,IAAI,CAAC,SAAS,EAAE,CAAC;YACf,eAAM,CAAC,gBAAgB,CAAC,QAAQ,CAAC,CAAC;QACpC,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;AACH,CAAC,CAAA,CAAC"}
@@ -1,2 +0,0 @@
1
- import logPlugin from './logPlugin';
2
- export default logPlugin;
package/dist/src/index.js DELETED
@@ -1,8 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- const logPlugin_1 = __importDefault(require("./logPlugin"));
7
- exports.default = logPlugin_1.default;
8
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;AAAA,4DAAoC;AAEpC,kBAAe,mBAAS,CAAC"}
@@ -1,274 +0,0 @@
1
- // @ts-ignore
2
- import XHRInterceptor from 'react-native/Libraries/Network/XHRInterceptor';
3
- import NetworkRequestInfo from './NetworkRequestInfo';
4
- import type {Headers, RequestMethod, StartNetworkLoggingOptions} from './types';
5
- import {LOGGER_REFRESH_RATE, LOGGER_MAX_REQUESTS} from './constant';
6
- import extractHost from './utils/extractHost';
7
- import {warn} from './utils/logger';
8
- import debounce from './utils/debounce';
9
-
10
- let nextXHRId = 0;
11
-
12
- type XHR = {
13
- _index: number;
14
- responseHeaders?: Headers;
15
- };
16
-
17
-
18
- export default class Logger {
19
- private requests: NetworkRequestInfo[] = [];
20
- private xhrIdMap: Map<number, () => number> = new Map();
21
- private maxRequests: number = LOGGER_MAX_REQUESTS;
22
- private refreshRate: number = LOGGER_REFRESH_RATE;
23
- private latestRequestUpdatedAt: number = 0;
24
- private ignoredHosts: Set<string> | undefined;
25
- private ignoredUrls: Set<string> | undefined;
26
- private ignoredPatterns: RegExp[] | undefined;
27
- public enabled = false;
28
- public paused = false;
29
-
30
- callback = (_: NetworkRequestInfo[]): void => null;
31
-
32
- setCallback = (callback: any) => {
33
- this.callback = callback;
34
- };
35
-
36
- debouncedCallback = debounce(() => {
37
- if (
38
- !this.latestRequestUpdatedAt ||
39
- this.requests.some(r => r.updatedAt > this.latestRequestUpdatedAt)
40
- ) {
41
- this.latestRequestUpdatedAt = Date.now();
42
- // prevent mutation of requests for all subscribers
43
- this.callback([...this.requests]);
44
- }
45
- }, this.refreshRate);
46
-
47
- private getRequest = (xhrIndex?: number) => {
48
- if (xhrIndex === undefined) {
49
- return undefined;
50
- }
51
- if (!this.xhrIdMap.has(xhrIndex)) {
52
- return undefined;
53
- }
54
- const index = this.xhrIdMap.get(xhrIndex)!();
55
- return this.requests[index];
56
- };
57
-
58
- private updateRequest = (
59
- index: number,
60
- update: Partial<NetworkRequestInfo>,
61
- ) => {
62
- const networkInfo = this.getRequest(index);
63
- if (!networkInfo) {
64
- return;
65
- }
66
- networkInfo.update(update);
67
- };
68
-
69
- private openCallback = (method: RequestMethod, url: string, xhr: XHR) => {
70
- if (this.paused) {
71
- return;
72
- }
73
-
74
- if (this.ignoredHosts) {
75
- const host = extractHost(url);
76
- if (host && this.ignoredHosts.has(host)) {
77
- return;
78
- }
79
- }
80
-
81
- if (this.ignoredUrls && this.ignoredUrls.has(url)) {
82
- return;
83
- }
84
-
85
- if (this.ignoredPatterns) {
86
- if (
87
- this.ignoredPatterns.some(pattern => pattern.test(`${method} ${url}`))
88
- ) {
89
- return;
90
- }
91
- }
92
-
93
- xhr._index = nextXHRId++;
94
- this.xhrIdMap.set(xhr._index, () => {
95
- return this.requests.findIndex(r => r.id === `${xhr._index}`);
96
- });
97
-
98
- const newRequest = new NetworkRequestInfo(
99
- `${xhr._index}`,
100
- 'XMLHttpRequest',
101
- method,
102
- url,
103
- );
104
-
105
- if (this.requests.length >= this.maxRequests) {
106
- this.requests.pop();
107
- }
108
-
109
- this.requests.unshift(newRequest);
110
- };
111
-
112
- private requestHeadersCallback = (
113
- header: string,
114
- value: string,
115
- xhr: XHR,
116
- ) => {
117
- const networkInfo = this.getRequest(xhr._index);
118
- if (!networkInfo) {
119
- return;
120
- }
121
- networkInfo.requestHeaders[header] = value;
122
- };
123
-
124
- private headerReceivedCallback = (
125
- responseContentType: string,
126
- responseSize: number,
127
- responseHeaders: Headers,
128
- xhr: XHR,
129
- ) => {
130
- this.updateRequest(xhr._index, {
131
- responseContentType,
132
- responseSize,
133
- responseHeaders: xhr.responseHeaders,
134
- });
135
- };
136
-
137
- private sendCallback = (data: string, xhr: XHR) => {
138
- this.updateRequest(xhr._index, {
139
- startTime: Date.now(),
140
- dataSent: data,
141
- });
142
- this.debouncedCallback();
143
- };
144
-
145
- private responseCallback = (
146
- status: number,
147
- timeout: number,
148
- response: string,
149
- responseURL: string,
150
- responseType: string,
151
- xhr: XHR,
152
- ) => {
153
- this.updateRequest(xhr._index, {
154
- endTime: Date.now(),
155
- status,
156
- timeout,
157
- response,
158
- responseURL,
159
- responseType,
160
- });
161
- this.debouncedCallback();
162
- };
163
-
164
- enableXHRInterception = (options?: StartNetworkLoggingOptions) => {
165
- if (
166
- this.enabled ||
167
- (XHRInterceptor.isInterceptorEnabled() && !options?.forceEnable)
168
- ) {
169
- if (!this.enabled) {
170
- warn(
171
- 'network interceptor has not been enabled as another interceptor is already running (e.g. another debugging program). Use option `forceEnable: true` to override this behaviour.',
172
- );
173
- }
174
- return;
175
- }
176
-
177
- if (options?.maxRequests !== undefined) {
178
- if (typeof options.maxRequests !== 'number' || options.maxRequests < 1) {
179
- warn(
180
- 'maxRequests must be a number greater than 0. The logger has not been started.',
181
- );
182
- return;
183
- }
184
- this.maxRequests = options.maxRequests;
185
- }
186
-
187
- if (options?.ignoredHosts) {
188
- if (
189
- !Array.isArray(options.ignoredHosts) ||
190
- typeof options.ignoredHosts[0] !== 'string'
191
- ) {
192
- warn(
193
- 'ignoredHosts must be an array of strings. The logger has not been started.',
194
- );
195
- return;
196
- }
197
- this.ignoredHosts = new Set(options.ignoredHosts);
198
- }
199
-
200
- if (options?.refreshRate) {
201
- if (typeof options.refreshRate !== 'number' || options.refreshRate < 1) {
202
- warn(
203
- 'refreshRate must be a number greater than 0. The logger has not been started.',
204
- );
205
- return;
206
- }
207
- this.refreshRate = options.refreshRate;
208
- }
209
-
210
- if (options?.ignoredPatterns) {
211
- this.ignoredPatterns = options.ignoredPatterns;
212
- }
213
-
214
- if (options?.ignoredUrls) {
215
- if (
216
- !Array.isArray(options.ignoredUrls) ||
217
- typeof options.ignoredUrls[0] !== 'string'
218
- ) {
219
- warn(
220
- 'ignoredUrls must be an array of strings. The logger has not been started.',
221
- );
222
- return;
223
- }
224
- this.ignoredUrls = new Set(options.ignoredUrls);
225
- }
226
-
227
- XHRInterceptor.setOpenCallback(this.openCallback);
228
- XHRInterceptor.setRequestHeaderCallback(this.requestHeadersCallback);
229
- XHRInterceptor.setHeaderReceivedCallback(this.headerReceivedCallback);
230
- XHRInterceptor.setSendCallback(this.sendCallback);
231
- XHRInterceptor.setResponseCallback(this.responseCallback);
232
-
233
- XHRInterceptor.enableInterception();
234
- this.enabled = true;
235
- };
236
-
237
- getRequests = () => {
238
- return this.requests;
239
- };
240
-
241
- clearRequests = () => {
242
- this.requests = [];
243
- this.latestRequestUpdatedAt = 0;
244
- this.debouncedCallback();
245
- };
246
-
247
- disableXHRInterception = () => {
248
- if (!this.enabled) {
249
- return;
250
- }
251
-
252
- this.clearRequests();
253
-
254
- nextXHRId = 0;
255
- this.enabled = false;
256
- this.paused = false;
257
- this.xhrIdMap.clear();
258
- this.maxRequests = LOGGER_MAX_REQUESTS;
259
- this.refreshRate = LOGGER_REFRESH_RATE;
260
- this.ignoredHosts = undefined;
261
- this.ignoredUrls = undefined;
262
- this.ignoredPatterns = undefined;
263
-
264
- const noop = (): void => null;
265
- // manually reset callbacks even if the XHRInterceptor lib does it for us with 'disableInterception'
266
- XHRInterceptor.setOpenCallback(noop);
267
- XHRInterceptor.setRequestHeaderCallback(noop);
268
- XHRInterceptor.setHeaderReceivedCallback(noop);
269
- XHRInterceptor.setSendCallback(noop);
270
- XHRInterceptor.setResponseCallback(noop);
271
-
272
- XHRInterceptor.disableInterception();
273
- };
274
- }
@@ -1,161 +0,0 @@
1
- // @ts-ignore
2
- import BlobFileReader from 'react-native/Libraries/Blob/FileReader';
3
- import type {Headers, NetworkRequestInfoRow, RequestMethod} from './types';
4
- import fromEntries from './utils/fromEntries';
5
-
6
- export default class NetworkRequestInfo {
7
- id = '';
8
- type = '';
9
- url = '';
10
- method: RequestMethod;
11
- status: number = -1;
12
- dataSent = '';
13
- responseContentType = '';
14
- responseSize = 0;
15
- requestHeaders: Headers = {};
16
- responseHeaders: Headers = {};
17
- response = '';
18
- responseURL = '';
19
- responseType = '';
20
- timeout = 0;
21
- closeReason = '';
22
- messages = '';
23
- serverClose: any = undefined;
24
- serverError: any = undefined;
25
- startTime: number = 0;
26
- endTime: number = 0;
27
- gqlOperation?: string;
28
- updatedAt: number = 0;
29
-
30
- constructor(id: string, type: string, method: RequestMethod, url: string) {
31
- this.id = id;
32
- this.type = type;
33
- this.method = method;
34
- this.url = url;
35
- this.updatedAt = Date.now();
36
- }
37
-
38
- get duration() {
39
- return this.endTime - this.startTime;
40
- }
41
-
42
- get curlRequest() {
43
- let headersPart =
44
- this.requestHeaders &&
45
- Object.entries(this.requestHeaders)
46
- .map(([key, value]) => `'${key}: ${this.escapeQuotes(value)}'`)
47
- .join(' -H ');
48
- headersPart = headersPart ? `-H ${headersPart}` : '';
49
-
50
- const body = this.dataSent && this.escapeQuotes(this.dataSent);
51
-
52
- const methodPart =
53
- this.method !== 'GET' ? `-X${this.method.toUpperCase()}` : '';
54
- const bodyPart = body ? `-d '${body}'` : '';
55
-
56
- const parts = ['curl', methodPart, headersPart, bodyPart, `'${this.url}'`];
57
-
58
- return parts.filter(Boolean).join(' ');
59
- }
60
-
61
- update(values: Partial<NetworkRequestInfo>) {
62
- Object.assign(this, values);
63
- if (values.dataSent) {
64
- const data = this.parseData(values.dataSent);
65
- this.gqlOperation = data?.operationName;
66
- }
67
- this.updatedAt = Date.now();
68
- }
69
-
70
- private escapeQuotes(value: string) {
71
- return value.replace?.(/'/g, "\\'");
72
- }
73
-
74
- private parseData(data: any) {
75
- try {
76
- if (data?._parts?.length) {
77
- return fromEntries(data?._parts);
78
- }
79
- return JSON.parse(data);
80
- } catch (e) {
81
- return {data};
82
- }
83
- }
84
-
85
- private stringifyFormat(data: any) {
86
- return JSON.stringify(this.parseData(data), null, 2);
87
- }
88
-
89
- public toRow(): NetworkRequestInfoRow {
90
- return {
91
- url: this.url,
92
- gqlOperation: this.gqlOperation,
93
- id: this.id,
94
- method: this.method,
95
- status: this.status,
96
- duration: this.duration,
97
- startTime: this.startTime,
98
- };
99
- }
100
-
101
- getRequestBody(replaceEscaped = false) {
102
- const body = this.stringifyFormat(this.dataSent);
103
-
104
- if (replaceEscaped) {
105
- return body.replace(/\\n/g, '\n').replace(/\\"/g, '"');
106
- }
107
-
108
- return body;
109
- }
110
-
111
- private async parseResponseBlob() {
112
- const blobReader = new BlobFileReader();
113
- blobReader.readAsText(this.response);
114
-
115
- return await new Promise<string>((resolve, reject) => {
116
- const handleError = () => reject(blobReader.error);
117
-
118
- blobReader.addEventListener('load', () => {
119
- resolve(blobReader.result);
120
- });
121
- blobReader.addEventListener('error', handleError);
122
- blobReader.addEventListener('abort', handleError);
123
- });
124
- }
125
-
126
- async getResponseBody() {
127
- const body = await (this.responseType !== 'blob'
128
- ? this.response
129
- : this.parseResponseBlob());
130
-
131
- return this.stringifyFormat(body);
132
- }
133
-
134
- public copy(): NetworkRequestInfo {
135
- const newInstance = new NetworkRequestInfo(this.id, this.type, this.method, this.url);
136
-
137
- // 复制基本类型属性
138
- newInstance.status = this.status;
139
- newInstance.dataSent = this.dataSent;
140
- newInstance.responseContentType = this.responseContentType;
141
- newInstance.responseSize = this.responseSize;
142
- newInstance.response = this.response;
143
- newInstance.responseURL = this.responseURL;
144
- newInstance.responseType = this.responseType;
145
- newInstance.timeout = this.timeout;
146
- newInstance.closeReason = this.closeReason;
147
- newInstance.messages = this.messages;
148
- newInstance.serverClose = this.serverClose;
149
- newInstance.serverError = this.serverError;
150
- newInstance.startTime = this.startTime;
151
- newInstance.endTime = this.endTime;
152
- newInstance.gqlOperation = this.gqlOperation;
153
- newInstance.updatedAt = this.updatedAt;
154
-
155
- // 深拷贝对象类型属性
156
- newInstance.requestHeaders = JSON.parse(JSON.stringify(this.requestHeaders));
157
- newInstance.responseHeaders = JSON.parse(JSON.stringify(this.responseHeaders));
158
-
159
- return newInstance;
160
- }
161
- }
@@ -1,3 +0,0 @@
1
- // StartNetworkLoggingOptions
2
- export const LOGGER_MAX_REQUESTS: number = 500;
3
- export const LOGGER_REFRESH_RATE: number = 50;