react-native-update-cli 2.29.4 → 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;
@@ -11,6 +12,13 @@ export declare const saveSession: () => void;
11
12
  export declare const closeSession: () => void;
12
13
  /** Remove credentials, query signatures and fragments before logging a URL. */
13
14
  export declare function redactRequestUrl(requestUrl: string): string;
15
+ /**
16
+ * The underlying reason of a network failure, e.g.
17
+ * `ENOTFOUND: getaddrinfo ENOTFOUND 1.rnupdate.online`. Node's fetch only says
18
+ * "fetch failed" and keeps the reason in `cause`, which is otherwise printed
19
+ * only under RNU_DEBUG=1.
20
+ */
21
+ export declare function describeNetworkCause(error: unknown): string | undefined;
14
22
  export declare const get: (api: string) => Promise<any>;
15
23
  export declare const post: (api: string, body?: Record<string, any>) => Promise<any>;
16
24
  export declare const put: (api: string, body?: Record<string, any>) => Promise<any>;
@@ -22,6 +30,29 @@ export declare function uploadTimeoutMs(fileSize: number): number;
22
30
  * get here — they are surfaced as-is.
23
31
  */
24
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[]>;
25
56
  export declare function uploadFile(fn: string, appId?: string | number): Promise<{
26
57
  hash: any;
27
58
  }>;
package/lib/api.js CHANGED
@@ -5,8 +5,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.getAllPackages = exports.doDelete = exports.put = exports.post = exports.get = exports.closeSession = exports.saveSession = exports.loadSession = exports.replaceSession = exports.setApiToken = exports.getApiToken = exports.getSession = void 0;
7
7
  exports.redactRequestUrl = redactRequestUrl;
8
+ exports.describeNetworkCause = describeNetworkCause;
8
9
  exports.uploadTimeoutMs = uploadTimeoutMs;
9
10
  exports.isTransientUploadError = isTransientUploadError;
11
+ exports.chooseUploadUrls = chooseUploadUrls;
10
12
  exports.uploadFile = uploadFile;
11
13
  exports.getHermesBase = getHermesBase;
12
14
  const filesize_parser_1 = __importDefault(require("filesize-parser"));
@@ -95,12 +97,13 @@ function redactRequestUrl(requestUrl) {
95
97
  : `${requestUrl.slice(0, secretStart)}?<redacted>`;
96
98
  }
97
99
  }
98
- function createRequestError(error, requestUrl, status) {
99
- const message = typeof error === 'string'
100
+ function createRequestError(error, requestUrl, status, detail) {
101
+ const baseMessage = typeof error === 'string'
100
102
  ? error
101
103
  : error instanceof Error
102
104
  ? error.message
103
105
  : String(error);
106
+ const message = detail ? `${baseMessage} (${detail})` : baseMessage;
104
107
  const cause = error instanceof Error || (typeof error === 'object' && error !== null)
105
108
  ? error
106
109
  : undefined;
@@ -120,35 +123,103 @@ const PROXY_ERROR_PATTERNS = [
120
123
  'ETIMEDOUT',
121
124
  'EHOSTUNREACH',
122
125
  'ENETUNREACH',
126
+ // DNS: offline, or a proxy/VPN that hijacks name resolution
127
+ 'ENOTFOUND',
128
+ 'EAI_AGAIN',
129
+ // undici's own connect/socket failures (Node's fetch)
130
+ 'UND_ERR_CONNECT_TIMEOUT',
131
+ 'UND_ERR_SOCKET',
132
+ // a TLS-inspecting corporate proxy re-signing with an untrusted root
133
+ 'UNABLE_TO_GET_ISSUER_CERT',
134
+ 'SELF_SIGNED_CERT_IN_CHAIN',
123
135
  ];
136
+ /** The error chain from `error` down through its causes, without cycles. */
137
+ function errorChain(error) {
138
+ const chain = [];
139
+ let current = error;
140
+ while (current !== undefined &&
141
+ current !== null &&
142
+ !chain.includes(current)) {
143
+ chain.push(current);
144
+ current =
145
+ typeof current === 'object'
146
+ ? current.cause
147
+ : undefined;
148
+ }
149
+ return chain;
150
+ }
151
+ /**
152
+ * The underlying reason of a network failure, e.g.
153
+ * `ENOTFOUND: getaddrinfo ENOTFOUND 1.rnupdate.online`. Node's fetch only says
154
+ * "fetch failed" and keeps the reason in `cause`, which is otherwise printed
155
+ * only under RNU_DEBUG=1.
156
+ */
157
+ function describeNetworkCause(error) {
158
+ const top = error instanceof Error ? error.message : String(error);
159
+ for (const item of errorChain(error).slice(1).reverse()) {
160
+ if (!(item instanceof Error)) {
161
+ continue;
162
+ }
163
+ // happy-eyeballs connects fail with an AggregateError of per-address errors
164
+ const inner = !item.code &&
165
+ item instanceof AggregateError &&
166
+ item.errors[0] instanceof Error
167
+ ? item.errors[0]
168
+ : item;
169
+ const code = inner.code;
170
+ const message = inner.message || item.message;
171
+ if (!code && (!message || message === top)) {
172
+ continue;
173
+ }
174
+ if (!code) {
175
+ return message;
176
+ }
177
+ return message && !message.includes(code)
178
+ ? `${code}: ${message}`
179
+ : message || code;
180
+ }
181
+ return undefined;
182
+ }
124
183
  function isProxyRelatedError(error) {
125
- const seen = new Set();
126
184
  const parts = [];
127
- let current = error;
128
- while (current !== undefined && current !== null && !seen.has(current)) {
129
- seen.add(current);
185
+ for (const current of errorChain(error)) {
130
186
  if (current instanceof Error) {
131
187
  const code = current.code;
132
188
  parts.push(`${current.name} ${code ?? ''} ${current.message}`);
189
+ if (current instanceof AggregateError) {
190
+ for (const inner of current.errors) {
191
+ if (inner instanceof Error) {
192
+ const innerCode = inner.code;
193
+ parts.push(`${inner.name} ${innerCode ?? ''} ${inner.message}`);
194
+ }
195
+ }
196
+ }
133
197
  }
134
198
  else {
135
199
  parts.push(String(current));
136
200
  }
137
- current =
138
- typeof current === 'object'
139
- ? current.cause
140
- : undefined;
141
201
  }
142
202
  const lower = parts.join('\n').toLowerCase();
143
203
  return PROXY_ERROR_PATTERNS.some((p) => lower.includes(p.toLowerCase()));
144
204
  }
145
205
  /** A request error for `url`, with the proxy hints when a proxy is the likely cause. */
146
- function networkError(error, url) {
147
- const baseError = createRequestError(error, url);
206
+ function networkError(error, url, { apiRequest = false } = {}) {
207
+ const baseError = createRequestError(error, url, undefined, describeNetworkCause(error));
208
+ const hints = [];
209
+ if (apiRequest && (0, http_helper_1.isBaseUrlUnreachableFallback)()) {
210
+ hints.push((0, i18n_1.t)('allEndpointsUnreachable', {
211
+ example: constants_1.defaultEndpoints[constants_1.defaultEndpoints.length - 1],
212
+ }));
213
+ }
148
214
  if (isProxyRelatedError(error)) {
149
- return new Error(`${baseError.message}\n\n${(0, i18n_1.t)('proxyNetworkError')}\n${(0, i18n_1.t)('proxyNetworkErrorTips')}`, { cause: baseError });
215
+ hints.push(`${(0, i18n_1.t)('proxyNetworkError')}\n${(0, i18n_1.t)('proxyNetworkErrorTips')}`);
150
216
  }
151
- return baseError;
217
+ if (!hints.length) {
218
+ return baseError;
219
+ }
220
+ return new Error(`${baseError.message}\n\n${hints.join('\n\n')}`, {
221
+ cause: baseError,
222
+ });
152
223
  }
153
224
  async function query(url, options) {
154
225
  const baseUrl = await (0, http_helper_1.getBaseUrl)();
@@ -158,7 +229,7 @@ async function query(url, options) {
158
229
  resp = await (0, runtime_1.runtimeFetch)(fullUrl, options);
159
230
  }
160
231
  catch (error) {
161
- throw networkError(error, fullUrl);
232
+ throw networkError(error, fullUrl, { apiRequest: true });
162
233
  }
163
234
  const text = await resp.text();
164
235
  let json;
@@ -245,7 +316,7 @@ class UploadTimeoutError extends Error {
245
316
  * on a transient network error. `buildRequest` is invoked per attempt with a
246
317
  * fresh file stream (a consumed stream/form cannot be replayed).
247
318
  */
248
- 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) {
249
320
  const timeoutMs = uploadTimeoutMs(slice.end - slice.start);
250
321
  // HTTP(S)_PROXY / NO_PROXY, like every other request of the CLI
251
322
  const agent = (0, runtime_1.proxyAgentFor)(realUrl);
@@ -271,6 +342,7 @@ async function sendUpload(fn, realUrl, fileSize, bar, buildRequest, slice = { st
271
342
  agent,
272
343
  signal: controller.signal,
273
344
  userAgent,
345
+ family,
274
346
  });
275
347
  }
276
348
  catch (rawError) {
@@ -326,6 +398,81 @@ async function sendChunks(fn, realUrl, fileSize, bar, chunked, postForm) {
326
398
  throw failure;
327
399
  }
328
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
+ }
329
476
  async function uploadFile(fn, appId) {
330
477
  const fileSize = fs_1.default.statSync(fn).size;
331
478
  // appId 用于服务端路由:绑定了自托管节点(rnu-node)的应用,
@@ -337,25 +484,9 @@ async function uploadFile(fn, appId) {
337
484
  chunked: true,
338
485
  size: fileSize,
339
486
  });
340
- const { url, backupUrl, formData, maxSize } = resp;
341
- let realUrl = url;
342
- // GCS hands out the same url twice: nothing to switch to, no probe needed
343
- if (backupUrl && backupUrl !== url) {
344
- if (global.USE_ACC_OSS) {
345
- realUrl = backupUrl;
346
- }
347
- else if (!(0, runtime_1.resolveProxy)(url)) {
348
- // a direct TCP probe says nothing about the path through a proxy (and
349
- // usually cannot connect at all): the primary url stays in that case
350
- const latency = await (0, runtime_1.measureTcpLatency)(url, {
351
- attempts: 4,
352
- timeout: 1000,
353
- });
354
- if (!Number.isFinite(latency) || latency > 150) {
355
- realUrl = backupUrl;
356
- }
357
- }
358
- }
487
+ const { formData, maxSize } = resp;
488
+ const uploadTargets = await chooseUploadUrls(resp);
489
+ let realUrl = uploadTargets[0].url;
359
490
  if (maxSize && fileSize > (0, filesize_parser_1.default)(maxSize)) {
360
491
  const readableFileSize = `${(fileSize / 1048576).toFixed(1)}m`;
361
492
  throw new Error((0, i18n_1.t)('fileSizeExceeded', {
@@ -419,12 +550,32 @@ async function uploadFile(fn, appId) {
419
550
  });
420
551
  return { hash: resp.chunked.key };
421
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.
422
555
  let res;
423
- try {
424
- 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;
425
575
  }
426
- catch (error) {
427
- return rethrowUploadError(error);
576
+ if (!res) {
577
+ // unreachable: the last address either answers or throws above
578
+ throw createRequestError('Upload failed', realUrl);
428
579
  }
429
580
  if (res.status > 299) {
430
581
  throw createRequestError(`${res.status}: ${res.statusText || 'Upload failed'}`, realUrl);
@@ -138,6 +138,7 @@ declare const _default: {
138
138
  composeSourceMapsNotFound: string;
139
139
  installPackageRequired: string;
140
140
  installFailed: string;
141
+ allEndpointsUnreachable: string;
141
142
  proxyNetworkError: string;
142
143
  proxyNetworkErrorTips: string;
143
144
  invalidId: string;
package/lib/locales/en.js CHANGED
@@ -146,8 +146,9 @@ This can reduce the risk of inconsistent dependencies and supply chain attacks.
146
146
  composeSourceMapsNotFound: 'Cannot find react-native/scripts/compose-source-maps.js, skipping hermes sourcemap composing. The uploaded sourcemap may not match the compiled bundle.',
147
147
  installPackageRequired: 'Please specify the package to install, e.g. "{{scriptName}} install node-hdiffpatch"',
148
148
  installFailed: 'Failed to install {{packages}}: {{error}}',
149
- proxyNetworkError: 'Network error — likely caused by a proxy/VPN. Please try disabling your proxy and retry.',
150
- proxyNetworkErrorTips: 'Common fixes:\n1. Disable system proxy or VPN\n2. Check HTTP_PROXY / HTTPS_PROXY environment variables\n3. Check proxy settings in .npmrc',
149
+ allEndpointsUnreachable: 'None of the API endpoints is reachable from this machine (each was probed), so the problem is in the local network rather than the server. If only one endpoint works for you, pin it with the RNU_API environment variable, e.g. RNU_API={{example}}',
150
+ proxyNetworkError: 'Network error — likely caused by DNS, a proxy/VPN or a certificate problem. Please try disabling your proxy and retry.',
151
+ proxyNetworkErrorTips: "Common fixes:\n1. Disable system proxy or VPN (or let this service's domains bypass it)\n2. Check HTTP_PROXY / HTTPS_PROXY environment variables\n3. Check proxy settings in .npmrc\n4. If your network re-signs HTTPS certificates, point NODE_EXTRA_CA_CERTS at its root certificate",
151
152
  invalidId: 'Invalid id: {{id}}',
152
153
  outputPathRequired: 'Output path is required.',
153
154
  unsupportedFileType: 'Unsupported file type: {{fileType}}',
@@ -138,6 +138,7 @@ declare const _default: {
138
138
  composeSourceMapsNotFound: string;
139
139
  installPackageRequired: string;
140
140
  installFailed: string;
141
+ allEndpointsUnreachable: string;
141
142
  proxyNetworkError: string;
142
143
  proxyNetworkErrorTips: string;
143
144
  invalidId: string;
package/lib/locales/zh.js CHANGED
@@ -146,8 +146,9 @@ exports.default = {
146
146
  composeSourceMapsNotFound: '找不到 react-native/scripts/compose-source-maps.js,跳过 hermes sourcemap 合成。上传的 sourcemap 可能与编译后的 bundle 不匹配。',
147
147
  installPackageRequired: '请指定要安装的包,例如 "{{scriptName}} install node-hdiffpatch"',
148
148
  installFailed: '安装 {{packages}} 失败: {{error}}',
149
- proxyNetworkError: '网络连接异常,可能是代理/VPN 导致。请尝试关闭代理后重试。',
150
- proxyNetworkErrorTips: '常见解决方法:\n1. 关闭系统代理或 VPN\n2. 检查 HTTP_PROXY / HTTPS_PROXY 环境变量\n3. 检查 .npmrc 中的 proxy 配置',
149
+ allEndpointsUnreachable: '本机无法连接任何一条 API 线路(已逐一探测),问题出在本机网络而非服务端。如果只有某条线路可用,可以用 RNU_API 环境变量指定,例如 RNU_API={{example}}',
150
+ proxyNetworkError: '网络连接异常,可能是 DNS、代理/VPN 或证书问题导致。请尝试关闭代理后重试。',
151
+ proxyNetworkErrorTips: '常见解决方法:\n1. 关闭系统代理或 VPN(或将本服务的域名设为直连)\n2. 检查 HTTP_PROXY / HTTPS_PROXY 环境变量\n3. 检查 .npmrc 中的 proxy 配置\n4. 公司网络会替换 HTTPS 证书时,用 NODE_EXTRA_CA_CERTS 指定公司根证书',
151
152
  invalidId: '无效的 id:{{id}}',
152
153
  outputPathRequired: '必须指定输出路径。',
153
154
  unsupportedFileType: '不支持的文件类型:{{fileType}}',
@@ -1,5 +1,13 @@
1
1
  export declare const ping: (url: string, signal?: AbortSignal) => Promise<string | null>;
2
+ export declare const pickReachableUrl: (urls: string[], hedgeDelayMs?: number) => Promise<string | null>;
3
+ /** Like pickReachableUrl, but falls back to urls[0] when all fail. */
2
4
  export declare const testUrls: (urls?: string[], hedgeDelayMs?: number) => Promise<string | null>;
5
+ /**
6
+ * True when no default endpoint answered the ping and the API base url is the
7
+ * unverified fallback (defaultEndpoints[0]): a request failing there means the
8
+ * machine reaches none of the endpoints, not that this one host is down.
9
+ */
10
+ export declare const isBaseUrlUnreachableFallback: () => boolean;
3
11
  /**
4
12
  * The API base url: the env override, or the first default endpoint that
5
13
  * answers a HEAD ping. Resolved lazily on the first API call (offline commands
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getBaseUrl = exports.testUrls = exports.ping = void 0;
3
+ exports.getBaseUrl = exports.isBaseUrlUnreachableFallback = exports.testUrls = exports.pickReachableUrl = exports.ping = void 0;
4
4
  const constants_1 = require("./constants");
5
5
  const runtime_1 = require("./runtime");
6
6
  const ping = async (url, signal) => {
@@ -33,10 +33,10 @@ const HEDGE_DELAY_MS = 250;
33
33
  // Hedged race instead of pinging every endpoint at once: the preferred (first)
34
34
  // url is tried immediately, each following one only after HEDGE_DELAY_MS of
35
35
  // silence (or immediately when a previous ping failed). The first success wins
36
- // and the losing pings are aborted. Falls back to urls[0] when all fail.
37
- const testUrls = async (urls, hedgeDelayMs = HEDGE_DELAY_MS) => {
38
- if (!urls?.length) {
39
- return null;
36
+ // and the losing pings are aborted. Resolves null when every ping fails.
37
+ const pickReachableUrl = (urls, hedgeDelayMs = HEDGE_DELAY_MS) => {
38
+ if (!urls.length) {
39
+ return Promise.resolve(null);
40
40
  }
41
41
  return new Promise((resolve) => {
42
42
  const controllers = [];
@@ -57,7 +57,7 @@ const testUrls = async (urls, hedgeDelayMs = HEDGE_DELAY_MS) => {
57
57
  controller.abort();
58
58
  }
59
59
  }
60
- resolve(winner ?? urls[0]);
60
+ resolve(winner);
61
61
  };
62
62
  const launchNext = () => {
63
63
  if (hedgeTimer) {
@@ -91,20 +91,36 @@ const testUrls = async (urls, hedgeDelayMs = HEDGE_DELAY_MS) => {
91
91
  launchNext();
92
92
  });
93
93
  };
94
+ exports.pickReachableUrl = pickReachableUrl;
95
+ /** Like pickReachableUrl, but falls back to urls[0] when all fail. */
96
+ const testUrls = async (urls, hedgeDelayMs = HEDGE_DELAY_MS) => {
97
+ if (!urls?.length) {
98
+ return null;
99
+ }
100
+ return (await (0, exports.pickReachableUrl)(urls, hedgeDelayMs)) ?? urls[0];
101
+ };
94
102
  exports.testUrls = testUrls;
95
103
  let baseUrlPromise;
104
+ let noEndpointReachable = false;
105
+ /**
106
+ * True when no default endpoint answered the ping and the API base url is the
107
+ * unverified fallback (defaultEndpoints[0]): a request failing there means the
108
+ * machine reaches none of the endpoints, not that this one host is down.
109
+ */
110
+ const isBaseUrlUnreachableFallback = () => noEndpointReachable;
111
+ exports.isBaseUrlUnreachableFallback = isBaseUrlUnreachableFallback;
96
112
  async function resolveBaseUrl() {
97
113
  const testEndpoint = process.env.PUSHY_REGISTRY || process.env.RNU_API;
98
114
  if (testEndpoint) {
99
115
  return testEndpoint;
100
116
  }
101
- const ret = await (0, exports.testUrls)(constants_1.defaultEndpoints.map((url) => `${url}/status`));
102
- let baseUrl = constants_1.defaultEndpoints[0];
103
- if (ret) {
104
- // remove /status
105
- baseUrl = ret.replace('/status', '');
117
+ const ret = await (0, exports.pickReachableUrl)(constants_1.defaultEndpoints.map((url) => `${url}/status`));
118
+ if (!ret) {
119
+ noEndpointReachable = true;
120
+ return constants_1.defaultEndpoints[0];
106
121
  }
107
- return baseUrl;
122
+ // remove /status
123
+ return ret.replace('/status', '');
108
124
  }
109
125
  /**
110
126
  * The API base url: the env override, or the first default endpoint that
@@ -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.4",
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",