diff --git a/BUILDING.md b/BUILDING.md index 4f03b4cc..2acdb7a0 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -75,11 +75,13 @@ npm run build:web:docker:prod # Docker production build All web build commands use the `./scripts/build-web.sh` script, which provides: **Build Modes:** + - **Development**: Starts Vite dev server with hot reload (default) - **Test**: Optimized for testing with minimal minification - **Production**: Optimized for production with full minification **Script Features:** + - **Environment Validation**: Checks for Node.js, npm, npx, package.json - **Environment Setup**: Loads `.env` files based on build mode - **Clean Build**: Removes previous `dist/` directory @@ -88,6 +90,7 @@ All web build commands use the `./scripts/build-web.sh` script, which provides: - **Local Serving**: Built-in HTTP server for testing builds **Direct Script Usage:** + ```bash # Direct script usage (no npm chaining) ./scripts/build-web.sh # Development build @@ -325,17 +328,20 @@ npm run build:electron:dmg:prod ### Single Instance Enforcement The Electron app enforces single-instance operation to prevent: + - Database corruption from multiple instances - Resource conflicts and performance issues - User confusion from multiple windows **Behavior:** + - Only one instance can run at a time - Attempting to launch a second instance shows a user-friendly dialog - The existing window is focused and restored if minimized - Second instance exits gracefully **Implementation:** + - Uses Electron's `requestSingleInstanceLock()` API - Handles `second-instance` events to focus existing window - Shows informative dialog explaining why only one instance is allowed @@ -362,21 +368,25 @@ The Electron build process follows a multi-stage approach: ``` **Stage 1: Web Build** + - Vite builds web assets with Electron-specific configuration - Environment variables loaded based on build mode - Assets optimized for desktop application **Stage 2: Capacitor Sync** + - Copies web assets to Electron app directory - Syncs Capacitor configuration and plugins - Prepares native module bindings **Stage 3: TypeScript Compile** + - Compiles Electron main process TypeScript - Rebuilds native modules for target platform - Generates production-ready JavaScript **Stage 4: Package Creation** + - Creates platform-specific installers - Generates distribution packages - Signs applications (when configured) @@ -388,6 +398,7 @@ The Electron build process follows a multi-stage approach: **Purpose**: Local development and testing **Command**: `npm run build:electron:dev` **Features**: + - Hot reload enabled - Debug tools available - Development logging @@ -398,6 +409,7 @@ The Electron build process follows a multi-stage approach: **Purpose**: Staging and testing environments **Command**: `npm run build:electron -- --mode test` **Features**: + - Test API endpoints - Staging configurations - Optimized for testing @@ -408,6 +420,7 @@ The Electron build process follows a multi-stage approach: **Purpose**: Production deployment **Command**: `npm run build:electron -- --mode production` **Features**: + - Production optimizations - Code minification - Security hardening @@ -1454,3 +1467,633 @@ electron/ - Service worker injection This architecture ensures consistent builds across all platforms while providing flexibility for platform-specific optimizations and manual quality assurance steps. + +--- + +## Appendix A: Build Scripts Reference + +This appendix provides detailed documentation for all build scripts in the `scripts/` directory. + +### A.1 build-web.sh + +**File**: `scripts/build-web.sh` +**Author**: Matthew Raymer +**Description**: Web build script for TimeSafari application + +**Purpose**: Handles the complete web build process including cleanup, environment setup, Vite build, and optional Docker containerization. + +**Usage**: +```bash +# Direct script usage +./scripts/build-web.sh # Development build +./scripts/build-web.sh --dev # Development build (explicit) +./scripts/build-web.sh --test # Test environment build +./scripts/build-web.sh --prod # Production environment build +./scripts/build-web.sh --docker # Build with Docker containerization +./scripts/build-web.sh --docker:test # Test environment + Docker +./scripts/build-web.sh --docker:prod # Production environment + Docker +./scripts/build-web.sh --serve # Build and serve locally +./scripts/build-web.sh --help # Show help +./scripts/build-web.sh --verbose # Enable verbose logging + +# NPM Script Equivalents +npm run build:web # Development build +npm run build:web:test # Test environment build +npm run build:web:prod # Production environment build +npm run build:web:docker # Docker build +npm run build:web:docker:test # Test Docker build +npm run build:web:docker:prod # Production Docker build +``` + +**Build Modes**: +- **Development**: Starts Vite dev server with hot reload (default) +- **Test**: Optimized for testing with minimal minification +- **Production**: Optimized for production with full minification + +**Script Features**: +- **Environment Validation**: Checks for Node.js, npm, npx, package.json +- **Environment Setup**: Loads `.env` files based on build mode +- **Clean Build**: Removes previous `dist/` directory +- **Vite Build**: Executes `npx vite build --config vite.config.web.mts` +- **Docker Support**: Optional Docker containerization +- **Local Serving**: Built-in HTTP server for testing builds + +**Exit Codes**: +- `1` - Web cleanup failed +- `2` - Environment setup failed +- `3` - Vite build failed +- `4` - Docker build failed +- `5` - Serve command failed +- `6` - Invalid build mode + +### A.2 build-electron.sh + +**File**: `scripts/build-electron.sh` +**Author**: Matthew Raymer +**Description**: Clean, modular Electron build script for TimeSafari application + +**Purpose**: Handles Electron builds with proper separation of concerns and no command chaining, following DRY principles. + +**Usage**: +```bash +# Direct script usage +./scripts/build-electron.sh # Development build (runs app) +./scripts/build-electron.sh --dev # Development build (runs app) +./scripts/build-electron.sh --test # Test environment build +./scripts/build-electron.sh --prod # Production environment build +./scripts/build-electron.sh --windows # Windows build +./scripts/build-electron.sh --mac # macOS build +./scripts/build-electron.sh --linux # Linux build +./scripts/build-electron.sh --appimage # Linux AppImage +./scripts/build-electron.sh --deb # Debian package +./scripts/build-electron.sh --dmg # macOS DMG +./scripts/build-electron.sh --help # Show help +./scripts/build-electron.sh --verbose # Enable verbose logging + +# Examples +./scripts/build-electron.sh --prod --windows # Windows production build +./scripts/build-electron.sh --test --appimage # Linux AppImage test build +./scripts/build-electron.sh --dev --mac # macOS development build +``` + +**Build Modes**: +- **Development**: Development build (runs app) +- **Test**: Test environment build +- **Production**: Production environment build +- **Clean**: Clean Electron build artifacts only + +**Platforms**: +- **Windows**: Windows build +- **macOS**: macOS build +- **Linux**: Linux build + +**Packages**: +- **AppImage**: Linux AppImage +- **Deb**: Debian package +- **DMG**: macOS DMG + +**Exit Codes**: +- `1` - Invalid arguments +- `2` - Electron cleanup failed +- `3` - Web build failed +- `4` - Capacitor sync failed +- `5` - TypeScript compilation failed +- `6` - Electron packaging failed +- `7` - Asset generation failed +- `8` - Electron app launch failed + +### A.3 build-android.sh + +**File**: `scripts/build-android.sh` +**Author**: Matthew Raymer +**Date**: 2025-07-11 +**Description**: Android build script for TimeSafari application + +**Purpose**: Handles the complete Android build process including cleanup, web build, Capacitor build, Gradle build, and Android Studio launch. + +**Usage**: +```bash +# Direct script usage +./scripts/build-android.sh [options] + +# Options +--dev, --development Build for development environment +--test Build for testing environment +--prod, --production Build for production environment +--debug Build debug APK +--release Build release APK +--studio Open Android Studio after build +--apk Build APK file +--aab Build AAB (Android App Bundle) +--clean Clean build artifacts only +--sync Sync Capacitor only +--assets Generate assets only +--deploy Deploy APK to connected device +-h, --help Show this help message +-v, --verbose Enable verbose logging + +# Examples +./scripts/build-android.sh --dev --studio # Development build + open studio +./scripts/build-android.sh --prod --apk # Production APK build +./scripts/build-android.sh --test --aab # Testing AAB build +./scripts/build-android.sh --clean # Clean only +./scripts/build-android.sh --sync # Sync only +``` + +**Build Modes**: +- **Development**: Build for development environment +- **Test**: Build for testing environment +- **Production**: Build for production environment + +**Build Types**: +- **Debug**: Build debug APK (default) +- **Release**: Build release APK + +**Exit Codes**: +- `1` - Android cleanup failed +- `2` - Web build failed +- `3` - Capacitor build failed +- `4` - Gradle clean failed +- `5` - Gradle assemble failed +- `6` - Capacitor sync failed +- `7` - Asset generation failed +- `8` - Android Studio launch failed +- `9` - Resource check failed + +### A.4 build-ios.sh + +**File**: `scripts/build-ios.sh` +**Author**: Matthew Raymer +**Date**: 2025-07-11 +**Description**: iOS build script for TimeSafari application + +**Purpose**: Handles the complete iOS build process including cleanup, web build, Capacitor build, Xcode build, and iOS Simulator launch. + +**Usage**: +```bash +# Direct script usage +./scripts/build-ios.sh [options] + +# Options +--dev, --development Build for development environment +--test Build for testing environment +--prod, --production Build for production environment +--debug Build debug app (default) +--release Build release app +--studio Open Xcode after build +--ipa Build IPA file +--app Build app bundle +--clean Clean build artifacts only +--sync Sync Capacitor only +--assets Generate assets only +--deploy Deploy app to connected device +--auto-run Auto-run app after build +-h, --help Show this help message +-v, --verbose Enable verbose logging + +# Examples +./scripts/build-ios.sh --dev --studio # Development build + open Xcode +./scripts/build-ios.sh --prod --ipa # Production IPA build +./scripts/build-ios.sh --test --app # Testing app build +./scripts/build-ios.sh --clean # Clean only +./scripts/build-ios.sh --sync # Sync only +``` + +**Build Modes**: +- **Development**: Build for development environment +- **Test**: Build for testing environment +- **Production**: Build for production environment + +**Build Types**: +- **Debug**: Build debug app (default) +- **Release**: Build release app + +**Key Features**: +- **Environment Validation**: Checks for Xcode, iOS Simulator, Capacitor +- **Resource Checking**: Validates app icons, splash screens, Info.plist +- **Clean Build**: Removes Xcode build artifacts and DerivedData +- **Asset Generation**: Creates platform-specific assets +- **Simulator Support**: Launches iOS Simulator for testing + +### A.5 common.sh + +**File**: `scripts/common.sh` +**Author**: Matthew Raymer +**Description**: Common utilities and functions for build scripts + +**Purpose**: Provides shared functionality, logging, environment setup, and utility functions used by all build scripts. + +**Key Functions**: + +**Logging Functions**: +```bash +log_info "message" # Info level logging +log_success "message" # Success level logging +log_warning "message" # Warning level logging +log_error "message" # Error level logging +log_debug "message" # Debug level logging +``` + +**Environment Functions**: +```bash +setup_build_env "platform" # Setup build environment for platform +load_env_file "filename" # Load environment variables from file +print_env_vars "prefix" # Print environment variables with prefix +``` + +**Utility Functions**: +```bash +check_command "command" # Check if command is available +check_file "filename" # Check if file exists +safe_execute "description" "command" # Execute command with error handling +clean_build_artifacts "dir" # Clean build artifacts directory +``` + +**Validation Functions**: +```bash +validate_build_environment # Validate common build environment +setup_app_directories # Setup application directories +print_header "title" # Print formatted header +``` + +## Appendix B: Vite Configuration Files Reference + +This appendix provides detailed documentation for all Vite configuration files. + +### B.1 vite.config.common.mts + +**File**: `vite.config.common.mts` +**Author**: Matthew Raymer +**Description**: Common Vite configuration shared across all platforms + +**Purpose**: Provides base configuration that is extended by platform-specific configs. + +**Key Features**: +- **Platform Detection**: Automatically detects and configures for web/capacitor/electron +- **Environment Setup**: Loads environment variables and sets platform flags +- **Path Aliases**: Configures TypeScript path resolution +- **Build Optimization**: Platform-specific build optimizations +- **Dependency Management**: Handles platform-specific dependencies + +**Configuration Structure**: +```typescript +export async function createBuildConfig(platform: string): Promise { + const appConfig = await loadAppConfig(); + const isCapacitor = platform === "capacitor"; + const isElectron = platform === "electron"; + const isNative = isCapacitor || isElectron; + + return { + base: "/", + plugins: [vue()], + server: { /* CORS and dev server config */ }, + build: { /* Platform-specific build config */ }, + worker: { /* Web worker configuration */ }, + define: { /* Environment variables and flags */ }, + resolve: { /* Path aliases and module resolution */ }, + optimizeDeps: { /* Dependency optimization */ } + }; +} +``` + +**Environment Variables**: +- `VITE_PLATFORM`: Set to platform name (web/capacitor/electron) +- `__IS_MOBILE__`: Boolean flag for mobile platforms +- `__IS_ELECTRON__`: Boolean flag for Electron platform +- `__USE_QR_READER__`: Boolean flag for QR reader availability + +**Path Aliases**: +- `@`: Points to `src/` directory +- `@nostr/tools`: Nostr tools library +- `path`, `fs`, `crypto`: Node.js polyfills for browser + +### B.2 vite.config.web.mts + +**File**: `vite.config.web.mts` +**Author**: Matthew Raymer +**Description**: Vite configuration for web platform with PWA support + +**Purpose**: Configures Vite for web builds with environment-specific optimizations and PWA features. + +**Key Features**: + +- **Environment-Specific Configuration**: Different settings for dev/test/prod +- **PWA Integration**: Progressive Web App support with service worker +- **Build Optimization**: Manual chunk splitting for better caching +- **Source Maps**: Environment-specific source map configuration +- **Caching Strategies**: Production-specific API caching + +**Environment Configurations**: + +**Development Mode**: + +```typescript +{ + build: { + minify: false, + sourcemap: true, + rollupOptions: { output: { manualChunks: undefined } } + }, + define: { + __DEV__: true, + __TEST__: false, + __PROD__: false + } +} +``` + +**Test Mode**: + +```typescript +{ + build: { + minify: false, + sourcemap: true, + rollupOptions: { output: { manualChunks: undefined } } + }, + define: { + __DEV__: false, + __TEST__: true, + __PROD__: false + } +} +``` + +**Production Mode**: + +```typescript +{ + build: { + minify: 'terser', + sourcemap: false, + rollupOptions: { + output: { + manualChunks: { + vendor: ['vue', 'vue-router', 'pinia'], + utils: ['luxon', 'ramda', 'zod'], + crypto: ['@ethersproject/wallet', '@ethersproject/hdnode'], + sql: ['@jlongster/sql.js', 'absurd-sql'] + } + } + } + }, + define: { + __DEV__: false, + __TEST__: false, + __PROD__: true + } +} +``` + +**PWA Configuration**: + +```typescript +VitePWA({ + registerType: 'autoUpdate', + manifest: appConfig.pwaConfig?.manifest, + devOptions: { enabled: true, type: 'classic' }, + workbox: { + cleanupOutdatedCaches: true, + skipWaiting: true, + clientsClaim: true, + sourcemap: mode !== 'production', + maximumFileSizeToCacheInBytes: 10 * 1024 * 1024, + runtimeCaching: mode === 'production' ? [/* API caching */] : [] + } +}) +``` + +### B.3 vite.config.electron.mts + +**File**: `vite.config.electron.mts` +**Author**: Matthew Raymer +**Description**: Vite configuration for Electron desktop platform + +**Purpose**: Configures Vite for Electron builds with desktop-specific optimizations and native module support. + +**Key Features**: + +- **Electron-Specific Entry Point**: Uses `main.electron.ts` instead of `main.web.ts` +- **Native Module Support**: Handles Electron-specific dependencies +- **Desktop Optimizations**: Larger chunk sizes and desktop-specific settings +- **Source Map Suppression**: Prevents DevTools warnings for external modules +- **External Dependencies**: Properly handles Electron and native modules + +**Configuration Structure**: + +```typescript +export default defineConfig(async () => { + const baseConfig = await createBuildConfig("electron"); + + return { + ...baseConfig, + plugins: [ + // Electron entry point replacement + // Source map suppression + // External module handling + ], + build: { + outDir: "dist", + sourcemap: false, + target: "node16", + chunkSizeWarningLimit: 2000, + rollupOptions: { + external: ["electron", "@capacitor-community/electron"], + output: { + manualChunks: { + vendor: ["vue", "vue-router", "@vueuse/core"], + crypto: ["@nostr/tools", "crypto-js"], + ui: ["@fortawesome/vue-fontawesome"] + } + } + } + }, + define: { + '__ELECTRON__': JSON.stringify(true), + '__IS_DESKTOP__': JSON.stringify(true), + '__USE_NATIVE_SQLITE__': JSON.stringify(true) + } + }; +}); +``` + +**Plugins**: + +- **electron-entry-point**: Replaces main entry point for Electron +- **electron-config**: Handles Electron-specific configurations +- **suppress-source-maps**: Suppresses source map loading errors + +**External Dependencies**: + +- `electron`: Electron runtime +- `@capacitor-community/electron`: Capacitor Electron plugin +- `better-sqlite3-multiple-ciphers`: Native SQLite module + +### B.4 vite.config.capacitor.mts + +**File**: `vite.config.capacitor.mts` +**Author**: Matthew Raymer +**Description**: Vite configuration for Capacitor mobile platform + +**Purpose**: Provides minimal configuration for Capacitor builds, inheriting from common config. + +**Configuration**: + +```typescript +import { defineConfig } from "vite"; +import { createBuildConfig } from "./vite.config.common.mts"; + +export default defineConfig(async () => createBuildConfig('capacitor')); +``` + +**Key Features**: + +- **Minimal Configuration**: Inherits all settings from common config +- **Mobile Platform**: Automatically configures for mobile-specific settings +- **PWA Disabled**: Progressive Web App features disabled for native apps +- **Native Dependencies**: Handles Capacitor-specific dependencies + +### B.5 vite.config.utils.mts + +**File**: `vite.config.utils.mts` +**Author**: Matthew Raymer +**Description**: Utility functions for Vite configuration + +**Purpose**: Provides shared configuration loading and PWA manifest generation. + +**Key Functions**: + +**loadPackageJson()**: Loads and parses package.json for app configuration + +**loadAppConfig()**: Loads complete application configuration including PWA settings + +**PWA Configuration**: +```typescript +interface PWAConfig { + registerType: string; + strategies: string; + srcDir: string; + filename: string; + manifest: { + name: string; + short_name: string; + theme_color: string; + background_color: string; + icons: ManifestIcon[]; + share_target: ShareTarget; + }; +} +``` + +**Manifest Icons**: +- Android Chrome 192x192 PNG +- Android Chrome 512x512 PNG +- Maskable icons for adaptive UI + +**Share Target Configuration**: +```typescript +share_target: { + action: "/share-target", + method: "POST", + enctype: "multipart/form-data", + params: { + files: [{ name: "photo", accept: ["image/*"] }] + } +} +``` + +**Alias Configuration**: + +- `@`: Source directory alias +- `buffer`: Buffer polyfill +- `dexie-export-import`: Database import/export utilities + +### B.6 Additional Vite Configurations + +**vite.config.ts**: Legacy configuration file (minimal) +**vite.config.mts**: Main configuration entry point +**vite.config.dev.mts**: Development-specific configuration +**vite.config.optimized.mts**: Optimized build configuration + +## Appendix C: Build Script Integration + +### C.1 Script Dependencies + +All build scripts depend on `scripts/common.sh` for shared functionality: + +```bash +# Source common utilities in all build scripts +source "$(dirname "$0")/common.sh" +``` + +### C.2 Environment Variable Flow + +1. **Script Level**: Build scripts set `BUILD_MODE` and `NODE_ENV` +2. **Vite Level**: Vite configs read environment variables and set `define` values +3. **Application Level**: Vue components access environment via `import.meta.env` + +### C.3 Build Process Flow + +**Web Build**: +``` +build-web.sh → vite.config.web.mts → dist/ +``` + +**Electron Build**: +``` +build-electron.sh → vite.config.electron.mts → electron/app/ +``` + +**Mobile Build**: +``` +build-android.sh/build-ios.sh → vite.config.capacitor.mts → android/ios/ +``` + +### C.4 Error Handling + +All scripts use consistent error handling: +- Exit codes for different failure types +- Verbose logging with `--verbose` flag +- Safe command execution with `safe_execute()` +- Environment validation before builds + +### C.5 Platform-Specific Considerations + +**Web Platform**: +- PWA features enabled +- Service worker injection +- Browser-specific optimizations + +**Electron Platform**: +- Native module support +- Desktop-specific entry points +- Source map suppression + +**Mobile Platform**: +- Capacitor integration +- Native asset generation +- Platform-specific builds + +--- + +**Note**: This documentation is maintained alongside the build system. For the most up-to-date information, refer to the actual script files and Vite configuration files in the repository.