dsh-vscode-workbench 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.
- package/LICENSE +21 -0
- package/README.en.md +82 -0
- package/README.md +81 -0
- package/lib/client.js +6039 -0
- package/lib/client.js.map +1 -0
- package/lib/index.js +832 -0
- package/lib/index.js.map +1 -0
- package/lib/types/client/DshConversationPanel.d.ts +14 -0
- package/lib/types/client/DshMark.d.ts +4 -0
- package/lib/types/client/Icon.d.ts +8 -0
- package/lib/types/client/MarkdownPreview.d.ts +14 -0
- package/lib/types/client/MonacoEditor.d.ts +28 -0
- package/lib/types/client/Workbench.d.ts +34 -0
- package/lib/types/client/api.d.ts +1 -0
- package/lib/types/client/index.d.ts +20 -0
- package/lib/types/client/service.d.ts +60 -0
- package/lib/types/client/styles.d.ts +1 -0
- package/lib/types/context.d.ts +30 -0
- package/lib/types/host.d.ts +41 -0
- package/lib/types/index.d.ts +6 -0
- package/lib/types/types.d.ts +72 -0
- package/lib/types/wire.d.ts +11 -0
- package/package.json +97 -0
- package/src/client/DshConversationPanel.tsx +56 -0
- package/src/client/DshMark.tsx +16 -0
- package/src/client/Icon.tsx +23 -0
- package/src/client/MarkdownPreview.tsx +18 -0
- package/src/client/MonacoEditor.tsx +56 -0
- package/src/client/Workbench.tsx +185 -0
- package/src/client/api.ts +8 -0
- package/src/client/index.tsx +39 -0
- package/src/client/service.ts +58 -0
- package/src/client/styles.ts +49 -0
- package/src/context.ts +16 -0
- package/src/host.ts +306 -0
- package/src/index.ts +96 -0
- package/src/types.ts +18 -0
- package/src/wire.ts +49 -0
package/src/host.ts
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { spawn } from 'node:child_process'
|
|
3
|
+
import { createRequire } from 'node:module'
|
|
4
|
+
import { dirname, extname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path'
|
|
5
|
+
import { access, lstat, mkdir, open, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
6
|
+
import { constants } from 'node:fs'
|
|
7
|
+
import type { HostContext } from './context.ts'
|
|
8
|
+
import type { FileDocument, FileEntry, GitChange, GitCommit, GitCommitFile, GitDiff, GitStatus, SearchMatch, SearchRequest } from './types.ts'
|
|
9
|
+
import { WorkbenchError } from './wire.ts'
|
|
10
|
+
|
|
11
|
+
const require = createRequire(import.meta.url)
|
|
12
|
+
const TEXT_LIMIT = 5 * 1024 * 1024
|
|
13
|
+
const PROCESS_TIMEOUT = 30_000
|
|
14
|
+
|
|
15
|
+
export function cwdFor(ctx: HostContext, sessionId: string): string {
|
|
16
|
+
const cwd = ctx.sessions.get(sessionId)?.header.cwd
|
|
17
|
+
if (cwd === undefined || cwd === '') return process.cwd()
|
|
18
|
+
if (!isAbsolute(cwd)) throw new WorkbenchError('cwd-invalid', 'session working directory is not absolute')
|
|
19
|
+
return normalize(cwd)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function inside(root: string, target: string): boolean {
|
|
23
|
+
const rel = relative(root, target)
|
|
24
|
+
return rel === '' || (!rel.startsWith(`..${sep}`) && rel !== '..' && !isAbsolute(rel))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function canonicalRoot(cwd: string): Promise<string> {
|
|
28
|
+
return realpath(cwd).catch(() => { throw new WorkbenchError('cwd-missing', 'session working directory does not exist', 404) })
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Resolve a caller-relative path and reject traversal and symlink escape. */
|
|
32
|
+
export async function workspacePath(cwd: string, raw: string, create = false): Promise<{ root: string; absolute: string }> {
|
|
33
|
+
if (isAbsolute(raw)) throw new WorkbenchError('path-invalid', 'absolute paths are not accepted')
|
|
34
|
+
const root = await canonicalRoot(cwd)
|
|
35
|
+
const absolute = resolve(root, raw === '' ? '.' : raw)
|
|
36
|
+
if (!inside(root, absolute)) throw new WorkbenchError('path-outside', 'path is outside the workspace', 403)
|
|
37
|
+
if (create) {
|
|
38
|
+
const parent = await realpath(dirname(absolute)).catch(() => { throw new WorkbenchError('parent-missing', 'parent directory does not exist', 404) })
|
|
39
|
+
if (!inside(root, parent)) throw new WorkbenchError('path-outside', 'path follows a symlink outside the workspace', 403)
|
|
40
|
+
} else {
|
|
41
|
+
const actual = await realpath(absolute).catch(() => { throw new WorkbenchError('not-found', 'path does not exist', 404) })
|
|
42
|
+
if (!inside(root, actual)) throw new WorkbenchError('path-outside', 'path follows a symlink outside the workspace', 403)
|
|
43
|
+
}
|
|
44
|
+
return { root, absolute }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function relativePath(root: string, absolute: string): string { return relative(root, absolute).split(sep).join('/') }
|
|
48
|
+
function revision(content: Buffer, mtimeMs: number): string {
|
|
49
|
+
return createHash('sha256').update(content).update(String(mtimeMs)).digest('hex')
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export async function listFiles(cwd: string, path: string): Promise<FileEntry[]> {
|
|
53
|
+
const { root, absolute } = await workspacePath(cwd, path)
|
|
54
|
+
const values = await readdir(absolute, { withFileTypes: true })
|
|
55
|
+
const rows = await Promise.all(values.filter(item => item.name !== '.git').map(async item => {
|
|
56
|
+
const full = join(absolute, item.name)
|
|
57
|
+
const info = await lstat(full)
|
|
58
|
+
const kind = item.isDirectory() ? 'directory' as const : 'file' as const
|
|
59
|
+
return { name: item.name, path: relativePath(root, full), kind, size: info.size, mtimeMs: info.mtimeMs }
|
|
60
|
+
}))
|
|
61
|
+
return rows.sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'directory' ? -1 : 1)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function readDocument(cwd: string, path: string): Promise<FileDocument> {
|
|
65
|
+
const { root, absolute } = await workspacePath(cwd, path)
|
|
66
|
+
const info = await stat(absolute)
|
|
67
|
+
if (!info.isFile()) throw new WorkbenchError('not-file', 'path is not a file')
|
|
68
|
+
const tooLarge = info.size > TEXT_LIMIT
|
|
69
|
+
const handle = await open(absolute, 'r')
|
|
70
|
+
try {
|
|
71
|
+
const head = Buffer.alloc(Math.min(info.size, tooLarge ? 4096 : TEXT_LIMIT))
|
|
72
|
+
const { bytesRead } = await handle.read(head, 0, head.length, 0)
|
|
73
|
+
const bytes = head.subarray(0, bytesRead)
|
|
74
|
+
const binary = bytes.includes(0)
|
|
75
|
+
return {
|
|
76
|
+
path: relativePath(root, absolute), content: binary || tooLarge ? '' : bytes.toString('utf8'),
|
|
77
|
+
revision: revision(bytes, info.mtimeMs), size: info.size, binary, tooLarge,
|
|
78
|
+
}
|
|
79
|
+
} finally { await handle.close() }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function saveDocument(cwd: string, path: string, content: string, expected: string): Promise<FileDocument> {
|
|
83
|
+
const { absolute } = await workspacePath(cwd, path)
|
|
84
|
+
const current = await readDocument(cwd, path)
|
|
85
|
+
if (current.revision !== expected) throw new WorkbenchError('revision-conflict', 'file changed on disk; reload before saving', 409)
|
|
86
|
+
const temp = join(dirname(absolute), `.${randomUUID()}.dsh-vscode.tmp`)
|
|
87
|
+
await writeFile(temp, content, { encoding: 'utf8', flag: 'wx' })
|
|
88
|
+
try { await rename(temp, absolute) } catch (error) { await rm(temp, { force: true }); throw error }
|
|
89
|
+
return readDocument(cwd, path)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function createEntry(cwd: string, path: string, kind: 'file' | 'directory'): Promise<void> {
|
|
93
|
+
const { absolute } = await workspacePath(cwd, path, true)
|
|
94
|
+
if (kind === 'directory') await mkdir(absolute)
|
|
95
|
+
else { const handle = await open(absolute, 'wx'); await handle.close() }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function renameEntry(cwd: string, path: string, nextPath: string): Promise<void> {
|
|
99
|
+
const source = await workspacePath(cwd, path)
|
|
100
|
+
const target = await workspacePath(cwd, nextPath, true)
|
|
101
|
+
await access(target.absolute, constants.F_OK).then(
|
|
102
|
+
() => { throw new WorkbenchError('target-exists', 'destination already exists', 409) }, () => undefined,
|
|
103
|
+
)
|
|
104
|
+
await rename(source.absolute, target.absolute)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export async function deleteEntry(cwd: string, path: string): Promise<void> {
|
|
108
|
+
if (path === '') throw new WorkbenchError('root-delete', 'cannot delete workspace root', 403)
|
|
109
|
+
const { absolute } = await workspacePath(cwd, path)
|
|
110
|
+
await rm(absolute, { recursive: true, force: false })
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const IMAGE_TYPES:Record<string,string>={'.avif':'image/avif','.bmp':'image/bmp','.gif':'image/gif','.ico':'image/x-icon','.jpeg':'image/jpeg','.jpg':'image/jpeg','.png':'image/png','.svg':'image/svg+xml','.webp':'image/webp'}
|
|
114
|
+
/** Resolve an image inside the workspace for protected browser preview. */
|
|
115
|
+
export async function workspaceImage(cwd:string,path:string):Promise<{path:string;type:string}>{const resolved=await workspacePath(cwd,path);const type=IMAGE_TYPES[extname(resolved.absolute).toLowerCase()];if(type===undefined)throw new WorkbenchError('unsupported-media','file is not a supported image',415);return {path:resolved.absolute,type}}
|
|
116
|
+
|
|
117
|
+
interface ProcessResult { stdout: string; stderr: string; code: number }
|
|
118
|
+
export function run(command: string, args: string[], cwd: string, timeout = PROCESS_TIMEOUT, signal?: AbortSignal): Promise<ProcessResult> {
|
|
119
|
+
return new Promise((resolvePromise, reject) => {
|
|
120
|
+
const child = spawn(command, args, { cwd, shell: false, windowsHide: true })
|
|
121
|
+
let stdout = ''; let stderr = ''; let settled = false
|
|
122
|
+
const timer = setTimeout(() => { child.kill(); if (!settled) reject(new WorkbenchError('timeout', `${command} timed out`, 504)) }, timeout)
|
|
123
|
+
const abort = () => { child.kill(); if (!settled) { settled = true; clearTimeout(timer); reject(new WorkbenchError('cancelled', `${command} cancelled`, 499)) } }
|
|
124
|
+
signal?.addEventListener('abort', abort, { once: true })
|
|
125
|
+
child.stdout.on('data', chunk => { stdout += String(chunk) })
|
|
126
|
+
child.stderr.on('data', chunk => { stderr += String(chunk) })
|
|
127
|
+
child.on('error', error => { clearTimeout(timer); signal?.removeEventListener('abort', abort); if (!settled) { settled = true; reject(error) } })
|
|
128
|
+
child.on('close', code => { clearTimeout(timer); signal?.removeEventListener('abort', abort); if (!settled) { settled = true; resolvePromise({ stdout, stderr, code: code ?? 1 }) } })
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export async function searchWorkspace(cwd: string, request: SearchRequest, signal?: AbortSignal): Promise<{ matches: SearchMatch[]; limited: boolean }> {
|
|
133
|
+
if (request.query === '') return { matches: [], limited: false }
|
|
134
|
+
const root = await canonicalRoot(cwd)
|
|
135
|
+
const rg = require('@vscode/ripgrep').rgPath as string
|
|
136
|
+
const args = ['--json', '--line-number', '--column', '--hidden', '--glob', '!.git/**', '--max-count', '2000']
|
|
137
|
+
if (!request.regex) args.push('--fixed-strings')
|
|
138
|
+
if (!request.caseSensitive) args.push('--ignore-case')
|
|
139
|
+
if (request.wholeWord) args.push('--word-regexp')
|
|
140
|
+
if (request.include) args.push('--glob', request.include)
|
|
141
|
+
if (request.exclude) args.push('--glob', `!${request.exclude}`)
|
|
142
|
+
args.push('--', request.query, '.')
|
|
143
|
+
const result = await run(rg, args, root, PROCESS_TIMEOUT, signal)
|
|
144
|
+
if (result.code > 1) throw new WorkbenchError('search-failed', result.stderr || 'ripgrep failed', 500)
|
|
145
|
+
const matches: SearchMatch[] = []
|
|
146
|
+
for (const line of result.stdout.split('\n')) {
|
|
147
|
+
if (line === '') continue
|
|
148
|
+
const event = JSON.parse(line) as { type: string; data?: { path?: { text?: string }; lines?: { text?: string }; line_number?: number; submatches?: Array<{ start: number; end: number; match?: { text?: string } }> } }
|
|
149
|
+
if (event.type !== 'match' || event.data?.path?.text === undefined || event.data.lines?.text === undefined) continue
|
|
150
|
+
for (const hit of event.data.submatches ?? []) {
|
|
151
|
+
matches.push({ path: event.data.path.text.replace(/^\.\//, ''), line: event.data.line_number ?? 1, column: hit.start + 1, preview: event.data.lines.text.trimEnd(), match: hit.match?.text ?? '' })
|
|
152
|
+
if (matches.length >= 2000) return { matches, limited: true }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return { matches, limited: false }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
async function gitRoot(cwd: string): Promise<string> {
|
|
159
|
+
const result = await run('git', ['rev-parse', '--show-toplevel'], cwd)
|
|
160
|
+
if (result.code !== 0) throw new WorkbenchError('not-repository', 'current workspace is not inside a Git repository', 404)
|
|
161
|
+
return result.stdout.trim()
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function validateCommitHash(value?: string): string {
|
|
165
|
+
if (!/^[0-9a-f]{7,64}$/i.test(value ?? '')) throw new WorkbenchError('bad-request', 'commit hash is invalid')
|
|
166
|
+
return value!
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function validateGitPath(repository: string, path?: string): string {
|
|
170
|
+
if (path === undefined || path === '' || isAbsolute(path) || !inside(repository, resolve(repository, path))) throw new WorkbenchError('bad-request', 'repository-relative path is required')
|
|
171
|
+
return path
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async function gitObject(repository: string, spec: string): Promise<string> {
|
|
175
|
+
const result = await run('git', ['show', '--no-textconv', spec], repository)
|
|
176
|
+
return result.code === 0 ? result.stdout : ''
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function commitFiles(repository: string, hash: string): Promise<GitCommitFile[]> {
|
|
180
|
+
const parent=await run('git',['rev-parse','--verify',`${hash}^1`],repository)
|
|
181
|
+
const result = parent.code===0
|
|
182
|
+
? await run('git',['diff','--name-status','-z','-M',parent.stdout.trim(),hash,'--'],repository)
|
|
183
|
+
: await run('git', ['diff-tree', '--root', '--no-commit-id', '--name-status', '-r', '-z', '-M', hash], repository)
|
|
184
|
+
if (result.code !== 0) throw new WorkbenchError('git-failed', result.stderr || result.stdout, 409)
|
|
185
|
+
const tokens = result.stdout.split('\0').filter(Boolean); const files: GitCommitFile[] = []
|
|
186
|
+
for (let index = 0; index < tokens.length;) {
|
|
187
|
+
const status = tokens[index++] ?? ''; const code = status[0] ?? ''
|
|
188
|
+
if (code === 'R' || code === 'C') { const previousPath=tokens[index++]??'';const path=tokens[index++]??'';files.push({path,previousPath,status:code}) }
|
|
189
|
+
else { const path=tokens[index++]??'';files.push({path,status:code}) }
|
|
190
|
+
}
|
|
191
|
+
return files
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export async function gitStatus(cwd: string): Promise<GitStatus> {
|
|
195
|
+
const repository = await gitRoot(cwd)
|
|
196
|
+
const result = await run('git', ['status', '--porcelain=v2', '-z', '--branch', '--untracked-files=all'], repository)
|
|
197
|
+
if (result.code !== 0) throw new WorkbenchError('git-failed', result.stderr, 500)
|
|
198
|
+
let branch = 'HEAD'; let ahead = 0; let behind = 0
|
|
199
|
+
const changes: GitChange[] = []
|
|
200
|
+
for (const record of result.stdout.split('\0')) {
|
|
201
|
+
if (record.startsWith('# branch.head ')) branch = record.slice(14)
|
|
202
|
+
else if (record.startsWith('# branch.ab ')) {
|
|
203
|
+
const match = /\+(\d+) -(\d+)/.exec(record); ahead = Number(match?.[1] ?? 0); behind = Number(match?.[2] ?? 0)
|
|
204
|
+
} else if (record.startsWith('? ')) changes.push({ path: record.slice(2), index: '?', worktree: '?', staged: false, untracked: true })
|
|
205
|
+
else if (record.startsWith('1 ') || record.startsWith('2 ')) {
|
|
206
|
+
const parts = record.split(' '); const xy = parts[1] ?? '..'; const path = parts.slice(record.startsWith('2 ') ? 9 : 8).join(' ')
|
|
207
|
+
changes.push({ path, index: xy[0] ?? '.', worktree: xy[1] ?? '.', staged: xy[0] !== '.', untracked: false })
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return { repository, branch, ahead, behind, changes }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export async function gitAction(cwd: string, action: string, path?: string, value?: string): Promise<unknown> {
|
|
214
|
+
const repository = await gitRoot(cwd)
|
|
215
|
+
let args: string[]
|
|
216
|
+
switch (action) {
|
|
217
|
+
case 'stage': args = ['add', '--', path ?? '']; break
|
|
218
|
+
case 'stage.all': args = ['add', '-A']; break
|
|
219
|
+
case 'unstage': args = ['restore', '--staged', '--', path ?? '']; break
|
|
220
|
+
case 'unstage.all': args = ['restore', '--staged', '--', '.']; break
|
|
221
|
+
case 'discard': {
|
|
222
|
+
args = value === 'untracked' ? ['clean', '-f', '--', path ?? ''] : ['restore', '--worktree', '--', path ?? '']
|
|
223
|
+
break
|
|
224
|
+
}
|
|
225
|
+
case 'discard.all': {
|
|
226
|
+
const head = await run('git', ['rev-parse', '--verify', 'HEAD'], repository)
|
|
227
|
+
if (head.code === 0) {
|
|
228
|
+
const restore = await run('git', ['restore', '--source=HEAD', '--staged', '--worktree', '--', '.'], repository)
|
|
229
|
+
if (restore.code !== 0) throw new WorkbenchError('git-failed', restore.stderr || restore.stdout, 409)
|
|
230
|
+
}
|
|
231
|
+
const clean = await run('git', ['clean', '-fd'], repository)
|
|
232
|
+
if (clean.code !== 0) throw new WorkbenchError('git-failed', clean.stderr || clean.stdout, 409)
|
|
233
|
+
return gitStatus(cwd)
|
|
234
|
+
}
|
|
235
|
+
case 'commit': args = ['commit', '-m', value ?? '']; break
|
|
236
|
+
case 'branch.create': args = ['switch', '-c', value ?? '']; break
|
|
237
|
+
case 'branch.switch': args = ['switch', value ?? '']; break
|
|
238
|
+
case 'branches': {
|
|
239
|
+
const result = await run('git', ['for-each-ref', '--format=%(refname:short)', 'refs/heads'], repository)
|
|
240
|
+
if (result.code !== 0) throw new WorkbenchError('git-failed', result.stderr, 500)
|
|
241
|
+
return result.stdout.split('\n').filter(Boolean)
|
|
242
|
+
}
|
|
243
|
+
case 'log': {
|
|
244
|
+
const head = await run('git', ['rev-parse', '--verify', 'HEAD'], repository)
|
|
245
|
+
if (head.code !== 0) return []
|
|
246
|
+
const result = await run('git', ['log', '--topo-order', '--date=iso-strict', '--decorate=short', '--pretty=format:%H%x1f%P%x1f%an%x1f%aI%x1f%s%x1f%D%x00', '-n', '100'], repository)
|
|
247
|
+
if (result.code !== 0) throw new WorkbenchError('git-failed', result.stderr || result.stdout, 500)
|
|
248
|
+
return result.stdout.split('\0').filter(Boolean).map((record): GitCommit => {
|
|
249
|
+
const [rawHash = '', parents = '', author = '', date = '', subject = '', refs = ''] = record.split('\x1f');const hash=rawHash.trim()
|
|
250
|
+
return { hash, parents: parents.split(' ').filter(Boolean), author, date, subject, refs: refs.split(',').map(item => item.trim()).filter(Boolean) }
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
case 'commit.show': {
|
|
254
|
+
const hash = validateCommitHash(value)
|
|
255
|
+
const result = await run('git', ['show', '--no-ext-diff', '--find-renames', '--format=fuller', '--stat', '--patch', '--no-color', hash], repository)
|
|
256
|
+
if (result.code !== 0) throw new WorkbenchError('git-failed', result.stderr || result.stdout, 409)
|
|
257
|
+
return { diff: result.stdout, original: '', modified: result.stdout } satisfies GitDiff
|
|
258
|
+
}
|
|
259
|
+
case 'commit.files': return commitFiles(repository, validateCommitHash(value))
|
|
260
|
+
case 'commit.file.diff': {
|
|
261
|
+
const hash=validateCommitHash(value);const target=validateGitPath(repository,path);const files=await commitFiles(repository,hash);const file=files.find(item=>item.path===target)
|
|
262
|
+
if (file===undefined) throw new WorkbenchError('not-found','file is not part of the commit',404)
|
|
263
|
+
const parent=await run('git',['rev-parse','--verify',`${hash}^1`],repository)
|
|
264
|
+
const shown=parent.code===0
|
|
265
|
+
? await run('git',['diff','--no-ext-diff','--find-renames','--patch','--no-color',parent.stdout.trim(),hash,'--',file.previousPath??target,target],repository)
|
|
266
|
+
: await run('git',['show','--no-ext-diff','--find-renames','--format=','--patch','--no-color',hash,'--',file.previousPath??target,target],repository)
|
|
267
|
+
if(shown.code!==0)throw new WorkbenchError('git-failed',shown.stderr||shown.stdout,409)
|
|
268
|
+
const original=file.status==='A'||parent.code!==0?'':await gitObject(repository,`${parent.stdout.trim()}:${file.previousPath??target}`)
|
|
269
|
+
const modified=file.status==='D'?'':await gitObject(repository,`${hash}:${target}`)
|
|
270
|
+
return {diff:shown.stdout,original,modified} satisfies GitDiff
|
|
271
|
+
}
|
|
272
|
+
case 'diff': {
|
|
273
|
+
const untracked = value === 'untracked'
|
|
274
|
+
const staged = value === 'staged'
|
|
275
|
+
args = untracked
|
|
276
|
+
? ['diff', '--no-index', '--', process.platform === 'win32' ? 'NUL' : '/dev/null', path ?? '']
|
|
277
|
+
: ['diff', ...(staged ? ['--cached'] : []), '--', path ?? '']
|
|
278
|
+
break
|
|
279
|
+
}
|
|
280
|
+
default: throw new WorkbenchError('bad-action', `unknown Git action ${action}`)
|
|
281
|
+
}
|
|
282
|
+
if (args.some(arg => arg === '') && action !== 'commit') throw new WorkbenchError('bad-request', 'path or value is required')
|
|
283
|
+
const result = await run('git', args, repository)
|
|
284
|
+
const expectedUntrackedDifference = action === 'diff' && value === 'untracked' && result.code === 1
|
|
285
|
+
if (result.code !== 0 && !expectedUntrackedDifference) throw new WorkbenchError('git-failed', result.stderr || result.stdout, 409)
|
|
286
|
+
if(action!=='diff')return gitStatus(cwd)
|
|
287
|
+
const target=validateGitPath(repository,path)
|
|
288
|
+
const original=value==='untracked'?'':await gitObject(repository,`${value==='staged'?'HEAD:':':'}${target}`)
|
|
289
|
+
const modified=value==='staged'?await gitObject(repository,`:${target}`):await readFile(resolve(repository,target),'utf8').catch(()=> '')
|
|
290
|
+
return {diff:result.stdout,original,modified} satisfies GitDiff
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Resolve the official VS Code Codicon font shipped by @vscode/codicons. */
|
|
294
|
+
export function codiconAsset(): { path: string; type: string } {
|
|
295
|
+
const packageRoot = dirname(require.resolve('@vscode/codicons/package.json'))
|
|
296
|
+
return { path: resolve(packageRoot, 'dist', 'codicon.ttf'), type: 'font/ttf' }
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export function monacoAsset(raw: string): { path: string; type: string } {
|
|
300
|
+
const packageRoot = dirname(require.resolve('monaco-editor/package.json'))
|
|
301
|
+
const path = resolve(packageRoot, 'min', raw)
|
|
302
|
+
const root = resolve(packageRoot, 'min')
|
|
303
|
+
if (!inside(root, path)) throw new WorkbenchError('asset-invalid', 'invalid Monaco asset path', 403)
|
|
304
|
+
const type = extname(path) === '.css' ? 'text/css' : extname(path) === '.js' ? 'text/javascript' : extname(path) === '.ttf' ? 'font/ttf' : 'application/octet-stream'
|
|
305
|
+
return { path, type }
|
|
306
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/** DSH host plugin for the VS Code workbench. */
|
|
2
|
+
import { readFile } from 'node:fs/promises'
|
|
3
|
+
import type { IncomingMessage } from 'node:http'
|
|
4
|
+
import type { Duplex } from 'node:stream'
|
|
5
|
+
import chokidar from 'chokidar'
|
|
6
|
+
import { WebSocket, WebSocketServer } from 'ws'
|
|
7
|
+
import type { HostContext } from './context.ts'
|
|
8
|
+
import { codiconAsset, createEntry, cwdFor, deleteEntry, gitAction, gitStatus, listFiles, monacoAsset, readDocument, renameEntry, saveDocument, searchWorkspace, workspaceImage } from './host.ts'
|
|
9
|
+
import type { SearchRequest } from './types.ts'
|
|
10
|
+
import { readBody, send, sendError, stringField, trusted, WorkbenchError } from './wire.ts'
|
|
11
|
+
|
|
12
|
+
export { WorkbenchError } from './wire.ts'
|
|
13
|
+
export * from './types.ts'
|
|
14
|
+
export const name = 'dsh-vscode-workbench'
|
|
15
|
+
export const inject = ['webServer', 'sessions', 'webRuntime']
|
|
16
|
+
|
|
17
|
+
async function dispatch(ctx: HostContext, method: string, body: Record<string, unknown>, signal?: AbortSignal): Promise<unknown> {
|
|
18
|
+
const sessionId = stringField(body, 'sessionId'); const cwd = cwdFor(ctx, sessionId)
|
|
19
|
+
switch (method) {
|
|
20
|
+
case 'workspace': return { cwd, name: cwd.split(/[\\/]/).at(-1) || cwd }
|
|
21
|
+
case 'fs.list': return listFiles(cwd, stringField(body, 'path'))
|
|
22
|
+
case 'fs.read': return readDocument(cwd, stringField(body, 'path'))
|
|
23
|
+
case 'fs.save': return saveDocument(cwd, stringField(body, 'path'), stringField(body, 'content'), stringField(body, 'revision'))
|
|
24
|
+
case 'fs.create': return createEntry(cwd, stringField(body, 'path'), body.kind === 'directory' ? 'directory' : 'file').then(() => ({ ok: true }))
|
|
25
|
+
case 'fs.rename': return renameEntry(cwd, stringField(body, 'path'), stringField(body, 'nextPath')).then(() => ({ ok: true }))
|
|
26
|
+
case 'fs.delete': return deleteEntry(cwd, stringField(body, 'path')).then(() => ({ ok: true }))
|
|
27
|
+
case 'search': return searchWorkspace(cwd, body as unknown as SearchRequest, signal)
|
|
28
|
+
case 'git.status': return gitStatus(cwd)
|
|
29
|
+
case 'git.action': return gitAction(cwd, stringField(body, 'action'), typeof body.path === 'string' ? body.path : undefined, typeof body.value === 'string' ? body.value : undefined)
|
|
30
|
+
default: throw new WorkbenchError('not-found', `unknown workbench API method ${method}`, 404)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function apply(ctx: HostContext): void {
|
|
35
|
+
ctx.effect(() => ctx.webServer.register({
|
|
36
|
+
kind: 'exact', path: '/dsh-vscode/codicons/codicon.ttf', handler: async (req, res) => {
|
|
37
|
+
if (!trusted(req, ctx.webRuntime.trustedHosts)) { res.writeHead(403); res.end(); return }
|
|
38
|
+
try {
|
|
39
|
+
const asset = codiconAsset()
|
|
40
|
+
res.writeHead(200, { 'content-type': asset.type, 'cache-control': 'public, max-age=31536000, immutable' })
|
|
41
|
+
res.end(await readFile(asset.path))
|
|
42
|
+
} catch (error) { sendError(res, error) }
|
|
43
|
+
},
|
|
44
|
+
}), 'dsh-vscode-workbench: Codicon font')
|
|
45
|
+
|
|
46
|
+
ctx.effect(() => ctx.webServer.register({
|
|
47
|
+
kind: 'prefix', path: '/dsh-vscode/api', handler: async (req, res) => {
|
|
48
|
+
if (!trusted(req, ctx.webRuntime.trustedHosts)) return send(res, 403, { ok: false, error: { code: 'forbidden', message: 'forbidden' } })
|
|
49
|
+
if (req.method !== 'POST') return send(res, 405, { ok: false, error: { code: 'method', message: 'POST required' } })
|
|
50
|
+
try {
|
|
51
|
+
const controller = new AbortController()
|
|
52
|
+
req.once('aborted', () => controller.abort())
|
|
53
|
+
const path = new URL(req.url ?? '/', 'http://dsh.local').pathname
|
|
54
|
+
const method = path.slice('/dsh-vscode/api/'.length)
|
|
55
|
+
send(res, 200, { ok: true, value: await dispatch(ctx, method, await readBody(req), controller.signal) })
|
|
56
|
+
} catch (error) { sendError(res, error) }
|
|
57
|
+
},
|
|
58
|
+
}), 'dsh-vscode-workbench: API')
|
|
59
|
+
|
|
60
|
+
ctx.effect(() => ctx.webServer.register({
|
|
61
|
+
kind:'prefix',path:'/dsh-vscode/file',handler:async(req,res)=>{if(!trusted(req,ctx.webRuntime.trustedHosts)){res.writeHead(403);res.end();return}try{const url=new URL(req.url??'/','http://dsh.local');const sessionId=url.searchParams.get('sessionId');const path=url.searchParams.get('path');if(sessionId===null||path===null)throw new WorkbenchError('bad-request','sessionId and path are required');const asset=await workspaceImage(cwdFor(ctx,sessionId),path);res.writeHead(200,{'content-type':asset.type,'x-content-type-options':'nosniff','cache-control':'no-store'});res.end(await readFile(asset.path))}catch(error){sendError(res,error)}}
|
|
62
|
+
}), 'dsh-vscode-workbench: image preview')
|
|
63
|
+
|
|
64
|
+
ctx.effect(() => ctx.webServer.register({
|
|
65
|
+
kind: 'prefix', path: '/dsh-vscode/monaco', handler: async (req, res) => {
|
|
66
|
+
if (!trusted(req, ctx.webRuntime.trustedHosts)) { res.writeHead(403); res.end(); return }
|
|
67
|
+
try {
|
|
68
|
+
const raw = decodeURIComponent(new URL(req.url ?? '/', 'http://dsh.local').pathname.slice('/dsh-vscode/monaco/'.length))
|
|
69
|
+
const asset = monacoAsset(raw)
|
|
70
|
+
res.writeHead(200, { 'content-type': asset.type, 'cache-control': 'public, max-age=31536000, immutable' })
|
|
71
|
+
res.end(await readFile(asset.path))
|
|
72
|
+
} catch (error) { sendError(res, error) }
|
|
73
|
+
},
|
|
74
|
+
}), 'dsh-vscode-workbench: Monaco assets')
|
|
75
|
+
|
|
76
|
+
const wss = new WebSocketServer({ noServer: true })
|
|
77
|
+
ctx.effect(() => ctx.webServer.registerUpgrade({
|
|
78
|
+
path: '/dsh-vscode/ws/files', handler(req, socket, head) {
|
|
79
|
+
if (!trusted(req as IncomingMessage, ctx.webRuntime.trustedHosts)) { socket.destroy(); return }
|
|
80
|
+
wss.handleUpgrade(req as IncomingMessage, socket as Duplex, head, (ws) => {
|
|
81
|
+
const sessionId = new URL(req.url ?? '/', 'http://dsh.local').searchParams.get('sessionId')
|
|
82
|
+
if (sessionId === null) { ws.close(1008, 'sessionId required'); return }
|
|
83
|
+
const watcher = chokidar.watch(cwdFor(ctx, sessionId), { ignoreInitial: true, ignored: /(^|[/\\])\.git([/\\]|$)/, awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 25 } })
|
|
84
|
+
let paths = new Set<string>(); let timer: ReturnType<typeof setTimeout> | undefined
|
|
85
|
+
watcher.on('all', (_event, path) => {
|
|
86
|
+
paths.add(path); clearTimeout(timer); timer = setTimeout(() => {
|
|
87
|
+
if (ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify({ type: 'files.changed', paths: [...paths] }))
|
|
88
|
+
paths = new Set()
|
|
89
|
+
}, 150)
|
|
90
|
+
})
|
|
91
|
+
ws.on('close', () => { clearTimeout(timer); void watcher.close() })
|
|
92
|
+
})
|
|
93
|
+
},
|
|
94
|
+
}), 'dsh-vscode-workbench: file watcher')
|
|
95
|
+
ctx.effect(() => () => { wss.close() }, 'dsh-vscode-workbench: watcher teardown')
|
|
96
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** One directory entry returned by the workbench host. */
|
|
2
|
+
export interface FileEntry { name: string; path: string; kind: 'file' | 'directory'; size: number; mtimeMs: number }
|
|
3
|
+
/** A text file together with its optimistic-concurrency revision. */
|
|
4
|
+
export interface FileDocument { path: string; content: string; revision: string; size: number; binary: boolean; tooLarge: boolean }
|
|
5
|
+
/** One ripgrep match. */
|
|
6
|
+
export interface SearchMatch { path: string; line: number; column: number; preview: string; match: string }
|
|
7
|
+
/** Search request flags. */
|
|
8
|
+
export interface SearchRequest { query: string; caseSensitive?: boolean; wholeWord?: boolean; regex?: boolean; include?: string; exclude?: string }
|
|
9
|
+
/** One working tree change. */
|
|
10
|
+
export interface GitChange { path: string; originalPath?: string; index: string; worktree: string; staged: boolean; untracked: boolean }
|
|
11
|
+
/** Local repository state. */
|
|
12
|
+
export interface GitStatus { repository: string; branch: string; ahead: number; behind: number; changes: GitChange[] }
|
|
13
|
+
/** One commit displayed by the source-control graph. */
|
|
14
|
+
export interface GitCommit { hash: string; parents: string[]; author: string; date: string; subject: string; refs: string[] }
|
|
15
|
+
/** One path changed by a local commit. */
|
|
16
|
+
export interface GitCommitFile { path: string; previousPath?: string; status: string }
|
|
17
|
+
/** Unified patch and full texts used by the Monaco diff editor. */
|
|
18
|
+
export interface GitDiff { diff: string; original: string; modified: string }
|
package/src/wire.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http'
|
|
2
|
+
|
|
3
|
+
export class WorkbenchError extends Error {
|
|
4
|
+
constructor(public code: string, message: string, public status = 400) { super(message) }
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export async function readBody(req: IncomingMessage): Promise<Record<string, unknown>> {
|
|
8
|
+
const chunks: Buffer[] = []
|
|
9
|
+
let size = 0
|
|
10
|
+
for await (const chunk of req) {
|
|
11
|
+
const value = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
|
|
12
|
+
size += value.length
|
|
13
|
+
if (size > 2 * 1024 * 1024) throw new WorkbenchError('too-large', 'request body is too large', 413)
|
|
14
|
+
chunks.push(value)
|
|
15
|
+
}
|
|
16
|
+
try {
|
|
17
|
+
const value: unknown = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}')
|
|
18
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('object expected')
|
|
19
|
+
return value as Record<string, unknown>
|
|
20
|
+
} catch { throw new WorkbenchError('bad-json', 'request body must be a JSON object') }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function stringField(body: Record<string, unknown>, key: string): string {
|
|
24
|
+
const value = body[key]
|
|
25
|
+
if (typeof value !== 'string') throw new WorkbenchError('bad-request', `${key} must be a string`)
|
|
26
|
+
return value
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function send(res: ServerResponse, status: number, value: unknown): void {
|
|
30
|
+
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
|
|
31
|
+
res.end(JSON.stringify(value))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function sendError(res: ServerResponse, error: unknown): void {
|
|
35
|
+
const known = error instanceof WorkbenchError ? error : new WorkbenchError('internal', error instanceof Error ? error.message : String(error), 500)
|
|
36
|
+
send(res, known.status, { ok: false, error: { code: known.code, message: known.message } })
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function trusted(req: IncomingMessage, allowed: readonly string[]): boolean {
|
|
40
|
+
const host = req.headers.host
|
|
41
|
+
if (host === undefined || req.headers['sec-fetch-site'] === 'cross-site') return false
|
|
42
|
+
let hostUrl: URL
|
|
43
|
+
try { hostUrl = new URL(`http://${host}`) } catch { return false }
|
|
44
|
+
const loopback = hostUrl.hostname === 'localhost' || hostUrl.hostname === '[::1]' || /^127(?:\.\d{1,3}){3}$/.test(hostUrl.hostname)
|
|
45
|
+
if (!loopback && !allowed.some(candidate => candidate === host || candidate === hostUrl.hostname)) return false
|
|
46
|
+
const origin = req.headers.origin
|
|
47
|
+
if (origin === undefined) return true
|
|
48
|
+
try { return new URL(origin).host === hostUrl.host } catch { return false }
|
|
49
|
+
}
|