dsh-linked-workspace 0.34.0 → 0.35.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/CHANGELOG.md +65 -0
- package/docs/API.md +19 -0
- package/docs/VERIFY.md +70 -0
- package/lib/client.js +460 -127
- package/lib/index.js +441 -6
- package/lib/office.js +118 -0
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -26,6 +26,7 @@ import { fileURLToPath } from 'node:url'
|
|
|
26
26
|
import { createRequire } from 'node:module'
|
|
27
27
|
import { forgetKnownHost, listHosts, listKnownHosts, RemoteHost, SshError, writeLocalCredential } from './ssh.js'
|
|
28
28
|
import { renderMarkdownFragment } from './markdown.js'
|
|
29
|
+
import { convertOfficeToPdf, sofficePath } from './office.js'
|
|
29
30
|
import * as linkedFs from './linked.js'
|
|
30
31
|
import * as git from './git.js'
|
|
31
32
|
|
|
@@ -41,7 +42,7 @@ export const inject = ['webServer', 'tools', 'systemPrompt', 'workingDirectory']
|
|
|
41
42
|
* is still running an older copy of the Host — refreshing the page only swaps
|
|
42
43
|
* the browser bundle, so the two halves can drift by one restart.
|
|
43
44
|
*/
|
|
44
|
-
const API_REVISION =
|
|
45
|
+
const API_REVISION = 18
|
|
45
46
|
|
|
46
47
|
/** When this copy of the Host was loaded; shown by `meta.info`. */
|
|
47
48
|
const STARTED_AT = new Date().toISOString()
|
|
@@ -171,6 +172,33 @@ const IMAGE_MIME = Object.freeze({
|
|
|
171
172
|
'.avif': 'image/avif',
|
|
172
173
|
'.svg': 'image/svg+xml',
|
|
173
174
|
})
|
|
175
|
+
// Types the read-only byte route may serve. Anything else falls back to
|
|
176
|
+
// application/octet-stream, which the browser downloads rather than renders.
|
|
177
|
+
const RAW_MIME = Object.freeze({
|
|
178
|
+
...IMAGE_MIME,
|
|
179
|
+
'.html': 'text/html; charset=utf-8',
|
|
180
|
+
'.htm': 'text/html; charset=utf-8',
|
|
181
|
+
'.css': 'text/css; charset=utf-8',
|
|
182
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
183
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
184
|
+
'.json': 'application/json; charset=utf-8',
|
|
185
|
+
'.jsonl': 'application/x-ndjson; charset=utf-8',
|
|
186
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
187
|
+
'.md': 'text/markdown; charset=utf-8',
|
|
188
|
+
'.markdown': 'text/markdown; charset=utf-8',
|
|
189
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
190
|
+
'.tsv': 'text/tab-separated-values; charset=utf-8',
|
|
191
|
+
'.pdf': 'application/pdf',
|
|
192
|
+
'.wasm': 'application/wasm',
|
|
193
|
+
'.woff': 'font/woff',
|
|
194
|
+
'.woff2': 'font/woff2',
|
|
195
|
+
'.ttf': 'font/ttf',
|
|
196
|
+
'.otf': 'font/otf',
|
|
197
|
+
})
|
|
198
|
+
const RAW_PREFIX = '/dsh-linked-workspace/fs'
|
|
199
|
+
const CACHE_PREFIX = '/dsh-linked-workspace/cache'
|
|
200
|
+
const RAW_CHUNK = 1024 * 1024
|
|
201
|
+
const RAW_CACHE_NAME = /^[0-9a-f]{40}\.pdf$/
|
|
174
202
|
const MAX_NAME_LENGTH = 120
|
|
175
203
|
const CONNECT_TIMEOUT_MS = 20_000
|
|
176
204
|
const OP_TIMEOUT_MS = 60_000
|
|
@@ -2660,8 +2688,14 @@ export function apply(ctx) {
|
|
|
2660
2688
|
const DOC_TOOL = join(dirname(fileURLToPath(import.meta.url)), '..', 'scripts', 'doc_tool.py')
|
|
2661
2689
|
const DOC_KIND_BY_EXT = new Map([
|
|
2662
2690
|
['.md', 'markdown'], ['.markdown', 'markdown'],
|
|
2663
|
-
['.pdf', 'pdf'],
|
|
2691
|
+
['.pdf', 'pdf'],
|
|
2692
|
+
['.doc', 'doc'], ['.docx', 'docx'], ['.odt', 'odt'],
|
|
2693
|
+
['.xls', 'xls'], ['.xlsx', 'xlsx'], ['.ods', 'ods'],
|
|
2694
|
+
['.ppt', 'ppt'], ['.pptx', 'pptx'], ['.odp', 'odp'],
|
|
2664
2695
|
])
|
|
2696
|
+
// Everything below is converted by LibreOffice before it is rendered, so the
|
|
2697
|
+
// panel never has to understand the binary format itself.
|
|
2698
|
+
const OFFICE_KINDS = new Set(['doc', 'docx', 'odt', 'xls', 'xlsx', 'ods', 'ppt', 'pptx', 'odp'])
|
|
2665
2699
|
|
|
2666
2700
|
function docKind(path) {
|
|
2667
2701
|
return DOC_KIND_BY_EXT.get(extname(String(path || '')).toLowerCase()) || ''
|
|
@@ -2837,12 +2871,97 @@ export function apply(ctx) {
|
|
|
2837
2871
|
|
|
2838
2872
|
function assertDocKind(path, expected) {
|
|
2839
2873
|
const kind = docKind(path)
|
|
2840
|
-
if (kind === '') throw new ApiError('DOC_UNSUPPORTED', '仅支持 Markdown、PDF、
|
|
2874
|
+
if (kind === '') throw new ApiError('DOC_UNSUPPORTED', '仅支持 Markdown、PDF 与 Office 文档(doc/docx/odt、xls/xlsx/ods、ppt/pptx/odp)')
|
|
2841
2875
|
if (expected && expected !== kind) throw new ApiError('DOC_UNSUPPORTED', '文件类型与请求不一致')
|
|
2842
2876
|
return kind
|
|
2843
2877
|
}
|
|
2844
2878
|
|
|
2845
|
-
|
|
2879
|
+
// Office previews: one PDF per (content) hash, kept next to the plugin data so a
|
|
2880
|
+
// second open of the same document renders instantly.
|
|
2881
|
+
const officePdfCache = new Map()
|
|
2882
|
+
|
|
2883
|
+
function officeRenderDir() {
|
|
2884
|
+
const directory = join(tmpdir(), 'dsh-linked-workspace-office')
|
|
2885
|
+
mkdirSync(directory, { recursive: true })
|
|
2886
|
+
return directory
|
|
2887
|
+
}
|
|
2888
|
+
|
|
2889
|
+
async function officePdfFor(bytes, ext) {
|
|
2890
|
+
const key = createHash('sha1').update(bytes).digest('hex')
|
|
2891
|
+
const known = officePdfCache.get(key)
|
|
2892
|
+
if (known && existsSync(known)) return known
|
|
2893
|
+
const file = join(officeRenderDir(), key + '.pdf')
|
|
2894
|
+
if (existsSync(file)) {
|
|
2895
|
+
officePdfCache.set(key, file)
|
|
2896
|
+
return file
|
|
2897
|
+
}
|
|
2898
|
+
const pending = officePdfPending.get(key)
|
|
2899
|
+
if (pending) return await pending
|
|
2900
|
+
const job = (async () => {
|
|
2901
|
+
const converted = await convertOfficeToPdf(bytes, ext)
|
|
2902
|
+
writeFileSync(file, converted.pdf)
|
|
2903
|
+
officePdfCache.set(key, file)
|
|
2904
|
+
if (officePdfCache.size > 12) {
|
|
2905
|
+
const oldest = officePdfCache.keys().next().value
|
|
2906
|
+
const oldestFile = officePdfCache.get(oldest)
|
|
2907
|
+
officePdfCache.delete(oldest)
|
|
2908
|
+
try { rmSync(oldestFile, { force: true }) } catch { /* best effort */ }
|
|
2909
|
+
}
|
|
2910
|
+
return file
|
|
2911
|
+
})()
|
|
2912
|
+
officePdfPending.set(key, job)
|
|
2913
|
+
try {
|
|
2914
|
+
return await job
|
|
2915
|
+
} finally {
|
|
2916
|
+
officePdfPending.delete(key)
|
|
2917
|
+
}
|
|
2918
|
+
}
|
|
2919
|
+
|
|
2920
|
+
const officePdfPending = new Map()
|
|
2921
|
+
|
|
2922
|
+
function rawUrlForRemote(scope, absolute) {
|
|
2923
|
+
const root = scope.root
|
|
2924
|
+
if (typeof absolute !== 'string' || !absolute.startsWith(root + '/')) return ''
|
|
2925
|
+
const relative = absolute.slice(root.length + 1).split('/').map((part) => encodeURIComponent(part)).join('/')
|
|
2926
|
+
return scope.kind === 'linked'
|
|
2927
|
+
? `${RAW_PREFIX}/linked/${encodeURIComponent(scope.id)}/remote/${relative}`
|
|
2928
|
+
: `${RAW_PREFIX}/remote/${encodeURIComponent(scope.id)}/${relative}`
|
|
2929
|
+
}
|
|
2930
|
+
|
|
2931
|
+
function rawUrlForLocal(absolute) {
|
|
2932
|
+
const encoded = absolute.split(/[\\/]+/).filter((part) => part !== '').map((part) => encodeURIComponent(part)).join('/')
|
|
2933
|
+
return `${RAW_PREFIX}/local/${encoded}`
|
|
2934
|
+
}
|
|
2935
|
+
|
|
2936
|
+
// A preview used to show broken images for every relative reference: the HTML is
|
|
2937
|
+
// injected into the host page, so "images/x.png" resolved against the app, not
|
|
2938
|
+
// against the document. Send them through the byte route instead.
|
|
2939
|
+
function rewriteRelativeImages(html, target) {
|
|
2940
|
+
if (typeof html !== 'string' || html.indexOf('<img') < 0) return html
|
|
2941
|
+
const baseDir = target.remote ? posix.dirname(target.path) : dirname(target.path)
|
|
2942
|
+
return html.replace(/(<img\b[^>]*?\bsrc=")([^"]*)(")/gi, (whole, before, src, after) => {
|
|
2943
|
+
if (src === '' || /^(?:[a-z][a-z0-9+.-]*:|\/\/|#)/i.test(src)) return whole
|
|
2944
|
+
let decoded = src
|
|
2945
|
+
try {
|
|
2946
|
+
decoded = decodeURIComponent(src)
|
|
2947
|
+
} catch {
|
|
2948
|
+
/* keep the raw value */
|
|
2949
|
+
}
|
|
2950
|
+
const suffix = decoded.search(/[?#]/)
|
|
2951
|
+
const clean = suffix < 0 ? decoded : decoded.slice(0, suffix)
|
|
2952
|
+
const tail = suffix < 0 ? '' : decoded.slice(suffix)
|
|
2953
|
+
if (clean === '') return whole
|
|
2954
|
+
if (target.remote) {
|
|
2955
|
+
const absolute = posix.resolve(baseDir, clean)
|
|
2956
|
+
const url = rawUrlForRemote(target.scope, absolute)
|
|
2957
|
+
return url === '' ? whole : before + url + tail + after
|
|
2958
|
+
}
|
|
2959
|
+
const absolute = resolve(baseDir, clean)
|
|
2960
|
+
return before + rawUrlForLocal(absolute) + tail + after
|
|
2961
|
+
})
|
|
2962
|
+
}
|
|
2963
|
+
|
|
2964
|
+
async function docStat(target) {
|
|
2846
2965
|
if (!target.remote) {
|
|
2847
2966
|
try { const info = await fsStat(target.path); return info } catch { return null }
|
|
2848
2967
|
}
|
|
@@ -3888,6 +4007,60 @@ const GREP_MAX_QUERY = 200
|
|
|
3888
4007
|
}
|
|
3889
4008
|
},
|
|
3890
4009
|
|
|
4010
|
+
/**
|
|
4011
|
+
* Render one page of a Word/Excel/PowerPoint document. The preview is
|
|
4012
|
+
* read-only on purpose: a converted PDF is the only way to keep the layout
|
|
4013
|
+
* intact, and it cannot be written back into the original file.
|
|
4014
|
+
*/
|
|
4015
|
+
async 'docs.officePage'(params = {}) {
|
|
4016
|
+
const target = await docTarget(params)
|
|
4017
|
+
const kind = assertDocKind(target.path)
|
|
4018
|
+
if (kind !== 'docx' && kind !== 'xlsx' && kind !== 'pptx') {
|
|
4019
|
+
throw new ApiError('BAD_REQUEST', '只有 Word、Excel 与 PowerPoint 需要这种渲染')
|
|
4020
|
+
}
|
|
4021
|
+
const page = Number(params.page)
|
|
4022
|
+
if (!Number.isInteger(page) || page < 0) throw new ApiError('BAD_REQUEST', '页码无效')
|
|
4023
|
+
const engine = sofficePath() === '' ? '' : 'libreoffice'
|
|
4024
|
+
if (engine === '') {
|
|
4025
|
+
throw new ApiError('NO_RENDERER', '这台机器上没有 LibreOffice,无法渲染 Office 文档')
|
|
4026
|
+
}
|
|
4027
|
+
const current = await readDocBytes(target, target)
|
|
4028
|
+
const pdf = await officePdfFor(current.data, kind)
|
|
4029
|
+
const rendered = await runDocTool(['read', '--kind', 'pdf', '--file', pdf, '--page', String(page)])
|
|
4030
|
+
return { kind, engine, path: target.path, mtime: current.mtime, ...rendered }
|
|
4031
|
+
},
|
|
4032
|
+
|
|
4033
|
+
/**
|
|
4034
|
+
* The Office preview used to arrive as one PNG per page. The converted PDF
|
|
4035
|
+
* is already cached by content hash, so give the browser its URL instead and
|
|
4036
|
+
* let the built-in viewer handle selection, search and zoom.
|
|
4037
|
+
*/
|
|
4038
|
+
async 'docs.officePdf'(params = {}) {
|
|
4039
|
+
const target = await docTarget(params)
|
|
4040
|
+
const kind = assertDocKind(target.path)
|
|
4041
|
+
if (!OFFICE_KINDS.has(kind)) throw new ApiError('BAD_REQUEST', '只有 Office 文档需要转换')
|
|
4042
|
+
if (sofficePath() === '') throw new ApiError('NO_RENDERER', '这台机器上没有 LibreOffice,无法渲染 Office 文档')
|
|
4043
|
+
const current = await readDocBytes(target, target)
|
|
4044
|
+
const pdf = await officePdfFor(current.data, kind)
|
|
4045
|
+
const hash = basename(pdf, '.pdf')
|
|
4046
|
+
let pageCount = 0
|
|
4047
|
+
try {
|
|
4048
|
+
const probe = await runDocTool(['read', '--kind', 'pdf', '--file', pdf, '--page', '0'])
|
|
4049
|
+
pageCount = Number(probe.pageCount) || 0
|
|
4050
|
+
} catch {
|
|
4051
|
+
pageCount = 0
|
|
4052
|
+
}
|
|
4053
|
+
return {
|
|
4054
|
+
kind,
|
|
4055
|
+
engine: 'libreoffice',
|
|
4056
|
+
path: target.path,
|
|
4057
|
+
mtime: current.mtime,
|
|
4058
|
+
size: current.size,
|
|
4059
|
+
pageCount,
|
|
4060
|
+
url: `${CACHE_PREFIX}/${hash}.pdf`,
|
|
4061
|
+
}
|
|
4062
|
+
},
|
|
4063
|
+
|
|
3891
4064
|
async 'docs.pdfPage'(params = {}) {
|
|
3892
4065
|
const target = await docTarget(params)
|
|
3893
4066
|
assertDocKind(target.path, 'pdf')
|
|
@@ -3977,14 +4150,17 @@ const GREP_MAX_QUERY = 200
|
|
|
3977
4150
|
}
|
|
3978
4151
|
// F2: keep the last few previews. The key is the text itself, because the
|
|
3979
4152
|
// caller may send unsaved text, in which case path + mtime would be stale.
|
|
3980
|
-
|
|
4153
|
+
// The path is part of the key: relative images are rewritten against the
|
|
4154
|
+
// document's own directory, so the same text in two folders renders
|
|
4155
|
+
// differently.
|
|
4156
|
+
const cacheKey = createHash('sha1').update(target.path + '\u0000' + text).digest('hex')
|
|
3981
4157
|
const cached = previewCache.get(cacheKey)
|
|
3982
4158
|
if (typeof cached === 'string') {
|
|
3983
4159
|
previewCache.delete(cacheKey)
|
|
3984
4160
|
previewCache.set(cacheKey, cached)
|
|
3985
4161
|
return { kind: 'markdown-preview', html: cached }
|
|
3986
4162
|
}
|
|
3987
|
-
const html = renderMarkdownFragment(text)
|
|
4163
|
+
const html = rewriteRelativeImages(renderMarkdownFragment(text), target)
|
|
3988
4164
|
previewCache.set(cacheKey, html)
|
|
3989
4165
|
while (previewCache.size > PREVIEW_CACHE_LIMIT) {
|
|
3990
4166
|
const oldest = previewCache.keys().next()
|
|
@@ -6279,6 +6455,265 @@ const GREP_MAX_QUERY = 200
|
|
|
6279
6455
|
'dsh-linked-workspace: katex assets',
|
|
6280
6456
|
)
|
|
6281
6457
|
|
|
6458
|
+
// ── read-only bytes ──────────────────────────────────────────────────────
|
|
6459
|
+
// The renderers (images, HTML, PDF, Office PDFs) point the browser at these
|
|
6460
|
+
// URLs instead of shipping base64 through the API: no 24 MB image ceiling, no
|
|
6461
|
+
// 33% base64 tax, and a relative <img>/<link> inside a previewed page resolves
|
|
6462
|
+
// because the URL mirrors the directory tree.
|
|
6463
|
+
function rawMimeOf(filePath) {
|
|
6464
|
+
return RAW_MIME[extname(String(filePath || '')).toLowerCase()] || 'application/octet-stream'
|
|
6465
|
+
}
|
|
6466
|
+
|
|
6467
|
+
function parseRawUrl(url) {
|
|
6468
|
+
const path = String(url || '').split('?')[0]
|
|
6469
|
+
if (!path.startsWith(RAW_PREFIX + '/')) return null
|
|
6470
|
+
let segments
|
|
6471
|
+
try {
|
|
6472
|
+
segments = path.slice(RAW_PREFIX.length + 1).split('/').map((part) => decodeURIComponent(part))
|
|
6473
|
+
} catch {
|
|
6474
|
+
return null
|
|
6475
|
+
}
|
|
6476
|
+
if (segments.some((part) => part === '' || part === '.' || part === '..' || part.includes('\\') || part.includes('\u0000'))) return null
|
|
6477
|
+
if (segments[0] === 'linked' && segments.length >= 4 && (segments[2] === 'remote' || segments[2] === 'local')) {
|
|
6478
|
+
return { kind: 'linked', id: segments[1], side: segments[2], relative: segments.slice(3).join('/') }
|
|
6479
|
+
}
|
|
6480
|
+
if (segments[0] === 'local' && segments.length >= 2) {
|
|
6481
|
+
// Windows drive letters arrive as their own segment ("local/D:/x/y"), so a
|
|
6482
|
+
// leading slash would turn into D:\D:\x; POSIX paths need it back.
|
|
6483
|
+
const rest = segments.slice(1)
|
|
6484
|
+
const drive = /^[A-Za-z]:$/.test(rest[0])
|
|
6485
|
+
return { kind: 'local', side: 'local', absolute: (drive ? '' : '/') + rest.join('/') }
|
|
6486
|
+
}
|
|
6487
|
+
if (segments[0] === 'remote' && segments.length >= 3) {
|
|
6488
|
+
return { kind: 'remote', id: segments[1], side: 'remote', relative: segments.slice(2).join('/') }
|
|
6489
|
+
}
|
|
6490
|
+
return null
|
|
6491
|
+
}
|
|
6492
|
+
|
|
6493
|
+
function parseRange(header, size) {
|
|
6494
|
+
if (typeof header !== 'string' || !header.startsWith('bytes=')) return null
|
|
6495
|
+
const spec = header.slice(6).split(',')[0].trim()
|
|
6496
|
+
const parts = spec.split('-')
|
|
6497
|
+
if (parts.length !== 2) return null
|
|
6498
|
+
let start = parts[0] === '' ? null : Number(parts[0])
|
|
6499
|
+
let end = parts[1] === '' ? null : Number(parts[1])
|
|
6500
|
+
if (start === null && end === null) return null
|
|
6501
|
+
if (start === null) {
|
|
6502
|
+
start = Math.max(0, size - end)
|
|
6503
|
+
end = size - 1
|
|
6504
|
+
} else if (end === null) {
|
|
6505
|
+
end = size - 1
|
|
6506
|
+
}
|
|
6507
|
+
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start > end || start >= size) return null
|
|
6508
|
+
return { start, end: Math.min(end, size - 1) }
|
|
6509
|
+
}
|
|
6510
|
+
|
|
6511
|
+
async function serveLocalFile(res, req, filePath, size, range) {
|
|
6512
|
+
const info = await fsStat(filePath)
|
|
6513
|
+
if (!info.isFile()) return false
|
|
6514
|
+
const fd = openSync(filePath, 'r')
|
|
6515
|
+
try {
|
|
6516
|
+
let offset = range ? range.start : 0
|
|
6517
|
+
const end = range ? range.end : info.size - 1
|
|
6518
|
+
while (offset <= end) {
|
|
6519
|
+
const want = Math.min(RAW_CHUNK, end - offset + 1)
|
|
6520
|
+
const buffer = Buffer.allocUnsafe(want)
|
|
6521
|
+
const read = readSync(fd, buffer, 0, want, offset)
|
|
6522
|
+
if (read <= 0) break
|
|
6523
|
+
offset += read
|
|
6524
|
+
if (!res.write(buffer.subarray(0, read))) await new Promise((resolve) => res.once('drain', resolve))
|
|
6525
|
+
}
|
|
6526
|
+
res.end()
|
|
6527
|
+
return true
|
|
6528
|
+
} finally {
|
|
6529
|
+
closeSync(fd)
|
|
6530
|
+
}
|
|
6531
|
+
}
|
|
6532
|
+
|
|
6533
|
+
async function serveRemoteFile(res, remote, target, size, range) {
|
|
6534
|
+
let offset = range ? range.start : 0
|
|
6535
|
+
const end = range ? range.end : size - 1
|
|
6536
|
+
while (offset <= end) {
|
|
6537
|
+
const want = Math.min(RAW_CHUNK, end - offset + 1)
|
|
6538
|
+
const read = await remote.readFile(target, { offset, maxBytes: want })
|
|
6539
|
+
const buffer = read && read.data ? read.data : Buffer.alloc(0)
|
|
6540
|
+
if (buffer.length === 0) break
|
|
6541
|
+
offset += buffer.length
|
|
6542
|
+
if (!res.write(buffer)) await new Promise((resolve) => res.once('drain', resolve))
|
|
6543
|
+
}
|
|
6544
|
+
res.end()
|
|
6545
|
+
}
|
|
6546
|
+
|
|
6547
|
+
async function rawFileHandler(req, res) {
|
|
6548
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
6549
|
+
res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6550
|
+
res.end('method not allowed')
|
|
6551
|
+
return
|
|
6552
|
+
}
|
|
6553
|
+
const parsed = parseRawUrl(req.url)
|
|
6554
|
+
if (!parsed) {
|
|
6555
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6556
|
+
res.end('not found')
|
|
6557
|
+
return
|
|
6558
|
+
}
|
|
6559
|
+
try {
|
|
6560
|
+
if (parsed.kind === 'local') {
|
|
6561
|
+
const absolute = resolve(parsed.absolute)
|
|
6562
|
+
const owner = linkedStore.list().find((record) => {
|
|
6563
|
+
const root = typeof record.localPath === 'string' ? resolve(record.localPath) : ''
|
|
6564
|
+
return root !== '' && (absolute === root || absolute.startsWith(root + sep))
|
|
6565
|
+
})
|
|
6566
|
+
if (!owner) throw new ApiError('BAD_REQUEST', '本地路径不在任何工作区里')
|
|
6567
|
+
const info = await fsStat(absolute)
|
|
6568
|
+
if (!info.isFile()) throw new ApiError('FS_NOT_DIR', '只能读取文件')
|
|
6569
|
+
const size = Number(info.size) || 0
|
|
6570
|
+
const mime = rawMimeOf(absolute)
|
|
6571
|
+
const range = parseRange(req.headers.range, size)
|
|
6572
|
+
const headers = {
|
|
6573
|
+
'content-type': mime,
|
|
6574
|
+
'content-length': String(range ? range.end - range.start + 1 : size),
|
|
6575
|
+
'accept-ranges': 'bytes',
|
|
6576
|
+
'cache-control': 'no-store',
|
|
6577
|
+
'x-content-type-options': 'nosniff',
|
|
6578
|
+
}
|
|
6579
|
+
if (mime === 'text/html; charset=utf-8' || mime === 'image/svg+xml') headers['content-security-policy'] = 'sandbox'
|
|
6580
|
+
if (range) headers['content-range'] = `bytes ${range.start}-${range.end}/${size}`
|
|
6581
|
+
res.writeHead(range ? 206 : 200, headers)
|
|
6582
|
+
if (req.method === 'HEAD' || size === 0) {
|
|
6583
|
+
res.end()
|
|
6584
|
+
return
|
|
6585
|
+
}
|
|
6586
|
+
await serveLocalFile(res, req, absolute, size, range)
|
|
6587
|
+
return
|
|
6588
|
+
}
|
|
6589
|
+
// The local half of a linked workspace lives on this machine: serve it
|
|
6590
|
+
// straight from disk. Resolving the scope first would dial the SSH host
|
|
6591
|
+
// and fail the whole local tree whenever that host is down.
|
|
6592
|
+
if (parsed.side === 'local') {
|
|
6593
|
+
if (parsed.kind !== 'linked') throw new ApiError('BAD_REQUEST', '这个工作区没有本地目录')
|
|
6594
|
+
const record = linkedStore.get(parsed.id)
|
|
6595
|
+
if (!record) throw new ApiError('NOT_FOUND', '联动工作区不存在')
|
|
6596
|
+
const root = resolve(record.localPath)
|
|
6597
|
+
const localTarget = resolve(root, parsed.relative)
|
|
6598
|
+
if (!isInsideLocal(root, localTarget)) throw new ApiError('BAD_REQUEST', '路径超出该工作区的本地目录')
|
|
6599
|
+
const localInfo = await fsStat(localTarget)
|
|
6600
|
+
if (!localInfo.isFile()) throw new ApiError('FS_NOT_DIR', '只能读取文件')
|
|
6601
|
+
const localSize = Number(localInfo.size) || 0
|
|
6602
|
+
const localMime = rawMimeOf(localTarget)
|
|
6603
|
+
const localRange = parseRange(req.headers.range, localSize)
|
|
6604
|
+
const localHeaders = {
|
|
6605
|
+
'content-type': localMime,
|
|
6606
|
+
'content-length': String(localRange ? localRange.end - localRange.start + 1 : localSize),
|
|
6607
|
+
'accept-ranges': 'bytes',
|
|
6608
|
+
'cache-control': 'no-store',
|
|
6609
|
+
'x-content-type-options': 'nosniff',
|
|
6610
|
+
}
|
|
6611
|
+
if (localMime === 'text/html; charset=utf-8' || localMime === 'image/svg+xml') localHeaders['content-security-policy'] = 'sandbox'
|
|
6612
|
+
if (localRange) localHeaders['content-range'] = `bytes ${localRange.start}-${localRange.end}/${localSize}`
|
|
6613
|
+
res.writeHead(localRange ? 206 : 200, localHeaders)
|
|
6614
|
+
if (req.method === 'HEAD' || localSize === 0) {
|
|
6615
|
+
res.end()
|
|
6616
|
+
return
|
|
6617
|
+
}
|
|
6618
|
+
await serveLocalFile(res, req, localTarget, localSize, localRange)
|
|
6619
|
+
return
|
|
6620
|
+
}
|
|
6621
|
+
const scope = await requireScope(parsed.kind === 'linked' ? { linkedId: parsed.id } : { remoteId: parsed.id })
|
|
6622
|
+
const target = scopeTarget(scope, parsed.relative)
|
|
6623
|
+
const stat = await scope.remote.stat(target)
|
|
6624
|
+
if (stat.type !== 'file') throw new ApiError('FS_NOT_DIR', '只能读取文件')
|
|
6625
|
+
const size = Number(stat.size) || 0
|
|
6626
|
+
const mime = rawMimeOf(target)
|
|
6627
|
+
const range = parseRange(req.headers.range, size)
|
|
6628
|
+
const headers = {
|
|
6629
|
+
'content-type': mime,
|
|
6630
|
+
'content-length': String(range ? range.end - range.start + 1 : size),
|
|
6631
|
+
'accept-ranges': 'bytes',
|
|
6632
|
+
'cache-control': 'no-store',
|
|
6633
|
+
'x-content-type-options': 'nosniff',
|
|
6634
|
+
}
|
|
6635
|
+
if (mime === 'text/html; charset=utf-8' || mime === 'image/svg+xml') headers['content-security-policy'] = 'sandbox'
|
|
6636
|
+
if (range) headers['content-range'] = `bytes ${range.start}-${range.end}/${size}`
|
|
6637
|
+
res.writeHead(range ? 206 : 200, headers)
|
|
6638
|
+
if (req.method === 'HEAD' || size === 0) {
|
|
6639
|
+
res.end()
|
|
6640
|
+
return
|
|
6641
|
+
}
|
|
6642
|
+
await serveRemoteFile(res, scope.remote, target, size, range)
|
|
6643
|
+
} catch (error) {
|
|
6644
|
+
const apiError = asApiError(error)
|
|
6645
|
+
if (!res.headersSent) {
|
|
6646
|
+
res.writeHead(apiError.status, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6647
|
+
res.end(apiError.message)
|
|
6648
|
+
} else {
|
|
6649
|
+
try { res.end() } catch { /* already gone */ }
|
|
6650
|
+
}
|
|
6651
|
+
}
|
|
6652
|
+
}
|
|
6653
|
+
|
|
6654
|
+
// Converted Office PDFs, addressed by the content hash officePdfFor already
|
|
6655
|
+
// uses: the browser's own PDF viewer then handles text selection and search.
|
|
6656
|
+
async function cachePdfHandler(req, res) {
|
|
6657
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
6658
|
+
res.writeHead(405, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6659
|
+
res.end('method not allowed')
|
|
6660
|
+
return
|
|
6661
|
+
}
|
|
6662
|
+
const path = String(req.url || '').split('?')[0]
|
|
6663
|
+
if (!path.startsWith(CACHE_PREFIX + '/')) {
|
|
6664
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6665
|
+
res.end('not found')
|
|
6666
|
+
return
|
|
6667
|
+
}
|
|
6668
|
+
const name = path.slice(CACHE_PREFIX.length + 1)
|
|
6669
|
+
if (!RAW_CACHE_NAME.test(name)) {
|
|
6670
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6671
|
+
res.end('not found')
|
|
6672
|
+
return
|
|
6673
|
+
}
|
|
6674
|
+
const file = join(officeRenderDir(), name)
|
|
6675
|
+
if (!existsSync(file)) {
|
|
6676
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
6677
|
+
res.end('expired')
|
|
6678
|
+
return
|
|
6679
|
+
}
|
|
6680
|
+
const info = await fsStat(file)
|
|
6681
|
+
const range = parseRange(req.headers.range, info.size)
|
|
6682
|
+
const headers = {
|
|
6683
|
+
'content-type': 'application/pdf',
|
|
6684
|
+
'content-length': String(range ? range.end - range.start + 1 : info.size),
|
|
6685
|
+
'accept-ranges': 'bytes',
|
|
6686
|
+
'cache-control': 'no-store',
|
|
6687
|
+
}
|
|
6688
|
+
if (range) headers['content-range'] = `bytes ${range.start}-${range.end}/${info.size}`
|
|
6689
|
+
res.writeHead(range ? 206 : 200, headers)
|
|
6690
|
+
if (req.method === 'HEAD') {
|
|
6691
|
+
res.end()
|
|
6692
|
+
return
|
|
6693
|
+
}
|
|
6694
|
+
await serveLocalFile(res, req, file, info.size, range)
|
|
6695
|
+
}
|
|
6696
|
+
|
|
6697
|
+
ctx.effect(
|
|
6698
|
+
() =>
|
|
6699
|
+
ctx.webServer.register({
|
|
6700
|
+
kind: 'prefix',
|
|
6701
|
+
path: RAW_PREFIX,
|
|
6702
|
+
handler: rawFileHandler,
|
|
6703
|
+
}),
|
|
6704
|
+
'dsh-linked-workspace: raw files',
|
|
6705
|
+
)
|
|
6706
|
+
|
|
6707
|
+
ctx.effect(
|
|
6708
|
+
() =>
|
|
6709
|
+
ctx.webServer.register({
|
|
6710
|
+
kind: 'prefix',
|
|
6711
|
+
path: CACHE_PREFIX,
|
|
6712
|
+
handler: cachePdfHandler,
|
|
6713
|
+
}),
|
|
6714
|
+
'dsh-linked-workspace: rendered pdf cache',
|
|
6715
|
+
)
|
|
6716
|
+
|
|
6282
6717
|
ctx.effect(
|
|
6283
6718
|
() => () => {
|
|
6284
6719
|
pool.disposeAll().catch(() => {})
|
package/lib/office.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Convert Office documents to PDF with a headless LibreOffice.
|
|
2
|
+
//
|
|
3
|
+
// Why a subprocess: the PDF is only a stepping stone — PyMuPDF renders its pages
|
|
4
|
+
// for the read-only preview, and a real office engine is the only way to keep
|
|
5
|
+
// Word/Excel/PowerPoint layout intact. LibreOffice is started per conversion
|
|
6
|
+
// with its own profile directory, because two instances sharing one profile
|
|
7
|
+
// block each other and the first one wins.
|
|
8
|
+
|
|
9
|
+
import { spawn } from 'node:child_process'
|
|
10
|
+
import { existsSync } from 'node:fs'
|
|
11
|
+
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
|
|
12
|
+
import { tmpdir } from 'node:os'
|
|
13
|
+
import { join } from 'node:path'
|
|
14
|
+
|
|
15
|
+
const WINDOWS_PATHS = [
|
|
16
|
+
'C:\\Program Files\\LibreOffice\\program\\soffice.exe',
|
|
17
|
+
'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe',
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
let cachedPath
|
|
21
|
+
|
|
22
|
+
/** The LibreOffice binary, or '' when this machine has none. */
|
|
23
|
+
export function sofficePath() {
|
|
24
|
+
if (cachedPath !== undefined) return cachedPath
|
|
25
|
+
const fromEnv = typeof process.env.DSH_LINKED_WORKSPACE_SOFFICE === 'string'
|
|
26
|
+
? process.env.DSH_LINKED_WORKSPACE_SOFFICE.trim()
|
|
27
|
+
: ''
|
|
28
|
+
if (fromEnv !== '' && existsSync(fromEnv)) {
|
|
29
|
+
cachedPath = fromEnv
|
|
30
|
+
return cachedPath
|
|
31
|
+
}
|
|
32
|
+
if (process.platform === 'win32') {
|
|
33
|
+
cachedPath = WINDOWS_PATHS.find((item) => existsSync(item)) || ''
|
|
34
|
+
return cachedPath
|
|
35
|
+
}
|
|
36
|
+
const names = process.platform === 'darwin'
|
|
37
|
+
? ['/Applications/LibreOffice.app/Contents/MacOS/soffice', '/usr/local/bin/soffice']
|
|
38
|
+
: ['/usr/bin/soffice', '/usr/local/bin/soffice', '/snap/bin/libreoffice']
|
|
39
|
+
cachedPath = names.find((item) => existsSync(item)) || ''
|
|
40
|
+
return cachedPath
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function run(command, args, timeoutMs) {
|
|
44
|
+
return new Promise((resolve, reject) => {
|
|
45
|
+
let child
|
|
46
|
+
try {
|
|
47
|
+
child = spawn(command, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
48
|
+
} catch (error) {
|
|
49
|
+
reject(error)
|
|
50
|
+
return
|
|
51
|
+
}
|
|
52
|
+
let stderr = ''
|
|
53
|
+
const timer = setTimeout(() => {
|
|
54
|
+
// LibreOffice ignores SIGTERM on Windows; the tree kill is the only way out.
|
|
55
|
+
try {
|
|
56
|
+
if (process.platform === 'win32') {
|
|
57
|
+
spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
|
|
58
|
+
} else {
|
|
59
|
+
child.kill('SIGKILL')
|
|
60
|
+
}
|
|
61
|
+
} catch (error) {
|
|
62
|
+
/* already gone */
|
|
63
|
+
}
|
|
64
|
+
reject(new Error(`soffice timed out after ${timeoutMs} ms`))
|
|
65
|
+
}, timeoutMs)
|
|
66
|
+
child.stderr.on('data', (chunk) => {
|
|
67
|
+
if (stderr.length < 4000) stderr += chunk.toString('utf8')
|
|
68
|
+
})
|
|
69
|
+
child.on('error', (error) => {
|
|
70
|
+
clearTimeout(timer)
|
|
71
|
+
reject(error)
|
|
72
|
+
})
|
|
73
|
+
child.on('close', (code) => {
|
|
74
|
+
clearTimeout(timer)
|
|
75
|
+
if (code === 0) resolve(stderr)
|
|
76
|
+
else reject(new Error(`soffice exited ${code}: ${stderr.trim().slice(-400)}`))
|
|
77
|
+
})
|
|
78
|
+
})
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Convert one Office document (given as bytes) to PDF.
|
|
83
|
+
* Returns { pdf: Buffer, engine: 'libreoffice' }; throws when nothing can render.
|
|
84
|
+
*/
|
|
85
|
+
export async function convertOfficeToPdf(bytes, ext, options = {}) {
|
|
86
|
+
const binary = sofficePath()
|
|
87
|
+
if (binary === '') {
|
|
88
|
+
const error = new Error('这台机器上没有 LibreOffice,无法渲染 Office 文档')
|
|
89
|
+
error.code = 'NO_RENDERER'
|
|
90
|
+
throw error
|
|
91
|
+
}
|
|
92
|
+
const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : 120_000
|
|
93
|
+
const work = await mkdtemp(join(tmpdir(), 'dsh-office-'))
|
|
94
|
+
try {
|
|
95
|
+
const source = join(work, `source.${ext}`)
|
|
96
|
+
const profile = join(work, 'profile')
|
|
97
|
+
await writeFile(source, bytes)
|
|
98
|
+
await run(binary, [
|
|
99
|
+
`-env:UserInstallation=file:///${profile.replace(/\\/g, '/')}`,
|
|
100
|
+
'--headless',
|
|
101
|
+
'--norestore',
|
|
102
|
+
'--nologo',
|
|
103
|
+
'--nolockcheck',
|
|
104
|
+
'--nodefault',
|
|
105
|
+
'--convert-to',
|
|
106
|
+
'pdf',
|
|
107
|
+
'--outdir',
|
|
108
|
+
work,
|
|
109
|
+
source,
|
|
110
|
+
], timeoutMs)
|
|
111
|
+
const pdfPath = join(work, 'source.pdf')
|
|
112
|
+
if (!existsSync(pdfPath)) throw new Error('LibreOffice 没有产出 PDF')
|
|
113
|
+
const pdf = await readFile(pdfPath)
|
|
114
|
+
return { pdf, engine: 'libreoffice' }
|
|
115
|
+
} finally {
|
|
116
|
+
await rm(work, { recursive: true, force: true }).catch(() => {})
|
|
117
|
+
}
|
|
118
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-linked-workspace",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.35.0",
|
|
4
4
|
"description": "Linked local ⇄ remote workspaces and remote workspaces for DeepSeek Harness: theme-aware split editor, file-type icons, and agent tools that edit remote files directly.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|