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

terminal-links.ts

193 lines6.5 KB

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;
11​
12export interface TerminalBufferLineLike {
13 readonly isWrapped?: boolean;
14 translateToString(trimRight?: boolean): string;
16​
17export interface WrappedTerminalLinkLineSegment {
18 bufferLineNumber: number;
19 text: string;
20 startIndex: number;
21 endIndex: number;
23​
24export interface WrappedTerminalLinkLine {
25 text: string;
26 segments: ReadonlyArray<WrappedTerminalLinkLineSegment>;
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.
34const FILE_PATH_PATTERN =
35 /(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|(?<![\p{L}\p{M}\p{N}._-])[\p{L}\p{M}\p{N}._-]+(?:[\\/][\p{L}\p{M}\p{N}._-]+)+(?::\d+){0,2}/gu;
36const QUOTED_FILE_PATH_PATTERN =
37 /(["'`])(?<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;
38const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
39// Paths also drop a trailing colon: compilers end `file:line:col:` with one.
40const TRAILING_PATH_PUNCTUATION_PATTERN = /[.,;:!?]+$/;
41// A question mark is legal in filenames; only exclude query-bearing request targets.
42const REQUEST_ROUTE_PATTERN =
43 /(?:^|[\s"'`])(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|CONNECT|TRACE|proxying)\s+["'`]?(?:\/|[A-Za-z0-9_-]+\/)[^\s?]*\?\S*/g;
44​
45function trimClosingDelimiters(value: string, kind: TerminalLinkKind): string {
46 let output = value.replace(
47 kind === "path" ? TRAILING_PATH_PUNCTUATION_PATTERN : TRAILING_PUNCTUATION_PATTERN,
48 "",
49 );
50 if (output.length === 0) return output;
51​
52 const trimUnbalanced = (open: string, close: string) => {
53 while (output.endsWith(close)) {
54 const opens = output.split(open).length - 1;
55 const closes = output.split(close).length - 1;
56 if (opens >= closes) return;
57 output = output.slice(0, -1);
58 }
59 };
60​
61 trimUnbalanced("(", ")");
62 trimUnbalanced("[", "]");
63 trimUnbalanced("{", "}");
64 return output;
66​
67function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
68 return a.start < b.end && b.start < a.end;
70​
71function collectMatches(
72 line: string,
73 kind: TerminalLinkKind,
74 pattern: RegExp,
75 existing: TerminalLinkMatch[],
76): TerminalLinkMatch[] {
77 const matches: TerminalLinkMatch[] = [];
78 pattern.lastIndex = 0;
79​
80 for (const rawMatch of line.matchAll(pattern)) {
81 const quotedPath = rawMatch.groups?.path;
82 const raw =
83 quotedPath === undefined ? rawMatch[0] : quotedPath + (rawMatch.groups?.position ?? "");
84 const start = rawMatch.index + (quotedPath === undefined ? 0 : 1);
85 if (start < 0 || raw.length === 0) continue;
86​
87 const trimmed = quotedPath === undefined ? trimClosingDelimiters(raw, kind) : raw;
88 if (trimmed.length === 0) continue;
89 if (kind === "path" && isTerminalUrl(trimmed)) continue;
90​
91 const candidate: TerminalLinkMatch = {
92 kind,
93 text: trimmed,
94 start,
95 // A position outside quotes spans the closing quote in the terminal buffer.
96 end: start + trimmed.length + (rawMatch.groups?.position ? 1 : 0),
97 };
98​
99 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
100 if (collides) continue;
101​
102 matches.push(candidate);
103 }
104​
105 return matches;
107​
108export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
109 const promptPath = POWERSHELL_PROMPT_PATH_PATTERN.exec(line)?.[1];
110 const promptMatches: TerminalLinkMatch[] = promptPath
111 ? [{ kind: "path", text: promptPath, start: 3, end: 3 + promptPath.length }]
112 : [];
113 const requestRoutes = Array.from(line.matchAll(REQUEST_ROUTE_PATTERN), (match) => ({
114 start: match.index,
115 end: match.index + match[0].length,
116 }));
117 const urlMatches = collectMatches(line, "url", URL_PATTERN, promptMatches);
118 const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, [
119 ...promptMatches,
120 ...urlMatches,
121 ]);
122 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, [
123 ...promptMatches,
124 ...urlMatches,
125 ...quotedMatches,
126 ]);
127 return [...promptMatches, ...urlMatches, ...quotedMatches, ...pathMatches]
128 .filter(
129 (match) => match.kind === "url" || !requestRoutes.some((route) => overlaps(match, route)),
130 )
131 .toSorted((a, b) => a.start - b.start);
133​
134export function isTerminalUrl(value: string): boolean {
135 return /^https?:\/\//iu.test(value);
137​
138export function collectWrappedTerminalLinkLine(
139 bufferLineNumber: number,
140 getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined,
141): WrappedTerminalLinkLine | null {
142 const anchorLine = getLine(bufferLineNumber - 1);
143 if (!anchorLine) return null;
144​
145 let startBufferLineNumber = bufferLineNumber;
146 let startLine = anchorLine;
147​
148 while (startBufferLineNumber > 1 && startLine.isWrapped) {
149 const previousLine = getLine(startBufferLineNumber - 2);
150 if (!previousLine) return null;
151 startBufferLineNumber -= 1;
152 startLine = previousLine;
153 }
154​
155 const segments: WrappedTerminalLinkLineSegment[] = [];
156 let nextStartIndex = 0;
157 let currentBufferLineNumber = startBufferLineNumber;
158​
159 while (true) {
160 const currentLine = getLine(currentBufferLineNumber - 1);
161 if (!currentLine) break;
162​
163 const nextLine = getLine(currentBufferLineNumber);
164 const hasWrappedContinuation = nextLine?.isWrapped === true;
165 const text = currentLine.translateToString(!hasWrappedContinuation);
166​
167 segments.push({
168 bufferLineNumber: currentBufferLineNumber,
169 text,
170 startIndex: nextStartIndex,
171 endIndex: nextStartIndex + text.length,
172 });
173 nextStartIndex += text.length;
174​
175 if (!hasWrappedContinuation) break;
176 currentBufferLineNumber += 1;
177 }
178​
179 return {
180 text: segments.map((segment) => segment.text).join(""),
181 segments,
182 };
184​
185export function isTerminalLinkActivation(
186 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
187 platform = typeof navigator === "undefined" ? "" : navigator.platform,
188): boolean {
189 if (platform.length === 0) return false;
190 return isMacPlatform(platform)
191 ? event.metaKey && !event.ctrlKey
192 : event.ctrlKey && !event.metaKey;