﻿const express = require('express');
const path = require('path');
const fs = require('fs');
const router = express.Router();


// Stamp css content into html during development.
router.get('/custom-components/:component/*.html', (req, res) => {
	const element = req.params.component;
	const elementPath = path.join(__dirname, `../../public/${element}/${element}`);

	fs.readFile(`${elementPath}.html`, { encoding: 'utf-8' }, function (err, html) {
		if (err) {
			throw err;
		}

		fs.readFile(`${elementPath}.css`, { encoding: 'utf-8' }, function (err, css) {
			if (err) {
				throw err;
			}

			// Find the style tag that references the component's css.
			const stampLocation = new RegExp(`^[\S\s]+(<link.*href=".*?${element}.css.*?".*?\/>)`);
			const taggedCss = `<style>${css}</style>`;

			res.send(html.replace(stampLocation, taggedCss));
		});
	});
});

// Don't send the css file if it has been requested directly.
router.get('/custom-components/**/*.css', (req, res) => {
	res.send('');
});

// TODO: Add route to transpile js on request.
//router.get('/custom-components/**/*.js', (req, res) => { });


module.exports = {
	mountPath: '/',
	router: router
};

@@ -334,16 +334,34 @@
 /public/
+custom-components/
 $%7Belemen
@@ -418,39 +418,16 @@
 l%60, 
-%7B encoding: 'utf-8' %7D, function
+'utf-8',
  (er
@@ -434,16 +434,19 @@
 r, html)
+ =%3E
  %7B%0A%09%09if 
@@ -512,39 +512,16 @@
 s%60, 
-%7B encoding: 'utf-8' %7D, function
+'utf-8',
  (er
@@ -527,16 +527,19 @@
 rr, css)
+ =%3E
  %7B%0A%09%09%09if
@@ -671,17 +671,18 @@
 xp(%60
-%5E%5B%5CS%5Cs%5D+(
+%3Ctemplate%3E
 %3Clin
@@ -716,16 +716,17 @@
 *?%22.*?%5C/
+?
 %3E)%60);%0A%09%09
@@ -746,16 +746,26 @@
 Css = %60%3C
+template%3E%3C
 style%3E$%7B

Change regex to find the css import directly after the template. Fix bug in path to custom-component element.