贡献者 PR #584(fix: preserve reverse-proxy base paths,head 1ca99d8)的改动面在 dev 上仍然需要——JSON API / upload / file / html / bundle 与两条 WebSocket 都还是 源站绝对路径(带前导斜杠 → 反代子路径下 404 / 1006),目标 issue #753 仍 OPEN, docs/plans/2026-10-04-issue-triage.md 也把 #584 记为优先合入项。但它不能机械解冲突, 故按 dev 现有结构重写。 复用(PR 的可复用部分): - 新增 src/client/host-route-url.ts:hostRouteUrl() / hostWebSocketUrl() 先去前导 斜杠,再按注入基底解析;基底去 search/hash 并强制目录尾斜杠——launch token 查询串 与「缺尾斜杠的前缀」都不会吃掉路径最后一段。 改写(dev 侧已经变掉的东西): - 基底来源并进 dev 的 2718725:desktop-env.ts 的 sidebarWebSocketBase() 泛化为 hostTransportBase()(__DSH_TRANSPORT__.streamBaseUrl 优先,回落 document.baseURI), HTTP 与 WS 从此共用一个基底权威,而不是另起一套。丢弃 PR 的 hostDocumentBase() 「取 document.baseURI 与 location.href 中更长者」启发式:它会顶掉刚落地的桌面壳修复 (dsh-app://app/ 下 location.href 会重新拼出不可达的 ws://app/…),而基线 0.2.0-rc.1 的宿主产物里没有 <base href>(PR 自己的 e2e 也只采集、从不断言它)。 最终解析式与宿主 dsh-api-gateway 逐字同形(去前导斜杠 + 壳注入基底优先)。 - 丢弃 src/client/TerminalView.tsx 的改动:该文件在 dev 已删除(终端已交还宿主), 其覆盖的 WS 语义改由 dev 现存的两条调用点承担,并补齐 PR 文件清单里漏掉的 src/client/use-dir-watch.ts(fs-watch socket)。 调用点(一律相对路径 + 前缀解析):api.ts 的 JSON API / upload / file / html / archive、chunk-loader.ts 的 CHUNK_URL、markdown-images.ts 与 MarkdownHtml / TextEditor / DiffPane 的媒体改写(原 window.location.origin 在桌面壳下是 dsh-app://app,媒体同样不可达)、use-host-feeds.ts 与 use-dir-watch.ts 的两条 WebSocket。archiveDownloadUrl 是 PR 漏掉的同类调用点(FileTree 用它 fetch zip 字节), 一并纳入;open-in-app.ts 打的是宿主路由 /open-in-app/*,与 PR 明确不碰的宿主 /api 同类,不纳入。 消费插件契约(指南「接入 API 即文档」): - BetterSidebarService 新增 hostRouteUrl(path)(features 'hostRouteUrl'), docs/external-plugin-guide.md §6 / §7 / §15 的 fetch('/sidebar/api/…') 示例改为 经它解析,并写明「绝不写前导斜杠」。 验证:pnpm typecheck / pnpm exec vitest run(161 files / 1812 passed / 13 skipped)/ eslint 全绿。tests/base-path.spec.ts 钉前缀保留与基底优先级,并在真实调用点上断言 (api fetch 的 URL、chunk 注入的 script src、jsdom 下 fs-watch 的 socket URL); PR 自带的 base-path e2e 在 page.evaluate 里复制实现后自证,回归守不住,故不引入该 lane。 Refs #584 Co-authored-by: idoall <6040958+idoall@users.noreply.github.com>
141 lines
6.9 KiB
TypeScript
141 lines
6.9 KiB
TypeScript
/**
|
|
* Markdown-preview local-image resolution. The shared `MarkdownText` (from
|
|
* @deepseek-ai/dsh-client-ui-primitives) only renders absolute http(s) image
|
|
* URLs — relative links are disabled for chat security — so a local image in
|
|
* a previewed `.md` (``, an absolute `/cwd/img.png`, or a
|
|
* reference definition) would otherwise fall back to its alt text. This
|
|
* dependency-free helper rewrites those destinations into absolute
|
|
* `/sidebar/file` media URLs, resolved against the injected transport base so
|
|
* a reverse-proxy prefix survives; `MarkdownText` accepts them because they are
|
|
* absolute http(s), and the host media route then serves the bytes.
|
|
*/
|
|
|
|
import type { SessionScope } from './api.ts'
|
|
import { hostRouteUrl } from './host-route-url.ts'
|
|
import { isAbsolutePath } from './paths.ts'
|
|
|
|
/**
|
|
* True for a destination that is a remote URL — an absolute `scheme:` URL
|
|
* that is not a Windows drive path (`C:\...`). http/https/data/mailto etc.
|
|
* all match here and are handed back to `MarkdownText` untouched.
|
|
*/
|
|
function isRemoteUrl(dest: string): boolean {
|
|
return /^[a-z][a-z0-9+.-]*:/i.test(dest) && !/^[A-Za-z]:[\\/]/.test(dest)
|
|
}
|
|
|
|
/**
|
|
* Collapse `.`/`..` segments of an absolute local path, preserving its root
|
|
* (POSIX `/`), its Windows drive (`C:\`), or its UNC `\\server\share`
|
|
* prefix. The host's `requireAbsolute` (`path.resolve`) normalizes anyway,
|
|
* but producing a canonical path here keeps the `/sidebar/file` URL clean.
|
|
*/
|
|
function normalizeLocalPath(path: string): string {
|
|
const drive = /^([A-Za-z]:)[\\/]/.exec(path)?.[1]
|
|
const body = drive !== undefined ? path.slice(drive.length) : path
|
|
const parts = body.split(/[\\/]+/).filter((segment) => segment !== '' && segment !== '.')
|
|
const out: string[] = []
|
|
for (const part of parts) {
|
|
if (part === '..') { out.pop(); continue }
|
|
out.push(part)
|
|
}
|
|
if (drive !== undefined) return `${drive}\\${out.join('\\')}`
|
|
const separator = path.startsWith('\\') ? '\\' : '/'
|
|
const root = path.startsWith('/') ? '/' : path.startsWith('\\') ? '\\\\' : ''
|
|
return `${root}${out.join(separator)}`
|
|
}
|
|
|
|
/**
|
|
* Rewrite markdown image destinations that point at local files into
|
|
* absolute `/sidebar/file` media URLs. Relative destinations resolve against
|
|
* the opened file's directory (normalizing `.`/`..` segments); absolute
|
|
* local paths pass through. Remote (http/https/data/mailto) and `#`-anchor
|
|
* destinations are left untouched for `MarkdownText`. Reference-style images
|
|
* (`![x][id]` + `[id]: url`) are covered by rewriting their definition lines.
|
|
*
|
|
* Code spans (`` `...` ``) and fenced code blocks (``` ```...``` ```) are
|
|
* masked before rewriting so documentation that demonstrates ``
|
|
* is not mutated into a `/sidebar/file` URL. Reference definitions are only
|
|
* rewritten when their label is actually referenced by an image (collapsed
|
|
* `[![][id]]`, full `![alt][id]`, or shortcut `![]` referencing the next
|
|
* definition) — a plain link `[text][id]` must not have its destination
|
|
* redirected to the media route.
|
|
* @param text - The raw markdown source (inline + reference images).
|
|
* @param scope - The session scope (sessionId + cwd) for the media route.
|
|
* @param filePath - The absolute path of the opened `.md` file.
|
|
* @param baseUrl - The injected transport base (`hostTransportBase()` in the
|
|
* renderers); injected so the core rewrite stays pure and unit-testable.
|
|
* @returns The markdown with local image destinations rewritten in place.
|
|
*/
|
|
/**
|
|
* Resolve one media destination against the session's media route: local
|
|
* (relative or absolute) paths become absolute `/sidebar/file` URLs, resolved
|
|
* through `baseUrl` so the shared MarkdownText http(s) allowlist accepts them
|
|
* AND a reverse-proxy prefix is preserved, while remote URLs, `#`-anchors and
|
|
* empty destinations are returned untouched. Shared by the markdown image rewriter below and by the
|
|
* preview's raw-HTML sanitizer (`markdown-html.tsx`, which meets the same
|
|
* allowlist when rendering `<img src="./x.png">` inside HTML blocks).
|
|
*/
|
|
export function resolveLocalMediaDest(
|
|
dest: string,
|
|
scope: SessionScope,
|
|
filePath: string,
|
|
baseUrl: string,
|
|
): string {
|
|
const trimmed = dest.trim()
|
|
if (trimmed === '' || trimmed.startsWith('#')) return dest
|
|
if (isRemoteUrl(trimmed)) return dest
|
|
const slash = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'))
|
|
const directory = slash === -1 ? '/' : filePath.slice(0, slash + 1)
|
|
const candidate = isAbsolutePath(trimmed) ? trimmed : directory + trimmed
|
|
// Mirrors api.ts fileUrl/mediaUrl for the /sidebar/file media route, made
|
|
// absolute (and prefix-preserving) so the shared MarkdownText http(s)
|
|
// allowlist accepts it.
|
|
const params = new URLSearchParams({ sessionId: scope.sessionId, path: normalizeLocalPath(candidate) })
|
|
if (scope.cwd !== undefined && scope.cwd !== '') params.set('cwd', scope.cwd)
|
|
return hostRouteUrl(`sidebar/file?${params.toString()}`, baseUrl).href
|
|
}
|
|
|
|
export function rewriteLocalImageUrls(
|
|
text: string,
|
|
scope: SessionScope,
|
|
filePath: string,
|
|
baseUrl: string,
|
|
): string {
|
|
const resolve = (dest: string): string => resolveLocalMediaDest(dest, scope, filePath, baseUrl)
|
|
|
|
// Mask fenced code blocks and inline code spans so image-looking text
|
|
// inside documentation examples is never rewritten. The sentinel uses a
|
|
// character unlikely to appear in prose; the original spans are restored
|
|
// after the image rewrite.
|
|
const masks: string[] = []
|
|
const masked = text
|
|
.replace(/```[\s\S]*?```/g, (block) => { masks.push(block); return `\u0000${masks.length - 1}\u0000` })
|
|
.replace(/`[^`\n]*`/g, (span) => { masks.push(span); return `\u0000${masks.length - 1}\u0000` })
|
|
|
|
const inline = masked.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g, (_match, alt, dest) => {
|
|
return `})`
|
|
})
|
|
|
|
// Collect labels referenced by image syntax (full `![alt][id]` and
|
|
// collapsed `![][id]`) so only those reference definitions are rewritten.
|
|
// A shortcut reference (`![alt]` with no `[id]`) resolves to the label
|
|
// text `alt` itself; include it too. Plain links `[text][id]` never match
|
|
// the leading `!` and are left untouched.
|
|
const imageLabels = new Set<string>()
|
|
const labelRe = /!\[([^\]]*)\](?:\[((?:[^\][]|\[[^\]]*\])*)\])?/g
|
|
let labelMatch: RegExpExecArray | null
|
|
while ((labelMatch = labelRe.exec(inline)) !== null) {
|
|
const alt = labelMatch[1] ?? ''
|
|
const ref = labelMatch[2]
|
|
imageLabels.add(ref !== undefined && ref !== '' ? ref.toLowerCase() : alt.toLowerCase())
|
|
}
|
|
|
|
const refsRewritten = inline.replace(/^(\s*\[([^\]]+)\]:\s*)(<[^>]+>|[^\s]+)/gm, (match, head: string, label: string, dest: string) => {
|
|
if (!imageLabels.has(label.toLowerCase())) return match
|
|
return `${head}${resolve(dest.replace(/^<|>$/g, ''))}`
|
|
})
|
|
|
|
// eslint-disable-next-line no-control-regex -- NUL is the deliberate mask sentinel (cannot appear in source markdown)
|
|
return refsRewritten.replace(/\u0000(\d+)\u0000/g, (_m, index: string) => masks[Number(index)] ?? '')
|
|
}
|