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