@micheldever/fetch-debug 0.0.0-stage → 1.1.0
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/LICENSE +21 -0
- package/README.md +257 -2
- package/dist/client/attach.d.ts +58 -0
- package/dist/console/console.d.ts +51 -0
- package/dist/core/matcher.d.ts +28 -0
- package/dist/core/override.d.ts +72 -0
- package/dist/core/registry.d.ts +38 -0
- package/dist/core/response.d.ts +51 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +983 -0
- package/dist/storage/storage.d.ts +27 -0
- package/package.json +54 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,983 @@
|
|
|
1
|
+
import { FetchError } from "@micheldever/fetch";
|
|
2
|
+
// src/console/console.ts
|
|
3
|
+
/**
|
|
4
|
+
* The default property name used to install the console on the target.
|
|
5
|
+
*/
|
|
6
|
+
var DEFAULT_CONSOLE_NAMESPACE = "fetchDebug";
|
|
7
|
+
/**
|
|
8
|
+
* Creates a console facade backed by the given registry.
|
|
9
|
+
*
|
|
10
|
+
* Commands log through `logPrefix` and are not installed anywhere until passed
|
|
11
|
+
* to `installFetchDebugConsole`.
|
|
12
|
+
* @param registry The registry that stores the overrides.
|
|
13
|
+
* @param logPrefix The prefix for messages logged by the commands.
|
|
14
|
+
* @param namespace The property name used in the help title.
|
|
15
|
+
* @returns The console facade.
|
|
16
|
+
*/
|
|
17
|
+
function createFetchDebugConsole(registry, logPrefix, namespace = DEFAULT_CONSOLE_NAMESPACE) {
|
|
18
|
+
const helpText = [
|
|
19
|
+
`${namespace} — API response overrides (console only)`,
|
|
20
|
+
"",
|
|
21
|
+
"Commands:",
|
|
22
|
+
" override(input) Register an override and return it (async; await it).",
|
|
23
|
+
" list() Return and log the registered overrides.",
|
|
24
|
+
" clear(pattern, method?) Remove one override; returns whether a record was removed (async; await it).",
|
|
25
|
+
" clearAll() Remove every override (async; await it).",
|
|
26
|
+
" help() Return and log this help text.",
|
|
27
|
+
"",
|
|
28
|
+
"Async: override, clear, and clearAll return promises; await them before relying on the result or subsequent calls.",
|
|
29
|
+
"Hydration: controller.ready resolves after stored overrides have been loaded; await it before reading list() or issuing requests.",
|
|
30
|
+
"Availability: controlled by the consumer; attachFetchDebug installs this console by default.",
|
|
31
|
+
"Patterns: exact pathnames match literally. A single * matches any characters, including \"/\"; there is no ** syntax.",
|
|
32
|
+
"Methods: omit method to match any method; matching is case-insensitive.",
|
|
33
|
+
"Status: 2xx and 3xx resolve the configured body as a success; 4xx and 5xx reject with a synthetic FetchError. Status must be an integer between 200 and 599 and defaults to 200.",
|
|
34
|
+
"Precedence: registering the same pattern and method replaces the existing record. An exact pattern beats a wildcard; otherwise the most recent match wins.",
|
|
35
|
+
"One-shot: set times: 1 to remove an override after its first match.",
|
|
36
|
+
"Lifetime: overrides persist through the supplied StorageEntity; without storage they live in memory for the current registry.",
|
|
37
|
+
"Failure: failure: true rejects with a synthetic FetchError that has no HTTP status and the message \"Failed to fetch\", instead of returning a response.",
|
|
38
|
+
"No UI: this is a console-only surface with no visible interface."
|
|
39
|
+
].join("\n");
|
|
40
|
+
function showHelp() {
|
|
41
|
+
console.log(helpText);
|
|
42
|
+
return helpText;
|
|
43
|
+
}
|
|
44
|
+
async function registerOverride(input) {
|
|
45
|
+
const override = await registry.set(input);
|
|
46
|
+
console.warn(`${logPrefix} override active`, override);
|
|
47
|
+
return override;
|
|
48
|
+
}
|
|
49
|
+
function listOverrides() {
|
|
50
|
+
const overrides = registry.get();
|
|
51
|
+
console.log(`${logPrefix} overrides`, overrides);
|
|
52
|
+
return overrides;
|
|
53
|
+
}
|
|
54
|
+
async function clearOverride(pattern, method) {
|
|
55
|
+
const removed = await registry.remove(pattern, method);
|
|
56
|
+
const methodLabel = method === void 0 ? "" : ` ${method.toUpperCase()}`;
|
|
57
|
+
console.log(`${logPrefix} clear ${pattern}${methodLabel}: ${removed ? "removed" : "not found"}`);
|
|
58
|
+
return removed;
|
|
59
|
+
}
|
|
60
|
+
async function clearAllOverrides() {
|
|
61
|
+
await registry.clear();
|
|
62
|
+
console.log(`${logPrefix} all overrides cleared`);
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
clear: clearOverride,
|
|
66
|
+
clearAll: clearAllOverrides,
|
|
67
|
+
help: showHelp,
|
|
68
|
+
list: listOverrides,
|
|
69
|
+
override: registerOverride
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Installs a console facade on a target object.
|
|
74
|
+
*
|
|
75
|
+
* Does nothing and returns a no-op disposer when the console is disabled or
|
|
76
|
+
* when the namespace already exists on the target. Otherwise defines the
|
|
77
|
+
* namespace as a configurable, enumerable, writable property.
|
|
78
|
+
* @param facade The console facade to install.
|
|
79
|
+
* @param options The installation options.
|
|
80
|
+
* @param options.enabled Whether to install the console. Defaults to `true`.
|
|
81
|
+
* @param options.namespace The property name to install under. Defaults to `fetchDebug`.
|
|
82
|
+
* @param options.target The object to install on. Defaults to `globalThis`.
|
|
83
|
+
* @returns A disposer that removes the namespace, but only when it still points at the installed facade. Calling it more than once is a no-op.
|
|
84
|
+
*/
|
|
85
|
+
function installFetchDebugConsole(facade, options = {}) {
|
|
86
|
+
const enabled = options.enabled ?? true;
|
|
87
|
+
const namespace = options.namespace ?? DEFAULT_CONSOLE_NAMESPACE;
|
|
88
|
+
const target = options.target ?? globalThis;
|
|
89
|
+
if (!enabled || namespace in target) return () => {};
|
|
90
|
+
Object.defineProperty(target, namespace, {
|
|
91
|
+
configurable: true,
|
|
92
|
+
enumerable: true,
|
|
93
|
+
value: facade,
|
|
94
|
+
writable: true
|
|
95
|
+
});
|
|
96
|
+
let installed = true;
|
|
97
|
+
return () => {
|
|
98
|
+
if (!installed) return;
|
|
99
|
+
installed = false;
|
|
100
|
+
if (Reflect.get(target, namespace) === facade) Reflect.deleteProperty(target, namespace);
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* The default storage key for persisted overrides.
|
|
105
|
+
*
|
|
106
|
+
* Includes the schema version so payloads from different versions are stored
|
|
107
|
+
* separately.
|
|
108
|
+
*/
|
|
109
|
+
var DEFAULT_STORAGE_KEY = `fetch-debug:overrides:v1`;
|
|
110
|
+
/**
|
|
111
|
+
* The keys accepted on an override object; any other key is rejected.
|
|
112
|
+
*/
|
|
113
|
+
var FETCH_DEBUG_OVERRIDE_KEYS = /* @__PURE__ */ new Set([
|
|
114
|
+
"body",
|
|
115
|
+
"delay",
|
|
116
|
+
"failure",
|
|
117
|
+
"method",
|
|
118
|
+
"pattern",
|
|
119
|
+
"status",
|
|
120
|
+
"statusText",
|
|
121
|
+
"times"
|
|
122
|
+
]);
|
|
123
|
+
/**
|
|
124
|
+
* Matches a non-empty HTTP method token; separators and whitespace are rejected.
|
|
125
|
+
*/
|
|
126
|
+
var HTTP_METHOD_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
127
|
+
/**
|
|
128
|
+
* Checks whether a value is a plain object.
|
|
129
|
+
*
|
|
130
|
+
* Objects with a `null` prototype are accepted; class instances, arrays, and
|
|
131
|
+
* other objects are not.
|
|
132
|
+
* @param value The value to check.
|
|
133
|
+
* @returns `true` when the value is a plain object, otherwise `false`.
|
|
134
|
+
*/
|
|
135
|
+
function isPlainObject(value) {
|
|
136
|
+
if (typeof value !== "object" || value === null) return false;
|
|
137
|
+
const prototype = Object.getPrototypeOf(value);
|
|
138
|
+
return prototype === Object.prototype || prototype === null;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Checks whether every element of an array is a JSON value.
|
|
142
|
+
*
|
|
143
|
+
* Sparse arrays are rejected because their key count differs from their length.
|
|
144
|
+
* @param value The array to check.
|
|
145
|
+
* @param seen The objects already visited, used to detect cycles.
|
|
146
|
+
* @param isValue The recursive JSON value validator.
|
|
147
|
+
* @returns `true` when the array is a JSON array, otherwise `false`.
|
|
148
|
+
*/
|
|
149
|
+
function isJSONArray(value, seen, isValue) {
|
|
150
|
+
if (Object.keys(value).length !== value.length) return false;
|
|
151
|
+
for (const item of value) if (!isValue(item, seen)) return false;
|
|
152
|
+
return true;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Checks whether every own property of an object is a JSON value.
|
|
156
|
+
*
|
|
157
|
+
* Symbol keys, non-enumerable properties, and accessors are rejected.
|
|
158
|
+
* @param value The object to check.
|
|
159
|
+
* @param seen The objects already visited, used to detect cycles.
|
|
160
|
+
* @param isValue The recursive JSON value validator.
|
|
161
|
+
* @returns `true` when the object is a JSON object, otherwise `false`.
|
|
162
|
+
*/
|
|
163
|
+
function isJSONObject(value, seen, isValue) {
|
|
164
|
+
if (Object.getOwnPropertySymbols(value).length > 0) return false;
|
|
165
|
+
for (const key of Object.getOwnPropertyNames(value)) {
|
|
166
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
167
|
+
if (!descriptor || !("value" in descriptor) || !descriptor.enumerable || !isValue(descriptor.value, seen)) return false;
|
|
168
|
+
}
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* Checks whether a value is a JSON value.
|
|
173
|
+
*
|
|
174
|
+
* Only finite numbers other than negative zero are accepted, and objects and
|
|
175
|
+
* arrays must be acyclic and contain only enumerable own data properties.
|
|
176
|
+
* @param value The value to check.
|
|
177
|
+
* @param seen The objects already visited, used to detect cycles.
|
|
178
|
+
* @returns `true` when the value is a JSON value, otherwise `false`.
|
|
179
|
+
*/
|
|
180
|
+
function isJSONValue(value, seen = /* @__PURE__ */ new Set()) {
|
|
181
|
+
if (value === null) return true;
|
|
182
|
+
if (typeof value === "string" || typeof value === "boolean") return true;
|
|
183
|
+
if (typeof value === "number") return Number.isFinite(value) && !Object.is(value, -0);
|
|
184
|
+
if (typeof value !== "object") return false;
|
|
185
|
+
if (seen.has(value)) return false;
|
|
186
|
+
seen.add(value);
|
|
187
|
+
const valid = Array.isArray(value) ? isJSONArray(value, seen, isJSONValue) : isPlainObject(value) && isJSONObject(value, seen, isJSONValue);
|
|
188
|
+
seen.delete(value);
|
|
189
|
+
return valid;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Checks whether a string is a valid override pathname pattern.
|
|
193
|
+
*
|
|
194
|
+
* A valid pattern starts with `/` and contains no query string, hash, origin,
|
|
195
|
+
* or whitespace. Wildcards are allowed.
|
|
196
|
+
* @param pattern The pattern to check.
|
|
197
|
+
* @returns `true` when the pattern is valid, otherwise `false`.
|
|
198
|
+
*/
|
|
199
|
+
function isPathnamePattern(pattern) {
|
|
200
|
+
return pattern.startsWith("/") && !pattern.includes("?") && !pattern.includes("#") && !pattern.includes("://") && !/\s/.test(pattern);
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Checks whether a value is an HTTP status code accepted by an override.
|
|
204
|
+
*
|
|
205
|
+
* Accepted statuses are safe integers from `200` to `599`.
|
|
206
|
+
* @param value The value to check.
|
|
207
|
+
* @returns `true` when the value is a valid status, otherwise `false`.
|
|
208
|
+
*/
|
|
209
|
+
function isHTTPStatus(value) {
|
|
210
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 200 && value <= 599;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Checks whether a value is a valid override delay.
|
|
214
|
+
*
|
|
215
|
+
* A valid delay is a non-negative safe integer and is not negative zero.
|
|
216
|
+
* @param value The value to check.
|
|
217
|
+
* @returns `true` when the value is a valid delay, otherwise `false`.
|
|
218
|
+
*/
|
|
219
|
+
function isDelay(value) {
|
|
220
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && !Object.is(value, -0);
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Checks whether an object has the given key as an own property.
|
|
224
|
+
* @param object The object to inspect.
|
|
225
|
+
* @param key The property key to look for.
|
|
226
|
+
* @returns `true` when the key is an own property, otherwise `false`.
|
|
227
|
+
*/
|
|
228
|
+
function hasOwn(object, key) {
|
|
229
|
+
return Object.prototype.hasOwnProperty.call(object, key);
|
|
230
|
+
}
|
|
231
|
+
/**
|
|
232
|
+
* Creates a failed validation result.
|
|
233
|
+
* @param error The validation error message.
|
|
234
|
+
* @returns A result with `ok` set to `false`.
|
|
235
|
+
*/
|
|
236
|
+
function invalid(error) {
|
|
237
|
+
return {
|
|
238
|
+
error,
|
|
239
|
+
ok: false
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Creates a successful validation result.
|
|
244
|
+
* @param value The validated override.
|
|
245
|
+
* @returns A result with `ok` set to `true`.
|
|
246
|
+
*/
|
|
247
|
+
function valid(value) {
|
|
248
|
+
return {
|
|
249
|
+
ok: true,
|
|
250
|
+
value
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* Parses an override method.
|
|
255
|
+
*
|
|
256
|
+
* Accepts a valid HTTP method token and normalises it to uppercase.
|
|
257
|
+
* @param value The value to parse.
|
|
258
|
+
* @returns The uppercase method, or `undefined` when the value is invalid.
|
|
259
|
+
*/
|
|
260
|
+
function parseMethod(value) {
|
|
261
|
+
return typeof value === "string" && HTTP_METHOD_PATTERN.test(value) ? value.toUpperCase() : void 0;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Parses an override status.
|
|
265
|
+
* @param value The value to parse.
|
|
266
|
+
* @returns The status code, or `undefined` when the value is invalid.
|
|
267
|
+
*/
|
|
268
|
+
function parseStatus(value) {
|
|
269
|
+
return isHTTPStatus(value) ? value : void 0;
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Parses an override body.
|
|
273
|
+
* @param value The value to parse.
|
|
274
|
+
* @returns The JSON body, or `undefined` when the value is not a JSON value.
|
|
275
|
+
*/
|
|
276
|
+
function parseBody(value) {
|
|
277
|
+
return isJSONValue(value) ? value : void 0;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Parses an override delay.
|
|
281
|
+
* @param value The value to parse.
|
|
282
|
+
* @returns The delay in milliseconds, or `undefined` when the value is invalid.
|
|
283
|
+
*/
|
|
284
|
+
function parseDelay(value) {
|
|
285
|
+
return isDelay(value) ? value : void 0;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Parses an override failure flag.
|
|
289
|
+
*
|
|
290
|
+
* Only `true` is accepted; any other value is invalid.
|
|
291
|
+
* @param value The value to parse.
|
|
292
|
+
* @returns `true`, or `undefined` when the value is not `true`.
|
|
293
|
+
*/
|
|
294
|
+
function parseFailure(value) {
|
|
295
|
+
return value === true ? true : void 0;
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Parses an override status text.
|
|
299
|
+
* @param value The value to parse.
|
|
300
|
+
* @returns The status text, or `undefined` when the value is not a string.
|
|
301
|
+
*/
|
|
302
|
+
function parseStatusText(value) {
|
|
303
|
+
return typeof value === "string" ? value : void 0;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Parses an override use count.
|
|
307
|
+
*
|
|
308
|
+
* Only `1` is accepted, so an override can be consumed at most once.
|
|
309
|
+
* @param value The value to parse.
|
|
310
|
+
* @returns `1`, or `undefined` when the value is not `1`.
|
|
311
|
+
*/
|
|
312
|
+
function parseTimes(value) {
|
|
313
|
+
return value === 1 ? 1 : void 0;
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Parses one optional field from a candidate override.
|
|
317
|
+
*
|
|
318
|
+
* A field that is not an own property is valid and yields `undefined`. A field
|
|
319
|
+
* that is present but fails `parse` yields the supplied `error`.
|
|
320
|
+
* @template T The parsed field type.
|
|
321
|
+
* @param input The candidate override object.
|
|
322
|
+
* @param key The field key to read.
|
|
323
|
+
* @param parse The parser for the raw field value.
|
|
324
|
+
* @param error The error message used when parsing fails.
|
|
325
|
+
* @returns The parse result for the field.
|
|
326
|
+
*/
|
|
327
|
+
function parseField(input, key, parse, error) {
|
|
328
|
+
if (!hasOwn(input, key)) return {
|
|
329
|
+
ok: true,
|
|
330
|
+
value: void 0
|
|
331
|
+
};
|
|
332
|
+
const value = parse(input[key]);
|
|
333
|
+
return value === void 0 ? {
|
|
334
|
+
error,
|
|
335
|
+
ok: false
|
|
336
|
+
} : {
|
|
337
|
+
ok: true,
|
|
338
|
+
value
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Parses every optional field from a candidate override.
|
|
343
|
+
*
|
|
344
|
+
* Fields are parsed in a fixed order and the first failure is returned.
|
|
345
|
+
* @param input The candidate override object.
|
|
346
|
+
* @returns The parsed fields, or the first field error.
|
|
347
|
+
*/
|
|
348
|
+
function parseFields(input) {
|
|
349
|
+
const method = parseField(input, "method", parseMethod, "method must be a valid HTTP method");
|
|
350
|
+
if (!method.ok) return {
|
|
351
|
+
error: method.error,
|
|
352
|
+
ok: false
|
|
353
|
+
};
|
|
354
|
+
const status = parseField(input, "status", parseStatus, "status must be an integer between 200 and 599");
|
|
355
|
+
if (!status.ok) return {
|
|
356
|
+
error: status.error,
|
|
357
|
+
ok: false
|
|
358
|
+
};
|
|
359
|
+
const body = parseField(input, "body", parseBody, "body must be a JSON value");
|
|
360
|
+
if (!body.ok) return {
|
|
361
|
+
error: body.error,
|
|
362
|
+
ok: false
|
|
363
|
+
};
|
|
364
|
+
const delay = parseField(input, "delay", parseDelay, "delay must be a non-negative integer");
|
|
365
|
+
if (!delay.ok) return {
|
|
366
|
+
error: delay.error,
|
|
367
|
+
ok: false
|
|
368
|
+
};
|
|
369
|
+
const failure = parseField(input, "failure", parseFailure, "failure must be true");
|
|
370
|
+
if (!failure.ok) return {
|
|
371
|
+
error: failure.error,
|
|
372
|
+
ok: false
|
|
373
|
+
};
|
|
374
|
+
const statusText = parseField(input, "statusText", parseStatusText, "statusText must be a string");
|
|
375
|
+
if (!statusText.ok) return {
|
|
376
|
+
error: statusText.error,
|
|
377
|
+
ok: false
|
|
378
|
+
};
|
|
379
|
+
const times = parseField(input, "times", parseTimes, "times must be 1");
|
|
380
|
+
if (!times.ok) return {
|
|
381
|
+
error: times.error,
|
|
382
|
+
ok: false
|
|
383
|
+
};
|
|
384
|
+
return {
|
|
385
|
+
fields: {
|
|
386
|
+
body: body.value,
|
|
387
|
+
delay: delay.value,
|
|
388
|
+
failure: failure.value,
|
|
389
|
+
method: method.value,
|
|
390
|
+
status: status.value,
|
|
391
|
+
statusText: statusText.value,
|
|
392
|
+
times: times.value
|
|
393
|
+
},
|
|
394
|
+
ok: true
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Builds a network failure override from parsed fields.
|
|
399
|
+
*
|
|
400
|
+
* Copies the optional method, delay, and times; status, body, and status text
|
|
401
|
+
* are not part of a failure override.
|
|
402
|
+
* @param pattern The validated pathname pattern.
|
|
403
|
+
* @param fields The parsed optional fields.
|
|
404
|
+
* @returns The failure override.
|
|
405
|
+
*/
|
|
406
|
+
function toFailureOverride(pattern, fields) {
|
|
407
|
+
const override = {
|
|
408
|
+
failure: true,
|
|
409
|
+
pattern
|
|
410
|
+
};
|
|
411
|
+
if (fields.method !== void 0) override.method = fields.method;
|
|
412
|
+
if (fields.delay !== void 0) override.delay = fields.delay;
|
|
413
|
+
if (fields.times !== void 0) override.times = fields.times;
|
|
414
|
+
return override;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Builds a response override from parsed fields.
|
|
418
|
+
*
|
|
419
|
+
* Copies every optional response field and defaults `status` to `200` when it
|
|
420
|
+
* was not provided.
|
|
421
|
+
* @param pattern The validated pathname pattern.
|
|
422
|
+
* @param fields The parsed optional fields.
|
|
423
|
+
* @returns The response override.
|
|
424
|
+
*/
|
|
425
|
+
function toResponseOverride(pattern, fields) {
|
|
426
|
+
const override = {
|
|
427
|
+
pattern,
|
|
428
|
+
status: fields.status ?? 200
|
|
429
|
+
};
|
|
430
|
+
if (fields.method !== void 0) override.method = fields.method;
|
|
431
|
+
if (fields.body !== void 0) override.body = fields.body;
|
|
432
|
+
if (fields.delay !== void 0) override.delay = fields.delay;
|
|
433
|
+
if (fields.statusText !== void 0) override.statusText = fields.statusText;
|
|
434
|
+
if (fields.times !== void 0) override.times = fields.times;
|
|
435
|
+
return override;
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Validates and normalises a candidate override.
|
|
439
|
+
*
|
|
440
|
+
* Unknown keys, a non-object input, an invalid pattern, invalid field values,
|
|
441
|
+
* and a failure combined with `status`, `body`, or `statusText` are rejected.
|
|
442
|
+
* Methods are normalised to uppercase and a response override defaults its
|
|
443
|
+
* status to `200`.
|
|
444
|
+
* @param input The candidate override to validate.
|
|
445
|
+
* @returns A result whose `ok` flag discriminates success (`value`) from failure (`error`).
|
|
446
|
+
*/
|
|
447
|
+
function validateFetchDebugOverride(input) {
|
|
448
|
+
if (!isPlainObject(input)) return invalid("override must be a plain object");
|
|
449
|
+
const unknownKey = Object.keys(input).find((key) => !FETCH_DEBUG_OVERRIDE_KEYS.has(key));
|
|
450
|
+
if (unknownKey !== void 0) return invalid(`unknown key "${unknownKey}"`);
|
|
451
|
+
const pattern = input.pattern;
|
|
452
|
+
if (typeof pattern !== "string" || !isPathnamePattern(pattern)) return invalid("pattern must be a pathname starting with \"/\" without a query, hash, or origin");
|
|
453
|
+
const parsed = parseFields(input);
|
|
454
|
+
if (!parsed.ok) return invalid(parsed.error);
|
|
455
|
+
if (parsed.fields.failure === true) {
|
|
456
|
+
if (hasOwn(input, "status") || hasOwn(input, "body") || hasOwn(input, "statusText")) return invalid("failure cannot be combined with status, body, or statusText");
|
|
457
|
+
return valid(toFailureOverride(pattern, parsed.fields));
|
|
458
|
+
}
|
|
459
|
+
return valid(toResponseOverride(pattern, parsed.fields));
|
|
460
|
+
}
|
|
461
|
+
// src/storage/storage.ts
|
|
462
|
+
/**
|
|
463
|
+
* Checks whether an unknown value is a non-null, non-array object.
|
|
464
|
+
* @param value The value to check.
|
|
465
|
+
* @returns `true` when the value is a record, otherwise `false`.
|
|
466
|
+
*/
|
|
467
|
+
function isRecord(value) {
|
|
468
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* Extracts the valid overrides from a stored payload.
|
|
472
|
+
*
|
|
473
|
+
* Returns an empty array when the payload has an unsupported version or shape,
|
|
474
|
+
* and silently drops entries that fail validation.
|
|
475
|
+
* @param payload The unknown stored payload to parse.
|
|
476
|
+
* @returns The valid overrides, or an empty array when the payload is not recognised.
|
|
477
|
+
*/
|
|
478
|
+
function parsePayload(payload) {
|
|
479
|
+
if (!isRecord(payload) || payload.version !== 1 || !Array.isArray(payload.overrides)) return [];
|
|
480
|
+
const overrides = [];
|
|
481
|
+
for (const entry of payload.overrides) {
|
|
482
|
+
const result = validateFetchDebugOverride(entry);
|
|
483
|
+
if (result.ok) overrides.push(result.value);
|
|
484
|
+
}
|
|
485
|
+
return overrides;
|
|
486
|
+
}
|
|
487
|
+
/**
|
|
488
|
+
* Loads persisted overrides from storage.
|
|
489
|
+
*
|
|
490
|
+
* Resolves to an empty array when no storage is supplied, when the key is
|
|
491
|
+
* missing, or when the stored payload is not recognised. Read failures are
|
|
492
|
+
* reported to `onError` and resolve to an empty array; parse failures are
|
|
493
|
+
* swallowed and also resolve to an empty array.
|
|
494
|
+
* @param storage The storage entity to read from. When omitted, no read is attempted.
|
|
495
|
+
* @param key The logical storage key holding the override payload.
|
|
496
|
+
* @param onError Called once when the storage read fails.
|
|
497
|
+
* @returns The hydrated overrides, or an empty array when none are available.
|
|
498
|
+
*/
|
|
499
|
+
async function hydrateFetchDebugOverrides(storage, key = DEFAULT_STORAGE_KEY, onError) {
|
|
500
|
+
if (!storage) return [];
|
|
501
|
+
let payload;
|
|
502
|
+
try {
|
|
503
|
+
payload = await storage.get(key);
|
|
504
|
+
} catch (error) {
|
|
505
|
+
onError?.(error);
|
|
506
|
+
return [];
|
|
507
|
+
}
|
|
508
|
+
if (payload === void 0) return [];
|
|
509
|
+
try {
|
|
510
|
+
return parsePayload(payload);
|
|
511
|
+
} catch {
|
|
512
|
+
return [];
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Persists overrides to storage as a versioned payload.
|
|
517
|
+
*
|
|
518
|
+
* Storage failures are swallowed: a write failure is reported to `onError` and
|
|
519
|
+
* resolves to `false` so the caller can keep the in-memory state.
|
|
520
|
+
* @param overrides The overrides to persist.
|
|
521
|
+
* @param storage The storage entity to write to. When omitted, no write is attempted.
|
|
522
|
+
* @param key The logical storage key for the override payload.
|
|
523
|
+
* @param onError Called once when the storage write fails.
|
|
524
|
+
* @returns `true` when the payload was written, otherwise `false`.
|
|
525
|
+
*/
|
|
526
|
+
async function persistFetchDebugOverrides(overrides, storage, key = DEFAULT_STORAGE_KEY, onError) {
|
|
527
|
+
if (!storage) return false;
|
|
528
|
+
const entry = {
|
|
529
|
+
expiresAt: null,
|
|
530
|
+
value: {
|
|
531
|
+
overrides: Array.from(overrides),
|
|
532
|
+
version: 1
|
|
533
|
+
}
|
|
534
|
+
};
|
|
535
|
+
try {
|
|
536
|
+
await storage.set(key, entry);
|
|
537
|
+
return true;
|
|
538
|
+
} catch (error) {
|
|
539
|
+
onError?.(error);
|
|
540
|
+
return false;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
// src/core/matcher.ts
|
|
544
|
+
/**
|
|
545
|
+
* Matches the regular expression metacharacters escaped in literal wildcard segments.
|
|
546
|
+
*/
|
|
547
|
+
var REGEXP_SPECIAL_CHARACTERS = /[.*+?^${}()|[\]\\]/g;
|
|
548
|
+
/**
|
|
549
|
+
* Checks whether a pattern contains a wildcard.
|
|
550
|
+
* @param pattern The pathname pattern to check.
|
|
551
|
+
* @returns `true` when the pattern contains `*`, otherwise `false`.
|
|
552
|
+
*/
|
|
553
|
+
function isWildcardPattern(pattern) {
|
|
554
|
+
return pattern.includes("*");
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Compiles a wildcard pattern into an anchored regular expression.
|
|
558
|
+
*
|
|
559
|
+
* Each `*` matches any characters, including `/`, and literal segments are
|
|
560
|
+
* escaped so they match exactly. There is no `**` syntax.
|
|
561
|
+
* @param pattern The wildcard pattern to compile.
|
|
562
|
+
* @returns The anchored regular expression for the pattern.
|
|
563
|
+
*/
|
|
564
|
+
function toPathnameRegExp(pattern) {
|
|
565
|
+
const source = pattern.split("*").map((segment) => segment.replaceAll(REGEXP_SPECIAL_CHARACTERS, "\\$&")).join(".*");
|
|
566
|
+
return new RegExp(`^${source}$`);
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Checks whether a pathname matches a pattern.
|
|
570
|
+
*
|
|
571
|
+
* An exact pattern must equal the full pathname. A wildcard pattern is anchored
|
|
572
|
+
* to the full pathname, where each `*` matches any characters, including `/`.
|
|
573
|
+
* @param pattern The pathname pattern to match.
|
|
574
|
+
* @param pathname The pathname to test.
|
|
575
|
+
* @returns `true` when the pathname matches the pattern, otherwise `false`.
|
|
576
|
+
*/
|
|
577
|
+
function matchesPathname(pattern, pathname) {
|
|
578
|
+
if (!isWildcardPattern(pattern)) return pattern === pathname;
|
|
579
|
+
return toPathnameRegExp(pattern).test(pathname);
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* Checks whether an override matches a request pathname and method.
|
|
583
|
+
*
|
|
584
|
+
* The method comparison is case-insensitive, and an override without a method
|
|
585
|
+
* matches every method.
|
|
586
|
+
* @param override The override to match.
|
|
587
|
+
* @param pathname The request pathname to test.
|
|
588
|
+
* @param method The request method to test.
|
|
589
|
+
* @returns `true` when the override matches the request, otherwise `false`.
|
|
590
|
+
*/
|
|
591
|
+
function matchesFetchDebugOverride(override, pathname, method) {
|
|
592
|
+
if (!matchesPathname(override.pattern, pathname)) return false;
|
|
593
|
+
return override.method === void 0 || override.method.toUpperCase() === method.toUpperCase();
|
|
594
|
+
}
|
|
595
|
+
// src/core/registry.ts
|
|
596
|
+
/**
|
|
597
|
+
* The default prefix prepended to registry log messages.
|
|
598
|
+
*/
|
|
599
|
+
var DEFAULT_LOG_PREFIX$1 = "[fetch-debug]";
|
|
600
|
+
/**
|
|
601
|
+
* Creates a deep copy of an override.
|
|
602
|
+
* @param override The override to copy.
|
|
603
|
+
* @returns A detached copy of the override.
|
|
604
|
+
*/
|
|
605
|
+
function cloneOverride(override) {
|
|
606
|
+
return structuredClone(override);
|
|
607
|
+
}
|
|
608
|
+
/**
|
|
609
|
+
* Logs a storage failure without interrupting the registry.
|
|
610
|
+
*
|
|
611
|
+
* Failures are logged as warnings so a broken storage adapter does not reject
|
|
612
|
+
* registry operations; overrides remain available in memory.
|
|
613
|
+
* @param logPrefix The prefix prepended to the log message.
|
|
614
|
+
* @param operation The storage operation that failed.
|
|
615
|
+
* @param error The error raised by the storage adapter.
|
|
616
|
+
*/
|
|
617
|
+
function logStorageFailure(logPrefix, operation, error) {
|
|
618
|
+
console.warn(`${logPrefix} storage ${operation} failed`, error);
|
|
619
|
+
}
|
|
620
|
+
/**
|
|
621
|
+
* Creates a registry that hydrates stored overrides and persists mutations.
|
|
622
|
+
*
|
|
623
|
+
* Hydration starts immediately and resolves through `ready`. Storage failures
|
|
624
|
+
* are logged and swallowed, so the registry falls back to memory. Mutations
|
|
625
|
+
* wait for hydration, and persistence writes are queued in order.
|
|
626
|
+
* @param options The registry options.
|
|
627
|
+
* @returns The created registry.
|
|
628
|
+
*/
|
|
629
|
+
function createRegistry(options = {}) {
|
|
630
|
+
const logPrefix = options.logPrefix ?? DEFAULT_LOG_PREFIX$1;
|
|
631
|
+
let overrides = [];
|
|
632
|
+
let persistenceQueue = Promise.resolve();
|
|
633
|
+
async function hydrate() {
|
|
634
|
+
try {
|
|
635
|
+
overrides = await hydrateFetchDebugOverrides(options.storage, options.storageKey, (error) => {
|
|
636
|
+
logStorageFailure(logPrefix, "hydration", error);
|
|
637
|
+
});
|
|
638
|
+
} catch (error) {
|
|
639
|
+
logStorageFailure(logPrefix, "hydration", error);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
const ready = hydrate();
|
|
643
|
+
async function writeSnapshot(snapshot) {
|
|
644
|
+
await persistFetchDebugOverrides(snapshot, options.storage, options.storageKey, (error) => {
|
|
645
|
+
logStorageFailure(logPrefix, "persistence", error);
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
function persist() {
|
|
649
|
+
const snapshot = overrides.map(cloneOverride);
|
|
650
|
+
const settled = persistenceQueue.then(() => writeSnapshot(snapshot)).catch(() => {});
|
|
651
|
+
persistenceQueue = settled;
|
|
652
|
+
return settled;
|
|
653
|
+
}
|
|
654
|
+
function findMatch(pathname, method) {
|
|
655
|
+
const matching = overrides.filter((override) => matchesFetchDebugOverride(override, pathname, method));
|
|
656
|
+
if (matching.length === 0) return;
|
|
657
|
+
const exact = matching.filter((override) => !isWildcardPattern(override.pattern));
|
|
658
|
+
return (exact.length > 0 ? exact : matching).at(-1);
|
|
659
|
+
}
|
|
660
|
+
return {
|
|
661
|
+
async clear() {
|
|
662
|
+
await ready;
|
|
663
|
+
overrides = [];
|
|
664
|
+
await persist();
|
|
665
|
+
},
|
|
666
|
+
consume(pathname, method) {
|
|
667
|
+
const matched = findMatch(pathname, method);
|
|
668
|
+
if (!matched) return;
|
|
669
|
+
if (matched.times === 1) {
|
|
670
|
+
overrides = overrides.filter((override) => override !== matched);
|
|
671
|
+
persist();
|
|
672
|
+
}
|
|
673
|
+
return cloneOverride(matched);
|
|
674
|
+
},
|
|
675
|
+
get() {
|
|
676
|
+
return overrides.map(cloneOverride);
|
|
677
|
+
},
|
|
678
|
+
ready,
|
|
679
|
+
async remove(pattern, method) {
|
|
680
|
+
await ready;
|
|
681
|
+
const normalisedMethod = method?.toUpperCase();
|
|
682
|
+
const next = overrides.filter((override) => {
|
|
683
|
+
return override.pattern !== pattern || override.method !== normalisedMethod;
|
|
684
|
+
});
|
|
685
|
+
if (next.length === overrides.length) return false;
|
|
686
|
+
overrides = next;
|
|
687
|
+
await persist();
|
|
688
|
+
return true;
|
|
689
|
+
},
|
|
690
|
+
async set(input) {
|
|
691
|
+
const result = validateFetchDebugOverride(input);
|
|
692
|
+
if (!result.ok) throw new Error(result.error);
|
|
693
|
+
await ready;
|
|
694
|
+
overrides = overrides.filter((override) => {
|
|
695
|
+
return override.pattern !== result.value.pattern || override.method !== result.value.method;
|
|
696
|
+
});
|
|
697
|
+
overrides.push(result.value);
|
|
698
|
+
await persist();
|
|
699
|
+
return cloneOverride(result.value);
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
}
|
|
703
|
+
// src/core/response.ts
|
|
704
|
+
/**
|
|
705
|
+
* The base URL used to resolve relative request inputs.
|
|
706
|
+
*/
|
|
707
|
+
var LOCAL_BASE_URL = "http://localhost";
|
|
708
|
+
/**
|
|
709
|
+
* The message used for synthetic network failures.
|
|
710
|
+
*/
|
|
711
|
+
var NETWORK_FAILURE_MESSAGE = "Failed to fetch";
|
|
712
|
+
/**
|
|
713
|
+
* The name assigned to synthetic abort errors.
|
|
714
|
+
*/
|
|
715
|
+
var ABORT_ERROR_NAME = "AbortError";
|
|
716
|
+
/**
|
|
717
|
+
* The message used for synthetic abort errors.
|
|
718
|
+
*/
|
|
719
|
+
var ABORT_ERROR_MESSAGE = "The request was aborted.";
|
|
720
|
+
/**
|
|
721
|
+
* Creates an error that mirrors a native abort error.
|
|
722
|
+
* @returns A new `Error` with the name `AbortError`.
|
|
723
|
+
*/
|
|
724
|
+
function createAbortError() {
|
|
725
|
+
const error = /* @__PURE__ */ new Error(ABORT_ERROR_MESSAGE);
|
|
726
|
+
Object.defineProperty(error, "name", {
|
|
727
|
+
configurable: true,
|
|
728
|
+
value: ABORT_ERROR_NAME
|
|
729
|
+
});
|
|
730
|
+
return error;
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* Throws an abort error when the signal is already aborted.
|
|
734
|
+
* @param signal The abort signal to check.
|
|
735
|
+
* @throws {Error} When the signal is aborted.
|
|
736
|
+
*/
|
|
737
|
+
function throwIfAborted(signal) {
|
|
738
|
+
if (signal?.aborted) throw createAbortError();
|
|
739
|
+
}
|
|
740
|
+
/**
|
|
741
|
+
* Resolves after a delay, rejecting if the signal aborts first.
|
|
742
|
+
*
|
|
743
|
+
* The abort listener and timer are cleaned up on both resolution and
|
|
744
|
+
* rejection.
|
|
745
|
+
* @param delay The delay in milliseconds.
|
|
746
|
+
* @param signal The abort signal to observe, if provided.
|
|
747
|
+
* @returns A promise that resolves after the delay.
|
|
748
|
+
* @throws {Error} When the signal is aborted before the delay elapses.
|
|
749
|
+
*/
|
|
750
|
+
function wait(delay, signal) {
|
|
751
|
+
throwIfAborted(signal);
|
|
752
|
+
return new Promise((resolve, reject) => {
|
|
753
|
+
const timerRef = { current: void 0 };
|
|
754
|
+
function onAbort() {
|
|
755
|
+
if (timerRef.current !== void 0) clearTimeout(timerRef.current);
|
|
756
|
+
signal?.removeEventListener("abort", onAbort);
|
|
757
|
+
reject(createAbortError());
|
|
758
|
+
}
|
|
759
|
+
timerRef.current = setTimeout(() => {
|
|
760
|
+
signal?.removeEventListener("abort", onAbort);
|
|
761
|
+
resolve();
|
|
762
|
+
}, delay);
|
|
763
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
764
|
+
});
|
|
765
|
+
}
|
|
766
|
+
/**
|
|
767
|
+
* Checks whether a JSON body is a plain object.
|
|
768
|
+
* @param body The JSON body to check.
|
|
769
|
+
* @returns `true` when the body is a non-null, non-array object, otherwise `false`.
|
|
770
|
+
*/
|
|
771
|
+
function isPlainBodyObject(body) {
|
|
772
|
+
return typeof body === "object" && body !== null && !Array.isArray(body);
|
|
773
|
+
}
|
|
774
|
+
/**
|
|
775
|
+
* Builds the `data` payload for a synthetic HTTP error.
|
|
776
|
+
*
|
|
777
|
+
* A plain object body is merged with the status code and optional status text.
|
|
778
|
+
* Any other configured body is returned unchanged. When no body is configured,
|
|
779
|
+
* a minimal object containing the status code is returned.
|
|
780
|
+
* @param override The override that produced the error.
|
|
781
|
+
* @param statusCode The HTTP status code.
|
|
782
|
+
* @returns The error data payload.
|
|
783
|
+
*/
|
|
784
|
+
function createErrorData(override, statusCode) {
|
|
785
|
+
const statusText = override.statusText;
|
|
786
|
+
if (override.body === void 0) return {
|
|
787
|
+
statusCode,
|
|
788
|
+
...statusText && { statusText }
|
|
789
|
+
};
|
|
790
|
+
if (!isPlainBodyObject(override.body)) return override.body;
|
|
791
|
+
return {
|
|
792
|
+
...override.body,
|
|
793
|
+
statusCode,
|
|
794
|
+
...statusText && { statusText }
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
/**
|
|
798
|
+
* Creates a synthetic `FetchError` for an HTTP error override.
|
|
799
|
+
* @param override The override that produced the error.
|
|
800
|
+
* @param statusCode The HTTP status code.
|
|
801
|
+
* @returns A `FetchError` carrying the status, status text, and error data.
|
|
802
|
+
*/
|
|
803
|
+
function createHTTPError(override, statusCode) {
|
|
804
|
+
const statusText = override.statusText;
|
|
805
|
+
const statusLabel = statusText ? `${statusCode} ${statusText}` : String(statusCode);
|
|
806
|
+
const error = new FetchError(`API override responded with ${statusLabel}`);
|
|
807
|
+
Object.defineProperties(error, {
|
|
808
|
+
data: {
|
|
809
|
+
configurable: true,
|
|
810
|
+
value: createErrorData(override, statusCode)
|
|
811
|
+
},
|
|
812
|
+
status: {
|
|
813
|
+
configurable: true,
|
|
814
|
+
value: statusCode
|
|
815
|
+
},
|
|
816
|
+
statusCode: {
|
|
817
|
+
configurable: true,
|
|
818
|
+
value: statusCode
|
|
819
|
+
},
|
|
820
|
+
statusText: {
|
|
821
|
+
configurable: true,
|
|
822
|
+
value: statusText
|
|
823
|
+
}
|
|
824
|
+
});
|
|
825
|
+
return error;
|
|
826
|
+
}
|
|
827
|
+
/**
|
|
828
|
+
* Creates a synthetic `FetchError` for a network failure override.
|
|
829
|
+
* @returns A `FetchError` with the network failure message and no HTTP status.
|
|
830
|
+
*/
|
|
831
|
+
function createNetworkError() {
|
|
832
|
+
return new FetchError(NETWORK_FAILURE_MESSAGE);
|
|
833
|
+
}
|
|
834
|
+
/**
|
|
835
|
+
* Extracts the pathname from a request input.
|
|
836
|
+
*
|
|
837
|
+
* Relative strings resolve against `http://localhost`, and query strings and
|
|
838
|
+
* hashes are discarded.
|
|
839
|
+
* @param input The request input, URL, request, or pathname object.
|
|
840
|
+
* @returns The extracted pathname.
|
|
841
|
+
*/
|
|
842
|
+
function extractPathname(input) {
|
|
843
|
+
if (typeof input === "string") return new URL(input, LOCAL_BASE_URL).pathname;
|
|
844
|
+
if ("url" in input) return new URL(input.url).pathname;
|
|
845
|
+
return input.pathname;
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Extracts the request method from a request input.
|
|
849
|
+
*
|
|
850
|
+
* The `init` method takes precedence over the request method, and the result is
|
|
851
|
+
* uppercased. Defaults to `GET`.
|
|
852
|
+
* @param input The request input.
|
|
853
|
+
* @param init The request options, if provided.
|
|
854
|
+
* @returns The uppercased request method.
|
|
855
|
+
*/
|
|
856
|
+
function extractMethod(input, init) {
|
|
857
|
+
if (init?.method !== void 0) return init.method.toUpperCase();
|
|
858
|
+
if (typeof input !== "string" && "method" in input) return input.method.toUpperCase();
|
|
859
|
+
return "GET";
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Resolves an override into a response body or rejects with a synthetic error.
|
|
863
|
+
*
|
|
864
|
+
* Applies the configured delay, observing the abort signal before and after the
|
|
865
|
+
* wait. A `failure` override rejects with a network `FetchError` that has no
|
|
866
|
+
* HTTP status. Otherwise the status defaults to 200: 2xx and 3xx responses
|
|
867
|
+
* resolve the configured body, or `null` when no body is configured, while 4xx
|
|
868
|
+
* and 5xx responses reject with a synthetic `FetchError` carrying the status,
|
|
869
|
+
* status text, and error data.
|
|
870
|
+
* @param override The override to resolve.
|
|
871
|
+
* @param signal The abort signal to observe, if provided.
|
|
872
|
+
* @returns The configured body, or `null` when no body is configured.
|
|
873
|
+
* @throws {Error} When the signal is aborted before the override resolves.
|
|
874
|
+
* @throws {FetchError} When the override requests a network failure.
|
|
875
|
+
* @throws {FetchError} When the override status is 4xx or 5xx.
|
|
876
|
+
*/
|
|
877
|
+
async function resolveFetchDebugOverride(override, signal) {
|
|
878
|
+
throwIfAborted(signal);
|
|
879
|
+
if (override.delay !== void 0) await wait(override.delay, signal);
|
|
880
|
+
throwIfAborted(signal);
|
|
881
|
+
if (override.failure) throw createNetworkError();
|
|
882
|
+
const status = override.status ?? 200;
|
|
883
|
+
if (status >= 400) throw createHTTPError(override, status);
|
|
884
|
+
return override.body ?? null;
|
|
885
|
+
}
|
|
886
|
+
// src/client/attach.ts
|
|
887
|
+
/**
|
|
888
|
+
* The default prefix for messages logged by the debug client.
|
|
889
|
+
*/
|
|
890
|
+
var DEFAULT_LOG_PREFIX = "[fetch-debug]";
|
|
891
|
+
/**
|
|
892
|
+
* Controllers keyed by the client they are attached to, used to keep attachment idempotent.
|
|
893
|
+
*/
|
|
894
|
+
var attachedClients = /* @__PURE__ */ new WeakMap();
|
|
895
|
+
/**
|
|
896
|
+
* Creates a registry that resolves no overrides and rejects every mutation.
|
|
897
|
+
*
|
|
898
|
+
* Used when `registry: false` disables registry resolution while keeping the
|
|
899
|
+
* controller commands available.
|
|
900
|
+
* @returns A registry whose `ready` resolves immediately, whose `consume` returns `undefined`, and whose mutations reject.
|
|
901
|
+
*/
|
|
902
|
+
function createDisabledRegistry() {
|
|
903
|
+
function rejectDisabled() {
|
|
904
|
+
return Promise.reject(/* @__PURE__ */ new Error("fetch-debug registry is disabled by registry: false"));
|
|
905
|
+
}
|
|
906
|
+
return {
|
|
907
|
+
clear: rejectDisabled,
|
|
908
|
+
consume: () => void 0,
|
|
909
|
+
get: () => [],
|
|
910
|
+
ready: Promise.resolve(),
|
|
911
|
+
remove: rejectDisabled,
|
|
912
|
+
set: rejectDisabled
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
/**
|
|
916
|
+
* Attaches debug overrides to a fetch client.
|
|
917
|
+
*
|
|
918
|
+
* Replaces the client's own `fetch` with a wrapper that resolves a matching
|
|
919
|
+
* override from the source or registry before delegating to the original
|
|
920
|
+
* method. Installs the console unless disabled and returns a controller
|
|
921
|
+
* exposing the console commands, hydration state, and teardown.
|
|
922
|
+
*
|
|
923
|
+
* Calling this again with the same client returns the existing controller
|
|
924
|
+
* without installing another wrapper.
|
|
925
|
+
* @param client The fetch client to attach to.
|
|
926
|
+
* @param options The attachment options.
|
|
927
|
+
* @returns The controller for the attached client.
|
|
928
|
+
* @throws {TypeError} When first attaching and `client.fetch` is not a function.
|
|
929
|
+
* @throws {TypeError} When first attaching, `registry` is `false`, and `console.enabled` is `true`.
|
|
930
|
+
*/
|
|
931
|
+
function attachFetchDebug(client, options = {}) {
|
|
932
|
+
const existing = attachedClients.get(client);
|
|
933
|
+
if (existing) return existing;
|
|
934
|
+
const previousDescriptor = Object.getOwnPropertyDescriptor(client, "fetch");
|
|
935
|
+
const original = client.fetch;
|
|
936
|
+
if (typeof original !== "function") throw new TypeError("client.fetch must be a function");
|
|
937
|
+
if (options.registry === false && typeof options.console === "object" && options.console.enabled === true) throw new TypeError("console cannot be enabled when registry is false");
|
|
938
|
+
const logPrefix = options.logPrefix ?? DEFAULT_LOG_PREFIX;
|
|
939
|
+
const registry = options.registry === false ? createDisabledRegistry() : options.registry ?? createRegistry({
|
|
940
|
+
logPrefix,
|
|
941
|
+
storage: options.storage,
|
|
942
|
+
storageKey: options.storageKey
|
|
943
|
+
});
|
|
944
|
+
const requestedConsole = options.console === false ? { enabled: false } : options.console ?? {};
|
|
945
|
+
const consoleOptions = options.registry === false ? {
|
|
946
|
+
...requestedConsole,
|
|
947
|
+
enabled: false
|
|
948
|
+
} : requestedConsole;
|
|
949
|
+
const facade = createFetchDebugConsole(registry, logPrefix, consoleOptions.namespace);
|
|
950
|
+
const disposeConsole = installFetchDebugConsole(facade, consoleOptions);
|
|
951
|
+
function wrapper(input, init) {
|
|
952
|
+
const pathname = extractPathname(input);
|
|
953
|
+
const method = extractMethod(input, init);
|
|
954
|
+
const override = options.source?.consume(pathname, method) ?? registry.consume(pathname, method);
|
|
955
|
+
if (override) return resolveFetchDebugOverride(override, init?.signal);
|
|
956
|
+
return Reflect.apply(original, this, [input, init]);
|
|
957
|
+
}
|
|
958
|
+
Object.defineProperty(client, "fetch", {
|
|
959
|
+
configurable: true,
|
|
960
|
+
value: wrapper,
|
|
961
|
+
writable: true
|
|
962
|
+
});
|
|
963
|
+
let disposed = false;
|
|
964
|
+
const controller = {
|
|
965
|
+
clear: facade.clear,
|
|
966
|
+
clearAll: facade.clearAll,
|
|
967
|
+
dispose() {
|
|
968
|
+
if (disposed) return;
|
|
969
|
+
disposed = true;
|
|
970
|
+
if (previousDescriptor) Object.defineProperty(client, "fetch", previousDescriptor);
|
|
971
|
+
else Reflect.deleteProperty(client, "fetch");
|
|
972
|
+
disposeConsole();
|
|
973
|
+
attachedClients.delete(client);
|
|
974
|
+
},
|
|
975
|
+
help: facade.help,
|
|
976
|
+
list: facade.list,
|
|
977
|
+
override: facade.override,
|
|
978
|
+
ready: registry.ready
|
|
979
|
+
};
|
|
980
|
+
attachedClients.set(client, controller);
|
|
981
|
+
return controller;
|
|
982
|
+
}
|
|
983
|
+
export { attachFetchDebug, createRegistry };
|