Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions packages/codehike/src/code/lines.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { expect, test } from "vitest"
import { toLineGroups, toLines } from "./lines.js"
import { BlockAnnotation, Tokens } from "./types.js"

function linesFromSource(source: string) {
const tokens: Tokens = []
const rawLines = source.split("\n")
rawLines.forEach((line, i) => {
if (line.length) {
tokens.push([line])
}
if (i < rawLines.length - 1) {
tokens.push("\n")
}
})
return toLines(tokens)
}

test("throws a readable error when a block annotation is out of range", () => {
const lines = linesFromSource(
[
"const lorem = ipsum(dolor, sit)",
"const [amet, consectetur] = [0, 0]",
"lorem.adipiscing((sed, elit) => {",
" if (sed) {",
" amet += elit",
" }",
"})",
].join("\n"),
)
const annotation: BlockAnnotation = {
name: "mark",
query: "",
fromLineNumber: 100,
toLineNumber: 100,
}

expect(() => toLineGroups(lines, [annotation])).toThrowError(
'Cannot generate a valid range for the given code. Annotation "mark" targets lines 100-100, but the code only has 7 lines.',
)
})
7 changes: 7 additions & 0 deletions packages/codehike/src/code/lines.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,13 @@ function applyBlockAnnotation(
}
})

if (inside.length === 0) {
const lastLine = lines[lines.length - 1]?.range[1] ?? 0
throw new Error(
`Cannot generate a valid range for the given code. Annotation "${annotation.name}" targets lines ${fromLineNumber}-${toLineNumber}, but the code only has ${lastLine} lines.`,
)
}

return [
...before,
{
Expand Down