import type { TypstRequest } from "@typbase/engine"; import type { WorkspaceStore } from "@typbase/storage"; import type { InstalledPackage, PageMeta, Section } from "@typbase/typing"; import { parseQueryPath } from "@typbase/typing"; import { engineAvailable } from "~/lib/engineHealth"; import { getLinkIndex } from "~/lib/linkIndex"; import { extractLinksFallback, workspaceBacklinks } from "~/lib/links"; import { fetchPackageBytes, samePackage, specString } from "~/lib/packages"; import { getPluginSource, pluginSlugs } from "~/lib/plugins/registry"; interface TypstRequestHandler { (requests: TypstRequest[], spaceId: string): Promise | boolean; } /** Plugin surfaces only see their own plugin data. Sites see a page allowlist. */ export interface RequestScope { pluginId?: string; /** False strips page content from the channel (no `pages.read`). */ allowPages?: boolean; /** * Site builds: the pages that exist in the public projection. Queries, * embeds, sections, daily notes, and backlinks are limited to this set so a * public page cannot pull private workspace text into its output. */ pageIds?: ReadonlySet; /** Site builds: plugin data needs the plugin's `site.publish` capability. */ site?: boolean; } // Included pages are raw sources: the `#import "/typbase/lib.typ" as typbase` // lives in the compiling doc's prelude, not in the page text. Without this // an embedded page that calls `typbase.query(...)` fails with // "unknown variable: typbase". const EMBED_PRELUDE = '#import "/typbase/lib.typ" as typbase\n'; /** * Answers the Typst engine's requests with workspace data. * * - `typbase/query/.json` file requests are synthesized JSON from the * workspace (the `#typbase.query` stdlib loads them). * - `typbase/src/.typ` source requests are other pages' content * (the `#typbase.embed` stdlib includes them). * * The inserted query files go stale when workspace data changes. Callers * `purge()` them and force a recompile. */ export interface TypstRequestService { handler: TypstRequestHandler; purge(): void; setCurrentPage(id: string | null): void; } /** * Raw payloads a request resolves to, without touching any wasm instance. * The editor service inserts them into its own TypstState. The publish * worker forwards them to the worker's instance. */ export type RequestPayload = | { type: "source"; path: string; text: string } | { type: "file"; path: string; bytes: Uint8Array } | { type: "package"; spec: InstalledPackage; bytes: Uint8Array }; export async function resolveRequestPayloads( requests: TypstRequest[], store: WorkspaceStore, currentPage: string | null, scope?: RequestScope, ): Promise { const payloads: RequestPayload[] = []; for (const request of requests) { if (request.type === "package") { const spec: InstalledPackage = { namespace: request.value.namespace, name: request.value.name, version: request.value.version, }; try { payloads.push({ type: "package", spec, bytes: await fetchPackageBytes(spec), }); } catch (error) { console.warn(`[typbase] could not fetch ${specString(spec)}:`, error); } continue; } // Request paths are root-absolute ("/typbase/src/.typ"), so strip // the leading slash before matching. const path = request.value.replace(/^\//, ""); if (request.type === "source") { if (path.startsWith("typbase/src/")) { if (scope && scope.allowPages === false) continue; const id = path.slice("typbase/src/".length, -".typ".length); if (scope?.pageIds && !scope.pageIds.has(id)) { // The page is private in this projection. A comment would silently // publish an empty block, so surface it as a compile error. payloads.push({ type: "source", path, text: `#panic("Page ${id} is not part of this site")\n`, }); continue; } // Self-embeds would recurse forever. A comment keeps the include quiet. const text = id === currentPage ? "// self-embed\n" : store.getPage(id) ? // Page docs load lazily. The embed must not depend on the // editor having opened this page already. EMBED_PRELUDE + (await store.loadPageText(id)) : `// no page named ${JSON.stringify(id)}\n`; payloads.push({ type: "source", path, text }); continue; } // Plugin modules, so notes can `#import "/typbase/plugin/..."`. if (path.startsWith("typbase/plugin/") || path === "typbase/ui.typ") { const text = getPluginSource(`/${path}`); if (text !== undefined) { payloads.push({ type: "source", path, text }); continue; } if (path !== "typbase/ui.typ") { console.warn( `[typbase] ${path} is not a catalogued plugin module. Installed: ${ pluginSlugs().join(", ") || "none" }`, ); } continue; } } else if (request.type === "file") { // Local media: `#image("/typbase/blob/.")`. if (path.startsWith("typbase/blob/")) { const name = path.slice("typbase/blob/".length); const hash = name.replace(/\.[^.]*$/, ""); const bytes = await store.getBlob(hash); if (bytes) payloads.push({ type: "file", path, bytes }); continue; } if (path.startsWith("typbase/query/")) { const parsed = parseQueryPath(path); if (!parsed) continue; if (scope && scope.allowPages === false && parsed.kind !== "plugin-data") continue; const json = await buildQueryJson(path, store, scope); if (json === null) continue; payloads.push({ type: "file", path, bytes: new TextEncoder().encode(json), }); } } } return payloads; } export function createTypstRequestService( typstState: { createFileId(path: string): unknown; insertSource(id: unknown, source: string): void; insertFile(id: unknown, bytes: Uint8Array): void; removeFile(id: unknown): void; installPackage(spec: string, bytes: Uint8Array): void; }, store: WorkspaceStore, ): TypstRequestService { const insertedFiles = new Set(); const insertedSources = new Set(); let currentPage: string | null = null; async function handle(requests: TypstRequest[]): Promise { const payloads = await resolveRequestPayloads(requests, store, currentPage); let changed = false; for (const payload of payloads) { if (payload.type === "package") { typstState.installPackage(specString(payload.spec), payload.bytes); rememberPackage(store, payload.spec); changed = true; } else if (payload.type === "source") { typstState.insertSource(typstState.createFileId(payload.path), payload.text); insertedSources.add(payload.path); changed = true; } else { typstState.insertFile(typstState.createFileId(payload.path), payload.bytes); insertedFiles.add(payload.path); changed = true; } } return changed; } function purge(): void { // Embedded page sources and query JSON both go stale when workspace data // changes. Dropping them forces a re-request on the next compile. Blobs // are content-addressed and immutable, so they stay in the world: media // does not need to be re-read and re-copied on every change. for (const path of insertedSources) { typstState.removeFile(typstState.createFileId(path)); } insertedSources.clear(); for (const path of insertedFiles) { if (path.startsWith("typbase/blob/")) continue; typstState.removeFile(typstState.createFileId(path)); } insertedFiles.clear(); } return { handler: handle, purge, setCurrentPage: (id) => { currentPage = id; }, }; } /** * Records an auto-installed package in the workspace list, so the manager * shows what the notes actually depend on instead of only what was installed * by hand. */ function rememberPackage(store: WorkspaceStore, spec: InstalledPackage): void { const installed = store.getSettings().installedPackages; if (installed.some((pkg) => samePackage(pkg, spec))) return; store.updateSettings({ installedPackages: [...installed, spec] }); } export async function buildQueryJson( path: string, store: WorkspaceStore, scope?: RequestScope, ): Promise { const query = parseQueryPath(path); if (!query) return null; const pages = store.listPages().filter((page) => !scope?.pageIds || scope.pageIds.has(page.id)); const daily = pages.filter((page) => page.path.startsWith("daily/")); // Single-segment filters put the value in filterName (e.g. sections/). const filterValue = query.filterValue ?? query.filterName; switch (query.kind) { case "config": { const settings = store.getSettings(); const homePageId = scope?.pageIds && settings.homePageId && !scope.pageIds.has(settings.homePageId) ? null : settings.homePageId; return JSON.stringify({ name: settings.name, homePageId, // `font` is the original text-font field. Keep it for documents that // already read it, and expose the effective families separately. font: settings.font, textFont: settings.font, codeFont: settings.codeFont ?? settings.font, mathFont: settings.mathFont ?? settings.font, }); } case "pages": { if (query.filterName === "by-id" && query.filterValue) { const page = pages.find((candidate) => candidate.id === query.filterValue); // Typst's json() turns "null" into none. #typbase.page-link uses that // for missing pages instead of failing the compile. return page ? JSON.stringify(page) : "null"; } const list = query.filterName === "by-category" && query.filterValue ? pages.filter((page) => page.categoryId === query.filterValue) : pages; return JSON.stringify(list); } case "categories": return JSON.stringify( store .listCategories() .filter( (category) => !scope?.pageIds || pages.some((page) => page.categoryId === category.id), ), ); case "daily": { const list = query.filterName === "by-month" && query.filterValue ? daily.filter((page) => page.path.startsWith(`daily/${query.filterValue}-`)) : daily; return JSON.stringify(list); } case "sections": { // One page's sections, or every page's when no filter is given. if (filterValue) return JSON.stringify(store.getSections(filterValue)); const all: Array
= []; for (const page of pages) { for (const section of store.getSections(page.id)) { all.push({ ...section, pageId: page.id }); } } return JSON.stringify(all); } case "content": { if (!filterValue) return "null"; // Accepts a page id or a date, so calendars can query `daily/` notes. const page = pages.find((candidate) => candidate.id === filterValue) ?? pages.find((candidate) => candidate.path === `daily/${filterValue}.typ`); if (!page) return "null"; return JSON.stringify({ id: page.id, title: page.title, path: page.path, text: await store.loadPageText(page.id), }); } case "plugin-data": { if (!filterValue) return "null"; const instance = store.getPluginInstance(filterValue); if (!instance) return "null"; // Site builds publish plugin data only when the plugin opts in. Without // this, a public page could query any installed plugin's private records. if (scope?.site) { const install = store.getPluginInstall(instance.pluginId); let capabilities: string[] = []; try { capabilities = (JSON.parse(install?.manifest ?? "{}") as { capabilities?: string[] }).capabilities ?? []; } catch { return "null"; } if (!capabilities.includes("site.publish")) return "null"; } // Plugin surfaces read their own data only. Note content reads all. if (scope?.pluginId && instance.pluginId !== scope.pluginId) return "null"; return JSON.stringify(await store.readPluginState(filterValue)); } case "backlinks": { if (!query.filterValue) return JSON.stringify([]); const target = pages.find((page) => page.id === query.filterValue); if (!target) return JSON.stringify([]); const incoming = await incomingPages(store, pages, target.id); return JSON.stringify(pages.filter((page) => incoming.has(page.id))); } } // Every query kind returns above. Keep the fallthrough explicit. return null; } /** * Pages that link `targetId`. The running link index answers when the engine * is healthy. A failed or unstarted index falls back to the regex scan so a * query never fails a compile. Self-links are not backlinks, matching the * panel. */ async function incomingPages( store: WorkspaceStore, pages: PageMeta[], targetId: string, ): Promise> { if (engineAvailable()) { try { const index = getLinkIndex(store); await index.start(); if (!index.status.error) { const sources = index .backlinksFor(targetId) .map((group) => group.pageId) .filter((pageId) => pageId !== targetId); return new Set(sources); } } catch { // Fall through to the scan. A broken index must not fail the compile. } } const backlinks = await workspaceBacklinks(store, pages, extractLinksFallback); return backlinks.get(targetId) ?? new Set(); }