@indra211/exios 3.1.2 → 3.2.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.
@@ -2122,6 +2122,8 @@ async function dispatchRequest(config, registry2, observer) {
2122
2122
  breaker.record(ticket, (bcfg.isFailure ?? defaultIsFailure)(outcome));
2123
2123
  if (outcome.error) throw outcome.error;
2124
2124
  const response = outcome.response;
2125
+ response.meta ??= { attempts };
2126
+ response.config ??= config;
2125
2127
  response.meta.attempts = attempts;
2126
2128
  if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
2127
2129
  const { status } = response;
@@ -2504,6 +2506,61 @@ var InflightRequests = class {
2504
2506
  }
2505
2507
  };
2506
2508
 
2509
+ // src/core/plugins.ts
2510
+ var HOOKS = ["setup", "beforeRequest", "afterResponse", "onError"];
2511
+ function invalid(message) {
2512
+ throw new ExiosError(`ERR_BAD_OPTION_VALUE: ${message}`, ExiosError.ERR_BAD_OPTION_VALUE);
2513
+ }
2514
+ var PluginRegistry = class {
2515
+ list = [];
2516
+ get size() {
2517
+ return this.list.length;
2518
+ }
2519
+ add(plugin, instance) {
2520
+ if (typeof plugin !== "object" || plugin === null) invalid(`plugin must be an object (got ${String(plugin)})`);
2521
+ if (typeof plugin.name !== "string" || !plugin.name) invalid("plugin.name must be a non-empty string");
2522
+ for (const h of HOOKS)
2523
+ if (plugin[h] !== void 0 && typeof plugin[h] !== "function")
2524
+ invalid(`plugin "${plugin.name}": ${h} must be a function`);
2525
+ if (this.list.some((r) => r.plugin.name === plugin.name))
2526
+ invalid(`a plugin named "${plugin.name}" is already registered`);
2527
+ const entry = { plugin };
2528
+ const teardown = plugin.setup?.(instance);
2529
+ if (typeof teardown === "function") entry.teardown = teardown;
2530
+ this.list = [...this.list, entry];
2531
+ return () => void this.remove(plugin);
2532
+ }
2533
+ remove(nameOrPlugin) {
2534
+ const entry = this.list.find(
2535
+ (r) => typeof nameOrPlugin === "string" ? r.plugin.name === nameOrPlugin : r.plugin === nameOrPlugin
2536
+ );
2537
+ if (!entry) return false;
2538
+ this.list = this.list.filter((r) => r !== entry);
2539
+ entry.teardown?.();
2540
+ return true;
2541
+ }
2542
+ /** Run `final` wrapped in every plugin's hooks. */
2543
+ run(config, final) {
2544
+ const plugins = this.list.map((r) => r.plugin);
2545
+ const layer = async (i, cfg) => {
2546
+ if (i === plugins.length) return final(cfg);
2547
+ const p = plugins[i];
2548
+ const c = p.beforeRequest ? await p.beforeRequest(cfg) ?? cfg : cfg;
2549
+ let response;
2550
+ try {
2551
+ response = await layer(i + 1, c);
2552
+ } catch (err) {
2553
+ if (!p.onError || isCancel(err)) throw err;
2554
+ const recovered = await p.onError(err, c);
2555
+ if (recovered == null) throw err;
2556
+ return recovered;
2557
+ }
2558
+ return p.afterResponse ? await p.afterResponse(response, c) ?? response : response;
2559
+ };
2560
+ return layer(0, config);
2561
+ }
2562
+ };
2563
+
2507
2564
  // src/core/requestCache.ts
2508
2565
  var SAFE_METHODS = Object.freeze(["get", "head"]);
2509
2566
  var MemoryCache = class {
@@ -2734,6 +2791,9 @@ var Exios = class {
2734
2791
  events = new EventHub();
2735
2792
  memoryCache = new MemoryCache();
2736
2793
  inflight = new InflightRequests();
2794
+ plugins = new PluginRegistry();
2795
+ /** The callable instance wrapping this context (given to plugin `setup`). */
2796
+ instance;
2737
2797
  /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2738
2798
  cache;
2739
2799
  constructor(defaults) {
@@ -2808,7 +2868,11 @@ var Exios = class {
2808
2868
  synchronous = synchronous && h.synchronous;
2809
2869
  requestChain.unshift(h);
2810
2870
  });
2811
- const dispatch = (c) => this.dispatch(finalizeConfig(c));
2871
+ const dispatch = (c) => {
2872
+ const finalized = finalizeConfig(c);
2873
+ if (this.plugins.size === 0) return this.dispatch(finalized);
2874
+ return this.plugins.run(finalized, (pc) => this.dispatch(finalizeConfig(pc)));
2875
+ };
2812
2876
  let promise;
2813
2877
  if (synchronous) {
2814
2878
  promise = this.runSync(requestChain, resolved, dispatch);
@@ -2826,6 +2890,14 @@ var Exios = class {
2826
2890
  });
2827
2891
  return promise;
2828
2892
  }
2893
+ /** Register a plugin; returns a function that ejects it. Plugins are not inherited by `create()`. */
2894
+ use(plugin) {
2895
+ return this.plugins.add(plugin, this.instance);
2896
+ }
2897
+ /** Remove a plugin by name or by object (its `setup` teardown runs). True if it was registered. */
2898
+ eject(nameOrPlugin) {
2899
+ return this.plugins.remove(nameOrPlugin);
2900
+ }
2829
2901
  /** Subscribe to a lifecycle event; returns a function that unsubscribes. */
2830
2902
  on(name, listener) {
2831
2903
  return this.events.on(name, listener);
@@ -3129,6 +3201,8 @@ var Exios = class {
3129
3201
  };
3130
3202
  var METHODS = [
3131
3203
  "request",
3204
+ "use",
3205
+ "eject",
3132
3206
  "on",
3133
3207
  "once",
3134
3208
  "off",
@@ -3193,6 +3267,7 @@ function createInstance(defaults) {
3193
3267
  set: (v) => context.defaults = v,
3194
3268
  enumerable: true
3195
3269
  });
3270
+ context.instance = instance;
3196
3271
  instance.interceptors = context.interceptors;
3197
3272
  instance.breaker = context.breaker;
3198
3273
  instance.cache = context.cache;
@@ -3200,6 +3275,10 @@ function createInstance(defaults) {
3200
3275
  return instance;
3201
3276
  }
3202
3277
 
3278
+ // src/core/internals.ts
3279
+ var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
3280
+ var internals = { abortError, buildFullPath, finishResponse, prepareRequest };
3281
+
3203
3282
  // src/index.ts
3204
3283
  registerXhrAdapter();
3205
3284
  registerFetchAdapter();
@@ -3218,6 +3297,7 @@ var exios = Object.assign(
3218
3297
  createInstance(createDefaults()),
3219
3298
  statics
3220
3299
  );
3300
+ Object.defineProperty(exios, INTERNALS, { value: internals });
3221
3301
  var create = exios.create;
3222
3302
  var src_default = exios;
3223
3303
 
@@ -0,0 +1,275 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/testing/index.ts
31
+ var testing_exports = {};
32
+ __export(testing_exports, {
33
+ createMockAdapter: () => createMockAdapter
34
+ });
35
+ module.exports = __toCommonJS(testing_exports);
36
+ var import_exios = __toESM(require("@indra211/exios"), 1);
37
+
38
+ // src/core/internals.ts
39
+ var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
40
+
41
+ // src/testing/index.ts
42
+ var core = import_exios.default[INTERNALS];
43
+ if (!core)
44
+ throw new Error("@indra211/exios/testing: the installed @indra211/exios is too old (needs 3.2.0 or newer)");
45
+ var { abortError, buildFullPath, finishResponse, prepareRequest } = core;
46
+ var { ExiosError } = import_exios.default;
47
+ var METHODS = ["get", "post", "put", "patch", "delete", "head", "options"];
48
+ function createMockAdapter(instance, options = {}) {
49
+ const handlers = [];
50
+ const history = emptyHistory();
51
+ const baseDelay = options.delay ?? 0;
52
+ checkDelay(baseDelay);
53
+ const previous = instance ? { adapter: instance.defaults.adapter } : void 0;
54
+ const adapter = async (config) => {
55
+ const prepared = prepareRequest(config);
56
+ const request = {
57
+ method: config.method,
58
+ url: prepared.url,
59
+ headers: prepared.headers,
60
+ data: config.data,
61
+ body: prepared.body,
62
+ config
63
+ };
64
+ history.all.push(request);
65
+ history[config.method]?.push(request);
66
+ const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
67
+ const handler = handlers.find((h) => matches(h, config, request, fullPath));
68
+ if (handler?.once) handlers.splice(handlers.indexOf(handler), 1);
69
+ const ms = handler?.delay ?? baseDelay;
70
+ const reqInfo = { mock: true, method: config.method, url: prepared.url };
71
+ if (!handler) {
72
+ if (options.onNoMatch === "404") {
73
+ await wait(ms, config, reqInfo);
74
+ return finishResponse(config, { status: 404, statusText: "Not Found", headers: {}, data: "", request: reqInfo });
75
+ }
76
+ throw new ExiosError(
77
+ `[exios mock] no handler for ${config.method.toUpperCase()} ${prepared.url}`,
78
+ "ERR_MOCK_NO_MATCH",
79
+ config,
80
+ reqInfo
81
+ );
82
+ }
83
+ const r = handler.reply;
84
+ if (r.kind === "timeout") {
85
+ await wait(ms, config, reqInfo);
86
+ throw timeoutError(config, reqInfo);
87
+ }
88
+ await wait(ms, config, reqInfo);
89
+ if (r.kind === "networkError") throw new ExiosError("Network Error", ExiosError.ERR_NETWORK, config, reqInfo);
90
+ const [status, data, headers = {}] = await r.fn(config);
91
+ const raw = toRaw(data, headers, config);
92
+ return finishResponse(config, {
93
+ status,
94
+ statusText: STATUS_TEXT[status] ?? "",
95
+ headers: raw.headers,
96
+ data: raw.data,
97
+ request: reqInfo
98
+ });
99
+ };
100
+ const on = (method) => (url, opts = {}) => {
101
+ let delay;
102
+ const add = (reply, once) => {
103
+ handlers.push({ method, url, options: opts, reply, once, delay });
104
+ return mock;
105
+ };
106
+ const fnOf = (a, data, headers) => {
107
+ if (typeof a === "function") return a;
108
+ if (!Number.isInteger(a)) throw new TypeError(`[exios mock] reply status must be an integer (got ${String(a)})`);
109
+ return () => [a, data, headers];
110
+ };
111
+ const h = {
112
+ reply: (a, data, headers) => add({ kind: "reply", fn: fnOf(a, data, headers) }, false),
113
+ replyOnce: (a, data, headers) => add({ kind: "reply", fn: fnOf(a, data, headers) }, true),
114
+ networkError: () => add({ kind: "networkError" }, false),
115
+ networkErrorOnce: () => add({ kind: "networkError" }, true),
116
+ timeout: () => add({ kind: "timeout" }, false),
117
+ timeoutOnce: () => add({ kind: "timeout" }, true),
118
+ delay: (ms) => {
119
+ checkDelay(ms);
120
+ delay = ms;
121
+ return h;
122
+ }
123
+ };
124
+ return h;
125
+ };
126
+ const mock = {
127
+ adapter,
128
+ history,
129
+ onGet: on("get"),
130
+ onPost: on("post"),
131
+ onPut: on("put"),
132
+ onPatch: on("patch"),
133
+ onDelete: on("delete"),
134
+ onHead: on("head"),
135
+ onOptions: on("options"),
136
+ onAny: on("any"),
137
+ reset() {
138
+ handlers.length = 0;
139
+ mock.resetHistory();
140
+ },
141
+ resetHandlers() {
142
+ handlers.length = 0;
143
+ },
144
+ resetHistory() {
145
+ for (const list of Object.values(history)) list.length = 0;
146
+ },
147
+ restore() {
148
+ if (instance && previous && instance.defaults.adapter === adapter) instance.defaults.adapter = previous.adapter;
149
+ }
150
+ };
151
+ if (instance) instance.defaults.adapter = adapter;
152
+ return mock;
153
+ }
154
+ function emptyHistory() {
155
+ const h = { all: [] };
156
+ for (const m of METHODS) h[m] = [];
157
+ return h;
158
+ }
159
+ function checkDelay(ms) {
160
+ if (typeof ms !== "number" || !(ms >= 0) || !Number.isFinite(ms))
161
+ throw new TypeError(`[exios mock] delay must be a non-negative finite number (got ${String(ms)})`);
162
+ }
163
+ function matches(h, config, req, fullPath) {
164
+ if (h.method !== "any" && h.method !== config.method) return false;
165
+ if (h.url !== void 0 && !urlMatches(h.url, [config.url ?? "", fullPath, req.url])) return false;
166
+ const o = h.options;
167
+ if (o.params !== void 0 && !deepEqual(o.params, config.params ?? {})) return false;
168
+ if (o.headers !== void 0) {
169
+ const sent = lowerKeys(req.headers);
170
+ for (const [k, v] of Object.entries(o.headers)) if (sent[k.toLowerCase()] !== String(v)) return false;
171
+ }
172
+ if (o.data !== void 0) {
173
+ if (typeof o.data === "function") {
174
+ if (!o.data(config.data)) return false;
175
+ } else if (!deepEqual(o.data, parseBody(config.data))) return false;
176
+ }
177
+ return !o.match || o.match(config);
178
+ }
179
+ function urlMatches(m, candidates) {
180
+ if (typeof m === "function") return candidates.some(m);
181
+ if (m instanceof RegExp) return candidates.some((c) => test(m, c));
182
+ return candidates.some((c) => c === m || !m.includes("?") && c.split("?")[0] === m);
183
+ }
184
+ function test(re, s) {
185
+ re.lastIndex = 0;
186
+ return re.test(s);
187
+ }
188
+ function parseBody(data) {
189
+ if (typeof data !== "string") return data;
190
+ try {
191
+ return JSON.parse(data);
192
+ } catch {
193
+ return data;
194
+ }
195
+ }
196
+ function lowerKeys(h) {
197
+ const out = {};
198
+ for (const [k, v] of Object.entries(h)) out[k.toLowerCase()] = v;
199
+ return out;
200
+ }
201
+ function deepEqual(a, b) {
202
+ if (Object.is(a, b)) return true;
203
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) {
204
+ return (typeof a === "number" || typeof b === "number") && String(a) === String(b);
205
+ }
206
+ if (a instanceof Date || b instanceof Date)
207
+ return a instanceof Date && b instanceof Date && a.getTime() === b.getTime();
208
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
209
+ const ka = Object.keys(a).filter((k) => a[k] !== void 0);
210
+ const kb = Object.keys(b).filter((k) => b[k] !== void 0);
211
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
212
+ }
213
+ var isPlain = (v) => Array.isArray(v) || typeof v === "object" && v !== null && [Object.prototype, null].includes(Object.getPrototypeOf(v));
214
+ function toRaw(data, headers, config) {
215
+ const h = lowerKeys(headers);
216
+ let body = data === void 0 ? "" : data;
217
+ if (isPlain(body)) {
218
+ body = JSON.stringify(body);
219
+ h["content-type"] ??= "application/json";
220
+ }
221
+ if (typeof body === "string") {
222
+ if (config.responseType === "arraybuffer") body = new TextEncoder().encode(body).buffer;
223
+ else if (config.responseType === "blob" && typeof Blob !== "undefined")
224
+ body = new Blob([body], h["content-type"] ? { type: h["content-type"] } : {});
225
+ }
226
+ return { data: body, headers: h };
227
+ }
228
+ function timeoutError(config, request) {
229
+ return new ExiosError(
230
+ config.timeoutErrorMessage ?? `timeout of ${config.timeout ?? 0}ms exceeded`,
231
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
232
+ config,
233
+ request
234
+ );
235
+ }
236
+ function wait(ms, config, request) {
237
+ const signal = config.signal;
238
+ if (signal?.aborted) return Promise.reject(abortError(signal, config, request));
239
+ const limit = config.timeout && config.timeout > 0 && config.timeout <= ms ? config.timeout : void 0;
240
+ if (ms === 0) return Promise.resolve();
241
+ return new Promise((resolve, reject) => {
242
+ const done = () => signal?.removeEventListener("abort", onAbort);
243
+ const timer = setTimeout(() => {
244
+ done();
245
+ if (limit !== void 0) reject(timeoutError(config, request));
246
+ else resolve();
247
+ }, limit ?? ms);
248
+ const onAbort = () => {
249
+ clearTimeout(timer);
250
+ done();
251
+ reject(abortError(signal, config, request));
252
+ };
253
+ signal?.addEventListener("abort", onAbort, { once: true });
254
+ });
255
+ }
256
+ var STATUS_TEXT = {
257
+ 200: "OK",
258
+ 201: "Created",
259
+ 202: "Accepted",
260
+ 204: "No Content",
261
+ 301: "Moved Permanently",
262
+ 302: "Found",
263
+ 304: "Not Modified",
264
+ 400: "Bad Request",
265
+ 401: "Unauthorized",
266
+ 403: "Forbidden",
267
+ 404: "Not Found",
268
+ 409: "Conflict",
269
+ 422: "Unprocessable Entity",
270
+ 429: "Too Many Requests",
271
+ 500: "Internal Server Error",
272
+ 502: "Bad Gateway",
273
+ 503: "Service Unavailable",
274
+ 504: "Gateway Timeout"
275
+ };
@@ -0,0 +1,87 @@
1
+ import { AdapterFn, Method, InternalConfig, ExiosInstance } from '@indra211/exios';
2
+
3
+ /** `[status, data?, headers?]`: what a reply function returns. */
4
+ type MockReplyTuple = [status: number, data?: unknown, headers?: Record<string, string>];
5
+ type MockReplyFn = (config: InternalConfig) => MockReplyTuple | Promise<MockReplyTuple>;
6
+ /** Extra conditions for a handler; every given one must match. */
7
+ interface MockMatchOptions {
8
+ /** Deep-equal to `config.params`. */
9
+ params?: Record<string, unknown>;
10
+ /** Each listed header must be sent with this value (names are case-insensitive). */
11
+ headers?: Record<string, string>;
12
+ /** Deep-equal to the request body (a JSON string body is parsed first), or a predicate. */
13
+ data?: unknown;
14
+ /** Any other condition. */
15
+ match?: (config: InternalConfig) => boolean;
16
+ }
17
+ type MockUrlMatcher = string | RegExp | ((url: string) => boolean);
18
+ /** One recorded request. */
19
+ interface MockRequest {
20
+ method: Lowercase<Method>;
21
+ /** The full URL, with params. */
22
+ url: string;
23
+ /** The headers as sent. */
24
+ headers: Record<string, string>;
25
+ /** `config.data` as given (before transformRequest). */
26
+ data: unknown;
27
+ /** The body as sent (after transformRequest). */
28
+ body: unknown;
29
+ config: InternalConfig;
30
+ }
31
+ interface MockHandler {
32
+ /** Respond with this status, data and headers. Plain objects and arrays are sent as JSON. */
33
+ reply(status: number, data?: unknown, headers?: Record<string, string>): MockAdapter;
34
+ reply(fn: MockReplyFn): MockAdapter;
35
+ /** Like `reply`, for the next matching request only. */
36
+ replyOnce(status: number, data?: unknown, headers?: Record<string, string>): MockAdapter;
37
+ replyOnce(fn: MockReplyFn): MockAdapter;
38
+ /** Fail like a refused or dropped connection (`ERR_NETWORK`, retried like a real one). */
39
+ networkError(): MockAdapter;
40
+ networkErrorOnce(): MockAdapter;
41
+ /** Fail like an expired `timeout` (`ECONNABORTED`, or `ETIMEDOUT` with `transitional.clarifyTimeoutError`). */
42
+ timeout(): MockAdapter;
43
+ timeoutOnce(): MockAdapter;
44
+ /** Wait this long before answering (combined with `timeout`/`signal` like a slow server). */
45
+ delay(ms: number): MockHandler;
46
+ }
47
+ interface MockAdapterOptions {
48
+ /** Delay every reply (ms). Default 0. */
49
+ delay?: number;
50
+ /** A request no handler matches: `'throw'` (default) rejects with `ERR_MOCK_NO_MATCH`; `'404'` answers 404. */
51
+ onNoMatch?: "throw" | "404";
52
+ }
53
+ type HistoryMap = {
54
+ [M in Lowercase<Method>]: MockRequest[];
55
+ } & {
56
+ all: MockRequest[];
57
+ };
58
+ interface MockAdapter {
59
+ /** Use as `config.adapter` (or `createMockAdapter(instance)` sets it for you). */
60
+ readonly adapter: AdapterFn;
61
+ /** Requests received, all of them and per method. */
62
+ readonly history: HistoryMap;
63
+ onGet(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
64
+ onPost(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
65
+ onPut(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
66
+ onPatch(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
67
+ onDelete(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
68
+ onHead(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
69
+ onOptions(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
70
+ /** Any method. */
71
+ onAny(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
72
+ /** Remove every handler and the history. */
73
+ reset(): void;
74
+ resetHandlers(): void;
75
+ resetHistory(): void;
76
+ /** Give the instance back the adapter it had before `createMockAdapter(instance)`. */
77
+ restore(): void;
78
+ }
79
+ /**
80
+ * A mock adapter. With an instance, it becomes that instance's adapter (`restore()` undoes it); without
81
+ * one, pass `mock.adapter` as `config.adapter`. The rest of exios (transforms, validateStatus, retry,
82
+ * breaker, interceptors, plugins, events) runs for real on top of it.
83
+ */
84
+ declare function createMockAdapter(instance?: ExiosInstance, options?: MockAdapterOptions): MockAdapter;
85
+
86
+ export { createMockAdapter };
87
+ export type { MockAdapter, MockAdapterOptions, MockHandler, MockMatchOptions, MockReplyFn, MockReplyTuple, MockRequest, MockUrlMatcher };
@@ -0,0 +1,87 @@
1
+ import { AdapterFn, Method, InternalConfig, ExiosInstance } from '@indra211/exios';
2
+
3
+ /** `[status, data?, headers?]`: what a reply function returns. */
4
+ type MockReplyTuple = [status: number, data?: unknown, headers?: Record<string, string>];
5
+ type MockReplyFn = (config: InternalConfig) => MockReplyTuple | Promise<MockReplyTuple>;
6
+ /** Extra conditions for a handler; every given one must match. */
7
+ interface MockMatchOptions {
8
+ /** Deep-equal to `config.params`. */
9
+ params?: Record<string, unknown>;
10
+ /** Each listed header must be sent with this value (names are case-insensitive). */
11
+ headers?: Record<string, string>;
12
+ /** Deep-equal to the request body (a JSON string body is parsed first), or a predicate. */
13
+ data?: unknown;
14
+ /** Any other condition. */
15
+ match?: (config: InternalConfig) => boolean;
16
+ }
17
+ type MockUrlMatcher = string | RegExp | ((url: string) => boolean);
18
+ /** One recorded request. */
19
+ interface MockRequest {
20
+ method: Lowercase<Method>;
21
+ /** The full URL, with params. */
22
+ url: string;
23
+ /** The headers as sent. */
24
+ headers: Record<string, string>;
25
+ /** `config.data` as given (before transformRequest). */
26
+ data: unknown;
27
+ /** The body as sent (after transformRequest). */
28
+ body: unknown;
29
+ config: InternalConfig;
30
+ }
31
+ interface MockHandler {
32
+ /** Respond with this status, data and headers. Plain objects and arrays are sent as JSON. */
33
+ reply(status: number, data?: unknown, headers?: Record<string, string>): MockAdapter;
34
+ reply(fn: MockReplyFn): MockAdapter;
35
+ /** Like `reply`, for the next matching request only. */
36
+ replyOnce(status: number, data?: unknown, headers?: Record<string, string>): MockAdapter;
37
+ replyOnce(fn: MockReplyFn): MockAdapter;
38
+ /** Fail like a refused or dropped connection (`ERR_NETWORK`, retried like a real one). */
39
+ networkError(): MockAdapter;
40
+ networkErrorOnce(): MockAdapter;
41
+ /** Fail like an expired `timeout` (`ECONNABORTED`, or `ETIMEDOUT` with `transitional.clarifyTimeoutError`). */
42
+ timeout(): MockAdapter;
43
+ timeoutOnce(): MockAdapter;
44
+ /** Wait this long before answering (combined with `timeout`/`signal` like a slow server). */
45
+ delay(ms: number): MockHandler;
46
+ }
47
+ interface MockAdapterOptions {
48
+ /** Delay every reply (ms). Default 0. */
49
+ delay?: number;
50
+ /** A request no handler matches: `'throw'` (default) rejects with `ERR_MOCK_NO_MATCH`; `'404'` answers 404. */
51
+ onNoMatch?: "throw" | "404";
52
+ }
53
+ type HistoryMap = {
54
+ [M in Lowercase<Method>]: MockRequest[];
55
+ } & {
56
+ all: MockRequest[];
57
+ };
58
+ interface MockAdapter {
59
+ /** Use as `config.adapter` (or `createMockAdapter(instance)` sets it for you). */
60
+ readonly adapter: AdapterFn;
61
+ /** Requests received, all of them and per method. */
62
+ readonly history: HistoryMap;
63
+ onGet(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
64
+ onPost(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
65
+ onPut(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
66
+ onPatch(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
67
+ onDelete(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
68
+ onHead(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
69
+ onOptions(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
70
+ /** Any method. */
71
+ onAny(url?: MockUrlMatcher, options?: MockMatchOptions): MockHandler;
72
+ /** Remove every handler and the history. */
73
+ reset(): void;
74
+ resetHandlers(): void;
75
+ resetHistory(): void;
76
+ /** Give the instance back the adapter it had before `createMockAdapter(instance)`. */
77
+ restore(): void;
78
+ }
79
+ /**
80
+ * A mock adapter. With an instance, it becomes that instance's adapter (`restore()` undoes it); without
81
+ * one, pass `mock.adapter` as `config.adapter`. The rest of exios (transforms, validateStatus, retry,
82
+ * breaker, interceptors, plugins, events) runs for real on top of it.
83
+ */
84
+ declare function createMockAdapter(instance?: ExiosInstance, options?: MockAdapterOptions): MockAdapter;
85
+
86
+ export { createMockAdapter };
87
+ export type { MockAdapter, MockAdapterOptions, MockHandler, MockMatchOptions, MockReplyFn, MockReplyTuple, MockRequest, MockUrlMatcher };