import { formatFilePathPosition, parseFileUrlHref, resolvePathLinkTarget, splitFilePathPosition, } from "@t3tools/shared/fileLinks"; import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks"; import { stripSlashPrefixedWindowsDrive } from "@t3tools/shared/path"; import { isMacPlatform } from "./lib/utils"; export type TerminalLinkKind = "url" | "path"; export interface TerminalLinkMatch { kind: TerminalLinkKind; text: string; start: number; end: number; } export interface TerminalBufferLineLike { readonly isWrapped?: boolean; translateToString(trimRight?: boolean): string; } export interface WrappedTerminalLinkLineSegment { bufferLineNumber: number; text: string; startIndex: number; endIndex: number; } export interface WrappedTerminalLinkLine { text: string; segments: ReadonlyArray; } const URL_PATTERN = /https?:\/\/[^\s"'`<>]+/giu; // The default PowerShell prompt delimits its unquoted path with `PS ` and `>`. const POWERSHELL_PROMPT_PATH_PATTERN = /^PS ((?:[A-Za-z]:[\\/]|\\\\|\/)[^>\r\n]*)>/u; // Bare paths start only at a segment boundary: hover detection runs this on // every frame, so separator-free output must not be rescanned at every suffix. // For the same reason `]` needs its `[`: trimming a long run of `]` is quadratic. // Parentheses count only before a slash, so `src/foo.ts(3,10)` stays a compiler location. const FILE_PATH_PATTERN = /(?:~[\\/]|\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\\\)[^\s"'`<>]+|(?(?:~[\\/]|\.{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(?(?::\d+){0,2})/gu; const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/; // Paths also drop a trailing colon: compilers end `file:line:col:` with one. const TRAILING_PATH_PUNCTUATION_PATTERN = /[.,;:!?]+$/; // A question mark is legal in filenames; only exclude query-bearing request targets. const REQUEST_ROUTE_PATTERN = /(?:^|[\s"'`])(?:GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS|CONNECT|TRACE|proxying)\s+["'`]?(?:\/|[A-Za-z0-9_-]+\/)[^\s?]*\?\S*/g; // The tail of `redis://host/0` or `file:///a.mjs` is not a path. One-letter schemes stay drives, // a diff's `+` or `-` may lead, and the lookbehind keeps runs from being rescanned at every suffix. const SCHEME_URL_PATTERN = /(?]+/gu; // Nor is the tail of an SCP-style Git remote such as `git@github.com:acme/widgets.git`. Only a // path wholly inside the tail is dropped, so `src/contact@support.vue:12:3` keeps its link. const SCP_REMOTE_PATTERN = /(?]+/gu; function trimClosingDelimiters(value: string, kind: TerminalLinkKind): string { let output = value.replace( kind === "path" ? TRAILING_PATH_PUNCTUATION_PATTERN : TRAILING_PUNCTUATION_PATTERN, "", ); if (output.length === 0) return output; const trimUnbalanced = (open: string, close: string) => { while (output.endsWith(close)) { const opens = output.split(open).length - 1; const closes = output.split(close).length - 1; if (opens >= closes) return; output = output.slice(0, -1); } }; trimUnbalanced("(", ")"); trimUnbalanced("[", "]"); trimUnbalanced("{", "}"); return output; } function overlaps(a: { start: number; end: number }, b: { start: number; end: number }): boolean { return a.start < b.end && b.start < a.end; } function collectMatches( line: string, kind: TerminalLinkKind, pattern: RegExp, existing: TerminalLinkMatch[], ): TerminalLinkMatch[] { const matches: TerminalLinkMatch[] = []; pattern.lastIndex = 0; for (const rawMatch of line.matchAll(pattern)) { const quotedPath = rawMatch.groups?.path; const raw = quotedPath === undefined ? rawMatch[0] : quotedPath + (rawMatch.groups?.position ?? ""); const start = rawMatch.index + (quotedPath === undefined ? 0 : 1); if (start < 0 || raw.length === 0) continue; const trimmed = quotedPath === undefined ? trimClosingDelimiters(raw, kind) : raw; if (trimmed.length === 0) continue; if (kind === "path" && isTerminalUrl(trimmed)) continue; const candidate: TerminalLinkMatch = { kind, text: trimmed, start, // A position outside quotes spans the closing quote in the terminal buffer. end: start + trimmed.length + (rawMatch.groups?.position ? 1 : 0), }; const collides = [...existing, ...matches].some((other) => overlaps(candidate, other)); if (collides) continue; matches.push(candidate); } return matches; } export function extractTerminalLinks(line: string): TerminalLinkMatch[] { const promptPath = POWERSHELL_PROMPT_PATH_PATTERN.exec(line)?.[1]; const promptMatches: TerminalLinkMatch[] = promptPath ? [{ kind: "path", text: promptPath, start: 3, end: 3 + promptPath.length }] : []; const nonPathRanges = Array.from( [...line.matchAll(REQUEST_ROUTE_PATTERN), ...line.matchAll(SCHEME_URL_PATTERN)], (match) => ({ start: match.index, end: match.index + match[0].length }), ); const remoteTails = Array.from(line.matchAll(SCP_REMOTE_PATTERN), (match) => ({ start: match.index + match[0].indexOf(":") + 1, end: match.index + match[0].length, })); const urlMatches = collectMatches(line, "url", URL_PATTERN, promptMatches); const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, [ ...promptMatches, ...urlMatches, ]); const pathMatches = collectMatches(line, "path", FILE_PATH_PATTERN, [ ...promptMatches, ...urlMatches, ...quotedMatches, ]); return [...promptMatches, ...urlMatches, ...quotedMatches, ...pathMatches] .filter( (match) => match.kind === "url" || (!nonPathRanges.some((range) => overlaps(match, range)) && !remoteTails.some((tail) => match.start >= tail.start && match.end <= tail.end)), ) .toSorted((a, b) => a.start - b.start); } export function isTerminalUrl(value: string): boolean { return /^https?:\/\//iu.test(value); } /** Explicit OSC 8 targets may be `file://` URIs; everything else is a path relative to `cwd`. */ export function resolveTerminalLinkTarget(text: string, cwd: string): string { const fileUrl = /^file:\/\//iu.test(text) ? parseFileUrlHref(text) : null; if (!fileUrl) return resolvePathLinkTarget(text, cwd); return formatFilePathPosition( splitFilePathPosition( stripSlashPrefixedWindowsDrive(safeDecodeURIComponent(fileUrl.path)), fileUrl.hash, ), ); } export function collectWrappedTerminalLinkLine( bufferLineNumber: number, getLine: (bufferLineIndex: number) => TerminalBufferLineLike | null | undefined, ): WrappedTerminalLinkLine | null { const anchorLine = getLine(bufferLineNumber - 1); if (!anchorLine) return null; let startBufferLineNumber = bufferLineNumber; let startLine = anchorLine; while (startBufferLineNumber > 1 && startLine.isWrapped) { const previousLine = getLine(startBufferLineNumber - 2); if (!previousLine) return null; startBufferLineNumber -= 1; startLine = previousLine; } const segments: WrappedTerminalLinkLineSegment[] = []; let nextStartIndex = 0; let currentBufferLineNumber = startBufferLineNumber; while (true) { const currentLine = getLine(currentBufferLineNumber - 1); if (!currentLine) break; const nextLine = getLine(currentBufferLineNumber); const hasWrappedContinuation = nextLine?.isWrapped === true; const text = currentLine.translateToString(!hasWrappedContinuation); segments.push({ bufferLineNumber: currentBufferLineNumber, text, startIndex: nextStartIndex, endIndex: nextStartIndex + text.length, }); nextStartIndex += text.length; if (!hasWrappedContinuation) break; currentBufferLineNumber += 1; } return { text: segments.map((segment) => segment.text).join(""), segments, }; } export function isTerminalLinkActivation( event: Pick, platform = typeof navigator === "undefined" ? "" : navigator.platform, ): boolean { if (platform.length === 0) return false; return isMacPlatform(platform) ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey; }