#!/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 */ import fs from 'fs'; import path from 'path'; import { execFileSync } from 'child_process'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); 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); }