@sgedda/mockifyer-fetch 1.8.98 → 1.8.104

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.
@@ -67,6 +67,7 @@ var __importStar = (this && this.__importStar) || (function () {
67
67
  })();
68
68
  Object.defineProperty(exports, "__esModule", { value: true });
69
69
  exports.bufferAtlasBodySpill = bufferAtlasBodySpill;
70
+ exports.persistAtlasRenderBodySpills = persistAtlasRenderBodySpills;
70
71
  exports.createMockSyncMiddleware = createMockSyncMiddleware;
71
72
  exports.startAutoSync = startAutoSync;
72
73
  exports.stopAutoSync = stopAutoSync;
@@ -308,35 +309,110 @@ function getMockFilePathLocal(mockData, dateStr) {
308
309
  return { dir, filename };
309
310
  }
310
311
  /**
311
- * Get current scenario from scenario-config.json
312
+ * Scenario folder names the dashboard accepts (one path segment).
313
+ * `pool` is the fixture-pool directory and is not a scenario.
314
+ */
315
+ const SAFE_SCENARIO_NAME = /^[a-zA-Z0-9_-]+$/;
316
+ const FIXTURE_POOL_DIR_NAME = "pool";
317
+ /** True when `candidate` is `root` or a file/directory inside it. */
318
+ function isInsideDirectory(root, candidate) {
319
+ const rootResolved = path.resolve(root);
320
+ const target = path.resolve(candidate);
321
+ const prefix = rootResolved.endsWith(path.sep)
322
+ ? rootResolved
323
+ : rootResolved + path.sep;
324
+ return target === rootResolved || target.startsWith(prefix);
325
+ }
326
+ /**
327
+ * Accept a scenario name that can be used as a single directory under mock-data.
328
+ * Rejects traversal (`..`, slashes), absolute paths, and the reserved `pool` directory.
329
+ */
330
+ function sanitizeScenarioName(raw) {
331
+ if (typeof raw !== "string") {
332
+ return null;
333
+ }
334
+ const trimmed = raw.trim();
335
+ if (!trimmed ||
336
+ trimmed === FIXTURE_POOL_DIR_NAME ||
337
+ !SAFE_SCENARIO_NAME.test(trimmed)) {
338
+ return null;
339
+ }
340
+ return trimmed;
341
+ }
342
+ /** Absolute scenario directory, or null when `scenario` would escape mock-data. */
343
+ function resolveScenarioDirectory(mockDataPath, scenario) {
344
+ const name = sanitizeScenarioName(scenario);
345
+ if (!name) {
346
+ return null;
347
+ }
348
+ const dir = path.resolve(mockDataPath, name);
349
+ if (!isInsideDirectory(mockDataPath, dir)) {
350
+ return null;
351
+ }
352
+ return dir;
353
+ }
354
+ /**
355
+ * Relative `.json` path under a scenario folder (for example `redis/<hash>.json`).
356
+ * Rejects absolute paths and `.` / `..` segments.
357
+ */
358
+ function sanitizeMockRelativePath(raw) {
359
+ const normalized = raw.trim().replace(/\\/g, "/").replace(/^\/+/, "");
360
+ if (!normalized.endsWith(".json") || normalized.includes("\0")) {
361
+ return null;
362
+ }
363
+ const segments = normalized.split("/");
364
+ if (segments.some((seg) => seg.length === 0 || seg === "." || seg === "..")) {
365
+ return null;
366
+ }
367
+ return normalized;
368
+ }
369
+ /** Absolute mock file path inside `scenarioDir`, or null when the relative path escapes. */
370
+ function resolveMockFilePath(scenarioDir, relativePath) {
371
+ const rel = sanitizeMockRelativePath(relativePath);
372
+ if (!rel) {
373
+ return null;
374
+ }
375
+ const filePath = path.resolve(scenarioDir, rel);
376
+ if (!isInsideDirectory(scenarioDir, filePath) || filePath === path.resolve(scenarioDir)) {
377
+ return null;
378
+ }
379
+ return filePath;
380
+ }
381
+ /**
382
+ * Get current scenario from env or scenario-config.json.
383
+ * Unsafe names (path traversal, reserved `pool`) are ignored.
312
384
  */
313
385
  function getCurrentScenario(mockDataPath) {
314
- // Check environment variable first
315
- if (process.env.MOCKIFYER_SCENARIO) {
316
- return process.env.MOCKIFYER_SCENARIO;
386
+ const fromEnv = sanitizeScenarioName(process.env.MOCKIFYER_SCENARIO);
387
+ if (fromEnv) {
388
+ return fromEnv;
317
389
  }
318
- // Try to load from scenario-config.json
319
390
  try {
320
391
  const configPath = path.join(mockDataPath, "scenario-config.json");
321
392
  if (fs.existsSync(configPath)) {
322
393
  const fileContent = fs.readFileSync(configPath, "utf-8");
323
394
  const config = JSON.parse(fileContent);
324
- if (config.currentScenario) {
325
- return config.currentScenario;
395
+ const fromFile = sanitizeScenarioName(config.currentScenario);
396
+ if (fromFile) {
397
+ return fromFile;
326
398
  }
327
399
  }
328
400
  }
329
- catch (error) {
401
+ catch {
330
402
  // Silently fail - file might not exist or be invalid
331
403
  }
332
404
  return DEFAULT_SCENARIO;
333
405
  }
334
406
  /**
335
- * Get scenario folder path
407
+ * Scenario folder under mock-data. Throws when `scenario` is not a safe single segment
408
+ * so a poisoned name cannot mkdir outside the mock-data tree.
336
409
  */
337
410
  function getScenarioPath(scenario, mockDataPath) {
338
- // Always create scenario subfolder, even for 'default'
339
- return path.join(mockDataPath, scenario);
411
+ const dir = resolveScenarioDirectory(mockDataPath, scenario);
412
+ if (!dir) {
413
+ throw new Error(`Invalid scenario name: ${scenario}`);
414
+ }
415
+ return dir;
340
416
  }
341
417
  /**
342
418
  * Get test generation config from options or environment variables
@@ -543,17 +619,22 @@ function saveProxyMirrorMockToProject(mockData, projectRoot, mockDataPath, scena
543
619
  error: "Mock data contains nested Mockifyer sync requests",
544
620
  };
545
621
  }
546
- const id = scenarioName.trim();
622
+ const id = sanitizeScenarioName(scenarioName);
547
623
  if (!id) {
548
- return { success: false, error: "scenarioName is required" };
624
+ return { success: false, error: "Invalid scenarioName" };
549
625
  }
550
- const normalized = relativePath.replace(/\\/g, "/").replace(/^\//, "");
626
+ const normalized = sanitizeMockRelativePath(relativePath);
551
627
  if (!normalized) {
552
- return { success: false, error: "relativePath is required" };
628
+ return { success: false, error: "Invalid relativePath" };
629
+ }
630
+ const scenarioPath = resolveScenarioDirectory(mockDataPath, id);
631
+ const filePath = scenarioPath
632
+ ? resolveMockFilePath(scenarioPath, normalized)
633
+ : null;
634
+ if (!scenarioPath || !filePath) {
635
+ return { success: false, error: "Invalid relativePath" };
553
636
  }
554
- const scenarioPath = getScenarioPath(id, mockDataPath);
555
637
  fs.mkdirSync(scenarioPath, { recursive: true });
556
- const filePath = path.join(scenarioPath, normalized);
557
638
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
558
639
  fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
559
640
  if (testConfig) {
@@ -1063,6 +1144,19 @@ function bufferAtlasBodySpill(relativePath, text) {
1063
1144
  }
1064
1145
  return { success: true, relativePath: buffered };
1065
1146
  }
1147
+ /**
1148
+ * Write hop bodies for an Atlas HTML render.
1149
+ *
1150
+ * Device uploads sit in the Metro spill buffer and are often omitted from the
1151
+ * render POST (`bodySpills` is capped at 2MB, so a max-size body never fits).
1152
+ * Flush that buffer before writing the payload. Buffering the payload first
1153
+ * evicts older spills once the in-memory cap is hit, and those files are then
1154
+ * missing from disk.
1155
+ */
1156
+ function persistAtlasRenderBodySpills(outDir, bodySpills) {
1157
+ const flushed = (0, mockifyer_core_2.flushNetworkBodySpillsToDir)(outDir);
1158
+ return flushed + (0, mockifyer_core_2.writeNetworkBodySpillMap)(outDir, bodySpills);
1159
+ }
1066
1160
  const ATLAS_HTML_CONTENT_TYPES = {
1067
1161
  ".html": "text/html; charset=utf-8",
1068
1162
  ".htm": "text/html; charset=utf-8",
@@ -1601,8 +1695,14 @@ function createMockSyncMiddleware(options) {
1601
1695
  const params = new URLSearchParams(query);
1602
1696
  const scenarioParam = params.get("scenario");
1603
1697
  const scenarioName = scenarioParam && scenarioParam.trim() !== ""
1604
- ? scenarioParam.trim()
1698
+ ? sanitizeScenarioName(scenarioParam)
1605
1699
  : getCurrentScenario(mockDataPath);
1700
+ if (!scenarioName) {
1701
+ res.statusCode = 400;
1702
+ res.setHeader("Content-Type", "application/json");
1703
+ res.end(JSON.stringify({ success: false, error: "Invalid scenario name" }));
1704
+ return;
1705
+ }
1606
1706
  const rules = (0, mockifyer_core_2.readDomainPathRulesFile)(mockDataPath, scenarioName);
1607
1707
  res.setHeader("Content-Type", "application/json");
1608
1708
  res.end(JSON.stringify({ success: true, scenario: scenarioName, rules }));
@@ -1618,8 +1718,36 @@ function createMockSyncMiddleware(options) {
1618
1718
  try {
1619
1719
  const parsed = JSON.parse(body);
1620
1720
  const scenarioName = typeof parsed.scenario === "string" && parsed.scenario.trim() !== ""
1621
- ? parsed.scenario.trim()
1721
+ ? sanitizeScenarioName(parsed.scenario)
1622
1722
  : getCurrentScenario(mockDataPath);
1723
+ if (!scenarioName) {
1724
+ res.statusCode = 400;
1725
+ res.setHeader("Content-Type", "application/json");
1726
+ res.end(JSON.stringify({ success: false, error: "Invalid scenario name" }));
1727
+ return;
1728
+ }
1729
+ if (parsed.replace === true) {
1730
+ const updates = (0, mockifyer_core_2.parseDomainPathRules)(parsed.rules ?? {});
1731
+ // Re-read to pick up concurrent new keys, then apply recordResponses updates.
1732
+ const existing = (0, mockifyer_core_2.readDomainPathRulesFile)(mockDataPath, scenarioName);
1733
+ const merged = { ...updates };
1734
+ // Add any new keys that were discovered concurrently but preserve the recordResponses updates.
1735
+ for (const [key, rule] of Object.entries(existing)) {
1736
+ if (!merged[key]) {
1737
+ merged[key] = { ...rule };
1738
+ }
1739
+ }
1740
+ (0, mockifyer_core_2.writeDomainPathRulesFile)(mockDataPath, scenarioName, merged);
1741
+ res.setHeader("Content-Type", "application/json");
1742
+ res.end(JSON.stringify({
1743
+ success: true,
1744
+ changed: true,
1745
+ replaced: true,
1746
+ scenario: scenarioName,
1747
+ rules: merged,
1748
+ }));
1749
+ return;
1750
+ }
1623
1751
  const upserts = (0, mockifyer_core_2.parseDomainPathRules)(parsed.upserts ?? parsed.rules ?? {});
1624
1752
  const existing = (0, mockifyer_core_2.readDomainPathRulesFile)(mockDataPath, scenarioName);
1625
1753
  const { rules, changed } = (0, mockifyer_core_2.mergeDomainPathRuleUpserts)(existing, upserts);
@@ -1892,7 +2020,7 @@ function createMockSyncMiddleware(options) {
1892
2020
  }
1893
2021
  (0, mockifyer_core_2.setAtlasDocMap)(doc);
1894
2022
  (0, mockifyer_core_2.setAtlasDocHtmlOutputPath)(outDir);
1895
- const spillWritten = (0, mockifyer_core_2.writeNetworkBodySpillMap)(outDir, parsed.bodySpills);
2023
+ const spillWritten = persistAtlasRenderBodySpills(outDir, parsed.bodySpills);
1896
2024
  const events = Array.isArray(parsed.events) ? parsed.events : [];
1897
2025
  const written = (0, mockifyer_core_2.writeAtlasDocHtml)(outDir, doc, events);
1898
2026
  const relativeFromRoot = path
@@ -2062,8 +2190,10 @@ function createMockSyncMiddleware(options) {
2062
2190
  try {
2063
2191
  // Check environment variable first (highest priority)
2064
2192
  if (process.env.MOCKIFYER_SCENARIO) {
2065
- mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${process.env.MOCKIFYER_SCENARIO}`);
2066
- writeScenarioResponse(process.env.MOCKIFYER_SCENARIO);
2193
+ const fromEnv = sanitizeScenarioName(process.env.MOCKIFYER_SCENARIO) ||
2194
+ DEFAULT_SCENARIO;
2195
+ mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${fromEnv}`);
2196
+ writeScenarioResponse(fromEnv);
2067
2197
  return;
2068
2198
  }
2069
2199
  const configPath = path.join(mockDataPath, "scenario-config.json");
@@ -2074,7 +2204,7 @@ function createMockSyncMiddleware(options) {
2074
2204
  const fileContent = fs.readFileSync(configPath, "utf-8");
2075
2205
  mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] File content: ${fileContent}`);
2076
2206
  const config = JSON.parse(fileContent);
2077
- const scenario = config.currentScenario || DEFAULT_SCENARIO;
2207
+ const scenario = sanitizeScenarioName(config.currentScenario) || DEFAULT_SCENARIO;
2078
2208
  mockifyer_core_1.logger.debug(`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`);
2079
2209
  writeScenarioResponse(scenario);
2080
2210
  }
@@ -2100,6 +2230,16 @@ function createMockSyncMiddleware(options) {
2100
2230
  req.on("end", () => {
2101
2231
  try {
2102
2232
  const config = JSON.parse(body);
2233
+ if (config &&
2234
+ typeof config === "object" &&
2235
+ typeof config.currentScenario === "string" &&
2236
+ config.currentScenario.trim() !== "" &&
2237
+ !sanitizeScenarioName(config.currentScenario)) {
2238
+ res.statusCode = 400;
2239
+ res.setHeader("Content-Type", "application/json");
2240
+ res.end(JSON.stringify({ success: false, error: "Invalid scenario name" }));
2241
+ return;
2242
+ }
2103
2243
  const configPath = path.join(mockDataPath, "scenario-config.json");
2104
2244
  fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
2105
2245
  res.setHeader("Content-Type", "application/json");
@@ -15,6 +15,10 @@ export interface MockifyerInstance extends HTTPClient {
15
15
  clearAllMocks: () => Promise<void>;
16
16
  setClientId: (lane: string) => void;
17
17
  getClientId: () => string | undefined;
18
+ setRecordMode: (enabled: boolean) => void;
19
+ isRecordMode: () => boolean;
20
+ setRecordResponses: (enabled: boolean) => void;
21
+ isRecordResponses: () => boolean;
18
22
  enableMockifyer: () => void;
19
23
  disableMockifyer: () => void;
20
24
  isMockifyerEnabled: () => boolean;
@@ -22,7 +26,7 @@ export interface MockifyerInstance extends HTTPClient {
22
26
  /**
23
27
  * Outcome of {@link setupMockifyerForReactNative}.
24
28
  *
25
- * - **`not_activated`** — `fetch` was not patched this run (see **`MOCKIFYER_MODE`** / `runtimeMode`: `off`, or `launch_client` without a launch-arg lane).
29
+ * - **`not_activated`** — `fetch` was not patched this run (see **`MOCKIFYER_MODE`** / `runtimeMode`: `off`, or `launch_client` without a launch-arg lane or scenario).
26
30
  * Not the same as “permanently off” unless mode is **`off`** (then launch args do not activate).
27
31
  * - **`active`** — Mockifyer initialized and patched `global.fetch`.
28
32
  * - **`failed_no_bundled_mocks`** — Activation criteria were met and `isDev` was false, but bundled mock data was missing or empty.
@@ -72,7 +76,9 @@ export interface ReactNativeMockifyerConfig {
72
76
  /**
73
77
  * When true, reads `scenario` from `react-native-launch-arguments` (optional peer).
74
78
  * Highest priority over MOCKIFYER_SCENARIO, config.scenarios, Metro scenario sync, and scenario-config.json.
75
- * When a launch `scenario` is present, Mockifyer also **starts enabled** (even with `runtimeMode: 'manual'`).
79
+ * When a launch `scenario` is present, Mockifyer **activates** (also under `launch_client`, no lane needed),
80
+ * **starts enabled** (even with `runtimeMode: 'manual'`), and sends it as the dashboard proxy scenario
81
+ * (unless `proxyScenario` is set). `runtimeMode: 'off'` still wins.
76
82
  * Set to `false` to ignore launch scenario args entirely.
77
83
  * Default: auto-detect when a non-empty launch `scenario` is present.
78
84
  */
@@ -41,26 +41,26 @@ function isMockifyerReactNativeActive(result) {
41
41
  }
42
42
  /**
43
43
  * Apply scenario from launch arguments and/or defaultScenario (highest priority in getCurrentScenario).
44
- * @returns `true` when a native launch-argument `scenario` was applied (forces runtime toggle on).
44
+ * @returns The native launch-argument `scenario` when one was applied (activates Mockifyer, forces runtime toggle on,
45
+ * and is sent as the proxy scenario); otherwise `undefined`.
45
46
  */
46
47
  function applyReactNativeScenarioOptions(options) {
47
- let appliedFromLaunchArgs = false;
48
48
  // Auto-detect launch `scenario` when present (E2E). Opt out with useLaunchArgumentsScenario: false.
49
49
  if (options.useLaunchArgumentsScenario !== false) {
50
50
  const scenarioFromLaunch = (0, mockifyer_core_2.tryGetScenarioFromLaunchArguments)();
51
51
  if (scenarioFromLaunch) {
52
52
  (0, mockifyer_core_1.setScenarioLaunchOverride)(scenarioFromLaunch, { fromLaunchArguments: true });
53
- appliedFromLaunchArgs = true;
53
+ return scenarioFromLaunch;
54
54
  }
55
55
  }
56
- if (!appliedFromLaunchArgs && options.defaultScenario !== undefined && options.defaultScenario !== null) {
56
+ if (options.defaultScenario !== undefined && options.defaultScenario !== null) {
57
57
  const t = String(options.defaultScenario).trim();
58
58
  if (t !== '') {
59
59
  // App config default — not a native launch arg; do not force runtime toggle on.
60
60
  (0, mockifyer_core_1.setScenarioLaunchOverride)(t);
61
61
  }
62
62
  }
63
- return appliedFromLaunchArgs;
63
+ return undefined;
64
64
  }
65
65
  // Lazy load bundled data (only used in production builds)
66
66
  let bundledMockData = null;
@@ -138,7 +138,11 @@ async function setupMockifyerForReactNative(options) {
138
138
  }
139
139
  }
140
140
  // Apply scenario launch override early so we know if E2E forced a scenario.
141
- const launchScenarioApplied = applyReactNativeScenarioOptions(options);
141
+ const launchScenario = applyReactNativeScenarioOptions(options);
142
+ const launchScenarioApplied = launchScenario !== undefined;
143
+ // Launch `scenario` travels on every dashboard proxy request (body override wins over lane / global scenario),
144
+ // so E2E does not need a lane mapped in the dashboard. An explicit `proxyScenario` still wins.
145
+ const effectiveProxyScenario = proxyScenario ?? launchScenario;
142
146
  if (launchScenarioApplied) {
143
147
  // Launch `scenario` arg → start enabled (wins over persisted off for this session).
144
148
  initialRuntimeEnabled = true;
@@ -164,8 +168,7 @@ async function setupMockifyerForReactNative(options) {
164
168
  }
165
169
  return 'React Native dev · hybrid (device + Metro)';
166
170
  };
167
- // Patch fetch for on / manual; launch_client only when lane id is present.
168
- // Launch `scenario` forces runtime toggle on after activation — it does not replace client id.
171
+ // Patch fetch for on / manual; launch_client when a launch lane id or launch scenario is present.
169
172
  const isEnabled = (0, mockifyer_core_2.shouldActivateMockifyerForReactNative)({
170
173
  runtimeMode: resolvedRuntimeMode,
171
174
  hasLaunchClientId: Boolean(clientIdFromLaunchArgs),
@@ -230,7 +233,7 @@ async function setupMockifyerForReactNative(options) {
230
233
  proxy: strictProxyEnabled && proxyBaseUrl
231
234
  ? {
232
235
  baseUrl: proxyBaseUrl,
233
- scenario: proxyScenario,
236
+ scenario: effectiveProxyScenario,
234
237
  recordOnMiss: proxyShouldRecordOnMiss,
235
238
  recordResponses: proxyShouldRecordResponses,
236
239
  }
@@ -292,7 +295,7 @@ async function setupMockifyerForReactNative(options) {
292
295
  proxy: proxyBaseUrl
293
296
  ? {
294
297
  baseUrl: proxyBaseUrl,
295
- scenario: proxyScenario,
298
+ scenario: effectiveProxyScenario,
296
299
  recordOnMiss: proxyShouldRecordOnMiss,
297
300
  recordResponses: proxyShouldRecordResponses,
298
301
  }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Resolve `fetch(input, init)` into the HTTPClient shape used by the global fetch patch.
3
+ *
4
+ * Native fetch reads method/headers/body from a `Request` argument when `init` omits them.
5
+ * The patch historically only inspected `init`, so `fetch(new Request(url, { method, headers, body }))`
6
+ * was treated as GET with no headers or body.
7
+ */
8
+ export interface ResolvedPatchedFetchRequest {
9
+ url: string;
10
+ method: string;
11
+ headers: Record<string, string>;
12
+ body: unknown;
13
+ }
14
+ /**
15
+ * Parse JSON text when it looks like an object/array; keep invalid JSON as the original string
16
+ * so the request still proceeds (native fetch does not throw on unparsable bodies).
17
+ */
18
+ export declare function decodeFetchBodyText(text: string): unknown;
19
+ /**
20
+ * Method, headers, and body as native `fetch(input, init)` would use them.
21
+ * `init` fields override the `Request` argument (Fetch spec). Relative URL strings
22
+ * are left unchanged — `new Request('/path')` throws in Node without a base URL.
23
+ */
24
+ export declare function resolvePatchedFetchRequest(input: RequestInfo | URL, init?: RequestInit): Promise<ResolvedPatchedFetchRequest>;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ /**
3
+ * Resolve `fetch(input, init)` into the HTTPClient shape used by the global fetch patch.
4
+ *
5
+ * Native fetch reads method/headers/body from a `Request` argument when `init` omits them.
6
+ * The patch historically only inspected `init`, so `fetch(new Request(url, { method, headers, body }))`
7
+ * was treated as GET with no headers or body.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.decodeFetchBodyText = decodeFetchBodyText;
11
+ exports.resolvePatchedFetchRequest = resolvePatchedFetchRequest;
12
+ function isRequest(input) {
13
+ return typeof Request !== 'undefined' && input instanceof Request;
14
+ }
15
+ function headersToRecord(headers) {
16
+ const out = {};
17
+ if (!headers) {
18
+ return out;
19
+ }
20
+ if (headers instanceof Headers) {
21
+ headers.forEach((value, key) => {
22
+ out[key] = value;
23
+ });
24
+ return out;
25
+ }
26
+ if (Array.isArray(headers)) {
27
+ for (const [key, value] of headers) {
28
+ out[key] = value;
29
+ }
30
+ return out;
31
+ }
32
+ for (const [key, value] of Object.entries(headers)) {
33
+ if (value !== undefined && value !== null) {
34
+ out[key] = String(value);
35
+ }
36
+ }
37
+ return out;
38
+ }
39
+ /**
40
+ * Parse JSON text when it looks like an object/array; keep invalid JSON as the original string
41
+ * so the request still proceeds (native fetch does not throw on unparsable bodies).
42
+ */
43
+ function decodeFetchBodyText(text) {
44
+ const start = text.trimStart();
45
+ if (start.startsWith('{') || start.startsWith('[')) {
46
+ try {
47
+ return JSON.parse(text);
48
+ }
49
+ catch {
50
+ return text;
51
+ }
52
+ }
53
+ return text;
54
+ }
55
+ function decodeFetchBodyInit(body) {
56
+ if (typeof body === 'string') {
57
+ return decodeFetchBodyText(body);
58
+ }
59
+ return body;
60
+ }
61
+ function urlFromFetchInput(input) {
62
+ if (typeof input === 'string') {
63
+ return input;
64
+ }
65
+ if (input instanceof URL) {
66
+ return input.toString();
67
+ }
68
+ return input.url;
69
+ }
70
+ /**
71
+ * Method, headers, and body as native `fetch(input, init)` would use them.
72
+ * `init` fields override the `Request` argument (Fetch spec). Relative URL strings
73
+ * are left unchanged — `new Request('/path')` throws in Node without a base URL.
74
+ */
75
+ async function resolvePatchedFetchRequest(input, init) {
76
+ const url = urlFromFetchInput(input);
77
+ const method = String(init?.method || (isRequest(input) ? input.method : 'GET') || 'GET');
78
+ const headers = headersToRecord(init?.headers !== undefined ? init.headers : isRequest(input) ? input.headers : undefined);
79
+ let body;
80
+ if (init !== undefined && init.body !== undefined && init.body !== null) {
81
+ body = decodeFetchBodyInit(init.body);
82
+ }
83
+ else if (isRequest(input) && method.toUpperCase() !== 'GET' && method.toUpperCase() !== 'HEAD') {
84
+ const text = await input.clone().text();
85
+ body = text ? decodeFetchBodyText(text) : undefined;
86
+ }
87
+ else {
88
+ body = undefined;
89
+ }
90
+ return { url, method, headers, body };
91
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sgedda/mockifyer-fetch",
3
- "version": "1.8.98",
3
+ "version": "1.8.104",
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,7 +49,7 @@
49
49
  },
50
50
  "license": "MIT",
51
51
  "dependencies": {
52
- "@sgedda/mockifyer-core": "^1.10.178"
52
+ "@sgedda/mockifyer-core": "^1.10.187"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@types/node": "^20.11.24",
@@ -12,6 +12,61 @@ import {
12
12
  } from '@sgedda/mockifyer-core';
13
13
  import { performDashboardProxyRequest } from '../core-proxy';
14
14
 
15
+ function headerContentType(headers: Headers): string | undefined {
16
+ const contentType = headers.get('content-type');
17
+ return contentType ? contentType.toLowerCase() : undefined;
18
+ }
19
+
20
+ /** Native Fetch body types that must not be JSON.stringified (bypass / direct upstream). */
21
+ function isNativeFetchBody(value: unknown): value is BodyInit {
22
+ return (
23
+ typeof value === 'string' ||
24
+ (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) ||
25
+ (typeof FormData !== 'undefined' && value instanceof FormData) ||
26
+ (typeof Blob !== 'undefined' && value instanceof Blob) ||
27
+ (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) ||
28
+ (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView(value))
29
+ );
30
+ }
31
+
32
+ function plainObjectToUrlEncoded(body: Record<string, unknown>): URLSearchParams {
33
+ const params = new URLSearchParams();
34
+ for (const [key, value] of Object.entries(body)) {
35
+ if (value === undefined || value === null) continue;
36
+ params.append(key, String(value));
37
+ }
38
+ return params;
39
+ }
40
+
41
+ /**
42
+ * Build a RequestInit body for direct (non-proxy) fetch.
43
+ * JSON.stringify on URLSearchParams/FormData yields "{}" and corrupts OAuth/uploads on bypass paths.
44
+ */
45
+ function buildDirectFetchBody(
46
+ data: unknown,
47
+ method: string,
48
+ headers: Headers
49
+ ): BodyInit | undefined {
50
+ const upperMethod = method.toUpperCase();
51
+ if (upperMethod === 'GET' || upperMethod === 'HEAD' || data === undefined || data === null) {
52
+ return undefined;
53
+ }
54
+
55
+ if (isNativeFetchBody(data)) {
56
+ return data;
57
+ }
58
+
59
+ if (
60
+ typeof data === 'object' &&
61
+ !Array.isArray(data) &&
62
+ headerContentType(headers)?.includes('application/x-www-form-urlencoded')
63
+ ) {
64
+ return plainObjectToUrlEncoded(data as Record<string, unknown>);
65
+ }
66
+
67
+ return JSON.stringify(data);
68
+ }
69
+
15
70
  export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
16
71
  private baseUrl?: string;
17
72
  private defaultHeaders: Record<string, string>;
@@ -117,7 +172,7 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
117
172
  const requestConfig: RequestInit = {
118
173
  method: config.method || 'GET',
119
174
  headers,
120
- body: config.data ? JSON.stringify(config.data) : undefined
175
+ body: buildDirectFetchBody(config.data, config.method || 'GET', headers),
121
176
  };
122
177
 
123
178
  // Use original fetch if available (when global fetch is patched), otherwise use global fetch
@@ -201,6 +256,16 @@ export class FetchHTTPClient extends BaseHTTPClient<any, HTTPResponse<any>> {
201
256
  };
202
257
  }
203
258
 
259
+ /** Update whether `/api/proxy` sends `record` (record-on-miss). */
260
+ setProxyRecordOnMiss(recordOnMiss: boolean | undefined): void {
261
+ this.proxyRecordOnMiss = recordOnMiss;
262
+ }
263
+
264
+ /** Update whether `/api/proxy` asks the dashboard to store response bodies. */
265
+ setProxyRecordResponses(recordResponses: boolean): void {
266
+ this.proxyRecordResponses = recordResponses;
267
+ }
268
+
204
269
  protected getDefaultHeaders(): Record<string, string> {
205
270
  return this.defaultHeaders;
206
271
  }