@sgedda/mockifyer-fetch 1.8.107 → 1.8.108
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/README.md +27 -1
- package/dist/clients/fetch-client.d.ts +6 -1
- package/dist/clients/fetch-client.js +43 -5
- package/dist/index.browser.d.ts +2 -1
- package/dist/index.browser.js +7 -3
- package/dist/index.js +9 -2
- package/dist/mockifyer-class.d.ts +5 -0
- package/dist/mockifyer-class.js +120 -9
- package/dist/utils/fetch-response-body.d.ts +18 -1
- package/dist/utils/fetch-response-body.js +18 -4
- package/package.json +2 -2
- package/src/clients/fetch-client.ts +56 -7
- package/src/index.browser.ts +8 -3
- package/src/index.ts +16 -6
- package/src/mockifyer-class.ts +140 -10
- package/src/utils/fetch-response-body.ts +38 -1
package/README.md
CHANGED
|
@@ -23,6 +23,30 @@ const mockifyer = setupMockifyer({
|
|
|
23
23
|
const response = await fetch('https://api.example.com/data');
|
|
24
24
|
```
|
|
25
25
|
|
|
26
|
+
## Streaming responses (SSE / chunked)
|
|
27
|
+
|
|
28
|
+
When a live response is `text/event-stream` or chunked without `Content-Length`, Mockifyer can record a chunk timeline on `response.stream` while keeping `response.data` as the concatenated body (backward compatible).
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
setupMockifyer({
|
|
32
|
+
mockDataPath: './mock-data',
|
|
33
|
+
recordMode: true,
|
|
34
|
+
recordResponses: true,
|
|
35
|
+
useGlobalFetch: true,
|
|
36
|
+
// 'accelerated' (default) | 'original' | 'immediate'
|
|
37
|
+
streamReplay: 'accelerated',
|
|
38
|
+
streamRecordMaxBytes: 1_000_000,
|
|
39
|
+
streamRecordMaxDurationMs: 30_000,
|
|
40
|
+
});
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
- **Record:** the fetch body is teed — your caller still gets the live `ReadableStream` without extra buffering; recording respects the byte/duration caps and sets `truncated` when a cap is hit.
|
|
44
|
+
- **Replay:** mocks with `stream` rebuild a real `ReadableStream` paced by `streamReplay`. Mocks without `stream` behave exactly as before.
|
|
45
|
+
- **Proxy (phase 1):** dashboard `/api/proxy` still returns a JSON envelope; the client rebuilds the stream from stored chunks on mock-hit.
|
|
46
|
+
- **React Native:** if `ReadableStream` is unavailable, Mockifyer falls back to flat bodies (no crash).
|
|
47
|
+
|
|
48
|
+
Axios `responseType: 'stream'` and `EventSource` patching are not included in this release.
|
|
49
|
+
|
|
26
50
|
## Browser & Expo Web Usage
|
|
27
51
|
|
|
28
52
|
Mockifyer works in browsers and Expo web builds with the memory provider and preloaded fixtures.
|
|
@@ -141,13 +165,15 @@ Mockifyer uses package.json `browser` field mappings to automatically resolve br
|
|
|
141
165
|
|
|
142
166
|
### Limitations in Browser
|
|
143
167
|
|
|
144
|
-
- No filesystem
|
|
168
|
+
- **No local filesystem recording**. Record through the dashboard proxy or in Node.
|
|
145
169
|
- No Redis/SQLite support
|
|
146
170
|
- All fixtures must be preloaded at initialization
|
|
147
171
|
- Request correlation is simplified (header-only)
|
|
148
172
|
- No Atlas HTML generation
|
|
149
173
|
- No screenshot capture
|
|
150
174
|
|
|
175
|
+
**Dashboard proxy in the browser:** Set `proxy.baseUrl` (for example `http://localhost:3002`) in `setupMockifyer`. The browser build sends requests to the dashboard's `/api/proxy` using `fetch`, so you can record and replay through the dashboard without Node. `initMockifyerForDashboardProxy` and `initMockifyerForDashboardProxyClients` are not available in browser builds, so use `setupMockifyer` from the browser entry.
|
|
176
|
+
|
|
151
177
|
### See Also
|
|
152
178
|
|
|
153
179
|
- [@sgedda/mockifyer-core](../mockifyer-core/README.md) - Core types and providers
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BaseHTTPClient, HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
|
|
1
|
+
import { BaseHTTPClient, HTTPRequestConfig, HTTPResponse, type StreamRecordCaps } from '@sgedda/mockifyer-core';
|
|
2
2
|
export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
3
3
|
private baseUrl?;
|
|
4
4
|
private defaultHeaders;
|
|
@@ -11,6 +11,8 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
|
|
|
11
11
|
private getStrictLaneScenario?;
|
|
12
12
|
private getUpstreamTlsInsecure?;
|
|
13
13
|
private getExplicitProxyScenarioContext?;
|
|
14
|
+
private getShouldRecordStreams?;
|
|
15
|
+
private getStreamRecordCaps?;
|
|
14
16
|
private clientIdSnapshot?;
|
|
15
17
|
private deviceId?;
|
|
16
18
|
constructor(config?: {
|
|
@@ -30,6 +32,9 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
|
|
|
30
32
|
getUpstreamTlsInsecure?: () => boolean;
|
|
31
33
|
/** When false, skip `/api/proxy` and call the real URL (devtools-friendly passthrough). */
|
|
32
34
|
getExplicitProxyScenarioContext?: () => boolean;
|
|
35
|
+
/** When true, tee streaming bodies and capture chunk timelines while recording. */
|
|
36
|
+
getShouldRecordStreams?: () => boolean;
|
|
37
|
+
getStreamRecordCaps?: () => StreamRecordCaps;
|
|
33
38
|
deviceId?: string;
|
|
34
39
|
});
|
|
35
40
|
private resolvedClientLane;
|
|
@@ -57,6 +57,8 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
|
|
|
57
57
|
this.getStrictLaneScenario = config?.getStrictLaneScenario;
|
|
58
58
|
this.getUpstreamTlsInsecure = config?.getUpstreamTlsInsecure;
|
|
59
59
|
this.getExplicitProxyScenarioContext = config?.getExplicitProxyScenarioContext;
|
|
60
|
+
this.getShouldRecordStreams = config?.getShouldRecordStreams;
|
|
61
|
+
this.getStreamRecordCaps = config?.getStreamRecordCaps;
|
|
60
62
|
this.clientIdSnapshot = config?.clientId;
|
|
61
63
|
this.deviceId = config?.deviceId;
|
|
62
64
|
}
|
|
@@ -161,7 +163,48 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
|
|
|
161
163
|
headers.set(mockifyer_core_1.MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
|
|
162
164
|
}
|
|
163
165
|
const response = await fetchFn(url, requestConfig);
|
|
166
|
+
const responseHeaders = {};
|
|
167
|
+
response.headers.forEach((value, key) => {
|
|
168
|
+
responseHeaders[key] = value;
|
|
169
|
+
});
|
|
170
|
+
const mockifyerTrace = (0, mockifyer_core_1.resolveMockifyerTraceFromHeaders)(responseHeaders);
|
|
164
171
|
const contentType = response.headers.get('content-type') || '';
|
|
172
|
+
const streamKind = (0, mockifyer_core_1.detectStreamKind)(response.headers);
|
|
173
|
+
const canStream = (0, mockifyer_core_1.supportsReadableStreamBody)() && streamKind != null && response.body != null;
|
|
174
|
+
const shouldRecordStreams = this.getShouldRecordStreams?.() === true;
|
|
175
|
+
// Streaming path: pass the live body through without buffering so the caller
|
|
176
|
+
// is not delayed. When recording, tee and capture chunks in the background.
|
|
177
|
+
if (canStream) {
|
|
178
|
+
const caps = this.getStreamRecordCaps?.() ?? {};
|
|
179
|
+
if (shouldRecordStreams) {
|
|
180
|
+
const teed = (0, mockifyer_core_1.teeResponseBodyForRecording)(response.body);
|
|
181
|
+
if (teed) {
|
|
182
|
+
const recording = (0, mockifyer_core_1.captureReadableStreamChunks)(teed.record, streamKind, caps);
|
|
183
|
+
return {
|
|
184
|
+
data: teed.live,
|
|
185
|
+
status: response.status,
|
|
186
|
+
statusText: response.statusText,
|
|
187
|
+
headers: responseHeaders,
|
|
188
|
+
config,
|
|
189
|
+
mockifyerStreamRecording: recording,
|
|
190
|
+
...(mockifyerTrace ? { mockifyerTrace } : {}),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
// Tee unavailable — fall through to buffered text() so recording still works.
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
// Not recording: avoid buffering the live stream for the caller.
|
|
197
|
+
return {
|
|
198
|
+
data: response.body,
|
|
199
|
+
status: response.status,
|
|
200
|
+
statusText: response.statusText,
|
|
201
|
+
headers: responseHeaders,
|
|
202
|
+
config,
|
|
203
|
+
...(mockifyerTrace ? { mockifyerTrace } : {}),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
// Flat path (legacy / React Native without ReadableStream / non-stream responses)
|
|
165
208
|
const rawText = await response.text();
|
|
166
209
|
let data = rawText;
|
|
167
210
|
if (contentType.includes('application/json')) {
|
|
@@ -172,11 +215,6 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
|
|
|
172
215
|
data = rawText;
|
|
173
216
|
}
|
|
174
217
|
}
|
|
175
|
-
const responseHeaders = {};
|
|
176
|
-
response.headers.forEach((value, key) => {
|
|
177
|
-
responseHeaders[key] = value;
|
|
178
|
-
});
|
|
179
|
-
const mockifyerTrace = (0, mockifyer_core_1.resolveMockifyerTraceFromHeaders)(responseHeaders);
|
|
180
218
|
return {
|
|
181
219
|
data,
|
|
182
220
|
status: response.status,
|
package/dist/index.browser.d.ts
CHANGED
|
@@ -6,7 +6,8 @@ import type { MockifyerConfig, MockData, StoredRequest, StoredResponse, HTTPClie
|
|
|
6
6
|
export type { MockifyerConfig, MockData, StoredRequest, StoredResponse, HTTPClient, HTTPResponse, DatabaseProvider, DatabaseProviderConfig, };
|
|
7
7
|
export { MemoryProvider, createProvider, } from '@sgedda/mockifyer-core';
|
|
8
8
|
export { FetchHTTPClient } from './clients/fetch-client';
|
|
9
|
-
|
|
9
|
+
import { bodyInitForFetchResponse } from './utils/fetch-response-body';
|
|
10
|
+
export { bodyInitForFetchResponse };
|
|
10
11
|
export { resolvePatchedFetchRequest } from './utils/resolve-patched-fetch-request';
|
|
11
12
|
export { canUseDashboardRedisProxy, canUseDashboardCentralProxy, } from './utils/dashboard-redis-health';
|
|
12
13
|
export interface MockifyerInstance extends HTTPClient {
|
package/dist/index.browser.js
CHANGED
|
@@ -12,7 +12,7 @@ Object.defineProperty(exports, "createProvider", { enumerable: true, get: functi
|
|
|
12
12
|
// Re-export browser-safe fetch utilities
|
|
13
13
|
var fetch_client_1 = require("./clients/fetch-client");
|
|
14
14
|
Object.defineProperty(exports, "FetchHTTPClient", { enumerable: true, get: function () { return fetch_client_1.FetchHTTPClient; } });
|
|
15
|
-
|
|
15
|
+
const fetch_response_body_1 = require("./utils/fetch-response-body");
|
|
16
16
|
Object.defineProperty(exports, "bodyInitForFetchResponse", { enumerable: true, get: function () { return fetch_response_body_1.bodyInitForFetchResponse; } });
|
|
17
17
|
var resolve_patched_fetch_request_1 = require("./utils/resolve-patched-fetch-request");
|
|
18
18
|
Object.defineProperty(exports, "resolvePatchedFetchRequest", { enumerable: true, get: function () { return resolve_patched_fetch_request_1.resolvePatchedFetchRequest; } });
|
|
@@ -82,9 +82,13 @@ function setupMockifyer(config) {
|
|
|
82
82
|
headers: init?.headers || {},
|
|
83
83
|
data: init?.body,
|
|
84
84
|
});
|
|
85
|
-
// Convert mockifyer response to fetch Response
|
|
86
|
-
return new Response(
|
|
85
|
+
// Convert mockifyer response to fetch Response (rebuild stream when present)
|
|
86
|
+
return new Response((0, fetch_response_body_1.bodyInitForFetchResponse)(response.status, response.data, {
|
|
87
|
+
stream: response.mockifyerStoredStream,
|
|
88
|
+
streamReplay: config.streamReplay,
|
|
89
|
+
}), {
|
|
87
90
|
status: response.status,
|
|
91
|
+
statusText: response.statusText || '',
|
|
88
92
|
headers: new Headers(response.headers || {})
|
|
89
93
|
});
|
|
90
94
|
};
|
package/dist/index.js
CHANGED
|
@@ -166,7 +166,11 @@ function setupMockifyer(config) {
|
|
|
166
166
|
}
|
|
167
167
|
});
|
|
168
168
|
}
|
|
169
|
-
|
|
169
|
+
const streamOpts = {
|
|
170
|
+
stream: response.mockifyerStoredStream,
|
|
171
|
+
streamReplay: resolvedConfig.streamReplay,
|
|
172
|
+
};
|
|
173
|
+
return new Response((0, fetch_response_body_1.bodyInitForFetchResponse)(response.status, response.data, streamOpts), {
|
|
170
174
|
status: response.status,
|
|
171
175
|
statusText: response.statusText || '',
|
|
172
176
|
headers: responseHeaders
|
|
@@ -179,7 +183,10 @@ function setupMockifyer(config) {
|
|
|
179
183
|
responseHeaders.set(key, String(value));
|
|
180
184
|
});
|
|
181
185
|
const errorStatus = error.response.status;
|
|
182
|
-
return new Response((0, fetch_response_body_1.bodyInitForFetchResponse)(errorStatus, error.response.data
|
|
186
|
+
return new Response((0, fetch_response_body_1.bodyInitForFetchResponse)(errorStatus, error.response.data, {
|
|
187
|
+
stream: error.response.mockifyerStoredStream,
|
|
188
|
+
streamReplay: resolvedConfig.streamReplay,
|
|
189
|
+
}), {
|
|
183
190
|
status: errorStatus,
|
|
184
191
|
statusText: error.response.statusText || '',
|
|
185
192
|
headers: responseHeaders
|
|
@@ -76,6 +76,11 @@ export declare class MockifyerClass {
|
|
|
76
76
|
private setupResponseInterceptor;
|
|
77
77
|
private maybeMirrorProxyRecordingToClient;
|
|
78
78
|
private tryMirrorProxyRecordingViaMetro;
|
|
79
|
+
/**
|
|
80
|
+
* Await background stream capture, then persist concatenated body + stream timeline.
|
|
81
|
+
* Called without blocking the caller's live ReadableStream.
|
|
82
|
+
*/
|
|
83
|
+
private saveStreamRecording;
|
|
79
84
|
private saveResponse;
|
|
80
85
|
private persistMatchedMockAfterLiveCapture;
|
|
81
86
|
/**
|
package/dist/mockifyer-class.js
CHANGED
|
@@ -316,11 +316,22 @@ class MockifyerClass {
|
|
|
316
316
|
config.useSimilarMatch = true;
|
|
317
317
|
}
|
|
318
318
|
}
|
|
319
|
+
let launchClientId;
|
|
320
|
+
if (config.useLaunchArgumentsClientId) {
|
|
321
|
+
const key = config.launchArgumentClientIdKey ?? mockifyer_core_1.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
|
|
322
|
+
launchClientId = (0, mockifyer_core_1.tryGetClientIdFromLaunchArguments)(key);
|
|
323
|
+
if (launchClientId) {
|
|
324
|
+
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] clientId from launch arguments (${key}): ${launchClientId}`);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
319
327
|
// Store config BEFORE any modifications
|
|
320
328
|
this.config = { ...config }; // Create a copy to avoid mutations
|
|
321
|
-
//
|
|
329
|
+
// Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
|
|
322
330
|
// Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
|
|
323
|
-
if (
|
|
331
|
+
if (launchClientId) {
|
|
332
|
+
this.config.clientId = launchClientId;
|
|
333
|
+
}
|
|
334
|
+
else if ((0, mockifyer_core_1.resolveStrictScenarioResolution)(this.config) &&
|
|
324
335
|
Boolean(this.config.proxy?.baseUrl?.trim())) {
|
|
325
336
|
this.config.clientId = (0, mockifyer_core_1.resolveExplicitClientIdOnly)(this.config);
|
|
326
337
|
}
|
|
@@ -351,6 +362,21 @@ class MockifyerClass {
|
|
|
351
362
|
: 'startDisabled: true';
|
|
352
363
|
mockifyer_core_1.logger.info(`[Mockifyer-Fetch] Starting with Mockifyer DISABLED (${reason}). Call enableMockifyer() to activate.`);
|
|
353
364
|
}
|
|
365
|
+
else if ((0, mockifyer_core_1.isScenarioLaunchFromNativeArguments)()) {
|
|
366
|
+
mockifyer_core_1.logger.info('[Mockifyer-Fetch] Starting with Mockifyer ENABLED (native launch scenario argument).');
|
|
367
|
+
}
|
|
368
|
+
else if (typeof config.initialRuntimeEnabled === 'boolean' && config.initialRuntimeEnabled) {
|
|
369
|
+
mockifyer_core_1.logger.info('[Mockifyer-Fetch] Starting with Mockifyer ENABLED (restored from persisted preference).');
|
|
370
|
+
}
|
|
371
|
+
(0, mockifyer_core_1.configureFlightRecorder)((0, mockifyer_core_1.resolveFlightRecorderConfig)(this.config));
|
|
372
|
+
(0, mockifyer_core_1.configureAtlas)(this.config, {
|
|
373
|
+
scenario: this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId),
|
|
374
|
+
clientId: this.config.clientId ?? null,
|
|
375
|
+
});
|
|
376
|
+
(0, mockifyer_core_1.setFlightRecorderRuntimeContext)({
|
|
377
|
+
clientId: this.config.clientId,
|
|
378
|
+
scenario: this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId),
|
|
379
|
+
});
|
|
354
380
|
if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
|
|
355
381
|
const raw = typeof process !== 'undefined'
|
|
356
382
|
? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
|
|
@@ -395,8 +421,13 @@ class MockifyerClass {
|
|
|
395
421
|
clientId: this.config.clientId,
|
|
396
422
|
getClientId: () => this.config.clientId,
|
|
397
423
|
getStrictLaneScenario: () => (0, mockifyer_core_1.resolveProxyStrictLaneScenario)(this.config),
|
|
398
|
-
getUpstreamTlsInsecure: () =>
|
|
424
|
+
getUpstreamTlsInsecure: () => (0, mockifyer_core_1.resolveProxyUpstreamTlsInsecure)(this.config),
|
|
399
425
|
getExplicitProxyScenarioContext: () => (0, mockifyer_core_1.isExplicitProxyScenarioContext)(this.config),
|
|
426
|
+
getShouldRecordStreams: () => this.config.recordMode === true && !this.config.proxy?.baseUrl,
|
|
427
|
+
getStreamRecordCaps: () => ({
|
|
428
|
+
maxBytes: this.config.streamRecordMaxBytes,
|
|
429
|
+
maxDurationMs: this.config.streamRecordMaxDurationMs,
|
|
430
|
+
}),
|
|
400
431
|
deviceId: this.config.deviceId,
|
|
401
432
|
});
|
|
402
433
|
if (!config.recordSameEndpoints) {
|
|
@@ -406,7 +437,10 @@ class MockifyerClass {
|
|
|
406
437
|
this.setupMockResponses();
|
|
407
438
|
// Set up response interceptor to save responses when recordMode is enabled
|
|
408
439
|
this.setupResponseInterceptor();
|
|
409
|
-
mockifyer_core_1.
|
|
440
|
+
(0, mockifyer_core_1.logMockifyerInitSummary)(this.config, {
|
|
441
|
+
runtimeMode: this.config.runtimeMode,
|
|
442
|
+
headline: this.config.initLog?.headline,
|
|
443
|
+
});
|
|
410
444
|
}
|
|
411
445
|
ensureMockDataDirectory() {
|
|
412
446
|
const fs = getFs();
|
|
@@ -509,6 +543,7 @@ class MockifyerClass {
|
|
|
509
543
|
}
|
|
510
544
|
const currentScenario = this.capabilities.getCurrentScenario(resolvedMockDataPath, this.config.clientId);
|
|
511
545
|
const scenarioPath = this.capabilities.getScenarioFolderPath(resolvedMockDataPath, currentScenario);
|
|
546
|
+
(0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(scenarioPath, { clientId: this.config.clientId });
|
|
512
547
|
if (!fs.existsSync(scenarioPath)) {
|
|
513
548
|
mockifyer_core_1.logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
|
|
514
549
|
return undefined;
|
|
@@ -699,6 +734,9 @@ class MockifyerClass {
|
|
|
699
734
|
const hitScenarioPath = path
|
|
700
735
|
? this.capabilities.getScenarioFolderPath(path.resolve(this.config.mockDataPath), this.capabilities.getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId))
|
|
701
736
|
: undefined;
|
|
737
|
+
if (hitScenarioPath) {
|
|
738
|
+
(0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(hitScenarioPath, { clientId: this.config.clientId });
|
|
739
|
+
}
|
|
702
740
|
if (mockData.responseDelayMs && mockData.responseDelayMs > 0) {
|
|
703
741
|
await new Promise(resolve => setTimeout(resolve, mockData.responseDelayMs));
|
|
704
742
|
}
|
|
@@ -725,7 +763,10 @@ class MockifyerClass {
|
|
|
725
763
|
status: effectiveStatus,
|
|
726
764
|
statusText: 'OK',
|
|
727
765
|
headers: responseHeaders,
|
|
728
|
-
config: config
|
|
766
|
+
config: config,
|
|
767
|
+
...(mockData.response.stream
|
|
768
|
+
? { mockifyerStoredStream: mockData.response.stream }
|
|
769
|
+
: {}),
|
|
729
770
|
};
|
|
730
771
|
return {
|
|
731
772
|
...config,
|
|
@@ -739,7 +780,34 @@ class MockifyerClass {
|
|
|
739
780
|
}
|
|
740
781
|
// Check request limit BEFORE making real API call (only if no mock found and in record mode)
|
|
741
782
|
if (this.config.recordMode) {
|
|
742
|
-
|
|
783
|
+
const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
|
|
784
|
+
if (limitCheck.limitReached && limitCheck.error) {
|
|
785
|
+
console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
|
|
786
|
+
const responseHeaders = {
|
|
787
|
+
'x-mockifyer': 'true',
|
|
788
|
+
'x-mockifyer-limit-reached': 'true',
|
|
789
|
+
'content-type': 'application/json'
|
|
790
|
+
};
|
|
791
|
+
const mockErrorResponse = {
|
|
792
|
+
data: {
|
|
793
|
+
error: limitCheck.error.message,
|
|
794
|
+
message: limitCheck.error.message,
|
|
795
|
+
limitReached: true,
|
|
796
|
+
maxRequests: limitCheck.error.maxRequests,
|
|
797
|
+
currentScenario: limitCheck.error.currentScenario
|
|
798
|
+
},
|
|
799
|
+
status: 429,
|
|
800
|
+
statusText: 'Too Many Requests',
|
|
801
|
+
headers: responseHeaders,
|
|
802
|
+
config: config
|
|
803
|
+
};
|
|
804
|
+
return {
|
|
805
|
+
...config,
|
|
806
|
+
__mockResponse: Promise.resolve(mockErrorResponse),
|
|
807
|
+
__mockifyer_requestKey: requestKey,
|
|
808
|
+
__mockifyer_limit_reached: true
|
|
809
|
+
};
|
|
810
|
+
}
|
|
743
811
|
}
|
|
744
812
|
if (this.config.failOnMissingMock) {
|
|
745
813
|
const scenario = this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
@@ -835,6 +903,9 @@ class MockifyerClass {
|
|
|
835
903
|
const liveScenarioPath = path
|
|
836
904
|
? this.capabilities.getScenarioFolderPath(path.resolve(this.config.mockDataPath), this.capabilities.getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId))
|
|
837
905
|
: undefined;
|
|
906
|
+
if (liveScenarioPath) {
|
|
907
|
+
(0, mockifyer_core_1.ensureOverrideGroupRuntimeForScenarioPath)(liveScenarioPath, { clientId: this.config.clientId });
|
|
908
|
+
}
|
|
838
909
|
const clientResponse = (0, mockifyer_core_1.buildClientResponseFromLiveCapture)(matchedMock.mockData, capturedResponse, (0, mockifyer_core_1.createServeTimeClock)(this.config), { filename: matchedMock.filename, scenarioPath: liveScenarioPath });
|
|
839
910
|
response.data = clientResponse.data;
|
|
840
911
|
response.status = clientResponse.status;
|
|
@@ -853,12 +924,23 @@ class MockifyerClass {
|
|
|
853
924
|
? response.config.metadata.durationMs
|
|
854
925
|
: undefined,
|
|
855
926
|
requestBody: response.config?.data,
|
|
856
|
-
responseBody: response.data
|
|
927
|
+
responseBody: typeof ReadableStream !== 'undefined' && response.data instanceof ReadableStream
|
|
928
|
+
? '[stream]'
|
|
929
|
+
: response.data,
|
|
857
930
|
}, this.readRequestCorrelation(response.config), response.config?.headers);
|
|
858
931
|
this.unwrapResponseInlineTrace(response);
|
|
859
932
|
// Only save locally if recordMode is enabled AND we're not proxying upstream calls.
|
|
860
933
|
if (this.config.recordMode && !this.config.proxy?.baseUrl) {
|
|
861
|
-
|
|
934
|
+
if (response.mockifyerStreamRecording) {
|
|
935
|
+
// Do not await recording — the caller already has the live stream.
|
|
936
|
+
// Persist once the recording branch finishes (caps / EOF).
|
|
937
|
+
void this.saveStreamRecording(response).catch((err) => {
|
|
938
|
+
mockifyer_core_1.logger.error('[Mockifyer-Fetch] Failed to save stream recording:', err);
|
|
939
|
+
});
|
|
940
|
+
}
|
|
941
|
+
else {
|
|
942
|
+
await this.saveResponse(response);
|
|
943
|
+
}
|
|
862
944
|
}
|
|
863
945
|
return response;
|
|
864
946
|
}, async (error) => {
|
|
@@ -946,6 +1028,25 @@ class MockifyerClass {
|
|
|
946
1028
|
mockifyer_core_1.logger.warn('[Mockifyer-Fetch] Proxy client mirror (Metro) failed:', e);
|
|
947
1029
|
}
|
|
948
1030
|
}
|
|
1031
|
+
/**
|
|
1032
|
+
* Await background stream capture, then persist concatenated body + stream timeline.
|
|
1033
|
+
* Called without blocking the caller's live ReadableStream.
|
|
1034
|
+
*/
|
|
1035
|
+
async saveStreamRecording(response) {
|
|
1036
|
+
const recording = response.mockifyerStreamRecording;
|
|
1037
|
+
if (!recording) {
|
|
1038
|
+
await this.saveResponse(response);
|
|
1039
|
+
return;
|
|
1040
|
+
}
|
|
1041
|
+
const captured = await recording;
|
|
1042
|
+
const withBody = {
|
|
1043
|
+
...response,
|
|
1044
|
+
data: captured.concatenated,
|
|
1045
|
+
mockifyerStoredStream: captured.stream,
|
|
1046
|
+
mockifyerStreamRecording: undefined,
|
|
1047
|
+
};
|
|
1048
|
+
await this.saveResponse(withBody);
|
|
1049
|
+
}
|
|
949
1050
|
async saveResponse(response) {
|
|
950
1051
|
// CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
|
|
951
1052
|
if (response.config?.__mockifyer_skip_save || response.config?.__mockifyer_bypass) {
|
|
@@ -1032,12 +1133,17 @@ class MockifyerClass {
|
|
|
1032
1133
|
this.config.proxy?.recordResponses ??
|
|
1033
1134
|
this.config.recordResponses;
|
|
1034
1135
|
const recordBodies = (0, mockifyer_core_1.resolveLocalRecordResponsesForUrl)(storedRequest.url, configValue, this.config.baseUrl);
|
|
1136
|
+
const storedStream = response.mockifyerStoredStream;
|
|
1137
|
+
const responseDataForSave = typeof ReadableStream !== 'undefined' && response.data instanceof ReadableStream
|
|
1138
|
+
? ''
|
|
1139
|
+
: response.data;
|
|
1035
1140
|
const mockData = (0, mockifyer_core_1.buildLocalRecordingMockData)({
|
|
1036
1141
|
request: storedRequest,
|
|
1037
1142
|
response: {
|
|
1038
1143
|
status: response.status,
|
|
1039
|
-
data:
|
|
1144
|
+
data: responseDataForSave,
|
|
1040
1145
|
headers: response.headers || {},
|
|
1146
|
+
...(storedStream && recordBodies ? { stream: storedStream } : {}),
|
|
1041
1147
|
},
|
|
1042
1148
|
recordResponses: recordBodies,
|
|
1043
1149
|
meta: {
|
|
@@ -1076,6 +1182,11 @@ class MockifyerClass {
|
|
|
1076
1182
|
const currentScenario = this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
1077
1183
|
const scenarioPath = this.capabilities.getScenarioFolderPath(this.config.mockDataPath, currentScenario);
|
|
1078
1184
|
this.capabilities.ensureScenarioFolder(this.config.mockDataPath, currentScenario);
|
|
1185
|
+
const limitCheck = (0, mockifyer_core_1.checkRequestLimit)(this.config.mockDataPath);
|
|
1186
|
+
if (limitCheck.limitReached && limitCheck.error) {
|
|
1187
|
+
console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
|
|
1188
|
+
return;
|
|
1189
|
+
}
|
|
1079
1190
|
if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
|
|
1080
1191
|
fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
|
|
1081
1192
|
mockifyer_core_1.logger.info(`[Mockifyer] Refreshed passthrough mock: ${currentScenario}/${existingMock.filename}`);
|
|
@@ -1,9 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fetch "null body status" codes — Response body must be null.
|
|
3
|
+
* Passing '' / JSON (including JSON.stringify(null) → "null") throws in undici:
|
|
4
|
+
* `TypeError: Response constructor: Invalid response status code 204`
|
|
5
|
+
*
|
|
6
|
+
* @see https://fetch.spec.whatwg.org/#null-body-status
|
|
7
|
+
*/
|
|
8
|
+
import type { StreamReplayMode, StoredResponseStream } from '@sgedda/mockifyer-core';
|
|
1
9
|
/**
|
|
2
10
|
* Whether `status` forbids a Response body under the Fetch spec.
|
|
3
11
|
*/
|
|
4
12
|
export declare function isFetchNullBodyStatus(status: number): boolean;
|
|
13
|
+
export interface BodyInitForFetchResponseOptions {
|
|
14
|
+
/** Recorded stream timeline — when set (and ReadableStream is supported), rebuild a paced stream. */
|
|
15
|
+
stream?: StoredResponseStream | null;
|
|
16
|
+
/** Replay pacing; defaults to `accelerated`. */
|
|
17
|
+
streamReplay?: StreamReplayMode | null;
|
|
18
|
+
}
|
|
5
19
|
/**
|
|
6
20
|
* Body argument for `new Response(body, { status })`.
|
|
7
21
|
* Returns `null` for null-body statuses so Node/undici does not throw.
|
|
22
|
+
* When `data` is already a ReadableStream, it is returned as-is (live passthrough).
|
|
23
|
+
* When `options.stream` is set and the runtime supports ReadableStream bodies,
|
|
24
|
+
* returns a paced replay stream; otherwise falls back to the flat concatenated body.
|
|
8
25
|
*/
|
|
9
|
-
export declare function bodyInitForFetchResponse(status: number, data: unknown): BodyInit | null;
|
|
26
|
+
export declare function bodyInitForFetchResponse(status: number, data: unknown, options?: BodyInitForFetchResponseOptions): BodyInit | null;
|
|
@@ -1,7 +1,4 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isFetchNullBodyStatus = isFetchNullBodyStatus;
|
|
4
|
-
exports.bodyInitForFetchResponse = bodyInitForFetchResponse;
|
|
5
2
|
/**
|
|
6
3
|
* Fetch "null body status" codes — Response body must be null.
|
|
7
4
|
* Passing '' / JSON (including JSON.stringify(null) → "null") throws in undici:
|
|
@@ -9,6 +6,10 @@ exports.bodyInitForFetchResponse = bodyInitForFetchResponse;
|
|
|
9
6
|
*
|
|
10
7
|
* @see https://fetch.spec.whatwg.org/#null-body-status
|
|
11
8
|
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.isFetchNullBodyStatus = isFetchNullBodyStatus;
|
|
11
|
+
exports.bodyInitForFetchResponse = bodyInitForFetchResponse;
|
|
12
|
+
const mockifyer_core_1 = require("@sgedda/mockifyer-core");
|
|
12
13
|
const FETCH_NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
|
|
13
14
|
/**
|
|
14
15
|
* Whether `status` forbids a Response body under the Fetch spec.
|
|
@@ -19,11 +20,24 @@ function isFetchNullBodyStatus(status) {
|
|
|
19
20
|
/**
|
|
20
21
|
* Body argument for `new Response(body, { status })`.
|
|
21
22
|
* Returns `null` for null-body statuses so Node/undici does not throw.
|
|
23
|
+
* When `data` is already a ReadableStream, it is returned as-is (live passthrough).
|
|
24
|
+
* When `options.stream` is set and the runtime supports ReadableStream bodies,
|
|
25
|
+
* returns a paced replay stream; otherwise falls back to the flat concatenated body.
|
|
22
26
|
*/
|
|
23
|
-
function bodyInitForFetchResponse(status, data) {
|
|
27
|
+
function bodyInitForFetchResponse(status, data, options) {
|
|
24
28
|
if (isFetchNullBodyStatus(status)) {
|
|
25
29
|
return null;
|
|
26
30
|
}
|
|
31
|
+
if (typeof ReadableStream !== 'undefined' && data instanceof ReadableStream) {
|
|
32
|
+
return data;
|
|
33
|
+
}
|
|
34
|
+
const storedStream = options?.stream;
|
|
35
|
+
if (storedStream &&
|
|
36
|
+
Array.isArray(storedStream.chunks) &&
|
|
37
|
+
storedStream.chunks.length > 0 &&
|
|
38
|
+
(0, mockifyer_core_1.supportsReadableStreamBody)()) {
|
|
39
|
+
return (0, mockifyer_core_1.createReplayReadableStream)(storedStream, (0, mockifyer_core_1.resolveStreamReplayMode)(options?.streamReplay));
|
|
40
|
+
}
|
|
27
41
|
if (typeof data === 'string') {
|
|
28
42
|
return data;
|
|
29
43
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sgedda/mockifyer-fetch",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.108",
|
|
4
4
|
"description": "Mockifyer for Fetch - API mocking and logging utility for storing and replaying API responses",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -60,7 +60,7 @@
|
|
|
60
60
|
},
|
|
61
61
|
"license": "MIT",
|
|
62
62
|
"dependencies": {
|
|
63
|
-
"@sgedda/mockifyer-core": "^1.10.
|
|
63
|
+
"@sgedda/mockifyer-core": "^1.10.199"
|
|
64
64
|
},
|
|
65
65
|
"devDependencies": {
|
|
66
66
|
"@types/node": "^20.11.24",
|
|
@@ -9,6 +9,11 @@ import {
|
|
|
9
9
|
MOCKIFYER_CLIENT_ID_HEADER,
|
|
10
10
|
MOCKIFYER_DEVICE_ID_HEADER,
|
|
11
11
|
resolveMockifyerTraceFromHeaders,
|
|
12
|
+
detectStreamKind,
|
|
13
|
+
teeResponseBodyForRecording,
|
|
14
|
+
captureReadableStreamChunks,
|
|
15
|
+
supportsReadableStreamBody,
|
|
16
|
+
type StreamRecordCaps,
|
|
12
17
|
} from '@sgedda/mockifyer-core';
|
|
13
18
|
|
|
14
19
|
function headerContentType(headers: Headers): string | undefined {
|
|
@@ -78,6 +83,8 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
|
78
83
|
private getStrictLaneScenario?: () => boolean;
|
|
79
84
|
private getUpstreamTlsInsecure?: () => boolean;
|
|
80
85
|
private getExplicitProxyScenarioContext?: () => boolean;
|
|
86
|
+
private getShouldRecordStreams?: () => boolean;
|
|
87
|
+
private getStreamRecordCaps?: () => StreamRecordCaps;
|
|
81
88
|
private clientIdSnapshot?: string;
|
|
82
89
|
private deviceId?: string;
|
|
83
90
|
|
|
@@ -98,6 +105,9 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
|
98
105
|
getUpstreamTlsInsecure?: () => boolean;
|
|
99
106
|
/** When false, skip `/api/proxy` and call the real URL (devtools-friendly passthrough). */
|
|
100
107
|
getExplicitProxyScenarioContext?: () => boolean;
|
|
108
|
+
/** When true, tee streaming bodies and capture chunk timelines while recording. */
|
|
109
|
+
getShouldRecordStreams?: () => boolean;
|
|
110
|
+
getStreamRecordCaps?: () => StreamRecordCaps;
|
|
101
111
|
deviceId?: string;
|
|
102
112
|
}) {
|
|
103
113
|
super();
|
|
@@ -112,6 +122,8 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
|
112
122
|
this.getStrictLaneScenario = config?.getStrictLaneScenario;
|
|
113
123
|
this.getUpstreamTlsInsecure = config?.getUpstreamTlsInsecure;
|
|
114
124
|
this.getExplicitProxyScenarioContext = config?.getExplicitProxyScenarioContext;
|
|
125
|
+
this.getShouldRecordStreams = config?.getShouldRecordStreams;
|
|
126
|
+
this.getStreamRecordCaps = config?.getStreamRecordCaps;
|
|
115
127
|
this.clientIdSnapshot = config?.clientId;
|
|
116
128
|
this.deviceId = config?.deviceId;
|
|
117
129
|
}
|
|
@@ -231,7 +243,51 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
|
231
243
|
}
|
|
232
244
|
|
|
233
245
|
const response = await fetchFn(url, requestConfig);
|
|
246
|
+
|
|
247
|
+
const responseHeaders: Record<string, string> = {};
|
|
248
|
+
response.headers.forEach((value: string, key: string) => {
|
|
249
|
+
responseHeaders[key] = value;
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
const mockifyerTrace = resolveMockifyerTraceFromHeaders(responseHeaders);
|
|
234
253
|
const contentType = response.headers.get('content-type') || '';
|
|
254
|
+
const streamKind = detectStreamKind(response.headers);
|
|
255
|
+
const canStream = supportsReadableStreamBody() && streamKind != null && response.body != null;
|
|
256
|
+
const shouldRecordStreams = this.getShouldRecordStreams?.() === true;
|
|
257
|
+
|
|
258
|
+
// Streaming path: pass the live body through without buffering so the caller
|
|
259
|
+
// is not delayed. When recording, tee and capture chunks in the background.
|
|
260
|
+
if (canStream) {
|
|
261
|
+
const caps = this.getStreamRecordCaps?.() ?? {};
|
|
262
|
+
if (shouldRecordStreams) {
|
|
263
|
+
const teed = teeResponseBodyForRecording(response.body);
|
|
264
|
+
if (teed) {
|
|
265
|
+
const recording = captureReadableStreamChunks(teed.record, streamKind, caps);
|
|
266
|
+
return {
|
|
267
|
+
data: teed.live as any,
|
|
268
|
+
status: response.status,
|
|
269
|
+
statusText: response.statusText,
|
|
270
|
+
headers: responseHeaders,
|
|
271
|
+
config,
|
|
272
|
+
mockifyerStreamRecording: recording,
|
|
273
|
+
...(mockifyerTrace ? { mockifyerTrace } : {}),
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
// Tee unavailable — fall through to buffered text() so recording still works.
|
|
277
|
+
} else {
|
|
278
|
+
// Not recording: avoid buffering the live stream for the caller.
|
|
279
|
+
return {
|
|
280
|
+
data: response.body as any,
|
|
281
|
+
status: response.status,
|
|
282
|
+
statusText: response.statusText,
|
|
283
|
+
headers: responseHeaders,
|
|
284
|
+
config,
|
|
285
|
+
...(mockifyerTrace ? { mockifyerTrace } : {}),
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Flat path (legacy / React Native without ReadableStream / non-stream responses)
|
|
235
291
|
const rawText = await response.text();
|
|
236
292
|
let data: any = rawText;
|
|
237
293
|
if (contentType.includes('application/json')) {
|
|
@@ -242,13 +298,6 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
|
|
|
242
298
|
}
|
|
243
299
|
}
|
|
244
300
|
|
|
245
|
-
const responseHeaders: Record<string, string> = {};
|
|
246
|
-
response.headers.forEach((value: string, key: string) => {
|
|
247
|
-
responseHeaders[key] = value;
|
|
248
|
-
});
|
|
249
|
-
|
|
250
|
-
const mockifyerTrace = resolveMockifyerTraceFromHeaders(responseHeaders);
|
|
251
|
-
|
|
252
301
|
return {
|
|
253
302
|
data,
|
|
254
303
|
status: response.status,
|
package/src/index.browser.ts
CHANGED
|
@@ -34,7 +34,8 @@ export {
|
|
|
34
34
|
|
|
35
35
|
// Re-export browser-safe fetch utilities
|
|
36
36
|
export { FetchHTTPClient } from './clients/fetch-client';
|
|
37
|
-
|
|
37
|
+
import { bodyInitForFetchResponse } from './utils/fetch-response-body';
|
|
38
|
+
export { bodyInitForFetchResponse };
|
|
38
39
|
export { resolvePatchedFetchRequest } from './utils/resolve-patched-fetch-request';
|
|
39
40
|
|
|
40
41
|
export {
|
|
@@ -135,11 +136,15 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
135
136
|
data: init?.body,
|
|
136
137
|
});
|
|
137
138
|
|
|
138
|
-
// Convert mockifyer response to fetch Response
|
|
139
|
+
// Convert mockifyer response to fetch Response (rebuild stream when present)
|
|
139
140
|
return new Response(
|
|
140
|
-
|
|
141
|
+
bodyInitForFetchResponse(response.status, response.data, {
|
|
142
|
+
stream: response.mockifyerStoredStream,
|
|
143
|
+
streamReplay: config.streamReplay,
|
|
144
|
+
}),
|
|
141
145
|
{
|
|
142
146
|
status: response.status,
|
|
147
|
+
statusText: response.statusText || '',
|
|
143
148
|
headers: new Headers(response.headers || {})
|
|
144
149
|
}
|
|
145
150
|
);
|
package/src/index.ts
CHANGED
|
@@ -290,7 +290,11 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
290
290
|
});
|
|
291
291
|
}
|
|
292
292
|
|
|
293
|
-
|
|
293
|
+
const streamOpts = {
|
|
294
|
+
stream: (response as HTTPResponse).mockifyerStoredStream,
|
|
295
|
+
streamReplay: resolvedConfig.streamReplay,
|
|
296
|
+
};
|
|
297
|
+
return new Response(bodyInitForFetchResponse(response.status, response.data, streamOpts), {
|
|
294
298
|
status: response.status,
|
|
295
299
|
statusText: response.statusText || '',
|
|
296
300
|
headers: responseHeaders
|
|
@@ -303,11 +307,17 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
303
307
|
});
|
|
304
308
|
|
|
305
309
|
const errorStatus = error.response.status;
|
|
306
|
-
return new Response(
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
310
|
+
return new Response(
|
|
311
|
+
bodyInitForFetchResponse(errorStatus, error.response.data, {
|
|
312
|
+
stream: (error.response as HTTPResponse).mockifyerStoredStream,
|
|
313
|
+
streamReplay: resolvedConfig.streamReplay,
|
|
314
|
+
}),
|
|
315
|
+
{
|
|
316
|
+
status: errorStatus,
|
|
317
|
+
statusText: error.response.statusText || '',
|
|
318
|
+
headers: responseHeaders
|
|
319
|
+
}
|
|
320
|
+
);
|
|
311
321
|
}
|
|
312
322
|
throw attachMockifyerRequestIdToError(
|
|
313
323
|
error,
|
package/src/mockifyer-class.ts
CHANGED
|
@@ -50,6 +50,15 @@ import {
|
|
|
50
50
|
shouldApplyMockifyer,
|
|
51
51
|
isScenarioLaunchFromNativeArguments,
|
|
52
52
|
getCurrentScenario,
|
|
53
|
+
tryGetClientIdFromLaunchArguments,
|
|
54
|
+
MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
|
|
55
|
+
checkRequestLimit,
|
|
56
|
+
ensureOverrideGroupRuntimeForScenarioPath,
|
|
57
|
+
configureFlightRecorder,
|
|
58
|
+
resolveFlightRecorderConfig,
|
|
59
|
+
configureAtlas,
|
|
60
|
+
logMockifyerInitSummary,
|
|
61
|
+
resolveProxyUpstreamTlsInsecure,
|
|
53
62
|
unwrapAndMergeInlineTraceEnvelope,
|
|
54
63
|
unwrapInlineTraceEnvelopeEmittingNetworkEvents,
|
|
55
64
|
applyOutboundRequestCorrelation,
|
|
@@ -472,13 +481,24 @@ export class MockifyerClass {
|
|
|
472
481
|
config.useSimilarMatch = true;
|
|
473
482
|
}
|
|
474
483
|
}
|
|
484
|
+
|
|
485
|
+
let launchClientId: string | undefined;
|
|
486
|
+
if (config.useLaunchArgumentsClientId) {
|
|
487
|
+
const key = config.launchArgumentClientIdKey ?? MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
|
|
488
|
+
launchClientId = tryGetClientIdFromLaunchArguments(key);
|
|
489
|
+
if (launchClientId) {
|
|
490
|
+
logger.info(`[Mockifyer-Fetch] clientId from launch arguments (${key}): ${launchClientId}`);
|
|
491
|
+
}
|
|
492
|
+
}
|
|
475
493
|
|
|
476
494
|
// Store config BEFORE any modifications
|
|
477
495
|
this.config = { ...config }; // Create a copy to avoid mutations
|
|
478
496
|
|
|
479
|
-
//
|
|
497
|
+
// Launch arg wins over MOCKIFYER_CLIENT_ID / config.clientId when present (E2E).
|
|
480
498
|
// Strict proxy: no auto lane until explicit clientId / setClientId (devtools show real URLs).
|
|
481
|
-
if (
|
|
499
|
+
if (launchClientId) {
|
|
500
|
+
this.config.clientId = launchClientId;
|
|
501
|
+
} else if (
|
|
482
502
|
resolveStrictScenarioResolution(this.config) &&
|
|
483
503
|
Boolean(this.config.proxy?.baseUrl?.trim())
|
|
484
504
|
) {
|
|
@@ -516,8 +536,26 @@ export class MockifyerClass {
|
|
|
516
536
|
logger.info(
|
|
517
537
|
`[Mockifyer-Fetch] Starting with Mockifyer DISABLED (${reason}). Call enableMockifyer() to activate.`
|
|
518
538
|
);
|
|
539
|
+
} else if (isScenarioLaunchFromNativeArguments()) {
|
|
540
|
+
logger.info(
|
|
541
|
+
'[Mockifyer-Fetch] Starting with Mockifyer ENABLED (native launch scenario argument).'
|
|
542
|
+
);
|
|
543
|
+
} else if (typeof config.initialRuntimeEnabled === 'boolean' && config.initialRuntimeEnabled) {
|
|
544
|
+
logger.info(
|
|
545
|
+
'[Mockifyer-Fetch] Starting with Mockifyer ENABLED (restored from persisted preference).'
|
|
546
|
+
);
|
|
519
547
|
}
|
|
520
548
|
|
|
549
|
+
configureFlightRecorder(resolveFlightRecorderConfig(this.config));
|
|
550
|
+
configureAtlas(this.config, {
|
|
551
|
+
scenario: this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId),
|
|
552
|
+
clientId: this.config.clientId ?? null,
|
|
553
|
+
});
|
|
554
|
+
setFlightRecorderRuntimeContext({
|
|
555
|
+
clientId: this.config.clientId,
|
|
556
|
+
scenario: this.capabilities.getCurrentScenario(this.config.mockDataPath, this.config.clientId),
|
|
557
|
+
});
|
|
558
|
+
|
|
521
559
|
if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
|
|
522
560
|
const raw =
|
|
523
561
|
typeof process !== 'undefined'
|
|
@@ -566,8 +604,14 @@ export class MockifyerClass {
|
|
|
566
604
|
clientId: this.config.clientId,
|
|
567
605
|
getClientId: () => this.config.clientId,
|
|
568
606
|
getStrictLaneScenario: () => resolveProxyStrictLaneScenario(this.config),
|
|
569
|
-
getUpstreamTlsInsecure: () =>
|
|
607
|
+
getUpstreamTlsInsecure: () => resolveProxyUpstreamTlsInsecure(this.config),
|
|
570
608
|
getExplicitProxyScenarioContext: () => isExplicitProxyScenarioContext(this.config),
|
|
609
|
+
getShouldRecordStreams: () =>
|
|
610
|
+
this.config.recordMode === true && !this.config.proxy?.baseUrl,
|
|
611
|
+
getStreamRecordCaps: () => ({
|
|
612
|
+
maxBytes: this.config.streamRecordMaxBytes,
|
|
613
|
+
maxDurationMs: this.config.streamRecordMaxDurationMs,
|
|
614
|
+
}),
|
|
571
615
|
deviceId: (this.config as any).deviceId,
|
|
572
616
|
});
|
|
573
617
|
|
|
@@ -580,7 +624,10 @@ export class MockifyerClass {
|
|
|
580
624
|
// Set up response interceptor to save responses when recordMode is enabled
|
|
581
625
|
this.setupResponseInterceptor();
|
|
582
626
|
|
|
583
|
-
|
|
627
|
+
logMockifyerInitSummary(this.config, {
|
|
628
|
+
runtimeMode: this.config.runtimeMode,
|
|
629
|
+
headline: this.config.initLog?.headline,
|
|
630
|
+
});
|
|
584
631
|
}
|
|
585
632
|
|
|
586
633
|
private ensureMockDataDirectory(): void {
|
|
@@ -708,6 +755,7 @@ export class MockifyerClass {
|
|
|
708
755
|
|
|
709
756
|
const currentScenario = this.capabilities.getCurrentScenario(resolvedMockDataPath, this.config.clientId);
|
|
710
757
|
const scenarioPath = this.capabilities.getScenarioFolderPath(resolvedMockDataPath, currentScenario);
|
|
758
|
+
ensureOverrideGroupRuntimeForScenarioPath(scenarioPath, { clientId: this.config.clientId });
|
|
711
759
|
|
|
712
760
|
if (!fs.existsSync(scenarioPath)) {
|
|
713
761
|
logger.warn('[Mockifyer-Fetch] ⚠️ Scenario path does not exist:', scenarioPath);
|
|
@@ -943,6 +991,9 @@ export class MockifyerClass {
|
|
|
943
991
|
this.capabilities.getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId)
|
|
944
992
|
)
|
|
945
993
|
: undefined;
|
|
994
|
+
if (hitScenarioPath) {
|
|
995
|
+
ensureOverrideGroupRuntimeForScenarioPath(hitScenarioPath, { clientId: this.config.clientId });
|
|
996
|
+
}
|
|
946
997
|
|
|
947
998
|
if (mockData.responseDelayMs && mockData.responseDelayMs > 0) {
|
|
948
999
|
await new Promise(resolve => setTimeout(resolve, mockData.responseDelayMs));
|
|
@@ -972,12 +1023,15 @@ export class MockifyerClass {
|
|
|
972
1023
|
|
|
973
1024
|
await this.warmPoolResponseCache(mockData);
|
|
974
1025
|
|
|
975
|
-
const mockResponse = {
|
|
1026
|
+
const mockResponse: HTTPResponse = {
|
|
976
1027
|
data: mockResponseBody,
|
|
977
1028
|
status: effectiveStatus,
|
|
978
1029
|
statusText: 'OK',
|
|
979
1030
|
headers: responseHeaders,
|
|
980
|
-
config: config as any
|
|
1031
|
+
config: config as any,
|
|
1032
|
+
...(mockData.response.stream
|
|
1033
|
+
? { mockifyerStoredStream: mockData.response.stream }
|
|
1034
|
+
: {}),
|
|
981
1035
|
};
|
|
982
1036
|
|
|
983
1037
|
return {
|
|
@@ -996,7 +1050,37 @@ export class MockifyerClass {
|
|
|
996
1050
|
|
|
997
1051
|
// Check request limit BEFORE making real API call (only if no mock found and in record mode)
|
|
998
1052
|
if (this.config.recordMode) {
|
|
999
|
-
|
|
1053
|
+
const limitCheck = checkRequestLimit(this.config.mockDataPath);
|
|
1054
|
+
if (limitCheck.limitReached && limitCheck.error) {
|
|
1055
|
+
console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
|
|
1056
|
+
|
|
1057
|
+
const responseHeaders = {
|
|
1058
|
+
'x-mockifyer': 'true',
|
|
1059
|
+
'x-mockifyer-limit-reached': 'true',
|
|
1060
|
+
'content-type': 'application/json'
|
|
1061
|
+
};
|
|
1062
|
+
|
|
1063
|
+
const mockErrorResponse = {
|
|
1064
|
+
data: {
|
|
1065
|
+
error: limitCheck.error.message,
|
|
1066
|
+
message: limitCheck.error.message,
|
|
1067
|
+
limitReached: true,
|
|
1068
|
+
maxRequests: limitCheck.error.maxRequests,
|
|
1069
|
+
currentScenario: limitCheck.error.currentScenario
|
|
1070
|
+
},
|
|
1071
|
+
status: 429,
|
|
1072
|
+
statusText: 'Too Many Requests',
|
|
1073
|
+
headers: responseHeaders,
|
|
1074
|
+
config: config as any
|
|
1075
|
+
};
|
|
1076
|
+
|
|
1077
|
+
return {
|
|
1078
|
+
...config,
|
|
1079
|
+
__mockResponse: Promise.resolve(mockErrorResponse),
|
|
1080
|
+
__mockifyer_requestKey: requestKey,
|
|
1081
|
+
__mockifyer_limit_reached: true
|
|
1082
|
+
} as any;
|
|
1083
|
+
}
|
|
1000
1084
|
}
|
|
1001
1085
|
|
|
1002
1086
|
if (this.config.failOnMissingMock) {
|
|
@@ -1124,6 +1208,9 @@ export class MockifyerClass {
|
|
|
1124
1208
|
this.capabilities.getCurrentScenario(path.resolve(this.config.mockDataPath), this.config.clientId)
|
|
1125
1209
|
)
|
|
1126
1210
|
: undefined;
|
|
1211
|
+
if (liveScenarioPath) {
|
|
1212
|
+
ensureOverrideGroupRuntimeForScenarioPath(liveScenarioPath, { clientId: this.config.clientId });
|
|
1213
|
+
}
|
|
1127
1214
|
const clientResponse = buildClientResponseFromLiveCapture(
|
|
1128
1215
|
matchedMock.mockData,
|
|
1129
1216
|
capturedResponse,
|
|
@@ -1151,7 +1238,10 @@ export class MockifyerClass {
|
|
|
1151
1238
|
? response.config.metadata.durationMs
|
|
1152
1239
|
: undefined,
|
|
1153
1240
|
requestBody: response.config?.data,
|
|
1154
|
-
responseBody:
|
|
1241
|
+
responseBody:
|
|
1242
|
+
typeof ReadableStream !== 'undefined' && response.data instanceof ReadableStream
|
|
1243
|
+
? '[stream]'
|
|
1244
|
+
: response.data,
|
|
1155
1245
|
},
|
|
1156
1246
|
this.readRequestCorrelation(response.config),
|
|
1157
1247
|
response.config?.headers
|
|
@@ -1160,7 +1250,15 @@ export class MockifyerClass {
|
|
|
1160
1250
|
|
|
1161
1251
|
// Only save locally if recordMode is enabled AND we're not proxying upstream calls.
|
|
1162
1252
|
if (this.config.recordMode && !this.config.proxy?.baseUrl) {
|
|
1163
|
-
|
|
1253
|
+
if (response.mockifyerStreamRecording) {
|
|
1254
|
+
// Do not await recording — the caller already has the live stream.
|
|
1255
|
+
// Persist once the recording branch finishes (caps / EOF).
|
|
1256
|
+
void this.saveStreamRecording(response).catch((err) => {
|
|
1257
|
+
logger.error('[Mockifyer-Fetch] Failed to save stream recording:', err);
|
|
1258
|
+
});
|
|
1259
|
+
} else {
|
|
1260
|
+
await this.saveResponse(response);
|
|
1261
|
+
}
|
|
1164
1262
|
}
|
|
1165
1263
|
|
|
1166
1264
|
return response;
|
|
@@ -1261,6 +1359,26 @@ export class MockifyerClass {
|
|
|
1261
1359
|
}
|
|
1262
1360
|
}
|
|
1263
1361
|
|
|
1362
|
+
/**
|
|
1363
|
+
* Await background stream capture, then persist concatenated body + stream timeline.
|
|
1364
|
+
* Called without blocking the caller's live ReadableStream.
|
|
1365
|
+
*/
|
|
1366
|
+
private async saveStreamRecording(response: HTTPResponse): Promise<void> {
|
|
1367
|
+
const recording = response.mockifyerStreamRecording;
|
|
1368
|
+
if (!recording) {
|
|
1369
|
+
await this.saveResponse(response);
|
|
1370
|
+
return;
|
|
1371
|
+
}
|
|
1372
|
+
const captured = await recording;
|
|
1373
|
+
const withBody: HTTPResponse = {
|
|
1374
|
+
...response,
|
|
1375
|
+
data: captured.concatenated,
|
|
1376
|
+
mockifyerStoredStream: captured.stream,
|
|
1377
|
+
mockifyerStreamRecording: undefined,
|
|
1378
|
+
};
|
|
1379
|
+
await this.saveResponse(withBody);
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1264
1382
|
private async saveResponse(response: HTTPResponse): Promise<void> {
|
|
1265
1383
|
// CRITICAL: Check for bypass flags FIRST - if set, completely skip processing
|
|
1266
1384
|
if ((response.config as any)?.__mockifyer_skip_save || (response.config as any)?.__mockifyer_bypass) {
|
|
@@ -1378,12 +1496,18 @@ export class MockifyerClass {
|
|
|
1378
1496
|
this.config.proxy?.recordResponses ??
|
|
1379
1497
|
this.config.recordResponses;
|
|
1380
1498
|
const recordBodies = resolveLocalRecordResponsesForUrl(storedRequest.url, configValue, this.config.baseUrl);
|
|
1499
|
+
const storedStream = response.mockifyerStoredStream;
|
|
1500
|
+
const responseDataForSave =
|
|
1501
|
+
typeof ReadableStream !== 'undefined' && response.data instanceof ReadableStream
|
|
1502
|
+
? ''
|
|
1503
|
+
: response.data;
|
|
1381
1504
|
const mockData = buildLocalRecordingMockData({
|
|
1382
1505
|
request: storedRequest,
|
|
1383
1506
|
response: {
|
|
1384
1507
|
status: response.status,
|
|
1385
|
-
data:
|
|
1508
|
+
data: responseDataForSave,
|
|
1386
1509
|
headers: response.headers || {},
|
|
1510
|
+
...(storedStream && recordBodies ? { stream: storedStream } : {}),
|
|
1387
1511
|
},
|
|
1388
1512
|
recordResponses: recordBodies,
|
|
1389
1513
|
meta: {
|
|
@@ -1428,6 +1552,12 @@ export class MockifyerClass {
|
|
|
1428
1552
|
const scenarioPath = this.capabilities.getScenarioFolderPath(this.config.mockDataPath, currentScenario);
|
|
1429
1553
|
this.capabilities.ensureScenarioFolder(this.config.mockDataPath, currentScenario);
|
|
1430
1554
|
|
|
1555
|
+
const limitCheck = checkRequestLimit(this.config.mockDataPath);
|
|
1556
|
+
if (limitCheck.limitReached && limitCheck.error) {
|
|
1557
|
+
console.warn(`[Mockifyer] ⚠️ ${limitCheck.error.message}`);
|
|
1558
|
+
return;
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1431
1561
|
if (saveDecision.action === 'overwrite' && existingMock?.filePath) {
|
|
1432
1562
|
fs.writeFileSync(existingMock.filePath, JSON.stringify(mockData, null, 2));
|
|
1433
1563
|
logger.info(
|
|
@@ -5,6 +5,14 @@
|
|
|
5
5
|
*
|
|
6
6
|
* @see https://fetch.spec.whatwg.org/#null-body-status
|
|
7
7
|
*/
|
|
8
|
+
|
|
9
|
+
import type { StreamReplayMode, StoredResponseStream } from '@sgedda/mockifyer-core';
|
|
10
|
+
import {
|
|
11
|
+
createReplayReadableStream,
|
|
12
|
+
resolveStreamReplayMode,
|
|
13
|
+
supportsReadableStreamBody,
|
|
14
|
+
} from '@sgedda/mockifyer-core';
|
|
15
|
+
|
|
8
16
|
const FETCH_NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
|
|
9
17
|
|
|
10
18
|
/**
|
|
@@ -14,14 +22,43 @@ export function isFetchNullBodyStatus(status: number): boolean {
|
|
|
14
22
|
return FETCH_NULL_BODY_STATUSES.has(status);
|
|
15
23
|
}
|
|
16
24
|
|
|
25
|
+
export interface BodyInitForFetchResponseOptions {
|
|
26
|
+
/** Recorded stream timeline — when set (and ReadableStream is supported), rebuild a paced stream. */
|
|
27
|
+
stream?: StoredResponseStream | null;
|
|
28
|
+
/** Replay pacing; defaults to `accelerated`. */
|
|
29
|
+
streamReplay?: StreamReplayMode | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
17
32
|
/**
|
|
18
33
|
* Body argument for `new Response(body, { status })`.
|
|
19
34
|
* Returns `null` for null-body statuses so Node/undici does not throw.
|
|
35
|
+
* When `data` is already a ReadableStream, it is returned as-is (live passthrough).
|
|
36
|
+
* When `options.stream` is set and the runtime supports ReadableStream bodies,
|
|
37
|
+
* returns a paced replay stream; otherwise falls back to the flat concatenated body.
|
|
20
38
|
*/
|
|
21
|
-
export function bodyInitForFetchResponse(
|
|
39
|
+
export function bodyInitForFetchResponse(
|
|
40
|
+
status: number,
|
|
41
|
+
data: unknown,
|
|
42
|
+
options?: BodyInitForFetchResponseOptions
|
|
43
|
+
): BodyInit | null {
|
|
22
44
|
if (isFetchNullBodyStatus(status)) {
|
|
23
45
|
return null;
|
|
24
46
|
}
|
|
47
|
+
if (typeof ReadableStream !== 'undefined' && data instanceof ReadableStream) {
|
|
48
|
+
return data as BodyInit;
|
|
49
|
+
}
|
|
50
|
+
const storedStream = options?.stream;
|
|
51
|
+
if (
|
|
52
|
+
storedStream &&
|
|
53
|
+
Array.isArray(storedStream.chunks) &&
|
|
54
|
+
storedStream.chunks.length > 0 &&
|
|
55
|
+
supportsReadableStreamBody()
|
|
56
|
+
) {
|
|
57
|
+
return createReplayReadableStream(
|
|
58
|
+
storedStream,
|
|
59
|
+
resolveStreamReplayMode(options?.streamReplay)
|
|
60
|
+
);
|
|
61
|
+
}
|
|
25
62
|
if (typeof data === 'string') {
|
|
26
63
|
return data;
|
|
27
64
|
}
|