Open History to see the last commit
1import {
2 AuthFilesystemReadScope,
3 FILESYSTEM_METADATA_PATH_MAX_LENGTH,
4 type EnvironmentId,
5 type ScopedThreadRef,
6} from "@t3tools/contracts";
7import {
8 joinPath,
9 parseFileUrlHref,
10 resolvePathLinkTarget,
11 splitFilePathPosition,
12} from "@t3tools/shared/fileLinks";
13import {
14 isAbsolutePath,
15 isNetworkPath,
16 isWindowsAbsolutePath,
17 normalizeFileMetadataPath,
18} from "@t3tools/shared/path";
19import { safeDecodeURIComponent } from "@t3tools/shared/markdownLinks";
20import { useContext } from "react";
21
22import { useEnvironmentScope } from "../state/session";
23import { projectEnvironment } from "../state/projects";
24import { useEnvironmentQuery } from "../state/query";
25import { FileMetadataThreadContext } from "./FileMetadataThreadProvider";
26
27export function getFileMetadataQueryAtom(
28 environmentId: EnvironmentId,
29 path: string,
30 cwd?: string,
31 threadRef?: ScopedThreadRef | null,
32 literal = false,
33) {
34 const uri = /^file:\/\//iu.test(path) ? parseFileUrlHref(path) : null;
35 const hostPath = literal ? path : splitFilePathPosition(path).path;
36 const targetPath = normalizeFileMetadataPath(
37 uri
38 ? safeDecodeURIComponent(uri.path)
39 : hostPath.startsWith("~/") || !cwd
40 ? hostPath
41 : // A POSIX name may end in `:<digits>`; Windows names cannot contain `:`.
42 literal && !isWindowsAbsolutePath(cwd)
43 ? isAbsolutePath(hostPath)
44 ? hostPath
45 : joinPath(cwd, hostPath.replace(/^(?:\.\/)+/, ""), "/")
46 : resolvePathLinkTarget(hostPath, cwd),
47 );
48 const absolute = isAbsolutePath(targetPath) || targetPath.startsWith("~/");
49 return (
50 // Servers stat what they are asked about, and a network path leaks the
51 // Windows user's NTLM credentials to its host before any chip is clicked.
52 absolute &&
53 !isNetworkPath(targetPath) &&
54 targetPath.length <= FILESYSTEM_METADATA_PATH_MAX_LENGTH
55 ? projectEnvironment.fileMetadata({
56 environmentId,
57 input: {
58 path: targetPath,
59 ...(threadRef?.environmentId === environmentId ? { threadId: threadRef.threadId } : {}),
60 },
61 })
62 : null
63 );
64}
65
66export function useFileMetadata(
67 environmentId: EnvironmentId | null | undefined,
68 path: string,
69 cwd?: string,
70) {
71 const canRead = useEnvironmentScope(environmentId ?? null, AuthFilesystemReadScope);
72 const threadRef = useContext(FileMetadataThreadContext);
73 return useEnvironmentQuery(
74 environmentId && canRead
75 ? getFileMetadataQueryAtom(environmentId, path, cwd, threadRef, true)
76 : null,
77 ).data;
78}