@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/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,258 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
|
+
<h1>@micheldever/fetch-debug</h1>
|
|
3
|
+
<div>Deterministic response overrides for @micheldever/fetch</div>
|
|
4
|
+
</div>
|
|
2
5
|
|
|
3
|
-
|
|
6
|
+
## Installation
|
|
7
|
+
|
|
8
|
+
This package is distributed via npm. It is a companion to `@micheldever/fetch`, which is a peer dependency:
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
npm install @micheldever/fetch-debug @micheldever/fetch
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
`@micheldever/fetch-debug` requires `@micheldever/fetch` `^2.2.0`. The fetcher is a peer dependency so your project controls its version, and synthetic errors use the same `FetchError` class as real requests.
|
|
15
|
+
|
|
16
|
+
`@micheldever/storage` is an optional peer dependency. Install it only when overrides need to persist across reloads:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install @micheldever/storage
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The package imports storage types only, so there is no runtime dependency. TypeScript consumers need `@micheldever/storage` installed even without persisting overrides, because `StorageEntity` appears in the public `AttachOptions` declarations. This is the accepted trade-off for keeping the runtime bundle free of storage imports.
|
|
23
|
+
|
|
24
|
+
## Usage
|
|
25
|
+
|
|
26
|
+
Create or obtain a `FetchClient`, then call `attachFetchDebug` with the client and its options. The function returns a controller, installs the console by default, and replaces the client's `fetch` with a wrapper that checks for overrides before delegating.
|
|
27
|
+
|
|
28
|
+
### Browser
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
import { FetchClient } from '@micheldever/fetch';
|
|
32
|
+
import { attachFetchDebug } from '@micheldever/fetch-debug';
|
|
33
|
+
import { StorageEntity } from '@micheldever/storage';
|
|
34
|
+
import { BrowserStorageAdapter } from '@micheldever/storage/adapters/browser';
|
|
35
|
+
|
|
36
|
+
const client = new FetchClient();
|
|
37
|
+
|
|
38
|
+
const storage = new StorageEntity([
|
|
39
|
+
new BrowserStorageAdapter('session', { namespace: 'my-app', unavailable: 'memory' }),
|
|
40
|
+
]);
|
|
41
|
+
|
|
42
|
+
const debug = attachFetchDebug(client, {
|
|
43
|
+
storage,
|
|
44
|
+
storageKey: 'my-app:fetch-overrides',
|
|
45
|
+
logPrefix: '[api-debug]',
|
|
46
|
+
console: { namespace: 'debug' },
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
await debug.ready;
|
|
50
|
+
|
|
51
|
+
await debug.override({
|
|
52
|
+
pattern: '/api/orders',
|
|
53
|
+
method: 'GET',
|
|
54
|
+
status: 503,
|
|
55
|
+
body: { message: 'Temporarily unavailable' },
|
|
56
|
+
});
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
`storageKey` is the logical key for the override payload; the browser adapter scopes the physical storage entry to its configured namespace. The `unavailable: 'memory'` option keeps the debug session working when browser storage is blocked.
|
|
60
|
+
|
|
61
|
+
`attachFetchDebug` installs the console at `globalThis.debug` in this example and returns the controller as `debug`. Call `await debug.ready` before relying on hydrated persisted overrides, reading `list()`, or issuing requests that should match them. The controller commands that change state are asynchronous:
|
|
62
|
+
|
|
63
|
+
```typescript
|
|
64
|
+
await debug.override({ pattern: '/api/customers', status: 404 });
|
|
65
|
+
await debug.clear('/api/customers');
|
|
66
|
+
await debug.clearAll();
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Call `dispose()` when the debug session ends. It restores the original `fetch` and removes the console namespace it installed:
|
|
70
|
+
|
|
71
|
+
```typescript
|
|
72
|
+
debug.dispose();
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
Calling `attachFetchDebug` again with the same client returns the existing controller and ignores the new options; the association is kept in a module-level `WeakMap`. When attaching once to a shared, long-lived client, `source` must therefore be a stable resolver that reads ambient request context on every call. A per-request source cannot be swapped in after the first attach; create a client per request if that is needed.
|
|
76
|
+
|
|
77
|
+
### Node
|
|
78
|
+
|
|
79
|
+
Inject storage and disable the console:
|
|
80
|
+
|
|
81
|
+
```typescript
|
|
82
|
+
import { FetchClient } from '@micheldever/fetch';
|
|
83
|
+
import { attachFetchDebug } from '@micheldever/fetch-debug';
|
|
84
|
+
import { StorageEntity } from '@micheldever/storage';
|
|
85
|
+
import { MemoryStorageAdapter } from '@micheldever/storage/adapters/memory';
|
|
86
|
+
|
|
87
|
+
const client = new FetchClient();
|
|
88
|
+
|
|
89
|
+
const debug = attachFetchDebug(client, {
|
|
90
|
+
storage: new StorageEntity([new MemoryStorageAdapter()]),
|
|
91
|
+
console: false,
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
await debug.ready;
|
|
95
|
+
|
|
96
|
+
await debug.override({
|
|
97
|
+
pattern: '/api/orders',
|
|
98
|
+
method: 'GET',
|
|
99
|
+
body: { items: [] },
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
const orders = await client.fetch('https://api.example.com/api/orders');
|
|
103
|
+
|
|
104
|
+
debug.dispose();
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
`MemoryStorageAdapter` keeps overrides for the lifetime of the process. `console: false` skips console installation entirely, which is the usual choice outside a browser. The same attachment works during server-side rendering; see [Server-side Request Overrides](#server-side-request-overrides) when each request needs its own overrides.
|
|
108
|
+
|
|
109
|
+
## Registries
|
|
110
|
+
|
|
111
|
+
`attachFetchDebug` creates an override registry for you. Import `createRegistry` when you need to build and own a registry independently of `attachFetchDebug`, such as when scoping overrides to a single request:
|
|
112
|
+
|
|
113
|
+
```typescript
|
|
114
|
+
import { createRegistry } from '@micheldever/fetch-debug';
|
|
115
|
+
import { StorageEntity } from '@micheldever/storage';
|
|
116
|
+
import { MemoryStorageAdapter } from '@micheldever/storage/adapters/memory';
|
|
117
|
+
|
|
118
|
+
const registry = createRegistry({
|
|
119
|
+
storage: new StorageEntity([new MemoryStorageAdapter()]),
|
|
120
|
+
storageKey: 'my-app:fetch-overrides',
|
|
121
|
+
logPrefix: '[api-debug]',
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
await registry.ready;
|
|
125
|
+
|
|
126
|
+
await registry.set({ pattern: '/api/orders', status: 503 });
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
`createRegistry({ storage, storageKey, logPrefix })` builds a registry that hydrates from the supplied `StorageEntity` and persists every mutation. The options and defaults match the corresponding `attachFetchDebug` options. The returned `FetchDebugRegistry` exposes:
|
|
130
|
+
|
|
131
|
+
| Member | Description |
|
|
132
|
+
| --- | --- |
|
|
133
|
+
| `ready` | Promise that resolves after stored overrides have been loaded. |
|
|
134
|
+
| `set(input)` | Async. Validate and register an override; returns the stored record. |
|
|
135
|
+
| `get()` | Synchronous. Return every registered override. |
|
|
136
|
+
| `remove(pattern, method?)` | Async. Remove one override and return whether a record was removed. |
|
|
137
|
+
| `clear()` | Async. Remove every override. |
|
|
138
|
+
| `consume(pathname, method)` | Synchronous. Return the override matching a stripped pathname and method, or `undefined`. Matching removes `times: 1` records. |
|
|
139
|
+
|
|
140
|
+
The `FetchDebugRegistry`, `FetchDebugRegistryOptions`, and `FetchDebugOverrideSource` types are exported from the package root.
|
|
141
|
+
|
|
142
|
+
## Options
|
|
143
|
+
|
|
144
|
+
`attachFetchDebug(client, options)` accepts:
|
|
145
|
+
|
|
146
|
+
| Option | Type | Description |
|
|
147
|
+
| --- | --- | --- |
|
|
148
|
+
| `storage` | `StorageEntity` | Optional. Storage entity used to hydrate and persist overrides. When omitted, overrides live in memory. |
|
|
149
|
+
| `storageKey` | `string` | Logical key used for the stored payload. |
|
|
150
|
+
| `logPrefix` | `string` | Prefix for messages logged by the console commands. |
|
|
151
|
+
| `console` | `false \| { enabled?: boolean; namespace?: string; target?: object }` | Console installation. `false` disables it; an object configures it. |
|
|
152
|
+
| `registry` | `FetchDebugRegistry \| false` | Optional. Supply a registry instead of creating one, or `false` to disable registry resolution. A supplied registry is neither hydrated nor persisted by `attachFetchDebug`, and `controller.ready` is that registry's `ready`. |
|
|
153
|
+
| `source` | `FetchDebugOverrideSource` | Optional. Request-scoped resolver consulted before the registry. Receives the query/hash-stripped pathname and the uppercased method. |
|
|
154
|
+
|
|
155
|
+
`source` has the shape `{ consume(pathname: string, method: string): FetchDebugOverride | undefined }`, which is `Pick<FetchDebugRegistry, 'consume'>`. Overrides resolve in this order: `source.consume(...)` first; when it returns `undefined`, the registry is consulted; when neither matches, the request delegates to the original `fetch`.
|
|
156
|
+
|
|
157
|
+
### Defaults
|
|
158
|
+
|
|
159
|
+
- Console namespace: `fetchDebug`
|
|
160
|
+
- Logical storage key: `fetch-debug:overrides:v1`
|
|
161
|
+
- Log prefix: `[fetch-debug]`
|
|
162
|
+
- Storage: in-memory when no `storage` is supplied
|
|
163
|
+
- Registry: created from `storage` and `storageKey` when `registry` is omitted
|
|
164
|
+
- Source: none; the registry is the only override source
|
|
165
|
+
|
|
166
|
+
### Disabling the Registry
|
|
167
|
+
|
|
168
|
+
Pass `registry: false` when overrides should come only from `source`, or when the client should behave like an unattached client for override resolution and no override is ever applied:
|
|
169
|
+
|
|
170
|
+
- No registry is created, and no storage hydration or persistence happens.
|
|
171
|
+
- `controller.ready` resolves immediately and `controller.list()` returns `[]`.
|
|
172
|
+
- `controller.override`, `controller.clear`, and `controller.clearAll` reject with `fetch-debug registry is disabled by registry: false`.
|
|
173
|
+
- `controller.help()` still returns the help text.
|
|
174
|
+
- The console is forced off, even when `console` is configured. Passing `console: { enabled: true }` together with `registry: false` throws a `TypeError` when first attaching, with the message `console cannot be enabled when registry is false`. Re-attaching the same client returns the existing controller and does not throw.
|
|
175
|
+
|
|
176
|
+
## Override Input
|
|
177
|
+
|
|
178
|
+
Pass an override to `override(input)`:
|
|
179
|
+
|
|
180
|
+
| Field | Type | Description |
|
|
181
|
+
| --- | --- | --- |
|
|
182
|
+
| `pattern` | `string` | Required. Pathname beginning with `/`. Query strings, hashes, origins, and whitespace are rejected. |
|
|
183
|
+
| `method` | `string` | Optional HTTP method. Matching is case-insensitive; omitting it matches every method. |
|
|
184
|
+
| `status` | `number` | Integer from 200 to 599. Defaults to 200. |
|
|
185
|
+
| `body` | `JSONValue` | JSON value resolved for 2xx and 3xx responses, or used as `data` for 4xx and 5xx responses. |
|
|
186
|
+
| `delay` | `number` | Non-negative integer number of milliseconds to wait before resolving or rejecting. |
|
|
187
|
+
| `failure` | `true` | Reject as a network failure instead of responding. Cannot be combined with `status`, `body`, or `statusText`. |
|
|
188
|
+
| `statusText` | `string` | Status text used in the error message and error data. |
|
|
189
|
+
| `times` | `1` | Remove the override after its first match. |
|
|
190
|
+
|
|
191
|
+
Unknown keys are rejected. `override()` rejects when validation fails.
|
|
192
|
+
|
|
193
|
+
## Matching and Precedence
|
|
194
|
+
|
|
195
|
+
Overrides match the request pathname only. Query strings, hashes, and origins are ignored.
|
|
196
|
+
|
|
197
|
+
- `*` matches any characters, including `/`. There is no `**` syntax and no segment-level matching.
|
|
198
|
+
- `method` is optional and case-insensitive. Omitting it matches every method.
|
|
199
|
+
- Registering the same pattern and method replaces the existing record, even when the method casing differs.
|
|
200
|
+
- An exact pattern beats a wildcard; otherwise the most recent match wins.
|
|
201
|
+
- `times: 1` removes the record when it matches, before any configured delay.
|
|
202
|
+
|
|
203
|
+
## Response Semantics
|
|
204
|
+
|
|
205
|
+
- `status` must be an integer between 200 and 599 and defaults to 200.
|
|
206
|
+
- A 2xx or 3xx status resolves the configured `body`. When `body` is omitted, the request resolves with `null`.
|
|
207
|
+
- A 4xx or 5xx status rejects with a genuine `FetchError` carrying `statusCode` and `data`. A plain object `body` is merged with `statusCode` and, when provided, `statusText`; other bodies become `data` as-is. When `body` is omitted, `data` contains the status and, when provided, `statusText`.
|
|
208
|
+
- `failure: true` rejects with a `FetchError` that has no HTTP status and the message `Failed to fetch`.
|
|
209
|
+
- `delay` defers the outcome. Aborting the request signal rejects with an `AbortError` instead.
|
|
210
|
+
|
|
211
|
+
## Console Commands
|
|
212
|
+
|
|
213
|
+
`attachFetchDebug` installs a console object at `globalThis.fetchDebug` by default. Set `console: false` to disable installation, or pass `{ enabled: false }` for the same effect. Use `namespace` to choose the property name and `target` to install somewhere other than `globalThis`. If the namespace already exists on the target, it is left untouched. `registry: false` forces the console off regardless of these options.
|
|
214
|
+
|
|
215
|
+
| Command | Description |
|
|
216
|
+
| --- | --- |
|
|
217
|
+
| `override(input)` | Async. Validate and register an override; returns the stored record. |
|
|
218
|
+
| `list()` | Synchronous. Return and log every registered override. |
|
|
219
|
+
| `clear(pattern, method?)` | Async. Remove one override and return whether a record was removed. Omitting `method` removes only the method-agnostic record. |
|
|
220
|
+
| `clearAll()` | Async. Remove every override. |
|
|
221
|
+
| `help()` | Synchronous. Return and log the command reference. |
|
|
222
|
+
|
|
223
|
+
`override`, `clear`, and `clearAll` return promises and should be awaited before relying on their result or making subsequent calls. `list` and `help` are synchronous.
|
|
224
|
+
|
|
225
|
+
The controller returned by `attachFetchDebug` exposes the same commands, plus `ready` and `dispose`:
|
|
226
|
+
|
|
227
|
+
```typescript
|
|
228
|
+
await debug.override({ pattern: '/api/orders', status: 503 });
|
|
229
|
+
debug.list();
|
|
230
|
+
await debug.clear('/api/orders');
|
|
231
|
+
await debug.clearAll();
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
`controller.ready` resolves after stored overrides have been loaded. Await it before reading `list()` or issuing requests that should match persisted overrides. When you supply `registry`, `controller.ready` is that registry's `ready` promise.
|
|
235
|
+
|
|
236
|
+
## Storage
|
|
237
|
+
|
|
238
|
+
`StorageEntity` coordinates one or more adapters. In the browser, use `new BrowserStorageAdapter('session')` or `new BrowserStorageAdapter('local')`. In Node, use `new MemoryStorageAdapter()`. Import each adapter from its subpath, such as `@micheldever/storage/adapters/browser` and `@micheldever/storage/adapters/memory`.
|
|
239
|
+
|
|
240
|
+
The stored payload version remains `1`, and the logical key defaults to `fetch-debug:overrides:v1`.
|
|
241
|
+
|
|
242
|
+
Old raw `sessionStorage` data written by the previous custom storage layer is ignored. No migration is performed; register overrides again after upgrading.
|
|
243
|
+
|
|
244
|
+
`clearAll` affects only the package's own logical key and leaves every other key in the entity untouched. It does not clear the whole `StorageEntity`.
|
|
245
|
+
|
|
246
|
+
Storage reads and writes are awaited. A failed hydration starts with an empty registry, and a failed write is logged while the override remains in memory.
|
|
247
|
+
|
|
248
|
+
## Interaction with the Fetcher
|
|
249
|
+
|
|
250
|
+
The override check runs before the client's original `fetch`, so an override takes precedence over cache, deduplication, retry, and interceptors.
|
|
251
|
+
|
|
252
|
+
- Synthetic responses are never cached or retried.
|
|
253
|
+
- A synthetic 401 does not trigger the consumer's normal 401 handling, because no real response reaches interceptors or consumer code.
|
|
254
|
+
- Requests without a matching override pass through unchanged: same arguments, same receiver, same return value.
|
|
255
|
+
|
|
256
|
+
## Consumer Responsibilities
|
|
257
|
+
|
|
258
|
+
This package performs no environment gating. The consumer decides when to attach it and must not attach it in production. The consumer also supplies storage and chooses the console target and namespace.
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { FetchClient } from '@micheldever/fetch';
|
|
2
|
+
import { FetchDebugConsole, FetchDebugConsoleOptions } from '../console/console.js';
|
|
3
|
+
import { FetchDebugRegistry } from '../core/registry.js';
|
|
4
|
+
import { StorageEntity } from '@micheldever/storage';
|
|
5
|
+
/**
|
|
6
|
+
* The minimal fetch client shape intercepted by `attachFetchDebug`.
|
|
7
|
+
*/
|
|
8
|
+
export type FetchDebugClient = Pick<FetchClient, 'fetch'>;
|
|
9
|
+
/**
|
|
10
|
+
* A request-scoped source of overrides consulted before the registry.
|
|
11
|
+
*
|
|
12
|
+
* The source receives the query/hash-stripped pathname and the uppercased
|
|
13
|
+
* method, and returns an override to apply or `undefined` to fall back to the
|
|
14
|
+
* registry.
|
|
15
|
+
*/
|
|
16
|
+
export type FetchDebugOverrideSource = Pick<FetchDebugRegistry, 'consume'>;
|
|
17
|
+
/**
|
|
18
|
+
* Options for `attachFetchDebug`.
|
|
19
|
+
*
|
|
20
|
+
* The console installs at `globalThis.fetchDebug` by default, the storage key
|
|
21
|
+
* defaults to the versioned fetch-debug key, and overrides live in memory when
|
|
22
|
+
* no storage is supplied. Supplying `registry` uses that registry instead of
|
|
23
|
+
* creating one, and `registry: false` disables registry resolution entirely.
|
|
24
|
+
*/
|
|
25
|
+
export interface AttachOptions {
|
|
26
|
+
console?: false | FetchDebugConsoleOptions;
|
|
27
|
+
logPrefix?: string;
|
|
28
|
+
registry?: false | FetchDebugRegistry;
|
|
29
|
+
source?: FetchDebugOverrideSource;
|
|
30
|
+
storage?: StorageEntity;
|
|
31
|
+
storageKey?: string;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Controller returned by `attachFetchDebug`.
|
|
35
|
+
*
|
|
36
|
+
* Exposes the console commands, a hydration signal, and teardown.
|
|
37
|
+
*/
|
|
38
|
+
export interface FetchDebugController extends FetchDebugConsole {
|
|
39
|
+
dispose(): void;
|
|
40
|
+
ready: Promise<void>;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Attaches debug overrides to a fetch client.
|
|
44
|
+
*
|
|
45
|
+
* Replaces the client's own `fetch` with a wrapper that resolves a matching
|
|
46
|
+
* override from the source or registry before delegating to the original
|
|
47
|
+
* method. Installs the console unless disabled and returns a controller
|
|
48
|
+
* exposing the console commands, hydration state, and teardown.
|
|
49
|
+
*
|
|
50
|
+
* Calling this again with the same client returns the existing controller
|
|
51
|
+
* without installing another wrapper.
|
|
52
|
+
* @param client The fetch client to attach to.
|
|
53
|
+
* @param options The attachment options.
|
|
54
|
+
* @returns The controller for the attached client.
|
|
55
|
+
* @throws {TypeError} When first attaching and `client.fetch` is not a function.
|
|
56
|
+
* @throws {TypeError} When first attaching, `registry` is `false`, and `console.enabled` is `true`.
|
|
57
|
+
*/
|
|
58
|
+
export declare function attachFetchDebug(client: FetchDebugClient, options?: AttachOptions): FetchDebugController;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { FetchDebugOverride } from '../core/override.js';
|
|
2
|
+
import { FetchDebugRegistry } from '../core/registry.js';
|
|
3
|
+
/**
|
|
4
|
+
* Console-only facade for managing response overrides.
|
|
5
|
+
*
|
|
6
|
+
* Exposes the command set installed by `installFetchDebugConsole` and returned
|
|
7
|
+
* by `attachFetchDebug` as the controller.
|
|
8
|
+
*/
|
|
9
|
+
export interface FetchDebugConsole {
|
|
10
|
+
clear(pattern: string, method?: string): Promise<boolean>;
|
|
11
|
+
clearAll(): Promise<void>;
|
|
12
|
+
help(): string;
|
|
13
|
+
list(): FetchDebugOverride[];
|
|
14
|
+
override(input: unknown): Promise<FetchDebugOverride>;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Options for installing the debug console.
|
|
18
|
+
*
|
|
19
|
+
* The console is enabled by default, installs under the `fetchDebug`
|
|
20
|
+
* namespace, and targets `globalThis`.
|
|
21
|
+
*/
|
|
22
|
+
export interface FetchDebugConsoleOptions {
|
|
23
|
+
enabled?: boolean;
|
|
24
|
+
namespace?: string;
|
|
25
|
+
target?: object;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Creates a console facade backed by the given registry.
|
|
29
|
+
*
|
|
30
|
+
* Commands log through `logPrefix` and are not installed anywhere until passed
|
|
31
|
+
* to `installFetchDebugConsole`.
|
|
32
|
+
* @param registry The registry that stores the overrides.
|
|
33
|
+
* @param logPrefix The prefix for messages logged by the commands.
|
|
34
|
+
* @param namespace The property name used in the help title.
|
|
35
|
+
* @returns The console facade.
|
|
36
|
+
*/
|
|
37
|
+
export declare function createFetchDebugConsole(registry: FetchDebugRegistry, logPrefix: string, namespace?: string): FetchDebugConsole;
|
|
38
|
+
/**
|
|
39
|
+
* Installs a console facade on a target object.
|
|
40
|
+
*
|
|
41
|
+
* Does nothing and returns a no-op disposer when the console is disabled or
|
|
42
|
+
* when the namespace already exists on the target. Otherwise defines the
|
|
43
|
+
* namespace as a configurable, enumerable, writable property.
|
|
44
|
+
* @param facade The console facade to install.
|
|
45
|
+
* @param options The installation options.
|
|
46
|
+
* @param options.enabled Whether to install the console. Defaults to `true`.
|
|
47
|
+
* @param options.namespace The property name to install under. Defaults to `fetchDebug`.
|
|
48
|
+
* @param options.target The object to install on. Defaults to `globalThis`.
|
|
49
|
+
* @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.
|
|
50
|
+
*/
|
|
51
|
+
export declare function installFetchDebugConsole(facade: FetchDebugConsole, options?: FetchDebugConsoleOptions): () => void;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { FetchDebugOverride } from './override.js';
|
|
2
|
+
/**
|
|
3
|
+
* Checks whether a pattern contains a wildcard.
|
|
4
|
+
* @param pattern The pathname pattern to check.
|
|
5
|
+
* @returns `true` when the pattern contains `*`, otherwise `false`.
|
|
6
|
+
*/
|
|
7
|
+
export declare function isWildcardPattern(pattern: string): boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Checks whether a pathname matches a pattern.
|
|
10
|
+
*
|
|
11
|
+
* An exact pattern must equal the full pathname. A wildcard pattern is anchored
|
|
12
|
+
* to the full pathname, where each `*` matches any characters, including `/`.
|
|
13
|
+
* @param pattern The pathname pattern to match.
|
|
14
|
+
* @param pathname The pathname to test.
|
|
15
|
+
* @returns `true` when the pathname matches the pattern, otherwise `false`.
|
|
16
|
+
*/
|
|
17
|
+
export declare function matchesPathname(pattern: string, pathname: string): boolean;
|
|
18
|
+
/**
|
|
19
|
+
* Checks whether an override matches a request pathname and method.
|
|
20
|
+
*
|
|
21
|
+
* The method comparison is case-insensitive, and an override without a method
|
|
22
|
+
* matches every method.
|
|
23
|
+
* @param override The override to match.
|
|
24
|
+
* @param pathname The request pathname to test.
|
|
25
|
+
* @param method The request method to test.
|
|
26
|
+
* @returns `true` when the override matches the request, otherwise `false`.
|
|
27
|
+
*/
|
|
28
|
+
export declare function matchesFetchDebugOverride(override: FetchDebugOverride, pathname: string, method: string): boolean;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The persisted override payload schema version.
|
|
3
|
+
*
|
|
4
|
+
* Stored payloads carry this value, and hydration ignores any payload whose
|
|
5
|
+
* version does not match. Bump it when the persisted shape changes.
|
|
6
|
+
*/
|
|
7
|
+
export declare const FETCH_DEBUG_VERSION: 1;
|
|
8
|
+
/**
|
|
9
|
+
* The default storage key for persisted overrides.
|
|
10
|
+
*
|
|
11
|
+
* Includes the schema version so payloads from different versions are stored
|
|
12
|
+
* separately.
|
|
13
|
+
*/
|
|
14
|
+
export declare const DEFAULT_STORAGE_KEY: string;
|
|
15
|
+
/**
|
|
16
|
+
* A primitive JSON value.
|
|
17
|
+
*/
|
|
18
|
+
export type JSONPrimitive = boolean | null | number | string;
|
|
19
|
+
/**
|
|
20
|
+
* Any value that survives a JSON round-trip.
|
|
21
|
+
*/
|
|
22
|
+
export type JSONValue = JSONPrimitive | JSONValue[] | {
|
|
23
|
+
[key: string]: JSONValue;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* A validated response override matched against a request pathname.
|
|
27
|
+
*
|
|
28
|
+
* A `failure` override simulates a network failure; otherwise the override
|
|
29
|
+
* produces a response, defaulting `status` to `200`. `times` is limited to `1`
|
|
30
|
+
* because only single-use overrides are supported.
|
|
31
|
+
*/
|
|
32
|
+
export interface FetchDebugOverride {
|
|
33
|
+
body?: JSONValue;
|
|
34
|
+
delay?: number;
|
|
35
|
+
failure?: true;
|
|
36
|
+
method?: string;
|
|
37
|
+
pattern: string;
|
|
38
|
+
status?: number;
|
|
39
|
+
statusText?: string;
|
|
40
|
+
times?: 1;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The persisted payload containing all overrides for a schema version.
|
|
44
|
+
*/
|
|
45
|
+
export interface FetchDebugOverridePayload {
|
|
46
|
+
overrides: FetchDebugOverride[];
|
|
47
|
+
version: typeof FETCH_DEBUG_VERSION;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The result of validating a candidate override.
|
|
51
|
+
*
|
|
52
|
+
* On success `ok` is `true` and `value` holds the normalised override; on
|
|
53
|
+
* failure `ok` is `false` and `error` describes the first validation problem.
|
|
54
|
+
*/
|
|
55
|
+
export type FetchDebugValidationResult = {
|
|
56
|
+
error: string;
|
|
57
|
+
ok: false;
|
|
58
|
+
} | {
|
|
59
|
+
ok: true;
|
|
60
|
+
value: FetchDebugOverride;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Validates and normalises a candidate override.
|
|
64
|
+
*
|
|
65
|
+
* Unknown keys, a non-object input, an invalid pattern, invalid field values,
|
|
66
|
+
* and a failure combined with `status`, `body`, or `statusText` are rejected.
|
|
67
|
+
* Methods are normalised to uppercase and a response override defaults its
|
|
68
|
+
* status to `200`.
|
|
69
|
+
* @param input The candidate override to validate.
|
|
70
|
+
* @returns A result whose `ok` flag discriminates success (`value`) from failure (`error`).
|
|
71
|
+
*/
|
|
72
|
+
export declare function validateFetchDebugOverride(input: unknown): FetchDebugValidationResult;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { FetchDebugOverride } from './override.js';
|
|
2
|
+
import { StorageEntity } from '@micheldever/storage';
|
|
3
|
+
/**
|
|
4
|
+
* Options for creating a fetch-debug registry.
|
|
5
|
+
*
|
|
6
|
+
* `logPrefix` defaults to `[fetch-debug]`. `storage` enables hydration and
|
|
7
|
+
* persistence; without it, overrides live in memory. `storageKey` defaults to
|
|
8
|
+
* the package storage key.
|
|
9
|
+
*/
|
|
10
|
+
export interface FetchDebugRegistryOptions {
|
|
11
|
+
logPrefix?: string;
|
|
12
|
+
storage?: StorageEntity;
|
|
13
|
+
storageKey?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The public interface for a fetch-debug override registry.
|
|
17
|
+
*
|
|
18
|
+
* The registry hydrates stored overrides once when created and persists every
|
|
19
|
+
* mutation through the configured storage entity.
|
|
20
|
+
*/
|
|
21
|
+
export interface FetchDebugRegistry {
|
|
22
|
+
clear(): Promise<void>;
|
|
23
|
+
consume(pathname: string, method: string): FetchDebugOverride | undefined;
|
|
24
|
+
get(): FetchDebugOverride[];
|
|
25
|
+
ready: Promise<void>;
|
|
26
|
+
remove(pattern: string, method?: string): Promise<boolean>;
|
|
27
|
+
set(input: unknown): Promise<FetchDebugOverride>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Creates a registry that hydrates stored overrides and persists mutations.
|
|
31
|
+
*
|
|
32
|
+
* Hydration starts immediately and resolves through `ready`. Storage failures
|
|
33
|
+
* are logged and swallowed, so the registry falls back to memory. Mutations
|
|
34
|
+
* wait for hydration, and persistence writes are queued in order.
|
|
35
|
+
* @param options The registry options.
|
|
36
|
+
* @returns The created registry.
|
|
37
|
+
*/
|
|
38
|
+
export declare function createRegistry(options?: FetchDebugRegistryOptions): FetchDebugRegistry;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { FetchDebugOverride } from './override.js';
|
|
2
|
+
import { FetchInput } from '@micheldever/fetch';
|
|
3
|
+
/**
|
|
4
|
+
* Request options containing an optional method override.
|
|
5
|
+
*/
|
|
6
|
+
interface MethodInit {
|
|
7
|
+
method?: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* The request inputs accepted when extracting a pathname.
|
|
11
|
+
*/
|
|
12
|
+
type PathnameInput = FetchInput | {
|
|
13
|
+
pathname: string;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Extracts the pathname from a request input.
|
|
17
|
+
*
|
|
18
|
+
* Relative strings resolve against `http://localhost`, and query strings and
|
|
19
|
+
* hashes are discarded.
|
|
20
|
+
* @param input The request input, URL, request, or pathname object.
|
|
21
|
+
* @returns The extracted pathname.
|
|
22
|
+
*/
|
|
23
|
+
export declare function extractPathname(input: PathnameInput): string;
|
|
24
|
+
/**
|
|
25
|
+
* Extracts the request method from a request input.
|
|
26
|
+
*
|
|
27
|
+
* The `init` method takes precedence over the request method, and the result is
|
|
28
|
+
* uppercased. Defaults to `GET`.
|
|
29
|
+
* @param input The request input.
|
|
30
|
+
* @param init The request options, if provided.
|
|
31
|
+
* @returns The uppercased request method.
|
|
32
|
+
*/
|
|
33
|
+
export declare function extractMethod(input: FetchInput, init?: MethodInit): string;
|
|
34
|
+
/**
|
|
35
|
+
* Resolves an override into a response body or rejects with a synthetic error.
|
|
36
|
+
*
|
|
37
|
+
* Applies the configured delay, observing the abort signal before and after the
|
|
38
|
+
* wait. A `failure` override rejects with a network `FetchError` that has no
|
|
39
|
+
* HTTP status. Otherwise the status defaults to 200: 2xx and 3xx responses
|
|
40
|
+
* resolve the configured body, or `null` when no body is configured, while 4xx
|
|
41
|
+
* and 5xx responses reject with a synthetic `FetchError` carrying the status,
|
|
42
|
+
* status text, and error data.
|
|
43
|
+
* @param override The override to resolve.
|
|
44
|
+
* @param signal The abort signal to observe, if provided.
|
|
45
|
+
* @returns The configured body, or `null` when no body is configured.
|
|
46
|
+
* @throws {Error} When the signal is aborted before the override resolves.
|
|
47
|
+
* @throws {FetchError} When the override requests a network failure.
|
|
48
|
+
* @throws {FetchError} When the override status is 4xx or 5xx.
|
|
49
|
+
*/
|
|
50
|
+
export declare function resolveFetchDebugOverride(override: FetchDebugOverride, signal?: AbortSignal | null): Promise<unknown>;
|
|
51
|
+
export {};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { attachFetchDebug } from './client/attach.js';
|
|
2
|
+
export type { AttachOptions, FetchDebugClient, FetchDebugController, FetchDebugOverrideSource } from './client/attach.js';
|
|
3
|
+
export type { FetchDebugConsole, FetchDebugConsoleOptions } from './console/console.js';
|
|
4
|
+
export type { FetchDebugOverride } from './core/override.js';
|
|
5
|
+
export { createRegistry } from './core/registry.js';
|
|
6
|
+
export type { FetchDebugRegistry, FetchDebugRegistryOptions } from './core/registry.js';
|