@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.
@@ -1,13 +1,15 @@
1
- import { BaseHTTPClient } from '@sgedda/mockifyer-core';
2
- import { HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
1
+ import { BaseHTTPClient, HTTPRequestConfig, HTTPResponse } from '@sgedda/mockifyer-core';
3
2
  export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
4
3
  private baseUrl?;
5
4
  private defaultHeaders;
6
5
  private proxyBaseUrl?;
7
6
  private proxyScenario?;
8
- private proxyRecordOnMiss;
7
+ /** When set, included as `record` on `/api/proxy`. When unset, dashboard per-scenario default applies. */
8
+ private proxyRecordOnMiss?;
9
+ private proxyRecordResponses;
9
10
  private getClientId?;
10
11
  private getStrictLaneScenario?;
12
+ private getExplicitProxyScenarioContext?;
11
13
  private clientIdSnapshot?;
12
14
  private deviceId?;
13
15
  constructor(config?: {
@@ -17,11 +19,15 @@ export declare class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<an
17
19
  baseUrl: string;
18
20
  scenario?: string;
19
21
  recordOnMiss?: boolean;
22
+ recordResponses?: boolean;
20
23
  strictLaneScenario?: boolean;
24
+ mirrorRecordedMocksToClient?: boolean;
21
25
  };
22
26
  clientId?: string;
23
27
  getClientId?: () => string | undefined;
24
28
  getStrictLaneScenario?: () => boolean;
29
+ /** When false, skip `/api/proxy` and call the real URL (devtools-friendly passthrough). */
30
+ getExplicitProxyScenarioContext?: () => boolean;
25
31
  deviceId?: string;
26
32
  });
27
33
  private resolvedClientLane;
@@ -2,8 +2,6 @@
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");
6
- const join_proxy_dashboard_api_url_1 = require("../utils/join-proxy-dashboard-api-url");
7
5
  class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
8
6
  constructor(config) {
9
7
  super();
@@ -11,13 +9,23 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
11
9
  this.defaultHeaders = config?.defaultHeaders || {};
12
10
  this.proxyBaseUrl = config?.proxy?.baseUrl;
13
11
  this.proxyScenario = config?.proxy?.scenario;
14
- this.proxyRecordOnMiss = config?.proxy?.recordOnMiss ?? false;
12
+ this.proxyRecordOnMiss = config?.proxy?.recordOnMiss;
13
+ this.proxyRecordResponses = config?.proxy?.recordResponses ?? false;
15
14
  this.getClientId = config?.getClientId;
16
15
  this.getStrictLaneScenario = config?.getStrictLaneScenario;
16
+ this.getExplicitProxyScenarioContext = config?.getExplicitProxyScenarioContext;
17
17
  this.clientIdSnapshot = config?.clientId;
18
18
  this.deviceId = config?.deviceId;
19
19
  }
20
- resolvedClientLane() {
20
+ resolvedClientLane(hopHeaders) {
21
+ const fromHop = (0, mockifyer_core_1.getOutboundMockifyerClientIdHeader)(hopHeaders);
22
+ if (fromHop) {
23
+ return fromHop;
24
+ }
25
+ const fromInbound = (0, mockifyer_core_1.getActiveInboundClientId)();
26
+ if (fromInbound) {
27
+ return fromInbound;
28
+ }
21
29
  if (this.getClientId) {
22
30
  const v = this.getClientId();
23
31
  if (v != null && String(v).trim() !== '') {
@@ -64,74 +72,47 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
64
72
  body: config.data ? JSON.stringify(config.data) : undefined
65
73
  };
66
74
  // Use original fetch if available (when global fetch is patched), otherwise use global fetch
67
- // CRITICAL: Always use _originalFetch if available to prevent infinite loops
68
75
  const fetchFn = this._originalFetch || fetch;
69
76
  if (!this._originalFetch) {
70
77
  console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
71
78
  }
72
- const lane = this.resolvedClientLane();
73
- // Proxy mode (e.g. React Native → dashboard → Redis)
74
- if (this.proxyBaseUrl) {
75
- const proxyUrl = (0, join_proxy_dashboard_api_url_1.joinProxyDashboardApiUrl)(this.proxyBaseUrl, 'api/proxy');
76
- const proxyResponse = await fetchFn(proxyUrl, {
77
- method: 'POST',
78
- headers: {
79
- 'content-type': 'application/json',
80
- ...(lane ? { [mockifyer_core_2.MOCKIFYER_CLIENT_ID_HEADER]: lane } : {}),
81
- ...(this.deviceId ? { [mockifyer_core_2.MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
82
- },
83
- body: JSON.stringify({
84
- url,
85
- method: requestConfig.method,
86
- clientId: lane,
87
- deviceId: this.deviceId,
88
- headers: (() => {
89
- const out = {};
90
- headers.forEach((value, key) => {
91
- out[key] = value;
92
- });
93
- return out;
94
- })(),
95
- body: config.data ?? null,
96
- scenario: this.proxyScenario,
97
- record: this.proxyRecordOnMiss,
98
- strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
99
- }),
79
+ const lane = this.resolvedClientLane(config.headers);
80
+ const bypassMockifyer = config.__mockifyer_bypass === true || config.__mockifyer_skip_save === true;
81
+ const hopRequestId = config.__mockifyer_requestId;
82
+ const hopParentRequestId = config.__mockifyer_parentRequestId;
83
+ const explicitProxyContext = this.getExplicitProxyScenarioContext?.() ?? true;
84
+ if (this.proxyBaseUrl && !bypassMockifyer && explicitProxyContext) {
85
+ const headerRecord = {};
86
+ headers.forEach((value, key) => {
87
+ headerRecord[key] = value;
100
88
  });
101
- if (!proxyResponse.ok) {
102
- const txt = await proxyResponse.text();
103
- throw new Error(`[FetchHTTPClient] Proxy error: ${proxyResponse.status} ${txt}`);
104
- }
105
- const payload = await proxyResponse.json();
106
- try {
107
- const source = String(payload?.source || '');
108
- const hash = typeof payload?.hash === 'string' ? payload.hash : '';
109
- if (source) {
110
- const hashShort = hash ? `${hash.slice(0, 8)}…` : '';
111
- const laneLabel = lane ? lane : '—';
112
- const kind = source === 'redis' ? 'mock hit' : 'upstream';
113
- console.log(`[Mockifyer-Fetch] Proxy ${kind}: ${requestConfig.method} ${url} ${hashShort ? `(hash=${hashShort}) ` : ''}(lane=${laneLabel})`);
114
- }
115
- }
116
- catch {
117
- // ignore logging failures
118
- }
119
- const data = payload?.response?.data;
120
- const status = payload?.response?.status ?? 200;
121
- const responseHeaders = payload?.response?.headers ?? {};
122
- return {
123
- data,
124
- status,
125
- statusText: String(status),
126
- headers: responseHeaders,
89
+ return (0, mockifyer_core_1.performDashboardProxyRequest)({
90
+ proxyBaseUrl: this.proxyBaseUrl,
91
+ url,
92
+ method: String(requestConfig.method || 'GET'),
93
+ headers: headerRecord,
94
+ body: config.data ?? null,
95
+ lane,
96
+ deviceId: this.deviceId,
97
+ requestId: hopRequestId,
98
+ parentRequestId: hopParentRequestId,
99
+ scenario: this.proxyScenario,
100
+ recordOnMiss: this.proxyRecordOnMiss,
101
+ recordResponses: this.proxyRecordResponses,
102
+ strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
127
103
  config,
128
- };
104
+ fetchFn,
105
+ logTag: 'Mockifyer-Fetch',
106
+ });
129
107
  }
130
- if (lane && !(0, mockifyer_core_2.getOutboundMockifyerClientIdHeader)(headers)) {
131
- headers.set(mockifyer_core_2.MOCKIFYER_CLIENT_ID_HEADER, lane);
108
+ if (!bypassMockifyer && lane && !(0, mockifyer_core_1.getOutboundMockifyerClientIdHeader)(headers)) {
109
+ headers.set(mockifyer_core_1.MOCKIFYER_CLIENT_ID_HEADER, lane);
132
110
  }
133
- if (this.deviceId && String(this.deviceId).trim() && !(0, mockifyer_core_2.getOutboundMockifyerDeviceIdHeader)(headers)) {
134
- headers.set(mockifyer_core_2.MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
111
+ if (!bypassMockifyer &&
112
+ this.deviceId &&
113
+ String(this.deviceId).trim() &&
114
+ !(0, mockifyer_core_1.getOutboundMockifyerDeviceIdHeader)(headers)) {
115
+ headers.set(mockifyer_core_1.MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
135
116
  }
136
117
  const response = await fetchFn(url, requestConfig);
137
118
  const contentType = response.headers.get('content-type') || '';
@@ -145,7 +126,6 @@ class FetchHTTPClient extends mockifyer_core_1.BaseHTTPClient {
145
126
  data = rawText;
146
127
  }
147
128
  }
148
- // Convert response Headers to Record<string, string>
149
129
  const responseHeaders = {};
150
130
  response.headers.forEach((value, key) => {
151
131
  responseHeaders[key] = value;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { MockifyerConfig, HTTPClient } from '@sgedda/mockifyer-core';
1
+ import { MockifyerConfig, HTTPClient, type InitMockifyerForDashboardProxyOptions, type InitMockifyerForLocalFilesystemOptions } from '@sgedda/mockifyer-core';
2
2
  export interface MockifyerInstance extends HTTPClient {
3
3
  reloadMockData: (syncFromProject?: boolean) => Promise<void>;
4
4
  clearStaleCacheEntries: () => number;
@@ -7,5 +7,16 @@ export interface MockifyerInstance extends HTTPClient {
7
7
  getClientId: () => string | undefined;
8
8
  }
9
9
  export declare function setupMockifyer(config: MockifyerConfig): MockifyerInstance;
10
+ export type { InitMockifyerForDashboardProxyOptions, InitMockifyerForLocalFilesystemOptions };
11
+ /**
12
+ * Preset: dashboard central store proxy when health check passes; otherwise filesystem mocks.
13
+ * For full control, use {@link setupMockifyer} directly.
14
+ */
15
+ export declare function initMockifyerForDashboardProxy(options: InitMockifyerForDashboardProxyOptions): Promise<MockifyerInstance>;
16
+ /**
17
+ * Preset: local filesystem mocks. No dashboard proxy.
18
+ */
19
+ export declare function initMockifyerForLocalFilesystem(options?: InitMockifyerForLocalFilesystemOptions): MockifyerInstance;
20
+ /** Shared with {@link setupMockifyerForReactNative} strict-proxy branching. */
21
+ export { canUseDashboardRedisProxy, canUseDashboardCentralProxy, } from './utils/dashboard-redis-health';
10
22
  export * from '@sgedda/mockifyer-core';
11
- export * from './react-native';