postinstall.mjs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #!/usr/bin/env node
  2. import fs from "fs"
  3. import path from "path"
  4. import os from "os"
  5. import { fileURLToPath } from "url"
  6. import { createRequire } from "module"
  7. const __dirname = path.dirname(fileURLToPath(import.meta.url))
  8. const require = createRequire(import.meta.url)
  9. function detectPlatformAndArch() {
  10. // Map platform names
  11. let platform
  12. switch (os.platform()) {
  13. case "darwin":
  14. platform = "darwin"
  15. break
  16. case "linux":
  17. platform = "linux"
  18. break
  19. case "win32":
  20. platform = "win32"
  21. break
  22. default:
  23. platform = os.platform()
  24. break
  25. }
  26. // Map architecture names
  27. let arch
  28. switch (os.arch()) {
  29. case "x64":
  30. arch = "x64"
  31. break
  32. case "arm64":
  33. arch = "arm64"
  34. break
  35. case "arm":
  36. arch = "arm"
  37. break
  38. default:
  39. arch = os.arch()
  40. break
  41. }
  42. return { platform, arch }
  43. }
  44. function findBinary() {
  45. const { platform, arch } = detectPlatformAndArch()
  46. const packageName = `opencode-${platform}-${arch}`
  47. const binary = platform === "win32" ? "opencode.exe" : "opencode"
  48. try {
  49. // Use require.resolve to find the package
  50. const packageJsonPath = require.resolve(`${packageName}/package.json`)
  51. const packageDir = path.dirname(packageJsonPath)
  52. const binaryPath = path.join(packageDir, "bin", binary)
  53. if (!fs.existsSync(binaryPath)) {
  54. throw new Error(`Binary not found at ${binaryPath}`)
  55. }
  56. return binaryPath
  57. } catch (error) {
  58. throw new Error(`Could not find package ${packageName}: ${error.message}`)
  59. }
  60. }
  61. function main() {
  62. try {
  63. const binaryPath = findBinary()
  64. const binScript = path.join(__dirname, "bin", "opencode")
  65. // Remove existing bin script if it exists
  66. if (fs.existsSync(binScript)) {
  67. fs.unlinkSync(binScript)
  68. }
  69. // Create symlink to the actual binary
  70. fs.symlinkSync(binaryPath, binScript)
  71. console.log(`opencode binary symlinked: ${binScript} -> ${binaryPath}`)
  72. } catch (error) {
  73. console.error("Failed to create opencode binary symlink:", error.message)
  74. process.exit(1)
  75. }
  76. }
  77. main()