@djiji/freq 0.0.0-stage → 1.0.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 +22 -0
- package/README.md +402 -2
- package/dist/constants.d.ts +9 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/core.d.ts +13 -0
- package/dist/core.d.ts.map +1 -0
- package/dist/errorType.d.ts +31 -0
- package/dist/errorType.d.ts.map +1 -0
- package/dist/hooks.d.ts +7 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -0
- package/dist/parse.d.ts +8 -0
- package/dist/parse.d.ts.map +1 -0
- package/dist/types.d.ts +78 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/utils.d.ts +7 -0
- package/dist/utils.d.ts.map +1 -0
- package/package.json +50 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 djiji
|
|
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 (including the next
|
|
13
|
+
paragraph) shall be included in all copies or substantial portions of the
|
|
14
|
+
Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,403 @@
|
|
|
1
|
-
#
|
|
1
|
+
# freq
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Name: `fetch-request -> freq`
|
|
4
|
+
|
|
5
|
+
Zero-dependency TypeScript HTTP client built on native `fetch`, with built-in SSE parsing.
|
|
6
|
+
|
|
7
|
+
[中文文档](./README-cn.md)
|
|
8
|
+
|
|
9
|
+
- Throws on non-2xx, no need to check `ok` yourself
|
|
10
|
+
- `baseURL` prefix and `query` joined automatically
|
|
11
|
+
- `get` / `post` / `put` / `del` shortcuts, `path` can also be a full `http(s)://` URL
|
|
12
|
+
- Typed: `api.get<User>()` gives you a `User`
|
|
13
|
+
- Parses the body by `content-type`
|
|
14
|
+
- Retry, timeout, cancellation
|
|
15
|
+
- Four hook stages
|
|
16
|
+
- Built-in SSE parsing and reconnection
|
|
17
|
+
- `raw()` returns the native `Response`
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm i @djiji/freq
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Node >= 20.
|
|
24
|
+
|
|
25
|
+
## Quick Start
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { createClient } from "@djiji/freq";
|
|
29
|
+
|
|
30
|
+
// create one client with shared config — this step is required
|
|
31
|
+
const api = createClient({ baseURL: "https://example.com" });
|
|
32
|
+
|
|
33
|
+
// describe the shape you expect
|
|
34
|
+
interface User {
|
|
35
|
+
name: string;
|
|
36
|
+
age: number;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// GET a list of users
|
|
40
|
+
const res = await api.get<User[]>("/users", {
|
|
41
|
+
query: { page: "2", size: "10" },
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
res.code; // 200
|
|
45
|
+
res.data; // [{name: "djiji", age: 18}, {...}]
|
|
46
|
+
res.url; // https://example.com/users?page=2&size=10
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
...
|
|
51
|
+
const api = createClient({}); // an empty config is fine
|
|
52
|
+
...
|
|
53
|
+
const res = await api.get<User[]>("https://example.com/users", {
|
|
54
|
+
query: { page: "2", size: "10" },
|
|
55
|
+
});
|
|
56
|
+
...
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Shortcuts
|
|
60
|
+
|
|
61
|
+
```ts
|
|
62
|
+
api.get("/users", { query: { page: "1" } });
|
|
63
|
+
api.get("https://example.com/users", { query: { page: "1" } }); // absolute URL works
|
|
64
|
+
api.post("/users", { body: { name: "djiji" } });
|
|
65
|
+
api.put("/users/1", { body: { age: 19 } });
|
|
66
|
+
api.del("/users/1");
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
All four are `api.request()` with a `method`:
|
|
70
|
+
|
|
71
|
+
```ts
|
|
72
|
+
// equivalent
|
|
73
|
+
api.request("/users", { method: "GET" });
|
|
74
|
+
api.get("/users");
|
|
75
|
+
...
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Request and Response
|
|
79
|
+
|
|
80
|
+
Note: `.get()`, `.post()`, `.put()` and `.del()` take almost the same options.
|
|
81
|
+
|
|
82
|
+
**Request**
|
|
83
|
+
` const api = createClient(options?: HttpConfig) `
|
|
84
|
+
```ts
|
|
85
|
+
baseURL?: string; // URL prefix
|
|
86
|
+
headers?: HeadersInit; // default headers
|
|
87
|
+
timeout?: number; // request timeout
|
|
88
|
+
signal?: AbortSignal; // cancellation signal
|
|
89
|
+
retry?: number; // retry count, default 0
|
|
90
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // retry delay
|
|
91
|
+
retryCodes?: number[]; // status codes to retry
|
|
92
|
+
hooks?: Hooks; // four hooks
|
|
93
|
+
sseReconnect?: SSEReconnect; // SSE reconnection
|
|
94
|
+
responseType?: ResponseType; // json, text...
|
|
95
|
+
```
|
|
96
|
+
` api.request(path: string, options?: RequestOptions) `
|
|
97
|
+
```ts
|
|
98
|
+
method?: string; // HTTP method
|
|
99
|
+
body?: BodyInit | Record<string, unknown> | unknown[] | null; // plain objects are stringified, content-type is set
|
|
100
|
+
headers?: HeadersInit; // request headers
|
|
101
|
+
timeout?: number; // overrides the global one
|
|
102
|
+
signal?: AbortSignal; // cancellation signal
|
|
103
|
+
query?: Record<string, string>; // joined and encoded automatically
|
|
104
|
+
responseType?: ResponseType; // overrides the global one
|
|
105
|
+
retry?: number; // retry count, default 0
|
|
106
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // retry delay
|
|
107
|
+
retryCodes?: number[]; // status codes to retry
|
|
108
|
+
hooks?: Hooks; // four hooks
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
**Response**
|
|
112
|
+
```ts
|
|
113
|
+
data: T; // parsed body, typed by the generic
|
|
114
|
+
ok: boolean; // always true, failures throw
|
|
115
|
+
code: number; // status code
|
|
116
|
+
url: string; // final URL after redirects
|
|
117
|
+
headers: Headers; // response headers
|
|
118
|
+
redirected: boolean; // whether a redirect happened
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## SSE
|
|
122
|
+
|
|
123
|
+
Low-level: grab the stream yourself and feed it to the built-in parser.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
const res = await api.request<ReadableStream>("/events", {
|
|
127
|
+
headers: { accept: "text/event-stream" },
|
|
128
|
+
responseType: "stream",
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
for await (const ev of parseSSE(res.data!)) {
|
|
132
|
+
console.log(ev.event, ev.data, ev.id);
|
|
133
|
+
}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Shortcut — request and parse in one step:
|
|
137
|
+
|
|
138
|
+
```ts
|
|
139
|
+
for await (const ev of api.sse("/events")) {
|
|
140
|
+
console.log(ev.event, ev.data, ev.id);
|
|
141
|
+
}
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
With `reconnect`, a dropped connection is reopened with `Last-Event-ID` to resume:
|
|
145
|
+
|
|
146
|
+
```ts
|
|
147
|
+
for await (const ev of api.sse("/events", { reconnect: { retry: 3 } })) {
|
|
148
|
+
console.log(ev.data);
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
**Request**
|
|
153
|
+
` for await (const ev of api.sse(path: string, options?: SSEOptions)) `
|
|
154
|
+
```ts
|
|
155
|
+
path: string; // relative path or full http(s):// URL
|
|
156
|
+
method?: string; // HTTP method, default GET
|
|
157
|
+
body?: BodyInit | Record<string, unknown> | unknown[] | null; // request body
|
|
158
|
+
headers?: HeadersInit; // accept: text/event-stream is added when missing
|
|
159
|
+
timeout?: number; // defaults to 0, the global timeout never cuts a long connection
|
|
160
|
+
signal?: AbortSignal; // throws AbortError on cancel
|
|
161
|
+
query?: Record<string, string>; // joined and encoded automatically
|
|
162
|
+
retry?: number; // retries of a single request, forced to 0 when reconnect is set
|
|
163
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // fallback for reconnect delay
|
|
164
|
+
retryCodes?: number[]; // fallback for reconnect codes
|
|
165
|
+
hooks?: Hooks; // four hooks
|
|
166
|
+
reconnect?: SSEReconnect; // without it a dropped stream throws, falls back to the global sseReconnect
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
`reconnect` fields:
|
|
170
|
+
```ts
|
|
171
|
+
retry?: number; // max reconnects, default 0
|
|
172
|
+
delay?: number | ((attempt: number) => number | Promise<number>); // waits Math.max(yours, server retry)
|
|
173
|
+
codes?: number[]; // status codes that trigger a reconnect, defaults to retryCodes
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
**Response**
|
|
177
|
+
```ts
|
|
178
|
+
// AsyncGenerator<SSEMessage>, consumed with for await
|
|
179
|
+
event: string; // "message" when not set
|
|
180
|
+
data: string; // multi-line data joined with \n
|
|
181
|
+
id: string | undefined; // sticky across events
|
|
182
|
+
retry: number | undefined; // server-suggested interval, sticky once sent
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## raw
|
|
186
|
+
|
|
187
|
+
Returns the native `Response`, body untouched.
|
|
188
|
+
|
|
189
|
+
```ts
|
|
190
|
+
const res = await api.raw("/big.zip");
|
|
191
|
+
await res.arrayBuffer();
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
**Request**
|
|
195
|
+
` const res = await api.raw(path: string, options?: RequestOptions) `
|
|
196
|
+
```ts
|
|
197
|
+
path: string; // relative path or full http(s):// URL
|
|
198
|
+
options?: RequestOptions; // same as api.request
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
**Response**
|
|
202
|
+
```ts
|
|
203
|
+
// native Response, body not consumed
|
|
204
|
+
status: number;
|
|
205
|
+
ok: boolean;
|
|
206
|
+
headers: Headers;
|
|
207
|
+
body: ReadableStream<Uint8Array> | null; // read it yourself
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
**Notes**
|
|
211
|
+
|
|
212
|
+
- No status check: 4xx and 5xx come back as-is, check `res.ok` yourself
|
|
213
|
+
- Body is not parsed
|
|
214
|
+
- `Response` and `ResponseError` hooks do not fire
|
|
215
|
+
- No status-code retry: only timeouts (`TimeoutError`) retry, network failures (`TypeError`) do not
|
|
216
|
+
|
|
217
|
+
## Hooks
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
const api = createClient({
|
|
221
|
+
baseURL: "https://api.example.com",
|
|
222
|
+
hooks: {
|
|
223
|
+
Request: [({ headers }) => headers.set("authorization", `Bearer ${token}`)],
|
|
224
|
+
Response: [({ result }) => console.log(result.code)],
|
|
225
|
+
RequestError: [({ error }) => console.warn("request failed", error)],
|
|
226
|
+
ResponseError: [({ error, code }) => console.warn(code, error)],
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
**Request**
|
|
232
|
+
` hooks?: Hooks `
|
|
233
|
+
```ts
|
|
234
|
+
Request?: RequestHook[]; // before sending, edit url / method / headers / body
|
|
235
|
+
Response?: ResponseHook[]; // after parsing, edit result
|
|
236
|
+
RequestError?: RequestErrorHook[]; // fetch itself failed
|
|
237
|
+
ResponseError?: ResponseErrorHook[]; // non-2xx or parse failure
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
Context each hook receives:
|
|
241
|
+
```ts
|
|
242
|
+
// Request
|
|
243
|
+
url: string; method: string; headers: Headers; body: string | undefined;
|
|
244
|
+
// Response
|
|
245
|
+
result: HttpResult<unknown>;
|
|
246
|
+
// RequestError
|
|
247
|
+
error: unknown; url: string; method: string;
|
|
248
|
+
// ResponseError
|
|
249
|
+
error: unknown; code: number; headers: Headers; url: string;
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
**Response**
|
|
253
|
+
```ts
|
|
254
|
+
void | Promise<void>; // nothing is read back, mutate the context instead
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
**Notes**
|
|
258
|
+
|
|
259
|
+
- Run in sequence, a throw stops the rest
|
|
260
|
+
- A thrown hook is wrapped into `HookError` and is not retried
|
|
261
|
+
- Throws inside `RequestError` / `ResponseError` are swallowed
|
|
262
|
+
- Global hooks and per-request hooks stack, global first
|
|
263
|
+
|
|
264
|
+
## Error Handling
|
|
265
|
+
|
|
266
|
+
Everything fails by throwing, so `HttpResult.ok` is always `true`:
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
import {
|
|
270
|
+
HttpError,
|
|
271
|
+
TimeoutError,
|
|
272
|
+
AbortError,
|
|
273
|
+
ParseError,
|
|
274
|
+
HookError,
|
|
275
|
+
} from "@djiji/freq";
|
|
276
|
+
|
|
277
|
+
try {
|
|
278
|
+
await api.get("/missing");
|
|
279
|
+
} catch (e) {
|
|
280
|
+
if (e instanceof HttpError) console.error(e.status, e.body); // non-2xx
|
|
281
|
+
else if (e instanceof TimeoutError) console.error(e.timeout); // timeout
|
|
282
|
+
else if (e instanceof AbortError) console.error("aborted"); // cancelled
|
|
283
|
+
else if (e instanceof ParseError) console.error(e.body); // parse failure
|
|
284
|
+
else if (e instanceof HookError) console.error(e.hook); // hook threw
|
|
285
|
+
}
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
**Thrown types**
|
|
289
|
+
```ts
|
|
290
|
+
HttpError: { status: number; path: string; method: string; body: string; headers: Headers }; // non-2xx
|
|
291
|
+
TimeoutError: { timeout: number; path: string; method: string }; // timeout
|
|
292
|
+
AbortError: { path: string; method: string }; // cancelled
|
|
293
|
+
ParseError: { path: string; method: string; body: string; headers: Headers }; // parse failure
|
|
294
|
+
HookError: { hook: string; cause: unknown }; // hook threw
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
`body` keeps only the first 500 characters.
|
|
298
|
+
|
|
299
|
+
## Retry
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
const api = createClient({
|
|
303
|
+
baseURL: "https://api.example.com",
|
|
304
|
+
retry: 3,
|
|
305
|
+
retryDelay: (attempt) => attempt * 500,
|
|
306
|
+
retryCodes: [429, 500, 502, 503, 504, 508],
|
|
307
|
+
});
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
**Request**
|
|
311
|
+
```ts
|
|
312
|
+
retry?: number; // max retries, default 0; total attempts = retry + 1
|
|
313
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>); // default 1000 * 2 ** (attempt - 1), i.e. 1s, 2s, 4s...
|
|
314
|
+
retryCodes?: number[]; // default [429, 500, 502, 503, 504, 508]
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
**Notes**
|
|
318
|
+
|
|
319
|
+
- Only timeouts and status codes in `retryCodes` are retried
|
|
320
|
+
- Cancellation, parse failures, hook throws and network failures are not retried
|
|
321
|
+
- Per-request fields override the global ones
|
|
322
|
+
- The last error is thrown once retries run out
|
|
323
|
+
|
|
324
|
+
## Timeout and Cancellation
|
|
325
|
+
|
|
326
|
+
```ts
|
|
327
|
+
const api = createClient({ timeout: 10_000 });
|
|
328
|
+
|
|
329
|
+
const ac = new AbortController();
|
|
330
|
+
const pending = api.get("/slow", { signal: ac.signal });
|
|
331
|
+
ac.abort();
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
**Request**
|
|
335
|
+
```ts
|
|
336
|
+
timeout?: number; // milliseconds, 0 or negative means no limit; per-request wins
|
|
337
|
+
signal?: AbortSignal; // merged with the global one, any abort cancels
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
**Thrown types**
|
|
341
|
+
```ts
|
|
342
|
+
TimeoutError: { timeout: number; path: string; method: string; cause: unknown }; // timeout
|
|
343
|
+
AbortError: { path: string; method: string; cause: unknown }; // cancelled, cause is the original DOMException
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
**Notes**
|
|
347
|
+
|
|
348
|
+
- Cancelling during a retry wait aborts immediately
|
|
349
|
+
- `api.sse` uses `timeout: 0`, a long connection is never cut by the global timeout
|
|
350
|
+
|
|
351
|
+
## Request Body
|
|
352
|
+
|
|
353
|
+
**Rules**
|
|
354
|
+
```ts
|
|
355
|
+
plain objects and arrays → JSON.stringify, content-type: application/json is added
|
|
356
|
+
strings → sent as-is, content-type filled by fetch
|
|
357
|
+
FormData, URLSearchParams, Blob → sent as-is, content-type filled by fetch (boundary included)
|
|
358
|
+
null, undefined → no body
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
## Response Parsing
|
|
362
|
+
|
|
363
|
+
**Specify a type**
|
|
364
|
+
```ts
|
|
365
|
+
responseType?: "json" | "text" | "blob" | "arrayBuffer" | "bytes" | "stream"; // when omitted, content-type decides
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
**Rules**
|
|
369
|
+
```ts
|
|
370
|
+
// without responseType, matched top-down against content-type
|
|
371
|
+
contains event-stream → ReadableStream | null
|
|
372
|
+
contains json → parsed value, undefined for an empty body
|
|
373
|
+
text/*, xml, html, svg, form-urlencoded, missing content-type → string, undefined for an empty body
|
|
374
|
+
anything else (images, pdf, octet-stream...) → Blob
|
|
375
|
+
|
|
376
|
+
// with responseType
|
|
377
|
+
"json" → text then JSON.parse, undefined for an empty body, throws ParseError on failure
|
|
378
|
+
"text" → string, undefined for an empty body
|
|
379
|
+
"blob" → Blob
|
|
380
|
+
"arrayBuffer" → ArrayBuffer
|
|
381
|
+
"bytes" → Uint8Array
|
|
382
|
+
"stream" → ReadableStream | null
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
**Response**
|
|
386
|
+
```ts
|
|
387
|
+
data: T; // actual type follows the rules above, T is given at the call site
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
Usage:
|
|
391
|
+
```ts
|
|
392
|
+
await api.get<Data>("/x"); // auto
|
|
393
|
+
await api.get<Data>("/x", { responseType: "json" });
|
|
394
|
+
await api.get<string>("/x", { responseType: "text" });
|
|
395
|
+
await api.get<Blob>("/x", { responseType: "blob" });
|
|
396
|
+
await api.get<Uint8Array>("/x", { responseType: "bytes" });
|
|
397
|
+
await api.get<ArrayBuffer>("/x", { responseType: "arrayBuffer" });
|
|
398
|
+
await api.get<ReadableStream>("/x", { responseType: "stream" });
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
## License
|
|
402
|
+
|
|
403
|
+
MIT © djiji
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** 默认 HTTP 方法。 */
|
|
2
|
+
export declare const DEFAULT_METHOD = "GET";
|
|
3
|
+
/** 默认重试状态码。 */
|
|
4
|
+
export declare const DEFAULT_RETRY_CODES: number[];
|
|
5
|
+
/** 默认退避:1s、2s、4s…(指数)。 */
|
|
6
|
+
export declare const DEFAULT_RETRY_DELAY: (attempt: number) => number;
|
|
7
|
+
/** 错误体/响应体截断长度,避免把整个大 body 塞进 Error。 */
|
|
8
|
+
export declare const MAX_ERROR_BODY = 500;
|
|
9
|
+
//# sourceMappingURL=constants.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":"AAAA,kBAAkB;AAClB,eAAO,MAAM,cAAc,QAAQ,CAAC;AAEpC,eAAe;AACf,eAAO,MAAM,mBAAmB,EAAE,MAAM,EAAmC,CAAC;AAE5E,0BAA0B;AAC1B,eAAO,MAAM,mBAAmB,YAAa,MAAM,WACxB,CAAC;AAE5B,wCAAwC;AACxC,eAAO,MAAM,cAAc,MAAM,CAAC"}
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { HttpConfig, Hooks, HttpResult, RequestOptions, ResponseType } from "./types";
|
|
2
|
+
export declare function readResponse<T>(res: Response, responseType: ResponseType | undefined, path: string, method: string): Promise<HttpResult<T>>;
|
|
3
|
+
interface SendResult {
|
|
4
|
+
response: Response;
|
|
5
|
+
method: string;
|
|
6
|
+
hooks: Hooks;
|
|
7
|
+
}
|
|
8
|
+
export declare function requestResult(config: HttpConfig, path: string, options: RequestOptions | undefined, attempt: number, maxRetry: number, retryCodes: number[]): Promise<SendResult>;
|
|
9
|
+
export declare function once<T = unknown>(config: HttpConfig, path: string, options: RequestOptions | undefined, attempt: number, maxRetry: number, retryCodes: number[]): Promise<HttpResult<T>>;
|
|
10
|
+
export declare function shouldRetry(e: unknown, codes: number[]): boolean;
|
|
11
|
+
export declare function shouldReconnect(e: unknown, codes: number[]): boolean;
|
|
12
|
+
export {};
|
|
13
|
+
//# sourceMappingURL=core.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EACV,UAAU,EACV,KAAK,EACL,UAAU,EAEV,cAAc,EACd,YAAY,EACb,MAAM,SAAS,CAAC;AAgBjB,wBAAsB,YAAY,CAAC,CAAC,EAClC,GAAG,EAAE,QAAQ,EACb,YAAY,EAAE,YAAY,GAAG,SAAS,EACtC,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAwFxB;AAED,UAAU,UAAU;IAClB,QAAQ,EAAE,QAAQ,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,KAAK,CAAC;CACd;AAED,wBAAsB,aAAa,CACjC,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,cAAc,GAAG,SAAS,EACnC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAAE,GACnB,OAAO,CAAC,UAAU,CAAC,CA4ErB;AAED,wBAAsB,IAAI,CAAC,CAAC,GAAG,OAAO,EACpC,MAAM,EAAE,UAAU,EAClB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,cAAc,GAAG,SAAS,EACnC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,EAChB,UAAU,EAAE,MAAM,EAAE,GACnB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CA8CxB;AAED,wBAAgB,WAAW,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAOhE;AAED,wBAAgB,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAMpE"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export declare class HttpError extends Error {
|
|
2
|
+
readonly status: number;
|
|
3
|
+
readonly path: string;
|
|
4
|
+
readonly method: string;
|
|
5
|
+
readonly body: string;
|
|
6
|
+
readonly headers: Headers;
|
|
7
|
+
constructor(status: number, path: string, method: string, body: string, headers: Headers);
|
|
8
|
+
}
|
|
9
|
+
export declare class TimeoutError extends Error {
|
|
10
|
+
readonly timeout: number;
|
|
11
|
+
readonly path: string;
|
|
12
|
+
readonly method: string;
|
|
13
|
+
constructor(timeout: number, path: string, method: string, cause?: unknown);
|
|
14
|
+
}
|
|
15
|
+
export declare class AbortError extends Error {
|
|
16
|
+
readonly path: string;
|
|
17
|
+
readonly method: string;
|
|
18
|
+
constructor(path: string, method: string, cause?: unknown);
|
|
19
|
+
}
|
|
20
|
+
export declare class ParseError extends Error {
|
|
21
|
+
readonly path: string;
|
|
22
|
+
readonly method: string;
|
|
23
|
+
readonly body: string;
|
|
24
|
+
readonly headers: Headers;
|
|
25
|
+
constructor(path: string, method: string, body: string, headers: Headers);
|
|
26
|
+
}
|
|
27
|
+
export declare class HookError extends Error {
|
|
28
|
+
readonly hook: string;
|
|
29
|
+
constructor(hook: string, cause: unknown);
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=errorType.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errorType.d.ts","sourceRoot":"","sources":["../src/errorType.ts"],"names":[],"mappings":"AAAA,qBAAa,SAAU,SAAQ,KAAK;IAClC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAE1B,YACE,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,OAAO,EASjB;CACF;AAED,qBAAa,YAAa,SAAQ,KAAK;IACrC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,YAAY,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,EASzE;CACF;AAED,qBAAa,UAAW,SAAQ,KAAK;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAExB,YAAY,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO,EAQxD;CACF;AAED,qBAAa,UAAW,SAAQ,KAAK;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC;IAE1B,YAAY,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAOvE;CACF;AAED,qBAAa,SAAU,SAAQ,KAAK;IAClC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,YAAY,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAOvC;CACF"}
|
package/dist/hooks.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Hooks, RequestHooksContext, RequestErrorHooksContext, ResponseHooksContext, ResponseErrorHooksContext } from "./types";
|
|
2
|
+
export declare function RequestHooks(brc: RequestHooksContext, hooks: Hooks): Promise<void>;
|
|
3
|
+
export declare function ResponseHooks(brc: ResponseHooksContext, hooks: Hooks): Promise<void>;
|
|
4
|
+
export declare function RequestErrorHooks(brc: RequestErrorHooksContext, hooks: Hooks): Promise<void>;
|
|
5
|
+
export declare function ResponseErrorHooks(brc: ResponseErrorHooksContext, hooks: Hooks): Promise<void>;
|
|
6
|
+
export declare function mergeHooks(base: Hooks | undefined, extra: Hooks | undefined): Hooks;
|
|
7
|
+
//# sourceMappingURL=hooks.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,KAAK,EACL,mBAAmB,EACnB,wBAAwB,EACxB,oBAAoB,EACpB,yBAAyB,EAC1B,MAAM,SAAS,CAAC;AAEjB,wBAAsB,YAAY,CAAC,GAAG,EAAE,mBAAmB,EAAE,KAAK,EAAE,KAAK,iBAQxE;AAED,wBAAsB,aAAa,CAAC,GAAG,EAAE,oBAAoB,EAAE,KAAK,EAAE,KAAK,iBAQ1E;AAED,wBAAsB,iBAAiB,CACrC,GAAG,EAAE,wBAAwB,EAC7B,KAAK,EAAE,KAAK,iBAOb;AAED,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,yBAAyB,EAC9B,KAAK,EAAE,KAAK,iBAOb;AAED,wBAAgB,UAAU,CAAC,IAAI,EAAE,KAAK,GAAG,SAAS,EAAE,KAAK,EAAE,KAAK,GAAG,SAAS,GAAG,KAAK,CAanF"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export { HttpError, TimeoutError, AbortError, ParseError, HookError, } from "./errorType";
|
|
2
|
+
import { parseSSE, type SSEMessage } from "./parse";
|
|
3
|
+
export { parseSSE, type SSEMessage };
|
|
4
|
+
export { readResponse } from "./core";
|
|
5
|
+
export { buildQuery, buildUrl, isAbsoluteUrl } from "./utils";
|
|
6
|
+
import type { DelOptions, GetOptions, HttpConfig, HttpResult, PostOptions, PutOptions, RequestOptions, SSEOptions } from "./types";
|
|
7
|
+
export type { Hooks, HttpConfig, HttpResult, RequestErrorHook, RequestErrorHooksContext, RequestHook, RequestHooksContext, RequestOptions, ResponseErrorHook, ResponseErrorHooksContext, ResponseHook, ResponseHooksContext, ResponseType, SSEReconnect, SSEOptions, } from "./types";
|
|
8
|
+
export declare function createClient(config: HttpConfig): {
|
|
9
|
+
request: <T = unknown>(path: string, options?: RequestOptions) => Promise<HttpResult<T>>;
|
|
10
|
+
get: <T = unknown>(path: string, options?: GetOptions) => Promise<HttpResult<T>>;
|
|
11
|
+
post: <T = unknown>(path: string, options?: PostOptions) => Promise<HttpResult<T>>;
|
|
12
|
+
put: <T = unknown>(path: string, options?: PutOptions) => Promise<HttpResult<T>>;
|
|
13
|
+
del: <T = unknown>(path: string, options?: DelOptions) => Promise<HttpResult<T>>;
|
|
14
|
+
raw: (path: string, options?: RequestOptions) => Promise<Response>;
|
|
15
|
+
sse: (path: string, options?: SSEOptions) => AsyncGenerator<SSEMessage, void, undefined>;
|
|
16
|
+
};
|
|
17
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EACL,SAAS,EACT,YAAY,EACZ,UAAU,EACV,UAAU,EACV,SAAS,GACV,MAAM,aAAa,CAAC;AAErB,OAAO,EAAE,QAAQ,EAAE,KAAK,UAAU,EAAE,MAAM,SAAS,CAAC;AACpD,OAAO,EAAE,QAAQ,EAAE,KAAK,UAAU,EAAE,CAAC;AAGrC,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAC;AAGtC,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAQ9D,OAAO,KAAK,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,UAAU,EACV,WAAW,EACX,UAAU,EACV,cAAc,EACd,UAAU,EACX,MAAM,SAAS,CAAC;AAEjB,YAAY,EACV,KAAK,EACL,UAAU,EACV,UAAU,EACV,gBAAgB,EAChB,wBAAwB,EACxB,WAAW,EACX,mBAAmB,EACnB,cAAc,EACd,iBAAiB,EACjB,yBAAyB,EACzB,YAAY,EACZ,oBAAoB,EACpB,YAAY,EACZ,YAAY,EACZ,UAAU,GACX,MAAM,SAAS,CAAC;AAEjB,wBAAgB,YAAY,CAAC,MAAM,EAAE,UAAU;cAyCtB,CAAC,kBAChB,MAAM,YACF,cAAc,KACvB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;UAMN,CAAC,kBACZ,MAAM,YACF,UAAU,KACnB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;WAIL,CAAC,kBACb,MAAM,YACF,WAAW,KACpB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;UAIN,CAAC,kBACZ,MAAM,YACF,UAAU,KACnB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;UAIN,CAAC,kBACZ,MAAM,YACF,UAAU,KACnB,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;gBAKjB,MAAM,YACF,cAAc,KACvB,OAAO,CAAC,QAAQ,CAAC;gBAmBZ,MAAM,YACF,UAAU,KACnB,cAAc,CAAC,UAAU,EAAE,IAAI,EAAE,SAAS,CAAC;EAiG/C"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var q=class extends Error{status;path;method;body;headers;constructor(t,r,o,n,a){super(`HTTP ${t} ${o} ${r}`),this.name="HttpError",this.status=t,this.path=r,this.method=o,this.body=n,this.headers=a}},S=class extends Error{timeout;path;method;constructor(t,r,o,n){super(`Timeout ${t}ms ${o} ${r}`,n===void 0?void 0:{cause:n}),this.name="TimeoutError",this.timeout=t,this.path=r,this.method=o}},g=class extends Error{path;method;constructor(t,r,o){super(`Aborted ${r} ${t}`,o===void 0?void 0:{cause:o}),this.name="AbortError",this.path=t,this.method=r}},H=class extends Error{path;method;body;headers;constructor(t,r,o,n){super(`Parse error ${r} ${t} ${o}`),this.name="ParseError",this.path=t,this.method=r,this.body=o,this.headers=n}},x=class extends Error{hook;constructor(t,r){super(`hook "${t}" failed: ${r instanceof Error?r.message:String(r)}`,{cause:r}),this.name="HookError",this.hook=t}};function F(e,t){let r=[],o=0,n=0;for(;n<e.length;){let a=e.charCodeAt(n);if(a===10){r.push(e.slice(o,n)),n+=1,o=n;continue}if(a===13){if(n+1<e.length)r.push(e.slice(o,n)),n+=e.charCodeAt(n+1)===10?2:1,o=n;else if(t)r.push(e.slice(o,n)),n+=1,o=n;else break;continue}n+=1}return{lines:r,rest:e.slice(o)}}async function*G(e){let t=e.getReader(),r=new TextDecoder,o="",n,a,c="",l=[];function*k(s){if(s===""){l.length>0&&(yield{event:c||"message",data:l.join(`
|
|
2
|
+
`),id:n,retry:a},l=[]),c="";return}if(s.startsWith(":"))return;let i=s.indexOf(":"),f=i===-1?s:s.slice(0,i),u=i===-1?"":s.slice(i+1);u.startsWith(" ")&&(u=u.slice(1)),f==="data"?l.push(u):f==="event"?c=u:f==="id"?u.includes("\0")||(n=u):f==="retry"&&/^\d+$/.test(u)&&(a=Number(u))}try{for(;;){let{done:s,value:i}=await t.read();if(s){o+=r.decode();let{lines:d}=F(o,!0);for(let h of d)yield*k(h);break}o+=r.decode(i,{stream:!0});let{lines:f,rest:u}=F(o,!1);o=u;for(let d of f)yield*k(d)}}finally{try{await t.cancel()}catch{}t.releaseLock()}}function N(e){if(typeof e!="object"||e===null)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function I(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function U(e,t){if(I(t))return t;if(!e)throw new Error(`baseURL is required when path is not absolute: ${t}`);if(/^\/\/[^/]/.test(t))throw new Error(`protocol-relative URL is not supported: ${t}`);let r=e.replace(/\/+$/,""),o=t.replace(/^\/+/,"");return`${r}/${o}`}function M(e,t){if(!t||Object.keys(t).length===0)return e;let r=new URLSearchParams(t).toString();return e.includes("?")?e.endsWith("?")?`${e}${r}`:`${e}&${r}`:`${e}?${r}`}function _(e,t){return new Promise((r,o)=>{if(t?.aborted){o(t.reason);return}function n(){clearTimeout(a),o(t.reason)}let a=setTimeout(()=>{t?.removeEventListener("abort",n),r()},e);t?.addEventListener("abort",n,{once:!0})})}function $(e){let t=e.filter(r=>r!=null);if(t.length!==0)return t.length===1?t[0]:AbortSignal.any(t)}async function W(e,t){try{for(let r of t.Request??[])await r(e)}catch(r){throw new x("Request",r)}}async function J(e,t){try{for(let r of t.Response??[])await r(e)}catch(r){throw new x("Response",r)}}async function Q(e,t){for(let r of t.RequestError??[])try{await r(e)}catch{}}async function X(e,t){for(let r of t.ResponseError??[])try{await r(e)}catch{}}function z(e,t){return{Request:[...e?.Request??[],...t?.Request??[]],Response:[...e?.Response??[],...t?.Response??[]],RequestError:[...e?.RequestError??[],...t?.RequestError??[]],ResponseError:[...e?.ResponseError??[],...t?.ResponseError??[]]}}var j=[429,500,502,503,504,508],Y=e=>1e3*2**(e-1),L=500;async function K(e,t,r,o){let n={ok:e.ok,code:e.status,url:e.url,headers:e.headers,redirected:e.redirected};switch(t){case"bytes":return{data:await e.bytes(),...n};case"arrayBuffer":return{data:await e.arrayBuffer(),...n};case"blob":return{data:await e.blob(),...n};case"text":return{data:await e.text(),...n};case"json":{let a=await e.text();if(a==="")return{data:void 0,...n};try{return{data:JSON.parse(a),...n}}catch{throw new H(r,o,a.slice(0,L),e.headers)}}case"stream":return{data:e.body??null,...n};case void 0:{let a=(e.headers.get("content-type")??"")?.toLowerCase();if(a.includes("event-stream"))return{data:e.body??null,...n};if(a.includes("json")){let l=await e.text();if(l==="")return{data:void 0,...n};try{return{data:JSON.parse(l),...n}}catch{throw new H(r,o,l.slice(0,L),e.headers)}}if(a?.startsWith("text")||a.includes("xml")||a.includes("html")||a.includes("svg")||a.includes("form-urlencoded")||a===""){let l=await e.text();return{data:l===""?void 0:l,...n}}return{data:await e.blob(),...n}}default:throw new H(r,o,`unsupported responseType: ${String(t)}`,e.headers)}}async function B(e,t,r,o,n,a){let c=new Headers(e.headers);r?.headers&&new Headers(r.headers).forEach((p,m)=>{c.set(m,p)});let{timeout:l,signal:k,query:s,body:i,...f}=r??{},u=e.signal,d=l??e.timeout,h=d&&d>0?AbortSignal.timeout(d):void 0,T=$([u,k,h]),E=U(e.baseURL,t);s&&(E=M(E,s));let w;N(i)||Array.isArray(i)?(w=JSON.stringify(i),c.has("content-type")||c.set("content-type","application/json")):w=i??void 0;let R=f.method??"GET";if(T?.aborted)throw new g(t,R);let y={url:E,method:R,headers:c,body:typeof w=="string"?w:void 0},O=z(e.hooks,r?.hooks);await W(y,O),R=y.method;let D=y.body!==void 0?y.body:w,A={...f,method:R,headers:y.headers,...D!==void 0?{body:D}:{},...T?{signal:T}:{}},P;try{return P=await fetch(y.url,A),{response:P,method:R,hooks:O}}catch(p){let m=p;throw p instanceof DOMException&&p.name==="TimeoutError"&&(m=new S(d,t,R,p)),p instanceof DOMException&&p.name==="AbortError"&&(m=new g(t,R,p)),(o>=n||!v(m,a))&&await Q({error:m,url:y.url,method:R},O),m}}async function V(e,t,r,o,n,a){let c,l="GET",k={};try{let s=await B(e,t,r,o,n,a);if(c=s.response,l=s.method,k=s.hooks,!c.ok){let f=await c.text();throw new q(c.status,t,l,f.slice(0,L),c.headers)}let i=await K(c,r?.responseType??e.responseType,t,l);return await J({result:i},k),i}catch(s){throw(o>=n||!v(s,a))&&c&&!(s instanceof x)&&await X({error:s,code:c.status,headers:c.headers,url:c.url},k),s}}function v(e,t){return e instanceof x||e instanceof g||e instanceof H?!1:e instanceof S?!0:e instanceof q?t.includes(e.status):!1}function Z(e,t){return e instanceof g||e instanceof x||e instanceof H?!1:e instanceof q?t.includes(e.status):!0}function ge(e){async function t(s,i,f){let u=i?.retry??e.retry??0;if(!Number.isInteger(u)||u<0)throw new Error(`retry must be a non-negative integer, got ${u}`);let d=i?.retryCodes??e.retryCodes??j,h=i?.retryDelay??e.retryDelay??Y,T;for(let E=0;E<=u;E++)try{return await f(E,u,d)}catch(w){if(T=w,E>=u||!v(w,d))throw w;let R=typeof h=="function"?await h(E+1):h;try{await _(R,$([e.signal,i?.signal]))}catch(y){throw y instanceof DOMException&&y.name==="AbortError"?new g(s,i?.method??"GET",y):y}}throw T}async function r(s,i){return t(s,i,(f,u,d)=>V(e,s,i,f,u,d))}async function o(s,i){return r(s,{...i,method:"GET"})}async function n(s,i){return r(s,{...i,method:"POST"})}async function a(s,i){return r(s,{...i,method:"PUT"})}async function c(s,i){return r(s,{...i,method:"DELETE"})}async function l(s,i){return t(s,i,async(f,u,d)=>{let{response:h}=await B(e,s,i,f,u,d);return h})}async function*k(s,i){let{reconnect:f,headers:u,...d}=i??{},h=f??e.sseReconnect,T=h?.retry??0,E=h?.codes??d.retryCodes??e.retryCodes??j,w=d.method??"GET",R=$([e.signal,d.signal]),y=0,O,D;for(;;){let A=new Headers(u);A.has("accept")||A.set("accept","text/event-stream"),O!==void 0&&A.set("Last-Event-ID",O);let P=!1;try{let p={...d,headers:A,responseType:"stream",timeout:d.timeout??0};h&&(p.retry=0);let{data:m}=await r(s,p);if(!m)return;for await(let b of G(m))P=!0,b.id!==void 0&&(O=b.id),b.retry!==void 0&&(D=b.retry),yield b;return}catch(p){let m=p;if(p instanceof DOMException&&(p.name==="AbortError"?m=new g(s,w,p):p.name==="TimeoutError"&&(m=new S(d.timeout??0,s,w,p))),P&&(y=0),!h||y>=T||!Z(m,E))throw m;y++;let b=h.delay??d.retryDelay??e.retryDelay,ee=typeof b=="function"?await b(y):b??Y(y),te=Math.max(ee,D??0);try{await _(te,R)}catch(re){throw new g(s,w,re)}}}}return{request:r,get:o,post:n,put:a,del:c,raw:l,sse:k}}export{g as AbortError,x as HookError,q as HttpError,H as ParseError,S as TimeoutError,M as buildQuery,U as buildUrl,ge as createClient,I as isAbsoluteUrl,G as parseSSE,K as readResponse};
|
package/dist/parse.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parse.d.ts","sourceRoot":"","sources":["../src/parse.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,GAAG,SAAS,CAAC;IACvB,KAAK,EAAE,MAAM,GAAG,SAAS,CAAC;CAC3B;AAiDD,wBAAuB,QAAQ,CAC7B,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GACjC,cAAc,CAAC,UAAU,CAAC,CAmE5B"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
export interface HttpConfig {
|
|
2
|
+
baseURL?: string;
|
|
3
|
+
headers?: HeadersInit;
|
|
4
|
+
timeout?: number;
|
|
5
|
+
signal?: AbortSignal;
|
|
6
|
+
retry?: number;
|
|
7
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>);
|
|
8
|
+
retryCodes?: number[];
|
|
9
|
+
hooks?: Hooks;
|
|
10
|
+
sseReconnect?: SSEReconnect;
|
|
11
|
+
responseType?: ResponseType;
|
|
12
|
+
}
|
|
13
|
+
export interface RequestHooksContext {
|
|
14
|
+
url: string;
|
|
15
|
+
method: string;
|
|
16
|
+
headers: Headers;
|
|
17
|
+
body: string | undefined;
|
|
18
|
+
}
|
|
19
|
+
export interface ResponseHooksContext {
|
|
20
|
+
result: HttpResult<unknown>;
|
|
21
|
+
}
|
|
22
|
+
export interface RequestErrorHooksContext {
|
|
23
|
+
error: unknown;
|
|
24
|
+
url: string;
|
|
25
|
+
method: string;
|
|
26
|
+
}
|
|
27
|
+
export interface ResponseErrorHooksContext {
|
|
28
|
+
error: unknown;
|
|
29
|
+
code: number;
|
|
30
|
+
headers: Headers;
|
|
31
|
+
url: string;
|
|
32
|
+
}
|
|
33
|
+
export type RequestHook = (ctx: RequestHooksContext) => void | Promise<void>;
|
|
34
|
+
export type ResponseHook = (ctx: ResponseHooksContext) => void | Promise<void>;
|
|
35
|
+
export type RequestErrorHook = (ctx: RequestErrorHooksContext) => void | Promise<void>;
|
|
36
|
+
export type ResponseErrorHook = (ctx: ResponseErrorHooksContext) => void | Promise<void>;
|
|
37
|
+
export interface Hooks {
|
|
38
|
+
Request?: RequestHook[];
|
|
39
|
+
Response?: ResponseHook[];
|
|
40
|
+
RequestError?: RequestErrorHook[];
|
|
41
|
+
ResponseError?: ResponseErrorHook[];
|
|
42
|
+
}
|
|
43
|
+
export interface RequestOptions extends Omit<RequestInit, "body" | "headers" | "method" | "signal"> {
|
|
44
|
+
method?: string;
|
|
45
|
+
body?: BodyInit | Record<string, unknown> | unknown[] | null;
|
|
46
|
+
headers?: HeadersInit;
|
|
47
|
+
timeout?: number;
|
|
48
|
+
signal?: AbortSignal;
|
|
49
|
+
query?: Record<string, string>;
|
|
50
|
+
responseType?: ResponseType;
|
|
51
|
+
retry?: number;
|
|
52
|
+
retryDelay?: number | ((attempt: number) => number | Promise<number>);
|
|
53
|
+
retryCodes?: number[];
|
|
54
|
+
hooks?: Hooks;
|
|
55
|
+
}
|
|
56
|
+
export interface SSEReconnect {
|
|
57
|
+
retry?: number;
|
|
58
|
+
delay?: number | ((attempt: number) => number | Promise<number>);
|
|
59
|
+
codes?: number[];
|
|
60
|
+
}
|
|
61
|
+
export interface SSEOptions extends Omit<RequestOptions, "responseType"> {
|
|
62
|
+
reconnect?: SSEReconnect;
|
|
63
|
+
}
|
|
64
|
+
type GetOptions = Omit<RequestOptions, "method" | "body">;
|
|
65
|
+
type PostOptions = Omit<RequestOptions, "method">;
|
|
66
|
+
type PutOptions = Omit<RequestOptions, "method">;
|
|
67
|
+
type DelOptions = Omit<RequestOptions, "method">;
|
|
68
|
+
export interface HttpResult<T> {
|
|
69
|
+
data: T;
|
|
70
|
+
ok: boolean;
|
|
71
|
+
code: number;
|
|
72
|
+
url: string;
|
|
73
|
+
headers: Headers;
|
|
74
|
+
redirected: boolean;
|
|
75
|
+
}
|
|
76
|
+
export type ResponseType = "json" | "text" | "blob" | "arrayBuffer" | "bytes" | "stream";
|
|
77
|
+
export type { GetOptions, PostOptions, PutOptions, DelOptions };
|
|
78
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"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"}
|
package/dist/utils.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function isPlainObject(value: unknown): value is Record<string, unknown>;
|
|
2
|
+
export declare function isAbsoluteUrl(input: string): boolean;
|
|
3
|
+
export declare function buildUrl(baseURL: string | undefined, path: string): string;
|
|
4
|
+
export declare function buildQuery(url: string, query: Record<string, string>): string;
|
|
5
|
+
export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
6
|
+
export declare function mergeSignals(list: (AbortSignal | undefined)[]): AbortSignal | undefined;
|
|
7
|
+
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":"AAAA,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAI9E;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAQpD;AAED,wBAAgB,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAS1E;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAM7E;AAED,wBAAgB,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAmBrE;AAED,wBAAgB,YAAY,CAC1B,IAAI,EAAE,CAAC,WAAW,GAAG,SAAS,CAAC,EAAE,GAChC,WAAW,GAAG,SAAS,CAKzB"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,50 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@djiji/freq",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@djiji/freq",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Zero-dependency TypeScript HTTP client built on native fetch, with retry, hooks and SSE.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist"
|
|
16
|
+
],
|
|
17
|
+
"sideEffects": false,
|
|
18
|
+
"engines": {
|
|
19
|
+
"node": ">=20"
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"prepublishOnly": "npm run build",
|
|
23
|
+
"build": "tsup src/index.ts --format esm --minify --clean && tsc -p tsconfig.build.json",
|
|
24
|
+
"check": "tsc --noEmit",
|
|
25
|
+
"test": "tsx --test \"test/**/*.test.ts\""
|
|
26
|
+
},
|
|
27
|
+
"keywords": [
|
|
28
|
+
"http",
|
|
29
|
+
"fetch",
|
|
30
|
+
"client",
|
|
31
|
+
"sse",
|
|
32
|
+
"typescript"
|
|
33
|
+
],
|
|
34
|
+
"author": "djiji",
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"repository": {
|
|
37
|
+
"type": "git",
|
|
38
|
+
"url": "git+https://github.com/xinghenyu/freq.git"
|
|
39
|
+
},
|
|
40
|
+
"homepage": "https://github.com/xinghenyu/freq#readme",
|
|
41
|
+
"bugs": {
|
|
42
|
+
"url": "https://github.com/xinghenyu/freq/issues"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/node": "^26.6.6",
|
|
46
|
+
"tsup": "^9.0.0",
|
|
47
|
+
"tsx": "^4.23.15",
|
|
48
|
+
"typescript": "^7.0.2"
|
|
49
|
+
}
|
|
50
|
+
}
|