52 lines
1.3 KiB
TypeScript
52 lines
1.3 KiB
TypeScript
// Import this file with 'import * as sg from "#sitegen";'
|
|
export type ScriptId = string;
|
|
|
|
const frameworkDir = path.dirname(import.meta.dirname);
|
|
|
|
export interface SitegenRender {
|
|
scripts: Set<ScriptId>;
|
|
}
|
|
|
|
export function initRender(): SitegenRender {
|
|
return {
|
|
scripts: new Set(),
|
|
};
|
|
}
|
|
|
|
export function getRender() {
|
|
return ssr.getUserData<SitegenRender>("sitegen", () => {
|
|
throw new Error(
|
|
"This function can only be used in a page (static or view)",
|
|
);
|
|
});
|
|
}
|
|
|
|
/** Add a client-side script to the page. */
|
|
export function addScript(id: ScriptId) {
|
|
const srcFile: string = util.getCallSites()
|
|
.find((site) => !site.scriptName.startsWith(frameworkDir))!
|
|
.scriptName;
|
|
const filePath = hot.resolveFrom(srcFile, id);
|
|
if (
|
|
!filePath.endsWith(".client.ts") &&
|
|
!filePath.endsWith(".client.tsx")
|
|
) {
|
|
throw new Error("addScript must be a .client.ts or .client.tsx");
|
|
}
|
|
getRender().scripts.add(filePath);
|
|
}
|
|
|
|
export function Script({ src }: { src: ScriptId }) {
|
|
if (!src) throw new Error("Missing 'src' attribute");
|
|
addScript(src);
|
|
return null;
|
|
}
|
|
|
|
export interface Section {
|
|
root: string;
|
|
}
|
|
|
|
import * as ssr from "../engine/ssr.ts";
|
|
import * as util from "node:util";
|
|
import * as hot from "../hot.ts";
|
|
import * as path from "node:path";
|