build.ts 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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") || (!!process.env.CI && !process.argv.includes("--all"))
  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: "win32",
  99. arch: "x64",
  100. },
  101. {
  102. os: "win32",
  103. arch: "x64",
  104. avx2: false,
  105. },
  106. ]
  107. const targets = singleFlag
  108. ? allTargets.filter((item) => {
  109. if (item.os !== process.platform || item.arch !== process.arch) {
  110. return false
  111. }
  112. // When building for the current platform, prefer a single native binary by default.
  113. // Baseline binaries require additional Bun artifacts and can be flaky to download.
  114. if (item.avx2 === false) {
  115. return baselineFlag
  116. }
  117. // also skip abi-specific builds for the same reason
  118. if (item.abi !== undefined) {
  119. return false
  120. }
  121. return true
  122. })
  123. : allTargets
  124. await $`rm -rf dist`
  125. const binaries: Record<string, string> = {}
  126. if (!skipInstall) {
  127. await $`bun install --os="*" --cpu="*" @opentui/core@${pkg.dependencies["@opentui/core"]}`
  128. await $`bun install --os="*" --cpu="*" @parcel/watcher@${pkg.dependencies["@parcel/watcher"]}`
  129. }
  130. for (const item of targets) {
  131. const name = [
  132. pkg.name,
  133. // changing to win32 flags npm for some reason
  134. item.os === "win32" ? "windows" : item.os,
  135. item.arch,
  136. item.avx2 === false ? "baseline" : undefined,
  137. item.abi === undefined ? undefined : item.abi,
  138. ]
  139. .filter(Boolean)
  140. .join("-")
  141. console.log(`building ${name}`)
  142. await $`mkdir -p dist/${name}/bin`
  143. const parserWorker = fs.realpathSync(path.resolve(dir, "./node_modules/@opentui/core/parser.worker.js"))
  144. const workerPath = "./src/cli/cmd/tui/worker.ts"
  145. // Use platform-specific bunfs root path based on target OS
  146. const bunfsRoot = item.os === "win32" ? "B:/~BUN/root/" : "/$bunfs/root/"
  147. const workerRelativePath = path.relative(dir, parserWorker).replaceAll("\\", "/")
  148. await Bun.build({
  149. conditions: ["browser"],
  150. tsconfig: "./tsconfig.json",
  151. plugins: [solidPlugin],
  152. sourcemap: "external",
  153. compile: {
  154. autoloadBunfig: false,
  155. autoloadDotenv: false,
  156. autoloadTsconfig: true,
  157. autoloadPackageJson: true,
  158. target: name.replace(pkg.name, "bun") as any,
  159. outfile: `dist/${name}/bin/opencode`,
  160. execArgv: [`--user-agent=opencode/${Script.version}`, "--use-system-ca", "--"],
  161. windows: {},
  162. },
  163. entrypoints: ["./src/index.ts", parserWorker, workerPath],
  164. define: {
  165. OPENCODE_VERSION: `'${Script.version}'`,
  166. OPENCODE_MIGRATIONS: JSON.stringify(migrations),
  167. OTUI_TREE_SITTER_WORKER_PATH: bunfsRoot + workerRelativePath,
  168. OPENCODE_WORKER_PATH: workerPath,
  169. OPENCODE_CHANNEL: `'${Script.channel}'`,
  170. OPENCODE_LIBC: item.os === "linux" ? `'${item.abi ?? "glibc"}'` : "",
  171. },
  172. })
  173. await $`rm -rf ./dist/${name}/bin/tui`
  174. await Bun.file(`dist/${name}/package.json`).write(
  175. JSON.stringify(
  176. {
  177. name,
  178. version: Script.version,
  179. os: [item.os],
  180. cpu: [item.arch],
  181. },
  182. null,
  183. 2,
  184. ),
  185. )
  186. binaries[name] = Script.version
  187. }
  188. if (Script.release) {
  189. for (const key of Object.keys(binaries)) {
  190. if (key.includes("linux")) {
  191. await $`tar -czf ../../${key}.tar.gz *`.cwd(`dist/${key}/bin`)
  192. } else {
  193. await $`zip -r ../../${key}.zip *`.cwd(`dist/${key}/bin`)
  194. }
  195. }
  196. await $`gh release upload v${Script.version} ./dist/*.zip ./dist/*.tar.gz --clobber --repo ${process.env.GH_REPO}`
  197. }
  198. export { binaries }