@sgedda/mockifyer-fetch 1.8.44 → 1.8.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +38 -30
- package/dist/metro-sync-middleware.d.ts +5 -4
- package/dist/metro-sync-middleware.js +56 -8
- package/dist/utils/fetch-response-body.d.ts +9 -0
- package/dist/utils/fetch-response-body.js +35 -0
- package/package.json +2 -2
- package/src/index.ts +46 -35
- package/src/metro-sync-middleware.ts +71 -8
- package/src/utils/fetch-response-body.ts +33 -0
package/dist/index.js
CHANGED
|
@@ -38,6 +38,7 @@ const mockifyer_core_2 = require("@sgedda/mockifyer-core");
|
|
|
38
38
|
const core_proxy_1 = require("./core-proxy");
|
|
39
39
|
const proxy_upstream_tls_insecure_1 = require("@sgedda/mockifyer-core/utils/proxy-upstream-tls-insecure");
|
|
40
40
|
const fetch_client_1 = require("./clients/fetch-client");
|
|
41
|
+
const fetch_response_body_1 = require("./utils/fetch-response-body");
|
|
41
42
|
class MockifyerClass {
|
|
42
43
|
/** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
|
|
43
44
|
logNetworkEvent(partial, correlation) {
|
|
@@ -255,6 +256,7 @@ class MockifyerClass {
|
|
|
255
256
|
this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
|
|
256
257
|
}
|
|
257
258
|
this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
|
|
259
|
+
this.domainPathRules = new mockifyer_core_1.DomainPathRulesSession({ config: this.config });
|
|
258
260
|
if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
|
|
259
261
|
const raw = typeof process !== 'undefined'
|
|
260
262
|
? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
|
|
@@ -335,16 +337,12 @@ class MockifyerClass {
|
|
|
335
337
|
async findBestMatchingMock(request, options) {
|
|
336
338
|
// CRITICAL: Never try to match sync endpoint requests - they should never be mocked
|
|
337
339
|
const requestUrl = request?.url || '';
|
|
338
|
-
if (
|
|
339
|
-
requestUrl.includes('/mockifyer-clear') ||
|
|
340
|
-
requestUrl.includes('/mockifyer-sync')) {
|
|
340
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestUrl)) {
|
|
341
341
|
return undefined;
|
|
342
342
|
}
|
|
343
343
|
const requestKey = this.generateRequestKey(request);
|
|
344
344
|
// CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
|
|
345
|
-
if (
|
|
346
|
-
requestKey.includes('/mockifyer-clear') ||
|
|
347
|
-
requestKey.includes('/mockifyer-sync')) {
|
|
345
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestKey)) {
|
|
348
346
|
return undefined;
|
|
349
347
|
}
|
|
350
348
|
// Use database provider if available, otherwise fallback to filesystem
|
|
@@ -360,16 +358,12 @@ class MockifyerClass {
|
|
|
360
358
|
}
|
|
361
359
|
// CRITICAL: Never try to match sync endpoint requests - they should never be mocked
|
|
362
360
|
const requestUrl = request?.url || '';
|
|
363
|
-
if (
|
|
364
|
-
requestUrl.includes('/mockifyer-clear') ||
|
|
365
|
-
requestUrl.includes('/mockifyer-sync')) {
|
|
361
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestUrl)) {
|
|
366
362
|
return undefined;
|
|
367
363
|
}
|
|
368
364
|
const requestKey = this.generateRequestKey(request);
|
|
369
365
|
// CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
|
|
370
|
-
if (
|
|
371
|
-
requestKey.includes('/mockifyer-clear') ||
|
|
372
|
-
requestKey.includes('/mockifyer-sync')) {
|
|
366
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(requestKey)) {
|
|
373
367
|
return undefined;
|
|
374
368
|
}
|
|
375
369
|
// Try exact match first
|
|
@@ -521,7 +515,7 @@ class MockifyerClass {
|
|
|
521
515
|
// CRITICAL: Completely bypass Mockifyer interception for sync endpoints
|
|
522
516
|
// This prevents any Mockifyer processing (mocking, saving, etc.) for these endpoints
|
|
523
517
|
const url = config.url || '';
|
|
524
|
-
if (
|
|
518
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url)) {
|
|
525
519
|
// Mark this request to completely skip Mockifyer processing
|
|
526
520
|
config.__mockifyer_skip_save = true;
|
|
527
521
|
config.__mockifyer_bypass = true;
|
|
@@ -568,6 +562,14 @@ class MockifyerClass {
|
|
|
568
562
|
if (this.usesDashboardProxy()) {
|
|
569
563
|
return config;
|
|
570
564
|
}
|
|
565
|
+
this.domainPathRules.discover(request.url, this.config.baseUrl);
|
|
566
|
+
const trafficGate = this.domainPathRules.getTrafficGate(request.url, this.config.baseUrl);
|
|
567
|
+
config.__mockifyer_domain_path_may_record = trafficGate.mayRecord;
|
|
568
|
+
if (!trafficGate.mayReplay) {
|
|
569
|
+
mockifyer_core_2.logger.debug(`[Mockifyer-Fetch] Domain path rules: replay denied for ${request.method} ${request.url}` +
|
|
570
|
+
(trafficGate.matchedDomainPath ? ` (rule: ${trafficGate.matchedDomainPath})` : ' (allowlist unmatched)'));
|
|
571
|
+
return config;
|
|
572
|
+
}
|
|
571
573
|
const cachedMock = await this.findBestMatchingMock(request);
|
|
572
574
|
// Return cached mock if found
|
|
573
575
|
if (cachedMock) {
|
|
@@ -659,7 +661,7 @@ class MockifyerClass {
|
|
|
659
661
|
// Check multiple ways to get the URL in case response.config is undefined
|
|
660
662
|
const url = response.config?.url || response.request?.responseURL || response.url || response.config?.url || '';
|
|
661
663
|
// CRITICAL: Check URL FIRST before any other processing
|
|
662
|
-
if (
|
|
664
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url)) {
|
|
663
665
|
// Mark as bypassed to prevent any further processing
|
|
664
666
|
response.config.__mockifyer_skip_save = true;
|
|
665
667
|
response.config.__mockifyer_bypass = true;
|
|
@@ -705,9 +707,7 @@ class MockifyerClass {
|
|
|
705
707
|
return response;
|
|
706
708
|
}
|
|
707
709
|
// CRITICAL: Check for sync endpoint URLs in response data
|
|
708
|
-
if (
|
|
709
|
-
responseDataStr.includes('/mockifyer-clear') ||
|
|
710
|
-
responseDataStr.includes('/mockifyer-sync'))) {
|
|
710
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(responseDataStr)) {
|
|
711
711
|
return response;
|
|
712
712
|
}
|
|
713
713
|
}
|
|
@@ -885,6 +885,17 @@ class MockifyerClass {
|
|
|
885
885
|
(0, mockifyer_core_1.shouldExcludeRecording)(url, recordingExclusions, this.config.baseUrl)) {
|
|
886
886
|
return;
|
|
887
887
|
}
|
|
888
|
+
const mayRecordFlag = response.config?.__mockifyer_domain_path_may_record;
|
|
889
|
+
if (mayRecordFlag === false) {
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
if (mayRecordFlag !== true) {
|
|
893
|
+
this.domainPathRules.discover(url, this.config.baseUrl);
|
|
894
|
+
const gate = this.domainPathRules.getTrafficGate(url, this.config.baseUrl);
|
|
895
|
+
if (!gate.mayRecord) {
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
}
|
|
888
899
|
// CRITICAL: Check response data for sync endpoint references and Metro rejection messages
|
|
889
900
|
// This is a defense-in-depth measure
|
|
890
901
|
try {
|
|
@@ -905,9 +916,7 @@ class MockifyerClass {
|
|
|
905
916
|
return;
|
|
906
917
|
}
|
|
907
918
|
// CRITICAL: Check for sync endpoint URLs in response data
|
|
908
|
-
if (
|
|
909
|
-
responseDataStr.includes('/mockifyer-clear') ||
|
|
910
|
-
responseDataStr.includes('/mockifyer-sync'))) {
|
|
919
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(responseDataStr)) {
|
|
911
920
|
return;
|
|
912
921
|
}
|
|
913
922
|
}
|
|
@@ -1232,6 +1241,10 @@ class MockifyerClass {
|
|
|
1232
1241
|
this.loadMockData();
|
|
1233
1242
|
}
|
|
1234
1243
|
}
|
|
1244
|
+
// RN Hybrid: pull domain-path-rules.json via Metro before traffic can discover
|
|
1245
|
+
// allowlist defaults that would block already-enabled paths.
|
|
1246
|
+
this.domainPathRules.invalidateCache();
|
|
1247
|
+
await this.domainPathRules.hydrate();
|
|
1235
1248
|
}
|
|
1236
1249
|
clearStaleCacheEntries() {
|
|
1237
1250
|
return 0; // No cache in fetch implementation
|
|
@@ -1304,9 +1317,7 @@ function setupMockifyer(config) {
|
|
|
1304
1317
|
const headers = init?.headers || {};
|
|
1305
1318
|
const body = init?.body;
|
|
1306
1319
|
// Skip Mockifyer sync endpoints, dashboard `/api/proxy` plumbing, and Resend API
|
|
1307
|
-
if (
|
|
1308
|
-
url.includes('/mockifyer-clear') ||
|
|
1309
|
-
url.includes('/mockifyer-sync') ||
|
|
1320
|
+
if ((0, mockifyer_core_1.containsMockifyerSyncEndpointMarker)(url) ||
|
|
1310
1321
|
url.includes('api.resend.com') ||
|
|
1311
1322
|
(0, mockifyer_core_1.isMockifyerDashboardProxyApiUrl)(url)) {
|
|
1312
1323
|
return await originalFetchForPatched(input, init);
|
|
@@ -1364,8 +1375,7 @@ function setupMockifyer(config) {
|
|
|
1364
1375
|
}
|
|
1365
1376
|
});
|
|
1366
1377
|
}
|
|
1367
|
-
|
|
1368
|
-
return new Response(responseBody, {
|
|
1378
|
+
return new Response((0, fetch_response_body_1.bodyInitForFetchResponse)(response.status, response.data), {
|
|
1369
1379
|
status: response.status,
|
|
1370
1380
|
statusText: response.statusText || '',
|
|
1371
1381
|
headers: responseHeaders
|
|
@@ -1377,11 +1387,9 @@ function setupMockifyer(config) {
|
|
|
1377
1387
|
Object.entries(error.response.headers || {}).forEach(([key, value]) => {
|
|
1378
1388
|
responseHeaders.set(key, String(value));
|
|
1379
1389
|
});
|
|
1380
|
-
const
|
|
1381
|
-
|
|
1382
|
-
:
|
|
1383
|
-
return new Response(errorBody, {
|
|
1384
|
-
status: error.response.status,
|
|
1390
|
+
const errorStatus = error.response.status;
|
|
1391
|
+
return new Response((0, fetch_response_body_1.bodyInitForFetchResponse)(errorStatus, error.response.data), {
|
|
1392
|
+
status: errorStatus,
|
|
1385
1393
|
statusText: error.response.statusText || '',
|
|
1386
1394
|
headers: responseHeaders
|
|
1387
1395
|
});
|
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Provides sync mechanisms:
|
|
5
5
|
* 1. POST /mockifyer-save - Direct save endpoint (used by Hybrid Provider for instant sync)
|
|
6
|
-
* 2. GET /mockifyer-
|
|
7
|
-
* 3. GET /mockifyer-sync-to-device
|
|
8
|
-
* 4. GET /mockifyer-
|
|
9
|
-
* 5. GET /mockifyer-
|
|
6
|
+
* 2. GET/POST /mockifyer-domain-path-rules - Load or merge discovered domain-path allowlist keys into scenario file
|
|
7
|
+
* 3. GET /mockifyer-sync-to-device-manifest + /mockifyer-sync-to-device-file - Project → app (HybridProvider; avoids huge single JSON)
|
|
8
|
+
* 4. GET /mockifyer-sync-to-device - Legacy: all files in one response (may fail on large scenarios)
|
|
9
|
+
* 5. GET /mockifyer-pool-response?id= - Load a promoted pool response for RN `$pool` resolve
|
|
10
|
+
* 6. GET /mockifyer-sync - Legacy: iOS simulator mock-data → project folder
|
|
10
11
|
*
|
|
11
12
|
* The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
|
|
12
13
|
* Legacy polling-based sync is still available for backward compatibility.
|
|
@@ -4,10 +4,11 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Provides sync mechanisms:
|
|
6
6
|
* 1. POST /mockifyer-save - Direct save endpoint (used by Hybrid Provider for instant sync)
|
|
7
|
-
* 2. GET /mockifyer-
|
|
8
|
-
* 3. GET /mockifyer-sync-to-device
|
|
9
|
-
* 4. GET /mockifyer-
|
|
10
|
-
* 5. GET /mockifyer-
|
|
7
|
+
* 2. GET/POST /mockifyer-domain-path-rules - Load or merge discovered domain-path allowlist keys into scenario file
|
|
8
|
+
* 3. GET /mockifyer-sync-to-device-manifest + /mockifyer-sync-to-device-file - Project → app (HybridProvider; avoids huge single JSON)
|
|
9
|
+
* 4. GET /mockifyer-sync-to-device - Legacy: all files in one response (may fail on large scenarios)
|
|
10
|
+
* 5. GET /mockifyer-pool-response?id= - Load a promoted pool response for RN `$pool` resolve
|
|
11
|
+
* 6. GET /mockifyer-sync - Legacy: iOS simulator mock-data → project folder
|
|
11
12
|
*
|
|
12
13
|
* The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
|
|
13
14
|
* Legacy polling-based sync is still available for backward compatibility.
|
|
@@ -256,13 +257,13 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
|
|
|
256
257
|
try {
|
|
257
258
|
// CRITICAL: Never save Mockifyer sync endpoint requests to prevent infinite loops
|
|
258
259
|
const url = mockData?.request?.url || '';
|
|
259
|
-
if (
|
|
260
|
+
if ((0, mockifyer_core_2.containsMockifyerSyncEndpointMarker)(url)) {
|
|
260
261
|
console.warn(`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`);
|
|
261
262
|
return { success: false, error: 'Cannot save Mockifyer sync endpoint requests' };
|
|
262
263
|
}
|
|
263
264
|
// Also check if the mockData string contains nested sync requests
|
|
264
265
|
const mockDataStr = JSON.stringify(mockData);
|
|
265
|
-
if (
|
|
266
|
+
if ((0, mockifyer_core_2.containsMockifyerSyncEndpointMarker)(mockDataStr)) {
|
|
266
267
|
mockifyer_core_1.logger.warn(`[MockSync] ⚠️ Rejecting save - Mock data contains nested Mockifyer sync requests`);
|
|
267
268
|
return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
|
|
268
269
|
}
|
|
@@ -299,12 +300,12 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
|
|
|
299
300
|
function saveProxyMirrorMockToProject(mockData, projectRoot, mockDataPath, scenarioName, relativePath, testConfig) {
|
|
300
301
|
try {
|
|
301
302
|
const url = mockData?.request?.url || '';
|
|
302
|
-
if (
|
|
303
|
+
if ((0, mockifyer_core_2.containsMockifyerSyncEndpointMarker)(url)) {
|
|
303
304
|
console.warn(`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`);
|
|
304
305
|
return { success: false, error: 'Cannot save Mockifyer sync endpoint requests' };
|
|
305
306
|
}
|
|
306
307
|
const mockDataStr = JSON.stringify(mockData);
|
|
307
|
-
if (
|
|
308
|
+
if ((0, mockifyer_core_2.containsMockifyerSyncEndpointMarker)(mockDataStr)) {
|
|
308
309
|
return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
|
|
309
310
|
}
|
|
310
311
|
const id = scenarioName.trim();
|
|
@@ -625,6 +626,53 @@ function createMockSyncMiddleware(options) {
|
|
|
625
626
|
res.end(JSON.stringify(result));
|
|
626
627
|
return;
|
|
627
628
|
}
|
|
629
|
+
// Handle GET endpoint for domain-path rules (RN Hybrid hydrate at startup)
|
|
630
|
+
if (url === '/mockifyer-domain-path-rules' && req.method === 'GET') {
|
|
631
|
+
const fullUrl = req.url || '';
|
|
632
|
+
const qIndex = fullUrl.indexOf('?');
|
|
633
|
+
const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : '';
|
|
634
|
+
const params = new URLSearchParams(query);
|
|
635
|
+
const scenarioParam = params.get('scenario');
|
|
636
|
+
const scenarioName = scenarioParam && scenarioParam.trim() !== ''
|
|
637
|
+
? scenarioParam.trim()
|
|
638
|
+
: getCurrentScenario(mockDataPath);
|
|
639
|
+
const rules = (0, mockifyer_core_2.readDomainPathRulesFile)(mockDataPath, scenarioName);
|
|
640
|
+
res.setHeader('Content-Type', 'application/json');
|
|
641
|
+
res.end(JSON.stringify({ success: true, scenario: scenarioName, rules }));
|
|
642
|
+
return;
|
|
643
|
+
}
|
|
644
|
+
// Handle POST endpoint for domain-path rules discovery merge (Hybrid / RN)
|
|
645
|
+
if (url === '/mockifyer-domain-path-rules' && req.method === 'POST') {
|
|
646
|
+
let body = '';
|
|
647
|
+
req.on('data', (chunk) => {
|
|
648
|
+
body += chunk.toString();
|
|
649
|
+
});
|
|
650
|
+
req.on('end', () => {
|
|
651
|
+
try {
|
|
652
|
+
const parsed = JSON.parse(body);
|
|
653
|
+
const scenarioName = typeof parsed.scenario === 'string' && parsed.scenario.trim() !== ''
|
|
654
|
+
? parsed.scenario.trim()
|
|
655
|
+
: getCurrentScenario(mockDataPath);
|
|
656
|
+
const upserts = (0, mockifyer_core_2.parseDomainPathRules)(parsed.upserts ?? parsed.rules ?? {});
|
|
657
|
+
const existing = (0, mockifyer_core_2.readDomainPathRulesFile)(mockDataPath, scenarioName);
|
|
658
|
+
const { rules, changed } = (0, mockifyer_core_2.mergeDomainPathRuleUpserts)(existing, upserts);
|
|
659
|
+
if (changed) {
|
|
660
|
+
(0, mockifyer_core_2.writeDomainPathRulesFile)(mockDataPath, scenarioName, rules);
|
|
661
|
+
}
|
|
662
|
+
res.setHeader('Content-Type', 'application/json');
|
|
663
|
+
res.end(JSON.stringify({ success: true, changed, scenario: scenarioName, rules }));
|
|
664
|
+
}
|
|
665
|
+
catch (error) {
|
|
666
|
+
res.statusCode = 400;
|
|
667
|
+
res.setHeader('Content-Type', 'application/json');
|
|
668
|
+
res.end(JSON.stringify({
|
|
669
|
+
success: false,
|
|
670
|
+
error: `Invalid JSON: ${error.message}`,
|
|
671
|
+
}));
|
|
672
|
+
}
|
|
673
|
+
});
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
628
676
|
// Handle POST endpoint for direct save (HybridProvider)
|
|
629
677
|
if (url === '/mockifyer-save' && req.method === 'POST') {
|
|
630
678
|
let body = '';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether `status` forbids a Response body under the Fetch spec.
|
|
3
|
+
*/
|
|
4
|
+
export declare function isFetchNullBodyStatus(status: number): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Body argument for `new Response(body, { status })`.
|
|
7
|
+
* Returns `null` for null-body statuses so Node/undici does not throw.
|
|
8
|
+
*/
|
|
9
|
+
export declare function bodyInitForFetchResponse(status: number, data: unknown): BodyInit | null;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isFetchNullBodyStatus = isFetchNullBodyStatus;
|
|
4
|
+
exports.bodyInitForFetchResponse = bodyInitForFetchResponse;
|
|
5
|
+
/**
|
|
6
|
+
* Fetch "null body status" codes — Response body must be null.
|
|
7
|
+
* Passing '' / JSON (including JSON.stringify(null) → "null") throws in undici:
|
|
8
|
+
* `TypeError: Response constructor: Invalid response status code 204`
|
|
9
|
+
*
|
|
10
|
+
* @see https://fetch.spec.whatwg.org/#null-body-status
|
|
11
|
+
*/
|
|
12
|
+
const FETCH_NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
|
|
13
|
+
/**
|
|
14
|
+
* Whether `status` forbids a Response body under the Fetch spec.
|
|
15
|
+
*/
|
|
16
|
+
function isFetchNullBodyStatus(status) {
|
|
17
|
+
return FETCH_NULL_BODY_STATUSES.has(status);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Body argument for `new Response(body, { status })`.
|
|
21
|
+
* Returns `null` for null-body statuses so Node/undici does not throw.
|
|
22
|
+
*/
|
|
23
|
+
function bodyInitForFetchResponse(status, data) {
|
|
24
|
+
if (isFetchNullBodyStatus(status)) {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
if (typeof data === 'string') {
|
|
28
|
+
return data;
|
|
29
|
+
}
|
|
30
|
+
// JSON.stringify(undefined) is undefined — Response treats nullish as empty body
|
|
31
|
+
if (data === undefined) {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
return JSON.stringify(data);
|
|
35
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sgedda/mockifyer-fetch",
|
|
3
|
-
"version": "1.8.
|
|
3
|
+
"version": "1.8.47",
|
|
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",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
},
|
|
50
50
|
"license": "MIT",
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@sgedda/mockifyer-core": "^1.10.
|
|
52
|
+
"@sgedda/mockifyer-core": "^1.10.31"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@types/node": "^20.11.24",
|
package/src/index.ts
CHANGED
|
@@ -42,6 +42,7 @@ import {
|
|
|
42
42
|
isUsableNodeLikePoolFs,
|
|
43
43
|
type PoolResponseItem,
|
|
44
44
|
shouldBypassMockifyerForUrl,
|
|
45
|
+
containsMockifyerSyncEndpointMarker,
|
|
45
46
|
isMockifyerDashboardProxyApiUrl,
|
|
46
47
|
resolveRecordingExclusions,
|
|
47
48
|
shouldExcludeRecording,
|
|
@@ -78,6 +79,7 @@ import {
|
|
|
78
79
|
attachMockifyerRequestIdToError,
|
|
79
80
|
resolveMockifyerRequestIdForError,
|
|
80
81
|
type RequestCorrelationContext,
|
|
82
|
+
DomainPathRulesSession,
|
|
81
83
|
installNodeInboundRequestCorrelationCapture,
|
|
82
84
|
} from '@sgedda/mockifyer-core';
|
|
83
85
|
import { logger, setLogLevel } from '@sgedda/mockifyer-core';
|
|
@@ -98,6 +100,7 @@ import {
|
|
|
98
100
|
import { resolveProxyUpstreamTlsInsecure } from '@sgedda/mockifyer-core/utils/proxy-upstream-tls-insecure';
|
|
99
101
|
|
|
100
102
|
import { FetchHTTPClient } from './clients/fetch-client';
|
|
103
|
+
import { bodyInitForFetchResponse } from './utils/fetch-response-body';
|
|
101
104
|
|
|
102
105
|
class MockifyerClass {
|
|
103
106
|
private config: MockifyerConfig;
|
|
@@ -117,6 +120,7 @@ class MockifyerClass {
|
|
|
117
120
|
* unavailable (React Native / Metro stubs). Seeded via {@link warmPoolResponseCache}.
|
|
118
121
|
*/
|
|
119
122
|
private readonly poolResponseCache = new Map<string, PoolResponseItem>();
|
|
123
|
+
private readonly domainPathRules: DomainPathRulesSession;
|
|
120
124
|
|
|
121
125
|
/** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
|
|
122
126
|
private logNetworkEvent(
|
|
@@ -366,6 +370,7 @@ class MockifyerClass {
|
|
|
366
370
|
this.config.clientId = resolveClientId(this.config);
|
|
367
371
|
}
|
|
368
372
|
this.activationMode = resolveActivationMode(this.config);
|
|
373
|
+
this.domainPathRules = new DomainPathRulesSession({ config: this.config });
|
|
369
374
|
|
|
370
375
|
if (this.config.proxy?.baseUrl && this.config.proxy.mirrorRecordedMocksToClient === undefined) {
|
|
371
376
|
const raw =
|
|
@@ -461,18 +466,14 @@ class MockifyerClass {
|
|
|
461
466
|
): Promise<CachedMockData | undefined> {
|
|
462
467
|
// CRITICAL: Never try to match sync endpoint requests - they should never be mocked
|
|
463
468
|
const requestUrl = request?.url || '';
|
|
464
|
-
if (requestUrl
|
|
465
|
-
requestUrl.includes('/mockifyer-clear') ||
|
|
466
|
-
requestUrl.includes('/mockifyer-sync')) {
|
|
469
|
+
if (containsMockifyerSyncEndpointMarker(requestUrl)) {
|
|
467
470
|
return undefined;
|
|
468
471
|
}
|
|
469
472
|
|
|
470
473
|
const requestKey = this.generateRequestKey(request);
|
|
471
474
|
|
|
472
475
|
// CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
|
|
473
|
-
if (requestKey
|
|
474
|
-
requestKey.includes('/mockifyer-clear') ||
|
|
475
|
-
requestKey.includes('/mockifyer-sync')) {
|
|
476
|
+
if (containsMockifyerSyncEndpointMarker(requestKey)) {
|
|
476
477
|
return undefined;
|
|
477
478
|
}
|
|
478
479
|
|
|
@@ -494,18 +495,14 @@ class MockifyerClass {
|
|
|
494
495
|
|
|
495
496
|
// CRITICAL: Never try to match sync endpoint requests - they should never be mocked
|
|
496
497
|
const requestUrl = request?.url || '';
|
|
497
|
-
if (requestUrl
|
|
498
|
-
requestUrl.includes('/mockifyer-clear') ||
|
|
499
|
-
requestUrl.includes('/mockifyer-sync')) {
|
|
498
|
+
if (containsMockifyerSyncEndpointMarker(requestUrl)) {
|
|
500
499
|
return undefined;
|
|
501
500
|
}
|
|
502
501
|
|
|
503
502
|
const requestKey = this.generateRequestKey(request);
|
|
504
503
|
|
|
505
504
|
// CRITICAL: Also check requestKey for sync endpoint URLs (defense in depth)
|
|
506
|
-
if (requestKey
|
|
507
|
-
requestKey.includes('/mockifyer-clear') ||
|
|
508
|
-
requestKey.includes('/mockifyer-sync')) {
|
|
505
|
+
if (containsMockifyerSyncEndpointMarker(requestKey)) {
|
|
509
506
|
return undefined;
|
|
510
507
|
}
|
|
511
508
|
|
|
@@ -685,7 +682,7 @@ class MockifyerClass {
|
|
|
685
682
|
// CRITICAL: Completely bypass Mockifyer interception for sync endpoints
|
|
686
683
|
// This prevents any Mockifyer processing (mocking, saving, etc.) for these endpoints
|
|
687
684
|
const url = config.url || '';
|
|
688
|
-
if (
|
|
685
|
+
if (containsMockifyerSyncEndpointMarker(url)) {
|
|
689
686
|
// Mark this request to completely skip Mockifyer processing
|
|
690
687
|
(config as any).__mockifyer_skip_save = true;
|
|
691
688
|
(config as any).__mockifyer_bypass = true;
|
|
@@ -745,6 +742,17 @@ class MockifyerClass {
|
|
|
745
742
|
if (this.usesDashboardProxy()) {
|
|
746
743
|
return config;
|
|
747
744
|
}
|
|
745
|
+
|
|
746
|
+
this.domainPathRules.discover(request.url, this.config.baseUrl);
|
|
747
|
+
const trafficGate = this.domainPathRules.getTrafficGate(request.url, this.config.baseUrl);
|
|
748
|
+
(config as any).__mockifyer_domain_path_may_record = trafficGate.mayRecord;
|
|
749
|
+
if (!trafficGate.mayReplay) {
|
|
750
|
+
logger.debug(
|
|
751
|
+
`[Mockifyer-Fetch] Domain path rules: replay denied for ${request.method} ${request.url}` +
|
|
752
|
+
(trafficGate.matchedDomainPath ? ` (rule: ${trafficGate.matchedDomainPath})` : ' (allowlist unmatched)')
|
|
753
|
+
);
|
|
754
|
+
return config;
|
|
755
|
+
}
|
|
748
756
|
|
|
749
757
|
const cachedMock = await this.findBestMatchingMock(request);
|
|
750
758
|
|
|
@@ -860,7 +868,7 @@ class MockifyerClass {
|
|
|
860
868
|
const url = response.config?.url || response.request?.responseURL || response.url || (response as any).config?.url || '';
|
|
861
869
|
|
|
862
870
|
// CRITICAL: Check URL FIRST before any other processing
|
|
863
|
-
if (
|
|
871
|
+
if (containsMockifyerSyncEndpointMarker(url)) {
|
|
864
872
|
// Mark as bypassed to prevent any further processing
|
|
865
873
|
(response.config as any).__mockifyer_skip_save = true;
|
|
866
874
|
(response.config as any).__mockifyer_bypass = true;
|
|
@@ -914,10 +922,7 @@ class MockifyerClass {
|
|
|
914
922
|
}
|
|
915
923
|
|
|
916
924
|
// CRITICAL: Check for sync endpoint URLs in response data
|
|
917
|
-
if (responseDataStr
|
|
918
|
-
responseDataStr.includes('/mockifyer-save') ||
|
|
919
|
-
responseDataStr.includes('/mockifyer-clear') ||
|
|
920
|
-
responseDataStr.includes('/mockifyer-sync'))) {
|
|
925
|
+
if (containsMockifyerSyncEndpointMarker(responseDataStr)) {
|
|
921
926
|
return response;
|
|
922
927
|
}
|
|
923
928
|
} catch (e) {
|
|
@@ -1134,6 +1139,18 @@ class MockifyerClass {
|
|
|
1134
1139
|
) {
|
|
1135
1140
|
return;
|
|
1136
1141
|
}
|
|
1142
|
+
|
|
1143
|
+
const mayRecordFlag = (response.config as any)?.__mockifyer_domain_path_may_record;
|
|
1144
|
+
if (mayRecordFlag === false) {
|
|
1145
|
+
return;
|
|
1146
|
+
}
|
|
1147
|
+
if (mayRecordFlag !== true) {
|
|
1148
|
+
this.domainPathRules.discover(url, this.config.baseUrl);
|
|
1149
|
+
const gate = this.domainPathRules.getTrafficGate(url, this.config.baseUrl);
|
|
1150
|
+
if (!gate.mayRecord) {
|
|
1151
|
+
return;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1137
1154
|
|
|
1138
1155
|
// CRITICAL: Check response data for sync endpoint references and Metro rejection messages
|
|
1139
1156
|
// This is a defense-in-depth measure
|
|
@@ -1155,10 +1172,7 @@ class MockifyerClass {
|
|
|
1155
1172
|
}
|
|
1156
1173
|
|
|
1157
1174
|
// CRITICAL: Check for sync endpoint URLs in response data
|
|
1158
|
-
if (responseDataStr
|
|
1159
|
-
responseDataStr.includes('/mockifyer-save') ||
|
|
1160
|
-
responseDataStr.includes('/mockifyer-clear') ||
|
|
1161
|
-
responseDataStr.includes('/mockifyer-sync'))) {
|
|
1175
|
+
if (containsMockifyerSyncEndpointMarker(responseDataStr)) {
|
|
1162
1176
|
return;
|
|
1163
1177
|
}
|
|
1164
1178
|
} catch (e) {
|
|
@@ -1548,6 +1562,10 @@ class MockifyerClass {
|
|
|
1548
1562
|
(this as any).loadMockData();
|
|
1549
1563
|
}
|
|
1550
1564
|
}
|
|
1565
|
+
// RN Hybrid: pull domain-path-rules.json via Metro before traffic can discover
|
|
1566
|
+
// allowlist defaults that would block already-enabled paths.
|
|
1567
|
+
this.domainPathRules.invalidateCache();
|
|
1568
|
+
await this.domainPathRules.hydrate();
|
|
1551
1569
|
}
|
|
1552
1570
|
|
|
1553
1571
|
clearStaleCacheEntries(): number {
|
|
@@ -1639,9 +1657,7 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1639
1657
|
|
|
1640
1658
|
// Skip Mockifyer sync endpoints, dashboard `/api/proxy` plumbing, and Resend API
|
|
1641
1659
|
if (
|
|
1642
|
-
url
|
|
1643
|
-
url.includes('/mockifyer-clear') ||
|
|
1644
|
-
url.includes('/mockifyer-sync') ||
|
|
1660
|
+
containsMockifyerSyncEndpointMarker(url) ||
|
|
1645
1661
|
url.includes('api.resend.com') ||
|
|
1646
1662
|
isMockifyerDashboardProxyApiUrl(url)
|
|
1647
1663
|
) {
|
|
@@ -1704,9 +1720,7 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1704
1720
|
});
|
|
1705
1721
|
}
|
|
1706
1722
|
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
return new Response(responseBody, {
|
|
1723
|
+
return new Response(bodyInitForFetchResponse(response.status, response.data), {
|
|
1710
1724
|
status: response.status,
|
|
1711
1725
|
statusText: response.statusText || '',
|
|
1712
1726
|
headers: responseHeaders
|
|
@@ -1717,13 +1731,10 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1717
1731
|
Object.entries(error.response.headers || {}).forEach(([key, value]) => {
|
|
1718
1732
|
responseHeaders.set(key, String(value));
|
|
1719
1733
|
});
|
|
1720
|
-
|
|
1721
|
-
const
|
|
1722
|
-
|
|
1723
|
-
:
|
|
1724
|
-
|
|
1725
|
-
return new Response(errorBody, {
|
|
1726
|
-
status: error.response.status,
|
|
1734
|
+
|
|
1735
|
+
const errorStatus = error.response.status;
|
|
1736
|
+
return new Response(bodyInitForFetchResponse(errorStatus, error.response.data), {
|
|
1737
|
+
status: errorStatus,
|
|
1727
1738
|
statusText: error.response.statusText || '',
|
|
1728
1739
|
headers: responseHeaders
|
|
1729
1740
|
});
|
|
@@ -3,10 +3,11 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Provides sync mechanisms:
|
|
5
5
|
* 1. POST /mockifyer-save - Direct save endpoint (used by Hybrid Provider for instant sync)
|
|
6
|
-
* 2. GET /mockifyer-
|
|
7
|
-
* 3. GET /mockifyer-sync-to-device
|
|
8
|
-
* 4. GET /mockifyer-
|
|
9
|
-
* 5. GET /mockifyer-
|
|
6
|
+
* 2. GET/POST /mockifyer-domain-path-rules - Load or merge discovered domain-path allowlist keys into scenario file
|
|
7
|
+
* 3. GET /mockifyer-sync-to-device-manifest + /mockifyer-sync-to-device-file - Project → app (HybridProvider; avoids huge single JSON)
|
|
8
|
+
* 4. GET /mockifyer-sync-to-device - Legacy: all files in one response (may fail on large scenarios)
|
|
9
|
+
* 5. GET /mockifyer-pool-response?id= - Load a promoted pool response for RN `$pool` resolve
|
|
10
|
+
* 6. GET /mockifyer-sync - Legacy: iOS simulator mock-data → project folder
|
|
10
11
|
*
|
|
11
12
|
* The Hybrid Provider (recommended) uses POST /mockifyer-save for instant file sync.
|
|
12
13
|
* Legacy polling-based sync is still available for backward compatibility.
|
|
@@ -23,6 +24,12 @@ import {
|
|
|
23
24
|
POOL_ID_PATTERN,
|
|
24
25
|
loadPoolResponseItem,
|
|
25
26
|
type PoolResponseItem,
|
|
27
|
+
mergeDomainPathRuleUpserts,
|
|
28
|
+
parseDomainPathRules,
|
|
29
|
+
readDomainPathRulesFile,
|
|
30
|
+
writeDomainPathRulesFile,
|
|
31
|
+
type DomainPathRulesMap,
|
|
32
|
+
containsMockifyerSyncEndpointMarker,
|
|
26
33
|
} from '@sgedda/mockifyer-core';
|
|
27
34
|
|
|
28
35
|
export interface MetroSyncMiddlewareOptions {
|
|
@@ -275,14 +282,14 @@ function saveMockToProjectFolder(
|
|
|
275
282
|
try {
|
|
276
283
|
// CRITICAL: Never save Mockifyer sync endpoint requests to prevent infinite loops
|
|
277
284
|
const url = mockData?.request?.url || '';
|
|
278
|
-
if (
|
|
285
|
+
if (containsMockifyerSyncEndpointMarker(url)) {
|
|
279
286
|
console.warn(`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`);
|
|
280
287
|
return { success: false, error: 'Cannot save Mockifyer sync endpoint requests' };
|
|
281
288
|
}
|
|
282
289
|
|
|
283
290
|
// Also check if the mockData string contains nested sync requests
|
|
284
291
|
const mockDataStr = JSON.stringify(mockData);
|
|
285
|
-
if (
|
|
292
|
+
if (containsMockifyerSyncEndpointMarker(mockDataStr)) {
|
|
286
293
|
logger.warn(`[MockSync] ⚠️ Rejecting save - Mock data contains nested Mockifyer sync requests`);
|
|
287
294
|
return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
|
|
288
295
|
}
|
|
@@ -332,12 +339,12 @@ function saveProxyMirrorMockToProject(
|
|
|
332
339
|
): { success: boolean; filename?: string; scenario?: string; error?: string } {
|
|
333
340
|
try {
|
|
334
341
|
const url = mockData?.request?.url || '';
|
|
335
|
-
if (
|
|
342
|
+
if (containsMockifyerSyncEndpointMarker(url)) {
|
|
336
343
|
console.warn(`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`);
|
|
337
344
|
return { success: false, error: 'Cannot save Mockifyer sync endpoint requests' };
|
|
338
345
|
}
|
|
339
346
|
const mockDataStr = JSON.stringify(mockData);
|
|
340
|
-
if (
|
|
347
|
+
if (containsMockifyerSyncEndpointMarker(mockDataStr)) {
|
|
341
348
|
return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
|
|
342
349
|
}
|
|
343
350
|
const id = scenarioName.trim();
|
|
@@ -718,6 +725,62 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
718
725
|
return;
|
|
719
726
|
}
|
|
720
727
|
|
|
728
|
+
// Handle GET endpoint for domain-path rules (RN Hybrid hydrate at startup)
|
|
729
|
+
if (url === '/mockifyer-domain-path-rules' && req.method === 'GET') {
|
|
730
|
+
const fullUrl = req.url || '';
|
|
731
|
+
const qIndex = fullUrl.indexOf('?');
|
|
732
|
+
const query = qIndex >= 0 ? fullUrl.slice(qIndex + 1) : '';
|
|
733
|
+
const params = new URLSearchParams(query);
|
|
734
|
+
const scenarioParam = params.get('scenario');
|
|
735
|
+
const scenarioName =
|
|
736
|
+
scenarioParam && scenarioParam.trim() !== ''
|
|
737
|
+
? scenarioParam.trim()
|
|
738
|
+
: getCurrentScenario(mockDataPath);
|
|
739
|
+
const rules = readDomainPathRulesFile(mockDataPath, scenarioName);
|
|
740
|
+
res.setHeader('Content-Type', 'application/json');
|
|
741
|
+
res.end(JSON.stringify({ success: true, scenario: scenarioName, rules }));
|
|
742
|
+
return;
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
// Handle POST endpoint for domain-path rules discovery merge (Hybrid / RN)
|
|
746
|
+
if (url === '/mockifyer-domain-path-rules' && req.method === 'POST') {
|
|
747
|
+
let body = '';
|
|
748
|
+
req.on('data', (chunk: Buffer) => {
|
|
749
|
+
body += chunk.toString();
|
|
750
|
+
});
|
|
751
|
+
req.on('end', () => {
|
|
752
|
+
try {
|
|
753
|
+
const parsed = JSON.parse(body) as {
|
|
754
|
+
scenario?: string;
|
|
755
|
+
upserts?: DomainPathRulesMap;
|
|
756
|
+
rules?: DomainPathRulesMap;
|
|
757
|
+
};
|
|
758
|
+
const scenarioName =
|
|
759
|
+
typeof parsed.scenario === 'string' && parsed.scenario.trim() !== ''
|
|
760
|
+
? parsed.scenario.trim()
|
|
761
|
+
: getCurrentScenario(mockDataPath);
|
|
762
|
+
const upserts = parseDomainPathRules(parsed.upserts ?? parsed.rules ?? {});
|
|
763
|
+
const existing = readDomainPathRulesFile(mockDataPath, scenarioName);
|
|
764
|
+
const { rules, changed } = mergeDomainPathRuleUpserts(existing, upserts);
|
|
765
|
+
if (changed) {
|
|
766
|
+
writeDomainPathRulesFile(mockDataPath, scenarioName, rules);
|
|
767
|
+
}
|
|
768
|
+
res.setHeader('Content-Type', 'application/json');
|
|
769
|
+
res.end(JSON.stringify({ success: true, changed, scenario: scenarioName, rules }));
|
|
770
|
+
} catch (error) {
|
|
771
|
+
res.statusCode = 400;
|
|
772
|
+
res.setHeader('Content-Type', 'application/json');
|
|
773
|
+
res.end(
|
|
774
|
+
JSON.stringify({
|
|
775
|
+
success: false,
|
|
776
|
+
error: `Invalid JSON: ${(error as Error).message}`,
|
|
777
|
+
})
|
|
778
|
+
);
|
|
779
|
+
}
|
|
780
|
+
});
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
|
|
721
784
|
// Handle POST endpoint for direct save (HybridProvider)
|
|
722
785
|
if (url === '/mockifyer-save' && req.method === 'POST') {
|
|
723
786
|
let body = '';
|
|
@@ -0,0 +1,33 @@
|
|
|
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
|
+
const FETCH_NULL_BODY_STATUSES = new Set([101, 103, 204, 205, 304]);
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Whether `status` forbids a Response body under the Fetch spec.
|
|
12
|
+
*/
|
|
13
|
+
export function isFetchNullBodyStatus(status: number): boolean {
|
|
14
|
+
return FETCH_NULL_BODY_STATUSES.has(status);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Body argument for `new Response(body, { status })`.
|
|
19
|
+
* Returns `null` for null-body statuses so Node/undici does not throw.
|
|
20
|
+
*/
|
|
21
|
+
export function bodyInitForFetchResponse(status: number, data: unknown): BodyInit | null {
|
|
22
|
+
if (isFetchNullBodyStatus(status)) {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
if (typeof data === 'string') {
|
|
26
|
+
return data;
|
|
27
|
+
}
|
|
28
|
+
// JSON.stringify(undefined) is undefined — Response treats nullish as empty body
|
|
29
|
+
if (data === undefined) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
return JSON.stringify(data);
|
|
33
|
+
}
|