-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest-downloads.js
More file actions
948 lines (810 loc) · 28.4 KB
/
test-downloads.js
File metadata and controls
948 lines (810 loc) · 28.4 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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
#!/usr/bin/env node
import { RuntimeInjector } from './dist/index.js';
import fs from 'fs-extra';
import path from 'path';
import { fileURLToPath } from 'url';
import axios from 'axios';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Test configurations for different platforms and architectures
const testConfigs = [
// Node.js configurations
{
type: 'node',
platforms: [
{ platform: 'win32', arch: 'x64' },
{ platform: 'win32', arch: 'x86' },
{ platform: 'win32', arch: 'arm64' },
{ platform: 'darwin', arch: 'x64' },
{ platform: 'darwin', arch: 'arm64' },
{ platform: 'linux', arch: 'x64' },
{ platform: 'linux', arch: 'arm64' },
{ platform: 'linux', arch: 'armv7l' },
{ platform: 'linux', arch: 'ppc64le' },
{ platform: 'linux', arch: 's390x' },
]
},
// Bun configurations
{
type: 'bun',
platforms: [
{ platform: 'win32', arch: 'x64' },
{ platform: 'darwin', arch: 'x64' },
{ platform: 'darwin', arch: 'arm64' },
{ platform: 'linux', arch: 'x64' },
{ platform: 'linux', arch: 'arm64' },
]
},
// uv configurations
{
type: 'uv',
platforms: [
{ platform: 'win32', arch: 'x64' },
{ platform: 'win32', arch: 'x86' },
{ platform: 'win32', arch: 'arm64' },
{ platform: 'darwin', arch: 'x64' },
{ platform: 'darwin', arch: 'arm64' },
{ platform: 'linux', arch: 'x64' },
{ platform: 'linux', arch: 'x86' },
{ platform: 'linux', arch: 'arm64' },
{ platform: 'linux', arch: 'armv7l' },
{ platform: 'linux', arch: 'ppc64' },
{ platform: 'linux', arch: 'ppc64le' },
{ platform: 'linux', arch: 's390x' },
{ platform: 'linux', arch: 'riscv64' },
// MUSL variants
{ platform: 'linux', arch: 'x64-musl' },
{ platform: 'linux', arch: 'x86-musl' },
{ platform: 'linux', arch: 'arm64-musl' },
{ platform: 'linux', arch: 'arm-musl' },
{ platform: 'linux', arch: 'armv7-musl' },
]
},
// ripgrep configurations
{
type: 'ripgrep',
platforms: [
{ platform: 'win32', arch: 'x64' },
{ platform: 'win32', arch: 'arm64' },
{ platform: 'darwin', arch: 'x64' },
{ platform: 'darwin', arch: 'arm64' },
{ platform: 'linux', arch: 'x64' },
{ platform: 'linux', arch: 'arm64' },
]
},
// Python configurations
{
type: 'python',
platforms: [
{ platform: 'win32', arch: 'x64' },
{ platform: 'win32', arch: 'arm64' },
{ platform: 'darwin', arch: 'x64' },
{ platform: 'darwin', arch: 'arm64' },
{ platform: 'linux', arch: 'x64' },
{ platform: 'linux', arch: 'arm64' },
]
},
// rtk configurations
{
type: 'rtk',
platforms: [
{ platform: 'win32', arch: 'x64' },
{ platform: 'darwin', arch: 'x64' },
{ platform: 'darwin', arch: 'arm64' },
{ platform: 'linux', arch: 'x64' },
{ platform: 'linux', arch: 'arm64' },
]
}
];
const testRootDir = path.join(__dirname, 'test-runtimes');
const results = {
total: 0,
passed: 0,
failed: 0,
errors: []
};
// Colors for console output
const colors = {
reset: '\x1b[0m',
bright: '\x1b[1m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m'
};
function log(message, color = 'reset') {
console.log(`${colors[color]}${message}${colors.reset}`);
}
function logHeader(message) {
log(`\n${'='.repeat(60)}`, 'cyan');
log(`${message}`, 'bright');
log(`${'='.repeat(60)}`, 'cyan');
}
function logSection(message) {
log(`\n${'-'.repeat(40)}`, 'blue');
log(`${message}`, 'blue');
log(`${'-'.repeat(40)}`, 'blue');
}
const PROXY_ENV_KEYS = {
httpProxy: ['HTTP_PROXY', 'http_proxy'],
httpsProxy: ['HTTPS_PROXY', 'https_proxy'],
noProxy: ['NO_PROXY', 'no_proxy'],
};
const GITHUB_TOKEN_ENV_KEYS = ['GITHUB_TOKEN', 'GH_TOKEN'];
function getEnvValue(keys) {
for (const key of keys) {
const value = process.env[key];
if (value) {
return value;
}
}
return undefined;
}
function getTrimmedEnvValue(keys) {
for (const key of keys) {
const value = process.env[key];
if (!value) {
continue;
}
const trimmedValue = value.trim();
if (trimmedValue) {
return trimmedValue;
}
}
return undefined;
}
function getGitHubToken() {
return getTrimmedEnvValue(GITHUB_TOKEN_ENV_KEYS);
}
function getResponseMessage(data) {
if (!data || typeof data !== 'object') {
return undefined;
}
return typeof data.message === 'string' ? data.message : undefined;
}
function createRtkReleaseLookupError(error, hasGitHubToken) {
if (axios.isAxiosError(error)) {
const responseMessage = getResponseMessage(error.response?.data) || error.message;
const hint = hasGitHubToken
? 'Check GITHUB_TOKEN or GH_TOKEN permissions/value, or pin a specific rtk version with --runtime-version to skip the latest release lookup.'
: 'Set GITHUB_TOKEN or GH_TOKEN in CI, or pin a specific rtk version with --runtime-version to skip the latest release lookup.';
if (error.response?.status === 401) {
return new Error(
`Failed to authenticate with GitHub while resolving the latest rtk release. ${hint} GitHub API response: ${responseMessage}`
);
}
if (error.response?.status === 403) {
const isRateLimitError = responseMessage.toLowerCase().includes('rate limit');
const prefix = !hasGitHubToken && isRateLimitError
? 'GitHub API rate limit exceeded while resolving the latest rtk release.'
: 'GitHub API denied access while resolving the latest rtk release.';
return new Error(`${prefix} ${hint} GitHub API response: ${responseMessage}`);
}
return new Error(
`Failed to resolve the latest rtk release from GitHub. GitHub API response: ${responseMessage}`
);
}
const fallbackMessage = error instanceof Error ? error.message : String(error);
return new Error(`Failed to resolve the latest rtk release from GitHub. ${fallbackMessage}`);
}
function normalizeProxyUrl(proxyUrl, fallbackProtocol) {
if (/^[a-z]+:\/\//i.test(proxyUrl)) {
return proxyUrl;
}
const protocol = fallbackProtocol.endsWith(':')
? fallbackProtocol
: `${fallbackProtocol}:`;
return `${protocol}//${proxyUrl}`;
}
function getDefaultPort(protocol) {
return protocol === 'https:' ? 443 : 80;
}
function parseNoProxyEntry(entry) {
let value = entry.trim();
if (!value) {
return { host: '' };
}
if (value.includes('://')) {
try {
value = new URL(value).host;
} catch {
value = value.split('://')[1] || value;
}
}
value = value.split('/')[0];
if (value.startsWith('[') && value.includes(']')) {
const endIndex = value.indexOf(']');
const host = value.slice(1, endIndex);
const portValue = value.slice(endIndex + 1);
if (portValue.startsWith(':')) {
return { host, port: portValue.slice(1) };
}
return { host };
}
const lastColon = value.lastIndexOf(':');
if (lastColon > -1 && value.indexOf(':') === lastColon) {
return {
host: value.slice(0, lastColon),
port: value.slice(lastColon + 1),
};
}
return { host: value };
}
function isNoProxyMatch(targetUrl, noProxy) {
const entries = noProxy
.split(/[,\s]+/)
.map((entry) => entry.trim())
.filter(Boolean);
if (entries.length === 0) {
return false;
}
if (entries.includes('*')) {
return true;
}
const hostname = targetUrl.hostname.toLowerCase();
const port = targetUrl.port || String(getDefaultPort(targetUrl.protocol));
for (const entry of entries) {
if (entry === '*') {
return true;
}
const { host, port: entryPort } = parseNoProxyEntry(entry);
if (!host) {
continue;
}
if (entryPort && entryPort !== port) {
continue;
}
const normalizedHost = host.toLowerCase();
if (!normalizedHost) {
continue;
}
if (!/^[.*]/.test(normalizedHost)) {
if (hostname === normalizedHost) {
return true;
}
continue;
}
const matchHost = normalizedHost.startsWith('*')
? normalizedHost.slice(1)
: normalizedHost;
if (hostname.endsWith(matchHost)) {
return true;
}
}
return false;
}
function buildProxyConfig(proxyUrl, fallbackProtocol) {
const normalizedUrl = normalizeProxyUrl(proxyUrl, fallbackProtocol);
let parsed;
try {
parsed = new URL(normalizedUrl);
} catch {
throw new Error(`Invalid proxy URL: ${proxyUrl}`);
}
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
throw new Error(`Unsupported proxy protocol: ${parsed.protocol}`);
}
const port = parsed.port ? Number(parsed.port) : getDefaultPort(parsed.protocol);
if (Number.isNaN(port)) {
throw new Error(`Invalid proxy port in URL: ${proxyUrl}`);
}
const proxyConfig = {
protocol: parsed.protocol,
host: parsed.hostname,
port,
};
if (parsed.username || parsed.password) {
proxyConfig.auth = {
username: parsed.username,
password: parsed.password,
};
}
return proxyConfig;
}
function formatProxyUrl(proxyUrl, fallbackProtocol) {
try {
const normalized = normalizeProxyUrl(proxyUrl, fallbackProtocol);
const parsed = new URL(normalized);
const auth = parsed.username ? `${parsed.username}:***@` : '';
const port = parsed.port ? `:${parsed.port}` : '';
return `${parsed.protocol}//${auth}${parsed.hostname}${port}`;
} catch {
return proxyUrl;
}
}
function formatProxyConfig(proxyConfig) {
const auth = proxyConfig.auth?.username ? `${proxyConfig.auth.username}:***@` : '';
return `${proxyConfig.protocol}//${auth}${proxyConfig.host}:${proxyConfig.port}`;
}
function resolveProxyForUrl(url) {
const parsedUrl = new URL(url);
const noProxy = getEnvValue(PROXY_ENV_KEYS.noProxy);
if (noProxy && isNoProxyMatch(parsedUrl, noProxy)) {
return { proxy: undefined, reason: 'no_proxy' };
}
const proxyUrl =
parsedUrl.protocol === 'https:'
? getEnvValue(PROXY_ENV_KEYS.httpsProxy)
: getEnvValue(PROXY_ENV_KEYS.httpProxy);
if (!proxyUrl) {
return { proxy: undefined, reason: 'none' };
}
return {
proxy: buildProxyConfig(proxyUrl, parsedUrl.protocol),
reason: parsedUrl.protocol === 'https:' ? 'https_proxy' : 'http_proxy',
};
}
function logProxySummary() {
const httpProxy = getEnvValue(PROXY_ENV_KEYS.httpProxy);
const httpsProxy = getEnvValue(PROXY_ENV_KEYS.httpsProxy);
const noProxy = getEnvValue(PROXY_ENV_KEYS.noProxy);
if (!httpProxy && !httpsProxy && !noProxy) {
log('未检测到代理环境变量,将直接连接。', 'cyan');
return;
}
log('检测到代理环境变量:', 'cyan');
if (httpProxy) {
log(` HTTP_PROXY: ${formatProxyUrl(httpProxy, 'http:')}`, 'cyan');
}
if (httpsProxy) {
log(` HTTPS_PROXY: ${formatProxyUrl(httpsProxy, 'https:')}`, 'cyan');
}
if (noProxy) {
log(` NO_PROXY: ${noProxy}`, 'cyan');
}
}
async function testDownload(type, platform, arch, version) {
const testId = `${type}-${platform}-${arch}`;
const targetDir = path.join(testRootDir, testId);
try {
log(`Testing: ${testId}`, 'yellow');
const injector = new RuntimeInjector({
type,
platform,
arch,
version,
targetDir,
cleanup: false // 不清理,便于测试
});
// 只测试到下载步骤,不实际运行可执行文件(因为跨平台问题)
await injector.inject();
log(`✓ ${testId} - SUCCESS`, 'green');
results.passed++;
return true;
} catch (error) {
log(`✗ ${testId} - FAILED: ${error.message}`, 'red');
results.failed++;
results.errors.push({
testId,
error: error.message,
stack: error.stack
});
return false;
}
}
const RIPGREP_PLATFORM = {
'x64-win32': { target: 'x86_64-pc-windows-msvc', ext: 'zip' },
'arm64-win32': { target: 'aarch64-pc-windows-msvc', ext: 'zip' },
'x64-linux': { target: 'x86_64-unknown-linux-musl', ext: 'tar.gz' },
'arm64-linux': { target: 'aarch64-unknown-linux-gnu', ext: 'tar.gz' },
'x64-darwin': { target: 'x86_64-apple-darwin', ext: 'tar.gz' },
'arm64-darwin': { target: 'aarch64-apple-darwin', ext: 'tar.gz' },
};
const RTK_PLATFORM = {
'x64-win32': { target: 'x86_64-pc-windows-msvc', ext: 'zip' },
'x64-linux': { target: 'x86_64-unknown-linux-musl', ext: 'tar.gz' },
'arm64-linux': { target: 'aarch64-unknown-linux-gnu', ext: 'tar.gz' },
'x64-darwin': { target: 'x86_64-apple-darwin', ext: 'tar.gz' },
'arm64-darwin': { target: 'aarch64-apple-darwin', ext: 'tar.gz' },
};
const RTK_SUPPORTED_PLATFORMS =
'darwin-x64, darwin-arm64, linux-x64, linux-arm64, win32-x64';
const RTK_RELEASE_API = 'https://api.github.com/repos/rtk-ai/rtk/releases/latest';
let latestRtkReleasePromise;
function normalizeRtkVersion(version) {
if (!version || version === 'latest') {
return 'latest';
}
return version.startsWith('v') ? version : `v${version}`;
}
function getRtkPlatformConfig(platform, arch) {
const platformKey = `${String(arch)}-${platform}`;
const platformConfig = RTK_PLATFORM[platformKey];
if (platformConfig) {
return platformConfig;
}
throw new Error(
`Unsupported platform for rtk: ${platform}-${arch}. Supported targets: ${RTK_SUPPORTED_PLATFORMS}.`
);
}
function getRtkAssetName(platform, arch) {
const platformConfig = getRtkPlatformConfig(platform, arch);
return `rtk-${platformConfig.target}.${platformConfig.ext}`;
}
async function getLatestRtkRelease() {
if (!latestRtkReleasePromise) {
latestRtkReleasePromise = (async () => {
const proxyDecision = resolveProxyForUrl(RTK_RELEASE_API);
const githubToken = getGitHubToken();
const headers = {
Accept: 'application/vnd.github+json',
'User-Agent': 'tiny-runtime-injector-tests',
};
if (githubToken) {
headers.Authorization = `Bearer ${githubToken}`;
}
try {
const response = await axios.get(RTK_RELEASE_API, {
headers,
timeout: 10000,
proxy: proxyDecision.proxy ?? false,
});
return {
tagName: normalizeRtkVersion(response.data.tag_name),
assets: (response.data.assets || []).map((asset) => asset.name),
};
} catch (error) {
throw createRtkReleaseLookupError(error, Boolean(githubToken));
}
})();
}
return latestRtkReleasePromise;
}
async function resolveVersion(type, platform, arch, version) {
if (type !== 'rtk') {
return version;
}
const normalizedVersion = normalizeRtkVersion(version);
if (normalizedVersion !== 'latest') {
return normalizedVersion;
}
const expectedAsset = getRtkAssetName(platform, arch);
const release = await getLatestRtkRelease();
if (!release.assets.includes(expectedAsset)) {
throw new Error(
`Latest rtk release ${release.tagName} does not include asset ${expectedAsset} for ${platform}-${arch}`
);
}
return release.tagName;
}
// 直接实现URL生成逻辑用于测试
function generateDownloadUrl(type, platform, arch, version) {
if (type === 'node') {
const platformId = getNodePlatformIdentifier(platform, arch);
const fileExtension = platform === "win32" ? "zip" : "tar.gz";
const fileName = `node-${version}-${platformId}.${fileExtension}`;
return `https://nodejs.org/dist/${version}/${fileName}`;
} else if (type === 'bun') {
const platformId = getBunPlatformIdentifier(platform, arch);
const fileName = `bun-${platformId}.zip`;
return `https://github.com/oven-sh/bun/releases/download/bun-${version}/${fileName}`;
} else if (type === 'uv') {
const platformId = getUvPlatformIdentifier(platform, arch);
const fileExtension = platform === "win32" ? "zip" : "tar.gz";
const fileName = `uv-${platformId}.${fileExtension}`;
return `https://github.com/astral-sh/uv/releases/download/${version}/${fileName}`;
} else if (type === 'ripgrep') {
const platformKey = `${arch}-${platform}`;
const platformConfig = RIPGREP_PLATFORM[platformKey];
if (!platformConfig) {
throw new Error(`Unsupported platform for ripgrep: ${platform}-${arch}`);
}
const fileName = `ripgrep-${version}-${platformConfig.target}.${platformConfig.ext}`;
return `https://github.com/BurntSushi/ripgrep/releases/download/${version}/${fileName}`;
} else if (type === 'python') {
const platformTarget = getPythonPlatformIdentifier(platform, arch);
const releaseDate = version.includes('+') ? version.split('+')[1] : '20250117';
const pythonVersion = version.includes('+') ? version.split('+')[0] : version;
const fileName = `cpython-${pythonVersion}+${releaseDate}-${platformTarget}-install_only.tar.gz`;
return `https://github.com/astral-sh/python-build-standalone/releases/download/${releaseDate}/${fileName}`;
} else if (type === 'rtk') {
const fileName = getRtkAssetName(platform, arch);
return `https://github.com/rtk-ai/rtk/releases/download/${normalizeRtkVersion(version)}/${fileName}`;
}
throw new Error(`Unknown runtime type: ${type}`);
}
function getNodePlatformIdentifier(platform, arch) {
const archStr = String(arch);
if (platform === "darwin") {
return archStr === "arm64" ? "darwin-arm64" : "darwin-x64";
} else if (platform === "linux") {
if (archStr === "arm64") return "linux-arm64";
if (archStr === "arm" || archStr === "armv7l") return "linux-armv7l";
if (archStr === "ppc64" || archStr === "ppc64le") return "linux-ppc64le";
if (archStr === "s390" || archStr === "s390x") return "linux-s390x";
return "linux-x64";
} else if (platform === "win32") {
if (archStr === "arm64") return "win-arm64";
if (archStr === "ia32" || archStr === "x86") return "win-x86";
return "win-x64";
}
throw new Error(`Unsupported platform: ${platform}-${archStr}`);
}
function getBunPlatformIdentifier(platform, arch) {
if (platform === "darwin") {
return arch === "arm64" ? "darwin-aarch64" : "darwin-x64";
} else if (platform === "linux") {
return arch === "arm64" ? "linux-aarch64" : "linux-x64";
} else if (platform === "win32") {
return arch === "arm64" ? "windows-aarch64" : "windows-x64";
}
throw new Error(`Unsupported platform for Bun: ${platform}-${arch}`);
}
function getUvPlatformIdentifier(platform, arch) {
if (platform === "darwin") {
return arch === "arm64" ? "aarch64-apple-darwin" : "x86_64-apple-darwin";
} else if (platform === "linux") {
// Standard Linux builds
if (arch === "arm64") return "aarch64-unknown-linux-gnu";
if (arch === "x64" || arch === "x86_64") return "x86_64-unknown-linux-gnu";
if (arch === "x86" || arch === "ia32") return "i686-unknown-linux-gnu";
if (arch === "arm" || arch === "armv7l") return "armv7-unknown-linux-gnueabihf";
if (arch === "ppc64") return "powerpc64-unknown-linux-gnu";
if (arch === "ppc64le") return "powerpc64le-unknown-linux-gnu";
if (arch === "s390x") return "s390x-unknown-linux-gnu";
if (arch === "riscv64") return "riscv64gc-unknown-linux-gnu";
// MUSL builds
if (arch === "arm64-musl") return "aarch64-unknown-linux-musl";
if (arch === "x64-musl" || arch === "x86_64-musl") return "x86_64-unknown-linux-musl";
if (arch === "x86-musl" || arch === "ia32-musl") return "i686-unknown-linux-musl";
if (arch === "arm-musl") return "arm-unknown-linux-musleabihf";
if (arch === "armv7-musl") return "armv7-unknown-linux-musleabihf";
// Default to standard x64 GNU build for unknown architectures
return "x86_64-unknown-linux-gnu";
} else if (platform === "win32") {
if (arch === "arm64") return "aarch64-pc-windows-msvc";
if (arch === "x86" || arch === "ia32") return "i686-pc-windows-msvc";
return "x86_64-pc-windows-msvc";
}
throw new Error(`Unsupported platform for uv: ${platform}-${arch}`);
}
function getPythonPlatformIdentifier(platform, arch) {
const archStr = String(arch);
if (platform === "darwin") {
return archStr === "arm64"
? "aarch64-apple-darwin"
: "x86_64-apple-darwin";
} else if (platform === "linux") {
if (arch === "arm64") return "aarch64-unknown-linux-gnu";
if (arch === "x64" || arch === "x86_64") return "x86_64-unknown-linux-gnu";
throw new Error(
`Unsupported platform for Python: ${platform}-${archStr}. Only x64 and arm64 are supported for Linux.`
);
} else if (platform === "win32") {
if (arch === "x64" || arch === "x86_64") return "x86_64-pc-windows-msvc";
if (arch === "arm64") return "aarch64-pc-windows-msvc";
throw new Error(
`Unsupported platform for Python: ${platform}-${archStr}. Only x64 and arm64 are supported for Windows.`
);
}
throw new Error(
`Unsupported platform for Python: ${platform}-${archStr}`
);
}
// 检查URL是否可访问(不下载文件内容)
async function checkUrlAccessibility(url, testId) {
let proxyDecision;
try {
proxyDecision = resolveProxyForUrl(url);
} catch (error) {
log(`✗ ${testId} - Proxy error: ${error.message} - ${url}`, 'red');
return { success: false, error: error.message };
}
const proxySuffix = proxyDecision.proxy
? ` (proxy ${formatProxyConfig(proxyDecision.proxy)})`
: proxyDecision.reason === 'no_proxy'
? ' (no_proxy)'
: '';
try {
const response = await axios.head(url, {
timeout: 10000, // 10秒超时
maxRedirects: 5,
validateStatus: (status) => status < 400, // 只要不是4xx或5xx错误就算成功
proxy: proxyDecision.proxy ?? false,
});
const contentLength = response.headers['content-length'];
const sizeInfo = contentLength ? ` (${Math.round(contentLength / 1024 / 1024 * 100) / 100}MB)` : '';
log(`✓ ${testId} - HTTP ${response.status}${sizeInfo}${proxySuffix} - ${url}`, 'green');
return { success: true, status: response.status, size: contentLength };
} catch (error) {
if (error.response) {
// 服务器响应了错误状态码
log(`✗ ${testId} - HTTP ${error.response.status}${proxySuffix} - ${url}`, 'red');
return {
success: false,
status: error.response.status,
error: `HTTP ${error.response.status}`
};
} else {
// 网络错误或其他错误
log(`✗ ${testId} - ${error.message}${proxySuffix} - ${url}`, 'red');
return {
success: false,
error: error.message
};
}
}
}
async function validateDownloadUrl(type, platform, arch, version) {
const testId = `${type}-${platform}-${arch}`;
try {
const resolvedVersion = await resolveVersion(type, platform, arch, version);
const downloadUrl = generateDownloadUrl(type, platform, arch, resolvedVersion);
// 使用HEAD请求检查URL可访问性
const result = await checkUrlAccessibility(downloadUrl, testId);
return {
testId,
downloadUrl,
resolvedVersion,
valid: result.success,
status: result.status,
error: result.error,
size: result.size
};
} catch (error) {
log(`✗ ${testId} - Invalid URL: ${error.message}`, 'red');
return {
testId,
error: error.message,
valid: false
};
}
}
async function validateExpectedFailure(type, platform, arch, version, expectedMessage) {
const testId = `${type}-${platform}-${arch}-expected-error`;
try {
const resolvedVersion = await resolveVersion(type, platform, arch, version);
generateDownloadUrl(type, platform, arch, resolvedVersion);
log(`✗ ${testId} - Expected an error but URL generation succeeded`, 'red');
return {
testId,
valid: false,
error: 'Expected an error but URL generation succeeded',
};
} catch (error) {
if (error.message.includes(expectedMessage)) {
log(`✓ ${testId} - Expected error: ${error.message}`, 'green');
return {
testId,
valid: true,
status: 'expected-error',
};
}
log(`✗ ${testId} - Unexpected error: ${error.message}`, 'red');
return {
testId,
valid: false,
error: error.message,
};
}
}
async function runUrlValidationTests() {
logHeader('下载链接可用性测试');
logProxySummary();
const urlResults = [];
let totalChecked = 0;
for (const config of testConfigs) {
logSection(`测试 ${config.type.toUpperCase()} 下载链接`);
// 并发检查所有URL以提高速度
const promises = config.platforms.map(({ platform, arch }) => {
totalChecked++;
return validateDownloadUrl(config.type, platform, arch, getDefaultVersion(config.type));
});
const results = await Promise.all(promises);
urlResults.push(...results);
}
logSection('测试 RTK 额外版本场景');
const extraRtkChecks = await Promise.all([
validateDownloadUrl('rtk', 'win32', 'x64', 'v0.30.0'),
validateDownloadUrl('rtk', 'win32', 'x64', '0.30.0'),
validateExpectedFailure('rtk', 'win32', 'arm64', 'latest', 'Unsupported platform for rtk'),
]);
totalChecked += extraRtkChecks.length;
urlResults.push(...extraRtkChecks);
const validUrls = urlResults.filter(r => r.valid);
const invalidUrls = urlResults.filter(r => !r.valid);
// 按状态分组统计
const statusCounts = {};
validUrls.forEach(r => {
const status = r.status || 'unknown';
statusCounts[status] = (statusCounts[status] || 0) + 1;
});
logHeader('测试结果统计');
log(`总共检查: ${totalChecked} 个下载链接`, 'bright');
log(`✓ 可用链接: ${validUrls.length}`, 'green');
log(`✗ 不可用链接: ${invalidUrls.length}`, 'red');
log(`成功率: ${Math.round((validUrls.length / totalChecked) * 100)}%`, 'blue');
if (Object.keys(statusCounts).length > 0) {
log(`\nHTTP状态码统计:`, 'cyan');
Object.entries(statusCounts).forEach(([status, count]) => {
log(` HTTP ${status}: ${count} 个`, 'cyan');
});
}
if (invalidUrls.length > 0) {
log(`\n不可用的下载链接:`, 'red');
invalidUrls.forEach(r => {
log(` - ${r.testId}: ${r.error || 'Unknown error'}`, 'red');
if (r.downloadUrl) {
log(` URL: ${r.downloadUrl}`, 'yellow');
}
});
}
// 显示一些有效链接作为示例
if (validUrls.length > 0) {
log(`\n有效链接示例:`, 'green');
validUrls.slice(0, 5).forEach(r => {
const sizeInfo = r.size ? ` (${Math.round(r.size / 1024 / 1024 * 100) / 100}MB)` : '';
log(` ✓ ${r.testId}${sizeInfo}`, 'green');
log(` ${r.downloadUrl}`, 'cyan');
});
if (validUrls.length > 5) {
log(` ... 还有 ${validUrls.length - 5} 个有效链接`, 'green');
}
}
results.total = totalChecked;
results.passed = validUrls.length;
results.failed = invalidUrls.length;
results.errors = invalidUrls.map(r => ({
testId: r.testId,
error: r.error || 'Unknown error',
url: r.downloadUrl
}));
return urlResults;
}
function getDefaultVersion(type) {
const defaultVersions = {
node: 'v24.12.0',
bun: 'v1.3.5',
uv: '0.9.18',
ripgrep: '14.1.1',
python: '3.12.12+20251217',
rtk: 'latest',
};
return defaultVersions[type];
}
async function printSummary() {
logHeader('最终总结');
log(`测试完成!`, 'bright');
log(`✓ 成功: ${results.passed}`, 'green');
log(`✗ 失败: ${results.failed}`, 'red');
log(`总计: ${results.total}`, 'blue');
log(`成功率: ${results.total > 0 ? Math.round((results.passed / results.total) * 100) : 0}%`, 'bright');
if (results.errors.length > 0) {
log(`\n失败详情:`, 'red');
results.errors.forEach((error, index) => {
log(`\n${index + 1}. ${error.testId}:`, 'red');
log(` 错误: ${error.error}`, 'red');
if (error.url) {
log(` 链接: ${error.url}`, 'yellow');
}
});
}
}
async function main() {
logHeader('TINY RUNTIME INJECTOR - 下载链接验证测试');
const startTime = Date.now();
try {
log('开始检查所有运行时的下载链接...', 'blue');
log('注意: 此测试只检查链接可用性,不下载实际文件\n', 'yellow');
// 运行URL验证测试
await runUrlValidationTests();
// 打印总结
await printSummary();
} catch (error) {
log(`\n致命错误: ${error.message}`, 'red');
console.error(error.stack);
}
const endTime = Date.now();
const duration = Math.round((endTime - startTime) / 1000);
log(`\n测试耗时: ${duration} 秒`, 'blue');
// 退出状态
process.exit(results.failed > 0 ? 1 : 0);
}
// 导出测试函数以便单独使用
export { runUrlValidationTests };
// 如果直接运行此脚本
if (import.meta.url === `file://${process.argv[1]}`) {
main().catch(console.error);
}