@capybara-devtools/core 0.5.0 → 0.5.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.
Files changed (102) hide show
  1. package/dist/client.d.ts.map +1 -1
  2. package/dist/client.js +20 -2
  3. package/dist/client.js.map +1 -1
  4. package/dist/index.d.ts +8 -2
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +4 -1
  7. package/dist/index.js.map +1 -1
  8. package/dist/init.d.ts +40 -0
  9. package/dist/init.d.ts.map +1 -0
  10. package/dist/init.js +35 -0
  11. package/dist/init.js.map +1 -0
  12. package/dist/plugins/console.d.ts.map +1 -1
  13. package/dist/plugins/console.js +105 -9
  14. package/dist/plugins/console.js.map +1 -1
  15. package/dist/plugins/network/body.d.ts +9 -0
  16. package/dist/plugins/network/body.d.ts.map +1 -0
  17. package/dist/plugins/network/body.js +114 -0
  18. package/dist/plugins/network/body.js.map +1 -0
  19. package/dist/plugins/network/failure.d.ts +16 -0
  20. package/dist/plugins/network/failure.d.ts.map +1 -0
  21. package/dist/plugins/network/failure.js +73 -0
  22. package/dist/plugins/network/failure.js.map +1 -0
  23. package/dist/plugins/network/fetch.d.ts +12 -0
  24. package/dist/plugins/network/fetch.d.ts.map +1 -0
  25. package/dist/plugins/network/fetch.js +159 -0
  26. package/dist/plugins/network/fetch.js.map +1 -0
  27. package/dist/plugins/network/settings.d.ts +24 -0
  28. package/dist/plugins/network/settings.d.ts.map +1 -0
  29. package/dist/plugins/network/settings.js +26 -0
  30. package/dist/plugins/network/settings.js.map +1 -0
  31. package/dist/plugins/network/xhr.d.ts +4 -0
  32. package/dist/plugins/network/xhr.d.ts.map +1 -0
  33. package/dist/plugins/network/xhr.js +214 -0
  34. package/dist/plugins/network/xhr.js.map +1 -0
  35. package/dist/plugins/network.d.ts +2 -15
  36. package/dist/plugins/network.d.ts.map +1 -1
  37. package/dist/plugins/network.js +5 -518
  38. package/dist/plugins/network.js.map +1 -1
  39. package/dist/plugins/state/context-names.d.ts +13 -0
  40. package/dist/plugins/state/context-names.d.ts.map +1 -0
  41. package/dist/plugins/state/context-names.js +280 -0
  42. package/dist/plugins/state/context-names.js.map +1 -0
  43. package/dist/plugins/state/context.d.ts +0 -89
  44. package/dist/plugins/state/context.d.ts.map +1 -1
  45. package/dist/plugins/state/context.js +3 -474
  46. package/dist/plugins/state/context.js.map +1 -1
  47. package/dist/plugins/state/engine.d.ts +5 -0
  48. package/dist/plugins/state/engine.d.ts.map +1 -1
  49. package/dist/plugins/state/engine.js +12 -2
  50. package/dist/plugins/state/engine.js.map +1 -1
  51. package/dist/plugins/state/fibers.d.ts +75 -0
  52. package/dist/plugins/state/fibers.d.ts.map +1 -0
  53. package/dist/plugins/state/fibers.js +92 -0
  54. package/dist/plugins/state/fibers.js.map +1 -0
  55. package/dist/plugins/state/index.d.ts +5 -0
  56. package/dist/plugins/state/index.d.ts.map +1 -1
  57. package/dist/plugins/state/index.js.map +1 -1
  58. package/dist/plugins/state/mobx.d.ts +22 -0
  59. package/dist/plugins/state/mobx.d.ts.map +1 -0
  60. package/dist/plugins/state/mobx.js +69 -0
  61. package/dist/plugins/state/mobx.js.map +1 -0
  62. package/dist/plugins/state/react-hook.d.ts +19 -0
  63. package/dist/plugins/state/react-hook.d.ts.map +1 -0
  64. package/dist/plugins/state/react-hook.js +100 -0
  65. package/dist/plugins/state/react-hook.js.map +1 -0
  66. package/dist/plugins/state/redux.d.ts +2 -0
  67. package/dist/plugins/state/redux.d.ts.map +1 -1
  68. package/dist/plugins/state/redux.js +2 -2
  69. package/dist/plugins/state/redux.js.map +1 -1
  70. package/dist/plugins/state/xstate.d.ts +26 -0
  71. package/dist/plugins/state/xstate.d.ts.map +1 -0
  72. package/dist/plugins/state/xstate.js +85 -0
  73. package/dist/plugins/state/xstate.js.map +1 -0
  74. package/dist/plugins/storage.d.ts +1 -1
  75. package/dist/plugins/storage.d.ts.map +1 -1
  76. package/dist/plugins/storage.js +5 -7
  77. package/dist/plugins/storage.js.map +1 -1
  78. package/dist/serialize.d.ts.map +1 -1
  79. package/dist/serialize.js +1 -0
  80. package/dist/serialize.js.map +1 -1
  81. package/package.json +7 -5
  82. package/src/client.ts +19 -2
  83. package/src/index.ts +8 -2
  84. package/src/init.ts +66 -0
  85. package/src/plugins/console.ts +103 -10
  86. package/src/plugins/network/body.ts +114 -0
  87. package/src/plugins/network/failure.ts +79 -0
  88. package/src/plugins/network/fetch.ts +169 -0
  89. package/src/plugins/network/settings.ts +48 -0
  90. package/src/plugins/network/xhr.ts +223 -0
  91. package/src/plugins/network.ts +8 -572
  92. package/src/plugins/state/context-names.ts +265 -0
  93. package/src/plugins/state/context.ts +3 -532
  94. package/src/plugins/state/engine.ts +12 -2
  95. package/src/plugins/state/fibers.ts +160 -0
  96. package/src/plugins/state/index.ts +2 -0
  97. package/src/plugins/state/mobx.ts +80 -0
  98. package/src/plugins/state/react-hook.ts +98 -0
  99. package/src/plugins/state/redux.ts +2 -2
  100. package/src/plugins/state/xstate.ts +94 -0
  101. package/src/plugins/storage.ts +13 -8
  102. package/src/serialize.ts +2 -1
@@ -0,0 +1,223 @@
1
+ import type { BodyPreview } from '@capybara-devtools/protocol';
2
+ import type { PluginContext } from '../../client.js';
3
+ import { now, randomId } from '../../utils.js';
4
+ import { absoluteUrl, findHeader, isTextual, parseRawHeaders, previewRequestBody, textPreview } from './body.js';
5
+ import type { FetchFunction } from './fetch.js';
6
+ import type { Settings } from './settings.js';
7
+
8
+ interface XhrInfo {
9
+ method: string;
10
+ url: string;
11
+ headers: Record<string, string>;
12
+ }
13
+
14
+ const XHR_DONE = 4;
15
+
16
+ export function patchXhr(ctx: PluginContext, settings: Settings, fetchOverXhr: boolean): () => void {
17
+ const XHR = (globalThis as { XMLHttpRequest?: { prototype: XMLHttpRequest } }).XMLHttpRequest;
18
+ if (!XHR?.prototype) return () => {};
19
+ const proto = XHR.prototype;
20
+ const g = globalThis as { fetch?: FetchFunction };
21
+ // whatwg-fetch opens and sends its XHR inside the fetch call, so XHRs sent meanwhile are the fetch.
22
+ let fetching = 0;
23
+ const originalFetch = fetchOverXhr ? g.fetch : undefined;
24
+ const taggedFetch: FetchFunction | undefined = originalFetch
25
+ ? Object.assign(
26
+ function fetch(this: unknown) {
27
+ fetching++;
28
+ try {
29
+ return originalFetch.apply(this, arguments as unknown as unknown[]);
30
+ } finally {
31
+ fetching--;
32
+ }
33
+ },
34
+ { polyfill: originalFetch.polyfill },
35
+ )
36
+ : undefined;
37
+ if (taggedFetch) g.fetch = taggedFetch;
38
+ const originalOpen = proto.open;
39
+ const originalSend = proto.send;
40
+ const originalSetRequestHeader = proto.setRequestHeader;
41
+ const requests = new WeakMap<XMLHttpRequest, XhrInfo>();
42
+ // React Native hands the native reason for a failure (e.g. "Unable to resolve host …") to this
43
+ // internal method. It reaches responseText only for text responses, and whatwg-fetch asks for blobs.
44
+ const nativeErrors = new WeakMap<XMLHttpRequest, string>();
45
+ // Ends the request an XHR is on; apps may open the same XHR again for the next one.
46
+ const inFlight = new WeakMap<XMLHttpRequest, (cutOff?: boolean) => void>();
47
+ let active = true;
48
+ const internals = proto as unknown as Record<string, unknown>;
49
+ const originalComplete = internals.__didCompleteResponse;
50
+ if (typeof originalComplete === 'function') {
51
+ internals.__didCompleteResponse = function (this: XMLHttpRequest, _requestId: unknown, error: unknown) {
52
+ if (typeof error === 'string' && error) nativeErrors.set(this, error);
53
+ return (originalComplete as (...args: unknown[]) => unknown).apply(this, arguments as unknown as unknown[]);
54
+ };
55
+ }
56
+
57
+ const track = (xhr: XMLHttpRequest, info: XhrInfo, body: unknown) => {
58
+ const id = randomId();
59
+ const start = now();
60
+ ctx.emit('network.request', {
61
+ id,
62
+ initiator: fetching > 0 ? 'fetch' : 'xhr',
63
+ method: info.method,
64
+ url: absoluteUrl(info.url),
65
+ headers: settings.redact(info.headers),
66
+ body: previewRequestBody(body, settings.maxBody, findHeader(info.headers, 'content-type')),
67
+ });
68
+
69
+ let failure: 'error' | 'timeout' | 'abort' | undefined;
70
+ const listeners: Record<string, () => void> = {
71
+ error: () => (failure = 'error'),
72
+ timeout: () => (failure = 'timeout'),
73
+ abort: () => (failure = 'abort'),
74
+ loadend: () => {
75
+ // Browsers still dispatch the last request's loadend after the app opened the XHR again from its onload.
76
+ if (typeof xhr.readyState === 'number' && xhr.readyState !== XHR_DONE) return;
77
+ end();
78
+ },
79
+ };
80
+ for (const [type, listener] of Object.entries(listeners)) xhr.addEventListener(type, listener);
81
+ const end = (cutOff = false) => {
82
+ for (const [type, listener] of Object.entries(listeners)) xhr.removeEventListener(type, listener);
83
+ if (inFlight.get(xhr) === end) inFlight.delete(xhr);
84
+ if (cutOff) failure = 'abort';
85
+ const duration = now() - start;
86
+ try {
87
+ if (failure || xhr.status === 0) {
88
+ const base = { id, duration, aborted: failure === 'abort', timeout: failure === 'timeout' };
89
+ if (failure === 'timeout' || failure === 'abort') {
90
+ ctx.emit('network.error', { ...base, message: failure === 'timeout' ? 'Request timed out' : 'Request aborted' });
91
+ return;
92
+ }
93
+ const native = nativeErrors.get(xhr);
94
+ if (native) {
95
+ ctx.emit('network.error', { ...base, message: native });
96
+ return;
97
+ }
98
+ settings.failures.explain(absoluteUrl(info.url), xhr.withCredentials === true, (explanation) =>
99
+ ctx.emit('network.error', { ...base, ...explanation, message: explanation.message ?? 'Network request failed' }),
100
+ );
101
+ return;
102
+ }
103
+ const headers = parseRawHeaders(xhr.getAllResponseHeaders());
104
+ const done = (responseBody?: BodyPreview) =>
105
+ ctx.emit('network.response', {
106
+ id,
107
+ status: xhr.status,
108
+ statusText: xhr.statusText || undefined,
109
+ headers: settings.redact(headers),
110
+ body: responseBody,
111
+ duration,
112
+ });
113
+ const result = readXhrBody(xhr, findHeader(headers, 'content-type'), settings.maxBody);
114
+ if (result && typeof (result as Promise<unknown>).then === 'function') {
115
+ (result as Promise<BodyPreview | undefined>).then(done, () => done());
116
+ } else {
117
+ done(result as BodyPreview | undefined);
118
+ }
119
+ } catch {
120
+ // never surface SDK failures to the app
121
+ }
122
+ };
123
+ inFlight.set(xhr, end);
124
+ };
125
+
126
+ proto.open = function open(this: XMLHttpRequest, method: string, url: string | URL) {
127
+ // Opening resets the XHR: record a request that is done but whose loadend has not run (opened again from onload).
128
+ if (this.readyState === XHR_DONE) inFlight.get(this)?.();
129
+ requests.set(this, { method: String(method).toUpperCase(), url: String(url), headers: {} });
130
+ nativeErrors.delete(this);
131
+ // `arguments` keeps the caller's exact arity; some engines treat an explicit `undefined` async flag as false.
132
+ const result = (originalOpen as (...args: unknown[]) => void).apply(this, arguments as unknown as unknown[]);
133
+ // A request still on its way is cut off, and browsers fire no event for it.
134
+ inFlight.get(this)?.(true);
135
+ return result;
136
+ } as XMLHttpRequest['open'];
137
+
138
+ proto.setRequestHeader = function setRequestHeader(this: XMLHttpRequest, name: string, value: string) {
139
+ const info = requests.get(this);
140
+ if (info) info.headers[name] = name in info.headers ? `${info.headers[name]}, ${value}` : String(value);
141
+ return originalSetRequestHeader.call(this, name, value);
142
+ };
143
+
144
+ proto.send = function send(this: XMLHttpRequest, body?: Document | XMLHttpRequestBodyInit | null) {
145
+ const info = requests.get(this);
146
+ if (active && info && !settings.isIgnored(info.url)) {
147
+ try {
148
+ track(this, info, body);
149
+ } catch {
150
+ // never surface SDK failures to the app
151
+ }
152
+ }
153
+ return originalSend.call(this, body);
154
+ };
155
+
156
+ const patched = {
157
+ open: proto.open,
158
+ send: proto.send,
159
+ setRequestHeader: proto.setRequestHeader,
160
+ complete: internals.__didCompleteResponse,
161
+ };
162
+ return () => {
163
+ // Wrappers installed after ours (Sentry, Reactotron) stay; ours, still under them, then only pass calls on.
164
+ active = false;
165
+ if (proto.open === patched.open) proto.open = originalOpen;
166
+ if (proto.send === patched.send) proto.send = originalSend;
167
+ if (proto.setRequestHeader === patched.setRequestHeader) proto.setRequestHeader = originalSetRequestHeader;
168
+ if (typeof originalComplete === 'function' && internals.__didCompleteResponse === patched.complete) {
169
+ internals.__didCompleteResponse = originalComplete;
170
+ }
171
+ if (taggedFetch && g.fetch === taggedFetch) g.fetch = originalFetch;
172
+ };
173
+ }
174
+
175
+ function readXhrBody(
176
+ xhr: XMLHttpRequest,
177
+ contentType: string | undefined,
178
+ maxBody: number,
179
+ ): BodyPreview | undefined | Promise<BodyPreview | undefined> {
180
+ const type = xhr.responseType;
181
+ if (type === '' || type === 'text') {
182
+ const text = xhr.responseText;
183
+ return text ? textPreview(text, maxBody, contentType) : undefined;
184
+ }
185
+ const response: unknown = xhr.response;
186
+ if (response === null || response === undefined) return undefined;
187
+ if (type === 'json') {
188
+ try {
189
+ return textPreview(JSON.stringify(response), maxBody, contentType);
190
+ } catch {
191
+ return { kind: 'unknown', contentType, summary: 'JSON' };
192
+ }
193
+ }
194
+ if (type === 'blob') {
195
+ // React Native's fetch polyfill always asks XHR for a blob.
196
+ const blob = response as Blob;
197
+ if (!isTextual(contentType)) return { kind: 'binary', size: blob.size, contentType, summary: contentType ?? 'Blob' };
198
+ const truncated = blob.size > maxBody;
199
+ return readBlobText(truncated ? blob.slice(0, maxBody) : blob).then(
200
+ (text): BodyPreview => ({ kind: 'text', text, size: blob.size, truncated, contentType }),
201
+ );
202
+ }
203
+ if (type === 'arraybuffer') {
204
+ const buffer = response as ArrayBuffer;
205
+ if (isTextual(contentType) && typeof TextDecoder !== 'undefined') {
206
+ const truncated = buffer.byteLength > maxBody;
207
+ const text = new TextDecoder().decode(truncated ? buffer.slice(0, maxBody) : buffer);
208
+ return { kind: 'text', text, size: buffer.byteLength, truncated, contentType };
209
+ }
210
+ return { kind: 'binary', size: buffer.byteLength, contentType, summary: contentType ?? 'ArrayBuffer' };
211
+ }
212
+ return { kind: 'unknown', contentType, summary: `responseType "${type}"` };
213
+ }
214
+
215
+ function readBlobText(blob: Blob): Promise<string> {
216
+ if (typeof blob.text === 'function') return blob.text();
217
+ return new Promise((resolve, reject) => {
218
+ const reader = new FileReader();
219
+ reader.onload = () => resolve(typeof reader.result === 'string' ? reader.result : '');
220
+ reader.onerror = () => reject(reader.error ?? new Error('Failed to read blob'));
221
+ reader.readAsText(blob);
222
+ });
223
+ }