postinstall.mjs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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 = "windows"
  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 === "windows" ? "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. if (os.platform() === "win32") {
  64. console.log("Windows detected, skipping postinstall")
  65. return
  66. }
  67. const binaryPath = findBinary()
  68. const binScript = path.join(__dirname, "bin", "opencode")
  69. // Remove existing bin script if it exists
  70. if (fs.existsSync(binScript)) {
  71. fs.unlinkSync(binScript)
  72. }
  73. // Create symlink to the actual binary
  74. fs.symlinkSync(binaryPath, binScript)
  75. console.log(`opencode binary symlinked: ${binScript} -> ${binaryPath}`)
  76. } catch (error) {
  77. console.error("Failed to create opencode binary symlink:", error.message)
  78. process.exit(1)
  79. }
  80. }
  81. main()