@yuridulin/pointer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +54 -2
  2. package/package.json +51 -4
  3. package/server/acp/catalog.ts +111 -0
  4. package/server/acp/connection.ts +233 -0
  5. package/server/acp/fake-agent.ts +408 -0
  6. package/server/acp/protocol.ts +167 -0
  7. package/server/acp/run.ts +139 -0
  8. package/server/acp/session.ts +1249 -0
  9. package/server/attachments.ts +115 -0
  10. package/server/changes.ts +239 -0
  11. package/server/cli.ts +362 -0
  12. package/server/compact.ts +361 -0
  13. package/server/config.ts +176 -0
  14. package/server/db.ts +462 -0
  15. package/server/dev.ts +8 -0
  16. package/server/diff.ts +190 -0
  17. package/server/engines.ts +63 -0
  18. package/server/files.ts +254 -0
  19. package/server/git.ts +319 -0
  20. package/server/history.ts +425 -0
  21. package/server/http/attachments.ts +63 -0
  22. package/server/http/browse.ts +108 -0
  23. package/server/http/chats.ts +627 -0
  24. package/server/http/closing.ts +14 -0
  25. package/server/http/files.ts +115 -0
  26. package/server/http/git.ts +84 -0
  27. package/server/http/preview.ts +21 -0
  28. package/server/http/providers.ts +200 -0
  29. package/server/http/reply.ts +38 -0
  30. package/server/hub.ts +521 -0
  31. package/server/install.ts +169 -0
  32. package/server/jobs.ts +664 -0
  33. package/server/linkPreview.ts +172 -0
  34. package/server/loop.ts +328 -0
  35. package/server/main.ts +353 -0
  36. package/server/probe.ts +34 -0
  37. package/server/process.ts +333 -0
  38. package/server/prompt.ts +196 -0
  39. package/server/providers/fake.ts +100 -0
  40. package/server/providers/opencode.ts +468 -0
  41. package/server/providers/registry.ts +149 -0
  42. package/server/providers/store.ts +210 -0
  43. package/server/segments.ts +248 -0
  44. package/server/sse.ts +93 -0
  45. package/server/tools/bash.ts +222 -0
  46. package/server/tools/edit.ts +254 -0
  47. package/server/tools/glob.ts +63 -0
  48. package/server/tools/grep.ts +122 -0
  49. package/server/tools/ignore.ts +54 -0
  50. package/server/tools/index.ts +129 -0
  51. package/server/tools/jail.ts +85 -0
  52. package/server/tools/jobs.ts +293 -0
  53. package/server/tools/read.ts +248 -0
  54. package/server/tools/write.ts +70 -0
  55. package/server/tray.ps1 +191 -0
  56. package/server/turn.ts +663 -0
  57. package/server/watch.ts +94 -0
  58. package/shared/acpConfig.ts +113 -0
  59. package/shared/links.ts +122 -0
  60. package/shared/types.ts +392 -0
  61. package/web/dist/app.css +1 -0
  62. package/web/dist/assets/codicon-mxdk0fnd.ttf +0 -0
  63. package/web/dist/index.html +28 -0
  64. package/web/dist/main.css +1 -0
  65. package/web/dist/main.js +1366 -0
  66. package/web/dist/tokens.css +1 -0
  67. package/web/dist/workers/css.worker.js +97 -0
  68. package/web/dist/workers/editor.worker.js +30 -0
  69. package/web/dist/workers/html.worker.js +300 -0
  70. package/web/dist/workers/json.worker.js +62 -0
  71. package/web/dist/workers/ts.worker.js +67733 -0
@@ -0,0 +1,63 @@
1
+ import { existsSync } from 'node:fs'
2
+ import type { EngineInfo } from '../shared/types'
3
+ import type { Config } from './config'
4
+ import type { AcpOverride } from './providers/store'
5
+
6
+ export type AcpAgentSpec = {
7
+ id: string
8
+ label: string
9
+ args: string[]
10
+ authMethod?: string
11
+ }
12
+
13
+ export const ACP_AGENTS: readonly AcpAgentSpec[] = [
14
+ { id: 'cursor', label: 'Cursor', args: ['acp'], authMethod: 'cursor_login' },
15
+ ]
16
+
17
+ export function acpAgent(engineId: string): AcpAgentSpec | null {
18
+ if (!engineId.startsWith('acp:')) return null
19
+ const id = engineId.slice('acp:'.length)
20
+ return ACP_AGENTS.find((agent) => agent.id === id) ?? null
21
+ }
22
+
23
+ export function isAcpEngine(engineId: string): boolean {
24
+ return acpAgent(engineId) !== null
25
+ }
26
+
27
+ /** Finds the ACP CLI from the configured command or PATH. */
28
+ export function resolveAcpCommand(
29
+ config: Config,
30
+ spec: AcpAgentSpec,
31
+ override?: AcpOverride,
32
+ ): { command: string; args: string[] } | null {
33
+ const preferred = override?.command || config.acpCommand
34
+ const candidates = [preferred, 'cursor-agent', 'agent'].filter(
35
+ (candidate, index, all) => candidate.length > 0 && all.indexOf(candidate) === index,
36
+ )
37
+ const args = override?.args ?? config.acpArgs ?? spec.args
38
+ for (const candidate of candidates) {
39
+ const command = lookup(candidate)
40
+ if (command) return { command, args }
41
+ }
42
+ return null
43
+ }
44
+
45
+ function lookup(command: string): string | null {
46
+ if (command.includes('/') || command.includes('\\')) {
47
+ return existsSync(command) ? command : null
48
+ }
49
+ return Bun.which(command)
50
+ }
51
+
52
+ export function listEngines(config: Config, override?: AcpOverride, cursorEnabled = true): EngineInfo[] {
53
+ const engines: EngineInfo[] = [{ id: 'native', label: 'Свой цикл', kind: 'native', available: true }]
54
+ for (const agent of ACP_AGENTS) {
55
+ engines.push({
56
+ id: `acp:${agent.id}`,
57
+ label: agent.label,
58
+ kind: 'acp',
59
+ available: cursorEnabled && resolveAcpCommand(config, agent, override) !== null,
60
+ })
61
+ }
62
+ return engines
63
+ }
@@ -0,0 +1,254 @@
1
+ import { readdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs'
2
+ import type { Stats } from 'node:fs'
3
+ import { join, parse, resolve } from 'node:path'
4
+ import type { BrowseEntry, BrowseResult, FileNode } from '../shared/types'
5
+ import { BLOB_LIMIT, hashBytes, hashOnDisk, writeAtomic } from './changes'
6
+ import { isIgnoredDir } from './tools/ignore'
7
+ import { resolveInRoot } from './tools/jail'
8
+
9
+ const TEXT_SNIFF = 8 * 1024
10
+
11
+ /** An expected failure of a file operation; `status` is the HTTP code for the route. */
12
+ export class FileError extends Error {
13
+ constructor(
14
+ readonly status: number,
15
+ message: string,
16
+ ) {
17
+ super(message)
18
+ this.name = 'FileError'
19
+ }
20
+ }
21
+
22
+ export type WriteOutcome =
23
+ | { status: 'written'; path: string; hash: string }
24
+ | { status: 'conflict'; path: string; hash: string | null; content: string | null }
25
+
26
+ export type RenameOutcome = { from: string; to: string; hash: string | null }
27
+
28
+ export type DeleteOutcome = { path: string; type: 'file' | 'dir' }
29
+
30
+ export type UploadedFile = { path: string; hash: string }
31
+
32
+ /** Dirs first, then files, both by name. Ignored directories are left out. */
33
+ export function readTree(root: string): FileNode[] {
34
+ const base = resolve(root)
35
+ const stat = statOrNull(base)
36
+ if (!stat?.isDirectory()) throw new FileError(400, 'Папка не читается')
37
+ return childrenOf(base, '')
38
+ }
39
+
40
+ function childrenOf(dirAbs: string, relDir: string): FileNode[] {
41
+ let entries
42
+ try {
43
+ entries = readdirSync(dirAbs, { withFileTypes: true })
44
+ } catch {
45
+ return []
46
+ }
47
+ const nodes: FileNode[] = []
48
+ for (const entry of entries) {
49
+ const rel = relDir ? `${relDir}/${entry.name}` : entry.name
50
+ if (entry.isDirectory()) {
51
+ if (isIgnoredDir(entry.name)) continue
52
+ nodes.push({
53
+ name: entry.name,
54
+ path: rel,
55
+ type: 'dir',
56
+ children: childrenOf(join(dirAbs, entry.name), rel),
57
+ })
58
+ continue
59
+ }
60
+ if (!entry.isFile()) continue
61
+ nodes.push({ name: entry.name, path: rel, type: 'file' })
62
+ }
63
+ nodes.sort((a, b) =>
64
+ a.type === b.type
65
+ ? a.name < b.name
66
+ ? -1
67
+ : a.name > b.name
68
+ ? 1
69
+ : 0
70
+ : a.type === 'dir'
71
+ ? -1
72
+ : 1,
73
+ )
74
+ return nodes
75
+ }
76
+
77
+ export function readText(root: string, input: string): { content: string; hash: string } {
78
+ const jailed = jailedPath(root, input)
79
+ if (jailed.rel === '') throw new FileError(400, 'Нужен путь к файлу')
80
+ const stat = statOrNull(jailed.abs)
81
+ if (stat === null) throw new FileError(404, 'Файл не найден')
82
+ if (stat.isDirectory()) throw new FileError(400, `${jailed.rel} — это папка`)
83
+ if (stat.size > BLOB_LIMIT) throw new FileError(400, `${jailed.rel} больше 2 МБ`)
84
+ const bytes = readFileSync(jailed.abs)
85
+ if (bytes.subarray(0, TEXT_SNIFF).includes(0)) {
86
+ throw new FileError(400, `${jailed.rel} — бинарный файл`)
87
+ }
88
+ let content: string
89
+ try {
90
+ // ignoreBOM keeps a leading U+FEFF, so saving the same text restores the same bytes.
91
+ content = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes)
92
+ } catch {
93
+ throw new FileError(400, `${jailed.rel} — не UTF-8`)
94
+ }
95
+ return { content, hash: hashBytes(bytes) }
96
+ }
97
+
98
+ /** `baseHash` undefined writes unconditionally; null requires the file to be absent. */
99
+ export function writeText(
100
+ root: string,
101
+ input: string,
102
+ content: string,
103
+ baseHash?: string | null,
104
+ ): WriteOutcome {
105
+ const jailed = jailedPath(root, input)
106
+ if (jailed.rel === '') throw new FileError(400, 'Нужен путь к файлу')
107
+ const stat = statOrNull(jailed.abs)
108
+ if (stat?.isDirectory()) throw new FileError(400, `${jailed.rel} — это папка`)
109
+ // Hashing reads the whole file, so an oversized target is rejected from its stat first.
110
+ if (stat !== null && stat.size > BLOB_LIMIT) {
111
+ throw new FileError(400, `${jailed.rel} больше 2 МБ`)
112
+ }
113
+ const current = hashOnDisk(jailed.abs)
114
+ if (baseHash !== undefined && baseHash !== current) {
115
+ let text: string | null
116
+ try {
117
+ text = readText(root, jailed.rel).content
118
+ } catch {
119
+ text = null
120
+ }
121
+ return { status: 'conflict', path: jailed.rel, hash: current, content: text }
122
+ }
123
+ const bytes = new TextEncoder().encode(content)
124
+ if (bytes.byteLength > BLOB_LIMIT) {
125
+ throw new FileError(400, `Новое содержимое ${jailed.rel} больше 2 МБ`)
126
+ }
127
+ writeAtomic(jailed.abs, bytes)
128
+ return { status: 'written', path: jailed.rel, hash: hashBytes(bytes) }
129
+ }
130
+
131
+ export function renameEntry(root: string, input: string, to: string): RenameOutcome {
132
+ const source = jailedPath(root, input)
133
+ const target = jailedPath(root, to)
134
+ if (source.rel === '') throw new FileError(400, 'Нельзя переименовать корень папки')
135
+ if (target.rel === '') throw new FileError(400, 'Нужно новое имя внутри папки')
136
+ const stat = statOrNull(source.abs)
137
+ if (stat === null) throw new FileError(404, 'Источник не найден')
138
+ if (statOrNull(target.abs) !== null) throw new FileError(409, `Уже существует: ${target.rel}`)
139
+ try {
140
+ renameSync(source.abs, target.abs)
141
+ } catch (error) {
142
+ throw new FileError(400, error instanceof Error ? error.message : String(error))
143
+ }
144
+ return { from: source.rel, to: target.rel, hash: stat.isDirectory() ? null : hashOnDisk(target.abs) }
145
+ }
146
+
147
+ export function deleteEntry(root: string, input: string, recursive: boolean): DeleteOutcome {
148
+ const jailed = jailedPath(root, input)
149
+ if (jailed.rel === '') throw new FileError(400, 'Нельзя удалить корень папки')
150
+ const stat = statOrNull(jailed.abs)
151
+ if (stat === null) throw new FileError(404, 'Путь не найден')
152
+ if (stat.isDirectory()) {
153
+ let entries
154
+ try {
155
+ entries = readdirSync(jailed.abs)
156
+ } catch (error) {
157
+ throw new FileError(400, error instanceof Error ? error.message : String(error))
158
+ }
159
+ if (entries.length > 0 && !recursive) throw new FileError(409, 'Папка не пуста')
160
+ rmSync(jailed.abs, { recursive: true, force: true })
161
+ return { path: jailed.rel, type: 'dir' }
162
+ }
163
+ rmSync(jailed.abs, { force: true })
164
+ return { path: jailed.rel, type: 'file' }
165
+ }
166
+
167
+ export async function saveUploads(
168
+ root: string,
169
+ dir: string,
170
+ files: File[],
171
+ ): Promise<UploadedFile[]> {
172
+ if (files.length === 0) throw new FileError(400, 'Нет файлов')
173
+ const targetDir = jailedPath(root, dir === '' ? '.' : dir)
174
+ if (statOrNull(targetDir.abs)?.isDirectory() !== true) {
175
+ throw new FileError(400, 'Папка для загрузки не найдена')
176
+ }
177
+ const saved: UploadedFile[] = []
178
+ for (const file of files) {
179
+ const name = uploadName(file.name)
180
+ const target = jailedPath(root, targetDir.rel === '' ? name : `${targetDir.rel}/${name}`)
181
+ if (file.size > BLOB_LIMIT) {
182
+ throw new FileError(400, `${target.rel} больше 2 МБ`)
183
+ }
184
+ const bytes = new Uint8Array(await file.arrayBuffer())
185
+ try {
186
+ writeAtomic(target.abs, bytes)
187
+ } catch (error) {
188
+ throw new FileError(400, error instanceof Error ? error.message : String(error))
189
+ }
190
+ saved.push({ path: target.rel, hash: hashBytes(bytes) })
191
+ }
192
+ return saved
193
+ }
194
+
195
+ export function browseDirs(input: string): BrowseResult {
196
+ const wanted = input.trim()
197
+ if (wanted === '') return roots()
198
+ const path = resolve(wanted)
199
+ const dirs = listDirs(path)
200
+ if (dirs === null) throw new FileError(400, 'Папка не читается')
201
+ return { path, parent: parse(path).root === path ? null : resolve(path, '..'), dirs }
202
+ }
203
+
204
+ function roots(): BrowseResult {
205
+ if (process.platform !== 'win32') {
206
+ return { path: '/', parent: null, dirs: listDirs('/') ?? [] }
207
+ }
208
+ const dirs: BrowseEntry[] = []
209
+ for (let code = 65; code <= 90; code++) {
210
+ const letter = String.fromCharCode(code)
211
+ const root = `${letter}:\\`
212
+ if (listDirs(root) === null) continue
213
+ dirs.push({ name: `${letter}:`, path: root })
214
+ }
215
+ return { path: '', parent: null, dirs }
216
+ }
217
+
218
+ function listDirs(path: string): BrowseEntry[] | null {
219
+ let entries
220
+ try {
221
+ entries = readdirSync(path, { withFileTypes: true })
222
+ } catch {
223
+ return null
224
+ }
225
+ return entries
226
+ .filter((entry) => entry.isDirectory())
227
+ .map((entry) => ({ name: entry.name, path: join(path, entry.name) }))
228
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0))
229
+ }
230
+
231
+ function uploadName(raw: string): string {
232
+ if (!raw || raw === '.' || raw === '..' || /[\\/]/.test(raw) || raw.includes('\0')) {
233
+ throw new FileError(400, `Недопустимое имя файла: ${raw}`)
234
+ }
235
+ return raw
236
+ }
237
+
238
+ /** Jail rejections are expected model/user mistakes, so they become 400 instead of a crash. */
239
+ function jailedPath(root: string, input: string) {
240
+ try {
241
+ return resolveInRoot(root, input)
242
+ } catch (error) {
243
+ throw new FileError(400, error instanceof Error ? error.message : String(error))
244
+ }
245
+ }
246
+
247
+ function statOrNull(path: string): Stats | null {
248
+ try {
249
+ return statSync(path)
250
+ } catch (error) {
251
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null
252
+ throw new FileError(400, 'Путь не читается')
253
+ }
254
+ }
package/server/git.ts ADDED
@@ -0,0 +1,319 @@
1
+ import type { GitBranch, GitChange, GitStatus } from '../shared/types'
2
+ import { BLOB_LIMIT } from './changes'
3
+ import { resolveInRoot } from './tools/jail'
4
+
5
+ const TEXT_SNIFF = 8 * 1024
6
+ const GIT_TIMEOUT_MS = 30_000
7
+ const STATUS_LIMIT = 16 * 1024 * 1024
8
+
9
+ /** Optional plumbing for every git call: a configured binary, cancellation and a deadline. */
10
+ export type GitOptions = { gitPath?: string; signal?: AbortSignal; timeoutMs?: number }
11
+
12
+ /** An expected failure of a git operation; `status` is the HTTP code for the route. */
13
+ export class GitError extends Error {
14
+ constructor(
15
+ readonly status: number,
16
+ message: string,
17
+ ) {
18
+ super(message)
19
+ this.name = 'GitError'
20
+ }
21
+ }
22
+
23
+ type GitRun = { code: number; bytes: Uint8Array; text: string; stderr: string }
24
+
25
+ async function runGit(root: string, args: string[], options?: GitOptions): Promise<GitRun> {
26
+ let proc: Bun.Subprocess<'ignore', 'pipe', 'pipe'>
27
+ try {
28
+ proc = Bun.spawn([options?.gitPath ?? 'git', ...args], {
29
+ cwd: root,
30
+ stdin: 'ignore',
31
+ stdout: 'pipe',
32
+ stderr: 'pipe',
33
+ // A credentials prompt would hang the daemon with no one to answer it.
34
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
35
+ signal: options?.signal,
36
+ })
37
+ } catch (error) {
38
+ // An invalid gitPath is a configuration error, not a broken request.
39
+ throw new GitError(503, `git не запускается: ${error instanceof Error ? error.message : String(error)}`)
40
+ }
41
+ const timeoutMs = options?.timeoutMs ?? GIT_TIMEOUT_MS
42
+ let timedOut = false
43
+ const timer =
44
+ timeoutMs > 0
45
+ ? setTimeout(() => {
46
+ timedOut = true
47
+ try {
48
+ proc.kill(9)
49
+ } catch {}
50
+ }, timeoutMs)
51
+ : undefined
52
+ try {
53
+ const [out, err, code] = await Promise.all([
54
+ new Response(proc.stdout).arrayBuffer(),
55
+ new Response(proc.stderr).text(),
56
+ proc.exited,
57
+ ])
58
+ if (timedOut) {
59
+ throw new GitError(504, `git ${args[0] ?? ''} не завершился за ${timeoutMs} мс`)
60
+ }
61
+ const bytes = new Uint8Array(out)
62
+ return { code, bytes, text: new TextDecoder().decode(bytes), stderr: err.trim() }
63
+ } finally {
64
+ clearTimeout(timer)
65
+ }
66
+ }
67
+
68
+ async function mustGit(root: string, args: string[], options?: GitOptions): Promise<GitRun> {
69
+ const run = await runGit(root, args, options)
70
+ if (run.code !== 0) {
71
+ throw new GitError(400, run.stderr || `git ${args[0] ?? ''} exited with ${run.code}`)
72
+ }
73
+ return run
74
+ }
75
+
76
+ /** Paths from the UI are resolved inside the workspace before git sees them. */
77
+ function inWorkspace(root: string, input: string): string {
78
+ try {
79
+ // A leading colon would be read as pathspec magic (`:(top)`, `:!`), so it never reaches git.
80
+ if (input.startsWith(':')) throw new Error('Путь не может начинаться с двоеточия')
81
+ const jailed = resolveInRoot(root, input)
82
+ if (jailed.rel === '') throw new Error('Путь не может быть корнем папки')
83
+ return jailed.rel
84
+ } catch (error) {
85
+ throw new GitError(400, error instanceof Error ? error.message : String(error))
86
+ }
87
+ }
88
+
89
+ async function branchOf(root: string, options?: GitOptions): Promise<string | null> {
90
+ // symbolic-ref works on an unborn branch, where rev-parse HEAD does not.
91
+ const run = await runGit(root, ['symbolic-ref', '--short', '-q', 'HEAD'], options)
92
+ return run.code === 0 ? run.text.trim() || null : null
93
+ }
94
+
95
+ export async function gitStatus(root: string, options?: GitOptions): Promise<GitStatus> {
96
+ const repo = await runGit(root, ['rev-parse', '--show-toplevel'], options)
97
+ if (repo.code !== 0) return { repo: false, branch: null, changes: [] }
98
+ const [branch, prefix, status] = await Promise.all([
99
+ branchOf(root, options),
100
+ runGit(root, ['rev-parse', '--show-prefix'], options),
101
+ mustGit(root, ['status', '--porcelain=v2', '-z', '--untracked-files=all'], options),
102
+ ])
103
+ if (status.bytes.byteLength > STATUS_LIMIT) {
104
+ throw new GitError(400, 'Список изменений git больше 16 МБ; закоммитьте часть работы')
105
+ }
106
+ const inside = prefix.code === 0 ? prefix.text.trim() : ''
107
+ return { repo: true, branch, changes: scoped(parsePorcelain(status.text), inside) }
108
+ }
109
+
110
+ /** Status paths are relative to the repository root; the panel shows the workspace folder. */
111
+ function scoped(changes: GitChange[], prefix: string): GitChange[] {
112
+ if (prefix === '') return changes
113
+ const kept: GitChange[] = []
114
+ for (const change of changes) {
115
+ if (!change.path.startsWith(prefix)) continue
116
+ const path = change.path.slice(prefix.length)
117
+ if (path === '') continue
118
+ const origPath =
119
+ change.origPath !== undefined && change.origPath.startsWith(prefix)
120
+ ? change.origPath.slice(prefix.length)
121
+ : change.origPath
122
+ kept.push(origPath === undefined ? { ...change, path } : { ...change, path, origPath })
123
+ }
124
+ return kept
125
+ }
126
+
127
+ /** `status --porcelain=v2 -z`: NUL-separated records, paths are raw UTF-8. */
128
+ function parsePorcelain(raw: string): GitChange[] {
129
+ const tokens = raw.split('\0')
130
+ const changes: GitChange[] = []
131
+ let at = 0
132
+ while (at < tokens.length) {
133
+ const token = tokens[at++] ?? ''
134
+ if (token === '') continue
135
+ const kind = token[0]
136
+ if (kind === '1') {
137
+ const fields = token.split(' ')
138
+ changes.push(entry('changed', fields, 8))
139
+ continue
140
+ }
141
+ if (kind === '2') {
142
+ const fields = token.split(' ')
143
+ const change = entry('renamed', fields, 9)
144
+ change.origPath = tokens[at++] ?? ''
145
+ changes.push(change)
146
+ continue
147
+ }
148
+ if (kind === 'u') {
149
+ changes.push(entry('unmerged', token.split(' '), 10))
150
+ continue
151
+ }
152
+ if (kind === '?') {
153
+ changes.push({ path: token.slice(2), index: '?', worktree: '?', kind: 'untracked' })
154
+ }
155
+ }
156
+ return changes
157
+ }
158
+
159
+ function entry(
160
+ kind: GitChange['kind'],
161
+ fields: string[],
162
+ pathAt: number,
163
+ ): GitChange {
164
+ const xy = fields[1] ?? ''
165
+ return {
166
+ path: fields.slice(pathAt).join(' '),
167
+ index: xy[0] ?? ' ',
168
+ worktree: xy[1] ?? ' ',
169
+ kind,
170
+ }
171
+ }
172
+
173
+ export async function gitFile(
174
+ root: string,
175
+ ref: string,
176
+ path: string,
177
+ options?: GitOptions,
178
+ ): Promise<{ content: string | null }> {
179
+ if (!/^[A-Za-z0-9_][A-Za-z0-9._/^~@{}-]*$/.test(ref)) {
180
+ throw new GitError(400, `Недопустимый ref: ${ref}`)
181
+ }
182
+ const rel = inWorkspace(root, path)
183
+ const known = await runGit(root, ['rev-parse', '--verify', `${ref}^{commit}`], options)
184
+ if (known.code !== 0) throw new GitError(400, `Неизвестный ref: ${ref}`)
185
+
186
+ const object = `${ref}:./${rel}`
187
+ const exists = await runGit(root, ['cat-file', '-e', object], options)
188
+ if (exists.code !== 0) return { content: null }
189
+
190
+ // The blob size is cheap to ask for; reading a huge blob just to reject it is not.
191
+ const sized = await runGit(root, ['cat-file', '-s', object], options)
192
+ const size = sized.code === 0 ? Number(sized.text.trim()) : Number.NaN
193
+ if (!Number.isFinite(size)) throw new GitError(400, `${rel} не читается в ${ref}`)
194
+ if (size > BLOB_LIMIT) {
195
+ throw new GitError(400, `${rel} больше 2 МБ в ${ref}`)
196
+ }
197
+
198
+ const shown = await mustGit(root, ['show', object], options)
199
+ if (shown.bytes.subarray(0, TEXT_SNIFF).includes(0)) {
200
+ throw new GitError(400, `${rel} — бинарный файл`)
201
+ }
202
+ try {
203
+ return { content: new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(shown.bytes) }
204
+ } catch {
205
+ throw new GitError(400, `${rel} в ${ref} — не UTF-8`)
206
+ }
207
+ }
208
+
209
+ export async function gitBranches(root: string, options?: GitOptions): Promise<GitBranch[]> {
210
+ const run = await mustGit(root, ['branch', '--format=%(refname:short)%09%(HEAD)'], options)
211
+ return run.text
212
+ .split('\n')
213
+ .filter((line) => line !== '')
214
+ .map((line) => {
215
+ const [name = '', head = ''] = line.split('\t')
216
+ return { name, current: head === '*' }
217
+ })
218
+ }
219
+
220
+ /** Empty `paths` is a mistake, not a request to touch the whole workspace. */
221
+ function targetsOf(root: string, paths: string[] | null): string[] {
222
+ if (paths === null) return ['.']
223
+ if (paths.length === 0) throw new GitError(400, 'Список путей пуст')
224
+ return paths.map((path) => inWorkspace(root, path))
225
+ }
226
+
227
+ /** `paths === null` means every change in the workspace folder. */
228
+ export async function gitStage(
229
+ root: string,
230
+ paths: string[] | null,
231
+ options?: GitOptions,
232
+ ): Promise<void> {
233
+ const targets = targetsOf(root, paths)
234
+ // --literal-pathspecs keeps glob and `:(top)` magic out of user-supplied names.
235
+ await mustGit(root, ['--literal-pathspecs', 'add', '-A', '--', ...targets], options)
236
+ }
237
+
238
+ export async function gitUnstage(
239
+ root: string,
240
+ paths: string[] | null,
241
+ options?: GitOptions,
242
+ ): Promise<void> {
243
+ const targets = targetsOf(root, paths)
244
+ const head = await runGit(root, ['rev-parse', '--verify', 'HEAD'], options)
245
+ // On an unborn branch there is no HEAD to reset to; the index is cleared directly.
246
+ const args =
247
+ head.code === 0
248
+ ? ['--literal-pathspecs', 'reset', '--', ...targets]
249
+ : ['--literal-pathspecs', 'rm', '-r', '--cached', '--ignore-unmatch', '--', ...targets]
250
+ await mustGit(root, args, options)
251
+ }
252
+
253
+ /** Paths staged outside the workspace folder would ride along into this commit. */
254
+ async function assertIndexInside(root: string, options?: GitOptions): Promise<void> {
255
+ const prefix = await mustGit(root, ['rev-parse', '--show-prefix'], options)
256
+ const inside = prefix.text.trim()
257
+ if (inside === '') return
258
+ const staged = await mustGit(
259
+ root,
260
+ ['diff', '--cached', '--name-only', '-z', '--no-renames'],
261
+ options,
262
+ )
263
+ const outside = staged.text
264
+ .split('\0')
265
+ .filter((path) => path !== '' && !path.startsWith(inside))
266
+ if (outside.length === 0) return
267
+ const shown = outside.slice(0, 5).join(', ')
268
+ const more = outside.length > 5 ? ` и ещё ${outside.length - 5}` : ''
269
+ throw new GitError(
270
+ 400,
271
+ `В индексе есть файлы вне папки проекта: ${shown}${more}. Закоммитьте их отдельно или исключите из индекса`,
272
+ )
273
+ }
274
+
275
+ export async function gitCommit(
276
+ root: string,
277
+ message: string,
278
+ amend: boolean,
279
+ options?: GitOptions,
280
+ ): Promise<{ commit: string }> {
281
+ await assertIndexInside(root, options)
282
+ const args = ['commit', '-m', message]
283
+ if (amend) args.push('--amend')
284
+ await mustGit(root, args, options)
285
+ const head = await mustGit(root, ['rev-parse', 'HEAD'], options)
286
+ return { commit: head.text.trim() }
287
+ }
288
+
289
+ export async function gitCheckout(
290
+ root: string,
291
+ branch: string,
292
+ create: boolean,
293
+ options?: GitOptions,
294
+ ): Promise<{ branch: string; changed: string[] }> {
295
+ const valid = await runGit(root, ['check-ref-format', '--branch', branch], options)
296
+ if (valid.code !== 0) throw new GitError(400, `Недопустимое имя ветки: ${branch}`)
297
+
298
+ const before = await runGit(root, ['rev-parse', '--verify', 'HEAD'], options)
299
+ await mustGit(root, create ? ['checkout', '-b', branch] : ['checkout', branch], options)
300
+ const after = await runGit(root, ['rev-parse', '--verify', 'HEAD'], options)
301
+
302
+ const changed: string[] = []
303
+ if (before.code === 0 && after.code === 0 && before.text !== after.text) {
304
+ const diff = await runGit(
305
+ root,
306
+ [
307
+ 'diff',
308
+ '--name-only',
309
+ '-z',
310
+ '--relative',
311
+ before.text.trim(),
312
+ after.text.trim(),
313
+ ],
314
+ options,
315
+ )
316
+ if (diff.code === 0) changed.push(...diff.text.split('\0').filter((path) => path !== ''))
317
+ }
318
+ return { branch: (await branchOf(root, options)) ?? branch, changed }
319
+ }