import { existsSync } from "node:fs"; import path from "node:path"; import type { AstroIntegration } from "astro"; import type { AnalyticsClient } from "./analytics-client.ts"; import type { CommentsClient } from "./comments-client.ts"; import { scriptsNotInlined } from "./csp.ts"; /** Options for the `cloudhal()` integration; made available to pages via `virtual:cloudhal/config`. */ export interface CloudhalRendererConfig { /** Directory holding `data.db` and `blobs/` (absolute or relative to the Astro project root). */ readonly dataDir: string; readonly siteId: string; /** * `live` reads current nodes on every request (dev); `snapshot:` renders a frozen snapshot * (build/production). `CLOUDHAL_SOURCE` in the environment overrides this. */ readonly source?: "live" | `snapshot:${string}`; /** * `node` (default): `cloudhal dev` / static `cloudhal build` from the local store. * `cloudflare`: the deployed Site Worker — every page renders on demand from D1/R2 so publish and * rollback are pointer flips (needs the `@astrojs/cloudflare` adapter; see ADR-0012). */ readonly target?: "node" | "cloudflare"; /** * Media (RFC-0004 §7.5): `transform: "cdn-cgi"` emits responsive `srcset`s through Cloudflare * image transformations on the site's own zone. Opt-in (answer 13): it needs Transformations * enabled on a custom domain; the default `"none"` serves originals. */ readonly media?: { readonly transform?: "cdn-cgi" | "none" }; /** * Site analytics (RFC-0006) on **Node** targets: `cloudhal.json`'s `analytics` block. Without it, * `CLOUDHAL_ANALYTICS` / `CLOUDHAL_ANALYTICS_DEFAULTS` in the environment decide, as on the * Cloudflare Site Worker (where the Worker vars always decide and this is ignored). `dev: true` * records `cloudhal dev` traffic into the local SQLite store; by default `cloudhal dev` answers the * beacon endpoint and records nothing. Static builds never carry analytics (no endpoint). */ readonly analytics?: { readonly enabled?: boolean; readonly uniqueVisitors?: boolean; readonly vitalsOneIn?: number; readonly dev?: boolean; }; /** Set by the integration: URL of the built page-view script (`/_cloudhal/p..js`). */ readonly analyticsScript?: string; /** * Reader comments (RFC-0007): `cloudhal.json`'s `comments` block. `available: false` removes * the endpoints, the module and the section for the deployment; by default they exist and each * site turns comments on in its settings (off until then). Static builds never have comments. */ readonly comments?: { readonly available?: boolean }; /** * Set by the integration when comments are available on this target: URL of the built comments * module (`/_cloudhal/c..js`, loaded only on pages with an open thread). */ readonly commentsScript?: string; } const VIRTUAL_ID = "virtual:cloudhal/config"; const RESOLVED_ID = `\0${VIRTUAL_ID}`; /** Dev only: the built analytics scripts, served from memory by the analytics middleware. */ const CLIENT_ID = "virtual:cloudhal/analytics-client"; const RESOLVED_CLIENT_ID = `\0${CLIENT_ID}`; /** Dev only: the built comments module and worker, served from memory by the comments middleware. */ const COMMENTS_CLIENT_ID = "virtual:cloudhal/comments-client"; const RESOLVED_COMMENTS_CLIENT_ID = `\0${COMMENTS_CLIENT_ID}`; /** * RFC-0043 §1.7: a lazy loader of the project's `src/theme.ts` for the status pages' theme hook * (root-relative, so Vite resolves it in dev and in the Site Worker build), or of an empty module * when the project has no theme module. Evaluated only when a status page is drawn. */ const THEME_HOOKS_ID = "virtual:cloudhal/theme-hooks"; const RESOLVED_THEME_HOOKS_ID = `\0${THEME_HOOKS_ID}`; const THEME_MODULE = "src/theme.ts"; /** * The type of `virtual:cloudhal/config`: the integration's config, with `dataDir` absent on the * `cloudflare` target (`virtualConfig`). Theme code that reads `dataDir` must handle that. */ export type VirtualCloudhalConfig = Omit & { readonly dataDir?: string; }; /** * What pages see as `virtual:cloudhal/config`. On the `cloudflare` target there is no `dataDir`: * the Site Worker reads D1 and R2 through its bindings (`runtime-workerd.ts` ignores the field), * and the resolved value is the build machine's absolute path, which a release bundle built in CI * would otherwise carry to every deployment (RFC-0046 §11b, #239). */ export function virtualConfig( resolved: CloudhalRendererConfig, cloudflare: boolean, ): VirtualCloudhalConfig { if (!cloudflare) return resolved; const { dataDir: _buildMachinePath, ...rest } = resolved; return rest; } /** The virtual modules: the project config, and in dev the built analytics and comments clients. */ function configPlugin(modules: { config: unknown; client: unknown; comments: unknown }) { const ids: Record = { [VIRTUAL_ID]: RESOLVED_ID, [CLIENT_ID]: RESOLVED_CLIENT_ID, [COMMENTS_CLIENT_ID]: RESOLVED_COMMENTS_CLIENT_ID, [THEME_HOOKS_ID]: RESOLVED_THEME_HOOKS_ID, }; const bodies: Record = { [RESOLVED_ID]: modules.config, [RESOLVED_CLIENT_ID]: modules.client, [RESOLVED_COMMENTS_CLIENT_ID]: modules.comments, }; let root = process.cwd(); return { name: "cloudhal-config", configResolved: (config: { root: string }) => { root = config.root; }, resolveId: (id: string) => (Object.hasOwn(ids, id) ? ids[id] : undefined), load: (id: string) => { if (id === RESOLVED_THEME_HOOKS_ID) return existsSync(path.join(root, THEME_MODULE)) ? `export const loadTheme = () => import("/${THEME_MODULE}");` : "export const loadTheme = () => Promise.resolve({});"; return Object.hasOwn(bodies, id) ? `export default ${JSON.stringify(bodies[id])};` : undefined; }, }; } /** * What only `cloudhal dev` runs as middleware (the Site Worker's entry and builds do these jobs): * the analytics beacon (RFC-0006 §5.1); the click-to-load video player (RFC-0015 §4) and the * interaction runtime (RFC-0020 §4), which builds write as files; the Site Worker's CSP sent * report-only, so the console shows what a deploy would block; and the status pages' preview * route (RFC-0043 §1.8). */ const DEV_MIDDLEWARE = [ "analytics-middleware", "embed-middleware", "csp-middleware", // RFC-0043 §1.8: the status pages drawn on demand at `/__cloudhal/status/`. "status-middleware", ].map((m) => ({ entrypoint: `@cloudhal/astro-renderer/${m}`, order: "pre" as const, })); export function cloudhal(config: CloudhalRendererConfig): AstroIntegration { let resolved: CloudhalRendererConfig = config; let client: AnalyticsClient | undefined; let comments: CommentsClient | undefined; /** `astro dev` (`cloudhal dev`): pages render per request. */ let devServer = false; return { name: "@cloudhal/astro-renderer", hooks: { "astro:config:setup": async ({ updateConfig, addMiddleware, config: astroConfig, command, }) => { devServer = command === "dev"; const root = astroConfig.root.pathname; resolved = { ...config, dataDir: config.dataDir.startsWith("/") ? config.dataDir : `${root}${config.dataDir}`, }; const cloudflare = config.target === "cloudflare"; // `cloudhal dev` answers the media route from the local blob store (RFC-0004 §7.8); the // Cloudflare Site Worker answers it in its entry, before Astro. if (!cloudflare) addMiddleware({ entrypoint: "@cloudhal/astro-renderer/media-middleware", order: "pre" }); // Analytics (RFC-0006 §5.1, §11): the Site Worker build ships the two hashed scripts as // static assets and its entry injects the tag; `cloudhal dev` serves them and answers the // beacon from a middleware. Static builds have no endpoint, so no script at all. if ((cloudflare && command === "build") || (!cloudflare && command === "dev")) { const { buildAnalyticsClient } = await import("./analytics-client.ts"); client = await buildAnalyticsClient(); resolved = { ...resolved, analyticsScript: client.script.path }; } if (!cloudflare && command === "dev") for (const m of DEV_MIDDLEWARE) addMiddleware(m); // Reader comments (RFC-0007 §8.2, §15.2), on the same targets: the Site Worker build ships // the module and its proof-of-work worker as hashed static assets and its entry answers the // endpoints; `cloudhal dev` serves both and answers them from a middleware on SQLite. if ( config.comments?.available !== false && ((cloudflare && command === "build") || (!cloudflare && command === "dev")) ) { const { buildCommentsClient } = await import("./comments-client.ts"); comments = await buildCommentsClient(); resolved = { ...resolved, commentsScript: comments.module.path }; if (!cloudflare) addMiddleware({ entrypoint: "@cloudhal/astro-renderer/comments-middleware", order: "pre", }); } // RFC-0042 §5: a collection's feed where the theme's routes answer 404, on every target. addMiddleware({ entrypoint: "@cloudhal/astro-renderer/collection-feed-middleware", order: "pre", }); updateConfig({ vite: { plugins: [ configPlugin({ config: virtualConfig(resolved, cloudflare), client: cloudflare ? null : (client ?? null), comments: cloudflare ? null : (comments ?? null), }), ], // `SITE_CSP` allows no inline script, so theme `