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

terminal-links.ts

342 lines14.9 KB

1import { scriptPunctuationAfterAscii } from "@t3tools/shared/markdownLinks";
2import { parseFileUrlHref, resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
3import { isMacPlatform } from "./lib/utils";
4​
5export type TerminalLinkKind = "url" | "path";
6​
7export interface TerminalLinkMatch {
8 kind: TerminalLinkKind;
9 text: string;
10 start: number;
11 end: number;
12 /**
13 * `text` cut after its `:line:col` or after the `(line)` of a pdb frame, or with its closing
14 * `(line,col)`, `:[line,col]` or `:line` and its number, each read as a position. Only the
15 * filesystem can tell grep's `./a.js:1:function` or MSBuild's `/a.cs(1,2)` from a name that
16 * holds those characters, so this stands in when `text` as a whole is not a file.
17 */
18 fallback?: { text: string; end: number };
20​
21export interface TerminalBufferLineLike {
22 readonly isWrapped?: boolean;
23 translateToString(trimRight?: boolean): string;
25​
26export interface WrappedTerminalLinkLineSegment {
27 bufferLineNumber: number;
28 text: string;
29 startIndex: number;
30 endIndex: number;
32​
33export interface WrappedTerminalLinkLine {
34 text: string;
35 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
37​
38const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/giu;
39// The default PowerShell prompt delimits its unquoted path with `PS ` and `>`.
40const POWERSHELL_PROMPT_PATH_PATTERN = /^PS ((?:[A-Za-z]:[\\/]|\\\\|\/)[^>\r\n]*)>/u;
41// Bare paths start only at a segment boundary: hover detection runs this on
42// every frame, so separator-free output must not be rescanned at every suffix.
43// Parenthesized path segments need a following slash to distinguish compiler locations.
44// A bare `name.ext` needs `:line:col`, a TS location, or a line-start Bash `: line N:` after it.
45const FILE_PATH_PATTERN =
46 /(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|(?<![\p{L}\p{M}\p{N}._$+@-])[\p{L}\p{M}\p{N}._$+@-]+(?:(?:[\\/](?:[\p{L}\p{M}\p{N}._$+@-]|\[{1,2}[\p{L}\p{M}\p{N}._-]+\]{1,2}|\([\p{L}\p{M}\p{N}._-]+\)(?=[\\/]))+)+|\.\p{L}[\p{L}\p{M}\p{N}_-]*(?=:\d+:\d|\(\d+,\d+\):\s+(?:error|warning) TS\d+:))(?:(?::\d+){1,2}|\(\d+,\d+\)(?=:\s+(?:error|warning) (?:TS|CS)\d+:))?|^[\p{L}\p{M}\p{N}._$+@-]+\.\p{L}[\p{L}\p{M}\p{N}_-]*(?=: line \d+:)/gu;
47const QUOTED_FILE_PATH_PATTERN =
48 /(["'`])(?<path>(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\|[\p{L}\p{M}\p{N}._ -]+[\\/])[^\r\n]*?|[\p{L}\p{M}\p{N}._ -]+\.[\p{L}\p{M}\p{N}_-]+(?::\d+){0,2})\1(?<position>(?::\d+){0,2})/gu;
49// The `:line` or `:line:col` that grep, ripgrep and Ruby backtraces follow with a colon and text.
50const POSITION_BEFORE_TEXT_PATTERN = /^.+?(?::\d+){1,2}(?=:)/u;
51const POSITIONS_ONLY_PATTERN = /^(?::\d+)+$/u;
52// The `(line)` or `(line,col)` that MSBuild, MSVC and PHP stack frames put right after a file name.
53const PARENTHESIZED_POSITION_PATTERN = /(?<![\\/])\((\d+)(?:,(\d+))?\)$/u;
54// The `:[line]` or `:[line,col]` that Maven's compiler plugin puts there instead.
55const BRACKETED_POSITION_PATTERN = /(?<![\\/]):\[(\d+)(?:,(\d+))?\]$/u;
56// The `:line 29` that .NET stack frames put there; the candidate stops at the space, so the
57// number is read from the text after it.
58const LINE_WORD_PATTERN = /(?<![\\/]):line$/u;
59const NUMBER_AFTER_LINE_WORD_PATTERN = /^ (\d+)\b/u;
60// The `, line 12` that a Python traceback puts after the quoted file name, and the ` line: 12`
61// that Gradle puts after `Build file '...'`.
62const LINE_AFTER_QUOTE_PATTERN = /^(?:", line |' line: )(\d+)\b/u;
63// The `: line 3` of bash, the ` on line 3` of PHP and the ` line 3` of Perl after a bare path.
64const LINE_AFTER_PATH_PATTERN = /^(?::| on)? line (\d+)\b/u;
65// The `(line)` that pdb follows with the function name, as in `/a.py(3)f()` or `/a.py(3)f()->None`;
66// the candidate stops at the `>`.
67const POSITION_BEFORE_FUNCTION_PATTERN = /^.+[^\\/]\(\d+\)(?=[\p{L}\p{M}\p{N}_]+\(\)-?$)/u;
68const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
69// Paths also drop a trailing colon: compilers end `file:line:col:` with one.
70const TRAILING_PATH_PUNCTUATION_PATTERN = /[.,;:!?]+$/;
71// A question mark is legal in filenames; only exclude query-bearing request targets.
72const REQUEST_ROUTE_PATTERN =
73 /(?:^|[\s"'`])(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|CONNECT|TRACE|proxying)\s+["'`]?(?:\/|[A-Za-z0-9_-]+\/)[^\s?]*\?\S*/g;
74// The tail of `redis://host/0` or `file:///a.mjs` is not a path. One-letter schemes stay drives,
75// a diff's `+` or `-` may lead, and the lookbehind keeps runs from being rescanned at every suffix.
76const SCHEME_URL_PATTERN = /(?<![A-Za-z\d+.-])[+-]?[A-Za-z][A-Za-z\d+.-]+:\/\/[^\s"'`<>]+/gu;
77// Nor is the tail of an SCP-style Git remote such as `git@github.com:acme/widgets.git`. Only a
78// path wholly inside the tail is dropped, so `src/contact@support.vue:12:3` keeps its link.
79const SCP_REMOTE_PATTERN = /(?<![\w.@-])[\w.-]+@[\w.-]+:[^\s"'`<>]+/gu;
80​
81function trimClosingDelimiters(rawValue: string, kind: TerminalLinkKind, emphasis: string): string {
82 // A URL or path that is ASCII up to a full-width mark ends there, as the chat renderer ends it.
83 const stop = scriptPunctuationAfterAscii(rawValue);
84 const value = stop > 0 ? rawValue.slice(0, stop) : rawValue;
85 const trailingPunctuation =
86 kind === "path" ? TRAILING_PATH_PUNCTUATION_PATTERN : TRAILING_PUNCTUATION_PATTERN;
87 const unpunctuated = value.replace(trailingPunctuation, "");
88 // Only the marks that close `**https://example.com**` go; `https://example.com/?q=*` keeps its own.
89 const closesEmphasis = emphasis.length > 0 && unpunctuated.endsWith(emphasis);
90 const output = closesEmphasis
91 ? unpunctuated.slice(0, -emphasis.length).replace(trailingPunctuation, "")
92 : unpunctuated;
93 if (output.length === 0) return output;
94 const excess = new Map<string, number>(
95 (
96 [
97 ["(", ")"],
98 ["[", "]"],
99 ["{", "}"],
100 ] as const
101 ).map(([open, close]) => [close, output.split(close).length - output.split(open).length]),
102 );
103 let end = output.length;
104 // Walk the suffix in order so mixed wrappers such as `[(url)]` peel from the outside in.
105 for (let close = output.charAt(end - 1); (excess.get(close) ?? 0) > 0;) {
106 excess.set(close, (excess.get(close) ?? 0) - 1);
107 end -= 1;
108 close = output.charAt(end - 1);
109 }
110 // Peeling a closer can expose sentence punctuation, as in `(see https://example.com/docs.)`.
111 const peeled = output.slice(0, end).replace(trailingPunctuation, "");
112 // It can also expose the closing marks, as in `(**https://example.com**)`, if none went yet.
113 return !closesEmphasis && end < output.length && emphasis.length > 0 && peeled.endsWith(emphasis)
114 ? trimClosingDelimiters(peeled.slice(0, -emphasis.length), kind, "")
115 : peeled;
117​
118// The marks that open `**see (https://example.com)**` and are still open at the URL. A run opens
119// only after a space or opening bracket, as in Markdown, so `src/*.ts` and `2*3` do not; a run
120// after text closes the open run of the same length. Code spans hold no emphasis.
121function openingEmphasisBefore(line: string, start: number): string {
122 const text = line.slice(0, start).replace(/`[^`]*`/gu, (span) => " ".repeat(span.length));
123 // A backtick left open before the link and closed after it puts the link in a code span.
124 if (text.includes("`") && line.indexOf("`", start) !== -1) return "";
125 const open: string[] = [];
126 for (const run of text.matchAll(/\*+/gu)) {
127 const before = text.charAt(run.index - 1);
128 const after = text.charAt(run.index + run[0].length);
129 if (/^[\s([{]?$/u.test(before)) {
130 if (after !== "" && !/\s/u.test(after)) open.push(run[0]);
131 } else if (open.at(-1) === run[0]) open.pop();
132 }
133 return open.at(-1) ?? "";
135​
136function toPosition(_: string, row: string, column?: string): string {
137 return column === undefined ? `:${row}` : `:${row}:${column}`;
139​
140function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
141 return a.start < b.end && b.start < a.end;
143​
144function collectMatches(
145 line: string,
146 kind: TerminalLinkKind,
147 pattern: RegExp,
148 existing: TerminalLinkMatch[],
149): TerminalLinkMatch[] {
150 const matches: TerminalLinkMatch[] = [];
151 pattern.lastIndex = 0;
152​
153 for (const rawMatch of line.matchAll(pattern)) {
154 const quotedPath = rawMatch.groups?.path;
155 const raw =
156 quotedPath === undefined ? rawMatch[0] : quotedPath + (rawMatch.groups?.position ?? "");
157 const start = rawMatch.index + (quotedPath === undefined ? 0 : 1);
158 if (start < 0 || raw.length === 0) continue;
159​
160 let emphasisStart = start;
161 while (line.charAt(emphasisStart - 1) === "*") emphasisStart -= 1;
162 const emphasis = line.slice(emphasisStart, start);
163 const trimmed =
164 quotedPath === undefined
165 ? trimClosingDelimiters(
166 raw,
167 kind,
168 emphasis || (raw.includes("*") ? openingEmphasisBefore(line, start) : ""),
169 )
170 : raw;
171 if (trimmed.length === 0) continue;
172 if (kind === "path" && isTerminalUrl(trimmed)) continue;
173​
174 const cut =
175 kind === "path" && quotedPath === undefined
176 ? POSITION_BEFORE_TEXT_PATTERN.exec(trimmed)?.[0]
177 : undefined;
178 // What follows `main.c:10` in `main.c:10:5` is its column, not text.
179 const fallback =
180 cut !== undefined && !POSITIONS_ONLY_PATTERN.test(trimmed.slice(cut.length))
181 ? cut
182 : undefined;
183 const text =
184 kind === "path" && /^:\s+(?:error|warning) TS\d+:/u.test(line.slice(start + trimmed.length))
185 ? trimmed.replace(/\((\d+),(\d+)\)$/, ":$1:$2")
186 : trimmed;
187 const located =
188 kind === "path" && quotedPath === undefined
189 ? text
190 .replace(PARENTHESIZED_POSITION_PATTERN, toPosition)
191 .replace(BRACKETED_POSITION_PATTERN, toPosition)
192 .replace(LINE_WORD_PATTERN, (word) => {
193 const row = NUMBER_AFTER_LINE_WORD_PATTERN.exec(line.slice(start + trimmed.length));
194 return row ? `:${row[1]}` : word;
195 })
196 : text;
197 const frame =
198 kind === "path" && quotedPath === undefined
199 ? POSITION_BEFORE_FUNCTION_PATTERN.exec(text)?.[0]
200 : undefined;
201 const lineAfterPath =
202 kind === "path" && !/:\d+(?:-\d+)?$/u.test(trimmed)
203 ? (quotedPath !== undefined ? LINE_AFTER_QUOTE_PATTERN : LINE_AFTER_PATH_PATTERN).exec(
204 line.slice(start + trimmed.length),
205 )?.[1]
206 : undefined;
207 const candidate: TerminalLinkMatch = {
208 kind,
209 text: lineAfterPath === undefined ? text : `${text}:${lineAfterPath}`,
210 start,
211 // A position outside quotes spans the closing quote in the terminal buffer.
212 end: start + trimmed.length + (rawMatch.groups?.position ? 1 : 0),
213 ...(fallback !== undefined
214 ? { fallback: { text: fallback, end: start + fallback.length } }
215 : located !== text
216 ? { fallback: { text: located, end: start + trimmed.length } }
217 : frame !== undefined
218 ? {
219 fallback: {
220 text: frame.replace(PARENTHESIZED_POSITION_PATTERN, toPosition),
221 end: start + frame.length,
222 },
223 }
224 : {}),
225 };
226​
227 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
228 if (collides) continue;
229​
230 matches.push(candidate);
231 }
232​
233 return matches;
235​
236export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
237 const promptPath = POWERSHELL_PROMPT_PATH_PATTERN.exec(line)?.[1];
238 const promptMatches: TerminalLinkMatch[] = promptPath
239 ? [{ kind: "path", text: promptPath, start: 3, end: 3 + promptPath.length }]
240 : [];
241 const nonPathRanges = Array.from(
242 [...line.matchAll(REQUEST_ROUTE_PATTERN), ...line.matchAll(SCHEME_URL_PATTERN)],
243 (match) => ({ start: match.index, end: match.index + match[0].length }),
244 );
245 const remoteTails = Array.from(line.matchAll(SCP_REMOTE_PATTERN), (match) => ({
246 start: match.index + match[0].indexOf(":") + 1,
247 end: match.index + match[0].length,
248 }));
249 const urlMatches = collectMatches(line, "url", URL_PATTERN, promptMatches);
250 const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, [
251 ...promptMatches,
252 ...urlMatches,
253 ]);
254 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, [
255 ...promptMatches,
256 ...urlMatches,
257 ...quotedMatches,
258 ]);
259 return [...promptMatches, ...urlMatches, ...quotedMatches, ...pathMatches]
260 .filter(
261 (match) =>
262 match.kind === "url" ||
263 (!nonPathRanges.some((range) => overlaps(match, range)) &&
264 !remoteTails.some((tail) => match.start >= tail.start && match.end <= tail.end)),
265 )
266 .toSorted((a, b) => a.start - b.start);
268​
269export function isTerminalUrl(value: string): boolean {
270 return /^https?:\/\//iu.test(value);
272​
273/**
274 * Explicit OSC 8 targets may be `file://` URIs; everything else is a path relative to `cwd`.
275 * `hostname` is the terminal's environment's, which producers such as GNU `ls` put in the URI.
276 * A URI's path is the exact filename, so only its `#L12C3` hash is a position.
277 */
278export function resolveTerminalLinkTarget(text: string, cwd: string, hostname?: string): string {
279 const fileUrl = /^file:\/\//iu.test(text) ? parseFileUrlHref(text, hostname) : null;
280 if (!fileUrl) return resolvePathLinkTarget(text, cwd);
281 // Keep URI identity until consumers decode the filename, separately from its position.
282 const uri = new URL(text);
283 if (!fileUrl.path.startsWith("\\")) uri.hostname = "";
284 return uri.href;
286​
287export function collectWrappedTerminalLinkLine(
288 bufferLineNumber: number,
289 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
290): WrappedTerminalLinkLine | null {
291 const anchorLine = getLine(bufferLineNumber - 1);
292 if (!anchorLine) return null;
293​
294 let startBufferLineNumber = bufferLineNumber;
295 let startLine = anchorLine;
296​
297 while (startBufferLineNumber > 1 && startLine.isWrapped) {
298 const previousLine = getLine(startBufferLineNumber - 2);
299 if (!previousLine) return null;
300 startBufferLineNumber -= 1;
301 startLine = previousLine;
302 }
303​
304 const segments: WrappedTerminalLinkLineSegment[] = [];
305 let nextStartIndex = 0;
306 let currentBufferLineNumber = startBufferLineNumber;
307​
308 while (true) {
309 const currentLine = getLine(currentBufferLineNumber - 1);
310 if (!currentLine) break;
311​
312 const nextLine = getLine(currentBufferLineNumber);
313 const hasWrappedContinuation = nextLine?.isWrapped === true;
314 const text = currentLine.translateToString(!hasWrappedContinuation);
315​
316 segments.push({
317 bufferLineNumber: currentBufferLineNumber,
318 text,
319 startIndex: nextStartIndex,
320 endIndex: nextStartIndex + text.length,
321 });
322 nextStartIndex += text.length;
323​
324 if (!hasWrappedContinuation) break;
325 currentBufferLineNumber += 1;
326 }
327​
328 return {
329 text: segments.map((segment) => segment.text).join(""),
330 segments,
331 };
333​
334export function isTerminalLinkActivation(
335 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
336 platform = typeof navigator === "undefined" ? "" : navigator.platform,
337): boolean {
338 if (platform.length === 0) return false;
339 return isMacPlatform(platform)
340 ? event.metaKey && !event.ctrlKey
341 : event.ctrlKey && !event.metaKey;