1
0

build-node.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. #!/usr/bin/env bun
  2. import { spawnSync } from "node:child_process"
  3. import { createHash } from "node:crypto"
  4. import { chmod, copyFile, mkdir, mkdtemp, realpath, rename, rm, stat, writeFile } from "node:fs/promises"
  5. import os from "node:os"
  6. import path from "node:path"
  7. import { build } from "vite"
  8. import { Script } from "@opencode-ai/script"
  9. import pkg from "../package.json"
  10. import { modelsData } from "./generate"
  11. import { collectNodeAssets, copyNodeAssets, hashNodeAssets, seaAssetMap } from "./node-assets"
  12. import { mainConfig } from "../vite.node.config"
  13. import { nodeExecArgv, nodeTarget, type NodeTarget } from "../src/node/target"
  14. const NODE_VERSION = "26.4.0"
  15. const dir = path.resolve(import.meta.dirname, "..")
  16. const outdir = path.resolve(
  17. dir,
  18. process.argv.find((arg) => arg.startsWith("--outdir="))?.slice("--outdir=".length) ?? "dist",
  19. )
  20. if (outdir === dir) throw new Error("--outdir must not be the package directory")
  21. if (outdir === path.join(dir, "dist-node")) {
  22. throw new Error("--outdir must not be dist-node because it contains temporary files")
  23. }
  24. const bundleOnly = process.argv.includes("--bundle-only")
  25. const single = process.argv.includes("--single")
  26. const skipInstall = process.argv.includes("--skip-install")
  27. const requested = process.argv.find((arg) => arg.startsWith("--target="))?.slice("--target=".length)
  28. const allTargets = [
  29. nodeTarget("linux", "arm64"),
  30. nodeTarget("linux", "x64"),
  31. nodeTarget("darwin", "arm64"),
  32. nodeTarget("win32", "arm64"),
  33. nodeTarget("win32", "x64"),
  34. ]
  35. const targets = requested
  36. ? allTargets.filter((target) => targetName(target) === requested)
  37. : single || bundleOnly
  38. ? [nodeTarget(process.platform, process.arch)]
  39. : allTargets
  40. if (targets.length === 0) {
  41. if (requested === "darwin-x64") throw new Error("Node 26.4 SEA does not support macOS x64")
  42. throw new Error(`Unknown Node target: ${requested}`)
  43. }
  44. if (!bundleOnly && targets.some((target) => target.platform === "darwin" && target.arch === "x64")) {
  45. throw new Error("Node 26.4 SEA does not support macOS x64")
  46. }
  47. process.chdir(dir)
  48. if (!skipInstall) run(process.execPath, ["install", "--os=*", "--cpu=*"])
  49. if (!bundleOnly) await rm(outdir, { recursive: true, force: true })
  50. const builder =
  51. !bundleOnly || targets.some((target) => target.platform === process.platform && target.arch === process.arch)
  52. ? await resolveHostNode()
  53. : undefined
  54. for (const target of targets) {
  55. console.log(`building cli-node-${targetName(target)}`)
  56. const assets = await collectNodeAssets(target)
  57. await rm("dist-node", { recursive: true, force: true })
  58. const assetHash = await hashNodeAssets(assets)
  59. const input = { version: Script.version, channel: Script.channel, models: modelsData, assetHash, target }
  60. await copyNodeAssets(assets)
  61. await build(mainConfig(input))
  62. const host = target.platform === process.platform && target.arch === process.arch
  63. if (host) {
  64. if (!builder) throw new Error("Node SEA builder is unavailable")
  65. run(builder, [...nodeExecArgv, "dist-node/opencode.mjs", "--version"])
  66. run(builder, [...nodeExecArgv, "dist-node/opencode.mjs", "--help"])
  67. }
  68. if (bundleOnly) continue
  69. const name = `cli-node-${targetName(target)}`
  70. const binary = target.platform === "win32" ? "opencode2-node.exe" : "opencode2-node"
  71. const output = path.join(outdir, name, "bin", binary)
  72. if (!builder) throw new Error("Node SEA builder is unavailable")
  73. await mkdir(path.dirname(output), { recursive: true })
  74. const config = {
  75. main: "dist-node/opencode.mjs",
  76. mainFormat: "module",
  77. executable: await resolveTargetNode(target, builder),
  78. output: path.relative(dir, output),
  79. disableExperimentalSEAWarning: true,
  80. useSnapshot: false,
  81. useCodeCache: false,
  82. execArgv: nodeExecArgv,
  83. execArgvExtension: "none",
  84. assets: await seaAssetMap(),
  85. }
  86. await writeFile("dist-node/sea.json", `${JSON.stringify(config, null, 2)}\n`)
  87. run(builder, ["--build-sea", "dist-node/sea.json"])
  88. if (target.platform !== "win32") await chmod(output, 0o755)
  89. if (target.platform === "darwin" && process.platform === "darwin") run("codesign", ["--sign", "-", output])
  90. if (target.platform === "darwin" && process.platform !== "darwin") {
  91. console.warn(`${output} must be signed on macOS before it can run`)
  92. }
  93. await writeFile(
  94. path.join(outdir, name, "package.json"),
  95. `${JSON.stringify(
  96. {
  97. name: `@opencode-ai/${name}`,
  98. version: Script.version,
  99. license: pkg.license,
  100. repository: { type: "git", url: "git+https://github.com/anomalyco/opencode.git" },
  101. os: [target.platform],
  102. cpu: [target.arch],
  103. },
  104. null,
  105. 2,
  106. )}\n`,
  107. )
  108. if (host) await smoke(output)
  109. }
  110. async function resolveHostNode() {
  111. const candidates = [process.env.NODE_BIN, "node"].filter((item): item is string => Boolean(item))
  112. for (const candidate of candidates) {
  113. const result = spawnSync(
  114. candidate,
  115. ["-p", "JSON.stringify({version:process.versions.node,path:process.execPath})"],
  116. {
  117. encoding: "utf8",
  118. },
  119. )
  120. if (result.status !== 0) continue
  121. const info = JSON.parse(result.stdout) as { version: string; path: string }
  122. if (info.version === NODE_VERSION) return realpath(info.path)
  123. }
  124. return resolveTargetNode(nodeTarget(process.platform, process.arch))
  125. }
  126. async function resolveTargetNode(target: NodeTarget, host?: string) {
  127. if (host && target.platform === process.platform && target.arch === process.arch) return host
  128. const cache = path.resolve(dir, ".cache", "node")
  129. const platform = target.platform === "win32" ? "win" : target.platform
  130. const archiveName = `node-v${NODE_VERSION}-${platform}-${target.arch}`
  131. const targetDirectory = path.join(cache, archiveName)
  132. const executable = path.join(targetDirectory, target.platform === "win32" ? "node.exe" : "bin/node")
  133. if (
  134. (await stat(executable).then(
  135. () => true,
  136. () => false,
  137. )) &&
  138. (await stat(path.join(targetDirectory, ".verified")).then(
  139. () => true,
  140. () => false,
  141. ))
  142. )
  143. return realpath(executable)
  144. await mkdir(cache, { recursive: true })
  145. const extension = target.platform === "win32" ? "zip" : "tar.gz"
  146. const filename = `${archiveName}.${extension}`
  147. const archive = path.join(cache, filename)
  148. const base = `https://nodejs.org/dist/v${NODE_VERSION}`
  149. const [response, sums] = await Promise.all([fetch(`${base}/${filename}`), fetch(`${base}/SHASUMS256.txt`)])
  150. if (!response.ok) throw new Error(`Failed to download Node ${NODE_VERSION}: ${response.status}`)
  151. if (!sums.ok) throw new Error(`Failed to download Node ${NODE_VERSION} checksums: ${sums.status}`)
  152. const data = new Uint8Array(await response.arrayBuffer())
  153. const expected = (await sums.text())
  154. .split("\n")
  155. .find((line) => line.endsWith(` ${filename}`))
  156. ?.split(/\s+/)[0]
  157. if (!expected) throw new Error(`Missing checksum for ${filename}`)
  158. if (createHash("sha256").update(data).digest("hex") !== expected) throw new Error(`Checksum mismatch for ${filename}`)
  159. await writeFile(archive, data)
  160. const temporary = path.join(cache, `${archiveName}.${process.pid}.tmp`)
  161. await rm(temporary, { recursive: true, force: true })
  162. await mkdir(temporary)
  163. if (target.platform !== "win32") run("tar", ["-xzf", archive, "-C", temporary])
  164. if (target.platform === "win32" && process.platform === "win32") {
  165. run(path.join(process.env.SystemRoot ?? "C:\\Windows", "System32", "tar.exe"), ["-xf", archive, "-C", temporary])
  166. }
  167. if (target.platform === "win32" && process.platform !== "win32") run("unzip", ["-q", archive, "-d", temporary])
  168. await rm(targetDirectory, { recursive: true, force: true })
  169. await rename(path.join(temporary, archiveName), targetDirectory)
  170. await writeFile(path.join(targetDirectory, ".verified"), `${expected}\n`)
  171. await rm(temporary, { recursive: true, force: true })
  172. await rm(archive, { force: true })
  173. return realpath(executable)
  174. }
  175. async function smoke(output: string) {
  176. const root = await mkdtemp(path.join(os.tmpdir(), "opencode-node-smoke-"))
  177. const executable = path.join(root, path.basename(output))
  178. await copyFile(output, executable)
  179. if (process.platform !== "win32") await chmod(executable, 0o755)
  180. run(executable, ["--version"], root)
  181. run(executable, ["--help"], root)
  182. await rm(root, { recursive: true, force: true })
  183. }
  184. function targetName(target: NodeTarget) {
  185. return `${target.platform === "win32" ? "windows" : target.platform}-${target.arch}`
  186. }
  187. function run(command: string, args: readonly string[], cwd = dir) {
  188. const result = spawnSync(command, args, { cwd, stdio: "inherit", env: process.env })
  189. if (result.error) throw result.error
  190. if (result.status !== 0) throw new Error(`${command} exited with status ${result.status ?? "unknown"}`)
  191. }