@sgedda/mockifyer-fetch 1.8.100 → 1.8.106
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.
- package/dist/clients/fetch-client.d.ts +4 -0
- package/dist/clients/fetch-client.js +50 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +207 -65
- package/dist/metro-sync-middleware.d.ts +10 -0
- package/dist/metro-sync-middleware.js +159 -73
- package/dist/react-native.d.ts +4 -0
- package/dist/utils/resolve-patched-fetch-request.d.ts +24 -0
- package/dist/utils/resolve-patched-fetch-request.js +91 -0
- package/package.json +3 -3
- package/src/clients/fetch-client.ts +66 -1
- package/src/index.ts +251 -68
- package/src/metro-sync-middleware.ts +201 -76
- package/src/react-native.ts +4 -0
- package/src/utils/resolve-patched-fetch-request.ts +105 -0
|
@@ -39,13 +39,14 @@ import {
|
|
|
39
39
|
MockData,
|
|
40
40
|
TestGenerator,
|
|
41
41
|
TestGenerationOptions,
|
|
42
|
+
getMockFilePath,
|
|
43
|
+
logger,
|
|
42
44
|
} from "@sgedda/mockifyer-core";
|
|
43
|
-
import { logger } from "@sgedda/mockifyer-core";
|
|
44
45
|
import {
|
|
45
46
|
POOL_ID_PATTERN,
|
|
46
47
|
loadPoolResponseItem,
|
|
47
48
|
type PoolResponseItem,
|
|
48
|
-
|
|
49
|
+
mergeDiscoveredDomainPathUpserts,
|
|
49
50
|
parseDomainPathRules,
|
|
50
51
|
readDomainPathRulesFile,
|
|
51
52
|
writeDomainPathRulesFile,
|
|
@@ -366,78 +367,111 @@ function collectRequestBodyUtf8(
|
|
|
366
367
|
req.on("error", (e: Error) => finish(e, ""));
|
|
367
368
|
}
|
|
368
369
|
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
type = "rest";
|
|
394
|
-
remainingSegments = pathSegments.slice(restIdx + 1);
|
|
395
|
-
} else {
|
|
396
|
-
type = "";
|
|
397
|
-
remainingSegments = pathSegments;
|
|
370
|
+
/**
|
|
371
|
+
* Scenario folder names the dashboard accepts (one path segment).
|
|
372
|
+
* `pool` is the fixture-pool directory and is not a scenario.
|
|
373
|
+
*/
|
|
374
|
+
const SAFE_SCENARIO_NAME = /^[a-zA-Z0-9_-]+$/;
|
|
375
|
+
const FIXTURE_POOL_DIR_NAME = "pool";
|
|
376
|
+
|
|
377
|
+
/** True when `candidate` is `root` or a file/directory inside it. */
|
|
378
|
+
function isInsideDirectory(root: string, candidate: string): boolean {
|
|
379
|
+
const rootResolved = path.resolve(root);
|
|
380
|
+
const target = path.resolve(candidate);
|
|
381
|
+
const prefix = rootResolved.endsWith(path.sep)
|
|
382
|
+
? rootResolved
|
|
383
|
+
: rootResolved + path.sep;
|
|
384
|
+
return target === rootResolved || target.startsWith(prefix);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Accept a scenario name that can be used as a single directory under mock-data.
|
|
389
|
+
* Rejects traversal (`..`, slashes), absolute paths, and the reserved `pool` directory.
|
|
390
|
+
*/
|
|
391
|
+
function sanitizeScenarioName(raw: unknown): string | null {
|
|
392
|
+
if (typeof raw !== "string") {
|
|
393
|
+
return null;
|
|
398
394
|
}
|
|
399
|
-
|
|
400
|
-
if (
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
const
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
395
|
+
const trimmed = raw.trim();
|
|
396
|
+
if (
|
|
397
|
+
!trimmed ||
|
|
398
|
+
trimmed === FIXTURE_POOL_DIR_NAME ||
|
|
399
|
+
!SAFE_SCENARIO_NAME.test(trimmed)
|
|
400
|
+
) {
|
|
401
|
+
return null;
|
|
402
|
+
}
|
|
403
|
+
return trimmed;
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/** Absolute scenario directory, or null when `scenario` would escape mock-data. */
|
|
407
|
+
function resolveScenarioDirectory(
|
|
408
|
+
mockDataPath: string,
|
|
409
|
+
scenario: string,
|
|
410
|
+
): string | null {
|
|
411
|
+
const name = sanitizeScenarioName(scenario);
|
|
412
|
+
if (!name) {
|
|
413
|
+
return null;
|
|
414
|
+
}
|
|
415
|
+
const dir = path.resolve(mockDataPath, name);
|
|
416
|
+
if (!isInsideDirectory(mockDataPath, dir)) {
|
|
417
|
+
return null;
|
|
418
|
+
}
|
|
419
|
+
return dir;
|
|
419
420
|
}
|
|
420
421
|
|
|
421
422
|
/**
|
|
422
|
-
*
|
|
423
|
+
* Relative `.json` path under a scenario folder (for example `redis/<hash>.json`).
|
|
424
|
+
* Rejects absolute paths and `.` / `..` segments.
|
|
425
|
+
*/
|
|
426
|
+
function sanitizeMockRelativePath(raw: string): string | null {
|
|
427
|
+
const normalized = raw.trim().replace(/\\/g, "/").replace(/^\/+/, "");
|
|
428
|
+
if (!normalized.endsWith(".json") || normalized.includes("\0")) {
|
|
429
|
+
return null;
|
|
430
|
+
}
|
|
431
|
+
const segments = normalized.split("/");
|
|
432
|
+
if (segments.some((seg) => seg.length === 0 || seg === "." || seg === "..")) {
|
|
433
|
+
return null;
|
|
434
|
+
}
|
|
435
|
+
return normalized;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Absolute mock file path inside `scenarioDir`, or null when the relative path escapes. */
|
|
439
|
+
function resolveMockFilePath(
|
|
440
|
+
scenarioDir: string,
|
|
441
|
+
relativePath: string,
|
|
442
|
+
): string | null {
|
|
443
|
+
const rel = sanitizeMockRelativePath(relativePath);
|
|
444
|
+
if (!rel) {
|
|
445
|
+
return null;
|
|
446
|
+
}
|
|
447
|
+
const filePath = path.resolve(scenarioDir, rel);
|
|
448
|
+
if (!isInsideDirectory(scenarioDir, filePath) || filePath === path.resolve(scenarioDir)) {
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
return filePath;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* Get current scenario from env or scenario-config.json.
|
|
456
|
+
* Unsafe names (path traversal, reserved `pool`) are ignored.
|
|
423
457
|
*/
|
|
424
458
|
function getCurrentScenario(mockDataPath: string): string {
|
|
425
|
-
|
|
426
|
-
if (
|
|
427
|
-
return
|
|
459
|
+
const fromEnv = sanitizeScenarioName(process.env.MOCKIFYER_SCENARIO);
|
|
460
|
+
if (fromEnv) {
|
|
461
|
+
return fromEnv;
|
|
428
462
|
}
|
|
429
463
|
|
|
430
|
-
// Try to load from scenario-config.json
|
|
431
464
|
try {
|
|
432
465
|
const configPath = path.join(mockDataPath, "scenario-config.json");
|
|
433
466
|
if (fs.existsSync(configPath)) {
|
|
434
467
|
const fileContent = fs.readFileSync(configPath, "utf-8");
|
|
435
468
|
const config = JSON.parse(fileContent);
|
|
436
|
-
|
|
437
|
-
|
|
469
|
+
const fromFile = sanitizeScenarioName(config.currentScenario);
|
|
470
|
+
if (fromFile) {
|
|
471
|
+
return fromFile;
|
|
438
472
|
}
|
|
439
473
|
}
|
|
440
|
-
} catch
|
|
474
|
+
} catch {
|
|
441
475
|
// Silently fail - file might not exist or be invalid
|
|
442
476
|
}
|
|
443
477
|
|
|
@@ -445,11 +479,15 @@ function getCurrentScenario(mockDataPath: string): string {
|
|
|
445
479
|
}
|
|
446
480
|
|
|
447
481
|
/**
|
|
448
|
-
*
|
|
482
|
+
* Scenario folder under mock-data. Throws when `scenario` is not a safe single segment
|
|
483
|
+
* so a poisoned name cannot mkdir outside the mock-data tree.
|
|
449
484
|
*/
|
|
450
485
|
function getScenarioPath(scenario: string, mockDataPath: string): string {
|
|
451
|
-
|
|
452
|
-
|
|
486
|
+
const dir = resolveScenarioDirectory(mockDataPath, scenario);
|
|
487
|
+
if (!dir) {
|
|
488
|
+
throw new Error(`Invalid scenario name: ${scenario}`);
|
|
489
|
+
}
|
|
490
|
+
return dir;
|
|
453
491
|
}
|
|
454
492
|
|
|
455
493
|
/**
|
|
@@ -667,7 +705,7 @@ function saveMockToProjectFolder(
|
|
|
667
705
|
.replace(/T/, "_")
|
|
668
706
|
.replace(/\..+/, "")
|
|
669
707
|
.replace(/:/g, "-");
|
|
670
|
-
const { dir, filename } =
|
|
708
|
+
const { dir, filename } = getMockFilePath(mockData, dateStr);
|
|
671
709
|
const fullDir = path.join(scenarioPath, dir);
|
|
672
710
|
const filePath = path.join(fullDir, filename);
|
|
673
711
|
|
|
@@ -731,17 +769,22 @@ function saveProxyMirrorMockToProject(
|
|
|
731
769
|
error: "Mock data contains nested Mockifyer sync requests",
|
|
732
770
|
};
|
|
733
771
|
}
|
|
734
|
-
const id = scenarioName
|
|
772
|
+
const id = sanitizeScenarioName(scenarioName);
|
|
735
773
|
if (!id) {
|
|
736
|
-
return { success: false, error: "scenarioName
|
|
774
|
+
return { success: false, error: "Invalid scenarioName" };
|
|
737
775
|
}
|
|
738
|
-
const normalized = relativePath
|
|
776
|
+
const normalized = sanitizeMockRelativePath(relativePath);
|
|
739
777
|
if (!normalized) {
|
|
740
|
-
return { success: false, error: "relativePath
|
|
778
|
+
return { success: false, error: "Invalid relativePath" };
|
|
779
|
+
}
|
|
780
|
+
const scenarioPath = resolveScenarioDirectory(mockDataPath, id);
|
|
781
|
+
const filePath = scenarioPath
|
|
782
|
+
? resolveMockFilePath(scenarioPath, normalized)
|
|
783
|
+
: null;
|
|
784
|
+
if (!scenarioPath || !filePath) {
|
|
785
|
+
return { success: false, error: "Invalid relativePath" };
|
|
741
786
|
}
|
|
742
|
-
const scenarioPath = getScenarioPath(id, mockDataPath);
|
|
743
787
|
fs.mkdirSync(scenarioPath, { recursive: true });
|
|
744
|
-
const filePath = path.join(scenarioPath, normalized);
|
|
745
788
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
746
789
|
fs.writeFileSync(filePath, JSON.stringify(mockData, null, 2));
|
|
747
790
|
if (testConfig) {
|
|
@@ -1397,6 +1440,23 @@ export function bufferAtlasBodySpill(
|
|
|
1397
1440
|
return { success: true, relativePath: buffered };
|
|
1398
1441
|
}
|
|
1399
1442
|
|
|
1443
|
+
/**
|
|
1444
|
+
* Write hop bodies for an Atlas HTML render.
|
|
1445
|
+
*
|
|
1446
|
+
* Device uploads sit in the Metro spill buffer and are often omitted from the
|
|
1447
|
+
* render POST (`bodySpills` is capped at 2MB, so a max-size body never fits).
|
|
1448
|
+
* Flush that buffer before writing the payload. Buffering the payload first
|
|
1449
|
+
* evicts older spills once the in-memory cap is hit, and those files are then
|
|
1450
|
+
* missing from disk.
|
|
1451
|
+
*/
|
|
1452
|
+
export function persistAtlasRenderBodySpills(
|
|
1453
|
+
outDir: string,
|
|
1454
|
+
bodySpills: Record<string, string> | undefined,
|
|
1455
|
+
): number {
|
|
1456
|
+
const flushed = flushNetworkBodySpillsToDir(outDir);
|
|
1457
|
+
return flushed + writeNetworkBodySpillMap(outDir, bodySpills);
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1400
1460
|
const ATLAS_HTML_CONTENT_TYPES: Record<string, string> = {
|
|
1401
1461
|
".html": "text/html; charset=utf-8",
|
|
1402
1462
|
".htm": "text/html; charset=utf-8",
|
|
@@ -2053,8 +2113,16 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2053
2113
|
const scenarioParam = params.get("scenario");
|
|
2054
2114
|
const scenarioName =
|
|
2055
2115
|
scenarioParam && scenarioParam.trim() !== ""
|
|
2056
|
-
? scenarioParam
|
|
2116
|
+
? sanitizeScenarioName(scenarioParam)
|
|
2057
2117
|
: getCurrentScenario(mockDataPath);
|
|
2118
|
+
if (!scenarioName) {
|
|
2119
|
+
res.statusCode = 400;
|
|
2120
|
+
res.setHeader("Content-Type", "application/json");
|
|
2121
|
+
res.end(
|
|
2122
|
+
JSON.stringify({ success: false, error: "Invalid scenario name" }),
|
|
2123
|
+
);
|
|
2124
|
+
return;
|
|
2125
|
+
}
|
|
2058
2126
|
const rules = readDomainPathRulesFile(mockDataPath, scenarioName);
|
|
2059
2127
|
res.setHeader("Content-Type", "application/json");
|
|
2060
2128
|
res.end(JSON.stringify({ success: true, scenario: scenarioName, rules }));
|
|
@@ -2073,16 +2141,52 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2073
2141
|
scenario?: string;
|
|
2074
2142
|
upserts?: DomainPathRulesMap;
|
|
2075
2143
|
rules?: DomainPathRulesMap;
|
|
2144
|
+
/** When true, replace the scenario file with `rules` (enable-record migrations). */
|
|
2145
|
+
replace?: boolean;
|
|
2076
2146
|
};
|
|
2077
2147
|
const scenarioName =
|
|
2078
2148
|
typeof parsed.scenario === "string" && parsed.scenario.trim() !== ""
|
|
2079
|
-
? parsed.scenario
|
|
2149
|
+
? sanitizeScenarioName(parsed.scenario)
|
|
2080
2150
|
: getCurrentScenario(mockDataPath);
|
|
2151
|
+
if (!scenarioName) {
|
|
2152
|
+
res.statusCode = 400;
|
|
2153
|
+
res.setHeader("Content-Type", "application/json");
|
|
2154
|
+
res.end(
|
|
2155
|
+
JSON.stringify({ success: false, error: "Invalid scenario name" }),
|
|
2156
|
+
);
|
|
2157
|
+
return;
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
if (parsed.replace === true) {
|
|
2161
|
+
const updates = parseDomainPathRules(parsed.rules ?? {});
|
|
2162
|
+
// Re-read to pick up concurrent new keys, then apply recordResponses updates.
|
|
2163
|
+
const existing = readDomainPathRulesFile(mockDataPath, scenarioName);
|
|
2164
|
+
const merged: DomainPathRulesMap = { ...updates };
|
|
2165
|
+
// Add any new keys that were discovered concurrently but preserve the recordResponses updates.
|
|
2166
|
+
for (const [key, rule] of Object.entries(existing)) {
|
|
2167
|
+
if (!merged[key]) {
|
|
2168
|
+
merged[key] = { ...rule };
|
|
2169
|
+
}
|
|
2170
|
+
}
|
|
2171
|
+
writeDomainPathRulesFile(mockDataPath, scenarioName, merged);
|
|
2172
|
+
res.setHeader("Content-Type", "application/json");
|
|
2173
|
+
res.end(
|
|
2174
|
+
JSON.stringify({
|
|
2175
|
+
success: true,
|
|
2176
|
+
changed: true,
|
|
2177
|
+
replaced: true,
|
|
2178
|
+
scenario: scenarioName,
|
|
2179
|
+
rules: merged,
|
|
2180
|
+
}),
|
|
2181
|
+
);
|
|
2182
|
+
return;
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2081
2185
|
const upserts = parseDomainPathRules(
|
|
2082
2186
|
parsed.upserts ?? parsed.rules ?? {},
|
|
2083
2187
|
);
|
|
2084
2188
|
const existing = readDomainPathRulesFile(mockDataPath, scenarioName);
|
|
2085
|
-
const { rules, changed } =
|
|
2189
|
+
const { rules, changed } = mergeDiscoveredDomainPathUpserts(
|
|
2086
2190
|
existing,
|
|
2087
2191
|
upserts,
|
|
2088
2192
|
);
|
|
@@ -2447,7 +2551,10 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2447
2551
|
}
|
|
2448
2552
|
setAtlasDocMap(doc);
|
|
2449
2553
|
setAtlasDocHtmlOutputPath(outDir);
|
|
2450
|
-
const spillWritten =
|
|
2554
|
+
const spillWritten = persistAtlasRenderBodySpills(
|
|
2555
|
+
outDir,
|
|
2556
|
+
parsed.bodySpills,
|
|
2557
|
+
);
|
|
2451
2558
|
const events = Array.isArray(parsed.events) ? parsed.events : [];
|
|
2452
2559
|
const written = writeAtlasDocHtml(outDir, doc, events);
|
|
2453
2560
|
const relativeFromRoot = path
|
|
@@ -2654,10 +2761,13 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2654
2761
|
try {
|
|
2655
2762
|
// Check environment variable first (highest priority)
|
|
2656
2763
|
if (process.env.MOCKIFYER_SCENARIO) {
|
|
2764
|
+
const fromEnv =
|
|
2765
|
+
sanitizeScenarioName(process.env.MOCKIFYER_SCENARIO) ||
|
|
2766
|
+
DEFAULT_SCENARIO;
|
|
2657
2767
|
logger.debug(
|
|
2658
|
-
`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${
|
|
2768
|
+
`[MetroSyncMiddleware] Using scenario from MOCKIFYER_SCENARIO env var: ${fromEnv}`,
|
|
2659
2769
|
);
|
|
2660
|
-
writeScenarioResponse(
|
|
2770
|
+
writeScenarioResponse(fromEnv);
|
|
2661
2771
|
return;
|
|
2662
2772
|
}
|
|
2663
2773
|
|
|
@@ -2674,7 +2784,8 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2674
2784
|
const fileContent = fs.readFileSync(configPath, "utf-8");
|
|
2675
2785
|
logger.debug(`[MetroSyncMiddleware] File content: ${fileContent}`);
|
|
2676
2786
|
const config = JSON.parse(fileContent);
|
|
2677
|
-
const scenario =
|
|
2787
|
+
const scenario =
|
|
2788
|
+
sanitizeScenarioName(config.currentScenario) || DEFAULT_SCENARIO;
|
|
2678
2789
|
logger.debug(
|
|
2679
2790
|
`[MetroSyncMiddleware] Found scenario in config: ${scenario} (from file: ${JSON.stringify(config)})`,
|
|
2680
2791
|
);
|
|
@@ -2708,6 +2819,20 @@ export function createMockSyncMiddleware(options?: MetroSyncMiddlewareOptions) {
|
|
|
2708
2819
|
req.on("end", () => {
|
|
2709
2820
|
try {
|
|
2710
2821
|
const config = JSON.parse(body);
|
|
2822
|
+
if (
|
|
2823
|
+
config &&
|
|
2824
|
+
typeof config === "object" &&
|
|
2825
|
+
typeof config.currentScenario === "string" &&
|
|
2826
|
+
config.currentScenario.trim() !== "" &&
|
|
2827
|
+
!sanitizeScenarioName(config.currentScenario)
|
|
2828
|
+
) {
|
|
2829
|
+
res.statusCode = 400;
|
|
2830
|
+
res.setHeader("Content-Type", "application/json");
|
|
2831
|
+
res.end(
|
|
2832
|
+
JSON.stringify({ success: false, error: "Invalid scenario name" }),
|
|
2833
|
+
);
|
|
2834
|
+
return;
|
|
2835
|
+
}
|
|
2711
2836
|
const configPath = path.join(mockDataPath, "scenario-config.json");
|
|
2712
2837
|
fs.writeFileSync(configPath, JSON.stringify(config, null, 2));
|
|
2713
2838
|
res.setHeader("Content-Type", "application/json");
|
package/src/react-native.ts
CHANGED
|
@@ -36,6 +36,10 @@ export interface MockifyerInstance extends HTTPClient {
|
|
|
36
36
|
clearAllMocks: () => Promise<void>;
|
|
37
37
|
setClientId: (lane: string) => void;
|
|
38
38
|
getClientId: () => string | undefined;
|
|
39
|
+
setRecordMode: (enabled: boolean) => void;
|
|
40
|
+
isRecordMode: () => boolean;
|
|
41
|
+
setRecordResponses: (enabled: boolean) => void;
|
|
42
|
+
isRecordResponses: () => boolean;
|
|
39
43
|
enableMockifyer: () => void;
|
|
40
44
|
disableMockifyer: () => void;
|
|
41
45
|
isMockifyerEnabled: () => boolean;
|
|
@@ -0,0 +1,105 @@
|
|
|
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
|
+
|
|
9
|
+
export interface ResolvedPatchedFetchRequest {
|
|
10
|
+
url: string;
|
|
11
|
+
method: string;
|
|
12
|
+
headers: Record<string, string>;
|
|
13
|
+
body: unknown;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function isRequest(input: unknown): input is Request {
|
|
17
|
+
return typeof Request !== 'undefined' && input instanceof Request;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function headersToRecord(headers: HeadersInit | undefined): Record<string, string> {
|
|
21
|
+
const out: Record<string, string> = {};
|
|
22
|
+
if (!headers) {
|
|
23
|
+
return out;
|
|
24
|
+
}
|
|
25
|
+
if (headers instanceof Headers) {
|
|
26
|
+
headers.forEach((value, key) => {
|
|
27
|
+
out[key] = value;
|
|
28
|
+
});
|
|
29
|
+
return out;
|
|
30
|
+
}
|
|
31
|
+
if (Array.isArray(headers)) {
|
|
32
|
+
for (const [key, value] of headers) {
|
|
33
|
+
out[key] = value;
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
38
|
+
if (value !== undefined && value !== null) {
|
|
39
|
+
out[key] = String(value);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Parse JSON text when it looks like an object/array; keep invalid JSON as the original string
|
|
47
|
+
* so the request still proceeds (native fetch does not throw on unparsable bodies).
|
|
48
|
+
*/
|
|
49
|
+
export function decodeFetchBodyText(text: string): unknown {
|
|
50
|
+
const start = text.trimStart();
|
|
51
|
+
if (start.startsWith('{') || start.startsWith('[')) {
|
|
52
|
+
try {
|
|
53
|
+
return JSON.parse(text);
|
|
54
|
+
} catch {
|
|
55
|
+
return text;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return text;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function decodeFetchBodyInit(body: BodyInit): unknown {
|
|
62
|
+
if (typeof body === 'string') {
|
|
63
|
+
return decodeFetchBodyText(body);
|
|
64
|
+
}
|
|
65
|
+
return body;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function urlFromFetchInput(input: RequestInfo | URL): string {
|
|
69
|
+
if (typeof input === 'string') {
|
|
70
|
+
return input;
|
|
71
|
+
}
|
|
72
|
+
if (input instanceof URL) {
|
|
73
|
+
return input.toString();
|
|
74
|
+
}
|
|
75
|
+
return input.url;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Method, headers, and body as native `fetch(input, init)` would use them.
|
|
80
|
+
* `init` fields override the `Request` argument (Fetch spec). Relative URL strings
|
|
81
|
+
* are left unchanged — `new Request('/path')` throws in Node without a base URL.
|
|
82
|
+
*/
|
|
83
|
+
export async function resolvePatchedFetchRequest(
|
|
84
|
+
input: RequestInfo | URL,
|
|
85
|
+
init?: RequestInit
|
|
86
|
+
): Promise<ResolvedPatchedFetchRequest> {
|
|
87
|
+
const url = urlFromFetchInput(input);
|
|
88
|
+
const method = String(init?.method || (isRequest(input) ? input.method : 'GET') || 'GET');
|
|
89
|
+
|
|
90
|
+
const headers = headersToRecord(
|
|
91
|
+
init?.headers !== undefined ? init.headers : isRequest(input) ? input.headers : undefined
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
let body: unknown;
|
|
95
|
+
if (init !== undefined && init.body !== undefined && init.body !== null) {
|
|
96
|
+
body = decodeFetchBodyInit(init.body);
|
|
97
|
+
} else if (isRequest(input) && method.toUpperCase() !== 'GET' && method.toUpperCase() !== 'HEAD') {
|
|
98
|
+
const text = await input.clone().text();
|
|
99
|
+
body = text ? decodeFetchBodyText(text) : undefined;
|
|
100
|
+
} else {
|
|
101
|
+
body = undefined;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return { url, method, headers, body };
|
|
105
|
+
}
|