prettier and code cleanup

This commit is contained in:
chezsmithy 2025-07-13 14:47:54 -07:00
parent ad2bbc28c9
commit 948246dc44
10 changed files with 473 additions and 265 deletions

View file

@ -10,10 +10,7 @@ import {
shouldStopAtMarkdownBlock,
} from "../../../utils/streamMarkdownUtils";
import {
hasNestedMarkdownBlocks,
shouldChangeLineAndStop,
} from "./lineStream";
import { hasNestedMarkdownBlocks, shouldChangeLineAndStop } from "./lineStream";
/**
* Filters and processes lines from a code block, removing unnecessary markers and handling edge cases.
@ -83,7 +80,11 @@ export async function* filterCodeBlockLines(
const line = allLines[i];
// Process block nesting logic for the first fence
const nesting = processBlockNesting(line, seenFirstFence, shouldRemoveLineBeforeStart);
const nesting = processBlockNesting(
line,
seenFirstFence,
shouldRemoveLineBeforeStart,
);
if (nesting.shouldSkip) {
continue; // Filter out starting ``` or START block
}

View file

@ -3,13 +3,8 @@ import { distance } from "fastest-levenshtein";
import { DiffLine } from "../../..";
import { LineStream } from "../../../diff/util";
import {
headerIsMarkdown,
isMarkdownFile
} from "../../../utils/markdownUtils";
import {
processBlockNesting as processBlockNestingUtil
} from "../../../utils/streamMarkdownUtils";
import { headerIsMarkdown, isMarkdownFile } from "../../../utils/markdownUtils";
import { processBlockNesting as processBlockNestingUtil } from "../../../utils/streamMarkdownUtils";
export { filterCodeBlockLines } from "./filterCodeBlock";
@ -60,6 +55,47 @@ function shouldRemoveLineBeforeStart(line: string): boolean {
);
}
/**
* Shared utility for validating patterns in lines to avoid code duplication.
* Checks if a pattern appears in a valid context (not inside quotes or identifiers).
*/
export function validatePatternInLine(
line: string,
pattern: string,
): {
isValid: boolean;
patternIndex: number;
beforePattern: string;
} {
const patternIndex = line.indexOf(pattern);
if (patternIndex === -1) {
return { isValid: false, patternIndex: -1, beforePattern: "" };
}
// Check if pattern is preceded by a non-whitespace character
// If so, it might be part of an identifier, so don't handle it
if (patternIndex > 0) {
const charBefore = line[patternIndex - 1];
if (charBefore && !charBefore.match(/\s/)) {
return { isValid: false, patternIndex, beforePattern: "" };
}
}
// Check if pattern appears to be inside quotes
// Simple heuristic: count unmatched quotes before the pattern
const beforePattern = line.substring(0, patternIndex);
const singleQuotes = (beforePattern.match(/'/g) || []).length;
const doubleQuotes = (beforePattern.match(/"/g) || []).length;
// If there's an odd number of quotes before pattern, we're likely inside quotes
if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) {
return { isValid: false, patternIndex, beforePattern };
}
return { isValid: true, patternIndex, beforePattern };
}
export function shouldChangeLineAndStop(line: string): string | undefined {
if (line.trimStart() === "```") {
return line;
@ -67,26 +103,10 @@ export function shouldChangeLineAndStop(line: string): string | undefined {
// Check if [/CODE] appears in the line
if (line.includes(CODE_STOP_BLOCK)) {
const stopBlockIndex = line.indexOf(CODE_STOP_BLOCK);
const validation = validatePatternInLine(line, CODE_STOP_BLOCK);
// Check if [/CODE] is preceded by a non-whitespace character
// If so, it might be part of an identifier, so don't handle it
if (stopBlockIndex > 0) {
const charBefore = line[stopBlockIndex - 1];
if (charBefore && !charBefore.match(/\s/)) {
return undefined; // Don't handle [/CODE] that's part of an identifier
}
}
// Check if [/CODE] appears to be inside quotes
// Simple heuristic: count unmatched quotes before the stop block
const beforeStopBlock = line.substring(0, stopBlockIndex);
const singleQuotes = (beforeStopBlock.match(/'/g) || []).length;
const doubleQuotes = (beforeStopBlock.match(/"/g) || []).length;
// If there's an odd number of quotes before [/CODE], we're likely inside quotes
if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) {
return undefined; // Don't handle [/CODE] inside quotes
if (!validation.isValid) {
return undefined;
}
// Get the trimmed line to check if [/CODE] is at logical start
@ -100,7 +120,7 @@ export function shouldChangeLineAndStop(line: string): string | undefined {
}
// [/CODE] appears after some content (separated by whitespace) - return part before
return beforeStopBlock.trimEnd();
return validation.beforePattern.trimEnd();
}
return undefined;
@ -336,26 +356,10 @@ export async function* stopAtLines(
// Check each stop phrase
for (const stopAt of linesToStopAt) {
if (line.includes(stopAt)) {
const stopAtIndex = line.indexOf(stopAt);
const validation = validatePatternInLine(line, stopAt);
// Check if stop phrase is preceded by a non-whitespace character
// If so, it might be part of an identifier, so don't handle it
if (stopAtIndex > 0) {
const charBefore = line[stopAtIndex - 1];
if (charBefore && !charBefore.match(/\s/)) {
continue; // Don't handle stop phrase that's part of an identifier
}
}
// Check if stop phrase appears to be inside quotes
// Simple heuristic: count unmatched quotes before the stop phrase
const beforeStopPhrase = line.substring(0, stopAtIndex);
const singleQuotes = (beforeStopPhrase.match(/'/g) || []).length;
const doubleQuotes = (beforeStopPhrase.match(/"/g) || []).length;
// If there's an odd number of quotes before stop phrase, we're likely inside quotes
if (singleQuotes % 2 !== 0 || doubleQuotes % 2 !== 0) {
continue; // Don't handle stop phrase inside quotes
if (!validation.isValid) {
continue;
}
// Get the trimmed line to check if stop phrase is at logical start
@ -367,8 +371,10 @@ export async function* stopAtLines(
break;
} else {
// Stop phrase appears after some content - check if it's separated by whitespace
const contentBeforeStopPhrase = beforeStopPhrase.trimEnd();
if (contentBeforeStopPhrase.length < beforeStopPhrase.length) {
const contentBeforeStopPhrase = validation.beforePattern.trimEnd();
if (
contentBeforeStopPhrase.length < validation.beforePattern.length
) {
// There's whitespace before the stop phrase, so it's properly separated
shouldStop = true;
break;

View file

@ -1,6 +1,9 @@
import { beforeEach, describe, expect, it, Mock, vi } from "vitest";
import { collectAllLines, MarkdownBlockStateTracker } from "../../../utils/markdownUtils";
import {
collectAllLines,
MarkdownBlockStateTracker,
} from "../../../utils/markdownUtils";
import { shouldStopAtMarkdownBlock } from "../../../utils/streamMarkdownUtils";
import * as lineStream from "./lineStream";
@ -1205,4 +1208,94 @@ describe("lineStream", () => {
]);
});
});
describe("validatePatternInLine", () => {
it("should return false when pattern is not found", () => {
const result = lineStream.validatePatternInLine(
"const x = 5;",
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(-1);
expect(result.beforePattern).toBe("");
});
it("should return false when pattern is preceded by non-whitespace", () => {
const result = lineStream.validatePatternInLine(
'const var[/CODE]Name = "test";',
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(9);
});
it("should return false when pattern is inside double quotes", () => {
const result = lineStream.validatePatternInLine(
'console.log("test [/CODE] end");',
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(18);
});
it("should return false when pattern is inside single quotes", () => {
const result = lineStream.validatePatternInLine(
"const message = 'test [/CODE] end';",
"[/CODE]",
);
expect(result.isValid).toBe(false);
expect(result.patternIndex).toBe(22);
});
it("should return true when pattern is properly separated by whitespace", () => {
const result = lineStream.validatePatternInLine(
"some code [/CODE] more text",
"[/CODE]",
);
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(10);
expect(result.beforePattern).toBe("some code ");
});
it("should return true when pattern is at start of line", () => {
const result = lineStream.validatePatternInLine("[/CODE]", "[/CODE]");
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(0);
expect(result.beforePattern).toBe("");
});
it("should return true when pattern has only whitespace before it", () => {
const result = lineStream.validatePatternInLine(" [/CODE]", "[/CODE]");
expect(result.isValid).toBe(true);
expect(result.patternIndex).toBe(4);
expect(result.beforePattern).toBe(" ");
});
it("should handle complex quote scenarios correctly", () => {
// Unmatched quote should make it invalid
const result1 = lineStream.validatePatternInLine(
'const x = "unclosed quote [/CODE]',
"[/CODE]",
);
expect(result1.isValid).toBe(false);
// Matched quotes should make it valid
const result2 = lineStream.validatePatternInLine(
'const x = "closed"; [/CODE]',
"[/CODE]",
);
expect(result2.isValid).toBe(true);
});
it("should work with different patterns", () => {
const result1 = lineStream.validatePatternInLine(
"# End of file. Done",
"# End of file.",
);
expect(result1.isValid).toBe(true);
const result2 = lineStream.validatePatternInLine(" ```", "```");
expect(result2.isValid).toBe(true);
});
});
});

View file

@ -400,6 +400,5 @@ export {
autodetectTemplateType,
llmCanGenerateInParallel,
modelSupportsImages,
modelSupportsTools
modelSupportsTools,
};

View file

@ -38,8 +38,8 @@ export function isMarkdownFile(filepath?: string): boolean {
* Optimized to handle nested markdown code blocks.
*/
export class MarkdownBlockStateTracker {
private trimmedLines: string[];
private bareBacktickPositions: number[];
protected trimmedLines: string[];
protected bareBacktickPositions: number[];
private markdownNestCount: number = 0;
private lastProcessedIndex: number = -1;
@ -72,9 +72,8 @@ export class MarkdownBlockStateTracker {
if (currentLine.match(/^`+$/)) {
// Found bare backticks - check if this is the last one
if (j === currentIndex) {
const remainingBareBackticks = this.bareBacktickPositions.filter(
(pos) => pos > j,
).length;
const remainingBareBackticks =
this.getRemainingBareBackticksAfter(j);
if (remainingBareBackticks === 0) {
this.markdownNestCount = 0;
this.lastProcessedIndex = j;
@ -99,6 +98,28 @@ export class MarkdownBlockStateTracker {
this.lastProcessedIndex = currentIndex;
return false;
}
/**
* Efficiently determines if there are remaining bare backticks after the given position.
*/
getRemainingBareBackticksAfter(currentIndex: number): number {
return this.bareBacktickPositions.filter((pos) => pos > currentIndex)
.length;
}
/**
* Checks if the line at the given index is a bare backtick line.
*/
isBareBacktickLine(index: number): boolean {
return this.bareBacktickPositions.includes(index);
}
/**
* Gets the trimmed lines array.
*/
getTrimmedLines(): string[] {
return this.trimmedLines;
}
}
/**

View file

@ -1,84 +1,306 @@
import { test, expect } from "vitest";
import { describe, expect, it } from "vitest";
import {
collectAllLines,
headerIsMarkdown,
isMarkdownFile,
MarkdownBlockStateTracker,
} from "./markdownUtils";
test("headerIsMarkdown correctly identifies markdown headers", () => {
// Should return true for markdown headers
expect(headerIsMarkdown("md")).toBe(true);
expect(headerIsMarkdown("markdown")).toBe(true);
expect(headerIsMarkdown("gfm")).toBe(true);
expect(headerIsMarkdown("github-markdown")).toBe(true);
expect(headerIsMarkdown("language md")).toBe(true);
expect(headerIsMarkdown("language markdown")).toBe(true);
expect(headerIsMarkdown("filename.md")).toBe(true);
expect(headerIsMarkdown("path/to/file.md language")).toBe(true);
describe("headerIsMarkdown", () => {
// Test exact match with common Markdown identifiers
it("should identify exact matches with common Markdown identifiers", () => {
expect(headerIsMarkdown("md")).toBe(true);
expect(headerIsMarkdown("markdown")).toBe(true);
expect(headerIsMarkdown("gfm")).toBe(true);
expect(headerIsMarkdown("github-markdown")).toBe(true);
});
// Should return false for non-markdown headers
expect(headerIsMarkdown("javascript")).toBe(false);
expect(headerIsMarkdown("typescript")).toBe(false);
expect(headerIsMarkdown("python")).toBe(false);
expect(headerIsMarkdown("")).toBe(false);
// Test identifiers preceded by a space
it("should identify identifiers preceded by a space", () => {
expect(headerIsMarkdown("lang md")).toBe(true);
expect(headerIsMarkdown("something markdown")).toBe(true);
expect(headerIsMarkdown("language gfm")).toBe(true);
expect(headerIsMarkdown("spec github-markdown")).toBe(true);
});
// Test file extensions
it("should identify file names with markdown extensions", () => {
expect(headerIsMarkdown("example.md")).toBe(true);
expect(headerIsMarkdown("document.markdown")).toBe(true);
expect(headerIsMarkdown("readme.gfm")).toBe(true);
});
// Test more complex cases with extensions
it("should identify file names with markdown extensions followed by other text", () => {
expect(headerIsMarkdown("example.md additional text")).toBe(true);
expect(headerIsMarkdown("document.markdown with some description")).toBe(
true,
);
expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true);
});
// Test non-markdown cases
it("should not identify non-markdown headers", () => {
expect(headerIsMarkdown("javascript")).toBe(false);
expect(headerIsMarkdown("typescript")).toBe(false);
expect(headerIsMarkdown("plain")).toBe(false);
expect(headerIsMarkdown("python")).toBe(false);
});
// Test edge cases
it("should handle edge cases correctly", () => {
expect(headerIsMarkdown("")).toBe(false);
expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md"
expect(headerIsMarkdown("readme md")).toBe(true);
expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension
});
// Test case sensitivity
it("should respect case sensitivity", () => {
expect(headerIsMarkdown("MD")).toBe(false);
expect(headerIsMarkdown("MARKDOWN")).toBe(false);
expect(headerIsMarkdown("example.MD")).toBe(false);
expect(headerIsMarkdown("lang MD")).toBe(false);
});
// Test with special characters and spacing
it("should handle special characters and spacing correctly", () => {
expect(headerIsMarkdown(" md")).toBe(true); // Space before "md"
expect(headerIsMarkdown("md ")).toBe(true); // Space after "md"
expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix
expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix
});
});
test("isMarkdownFile correctly identifies markdown files", () => {
// Should return true for markdown files
expect(isMarkdownFile("test.md")).toBe(true);
expect(isMarkdownFile("path/to/file.markdown")).toBe(true);
expect(isMarkdownFile("README.md")).toBe(true);
describe("isMarkdownFile", () => {
it("should identify markdown files by .md extension", () => {
expect(isMarkdownFile("README.md")).toBe(true);
expect(isMarkdownFile("docs/guide.md")).toBe(true);
expect(isMarkdownFile("/path/to/file.md")).toBe(true);
});
// Should return false for non-markdown files
expect(isMarkdownFile("test.js")).toBe(false);
expect(isMarkdownFile("script.ts")).toBe(false);
expect(isMarkdownFile("")).toBe(false);
expect(isMarkdownFile(undefined)).toBe(false);
it("should identify markdown files by .markdown extension", () => {
expect(isMarkdownFile("README.markdown")).toBe(true);
expect(isMarkdownFile("docs/guide.markdown")).toBe(true);
expect(isMarkdownFile("/path/to/file.markdown")).toBe(true);
});
it("should identify markdown files by .gfm extension", () => {
expect(isMarkdownFile("README.gfm")).toBe(true);
expect(isMarkdownFile("docs/guide.gfm")).toBe(true);
expect(isMarkdownFile("/path/to/file.gfm")).toBe(true);
});
it("should handle case insensitive extensions", () => {
expect(isMarkdownFile("README.MD")).toBe(true);
expect(isMarkdownFile("guide.MARKDOWN")).toBe(true);
expect(isMarkdownFile("file.GFM")).toBe(true);
});
it("should return false for non-markdown files", () => {
expect(isMarkdownFile("script.js")).toBe(false);
expect(isMarkdownFile("style.css")).toBe(false);
expect(isMarkdownFile("data.json")).toBe(false);
expect(isMarkdownFile("document.txt")).toBe(false);
});
it("should return false for undefined or empty filepath", () => {
expect(isMarkdownFile(undefined)).toBe(false);
expect(isMarkdownFile("")).toBe(false);
});
it("should return false for files without extensions", () => {
expect(isMarkdownFile("README")).toBe(false);
expect(isMarkdownFile("Dockerfile")).toBe(false);
});
it("should handle files with multiple dots", () => {
expect(isMarkdownFile("file.backup.md")).toBe(true);
expect(isMarkdownFile("config.test.js")).toBe(false);
});
});
test("MarkdownBlockStateTracker correctly tracks nested markdown blocks", () => {
const lines = [
"# Header",
"",
"Some text",
"",
"```md",
"Nested markdown content",
"```javascript",
"function test() {",
" return true;",
"}",
"```",
"More nested markdown",
"```",
"",
"End of file",
];
describe("MarkdownBlockStateTracker", () => {
it("should initialize correctly with empty lines", () => {
const tracker = new MarkdownBlockStateTracker([]);
expect(tracker.shouldStopAtPosition(0)).toBe(false);
});
const stateTracker = new MarkdownBlockStateTracker(lines);
it("should initialize correctly with non-markdown lines", () => {
const tracker = new MarkdownBlockStateTracker([
"const x = 5;",
"console.log(x);",
]);
expect(tracker.shouldStopAtPosition(0)).toBe(false);
expect(tracker.shouldStopAtPosition(1)).toBe(false);
});
// First backtick closure is within nested block (not markdown end)
expect(stateTracker.shouldStopAtPosition(10)).toBe(false);
it("should detect simple markdown blocks", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"# Title",
"```",
]);
expect(tracker.shouldStopAtPosition(0)).toBe(false); // Opening
expect(tracker.shouldStopAtPosition(1)).toBe(false); // Content
expect(tracker.shouldStopAtPosition(2)).toBe(true); // Closing
});
// This is the backtick that closes the outer markdown block
expect(stateTracker.shouldStopAtPosition(12)).toBe(true);
it("should handle nested code blocks within markdown", () => {
const tracker = new MarkdownBlockStateTracker([
"```md",
"Here's some code:",
"```javascript",
"console.log('hello');",
"```",
"More content",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening
expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing
expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing
});
it("should handle multiple bare backticks", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"Content with ```inline``` code",
"```",
"More content",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(false); // First bare backticks
expect(tracker.shouldStopAtPosition(4)).toBe(true); // Last bare backticks
});
it("should handle non-markdown code blocks", () => {
const tracker = new MarkdownBlockStateTracker([
"```javascript",
"console.log('hello');",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Not a markdown block
});
it("should handle mixed markdown types", () => {
const tracker = new MarkdownBlockStateTracker([
"```gfm",
"# GitHub Flavored Markdown",
"```",
]);
expect(tracker.shouldStopAtPosition(2)).toBe(true);
});
it("should handle state persistence across multiple calls", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"# Documentation",
"```typescript",
"interface Config {}",
"```",
"Final notes",
"```",
]);
// Process incrementally
expect(tracker.shouldStopAtPosition(2)).toBe(false); // Inner opening
expect(tracker.shouldStopAtPosition(4)).toBe(false); // Inner closing
expect(tracker.shouldStopAtPosition(6)).toBe(true); // Outer closing
});
it("should handle lines that are not closing backticks", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"Regular content line",
"```",
]);
expect(tracker.shouldStopAtPosition(1)).toBe(false); // Not backticks
});
it("should provide access to trimmed lines", () => {
const tracker = new MarkdownBlockStateTracker([
" ```markdown ",
" # Title ",
" ``` ",
]);
const trimmedLines = tracker.getTrimmedLines();
expect(trimmedLines).toEqual(["```markdown", "# Title", "```"]);
});
it("should identify bare backtick lines correctly", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"```",
"content",
"```",
]);
expect(tracker.isBareBacktickLine(0)).toBe(false); // Has language
expect(tracker.isBareBacktickLine(1)).toBe(true); // Bare backticks
expect(tracker.isBareBacktickLine(2)).toBe(false); // Content
expect(tracker.isBareBacktickLine(3)).toBe(true); // Bare backticks
});
it("should count remaining bare backticks correctly", () => {
const tracker = new MarkdownBlockStateTracker([
"```markdown",
"```",
"content",
"```",
"more content",
"```",
]);
expect(tracker.getRemainingBareBackticksAfter(0)).toBe(3); // After opening
expect(tracker.getRemainingBareBackticksAfter(1)).toBe(2); // After first bare
expect(tracker.getRemainingBareBackticksAfter(3)).toBe(1); // After second bare
expect(tracker.getRemainingBareBackticksAfter(5)).toBe(0); // After last bare
});
});
test("MarkdownBlockStateTracker handles simple code blocks correctly", () => {
const lines = [
"Some code:",
"",
"```javascript",
"function test() {",
" return true;",
"}",
"```",
"",
"More text",
];
describe("collectAllLines", () => {
async function* createAsyncGenerator<T>(items: T[]): AsyncGenerator<T> {
for (const item of items) {
yield item;
}
}
const stateTracker = new MarkdownBlockStateTracker(lines);
it("should collect all lines from a stream", async () => {
const stream = createAsyncGenerator(["line1", "line2", "line3"]);
const result = await collectAllLines(stream);
expect(result).toEqual(["line1", "line2", "line3"]);
});
// This is just a simple code block, not nested markdown
expect(stateTracker.shouldStopAtPosition(6)).toBe(false);
it("should handle empty streams", async () => {
const stream = createAsyncGenerator([]);
const result = await collectAllLines(stream);
expect(result).toEqual([]);
});
it("should handle streams with mixed types", async () => {
const stream = createAsyncGenerator([1, "text", null, true]);
const result = await collectAllLines(stream);
expect(result).toEqual([1, "text", null, true]);
});
it("should handle streams with empty strings", async () => {
const stream = createAsyncGenerator(["", "line2", "", "line4"]);
const result = await collectAllLines(stream);
expect(result).toEqual(["", "line2", "", "line4"]);
});
it("should handle large streams", async () => {
const largeArray = Array.from({ length: 1000 }, (_, i) => `line${i}`);
const stream = createAsyncGenerator(largeArray);
const result = await collectAllLines(stream);
expect(result).toEqual(largeArray);
});
it("should handle object streams", async () => {
const objects = [
{ type: "new", line: "const x = 5;" },
{ type: "old", line: "let y = 10;" },
];
const stream = createAsyncGenerator(objects);
const result = await collectAllLines(stream);
expect(result).toEqual(objects);
});
});

View file

@ -1,8 +1,5 @@
import { LineStream } from "../diff/util";
import {
isMarkdownFile,
MarkdownBlockStateTracker
} from "./markdownUtils";
import { isMarkdownFile, MarkdownBlockStateTracker } from "./markdownUtils";
/**
* Determines if we should stop at a markdown block based on nested markdown logic.

View file

@ -1,67 +0,0 @@
import { headerIsMarkdown } from "./headerIsMarkdown";
describe("headerIsMarkdown", () => {
// Test exact match with common Markdown identifiers
it("should identify exact matches with common Markdown identifiers", () => {
expect(headerIsMarkdown("md")).toBe(true);
expect(headerIsMarkdown("markdown")).toBe(true);
expect(headerIsMarkdown("gfm")).toBe(true);
expect(headerIsMarkdown("github-markdown")).toBe(true);
});
// Test identifiers preceded by a space
it("should identify identifiers preceded by a space", () => {
expect(headerIsMarkdown("lang md")).toBe(true);
expect(headerIsMarkdown("something markdown")).toBe(true);
expect(headerIsMarkdown("language gfm")).toBe(true);
expect(headerIsMarkdown("spec github-markdown")).toBe(true);
});
// Test file extensions
it("should identify file names with markdown extensions", () => {
expect(headerIsMarkdown("example.md")).toBe(true);
expect(headerIsMarkdown("document.markdown")).toBe(true);
expect(headerIsMarkdown("readme.gfm")).toBe(true);
});
// Test more complex cases with extensions
it("should identify file names with markdown extensions followed by other text", () => {
expect(headerIsMarkdown("example.md additional text")).toBe(true);
expect(headerIsMarkdown("document.markdown with some description")).toBe(
true,
);
expect(headerIsMarkdown("readme.gfm v2.0")).toBe(true);
});
// Test non-markdown cases
it("should not identify non-markdown headers", () => {
expect(headerIsMarkdown("javascript")).toBe(false);
expect(headerIsMarkdown("typescript")).toBe(false);
expect(headerIsMarkdown("plain")).toBe(false);
expect(headerIsMarkdown("python")).toBe(false);
});
// Test edge cases
it("should handle edge cases correctly", () => {
expect(headerIsMarkdown("")).toBe(false);
expect(headerIsMarkdown("mdx")).toBe(false); // Similar but not exactly "md"
expect(headerIsMarkdown("readme md")).toBe(true);
expect(headerIsMarkdown("md.js")).toBe(false); // "md" is not the extension
});
// Test case sensitivity
it("should respect case sensitivity", () => {
expect(headerIsMarkdown("MD")).toBe(false);
expect(headerIsMarkdown("MARKDOWN")).toBe(false);
expect(headerIsMarkdown("example.MD")).toBe(false);
expect(headerIsMarkdown("lang MD")).toBe(false);
});
// Test with special characters and spacing
it("should handle special characters and spacing correctly", () => {
expect(headerIsMarkdown(" md")).toBe(true); // Space before "md"
expect(headerIsMarkdown("md ")).toBe(true); // Space after "md"
expect(headerIsMarkdown("hello-md")).toBe(false); // "md" with hyphen prefix
expect(headerIsMarkdown("markdown:")).toBe(false); // "markdown" with suffix
});
});

View file

@ -1,26 +0,0 @@
/**
* Determines if a given header string represents Markdown content.
*
* The function checks various patterns to identify Markdown headers:
* - Exact match with common Markdown identifiers (md, markdown, gfm, github-markdown)
* - Contains these identifiers preceded by a space
* - First word has a file extension of md, markdown, or gfm
*
* @param header - The string to check for Markdown indicators
* @returns True if the header represents Markdown content, false otherwise
*/
export function headerIsMarkdown(header: string): boolean {
return (
header === "md" ||
header === "markdown" ||
header === "gfm" ||
header === "github-markdown" ||
header.includes(" md") ||
header.includes(" markdown") ||
header.includes(" gfm") ||
header.includes(" github-markdown") ||
header.split(" ")[0]?.split(".").pop() === "md" ||
header.split(" ")[0]?.split(".").pop() === "markdown" ||
header.split(" ")[0]?.split(".").pop() === "gfm"
);
}

View file

@ -7,48 +7,10 @@
Note, this was benchmarked at sub-millisecond
*/
import { headerIsMarkdown } from "./headerIsMarkdown";
/**
* Optimized state tracker for markdown patch operations to avoid recomputing on each call.
*/
class MarkdownPatchStateTracker {
private trimmedLines: string[];
private bareBacktickPositions: number[];
constructor(lines: string[]) {
this.trimmedLines = lines.map((l) => l.trim());
// Pre-compute positions of all bare backtick lines for faster lookup
this.bareBacktickPositions = [];
for (let i = 0; i < this.trimmedLines.length; i++) {
if (this.trimmedLines[i].match(/^`+$/)) {
this.bareBacktickPositions.push(i);
}
}
}
/**
* Efficiently determines if there are remaining bare backticks after the given position.
*/
getRemainingBareBackticksAfter(currentIndex: number): number {
return this.bareBacktickPositions.filter((pos) => pos > currentIndex)
.length;
}
/**
* Checks if the line at the given index is a bare backtick line.
*/
isBareBacktickLine(index: number): boolean {
return this.bareBacktickPositions.includes(index);
}
/**
* Gets the trimmed lines array.
*/
getTrimmedLines(): string[] {
return this.trimmedLines;
}
}
import {
headerIsMarkdown,
MarkdownBlockStateTracker,
} from "../../../../../core/utils/markdownUtils";
export const patchNestedMarkdown = (source: string): string => {
// Early return if no markdown codeblock pattern is found (including GitHub variants)
@ -59,7 +21,7 @@ export const patchNestedMarkdown = (source: string): string => {
const lines = source.split("\n");
// Use optimized state tracker for efficient bare backtick analysis
const stateTracker = new MarkdownPatchStateTracker(lines);
const stateTracker = new MarkdownBlockStateTracker(lines);
const trimmedLines = stateTracker.getTrimmedLines();
for (let i = 0; i < trimmedLines.length; i++) {