build.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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 solidPlugin from "../node_modules/@opentui/solid/scripts/solid-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. import { Script } from "@opencode-ai/script"
  12. import pkg from "../package.json"
  13. const modelsUrl = process.env.OPENCODE_MODELS_URL || "https://models.dev"
  14. // Fetch and generate models.dev snapshot
  15. const modelsData = process.env.MODELS_DEV_API_JSON
  16. ? await Bun.file(process.env.MODELS_DEV_API_JSON).text()
  17. : await fetch(`${modelsUrl}/api.json`).then((x) => x.text())
  18. await Bun.write(
  19. path.join(dir, "src/provider/models-snapshot.ts"),
  20. `// Auto-generated by build.ts - do not edit\nexport const snapshot = ${modelsData} as const\n`,
  21. )
  22. console.log("Generated models-snapshot.ts")
  23. // Load migrations from migration directories
  24. const migrationDirs = (
  25. await fs.promises.readdir(path.join(dir, "migration"), {
  26. withFileTypes: true,
  27. })
  28. )
  29. .filter((entry) => entry.isDirectory() && /^\d{4}\d{2}\d{2}\d{2}\d{2}\d{2}/.test(entry.name))
  30. .map((entry) => entry.name)
  31. .sort()
  32. const migrations = await Promise.all(
  33. migrationDirs.map(async (name) => {
  34. const file = path.join(dir, "migration", name, "migration.sql")
  35. const sql = await Bun.file(file).text()
  36. const match = /^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/.exec(name)
  37. const timestamp = match
  38. ? Date.UTC(
  39. Number(match[1]),
  40. Number(match[2]) - 1,
  41. Number(match[3]),
  42. Number(match[4]),
  43. Number(match[5]),
  44. Number(match[6]),
  45. )
  46. : 0
  47. return { sql, timestamp }
  48. }),
  49. )
  50. console.log(`Loaded ${migrations.length} migrations`)
  51. const singleFlag = process.argv.includes("--single")
  52. const baselineFlag = process.argv.includes("--baseline")
  53. const skipInstall = process.argv.includes("--skip-install")
  54. const allTargets: {
  55. os: string
  56. arch: "arm64" | "x64"
  57. abi?: "musl"
  58. avx2?: false
  59. }[] = [
  60. {
  61. os: "linux",
  62. arch: "arm64",
  63. },
  64. {
  65. os: "linux",
  66. arch: "x64",
  67. },
  68. {
  69. os: "linux",
  70. arch: "x64",
  71. avx2: false,
  72. },
  73. {
  74. os: "linux",
  75. arch: "arm64",
  76. abi: "musl",
  77. },
  78. {
  79. os: "linux",
  80. arch: "x64",
  81. abi: "musl",
  82. },
  83. {
  84. os: "linux",
  85. arch: "x64",
  86. abi: "musl",
  87. avx2: false,
  88. },
  89. {
  90. os: "darwin",
  91. arch: "arm64",
  92. },
  93. {
  94. os: "darwin",
  95. arch: "x64",
  96. },
  97. {
  98. os: "darwin",
  99. arch: "x64",
  100. avx2: false,
  101. },
  102. {
  103. os: "win32",
  104. arch: "x64",
  105. },
  106. {
  107. os: "win32",
  108. arch: "x64",
  109. avx2: false,
  110. },
  111. ]
  112. const targets = singleFlag
  113. ? allTargets.filter((item) => {
  114. if (item.os !== process.platform || item.arch !== process.arch) {
  115. return false
  116. }
  117. // When building for the current platform, prefer a single native binary by default.
  118. // Baseline binaries require additional Bun artifacts and can be flaky to download.
  119. if (item.avx2 === false) {
  120. return baselineFlag
  121. }
  122. // also skip abi-specific builds for the same reason
  123. if (item.abi !== undefined) {
  124. return false
  125. }
  126. return true
  127. })
  128. : allTargets
  129. await $`rm -rf dist`
  130. const binaries: Record<string, string> = {}
  131. if (!skipInstall) {
  132. await $`bun install --os="*" --cpu="*" @opentui/core@${pkg.dependencies["@opentui/core"]}`
  133. await $`bun install --os="*" --cpu="*" @parcel/watcher@${pkg.dependencies["@parcel/watcher"]}`
  134. }
  135. for (const item of targets) {
  136. const name = [
  137. pkg.name,
  138. // changing to win32 flags npm for some reason
  139. item.os === "win32" ? "windows" : item.os,
  140. item.arch,
  141. item.avx2 === false ? "baseline" : undefined,
  142. item.abi === undefined ? undefined : item.abi,
  143. ]
  144. .filter(Boolean)
  145. .join("-")
  146. console.log(`building ${name}`)
  147. await $`mkdir -p dist/${name}/bin`
  148. const parserWorker = fs.realpathSync(path.resolve(dir, "./node_modules/@opentui/core/parser.worker.js"))
  149. const workerPath = "./src/cli/cmd/tui/worker.ts"
  150. // Use platform-specific bunfs root path based on target OS
  151. const bunfsRoot = item.os === "win32" ? "B:/~BUN/root/" : "/$bunfs/root/"
  152. const workerRelativePath = path.relative(dir, parserWorker).replaceAll("\\", "/")
  153. await Bun.build({
  154. conditions: ["browser"],
  155. tsconfig: "./tsconfig.json",
  156. plugins: [solidPlugin],
  157. sourcemap: "external",
  158. compile: {
  159. autoloadBunfig: false,
  160. autoloadDotenv: false,
  161. autoloadTsconfig: true,
  162. autoloadPackageJson: true,
  163. target: name.replace(pkg.name, "bun") as any,
  164. outfile: `dist/${name}/bin/opencode`,
  165. execArgv: [`--user-agent=opencode/${Script.version}`, "--use-system-ca", "--"],
  166. windows: {},
  167. },
  168. entrypoints: ["./src/index.ts", parserWorker, workerPath],
  169. define: {
  170. OPENCODE_VERSION: `'${Script.version}'`,
  171. OPENCODE_MIGRATIONS: JSON.stringify(migrations),
  172. OTUI_TREE_SITTER_WORKER_PATH: bunfsRoot + workerRelativePath,
  173. OPENCODE_WORKER_PATH: workerPath,
  174. OPENCODE_CHANNEL: `'${Script.channel}'`,
  175. OPENCODE_LIBC: item.os === "linux" ? `'${item.abi ?? "glibc"}'` : "",
  176. },
  177. })
  178. await $`rm -rf ./dist/${name}/bin/tui`
  179. await Bun.file(`dist/${name}/package.json`).write(
  180. JSON.stringify(
  181. {
  182. name,
  183. version: Script.version,
  184. os: [item.os],
  185. cpu: [item.arch],
  186. },
  187. null,
  188. 2,
  189. ),
  190. )
  191. binaries[name] = Script.version
  192. }
  193. if (Script.release) {
  194. for (const key of Object.keys(binaries)) {
  195. if (key.includes("linux")) {
  196. await $`tar -czf ../../${key}.tar.gz *`.cwd(`dist/${key}/bin`)
  197. } else {
  198. await $`zip -r ../../${key}.zip *`.cwd(`dist/${key}/bin`)
  199. }
  200. }
  201. await $`gh release upload v${Script.version} ./dist/*.zip ./dist/*.tar.gz --clobber --repo ${process.env.GH_REPO}`
  202. }
  203. export { binaries }