react-native-update-cli 2.29.5 → 2.30.0

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/lib/api.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Package, Session } from './types';
2
2
  import type { HermesBaseServerRecord } from './utils/hermes-base';
3
+ import { type AddressFamily } from './utils/runtime';
3
4
  export declare const getSession: () => Session | undefined;
4
5
  export declare const getApiToken: () => string | undefined;
5
6
  export declare const setApiToken: (token: string) => void;
@@ -29,6 +30,29 @@ export declare function uploadTimeoutMs(fileSize: number): number;
29
30
  * get here — they are surfaced as-is.
30
31
  */
31
32
  export declare function isTransientUploadError(error: unknown): boolean;
33
+ /** An address to post the upload form to, and the family that probed best. */
34
+ export interface UploadTarget {
35
+ url: string;
36
+ family?: AddressFamily;
37
+ }
38
+ /**
39
+ * The addresses to post the upload form to, best first; every one of them
40
+ * accepts the same form. `backupUrls` (newer servers) lists all alternatives
41
+ * to `url`, `backupUrl` (older ones) names a single one.
42
+ *
43
+ * The primary stays first while its TCP connect takes at most 150 ms, unprobed
44
+ * further. When it is far or unreachable, every address, the primary
45
+ * included, is timed by TLS handshake over IPv4 and IPv6 apart and tried
46
+ * fastest first with the family that won; ties keep the server's order. The
47
+ * family matters: an edge network may answer AAAA queries with an address on
48
+ * another continent while its A records are near, and the TCP probe above
49
+ * takes whichever family the system prefers.
50
+ */
51
+ export declare function chooseUploadUrls(instruction: {
52
+ url: string;
53
+ backupUrl?: string;
54
+ backupUrls?: string[];
55
+ }): Promise<UploadTarget[]>;
32
56
  export declare function uploadFile(fn: string, appId?: string | number): Promise<{
33
57
  hash: any;
34
58
  }>;
package/lib/api.js CHANGED
@@ -8,6 +8,7 @@ exports.redactRequestUrl = redactRequestUrl;
8
8
  exports.describeNetworkCause = describeNetworkCause;
9
9
  exports.uploadTimeoutMs = uploadTimeoutMs;
10
10
  exports.isTransientUploadError = isTransientUploadError;
11
+ exports.chooseUploadUrls = chooseUploadUrls;
11
12
  exports.uploadFile = uploadFile;
12
13
  exports.getHermesBase = getHermesBase;
13
14
  const filesize_parser_1 = __importDefault(require("filesize-parser"));
@@ -315,7 +316,7 @@ class UploadTimeoutError extends Error {
315
316
  * on a transient network error. `buildRequest` is invoked per attempt with a
316
317
  * fresh file stream (a consumed stream/form cannot be replayed).
317
318
  */
318
- async function sendUpload(fn, realUrl, fileSize, bar, buildRequest, slice = { start: 0, end: fileSize, retries: UPLOAD_MAX_RETRIES }) {
319
+ async function sendUpload(fn, realUrl, fileSize, bar, buildRequest, slice = { start: 0, end: fileSize, retries: UPLOAD_MAX_RETRIES }, family) {
319
320
  const timeoutMs = uploadTimeoutMs(slice.end - slice.start);
320
321
  // HTTP(S)_PROXY / NO_PROXY, like every other request of the CLI
321
322
  const agent = (0, runtime_1.proxyAgentFor)(realUrl);
@@ -341,6 +342,7 @@ async function sendUpload(fn, realUrl, fileSize, bar, buildRequest, slice = { st
341
342
  agent,
342
343
  signal: controller.signal,
343
344
  userAgent,
345
+ family,
344
346
  });
345
347
  }
346
348
  catch (rawError) {
@@ -396,6 +398,81 @@ async function sendChunks(fn, realUrl, fileSize, bar, chunked, postForm) {
396
398
  throw failure;
397
399
  }
398
400
  }
401
+ /** Above this TCP connect time the primary address counts as far away. */
402
+ const UPLOAD_PRIMARY_MAX_LATENCY_MS = 150;
403
+ /**
404
+ * The addresses to post the upload form to, best first; every one of them
405
+ * accepts the same form. `backupUrls` (newer servers) lists all alternatives
406
+ * to `url`, `backupUrl` (older ones) names a single one.
407
+ *
408
+ * The primary stays first while its TCP connect takes at most 150 ms, unprobed
409
+ * further. When it is far or unreachable, every address, the primary
410
+ * included, is timed by TLS handshake over IPv4 and IPv6 apart and tried
411
+ * fastest first with the family that won; ties keep the server's order. The
412
+ * family matters: an edge network may answer AAAA queries with an address on
413
+ * another continent while its A records are near, and the TCP probe above
414
+ * takes whichever family the system prefers.
415
+ */
416
+ async function chooseUploadUrls(instruction) {
417
+ const urls = (items) => items.map((item) => ({ url: item }));
418
+ const { url, backupUrl } = instruction;
419
+ const listed = Array.isArray(instruction.backupUrls)
420
+ ? instruction.backupUrls.filter((item) => typeof item === 'string' && item)
421
+ : [];
422
+ const backups = [
423
+ ...new Set([...(backupUrl ? [backupUrl] : []), ...listed]),
424
+ // GCS hands out the same url twice: nothing to switch to, no probe needed
425
+ ].filter((item) => item !== url);
426
+ if (backups.length === 0) {
427
+ return urls([url]);
428
+ }
429
+ if (global.USE_ACC_OSS) {
430
+ return urls([...backups, url]);
431
+ }
432
+ if ((0, runtime_1.resolveProxy)(url)) {
433
+ // a direct probe says nothing about the path through a proxy (and
434
+ // usually cannot connect at all): the primary url stays in that case
435
+ return urls([url, ...backups]);
436
+ }
437
+ const latency = await (0, runtime_1.measureTcpLatency)(url, {
438
+ attempts: 4,
439
+ timeout: 1000,
440
+ });
441
+ if (Number.isFinite(latency) && latency <= UPLOAD_PRIMARY_MAX_LATENCY_MS) {
442
+ return urls([url, ...backups]);
443
+ }
444
+ if (!Array.isArray(instruction.backupUrls)) {
445
+ // an older server: one backup, chosen on the primary's probe alone
446
+ return urls([...backups, url]);
447
+ }
448
+ const timed = await Promise.all([url, ...backups].map(async (item) => ({
449
+ url: item,
450
+ ...(await (0, runtime_1.measureTlsLatencyByFamily)(item)),
451
+ })));
452
+ // Array.prototype.sort is stable: ties keep the server's order
453
+ timed.sort((a, b) => a.latency === b.latency ? 0 : a.latency < b.latency ? -1 : 1);
454
+ return timed.map(({ url: item, family }) => ({
455
+ url: item,
456
+ ...(family ? { family } : {}),
457
+ }));
458
+ }
459
+ /**
460
+ * An answer worth trying the next address for: whatever fronts the store is
461
+ * failing (5xx), turned the request away (403/410) or caps uploads below the
462
+ * store's own limit (413). A store that refuses the form itself answers the
463
+ * same everywhere, which costs one more short request.
464
+ */
465
+ function uploadAnswerIsRetriableElsewhere(status) {
466
+ return status >= 500 || status === 403 || status === 410 || status === 413;
467
+ }
468
+ function uploadHost(url) {
469
+ try {
470
+ return new URL(url).host;
471
+ }
472
+ catch {
473
+ return url;
474
+ }
475
+ }
399
476
  async function uploadFile(fn, appId) {
400
477
  const fileSize = fs_1.default.statSync(fn).size;
401
478
  // appId 用于服务端路由:绑定了自托管节点(rnu-node)的应用,
@@ -407,25 +484,9 @@ async function uploadFile(fn, appId) {
407
484
  chunked: true,
408
485
  size: fileSize,
409
486
  });
410
- const { url, backupUrl, formData, maxSize } = resp;
411
- let realUrl = url;
412
- // GCS hands out the same url twice: nothing to switch to, no probe needed
413
- if (backupUrl && backupUrl !== url) {
414
- if (global.USE_ACC_OSS) {
415
- realUrl = backupUrl;
416
- }
417
- else if (!(0, runtime_1.resolveProxy)(url)) {
418
- // a direct TCP probe says nothing about the path through a proxy (and
419
- // usually cannot connect at all): the primary url stays in that case
420
- const latency = await (0, runtime_1.measureTcpLatency)(url, {
421
- attempts: 4,
422
- timeout: 1000,
423
- });
424
- if (!Number.isFinite(latency) || latency > 150) {
425
- realUrl = backupUrl;
426
- }
427
- }
428
- }
487
+ const { formData, maxSize } = resp;
488
+ const uploadTargets = await chooseUploadUrls(resp);
489
+ let realUrl = uploadTargets[0].url;
429
490
  if (maxSize && fileSize > (0, filesize_parser_1.default)(maxSize)) {
430
491
  const readableFileSize = `${(fileSize / 1048576).toFixed(1)}m`;
431
492
  throw new Error((0, i18n_1.t)('fileSizeExceeded', {
@@ -489,12 +550,32 @@ async function uploadFile(fn, appId) {
489
550
  });
490
551
  return { hash: resp.chunked.key };
491
552
  }
553
+ // Only the plain form upload has alternatives: a presigned PUT and the parts
554
+ // of a chunked upload are bound to the address they were issued for.
492
555
  let res;
493
- try {
494
- res = await sendUpload(fn, realUrl, fileSize, bar, postForm(formData, fileSize));
556
+ for (const [index, target] of uploadTargets.entries()) {
557
+ realUrl = target.url;
558
+ const next = uploadTargets[index + 1]?.url;
559
+ let reason;
560
+ try {
561
+ res = await sendUpload(fn, target.url, fileSize, bar, postForm(formData, fileSize), undefined, target.family);
562
+ if (!next || !uploadAnswerIsRetriableElsewhere(res.status)) {
563
+ break;
564
+ }
565
+ reason = `${res.status}`;
566
+ }
567
+ catch (error) {
568
+ if (!next) {
569
+ return rethrowUploadError(error);
570
+ }
571
+ reason = error instanceof Error ? error.message : String(error);
572
+ }
573
+ console.warn(`\nUpload via ${uploadHost(target.url)} failed (${reason}), trying ${uploadHost(next)}...`);
574
+ bar.curr = 0;
495
575
  }
496
- catch (error) {
497
- return rethrowUploadError(error);
576
+ if (!res) {
577
+ // unreachable: the last address either answers or throws above
578
+ throw createRequestError('Upload failed', realUrl);
498
579
  }
499
580
  if (res.status > 299) {
500
581
  throw createRequestError(`${res.status}: ${res.statusText || 'Upload failed'}`, realUrl);
@@ -39,6 +39,34 @@ export declare function measureTcpLatency(input: string, { attempts, timeout, }?
39
39
  attempts?: number;
40
40
  timeout?: number;
41
41
  }): Promise<number>;
42
+ export type AddressFamily = 4 | 6;
43
+ /**
44
+ * Time to a finished TLS handshake with the host of `input`, the best of
45
+ * `attempts`; Infinity when none completes (unreachable, or a certificate that
46
+ * does not verify). Unlike a TCP connect, the handshake is answered by whoever
47
+ * terminates TLS, so an address fronted by a forwarding entry is timed over
48
+ * its whole path and not just to the entry. Plain http falls back to the TCP
49
+ * connect time.
50
+ */
51
+ export declare function measureTlsLatency(input: string, { attempts, timeout, family, }?: {
52
+ attempts?: number;
53
+ timeout?: number;
54
+ family?: AddressFamily;
55
+ }): Promise<number>;
56
+ /**
57
+ * measureTlsLatency over IPv4 and over IPv6 at once, with the family that won.
58
+ * The two can lead to different places: an edge network may answer AAAA
59
+ * queries with an address on another continent while its A records are near,
60
+ * and a client that prefers IPv6 would then take the far path for the whole
61
+ * upload. A tie goes to IPv4. No family when neither completes.
62
+ */
63
+ export declare function measureTlsLatencyByFamily(input: string, options?: {
64
+ attempts?: number;
65
+ timeout?: number;
66
+ }): Promise<{
67
+ latency: number;
68
+ family?: AddressFamily;
69
+ }>;
42
70
  export declare function detectPackageManager(cwd?: string, env?: NodeJS.ProcessEnv): PackageManager;
43
71
  export declare function getInstallCommand(installArgs: string[], cwd?: string): {
44
72
  command: string;
@@ -9,6 +9,8 @@ exports.resolveProxy = resolveProxy;
9
9
  exports.webFetch = webFetch;
10
10
  exports.proxyAgentFor = proxyAgentFor;
11
11
  exports.measureTcpLatency = measureTcpLatency;
12
+ exports.measureTlsLatency = measureTlsLatency;
13
+ exports.measureTlsLatencyByFamily = measureTlsLatencyByFamily;
12
14
  exports.detectPackageManager = detectPackageManager;
13
15
  exports.getInstallCommand = getInstallCommand;
14
16
  exports.getJavaScriptRuntime = getJavaScriptRuntime;
@@ -18,6 +20,7 @@ const child_process_1 = require("child_process");
18
20
  const fs_1 = __importDefault(require("fs"));
19
21
  const net_1 = require("net");
20
22
  const path_1 = __importDefault(require("path"));
23
+ const tls_1 = require("tls");
21
24
  exports.isBunRuntime = typeof process.versions.bun ===
22
25
  'string';
23
26
  function runtimeFetch(url, options) {
@@ -166,10 +169,14 @@ function resolveTcpTarget(input) {
166
169
  };
167
170
  }
168
171
  }
169
- function measureTcpConnectOnce(host, port, timeout) {
172
+ function measureTcpConnectOnce(host, port, timeout, family) {
170
173
  return new Promise((resolve) => {
171
174
  const startedAt = Date.now();
172
- const socket = (0, net_1.createConnection)({ host, port });
175
+ const socket = (0, net_1.createConnection)({
176
+ host,
177
+ port,
178
+ ...(family ? { family } : {}),
179
+ });
173
180
  const finish = (latency) => {
174
181
  socket.removeAllListeners();
175
182
  socket.destroy();
@@ -197,6 +204,73 @@ async function measureTcpLatency(input, { attempts = 4, timeout = 1000, } = {})
197
204
  }
198
205
  return (latencies.reduce((sum, latency) => sum + latency, 0) / latencies.length);
199
206
  }
207
+ function measureTlsHandshakeOnce(host, port, timeout, family) {
208
+ return new Promise((resolve) => {
209
+ const startedAt = Date.now();
210
+ // SNI must be a name: Node refuses an IP literal as servername
211
+ const socket = (0, tls_1.connect)({
212
+ host,
213
+ port,
214
+ // a name without an address of this family fails the lookup at once
215
+ ...(family ? { family } : {}),
216
+ ...((0, net_1.isIP)(host) ? {} : { servername: host }),
217
+ });
218
+ const finish = (latency) => {
219
+ socket.removeAllListeners();
220
+ // a late error after destroy must not surface as an unhandled event
221
+ socket.on('error', () => { });
222
+ socket.destroy();
223
+ resolve(latency);
224
+ };
225
+ socket.setTimeout(timeout);
226
+ socket.once('secureConnect', () => {
227
+ finish(Date.now() - startedAt);
228
+ });
229
+ socket.once('timeout', () => {
230
+ finish(Number.POSITIVE_INFINITY);
231
+ });
232
+ socket.once('error', () => {
233
+ finish(Number.POSITIVE_INFINITY);
234
+ });
235
+ });
236
+ }
237
+ /**
238
+ * Time to a finished TLS handshake with the host of `input`, the best of
239
+ * `attempts`; Infinity when none completes (unreachable, or a certificate that
240
+ * does not verify). Unlike a TCP connect, the handshake is answered by whoever
241
+ * terminates TLS, so an address fronted by a forwarding entry is timed over
242
+ * its whole path and not just to the entry. Plain http falls back to the TCP
243
+ * connect time.
244
+ */
245
+ async function measureTlsLatency(input, { attempts = 2, timeout = 3000, family, } = {}) {
246
+ let secure = true;
247
+ try {
248
+ secure = new URL(input).protocol !== 'http:';
249
+ }
250
+ catch { }
251
+ const { host, port } = resolveTcpTarget(input);
252
+ const results = await Promise.all(Array.from({ length: attempts }, () => secure
253
+ ? measureTlsHandshakeOnce(host, port, timeout, family)
254
+ : measureTcpConnectOnce(host, port, timeout, family)));
255
+ return Math.min(...results, Number.POSITIVE_INFINITY);
256
+ }
257
+ /**
258
+ * measureTlsLatency over IPv4 and over IPv6 at once, with the family that won.
259
+ * The two can lead to different places: an edge network may answer AAAA
260
+ * queries with an address on another continent while its A records are near,
261
+ * and a client that prefers IPv6 would then take the far path for the whole
262
+ * upload. A tie goes to IPv4. No family when neither completes.
263
+ */
264
+ async function measureTlsLatencyByFamily(input, options = {}) {
265
+ const [v4, v6] = await Promise.all([
266
+ measureTlsLatency(input, { ...options, family: 4 }),
267
+ measureTlsLatency(input, { ...options, family: 6 }),
268
+ ]);
269
+ if (!Number.isFinite(v4) && !Number.isFinite(v6)) {
270
+ return { latency: Number.POSITIVE_INFINITY };
271
+ }
272
+ return v6 < v4 ? { latency: v6, family: 6 } : { latency: v4, family: 4 };
273
+ }
200
274
  function detectPackageManager(cwd = process.cwd(), env = process.env) {
201
275
  const lockFiles = [
202
276
  ['bun.lock', 'bun'],
@@ -30,4 +30,6 @@ export declare function sendUploadRequest(url: string, request: UploadRequest, o
30
30
  agent?: HttpAgent;
31
31
  signal?: AbortSignal;
32
32
  userAgent?: string;
33
+ /** Connect over this address family only (no effect through a proxy). */
34
+ family?: 4 | 6;
33
35
  }): Promise<UploadResponse>;
@@ -89,6 +89,7 @@ function sendUploadRequest(url, request, options) {
89
89
  ...request.headers,
90
90
  },
91
91
  agent: options.agent,
92
+ ...(options.family && !options.agent ? { family: options.family } : {}),
92
93
  });
93
94
  const fail = (error) => {
94
95
  request.body.destroy();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-update-cli",
3
- "version": "2.29.5",
3
+ "version": "2.30.0",
4
4
  "description": "command line tool for react-native-update (remote updates for react native)",
5
5
  "main": "lib/exports.js",
6
6
  "types": "lib/exports.d.ts",