1import { AuthFilesystemReadScope, type EnvironmentId } from "@t3tools/contracts";
2import { resolvePathLinkTarget, splitFilePathPosition } from "@t3tools/shared/fileLinks";
3import { normalizeProjectPathForComparison, isAbsolutePath } from "@t3tools/shared/path";
4import { useContext } from "react";
5
6import { useEnvironmentScope } from "../state/session";
7import { projectEnvironment } from "../state/projects";
8import { useEnvironmentQuery } from "../state/query";
9import { FileMetadataThreadContext } from "./FileMetadataThreadProvider";
10
11export function useFileMetadata(
12 environmentId: EnvironmentId | null | undefined,
13 path: string,
14 cwd?: string,
15) {
16 const canRead = useEnvironmentScope(environmentId ?? null, AuthFilesystemReadScope);
17 const threadRef = useContext(FileMetadataThreadContext);
18 const hostPath = splitFilePathPosition(path).path;
19 const targetPath = normalizeProjectPathForComparison(
20 hostPath.startsWith("~/") || !cwd ? hostPath : resolvePathLinkTarget(hostPath, cwd),
21 );
22 const absolute = isAbsolutePath(targetPath) || targetPath.startsWith("~/");
23 return useEnvironmentQuery(
24 environmentId && canRead && absolute && targetPath.length <= 512
25 ? projectEnvironment.fileMetadata({
26 environmentId,
27 input: {
28 path: targetPath,
29 ...(threadRef?.environmentId === environmentId ? { threadId: threadRef.threadId } : {}),
30 },
31 })
32 : null,
33 ).data;
34}