@xharness/cordis-plugin-http 0.0.0-stage → 1.6.1-alpha.2

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020-present Shigma
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,196 @@
1
- # Temporary Holding Version
1
+ # @cordisjs/http
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Fetch-based HTTP client for [Cordis](https://cordis.io).
4
+
5
+ ## Features
6
+
7
+ - Browser and Node.js support
8
+ - Proxy agents (HTTP / HTTPS / SOCKS)
9
+ - WebSocket
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { Context } from '@xharness/cordis'
15
+ import HTTP from '@xharness/cordis-plugin-http'
16
+
17
+ const ctx = new Context()
18
+ ctx.plugin(HTTP)
19
+
20
+ const data = await ctx.http.get('https://example.com')
21
+ const data = await ctx.http.post('https://example.com', body)
22
+ const { status, data } = await ctx.http('https://example.com', { method: 'GET' })
23
+ ```
24
+
25
+ ## API
26
+
27
+ ### Instance Methods
28
+
29
+ #### http(url, config?)
30
+
31
+ ```ts
32
+ interface HTTP {
33
+ <T = any>(url: string | URL, config?: Config): Promise<Response<T>>
34
+ }
35
+ ```
36
+
37
+ Send a request.
38
+
39
+ #### http.[get|delete|head](url, config?)
40
+
41
+ ```ts
42
+ interface HTTP {
43
+ get: Request1
44
+ delete: Request1
45
+ head(url: string, config?: Config): Promise<Headers>
46
+ }
47
+
48
+ interface Request1 {
49
+ <K extends keyof ResponseTypes>(url: string, config: Config & { responseType: K }): Promise<ResponseTypes[K]>
50
+ <T = any>(url: string, config?: Config): Promise<T>
51
+ }
52
+ ```
53
+
54
+ Send a GET / DELETE / HEAD request.
55
+
56
+ #### http.[post|put|patch](url, data, config?)
57
+
58
+ ```ts
59
+ interface HTTP {
60
+ patch: Request2
61
+ post: Request2
62
+ put: Request2
63
+ }
64
+
65
+ interface Request2 {
66
+ <K extends keyof ResponseTypes>(url: string, data: any, config: Config & { responseType: K }): Promise<ResponseTypes[K]>
67
+ <T = any>(url: string, data?: any, config?: Config): Promise<T>
68
+ }
69
+ ```
70
+
71
+ #### http.ws(url, config?)
72
+
73
+ ```ts
74
+ interface HTTP {
75
+ ws(url: string | URL, config?: Config): WebSocket
76
+ }
77
+ ```
78
+
79
+ Open a WebSocket connection.
80
+
81
+ > [!NOTE]
82
+ >
83
+ > Currently we will use [`ws`](https://github.com/websockets/ws) package to polyfill [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) in Node.js.
84
+ >
85
+ > Once Node.js has a stable WebSocket API, we will switch to it.
86
+
87
+ #### http.Error.is(error)
88
+
89
+ ```ts
90
+ function is(error: any): error is Http.Error
91
+ ```
92
+
93
+ ### Config
94
+
95
+ ```ts
96
+ interface Config {
97
+ baseUrl?: string
98
+ method?: Method
99
+ headers?: Record<string, string>
100
+ redirect?: RequestRedirect
101
+ keepAlive?: boolean
102
+ params?: Record<string, any>
103
+ data?: any
104
+ responseType?: keyof ResponseTypes
105
+ timeout?: number
106
+ }
107
+ ```
108
+
109
+ #### config.baseUrl
110
+
111
+ The base URL of the request. If it is set, the `url` will be resolved against it.
112
+
113
+ See [URL#base](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL#base).
114
+
115
+ #### config.method
116
+
117
+ See [fetch#method](https://developer.mozilla.org/en-US/docs/Web/API/fetch#method).
118
+
119
+ #### config.headers
120
+
121
+ See [fetch#headers](https://developer.mozilla.org/en-US/docs/Web/API/fetch#headers).
122
+
123
+ #### config.redirect
124
+
125
+ See [fetch#redirect](https://developer.mozilla.org/en-US/docs/Web/API/fetch#redirect).
126
+
127
+ #### config.keepAlive
128
+
129
+ See [fetch#keepalive](https://developer.mozilla.org/en-US/docs/Web/API/fetch#keepalive).
130
+
131
+ #### config.params
132
+
133
+ Additional query parameters. They will be appended to the URL.
134
+
135
+ #### config.data
136
+
137
+ The request body. Currently support below types:
138
+
139
+ - string
140
+ - URLSearchParams
141
+ - ArrayBuffer / ArrayBufferView
142
+ - Blob
143
+ - FormData
144
+ - Object (will be serialized to JSON)
145
+
146
+ #### config.responseType
147
+
148
+ Supported response types:
149
+
150
+ ```ts
151
+ interface ResponseTypes {
152
+ json: any
153
+ text: string
154
+ stream: ReadableStream<Uint8Array>
155
+ blob: Blob
156
+ formdata: FormData
157
+ arraybuffer: ArrayBuffer
158
+ }
159
+ ```
160
+
161
+ #### config.timeout
162
+
163
+ The request timeout in milliseconds.
164
+
165
+ #### config.proxyAgent
166
+
167
+ > [!NOTE]
168
+ >
169
+ > In order to use a proxy agent, you need to install `@cordisjs/plugin-proxy-agent`.
170
+
171
+ ### Response
172
+
173
+ ```ts
174
+ interface Response<T> {
175
+ status: number
176
+ statusText: string
177
+ headers: Headers
178
+ data: T
179
+ }
180
+ ```
181
+
182
+ #### response.status
183
+
184
+ See [Response#status](https://developer.mozilla.org/en-US/docs/Web/API/Response/status).
185
+
186
+ #### response.statusText
187
+
188
+ See [Response#statusText](https://developer.mozilla.org/en-US/docs/Web/API/Response/statusText).
189
+
190
+ #### response.headers
191
+
192
+ See [Response#headers](https://developer.mozilla.org/en-US/docs/Web/API/Response/headers).
193
+
194
+ #### response.data
195
+
196
+ The decoded response body.
package/lib/index.js ADDED
@@ -0,0 +1,348 @@
1
+ import { createRequire } from "node:module";
2
+ import { Service } from "@xharness/cordis";
3
+ import { Binary, defineProperty, isNullable } from "@xharness/cosmokit";
4
+ import fetchFile from "@xharness/cordis-fetch-file";
5
+ import z from "@xharness/schemastery";
6
+ //#region lib/types/index.js
7
+ const kHttpError = Symbol.for("cordis.http.error");
8
+ const kHttpConfig = Symbol.for("cordis.http.config");
9
+ function findOwnValue(source, predicate) {
10
+ for (const key of Reflect.ownKeys(source)) {
11
+ const value = source[key];
12
+ if (predicate(value, key)) return value;
13
+ }
14
+ }
15
+ function setupInternalUndici(undici) {
16
+ const runtime = undici;
17
+ if (!runtime.getGlobalDispatcher) return;
18
+ runtime.Agent ??= runtime.getGlobalDispatcher().constructor;
19
+ if (runtime.ProxyAgent && runtime.buildConnector) return;
20
+ if (!runtime.EnvHttpProxyAgent) return;
21
+ const envAgent = new runtime.EnvHttpProxyAgent({
22
+ httpProxy: "http://localhost",
23
+ noProxy: ""
24
+ });
25
+ const proxyAgent = findOwnValue(envAgent, (value) => {
26
+ return value?.constructor?.name === "ProxyAgent";
27
+ });
28
+ envAgent.close().catch(() => {});
29
+ if (!proxyAgent) return;
30
+ const ProxyAgent = runtime.ProxyAgent ??= proxyAgent.constructor;
31
+ runtime.buildConnector ??= (options = {}) => {
32
+ const agent = new ProxyAgent({
33
+ uri: "http://localhost",
34
+ requestTls: options
35
+ });
36
+ const connector = findOwnValue(agent, (value, key) => {
37
+ if (typeof value !== "function") return false;
38
+ if (typeof key === "symbol" && key.description === "connect endpoint function") return true;
39
+ return value.name === "connect" && value.length === 2;
40
+ });
41
+ agent.close().catch(() => {});
42
+ if (!connector) throw new Error("cannot access the internal undici connector");
43
+ return connector;
44
+ };
45
+ }
46
+ var HttpError = class extends Error {
47
+ code;
48
+ response;
49
+ [kHttpError] = true;
50
+ static is(error) {
51
+ return !!error?.[kHttpError];
52
+ }
53
+ constructor(message, code, response) {
54
+ super(message);
55
+ this.code = code;
56
+ this.response = response;
57
+ }
58
+ };
59
+ /**
60
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
61
+ */
62
+ function encodeRequest(data) {
63
+ if (data instanceof URLSearchParams) return [null, data];
64
+ if (data instanceof ArrayBuffer) return [null, data];
65
+ if (ArrayBuffer.isView(data)) return [null, data];
66
+ if (data instanceof Blob) return [null, data];
67
+ if (isFormData(data)) return [null, data];
68
+ if (data instanceof ReadableStream) return [null, data];
69
+ return ["application/json", JSON.stringify(data)];
70
+ }
71
+ /**
72
+ * Whether data is a multipart form body. Node's global FormData and the
73
+ * `undici` package's are distinct classes, and a request may carry either.
74
+ * @param data - request data.
75
+ * @returns true for a FormData of either class.
76
+ */
77
+ function isFormData(data) {
78
+ const Native = Http.undici?.FormData;
79
+ return data instanceof FormData || Native !== void 0 && data instanceof Native;
80
+ }
81
+ const validateStatus = (status) => status < 400;
82
+ var Http = class Http extends Service {
83
+ config;
84
+ static Error = HttpError;
85
+ static undici;
86
+ static {
87
+ const require = createRequire(import.meta.url);
88
+ try {
89
+ if (process.execArgv.includes("--expose-internals")) {
90
+ this.undici = require("internal/deps/undici/undici");
91
+ setupInternalUndici(this.undici);
92
+ } else this.undici = require("undici");
93
+ } catch {}
94
+ for (const method of ["get", "delete"]) defineProperty(Http.prototype, method, async function(url, config) {
95
+ const response = await this(url, {
96
+ method,
97
+ validateStatus,
98
+ ...config
99
+ });
100
+ return this._decode(response);
101
+ });
102
+ for (const method of [
103
+ "patch",
104
+ "post",
105
+ "put"
106
+ ]) defineProperty(Http.prototype, method, async function(url, data, config) {
107
+ const response = await this(url, {
108
+ method,
109
+ data,
110
+ validateStatus,
111
+ ...config
112
+ });
113
+ return this._decode(response);
114
+ });
115
+ }
116
+ static Config = z.object({
117
+ timeout: z.natural().role("ms").description("等待请求的最长时间。"),
118
+ keepAlive: z.boolean().description("是否保持连接。"),
119
+ proxyAgent: z.string().description("代理服务器地址。")
120
+ });
121
+ Config = z.object({
122
+ baseUrl: z.string().description("基础 URL。"),
123
+ timeout: z.natural().role("ms").description("等待请求的最长时间。"),
124
+ keepAlive: z.boolean().description("是否保持连接。"),
125
+ proxyAgent: z.string().description("代理服务器地址。")
126
+ });
127
+ isError = HttpError.is;
128
+ _decoders = Object.create(null);
129
+ _proxies = Object.create(null);
130
+ constructor(ctx, config = {}) {
131
+ super(ctx, "http");
132
+ this.config = config;
133
+ this.decoder("json", (raw) => raw.json());
134
+ this.decoder("text", (raw) => raw.text());
135
+ this.decoder("blob", (raw) => raw.blob());
136
+ this.decoder("arraybuffer", (raw) => raw.arrayBuffer());
137
+ this.decoder("formdata", (raw) => raw.formData());
138
+ this.decoder("stream", (raw) => raw.body);
139
+ this.decoder("headers", (raw) => raw.headers);
140
+ this.proxy(["http", "https"], (url) => {
141
+ return new this.undici.ProxyAgent(url.href);
142
+ });
143
+ this.ctx.on("http/fetch", async (url, init, config, next) => {
144
+ if (url.protocol !== "file:") return next();
145
+ if (init.method !== "GET") return new Response(null, {
146
+ status: 405,
147
+ statusText: "Method Not Allowed"
148
+ });
149
+ return fetchFile(url, init, {
150
+ download: true,
151
+ onError: ctx.logger.error
152
+ });
153
+ }, { prepend: true });
154
+ this.ctx.on("http/fetch", async (url, init, config, next) => {
155
+ const capture = /^data:([^,]*),(.*)$/.exec(url.href);
156
+ if (!capture) return next();
157
+ if (init.method !== "GET") return new Response(null, {
158
+ status: 405,
159
+ statusText: "Method Not Allowed"
160
+ });
161
+ let [, type, data] = capture;
162
+ let bodyInit = data;
163
+ if (type.endsWith(";base64")) {
164
+ type = type.slice(0, -7);
165
+ bodyInit = Binary.fromBase64(data);
166
+ } else bodyInit = decodeURIComponent(data);
167
+ return new Response(bodyInit, {
168
+ status: 200,
169
+ statusText: "OK",
170
+ headers: { "content-type": type }
171
+ });
172
+ }, { prepend: true });
173
+ }
174
+ get undici() {
175
+ if (Http.undici) return Http.undici;
176
+ throw new Error("please install `undici`");
177
+ }
178
+ static mergeConfig = (target, source) => ({
179
+ ...target,
180
+ ...source,
181
+ headers: {
182
+ ...target?.headers,
183
+ ...source?.headers
184
+ }
185
+ });
186
+ decoder(type, decoder) {
187
+ return this.ctx.effect(() => {
188
+ this._decoders[type] = decoder;
189
+ return () => delete this._decoders[type];
190
+ }, "ctx.http.decoder()");
191
+ }
192
+ proxy(name, factory) {
193
+ return this.ctx.effect(() => {
194
+ for (const key of name) this._proxies[key] = factory;
195
+ return () => {
196
+ for (const key of name) delete this._proxies[key];
197
+ };
198
+ }, "ctx.http.proxy()");
199
+ }
200
+ extend(config = {}) {
201
+ return this[Service.extend]({ config: Http.mergeConfig(this.config, config) });
202
+ }
203
+ resolveConfig(init) {
204
+ return {
205
+ ...this.config,
206
+ ...this[Service.resolveIntercept](),
207
+ ...init
208
+ };
209
+ }
210
+ resolveURL(url, config, isWebSocket = false) {
211
+ try {
212
+ url = new URL(url, config.baseUrl);
213
+ } catch (error) {
214
+ throw new TypeError(`Invalid URL: ${url}`);
215
+ }
216
+ if (isWebSocket) url.protocol = url.protocol.replace(/^http/, "ws");
217
+ for (const [key, value] of Object.entries(config.params ?? {})) {
218
+ if (isNullable(value)) continue;
219
+ url.searchParams.append(key, value);
220
+ }
221
+ return url;
222
+ }
223
+ defaultDecoder(response) {
224
+ const type = response.headers.get("content-type");
225
+ if (type?.startsWith("application/json")) return response.json();
226
+ else if (type?.startsWith("text/")) return response.text();
227
+ else return response.arrayBuffer();
228
+ }
229
+ /**
230
+ * Rebuild a multipart body in the FormData class the `undici` package
231
+ * recognizes. Node's global FormData belongs to the builtin fetch, which is a
232
+ * distinct class from the package's: undici coerces a foreign one to a string,
233
+ * so the request would carry `[object FormData]` instead of the parts.
234
+ * @param data - request data already recognized as a FormData.
235
+ * @returns the same body, or an equivalent one built by undici's class.
236
+ */
237
+ adoptFormData(data) {
238
+ const Native = Http.undici?.FormData;
239
+ if (Native === void 0 || data.constructor === Native) return data;
240
+ const form = new Native();
241
+ data.forEach((value, name) => {
242
+ if (typeof value === "string") form.append(name, value);
243
+ else form.append(name, value, value.name);
244
+ });
245
+ return form;
246
+ }
247
+ async [Service.invoke](...args) {
248
+ let method;
249
+ if (typeof args[1] === "string" || args[1] instanceof URL) method = args.shift();
250
+ const config = this.resolveConfig(args[1]);
251
+ const url = this.resolveURL(args[0], config);
252
+ method ??= config.method ?? "GET";
253
+ if (config.signal?.aborted) throw config.signal.reason;
254
+ const controller = new AbortController();
255
+ const requestSignal = config.signal ? AbortSignal.any([config.signal, controller.signal]) : controller.signal;
256
+ const dispose = this.ctx.effect(() => {
257
+ const timer = config.timeout && setTimeout(() => {
258
+ controller.abort(new HttpError("request timeout", "TIMEOUT"));
259
+ }, config.timeout);
260
+ return () => {
261
+ clearTimeout(timer);
262
+ };
263
+ });
264
+ controller.signal.addEventListener("abort", () => dispose());
265
+ try {
266
+ const headers = new Headers(config.headers);
267
+ const init = {
268
+ method,
269
+ headers,
270
+ body: config.data,
271
+ keepalive: config.keepAlive,
272
+ redirect: config.redirect,
273
+ signal: requestSignal
274
+ };
275
+ if (config.data && typeof config.data === "object") {
276
+ const [type, body] = encodeRequest(isFormData(config.data) ? this.adoptFormData(config.data) : config.data);
277
+ init.body = body;
278
+ if (type && !headers.has("content-type")) headers.append("content-type", type);
279
+ }
280
+ if (init.body) init.duplex = "half";
281
+ if (config.proxyAgent) {
282
+ const proxyURL = new URL(config.proxyAgent);
283
+ const factory = this._proxies[proxyURL.protocol.slice(0, -1)];
284
+ if (!factory) throw new Error(`Cannot resolve proxy agent ${proxyURL}`);
285
+ init.dispatcher = factory(proxyURL);
286
+ }
287
+ const response = await this.ctx.waterfall(this, "http/fetch", url, init, config, () => {
288
+ this.ctx.logger("http:request").debug("%C %s", method, url.href);
289
+ return this.undici.fetch(url, init);
290
+ }).catch((cause) => {
291
+ this.ctx.logger("http:request").debug("%C %s failed: %o", method, url.href, cause);
292
+ if (Http.Error.is(cause)) throw cause;
293
+ const error = new Http.Error(`fetch ${url} failed`);
294
+ error.cause = cause;
295
+ throw error;
296
+ });
297
+ this.ctx.logger("http:response").debug("%C %s %s %s", method, url.href, response.status, response.statusText);
298
+ response[kHttpConfig] = config;
299
+ return response;
300
+ } finally {
301
+ dispose();
302
+ }
303
+ }
304
+ async _decode(response) {
305
+ const config = response[kHttpConfig];
306
+ if (!(config.validateStatus ?? (() => true))(response.status)) throw new Http.Error(response.statusText, "STATUS_ERROR", response);
307
+ if (!config.responseType) return this.defaultDecoder(response);
308
+ let decoder;
309
+ if (typeof config.responseType === "function") decoder = config.responseType;
310
+ else {
311
+ decoder = this._decoders[config.responseType];
312
+ if (!decoder) throw new TypeError(`Unknown responseType: ${config.responseType}`);
313
+ }
314
+ return decoder(response);
315
+ }
316
+ async head(url, config) {
317
+ const response = await this(url, {
318
+ method: "HEAD",
319
+ responseType: "headers",
320
+ ...config
321
+ });
322
+ return this._decode(response);
323
+ }
324
+ ws(url, _config) {
325
+ const config = this.resolveConfig(_config);
326
+ url = this.resolveURL(url, config, true);
327
+ const init = { headers: Object.fromEntries(new Headers(config.headers)) };
328
+ if (config.proxyAgent) {
329
+ const proxyURL = new URL(config.proxyAgent);
330
+ const factory = this._proxies[proxyURL.protocol.slice(0, -1)];
331
+ if (!factory) throw new Error(`Cannot resolve proxy agent ${proxyURL}`);
332
+ init.dispatcher = factory(proxyURL);
333
+ }
334
+ const socket = this.ctx.waterfall(this, "http/websocket", url, init, config, () => {
335
+ this.ctx.logger("http:ws").debug("connect %s", url.href);
336
+ return new this.undici.WebSocket(url, init);
337
+ });
338
+ const dispose = this.ctx.effect(() => {
339
+ return () => socket.close(1e3, "context disposed");
340
+ }, "new WebSocket()");
341
+ socket.addEventListener("close", () => {
342
+ dispose();
343
+ });
344
+ return socket;
345
+ }
346
+ };
347
+ //#endregion
348
+ export { Http, Http as default };
@@ -0,0 +1,143 @@
1
+ import { Context, Service } from '@xharness/cordis';
2
+ import { type Awaitable, type Dict } from '@xharness/cosmokit';
3
+ import type { Dispatcher, RequestInit, WebSocketInit } from 'undici';
4
+ import z from '@xharness/schemastery';
5
+ declare module '@xharness/cordis' {
6
+ interface Context {
7
+ http: Http;
8
+ }
9
+ interface Intercept {
10
+ http: Http.Intercept;
11
+ }
12
+ interface Events {
13
+ 'http/fetch'(this: Http, url: URL, init: RequestInit, config: Http.Config, next: () => Promise<Response>): Promise<Response>;
14
+ 'http/websocket'(this: Http, url: URL, init: WebSocketInit, config: Http.Config, next: () => WebSocket): WebSocket;
15
+ }
16
+ }
17
+ declare const kHttpError: unique symbol;
18
+ declare class HttpError extends Error {
19
+ code?: Http.Error.Code | undefined;
20
+ response?: Response | undefined;
21
+ [kHttpError]: boolean;
22
+ static is(error: any): error is HttpError;
23
+ constructor(message?: string, code?: Http.Error.Code | undefined, response?: Response | undefined);
24
+ }
25
+ export declare namespace Http {
26
+ interface ResponseTypes {
27
+ json: any;
28
+ text: string;
29
+ stream: ReadableStream;
30
+ blob: Blob;
31
+ formdata: FormData;
32
+ arraybuffer: ArrayBuffer;
33
+ headers: Headers;
34
+ }
35
+ interface Request1 {
36
+ <K extends keyof ResponseTypes>(url: string | URL, config: Http.RequestConfig & {
37
+ responseType: K;
38
+ }): Promise<ResponseTypes[K]>;
39
+ <T = any>(url: string | URL, config: Http.RequestConfig & {
40
+ responseType: Decoder<T>;
41
+ }): Promise<T>;
42
+ <T = any>(url: string | URL, config?: Http.RequestConfig): Promise<T>;
43
+ }
44
+ interface Request2 {
45
+ <K extends keyof ResponseTypes>(url: string | URL, data: any, config: Http.RequestConfig & {
46
+ responseType: K;
47
+ }): Promise<ResponseTypes[K]>;
48
+ <T = any>(url: string | URL, data: any, config: Http.RequestConfig & {
49
+ responseType: Decoder<T>;
50
+ }): Promise<T>;
51
+ <T = any>(url: string | URL, data?: any, config?: Http.RequestConfig): Promise<T>;
52
+ }
53
+ interface Intercept {
54
+ baseUrl?: string;
55
+ headers?: Dict;
56
+ timeout?: number;
57
+ proxyAgent?: string;
58
+ }
59
+ interface Config extends Intercept {
60
+ }
61
+ interface RequestConfig extends Config {
62
+ method?: string;
63
+ params?: Dict;
64
+ data?: any;
65
+ keepAlive?: boolean;
66
+ redirect?: RequestRedirect;
67
+ signal?: AbortSignal;
68
+ responseType?: keyof ResponseTypes | Decoder;
69
+ validateStatus?: (status: number) => boolean;
70
+ }
71
+ interface Response<T = any> {
72
+ url: string;
73
+ data: T;
74
+ status: number;
75
+ statusText: string;
76
+ headers: Headers;
77
+ }
78
+ interface AfterFetch {
79
+ url: URL;
80
+ init: RequestInit;
81
+ config: RequestConfig;
82
+ response?: globalThis.Response;
83
+ error?: any;
84
+ }
85
+ type Decoder<T = any> = (raw: globalThis.Response) => Awaitable<T>;
86
+ type Error = HttpError;
87
+ namespace Error {
88
+ type Code = 'TIMEOUT' | 'STATUS_ERROR';
89
+ }
90
+ }
91
+ export interface FileOptions {
92
+ timeout?: number | string;
93
+ }
94
+ export interface Http {
95
+ (url: string | URL, config?: Http.RequestConfig): Promise<Response>;
96
+ config: Http.Config;
97
+ get: Http.Request1;
98
+ delete: Http.Request1;
99
+ patch: Http.Request2;
100
+ post: Http.Request2;
101
+ put: Http.Request2;
102
+ }
103
+ export declare class Http extends Service<Http.Intercept> {
104
+ config: Http.Config;
105
+ static Error: typeof HttpError;
106
+ static undici: typeof import('undici');
107
+ static Config: z<Http.Config>;
108
+ Config: z<Http.Config>;
109
+ isError: typeof HttpError.is;
110
+ private _decoders;
111
+ private _proxies;
112
+ constructor(ctx: Context, config?: Http.Config);
113
+ get undici(): typeof import("undici");
114
+ static mergeConfig: (target: Http.Config, source?: Http.Config) => {
115
+ headers: {
116
+ [x: string]: any;
117
+ };
118
+ baseUrl?: string;
119
+ timeout?: number;
120
+ proxyAgent?: string;
121
+ };
122
+ decoder<K extends keyof Http.ResponseTypes>(type: K, decoder: Http.Decoder<Http.ResponseTypes[K]>): import("@xharness/cordis").Disposable<Promise<void>>;
123
+ proxy(name: string[], factory: (url: URL) => Dispatcher): import("@xharness/cordis").Disposable<Promise<void>>;
124
+ extend(config?: Http.Config): any;
125
+ resolveConfig(init?: Http.RequestConfig): Http.RequestConfig;
126
+ resolveURL(url: string | URL, config: Http.RequestConfig, isWebSocket?: boolean): URL;
127
+ defaultDecoder(response: Response): Promise<any>;
128
+ /**
129
+ * Rebuild a multipart body in the FormData class the `undici` package
130
+ * recognizes. Node's global FormData belongs to the builtin fetch, which is a
131
+ * distinct class from the package's: undici coerces a foreign one to a string,
132
+ * so the request would carry `[object FormData]` instead of the parts.
133
+ * @param data - request data already recognized as a FormData.
134
+ * @returns the same body, or an equivalent one built by undici's class.
135
+ */
136
+ private adoptFormData;
137
+ [Service.invoke](...args: any[]): Promise<Response>;
138
+ private _decode;
139
+ head(url: string | URL, config?: Http.RequestConfig): Promise<any>;
140
+ ws(url: string | URL, _config?: Http.Config): WebSocket;
141
+ }
142
+ export default Http;
143
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAA;AACnD,OAAO,EAAE,KAAK,SAAS,EAA0B,KAAK,IAAI,EAAc,MAAM,oBAAoB,CAAA;AAGlG,OAAO,KAAK,EAAE,UAAU,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,QAAQ,CAAA;AACpE,OAAO,CAAC,MAAM,uBAAuB,CAAA;AAErC,OAAO,QAAQ,kBAAkB,CAAC;IAChC,UAAU,OAAO;QACf,IAAI,EAAE,IAAI,CAAA;KACX;IAED,UAAU,SAA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,GAAG,EAAE,GAAG,KAAK,UAAU;IAavD,MAAM,CAAC,MAAM,GAAE,IAAI,CAAC,MAAW;IAM/B,aAAa,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC,aAAa;IAI5D,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,EAAE,MAAM,EAAE,IAAI,CAAC,aAAa,EAAE,WAAW,UAAQ;IAe7E,cAAc,CAAC,QAAQ,EAAE,QAAQ;IAWjC;;;;;;;OAOG;IACH,OAAO,CAAC,aAAa;IAWf,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,GAAG,IAAI,EAAE,GAAG,EAAE;YA4EvB,OAAO;IAuBf,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,EAAE,MAAM,CAAC,EAAE,IAAI,CAAC,aAAa;IAKzD,EAAE,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,EAAE,OAAO,CAAC,EAAE,IAAI,CAAC,MAAM;CA2B5C;AAED,eAAe,IAAI,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,67 @@
1
1
  {
2
2
  "name": "@xharness/cordis-plugin-http",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "HTTP client service for Cordis",
4
+ "version": "1.6.1-alpha.2",
5
+ "type": "module",
6
+ "files": [
7
+ "lib/index.js",
8
+ "lib/types/**/*.d.ts",
9
+ "lib/types/**/*.d.ts.map",
10
+ "src"
11
+ ],
12
+ "author": "Shigma <shigma10826@gmail.com>",
13
+ "license": "MIT",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/Kuner/XHarness.git",
17
+ "directory": "vendor/http"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/cordiverse/cordis/issues"
21
+ },
22
+ "homepage": "https://github.com/cordiverse/cordis",
23
+ "keywords": [
24
+ "http",
25
+ "fetch",
26
+ "axios",
27
+ "https",
28
+ "undici",
29
+ "client",
30
+ "request",
31
+ "cordis",
32
+ "component"
33
+ ],
34
+ "cordis": {
35
+ "service": {
36
+ "implements": [
37
+ "http"
38
+ ]
39
+ }
40
+ },
41
+ "peerDependencies": {
42
+ "@xharness/cordis": "~4.2.0-alpha.2"
43
+ },
44
+ "devDependencies": {
45
+ "@xharness/cordis-plugin-logger-console": "~1.2.0-alpha.2",
46
+ "@xharness/cordis": "~4.2.0-alpha.2"
47
+ },
48
+ "dependencies": {
49
+ "@xharness/cordis-fetch-file": "~1.0.4-alpha.2",
50
+ "@xharness/cosmokit": "~1.10.0-alpha.2",
51
+ "@xharness/schemastery": "~3.20.0-alpha.2",
52
+ "undici": "8.12.4"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "main": "lib/index.js",
58
+ "types": "lib/types/index.d.ts",
59
+ "exports": {
60
+ ".": {
61
+ "types": "./lib/types/index.d.ts",
62
+ "default": "./lib/index.js"
63
+ },
64
+ "./src/*": "./src/*",
65
+ "./package.json": "./package.json"
66
+ }
6
67
  }
package/src/index.ts ADDED
@@ -0,0 +1,511 @@
1
+ import { Context, Service } from '@xharness/cordis'
2
+ import { type Awaitable, Binary, defineProperty, type Dict, isNullable } from '@xharness/cosmokit'
3
+ import { createRequire } from 'node:module'
4
+ import fetchFile from '@xharness/cordis-fetch-file'
5
+ import type { Dispatcher, RequestInit, WebSocketInit } from 'undici'
6
+ import z from '@xharness/schemastery'
7
+
8
+ declare module '@xharness/cordis' {
9
+ interface Context {
10
+ http: Http
11
+ }
12
+
13
+ interface Intercept {
14
+ http: Http.Intercept
15
+ }
16
+
17
+ interface Events {
18
+ 'http/fetch'(this: Http, url: URL, init: RequestInit, config: Http.Config, next: () => Promise<Response>): Promise<Response>
19
+ 'http/websocket'(this: Http, url: URL, init: WebSocketInit, config: Http.Config, next: () => WebSocket): WebSocket
20
+ }
21
+ }
22
+
23
+ const kHttpError = Symbol.for('cordis.http.error')
24
+ const kHttpConfig = Symbol.for('cordis.http.config')
25
+
26
+ function findOwnValue(source: any, predicate: (value: any, key: PropertyKey) => boolean) {
27
+ for (const key of Reflect.ownKeys(source)) {
28
+ const value = source[key]
29
+ if (predicate(value, key)) return value
30
+ }
31
+ }
32
+
33
+ function setupInternalUndici(undici: typeof import('undici')) {
34
+ const runtime: Partial<typeof import('undici')> = undici
35
+ if (!runtime.getGlobalDispatcher) return
36
+ runtime.Agent ??= runtime.getGlobalDispatcher().constructor as any
37
+ if (runtime.ProxyAgent && runtime.buildConnector) return
38
+ if (!runtime.EnvHttpProxyAgent) return
39
+
40
+ const envAgent = new runtime.EnvHttpProxyAgent({
41
+ httpProxy: 'http://localhost',
42
+ noProxy: '',
43
+ })
44
+ const proxyAgent = findOwnValue(envAgent, (value) => {
45
+ return value?.constructor?.name === 'ProxyAgent'
46
+ })
47
+ envAgent.close().catch(() => {})
48
+ if (!proxyAgent) return
49
+
50
+ const ProxyAgent = runtime.ProxyAgent ??= proxyAgent.constructor
51
+ runtime.buildConnector ??= (options = {}) => {
52
+ const agent = new ProxyAgent({
53
+ uri: 'http://localhost',
54
+ requestTls: options,
55
+ })
56
+ const connector = findOwnValue(agent, (value, key) => {
57
+ if (typeof value !== 'function') return false
58
+ if (typeof key === 'symbol' && key.description === 'connect endpoint function') return true
59
+ return value.name === 'connect' && value.length === 2
60
+ })
61
+ agent.close().catch(() => {})
62
+ if (!connector) throw new Error('cannot access the internal undici connector')
63
+ return connector
64
+ }
65
+ }
66
+
67
+ class HttpError extends Error {
68
+ [kHttpError] = true
69
+
70
+ static is(error: any): error is HttpError {
71
+ return !!error?.[kHttpError]
72
+ }
73
+
74
+ constructor(message?: string, public code?: Http.Error.Code, public response?: Response) {
75
+ super(message)
76
+ }
77
+ }
78
+
79
+ /**
80
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
81
+ */
82
+ function encodeRequest(data: any): [string | null, any] {
83
+ if (data instanceof URLSearchParams) return [null, data]
84
+ if (data instanceof ArrayBuffer) return [null, data]
85
+ if (ArrayBuffer.isView(data)) return [null, data]
86
+ if (data instanceof Blob) return [null, data]
87
+ if (isFormData(data)) return [null, data]
88
+ if (data instanceof ReadableStream) return [null, data]
89
+ return ['application/json', JSON.stringify(data)]
90
+ }
91
+
92
+ /**
93
+ * Whether data is a multipart form body. Node's global FormData and the
94
+ * `undici` package's are distinct classes, and a request may carry either.
95
+ * @param data - request data.
96
+ * @returns true for a FormData of either class.
97
+ */
98
+ function isFormData(data: unknown): boolean {
99
+ const Native = Http.undici?.FormData as (new () => object) | undefined
100
+ return data instanceof FormData || (Native !== undefined && data instanceof Native)
101
+ }
102
+
103
+ export namespace Http {
104
+ export interface ResponseTypes {
105
+ json: any
106
+ text: string
107
+ stream: ReadableStream
108
+ blob: Blob
109
+ formdata: FormData
110
+ arraybuffer: ArrayBuffer
111
+ headers: Headers
112
+ }
113
+
114
+ export interface Request1 {
115
+ <K extends keyof ResponseTypes>(url: string | URL, config: Http.RequestConfig & { responseType: K }): Promise<ResponseTypes[K]>
116
+ <T = any>(url: string | URL, config: Http.RequestConfig & { responseType: Decoder<T> }): Promise<T>
117
+ <T = any>(url: string | URL, config?: Http.RequestConfig): Promise<T>
118
+ }
119
+
120
+ export interface Request2 {
121
+ <K extends keyof ResponseTypes>(url: string | URL, data: any, config: Http.RequestConfig & { responseType: K }): Promise<ResponseTypes[K]>
122
+ <T = any>(url: string | URL, data: any, config: Http.RequestConfig & { responseType: Decoder<T> }): Promise<T>
123
+ <T = any>(url: string | URL, data?: any, config?: Http.RequestConfig): Promise<T>
124
+ }
125
+
126
+ export interface Intercept {
127
+ baseUrl?: string
128
+ headers?: Dict
129
+ timeout?: number
130
+ proxyAgent?: string
131
+ }
132
+
133
+ export interface Config extends Intercept {}
134
+
135
+ export interface RequestConfig extends Config {
136
+ method?: string
137
+ params?: Dict
138
+ data?: any
139
+ keepAlive?: boolean
140
+ redirect?: RequestRedirect
141
+ signal?: AbortSignal
142
+ responseType?: keyof ResponseTypes | Decoder
143
+ validateStatus?: (status: number) => boolean
144
+ }
145
+
146
+ export interface Response<T = any> {
147
+ url: string
148
+ data: T
149
+ status: number
150
+ statusText: string
151
+ headers: Headers
152
+ }
153
+
154
+ export interface AfterFetch {
155
+ url: URL
156
+ init: RequestInit
157
+ config: RequestConfig
158
+ response?: globalThis.Response
159
+ error?: any
160
+ }
161
+
162
+ export type Decoder<T = any> = (raw: globalThis.Response) => Awaitable<T>
163
+
164
+ export type Error = HttpError
165
+
166
+ export namespace Error {
167
+ export type Code = 'TIMEOUT' | 'STATUS_ERROR'
168
+ }
169
+ }
170
+
171
+ export interface FileOptions {
172
+ timeout?: number | string
173
+ }
174
+
175
+ export interface Http {
176
+ (url: string | URL, config?: Http.RequestConfig): Promise<Response>
177
+ config: Http.Config
178
+ get: Http.Request1
179
+ delete: Http.Request1
180
+ patch: Http.Request2
181
+ post: Http.Request2
182
+ put: Http.Request2
183
+ }
184
+
185
+ // we don't use `raw.ok` because it may be a 3xx redirect
186
+ const validateStatus = (status: number) => status < 400
187
+
188
+ export class Http extends Service<Http.Intercept> {
189
+ static Error = HttpError
190
+
191
+ static undici: typeof import('undici')
192
+
193
+ static {
194
+ const require = createRequire(import.meta.url)
195
+ try {
196
+ if (process.execArgv.includes('--expose-internals')) {
197
+ this.undici = require('internal/deps/undici/undici')
198
+ setupInternalUndici(this.undici)
199
+ } else {
200
+ this.undici = require('undici')
201
+ }
202
+ } catch {}
203
+
204
+ for (const method of ['get', 'delete'] as const) {
205
+ defineProperty(Http.prototype, method, async function (this: Http, url: string | URL, config?: Http.Config) {
206
+ const response = await this(url, { method, validateStatus, ...config })
207
+ return this._decode(response)
208
+ })
209
+ }
210
+
211
+ for (const method of ['patch', 'post', 'put'] as const) {
212
+ defineProperty(Http.prototype, method, async function (this: Http, url: string | URL, data?: any, config?: Http.Config) {
213
+ const response = await this(url, { method, data, validateStatus, ...config })
214
+ return this._decode(response)
215
+ })
216
+ }
217
+ }
218
+
219
+ static Config: z<Http.Config> = z.object({
220
+ timeout: z.natural().role('ms').description('等待请求的最长时间。'),
221
+ keepAlive: z.boolean().description('是否保持连接。'),
222
+ proxyAgent: z.string().description('代理服务器地址。'),
223
+ })
224
+
225
+ Config: z<Http.Config> = z.object({
226
+ baseUrl: z.string().description('基础 URL。'),
227
+ timeout: z.natural().role('ms').description('等待请求的最长时间。'),
228
+ keepAlive: z.boolean().description('是否保持连接。'),
229
+ proxyAgent: z.string().description('代理服务器地址。'),
230
+ })
231
+
232
+ public isError = HttpError.is
233
+
234
+ private _decoders: Dict = Object.create(null)
235
+ private _proxies: Dict<(url: URL) => Dispatcher> = Object.create(null)
236
+
237
+ constructor(ctx: Context, public config: Http.Config = {}) {
238
+ super(ctx, 'http')
239
+
240
+ this.decoder('json', (raw) => raw.json())
241
+ this.decoder('text', (raw) => raw.text())
242
+ this.decoder('blob', (raw) => raw.blob())
243
+ this.decoder('arraybuffer', (raw) => raw.arrayBuffer())
244
+ this.decoder('formdata', (raw) => raw.formData())
245
+ this.decoder('stream', (raw) => raw.body!)
246
+ this.decoder('headers', (raw) => raw.headers)
247
+
248
+ this.proxy(['http', 'https'], (url) => {
249
+ return new this.undici.ProxyAgent(url.href)
250
+ })
251
+
252
+ // file: URL
253
+ this.ctx.on('http/fetch', async (url, init, config, next) => {
254
+ if (url.protocol !== 'file:') return next()
255
+ if (init.method !== 'GET') {
256
+ return new Response(null, { status: 405, statusText: 'Method Not Allowed' })
257
+ }
258
+ return fetchFile(url, init as globalThis.RequestInit, {
259
+ download: true,
260
+ onError: ctx.logger.error,
261
+ })
262
+ }, { prepend: true })
263
+
264
+ // data: URL
265
+ // https://developer.mozilla.org/en-US/docs/Web/URI/Reference/Schemes/data
266
+ this.ctx.on('http/fetch', async (url, init, config, next) => {
267
+ // data:[<media-type>][;base64],<data>
268
+ const capture = /^data:([^,]*),(.*)$/.exec(url.href)
269
+ if (!capture) return next()
270
+ if (init.method !== 'GET') {
271
+ return new Response(null, { status: 405, statusText: 'Method Not Allowed' })
272
+ }
273
+ let [, type, data] = capture
274
+ let bodyInit: BodyInit = data
275
+ if (type.endsWith(';base64')) {
276
+ type = type.slice(0, -7)
277
+ bodyInit = Binary.fromBase64(data)
278
+ } else {
279
+ bodyInit = decodeURIComponent(data)
280
+ }
281
+ return new Response(bodyInit, {
282
+ status: 200,
283
+ statusText: 'OK',
284
+ headers: { 'content-type': type },
285
+ })
286
+ }, { prepend: true })
287
+ }
288
+
289
+ get undici() {
290
+ if (Http.undici) return Http.undici
291
+ throw new Error('please install `undici`')
292
+ }
293
+
294
+ static mergeConfig = (target: Http.Config, source?: Http.Config) => ({
295
+ ...target,
296
+ ...source,
297
+ headers: {
298
+ ...target?.headers,
299
+ ...source?.headers,
300
+ },
301
+ })
302
+
303
+ decoder<K extends keyof Http.ResponseTypes>(type: K, decoder: Http.Decoder<Http.ResponseTypes[K]>) {
304
+ return this.ctx.effect(() => {
305
+ this._decoders[type] = decoder
306
+ return () => delete this._decoders[type]
307
+ }, 'ctx.http.decoder()')
308
+ }
309
+
310
+ proxy(name: string[], factory: (url: URL) => Dispatcher) {
311
+ return this.ctx.effect(() => {
312
+ for (const key of name) {
313
+ this._proxies[key] = factory
314
+ }
315
+ return () => {
316
+ for (const key of name) {
317
+ delete this._proxies[key]
318
+ }
319
+ }
320
+ }, 'ctx.http.proxy()')
321
+ }
322
+
323
+ extend(config: Http.Config = {}) {
324
+ return this[Service.extend]({
325
+ config: Http.mergeConfig(this.config, config),
326
+ })
327
+ }
328
+
329
+ resolveConfig(init?: Http.RequestConfig): Http.RequestConfig {
330
+ return { ...this.config, ...this[Service.resolveIntercept](), ...init }
331
+ }
332
+
333
+ resolveURL(url: string | URL, config: Http.RequestConfig, isWebSocket = false) {
334
+ try {
335
+ url = new URL(url, config.baseUrl)
336
+ } catch (error) {
337
+ // prettify the error message
338
+ throw new TypeError(`Invalid URL: ${url}`)
339
+ }
340
+ if (isWebSocket) url.protocol = url.protocol.replace(/^http/, 'ws')
341
+ for (const [key, value] of Object.entries(config.params ?? {})) {
342
+ if (isNullable(value)) continue
343
+ url.searchParams.append(key, value)
344
+ }
345
+ return url
346
+ }
347
+
348
+ defaultDecoder(response: Response) {
349
+ const type = response.headers.get('content-type')
350
+ if (type?.startsWith('application/json')) {
351
+ return response.json()
352
+ } else if (type?.startsWith('text/')) {
353
+ return response.text()
354
+ } else {
355
+ return response.arrayBuffer()
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Rebuild a multipart body in the FormData class the `undici` package
361
+ * recognizes. Node's global FormData belongs to the builtin fetch, which is a
362
+ * distinct class from the package's: undici coerces a foreign one to a string,
363
+ * so the request would carry `[object FormData]` instead of the parts.
364
+ * @param data - request data already recognized as a FormData.
365
+ * @returns the same body, or an equivalent one built by undici's class.
366
+ */
367
+ private adoptFormData(data: FormData): FormData {
368
+ const Native = Http.undici?.FormData as (new () => FormData) | undefined
369
+ if (Native === undefined || data.constructor === Native) return data
370
+ const form = new Native()
371
+ data.forEach((value, name) => {
372
+ if (typeof value === 'string') form.append(name, value)
373
+ else form.append(name, value, value.name)
374
+ })
375
+ return form
376
+ }
377
+
378
+ async [Service.invoke](...args: any[]) {
379
+ let method: string | undefined
380
+ if (typeof args[1] === 'string' || args[1] instanceof URL) {
381
+ method = args.shift()
382
+ }
383
+ const config = this.resolveConfig(args[1])
384
+ const url = this.resolveURL(args[0], config)
385
+ method ??= config.method ?? 'GET'
386
+
387
+ if (config.signal?.aborted) {
388
+ throw config.signal.reason
389
+ }
390
+ const controller = new AbortController()
391
+ // Combine without attaching a strong listener to `config.signal` so repeated requests sharing a long-lived
392
+ // signal cannot accumulate closures while still cancelling both headers and response-body reads.
393
+ const requestSignal = config.signal ? AbortSignal.any([config.signal, controller.signal]) : controller.signal
394
+
395
+ const dispose = this.ctx.effect(() => {
396
+ const timer = config.timeout && setTimeout(() => {
397
+ controller.abort(new HttpError('request timeout', 'TIMEOUT'))
398
+ }, config.timeout)
399
+ return () => {
400
+ clearTimeout(timer)
401
+ }
402
+ })
403
+ controller.signal.addEventListener('abort', () => dispose())
404
+
405
+ try {
406
+ const headers = new Headers(config.headers)
407
+ const init: RequestInit = {
408
+ method,
409
+ headers: headers as any,
410
+ body: config.data,
411
+ keepalive: config.keepAlive,
412
+ redirect: config.redirect,
413
+ signal: requestSignal,
414
+ }
415
+
416
+ if (config.data && typeof config.data === 'object') {
417
+ const [type, body] = encodeRequest(isFormData(config.data) ? this.adoptFormData(config.data) : config.data)
418
+ init.body = body
419
+ if (type && !headers.has('content-type')) {
420
+ headers.append('content-type', type)
421
+ }
422
+ }
423
+
424
+ if (init.body) {
425
+ (init as any).duplex = 'half'
426
+ }
427
+
428
+ if (config.proxyAgent) {
429
+ const proxyURL = new URL(config.proxyAgent)
430
+ const factory = this._proxies[proxyURL.protocol.slice(0, -1)]
431
+ if (!factory) throw new Error(`Cannot resolve proxy agent ${proxyURL}`)
432
+ init.dispatcher = factory(proxyURL)
433
+ }
434
+
435
+ const response = await this.ctx.waterfall(this, 'http/fetch', url, init, config, () => {
436
+ this.ctx.logger('http:request').debug('%C %s', method, url.href)
437
+ return this.undici.fetch(url, init) as any
438
+ }).catch((cause) => {
439
+ this.ctx.logger('http:request').debug('%C %s failed: %o', method, url.href, cause)
440
+ if (Http.Error.is(cause)) throw cause
441
+ const error = new Http.Error(`fetch ${url} failed`)
442
+ error.cause = cause
443
+ throw error
444
+ })
445
+
446
+ this.ctx.logger('http:response').debug('%C %s %s %s', method, url.href, response.status, response.statusText)
447
+ response[kHttpConfig] = config
448
+ return response
449
+ } finally {
450
+ dispose()
451
+ }
452
+ }
453
+
454
+ private async _decode(response: Response) {
455
+ const config: Http.RequestConfig = response[kHttpConfig]
456
+ const validateStatus = config.validateStatus ?? (() => true)
457
+ if (!validateStatus(response.status)) {
458
+ throw new Http.Error(response.statusText, 'STATUS_ERROR', response)
459
+ }
460
+
461
+ if (!config.responseType) {
462
+ return this.defaultDecoder(response)
463
+ }
464
+
465
+ let decoder: Http.Decoder
466
+ if (typeof config.responseType === 'function') {
467
+ decoder = config.responseType
468
+ } else {
469
+ decoder = this._decoders[config.responseType]
470
+ if (!decoder) {
471
+ throw new TypeError(`Unknown responseType: ${config.responseType}`)
472
+ }
473
+ }
474
+ return decoder(response)
475
+ }
476
+
477
+ async head(url: string | URL, config?: Http.RequestConfig) {
478
+ const response = await this(url, { method: 'HEAD', responseType: 'headers', ...config })
479
+ return this._decode(response)
480
+ }
481
+
482
+ ws(url: string | URL, _config?: Http.Config) {
483
+ const config = this.resolveConfig(_config)
484
+ url = this.resolveURL(url, config, true)
485
+ const headers = Object.fromEntries(new Headers(config.headers))
486
+ const init: WebSocketInit = {
487
+ headers,
488
+ }
489
+
490
+ if (config.proxyAgent) {
491
+ const proxyURL = new URL(config.proxyAgent)
492
+ const factory = this._proxies[proxyURL.protocol.slice(0, -1)]
493
+ if (!factory) throw new Error(`Cannot resolve proxy agent ${proxyURL}`)
494
+ init.dispatcher = factory(proxyURL)
495
+ }
496
+
497
+ const socket = this.ctx.waterfall(this, 'http/websocket', url, init, config, () => {
498
+ this.ctx.logger('http:ws').debug('connect %s', url.href)
499
+ return new this.undici.WebSocket(url, init) as any
500
+ })
501
+ const dispose = this.ctx.effect(() => {
502
+ return () => socket.close(1000, 'context disposed')
503
+ }, 'new WebSocket()')
504
+ socket.addEventListener('close', () => {
505
+ dispose()
506
+ })
507
+ return socket
508
+ }
509
+ }
510
+
511
+ export default Http