The best way to control Claude Code, Codex and more from any computer or phone

main
ts 211 lines 7.32 KB
Raw
1 /**
2 * Copy editing for hand-written markdown files (`.md`, `.mdx`).
3 *
4 * {@link markdownBlocks} is a Sätteri mdast plugin (Astro 7's markdown
5 * processor) that tags each markdown block with its source range:
6 * `data-copy="md:<file>@<start>-<end>~<version>"`, where `version` hashes the
7 * text the page was rendered from. {@link markdownFiles} reads and writes
8 * those ranges, following offsets from older versions through the edits it
9 * has made since, so a page stays editable without reloading after each save.
10 */
11 import { createHash } from "node:crypto";
12 import { promises as fs } from "node:fs";
13 import path from "node:path";
14 import { fileURLToPath } from "node:url";
15 import type { CopyEditHandler } from "./index.ts";
16 import { CopyEditError } from "./text.ts";
17
18 export const MARKDOWN_FILE_SCHEME = "md";
19
20 /** Blocks edited as markdown, as a whole. */
21 const BLOCKS = new Set(["paragraph", "heading", "list", "blockquote", "table", "code"]);
22 /** Containers whose children are markdown blocks (asides, JSX components). */
23 const CONTAINERS = new Set(["containerDirective", "mdxJsxFlowElement"]);
24
25 export interface MarkdownFilesOptions {
26 /** Directory ids are relative to (usually the Vite root). */
27 root: string;
28 /** Files to mark. @default /\.mdx?$/ */
29 include?: RegExp;
30 /** Files to skip, e.g. generated pages. */
31 exclude?: RegExp;
32 /** `data-copy-style` preset for the blocks. */
33 style?: string;
34 }
35
36 interface Point {
37 offset?: number;
38 }
39 interface MdNode {
40 type: string;
41 children?: MdNode[];
42 data?: Record<string, unknown>;
43 position?: { start: Point; end: Point };
44 }
45 interface MdContext {
46 setProperty(node: MdNode, key: "data", value: Record<string, unknown>): void;
47 wrapNode(node: MdNode, parent: MdNode): void;
48 }
49
50 const toPosix = (p: string) => p.split(path.sep).join("/");
51
52 /**
53 * Hash of a document's text after its frontmatter. Renderers see frontmatter
54 * blanked to whitespace (so offsets stay file offsets); hashing only what
55 * follows it gives both sides the same version.
56 */
57 const version = (text: string) =>
58 createHash("sha1")
59 .update(text.replace(/^\s*---\r?\n[\s\S]*?\r?\n---/, "").trim())
60 .digest("hex")
61 .slice(0, 12);
62
63 const matches = (file: string, options: MarkdownFilesOptions) =>
64 (options.include ?? /\.mdx?$/).test(file) && !options.exclude?.test(file);
65
66 /**
67 * A Sätteri mdast plugin entry that marks markdown blocks for editing. Put it
68 * first in `markdown.processor.options.mdastPlugins`, in dev only, so it sees
69 * blocks before other plugins (asides, etc.) rewrite them.
70 */
71 export const markdownBlocks =
72 (options: MarkdownFilesOptions) =>
73 ({ fileURL, source }: { fileURL: URL | undefined; source: string }) => {
74 if (!fileURL || fileURL.protocol !== "file:") return undefined;
75 const file = fileURLToPath(fileURL);
76 const rel = toPosix(path.relative(options.root, file));
77 if (rel.startsWith("..") || !matches(file, options)) return undefined;
78 const v = version(source);
79 return {
80 name: "copy-editor-markdown-blocks",
81 options: { position: true },
82 before(root: MdNode, ctx: MdContext) {
83 const walk = (parent: MdNode) => {
84 for (const node of parent.children ?? []) {
85 if (CONTAINERS.has(node.type)) {
86 walk(node);
87 continue;
88 }
89 const start = node.position?.start.offset;
90 const end = node.position?.end.offset;
91 if (!BLOCKS.has(node.type) || start === undefined || end === undefined) {
92 continue;
93 }
94 const attributes = {
95 "data-copy": `${MARKDOWN_FILE_SCHEME}:${rel}@${start}-${end}~${v}`,
96 "data-copy-format": "markdown",
97 ...(options.style ? { "data-copy-style": options.style } : {}),
98 };
99 if (node.type === "code") {
100 // Code highlighters replace the <pre>, so mark a wrapper.
101 ctx.wrapNode(node, {
102 type: "copyEditorBlock",
103 data: { hName: "div", hProperties: attributes },
104 children: [],
105 });
106 continue;
107 }
108 const data = node.data ?? {};
109 ctx.setProperty(node, "data", {
110 ...data,
111 hProperties: {
112 ...(data.hProperties as Record<string, unknown> | undefined),
113 ...attributes,
114 },
115 });
116 }
117 };
118 walk(root);
119 },
120 };
121 };
122
123 const parseId = (id: string) => {
124 const m = /^md:(.+)@(\d+)-(\d+)~([0-9a-f]+)$/.exec(id);
125 return m ? { file: m[1]!, start: Number(m[2]), end: Number(m[3]), version: m[4]! } : undefined;
126 };
127
128 /** One saved edit: the `before` characters at `at` became `after` characters. */
129 interface Step {
130 at: number;
131 before: number;
132 after: number;
133 /** Version of the file after the edit. */
134 next: string;
135 }
136
137 const outdated = () =>
138 new CopyEditError(
139 "This page is out of date with its file (it changed elsewhere). Reload and try again.",
140 409,
141 );
142
143 /** Reads and writes the markdown behind blocks marked by {@link markdownBlocks}. */
144 export const markdownFiles = (options: MarkdownFilesOptions): CopyEditHandler => {
145 /** Per file, the edit saved from each version, to follow old offsets. */
146 const history = new Map<string, Map<string, Step>>();
147
148 const locate = async (id: string) => {
149 const parsed = parseId(id);
150 const file = parsed && path.resolve(options.root, parsed.file);
151 if (
152 !parsed ||
153 !file ||
154 !file.startsWith(path.resolve(options.root) + path.sep) ||
155 !matches(file, options)
156 ) {
157 throw new CopyEditError(`Invalid markdown copy id: ${id}`);
158 }
159 const code = await fs.readFile(file, "utf8");
160
161 let { start, end } = parsed;
162 const current = version(code);
163 const steps = history.get(file);
164 for (let v = parsed.version; v !== current;) {
165 const step = steps?.get(v);
166 if (!step) throw outdated();
167 if (start === step.at && end === step.at + step.before) {
168 end = step.at + step.after;
169 } else if (start >= step.at + step.before) {
170 start += step.after - step.before;
171 end += step.after - step.before;
172 } else if (end > step.at) {
173 throw outdated();
174 }
175 v = step.next;
176 }
177 if (end > code.length) throw outdated();
178 return { rel: parsed.file, file, code, start, end, current };
179 };
180
181 return {
182 async readSource(id) {
183 const { code, start, end } = await locate(id);
184 return code.slice(start, end);
185 },
186
187 async writeSource({ id, source, base }, context) {
188 const { rel, file, code, start, end, current } = await locate(id);
189 if (code.slice(start, end) !== base) {
190 throw new CopyEditError(
191 "This text changed since you started editing. Copy your text, reload, and try again.",
192 409,
193 );
194 }
195 const next = code.slice(0, start) + source + code.slice(end);
196 if (next === code) return { file: rel, changed: false };
197 await fs.writeFile(file, next);
198 const steps = history.get(file) ?? new Map<string, Step>();
199 steps.set(current, {
200 at: start,
201 before: end - start,
202 after: source.length,
203 next: version(next),
204 });
205 history.set(file, steps);
206 // Lets the page's own rendering replace the preview once it's rebuilt.
207 context.suppressReloads(Promise.resolve());
208 return { file: rel, changed: true };
209 },
210 };
211 };