2
0

build.ts 5.8 KB

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