puffin-app/scripts/inject-sw-version.js
Matt a279bb6aa9
Some checks failed
Build and Push Docker Images / docker (push) Failing after 44s
Add automatic cache clearing and version management to prevent white screen issues
Implements comprehensive service worker solution with:
- Dynamic versioning using git commit hash or timestamp
- Automatic cache invalidation on new deployments
- Hourly update checks and user notifications
- Network-first caching strategy with 24-hour expiration
- Build automation via prebuild script
- Update notification UI component

This prevents stale cached code from causing white screens by ensuring users always get the latest version after deployment.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-04 15:32:50 +01:00

53 lines
1.5 KiB
JavaScript

#!/usr/bin/env node
/**
* Inject build timestamp into service worker
* This script replaces __BUILD_TIMESTAMP__ with the current timestamp
* to force cache invalidation on new deployments
*/
const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
const SW_SOURCE = path.join(__dirname, '..', 'public', 'sw.js');
try {
// Read the service worker file
let swContent = fs.readFileSync(SW_SOURCE, 'utf8');
// Check if placeholder exists
if (!swContent.includes('__BUILD_TIMESTAMP__')) {
console.log('⚠️ Service worker appears to be already processed');
process.exit(0);
}
// Generate version (use git commit hash if available, otherwise use timestamp)
let version;
try {
// Try to get git commit hash using safe execFileSync
version = execFileSync('git', ['rev-parse', '--short', 'HEAD'], {
encoding: 'utf8',
stdio: ['pipe', 'pipe', 'ignore']
}).trim();
console.log(`📦 Using git commit hash: ${version}`);
} catch (error) {
// Fallback to timestamp
version = Date.now().toString();
console.log(`📦 Using timestamp: ${version}`);
}
// Replace the placeholder with the version
swContent = swContent.replace(/__BUILD_TIMESTAMP__/g, version);
// Write the updated service worker
fs.writeFileSync(SW_SOURCE, swContent);
console.log(`✅ Service worker version injected: ${version}`);
console.log(`📝 Updated: ${SW_SOURCE}`);
} catch (error) {
console.error('❌ Error injecting service worker version:', error);
process.exit(1);
}