@sgedda/mockifyer-fetch 1.8.19 → 1.8.21

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.
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FetchHTTPClient = void 0;
4
4
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
5
+ const mockifyer_core_2 = require("@sgedda/mockifyer-core");
5
6
  class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
6
7
  constructor(config) {
7
8
  super();
@@ -60,8 +61,8 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
60
61
  method: 'POST',
61
62
  headers: {
62
63
  'content-type': 'application/json',
63
- ...(this.clientId ? { 'x-mockifyer-client-id': this.clientId } : {}),
64
- ...(this.deviceId ? { 'x-mockifyer-device-id': this.deviceId } : {}),
64
+ ...(this.clientId ? { [mockifyer_core_2.MOCKIFYER_CLIENT_ID_HEADER]: this.clientId } : {}),
65
+ ...(this.deviceId ? { [mockifyer_core_2.MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
65
66
  },
66
67
  body: JSON.stringify({
67
68
  url,
@@ -109,6 +110,12 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
109
110
  config,
110
111
  };
111
112
  }
113
+ if (this.clientId && String(this.clientId).trim() && !(0, mockifyer_core_2.getOutboundMockifyerClientIdHeader)(headers)) {
114
+ headers.set(mockifyer_core_2.MOCKIFYER_CLIENT_ID_HEADER, String(this.clientId).trim());
115
+ }
116
+ if (this.deviceId && String(this.deviceId).trim() && !(0, mockifyer_core_2.getOutboundMockifyerDeviceIdHeader)(headers)) {
117
+ headers.set(mockifyer_core_2.MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
118
+ }
112
119
  const response = await fetchFn(url, requestConfig);
113
120
  const contentType = response.headers.get('content-type') || '';
114
121
  const rawText = await response.text();
package/dist/index.js CHANGED
@@ -98,6 +98,10 @@ class MockifyerClass {
98
98
  this.config.clientId = (0, mockifyer_core_1.resolveClientId)(this.config);
99
99
  }
100
100
  mockifyer_core_2.logger.info(`[Mockifyer-Fetch] clientId: ${this.config.clientId}`);
101
+ this.activationMode = (0, mockifyer_core_1.resolveActivationMode)(this.config);
102
+ if (this.activationMode !== 'always') {
103
+ mockifyer_core_2.logger.info(`[Mockifyer-Fetch] activationMode: ${this.activationMode}`);
104
+ }
101
105
  // Initialize test generator if test generation is enabled
102
106
  if (config.generateTests?.enabled) {
103
107
  this.testGenerator = new mockifyer_core_1.TestGenerator();
@@ -347,6 +351,12 @@ class MockifyerClass {
347
351
  config.__mockifyer_bypass = true;
348
352
  return config;
349
353
  }
354
+ if (!(0, mockifyer_core_1.shouldApplyMockifyer)(this.activationMode, config.headers, {
355
+ useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
356
+ })) {
357
+ config.__mockifyer_bypass = true;
358
+ return config;
359
+ }
350
360
  // Normalize empty params: treat {} the same as undefined for consistent matching
351
361
  const rawParams = config.params || {};
352
362
  const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
@@ -6,11 +6,38 @@
6
6
  */
7
7
  import { setupMockifyer } from './index';
8
8
  import { HTTPClient } from '@sgedda/mockifyer-core';
9
+ import { type MockifyerRuntimeMode } from '@sgedda/mockifyer-core';
9
10
  export interface MockifyerInstance extends HTTPClient {
10
11
  reloadMockData: (syncFromProject?: boolean) => Promise<void>;
11
12
  clearStaleCacheEntries: () => number;
12
13
  clearAllMocks: () => Promise<void>;
13
14
  }
15
+ /**
16
+ * Outcome of {@link setupMockifyerForReactNative}.
17
+ *
18
+ * - **`not_activated`** — `fetch` was not patched this run (see **`MOCKIFYER_MODE`** / `runtimeMode`: `off`, or `launch_client` without a launch-arg lane).
19
+ * Not the same as “permanently off” unless mode is **`off`** (then launch args do not activate).
20
+ * - **`active`** — Mockifyer initialized and patched `global.fetch`.
21
+ * - **`failed_no_bundled_mocks`** — Activation criteria were met and `isDev` was false, but bundled mock data was missing or empty.
22
+ */
23
+ export type MockifyerReactNativeInitStatus = 'not_activated' | 'active' | 'failed_no_bundled_mocks';
24
+ export type SetupMockifyerForReactNativeResult = {
25
+ readonly status: 'not_activated';
26
+ readonly instance: null;
27
+ } | {
28
+ readonly status: 'failed_no_bundled_mocks';
29
+ readonly instance: null;
30
+ } | {
31
+ readonly status: 'active';
32
+ readonly instance: MockifyerInstance;
33
+ };
34
+ /**
35
+ * Type guard: `true` when {@link setupMockifyerForReactNative} patched `fetch` and returned an instance.
36
+ */
37
+ export declare function isMockifyerReactNativeActive(result: SetupMockifyerForReactNativeResult): result is {
38
+ readonly status: 'active';
39
+ readonly instance: MockifyerInstance;
40
+ };
14
41
  export interface ReactNativeMockifyerConfig {
15
42
  /** Whether we're in development mode (determines which provider to use) */
16
43
  isDev: boolean;
@@ -35,10 +62,17 @@ export interface ReactNativeMockifyerConfig {
35
62
  * When true, read `clientId` from Maestro/native launch arguments (optional peer `react-native-launch-arguments`).
36
63
  * Prefer this over passing scenario from E2E if the dashboard/Redis should control scenario on the fly for that lane.
37
64
  * Forwards to {@link MockifyerConfig.useLaunchArgumentsClientId} on the merged config passed to `setupMockifyer`.
65
+ *
66
+ * If the launch argument is **set** (non-empty) for {@link launchArgumentClientIdKey}, the lane id is applied when Mockifyer activates (see **`runtimeMode`** / **`MOCKIFYER_MODE`**; with **`launch_client`**, a set arg is required to activate).
38
67
  */
39
68
  useLaunchArgumentsClientId?: boolean;
40
69
  /** Launch-argument key for the client lane id (default: `mockifyerClientId`). */
41
70
  launchArgumentClientIdKey?: string;
71
+ /**
72
+ * When Mockifyer may patch `fetch` at startup. Overrides **`MOCKIFYER_MODE`** env and `config.runtimeMode`.
73
+ * Prefer env **`MOCKIFYER_MODE`**: `off` | `on` | `launch_client` (aliases e.g. `e2e`, `maestro` → `launch_client`).
74
+ */
75
+ runtimeMode?: MockifyerRuntimeMode;
42
76
  }
43
77
  /**
44
78
  * Setup Mockifyer for React Native/Expo with automatic conditional provider selection
@@ -50,13 +84,15 @@ export interface ReactNativeMockifyerConfig {
50
84
  * ```typescript
51
85
  * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
52
86
  *
53
- * await setupMockifyerForReactNative({
54
- * isDev: __DEV__, // Pass React Native's __DEV__ variable
87
+ * // MOCKIFYER_MODE=on | launch_client | off — default when unset is on; use launch_client for Maestro-only activation.
88
+ * const result = await setupMockifyerForReactNative({
89
+ * isDev: __DEV__, // Selects Hybrid vs Memory provider once enabled
55
90
  * mockDataPath: 'mock-data',
56
91
  * bundledDataPath: './assets/mock-data',
57
92
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
58
93
  * });
94
+ * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
59
95
  * ```
60
96
  */
61
- export declare function setupMockifyerForReactNative(options: ReactNativeMockifyerConfig): Promise<MockifyerInstance | null>;
97
+ export declare function setupMockifyerForReactNative(options: ReactNativeMockifyerConfig): Promise<SetupMockifyerForReactNativeResult>;
62
98
  export { tryGetClientIdFromLaunchArguments, MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY } from '@sgedda/mockifyer-core';
@@ -7,10 +7,17 @@
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY = exports.tryGetClientIdFromLaunchArguments = void 0;
10
+ exports.isMockifyerReactNativeActive = isMockifyerReactNativeActive;
10
11
  exports.setupMockifyerForReactNative = setupMockifyerForReactNative;
11
12
  const index_1 = require("./index");
12
13
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
13
14
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
15
+ /**
16
+ * Type guard: `true` when {@link setupMockifyerForReactNative} patched `fetch` and returned an instance.
17
+ */
18
+ function isMockifyerReactNativeActive(result) {
19
+ return result.status === 'active';
20
+ }
14
21
  // Lazy load bundled data (only used in production builds)
15
22
  let bundledMockData = null;
16
23
  async function canUseStrictRedisProxy(proxyBaseUrl) {
@@ -74,31 +81,48 @@ async function loadBundledMockData(bundledDataPath) {
74
81
  * ```typescript
75
82
  * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
76
83
  *
77
- * await setupMockifyerForReactNative({
78
- * isDev: __DEV__, // Pass React Native's __DEV__ variable
84
+ * // MOCKIFYER_MODE=on | launch_client | off — default when unset is on; use launch_client for Maestro-only activation.
85
+ * const result = await setupMockifyerForReactNative({
86
+ * isDev: __DEV__, // Selects Hybrid vs Memory provider once enabled
79
87
  * mockDataPath: 'mock-data',
80
88
  * bundledDataPath: './assets/mock-data',
81
89
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
82
90
  * });
91
+ * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
83
92
  * ```
84
93
  */
85
94
  async function setupMockifyerForReactNative(options) {
86
- const { isDev, mockDataPath = 'mock-data', bundledDataPath = './assets/mock-data', recordMode = false, config = {}, proxyBaseUrl, proxyScenario, proxyRecordOnMiss, useLaunchArgumentsClientId = false, launchArgumentClientIdKey = mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY, } = options;
95
+ 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;
87
96
  const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
97
+ const launchClientIdKey = launchArgumentClientIdKey ?? mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
98
+ const clientIdFromLaunchArgs = (0, mockifyer_core_2.tryGetClientIdFromLaunchArguments)(launchClientIdKey);
99
+ const shouldApplyLaunchClientId = useLaunchArgumentsClientId || Boolean(clientIdFromLaunchArgs);
100
+ const resolvedRuntimeMode = (0, mockifyer_core_2.resolveMockifyerRuntimeMode)({
101
+ configMode: runtimeModeOption ?? userConfig.runtimeMode,
102
+ });
88
103
  const mergedConfig = {
89
- ...config,
90
- ...(useLaunchArgumentsClientId
104
+ ...userConfig,
105
+ runtimeMode: resolvedRuntimeMode,
106
+ ...(shouldApplyLaunchClientId
91
107
  ? {
92
108
  useLaunchArgumentsClientId: true,
93
- launchArgumentClientIdKey: launchArgumentClientIdKey ?? mockifyer_core_2.MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
109
+ launchArgumentClientIdKey: launchClientIdKey,
94
110
  }
95
111
  : {}),
96
112
  };
97
- // Check if Mockifyer is enabled
98
- const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
113
+ const isEnabled = resolvedRuntimeMode === 'on' ||
114
+ (resolvedRuntimeMode === 'launch_client' && Boolean(clientIdFromLaunchArgs));
99
115
  if (!isEnabled) {
100
- mockifyer_core_2.logger.info('[Mockifyer] Disabled');
101
- return null;
116
+ const hint = resolvedRuntimeMode === 'off'
117
+ ? 'MOCKIFYER_MODE=off (or runtimeMode off) — launch args are ignored.'
118
+ : resolvedRuntimeMode === 'launch_client'
119
+ ? 'MOCKIFYER_MODE=launch_client — pass mockifyerClientId via launch args, or set MOCKIFYER_MODE=on for always-on dev.'
120
+ : 'Adjust MOCKIFYER_MODE / runtimeMode.';
121
+ mockifyer_core_2.logger.info(`[Mockifyer] Not activated (${hint})`);
122
+ return { status: 'not_activated', instance: null };
123
+ }
124
+ if (clientIdFromLaunchArgs && !useLaunchArgumentsClientId) {
125
+ mockifyer_core_2.logger.info(`[Mockifyer] Enabled via launch argument "${launchClientIdKey}" (E2E lane "${clientIdFromLaunchArgs}")`);
102
126
  }
103
127
  if (isDev === true) {
104
128
  const strictProxyEnabled = await canUseStrictRedisProxy(proxyBaseUrl);
@@ -162,7 +186,7 @@ async function setupMockifyerForReactNative(options) {
162
186
  mockifyer_core_2.logger.warn('[Mockifyer] Initial project→device sync failed (Metro running with built mockifyer-fetch?):', error);
163
187
  }
164
188
  }
165
- return instance;
189
+ return { status: 'active', instance };
166
190
  }
167
191
  else {
168
192
  // PRODUCTION BUILD MODE
@@ -172,8 +196,8 @@ async function setupMockifyerForReactNative(options) {
172
196
  // Load bundled mock data
173
197
  const mockDataArray = await loadBundledMockData(bundledDataPath);
174
198
  if (mockDataArray.length === 0) {
175
- mockifyer_core_2.logger.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
176
- return null;
199
+ mockifyer_core_2.logger.warn('[Mockifyer] Activation requested but no bundled mock data found (status: failed_no_bundled_mocks). Run the bundle/generate step for your mocks.');
200
+ return { status: 'failed_no_bundled_mocks', instance: null };
177
201
  }
178
202
  // Pre-load all mocks into memory
179
203
  for (const mockData of mockDataArray) {
@@ -192,7 +216,7 @@ async function setupMockifyerForReactNative(options) {
192
216
  ...mergedConfig,
193
217
  });
194
218
  mockifyer_core_2.logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
195
- return instance;
219
+ return { status: 'active', instance };
196
220
  }
197
221
  }
198
222
  var mockifyer_core_3 = require("@sgedda/mockifyer-core");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgedda/mockifyer-fetch",
3
- "version": "1.8.19",
3
+ "version": "1.8.21",
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",
@@ -46,7 +46,7 @@
46
46
  "author": "sgedda",
47
47
  "license": "MIT",
48
48
  "dependencies": {
49
- "@sgedda/mockifyer-core": "^1.8.24"
49
+ "@sgedda/mockifyer-core": "^1.8.26"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@types/node": "^20.11.24",
@@ -1,5 +1,11 @@
1
1
  import { BaseHTTPClient } from '@sgedda/mockifyer-core';
2
2
  import { HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
3
+ import {
4
+ getOutboundMockifyerClientIdHeader,
5
+ getOutboundMockifyerDeviceIdHeader,
6
+ MOCKIFYER_CLIENT_ID_HEADER,
7
+ MOCKIFYER_DEVICE_ID_HEADER,
8
+ } from '@sgedda/mockifyer-core';
3
9
 
4
10
  export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
5
11
  private baseUrl?: string;
@@ -79,8 +85,8 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
79
85
  method: 'POST',
80
86
  headers: {
81
87
  'content-type': 'application/json',
82
- ...(this.clientId ? { 'x-mockifyer-client-id': this.clientId } : {}),
83
- ...(this.deviceId ? { 'x-mockifyer-device-id': this.deviceId } : {}),
88
+ ...(this.clientId ? { [MOCKIFYER_CLIENT_ID_HEADER]: this.clientId } : {}),
89
+ ...(this.deviceId ? { [MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
84
90
  },
85
91
  body: JSON.stringify({
86
92
  url,
@@ -133,6 +139,13 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
133
139
  };
134
140
  }
135
141
 
142
+ if (this.clientId && String(this.clientId).trim() && !getOutboundMockifyerClientIdHeader(headers)) {
143
+ headers.set(MOCKIFYER_CLIENT_ID_HEADER, String(this.clientId).trim());
144
+ }
145
+ if (this.deviceId && String(this.deviceId).trim() && !getOutboundMockifyerDeviceIdHeader(headers)) {
146
+ headers.set(MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
147
+ }
148
+
136
149
  const response = await fetchFn(url, requestConfig);
137
150
  const contentType = response.headers.get('content-type') || '';
138
151
  const rawText = await response.text();
package/src/index.ts CHANGED
@@ -39,7 +39,10 @@ import {
39
39
  mockPassesThroughToRealApi,
40
40
  resolveClientId,
41
41
  tryGetClientIdFromLaunchArguments,
42
- MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY
42
+ MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
43
+ resolveActivationMode,
44
+ shouldApplyMockifyer,
45
+ type MockifyerActivationMode,
43
46
  } from '@sgedda/mockifyer-core';
44
47
  import { logger, setLogLevel } from '@sgedda/mockifyer-core';
45
48
 
@@ -57,6 +60,7 @@ class MockifyerClass {
57
60
  private sessionStartTime: number = 0;
58
61
  private readonly SESSION_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes
59
62
  private testGenerator?: TestGenerator;
63
+ private readonly activationMode: MockifyerActivationMode;
60
64
 
61
65
  constructor(config: MockifyerConfig) {
62
66
  // Validate database provider - filesystem, expo-filesystem, hybrid, and memory are supported
@@ -127,7 +131,12 @@ class MockifyerClass {
127
131
  this.config.clientId = resolveClientId(this.config);
128
132
  }
129
133
  logger.info(`[Mockifyer-Fetch] clientId: ${this.config.clientId}`);
130
-
134
+
135
+ this.activationMode = resolveActivationMode(this.config);
136
+ if (this.activationMode !== 'always') {
137
+ logger.info(`[Mockifyer-Fetch] activationMode: ${this.activationMode}`);
138
+ }
139
+
131
140
  // Initialize test generator if test generation is enabled
132
141
  if (config.generateTests?.enabled) {
133
142
  this.testGenerator = new TestGenerator();
@@ -416,7 +425,16 @@ class MockifyerClass {
416
425
  (config as any).__mockifyer_bypass = true;
417
426
  return config;
418
427
  }
419
-
428
+
429
+ if (
430
+ !shouldApplyMockifyer(this.activationMode, config.headers, {
431
+ useProxyLane: { proxyBaseUrl: this.config.proxy?.baseUrl, resolvedClientId: this.config.clientId },
432
+ })
433
+ ) {
434
+ (config as any).__mockifyer_bypass = true;
435
+ return config;
436
+ }
437
+
420
438
  // Normalize empty params: treat {} the same as undefined for consistent matching
421
439
  const rawParams = config.params || {};
422
440
  const anonymizedQueryParams = this.anonymizeQueryParams(rawParams);
@@ -524,7 +542,7 @@ class MockifyerClass {
524
542
  if ((response.config as any).__mockifyer_skip_save || (response.config as any).__mockifyer_bypass) {
525
543
  return response;
526
544
  }
527
-
545
+
528
546
  // CRITICAL: Skip Mockifyer sync endpoints to prevent infinite loops
529
547
  // Check multiple ways to get the URL in case response.config is undefined
530
548
  const url = response.config?.url || response.request?.responseURL || response.url || (response as any).config?.url || '';
@@ -10,6 +10,9 @@ import { MemoryProvider, ExpoFileSystemProvider, MockData, HTTPClient } from '@s
10
10
  import {
11
11
  logger,
12
12
  MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
13
+ tryGetClientIdFromLaunchArguments,
14
+ resolveMockifyerRuntimeMode,
15
+ type MockifyerRuntimeMode,
13
16
  } from '@sgedda/mockifyer-core';
14
17
 
15
18
  // Re-export MockifyerInstance type to avoid circular dependency
@@ -19,6 +22,33 @@ export interface MockifyerInstance extends HTTPClient {
19
22
  clearAllMocks: () => Promise<void>;
20
23
  }
21
24
 
25
+ /**
26
+ * Outcome of {@link setupMockifyerForReactNative}.
27
+ *
28
+ * - **`not_activated`** — `fetch` was not patched this run (see **`MOCKIFYER_MODE`** / `runtimeMode`: `off`, or `launch_client` without a launch-arg lane).
29
+ * Not the same as “permanently off” unless mode is **`off`** (then launch args do not activate).
30
+ * - **`active`** — Mockifyer initialized and patched `global.fetch`.
31
+ * - **`failed_no_bundled_mocks`** — Activation criteria were met and `isDev` was false, but bundled mock data was missing or empty.
32
+ */
33
+ export type MockifyerReactNativeInitStatus =
34
+ | 'not_activated'
35
+ | 'active'
36
+ | 'failed_no_bundled_mocks';
37
+
38
+ export type SetupMockifyerForReactNativeResult =
39
+ | { readonly status: 'not_activated'; readonly instance: null }
40
+ | { readonly status: 'failed_no_bundled_mocks'; readonly instance: null }
41
+ | { readonly status: 'active'; readonly instance: MockifyerInstance };
42
+
43
+ /**
44
+ * Type guard: `true` when {@link setupMockifyerForReactNative} patched `fetch` and returned an instance.
45
+ */
46
+ export function isMockifyerReactNativeActive(
47
+ result: SetupMockifyerForReactNativeResult
48
+ ): result is { readonly status: 'active'; readonly instance: MockifyerInstance } {
49
+ return result.status === 'active';
50
+ }
51
+
22
52
  export interface ReactNativeMockifyerConfig {
23
53
  /** Whether we're in development mode (determines which provider to use) */
24
54
  isDev: boolean;
@@ -43,10 +73,17 @@ export interface ReactNativeMockifyerConfig {
43
73
  * When true, read `clientId` from Maestro/native launch arguments (optional peer `react-native-launch-arguments`).
44
74
  * Prefer this over passing scenario from E2E if the dashboard/Redis should control scenario on the fly for that lane.
45
75
  * Forwards to {@link MockifyerConfig.useLaunchArgumentsClientId} on the merged config passed to `setupMockifyer`.
76
+ *
77
+ * If the launch argument is **set** (non-empty) for {@link launchArgumentClientIdKey}, the lane id is applied when Mockifyer activates (see **`runtimeMode`** / **`MOCKIFYER_MODE`**; with **`launch_client`**, a set arg is required to activate).
46
78
  */
47
79
  useLaunchArgumentsClientId?: boolean;
48
80
  /** Launch-argument key for the client lane id (default: `mockifyerClientId`). */
49
81
  launchArgumentClientIdKey?: string;
82
+ /**
83
+ * When Mockifyer may patch `fetch` at startup. Overrides **`MOCKIFYER_MODE`** env and `config.runtimeMode`.
84
+ * Prefer env **`MOCKIFYER_MODE`**: `off` | `on` | `launch_client` (aliases e.g. `e2e`, `maestro` → `launch_client`).
85
+ */
86
+ runtimeMode?: MockifyerRuntimeMode;
50
87
  }
51
88
 
52
89
  type DashboardHealth = {
@@ -119,49 +156,75 @@ async function loadBundledMockData(bundledDataPath: string): Promise<MockData[]>
119
156
  * @example
120
157
  * ```typescript
121
158
  * import { setupMockifyerForReactNative } from '@sgedda/mockifyer-fetch/react-native';
122
- *
123
- * await setupMockifyerForReactNative({
124
- * isDev: __DEV__, // Pass React Native's __DEV__ variable
159
+ *
160
+ * // MOCKIFYER_MODE=on | launch_client | off — default when unset is on; use launch_client for Maestro-only activation.
161
+ * const result = await setupMockifyerForReactNative({
162
+ * isDev: __DEV__, // Selects Hybrid vs Memory provider once enabled
125
163
  * mockDataPath: 'mock-data',
126
164
  * bundledDataPath: './assets/mock-data',
127
165
  * recordMode: process.env.MOCKIFYER_RECORD === 'true',
128
166
  * });
167
+ * // result.status: 'not_activated' | 'active' | 'failed_no_bundled_mocks'
129
168
  * ```
130
169
  */
131
170
  export async function setupMockifyerForReactNative(
132
171
  options: ReactNativeMockifyerConfig
133
- ): Promise<MockifyerInstance | null> {
172
+ ): Promise<SetupMockifyerForReactNativeResult> {
134
173
  const {
135
174
  isDev,
136
175
  mockDataPath = 'mock-data',
137
176
  bundledDataPath = './assets/mock-data',
138
177
  recordMode = false,
139
- config = {},
178
+ config: userConfig = {},
140
179
  proxyBaseUrl,
141
180
  proxyScenario,
142
181
  proxyRecordOnMiss,
143
182
  useLaunchArgumentsClientId = false,
144
183
  launchArgumentClientIdKey = MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
184
+ runtimeMode: runtimeModeOption,
145
185
  } = options;
146
186
 
147
187
  const proxyShouldRecordOnMiss = proxyRecordOnMiss ?? recordMode;
148
188
 
149
- const mergedConfig: typeof config = {
150
- ...config,
151
- ...(useLaunchArgumentsClientId
189
+ const launchClientIdKey =
190
+ launchArgumentClientIdKey ?? MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY;
191
+ const clientIdFromLaunchArgs = tryGetClientIdFromLaunchArguments(launchClientIdKey);
192
+ const shouldApplyLaunchClientId =
193
+ useLaunchArgumentsClientId || Boolean(clientIdFromLaunchArgs);
194
+
195
+ const resolvedRuntimeMode = resolveMockifyerRuntimeMode({
196
+ configMode: runtimeModeOption ?? userConfig.runtimeMode,
197
+ });
198
+
199
+ const mergedConfig: typeof userConfig = {
200
+ ...userConfig,
201
+ runtimeMode: resolvedRuntimeMode,
202
+ ...(shouldApplyLaunchClientId
152
203
  ? {
153
204
  useLaunchArgumentsClientId: true as const,
154
- launchArgumentClientIdKey:
155
- launchArgumentClientIdKey ?? MOCKIFYER_LAUNCH_ARGUMENT_CLIENT_ID_KEY,
205
+ launchArgumentClientIdKey: launchClientIdKey,
156
206
  }
157
207
  : {}),
158
208
  };
159
209
 
160
- // Check if Mockifyer is enabled
161
- const isEnabled = process.env.MOCKIFYER_ENABLED === 'true' || isDev;
210
+ const isEnabled =
211
+ resolvedRuntimeMode === 'on' ||
212
+ (resolvedRuntimeMode === 'launch_client' && Boolean(clientIdFromLaunchArgs));
162
213
  if (!isEnabled) {
163
- logger.info('[Mockifyer] Disabled');
164
- return null;
214
+ const hint =
215
+ resolvedRuntimeMode === 'off'
216
+ ? 'MOCKIFYER_MODE=off (or runtimeMode off) — launch args are ignored.'
217
+ : resolvedRuntimeMode === 'launch_client'
218
+ ? 'MOCKIFYER_MODE=launch_client — pass mockifyerClientId via launch args, or set MOCKIFYER_MODE=on for always-on dev.'
219
+ : 'Adjust MOCKIFYER_MODE / runtimeMode.';
220
+ logger.info(`[Mockifyer] Not activated (${hint})`);
221
+ return { status: 'not_activated', instance: null } as const;
222
+ }
223
+
224
+ if (clientIdFromLaunchArgs && !useLaunchArgumentsClientId) {
225
+ logger.info(
226
+ `[Mockifyer] Enabled via launch argument "${launchClientIdKey}" (E2E lane "${clientIdFromLaunchArgs}")`
227
+ );
165
228
  }
166
229
 
167
230
  if (isDev === true) {
@@ -233,7 +296,7 @@ export async function setupMockifyerForReactNative(
233
296
  }
234
297
  }
235
298
 
236
- return instance;
299
+ return { status: 'active', instance } as const;
237
300
  } else {
238
301
  // PRODUCTION BUILD MODE
239
302
  // Use Memory provider with bundled TypeScript file
@@ -244,8 +307,10 @@ export async function setupMockifyerForReactNative(
244
307
  const mockDataArray = await loadBundledMockData(bundledDataPath);
245
308
 
246
309
  if (mockDataArray.length === 0) {
247
- logger.warn('[Mockifyer] No bundled mock data found. Make sure to run the build script first.');
248
- return null;
310
+ logger.warn(
311
+ '[Mockifyer] Activation requested but no bundled mock data found (status: failed_no_bundled_mocks). Run the bundle/generate step for your mocks.'
312
+ );
313
+ return { status: 'failed_no_bundled_mocks', instance: null } as const;
249
314
  }
250
315
 
251
316
  // Pre-load all mocks into memory
@@ -267,7 +332,7 @@ export async function setupMockifyerForReactNative(
267
332
  });
268
333
 
269
334
  logger.info(`[Mockifyer] Production mode: Loaded ${mockDataArray.length} mocks from bundle`);
270
- return instance;
335
+ return { status: 'active', instance } as const;
271
336
  }
272
337
  }
273
338