Skip to content

Commit

Permalink
fix: ensure file paths are resolved correctly for diagram generation
Browse files Browse the repository at this point in the history
  - modify index.js to resolve file paths relative to the current working directory
  - improve error logging to specify absolute file paths
  - adjust tests in index.test.js for the updated path resolution logic
  - update documentation in readme.md to include marker setup instructions
  • Loading branch information
tobiasbueschel committed Nov 30, 2024
1 parent 1f56fc7 commit 35827a2
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 21 deletions.
22 changes: 12 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,20 @@ export default async function jsonSchemaToDiagram(options) {
throw new Error("Missing required options");
}

const fileToUpdatePath = path.join(__dirname, filePath);
const fileToUpdatePath = path.isAbsolute(filePath)
? filePath
: path.resolve(process.cwd(), filePath);

try {
const data = await readFile(fileToUpdatePath, "utf8");

const regex = new RegExp(`${startMarker}[\\s\\S]*?${endMarker}`, "g");

if (!regex.test(data)) {
console.error(`Markers not found in ${fileToUpdatePath}`);
return;
}

const {
object: { mermaidDiagramString },
} = await generateObject({
Expand All @@ -75,21 +84,14 @@ export default async function jsonSchemaToDiagram(options) {

const diagramContent = `\`\`\`mermaid\n${mermaidDiagramString}\n\`\`\`\n`;

const regex = new RegExp(`${startMarker}[\\s\\S]*?${endMarker}`, "g");

if (!regex.test(data)) {
console.error(`Markers not found in ${filePath}.`);
return;
}

const newContent = data.replace(
regex,
`${startMarker}\n${diagramContent}${endMarker}`
);

await writeFile(fileToUpdatePath, newContent, "utf8");
console.log(`Diagram successfully updated in ${filePath}`);
console.log(`Diagram successfully updated in ${fileToUpdatePath}`);
} catch (err) {
console.error(`Error processing ${filePath}:`, err);
console.error(`Error processing ${fileToUpdatePath}:`, err);
}
}
30 changes: 20 additions & 10 deletions index.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { describe, beforeEach, it, expect, vi, afterEach } from "vitest";
import path from "path";
import { fs, vol } from "memfs";
import { fs, Volume } from "memfs";

const vol = new Volume();

vi.mock("node:fs");
vi.mock("node:fs/promises");
Expand All @@ -9,14 +11,19 @@ describe("jsonSchemaToDiagram", () => {
let jsonSchemaToDiagram;
const startMarker = "<!-- MERMAID_DIAGRAM_START -->";
const endMarker = "<!-- MERMAID_DIAGRAM_END -->";
const resolvedPath = path.resolve(process.cwd(), "./README.md");
const filePath = "./README.md";

beforeEach(async () => {
vi.restoreAllMocks();
process.env.OPENAI_API_KEY = "test-api-key";
vol.reset();

vi.mock("node:fs/promises", async () => {
const memfs = await vi.importActual("memfs");
return memfs.fs.promises;
});

vol.fromJSON({
"./README.md":
resolvedPath:
"<!-- MERMAID_DIAGRAM_START -->\nOld content\n<!-- MERMAID_DIAGRAM_END -->",
});

Expand All @@ -32,6 +39,7 @@ describe("jsonSchemaToDiagram", () => {
});

afterEach(() => {
vol.reset();
vi.restoreAllMocks();
});

Expand All @@ -55,7 +63,6 @@ describe("jsonSchemaToDiagram", () => {
});

it.todo("updates file with generated mermaid diagram", async () => {
const filePath = "./README.md";
const systemPrompt = "test system prompt";
const model = "test model";
const jsonSchema = { tools: [] };
Expand Down Expand Up @@ -83,13 +90,12 @@ describe("jsonSchemaToDiagram", () => {
});

it.todo("logs error if markers are not found in file", async () => {
const filePath = "./README.md";
const systemPrompt = "test system prompt";
const model = "test model";
const jsonSchema = { tools: [] };

vol.fromJSON({
"./README.md": "No markers here",
resolvedPath: "No markers here",
});

vi.spyOn(console, "error").mockImplementation(() => {});
Expand All @@ -109,14 +115,18 @@ describe("jsonSchemaToDiagram", () => {
);
});

it("logs error if there is an error processing the file", async () => {
const filePath = "./README.md";
it("logs error if the LLM fails to generate the diagram", async () => {
const systemPrompt = "test system prompt";
const model = "test model";
const jsonSchema = { tools: [] };

vi.spyOn(console, "error").mockImplementation(() => {});

vi.mock("ai", () => ({
__esModule: true,
generateObject: vi.fn().mockRejectedValue(new Error("Processing failed")),
}));

await jsonSchemaToDiagram({
filePath,
startMarker,
Expand All @@ -127,7 +137,7 @@ describe("jsonSchemaToDiagram", () => {
});

expect(console.error).toHaveBeenCalledWith(
`Error processing ${filePath}:`,
`Error processing ${resolvedPath}:`,
expect.any(Error)
);
});
Expand Down
12 changes: 11 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ npm install --save-dev json-schema-to-diagram

## Usage

1. Add a start and end marker to your README.md file.

```md
## Function Calling Tools - Diagram

<!-- MERMAID_DIAGRAM_START -->
<!-- MERMAID_DIAGRAM_END -->
```

2. Get the JSON schema of your function calling tools and generate the diagram by calling `jsonSchemaToDiagram` with the `jsonSchema` option.

```js
import jsonSchemaToDiagram from "json-schema-to-diagram";

Expand All @@ -62,7 +73,6 @@ const TOOLS = {
filePath: "./README.md",
jsonSchema: TOOLS,
});
console.log("Diagram appended successfully.");
} catch (error) {
console.error("Error appending diagram:", error);
process.exit(1);
Expand Down

0 comments on commit 35827a2

Please sign in to comment.