diff --git a/package-lock.json b/package-lock.json index 1afa581..31f571d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5,6 +5,7 @@ "packages": { "": { "dependencies": { + "esprima": "^4.0.1", "nitropack": "latest", "ultrahtml": "^1.5.2" } @@ -1757,6 +1758,18 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/estree-walker": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", diff --git a/package.json b/package.json index 9293263..5b02cad 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "build:preview": "npm run build && npm run preview" }, "dependencies": { + "esprima": "^4.0.1", "nitropack": "latest", "ultrahtml": "^1.5.2" } diff --git a/routes/[...index].ts b/routes/[...index].ts index e5ba753..8b0ac88 100644 --- a/routes/[...index].ts +++ b/routes/[...index].ts @@ -1,4 +1,5 @@ import { ELEMENT_NODE, parse, walkSync } from "ultrahtml"; +import { parseScript } from "esprima"; export default eventHandler(async (event) => { const rawPath = @@ -60,9 +61,13 @@ function doSetUp(html: string) { const setupMap = {}; serverScripts.forEach((script: string) => { - const constructor = ` - new Function(\`${script}\`); - `; + const { body } = parseScript(script); + const keys = body + .filter((node) => node.type === "VariableDeclaration") + .map((node) => node.declarations[0].id.name); + const constructor = `new Function(\`${script}; return {${keys.join( + "," + )}}\`);`; const evalStore = eval(constructor); Object.assign(setupMap, new evalStore()); }); @@ -73,7 +78,7 @@ function doSetUp(html: string) { let matches = []; while ((match = regex.exec(html)) != null) { console.log(match[0], match[1]); - html = html.replace(match[0], setupMap[match[1]]); + html = html.replace(match[0], setupMap[match[1].trim()]); } return html; diff --git a/src/pages/index.html b/src/pages/index.html index 8e41f96..36341fa 100644 --- a/src/pages/index.html +++ b/src/pages/index.html @@ -6,15 +6,20 @@ Hello Nitro - About + {{ count }}
- some text: {{greeting}} +

some text: {{greeting}}