Line data Source code
1 : import type {
2 : AxiosAdapter,
3 : AxiosResponse,
4 : InternalAxiosRequestConfig
5 : } from 'axios'
6 : import axios, { AxiosError } from 'axios'
7 :
8 : import {
9 : combineAbortSignals,
10 : createTimeoutSignal
11 : } from '@comfyorg/api-client/abortSignal'
12 : import type { WebSessionSend } from '@comfyorg/api-client/webSessionFetch'
13 :
14 0 : function requestHeaders({ headers }: InternalAxiosRequestConfig): Headers {
15 0 : const result = new Headers()
16 0 : for (const [name, value] of Object.entries(headers.toJSON(true))) {
17 0 : if (typeof value === 'string') result.set(name, value)
18 : }
19 0 : return result
20 : }
21 :
22 0 : function requestSignal({
23 : signal,
24 : timeout
25 : }: InternalAxiosRequestConfig): AbortSignal {
26 0 : const signals: AbortSignal[] = []
27 0 : if (signal instanceof AbortSignal) signals.push(signal)
28 0 : if (timeout) signals.push(createTimeoutSignal(timeout))
29 0 : return combineAbortSignals(signals)
30 : }
31 :
32 0 : function statusError(
33 : config: InternalAxiosRequestConfig,
34 : response: AxiosResponse<string>
35 : ): AxiosError {
36 0 : return new AxiosError(
37 : `Request failed with status code ${response.status}`,
38 : response.status >= 500
39 : ? AxiosError.ERR_BAD_RESPONSE
40 : : AxiosError.ERR_BAD_REQUEST,
41 : config,
42 : undefined,
43 : response
44 : )
45 : }
46 :
47 0 : export function createWebSessionAdapter(send: WebSessionSend): AxiosAdapter {
48 0 : return async (config) => {
49 0 : const signal = requestSignal(config)
50 0 : let response: Response
51 0 : try {
52 0 : response = await send(axios.getUri(config), {
53 : method: config.method?.toUpperCase(),
54 : headers: requestHeaders(config),
55 : body: config.data,
56 : signal
57 : })
58 : } catch (error) {
59 0 : throw AxiosError.from(
60 : error,
61 : signal.aborted
62 : ? signal.reason instanceof DOMException &&
63 : signal.reason.name === 'TimeoutError'
64 : ? AxiosError.ETIMEDOUT
65 : : AxiosError.ERR_CANCELED
66 : : AxiosError.ERR_NETWORK,
67 : config
68 : )
69 : }
70 :
71 0 : const result: AxiosResponse<string> = {
72 : data: await response.text(),
73 : status: response.status,
74 : statusText: response.statusText,
75 : headers: Object.fromEntries(response.headers),
76 : config
77 : }
78 0 : if (config.validateStatus?.(result.status) === false) {
79 0 : throw statusError(config, result)
80 : }
81 0 : return result
82 : }
83 : }
|