prepare-primary-runtime.ts 7.1 KB

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