cat\src\compiler.js
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const {
parseComponent,
generateComponentClassCode,
} = require('./component');
const {
parsePageComponent,
generatePageClassCode,
} = require('./page');
const { parseScript } = require('./scripter');
/**
* Detect used components in the provided HTML contents by parsing the HTML tags.
* @param {Array<string>} htmlContents - Array of HTML file contents.
* @param {Set<string>} availableComponents - Set of all available component tag names.
* @returns {Set<string>} - Set of used component tag names.
*/
function detectUsedComponents(htmlContents, availableComponents) {
const usedComponents = new Set();
// Regex to match all tags in the HTML
const tagRegex = /<\s*([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g;
htmlContents.forEach((content) => {
let match;
while ((match = tagRegex.exec(content)) !== null) {
let tag = match[1];
if (availableComponents.has(tag)) {
usedComponents.add(tag);
}
}
});
return usedComponents;
}
/**
* Generate the registration script for the components and pages.
* @param {Map<string, string>} classes - Map of tagName to compiled class code.
* @returns {string} - JavaScript code for registering components and pages.
*/
function generateRegistrationScript(classes) {
let script = '';
classes.forEach((classCode, tagName) => {
script += `
${classCode}
`;
});
return script;
}
/**
* Generate the router script for handling <load> and <router> elements.
* @param {Array<{ route: string, tagName: string }>} routeToTagName - Mappings of routes to tag names.
* @returns {string} - JavaScript code for the router.
*/
function generateRouterScript(routeToTagName) {
let routeMappings = routeToTagName
.map(({ route, tagName }) => ` '${route}': '${tagName}'`)
.join(',\n');
return `
const routeToTagName = {
${routeMappings}
};
function loadRouteContent(routerId, route) {
const tagName = routeToTagName[route];
if (tagName) {
const routerElement = document.getElementById(routerId);
if (routerElement) {
// Clear existing content
routerElement.innerHTML = '';
// Create and append the new page element
const customElement = document.createElement(tagName);
routerElement.appendChild(customElement);
// Set up router for the newly loaded content
setupRouterForElement(routerElement);
} else {
console.error('No router found with id:', routerId);
}
} else {
console.error('No page found for route:', route);
}
}
function handleRouterClick(event) {
event.preventDefault();
const navElement = event.currentTarget;
const routerId = navElement.getAttribute('router');
const route = navElement.getAttribute('route');
// Remove 'current' attribute from all navigation elements with the same router
document.querySelectorAll('[router="' + routerId + '"][route]').forEach(function(el) {
el.removeAttribute('current');
});
// Set 'current' attribute on the clicked navigation element
navElement.setAttribute('current', '');
// Load the corresponding route content into the router container
loadRouteContent(routerId, route);
}
function setupRouterForElement(element) {
// Handle <load route=""> elements
element.querySelectorAll('load[route]').forEach(function(loadElement) {
const route = loadElement.getAttribute('route');
const tagName = routeToTagName[route];
if(tagName) {
const customElement = document.createElement(tagName);
// Copy all attributes from <load> to the custom element
for (let i = 0; i < loadElement.attributes.length; i++) {
let attr = loadElement.attributes[i];
if (attr.name !== 'route') {
customElement.setAttribute(attr.name, attr.value);
}
}
loadElement.parentNode.replaceChild(customElement, loadElement);
setupRouterForElement(customElement);
} else {
console.error('No page found for route:', route);
}
});
// Handle navigation elements with [router] and [route] attributes
element.querySelectorAll('[router][route]').forEach(function(navElement) {
// Remove existing event listener if any
navElement.removeEventListener('click', handleRouterClick);
// Add the new click event listener
navElement.addEventListener('click', handleRouterClick);
});
// Initial loading based on elements with 'current' attribute
element.querySelectorAll('[router][route][current]').forEach(function(navElement) {
const routerId = navElement.getAttribute('router');
const route = navElement.getAttribute('route');
loadRouteContent(routerId, route);
});
}
function setupRouter() {
setupRouterForElement(document);
}
document.addEventListener('DOMContentLoaded', setupRouter);
`;
}
/**
* Compiler Function
* @param {string} indexPath - Path to the index.html file.
* @returns {Promise<string>} - Compiled HTML content with component registrations.
*/
async function compile(indexPath) {
// Read the index.html content
let indexContent = await fs.readFile(indexPath, 'utf-8');
// Define project root
const projectRoot = path.dirname(indexPath);
// Initialize style accumulator
let accumulatedStyles = '';
// -----------------------
// Step 1: Process Components and Pages
// -----------------------
// Find all .comp.html and .page.html files in the project directory
const compFiles = glob.sync('**/*.comp.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**'], // Ignore node_modules and cat directory to prevent recursion
});
const pageFiles = glob.sync('**/*.page.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**'],
});
const componentMap = new Map(); // Map of tagName to compiled class code
const parsedComponents = new Set(); // To track parsed components
const routeTagMap = []; // Array of { route, tagName }
// Parse and compile each component file
for (const file of compFiles) {
try {
const { tagName, html, script, style } = await parseComponent(file);
if (!parsedComponents.has(tagName)) {
// Parse script to extract properties and methods
const { properties, methods } = parseScript(script);
// Generate class code
const classCode = generateComponentClassCode({
tagName,
html,
style,
properties,
methods,
});
componentMap.set(tagName, classCode);
parsedComponents.add(tagName);
// Accumulate styles
if (style && style.trim()) {
accumulatedStyles += `\n/* Styles for component: ${tagName} */\n${style}`;
}
console.log(
`🔍 Parsed and compiled component: <${tagName}> from ${path.relative(
projectRoot,
file
)}`
);
} else {
console.log(
`ℹ️ Component <${tagName}> from ${path.relative(
projectRoot,
file
)} has already been parsed.`
);
}
} catch (error) {
console.error(`❌ Failed to parse ${file}: ${error.message}`);
}
}
// Parse and compile each page file as a custom element
for (const file of pageFiles) {
try {
const { tagName, route, html, script, style } = await parsePageComponent(
file
);
// Generate class code for all pages, regardless of usage
const { properties, methods } = parseScript(script);
const classCode = generatePageClassCode({
tagName,
html,
style,
properties,
methods,
});
componentMap.set(tagName, classCode);
parsedComponents.add(tagName);
// Accumulate styles
if (style && style.trim()) {
accumulatedStyles += `\n/* Styles for page: ${tagName} */\n${style}`;
}
// Add to routeTagMap
routeTagMap.push({ route, tagName });
console.log(
`📄 Parsed and compiled page: <${tagName}> with route "${route}" from ${path.relative(
projectRoot,
file
)}`
);
} catch (error) {
console.error(`❌ Failed to parse page ${file}: ${error.message}`);
}
}
if (componentMap.size === 0) {
console.warn('⚠️ No components or pages found to compile.');
}
// -----------------------
// Step 2: Detect Used Components and Pages
// -----------------------
// Find all .html files in the project directory for usage detection
const htmlFiles = glob.sync('**/*.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**'],
});
const htmlContents = [];
for (const file of htmlFiles) {
try {
const content = await fs.readFile(file, 'utf-8');
htmlContents.push(content);
} catch (error) {
console.error(`❌ Failed to read HTML file ${file}: ${error.message}`);
}
}
// Detect which components and pages are used across all HTML files
const availableComponents = new Set(componentMap.keys());
const usedComponents = detectUsedComponents(
htmlContents,
availableComponents
);
// Also detect used routes from <load> tags and <router> tags
const loadTagRegex = /<load\s+[^>]*route=["']([^"']+)["'][^>]*>/gi;
let loadRoutes = [];
htmlContents.forEach((content) => {
let match;
while ((match = loadTagRegex.exec(content)) !== null) {
const route = match[1];
loadRoutes.push(route);
}
});
// Additionally, handle <router name="..."/> tags
const routerTagRegex = /<router\s+name=["']([^"']+)["']\s*\/>/gi;
let routerNames = [];
htmlContents.forEach((content) => {
let match;
while ((match = routerTagRegex.exec(content)) !== null) {
const routerName = match[1];
routerNames.push(routerName);
}
});
// Map routes to tagNames
loadRoutes.forEach((route) => {
const mapping = routeTagMap.find((r) => r.route === route);
if (mapping) {
usedComponents.add(mapping.tagName);
} else {
console.error(
`❌ No page found for route "${route}". Please ensure a .page.html file exists with route="${route}".`
);
}
});
if (usedComponents.size === 0) {
console.warn('⚠️ No used components or pages found in HTML files.');
} else {
console.log(
`📦 Used components and pages: ${[...usedComponents].join(', ')}`
);
}
// -----------------------
// Step 3: Generate Registration and Router Script
// -----------------------
// Generate the registration script for all components and pages
const registrationScript = generateRegistrationScript(componentMap);
// Generate the router script
const routerScript = generateRouterScript(routeTagMap);
// Combine scripts
const fullScript = `
${registrationScript}
${routerScript}
`;
// -----------------------
// Step 4: Inject Styles and Script
// -----------------------
// Inject the accumulated styles into the <head> tag
if (accumulatedStyles.trim()) {
const styleTag = `<style>
${accumulatedStyles}
</style>
`;
// Check if <head> exists
if (indexContent.includes('</head>')) {
indexContent = indexContent.replace('</head>', `${styleTag}</head>`);
} else {
// If no </head>, check for <html> tag to insert after
if (indexContent.includes('<html')) {
indexContent = indexContent.replace(
/<html[^>]*>/,
`$&\n<head>\n${styleTag}\n</head>`
);
} else {
// If no <html> tag, prepend the style tag
indexContent = `<head>\n${styleTag}\n</head>\n${indexContent}`;
}
}
console.log('🎨 Injected accumulated styles into <head>');
}
// Inject the script before the closing </body> tag
if (fullScript.trim()) {
const scriptTag = `<script>
${fullScript}
</script>
`;
if (indexContent.includes('</body>')) {
indexContent = indexContent.replace('</body>', `${scriptTag}</body>`);
} else {
// If no </body> tag, append the script at the end
indexContent += `\n${scriptTag}`;
}
console.log('📝 Injected component, page registrations, and router script.');
}
// -----------------------
// Step 5: Return Compiled Content
// -----------------------
return indexContent;
}
module.exports = { compile };