@wyxos/zephyr 0.1.13 → 0.1.14

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.
Files changed (4) hide show
  1. package/README.md +104 -104
  2. package/bin/zephyr.mjs +6 -6
  3. package/package.json +48 -48
  4. package/src/index.mjs +1557 -1391
package/src/index.mjs CHANGED
@@ -1,1391 +1,1557 @@
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 chalk from 'chalk'
6
- import inquirer from 'inquirer'
7
- import { NodeSSH } from 'node-ssh'
8
-
9
- const PROJECT_CONFIG_DIR = '.zephyr'
10
- const PROJECT_CONFIG_FILE = 'config.json'
11
- const GLOBAL_CONFIG_DIR = path.join(os.homedir(), '.config', 'zephyr')
12
- const SERVERS_FILE = path.join(GLOBAL_CONFIG_DIR, 'servers.json')
13
- const PROJECT_LOCK_FILE = 'deploy.lock'
14
- const PENDING_TASKS_FILE = 'pending-tasks.json'
15
- const RELEASE_SCRIPT_NAME = 'release'
16
- const RELEASE_SCRIPT_COMMAND = 'npx @wyxos/zephyr@latest'
17
-
18
- const logProcessing = (message = '') => console.log(chalk.yellow(message))
19
- const logSuccess = (message = '') => console.log(chalk.green(message))
20
- const logWarning = (message = '') => console.warn(chalk.yellow(message))
21
- const logError = (message = '') => console.error(chalk.red(message))
22
-
23
- let logFilePath = null
24
-
25
- async function getLogFilePath(rootDir) {
26
- if (logFilePath) {
27
- return logFilePath
28
- }
29
-
30
- const configDir = getProjectConfigDir(rootDir)
31
- await ensureDirectory(configDir)
32
-
33
- const now = new Date()
34
- const dateStr = now.toISOString().replace(/:/g, '-').replace(/\..+/, '')
35
- logFilePath = path.join(configDir, `${dateStr}.log`)
36
-
37
- return logFilePath
38
- }
39
-
40
- async function writeToLogFile(rootDir, message) {
41
- const logPath = await getLogFilePath(rootDir)
42
- const timestamp = new Date().toISOString()
43
- await fs.appendFile(logPath, `${timestamp} - ${message}\n`)
44
- }
45
-
46
- async function closeLogFile() {
47
- logFilePath = null
48
- }
49
-
50
- const createSshClient = () => {
51
- if (typeof globalThis !== 'undefined' && globalThis.__zephyrSSHFactory) {
52
- return globalThis.__zephyrSSHFactory()
53
- }
54
-
55
- return new NodeSSH()
56
- }
57
-
58
- const runPrompt = async (questions) => {
59
- if (typeof globalThis !== 'undefined' && globalThis.__zephyrPrompt) {
60
- return globalThis.__zephyrPrompt(questions)
61
- }
62
-
63
- return inquirer.prompt(questions)
64
- }
65
-
66
- async function runCommand(command, args, { silent = false, cwd } = {}) {
67
- return new Promise((resolve, reject) => {
68
- const child = spawn(command, args, {
69
- stdio: silent ? 'ignore' : 'inherit',
70
- cwd
71
- })
72
-
73
- child.on('error', reject)
74
- child.on('close', (code) => {
75
- if (code === 0) {
76
- resolve()
77
- } else {
78
- const error = new Error(`${command} exited with code ${code}`)
79
- error.exitCode = code
80
- reject(error)
81
- }
82
- })
83
- })
84
- }
85
-
86
- async function runCommandCapture(command, args, { cwd } = {}) {
87
- return new Promise((resolve, reject) => {
88
- let stdout = ''
89
- let stderr = ''
90
-
91
- const child = spawn(command, args, {
92
- stdio: ['ignore', 'pipe', 'pipe'],
93
- cwd
94
- })
95
-
96
- child.stdout.on('data', (chunk) => {
97
- stdout += chunk
98
- })
99
-
100
- child.stderr.on('data', (chunk) => {
101
- stderr += chunk
102
- })
103
-
104
- child.on('error', reject)
105
- child.on('close', (code) => {
106
- if (code === 0) {
107
- resolve(stdout)
108
- } else {
109
- const error = new Error(`${command} exited with code ${code}: ${stderr.trim()}`)
110
- error.exitCode = code
111
- reject(error)
112
- }
113
- })
114
- })
115
- }
116
-
117
- async function getCurrentBranch(rootDir) {
118
- const output = await runCommandCapture('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
119
- cwd: rootDir
120
- })
121
-
122
- return output.trim()
123
- }
124
-
125
- async function getGitStatus(rootDir) {
126
- const output = await runCommandCapture('git', ['status', '--porcelain'], {
127
- cwd: rootDir
128
- })
129
-
130
- return output.trim()
131
- }
132
-
133
- function hasStagedChanges(statusOutput) {
134
- if (!statusOutput || statusOutput.length === 0) {
135
- return false
136
- }
137
-
138
- const lines = statusOutput.split('\n').filter((line) => line.trim().length > 0)
139
-
140
- return lines.some((line) => {
141
- const firstChar = line[0]
142
- // In git status --porcelain format:
143
- // - First char is space: unstaged changes (e.g., " M file")
144
- // - First char is '?': untracked files (e.g., "?? file")
145
- // - First char is letter (M, A, D, etc.): staged changes (e.g., "M file")
146
- // Only return true for staged changes, not unstaged or untracked
147
- return firstChar && firstChar !== ' ' && firstChar !== '?'
148
- })
149
- }
150
-
151
- async function getUpstreamRef(rootDir) {
152
- try {
153
- const output = await runCommandCapture('git', ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], {
154
- cwd: rootDir
155
- })
156
-
157
- const ref = output.trim()
158
- return ref.length > 0 ? ref : null
159
- } catch {
160
- return null
161
- }
162
- }
163
-
164
- async function ensureCommittedChangesPushed(targetBranch, rootDir) {
165
- const upstreamRef = await getUpstreamRef(rootDir)
166
-
167
- if (!upstreamRef) {
168
- logWarning(`Branch ${targetBranch} does not track a remote upstream; skipping automatic push of committed changes.`)
169
- return { pushed: false, upstreamRef: null }
170
- }
171
-
172
- const [remoteName, ...upstreamParts] = upstreamRef.split('/')
173
- const upstreamBranch = upstreamParts.join('/')
174
-
175
- if (!remoteName || !upstreamBranch) {
176
- logWarning(`Unable to determine remote destination for ${targetBranch}. Skipping automatic push.`)
177
- return { pushed: false, upstreamRef }
178
- }
179
-
180
- try {
181
- await runCommand('git', ['fetch', remoteName], { cwd: rootDir, silent: true })
182
- } catch (error) {
183
- logWarning(`Unable to fetch from ${remoteName} before push: ${error.message}`)
184
- }
185
-
186
- let remoteExists = true
187
-
188
- try {
189
- await runCommand('git', ['show-ref', '--verify', '--quiet', `refs/remotes/${upstreamRef}`], {
190
- cwd: rootDir,
191
- silent: true
192
- })
193
- } catch {
194
- remoteExists = false
195
- }
196
-
197
- let aheadCount = 0
198
- let behindCount = 0
199
-
200
- if (remoteExists) {
201
- const aheadOutput = await runCommandCapture('git', ['rev-list', '--count', `${upstreamRef}..HEAD`], {
202
- cwd: rootDir
203
- })
204
-
205
- aheadCount = parseInt(aheadOutput.trim() || '0', 10)
206
-
207
- const behindOutput = await runCommandCapture('git', ['rev-list', '--count', `HEAD..${upstreamRef}`], {
208
- cwd: rootDir
209
- })
210
-
211
- behindCount = parseInt(behindOutput.trim() || '0', 10)
212
- } else {
213
- aheadCount = 1
214
- }
215
-
216
- if (Number.isFinite(behindCount) && behindCount > 0) {
217
- throw new Error(
218
- `Local branch ${targetBranch} is behind ${upstreamRef} by ${behindCount} commit${behindCount === 1 ? '' : 's'}. Pull or rebase before deployment.`
219
- )
220
- }
221
-
222
- if (!Number.isFinite(aheadCount) || aheadCount <= 0) {
223
- return { pushed: false, upstreamRef }
224
- }
225
-
226
- const commitLabel = aheadCount === 1 ? 'commit' : 'commits'
227
- logProcessing(`Found ${aheadCount} ${commitLabel} not yet pushed to ${upstreamRef}. Pushing before deployment...`)
228
-
229
- await runCommand('git', ['push', remoteName, `${targetBranch}:${upstreamBranch}`], { cwd: rootDir })
230
- logSuccess(`Pushed committed changes to ${upstreamRef}.`)
231
-
232
- return { pushed: true, upstreamRef }
233
- }
234
-
235
- async function ensureLocalRepositoryState(targetBranch, rootDir = process.cwd()) {
236
- if (!targetBranch) {
237
- throw new Error('Deployment branch is not defined in the release configuration.')
238
- }
239
-
240
- const currentBranch = await getCurrentBranch(rootDir)
241
-
242
- if (!currentBranch) {
243
- throw new Error('Unable to determine the current git branch. Ensure this is a git repository.')
244
- }
245
-
246
- const initialStatus = await getGitStatus(rootDir)
247
- const hasPendingChanges = initialStatus.length > 0
248
-
249
- const statusReport = await runCommandCapture('git', ['status', '--short', '--branch'], {
250
- cwd: rootDir
251
- })
252
-
253
- const lines = statusReport.split(/\r?\n/)
254
- const branchLine = lines[0] || ''
255
- const aheadMatch = branchLine.match(/ahead (\d+)/)
256
- const behindMatch = branchLine.match(/behind (\d+)/)
257
- const aheadCount = aheadMatch ? parseInt(aheadMatch[1], 10) : 0
258
- const behindCount = behindMatch ? parseInt(behindMatch[1], 10) : 0
259
-
260
- if (aheadCount > 0) {
261
- logWarning(`Local branch ${currentBranch} is ahead of upstream by ${aheadCount} commit${aheadCount === 1 ? '' : 's'}.`)
262
- }
263
-
264
- if (behindCount > 0) {
265
- logProcessing(`Synchronizing local branch ${currentBranch} with its upstream...`)
266
- try {
267
- await runCommand('git', ['pull', '--ff-only'], { cwd: rootDir })
268
- logSuccess('Local branch fast-forwarded with upstream changes.')
269
- } catch (error) {
270
- throw new Error(
271
- `Unable to fast-forward ${currentBranch} with upstream changes. Resolve conflicts manually, then rerun the deployment.\n${error.message}`
272
- )
273
- }
274
- }
275
-
276
- if (currentBranch !== targetBranch) {
277
- if (hasPendingChanges) {
278
- throw new Error(
279
- `Local repository has uncommitted changes on ${currentBranch}. Commit or stash them before switching to ${targetBranch}.`
280
- )
281
- }
282
-
283
- logProcessing(`Switching local repository from ${currentBranch} to ${targetBranch}...`)
284
- await runCommand('git', ['checkout', targetBranch], { cwd: rootDir })
285
- logSuccess(`Checked out ${targetBranch} locally.`)
286
- }
287
-
288
- const statusAfterCheckout = currentBranch === targetBranch ? initialStatus : await getGitStatus(rootDir)
289
-
290
- if (statusAfterCheckout.length === 0) {
291
- await ensureCommittedChangesPushed(targetBranch, rootDir)
292
- logProcessing('Local repository is clean. Proceeding with deployment.')
293
- return
294
- }
295
-
296
- if (!hasStagedChanges(statusAfterCheckout)) {
297
- await ensureCommittedChangesPushed(targetBranch, rootDir)
298
- logProcessing('No staged changes detected. Unstaged or untracked files will not affect deployment. Proceeding with deployment.')
299
- return
300
- }
301
-
302
- logWarning(`Staged changes detected on ${targetBranch}. A commit is required before deployment.`)
303
-
304
- const { commitMessage } = await runPrompt([
305
- {
306
- type: 'input',
307
- name: 'commitMessage',
308
- message: 'Enter a commit message for pending changes before deployment',
309
- validate: (value) => (value && value.trim().length > 0 ? true : 'Commit message cannot be empty.')
310
- }
311
- ])
312
-
313
- const message = commitMessage.trim()
314
-
315
- logProcessing('Committing staged changes before deployment...')
316
- await runCommand('git', ['commit', '-m', message], { cwd: rootDir })
317
- await runCommand('git', ['push', 'origin', targetBranch], { cwd: rootDir })
318
- logSuccess(`Committed and pushed changes to origin/${targetBranch}.`)
319
-
320
- const finalStatus = await getGitStatus(rootDir)
321
-
322
- if (finalStatus.length > 0) {
323
- throw new Error('Local repository still has uncommitted changes after commit. Aborting deployment.')
324
- }
325
-
326
- await ensureCommittedChangesPushed(targetBranch, rootDir)
327
- logProcessing('Local repository is clean after committing pending changes.')
328
- }
329
-
330
- async function ensureProjectReleaseScript(rootDir) {
331
- const packageJsonPath = path.join(rootDir, 'package.json')
332
-
333
- let raw
334
- try {
335
- raw = await fs.readFile(packageJsonPath, 'utf8')
336
- } catch (error) {
337
- if (error.code === 'ENOENT') {
338
- return false
339
- }
340
-
341
- throw error
342
- }
343
-
344
- let packageJson
345
- try {
346
- packageJson = JSON.parse(raw)
347
- } catch (error) {
348
- logWarning('Unable to parse package.json; skipping release script injection.')
349
- return false
350
- }
351
-
352
- const currentCommand = packageJson?.scripts?.[RELEASE_SCRIPT_NAME]
353
-
354
- if (currentCommand && currentCommand.includes('@wyxos/zephyr')) {
355
- return false
356
- }
357
-
358
- const { installReleaseScript } = await runPrompt([
359
- {
360
- type: 'confirm',
361
- name: 'installReleaseScript',
362
- message: 'Add "release" script to package.json that runs "npx @wyxos/zephyr@latest"?',
363
- default: true
364
- }
365
- ])
366
-
367
- if (!installReleaseScript) {
368
- return false
369
- }
370
-
371
- if (!packageJson.scripts || typeof packageJson.scripts !== 'object') {
372
- packageJson.scripts = {}
373
- }
374
-
375
- packageJson.scripts[RELEASE_SCRIPT_NAME] = RELEASE_SCRIPT_COMMAND
376
-
377
- const updatedPayload = `${JSON.stringify(packageJson, null, 2)}\n`
378
- await fs.writeFile(packageJsonPath, updatedPayload)
379
- logSuccess('Added release script to package.json.')
380
-
381
- let isGitRepo = false
382
-
383
- try {
384
- await runCommand('git', ['rev-parse', '--is-inside-work-tree'], { cwd: rootDir, silent: true })
385
- isGitRepo = true
386
- } catch (error) {
387
- logWarning('Not a git repository; skipping commit for release script addition.')
388
- }
389
-
390
- if (isGitRepo) {
391
- try {
392
- await runCommand('git', ['add', 'package.json'], { cwd: rootDir, silent: true })
393
- await runCommand('git', ['commit', '-m', 'chore: add zephyr release script'], { cwd: rootDir, silent: true })
394
- logSuccess('Committed package.json release script addition.')
395
- } catch (error) {
396
- if (error.exitCode === 1) {
397
- logWarning('Git commit skipped: nothing to commit or pre-commit hook prevented commit.')
398
- } else {
399
- throw error
400
- }
401
- }
402
- }
403
-
404
- return true
405
- }
406
-
407
- function getProjectConfigDir(rootDir) {
408
- return path.join(rootDir, PROJECT_CONFIG_DIR)
409
- }
410
-
411
- function getPendingTasksPath(rootDir) {
412
- return path.join(getProjectConfigDir(rootDir), PENDING_TASKS_FILE)
413
- }
414
-
415
- function getLockFilePath(rootDir) {
416
- return path.join(getProjectConfigDir(rootDir), PROJECT_LOCK_FILE)
417
- }
418
-
419
- async function acquireProjectLock(rootDir) {
420
- const lockDir = getProjectConfigDir(rootDir)
421
- await ensureDirectory(lockDir)
422
- const lockPath = getLockFilePath(rootDir)
423
-
424
- try {
425
- const existing = await fs.readFile(lockPath, 'utf8')
426
- let details = {}
427
- try {
428
- details = JSON.parse(existing)
429
- } catch (error) {
430
- details = { raw: existing }
431
- }
432
-
433
- const startedBy = details.user ? `${details.user}@${details.hostname ?? 'unknown'}` : 'unknown user'
434
- const startedAt = details.startedAt ? ` at ${details.startedAt}` : ''
435
- throw new Error(
436
- `Another deployment is currently in progress (started by ${startedBy}${startedAt}). Remove ${lockPath} if you are sure it is stale.`
437
- )
438
- } catch (error) {
439
- if (error.code !== 'ENOENT') {
440
- throw error
441
- }
442
- }
443
-
444
- const payload = {
445
- user: os.userInfo().username,
446
- pid: process.pid,
447
- hostname: os.hostname(),
448
- startedAt: new Date().toISOString()
449
- }
450
-
451
- await fs.writeFile(lockPath, `${JSON.stringify(payload, null, 2)}\n`)
452
- return lockPath
453
- }
454
-
455
- async function releaseProjectLock(rootDir) {
456
- const lockPath = getLockFilePath(rootDir)
457
- try {
458
- await fs.unlink(lockPath)
459
- } catch (error) {
460
- if (error.code !== 'ENOENT') {
461
- throw error
462
- }
463
- }
464
- }
465
-
466
- async function loadPendingTasksSnapshot(rootDir) {
467
- const snapshotPath = getPendingTasksPath(rootDir)
468
-
469
- try {
470
- const raw = await fs.readFile(snapshotPath, 'utf8')
471
- return JSON.parse(raw)
472
- } catch (error) {
473
- if (error.code === 'ENOENT') {
474
- return null
475
- }
476
-
477
- throw error
478
- }
479
- }
480
-
481
- async function savePendingTasksSnapshot(rootDir, snapshot) {
482
- const configDir = getProjectConfigDir(rootDir)
483
- await ensureDirectory(configDir)
484
- const payload = `${JSON.stringify(snapshot, null, 2)}\n`
485
- await fs.writeFile(getPendingTasksPath(rootDir), payload)
486
- }
487
-
488
- async function clearPendingTasksSnapshot(rootDir) {
489
- try {
490
- await fs.unlink(getPendingTasksPath(rootDir))
491
- } catch (error) {
492
- if (error.code !== 'ENOENT') {
493
- throw error
494
- }
495
- }
496
- }
497
-
498
- async function ensureGitignoreEntry(rootDir) {
499
- const gitignorePath = path.join(rootDir, '.gitignore')
500
- const targetEntry = `${PROJECT_CONFIG_DIR}/`
501
- let existingContent = ''
502
-
503
- try {
504
- existingContent = await fs.readFile(gitignorePath, 'utf8')
505
- } catch (error) {
506
- if (error.code !== 'ENOENT') {
507
- throw error
508
- }
509
- }
510
-
511
- const hasEntry = existingContent
512
- .split(/\r?\n/)
513
- .some((line) => line.trim() === targetEntry)
514
-
515
- if (hasEntry) {
516
- return
517
- }
518
-
519
- const updatedContent = existingContent
520
- ? `${existingContent.replace(/\s*$/, '')}\n${targetEntry}\n`
521
- : `${targetEntry}\n`
522
-
523
- await fs.writeFile(gitignorePath, updatedContent)
524
- logSuccess('Added .zephyr/ to .gitignore')
525
-
526
- let isGitRepo = false
527
- try {
528
- await runCommand('git', ['rev-parse', '--is-inside-work-tree'], {
529
- silent: true,
530
- cwd: rootDir
531
- })
532
- isGitRepo = true
533
- } catch (error) {
534
- logWarning('Not a git repository; skipping commit for .gitignore update.')
535
- }
536
-
537
- if (!isGitRepo) {
538
- return
539
- }
540
-
541
- try {
542
- await runCommand('git', ['add', '.gitignore'], { cwd: rootDir })
543
- await runCommand('git', ['commit', '-m', 'chore: ignore zephyr config'], { cwd: rootDir })
544
- } catch (error) {
545
- if (error.exitCode === 1) {
546
- logWarning('Git commit skipped: nothing to commit or pre-commit hook prevented commit.')
547
- } else {
548
- throw error
549
- }
550
- }
551
- }
552
-
553
- async function ensureDirectory(dirPath) {
554
- await fs.mkdir(dirPath, { recursive: true })
555
- }
556
-
557
- async function loadServers() {
558
- try {
559
- const raw = await fs.readFile(SERVERS_FILE, 'utf8')
560
- const data = JSON.parse(raw)
561
- return Array.isArray(data) ? data : []
562
- } catch (error) {
563
- if (error.code === 'ENOENT') {
564
- return []
565
- }
566
-
567
- logWarning('Failed to read servers.json, starting with an empty list.')
568
- return []
569
- }
570
- }
571
-
572
- async function saveServers(servers) {
573
- await ensureDirectory(GLOBAL_CONFIG_DIR)
574
- const payload = JSON.stringify(servers, null, 2)
575
- await fs.writeFile(SERVERS_FILE, `${payload}\n`)
576
- }
577
-
578
- function getProjectConfigPath(rootDir) {
579
- return path.join(rootDir, PROJECT_CONFIG_DIR, PROJECT_CONFIG_FILE)
580
- }
581
-
582
- async function loadProjectConfig(rootDir) {
583
- const configPath = getProjectConfigPath(rootDir)
584
-
585
- try {
586
- const raw = await fs.readFile(configPath, 'utf8')
587
- const data = JSON.parse(raw)
588
- return {
589
- apps: Array.isArray(data?.apps) ? data.apps : []
590
- }
591
- } catch (error) {
592
- if (error.code === 'ENOENT') {
593
- return { apps: [] }
594
- }
595
-
596
- logWarning('Failed to read .zephyr/config.json, starting with an empty list of apps.')
597
- return { apps: [] }
598
- }
599
- }
600
-
601
- async function saveProjectConfig(rootDir, config) {
602
- const configDir = path.join(rootDir, PROJECT_CONFIG_DIR)
603
- await ensureDirectory(configDir)
604
- const payload = JSON.stringify({ apps: config.apps ?? [] }, null, 2)
605
- await fs.writeFile(path.join(configDir, PROJECT_CONFIG_FILE), `${payload}\n`)
606
- }
607
-
608
- function defaultProjectPath(currentDir) {
609
- return `~/webapps/${path.basename(currentDir)}`
610
- }
611
-
612
- async function listGitBranches(currentDir) {
613
- try {
614
- const output = await runCommandCapture(
615
- 'git',
616
- ['branch', '--format', '%(refname:short)'],
617
- { cwd: currentDir }
618
- )
619
-
620
- const branches = output
621
- .split(/\r?\n/)
622
- .map((line) => line.trim())
623
- .filter(Boolean)
624
-
625
- return branches.length ? branches : ['master']
626
- } catch (error) {
627
- logWarning('Unable to read git branches; defaulting to master.')
628
- return ['master']
629
- }
630
- }
631
-
632
- async function listSshKeys() {
633
- const sshDir = path.join(os.homedir(), '.ssh')
634
-
635
- try {
636
- const entries = await fs.readdir(sshDir, { withFileTypes: true })
637
-
638
- const candidates = entries
639
- .filter((entry) => entry.isFile())
640
- .map((entry) => entry.name)
641
- .filter((name) => {
642
- if (!name) return false
643
- if (name.startsWith('.')) return false
644
- if (name.endsWith('.pub')) return false
645
- if (name.startsWith('known_hosts')) return false
646
- if (name === 'config') return false
647
- return name.trim().length > 0
648
- })
649
-
650
- const keys = []
651
-
652
- for (const name of candidates) {
653
- const filePath = path.join(sshDir, name)
654
- if (await isPrivateKeyFile(filePath)) {
655
- keys.push(name)
656
- }
657
- }
658
-
659
- return {
660
- sshDir,
661
- keys
662
- }
663
- } catch (error) {
664
- if (error.code === 'ENOENT') {
665
- return {
666
- sshDir,
667
- keys: []
668
- }
669
- }
670
-
671
- throw error
672
- }
673
- }
674
-
675
- async function isPrivateKeyFile(filePath) {
676
- try {
677
- const content = await fs.readFile(filePath, 'utf8')
678
- return /-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(content)
679
- } catch (error) {
680
- return false
681
- }
682
- }
683
-
684
- async function promptSshDetails(currentDir, existing = {}) {
685
- const { sshDir, keys: sshKeys } = await listSshKeys()
686
- const defaultUser = existing.sshUser || os.userInfo().username
687
- const fallbackKey = path.join(sshDir, 'id_rsa')
688
- const preselectedKey = existing.sshKey || (sshKeys.length ? path.join(sshDir, sshKeys[0]) : fallbackKey)
689
-
690
- const sshKeyPrompt = sshKeys.length
691
- ? {
692
- type: 'list',
693
- name: 'sshKeySelection',
694
- message: 'SSH key',
695
- choices: [
696
- ...sshKeys.map((key) => ({ name: key, value: path.join(sshDir, key) })),
697
- new inquirer.Separator(),
698
- { name: 'Enter custom SSH key path…', value: '__custom' }
699
- ],
700
- default: preselectedKey
701
- }
702
- : {
703
- type: 'input',
704
- name: 'sshKeySelection',
705
- message: 'SSH key path',
706
- default: preselectedKey
707
- }
708
-
709
- const answers = await runPrompt([
710
- {
711
- type: 'input',
712
- name: 'sshUser',
713
- message: 'SSH user',
714
- default: defaultUser
715
- },
716
- sshKeyPrompt
717
- ])
718
-
719
- let sshKey = answers.sshKeySelection
720
-
721
- if (sshKey === '__custom') {
722
- const { customSshKey } = await runPrompt([
723
- {
724
- type: 'input',
725
- name: 'customSshKey',
726
- message: 'SSH key path',
727
- default: preselectedKey
728
- }
729
- ])
730
-
731
- sshKey = customSshKey.trim() || preselectedKey
732
- }
733
-
734
- return {
735
- sshUser: answers.sshUser.trim() || defaultUser,
736
- sshKey: sshKey.trim() || preselectedKey
737
- }
738
- }
739
-
740
- async function ensureSshDetails(config, currentDir) {
741
- if (config.sshUser && config.sshKey) {
742
- return false
743
- }
744
-
745
- logProcessing('SSH details missing. Please provide them now.')
746
- const details = await promptSshDetails(currentDir, config)
747
- Object.assign(config, details)
748
- return true
749
- }
750
-
751
- function expandHomePath(targetPath) {
752
- if (!targetPath) {
753
- return targetPath
754
- }
755
-
756
- if (targetPath.startsWith('~')) {
757
- return path.join(os.homedir(), targetPath.slice(1))
758
- }
759
-
760
- return targetPath
761
- }
762
-
763
- async function resolveSshKeyPath(targetPath) {
764
- const expanded = expandHomePath(targetPath)
765
-
766
- try {
767
- await fs.access(expanded)
768
- } catch (error) {
769
- throw new Error(`SSH key not accessible at ${expanded}`)
770
- }
771
-
772
- return expanded
773
- }
774
-
775
- function resolveRemotePath(projectPath, remoteHome) {
776
- if (!projectPath) {
777
- return projectPath
778
- }
779
-
780
- const sanitizedHome = remoteHome.replace(/\/+$/, '')
781
-
782
- if (projectPath === '~') {
783
- return sanitizedHome
784
- }
785
-
786
- if (projectPath.startsWith('~/')) {
787
- const remainder = projectPath.slice(2)
788
- return remainder ? `${sanitizedHome}/${remainder}` : sanitizedHome
789
- }
790
-
791
- if (projectPath.startsWith('/')) {
792
- return projectPath
793
- }
794
-
795
- return `${sanitizedHome}/${projectPath}`
796
- }
797
-
798
- async function runRemoteTasks(config, options = {}) {
799
- const { snapshot = null, rootDir = process.cwd() } = options
800
-
801
- await ensureLocalRepositoryState(config.branch, rootDir)
802
-
803
- const ssh = createSshClient()
804
- const sshUser = config.sshUser || os.userInfo().username
805
- const privateKeyPath = await resolveSshKeyPath(config.sshKey)
806
- const privateKey = await fs.readFile(privateKeyPath, 'utf8')
807
-
808
- logProcessing(`\nConnecting to ${config.serverIp} as ${sshUser}...`)
809
-
810
- try {
811
- await ssh.connect({
812
- host: config.serverIp,
813
- username: sshUser,
814
- privateKey
815
- })
816
-
817
- const remoteHomeResult = await ssh.execCommand('printf "%s" "$HOME"')
818
- const remoteHome = remoteHomeResult.stdout.trim() || `/home/${sshUser}`
819
- const remoteCwd = resolveRemotePath(config.projectPath, remoteHome)
820
-
821
- logProcessing(`Connection established. Running deployment commands in ${remoteCwd}...`)
822
-
823
- // Robust environment bootstrap that works even when profile files don't export PATH
824
- // for non-interactive shells. This handles:
825
- // 1. Sourcing profile files (may not export PATH for non-interactive shells)
826
- // 2. Loading nvm if available (common Node.js installation method)
827
- // 3. Finding and adding common Node.js/npm installation paths
828
- const profileBootstrap = [
829
- // Source profile files (may set PATH, but often skip for non-interactive shells)
830
- 'if [ -f "$HOME/.profile" ]; then . "$HOME/.profile"; fi',
831
- 'if [ -f "$HOME/.bash_profile" ]; then . "$HOME/.bash_profile"; fi',
832
- 'if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc"; fi',
833
- 'if [ -f "$HOME/.zprofile" ]; then . "$HOME/.zprofile"; fi',
834
- 'if [ -f "$HOME/.zshrc" ]; then . "$HOME/.zshrc"; fi',
835
- // Load nvm if available (common Node.js installation method)
836
- 'if [ -s "$HOME/.nvm/nvm.sh" ]; then . "$HOME/.nvm/nvm.sh"; fi',
837
- 'if [ -s "$HOME/.config/nvm/nvm.sh" ]; then . "$HOME/.config/nvm/nvm.sh"; fi',
838
- 'if [ -s "/usr/local/opt/nvm/nvm.sh" ]; then . "/usr/local/opt/nvm/nvm.sh"; fi',
839
- // Try to find npm/node in common locations and add to PATH
840
- 'if command -v npm >/dev/null 2>&1; then :',
841
- '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"',
842
- 'elif [ -d "/usr/local/lib/node_modules/npm/bin" ]; then export PATH="/usr/local/lib/node_modules/npm/bin:$PATH"',
843
- 'elif [ -d "/opt/homebrew/bin" ] && [ -f "/opt/homebrew/bin/npm" ]; then export PATH="/opt/homebrew/bin:$PATH"',
844
- 'elif [ -d "/usr/local/bin" ] && [ -f "/usr/local/bin/npm" ]; then export PATH="/usr/local/bin:$PATH"',
845
- 'elif [ -d "$HOME/.local/bin" ] && [ -f "$HOME/.local/bin/npm" ]; then export PATH="$HOME/.local/bin:$PATH"',
846
- 'fi'
847
- ].join('; ')
848
-
849
- const escapeForDoubleQuotes = (value) => value.replace(/(["\\$`])/g, '\\$1')
850
-
851
- const executeRemote = async (label, command, options = {}) => {
852
- const { cwd = remoteCwd, allowFailure = false, printStdout = true, bootstrapEnv = true } = options
853
- logProcessing(`\n→ ${label}`)
854
-
855
- let wrappedCommand = command
856
- let execOptions = { cwd }
857
-
858
- if (bootstrapEnv) {
859
- const cwdForShell = escapeForDoubleQuotes(cwd)
860
- wrappedCommand = `${profileBootstrap}; cd "${cwdForShell}" && ${command}`
861
- execOptions = {}
862
- }
863
-
864
- const result = await ssh.execCommand(wrappedCommand, execOptions)
865
-
866
- // Log all output to file
867
- if (result.stdout && result.stdout.trim()) {
868
- await writeToLogFile(rootDir, `[${label}] STDOUT:\n${result.stdout.trim()}`)
869
- }
870
-
871
- if (result.stderr && result.stderr.trim()) {
872
- await writeToLogFile(rootDir, `[${label}] STDERR:\n${result.stderr.trim()}`)
873
- }
874
-
875
- // Only show errors in terminal
876
- if (result.code !== 0) {
877
- if (result.stdout && result.stdout.trim()) {
878
- logError(`\n[${label}] Output:\n${result.stdout.trim()}`)
879
- }
880
-
881
- if (result.stderr && result.stderr.trim()) {
882
- logError(`\n[${label}] Error:\n${result.stderr.trim()}`)
883
- }
884
- }
885
-
886
- if (result.code !== 0 && !allowFailure) {
887
- const stderr = result.stderr?.trim() ?? ''
888
- if (/command not found/.test(stderr) || /is not recognized/.test(stderr)) {
889
- throw new Error(
890
- `Command failed: ${command}. Ensure the remote environment loads required tools for non-interactive shells (e.g. export PATH in profile scripts).`
891
- )
892
- }
893
-
894
- throw new Error(`Command failed: ${command}`)
895
- }
896
-
897
- // Show success confirmation with command
898
- if (result.code === 0) {
899
- logSuccess(`✓ ${command}`)
900
- }
901
-
902
- return result
903
- }
904
-
905
- const laravelCheck = await ssh.execCommand(
906
- 'if [ -f artisan ] && [ -f composer.json ] && grep -q "laravel/framework" composer.json; then echo "yes"; else echo "no"; fi',
907
- { cwd: remoteCwd }
908
- )
909
- const isLaravel = laravelCheck.stdout.trim() === 'yes'
910
-
911
- if (isLaravel) {
912
- logSuccess('Laravel project detected.')
913
- } else {
914
- logWarning('Laravel project not detected; skipping Laravel-specific maintenance tasks.')
915
- }
916
-
917
- let changedFiles = []
918
-
919
- if (snapshot && snapshot.changedFiles) {
920
- changedFiles = snapshot.changedFiles
921
- logProcessing('Resuming deployment with saved task snapshot.')
922
- } else if (isLaravel) {
923
- await executeRemote(`Fetch latest changes for ${config.branch}`, `git fetch origin ${config.branch}`)
924
-
925
- const diffResult = await executeRemote(
926
- 'Inspect pending changes',
927
- `git diff --name-only HEAD..origin/${config.branch}`,
928
- { printStdout: false }
929
- )
930
-
931
- changedFiles = diffResult.stdout
932
- .split(/\r?\n/)
933
- .map((line) => line.trim())
934
- .filter(Boolean)
935
-
936
- if (changedFiles.length > 0) {
937
- const preview = changedFiles
938
- .slice(0, 20)
939
- .map((file) => ` - ${file}`)
940
- .join('\n')
941
-
942
- logProcessing(
943
- `Detected ${changedFiles.length} changed file(s):\n${preview}${changedFiles.length > 20 ? '\n - ...' : ''
944
- }`
945
- )
946
- } else {
947
- logProcessing('No upstream file changes detected.')
948
- }
949
- }
950
-
951
- const shouldRunComposer =
952
- isLaravel &&
953
- changedFiles.some(
954
- (file) =>
955
- file === 'composer.json' ||
956
- file === 'composer.lock' ||
957
- file.endsWith('/composer.json') ||
958
- file.endsWith('/composer.lock')
959
- )
960
-
961
- const shouldRunMigrations =
962
- isLaravel &&
963
- changedFiles.some(
964
- (file) => file.startsWith('database/migrations/') && file.endsWith('.php')
965
- )
966
-
967
- const hasPhpChanges = isLaravel && changedFiles.some((file) => file.endsWith('.php'))
968
-
969
- const shouldRunNpmInstall =
970
- isLaravel &&
971
- changedFiles.some(
972
- (file) =>
973
- file === 'package.json' ||
974
- file === 'package-lock.json' ||
975
- file.endsWith('/package.json') ||
976
- file.endsWith('/package-lock.json')
977
- )
978
-
979
- const hasFrontendChanges =
980
- isLaravel &&
981
- changedFiles.some((file) =>
982
- ['.vue', '.css', '.scss', '.js', '.ts', '.tsx', '.less'].some((ext) =>
983
- file.endsWith(ext)
984
- )
985
- )
986
-
987
- const shouldRunBuild = isLaravel && (hasFrontendChanges || shouldRunNpmInstall)
988
- const shouldClearCaches = hasPhpChanges
989
- const shouldRestartQueues = hasPhpChanges
990
-
991
- let horizonConfigured = false
992
- if (shouldRestartQueues) {
993
- const horizonCheck = await ssh.execCommand(
994
- 'if [ -f config/horizon.php ]; then echo "yes"; else echo "no"; fi',
995
- { cwd: remoteCwd }
996
- )
997
- horizonConfigured = horizonCheck.stdout.trim() === 'yes'
998
- }
999
-
1000
- const steps = [
1001
- {
1002
- label: `Pull latest changes for ${config.branch}`,
1003
- command: `git pull origin ${config.branch}`
1004
- }
1005
- ]
1006
-
1007
- if (shouldRunComposer) {
1008
- steps.push({
1009
- label: 'Update Composer dependencies',
1010
- command: 'composer update --no-dev --no-interaction --prefer-dist'
1011
- })
1012
- }
1013
-
1014
- if (shouldRunMigrations) {
1015
- steps.push({
1016
- label: 'Run database migrations',
1017
- command: 'php artisan migrate --force'
1018
- })
1019
- }
1020
-
1021
- if (shouldRunNpmInstall) {
1022
- steps.push({
1023
- label: 'Install Node dependencies',
1024
- command: 'npm install'
1025
- })
1026
- }
1027
-
1028
- if (shouldRunBuild) {
1029
- steps.push({
1030
- label: 'Compile frontend assets',
1031
- command: 'npm run build'
1032
- })
1033
- }
1034
-
1035
- if (shouldClearCaches) {
1036
- steps.push({
1037
- label: 'Clear Laravel caches',
1038
- command: 'php artisan cache:clear && php artisan config:clear && php artisan view:clear'
1039
- })
1040
- }
1041
-
1042
- if (shouldRestartQueues) {
1043
- steps.push({
1044
- label: horizonConfigured ? 'Restart Horizon workers' : 'Restart queue workers',
1045
- command: horizonConfigured ? 'php artisan horizon:terminate' : 'php artisan queue:restart'
1046
- })
1047
- }
1048
-
1049
- const usefulSteps = steps.length > 1
1050
-
1051
- let pendingSnapshot
1052
-
1053
- if (usefulSteps) {
1054
- pendingSnapshot = snapshot ?? {
1055
- serverName: config.serverName,
1056
- branch: config.branch,
1057
- projectPath: config.projectPath,
1058
- sshUser: config.sshUser,
1059
- createdAt: new Date().toISOString(),
1060
- changedFiles,
1061
- taskLabels: steps.map((step) => step.label)
1062
- }
1063
-
1064
- await savePendingTasksSnapshot(rootDir, pendingSnapshot)
1065
-
1066
- const payload = Buffer.from(JSON.stringify(pendingSnapshot)).toString('base64')
1067
- await executeRemote(
1068
- 'Record pending deployment tasks',
1069
- `mkdir -p .zephyr && echo '${payload}' | base64 --decode > .zephyr/${PENDING_TASKS_FILE}`,
1070
- { printStdout: false }
1071
- )
1072
- }
1073
-
1074
- if (steps.length === 1) {
1075
- logProcessing('No additional maintenance tasks scheduled beyond git pull.')
1076
- } else {
1077
- const extraTasks = steps
1078
- .slice(1)
1079
- .map((step) => step.label)
1080
- .join(', ')
1081
-
1082
- logProcessing(`Additional tasks scheduled: ${extraTasks}`)
1083
- }
1084
-
1085
- let completed = false
1086
-
1087
- try {
1088
- for (const step of steps) {
1089
- await executeRemote(step.label, step.command)
1090
- }
1091
-
1092
- completed = true
1093
- } finally {
1094
- if (usefulSteps && completed) {
1095
- await executeRemote(
1096
- 'Clear pending deployment snapshot',
1097
- `rm -f .zephyr/${PENDING_TASKS_FILE}`,
1098
- { printStdout: false, allowFailure: true }
1099
- )
1100
- await clearPendingTasksSnapshot(rootDir)
1101
- }
1102
- }
1103
-
1104
- logSuccess('\nDeployment commands completed successfully.')
1105
-
1106
- const logPath = await getLogFilePath(rootDir)
1107
- logSuccess(`\nAll task output has been logged to: ${logPath}`)
1108
- } catch (error) {
1109
- const logPath = logFilePath || await getLogFilePath(rootDir).catch(() => null)
1110
- if (logPath) {
1111
- logError(`\nTask output has been logged to: ${logPath}`)
1112
- }
1113
- throw new Error(`Deployment failed: ${error.message}`)
1114
- } finally {
1115
- await closeLogFile()
1116
- ssh.dispose()
1117
- }
1118
- }
1119
-
1120
- async function promptServerDetails(existingServers = []) {
1121
- const defaults = {
1122
- serverName: existingServers.length === 0 ? 'home' : `server-${existingServers.length + 1}`,
1123
- serverIp: '1.1.1.1'
1124
- }
1125
-
1126
- const answers = await runPrompt([
1127
- {
1128
- type: 'input',
1129
- name: 'serverName',
1130
- message: 'Server name',
1131
- default: defaults.serverName
1132
- },
1133
- {
1134
- type: 'input',
1135
- name: 'serverIp',
1136
- message: 'Server IP address',
1137
- default: defaults.serverIp
1138
- }
1139
- ])
1140
-
1141
- return {
1142
- serverName: answers.serverName.trim() || defaults.serverName,
1143
- serverIp: answers.serverIp.trim() || defaults.serverIp
1144
- }
1145
- }
1146
-
1147
- async function selectServer(servers) {
1148
- if (servers.length === 0) {
1149
- logProcessing("No servers configured. Let's create one.")
1150
- const server = await promptServerDetails()
1151
- servers.push(server)
1152
- await saveServers(servers)
1153
- logSuccess('Saved server configuration to ~/.config/zephyr/servers.json')
1154
- return server
1155
- }
1156
-
1157
- const choices = servers.map((server, index) => ({
1158
- name: `${server.serverName} (${server.serverIp})`,
1159
- value: index
1160
- }))
1161
-
1162
- choices.push(new inquirer.Separator(), {
1163
- name: '➕ Register a new server',
1164
- value: 'create'
1165
- })
1166
-
1167
- const { selection } = await runPrompt([
1168
- {
1169
- type: 'list',
1170
- name: 'selection',
1171
- message: 'Select server or register new',
1172
- choices,
1173
- default: 0
1174
- }
1175
- ])
1176
-
1177
- if (selection === 'create') {
1178
- const server = await promptServerDetails(servers)
1179
- servers.push(server)
1180
- await saveServers(servers)
1181
- logSuccess('Appended server configuration to ~/.config/zephyr/servers.json')
1182
- return server
1183
- }
1184
-
1185
- return servers[selection]
1186
- }
1187
-
1188
- async function promptAppDetails(currentDir, existing = {}) {
1189
- const branches = await listGitBranches(currentDir)
1190
- const defaultBranch = existing.branch || (branches.includes('master') ? 'master' : branches[0])
1191
- const defaults = {
1192
- projectPath: existing.projectPath || defaultProjectPath(currentDir),
1193
- branch: defaultBranch
1194
- }
1195
-
1196
- const answers = await runPrompt([
1197
- {
1198
- type: 'input',
1199
- name: 'projectPath',
1200
- message: 'Remote project path',
1201
- default: defaults.projectPath
1202
- },
1203
- {
1204
- type: 'list',
1205
- name: 'branchSelection',
1206
- message: 'Branch to deploy',
1207
- choices: [
1208
- ...branches.map((branch) => ({ name: branch, value: branch })),
1209
- new inquirer.Separator(),
1210
- { name: 'Enter custom branch…', value: '__custom' }
1211
- ],
1212
- default: defaults.branch
1213
- }
1214
- ])
1215
-
1216
- let branch = answers.branchSelection
1217
-
1218
- if (branch === '__custom') {
1219
- const { customBranch } = await runPrompt([
1220
- {
1221
- type: 'input',
1222
- name: 'customBranch',
1223
- message: 'Custom branch name',
1224
- default: defaults.branch
1225
- }
1226
- ])
1227
-
1228
- branch = customBranch.trim() || defaults.branch
1229
- }
1230
-
1231
- const sshDetails = await promptSshDetails(currentDir, existing)
1232
-
1233
- return {
1234
- projectPath: answers.projectPath.trim() || defaults.projectPath,
1235
- branch,
1236
- ...sshDetails
1237
- }
1238
- }
1239
-
1240
- async function selectApp(projectConfig, server, currentDir) {
1241
- const apps = projectConfig.apps ?? []
1242
- const matches = apps
1243
- .map((app, index) => ({ app, index }))
1244
- .filter(({ app }) => app.serverName === server.serverName)
1245
-
1246
- if (matches.length === 0) {
1247
- logProcessing(`No applications configured for ${server.serverName}. Let's create one.`)
1248
- const appDetails = await promptAppDetails(currentDir)
1249
- const appConfig = {
1250
- serverName: server.serverName,
1251
- ...appDetails
1252
- }
1253
- projectConfig.apps.push(appConfig)
1254
- await saveProjectConfig(currentDir, projectConfig)
1255
- logSuccess('Saved deployment configuration to .zephyr/config.json')
1256
- return appConfig
1257
- }
1258
-
1259
- const choices = matches.map(({ app, index }) => ({
1260
- name: `${app.projectPath} (${app.branch})`,
1261
- value: index
1262
- }))
1263
-
1264
- choices.push(new inquirer.Separator(), {
1265
- name: '➕ Configure new application for this server',
1266
- value: 'create'
1267
- })
1268
-
1269
- const { selection } = await runPrompt([
1270
- {
1271
- type: 'list',
1272
- name: 'selection',
1273
- message: `Select application for ${server.serverName}`,
1274
- choices,
1275
- default: 0
1276
- }
1277
- ])
1278
-
1279
- if (selection === 'create') {
1280
- const appDetails = await promptAppDetails(currentDir)
1281
- const appConfig = {
1282
- serverName: server.serverName,
1283
- ...appDetails
1284
- }
1285
- projectConfig.apps.push(appConfig)
1286
- await saveProjectConfig(currentDir, projectConfig)
1287
- logSuccess('Appended deployment configuration to .zephyr/config.json')
1288
- return appConfig
1289
- }
1290
-
1291
- const chosen = projectConfig.apps[selection]
1292
- return chosen
1293
- }
1294
-
1295
- async function main() {
1296
- const rootDir = process.cwd()
1297
-
1298
- await ensureGitignoreEntry(rootDir)
1299
- await ensureProjectReleaseScript(rootDir)
1300
-
1301
- const servers = await loadServers()
1302
- const server = await selectServer(servers)
1303
- const projectConfig = await loadProjectConfig(rootDir)
1304
- const appConfig = await selectApp(projectConfig, server, rootDir)
1305
-
1306
- const updated = await ensureSshDetails(appConfig, rootDir)
1307
-
1308
- if (updated) {
1309
- await saveProjectConfig(rootDir, projectConfig)
1310
- logSuccess('Updated .zephyr/config.json with SSH details.')
1311
- }
1312
-
1313
- const deploymentConfig = {
1314
- serverName: server.serverName,
1315
- serverIp: server.serverIp,
1316
- projectPath: appConfig.projectPath,
1317
- branch: appConfig.branch,
1318
- sshUser: appConfig.sshUser,
1319
- sshKey: appConfig.sshKey
1320
- }
1321
-
1322
- logProcessing('\nSelected deployment target:')
1323
- console.log(JSON.stringify(deploymentConfig, null, 2))
1324
-
1325
- const existingSnapshot = await loadPendingTasksSnapshot(rootDir)
1326
- let snapshotToUse = null
1327
-
1328
- if (existingSnapshot) {
1329
- const matchesSelection =
1330
- existingSnapshot.serverName === deploymentConfig.serverName &&
1331
- existingSnapshot.branch === deploymentConfig.branch
1332
-
1333
- const messageLines = [
1334
- 'Pending deployment tasks were detected from a previous run.',
1335
- `Server: ${existingSnapshot.serverName}`,
1336
- `Branch: ${existingSnapshot.branch}`
1337
- ]
1338
-
1339
- if (existingSnapshot.taskLabels && existingSnapshot.taskLabels.length > 0) {
1340
- messageLines.push(`Tasks: ${existingSnapshot.taskLabels.join(', ')}`)
1341
- }
1342
-
1343
- const { resumePendingTasks } = await runPrompt([
1344
- {
1345
- type: 'confirm',
1346
- name: 'resumePendingTasks',
1347
- message: `${messageLines.join(' | ')}. Resume using this plan?`,
1348
- default: matchesSelection
1349
- }
1350
- ])
1351
-
1352
- if (resumePendingTasks) {
1353
- snapshotToUse = existingSnapshot
1354
- logProcessing('Resuming deployment using saved task snapshot...')
1355
- } else {
1356
- await clearPendingTasksSnapshot(rootDir)
1357
- logWarning('Discarded pending deployment snapshot.')
1358
- }
1359
- }
1360
-
1361
- let lockAcquired = false
1362
-
1363
- try {
1364
- await acquireProjectLock(rootDir)
1365
- lockAcquired = true
1366
- await runRemoteTasks(deploymentConfig, { rootDir, snapshot: snapshotToUse })
1367
- } finally {
1368
- if (lockAcquired) {
1369
- await releaseProjectLock(rootDir)
1370
- }
1371
- }
1372
- }
1373
-
1374
- export {
1375
- ensureGitignoreEntry,
1376
- ensureProjectReleaseScript,
1377
- listSshKeys,
1378
- resolveRemotePath,
1379
- isPrivateKeyFile,
1380
- runRemoteTasks,
1381
- promptServerDetails,
1382
- selectServer,
1383
- promptAppDetails,
1384
- selectApp,
1385
- promptSshDetails,
1386
- ensureSshDetails,
1387
- ensureLocalRepositoryState,
1388
- loadServers,
1389
- loadProjectConfig,
1390
- main
1391
- }
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 chalk from 'chalk'
6
+ import inquirer from 'inquirer'
7
+ import { NodeSSH } from 'node-ssh'
8
+
9
+ const PROJECT_CONFIG_DIR = '.zephyr'
10
+ const PROJECT_CONFIG_FILE = 'config.json'
11
+ const GLOBAL_CONFIG_DIR = path.join(os.homedir(), '.config', 'zephyr')
12
+ const SERVERS_FILE = path.join(GLOBAL_CONFIG_DIR, 'servers.json')
13
+ const PROJECT_LOCK_FILE = 'deploy.lock'
14
+ const PENDING_TASKS_FILE = 'pending-tasks.json'
15
+ const RELEASE_SCRIPT_NAME = 'release'
16
+ const RELEASE_SCRIPT_COMMAND = 'npx @wyxos/zephyr@latest'
17
+
18
+ const logProcessing = (message = '') => console.log(chalk.yellow(message))
19
+ const logSuccess = (message = '') => console.log(chalk.green(message))
20
+ const logWarning = (message = '') => console.warn(chalk.yellow(message))
21
+ const logError = (message = '') => console.error(chalk.red(message))
22
+
23
+ let logFilePath = null
24
+
25
+ async function getLogFilePath(rootDir) {
26
+ if (logFilePath) {
27
+ return logFilePath
28
+ }
29
+
30
+ const configDir = getProjectConfigDir(rootDir)
31
+ await ensureDirectory(configDir)
32
+
33
+ const now = new Date()
34
+ const dateStr = now.toISOString().replace(/:/g, '-').replace(/\..+/, '')
35
+ logFilePath = path.join(configDir, `${dateStr}.log`)
36
+
37
+ return logFilePath
38
+ }
39
+
40
+ async function writeToLogFile(rootDir, message) {
41
+ const logPath = await getLogFilePath(rootDir)
42
+ const timestamp = new Date().toISOString()
43
+ await fs.appendFile(logPath, `${timestamp} - ${message}\n`)
44
+ }
45
+
46
+ async function closeLogFile() {
47
+ logFilePath = null
48
+ }
49
+
50
+ const createSshClient = () => {
51
+ if (typeof globalThis !== 'undefined' && globalThis.__zephyrSSHFactory) {
52
+ return globalThis.__zephyrSSHFactory()
53
+ }
54
+
55
+ return new NodeSSH()
56
+ }
57
+
58
+ const runPrompt = async (questions) => {
59
+ if (typeof globalThis !== 'undefined' && globalThis.__zephyrPrompt) {
60
+ return globalThis.__zephyrPrompt(questions)
61
+ }
62
+
63
+ return inquirer.prompt(questions)
64
+ }
65
+
66
+ async function runCommand(command, args, { silent = false, cwd } = {}) {
67
+ return new Promise((resolve, reject) => {
68
+ const child = spawn(command, args, {
69
+ stdio: silent ? 'ignore' : 'inherit',
70
+ cwd
71
+ })
72
+
73
+ child.on('error', reject)
74
+ child.on('close', (code) => {
75
+ if (code === 0) {
76
+ resolve()
77
+ } else {
78
+ const error = new Error(`${command} exited with code ${code}`)
79
+ error.exitCode = code
80
+ reject(error)
81
+ }
82
+ })
83
+ })
84
+ }
85
+
86
+ async function runCommandCapture(command, args, { cwd } = {}) {
87
+ return new Promise((resolve, reject) => {
88
+ let stdout = ''
89
+ let stderr = ''
90
+
91
+ const child = spawn(command, args, {
92
+ stdio: ['ignore', 'pipe', 'pipe'],
93
+ cwd
94
+ })
95
+
96
+ child.stdout.on('data', (chunk) => {
97
+ stdout += chunk
98
+ })
99
+
100
+ child.stderr.on('data', (chunk) => {
101
+ stderr += chunk
102
+ })
103
+
104
+ child.on('error', reject)
105
+ child.on('close', (code) => {
106
+ if (code === 0) {
107
+ resolve(stdout)
108
+ } else {
109
+ const error = new Error(`${command} exited with code ${code}: ${stderr.trim()}`)
110
+ error.exitCode = code
111
+ reject(error)
112
+ }
113
+ })
114
+ })
115
+ }
116
+
117
+ async function getCurrentBranch(rootDir) {
118
+ const output = await runCommandCapture('git', ['rev-parse', '--abbrev-ref', 'HEAD'], {
119
+ cwd: rootDir
120
+ })
121
+
122
+ return output.trim()
123
+ }
124
+
125
+ async function getGitStatus(rootDir) {
126
+ const output = await runCommandCapture('git', ['status', '--porcelain'], {
127
+ cwd: rootDir
128
+ })
129
+
130
+ return output.trim()
131
+ }
132
+
133
+ function hasStagedChanges(statusOutput) {
134
+ if (!statusOutput || statusOutput.length === 0) {
135
+ return false
136
+ }
137
+
138
+ const lines = statusOutput.split('\n').filter((line) => line.trim().length > 0)
139
+
140
+ return lines.some((line) => {
141
+ const firstChar = line[0]
142
+ // In git status --porcelain format:
143
+ // - First char is space: unstaged changes (e.g., " M file")
144
+ // - First char is '?': untracked files (e.g., "?? file")
145
+ // - First char is letter (M, A, D, etc.): staged changes (e.g., "M file")
146
+ // Only return true for staged changes, not unstaged or untracked
147
+ return firstChar && firstChar !== ' ' && firstChar !== '?'
148
+ })
149
+ }
150
+
151
+ async function getUpstreamRef(rootDir) {
152
+ try {
153
+ const output = await runCommandCapture('git', ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'], {
154
+ cwd: rootDir
155
+ })
156
+
157
+ const ref = output.trim()
158
+ return ref.length > 0 ? ref : null
159
+ } catch {
160
+ return null
161
+ }
162
+ }
163
+
164
+ async function ensureCommittedChangesPushed(targetBranch, rootDir) {
165
+ const upstreamRef = await getUpstreamRef(rootDir)
166
+
167
+ if (!upstreamRef) {
168
+ logWarning(`Branch ${targetBranch} does not track a remote upstream; skipping automatic push of committed changes.`)
169
+ return { pushed: false, upstreamRef: null }
170
+ }
171
+
172
+ const [remoteName, ...upstreamParts] = upstreamRef.split('/')
173
+ const upstreamBranch = upstreamParts.join('/')
174
+
175
+ if (!remoteName || !upstreamBranch) {
176
+ logWarning(`Unable to determine remote destination for ${targetBranch}. Skipping automatic push.`)
177
+ return { pushed: false, upstreamRef }
178
+ }
179
+
180
+ try {
181
+ await runCommand('git', ['fetch', remoteName], { cwd: rootDir, silent: true })
182
+ } catch (error) {
183
+ logWarning(`Unable to fetch from ${remoteName} before push: ${error.message}`)
184
+ }
185
+
186
+ let remoteExists = true
187
+
188
+ try {
189
+ await runCommand('git', ['show-ref', '--verify', '--quiet', `refs/remotes/${upstreamRef}`], {
190
+ cwd: rootDir,
191
+ silent: true
192
+ })
193
+ } catch {
194
+ remoteExists = false
195
+ }
196
+
197
+ let aheadCount = 0
198
+ let behindCount = 0
199
+
200
+ if (remoteExists) {
201
+ const aheadOutput = await runCommandCapture('git', ['rev-list', '--count', `${upstreamRef}..HEAD`], {
202
+ cwd: rootDir
203
+ })
204
+
205
+ aheadCount = parseInt(aheadOutput.trim() || '0', 10)
206
+
207
+ const behindOutput = await runCommandCapture('git', ['rev-list', '--count', `HEAD..${upstreamRef}`], {
208
+ cwd: rootDir
209
+ })
210
+
211
+ behindCount = parseInt(behindOutput.trim() || '0', 10)
212
+ } else {
213
+ aheadCount = 1
214
+ }
215
+
216
+ if (Number.isFinite(behindCount) && behindCount > 0) {
217
+ throw new Error(
218
+ `Local branch ${targetBranch} is behind ${upstreamRef} by ${behindCount} commit${behindCount === 1 ? '' : 's'}. Pull or rebase before deployment.`
219
+ )
220
+ }
221
+
222
+ if (!Number.isFinite(aheadCount) || aheadCount <= 0) {
223
+ return { pushed: false, upstreamRef }
224
+ }
225
+
226
+ const commitLabel = aheadCount === 1 ? 'commit' : 'commits'
227
+ logProcessing(`Found ${aheadCount} ${commitLabel} not yet pushed to ${upstreamRef}. Pushing before deployment...`)
228
+
229
+ await runCommand('git', ['push', remoteName, `${targetBranch}:${upstreamBranch}`], { cwd: rootDir })
230
+ logSuccess(`Pushed committed changes to ${upstreamRef}.`)
231
+
232
+ return { pushed: true, upstreamRef }
233
+ }
234
+
235
+ async function ensureLocalRepositoryState(targetBranch, rootDir = process.cwd()) {
236
+ if (!targetBranch) {
237
+ throw new Error('Deployment branch is not defined in the release configuration.')
238
+ }
239
+
240
+ const currentBranch = await getCurrentBranch(rootDir)
241
+
242
+ if (!currentBranch) {
243
+ throw new Error('Unable to determine the current git branch. Ensure this is a git repository.')
244
+ }
245
+
246
+ const initialStatus = await getGitStatus(rootDir)
247
+ const hasPendingChanges = initialStatus.length > 0
248
+
249
+ const statusReport = await runCommandCapture('git', ['status', '--short', '--branch'], {
250
+ cwd: rootDir
251
+ })
252
+
253
+ const lines = statusReport.split(/\r?\n/)
254
+ const branchLine = lines[0] || ''
255
+ const aheadMatch = branchLine.match(/ahead (\d+)/)
256
+ const behindMatch = branchLine.match(/behind (\d+)/)
257
+ const aheadCount = aheadMatch ? parseInt(aheadMatch[1], 10) : 0
258
+ const behindCount = behindMatch ? parseInt(behindMatch[1], 10) : 0
259
+
260
+ if (aheadCount > 0) {
261
+ logWarning(`Local branch ${currentBranch} is ahead of upstream by ${aheadCount} commit${aheadCount === 1 ? '' : 's'}.`)
262
+ }
263
+
264
+ if (behindCount > 0) {
265
+ logProcessing(`Synchronizing local branch ${currentBranch} with its upstream...`)
266
+ try {
267
+ await runCommand('git', ['pull', '--ff-only'], { cwd: rootDir })
268
+ logSuccess('Local branch fast-forwarded with upstream changes.')
269
+ } catch (error) {
270
+ throw new Error(
271
+ `Unable to fast-forward ${currentBranch} with upstream changes. Resolve conflicts manually, then rerun the deployment.\n${error.message}`
272
+ )
273
+ }
274
+ }
275
+
276
+ if (currentBranch !== targetBranch) {
277
+ if (hasPendingChanges) {
278
+ throw new Error(
279
+ `Local repository has uncommitted changes on ${currentBranch}. Commit or stash them before switching to ${targetBranch}.`
280
+ )
281
+ }
282
+
283
+ logProcessing(`Switching local repository from ${currentBranch} to ${targetBranch}...`)
284
+ await runCommand('git', ['checkout', targetBranch], { cwd: rootDir })
285
+ logSuccess(`Checked out ${targetBranch} locally.`)
286
+ }
287
+
288
+ const statusAfterCheckout = currentBranch === targetBranch ? initialStatus : await getGitStatus(rootDir)
289
+
290
+ if (statusAfterCheckout.length === 0) {
291
+ await ensureCommittedChangesPushed(targetBranch, rootDir)
292
+ logProcessing('Local repository is clean. Proceeding with deployment.')
293
+ return
294
+ }
295
+
296
+ if (!hasStagedChanges(statusAfterCheckout)) {
297
+ await ensureCommittedChangesPushed(targetBranch, rootDir)
298
+ logProcessing('No staged changes detected. Unstaged or untracked files will not affect deployment. Proceeding with deployment.')
299
+ return
300
+ }
301
+
302
+ logWarning(`Staged changes detected on ${targetBranch}. A commit is required before deployment.`)
303
+
304
+ const { commitMessage } = await runPrompt([
305
+ {
306
+ type: 'input',
307
+ name: 'commitMessage',
308
+ message: 'Enter a commit message for pending changes before deployment',
309
+ validate: (value) => (value && value.trim().length > 0 ? true : 'Commit message cannot be empty.')
310
+ }
311
+ ])
312
+
313
+ const message = commitMessage.trim()
314
+
315
+ logProcessing('Committing staged changes before deployment...')
316
+ await runCommand('git', ['commit', '-m', message], { cwd: rootDir })
317
+ await runCommand('git', ['push', 'origin', targetBranch], { cwd: rootDir })
318
+ logSuccess(`Committed and pushed changes to origin/${targetBranch}.`)
319
+
320
+ const finalStatus = await getGitStatus(rootDir)
321
+
322
+ if (finalStatus.length > 0) {
323
+ throw new Error('Local repository still has uncommitted changes after commit. Aborting deployment.')
324
+ }
325
+
326
+ await ensureCommittedChangesPushed(targetBranch, rootDir)
327
+ logProcessing('Local repository is clean after committing pending changes.')
328
+ }
329
+
330
+ async function ensureProjectReleaseScript(rootDir) {
331
+ const packageJsonPath = path.join(rootDir, 'package.json')
332
+
333
+ let raw
334
+ try {
335
+ raw = await fs.readFile(packageJsonPath, 'utf8')
336
+ } catch (error) {
337
+ if (error.code === 'ENOENT') {
338
+ return false
339
+ }
340
+
341
+ throw error
342
+ }
343
+
344
+ let packageJson
345
+ try {
346
+ packageJson = JSON.parse(raw)
347
+ } catch (error) {
348
+ logWarning('Unable to parse package.json; skipping release script injection.')
349
+ return false
350
+ }
351
+
352
+ const currentCommand = packageJson?.scripts?.[RELEASE_SCRIPT_NAME]
353
+
354
+ if (currentCommand && currentCommand.includes('@wyxos/zephyr')) {
355
+ return false
356
+ }
357
+
358
+ const { installReleaseScript } = await runPrompt([
359
+ {
360
+ type: 'confirm',
361
+ name: 'installReleaseScript',
362
+ message: 'Add "release" script to package.json that runs "npx @wyxos/zephyr@latest"?',
363
+ default: true
364
+ }
365
+ ])
366
+
367
+ if (!installReleaseScript) {
368
+ return false
369
+ }
370
+
371
+ if (!packageJson.scripts || typeof packageJson.scripts !== 'object') {
372
+ packageJson.scripts = {}
373
+ }
374
+
375
+ packageJson.scripts[RELEASE_SCRIPT_NAME] = RELEASE_SCRIPT_COMMAND
376
+
377
+ const updatedPayload = `${JSON.stringify(packageJson, null, 2)}\n`
378
+ await fs.writeFile(packageJsonPath, updatedPayload)
379
+ logSuccess('Added release script to package.json.')
380
+
381
+ let isGitRepo = false
382
+
383
+ try {
384
+ await runCommand('git', ['rev-parse', '--is-inside-work-tree'], { cwd: rootDir, silent: true })
385
+ isGitRepo = true
386
+ } catch (error) {
387
+ logWarning('Not a git repository; skipping commit for release script addition.')
388
+ }
389
+
390
+ if (isGitRepo) {
391
+ try {
392
+ await runCommand('git', ['add', 'package.json'], { cwd: rootDir, silent: true })
393
+ await runCommand('git', ['commit', '-m', 'chore: add zephyr release script'], { cwd: rootDir, silent: true })
394
+ logSuccess('Committed package.json release script addition.')
395
+ } catch (error) {
396
+ if (error.exitCode === 1) {
397
+ logWarning('Git commit skipped: nothing to commit or pre-commit hook prevented commit.')
398
+ } else {
399
+ throw error
400
+ }
401
+ }
402
+ }
403
+
404
+ return true
405
+ }
406
+
407
+ function getProjectConfigDir(rootDir) {
408
+ return path.join(rootDir, PROJECT_CONFIG_DIR)
409
+ }
410
+
411
+ function getPendingTasksPath(rootDir) {
412
+ return path.join(getProjectConfigDir(rootDir), PENDING_TASKS_FILE)
413
+ }
414
+
415
+ function getLockFilePath(rootDir) {
416
+ return path.join(getProjectConfigDir(rootDir), PROJECT_LOCK_FILE)
417
+ }
418
+
419
+ async function acquireRemoteLock(ssh, remoteCwd) {
420
+ const lockPath = `.zephyr/${PROJECT_LOCK_FILE}`
421
+ const escapedLockPath = lockPath.replace(/'/g, "'\\''")
422
+ const checkCommand = `mkdir -p .zephyr && if [ -f '${escapedLockPath}' ]; then cat '${escapedLockPath}'; else echo "LOCK_NOT_FOUND"; fi`
423
+
424
+ const checkResult = await ssh.execCommand(checkCommand, { cwd: remoteCwd })
425
+
426
+ if (checkResult.stdout && checkResult.stdout.trim() !== 'LOCK_NOT_FOUND' && checkResult.stdout.trim() !== '') {
427
+ let details = {}
428
+ try {
429
+ details = JSON.parse(checkResult.stdout.trim())
430
+ } catch (error) {
431
+ details = { raw: checkResult.stdout.trim() }
432
+ }
433
+
434
+ const startedBy = details.user ? `${details.user}@${details.hostname ?? 'unknown'}` : 'unknown user'
435
+ const startedAt = details.startedAt ? ` at ${details.startedAt}` : ''
436
+ throw new Error(
437
+ `Another deployment is currently in progress on the server (started by ${startedBy}${startedAt}). Remove ${remoteCwd}/${lockPath} if you are sure it is stale.`
438
+ )
439
+ }
440
+
441
+ const payload = {
442
+ user: os.userInfo().username,
443
+ pid: process.pid,
444
+ hostname: os.hostname(),
445
+ startedAt: new Date().toISOString()
446
+ }
447
+
448
+ const payloadJson = JSON.stringify(payload, null, 2)
449
+ const payloadBase64 = Buffer.from(payloadJson).toString('base64')
450
+ const createCommand = `mkdir -p .zephyr && echo '${payloadBase64}' | base64 --decode > '${escapedLockPath}'`
451
+
452
+ const createResult = await ssh.execCommand(createCommand, { cwd: remoteCwd })
453
+
454
+ if (createResult.code !== 0) {
455
+ throw new Error(`Failed to create lock file on server: ${createResult.stderr}`)
456
+ }
457
+
458
+ return lockPath
459
+ }
460
+
461
+ async function releaseRemoteLock(ssh, remoteCwd) {
462
+ const lockPath = `.zephyr/${PROJECT_LOCK_FILE}`
463
+ const escapedLockPath = lockPath.replace(/'/g, "'\\''")
464
+ const removeCommand = `rm -f '${escapedLockPath}'`
465
+
466
+ const result = await ssh.execCommand(removeCommand, { cwd: remoteCwd })
467
+ if (result.code !== 0 && result.code !== 1) {
468
+ logWarning(`Failed to remove lock file: ${result.stderr}`)
469
+ }
470
+ }
471
+
472
+ async function loadPendingTasksSnapshot(rootDir) {
473
+ const snapshotPath = getPendingTasksPath(rootDir)
474
+
475
+ try {
476
+ const raw = await fs.readFile(snapshotPath, 'utf8')
477
+ return JSON.parse(raw)
478
+ } catch (error) {
479
+ if (error.code === 'ENOENT') {
480
+ return null
481
+ }
482
+
483
+ throw error
484
+ }
485
+ }
486
+
487
+ async function savePendingTasksSnapshot(rootDir, snapshot) {
488
+ const configDir = getProjectConfigDir(rootDir)
489
+ await ensureDirectory(configDir)
490
+ const payload = `${JSON.stringify(snapshot, null, 2)}\n`
491
+ await fs.writeFile(getPendingTasksPath(rootDir), payload)
492
+ }
493
+
494
+ async function clearPendingTasksSnapshot(rootDir) {
495
+ try {
496
+ await fs.unlink(getPendingTasksPath(rootDir))
497
+ } catch (error) {
498
+ if (error.code !== 'ENOENT') {
499
+ throw error
500
+ }
501
+ }
502
+ }
503
+
504
+ async function ensureGitignoreEntry(rootDir) {
505
+ const gitignorePath = path.join(rootDir, '.gitignore')
506
+ const targetEntry = `${PROJECT_CONFIG_DIR}/`
507
+ let existingContent = ''
508
+
509
+ try {
510
+ existingContent = await fs.readFile(gitignorePath, 'utf8')
511
+ } catch (error) {
512
+ if (error.code !== 'ENOENT') {
513
+ throw error
514
+ }
515
+ }
516
+
517
+ const hasEntry = existingContent
518
+ .split(/\r?\n/)
519
+ .some((line) => line.trim() === targetEntry)
520
+
521
+ if (hasEntry) {
522
+ return
523
+ }
524
+
525
+ const updatedContent = existingContent
526
+ ? `${existingContent.replace(/\s*$/, '')}\n${targetEntry}\n`
527
+ : `${targetEntry}\n`
528
+
529
+ await fs.writeFile(gitignorePath, updatedContent)
530
+ logSuccess('Added .zephyr/ to .gitignore')
531
+
532
+ let isGitRepo = false
533
+ try {
534
+ await runCommand('git', ['rev-parse', '--is-inside-work-tree'], {
535
+ silent: true,
536
+ cwd: rootDir
537
+ })
538
+ isGitRepo = true
539
+ } catch (error) {
540
+ logWarning('Not a git repository; skipping commit for .gitignore update.')
541
+ }
542
+
543
+ if (!isGitRepo) {
544
+ return
545
+ }
546
+
547
+ try {
548
+ await runCommand('git', ['add', '.gitignore'], { cwd: rootDir })
549
+ await runCommand('git', ['commit', '-m', 'chore: ignore zephyr config'], { cwd: rootDir })
550
+ } catch (error) {
551
+ if (error.exitCode === 1) {
552
+ logWarning('Git commit skipped: nothing to commit or pre-commit hook prevented commit.')
553
+ } else {
554
+ throw error
555
+ }
556
+ }
557
+ }
558
+
559
+ async function ensureDirectory(dirPath) {
560
+ await fs.mkdir(dirPath, { recursive: true })
561
+ }
562
+
563
+ async function loadServers() {
564
+ try {
565
+ const raw = await fs.readFile(SERVERS_FILE, 'utf8')
566
+ const data = JSON.parse(raw)
567
+ return Array.isArray(data) ? data : []
568
+ } catch (error) {
569
+ if (error.code === 'ENOENT') {
570
+ return []
571
+ }
572
+
573
+ logWarning('Failed to read servers.json, starting with an empty list.')
574
+ return []
575
+ }
576
+ }
577
+
578
+ async function saveServers(servers) {
579
+ await ensureDirectory(GLOBAL_CONFIG_DIR)
580
+ const payload = JSON.stringify(servers, null, 2)
581
+ await fs.writeFile(SERVERS_FILE, `${payload}\n`)
582
+ }
583
+
584
+ function getProjectConfigPath(rootDir) {
585
+ return path.join(rootDir, PROJECT_CONFIG_DIR, PROJECT_CONFIG_FILE)
586
+ }
587
+
588
+ async function loadProjectConfig(rootDir) {
589
+ const configPath = getProjectConfigPath(rootDir)
590
+
591
+ try {
592
+ const raw = await fs.readFile(configPath, 'utf8')
593
+ const data = JSON.parse(raw)
594
+ return {
595
+ apps: Array.isArray(data?.apps) ? data.apps : [],
596
+ presets: Array.isArray(data?.presets) ? data.presets : []
597
+ }
598
+ } catch (error) {
599
+ if (error.code === 'ENOENT') {
600
+ return { apps: [], presets: [] }
601
+ }
602
+
603
+ logWarning('Failed to read .zephyr/config.json, starting with an empty list of apps.')
604
+ return { apps: [], presets: [] }
605
+ }
606
+ }
607
+
608
+ async function saveProjectConfig(rootDir, config) {
609
+ const configDir = path.join(rootDir, PROJECT_CONFIG_DIR)
610
+ await ensureDirectory(configDir)
611
+ const payload = JSON.stringify(
612
+ {
613
+ apps: config.apps ?? [],
614
+ presets: config.presets ?? []
615
+ },
616
+ null,
617
+ 2
618
+ )
619
+ await fs.writeFile(path.join(configDir, PROJECT_CONFIG_FILE), `${payload}\n`)
620
+ }
621
+
622
+ function defaultProjectPath(currentDir) {
623
+ return `~/webapps/${path.basename(currentDir)}`
624
+ }
625
+
626
+ async function listGitBranches(currentDir) {
627
+ try {
628
+ const output = await runCommandCapture(
629
+ 'git',
630
+ ['branch', '--format', '%(refname:short)'],
631
+ { cwd: currentDir }
632
+ )
633
+
634
+ const branches = output
635
+ .split(/\r?\n/)
636
+ .map((line) => line.trim())
637
+ .filter(Boolean)
638
+
639
+ return branches.length ? branches : ['master']
640
+ } catch (error) {
641
+ logWarning('Unable to read git branches; defaulting to master.')
642
+ return ['master']
643
+ }
644
+ }
645
+
646
+ async function listSshKeys() {
647
+ const sshDir = path.join(os.homedir(), '.ssh')
648
+
649
+ try {
650
+ const entries = await fs.readdir(sshDir, { withFileTypes: true })
651
+
652
+ const candidates = entries
653
+ .filter((entry) => entry.isFile())
654
+ .map((entry) => entry.name)
655
+ .filter((name) => {
656
+ if (!name) return false
657
+ if (name.startsWith('.')) return false
658
+ if (name.endsWith('.pub')) return false
659
+ if (name.startsWith('known_hosts')) return false
660
+ if (name === 'config') return false
661
+ return name.trim().length > 0
662
+ })
663
+
664
+ const keys = []
665
+
666
+ for (const name of candidates) {
667
+ const filePath = path.join(sshDir, name)
668
+ if (await isPrivateKeyFile(filePath)) {
669
+ keys.push(name)
670
+ }
671
+ }
672
+
673
+ return {
674
+ sshDir,
675
+ keys
676
+ }
677
+ } catch (error) {
678
+ if (error.code === 'ENOENT') {
679
+ return {
680
+ sshDir,
681
+ keys: []
682
+ }
683
+ }
684
+
685
+ throw error
686
+ }
687
+ }
688
+
689
+ async function isPrivateKeyFile(filePath) {
690
+ try {
691
+ const content = await fs.readFile(filePath, 'utf8')
692
+ return /-----BEGIN [A-Z ]*PRIVATE KEY-----/.test(content)
693
+ } catch (error) {
694
+ return false
695
+ }
696
+ }
697
+
698
+ async function promptSshDetails(currentDir, existing = {}) {
699
+ const { sshDir, keys: sshKeys } = await listSshKeys()
700
+ const defaultUser = existing.sshUser || os.userInfo().username
701
+ const fallbackKey = path.join(sshDir, 'id_rsa')
702
+ const preselectedKey = existing.sshKey || (sshKeys.length ? path.join(sshDir, sshKeys[0]) : fallbackKey)
703
+
704
+ const sshKeyPrompt = sshKeys.length
705
+ ? {
706
+ type: 'list',
707
+ name: 'sshKeySelection',
708
+ message: 'SSH key',
709
+ choices: [
710
+ ...sshKeys.map((key) => ({ name: key, value: path.join(sshDir, key) })),
711
+ new inquirer.Separator(),
712
+ { name: 'Enter custom SSH key path…', value: '__custom' }
713
+ ],
714
+ default: preselectedKey
715
+ }
716
+ : {
717
+ type: 'input',
718
+ name: 'sshKeySelection',
719
+ message: 'SSH key path',
720
+ default: preselectedKey
721
+ }
722
+
723
+ const answers = await runPrompt([
724
+ {
725
+ type: 'input',
726
+ name: 'sshUser',
727
+ message: 'SSH user',
728
+ default: defaultUser
729
+ },
730
+ sshKeyPrompt
731
+ ])
732
+
733
+ let sshKey = answers.sshKeySelection
734
+
735
+ if (sshKey === '__custom') {
736
+ const { customSshKey } = await runPrompt([
737
+ {
738
+ type: 'input',
739
+ name: 'customSshKey',
740
+ message: 'SSH key path',
741
+ default: preselectedKey
742
+ }
743
+ ])
744
+
745
+ sshKey = customSshKey.trim() || preselectedKey
746
+ }
747
+
748
+ return {
749
+ sshUser: answers.sshUser.trim() || defaultUser,
750
+ sshKey: sshKey.trim() || preselectedKey
751
+ }
752
+ }
753
+
754
+ async function ensureSshDetails(config, currentDir) {
755
+ if (config.sshUser && config.sshKey) {
756
+ return false
757
+ }
758
+
759
+ logProcessing('SSH details missing. Please provide them now.')
760
+ const details = await promptSshDetails(currentDir, config)
761
+ Object.assign(config, details)
762
+ return true
763
+ }
764
+
765
+ function expandHomePath(targetPath) {
766
+ if (!targetPath) {
767
+ return targetPath
768
+ }
769
+
770
+ if (targetPath.startsWith('~')) {
771
+ return path.join(os.homedir(), targetPath.slice(1))
772
+ }
773
+
774
+ return targetPath
775
+ }
776
+
777
+ async function resolveSshKeyPath(targetPath) {
778
+ const expanded = expandHomePath(targetPath)
779
+
780
+ try {
781
+ await fs.access(expanded)
782
+ } catch (error) {
783
+ throw new Error(`SSH key not accessible at ${expanded}`)
784
+ }
785
+
786
+ return expanded
787
+ }
788
+
789
+ function resolveRemotePath(projectPath, remoteHome) {
790
+ if (!projectPath) {
791
+ return projectPath
792
+ }
793
+
794
+ const sanitizedHome = remoteHome.replace(/\/+$/, '')
795
+
796
+ if (projectPath === '~') {
797
+ return sanitizedHome
798
+ }
799
+
800
+ if (projectPath.startsWith('~/')) {
801
+ const remainder = projectPath.slice(2)
802
+ return remainder ? `${sanitizedHome}/${remainder}` : sanitizedHome
803
+ }
804
+
805
+ if (projectPath.startsWith('/')) {
806
+ return projectPath
807
+ }
808
+
809
+ return `${sanitizedHome}/${projectPath}`
810
+ }
811
+
812
+ async function isLocalLaravelProject(rootDir) {
813
+ try {
814
+ const artisanPath = path.join(rootDir, 'artisan')
815
+ const composerPath = path.join(rootDir, 'composer.json')
816
+
817
+ await fs.access(artisanPath)
818
+ const composerContent = await fs.readFile(composerPath, 'utf8')
819
+ const composerJson = JSON.parse(composerContent)
820
+
821
+ return (
822
+ composerJson.require &&
823
+ typeof composerJson.require === 'object' &&
824
+ 'laravel/framework' in composerJson.require
825
+ )
826
+ } catch {
827
+ return false
828
+ }
829
+ }
830
+
831
+ async function runRemoteTasks(config, options = {}) {
832
+ const { snapshot = null, rootDir = process.cwd() } = options
833
+
834
+ await ensureLocalRepositoryState(config.branch, rootDir)
835
+
836
+ const isLaravel = await isLocalLaravelProject(rootDir)
837
+ if (isLaravel) {
838
+ logProcessing('Running Laravel tests locally...')
839
+ try {
840
+ await runCommand('php', ['artisan', 'test', '--compact'], { cwd: rootDir })
841
+ logSuccess('Local tests passed.')
842
+ } catch (error) {
843
+ throw new Error(`Local tests failed. Fix test failures before deploying. ${error.message}`)
844
+ }
845
+ }
846
+
847
+ const ssh = createSshClient()
848
+ const sshUser = config.sshUser || os.userInfo().username
849
+ const privateKeyPath = await resolveSshKeyPath(config.sshKey)
850
+ const privateKey = await fs.readFile(privateKeyPath, 'utf8')
851
+
852
+ logProcessing(`\nConnecting to ${config.serverIp} as ${sshUser}...`)
853
+
854
+ let lockAcquired = false
855
+
856
+ try {
857
+ await ssh.connect({
858
+ host: config.serverIp,
859
+ username: sshUser,
860
+ privateKey
861
+ })
862
+
863
+ const remoteHomeResult = await ssh.execCommand('printf "%s" "$HOME"')
864
+ const remoteHome = remoteHomeResult.stdout.trim() || `/home/${sshUser}`
865
+ const remoteCwd = resolveRemotePath(config.projectPath, remoteHome)
866
+
867
+ logProcessing(`Connection established. Acquiring deployment lock on server...`)
868
+ await acquireRemoteLock(ssh, remoteCwd)
869
+ lockAcquired = true
870
+ logProcessing(`Lock acquired. Running deployment commands in ${remoteCwd}...`)
871
+
872
+ // Robust environment bootstrap that works even when profile files don't export PATH
873
+ // for non-interactive shells. This handles:
874
+ // 1. Sourcing profile files (may not export PATH for non-interactive shells)
875
+ // 2. Loading nvm if available (common Node.js installation method)
876
+ // 3. Finding and adding common Node.js/npm installation paths
877
+ const profileBootstrap = [
878
+ // Source profile files (may set PATH, but often skip for non-interactive shells)
879
+ 'if [ -f "$HOME/.profile" ]; then . "$HOME/.profile"; fi',
880
+ 'if [ -f "$HOME/.bash_profile" ]; then . "$HOME/.bash_profile"; fi',
881
+ 'if [ -f "$HOME/.bashrc" ]; then . "$HOME/.bashrc"; fi',
882
+ 'if [ -f "$HOME/.zprofile" ]; then . "$HOME/.zprofile"; fi',
883
+ 'if [ -f "$HOME/.zshrc" ]; then . "$HOME/.zshrc"; fi',
884
+ // Load nvm if available (common Node.js installation method)
885
+ 'if [ -s "$HOME/.nvm/nvm.sh" ]; then . "$HOME/.nvm/nvm.sh"; fi',
886
+ 'if [ -s "$HOME/.config/nvm/nvm.sh" ]; then . "$HOME/.config/nvm/nvm.sh"; fi',
887
+ 'if [ -s "/usr/local/opt/nvm/nvm.sh" ]; then . "/usr/local/opt/nvm/nvm.sh"; fi',
888
+ // Try to find npm/node in common locations and add to PATH
889
+ 'if command -v npm >/dev/null 2>&1; then :',
890
+ '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"',
891
+ 'elif [ -d "/usr/local/lib/node_modules/npm/bin" ]; then export PATH="/usr/local/lib/node_modules/npm/bin:$PATH"',
892
+ 'elif [ -d "/opt/homebrew/bin" ] && [ -f "/opt/homebrew/bin/npm" ]; then export PATH="/opt/homebrew/bin:$PATH"',
893
+ 'elif [ -d "/usr/local/bin" ] && [ -f "/usr/local/bin/npm" ]; then export PATH="/usr/local/bin:$PATH"',
894
+ 'elif [ -d "$HOME/.local/bin" ] && [ -f "$HOME/.local/bin/npm" ]; then export PATH="$HOME/.local/bin:$PATH"',
895
+ 'fi'
896
+ ].join('; ')
897
+
898
+ const escapeForDoubleQuotes = (value) => value.replace(/(["\\$`])/g, '\\$1')
899
+
900
+ const executeRemote = async (label, command, options = {}) => {
901
+ const { cwd = remoteCwd, allowFailure = false, printStdout = true, bootstrapEnv = true } = options
902
+ logProcessing(`\n→ ${label}`)
903
+
904
+ let wrappedCommand = command
905
+ let execOptions = { cwd }
906
+
907
+ if (bootstrapEnv) {
908
+ const cwdForShell = escapeForDoubleQuotes(cwd)
909
+ wrappedCommand = `${profileBootstrap}; cd "${cwdForShell}" && ${command}`
910
+ execOptions = {}
911
+ }
912
+
913
+ const result = await ssh.execCommand(wrappedCommand, execOptions)
914
+
915
+ // Log all output to file
916
+ if (result.stdout && result.stdout.trim()) {
917
+ await writeToLogFile(rootDir, `[${label}] STDOUT:\n${result.stdout.trim()}`)
918
+ }
919
+
920
+ if (result.stderr && result.stderr.trim()) {
921
+ await writeToLogFile(rootDir, `[${label}] STDERR:\n${result.stderr.trim()}`)
922
+ }
923
+
924
+ // Only show errors in terminal
925
+ if (result.code !== 0) {
926
+ if (result.stdout && result.stdout.trim()) {
927
+ logError(`\n[${label}] Output:\n${result.stdout.trim()}`)
928
+ }
929
+
930
+ if (result.stderr && result.stderr.trim()) {
931
+ logError(`\n[${label}] Error:\n${result.stderr.trim()}`)
932
+ }
933
+ }
934
+
935
+ if (result.code !== 0 && !allowFailure) {
936
+ const stderr = result.stderr?.trim() ?? ''
937
+ if (/command not found/.test(stderr) || /is not recognized/.test(stderr)) {
938
+ throw new Error(
939
+ `Command failed: ${command}. Ensure the remote environment loads required tools for non-interactive shells (e.g. export PATH in profile scripts).`
940
+ )
941
+ }
942
+
943
+ throw new Error(`Command failed: ${command}`)
944
+ }
945
+
946
+ // Show success confirmation with command
947
+ if (result.code === 0) {
948
+ logSuccess(`✓ ${command}`)
949
+ }
950
+
951
+ return result
952
+ }
953
+
954
+ const laravelCheck = await ssh.execCommand(
955
+ 'if [ -f artisan ] && [ -f composer.json ] && grep -q "laravel/framework" composer.json; then echo "yes"; else echo "no"; fi',
956
+ { cwd: remoteCwd }
957
+ )
958
+ const isLaravel = laravelCheck.stdout.trim() === 'yes'
959
+
960
+ if (isLaravel) {
961
+ logSuccess('Laravel project detected.')
962
+ } else {
963
+ logWarning('Laravel project not detected; skipping Laravel-specific maintenance tasks.')
964
+ }
965
+
966
+ let changedFiles = []
967
+
968
+ if (snapshot && snapshot.changedFiles) {
969
+ changedFiles = snapshot.changedFiles
970
+ logProcessing('Resuming deployment with saved task snapshot.')
971
+ } else if (isLaravel) {
972
+ await executeRemote(`Fetch latest changes for ${config.branch}`, `git fetch origin ${config.branch}`)
973
+
974
+ const diffResult = await executeRemote(
975
+ 'Inspect pending changes',
976
+ `git diff --name-only HEAD..origin/${config.branch}`,
977
+ { printStdout: false }
978
+ )
979
+
980
+ changedFiles = diffResult.stdout
981
+ .split(/\r?\n/)
982
+ .map((line) => line.trim())
983
+ .filter(Boolean)
984
+
985
+ if (changedFiles.length > 0) {
986
+ const preview = changedFiles
987
+ .slice(0, 20)
988
+ .map((file) => ` - ${file}`)
989
+ .join('\n')
990
+
991
+ logProcessing(
992
+ `Detected ${changedFiles.length} changed file(s):\n${preview}${changedFiles.length > 20 ? '\n - ...' : ''
993
+ }`
994
+ )
995
+ } else {
996
+ logProcessing('No upstream file changes detected.')
997
+ }
998
+ }
999
+
1000
+ const shouldRunComposer =
1001
+ isLaravel &&
1002
+ changedFiles.some(
1003
+ (file) =>
1004
+ file === 'composer.json' ||
1005
+ file === 'composer.lock' ||
1006
+ file.endsWith('/composer.json') ||
1007
+ file.endsWith('/composer.lock')
1008
+ )
1009
+
1010
+ const shouldRunMigrations =
1011
+ isLaravel &&
1012
+ changedFiles.some(
1013
+ (file) => file.startsWith('database/migrations/') && file.endsWith('.php')
1014
+ )
1015
+
1016
+ const hasPhpChanges = isLaravel && changedFiles.some((file) => file.endsWith('.php'))
1017
+
1018
+ const shouldRunNpmInstall =
1019
+ isLaravel &&
1020
+ changedFiles.some(
1021
+ (file) =>
1022
+ file === 'package.json' ||
1023
+ file === 'package-lock.json' ||
1024
+ file.endsWith('/package.json') ||
1025
+ file.endsWith('/package-lock.json')
1026
+ )
1027
+
1028
+ const hasFrontendChanges =
1029
+ isLaravel &&
1030
+ changedFiles.some((file) =>
1031
+ ['.vue', '.css', '.scss', '.js', '.ts', '.tsx', '.less'].some((ext) =>
1032
+ file.endsWith(ext)
1033
+ )
1034
+ )
1035
+
1036
+ const shouldRunBuild = isLaravel && (hasFrontendChanges || shouldRunNpmInstall)
1037
+ const shouldClearCaches = hasPhpChanges
1038
+ const shouldRestartQueues = hasPhpChanges
1039
+
1040
+ let horizonConfigured = false
1041
+ if (shouldRestartQueues) {
1042
+ const horizonCheck = await ssh.execCommand(
1043
+ 'if [ -f config/horizon.php ]; then echo "yes"; else echo "no"; fi',
1044
+ { cwd: remoteCwd }
1045
+ )
1046
+ horizonConfigured = horizonCheck.stdout.trim() === 'yes'
1047
+ }
1048
+
1049
+ const steps = [
1050
+ {
1051
+ label: `Pull latest changes for ${config.branch}`,
1052
+ command: `git pull origin ${config.branch}`
1053
+ }
1054
+ ]
1055
+
1056
+ if (shouldRunComposer) {
1057
+ steps.push({
1058
+ label: 'Update Composer dependencies',
1059
+ command: 'composer update --no-dev --no-interaction --prefer-dist'
1060
+ })
1061
+ }
1062
+
1063
+ if (shouldRunMigrations) {
1064
+ steps.push({
1065
+ label: 'Run database migrations',
1066
+ command: 'php artisan migrate --force'
1067
+ })
1068
+ }
1069
+
1070
+ if (shouldRunNpmInstall) {
1071
+ steps.push({
1072
+ label: 'Install Node dependencies',
1073
+ command: 'npm install'
1074
+ })
1075
+ }
1076
+
1077
+ if (shouldRunBuild) {
1078
+ steps.push({
1079
+ label: 'Compile frontend assets',
1080
+ command: 'npm run build'
1081
+ })
1082
+ }
1083
+
1084
+ if (shouldClearCaches) {
1085
+ steps.push({
1086
+ label: 'Clear Laravel caches',
1087
+ command: 'php artisan cache:clear && php artisan config:clear && php artisan view:clear'
1088
+ })
1089
+ }
1090
+
1091
+ if (shouldRestartQueues) {
1092
+ steps.push({
1093
+ label: horizonConfigured ? 'Restart Horizon workers' : 'Restart queue workers',
1094
+ command: horizonConfigured ? 'php artisan horizon:terminate' : 'php artisan queue:restart'
1095
+ })
1096
+ }
1097
+
1098
+ const usefulSteps = steps.length > 1
1099
+
1100
+ let pendingSnapshot
1101
+
1102
+ if (usefulSteps) {
1103
+ pendingSnapshot = snapshot ?? {
1104
+ serverName: config.serverName,
1105
+ branch: config.branch,
1106
+ projectPath: config.projectPath,
1107
+ sshUser: config.sshUser,
1108
+ createdAt: new Date().toISOString(),
1109
+ changedFiles,
1110
+ taskLabels: steps.map((step) => step.label)
1111
+ }
1112
+
1113
+ await savePendingTasksSnapshot(rootDir, pendingSnapshot)
1114
+
1115
+ const payload = Buffer.from(JSON.stringify(pendingSnapshot)).toString('base64')
1116
+ await executeRemote(
1117
+ 'Record pending deployment tasks',
1118
+ `mkdir -p .zephyr && echo '${payload}' | base64 --decode > .zephyr/${PENDING_TASKS_FILE}`,
1119
+ { printStdout: false }
1120
+ )
1121
+ }
1122
+
1123
+ if (steps.length === 1) {
1124
+ logProcessing('No additional maintenance tasks scheduled beyond git pull.')
1125
+ } else {
1126
+ const extraTasks = steps
1127
+ .slice(1)
1128
+ .map((step) => step.label)
1129
+ .join(', ')
1130
+
1131
+ logProcessing(`Additional tasks scheduled: ${extraTasks}`)
1132
+ }
1133
+
1134
+ let completed = false
1135
+
1136
+ try {
1137
+ for (const step of steps) {
1138
+ await executeRemote(step.label, step.command)
1139
+ }
1140
+
1141
+ completed = true
1142
+ } finally {
1143
+ if (usefulSteps && completed) {
1144
+ await executeRemote(
1145
+ 'Clear pending deployment snapshot',
1146
+ `rm -f .zephyr/${PENDING_TASKS_FILE}`,
1147
+ { printStdout: false, allowFailure: true }
1148
+ )
1149
+ await clearPendingTasksSnapshot(rootDir)
1150
+ }
1151
+ }
1152
+
1153
+ logSuccess('\nDeployment commands completed successfully.')
1154
+
1155
+ const logPath = await getLogFilePath(rootDir)
1156
+ logSuccess(`\nAll task output has been logged to: ${logPath}`)
1157
+ } catch (error) {
1158
+ const logPath = logFilePath || await getLogFilePath(rootDir).catch(() => null)
1159
+ if (logPath) {
1160
+ logError(`\nTask output has been logged to: ${logPath}`)
1161
+ }
1162
+ throw new Error(`Deployment failed: ${error.message}`)
1163
+ } finally {
1164
+ if (lockAcquired && ssh) {
1165
+ try {
1166
+ const remoteHomeResult = await ssh.execCommand('printf "%s" "$HOME"')
1167
+ const remoteHome = remoteHomeResult.stdout.trim() || `/home/${sshUser}`
1168
+ const remoteCwd = resolveRemotePath(config.projectPath, remoteHome)
1169
+ await releaseRemoteLock(ssh, remoteCwd)
1170
+ } catch (error) {
1171
+ logWarning(`Failed to release lock: ${error.message}`)
1172
+ }
1173
+ }
1174
+ await closeLogFile()
1175
+ if (ssh) {
1176
+ ssh.dispose()
1177
+ }
1178
+ }
1179
+ }
1180
+
1181
+ async function promptServerDetails(existingServers = []) {
1182
+ const defaults = {
1183
+ serverName: existingServers.length === 0 ? 'home' : `server-${existingServers.length + 1}`,
1184
+ serverIp: '1.1.1.1'
1185
+ }
1186
+
1187
+ const answers = await runPrompt([
1188
+ {
1189
+ type: 'input',
1190
+ name: 'serverName',
1191
+ message: 'Server name',
1192
+ default: defaults.serverName
1193
+ },
1194
+ {
1195
+ type: 'input',
1196
+ name: 'serverIp',
1197
+ message: 'Server IP address',
1198
+ default: defaults.serverIp
1199
+ }
1200
+ ])
1201
+
1202
+ return {
1203
+ serverName: answers.serverName.trim() || defaults.serverName,
1204
+ serverIp: answers.serverIp.trim() || defaults.serverIp
1205
+ }
1206
+ }
1207
+
1208
+ async function selectServer(servers) {
1209
+ if (servers.length === 0) {
1210
+ logProcessing("No servers configured. Let's create one.")
1211
+ const server = await promptServerDetails()
1212
+ servers.push(server)
1213
+ await saveServers(servers)
1214
+ logSuccess('Saved server configuration to ~/.config/zephyr/servers.json')
1215
+ return server
1216
+ }
1217
+
1218
+ const choices = servers.map((server, index) => ({
1219
+ name: `${server.serverName} (${server.serverIp})`,
1220
+ value: index
1221
+ }))
1222
+
1223
+ choices.push(new inquirer.Separator(), {
1224
+ name: '➕ Register a new server',
1225
+ value: 'create'
1226
+ })
1227
+
1228
+ const { selection } = await runPrompt([
1229
+ {
1230
+ type: 'list',
1231
+ name: 'selection',
1232
+ message: 'Select server or register new',
1233
+ choices,
1234
+ default: 0
1235
+ }
1236
+ ])
1237
+
1238
+ if (selection === 'create') {
1239
+ const server = await promptServerDetails(servers)
1240
+ servers.push(server)
1241
+ await saveServers(servers)
1242
+ logSuccess('Appended server configuration to ~/.config/zephyr/servers.json')
1243
+ return server
1244
+ }
1245
+
1246
+ return servers[selection]
1247
+ }
1248
+
1249
+ async function promptAppDetails(currentDir, existing = {}) {
1250
+ const branches = await listGitBranches(currentDir)
1251
+ const defaultBranch = existing.branch || (branches.includes('master') ? 'master' : branches[0])
1252
+ const defaults = {
1253
+ projectPath: existing.projectPath || defaultProjectPath(currentDir),
1254
+ branch: defaultBranch
1255
+ }
1256
+
1257
+ const answers = await runPrompt([
1258
+ {
1259
+ type: 'input',
1260
+ name: 'projectPath',
1261
+ message: 'Remote project path',
1262
+ default: defaults.projectPath
1263
+ },
1264
+ {
1265
+ type: 'list',
1266
+ name: 'branchSelection',
1267
+ message: 'Branch to deploy',
1268
+ choices: [
1269
+ ...branches.map((branch) => ({ name: branch, value: branch })),
1270
+ new inquirer.Separator(),
1271
+ { name: 'Enter custom branch…', value: '__custom' }
1272
+ ],
1273
+ default: defaults.branch
1274
+ }
1275
+ ])
1276
+
1277
+ let branch = answers.branchSelection
1278
+
1279
+ if (branch === '__custom') {
1280
+ const { customBranch } = await runPrompt([
1281
+ {
1282
+ type: 'input',
1283
+ name: 'customBranch',
1284
+ message: 'Custom branch name',
1285
+ default: defaults.branch
1286
+ }
1287
+ ])
1288
+
1289
+ branch = customBranch.trim() || defaults.branch
1290
+ }
1291
+
1292
+ const sshDetails = await promptSshDetails(currentDir, existing)
1293
+
1294
+ return {
1295
+ projectPath: answers.projectPath.trim() || defaults.projectPath,
1296
+ branch,
1297
+ ...sshDetails
1298
+ }
1299
+ }
1300
+
1301
+ async function selectApp(projectConfig, server, currentDir) {
1302
+ const apps = projectConfig.apps ?? []
1303
+ const matches = apps
1304
+ .map((app, index) => ({ app, index }))
1305
+ .filter(({ app }) => app.serverName === server.serverName)
1306
+
1307
+ if (matches.length === 0) {
1308
+ if (apps.length > 0) {
1309
+ const availableServers = [...new Set(apps.map((app) => app.serverName))]
1310
+ logWarning(
1311
+ `No applications configured for server "${server.serverName}". Available servers: ${availableServers.join(', ')}`
1312
+ )
1313
+ }
1314
+ logProcessing(`No applications configured for ${server.serverName}. Let's create one.`)
1315
+ const appDetails = await promptAppDetails(currentDir)
1316
+ const appConfig = {
1317
+ serverName: server.serverName,
1318
+ ...appDetails
1319
+ }
1320
+ projectConfig.apps.push(appConfig)
1321
+ await saveProjectConfig(currentDir, projectConfig)
1322
+ logSuccess('Saved deployment configuration to .zephyr/config.json')
1323
+ return appConfig
1324
+ }
1325
+
1326
+ const choices = matches.map(({ app, index }, matchIndex) => ({
1327
+ name: `${app.projectPath} (${app.branch})`,
1328
+ value: matchIndex
1329
+ }))
1330
+
1331
+ choices.push(new inquirer.Separator(), {
1332
+ name: '➕ Configure new application for this server',
1333
+ value: 'create'
1334
+ })
1335
+
1336
+ const { selection } = await runPrompt([
1337
+ {
1338
+ type: 'list',
1339
+ name: 'selection',
1340
+ message: `Select application for ${server.serverName}`,
1341
+ choices,
1342
+ default: 0
1343
+ }
1344
+ ])
1345
+
1346
+ if (selection === 'create') {
1347
+ const appDetails = await promptAppDetails(currentDir)
1348
+ const appConfig = {
1349
+ serverName: server.serverName,
1350
+ ...appDetails
1351
+ }
1352
+ projectConfig.apps.push(appConfig)
1353
+ await saveProjectConfig(currentDir, projectConfig)
1354
+ logSuccess('Appended deployment configuration to .zephyr/config.json')
1355
+ return appConfig
1356
+ }
1357
+
1358
+ const chosen = matches[selection].app
1359
+ return chosen
1360
+ }
1361
+
1362
+ async function promptPresetName() {
1363
+ const { presetName } = await runPrompt([
1364
+ {
1365
+ type: 'input',
1366
+ name: 'presetName',
1367
+ message: 'Enter a name for this preset',
1368
+ validate: (value) => (value && value.trim().length > 0 ? true : 'Preset name cannot be empty.')
1369
+ }
1370
+ ])
1371
+
1372
+ return presetName.trim()
1373
+ }
1374
+
1375
+ async function selectPreset(projectConfig) {
1376
+ const presets = projectConfig.presets ?? []
1377
+
1378
+ if (presets.length === 0) {
1379
+ return null
1380
+ }
1381
+
1382
+ const choices = presets.map((preset, index) => ({
1383
+ name: `${preset.name} (${preset.serverName} → ${preset.projectPath} [${preset.branch}])`,
1384
+ value: index
1385
+ }))
1386
+
1387
+ choices.push(new inquirer.Separator(), {
1388
+ name: '➕ Create new preset',
1389
+ value: 'create'
1390
+ })
1391
+
1392
+ const { selection } = await runPrompt([
1393
+ {
1394
+ type: 'list',
1395
+ name: 'selection',
1396
+ message: 'Select preset or create new',
1397
+ choices,
1398
+ default: 0
1399
+ }
1400
+ ])
1401
+
1402
+ if (selection === 'create') {
1403
+ return 'create' // Return a special marker instead of null
1404
+ }
1405
+
1406
+ return presets[selection]
1407
+ }
1408
+
1409
+ async function main() {
1410
+ const rootDir = process.cwd()
1411
+
1412
+ await ensureGitignoreEntry(rootDir)
1413
+ await ensureProjectReleaseScript(rootDir)
1414
+
1415
+ const projectConfig = await loadProjectConfig(rootDir)
1416
+ let server = null
1417
+ let appConfig = null
1418
+ let isCreatingNewPreset = false
1419
+
1420
+ const preset = await selectPreset(projectConfig)
1421
+
1422
+ if (preset === 'create') {
1423
+ // User explicitly chose to create a new preset
1424
+ isCreatingNewPreset = true
1425
+ const servers = await loadServers()
1426
+ server = await selectServer(servers)
1427
+ appConfig = await selectApp(projectConfig, server, rootDir)
1428
+ } else if (preset) {
1429
+ // User selected an existing preset
1430
+ const servers = await loadServers()
1431
+ server = servers.find((s) => s.serverName === preset.serverName)
1432
+
1433
+ if (!server) {
1434
+ logWarning(`Preset references server "${preset.serverName}" which no longer exists. Creating new configuration.`)
1435
+ const servers = await loadServers()
1436
+ server = await selectServer(servers)
1437
+ appConfig = await selectApp(projectConfig, server, rootDir)
1438
+ } else {
1439
+ appConfig = {
1440
+ serverName: preset.serverName,
1441
+ projectPath: preset.projectPath,
1442
+ branch: preset.branch,
1443
+ sshUser: preset.sshUser,
1444
+ sshKey: preset.sshKey
1445
+ }
1446
+ }
1447
+ } else {
1448
+ // No presets exist, go through normal flow
1449
+ const servers = await loadServers()
1450
+ server = await selectServer(servers)
1451
+ appConfig = await selectApp(projectConfig, server, rootDir)
1452
+ }
1453
+
1454
+ const updated = await ensureSshDetails(appConfig, rootDir)
1455
+
1456
+ if (updated) {
1457
+ await saveProjectConfig(rootDir, projectConfig)
1458
+ logSuccess('Updated .zephyr/config.json with SSH details.')
1459
+ }
1460
+
1461
+ const deploymentConfig = {
1462
+ serverName: server.serverName,
1463
+ serverIp: server.serverIp,
1464
+ projectPath: appConfig.projectPath,
1465
+ branch: appConfig.branch,
1466
+ sshUser: appConfig.sshUser,
1467
+ sshKey: appConfig.sshKey
1468
+ }
1469
+
1470
+ logProcessing('\nSelected deployment target:')
1471
+ console.log(JSON.stringify(deploymentConfig, null, 2))
1472
+
1473
+ if (isCreatingNewPreset || !preset) {
1474
+ const { saveAsPreset } = await runPrompt([
1475
+ {
1476
+ type: 'confirm',
1477
+ name: 'saveAsPreset',
1478
+ message: 'Save this configuration as a preset?',
1479
+ default: isCreatingNewPreset // Default to true if user explicitly chose to create preset
1480
+ }
1481
+ ])
1482
+
1483
+ if (saveAsPreset) {
1484
+ const presetName = await promptPresetName()
1485
+ const presets = projectConfig.presets ?? []
1486
+ presets.push({
1487
+ name: presetName,
1488
+ serverName: deploymentConfig.serverName,
1489
+ projectPath: deploymentConfig.projectPath,
1490
+ branch: deploymentConfig.branch,
1491
+ sshUser: deploymentConfig.sshUser,
1492
+ sshKey: deploymentConfig.sshKey
1493
+ })
1494
+ projectConfig.presets = presets
1495
+ await saveProjectConfig(rootDir, projectConfig)
1496
+ logSuccess(`Saved preset "${presetName}" to .zephyr/config.json`)
1497
+ }
1498
+ }
1499
+
1500
+ const existingSnapshot = await loadPendingTasksSnapshot(rootDir)
1501
+ let snapshotToUse = null
1502
+
1503
+ if (existingSnapshot) {
1504
+ const matchesSelection =
1505
+ existingSnapshot.serverName === deploymentConfig.serverName &&
1506
+ existingSnapshot.branch === deploymentConfig.branch
1507
+
1508
+ const messageLines = [
1509
+ 'Pending deployment tasks were detected from a previous run.',
1510
+ `Server: ${existingSnapshot.serverName}`,
1511
+ `Branch: ${existingSnapshot.branch}`
1512
+ ]
1513
+
1514
+ if (existingSnapshot.taskLabels && existingSnapshot.taskLabels.length > 0) {
1515
+ messageLines.push(`Tasks: ${existingSnapshot.taskLabels.join(', ')}`)
1516
+ }
1517
+
1518
+ const { resumePendingTasks } = await runPrompt([
1519
+ {
1520
+ type: 'confirm',
1521
+ name: 'resumePendingTasks',
1522
+ message: `${messageLines.join(' | ')}. Resume using this plan?`,
1523
+ default: matchesSelection
1524
+ }
1525
+ ])
1526
+
1527
+ if (resumePendingTasks) {
1528
+ snapshotToUse = existingSnapshot
1529
+ logProcessing('Resuming deployment using saved task snapshot...')
1530
+ } else {
1531
+ await clearPendingTasksSnapshot(rootDir)
1532
+ logWarning('Discarded pending deployment snapshot.')
1533
+ }
1534
+ }
1535
+
1536
+ await runRemoteTasks(deploymentConfig, { rootDir, snapshot: snapshotToUse })
1537
+ }
1538
+
1539
+ export {
1540
+ ensureGitignoreEntry,
1541
+ ensureProjectReleaseScript,
1542
+ listSshKeys,
1543
+ resolveRemotePath,
1544
+ isPrivateKeyFile,
1545
+ runRemoteTasks,
1546
+ promptServerDetails,
1547
+ selectServer,
1548
+ promptAppDetails,
1549
+ selectApp,
1550
+ promptSshDetails,
1551
+ ensureSshDetails,
1552
+ ensureLocalRepositoryState,
1553
+ loadServers,
1554
+ loadProjectConfig,
1555
+ saveProjectConfig,
1556
+ main
1557
+ }