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

terminal-links.ts

247 lines9.6 KB

1import { parseFileUrlHref, resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
2import { isMacPlatform } from "./lib/utils";
3​
4export type TerminalLinkKind = "url" | "path";
5​
6export interface TerminalLinkMatch {
7 kind: TerminalLinkKind;
8 text: string;
9 start: number;
10 end: number;
11 /**
12 * `text` cut after its `:line:col`. Only the filesystem can tell grep's `./a.js:1:function`
13 * from a name with colons in it, so this stands in when `text` as a whole is not a file.
14 */
15 fallback?: { text: string; end: number };
17​
18export interface TerminalBufferLineLike {
19 readonly isWrapped?: boolean;
20 translateToString(trimRight?: boolean): string;
22​
23export interface WrappedTerminalLinkLineSegment {
24 bufferLineNumber: number;
25 text: string;
26 startIndex: number;
27 endIndex: number;
29​
30export interface WrappedTerminalLinkLine {
31 text: string;
32 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
34​
35const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/giu;
36// The default PowerShell prompt delimits its unquoted path with `PS ` and `>`.
37const POWERSHELL_PROMPT_PATH_PATTERN = /^PS ((?:[A-Za-z]:[\\/]|\\\\|\/)[^>\r\n]*)>/u;
38// Bare paths start only at a segment boundary: hover detection runs this on
39// every frame, so separator-free output must not be rescanned at every suffix.
40// Parenthesized path segments need a following slash to distinguish compiler locations.
41// A bare `name.ext` needs `:line:col` or a TS location after it, so prose and `host:port` stay text.
42const FILE_PATH_PATTERN =
43 /(?:~[\\/]|\.{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\d+:))?/gu;
44const QUOTED_FILE_PATH_PATTERN =
45 /(["'`])(?<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;
46// The `:line` or `:line:col` that grep, ripgrep and Ruby backtraces follow with a colon and text.
47const POSITION_BEFORE_TEXT_PATTERN = /^.+?(?::\d+){1,2}(?=:)/u;
48const POSITIONS_ONLY_PATTERN = /^(?::\d+)+$/u;
49const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
50// Paths also drop a trailing colon: compilers end `file:line:col:` with one.
51const TRAILING_PATH_PUNCTUATION_PATTERN = /[.,;:!?]+$/;
52// A question mark is legal in filenames; only exclude query-bearing request targets.
53const REQUEST_ROUTE_PATTERN =
54 /(?:^|[\s"'`])(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|CONNECT|TRACE|proxying)\s+["'`]?(?:\/|[A-Za-z0-9_-]+\/)[^\s?]*\?\S*/g;
55// The tail of `redis://host/0` or `file:///a.mjs` is not a path. One-letter schemes stay drives,
56// a diff's `+` or `-` may lead, and the lookbehind keeps runs from being rescanned at every suffix.
57const SCHEME_URL_PATTERN = /(?<![A-Za-z\d+.-])[+-]?[A-Za-z][A-Za-z\d+.-]+:\/\/[^\s"'`<>]+/gu;
58// Nor is the tail of an SCP-style Git remote such as `git@github.com:acme/widgets.git`. Only a
59// path wholly inside the tail is dropped, so `src/contact@support.vue:12:3` keeps its link.
60const SCP_REMOTE_PATTERN = /(?<![\w.@-])[\w.-]+@[\w.-]+:[^\s"'`<>]+/gu;
61​
62function trimClosingDelimiters(value: string, kind: TerminalLinkKind): string {
63 const output = value.replace(
64 kind === "path" ? TRAILING_PATH_PUNCTUATION_PATTERN : TRAILING_PUNCTUATION_PATTERN,
65 "",
66 );
67 if (output.length === 0) return output;
68 let end = output.length;
69​
70 const trimUnbalanced = (open: string, close: string) => {
71 if (output[end - 1] !== close) return;
72 let excess = output.split(close).length - output.split(open).length;
73 while (excess > 0 && output[end - 1] === close) {
74 end -= 1;
75 excess -= 1;
76 }
77 };
78​
79 trimUnbalanced("(", ")");
80 trimUnbalanced("[", "]");
81 trimUnbalanced("{", "}");
82 return output.slice(0, end);
84​
85function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
86 return a.start < b.end && b.start < a.end;
88​
89function collectMatches(
90 line: string,
91 kind: TerminalLinkKind,
92 pattern: RegExp,
93 existing: TerminalLinkMatch[],
94): TerminalLinkMatch[] {
95 const matches: TerminalLinkMatch[] = [];
96 pattern.lastIndex = 0;
97​
98 for (const rawMatch of line.matchAll(pattern)) {
99 const quotedPath = rawMatch.groups?.path;
100 const raw =
101 quotedPath === undefined ? rawMatch[0] : quotedPath + (rawMatch.groups?.position ?? "");
102 const start = rawMatch.index + (quotedPath === undefined ? 0 : 1);
103 if (start < 0 || raw.length === 0) continue;
104​
105 const trimmed = quotedPath === undefined ? trimClosingDelimiters(raw, kind) : raw;
106 if (trimmed.length === 0) continue;
107 if (kind === "path" && isTerminalUrl(trimmed)) continue;
108​
109 const cut =
110 kind === "path" && quotedPath === undefined
111 ? POSITION_BEFORE_TEXT_PATTERN.exec(trimmed)?.[0]
112 : undefined;
113 // What follows `main.c:10` in `main.c:10:5` is its column, not text.
114 const fallback =
115 cut !== undefined && !POSITIONS_ONLY_PATTERN.test(trimmed.slice(cut.length))
116 ? cut
117 : undefined;
118 const candidate: TerminalLinkMatch = {
119 kind,
120 text:
121 kind === "path" && /^:\s+(?:error|warning) TS\d+:/u.test(line.slice(start + trimmed.length))
122 ? trimmed.replace(/\((\d+),(\d+)\)$/, ":$1:$2")
123 : trimmed,
124 start,
125 // A position outside quotes spans the closing quote in the terminal buffer.
126 end: start + trimmed.length + (rawMatch.groups?.position ? 1 : 0),
127 ...(fallback === undefined
128 ? {}
129 : { fallback: { text: fallback, end: start + fallback.length } }),
130 };
131​
132 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
133 if (collides) continue;
134​
135 matches.push(candidate);
136 }
137​
138 return matches;
140​
141export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
142 const promptPath = POWERSHELL_PROMPT_PATH_PATTERN.exec(line)?.[1];
143 const promptMatches: TerminalLinkMatch[] = promptPath
144 ? [{ kind: "path", text: promptPath, start: 3, end: 3 + promptPath.length }]
145 : [];
146 const nonPathRanges = Array.from(
147 [...line.matchAll(REQUEST_ROUTE_PATTERN), ...line.matchAll(SCHEME_URL_PATTERN)],
148 (match) => ({ start: match.index, end: match.index + match[0].length }),
149 );
150 const remoteTails = Array.from(line.matchAll(SCP_REMOTE_PATTERN), (match) => ({
151 start: match.index + match[0].indexOf(":") + 1,
152 end: match.index + match[0].length,
153 }));
154 const urlMatches = collectMatches(line, "url", URL_PATTERN, promptMatches);
155 const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, [
156 ...promptMatches,
157 ...urlMatches,
158 ]);
159 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, [
160 ...promptMatches,
161 ...urlMatches,
162 ...quotedMatches,
163 ]);
164 return [...promptMatches, ...urlMatches, ...quotedMatches, ...pathMatches]
165 .filter(
166 (match) =>
167 match.kind === "url" ||
168 (!nonPathRanges.some((range) => overlaps(match, range)) &&
169 !remoteTails.some((tail) => match.start >= tail.start && match.end <= tail.end)),
170 )
171 .toSorted((a, b) => a.start - b.start);
173​
174export function isTerminalUrl(value: string): boolean {
175 return /^https?:\/\//iu.test(value);
177​
178/**
179 * Explicit OSC 8 targets may be `file://` URIs; everything else is a path relative to `cwd`.
180 * `hostname` is the terminal's environment's, which producers such as GNU `ls` put in the URI.
181 * A URI's path is the exact filename, so only its `#L12C3` hash is a position.
182 */
183export function resolveTerminalLinkTarget(text: string, cwd: string, hostname?: string): string {
184 const fileUrl = /^file:\/\//iu.test(text) ? parseFileUrlHref(text, hostname) : null;
185 if (!fileUrl) return resolvePathLinkTarget(text, cwd);
186 // Keep URI identity until consumers decode the filename, separately from its position.
187 const uri = new URL(text);
188 if (!fileUrl.path.startsWith("\\")) uri.hostname = "";
189 return uri.href;
191​
192export function collectWrappedTerminalLinkLine(
193 bufferLineNumber: number,
194 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
195): WrappedTerminalLinkLine | null {
196 const anchorLine = getLine(bufferLineNumber - 1);
197 if (!anchorLine) return null;
198​
199 let startBufferLineNumber = bufferLineNumber;
200 let startLine = anchorLine;
201​
202 while (startBufferLineNumber > 1 && startLine.isWrapped) {
203 const previousLine = getLine(startBufferLineNumber - 2);
204 if (!previousLine) return null;
205 startBufferLineNumber -= 1;
206 startLine = previousLine;
207 }
208​
209 const segments: WrappedTerminalLinkLineSegment[] = [];
210 let nextStartIndex = 0;
211 let currentBufferLineNumber = startBufferLineNumber;
212​
213 while (true) {
214 const currentLine = getLine(currentBufferLineNumber - 1);
215 if (!currentLine) break;
216​
217 const nextLine = getLine(currentBufferLineNumber);
218 const hasWrappedContinuation = nextLine?.isWrapped === true;
219 const text = currentLine.translateToString(!hasWrappedContinuation);
220​
221 segments.push({
222 bufferLineNumber: currentBufferLineNumber,
223 text,
224 startIndex: nextStartIndex,
225 endIndex: nextStartIndex + text.length,
226 });
227 nextStartIndex += text.length;
228​
229 if (!hasWrappedContinuation) break;
230 currentBufferLineNumber += 1;
231 }
232​
233 return {
234 text: segments.map((segment) => segment.text).join(""),
235 segments,
236 };
238​
239export function isTerminalLinkActivation(
240 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
241 platform = typeof navigator === "undefined" ? "" : navigator.platform,
242): boolean {
243 if (platform.length === 0) return false;
244 return isMacPlatform(platform)
245 ? event.metaKey && !event.ctrlKey
246 : event.ctrlKey && !event.metaKey;