]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
refactor(shared): improve handling of out-of-range start and end values in generateCo...
authorTycho <jh.leong@outlook.com>
Mon, 10 Jun 2024 07:28:00 +0000 (15:28 +0800)
committerGitHub <noreply@github.com>
Mon, 10 Jun 2024 07:28:00 +0000 (15:28 +0800)
related: #10854

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

index 4caa583461d2fa30e59f870bdefa88f17400c697..28486d717230e68b7ea3dec914876dfdc8e86cd9 100644 (file)
@@ -1,5 +1,31 @@
 // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
 
+exports[`compiler: codeframe > invalid start and end 1`] = `
+"1  |  <div>
+   |  ^
+2  |    <template key="one"></template>
+3  |    <ul>"
+`;
+
+exports[`compiler: codeframe > invalid start and end 2`] = `
+"1  |  <div>
+   |  ^^^^^
+2  |    <template key="one"></template>
+   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+3  |    <ul>
+   |  ^^^^^^
+4  |      <li v-for="foobar">hi</li>
+   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+5  |    </ul>
+   |  ^^^^^^^
+6  |    <template key="two"></template>
+   |  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+7  |  </div>
+   |  ^^^^^^"
+`;
+
+exports[`compiler: codeframe > invalid start and end 3`] = `""`;
+
 exports[`compiler: codeframe > line in middle 1`] = `
 "2  |    <template key="one"></template>
 3  |    <ul>
index addae82c90848279855ac3c69351cf5dd07996c8..41ad08b2a9b0c01646a7935e2512882a4557f99e 100644 (file)
@@ -44,6 +44,12 @@ attr
     expect(generateCodeFrame(source, attrStart, attrEnd)).toMatchSnapshot()
   })
 
+  test('invalid start and end', () => {
+    expect(generateCodeFrame(source, -Infinity, 0)).toMatchSnapshot()
+    expect(generateCodeFrame(source, 0, Infinity)).toMatchSnapshot()
+    expect(generateCodeFrame(source, Infinity, 0)).toMatchSnapshot()
+  })
+
   {
     const source = `
 <template>
index af7212166eecb6b815ad67f94fe7932d24ad8f25..c2c1c8b1874d0504bd62fcedd67ca6f45890dc86 100644 (file)
@@ -5,6 +5,12 @@ export function generateCodeFrame(
   start = 0,
   end = source.length,
 ): string {
+  // Ensure start and end are within the source length
+  start = Math.max(0, Math.min(start, source.length))
+  end = Math.max(0, Math.min(end, source.length))
+
+  if (start > end) return ''
+
   // Split the content into individual lines but capture the newline sequence
   // that separated each line. This is important because the actual sequence is
   // needed to properly take into account the full line length for offset