justget 0.1.2

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.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +263 -0
  3. package/dist/chunks/strategy.d.ts +39 -0
  4. package/dist/chunks/strategy.d.ts.map +1 -0
  5. package/dist/chunks/strategy.js +97 -0
  6. package/dist/chunks/strategy.js.map +1 -0
  7. package/dist/cli.d.ts +7 -0
  8. package/dist/cli.d.ts.map +1 -0
  9. package/dist/cli.js +117 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/config.d.ts +71 -0
  12. package/dist/config.d.ts.map +1 -0
  13. package/dist/config.js +158 -0
  14. package/dist/config.js.map +1 -0
  15. package/dist/core/downloader.d.ts +22 -0
  16. package/dist/core/downloader.d.ts.map +1 -0
  17. package/dist/core/downloader.js +555 -0
  18. package/dist/core/downloader.js.map +1 -0
  19. package/dist/core/http.d.ts +51 -0
  20. package/dist/core/http.d.ts.map +1 -0
  21. package/dist/core/http.js +186 -0
  22. package/dist/core/http.js.map +1 -0
  23. package/dist/core/temp.d.ts +47 -0
  24. package/dist/core/temp.d.ts.map +1 -0
  25. package/dist/core/temp.js +137 -0
  26. package/dist/core/temp.js.map +1 -0
  27. package/dist/index.d.ts +13 -0
  28. package/dist/index.d.ts.map +1 -0
  29. package/dist/index.js +17 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/speed/ewma.d.ts +38 -0
  32. package/dist/speed/ewma.d.ts.map +1 -0
  33. package/dist/speed/ewma.js +87 -0
  34. package/dist/speed/ewma.js.map +1 -0
  35. package/dist/speed/speed-monitor.d.ts +56 -0
  36. package/dist/speed/speed-monitor.d.ts.map +1 -0
  37. package/dist/speed/speed-monitor.js +94 -0
  38. package/dist/speed/speed-monitor.js.map +1 -0
  39. package/dist/types.d.ts +236 -0
  40. package/dist/types.d.ts.map +1 -0
  41. package/dist/types.js +5 -0
  42. package/dist/types.js.map +1 -0
  43. package/dist/utils/hash.d.ts +38 -0
  44. package/dist/utils/hash.d.ts.map +1 -0
  45. package/dist/utils/hash.js +89 -0
  46. package/dist/utils/hash.js.map +1 -0
  47. package/dist/utils/validator.d.ts +21 -0
  48. package/dist/utils/validator.d.ts.map +1 -0
  49. package/dist/utils/validator.js +72 -0
  50. package/dist/utils/validator.js.map +1 -0
  51. package/package.json +70 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Wind Li
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,263 @@
1
+ # JustGet
2
+
3
+ <div align="center">
4
+
5
+ **高性能多源竞速分块下载工具** / **Multi-source racing chunked downloader with intelligent scheduling**
6
+
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
8
+ [![Node.js Version](https://img.shields.io/node/v/justget.svg)](https://nodejs.org)
9
+
10
+ </div>
11
+
12
+ ---
13
+
14
+ ## ✨ 特性 / Features
15
+
16
+ - 🔀 **多源竞速** / Multi-source racing — 主站 + 多镜像同时下载,自动选择最快源
17
+ - 🧩 **分块下载** / Chunked download — 大文件分块并行,充分利用带宽
18
+ - 📊 **智能调度** / Intelligent scheduling — 按速度、文件大小动态调整策略
19
+ - 🛡️ **容错机制** / Fault tolerance — 单源失败不影响整体下载
20
+ - 🧮 **平滑测速** / EWMA speed — 指数加权移动平均,速度估计更稳定
21
+ - ✅ **校验支持** / Checksum validation — md5 / sha1 / sha256 / sha512
22
+
23
+ ## 📌 当前状态 / Status
24
+
25
+ | 模块 / Module | 状态 / Status |
26
+ |---|---|
27
+ | 类型定义、配置管理(含默认值/校验/合并) | ✅ 已完成 |
28
+ | 分块策略(chunk size / ranges) | ✅ 已完成 |
29
+ | 速度监控(EWMA / 瞬时 / 平均 / 峰值) | ✅ 已完成 |
30
+ | 临时文件命名、文件校验(checksum) | ✅ 已完成 |
31
+ | **核心下载器 `download()`**(探测→分块→预热→决策→竞速→替换→合并→校验) | ✅ 已完成(真实下载验证通过) |
32
+ | CLI 接入 `download()` | ✅ 已完成 |
33
+
34
+ 已通过的验证场景 / Verified scenarios:
35
+ - 分块下载 + 合并 + 临时文件清理 ✅
36
+ - 多源并行竞速(镜像启动) ✅
37
+ - 主站立即失败(4xx/连接错误)→ 镜像自动接手 ✅
38
+ - checksum 校验(sha256) ✅
39
+ - 断点续传(输出已存在 / merged 临时文件复用) ✅
40
+ - CLI 端到端 ✅
41
+
42
+ ---
43
+
44
+ ## 📦 安装 / Install
45
+
46
+ ```bash
47
+ npm install justget
48
+ # 或 / or
49
+ yarn add justget
50
+ # 或 / or
51
+ pnpm add justget
52
+ ```
53
+
54
+ 需要 Node.js ≥ 18。
55
+
56
+ ---
57
+
58
+ ## 🚀 快速开始 / Quick Start
59
+
60
+ ```typescript
61
+ import { download } from 'justget';
62
+
63
+ await download({
64
+ url: 'https://nodejs.org/dist/v20.10.0/node-v20.10.0-linux-x64.tar.xz',
65
+ output: './node.tar.xz',
66
+ });
67
+ ```
68
+
69
+ 带镜像与进度回调 / With mirrors and progress:
70
+
71
+ ```typescript
72
+ await download({
73
+ url: 'https://nodejs.org/dist/v20.10.0/node-v20.10.0-linux-x64.tar.xz',
74
+ output: './node.tar.xz',
75
+ mirrors: [
76
+ 'https://npmmirror.com/mirrors/node/v20.10.0/node-v20.10.0-linux-x64.tar.xz',
77
+ 'https://mirrors.tuna.tsinghua.edu.cn/nodejs-release/v20.10.0/node-v20.10.0-linux-x64.tar.xz',
78
+ ],
79
+ options: {
80
+ onProgress: (p) => {
81
+ console.log(`${p.percentage.toFixed(1)}% | ${(p.speed / 1024).toFixed(0)} KB/s`);
82
+ },
83
+ },
84
+ });
85
+ ```
86
+
87
+ 完整示例见 / More examples in [`examples/`](./examples/)。
88
+
89
+ ---
90
+
91
+ ## 🖥️ 对外接口 / Public API
92
+
93
+ ### 1. `download(options: DownloadOptions): Promise<DownloadResult>`
94
+
95
+ 核心入口。下载完成后返回结果;失败则抛出异常(含校验失败)。
96
+
97
+ **`DownloadOptions` 参数 / Parameters**(`options` 字段即 `DownloadConfig`,全部可选,均有默认值):
98
+
99
+ | 字段 / Field | 类型 / Type | 默认值 / Default | 说明 / Description |
100
+ |---|---|---|---|
101
+ | `url` | `string` | — | 主站 URL / Primary URL(必填) |
102
+ | `output` | `string` | — | 输出文件路径 / Output file path(必填) |
103
+ | `mirrors` | `string[]` | `[]` | 镜像 URL 列表 / Mirror URLs |
104
+ | `options.primaryWarmupTime` | `number` | `5000` | 主站预热时间 ms(期间只观察不启动镜像)/ Primary warmup |
105
+ | `options.speedThreshold` | `number` | `512000` | 速度阈值 B/s,低于此值考虑启动镜像 / Slow threshold |
106
+ | `options.fastPrimaryThreshold` | `number` | `2048000` | 快速主站阈值 B/s,主站高于此值则跳过镜像 / Fast-primary threshold |
107
+ | `options.sizeThreshold` | `number` | `52428800` | 文件大小阈值 B,小于此值不启动镜像 / Size threshold |
108
+ | `options.minReplaceTime` | `number` | `30000` | 慢源替换最短等待时间 ms / Min time before replacement |
109
+ | `options.replaceCheckInterval` | `number` | `10000` | 源替换检查间隔 ms / Replacement check interval |
110
+ | `options.chunks` | `number \| 'auto'` | `'auto'` | 分块数量 / Chunk count |
111
+ | `options.chunkSize` | `number \| 'auto'` | `'auto'` | 分块大小 B / Chunk size |
112
+ | `options.minChunkSize` | `number` | `1048576` | 最小分块大小 B / Min chunk size |
113
+ | `options.retries` | `number` | `3` | 每源重试次数 / Retries per source |
114
+ | `options.retryDelay` | `number` | `2000` | 重试间隔 ms / Retry delay |
115
+ | `options.timeout` | `number` | `300000` | 下载超时 ms / Download timeout |
116
+ | `options.connectTimeout` | `number` | `10000` | 连接超时 ms / Connection timeout |
117
+ | `options.checksum` | `string` | — | 预期校验和(下载后校验)/ Expected checksum |
118
+ | `options.checksumAlgorithm` | `'md5'\|'sha1'\|'sha256'\|'sha512'` | `'sha256'` | 校验算法 / Algorithm |
119
+ | `options.onProgress` | `(p: ProgressInfo) => void` | — | 进度回调 / Progress callback |
120
+ | `options.onComplete` | `(r: DownloadResult) => void` | — | 完成回调 / Completion callback |
121
+ | `options.onError` | `(e: Error) => void` | — | 错误回调 / Error callback |
122
+
123
+ ### 2. 回调与类型 / Callbacks & Types
124
+
125
+ **`ProgressInfo`**(`onProgress` 入参 / argument):
126
+
127
+ ```typescript
128
+ interface ProgressInfo {
129
+ downloadedBytes: number; // 已下载字节 / bytes downloaded
130
+ totalBytes: number; // 总字节 / total bytes
131
+ percentage: number; // 0-100
132
+ speed: number; // 当前速度 B/s / current speed
133
+ eta: number; // 预计剩余 ms / estimated time remaining
134
+ sources: SourceProgress[]; // 各源进度 / per-source progress
135
+ }
136
+ ```
137
+
138
+ **`DownloadResult`**(`download()` 返回值 / return value):
139
+
140
+ ```typescript
141
+ interface DownloadResult {
142
+ path: string; // 输出文件路径 / output path
143
+ bytes: number; // 总下载字节 / total bytes
144
+ duration: number; // 耗时 ms / duration
145
+ averageSpeed: number; // 平均速度 B/s / average speed
146
+ sources: SourceResult[]; // 各源结果 / per-source results
147
+ }
148
+ ```
149
+
150
+ ### 3. 其他导出 / Other exports
151
+
152
+ 除 `download()` 外,库还导出常用工具(供高级用法与内部使用 / for advanced use):
153
+
154
+ - 配置 / Config: `DEFAULT_CONFIG`、`mergeConfig(user)`
155
+ - 分块策略 / Chunk strategy: `calculateChunkStrategy`、`calculateChunkSize`、`calculateChunkCount`、`createChunkRanges`
156
+ - 速度 / Speed: `SpeedMonitor`、`EWMA`、`getSpeedStats`
157
+ - 工具 / Utils: `calculateChecksum`、`validateFile`、`getTempFileName`、`generateShortHash` 等
158
+ - 类型 / Types: `DownloadOptions`、`DownloadConfig`、`ProgressInfo`、`DownloadResult` 等
159
+
160
+ ---
161
+
162
+ ## 🖥️ CLI
163
+
164
+ ```bash
165
+ # 全局安装后使用 / after global install:
166
+ npm install -g justget
167
+
168
+ justget <url> [options]
169
+ ```
170
+
171
+ ### 参数详解 / Options
172
+
173
+ | 参数 / Option | 类型 / Type | 默认 / Default | 说明 / Description |
174
+ |---|---|---|---|
175
+ | `<url>` | string | — | 下载地址(必填)/ URL to download |
176
+ | `-o, --output <path>` | string | 当前目录文件名 | 输出路径 / Output path |
177
+ | `-m, --mirror <url>` | string[] | — | 镜像地址,可多次指定 / Mirror URL (repeatable) |
178
+ | `--warmup <ms>` | number | `5000` | 主站预热时间 / Primary warmup |
179
+ | `--min-speed <bytes/s>` | number | `512000` | 速度阈值,低于此值启动镜像 / Slow threshold |
180
+ | `--fast-primary-threshold <bytes/s>` | number | `2048000` | 主站超过此速度则跳过镜像 / Fast-primary threshold |
181
+ | `--min-size <bytes>` | number | `52428800` | 文件小于此大小不启动镜像 / Size threshold |
182
+ | `--min-replace-time <ms>` | number | `30000` | 慢源替换最短等待 / Min replace time |
183
+ | `--replace-check-interval <ms>` | number | `10000` | 替换检查间隔 / Check interval |
184
+ | `--chunks <n>` | number\|auto | `auto` | 分块数量 / Chunk count |
185
+ | `--chunk-size <bytes>` | number\|auto | `auto` | 分块大小 / Chunk size |
186
+ | `--min-chunk-size <bytes>` | number | `1048576` | 最小分块大小 / Min chunk size |
187
+ | `--retries <n>` | number | `3` | 每源重试次数 / Retries |
188
+ | `--retry-delay <ms>` | number | `2000` | 重试间隔 / Retry delay |
189
+ | `--timeout <ms>` | number | `300000` | 下载超时 / Timeout |
190
+ | `--connect-timeout <ms>` | number | `10000` | 连接超时 / Connect timeout |
191
+ | `--checksum <hash>` | string | — | 预期校验和 / Expected checksum |
192
+ | `--checksum-algo <algo>` | string | `sha256` | 校验算法 / Algorithm |
193
+ | `-V, --version` | — | — | 版本号 / Version |
194
+ | `-h, --help` | — | — | 帮助 / Help |
195
+
196
+ ### 示例 / Examples
197
+
198
+ ```bash
199
+ # 基础下载 / basic
200
+ justget https://example.com/file.zip -o file.zip
201
+
202
+ # 多镜像竞速 / racing with mirrors
203
+ justget https://example.com/file.zip -o file.zip \
204
+ --mirror https://mirror1.com/file.zip \
205
+ --mirror https://mirror2.com/file.zip
206
+
207
+ # 小文件快速下载(跳过镜像)/ small-file fast mode
208
+ justget https://example.com/file.zip -o file.zip --min-size 0 --fast-primary-threshold 0
209
+
210
+ # 校验 / checksum
211
+ justget https://example.com/file.zip -o file.zip \
212
+ --checksum a1b2c3... --checksum-algo sha256
213
+
214
+ # 查看帮助 / help
215
+ justget --help
216
+ ```
217
+
218
+ ---
219
+
220
+ ## 🧠 工作原理 / How It Works
221
+
222
+ ```
223
+ 阶段1 预热 → 阶段2 决策 → 阶段3 竞速 → 阶段4 优化 → 阶段5 完成
224
+ Primary Decide whether Race primary Replace slow Merge chunks,
225
+ warmup to start + mirrors sources verify, clean
226
+ (默认5s) mirrors (每10s)
227
+ ```
228
+
229
+ - **启动镜像条件 / When mirrors start**:主站速度低于 `speedThreshold`,且文件大于 `sizeThreshold`,且主站速度低于 `fastPrimaryThreshold`;主站立即失败(4xx/5xx 或网络错误)时无条件提前启动镜像。
230
+ - **分块分配 / Chunk allocation**:主源从分块池头部取块、镜像从尾部取块(主源优先持有前段),合并时按 index 顺序拼接。
231
+ - **慢源替换 / Slow-source replacement**:下载超过 `minReplaceTime` 后每 `replaceCheckInterval` 评估一次,连续 `slowChecks` 次低于快源 1/3 速度的慢源被中止、其未完成分块交还池子。
232
+ - **不支持 Range 时 / No Range support**:主站与镜像整文件同时下载,先完成者胜出。
233
+ - **校验 / Validation**:指定 `checksum` 时,合并后校验整个文件。
234
+
235
+ ---
236
+
237
+ ## 🗂️ 临时文件 / Temporary Files
238
+
239
+ 命名格式 / Naming: `.justget-{basename}-{hash}-{source}-{chunk}.{ext}`
240
+
241
+ - 下载完成后自动清理 / cleaned after completion
242
+ - 异常中断可断点续传(>=90% 完整时)/ resume support
243
+
244
+ ---
245
+
246
+ ## 🛠️ 开发 / Development
247
+
248
+ ```bash
249
+ npm install # 安装依赖(含 devDependencies)
250
+ npm run build # tsc 编译到 dist/
251
+ npm run dev # 监听编译
252
+ npm test # vitest 单元测试
253
+ npm run lint # eslint
254
+ npm run format # prettier
255
+ ```
256
+
257
+ ## 📄 许可证 / License
258
+
259
+ MIT License — © Wind Li
260
+
261
+ ---
262
+
263
+ *Made with ❤️ by Wind Li*
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Chunk strategy calculation
3
+ */
4
+ import type { ChunkStrategy } from '../types.js';
5
+ /**
6
+ * Calculate chunk strategy based on file size, primary speed, and progress
7
+ *
8
+ * @param fileSize - Total file size in bytes
9
+ * @param primarySpeed - Current primary source speed in bytes/s
10
+ * @param primaryProgress - Primary source progress (0-1)
11
+ * @returns Chunk strategy
12
+ */
13
+ export declare function calculateChunkStrategy(fileSize: number, primarySpeed: number, primaryProgress: number): ChunkStrategy;
14
+ /**
15
+ * Calculate optimal chunk size
16
+ *
17
+ * @param fileSize - Total file size in bytes
18
+ * @param chunks - Number of chunks or 'auto'
19
+ * @param minChunkSize - Minimum chunk size in bytes (default: 1 MB)
20
+ * @returns Chunk size in bytes
21
+ */
22
+ export declare function calculateChunkSize(fileSize: number, chunks: number | 'auto', minChunkSize?: number): number;
23
+ /**
24
+ * Calculate optimal chunk count
25
+ *
26
+ * @param fileSize - Total file size in bytes
27
+ * @param chunkSize - Chunk size in bytes or 'auto'
28
+ * @returns Number of chunks
29
+ */
30
+ export declare function calculateChunkCount(fileSize: number, chunkSize: number | 'auto'): number;
31
+ /**
32
+ * Create chunk ranges
33
+ *
34
+ * @param fileSize - Total file size in bytes
35
+ * @param chunkCount - Number of chunks
36
+ * @returns Array of chunk ranges [start, end]
37
+ */
38
+ export declare function createChunkRanges(fileSize: number, chunkCount: number): Array<[number, number]>;
39
+ //# sourceMappingURL=strategy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strategy.d.ts","sourceRoot":"","sources":["../../src/chunks/strategy.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAGjD;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,QAAQ,EAAE,MAAM,EAChB,YAAY,EAAE,MAAM,EACpB,eAAe,EAAE,MAAM,GACtB,aAAa,CAyBf;AAED;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GAAG,MAAM,EACvB,YAAY,CAAC,EAAE,MAAM,GACpB,MAAM,CAsBR;AAED;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,GAAG,MAAM,CAKxF;AAED;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,KAAK,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAW/F"}
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Chunk strategy calculation
3
+ */
4
+ import { CHUNK_STRATEGY_CONFIG } from '../config.js';
5
+ /**
6
+ * Calculate chunk strategy based on file size, primary speed, and progress
7
+ *
8
+ * @param fileSize - Total file size in bytes
9
+ * @param primarySpeed - Current primary source speed in bytes/s
10
+ * @param primaryProgress - Primary source progress (0-1)
11
+ * @returns Chunk strategy
12
+ */
13
+ export function calculateChunkStrategy(fileSize, primarySpeed, primaryProgress) {
14
+ const cfg = CHUNK_STRATEGY_CONFIG;
15
+ // Size factor: larger files mean less reserve for primary
16
+ const sizeFactor = Math.min(fileSize / (100 * 1024 * 1024), 1);
17
+ // Speed factor: faster primary means more reserve
18
+ const speedFactor = Math.min(primarySpeed / (1024 * 1024), 1);
19
+ // Progress factor: more progress means more reserve
20
+ const progressFactor = Math.min(primaryProgress, 1);
21
+ // Calculate primary reserve ratio
22
+ let primaryReserve = cfg.basePrimaryReserve
23
+ + sizeFactor * cfg.sizeFactorMax
24
+ + speedFactor * cfg.speedFactorMax
25
+ + progressFactor * cfg.progressFactorMax;
26
+ // Clamp to valid range
27
+ primaryReserve = Math.max(cfg.minPrimaryReserve, Math.min(cfg.maxPrimaryReserve, primaryReserve));
28
+ return {
29
+ primaryReserve,
30
+ mirrorStart: primaryReserve,
31
+ };
32
+ }
33
+ /**
34
+ * Calculate optimal chunk size
35
+ *
36
+ * @param fileSize - Total file size in bytes
37
+ * @param chunks - Number of chunks or 'auto'
38
+ * @param minChunkSize - Minimum chunk size in bytes (default: 1 MB)
39
+ * @returns Chunk size in bytes
40
+ */
41
+ export function calculateChunkSize(fileSize, chunks, minChunkSize) {
42
+ const min = minChunkSize ?? 1024 * 1024; // 1 MB default
43
+ if (chunks === 'auto') {
44
+ // Auto-calculate based on file size
45
+ if (fileSize < 10 * 1024 * 1024) {
46
+ // < 10MB: single chunk
47
+ return fileSize;
48
+ }
49
+ else if (fileSize < 100 * 1024 * 1024) {
50
+ // 10-100MB: 2-4 chunks
51
+ return Math.max(min, Math.ceil(fileSize / 4));
52
+ }
53
+ else if (fileSize < 1024 * 1024 * 1024) {
54
+ // 100MB-1GB: 4-8 chunks
55
+ return Math.max(min, Math.ceil(fileSize / 8));
56
+ }
57
+ else {
58
+ // > 1GB: 8-16 chunks
59
+ return Math.max(min * 2, Math.ceil(fileSize / 16));
60
+ }
61
+ }
62
+ else {
63
+ // Explicit chunk count
64
+ return Math.max(min, Math.ceil(fileSize / chunks));
65
+ }
66
+ }
67
+ /**
68
+ * Calculate optimal chunk count
69
+ *
70
+ * @param fileSize - Total file size in bytes
71
+ * @param chunkSize - Chunk size in bytes or 'auto'
72
+ * @returns Number of chunks
73
+ */
74
+ export function calculateChunkCount(fileSize, chunkSize) {
75
+ if (chunkSize === 'auto') {
76
+ chunkSize = calculateChunkSize(fileSize, 'auto');
77
+ }
78
+ return Math.ceil(fileSize / chunkSize);
79
+ }
80
+ /**
81
+ * Create chunk ranges
82
+ *
83
+ * @param fileSize - Total file size in bytes
84
+ * @param chunkCount - Number of chunks
85
+ * @returns Array of chunk ranges [start, end]
86
+ */
87
+ export function createChunkRanges(fileSize, chunkCount) {
88
+ const chunks = [];
89
+ const chunkSize = Math.ceil(fileSize / chunkCount);
90
+ for (let i = 0; i < chunkCount; i++) {
91
+ const start = i * chunkSize;
92
+ const end = Math.min(start + chunkSize - 1, fileSize - 1);
93
+ chunks.push([start, end]);
94
+ }
95
+ return chunks;
96
+ }
97
+ //# sourceMappingURL=strategy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"strategy.js","sourceRoot":"","sources":["../../src/chunks/strategy.ts"],"names":[],"mappings":"AAAA;;GAEG;AAGH,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAErD;;;;;;;GAOG;AACH,MAAM,UAAU,sBAAsB,CACpC,QAAgB,EAChB,YAAoB,EACpB,eAAuB;IAEvB,MAAM,GAAG,GAAG,qBAAqB,CAAC;IAElC,0DAA0D;IAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,GAAG,CAAC,GAAG,GAAG,IAAI,GAAG,IAAI,CAAC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AC,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC;IAC5B,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
package/dist/cli.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * JustGet CLI
4
+ * 命令行入口(对外接口)
5
+ */
6
+ export {};
7
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA;;;GAGG"}
package/dist/cli.js ADDED
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * JustGet CLI
4
+ * 命令行入口(对外接口)
5
+ */
6
+ import { program } from 'commander';
7
+ import * as path from 'node:path';
8
+ import { download } from './index.js';
9
+ program
10
+ .name('justget')
11
+ .description('Multi-source racing chunked downloader / 多源竞速分块下载器')
12
+ .version('0.1.0');
13
+ program
14
+ .argument('<url>', 'URL to download / 下载地址')
15
+ .option('-o, --output <path>', 'Output file path / 输出文件路径')
16
+ .option('-m, --mirror <url>', 'Mirror URL, repeatable / 镜像地址(可多次指定)', [])
17
+ .option('--warmup <ms>', 'Primary warmup time / 主站预热时间 (ms)', '5000')
18
+ .option('--min-speed <bytes/s>', 'Speed threshold below which mirrors start / 低于此速度启动镜像 (bytes/s)', '512000')
19
+ .option('--fast-primary-threshold <bytes/s>', 'Above this speed, skip mirrors / 主站超过此速度则不启动镜像 (bytes/s)', '2048000')
20
+ .option('--min-size <bytes>', 'File size threshold for mirrors / 启动镜像的最小文件大小 (bytes)', '52428800')
21
+ .option('--min-replace-time <ms>', 'Minimum time before replacing a slow source / 慢源替换最短等待时间 (ms)', '30000')
22
+ .option('--replace-check-interval <ms>', 'Source replacement check interval / 源替换检查间隔 (ms)', '10000')
23
+ .option('--chunks <n>', 'Number of chunks / 分块数量 (auto|n)', 'auto')
24
+ .option('--chunk-size <bytes>', 'Chunk size / 分块大小 (auto|bytes)', 'auto')
25
+ .option('--min-chunk-size <bytes>', 'Minimum chunk size / 最小分块大小 (bytes)', '1048576')
26
+ .option('--retries <n>', 'Retry count per source / 每源重试次数', '3')
27
+ .option('--retry-delay <ms>', 'Retry delay / 重试间隔 (ms)', '2000')
28
+ .option('--timeout <ms>', 'Download timeout / 下载超时 (ms)', '300000')
29
+ .option('--connect-timeout <ms>', 'Connection timeout / 连接超时 (ms)', '10000')
30
+ .option('--checksum <hash>', 'Expected checksum for validation / 预期校验和')
31
+ .option('--checksum-algo <algo>', 'Checksum algorithm / 校验算法 (md5|sha1|sha256|sha512)', 'sha256')
32
+ .action(async (url, options) => {
33
+ try {
34
+ const mirrors = Array.isArray(options.mirror) ? options.mirror : [options.mirror].filter(Boolean);
35
+ await download({
36
+ url,
37
+ output: options.output ?? defaultOutputName(url),
38
+ mirrors,
39
+ options: {
40
+ primaryWarmupTime: parseInt(options.warmup),
41
+ speedThreshold: parseInt(options.minSpeed),
42
+ fastPrimaryThreshold: parseInt(options.fastPrimaryThreshold),
43
+ sizeThreshold: parseInt(options.minSize),
44
+ minReplaceTime: parseInt(options.minReplaceTime),
45
+ replaceCheckInterval: parseInt(options.replaceCheckInterval),
46
+ chunks: options.chunks === 'auto' ? 'auto' : parseInt(options.chunks),
47
+ chunkSize: options.chunkSize === 'auto' ? 'auto' : parseInt(options.chunkSize),
48
+ minChunkSize: parseInt(options.minChunkSize),
49
+ retries: parseInt(options.retries),
50
+ retryDelay: parseInt(options.retryDelay),
51
+ timeout: parseInt(options.timeout),
52
+ connectTimeout: parseInt(options.connectTimeout),
53
+ checksum: options.checksum,
54
+ checksumAlgorithm: options.checksumAlgo,
55
+ onProgress: (progress) => {
56
+ const percentage = progress.percentage.toFixed(1);
57
+ const speed = formatSpeed(progress.speed);
58
+ const eta = formatTime(progress.eta);
59
+ process.stdout.write(`\r${percentage}% | ${speed}/s | ETA: ${eta}`);
60
+ },
61
+ },
62
+ });
63
+ process.stdout.write('\n✓ Download complete / 下载完成!\n');
64
+ // Node ≥19 默认 agent keep-alive 会挂住事件循环,主动退出
65
+ // Node >=19 default keep-alive agent keeps the event loop alive; exit explicitly
66
+ process.exit(0);
67
+ }
68
+ catch (error) {
69
+ console.error('\n✗ Download failed / 下载失败:', error instanceof Error ? error.message : error);
70
+ process.exit(1);
71
+ }
72
+ });
73
+ program.parse();
74
+ /**
75
+ * 未指定 -o 时根据 URL 推断默认输出文件名
76
+ * Default output filename derived from the URL when -o is omitted
77
+ */
78
+ function defaultOutputName(url) {
79
+ try {
80
+ const basename = path.basename(new URL(url).pathname);
81
+ return basename || 'download.bin';
82
+ }
83
+ catch {
84
+ return 'download.bin';
85
+ }
86
+ }
87
+ /**
88
+ * Format speed for display / 格式化速度显示
89
+ */
90
+ function formatSpeed(bytesPerSecond) {
91
+ const units = ['B', 'KB', 'MB', 'GB'];
92
+ let value = bytesPerSecond;
93
+ let unitIndex = 0;
94
+ while (value >= 1024 && unitIndex < units.length - 1) {
95
+ value /= 1024;
96
+ unitIndex++;
97
+ }
98
+ return `${value.toFixed(2)} ${units[unitIndex]}`;
99
+ }
100
+ /**
101
+ * Format time for display / 格式化时间显示
102
+ */
103
+ function formatTime(milliseconds) {
104
+ const seconds = Math.ceil(milliseconds / 1000);
105
+ if (seconds < 60) {
106
+ return `${seconds}s`;
107
+ }
108
+ const minutes = Math.floor(seconds / 60);
109
+ const remainingSeconds = seconds % 60;
110
+ if (minutes < 60) {
111
+ return `${minutes}m ${remainingSeconds}s`;
112
+ }
113
+ const hours = Math.floor(minutes / 60);
114
+ const remainingMinutes = minutes % 60;
115
+ return `${hours}h ${remainingMinutes}m`;
116
+ }
117
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA;;;GAGG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAA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;;GAEG;AACH,SAAS,WAAW,CAAC,cAAsB;IACzC,MAAM,KAAK,GAAG,CAAC,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;IACtC,IAAI,KAAK,GAAG,cAAc,CAAC;IAC3B,IAAI,SAAS,GAAG,CAAC,CAAC;IAElB,OAAO,KAAK,IAAI,IAAI,IAAI,SAAS,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QACrD,KAAK,IAAI,IAAI,CAAC;QACd,SAAS,EAAE,CAAC;IACd,CAAC;IAED,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,SAAS,CAAC,EAAE,CAAC;AACnD,CAAC;AAED;;GAEG;AACH,SAAS,UAAU,CAAC,YAAoB;IACtC,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,CAAC;IAE/C,IAAI,OAAO,GAAG,EAAE,EAAE,CAAC;QACjB,OAAO,GAAG,OAAO,GAAG,CAAC;IACvB,CAAC;IAED,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;IACzC,MAAM,gBAAgB,GAAG,OAAO,GAAG,EAAE,CAAC;IAEtC,IAAI,OAAO,GAAG,EAAE,EAAE,CAAC;QACjB,OAAO,GAAG,OAAO,KAAK,gBAAgB,GAAG,CAAC;IAC5C,CAAC;IAED,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,OAAO,GAAG,EAAE,CAAC,CAAC;IACvC,MAAM,gBAAgB,GAAG,OAAO,GAAG,EAAE,CAAC;IAEtC,OAAO,GAAG,KAAK,KAAK,gBAAgB,GAAG,CAAC;AAC1C,CAAC"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * JustGet 默认配置
3
+ * Default configuration for JustGet downloader
4
+ */
5
+ import type { DownloadConfig } from './types.js';
6
+ /**
7
+ * 默认配置中可被完整默认化的字段(回调与校验和由调用方提供)
8
+ * Fields that always have defaults; callbacks/checksum are caller-provided
9
+ */
10
+ type DefaultConfig = Required<Omit<DownloadConfig, 'checksum' | 'onProgress' | 'onComplete' | 'onError'>>;
11
+ /**
12
+ * Default download configuration
13
+ */
14
+ export declare const DEFAULT_CONFIG: DefaultConfig;
15
+ /**
16
+ * Configuration for speed calculation
17
+ */
18
+ export declare const SPEED_CONFIG: {
19
+ ewmaAlpha: number;
20
+ sampleInterval: number;
21
+ windowSize: number;
22
+ };
23
+ /**
24
+ * Configuration for chunk strategy
25
+ */
26
+ export declare const CHUNK_STRATEGY_CONFIG: {
27
+ minPrimaryReserve: number;
28
+ maxPrimaryReserve: number;
29
+ basePrimaryReserve: number;
30
+ sizeFactorMax: number;
31
+ speedFactorMax: number;
32
+ progressFactorMax: number;
33
+ };
34
+ /**
35
+ * Configuration for source replacement
36
+ */
37
+ export declare const REPLACEMENT_CONFIG: {
38
+ minTimeBeforeReplace: number;
39
+ checkInterval: number;
40
+ slowThresholdRatio: number;
41
+ maxSlowChecks: number;
42
+ bufferSize: number;
43
+ immediateFailureCodes: string[];
44
+ immediateFailureHttp: number[];
45
+ };
46
+ /**
47
+ * Configuration for temporary files
48
+ */
49
+ export declare const TEMP_FILE_CONFIG: {
50
+ prefix: string;
51
+ hashLength: number;
52
+ maxAgeHours: number;
53
+ resumeThreshold: number;
54
+ };
55
+ /**
56
+ * Check if an error indicates immediate failure (not just slow)
57
+ *
58
+ * Immediate failures should trigger mirror start immediately,
59
+ * not wait for warmup timeout.
60
+ */
61
+ export declare function isImmediateFailure(error: Error, httpStatus?: number): boolean;
62
+ /**
63
+ * Merge user config with defaults
64
+ */
65
+ export declare function mergeConfig(userConfig?: DownloadConfig): DownloadConfig;
66
+ /**
67
+ * Validate configuration
68
+ */
69
+ export declare function validateConfig(config: DownloadConfig): void;
70
+ export {};
71
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD;;;GAGG;AACH,KAAK,aAAa,GAAG,QAAQ,CAC3B,IAAI,CAAC,cAAc,EAAE,UAAU,GAAG,YAAY,GAAG,YAAY,GAAG,SAAS,CAAC,CAC3E,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,cAAc,EAAE,aAe5B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,YAAY;;;;CAIxB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,qBAAqB;;;;;;;CAOjC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,kBAAkB;;;;;;;;CAiB9B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,gBAAgB;;;;;CAK5B,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,KAAK,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAwB7E;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,UAAU,CAAC,EAAE,cAAc,GAAG,cAAc,CAUvE;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI,CAuD3D"}