Here are the updated files with the enhanced architecture and new features:
cat/src/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');
/**
* Compiler Function
* @param {string} indexPath - Path to the index.html file.
* @returns {Promise<string>} - Compiled HTML content with component and page 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);
// -----------------------
// 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,
isPage: false, // Indicate that this is a component, not a page
});
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 { className, classCode }
let pageCounter = 0; // To generate unique class names for pages
for (const file of pageFiles) {
try {
const { route, html, script, style } = await parseComponent(file); // Reuse parseComponent for pages
// Parse script to extract properties and methods
const { properties, methods } = parseScript(script);
// Generate a unique class name for the page
const className = `_page${++pageCounter}`;
// Generate class code for the page
const classCode = generateClassCode({
tagName: className, // Use className instead of tagName
html,
style,
properties,
methods,
isPage: true, // Indicate that this is a page
});
pageMap.set(route, { className, classCode });
console.log(`📄 Compiled page for route "${route}" from ${path.relative(projectRoot, file)}`);
} 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
// -----------------------
// 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 are used across all HTML files
const availableComponents = new Set(componentMap.keys());
const usedComponents = detectUsedComponents(htmlContents, availableComponents);
if (usedComponents.size === 0) {
console.warn('⚠️ No used components found in HTML files.');
} else {
console.log(`📦 Used components: ${[...usedComponents].join(', ')}`);
}
// -----------------------
// Step 4: Generate Registration Script
// -----------------------
const registrationScript = generateRegistrationScript(
Array.from(usedComponents).reduce((map, tag) => map.set(tag, componentMap.get(tag)), new Map()),
pageMap
);
// -----------------------
// Step 5: 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.');
}
// -----------------------
// Step 6: Return Compiled Content
// -----------------------
return indexContent;
}
/**
* 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 used components and pages.
* @param {Map<string, string>} components - Map of tagName to compiled class code.
* @param {Map<string, {className: string, classCode: string}>} pages - Map of route to page class details.
* @returns {string} - JavaScript code for registering components and pages.
*/
function generateRegistrationScript(components, pages) {
let script = '';
// Register components
components.forEach((classCode) => {
script += `
${classCode}
`;
});
// Register pages
pages.forEach(({ className, classCode }) => {
script += `
${classCode}
`;
});
// Add Router class and instantiate it
if (pages.size > 0) {
script += `
class Router {
constructor() {
this.routes = new Map();
this.init();
}
init() {
// Map routes to page classes
${[...pages.entries()].map(([route, { className }]) => `this.routes.set('${route}', ${className});`).join('\n ')}
// Process load elements
document.addEventListener('DOMContentLoaded', () => {
this.processLoadElements();
});
}
processLoadElements() {
const loadElements = document.querySelectorAll('load[route]');
loadElements.forEach(el => {
const route = el.getAttribute('route');
const PageClass = this.routes.get(route);
if (PageClass) {
const pageInstance = new PageClass();
el.parentNode.replaceChild(pageInstance, el);
} else {
console.error(\`No page found for route "\${route}"\`);
}
});
}
}
// Instantiate the Router
const appRouter = new Router();
`;
}
return script;
}
module.exports = { compile };
cat/src/component.js
// cat/src/component.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 component or page file to extract tagName/route, HTML, script, and style sections.
* @param {string} filePath - Path to the .comp.html or .page.html file.
* @returns {Promise<{ tagName?: string, route?: string, html: string, script: string, style: string }>} - Component or page details.
*/
async function parseComponent(filePath) {
const content = await fs.readFile(filePath, 'utf-8');
// Determine if it's a component or a page based on file extension
const isPage = filePath.endsWith('.page.html');
let tagName, route, innerContent;
if (isPage) {
// Regex to match the <page> tag and extract the route attribute
const pageTagRegex = /<page\s+[^>]*route=["']([^"']+)["'][^>]*>/i;
const pageMatch = content.match(pageTagRegex);
if (!pageMatch) {
throw new Error(`No valid <page> tag with 'route' attribute found in ${path.basename(filePath)}`);
}
route = pageMatch[1];
// Extract the inner HTML of the <page> tag
const innerContentRegex = new RegExp(`<page[^>]*>([\\s\\S]*?)<\\/page>`, 'i');
const innerMatch = content.match(innerContentRegex);
innerContent = innerMatch ? innerMatch[1].trim() : '';
} else {
// Extract the outermost tag name and inner HTML for components
const componentRegex = /<([\w-]+)>([\s\S]*?)<\/\1>/;
const componentMatch = content.match(componentRegex);
if (!componentMatch) {
throw new Error(`Invalid component structure in ${path.basename(filePath)}`);
}
tagName = componentMatch[1];
innerContent = componentMatch[2].trim();
}
// Extract all <script> sections
const scriptRegex = /<script>([\s\S]*?)<\/script>/g;
let scriptContent = '';
let scriptMatch;
while ((scriptMatch = scriptRegex.exec(content)) !== null) {
scriptContent += scriptMatch[1].trim() + '\n';
}
// Extract all <style> sections
const styleRegex = /<style>([\s\S]*?)<\/style>/g;
let styleContent = '';
let styleMatch;
while ((styleMatch = styleRegex.exec(content)) !== null) {
styleContent += styleMatch[1].trim() + '\n';
}
// Remove all <script> and <style> tags from innerContent
innerContent = innerContent
.replace(scriptRegex, '')
.replace(styleRegex, '')
.trim();
return {
tagName,
route,
html: 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 kebab-case or other tag name to PascalCase for class naming.
* @param {string} name - The custom element tag name or class name.
* @returns {string} - PascalCase string.
*/
function toPascalCase(name) {
return name
.split(/[-_]/)
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join('');
}
/**
* Escape backticks in templates to avoid breaking template literals.
* @param {string} str - The template string.
* @returns {string} - Escaped string.
*/
function escapeBackticks(str) {
return str.replace(/`/g, '\\`');
}
/**
* Generate the class code for the component or page.
* @param {object} component - Component or page details.
* @param {boolean} isPage - Whether it's a page or a component.
* @returns {string} - The compiled class code.
*/
function generateClassCode({ tagName, html, style, properties, methods, isPage }) {
const className = isPage ? tagName : toPascalCase(tagName);
let classCode = `class ${className} extends ${isPage ? 'HTMLElement' : 'HTMLElement'} {
constructor() {
super();
`;
// Initialize properties
properties.forEach(prop => {
classCode += ` this._${prop.name} = ${prop.value};
`;
});
classCode += `
this.attachShadow({ mode: 'open' });
this._buildDOM();
}
_buildDOM() {
const fragment = document.createDocumentFragment();
`;
// Add styles
if (style) {
classCode += ` const style = document.createElement('style');
style.textContent = \`
${escapeBackticks(style)}
\`;
fragment.appendChild(style);
`;
}
// Generate DOM creation code
const { code: domCode, cachedNodes, eventListeners } = generateDOMCode(html);
classCode += domCode;
classCode += `
this.shadowRoot.appendChild(fragment);
}
`;
// connectedCallback
classCode += `
connectedCallback() {
`;
// Attach event listeners
if (eventListeners && eventListeners.length > 0) {
eventListeners.forEach(listener => {
classCode += ` this.${listener.elementVarName}.addEventListener('${listener.event}', this.${listener.handlerName}.bind(this));
`;
});
}
classCode += ` }
disconnectedCallback() {
`;
// Remove event listeners
if (eventListeners && eventListeners.length > 0) {
eventListeners.forEach(listener => {
classCode += ` this.${listener.elementVarName}.removeEventListener('${listener.event}', this.${listener.handlerName}.bind(this));
`;
});
}
classCode += ` }
`;
// Generate getters and setters
Object.keys(cachedNodes).forEach(propName => {
const nodes = cachedNodes[propName];
classCode += `
get ${propName}() { return this._${propName}; }
set ${propName}(value) {
if (this._${propName} !== value) {
this._${propName} = value;
`;
nodes.forEach(node => {
if (node.type === 'text') {
classCode += ` this.${node.varName}.textContent = ${node.expression};
`;
} else if (node.type === 'attribute') {
classCode += ` this.${node.elementVarName}.setAttribute('${node.attrName}', ${node.expression});
`;
}
});
classCode += ` }
}
`;
});
// Add methods
methods.forEach(method => {
const transformedBody = transformMethodBody(method.body, properties.map(p => p.name));
classCode += `
${method.name}(${method.params}) {
${transformedBody}
}
`;
});
classCode += `}`;
if (!isPage) {
// Register custom element for components
classCode += `
customElements.define('${tagName}', ${className});
`;
}
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 transformMethodBody(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 component or 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 = node.name + ++varCounter;
// Decide whether to assign to 'this.' or 'const'
let declaration;
if (needsReference(node)) {
declaration = `this.${varName}`;
} else {
declaration = `const ${varName}`;
}
const varReference = declaration.replace(/^const /, '');
code += ` ${declaration} = document.createElement('${node.name}');
`;
// Handle attributes
const attribs = node.attribs || {};
for (let [attrName, attrValue] of Object.entries(attribs)) {
if (attrName === 'class' || attrName === 'style' || attrName.startsWith('data-') || attrName === 'id' || attrName === 'src' || attrName === 'alt') {
// Handle attributes with embedded expressions
const { expression, propNames } = generateAttributeExpression(attrValue);
code += ` ${varReference}.setAttribute('${attrName}', ${expression});
`;
// Cache nodes for reactive updates
propNames.forEach(propName => {
if (!cachedNodes[propName]) cachedNodes[propName] = [];
cachedNodes[propName].push({
type: 'attribute',
elementVarName: varReference.replace(/^this\./, ''),
attrName: attrName,
expression: generateAttributeExpression(attrValue).expression,
});
});
} else if (attrName.startsWith('on')) {
// Event listener
const event = attrName.substring(2);
const handlerName = attrValue.replace(/\(\)$/, '').trim();
eventListeners.push({ elementVarName: varReference.replace(/^this\./, ''), event, handlerName });
} else {
// For other attributes
code += ` ${varReference}.setAttribute('${attrName}', '${attrValue}');
`;
}
}
// Append to parent
const parentRef = parentVarName ? parentVarName : 'fragment';
code += ` ${parentRef}.appendChild(${varReference});
`;
// Traverse children
if (node.children && node.children.length) {
for (let child of node.children) {
traverse(child, varReference);
}
}
} else if (node.type === 'text') {
const textContent = node.data;
if (textContent.trim()) {
// Handle text nodes with expressions
const { expression, propNames } = generateTextExpression(textContent);
const varName = 'textNode' + ++varCounter;
// Decide whether to assign to 'this.' or 'const'
let declaration;
if (expression.includes('this._')) {
declaration = `this.${varName}`;
} else {
declaration = `const ${varName}`;
}
const varReference = declaration.replace(/^const /, '');
code += ` ${declaration} = document.createTextNode(${expression});
`;
code += ` ${parentVarName}.appendChild(${varReference});
`;
// Cache nodes for reactive updates
propNames.forEach(propName => {
if (!cachedNodes[propName]) cachedNodes[propName] = [];
cachedNodes[propName].push({
type: 'text',
varName: varReference.replace(/^this\./, ''),
expression: generateTextExpression(textContent).expression,
});
});
}
}
}
function needsReference(node) {
// Determines if the element needs to be assigned to 'this.'
// Elements that are:
// - Targets of event listeners
// - Contain reactive expressions
// Need to be accessible outside of _buildDOM
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(JSON.stringify(textContent.slice(lastIndex, match.index)));
}
segments.push(`this._${match[1]}`);
propNames.push(match[1]);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < textContent.length) {
segments.push(JSON.stringify(textContent.slice(lastIndex)));
}
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(JSON.stringify(attrValue.slice(lastIndex, match.index)));
}
segments.push(`this._${match[1]}`);
propNames.push(match[1]);
lastIndex = exprRegex.lastIndex;
}
if (lastIndex < attrValue.length) {
segments.push(JSON.stringify(attrValue.slice(lastIndex)));
}
return {
expression: segments.join(' + '),
propNames,
};
}
dom.forEach(node => traverse(node, null));
return { code, cachedNodes, eventListeners };
}
module.exports = {
parseComponent,
parseScript,
toPascalCase,
escapeBackticks,
generateClassCode,
transformMethodBody,
generateDOMCode
};
cat/src/page.js
// cat/src/page.js
// Note: The functionality from page.js has been integrated into component.js
// This file is kept for potential future use or as a placeholder.
module.exports = {
// Exports can remain empty or include any utility functions if needed in the future
};
Report of Changes
1. Enhanced Architecture:
- Refactored the code in
compiler.js and component.js to be more modular and reusable.
- Removed redundant code by reusing functions for both components and pages.
- Integrated the functionality of
page.js into component.js, simplifying the architecture to only require two main modules (compiler.js and component.js).
2. Compiling .page.html Files:
- The
parseComponent function in component.js is now capable of parsing both components (.comp.html) and pages (.page.html).
- It detects the file type based on the file extension.
- For pages, it extracts the
<page> tag and its route attribute.
- Pages are compiled into classes similar to components but are named with a unique
_page{number} convention (e.g., _page1, _page2).
- The
generateClassCode function now accepts an isPage flag to handle differences between components and pages.
- For pages, the classes are not registered as custom elements.
3. Global Router Class:
- Implemented a
Router class within the generateRegistrationScript function in compiler.js.
- The
Router class:
- Maintains a mapping of routes to page classes.
- On
DOMContentLoaded, it searches for <load> elements with a route attribute.
- Replaces
<load> elements with instances of the corresponding page class if the route exists.
- The
Router class is instantiated as appRouter in the generated script to kickstart the routing process.
4. Injecting Registration Script:
- The compiled classes for both components and pages are included in the registration script injected into the
index.html.
- The
registrationScript now contains:
- Component class definitions and their custom element registrations.
- Page class definitions.
- The
Router class definition and its instantiation.
5. Simplifying Modules:
- Since the functionality of
page.js was merged into component.js, page.js now serves as a placeholder for future expansions or utilities.
- This consolidation reduces the complexity of the codebase and makes it easier to maintain.
6. Other Improvements:
- Ensured that the code follows consistent formatting and indentation for better readability.
- Updated comments and documentation within the code to reflect the new changes and assist future developers.
- Enhanced error handling and logging for better debugging and user feedback.
By making these changes, we've enhanced the scalability and reusability of the compiler while implementing the requested features. The code is now better organized, making it easier to maintain and extend in the future.