merge fix/crlf-markdown-surface into dev(修 CRLF 输入下的三层 \r 误判与预览双拼写渲染:markdown-html 的 isBlank / mermaid-blocks 的 CLOSE_FENCE_RE / markdown-code 的 closesFence 把 \r 当内容,导致 HTML 段永不终止、mermaid 围栏吞掉余下文件、链接改写从第一个围栏起全部失效;TextEditor 的 draft 快照把 CodeMirror 归一化后的 LF 文档覆盖预览源,使挂载那一趟写入的标题 id 被丢弃。含测试脚手架 CRLF 安全化与 9 条 CRLF≡LF 判别性用例)

This commit is contained in:
Menghuan1918 committed 2026-10-06 00:57:35 +08:00
commit 0ee870ade2
7 files changed
+301 -8

No files matched your search

+21 -1
View File
@@ -62,6 +62,15 @@ type ViewMode = 'preview' | 'edit'
const previewScrollMemory = new Map<string, number>()
const previewScrollKey = (scope: { sessionId: string }, path: string): string => `${scope.sessionId}::${path}`
/** Whether two spellings are the SAME document — byte-equal, or equal once
* line endings are normalized CRLF/CR → LF. Line endings are not content:
* CodeMirror keeps every document with `\n` endings whatever the file used,
* so the live document of a freshly opened CRLF file differs from the bytes
* it was loaded from by line endings alone. */
function sameDocument(a: string, b: string): boolean {
return a === b || a.replace(/\r\n?/g, '\n') === b.replace(/\r\n?/g, '\n')
}
export function TextEditor(props: FileViewerProps) {
const { ctx, scope, path, viewerId, content, truncated } = props
const [mode, setMode] = useState<ViewMode>('preview')
@@ -448,9 +457,20 @@ export function TextEditor(props: FileViewerProps) {
// the new document — matching the reset-to-null of a clean tab). The
// updateListener used to re-stringify the WHOLE document on every
// keystroke (O(docLength) per key) for a draft only preview reads.
//
// Only an EDIT becomes a draft. Publishing the live document when it is the
// loaded content under another line-ending spelling (CodeMirror normalizes
// CRLF → LF, so that is every CRLF file) would hand the preview a second
// spelling of the same document one render after the mount: the renderer
// rebuilds the markdown elements it owns, and every DOM-side pass result
// written onto them — heading ids, collapsed anchors — is discarded with
// them until the surface's MutationObserver re-runs (a microtask later,
// i.e. after a synchronous caller has already looked).
useEffect(() => {
const view = viewRef.current
setDraft(view === null ? null : view.state.doc.toString())
if (view === null) { setDraft(null); return }
const live = view.state.doc.toString()
setDraft(content !== undefined && sameDocument(live, content) ? null : live)
}, [mode, content])
const save = (): void => {
+6 -2
View File
@@ -47,12 +47,16 @@ function fenceRun(line: string): { marker: string; length: number } | null {
return length >= 3 ? { marker, length } : null
}
/** Whether a line closes a fence opened by `marker` × `length` (CommonMark). */
/** Whether a line closes a fence opened by `marker` × `length` (CommonMark).
* The tail may carry a CRLF terminator: `\r` is the line's ending, not
* content, and reading it as content left every fence in a CRLF document
* unclosed — the masked region then ran to the end of the file and the link /
* image passes skipped everything after the first fence. */
function closesFence(line: string, marker: string, length: number): boolean {
if (line.charAt(0) !== marker) return false
let run = 0
while (line.charAt(run) === marker) run += 1
return run >= length && /^[ \t]*$/.test(line.slice(run))
return run >= length && /^[ \t\r]*$/.test(line.slice(run))
}
/**
+6 -1
View File
@@ -231,7 +231,12 @@ export function splitHtmlBlocks(text: string): MdHtmlSegment[] {
inHtmlRun = false
inComment = false
}
const isBlank = (line: string): boolean => /^[ \t]*$/.test(line)
// A blank line is blank whichever terminator it carries: `\r` is the first
// half of a CRLF pair, not content (a Windows checkout reaches this splitter
// with `\r\n` intact). Reading it as content used to keep an HTML run open
// across the blank line that ends it, so the markdown after a `<div>` run was
// swallowed as raw HTML and rendered as text.
const isBlank = (line: string): boolean => /^[ \t\r]*$/.test(line)
for (const line of lines) {
if (openFence !== null) {
+6 -2
View File
@@ -36,8 +36,12 @@ export interface MermaidMarkdownProps {
/** CommonMark opening fence: 0-3 spaces indent + a run of 3+ backticks or tildes. */
export const OPEN_FENCE_RE = /^ {0,3}(`{3,}|~{3,})/
/** A closing-fence line: 0-3 spaces indent + 3+ backticks/tildes + trailing spaces only. */
export const CLOSE_FENCE_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/
/** A closing-fence line: 0-3 spaces indent + 3+ backticks/tildes + trailing
* spaces only. The optional `\r` is a CRLF line's terminator, not content: a
* CRLF document reaches this regex with its line endings intact, and without
* the `\r` no fence would ever close (the block would swallow the rest of the
* file). */
export const CLOSE_FENCE_RE = /^ {0,3}(`{3,}|~{3,})[ \t]*\r?$/
/** Parse the info string from the line tail after the fence run; null when invalid. */
export function fenceInfo(rest: string, fence: string): string | null {
+9 -1
View File
@@ -65,13 +65,21 @@ export interface DocumentAnchors {
* its ATX headings and its same-document link destinations. Fenced code is
* skipped (a `#` inside a fence is a comment, not a heading) and so is the
* trailing `#`-run of a closed ATX heading.
*
* Lines are split on CRLF as well as LF: this scanner reads the repo's own
* READMEs, and a Windows checkout (`core.autocrlf=true`, i.e. the `ci-windows`
* lane) hands it `\r\n`. Keeping the `\r` on the line made the closed-ATX
* pattern below match NOTHING — `.` does not match `\r`, and without the `m`
* flag `$` only matches at the very end of the string — so every README
* heading silently disappeared and the anchor specs compared the READMEs'
* tables of contents against an empty heading list.
* @param text - the markdown source.
*/
export function scanDocumentAnchors(text: string): DocumentAnchors {
const headings: string[] = []
const anchors: string[] = []
let fence: string | null = null
for (const line of text.split('\n')) {
for (const line of text.split(/\r?\n/)) {
const fenceLine = /^ {0,3}(`{3,}|~{3,})/.exec(line)
const fenceMarker = fenceLine?.at(1)?.charAt(0)
if (fenceMarker !== undefined) {
+171
View File
@@ -0,0 +1,171 @@
/**
* Line endings are not content: every line-based scanner in the markdown
* pipeline must read a CRLF document exactly like the same document with LF
* endings.
*
* WHY THIS FILE EXISTS: the pipeline's scanners split a document on `\n` and
* then reason about each line (`isBlank`, a closed-ATX heading, a closing
* fence). A Windows checkout — `core.autocrlf=true`, which is both the
* `ci-windows` lane and every user who clones on Windows — hands them `\r\n`,
* and a `\r` left at the end of a line is invisible in the rendered output but
* not to those predicates. Measured on this repo's own README before the fix:
* the HTML-run splitter produced 4 segments instead of 36 (an HTML run stayed
* open across the blank line that should have ended it and swallowed the
* markdown after it), `splitMermaidBlocks` never closed a fence, and
* `maskCodeRegions` masked everything from the first fence to the end of the
* file, so the link rewriter stopped claiming every `.md` link after it. The
* same document with LF endings was correct in all three.
*
* The invariant pinned here is that whole contract, scanner by scanner: the
* CRLF spelling's output must equal the LF spelling's output once `\r` is
* ignored. These cases are DISCRIMINATING by construction — reverting any of
* the three `\r` fixes in `src/client` turns them red (the CRLF half diverges
* from the LF half), which is exactly how the `ci-windows` failures got here:
* only the CRLF half of each pair was ever exercised there.
*/
import { describe, expect, it } from 'vitest'
import {
analyzeMarkdownHtml,
splitHtmlBlocks,
type AnalyzedMarkdownHtml,
type MdHtmlSegment,
} from '../src/client/markdown-html.ts'
import { splitMermaidBlocks, type MdBlock } from '../src/client/mermaid-blocks.ts'
import { maskCodeRegions } from '../src/client/markdown-code.ts'
import { rewriteLocalMarkdownLinks } from '../src/client/markdown-navigation.ts'
import { rewriteLocalImageUrls } from '../src/client/markdown-images.ts'
import type { SessionScope } from '../src/client/api.ts'
/** One document, both spellings — every case below compares the two. */
const LF = [
'# 标题',
'',
'<!-- hero -->',
'',
'<div align="center">',
' <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />',
'</div>',
'',
'## 🚀 安装',
'',
'```sh',
'dsh plugin --profile web add dsh-better-sidebar',
'```',
'',
'[other](./other.md#安装)',
'',
'~~~text',
'[demonstration](./demonstration.md#标题)',
'~~~',
'',
'![image](./pic.png)',
'',
].join('\n')
const CRLF = LF.replace(/\n/g, '\r\n')
/** `\r` is a line terminator, so dropping it reduces one spelling to the other. */
const stripCr = (value: string): string => value.replace(/\r/g, '')
/** The CRLF spelling of a split document, reduced to the LF one. */
function segmentsLf(segments: readonly MdHtmlSegment[]): MdHtmlSegment[] {
return segments.map(segment => ({ kind: segment.kind, text: stripCr(segment.text) }))
}
/** The CRLF spelling of a whole-document analysis, reduced to the LF one. */
function analysisLf(info: AnalyzedMarkdownHtml): AnalyzedMarkdownHtml {
return {
...info,
segments: segmentsLf(info.segments),
referenceDefinitions: stripCr(info.referenceDefinitions),
}
}
/** The CRLF spelling of a mermaid split, reduced to the LF one. */
function blocksLf(blocks: readonly MdBlock[]): MdBlock[] {
return blocks.map(block => block.kind === 'mermaid'
? { kind: 'mermaid' as const, code: stripCr(block.code) }
: { kind: 'markdown' as const, text: stripCr(block.text) })
}
const SCOPE: SessionScope = { sessionId: 's1', cwd: '/p' }
const DOC = '/p/docs/README.md'
describe('the markdown pipeline reads CRLF and LF documents identically', () => {
it('splitHtmlBlocks: an HTML run ends at a blank line in both spellings', () => {
// The regression: `isBlank` was `/^[ \t]*$/`, so a CRLF blank line (`'\r'`)
// was content. The `<div>` run stayed open and swallowed `## 🚀 安装` and
// everything after it as raw HTML, i.e. the preview rendered markdown as
// text.
expect(segmentsLf(splitHtmlBlocks(CRLF))).toEqual(splitHtmlBlocks(LF))
// Guard the guard: the LF half really does carry the markdown after the
// HTML run as MARKDOWN (a splitter that returned one HTML segment for the
// whole document would satisfy the equality above for the wrong reason).
const segments = splitHtmlBlocks(LF)
const markdown = segments.filter(segment => segment.kind === 'markdown').map(segment => segment.text).join('\n')
const html = segments.filter(segment => segment.kind === 'html').map(segment => segment.text).join('\n')
expect(markdown).toContain('## 🚀 安装')
expect(markdown).toContain('![image](./pic.png)')
expect(html).not.toContain('安装')
expect(html).toContain('<div align="center">')
})
it('splitHtmlBlocks: a minimal HTML block + blank line + markdown document', () => {
const lf = '# a\n\n<div>x</div>\n\n# b\n'
expect(segmentsLf(splitHtmlBlocks(lf.replace(/\n/g, '\r\n')))).toEqual(splitHtmlBlocks(lf))
// `# b` is a markdown heading, not part of the `<div>` run.
expect(splitHtmlBlocks(lf).map(segment => segment.kind)).toEqual(['markdown', 'html', 'markdown'])
})
it('analyzeMarkdownHtml: same segmentation, gates and reference definitions', () => {
const lf = `${LF}\n[ref]: ./target.md#锚点\n`
expect(analysisLf(analyzeMarkdownHtml(lf.replace(/\n/g, '\r\n')))).toEqual(analyzeMarkdownHtml(lf))
})
it('maskCodeRegions: a CRLF fence closes where its LF twin does', () => {
// The regression: `closesFence` tested the fence tail with `/^[ \t]*$/`,
// which a `\r` fails — no fence ever closed, so the masked region ran to
// the end of the file and every later pass skipped a masked document.
expect(stripCr(maskCodeRegions(CRLF).masked)).toEqual(maskCodeRegions(LF).masked)
// The mask really does stop at the closing fence: the text right after it
// survives unmasked in both spellings.
expect(maskCodeRegions(LF).masked).toContain('[other](./other.md#安装)')
expect(stripCr(maskCodeRegions(CRLF).masked)).toContain('[other](./other.md#安装)')
})
it('rewriteLocalMarkdownLinks: a `.md` link after a fence is still claimed', () => {
// The regression's user-visible half: on CRLF the destination kept its own
// `#`, the host parser refused it, and the link rendered as inert text.
const rewrittenLf = rewriteLocalMarkdownLinks(LF, DOC, SCOPE.cwd)
const rewrittenCrlf = rewriteLocalMarkdownLinks(CRLF, DOC, SCOPE.cwd)
expect(stripCr(rewrittenCrlf)).toEqual(rewrittenLf)
// Claimed: the heading fragment is carried past the host parser as %23.
expect(rewrittenLf).toContain('[other](./other.md%23安装)')
expect(rewrittenCrlf).toContain('[other](./other.md%23安装)')
// Not claimed: the link demonstrated inside the `~~~` fence is untouched
// (the fence is masked, in both spellings), and a non-markdown local
// destination stays inert.
expect(rewrittenLf).toContain('[demonstration](./demonstration.md#标题)')
expect(rewrittenCrlf).toContain('[demonstration](./demonstration.md#标题)')
})
it('rewriteLocalImageUrls + rewriteLocalMarkdownLinks: byte parity', () => {
const rewrite = (text: string): string =>
rewriteLocalMarkdownLinks(rewriteLocalImageUrls(text, SCOPE, DOC, ''), DOC, SCOPE.cwd)
expect(stripCr(rewrite(CRLF))).toEqual(rewrite(LF))
// The image pass ran in the CRLF spelling too (its destination became the
// session-scoped media URL).
expect(rewrite(CRLF)).toContain('pic.png')
expect(rewrite(CRLF)).not.toContain('](./pic.png)')
})
it('splitMermaidBlocks: a CRLF mermaid fence closes instead of swallowing the file', () => {
const lf = '# t\n\n```mermaid\ngraph TD;\n A-->B\n```\n\nafter\n'
expect(blocksLf(splitMermaidBlocks(lf.replace(/\n/g, '\r\n')))).toEqual(splitMermaidBlocks(lf))
// The diagram is exactly the fence's body — not the rest of the document.
expect(splitMermaidBlocks(lf.replace(/\n/g, '\r\n'))).toEqual([
{ kind: 'markdown', text: '# t\r\n\r' },
{ kind: 'mermaid', code: 'graph TD;\r\n A-->B\r' },
{ kind: 'markdown', text: '\r\nafter\r\n' },
])
})
})
+82 -1
View File
@@ -496,6 +496,83 @@ describe('the markdown preview surface', () => {
again.unmount()
})
it('renders a CRLF document exactly like its LF twin, ids included', () => {
// Line endings are not content. The scanner half of this invariant is
// pinned in tests/markdown-crlf.spec.ts; this is the half a reader sees,
// through the real renderer — and it is asserted SYNCHRONOUSLY after the
// mount, because that is when the surface pass runs: every id it writes
// onto the headings is thrown away if the preview re-renders the document
// under the other spelling one commit later. That is what a CRLF file used
// to do — CodeMirror holds every document with LF endings, so the draft it
// snapshots differs from the loaded bytes by line endings alone, and the
// host renderer rebuilds the markdown elements it owns on that change.
const lf = [
'# 标题',
'',
'<div align="center">',
' <img alt="badge" src="https://img.shields.io/badge/x-y-blue" />',
'</div>',
'',
'## 🚀 安装',
'',
'See [other](./other.md#安装).',
'',
].join('\n')
/** Everything the surface pass and the delegate are responsible for. */
const shapeOf = (text: string): Record<string, unknown> => {
const mounted = mountEditor(text, '/p/README.md')
const surface = surfaceOf(mounted.container)
const shape = {
ids: [...surface.querySelectorAll<HTMLElement>('h1, h2, h3, h4, h5, h6')].map(heading => heading.id),
htmlSegments: surface.querySelectorAll('[data-dsh-html-segment]').length,
// Whitespace-normalized: a raw-HTML run's own last line keeps its `\r`
// in the CRLF spelling, and the sanitizer turns that terminator into a
// whitespace text node inside the rendered leaf. Invisible (browsers
// collapse it), so the reader-visible text is what is compared.
text: (surface.textContent ?? '').replace(/\s+/g, ' ').trim(),
claimedLinks: [...surface.querySelectorAll<HTMLButtonElement>('button')]
.map(button => button.title)
.filter(title => title.startsWith('./')),
}
mounted.unmount()
return shape
}
const crlf = shapeOf(lf.replace(/\n/g, '\r\n'))
// Guard the guard: the fixture really does exercise both halves — a
// heading that slugs to its own text, one whose id carries the space the
// emoji left behind, and a claimed `.md` link carrying a heading fragment.
expect(crlf.ids).toEqual(['标题', '-安装'])
expect(crlf.claimedLinks).toEqual(['./other.md#安装'])
expect(shapeOf(lf)).toEqual(crlf)
})
it('resolves every README anchor from a CRLF copy, on every lane', () => {
// The acceptance case below reads whatever line endings the checkout has,
// so on the ubuntu/macOS lanes it never sees the spelling the `ci-windows`
// lane checks out. This copy pins that spelling on EVERY lane, and it
// asserts synchronously for the reason given in the case above.
const crlf = readFileSync(join(process.cwd(), 'README.md'), 'utf8')
.replace(/\r\n/g, '\n')
.replace(/\n/g, '\r\n')
const mounted = mountEditor(crlf, '/p/README.md')
const surface = surfaceOf(mounted.container)
const headings = [...surface.querySelectorAll<HTMLElement>('h1, h2, h3, h4, h5, h6')]
const tocAnchors = crlf.split(/\r?\n/).slice(34, 44)
.flatMap(line => [...line.matchAll(/\]\((#[^)\s]*)\)/g)])
.map(match => match[1] ?? '')
.filter(anchor => anchor !== '')
expect(tocAnchors.length).toBeGreaterThanOrEqual(15)
const unresolved = tocAnchors.filter((anchor) => {
const fragment = decodeURIComponent(anchor.slice(1))
const heading = headings.find(candidate => candidate.id === fragment)
const link = [...surface.querySelectorAll<HTMLButtonElement>('button')].find(button => button.title === anchor)
return heading === undefined || link === undefined
})
expect(unresolved).toEqual([])
mounted.unmount()
})
it('resolves and scrolls for EVERY table-of-contents anchor of the repo\u2019s own READMEs', () => {
// The acceptance case for the slug fix, through the real renderer: the
// READMEs are the documents whose anchors were 0/15 before it (the heading
@@ -507,7 +584,11 @@ describe('the markdown preview surface', () => {
const mounted = mountEditor(readFileSync(join(process.cwd(), name), 'utf8'), `/p/${name}`)
const surface = surfaceOf(mounted.container)
const headings = [...surface.querySelectorAll<HTMLElement>('h1, h2, h3, h4, h5, h6')]
const tocLines = readFileSync(join(process.cwd(), name), 'utf8').split('\n').slice(34, 44)
// CRLF checkout: a README line carries a `\r` terminator, so split on
// both endings. (The anchor pattern below happens to survive a trailing
// `\r` — `\s` is excluded from the destination — but the slice must not
// depend on that accident.)
const tocLines = readFileSync(join(process.cwd(), name), 'utf8').split(/\r?\n/).slice(34, 44)
const tocAnchors = tocLines.flatMap(line => [...line.matchAll(/\]\((#[^)\s]*)\)/g)])
.map(match => match[1] ?? '')
.filter(anchor => anchor !== '')