@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.
@@ -0,0 +1,244 @@
1
+ // src/testing/index.ts
2
+ import exios from "@indra211/exios";
3
+
4
+ // src/core/internals.ts
5
+ var INTERNALS = /* @__PURE__ */ Symbol.for("@indra211/exios/internals");
6
+
7
+ // src/testing/index.ts
8
+ var core = exios[INTERNALS];
9
+ if (!core)
10
+ throw new Error("@indra211/exios/testing: the installed @indra211/exios is too old (needs 3.2.0 or newer)");
11
+ var { abortError, buildFullPath, finishResponse, prepareRequest } = core;
12
+ var { ExiosError } = exios;
13
+ var METHODS = ["get", "post", "put", "patch", "delete", "head", "options"];
14
+ function createMockAdapter(instance, options = {}) {
15
+ const handlers = [];
16
+ const history = emptyHistory();
17
+ const baseDelay = options.delay ?? 0;
18
+ checkDelay(baseDelay);
19
+ const previous = instance ? { adapter: instance.defaults.adapter } : void 0;
20
+ const adapter = async (config) => {
21
+ const prepared = prepareRequest(config);
22
+ const request = {
23
+ method: config.method,
24
+ url: prepared.url,
25
+ headers: prepared.headers,
26
+ data: config.data,
27
+ body: prepared.body,
28
+ config
29
+ };
30
+ history.all.push(request);
31
+ history[config.method]?.push(request);
32
+ const fullPath = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
33
+ const handler = handlers.find((h) => matches(h, config, request, fullPath));
34
+ if (handler?.once) handlers.splice(handlers.indexOf(handler), 1);
35
+ const ms = handler?.delay ?? baseDelay;
36
+ const reqInfo = { mock: true, method: config.method, url: prepared.url };
37
+ if (!handler) {
38
+ if (options.onNoMatch === "404") {
39
+ await wait(ms, config, reqInfo);
40
+ return finishResponse(config, { status: 404, statusText: "Not Found", headers: {}, data: "", request: reqInfo });
41
+ }
42
+ throw new ExiosError(
43
+ `[exios mock] no handler for ${config.method.toUpperCase()} ${prepared.url}`,
44
+ "ERR_MOCK_NO_MATCH",
45
+ config,
46
+ reqInfo
47
+ );
48
+ }
49
+ const r = handler.reply;
50
+ if (r.kind === "timeout") {
51
+ await wait(ms, config, reqInfo);
52
+ throw timeoutError(config, reqInfo);
53
+ }
54
+ await wait(ms, config, reqInfo);
55
+ if (r.kind === "networkError") throw new ExiosError("Network Error", ExiosError.ERR_NETWORK, config, reqInfo);
56
+ const [status, data, headers = {}] = await r.fn(config);
57
+ const raw = toRaw(data, headers, config);
58
+ return finishResponse(config, {
59
+ status,
60
+ statusText: STATUS_TEXT[status] ?? "",
61
+ headers: raw.headers,
62
+ data: raw.data,
63
+ request: reqInfo
64
+ });
65
+ };
66
+ const on = (method) => (url, opts = {}) => {
67
+ let delay;
68
+ const add = (reply, once) => {
69
+ handlers.push({ method, url, options: opts, reply, once, delay });
70
+ return mock;
71
+ };
72
+ const fnOf = (a, data, headers) => {
73
+ if (typeof a === "function") return a;
74
+ if (!Number.isInteger(a)) throw new TypeError(`[exios mock] reply status must be an integer (got ${String(a)})`);
75
+ return () => [a, data, headers];
76
+ };
77
+ const h = {
78
+ reply: (a, data, headers) => add({ kind: "reply", fn: fnOf(a, data, headers) }, false),
79
+ replyOnce: (a, data, headers) => add({ kind: "reply", fn: fnOf(a, data, headers) }, true),
80
+ networkError: () => add({ kind: "networkError" }, false),
81
+ networkErrorOnce: () => add({ kind: "networkError" }, true),
82
+ timeout: () => add({ kind: "timeout" }, false),
83
+ timeoutOnce: () => add({ kind: "timeout" }, true),
84
+ delay: (ms) => {
85
+ checkDelay(ms);
86
+ delay = ms;
87
+ return h;
88
+ }
89
+ };
90
+ return h;
91
+ };
92
+ const mock = {
93
+ adapter,
94
+ history,
95
+ onGet: on("get"),
96
+ onPost: on("post"),
97
+ onPut: on("put"),
98
+ onPatch: on("patch"),
99
+ onDelete: on("delete"),
100
+ onHead: on("head"),
101
+ onOptions: on("options"),
102
+ onAny: on("any"),
103
+ reset() {
104
+ handlers.length = 0;
105
+ mock.resetHistory();
106
+ },
107
+ resetHandlers() {
108
+ handlers.length = 0;
109
+ },
110
+ resetHistory() {
111
+ for (const list of Object.values(history)) list.length = 0;
112
+ },
113
+ restore() {
114
+ if (instance && previous && instance.defaults.adapter === adapter) instance.defaults.adapter = previous.adapter;
115
+ }
116
+ };
117
+ if (instance) instance.defaults.adapter = adapter;
118
+ return mock;
119
+ }
120
+ function emptyHistory() {
121
+ const h = { all: [] };
122
+ for (const m of METHODS) h[m] = [];
123
+ return h;
124
+ }
125
+ function checkDelay(ms) {
126
+ if (typeof ms !== "number" || !(ms >= 0) || !Number.isFinite(ms))
127
+ throw new TypeError(`[exios mock] delay must be a non-negative finite number (got ${String(ms)})`);
128
+ }
129
+ function matches(h, config, req, fullPath) {
130
+ if (h.method !== "any" && h.method !== config.method) return false;
131
+ if (h.url !== void 0 && !urlMatches(h.url, [config.url ?? "", fullPath, req.url])) return false;
132
+ const o = h.options;
133
+ if (o.params !== void 0 && !deepEqual(o.params, config.params ?? {})) return false;
134
+ if (o.headers !== void 0) {
135
+ const sent = lowerKeys(req.headers);
136
+ for (const [k, v] of Object.entries(o.headers)) if (sent[k.toLowerCase()] !== String(v)) return false;
137
+ }
138
+ if (o.data !== void 0) {
139
+ if (typeof o.data === "function") {
140
+ if (!o.data(config.data)) return false;
141
+ } else if (!deepEqual(o.data, parseBody(config.data))) return false;
142
+ }
143
+ return !o.match || o.match(config);
144
+ }
145
+ function urlMatches(m, candidates) {
146
+ if (typeof m === "function") return candidates.some(m);
147
+ if (m instanceof RegExp) return candidates.some((c) => test(m, c));
148
+ return candidates.some((c) => c === m || !m.includes("?") && c.split("?")[0] === m);
149
+ }
150
+ function test(re, s) {
151
+ re.lastIndex = 0;
152
+ return re.test(s);
153
+ }
154
+ function parseBody(data) {
155
+ if (typeof data !== "string") return data;
156
+ try {
157
+ return JSON.parse(data);
158
+ } catch {
159
+ return data;
160
+ }
161
+ }
162
+ function lowerKeys(h) {
163
+ const out = {};
164
+ for (const [k, v] of Object.entries(h)) out[k.toLowerCase()] = v;
165
+ return out;
166
+ }
167
+ function deepEqual(a, b) {
168
+ if (Object.is(a, b)) return true;
169
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) {
170
+ return (typeof a === "number" || typeof b === "number") && String(a) === String(b);
171
+ }
172
+ if (a instanceof Date || b instanceof Date)
173
+ return a instanceof Date && b instanceof Date && a.getTime() === b.getTime();
174
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
175
+ const ka = Object.keys(a).filter((k) => a[k] !== void 0);
176
+ const kb = Object.keys(b).filter((k) => b[k] !== void 0);
177
+ return ka.length === kb.length && ka.every((k) => deepEqual(a[k], b[k]));
178
+ }
179
+ var isPlain = (v) => Array.isArray(v) || typeof v === "object" && v !== null && [Object.prototype, null].includes(Object.getPrototypeOf(v));
180
+ function toRaw(data, headers, config) {
181
+ const h = lowerKeys(headers);
182
+ let body = data === void 0 ? "" : data;
183
+ if (isPlain(body)) {
184
+ body = JSON.stringify(body);
185
+ h["content-type"] ??= "application/json";
186
+ }
187
+ if (typeof body === "string") {
188
+ if (config.responseType === "arraybuffer") body = new TextEncoder().encode(body).buffer;
189
+ else if (config.responseType === "blob" && typeof Blob !== "undefined")
190
+ body = new Blob([body], h["content-type"] ? { type: h["content-type"] } : {});
191
+ }
192
+ return { data: body, headers: h };
193
+ }
194
+ function timeoutError(config, request) {
195
+ return new ExiosError(
196
+ config.timeoutErrorMessage ?? `timeout of ${config.timeout ?? 0}ms exceeded`,
197
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
198
+ config,
199
+ request
200
+ );
201
+ }
202
+ function wait(ms, config, request) {
203
+ const signal = config.signal;
204
+ if (signal?.aborted) return Promise.reject(abortError(signal, config, request));
205
+ const limit = config.timeout && config.timeout > 0 && config.timeout <= ms ? config.timeout : void 0;
206
+ if (ms === 0) return Promise.resolve();
207
+ return new Promise((resolve, reject) => {
208
+ const done = () => signal?.removeEventListener("abort", onAbort);
209
+ const timer = setTimeout(() => {
210
+ done();
211
+ if (limit !== void 0) reject(timeoutError(config, request));
212
+ else resolve();
213
+ }, limit ?? ms);
214
+ const onAbort = () => {
215
+ clearTimeout(timer);
216
+ done();
217
+ reject(abortError(signal, config, request));
218
+ };
219
+ signal?.addEventListener("abort", onAbort, { once: true });
220
+ });
221
+ }
222
+ var STATUS_TEXT = {
223
+ 200: "OK",
224
+ 201: "Created",
225
+ 202: "Accepted",
226
+ 204: "No Content",
227
+ 301: "Moved Permanently",
228
+ 302: "Found",
229
+ 304: "Not Modified",
230
+ 400: "Bad Request",
231
+ 401: "Unauthorized",
232
+ 403: "Forbidden",
233
+ 404: "Not Found",
234
+ 409: "Conflict",
235
+ 422: "Unprocessable Entity",
236
+ 429: "Too Many Requests",
237
+ 500: "Internal Server Error",
238
+ 502: "Bad Gateway",
239
+ 503: "Service Unavailable",
240
+ 504: "Gateway Timeout"
241
+ };
242
+ export {
243
+ createMockAdapter
244
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indra211/exios",
3
- "version": "3.1.2",
3
+ "version": "3.2.0",
4
4
  "description": "Zero-dependency axios-compatible HTTP client (XHR in browsers, Node http in Node, fetch fallback) with retry and a circuit breaker.",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -11,6 +11,13 @@
11
11
  "main": "./dist/index.node.cjs",
12
12
  "module": "./dist/index.js",
13
13
  "types": "./dist/index.d.ts",
14
+ "typesVersions": {
15
+ "*": {
16
+ "testing": [
17
+ "./dist/testing.d.ts"
18
+ ]
19
+ }
20
+ },
14
21
  "exports": {
15
22
  ".": {
16
23
  "deno": {
@@ -72,6 +79,16 @@
72
79
  "default": "./dist/index.cjs"
73
80
  }
74
81
  },
82
+ "./testing": {
83
+ "import": {
84
+ "types": "./dist/testing.d.ts",
85
+ "default": "./dist/testing.js"
86
+ },
87
+ "require": {
88
+ "types": "./dist/testing.d.cts",
89
+ "default": "./dist/testing.cjs"
90
+ }
91
+ },
75
92
  "./package.json": "./package.json"
76
93
  },
77
94
  "files": [