贡献者 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>
371 lines
15 KiB
TypeScript
371 lines
15 KiB
TypeScript
/**
|
|
* MarkdownDocument spec: the split-document renderer — sanitized HTML leaves
|
|
* (denylist + anchor hardening + local media rewrite), `<details>` nesting of
|
|
* in-between markdown, cross-segment reference definitions, and the inline
|
|
* pass that turns tag text inside rendered markdown back into elements.
|
|
* Renders with the real shared MarkdownText in jsdom (same pattern as
|
|
* tests/mermaid-markdown.spec.tsx).
|
|
*/
|
|
// @vitest-environment jsdom
|
|
import { describe, expect, it, beforeEach } from 'vitest'
|
|
import { createElement } from 'react'
|
|
import { createRoot, type Root } from 'react-dom/client'
|
|
import { act } from 'react-dom/test-utils'
|
|
import { MarkdownDocument, type MarkdownHtmlMedia } from '../src/client/MarkdownHtml.tsx'
|
|
import { analyzeMarkdownHtml } from '../src/client/markdown-html.ts'
|
|
|
|
// The act() environment flag (React 18.2 reads it before flushing effects).
|
|
import { setupReactAct } from './test-utils.ts'
|
|
setupReactAct()
|
|
|
|
const media: MarkdownHtmlMedia = {
|
|
scope: { sessionId: 's1', cwd: '/ws' },
|
|
path: '/ws/docs/README.md',
|
|
baseUrl: 'http://gui.origin/proxy/3080/',
|
|
}
|
|
const codeLabels = {
|
|
copyLabel: 'Copy', copiedLabel: 'Copied', codeLabel: 'Code block', wrapLabel: 'Wrap lines', unwrapLabel: 'Do not wrap lines',
|
|
}
|
|
|
|
async function renderDocument(text: string): Promise<{ container: HTMLElement; root: Root }> {
|
|
const container = document.createElement('div')
|
|
document.body.appendChild(container)
|
|
const root = createRoot(container)
|
|
await act(async () => {
|
|
root.render(createElement(MarkdownDocument, {
|
|
info: analyzeMarkdownHtml(text),
|
|
media,
|
|
codeLabels,
|
|
}))
|
|
// Let the MutationObserver's queued inline pass settle inside the act scope.
|
|
await new Promise((resolve) => { setTimeout(resolve, 0) })
|
|
})
|
|
return { container, root }
|
|
}
|
|
|
|
async function unmount(root: Root): Promise<void> {
|
|
await act(async () => { root.unmount() })
|
|
}
|
|
|
|
beforeEach(() => {
|
|
document.body.innerHTML = ''
|
|
})
|
|
|
|
describe('MarkdownDocument (HTML leaves)', () => {
|
|
it('renders a balanced HTML block as sanitized DOM, not literal text', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'# Title',
|
|
'',
|
|
'<div align="center">',
|
|
' <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />',
|
|
'</div>',
|
|
].join('\n'))
|
|
const leaf = container.querySelector('[data-dsh-html-segment]')
|
|
expect(leaf, 'the html run must render as a sanitized leaf').not.toBeNull()
|
|
expect(leaf?.querySelector('img[src*="img.shields.io"]')).not.toBeNull()
|
|
expect(leaf?.firstElementChild?.getAttribute('align')).toBe('center')
|
|
expect(container.textContent).not.toContain('<div')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('strips denied tags and hardens anchors', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<div>',
|
|
' <script>alert(1)</script>',
|
|
' <a href="https://example.com">link</a>',
|
|
'</div>',
|
|
].join('\n'))
|
|
expect(container.querySelector('script')).toBeNull()
|
|
const anchor = container.querySelector('a[href="https://example.com"]')
|
|
expect(anchor).not.toBeNull()
|
|
expect(anchor?.getAttribute('target')).toBe('_blank')
|
|
expect(anchor?.getAttribute('rel')).toBe('noopener noreferrer')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('rewrites local media sources through the /sidebar/file route', async () => {
|
|
const { container, root } = await renderDocument('<picture><img src="./shot.png" alt="shot"/></picture>')
|
|
const img = container.querySelector('img')
|
|
expect(img?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fshot.png&cwd=%2Fws')
|
|
await unmount(root)
|
|
})
|
|
})
|
|
|
|
describe('MarkdownDocument (nesting + markdown runs)', () => {
|
|
it('nests markdown runs inside an unclosed <details> element', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<details>',
|
|
'<summary><b>更新</b></summary>',
|
|
'',
|
|
'```sh',
|
|
'dsh plugin --profile web add x',
|
|
'```',
|
|
'',
|
|
'</details>',
|
|
'',
|
|
'after the fold',
|
|
].join('\n'))
|
|
const details = container.querySelector('details')
|
|
expect(details, 'the open part must lower following runs into a details element').not.toBeNull()
|
|
// Direct child, not just a descendant: HTML only treats a summary as the
|
|
// disclosure widget in that position (a nested one gets the UA's own
|
|
// "Details" label and the authored text drops into the body).
|
|
const summary = details?.querySelector(':scope > summary')
|
|
expect(summary, 'the summary must be a direct child of <details>').not.toBeNull()
|
|
expect(summary?.textContent).toBe('更新')
|
|
expect(summary?.querySelector('b'), 'inline markup inside the summary must survive').not.toBeNull()
|
|
expect(details?.textContent).toContain('dsh plugin --profile web add x')
|
|
// The close part pops the frame: the trailing markdown is a sibling.
|
|
expect(details?.textContent).not.toContain('after the fold')
|
|
expect(container.querySelector('details')?.nextElementSibling?.textContent).toContain('after the fold')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('keeps the authored summary label and the markdown run inside <details>', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<details>',
|
|
'<summary>Implementation internals — click to expand</summary>',
|
|
'',
|
|
'The bundle is a static patch document.',
|
|
'',
|
|
'</details>',
|
|
'',
|
|
'outside the fold',
|
|
].join('\n'))
|
|
const details = container.querySelector('details')
|
|
const summary = details?.querySelector(':scope > summary')
|
|
expect(summary?.textContent).toBe('Implementation internals — click to expand')
|
|
// The leaf wrapper must not sit between the details and its summary.
|
|
expect(details?.firstElementChild?.tagName).toBe('SUMMARY')
|
|
expect(details?.querySelector('[data-dsh-html-segment]'), 'no leaf wrapper around the summary').toBeNull()
|
|
const paragraph = [...(details?.querySelectorAll('p') ?? [])]
|
|
.find((node) => node.textContent?.includes('The bundle is a static patch document.'))
|
|
expect(paragraph, 'the following markdown run must stay inside the details').not.toBeUndefined()
|
|
expect(details?.textContent).not.toContain('outside the fold')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('never injects a hardcoded disclosure label', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<details>',
|
|
'<summary>Folded details</summary>',
|
|
'',
|
|
'body',
|
|
'',
|
|
'</details>',
|
|
].join('\n'))
|
|
expect(container.textContent).not.toContain('Details')
|
|
expect(container.textContent).not.toContain('详情')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('keeps a summary leaf inside a non-details wrapper', async () => {
|
|
// The hoist is details-specific: a balanced run that merely starts with a
|
|
// summary (no <details> frame open) must still take the plain leaf path.
|
|
const { container, root } = await renderDocument([
|
|
'<div>',
|
|
'<summary>not a disclosure widget here</summary>',
|
|
'</div>',
|
|
].join('\n'))
|
|
const leaf = container.querySelector('[data-dsh-html-segment]')
|
|
expect(leaf, 'the run must stay a sanitized leaf').not.toBeNull()
|
|
expect(leaf?.querySelector('summary')).not.toBeNull()
|
|
expect(container.querySelector('details')).toBeNull()
|
|
await unmount(root)
|
|
})
|
|
|
|
it('keeps trailing leaf content after a hoisted summary', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<details><summary>label</summary>',
|
|
'trailing html line',
|
|
].join('\n'))
|
|
const details = container.querySelector('details')
|
|
expect(details?.querySelector(':scope > summary')?.textContent).toBe('label')
|
|
expect(details?.textContent).toContain('trailing html line')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('keeps reference definitions resolving across lifted HTML runs', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'see [the docs][shared]',
|
|
'',
|
|
'<div align="center">badges</div>',
|
|
'',
|
|
'[shared]: https://example.com/docs',
|
|
].join('\n'))
|
|
const anchor = container.querySelector('a[href="https://example.com/docs"]')
|
|
expect(anchor, 'a definition after an HTML run must still resolve').not.toBeNull()
|
|
expect(anchor?.textContent).toContain('the docs')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('renders a forbidden wrapper as transparent (children survive)', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<form action="/x">',
|
|
'',
|
|
'inner text',
|
|
'',
|
|
'</form>',
|
|
].join('\n'))
|
|
expect(container.querySelector('form')).toBeNull()
|
|
expect(container.textContent).toContain('inner text')
|
|
await unmount(root)
|
|
})
|
|
})
|
|
|
|
describe('MarkdownDocument (inline pass)', () => {
|
|
it('turns tag text in table cells back into elements', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'| feature | notes |',
|
|
'|---|---|',
|
|
'| alpha | line one<br/>line two |',
|
|
].join('\n'))
|
|
const cell = [...container.querySelectorAll('td')].find((td) => td.textContent?.includes('line one'))
|
|
expect(cell?.querySelector('[data-html-inline] br'), 'the <br/> must render as a real element').not.toBeNull()
|
|
await unmount(root)
|
|
})
|
|
|
|
it('leaves rendered code and comparison prose untouched', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'a < b comparison stays text',
|
|
'',
|
|
'```html',
|
|
'<div>demo</div>',
|
|
'```',
|
|
].join('\n'))
|
|
expect(container.querySelectorAll('[data-html-inline]').length).toBe(0)
|
|
expect(container.textContent).toContain('a < b comparison stays text')
|
|
const code = container.querySelector('code')
|
|
expect(code?.textContent).toContain('<div>demo</div>')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('rewrites local image src inside inline-swapped tags', async () => {
|
|
const { container, root } = await renderDocument('text <img src="./icon.png" alt="i"/> tail')
|
|
const img = container.querySelector('[data-html-inline] img')
|
|
expect(img?.getAttribute('src')).toContain('/sidebar/file?')
|
|
await unmount(root)
|
|
})
|
|
})
|
|
|
|
describe('MarkdownDocument (isolated close tags)', () => {
|
|
// The host renderer emits one text node per raw-HTML token, so a README's
|
|
// `<a id="x"></a>` arrives as two siblings: the open tag (sanitized into a
|
|
// real element) and a lone `</a>` that DOMPurify can only drop. That stray
|
|
// node used to fall through the "keep prose untouched" branch and print the
|
|
// source's `</a>` into the preview.
|
|
it('drops a stray close tag instead of printing it, keeping the anchor id', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<a id="understand-the-implementation"></a>',
|
|
'',
|
|
'## Heading',
|
|
].join('\n'))
|
|
expect(container.textContent, 'the raw close tag must not reach the page').not.toContain('</a>')
|
|
const anchor = container.querySelector('a#understand-the-implementation')
|
|
expect(anchor, 'the anchor id must survive (deep links target it)').not.toBeNull()
|
|
expect(anchor?.textContent).toBe('')
|
|
expect(container.textContent).toContain('Heading')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('drops isolated inline-only close tags that stay in the markdown run', async () => {
|
|
// Block-level close lines (`</div>`) are lifted into their own HTML run and
|
|
// never reach this pass; the tags below are inline-only, stay in the
|
|
// markdown run, and are the ones the pass has to drop.
|
|
const { container, root } = await renderDocument([
|
|
'before the run',
|
|
'',
|
|
'</a>',
|
|
'',
|
|
'between',
|
|
'',
|
|
'</sub>',
|
|
'',
|
|
'after the run',
|
|
].join('\n'))
|
|
expect(container.textContent).not.toContain('</a>')
|
|
expect(container.textContent).not.toContain('</sub>')
|
|
expect(container.textContent).toContain('before the run')
|
|
expect(container.textContent).toContain('between')
|
|
expect(container.textContent).toContain('after the run')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('never prints a stray block-level close line either', async () => {
|
|
// The block-run path (frame stack) already drops top-level stray closes —
|
|
// pinned here so the "no source close tag on screen" acceptance holds for
|
|
// block tags too, not just for the inline pass.
|
|
const { container, root } = await renderDocument([
|
|
'before',
|
|
'',
|
|
'</div>',
|
|
'',
|
|
'</p>',
|
|
'',
|
|
'after',
|
|
].join('\n'))
|
|
expect(container.textContent).not.toContain('</div>')
|
|
expect(container.textContent).not.toContain('</p>')
|
|
expect(container.textContent).toContain('before')
|
|
expect(container.textContent).toContain('after')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('leaves comparison prose untouched', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'a < b and x </ y and 1 < 2 all stay text',
|
|
].join('\n'))
|
|
expect(container.textContent).toContain('a < b and x </ y and 1 < 2 all stay text')
|
|
expect(container.querySelectorAll('[data-html-inline]').length).toBe(0)
|
|
await unmount(root)
|
|
})
|
|
})
|
|
|
|
describe('MarkdownDocument (local markdown images)', () => {
|
|
it('renders markdown-syntax local images through the /sidebar/file route', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'# Title',
|
|
'',
|
|
'',
|
|
'',
|
|
'![logo][logo]',
|
|
'',
|
|
'[logo]: ./logo.png',
|
|
].join('\n'))
|
|
const imgs = [...container.querySelectorAll('img')]
|
|
expect(imgs.length, 'both local images must render as <img>, not alt fallback').toBe(2)
|
|
expect(imgs[0]?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fassets%2Ficon.svg&cwd=%2Fws')
|
|
expect(imgs[0]?.getAttribute('alt')).toBe('icon')
|
|
expect(imgs[1]?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Flogo.png&cwd=%2Fws')
|
|
expect(imgs[1]?.getAttribute('alt')).toBe('logo')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('renders local markdown images in HTML-mixed documents (the production path)', async () => {
|
|
const { container, root } = await renderDocument([
|
|
'<div align="center">badges</div>',
|
|
'',
|
|
'',
|
|
].join('\n'))
|
|
const img = container.querySelector('img')
|
|
expect(img, 'the markdown-syntax image after an HTML run must render').not.toBeNull()
|
|
expect(img?.getAttribute('src')).toBe('http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('keeps remote image destinations untouched', async () => {
|
|
const { container, root } = await renderDocument('')
|
|
const img = container.querySelector('img')
|
|
expect(img?.getAttribute('src')).toBe('https://example.com/x.png')
|
|
await unmount(root)
|
|
})
|
|
|
|
it('is idempotent for already-rewritten media URLs', async () => {
|
|
const url = 'http://gui.origin/proxy/3080/sidebar/file?sessionId=s1&path=%2Fws%2Fdocs%2Fimg.png&cwd=%2Fws'
|
|
const { container, root } = await renderDocument(``)
|
|
const img = container.querySelector('img')
|
|
expect(img?.getAttribute('src')).toBe(url)
|
|
await unmount(root)
|
|
})
|
|
})
|