@sgedda/mockifyer-fetch 1.8.25 → 1.8.32

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,29 +1,95 @@
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
+ MOCKIFYER_PARENT_REQUEST_ID_HEADER,
12
+ MOCKIFYER_REQUEST_ID_HEADER,
8
13
  } from '@sgedda/mockifyer-core';
9
14
  import { joinProxyDashboardApiUrl } from '../utils/join-proxy-dashboard-api-url';
10
15
 
16
+ function buildProxyEnvelope(params: {
17
+ url: string;
18
+ method: string;
19
+ lane: string | undefined;
20
+ deviceId: string | undefined;
21
+ requestId: string | undefined;
22
+ parentRequestId: string | undefined;
23
+ headers: Record<string, string>;
24
+ body: unknown;
25
+ scenario: string | undefined;
26
+ recordOnMiss: boolean | undefined;
27
+ recordResponses: boolean;
28
+ strictLaneScenario: boolean;
29
+ }): Record<string, unknown> {
30
+ const {
31
+ url,
32
+ method,
33
+ lane,
34
+ deviceId,
35
+ requestId,
36
+ parentRequestId,
37
+ headers,
38
+ body,
39
+ scenario,
40
+ recordOnMiss,
41
+ recordResponses,
42
+ strictLaneScenario,
43
+ } = params;
44
+ const envelope: Record<string, unknown> = {
45
+ url,
46
+ method,
47
+ clientId: lane,
48
+ deviceId,
49
+ requestId,
50
+ parentRequestId,
51
+ headers,
52
+ body,
53
+ scenario,
54
+ recordResponses,
55
+ strictLaneScenario,
56
+ };
57
+ if (typeof recordOnMiss === 'boolean') {
58
+ envelope.record = recordOnMiss;
59
+ }
60
+ return envelope;
61
+ }
62
+
11
63
  export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
12
64
  private baseUrl?: string;
13
65
  private defaultHeaders: Record<string, string>;
14
66
  private proxyBaseUrl?: string;
15
67
  private proxyScenario?: string;
16
- private proxyRecordOnMiss: boolean;
68
+ /** When set, included as `record` on `/api/proxy`. When unset, dashboard per-scenario default applies. */
69
+ private proxyRecordOnMiss?: boolean;
70
+ private proxyRecordResponses: boolean;
17
71
  private getClientId?: () => string | undefined;
72
+ private getStrictLaneScenario?: () => boolean;
73
+ private getExplicitProxyScenarioContext?: () => boolean;
18
74
  private clientIdSnapshot?: string;
19
75
  private deviceId?: string;
20
76
 
21
77
  constructor(config?: {
22
78
  baseUrl?: string;
23
79
  defaultHeaders?: Record<string, string>;
24
- proxy?: { baseUrl: string; scenario?: string; recordOnMiss?: boolean };
80
+ proxy?: {
81
+ baseUrl: string;
82
+ scenario?: string;
83
+ recordOnMiss?: boolean;
84
+ recordResponses?: boolean;
85
+ strictLaneScenario?: boolean;
86
+ mirrorRecordedMocksToClient?: boolean;
87
+ };
25
88
  clientId?: string;
26
89
  getClientId?: () => string | undefined;
90
+ getStrictLaneScenario?: () => boolean;
91
+ /** When false, skip `/api/proxy` and call the real URL (devtools-friendly passthrough). */
92
+ getExplicitProxyScenarioContext?: () => boolean;
27
93
  deviceId?: string;
28
94
  }) {
29
95
  super();
@@ -31,13 +97,24 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
31
97
  this.defaultHeaders = config?.defaultHeaders || {};
32
98
  this.proxyBaseUrl = config?.proxy?.baseUrl;
33
99
  this.proxyScenario = config?.proxy?.scenario;
34
- this.proxyRecordOnMiss = config?.proxy?.recordOnMiss ?? false;
100
+ this.proxyRecordOnMiss = config?.proxy?.recordOnMiss;
101
+ this.proxyRecordResponses = config?.proxy?.recordResponses ?? false;
35
102
  this.getClientId = config?.getClientId;
103
+ this.getStrictLaneScenario = config?.getStrictLaneScenario;
104
+ this.getExplicitProxyScenarioContext = config?.getExplicitProxyScenarioContext;
36
105
  this.clientIdSnapshot = config?.clientId;
37
106
  this.deviceId = config?.deviceId;
38
107
  }
39
108
 
40
- private resolvedClientLane(): string | undefined {
109
+ private resolvedClientLane(hopHeaders?: unknown): string | undefined {
110
+ const fromHop = getOutboundMockifyerClientIdHeader(hopHeaders);
111
+ if (fromHop) {
112
+ return fromHop;
113
+ }
114
+ const fromInbound = getActiveInboundClientId();
115
+ if (fromInbound) {
116
+ return fromInbound;
117
+ }
41
118
  if (this.getClientId) {
42
119
  const v = this.getClientId();
43
120
  if (v != null && String(v).trim() !== '') {
@@ -95,10 +172,16 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
95
172
  console.warn('[FetchHTTPClient] _originalFetch not set! This may cause infinite loops if global fetch is patched.');
96
173
  }
97
174
 
98
- const lane = this.resolvedClientLane();
175
+ const lane = this.resolvedClientLane(config.headers);
176
+ const bypassMockifyer =
177
+ (config as any).__mockifyer_bypass === true || (config as any).__mockifyer_skip_save === true;
178
+ const hopRequestId = (config as any).__mockifyer_requestId as string | undefined;
179
+ const hopParentRequestId = (config as any).__mockifyer_parentRequestId as string | undefined;
180
+
181
+ const explicitProxyContext = this.getExplicitProxyScenarioContext?.() ?? true;
99
182
 
100
183
  // Proxy mode (e.g. React Native → dashboard → Redis)
101
- if (this.proxyBaseUrl) {
184
+ if (this.proxyBaseUrl && !bypassMockifyer && explicitProxyContext) {
102
185
  const proxyUrl = joinProxyDashboardApiUrl(this.proxyBaseUrl, 'api/proxy');
103
186
  const proxyResponse = await fetchFn(proxyUrl, {
104
187
  method: 'POST',
@@ -106,23 +189,31 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
106
189
  'content-type': 'application/json',
107
190
  ...(lane ? { [MOCKIFYER_CLIENT_ID_HEADER]: lane } : {}),
108
191
  ...(this.deviceId ? { [MOCKIFYER_DEVICE_ID_HEADER]: this.deviceId } : {}),
192
+ ...(hopRequestId ? { [MOCKIFYER_REQUEST_ID_HEADER]: hopRequestId } : {}),
193
+ ...(hopParentRequestId ? { [MOCKIFYER_PARENT_REQUEST_ID_HEADER]: hopParentRequestId } : {}),
109
194
  },
110
- body: JSON.stringify({
111
- url,
112
- method: requestConfig.method,
113
- clientId: lane,
114
- deviceId: this.deviceId,
115
- headers: (() => {
116
- const out: Record<string, string> = {};
117
- headers.forEach((value, key) => {
118
- out[key] = value;
119
- });
120
- return out;
121
- })(),
122
- body: config.data ?? null,
123
- scenario: this.proxyScenario,
124
- record: this.proxyRecordOnMiss,
125
- }),
195
+ body: JSON.stringify(
196
+ buildProxyEnvelope({
197
+ url,
198
+ method: String(requestConfig.method || 'GET'),
199
+ lane,
200
+ deviceId: this.deviceId,
201
+ requestId: hopRequestId,
202
+ parentRequestId: hopParentRequestId,
203
+ headers: (() => {
204
+ const out: Record<string, string> = {};
205
+ headers.forEach((value, key) => {
206
+ out[key] = value;
207
+ });
208
+ return out;
209
+ })(),
210
+ body: config.data ?? null,
211
+ scenario: this.proxyScenario,
212
+ recordOnMiss: this.proxyRecordOnMiss,
213
+ recordResponses: this.proxyRecordResponses,
214
+ strictLaneScenario: this.getStrictLaneScenario?.() ?? true,
215
+ })
216
+ ),
126
217
  });
127
218
  if (!proxyResponse.ok) {
128
219
  const txt = await proxyResponse.text();
@@ -136,7 +227,7 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
136
227
  const hashShort = hash ? `${hash.slice(0, 8)}…` : '';
137
228
  const laneLabel = lane ? lane : '—';
138
229
  const kind = source === 'redis' ? 'mock hit' : 'upstream';
139
- console.log(
230
+ logger.debug(
140
231
  `[Mockifyer-Fetch] Proxy ${kind}: ${requestConfig.method} ${url} ${
141
232
  hashShort ? `(hash=${hashShort}) ` : ''
142
233
  }(lane=${laneLabel})`
@@ -149,19 +240,43 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
149
240
  const status = payload?.response?.status ?? 200;
150
241
  const responseHeaders: Record<string, string> = payload?.response?.headers ?? {};
151
242
 
243
+ const scenarioResolution = payload?.scenarioResolution as
244
+ | { scenario?: string | null }
245
+ | undefined;
246
+ const scenarioName =
247
+ typeof scenarioResolution?.scenario === 'string' && scenarioResolution.scenario.trim()
248
+ ? scenarioResolution.scenario.trim()
249
+ : undefined;
250
+
251
+ const mockifyerProxyRecording =
252
+ payload?.recordedToStore === true && payload?.storedMock
253
+ ? {
254
+ recordedToStore: true as const,
255
+ storedMock: payload.storedMock,
256
+ hash: typeof payload.hash === 'string' ? payload.hash : undefined,
257
+ scenarioName,
258
+ }
259
+ : undefined;
260
+
152
261
  return {
153
262
  data,
154
263
  status,
155
264
  statusText: String(status),
156
265
  headers: responseHeaders,
157
266
  config,
267
+ mockifyerProxyRecording,
158
268
  };
159
269
  }
160
270
 
161
- if (lane && !getOutboundMockifyerClientIdHeader(headers)) {
271
+ if (!bypassMockifyer && lane && !getOutboundMockifyerClientIdHeader(headers)) {
162
272
  headers.set(MOCKIFYER_CLIENT_ID_HEADER, lane);
163
273
  }
164
- if (this.deviceId && String(this.deviceId).trim() && !getOutboundMockifyerDeviceIdHeader(headers)) {
274
+ if (
275
+ !bypassMockifyer &&
276
+ this.deviceId &&
277
+ String(this.deviceId).trim() &&
278
+ !getOutboundMockifyerDeviceIdHeader(headers)
279
+ ) {
165
280
  headers.set(MOCKIFYER_DEVICE_ID_HEADER, String(this.deviceId).trim());
166
281
  }
167
282