Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

threadLinks.ts

154 lines6.2 KB

1import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4​
5export const THREAD_LINK_PROTOCOL = "t3-thread";
6const V1_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;
7const V2_PREFIX = `${THREAD_LINK_PROTOCOL}://v2/`;
8// Code comes first in the alternation so a link written inside a code span or fence is skipped.
9const THREAD_LINK_OUTSIDE_CODE =
10 /(?<fence>(`{3,}|~{3,})[\s\S]*?(?:\2|$))|(?<span>(`+)[^\n]*?\4)|\[(?<label>[^\]\n]*)\]\((?<href>t3-thread:\/\/v[12]\/[^\s)]+)\)|<(?<autolink>t3-thread:\/\/v[12]\/[^\s<>]+)>/g;
11​
12const decodeThreadId = Schema.decodeUnknownOption(ThreadId);
13const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId);
14​
15/** A v1 link names no environment; the message's own, or a unique match, stands in. */
16export interface ThreadLink {
17 readonly environmentId: EnvironmentId | null;
18 readonly threadId: ThreadId;
20​
21/** The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded. */
22export function parseThreadLinkHref(href: string): ThreadLink | null {
23 if (href.startsWith(V1_PREFIX)) {
24 const threadId = Option.getOrNull(decodeThreadId(href.slice(V1_PREFIX.length)));
25 return threadId === null ? null : { environmentId: null, threadId };
26 }
27 if (!href.startsWith(V2_PREFIX)) return null;
28 const path = href.slice(V2_PREFIX.length);
29 const slash = path.indexOf("/");
30 if (slash < 0) return null;
31 const environmentId = Option.getOrNull(decodeEnvironmentId(path.slice(0, slash)));
32 const threadId = Option.getOrNull(decodeThreadId(path.slice(slash + 1)));
33 return environmentId === null || threadId === null ? null : { environmentId, threadId };
35​
36export function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null {
37 try {
38 const decoded = decodeURIComponent(threadId);
39 return decoded === threadId ? null : Option.getOrNull(decodeThreadId(decoded));
40 } catch {
41 return null;
42 }
44​
45/** The threads a link can name, in its own environment or else the message's: as written, then decoded. */
46export function threadLinkCandidates(
47 link: ThreadLink,
48 messageEnvironmentId: EnvironmentId,
49): ReadonlyArray<ScopedThreadRef> {
50 const environmentId = link.environmentId ?? messageEnvironmentId;
51 const decodedId = percentDecodedThreadLinkId(link.threadId);
52 const written = { environmentId, threadId: link.threadId };
53 return decodedId === null ? [written] : [written, { environmentId, threadId: decodedId }];
55​
56/** A v1 link its message's environment lacks opens a unique match elsewhere; a v2 link never does. */
57export function guessThreadLinkRef(
58 link: ThreadLink,
59 refs: ReadonlyArray<ScopedThreadRef>,
60): ScopedThreadRef | null {
61 if (link.environmentId !== null) return null;
62 const decodedId = percentDecodedThreadLinkId(link.threadId);
63 for (const threadId of decodedId === null ? [link.threadId] : [link.threadId, decodedId]) {
64 let match: ScopedThreadRef | null = null;
65 for (const ref of refs) {
66 if (ref.threadId !== threadId) continue;
67 if (match !== null) return null;
68 match = ref;
69 }
70 if (match !== null) return match;
71 }
72 return null;
74​
75function threadLinkHref(link: ThreadLink): string {
76 return link.environmentId === null
77 ? `${V1_PREFIX}${link.threadId}`
78 : `${V2_PREFIX}${link.environmentId}/${link.threadId}`;
80​
81/** Without a label, an autolink: clients show the thread's current title. */
82export function formatThreadLink(ref: ThreadLink, label?: string): string {
83 const cleaned = label
84 ?.replace(/[[\]\\\r\n]/g, " ")
85 .replace(/\s+/g, " ")
86 .trim();
87 return cleaned ? `[${cleaned}](${threadLinkHref(ref)})` : `<${threadLinkHref(ref)}>`;
89​
90export function hasThreadLinks(markdown: string): boolean {
91 return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`);
93​
94/** Every thread the markdown's links can name, so their titles are keyed reads. */
95export function threadLinkRefs(
96 markdown: string,
97 messageEnvironmentId: EnvironmentId,
98): ReadonlyArray<ScopedThreadRef> {
99 const refs = new Map<string, ScopedThreadRef>();
100 for (const match of markdown.matchAll(THREAD_LINK_OUTSIDE_CODE)) {
101 const href = match.groups?.href ?? match.groups?.autolink;
102 const link = href === undefined ? null : parseThreadLinkHref(href);
103 if (link === null) continue;
104 for (const ref of threadLinkCandidates(link, messageEnvironmentId)) {
105 refs.set(`${ref.environmentId}/${ref.threadId}`, ref);
106 }
107 }
108 return [...refs.values()];
110​
111export function unknownThreadLinkLabel(
112 link: ThreadLink,
113 messageEnvironmentId: EnvironmentId,
114): string {
115 return link.environmentId === null || link.environmentId === messageEnvironmentId
116 ? "Thread no longer available"
117 : "Thread on another machine";
119​
120/**
121 * Writes each link with its thread's current title. A link `title` cannot resolve becomes plain
122 * text, its written label or a neutral one, except a labeled v1 link, which may open elsewhere.
123 */
124export function relabelThreadLinks(
125 markdown: string,
126 messageEnvironmentId: EnvironmentId,
127 title: (ref: ScopedThreadRef) => string | undefined,
128): string {
129 if (!hasThreadLinks(markdown)) return markdown;
130 return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => {
131 const groups = args.at(-1) as { href?: string; autolink?: string; label?: string };
132 const href = groups.href ?? groups.autolink;
133 if (href === undefined) return source;
134 const written = parseThreadLinkHref(href);
135 if (written === null) return source;
136 const environmentId = written.environmentId ?? messageEnvironmentId;
137 const decoded = percentDecodedThreadLinkId(written.threadId);
138 const threadId =
139 title({ environmentId, threadId: written.threadId }) === undefined &&
140 decoded !== null &&
141 title({ environmentId, threadId: decoded }) !== undefined
142 ? decoded
143 : written.threadId;
144 const current = title({ environmentId, threadId });
145 if (current === undefined) {
146 if (groups.href !== undefined && written.environmentId === null) return source;
147 return groups.label?.trim() || unknownThreadLinkLabel(written, messageEnvironmentId);
148 }
149 return formatThreadLink(
150 { environmentId: written.environmentId, threadId },
151 current.trim() || groups.label || threadId,
152 );
153 });