Open History to see the last commit
1import {
2 executeAtomQuery,
3 runAtomCommand,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import { scopedProjectKey } from "@t3tools/client-runtime/environment";
7import type {
8 EnvironmentId,
9 ProjectCloneSnapshot,
10 ProjectId,
11 ScopedProjectRef,
12} from "@t3tools/contracts";
13import { create } from "zustand";
14
15import { appAtomRegistry } from "../rpc/atomRegistry";
16import { environmentProjectClonesAtom, silenceProjectCloneToasts } from "../state/projectClones";
17import { projectEnvironment } from "../state/projects";
18import { sourceControlEnvironment } from "../state/sourceControl";
19
20/** Matches the server's read cap: a larger file would arrive truncated. */
21export const COPYABLE_FILE_MAX_BYTES = 1024 * 1024;
22
23const DEFAULT_COPIED_FILE_NAME = /^(?:\.env(?:\..+)?|\.envrc|\.dev\.vars)$/;
24
25/** Env files are the ignored files people almost always want on a new machine. */
26export function isDefaultCopiedFile(path: string): boolean {
27 const name = path.split("/").at(-1) ?? path;
28 return DEFAULT_COPIED_FILE_NAME.test(name);
29}
30
31export interface AddProjectToMachineInput {
32 readonly source: { readonly environmentId: EnvironmentId; readonly cwd: string };
33 /** Where the source project sits below its repository root, or "". */
34 readonly subdirectory: string;
35 readonly target: { readonly environmentId: EnvironmentId; readonly label: string };
36 readonly projectId: ProjectId;
37 readonly title: string;
38 readonly remoteUrl: string;
39 readonly destinationPath: string;
40 readonly files: ReadonlyArray<string>;
41}
42
43function failureMessage(result: Parameters<typeof squashAtomCommandFailure>[0]): string {
44 const error = squashAtomCommandFailure(result);
45 return error instanceof Error ? error.message : "An error occurred.";
46}
47
48/**
49 * Resolves when the clone finishes, or null once it is removed. A failed or
50 * cancelled clone keeps waiting, since the composer offers a retry.
51 */
52function waitForClone(environmentId: EnvironmentId, projectId: ProjectId) {
53 return new Promise<ProjectCloneSnapshot | null>((resolve) => {
54 const atom = environmentProjectClonesAtom(environmentId);
55 let seen = false;
56 let settled = false;
57 let unsubscribe: (() => void) | null = null;
58 const check = (clones: ReadonlyArray<ProjectCloneSnapshot>) => {
59 if (settled) return;
60 const clone = clones.find((candidate) => candidate.projectId === projectId);
61 if (clone) seen = true;
62 const result = clone?.phase === "done" ? clone : !clone && seen ? null : undefined;
63 if (result === undefined) return;
64 settled = true;
65 unsubscribe?.();
66 resolve(result);
67 };
68 unsubscribe = appAtomRegistry.subscribe(atom, check);
69 check(appAtomRegistry.get(atom));
70 });
71}
72
73export type ProjectFileCopy =
74 | { readonly phase: "copying" }
75 | { readonly phase: "failed"; readonly title: string; readonly failures: ReadonlyArray<string> };
76
77/** Ignored-file copies still owed to a cloned project, keyed by its scoped project key. */
78const useFileCopies = create<{ copies: Readonly<Record<string, ProjectFileCopy>> }>(() => ({
79 copies: {},
80}));
81
82function setFileCopy(key: string, copy: ProjectFileCopy | null) {
83 useFileCopies.setState(({ copies }) => {
84 const { [key]: _previous, ...rest } = copies;
85 return { copies: copy === null ? rest : { ...rest, [key]: copy } };
86 });
87}
88
89/** The composer holds sends until the copy lands, and shows a failed copy until dismissed. */
90export function useProjectFileCopy(ref: ScopedProjectRef | null): ProjectFileCopy | null {
91 return useFileCopies((state) => (ref ? (state.copies[scopedProjectKey(ref)] ?? null) : null));
92}
93
94export function dismissProjectFileCopy(ref: ScopedProjectRef) {
95 setFileCopy(scopedProjectKey(ref), null);
96}
97
98/**
99 * Clones a project onto another machine, then copies the chosen ignored files
100 * from the source. The client relays the files because the two servers never
101 * talk to each other. Resolves once the clone starts. The caller opens the new
102 * project, whose composer shows the clone and copy progress, so nothing toasts.
103 */
104export async function addProjectToMachine(input: AddProjectToMachineInput): Promise<void> {
105 // Read first, so the copy reflects the files as they were when the user asked.
106 const reads = await Promise.all(
107 input.files.map(async (relativePath) => {
108 const result = await executeAtomQuery(
109 appAtomRegistry,
110 projectEnvironment.readFile({
111 environmentId: input.source.environmentId,
112 input: { cwd: input.source.cwd, relativePath },
113 }),
114 { label: "Read file to copy", reportFailure: false, refresh: true },
115 );
116 if (result._tag === "Failure") return { relativePath, error: failureMessage(result) };
117 if (result.value.truncated) return { relativePath, error: "Too large to copy." };
118 return { relativePath, contents: result.value.contents };
119 }),
120 );
121
122 const targetRef = { environmentId: input.target.environmentId, projectId: input.projectId };
123 const copyKey = scopedProjectKey(targetRef);
124 // Marked before the start request, since the clone list can arrive before its reply.
125 silenceProjectCloneToasts(targetRef);
126 if (reads.length > 0) setFileCopy(copyKey, { phase: "copying" });
127 const started = await runAtomCommand(
128 appAtomRegistry,
129 sourceControlEnvironment.startProjectClone,
130 {
131 environmentId: input.target.environmentId,
132 input: {
133 projectId: input.projectId,
134 title: input.title,
135 createdAt: new Date().toISOString(),
136 remoteUrl: input.remoteUrl,
137 destinationPath: input.destinationPath,
138 },
139 },
140 { label: "Add project to machine", reportFailure: false },
141 );
142 if (started._tag === "Failure") {
143 setFileCopy(copyKey, null);
144 throw new Error(failureMessage(started));
145 }
146 if (reads.length === 0) return;
147
148 void (async () => {
149 const clone = await waitForClone(input.target.environmentId, input.projectId);
150 if (!clone) {
151 setFileCopy(copyKey, null);
152 return;
153 }
154 const failed: Array<string> = [];
155 for (const read of reads) {
156 if (!("contents" in read)) {
157 failed.push(`${read.relativePath}: ${read.error}`);
158 continue;
159 }
160 const written = await runAtomCommand(
161 appAtomRegistry,
162 projectEnvironment.writeFile,
163 {
164 environmentId: input.target.environmentId,
165 input: {
166 cwd: started.value.cwd,
167 relativePath: input.subdirectory
168 ? `${input.subdirectory}/${read.relativePath}`
169 : read.relativePath,
170 contents: read.contents,
171 },
172 },
173 { label: "Copy file to machine", reportFailure: false },
174 );
175 if (written._tag === "Failure")
176 failed.push(`${read.relativePath}: ${failureMessage(written)}`);
177 }
178 setFileCopy(
179 copyKey,
180 failed.length === 0
181 ? null
182 : {
183 phase: "failed",
184 title: `Could not copy ${failed.length} ${failed.length === 1 ? "file" : "files"} to ${input.target.label}`,
185 failures: failed,
186 },
187 );
188 })();
189}