@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, 03:37 UTC

main
ts 63 lines 2.22 KB
Raw
1 import { parseMarkdownFileLink } from "./markdownLinks.ts";
2
3 export interface CodexFileCitationLink {
4 readonly path: string;
5 readonly href: string;
6 readonly label: string;
7 readonly lineRangeStart?: number;
8 }
9
10 export type CodexFileCitationAttributes = Readonly<Record<string, string | null | undefined>>;
11
12 function positiveInteger(value: string | null | undefined): number | undefined {
13 if (value === null || value === undefined || value.trim().length === 0) return undefined;
14 const parsed = Number(value);
15 return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;
16 }
17
18 function citationLabel(path: string): string {
19 const normalized = path.replaceAll("\\", "/").replace(/\/+$/, "");
20 return normalized.slice(normalized.lastIndexOf("/") + 1) || normalized || "File";
21 }
22
23 function markdownDestinationPath(path: string): string {
24 const destination = path.replaceAll("%", "%25").replaceAll("#", "%23").replaceAll("?", "%3F");
25 // Only disambiguate rejected relative paths; recognized links keep workspace lookup behavior.
26 return parseMarkdownFileLink(destination) || /^(?:[a-z][a-z\d+.-]*:|[\\/])/i.test(path)
27 ? destination
28 : `./${destination}`;
29 }
30
31 export function resolveCodexFileCitationLink(
32 attributes: CodexFileCitationAttributes | null | undefined,
33 ): CodexFileCitationLink | null {
34 const path = attributes?.path?.trim();
35 if (!path) return null;
36
37 const lineRangeStart = positiveInteger(attributes?.line_range_start);
38 const destinationPath = markdownDestinationPath(path);
39 return {
40 path,
41 href: lineRangeStart === undefined ? destinationPath : `${destinationPath}#L${lineRangeStart}`,
42 label: citationLabel(path),
43 ...(lineRangeStart === undefined ? {} : { lineRangeStart }),
44 };
45 }
46
47 function markdownLabel(value: string): string {
48 return value.replace(/[\\[\]*_`<&]/g, "\\$&");
49 }
50
51 function markdownDestination(value: string): string {
52 return value
53 .replaceAll("\\", "%5C")
54 .replaceAll("&", "%26")
55 .replaceAll("<", "%3C")
56 .replaceAll(">", "%3E")
57 .replaceAll("\r", "%0D")
58 .replaceAll("\n", "%0A");
59 }
60
61 export function codexFileCitationMarkdown(citation: CodexFileCitationLink): string {
62 return `[${markdownLabel(citation.label)}](<${markdownDestination(citation.href)}>)`;
63 }