@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 202 lines 6.6 KB
Raw
1 import { spawn } from "node:child_process";
2 import { promises as fs } from "node:fs";
3 import path from "node:path";
4 import { fileURLToPath } from "node:url";
5 import {
6 docCommentLines,
7 docTargets,
8 JSDOC_LINE_PREFIX,
9 linkTagText,
10 parseJsdocCopyId,
11 regionSource,
12 replaceRegion,
13 } from "../../scripts/jsdoc-blocks.ts";
14 import {
15 applyRuns,
16 CopyEditError,
17 markdownDialect,
18 markdownRuns,
19 type CopyEditHandler,
20 type MarkdownOptions,
21 type MarkdownStyle,
22 } from "../src/copy-editor/index.ts";
23
24 const repoRoot = fileURLToPath(new URL("../../", import.meta.url));
25 const generator = path.join(repoRoot, "scripts/generate-api-reference.ts");
26
27 const markdown: MarkdownOptions = {
28 linePrefix: JSDOC_LINE_PREFIX,
29 atomics: [{ pattern: /\{@link\s+([^}]+)\}/, text: (m) => linkTagText(m[1]!) }],
30 };
31 const dialect = markdownDialect(markdown);
32
33 /**
34 * Preview style for edited JSDoc markdown on the reference pages, matching
35 * Starlight's markdown until the regenerated page replaces the preview.
36 */
37 export const jsdocMarkdownStyle: MarkdownStyle = {
38 elements: {
39 code: { dir: "auto" },
40 pre: { class: "copy-preview-code" },
41 },
42 // `{@link X}` / `{@link X label}` render as the label or `X` in code.
43 rewrite: [
44 ["\\{@link\\s+[^}\\s|]+\\s*[|\\s]\\s*([^}]+)\\}", "$1"],
45 ["\\{@link\\s+(?:import\\([^)]*\\)\\.)?([^}\\s]+)\\s*\\}", "`$1`"],
46 ],
47 css: `
48 [data-copy-style="docs"] pre.copy-preview-code {
49 margin: 1rem 0;
50 padding: 0.9rem 1.1rem;
51 overflow-x: auto;
52 border: 1px solid var(--sl-color-gray-5, #444);
53 border-radius: 6px;
54 background: var(--sl-color-gray-6, #1a1a1a);
55 font-size: var(--sl-text-code, 0.875rem);
56 line-height: 1.6;
57 }
58 [data-copy-style="docs"] pre.copy-preview-code code {
59 background: none;
60 padding: 0;
61 font-size: inherit;
62 }
63 `,
64 };
65
66 /** Resolves a copy id to its source file and parsed comment. */
67 const locate = async (id: string) => {
68 const parsed = parseJsdocCopyId(id);
69 const file = parsed && path.resolve(repoRoot, parsed.file);
70 if (
71 !parsed ||
72 !file ||
73 !file.startsWith(path.join(repoRoot, "packages") + path.sep) ||
74 !/\.tsx?$/.test(file)
75 ) {
76 throw new CopyEditError(`Invalid JSDoc copy id: ${id}`);
77 }
78 const code = await fs.readFile(file, "utf8");
79 if (!code.startsWith("/**", parsed.commentStart)) {
80 throw new CopyEditError(
81 "The JSDoc moved since this page was generated. Reload and try again.",
82 409,
83 );
84 }
85 const lines = docCommentLines(code, parsed.commentStart);
86 return { parsed, file, code, lines, targets: docTargets(lines) };
87 };
88
89 const gone = () =>
90 new CopyEditError("This part of the JSDoc no longer exists. Reload and try again.", 409);
91
92 /** A fingerprint of a comment's editable structure (ids depend on it). */
93 const shape = (targets: ReturnType<typeof docTargets>) =>
94 JSON.stringify([
95 targets.regions.map((r) => [r.kind, r.editable]),
96 targets.inline.map((b) => b.kind),
97 ]);
98
99 /**
100 * Saves copy edits made on generated API reference pages back into the JSDoc
101 * the page was generated from, then regenerates the reference pages.
102 *
103 * Pages carry copy markup when the generator runs with
104 * `API_REFERENCE_COPY_MARKERS=1` (see `dev:site`): prose regions are edited
105 * as markdown, titles inline.
106 */
107 export const jsdocCopyHandler = (): CopyEditHandler => {
108 let running: Promise<void> | undefined;
109 let queued: Promise<void> | undefined;
110
111 const runGenerator = () =>
112 new Promise<void>((resolve, reject) => {
113 const child = spawn("node", [generator], {
114 cwd: repoRoot,
115 env: { ...process.env, API_REFERENCE_COPY_MARKERS: "1" },
116 stdio: ["ignore", "ignore", "pipe"],
117 });
118 let stderr = "";
119 child.stderr.on("data", (chunk) => (stderr += chunk));
120 child.on("error", reject);
121 child.on("exit", (code) =>
122 code === 0 ? resolve() : reject(new Error(`API reference generation failed:\n${stderr}`)),
123 );
124 });
125
126 // One run at a time; edits made during a run share a single follow-up run.
127 const regenerate = (): Promise<void> => {
128 if (queued) return queued;
129 if (!running) {
130 running = runGenerator().finally(() => (running = undefined));
131 return running;
132 }
133 queued = running
134 .catch(() => {})
135 .then(() => {
136 queued = undefined;
137 return regenerate();
138 });
139 return queued;
140 };
141
142 const save = async (
143 file: string,
144 display: string,
145 before: ReturnType<typeof docTargets>,
146 code: string,
147 commentStart: number,
148 context: Parameters<NonNullable<CopyEditHandler["edit"]>>[1],
149 ) => {
150 await fs.writeFile(file, code);
151 // The page already shows the edit; keep the regenerated page's reload
152 // from interrupting whatever the editor does next.
153 const work = regenerate();
154 work.catch((error: Error) => context.logger.error(error.message));
155 context.suppressReloads(work);
156 const after = docTargets(docCommentLines(code, commentStart));
157 return {
158 file: display,
159 changed: true,
160 reload: shape(after) !== shape(before),
161 };
162 };
163
164 return {
165 async edit({ id, before, after }, context) {
166 const { parsed, file, code, targets } = await locate(id);
167 const block = "block" in parsed ? targets.inline[parsed.block!] : undefined;
168 if (!block) throw gone();
169 const runs = markdownRuns(code, block.start, block.end, markdown);
170 const next = applyRuns(code, runs, dialect, { before, after });
171 if (next === code) return { file: parsed.file, changed: false };
172 return save(file, parsed.file, targets, next, parsed.commentStart, context);
173 },
174
175 async readSource(id) {
176 const { parsed, lines, targets } = await locate(id);
177 const region = "region" in parsed ? targets.regions[parsed.region!] : undefined;
178 if (!region?.editable) throw gone();
179 return regionSource(lines, region);
180 },
181
182 async writeSource({ id, source, base }, context) {
183 const { parsed, file, code, lines, targets } = await locate(id);
184 const region = "region" in parsed ? targets.regions[parsed.region!] : undefined;
185 if (!region?.editable) throw gone();
186 if (regionSource(lines, region) !== base) {
187 throw new CopyEditError(
188 "This JSDoc changed since you started editing. Copy your text, reload, and try again.",
189 409,
190 );
191 }
192 let next: string;
193 try {
194 next = replaceRegion(code, lines, region, source);
195 } catch (error) {
196 throw new CopyEditError((error as Error).message);
197 }
198 if (next === code) return { file: parsed.file, changed: false };
199 return save(file, parsed.file, targets, next, parsed.commentStart, context);
200 },
201 };
202 };