sitegen/framework/lib/sitegen.ts
2025-06-09 21:13:51 -07:00

61 lines
1.4 KiB
TypeScript

// Import this file with 'import * as sg from "#sitegen";'
export type ScriptId = string;
/**
* A filesystem object associated with some ID,
* such as a page's route to it's source file.
*/
export interface FileItem {
id: string;
file: 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";