-
Notifications
You must be signed in to change notification settings - Fork 213
Expand file tree
/
Copy pathapi-client.ts
More file actions
386 lines (326 loc) · 10.3 KB
/
api-client.ts
File metadata and controls
386 lines (326 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
import { logger } from '@redocly/openapi-core';
import fetchWithTimeout, { type FetchWithTimeoutOptions } from '../../utils/fetch-with-timeout.js';
import { DEFAULT_FETCH_TIMEOUT } from '../../utils/constants.js';
import { version } from '../../utils/package.js';
import type { ReadStream } from 'node:fs';
import type { Readable } from 'node:stream';
import type {
ListRemotesResponse,
ProjectSourceResponse,
PushResponse,
UpsertRemoteResponse,
} from './types.js';
interface BaseApiClient {
request(url: string, options: FetchWithTimeoutOptions): Promise<Response>;
}
type CommandOption = 'push' | 'push-status';
export type SunsetWarning = { sunsetDate: Date; isSunsetExpired: boolean };
export type SunsetWarningsBuffer = SunsetWarning[];
export class ReuniteApiError extends Error {
constructor(message: string, public status: number) {
super(message);
}
}
export class ReuniteApiClient implements BaseApiClient {
public sunsetWarnings: SunsetWarningsBuffer = [];
constructor(protected command: string) {}
public async request(url: string, options: FetchWithTimeoutOptions) {
const headers = {
...options.headers,
'user-agent': `redocly-cli/${version} ${this.command}`,
};
try {
const response = await fetchWithTimeout(url, {
...options,
headers,
});
this.collectSunsetWarning(response);
return response;
} catch (err) {
let errorMessage = 'Failed to fetch.';
if (err.cause) {
errorMessage += ` Caused by ${err.cause.message || err.cause.name}.`;
}
if (err.code || err.cause?.code) {
errorMessage += ` Code: ${err.code || err.cause?.code}`;
}
throw new Error(errorMessage);
}
}
private collectSunsetWarning(response: Response) {
const sunsetTime = this.getSunsetDate(response);
if (!sunsetTime) return;
const sunsetDate = new Date(sunsetTime);
if (sunsetTime > Date.now()) {
this.sunsetWarnings.push({
sunsetDate,
isSunsetExpired: false,
});
} else {
this.sunsetWarnings.push({
sunsetDate,
isSunsetExpired: true,
});
}
}
private getSunsetDate(response: Response): number | undefined {
const { headers } = response;
if (!headers) {
return;
}
const sunsetDate = headers.get('sunset') || headers.get('Sunset');
if (!sunsetDate) {
return;
}
return Date.parse(sunsetDate);
}
}
class RemotesApi {
constructor(
private client: BaseApiClient,
private readonly domain: string,
private readonly apiKey: string
) {}
protected async getParsedResponse<T>(response: Response): Promise<T> {
const responseBody = await response.json();
if (response.ok) {
return responseBody as T;
}
throw new ReuniteApiError(
`${responseBody.title || response.statusText || 'Unknown error'}.`,
response.status
);
}
async getDefaultBranch(organizationId: string, projectId: string) {
try {
const response = await this.client.request(
`${this.domain}/api/orgs/${organizationId}/projects/${projectId}/source`,
{
timeout: DEFAULT_FETCH_TIMEOUT,
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
}
);
const source = await this.getParsedResponse<ProjectSourceResponse>(response);
return source.branchName;
} catch (err) {
const message = `Failed to fetch default branch. ${err.message}`;
if (err instanceof ReuniteApiError) {
throw new ReuniteApiError(message, err.status);
}
throw new Error(message);
}
}
async upsert(
organizationId: string,
projectId: string,
remote: {
mountPath: string;
mountBranchName: string;
}
): Promise<UpsertRemoteResponse> {
try {
const response = await this.client.request(
`${this.domain}/api/orgs/${organizationId}/projects/${projectId}/remotes`,
{
timeout: DEFAULT_FETCH_TIMEOUT,
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify({
mountPath: remote.mountPath,
mountBranchName: remote.mountBranchName,
type: 'CICD',
autoMerge: true,
}),
}
);
return await this.getParsedResponse<UpsertRemoteResponse>(response);
} catch (err) {
const message = `Failed to upsert remote. ${err.message}`;
if (err instanceof ReuniteApiError) {
throw new ReuniteApiError(message, err.status);
}
throw new Error(message);
}
}
async push(
organizationId: string,
projectId: string,
payload: PushPayload,
files: { path: string; stream: ReadStream | Buffer }[]
): Promise<PushResponse> {
const formData = new globalThis.FormData();
formData.append('remoteId', payload.remoteId);
formData.append('commit[message]', payload.commit.message);
formData.append('commit[author][name]', payload.commit.author.name);
formData.append('commit[author][email]', payload.commit.author.email);
formData.append('commit[branchName]', payload.commit.branchName);
payload.commit.url && formData.append('commit[url]', payload.commit.url);
payload.commit.namespace && formData.append('commit[namespaceId]', payload.commit.namespace);
payload.commit.sha && formData.append('commit[sha]', payload.commit.sha);
payload.commit.repository && formData.append('commit[repositoryId]', payload.commit.repository);
payload.commit.createdAt && formData.append('commit[createdAt]', payload.commit.createdAt);
for (const file of files) {
const blob = Buffer.isBuffer(file.stream)
? new Blob([file.stream as BlobPart])
: new Blob([(await streamToBuffer(file.stream)) as BlobPart]);
formData.append(`files[${file.path}]`, blob, file.path);
}
payload.isMainBranch && formData.append('isMainBranch', 'true');
try {
const response = await this.client.request(
`${this.domain}/api/orgs/${organizationId}/projects/${projectId}/pushes`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${this.apiKey}`,
},
body: formData,
}
);
return await this.getParsedResponse<PushResponse>(response);
} catch (err) {
const message = `Failed to push. ${err.message}`;
if (err instanceof ReuniteApiError) {
throw new ReuniteApiError(message, err.status);
}
throw new Error(message);
}
}
async getRemotesList({
organizationId,
projectId,
mountPath,
}: {
organizationId: string;
projectId: string;
mountPath: string;
}) {
try {
const response = await this.client.request(
`${this.domain}/api/orgs/${organizationId}/projects/${projectId}/remotes?filter=mountPath:/${mountPath}/`,
{
timeout: DEFAULT_FETCH_TIMEOUT,
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
}
);
return await this.getParsedResponse<ListRemotesResponse>(response);
} catch (err) {
const message = `Failed to get remote list. ${err.message}`;
if (err instanceof ReuniteApiError) {
throw new ReuniteApiError(message, err.status);
}
throw new Error(message);
}
}
async getPush({
organizationId,
projectId,
pushId,
}: {
organizationId: string;
projectId: string;
pushId: string;
}) {
try {
const response = await this.client.request(
`${this.domain}/api/orgs/${organizationId}/projects/${projectId}/pushes/${pushId}`,
{
timeout: DEFAULT_FETCH_TIMEOUT,
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${this.apiKey}`,
},
}
);
return await this.getParsedResponse<PushResponse>(response);
} catch (err) {
const message = `Failed to get push status. ${err.message}`;
if (err instanceof ReuniteApiError) {
throw new ReuniteApiError(message, err.status);
}
throw new Error(message);
}
}
}
export class ReuniteApi {
private apiClient: ReuniteApiClient;
private command: CommandOption;
public remotes: RemotesApi;
constructor({
domain,
apiKey,
command,
}: {
domain: string;
apiKey: string;
command: CommandOption;
}) {
this.command = command;
this.apiClient = new ReuniteApiClient(this.command);
this.remotes = new RemotesApi(this.apiClient, domain, apiKey);
}
public reportSunsetWarnings(): void {
const sunsetWarnings = this.apiClient.sunsetWarnings;
if (sunsetWarnings.length) {
const [{ isSunsetExpired, sunsetDate }] = sunsetWarnings.sort(
(a: SunsetWarning, b: SunsetWarning) => {
// First, prioritize by expiration status
if (a.isSunsetExpired !== b.isSunsetExpired) {
return a.isSunsetExpired ? -1 : 1;
}
// If both are either expired or not, sort by sunset date
return a.sunsetDate > b.sunsetDate ? 1 : -1;
}
);
const updateVersionMessage = `Update to the latest version by running "npm install @redocly/cli@latest".`;
if (isSunsetExpired) {
logger.error(
`The "${this.command}" command is not compatible with your version of Redocly CLI. ${updateVersionMessage}\n\n`
);
} else {
logger.warn(
`The "${
this.command
}" command will be incompatible with your version of Redocly CLI after ${sunsetDate.toLocaleString()}. ${updateVersionMessage}\n\n`
);
}
}
}
}
export type PushPayload = {
remoteId: string;
commit: {
message: string;
branchName: string;
sha?: string;
url?: string;
createdAt?: string;
namespace?: string;
repository?: string;
author: {
name: string;
email: string;
image?: string;
};
};
isMainBranch?: boolean;
};
export async function streamToBuffer(stream: ReadStream | Readable): Promise<Buffer> {
const chunks: Buffer[] = [];
for await (const chunk of stream) {
chunks.push(chunk);
}
return Buffer.concat(chunks);
}