build.ts 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. #!/usr/bin/env bun
  2. import solidPlugin from "./solid-plugin"
  3. import path from "path"
  4. import { $ } from "bun"
  5. import { fileURLToPath } from "url"
  6. import { createRequire } from "module"
  7. const __filename = fileURLToPath(import.meta.url)
  8. const __dirname = path.dirname(__filename)
  9. const require = createRequire(import.meta.url)
  10. const dir = path.resolve(__dirname, "..")
  11. process.chdir(dir)
  12. import pkg from "../package.json"
  13. import { Script } from "@opencode-ai/script"
  14. import fs from "fs/promises"
  15. import nodefs from "fs"
  16. await $`bun run build:webgui`
  17. const webGuiDir = path.join(dir, "webgui-dist")
  18. const embedOutput = path.join(dir, "src/webgui/embed.generated.ts")
  19. async function listWebGuiFiles(current: string) {
  20. const entries = await fs.readdir(current, { withFileTypes: true })
  21. const files: { path: string; data: string }[] = []
  22. for (const entry of entries) {
  23. const absolute = path.join(current, entry.name)
  24. if (entry.isDirectory()) {
  25. const nested = await listWebGuiFiles(absolute)
  26. files.push(...nested)
  27. continue
  28. }
  29. const relative = path.relative(webGuiDir, absolute).split(path.sep).join("/")
  30. const file = Bun.file(absolute)
  31. const buffer = Buffer.from(await file.arrayBuffer())
  32. files.push({ path: relative, data: buffer.toString("base64") })
  33. }
  34. return files
  35. }
  36. async function generateEmbeddedWebGui() {
  37. const indexFile = Bun.file(path.join(webGuiDir, "index.html"))
  38. if (!(await indexFile.exists())) {
  39. await Bun.write(embedOutput, "export const embeddedWebGui = [] as const\n")
  40. return
  41. }
  42. const items = await listWebGuiFiles(webGuiDir)
  43. const lines = [
  44. "export const embeddedWebGui = [",
  45. ...items.map((item) => ` { path: ${JSON.stringify(item.path)}, data: ${JSON.stringify(item.data)} },`),
  46. "] as const",
  47. "",
  48. ]
  49. await Bun.write(embedOutput, lines.join("\n"))
  50. }
  51. await generateEmbeddedWebGui()
  52. const singleFlag = process.argv.includes("--single")
  53. const baselineFlag = process.argv.includes("--baseline")
  54. const skipInstall = process.argv.includes("--skip-install")
  55. const allTargets: {
  56. os: string
  57. arch: "arm64" | "x64"
  58. abi?: "musl"
  59. avx2?: false
  60. }[] = [
  61. {
  62. os: "linux",
  63. arch: "arm64",
  64. },
  65. {
  66. os: "linux",
  67. arch: "x64",
  68. },
  69. {
  70. os: "darwin",
  71. arch: "arm64",
  72. },
  73. {
  74. os: "darwin",
  75. arch: "x64",
  76. },
  77. {
  78. os: "win32",
  79. arch: "x64",
  80. },
  81. ]
  82. const targets = singleFlag
  83. ? allTargets.filter((item) => {
  84. if (item.os !== process.platform || item.arch !== process.arch) {
  85. return false
  86. }
  87. // When building for the current platform, prefer a single native binary by default.
  88. // Baseline binaries require additional Bun artifacts and can be flaky to download.
  89. if (item.avx2 === false) {
  90. return baselineFlag
  91. }
  92. return true
  93. })
  94. : allTargets
  95. await fs.rm("dist", { recursive: true, force: true })
  96. const binaries: Record<string, string> = {}
  97. if (!skipInstall) {
  98. await $`bun install --os="*" --cpu="*" @opentui/core@${pkg.dependencies["@opentui/core"]}`
  99. await $`bun install --os="*" --cpu="*" @parcel/watcher@${pkg.dependencies["@parcel/watcher"]}`
  100. }
  101. for (const item of targets) {
  102. const name = [
  103. pkg.name,
  104. // changing to win32 flags npm for some reason
  105. item.os === "win32" ? "windows" : item.os,
  106. item.arch,
  107. item.avx2 === false ? "baseline" : undefined,
  108. item.abi === undefined ? undefined : item.abi,
  109. ]
  110. .filter(Boolean)
  111. .join("-")
  112. console.log(`building ${name}`)
  113. await fs.mkdir(`dist/${name}/bin`, { recursive: true })
  114. const opentuiCoreEntry = require.resolve("@opentui/core")
  115. const parserWorker = nodefs.realpathSync(path.join(path.dirname(opentuiCoreEntry), "parser.worker.js"))
  116. const workerPath = "./src/cli/cmd/tui/worker.ts"
  117. // Use platform-specific bunfs root path based on target OS
  118. const bunfsRoot = item.os === "win32" ? "B:/~BUN/root/" : "/$bunfs/root/"
  119. const workerRelativePath = path.relative(dir, parserWorker).replaceAll("\\", "/")
  120. await Bun.build({
  121. conditions: ["browser"],
  122. tsconfig: "./tsconfig.json",
  123. plugins: [solidPlugin],
  124. sourcemap: "external",
  125. compile: {
  126. autoloadBunfig: false,
  127. autoloadDotenv: false,
  128. //@ts-ignore (bun types aren't up to date)
  129. autoloadTsconfig: true,
  130. autoloadPackageJson: true,
  131. target: name.replace(pkg.name, "bun") as any,
  132. outfile: `dist/${name}/bin/opencode`,
  133. execArgv: [`--user-agent=opencode/${Script.version}`, "--"],
  134. windows: {},
  135. },
  136. entrypoints: ["./src/index.ts", parserWorker, workerPath],
  137. define: {
  138. OPENCODE_VERSION: `'${Script.version}'`,
  139. OTUI_TREE_SITTER_WORKER_PATH: bunfsRoot + workerRelativePath,
  140. OPENCODE_WORKER_PATH: workerPath,
  141. OPENCODE_CHANNEL: `'${Script.channel}'`,
  142. OPENCODE_LIBC: item.os === "linux" ? `'${item.abi ?? "glibc"}'` : "",
  143. },
  144. })
  145. await fs.rm(`./dist/${name}/bin/tui`, { recursive: true, force: true })
  146. await Bun.file(`dist/${name}/package.json`).write(
  147. JSON.stringify(
  148. {
  149. name,
  150. version: Script.version,
  151. os: [item.os],
  152. cpu: [item.arch],
  153. },
  154. null,
  155. 2,
  156. ),
  157. )
  158. binaries[name] = Script.version
  159. }
  160. export { binaries }