bagsy/scripts/deploy.ts

407 lines
11 KiB
JavaScript

#!/usr/bin/env node
/**
* ShopList Deployment Wizard
* Interactive CLI to deploy backend and help install frontend
*
* Usage: bun run scripts/deploy.ts
*/
import * as fs from 'fs';
import * as path from 'path';
import { createInterface } from 'readline';
import { exec } from 'child_process';
import { promisify } from 'util';
const execAsync = promisify(exec);
const rl = createInterface({
input: process.stdin,
output: process.stdout,
});
const question = (query: string): Promise<string> => {
return new Promise((resolve) => {
rl.question(query, resolve);
});
};
interface DeploymentConfig {
environment: 'development' | 'staging' | 'production';
region: string;
domain?: string;
betterAuthSecret?: string;
openrouterApiKey?: string;
databaseName: string;
redisCacheEnabled: boolean;
}
async function checkPrerequisites() {
console.log('\n🔍 Checking prerequisites...\n');
const checks = [
{ name: 'bun', command: 'bun --version' },
{ name: 'aws', command: 'aws --version' },
{ name: 'docker', command: 'docker --version' },
{ name: 'git', command: 'git --version' },
];
for (const check of checks) {
try {
await execAsync(check.command);
console.log(`✅ ${check.name} is installed`);
} catch {
console.log(`❌ ${check.name} is NOT installed`);
console.log(` Install from: https://docs.${check.name}.io/install`);
}
}
}
async function promptDeploymentConfig(): Promise<DeploymentConfig> {
console.log('\n🚀 ShopList Deployment Wizard\n');
console.log('This wizard will help you deploy the backend to AWS using SST.\n');
const environment = (await question(
'Environment (development/staging/production) [development]: '
)) as 'development' | 'staging' | 'production' | '';
const region = (await question('AWS Region [us-east-1]: ')) || 'us-east-1';
const domain = await question('Custom domain (optional, press Enter to skip): ');
const redisCacheEnabled = (await question('Enable Redis caching? (y/n) [y]: ')) !== 'n';
const databaseName = (await question('Database name [shoplist]: ')) || 'shoplist';
console.log('\n📝 Secrets Setup\n');
console.log('These will be stored securely in AWS Secrets Manager.\n');
let betterAuthSecret: string | undefined;
let openrouterApiKey: string | undefined;
const generateSecret = (await question('Generate new BETTER_AUTH_SECRET? (y/n) [y]: ')) !== 'n';
if (generateSecret) {
console.log('Generating BETTER_AUTH_SECRET...');
betterAuthSecret = Buffer.from(Math.random().toString()).toString('base64').slice(0, 32);
console.log(`✅ Generated: ${betterAuthSecret.slice(0, 8)}...`);
} else {
betterAuthSecret = await question('Enter BETTER_AUTH_SECRET: ');
}
const hasOpenRouter =
(await question('Do you have an OpenRouter API key for AI suggestions? (y/n) [n]: ')) === 'y';
if (hasOpenRouter) {
openrouterApiKey = await question('Enter OPENROUTER_API_KEY (paste and press Enter): ');
}
return {
environment: environment || 'development',
region,
domain: domain || undefined,
betterAuthSecret,
openrouterApiKey,
databaseName,
redisCacheEnabled,
};
}
async function createEnvironmentFile(config: DeploymentConfig) {
console.log('\n📝 Creating environment file...\n');
const envContent = `# ShopList Backend Environment
# Generated by deployment wizard at ${new Date().toISOString()}
# Deployment
ENVIRONMENT=${config.environment}
AWS_REGION=${config.region}
${config.domain ? `DOMAIN=${config.domain}` : ''}
# Database
DATABASE_NAME=${config.databaseName}
DATABASE_POOL_SIZE=10
# Auth
BETTER_AUTH_SECRET=${config.betterAuthSecret}
BETTER_AUTH_URL=https://${config.domain || 'api.shoplist.local'}
# AI
${config.openrouterApiKey ? `OPENROUTER_API_KEY=${config.openrouterApiKey}` : 'OPENROUTER_API_KEY=your_key_here'}
# Redis
REDIS_CACHE_ENABLED=${config.redisCacheEnabled}
# Node
NODE_ENV=production
LOG_LEVEL=info
`;
fs.writeFileSync(path.join(process.cwd(), 'apps/api/.env.production'), envContent);
console.log('✅ Created apps/api/.env.production');
// Also create secrets.json for SST
const secrets = {
BETTER_AUTH_SECRET: config.betterAuthSecret,
OPENROUTER_API_KEY: config.openrouterApiKey || '',
};
fs.writeFileSync(path.join(process.cwd(), '.sst/secrets.json'), JSON.stringify(secrets, null, 2));
console.log('✅ Created .sst/secrets.json\n');
}
async function setupAWS() {
console.log('🔐 AWS Setup\n');
const hasAWSCreds =
(await question('Do you have AWS credentials configured? (y/n) [y]: ')) !== 'n';
if (!hasAWSCreds) {
console.log(`
❌ AWS credentials not found. To configure:
1. Create AWS account at https://aws.amazon.com
2. Create IAM user with programmatic access
3. Run: aws configure
4. Enter your access key, secret key, and region
Then run this wizard again.
`);
process.exit(1);
}
console.log('✅ AWS credentials found\n');
}
async function deployBackend() {
console.log('🚀 Deploying backend with SST...\n');
try {
console.log('Building backend...');
await execAsync('bun run build', { cwd: path.join(process.cwd(), 'apps/api') });
console.log('Starting SST deployment...');
const { stdout } = await execAsync('bunx sst deploy --stage prod', {
cwd: process.cwd(),
timeout: 600000, // 10 minutes
});
console.log(stdout);
console.log('\n✅ Backend deployed successfully!\n');
// Extract and save outputs
const outputsMatch = stdout.match(/Outputs:\n([\s\S]*?)(?:\n\n|$)/);
if (outputsMatch) {
const outputs = outputsMatch[1];
fs.writeFileSync(path.join(process.cwd(), '.deployment/outputs.txt'), outputs);
console.log('📄 Outputs saved to .deployment/outputs.txt\n');
}
return true;
} catch (err) {
console.error('❌ Deployment failed:', err);
return false;
}
}
async function getMobileSetupInfo() {
console.log('\n📱 Frontend (Mobile App) Setup\n');
const iosDeploy = await question('Deploy iOS? (y/n) [y]: ');
const androidDeploy = await question('Deploy Android? (y/n) [y]: ');
return {
ios: iosDeploy !== 'n',
android: androidDeploy !== 'n',
};
}
async function setupMobileApp(config: { ios: boolean; android: boolean }) {
console.log('\n📱 Setting up mobile app...\n');
// Create mobile environment file
const mobileEnvContent = `# ShopList Mobile Environment
# Generated by deployment wizard at ${new Date().toISOString()}
# API
EXPO_PUBLIC_API_URL=https://api.shoplist.local
# App
EXPO_PUBLIC_APP_NAME=ShopList
EXPO_PUBLIC_VERSION=1.0.0
# Environment
NODE_ENV=production
`;
fs.writeFileSync(path.join(process.cwd(), 'apps/mobile/.env.production'), mobileEnvContent);
console.log('✅ Created apps/mobile/.env.production\n');
if (config.ios) {
console.log('📱 iOS Setup Instructions:');
console.log(`
1. Install EAS CLI:
npm install -g eas-cli
2. Build iOS:
cd apps/mobile
eas build --platform ios --auto-submit
3. Or for TestFlight (recommended):
eas build --platform ios
# Then submit manually to TestFlight
4. Share TestFlight link with family
`);
}
if (config.android) {
console.log('🤖 Android Setup Instructions:');
console.log(`
1. Install EAS CLI:
npm install -g eas-cli
2. Build Android:
cd apps/mobile
eas build --platform android
3. Share APK link with family for sideload
`);
}
}
async function createDeploymentChecklist() {
console.log('\n📋 Deployment Checklist\n');
const checklist = `# ShopList Deployment Checklist
## Pre-Deployment
- [ ] AWS account created and credentials configured
- [ ] GitHub repository created for source control
- [ ] Domain registered (if using custom domain)
- [ ] OpenRouter API key obtained (for AI features)
## Backend Deployment
- [ ] Environment variables configured
- [ ] Database migrations tested locally
- [ ] API endpoints tested with curl/Postman
- [ ] WebSocket tested with multiple connections
- [ ] Error logging verified
## Backend Post-Deployment
- [ ] Check CloudWatch logs for errors
- [ ] Database connection verified
- [ ] API endpoint responding
- [ ] WebSocket endpoint accessible
- [ ] Secrets stored in AWS Secrets Manager
## Frontend Deployment (iOS)
- [ ] EAS CLI installed
- [ ] Apple ID created
- [ ] Provisioning profiles configured
- [ ] Build artifact generated
- [ ] TestFlight invites sent to family
## Frontend Deployment (Android)
- [ ] Google Play Developer account created
- [ ] App signing key generated
- [ ] Build artifact generated
- [ ] APK sideload link generated
## Post-Launch
- [ ] Monitor CloudWatch metrics
- [ ] Check error logs regularly
- [ ] Gather family feedback
- [ ] Plan feature updates
- [ ] Schedule database backups
## Troubleshooting
- [ ] WebSocket connection issues documented
- [ ] Database performance baseline established
- [ ] API rate limits configured
- [ ] Error recovery procedures documented
`;
fs.writeFileSync(path.join(process.cwd(), '.deployment/CHECKLIST.md'), checklist);
console.log('✅ Created .deployment/CHECKLIST.md\n');
}
async function saveDeploymentConfig(config: DeploymentConfig) {
console.log('💾 Saving deployment configuration...\n');
// Ensure directory exists
if (!fs.existsSync('.deployment')) {
fs.mkdirSync('.deployment', { recursive: true });
}
// Save config (without secrets)
const safeConfig = {
...config,
betterAuthSecret: '***',
openrouterApiKey: '***',
};
fs.writeFileSync(
path.join(process.cwd(), '.deployment/config.json'),
JSON.stringify(safeConfig, null, 2)
);
console.log('✅ Configuration saved to .deployment/config.json\n');
}
async function runWizard() {
try {
console.clear();
// Check prerequisites
await checkPrerequisites();
// Prompt for configuration
const config = await promptDeploymentConfig();
// Setup AWS
await setupAWS();
// Create environment files
await createEnvironmentFile(config);
// Save configuration
await saveDeploymentConfig(config);
// Deploy backend
const deploySuccess = await deployBackend();
if (!deploySuccess) {
console.log('Deployment failed. Please check the errors above.');
process.exit(1);
}
// Setup mobile
const mobileConfig = await getMobileSetupInfo();
await setupMobileApp(mobileConfig);
// Create checklist
await createDeploymentChecklist();
// Final summary
console.log('\n🎉 Deployment Wizard Complete!\n');
console.log('📝 Next Steps:');
console.log('1. Review .deployment/config.json');
console.log('2. Follow iOS/Android setup instructions above');
console.log('3. Test backend API with: curl https://your-domain/api/health');
console.log('4. Check logs: bunx sst logs --stage prod');
console.log('5. Share TestFlight/APK link with family');
console.log('\n📚 Documentation:');
console.log('- Backend: docs/BACKEND_SETUP.md');
console.log('- Deployment: DEPLOYMENT_GUIDE.md');
console.log('- iOS Sideload: docs/iOS_SIDELOADING_GUIDE.md\n');
rl.close();
} catch (err) {
console.error('Error:', err);
rl.close();
process.exit(1);
}
}
// Run the wizard
runWizard();