@sgedda/mockifyer-fetch 1.8.98 → 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/src/index.ts CHANGED
@@ -36,7 +36,7 @@ import {
36
36
  TestGenerationOptions,
37
37
  checkRequestLimit,
38
38
  prepareMockResponseBody,
39
- getCurrentDate,
39
+ createServeTimeClock,
40
40
  createServeTimePoolResponseLoader,
41
41
  collectPoolRefIds,
42
42
  arePoolRefsEnabled,
@@ -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 {
@@ -309,7 +321,7 @@ class MockifyerClass {
309
321
  private prepareStoredResponseBody(mockData: MockData, filename?: string, scenarioPath?: string): unknown {
310
322
  const joinPath =
311
323
  path && typeof path.join === 'function' ? path.join.bind(path) : null;
312
- return prepareMockResponseBody(mockData, getCurrentDate, {
324
+ return prepareMockResponseBody(mockData, createServeTimeClock(this.config), {
313
325
  loadPoolResponse: createServeTimePoolResponseLoader({
314
326
  mockDataPath: this.config.mockDataPath,
315
327
  nodeFs: isUsableNodeLikePoolFs(fs) ? fs : null,
@@ -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({ config: this.config });
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) {
@@ -1198,7 +1213,7 @@ class MockifyerClass {
1198
1213
  const clientResponse = buildClientResponseFromLiveCapture(
1199
1214
  matchedMock.mockData,
1200
1215
  capturedResponse,
1201
- getCurrentDate,
1216
+ createServeTimeClock(this.config),
1202
1217
  { filename: matchedMock.filename, scenarioPath: liveScenarioPath }
1203
1218
  );
1204
1219
  response.data = clientResponse.data;
@@ -1467,30 +1482,42 @@ class MockifyerClass {
1467
1482
  correlation
1468
1483
  );
1469
1484
 
1470
- const mockData: MockData = {
1471
- request: {
1472
- method: response.config?.method?.toUpperCase() || 'GET',
1473
- url: response.config?.url || '',
1474
- headers: this.anonymizeHeaders(response.config?.headers || {}),
1475
- data: response.config?.data,
1476
- queryParams: normalizedParamsForSave,
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
- timestamp: new Date().toISOString(),
1484
- duration,
1485
- sessionId:
1486
- saveDecision.action === 'overwrite' && existingMock?.mockData.sessionId
1487
- ? existingMock.mockData.sessionId
1488
- : this.currentSessionId,
1489
- requestId: hopIds.requestId,
1490
- parentRequestId: hopIds.parentRequestId,
1491
- parentRequestIds: hopIds.parentRequestIds,
1492
- ...(newRecordingUsesAlwaysUseRealApi() ? { alwaysUseRealApi: true as const } : {}),
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: headersObj,
2130
+ headers: resolved.headers,
1980
2131
  params: params,
1981
- data: body ? (typeof body === 'string' ? (body.startsWith('{') || body.startsWith('[') ? JSON.parse(body) : body) : body) : undefined
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();