From abaab2b73f24dd526e17e5ef8e948092f379db76 Mon Sep 17 00:00:00 2001 From: Ayo Date: Fri, 27 Jun 2025 22:17:59 +0200 Subject: [PATCH] feat(core): expose McFly global to app server scripts --- packages/core/src/route-middleware.js | 2 +- packages/core/src/runtime/evaluate-scripts.ts | 29 ++++++++++++++++--- site/src/pages/cozy.html | 19 ++++++++++++ 3 files changed, 45 insertions(+), 5 deletions(-) create mode 100644 site/src/pages/cozy.html diff --git a/packages/core/src/route-middleware.js b/packages/core/src/route-middleware.js index 6164a61..b0c3d07 100644 --- a/packages/core/src/route-middleware.js +++ b/packages/core/src/route-middleware.js @@ -75,7 +75,7 @@ export default eventHandler(async (event) => { const transforms = [ { fn: evaluateServerScripts, - args: [''], + args: [event], hook: mcflyHooks.serverScriptsEvaluated, }, { diff --git a/packages/core/src/runtime/evaluate-scripts.ts b/packages/core/src/runtime/evaluate-scripts.ts index 8324385..552dd86 100644 --- a/packages/core/src/runtime/evaluate-scripts.ts +++ b/packages/core/src/runtime/evaluate-scripts.ts @@ -2,6 +2,15 @@ import { ELEMENT_NODE, parse, renderSync, walkSync } from 'ultrahtml' import { parseScript } from 'esprima' import { consola } from 'consola' import type { BaseNode as JsNode } from 'estree' +import type { H3Event } from 'h3' + +const McFlyGlobal: { + hello: string + event: any +} = { + hello: 'world', + event: undefined, +} /** * @typedef {import('estree').BaseNode} JsNode @@ -12,7 +21,13 @@ import type { BaseNode as JsNode } from 'estree' * @param {string} _html * @returns {string} */ -export function evaluateServerScripts(_html: string) { +export function evaluateServerScripts(_html: string, event: H3Event) { + McFlyGlobal.event = { + url: event.node.req.url, + method: event.node.req.method, + statusCode: event.node.req.statusCode, + statusMessage: event.node.req.statusMessage, + } let html = evaluateServerScript(_html) html = deleteServerScripts(html) return html @@ -52,9 +67,15 @@ function evaluateServerScript(html: string) { // @ts-ignore .map((n) => n.declarations[0].id.name) //['declarations'][0].id.name) - const constructor = `(function(){}.constructor)(\`${script}; return {${keys.join( - ',' - )}}\`);` + // const McFly=${JSON.stringify(McFlyGlobal)}; + const constructor = `(function(){}.constructor)(\` + const McFly=${JSON.stringify(McFlyGlobal)} + ${script}; + return { + ${keys.join(',')}, + McFly: ${JSON.stringify(McFlyGlobal)} + }\`);` + const evalStore = eval(constructor) Object.assign(setupMap, new evalStore()) }) diff --git a/site/src/pages/cozy.html b/site/src/pages/cozy.html new file mode 100644 index 0000000..addf201 --- /dev/null +++ b/site/src/pages/cozy.html @@ -0,0 +1,19 @@ + + + + + + Cozy (McFly) + + + +

{{ appName }} - {{McFly.hello}}

+
+ + +
+ + \ No newline at end of file