Something went wrong. Try again.
Local-first knowledge base made for Typst and the Atmosphere. typbase.at
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409import 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> | 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<string>; /** 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/<kind>.json` file requests are synthesized JSON from the * workspace (the `#typbase.query` stdlib loads them). * - `typbase/src/<id>.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<RequestPayload[]> { 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/<id>.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/<hash>.<ext>")`. 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<string>(); const insertedSources = new Set<string>(); let currentPage: string | null = null;
async function handle(requests: TypstRequest[]): Promise<boolean> { 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<string | null> { 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/<id>). 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<Section & { pageId: string }> = []; 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<Set<string>> { 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();}