Open History to see the last commit
1import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4import type { Nodes } from "mdast";
5import remarkGfm from "remark-gfm";
6import remarkParse from "remark-parse";
7import { unified, type Processor } from "unified";
8
9import { DEFAULT_HOSTED_APP_URL } from "./connectAuth.ts";
10
11export const THREAD_LINK_PROTOCOL = "t3-thread";
12const V1_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;
13const V2_PREFIX = `${THREAD_LINK_PROTOCOL}://v2/`;
14const HOSTED_PREFIX = `${DEFAULT_HOSTED_APP_URL}/threads/`;
15const HOSTED_SEGMENT = "[A-Za-z0-9_%-]+(?:\\.+[A-Za-z0-9_%-]+)*";
16const HOSTED_LINK = `${HOSTED_PREFIX.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}${HOSTED_SEGMENT}/${HOSTED_SEGMENT}`;
17const THREAD_HREF = String.raw`t3-thread:\/\/v[12]\/`;
18// Unescaped brackets end a label, so consecutive unclosed brackets cannot restart a long scan.
19const LABEL = String.raw`(?:\\[^\n]|[^\\[\]\n])*`;
20const FLAT_LABEL = new RegExp(`^${LABEL}$`);
21const LIST_MARKERS = String.raw`(?:(?:[-*+]|\d{1,9}[.)])[ \t]+)*`;
22const QUOTE_PREFIX = new RegExp(String.raw`^([ \t]*${LIST_MARKERS})(>(?:[ \t]*>)+)`, "gm");
23// Move inter-marker spacing before the quote so fence depth matches and offsets stay intact. A label
24// may span \r or U+2028, which multiline `^` follows, so labels and output are read from the original.
25const threadLinkSource = (markdown: string) =>
26 markdown.replace(QUOTE_PREFIX, (_source, indent: string, quote: string) => {
27 const markers = quote.replace(/[ \t]/g, "");
28 return indent + " ".repeat(quote.length - markers.length) + markers;
29 });
30// CommonMark fences start on their own line (optional blockquotes, indentation, or list markers)
31// and close on a line with at least as many of the same marker; backtick info strings hold no `.
32// Quote markers are compared from the first `>`, so lines may indent them differently.
33// Space after the markers is matched only after a `>`: two adjacent `[ \t]*` backtrack quadratically.
34const AFTER_QUOTE = String.raw`(?:(?<=>)[ \t]*)?`;
35const OPENER_LIST_MARKERS = String.raw`(?:(?:[-*+]|\d{1,9}[.)])[ \t]{1,4}(?![ \t]))*`;
36const fencedCode = (char: "`" | "~", name: string) => {
37 const bq = `${name}Bq`;
38 const info = char === "`" ? "[^`\\r\\n]*" : "[^\\r\\n]*";
39 const closer = String.raw`[ \t]*\k<${bq}>${AFTER_QUOTE}\k<${name}>${char}*(?!${char})[ \t]*\r?$`;
40 return String.raw`^[ \t]*${OPENER_LIST_MARKERS}(?<${bq}>(?:>(?:[ \t]*>)*)?)(?:(?<=>)[ \t]{0,4}(?![ \t])${OPENER_LIST_MARKERS})?(?<${name}>${char}{3,}(?!${char}))${info}(?=\r?$)(?:(?:\r\n?|\n)(?!${closer})[ \t]*\k<${bq}>[^\r\n]*)*(?:(?:\r\n?|\n)${closer})?`;
41};
42// A code span may wrap lines until its paragraph ends: a blank line, heading, list item, fence, rule,
43// setext underline, or deeper blockquote.
44const SPAN_BREAK_LINE =
45 /[ \t>]*(?:\r?$|#{1,6}(?:[ \t]|\r?$)|(?:[-*+]|\d{1,9}[.)])[ \t]|`{3,}[^`\r\n]*\r?$|~{3,})/my;
46const LINE_PREFIX = /([ \t]*)(>|(?:[-*+]|\d{1,9}[.)])[ \t]+)?/y;
47const THEMATIC_BREAK = /^(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})\r?$/;
48const SETEXT_UNDERLINE = /^(?:-+|=+)[ \t]*\r?$/;
49// Earlier alternatives claim text so later ones cannot match inside it: an escaped character opens
50// nothing, code is literal, and a link to anywhere else keeps a thread URL in its label or href.
51const ESCAPED_CHARACTER = String.raw`\\[!-/:-@[-\`{-~]`;
52const LABEL_MARKER = new RegExp(String.raw`${ESCAPED_CHARACTER}|[[\]\n<\`]`, "g");
53// A labeled link's destination may be angle-bracketed, as CommonMark allows: [label](<href>).
54const THREAD_DESTINATION = String.raw`(?:<(?<angleHref>${THREAD_HREF}[^\s<>]+|${HOSTED_LINK})>\)|(?<href>${HOSTED_LINK})\)|(?<customHref>${THREAD_HREF}))`;
55const PARSED_THREAD_DESTINATION = new RegExp(`^${THREAD_DESTINATION}`);
56const LINK_PATTERNS = [
57 String.raw`\[(?<label>${LABEL})\]\(${THREAD_DESTINATION}`,
58 String.raw`\[${LABEL}\]\((?:<[^<>\n]*>|[^\s()]*(?:\([^\s()]*\)[^\s()]*)*)(?:[ \t]+(?:"[^"\n]*"|'[^'\n]*'))?\)`,
59 String.raw`<(?<autolink>${THREAD_HREF}[^\s<>]+|${HOSTED_LINK})>`,
60 // After a URL character the hosted link is part of a longer URL, such as a redirect target.
61 String.raw`(?<![A-Za-z0-9%/?#=&@+-])(?<bare>${HOSTED_LINK})(?!\.*[\w%/?#-])`,
62].join("|");
63const THREAD_LINK = new RegExp(`${ESCAPED_CHARACTER}|${LINK_PATTERNS}`, "gm");
64const THREAD_LINK_OUTSIDE_CODE = new RegExp(
65 [
66 ESCAPED_CHARACTER,
67 fencedCode("`", "bt"),
68 fencedCode("~", "tl"),
69 String.raw`(?<spanTicks>\`+)`,
70 LINK_PATTERNS,
71 ].join("|"),
72 "gm",
73);
74
75function codeSpanLines(markdown: string) {
76 const lines: Array<{ start: number; depth: number; breaksSpan: boolean }> = [];
77 const listIndents: number[] = [];
78 let paragraphDepth: number | undefined;
79 let start = 0;
80 for (const rawLine of markdown.split(/(?<=\n)|(?<=\r)(?!\n)/u)) {
81 const line = rawLine.replace(/[\r\n]+$/u, "");
82 let offset = 0;
83 let depth = 0;
84 let hasList = false;
85 let listOffset = 0;
86 while (offset < line.length) {
87 LINE_PREFIX.lastIndex = offset;
88 const prefix = LINE_PREFIX.exec(line);
89 if (prefix === null) break;
90 const indent = prefix[1]!.replace(/\t/g, " ").length;
91 if (
92 listOffset === 0 &&
93 paragraphDepth === undefined &&
94 indent < (listIndents[depth] ?? 0) &&
95 line.trim()
96 ) {
97 listIndents.length = depth;
98 }
99 const containerIndent = listIndents[depth] ?? 0;
100 const continuedIndent = indent >= containerIndent ? containerIndent : 0;
101 if (prefix[2] === undefined || indent - continuedIndent > 3) break;
102 offset = LINE_PREFIX.lastIndex;
103 if (prefix[2] === ">") {
104 depth++;
105 listOffset = 0;
106 if (line[offset] === " " || line[offset] === "\t") offset++;
107 } else {
108 listOffset += indent + prefix[2]!.replace(/\t/g, " ").length;
109 listIndents[depth] = listOffset;
110 hasList = true;
111 }
112 }
113 const content = line.slice(offset);
114 const text = content.trimStart();
115 const indent = content.slice(0, content.length - text.length).replace(/\t/g, " ").length;
116 const containerIndent = hasList ? 0 : (listIndents[depth] ?? 0);
117 const lazy = indent < containerIndent || depth < (paragraphDepth ?? 0);
118 // Rules and setext underlines end a paragraph unless indented as code; a lazy line is never an underline.
119 const breaksSpan =
120 !hasList &&
121 (lazy ? indent : indent - containerIndent) <= 3 &&
122 (THEMATIC_BREAK.test(text) ||
123 (paragraphDepth !== undefined && !lazy && SETEXT_UNDERLINE.test(text)));
124 const endsParagraph =
125 breaksSpan ||
126 /^(?:[ \t\r]*$|[ \t]*#{1,6}(?:[ \t]|$)|[ \t]*`{3,}[^`]*$|[ \t]*~{3,})/.test(content);
127 const effectiveDepth = endsParagraph || hasList ? depth : Math.max(depth, paragraphDepth ?? 0);
128 lines.push({ start, depth: effectiveDepth, breaksSpan });
129 paragraphDepth = endsParagraph ? undefined : effectiveDepth;
130 start += rawLine.length;
131 }
132 return lines;
133}
134
135function findCodeSpanEnd(
136 markdown: string,
137 openIndex: number,
138 tickCount: number,
139 lines: ReturnType<typeof codeSpanLines>,
140 lineIndex: number,
141): number {
142 const openDepth = lines[lineIndex]!.depth;
143 for (let i = openIndex + tickCount; i < markdown.length; i++) {
144 if (markdown[i] === "`") {
145 let runEnd = i + 1;
146 while (markdown[runEnd] === "`") runEnd++;
147 if (runEnd - i === tickCount) return runEnd;
148 i = runEnd - 1;
149 } else if (i + 1 === lines[lineIndex + 1]?.start) {
150 lineIndex++;
151 SPAN_BREAK_LINE.lastIndex = i + 1;
152 const line = lines[lineIndex]!;
153 if (SPAN_BREAK_LINE.test(markdown) || line.breaksSpan || line.depth > openDepth) return -1;
154 }
155 }
156 return -1;
157}
158
159const decodeThreadId = Schema.decodeUnknownOption(ThreadId);
160const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId);
161
162/** A v1 link names no environment; the message's own, or a unique match, stands in. */
163export interface ThreadLink {
164 readonly environmentId: EnvironmentId | null;
165 readonly threadId: ThreadId;
166 readonly hosted?: boolean;
167}
168
169// Escapes even URL-safe punctuation, so a sentence's closing period never reads as part of an id.
170const hostedSegment = (id: string) =>
171 encodeURIComponent(id).replace(
172 /[.!~*'()]/g,
173 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
174 );
175
176/** Opens the thread from anywhere: the hosted app offers the desktop app, the mobile app, or itself. */
177export function hostedThreadLink(ref: ScopedThreadRef, origin = DEFAULT_HOSTED_APP_URL): string {
178 const path = `/threads/${hostedSegment(ref.environmentId)}/${hostedSegment(ref.threadId)}`;
179 return new URL(path, origin).toString();
180}
181
182const HOSTED_PATH = new RegExp(`^(${HOSTED_SEGMENT})/(${HOSTED_SEGMENT})$`);
183
184function parseHostedThreadLink(href: string): ThreadLink | null {
185 const match = HOSTED_PATH.exec(href.slice(HOSTED_PREFIX.length));
186 if (!match) return null;
187 try {
188 const environmentId = Option.getOrNull(decodeEnvironmentId(decodeURIComponent(match[1]!)));
189 const threadId = Option.getOrNull(decodeThreadId(decodeURIComponent(match[2]!)));
190 return environmentId === null || threadId === null
191 ? null
192 : { environmentId, threadId, hosted: true };
193 } catch {
194 return null;
195 }
196}
197
198/**
199 * The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded,
200 * except in a hosted link, which escapes them itself.
201 */
202export function parseThreadLinkHref(href: string): ThreadLink | null {
203 if (href.startsWith(HOSTED_PREFIX)) return parseHostedThreadLink(href);
204 if (href.startsWith(V1_PREFIX)) {
205 const threadId = Option.getOrNull(decodeThreadId(href.slice(V1_PREFIX.length)));
206 return threadId === null ? null : { environmentId: null, threadId };
207 }
208 if (!href.startsWith(V2_PREFIX)) return null;
209 const path = href.slice(V2_PREFIX.length);
210 const slash = path.indexOf("/");
211 if (slash < 0) return null;
212 const environmentId = Option.getOrNull(decodeEnvironmentId(path.slice(0, slash)));
213 const threadId = Option.getOrNull(decodeThreadId(path.slice(slash + 1)));
214 return environmentId === null || threadId === null ? null : { environmentId, threadId };
215}
216
217function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null {
218 try {
219 const decoded = decodeURIComponent(threadId);
220 return decoded === threadId ? null : Option.getOrNull(decodeThreadId(decoded));
221 } catch {
222 return null;
223 }
224}
225
226/** The threads a link can name, in its own environment or else the message's: as written, then decoded for custom-scheme links. */
227export function threadLinkCandidates(
228 link: ThreadLink,
229 messageEnvironmentId: EnvironmentId,
230): ReadonlyArray<ScopedThreadRef> {
231 const environmentId = link.environmentId ?? messageEnvironmentId;
232 const written = { environmentId, threadId: link.threadId };
233 if (link.hosted) return [written];
234 const decodedId = percentDecodedThreadLinkId(link.threadId);
235 return decodedId === null ? [written] : [written, { environmentId, threadId: decodedId }];
236}
237
238/** A v1 link its message's environment lacks opens a unique match elsewhere; a v2 link never does. */
239export function guessThreadLinkRef(
240 link: ThreadLink,
241 refs: ReadonlyArray<ScopedThreadRef>,
242): ScopedThreadRef | null {
243 if (link.environmentId !== null) return null;
244 const decodedId = percentDecodedThreadLinkId(link.threadId);
245 for (const threadId of decodedId === null ? [link.threadId] : [link.threadId, decodedId]) {
246 let match: ScopedThreadRef | null = null;
247 for (const ref of refs) {
248 if (ref.threadId !== threadId) continue;
249 if (match !== null) return null;
250 match = ref;
251 }
252 if (match !== null) return match;
253 }
254 return null;
255}
256
257// A Markdown destination cannot hold these verbatim. v2 ids are written unescaped, so those links
258// become hosted links, which escape; v1 ids may be escaped because their readers also try decoding.
259const UNSAFE_HREF = /[\s<>\\\p{Cc}]/u;
260
261function threadLinkHref({ environmentId, threadId }: ThreadLink): string {
262 if (environmentId === null) {
263 return V1_PREFIX + (UNSAFE_HREF.test(threadId) ? encodeURIComponent(threadId) : threadId);
264 }
265 // A v2 link splits at its first slash, so an environment id holding one cannot be written there.
266 return environmentId.includes("/") || UNSAFE_HREF.test(environmentId + threadId)
267 ? hostedThreadLink({ environmentId, threadId })
268 : `${V2_PREFIX}${environmentId}/${threadId}`;
269}
270
271const linkLabel = (label: string | undefined) =>
272 label
273 ?.replace(/[[\]\\\r\n]/g, " ")
274 .replace(/\s+/g, " ")
275 .trim();
276
277/** Without a label, an autolink: clients show the thread's current title. */
278export function formatThreadLink(ref: ThreadLink, label?: string): string {
279 const cleaned = linkLabel(label);
280 const href = threadLinkHref(ref);
281 const destination = /[()]/.test(href) ? `<${href}>` : href;
282 return cleaned ? `[${cleaned}](${destination})` : `<${href}>`;
283}
284
285/** What a person copies out of T3 Code: a Markdown link that opens the thread anywhere. */
286export function formatHostedThreadLink(
287 ref: ScopedThreadRef,
288 label: string,
289 origin?: string,
290): string {
291 const href = hostedThreadLink(ref, origin);
292 const cleaned = linkLabel(label);
293 return cleaned ? `[${cleaned}](${href})` : href;
294}
295
296export function hasThreadLinks(markdown: string): boolean {
297 return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`) || markdown.includes(HOSTED_PREFIX);
298}
299
300/** Every thread the markdown's links can name, so their titles are keyed reads. */
301export function threadLinkRefs(
302 markdown: string,
303 messageEnvironmentId: EnvironmentId,
304): ReadonlyArray<ScopedThreadRef> {
305 const refs = new Map<string, ScopedThreadRef>();
306 replaceThreadLinks(markdown, (link) => {
307 for (const ref of threadLinkCandidates(link, messageEnvironmentId)) {
308 refs.set(`${ref.environmentId}/${ref.threadId}`, ref);
309 }
310 return undefined;
311 });
312 return [...refs.values()];
313}
314
315const resourceStarts = new WeakMap<Nodes, number>();
316const destinationRanges = new WeakMap<Nodes, { start: number; end: number }>();
317
318function recordLinkPositions(this: Processor) {
319 (this.data().fromMarkdownExtensions ??= []).push({
320 enter: {
321 resourceDestination(token) {
322 const node = this.stack.at(-1);
323 const { start, end } = token;
324 if (
325 (node?.type === "link" || node?.type === "image") &&
326 start.offset !== undefined &&
327 end.offset !== undefined
328 ) {
329 destinationRanges.set(node, { start: start.offset, end: end.offset });
330 }
331 },
332 resource(token) {
333 const node = this.stack.at(-1);
334 if ((node?.type === "link" || node?.type === "image") && token.start.offset !== undefined) {
335 resourceStarts.set(node, token.start.offset);
336 }
337 },
338 },
339 });
340}
341
342// GFM like the chat renderer, so footnotes and other GFM containers hold prose, not code.
343const markdownParser = unified().use(remarkParse).use(remarkGfm).use(recordLinkPositions);
344const commonMarkParser = unified().use(remarkParse).use(recordLinkPositions);
345const INDENTED_CODE_LINE = /^[ \t>*+\-\d.)]*(?: {4}|\t)/m;
346const FENCE_LIKE_LINE = /^[ \t>*+\-\d.)]*(?:`{3}|~{3})/m;
347const LIST_ITEM_LINE = /^[ \t>]*(?:[-*+]|\d{1,9}[.)])(?:[ \t]|\r?$)/m;
348
349function mayHaveComplexLabel(markdown: string) {
350 if (!markdown.includes("](")) return false;
351 const markers = new RegExp(LABEL_MARKER);
352 let previousBracket: string | undefined;
353 let complex = false;
354 for (let match = markers.exec(markdown); match !== null; match = markers.exec(markdown)) {
355 const marker = match[0];
356 if (marker.length !== 1) continue;
357 if (marker === "[" || marker === "]") {
358 if (marker === previousBracket) return true;
359 if (marker === "]" && markdown[markers.lastIndex] === "(") {
360 if (complex) return true;
361 previousBracket = undefined;
362 continue;
363 }
364 previousBracket = marker;
365 } else if (previousBracket !== undefined) {
366 // Line breaks and inline HTML or code can make bracket order alone misleading.
367 complex = true;
368 }
369 }
370 return false;
371}
372
373function parseMarkdown(markdown: string) {
374 // GFM walks the tree recursively. Plain CommonMark can still parse deeply nested input.
375 for (const parser of [markdownParser, commonMarkParser]) {
376 try {
377 return parser.parse(markdown);
378 } catch (error) {
379 if (!(error instanceof RangeError)) throw error;
380 }
381 }
382 return undefined;
383}
384
385// An HTML tag's quoted attribute may hold a backtick, which must not open a code span. As in
386// CommonMark, escapes and code are read left to right first, so only real tags are masked.
387const BACKTICK_TAG_SCAN = new RegExp(
388 String.raw`${ESCAPED_CHARACTER}|${fencedCode("`", "bt")}|${fencedCode("~", "tl")}|(?<ticks>\`+)|<[A-Za-z][A-Za-z0-9-]*(?:\s+[A-Za-z_:][\w.:-]*(?:\s*=\s*(?:[^\s"'=<>\`]+|'[^']*'|"[^"]*"))?)*\s*\/?>`,
389 "gm",
390);
391
392// Masks whole tags, attribute links included, keeping offsets and line breaks.
393function maskBacktickTags(markdown: string) {
394 if (!markdown.includes("<") || !markdown.includes("`")) return markdown;
395 const pattern = new RegExp(BACKTICK_TAG_SCAN);
396 let lines: ReturnType<typeof codeSpanLines> | undefined;
397 let lineIndex = 0;
398 let masked = "";
399 let cursor = 0;
400 for (let match = pattern.exec(markdown); match !== null; match = pattern.exec(markdown)) {
401 const ticks = match.groups?.ticks;
402 if (ticks !== undefined) {
403 lines ??= codeSpanLines(markdown);
404 while (lineIndex + 1 < lines.length && lines[lineIndex + 1]!.start <= match.index)
405 lineIndex++;
406 const spanEnd = findCodeSpanEnd(markdown, match.index, ticks.length, lines, lineIndex);
407 if (spanEnd !== -1) pattern.lastIndex = spanEnd;
408 } else if (match[0].startsWith("<") && match[0].includes("`")) {
409 masked += markdown.slice(cursor, match.index) + match[0].replace(/[^\r\n]/g, "x");
410 cursor = pattern.lastIndex;
411 }
412 }
413 return masked + markdown.slice(cursor);
414}
415
416function parsedLinkSource(markdown: string) {
417 const text = maskBacktickTags(markdown);
418 // Parse only when an indented line could be code, when a list could end an unclosed fence,
419 // when a footnote or link reference definition may appear, or when a label may exceed the flat scanner.
420 const scanCode =
421 markdown.includes("]:") ||
422 INDENTED_CODE_LINE.test(markdown) ||
423 (LIST_ITEM_LINE.test(markdown) && FENCE_LIKE_LINE.test(markdown));
424 const scanLabels = mayHaveComplexLabel(markdown);
425 const source = threadLinkSource(text);
426 const links = new Map<number, { end: number; href: string | undefined; label: string }>();
427 if (!scanCode && !scanLabels) return { text, source, links, skippedRanges: undefined };
428
429 const root = parseMarkdown(markdown);
430 if (!root) return { text, source, links, skippedRanges: undefined };
431
432 const skippedRanges = scanCode ? new Array<{ start: number; end: number }>() : undefined;
433 const pending: Nodes[] = [root];
434 while (pending.length > 0) {
435 const node = pending.pop()!;
436 const start = node.position?.start.offset;
437 const end = node.position?.end.offset;
438 if (
439 node.type === "code" ||
440 node.type === "inlineCode" ||
441 node.type === "definition" ||
442 node.type === "linkReference" ||
443 node.type === "imageReference"
444 ) {
445 if (start !== undefined && end !== undefined) skippedRanges?.push({ start, end });
446 continue;
447 }
448 if (scanLabels && (node.type === "link" || node.type === "image")) {
449 const resource = resourceStarts.get(node);
450 if (start !== undefined && end !== undefined && resource !== undefined) {
451 const opening = node.type === "image" ? start + 1 : start;
452 const label = markdown.slice(opening + 1, resource - 1);
453 if (!FLAT_LABEL.test(label)) {
454 // Keep the image's leading !, matching the existing flat-label behavior.
455 const range = destinationRanges.get(node);
456 const href =
457 node.title == null && range
458 ? readParsedThreadDestination(markdown.slice(range.start, range.end), node.url)
459 : undefined;
460 links.set(opening, { end, href, label });
461 continue;
462 }
463 }
464 }
465 if ("children" in node) {
466 for (let index = node.children.length - 1; index >= 0; index--) {
467 pending.push(node.children[index]!);
468 }
469 }
470 }
471 return { text, source: scanCode ? text : source, links, skippedRanges };
472}
473
474function readDestination(markdown: string, match: RegExpExecArray) {
475 const start = match.index + match[0].length - match.groups!.customHref!.length;
476 for (let i = start, depth = 0; i < markdown.length; i++) {
477 const ch = markdown[i]!;
478 if (ch === "\\" && /[!-/:-@[-`{-~]/.test(markdown[i + 1] ?? "")) i++;
479 else if (ch === "(") depth++;
480 else if (ch === ")" && depth-- === 0)
481 return { href: markdown.slice(start, i).replace(/\\([!-/:-@[-`{-~])/g, "$1"), end: i + 1 };
482 else if (/[\s\p{Cc}]/u.test(ch)) {
483 const skip = depth === 0 ? /^[ \t]+(?:"[^"\n]*"|'[^'\n]*')\)/.exec(markdown.slice(i)) : null;
484 return { href: undefined, end: skip ? i + skip[0].length : match.index + 1 };
485 }
486 }
487 return { href: undefined, end: match.index + 1 };
488}
489
490function readParsedThreadDestination(destination: string, decoded: string) {
491 // Hosted URLs allow Markdown escapes. Custom-scheme IDs keep their literal spelling.
492 if (decoded.startsWith(HOSTED_PREFIX)) return decoded;
493 const source = destination + ")";
494 const match = PARSED_THREAD_DESTINATION.exec(source);
495 return match?.groups?.customHref ? readDestination(source, match).href : match?.groups?.angleHref;
496}
497
498/** Rewrites each link outside code `replace` answers for. `label` is a Markdown link's own text. */
499export function replaceThreadLinks(
500 markdown: string,
501 replace: (link: ThreadLink, label: string | undefined) => string | undefined,
502): string {
503 if (!hasThreadLinks(markdown)) return markdown;
504 // A leading BOM is not content: Markdown blocks such as fences start after it.
505 if (markdown.startsWith("\uFEFF"))
506 return `\uFEFF${replaceThreadLinks(markdown.slice(1), replace)}`;
507 // Hermes' matchAll yields matches without `groups`; exec keeps them.
508 const { text, source, links, skippedRanges } = parsedLinkSource(markdown);
509 const basePattern = skippedRanges ? THREAD_LINK : THREAD_LINK_OUTSIDE_CODE;
510 const pattern = new RegExp(
511 links.size ? String.raw`${basePattern.source}|\[` : basePattern.source,
512 "gm",
513 );
514 let result = "";
515 let cursor = 0;
516 let lines: ReturnType<typeof codeSpanLines> | undefined;
517 let lineIndex = 0;
518 let rangeIndex = 0;
519 for (let match = pattern.exec(source); match !== null; match = pattern.exec(source)) {
520 while (skippedRanges?.[rangeIndex] && skippedRanges[rangeIndex]!.end <= match.index) {
521 rangeIndex++;
522 }
523 const range = skippedRanges?.[rangeIndex];
524 if (range && range.start <= match.index) {
525 pattern.lastIndex = range.end;
526 continue;
527 }
528 const spanTicks = match.groups?.spanTicks;
529 if (spanTicks !== undefined) {
530 lines ??= codeSpanLines(text);
531 while (lineIndex + 1 < lines.length && lines[lineIndex + 1]!.start <= match.index)
532 lineIndex++;
533 const spanEnd = findCodeSpanEnd(text, match.index, spanTicks.length, lines, lineIndex);
534 if (spanEnd !== -1) pattern.lastIndex = spanEnd;
535 continue;
536 }
537 const parsed = links.get(match.index);
538 let href =
539 match.groups?.angleHref ?? match.groups?.href ?? match.groups?.autolink ?? match.groups?.bare;
540 if (parsed) ({ href, end: pattern.lastIndex } = parsed);
541 else if (match.groups?.customHref)
542 ({ href, end: pattern.lastIndex } = readDestination(markdown, match));
543 const link = href === undefined ? null : parseThreadLinkHref(href);
544 const flatLabel = match.groups?.label;
545 const label =
546 parsed?.label ??
547 (flatLabel && markdown.slice(match.index + 1, match.index + 1 + flatLabel.length));
548 const rewritten = link === null ? undefined : replace(link, label);
549 if (rewritten === undefined) continue;
550 result += markdown.slice(cursor, match.index) + rewritten;
551 cursor = pattern.lastIndex;
552 }
553 return cursor === 0 ? markdown : result + markdown.slice(cursor);
554}