build.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. // Fetch and generate models.dev snapshot
  53. const modelsData = process.env.MODELS_DEV_API_JSON
  54. ? await Bun.file(process.env.MODELS_DEV_API_JSON).text()
  55. : await fetch(`https://models.dev/api.json`).then((x) => x.text())
  56. await Bun.write(
  57. path.join(dir, "src/provider/models-snapshot.ts"),
  58. `// Auto-generated by build.ts - do not edit\nexport const snapshot = ${modelsData} as const\n`,
  59. )
  60. console.log("Generated models-snapshot.ts")
  61. const singleFlag = process.argv.includes("--single")
  62. const baselineFlag = process.argv.includes("--baseline")
  63. const skipInstall = process.argv.includes("--skip-install")
  64. const allTargets: {
  65. os: string
  66. arch: "arm64" | "x64"
  67. abi?: "musl"
  68. avx2?: false
  69. }[] = [
  70. {
  71. os: "linux",
  72. arch: "arm64",
  73. },
  74. {
  75. os: "linux",
  76. arch: "x64",
  77. },
  78. {
  79. os: "darwin",
  80. arch: "arm64",
  81. },
  82. {
  83. os: "darwin",
  84. arch: "x64",
  85. },
  86. {
  87. os: "win32",
  88. arch: "x64",
  89. },
  90. ]
  91. const targets = singleFlag
  92. ? allTargets.filter((item) => {
  93. if (item.os !== process.platform || item.arch !== process.arch) {
  94. return false
  95. }
  96. // When building for the current platform, prefer a single native binary by default.
  97. // Baseline binaries require additional Bun artifacts and can be flaky to download.
  98. if (item.avx2 === false) {
  99. return baselineFlag
  100. }
  101. // also skip abi-specific builds for the same reason
  102. if (item.abi !== undefined) {
  103. return false
  104. }
  105. return true
  106. })
  107. : allTargets
  108. await fs.rm("dist", { recursive: true, force: true })
  109. const binaries: Record<string, string> = {}
  110. if (!skipInstall) {
  111. await $`bun install --os="*" --cpu="*" @opentui/core@${pkg.dependencies["@opentui/core"]}`
  112. await $`bun install --os="*" --cpu="*" @parcel/watcher@${pkg.dependencies["@parcel/watcher"]}`
  113. }
  114. for (const item of targets) {
  115. const name = [
  116. pkg.name,
  117. // changing to win32 flags npm for some reason
  118. item.os === "win32" ? "windows" : item.os,
  119. item.arch,
  120. item.avx2 === false ? "baseline" : undefined,
  121. item.abi === undefined ? undefined : item.abi,
  122. ]
  123. .filter(Boolean)
  124. .join("-")
  125. console.log(`building ${name}`)
  126. await fs.mkdir(`dist/${name}/bin`, { recursive: true })
  127. const opentuiCoreEntry = require.resolve("@opentui/core")
  128. const parserWorker = nodefs.realpathSync(path.join(path.dirname(opentuiCoreEntry), "parser.worker.js"))
  129. const workerPath = "./src/cli/cmd/tui/worker.ts"
  130. // Use platform-specific bunfs root path based on target OS
  131. const bunfsRoot = item.os === "win32" ? "B:/~BUN/root/" : "/$bunfs/root/"
  132. const workerRelativePath = path.relative(dir, parserWorker).replaceAll("\\", "/")
  133. await Bun.build({
  134. conditions: ["browser"],
  135. tsconfig: "./tsconfig.json",
  136. plugins: [solidPlugin],
  137. sourcemap: "external",
  138. compile: {
  139. autoloadBunfig: false,
  140. autoloadDotenv: false,
  141. //@ts-ignore (bun types aren't up to date)
  142. autoloadTsconfig: true,
  143. autoloadPackageJson: true,
  144. target: name.replace(pkg.name, "bun") as any,
  145. outfile: `dist/${name}/bin/opencode`,
  146. execArgv: [`--user-agent=opencode/${Script.version}`, "--use-system-ca", "--"],
  147. windows: {},
  148. },
  149. entrypoints: ["./src/index.ts", parserWorker, workerPath],
  150. define: {
  151. OPENCODE_VERSION: `'${Script.version}'`,
  152. OTUI_TREE_SITTER_WORKER_PATH: bunfsRoot + workerRelativePath,
  153. OPENCODE_WORKER_PATH: workerPath,
  154. OPENCODE_CHANNEL: `'${Script.channel}'`,
  155. OPENCODE_LIBC: item.os === "linux" ? `'${item.abi ?? "glibc"}'` : "",
  156. },
  157. })
  158. await fs.rm(`./dist/${name}/bin/tui`, { recursive: true, force: true })
  159. await Bun.file(`dist/${name}/package.json`).write(
  160. JSON.stringify(
  161. {
  162. name,
  163. version: Script.version,
  164. os: [item.os],
  165. cpu: [item.arch],
  166. },
  167. null,
  168. 2,
  169. ),
  170. )
  171. binaries[name] = Script.version
  172. }
  173. export { binaries }