Open History to see the last commit
1import {
2 T3_PROJECT_FILE_NAME,
3 type EnvironmentId,
4 type T3ProjectFileScript,
5} from "@t3tools/contracts";
6import { T3ProjectFileFromJson } from "@t3tools/shared/t3ProjectFile";
7import * as Exit from "effect/Exit";
8import * as Schema from "effect/Schema";
9import { useMemo } from "react";
10
11import { useProjectFileQuery } from "~/components/files/projectFilesQueryState";
12
13const decodeT3ProjectFile = Schema.decodeExit(T3ProjectFileFromJson);
14
15const NO_SCRIPTS: ReadonlyArray<T3ProjectFileScript> = [];
16
17export interface T3ProjectFileState {
18 /**
19 * - `valid`: t3.json exists and decoded.
20 * - `invalid`: t3.json exists but fails to decode (the server then ignores
21 * the whole file, including `iconPath` and every script).
22 * - `missing`: no readable t3.json at the workspace root.
23 * - `loading`: the file query has not settled yet.
24 */
25 status: "loading" | "missing" | "invalid" | "valid";
26 scripts: ReadonlyArray<T3ProjectFileScript>;
27}
28
29/**
30 * Decoded state of the project's checked-in `t3.json`, including whether the
31 * file exists but is broken — which the runtime otherwise swallows silently.
32 */
33export function useT3ProjectFileState(
34 environmentId: EnvironmentId,
35 cwd: string | null,
36): T3ProjectFileState {
37 const query = useProjectFileQuery(environmentId, cwd ?? "", T3_PROJECT_FILE_NAME, cwd !== null);
38 const contents = query.data && !query.data.truncated ? query.data.contents : null;
39 const isPending = query.isPending;
40 return useMemo(() => {
41 if (contents === null) {
42 return { status: isPending ? "loading" : "missing", scripts: NO_SCRIPTS } as const;
43 }
44 const decoded = decodeT3ProjectFile(contents);
45 if (Exit.isFailure(decoded)) {
46 return { status: "invalid", scripts: NO_SCRIPTS } as const;
47 }
48 return { status: "valid", scripts: decoded.value.scripts ?? NO_SCRIPTS } as const;
49 }, [contents, isPending]);
50}
51
52/**
53 * Scripts declared in the project's checked-in `t3.json`, offered in the
54 * scripts menu for import. Missing, truncated, or invalid files resolve to
55 * an empty list.
56 */
57export function useT3ProjectFileScripts(
58 environmentId: EnvironmentId,
59 cwd: string | null,
60): ReadonlyArray<T3ProjectFileScript> {
61 return useT3ProjectFileState(environmentId, cwd).scripts;
62}