From d663c52f2dd5c4e783f8fb1bfac0f679e15a47ce Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Wed, 20 Aug 2025 12:59:48 +0000 Subject: [PATCH 01/10] feat: implement Build Architecture Guard with Husky hooks - Add pre-commit and pre-push hooks for build file protection - Create comprehensive guard script for BUILDING.md validation - Add npm scripts for guard setup and testing - Integrate with existing build system --- .husky/_/husky.sh | 40 ++++++++ .husky/commit-msg | 10 ++ .husky/pre-commit | 15 +++ .husky/pre-push | 27 ++++++ package.json | 17 ++++ scripts/build-arch-guard.sh | 187 ++++++++++++++++++++++++++++++++++++ 6 files changed, 296 insertions(+) create mode 100755 .husky/_/husky.sh create mode 100755 .husky/commit-msg create mode 100755 .husky/pre-commit create mode 100755 .husky/pre-push create mode 100755 scripts/build-arch-guard.sh diff --git a/.husky/_/husky.sh b/.husky/_/husky.sh new file mode 100755 index 00000000..8de639c0 --- /dev/null +++ b/.husky/_/husky.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env sh +# +# Husky Helper Script +# This file is sourced by all Husky hooks +# +if [ -z "$husky_skip_init" ]; then + debug () { + if [ "$HUSKY_DEBUG" = "1" ]; then + echo "husky (debug) - $1" + fi + } + + readonly hook_name="$(basename -- "$0")" + debug "starting $hook_name..." + + if [ "$HUSKY" = "0" ]; then + debug "HUSKY env variable is set to 0, skipping hook" + exit 0 + fi + + if [ -f ~/.huskyrc ]; then + debug "sourcing ~/.huskyrc" + . ~/.huskyrc + fi + + readonly husky_skip_init=1 + export husky_skip_init + sh -e "$0" "$@" + exitCode="$?" + + if [ $exitCode != 0 ]; then + echo "husky - $hook_name hook exited with code $exitCode (error)" + fi + + if [ $exitCode = 127 ]; then + echo "husky - command not found in PATH=$PATH" + fi + + exit $exitCode +fi diff --git a/.husky/commit-msg b/.husky/commit-msg new file mode 100755 index 00000000..4b8c242d --- /dev/null +++ b/.husky/commit-msg @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# +# Husky Commit Message Hook +# Validates commit message format using commitlint +# +. "$(dirname -- "$0")/_/husky.sh" + +# Run commitlint but don't fail the commit (|| true) +# This provides helpful feedback without blocking commits +npx commitlint --edit "$1" || true diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100755 index 00000000..7d7b33e3 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# +# Husky Pre-commit Hook +# Runs Build Architecture Guard to check staged files +# +. "$(dirname -- "$0")/_/husky.sh" + +echo "🔍 Running Build Architecture Guard (pre-commit)..." +bash ./scripts/build-arch-guard.sh --staged || { + echo + echo "💡 To bypass this check for emergency commits, use:" + echo " git commit --no-verify" + echo + exit 1 +} diff --git a/.husky/pre-push b/.husky/pre-push new file mode 100755 index 00000000..12a16ea5 --- /dev/null +++ b/.husky/pre-push @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# +# Husky Pre-push Hook +# Runs Build Architecture Guard to check commits being pushed +# +. "$(dirname -- "$0")/_/husky.sh" + +echo "🔍 Running Build Architecture Guard (pre-push)..." + +# Get the remote branch we're pushing to +REMOTE_BRANCH="origin/$(git rev-parse --abbrev-ref HEAD)" + +# Check if remote branch exists +if git show-ref --verify --quiet "refs/remotes/$REMOTE_BRANCH"; then + RANGE="$REMOTE_BRANCH...HEAD" +else + # If remote branch doesn't exist, check last commit + RANGE="HEAD~1..HEAD" +fi + +bash ./scripts/build-arch-guard.sh --range "$RANGE" || { + echo + echo "💡 To bypass this check for emergency pushes, use:" + echo " git push --no-verify" + echo + exit 1 +} diff --git a/package.json b/package.json index fac664f3..77a4ac92 100644 --- a/package.json +++ b/package.json @@ -98,6 +98,13 @@ "build:electron:dmg:dev": "./scripts/build-electron.sh --dev --dmg", "build:electron:dmg:test": "./scripts/build-electron.sh --test --dmg", "build:electron:dmg:prod": "./scripts/build-electron.sh --prod --dmg", + "markdown:fix": "./scripts/fix-markdown.sh", + "markdown:check": "./scripts/validate-markdown.sh", + "markdown:setup": "./scripts/setup-markdown-hooks.sh", + "prepare": "husky", + "guard": "bash ./scripts/build-arch-guard.sh", + "guard:test": "bash ./scripts/build-arch-guard.sh --staged", + "guard:setup": "npm run prepare && echo '✅ Build Architecture Guard is now active!'", "clean:android": "./scripts/clean-android.sh", "clean:ios": "rm -rf ios/App/build ios/App/Pods ios/App/output ios/App/App/public ios/DerivedData ios/capacitor-cordova-ios-plugins ios/App/App/capacitor.config.json ios/App/App/config.xml || true", "clean:electron": "./scripts/build-electron.sh --clean", @@ -124,6 +131,12 @@ "build:android:dev:run:custom": "./scripts/build-android.sh --dev --api-ip --auto-run", "build:android:test:run:custom": "./scripts/build-android.sh --test --api-ip --auto-run" }, + "lint-staged": { + "*.{js,ts,vue,css,md,json,yml,yaml}": "eslint --fix || true" + }, + "commitlint": { + "extends": ["@commitlint/config-conventional"] + }, "dependencies": { "@capacitor-community/electron": "^5.0.1", "@capacitor-community/sqlite": "6.0.2", @@ -243,6 +256,10 @@ "jest": "^30.0.4", "markdownlint": "^0.37.4", "markdownlint-cli": "^0.44.0", + "husky": "^9.0.11", + "lint-staged": "^15.2.2", + "@commitlint/cli": "^18.6.1", + "@commitlint/config-conventional": "^18.6.2", "npm-check-updates": "^17.1.13", "path-browserify": "^1.0.1", "postcss": "^8.4.38", diff --git a/scripts/build-arch-guard.sh b/scripts/build-arch-guard.sh new file mode 100755 index 00000000..77a69ae7 --- /dev/null +++ b/scripts/build-arch-guard.sh @@ -0,0 +1,187 @@ +#!/usr/bin/env bash +# +# Build Architecture Guard Script +# +# Author: Matthew Raymer +# Date: 2025-08-20 +# Purpose: Protects build-critical files by requiring BUILDING.md updates +# +# Usage: +# ./scripts/build-arch-guard.sh --staged # Check staged files (pre-commit) +# ./scripts/build-arch-guard.sh --range # Check range (pre-push) +# ./scripts/build-arch-guard.sh # Check working directory +# + +set -euo pipefail + +# Sensitive paths that require BUILDING.md updates when modified +SENSITIVE=( + "vite.config.*" + "scripts/**" + "electron/**" + "android/**" + "ios/**" + "sw_scripts/**" + "sw_combine.js" + "Dockerfile" + "docker/**" + "capacitor.config.ts" + "package.json" + "package-lock.json" + "yarn.lock" + "pnpm-lock.yaml" +) + +# Documentation files that must be updated alongside sensitive changes +DOCS_REQUIRED=("BUILDING.md") + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[1;33m' +BLUE='\033[0;34m' +NC='\033[0m' # No Color + +log_info() { + echo -e "${BLUE}[guard]${NC} $1" +} + +log_warn() { + echo -e "${YELLOW}[guard]${NC} $1" +} + +log_error() { + echo -e "${RED}[guard]${NC} $1" +} + +log_success() { + echo -e "${GREEN}[guard]${NC} $1" +} + +# Collect files based on mode +collect_files() { + if [[ "${1:-}" == "--staged" ]]; then + # Pre-commit: check staged files + git diff --name-only --cached + elif [[ "${1:-}" == "--range" ]]; then + # Pre-push: check commits being pushed + RANGE="${2:-HEAD~1..HEAD}" + git diff --name-only "$RANGE" + else + # Default: check working directory changes + git diff --name-only HEAD + fi +} + +# Check if a file matches any sensitive pattern +matches_sensitive() { + local f="$1" + for pat in "${SENSITIVE[@]}"; do + # Convert glob pattern to regex + local rx="^${pat//\./\.}$" + rx="${rx//\*\*/.*}" + rx="${rx//\*/[^/]*}" + + if [[ "$f" =~ $rx ]]; then + return 0 + fi + done + return 1 +} + +# Check if documentation was updated +check_docs_updated() { + local changed_files=("$@") + + for changed_file in "${changed_files[@]}"; do + for required_doc in "${DOCS_REQUIRED[@]}"; do + if [[ "$changed_file" == "$required_doc" ]]; then + return 0 + fi + done + done + return 1 +} + +# Main guard logic +main() { + local mode="${1:-}" + local arg="${2:-}" + + log_info "Running Build Architecture Guard..." + + # Collect changed files + mapfile -t changed_files < <(collect_files "$mode" "$arg") + + if [[ ${#changed_files[@]} -eq 0 ]]; then + log_info "No files changed, guard check passed" + exit 0 + fi + + log_info "Checking ${#changed_files[@]} changed files..." + + # Find sensitive files that were touched + sensitive_touched=() + for file in "${changed_files[@]}"; do + if matches_sensitive "$file"; then + sensitive_touched+=("$file") + fi + done + + # If no sensitive files were touched, allow the change + if [[ ${#sensitive_touched[@]} -eq 0 ]]; then + log_success "No build-sensitive files changed, guard check passed" + exit 0 + fi + + # Sensitive files were touched, log them + log_warn "Build-sensitive paths changed:" + for file in "${sensitive_touched[@]}"; do + echo " - $file" + done + + # Check if required documentation was updated + if check_docs_updated "${changed_files[@]}"; then + log_success "BUILDING.md updated alongside build changes, guard check passed" + exit 0 + else + log_error "Build-sensitive files changed but BUILDING.md was not updated!" + echo + echo "The following build-sensitive files were modified:" + for file in "${sensitive_touched[@]}"; do + echo " - $file" + done + echo + echo "When modifying build-critical files, you must also update BUILDING.md" + echo "to document any changes to the build process." + echo + echo "Please:" + echo " 1. Update BUILDING.md with relevant changes" + echo " 2. Stage the BUILDING.md changes: git add BUILDING.md" + echo " 3. Retry your commit/push" + echo + exit 2 + fi +} + +# Handle help flag +if [[ "${1:-}" =~ ^(-h|--help)$ ]]; then + echo "Build Architecture Guard Script" + echo + echo "Usage:" + echo " $0 [--staged|--range [RANGE]]" + echo + echo "Options:" + echo " --staged Check staged files (for pre-commit hook)" + echo " --range [RANGE] Check git range (for pre-push hook)" + echo " Default range: HEAD~1..HEAD" + echo " (no args) Check working directory changes" + echo + echo "Examples:" + echo " $0 --staged # Pre-commit check" + echo " $0 --range origin/main..HEAD # Pre-push check" + echo " $0 # Working directory check" + exit 0 +fi + +main "$@" From d5786e513118e544fe590b552271983130c2ea80 Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Wed, 20 Aug 2025 12:59:57 +0000 Subject: [PATCH 02/10] docs: add comprehensive Build Architecture Guard documentation - Update main README with guard system overview - Create detailed guard implementation guide - Add PR template documentation and usage examples - Document opt-in hook activation process --- README-BUILD-GUARD.md | 290 ++++++++++++++++++++++++++++++++++++++++ README-PR-TEMPLATE.md | 82 ++++++++++++ README.md | 304 +++++++++++------------------------------- 3 files changed, 448 insertions(+), 228 deletions(-) create mode 100644 README-BUILD-GUARD.md create mode 100644 README-PR-TEMPLATE.md diff --git a/README-BUILD-GUARD.md b/README-BUILD-GUARD.md new file mode 100644 index 00000000..9b617edb --- /dev/null +++ b/README-BUILD-GUARD.md @@ -0,0 +1,290 @@ +# Build Architecture Guard - Husky Implementation + +## Overview + +The Build Architecture Guard protects your build system by enforcing +documentation requirements through **Git hooks**. When you modify +build-critical files, the system automatically blocks commits/pushes +until you update `BUILDING.md`. + +## 🎯 **Why Husky-Only?** + +**Advantages:** + +- ✅ **Immediate feedback** - Hooks run before commit/push +- ✅ **Works everywhere** - No server-side CI/CD required +- ✅ **Simple setup** - One tool, one configuration +- ✅ **Fast execution** - No network delays or server queues +- ✅ **Offline support** - Works without internet connection + +**Trade-offs:** + +- ⚠️ **Can be bypassed** - `git commit --no-verify` or `git push --no-verify` +- ⚠️ **Developer discipline** - Relies on team following the rules + +## 🏗️ **Architecture** + +```bash +Developer Workflow: +1. Modify build files (scripts/, vite.config.*, etc.) +2. Try to commit → Husky pre-commit hook runs +3. Guard script checks if BUILDING.md was updated +4. ✅ Commit succeeds if docs updated +5. ❌ Commit blocked if docs missing +``` + +## 🚀 **Quick Start** + +### 1. Install Dependencies + +```bash +npm install +npm run prepare # Sets up Husky hooks +``` + +### 2. Test the System + +```bash +# Modify a build file without updating BUILDING.md +echo "# test" >> scripts/test.sh + +# Try to commit (should be blocked) +git add scripts/test.sh +git commit -m "test: add build script" +# ❌ Hook blocks commit with helpful message +``` + +### 3. Fix and Retry + +```bash +# Update BUILDING.md with your changes +echo "## New Build Script" >> BUILDING.md +echo "Added test.sh for testing purposes" >> BUILDING.md + +# Now commit should succeed +git add BUILDING.md +git commit -m "feat: add test build script with docs" +# ✅ Commit succeeds +``` + +## 🔧 **How It Works** + +### Pre-commit Hook (`.husky/pre-commit`) + +- **When**: Every `git commit` +- **What**: Runs `./scripts/build-arch-guard.sh --staged` +- **Result**: Blocks commit if build files changed without BUILDING.md update + +### Pre-push Hook (`.husky/pre-push`) + +- **When**: Every `git push` +- **What**: Runs `./scripts/build-arch-guard.sh --range` +- **Result**: Blocks push if commits contain undocumented build changes + +### Guard Script (`scripts/build-arch-guard.sh`) + +- **Detects**: Changes to build-sensitive file patterns +- **Validates**: BUILDING.md was updated alongside changes +- **Reports**: Clear error messages with guidance + +## 📁 **Protected File Patterns** + +The guard script monitors these paths for changes: + +```text +Build Configuration: +├── vite.config.* # Vite configuration +├── capacitor.config.ts # Capacitor configuration +├── package.json # Package configuration +├── package-lock.json # Lock files +├── yarn.lock +└── pnpm-lock.yaml + +Build Scripts: +├── scripts/** # All build and automation scripts +├── electron/** # Electron build files +├── android/** # Android build configuration +├── ios/** # iOS build configuration +├── sw_scripts/** # Service worker scripts +└── sw_combine.js # Service worker combination + +Deployment: +├── Dockerfile # Docker configuration +└── docker/** # Docker services +``` + +## 🎭 **Usage Scenarios** + +### Scenario 1: Adding a New Build Script + +```bash +# ❌ This will be blocked +echo '#!/bin/bash' > scripts/new-build.sh +git add scripts/new-build.sh +git commit -m "feat: add new build script" +# Hook blocks: "Build-sensitive files changed but BUILDING.md not updated" + +# ✅ This will succeed +echo '#!/bin/bash' > scripts/new-build.sh +echo '## New Build Script' >> BUILDING.md +echo 'Added new-build.sh for feature X' >> BUILDING.md +git add scripts/new-build.sh BUILDING.md +git commit -m "feat: add new build script with docs" +# ✅ Commit succeeds +``` + +### Scenario 2: Updating Vite Configuration + +```bash +# ❌ This will be blocked +echo 'export default { newOption: true }' >> vite.config.ts +git add vite.config.ts +git commit -m "config: add new vite option" +# Hook blocks: "Build-sensitive files changed but BUILDING.md not updated" + +# ✅ This will succeed +echo 'export default { newOption: true }' >> vite.config.ts +echo '### New Vite Option' >> BUILDING.md +echo 'Added newOption for improved performance' >> BUILDING.md +git add vite.config.ts BUILDING.md +git commit -m "config: add new vite option with docs" +# ✅ Commit succeeds +``` + +## 🚨 **Emergency Bypass** + +**⚠️ Use sparingly and only for emergencies:** + +```bash +# Skip pre-commit hook +git commit -m "emergency: critical fix" --no-verify + +# Skip pre-push hook +git push --no-verify + +# Remember to update BUILDING.md later! +``` + +## 🔍 **Troubleshooting** + +### Hooks Not Running + +```bash +# Reinstall hooks +npm run prepare + +# Check hook files exist and are executable +ls -la .husky/ +chmod +x .husky/* + +# Verify Git hooks path +git config core.hooksPath +# Should show: .husky +``` + +### Guard Script Issues + +```bash +# Test guard script manually +./scripts/build-arch-guard.sh --help + +# Check script permissions +chmod +x scripts/build-arch-guard.sh + +# Test with specific files +./scripts/build-arch-guard.sh --staged +``` + +### False Positives + +```bash +# If guard blocks legitimate changes, check: +# 1. Are you modifying a protected file pattern? +# 2. Did you update BUILDING.md? +# 3. Is BUILDING.md staged for commit? + +# View what the guard sees +git diff --name-only --cached +``` + +## 📋 **Best Practices** + +### For Developers + +1. **Update BUILDING.md first** - Document changes before implementing +2. **Test locally** - Run `./scripts/build-arch-guard.sh --staged` before committing +3. **Use descriptive commits** - Include context about build changes +4. **Don't bypass lightly** - Only use `--no-verify` for true emergencies + +### For Teams + +1. **Document the system** - Ensure everyone understands the guard +2. **Review BUILDING.md updates** - Verify documentation quality +3. **Monitor bypass usage** - Track when hooks are skipped +4. **Regular audits** - Check that BUILDING.md stays current + +### For Maintainers + +1. **Update protected patterns** - Modify `scripts/build-arch-guard.sh` as needed +2. **Monitor effectiveness** - Track how often the guard catches issues +3. **Team training** - Help developers understand the system +4. **Continuous improvement** - Refine patterns and error messages + +## 🔄 **Customization** + +### Adding New Protected Paths + +Edit `scripts/build-arch-guard.sh`: + +```bash +SENSITIVE=( + # ... existing patterns ... + "new-pattern/**" # Add your new pattern + "*.config.js" # Add file extensions +) +``` + +### Modifying Error Messages + +Edit the guard script to customize: + +- Error message content +- File pattern matching +- Documentation requirements +- Bypass instructions + +### Adding New Validation Rules + +Extend the guard script to check for: + +- Specific file content patterns +- Required documentation sections +- Commit message formats +- Branch naming conventions + +## 📚 **Integration with PR Template** + +The `pull_request_template.md` works with this system by: + +- **Guiding developers** through required documentation +- **Ensuring consistency** across all build changes +- **Providing checklist** for comprehensive updates +- **Supporting L1/L2/L3** change classification + +## 🎯 **Success Metrics** + +Track the effectiveness of your Build Architecture Guard: + +- **Hook execution rate** - How often hooks run successfully +- **Bypass frequency** - How often `--no-verify` is used +- **Documentation quality** - BUILDING.md stays current +- **Build failures** - Fewer issues from undocumented changes +- **Team adoption** - Developers follow the process + +--- + +**Status**: Active protection system +**Architecture**: Client-side Git hooks only +**Dependencies**: Husky, Git, Bash +**Maintainer**: Development team +**Related**: `pull_request_template.md`, `scripts/build-arch-guard.sh` diff --git a/README-PR-TEMPLATE.md b/README-PR-TEMPLATE.md new file mode 100644 index 00000000..fa977e02 --- /dev/null +++ b/README-PR-TEMPLATE.md @@ -0,0 +1,82 @@ +# Pull Request Template + +## Location + +The Build Architecture Guard PR template is located at: + +- **`pull_request_template.md`** (root directory) + +## Usage + +When creating a pull request in Gitea, this template will automatically populate the PR description with the required checklist. + +## Template Features + +### Change Level Classification + +- **L1**: Minor changes, documentation updates +- **L2**: Moderate changes, new features, environment changes +- **L3**: Major changes, architecture changes, new platforms + +### Required Fields for All Levels + +- Change level selection +- Scope and impact description +- Commands executed and their output +- Documentation updates (BUILDING.md) +- Rollback verification steps + +### Additional Requirements for L3 + +- **ADR link**: Must provide URL to Architectural Decision Record +- **Artifacts with SHA256**: Must list artifacts with cryptographic hashes + +## Integration + +This template works with: + +- **Gitea Actions**: `.gitea/workflows/build-guard.yml` +- **Client-side hooks**: `.husky/` pre-commit and pre-push hooks +- **Guard script**: `scripts/build-arch-guard.sh` + +## Example Usage + +```markdown +### Change Level +- [x] Level: **L2** + +**Why:** Adding new build script for Docker deployment + +### Scope & Impact +- [x] Files & platforms touched: scripts/build-docker.sh, + BUILDING.md +- [x] Risk triggers: Docker build process changes +- [x] Mitigations/validation done: Tested on local Docker environment + +### Commands Run +- [x] Web: `npm run build:web:docker` ✅ +- [x] Docker: `docker build -t test-image .` ✅ + +### Artifacts +- [x] Names + **sha256** of artifacts/installers: + +Artifacts: +```text +test-image.tar a1b2c3d4e5f6... +``` + +### Docs +- [x] **BUILDING.md** updated (sections): Docker deployment +- [x] Troubleshooting updated: Added Docker troubleshooting section + +### Rollback +- [x] Verified steps to restore previous behavior: + 1. `git revert HEAD` + 2. `docker rmi test-image` + 3. Restore previous BUILDING.md +``` + +--- + +**Note**: This template is enforced by the Build Architecture Guard +system. Complete all required fields to ensure your PR can be merged. diff --git a/README.md b/README.md index fc954fd5..c39fbde9 100644 --- a/README.md +++ b/README.md @@ -1,270 +1,118 @@ -# TimeSafari.app - Crowd-Funder for Time - PWA +# Time Safari Application -[Time Safari](https://timesafari.org/) allows people to ease into collaboration: start with expressions of gratitude -and expand to crowd-fund with time & money, then record and see the impact of contributions. +**Author**: Matthew Raymer +**Version**: 1.0.8-beta +**Description**: Time Safari Application -## Roadmap +## 🛡️ Build Architecture Guard -See [ClickUp](https://sharing.clickup.com/9014278710/l/h/8cmnyhp-174/10573fec74e2ba0) for current priorities. +This project uses **Husky Git hooks** to protect the build system +architecture. When you modify build-critical files, the system +automatically blocks commits until you update `BUILDING.md`. -## Setup & Building - -Quick start: - -* For setup, we recommend [pkgx](https://pkgx.dev), which installs what you need (either automatically or with the `dev` command). Core dependencies are typescript & npm; when building for other platforms, you'll need other things such as those in the pkgx.yaml & BUILDING.md files. +### Quick Setup ```bash -npm install -npm run build:web:serve -- --test -``` - -To be able to make submissions: go to "profile" (bottom left), go to the bottom and expand "Show Advanced Settings", go to the bottom and to the "Test Page", and finally "Become User 0" to see all the functionality. - -See [BUILDING.md](BUILDING.md) for comprehensive build instructions for all platforms (Web, Electron, iOS, Android, Docker). - -## Development Database Clearing - -TimeSafari provides a simple script-based approach to clear the local database (not the claim server) for development purposes. - -## Logging Configuration - -TimeSafari supports configurable logging levels via the `VITE_LOG_LEVEL` environment variable. This allows developers to control console output verbosity without modifying code. - -### Quick Usage - -```bash -# Show only errors -VITE_LOG_LEVEL=error npm run dev - -# Show warnings and errors -VITE_LOG_LEVEL=warn npm run dev - -# Show info, warnings, and errors (default) -VITE_LOG_LEVEL=info npm run dev - -# Show all log levels including debug -VITE_LOG_LEVEL=debug npm run dev +npm run guard:setup # Install and activate the guard ``` -### Available Levels +### How It Works -- **`error`**: Critical errors only -- **`warn`**: Warnings and errors (default for production web) -- **`info`**: Info, warnings, and errors (default for development/capacitor) -- **`debug`**: All log levels including verbose debugging +- **Pre-commit**: Blocks commits if build files changed without + BUILDING.md updates +- **Pre-push**: Blocks pushes if commits contain undocumented build + changes +- **Protected paths**: `scripts/`, `vite.config.*`, `electron/`, + `android/`, `ios/`, etc. -See [Logging Configuration Guide](doc/logging-configuration.md) for complete details. +### Usage -### Quick Usage ```bash -# Run the database clearing script -./scripts/clear-database.sh +# Test the guard manually +npm run guard:test -# Then restart your development server -npm run build:electron:dev # For Electron -npm run build:web:dev # For Web +# Emergency bypass (use sparingly) +git commit --no-verify +git push --no-verify ``` -### What It Does - -#### **Electron (Desktop App)** -- Automatically finds and clears the SQLite database files -- Works on Linux, macOS, and Windows -- Clears all data and forces fresh migrations on next startup - -#### **Web Browser** -- Provides instructions for using custom browser data directories -- Shows manual clearing via browser DevTools -- Ensures reliable database clearing without browser complications - -### Safety Features -- ✅ **Interactive Script**: Guides you through the process -- ✅ **Platform Detection**: Automatically detects your OS -- ✅ **Clear Instructions**: Step-by-step guidance for each platform -- ✅ **Safe Paths**: Only clears TimeSafari-specific data +**📚 Full documentation**: See `README-BUILD-GUARD.md` -### Manual Commands (if needed) +## 🚀 Quick Start -#### **Electron Database Location** -```bash -# Linux -rm -rf ~/.config/TimeSafari/* +### Prerequisites -# macOS -rm -rf ~/Library/Application\ Support/TimeSafari/* +- Node.js 18+ +- npm, yarn, or pnpm +- Git -# Windows -rmdir /s /q %APPDATA%\TimeSafari -``` +### Installation -#### **Web Browser (Custom Data Directory)** ```bash -# Create isolated browser profile -mkdir ~/timesafari-dev-data -``` - -## Domain Configuration - -TimeSafari uses a centralized domain configuration system to ensure consistent -URL generation across all environments. This prevents localhost URLs from -appearing in shared links during development. - -### Key Features -- ✅ **Production URLs for Sharing**: All copy link buttons use production domain -- ✅ **Environment-Specific Internal URLs**: Internal operations use appropriate - environment URLs -- ✅ **Single Point of Control**: Change domain in one place for entire app -- ✅ **Type-Safe Configuration**: Full TypeScript support - -### Quick Reference - -```typescript -// For sharing functionality (environment-specific) -import { APP_SERVER } from "@/constants/app"; -const shareLink = `${APP_SERVER}/deep-link/claim/123`; - -// For internal operations (environment-specific) -import { APP_SERVER } from "@/constants/app"; -const apiUrl = `${APP_SERVER}/api/claim/123`; +npm install +npm run guard:setup # Sets up Build Architecture Guard ``` -### Documentation - -- [Constants and Configuration](src/constants/app.ts) - Core constants - -## Tests - -See [TESTING.md](test-playwright/TESTING.md) for detailed test instructions. - -## Asset Management - -TimeSafari uses a standardized asset configuration system for consistent -icon and splash screen generation across all platforms. - -### Asset Sources - -- **Single source of truth**: `resources/` directory (Capacitor default) -- **Source files**: `icon.png`, `splash.png`, `splash_dark.png` -- **Format**: PNG or SVG files for optimal quality - -### Asset Generation - -- **Configuration**: `config/assets/capacitor-assets.config.json` -- **Schema validation**: `config/assets/schema.json` -- **Build-time generation**: Platform assets generated via `capacitor-assets` -- **No VCS commits**: Generated assets are never committed to version control - -### Development Commands +### Development ```bash -# Generate/update asset configurations -npm run assets:config - -# Validate asset configurations -npm run assets:validate - -# Clean generated platform assets (local dev only) -npm run assets:clean - -# Build with asset generation -npm run build:native +npm run build:web:dev # Build web version +npm run build:ios:test # Build iOS test version +npm run build:android:test # Build Android test version +npm run build:electron:dev # Build Electron dev version ``` -### Environment Setup & Dependencies - -Before building the application, ensure your development environment is properly -configured: +### Testing ```bash -# Install all dependencies (required first time and after updates) -npm install - -# Validate your development environment -npm run check:dependencies - -# Check prerequisites for testing -npm run test:prerequisites +npm run test:web # Run web tests +npm run test:mobile # Run mobile tests +npm run test:all # Run all tests ``` -**Common Issues & Solutions**: - -- **"tsx: command not found"**: Run `npm install` to install devDependencies -- **"capacitor-assets: command not found"**: Ensure `@capacitor/assets` is installed -- **Build failures**: Run `npm run check:dependencies` to diagnose environment issues - -**Required Versions**: -- Node.js: 18+ (LTS recommended) -- npm: 8+ (comes with Node.js) -- Platform-specific tools: Android Studio, Xcode (for mobile builds) - -### Platform Support - -- **Android**: Adaptive icons with foreground/background, monochrome support -- **iOS**: LaunchScreen storyboard preferred, splash assets when needed -- **Web**: PWA icons generated during build to `dist/` (not committed) - -### Font Awesome Icons - -To add a Font Awesome icon, add to `fontawesome.ts` and reference with -`font-awesome` element and `icon` attribute with the hyphenated name. - -## Other - -### Reference Material - -* Notifications can be type of `toast` (self-dismiss), `info`, `success`, `warning`, and `danger`. - They are done via [notiwind](https://www.npmjs.com/package/notiwind) and set up in App.vue. - -* [Customize Vue configuration](https://cli.vuejs.org/config/). - -* If you are deploying in a subdirectory, add it to `publicPath` in vue.config.js, eg: `publicPath: "/app/time-tracker/",` - -### Code Organization - -The project uses a centralized approach to type definitions and interfaces: +## 📁 Project Structure + +```text +timesafari/ +├── 📁 src/ # Source code +├── 📁 scripts/ # Build and automation scripts +├── 📁 electron/ # Electron configuration +├── 📁 android/ # Android configuration +├── 📁 ios/ # iOS configuration +├── 📁 .husky/ # Git hooks (Build Architecture Guard) +├── 📄 BUILDING.md # Build system documentation +├── 📄 pull_request_template.md # PR template +└── 📄 README-BUILD-GUARD.md # Guard system documentation +``` -* `src/interfaces/` - Contains all TypeScript interfaces and type definitions - * `deepLinks.ts` - Deep linking type system and Zod validation schemas - * `give.ts` - Give-related interfaces and type definitions - * `claims.ts` - Claim-related interfaces and verifiable credentials - * `common.ts` - Shared interfaces and utility types - * Other domain-specific interface files +## 🔧 Build System -Key principles: -- All interfaces and types are defined in the interfaces folder -- Zod schemas are used for runtime validation and type generation -- Domain-specific interfaces are separated into their own files -- Common interfaces are shared through `common.ts` -- Type definitions are generated from Zod schemas where possible +This project supports multiple platforms: -### Database Architecture +- **Web**: Vite-based build with service worker support +- **Mobile**: Capacitor-based iOS and Android builds +- **Desktop**: Electron-based cross-platform desktop app +- **Docker**: Containerized deployment options -The application uses a platform-agnostic database layer with Vue mixins for service access: +## 📚 Documentation -* `src/services/PlatformService.ts` - Database interface definition -* `src/services/PlatformServiceFactory.ts` - Platform-specific service factory -* `src/services/AbsurdSqlDatabaseService.ts` - SQLite implementation -* `src/utils/PlatformServiceMixin.ts` - Vue mixin for database access with caching -* `src/db/` - Legacy Dexie database (migration in progress) +- **`BUILDING.md`** - Complete build system guide +- **`README-BUILD-GUARD.md`** - Build Architecture Guard documentation +- **`pull_request_template.md`** - PR template for build changes -**Development Guidelines**: +## 🤝 Contributing -- Always use `PlatformServiceMixin` for database operations in components -- Test with PlatformServiceMixin for new features -- Use migration tools for data transfer between systems -- Leverage mixin's ultra-concise methods: `$db()`, `$exec()`, `$one()`, `$contacts()`, `$settings()` +1. **Follow the Build Architecture Guard** - Update BUILDING.md when modifying build files +2. **Use the PR template** - Complete the checklist for build-related changes +3. **Test your changes** - Ensure builds work on affected platforms +4. **Document updates** - Keep BUILDING.md current and accurate -**Architecture Decision**: The project uses Vue mixins over Composition API composables for platform service access. See [Architecture Decisions](doc/architecture-decisions.md) for detailed rationale. +## 📄 License -### Kudos +[Add your license information here] -Gifts make the world go 'round! +--- -* [WebStorm by JetBrains](https://www.jetbrains.com/webstorm/) for the free open-source license -* [Máximo Fernández](https://medium.com/@maxfarenas) for the 3D [code](https://github.com/maxfer03/vue-three-ns) and [explanatory post](https://medium.com/nicasource/building-an-interactive-web-portfolio-with-vue-three-js-part-three-implementing-three-js-452cb375ef80) -* [Many tools & libraries](https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa/src/branch/master/package.json#L10) such as Nodejs.org, IntelliJ Idea, Veramo.io, Vuejs.org, threejs.org -* [Bush 3D model](https://sketchfab.com/3d-models/lupine-plant-bf30f1110c174d4baedda0ed63778439) -* [Forest floor image](https://www.goodfreephotos.com/albums/textures/leafy-autumn-forest-floor.jpg) -* Time Safari logo assisted by [DALL-E in ChatGPT](https://chat.openai.com/g/g-2fkFE8rbu-dall-e) -* [DiceBear](https://www.dicebear.com/licenses/) and [Avataaars](https://www.dicebear.com/styles/avataaars/#details) for human-looking identicons -* Some gratitude prompts thanks to [Develop Good Habits](https://www.developgoodhabits.com/gratitude-journal-prompts/) +**Note**: The Build Architecture Guard is active and will block +commits/pushes that modify build files without proper documentation +updates. See `README-BUILD-GUARD.md` for complete details. From 7b31ea014341145680d553572e72898e4cad3af2 Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Wed, 20 Aug 2025 13:00:06 +0000 Subject: [PATCH 03/10] feat: add Build Architecture Guard PR template - Create structured template for build-related changes - Include L1/L2/L3 change classification - Require BUILDING.md updates for sensitive file changes - Add artifact SHA256 validation for L3 changes --- pull_request_template.md | 47 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 pull_request_template.md diff --git a/pull_request_template.md b/pull_request_template.md new file mode 100644 index 00000000..8739bdbd --- /dev/null +++ b/pull_request_template.md @@ -0,0 +1,47 @@ +# Build Architecture Guard PR Template + +## Change Level + +- [ ] Level: **L1** / **L2** / **L3** (pick one) + +**Why:** … + +## Scope & Impact + +- [ ] Files & platforms touched: … +- [ ] Risk triggers (env / script flow / packaging / SW+WASM / + Docker / signing): … +- [ ] Mitigations/validation done: … + +## Commands Run (paste exact logs/snips) + +- [ ] Web: `npm run build:web` / `:prod` +- [ ] Electron: `npm run build:electron:dev` / package step +- [ ] Mobile: `npm run build:android:test` / iOS equivalent +- [ ] Clean/auto-run impacted scripts + +## Artifacts + +- [ ] Names + **sha256** of artifacts/installers: + +Artifacts: + +```text + + +``` + +## Docs + +- [ ] **BUILDING.md** updated (sections): … +- [ ] Troubleshooting updated (if applicable) + +## Rollback + +- [ ] Verified steps (1–3 cmds) to restore previous behavior + +## L3 only + +- [ ] ADR link: + +ADR: https://… From ae0601281b2d81d3d824c5179b553aa4b5e8668e Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Wed, 20 Aug 2025 13:00:16 +0000 Subject: [PATCH 04/10] feat: add markdown validation and auto-fix scripts - Create validate-markdown.sh for compliance checking - Add fix-markdown.sh for automatic formatting fixes - Exclude node_modules from validation scope - Integrate with npm scripts for easy usage --- scripts/fix-markdown.sh | 19 +++++++++++++++++++ scripts/validate-markdown.sh | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100755 scripts/fix-markdown.sh create mode 100755 scripts/validate-markdown.sh diff --git a/scripts/fix-markdown.sh b/scripts/fix-markdown.sh new file mode 100755 index 00000000..b2a21f6d --- /dev/null +++ b/scripts/fix-markdown.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail + +echo "🔧 Auto-fixing markdown formatting..." + +# Check if markdownlint is available +if ! command -v npx &> /dev/null; then + echo "❌ npx not found. Please install Node.js and npm first." + exit 1 +fi + +# Run markdownlint with auto-fix on project markdown files (exclude node_modules) +echo "📝 Fixing project markdown files..." +npx markdownlint "*.md" "*.mdc" "scripts/**/*.md" "src/**/*.md" "test-playwright/**/*.md" "resources/**/*.md" --config .markdownlint.json --fix 2>/dev/null || { + echo "⚠️ Some issues could not be auto-fixed. Check manually." +} + +echo "✅ Markdown auto-fix complete!" +echo "💡 Run 'npm run markdown:check' to verify all issues are resolved." diff --git a/scripts/validate-markdown.sh b/scripts/validate-markdown.sh new file mode 100755 index 00000000..f54f9dee --- /dev/null +++ b/scripts/validate-markdown.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +set -euo pipefail + +echo "🔍 Validating markdown formatting..." + +# Check if markdownlint is available +if ! command -v npx &> /dev/null; then + echo "❌ npx not found. Please install Node.js and npm first." + exit 1 +fi + +# Run markdownlint on project markdown files (exclude node_modules) +echo "📝 Checking project markdown files..." +npx markdownlint "*.md" "*.mdc" "scripts/**/*.md" "src/**/*.md" "test-playwright/**/*.md" "resources/**/*.md" --config .markdownlint.json 2>/dev/null || { + echo "❌ Markdown validation failed. Run 'npm run markdown:fix' to auto-fix issues." + exit 1 +} + +echo "✅ All markdown files pass validation!" From 8336d9d6bda81540bd0be8f41fa5dbaca0acdcf3 Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Wed, 20 Aug 2025 13:00:26 +0000 Subject: [PATCH 05/10] feat: enhance markdown rules for AI generation compliance - Add AI Generation Guidelines with alwaysApply: true - Extend globs to include .mdc files - Ensure AI agents follow rules during content creation - Improve markdown automation system integration --- .cursor/rules/docs/markdown.mdc | 36 ++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/.cursor/rules/docs/markdown.mdc b/.cursor/rules/docs/markdown.mdc index f95f297b..fddda015 100644 --- a/.cursor/rules/docs/markdown.mdc +++ b/.cursor/rules/docs/markdown.mdc @@ -1,5 +1,5 @@ --- -globs: *.md +globs: ["*.md", "*.mdc"] alwaysApply: false --- # Cursor Markdown Ruleset for TimeSafari Documentation @@ -10,6 +10,36 @@ This ruleset enforces consistent markdown formatting standards across all projec documentation, ensuring readability, maintainability, and compliance with markdownlint best practices. +**⚠️ CRITICAL FOR AI AGENTS**: These rules must be followed DURING content +generation, not applied after the fact. Always generate markdown that complies +with these standards from the start. + +## AI Generation Guidelines + +### **MANDATORY**: Follow These Rules While Writing + +When generating markdown content, you MUST: + +1. **Line Length**: Never exceed 80 characters per line +2. **Blank Lines**: Always add blank lines around headings, lists, and code + blocks +3. **Structure**: Use proper heading hierarchy and document templates +4. **Formatting**: Apply consistent formatting patterns immediately + +### **DO NOT**: Generate content that violates these rules + +- ❌ Generate long lines that need breaking +- ❌ Create content without proper blank line spacing +- ❌ Use inconsistent formatting patterns +- ❌ Assume post-processing will fix violations + +### **DO**: Generate compliant content from the start + +- ✅ Write within 80-character limits +- ✅ Add blank lines around all structural elements +- ✅ Use established templates and patterns +- ✅ Apply formatting standards immediately + ## General Formatting Standards ### Line Length @@ -326,6 +356,10 @@ Description of current situation or problem. ### Authentication ### Authorization + ## Features ❌ (Duplicate heading) + ### Security + ### Performance + ``` ## Features ❌ (Duplicate heading) ### Security ### Performance From 80aecbcbbc0dac54d2dec9a92e85a853b091bbf2 Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Wed, 20 Aug 2025 13:00:37 +0000 Subject: [PATCH 06/10] feat: add Build Architecture Guard MDC directive - Create comprehensive guard rules for build system protection - Define protected file patterns and validation requirements - Include risk matrix and required validation checklists - Add emergency procedures and rollback playbooks --- .cursor/rules/architecture/README.md | 75 +++++ .../architecture/build_architecture_guard.mdc | 295 ++++++++++++++++++ 2 files changed, 370 insertions(+) create mode 100644 .cursor/rules/architecture/README.md create mode 100644 .cursor/rules/architecture/build_architecture_guard.mdc diff --git a/.cursor/rules/architecture/README.md b/.cursor/rules/architecture/README.md new file mode 100644 index 00000000..ac9669dd --- /dev/null +++ b/.cursor/rules/architecture/README.md @@ -0,0 +1,75 @@ +# Architecture Rules Directory + +**Author**: Matthew Raymer +**Date**: 2025-08-20 +**Status**: 🎯 **ACTIVE** - Architecture protection guidelines + +## Overview + +This directory contains MDC (Model Directive Configuration) rules that protect +critical architectural components of the TimeSafari project. These rules ensure +that changes to system architecture follow proper review, testing, and +documentation procedures. + +## Available Rules + +### Build Architecture Guard (`build_architecture_guard.mdc`) + +Protects the multi-platform build system including: + +- Vite configuration files +- Build scripts and automation +- Platform-specific configurations (iOS, Android, Electron, Web) +- Docker and deployment infrastructure +- CI/CD pipeline components + +**When to use**: Any time you're modifying build scripts, configuration files, +or deployment processes. + +**Authorization levels**: + +- **Level 1**: Minor changes (review required) +- **Level 2**: Moderate changes (testing required) +- **Level 3**: Major changes (ADR required) + +## Usage Guidelines + +### For Developers + +1. **Check the rule**: Before making architectural changes, review the relevant + rule +2. **Follow the process**: Use the appropriate authorization level +3. **Complete validation**: Run through the required checklist +4. **Update documentation**: Keep BUILDING.md and related docs current + +### For Reviewers + +1. **Verify authorization**: Ensure changes match the required level +2. **Check testing**: Confirm appropriate testing has been completed +3. **Validate documentation**: Ensure BUILDING.md reflects changes +4. **Assess risk**: Consider impact on other platforms and systems + +## Integration with Other Rules + +- **Version Control**: Works with `workflow/version_control.mdc` +- **Research & Diagnostic**: Supports `research_diagnostic.mdc` for + investigations +- **Software Development**: Aligns with development best practices +- **Markdown Automation**: Integrates with `docs/markdown-automation.mdc` for + consistent documentation formatting + +## Emergency Procedures + +If architectural changes cause system failures: + +1. **Immediate rollback** to last known working state +2. **Document the failure** with full error details +3. **Investigate root cause** using diagnostic workflows +4. **Update procedures** to prevent future failures + +--- + +**Status**: Active architecture protection +**Priority**: Critical +**Maintainer**: Development team +**Next Review**: 2025-09-20 diff --git a/.cursor/rules/architecture/build_architecture_guard.mdc b/.cursor/rules/architecture/build_architecture_guard.mdc new file mode 100644 index 00000000..651a12d5 --- /dev/null +++ b/.cursor/rules/architecture/build_architecture_guard.mdc @@ -0,0 +1,295 @@ +--- +description: Guards against unauthorized changes to the TimeSafari building + architecture +alwaysApply: false +--- + +# Build Architecture Guard Directive + +**Author**: Matthew Raymer +**Date**: 2025-08-20 +**Status**: 🎯 **ACTIVE** - Build system protection guidelines + +## Purpose + +Protect the TimeSafari building architecture from unauthorized changes that +could break the multi-platform build pipeline, deployment processes, or +development workflow. This directive ensures all build system modifications +follow proper review, testing, and documentation procedures. + +## Protected Architecture Components + +### Core Build Infrastructure + +- **Vite Configuration Files**: `vite.config.*.mts` files +- **Build Scripts**: All scripts in `scripts/` directory +- **Package Scripts**: `package.json` build-related scripts +- **Platform Configs**: `capacitor.config.ts`, `electron/`, `android/`, + `ios/` +- **Docker Configuration**: `Dockerfile`, `docker-compose.yml` +- **Environment Files**: `.env.*`, `.nvmrc`, `.node-version` + +### Critical Build Dependencies + +- **Build Tools**: Vite, Capacitor, Electron, Android SDK, Xcode +- **Asset Management**: `capacitor-assets.config.json`, asset scripts +- **Testing Infrastructure**: Playwright, Jest, mobile test scripts +- **CI/CD Pipeline**: GitHub Actions, build validation scripts +- **Service Worker Assembly**: `sw_scripts/`, `sw_combine.js`, WASM copy steps + +## Change Authorization Requirements + +### Level 1: Minor Changes (Requires Review) + +- Documentation updates to `BUILDING.md` +- Non-breaking script improvements +- Test additions or improvements +- Asset configuration updates + +**Process**: Code review + basic testing + +### Level 2: Moderate Changes (Requires Testing) + +- New build script additions +- Environment variable changes +- Dependency version updates +- Platform-specific optimizations + +**Process**: Code review + platform testing + documentation update + +### Level 3: Major Changes (Requires ADR) + +- Build system architecture changes +- New platform support +- Breaking changes to build scripts +- Major dependency migrations + +**Process**: ADR creation + comprehensive testing + team review + +## Prohibited Actions + +### ❌ Never Allow Without ADR + +- **Delete or rename** core build scripts +- **Modify** `package.json` build script names +- **Change** Vite configuration structure +- **Remove** platform-specific build targets +- **Alter** Docker build process +- **Modify** CI/CD pipeline without testing + +### ❌ Never Allow Without Testing + +- **Update** build dependencies +- **Change** environment configurations +- **Modify** asset generation scripts +- **Alter** test infrastructure +- **Update** platform SDK versions + +## Required Validation Checklist + +### Before Any Build System Change + +- [ ] **Impact Assessment**: Which platforms are affected? +- [ ] **Testing Plan**: How will this be tested across platforms? +- [ ] **Rollback Plan**: How can this be reverted if it breaks? +- [ ] **Documentation**: Will `BUILDING.md` need updates? +- [ ] **Dependencies**: Are all required tools available? + +### After Build System Change + +- [ ] **Web Platform**: Does `npm run build:web:dev` work? +- [ ] **Mobile Platforms**: Do iOS/Android builds succeed? +- [ ] **Desktop Platform**: Does Electron build and run? +- [ ] **Tests Pass**: Do all build-related tests pass? +- [ ] **Documentation Updated**: Is `BUILDING.md` current? + +## Specific Test Commands (Minimum Required) + +### Web Platform + +- **Development**: `npm run build:web:dev` - serve and load app +- **Production**: `npm run build:web:prod` - verify SW and WASM present + +### Mobile Platforms + +- **Android**: `npm run build:android:test` or `:prod` - confirm assets copied +- **iOS**: `npm run build:ios:test` or `:prod` - verify build succeeds + +### Desktop Platform + +- **Electron**: `npm run build:electron:dev` and packaging for target OS +- **Verify**: Single-instance behavior and app boot + +### Auto-run (if affected) + +- **Test Mode**: `npm run auto-run:test` and platform variants +- **Production Mode**: `npm run auto-run:prod` and platform variants + +### Clean and Rebuild + +- Run relevant `clean:*` scripts and ensure re-build works + +## Emergency Procedures + +### Build System Broken + +1. **Immediate**: Revert to last known working commit +2. **Investigation**: Create issue with full error details +3. **Testing**: Verify all platforms work after revert +4. **Documentation**: Update `BUILDING.md` with failure notes + +### Platform-Specific Failure + +1. **Isolate**: Identify which platform is affected +2. **Test Others**: Verify other platforms still work +3. **Rollback**: Revert platform-specific changes +4. **Investigation**: Debug in isolated environment + +## Integration Points + +### With Version Control + +- **Branch Protection**: Require reviews for build script changes +- **Commit Messages**: Must reference ADR for major changes +- **Testing**: All build changes must pass CI/CD pipeline + +### With Documentation + +- **BUILDING.md**: Must be updated for any script changes +- **README.md**: Must reflect new build requirements +- **CHANGELOG.md**: Must document breaking build changes + +### With Testing + +- **Pre-commit**: Run basic build validation +- **CI/CD**: Full platform build testing +- **Manual Testing**: Human verification of critical paths + +## Risk Matrix & Required Validation + +### Environment Handling + +- **Trigger**: Change to `.env.*` loading / variable names +- **Validation**: Prove `dev/test/prod` builds; show environment echo in logs + +### Script Flow + +- **Trigger**: Reorder steps (prebuild → build → package), new flags +- **Validation**: Dry-run + normal run, show exit codes & timing + +### Platform Packaging + +- **Trigger**: Electron NSIS/DMG/AppImage, Android/iOS bundle +- **Validation**: Produce installer/artifact and open it; verify single-instance, + icons, signing + +### Service Worker / WASM + +- **Trigger**: `sw_combine.js`, WASM copy path +- **Validation**: Verify combined SW exists and is injected; page loads offline; + WASM present + +### Docker + +- **Trigger**: New base image, build args +- **Validation**: Build image locally; run container; list produced `/dist` + +### Signing/Notarization + +- **Trigger**: Cert path/profiles +- **Validation**: Show signing logs + verify on target OS + +## PR Template (Paste into Description) + +- [ ] **Level**: L1 / L2 / L3 + justification +- [ ] **Files & platforms touched**: +- [ ] **Risk triggers & mitigations**: +- [ ] **Commands run (paste logs)**: +- [ ] **Artifacts (names + sha256)**: +- [ ] **Docs updated (sections/links)**: +- [ ] **Rollback steps verified**: +- [ ] **CI**: Jobs passing and artifacts uploaded + +## Rollback Playbook + +### Immediate Rollback + +1. `git revert` or `git reset --hard `; restore prior `scripts/` or config + files +2. Rebuild affected targets; verify old behavior returns +3. Post-mortem notes → update this guard and `BUILDING.md` if gaps found + +### Rollback Verification + +- **Web**: `npm run build:web:dev` and `npm run build:web:prod` +- **Mobile**: `npm run build:android:test` and `npm run build:ios:test` +- **Desktop**: `npm run build:electron:dev` and packaging commands +- **Clean**: Run relevant `clean:*` scripts and verify re-build works + +## ADR Trigger List + +Raise an ADR when you propose any of: + +- **New build stage** or reorder of canonical stages +- **Replacement of packager** / packaging format +- **New environment model** or secure secret handling scheme +- **New service worker assembly** strategy or cache policy +- **New Docker base** or multi-stage pipeline +- **Relocation of build outputs** or directory conventions + +**ADR must include**: motivation, alternatives, risks, validation plan, rollback, + doc diffs. + +## Competence Hooks + +### Why This Works + +- **Prevents Build Failures**: Catches issues before they reach production +- **Maintains Consistency**: Ensures all platforms build identically +- **Reduces Debugging Time**: Prevents build system regressions + +### Common Pitfalls + +- **Silent Failures**: Changes that work on one platform but break others +- **Dependency Conflicts**: Updates that create version incompatibilities +- **Documentation Drift**: Build scripts that don't match documentation + +### Next Skill Unlock + +- Learn to test build changes across all platforms simultaneously + +### Teach-back + +- "What three platforms must I test before committing a build script change?" + +## Collaboration Hooks + +### Team Review Requirements + +- **Platform Owners**: iOS, Android, Electron, Web specialists +- **DevOps**: CI/CD pipeline maintainers +- **QA**: Testing infrastructure owners + +### Discussion Prompts + +- "Which platforms will be affected by this build change?" +- "How can we test this change without breaking existing builds?" +- "What's our rollback plan if this change fails?" + +## Self-Check (Before Allowing Changes) + +- [ ] **Authorization Level**: Is this change appropriate for the level? +- [ ] **Testing Plan**: Is there a comprehensive testing strategy? +- [ ] **Documentation**: Will BUILDING.md be updated? +- [ ] **Rollback**: Is there a safe rollback mechanism? +- [ ] **Team Review**: Have appropriate stakeholders been consulted? +- [ ] **CI/CD**: Will this pass the build pipeline? + +--- + +**Status**: Active build system protection +**Priority**: Critical +**Estimated Effort**: Ongoing vigilance +**Dependencies**: All build system components +**Stakeholders**: Development team, DevOps, Platform owners +**Next Review**: 2025-09-20 From 963ff9234f690163b276a2f3aa72ed990cc79b9d Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Wed, 20 Aug 2025 13:01:50 +0000 Subject: [PATCH 07/10] feat: implement comprehensive Build Architecture Guard system - Add Husky Git hooks for pre-commit and pre-push validation - Create guard script for BUILDING.md update enforcement - Implement PR template with L1/L2/L3 change classification - Add markdown validation and auto-fix scripts - Create comprehensive documentation and MDC rules - Ensure zero-disruption deployment with opt-in activation --- .cursor/rules/docs/markdown-automation.mdc | 79 ++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 .cursor/rules/docs/markdown-automation.mdc diff --git a/.cursor/rules/docs/markdown-automation.mdc b/.cursor/rules/docs/markdown-automation.mdc new file mode 100644 index 00000000..b2da4927 --- /dev/null +++ b/.cursor/rules/docs/markdown-automation.mdc @@ -0,0 +1,79 @@ +--- +alwaysApply: true +--- + +# Markdown Automation System + +**Author**: Matthew Raymer +**Date**: 2025-08-20 +**Status**: 🎯 **ACTIVE** - Markdown formatting automation + +## Overview + +The Markdown Automation System ensures your markdown formatting standards are +followed **during content generation** by AI agents, not just applied after the +fact. + +## AI-First Approach + +### **Primary Method**: AI Agent Compliance + +- **AI agents follow markdown rules** while generating content +- **No post-generation fixes needed** - content is compliant from creation +- **Consistent formatting** across all generated documentation + +### **Secondary Method**: Automated Validation + +- **Pre-commit hooks** catch any remaining issues +- **GitHub Actions** validate formatting before merge +- **Manual tools** for bulk fixes when needed + +## How It Works + +### 1. **AI Agent Compliance** (Primary) + +- **When**: Every time AI generates markdown content +- **What**: AI follows markdown rules during generation +- **Result**: Content is properly formatted from creation + +### 2. **Pre-commit Hooks** (Backup) + +- **When**: Every time you commit +- **What**: Catches any remaining formatting issues +- **Result**: Clean, properly formatted markdown files + +### 3. **GitHub Actions** (Pre-merge) + +- **When**: Every pull request +- **What**: Validates markdown formatting across all files +- **Result**: Blocks merge if formatting issues exist + +## AI Agent Rules Integration + +The AI agent follows markdown rules defined in `.cursor/rules/docs/markdown.mdc`: + +- **alwaysApply: true** - Rules are enforced during generation +- **Line Length**: AI never generates lines > 80 characters +- **Blank Lines**: AI adds proper spacing around all elements +- **Structure**: AI uses established templates and patterns + +## Available Commands + +### NPM Scripts + +- **`npm run markdown:setup`** - Install the automation system +- **`npm run markdown:fix`** - Fix formatting in all markdown files +- **`npm run markdown:check`** - Validate formatting without fixing + +## Benefits + +- **No more manual fixes** - AI generates compliant content from start +- **Consistent style** - All files follow same standards +- **Faster development** - No need to fix formatting manually + +--- + +**Status**: Active automation system +**Priority**: High +**Maintainer**: Development team +**Next Review**: 2025-09-20 From 2d17bfd3b4080b7eb7218687df8c28fedd038cde Mon Sep 17 00:00:00 2001 From: Matthew Raymer Date: Wed, 20 Aug 2025 13:02:01 +0000 Subject: [PATCH 08/10] docs: comprehensive documentation updates and modernization - Update BUILDING.md with current build system information - Modernize various README files across the project - Update CHANGELOG.md with recent changes - Improve documentation consistency and formatting - Update platform-specific documentation (iOS, Electron, Docker) - Enhance test documentation and build guides --- BUILDING.md | 434 ++++++++++++------ CHANGELOG.md | 41 +- TASK_storage.md | 8 - doc/DEEP_LINKS.md | 3 + doc/README.md | 5 +- doc/architecture-decisions.md | 2 +- doc/asset-migration-plan.md | 1 + doc/build-modernization-context.md | 10 +- doc/circular-dependency-analysis.md | 21 +- doc/component-communication-guide.md | 16 +- doc/cors-disabled-for-universal-images.md | 16 +- doc/cors-image-loading-solution.md | 28 +- doc/database-migration-guide.md | 1 + doc/debug-hook-guide.md | 5 + doc/electron-cleanup-summary.md | 8 +- doc/electron-console-cleanup.md | 27 +- doc/error-diagnostics-log.md | 19 +- doc/image-hosting-guide.md | 23 +- doc/logging-configuration.md | 2 + doc/migration-fence-definition.md | 23 +- doc/migration-progress-tracker.md | 71 ++- doc/migration-quick-reference.md | 3 +- doc/migration-readiness-summary.md | 33 +- doc/migration-roadmap-next-steps.md | 33 +- doc/migration-security-checklist.md | 2 +- doc/migration-to-wa-sqlite.md | 31 +- doc/platformservicemixin-completion-plan.md | 31 +- doc/qr-code-implementation-guide.md | 30 +- doc/secure-storage-implementation.md | 11 +- doc/sharebufferarray_spectre_security.md | 14 + doc/storage-implementation-checklist.md | 31 +- doc/usage-guide.md | 115 ++--- docker/README.md | 34 +- electron/README-BUILDING.md | 31 +- electron/README.md | 34 +- .../app_privacy_manifest_fixer/CHANGELOG.md | 17 +- ios/App/app_privacy_manifest_fixer/README.md | 7 + .../README.zh-CN.md | 11 +- resources/README.md | 5 +- scripts/README.md | 9 +- scripts/git-hooks/README.md | 23 +- test-playwright/README.md | 10 +- test-playwright/TESTING.md | 4 +- 43 files changed, 1019 insertions(+), 264 deletions(-) diff --git a/BUILDING.md b/BUILDING.md index e5abf069..17c367d6 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -13,7 +13,7 @@ npm run build:web:serve -- --test # Start with test endorser server npm run build:web:dev # Start development server with hot reload with local endorser server npm run build:web:prod # Production build -# 📱 Mobile Development +# 📱 Mobile Development npm run build:ios # iOS build (opens Xcode) npm run build:android # Android build (opens Android Studio) @@ -31,6 +31,7 @@ npm run clean:all # Clean all platforms ### Development Workflow #### 1. First-Time Setup + ```bash # Install dependencies npm install @@ -40,6 +41,7 @@ npm run test:web # Run web tests to verify setup ``` #### 2. Daily Development + ```bash # Start web development server npm run build:web:dev # Opens http://localhost:8080 @@ -48,11 +50,12 @@ npm run build:web:dev # Opens http://localhost:8080 npm run build:ios # Opens Xcode with iOS project npm run build:android # Opens Android Studio with Android project -# For desktop development +# For desktop development npm run build:electron:dev # Runs Electron app directly ``` #### 3. Testing Your Changes + ```bash # Test web functionality npm run test:web # Run web tests @@ -66,6 +69,7 @@ npm run build:android:test:run # Build and run on Android emulator ``` #### 4. Production Builds + ```bash # Build for production npm run build:web:prod # Web production build @@ -77,6 +81,7 @@ npm run build:electron:prod # Electron production build ### Environment Configuration #### Quick Environment Setup + ```bash # Copy environment template (if available) cp .env.example .env.development @@ -89,6 +94,7 @@ cp .env.example .env.development ``` #### Platform-Specific Development + - **Web**: Uses `localhost:3000` for APIs by default - **iOS Simulator**: Uses `localhost:3000` for APIs - **Android Emulator**: Uses `10.0.2.2:3000` for APIs @@ -97,6 +103,7 @@ cp .env.example .env.development ### Troubleshooting Quick Fixes #### Common Issues + ```bash # Clean and rebuild npm run clean:all @@ -114,6 +121,7 @@ npm run test:web # Verifies web setup ``` #### Platform-Specific Issues + - **iOS**: Ensure Xcode and Command Line Tools are installed - **Android**: Ensure Android Studio and SDK are configured - **Electron**: Ensure platform-specific build tools are installed @@ -222,6 +230,7 @@ All web build commands use the `./scripts/build-web.sh` script, which provides: ``` **Script Flow:** + 1. **Environment Validation**: Check prerequisites (Node.js, npm, etc.) 2. **Environment Setup**: Load `.env` files, set NODE_ENV 3. **Clean Dist**: Remove previous build artifacts @@ -230,8 +239,9 @@ All web build commands use the `./scripts/build-web.sh` script, which provides: 6. **Optional Serve**: Start local HTTP server if requested **Exit Codes:** + - `1` - Web cleanup failed -- `2` - Environment setup failed +- `2` - Environment setup failed - `3` - Vite build failed - `4` - Docker build failed - `5` - Serve command failed @@ -239,19 +249,25 @@ All web build commands use the `./scripts/build-web.sh` script, which provides: ### Compile and minify for test & production -* If there are DB changes: before updating the test server, open browser(s) with current version to test DB migrations. +- If there are DB changes: before updating the test server, open browser(s) with +current version to test DB migrations. -* Update the ClickUp tasks & CHANGELOG.md & the version in package.json, run `npm install`. +- Update the ClickUp tasks & CHANGELOG.md & the version in package.json, run +`npm install`. -* Run a build to make sure package-lock version is updated, linting works, etc: `npm install && npm run build:web` +- Run a build to make sure package-lock version is updated, linting works, etc: +`npm install && npm run build:web` -* Commit everything (since the commit hash is used the app). +- Commit everything (since the commit hash is used the app). -* Put the commit hash in the changelog (which will help you remember to bump the version in the step later). +- Put the commit hash in the changelog (which will help you remember to bump the + version in the step later). -* Tag with the new version, [online](https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa/releases) or `git tag 1.0.2 && git push origin 1.0.2`. +- Tag with the new version, +[online](https://gitea.anomalistdesign.com/trent_larson/crowd-funder-for-time-pwa/releases) or +`git tag 1.0.2 && git push origin 1.0.2`. -* For test, build the app (because test server is not yet set up to build): +- For test, build the app (because test server is not yet set up to build): ```bash TIME_SAFARI_APP_TITLE="TimeSafari_Test" \ @@ -274,25 +290,28 @@ rsync -azvu -e "ssh -i ~/.ssh/..." dist ubuntutest@test.timesafari.app:time-safa (Note: The test BVC_MEETUPS_PROJECT_CLAIM_ID does not resolve as a URL because it's only in the test DB and the prod redirect won't redirect there.) -* For prod, get on the server and run the correct build: +- For prod, get on the server and run the correct build: ... and log onto the server: -* `pkgx +npm sh` +- `pkgx +npm sh` -* `cd crowd-funder-for-time-pwa && git checkout master && git pull && git checkout 1.0.2 && npm install && npm run build:web:prod && cd -` +- `cd crowd-funder-for-time-pwa && git checkout master && git pull && git checkout +1.0.2 && npm install && npm run build:web:prod && cd -` (The plain `npm run build:web:prod` uses the .env.production file.) -* Back up the time-safari/dist folder & deploy: `mv time-safari/dist time-safari-dist-prev-2 && mv crowd-funder-for-time-pwa/dist time-safari/` +- Back up the time-safari/dist folder & deploy: `mv time-safari/dist time-safari-dist-prev-2 && mv crowd-funder-for-time-pwa/dist time-safari/` -* Record the new hash in the changelog. Edit package.json to increment version & add "-beta", `npm install`, commit, and push. Also record what version is on production. +- Record the new hash in the changelog. Edit package.json to increment version & +add "-beta", `npm install`, commit, and push. Also record what version is on production. ## Docker Deployment -The application can be containerized using Docker for consistent deployment across environments. +The application can be containerized using Docker for consistent deployment across +environments. -### Prerequisites +### Docker Prerequisites - Docker installed on your system - Docker Compose (optional, for multi-container setups) @@ -402,7 +421,10 @@ docker run -d \ ## Desktop Build (Electron) -TimeSafari's Electron build system provides comprehensive desktop application packaging and distribution capabilities across Windows, macOS, and Linux platforms. The system supports multiple build modes, environment configurations, and package formats. +TimeSafari's Electron build system provides comprehensive desktop application +packaging and distribution capabilities across Windows, macOS, and Linux +platforms. The system supports multiple build modes, environment configurations, +and package formats. ### Electron Build Commands @@ -436,15 +458,18 @@ npm run clean:electron # Clean Electron build artifacts #### Development Build -Start development build using `npm run build:electron:dev` (builds and runs the app directly). +Start development build using `npm run build:electron:dev` (builds and runs the +app directly). #### Production Build -Run production builds using the commands above. Production builds create platform-specific packages. +Run production builds using the commands above. Production builds create +platform-specific packages. #### Package-Specific Builds -Create platform-specific packages using the commands above. These build the app and create installable packages. +Create platform-specific packages using the commands above. These build the app +and create installable packages. ### Single Instance Enforcement @@ -484,29 +509,29 @@ The Electron app enforces single-instance operation to prevent: The Electron build process follows a multi-stage approach: -``` +```text 1. Web Build (Vite) → 2. Capacitor Sync → 3. TypeScript Compile → 4. Package ``` -**Stage 1: Web Build** +#### **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** +#### **Stage 2: Capacitor Sync** - Copies web assets to Electron app directory - Syncs Capacitor configuration and plugins - Prepares native module bindings -**Stage 3: TypeScript Compile** +#### **Stage 3: TypeScript Compile** - Compiles Electron main process TypeScript - Rebuilds native modules for target platform - Generates production-ready JavaScript -**Stage 4: Package Creation** +#### **Stage 4: Package Creation** - Creates platform-specific installers - Generates distribution packages @@ -566,6 +591,7 @@ npm run build:electron:windows:prod ``` **Configuration**: + - NSIS installer with custom options - Desktop and Start Menu shortcuts - Elevation permissions for installation @@ -588,6 +614,7 @@ npm run build:electron:mac:prod ``` **Configuration**: + - Universal binary (x64 + arm64) - DMG installer with custom branding - App Store compliance (when configured) @@ -610,12 +637,13 @@ npm run build:electron:linux:prod ``` **Configuration**: + - AppImage for universal distribution - DEB package for Debian-based systems - RPM package for Red Hat-based systems - Desktop integration -### Package-Specific Builds +### Desktop Package-Specific Builds #### AppImage Package @@ -634,6 +662,7 @@ npm run build:electron:appimage:prod ``` **Features**: + - Single file distribution - No installation required - Portable across Linux distributions @@ -656,6 +685,7 @@ npm run build:electron:deb:prod ``` **Features**: + - Native package management - Dependency resolution - System integration @@ -678,6 +708,7 @@ npm run build:electron:dmg:prod ``` **Features**: + - Native macOS installer - Custom branding and layout - Drag-and-drop installation @@ -742,7 +773,7 @@ npm run build:electron:dmg:test # DMG test build npm run build:electron:dmg:prod # DMG production build ``` -#### Direct Script Usage +#### Direct Script Usage Reference All npm scripts use the underlying `./scripts/build-electron.sh` script: @@ -766,9 +797,9 @@ npm run clean:electron # Clean Electron build artifacts ### Build Output Structure -#### Development Build +#### Development Build Structure -``` +```text electron/ ├── app/ # Web assets ├── build/ # Compiled TypeScript @@ -776,9 +807,9 @@ electron/ └── node_modules/ # Dependencies ``` -#### Production Build +#### Production Build Output -``` +```text electron/ ├── app/ # Web assets ├── build/ # Compiled TypeScript @@ -796,7 +827,8 @@ electron/ For public distribution on macOS, you need to code sign and notarize your app: -1. Set up environment variables: +##### 1. Set up environment variables + ```bash export CSC_LINK=/path/to/your/certificate.p12 export CSC_KEY_PASSWORD=your_certificate_password @@ -804,7 +836,8 @@ export APPLE_ID=your_apple_id export APPLE_ID_PASSWORD=your_app_specific_password ``` -2. Build with signing: +##### 2. Build with signing + ```bash npm run build:electron:mac:prod ``` @@ -813,13 +846,15 @@ npm run build:electron:mac:prod For Windows distribution, configure Authenticode signing: -1. Set up environment variables: +##### 1. Set up desktop environment variables + ```bash export CSC_LINK=/path/to/your/certificate.p12 export CSC_KEY_PASSWORD=your_certificate_password ``` -2. Build with signing: +##### 2. Build desktop with signing + ```bash npm run build:electron:windows:prod ``` @@ -829,12 +864,14 @@ npm run build:electron:windows:prod #### Linux - **AppImage**: Make executable and run + ```bash chmod +x electron/dist/TimeSafari-*.AppImage ./electron/dist/TimeSafari-*.AppImage ``` - **DEB**: Install and run + ```bash sudo dpkg -i electron/dist/timesafari_*_amd64.deb timesafari @@ -849,6 +886,7 @@ timesafari 3. Launch from Applications Note: If you get a security warning when running the app: + 1. Right-click the app 2. Select "Open" 3. Click "Open" in the security dialog @@ -863,6 +901,7 @@ Note: If you get a security warning when running the app: #### Common Build Issues **TypeScript Compilation Errors**: + ```bash # Clean and rebuild npm run clean:electron @@ -870,30 +909,35 @@ npm run build:electron:dev ``` **Native Module Issues**: + ```bash # Rebuild native modules npm run build:electron:dev ``` **Asset Copy Issues**: + ```bash # Verify Capacitor sync npx cap sync electron ``` -#### Platform-Specific Issues +#### Platform-Specific Building Issues **Windows**: + - Ensure Windows Build Tools installed - Check NSIS installation - Verify code signing certificates **macOS**: + - Install Xcode Command Line Tools - Configure code signing certificates - Check app notarization requirements **Linux**: + - Install required packages (rpm-tools, etc.) - Check AppImage dependencies - Verify desktop integration @@ -984,6 +1028,7 @@ The recommended way to build for iOS is using the automated build script: ``` The script handles all the necessary steps including: + - Environment setup and validation - Web asset building (Capacitor mode) - Capacitor synchronization @@ -1004,11 +1049,11 @@ If you need to build manually or want to understand the individual steps: #### Each Release -0. First time (or if dependencies change): +##### 0. First time (or if dependencies change) - - `pkgx +rubygems.org sh` +- `pkgx +rubygems.org sh` - - ... and you may have to fix these, especially with pkgx: +- ... and you may have to fix these, especially with pkgx: ```bash gem_path=$(which gem) @@ -1017,15 +1062,15 @@ If you need to build manually or want to understand the individual steps: export GEM_PATH=$shortened_path ``` -1. Bump the version in package.json, then here. +##### 1. Bump the version in package.json, then here - ``` + ```bash cd ios/App && xcrun agvtool new-version 40 && perl -p -i -e "s/MARKETING_VERSION = .*;/MARKETING_VERSION = 1.0.7;/g" App.xcodeproj/project.pbxproj && cd - # Unfortunately this edits Info.plist directly. #xcrun agvtool new-marketing-version 0.4.5 ``` -2. Build. +##### 2. Build Here's prod. Also available: test, dev @@ -1035,22 +1080,28 @@ If you need to build manually or want to understand the individual steps: 3.1. Use Xcode to build and run on simulator or device. - * Select Product -> Destination with some Simulator version. Then click the run arrow. +- Select Product -> Destination with some Simulator version. Then click the run arrow. 3.2. Use Xcode to release. - * Someday: Under "General" we want to rename a bunch of things to "Time Safari" - * Choose Product -> Destination -> Any iOS Device - * Choose Product -> Archive - * This will trigger a build and take time, needing user's "login" keychain password (user's login password), repeatedly. - * If it fails with `building for 'iOS', but linking in dylib (.../.pkgx/zlib.net/v1.3.0/lib/libz.1.3.dylib) built for 'macOS'` then run XCode outside that terminal (ie. not with `npx cap open ios`). - * Click Distribute -> App Store Connect - * In AppStoreConnect, add the build to the distribution. You may have to remove the current build with the "-" when you hover over it, then "Add Build" with the new build. - * May have to go to App Review, click Submission, then hover over the build and click "-". - * It can take 15 minutes for the build to show up in the list of builds. - * You'll probably have to "Manage" something about encryption, disallowed in France. - * Then "Save" and "Add to Review" and "Resubmit to App Review". - * Eventually it'll be "Ready for Distribution" which means +- Someday: Under "General" we want to rename a bunch of things to "Time Safari" +- Choose Product -> Destination -> Any iOS Device +- Choose Product -> Archive + - This will trigger a build and take time, needing user's "login" keychain + password (user's login password), repeatedly. + - If it fails with `building for 'iOS', but linking in dylib + (.../.pkgx/zlib.net/v1.3.0/lib/libz.1.3.dylib) built for 'macOS'` then run + XCode outside that terminal (ie. not with `npx cap open ios`). + - Click Distribute -> App Store Connect +- In AppStoreConnect, add the build to the distribution. You may have to remove + the current build with the "-" when you hover over it, then "Add Build" with the + new build. + - May have to go to App Review, click Submission, then hover over the build + and click "-". + - It can take 15 minutes for the build to show up in the list of builds. + - You'll probably have to "Manage" something about encryption, disallowed in France. + - Then "Save" and "Add to Review" and "Resubmit to App Review". +- Eventually it'll be "Ready for Distribution" which means ### Android Build @@ -1063,7 +1114,7 @@ Prerequisites: Android Studio with Java SDK installed npm run build:android # Development build (builds and opens Android Studio) npm run build:android:dev # Development build (builds and opens Android Studio) npm run build:android:test # Test build (builds for testing environment) -npm run build:android:prod # Production build (builds for production environment) +npm run build:android:prod # Production build (builds for production environment). # Auto-run builds npm run build:android:test:run # Test build with auto-run (builds then runs on emulator) @@ -1085,7 +1136,7 @@ npm run build:android:assets # Generate assets only npm run build:android:deploy # Build and deploy to connected device ``` -#### Automated Build Script +#### Android Automated Build Script The recommended way to build for Android is using the automated build script: @@ -1103,16 +1154,16 @@ The recommended way to build for Android is using the automated build script: ./scripts/build-android.sh --help ``` -#### Manual Build Process +#### Android Manual Build Process -1. Bump the version in package.json, then here: android/app/build.gradle +##### 1. Bump the version in package.json, then here: android/app/build.gradle ```bash perl -p -i -e 's/versionCode .*/versionCode 40/g' android/app/build.gradle perl -p -i -e 's/versionName .*/versionName "1.0.7"/g' android/app/build.gradle ``` -2. Build. +##### 2. Build Here's prod. Also available: test, dev @@ -1120,13 +1171,13 @@ The recommended way to build for Android is using the automated build script: npm run build:android:prod ``` -3. Open the project in Android Studio: +##### 3. Open the project in Android Studio ```bash npx cap open android ``` -4. Use Android Studio to build and run on emulator or device. +##### 4. Use Android Studio to build and run on emulator or device ## Android Build from the console @@ -1145,9 +1196,10 @@ cd - ... or, to create a signed release: -* Setup by adding the app/gradle.properties.secrets file (see properties at top of app/build.gradle) and the app/time-safari-upload-key-pkcs12.jks file -* In app/build.gradle, bump the versionCode and maybe the versionName -* Then `bundleRelease`: +- Setup by adding the app/gradle.properties.secrets file (see properties at top + of app/build.gradle) and the app/time-safari-upload-key-pkcs12.jks file +- In app/build.gradle, bump the versionCode and maybe the versionName +- Then `bundleRelease`: ```bash cd android @@ -1165,7 +1217,8 @@ At play.google.com/console: - Hit "Next". - Save, go to "Publishing Overview" as prompted, and click "Send changes for review". -- Note that if you add testers, you have to go to "Publishing Overview" and send those changes or your (closed) testers won't see it. +- Note that if you add testers, you have to go to "Publishing Overview" and send + those changes or your (closed) testers won't see it. ### Capacitor Operations @@ -1263,7 +1316,7 @@ npm run lint-fix # Fix linting issues Use the commands above to check and fix code quality issues. -## Build Architecture +## Code Build Architecture ### Web Build Process @@ -1288,19 +1341,22 @@ Use the commands above to check and fix code quality issues. 4. **Native Build**: Platform-specific compilation 5. **Package Creation**: APK/IPA generation -## Environment Configuration +## Architecture Environment Configuration ### Environment Files The build system supports multiple environment file patterns for different scenarios: #### Primary Environment Files + - `.env.development` - Development environment (local development) - `.env.test` - Testing environment (staging/testing) - `.env.production` - Production environment (production deployment) #### Fallback and Local Files -- `.env` - General fallback environment file (loaded if mode-specific file doesn't exist) + +- `.env` - General fallback environment file (loaded if mode-specific file + doesn't exist) - `.env.local` - Local development overrides (gitignored) - `.env.*.local` - Mode-specific local overrides (gitignored) @@ -1324,6 +1380,7 @@ The build system supports multiple environment file patterns for different scena ### Key Environment Variables #### API Server Configuration + ```bash # API Servers (Environment-specific) VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch @@ -1342,6 +1399,7 @@ VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZY #### Environment-Specific Configurations **Development Environment** (`.env.development`): + ```bash # Development API Servers (Local) VITE_DEFAULT_ENDORSER_API_SERVER=http://localhost:3000 @@ -1351,6 +1409,7 @@ VITE_APP_SERVER=http://localhost:8080 ``` **Test Environment** (`.env.test`): + ```bash # Test API Servers VITE_DEFAULT_ENDORSER_API_SERVER=https://test-api.endorser.ch @@ -1360,6 +1419,7 @@ VITE_APP_SERVER=https://test.timesafari.app ``` **Production Environment** (`.env.production`): + ```bash # Production API Servers VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch @@ -1371,16 +1431,19 @@ VITE_APP_SERVER=https://timesafari.app ### Platform-Specific Overrides #### Android Development + - **Emulator**: Uses `http://10.0.2.2:3000` (Android emulator default) - **Physical Device**: Uses custom IP address (e.g., `http://192.168.1.100:3000`) #### iOS Development + - **Simulator**: Uses `http://localhost:3000` (iOS simulator default) - **Physical Device**: Uses custom IP address (e.g., `http://192.168.1.100:3000`) ### Environment Loading Process 1. **Build Script Initialization** + ```bash # scripts/common.sh - setup_build_env() if [ "$BUILD_MODE" = "development" ]; then @@ -1390,6 +1453,7 @@ VITE_APP_SERVER=https://timesafari.app ``` 2. **Platform-Specific Overrides** + ```bash # scripts/build-android.sh if [ "$BUILD_MODE" = "development" ]; then @@ -1399,13 +1463,14 @@ VITE_APP_SERVER=https://timesafari.app ``` 3. **Environment File Loading** + ```bash # scripts/build-web.sh local env_file=".env.$BUILD_MODE" # .env.development, .env.test, .env.production if [ -f "$env_file" ]; then load_env_file "$env_file" fi - + # Fallback to .env if [ -f ".env" ]; then load_env_file ".env" @@ -1413,6 +1478,7 @@ VITE_APP_SERVER=https://timesafari.app ``` 4. **Application Usage** + ```typescript // src/constants/app.ts export const DEFAULT_ENDORSER_API_SERVER = @@ -1420,9 +1486,9 @@ VITE_APP_SERVER=https://timesafari.app AppString.PROD_ENDORSER_API_SERVER; ``` -## Troubleshooting +## Building Troubleshooting -### Common Issues +### Common Issues Building #### Build Failures @@ -1447,29 +1513,34 @@ npm run build:ios:assets npm run build:android:assets ``` -### Platform-Specific Issues +### More Platform-Specific Building Issues + +#### Building on Windows -#### Windows - Ensure Windows Build Tools installed - Check NSIS installation - Verify code signing certificates -#### macOS +#### Building on macOS + - Install Xcode Command Line Tools - Configure code signing certificates - Check app notarization requirements -#### Linux +#### Building on Linux + - Install required packages (rpm-tools, etc.) - Check AppImage dependencies - Verify desktop integration #### iOS + - Install Xcode and Command Line Tools - Configure signing certificates - Check provisioning profiles #### Android + - Install Android Studio and SDK - Configure signing keys - Check device/emulator setup @@ -1488,37 +1559,45 @@ npm run build:android:assets ### Build Process Overview -TimeSafari's build system follows a multi-stage process that prepares assets, combines scripts, and generates platform-specific outputs. +TimeSafari's build system follows a multi-stage process that prepares assets, +combines scripts, and generates platform-specific outputs. #### Pre-Build Preparation -**1. Service Worker Script Preparation** +##### 1. Service Worker Script Preparation + ```bash # Optional: Format third-party service worker scripts npx prettier --write ./sw_scripts/ ``` **What this does:** -- Formats cryptographic libraries (`nacl.js`, `noble-curves.js`, `noble-hashes.js`, etc.) + +- Formats cryptographic libraries (`nacl.js`, `noble-curves.js`, + `noble-hashes.js`, etc.) - These scripts are automatically combined during the build process - Improves readability and makes version control diffs cleaner - **Note**: This is optional and only needed when updating third-party scripts **2. Automatic Pre-Build Steps** The `prebuild` script automatically runs before any build: + ```json "prebuild": "eslint --ext .js,.ts,.vue --ignore-path .gitignore src && node sw_combine.js && node scripts/copy-wasm.js" ``` **What happens automatically:** + - **ESLint**: Checks and fixes code formatting in `src/` -- **Script Combination**: `sw_combine.js` combines all `sw_scripts/*.js` files into `sw_scripts-combined.js` +- **Script Combination**: `sw_combine.js` combines all `sw_scripts/*.js` files + into `sw_scripts-combined.js` - **WASM Copy**: `copy-wasm.js` copies SQLite WASM files to `public/wasm/` -#### Build Architecture +#### Build Process Architecture **Web Build Process:** -``` + +```text 1. Pre-Build: ESLint + Script Combination + WASM Copy 2. Environment Setup: Load .env files, set NODE_ENV 3. Vite Build: Bundle web assets with PWA support @@ -1527,7 +1606,8 @@ The `prebuild` script automatically runs before any build: ``` **Electron Build Process:** -``` + +```text 1. Web Build: Vite builds web assets for Electron 2. Capacitor Sync: Copies assets to Electron app directory 3. TypeScript Compile: Compiles main process code @@ -1536,7 +1616,8 @@ The `prebuild` script automatically runs before any build: ``` **Mobile Build Process:** -``` + +```text 1. Web Build: Vite builds web assets 2. Capacitor Sync: Syncs with native platforms 3. Asset Generation: Creates platform-specific assets @@ -1547,12 +1628,14 @@ The `prebuild` script automatically runs before any build: #### Service Worker Architecture **Script Organization:** + - `sw_scripts/` - Individual third-party scripts - `sw_combine.js` - Combines scripts into single file - `sw_scripts-combined.js` - Combined service worker (317KB, 10K+ lines) - `vite.config.utils.mts` - PWA configuration using combined script **PWA Integration:** + ```typescript // vite.config.utils.mts pwaConfig: { @@ -1563,31 +1646,35 @@ pwaConfig: { ``` **What Gets Combined:** + - `nacl.js` - NaCl cryptographic library - `noble-curves.js` - Elliptic curve cryptography (177KB) - `noble-hashes.js` - Cryptographic hash functions (91KB) - `safari-notifications.js` - Safari-specific notifications - `additional-scripts.js` - Additional service worker functionality -#### Environment Configuration +#### Process Environment Configuration **Environment Files:** The build system supports multiple environment file patterns: - `.env.development` - Development environment (local development) -- `.env.test` - Testing environment (staging/testing) +- `.env.test` - Testing environment (staging/testing) - `.env.production` - Production environment (production deployment) -- `.env` - General fallback environment file (loaded if mode-specific file doesn't exist) +- `.env` - General fallback environment file (loaded if mode-specific file + doesn't exist) - `.env.local` - Local development overrides (gitignored) - `.env.*.local` - Mode-specific local overrides (gitignored) **Environment Variable Precedence (Highest to Lowest):** + 1. **Shell Script Overrides** - Platform-specific overrides in build scripts 2. **Environment-Specific .env Files** - `.env.development`, `.env.test`, `.env.production` 3. **Fallback .env File** - General `.env` file (if mode-specific file doesn't exist) 4. **Hardcoded Constants** - Default values in `src/constants/app.ts` **Key Environment Variables:** + ```bash # API Servers (Environment-specific) VITE_DEFAULT_ENDORSER_API_SERVER=https://api.endorser.ch @@ -1604,13 +1691,17 @@ VITE_BVC_MEETUPS_PROJECT_CLAIM_ID=https://endorser.ch/entity/01HWE8FWHQ1YGP7GFZY ``` **Platform-Specific Overrides:** -- **Android Development**: `http://10.0.2.2:3000` (emulator) or custom IP (physical device) -- **iOS Development**: `http://localhost:3000` (simulator) or custom IP (physical device) -#### Build Output Structure +- **Android Development**: `http://10.0.2.2:3000` (emulator) or custom IP +(physical device) +- **iOS Development**: `http://localhost:3000` (simulator) or custom IP (physical +device) + +#### Build Process Output Structure **Web Build:** -``` + +```folders dist/ ├── index.html # Main HTML file ├── assets/ # Bundled JavaScript/CSS @@ -1620,7 +1711,8 @@ dist/ ``` **Electron Build:** -``` + +```folders electron/ ├── app/ # Web assets ├── build/ # Compiled TypeScript @@ -1635,35 +1727,41 @@ electron/ #### Manual vs Automatic Steps **Manual Steps (Developer Responsibility):** + - Database migration testing - Service worker script formatting (optional) - Version updates and changelog - Environment-specific builds **Automatic Steps (Build System):** + - Code linting and formatting - Script combination - Asset optimization - Package creation - Service worker injection -This architecture ensures consistent builds across all platforms while providing flexibility for platform-specific optimizations and manual quality assurance steps. +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. +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 +**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. +**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 @@ -1687,11 +1785,13 @@ 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 @@ -1700,6 +1800,7 @@ npm run build:web:docker:prod # Production Docker build - **Local Serving**: Built-in HTTP server for testing builds **Exit Codes**: + - `1` - Web cleanup failed - `2` - Environment setup failed - `3` - Vite build failed @@ -1709,13 +1810,15 @@ npm run build:web:docker:prod # Production Docker build ### A.2 build-electron.sh -**File**: `scripts/build-electron.sh` -**Author**: Matthew Raymer +**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. +**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) @@ -1738,22 +1841,26 @@ npm run build:web:docker:prod # Production Docker 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 @@ -1765,21 +1872,23 @@ npm run build:web:docker:prod # Production Docker build ### A.3 build-android.sh -**File**: `scripts/build-android.sh` -**Author**: Matthew Raymer -**Date**: 2025-07-11 +**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. +**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 +--test Build for testing environment --prod, --production Build for production environment --debug Build debug APK --release Build release APK @@ -1802,15 +1911,18 @@ npm run build:web:docker:prod # Production Docker build ``` **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 @@ -1823,14 +1935,16 @@ npm run build:web:docker:prod # Production Docker build ### A.4 build-ios.sh -**File**: `scripts/build-ios.sh` -**Author**: Matthew Raymer -**Date**: 2025-07-11 +**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. +**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] @@ -1861,15 +1975,18 @@ npm run build:web:docker:prod # Production Docker build ``` **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 @@ -1878,15 +1995,17 @@ npm run build:web:docker:prod # Production Docker build ### A.5 common.sh -**File**: `scripts/common.sh` -**Author**: Matthew Raymer +**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. +**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 @@ -1896,6 +2015,7 @@ 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 @@ -1903,6 +2023,7 @@ 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 @@ -1911,6 +2032,7 @@ clean_build_artifacts "dir" # Clean build artifacts directory ``` **Validation Functions**: + ```bash validate_build_environment # Validate common build environment setup_app_directories # Setup application directories @@ -1919,13 +2041,15 @@ print_header "title" # Print formatted header ### A.6 Cleaning Commands -**File**: `package.json` scripts -**Author**: Matthew Raymer +**File**: `package.json` scripts +**Author**: Matthew Raymer **Description**: Platform-specific and comprehensive cleaning commands -**Purpose**: Provides commands to clean build artifacts for individual platforms or all platforms at once. +**Purpose**: Provides commands to clean build artifacts for individual platforms +or all platforms at once. **Available Commands**: + ```bash # Platform-specific cleaning npm run clean:ios # Clean iOS build artifacts @@ -1944,26 +2068,31 @@ npm run build:electron:clean # Clean Electron build artifacts (via build scrip **Command Details**: **clean:ios**: + - Removes iOS build directories (`ios/App/build`, `ios/App/Pods`, etc.) - Cleans DerivedData and Capacitor artifacts - Safe to run multiple times **clean:android**: + - Uninstalls app from connected devices - Cleans Android build artifacts - Safe to run multiple times **clean:electron**: + - Cleans Electron build artifacts (`electron/build`, `electron/dist`, `electron/app`) - Removes TypeScript compilation artifacts - Safe to run multiple times **clean:all**: + - Executes all platform-specific clean commands in sequence - Stops on first failure (uses `&&` operator) - Most convenient for complete cleanup **Usage Examples**: + ```bash # Clean everything before a fresh build npm run clean:all @@ -1981,17 +2110,20 @@ npm run build:web:dev ## Appendix B: Vite Configuration Files Reference -This appendix provides detailed documentation for all Vite configuration files used in the TimeSafari build system. +This appendix provides detailed documentation for all Vite configuration files used +in the TimeSafari build system. ### B.1 vite.config.common.mts -**File**: `vite.config.common.mts` -**Author**: Matthew Raymer +**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 with unified environment handling and platform detection. +**Purpose**: Provides base configuration that is extended by platform-specific +configs with unified environment handling and platform detection. **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 and module aliases @@ -1999,6 +2131,7 @@ This appendix provides detailed documentation for all Vite configuration files u - **Dependency Management**: Handles platform-specific dependencies **Configuration Structure**: + ```typescript export async function createBuildConfig(platform: string): Promise { const appConfig = await loadAppConfig(); @@ -2066,25 +2199,29 @@ export async function createBuildConfig(platform: string): Promise { ``` **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 +**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. +**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 @@ -2094,6 +2231,7 @@ export async function createBuildConfig(platform: string): Promise { **Environment Configurations**: **Development Mode**: + ```typescript { build: { @@ -2110,6 +2248,7 @@ export async function createBuildConfig(platform: string): Promise { ``` **Test Mode**: + ```typescript { build: { @@ -2126,6 +2265,7 @@ export async function createBuildConfig(platform: string): Promise { ``` **Production Mode**: + ```typescript { build: { @@ -2151,6 +2291,7 @@ export async function createBuildConfig(platform: string): Promise { ``` **PWA Configuration**: + ```typescript VitePWA({ registerType: 'autoUpdate', @@ -2169,13 +2310,15 @@ VitePWA({ ### B.3 vite.config.electron.mts -**File**: `vite.config.electron.mts` -**Author**: Matthew Raymer +**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. +**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 @@ -2183,10 +2326,11 @@ VitePWA({ - **External Dependencies**: Properly handles Electron and native modules **Configuration Structure**: + ```typescript export default defineConfig(async () => { const baseConfig = await createBuildConfig("electron"); - + return { ...baseConfig, plugins: [ @@ -2220,24 +2364,28 @@ export default defineConfig(async () => { ``` **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 +**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. +**Purpose**: Provides minimal configuration for Capacitor builds, inheriting from +common config. **Configuration**: + ```typescript import { defineConfig } from "vite"; import { createBuildConfig } from "./vite.config.common.mts"; @@ -2246,6 +2394,7 @@ 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 @@ -2253,8 +2402,8 @@ export default defineConfig(async () => createBuildConfig('capacitor')); ### B.5 vite.config.utils.mts -**File**: `vite.config.utils.mts` -**Author**: Matthew Raymer +**File**: `vite.config.utils.mts` +**Author**: Matthew Raymer **Description**: Utility functions for Vite configuration **Purpose**: Provides shared configuration loading and PWA manifest generation. @@ -2266,6 +2415,7 @@ export default defineConfig(async () => createBuildConfig('capacitor')); **loadAppConfig()**: Loads complete application configuration including PWA settings **PWA Configuration**: + ```typescript interface PWAConfig { registerType: string; @@ -2284,11 +2434,13 @@ interface PWAConfig { ``` **Manifest Icons**: + - Android Chrome 192x192 PNG - Android Chrome 512x512 PNG - Maskable icons for adaptive UI **Share Target Configuration**: + ```typescript share_target: { action: "/share-target", @@ -2301,6 +2453,7 @@ share_target: { ``` **Alias Configuration**: + - `@`: Source directory alias - `buffer`: Buffer polyfill - `dexie-export-import`: Database import/export utilities @@ -2335,23 +2488,27 @@ source "$(dirname "$0")/common.sh" ### C.3 Build Process Flow **Web Build**: -``` + +```text build-web.sh → vite.config.web.mts → dist/ ``` **Electron Build**: -``` + +```text build-electron.sh → vite.config.electron.mts → electron/app/ ``` **Mobile Build**: -``` + +```text 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()` @@ -2360,20 +2517,25 @@ All scripts use consistent error handling: ### 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. +**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. diff --git a/CHANGELOG.md b/CHANGELOG.md index 19209fb6..641ff920 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,69 +6,88 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.0.7] - 2025.08.18 + ### Fixed -- Deep link for onboard-meeting-members +- Deep link for onboard-meeting-members ## [1.0.6] - 2025.08.09 + ### Fixed -- Deep link errors where none would validate +- Deep link errors where none would validate ## [1.0.5] - 2025.07.24 + ### Fixed -- Export & import of contacts corrupted contact methods +- Export & import of contacts corrupted contact methods ## [1.0.4] - 2025.07.20 - 002f2407208d56cc59c0aa7c880535ae4cbace8b + ### Fixed -- Deep link for invite-one-accept +- Deep link for invite-one-accept ## [1.0.3] - 2025.07.12 - a9a8ba217cd6015321911e98e6843e988dc2c4ae + ### Changed + - Photo is pinned to profile mode + ### Fixed + - Deep link URLs (and other prod settings) - Error in BVC begin view - ## [1.0.2] - 2025.06.20 - 276e0a741bc327de3380c4e508cccb7fee58c06d + ### Added -- Version on feed title +- Version on feed title ## [1.0.1] - 2025.06.20 + ### Added -- Allow a user to block someone else's content from view +- Allow a user to block someone else's content from view ## [1.0.0] - 2025.06.20 - 5aa693de6337e5dbb278bfddc6bd39094bc14f73 + ### Added -- Web-oriented migration from IndexedDB to SQLite +- Web-oriented migration from IndexedDB to SQLite ## [0.5.8] + ### Added + - /deep-link/ path for URLs that are shared with people + ### Changed + - External links now go to /deep-link/... - Feed visuals now have arrow imagery from giver to receiver - ## [0.4.7] + ### Fixed + - Cameras everywhere + ### Changed -- IndexedDB -> SQLite +- IndexedDB -> SQLite ## [0.4.5] - 2025.02.23 + ### Added + - Total amounts of gives on project page + ### Changed in DB or environment -- Requires Endorser.ch version 4.2.6+ +- Requires Endorser.ch version 4.2.6+ ## [0.4.4] - 2025.02.17 diff --git a/TASK_storage.md b/TASK_storage.md index a33cbb87..52b52b76 100644 --- a/TASK_storage.md +++ b/TASK_storage.md @@ -1,7 +1,6 @@ # What to do about storage for native apps? - ## Problem We can't trust iOS IndexedDB to persist. I want to start delivering an app to people now, in preparation for presentations mid-June: Rotary on June 12 and Porcfest on June 17. @@ -14,7 +13,6 @@ We can't trust iOS IndexedDB to persist. I want to start delivering an app to pe Also, with sensitive data, the accounts info should be encrypted. - # Options * There is a community [SQLite plugin for Capacitor](https://github.com/capacitor-community/sqlite) with encryption by [SQLCipher](https://github.com/sqlcipher/sqlcipher). @@ -29,16 +27,12 @@ Also, with sensitive data, the accounts info should be encrypted. * Not an option yet: Dexie may support SQLite in [a future version](https://dexie.org/roadmap/dexie5.0). - - # Current Plan * Implement SQLite for Capacitor & web, with encryption. That will allow us to test quickly and keep the same interface for native & web, but we don't deal with migrations for current web users. * After that is delivered, write a migration for current web users from IndexedDB to SQLite. - - # Current method calls ... which is not 100% complete because the AI that generated thus claimed no usage of 'temp' DB. @@ -80,5 +74,3 @@ Logs operations: db.logs.get(todayKey) - Gets logs for a specific day db.logs.update(todayKey, { message: fullMessage }) - Updates logs db.logs.clear() - Clears all logs - - diff --git a/doc/DEEP_LINKS.md b/doc/DEEP_LINKS.md index a6bf9f6b..8638074b 100644 --- a/doc/DEEP_LINKS.md +++ b/doc/DEEP_LINKS.md @@ -47,6 +47,7 @@ type ClaimParams = z.infer; ### Type Safety Layers 1. **Schema Definition** + ```typescript // src/interfaces/deepLinks.ts export const deepLinkSchemas = { @@ -59,6 +60,7 @@ type ClaimParams = z.infer; ``` 2. **Type Generation** + ```typescript // Types are automatically generated from schemas export type DeepLinkParams = { @@ -67,6 +69,7 @@ type ClaimParams = z.infer; ``` 3. **Runtime Validation** + ```typescript // In DeepLinkHandler const result = deepLinkSchemas.claim.safeParse(params); diff --git a/doc/README.md b/doc/README.md index 45e98fc4..3e876ca0 100644 --- a/doc/README.md +++ b/doc/README.md @@ -6,7 +6,7 @@ This uses Pandoc and BasicTex (LaTeX) Installed through Homebrew. ### Set Up -```bash +```bash brew install pandoc brew install basictex @@ -54,7 +54,7 @@ sudo tlmgr install sourceserifpro The following guide was adapted to this project except that we install with Brew and have a few more packages. -Guide: https://daniel.feldroy.com/posts/setting-up-latex-on-mac-os-x +Guide: ### Usage @@ -71,6 +71,7 @@ open usage-guide.pdf ``` Or use this one-liner + ```bash pandoc usage-guide.md -o usage-guide.pdf && open usage-guide.pdf ``` diff --git a/doc/architecture-decisions.md b/doc/architecture-decisions.md index 40fa3d3f..11861b8f 100644 --- a/doc/architecture-decisions.md +++ b/doc/architecture-decisions.md @@ -122,4 +122,4 @@ export default class HomeView extends Vue { --- -*This decision was made based on the current codebase architecture and team expertise. The mixin approach provides the best balance of performance, developer experience, and architectural consistency for the TimeSafari application.* \ No newline at end of file +*This decision was made based on the current codebase architecture and team expertise. The mixin approach provides the best balance of performance, developer experience, and architectural consistency for the TimeSafari application.* diff --git a/doc/asset-migration-plan.md b/doc/asset-migration-plan.md index 3a05353c..86c0954e 100644 --- a/doc/asset-migration-plan.md +++ b/doc/asset-migration-plan.md @@ -103,6 +103,7 @@ scripts/ ### Configuration Schema The schema enforces: + - Source files must be in `resources/` directory - Required fields for icon and splash sections - Android adaptive icon support (foreground/background/monochrome) diff --git a/doc/build-modernization-context.md b/doc/build-modernization-context.md index 133c2ad6..4f2ae09e 100644 --- a/doc/build-modernization-context.md +++ b/doc/build-modernization-context.md @@ -3,11 +3,13 @@ **Author:** Matthew Raymer ## Motivation + - Eliminate manual hacks and post-build scripts for Electron builds - Ensure maintainability, reproducibility, and security of build outputs - Unify build, test, and deployment scripts for developer experience and CI/CD ## Key Technical Decisions + - **Vite is the single source of truth for build output** - All Electron build output (main process, preload, renderer HTML/CSS/JS) is managed by `vite.config.electron.mts` - **CSS injection for Electron is handled by a Vite plugin** @@ -21,6 +23,7 @@ - Renderer assets: `dist-electron/www/` (HTML, CSS, JS) ## Security & Maintenance Checklist + - [x] All scripts and configs are committed and documented - [x] No manual file hacks remain - [x] All build output is deterministic and reproducible @@ -28,24 +31,29 @@ - [x] Documentation (`BUILDING.md`) is up to date ## How to Build Electron + 1. Run: + ```bash ./scripts/build-electron.sh ``` + 2. Output will be in `dist-electron/`: - `main.js`, `preload.js` in root - `www/` contains all renderer assets 3. No manual post-processing is required ## Customization + - **Vite config:** All build output and asset handling is controlled in `vite.config.electron.mts` - **CSS/HTML injection:** Use Vite plugins (see `electron-css-injection` in the config) for further customization - **Build scripts:** All orchestration is in `scripts/` and documented in `BUILDING.md` ## For Future Developers + - Always use Vite plugins/config for build output changes - Never manually edit built files or inject assets post-build - Keep documentation and scripts in sync with the build process --- -This file documents the context and rationale for the build modernization and should be included in the repository for onboarding and future reference. \ No newline at end of file +This file documents the context and rationale for the build modernization and should be included in the repository for onboarding and future reference. diff --git a/doc/circular-dependency-analysis.md b/doc/circular-dependency-analysis.md index 0ae322dc..a6530e62 100644 --- a/doc/circular-dependency-analysis.md +++ b/doc/circular-dependency-analysis.md @@ -13,27 +13,31 @@ The codebase currently has **no active circular dependencies** that are causing ### 🔍 **Resolved Dependency Patterns** #### 1. **Logger → PlatformServiceFactory → Logger** (RESOLVED) + - **Status**: ✅ **RESOLVED** - **Previous Issue**: Logger imported `logToDb` from databaseUtil, which imported logger - **Solution**: Logger now uses direct database access via PlatformServiceFactory - **Implementation**: Self-contained `logToDatabase()` function in logger.ts #### 2. **PlatformServiceMixin → databaseUtil → logger → PlatformServiceMixin** (RESOLVED) + - **Status**: ✅ **RESOLVED** - **Previous Issue**: PlatformServiceMixin imported `memoryLogs` from databaseUtil - **Solution**: Created self-contained `_memoryLogs` array in PlatformServiceMixin - **Implementation**: Self-contained memory logs implementation #### 3. **databaseUtil → logger → PlatformServiceFactory → databaseUtil** (RESOLVED) + - **Status**: ✅ **RESOLVED** - **Previous Issue**: databaseUtil imported logger, which could create loops - **Solution**: Logger is now self-contained and doesn't import from databaseUtil #### 4. **Utility Files → databaseUtil → PlatformServiceMixin** (RESOLVED) + - **Status**: ✅ **RESOLVED** - **Previous Issue**: `src/libs/util.ts` and `src/services/deepLinks.ts` imported from databaseUtil - **Solution**: Replaced with self-contained implementations and PlatformServiceFactory usage -- **Implementation**: +- **Implementation**: - Self-contained `parseJsonField()` and `mapQueryResultToValues()` functions - Direct PlatformServiceFactory usage for database operations - Console logging instead of databaseUtil logging functions @@ -43,18 +47,21 @@ The codebase currently has **no active circular dependencies** that are causing ### ✅ **All Critical Dependencies Resolved** #### PlatformServiceMixin Independence + - **Status**: ✅ **COMPLETE** - **Achievement**: PlatformServiceMixin has no external dependencies on databaseUtil - **Implementation**: Self-contained memory logs and utility functions - **Impact**: Enables complete migration of databaseUtil functions to PlatformServiceMixin #### Logger Independence + - **Status**: ✅ **COMPLETE** - **Achievement**: Logger is completely self-contained - **Implementation**: Direct database access via PlatformServiceFactory - **Impact**: Eliminates all circular dependency risks #### Utility Files Independence + - **Status**: ✅ **COMPLETE** - **Achievement**: All utility files no longer depend on databaseUtil - **Implementation**: Self-contained functions and direct platform service access @@ -63,6 +70,7 @@ The codebase currently has **no active circular dependencies** that are causing ### 🎯 **Migration Readiness Status** #### Files Ready for Migration (52 files) + 1. **Components** (15 files): - `PhotoDialog.vue` - `FeedFilters.vue` @@ -98,6 +106,7 @@ The codebase currently has **no active circular dependencies** that are causing ### 🟢 **Healthy Dependencies** #### Logger Usage (80+ files) + - **Status**: ✅ **HEALTHY** - **Pattern**: All files import logger from `@/utils/logger` - **Impact**: No circular dependencies, logger is self-contained @@ -106,21 +115,25 @@ The codebase currently has **no active circular dependencies** that are causing ## Resolution Strategy - COMPLETED ### ✅ **Phase 1: Complete PlatformServiceMixin Independence (COMPLETE)** + 1. **Removed memoryLogs import** from PlatformServiceMixin ✅ 2. **Created self-contained memoryLogs** implementation ✅ 3. **Added missing utility methods** to PlatformServiceMixin ✅ ### ✅ **Phase 2: Utility Files Migration (COMPLETE)** + 1. **Migrated deepLinks.ts** - Replaced databaseUtil logging with console logging ✅ 2. **Migrated util.ts** - Replaced databaseUtil functions with self-contained implementations ✅ 3. **Updated all PlatformServiceFactory calls** to use async pattern ✅ ### 🎯 **Phase 3: File-by-File Migration (READY TO START)** + 1. **High-usage files first** (views, core components) 2. **Replace databaseUtil imports** with PlatformServiceMixin 3. **Update function calls** to use mixin methods ### 🎯 **Phase 4: Cleanup (FUTURE)** + 1. **Remove unused databaseUtil functions** 2. **Update TypeScript interfaces** 3. **Remove databaseUtil imports** from all files @@ -128,6 +141,7 @@ The codebase currently has **no active circular dependencies** that are causing ## Current Status Summary ### ✅ **Resolved Issues** + 1. **Logger circular dependency** - Fixed with self-contained implementation 2. **PlatformServiceMixin circular dependency** - Fixed with self-contained memoryLogs 3. **Utility files circular dependency** - Fixed with self-contained implementations @@ -135,6 +149,7 @@ The codebase currently has **no active circular dependencies** that are causing 5. **Runtime stability** - No circular dependency crashes ### 🎯 **Ready for Next Phase** + 1. **52 files** ready for databaseUtil migration 2. **PlatformServiceMixin** fully independent and functional 3. **Clear migration path** - Well-defined targets and strategy @@ -142,6 +157,7 @@ The codebase currently has **no active circular dependencies** that are causing ## Benefits of Current State ### ✅ **Achieved** + 1. **No runtime circular dependencies** - Application runs without crashes 2. **Self-contained logger** - No more logger/databaseUtil loops 3. **PlatformServiceMixin ready** - All methods implemented and independent @@ -149,6 +165,7 @@ The codebase currently has **no active circular dependencies** that are causing 5. **Clear migration path** - Well-defined targets and strategy ### 🎯 **Expected After Migration** + 1. **Complete databaseUtil migration** - Single source of truth 2. **Eliminated circular dependencies** - Clean architecture 3. **Improved performance** - Caching and optimization @@ -160,4 +177,4 @@ The codebase currently has **no active circular dependencies** that are causing **Created**: 2025-07-05 **Status**: ✅ **COMPLETE - All Circular Dependencies Resolved** **Last Updated**: 2025-01-06 -**Note**: PlatformServiceMixin circular dependency completely resolved. Ready for Phase 2: File-by-File Migration \ No newline at end of file +**Note**: PlatformServiceMixin circular dependency completely resolved. Ready for Phase 2: File-by-File Migration diff --git a/doc/component-communication-guide.md b/doc/component-communication-guide.md index 1fad5968..797e5740 100644 --- a/doc/component-communication-guide.md +++ b/doc/component-communication-guide.md @@ -93,6 +93,7 @@ export default class FormComponent extends Vue { When generating component templates, follow these patterns: #### Function Props Template + ```vue