build.ts 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. #!/usr/bin/env bun
  2. import { $ } from "bun"
  3. import fs from "fs"
  4. import path from "path"
  5. import { fileURLToPath } from "url"
  6. import { createSolidTransformPlugin } from "@opentui/solid/bun-plugin"
  7. const __filename = fileURLToPath(import.meta.url)
  8. const __dirname = path.dirname(__filename)
  9. const dir = path.resolve(__dirname, "..")
  10. process.chdir(dir)
  11. await import("./generate.ts")
  12. import { Script } from "@opencode-ai/script"
  13. import pkg from "../package.json"
  14. // Load migrations from migration directories
  15. const migrationDirs = (
  16. await fs.promises.readdir(path.join(dir, "migration"), {
  17. withFileTypes: true,
  18. })
  19. )
  20. .filter((entry) => entry.isDirectory() && /^\d{4}\d{2}\d{2}\d{2}\d{2}\d{2}/.test(entry.name))
  21. .map((entry) => entry.name)
  22. .sort()
  23. const migrations = await Promise.all(
  24. migrationDirs.map(async (name) => {
  25. const file = path.join(dir, "migration", name, "migration.sql")
  26. const sql = await Bun.file(file).text()
  27. const match = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(name)
  28. const timestamp = match
  29. ? Date.UTC(
  30. Number(match[1]),
  31. Number(match[2]) - 1,
  32. Number(match[3]),
  33. Number(match[4]),
  34. Number(match[5]),
  35. Number(match[6]),
  36. )
  37. : 0
  38. return { sql, timestamp, name }
  39. }),
  40. )
  41. console.log(`Loaded ${migrations.length} migrations`)
  42. const singleFlag = process.argv.includes("--single")
  43. const baselineFlag = process.argv.includes("--baseline")
  44. const skipInstall = process.argv.includes("--skip-install")
  45. const plugin = createSolidTransformPlugin()
  46. const skipEmbedWebUi = process.argv.includes("--skip-embed-web-ui")
  47. const createEmbeddedWebUIBundle = async () => {
  48. console.log(`Building Web UI to embed in the binary`)
  49. const appDir = path.join(import.meta.dirname, "../../app")
  50. const dist = path.join(appDir, "dist")
  51. await $`bun run --cwd ${appDir} build`
  52. const files = (await Array.fromAsync(new Bun.Glob("**/*").scan({ cwd: dist })))
  53. .map((file) => file.replaceAll("\\", "/"))
  54. .sort()
  55. const imports = files.map((file, i) => {
  56. const spec = path.relative(dir, path.join(dist, file)).replaceAll("\\", "/")
  57. return `import file_${i} from ${JSON.stringify(spec.startsWith(".") ? spec : `./${spec}`)} with { type: "file" };`
  58. })
  59. const entries = files.map((file, i) => ` ${JSON.stringify(file)}: file_${i},`)
  60. return [
  61. `// Import all files as file_$i with type: "file"`,
  62. ...imports,
  63. `// Export with original mappings`,
  64. `export default {`,
  65. ...entries,
  66. `}`,
  67. ].join("\n")
  68. }
  69. const embeddedFileMap = skipEmbedWebUi ? null : await createEmbeddedWebUIBundle()
  70. const allTargets: {
  71. os: string
  72. arch: "arm64" | "x64"
  73. abi?: "musl"
  74. avx2?: false
  75. }[] = [
  76. {
  77. os: "linux",
  78. arch: "arm64",
  79. },
  80. {
  81. os: "linux",
  82. arch: "x64",
  83. },
  84. {
  85. os: "linux",
  86. arch: "x64",
  87. avx2: false,
  88. },
  89. {
  90. os: "linux",
  91. arch: "arm64",
  92. abi: "musl",
  93. },
  94. {
  95. os: "linux",
  96. arch: "x64",
  97. abi: "musl",
  98. },
  99. {
  100. os: "linux",
  101. arch: "x64",
  102. abi: "musl",
  103. avx2: false,
  104. },
  105. {
  106. os: "darwin",
  107. arch: "arm64",
  108. },
  109. {
  110. os: "darwin",
  111. arch: "x64",
  112. },
  113. {
  114. os: "darwin",
  115. arch: "x64",
  116. avx2: false,
  117. },
  118. {
  119. os: "win32",
  120. arch: "arm64",
  121. },
  122. {
  123. os: "win32",
  124. arch: "x64",
  125. },
  126. {
  127. os: "win32",
  128. arch: "x64",
  129. avx2: false,
  130. },
  131. ]
  132. const targets = singleFlag
  133. ? allTargets.filter((item) => {
  134. if (item.os !== process.platform || item.arch !== process.arch) {
  135. return false
  136. }
  137. // When building for the current platform, prefer a single native binary by default.
  138. // Baseline binaries require additional Bun artifacts and can be flaky to download.
  139. if (item.avx2 === false) {
  140. return baselineFlag
  141. }
  142. // also skip abi-specific builds for the same reason
  143. if (item.abi !== undefined) {
  144. return false
  145. }
  146. return true
  147. })
  148. : allTargets
  149. await $`rm -rf dist`
  150. const binaries: Record<string, string> = {}
  151. if (!skipInstall) {
  152. await $`bun install --os="*" --cpu="*" @opentui/core@${pkg.dependencies["@opentui/core"]}`
  153. await $`bun install --os="*" --cpu="*" @parcel/watcher@${pkg.dependencies["@parcel/watcher"]}`
  154. }
  155. for (const item of targets) {
  156. const name = [
  157. pkg.name,
  158. // changing to win32 flags npm for some reason
  159. item.os === "win32" ? "windows" : item.os,
  160. item.arch,
  161. item.avx2 === false ? "baseline" : undefined,
  162. item.abi === undefined ? undefined : item.abi,
  163. ]
  164. .filter(Boolean)
  165. .join("-")
  166. console.log(`building ${name}`)
  167. await $`mkdir -p dist/${name}/bin`
  168. const localPath = path.resolve(dir, "node_modules/@opentui/core/parser.worker.js")
  169. const rootPath = path.resolve(dir, "../../node_modules/@opentui/core/parser.worker.js")
  170. const parserWorker = fs.realpathSync(fs.existsSync(localPath) ? localPath : rootPath)
  171. const workerPath = "./src/cli/cmd/tui/worker.ts"
  172. // Use platform-specific bunfs root path based on target OS
  173. const bunfsRoot = item.os === "win32" ? "B:/~BUN/root/" : "/$bunfs/root/"
  174. const workerRelativePath = path.relative(dir, parserWorker).replaceAll("\\", "/")
  175. await Bun.build({
  176. conditions: ["browser"],
  177. tsconfig: "./tsconfig.json",
  178. plugins: [plugin],
  179. external: ["node-gyp"],
  180. compile: {
  181. autoloadBunfig: false,
  182. autoloadDotenv: false,
  183. autoloadTsconfig: true,
  184. autoloadPackageJson: true,
  185. target: name.replace(pkg.name, "bun") as any,
  186. outfile: `dist/${name}/bin/opencode`,
  187. execArgv: [`--user-agent=opencode/${Script.version}`, "--use-system-ca", "--"],
  188. windows: {},
  189. },
  190. files: {
  191. ...(embeddedFileMap ? { "opencode-web-ui.gen.ts": embeddedFileMap } : {}),
  192. },
  193. entrypoints: ["./src/index.ts", parserWorker, workerPath, ...(embeddedFileMap ? ["opencode-web-ui.gen.ts"] : [])],
  194. define: {
  195. OPENCODE_VERSION: `'${Script.version}'`,
  196. OPENCODE_MIGRATIONS: JSON.stringify(migrations),
  197. OTUI_TREE_SITTER_WORKER_PATH: bunfsRoot + workerRelativePath,
  198. OPENCODE_WORKER_PATH: workerPath,
  199. OPENCODE_CHANNEL: `'${Script.channel}'`,
  200. OPENCODE_LIBC: item.os === "linux" ? `'${item.abi ?? "glibc"}'` : "",
  201. },
  202. })
  203. // Smoke test: only run if binary is for current platform
  204. if (item.os === process.platform && item.arch === process.arch && !item.abi) {
  205. const binaryPath = `dist/${name}/bin/opencode`
  206. console.log(`Running smoke test: ${binaryPath} --version`)
  207. try {
  208. const versionOutput = await $`${binaryPath} --version`.text()
  209. console.log(`Smoke test passed: ${versionOutput.trim()}`)
  210. } catch (e) {
  211. console.error(`Smoke test failed for ${name}:`, e)
  212. process.exit(1)
  213. }
  214. }
  215. await $`rm -rf ./dist/${name}/bin/tui`
  216. await Bun.file(`dist/${name}/package.json`).write(
  217. JSON.stringify(
  218. {
  219. name,
  220. version: Script.version,
  221. os: [item.os],
  222. cpu: [item.arch],
  223. },
  224. null,
  225. 2,
  226. ),
  227. )
  228. binaries[name] = Script.version
  229. }
  230. if (Script.release) {
  231. for (const key of Object.keys(binaries)) {
  232. if (key.includes("linux")) {
  233. await $`tar -czf ../../${key}.tar.gz *`.cwd(`dist/${key}/bin`)
  234. } else {
  235. await $`zip -r ../../${key}.zip *`.cwd(`dist/${key}/bin`)
  236. }
  237. }
  238. await $`gh release upload v${Script.version} ./dist/*.zip ./dist/*.tar.gz --clobber --repo ${process.env.GH_REPO}`
  239. }
  240. export { binaries }