import { InjectHTMLElementStream } from "https://esm.town/v/andreterron/InjectHTMLElementStream?v=9";
import { rootValRef } from "https://esm.town/v/andreterron/rootValRef?v=3";
import { ValRef } from "https://esm.town/v/andreterron/ValRef?v=1";
import { getCurrentValVersionNumber } from "https://esm.town/v/stevekrouse/getCurrentValVersionNumber";
import { modifyResponse } from "https://esm.town/v/stevekrouse/modifyResponse";
import { parentReference } from "https://esm.town/v/stevekrouse/parentReference";
import type { MiddlewareHandler } from "npm:hono";
export const reloadOnVals = async function(vals: ValRef[]) {
const valVersions = await Promise.all(vals.map(getCurrentValVersionNumber));
const interval = setInterval(async () => {
let newValVersions = await Promise.all(vals.map(getCurrentValVersionNumber));
if (JSON.stringify(newValVersions) !== JSON.stringify(valVersions)) {
clearInterval(interval);
window.location.reload();
}
}, 1000);
};
export function reloadOnSaveHonoMiddleware(vals: ValRef[] = [rootValRef()]): MiddlewareHandler {
return async function(c, next) {
await next();
if (!new URL(c.req.url).hostname.includes("val.run")) {
return;
}
c.res = modifyResponse(
c.res,
new InjectHTMLElementStream(ReloadScriptText(vals)),
);
};
}
export function reloadOnSaveFetchMiddleware(
handler: (req: Request) => Response | Promise<Response>,
vals = [rootValRef()],
): (req: Request) => Promise<Response> {
return async (req: Request): Promise<Response> => {
const res = await handler(req);
if (!new URL(req.url).hostname.includes("val.run")) {
return res;
}
return modifyResponse(
res,
new InjectHTMLElementStream(ReloadScriptText(vals)),
);
};
}
export const ReloadScriptText = (vals = [rootValRef()]) =>
`<script type="module">
import { reloadOnVals } from "${import.meta.url}"
reloadOnVals(${JSON.stringify(vals)})
</script>`;