# Development & Test-Fix Workflow for BinectChrome

This guide explains how to set up an efficient development workflow for testing and debugging the Chrome extension.

## Quick Start

### 1. Development Mode (Auto-rebuild on changes)
```bash
npm run dev
```
This starts webpack in watch mode - any changes to source files will automatically rebuild the extension.

### 2. Load Extension in Chrome

**Initial Load:**
1. Open Chrome and navigate to `chrome://extensions/`
2. Enable "Developer mode" (toggle in top-right corner)
3. Click "Load unpacked"
4. Select the `/home/worsch/binect-chrome/dist` directory
5. Note the extension ID (you'll need this for debugging)

**Reload After Changes:**
- **Option A (Manual):** Click the reload icon on the extension card at `chrome://extensions/`
- **Option B (Shortcut):** Click the extensions icon in Chrome toolbar → Manage Extensions → Reload
- **Option C (Recommended for service worker):** Navigate to `chrome://serviceworker-internals/` and click "Stop" then reload

### 3. Debug Service Worker

**View Service Worker Logs:**
1. Go to `chrome://extensions/`
2. Find your extension
3. Click "service worker" link (under "Inspect views")
4. This opens DevTools for the service worker

**Alternative Method:**
1. Go to `chrome://serviceworker-internals/`
2. Find "chrome-extension://[your-extension-id]"
3. Click "Inspect" to open DevTools

**View Service Worker Status:**
- `chrome://serviceworker-internals/` - Shows all service workers, their status, and errors

### 4. Debug Popup & UI

**Popup DevTools:**
1. Click the extension icon to open the popup
2. Right-click inside the popup → "Inspect"
3. This opens DevTools for the popup

**Tracking Page DevTools:**
1. Open the tracking page from the popup
2. Right-click → "Inspect"

## Complete Test-Fix Loop

### Workflow Pattern
```
┌─────────────────────────────────────────────────┐
│  1. Make code changes in src/                   │
│  2. Webpack auto-rebuilds (if using npm run dev)│
│  3. Reload extension in Chrome                  │
│  4. Check DevTools for errors                   │
│  5. Test functionality                          │
│  6. Repeat from step 1                          │
└─────────────────────────────────────────────────┘
```

### Detailed Steps

1. **Start Development Mode**
   ```bash
   npm run dev
   ```

2. **Make Your Changes**
   - Edit files in `src/`
   - Webpack will automatically rebuild

3. **Reload Extension**
   - Go to `chrome://extensions/`
   - Click reload icon on BinectChrome card
   - For service worker changes: Go to `chrome://serviceworker-internals/` → Stop → Reload

4. **Check for Errors**
   - **Service Worker:** Click "service worker" link or check `chrome://serviceworker-internals/`
   - **Popup:** Right-click popup → Inspect
   - **Console Errors:** Check the browser console in all DevTools windows

5. **Test Functionality**
   - Download a PDF to test detection
   - Check badge updates
   - Test sending PDFs
   - Verify tracking data

6. **Common Debugging Points**
   - Service worker errors: Usually permissions or API usage issues
   - PDF detection not working: Check Downloads API events
   - Badge not updating: Check service worker is running
   - Alarms not firing: Check `chrome://serviceworker-internals/` for service worker lifecycle

## Common Issues & Solutions

### Issue: Service Worker Registration Failed (Status Code 15)
**Cause:** Webpack output format doesn't match manifest type
**Solution:** Ensure webpack.config.js has:
```javascript
output: {
  module: true,
  environment: { module: true }
},
experiments: {
  outputModule: true
}
```

### Issue: "Cannot read properties of undefined (reading 'onAlarm')"
**Cause:** Missing "alarms" permission
**Solution:** Add to manifest.json:
```json
"permissions": ["downloads", "storage", "alarms"]
```

### Issue: Service Worker Stops Running
**Cause:** Chrome stops inactive service workers after 30 seconds (Manifest V3 behavior)
**Solution:** This is normal! Service workers wake up on events (downloads, alarms, messages)

### Issue: Changes Not Reflecting
**Cause:** Extension not reloaded, or cached service worker
**Solution:**
1. Always reload after rebuilding
2. For stubborn issues: Stop service worker at `chrome://serviceworker-internals/`
3. Hard reload: Remove extension and re-add it

## Testing Specific Features

### Test PDF Detection
1. Ensure extension is loaded and service worker is running
2. Download any PDF file from the web
3. Check service worker console for "PDF detected:" log
4. Verify badge shows "1"
5. Open popup and verify PDF info is displayed

### Test Credential Management
1. Open popup
2. Enter credentials
3. Check Chrome DevTools → Application → Storage → Extension Storage
4. Verify credentials are encrypted
5. Test credential expiry by manipulating storage

### Test Alarm/Expiry Check
1. Open `chrome://serviceworker-internals/`
2. Check for alarm registration
3. Or use: `chrome.alarms.getAll(console.log)` in service worker console

## Production Build & Testing

```bash
# Build for production
npm run build

# Build is in dist/ directory
# Test the production build by loading dist/ as unpacked extension
```

## Running Unit Tests

```bash
# Run tests once
npm test

# Run tests in watch mode
npm run test:watch

# Type checking
npm run type-check

# Linting
npm run lint
npm run lint:fix
```

## Useful Chrome URLs for Extension Development

- `chrome://extensions/` - Manage extensions
- `chrome://serviceworker-internals/` - Debug service workers
- `chrome://inspect/#service-workers` - Inspect active service workers
- `chrome://downloads/` - View downloads (for testing PDF detection)
- `chrome://version/` - Check Chrome version

## Debugging Tips

1. **Console.log is your friend**: Add logs liberally in development
2. **Breakpoints**: Use debugger; statements or set breakpoints in DevTools
3. **Storage inspection**: Check Application → Storage → Extension Storage in DevTools
4. **Network tab**: Monitor API calls to Binect
5. **Performance**: Use Performance tab to check service worker lifecycle
6. **Memory**: Watch for memory leaks in long-running service workers

## VS Code Integration (Optional)

Add to `.vscode/launch.json` for debugging:
```json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "chrome",
      "request": "launch",
      "name": "Debug Extension",
      "url": "chrome://extensions/",
      "webRoot": "${workspaceFolder}/dist"
    }
  ]
}
```

## Quick Reference Commands

```bash
# Development
npm run dev              # Watch mode with auto-rebuild
npm run build           # Production build
npm test                # Run tests
npm run lint            # Check code quality
npm run type-check      # TypeScript validation

# Chrome URLs
chrome://extensions/              # Extension management
chrome://serviceworker-internals/ # Service worker debugging
```

## Emergency Cleanup

If extension gets stuck or behaves oddly:
```bash
# 1. Stop service worker
# Go to chrome://serviceworker-internals/ → Stop

# 2. Clear extension storage
# DevTools → Application → Storage → Clear site data

# 3. Remove and reload extension
# chrome://extensions/ → Remove → Load unpacked again

# 4. Clean rebuild
rm -rf dist/
npm run build
```
