Open History to see the last commit
1import { access, mkdir, rm } from 'node:fs/promises'
2import { tmpdir } from 'node:os'
3import path from 'node:path'
4import { execFile } from 'node:child_process'
5import type { WorkspaceDefinition } from '@tanstack/ai-sandbox'
6
7/**
8 * Run git and resolve with its stdout. `maxBuffer` lifts the 1 MiB output cap
9 * of `execFile` for long lists.
10 */
11export function runGit(
12 args: ReadonlyArray<string>,
13 options: { cwd?: string; env?: NodeJS.ProcessEnv; maxBuffer?: number } = {},
14) {
15 return new Promise<string>((resolve, reject) => {
16 execFile('git', [...args], options, (error, stdout) => {
17 if (error) {
18 reject(error)
19 return
20 }
21 // trimEnd, not trim: the first path in a `-z` list can start with a space.
22 resolve(String(stdout ?? '').trimEnd())
23 })
24 })
25}
26
27export interface HostRepo {
28 hostDir: string
29 owned: boolean
30}
31
32const MISSING_GIT =
33 "sbxSandbox needs a Git repository to pass to `sbx create --clone`. Pass `workspaceDir` that contains `.git`, or set `workspace.source` to a git URL (for example `githubRepo({ repo: 'owner/repo' })`)."
34
35const MISSING_GIT_BIN =
36 'git is not on PATH. Install git, or pass `workspaceDir` that already contains `.git`.'
37
38/** True when `dir` has `.git`: a folder, or the file of a git worktree. */
39export async function hasGitDir(dir: string) {
40 try {
41 await access(path.join(dir, '.git'))
42 return true
43 } catch {
44 return false
45 }
46}
47
48const HOST_REPO_ROOT_NAME = 'tanstack-sbx'
49
50function ownedHostRepoRoot(): string {
51 return path.join(tmpdir(), HOST_REPO_ROOT_NAME)
52}
53
54function invalidSandboxId(id: string): Error {
55 return new Error(
56 `sbxSandbox: invalid sandbox id ${JSON.stringify(id)}. Use a single path segment (not empty, '.', or '..', and with no / or \\) that stays inside tmpdir()/${HOST_REPO_ROOT_NAME}/.`,
57 )
58}
59
60/**
61 * One source of truth for ids used as `sbx --name` and as the owned dest
62 * folder under `tmpdir()/tanstack-sbx/`. Rejects empty, `.`, `..`, path
63 * separators, and any value that would resolve outside that directory.
64 * Does not rewrite a bad id into a safe name.
65 */
66export function sandboxNameFromId(id: string): string {
67 if (typeof id !== 'string' || id.trim() === '' || id === '.' || id === '..') {
68 throw invalidSandboxId(typeof id === 'string' ? id : String(id))
69 }
70 if (id.includes('/') || id.includes('\\') || id.includes('\0')) {
71 throw invalidSandboxId(id)
72 }
73 const root = path.resolve(ownedHostRepoRoot())
74 const dest = path.resolve(path.join(root, id))
75 const prefix = root.endsWith(path.sep) ? root : root + path.sep
76 if (dest === root || !dest.startsWith(prefix)) {
77 throw invalidSandboxId(id)
78 }
79 return id
80}
81
82export function ownedHostRepoDir(id: string): string {
83 return path.join(ownedHostRepoRoot(), sandboxNameFromId(id))
84}
85
86export function ownedCloneMarkerPath(id: string): string {
87 return `${ownedHostRepoDir(id)}.owned`
88}
89
90export async function removeOwnedClone(id: string): Promise<void> {
91 await rm(ownedHostRepoDir(id), { recursive: true, force: true })
92 await rm(ownedCloneMarkerPath(id), { force: true })
93}
94
95function normalizeGitUrl(url: string): string {
96 let value = url.trim().replaceAll('\\', '/')
97 value = value.replace(/\/+$/, '')
98 if (value.toLowerCase().endsWith('.git')) {
99 value = value.slice(0, -4)
100 }
101 if (/^[A-Za-z]:\//.test(value)) {
102 const drive = value.slice(0, 1).toLowerCase()
103 value = drive + value.slice(1)
104 }
105 return value
106}
107
108function isUnexpectedGitProbeError(error: unknown): boolean {
109 // git exits with a number when the dest/remote/ref does not match.
110 // Spawn/syscall failures use a string code (ENOENT, EACCES, ...).
111 if (typeof error !== 'object' || error === null || !('code' in error)) {
112 return true
113 }
114 return typeof error.code !== 'number'
115}
116
117const GIT_SHA_RE = /^[0-9a-f]{7,40}$/i
118
119function isGitSha(ref: string): boolean {
120 return GIT_SHA_RE.test(ref)
121}
122
123/**
124 * Run git and resolve with its output, or with undefined when git exits with
125 * an error code (no such ref, no such config key) or prints nothing. A git
126 * that cannot start (ENOENT, ...) still rejects.
127 */
128export async function probeGit(args: ReadonlyArray<string>, cwd: string) {
129 try {
130 const out = await runGit(args, { cwd })
131 return out === '' ? undefined : out
132 } catch (error) {
133 if (isUnexpectedGitProbeError(error)) throw error
134 return undefined
135 }
136}
137
138async function ownedGitDestMatchesSource(
139 dest: string,
140 source: { url: string; ref?: string },
141): Promise<boolean> {
142 try {
143 const origin = await runGit(['remote', 'get-url', 'origin'], { cwd: dest })
144 if (origin === '') return false
145 if (normalizeGitUrl(origin) !== normalizeGitUrl(source.url)) {
146 return false
147 }
148
149 // Origin-only match is not enough. A leftover clone of the same URL on
150 // another branch (or any HEAD) must reclone when the caller omitted ref.
151 if (!source.ref) return false
152
153 const currentRef = await probeGit(
154 ['rev-parse', '--abbrev-ref', 'HEAD'],
155 dest,
156 )
157 if (currentRef === source.ref) return true
158
159 const headSha = await probeGit(['rev-parse', 'HEAD'], dest)
160 if (headSha === undefined) return false
161
162 if (isGitSha(source.ref)) {
163 const wanted = source.ref.toLowerCase()
164 const head = headSha.toLowerCase()
165 return head === wanted || head.startsWith(wanted)
166 }
167
168 const peeled = await probeGit(['rev-parse', `${source.ref}^{}`], dest)
169 if (peeled === headSha) return true
170
171 const described = await probeGit(
172 ['describe', '--exact-match', '--tags'],
173 dest,
174 )
175 return described === source.ref
176 } catch (error) {
177 if (isUnexpectedGitProbeError(error)) throw error
178 return false
179 }
180}
181
182// Credential helper that prints creds read from the child ENV. The helper
183// string references ${GIT_ASKPASS_*} only — the raw token never lands in
184// GIT_CONFIG_VALUE_0 (process listings / git config dumps).
185const CREDENTIAL_HELPER =
186 '!f() { echo "username=${GIT_ASKPASS_USER}"; echo "password=${GIT_ASKPASS_TOKEN}"; }; f'
187
188async function cloneGitSource(
189 id: string,
190 source: {
191 url: string
192 ref?: string
193 auth?: { username?: string; token: string }
194 depth?: number | 'full'
195 },
196): Promise<string> {
197 const dest = ownedHostRepoDir(id)
198 const resolvedDepth = source.depth ?? 1
199 if (
200 resolvedDepth !== 'full' &&
201 (!Number.isInteger(resolvedDepth) || resolvedDepth <= 0)
202 ) {
203 throw new Error(
204 'sbxSandbox: git clone depth must be a positive integer or "full".',
205 )
206 }
207 await mkdir(path.dirname(dest), { recursive: true })
208 if (
209 (await hasGitDir(dest)) &&
210 (await ownedGitDestMatchesSource(dest, source))
211 ) {
212 return dest
213 }
214 await rm(dest, { recursive: true, force: true })
215 const args = ['clone']
216 if (resolvedDepth !== 'full') {
217 args.push('--depth', String(resolvedDepth))
218 }
219 if (source.ref && !isGitSha(source.ref)) {
220 args.push('--branch', source.ref)
221 }
222 args.push('--', source.url, dest)
223 const env = { ...process.env }
224 if (source.auth?.token) {
225 env.GIT_TERMINAL_PROMPT = '0'
226 env.GIT_ASKPASS_USER = source.auth.username ?? 'x-access-token'
227 env.GIT_ASKPASS_TOKEN = source.auth.token
228 env.GIT_CONFIG_COUNT = '1'
229 env.GIT_CONFIG_KEY_0 = 'credential.helper'
230 env.GIT_CONFIG_VALUE_0 = CREDENTIAL_HELPER
231 }
232 try {
233 await runGit(args, { env })
234 if (source.ref && isGitSha(source.ref)) {
235 const fetchArgs = ['fetch']
236 if (resolvedDepth !== 'full') {
237 fetchArgs.push('--depth', String(resolvedDepth))
238 }
239 fetchArgs.push('--', 'origin', source.ref)
240 await runGit(fetchArgs, { cwd: dest, env })
241 await runGit(['checkout', '--detach', source.ref], { cwd: dest, env })
242 }
243 } catch (error) {
244 await rm(dest, { recursive: true, force: true }).catch(() => {})
245 if (
246 error &&
247 typeof error === 'object' &&
248 'code' in error &&
249 error.code === 'ENOENT'
250 ) {
251 throw new Error(MISSING_GIT_BIN)
252 }
253 throw error
254 }
255 return dest
256}
257
258export async function resolveHostRepo(input: {
259 id: string
260 workspaceDir?: string
261 workspace?: WorkspaceDefinition
262}): Promise<HostRepo> {
263 if (input.workspaceDir) {
264 if (!(await hasGitDir(input.workspaceDir))) {
265 throw new Error(MISSING_GIT)
266 }
267 return { hostDir: input.workspaceDir, owned: false }
268 }
269 const source = input.workspace?.source
270 if (source?.type === 'git') {
271 const hostDir = await cloneGitSource(input.id, source)
272 return { hostDir, owned: true }
273 }
274 if (source?.type === 'local') {
275 const hostDir = path.resolve(source.path)
276 if (!(await hasGitDir(hostDir))) {
277 throw new Error(MISSING_GIT)
278 }
279 return { hostDir, owned: false }
280 }
281 throw new Error(MISSING_GIT)
282}