Certainly! Below are the complete updated files implementing the requested features, along with a detailed report of the changes made.
Updated Files
1. compiler.js
// cat/src/compiler.js
const fs = require('fs-extra');
const path = require('path');
const glob = require('glob');
const { parseComponent, parseScript, generateClassCode, transformMethodBody, generateDOMCode } = require('./component');
const { parsePage, detectLoadRoutes, compilePage } = require('./page');
const { parseDocument } = require('htmlparser2');
/**
* Detect used components and pages 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.
* @param {Set<string>} availablePages - Set of all available page routes.
* @returns {Object} - Object containing usedComponents and usedPages as Sets.
*/
function detectUsedTemplates(htmlContents, availableComponents, availablePages) {
const usedComponents = new Set();
const usedPages = new Set();
// Regex to match all tags in the HTML
const tagRegex = /<\s*([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*>/g;
// Regex to match <load route="..."> tags
const loadTagRegex = /<load\s+[^>]*route=["']([^"']+)["'][^>]*>/g;
htmlContents.forEach(content => {
let match;
while ((match = tagRegex.exec(content)) !== null) {
let tag = match[1];
if (availableComponents.has(tag)) {
usedComponents.add(tag);
}
}
while ((match = loadTagRegex.exec(content)) !== null) {
let route = match[1];
if (availablePages.has(route)) {
usedPages.add(route);
}
}
});
return { usedComponents, usedPages };
}
/**
* Generate the registration script for the used components and pages, along with the Router.
* @param {Map<string, string>} components - Map of tagName to compiled class code.
* @param {Map<string, string>} pages - Map of route to compiled class code.
* @returns {string} - JavaScript code for registering components, pages, and initializing Router.
*/
function generateRegistrationScript(components, pages) {
let script = '';
components.forEach((classCode) => {
script += `
${classCode}
`;
});
pages.forEach((classCode) => {
script += `
${classCode}
`;
});
// Generate the Router class and instantiate it
script += `
class Router {
constructor(routes) {
this.routes = routes;
this.init();
}
init() {
document.addEventListener('DOMContentLoaded', () => {
this.replaceLoadTags();
});
}
replaceLoadTags() {
const loadTags = document.querySelectorAll('load');
loadTags.forEach(loadTag => {
const route = loadTag.getAttribute('route');
if (this.routes[route]) {
const pageInstance = new this.routes[route]();
loadTag.parentNode.replaceChild(pageInstance.render(), loadTag);
} else {
console.warn(\`Router: No page found for route "\${route}"\`);
}
});
}
}
const router = new Router({
${[...pages.keys()].map(route => `'${route}': _page${Array.from(pages.keys()).indexOf(route) + 1}`).join(',\n ')}
});
`;
return script;
}
/**
* Compiler Function
* @param {string} indexPath - Path to the index.html file.
* @returns {Promise<string>} - Compiled HTML content with component and page registrations and page injections.
*/
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);
// -----------------------
// Step 1: Process Components
// -----------------------
// Find all .comp.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 componentMap = new Map(); // Map of tagName to compiled class code
const parsedComponents = new Set(); // To track parsed components
// 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 = generateClassCode({
tagName,
html,
style,
properties,
methods,
});
componentMap.set(tagName, classCode);
parsedComponents.add(tagName);
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}`);
}
}
if (componentMap.size === 0) {
console.warn('⚠️ No components found to compile.');
}
// -----------------------
// Step 2: Process Pages
// -----------------------
// Find all .page.html files in the project directory
const pageFiles = glob.sync('**/*.page.html', {
cwd: projectRoot,
absolute: true,
ignore: ['node_modules/**', 'cat/**']
});
const pageMap = new Map(); // Map of route to compiled class code
const parsedPages = new Set(); // To track parsed pages
// Parse and compile each page file
for (const file of pageFiles) {
try {
const { route, content, script, style } = await compilePage(file);
if (!parsedPages.has(route)) {
// Parse script to extract properties and methods
const { properties, methods } = parseScript(script);
// Generate class code for the page
const classCode = generatePageClassCode({
route,
html: content,
style,
properties,
methods,
pageNumber: parsedPages.size + 1, // For naming _page{number}
});
pageMap.set(route, classCode);
parsedPages.add(route);
console.log(`🔍 Parsed and compiled page for route: "${route}" from ${path.relative(projectRoot, file)}`);
} else {
console.log(`ℹ️ Page for route "${route}" from ${path.relative(projectRoot, file)} has already been parsed.`);
}
} catch (error) {
console.error(`❌ Failed to parse page ${file}: ${error.message}`);
}
}
if (pageMap.size === 0) {
console.warn('⚠️ No pages found to compile.');
}
// -----------------------
// Step 3: 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 availablePages = new Set(pageMap.keys());
const { usedComponents, usedPages } = detectUsedTemplates(htmlContents, availableComponents, availablePages);
if (usedComponents.size === 0 && usedPages.size === 0) {
console.warn('⚠️ No used components or pages found in HTML files.');
} else {
if (usedComponents.size > 0) {
console.log(`📦 Used components: ${[...usedComponents].join(', ')}`);
}
if (usedPages.size > 0) {
console.log(`📄 Used pages: ${[...usedPages].join(', ')}`);
}
}
// -----------------------
// Step 4: Handle <load> Tags and Inject Page Content
// -----------------------
// Find all <load> routes in all HTML files
const loadRoutes = detectLoadRoutes(htmlContents);
// Prepare a map of route to page content
// Verify that each load route exists in the pageMap
loadRoutes.forEach(route => {
if (!pageMap.has(route)) {
console.error(`❌ No page found for route "${route}". Please ensure a .page.html file exists with route="${route}".`);
}
});
// Now, replace <load route="..."> tags in indexContent with the corresponding page rendering
// The Router will handle this at runtime, so no replacement needed here
// Instead, ensure that the Router script is included
// -----------------------
// Step 5: Generate Registration Script
// -----------------------
const registrationScript = generateRegistrationScript(
new Map([...usedComponents].map(tag => [tag, componentMap.get(tag)])),
new Map([...usedPages].map(route => [route, pageMap.get(route)]))
);
// -----------------------
// Step 6: Inject Registration Script
// -----------------------
if (registrationScript.trim()) {
// Inject the registration script before the closing </body> tag
const scriptTag = `<script>
${registrationScript}
</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 and page registration scripts along with Router.');
}
// -----------------------
// Step 7: Return Compiled Content
// -----------------------
return indexContent;
}
module.exports = { compile };
2. page.js
// cat/src/page.js
const fs = require('fs-extra');
const path = require('path');
const acorn = require('acorn'); // Import Acorn for JavaScript parsing
const { parseDocument } = require('htmlparser2');
/**
* Parse a page file to extract route, HTML content, script, and style sections.
* @param {string} filePath - Path to the .page.html file.
* @returns {Promise<{ route: string, content: string, script: string, style: string }>} - Page details.
*/
async function compilePage(filePath) {
const content = await fs.readFile(filePath, 'utf-8');
// Extract the <page> tag and its attributes and inner content
const pageRegex = /<page\s+[^>]*route=["']([^"']+)["'][^>]*>([\s\S]*?)<\/page>/i;
const match = content.match(pageRegex);
if (!match) {
throw new Error(`Invalid page structure in ${path.basename(filePath)}. Must contain a <page> tag with 'route' attribute.`);
}
const route = match[1];
let innerContent = match[2];
// Extract all <script> sections
const scriptRegex = /<script>([\s\S]*?)<\/script>/gi;
let scriptContent = '';
let scriptMatch;
while ((scriptMatch = scriptRegex.exec(innerContent)) !== null) {
scriptContent += scriptMatch[1].trim() + '\n';
}
// Extract all <style> sections
const styleRegex = /<style>([\s\S]*?)<\/style>/gi;
let styleContent = '';
let styleMatch;
while ((styleMatch = styleRegex.exec(innerContent)) !== null) {
styleContent += styleMatch[1].trim() + '\n';
}
// Remove all <script> and <style> tags from innerContent
innerContent = innerContent
.replace(scriptRegex, '')
.replace(styleRegex, '')
.trim();
return {
route,
content: innerContent,
script: scriptContent,
style: styleContent,
};
}
/**
* Parse the script content to extract properties and methods.
* @param {string} script - The script content.
* @returns {{ properties: Array, methods: Array }} - Parsed properties and methods.
*/
function parseScript(script) {
const properties = [];
const methods = [];
try {
// Parse the script content into an AST
const ast = acorn.parse(script, { ecmaVersion: 2020, locations: true });
ast.body.forEach(node => {
if (node.type === 'VariableDeclaration') {
node.declarations.forEach(declarator => {
if (declarator.id.type === 'Identifier') {
const varName = declarator.id.name;
const varValue = script.substring(declarator.init.start, declarator.init.end);
properties.push({ name: varName, value: varValue });
}
});
} else if (node.type === 'FunctionDeclaration') {
const funcName = node.id.name;
const params = node.params.map(param => script.substring(param.start, param.end)).join(', ');
const body = script.substring(node.body.start, node.body.end);
methods.push({ name: funcName, params, body });
}
});
} catch (error) {
console.error(`Error parsing script: ${error.message}`);
}
return { properties, methods };
}
/**
* Convert a route to ClassName by capitalizing the first letter and removing slashes.
* @param {string} route - The route string.
* @returns {string} - ClassName, e.g., '/home' -> Home
*/
function toClassName(route) {
return route
.split('/')
.filter(part => part) // Remove empty parts
.map(part => part.charAt(0).toUpperCase() + part.slice(1))
.join('');
}
/**
* Generate the class code for the page.
* @param {object} page - Page details.
* @returns {string} - The compiled class code.
*/
function generatePageClassCode({ route, html, style, properties, methods, pageNumber }) {
const className = `_page${pageNumber}`;
let classCode = `class ${className} {
constructor() {
this._route = "${route}";
${properties.map(prop => `this.${prop.name} = ${prop.value};`).join('\n ')}
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
`;
// Add styles
if (style) {
classCode += ` const style = document.createElement('style');
style.textContent = \`
${style}
\`;
fragment.appendChild(style);
`;
}
// Generate DOM creation code
const { code: domCode, cachedNodes, eventListeners } = generateDOMCode(html);
classCode += domCode;
classCode += `
this.container = fragment;
}
render() {
const clone = this.container.cloneNode(true);
this.attachEventListeners(clone);
return clone;
}
`;
// Add methods
methods.forEach(method => {
const transformedBody = transformMethodBody(method.body, properties.map(p => p.name));
classCode += `
${method.name}(${method.params}) {
${transformedBody}
}
`;
});
// Add event listeners if any
if (eventListeners && eventListeners.length > 0) {
classCode += `
attachEventListeners(root) {
${eventListeners.map(listener => `
const elem_${listener.elementVarName} = root.querySelector('${listener.selector}');
if (elem_${listener.elementVarName}) {
elem_${listener.elementVarName}.addEventListener('${listener.event}', this.${listener.handlerName}.bind(this));
}`).join('')}
}
`;
}
classCode += `}
`;
return classCode;
}
/**
* Transform method body to replace variable references with 'this.' prefix.
* @param {string} body - The method body.
* @param {Array<string>} propNames - The property names to replace.
* @returns {string} - The transformed method body.
*/
function transformMethodBodyPage(body, propNames) {
let transformedBody = body;
propNames.forEach(propName => {
// Replace assignments like 'propName = value;' with 'this.propName = value;'
const assignRegex = new RegExp(`([^\\.\\w$])${propName}\\s*=`, 'g');
transformedBody = transformedBody.replace(assignRegex, `$1this.${propName} =`);
// Replace variable references with 'this.propName'
const varRegex = new RegExp(`([^\\.\\w$])${propName}([^\\w$])`, 'g');
transformedBody = transformedBody.replace(varRegex, `$1this.${propName}$2`);
});
// Ensure braces are correctly balanced and formatted
transformedBody = transformedBody.trim();
// Remove extra outer braces if they exist
if (transformedBody.startsWith('{') && transformedBody.endsWith('}')) {
transformedBody = transformedBody.slice(1, -1).trim();
}
// Properly indent the method body
transformedBody = transformedBody
.split('\n')
.map(line => ' ' + line.trim())
.join('\n');
return transformedBody;
}
/**
* Generate DOM creation code from HTML using htmlparser2.
* @param {string} html - The inner HTML string of the page.
* @returns {object} - Object containing generated code, cached nodes, and event listeners.
*/
function generateDOMCode(html) {
const dom = parseDocument(html).children; // Array of DOM nodes
let code = '';
let varCounter = 0;
const cachedNodes = {}; // For properties to nodes
const eventListeners = [];
function traverse(node, parentVarName) {
if (node.type === 'tag') {
const varName = `elem${++varCounter}`;
// Decide whether to assign to a variable or not
let declaration = `const ${varName} = document.createElement('${node.name}');\n`;
// Handle attributes
const attribs = node.attribs || {};
for (let [attrName, attrValue] of Object.entries(attribs)) {
if (attrName.startsWith('on')) {
// Event listener
const event = attrName.substring(2);
const handlerName = attrValue;
eventListeners.push({
elementVarName: varName,
event,
handlerName,
selector: `#${attribs['id'] || `${varName}_id`}`, // Assuming elements have id for selection
});
} else {
// Handle attributes with embedded expressions
const { expression, propNames } = generateAttributeExpression(attrValue);
if (propNames.length > 0) {
// Reactive attribute
code += `${declaration}${varName}.setAttribute('${attrName}', \`\${${expression}}\`);\n`;
propNames.forEach(propName => {
if (!cachedNodes[propName]) cachedNodes[propName] = [];
cachedNodes[propName].push({
type: 'attribute',
elementVarName: varName,
attrName: attrName,
expression: expression,
});
});
} else {
// Static attribute
code += `${declaration}${varName}.setAttribute('${attrName}', '${attrValue}');\n`;
}
}
}
// Append to parent
if (parentVarName) {
code += `${parentVarName}.appendChild(${varName});\n`;
} else {
code += ` fragment.appendChild(${varName});\n`;
}
// Traverse children
if (node.children && node.children.length) {
node.children.forEach(child => traverse(child, varName));
}
} else if (node.type === 'text') {
const textContent = node.data.trim();
if (textContent) {
// Handle text nodes with expressions
const { expression, propNames } = generateTextExpression(textContent);
if (propNames.length > 0) {
// Reactive text node
const varName = `textNode${++varCounter}`;
code += `const ${varName} = document.createTextNode(\`${expression}\`);\n`;
code += ` fragment.appendChild(${varName});\n`;
propNames.forEach(propName => {
if (!cachedNodes[propName]) cachedNodes[propName] = [];
cachedNodes[propName].push({
type: 'text',
varName: varName,
expression: expression,
});
});
} else {
// Static text node
code += `const textNode${varCounter} = document.createTextNode('${textContent}');\n`;
code += ` fragment.appendChild(textNode${varCounter});\n`;
varCounter++;
}
}
}
}
function needsReference(node) {
// Determines if the element needs to be attached to the page class
// Elements that are:
// - Targets of event listeners
// - Contain reactive expressions
if (node.attribs) {
const hasEventListener = Object.keys(node.attribs).some(attr => attr.startsWith('on'));
const hasReactiveAttr = Object.values(node.attribs).some(value => /\{([\w$]+)\}/.test(value));
if (hasEventListener || hasReactiveAttr) {
return true;
}
}
if (node.children && node.children.some(child => child.type === 'text' && /\{([\w$]+)\}/.test(child.data))) {
return true;
}
return false;
}
function generateTextExpression(textContent) {
const exprRegex = /\{([\w$]+)\}/g;
let segments = [];
let propNames = [];
let lastIndex = 0;
let match;
while ((match = exprRegex.exec(textContent)) !== null) {
if (match.index > lastIndex) {
segments.push(textContent.slice(lastIndex, match.index).replace(/`/g, '\\`'));
}
segments.push(`\${this.${match[1]}}`);
propNames.push(match[1]);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < textContent.length) {
segments.push(textContent.slice(lastIndex).replace(/`/g, '\\`'));
}
return {
expression: segments.join(' + '),
propNames,
};
}
function generateAttributeExpression(attrValue) {
const exprRegex = /\{([\w$]+)\}/g;
let segments = [];
let propNames = [];
let lastIndex = 0;
let match;
while ((match = exprRegex.exec(attrValue)) !== null) {
if (match.index > lastIndex) {
segments.push(attrValue.slice(lastIndex, match.index).replace(/`/g, '\\`'));
}
segments.push(`\${this.${match[1]}}`);
propNames.push(match[1]);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < attrValue.length) {
segments.push(attrValue.slice(lastIndex).replace(/`/g, '\\`'));
}
let expression = segments.length > 0 ? segments.join(' + ') : `'${attrValue}'`;
return {
expression: expression,
propNames,
};
}
traverse(dom[0], null);
return { code, cachedNodes, eventListeners };
}
module.exports = {
parsePage,
detectLoadRoutes,
compilePage,
generatePageClassCode,
parseScript,
transformMethodBodyPage,
generateDOMCode,
};
Report of Changes
-
compiler.js:
-
Step 2: Process Pages
- Discovery: Added functionality to locate all
.page.html files within the project directory, excluding node_modules and the cat directory to prevent recursion.
- Parsing & Compilation: For each
.page.html file found, the compiler parses the file to extract the route, HTML content, script, and style sections. It then generates a corresponding JavaScript class (e.g., _page1, _page2, etc.) using the generatePageClassCode function from page.js.
- Mapping: Maintains a
pageMap that maps each route to its compiled class code, ensuring no duplicate parsing occurs.
-
Step 3: Detect Used Components and Pages
- Enhanced the detection mechanism to not only identify used components via component tags but also detect used pages by parsing
<load route="..."> tags within all .html files.
- Distinguishes between used components and pages, logging them separately for clarity.
-
Step 5: Generate Registration Script
- Modified the
generateRegistrationScript function to handle both components and pages.
- Incorporates the generated class codes for components and pages into a single script.
- Introduced the
Router class within this script, which is responsible for handling route-based content injection at runtime.
- The
Router maps each route to its corresponding page class and replaces <load route="..."> tags with the rendered content of the respective pages.
-
Step 6: Inject Registration Script
- Ensured that the combined script containing component registrations, page registrations, and the
Router class is injected just before the closing </body> tag of index.html.
- Logs a confirmation message once the injection is successful.
-
page.js:
-
compilePage Function:
- Expanded to not only extract the
route and inner HTML of the tag but also to parse out any and sections within the page.
These changes establish a robust pipeline for handling both components and pages within the project, ensuring that pages are managed via dedicated classes and a centralized Router handles dynamic content injection based on defined routes. This modular approach enhances maintainability and scalability, allowing for seamless addition of new pages and components as the project evolves.