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

path.ts

175 lines6.5 KB

1export function isWindowsDrivePath(value: string): boolean {
2 return /^[a-zA-Z]:([/\\]|$)/.test(value);
3}
4​
5export function isUncPath(value: string): boolean {
6 return value.startsWith("\\\\");
7}
8​
9/**
10 * Windows treats `/` and `\` alike, so any two leading separators name a UNC
11 * or device path. Touching one makes Windows sign in to that host with the
12 * user's NTLM credentials, so agent-authored paths must not reach one.
13 */
14export function isNetworkPath(value: string): boolean {
15 return /^[\\/]{2}/.test(value);
17​
18export function isWindowsAbsolutePath(value: string): boolean {
19 return isUncPath(value) || isWindowsDrivePath(value);
21​
22export function isExplicitRelativePath(value: string): boolean {
23 return (
24 value === "." ||
25 value === ".." ||
26 value.startsWith("./") ||
27 value.startsWith("../") ||
28 value.startsWith(".\\") ||
29 value.startsWith("..\\")
30 );
32​
33function isRootPath(value: string): boolean {
34 // Bare C: means the current directory on C, not its root; require the drive separator.
35 return value === "/" || value === "\\" || /^[a-zA-Z]:[/\\]$/.test(value);
37​
38function trimTrailingPathSeparators(value: string): string {
39 if (value.length === 0 || isRootPath(value)) {
40 return value;
41 }
42 const trimmed = value.startsWith("/")
43 ? value.replace(/\/+$/g, "")
44 : value.replace(/[\\/]+$/g, "");
45 if (trimmed.length === 0) {
46 return value;
47 }
48 return /^[a-zA-Z]:$/.test(trimmed) ? `${trimmed}\\` : trimmed;
50​
51export function normalizeProjectPathForDispatch(value: string): string {
52 return trimTrailingPathSeparators(value.trim());
54​
55export function normalizeProjectPathForComparison(value: string): string {
56 const normalized = normalizeProjectPathForDispatch(value);
57 if (isWindowsDrivePath(normalized) || isUncPath(normalized)) {
58 return normalized.replaceAll("/", "\\").toLowerCase();
59 }
60 return normalized;
62​
63// Windows refuses these as file names, with or without an extension.
64const WINDOWS_RESERVED_NAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/;
65​
66/** Folds accented Latin letters to ASCII ("tìm" -> "tim"); other scripts pass through. */
67export function foldLatinDiacritics(text: string): string {
68 return text
69 .normalize("NFKD")
70 .replace(/[\u0300-\u036f]/g, "")
71 .replace(/đ/g, "d") // d-with-stroke has no Unicode decomposition
72 .replace(/Đ/g, "D");
74​
75export function newProjectFolderName(name: string): string {
76 const slug = foldLatinDiacritics(name)
77 .toLowerCase()
78 .replace(/[^a-z0-9]+/g, "-")
79 .replace(/^-+/, "")
80 .slice(0, 64)
81 .replace(/-+$/, "");
82 if (slug.length === 0) return "project";
83 return WINDOWS_RESERVED_NAME.test(slug) ? `${slug}-project` : slug;
85​
86const SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN = /^\/[A-Za-z]:[\\/]/;
87​
88/** Browser URL parsers write `C:/foo` as `/C:/foo` for file URLs. */
89export function stripSlashPrefixedWindowsDrive(path: string): string {
90 return SLASH_PREFIXED_WINDOWS_DRIVE_PATTERN.test(path) ? path.slice(1) : path;
92​
93export function fileBasename(path: string): string {
94 const trimmed = path.replace(/[/\\]+$/, "");
95 if (trimmed.length === 0) return path;
96 const separatorIndex = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
97 return separatorIndex >= 0 ? trimmed.slice(separatorIndex + 1) : trimmed;
99​
100export function workspaceRelativeFilePath(
101 path: string,
102 workspaceRoot: string | null | undefined,
103): string | null {
104 if (!workspaceRoot) return null;
105 const caseInsensitive =
106 isWindowsAbsolutePath(stripSlashPrefixedWindowsDrive(workspaceRoot)) ||
107 (isNetworkPath(workspaceRoot) && isUncPath(path));
108 const normalizedPath = caseInsensitive
109 ? stripSlashPrefixedWindowsDrive(path.replaceAll("\\", "/"))
110 : path;
111 const normalizedRoot = (
112 caseInsensitive
113 ? stripSlashPrefixedWindowsDrive(workspaceRoot.replaceAll("\\", "/"))
114 : workspaceRoot
115 ).replace(/\/+$/, "");
116 const pathForCompare = caseInsensitive ? normalizedPath.toLowerCase() : normalizedPath;
117 const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot;
118 if (pathForCompare.replace(/\/+$/, "") === rootForCompare) return ".";
119 if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null;
120 const relativePath = normalizedPath.slice(normalizedRoot.length + 1);
121 // `/repo/../x` starts with the root but escapes it; the server rejects that as a workspace path.
122 let depth = 0;
123 for (const segment of relativePath.split("/")) {
124 if (segment === "..") depth -= 1;
125 else if (segment.length > 0 && segment !== ".") depth += 1;
126 if (depth < 0) return null;
127 }
128 return relativePath;
130​
131export function isAbsolutePath(value: string): boolean {
132 return value.startsWith("/") || isWindowsAbsolutePath(value);
134​
135/** Home-relative host paths are expanded by the destination server. */
136export function isHostPath(value: string): boolean {
137 return isAbsolutePath(value) || value.startsWith("~/");
139​
140// Finder and Explorer copy a path ready for a shell: `'/a b'`, `/a\'s\ b`, or `"C:\a b"`.
141const QUOTED_PATH_AT_END = /(?:'((?:[^']|'\\'')+)'|"([^"]+)")\s*$/;
142const SHELL_ESCAPE = /\\([\s'"\\()[\]{}<>|&;$`!*?#~^=])/g;
143​
144/**
145 * What a folder box holds after a change. A full path pasted into it replaces the box, even after
146 * the text already there, because `~/'/a b'` would create that nested folder.
147 */
148export function resolvePastedPath(previous: string, next: string): string {
149 const isTyping = next.startsWith(previous)
150 ? next.length === previous.length + 1
151 : previous.startsWith(next);
152 if (isTyping) return next;
153​
154 const match = QUOTED_PATH_AT_END.exec(next);
155 // Text before the quote that wasn't in the box is a search, not a folder to paste after.
156 if (match && previous.startsWith(next.slice(0, match.index).trimEnd())) {
157 const quoted = match[1]?.replaceAll("'\\''", "'") ?? match[2] ?? "";
158 if (isHostPath(quoted)) return quoted;
159 }
160​
161 // Without a trailing separator, `/a` then `/a/b` is a longer path, not one pasted after a folder.
162 const afterFolder = /[/\\]$/.test(previous) && next.startsWith(previous);
163 const path = afterFolder ? next.slice(previous.length) : next;
164 if (!isHostPath(path)) return next;
165 // `\` separates folders in Windows paths, so it only escapes in `/` and `~/` paths.
166 return isWindowsAbsolutePath(path) ? path : path.replace(SHELL_ESCAPE, "$1");
168​
169export function resolveWorkspaceFilePath(path: string, workspaceRoot: string): string {
170 if (isAbsolutePath(path) || path.startsWith("~/") || path.startsWith("~\\")) return path;
171 const base = workspaceRoot.replace(/[/\\]+$/, "");
172 return isWindowsAbsolutePath(workspaceRoot)
173 ? `${base}\\${path.replaceAll("/", "\\")}`
174 : `${base}/${path}`;