@sgedda/mockifyer-fetch 1.8.32 → 1.8.34

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,27 +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 join_proxy_dashboard_api_url_1 = require("../utils/join-proxy-dashboard-api-url");
6
- function buildProxyEnvelope(params) {
7
- const { url, method, lane, deviceId, requestId, parentRequestId, headers, body, scenario, recordOnMiss, recordResponses, strictLaneScenario, } = params;
8
- const envelope = {
9
- url,
10
- method,
11
- clientId: lane,
12
- deviceId,
13
- requestId,
14
- parentRequestId,
15
- headers,
16
- body,
17
- scenario,
18
- recordResponses,
19
- strictLaneScenario,
20
- };
21
- if (typeof recordOnMiss === 'boolean') {
22
- envelope.record = recordOnMiss;
23
- }
24
- return envelope;
25
- }
5
+ const core_proxy_1 = require("../core-proxy");
26
6
  class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
27
7
  constructor(config) {
28
8
  super();
@@ -93,7 +73,6 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
93
73
  body: config.data ? JSON.stringify(config.data) : undefined
94
74
  };
95
75
  // Use original fetch if available (when global fetch is patched), otherwise use global fetch
96
- // CRITICAL: Always use _originalFetch if available to prevent infinite loops
97
76
  const fetchFn = this._originalFetch || fetch;
98
77
  if (!this._originalFetch) {
99
78
  console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
@@ -103,80 +82,29 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
103
82
  const hopRequestId = config.__mockifyer_requestId;
104
83
  const hopParentRequestId = config.__mockifyer_parentRequestId;
105
84
  const explicitProxyContext = this.getExplicitProxyScenarioContext?.() ?? true;
106
- // Proxy mode (e.g. React Native → dashboard → Redis)
107
85
  if (this.proxyBaseUrl && !bypassMockifyer && explicitProxyContext) {
108
- const proxyUrl = (0, join_proxy_dashboard_api_url_1.joinProxyDashboardApiUrl)(this.proxyBaseUrl, 'api/proxy');
109
- const proxyResponse = await fetchFn(proxyUrl, {
110
- method: 'POST',
111
- headers: {
112
- 'content-type': 'application/json',
113
- ...(lane ? { [mockifyer_core_1.MOCKIFYER_CLIENT_ID_HEADER]: lane } : {}),
114
- ...(this.deviceId ? { [mockifyer_core_1.MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
115
- ...(hopRequestId ? { [mockifyer_core_1.MOCKIFYER_REQUEST_ID_HEADER]: hopRequestId } : {}),
116
- ...(hopParentRequestId ? { [mockifyer_core_1.MOCKIFYER_PARENT_REQUEST_ID_HEADER]: hopParentRequestId } : {}),
117
- },
118
- body: JSON.stringify(buildProxyEnvelope({
119
- url,
120
- method: String(requestConfig.method || 'GET'),
121
- lane,
122
- deviceId: this.deviceId,
123
- requestId: hopRequestId,
124
- parentRequestId: hopParentRequestId,
125
- headers: (() => {
126
- const out = {};
127
- headers.forEach((value, key) => {
128
- out[key] = value;
129
- });
130
- return out;
131
- })(),
132
- body: config.data ?? null,
133
- scenario: this.proxyScenario,
134
- recordOnMiss: this.proxyRecordOnMiss,
135
- recordResponses: this.proxyRecordResponses,
136
- strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
137
- })),
86
+ const headerRecord = {};
87
+ headers.forEach((value, key) => {
88
+ headerRecord[key] = value;
138
89
  });
139
- if (!proxyResponse.ok) {
140
- const txt = await proxyResponse.text();
141
- throw new Error(`[FetchHTTPClient] Proxy error: ${proxyResponse.status} ${txt}`);
142
- }
143
- const payload = await proxyResponse.json();
144
- try {
145
- const source = String(payload?.source || '');
146
- const hash = typeof payload?.hash === 'string' ? payload.hash : '';
147
- if (source) {
148
- const hashShort = hash ? `${hash.slice(0, 8)}…` : '';
149
- const laneLabel = lane ? lane : '—';
150
- const kind = source === 'redis' ? 'mock hit' : 'upstream';
151
- mockifyer_core_1.logger.debug(`[Mockifyer-Fetch] Proxy ${kind}: ${requestConfig.method} ${url} ${hashShort ? `(hash=${hashShort}) ` : ''}(lane=${laneLabel})`);
152
- }
153
- }
154
- catch {
155
- // ignore logging failures
156
- }
157
- const data = payload?.response?.data;
158
- const status = payload?.response?.status ?? 200;
159
- const responseHeaders = payload?.response?.headers ?? {};
160
- const scenarioResolution = payload?.scenarioResolution;
161
- const scenarioName = typeof scenarioResolution?.scenario === 'string' && scenarioResolution.scenario.trim()
162
- ? scenarioResolution.scenario.trim()
163
- : undefined;
164
- const mockifyerProxyRecording = payload?.recordedToStore === true && payload?.storedMock
165
- ? {
166
- recordedToStore: true,
167
- storedMock: payload.storedMock,
168
- hash: typeof payload.hash === 'string' ? payload.hash : undefined,
169
- scenarioName,
170
- }
171
- : undefined;
172
- return {
173
- data,
174
- status,
175
- statusText: String(status),
176
- headers: responseHeaders,
90
+ return (0, core_proxy_1.performDashboardProxyRequest)({
91
+ proxyBaseUrl: this.proxyBaseUrl,
92
+ url,
93
+ method: String(requestConfig.method || 'GET'),
94
+ headers: headerRecord,
95
+ body: config.data ?? null,
96
+ lane,
97
+ deviceId: this.deviceId,
98
+ requestId: hopRequestId,
99
+ parentRequestId: hopParentRequestId,
100
+ scenario: this.proxyScenario,
101
+ recordOnMiss: this.proxyRecordOnMiss,
102
+ recordResponses: this.proxyRecordResponses,
103
+ strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
177
104
  config,
178
- mockifyerProxyRecording,
179
- };
105
+ fetchFn,
106
+ logTag: 'Mockifyer-Fetch',
107
+ });
180
108
  }
181
109
  if (!bypassMockifyer && lane && !(0, mockifyer_core_1.getOutboundMockifyerClientIdHeader)(headers)) {
182
110
  headers.set(mockifyer_core_1.MOCKIFYER_CLIENT_ID_HEADER, lane);
@@ -199,7 +127,6 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
199
127
  data = rawText;
200
128
  }
201
129
  }
202
- // Convert response Headers to Record<string, string>
203
130
  const responseHeaders = {};
204
131
  response.headers.forEach((value, key) => {
205
132
  responseHeaders[key] = value;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Proxy/dashboard helpers from core via subpath exports (RN-safe; avoids barrel resolution).
3
+ */
4
+ export { applyProxyRecordOnMissEnv } from '@sgedda/mockifyer-core/utils/apply-proxy-record-on-miss-env';
5
+ export { mirrorProxyRecordingToClient } from '@sgedda/mockifyer-core/utils/mirror-proxy-recording-to-client';
6
+ export { initMockifyerForDashboardProxy, initMockifyerForLocalFilesystem, type InitMockifyerForDashboardProxyOptions, type InitMockifyerForLocalFilesystemOptions, } from '@sgedda/mockifyer-core/utils/init-mockifyer-presets';
7
+ export { performDashboardProxyRequest } from '@sgedda/mockifyer-core/utils/perform-dashboard-proxy-request';
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.performDashboardProxyRequest = exports.initMockifyerForLocalFilesystem = exports.initMockifyerForDashboardProxy = exports.mirrorProxyRecordingToClient = exports.applyProxyRecordOnMissEnv = void 0;
4
+ /**
5
+ * Proxy/dashboard helpers from core via subpath exports (RN-safe; avoids barrel resolution).
6
+ */
7
+ var apply_proxy_record_on_miss_env_1 = require("@sgedda/mockifyer-core/utils/apply-proxy-record-on-miss-env");
8
+ Object.defineProperty(exports, "applyProxyRecordOnMissEnv", { enumerable: true, get: function () { return apply_proxy_record_on_miss_env_1.applyProxyRecordOnMissEnv; } });
9
+ var mirror_proxy_recording_to_client_1 = require("@sgedda/mockifyer-core/utils/mirror-proxy-recording-to-client");
10
+ Object.defineProperty(exports, "mirrorProxyRecordingToClient", { enumerable: true, get: function () { return mirror_proxy_recording_to_client_1.mirrorProxyRecordingToClient; } });
11
+ var init_mockifyer_presets_1 = require("@sgedda/mockifyer-core/utils/init-mockifyer-presets");
12
+ Object.defineProperty(exports, "initMockifyerForDashboardProxy", { enumerable: true, get: function () { return init_mockifyer_presets_1.initMockifyerForDashboardProxy; } });
13
+ Object.defineProperty(exports, "initMockifyerForLocalFilesystem", { enumerable: true, get: function () { return init_mockifyer_presets_1.initMockifyerForLocalFilesystem; } });
14
+ var perform_dashboard_proxy_request_1 = require("@sgedda/mockifyer-core/utils/perform-dashboard-proxy-request");
15
+ Object.defineProperty(exports, "performDashboardProxyRequest", { enumerable: true, get: function () { return perform_dashboard_proxy_request_1.performDashboardProxyRequest; } });
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { MockifyerConfig, HTTPClient } from '@sgedda/mockifyer-core';
2
+ import { type InitMockifyerForDashboardProxyOptions, type InitMockifyerForLocalFilesystemOptions } from './core-proxy';
2
3
  export interface MockifyerInstance extends HTTPClient {
3
4
  reloadMockData: (syncFromProject?: boolean) => Promise<void>;
4
5
  clearStaleCacheEntries: () => number;
@@ -7,61 +8,14 @@ export interface MockifyerInstance extends HTTPClient {
7
8
  getClientId: () => string | undefined;
8
9
  }
9
10
  export declare function setupMockifyer(config: MockifyerConfig): MockifyerInstance;
10
- /** Options for {@link initMockifyerForDashboardProxy} — dashboard + `/api/proxy` (run `mockifyer-dashboard --provider redis`). */
11
- export interface InitMockifyerForDashboardProxyOptions {
12
- /** mockifyer-dashboard origin (e.g. `http://localhost:3002`). Not the Redis URL. */
13
- dashboardBaseUrl: string;
14
- /** Mock root for scenario file fallbacks etc. Defaults `MOCKIFYER_PATH` env or `./mock-data`. */
15
- mockDataPath?: string;
16
- /** Client lane id (`X-Mockifyer-Client-Id` / proxy envelope). Defaults `MOCKIFYER_CLIENT_ID` env. */
17
- clientId?: string;
18
- deviceId?: string;
19
- scenario?: string;
20
- /**
21
- * When **`true`**, each `/api/proxy` request sends **`"record": true`**. When **`false`**, sends **`"record": false`**.
22
- * When **omitted**, the **`record`** field is omitted so the **dashboard per-scenario** toggle applies; **`MOCKIFYER_PROXY_RECORD_ON_MISS`**
23
- * and **`MOCKIFYER_RECORD=true`** (last) still set an explicit client flag when you want env-driven recording without code.
24
- */
25
- recordOnMiss?: boolean;
26
- /**
27
- * When false, dashboard proxy stores request-only stubs on cache miss.
28
- * Defaults via {@link resolveRecordResponses} (`MOCKIFYER_RECORD_RESPONSES` env, else `false`).
29
- */
30
- recordResponses?: boolean;
31
- strictLaneScenario?: boolean;
32
- useGlobalFetch?: boolean;
33
- /** Use a local provider for mock hits before the proxy (default in-memory only) when **`/api/proxy`** is active. */
34
- databaseProvider?: MockifyerConfig['databaseProvider'];
35
- /** Additional `MockifyerConfig` fields — applied first, then preset fields win on `mockDataPath`, `proxy`, etc. */
36
- config?: Partial<MockifyerConfig>;
37
- /**
38
- * When **`true`**, skips **`GET …/api/health`** and always sets **`proxy`**.
39
- * Default **`false`**: if Redis is not healthy (or unreachable), omit **`proxy`** and use filesystem mocks + **`recordMode`** disk saves — aligns with **`setupMockifyerForReactNative`** dev fallback.
40
- */
41
- skipDashboardRedisHealthCheck?: boolean;
42
- /**
43
- * When the proxy records a response to Redis, also write the same mock under `mockDataPath` on this machine
44
- * (or via Metro when using strict RN + in-memory). Env: `MOCKIFYER_PROXY_MIRROR_TO_CLIENT`.
45
- */
46
- mirrorRecordedMocksToClient?: boolean;
47
- }
11
+ export type { InitMockifyerForDashboardProxyOptions, InitMockifyerForLocalFilesystemOptions };
48
12
  /**
49
- * Preset: **`GET /api/health`** must report Redis ready before **`proxy`** is set; otherwise filesystem mocks without proxy (like RN Hybrid fallback vs strict proxy).
50
- * Run **`mockifyer-dashboard --provider redis`** for the dashboard hop; use **`skipDashboardRedisHealthCheck`** to bypass the probe.
51
- *
13
+ * Preset: dashboard central store proxy when health check passes; otherwise filesystem mocks.
52
14
  * For full control, use {@link setupMockifyer} directly.
53
15
  */
54
16
  export declare function initMockifyerForDashboardProxy(options: InitMockifyerForDashboardProxyOptions): Promise<MockifyerInstance>;
55
- export interface InitMockifyerForLocalFilesystemOptions {
56
- mockDataPath?: string;
57
- useGlobalFetch?: boolean;
58
- recordMode?: boolean;
59
- /** Applied first; preset fills `mockDataPath` / `useGlobalFetch` when omitted. */
60
- config?: Partial<MockifyerConfig>;
61
- }
62
17
  /**
63
- * Preset: local **filesystem** mocks under {@link InitMockifyerForLocalFilesystemOptions.mockDataPath}
64
- * (default `./mock-data` or `MOCKIFYER_PATH`). No dashboard proxy.
18
+ * Preset: local filesystem mocks. No dashboard proxy.
65
19
  */
66
20
  export declare function initMockifyerForLocalFilesystem(options?: InitMockifyerForLocalFilesystemOptions): MockifyerInstance;
67
21
  /** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
package/dist/index.js CHANGED
@@ -35,32 +35,8 @@ catch (e) {
35
35
  // Import from core package
36
36
  const mockifyer_core_1 = require("@sgedda/mockifyer-core");
37
37
  const mockifyer_core_2 = require("@sgedda/mockifyer-core");
38
+ const core_proxy_1 = require("./core-proxy");
38
39
  const fetch_client_1 = require("./clients/fetch-client");
39
- const dashboard_redis_health_1 = require("./utils/dashboard-redis-health");
40
- /**
41
- * When `proxy.baseUrl` is set and `proxy.recordOnMiss` is omitted, apply `MOCKIFYER_PROXY_RECORD_ON_MISS` if set.
42
- */
43
- function applyProxyRecordOnMissEnv(config) {
44
- const proxy = config.proxy;
45
- const baseUrl = proxy?.baseUrl?.trim();
46
- if (!proxy || !baseUrl || proxy.recordOnMiss !== undefined) {
47
- return config;
48
- }
49
- const parsed = (0, mockifyer_core_1.parseProxyRecordOnMissEnv)();
50
- if (parsed === undefined) {
51
- return config;
52
- }
53
- return {
54
- ...config,
55
- proxy: {
56
- baseUrl: proxy.baseUrl,
57
- scenario: proxy.scenario,
58
- recordOnMiss: parsed,
59
- strictLaneScenario: proxy.strictLaneScenario,
60
- mirrorRecordedMocksToClient: proxy.mirrorRecordedMocksToClient,
61
- },
62
- };
63
- }
64
40
  class MockifyerClass {
65
41
  /** Best-effort dashboard network log (skipped when traffic goes through `proxy.baseUrl`). */
66
42
  logNetworkEvent(partial, correlation) {
@@ -694,55 +670,22 @@ class MockifyerClass {
694
670
  }
695
671
  const hash = rec.hash?.trim();
696
672
  const scenarioName = rec.scenarioName?.trim();
697
- if (!hash || !scenarioName) {
698
- mockifyer_core_2.logger.warn('[Mockifyer-Fetch] Proxy client mirror skipped: missing hash or scenario from proxy');
699
- return;
700
- }
701
673
  const mockData = rec.storedMock;
702
- const url = mockData?.request?.url || '';
703
- if ((0, mockifyer_core_1.shouldExcludeUrl)(url, this.config.excludedUrls)) {
704
- return;
705
- }
706
- const recExclusions = (0, mockifyer_core_1.resolveRecordingExclusions)(this.config);
707
- if ((0, mockifyer_core_1.shouldExcludeRecording)(url, recExclusions, this.config.baseUrl)) {
708
- return;
709
- }
710
- await this.databaseProviderInitPromise;
711
674
  const providerType = this.config.databaseProvider?.type;
712
- if (this.databaseProvider && providerType !== 'memory') {
713
- try {
714
- const out = this.databaseProvider.save(mockData, {
715
- relativePath: `redis/${hash}.json`,
716
- scenario: scenarioName,
717
- });
718
- if (out instanceof Promise) {
719
- await out;
720
- }
721
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (${providerType}): ${scenarioName}/redis/${hash}.json`);
722
- if (providerType === 'hybrid') {
723
- await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
724
- }
725
- }
726
- catch (e) {
727
- mockifyer_core_2.logger.error('[Mockifyer-Fetch] Proxy client mirror (provider) failed:', e);
728
- }
729
- return;
675
+ await (0, core_proxy_1.mirrorProxyRecordingToClient)({
676
+ config: this.config,
677
+ mockDataPath: this.config.mockDataPath,
678
+ recording: rec,
679
+ databaseProvider: this.databaseProvider,
680
+ databaseProviderInitPromise: this.databaseProviderInitPromise,
681
+ logPrefix: 'Mockifyer-Fetch',
682
+ });
683
+ if (providerType === 'hybrid' && hash && scenarioName && mockData) {
684
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
730
685
  }
731
- if (fs && path) {
732
- try {
733
- (0, mockifyer_core_1.ensureScenarioFolder)(this.config.mockDataPath, scenarioName);
734
- const scenarioPath = (0, mockifyer_core_1.getScenarioFolderPath)(this.config.mockDataPath, scenarioName);
735
- const filePath = path.join(scenarioPath, 'redis', `${hash}.json`);
736
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
737
- fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
738
- mockifyer_core_2.logger.info(`[Mockifyer-Fetch] Mirrored proxy recording (filesystem): ${scenarioName}/redis/${hash}.json`);
739
- }
740
- catch (e) {
741
- mockifyer_core_2.logger.error('[Mockifyer-Fetch] Proxy client mirror (Node fs) failed:', e);
742
- }
743
- return;
686
+ else if (!fs && hash && scenarioName && mockData) {
687
+ await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
744
688
  }
745
- await this.tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash);
746
689
  }
747
690
  async tryMirrorProxyRecordingViaMetro(mockData, scenarioName, hash) {
748
691
  const metroPort = process.env.METRO_PORT ? parseInt(process.env.METRO_PORT, 10) : 8081;
@@ -1172,7 +1115,7 @@ function setupMockifyer(config) {
1172
1115
  if (typeof mockifyer_core_1.installNodeInboundRequestCorrelationCapture === 'function') {
1173
1116
  (0, mockifyer_core_1.installNodeInboundRequestCorrelationCapture)();
1174
1117
  }
1175
- const resolvedConfig = applyProxyRecordOnMissEnv(config);
1118
+ const resolvedConfig = (0, core_proxy_1.applyProxyRecordOnMissEnv)(config);
1176
1119
  // Initialize logger with config level (default to 'info' if not specified)
1177
1120
  (0, mockifyer_core_2.setLogLevel)(resolvedConfig.logging || 'info');
1178
1121
  // Set environment variables for Metro middleware to read test generation config
@@ -1317,134 +1260,23 @@ function setupMockifyer(config) {
1317
1260
  (0, mockifyer_core_1.registerMockifyerInstance)(extendedClient);
1318
1261
  return extendedClient;
1319
1262
  }
1320
- /** Drops `proxy` when merging partial config so filesystem fallback cannot accidentally keep proxy. */
1321
- function omitProxyFromPartialConfig(config) {
1322
- const { proxy: _drop, ...rest } = config;
1323
- void _drop;
1324
- return rest;
1325
- }
1326
1263
  /**
1327
- * Preset: **`GET /api/health`** must report Redis ready before **`proxy`** is set; otherwise filesystem mocks without proxy (like RN Hybrid fallback vs strict proxy).
1328
- * Run **`mockifyer-dashboard --provider redis`** for the dashboard hop; use **`skipDashboardRedisHealthCheck`** to bypass the probe.
1329
- *
1264
+ * Preset: dashboard central store proxy when health check passes; otherwise filesystem mocks.
1330
1265
  * For full control, use {@link setupMockifyer} directly.
1331
1266
  */
1332
1267
  async function initMockifyerForDashboardProxy(options) {
1333
- const extra = options.config ?? {};
1334
- const dashboardBaseUrl = String(options.dashboardBaseUrl).trim();
1335
- if (!dashboardBaseUrl) {
1336
- throw new Error('initMockifyerForDashboardProxy: dashboardBaseUrl is required');
1337
- }
1338
- const mockDataPath = options.mockDataPath ??
1339
- extra.mockDataPath ??
1340
- (typeof process !== 'undefined' && process.env?.MOCKIFYER_PATH
1341
- ? process.env.MOCKIFYER_PATH
1342
- : './mock-data');
1343
- const envRecord = typeof process !== 'undefined' && process.env?.MOCKIFYER_RECORD === 'true';
1344
- const recordOnMiss = options.recordOnMiss ??
1345
- extra.proxy?.recordOnMiss ??
1346
- (0, mockifyer_core_1.parseProxyRecordOnMissEnv)() ??
1347
- (envRecord ? true : undefined);
1348
- const recordResponses = (0, mockifyer_core_1.resolveRecordResponses)(options.recordResponses ?? extra.proxy?.recordResponses);
1349
- const useRedisProxy = options.skipDashboardRedisHealthCheck === true ||
1350
- (await (0, dashboard_redis_health_1.canUseDashboardRedisProxy)(dashboardBaseUrl));
1351
- if (!useRedisProxy) {
1352
- const strictProxyOnly = (0, mockifyer_core_1.resolveStrictScenarioResolution)({
1353
- strictScenarioResolution: options.config?.strictScenarioResolution ?? extra.strictScenarioResolution,
1354
- });
1355
- mockifyer_core_2.logger.warn(`[Mockifyer] initMockifyerForDashboardProxy: "${dashboardBaseUrl}" did not report healthy Redis ` +
1356
- (strictProxyOnly
1357
- ? '(strict proxy-only — local recording disabled). '
1358
- : '(unreachable or non-Redis provider). Falling back to filesystem mocks without proxy. ') +
1359
- 'Set skipDashboardRedisHealthCheck: true to force proxy anyway.');
1360
- const stripped = omitProxyFromPartialConfig(extra);
1361
- const fallbackDb = options.databaseProvider ?? extra.databaseProvider;
1362
- const mergedInitLogFs = {
1363
- ...stripped.initLog,
1364
- headline: stripped.initLog?.headline ??
1365
- (strictProxyOnly
1366
- ? '[Mockifyer preset] Node · strict proxy-only (dashboard Redis health check failed)'
1367
- : '[Mockifyer preset] Node · filesystem (dashboard Redis health check failed)'),
1368
- };
1369
- return setupMockifyer({
1370
- ...stripped,
1371
- mockDataPath,
1372
- ...(fallbackDb !== undefined ? { databaseProvider: fallbackDb } : {}),
1373
- ...(strictProxyOnly ? { intendedProxyBaseUrl: dashboardBaseUrl.trim() } : {}),
1374
- useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1375
- clientId: options.clientId ?? extra.clientId,
1376
- deviceId: options.deviceId ?? extra.deviceId,
1377
- initLog: mergedInitLogFs,
1378
- });
1379
- }
1380
- const upstreamProxy = extra.proxy;
1381
- const mergedProxy = {
1382
- ...upstreamProxy,
1383
- baseUrl: upstreamProxy?.baseUrl ?? dashboardBaseUrl,
1384
- scenario: options.scenario ??
1385
- upstreamProxy?.scenario ??
1386
- (typeof process !== 'undefined' && process.env?.MOCKIFYER_SCENARIO?.trim()
1387
- ? process.env.MOCKIFYER_SCENARIO.trim()
1388
- : undefined),
1389
- ...(typeof recordOnMiss === 'boolean' ? { recordOnMiss } : {}),
1390
- recordResponses,
1391
- };
1392
- if (options.strictLaneScenario !== undefined ||
1393
- upstreamProxy?.strictLaneScenario !== undefined) {
1394
- mergedProxy.strictLaneScenario =
1395
- options.strictLaneScenario ?? upstreamProxy?.strictLaneScenario;
1396
- }
1397
- const envMirrorRaw = typeof process !== 'undefined'
1398
- ? String(process.env?.MOCKIFYER_PROXY_MIRROR_TO_CLIENT || '').trim().toLowerCase()
1399
- : '';
1400
- const envMirror = envMirrorRaw === '1' || envMirrorRaw === 'true' || envMirrorRaw === 'yes' || envMirrorRaw === 'on';
1401
- const mirrorRecordedMocksToClient = options.mirrorRecordedMocksToClient ??
1402
- extra.proxy?.mirrorRecordedMocksToClient ??
1403
- (envMirror ? true : undefined);
1404
- if (mirrorRecordedMocksToClient !== undefined) {
1405
- mergedProxy.mirrorRecordedMocksToClient = mirrorRecordedMocksToClient;
1406
- }
1407
- const mergedInitLogProxy = {
1408
- ...extra.initLog,
1409
- headline: extra.initLog?.headline ?? '[Mockifyer preset] Node · dashboard Redis proxy',
1410
- };
1411
- const strictScenarioResolution = extra.strictScenarioResolution ??
1412
- options.config?.strictScenarioResolution ??
1413
- true;
1414
- return setupMockifyer({
1415
- ...extra,
1416
- mockDataPath,
1417
- strictScenarioResolution,
1418
- databaseProvider: options.databaseProvider ?? extra.databaseProvider ?? { type: 'memory' },
1419
- useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1420
- clientId: options.clientId ?? extra.clientId,
1421
- deviceId: options.deviceId ?? extra.deviceId,
1422
- proxy: mergedProxy,
1423
- initLog: mergedInitLogProxy,
1424
- });
1268
+ return (0, core_proxy_1.initMockifyerForDashboardProxy)({ ...options, useGlobalFetch: options.useGlobalFetch ?? options.config?.useGlobalFetch ?? true }, setupMockifyer);
1425
1269
  }
1426
1270
  /**
1427
- * Preset: local **filesystem** mocks under {@link InitMockifyerForLocalFilesystemOptions.mockDataPath}
1428
- * (default `./mock-data` or `MOCKIFYER_PATH`). No dashboard proxy.
1271
+ * Preset: local filesystem mocks. No dashboard proxy.
1429
1272
  */
1430
1273
  function initMockifyerForLocalFilesystem(options = {}) {
1431
- const extra = options.config ?? {};
1432
- const mockDataPath = options.mockDataPath ??
1433
- extra.mockDataPath ??
1434
- (typeof process !== 'undefined' && process.env?.MOCKIFYER_PATH
1435
- ? process.env.MOCKIFYER_PATH
1436
- : './mock-data');
1437
- return setupMockifyer({
1438
- ...extra,
1439
- mockDataPath,
1440
- useGlobalFetch: options.useGlobalFetch ?? extra.useGlobalFetch ?? true,
1441
- recordMode: options.recordMode ?? extra.recordMode ?? false,
1442
- });
1274
+ return (0, core_proxy_1.initMockifyerForLocalFilesystem)({ ...options, useGlobalFetch: options.useGlobalFetch ?? options.config?.useGlobalFetch ?? true }, setupMockifyer);
1443
1275
  }
1444
1276
  /** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
1445
- var dashboard_redis_health_2 = require("./utils/dashboard-redis-health");
1446
- Object.defineProperty(exports, "canUseDashboardRedisProxy", { enumerable: true, get: function () { return dashboard_redis_health_2.canUseDashboardRedisProxy; } });
1447
- Object.defineProperty(exports, "canUseDashboardCentralProxy", { enumerable: true, get: function () { return dashboard_redis_health_2.canUseDashboardCentralProxy; } });
1277
+ var dashboard_redis_health_1 = require("./utils/dashboard-redis-health");
1278
+ Object.defineProperty(exports, "canUseDashboardRedisProxy", { enumerable: true, get: function () { return dashboard_redis_health_1.canUseDashboardRedisProxy; } });
1279
+ Object.defineProperty(exports, "canUseDashboardCentralProxy", { enumerable: true, get: function () { return dashboard_redis_health_1.canUseDashboardCentralProxy; } });
1448
1280
  // Re-export types from core
1449
1281
  __exportStar(require("@sgedda/mockifyer-core"), exports);
1450
1282
  // React Native helpers: import `@sgedda/mockifyer-fetch/react-native` (not this entry — avoids
@@ -75,6 +75,22 @@ function isMockifyerStubbedModule(moduleName) {
75
75
  return (NODE_BUILTINS.includes(moduleName) ||
76
76
  OPTIONAL_RN_PEER_MODULES.includes(moduleName));
77
77
  }
78
+ /** Metro often resolves `@sgedda/mockifyer-core` to `main` instead of the RN entry. */
79
+ function resolveMockifyerCoreReactNativeEntry(moduleName, platform) {
80
+ if (moduleName !== '@sgedda/mockifyer-core') {
81
+ return null;
82
+ }
83
+ if (platform === 'web') {
84
+ return null;
85
+ }
86
+ try {
87
+ const filePath = require.resolve('@sgedda/mockifyer-core/dist/index.react-native.js');
88
+ return { filePath, type: 'sourceFile' };
89
+ }
90
+ catch {
91
+ return null;
92
+ }
93
+ }
78
94
  /**
79
95
  * Configure Metro bundler for Mockifyer
80
96
  *
@@ -151,6 +167,10 @@ function configureMetroForMockifyer(config, options) {
151
167
  type: 'sourceFile',
152
168
  };
153
169
  }
170
+ const mockifyerCoreRn = resolveMockifyerCoreReactNativeEntry(moduleName, platform);
171
+ if (mockifyerCoreRn) {
172
+ return mockifyerCoreRn;
173
+ }
154
174
  // Call existing resolver if present
155
175
  if (existingResolveRequest) {
156
176
  const result = existingResolveRequest(context, moduleName, platform);
@@ -1,19 +1 @@
1
- /** Body shape returned by mockifyer-dashboard `GET /api/health` (subset). */
2
- export interface DashboardHealthPayload {
3
- status?: string;
4
- provider?: string;
5
- redisOk?: boolean | null;
6
- sqliteOk?: boolean | null;
7
- /** When true, dashboard central store (redis or sqlite) is ready for `/api/proxy`. */
8
- centralStoreOk?: boolean | null;
9
- }
10
- /**
11
- * True when mockifyer-dashboard responds to **`GET /api/health`** with a healthy central store
12
- * (**`provider === 'redis'`** and **`redisOk`**, or **`provider === 'sqlite'`** and **`sqliteOk`**,
13
- * or **`centralStoreOk === true`**). Same gate as React Native strict proxy / **`initMockifyerForDashboardProxy`**.
14
- */
15
- export declare function canUseDashboardCentralProxy(proxyBaseUrl: string | undefined): Promise<boolean>;
16
- /**
17
- * @deprecated Use {@link canUseDashboardCentralProxy}. Kept for existing imports.
18
- */
19
- export declare function canUseDashboardRedisProxy(proxyBaseUrl: string | undefined): Promise<boolean>;
1
+ export { canUseDashboardCentralProxy, canUseDashboardRedisProxy, type DashboardHealthPayload, } from '@sgedda/mockifyer-core/utils/dashboard-central-proxy-health';
@@ -1,49 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.canUseDashboardCentralProxy = canUseDashboardCentralProxy;
4
- exports.canUseDashboardRedisProxy = canUseDashboardRedisProxy;
5
- const join_proxy_dashboard_api_url_1 = require("./join-proxy-dashboard-api-url");
6
- const HEALTH_TIMEOUT_MS = 800;
7
- function centralStoreHealthy(data) {
8
- if (data.centralStoreOk === true) {
9
- return true;
10
- }
11
- if (data.provider === 'redis' && data.redisOk === true) {
12
- return true;
13
- }
14
- if (data.provider === 'sqlite' && data.sqliteOk === true) {
15
- return true;
16
- }
17
- return false;
18
- }
19
- /**
20
- * True when mockifyer-dashboard responds to **`GET /api/health`** with a healthy central store
21
- * (**`provider === 'redis'`** and **`redisOk`**, or **`provider === 'sqlite'`** and **`sqliteOk`**,
22
- * or **`centralStoreOk === true`**). Same gate as React Native strict proxy / **`initMockifyerForDashboardProxy`**.
23
- */
24
- async function canUseDashboardCentralProxy(proxyBaseUrl) {
25
- if (!proxyBaseUrl?.trim()) {
26
- return false;
27
- }
28
- try {
29
- const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined;
30
- const timeout = setTimeout(() => controller?.abort(), HEALTH_TIMEOUT_MS);
31
- const url = (0, join_proxy_dashboard_api_url_1.joinProxyDashboardApiUrl)(proxyBaseUrl.trim(), 'api/health');
32
- const res = await fetch(url, { signal: controller?.signal });
33
- clearTimeout(timeout);
34
- if (!res.ok) {
35
- return false;
36
- }
37
- const data = (await res.json());
38
- return centralStoreHealthy(data);
39
- }
40
- catch {
41
- return false;
42
- }
43
- }
44
- /**
45
- * @deprecated Use {@link canUseDashboardCentralProxy}. Kept for existing imports.
46
- */
47
- async function canUseDashboardRedisProxy(proxyBaseUrl) {
48
- return canUseDashboardCentralProxy(proxyBaseUrl);
49
- }
3
+ exports.canUseDashboardRedisProxy = exports.canUseDashboardCentralProxy = void 0;
4
+ var dashboard_central_proxy_health_1 = require("@sgedda/mockifyer-core/utils/dashboard-central-proxy-health");
5
+ Object.defineProperty(exports, "canUseDashboardCentralProxy", { enumerable: true, get: function () { return dashboard_central_proxy_health_1.canUseDashboardCentralProxy; } });
6
+ Object.defineProperty(exports, "canUseDashboardRedisProxy", { enumerable: true, get: function () { return dashboard_central_proxy_health_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; } });