-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathbuild.ts
More file actions
369 lines (328 loc) · 15.3 KB
/
build.ts
File metadata and controls
369 lines (328 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
import 'dotenv/config'
import fs from 'fs'
import os from 'os'
import path from 'path'
import crypto from 'crypto'
import { promisify } from 'util'
import { exec as _exec, execSync } from 'child_process'
import { performance } from 'perf_hooks'
import chalk from 'chalk'
import yaml from 'js-yaml'
import { generateAndPublishMacDownloadJson, publishToS3 } from './s3-upload'
import { publishChangelogToApi, publishPatchNotesToDiscord } from './changelog-publish'
const exec = promisify(_exec)
const debug = process.argv.includes('--debug') || process.argv.includes('-d')
const buildOnlyInstaller = process.argv.includes('--installer') || process.argv.includes('-i')
const buildApplication = process.argv.includes('--application') || process.argv.includes('-app')
const buildNativeModules = process.argv.includes('--nativeModules') || process.argv.includes('-n')
const sendPatchNotesFlag = process.argv.includes('--sendPatchNotes') || process.argv.includes('-sp')
const publishChangelogFlag = process.argv.includes('--publish-changelog') || process.argv.includes('--publishChangelog')
const macX64Build = process.argv.includes('--mac-x64') || process.argv.includes('--mac-amd64') || process.argv.includes('-mx64')
const publishIndex = process.argv.findIndex(arg => arg === '--publish')
let publishBranch: string | null = null
if (publishIndex !== -1) {
if (process.argv.length > publishIndex + 1) {
const candidate = process.argv[publishIndex + 1].trim().toLowerCase()
if (/^[a-z0-9][a-z0-9-]*$/u.test(candidate)) {
publishBranch = candidate
} else {
console.error(
chalk.red(`[ERROR] Invalid publish branch "${candidate}". Use only letters, numbers, and dashes (e.g. beta, alpha, dev, tests).`),
)
process.exit(1)
}
} else {
console.error(chalk.red('[ERROR] No branch specified after --publish'))
process.exit(1)
}
}
enum LogLevel {
INFO = 'INFO',
SUCCESS = 'SUCCESS',
WARN = 'WARN',
ERROR = 'ERROR',
}
function log(level: LogLevel, message: string): void {
const ts = new Date().toLocaleString()
const tag = {
[LogLevel.INFO]: chalk.blue('[INFO] '),
[LogLevel.SUCCESS]: chalk.green('[SUCCESS]'),
[LogLevel.WARN]: chalk.yellow('[WARN] '),
[LogLevel.ERROR]: chalk.red('[ERROR]'),
}[level]
const out = `${chalk.gray(ts)} ${tag} ${message}`
if (level === LogLevel.ERROR) console.error(out)
else console.log(out)
}
function generateBuildInfo(): { version: string } {
const pkgPath = path.resolve(__dirname, '../package.json')
log(LogLevel.INFO, `Reading package.json from ${pkgPath}`)
const raw = fs.readFileSync(pkgPath, 'utf-8')
const pkg = JSON.parse(raw) as { version: string; buildInfo?: any; [key: string]: any }
let branchHash = 'unknown'
try {
branchHash = execSync('git rev-parse --short HEAD', { cwd: process.cwd() }).toString().trim()
} catch {
log(LogLevel.WARN, 'Failed to get Git hash')
}
pkg.buildInfo = {
VERSION: pkg.version,
BRANCH: branchHash,
BUILD_TIME: new Date().toLocaleString(),
}
let baseVersion = pkg.version.split('-')[0]
let newVersion = baseVersion
if (publishBranch) {
newVersion = `${baseVersion}-${publishBranch}`
pkg.version = newVersion
}
fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 4), 'utf-8')
log(LogLevel.SUCCESS, `Updated package.json → version=${newVersion}, buildInfo.BRANCH=${branchHash}`)
return { version: newVersion }
}
function getProductNameFromConfig(): string {
const builderBase = path.resolve(__dirname, '../electron-builder.yml')
try {
const cfgRaw = fs.readFileSync(builderBase, 'utf-8')
const cfg = yaml.load(cfgRaw) as any
if (cfg && typeof cfg.productName === 'string') {
return cfg.productName
}
} catch {}
return 'PulseSync'
}
async function runCommandStep(name: string, command: string): Promise<void> {
log(LogLevel.INFO, `Running step "${name}"…`)
const start = performance.now()
try {
const { stdout, stderr } = await exec(command, { maxBuffer: 10 * 1024 * 1024 })
const duration = ((performance.now() - start) / 1000).toFixed(2)
if (debug) {
if (stdout) process.stdout.write(stdout)
if (stderr) process.stderr.write(stderr)
}
log(LogLevel.SUCCESS, `Step "${name}" completed in ${duration}s`)
} catch (err: any) {
const duration = ((performance.now() - start) / 1000).toFixed(2)
log(LogLevel.ERROR, `Step "${name}" failed in ${duration}s`)
log(LogLevel.ERROR, `Command: ${chalk.yellow(command)}`)
if (err.stdout) process.stderr.write(chalk.yellow(err.stdout))
if (err.stderr) process.stderr.write(chalk.yellow(err.stderr))
process.exit(err.code ?? 1)
}
}
function applyConfigFromEnv() {
const configSource = process.env.APP_CONFIG
if (configSource) {
const appConfigPath = path.resolve(__dirname, '../src/common/appConfig.ts')
fs.writeFileSync(appConfigPath, configSource, 'utf-8')
log(LogLevel.SUCCESS, `Wrote ${appConfigPath}`)
}
}
function ensureNodeHeapForMac(): void {
if (os.platform() !== 'darwin') return
const currentOptions = process.env.NODE_OPTIONS ?? ''
if (/--max-old-space-size=\d+/u.test(currentOptions)) {
return
}
const defaultHeapMb = 6144
const nextOptions = `${currentOptions} --max-old-space-size=${defaultHeapMb}`.trim()
process.env.NODE_OPTIONS = nextOptions
log(LogLevel.WARN, `NODE_OPTIONS not set; defaulting to "${nextOptions}" to avoid macOS OOMs`)
}
function setConfigDevFalse(branch?: string) {
const configPath = path.resolve(__dirname, '../src/common/appConfig.ts')
let content = fs.readFileSync(configPath, 'utf-8')
content = content.replace(/export const isDev\s*=\s*.*$/m, 'export const isDev = false')
if (branch !== 'dev') {
content = content.replace(/export const isDevmark\s*=\s*.*$/m, 'export const isDevmark = false')
}
fs.writeFileSync(configPath, content, 'utf-8')
const devmarkStatus = branch === 'dev' ? ' (isDevmark kept for dev branch)' : ''
log(LogLevel.SUCCESS, `Set isDev to false in appConfig.ts${devmarkStatus}`)
}
function setConfigBranch(branch: string) {
const configPath = path.resolve(__dirname, '../src/common/appConfig.ts')
let content = fs.readFileSync(configPath, 'utf-8')
content = content.replace(/export const branch\s*=\s*.*$/m, `export const branch = "${branch}"`)
fs.writeFileSync(configPath, content, 'utf-8')
log(LogLevel.SUCCESS, `Set branch=${branch} in appConfig.ts`)
}
async function main(): Promise<void> {
if (sendPatchNotesFlag && !buildApplication) {
await publishPatchNotesToDiscord()
return
}
ensureNodeHeapForMac()
log(LogLevel.INFO, `APP_CONFIG length: ${process.env.APP_CONFIG?.length}`)
applyConfigFromEnv()
log(LogLevel.INFO, `Platform: ${os.platform()}, Arch: ${os.arch()}`)
log(LogLevel.INFO, `CWD: ${process.cwd()}`)
log(LogLevel.INFO, `Debug: ${debug ? 'ON' : 'OFF'}`)
log(LogLevel.INFO, `Installer only: ${buildOnlyInstaller ? 'YES' : 'NO'}`)
log(LogLevel.INFO, `Build native modules: ${buildNativeModules ? 'YES' : 'NO'}`)
log(LogLevel.INFO, `Build application: ${buildApplication ? 'YES' : 'NO'}`)
log(LogLevel.INFO, `Publish branch: ${publishBranch ?? 'none'}`)
if (os.platform() === 'darwin') {
log(LogLevel.INFO, `Mac target arch: ${macX64Build ? 'x64' : 'arm64'}`)
}
const branchForConfig = publishBranch ?? 'beta'
setConfigBranch(branchForConfig)
if (buildNativeModules) {
const nmDir = path.resolve(__dirname, '../nativeModules')
log(LogLevel.INFO, `Building native modules in ${nmDir}`)
const modules = fs.readdirSync(nmDir).filter(name => fs.statSync(path.join(nmDir, name)).isDirectory())
const windowsOnlyModules = new Set(['checkAccess'])
for (const mod of modules) {
const fullPath = path.join(nmDir, mod)
const packageJsonPath = path.join(fullPath, 'package.json')
if (!fs.existsSync(packageJsonPath)) {
log(LogLevel.WARN, `Skipping native module "${mod}" (package.json not found)`)
continue
}
if (os.platform() !== 'win32' && windowsOnlyModules.has(mod)) {
log(LogLevel.WARN, `Skipping native module "${mod}" (Windows-only)`)
continue
}
await runCommandStep(`nativeModules:${mod}`, `cd "${fullPath}" && yarn build`)
}
log(LogLevel.SUCCESS, 'All native modules built successfully')
}
if (!buildNativeModules && buildOnlyInstaller && !publishBranch) {
const productName = getProductNameFromConfig()
const pdPath =
os.platform() === 'darwin'
? path.join('.', 'out', macX64Build ? 'PulseSync-darwin-x64' : 'PulseSync-darwin-arm64')
: path.join('.', 'out', `PulseSync-${os.platform()}-${os.arch()}`)
const builderBase = path.resolve(__dirname, '../electron-builder.yml')
const baseYml = fs.readFileSync(builderBase, 'utf-8')
const configObj = yaml.load(baseYml) as any
if (os.platform() === 'darwin') {
configObj.dmg = configObj.dmg || {}
configObj.dmg.contents = [
{ x: 130, y: 220, type: 'file', path: path.resolve(pdPath, `${productName}.app`) },
{ x: 410, y: 220, type: 'link', path: '/Applications' },
]
}
const tmpName = `builder-override-${crypto.randomBytes(4).toString('hex')}.yml`
const tmpPath = path.join(os.tmpdir(), tmpName)
fs.writeFileSync(tmpPath, yaml.dump(configObj), 'utf-8')
await runCommandStep('Build (electron-builder)', `electron-builder --pd "${pdPath}" --config "${tmpPath}"`)
fs.unlinkSync(tmpPath)
log(LogLevel.SUCCESS, 'Done')
return
}
if (buildApplication) {
if (publishBranch) {
setConfigDevFalse(publishBranch)
if (os.platform() !== 'darwin') {
const appUpdateConfig = {
provider: 'generic',
url: `${process.env.S3_URL}/builds/app/${publishBranch}/`,
channel: 'latest',
updaterCacheDirName: 'pulsesyncapp-updater',
useMultipleRangeRequest: true,
}
const rootAppUpdatePath = path.resolve(__dirname, '../app-update.yml')
fs.writeFileSync(rootAppUpdatePath, yaml.dump(appUpdateConfig), 'utf-8')
log(LogLevel.SUCCESS, `Generated ${rootAppUpdatePath}`)
}
}
const baseOutDir = path.join('.', 'out')
const outDir = path.join(baseOutDir, `PulseSync-${os.platform()}-${os.arch()}`)
const releaseDir = path.join('.', 'release')
const { version } = generateBuildInfo()
if (os.platform() === 'darwin') {
const targetArch = macX64Build ? 'x64' : 'arm64'
await runCommandStep(`Package (electron-forge:${targetArch})`, `electron-forge package --arch ${targetArch}`)
} else {
await runCommandStep('Package (electron-forge)', 'electron-forge package')
const nativeDir = path.resolve(__dirname, '../nativeModules')
function copyNodes(srcDir: string) {
fs.readdirSync(srcDir, { withFileTypes: true }).forEach(entry => {
const fullPath = path.join(srcDir, entry.name)
if (entry.isDirectory()) {
copyNodes(fullPath)
} else if (entry.isFile() && path.extname(entry.name).toLowerCase() === '.node') {
const relativePath = path.relative(nativeDir, fullPath)
const dest = path.join(outDir, 'modules', relativePath)
fs.mkdirSync(path.dirname(dest), { recursive: true })
fs.copyFileSync(fullPath, dest)
log(LogLevel.SUCCESS, `Copied native module to ${dest}`)
}
})
}
copyNodes(nativeDir)
}
const outDirX64 = path.join(baseOutDir, `PulseSync-${os.platform()}-x64`)
const outDirARM64 = path.join(baseOutDir, `PulseSync-${os.platform()}-arm64`)
const builderBase = path.resolve(__dirname, '../electron-builder.yml')
const baseYml = fs.readFileSync(builderBase, 'utf-8')
const configObj = yaml.load(baseYml) as any
if (!configObj.linux) configObj.linux = {}
configObj.linux.executableName = 'pulsesync'
if (configObj.linux.desktop && configObj.linux.desktop.entry) {
if (configObj.linux.desktop.entry.Icon) {
configObj.linux.desktop.entry.Icon = 'pulsesync'
}
}
if (publishBranch) {
configObj.publish = [
{
provider: 'generic',
url: `${process.env.S3_URL}/builds/app/${publishBranch}/`,
channel: 'latest',
updaterCacheDirName: 'pulsesyncapp-updater',
useMultipleRangeRequest: true,
},
]
configObj.extraMetadata = configObj.extraMetadata || {}
configObj.extraMetadata.branch = publishBranch
configObj.extraMetadata.version = version
}
if (os.platform() === 'darwin') {
const productName = getProductNameFromConfig()
configObj.dmg = configObj.dmg || {}
configObj.dmg.contents = [
{ x: 130, y: 220, type: 'file', path: path.resolve(outDir, `${productName}.app`) },
{ x: 410, y: 220, type: 'link', path: '/Applications' },
]
}
const tmpName = `builder-override-${crypto.randomBytes(4).toString('hex')}.yml`
const tmpPath = path.join(os.tmpdir(), tmpName)
fs.writeFileSync(tmpPath, yaml.dump(configObj), 'utf-8')
if (os.platform() === 'darwin') {
if (macX64Build) {
await runCommandStep(
'Build (electron-builder:x64)',
`electron-builder --mac --x64 --pd "${outDirX64}" --config "${tmpPath}" --publish never`,
)
} else {
await runCommandStep(
'Build (electron-builder:arm64)',
`electron-builder --mac --arm64 --pd "${outDirARM64}" --config "${tmpPath}" --publish never`,
)
}
} else {
await runCommandStep(
'Build (electron-builder)',
`electron-builder --pd "${path.join('.', 'out', `PulseSync-${os.platform()}-${os.arch()}`)}" --config "${tmpPath}" --publish never`,
)
}
fs.unlinkSync(tmpPath)
if (publishBranch) {
await publishToS3(publishBranch, releaseDir, version)
if (os.platform() === 'darwin') {
await generateAndPublishMacDownloadJson(publishBranch, releaseDir, version)
}
if (publishChangelogFlag) {
await publishChangelogToApi(version)
}
}
log(LogLevel.SUCCESS, 'All steps completed successfully')
}
}
main().catch(err => {
log(LogLevel.ERROR, `Unexpected error: ${err.message || err}`)
process.exit(1)
})