prepare-primary-runtime.ts 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. /** Prepare pinned, relocatable script interpreters without installing into the build host. */
  2. import { execFileSync } from 'node:child_process'
  3. import { createHash } from 'node:crypto'
  4. import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
  5. import { cp } from 'node:fs/promises'
  6. import { createRequire } from 'node:module'
  7. import { tmpdir } from 'node:os'
  8. import { dirname, join } from 'node:path'
  9. import extractZip from 'extract-zip'
  10. import { x as extractTar } from 'tar'
  11. import { workspaceDependencyPaths, type PrimaryRuntimeManifest } from '../../desktop-host/src/primary-runtime.ts'
  12. import { resolveDesktopBuildTarget, resolveDesktopTargetBuildPaths } from './desktop-build-paths.mjs'
  13. import { scrubWindowsSigningEnvironment } from './windows-sign.mjs'
  14. import lock from './primary-runtime-lock.json' with { type: 'json' }
  15. /**
  16. * Download or reuse an archive only when its bytes match the release lock.
  17. * @param url - Locked archive URL.
  18. * @param sha256 - Expected SHA-256 digest.
  19. * @param cache - Download cache directory.
  20. * @returns Verified local archive path.
  21. */
  22. export async function downloadPrimaryRuntimeAsset(url: string, sha256: string, cache: string): Promise<string> {
  23. const destination = join(cache, sha256)
  24. let bytes: Buffer
  25. try { bytes = readFileSync(destination) } catch (error) {
  26. if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
  27. const response = await fetch(url)
  28. if (!response.ok) throw new Error(`primary runtime download: ${String(response.status)} ${url}`)
  29. bytes = Buffer.from(await response.arrayBuffer())
  30. }
  31. if (createHash('sha256').update(bytes).digest('hex') !== sha256) throw new Error(`primary runtime download: checksum mismatch for ${url}`)
  32. writeFileSync(destination, bytes)
  33. return destination
  34. }
  35. async function pythonArchive(target: keyof typeof lock.targets, cache: string): Promise<string> {
  36. const artifact = lock.targets[target]
  37. const filename = `cpython-${lock.pythonVersion}+${lock.pythonRelease}-${artifact.pythonTarget}-install_only_stripped.tar.gz`
  38. return downloadPrimaryRuntimeAsset(`https://github.com/astral-sh/python-build-standalone/releases/download/${lock.pythonRelease}/${encodeURIComponent(filename)}`, artifact.pythonSha256, cache)
  39. }
  40. /**
  41. * Unpack a locked library wheel whose files all belong in site-packages.
  42. * @param archive - Hash-verified wheel archive.
  43. * @param destination - Absolute site-packages directory.
  44. * @returns Resolves after extraction; rejects wheels requiring installation into other directories.
  45. */
  46. export async function unpackPrimaryRuntimeWheel(archive: string, destination: string): Promise<void> {
  47. await extractZip(archive, {
  48. dir: destination,
  49. onEntry: (entry) => {
  50. if (entry.fileName.split('/')[0]?.endsWith('.data')) {
  51. throw new Error(`primary runtime: wheel requires unsupported installation paths: ${entry.fileName}`)
  52. }
  53. },
  54. })
  55. }
  56. /**
  57. * Materialize the selected Desktop target's primary runtime in its build resources.
  58. * @param options - Signed Windows packaging defers execution until its supervised signing stage.
  59. * @returns Resolves after materialization and, unless deferred, native-target execution checks.
  60. */
  61. export async function preparePrimaryRuntime(options: { deferSmoke?: boolean } = {}): Promise<void> {
  62. const target = resolveDesktopBuildTarget()
  63. const paths = resolveDesktopTargetBuildPaths()
  64. const artifact = lock.targets[target]
  65. mkdirSync(paths.runtime, { recursive: true })
  66. mkdirSync(paths.downloads, { recursive: true })
  67. const staging = mkdtempSync(join(tmpdir(), 'dsh-primary-'))
  68. try {
  69. const output = join(staging, 'payload')
  70. const dependencies = join(output, 'dependencies')
  71. mkdirSync(dependencies, { recursive: true })
  72. const nodeFilename = `node-v${lock.nodeVersion}-${artifact.nodeArchive}`
  73. const nodeArchive = await downloadPrimaryRuntimeAsset(`https://nodejs.org/dist/v${lock.nodeVersion}/${nodeFilename}`, artifact.nodeSha256, paths.downloads)
  74. const unpackedNode = join(staging, 'node')
  75. mkdirSync(unpackedNode)
  76. if (target === 'win-x64') await extractZip(nodeArchive, { dir: unpackedNode })
  77. else await extractTar({ file: nodeArchive, cwd: unpackedNode })
  78. const nodeSource = join(unpackedNode, nodeFilename.replace(/\.(?:zip|tar\.gz)$/u, ''))
  79. mkdirSync(join(dependencies, 'node', 'bin'), { recursive: true })
  80. mkdirSync(join(dependencies, 'node', 'node_modules'))
  81. writeFileSync(join(dependencies, 'node', 'node_modules', 'README.txt'), 'Reserved for bundled Node packages. pnpm uses its default installation directories.\n')
  82. cpSync(join(nodeSource, ...(target === 'win-x64' ? ['node.exe'] : ['bin', 'node'])),
  83. join(dependencies, 'node', 'bin', target === 'win-x64' ? 'node.exe' : 'node'))
  84. cpSync(join(nodeSource, 'LICENSE'), join(dependencies, 'node', 'LICENSE'))
  85. await extractTar({ file: await pythonArchive(target, paths.downloads), cwd: dependencies })
  86. const require = createRequire(import.meta.url)
  87. const pnpmManifest = require.resolve('pnpm')
  88. const pnpm = JSON.parse(readFileSync(pnpmManifest, 'utf8')) as { version: string }
  89. await cp(dirname(pnpmManifest), join(dependencies, 'pnpm'), { recursive: true, dereference: true })
  90. const desktop = JSON.parse(readFileSync(join(import.meta.dirname, '..', 'package.json'), 'utf8')) as { version: string }
  91. const manifest: PrimaryRuntimeManifest = {
  92. desktopVersion: desktop.version,
  93. platform: target === 'win-x64' ? 'win32' : 'darwin',
  94. arch: target === 'mac-arm64' ? 'arm64' : 'x64',
  95. components: {
  96. python: lock.pythonVersion, node: lock.nodeVersion, pnpm: pnpm.version,
  97. numpy: lock.numpyVersion, pandas: lock.pandasVersion,
  98. },
  99. }
  100. const entries = workspaceDependencyPaths(output, manifest)
  101. for (const wheel of [...artifact.wheels, ...lock.wheels]) {
  102. await unpackPrimaryRuntimeWheel(await downloadPrimaryRuntimeAsset(wheel.url, wheel.sha256, paths.downloads), entries.pythonPackages)
  103. }
  104. writeFileSync(join(output, 'runtime.json'), `${JSON.stringify(manifest, undefined, 2)}\n`)
  105. const destination = join(paths.runtime, 'primary-runtime')
  106. rmSync(destination, { recursive: true, force: true })
  107. await cp(output, destination, { recursive: true, dereference: true })
  108. } finally {
  109. rmSync(staging, { recursive: true, force: true })
  110. }
  111. if (!options.deferSmoke) smokePrimaryRuntime(join(paths.runtime, 'primary-runtime'))
  112. }
  113. /**
  114. * Execute the native payload's interpreters, package manager and Python libraries.
  115. * @param root - Final payload directory, including any platform signatures.
  116. */
  117. export function smokePrimaryRuntime(root: string): void {
  118. const manifest = JSON.parse(readFileSync(join(root, 'runtime.json'), 'utf8')) as PrimaryRuntimeManifest
  119. if (manifest.platform !== process.platform || manifest.arch !== process.arch) return
  120. const entries = workspaceDependencyPaths(root, manifest)
  121. const options = { stdio: 'inherit', timeout: 120_000, env: scrubWindowsSigningEnvironment(process.env) } as const
  122. execFileSync(entries.python, ['-I', '-c', 'import decimal, xml.parsers.expat, lzma, uuid, numpy, pandas; assert numpy.arange(4).sum() == 6; assert pandas.DataFrame({"n": [1, 2]}).n.sum() == 3'], options)
  123. execFileSync(entries.node, ['-e', `if (process.versions.node !== ${JSON.stringify(manifest.components.node)}) process.exit(1)`], options)
  124. execFileSync(entries.node, [entries.pnpm, '--version'], options)
  125. }
  126. if (import.meta.main) await preparePrimaryRuntime()