Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 57 additions & 4 deletions src/discord/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,64 @@ export interface ParsedClaudeResponse {
historyContent: string;
}

interface InlineCodeSpan {
start: number;
end: number;
}

function findInlineCodeSpans(text: string): InlineCodeSpan[] {
const spans: InlineCodeSpan[] = [];
let index = 0;

while (index < text.length) {
if (text[index] !== "`") {
index++;
continue;
}

let markerEnd = index + 1;
while (text[markerEnd] === "`") markerEnd++;
const marker = text.slice(index, markerEnd);
const lineBreakOffset = text.slice(markerEnd).search(/[\r\n]/);
const lineEnd =
lineBreakOffset === -1 ? text.length : markerEnd + lineBreakOffset;
const closingStart = text.indexOf(marker, markerEnd);
if (closingStart === -1 || closingStart >= lineEnd) {
index = markerEnd;
continue;
}

spans.push({
start: index,
end: closingStart + marker.length,
});
index = closingStart + marker.length;
}

return spans;
}

function isInsideInlineCode(spans: InlineCodeSpan[], index: number): boolean {
return spans.some((span) => index >= span.start && index < span.end);
}

export function parseClaudeResponse(response: string): ParsedClaudeResponse {
const reactions = [...response.matchAll(/\[REACT:(.+?)\]/g)].map((match) =>
match[1].trim(),
);
const text = response.replace(/\[REACT:(.+?)\]\s*/g, "").trim();
const inlineCodeSpans = findInlineCodeSpans(response);
const reactions: string[] = [];
const removals: { start: number; end: number }[] = [];

for (const match of response.matchAll(/\[REACT:(.+?)\]\s*/g)) {
const start = match.index ?? 0;
if (isInsideInlineCode(inlineCodeSpans, start)) continue;
reactions.push(match[1].trim());
removals.push({ start, end: start + match[0].length });
}

let text = response;
for (const removal of removals.reverse()) {
text = text.slice(0, removal.start) + text.slice(removal.end);
}
text = text.trim();

return {
reactions,
Expand Down
15 changes: 15 additions & 0 deletions tests/responseInlineCode.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import assert from "node:assert/strict";
import test from "node:test";

import { parseClaudeResponse } from "../build/discord/response.js";

test("keeps reaction tags inside inline code spans as literal text", () => {
assert.deepEqual(
parseClaudeResponse("Use `[REACT:literal]` in docs. [REACT:thumbsup] Done."),
{
reactions: ["thumbsup"],
text: "Use `[REACT:literal]` in docs. Done.",
historyContent: "Use `[REACT:literal]` in docs. Done.",
},
);
});