Open History to see the last commit
1import { isMacPlatform } from "./lib/utils";
2
3export type TerminalLinkKind = "url" | "path";
4
5export interface TerminalLinkMatch {
6 kind: TerminalLinkKind;
7 text: string;
8 start: number;
9 end: number;
10}
11
12export interface TerminalBufferLineLike {
13 readonly isWrapped?: boolean;
14 translateToString(trimRight?: boolean): string;
15}
16
17export interface WrappedTerminalLinkLineSegment {
18 bufferLineNumber: number;
19 text: string;
20 startIndex: number;
21 endIndex: number;
22}
23
24export interface WrappedTerminalLinkLine {
25 text: string;
26 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
27}
28
29const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/giu;
30// The default PowerShell prompt delimits its unquoted path with `PS ` and `>`.
31const POWERSHELL_PROMPT_PATH_PATTERN = /^PS ((?:[A-Za-z]:[\\/]|\\\\|\/)[^>\r\n]*)>/u;
32// Bare paths start only at a segment boundary: hover detection runs this on
33// every frame, so separator-free output must not be rescanned at every suffix.
34// For the same reason `]` needs its `[`: trimming a long run of `]` is quadratic.
35// Parentheses count only before a slash, so `src/foo.ts(3,10)` stays a compiler location.
36const FILE_PATH_PATTERN =
37 /(?:~[\\/]|\.{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}._-]+\)(?=[\\/]))+)+(?::\d+){0,2}/gu;
38const QUOTED_FILE_PATH_PATTERN =
39 /(["'`])(?<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;
40const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
41// Paths also drop a trailing colon: compilers end `file:line:col:` with one.
42const TRAILING_PATH_PUNCTUATION_PATTERN = /[.,;:!?]+$/;
43// A question mark is legal in filenames; only exclude query-bearing request targets.
44const REQUEST_ROUTE_PATTERN =
45 /(?:^|[\s"'`])(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|CONNECT|TRACE|proxying)\s+["'`]?(?:\/|[A-Za-z0-9_-]+\/)[^\s?]*\?\S*/g;
46// The tail of `redis://host/0` or `file:///a.mjs` is not a path. One-letter schemes stay drives,
47// a diff's `+` or `-` may lead, and the lookbehind keeps runs from being rescanned at every suffix.
48const SCHEME_URL_PATTERN = /(?<![A-Za-z\d+.-])[+-]?[A-Za-z][A-Za-z\d+.-]+:\/\/[^\s"'`<>]+/gu;
49
50function trimClosingDelimiters(value: string, kind: TerminalLinkKind): string {
51 let output = value.replace(
52 kind === "path" ? TRAILING_PATH_PUNCTUATION_PATTERN : TRAILING_PUNCTUATION_PATTERN,
53 "",
54 );
55 if (output.length === 0) return output;
56
57 const trimUnbalanced = (open: string, close: string) => {
58 while (output.endsWith(close)) {
59 const opens = output.split(open).length - 1;
60 const closes = output.split(close).length - 1;
61 if (opens >= closes) return;
62 output = output.slice(0, -1);
63 }
64 };
65
66 trimUnbalanced("(", ")");
67 trimUnbalanced("[", "]");
68 trimUnbalanced("{", "}");
69 return output;
70}
71
72function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
73 return a.start < b.end && b.start < a.end;
74}
75
76function collectMatches(
77 line: string,
78 kind: TerminalLinkKind,
79 pattern: RegExp,
80 existing: TerminalLinkMatch[],
81): TerminalLinkMatch[] {
82 const matches: TerminalLinkMatch[] = [];
83 pattern.lastIndex = 0;
84
85 for (const rawMatch of line.matchAll(pattern)) {
86 const quotedPath = rawMatch.groups?.path;
87 const raw =
88 quotedPath === undefined ? rawMatch[0] : quotedPath + (rawMatch.groups?.position ?? "");
89 const start = rawMatch.index + (quotedPath === undefined ? 0 : 1);
90 if (start < 0 || raw.length === 0) continue;
91
92 const trimmed = quotedPath === undefined ? trimClosingDelimiters(raw, kind) : raw;
93 if (trimmed.length === 0) continue;
94 if (kind === "path" && isTerminalUrl(trimmed)) continue;
95
96 const candidate: TerminalLinkMatch = {
97 kind,
98 text: trimmed,
99 start,
100 // A position outside quotes spans the closing quote in the terminal buffer.
101 end: start + trimmed.length + (rawMatch.groups?.position ? 1 : 0),
102 };
103
104 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
105 if (collides) continue;
106
107 matches.push(candidate);
108 }
109
110 return matches;
111}
112
113export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
114 const promptPath = POWERSHELL_PROMPT_PATH_PATTERN.exec(line)?.[1];
115 const promptMatches: TerminalLinkMatch[] = promptPath
116 ? [{ kind: "path", text: promptPath, start: 3, end: 3 + promptPath.length }]
117 : [];
118 const nonPathRanges = Array.from(
119 [...line.matchAll(REQUEST_ROUTE_PATTERN), ...line.matchAll(SCHEME_URL_PATTERN)],
120 (match) => ({ start: match.index, end: match.index + match[0].length }),
121 );
122 const urlMatches = collectMatches(line, "url", URL_PATTERN, promptMatches);
123 const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, [
124 ...promptMatches,
125 ...urlMatches,
126 ]);
127 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, [
128 ...promptMatches,
129 ...urlMatches,
130 ...quotedMatches,
131 ]);
132 return [...promptMatches, ...urlMatches, ...quotedMatches, ...pathMatches]
133 .filter(
134 (match) => match.kind === "url" || !nonPathRanges.some((range) => overlaps(match, range)),
135 )
136 .toSorted((a, b) => a.start - b.start);
137}
138
139export function isTerminalUrl(value: string): boolean {
140 return /^https?:\/\//iu.test(value);
141}
142
143export function collectWrappedTerminalLinkLine(
144 bufferLineNumber: number,
145 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
146): WrappedTerminalLinkLine | null {
147 const anchorLine = getLine(bufferLineNumber - 1);
148 if (!anchorLine) return null;
149
150 let startBufferLineNumber = bufferLineNumber;
151 let startLine = anchorLine;
152
153 while (startBufferLineNumber > 1 && startLine.isWrapped) {
154 const previousLine = getLine(startBufferLineNumber - 2);
155 if (!previousLine) return null;
156 startBufferLineNumber -= 1;
157 startLine = previousLine;
158 }
159
160 const segments: WrappedTerminalLinkLineSegment[] = [];
161 let nextStartIndex = 0;
162 let currentBufferLineNumber = startBufferLineNumber;
163
164 while (true) {
165 const currentLine = getLine(currentBufferLineNumber - 1);
166 if (!currentLine) break;
167
168 const nextLine = getLine(currentBufferLineNumber);
169 const hasWrappedContinuation = nextLine?.isWrapped === true;
170 const text = currentLine.translateToString(!hasWrappedContinuation);
171
172 segments.push({
173 bufferLineNumber: currentBufferLineNumber,
174 text,
175 startIndex: nextStartIndex,
176 endIndex: nextStartIndex + text.length,
177 });
178 nextStartIndex += text.length;
179
180 if (!hasWrappedContinuation) break;
181 currentBufferLineNumber += 1;
182 }
183
184 return {
185 text: segments.map((segment) => segment.text).join(""),
186 segments,
187 };
188}
189
190export function isTerminalLinkActivation(
191 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
192 platform = typeof navigator === "undefined" ? "" : navigator.platform,
193): boolean {
194 if (platform.length === 0) return false;
195 return isMacPlatform(platform)
196 ? event.metaKey && !event.ctrlKey
197 : event.ctrlKey && !event.metaKey;
198}