veodl 1.8.3 → 1.9.1

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/src/cli.js CHANGED
@@ -1,492 +1,655 @@
1
- import { outputOptions, outputStream, withOutputSettings } from './output.js';
2
- import { validateTemplate } from './naming.js';
3
- import { parseArgs } from 'node:util';
4
- import path from 'node:path';
5
- import { readFile } from 'node:fs/promises';
6
- import { createReporter } from './progress.js';
7
- import { openFile } from './open-file.js';
8
- import { maybeUpdateNotice, updateMain, UPDATE_HELP, defaultRegistry, packageVersion } from './updater.js';
9
- import { applyProfile, configMain, loadConfig } from './config.js';
10
- import { validateItems, describeEstimate } from './playlist.js';
11
- import { retryOptions, runJob, jobFilePath } from './jobs.js';
12
- import { QUALITIES, VIDEO_FORMATS, AUDIO_FORMATS, validateUrl, readableError, cleanText, validateCookieFile, validateBrowserSpec, cookieFileWarning } from './utils.js';
13
-
14
- export const HELP = `veo - simple video downloader
15
-
16
- Usage:
17
- veo <url> [<url>...] [options]
18
-
19
- Options:
20
- -q, --quality <quality> Video quality (best, 2160p, 1440p, 1080p, 720p, 480p, 360p)
21
- Numeric qualities are an upper bound: -q 720p never
22
- downloads 2160p. Use --closest-quality for the nearest
23
- available resolution instead.
24
- -o, --output <path> Output directory (default: current directory)
25
- -r, --rename <name> Filename without extension; * inserts the original title
26
- --closest-quality Pick the nearest available resolution, above or below
27
- --open Open the saved file with your default app
28
- --audio Download audio only (default: mp3)
29
- --format <format> Video: mp4, mkv, webm, mov; audio: mp3, m4a, aac, opus, flac, wav
30
- Video uses lossless remux; incompatible codecs fail.
31
- --compatible Ensure MP4 H.264/AAC; converts only when needed (may lose quality)
32
- --recode Allow video conversion (requires --format; may lose quality)
33
- --concurrent-downloads <n> Parallel URLs/batch entries (1-4; default: 2)
34
- --adaptive-concurrency Reduce connections and retry temporary failures (default: on)
35
- --filename-template <s> Filename without extension, e.g. {index} - {title}
36
- --folder-template <s> Relative folders, e.g. {channel}/{year}
37
- --check-space Estimate cache/output space before downloading (default: on)
38
- --timings Show phase timings (default: on; --no-timings disables)
39
- --no-color Disable terminal colors (also respects NO_COLOR)
40
- --playlist-concurrency <n> Simultaneous playlist downloads (1-4; default: 2)
41
- --playlist Download every entry of a playlist or channel URL
42
- -N, --concurrent-fragments <n>
43
- Download this many fragments in parallel (1-16; default: 8)
44
- --subs Download subtitles (default languages: en)
45
- --sub-langs <langs> Subtitle languages, e.g. "de,en" (implies --subs)
46
- --embed-subs Embed subtitles into the video file
47
- --embed-metadata Embed title, date and other metadata
48
- --embed-thumbnail Embed the thumbnail
49
- --sponsorblock-remove <categories>
50
- Remove sponsor segments, e.g. "sponsor,selfpromo"
51
- --section <range> Download only a time range, e.g. "*10:00-12:00"
52
- --cookies <file> Netscape cookie file, for content you may access
53
- --cookies-from-browser <browser[:profile]>
54
- Read cookies from an installed browser
55
- --resume Keep partial data and continue an interrupted download
56
- --list-formats Show the available formats and exit
57
- --dry-run Show what would be downloaded and exit
58
- --json Print one JSON object per URL instead of prose
59
- --profile <name> Apply a named config profile
60
- --batch-file <file> Read URLs from a file (one per line; # comments)
61
- --retry-failed <file> Retry failed/unfinished items from a saved job
62
- --playlist-items <list> Select playlist entries, e.g. 1,3-5 (implies --playlist)
63
- --skip-existing Skip matching downloads still present on disk
64
- --no-<boolean-option> Disable a stored boolean default, e.g. --no-open
65
- -v, --version Show installed version (also: veo version)
66
- -h, --help Show help (also: veo help)
67
-
68
- Commands:
69
- veo update|up [--check] Update veo itself with npm (up is a short alias)
70
- veo backend update Install a newer yt-dlp release (see veo backend --help)
71
- veo doctor Diagnose the local setup
72
- veo flush Stop veo runs and clear temporary downloads and jobs
73
- veo stats Show persistent download statistics
74
- veo history Show the last 5 downloads (--json for scripting)
75
- veo retry --last Retry the newest failed or unfinished job
76
- veo history --failed --limit 20 Filter and extend download history
77
- veo runs [id] List active runs; add --json for metadata and progress
78
- veo inspect <file> Read media metadata; --check-audio measures audio signal
79
- veo inspect run <id> Inspect saved files from a finished run by its id
80
- veo stop [id] Stop one run, or every active run
81
- veo alias list|add|remove Manage extra command names (wrappers calling veo)
82
- veo uninstall [-p <name>] Remove one alias, or everything with --yes
83
- veo version Show the installed version
84
- veo config edit|path|profiles|check|show|reset Manage defaults and named profiles
85
- veo config edit [--external|--terminal] Choose the configuration editor
86
-
87
- Run veo without arguments in a terminal for interactive setup.
88
- Agent workflow: see docs/AGENT_GUIDE.md in the repository or installed package.
89
-
90
- Defaults can be stored in the veo config file; veo doctor prints its location.
91
-
92
- Examples:
93
- veo "https://youtube.com/watch?v=..."
94
- veo <url> -q 1080p
95
- veo <url> --audio
96
- veo <url> -o ./downloads
97
- veo <url> -r "My Video" --open
98
- veo <url1> <url2> --subs --embed-metadata
99
- veo update --check
100
-
101
- Only download content you are authorized or legally permitted to download.
102
- `;
103
-
104
- const STRING_OPTIONS = {
105
- quality: { short: 'q' },
106
- output: { short: 'o' },
107
- rename: { short: 'r' },
108
- format: {},
109
- 'playlist-concurrency': {},
110
- 'concurrent-downloads': {},
111
- 'filename-template': {},
112
- 'folder-template': {},
113
- cookies: {},
114
- 'cookies-from-browser': {},
115
- 'concurrent-fragments': { short: 'N' },
116
- 'sub-langs': {},
117
- 'sponsorblock-remove': {},
118
- section: {},
119
- profile: {},
120
- 'batch-file': {},
121
- 'retry-failed': {},
122
- 'playlist-items': {},
123
- };
124
-
125
- const BOOLEAN_OPTIONS = {
126
- compatible: {},
127
- recode: {},
128
- 'adaptive-concurrency': {},
129
- 'check-space': {},
130
- timings: {},
131
- color: {},
132
- open: {},
133
- audio: {},
134
- resume: {},
135
- playlist: {},
136
- subs: {},
137
- 'embed-subs': {},
138
- 'embed-metadata': {},
139
- 'embed-thumbnail': {},
140
- 'closest-quality': {},
141
- 'list-formats': {},
142
- 'dry-run': {},
143
- json: {},
144
- help: { short: 'h' },
145
- version: { short: 'v' },
146
- 'skip-existing': {},
147
- };
148
-
149
- // Config defaults, so an explicit flag always wins but a stored preference does not.
150
- export function optionDefaults(config = {}) {
151
- return {
152
- quality: config.quality ?? 'best',
153
- output: config.output ?? process.cwd(),
154
- rename: config.rename,
155
- format: config.format,
156
- compatible: config.compatible ?? false,
157
- recode: config.recode ?? false,
158
- 'concurrent-downloads': String(config.concurrentDownloads ?? 2),
159
- 'filename-template': config.filenameTemplate,
160
- 'folder-template': config.folderTemplate,
161
- 'adaptive-concurrency': config.adaptiveConcurrency ?? true,
162
- 'check-space': config.checkSpace ?? true,
163
- timings: config.timings ?? true,
164
- color: config.color ?? true,
165
- 'playlist-concurrency': String(config.playlistConcurrency ?? 2),
166
- cookies: config.cookies,
167
- 'cookies-from-browser': config.cookiesFromBrowser,
168
- 'concurrent-fragments': String(config.concurrentFragments ?? 8),
169
- 'sub-langs': config.subLangs,
170
- 'sponsorblock-remove': config.sponsorblockRemove,
171
- section: config.section,
172
- open: config.open ?? false,
173
- audio: config.audio ?? false,
174
- resume: config.resume ?? false,
175
- playlist: config.playlist ?? false,
176
- subs: config.subs ?? false,
177
- 'embed-subs': config.embedSubs ?? false,
178
- 'embed-metadata': config.embedMetadata ?? false,
179
- 'embed-thumbnail': config.embedThumbnail ?? false,
180
- 'closest-quality': config.closestQuality ?? false,
181
- json: config.json ?? false,
182
- 'skip-existing': config.skipExisting ?? false,
183
- 'playlist-items': config.playlistItems,
184
- };
185
- }
186
-
1
+ import { outputOptions, outputStream, withOutputSettings } from './output.js';
2
+ import { validateTemplate } from './naming.js';
3
+ import { parseArgs } from 'node:util';
4
+ import path from 'node:path';
5
+ import { readFile } from 'node:fs/promises';
6
+ import { createInterface } from 'node:readline/promises';
7
+ import { createReporter } from './progress.js';
8
+ import { openFile } from './open-file.js';
9
+ import { maybeUpdateNotice, updateMain, UPDATE_HELP, defaultRegistry, packageVersion } from './updater.js';
10
+ import { applyProfile, configMain, loadConfig } from './config.js';
11
+ import { validateItems, describeEstimate } from './playlist.js';
12
+ import { parseSourceTimeout } from './source-discovery.js';
13
+ import { explainUnknownOption, optionSpellings, suggestOption } from './option-suggestions.js';
14
+ import { retryOptions, runJob, jobFilePath } from './jobs.js';
15
+ import { QUALITIES, VIDEO_FORMATS, AUDIO_FORMATS, validateUrl, readableError, cleanText, validateCookieFile, validateBrowserSpec, cookieFileWarning } from './utils.js';
16
+
17
+ export const HELP = `veo - simple video downloader
18
+
19
+ Usage:
20
+ veo <url> [<url>...] [options]
21
+
22
+ Options:
23
+ -q, --quality <quality> Video quality (best, 2160p, 1440p, 1080p, 720p, 480p, 360p)
24
+ Numeric qualities are an upper bound: -q 720p never
25
+ downloads 2160p. Use --closest-quality for the nearest
26
+ available resolution instead.
27
+ -o, --output <path> Output directory (default: current directory)
28
+ -r, --rename <name> Filename without extension; * inserts the original title
29
+ --closest-quality Pick the nearest available resolution, above or below
30
+ --open Open the saved file with your default app
31
+ --audio Download audio only (default: mp3)
32
+ --format <format> Video: mp4, mkv, webm, mov; audio: mp3, m4a, aac, opus, flac, wav
33
+ Video uses lossless remux; incompatible codecs fail.
34
+ --compatible Ensure MP4 H.264/AAC; converts only when needed (may lose quality)
35
+ --recode Allow video conversion (requires --format; may lose quality)
36
+ --concurrent-downloads <n> Parallel URLs/batch entries (1-4; default: 2)
37
+ --adaptive-concurrency Reduce connections and retry temporary failures (default: on)
38
+ --filename-template <s> Filename without extension, e.g. {index} - {title}
39
+ --folder-template <s> Relative folders, e.g. {channel}/{year}
40
+ --check-space Estimate cache/output space before downloading (default: on)
41
+ --timings Show phase timings (default: on; --no-timings disables)
42
+ --no-color Disable terminal colors (also respects NO_COLOR)
43
+ --playlist-concurrency <n> Simultaneous playlist downloads (1-4; default: 2)
44
+ --playlist Download every entry of a playlist or channel URL
45
+ -N, --concurrent-fragments <n>
46
+ Download this many fragments in parallel (1-16; default: 8)
47
+ --subs Download subtitles (default languages: en)
48
+ --sub-langs <langs> Subtitle languages, e.g. "de,en" (implies --subs)
49
+ --embed-subs Embed subtitles into the video file
50
+ --embed-metadata Embed title, date and other metadata
51
+ --embed-thumbnail Embed the thumbnail
52
+ --sponsorblock-remove <categories>
53
+ Remove sponsor segments, e.g. "sponsor,selfpromo"
54
+ --section <range> Download only a time range, e.g. "*10:00-12:00"
55
+ --cookies <file> Netscape cookie file, for content you may access
56
+ --cookies-from-browser <browser[:profile]>
57
+ Read cookies from an installed browser
58
+ --resume Keep partial data and continue an interrupted download
59
+ --list-formats Show the available formats and exit
60
+ --list-sources Find video sources loaded by a web page and exit
61
+ --auto-list-sources Search automatically after no downloadable video is found
62
+ --source <n> Select source number from that page (also for scripts)
63
+ --deep-scan Check every media candidate found during source search
64
+ --timeout <duration> Source search deadline, e.g. 30, 30s or 2m (5s-10m)
65
+ --dry-run Show what would be downloaded and exit
66
+ --json Print one JSON object per URL instead of prose
67
+ --profile <name> Apply a named config profile
68
+ --batch-file <file> Read URLs from a file (one per line; # comments)
69
+ --retry-failed <file> Retry failed/unfinished items from a saved job
70
+ --playlist-items <list> Select playlist entries, e.g. 1,3-5 (implies --playlist)
71
+ --skip-existing Skip matching downloads still present on disk
72
+ --no-<boolean-option> Disable a stored boolean default, e.g. --no-open
73
+ -v, --version Show installed version (also: veo version)
74
+ -h, --help Show help (also: veo help)
75
+
76
+ Commands:
77
+ veo update|up [--check] Update veo itself with npm (up is a short alias)
78
+ veo backend update Install a newer yt-dlp release (see veo backend --help)
79
+ veo doctor Diagnose the local setup
80
+ veo flush Stop veo runs and clear temporary downloads and jobs
81
+ veo stats Show persistent download statistics
82
+ veo history Show the last 5 downloads (--json for scripting)
83
+ veo retry --last Retry the newest failed or unfinished job
84
+ veo history --failed --limit 20 Filter and extend download history
85
+ veo runs [id] List active runs; add --json for metadata and progress
86
+ veo inspect <file> Read media metadata; --check-audio measures audio signal
87
+ veo inspect run <id> Inspect saved files from a finished run by its id
88
+ veo stop [id] Stop one run, or every active run
89
+ veo alias list|add|remove Manage extra command names (wrappers calling veo)
90
+ veo uninstall [-p <name>] Remove one alias, or everything with --yes
91
+ veo version Show the installed version
92
+ veo config edit|path|profiles|check|show|reset Manage defaults and named profiles
93
+ veo config edit [--external|--terminal] Choose the configuration editor
94
+
95
+ Run veo without arguments in a terminal for interactive setup.
96
+ Agent workflow: see docs/AGENT_GUIDE.md in the repository or installed package.
97
+
98
+ Defaults can be stored in the veo config file; veo doctor prints its location.
99
+
100
+ Examples:
101
+ veo "https://youtube.com/watch?v=..."
102
+ veo <url> -q 1080p
103
+ veo <url> --audio
104
+ veo <url> -o ./downloads
105
+ veo <url> -r "My Video" --open
106
+ veo <url1> <url2> --subs --embed-metadata
107
+ veo update --check
108
+
109
+ Only download content you are authorized or legally permitted to download.
110
+ `;
111
+
112
+ const STRING_OPTIONS = {
113
+ quality: { short: 'q' },
114
+ output: { short: 'o' },
115
+ rename: { short: 'r' },
116
+ format: {},
117
+ 'playlist-concurrency': {},
118
+ 'concurrent-downloads': {},
119
+ 'filename-template': {},
120
+ 'folder-template': {},
121
+ cookies: {},
122
+ 'cookies-from-browser': {},
123
+ 'concurrent-fragments': { short: 'N' },
124
+ 'sub-langs': {},
125
+ 'sponsorblock-remove': {},
126
+ section: {},
127
+ profile: {},
128
+ 'batch-file': {},
129
+ 'retry-failed': {},
130
+ 'playlist-items': {},
131
+ source: {},
132
+ timeout: {},
133
+ };
134
+
135
+ const BOOLEAN_OPTIONS = {
136
+ compatible: {},
137
+ recode: {},
138
+ 'adaptive-concurrency': {},
139
+ 'check-space': {},
140
+ timings: {},
141
+ color: {},
142
+ open: {},
143
+ audio: {},
144
+ resume: {},
145
+ playlist: {},
146
+ subs: {},
147
+ 'embed-subs': {},
148
+ 'embed-metadata': {},
149
+ 'embed-thumbnail': {},
150
+ 'closest-quality': {},
151
+ 'list-formats': {},
152
+ 'list-sources': {},
153
+ 'auto-list-sources': {},
154
+ 'deep-scan': {},
155
+ 'dry-run': {},
156
+ json: {},
157
+ help: { short: 'h' },
158
+ version: { short: 'v' },
159
+ 'skip-existing': {},
160
+ };
161
+
162
+ // Config defaults, so an explicit flag always wins but a stored preference does not.
163
+ export function optionDefaults(config = {}) {
164
+ return {
165
+ quality: config.quality ?? 'best',
166
+ output: config.output ?? process.cwd(),
167
+ rename: config.rename,
168
+ format: config.format,
169
+ compatible: config.compatible ?? false,
170
+ recode: config.recode ?? false,
171
+ 'concurrent-downloads': String(config.concurrentDownloads ?? 2),
172
+ 'filename-template': config.filenameTemplate,
173
+ 'folder-template': config.folderTemplate,
174
+ 'adaptive-concurrency': config.adaptiveConcurrency ?? true,
175
+ 'check-space': config.checkSpace ?? true,
176
+ timings: config.timings ?? true,
177
+ color: config.color ?? true,
178
+ 'playlist-concurrency': String(config.playlistConcurrency ?? 2),
179
+ cookies: config.cookies,
180
+ 'cookies-from-browser': config.cookiesFromBrowser,
181
+ 'concurrent-fragments': String(config.concurrentFragments ?? 8),
182
+ 'sub-langs': config.subLangs,
183
+ 'sponsorblock-remove': config.sponsorblockRemove,
184
+ section: config.section,
185
+ open: config.open ?? false,
186
+ audio: config.audio ?? false,
187
+ resume: config.resume ?? false,
188
+ playlist: config.playlist ?? false,
189
+ subs: config.subs ?? false,
190
+ 'embed-subs': config.embedSubs ?? false,
191
+ 'embed-metadata': config.embedMetadata ?? false,
192
+ 'embed-thumbnail': config.embedThumbnail ?? false,
193
+ 'closest-quality': config.closestQuality ?? false,
194
+ json: config.json ?? false,
195
+ 'skip-existing': config.skipExisting ?? false,
196
+ 'playlist-items': config.playlistItems,
197
+ source: config.source,
198
+ timeout: config.timeout,
199
+ 'deep-scan': config.deepScan ?? false,
200
+ 'list-sources': config.listSources ?? false,
201
+ 'auto-list-sources': config.autoListSources ?? false,
202
+ };
203
+ }
204
+
187
205
  export function cliOptions(config = {}) {
188
- const defaults = optionDefaults(config);
189
- const options = {};
190
- for (const [name, extra] of Object.entries(STRING_OPTIONS)) {
191
- options[name] = { type: 'string', ...extra };
192
- if (defaults[name] !== undefined) options[name].default = defaults[name];
193
- }
194
- for (const [name, extra] of Object.entries(BOOLEAN_OPTIONS)) {
195
- options[name] = { type: 'boolean', ...extra };
196
- if (defaults[name] !== undefined) options[name].default = defaults[name];
197
- }
198
- return options;
206
+ const defaults = optionDefaults(config);
207
+ const options = {};
208
+ for (const [name, extra] of Object.entries(STRING_OPTIONS)) {
209
+ options[name] = { type: 'string', ...extra };
210
+ if (defaults[name] !== undefined) options[name].default = defaults[name];
211
+ }
212
+ for (const [name, extra] of Object.entries(BOOLEAN_OPTIONS)) {
213
+ options[name] = { type: 'boolean', ...extra };
214
+ if (defaults[name] !== undefined) options[name].default = defaults[name];
215
+ }
216
+ return options;
199
217
  }
200
218
 
201
- export function parseCli(args, { config = {} } = {}) {
202
- if (args[0] === 'help') args = ['--help', ...args.slice(1)];
203
- if (args[0] === 'version') {
204
- if (args.length !== 1) throw new Error('Usage: veo version');
205
- return { version: true };
206
- }
207
- const preliminary = parseArgs({ args, allowPositionals: true, strict: true, allowNegative: true, options: cliOptions() });
208
- config = applyProfile(config, preliminary.values.profile);
209
- const { values, positionals, tokens } = parseArgs({ args, tokens: true, allowNegative: true, allowPositionals: true, strict: true, options: cliOptions(config) });
210
- if (values.help || values.version) return values;
211
- // A stored default conflicting with a flag typed right now is a user error;
212
- // a stored default merely ignored by another flag is not.
213
- const typed = {
214
- quality: tokens.some(token => token.name === 'quality'),
215
- closest: tokens.some(token => token.name === 'closest-quality'),
216
- audio: tokens.some(token => ['audio', 'no-audio'].includes(token.name)),
217
- };
218
- // An explicit numeric --quality states video intent, so it overrides an
219
- // audio-only default instead of turning into a confusing conflict error.
220
- if (typed.quality && values.quality !== 'best' && values.audio && !typed.audio) values.audio = false;
221
- if (!positionals.length && !values['batch-file'] && !values['retry-failed']) throw new Error('Provide at least one video URL. Run veo --help for usage.');
222
- if (!QUALITIES.includes(values.quality) && !/^[1-9]\d{1,4}p$/.test(values.quality)) throw new Error(`Invalid quality. Choose: ${QUALITIES.join(', ')} or a numeric resolution.`);
223
- if (values['playlist-items']) {
224
- if (values.playlist === false && tokens.some(token => token.name === 'playlist')) {
225
- if (tokens.some(token => token.name === 'playlist-items')) throw new Error('--playlist-items cannot be combined with --no-playlist.');
226
- values['playlist-items'] = undefined;
227
- } else { validateItems(values['playlist-items']); values.playlist = true; }
228
- }
229
- if (values['retry-failed'] && (positionals.length || values['batch-file'])) throw new Error('--retry-failed cannot be combined with URLs or --batch-file.');
230
- if (!values.output.trim()) throw new Error('The output directory cannot be empty.');
231
- if (values.rename !== undefined && !cleanText(values.rename)) throw new Error('The custom filename cannot be empty.');
232
- if (positionals.length > 1 && values.rename !== undefined && !values.rename.includes('*')) throw new Error('--rename only applies to a single URL unless the name contains * for the original title.');
233
- if (values.audio && values.quality !== 'best' && typed.quality) throw new Error('--quality is for video; omit it when using --audio.');
234
- if (values.audio && values['closest-quality'] && typed.closest) throw new Error('--closest-quality is for video; omit it when using --audio.');
235
- if (values['closest-quality'] && values.quality === 'best' && typed.closest) throw new Error('--closest-quality requires a numeric --quality such as 1080p.');
236
- if (values['list-formats'] && (values.audio || values.format)) throw new Error('--list-formats cannot be combined with --audio or --format.');
237
- if (values['list-formats'] && positionals.length > 1) throw new Error('--list-formats accepts exactly one URL.');
238
- if (values['concurrent-fragments'] !== undefined) {
239
- const fragments = Number(values['concurrent-fragments']);
240
- if (!Number.isInteger(fragments) || fragments < 1 || fragments > 16) throw new Error('--concurrent-fragments must be a whole number between 1 and 16.');
241
- }
242
- const concurrency = Number(values['playlist-concurrency']);
243
- if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 4) throw new Error('--playlist-concurrency must be a whole number between 1 and 4.');
244
- if (values.compatible && (values.audio || (values.format && values.format !== 'mp4') || values.recode || values['embed-subs'] || values['embed-thumbnail'])) throw new Error('--compatible requires video MP4 without --recode, --embed-subs or --embed-thumbnail.');
245
- if (values.compatible) values.format = 'mp4';
246
- if (values.recode && (!values.format || values.audio)) throw new Error('--recode requires --format and video mode.');
247
- if (values.section && !/^[*\d]/.test(values.section.trim())) throw new Error('--section requires a range such as "*10:00-12:00" or "10:00-12:00".');
248
- if (values['sponsorblock-remove'] && !/^[a-z_,-]+$/i.test(values['sponsorblock-remove'].trim())) throw new Error('--sponsorblock-remove takes comma-separated category names, e.g. "sponsor,selfpromo".');
249
- const formats = values.audio ? AUDIO_FORMATS : VIDEO_FORMATS;
250
- if (values.format && !formats.includes(values.format)) throw new Error(`Invalid ${values.audio ? 'audio' : 'video'} format. Choose: ${formats.join(', ')}.${!values.audio && AUDIO_FORMATS.includes(values.format) ? ' Use --audio for audio formats.' : ''}`);
219
+ const COMMAND_FLAGS = {
220
+ stats: ['--json'], history: ['--json', '--limit', '--failed'],
221
+ runs: ['--json'], stop: [], flush: ['--stats'],
222
+ inspect: ['--json', '--check-audio', '--search'],
223
+ doctor: ['--offline', '--output', '-o'],
224
+ update: ['--check'], up: ['--check'], upgrade: ['--check'], check: ['--check'],
225
+ backend: ['--check', '--keep-files'],
226
+ alias: ['--json', '--force', '--bin-dir'],
227
+ uninstall: ['--prefix', '-p', '--yes', '--keep-cache', '--keep-config', '--keep-aliases', '--json', '--bin-dir'],
228
+ config: ['--profile', '--external', '--terminal'],
229
+ };
230
+ const COMMAND_NAMES = [...Object.keys(COMMAND_FLAGS), 'retry', 'help', 'version'];
251
231
 
252
- const options = {};
253
- for (const [name, value] of Object.entries(values)) {
254
- if (value === undefined) continue;
255
- options[name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())] = value;
232
+ function mistypedCommandOption(args) {
233
+ const command = args[0];
234
+ if (command && !command.startsWith('-') && !COMMAND_NAMES.includes(command)) {
235
+ const suggestion = suggestOption(command, COMMAND_NAMES);
236
+ if (suggestion) return `Unknown command "${command}". Did you mean "${suggestion}"?`;
256
237
  }
257
- options.urls = positionals.map(validateUrl);
258
- options.url = options.urls[0];
259
- if (values.cookies !== undefined) options.cookies = validateCookieFile(values.cookies);
260
- if (values['cookies-from-browser'] !== undefined) options.cookiesFromBrowser = validateBrowserSpec(values['cookies-from-browser']);
261
- if (options.section) options.section = options.section.trim();
262
- if (options.sponsorblockRemove) options.sponsorblockRemove = options.sponsorblockRemove.trim();
263
- if (options.concurrentFragments !== undefined) options.concurrentFragments = Number(options.concurrentFragments);
264
- options.playlistConcurrency = concurrency;
265
- options.concurrentDownloads = Number(values['concurrent-downloads']);
266
- if (!Number.isInteger(options.concurrentDownloads) || options.concurrentDownloads < 1 || options.concurrentDownloads > 4) throw new Error('--concurrent-downloads must be a whole number between 1 and 4.');
267
- if (options.filenameTemplate !== undefined) validateTemplate(options.filenameTemplate);
268
- if (options.folderTemplate !== undefined) validateTemplate(options.folderTemplate, { folders: true });
269
- if (options.rename && options.filenameTemplate) throw new Error('--rename and --filename-template cannot be combined.');
270
- const disableSubs = values.subs === false && tokens.some(token => token.name === 'subs');
271
- if (options.subLangs && !disableSubs) options.subs = true;
272
- if (disableSubs) {
273
- options.subLangs = undefined;
274
- options.embedSubs = false;
238
+ const options = Object.hasOwn(COMMAND_FLAGS, command)
239
+ ? [...COMMAND_FLAGS[command], '--help', '-h', '--no-color', '--color', '--profile']
240
+ : command === 'retry' ? [...optionSpellings(cliOptions()), '--last'] : null;
241
+ if (!options) return null; // Download flags are checked by parseCli itself.
242
+ const start = ['config', 'backend', 'alias'].includes(command) && args[1] && !args[1].startsWith('-') ? 2 : 1;
243
+ for (const arg of args.slice(start)) {
244
+ if (arg === '--') break;
245
+ const name = arg.split('=')[0];
246
+ if (!name.startsWith('-') || options.includes(name)) continue;
247
+ const suggestion = suggestOption(name, options);
248
+ if (suggestion) return `Unknown option "${name}". Did you mean "${suggestion}"?`;
275
249
  }
276
- return options;
250
+ return null;
277
251
  }
278
-
252
+
253
+ export function parseCli(args, { config = {} } = {}) {
254
+ if (args[0] === 'help') args = ['--help', ...args.slice(1)];
255
+ if (args[0] === 'version') {
256
+ if (args.length !== 1) throw new Error('Usage: veo version');
257
+ return { version: true };
258
+ }
259
+ let preliminary;
260
+ try { preliminary = parseArgs({ args, allowPositionals: true, strict: true, allowNegative: true, options: cliOptions() }); }
261
+ catch (error) { throw explainUnknownOption(error, cliOptions()); }
262
+ config = applyProfile(config, preliminary.values.profile);
263
+ let parsed;
264
+ try { parsed = parseArgs({ args, tokens: true, allowNegative: true, allowPositionals: true, strict: true, options: cliOptions(config) }); }
265
+ catch (error) { throw explainUnknownOption(error, cliOptions(config)); }
266
+ const { values, positionals, tokens } = parsed;
267
+ if (values.help || values.version) return values;
268
+ // A stored default conflicting with a flag typed right now is a user error;
269
+ // a stored default merely ignored by another flag is not.
270
+ const typed = {
271
+ quality: tokens.some(token => token.name === 'quality'),
272
+ closest: tokens.some(token => token.name === 'closest-quality'),
273
+ audio: tokens.some(token => ['audio', 'no-audio'].includes(token.name)),
274
+ };
275
+ // An explicit numeric --quality states video intent, so it overrides an
276
+ // audio-only default instead of turning into a confusing conflict error.
277
+ if (typed.quality && values.quality !== 'best' && values.audio && !typed.audio) values.audio = false;
278
+ if (!positionals.length && !values['batch-file'] && !values['retry-failed']) throw new Error('Provide at least one video URL. Run veo --help for usage.');
279
+ if (!QUALITIES.includes(values.quality) && !/^[1-9]\d{1,4}p$/.test(values.quality)) throw new Error(`Invalid quality. Choose: ${QUALITIES.join(', ')} or a numeric resolution.`);
280
+ if (values['playlist-items']) {
281
+ if (values.playlist === false && tokens.some(token => token.name === 'playlist')) {
282
+ if (tokens.some(token => token.name === 'playlist-items')) throw new Error('--playlist-items cannot be combined with --no-playlist.');
283
+ values['playlist-items'] = undefined;
284
+ } else { validateItems(values['playlist-items']); values.playlist = true; }
285
+ }
286
+ if (values['retry-failed'] && (positionals.length || values['batch-file'])) throw new Error('--retry-failed cannot be combined with URLs or --batch-file.');
287
+ if (!values.output.trim()) throw new Error('The output directory cannot be empty.');
288
+ if (values.rename !== undefined && !cleanText(values.rename)) throw new Error('The custom filename cannot be empty.');
289
+ if (positionals.length > 1 && values.rename !== undefined && !values.rename.includes('*')) throw new Error('--rename only applies to a single URL unless the name contains * for the original title.');
290
+ if (values.audio && values.quality !== 'best' && typed.quality) throw new Error('--quality is for video; omit it when using --audio.');
291
+ if (values.audio && values['closest-quality'] && typed.closest) throw new Error('--closest-quality is for video; omit it when using --audio.');
292
+ if (values['closest-quality'] && values.quality === 'best' && typed.closest) throw new Error('--closest-quality requires a numeric --quality such as 1080p.');
293
+ if (values['list-formats'] && (values.audio || values.format)) throw new Error('--list-formats cannot be combined with --audio or --format.');
294
+ if (values['list-formats'] && positionals.length > 1) throw new Error('--list-formats accepts exactly one URL.');
295
+ if (values.source && (!/^[1-9]\d*$/.test(values.source) || !Number.isSafeInteger(Number(values.source)))) throw new Error('--source requires a positive source number.');
296
+ if (values.source && values['list-sources'] && !tokens.some(token => token.name === 'list-sources')) values['list-sources'] = false;
297
+ if (values['list-sources'] && !tokens.some(token => token.name === 'list-sources')
298
+ && (positionals.length !== 1 || values['batch-file'] || values['retry-failed'])) values['list-sources'] = false;
299
+ if (values['list-sources'] && (positionals.length !== 1 || values['batch-file'] || values['retry-failed'])) throw new Error('--list-sources accepts exactly one URL.');
300
+ if (values.source && (positionals.length > 1 || values['batch-file'])) throw new Error('--source accepts exactly one URL.');
301
+ if (values.source && values['list-sources']) throw new Error('--source and --list-sources are separate actions.');
302
+ if (values.timeout) parseSourceTimeout(values.timeout);
303
+ if ((values.source || values['list-sources']) && !tokens.some(token => ['playlist', 'playlist-items'].includes(token.name))) {
304
+ values.playlist = false;
305
+ values['playlist-items'] = undefined;
306
+ }
307
+ if ((values.source || values['list-sources']) && values.playlist) throw new Error('--source and --list-sources cannot be combined with --playlist.');
308
+ if (values['concurrent-fragments'] !== undefined) {
309
+ const fragments = Number(values['concurrent-fragments']);
310
+ if (!Number.isInteger(fragments) || fragments < 1 || fragments > 16) throw new Error('--concurrent-fragments must be a whole number between 1 and 16.');
311
+ }
312
+ const concurrency = Number(values['playlist-concurrency']);
313
+ if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > 4) throw new Error('--playlist-concurrency must be a whole number between 1 and 4.');
314
+ if (values.compatible && (values.audio || (values.format && values.format !== 'mp4') || values.recode || values['embed-subs'] || values['embed-thumbnail'])) throw new Error('--compatible requires video MP4 without --recode, --embed-subs or --embed-thumbnail.');
315
+ if (values.compatible) values.format = 'mp4';
316
+ if (values.recode && (!values.format || values.audio)) throw new Error('--recode requires --format and video mode.');
317
+ if (values.section && !/^[*\d]/.test(values.section.trim())) throw new Error('--section requires a range such as "*10:00-12:00" or "10:00-12:00".');
318
+ if (values['sponsorblock-remove'] && !/^[a-z_,-]+$/i.test(values['sponsorblock-remove'].trim())) throw new Error('--sponsorblock-remove takes comma-separated category names, e.g. "sponsor,selfpromo".');
319
+ const formats = values.audio ? AUDIO_FORMATS : VIDEO_FORMATS;
320
+ if (values.format && !formats.includes(values.format)) throw new Error(`Invalid ${values.audio ? 'audio' : 'video'} format. Choose: ${formats.join(', ')}.${!values.audio && AUDIO_FORMATS.includes(values.format) ? ' Use --audio for audio formats.' : ''}`);
321
+
322
+ const options = {};
323
+ for (const [name, value] of Object.entries(values)) {
324
+ if (value === undefined) continue;
325
+ options[name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())] = value;
326
+ }
327
+ options.urls = positionals.map(validateUrl);
328
+ options.url = options.urls[0];
329
+ if (values.cookies !== undefined) options.cookies = validateCookieFile(values.cookies);
330
+ if (values['cookies-from-browser'] !== undefined) options.cookiesFromBrowser = validateBrowserSpec(values['cookies-from-browser']);
331
+ if (options.section) options.section = options.section.trim();
332
+ if (options.sponsorblockRemove) options.sponsorblockRemove = options.sponsorblockRemove.trim();
333
+ if (options.concurrentFragments !== undefined) options.concurrentFragments = Number(options.concurrentFragments);
334
+ if (options.timeout) options.timeoutMs = parseSourceTimeout(options.timeout);
335
+ options.playlistConcurrency = concurrency;
336
+ options.concurrentDownloads = Number(values['concurrent-downloads']);
337
+ if (!Number.isInteger(options.concurrentDownloads) || options.concurrentDownloads < 1 || options.concurrentDownloads > 4) throw new Error('--concurrent-downloads must be a whole number between 1 and 4.');
338
+ if (options.filenameTemplate !== undefined) validateTemplate(options.filenameTemplate);
339
+ if (options.folderTemplate !== undefined) validateTemplate(options.folderTemplate, { folders: true });
340
+ if (options.rename && options.filenameTemplate) throw new Error('--rename and --filename-template cannot be combined.');
341
+ const disableSubs = values.subs === false && tokens.some(token => token.name === 'subs');
342
+ if (options.subLangs && !disableSubs) options.subs = true;
343
+ if (disableSubs) {
344
+ options.subLangs = undefined;
345
+ options.embedSubs = false;
346
+ }
347
+ return options;
348
+ }
349
+
279
350
  export async function main(args = process.argv.slice(2), { config } = {}) {
280
351
  if (args[0] === 'help') args = ['--help', ...args.slice(1)];
281
- let color = !args.includes('--no-color') && !args.includes('--json');
282
- let display;
283
- try {
284
- display = outputOptions(args);
285
- const loaded = config ?? await loadConfig();
286
- color = !args.includes('--json') && (display.color ?? applyProfile(loaded.config || {}, display.profile).color ?? true);
287
- // Validate explicit profiles even when a color flag overrides their setting.
288
- if (display.profile) applyProfile(loaded.config || {}, display.profile);
289
- } catch (error) {
290
- if (!display || display.profile) {
291
- process.stderr.write(`veo: ${readableError(error)}\n`);
292
- return 1;
293
- }
294
- // The command's own validation reports configuration errors.
295
- }
296
- if (['stats', 'history', 'flush', 'runs', 'inspect', 'stop', 'update', 'up', 'upgrade', 'check', 'doctor', 'backend', 'alias', 'uninstall'].includes(args[0])) args = display.remaining;
297
- const code = await withOutputSettings(color, () => runMain(args, { config }));
298
- // One throttled (once per day) update hint after every successful command.
299
- // Failures, cancellations, help/version output and the update commands
300
- // themselves never trigger it; VEO_NO_UPDATE_CHECK=1 disables it for scripts.
301
- if (code === 0 && shouldUpdateNotice(args)) {
302
- try {
303
- const notice = await maybeUpdateNotice({ currentVersion: await packageVersion() });
304
- if (notice) process.stderr.write(`${notice}\n`);
305
- } catch {
306
- // Informational only: a broken notice must never fail the command.
307
- }
308
- }
309
- return code;
310
- }
311
-
312
- // Help, version and the update commands report versions themselves;
313
- // anything else earns the daily update hint on success.
314
- export function shouldUpdateNotice(args = []) {
315
- if (args.includes('-h') || args.includes('--help') || args.includes('-v') || args.includes('--version')) return false;
316
- if (['update', 'up', 'upgrade', 'check', 'version', 'help'].includes(args[0])) return false;
317
- return true;
318
- }
319
-
320
- async function runMain(args, { config }) {
321
- const stdout = outputStream(process.stdout, { plain: args.includes('--json') });
322
- const stderr = outputStream(process.stderr, { plain: args.includes('--json') });
323
- if (args[0] === 'stats') {
324
- try { return await (await import('./stats.js')).statsMain(args.slice(1)); }
325
- catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
326
- }
327
- if (args[0] === 'history') {
328
- try { return await (await import('./history.js')).historyMain(args.slice(1)); }
329
- catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
330
- }
331
- if (args[0] === 'flush') {
332
- try { return await (await import('./flush.js')).flushMain(args.slice(1)); }
333
- catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
334
- }
335
- if (args[0] === 'runs') {
336
- try { return await (await import('./runs.js')).runsMain(args.slice(1)); }
337
- catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
338
- }
339
- if (args[0] === 'inspect') {
340
- try { return await (await import('./inspect-media.js')).inspectMain(args.slice(1)); }
341
- catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return error.name === 'AbortError' ? 130 : 1; }
342
- }
343
- if (args[0] === 'stop') {
344
- try { return await (await import('./runs.js')).stopMain(args.slice(1)); }
345
- catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
346
- }
347
- if (args[0] === 'retry') {
348
- if (args[1] !== '--last') {
349
- stderr.write('veo: Usage: veo retry --last [download options]\n');
350
- return 1;
351
- }
352
- try {
353
- const { latestFailedJob } = await import('./jobs.js');
354
- args = ['--retry-failed', await latestFailedJob(), ...args.slice(2)];
355
- } catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
356
- }
357
- const { cleanupDownloadCache } = await import('./download-cache.js');
358
- await cleanupDownloadCache().catch(error => stderr.write(`veo: Could not clean expired local downloads: ${readableError(error)}\n`));
359
- // update/upgrade/up/check subcommands are handled before URL validation.
360
- if (['update', 'up', 'upgrade', 'check'].includes(args[0])) {
361
- if (args[0] === 'up') args = ['update', ...args.slice(1)];
362
- if (args[0] === 'check' && args[1] !== 'update') {
363
- stdout.write(UPDATE_HELP);
364
- return 0;
365
- }
366
- return updateMain(args, { registry: defaultRegistry() });
367
- }
368
- if (args[0] === 'config') {
369
- try { return await configMain(args.slice(1)); }
370
- catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
371
- }
372
- if (args[0] === 'doctor') {
373
- try {
374
- const { doctorMain } = await import('./doctor.js');
375
- return await doctorMain(args.slice(1));
376
- } catch (error) {
377
- stderr.write(`veo: ${readableError(error)}\n`);
378
- return 1;
379
- }
380
- }
381
- if (args[0] === 'backend') {
382
- try {
383
- const { backendUpdateMain } = await import('./backend-update.js');
384
- return await backendUpdateMain(args.slice(1));
385
- } catch (error) {
386
- stderr.write(`veo: ${readableError(error)}\n`);
387
- return 1;
388
- }
389
- }
390
- if (args[0] === 'alias') {
391
- try {
392
- const { aliasMain } = await import('./alias.js');
393
- return await aliasMain(args.slice(1));
394
- } catch (error) {
395
- stderr.write(`veo: ${readableError(error)}\n`);
396
- return 1;
397
- }
398
- }
399
- if (args[0] === 'uninstall') {
400
- try {
401
- const { uninstallMain } = await import('./uninstall.js');
402
- return await uninstallMain(args.slice(1));
403
- } catch (error) {
404
- stderr.write(`veo: ${readableError(error)}\n`);
405
- return 1;
406
- }
407
- }
408
- const reporter = createReporter();
409
- const controller = new AbortController();
410
- const cancel = () => controller.abort();
411
- let run;
412
- process.once('SIGINT', cancel);
413
- process.once('SIGTERM', cancel);
414
- try {
415
- if (!args.includes('--help') && !args.includes('-h') && !args.includes('--version')) {
416
- run = await (await import('./runs.js')).registerRun(cancel);
417
- }
418
- const loaded = config ?? await loadConfig();
419
- for (const warning of loaded.warnings || []) stderr.write(`veo: ${warning}\n`);
420
- if (!args.length && process.stdin.isTTY && process.stderr.isTTY) {
421
- const { interactiveArgs } = await import('./interactive.js');
422
- args = await interactiveArgs(loaded.config || {}, { signal: controller.signal });
423
- if (!args) return 0;
424
- }
425
- let options = parseCli(args, { config: loaded.config });
426
- if (options.help) { stdout.write(HELP); return 0; }
427
- if (options.version) {
428
- const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
429
- stdout.write(`${pkg.version}\n`);
430
- return 0;
431
- }
432
- let retryItems;
433
- if (options.retryFailed) {
434
- retryItems = await retryOptions(options.retryFailed);
435
- // Revalidate stored options and apply only flags explicitly supplied now.
436
- const retryArgs = args.filter((arg, index) => arg !== '--retry-failed' && args[index - 1] !== '--retry-failed' && !arg.startsWith('--retry-failed='));
437
- retryItems = retryItems.map(item => parseCli([item.url, ...retryArgs], { config: { ...item, profiles: loaded.config?.profiles } }));
438
- options = { ...retryItems[0], urls: retryItems.map(item => item.url) };
439
- }
440
- if (options.batchFile) {
441
- const lines = (await readFile(options.batchFile, 'utf8')).replace(/^\uFEFF/, '').split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith('#'));
442
- options.urls.push(...lines.map(validateUrl));
443
- options.url = options.urls[0];
444
- if (!options.urls.length) throw new Error('The URL list is empty.');
445
- if (options.rename && options.urls.length > 1 && !options.rename.includes('*')) throw new Error('--rename only applies to a single URL unless the name contains * for the original title.');
446
- if (options.listFormats && options.urls.length > 1) throw new Error('--list-formats accepts exactly one URL.');
447
- }
448
- // The job file is created before the first download, so another terminal can
449
- // follow this run's per-item progress with `veo runs <id>`.
450
- const jobFile = options.listFormats || options.dryRun ? null : jobFilePath();
451
- await run?.describe({ urls: options.urls, output: options.output ? path.resolve(options.output) : null,
452
- audio: options.audio, quality: options.quality, format: options.format, playlist: options.playlist, job: jobFile });
453
- reporter.configure?.({ color: options.color && !options.json });
454
- reporter.start(options.rename);
455
- const cookieWarning = cookieFileWarning(options.cookies);
456
- if (cookieWarning) stderr.write(`veo: ${cookieWarning}\n`);
457
-
458
- if (options.listFormats) {
459
- const { listFormats } = await import('./downloader.js');
460
- stdout.write(await listFormats(options, { signal: controller.signal, reporter }));
461
- return 0;
462
- }
463
- if (options.dryRun) {
464
- const { planDownload } = await import('./downloader.js');
465
- for (const request of retryItems || options.urls.map(url => ({ ...options, url }))) {
466
- const { url } = request;
467
- const plan = await planDownload(request, { signal: controller.signal, reporter });
468
- if (options.json) stdout.write(`${JSON.stringify({ url, status: 'planned', ...plan })}\n`);
469
- else {
470
- stdout.write(`URL: ${url}\n`);
471
- stdout.write(`${describeEstimate(plan)}\n`);
472
- if (plan.quality) stdout.write(`${plan.quality}\n`);
473
- for (const entry of plan.entries) stdout.write(`Would save: ${cleanText(entry.path)}\n`);
474
- }
475
- }
476
- return 0;
477
- }
478
- const { download } = await import('./downloader.js');
479
- const { createStatsRecorder } = await import('./stats.js');
480
- const { createHistoryRecorder } = await import('./history.js');
481
- const result = await runJob(options, { download, reporter, signal: controller.signal, openFile, items: retryItems, jobFile: jobFile || undefined, runId: run?.id, recordStats: createStatsRecorder(), recordHistory: createHistoryRecorder() });
482
- return result;
483
- } catch (error) {
484
- reporter.fail(controller.signal.aborted);
485
- stderr.write(`veo: ${readableError(error)}\n`);
486
- return controller.signal.aborted || error.name === 'AbortError' ? 130 : 1;
487
- } finally {
488
- await run?.unregister();
489
- process.removeListener('SIGINT', cancel);
490
- process.removeListener('SIGTERM', cancel);
491
- }
492
- }
352
+ const mistyped = mistypedCommandOption(args);
353
+ if (mistyped) { process.stderr.write(`veo: ${mistyped}\n`); return 1; }
354
+ let color = !args.includes('--no-color') && !args.includes('--json');
355
+ let display;
356
+ try {
357
+ display = outputOptions(args);
358
+ const loaded = config ?? await loadConfig();
359
+ color = !args.includes('--json') && (display.color ?? applyProfile(loaded.config || {}, display.profile).color ?? true);
360
+ // Validate explicit profiles even when a color flag overrides their setting.
361
+ if (display.profile) applyProfile(loaded.config || {}, display.profile);
362
+ } catch (error) {
363
+ if (!display || display.profile) {
364
+ process.stderr.write(`veo: ${readableError(error)}\n`);
365
+ return 1;
366
+ }
367
+ // The command's own validation reports configuration errors.
368
+ }
369
+ if (['stats', 'history', 'flush', 'runs', 'inspect', 'stop', 'update', 'up', 'upgrade', 'check', 'doctor', 'backend', 'alias', 'uninstall'].includes(args[0])) args = display.remaining;
370
+ const code = await withOutputSettings(color, () => runMain(args, { config }));
371
+ // One throttled (once per day) update hint after every successful command.
372
+ // Failures, cancellations, help/version output and the update commands
373
+ // themselves never trigger it; VEO_NO_UPDATE_CHECK=1 disables it for scripts.
374
+ if (code === 0 && shouldUpdateNotice(args)) {
375
+ try {
376
+ const notice = await maybeUpdateNotice({ currentVersion: await packageVersion() });
377
+ if (notice) process.stderr.write(`${notice}\n`);
378
+ } catch {
379
+ // Informational only: a broken notice must never fail the command.
380
+ }
381
+ }
382
+ return code;
383
+ }
384
+
385
+ // Help, version and the update commands report versions themselves;
386
+ // anything else earns the daily update hint on success.
387
+ export function shouldUpdateNotice(args = []) {
388
+ if (args.includes('-h') || args.includes('--help') || args.includes('-v') || args.includes('--version')) return false;
389
+ if (['update', 'up', 'upgrade', 'check', 'version', 'help'].includes(args[0])) return false;
390
+ return true;
391
+ }
392
+
393
+ async function runMain(args, { config }) {
394
+ const stdout = outputStream(process.stdout, { plain: args.includes('--json') });
395
+ const stderr = outputStream(process.stderr, { plain: args.includes('--json') });
396
+ if (args[0] === 'stats') {
397
+ try { return await (await import('./stats.js')).statsMain(args.slice(1)); }
398
+ catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
399
+ }
400
+ if (args[0] === 'history') {
401
+ try { return await (await import('./history.js')).historyMain(args.slice(1)); }
402
+ catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
403
+ }
404
+ if (args[0] === 'flush') {
405
+ try { return await (await import('./flush.js')).flushMain(args.slice(1)); }
406
+ catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
407
+ }
408
+ if (args[0] === 'runs') {
409
+ try { return await (await import('./runs.js')).runsMain(args.slice(1)); }
410
+ catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
411
+ }
412
+ if (args[0] === 'inspect') {
413
+ try { return await (await import('./inspect-media.js')).inspectMain(args.slice(1)); }
414
+ catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return error.name === 'AbortError' ? 130 : 1; }
415
+ }
416
+ if (args[0] === 'stop') {
417
+ try { return await (await import('./runs.js')).stopMain(args.slice(1)); }
418
+ catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
419
+ }
420
+ if (args[0] === 'retry') {
421
+ if (args[1] !== '--last') {
422
+ stderr.write('veo: Usage: veo retry --last [download options]\n');
423
+ return 1;
424
+ }
425
+ try {
426
+ const { latestFailedJob } = await import('./jobs.js');
427
+ args = ['--retry-failed', await latestFailedJob(), ...args.slice(2)];
428
+ } catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
429
+ }
430
+ const { cleanupDownloadCache } = await import('./download-cache.js');
431
+ await cleanupDownloadCache().catch(error => stderr.write(`veo: Could not clean expired local downloads: ${readableError(error)}\n`));
432
+ // update/upgrade/up/check subcommands are handled before URL validation.
433
+ if (['update', 'up', 'upgrade', 'check'].includes(args[0])) {
434
+ if (args[0] === 'up') args = ['update', ...args.slice(1)];
435
+ if (args[0] === 'check' && args[1] !== 'update') {
436
+ stdout.write(UPDATE_HELP);
437
+ return 0;
438
+ }
439
+ return updateMain(args, { registry: defaultRegistry() });
440
+ }
441
+ if (args[0] === 'config') {
442
+ try { return await configMain(args.slice(1)); }
443
+ catch (error) { stderr.write(`veo: ${readableError(error)}\n`); return 1; }
444
+ }
445
+ if (args[0] === 'doctor') {
446
+ try {
447
+ const { doctorMain } = await import('./doctor.js');
448
+ return await doctorMain(args.slice(1));
449
+ } catch (error) {
450
+ stderr.write(`veo: ${readableError(error)}\n`);
451
+ return 1;
452
+ }
453
+ }
454
+ if (args[0] === 'backend') {
455
+ try {
456
+ const { backendUpdateMain } = await import('./backend-update.js');
457
+ return await backendUpdateMain(args.slice(1));
458
+ } catch (error) {
459
+ stderr.write(`veo: ${readableError(error)}\n`);
460
+ return 1;
461
+ }
462
+ }
463
+ if (args[0] === 'alias') {
464
+ try {
465
+ const { aliasMain } = await import('./alias.js');
466
+ return await aliasMain(args.slice(1));
467
+ } catch (error) {
468
+ stderr.write(`veo: ${readableError(error)}\n`);
469
+ return 1;
470
+ }
471
+ }
472
+ if (args[0] === 'uninstall') {
473
+ try {
474
+ const { uninstallMain } = await import('./uninstall.js');
475
+ return await uninstallMain(args.slice(1));
476
+ } catch (error) {
477
+ stderr.write(`veo: ${readableError(error)}\n`);
478
+ return 1;
479
+ }
480
+ }
481
+ const reporter = createReporter();
482
+ const controller = new AbortController();
483
+ const cancel = () => controller.abort();
484
+ let run;
485
+ process.once('SIGINT', cancel);
486
+ process.once('SIGTERM', cancel);
487
+ try {
488
+ if (!args.includes('--help') && !args.includes('-h') && !args.includes('--version')) {
489
+ run = await (await import('./runs.js')).registerRun(cancel);
490
+ }
491
+ const loaded = config ?? await loadConfig();
492
+ for (const warning of loaded.warnings || []) stderr.write(`veo: ${warning}\n`);
493
+ if (!args.length && process.stdin.isTTY && process.stderr.isTTY) {
494
+ const { interactiveArgs } = await import('./interactive.js');
495
+ args = await interactiveArgs(loaded.config || {}, { signal: controller.signal });
496
+ if (!args) return 0;
497
+ }
498
+ let options = parseCli(args, { config: loaded.config });
499
+ if (options.help) { stdout.write(HELP); return 0; }
500
+ if (options.version) {
501
+ const pkg = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8'));
502
+ stdout.write(`${pkg.version}\n`);
503
+ return 0;
504
+ }
505
+ let retryItems;
506
+ if (options.retryFailed) {
507
+ retryItems = await retryOptions(options.retryFailed);
508
+ // Revalidate stored options and apply only flags explicitly supplied now.
509
+ const retryArgs = args.filter((arg, index) => arg !== '--retry-failed' && args[index - 1] !== '--retry-failed' && !arg.startsWith('--retry-failed='));
510
+ retryItems = retryItems.map(item => parseCli([item.url, ...retryArgs], { config: { ...item, profiles: loaded.config?.profiles } }));
511
+ options = { ...retryItems[0], urls: retryItems.map(item => item.url) };
512
+ }
513
+ if (options.batchFile) {
514
+ const lines = (await readFile(options.batchFile, 'utf8')).replace(/^\uFEFF/, '').split(/\r?\n/).map(line => line.trim()).filter(line => line && !line.startsWith('#'));
515
+ options.urls.push(...lines.map(validateUrl));
516
+ options.url = options.urls[0];
517
+ if (!options.urls.length) throw new Error('The URL list is empty.');
518
+ if (options.rename && options.urls.length > 1 && !options.rename.includes('*')) throw new Error('--rename only applies to a single URL unless the name contains * for the original title.');
519
+ if (options.listFormats && options.urls.length > 1) throw new Error('--list-formats accepts exactly one URL.');
520
+ }
521
+ // The job file is created before the first download, so another terminal can
522
+ // follow this run's per-item progress with `veo runs <id>`.
523
+ const jobFile = options.listFormats || options.listSources || options.dryRun ? null : jobFilePath();
524
+ await run?.describe({ urls: options.urls, output: options.output ? path.resolve(options.output) : null,
525
+ audio: options.audio, quality: options.quality, format: options.format, playlist: options.playlist, job: jobFile });
526
+ reporter.configure?.({ color: options.color && !options.json });
527
+ reporter.start(options.rename);
528
+ const cookieWarning = cookieFileWarning(options.cookies);
529
+ if (cookieWarning) stderr.write(`veo: ${cookieWarning}\n`);
530
+
531
+ // For a single page, fall back to media requests observed while its player loads.
532
+ // Explicit --source always rediscovers: signed media URLs can expire between runs.
533
+ if (!retryItems && options.urls.length === 1 && (!options.playlist || options.listSources)) {
534
+ const discovery = await resolvePageSource(options, { signal: controller.signal, stderr });
535
+ if (options.listSources) {
536
+ if (options.json) stdout.write(`${JSON.stringify({ url: options.url, status: 'sources', timedOut: Boolean(discovery.sources.timedOut), sources: discovery.sources.map(({ url, pageUrl, ...safe }) => safe) })}\n`);
537
+ else for (const source of discovery.sources) stdout.write(`${discovery.formatSource(source)}\n`);
538
+ if (discovery.sources.timedOut) stderr.write(`veo: Source search timed out after ${options.timeout || (options.deepScan ? '120s' : '45s')}; showing verified sources found so far.\n`);
539
+ if (!discovery.sources.length) stderr.write(discovery.sources.timedOut
540
+ ? 'veo: No sources were verified before the timeout.\n'
541
+ : 'veo: No downloadable sources were found on this page.\n');
542
+ return discovery.sources.length && !discovery.sources.timedOut ? 0 : 1;
543
+ }
544
+ if (discovery.needsSelection) {
545
+ if (options.json) stdout.write(`${JSON.stringify({ url: options.url, status: 'sources', timedOut: Boolean(discovery.sources.timedOut), sources: discovery.sources.map(({ url, pageUrl, ...safe }) => safe) })}\n`);
546
+ else for (const source of discovery.sources) stdout.write(`${discovery.formatSource(source)}\n`);
547
+ stderr.write('veo: Select a source with --source <number>.\n');
548
+ return 1;
549
+ }
550
+ if (discovery.mediaUrl) {
551
+ options.mediaUrl = discovery.mediaUrl;
552
+ options.source = String(discovery.source);
553
+ }
554
+ }
555
+ if (retryItems) for (const item of retryItems) {
556
+ if (!item.source) continue;
557
+ const discovery = await resolvePageSource(item, { signal: controller.signal, stderr });
558
+ item.mediaUrl = discovery.mediaUrl;
559
+ }
560
+
561
+ if (options.listFormats) {
562
+ const { listFormats } = await import('./downloader.js');
563
+ stdout.write(await listFormats(options, { signal: controller.signal, reporter }));
564
+ return 0;
565
+ }
566
+ if (options.dryRun) {
567
+ const { planDownload } = await import('./downloader.js');
568
+ for (const request of retryItems || options.urls.map(url => ({ ...options, url }))) {
569
+ const { url } = request;
570
+ const plan = await planDownload(request, { signal: controller.signal, reporter });
571
+ if (options.json) stdout.write(`${JSON.stringify({ url, status: 'planned', ...plan })}\n`);
572
+ else {
573
+ stdout.write(`URL: ${url}\n`);
574
+ stdout.write(`${describeEstimate(plan)}\n`);
575
+ if (plan.quality) stdout.write(`${plan.quality}\n`);
576
+ for (const entry of plan.entries) stdout.write(`Would save: ${cleanText(entry.path)}\n`);
577
+ }
578
+ }
579
+ return 0;
580
+ }
581
+ const { download } = await import('./downloader.js');
582
+ const { createStatsRecorder } = await import('./stats.js');
583
+ const { createHistoryRecorder } = await import('./history.js');
584
+ const result = await runJob(options, { download, reporter, signal: controller.signal, openFile, items: retryItems, jobFile: jobFile || undefined, runId: run?.id, recordStats: createStatsRecorder(), recordHistory: createHistoryRecorder() });
585
+ return result;
586
+ } catch (error) {
587
+ reporter.fail(controller.signal.aborted);
588
+ stderr.write(`veo: ${readableError(error)}\n`);
589
+ return controller.signal.aborted || error.name === 'AbortError' ? 130 : 1;
590
+ } finally {
591
+ await run?.unregister();
592
+ process.removeListener('SIGINT', cancel);
593
+ process.removeListener('SIGTERM', cancel);
594
+ }
595
+ }
596
+
597
+ async function askSourceQuestion(prompt, signal) {
598
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
599
+ try { return await rl.question(prompt, { signal }); }
600
+ finally { rl.close(); }
601
+ }
602
+
603
+ export async function resolvePageSource(options, { signal, stderr, inspect, discover, ask = askSourceQuestion,
604
+ backendResolver, interactive = Boolean(process.stdin.isTTY && process.stderr.isTTY && !options.json) }) {
605
+ const { fetchMetadata, prepareBackend, runBackend } = await import('./downloader.js');
606
+ const { discoverSources, formatSource, shouldOfferSourceDiscovery } = await import('./source-discovery.js');
607
+ const backend = inspect ? null : await (backendResolver || prepareBackend)(options, { signal });
608
+ const inspectMedia = (request, requestSignal = signal) => inspect ? inspect(request, requestSignal) : fetchMetadata(request, { signal: requestSignal, backend, runner: runBackend });
609
+ let originalError;
610
+ if (!options.source && !options.listSources) {
611
+ try {
612
+ const metadata = await inspectMedia(options);
613
+ if (!metadata.entries?.length && !metadata.formats?.length && !metadata.url) {
614
+ throw new Error('No downloadable video formats found.');
615
+ }
616
+ return {};
617
+ }
618
+ catch (error) { originalError = error; }
619
+ if (!shouldOfferSourceDiscovery(originalError)) throw originalError;
620
+ if (!interactive && !options.autoListSources) throw new Error(`${originalError.message} Use --list-sources to search this page, then --source <number> to select one.`);
621
+ if (interactive && !options.autoListSources) {
622
+ const answer = (await ask('No downloadable video found. Search this page for other sources? (y/N): ', signal)).trim().toLowerCase();
623
+ if (!['y', 'yes'].includes(answer)) throw originalError;
624
+ }
625
+ }
626
+ let sources;
627
+ try {
628
+ sources = await (discover || discoverSources)(options.url, {
629
+ signal, deepScan: options.deepScan, timeoutMs: options.timeoutMs,
630
+ inspect: (url, _page, { signal: scanSignal } = {}) => inspectMedia({ ...options, mediaUrl: url }, scanSignal),
631
+ });
632
+ } catch (error) {
633
+ if (signal?.aborted || error?.name === 'AbortError') throw error;
634
+ if (originalError) throw new Error(`${originalError.message} Source discovery also failed: ${error.message}`);
635
+ throw error;
636
+ }
637
+ if (options.listSources) return { sources, formatSource };
638
+ if (sources.timedOut) stderr.write(`veo: Source search timed out after ${options.timeout || (options.deepScan ? '120s' : '45s')}; showing verified sources found so far.\n`);
639
+ if (!sources.length) {
640
+ if (originalError) throw originalError;
641
+ throw new Error('No downloadable video sources were found on this page.');
642
+ }
643
+ let index = Number(options.source);
644
+ if (!index) {
645
+ if (!interactive && options.autoListSources) return { sources, formatSource, needsSelection: true };
646
+ for (const source of sources) stderr.write(`${formatSource(source)}\n`);
647
+ if (!interactive) throw new Error('Select a source with --source <number>.');
648
+ const answer = await ask('Source number (Enter to cancel): ', signal);
649
+ if (!/^[1-9]\d*$/.test(answer.trim())) throw new Error('No source selected.');
650
+ index = Number(answer.trim());
651
+ }
652
+ const selected = sources[index - 1];
653
+ if (!selected) throw new Error(`Source ${index} does not exist; choose 1-${sources.length}.`);
654
+ return { mediaUrl: selected.url, source: index };
655
+ }