@wyxos/zephyr 0.2.17 → 0.2.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.mjs DELETED
@@ -1,2135 +0,0 @@
1
- import fs from 'node:fs/promises'
2
- import path from 'node:path'
3
- import { spawn } from 'node:child_process'
4
- import os from 'node:os'
5
- import process from 'node:process'
6
- import crypto from 'node:crypto'
7
- import chalk from 'chalk'
8
- import inquirer from 'inquirer'
9
- import { NodeSSH } from 'node-ssh'
10
- import { releaseNode } from './release-node.mjs'
11
- import { releasePackagist } from './release-packagist.mjs'
12
- import { validateLocalDependencies } from './dependency-scanner.mjs'
13
- import { checkAndUpdateVersion } from './version-checker.mjs'
14
-
15
- const IS_WINDOWS = process.platform === 'win32'
16
-
17
- const PROJECT_CONFIG_DIR = '.zephyr'
18
- const PROJECT_CONFIG_FILE = 'config.json'
19
- const GLOBAL_CONFIG_DIR = path.join(os.homedir(), '.config', 'zephyr')
20
- const SERVERS_FILE = path.join(GLOBAL_CONFIG_DIR, 'servers.json')
21
- const PROJECT_LOCK_FILE = 'deploy.lock'
22
- const PENDING_TASKS_FILE = 'pending-tasks.json'
23
- const RELEASE_SCRIPT_NAME = 'release'
24
- const RELEASE_SCRIPT_COMMAND = 'npx @wyxos/zephyr@latest'
25
-
26
- const logProcessing = (message = '') => console.log(chalk.yellow(message))
27
- const logSuccess = (message = '') => console.log(chalk.green(message))
28
- const logWarning = (message = '') => console.warn(chalk.yellow(message))
29
- const logError = (message = '') => console.error(chalk.red(message))
30
-
31
- let logFilePath = null
32
-
33
- async function getLogFilePath(rootDir) {
34
- if (logFilePath) {
35
- return logFilePath
36
- }
37
-
38
- const configDir = getProjectConfigDir(rootDir)
39
- await ensureDirectory(configDir)
40
-
41
- const now = new Date()
42
- const dateStr = now.toISOString().replace(/:/g, '-').replace(/\..+/, '')
43
- logFilePath = path.join(configDir, `${dateStr}.log`)
44
-
45
- return logFilePath
46
- }
47
-
48
- async function writeToLogFile(rootDir, message) {
49
- const logPath = await getLogFilePath(rootDir)
50
- const timestamp = new Date().toISOString()
51
- await fs.appendFile(logPath, `${timestamp} - ${message}\n`)
52
- }
53
-
54
- async function closeLogFile() {
55
- logFilePath = null
56
- }
57
-
58
- async function cleanupOldLogs(rootDir) {
59
- const configDir = getProjectConfigDir(rootDir)
60
-
61
- try {
62
- const files = await fs.readdir(configDir)
63
- const logFiles = files
64
- .filter((file) => file.endsWith('.log'))
65
- .map((file) => ({
66
- name: file,
67
- path: path.join(configDir, file)
68
- }))
69
-
70
- if (logFiles.length <= 3) {
71
- return
72
- }
73
-
74
- // Get file stats and sort by modification time (newest first)
75
- const filesWithStats = await Promise.all(
76
- logFiles.map(async (file) => {
77
- const stats = await fs.stat(file.path)
78
- return {
79
- ...file,
80
- mtime: stats.mtime
81
- }
82
- })
83
- )
84
-
85
- filesWithStats.sort((a, b) => b.mtime - a.mtime)
86
-
87
- // Keep the 3 newest, delete the rest
88
- const filesToDelete = filesWithStats.slice(3)
89
-
90
- for (const file of filesToDelete) {
91
- try {
92
- await fs.unlink(file.path)
93
- } catch (_error) {
94
- // Ignore errors when deleting old logs
95
- }
96
- }
97
- } catch (error) {
98
- // Ignore errors during log cleanup
99
- if (error.code !== 'ENOENT') {
100
- // Only log if it's not a "directory doesn't exist" error
101
- }
102
- }
103
- }
104
-
105
- const createSshClient = () => {
106
- if (typeof globalThis !== 'undefined' && globalThis.__zephyrSSHFactory) {
107
- return globalThis.__zephyrSSHFactory()
108
- }
109
-
110
- return new NodeSSH()
111
- }
112
-
113
- const runPrompt = async (questions) => {
114
- if (typeof globalThis !== 'undefined' && globalThis.__zephyrPrompt) {
115
- return globalThis.__zephyrPrompt(questions)
116
- }
117
-
118
- return inquirer.prompt(questions)
119
- }
120
-
121
- async function runCommand(command, args, { silent = false, cwd } = {}) {
122
- return new Promise((resolve, reject) => {
123
- const spawnOptions = {
124
- stdio: silent ? 'ignore' : 'inherit',
125
- cwd
126
- }
127
-
128
- // On Windows, use shell for commands that might need PATH resolution (php, composer, etc.)
129
- // Git commands work fine without shell
130
- if (IS_WINDOWS && command !== 'git') {
131
- spawnOptions.shell = true
132
- }
133
-
134
- const child = spawn(command, args, spawnOptions)
135
-
136
- child.on('error', reject)
137
- child.on('close', (code) => {
138
- if (code === 0) {
139
- resolve()
140
- } else {
141
- const error = new Error(`${command} exited with code ${code}`)
142
- error.exitCode = code
143
- reject(error)
144
- }
145
- })
146
- })
147
- }
148
-
149
- async function runCommandCapture(command, args, { cwd } = {}) {
150
- return new Promise((resolve, reject) => {
151
- let stdout = ''
152
- let stderr = ''
153
-
154
- const spawnOptions = {
155
- stdio: ['ignore', 'pipe', 'pipe'],
156
- cwd
157
- }
158
-
159
- // On Windows, use shell for commands that might need PATH resolution (php, composer, etc.)
160
- // Git commands work fine without shell
161
- if (IS_WINDOWS && command !== 'git') {
162
- spawnOptions.shell = true
163
- }
164
-
165
- const child = spawn(command, args, spawnOptions)
166
-
167
- child.stdout.on('data', (chunk) => {
168
- stdout += chunk
169
- })
170
-
171
- child.stderr.on('data', (chunk) => {
172
- stderr += chunk
173
- })
174
-
175
- child.on('error', reject)
176
- child.on('close', (code) => {
177
- if (code === 0) {
178
- resolve(stdout)
179
- } else {
180
- const error = new Error(`${command} exited with code ${code}: ${stderr.trim()}`)
181
- error.exitCode = code
182
- reject(error)
183
- }
184
- })
185
- })
186
- }
187
-
188
- async function getCurrentBranch(rootDir) {
189
- const output = await runCommandCapture('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
190
- cwd: rootDir
191
- })
192
-
193
- return output.trim()
194
- }
195
-
196
- async function getGitStatus(rootDir) {
197
- const output = await runCommandCapture('git', ['status', '--porcelain'], {
198
- cwd: rootDir
199
- })
200
-
201
- return output.trim()
202
- }
203
-
204
- function hasStagedChanges(statusOutput) {
205
- if (!statusOutput || statusOutput.length === 0) {
206
- return false
207
- }
208
-
209
- const lines = statusOutput.split('\n').filter((line) => line.trim().length > 0)
210
-
211
- return lines.some((line) => {
212
- const firstChar = line[0]
213
- // In git status --porcelain format:
214
- // - First char is space: unstaged changes (e.g., " M file")
215
- // - First char is '?': untracked files (e.g., "?? file")
216
- // - First char is letter (M, A, D, etc.): staged changes (e.g., "M file")
217
- // Only return true for staged changes, not unstaged or untracked
218
- return firstChar && firstChar !== ' ' && firstChar !== '?'
219
- })
220
- }
221
-
222
- async function getUpstreamRef(rootDir) {
223
- try {
224
- const output = await runCommandCapture('git', ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], {
225
- cwd: rootDir
226
- })
227
-
228
- const ref = output.trim()
229
- return ref.length > 0 ? ref : null
230
- } catch {
231
- return null
232
- }
233
- }
234
-
235
- async function ensureCommittedChangesPushed(targetBranch, rootDir) {
236
- const upstreamRef = await getUpstreamRef(rootDir)
237
-
238
- if (!upstreamRef) {
239
- logWarning(`Branch ${targetBranch} does not track a remote upstream; skipping automatic push of committed changes.`)
240
- return { pushed: false, upstreamRef: null }
241
- }
242
-
243
- const [remoteName, ...upstreamParts] = upstreamRef.split('/')
244
- const upstreamBranch = upstreamParts.join('/')
245
-
246
- if (!remoteName || !upstreamBranch) {
247
- logWarning(`Unable to determine remote destination for ${targetBranch}. Skipping automatic push.`)
248
- return { pushed: false, upstreamRef }
249
- }
250
-
251
- try {
252
- await runCommand('git', ['fetch', remoteName], { cwd: rootDir, silent: true })
253
- } catch (error) {
254
- logWarning(`Unable to fetch from ${remoteName} before push: ${error.message}`)
255
- }
256
-
257
- let remoteExists = true
258
-
259
- try {
260
- await runCommand('git', ['show-ref', '--verify', '--quiet', `refs/remotes/${upstreamRef}`], {
261
- cwd: rootDir,
262
- silent: true
263
- })
264
- } catch {
265
- remoteExists = false
266
- }
267
-
268
- let aheadCount = 0
269
- let behindCount = 0
270
-
271
- if (remoteExists) {
272
- const aheadOutput = await runCommandCapture('git', ['rev-list', '--count', `${upstreamRef}..HEAD`], {
273
- cwd: rootDir
274
- })
275
-
276
- aheadCount = parseInt(aheadOutput.trim() || '0', 10)
277
-
278
- const behindOutput = await runCommandCapture('git', ['rev-list', '--count', `HEAD..${upstreamRef}`], {
279
- cwd: rootDir
280
- })
281
-
282
- behindCount = parseInt(behindOutput.trim() || '0', 10)
283
- } else {
284
- aheadCount = 1
285
- }
286
-
287
- if (Number.isFinite(behindCount) && behindCount > 0) {
288
- throw new Error(
289
- `Local branch ${targetBranch} is behind ${upstreamRef} by ${behindCount} commit${behindCount === 1 ? '' : 's'}. Pull or rebase before deployment.`
290
- )
291
- }
292
-
293
- if (!Number.isFinite(aheadCount) || aheadCount <= 0) {
294
- return { pushed: false, upstreamRef }
295
- }
296
-
297
- const commitLabel = aheadCount === 1 ? 'commit' : 'commits'
298
- logProcessing(`Found ${aheadCount} ${commitLabel} not yet pushed to ${upstreamRef}. Pushing before deployment...`)
299
-
300
- await runCommand('git', ['push', remoteName, `${targetBranch}:${upstreamBranch}`], { cwd: rootDir })
301
- logSuccess(`Pushed committed changes to ${upstreamRef}.`)
302
-
303
- return { pushed: true, upstreamRef }
304
- }
305
-
306
- async function ensureLocalRepositoryState(targetBranch, rootDir = process.cwd()) {
307
- if (!targetBranch) {
308
- throw new Error('Deployment branch is not defined in the release configuration.')
309
- }
310
-
311
- const currentBranch = await getCurrentBranch(rootDir)
312
-
313
- if (!currentBranch) {
314
- throw new Error('Unable to determine the current git branch. Ensure this is a git repository.')
315
- }
316
-
317
- const initialStatus = await getGitStatus(rootDir)
318
- const hasPendingChanges = initialStatus.length > 0
319
-
320
- const statusReport = await runCommandCapture('git', ['status', '--short', '--branch'], {
321
- cwd: rootDir
322
- })
323
-
324
- const lines = statusReport.split(/\r?\n/)
325
- const branchLine = lines[0] || ''
326
- const aheadMatch = branchLine.match(/ahead (\d+)/)
327
- const behindMatch = branchLine.match(/behind (\d+)/)
328
- const aheadCount = aheadMatch ? parseInt(aheadMatch[1], 10) : 0
329
- const behindCount = behindMatch ? parseInt(behindMatch[1], 10) : 0
330
-
331
- if (aheadCount > 0) {
332
- logWarning(`Local branch ${currentBranch} is ahead of upstream by ${aheadCount} commit${aheadCount === 1 ? '' : 's'}.`)
333
- }
334
-
335
- if (behindCount > 0) {
336
- logProcessing(`Synchronizing local branch ${currentBranch} with its upstream...`)
337
- try {
338
- await runCommand('git', ['pull', '--ff-only'], { cwd: rootDir })
339
- logSuccess('Local branch fast-forwarded with upstream changes.')
340
- } catch (error) {
341
- throw new Error(
342
- `Unable to fast-forward ${currentBranch} with upstream changes. Resolve conflicts manually, then rerun the deployment.\n${error.message}`
343
- )
344
- }
345
- }
346
-
347
- if (currentBranch !== targetBranch) {
348
- if (hasPendingChanges) {
349
- throw new Error(
350
- `Local repository has uncommitted changes on ${currentBranch}. Commit or stash them before switching to ${targetBranch}.`
351
- )
352
- }
353
-
354
- logProcessing(`Switching local repository from ${currentBranch} to ${targetBranch}...`)
355
- await runCommand('git', ['checkout', targetBranch], { cwd: rootDir })
356
- logSuccess(`Checked out ${targetBranch} locally.`)
357
- }
358
-
359
- const statusAfterCheckout = currentBranch === targetBranch ? initialStatus : await getGitStatus(rootDir)
360
-
361
- if (statusAfterCheckout.length === 0) {
362
- await ensureCommittedChangesPushed(targetBranch, rootDir)
363
- logProcessing('Local repository is clean. Proceeding with deployment.')
364
- return
365
- }
366
-
367
- if (!hasStagedChanges(statusAfterCheckout)) {
368
- await ensureCommittedChangesPushed(targetBranch, rootDir)
369
- logProcessing('No staged changes detected. Unstaged or untracked files will not affect deployment. Proceeding with deployment.')
370
- return
371
- }
372
-
373
- logWarning(`Staged changes detected on ${targetBranch}. A commit is required before deployment.`)
374
-
375
- const { commitMessage } = await runPrompt([
376
- {
377
- type: 'input',
378
- name: 'commitMessage',
379
- message: 'Enter a commit message for pending changes before deployment',
380
- validate: (value) => (value && value.trim().length > 0 ? true : 'Commit message cannot be empty.')
381
- }
382
- ])
383
-
384
- const message = commitMessage.trim()
385
-
386
- logProcessing('Committing staged changes before deployment...')
387
- await runCommand('git', ['commit', '-m', message], { cwd: rootDir })
388
- await runCommand('git', ['push', 'origin', targetBranch], { cwd: rootDir })
389
- logSuccess(`Committed and pushed changes to origin/${targetBranch}.`)
390
-
391
- const finalStatus = await getGitStatus(rootDir)
392
-
393
- if (finalStatus.length > 0) {
394
- throw new Error('Local repository still has uncommitted changes after commit. Aborting deployment.')
395
- }
396
-
397
- await ensureCommittedChangesPushed(targetBranch, rootDir)
398
- logProcessing('Local repository is clean after committing pending changes.')
399
- }
400
-
401
- async function ensureProjectReleaseScript(rootDir) {
402
- const packageJsonPath = path.join(rootDir, 'package.json')
403
-
404
- let raw
405
- try {
406
- raw = await fs.readFile(packageJsonPath, 'utf8')
407
- } catch (error) {
408
- if (error.code === 'ENOENT') {
409
- return false
410
- }
411
-
412
- throw error
413
- }
414
-
415
- let packageJson
416
- try {
417
- packageJson = JSON.parse(raw)
418
- } catch (_error) {
419
- logWarning('Unable to parse package.json; skipping release script injection.')
420
- return false
421
- }
422
-
423
- const currentCommand = packageJson?.scripts?.[RELEASE_SCRIPT_NAME]
424
-
425
- if (currentCommand && currentCommand.includes('@wyxos/zephyr')) {
426
- return false
427
- }
428
-
429
- const { installReleaseScript } = await runPrompt([
430
- {
431
- type: 'confirm',
432
- name: 'installReleaseScript',
433
- message: 'Add "release" script to package.json that runs "npx @wyxos/zephyr@latest"?',
434
- default: true
435
- }
436
- ])
437
-
438
- if (!installReleaseScript) {
439
- return false
440
- }
441
-
442
- if (!packageJson.scripts || typeof packageJson.scripts !== 'object') {
443
- packageJson.scripts = {}
444
- }
445
-
446
- packageJson.scripts[RELEASE_SCRIPT_NAME] = RELEASE_SCRIPT_COMMAND
447
-
448
- const updatedPayload = `${JSON.stringify(packageJson, null, 2)}\n`
449
- await fs.writeFile(packageJsonPath, updatedPayload)
450
- logSuccess('Added release script to package.json.')
451
-
452
- let isGitRepo = false
453
-
454
- try {
455
- await runCommand('git', ['rev-parse', '--is-inside-work-tree'], { cwd: rootDir, silent: true })
456
- isGitRepo = true
457
- } catch (_error) {
458
- logWarning('Not a git repository; skipping commit for release script addition.')
459
- }
460
-
461
- if (isGitRepo) {
462
- try {
463
- await runCommand('git', ['add', 'package.json'], { cwd: rootDir, silent: true })
464
- await runCommand('git', ['commit', '-m', 'chore: add zephyr release script'], { cwd: rootDir, silent: true })
465
- logSuccess('Committed package.json release script addition.')
466
- } catch (error) {
467
- if (error.exitCode === 1) {
468
- logWarning('Git commit skipped: nothing to commit or pre-commit hook prevented commit.')
469
- } else {
470
- throw error
471
- }
472
- }
473
- }
474
-
475
- return true
476
- }
477
-
478
- function getProjectConfigDir(rootDir) {
479
- return path.join(rootDir, PROJECT_CONFIG_DIR)
480
- }
481
-
482
- function getPendingTasksPath(rootDir) {
483
- return path.join(getProjectConfigDir(rootDir), PENDING_TASKS_FILE)
484
- }
485
-
486
- function getLockFilePath(rootDir) {
487
- return path.join(getProjectConfigDir(rootDir), PROJECT_LOCK_FILE)
488
- }
489
-
490
- function createLockPayload() {
491
- return {
492
- user: os.userInfo().username,
493
- pid: process.pid,
494
- hostname: os.hostname(),
495
- startedAt: new Date().toISOString()
496
- }
497
- }
498
-
499
- async function acquireLocalLock(rootDir) {
500
- const lockPath = getLockFilePath(rootDir)
501
- const configDir = getProjectConfigDir(rootDir)
502
- await ensureDirectory(configDir)
503
-
504
- const payload = createLockPayload()
505
- const payloadJson = JSON.stringify(payload, null, 2)
506
- await fs.writeFile(lockPath, payloadJson, 'utf8')
507
-
508
- return payload
509
- }
510
-
511
- async function releaseLocalLock(rootDir) {
512
- const lockPath = getLockFilePath(rootDir)
513
- try {
514
- await fs.unlink(lockPath)
515
- } catch (error) {
516
- if (error.code !== 'ENOENT') {
517
- logWarning(`Failed to remove local lock file: ${error.message}`)
518
- }
519
- }
520
- }
521
-
522
- async function readLocalLock(rootDir) {
523
- const lockPath = getLockFilePath(rootDir)
524
- try {
525
- const content = await fs.readFile(lockPath, 'utf8')
526
- return JSON.parse(content)
527
- } catch (error) {
528
- if (error.code === 'ENOENT') {
529
- return null
530
- }
531
- throw error
532
- }
533
- }
534
-
535
- async function readRemoteLock(ssh, remoteCwd) {
536
- const lockPath = `.zephyr/${PROJECT_LOCK_FILE}`
537
- const escapedLockPath = lockPath.replace(/'/g, "'\\''")
538
- const checkCommand = `mkdir -p .zephyr && if [ -f '${escapedLockPath}' ]; then cat '${escapedLockPath}'; else echo "LOCK_NOT_FOUND"; fi`
539
-
540
- const checkResult = await ssh.execCommand(checkCommand, { cwd: remoteCwd })
541
-
542
- if (checkResult.stdout && checkResult.stdout.trim() !== 'LOCK_NOT_FOUND' && checkResult.stdout.trim() !== '') {
543
- try {
544
- return JSON.parse(checkResult.stdout.trim())
545
- } catch (_error) {
546
- return { raw: checkResult.stdout.trim() }
547
- }
548
- }
549
-
550
- return null
551
- }
552
-
553
- async function compareLocksAndPrompt(rootDir, ssh, remoteCwd) {
554
- const localLock = await readLocalLock(rootDir)
555
- const remoteLock = await readRemoteLock(ssh, remoteCwd)
556
-
557
- if (!localLock || !remoteLock) {
558
- return false
559
- }
560
-
561
- // Compare lock contents - if they match, it's likely stale
562
- const localKey = `${localLock.user}@${localLock.hostname}:${localLock.pid}:${localLock.startedAt}`
563
- const remoteKey = `${remoteLock.user}@${remoteLock.hostname}:${remoteLock.pid}:${remoteLock.startedAt}`
564
-
565
- if (localKey === remoteKey) {
566
- const startedBy = remoteLock.user ? `${remoteLock.user}@${remoteLock.hostname ?? 'unknown'}` : 'unknown user'
567
- const startedAt = remoteLock.startedAt ? ` at ${remoteLock.startedAt}` : ''
568
- const { shouldRemove } = await runPrompt([
569
- {
570
- type: 'confirm',
571
- name: 'shouldRemove',
572
- message: `Stale lock detected on server (started by ${startedBy}${startedAt}). This appears to be from a failed deployment. Remove it?`,
573
- default: true
574
- }
575
- ])
576
-
577
- if (shouldRemove) {
578
- const lockPath = `.zephyr/${PROJECT_LOCK_FILE}`
579
- const escapedLockPath = lockPath.replace(/'/g, "'\\''")
580
- const removeCommand = `rm -f '${escapedLockPath}'`
581
- await ssh.execCommand(removeCommand, { cwd: remoteCwd })
582
- await releaseLocalLock(rootDir)
583
- return true
584
- }
585
- }
586
-
587
- return false
588
- }
589
-
590
- async function acquireRemoteLock(ssh, remoteCwd, rootDir) {
591
- const lockPath = `.zephyr/${PROJECT_LOCK_FILE}`
592
- const escapedLockPath = lockPath.replace(/'/g, "'\\''")
593
- const checkCommand = `mkdir -p .zephyr && if [ -f '${escapedLockPath}' ]; then cat '${escapedLockPath}'; else echo "LOCK_NOT_FOUND"; fi`
594
-
595
- const checkResult = await ssh.execCommand(checkCommand, { cwd: remoteCwd })
596
-
597
- if (checkResult.stdout && checkResult.stdout.trim() !== 'LOCK_NOT_FOUND' && checkResult.stdout.trim() !== '') {
598
- // Check if we have a local lock and compare
599
- const localLock = await readLocalLock(rootDir)
600
- if (localLock) {
601
- const removed = await compareLocksAndPrompt(rootDir, ssh, remoteCwd)
602
- if (removed) {
603
- // Lock was removed, continue to create new one
604
- } else {
605
- // User chose not to remove, throw error
606
- let details = {}
607
- try {
608
- details = JSON.parse(checkResult.stdout.trim())
609
- } catch (_error) {
610
- details = { raw: checkResult.stdout.trim() }
611
- }
612
-
613
- const startedBy = details.user ? `${details.user}@${details.hostname ?? 'unknown'}` : 'unknown user'
614
- const startedAt = details.startedAt ? ` at ${details.startedAt}` : ''
615
- throw new Error(
616
- `Another deployment is currently in progress on the server (started by ${startedBy}${startedAt}). Remove ${remoteCwd}/${lockPath} if you are sure it is stale.`
617
- )
618
- }
619
- } else {
620
- // No local lock, but remote lock exists
621
- let details = {}
622
- try {
623
- details = JSON.parse(checkResult.stdout.trim())
624
- } catch (_error) {
625
- details = { raw: checkResult.stdout.trim() }
626
- }
627
-
628
- const startedBy = details.user ? `${details.user}@${details.hostname ?? 'unknown'}` : 'unknown user'
629
- const startedAt = details.startedAt ? ` at ${details.startedAt}` : ''
630
- throw new Error(
631
- `Another deployment is currently in progress on the server (started by ${startedBy}${startedAt}). Remove ${remoteCwd}/${lockPath} if you are sure it is stale.`
632
- )
633
- }
634
- }
635
-
636
- const payload = createLockPayload()
637
- const payloadJson = JSON.stringify(payload, null, 2)
638
- const payloadBase64 = Buffer.from(payloadJson).toString('base64')
639
- const createCommand = `mkdir -p .zephyr && echo '${payloadBase64}' | base64 --decode > '${escapedLockPath}'`
640
-
641
- const createResult = await ssh.execCommand(createCommand, { cwd: remoteCwd })
642
-
643
- if (createResult.code !== 0) {
644
- throw new Error(`Failed to create lock file on server: ${createResult.stderr}`)
645
- }
646
-
647
- // Create local lock as well
648
- await acquireLocalLock(rootDir)
649
-
650
- return lockPath
651
- }
652
-
653
- async function releaseRemoteLock(ssh, remoteCwd) {
654
- const lockPath = `.zephyr/${PROJECT_LOCK_FILE}`
655
- const escapedLockPath = lockPath.replace(/'/g, "'\\''")
656
- const removeCommand = `rm -f '${escapedLockPath}'`
657
-
658
- const result = await ssh.execCommand(removeCommand, { cwd: remoteCwd })
659
- if (result.code !== 0 && result.code !== 1) {
660
- logWarning(`Failed to remove lock file: ${result.stderr}`)
661
- }
662
- }
663
-
664
- async function loadPendingTasksSnapshot(rootDir) {
665
- const snapshotPath = getPendingTasksPath(rootDir)
666
-
667
- try {
668
- const raw = await fs.readFile(snapshotPath, 'utf8')
669
- return JSON.parse(raw)
670
- } catch (error) {
671
- if (error.code === 'ENOENT') {
672
- return null
673
- }
674
-
675
- throw error
676
- }
677
- }
678
-
679
- async function savePendingTasksSnapshot(rootDir, snapshot) {
680
- const configDir = getProjectConfigDir(rootDir)
681
- await ensureDirectory(configDir)
682
- const payload = `${JSON.stringify(snapshot, null, 2)}\n`
683
- await fs.writeFile(getPendingTasksPath(rootDir), payload)
684
- }
685
-
686
- async function clearPendingTasksSnapshot(rootDir) {
687
- try {
688
- await fs.unlink(getPendingTasksPath(rootDir))
689
- } catch (error) {
690
- if (error.code !== 'ENOENT') {
691
- throw error
692
- }
693
- }
694
- }
695
-
696
- async function ensureGitignoreEntry(rootDir) {
697
- const gitignorePath = path.join(rootDir, '.gitignore')
698
- const targetEntry = `${PROJECT_CONFIG_DIR}/`
699
- let existingContent = ''
700
-
701
- try {
702
- existingContent = await fs.readFile(gitignorePath, 'utf8')
703
- } catch (error) {
704
- if (error.code !== 'ENOENT') {
705
- throw error
706
- }
707
- }
708
-
709
- const hasEntry = existingContent
710
- .split(/\r?\n/)
711
- .some((line) => line.trim() === targetEntry)
712
-
713
- if (hasEntry) {
714
- return
715
- }
716
-
717
- const updatedContent = existingContent
718
- ? `${existingContent.replace(/\s*$/, '')}\n${targetEntry}\n`
719
- : `${targetEntry}\n`
720
-
721
- await fs.writeFile(gitignorePath, updatedContent)
722
- logSuccess('Added .zephyr/ to .gitignore')
723
-
724
- let isGitRepo = false
725
- try {
726
- await runCommand('git', ['rev-parse', '--is-inside-work-tree'], {
727
- silent: true,
728
- cwd: rootDir
729
- })
730
- isGitRepo = true
731
- } catch (_error) {
732
- logWarning('Not a git repository; skipping commit for .gitignore update.')
733
- }
734
-
735
- if (!isGitRepo) {
736
- return
737
- }
738
-
739
- try {
740
- await runCommand('git', ['add', '.gitignore'], { cwd: rootDir })
741
- await runCommand('git', ['commit', '-m', 'chore: ignore zephyr config'], { cwd: rootDir })
742
- } catch (error) {
743
- if (error.exitCode === 1) {
744
- logWarning('Git commit skipped: nothing to commit or pre-commit hook prevented commit.')
745
- } else {
746
- throw error
747
- }
748
- }
749
- }
750
-
751
- async function ensureDirectory(dirPath) {
752
- await fs.mkdir(dirPath, { recursive: true })
753
- }
754
-
755
- function generateId() {
756
- return crypto.randomBytes(8).toString('hex')
757
- }
758
-
759
- function migrateServers(servers) {
760
- if (!Array.isArray(servers)) {
761
- return []
762
- }
763
-
764
- let needsMigration = false
765
- const migrated = servers.map((server) => {
766
- if (!server.id) {
767
- needsMigration = true
768
- return {
769
- ...server,
770
- id: generateId()
771
- }
772
- }
773
- return server
774
- })
775
-
776
- return { servers: migrated, needsMigration }
777
- }
778
-
779
- function migrateApps(apps, servers) {
780
- if (!Array.isArray(apps)) {
781
- return { apps: [], needsMigration: false }
782
- }
783
-
784
- // Create a map of serverName -> serverId for migration
785
- const serverNameToId = new Map()
786
- servers.forEach((server) => {
787
- if (server.id && server.serverName) {
788
- serverNameToId.set(server.serverName, server.id)
789
- }
790
- })
791
-
792
- let needsMigration = false
793
- const migrated = apps.map((app) => {
794
- const updated = { ...app }
795
-
796
- if (!app.id) {
797
- needsMigration = true
798
- updated.id = generateId()
799
- }
800
-
801
- // Migrate serverName to serverId if needed
802
- if (app.serverName && !app.serverId) {
803
- const serverId = serverNameToId.get(app.serverName)
804
- if (serverId) {
805
- needsMigration = true
806
- updated.serverId = serverId
807
- }
808
- }
809
-
810
- return updated
811
- })
812
-
813
- return { apps: migrated, needsMigration }
814
- }
815
-
816
- function migratePresets(presets, apps) {
817
- if (!Array.isArray(presets)) {
818
- return { presets: [], needsMigration: false }
819
- }
820
-
821
- // Create a map of serverName:projectPath -> appId for migration
822
- const keyToAppId = new Map()
823
- apps.forEach((app) => {
824
- if (app.id && app.serverName && app.projectPath) {
825
- const key = `${app.serverName}:${app.projectPath}`
826
- keyToAppId.set(key, app.id)
827
- }
828
- })
829
-
830
- let needsMigration = false
831
- const migrated = presets.map((preset) => {
832
- const updated = { ...preset }
833
-
834
- // Migrate from key-based to appId-based if needed
835
- if (preset.key && !preset.appId) {
836
- const appId = keyToAppId.get(preset.key)
837
- if (appId) {
838
- needsMigration = true
839
- updated.appId = appId
840
- // Keep key for backward compatibility during transition, but it's deprecated
841
- }
842
- }
843
-
844
- return updated
845
- })
846
-
847
- return { presets: migrated, needsMigration }
848
- }
849
-
850
- async function loadServers() {
851
- try {
852
- const raw = await fs.readFile(SERVERS_FILE, 'utf8')
853
- const data = JSON.parse(raw)
854
- const servers = Array.isArray(data) ? data : []
855
-
856
- const { servers: migrated, needsMigration } = migrateServers(servers)
857
-
858
- if (needsMigration) {
859
- await saveServers(migrated)
860
- logSuccess('Migrated servers configuration to use unique IDs.')
861
- }
862
-
863
- return migrated
864
- } catch (error) {
865
- if (error.code === 'ENOENT') {
866
- return []
867
- }
868
-
869
- logWarning('Failed to read servers.json, starting with an empty list.')
870
- return []
871
- }
872
- }
873
-
874
- async function saveServers(servers) {
875
- await ensureDirectory(GLOBAL_CONFIG_DIR)
876
- const payload = JSON.stringify(servers, null, 2)
877
- await fs.writeFile(SERVERS_FILE, `${payload}\n`)
878
- }
879
-
880
- function getProjectConfigPath(rootDir) {
881
- return path.join(rootDir, PROJECT_CONFIG_DIR, PROJECT_CONFIG_FILE)
882
- }
883
-
884
- async function loadProjectConfig(rootDir, servers = []) {
885
- const configPath = getProjectConfigPath(rootDir)
886
-
887
- try {
888
- const raw = await fs.readFile(configPath, 'utf8')
889
- const data = JSON.parse(raw)
890
- const apps = Array.isArray(data?.apps) ? data.apps : []
891
- const presets = Array.isArray(data?.presets) ? data.presets : []
892
-
893
- // Migrate apps first (needs servers for serverName -> serverId mapping)
894
- const { apps: migratedApps, needsMigration: appsNeedMigration } = migrateApps(apps, servers)
895
-
896
- // Migrate presets (needs migrated apps for key -> appId mapping)
897
- const { presets: migratedPresets, needsMigration: presetsNeedMigration } = migratePresets(presets, migratedApps)
898
-
899
- if (appsNeedMigration || presetsNeedMigration) {
900
- await saveProjectConfig(rootDir, {
901
- apps: migratedApps,
902
- presets: migratedPresets
903
- })
904
- logSuccess('Migrated project configuration to use unique IDs.')
905
- }
906
-
907
- return {
908
- apps: migratedApps,
909
- presets: migratedPresets
910
- }
911
- } catch (error) {
912
- if (error.code === 'ENOENT') {
913
- return { apps: [], presets: [] }
914
- }
915
-
916
- logWarning('Failed to read .zephyr/config.json, starting with an empty list of apps.')
917
- return { apps: [], presets: [] }
918
- }
919
- }
920
-
921
- async function saveProjectConfig(rootDir, config) {
922
- const configDir = path.join(rootDir, PROJECT_CONFIG_DIR)
923
- await ensureDirectory(configDir)
924
- const payload = JSON.stringify(
925
- {
926
- apps: config.apps ?? [],
927
- presets: config.presets ?? []
928
- },
929
- null,
930
- 2
931
- )
932
- await fs.writeFile(path.join(configDir, PROJECT_CONFIG_FILE), `${payload}\n`)
933
- }
934
-
935
- function defaultProjectPath(currentDir) {
936
- return `~/webapps/${path.basename(currentDir)}`
937
- }
938
-
939
- async function listGitBranches(currentDir) {
940
- try {
941
- const output = await runCommandCapture(
942
- 'git',
943
- ['branch', '--format', '%(refname:short)'],
944
- { cwd: currentDir }
945
- )
946
-
947
- const branches = output
948
- .split(/\r?\n/)
949
- .map((line) => line.trim())
950
- .filter(Boolean)
951
-
952
- return branches.length ? branches : ['master']
953
- } catch (_error) {
954
- logWarning('Unable to read git branches; defaulting to master.')
955
- return ['master']
956
- }
957
- }
958
-
959
- async function listSshKeys() {
960
- const sshDir = path.join(os.homedir(), '.ssh')
961
-
962
- try {
963
- const entries = await fs.readdir(sshDir, { withFileTypes: true })
964
-
965
- const candidates = entries
966
- .filter((entry) => entry.isFile())
967
- .map((entry) => entry.name)
968
- .filter((name) => {
969
- if (!name) return false
970
- if (name.startsWith('.')) return false
971
- if (name.endsWith('.pub')) return false
972
- if (name.startsWith('known_hosts')) return false
973
- if (name === 'config') return false
974
- return name.trim().length > 0
975
- })
976
-
977
- const keys = []
978
-
979
- for (const name of candidates) {
980
- const filePath = path.join(sshDir, name)
981
- if (await isPrivateKeyFile(filePath)) {
982
- keys.push(name)
983
- }
984
- }
985
-
986
- return {
987
- sshDir,
988
- keys
989
- }
990
- } catch (error) {
991
- if (error.code === 'ENOENT') {
992
- return {
993
- sshDir,
994
- keys: []
995
- }
996
- }
997
-
998
- throw error
999
- }
1000
- }
1001
-
1002
- async function isPrivateKeyFile(filePath) {
1003
- try {
1004
- const content = await fs.readFile(filePath, 'utf8')
1005
- return /-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(content)
1006
- } catch (_error) {
1007
- return false
1008
- }
1009
- }
1010
-
1011
- async function promptSshDetails(currentDir, existing = {}) {
1012
- const { sshDir, keys: sshKeys } = await listSshKeys()
1013
- const defaultUser = existing.sshUser || os.userInfo().username
1014
- const fallbackKey = path.join(sshDir, 'id_rsa')
1015
- const preselectedKey = existing.sshKey || (sshKeys.length ? path.join(sshDir, sshKeys[0]) : fallbackKey)
1016
-
1017
- const sshKeyPrompt = sshKeys.length
1018
- ? {
1019
- type: 'list',
1020
- name: 'sshKeySelection',
1021
- message: 'SSH key',
1022
- choices: [
1023
- ...sshKeys.map((key) => ({ name: key, value: path.join(sshDir, key) })),
1024
- new inquirer.Separator(),
1025
- { name: 'Enter custom SSH key path…', value: '__custom' }
1026
- ],
1027
- default: preselectedKey
1028
- }
1029
- : {
1030
- type: 'input',
1031
- name: 'sshKeySelection',
1032
- message: 'SSH key path',
1033
- default: preselectedKey
1034
- }
1035
-
1036
- const answers = await runPrompt([
1037
- {
1038
- type: 'input',
1039
- name: 'sshUser',
1040
- message: 'SSH user',
1041
- default: defaultUser
1042
- },
1043
- sshKeyPrompt
1044
- ])
1045
-
1046
- let sshKey = answers.sshKeySelection
1047
-
1048
- if (sshKey === '__custom') {
1049
- const { customSshKey } = await runPrompt([
1050
- {
1051
- type: 'input',
1052
- name: 'customSshKey',
1053
- message: 'SSH key path',
1054
- default: preselectedKey
1055
- }
1056
- ])
1057
-
1058
- sshKey = customSshKey.trim() || preselectedKey
1059
- }
1060
-
1061
- return {
1062
- sshUser: answers.sshUser.trim() || defaultUser,
1063
- sshKey: sshKey.trim() || preselectedKey
1064
- }
1065
- }
1066
-
1067
- async function ensureSshDetails(config, currentDir) {
1068
- if (config.sshUser && config.sshKey) {
1069
- return false
1070
- }
1071
-
1072
- logProcessing('SSH details missing. Please provide them now.')
1073
- const details = await promptSshDetails(currentDir, config)
1074
- Object.assign(config, details)
1075
- return true
1076
- }
1077
-
1078
- function expandHomePath(targetPath) {
1079
- if (!targetPath) {
1080
- return targetPath
1081
- }
1082
-
1083
- if (targetPath.startsWith('~')) {
1084
- return path.join(os.homedir(), targetPath.slice(1))
1085
- }
1086
-
1087
- return targetPath
1088
- }
1089
-
1090
- async function resolveSshKeyPath(targetPath) {
1091
- const expanded = expandHomePath(targetPath)
1092
-
1093
- try {
1094
- await fs.access(expanded)
1095
- } catch (_error) {
1096
- throw new Error(`SSH key not accessible at ${expanded}`)
1097
- }
1098
-
1099
- return expanded
1100
- }
1101
-
1102
- function resolveRemotePath(projectPath, remoteHome) {
1103
- if (!projectPath) {
1104
- return projectPath
1105
- }
1106
-
1107
- const sanitizedHome = remoteHome.replace(/\/+$/, '')
1108
-
1109
- if (projectPath === '~') {
1110
- return sanitizedHome
1111
- }
1112
-
1113
- if (projectPath.startsWith('~/')) {
1114
- const remainder = projectPath.slice(2)
1115
- return remainder ? `${sanitizedHome}/${remainder}` : sanitizedHome
1116
- }
1117
-
1118
- if (projectPath.startsWith('/')) {
1119
- return projectPath
1120
- }
1121
-
1122
- return `${sanitizedHome}/${projectPath}`
1123
- }
1124
-
1125
- async function hasPrePushHook(rootDir) {
1126
- const hookPaths = [
1127
- path.join(rootDir, '.git', 'hooks', 'pre-push'),
1128
- path.join(rootDir, '.husky', 'pre-push'),
1129
- path.join(rootDir, '.githooks', 'pre-push')
1130
- ]
1131
-
1132
- for (const hookPath of hookPaths) {
1133
- try {
1134
- await fs.access(hookPath)
1135
- const stats = await fs.stat(hookPath)
1136
- if (stats.isFile()) {
1137
- return true
1138
- }
1139
- } catch {
1140
- // Hook doesn't exist at this path, continue checking
1141
- }
1142
- }
1143
-
1144
- return false
1145
- }
1146
-
1147
- async function hasLintScript(rootDir) {
1148
- try {
1149
- const packageJsonPath = path.join(rootDir, 'package.json')
1150
- const raw = await fs.readFile(packageJsonPath, 'utf8')
1151
- const packageJson = JSON.parse(raw)
1152
- return packageJson.scripts && typeof packageJson.scripts.lint === 'string'
1153
- } catch {
1154
- return false
1155
- }
1156
- }
1157
-
1158
- async function hasLaravelPint(rootDir) {
1159
- try {
1160
- const pintPath = path.join(rootDir, 'vendor', 'bin', 'pint')
1161
- await fs.access(pintPath)
1162
- const stats = await fs.stat(pintPath)
1163
- return stats.isFile()
1164
- } catch {
1165
- return false
1166
- }
1167
- }
1168
-
1169
- async function runLinting(rootDir) {
1170
- const hasNpmLint = await hasLintScript(rootDir)
1171
- const hasPint = await hasLaravelPint(rootDir)
1172
-
1173
- if (hasNpmLint) {
1174
- logProcessing('Running npm lint...')
1175
- await runCommand('npm', ['run', 'lint'], { cwd: rootDir })
1176
- logSuccess('Linting completed.')
1177
- return true
1178
- } else if (hasPint) {
1179
- logProcessing('Running Laravel Pint...')
1180
- await runCommand('php', ['vendor/bin/pint'], { cwd: rootDir })
1181
- logSuccess('Linting completed.')
1182
- return true
1183
- }
1184
-
1185
- return false
1186
- }
1187
-
1188
- async function hasUncommittedChanges(rootDir) {
1189
- const status = await getGitStatus(rootDir)
1190
- return status.length > 0
1191
- }
1192
-
1193
- async function commitLintingChanges(rootDir) {
1194
- const status = await getGitStatus(rootDir)
1195
-
1196
- if (!hasStagedChanges(status)) {
1197
- // Stage only modified tracked files (not untracked files)
1198
- await runCommand('git', ['add', '-u'], { cwd: rootDir })
1199
- const newStatus = await getGitStatus(rootDir)
1200
- if (!hasStagedChanges(newStatus)) {
1201
- return false
1202
- }
1203
- }
1204
-
1205
- logProcessing('Committing linting changes...')
1206
- await runCommand('git', ['commit', '-m', 'style: apply linting fixes'], { cwd: rootDir })
1207
- logSuccess('Linting changes committed.')
1208
- return true
1209
- }
1210
-
1211
- async function isLocalLaravelProject(rootDir) {
1212
- try {
1213
- const artisanPath = path.join(rootDir, 'artisan')
1214
- const composerPath = path.join(rootDir, 'composer.json')
1215
-
1216
- await fs.access(artisanPath)
1217
- const composerContent = await fs.readFile(composerPath, 'utf8')
1218
- const composerJson = JSON.parse(composerContent)
1219
-
1220
- return (
1221
- composerJson.require &&
1222
- typeof composerJson.require === 'object' &&
1223
- 'laravel/framework' in composerJson.require
1224
- )
1225
- } catch {
1226
- return false
1227
- }
1228
- }
1229
-
1230
- async function runRemoteTasks(config, options = {}) {
1231
- const { snapshot = null, rootDir = process.cwd() } = options
1232
-
1233
- await cleanupOldLogs(rootDir)
1234
- await ensureLocalRepositoryState(config.branch, rootDir)
1235
-
1236
- const isLaravel = await isLocalLaravelProject(rootDir)
1237
- const hasHook = await hasPrePushHook(rootDir)
1238
-
1239
- if (!hasHook) {
1240
- // Run linting before tests
1241
- const lintRan = await runLinting(rootDir)
1242
- if (lintRan) {
1243
- // Check if linting made changes and commit them
1244
- const hasChanges = await hasUncommittedChanges(rootDir)
1245
- if (hasChanges) {
1246
- await commitLintingChanges(rootDir)
1247
- }
1248
- }
1249
-
1250
- // Run tests for Laravel projects
1251
- if (isLaravel) {
1252
- logProcessing('Running Laravel tests locally...')
1253
- try {
1254
- await runCommand('php', ['artisan', 'test', '--compact'], { cwd: rootDir })
1255
- logSuccess('Local tests passed.')
1256
- } catch (error) {
1257
- throw new Error(`Local tests failed. Fix test failures before deploying. ${error.message}`)
1258
- }
1259
- }
1260
- } else {
1261
- logProcessing('Pre-push git hook detected. Skipping local linting and test execution.')
1262
- }
1263
-
1264
- const ssh = createSshClient()
1265
- const sshUser = config.sshUser || os.userInfo().username
1266
- const privateKeyPath = await resolveSshKeyPath(config.sshKey)
1267
- const privateKey = await fs.readFile(privateKeyPath, 'utf8')
1268
-
1269
- logProcessing(`\nConnecting to ${config.serverIp} as ${sshUser}...`)
1270
-
1271
- let lockAcquired = false
1272
-
1273
- try {
1274
- await ssh.connect({
1275
- host: config.serverIp,
1276
- username: sshUser,
1277
- privateKey
1278
- })
1279
-
1280
- const remoteHomeResult = await ssh.execCommand('printf "%s" "$HOME"')
1281
- const remoteHome = remoteHomeResult.stdout.trim() || `/home/${sshUser}`
1282
- const remoteCwd = resolveRemotePath(config.projectPath, remoteHome)
1283
-
1284
- logProcessing(`Connection established. Acquiring deployment lock on server...`)
1285
- await acquireRemoteLock(ssh, remoteCwd, rootDir)
1286
- lockAcquired = true
1287
- logProcessing(`Lock acquired. Running deployment commands in ${remoteCwd}...`)
1288
-
1289
- // Robust environment bootstrap that works even when profile files don't export PATH
1290
- // for non-interactive shells. This handles:
1291
- // 1. Sourcing profile files (may not export PATH for non-interactive shells)
1292
- // 2. Loading nvm if available (common Node.js installation method)
1293
- // 3. Finding and adding common Node.js/npm installation paths
1294
- const profileBootstrap = [
1295
- // Source profile files (may set PATH, but often skip for non-interactive shells)
1296
- 'if [ -f "$HOME/.profile" ]; then . "$HOME/.profile"; fi',
1297
- 'if [ -f "$HOME/.bash_profile" ]; then . "$HOME/.bash_profile"; fi',
1298
- 'if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc"; fi',
1299
- 'if [ -f "$HOME/.zprofile" ]; then . "$HOME/.zprofile"; fi',
1300
- 'if [ -f "$HOME/.zshrc" ]; then . "$HOME/.zshrc"; fi',
1301
- // Load nvm if available (common Node.js installation method)
1302
- 'if [ -s "$HOME/.nvm/nvm.sh" ]; then . "$HOME/.nvm/nvm.sh"; fi',
1303
- 'if [ -s "$HOME/.config/nvm/nvm.sh" ]; then . "$HOME/.config/nvm/nvm.sh"; fi',
1304
- 'if [ -s "/usr/local/opt/nvm/nvm.sh" ]; then . "/usr/local/opt/nvm/nvm.sh"; fi',
1305
- // Try to find npm/node in common locations and add to PATH
1306
- 'if command -v npm >/dev/null 2>&1; then :',
1307
- 'elif [ -d "$HOME/.nvm/versions/node" ]; then NODE_VERSION=$(ls -1 "$HOME/.nvm/versions/node" | tail -1) && export PATH="$HOME/.nvm/versions/node/$NODE_VERSION/bin:$PATH"',
1308
- 'elif [ -d "/usr/local/lib/node_modules/npm/bin" ]; then export PATH="/usr/local/lib/node_modules/npm/bin:$PATH"',
1309
- 'elif [ -d "/opt/homebrew/bin" ] && [ -f "/opt/homebrew/bin/npm" ]; then export PATH="/opt/homebrew/bin:$PATH"',
1310
- 'elif [ -d "/usr/local/bin" ] && [ -f "/usr/local/bin/npm" ]; then export PATH="/usr/local/bin:$PATH"',
1311
- 'elif [ -d "$HOME/.local/bin" ] && [ -f "$HOME/.local/bin/npm" ]; then export PATH="$HOME/.local/bin:$PATH"',
1312
- 'fi'
1313
- ].join('; ')
1314
-
1315
- const escapeForDoubleQuotes = (value) => value.replace(/(["\\$`])/g, '\\$1')
1316
-
1317
- const executeRemote = async (label, command, options = {}) => {
1318
- const { cwd = remoteCwd, allowFailure = false, bootstrapEnv = true } = options
1319
- logProcessing(`\n→ ${label}`)
1320
-
1321
- let wrappedCommand = command
1322
- let execOptions = { cwd }
1323
-
1324
- if (bootstrapEnv) {
1325
- const cwdForShell = escapeForDoubleQuotes(cwd)
1326
- wrappedCommand = `${profileBootstrap}; cd "${cwdForShell}" && ${command}`
1327
- execOptions = {}
1328
- }
1329
-
1330
- const result = await ssh.execCommand(wrappedCommand, execOptions)
1331
-
1332
- // Log all output to file
1333
- if (result.stdout && result.stdout.trim()) {
1334
- await writeToLogFile(rootDir, `[${label}] STDOUT:\n${result.stdout.trim()}`)
1335
- }
1336
-
1337
- if (result.stderr && result.stderr.trim()) {
1338
- await writeToLogFile(rootDir, `[${label}] STDERR:\n${result.stderr.trim()}`)
1339
- }
1340
-
1341
- // Only show errors in terminal
1342
- if (result.code !== 0) {
1343
- if (result.stdout && result.stdout.trim()) {
1344
- logError(`\n[${label}] Output:\n${result.stdout.trim()}`)
1345
- }
1346
-
1347
- if (result.stderr && result.stderr.trim()) {
1348
- logError(`\n[${label}] Error:\n${result.stderr.trim()}`)
1349
- }
1350
- }
1351
-
1352
- if (result.code !== 0 && !allowFailure) {
1353
- const stderr = result.stderr?.trim() ?? ''
1354
- if (/command not found/.test(stderr) || /is not recognized/.test(stderr)) {
1355
- throw new Error(
1356
- `Command failed: ${command}. Ensure the remote environment loads required tools for non-interactive shells (e.g. export PATH in profile scripts).`
1357
- )
1358
- }
1359
-
1360
- throw new Error(`Command failed: ${command}`)
1361
- }
1362
-
1363
- // Show success confirmation with command
1364
- if (result.code === 0) {
1365
- logSuccess(`✓ ${command}`)
1366
- }
1367
-
1368
- return result
1369
- }
1370
-
1371
- const laravelCheck = await ssh.execCommand(
1372
- 'if [ -f artisan ] && [ -f composer.json ] && grep -q "laravel/framework" composer.json; then echo "yes"; else echo "no"; fi',
1373
- { cwd: remoteCwd }
1374
- )
1375
- const isLaravel = laravelCheck.stdout.trim() === 'yes'
1376
-
1377
- if (isLaravel) {
1378
- logSuccess('Laravel project detected.')
1379
- } else {
1380
- logWarning('Laravel project not detected; skipping Laravel-specific maintenance tasks.')
1381
- }
1382
-
1383
- let changedFiles = []
1384
-
1385
- if (snapshot && snapshot.changedFiles) {
1386
- changedFiles = snapshot.changedFiles
1387
- logProcessing('Resuming deployment with saved task snapshot.')
1388
- } else if (isLaravel) {
1389
- await executeRemote(`Fetch latest changes for ${config.branch}`, `git fetch origin ${config.branch}`)
1390
-
1391
- const diffResult = await executeRemote(
1392
- 'Inspect pending changes',
1393
- `git diff --name-only HEAD..origin/${config.branch}`,
1394
- { printStdout: false }
1395
- )
1396
-
1397
- changedFiles = diffResult.stdout
1398
- .split(/\r?\n/)
1399
- .map((line) => line.trim())
1400
- .filter(Boolean)
1401
-
1402
- if (changedFiles.length > 0) {
1403
- const preview = changedFiles
1404
- .slice(0, 20)
1405
- .map((file) => ` - ${file}`)
1406
- .join('\n')
1407
-
1408
- logProcessing(
1409
- `Detected ${changedFiles.length} changed file(s):\n${preview}${changedFiles.length > 20 ? '\n - ...' : ''
1410
- }`
1411
- )
1412
- } else {
1413
- logProcessing('No upstream file changes detected.')
1414
- }
1415
- }
1416
-
1417
- const shouldRunComposer =
1418
- isLaravel &&
1419
- changedFiles.some(
1420
- (file) =>
1421
- file === 'composer.json' ||
1422
- file === 'composer.lock' ||
1423
- file.endsWith('/composer.json') ||
1424
- file.endsWith('/composer.lock')
1425
- )
1426
-
1427
- const shouldRunMigrations =
1428
- isLaravel &&
1429
- changedFiles.some(
1430
- (file) => file.startsWith('database/migrations/') && file.endsWith('.php')
1431
- )
1432
-
1433
- const hasPhpChanges = isLaravel && changedFiles.some((file) => file.endsWith('.php'))
1434
-
1435
- const shouldRunNpmInstall =
1436
- isLaravel &&
1437
- changedFiles.some(
1438
- (file) =>
1439
- file === 'package.json' ||
1440
- file === 'package-lock.json' ||
1441
- file.endsWith('/package.json') ||
1442
- file.endsWith('/package-lock.json')
1443
- )
1444
-
1445
- const hasFrontendChanges =
1446
- isLaravel &&
1447
- changedFiles.some((file) =>
1448
- ['.vue', '.css', '.scss', '.js', '.ts', '.tsx', '.less'].some((ext) =>
1449
- file.endsWith(ext)
1450
- )
1451
- )
1452
-
1453
- const shouldRunBuild = isLaravel && (hasFrontendChanges || shouldRunNpmInstall)
1454
- const shouldClearCaches = hasPhpChanges
1455
- const shouldRestartQueues = hasPhpChanges
1456
-
1457
- let horizonConfigured = false
1458
- if (shouldRestartQueues) {
1459
- const horizonCheck = await ssh.execCommand(
1460
- 'if [ -f config/horizon.php ]; then echo "yes"; else echo "no"; fi',
1461
- { cwd: remoteCwd }
1462
- )
1463
- horizonConfigured = horizonCheck.stdout.trim() === 'yes'
1464
- }
1465
-
1466
- const steps = [
1467
- {
1468
- label: `Pull latest changes for ${config.branch}`,
1469
- command: `git pull origin ${config.branch}`
1470
- }
1471
- ]
1472
-
1473
- if (shouldRunComposer) {
1474
- steps.push({
1475
- label: 'Update Composer dependencies',
1476
- command: 'composer update --no-dev --no-interaction --prefer-dist'
1477
- })
1478
- }
1479
-
1480
- if (shouldRunMigrations) {
1481
- steps.push({
1482
- label: 'Run database migrations',
1483
- command: 'php artisan migrate --force'
1484
- })
1485
- }
1486
-
1487
- if (shouldRunNpmInstall) {
1488
- steps.push({
1489
- label: 'Install Node dependencies',
1490
- command: 'npm install'
1491
- })
1492
- }
1493
-
1494
- if (shouldRunBuild) {
1495
- steps.push({
1496
- label: 'Compile frontend assets',
1497
- command: 'npm run build'
1498
- })
1499
- }
1500
-
1501
- if (shouldClearCaches) {
1502
- steps.push({
1503
- label: 'Clear Laravel caches',
1504
- command: 'php artisan cache:clear && php artisan config:clear && php artisan view:clear'
1505
- })
1506
- }
1507
-
1508
- if (shouldRestartQueues) {
1509
- steps.push({
1510
- label: horizonConfigured ? 'Restart Horizon workers' : 'Restart queue workers',
1511
- command: horizonConfigured ? 'php artisan horizon:terminate' : 'php artisan queue:restart'
1512
- })
1513
- }
1514
-
1515
- const usefulSteps = steps.length > 1
1516
-
1517
- let pendingSnapshot
1518
-
1519
- if (usefulSteps) {
1520
- pendingSnapshot = snapshot ?? {
1521
- serverName: config.serverName,
1522
- branch: config.branch,
1523
- projectPath: config.projectPath,
1524
- sshUser: config.sshUser,
1525
- createdAt: new Date().toISOString(),
1526
- changedFiles,
1527
- taskLabels: steps.map((step) => step.label)
1528
- }
1529
-
1530
- await savePendingTasksSnapshot(rootDir, pendingSnapshot)
1531
-
1532
- const payload = Buffer.from(JSON.stringify(pendingSnapshot)).toString('base64')
1533
- await executeRemote(
1534
- 'Record pending deployment tasks',
1535
- `mkdir -p .zephyr && echo '${payload}' | base64 --decode > .zephyr/${PENDING_TASKS_FILE}`,
1536
- { printStdout: false }
1537
- )
1538
- }
1539
-
1540
- if (steps.length === 1) {
1541
- logProcessing('No additional maintenance tasks scheduled beyond git pull.')
1542
- } else {
1543
- const extraTasks = steps
1544
- .slice(1)
1545
- .map((step) => step.label)
1546
- .join(', ')
1547
-
1548
- logProcessing(`Additional tasks scheduled: ${extraTasks}`)
1549
- }
1550
-
1551
- let completed = false
1552
-
1553
- try {
1554
- for (const step of steps) {
1555
- await executeRemote(step.label, step.command)
1556
- }
1557
-
1558
- completed = true
1559
- } finally {
1560
- if (usefulSteps && completed) {
1561
- await executeRemote(
1562
- 'Clear pending deployment snapshot',
1563
- `rm -f .zephyr/${PENDING_TASKS_FILE}`,
1564
- { printStdout: false, allowFailure: true }
1565
- )
1566
- await clearPendingTasksSnapshot(rootDir)
1567
- }
1568
- }
1569
-
1570
- logSuccess('\nDeployment commands completed successfully.')
1571
-
1572
- const logPath = await getLogFilePath(rootDir)
1573
- logSuccess(`\nAll task output has been logged to: ${logPath}`)
1574
- } catch (error) {
1575
- const logPath = logFilePath || await getLogFilePath(rootDir).catch(() => null)
1576
- if (logPath) {
1577
- logError(`\nTask output has been logged to: ${logPath}`)
1578
- }
1579
-
1580
- // If lock was acquired but deployment failed, check for stale locks
1581
- if (lockAcquired && ssh) {
1582
- try {
1583
- const remoteHomeResult = await ssh.execCommand('printf "%s" "$HOME"')
1584
- const remoteHome = remoteHomeResult.stdout.trim() || `/home/${sshUser}`
1585
- const remoteCwd = resolveRemotePath(config.projectPath, remoteHome)
1586
- await compareLocksAndPrompt(rootDir, ssh, remoteCwd)
1587
- } catch (_lockError) {
1588
- // Ignore lock comparison errors during error handling
1589
- }
1590
- }
1591
-
1592
- throw new Error(`Deployment failed: ${error.message}`)
1593
- } finally {
1594
- if (lockAcquired && ssh) {
1595
- try {
1596
- const remoteHomeResult = await ssh.execCommand('printf "%s" "$HOME"')
1597
- const remoteHome = remoteHomeResult.stdout.trim() || `/home/${sshUser}`
1598
- const remoteCwd = resolveRemotePath(config.projectPath, remoteHome)
1599
- await releaseRemoteLock(ssh, remoteCwd)
1600
- await releaseLocalLock(rootDir)
1601
- } catch (error) {
1602
- logWarning(`Failed to release lock: ${error.message}`)
1603
- }
1604
- }
1605
- await closeLogFile()
1606
- if (ssh) {
1607
- ssh.dispose()
1608
- }
1609
- }
1610
- }
1611
-
1612
- async function promptServerDetails(existingServers = []) {
1613
- const defaults = {
1614
- serverName: existingServers.length === 0 ? 'home' : `server-${existingServers.length + 1}`,
1615
- serverIp: '1.1.1.1'
1616
- }
1617
-
1618
- const answers = await runPrompt([
1619
- {
1620
- type: 'input',
1621
- name: 'serverName',
1622
- message: 'Server name',
1623
- default: defaults.serverName
1624
- },
1625
- {
1626
- type: 'input',
1627
- name: 'serverIp',
1628
- message: 'Server IP address',
1629
- default: defaults.serverIp
1630
- }
1631
- ])
1632
-
1633
- return {
1634
- id: generateId(),
1635
- serverName: answers.serverName.trim() || defaults.serverName,
1636
- serverIp: answers.serverIp.trim() || defaults.serverIp
1637
- }
1638
- }
1639
-
1640
- async function selectServer(servers) {
1641
- if (servers.length === 0) {
1642
- logProcessing("No servers configured. Let's create one.")
1643
- const server = await promptServerDetails()
1644
- servers.push(server)
1645
- await saveServers(servers)
1646
- logSuccess('Saved server configuration to ~/.config/zephyr/servers.json')
1647
- return server
1648
- }
1649
-
1650
- const choices = servers.map((server, index) => ({
1651
- name: `${server.serverName} (${server.serverIp})`,
1652
- value: index
1653
- }))
1654
-
1655
- choices.push(new inquirer.Separator(), {
1656
- name: '➕ Register a new server',
1657
- value: 'create'
1658
- })
1659
-
1660
- const { selection } = await runPrompt([
1661
- {
1662
- type: 'list',
1663
- name: 'selection',
1664
- message: 'Select server or register new',
1665
- choices,
1666
- default: 0
1667
- }
1668
- ])
1669
-
1670
- if (selection === 'create') {
1671
- const server = await promptServerDetails(servers)
1672
- servers.push(server)
1673
- await saveServers(servers)
1674
- logSuccess('Appended server configuration to ~/.config/zephyr/servers.json')
1675
- return server
1676
- }
1677
-
1678
- return servers[selection]
1679
- }
1680
-
1681
- async function promptAppDetails(currentDir, existing = {}) {
1682
- const branches = await listGitBranches(currentDir)
1683
- const defaultBranch = existing.branch || (branches.includes('master') ? 'master' : branches[0])
1684
- const defaults = {
1685
- projectPath: existing.projectPath || defaultProjectPath(currentDir),
1686
- branch: defaultBranch
1687
- }
1688
-
1689
- const answers = await runPrompt([
1690
- {
1691
- type: 'input',
1692
- name: 'projectPath',
1693
- message: 'Remote project path',
1694
- default: defaults.projectPath
1695
- },
1696
- {
1697
- type: 'list',
1698
- name: 'branchSelection',
1699
- message: 'Branch to deploy',
1700
- choices: [
1701
- ...branches.map((branch) => ({ name: branch, value: branch })),
1702
- new inquirer.Separator(),
1703
- { name: 'Enter custom branch…', value: '__custom' }
1704
- ],
1705
- default: defaults.branch
1706
- }
1707
- ])
1708
-
1709
- let branch = answers.branchSelection
1710
-
1711
- if (branch === '__custom') {
1712
- const { customBranch } = await runPrompt([
1713
- {
1714
- type: 'input',
1715
- name: 'customBranch',
1716
- message: 'Custom branch name',
1717
- default: defaults.branch
1718
- }
1719
- ])
1720
-
1721
- branch = customBranch.trim() || defaults.branch
1722
- }
1723
-
1724
- const sshDetails = await promptSshDetails(currentDir, existing)
1725
-
1726
- return {
1727
- projectPath: answers.projectPath.trim() || defaults.projectPath,
1728
- branch,
1729
- ...sshDetails
1730
- }
1731
- }
1732
-
1733
- async function selectApp(projectConfig, server, currentDir) {
1734
- const apps = projectConfig.apps ?? []
1735
- const matches = apps
1736
- .map((app, index) => ({ app, index }))
1737
- .filter(({ app }) => app.serverId === server.id || app.serverName === server.serverName)
1738
-
1739
- if (matches.length === 0) {
1740
- if (apps.length > 0) {
1741
- const availableServers = [...new Set(apps.map((app) => app.serverName).filter(Boolean))]
1742
- if (availableServers.length > 0) {
1743
- logWarning(
1744
- `No applications configured for server "${server.serverName}". Available servers: ${availableServers.join(', ')}`
1745
- )
1746
- }
1747
- }
1748
- logProcessing(`No applications configured for ${server.serverName}. Let's create one.`)
1749
- const appDetails = await promptAppDetails(currentDir)
1750
- const appConfig = {
1751
- id: generateId(),
1752
- serverId: server.id,
1753
- serverName: server.serverName,
1754
- ...appDetails
1755
- }
1756
- projectConfig.apps.push(appConfig)
1757
- await saveProjectConfig(currentDir, projectConfig)
1758
- logSuccess('Saved deployment configuration to .zephyr/config.json')
1759
- return appConfig
1760
- }
1761
-
1762
- const choices = matches.map(({ app }, matchIndex) => ({
1763
- name: `${app.projectPath} (${app.branch})`,
1764
- value: matchIndex
1765
- }))
1766
-
1767
- choices.push(new inquirer.Separator(), {
1768
- name: '➕ Configure new application for this server',
1769
- value: 'create'
1770
- })
1771
-
1772
- const { selection } = await runPrompt([
1773
- {
1774
- type: 'list',
1775
- name: 'selection',
1776
- message: `Select application for ${server.serverName}`,
1777
- choices,
1778
- default: 0
1779
- }
1780
- ])
1781
-
1782
- if (selection === 'create') {
1783
- const appDetails = await promptAppDetails(currentDir)
1784
- const appConfig = {
1785
- id: generateId(),
1786
- serverId: server.id,
1787
- serverName: server.serverName,
1788
- ...appDetails
1789
- }
1790
- projectConfig.apps.push(appConfig)
1791
- await saveProjectConfig(currentDir, projectConfig)
1792
- logSuccess('Appended deployment configuration to .zephyr/config.json')
1793
- return appConfig
1794
- }
1795
-
1796
- const chosen = matches[selection].app
1797
- return chosen
1798
- }
1799
-
1800
- async function selectPreset(projectConfig, servers) {
1801
- const presets = projectConfig.presets ?? []
1802
- const apps = projectConfig.apps ?? []
1803
-
1804
- if (presets.length === 0) {
1805
- return null
1806
- }
1807
-
1808
- const choices = presets.map((preset, index) => {
1809
- let displayName = preset.name
1810
-
1811
- if (preset.appId) {
1812
- // New format: look up app by ID
1813
- const app = apps.find((a) => a.id === preset.appId)
1814
- if (app) {
1815
- const server = servers.find((s) => s.id === app.serverId || s.serverName === app.serverName)
1816
- const serverName = server?.serverName || 'unknown'
1817
- const branch = preset.branch || app.branch || 'unknown'
1818
- displayName = `${preset.name} (${serverName} → ${app.projectPath} [${branch}])`
1819
- }
1820
- } else if (preset.key) {
1821
- // Legacy format: parse from key
1822
- const keyParts = preset.key.split(':')
1823
- const serverName = keyParts[0]
1824
- const projectPath = keyParts[1]
1825
- const branch = preset.branch || (keyParts.length === 3 ? keyParts[2] : 'unknown')
1826
- displayName = `${preset.name} (${serverName} → ${projectPath} [${branch}])`
1827
- }
1828
-
1829
- return {
1830
- name: displayName,
1831
- value: index
1832
- }
1833
- })
1834
-
1835
- choices.push(new inquirer.Separator(), {
1836
- name: '➕ Create new preset',
1837
- value: 'create'
1838
- })
1839
-
1840
- const { selection } = await runPrompt([
1841
- {
1842
- type: 'list',
1843
- name: 'selection',
1844
- message: 'Select preset or create new',
1845
- choices,
1846
- default: 0
1847
- }
1848
- ])
1849
-
1850
- if (selection === 'create') {
1851
- return 'create' // Return a special marker instead of null
1852
- }
1853
-
1854
- return presets[selection]
1855
- }
1856
-
1857
- async function main(releaseType = null) {
1858
- // Best-effort update check (skip during tests or when explicitly disabled)
1859
- // If an update is accepted, the process will re-execute via npx @latest and we should exit early.
1860
- if (
1861
- process.env.ZEPHYR_SKIP_VERSION_CHECK !== '1' &&
1862
- process.env.NODE_ENV !== 'test' &&
1863
- process.env.VITEST !== 'true'
1864
- ) {
1865
- try {
1866
- const args = process.argv.slice(2)
1867
- const reExecuted = await checkAndUpdateVersion(runPrompt, args)
1868
- if (reExecuted) {
1869
- return
1870
- }
1871
- } catch (_error) {
1872
- // Never block execution due to update check issues
1873
- }
1874
- }
1875
-
1876
- // Handle node/vue package release
1877
- if (releaseType === 'node' || releaseType === 'vue') {
1878
- try {
1879
- await releaseNode()
1880
- return
1881
- } catch (error) {
1882
- logError('\nRelease failed:')
1883
- logError(error.message)
1884
- if (error.stack) {
1885
- console.error(error.stack)
1886
- }
1887
- process.exit(1)
1888
- }
1889
- }
1890
-
1891
- // Handle packagist/composer package release
1892
- if (releaseType === 'packagist') {
1893
- try {
1894
- await releasePackagist()
1895
- return
1896
- } catch (error) {
1897
- logError('\nRelease failed:')
1898
- logError(error.message)
1899
- if (error.stack) {
1900
- console.error(error.stack)
1901
- }
1902
- process.exit(1)
1903
- }
1904
- }
1905
-
1906
- // Default: Laravel deployment workflow
1907
- const rootDir = process.cwd()
1908
-
1909
- await ensureGitignoreEntry(rootDir)
1910
- await ensureProjectReleaseScript(rootDir)
1911
-
1912
- // Validate dependencies if package.json or composer.json exists
1913
- const packageJsonPath = path.join(rootDir, 'package.json')
1914
- const composerJsonPath = path.join(rootDir, 'composer.json')
1915
- const hasPackageJson = await fs.access(packageJsonPath).then(() => true).catch(() => false)
1916
- const hasComposerJson = await fs.access(composerJsonPath).then(() => true).catch(() => false)
1917
-
1918
- if (hasPackageJson || hasComposerJson) {
1919
- logProcessing('Validating dependencies...')
1920
- await validateLocalDependencies(rootDir, runPrompt, logSuccess)
1921
- }
1922
-
1923
- // Load servers first (they may be migrated)
1924
- const servers = await loadServers()
1925
- // Load project config with servers for migration
1926
- const projectConfig = await loadProjectConfig(rootDir, servers)
1927
-
1928
- let server = null
1929
- let appConfig = null
1930
- let isCreatingNewPreset = false
1931
-
1932
- const preset = await selectPreset(projectConfig, servers)
1933
-
1934
- if (preset === 'create') {
1935
- // User explicitly chose to create a new preset
1936
- isCreatingNewPreset = true
1937
- server = await selectServer(servers)
1938
- appConfig = await selectApp(projectConfig, server, rootDir)
1939
- } else if (preset) {
1940
- // User selected an existing preset - look up by appId
1941
- if (preset.appId) {
1942
- appConfig = projectConfig.apps?.find((a) => a.id === preset.appId)
1943
-
1944
- if (!appConfig) {
1945
- logWarning(`Preset references app configuration that no longer exists. Creating new configuration.`)
1946
- server = await selectServer(servers)
1947
- appConfig = await selectApp(projectConfig, server, rootDir)
1948
- } else {
1949
- server = servers.find((s) => s.id === appConfig.serverId || s.serverName === appConfig.serverName)
1950
-
1951
- if (!server) {
1952
- logWarning(`Preset references server that no longer exists. Creating new configuration.`)
1953
- server = await selectServer(servers)
1954
- appConfig = await selectApp(projectConfig, server, rootDir)
1955
- } else if (preset.branch && appConfig.branch !== preset.branch) {
1956
- // Update branch if preset has a different branch
1957
- appConfig.branch = preset.branch
1958
- await saveProjectConfig(rootDir, projectConfig)
1959
- logSuccess(`Updated branch to ${preset.branch} from preset.`)
1960
- }
1961
- }
1962
- } else if (preset.key) {
1963
- // Legacy preset format - migrate it
1964
- const keyParts = preset.key.split(':')
1965
- const serverName = keyParts[0]
1966
- const projectPath = keyParts[1]
1967
- const presetBranch = preset.branch || (keyParts.length === 3 ? keyParts[2] : null)
1968
-
1969
- server = servers.find((s) => s.serverName === serverName)
1970
-
1971
- if (!server) {
1972
- logWarning(`Preset references server "${serverName}" which no longer exists. Creating new configuration.`)
1973
- server = await selectServer(servers)
1974
- appConfig = await selectApp(projectConfig, server, rootDir)
1975
- } else {
1976
- appConfig = projectConfig.apps?.find(
1977
- (a) => (a.serverId === server.id || a.serverName === serverName) && a.projectPath === projectPath
1978
- )
1979
-
1980
- if (!appConfig) {
1981
- logWarning(`Preset references app configuration that no longer exists. Creating new configuration.`)
1982
- appConfig = await selectApp(projectConfig, server, rootDir)
1983
- } else {
1984
- // Migrate preset to use appId
1985
- preset.appId = appConfig.id
1986
- if (presetBranch && appConfig.branch !== presetBranch) {
1987
- appConfig.branch = presetBranch
1988
- }
1989
- preset.branch = appConfig.branch
1990
- await saveProjectConfig(rootDir, projectConfig)
1991
- }
1992
- }
1993
- } else {
1994
- logWarning(`Preset format is invalid. Creating new configuration.`)
1995
- server = await selectServer(servers)
1996
- appConfig = await selectApp(projectConfig, server, rootDir)
1997
- }
1998
- } else {
1999
- // No presets exist, go through normal flow
2000
- server = await selectServer(servers)
2001
- appConfig = await selectApp(projectConfig, server, rootDir)
2002
- }
2003
-
2004
- const updated = await ensureSshDetails(appConfig, rootDir)
2005
-
2006
- if (updated) {
2007
- await saveProjectConfig(rootDir, projectConfig)
2008
- logSuccess('Updated .zephyr/config.json with SSH details.')
2009
- }
2010
-
2011
- const deploymentConfig = {
2012
- serverName: server.serverName,
2013
- serverIp: server.serverIp,
2014
- projectPath: appConfig.projectPath,
2015
- branch: appConfig.branch,
2016
- sshUser: appConfig.sshUser,
2017
- sshKey: appConfig.sshKey
2018
- }
2019
-
2020
- logProcessing('\nSelected deployment target:')
2021
- console.log(JSON.stringify(deploymentConfig, null, 2))
2022
-
2023
- if (isCreatingNewPreset || !preset) {
2024
- const { presetName } = await runPrompt([
2025
- {
2026
- type: 'input',
2027
- name: 'presetName',
2028
- message: 'Enter a name for this preset (leave blank to skip)',
2029
- default: isCreatingNewPreset ? '' : undefined
2030
- }
2031
- ])
2032
-
2033
- const trimmedName = presetName?.trim()
2034
-
2035
- if (trimmedName && trimmedName.length > 0) {
2036
- const presets = projectConfig.presets ?? []
2037
-
2038
- // Find app config to get its ID
2039
- const appId = appConfig.id
2040
-
2041
- if (!appId) {
2042
- logWarning('Cannot save preset: app configuration missing ID.')
2043
- } else {
2044
- // Check if preset with this appId already exists
2045
- const existingIndex = presets.findIndex((p) => p.appId === appId)
2046
- if (existingIndex >= 0) {
2047
- presets[existingIndex].name = trimmedName
2048
- presets[existingIndex].branch = deploymentConfig.branch
2049
- } else {
2050
- presets.push({
2051
- name: trimmedName,
2052
- appId: appId,
2053
- branch: deploymentConfig.branch
2054
- })
2055
- }
2056
-
2057
- projectConfig.presets = presets
2058
- await saveProjectConfig(rootDir, projectConfig)
2059
- logSuccess(`Saved preset "${trimmedName}" to .zephyr/config.json`)
2060
- }
2061
- }
2062
- }
2063
-
2064
- const existingSnapshot = await loadPendingTasksSnapshot(rootDir)
2065
- let snapshotToUse = null
2066
-
2067
- if (existingSnapshot) {
2068
- const matchesSelection =
2069
- existingSnapshot.serverName === deploymentConfig.serverName &&
2070
- existingSnapshot.branch === deploymentConfig.branch
2071
-
2072
- const messageLines = [
2073
- 'Pending deployment tasks were detected from a previous run.',
2074
- `Server: ${existingSnapshot.serverName}`,
2075
- `Branch: ${existingSnapshot.branch}`
2076
- ]
2077
-
2078
- if (existingSnapshot.taskLabels && existingSnapshot.taskLabels.length > 0) {
2079
- messageLines.push(`Tasks: ${existingSnapshot.taskLabels.join(', ')}`)
2080
- }
2081
-
2082
- const { resumePendingTasks } = await runPrompt([
2083
- {
2084
- type: 'confirm',
2085
- name: 'resumePendingTasks',
2086
- message: `${messageLines.join(' | ')}. Resume using this plan?`,
2087
- default: matchesSelection
2088
- }
2089
- ])
2090
-
2091
- if (resumePendingTasks) {
2092
- snapshotToUse = existingSnapshot
2093
- logProcessing('Resuming deployment using saved task snapshot...')
2094
- } else {
2095
- await clearPendingTasksSnapshot(rootDir)
2096
- logWarning('Discarded pending deployment snapshot.')
2097
- }
2098
- }
2099
-
2100
- await runRemoteTasks(deploymentConfig, { rootDir, snapshot: snapshotToUse })
2101
- }
2102
-
2103
- export {
2104
- ensureGitignoreEntry,
2105
- ensureProjectReleaseScript,
2106
- listSshKeys,
2107
- resolveRemotePath,
2108
- isPrivateKeyFile,
2109
- runRemoteTasks,
2110
- promptServerDetails,
2111
- selectServer,
2112
- promptAppDetails,
2113
- selectApp,
2114
- promptSshDetails,
2115
- ensureSshDetails,
2116
- ensureLocalRepositoryState,
2117
- loadServers,
2118
- loadProjectConfig,
2119
- saveProjectConfig,
2120
- main,
2121
- releaseNode,
2122
- releasePackagist,
2123
- createSshClient,
2124
- resolveSshKeyPath,
2125
- selectPreset,
2126
- logProcessing,
2127
- logSuccess,
2128
- logWarning,
2129
- logError,
2130
- writeToLogFile,
2131
- getLogFilePath,
2132
- ensureDirectory,
2133
- runCommand,
2134
- runCommandCapture
2135
- }