Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
quarto-dev
GitHub Repository: quarto-dev/quarto-cli
Path: blob/main/src/publish/netlify/api/core/request.ts
6464 views
1
// deno-lint-ignore-file
2
/* istanbul ignore file */
3
/* tslint:disable */
4
/* eslint-disable */
5
import { ApiError } from "./ApiError.ts";
6
import type { ApiRequestOptions } from "./ApiRequestOptions.ts";
7
import type { ApiResult } from "./ApiResult.ts";
8
import { CancelablePromise } from "./CancelablePromise.ts";
9
import type { OnCancel } from "./CancelablePromise.ts";
10
import type { OpenAPIConfig } from "./OpenAPI.ts";
11
12
const isDefined = <T>(
13
value: T | null | undefined,
14
): value is Exclude<T, null | undefined> => {
15
return value !== undefined && value !== null;
16
};
17
18
const isString = (value: any): value is string => {
19
return typeof value === "string";
20
};
21
22
const isStringWithValue = (value: any): value is string => {
23
return isString(value) && value !== "";
24
};
25
26
const isBlob = (value: any): value is Blob => {
27
return (
28
typeof value === "object" &&
29
typeof value.type === "string" &&
30
typeof value.stream === "function" &&
31
typeof value.arrayBuffer === "function" &&
32
typeof value.constructor === "function" &&
33
typeof value.constructor.name === "string" &&
34
/^(Blob|File)$/.test(value.constructor.name) &&
35
/^(Blob|File)$/.test(value[Symbol.toStringTag])
36
);
37
};
38
39
const isFormData = (value: any): value is FormData => {
40
return value instanceof FormData;
41
};
42
43
const base64 = (str: string): string => {
44
try {
45
return btoa(str);
46
} catch (err) {
47
// @ts-ignore
48
return Buffer.from(str).toString("base64");
49
}
50
};
51
52
const getQueryString = (params: Record<string, any>): string => {
53
const qs: string[] = [];
54
55
const append = (key: string, value: any) => {
56
qs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
57
};
58
59
const process = (key: string, value: any) => {
60
if (isDefined(value)) {
61
if (Array.isArray(value)) {
62
value.forEach((v) => {
63
process(key, v);
64
});
65
} else if (typeof value === "object") {
66
Object.entries(value).forEach(([k, v]) => {
67
process(`${key}[${k}]`, v);
68
});
69
} else {
70
append(key, value);
71
}
72
}
73
};
74
75
Object.entries(params).forEach(([key, value]) => {
76
process(key, value);
77
});
78
79
if (qs.length > 0) {
80
return `?${qs.join("&")}`;
81
}
82
83
return "";
84
};
85
86
const getUrl = (config: OpenAPIConfig, options: ApiRequestOptions): string => {
87
const encoder = config.ENCODE_PATH || encodeURI;
88
89
const path = options.url
90
.replace("{api-version}", config.VERSION)
91
.replace(/{(.*?)}/g, (substring: string, group: string) => {
92
if (options.path?.hasOwnProperty(group)) {
93
return encoder(String(options.path[group]));
94
}
95
return substring;
96
});
97
98
const url = `${config.BASE}${path}`;
99
if (options.query) {
100
return `${url}${getQueryString(options.query)}`;
101
}
102
return url;
103
};
104
105
const getFormData = (options: ApiRequestOptions): FormData | undefined => {
106
if (options.formData) {
107
const formData = new FormData();
108
109
const process = (key: string, value: any) => {
110
if (isString(value) || isBlob(value)) {
111
formData.append(key, value);
112
} else {
113
formData.append(key, JSON.stringify(value));
114
}
115
};
116
117
Object.entries(options.formData)
118
.filter(([_, value]) => isDefined(value))
119
.forEach(([key, value]) => {
120
if (Array.isArray(value)) {
121
value.forEach((v) => process(key, v));
122
} else {
123
process(key, value);
124
}
125
});
126
127
return formData;
128
}
129
return undefined;
130
};
131
132
type Resolver<T> = (options: ApiRequestOptions) => Promise<T>;
133
134
const resolve = async <T>(
135
options: ApiRequestOptions,
136
resolver?: T | Resolver<T>,
137
): Promise<T | undefined> => {
138
if (typeof resolver === "function") {
139
return (resolver as Resolver<T>)(options);
140
}
141
return resolver;
142
};
143
144
const getHeaders = async (
145
config: OpenAPIConfig,
146
options: ApiRequestOptions,
147
): Promise<Headers> => {
148
const token = await resolve(options, config.TOKEN);
149
const username = await resolve(options, config.USERNAME);
150
const password = await resolve(options, config.PASSWORD);
151
const additionalHeaders = await resolve(options, config.HEADERS);
152
153
const headers = Object.entries({
154
Accept: "application/json",
155
...additionalHeaders,
156
...options.headers,
157
})
158
.filter(([_, value]) => isDefined(value))
159
.reduce((headers, [key, value]) => ({
160
...headers,
161
[key]: String(value),
162
}), {} as Record<string, string>);
163
164
if (isStringWithValue(token)) {
165
headers["Authorization"] = `Bearer ${token}`;
166
}
167
168
if (isStringWithValue(username) && isStringWithValue(password)) {
169
const credentials = base64(`${username}:${password}`);
170
headers["Authorization"] = `Basic ${credentials}`;
171
}
172
173
if (options.body) {
174
if (options.mediaType) {
175
headers["Content-Type"] = options.mediaType;
176
} else if (isBlob(options.body)) {
177
headers["Content-Type"] = options.body.type || "application/octet-stream";
178
} else if (isString(options.body)) {
179
headers["Content-Type"] = "text/plain";
180
} else if (!isFormData(options.body)) {
181
headers["Content-Type"] = "application/json";
182
}
183
}
184
185
return new Headers(headers);
186
};
187
188
const getRequestBody = (options: ApiRequestOptions): any => {
189
if (options.body) {
190
if (options.mediaType?.includes("/json")) {
191
return JSON.stringify(options.body);
192
} else if (
193
isString(options.body) || isBlob(options.body) || isFormData(options.body)
194
) {
195
return options.body;
196
} else {
197
return JSON.stringify(options.body);
198
}
199
}
200
return undefined;
201
};
202
203
export const sendRequest = async (
204
config: OpenAPIConfig,
205
options: ApiRequestOptions,
206
url: string,
207
body: any,
208
formData: FormData | undefined,
209
headers: Headers,
210
onCancel: OnCancel,
211
): Promise<Response> => {
212
const controller = new AbortController();
213
214
const request: RequestInit = {
215
headers,
216
body: body ?? formData,
217
method: options.method,
218
signal: controller.signal,
219
};
220
221
if (config.WITH_CREDENTIALS) {
222
request.credentials = config.CREDENTIALS;
223
}
224
225
onCancel(() => controller.abort());
226
227
return await fetch(url, request);
228
};
229
230
const getResponseHeader = (
231
response: Response,
232
responseHeader?: string,
233
): string | undefined => {
234
if (responseHeader) {
235
const content = response.headers.get(responseHeader);
236
if (isString(content)) {
237
return content;
238
}
239
}
240
return undefined;
241
};
242
243
const getResponseBody = async (response: Response): Promise<any> => {
244
if (response.status !== 204) {
245
try {
246
const contentType = response.headers.get("Content-Type");
247
if (contentType) {
248
const isJSON = contentType.toLowerCase().startsWith("application/json");
249
if (isJSON) {
250
return await response.json();
251
} else {
252
return await response.text();
253
}
254
}
255
} catch (error) {
256
console.error(error);
257
}
258
}
259
return undefined;
260
};
261
262
const catchErrorCodes = (
263
options: ApiRequestOptions,
264
result: ApiResult,
265
): void => {
266
const errors: Record<number, string> = {
267
400: "Bad Request",
268
401: "Unauthorized",
269
403: "Forbidden",
270
404: "Not Found",
271
500: "Internal Server Error",
272
502: "Bad Gateway",
273
503: "Service Unavailable",
274
...options.errors,
275
};
276
277
const error = errors[result.status];
278
if (error) {
279
throw new ApiError(result, error);
280
}
281
282
if (!result.ok) {
283
throw new ApiError(result, "Generic Error");
284
}
285
};
286
287
/**
288
* Request method
289
* @param config The OpenAPI configuration object
290
* @param options The request options from the service
291
* @returns CancelablePromise<T>
292
* @throws ApiError
293
*/
294
export const request = <T>(
295
config: OpenAPIConfig,
296
options: ApiRequestOptions,
297
): CancelablePromise<T> => {
298
return new CancelablePromise(async (resolve, reject, onCancel) => {
299
try {
300
const url = getUrl(config, options);
301
const formData = getFormData(options);
302
const body = getRequestBody(options);
303
const headers = await getHeaders(config, options);
304
305
if (!onCancel.isCancelled) {
306
const response = await sendRequest(
307
config,
308
options,
309
url,
310
body,
311
formData,
312
headers,
313
onCancel,
314
);
315
const responseBody = await getResponseBody(response);
316
const responseHeader = getResponseHeader(
317
response,
318
options.responseHeader,
319
);
320
321
const result: ApiResult = {
322
url,
323
ok: response.ok,
324
status: response.status,
325
statusText: response.statusText,
326
body: responseHeader ?? responseBody,
327
};
328
329
catchErrorCodes(options, result);
330
331
resolve(result.body);
332
}
333
} catch (error) {
334
reject(error);
335
}
336
});
337
};
338
339