@sgedda/mockifyer-fetch 1.8.100 → 1.8.104
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/clients/fetch-client.d.ts +4 -0
- package/dist/clients/fetch-client.js +50 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +161 -41
- package/dist/metro-sync-middleware.d.ts +10 -0
- package/dist/metro-sync-middleware.js +163 -23
- package/dist/react-native.d.ts +4 -0
- package/dist/utils/resolve-patched-fetch-request.d.ts +24 -0
- package/dist/utils/resolve-patched-fetch-request.js +91 -0
- package/package.json +2 -2
- package/src/clients/fetch-client.ts +66 -1
- package/src/index.ts +196 -41
- package/src/metro-sync-middleware.ts +199 -23
- package/src/react-native.ts +4 -0
- package/src/utils/resolve-patched-fetch-request.ts +105 -0
package/src/index.ts
CHANGED
|
@@ -80,10 +80,16 @@ import {
|
|
|
80
80
|
resolveNetworkLogIncludeTraceOptionsAsync,
|
|
81
81
|
getInlineTraceEnvelopeBusinessBody,
|
|
82
82
|
resolveRecordResponses,
|
|
83
|
+
resolveLocalRecordResponses,
|
|
84
|
+
buildLocalRecordingMockData,
|
|
83
85
|
applyOutboundRequestCorrelation,
|
|
84
86
|
adoptStoredOutboundRequestId,
|
|
85
87
|
resolvePersistedHopIds,
|
|
86
88
|
applyPersistedHopIds,
|
|
89
|
+
ensureLocalInboundParentStubSaved,
|
|
90
|
+
inboundParentStubFilename,
|
|
91
|
+
readOutboundParentHopFromConfig,
|
|
92
|
+
getActiveInboundRequest,
|
|
87
93
|
attachMockifyerRequestIdToError,
|
|
88
94
|
resolveMockifyerRequestIdForError,
|
|
89
95
|
configureFlightRecorder,
|
|
@@ -121,6 +127,7 @@ import { resolveProxyUpstreamTlsInsecure } from '@sgedda/mockifyer-core/utils/pr
|
|
|
121
127
|
|
|
122
128
|
import { FetchHTTPClient } from './clients/fetch-client';
|
|
123
129
|
import { bodyInitForFetchResponse } from './utils/fetch-response-body';
|
|
130
|
+
import { resolvePatchedFetchRequest } from './utils/resolve-patched-fetch-request';
|
|
124
131
|
|
|
125
132
|
class MockifyerClass {
|
|
126
133
|
private config: MockifyerConfig;
|
|
@@ -145,6 +152,11 @@ class MockifyerClass {
|
|
|
145
152
|
private runtimeEnabled: boolean;
|
|
146
153
|
/** Optional storage for persisting enable/disable across restarts. */
|
|
147
154
|
private readonly runtimeEnabledStorage?: MockifyerRuntimeEnabledStorage;
|
|
155
|
+
/**
|
|
156
|
+
* Runtime override for whether local/proxy recordings include response bodies.
|
|
157
|
+
* `undefined` = follow env / defaults ({@link resolveLocalRecordResponses} / {@link resolveRecordResponses}).
|
|
158
|
+
*/
|
|
159
|
+
private recordResponsesOverride: boolean | undefined = undefined;
|
|
148
160
|
|
|
149
161
|
/** Session id for timeline hops — per-screen id from {@link setFlightRecorderRuntimeContext} when set. */
|
|
150
162
|
private getRuntimeSessionId(): string {
|
|
@@ -472,7 +484,10 @@ class MockifyerClass {
|
|
|
472
484
|
this.config.clientId = resolveClientId(this.config);
|
|
473
485
|
}
|
|
474
486
|
this.activationMode = resolveActivationMode(this.config);
|
|
475
|
-
this.domainPathRules = new DomainPathRulesSession({
|
|
487
|
+
this.domainPathRules = new DomainPathRulesSession({
|
|
488
|
+
config: this.config,
|
|
489
|
+
getRecordMode: () => this.config.recordMode === true,
|
|
490
|
+
});
|
|
476
491
|
|
|
477
492
|
this.runtimeEnabledStorage = resolveRuntimeEnabledStorage(config.persistRuntimeEnabled);
|
|
478
493
|
if (config.persistRuntimeEnabled === true && !this.runtimeEnabledStorage) {
|
|
@@ -1467,30 +1482,42 @@ class MockifyerClass {
|
|
|
1467
1482
|
correlation
|
|
1468
1483
|
);
|
|
1469
1484
|
|
|
1470
|
-
const
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1485
|
+
const storedRequest: StoredRequest = {
|
|
1486
|
+
method: response.config?.method?.toUpperCase() || 'GET',
|
|
1487
|
+
url: response.config?.url || '',
|
|
1488
|
+
headers: this.anonymizeHeaders(response.config?.headers || {}),
|
|
1489
|
+
data: response.config?.data,
|
|
1490
|
+
queryParams: normalizedParamsForSave,
|
|
1491
|
+
};
|
|
1492
|
+
// Prefer explicit override / config; else request-only default (same as proxy).
|
|
1493
|
+
const recordBodies = resolveLocalRecordResponses(
|
|
1494
|
+
this.recordResponsesOverride ??
|
|
1495
|
+
this.config.proxy?.recordResponses ??
|
|
1496
|
+
this.config.recordResponses
|
|
1497
|
+
);
|
|
1498
|
+
const mockData = buildLocalRecordingMockData({
|
|
1499
|
+
request: storedRequest,
|
|
1478
1500
|
response: {
|
|
1479
1501
|
status: response.status,
|
|
1480
1502
|
data: stripMockifyerTraceFromBody(response.data),
|
|
1481
1503
|
headers: response.headers || {},
|
|
1482
1504
|
},
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1505
|
+
recordResponses: recordBodies,
|
|
1506
|
+
meta: {
|
|
1507
|
+
timestamp: new Date().toISOString(),
|
|
1508
|
+
duration,
|
|
1509
|
+
sessionId:
|
|
1510
|
+
saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
|
|
1511
|
+
? existingMock.mockData.sessionId
|
|
1512
|
+
: this.currentSessionId,
|
|
1513
|
+
requestId: hopIds.requestId,
|
|
1514
|
+
parentRequestId: hopIds.parentRequestId,
|
|
1515
|
+
parentRequestIds: hopIds.parentRequestIds,
|
|
1516
|
+
...(newRecordingUsesAlwaysUseRealApi() || !recordBodies
|
|
1517
|
+
? { alwaysUseRealApi: true as const }
|
|
1518
|
+
: {}),
|
|
1519
|
+
},
|
|
1520
|
+
});
|
|
1494
1521
|
|
|
1495
1522
|
applyRecordingPassthroughFlag(mockData, saveDecision.alwaysUseRealApi);
|
|
1496
1523
|
|
|
@@ -1541,11 +1568,65 @@ class MockifyerClass {
|
|
|
1541
1568
|
} else {
|
|
1542
1569
|
console.warn('[Mockifyer] Cannot save mock: no database provider and fs/path not available');
|
|
1543
1570
|
}
|
|
1571
|
+
|
|
1572
|
+
await this.ensureInboundParentStubForChild(hopIds.parentRequestId, response.config);
|
|
1544
1573
|
} finally {
|
|
1545
1574
|
this.savingResponses.delete(requestKey);
|
|
1546
1575
|
}
|
|
1547
1576
|
}
|
|
1548
1577
|
|
|
1578
|
+
/**
|
|
1579
|
+
* When a child hop is recorded locally, persist a synthetic inbound-parent stub so
|
|
1580
|
+
* Hops does not show "Missing entry hop" for the ALS gateway id.
|
|
1581
|
+
*/
|
|
1582
|
+
private async ensureInboundParentStubForChild(
|
|
1583
|
+
parentRequestId: string | null | undefined,
|
|
1584
|
+
config: unknown
|
|
1585
|
+
): Promise<void> {
|
|
1586
|
+
const activeInbound = getActiveInboundRequest();
|
|
1587
|
+
const hop =
|
|
1588
|
+
readOutboundParentHopFromConfig(config) ??
|
|
1589
|
+
(activeInbound ? { method: activeInbound.method, url: activeInbound.url } : undefined);
|
|
1590
|
+
|
|
1591
|
+
try {
|
|
1592
|
+
await ensureLocalInboundParentStubSaved({
|
|
1593
|
+
parentRequestId,
|
|
1594
|
+
hop,
|
|
1595
|
+
parentExists: (id) => {
|
|
1596
|
+
if (!fs || !path || this.databaseProvider) {
|
|
1597
|
+
return false;
|
|
1598
|
+
}
|
|
1599
|
+
const currentScenario = getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
1600
|
+
const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, currentScenario);
|
|
1601
|
+
return fs.existsSync(path.join(scenarioPath, inboundParentStubFilename(id)));
|
|
1602
|
+
},
|
|
1603
|
+
save: async (row) => {
|
|
1604
|
+
if (this.databaseProvider) {
|
|
1605
|
+
await this.databaseProvider.save(row.mock);
|
|
1606
|
+
return;
|
|
1607
|
+
}
|
|
1608
|
+
if (!fs || !path) {
|
|
1609
|
+
return;
|
|
1610
|
+
}
|
|
1611
|
+
const currentScenario = getCurrentScenario(this.config.mockDataPath, this.config.clientId);
|
|
1612
|
+
const scenarioPath = getScenarioFolderPath(this.config.mockDataPath, currentScenario);
|
|
1613
|
+
ensureScenarioFolder(this.config.mockDataPath, currentScenario);
|
|
1614
|
+
const filePath = path.join(scenarioPath, row.filename);
|
|
1615
|
+
if (fs.existsSync(filePath)) {
|
|
1616
|
+
return;
|
|
1617
|
+
}
|
|
1618
|
+
fs.writeFileSync(filePath, JSON.stringify(row.mock, null, 2));
|
|
1619
|
+
logger.info(
|
|
1620
|
+
`[Mockifyer-Fetch] Saved inbound parent stub: ${currentScenario}/${row.filename}`
|
|
1621
|
+
);
|
|
1622
|
+
},
|
|
1623
|
+
});
|
|
1624
|
+
} catch (error) {
|
|
1625
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1626
|
+
logger.warn(`[Mockifyer-Fetch] Failed to save inbound parent stub: ${message}`);
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1549
1630
|
private async persistMatchedMockAfterLiveCapture(
|
|
1550
1631
|
cachedMock: CachedMockData,
|
|
1551
1632
|
capturedResponse: StoredResponse,
|
|
@@ -1774,6 +1855,74 @@ class MockifyerClass {
|
|
|
1774
1855
|
return this.config.clientId;
|
|
1775
1856
|
}
|
|
1776
1857
|
|
|
1858
|
+
/**
|
|
1859
|
+
* Turn record mode on/off at runtime (dev menus, tests).
|
|
1860
|
+
* Also updates `proxy.recordOnMiss` when a dashboard proxy is configured so
|
|
1861
|
+
* Redis/proxy recording follows the same switch as local hybrid saves.
|
|
1862
|
+
*
|
|
1863
|
+
* When enabling: flips existing allowlist `recordResponses` to true and new
|
|
1864
|
+
* discoveries enable recording. When disabled, allowlist discovery stops
|
|
1865
|
+
* persisting new keys (so browsing does not poison the rules file).
|
|
1866
|
+
*/
|
|
1867
|
+
setRecordMode(enabled: boolean): void {
|
|
1868
|
+
const next = Boolean(enabled);
|
|
1869
|
+
this.config.recordMode = next;
|
|
1870
|
+
if (next) {
|
|
1871
|
+
// Recording needs live upstream calls; fail-on-miss conflicts with that.
|
|
1872
|
+
this.config.failOnMissingMock = false;
|
|
1873
|
+
this.domainPathRules.enableRecordResponsesForAllRules();
|
|
1874
|
+
}
|
|
1875
|
+
if (this.config.proxy?.baseUrl) {
|
|
1876
|
+
this.config.proxy = {
|
|
1877
|
+
...this.config.proxy,
|
|
1878
|
+
recordOnMiss: next,
|
|
1879
|
+
};
|
|
1880
|
+
const client = this.httpClient as FetchHTTPClient & {
|
|
1881
|
+
setProxyRecordOnMiss?: (value: boolean | undefined) => void;
|
|
1882
|
+
};
|
|
1883
|
+
client.setProxyRecordOnMiss?.(next);
|
|
1884
|
+
}
|
|
1885
|
+
logger.info(`[Mockifyer-Fetch] recordMode set to: ${next}`);
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
/** Whether newly unmatched requests can be recorded (local or proxy record-on-miss). */
|
|
1889
|
+
isRecordMode(): boolean {
|
|
1890
|
+
return this.config.recordMode === true;
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
/**
|
|
1894
|
+
* Whether new recordings store full response bodies (true) or request-only stubs (false, default).
|
|
1895
|
+
* Matches dashboard proxy `recordResponses` / env `MOCKIFYER_RECORD_RESPONSES`.
|
|
1896
|
+
*/
|
|
1897
|
+
setRecordResponses(enabled: boolean): void {
|
|
1898
|
+
const next = Boolean(enabled);
|
|
1899
|
+
this.recordResponsesOverride = next;
|
|
1900
|
+
this.config.recordResponses = next;
|
|
1901
|
+
if (this.config.proxy) {
|
|
1902
|
+
this.config.proxy = {
|
|
1903
|
+
...this.config.proxy,
|
|
1904
|
+
recordResponses: next,
|
|
1905
|
+
};
|
|
1906
|
+
}
|
|
1907
|
+
const client = this.httpClient as FetchHTTPClient & {
|
|
1908
|
+
setProxyRecordResponses?: (value: boolean) => void;
|
|
1909
|
+
};
|
|
1910
|
+
client.setProxyRecordResponses?.(next);
|
|
1911
|
+
logger.info(`[Mockifyer-Fetch] recordResponses (store bodies) set to: ${next}`);
|
|
1912
|
+
}
|
|
1913
|
+
|
|
1914
|
+
/** True when new recordings include response bodies (not request-only stubs). */
|
|
1915
|
+
isRecordResponses(): boolean {
|
|
1916
|
+
if (this.config.proxy?.baseUrl) {
|
|
1917
|
+
return resolveRecordResponses(
|
|
1918
|
+
this.recordResponsesOverride ?? this.config.proxy.recordResponses
|
|
1919
|
+
);
|
|
1920
|
+
}
|
|
1921
|
+
return resolveLocalRecordResponses(
|
|
1922
|
+
this.recordResponsesOverride ?? this.config.recordResponses
|
|
1923
|
+
);
|
|
1924
|
+
}
|
|
1925
|
+
|
|
1777
1926
|
/**
|
|
1778
1927
|
* Enable Mockifyer at runtime. All subsequent requests will go through Mockifyer
|
|
1779
1928
|
* (mock lookup, recording, dashboard/Redis proxy, etc.).
|
|
@@ -1816,6 +1965,9 @@ class MockifyerClass {
|
|
|
1816
1965
|
|
|
1817
1966
|
async reloadMockData(syncFromProject: boolean = true): Promise<void> {
|
|
1818
1967
|
await this.databaseProviderInitPromise;
|
|
1968
|
+
// `$pool` fixtures are cached write-once for RN (no Node fs). Clear so a reload
|
|
1969
|
+
// picks up updated pool response bodies from the provider / Metro sync.
|
|
1970
|
+
this.poolResponseCache.clear();
|
|
1819
1971
|
// If provider has a reload method, use it (for ExpoFileSystemProvider with caching)
|
|
1820
1972
|
// For HybridProvider, this will also sync files from project folder to device
|
|
1821
1973
|
if (this.databaseProvider && typeof (this.databaseProvider as any).reload === 'function') {
|
|
@@ -1856,6 +2008,10 @@ export interface MockifyerInstance extends HTTPClient {
|
|
|
1856
2008
|
clearAllMocks: () => Promise<void>;
|
|
1857
2009
|
setClientId: (lane: string) => void;
|
|
1858
2010
|
getClientId: () => string | undefined;
|
|
2011
|
+
setRecordMode: (enabled: boolean) => void;
|
|
2012
|
+
isRecordMode: () => boolean;
|
|
2013
|
+
setRecordResponses: (enabled: boolean) => void;
|
|
2014
|
+
isRecordResponses: () => boolean;
|
|
1859
2015
|
enableMockifyer: () => void;
|
|
1860
2016
|
disableMockifyer: () => void;
|
|
1861
2017
|
isMockifyerEnabled: () => boolean;
|
|
@@ -1923,10 +2079,15 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1923
2079
|
const originalFetchForPatched = (global as any).__mockifyer_original_fetch || originalFetch;
|
|
1924
2080
|
|
|
1925
2081
|
global.fetch = async function(input: string | Request | URL, init?: RequestInit): Promise<Response> {
|
|
2082
|
+
// Disabled means the real network: do not rebuild the call. The interceptor
|
|
2083
|
+
// bypass flag still runs FetchHTTPClient, which JSON.parses `{`/`[` bodies
|
|
2084
|
+
// (throwing on invalid JSON), JSON.stringifies FormData/Blob/URLSearchParams,
|
|
2085
|
+
// and drops credentials, abort signals, and Request-only method/headers/body.
|
|
2086
|
+
if (!mockifyerInstance.isMockifyerEnabled()) {
|
|
2087
|
+
return await originalFetchForPatched(input, init);
|
|
2088
|
+
}
|
|
2089
|
+
|
|
1926
2090
|
const url = typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url;
|
|
1927
|
-
const method = init?.method || 'GET';
|
|
1928
|
-
const headers = init?.headers || {};
|
|
1929
|
-
const body = init?.body;
|
|
1930
2091
|
|
|
1931
2092
|
// Skip Mockifyer sync endpoints, dashboard plumbing, and Resend API
|
|
1932
2093
|
if (
|
|
@@ -1936,17 +2097,20 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1936
2097
|
) {
|
|
1937
2098
|
return await originalFetchForPatched(input, init);
|
|
1938
2099
|
}
|
|
2100
|
+
|
|
2101
|
+
const resolved = await resolvePatchedFetchRequest(input, init);
|
|
2102
|
+
const method = resolved.method;
|
|
1939
2103
|
|
|
1940
|
-
const simpleRequestKey = `${method}:${url}`;
|
|
2104
|
+
const simpleRequestKey = `${method}:${resolved.url}`;
|
|
1941
2105
|
const isProcessing = (mockifyerInstance as any).processingRequests?.has(simpleRequestKey);
|
|
1942
2106
|
if (isProcessing) {
|
|
1943
2107
|
return await originalFetchForPatched(input, init);
|
|
1944
2108
|
}
|
|
1945
2109
|
|
|
1946
2110
|
let params: Record<string, string> | undefined = undefined;
|
|
1947
|
-
let baseUrl = url;
|
|
2111
|
+
let baseUrl = resolved.url;
|
|
1948
2112
|
try {
|
|
1949
|
-
const urlObj = new URL(url);
|
|
2113
|
+
const urlObj = new URL(resolved.url);
|
|
1950
2114
|
if (urlObj.search) {
|
|
1951
2115
|
params = {};
|
|
1952
2116
|
urlObj.searchParams.forEach((value, key) => {
|
|
@@ -1959,26 +2123,13 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
1959
2123
|
// URL parsing failed, use URL as-is
|
|
1960
2124
|
}
|
|
1961
2125
|
|
|
1962
|
-
let headersObj: Record<string, string> = {};
|
|
1963
|
-
if (headers instanceof Headers) {
|
|
1964
|
-
headers.forEach((value, key) => {
|
|
1965
|
-
headersObj[key] = value;
|
|
1966
|
-
});
|
|
1967
|
-
} else if (Array.isArray(headers)) {
|
|
1968
|
-
headers.forEach(([key, value]) => {
|
|
1969
|
-
headersObj[key] = value;
|
|
1970
|
-
});
|
|
1971
|
-
} else {
|
|
1972
|
-
headersObj = { ...(headers as Record<string, string>) };
|
|
1973
|
-
}
|
|
1974
|
-
|
|
1975
2126
|
try {
|
|
1976
2127
|
const requestConfig = {
|
|
1977
2128
|
url: baseUrl,
|
|
1978
2129
|
method: method as any,
|
|
1979
|
-
headers:
|
|
2130
|
+
headers: resolved.headers,
|
|
1980
2131
|
params: params,
|
|
1981
|
-
data:
|
|
2132
|
+
data: resolved.body
|
|
1982
2133
|
};
|
|
1983
2134
|
|
|
1984
2135
|
const response = await httpClient.request(requestConfig);
|
|
@@ -2033,6 +2184,10 @@ export function setupMockifyer(config: MockifyerConfig): MockifyerInstance {
|
|
|
2033
2184
|
extendedClient.clearAllMocks = () => mockifyer.clearAllMocks();
|
|
2034
2185
|
extendedClient.setClientId = (lane: string) => mockifyer.setClientId(lane);
|
|
2035
2186
|
extendedClient.getClientId = () => mockifyer.getClientId();
|
|
2187
|
+
extendedClient.setRecordMode = (enabled: boolean) => mockifyer.setRecordMode(enabled);
|
|
2188
|
+
extendedClient.isRecordMode = () => mockifyer.isRecordMode();
|
|
2189
|
+
extendedClient.setRecordResponses = (enabled: boolean) => mockifyer.setRecordResponses(enabled);
|
|
2190
|
+
extendedClient.isRecordResponses = () => mockifyer.isRecordResponses();
|
|
2036
2191
|
extendedClient.enableMockifyer = () => mockifyer.enableMockifyer();
|
|
2037
2192
|
extendedClient.disableMockifyer = () => mockifyer.disableMockifyer();
|
|
2038
2193
|
extendedClient.isMockifyerEnabled = () => mockifyer.isMockifyerEnabled();
|
|
@@ -419,25 +419,110 @@ function getMockFilePathLocal(
|
|
|
419
419
|
}
|
|
420
420
|
|
|
421
421
|
/**
|
|
422
|
-
*
|
|
422
|
+
* Scenario folder names the dashboard accepts (one path segment).
|
|
423
|
+
* `pool` is the fixture-pool directory and is not a scenario.
|
|
424
|
+
*/
|
|
425
|
+
const SAFE_SCENARIO_NAME = /^[a-zA-Z0-9_-]+$/;
|
|
426
|
+
const FIXTURE_POOL_DIR_NAME = "pool";
|
|
427
|
+
|
|
428
|
+
/** True when `candidate` is `root` or a file/directory inside it. */
|
|
429
|
+
function isInsideDirectory(root: string, candidate: string): boolean {
|
|
430
|
+
const rootResolved = path.resolve(root);
|
|
431
|
+
const target = path.resolve(candidate);
|
|
432
|
+
const prefix = rootResolved.endsWith(path.sep)
|
|
433
|
+
? rootResolved
|
|
434
|
+
: rootResolved + path.sep;
|
|
435
|
+
return target === rootResolved || target.startsWith(prefix);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* Accept a scenario name that can be used as a single directory under mock-data.
|
|
440
|
+
* Rejects traversal (`..`, slashes), absolute paths, and the reserved `pool` directory.
|
|
441
|
+
*/
|
|
442
|
+
function sanitizeScenarioName(raw: unknown): string | null {
|
|
443
|
+
if (typeof raw !== "string") {
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
const trimmed = raw.trim();
|
|
447
|
+
if (
|
|
448
|
+
!trimmed ||
|
|
449
|
+
trimmed === FIXTURE_POOL_DIR_NAME ||
|
|
450
|
+
!SAFE_SCENARIO_NAME.test(trimmed)
|
|
451
|
+
) {
|
|
452
|
+
return null;
|
|
453
|
+
}
|
|
454
|
+
return trimmed;
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** Absolute scenario directory, or null when `scenario` would escape mock-data. */
|
|
458
|
+
function resolveScenarioDirectory(
|
|
459
|
+
mockDataPath: string,
|
|
460
|
+
scenario: string,
|
|
461
|
+
): string | null {
|
|
462
|
+
const name = sanitizeScenarioName(scenario);
|
|
463
|
+
if (!name) {
|
|
464
|
+
return null;
|
|
465
|
+
}
|
|
466
|
+
const dir = path.resolve(mockDataPath, name);
|
|
467
|
+
if (!isInsideDirectory(mockDataPath, dir)) {
|
|
468
|
+
return null;
|
|
469
|
+
}
|
|
470
|
+
return dir;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/**
|
|
474
|
+
* Relative `.json` path under a scenario folder (for example `redis/<hash>.json`).
|
|
475
|
+
* Rejects absolute paths and `.` / `..` segments.
|
|
476
|
+
*/
|
|
477
|
+
function sanitizeMockRelativePath(raw: string): string | null {
|
|
478
|
+
const normalized = raw.trim().replace(/\\/g, "/").replace(/^\/+/, "");
|
|
479
|
+
if (!normalized.endsWith(".json") || normalized.includes("\0")) {
|
|
480
|
+
return null;
|
|
481
|
+
}
|
|
482
|
+
const segments = normalized.split("/");
|
|
483
|
+
if (segments.some((seg) => seg.length === 0 || seg === "." || seg === "..")) {
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
return normalized;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** Absolute mock file path inside `scenarioDir`, or null when the relative path escapes. */
|
|
490
|
+
function resolveMockFilePath(
|
|
491
|
+
scenarioDir: string,
|
|
492
|
+
relativePath: string,
|
|
493
|
+
): string | null {
|
|
494
|
+
const rel = sanitizeMockRelativePath(relativePath);
|
|
495
|
+
if (!rel) {
|
|
496
|
+
return null;
|
|
497
|
+
}
|
|
498
|
+
const filePath = path.resolve(scenarioDir, rel);
|
|
499
|
+
if (!isInsideDirectory(scenarioDir, filePath) || filePath === path.resolve(scenarioDir)) {
|
|
500
|
+
return null;
|
|
501
|
+
}
|
|
502
|
+
return filePath;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* Get current scenario from env or scenario-config.json.
|
|
507
|
+
* Unsafe names (path traversal, reserved `pool`) are ignored.
|
|
423
508
|
*/
|
|
424
509
|
function getCurrentScenario(mockDataPath: string): string {
|
|
425
|
-
|
|
426
|
-
if (
|
|
427
|
-
return
|
|
510
|
+
const fromEnv = sanitizeScenarioName(process.env.MOCKIFYER_SCENARIO);
|
|
511
|
+
if (fromEnv) {
|
|
512
|
+
return fromEnv;
|
|
428
513
|
}
|
|
429
514
|
|
|
430
|
-
// Try to load from scenario-config.json
|
|
431
515
|
try {
|
|
432
516
|
const configPath = path.join(mockDataPath, "scenario-config.json");
|
|
433
517
|
if (fs.existsSync(configPath)) {
|
|
434
518
|
const fileContent = fs.readFileSync(configPath, "utf-8");
|
|
435
519
|
const config = JSON.parse(fileContent);
|
|
436
|
-
|
|
437
|
-
|
|
520
|
+
const fromFile = sanitizeScenarioName(config.currentScenario);
|
|
521
|
+
if (fromFile) {
|
|
522
|
+
return fromFile;
|
|
438
523
|
}
|
|
439
524
|
}
|
|
440
|
-
} catch
|
|
525
|
+
} catch {
|
|
441
526
|
// Silently fail - file might not exist or be invalid
|
|
442
527
|
}
|
|
443
528
|
|
|
@@ -445,11 +530,15 @@ function getCurrentScenario(mockDataPath: string): string {
|
|
|
445
530
|
}
|
|
446
531
|
|
|
447
532
|
/**
|
|
448
|
-
*
|
|
533
|
+
* Scenario folder under mock-data. Throws when `scenario` is not a safe single segment
|
|
534
|
+
* so a poisoned name cannot mkdir outside the mock-data tree.
|
|
449
535
|
*/
|
|
450
536
|
function getScenarioPath(scenario: string, mockDataPath: string): string {
|
|
451
|
-
|
|
452
|
-
|
|
537
|
+
const dir = resolveScenarioDirectory(mockDataPath, scenario);
|
|
538
|
+
if (!dir) {
|
|
539
|
+
throw new Error(`Invalid scenario name: ${scenario}`);
|
|
540
|
+
}
|
|
541
|
+
return dir;
|
|
453
542
|
}
|
|
454
543
|
|
|
455
544
|
/**
|
|
@@ -731,17 +820,22 @@ function saveProxyMirrorMockToProject(
|
|
|
731
820
|
error: "Mock data contains nested Mockifyer sync requests",
|
|
732
821
|
};
|
|
733
822
|
}
|
|
734
|
-
const id = scenarioName
|
|
823
|
+
const id = sanitizeScenarioName(scenarioName);
|
|
735
824
|
if (!id) {
|
|
736
|
-
return { success: false, error: "scenarioName
|
|
825
|
+
return { success: false, error: "Invalid scenarioName" };
|
|
737
826
|
}
|
|
738
|
-
const normalized = relativePath
|
|
827
|
+
const normalized = sanitizeMockRelativePath(relativePath);
|
|
739
828
|
if (!normalized) {
|
|
740
|
-
return { success: false, error: "relativePath
|
|
829
|
+
return { success: false, error: "Invalid relativePath" };
|
|
830
|
+
}
|
|
831
|
+
const scenarioPath = resolveScenarioDirectory(mockDataPath, id);
|
|
832
|
+
const filePath = scenarioPath
|
|
833
|
+
? resolveMockFilePath(scenarioPath, normalized)
|
|
834
|
+
: null;
|
|
835
|
+
if (!scenarioPath || !filePath) {
|
|
836
|
+
return { success: false, error: "Invalid relativePath" };
|
|
741
837
|
}
|
|
742
|
-
const scenarioPath = getScenarioPath(id, mockDataPath);
|
|
743
838
|
fs.mkdirSync(scenarioPath, { recursive: true });
|
|
744
|
-
const filePath = path.join(scenarioPath, normalized);
|
|
745
839
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
746
840
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
747
841
|
if (testConfig) {
|
|
@@ -1397,6 +1491,23 @@ export function bufferAtlasBodySpill(
|
|
|
1397
1491
|
return { success: true, relativePath: buffered };
|
|
1398
1492
|
}
|
|
1399
1493
|
|
|
1494
|
+
/**
|
|
1495
|
+
* Write hop bodies for an Atlas HTML render.
|
|
1496
|
+
*
|
|
1497
|
+
* Device uploads sit in the Metro spill buffer and are often omitted from the
|
|
1498
|
+
* render POST (`bodySpills` is capped at 2MB, so a max-size body never fits).
|
|
1499
|
+
* Flush that buffer before writing the payload. Buffering the payload first
|
|
1500
|
+
* evicts older spills once the in-memory cap is hit, and those files are then
|
|
1501
|
+
* missing from disk.
|
|
1502
|
+
*/
|
|
1503
|
+
export function persistAtlasRenderBodySpills(
|
|
1504
|
+
outDir: string,
|
|
1505
|
+
bodySpills: Record<string, string> | undefined,
|
|
1506
|
+
): number {
|
|
1507
|
+
const flushed = flushNetworkBodySpillsToDir(outDir);
|
|
1508
|
+
return flushed + writeNetworkBodySpillMap(outDir, bodySpills);
|
|
1509
|
+
}
|
|
1510
|
+
|
|
1400
1511
|
const ATLAS_HTML_CONTENT_TYPES: Record<string, string> = {
|
|
1401
1512
|
".html": "text/html; charset=utf-8",
|
|
1402
1513
|
".htm": "text/html; charset=utf-8",
|
|
@@ -2053,8 +2164,16 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2053
2164
|
const scenarioParam = params.get("scenario");
|
|
2054
2165
|
const scenarioName =
|
|
2055
2166
|
scenarioParam && scenarioParam.trim() !== ""
|
|
2056
|
-
? scenarioParam
|
|
2167
|
+
? sanitizeScenarioName(scenarioParam)
|
|
2057
2168
|
: getCurrentScenario(mockDataPath);
|
|
2169
|
+
if (!scenarioName) {
|
|
2170
|
+
res.statusCode = 400;
|
|
2171
|
+
res.setHeader("Content-Type", "application/json");
|
|
2172
|
+
res.end(
|
|
2173
|
+
JSON.stringify({ success: false, error: "Invalid scenario name" }),
|
|
2174
|
+
);
|
|
2175
|
+
return;
|
|
2176
|
+
}
|
|
2058
2177
|
const rules = readDomainPathRulesFile(mockDataPath, scenarioName);
|
|
2059
2178
|
res.setHeader("Content-Type", "application/json");
|
|
2060
2179
|
res.end(JSON.stringify({ success: true, scenario: scenarioName, rules }));
|
|
@@ -2073,11 +2192,47 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2073
2192
|
scenario?: string;
|
|
2074
2193
|
upserts?: DomainPathRulesMap;
|
|
2075
2194
|
rules?: DomainPathRulesMap;
|
|
2195
|
+
/** When true, replace the scenario file with `rules` (enable-record migrations). */
|
|
2196
|
+
replace?: boolean;
|
|
2076
2197
|
};
|
|
2077
2198
|
const scenarioName =
|
|
2078
2199
|
typeof parsed.scenario === "string" && parsed.scenario.trim() !== ""
|
|
2079
|
-
? parsed.scenario
|
|
2200
|
+
? sanitizeScenarioName(parsed.scenario)
|
|
2080
2201
|
: getCurrentScenario(mockDataPath);
|
|
2202
|
+
if (!scenarioName) {
|
|
2203
|
+
res.statusCode = 400;
|
|
2204
|
+
res.setHeader("Content-Type", "application/json");
|
|
2205
|
+
res.end(
|
|
2206
|
+
JSON.stringify({ success: false, error: "Invalid scenario name" }),
|
|
2207
|
+
);
|
|
2208
|
+
return;
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
if (parsed.replace === true) {
|
|
2212
|
+
const updates = parseDomainPathRules(parsed.rules ?? {});
|
|
2213
|
+
// Re-read to pick up concurrent new keys, then apply recordResponses updates.
|
|
2214
|
+
const existing = readDomainPathRulesFile(mockDataPath, scenarioName);
|
|
2215
|
+
const merged: DomainPathRulesMap = { ...updates };
|
|
2216
|
+
// Add any new keys that were discovered concurrently but preserve the recordResponses updates.
|
|
2217
|
+
for (const [key, rule] of Object.entries(existing)) {
|
|
2218
|
+
if (!merged[key]) {
|
|
2219
|
+
merged[key] = { ...rule };
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
writeDomainPathRulesFile(mockDataPath, scenarioName, merged);
|
|
2223
|
+
res.setHeader("Content-Type", "application/json");
|
|
2224
|
+
res.end(
|
|
2225
|
+
JSON.stringify({
|
|
2226
|
+
success: true,
|
|
2227
|
+
changed: true,
|
|
2228
|
+
replaced: true,
|
|
2229
|
+
scenario: scenarioName,
|
|
2230
|
+
rules: merged,
|
|
2231
|
+
}),
|
|
2232
|
+
);
|
|
2233
|
+
return;
|
|
2234
|
+
}
|
|
2235
|
+
|
|
2081
2236
|
const upserts = parseDomainPathRules(
|
|
2082
2237
|
parsed.upserts ?? parsed.rules ?? {},
|
|
2083
2238
|
);
|
|
@@ -2447,7 +2602,10 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2447
2602
|
}
|
|
2448
2603
|
setAtlasDocMap(doc);
|
|
2449
2604
|
setAtlasDocHtmlOutputPath(outDir);
|
|
2450
|
-
const spillWritten =
|
|
2605
|
+
const spillWritten = persistAtlasRenderBodySpills(
|
|
2606
|
+
outDir,
|
|
2607
|
+
parsed.bodySpills,
|
|
2608
|
+
);
|
|
2451
2609
|
const events = Array.isArray(parsed.events) ? parsed.events : [];
|
|
2452
2610
|
const written = writeAtlasDocHtml(outDir, doc, events);
|
|
2453
2611
|
const relativeFromRoot = path
|
|
@@ -2654,10 +2812,13 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2654
2812
|
try {
|
|
2655
2813
|
// Check environment variable first (highest priority)
|
|
2656
2814
|
if (process.env.MOCKIFYER_SCENARIO) {
|
|
2815
|
+
const fromEnv =
|
|
2816
|
+
sanitizeScenarioName(process.env.MOCKIFYER_SCENARIO) ||
|
|
2817
|
+
DEFAULT_SCENARIO;
|
|
2657
2818
|
logger.debug(
|
|
2658
|
-
`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${
|
|
2819
|
+
`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${fromEnv}`,
|
|
2659
2820
|
);
|
|
2660
|
-
writeScenarioResponse(
|
|
2821
|
+
writeScenarioResponse(fromEnv);
|
|
2661
2822
|
return;
|
|
2662
2823
|
}
|
|
2663
2824
|
|
|
@@ -2674,7 +2835,8 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2674
2835
|
const fileContent = fs.readFileSync(configPath, "utf-8");
|
|
2675
2836
|
logger.debug(`[MetroSyncMiddleware] File content: ${fileContent}`);
|
|
2676
2837
|
const config = JSON.parse(fileContent);
|
|
2677
|
-
const scenario =
|
|
2838
|
+
const scenario =
|
|
2839
|
+
sanitizeScenarioName(config.currentScenario) || DEFAULT_SCENARIO;
|
|
2678
2840
|
logger.debug(
|
|
2679
2841
|
`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`,
|
|
2680
2842
|
);
|
|
@@ -2708,6 +2870,20 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2708
2870
|
req.on("end", () => {
|
|
2709
2871
|
try {
|
|
2710
2872
|
const config = JSON.parse(body);
|
|
2873
|
+
if (
|
|
2874
|
+
config &&
|
|
2875
|
+
typeof config === "object" &&
|
|
2876
|
+
typeof config.currentScenario === "string" &&
|
|
2877
|
+
config.currentScenario.trim() !== "" &&
|
|
2878
|
+
!sanitizeScenarioName(config.currentScenario)
|
|
2879
|
+
) {
|
|
2880
|
+
res.statusCode = 400;
|
|
2881
|
+
res.setHeader("Content-Type", "application/json");
|
|
2882
|
+
res.end(
|
|
2883
|
+
JSON.stringify({ success: false, error: "Invalid scenario name" }),
|
|
2884
|
+
);
|
|
2885
|
+
return;
|
|
2886
|
+
}
|
|
2711
2887
|
const configPath = path.join(mockDataPath, "scenario-config.json");
|
|
2712
2888
|
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
|
|
2713
2889
|
res.setHeader("Content-Type", "application/json");
|
package/src/react-native.ts
CHANGED
|
@@ -36,6 +36,10 @@ export interface MockifyerInstance extends HTTPClient {
|
|
|
36
36
|
clearAllMocks: () => Promise<void>;
|
|
37
37
|
setClientId: (lane: string) => void;
|
|
38
38
|
getClientId: () => string | undefined;
|
|
39
|
+
setRecordMode: (enabled: boolean) => void;
|
|
40
|
+
isRecordMode: () => boolean;
|
|
41
|
+
setRecordResponses: (enabled: boolean) => void;
|
|
42
|
+
isRecordResponses: () => boolean;
|
|
39
43
|
enableMockifyer: () => void;
|
|
40
44
|
disableMockifyer: () => void;
|
|
41
45
|
isMockifyerEnabled: () => boolean;
|