Files
planet/client/scripts/dist-target.mjs
T
linkong 6d310f4dbe
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
release: bump version to 0.80.3
2026-11-30 14:35:38 +08:00

339 lines
12 KiB
JavaScript

import { spawnSync } from 'node:child_process'
import {
chmodSync,
copyFileSync,
cpSync,
existsSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
writeFileSync,
} from 'node:fs'
import { homedir, tmpdir } from 'node:os'
import { delimiter, dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = dirname(fileURLToPath(import.meta.url))
const desktopRoot = join(__dirname, '..')
const builderBin = join(
desktopRoot,
'node_modules/.bin',
process.platform === 'win32' ? 'electron-builder.cmd' : 'electron-builder',
)
const env = {
...process.env,
ELECTRON_MIRROR: process.env.ELECTRON_MIRROR || 'https://cdn.npmmirror.com/binaries/electron/',
ELECTRON_BUILDER_BINARIES_MIRROR:
process.env.ELECTRON_BUILDER_BINARIES_MIRROR ||
'https://registry.npmmirror.com/-/binary/electron-builder-binaries/',
}
const rawArgs = process.argv.slice(2)
const mode = rawArgs[0] || '--dir'
function hasCommand(cmd, customEnv = env) {
const probe = process.platform === 'win32'
? spawnSync('where.exe', [cmd], { env: customEnv, stdio: 'ignore' })
: spawnSync('which', [cmd], { env: customEnv, stdio: 'ignore' })
return probe.status === 0
}
function findNvmBinDir() {
const nvmVersionsDir = join(homedir(), '.nvm', 'versions', 'node')
if (!existsSync(nvmVersionsDir)) return null
try {
const dirs = readdirSync(nvmVersionsDir).sort().reverse()
for (const dir of dirs) {
const binDir = join(nvmVersionsDir, dir, 'bin')
if (existsSync(join(binDir, 'npm'))) {
return binDir
}
}
} catch {
return null
}
return null
}
function prepareBuilderEnv() {
const preparedEnv = { ...env }
if (process.platform === 'win32') {
return { buildEnv: preparedEnv, cleanup: () => {} }
}
if (hasCommand('npm', preparedEnv)) {
return { buildEnv: preparedEnv, cleanup: () => {} }
}
const nvmBin = findNvmBinDir()
if (nvmBin) {
preparedEnv.PATH = preparedEnv.PATH ? `${nvmBin}${delimiter}${preparedEnv.PATH}` : nvmBin
if (hasCommand('npm', preparedEnv)) {
return { buildEnv: preparedEnv, cleanup: () => {} }
}
}
// Pure-Bun environment fallback: client has no runtime dependencies, so a
// minimal npm shim satisfies electron-builder v26's NodeModulesCollector lookup
// when bun.lock (text) is present without Node/npm installed.
const pkg = JSON.parse(readFileSync(join(desktopRoot, 'package.json'), 'utf8'))
const shimDir = mkdtempSync(join(tmpdir(), 'planet-eb-npm-'))
const shimPath = join(shimDir, 'npm')
const jsonPayload = JSON.stringify({
name: pkg.name || 'planet-client',
version: pkg.version || '0.0.0',
dependencies: {},
})
writeFileSync(
shimPath,
`#!/usr/bin/env sh\nprintf '%s\\n' '${jsonPayload.replace(/'/g, "'\\''")}'\n`,
'utf8',
)
chmodSync(shimPath, 0o755)
preparedEnv.PATH = preparedEnv.PATH ? `${shimDir}${delimiter}${preparedEnv.PATH}` : shimDir
return {
buildEnv: preparedEnv,
cleanup: () => {
rmSync(shimDir, { recursive: true, force: true })
},
}
}
function runBuilder(builderArgs) {
const { buildEnv, cleanup } = prepareBuilderEnv()
try {
const result = spawnSync(builderBin, [...builderArgs, '--publish', 'never'], {
cwd: desktopRoot,
env: buildEnv,
stdio: 'inherit',
shell: process.platform === 'win32',
})
if ((result.status ?? 1) !== 0) {
process.exit(result.status ?? 1)
}
} finally {
cleanup()
}
}
function isWsl() {
return process.platform === 'linux' && Boolean(process.env.WSL_DISTRO_NAME || existsSync('/proc/sys/fs/binfmt_misc/WSLInterop'))
}
function resolveLinuxTargets() {
const targets = []
if (hasCommand('mksquashfs')) targets.push('AppImage')
if (hasCommand('dpkg-deb')) targets.push('deb')
if (targets.length === 0) targets.push('tar.gz')
return targets
}
function toWslPath(winPath) {
if (!winPath) return ''
const res = spawnSync('wslpath', ['-u', winPath], { encoding: 'utf8' })
return res.status === 0 ? (res.stdout || '').trim() : ''
}
function toWinPath(linuxPath) {
const res = spawnSync('wslpath', ['-w', linuxPath], { encoding: 'utf8' })
return res.status === 0 ? (res.stdout || '').trim() : ''
}
function resolveElectronVersion() {
try {
const pkg = JSON.parse(readFileSync(join(desktopRoot, 'package.json'), 'utf8'))
const raw = String(pkg?.devDependencies?.electron || '').replace(/^[^0-9]*/, '')
return raw || ''
} catch {
return ''
}
}
function runWinViaWindowsHost() {
if (!isWsl()) return false
const winProbeScript = [
'$env:PLANET_WIN_BUN_EXE',
'(Get-Command bun.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source)',
'(Join-Path $env:USERPROFILE ".bun\\bin\\bun.exe")',
'(Join-Path $env:USERPROFILE "scoop\\shims\\bun.exe")',
'(Join-Path $env:LOCALAPPDATA "bun\\bin\\bun.exe")',
'@(Get-ChildItem (Join-Path $env:LOCALAPPDATA "PlanetReleaseBuild\\*\\tools\\bun.exe") -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -ExpandProperty FullName)',
].join(', ')
const probePs = [
`$candidates = @(${winProbeScript}) | Where-Object { $_ -and (Test-Path -LiteralPath $_) }`,
'$bunPath = $candidates | Select-Object -First 1',
'$cacheDirs = @((Get-ChildItem (Join-Path $env:LOCALAPPDATA "PlanetReleaseBuild\\*\\electron-cache") -Directory -ErrorAction SilentlyContinue | Sort-Object LastWriteTime -Descending | Select-Object -ExpandProperty FullName), (Join-Path $env:LOCALAPPDATA "electron\\Cache")) | Where-Object { $_ -and (Test-Path -LiteralPath $_) }',
'$cacheHit = $cacheDirs | Where-Object { Get-ChildItem $_ -Filter "electron-v*-win32-x64.zip" -ErrorAction SilentlyContinue } | Select-Object -First 1',
'Write-Output ("LOCALAPPDATA=" + $env:LOCALAPPDATA)',
'Write-Output ("BUN=" + $bunPath)',
'Write-Output ("ELECTRON_CACHE=" + $cacheHit)',
].join('; ')
const probe = spawnSync('powershell.exe', ['-NoProfile', '-Command', probePs], { encoding: 'utf8' })
if (probe.status !== 0) return false
const info = {}
for (const line of (probe.stdout || '').split(/\r?\n/)) {
const idx = line.indexOf('=')
if (idx > 0) info[line.slice(0, idx).trim()] = line.slice(idx + 1).trim()
}
const winBunPath = info.BUN || ''
const winLocalAppData = info.LOCALAPPDATA || ''
if (!winBunPath || !winLocalAppData) return false
const localAppDataWsl = toWslPath(winLocalAppData)
if (!localAppDataWsl) return false
const releaseOutDir = join(desktopRoot, 'release')
mkdirSync(releaseOutDir, { recursive: true })
const stageRoot = join(localAppDataWsl, 'PlanetReleaseBuild', `wsl-stage-${process.pid}`)
const stageClient = join(stageRoot, 'client')
const stageRelease = join(stageClient, 'release')
const stageCache = join(stageRoot, 'electron-cache')
mkdirSync(stageClient, { recursive: true })
let winElectronDist = info.ELECTRON_CACHE || ''
const electronVer = resolveElectronVersion()
const wslElectronZip = electronVer ? join(homedir(), '.cache', 'electron', `electron-v${electronVer}-win32-x64.zip`) : ''
if (!winElectronDist && wslElectronZip && existsSync(wslElectronZip)) {
mkdirSync(stageCache, { recursive: true })
copyFileSync(wslElectronZip, join(stageCache, `electron-v${electronVer}-win32-x64.zip`))
winElectronDist = toWinPath(stageCache)
}
try {
console.log(`WSL2 detected; staging Windows NSIS + zip build on NTFS via ${winBunPath}...`)
for (const rel of ['package.json', 'bun.lock', 'electron-builder.yml', 'dist-electron', '.earth-bundle', 'resources', 'scripts']) {
const src = join(desktopRoot, rel)
if (!existsSync(src)) {
throw new Error(`Missing required client build asset for Windows staging: ${src}`)
}
cpSync(src, join(stageClient, rel), { recursive: true })
}
const winStageClient = toWinPath(stageClient)
if (!winStageClient) return false
const builderArgs = ['--win', 'nsis', 'zip', '--x64', '--publish', 'never']
if (winElectronDist) {
builderArgs.push(`--config.electronDist=${winElectronDist}`)
}
const psArgs = builderArgs.map((arg) => `'${arg.replace(/'/g, "''")}'`).join(' ')
const psScript = [
"$ErrorActionPreference = 'Stop'",
`$env:ELECTRON_MIRROR = '${env.ELECTRON_MIRROR}'`,
`$env:ELECTRON_BUILDER_BINARIES_MIRROR = '${env.ELECTRON_BUILDER_BINARIES_MIRROR}'`,
`Set-Location -LiteralPath '${winStageClient.replace(/'/g, "''")}'`,
`& '${winBunPath.replace(/'/g, "''")}' install --frozen-lockfile --ignore-scripts`,
'if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }',
`& '${winBunPath.replace(/'/g, "''")}' ./node_modules/electron-builder/cli.js ${psArgs}`,
'if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }',
].join('; ')
const winRun = spawnSync('powershell.exe', ['-NoProfile', '-Command', psScript], { stdio: 'inherit' })
if ((winRun.status ?? 1) !== 0 || !existsSync(stageRelease)) {
return false
}
let copied = 0
for (const entry of readdirSync(stageRelease)) {
if (entry.startsWith('__uninstaller-')) continue
if (entry.toLowerCase().endsWith('.exe') || entry.toLowerCase().endsWith('-win.zip')) {
copyFileSync(join(stageRelease, entry), join(releaseOutDir, entry))
copied += 1
}
}
return copied >= 2
} finally {
rmSync(stageRoot, { recursive: true, force: true })
}
}
function runWinViaDockerWine() {
if (!hasCommand('docker')) return false
const image = process.env.PLANET_ELECTRON_BUILDER_IMAGE || 'electronuserland/builder:wine'
const home = homedir()
const electronCache = join(home, '.cache', 'electron')
const builderCache = join(home, '.cache', 'electron-builder')
mkdirSync(electronCache, { recursive: true })
mkdirSync(builderCache, { recursive: true })
const uid = typeof process.getuid === 'function' ? process.getuid() : 0
const gid = typeof process.getgid === 'function' ? process.getgid() : 0
console.log(`Building Windows NSIS + zip installers via Docker Wine (${image})...`)
const dockerCmd = [
'run', '--rm',
'-v', `${desktopRoot}:/project`,
'-v', `${electronCache}:/root/.cache/electron`,
'-v', `${builderCache}:/root/.cache/electron-builder`,
'-e', `ELECTRON_MIRROR=${env.ELECTRON_MIRROR}`,
'-e', `ELECTRON_BUILDER_BINARIES_MIRROR=${env.ELECTRON_BUILDER_BINARIES_MIRROR}`,
'-w', '/project',
image,
'bash', '-lc',
`./node_modules/.bin/electron-builder --win nsis zip --publish never; status=$?; chown -R ${uid}:${gid} /project/release 2>/dev/null || true; exit $status`,
]
const res = spawnSync('docker', dockerCmd, { stdio: 'inherit' })
return (res.status ?? 1) === 0
}
function runWinBuild() {
if (process.platform === 'win32' || hasCommand('wine') || hasCommand('wine64')) {
runBuilder(['--win', 'nsis', 'zip'])
return
}
if (runWinViaWindowsHost()) {
return
}
if (runWinViaDockerWine()) {
return
}
if (process.env.PLANET_ALLOW_WIN_ZIP_FALLBACK === '1') {
console.warn('PLANET_ALLOW_WIN_ZIP_FALLBACK=1 set without Wine/Docker/Windows Bun: building win zip without NSIS .exe.')
runBuilder(['--win', 'zip', '--config.win.signAndEditExecutable=false'])
return
}
console.error(
'Unable to build Windows NSIS (.exe) installer: install Wine (wine64), enable Docker (electronuserland/builder:wine), or install Windows bun.exe (or set PLANET_ALLOW_WIN_ZIP_FALLBACK=1 for zip-only).',
)
process.exit(1)
}
function runMacBuild() {
if (process.platform === 'darwin') {
runBuilder(['--mac', 'dmg', 'zip'])
} else {
console.warn('Non-macOS host detected: building macOS zip bundle without dmg/codesign.')
runBuilder(['--mac', 'zip'])
}
}
if (mode === '--hotfix') {
const result = spawnSync(process.execPath, [join(__dirname, 'build-earth-bundle.mjs')], {
cwd: desktopRoot,
env,
stdio: 'inherit',
})
process.exit(result.status ?? 1)
} else if (mode === '--dir') {
runBuilder(['--dir'])
} else if (mode === '--linux') {
runBuilder(['--linux', ...resolveLinuxTargets()])
} else if (mode === '--mac') {
runMacBuild()
} else if (mode === '--win') {
runWinBuild()
} else if (mode === '--all') {
runBuilder(['--linux', ...resolveLinuxTargets()])
runWinBuild()
runMacBuild()
} else {
runBuilder(rawArgs)
}