import { readTask, newTask, split } from "./notes.ts"; import type { Task, TaskFields, Workspace } from "../model/model.ts"; import { backupFile, type OriginalFile } from "./catalog.ts"; import { legacyPosition } from "./order.ts"; import { mapConcurrent, readSources } from "./scan.ts"; import { cardsFolder, cardsMarker, isHiddenCard, readOptional, saveDocument, } from "./persistence.ts"; import { format, message } from "./message.ts"; /** The issue of one file: its path and its problem. */ export function fileIssue(path: string, problem: string) { return format(message("In {path}: {problem}"), { path, problem }); } export function cardPath(id: string) { const key = Array.from(new TextEncoder().encode(id), (byte) => byte.toString(16).padStart(2, "0"), ).join(""); return `${cardsFolder}/${key}.md`; } export function cardOrigin(source: string): OriginalFile | undefined { const origin = split(source).doc.toJS({ maxAliasCount: 50, }).runestone_pm_origin; if (origin === undefined) return; if ( !origin || typeof origin.path !== "string" || typeof origin.source !== "string" || typeof origin.backup !== "string" || origin.path.startsWith(".") || origin.path.includes("\\") || origin.path .split("/") .some((part: string) => !part || part === "." || part === "..") || origin.backup !== `.runestone/pm/backups/${origin.path}` ) throw new Error(message("The card migration record is invalid. Keep the original note.")); return origin; } /** Read one hidden card file. It throws when the file is invalid or when its name does not match the card ID. */ export function parseCard(path: string, source: string): Task { cardOrigin(source); const task = readTask(path, source); if (!task || cardPath(task.id) !== path) throw new Error(message("The hidden card ID does not match its storage path.")); return task; } export async function prepareCards(workspace: Workspace) { const marker = await readOptional(workspace, cardsMarker); if (marker !== null) return; try { await saveDocument(workspace, cardsMarker, "*\n", null); } catch (error) { if ((await readOptional(workspace, cardsMarker)) !== "*\n") throw error; } } export async function readCards( workspace: Workspace, previous: ReadonlyMap = new Map(), ): Promise<{ tasks: Task[]; issues: string[] }> { const tasks: Task[] = [], issues: string[] = []; // Direct reads are necessary because the host hides .runestone from root listings. if ( !workspace.readOptional || (await workspace.readOptional(cardsMarker)) === null ) return { tasks, issues }; const entries = (await workspace.list(cardsFolder)).filter( (entry) => entry.kind !== "folder" && isHiddenCard(entry.rel_path), ); const sources = await readSources(workspace, entries.map(entry => entry.rel_path)); const documents = await mapConcurrent(entries, async (entry) => { try { const result = sources.get(entry.rel_path)!; if (result.error || result.source === undefined) throw new Error(result.error ?? message("The card is unavailable.")); const source = result.source; const cached = previous.get(entry.rel_path); if (cached?.source === source) return { task: cached }; return { task: parseCard(entry.rel_path, source) }; } catch (error) { return { issue: fileIssue(entry.rel_path, error instanceof Error ? error.message : String(error)), }; } }); for (const document of documents) { if (document.task) tasks.push(document.task); if (document.issue) issues.push(document.issue); } return { tasks, issues }; } export async function createCard( workspace: Workspace, title: string, fields: TaskFields, body: string, id: string = crypto.randomUUID(), ) { // The storage name is independent of the title, so punctuation and duplicate titles are safe. const note = newTask(id, { ...fields, title: title.trim() }, body, id); const path = cardPath(id); await prepareCards(workspace); await saveDocument(workspace, path, note.source, null); return { path, source: note.source }; } export async function migrateCards(workspace: Workspace, tasks: Task[]) { for (const task of tasks) { if (isHiddenCard(task.path)) continue; if ((await workspace.read(task.path)) !== task.source) throw new Error( format(message("The card changed: {path}. Refresh before migration."), { path: task.path }), ); const destination = await readOptional(workspace, cardPath(task.id)); if (destination !== null) { const origin = cardOrigin(destination); if (origin?.path !== task.path || origin.source !== task.source) throw new Error( format(message("A different hidden card already uses the ID from {path}."), { path: task.path }), ); } if (split(task.source).doc.has("runestone_pm_origin")) throw new Error( format(message("The note already contains a migration record: {path}. Review it before migration."), { path: task.path }), ); } for (const task of tasks) { if (isHiddenCard(task.path)) continue; const original = await backupFile(workspace, task.path, task.source); const path = cardPath(task.id); if ((await readOptional(workspace, path)) !== null) continue; const { doc, body, newline, match } = split(task.source); doc.set("runestone_pm_origin", original); if (task.order === undefined) doc.setIn(["runestone_pm", "order"], legacyPosition(task.path)); for (const [id, placement] of Object.entries(task.placements ?? {})) if (placement.order === undefined) doc.setIn( ["runestone_pm", "placements", id, "order"], legacyPosition(task.path), ); const source = `${match?.[1] ?? ""}---${newline}${doc.toString({ lineWidth: 0 }).replaceAll("\n", newline)}---${newline}${body}`; const copied = readTask(path, source)!; if ( copied.id !== task.id || copied.title !== task.title || copied.body !== task.body ) throw new Error( format(message("The card copy differs from {path}. Keep the original."), { path: task.path }), ); if ((await workspace.read(task.path)) !== task.source) throw new Error(format(message("The card changed: {path}. Retry migration."), { path: task.path })); await prepareCards(workspace); await saveDocument(workspace, path, source, null); if ((await workspace.read(path)) !== source) throw new Error( format(message("The saved card check failed: {path}. Keep the original."), { path: task.path }), ); } }