diff --git a/packages/vite/src/node/__tests__/__snapshots__/utils.spec.ts.snap b/packages/vite/src/node/__tests__/__snapshots__/utils.spec.ts.snap index 7692ad1d7b223f..806e9eba2be8ce 100644 --- a/packages/vite/src/node/__tests__/__snapshots__/utils.spec.ts.snap +++ b/packages/vite/src/node/__tests__/__snapshots__/utils.spec.ts.snap @@ -139,6 +139,17 @@ exports[`generateCodeFrames > start with position 3`] = ` " `; +exports[`generateCodeFrames > supports more than 1000 lines 1`] = ` +" +1198 | // 1197 +1199 | // 1198 +1200 | // 1199 + | ^ +1201 | // 1200 +1202 | // 1201 +" +`; + exports[`generateCodeFrames > works with CRLF 1`] = ` " 1 | import foo from './foo' diff --git a/packages/vite/src/node/__tests__/utils.spec.ts b/packages/vite/src/node/__tests__/utils.spec.ts index 0996b9e712d8b9..9dbf6784994f07 100644 --- a/packages/vite/src/node/__tests__/utils.spec.ts +++ b/packages/vite/src/node/__tests__/utils.spec.ts @@ -288,6 +288,9 @@ foo() // 2 // 3 `.trim() + const veryLongSource = Array.from({ length: 2000 }, (_, i) => `// ${i}`).join( + '\n', + ) const expectSnapshot = (value: string) => { try { @@ -340,6 +343,10 @@ foo() test('invalid start > end', () => { expectSnapshot(generateCodeFrame(source, 2, 0)) }) + + test('supports more than 1000 lines', () => { + expectSnapshot(generateCodeFrame(veryLongSource, { line: 1200, column: 0 })) + }) }) describe('getHash', () => { diff --git a/packages/vite/src/node/utils.ts b/packages/vite/src/node/utils.ts index 882aa00e03f170..4b0094aff46133 100644 --- a/packages/vite/src/node/utils.ts +++ b/packages/vite/src/node/utils.ts @@ -511,6 +511,11 @@ export function generateCodeFrame( end !== undefined ? posToNumber(source, end) : start, source.length, ) + const lastPosLine = + end !== undefined + ? numberToPos(source, end).line + : numberToPos(source, start).line + range + const lineNumberWidth = Math.max(3, String(lastPosLine).length + 1) const lines = source.split(splitRE) let count = 0 const res: string[] = [] @@ -521,7 +526,7 @@ export function generateCodeFrame( if (j < 0 || j >= lines.length) continue const line = j + 1 res.push( - `${line}${' '.repeat(Math.max(3 - String(line).length, 0))}| ${ + `${line}${' '.repeat(lineNumberWidth - String(line).length)}| ${ lines[j] }`, ) @@ -533,11 +538,15 @@ export function generateCodeFrame( 1, end > count ? lineLength - pad : end - start, ) - res.push(` | ` + ' '.repeat(pad) + '^'.repeat(length)) + res.push( + `${' '.repeat(lineNumberWidth)}| ` + + ' '.repeat(pad) + + '^'.repeat(length), + ) } else if (j > i) { if (end > count) { const length = Math.max(Math.min(end - count, lineLength), 1) - res.push(` | ` + '^'.repeat(length)) + res.push(`${' '.repeat(lineNumberWidth)}| ` + '^'.repeat(length)) } count += lineLength + 1 }