windows-shell.mjs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { spawn } from 'node:child_process'
  2. import { resolve as resolvePath } from 'node:path'
  3. export function powershellArguments(command) {
  4. const script = `[Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = New-Object System.Text.UTF8Encoding($false)\n$global:LASTEXITCODE = 0\ntry {\n& {\n${command}\n}\n$ok = $?\nif ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }\nif (-not $ok) { exit 1 }\n} catch { [Console]::Error.WriteLine($_.ToString()); exit 1 }`
  5. return ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')]
  6. }
  7. /** Bound both output streams, and terminate the owned process tree before
  8. * resolving a timeout or authorization cancellation. Never spawn a shell. */
  9. export function windowsShell(shell, command, { cwd, timeout, signal, helper = resolvePath(import.meta.dirname, '../.desktop-build/computer-helper-dev.exe'), limit = 512 * 1024 }) {
  10. return new Promise(resolve => {
  11. let child, timer, timedOut = false, cancelled = false, finished = false
  12. const output = { stdout: [], stderr: [] }, sizes = { stdout: 0, stderr: 0 }
  13. const capture = (key, bytes) => {
  14. const kept = bytes.subarray(0, Math.max(0, limit - sizes[key]))
  15. output[key].push(kept); sizes[key] += kept.length
  16. }
  17. const finish = async (code, error) => {
  18. if (finished) return
  19. finished = true; clearTimeout(timer); signal?.removeEventListener('abort', abort)
  20. if (error) capture('stderr', Buffer.from(error.message))
  21. resolve({ command, exitCode: timedOut || cancelled || error ? 1 : code ?? 1, timedOut,
  22. ...(cancelled ? { cancelled: true } : {}),
  23. stdout: Buffer.concat(output.stdout).toString('utf8'), stderr: Buffer.concat(output.stderr).toString('utf8') })
  24. }
  25. const stop = () => {
  26. // The native helper owns a KILL_ON_JOB_CLOSE job. Terminating the helper
  27. // closes that kernel handle and the entire owned PowerShell process tree.
  28. if (!finished && child?.pid) child.kill()
  29. }
  30. const abort = () => { cancelled = true; stop() }
  31. if (signal?.aborted) { cancelled = true; void finish(1); return }
  32. try {
  33. child = spawn(helper, ['--shell'], { cwd, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, TERM: 'dumb' } })
  34. child.stdin.on('error', () => {})
  35. child.stdin.end(JSON.stringify({ encoded: powershellArguments(command).at(-1), cwd }))
  36. child.stdout.on('data', bytes => capture('stdout', bytes))
  37. child.stderr.on('data', bytes => capture('stderr', bytes))
  38. child.once('error', error => { void finish(1, error) })
  39. child.once('close', code => { void finish(code) })
  40. signal?.addEventListener('abort', abort, { once: true })
  41. timer = setTimeout(() => { timedOut = true; stop() }, timeout)
  42. } catch (error) { void finish(1, error) }
  43. })
  44. }