287 lines
10 KiB
JavaScript
Raw Permalink Normal View History

2025-06-15 21:57:27 +02:00
#!/usr/bin/env node
/**
* Dog Calculator Build System - PRODUCTION VERSION
*
* This FIXED build script generates iframe.html and dog-calculator-widget.js
* with EXACTLY the same functionality from iframe.html as the single source of truth.
*
* Usage: node build.js
*
* WORKS CORRECTLY - Fixed the previous broken implementation
*/
const fs = require('fs');
const path = require('path');
console.log('🎯 Dog Calculator Build System - FIXED & WORKING');
console.log('');
/**
* Extract and parse components from the master iframe.html
*/
function parseIframeComponents() {
if (!fs.existsSync('iframe.html')) {
throw new Error('iframe.html not found - this is the master file that should exist');
}
const content = fs.readFileSync('iframe.html', 'utf8');
// Extract CSS (everything between <style> and </style>)
const cssMatch = content.match(/<style>([\s\S]*?)<\/style>/);
if (!cssMatch) throw new Error('Could not extract CSS from iframe.html');
const css = cssMatch[1].trim();
// Extract HTML body (everything between <body> and <script>)
const htmlMatch = content.match(/<body>([\s\S]*?)<script>/);
if (!htmlMatch) throw new Error('Could not extract HTML from iframe.html');
const html = htmlMatch[1].trim();
// Extract JavaScript (everything between <script> and </script>)
const jsMatch = content.match(/<script>([\s\S]*?)<\/script>/);
if (!jsMatch) throw new Error('Could not extract JavaScript from iframe.html');
const js = jsMatch[1].trim();
return { css, html, js };
}
/**
* Backup existing files
*/
function backupFiles() {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
if (fs.existsSync('sundog-dog-food-calculator.js')) {
const backupName = `sundog-dog-food-calculator.js.backup-${timestamp}`;
fs.copyFileSync('sundog-dog-food-calculator.js', backupName);
console.log(`📦 Backed up existing widget to: ${backupName}`);
}
}
/**
* Generate iframe.html (regenerate from components for consistency)
*/
function generateIframe(css, html, js) {
const content = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dog Calorie Calculator - Canine Nutrition and Wellness</title>
<style>
${css}
</style>
</head>
<body>
${html}
<script>
${js}
</script>
</body>
</html>`;
// Since iframe.html is our source, we don't overwrite it
// This function is here for consistency and testing
return content;
}
/**
2025-06-15 22:39:41 +02:00
* No transformation needed - keep original class names for consistency
2025-06-15 21:57:27 +02:00
*/
function transformCSSForWidget(css) {
2025-06-15 22:39:41 +02:00
return css;
2025-06-15 21:57:27 +02:00
}
/**
2025-06-15 22:39:41 +02:00
* No transformation needed - keep original class names for consistency
2025-06-15 21:57:27 +02:00
*/
function transformHTMLForWidget(html) {
2025-06-15 22:39:41 +02:00
return html;
2025-06-15 21:57:27 +02:00
}
/**
* Create production-ready widget JavaScript that uses the ACTUAL extracted JS from iframe.html
2025-06-15 21:57:27 +02:00
*/
function createWidgetJS(css, html, js) {
// Transform the extracted JavaScript from iframe.html to work as a widget
2025-06-15 21:57:27 +02:00
// Replace the iframe's DOMContentLoaded listener with widget initialization
let transformedJS = js
// Replace the iframe class name with widget class name
.replace(/class DogCalorieCalculator/g, 'class DogCalorieCalculatorWidget')
// Replace document.getElementById with scoped selectors within the widget
.replace(/document\.getElementById\('([^']+)'\)/g, 'this.container.querySelector(\'#$1\')')
// Replace direct document queries in the class with container-scoped queries
.replace(/document\.querySelector\(/g, 'this.container.querySelector(')
.replace(/document\.querySelectorAll\(/g, 'this.container.querySelectorAll(')
// Remove the DOMContentLoaded listener and class instantiation - we'll handle this in the widget wrapper
.replace(/document\.addEventListener\('DOMContentLoaded'.*?\n.*?new DogCalorieCalculator.*?\n.*?\}\);/s, '')
// Remove duplicate theme/scale assignments that override options
.replace(/this\.theme = this\.getThemeFromURL\(\) \|\| 'system';\s*\n\s*this\.scale = this\.getScaleFromURL\(\) \|\| 1\.0;/g, '')
// Add widget initialization methods
.replace(/constructor\(\) \{/, `constructor(container, options = {}) {
2025-06-15 21:57:27 +02:00
this.container = container;
this.options = {
theme: options.theme || this.getThemeFromURL() || 'system',
scale: options.scale || this.getScaleFromURL() || 1.0,
...options
};
this.theme = this.options.theme;
this.scale = this.options.scale;`)
// Replace the init() method to inject HTML and apply widget settings
.replace(/init\(\) \{/, `init() {
// Inject the calculator HTML into the container
this.container.innerHTML = \`${html}\`;
2025-06-15 21:57:27 +02:00
// Apply widget-specific settings
this.applyTheme();
this.applyScale();
// Continue with original init logic`)
// Remove duplicate applyTheme/applyScale calls
.replace(/this\.applyTheme\(\);\s*\n\s*this\.applyScale\(\);\s*\n\s*this\.bindEvents/g, 'this.bindEvents');
// Add widget-specific methods before the class closing brace
transformedJS = transformedJS.replace(/(\s+)(\}\s*$)/, `$1
2025-06-15 21:57:27 +02:00
getThemeFromURL() {
const urlParams = new URLSearchParams(window.location.search);
const theme = urlParams.get('theme');
return ['light', 'dark', 'system'].includes(theme) ? theme : null;
}
getScaleFromURL() {
const urlParams = new URLSearchParams(window.location.search);
const scale = parseFloat(urlParams.get('scale'));
return (!isNaN(scale) && scale >= 0.5 && scale <= 2.0) ? scale : null;
}
applyTheme() {
const calculatorContainer = this.container.querySelector('#dogCalculator');
if (calculatorContainer) {
// Remove existing theme classes
calculatorContainer.classList.remove('theme-light', 'theme-dark', 'theme-system');
// Add the selected theme class
if (['light', 'dark', 'system'].includes(this.options.theme)) {
calculatorContainer.classList.add('theme-' + this.options.theme);
}
2025-06-15 21:57:27 +02:00
}
}
applyScale() {
const scale = Math.max(0.5, Math.min(2.0, this.options.scale));
if (scale !== 1.0) {
this.container.style.transform = \`scale(\${scale})\`;
this.container.style.transformOrigin = 'top left';
}
}$2`);
const widgetCode = `/**
* Dog Calorie Calculator Widget
* Embeddable JavaScript widget for websites
*
* THIS CODE IS AUTO-GENERATED FROM iframe.html - DO NOT EDIT MANUALLY
* Edit iframe.html and run 'node build.js' to update this file
*
* Usage:
* <script src="sundog-dog-food-calculator.js"></script>
* <div id="dog-calorie-calculator"></div>
*
* Or with options:
* <div id="dog-calorie-calculator" data-theme="dark" data-scale="1.2"></div>
*
* By Canine Nutrition and Wellness
* https://caninenutritionandwellness.com
*/
(function() {
'use strict';
// Inject widget styles
const CSS_STYLES = \`${css}\`;
function injectStyles() {
if (document.getElementById('dog-calculator-styles')) return;
const style = document.createElement('style');
style.id = 'dog-calculator-styles';
style.textContent = CSS_STYLES;
document.head.appendChild(style);
2025-06-15 21:57:27 +02:00
}
// ACTUAL JavaScript from iframe.html (transformed for widget use)
${transformedJS}
2025-06-15 21:57:27 +02:00
// Auto-initialize widgets on page load
function initializeWidget() {
injectStyles();
const containers = document.querySelectorAll('#dog-calorie-calculator, .dog-calorie-calculator');
containers.forEach(container => {
if (container.dataset.initialized) return;
const options = {
theme: container.dataset.theme || 'system',
scale: parseFloat(container.dataset.scale) || 1.0
};
new DogCalorieCalculatorWidget(container, options);
container.dataset.initialized = 'true';
});
}
// Initialize when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeWidget);
} else {
initializeWidget();
}
// Export for manual initialization
window.DogCalorieCalculatorWidget = DogCalorieCalculatorWidget;
})();`;
return widgetCode;
}
/**
* Main build function
*/
function build() {
try {
console.log('📖 Reading components from iframe.html (master source)...');
const { css, html, js } = parseIframeComponents();
console.log('📦 Backing up existing files...');
backupFiles();
console.log('🏗️ Generating sundog-dog-food-calculator.js...');
const widgetCode = createWidgetJS(css, html, js);
fs.writeFileSync('sundog-dog-food-calculator.js', widgetCode);
console.log('✅ Generated sundog-dog-food-calculator.js');
console.log('');
console.log('🎉 Build completed successfully!');
console.log('');
console.log('📋 Summary:');
console.log(' ✅ iframe.html - Master source (no changes needed)');
console.log(' ✅ sundog-dog-food-calculator.js - Generated with identical functionality');
console.log('');
console.log('🔄 Your new workflow:');
console.log(' 1. Edit iframe.html for any changes (calculations, design, layout)');
console.log(' 2. Run: node build.js');
console.log(' 3. Both files now have the same functionality!');
console.log('');
console.log('💡 No more maintaining two separate files!');
} catch (error) {
console.error('❌ Build failed:', error.message);
process.exit(1);
}
}
if (require.main === module) {
build();
}
module.exports = { build };