@o/cli 0.16.19 → 0.16.20

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.
@@ -0,0 +1,1420 @@
1
+ /**
2
+ * Onboard command - interactive setup for Takeout starter kit
3
+ */
4
+
5
+ import { execSync } from 'node:child_process'
6
+ import { randomBytes } from 'node:crypto'
7
+ import {
8
+ existsSync,
9
+ mkdirSync,
10
+ readFileSync,
11
+ readdirSync,
12
+ unlinkSync,
13
+ writeFileSync,
14
+ } from 'node:fs'
15
+ import { homedir } from 'node:os'
16
+ import { resolve } from 'node:path'
17
+
18
+ import { defineCommand } from 'citty'
19
+ import pc from 'picocolors'
20
+
21
+ import {
22
+ copyEnvFile,
23
+ createEnvLocal,
24
+ envFileExists,
25
+ updateEnvVariable,
26
+ } from '../utils/env'
27
+ import { setupProductionEnv } from '../utils/env-setup'
28
+ import {
29
+ ejectFromMonorepo,
30
+ markOnboarded,
31
+ updateAppConfig,
32
+ updatePackageJson,
33
+ updatePackageJsonEnv,
34
+ } from '../utils/files'
35
+ import { checkAllPorts, getConflictingPorts } from '../utils/ports'
36
+ import { checkAllPrerequisites, hasRequiredPrerequisites } from '../utils/prerequisites'
37
+ import {
38
+ confirmContinue,
39
+ displayOutro,
40
+ displayPortConflicts,
41
+ displayPrerequisites,
42
+ displayWelcome,
43
+ promptText,
44
+ promptSelect,
45
+ promptStartStep,
46
+ showError,
47
+ showInfo,
48
+ showSpinner,
49
+ showStep,
50
+ showSuccess,
51
+ showWarning,
52
+ } from '../utils/prompts'
53
+
54
+ export const onboardCommand = defineCommand({
55
+ meta: {
56
+ name: 'onboard',
57
+ description: 'Interactive onboarding for Takeout starter kit',
58
+ },
59
+ args: {
60
+ skip: {
61
+ type: 'boolean',
62
+ description: 'Skip onboarding entirely',
63
+ default: false,
64
+ },
65
+ defaults: {
66
+ type: 'boolean',
67
+ description: 'Run with defaults (non-interactive)',
68
+ default: false,
69
+ },
70
+ },
71
+ async run({ args }) {
72
+ const cwd = process.cwd()
73
+ const packagesDir = resolve(cwd, 'packages')
74
+ const hasLocalPackages =
75
+ existsSync(packagesDir) &&
76
+ readdirSync(packagesDir, { withFileTypes: true }).some(
77
+ (entry) =>
78
+ entry.isDirectory() &&
79
+ existsSync(resolve(packagesDir, entry.name, 'package.json'))
80
+ )
81
+
82
+ if (args.skip) {
83
+ showInfo('Skipping onboarding (--skip flag)')
84
+ return
85
+ }
86
+
87
+ // non-interactive defaults mode
88
+ if (args.defaults) {
89
+ showInfo('Running onboarding with defaults (--defaults flag)')
90
+ console.info()
91
+
92
+ // setup environment
93
+ const hasEnv = envFileExists(cwd, '.env')
94
+ if (!hasEnv) {
95
+ const copyResult = copyEnvFile(cwd, '.env.development', '.env')
96
+ if (copyResult.success) {
97
+ showSuccess('Created .env from .env.development')
98
+ } else {
99
+ showError(`Failed to create .env: ${copyResult.error}`)
100
+ return
101
+ }
102
+ createEnvLocal(cwd)
103
+ showSuccess('Created .env.local for personal overrides')
104
+ } else {
105
+ showInfo('.env already exists, skipping')
106
+ }
107
+
108
+ markOnboarded(cwd)
109
+ showSuccess('Onboarding complete with defaults')
110
+ console.info()
111
+ showInfo('Next steps:')
112
+ console.info(' bun backend # start docker services')
113
+ console.info(' bun dev # start web dev server')
114
+ return
115
+ }
116
+
117
+ // Phase 0: Check for saved state
118
+ displayWelcome()
119
+
120
+ const savedState = loadOnboardState(cwd)
121
+ let startStep:
122
+ | 'full'
123
+ | 'prerequisites'
124
+ | 'identity'
125
+ | 'ports'
126
+ | 'eject'
127
+ | 'ci-runners'
128
+ | 'production'
129
+ | 'cancel'
130
+
131
+ if (savedState) {
132
+ console.info()
133
+ showInfo(`Found incomplete setup from previous session (${savedState.step})`)
134
+ const shouldResume = await confirmContinue('Resume from where you left off?', true)
135
+
136
+ if (shouldResume) {
137
+ startStep = savedState.step
138
+ } else {
139
+ clearOnboardState(cwd)
140
+ startStep = await promptStartStep(hasLocalPackages)
141
+ }
142
+ } else {
143
+ startStep = await promptStartStep(hasLocalPackages)
144
+ }
145
+
146
+ if (startStep === 'cancel') {
147
+ displayOutro('Setup cancelled')
148
+ return
149
+ }
150
+
151
+ // Direct eject - skip to eject step
152
+ if (startStep === 'eject') {
153
+ showStep('Monorepo Ejection')
154
+ console.info()
155
+
156
+ console.info(
157
+ pc.gray(
158
+ "We've included a variety of packages we found useful building apps with this stack:"
159
+ )
160
+ )
161
+ console.info(pc.gray(' • @o/cli - CLI tools and onboarding'))
162
+ console.info(pc.gray(' • @o/helpers - Utility functions'))
163
+ console.info(pc.gray(' • @o/hooks - React hooks'))
164
+ console.info(pc.gray(' • @o/database - Database utilities'))
165
+ console.info(pc.gray(' • @o/scripts - Build and dev scripts'))
166
+ console.info(pc.gray(' • @o/better-auth-utils - Auth helpers'))
167
+ console.info()
168
+
169
+ const shouldEject = await confirmContinue(
170
+ 'Eject from monorepo setup? (removes ./packages, uses published versions)',
171
+ true
172
+ )
173
+
174
+ if (shouldEject) {
175
+ // first run a dry-run to show what will happen
176
+ const dryResult = await ejectFromMonorepo(cwd, { dryRun: true })
177
+
178
+ if (!dryResult.success) {
179
+ showError(`Cannot eject: ${dryResult.error}`)
180
+ clearOnboardState(cwd)
181
+ return
182
+ }
183
+
184
+ console.info()
185
+ showInfo(`Found ${dryResult.packages?.length} packages to convert:`)
186
+ for (const pkg of dryResult.packages || []) {
187
+ console.info(pc.gray(` • ${pkg.name}@${pkg.version}`))
188
+ }
189
+ if (dryResult.warnings?.length) {
190
+ for (const warn of dryResult.warnings) {
191
+ showWarning(warn)
192
+ }
193
+ }
194
+ console.info()
195
+
196
+ const confirmEject = await confirmContinue('Proceed with ejection?', true)
197
+ if (!confirmEject) {
198
+ showInfo('Eject cancelled')
199
+ clearOnboardState(cwd)
200
+ displayOutro('Done!')
201
+ return
202
+ }
203
+
204
+ const spinner = showSpinner('Ejecting from monorepo...')
205
+
206
+ const result = await ejectFromMonorepo(cwd)
207
+
208
+ if (result.success) {
209
+ spinner.stop('Ejected from monorepo')
210
+ showSuccess('✓ Removed ./packages directory')
211
+ showSuccess('✓ Updated package.json to use published versions')
212
+ showSuccess('✓ Installed published packages')
213
+
214
+ try {
215
+ execSync('git add -A && git commit -m "ejected from monorepo"', {
216
+ cwd,
217
+ stdio: 'ignore',
218
+ })
219
+ showSuccess('✓ Committed eject changes')
220
+ } catch {
221
+ showWarning('Git commit skipped (not a git repo or no changes)')
222
+ }
223
+
224
+ console.info()
225
+ showInfo('You can now upgrade packages with: bun up takeout')
226
+ } else {
227
+ spinner.stop('Ejection failed')
228
+ showError(`Failed to eject: ${result.error}`)
229
+ if (result.error?.includes('install failed')) {
230
+ showInfo('You may be able to fix this by running "bun install" manually')
231
+ showInfo('Or restore the repo from git with "git checkout ."')
232
+ }
233
+ }
234
+ } else {
235
+ showInfo('Eject cancelled')
236
+ }
237
+
238
+ clearOnboardState(cwd)
239
+ displayOutro('Done!')
240
+ return
241
+ }
242
+
243
+ // Phase 1: Prerequisites
244
+ if (startStep === 'prerequisites' || startStep === 'full') {
245
+ saveOnboardState(cwd, { step: 'prerequisites', timestamp: Date.now() })
246
+ showStep('Checking prerequisites...')
247
+ console.info()
248
+
249
+ const checks = checkAllPrerequisites()
250
+ displayPrerequisites(checks)
251
+
252
+ const hasRequired = hasRequiredPrerequisites(checks)
253
+
254
+ if (!hasRequired) {
255
+ showWarning(
256
+ 'Some required prerequisites are missing. You can continue, but setup may fail.'
257
+ )
258
+ const shouldContinue = await confirmContinue('Continue anyway?', false)
259
+ if (!shouldContinue) {
260
+ displayOutro('Setup cancelled. Install prerequisites and try again.')
261
+ return
262
+ }
263
+ }
264
+
265
+ console.info()
266
+ }
267
+
268
+ // Phase 2: Project Identity
269
+ if (
270
+ startStep === 'prerequisites' ||
271
+ startStep === 'identity' ||
272
+ startStep === 'full'
273
+ ) {
274
+ saveOnboardState(cwd, { step: 'identity', timestamp: Date.now() })
275
+ showStep('Configuring project identity...')
276
+ console.info()
277
+
278
+ const shouldCustomize = await confirmContinue(
279
+ 'Customize project name and bundle identifier?',
280
+ false
281
+ )
282
+
283
+ if (shouldCustomize) {
284
+ await customizeProject(cwd)
285
+ } else {
286
+ showInfo('Keeping default project configuration')
287
+ }
288
+
289
+ console.info()
290
+ }
291
+
292
+ // Phase 3: Web Port Configuration
293
+ if (
294
+ startStep === 'prerequisites' ||
295
+ startStep === 'identity' ||
296
+ startStep === 'ports' ||
297
+ startStep === 'full'
298
+ ) {
299
+ saveOnboardState(cwd, { step: 'ports', timestamp: Date.now() })
300
+ showStep('Configuring web server port...')
301
+ console.info()
302
+
303
+ showInfo('Default web port: 8081 (TAMA in T9)')
304
+ const shouldCustomizePort = await confirmContinue(
305
+ 'Customize web server port?',
306
+ false
307
+ )
308
+
309
+ if (shouldCustomizePort) {
310
+ const newPort = await promptText(
311
+ 'Web server port:',
312
+ '8081',
313
+ '3000, 8080, 8081, etc.'
314
+ )
315
+
316
+ if (newPort && newPort !== '8081') {
317
+ await replacePortInProject(cwd, '8081', newPort)
318
+ showSuccess(`✓ Updated web server port to ${newPort}`)
319
+ }
320
+ } else {
321
+ showInfo('Keeping default port 8081')
322
+ }
323
+
324
+ console.info()
325
+ showStep('Checking service ports...')
326
+ console.info()
327
+
328
+ const portChecks = checkAllPorts()
329
+ const conflicts = getConflictingPorts(portChecks)
330
+
331
+ if (conflicts.length > 0) {
332
+ displayPortConflicts(conflicts)
333
+ showWarning('Some ports are already in use. You may need to stop other services.')
334
+ }
335
+
336
+ console.info()
337
+ }
338
+
339
+ // Phase 4: CI/CD Runner Configuration
340
+ if (
341
+ startStep === 'prerequisites' ||
342
+ startStep === 'identity' ||
343
+ startStep === 'ports' ||
344
+ startStep === 'full'
345
+ ) {
346
+ saveOnboardState(cwd, { step: 'ci-runners', timestamp: Date.now() })
347
+ showStep('Configuring CI/CD runners...')
348
+ console.info()
349
+
350
+ const shouldConfigureCI = await confirmContinue(
351
+ 'Configure GitHub Actions CI runners?',
352
+ true
353
+ )
354
+
355
+ if (shouldConfigureCI) {
356
+ await configureCIRunners(cwd)
357
+ } else {
358
+ showInfo('Skipping CI runner configuration')
359
+ showWarning(
360
+ 'Default CI uses ARM64 Docker builds. If not using ARM runners, update scripts/web/build-docker.ts'
361
+ )
362
+ }
363
+
364
+ console.info()
365
+ }
366
+
367
+ // Phase 6: Development Complete
368
+ if (startStep !== 'production') {
369
+ showStep('Development setup complete!')
370
+ console.info()
371
+
372
+ showSuccess('✓ Environment configured')
373
+ showSuccess('✓ Project ready for development')
374
+
375
+ markOnboarded(cwd)
376
+
377
+ console.info()
378
+ showInfo('Next steps (run in separate terminals):')
379
+ console.info()
380
+ console.info(' bun backend # start docker services first')
381
+ console.info(' bun dev # start web dev server')
382
+ console.info()
383
+ console.info(' bun ios # build iOS dev app')
384
+ console.info(' bun android # build Android dev app')
385
+ console.info(' bun tko docs list # view repository docs')
386
+ console.info()
387
+ }
388
+
389
+ // Phase 6.5: Monorepo Ejection (Optional)
390
+ if (startStep !== 'production' && hasLocalPackages) {
391
+ console.info()
392
+ showStep('Monorepo Setup')
393
+ console.info()
394
+
395
+ console.info(
396
+ pc.gray(
397
+ "We've included a variety of packages we found useful building apps with this stack:"
398
+ )
399
+ )
400
+ console.info(pc.gray(' • @o/cli - CLI tools and onboarding'))
401
+ console.info(pc.gray(' • @o/helpers - Utility functions'))
402
+ console.info(pc.gray(' • @o/hooks - React hooks'))
403
+ console.info(pc.gray(' • @o/database - Database utilities'))
404
+ console.info(pc.gray(' • @o/scripts - Build and dev scripts'))
405
+ console.info(pc.gray(' • @o/better-auth-utils - Auth helpers'))
406
+ console.info()
407
+ console.info(pc.gray('These packages are included locally for two reasons:'))
408
+ console.info(
409
+ pc.gray(' 1. You can see their source and decide if you want to keep them')
410
+ )
411
+ console.info(
412
+ pc.gray(' 2. Anyone can easily submit fixes or improvements back to our repo')
413
+ )
414
+ console.info()
415
+ console.info(
416
+ pc.gray(
417
+ "Over time we'll publish new versions. You can sync with 'bun tko sync' (monorepo)"
418
+ )
419
+ )
420
+ console.info(pc.gray("or if you eject, use 'bun up takeout' for package updates."))
421
+ console.info()
422
+
423
+ const shouldEject = await confirmContinue(
424
+ 'Eject from monorepo setup? (removes ./packages, uses published versions)',
425
+ false
426
+ )
427
+
428
+ if (shouldEject) {
429
+ // first run a dry-run to show what will happen
430
+ const dryResult = await ejectFromMonorepo(cwd, { dryRun: true })
431
+
432
+ if (!dryResult.success) {
433
+ showError(`Cannot eject: ${dryResult.error}`)
434
+ } else {
435
+ console.info()
436
+ showInfo(`Found ${dryResult.packages?.length} packages to convert:`)
437
+ for (const pkg of dryResult.packages || []) {
438
+ console.info(pc.gray(` • ${pkg.name}@${pkg.version}`))
439
+ }
440
+ if (dryResult.warnings?.length) {
441
+ for (const warn of dryResult.warnings) {
442
+ showWarning(warn)
443
+ }
444
+ }
445
+ console.info()
446
+
447
+ const confirmEject = await confirmContinue('Proceed with ejection?', true)
448
+ if (confirmEject) {
449
+ const spinner = showSpinner('Ejecting from monorepo...')
450
+
451
+ const result = await ejectFromMonorepo(cwd)
452
+
453
+ if (result.success) {
454
+ spinner.stop('Ejected from monorepo')
455
+ showSuccess('✓ Removed ./packages directory')
456
+ showSuccess('✓ Updated package.json to use published versions')
457
+ showSuccess('✓ Installed published packages')
458
+
459
+ // commit the eject changes
460
+ try {
461
+ execSync('git add -A && git commit -m "ejected from monorepo"', {
462
+ cwd,
463
+ stdio: 'ignore',
464
+ })
465
+ showSuccess('✓ Committed eject changes')
466
+ } catch {
467
+ showWarning('Git commit skipped (not a git repo or no changes)')
468
+ }
469
+
470
+ console.info()
471
+ showInfo('You can now upgrade packages with: bun up takeout')
472
+ } else {
473
+ spinner.stop('Ejection failed')
474
+ showError(`Failed to eject: ${result.error}`)
475
+ if (result.error?.includes('install failed')) {
476
+ showInfo('You may be able to fix this by running "bun install" manually')
477
+ showInfo('Or restore the repo from git with "git checkout ."')
478
+ }
479
+ }
480
+ } else {
481
+ showInfo('Keeping monorepo setup - you can customize packages locally')
482
+ showInfo('Run "bun tko sync" to sync with upstream Takeout updates later')
483
+ }
484
+ }
485
+ } else {
486
+ showInfo('Keeping monorepo setup - you can customize packages locally')
487
+ showInfo('Run "bun tko sync" to sync with upstream Takeout updates later')
488
+ }
489
+
490
+ console.info()
491
+ }
492
+
493
+ // Phase 7: Production Setup (Optional or direct)
494
+ if (startStep === 'full' || startStep === 'production') {
495
+ saveOnboardState(cwd, { step: 'production', timestamp: Date.now() })
496
+ console.info()
497
+ showStep('Production deployment setup')
498
+ console.info()
499
+
500
+ // Only ask to confirm if doing full setup, skip if directly chose production
501
+ let setupProd = startStep === 'production'
502
+ if (startStep === 'full') {
503
+ setupProd = await confirmContinue('Set up production deployment?', false)
504
+ }
505
+
506
+ if (setupProd) {
507
+ await setupProductionDeployment(cwd)
508
+ } else {
509
+ showInfo('Skipping production setup')
510
+ showInfo('You can set up production later with: bun tko onboard --production')
511
+ }
512
+ }
513
+
514
+ // Clear state on successful completion
515
+ clearOnboardState(cwd)
516
+
517
+ console.info()
518
+ displayOutro('Happy coding! 🚀')
519
+ },
520
+ })
521
+
522
+ async function customizeProject(cwd: string): Promise<void> {
523
+ const projectName = await promptText('Project name:', 'takeout', 'my-awesome-app')
524
+
525
+ const slug = await promptText(
526
+ 'Project slug (URL-friendly):',
527
+ projectName.toLowerCase().replace(/\s+/g, '-'),
528
+ 'my-awesome-app'
529
+ )
530
+
531
+ const bundleId = await promptText(
532
+ 'Bundle identifier:',
533
+ `com.${slug}.app`,
534
+ 'com.example.app'
535
+ )
536
+
537
+ const domain = await promptText(
538
+ 'Development domain:',
539
+ 'localhost:8081',
540
+ 'localhost:8081'
541
+ )
542
+
543
+ // Update package.json
544
+ const pkgResult = updatePackageJson(cwd, {
545
+ name: projectName,
546
+ description: `${projectName} - Built with Takeout starter kit`,
547
+ })
548
+
549
+ if (pkgResult.success) {
550
+ showSuccess('Updated package.json')
551
+ } else {
552
+ showError(`Failed to update package.json: ${pkgResult.error}`)
553
+ }
554
+
555
+ // Update app.config.ts
556
+ const configResult = updateAppConfig(cwd, {
557
+ name: projectName,
558
+ slug,
559
+ bundleId,
560
+ })
561
+
562
+ if (configResult.success) {
563
+ showSuccess('Updated app.config.ts')
564
+ } else {
565
+ showError(`Failed to update app.config.ts: ${configResult.error}`)
566
+ }
567
+
568
+ // Update .env URLs
569
+ const serverUrl = `http://${domain}`
570
+ updateEnvVariable(cwd, 'BETTER_AUTH_URL', serverUrl)
571
+ updateEnvVariable(cwd, 'ONE_SERVER_URL', serverUrl)
572
+ showSuccess('Updated environment URLs')
573
+ }
574
+
575
+ async function setupProductionDeployment(cwd: string): Promise<void> {
576
+ // Choose platform
577
+ const platform = await promptSelect<'uncloud' | 'sst'>('Choose deployment platform:', [
578
+ {
579
+ value: 'uncloud',
580
+ label: 'Uncloud',
581
+ hint: 'Simpler and quicker (~10 minutes setup)',
582
+ },
583
+ {
584
+ value: 'sst',
585
+ label: 'AWS SST',
586
+ hint: 'Proven and reliable (~1 hour setup)',
587
+ },
588
+ ])
589
+
590
+ if (platform === 'cancel') {
591
+ showInfo('Skipping production setup')
592
+ return
593
+ }
594
+
595
+ console.info()
596
+
597
+ if (platform === 'uncloud') {
598
+ await setupUncloudDeployment(cwd)
599
+ } else {
600
+ await setupSSTDeployment(cwd)
601
+ }
602
+ }
603
+
604
+ async function setupUncloudDeployment(cwd: string): Promise<void> {
605
+ showInfo('Setting up Uncloud deployment')
606
+ console.info()
607
+ console.info(
608
+ pc.gray(
609
+ 'Uncloud provides:\n • Managed PostgreSQL with logical replication\n • Free subdomain (your-app.uncld.dev)\n • Automatic SSL certificates\n • Easy scaling'
610
+ )
611
+ )
612
+ console.info()
613
+
614
+ // ask about server architecture
615
+ console.info()
616
+ showInfo('Server Architecture')
617
+ console.info(pc.gray('Docker images must match your server CPU architecture'))
618
+ console.info()
619
+
620
+ const architecture = await promptSelect<'amd64' | 'arm64'>(
621
+ 'What CPU architecture is your deployment server?',
622
+ [
623
+ {
624
+ value: 'amd64',
625
+ label: 'AMD64/x86_64 (Intel/AMD)',
626
+ hint: 'Most VPS providers (DigitalOcean, Linode, Vultr)',
627
+ },
628
+ {
629
+ value: 'arm64',
630
+ label: 'ARM64 (Apple Silicon)',
631
+ hint: 'Hetzner ARM, Oracle ARM, Bare metal ARM servers',
632
+ },
633
+ ]
634
+ )
635
+
636
+ if (architecture === 'cancel') {
637
+ showInfo('Skipping production setup')
638
+ return
639
+ }
640
+
641
+ const deploymentArch = architecture === 'arm64' ? 'linux/arm64' : 'linux/amd64'
642
+ console.info()
643
+ showInfo(`Will build Docker images for: ${deploymentArch}`)
644
+ console.info()
645
+
646
+ // Read app name from constants
647
+ const appConstantsPath = resolve(cwd, 'src/constants/app.ts')
648
+ let defaultAppName = 'my-app'
649
+ try {
650
+ const appConstants = readFileSync(appConstantsPath, 'utf-8')
651
+ const appNameMatch = appConstants.match(/APP_NAME_LOWERCASE\s*=\s*['"](.+?)['"]/)
652
+ if (appNameMatch?.[1]) {
653
+ defaultAppName = appNameMatch[1]
654
+ }
655
+ } catch {
656
+ // use default if can't read file
657
+ }
658
+
659
+ // Domain choice
660
+ const useFreeSubdomain = await confirmContinue('Use free Uncloud subdomain?', true)
661
+
662
+ let domain: string
663
+ let zeroUrl: string
664
+
665
+ // TODO: reconsider the domain configuration onboarding flow as the cluster DNS xxxxxx.uncld.dev will be available
666
+ // only after initializing the cluster.
667
+ if (useFreeSubdomain) {
668
+ const appName = await promptText(
669
+ 'App name for subdomain:',
670
+ defaultAppName,
671
+ defaultAppName
672
+ )
673
+ domain = `https://${appName}.uncld.dev`
674
+ zeroUrl = `https://zero-${appName}.uncld.dev`
675
+ } else {
676
+ domain = await promptText(
677
+ 'Enter your custom domain:',
678
+ undefined,
679
+ 'https://yourapp.com'
680
+ )
681
+ zeroUrl = await promptText(
682
+ 'Enter your Zero sync domain:',
683
+ undefined,
684
+ 'https://zero.yourapp.com'
685
+ )
686
+ console.info()
687
+ showWarning('Custom domain setup requires DNS configuration after deployment')
688
+ // TODO: there is no such doc
689
+ console.info(pc.gray('See: https://uncloud.run/docs/domains'))
690
+ }
691
+
692
+ console.info()
693
+
694
+ // Database setup
695
+ showInfo('Database Configuration')
696
+ console.info()
697
+ console.info(pc.gray('PostgreSQL database with logical replication enabled'))
698
+ console.info(pc.gray('Zero sync requires 3 databases on the same host:'))
699
+ console.info(pc.gray(' • Main database (your app data)'))
700
+ console.info(pc.gray(' • Two Zero databases (for sync infrastructure)'))
701
+ console.info()
702
+ console.info(pc.gray('Use a managed database (DigitalOcean, Render, Supabase, etc.)'))
703
+ console.info(pc.gray('The deployment will automatically create the Zero databases'))
704
+ console.info()
705
+
706
+ const dbUser = await promptText('Database username:', 'postgres', 'postgres')
707
+ const dbPassword = await promptText('Database password:', undefined, '')
708
+ const dbHost = await promptText(
709
+ 'Database host (e.g., db-xxx.ondigitalocean.com):',
710
+ undefined,
711
+ 'localhost'
712
+ )
713
+ const dbPort = await promptText('Database port:', '5432', '5432')
714
+ const dbName = await promptText(
715
+ 'Main database name (will derive Zero databases from this):',
716
+ 'postgres',
717
+ 'postgres'
718
+ )
719
+
720
+ // Construct database URL (deployment script will derive Zero databases from this)
721
+ const dbUrl = `postgresql://${dbUser}:${dbPassword}@${dbHost}:${dbPort}/${dbName}`
722
+
723
+ // Generate auth secret
724
+ console.info()
725
+ const authSecret = randomBytes(32).toString('hex')
726
+
727
+ // Ensure .env.production exists (create from example if needed)
728
+ const envFile = '.env.production'
729
+ if (!envFileExists(cwd, envFile)) {
730
+ const copyResult = copyEnvFile(cwd, '.env.production.example', envFile)
731
+ if (copyResult.success) {
732
+ showSuccess(`Created ${envFile} from .env.production.example`)
733
+ } else {
734
+ showError(`Failed to create ${envFile}: ${copyResult.error}`)
735
+ return
736
+ }
737
+ }
738
+
739
+ updateEnvVariable(cwd, 'DEPLOYMENT_PLATFORM', 'uncloud', envFile)
740
+ updateEnvVariable(cwd, 'DEPLOYMENT_ARCH', deploymentArch, envFile)
741
+ updateEnvVariable(cwd, 'DEPLOY_DB', dbUrl, envFile)
742
+ updateEnvVariable(cwd, 'BETTER_AUTH_SECRET', authSecret, envFile)
743
+ updateEnvVariable(cwd, 'BETTER_AUTH_URL', domain, envFile)
744
+ updateEnvVariable(cwd, 'ONE_SERVER_URL', domain, envFile)
745
+ // extract hostname from URL (remove protocol)
746
+ const zeroHost = zeroUrl.replace(/^https?:\/\//, '')
747
+ const webHost = domain.replace(/^https?:\/\//, '')
748
+ updateEnvVariable(cwd, 'VITE_ZERO_HOSTNAME', zeroHost, envFile)
749
+ updateEnvVariable(cwd, 'VITE_WEB_HOSTNAME', webHost, envFile)
750
+
751
+ // derive zero database URLs from the main database URL
752
+ const dbBase = dbUrl.split('/').slice(0, -1).join('/')
753
+ const zeroCvrDb = `${dbBase}/zero_cvr`
754
+ const zeroChangeDb = `${dbBase}/zero_cdb`
755
+
756
+ // set zero database vars in .env.production (for production deployment)
757
+ updateEnvVariable(cwd, 'ZERO_UPSTREAM_DB', dbUrl, envFile)
758
+ updateEnvVariable(cwd, 'ZERO_CVR_DB', zeroCvrDb, envFile)
759
+ updateEnvVariable(cwd, 'ZERO_CHANGE_DB', zeroChangeDb, envFile)
760
+
761
+ // also set in .env for local dev
762
+ updateEnvVariable(cwd, 'ZERO_UPSTREAM_DB', dbUrl, '.env')
763
+ updateEnvVariable(cwd, 'ZERO_CVR_DB', zeroCvrDb, '.env')
764
+ updateEnvVariable(cwd, 'ZERO_CHANGE_DB', zeroChangeDb, '.env')
765
+
766
+ // Extract host from domain URL and save for deployment
767
+ const deployHost = new URL(domain).hostname
768
+ updateEnvVariable(cwd, 'DEPLOY_HOST', deployHost, envFile)
769
+ updateEnvVariable(cwd, 'DEPLOY_USER', 'root', envFile)
770
+
771
+ // SSH key setup
772
+ console.info()
773
+ showInfo('SSH Key Configuration')
774
+ console.info(pc.gray('Deployment requires SSH access to your server'))
775
+ console.info()
776
+
777
+ const sshKeyPath = await promptText(
778
+ 'Path to SSH private key:',
779
+ `${homedir()}/.ssh/id_rsa`,
780
+ `${homedir()}/.ssh/id_rsa`
781
+ )
782
+
783
+ if (sshKeyPath) {
784
+ // verify the key exists
785
+ if (existsSync(sshKeyPath)) {
786
+ updateEnvVariable(cwd, 'DEPLOY_SSH_KEY', sshKeyPath, envFile)
787
+ showSuccess(`✓ SSH key configured: ${sshKeyPath}`)
788
+ console.info()
789
+ showInfo(
790
+ pc.gray(
791
+ "For CI/CD, you'll need to add the SSH private key content as a GitHub secret"
792
+ )
793
+ )
794
+ showInfo(pc.gray('The sync script will help with this'))
795
+ } else {
796
+ showWarning(`SSH key not found at: ${sshKeyPath}`)
797
+ showInfo('You can add DEPLOY_SSH_KEY to .env.production manually later')
798
+ }
799
+ }
800
+
801
+ console.info()
802
+ showSuccess(`✓ Saved configuration to ${envFile}`)
803
+
804
+ // Custom domain setup (optional)
805
+ console.info()
806
+ showInfo('Custom Domain Setup (Optional)')
807
+ console.info(pc.gray('By default, your app will use:'))
808
+ console.info(pc.gray(` ${deployHost} (cluster subdomain from Uncloud DNS)`))
809
+ console.info()
810
+ console.info(
811
+ pc.gray('You can optionally configure custom domains (e.g., app.yourdomain.com) by:')
812
+ )
813
+ console.info(pc.gray(' 1. Adding CNAME records in your DNS provider'))
814
+ console.info(pc.gray(` 2. Pointing to your cluster subdomain`))
815
+ console.info(
816
+ pc.gray(' 3. Setting VITE_WEB_HOSTNAME and VITE_ZERO_HOSTNAME in .env.production')
817
+ )
818
+ console.info()
819
+
820
+ const configureCustomDomain = await confirmContinue(
821
+ 'Configure custom domain now?',
822
+ false
823
+ )
824
+
825
+ if (configureCustomDomain) {
826
+ console.info()
827
+ console.info(pc.gray('First, run: uc dns reserve'))
828
+ console.info(pc.gray('This will give you a cluster subdomain like: abc123.uncld.dev'))
829
+ console.info()
830
+
831
+ const clusterSubdomain = await promptText(
832
+ 'Enter your cluster subdomain from uc dns show:',
833
+ '',
834
+ ''
835
+ )
836
+
837
+ if (clusterSubdomain) {
838
+ console.info()
839
+ showInfo('DNS Setup Instructions:')
840
+ console.info(
841
+ pc.gray('Add these CNAME records in your DNS provider (e.g., Cloudflare):')
842
+ )
843
+ console.info()
844
+
845
+ const webDomain = await promptText(
846
+ 'Custom domain for web app (e.g., app.yourdomain.com):',
847
+ '',
848
+ ''
849
+ )
850
+
851
+ const zeroDomain = await promptText(
852
+ 'Custom domain for zero sync (e.g., zero.yourdomain.com):',
853
+ '',
854
+ ''
855
+ )
856
+
857
+ if (webDomain) {
858
+ console.info()
859
+ console.info(pc.cyan(` CNAME: ${webDomain} → ${clusterSubdomain}`))
860
+ if (zeroDomain) {
861
+ console.info(pc.cyan(` CNAME: ${zeroDomain} → ${clusterSubdomain}`))
862
+ }
863
+ console.info()
864
+ console.info(
865
+ pc.yellow('⚠️ Set DNS to "DNS only" mode (gray cloud), not proxied')
866
+ )
867
+ console.info()
868
+
869
+ const webUrl = `https://${webDomain}`
870
+ updateEnvVariable(cwd, 'VITE_WEB_HOSTNAME', webDomain, envFile)
871
+ updateEnvVariable(cwd, 'BETTER_AUTH_URL', webUrl, envFile)
872
+ updateEnvVariable(cwd, 'ONE_SERVER_URL', webUrl, envFile)
873
+
874
+ if (zeroDomain) {
875
+ updateEnvVariable(cwd, 'VITE_ZERO_HOSTNAME', zeroDomain, envFile)
876
+ }
877
+
878
+ showSuccess('✓ Custom domains configured')
879
+ console.info()
880
+ showInfo(pc.gray('DNS propagation typically takes 5-30 minutes'))
881
+
882
+ // offer cloudflare origin ca option
883
+ console.info()
884
+ showInfo('SSL Certificate Options')
885
+ console.info(
886
+ pc.gray("By default, Caddy will use Let's Encrypt for SSL certificates.")
887
+ )
888
+ console.info(pc.gray('If using Cloudflare, you can use Origin CA instead to:'))
889
+ console.info(pc.gray(" • Bypass Let's Encrypt rate limits"))
890
+ console.info(pc.gray(' • Enable Cloudflare proxy (DDoS protection, caching)'))
891
+ console.info()
892
+
893
+ const useOriginCA = await confirmContinue(
894
+ 'Use Cloudflare Origin CA? (requires Cloudflare account)',
895
+ false
896
+ )
897
+
898
+ if (useOriginCA) {
899
+ console.info()
900
+ showInfo('Cloudflare Origin CA Setup')
901
+ console.info(pc.gray('1. Go to Cloudflare Dashboard → SSL/TLS → Origin Server'))
902
+ console.info(pc.gray('2. Click "Create Certificate"'))
903
+ console.info(
904
+ pc.gray(
905
+ `3. Add hostnames: ${webDomain}${zeroDomain ? `, ${zeroDomain}` : ''}`
906
+ )
907
+ )
908
+ console.info(pc.gray('4. Choose 15 year validity'))
909
+ console.info(pc.gray('5. Save certificate to: certs/origin.pem'))
910
+ console.info(pc.gray('6. Save private key to: certs/origin.key'))
911
+ console.info()
912
+
913
+ const certPath = await promptText(
914
+ 'Path to Origin CA certificate:',
915
+ 'certs/origin.pem',
916
+ 'certs/origin.pem'
917
+ )
918
+
919
+ const keyPath = await promptText(
920
+ 'Path to Origin CA private key:',
921
+ 'certs/origin.key',
922
+ 'certs/origin.key'
923
+ )
924
+
925
+ if (certPath && keyPath) {
926
+ updateEnvVariable(cwd, 'ORIGIN_CA_CERT', certPath, envFile)
927
+ updateEnvVariable(cwd, 'ORIGIN_CA_KEY', keyPath, envFile)
928
+
929
+ showSuccess('✓ Origin CA configured')
930
+ console.info(pc.gray(' Caddyfile will be auto-generated during deploy'))
931
+ console.info()
932
+ console.info(pc.yellow('Important: In Cloudflare Dashboard:'))
933
+ console.info(pc.yellow(' 1. Enable proxy (orange cloud) for your domains'))
934
+ console.info(pc.yellow(' 2. Set SSL mode to "Full (strict)"'))
935
+ }
936
+ }
937
+ }
938
+ }
939
+ }
940
+
941
+ // update package.json env section to remove sst-specific vars
942
+ console.info()
943
+ showInfo('Updating package.json env section for Uncloud deployment...')
944
+ const envUpdateResult = updatePackageJsonEnv(cwd, 'uncloud')
945
+ if (envUpdateResult.success) {
946
+ showSuccess('✓ Removed SST-specific environment variables from package.json')
947
+ } else {
948
+ showWarning(`Failed to update package.json env: ${envUpdateResult.error}`)
949
+ }
950
+
951
+ // run env:update to sync to GitHub workflow
952
+ console.info()
953
+ showInfo('Updating GitHub workflow with environment variables...')
954
+ try {
955
+ execSync('bun env:update', { cwd, stdio: 'ignore' })
956
+ showSuccess('✓ GitHub workflow updated')
957
+ } catch (error) {
958
+ showWarning('Failed to update GitHub workflow (non-critical)')
959
+ }
960
+
961
+ // offer to sync to github
962
+ console.info()
963
+ const syncToGitHub = await confirmContinue(
964
+ 'Sync environment to GitHub secrets for CI/CD?',
965
+ true
966
+ )
967
+
968
+ if (syncToGitHub) {
969
+ try {
970
+ execSync('bun scripts/env/sync-to-github.ts --yes', { cwd, stdio: 'inherit' })
971
+ } catch (error) {
972
+ showWarning('Failed to sync to GitHub (you can do this later)')
973
+ showInfo('Run manually: bun scripts/env/sync-to-github.ts')
974
+ }
975
+ } else {
976
+ showInfo('You can sync later with: bun scripts/env/sync-to-github.ts')
977
+ }
978
+
979
+ // Next steps
980
+ console.info()
981
+ showStep('Ready to deploy!')
982
+ console.info()
983
+ console.info(pc.bold('Next steps:'))
984
+ console.info()
985
+ console.info(pc.cyan('1. Install Uncloud CLI (if not already installed):'))
986
+ console.info(pc.gray(' npm install -g uncloud-cli'))
987
+ console.info()
988
+ console.info(pc.cyan('2. Login to Uncloud:'))
989
+ console.info(pc.gray(' uncloud login'))
990
+ console.info()
991
+ console.info(pc.cyan('3. Deploy your app:'))
992
+ console.info(pc.gray(' bun tko uncloud deploy-prod'))
993
+ console.info()
994
+ console.info(pc.cyan('Or push to main branch for automatic CI/CD deployment:'))
995
+ console.info(pc.gray(' git push origin main'))
996
+ console.info()
997
+ console.info(pc.bold('scaling to multiple machines:'))
998
+ console.info(pc.gray(' uc machine add --name server-2 root@IP'))
999
+ console.info(pc.gray(' uc scale web 3 # run 3 instances'))
1000
+ console.info()
1001
+ console.info(pc.gray('view detailed guide: bun tko docs get deploy-uncloud'))
1002
+ console.info(pc.gray('or see: docs/deployment-uncloud.md'))
1003
+ }
1004
+
1005
+ async function setupSSTDeployment(cwd: string): Promise<void> {
1006
+ showInfo('Setting up AWS SST deployment')
1007
+ console.info()
1008
+ showWarning('AWS setup takes approximately 30 minutes')
1009
+ console.info()
1010
+ console.info(
1011
+ pc.gray(
1012
+ 'SST provides:\n • AWS infrastructure (ECS, Aurora, ALB)\n • Auto-scaling\n • Full control over resources\n • Higher setup complexity'
1013
+ )
1014
+ )
1015
+ console.info()
1016
+
1017
+ // ask about architecture (ARM is cheaper for AWS)
1018
+ console.info()
1019
+ showInfo('AWS ECS Architecture')
1020
+ console.info(pc.gray('AWS Graviton (ARM64) is ~40% cheaper than x86_64'))
1021
+ console.info(
1022
+ pc.gray('Both have excellent performance, ARM recommended for cost savings')
1023
+ )
1024
+ console.info()
1025
+
1026
+ const architecture = await promptSelect<'amd64' | 'arm64'>(
1027
+ 'What CPU architecture for AWS ECS?',
1028
+ [
1029
+ {
1030
+ value: 'arm64',
1031
+ label: 'ARM64 (Graviton) - Recommended',
1032
+ hint: 'Significantly cheaper, excellent performance',
1033
+ },
1034
+ {
1035
+ value: 'amd64',
1036
+ label: 'AMD64/x86_64 (Intel/AMD)',
1037
+ hint: 'Standard option if you need specific x86 dependencies',
1038
+ },
1039
+ ]
1040
+ )
1041
+
1042
+ if (architecture === 'cancel') {
1043
+ showInfo('Skipping AWS setup')
1044
+ return
1045
+ }
1046
+
1047
+ const deploymentArch = architecture === 'arm64' ? 'linux/arm64' : 'linux/amd64'
1048
+ console.info()
1049
+ showInfo(`Will build Docker images for: ${deploymentArch}`)
1050
+ console.info()
1051
+
1052
+ const shouldContinue = await confirmContinue(
1053
+ 'Continue with AWS SST setup? (requires AWS account)',
1054
+ false
1055
+ )
1056
+
1057
+ if (!shouldContinue) {
1058
+ showInfo('Skipping AWS setup')
1059
+ showInfo('You can set up AWS later with: bun tko env:setup --category aws')
1060
+ return
1061
+ }
1062
+
1063
+ // Run the existing production env setup with AWS category
1064
+ await setupProductionEnv(cwd, {
1065
+ onlyCategory: 'aws',
1066
+ envFile: '.env.production',
1067
+ interactive: true,
1068
+ })
1069
+
1070
+ // Save deployment platform
1071
+ const envFile = '.env.production'
1072
+ updateEnvVariable(cwd, 'DEPLOYMENT_PLATFORM', 'sst', envFile)
1073
+ updateEnvVariable(cwd, 'DEPLOYMENT_ARCH', deploymentArch, envFile)
1074
+
1075
+ // update sst.config.ts architecture
1076
+ console.info()
1077
+ showInfo('Updating sst.config.ts architecture...')
1078
+ try {
1079
+ const sstConfigPath = resolve(cwd, 'sst.config.ts')
1080
+ let sstConfig = readFileSync(sstConfigPath, 'utf-8')
1081
+
1082
+ // replace architecture in all services
1083
+ const archValue = architecture === 'arm64' ? 'arm64' : 'x86_64'
1084
+ sstConfig = sstConfig.replace(
1085
+ /architecture:\s*['"]arm64['"]/g,
1086
+ `architecture: '${archValue}'`
1087
+ )
1088
+ sstConfig = sstConfig.replace(
1089
+ /architecture:\s*['"]x86_64['"]/g,
1090
+ `architecture: '${archValue}'`
1091
+ )
1092
+
1093
+ writeFileSync(sstConfigPath, sstConfig)
1094
+ showSuccess(`✓ Updated sst.config.ts to use ${archValue}`)
1095
+ } catch (error) {
1096
+ showWarning('Could not update sst.config.ts (you can update manually)')
1097
+ }
1098
+
1099
+ // update package.json env section to remove uncloud-specific vars
1100
+ console.info()
1101
+ showInfo('Updating package.json env section for SST deployment...')
1102
+ const envUpdateResult = updatePackageJsonEnv(cwd, 'sst')
1103
+ if (envUpdateResult.success) {
1104
+ showSuccess('✓ Removed Uncloud-specific environment variables from package.json')
1105
+ } else {
1106
+ showWarning(`Failed to update package.json env: ${envUpdateResult.error}`)
1107
+ }
1108
+
1109
+ // run env:update to sync to GitHub workflow
1110
+ console.info()
1111
+ showInfo('Updating GitHub workflow with environment variables...')
1112
+ try {
1113
+ execSync('bun env:update', { cwd, stdio: 'ignore' })
1114
+ showSuccess('✓ GitHub workflow updated')
1115
+ } catch (error) {
1116
+ showWarning('Failed to update GitHub workflow (non-critical)')
1117
+ }
1118
+
1119
+ // offer to sync to github
1120
+ console.info()
1121
+ const syncToGitHub = await confirmContinue(
1122
+ 'Sync environment to GitHub secrets for CI/CD?',
1123
+ true
1124
+ )
1125
+
1126
+ if (syncToGitHub) {
1127
+ try {
1128
+ execSync('bun scripts/env/sync-to-github.ts --yes', { cwd, stdio: 'inherit' })
1129
+ } catch (error) {
1130
+ showWarning('Failed to sync to GitHub (you can do this later)')
1131
+ showInfo('Run manually: bun scripts/env/sync-to-github.ts')
1132
+ }
1133
+ } else {
1134
+ showInfo('You can sync later with: bun scripts/env/sync-to-github.ts')
1135
+ }
1136
+
1137
+ console.info()
1138
+ showInfo(
1139
+ 'For complete AWS deployment guide, see: https://docs.yourapp.com/deployment/sst'
1140
+ )
1141
+ }
1142
+
1143
+ async function configureCIRunners(cwd: string): Promise<void> {
1144
+ showInfo('GitHub Actions CI/CD Runner Configuration')
1145
+ console.info()
1146
+ console.info(
1147
+ pc.gray(
1148
+ 'Your project uses ARM64 (Apple Silicon) architecture for Docker builds.\n' +
1149
+ 'GitHub Actions requires compatible runners for CI/CD to work properly.'
1150
+ )
1151
+ )
1152
+ console.info()
1153
+
1154
+ const runnerChoice = await promptSelect<'warp' | 'github-arm' | 'github-x64' | 'skip'>(
1155
+ 'Choose your CI runner configuration:',
1156
+ [
1157
+ {
1158
+ value: 'warp',
1159
+ label: 'Warp Runners (Recommended)',
1160
+ hint: 'Fast ARM64 runners, cheaper than GitHub ($0.005/min)',
1161
+ },
1162
+ {
1163
+ value: 'github-arm',
1164
+ label: 'GitHub ARM Runners',
1165
+ hint: 'Native ARM64, requires GitHub Teams/Enterprise ($0.16/min)',
1166
+ },
1167
+ {
1168
+ value: 'github-x64',
1169
+ label: 'GitHub x64 Runners (Free)',
1170
+ hint: 'Requires changing Docker builds to x64 architecture',
1171
+ },
1172
+ {
1173
+ value: 'skip',
1174
+ label: 'Configure Later',
1175
+ hint: 'Skip for now (CI will fail until configured)',
1176
+ },
1177
+ ]
1178
+ )
1179
+
1180
+ if (runnerChoice === 'cancel' || runnerChoice === 'skip') {
1181
+ showInfo('Skipping CI runner configuration')
1182
+ showWarning(
1183
+ 'CI/CD will fail until you configure runners. Update .github/workflows/ci.yml'
1184
+ )
1185
+ return
1186
+ }
1187
+
1188
+ const ciConfigPath = resolve(cwd, '.github/workflows/ci.yml')
1189
+ const dockerBuildPath = resolve(cwd, 'scripts/web/build-docker.ts')
1190
+
1191
+ try {
1192
+ let ciContent = readFileSync(ciConfigPath, 'utf-8')
1193
+ let dockerContent = readFileSync(dockerBuildPath, 'utf-8')
1194
+
1195
+ if (runnerChoice === 'warp') {
1196
+ console.info()
1197
+ showStep('Setting up Warp runners')
1198
+ console.info()
1199
+ console.info(pc.cyan('1. Sign up for Warp Build (if not already):'))
1200
+ console.info(pc.gray(' https://www.warpbuild.com'))
1201
+ console.info()
1202
+ console.info(pc.cyan('2. Install Warp GitHub App:'))
1203
+ console.info(pc.gray(' https://github.com/apps/warp-build'))
1204
+ console.info()
1205
+ console.info(pc.cyan('3. Grant access to your repository'))
1206
+ console.info()
1207
+
1208
+ // CI config is already set for Warp, just confirm
1209
+ showSuccess('✓ CI configuration already set for Warp runners')
1210
+ showInfo('Warp uses ARM64 runners matching your local architecture')
1211
+ } else if (runnerChoice === 'github-arm') {
1212
+ // Update CI to use GitHub ARM runners
1213
+ ciContent = ciContent.replace(
1214
+ /runs-on:.*warp-ubuntu-latest-arm64.*/,
1215
+ 'runs-on: ubuntu-24.04-arm'
1216
+ )
1217
+ writeFileSync(ciConfigPath, ciContent)
1218
+
1219
+ console.info()
1220
+ showSuccess('✓ Updated CI to use GitHub ARM runners')
1221
+ showWarning('Note: GitHub ARM runners require Teams or Enterprise plan')
1222
+ showInfo('Pricing: $0.16/minute for ARM runners')
1223
+ } else if (runnerChoice === 'github-x64') {
1224
+ // Update CI to use standard GitHub runners
1225
+ ciContent = ciContent.replace(
1226
+ /runs-on:.*warp-ubuntu-latest-arm64.*/,
1227
+ 'runs-on: ubuntu-latest'
1228
+ )
1229
+ writeFileSync(ciConfigPath, ciContent)
1230
+
1231
+ // Update Docker build script to use x64
1232
+ dockerContent = dockerContent.replace('linux/arm64', 'linux/amd64')
1233
+ writeFileSync(dockerBuildPath, dockerContent)
1234
+
1235
+ console.info()
1236
+ showSuccess('✓ Updated CI to use free GitHub x64 runners')
1237
+ showSuccess('✓ Updated Docker builds to x64 architecture')
1238
+ showWarning(
1239
+ "Note: Docker images built on x64 won't run on ARM64 machines without emulation"
1240
+ )
1241
+ }
1242
+
1243
+ console.info()
1244
+ showInfo('CI runner configuration complete')
1245
+ } catch (error) {
1246
+ showError('Failed to update CI configuration')
1247
+ showInfo(
1248
+ 'Please manually update .github/workflows/ci.yml and scripts/web/build-docker.ts'
1249
+ )
1250
+ }
1251
+ }
1252
+
1253
+ async function startServices(cwd: string): Promise<void> {
1254
+ const spinner = showSpinner('Starting Docker services...')
1255
+
1256
+ try {
1257
+ // Start services in background
1258
+ execSync('bun backend', {
1259
+ stdio: 'ignore',
1260
+ cwd,
1261
+ })
1262
+
1263
+ // Wait a bit for services to start
1264
+ await new Promise((resolve) => setTimeout(resolve, 3000))
1265
+
1266
+ spinner.stop('Docker services started')
1267
+ showSuccess('✓ PostgreSQL running on port 5432')
1268
+ showSuccess('✓ Zero sync running on port 4848')
1269
+ showSuccess('✓ MinIO (S3) running on port 9090')
1270
+
1271
+ // Run migrations
1272
+ const shouldMigrate = await confirmContinue('Run database migrations?', true)
1273
+
1274
+ if (shouldMigrate) {
1275
+ const migrateSpinner = showSpinner('Running migrations...')
1276
+ try {
1277
+ execSync('bun migrate', { stdio: 'ignore', cwd })
1278
+ migrateSpinner.stop('Database migrated')
1279
+ showSuccess('✓ Database migrations complete')
1280
+ } catch {
1281
+ migrateSpinner.stop('Migration failed')
1282
+ showError('Failed to run migrations')
1283
+ showInfo("Try running 'bun migrate' manually")
1284
+ }
1285
+ }
1286
+ } catch (error) {
1287
+ spinner.stop('Failed to start services')
1288
+ showError(error instanceof Error ? error.message : 'Unknown error')
1289
+ showInfo("Try running 'bun backend' manually")
1290
+ }
1291
+ }
1292
+
1293
+ /**
1294
+ * Replace port throughout project files (cross-platform)
1295
+ */
1296
+ async function replacePortInProject(
1297
+ cwd: string,
1298
+ oldPort: string,
1299
+ newPort: string
1300
+ ): Promise<void> {
1301
+ const spinner = showSpinner(
1302
+ `Replacing port ${oldPort} with ${newPort} throughout project...`
1303
+ )
1304
+
1305
+ // directories to skip
1306
+ const excludeDirs = new Set([
1307
+ 'node_modules',
1308
+ '.git',
1309
+ 'dist',
1310
+ 'build',
1311
+ '.next',
1312
+ '.turbo',
1313
+ 'types',
1314
+ ])
1315
+
1316
+ // file extensions to process
1317
+ const includeExts = new Set([
1318
+ '.ts',
1319
+ '.tsx',
1320
+ '.js',
1321
+ '.jsx',
1322
+ '.json',
1323
+ '.md',
1324
+ '.yml',
1325
+ '.yaml',
1326
+ ])
1327
+
1328
+ // recursively find and replace in files
1329
+ async function processDir(dir: string): Promise<void> {
1330
+ const { readdirSync, statSync } = await import('node:fs')
1331
+ const { join, extname, basename } = await import('node:path')
1332
+
1333
+ const entries = readdirSync(dir)
1334
+
1335
+ for (const entry of entries) {
1336
+ const fullPath = join(dir, entry)
1337
+
1338
+ try {
1339
+ const stat = statSync(fullPath)
1340
+
1341
+ if (stat.isDirectory()) {
1342
+ if (!excludeDirs.has(entry)) {
1343
+ await processDir(fullPath)
1344
+ }
1345
+ } else if (stat.isFile()) {
1346
+ const ext = extname(entry)
1347
+ const name = basename(entry)
1348
+ // check extension or .env* pattern
1349
+ if (includeExts.has(ext) || name.startsWith('.env')) {
1350
+ const content = readFileSync(fullPath, 'utf-8')
1351
+ if (content.includes(oldPort)) {
1352
+ const newContent = content.split(oldPort).join(newPort)
1353
+ writeFileSync(fullPath, newContent, 'utf-8')
1354
+ }
1355
+ }
1356
+ }
1357
+ } catch {
1358
+ // skip files we can't read
1359
+ }
1360
+ }
1361
+ }
1362
+
1363
+ try {
1364
+ await processDir(cwd)
1365
+ spinner.stop(`Port updated from ${oldPort} to ${newPort}`)
1366
+ } catch (error) {
1367
+ spinner.stop('Port replacement failed')
1368
+ showError('Failed to replace port. You may need to update manually.')
1369
+ throw error
1370
+ }
1371
+ }
1372
+
1373
+ // State management helpers
1374
+ interface OnboardState {
1375
+ step: 'prerequisites' | 'identity' | 'ports' | 'eject' | 'ci-runners' | 'production'
1376
+ platform?: 'uncloud' | 'sst'
1377
+ timestamp: number
1378
+ }
1379
+
1380
+ function getStatePath(cwd: string): string {
1381
+ return resolve(cwd, 'node_modules/.takeout/onboard-state.json')
1382
+ }
1383
+
1384
+ function saveOnboardState(cwd: string, state: OnboardState): void {
1385
+ const statePath = getStatePath(cwd)
1386
+ const stateDir = resolve(cwd, 'node_modules/.takeout')
1387
+
1388
+ if (!existsSync(stateDir)) {
1389
+ mkdirSync(stateDir, { recursive: true })
1390
+ }
1391
+
1392
+ writeFileSync(statePath, JSON.stringify(state, null, 2))
1393
+ }
1394
+
1395
+ function loadOnboardState(cwd: string): OnboardState | null {
1396
+ const statePath = getStatePath(cwd)
1397
+
1398
+ if (!existsSync(statePath)) {
1399
+ return null
1400
+ }
1401
+
1402
+ try {
1403
+ const content = readFileSync(statePath, 'utf-8')
1404
+ return JSON.parse(content)
1405
+ } catch {
1406
+ return null
1407
+ }
1408
+ }
1409
+
1410
+ function clearOnboardState(cwd: string): void {
1411
+ const statePath = getStatePath(cwd)
1412
+
1413
+ if (existsSync(statePath)) {
1414
+ try {
1415
+ unlinkSync(statePath)
1416
+ } catch {
1417
+ // ignore errors
1418
+ }
1419
+ }
1420
+ }