@sgedda/mockifyer-fetch 1.8.26 → 1.8.33

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.
@@ -290,6 +290,44 @@ function saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig
290
290
  return { success: false, error: error.message };
291
291
  }
292
292
  }
293
+ /**
294
+ * Save a proxy-mirrored mock to an explicit scenario subpath (e.g. `redis/<hash>.json`).
295
+ * Used when the dashboard records to Redis and the RN app POSTs an envelope to `/mockifyer-save`.
296
+ */
297
+ function saveProxyMirrorMockToProject(mockData, projectRoot, mockDataPath, scenarioName, relativePath, testConfig) {
298
+ try {
299
+ const url = mockData?.request?.url || '';
300
+ if (url.includes('/mockifyer-save') || url.includes('/mockifyer-clear') || url.includes('/mockifyer-sync')) {
301
+ console.warn(`[MockSync] ⚠️ Rejecting save - Mockifyer sync endpoint detected: ${url}`);
302
+ return { success: false, error: 'Cannot save Mockifyer sync endpoint requests' };
303
+ }
304
+ const mockDataStr = JSON.stringify(mockData);
305
+ if (mockDataStr.includes('/mockifyer-save') || mockDataStr.includes('/mockifyer-clear')) {
306
+ return { success: false, error: 'Mock data contains nested Mockifyer sync requests' };
307
+ }
308
+ const id = scenarioName.trim();
309
+ if (!id) {
310
+ return { success: false, error: 'scenarioName is required' };
311
+ }
312
+ const normalized = relativePath.replace(/\\/g, '/').replace(/^\//, '');
313
+ if (!normalized) {
314
+ return { success: false, error: 'relativePath is required' };
315
+ }
316
+ const scenarioPath = getScenarioPath(id, mockDataPath);
317
+ fs.mkdirSync(scenarioPath, { recursive: true });
318
+ const filePath = path.join(scenarioPath, normalized);
319
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
320
+ fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
321
+ if (testConfig) {
322
+ generateTestForMock(mockData, testConfig, projectRoot);
323
+ }
324
+ return { success: true, filename: normalized, scenario: id };
325
+ }
326
+ catch (error) {
327
+ console.error(`[MockSync] ❌ Error saving proxy mirror mock:`, error);
328
+ return { success: false, error: error.message };
329
+ }
330
+ }
293
331
  /**
294
332
  * Clear all mock files from project folder (current scenario)
295
333
  */
@@ -565,7 +603,19 @@ function createMockSyncMiddleware(options) {
565
603
  });
566
604
  req.on('end', () => {
567
605
  try {
568
- const mockData = JSON.parse(body);
606
+ const parsed = JSON.parse(body);
607
+ if (parsed &&
608
+ typeof parsed === 'object' &&
609
+ parsed.__mockifyerProxyMirror === true &&
610
+ parsed.mockData) {
611
+ const scenarioName = typeof parsed.scenarioName === 'string' ? parsed.scenarioName : '';
612
+ const relativePath = typeof parsed.relativePath === 'string' ? parsed.relativePath : '';
613
+ const result = saveProxyMirrorMockToProject(parsed.mockData, projectRoot, mockDataPath, scenarioName, relativePath, testConfig);
614
+ res.setHeader('Content-Type', 'application/json');
615
+ res.end(JSON.stringify(result));
616
+ return;
617
+ }
618
+ const mockData = parsed;
569
619
  const result = saveMockToProjectFolder(mockData, projectRoot, mockDataPath, testConfig);
570
620
  res.setHeader('Content-Type', 'application/json');
571
621
  res.end(JSON.stringify(result));
@@ -49,6 +49,16 @@ export interface ReactNativeMockifyerConfig {
49
49
  bundledDataPath?: string;
50
50
  /** Enable recording mode (development only) */
51
51
  recordMode?: boolean;
52
+ /**
53
+ * When true, reads `scenario` from `react-native-launch-arguments` (optional peer).
54
+ * Highest priority over MOCKIFYER_SCENARIO, config.scenarios, Metro scenario sync, and scenario-config.json.
55
+ */
56
+ useLaunchArgumentsScenario?: boolean;
57
+ /**
58
+ * Sets the same highest-priority scenario as {@link useLaunchArgumentsScenario} when you pass the value yourself
59
+ * (e.g. after reading launch args). Ignored if empty after trim.
60
+ */
61
+ defaultScenario?: string;
52
62
  /** Additional Mockifyer config options */
53
63
  config?: Partial<Parameters<typeof setupMockifyer>[0]>;
54
64
  /** Optional: route real network calls through a proxy service (e.g. mockifyer-dashboard in Redis mode) */
@@ -60,6 +70,15 @@ export interface ReactNativeMockifyerConfig {
60
70
  * Deprecated: prefer using `recordMode` when `proxyBaseUrl` is provided.
61
71
  */
62
72
  proxyRecordOnMiss?: boolean;
73
+ /**
74
+ * When false, dashboard proxy stores request-only stubs on cache miss (Responses: Off).
75
+ * Defaults to `false`. Env **`MOCKIFYER_RECORD_RESPONSES`** overrides when set.
76
+ */
77
+ proxyRecordResponses?: boolean;
78
+ /**
79
+ * When true, skip `GET /api/health` and always wire dashboard proxy (same as Node preset).
80
+ */
81
+ skipDashboardRedisHealthCheck?: boolean;
63
82
  /**
64
83
  * When true, read `clientId` from Maestro/native launch arguments (optional peer `react-native-launch-arguments`).
65
84
  * Prefer this over passing scenario from E2E if the dashboard/Redis should control scenario on the fly for that lane.
@@ -92,9 +111,25 @@ export interface ReactNativeMockifyerConfig {
92
111
  * mockDataPath: 'mock-data',
93
112
  * bundledDataPath: './assets/mock-data',
94
113
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
114
+ * useLaunchArgumentsScenario: true, // optional: scenario from react-native-launch-arguments (highest priority)
95
115
  * });
96
116
  * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
97
117
  * ```
98
118
  */
99
119
  export declare function setupMockifyerForReactNative(options: ReactNativeMockifyerConfig): Promise<SetupMockifyerForReactNativeResult>;
120
+ /** React Native options with an explicit dashboard alias (see {@link initMockifyerForReactNativeDashboard}). */
121
+ export interface InitMockifyerForReactNativeDashboardOptions extends ReactNativeMockifyerConfig {
122
+ /**
123
+ * mockifyer-dashboard origin — same role as {@link ReactNativeMockifyerConfig.proxyBaseUrl}.
124
+ * Useful when you prefer naming that matches the Node preset {@link initMockifyerForDashboardProxy}.
125
+ */
126
+ dashboardBaseUrl?: string;
127
+ }
128
+ /**
129
+ * Preset: point the app at **mockifyer-dashboard** for `/api/proxy` (typically **`--provider redis`**).
130
+ *
131
+ * Resolves URL in order: **`proxyBaseUrl`** → **`dashboardBaseUrl`** → **`MOCKIFYER_PROXY_URL`** env.
132
+ * Then delegates to {@link setupMockifyerForReactNative}. For bespoke wiring, call that helper directly.
133
+ */
134
+ export declare function initMockifyerForReactNativeDashboard(options: InitMockifyerForReactNativeDashboardOptions): Promise<SetupMockifyerForReactNativeResult>;
100
135
  export { tryGetClientIdFromLaunchArguments, MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY, getClientId, setClientId, registerMockifyerInstance, clearMockifyerClientIdRuntime, } from '@sgedda/mockifyer-core';
@@ -9,7 +9,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.clearMockifyerClientIdRuntime = exports.registerMockifyerInstance = exports.setClientId = exports.getClientId = exports.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY = exports.tryGetClientIdFromLaunchArguments = void 0;
10
10
  exports.isMockifyerReactNativeActive = isMockifyerReactNativeActive;
11
11
  exports.setupMockifyerForReactNative = setupMockifyerForReactNative;
12
- const join_proxy_dashboard_api_url_1 = require("./utils/join-proxy-dashboard-api-url");
12
+ exports.initMockifyerForReactNativeDashboard = initMockifyerForReactNativeDashboard;
13
+ const dashboard_redis_health_1 = require("./utils/dashboard-redis-health");
13
14
  const index_1 = require("./index");
14
15
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
15
16
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
@@ -19,26 +20,37 @@ const mockifyer_core_2 = require("@sgedda/mockifyer-core");
19
20
  function isMockifyerReactNativeActive(result) {
20
21
  return result.status === 'active';
21
22
  }
22
- // Lazy load bundled data (only used in production builds)
23
- let bundledMockData = null;
24
- async function canUseStrictRedisProxy(proxyBaseUrl) {
25
- if (!proxyBaseUrl)
26
- return false;
27
- try {
28
- const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
29
- const timeout = setTimeout(() => controller?.abort(), 800);
30
- const url = (0, join_proxy_dashboard_api_url_1.joinProxyDashboardApiUrl)(proxyBaseUrl, 'api/health');
31
- const res = await fetch(url, { signal: controller?.signal });
32
- clearTimeout(timeout);
33
- if (!res.ok)
34
- return false;
35
- const data = (await res.json());
36
- return data?.provider === 'redis' && data?.redisOk === true;
23
+ /**
24
+ * Apply scenario from launch arguments and/or defaultScenario (highest priority in getCurrentScenario).
25
+ */
26
+ function applyReactNativeScenarioOptions(options) {
27
+ let applied = false;
28
+ if (options.useLaunchArgumentsScenario) {
29
+ try {
30
+ // Optional dependency — install `react-native-launch-arguments` in the app when using this flag
31
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
32
+ const mod = require(/* webpackIgnore: true */ 'react-native-launch-arguments');
33
+ const LaunchArguments = mod.LaunchArguments;
34
+ const raw = LaunchArguments && typeof LaunchArguments.value === 'function' ? LaunchArguments.value() : undefined;
35
+ const scenario = raw?.scenario;
36
+ if (scenario !== undefined && scenario !== null && String(scenario).trim() !== '') {
37
+ (0, mockifyer_core_1.setScenarioLaunchOverride)(String(scenario).trim());
38
+ applied = true;
39
+ }
40
+ }
41
+ catch {
42
+ // Package not installed or native module unavailable
43
+ }
37
44
  }
38
- catch {
39
- return false;
45
+ if (!applied && options.defaultScenario !== undefined && options.defaultScenario !== null) {
46
+ const t = String(options.defaultScenario).trim();
47
+ if (t !== '') {
48
+ (0, mockifyer_core_1.setScenarioLaunchOverride)(t);
49
+ }
40
50
  }
41
51
  }
52
+ // Lazy load bundled data (only used in production builds)
53
+ let bundledMockData = null;
42
54
  /**
43
55
  * Load bundled mock data from a TypeScript/JavaScript module
44
56
  *
@@ -88,13 +100,15 @@ async function loadBundledMockData(bundledDataPath) {
88
100
  * mockDataPath: 'mock-data',
89
101
  * bundledDataPath: './assets/mock-data',
90
102
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
103
+ * useLaunchArgumentsScenario: true, // optional: scenario from react-native-launch-arguments (highest priority)
91
104
  * });
92
105
  * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
93
106
  * ```
94
107
  */
95
108
  async function setupMockifyerForReactNative(options) {
96
- const { isDev, mockDataPath = 'mock-data', bundledDataPath = './assets/mock-data', recordMode = false, config: userConfig = {}, proxyBaseUrl, proxyScenario, proxyRecordOnMiss, useLaunchArgumentsClientId = false, launchArgumentClientIdKey = mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY, runtimeMode: runtimeModeOption, } = options;
109
+ const { isDev, mockDataPath = 'mock-data', bundledDataPath = './assets/mock-data', recordMode = false, config: userConfig = {}, proxyBaseUrl, proxyScenario, proxyRecordOnMiss, proxyRecordResponses, skipDashboardRedisHealthCheck, useLaunchArgumentsClientId = false, launchArgumentClientIdKey = mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY, runtimeMode: runtimeModeOption, } = options;
97
110
  const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
111
+ const proxyShouldRecordResponses = (0, mockifyer_core_2.resolveRecordResponses)(proxyRecordResponses ?? userConfig.proxy?.recordResponses);
98
112
  const launchClientIdKey = launchArgumentClientIdKey ?? mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
99
113
  const clientIdFromLaunchArgs = (0, mockifyer_core_2.tryGetClientIdFromLaunchArguments)(launchClientIdKey);
100
114
  const shouldApplyLaunchClientId = useLaunchArgumentsClientId || Boolean(clientIdFromLaunchArgs);
@@ -111,9 +125,14 @@ async function setupMockifyerForReactNative(options) {
111
125
  }
112
126
  : {}),
113
127
  };
114
- const devInitHeadline = (strictProxy) => strictProxy
115
- ? 'React Native dev · dashboard Redis proxy'
116
- : 'React Native dev · hybrid (device + Metro)';
128
+ const devInitHeadline = (strictProxy, strictProxyOnlyFallback) => {
129
+ if (strictProxy)
130
+ return 'React Native dev · dashboard Redis proxy';
131
+ if (strictProxyOnlyFallback) {
132
+ return 'React Native dev · strict proxy-only (dashboard unhealthy — local recording disabled)';
133
+ }
134
+ return 'React Native dev · hybrid (device + Metro)';
135
+ };
117
136
  const isEnabled = resolvedRuntimeMode === 'on' ||
118
137
  (resolvedRuntimeMode === 'launch_client' && Boolean(clientIdFromLaunchArgs));
119
138
  if (!isEnabled) {
@@ -123,8 +142,20 @@ async function setupMockifyerForReactNative(options) {
123
142
  });
124
143
  return { status: 'not_activated', instance: null };
125
144
  }
145
+ applyReactNativeScenarioOptions(options);
126
146
  if (isDev === true) {
127
- const strictProxyEnabled = await canUseStrictRedisProxy(proxyBaseUrl);
147
+ const strictProxyEnabled = proxyBaseUrl
148
+ ? skipDashboardRedisHealthCheck === true ||
149
+ (await (0, dashboard_redis_health_1.canUseDashboardRedisProxy)(proxyBaseUrl))
150
+ : false;
151
+ const strictProxyOnlyFallback = Boolean(proxyBaseUrl?.trim()) &&
152
+ !strictProxyEnabled &&
153
+ (0, mockifyer_core_2.resolveStrictScenarioResolution)(mergedConfig);
154
+ if (strictProxyOnlyFallback) {
155
+ mockifyer_core_2.logger.warn(`[Mockifyer] Strict proxy-only: "${proxyBaseUrl}" did not report healthy Redis. ` +
156
+ 'Using memory provider without local recording. Start mockifyer-dashboard --provider redis ' +
157
+ 'or set skipDashboardRedisHealthCheck: true to force proxy.');
158
+ }
128
159
  // DEVELOPMENT MODE (React Native app running in dev)
129
160
  // Use Hybrid provider - saves to both device AND project folder simultaneously
130
161
  // Files are immediately available in project folder (no polling needed)
@@ -152,7 +183,7 @@ async function setupMockifyerForReactNative(options) {
152
183
  : baseDatabaseProvider;
153
184
  const instance = (0, index_1.setupMockifyer)({
154
185
  mockDataPath,
155
- databaseProvider: strictProxyEnabled
186
+ databaseProvider: strictProxyEnabled || strictProxyOnlyFallback
156
187
  ? {
157
188
  // Strict proxy source of truth: disable local mock lookup so all requests go through the dashboard proxy.
158
189
  type: 'memory',
@@ -161,15 +192,34 @@ async function setupMockifyerForReactNative(options) {
161
192
  recordMode,
162
193
  useGlobalFetch: true,
163
194
  proxy: strictProxyEnabled && proxyBaseUrl
164
- ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
195
+ ? {
196
+ baseUrl: proxyBaseUrl,
197
+ scenario: proxyScenario,
198
+ recordOnMiss: proxyShouldRecordOnMiss,
199
+ recordResponses: proxyShouldRecordResponses,
200
+ }
165
201
  : undefined,
202
+ ...(strictProxyEnabled
203
+ ? {
204
+ strictScenarioResolution: mergedConfig.strictScenarioResolution ?? true,
205
+ }
206
+ : {}),
166
207
  ...mergedConfig,
167
- initLog: { headline: mergedConfig.initLog?.headline ?? devInitHeadline(strictProxyEnabled) },
208
+ ...(strictProxyOnlyFallback
209
+ ? {
210
+ databaseProvider: { type: 'memory' },
211
+ intendedProxyBaseUrl: proxyBaseUrl.trim(),
212
+ }
213
+ : {}),
214
+ initLog: {
215
+ headline: mergedConfig.initLog?.headline ??
216
+ devInitHeadline(strictProxyEnabled, strictProxyOnlyFallback),
217
+ },
168
218
  });
169
- if (!strictProxyEnabled) {
219
+ if (!strictProxyEnabled && !strictProxyOnlyFallback) {
170
220
  mockifyer_core_2.logger.info(`[Mockifyer] Metro: http://localhost:${metroPort}/mockifyer-save · scenario: /mockifyer-scenario-config`);
171
221
  }
172
- if (!strictProxyEnabled) {
222
+ if (!strictProxyEnabled && !strictProxyOnlyFallback) {
173
223
  // Pull repo mock-data onto device once Metro + provider are ready (HybridProvider.reload)
174
224
  try {
175
225
  await instance.reloadMockData(true);
@@ -203,8 +253,18 @@ async function setupMockifyerForReactNative(options) {
203
253
  recordMode: false, // Can't record in production builds
204
254
  useGlobalFetch: true,
205
255
  proxy: proxyBaseUrl
206
- ? { baseUrl: proxyBaseUrl, scenario: proxyScenario, recordOnMiss: proxyShouldRecordOnMiss }
256
+ ? {
257
+ baseUrl: proxyBaseUrl,
258
+ scenario: proxyScenario,
259
+ recordOnMiss: proxyShouldRecordOnMiss,
260
+ recordResponses: proxyShouldRecordResponses,
261
+ }
207
262
  : undefined,
263
+ ...(proxyBaseUrl
264
+ ? {
265
+ strictScenarioResolution: mergedConfig.strictScenarioResolution ?? true,
266
+ }
267
+ : {}),
208
268
  ...mergedConfig,
209
269
  initLog: {
210
270
  headline: mergedConfig.initLog?.headline ??
@@ -214,6 +274,27 @@ async function setupMockifyerForReactNative(options) {
214
274
  return { status: 'active', instance };
215
275
  }
216
276
  }
277
+ /**
278
+ * Preset: point the app at **mockifyer-dashboard** for `/api/proxy` (typically **`--provider redis`**).
279
+ *
280
+ * Resolves URL in order: **`proxyBaseUrl`** → **`dashboardBaseUrl`** → **`MOCKIFYER_PROXY_URL`** env.
281
+ * Then delegates to {@link setupMockifyerForReactNative}. For bespoke wiring, call that helper directly.
282
+ */
283
+ async function initMockifyerForReactNativeDashboard(options) {
284
+ const fromEnv = typeof process !== 'undefined' && process.env?.MOCKIFYER_PROXY_URL
285
+ ? process.env.MOCKIFYER_PROXY_URL.trim()
286
+ : '';
287
+ const resolved = String(options.proxyBaseUrl ?? '').trim() ||
288
+ String(options.dashboardBaseUrl ?? '').trim() ||
289
+ fromEnv;
290
+ if (!resolved) {
291
+ throw new Error('initMockifyerForReactNativeDashboard: set proxyBaseUrl, dashboardBaseUrl, or MOCKIFYER_PROXY_URL');
292
+ }
293
+ return setupMockifyerForReactNative({
294
+ ...options,
295
+ proxyBaseUrl: resolved,
296
+ });
297
+ }
217
298
  var mockifyer_core_3 = require("@sgedda/mockifyer-core");
218
299
  Object.defineProperty(exports, "tryGetClientIdFromLaunchArguments", { enumerable: true, get: function () { return mockifyer_core_3.tryGetClientIdFromLaunchArguments; } });
219
300
  Object.defineProperty(exports, "MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY", { enumerable: true, get: function () { return mockifyer_core_3.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY; } });
@@ -0,0 +1 @@
1
+ export { canUseDashboardCentralProxy, canUseDashboardRedisProxy, type DashboardHealthPayload, } from '@sgedda/mockifyer-core';
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.canUseDashboardRedisProxy = exports.canUseDashboardCentralProxy = void 0;
4
+ var mockifyer_core_1 = require("@sgedda/mockifyer-core");
5
+ Object.defineProperty(exports, "canUseDashboardCentralProxy", { enumerable: true, get: function () { return mockifyer_core_1.canUseDashboardCentralProxy; } });
6
+ Object.defineProperty(exports, "canUseDashboardRedisProxy", { enumerable: true, get: function () { return mockifyer_core_1.canUseDashboardRedisProxy; } });
@@ -1,11 +1 @@
1
- /**
2
- * Builds a full URL to the Mockifyer dashboard HTTP API under a given `proxyBaseUrl`.
3
- *
4
- * `proxyBaseUrl` may include a path prefix (e.g. `https://host/apim-prefix/mockifyer/`).
5
- * Avoid `new URL('/api/...', proxyBaseUrl)` — a leading `/` on the second argument replaces the
6
- * entire pathname of the base URL, so the gateway prefix is lost.
7
- *
8
- * @param proxyBaseUrl - Origin and optional path prefix (with or without trailing slash)
9
- * @param apiSubPath - Path under that prefix without a leading slash (e.g. `api/health`, `api/proxy`)
10
- */
11
- export declare function joinProxyDashboardApiUrl(proxyBaseUrl: string, apiSubPath: string): string;
1
+ export { joinProxyDashboardApiUrl } from '@sgedda/mockifyer-core';
@@ -1,18 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.joinProxyDashboardApiUrl = joinProxyDashboardApiUrl;
4
- /**
5
- * Builds a full URL to the Mockifyer dashboard HTTP API under a given `proxyBaseUrl`.
6
- *
7
- * `proxyBaseUrl` may include a path prefix (e.g. `https://host/apim-prefix/mockifyer/`).
8
- * Avoid `new URL('/api/...', proxyBaseUrl)` — a leading `/` on the second argument replaces the
9
- * entire pathname of the base URL, so the gateway prefix is lost.
10
- *
11
- * @param proxyBaseUrl - Origin and optional path prefix (with or without trailing slash)
12
- * @param apiSubPath - Path under that prefix without a leading slash (e.g. `api/health`, `api/proxy`)
13
- */
14
- function joinProxyDashboardApiUrl(proxyBaseUrl, apiSubPath) {
15
- const normalizedBase = proxyBaseUrl.trim().replace(/\/+$/, '');
16
- const normalizedPath = apiSubPath.trim().replace(/^\/+/, '');
17
- return `${normalizedBase}/${normalizedPath}`;
18
- }
3
+ exports.joinProxyDashboardApiUrl = void 0;
4
+ var mockifyer_core_1 = require("@sgedda/mockifyer-core");
5
+ Object.defineProperty(exports, "joinProxyDashboardApiUrl", { enumerable: true, get: function () { return mockifyer_core_1.joinProxyDashboardApiUrl; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgedda/mockifyer-fetch",
3
- "version": "1.8.26",
3
+ "version": "1.8.33",
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,15 +49,27 @@
49
49
  },
50
50
  "license": "MIT",
51
51
  "dependencies": {
52
- "@sgedda/mockifyer-core": "^1.8.31"
52
+ "@sgedda/mockifyer-core": "^1.10.0"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@types/node": "^20.11.24",
56
56
  "typescript": "^5.3.3"
57
57
  },
58
+ "peerDependencies": {
59
+ "react-native-launch-arguments": ">=4.0.0"
60
+ },
61
+ "peerDependenciesMeta": {
62
+ "react-native-launch-arguments": {
63
+ "optional": true
64
+ }
65
+ },
58
66
  "publishConfig": {
59
67
  "access": "public"
60
68
  },
69
+ "homepage": "https://mockifyer.dev",
70
+ "bugs": {
71
+ "url": "https://github.com/sgedda/mockifyer/issues"
72
+ },
61
73
  "repository": {
62
74
  "type": "git",
63
75
  "url": "git+https://github.com/sgedda/mockifyer.git"
@@ -1,31 +1,46 @@
1
- import { BaseHTTPClient } from '@sgedda/mockifyer-core';
2
- import { HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
3
1
  import {
2
+ BaseHTTPClient,
3
+ HTTPRequestConfig,
4
+ HTTPResponse,
5
+ logger,
6
+ getActiveInboundClientId,
4
7
  getOutboundMockifyerClientIdHeader,
5
8
  getOutboundMockifyerDeviceIdHeader,
6
9
  MOCKIFYER_CLIENT_ID_HEADER,
7
10
  MOCKIFYER_DEVICE_ID_HEADER,
11
+ performDashboardProxyRequest,
8
12
  } from '@sgedda/mockifyer-core';
9
- import { joinProxyDashboardApiUrl } from '../utils/join-proxy-dashboard-api-url';
10
13
 
11
14
  export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
12
15
  private baseUrl?: string;
13
16
  private defaultHeaders: Record<string, string>;
14
17
  private proxyBaseUrl?: string;
15
18
  private proxyScenario?: string;
16
- private proxyRecordOnMiss: boolean;
19
+ /** When set, included as `record` on `/api/proxy`. When unset, dashboard per-scenario default applies. */
20
+ private proxyRecordOnMiss?: boolean;
21
+ private proxyRecordResponses: boolean;
17
22
  private getClientId?: () => string | undefined;
18
23
  private getStrictLaneScenario?: () => boolean;
24
+ private getExplicitProxyScenarioContext?: () => boolean;
19
25
  private clientIdSnapshot?: string;
20
26
  private deviceId?: string;
21
27
 
22
28
  constructor(config?: {
23
29
  baseUrl?: string;
24
30
  defaultHeaders?: Record<string, string>;
25
- proxy?: { baseUrl: string; scenario?: string; recordOnMiss?: boolean; strictLaneScenario?: boolean };
31
+ proxy?: {
32
+ baseUrl: string;
33
+ scenario?: string;
34
+ recordOnMiss?: boolean;
35
+ recordResponses?: boolean;
36
+ strictLaneScenario?: boolean;
37
+ mirrorRecordedMocksToClient?: boolean;
38
+ };
26
39
  clientId?: string;
27
40
  getClientId?: () => string | undefined;
28
41
  getStrictLaneScenario?: () => boolean;
42
+ /** When false, skip `/api/proxy` and call the real URL (devtools-friendly passthrough). */
43
+ getExplicitProxyScenarioContext?: () => boolean;
29
44
  deviceId?: string;
30
45
  }) {
31
46
  super();
@@ -33,14 +48,24 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
33
48
  this.defaultHeaders = config?.defaultHeaders || {};
34
49
  this.proxyBaseUrl = config?.proxy?.baseUrl;
35
50
  this.proxyScenario = config?.proxy?.scenario;
36
- this.proxyRecordOnMiss = config?.proxy?.recordOnMiss ?? false;
51
+ this.proxyRecordOnMiss = config?.proxy?.recordOnMiss;
52
+ this.proxyRecordResponses = config?.proxy?.recordResponses ?? false;
37
53
  this.getClientId = config?.getClientId;
38
54
  this.getStrictLaneScenario = config?.getStrictLaneScenario;
55
+ this.getExplicitProxyScenarioContext = config?.getExplicitProxyScenarioContext;
39
56
  this.clientIdSnapshot = config?.clientId;
40
57
  this.deviceId = config?.deviceId;
41
58
  }
42
59
 
43
- private resolvedClientLane(): string | undefined {
60
+ private resolvedClientLane(hopHeaders?: unknown): string | undefined {
61
+ const fromHop = getOutboundMockifyerClientIdHeader(hopHeaders);
62
+ if (fromHop) {
63
+ return fromHop;
64
+ }
65
+ const fromInbound = getActiveInboundClientId();
66
+ if (fromInbound) {
67
+ return fromInbound;
68
+ }
44
69
  if (this.getClientId) {
45
70
  const v = this.getClientId();
46
71
  if (v != null && String(v).trim() !== '') {
@@ -92,80 +117,53 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
92
117
  };
93
118
 
94
119
  // Use original fetch if available (when global fetch is patched), otherwise use global fetch
95
- // CRITICAL: Always use _originalFetch if available to prevent infinite loops
96
120
  const fetchFn = (this as any)._originalFetch || fetch;
97
121
  if (!(this as any)._originalFetch) {
98
122
  console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
99
123
  }
100
124
 
101
- const lane = this.resolvedClientLane();
102
-
103
- // Proxy mode (e.g. React Native → dashboard → Redis)
104
- if (this.proxyBaseUrl) {
105
- const proxyUrl = joinProxyDashboardApiUrl(this.proxyBaseUrl, 'api/proxy');
106
- const proxyResponse = await fetchFn(proxyUrl, {
107
- method: 'POST',
108
- headers: {
109
- 'content-type': 'application/json',
110
- ...(lane ? { [MOCKIFYER_CLIENT_ID_HEADER]: lane } : {}),
111
- ...(this.deviceId ? { [MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
112
- },
113
- body: JSON.stringify({
114
- url,
115
- method: requestConfig.method,
116
- clientId: lane,
117
- deviceId: this.deviceId,
118
- headers: (() => {
119
- const out: Record<string, string> = {};
120
- headers.forEach((value, key) => {
121
- out[key] = value;
122
- });
123
- return out;
124
- })(),
125
- body: config.data ?? null,
126
- scenario: this.proxyScenario,
127
- record: this.proxyRecordOnMiss,
128
- strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
129
- }),
125
+ const lane = this.resolvedClientLane(config.headers);
126
+ const bypassMockifyer =
127
+ (config as any).__mockifyer_bypass === true || (config as any).__mockifyer_skip_save === true;
128
+ const hopRequestId = (config as any).__mockifyer_requestId as string | undefined;
129
+ const hopParentRequestId = (config as any).__mockifyer_parentRequestId as string | undefined;
130
+
131
+ const explicitProxyContext = this.getExplicitProxyScenarioContext?.() ?? true;
132
+
133
+ if (this.proxyBaseUrl && !bypassMockifyer && explicitProxyContext) {
134
+ const headerRecord: Record<string, string> = {};
135
+ headers.forEach((value, key) => {
136
+ headerRecord[key] = value;
130
137
  });
131
- if (!proxyResponse.ok) {
132
- const txt = await proxyResponse.text();
133
- throw new Error(`[FetchHTTPClient] Proxy error: ${proxyResponse.status} ${txt}`);
134
- }
135
- const payload = await proxyResponse.json();
136
- try {
137
- const source = String(payload?.source || '');
138
- const hash = typeof payload?.hash === 'string' ? payload.hash : '';
139
- if (source) {
140
- const hashShort = hash ? `${hash.slice(0, 8)}…` : '';
141
- const laneLabel = lane ? lane : '—';
142
- const kind = source === 'redis' ? 'mock hit' : 'upstream';
143
- console.log(
144
- `[Mockifyer-Fetch] Proxy ${kind}: ${requestConfig.method} ${url} ${
145
- hashShort ? `(hash=${hashShort}) ` : ''
146
- }(lane=${laneLabel})`
147
- );
148
- }
149
- } catch {
150
- // ignore logging failures
151
- }
152
- const data = payload?.response?.data;
153
- const status = payload?.response?.status ?? 200;
154
- const responseHeaders: Record<string, string> = payload?.response?.headers ?? {};
155
-
156
- return {
157
- data,
158
- status,
159
- statusText: String(status),
160
- headers: responseHeaders,
138
+ return performDashboardProxyRequest({
139
+ proxyBaseUrl: this.proxyBaseUrl,
140
+ url,
141
+ method: String(requestConfig.method || 'GET'),
142
+ headers: headerRecord,
143
+ body: config.data ?? null,
144
+ lane,
145
+ deviceId: this.deviceId,
146
+ requestId: hopRequestId,
147
+ parentRequestId: hopParentRequestId,
148
+ scenario: this.proxyScenario,
149
+ recordOnMiss: this.proxyRecordOnMiss,
150
+ recordResponses: this.proxyRecordResponses,
151
+ strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
161
152
  config,
162
- };
153
+ fetchFn,
154
+ logTag: 'Mockifyer-Fetch',
155
+ });
163
156
  }
164
157
 
165
- if (lane && !getOutboundMockifyerClientIdHeader(headers)) {
158
+ if (!bypassMockifyer && lane && !getOutboundMockifyerClientIdHeader(headers)) {
166
159
  headers.set(MOCKIFYER_CLIENT_ID_HEADER, lane);
167
160
  }
168
- if (this.deviceId && String(this.deviceId).trim() && !getOutboundMockifyerDeviceIdHeader(headers)) {
161
+ if (
162
+ !bypassMockifyer &&
163
+ this.deviceId &&
164
+ String(this.deviceId).trim() &&
165
+ !getOutboundMockifyerDeviceIdHeader(headers)
166
+ ) {
169
167
  headers.set(MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
170
168
  }
171
169
 
@@ -181,7 +179,6 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
181
179
  }
182
180
  }
183
181
 
184
- // Convert response Headers to Record<string, string>
185
182
  const responseHeaders: Record<string, string> = {};
186
183
  response.headers.forEach((value: string, key: string) => {
187
184
  responseHeaders[key] = value;
@@ -206,4 +203,3 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
206
203
  };
207
204
  }
208
205
  }
209
-