✅ All 169 tests passing ✅ Service worker registration working correctly ✅ Push notifications enabled ✅ Test environment properly isolated Final implementation includes: - Fixed vite.config.ts configuration for proper service worker registration - Environment-aware registration (disabled in tests, enabled in dev/prod) - Documentation and outcome report completed - Branch ready for merge Refs: docs/plans/FixServiceWorkerDevRegistrationIssues.md
531 lines
21 KiB
Markdown
531 lines
21 KiB
Markdown
# Execution Plan: Fix Service Worker Development Registration Issues
|
|
|
|
**Created:** 2025-12-22
|
|
**Status:** Planning
|
|
**Priority:** Critical - Service Worker registration failing in development and tests
|
|
**Outcome Name:** FixServiceWorkerDevRegistrationIssues
|
|
|
|
---
|
|
|
|
## Executive Summary
|
|
|
|
The service worker registration is failing in both development mode and test environments with the error: `"SecurityError: Failed to register a ServiceWorker for scope ('https://localhost:63315/') with script ('https://localhost:63315/dev-sw.js?dev-sw'): An unknown error occurred when fetching the script."`
|
|
|
|
**Root Cause Analysis:** The vite-pwa plugin is generating a registration script that tries to fetch `/dev-sw.js?dev-sw` in development mode, but this file doesn't exist. The actual development service worker is generated as `sw.js` in the `dev-dist` directory, but it's not being served at the path expected by the registration script.
|
|
|
|
This is a critical issue because:
|
|
1. **Push notifications are essential** for the app's core functionality
|
|
2. **PWA features are broken** in development, preventing proper testing
|
|
3. **Test suite has unhandled errors** due to service worker registration failures
|
|
4. **Development workflow is impaired** without working service worker functionality
|
|
|
|
---
|
|
|
|
## Current State Analysis
|
|
|
|
### Identified Issues
|
|
|
|
**Problem 1: File Path Mismatch**
|
|
- Registration script: `/dev-dist/registerSW.js` tries to load `/dev-sw.js?dev-sw`
|
|
- Actual development service worker: `/dev-dist/sw.js`
|
|
- Result: 404 error because `dev-sw.js` doesn't exist
|
|
|
|
**Problem 2: Development Server Path Mapping**
|
|
- Development server not serving service worker at expected registration path
|
|
- Service worker generated in `dev-dist/` but not accessible at root level
|
|
- Vite-pwa development configuration mismatch
|
|
|
|
**Problem 3: Test Environment Impact**
|
|
- Service worker registration failures causing unhandled promise rejections
|
|
- Tests reporting service worker errors even when not directly testing service worker
|
|
- Registration errors interfering with test stability
|
|
|
|
### Current Configuration Analysis
|
|
|
|
**Vite Configuration Status:**
|
|
```typescript
|
|
// vite.config.ts - Current Configuration
|
|
SvelteKitPWA({
|
|
strategies: 'injectManifest',
|
|
filename: 'service-worker.ts', // Source file
|
|
devOptions: {
|
|
enabled: true,
|
|
suppressWarnings: true,
|
|
navigateFallback: '/',
|
|
type: 'module' // ← Potential issue
|
|
}
|
|
})
|
|
```
|
|
|
|
**SvelteKit Configuration Status:**
|
|
```javascript
|
|
// svelte.config.js - Correctly configured
|
|
serviceWorker: {
|
|
register: false // ✅ Properly disabled
|
|
}
|
|
```
|
|
|
|
**Service Worker Implementation Status:**
|
|
- ✅ 270-line custom service worker with comprehensive push notification handling
|
|
- ✅ Workbox precaching and navigation routing properly implemented
|
|
- ✅ Background sync and message handling functional
|
|
- ✅ Error handling and logging throughout
|
|
- ❌ Registration failing due to development file path issues
|
|
|
|
---
|
|
|
|
## Impact Assessment
|
|
|
|
### Business Impact
|
|
- **High**: Push notifications are critical for user experience
|
|
- **High**: PWA functionality is a core application feature
|
|
- **Medium**: Development workflow disruption affecting team productivity
|
|
|
|
### Technical Impact
|
|
- **Critical**: Service worker registration completely broken in development
|
|
- **High**: Test suite reporting unhandled errors affecting reliability
|
|
- **Medium**: Unable to test PWA features during development
|
|
|
|
### User Impact
|
|
- **High**: Push notifications not working affects core functionality
|
|
- **Medium**: PWA installation and offline features not testable in development
|
|
- **Low**: Production deployments may still work if issue is development-only
|
|
|
|
---
|
|
|
|
## Root Cause Deep Dive
|
|
|
|
### Primary Cause: Vite-PWA Development Path Configuration
|
|
|
|
**Investigation Findings:**
|
|
1. **Registration Script Generated**: `/dev-dist/registerSW.js` contains:
|
|
```javascript
|
|
navigator.serviceWorker.register('/dev-sw.js?dev-sw', { scope: '/', type: 'module' })
|
|
```
|
|
|
|
2. **Actual Service Worker File**: `/dev-dist/sw.js` exists but not at expected path
|
|
|
|
3. **Path Mapping Issue**: Development server doesn't serve `/dev-sw.js?dev-sw`
|
|
|
|
4. **Module Type Issue**: `type: 'module'` in devOptions may be causing path generation issues
|
|
|
|
### Secondary Causes
|
|
|
|
**Development Server Middleware:**
|
|
- Vite development server not properly mapping service worker paths
|
|
- HTTPS configuration may be interfering with service worker serving
|
|
- Static file serving rules not configured for development service worker
|
|
|
|
**Test Environment Complications:**
|
|
- Service worker registration attempted during test runs
|
|
- Test environment doesn't need service worker but registration still attempted
|
|
- Unhandled promise rejections affecting test stability
|
|
|
|
---
|
|
|
|
## Solution Architecture
|
|
|
|
### Hexagonal Architecture Compliance
|
|
|
|
The service worker sits at the **Primary Adapter (Inbound)** layer:
|
|
|
|
```
|
|
┌─────────────────────────────────────────────────┐
|
|
│ Primary Adapters (Inbound) │
|
|
│ ┌─────────────────────────────────────────────┐│
|
|
│ │ Service Worker (PWA Adapter) ││ ← FIX NEEDED
|
|
│ │ - Push notification handling ││
|
|
│ │ - Offline functionality ││
|
|
│ │ - Background sync ││
|
|
│ │ - Cache management ││
|
|
│ └─────────────────────────────────────────────┘│
|
|
│ │ Other Adapters: Web UI, Share Handler │
|
|
└─────────────────┬───────────────────────────────┘
|
|
│
|
|
┌─────────────────┴───────────────────────────────┐
|
|
│ Domain (Core) - UNAFFECTED │
|
|
│ │ Queue Management │
|
|
│ │ Recipe Processing │
|
|
│ │ Push Notification Domain Logic │
|
|
│ │ Background Job Processing │
|
|
└─────────────────┬───────────────────────────────┘
|
|
│
|
|
┌─────────────────┴───────────────────────────────┐
|
|
│ Secondary Adapters (Outbound) │
|
|
│ │ Instagram API, LLM Services, Tandoor API │
|
|
│ │ Push Notification Service - UNAFFECTED │
|
|
└─────────────────────────────────────────────────┘
|
|
```
|
|
|
|
**Key Architectural Insights:**
|
|
- Service worker failure only affects PWA adapter layer
|
|
- Core domain logic (queue processing, notifications) remains unaffected
|
|
- Push notification domain logic works; only delivery mechanism (service worker) is broken
|
|
- Fix involves only adapter configuration, not business logic
|
|
|
|
### Technical Solution Design
|
|
|
|
**Solution 1: Fix Development Service Worker Path Configuration**
|
|
|
|
```typescript
|
|
// Enhanced vite.config.ts configuration
|
|
SvelteKitPWA({
|
|
strategies: 'injectManifest',
|
|
filename: 'service-worker.ts',
|
|
srcDir: './src',
|
|
scope: '/',
|
|
base: '/',
|
|
mode: process.env.NODE_ENV === 'production' ? 'production' : 'development',
|
|
injectManifest: {
|
|
swSrc: 'src/service-worker.ts',
|
|
swDest: 'service-worker.js',
|
|
injectionPoint: 'self.__WB_MANIFEST'
|
|
},
|
|
devOptions: {
|
|
enabled: true,
|
|
suppressWarnings: true,
|
|
navigateFallback: '/',
|
|
// Remove 'type: module' - may be causing path issues
|
|
// Add explicit service worker path configuration
|
|
swUrl: '/service-worker.js' // Force specific path
|
|
},
|
|
// ... rest of configuration
|
|
})
|
|
```
|
|
|
|
**Solution 2: Test Environment Service Worker Bypass**
|
|
|
|
```typescript
|
|
// Add test environment detection
|
|
devOptions: {
|
|
enabled: process.env.NODE_ENV !== 'test', // Disable in test environment
|
|
suppressWarnings: true,
|
|
navigateFallback: '/'
|
|
}
|
|
```
|
|
|
|
**Solution 3: Development Server Middleware Enhancement**
|
|
|
|
Ensure proper service worker serving in development mode through Vite configuration.
|
|
|
|
---
|
|
|
|
## Story Breakdown
|
|
|
|
### Story 1: Fix Development Service Worker Path Configuration
|
|
|
|
**Priority:** Critical
|
|
**Dependencies:** None
|
|
**Estimated Effort:** 2-3 hours
|
|
|
|
**Objective:** Fix the vite-pwa development configuration to generate service worker at correct path and ensure registration script matches.
|
|
|
|
**Root Cause:** Development service worker generated at wrong path, registration script references non-existent file.
|
|
|
|
**Technical Approach:**
|
|
1. **Remove problematic devOptions**: Remove `type: 'module'` which may be causing path generation issues
|
|
2. **Add explicit path configuration**: Specify service worker URL explicitly
|
|
3. **Verify development server mapping**: Ensure Vite serves service worker correctly
|
|
4. **Test registration path**: Confirm registration script matches actual file location
|
|
|
|
**Acceptance Criteria:**
|
|
- ✅ Service worker registration succeeds in development mode
|
|
- ✅ Registration script references existing service worker file
|
|
- ✅ Development server serves service worker at expected path
|
|
- ✅ No "unknown error occurred when fetching the script" errors
|
|
- ✅ Push notifications work in development environment
|
|
|
|
**Files Modified:**
|
|
- `vite.config.ts` - Update SvelteKitPWA devOptions configuration
|
|
- Verify `dev-dist/` generated files match registration expectations
|
|
|
|
---
|
|
|
|
### Story 2: Add Test Environment Service Worker Handling
|
|
|
|
**Priority:** High
|
|
**Dependencies:** Story 1
|
|
**Estimated Effort:** 1-2 hours
|
|
|
|
**Objective:** Prevent service worker registration failures from affecting test suite reliability.
|
|
|
|
**Root Cause:** Tests attempting service worker registration when not needed, causing unhandled promise rejections.
|
|
|
|
**Technical Approach:**
|
|
1. **Environment Detection**: Add test environment detection in service worker configuration
|
|
2. **Conditional Registration**: Only register service worker in appropriate environments
|
|
3. **Test Cleanup**: Ensure test environment doesn't trigger service worker registration
|
|
4. **Error Handling**: Add graceful handling for service worker failures in test environment
|
|
|
|
**Acceptance Criteria:**
|
|
- ✅ Test suite runs without service worker registration errors
|
|
- ✅ No unhandled promise rejections from service worker registration
|
|
- ✅ Tests complete without service worker interference
|
|
- ✅ Service worker still works in development and production environments
|
|
|
|
**Files Modified:**
|
|
- `vite.config.ts` - Add test environment conditional
|
|
- Test configuration files if needed
|
|
|
|
---
|
|
|
|
### Story 3: Verify Push Notification Functionality Preservation
|
|
|
|
**Priority:** Critical
|
|
**Dependencies:** Story 1, Story 2
|
|
**Estimated Effort:** 2-3 hours
|
|
|
|
**Objective:** Ensure all push notification functionality continues to work after service worker registration fixes.
|
|
|
|
**Root Cause:** Changes to service worker configuration must not break existing push notification features.
|
|
|
|
**Technical Approach:**
|
|
1. **Push Registration Testing**: Verify push notification subscription still works
|
|
2. **Custom Actions Testing**: Test notification action buttons (view, retry, dismiss)
|
|
3. **Background Sync Testing**: Verify background sync for retry operations
|
|
4. **Message Passing Testing**: Test service worker to client communication
|
|
5. **Cross-Browser Testing**: Verify functionality across different browsers
|
|
|
|
**Acceptance Criteria:**
|
|
- ✅ Push notification subscription works correctly
|
|
- ✅ Custom notification actions function as expected
|
|
- ✅ Background sync for retry operations operational
|
|
- ✅ Service worker message handling works
|
|
- ✅ Push notifications display with correct content and actions
|
|
- ✅ Cross-browser compatibility maintained (Chrome, Firefox, Safari, Edge)
|
|
|
|
**Files Modified:**
|
|
- Verify `src/service-worker.ts` functionality unchanged
|
|
- Test push notification workflows
|
|
|
|
---
|
|
|
|
### Story 4: Enhance Development and Production Service Worker Testing
|
|
|
|
**Priority:** Medium
|
|
**Dependencies:** Story 1, Story 2, Story 3
|
|
**Estimated Effort:** 1-2 hours
|
|
|
|
**Objective:** Add comprehensive testing for service worker functionality in both development and production environments.
|
|
|
|
**Root Cause:** Need reliable testing to prevent future service worker registration issues.
|
|
|
|
**Technical Approach:**
|
|
1. **Development Mode Testing**: Create test scripts for development service worker
|
|
2. **Production Build Testing**: Verify production service worker generation
|
|
3. **Registration Flow Testing**: Test complete service worker registration flow
|
|
4. **Error Scenario Testing**: Test graceful handling of service worker failures
|
|
|
|
**Acceptance Criteria:**
|
|
- ✅ Development service worker can be tested reliably
|
|
- ✅ Production builds generate correct service worker files
|
|
- ✅ Registration flow works in both environments
|
|
- ✅ Error scenarios handled gracefully
|
|
- ✅ Documentation for testing service worker functionality
|
|
|
|
**Files Modified:**
|
|
- Add development testing utilities
|
|
- Update documentation for service worker testing
|
|
|
|
---
|
|
|
|
## Implementation Strategy
|
|
|
|
### Phase 1: Core Service Worker Registration Fix (Day 1)
|
|
|
|
**Hours 1-3: Diagnose and Fix Configuration**
|
|
1. **Current State Analysis**:
|
|
- Verify current file generation in `dev-dist/`
|
|
- Examine registration script content
|
|
- Test current service worker registration behavior
|
|
|
|
2. **Configuration Updates**:
|
|
- Modify `vite.config.ts` devOptions
|
|
- Remove problematic `type: 'module'` setting
|
|
- Add explicit service worker path configuration
|
|
|
|
3. **Verification Testing**:
|
|
- Test development server startup
|
|
- Verify service worker registration succeeds
|
|
- Check for absence of registration errors
|
|
|
|
**Hours 4-6: Test Environment Fixes**
|
|
1. **Test Environment Configuration**:
|
|
- Add environment detection to service worker config
|
|
- Disable service worker registration in test environment
|
|
- Verify test suite runs cleanly
|
|
|
|
2. **Regression Testing**:
|
|
- Run full test suite to ensure no regressions
|
|
- Verify test environment service worker handling
|
|
- Check for unhandled promise rejections
|
|
|
|
### Phase 2: Push Notification Verification (Day 1-2)
|
|
|
|
**Hours 6-9: Push Notification Testing**
|
|
1. **Functionality Verification**:
|
|
- Test push notification subscription
|
|
- Verify custom notification actions
|
|
- Test background sync and retry mechanisms
|
|
|
|
2. **Cross-Browser Testing**:
|
|
- Test in Chrome, Firefox, Safari
|
|
- Verify service worker registration across browsers
|
|
- Test push notification display and interaction
|
|
|
|
3. **Integration Testing**:
|
|
- Test complete queue processing with notifications
|
|
- Verify service worker message passing
|
|
- Test offline functionality if applicable
|
|
|
|
### Phase 3: Production Readiness (Day 2)
|
|
|
|
**Hours 9-12: Production Testing and Documentation**
|
|
1. **Production Build Testing**:
|
|
- Generate production build
|
|
- Verify service worker files generated correctly
|
|
- Test production service worker registration
|
|
|
|
2. **Documentation and Monitoring**:
|
|
- Document service worker testing procedures
|
|
- Add monitoring for service worker registration success
|
|
- Create troubleshooting guide
|
|
|
|
---
|
|
|
|
## Risk Assessment
|
|
|
|
### High Risk Items
|
|
|
|
**Configuration Changes Breaking Production**
|
|
- **Risk**: Changes to vite-pwa configuration affect production builds
|
|
- **Impact**: Production service worker registration could fail
|
|
- **Mitigation**: Thorough testing in development before production deployment
|
|
- **Rollback**: Keep backup of working vite.config.ts
|
|
|
|
**Push Notification Regression**
|
|
- **Risk**: Service worker changes break push notification functionality
|
|
- **Impact**: Core app feature stops working for users
|
|
- **Mitigation**: Comprehensive push notification testing before deployment
|
|
- **Rollback**: Service worker configuration is easily reversible
|
|
|
|
### Medium Risk Items
|
|
|
|
**Cross-Browser Compatibility**
|
|
- **Risk**: Service worker changes work in some browsers but not others
|
|
- **Impact**: Partial user base loses PWA functionality
|
|
- **Mitigation**: Test in all major browsers during development
|
|
- **Rollback**: Browser-specific service worker configuration if needed
|
|
|
|
**Test Environment Disruption**
|
|
- **Risk**: Changes affect test environment stability
|
|
- **Impact**: CI/CD pipeline reliability issues
|
|
- **Mitigation**: Thorough testing of test environment changes
|
|
- **Rollback**: Environment-specific configuration rollback
|
|
|
|
### Low Risk Items
|
|
|
|
**Development Workflow Changes**
|
|
- **Risk**: Service worker changes affect development hot reloading
|
|
- **Impact**: Developer experience degradation
|
|
- **Mitigation**: Test development workflow thoroughly
|
|
- **Rollback**: Development-specific configuration adjustment
|
|
|
|
---
|
|
|
|
## Success Criteria
|
|
|
|
### Primary Success Metrics
|
|
|
|
**Must Have:**
|
|
1. ✅ Service worker registration succeeds in development mode without errors
|
|
2. ✅ Test suite runs without service worker registration failures
|
|
3. ✅ Push notifications continue to work exactly as before
|
|
4. ✅ PWA functionality (installation, offline) works in development
|
|
|
|
**Should Have:**
|
|
5. ✅ Service worker registration works across all major browsers
|
|
6. ✅ Production builds generate correct service worker files
|
|
7. ✅ Background sync and retry mechanisms continue to function
|
|
8. ✅ Development workflow remains smooth with working service worker
|
|
|
|
**Nice to Have:**
|
|
9. ✅ Enhanced service worker testing capabilities
|
|
10. ✅ Better error handling for service worker failures
|
|
11. ✅ Documentation for service worker troubleshooting
|
|
12. ✅ Monitoring capabilities for service worker registration success
|
|
|
|
### Validation Approach
|
|
|
|
**Development Environment:**
|
|
- Ask the user to test service worker registration.
|
|
|
|
**Test Environment:**
|
|
- Run test suite: `npm run test`
|
|
- Verify no unhandled promise rejections
|
|
- Check test completion without service worker errors
|
|
- Validate test environment isolation from service worker
|
|
|
|
**Production Environment:**
|
|
- Generate production build: `npm run build`
|
|
- Verify service worker files generated correctly
|
|
|
|
---
|
|
|
|
## Dependencies and Prerequisites
|
|
|
|
### Technical Dependencies
|
|
- **SvelteKit**: Service worker integration depends on SvelteKit configuration
|
|
- **Vite**: Development server must properly serve service worker files
|
|
- **@vite-pwa/sveltekit**: Plugin configuration must generate correct registration scripts
|
|
- **Workbox**: Service worker precaching and routing functionality
|
|
|
|
### Environmental Prerequisites
|
|
- **HTTPS Development Server**: Already configured with valid certificates
|
|
- **Browser Support**: Modern browsers with service worker support
|
|
- **Test Environment**: Test runner that can handle service worker registration attempts
|
|
|
|
### Configuration Dependencies
|
|
- **svelte.config.js**: Must keep SvelteKit service worker disabled
|
|
- **vite.config.ts**: Primary configuration point for service worker setup
|
|
- **src/service-worker.ts**: Service worker implementation must remain functional
|
|
|
|
---
|
|
|
|
## Monitoring and Validation
|
|
|
|
### Development Monitoring
|
|
- Browser console errors related to service worker registration
|
|
- Network requests for service worker files (should succeed)
|
|
- Push notification subscription success/failure rates
|
|
- Service worker update and installation events
|
|
|
|
### Test Environment Monitoring
|
|
- Test suite completion rates and error logs
|
|
- Unhandled promise rejection tracking
|
|
- Service worker registration attempt monitoring
|
|
- Test environment isolation verification
|
|
|
|
### Production Monitoring (Future)
|
|
- Service worker registration success rates
|
|
- Push notification delivery rates
|
|
- PWA installation success rates
|
|
- Background sync operation success rates
|
|
|
|
---
|
|
|
|
## Conclusion
|
|
|
|
This execution plan addresses the critical service worker registration failures that are preventing push notifications and PWA functionality from working in development and test environments. The root cause is a file path mismatch in the vite-pwa development configuration, which is causing registration scripts to reference non-existent service worker files.
|
|
|
|
The plan focuses on:
|
|
1. **Immediate Fix**: Correcting the development service worker path configuration
|
|
2. **Test Stability**: Ensuring test environment doesn't suffer from service worker registration failures
|
|
3. **Functionality Preservation**: Maintaining all existing push notification and PWA features
|
|
4. **Future Prevention**: Adding comprehensive testing and monitoring capabilities
|
|
|
|
The solution maintains hexagonal architecture principles by treating the service worker as a Primary Adapter that interfaces with the core domain logic without affecting business rules or secondary adapters.
|
|
|
|
**Expected Timeline**: 1-2 days for complete implementation and verification
|
|
**Risk Level**: Medium (configuration changes with comprehensive testing)
|
|
**Business Impact**: High (enables critical push notification functionality) |