Open History to see the last commit
1import { EDITORS, type EditorId } from "@t3tools/contracts";
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
13const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/g;
14const FILE_PATH_PATTERN =
15 /(?:~\/|\.{1,2}\/|\/|[A-Za-z]:\\|\\\\)[^\s"'`<>]+|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+(?::\d+){0,2}/g;
16const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/;
17const LAST_EDITOR_KEY = "t3code:last-editor";
18
19function trimClosingDelimiters(value: string): string {
20 let output = value.replace(TRAILING_PUNCTUATION_PATTERN, "");
21 if (output.length === 0) return output;
22
23 const trimUnbalanced = (open: string, close: string) => {
24 while (output.endsWith(close)) {
25 const opens = output.split(open).length - 1;
26 const closes = output.split(close).length - 1;
27 if (opens >= closes) return;
28 output = output.slice(0, -1);
29 }
30 };
31
32 trimUnbalanced("(", ")");
33 trimUnbalanced("[", "]");
34 trimUnbalanced("{", "}");
35 return output;
36}
37
38function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean {
39 return a.start < b.end && b.start < a.end;
40}
41
42function collectMatches(
43 line: string,
44 kind: TerminalLinkKind,
45 pattern: RegExp,
46 existing: TerminalLinkMatch[],
47): TerminalLinkMatch[] {
48 const matches: TerminalLinkMatch[] = [];
49 pattern.lastIndex = 0;
50
51 for (const rawMatch of line.matchAll(pattern)) {
52 const raw = rawMatch[0];
53 const start = rawMatch.index ?? -1;
54 if (start < 0 || raw.length === 0) continue;
55
56 const trimmed = trimClosingDelimiters(raw);
57 if (trimmed.length === 0) continue;
58 if (kind === "path" && /^https?:\/\//i.test(trimmed)) continue;
59
60 const candidate: TerminalLinkMatch = {
61 kind,
62 text: trimmed,
63 start,
64 end: start + trimmed.length,
65 };
66
67 const collides = [...existing, ...matches].some((other) => overlaps(candidate, other));
68 if (collides) continue;
69
70 matches.push(candidate);
71 }
72
73 return matches;
74}
75
76function isWindowsAbsolutePath(value: string): boolean {
77 return /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
78}
79
80function isAbsolutePath(value: string): boolean {
81 return value.startsWith("/") || isWindowsAbsolutePath(value);
82}
83
84function isWindowsPathStyle(value: string): boolean {
85 return isWindowsAbsolutePath(value) || /[A-Za-z]:\\/.test(value);
86}
87
88function joinPath(base: string, next: string, separator: "/" | "\\"): string {
89 const cleanBase = base.replace(/[\\/]+$/, "");
90 if (separator === "\\") {
91 return `${cleanBase}\\${next.replaceAll("/", "\\")}`;
92 }
93 return `${cleanBase}/${next.replace(/^\/+/, "")}`;
94}
95
96function inferHomeFromCwd(cwd: string): string | undefined {
97 const posixUser = cwd.match(/^\/Users\/([^/]+)/);
98 if (posixUser?.[1]) {
99 return `/Users/${posixUser[1]}`;
100 }
101
102 const posixHome = cwd.match(/^\/home\/([^/]+)/);
103 if (posixHome?.[1]) {
104 return `/home/${posixHome[1]}`;
105 }
106
107 const windowsUser = cwd.match(/^([A-Za-z]:\\Users\\[^\\]+)/);
108 if (windowsUser?.[1]) {
109 return windowsUser[1];
110 }
111
112 return undefined;
113}
114
115function splitPathAndPosition(value: string): {
116 path: string;
117 line: string | undefined;
118 column: string | undefined;
119} {
120 let path = value;
121 let column: string | undefined;
122 let line: string | undefined;
123
124 const columnMatch = path.match(/:(\d+)$/);
125 if (!columnMatch?.[1]) {
126 return { path, line: undefined, column: undefined };
127 }
128
129 column = columnMatch[1];
130 path = path.slice(0, -columnMatch[0].length);
131
132 const lineMatch = path.match(/:(\d+)$/);
133 if (lineMatch?.[1]) {
134 line = lineMatch[1];
135 path = path.slice(0, -lineMatch[0].length);
136 } else {
137 line = column;
138 column = undefined;
139 }
140
141 return { path, line, column };
142}
143
144export function extractTerminalLinks(line: string): TerminalLinkMatch[] {
145 const urlMatches = collectMatches(line, "url", URL_PATTERN, []);
146 const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, urlMatches);
147 return [...urlMatches, ...pathMatches].toSorted((a, b) => a.start - b.start);
148}
149
150export function isTerminalLinkActivation(
151 event: Pick<MouseEvent, "metaKey" | "ctrlKey">,
152 platform = typeof navigator === "undefined" ? "" : navigator.platform,
153): boolean {
154 if (platform.length === 0) return false;
155 return isMacPlatform(platform)
156 ? event.metaKey && !event.ctrlKey
157 : event.ctrlKey && !event.metaKey;
158}
159
160export function resolvePathLinkTarget(rawPath: string, cwd: string): string {
161 const { path, line, column } = splitPathAndPosition(rawPath);
162
163 let resolvedPath = path;
164 if (path.startsWith("~/")) {
165 const home = inferHomeFromCwd(cwd);
166 if (home) {
167 const separator: "/" | "\\" = isWindowsPathStyle(home) ? "\\" : "/";
168 resolvedPath = joinPath(home, path.slice(2), separator);
169 }
170 } else if (!isAbsolutePath(path)) {
171 const separator: "/" | "\\" = isWindowsPathStyle(cwd) ? "\\" : "/";
172 resolvedPath = joinPath(cwd, path, separator);
173 }
174
175 if (!line) return resolvedPath;
176 return `${resolvedPath}:${line}${column ? `:${column}` : ""}`;
177}
178
179export function preferredTerminalEditor(): EditorId {
180 const fallback = EDITORS.find((editor) => editor.command)?.id ?? EDITORS[0]?.id ?? "cursor";
181
182 if (typeof window === "undefined") {
183 return fallback;
184 }
185
186 const storedEditor = window.localStorage.getItem(LAST_EDITOR_KEY);
187 if (!storedEditor) {
188 return fallback;
189 }
190
191 const configured = EDITORS.find((editor) => editor.id === storedEditor);
192 if (!configured?.command) {
193 return fallback;
194 }
195
196 return configured.id;
197}