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

threadLinks.ts

217 lines8.8 KB

1import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";
2import * as Option from "effect/Option";
3import * as Schema from "effect/Schema";
4​
5import { DEFAULT_HOSTED_APP_URL } from "./connectAuth.ts";
6​
7export const THREAD_LINK_PROTOCOL = "t3-thread";
8const V1_PREFIX = `${THREAD_LINK_PROTOCOL}://v1/`;
9const V2_PREFIX = `${THREAD_LINK_PROTOCOL}://v2/`;
10const HOSTED_PREFIX = `${DEFAULT_HOSTED_APP_URL}/threads/`;
11const HOSTED_SEGMENT = "[A-Za-z0-9_%-]+";
12const HOSTED_LINK = `${HOSTED_PREFIX.replace(/[.*+?^${}()|[\]\\/]/g, "\\$&")}${HOSTED_SEGMENT}/${HOSTED_SEGMENT}`;
13// Code comes first in the alternation so a link written inside a code span or fence is skipped.
14const THREAD_LINK_OUTSIDE_CODE = new RegExp(
15 String.raw`(?<fence>(\`{3,}|~{3,})[\s\S]*?(?:\2|$))|(?<span>(\`+)[^\n]*?\4)|\[(?<label>[^\]\n]*)\]\((?<href>t3-thread:\/\/v[12]\/[^\s)]+|${HOSTED_LINK})\)|<(?<autolink>t3-thread:\/\/v[12]\/[^\s<>]+|${HOSTED_LINK})>|(?<bare>${HOSTED_LINK})(?![\w%/?#-])`,
16 "g",
17);
18​
19const decodeThreadId = Schema.decodeUnknownOption(ThreadId);
20const decodeEnvironmentId = Schema.decodeUnknownOption(EnvironmentId);
21​
22/** A v1 link names no environment; the message's own, or a unique match, stands in. */
23export interface ThreadLink {
24 readonly environmentId: EnvironmentId | null;
25 readonly threadId: ThreadId;
27​
28// Escapes even URL-safe punctuation, so a sentence's closing period never reads as part of an id.
29const hostedSegment = (id: string) =>
30 encodeURIComponent(id).replace(
31 /[.!~*'()]/g,
32 (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,
33 );
34​
35/** Opens the thread from anywhere: the hosted app offers the desktop app, the mobile app, or itself. */
36export function hostedThreadLink(ref: ScopedThreadRef, origin = DEFAULT_HOSTED_APP_URL): string {
37 const path = `/threads/${hostedSegment(ref.environmentId)}/${hostedSegment(ref.threadId)}`;
38 return new URL(path, origin).toString();
40​
41const HOSTED_PATH = new RegExp(`^(${HOSTED_SEGMENT})/(${HOSTED_SEGMENT})$`);
42​
43function parseHostedThreadLink(href: string): ThreadLink | null {
44 const match = HOSTED_PATH.exec(href.slice(HOSTED_PREFIX.length));
45 if (!match) return null;
46 try {
47 const environmentId = Option.getOrNull(decodeEnvironmentId(decodeURIComponent(match[1]!)));
48 const threadId = Option.getOrNull(decodeThreadId(decodeURIComponent(match[2]!)));
49 return environmentId === null || threadId === null ? null : { environmentId, threadId };
50 } catch {
51 return null;
52 }
54​
55/**
56 * The ids as written. Thread ids can hold percent escapes of their own, so they are not decoded,
57 * except in a hosted link, which escapes them itself.
58 */
59export function parseThreadLinkHref(href: string): ThreadLink | null {
60 if (href.startsWith(HOSTED_PREFIX)) return parseHostedThreadLink(href);
61 if (href.startsWith(V1_PREFIX)) {
62 const threadId = Option.getOrNull(decodeThreadId(href.slice(V1_PREFIX.length)));
63 return threadId === null ? null : { environmentId: null, threadId };
64 }
65 if (!href.startsWith(V2_PREFIX)) return null;
66 const path = href.slice(V2_PREFIX.length);
67 const slash = path.indexOf("/");
68 if (slash < 0) return null;
69 const environmentId = Option.getOrNull(decodeEnvironmentId(path.slice(0, slash)));
70 const threadId = Option.getOrNull(decodeThreadId(path.slice(slash + 1)));
71 return environmentId === null || threadId === null ? null : { environmentId, threadId };
73​
74export function percentDecodedThreadLinkId(threadId: ThreadId): ThreadId | null {
75 try {
76 const decoded = decodeURIComponent(threadId);
77 return decoded === threadId ? null : Option.getOrNull(decodeThreadId(decoded));
78 } catch {
79 return null;
80 }
82​
83/** The threads a link can name, in its own environment or else the message's: as written, then decoded. */
84export function threadLinkCandidates(
85 link: ThreadLink,
86 messageEnvironmentId: EnvironmentId,
87): ReadonlyArray<ScopedThreadRef> {
88 const environmentId = link.environmentId ?? messageEnvironmentId;
89 const decodedId = percentDecodedThreadLinkId(link.threadId);
90 const written = { environmentId, threadId: link.threadId };
91 return decodedId === null ? [written] : [written, { environmentId, threadId: decodedId }];
93​
94/** A v1 link its message's environment lacks opens a unique match elsewhere; a v2 link never does. */
95export function guessThreadLinkRef(
96 link: ThreadLink,
97 refs: ReadonlyArray<ScopedThreadRef>,
98): ScopedThreadRef | null {
99 if (link.environmentId !== null) return null;
100 const decodedId = percentDecodedThreadLinkId(link.threadId);
101 for (const threadId of decodedId === null ? [link.threadId] : [link.threadId, decodedId]) {
102 let match: ScopedThreadRef | null = null;
103 for (const ref of refs) {
104 if (ref.threadId !== threadId) continue;
105 if (match !== null) return null;
106 match = ref;
107 }
108 if (match !== null) return match;
109 }
110 return null;
112​
113function threadLinkHref(link: ThreadLink): string {
114 return link.environmentId === null
115 ? `${V1_PREFIX}${link.threadId}`
116 : `${V2_PREFIX}${link.environmentId}/${link.threadId}`;
118​
119const linkLabel = (label: string | undefined) =>
120 label
121 ?.replace(/[[\]\\\r\n]/g, " ")
122 .replace(/\s+/g, " ")
123 .trim();
124​
125/** Without a label, an autolink: clients show the thread's current title. */
126export function formatThreadLink(ref: ThreadLink, label?: string): string {
127 const cleaned = linkLabel(label);
128 return cleaned ? `[${cleaned}](${threadLinkHref(ref)})` : `<${threadLinkHref(ref)}>`;
130​
131/** What a person copies out of T3 Code: a Markdown link that opens the thread anywhere. */
132export function formatHostedThreadLink(
133 ref: ScopedThreadRef,
134 label: string,
135 origin?: string,
136): string {
137 const href = hostedThreadLink(ref, origin);
138 const cleaned = linkLabel(label);
139 return cleaned ? `[${cleaned}](${href})` : href;
141​
142export function hasThreadLinks(markdown: string): boolean {
143 return markdown.includes(`${THREAD_LINK_PROTOCOL}://v`) || markdown.includes(HOSTED_PREFIX);
145​
146/** Every thread the markdown's links can name, so their titles are keyed reads. */
147export function threadLinkRefs(
148 markdown: string,
149 messageEnvironmentId: EnvironmentId,
150): ReadonlyArray<ScopedThreadRef> {
151 const refs = new Map<string, ScopedThreadRef>();
152 // Hermes' matchAll yields matches without `groups`; exec keeps them.
153 const pattern = new RegExp(THREAD_LINK_OUTSIDE_CODE);
154 for (let match = pattern.exec(markdown); match !== null; match = pattern.exec(markdown)) {
155 const href = match.groups?.href ?? match.groups?.autolink ?? match.groups?.bare;
156 const link = href === undefined ? null : parseThreadLinkHref(href);
157 if (link === null) continue;
158 for (const ref of threadLinkCandidates(link, messageEnvironmentId)) {
159 refs.set(`${ref.environmentId}/${ref.threadId}`, ref);
160 }
161 }
162 return [...refs.values()];
164​
165export function unknownThreadLinkLabel(
166 link: ThreadLink,
167 messageEnvironmentId: EnvironmentId,
168): string {
169 return link.environmentId === null || link.environmentId === messageEnvironmentId
170 ? "Thread no longer available"
171 : "Thread on another machine";
173​
174/** Rewrites each link outside code `replace` answers for. `label` is a Markdown link's own text. */
175export function replaceThreadLinks(
176 markdown: string,
177 replace: (link: ThreadLink, label: string | undefined) => string | undefined,
178): string {
179 if (!hasThreadLinks(markdown)) return markdown;
180 return markdown.replace(THREAD_LINK_OUTSIDE_CODE, (source, ...args) => {
181 const groups = args.at(-1) as Partial<Record<"href" | "autolink" | "bare" | "label", string>>;
182 const href = groups.href ?? groups.autolink ?? groups.bare;
183 const link = href === undefined ? null : parseThreadLinkHref(href);
184 return (link && replace(link, groups.label)) ?? source;
185 });
187​
188/**
189 * Writes each link with its thread's current title, a hosted link as a v2 link. A link `title`
190 * cannot resolve becomes plain text, its written label or a neutral one, except a labeled v1
191 * link, which may open elsewhere.
192 */
193export function relabelThreadLinks(
194 markdown: string,
195 messageEnvironmentId: EnvironmentId,
196 title: (ref: ScopedThreadRef) => string | undefined,
197): string {
198 return replaceThreadLinks(markdown, (written, label) => {
199 const environmentId = written.environmentId ?? messageEnvironmentId;
200 const decoded = percentDecodedThreadLinkId(written.threadId);
201 const threadId =
202 title({ environmentId, threadId: written.threadId }) === undefined &&
203 decoded !== null &&
204 title({ environmentId, threadId: decoded }) !== undefined
205 ? decoded
206 : written.threadId;
207 const current = title({ environmentId, threadId });
208 if (current === undefined) {
209 if (label !== undefined && written.environmentId === null) return undefined;
210 return label?.trim() || unknownThreadLinkLabel(written, messageEnvironmentId);
211 }
212 return formatThreadLink(
213 { environmentId: written.environmentId, threadId },
214 current.trim() || label || threadId,
215 );
216 });