# PWA Setup

**For AI Agents:** Enable PWA in config, add required app metadata. Framework handles service worker, manifest, and caching.

---

## Quick Start

### 1. Add Required App Metadata

PWA requires `name`, `shortName`, and `description` in your app config:

```typescript
// src/config/app.ts
import type { AppConfig } from '@donotdev/core';

export const appConfig: AppConfig = {
  app: {
    name: 'My App',              // Full app name (required for PWA)
    shortName: 'App',            // Short name for home screen (required for PWA)
    description: 'My app description', // App description (required for PWA)
    url: 'https://myapp.com',
  },
  // ... rest of config
};
```

### 2. Enable PWA in Build Config

**For Vite apps:**

```typescript
// vite.config.ts
import { defineViteConfig } from '@donotdev/core/vite';
import { appConfig } from './src/config/app';

export default defineViteConfig({
  appConfig,
  pwa: {
    enabled: true,        // Enable PWA in production builds
    devEnabled: false,   // Enable PWA in development (optional)
  },
});
```

**For Next.js apps:**

```typescript
// next.config.ts
import { defineNextConfig } from '@donotdev/core/next';
import { appConfig } from './src/config/app';

export default defineNextConfig({
  appConfig,
  pwa: {
    enabled: true,        // Enable PWA in production builds
    devEnabled: false,   // Enable PWA in development (optional)
  },
});
```

**Done.** Framework automatically:
- Generates `manifest.json` from app metadata
- Creates service worker with Workbox
- Discovers and precaches app icons
- Sets up offline caching strategies

---

## What Gets Auto-Generated

### Manifest (`manifest.json`)
- **Name & description:** From `appConfig.app.name`, `shortName`, `description`
- **Icons:** Auto-discovered from `public/` folder (favicon, apple-touch-icon, etc.)
- **Theme colors:** Defaults to white background, black theme (customizable)
- **Display mode:** `standalone` (app-like experience)

### Service Worker (`sw.js`)
- **Precaching:** All JS, CSS, HTML, icons, and fonts
- **Runtime caching:** Smart defaults for API calls and images
- **Offline support:** Navigation fallback to `/`
- **Update strategy:** Prompts user to update when new version available

### Icons
Framework discovers icons from:
- `public/favicon.svg` or `public/favicon.ico`
- `public/apple-touch-icon.png`
- Any icons generated by AssetPlugin

---

## Optional Configuration

### Custom Manifest Values

```typescript
// vite.config.ts or next.config.ts
export default defineViteConfig({
  appConfig,
  pwa: {
    enabled: true,
    manifest: {
      // Override any manifest values
      theme_color: '#667eea',
      background_color: '#ffffff',
      display: 'standalone',
      orientation: 'portrait',
    },
  },
});
```

### Custom Workbox Configuration

```typescript
pwa: {
  enabled: true,
  workbox: {
    // Maximum file size to cache (default: 5MB)
    maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
    
    // Custom precache patterns
    globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2}'],
    globIgnores: ['**/node_modules/**'],
    
    // Runtime caching strategies
    runtimeCaching: [
      {
        urlPattern: /^https:\/\/api\.example\.com\/.*/i,
        handler: 'NetworkFirst',
        options: {
          cacheName: 'api-cache',
          expiration: {
            maxEntries: 50,
            maxAgeSeconds: 60 * 60, // 1 hour
          },
        },
      },
    ],
  },
},
```

### Development Mode

Enable PWA in development for testing:

```typescript
pwa: {
  enabled: true,
  devEnabled: true,  // Enable service worker in dev mode
  debug: true,       // Enable debug logging
},
```

**Note:** Service workers require HTTPS (or localhost). Use `server: { https: true }` in Vite config for local HTTPS.

---

## Testing PWA

1. **Build for production:**
   ```bash
   bun run build
   ```

2. **Serve production build:**
   ```bash
   bun run preview  # Vite
   # or
   bun run start    # Next.js
   ```

3. **Test in browser:**
   - Open DevTools → Application → Service Workers
   - Check "Offline" checkbox to test offline mode
   - Verify manifest in Application → Manifest
   - Test "Add to Home Screen" prompt

---

## Requirements Checklist

- [ ] `appConfig.app.name` defined
- [ ] `appConfig.app.shortName` defined
- [ ] `appConfig.app.description` defined
- [ ] `pwa.enabled: true` in build config
- [ ] Icons in `public/` folder (auto-discovered)
- [ ] HTTPS in production (required for service workers)

---

## Troubleshooting

**PWA not working:**
- Check browser console for service worker errors
- Verify HTTPS (required except localhost)
- Check manifest.json exists in build output
- Verify app metadata is complete

**Icons not showing:**
- Ensure icons exist in `public/` folder
- Check icon formats (SVG, PNG, ICO supported)
- Verify AssetPlugin discovered icons (check build logs)

**Service worker not registering:**
- Check browser console for registration errors
- Verify HTTPS (service workers require secure context)
- Clear browser cache and hard refresh

---

**Zero config. Override when needed.**
