Open History to see the last commit
1import type { ComposerContextRecord, ElementContextDetails } from "@t3tools/contracts";
2
3import { collectComposerContextReferences } from "./composerContextReferences.ts";
4
5/** Embeds context in message text for older servers that drop records and cannot resolve inline links. */
6export function serializeLegacyContextMessage(input: {
7 text: string;
8 records: ReadonlyArray<ComposerContextRecord>;
9}): string {
10 const recordsById = new Map(input.records.map((record) => [record.contextId, record]));
11 const used = new Set<string>();
12
13 let text = input.text;
14 const occurrences = collectComposerContextReferences(text);
15 for (const occurrence of [...occurrences].reverse()) {
16 const record = recordsById.get(occurrence.contextId);
17 if (!record) continue;
18 used.add(occurrence.contextId);
19 const replacement =
20 record.kind === "review-comment" ? renderReviewComment(record) : inlineLabel(record);
21 text = `${text.slice(0, occurrence.start)}${replacement}${text.slice(occurrence.end)}`;
22 }
23
24 const blocks = [
25 renderBlock(
26 "terminal_context",
27 input.records.filter((record) => record.kind === "terminal").map(renderTerminalEntry),
28 ),
29 renderBlock(
30 "element_context",
31 input.records.filter((record) => record.kind === "element").map(renderElementEntry),
32 ),
33 ...input.records
34 .filter((record) => record.kind === "preview-annotation")
35 .map((record) => `<preview_annotation>\n${renderPreviewBody(record)}\n</preview_annotation>`),
36 ...input.records
37 .filter((record) => record.kind === "review-comment" && !used.has(record.contextId))
38 .map(renderReviewComment),
39 ].filter((block) => block.length > 0);
40
41 return [text.trimEnd(), ...blocks].filter((part) => part.length > 0).join("\n\n");
42}
43
44function inlineLabel(record: ComposerContextRecord): string {
45 if (record.kind === "terminal" && "terminalLabel" in record) {
46 const slug = record.terminalLabel.trim().toLowerCase().replace(/\s+/g, "-");
47 const range =
48 record.lineStart === record.lineEnd
49 ? `${record.lineStart}`
50 : `${record.lineStart}-${record.lineEnd}`;
51 return `@${slug}:${range}`;
52 }
53 return record.label;
54}
55
56function renderBlock(tag: string, entries: ReadonlyArray<string>): string {
57 const body = entries.filter((entry) => entry.length > 0).join("\n");
58 return body.length === 0 ? "" : `<${tag}>\n${body}\n</${tag}>`;
59}
60
61function indent(value: string): string {
62 return value
63 .split("\n")
64 .map((line) => (line.length === 0 ? "" : ` ${line}`))
65 .join("\n");
66}
67
68function renderTerminalEntry(record: ComposerContextRecord): string {
69 if (!("terminalLabel" in record)) return "";
70 const range =
71 record.lineStart === record.lineEnd
72 ? `line ${record.lineStart}`
73 : `lines ${record.lineStart}-${record.lineEnd}`;
74 const body = record.text
75 .split("\n")
76 // A trailing newline would otherwise number a line past the range the label declares.
77 .slice(0, record.lineEnd - record.lineStart + 1)
78 .map((line, index) => `${record.lineStart + index} | ${line}`)
79 .join("\n");
80 return `- ${record.terminalLabel} ${range}:\n${indent(body)}`;
81}
82
83function renderElementEntry(record: ComposerContextRecord): string {
84 if (!("tagName" in record)) return "";
85 return renderElementDetailsEntry(record);
86}
87
88function renderElementDetailsEntry(record: ElementContextDetails): string {
89 const lines: string[] = [];
90 if (record.pageUrl) lines.push(`url: ${record.pageUrl}`);
91 if (record.selector) lines.push(`selector: ${record.selector}`);
92 const source = record.source;
93 if (source?.fileName) {
94 const position = [source.lineNumber, source.columnNumber].filter(
95 (part) => part !== null && part !== undefined,
96 );
97 lines.push(`source: ${[source.fileName, ...position].join(":")}`);
98 }
99 if (record.htmlPreview) lines.push(`html:\n${indent(record.htmlPreview)}`);
100 if (record.styles) lines.push(`styles:\n${indent(record.styles)}`);
101 return `- <${record.componentName ?? record.tagName}>:\n${indent(lines.join("\n"))}`;
102}
103
104function renderPreviewBody(record: ComposerContextRecord): string {
105 if (!("annotationId" in record)) return "";
106 const lines = [`Id: ${record.annotationId}`, `Page: ${record.pageUrl || record.pageTitle || ""}`];
107 if (record.comment) lines.push(`Comment: ${record.comment}`);
108 if (record.targetSummary) lines.push(`Targets: ${record.targetSummary}`);
109 if (record.styleChanges.length > 0) {
110 lines.push("Requested visual changes:", ...record.styleChanges.map((change) => `- ${change}`));
111 }
112 if (record.elements && record.elements.length > 0) {
113 lines.push(
114 "<element_context>",
115 record.elements.map(renderElementDetailsEntry).join("\n"),
116 "</element_context>",
117 );
118 }
119 return lines.join("\n");
120}
121
122function escapeAttribute(value: string): string {
123 return value
124 .replace(/&/g, "&")
125 .replace(/</g, "<")
126 .replace(/>/g, ">")
127 .replace(/"/g, """);
128}
129
130function renderReviewComment(record: ComposerContextRecord): string {
131 if (!("sectionId" in record)) return record.label;
132 const attributes = [
133 `sectionId="${escapeAttribute(record.sectionId)}"`,
134 `sectionTitle="${escapeAttribute(record.sectionTitle)}"`,
135 `filePath="${escapeAttribute(record.filePath)}"`,
136 `rangeLabel="${escapeAttribute(record.rangeLabel)}"`,
137 `startIndex="${record.startIndex}"`,
138 `endIndex="${record.endIndex}"`,
139 ].join(" ");
140 // The fence must be longer than any run of backticks inside the diff so the body stays intact.
141 const longestRun = Math.max(
142 0,
143 ...[...record.diff.matchAll(/`+/g)].map((match) => match[0].length),
144 );
145 const fence = "`".repeat(Math.max(3, longestRun + 1));
146 const body = record.diff
147 ? `${record.text}\n\n${fence}${record.fenceLanguage ?? "diff"}\n${record.diff}\n${fence}`
148 : record.text;
149 return `<review_comment ${attributes}>\n${body}\n</review_comment>`;
150}