Skip to content

Commit 80e4029

Browse files
authored
refactor(shared): improve handling of out-of-range start and end values in generateCodeFrame (#10883)
related: #10854
1 parent bdeac37 commit 80e4029

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

packages/shared/__tests__/__snapshots__/codeframe.spec.ts.snap

+26
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,31 @@
11
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
22

3+
exports[`compiler: codeframe > invalid start and end 1`] = `
4+
"1 | <div>
5+
| ^
6+
2 | <template key="one"></template>
7+
3 | <ul>"
8+
`;
9+
10+
exports[`compiler: codeframe > invalid start and end 2`] = `
11+
"1 | <div>
12+
| ^^^^^
13+
2 | <template key="one"></template>
14+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
15+
3 | <ul>
16+
| ^^^^^^
17+
4 | <li v-for="foobar">hi</li>
18+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
19+
5 | </ul>
20+
| ^^^^^^^
21+
6 | <template key="two"></template>
22+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
23+
7 | </div>
24+
| ^^^^^^"
25+
`;
26+
27+
exports[`compiler: codeframe > invalid start and end 3`] = `""`;
28+
329
exports[`compiler: codeframe > line in middle 1`] = `
430
"2 | <template key="one"></template>
531
3 | <ul>

packages/shared/__tests__/codeframe.spec.ts

+6
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,12 @@ attr
4444
expect(generateCodeFrame(source, attrStart, attrEnd)).toMatchSnapshot()
4545
})
4646

47+
test('invalid start and end', () => {
48+
expect(generateCodeFrame(source, -Infinity, 0)).toMatchSnapshot()
49+
expect(generateCodeFrame(source, 0, Infinity)).toMatchSnapshot()
50+
expect(generateCodeFrame(source, Infinity, 0)).toMatchSnapshot()
51+
})
52+
4753
{
4854
const source = `
4955
<template>

packages/shared/src/codeframe.ts

+6
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,12 @@ export function generateCodeFrame(
55
start = 0,
66
end = source.length,
77
): string {
8+
// Ensure start and end are within the source length
9+
start = Math.max(0, Math.min(start, source.length))
10+
end = Math.max(0, Math.min(end, source.length))
11+
12+
if (start > end) return ''
13+
814
// Split the content into individual lines but capture the newline sequence
915
// that separated each line. This is important because the actual sequence is
1016
// needed to properly take into account the full line length for offset

0 commit comments

Comments
 (0)