dsh-harness-toolbox 1.6.4 → 1.8.8

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.
@@ -0,0 +1,384 @@
1
+ import { chmodSync, cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, rmdirSync, statSync } from 'node:fs'
2
+
3
+ import { join } from 'node:path'
4
+ import { downloadWithResume, extractArchive, runCommand } from './gh.js'
5
+ import { moveIntoPlace } from './swap.js'
6
+
7
+ /**
8
+ * Managed components beyond `gh` and ffmpeg: git and Python.
9
+ *
10
+ * Both install a whole extracted tree below the shared download root, next to
11
+ * `<root>/gh` and `<root>/ffmpeg`, so one configured `toolsPath` covers every
12
+ * managed binary:
13
+ *
14
+ * <root>/git MinGit zip binary <root>/git/cmd/git.exe
15
+ * <root>/python python-build-* binary <root>/python/python.exe
16
+ *
17
+ * Versions are pinned here together with the exact release asset; the probe
18
+ * after extraction is what makes a broken or truncated archive fail before it
19
+ * replaces a working install.
20
+ */
21
+
22
+ const DOWNLOAD_TIMEOUT_MS = 20 * 60_000
23
+ const VERIFY_TIMEOUT_MS = 30_000
24
+
25
+ const GIT_VERSION = '2.56.1'
26
+ const GIT_TAG = `v${GIT_VERSION}.windows.1`
27
+ const GIT_RELEASE = `https://github.com/git-for-windows/git/releases/download/${GIT_TAG}`
28
+
29
+ const PYTHON_VERSION = '3.11.18'
30
+ const PYTHON_TAG = '20261110'
31
+ const PYTHON_RELEASE = `https://github.com/astral-sh/python-build-standalone/releases/download/${PYTHON_TAG}`
32
+ const PYTHON_ASSET = `cpython-${PYTHON_VERSION}+${PYTHON_TAG}-x86_64-pc-windows-msvc-install_only.tar.gz`
33
+
34
+ /**
35
+ * One entry per component. `binary` is relative to the installed tree and is
36
+ * what the post-install probe runs; `binDirs` are the directories that go on
37
+ * PATH (`.` means the install root itself).
38
+ */
39
+ export const COMPONENTS = {
40
+ git: {
41
+ id: 'git',
42
+ name: 'git',
43
+ version: GIT_VERSION,
44
+ source: 'https://git-scm.com/',
45
+ assets: {
46
+ 'win32-x64': { url: `${GIT_RELEASE}/MinGit-${GIT_VERSION}-64-bit.zip`, file: `MinGit-${GIT_VERSION}-64-bit.zip`, kind: 'zip' },
47
+ 'win32-arm64': { url: `${GIT_RELEASE}/MinGit-${GIT_VERSION}-arm64.zip`, file: `MinGit-${GIT_VERSION}-arm64.zip`, kind: 'zip' },
48
+ },
49
+ binary: join('cmd', 'git.exe'),
50
+ binDirs: ['cmd'],
51
+ args: ['--version'],
52
+ versionPattern: /git version (\S+)/i,
53
+ },
54
+ python: {
55
+ id: 'python',
56
+ name: 'Python',
57
+ version: PYTHON_VERSION,
58
+ source: 'https://github.com/astral-sh/python-build-standalone',
59
+ assets: {
60
+ 'win32-x64': {
61
+ // The `+` of the release file name must stay percent-encoded in the URL.
62
+ url: `${PYTHON_RELEASE}/${PYTHON_ASSET.replace('+', '%2B')}`,
63
+ file: PYTHON_ASSET,
64
+ kind: 'tar.gz',
65
+ },
66
+ },
67
+ // The archive carries one top-level `python/` directory.
68
+ subdir: 'python',
69
+ binary: 'python.exe',
70
+ binDirs: ['.', 'Scripts'],
71
+ args: ['--version'],
72
+ versionPattern: /Python (\d+\.\d+\.\d+)/i,
73
+ },
74
+ }
75
+
76
+ export const COMPONENT_IDS = Object.keys(COMPONENTS)
77
+
78
+ export function componentSpec(id) {
79
+ return COMPONENTS[id] || null
80
+ }
81
+
82
+ export function componentRoot(root, id) {
83
+ return join(root, id)
84
+ }
85
+
86
+ /** The release asset for this platform, or null when there is no managed build. */
87
+ export function componentAsset(id, platform = process.platform, arch = process.arch) {
88
+ const spec = componentSpec(id)
89
+ if (!spec) return null
90
+ const asset = spec.assets[`${platform}-${arch}`]
91
+ return asset ? { ...asset } : null
92
+ }
93
+
94
+ /** The managed binary's path (independent of whether it exists yet). */
95
+ export function componentBinaryPath(root, id) {
96
+ const spec = componentSpec(id)
97
+ if (!spec) return null
98
+ return join(componentRoot(root, id), spec.binary)
99
+ }
100
+
101
+ /** Directories to put on PATH for this component. */
102
+ export function componentBinDirs(root, id) {
103
+ const spec = componentSpec(id)
104
+ if (!spec) return []
105
+ return spec.binDirs.map((dir) => (dir === '.' ? componentRoot(root, id) : join(componentRoot(root, id), dir)))
106
+ }
107
+
108
+ /** First `file` on PATH, without running anything. */
109
+ export function systemComponentFile(file, platform = process.platform, envPath = process.env.PATH) {
110
+ const separator = platform === 'win32' ? ';' : ':'
111
+ for (const dir of String(envPath || '').split(separator)) {
112
+ if (!dir) continue
113
+ const candidate = join(dir, file)
114
+ try {
115
+ if (existsSync(candidate) && statSync(candidate).isFile()) return candidate
116
+ } catch {
117
+ // An unreadable PATH entry is not a candidate.
118
+ }
119
+ }
120
+ return null
121
+ }
122
+
123
+ /** `git version 2.56.1.windows.1` / `Python 3.11.18` → the version, or null. */
124
+ export function parseComponentVersion(id, output) {
125
+ const spec = componentSpec(id)
126
+ if (!spec) return null
127
+ return spec.versionPattern.exec(String(output || ''))?.[1] || null
128
+ }
129
+
130
+ const versionCache = new Map()
131
+
132
+ async function probeVersion(path, spec, run) {
133
+ let stamp
134
+ try {
135
+ const info = statSync(path)
136
+ stamp = `${info.size}:${info.mtimeMs}`
137
+ } catch {
138
+ return null
139
+ }
140
+ const key = `${path}:${spec.id}`
141
+ const cached = versionCache.get(key)
142
+ if (cached && cached.stamp === stamp) return cached.version
143
+ const result = await run(path, spec.args, { timeoutMs: VERIFY_TIMEOUT_MS })
144
+ if (result.code !== 0) return null
145
+ const version = parseComponentVersion(spec.id, `${result.stdout}${result.stderr}`)
146
+ versionCache.set(key, { stamp, version })
147
+ return version
148
+ }
149
+
150
+ const jobs = new Map()
151
+
152
+ function jobKey(root, id) {
153
+ return `${root}::${id}`
154
+ }
155
+
156
+ /** The `.part` file a resumed download continues from. */
157
+ function partPath(root, id, asset) {
158
+ return join(componentRoot(root, id), 'download', `${asset.file}.part`)
159
+ }
160
+
161
+ /** Whether an install for this component is in flight. */
162
+ export function componentDownloadRunning(root, id) {
163
+ return jobs.get(jobKey(root, id))?.running === true
164
+ }
165
+
166
+ /**
167
+ * What the settings page shows for one component: managed or PATH copy, its
168
+ * version, and the state of the last managed download.
169
+ */
170
+ export async function componentStatus(root, id, { platform = process.platform, arch = process.arch, envPath = process.env.PATH, run = runCommand } = {}) {
171
+ const spec = componentSpec(id)
172
+ if (!spec) throw new Error(`unknown component: ${id}`)
173
+ const asset = componentAsset(id, platform, arch)
174
+ const job = jobs.get(jobKey(root, id)) || null
175
+ const managed = componentBinaryPath(root, id)
176
+ const hasManaged = existsSync(managed)
177
+ // A failed job keeps the component "not installed" even if a binary is still
178
+ // on disk, so the page offers a retry instead of a broken install.
179
+ const installed = hasManaged && !job?.error
180
+ const system = installed ? null : systemComponentFile(spec.binary.split(/[\\/]/).pop(), platform, envPath)
181
+ const version = installed
182
+ ? await probeVersion(managed, spec, run)
183
+ : system ? await probeVersion(system, spec, run) : null
184
+ const partBytes = asset && existsSync(partPath(root, id, asset)) ? statSync(partPath(root, id, asset)).size : 0
185
+ let state = 'missing'
186
+ if (job?.running) state = 'downloading'
187
+ else if (installed) state = 'installed'
188
+ else if (job?.error) state = 'error'
189
+ else if (system) state = 'system'
190
+ else if (partBytes > 0) state = 'partial'
191
+ const received = job?.running ? job.received : partBytes
192
+ const total = job?.running ? job.total ?? null : null
193
+ return {
194
+ id,
195
+ name: spec.name,
196
+ version: spec.version,
197
+ source: spec.source,
198
+ supported: Boolean(asset),
199
+ url: asset?.url || null,
200
+ file: asset?.file || null,
201
+ state,
202
+ installed,
203
+ system: system !== null,
204
+ systemPath: system,
205
+ binaryPath: installed ? managed : system,
206
+ sourceKind: installed ? 'managed' : system ? 'system' : null,
207
+ toolVersion: version,
208
+ received,
209
+ total,
210
+ percent: total ? Math.min(100, Math.round((received / total) * 100)) : null,
211
+ error: job?.error || null,
212
+ installDir: componentRoot(root, id),
213
+ }
214
+ }
215
+
216
+ /** Put the component's directories first on PATH; true when the binary exists. */
217
+ export function prependComponentPath(root, id, platform = process.platform) {
218
+ const spec = componentSpec(id)
219
+ if (!spec) return false
220
+ const binary = componentBinaryPath(root, id)
221
+ if (!existsSync(binary)) return false
222
+ const separator = platform === 'win32' ? ';' : ':'
223
+ const current = String(process.env.PATH || '')
224
+ const parts = current.split(separator)
225
+ const dirs = componentBinDirs(root, id).filter((dir) => !parts.includes(dir))
226
+ if (dirs.length === 0) return true
227
+ process.env.PATH = [...dirs, ...parts].join(separator)
228
+ return true
229
+ }
230
+
231
+ /**
232
+ * Where an install unpacks and stages a tree. This must sit beside the
233
+ * component directory, never inside it: the last step renames the staged tree
234
+ * onto `<root>/<id>`, which cannot work while the tree lives below it.
235
+ */
236
+ function stagingRoot(root, id) {
237
+ return join(root, '.staging', id)
238
+ }
239
+
240
+ /** Drop what an install needed; a `.part` file is kept until it succeeds. */
241
+ function prune(root, id) {
242
+ for (const path of [stagingRoot(root, id), join(componentRoot(root, id), 'download')]) {
243
+ try {
244
+ if (existsSync(path)) rmSync(path, { recursive: true, force: true })
245
+ } catch {
246
+ // Leftovers are harmless; the next install overwrites them.
247
+ }
248
+ }
249
+ // Drop the empty `.staging` parent as well, but never a directory still
250
+ // holding another component's half-finished install.
251
+ try {
252
+ const parent = join(root, '.staging')
253
+ if (existsSync(parent) && readdirSync(parent).length === 0) rmdirSync(parent)
254
+ } catch {
255
+ // An empty parent directory is harmless.
256
+ }
257
+ }
258
+
259
+ /**
260
+ * Move the staged tree into place and probe the installed binary. The previous
261
+ * install is kept until the probe passes, then dropped; on failure it is
262
+ * restored, so an install either fully replaces the component or changes
263
+ * nothing. Both renames go through `moveIntoPlace`: Windows reports a tree that
264
+ * is still being scanned (or whose probe process has not fully exited) as
265
+ * `EPERM`, so the swap retries and finally copies instead of failing.
266
+ */
267
+ async function swapTree(finalDir, stagedDir, spec, platform, run) {
268
+ const backup = `${finalDir}.old-${process.pid}-${Date.now()}`
269
+ let moved = false
270
+ try {
271
+ if (existsSync(finalDir)) await moveIntoPlace(finalDir, backup)
272
+ await moveIntoPlace(stagedDir, finalDir)
273
+ moved = true
274
+ const binary = join(finalDir, spec.binary)
275
+ const check = await run(binary, spec.args, { timeoutMs: VERIFY_TIMEOUT_MS })
276
+ if (check.code !== 0) {
277
+ const detail = `${check.stderr}${check.stdout}`.trim().slice(-300)
278
+ throw new Error(`${spec.name} failed its probe after install: ${detail || `exit ${check.code}`}`)
279
+ }
280
+ if (platform !== 'win32') {
281
+ try {
282
+ chmodSync(binary, 0o755)
283
+ } catch {
284
+ // Already executable; the probe above is the real check.
285
+ }
286
+ }
287
+ if (existsSync(backup)) rmSync(backup, { recursive: true, force: true })
288
+ } catch (error) {
289
+ try {
290
+ if (moved && existsSync(finalDir)) rmSync(finalDir, { recursive: true, force: true })
291
+ } catch {
292
+ // Keep restoring the old tree even if the new one is locked.
293
+ }
294
+ try {
295
+ if (existsSync(backup)) await moveIntoPlace(backup, finalDir)
296
+ } catch {
297
+ // Best effort; the caller still reports the install error.
298
+ }
299
+ throw error
300
+ }
301
+ }
302
+
303
+ /**
304
+ * Download, extract and install one component in the background; the page
305
+ * polls {@link componentStatus} for progress. Returns that status at once.
306
+ */
307
+ export async function startComponentDownload(root, id, { platform = process.platform, arch = process.arch, run = runCommand } = {}) {
308
+ const spec = componentSpec(id)
309
+ if (!spec) throw new Error(`unknown component: ${id}`)
310
+ const asset = componentAsset(id, platform, arch)
311
+ if (!asset) throw new Error(`${spec.name} has no managed build for ${platform}/${arch}`)
312
+ const key = jobKey(root, id)
313
+ if (jobs.get(key)?.running) return componentStatus(root, id, { platform, arch })
314
+ const job = { running: true, received: 0, total: null, error: null }
315
+ jobs.set(key, job)
316
+ const dir = componentRoot(root, id)
317
+ const part = partPath(root, id, asset)
318
+ const controller = new AbortController()
319
+ let timedOut = false
320
+ const timer = setTimeout(() => {
321
+ timedOut = true
322
+ controller.abort(new Error('download timed out after 20 minutes'))
323
+ }, DOWNLOAD_TIMEOUT_MS)
324
+ if (typeof timer.unref === 'function') timer.unref()
325
+
326
+ void (async () => {
327
+ const downloadDir = join(dir, 'download')
328
+ mkdirSync(downloadDir, { recursive: true })
329
+ const archive = join(downloadDir, asset.file)
330
+ // A finished download is what puts the archive there, so a retry after a
331
+ // failed install reuses it instead of downloading the release again.
332
+ if (!existsSync(archive)) {
333
+ await downloadWithResume({
334
+ url: asset.url,
335
+ partPath: part,
336
+ signal: controller.signal,
337
+ onProgress: (progress) => {
338
+ job.received = progress.received
339
+ job.total = progress.total
340
+ },
341
+ })
342
+ await moveIntoPlace(part, archive)
343
+ }
344
+ const staging = stagingRoot(root, id)
345
+ rmSync(staging, { recursive: true, force: true })
346
+ const unpacked = join(staging, 'unpacked')
347
+ await extractArchive(archive, unpacked, asset.kind, platform)
348
+ const tree = spec.subdir ? join(unpacked, spec.subdir) : unpacked
349
+ if (!existsSync(join(tree, spec.binary))) {
350
+ throw new Error(`the archive did not contain ${spec.binary}`)
351
+ }
352
+ // Probe the staged copy first: a broken binary must never replace a working one.
353
+ const stagedCheck = await run(join(tree, spec.binary), spec.args, { timeoutMs: VERIFY_TIMEOUT_MS })
354
+ if (platform !== 'win32') {
355
+ try {
356
+ chmodSync(join(tree, spec.binary), 0o755)
357
+ } catch {
358
+ // Non-fatal; the probe already ran.
359
+ }
360
+ }
361
+ if (stagedCheck.code !== 0) {
362
+ const detail = `${stagedCheck.stderr}${stagedCheck.stdout}`.trim().slice(-300)
363
+ throw new Error(`${spec.name} staged probe failed: ${detail || `exit ${stagedCheck.code}`}`)
364
+ }
365
+ const staged = join(staging, 'tree')
366
+ if (spec.subdir) {
367
+ cpSync(tree, staged, { recursive: true })
368
+ rmSync(unpacked, { recursive: true, force: true })
369
+ } else {
370
+ await moveIntoPlace(unpacked, staged)
371
+ }
372
+ await swapTree(dir, staged, spec, platform, run)
373
+ prune(root, id)
374
+ prependComponentPath(root, id, platform)
375
+ })().catch((error) => {
376
+ job.error = timedOut
377
+ ? 'download timed out after 20 minutes; the partial file was kept for resume'
378
+ : error instanceof Error ? error.message : String(error)
379
+ }).finally(() => {
380
+ clearTimeout(timer)
381
+ job.running = false
382
+ })
383
+ return componentStatus(root, id, { platform, arch })
384
+ }
package/src/ffmpeg.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { chmodSync, copyFileSync, existsSync, mkdirSync, renameSync, rmSync, statSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
  import { downloadWithResume, extractArchive, findBinary, runCommand } from './gh.js'
4
+ import { moveIntoPlace } from './swap.js'
4
5
 
5
6
  /**
6
7
  * Managed ffmpeg + ffprobe, next to the managed `gh`.
@@ -8,9 +9,9 @@ import { downloadWithResume, extractArchive, findBinary, runCommand } from './gh
8
9
  * The tools are wanted by video work (ffprobe reads durations and codecs,
9
10
  * ffmpeg cuts and transcodes), but a "please install ffmpeg and add it to PATH"
10
11
  * note costs more time than the install. This module detects a PATH copy, keeps
11
- * a managed copy in `<DSH home>/compression-tiers/ffmpeg/bin`, and downloads the
12
- * release build with HTTP Range resume so an interrupted 110 MB download
13
- * continues instead of restarting.
12
+ * a managed copy in `<toolsPath>/ffmpeg/bin` next to the managed `gh`, and
13
+ * downloads the release build with HTTP Range resume so an interrupted 110 MB
14
+ * download continues instead of restarting.
14
15
  *
15
16
  * The archive is a floating "release essentials" build rather than a pinned
16
17
  * version: gyan.dev only serves the current release at a stable URL, so the
@@ -32,13 +33,13 @@ const SOURCES = {
32
33
  },
33
34
  }
34
35
 
35
- /** Where managed copies, downloads and the extracted tree live. */
36
- export function ffmpegRoot(home) {
37
- return join(home, 'compression-tiers', 'ffmpeg')
36
+ /** `<toolsPath>/ffmpeg`: the managed component's own directory. */
37
+ export function ffmpegRoot(root) {
38
+ return join(root, 'ffmpeg')
38
39
  }
39
40
 
40
- export function ffmpegBinDir(home) {
41
- return join(ffmpegRoot(home), 'bin')
41
+ export function ffmpegBinDir(root) {
42
+ return join(ffmpegRoot(root), 'bin')
42
43
  }
43
44
 
44
45
  export function ffmpegSource(platform = process.platform) {
@@ -62,9 +63,9 @@ export function systemTool(name, platform = process.platform, envPath = process.
62
63
  }
63
64
 
64
65
  /** Managed copy first, then PATH: the same precedence the managed `gh` uses. */
65
- export function resolveTool(home, name, { platform = process.platform, envPath = process.env.PATH } = {}) {
66
+ export function resolveTool(root, name, { platform = process.platform, envPath = process.env.PATH } = {}) {
66
67
  const source = ffmpegSource(platform)
67
- const managed = source ? join(ffmpegBinDir(home), source.binaries[name]) : null
68
+ const managed = source ? join(ffmpegBinDir(root), source.binaries[name]) : null
68
69
  if (managed) {
69
70
  try {
70
71
  if (existsSync(managed) && statSync(managed).isFile()) return { path: managed, managed: true }
@@ -104,32 +105,37 @@ async function toolVersion(path, { run = runCommand, timeoutMs = VERIFY_TIMEOUT_
104
105
 
105
106
  const jobs = new Map()
106
107
 
107
- function jobKey(home) {
108
- return join(ffmpegRoot(home))
108
+ function jobKey(root) {
109
+ return join(ffmpegRoot(root))
109
110
  }
110
111
 
111
- function jobFor(home) {
112
- return jobs.get(jobKey(home)) || null
112
+ function jobFor(root) {
113
+ return jobs.get(jobKey(root)) || null
114
+ }
115
+
116
+ /** Whether a managed ffmpeg install is in flight; migration refuses to move it. */
117
+ export function ffmpegDownloadRunning(root) {
118
+ return jobFor(root)?.running === true
113
119
  }
114
120
 
115
121
  /**
116
122
  * What the page shows: whether the tools are usable, where they came from, and
117
123
  * the state of the last managed download.
118
124
  */
119
- export async function ffmpegStatus(home, {
125
+ export async function ffmpegStatus(root, {
120
126
  platform = process.platform,
121
127
  arch = process.arch,
122
128
  envPath = process.env.PATH,
123
129
  run = runCommand,
124
130
  } = {}) {
125
131
  const source = ffmpegSource(platform)
126
- const ffmpeg = resolveTool(home, 'ffmpeg', { platform, envPath })
127
- const ffprobe = resolveTool(home, 'ffprobe', { platform, envPath })
132
+ const ffmpeg = resolveTool(root, 'ffmpeg', { platform, envPath })
133
+ const ffprobe = resolveTool(root, 'ffprobe', { platform, envPath })
128
134
  const [ffmpegVersion, ffprobeVersion] = await Promise.all([
129
135
  ffmpeg ? toolVersion(ffmpeg.path, { run }) : null,
130
136
  ffprobe ? toolVersion(ffprobe.path, { run }) : null,
131
137
  ])
132
- const job = jobFor(home)
138
+ const job = jobFor(root)
133
139
  const installed = Boolean(ffmpeg && ffprobe)
134
140
  return {
135
141
  // The host platform either has a managed source or the tools must come from PATH.
@@ -150,8 +156,8 @@ export async function ffmpegStatus(home, {
150
156
  }
151
157
  }
152
158
 
153
- function prune(home) {
154
- for (const dir of [join(ffmpegRoot(home), 'src'), join(ffmpegRoot(home), 'download')]) {
159
+ function prune(root) {
160
+ for (const dir of [join(ffmpegRoot(root), 'src'), join(ffmpegRoot(root), 'download')]) {
155
161
  try {
156
162
  if (existsSync(dir)) rmSync(dir, { recursive: true, force: true })
157
163
  } catch {
@@ -162,15 +168,17 @@ function prune(home) {
162
168
 
163
169
  /**
164
170
  * Move the staged `bin` directory into place. The previous directory is kept
165
- * until the new binaries answer `-version`, then removed.
171
+ * until the new binaries answer `-version`, then removed. Renames go through
172
+ * `moveIntoPlace` so a lingering lock (antivirus scanning the freshly probed
173
+ * binaries) retries and, if needed, copies instead of failing the install.
166
174
  */
167
- async function swapBinDir(home, stagedBin, platform) {
168
- const binDir = ffmpegBinDir(home)
175
+ async function swapBinDir(root, stagedBin, platform) {
176
+ const binDir = ffmpegBinDir(root)
169
177
  const backup = `${binDir}.old-${process.pid}-${Date.now()}`
170
178
  let moved = false
171
179
  try {
172
- if (existsSync(binDir)) renameSync(binDir, backup)
173
- renameSync(stagedBin, binDir)
180
+ if (existsSync(binDir)) await moveIntoPlace(binDir, backup)
181
+ await moveIntoPlace(stagedBin, binDir)
174
182
  moved = true
175
183
  const names = ffmpegSource(platform).binaries
176
184
  for (const name of Object.values(names)) {
@@ -187,7 +195,7 @@ async function swapBinDir(home, stagedBin, platform) {
187
195
  // Keep restoring the old directory even if the new one is locked.
188
196
  }
189
197
  try {
190
- if (existsSync(backup)) renameSync(backup, binDir)
198
+ if (existsSync(backup)) await moveIntoPlace(backup, binDir)
191
199
  } catch {
192
200
  // Best effort; the caller still reports the install error.
193
201
  }
@@ -199,10 +207,10 @@ async function swapBinDir(home, stagedBin, platform) {
199
207
  * Download, extract and install in the background; return the current status
200
208
  * at once. The page polls {@link ffmpegStatus} for progress and the outcome.
201
209
  */
202
- export function startFfmpegDownload(home, { platform = process.platform, arch = process.arch } = {}) {
210
+ export function startFfmpegDownload(root, { platform = process.platform, arch = process.arch } = {}) {
203
211
  const source = ffmpegSource(platform)
204
212
  if (!source) throw new Error(`no managed ffmpeg build for ${platform}/${arch}; install it on PATH instead`)
205
- const key = jobKey(home)
213
+ const key = jobKey(root)
206
214
  const current = jobs.get(key)
207
215
  if (current?.running) return current.status()
208
216
  const job = {
@@ -210,10 +218,10 @@ export function startFfmpegDownload(home, { platform = process.platform, arch =
210
218
  received: 0,
211
219
  total: null,
212
220
  error: null,
213
- status: () => ffmpegStatus(home, { platform, arch }),
221
+ status: () => ffmpegStatus(root, { platform, arch }),
214
222
  }
215
223
  jobs.set(key, job)
216
- const downloadDir = join(ffmpegRoot(home), 'download')
224
+ const downloadDir = join(ffmpegRoot(root), 'download')
217
225
  const part = join(downloadDir, `${source.file}.part`)
218
226
  const controller = new AbortController()
219
227
  let timedOut = false
@@ -225,20 +233,25 @@ export function startFfmpegDownload(home, { platform = process.platform, arch =
225
233
 
226
234
  void (async () => {
227
235
  mkdirSync(downloadDir, { recursive: true })
228
- await downloadWithResume({
229
- url: source.url,
230
- partPath: part,
231
- signal: controller.signal,
232
- onProgress: (progress) => {
233
- job.received = progress.received
234
- job.total = progress.total
235
- },
236
- })
237
236
  const archive = join(downloadDir, source.file)
238
- renameSync(part, archive)
239
- const staging = join(ffmpegRoot(home), 'src')
237
+ // The archive only carries this name after a finished download, so a retry
238
+ // after a failed install (locked bin, probe failure) reuses it instead of
239
+ // pulling 110+ MB again.
240
+ if (!existsSync(archive)) {
241
+ await downloadWithResume({
242
+ url: source.url,
243
+ partPath: part,
244
+ signal: controller.signal,
245
+ onProgress: (progress) => {
246
+ job.received = progress.received
247
+ job.total = progress.total
248
+ },
249
+ })
250
+ await moveIntoPlace(part, archive)
251
+ }
252
+ const staging = join(ffmpegRoot(root), 'src')
240
253
  await extractArchive(archive, staging, source.kind, platform)
241
- const stagedBin = join(ffmpegRoot(home), 'staged-bin')
254
+ const stagedBin = join(ffmpegRoot(root), 'staged-bin')
242
255
  rmSync(stagedBin, { recursive: true, force: true })
243
256
  mkdirSync(stagedBin, { recursive: true })
244
257
  for (const [name, file] of Object.entries(source.binaries)) {
@@ -252,9 +265,9 @@ export function startFfmpegDownload(home, { platform = process.platform, arch =
252
265
  throw new Error(`${name} failed its probe before install: ${`${check.stderr}${check.stdout}`.trim().slice(-300) || `exit ${check.code}`}`)
253
266
  }
254
267
  }
255
- await swapBinDir(home, stagedBin, platform)
256
- prune(home)
257
- prependFfmpegPath(home, platform)
268
+ await swapBinDir(root, stagedBin, platform)
269
+ prune(root)
270
+ prependFfmpegPath(root, platform)
258
271
  })().catch((error) => {
259
272
  job.error = timedOut
260
273
  ? 'download timed out after 20 minutes; the partial file was kept for resume'
@@ -267,10 +280,10 @@ export function startFfmpegDownload(home, { platform = process.platform, arch =
267
280
  }
268
281
 
269
282
  /** Put the managed `bin` directory first on PATH; true when both tools exist. */
270
- export function prependFfmpegPath(home, platform = process.platform) {
283
+ export function prependFfmpegPath(root, platform = process.platform) {
271
284
  const source = ffmpegSource(platform)
272
285
  if (!source) return false
273
- const dir = ffmpegBinDir(home)
286
+ const dir = ffmpegBinDir(root)
274
287
  for (const file of Object.values(source.binaries)) {
275
288
  if (!existsSync(join(dir, file))) return false
276
289
  }