-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi.ts
More file actions
288 lines (260 loc) · 7.18 KB
/
Copy pathapi.ts
File metadata and controls
288 lines (260 loc) · 7.18 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
import filesizeParser from 'filesize-parser';
import FormData from 'form-data';
import fs from 'fs';
import fetch from 'node-fetch';
import path from 'path';
import ProgressBar from 'progress';
import { getBaseUrl } from 'utils/http-helper';
import packageJson from '../package.json';
import type { Package, Session } from './types';
import { credentialFile, IS_CRESC, pricingPageUrl } from './utils/constants';
import { t } from './utils/i18n';
import {
measureTcpLatency,
type RuntimeRequestInit,
type RuntimeResponse,
runtimeFetch,
} from './utils/runtime';
let session: Session | undefined;
let savedSession: Session | undefined;
let apiToken: string | undefined;
const userAgent = `react-native-update-cli/${packageJson.version}`;
export const getSession = () => session;
export const getApiToken = () => apiToken;
export const setApiToken = (token: string) => {
apiToken = token;
};
const loadApiTokenFromEnv = () => {
// Use CRESC_API_TOKEN for cresc, PUSHY_API_TOKEN for pushy
const envToken = IS_CRESC
? process.env.CRESC_API_TOKEN
: process.env.PUSHY_API_TOKEN;
if (envToken) {
apiToken = envToken;
}
};
export const replaceSession = (newSession: { token: string }) => {
session = newSession;
};
export const loadSession = async () => {
loadApiTokenFromEnv();
if (fs.existsSync(credentialFile)) {
try {
replaceSession(JSON.parse(fs.readFileSync(credentialFile, 'utf8')));
savedSession = session;
} catch (e) {
console.error(
`Failed to parse file ${credentialFile}. Try to remove it manually.`,
);
throw e;
}
}
};
export const saveSession = () => {
// Only save on change.
if (session !== savedSession) {
const current = session;
const data = JSON.stringify(current, null, 4);
fs.writeFileSync(credentialFile, data, 'utf8');
savedSession = current;
}
};
export const closeSession = () => {
if (fs.existsSync(credentialFile)) {
fs.unlinkSync(credentialFile);
savedSession = undefined;
}
session = undefined;
};
function createRequestError(
error: unknown,
requestUrl: string,
status?: number,
) {
const message =
typeof error === 'string'
? error
: error instanceof Error
? error.message
: String(error);
const requestError = new Error(`${message}\nURL: ${requestUrl}`) as Error & {
status?: number;
};
requestError.status = status;
return requestError;
}
const PROXY_ERROR_PATTERNS = [
'socket disconnected before secure TLS connection',
'ECONNRESET',
'ECONNREFUSED',
'DEPTH_ZERO_SELF_SIGNED_CERT',
'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
'CERT_HAS_EXPIRED',
'self signed certificate',
'proxy',
'ETIMEDOUT',
'EHOSTUNREACH',
'ENETUNREACH',
];
function isProxyRelatedError(error: unknown): boolean {
const msg =
error instanceof Error
? error.message
: typeof error === 'string'
? error
: '';
const lower = msg.toLowerCase();
return PROXY_ERROR_PATTERNS.some((p) => lower.includes(p.toLowerCase()));
}
async function query(url: string, options: RuntimeRequestInit) {
const baseUrl = await getBaseUrl;
const fullUrl = `${baseUrl}${url}`;
let resp: RuntimeResponse;
try {
resp = await runtimeFetch(fullUrl, options);
} catch (error) {
const baseError = createRequestError(error, fullUrl);
if (isProxyRelatedError(error)) {
throw new Error(
`${baseError.message}\n\n${t('proxyNetworkError')}\n${t('proxyNetworkErrorTips')}`,
);
}
throw baseError;
}
const text = await resp.text();
let json: any;
try {
json = JSON.parse(text);
} catch (_e) {
if (resp.status === 200 && text) {
console.warn(
`Warning: API returned 200 with non-JSON body (${text.length} bytes)`,
);
}
}
if (resp.status !== 200) {
const message = json?.message || resp.statusText || `HTTP ${resp.status}`;
if (resp.status === 401) {
throw createRequestError(t('loginExpired'), fullUrl, resp.status);
}
throw createRequestError(message, fullUrl, resp.status);
}
return json;
}
function queryWithoutBody(method: string) {
return (api: string) => {
const headers: Record<string, string> = {
'User-Agent': userAgent,
};
if (apiToken) {
headers['x-api-token'] = apiToken;
} else if (session?.token) {
headers['X-AccessToken'] = session.token;
}
return query(api, {
method,
headers,
});
};
}
function queryWithBody(method: string) {
return (api: string, body?: Record<string, any>) => {
const headers: Record<string, string> = {
'User-Agent': userAgent,
'Content-Type': 'application/json',
};
if (apiToken) {
headers['x-api-token'] = apiToken;
} else if (session?.token) {
headers['X-AccessToken'] = session.token;
}
return query(api, {
method,
headers,
body: JSON.stringify(body),
});
};
}
export const get = queryWithoutBody('GET');
export const post = queryWithBody('POST');
export const put = queryWithBody('PUT');
export const doDelete = queryWithBody('DELETE');
export async function uploadFile(fn: string, key?: string) {
const { url, backupUrl, formData, maxSize } = await post('/upload', {
ext: path.extname(fn),
});
let realUrl = url;
if (backupUrl) {
if (global.USE_ACC_OSS) {
realUrl = backupUrl;
} else {
const latency = await measureTcpLatency(url, {
attempts: 4,
timeout: 1000,
});
if (!Number.isFinite(latency) || latency > 150) {
realUrl = backupUrl;
}
}
// console.log({realUrl});
}
const fileSize = fs.statSync(fn).size;
if (maxSize && fileSize > filesizeParser(maxSize)) {
const readableFileSize = `${(fileSize / 1048576).toFixed(1)}m`;
throw new Error(
t('fileSizeExceeded', {
fileSize: readableFileSize,
maxSize,
pricingPageUrl,
}),
);
}
const bar = new ProgressBar(' Uploading [:bar] :percent :etas', {
complete: '=',
incomplete: ' ',
total: fileSize,
});
const form = new FormData();
for (const [k, v] of Object.entries(formData)) {
form.append(k, v);
}
const fileStream = fs.createReadStream(fn);
fileStream.on('data', (data) => {
bar.tick(data.length);
});
if (key) {
form.append('key', key);
}
form.append('file', fileStream);
// form.append('file', fileStream, {
// contentType: 'application/octet-stream',
// });
let res: fetch.Response;
try {
res = await fetch(realUrl, {
method: 'POST',
body: form,
});
} catch (error) {
if (isProxyRelatedError(error)) {
const rawMessage =
error instanceof Error ? error.message : String(error);
throw new Error(
`${rawMessage}\n\n${t('proxyNetworkError')}\n${t('proxyNetworkErrorTips')}`,
);
}
throw createRequestError(error, realUrl);
}
if (res.status > 299) {
throw createRequestError(
`${res.status}: ${res.statusText || 'Upload failed'}`,
realUrl,
);
}
// const body = await response.json();
return { hash: key || formData.key };
}
export const getAllPackages = async (appId: string) => {
const { data } = await get(`/app/${appId}/package/list?limit=1000`);
return data as Package[] | undefined | null;
};