Skip to content
Merged
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
5 changes: 5 additions & 0 deletions src/lib/utils/pdfProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,11 @@ export class PDFProcessor {
});
}

// Check for empty PDF (0 pages)
if (images.length === 0) {
throw new Error("PDF has 0 pages. Cannot convert empty PDF to images.");
}
Comment on lines +414 to +417

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# Check if ErrorFactory exists and how it's used
echo "=== Checking for ErrorFactory usage ==="
rg -n "ErrorFactory" --type ts -A 3

echo ""
echo "=== Checking file path and content around the target lines ==="
if [ -f "src/lib/utils/pdfProcessor.ts" ]; then
  echo "File exists, checking content around lines 414-417:"
  sed -n '410,445p' src/lib/utils/pdfProcessor.ts | cat -n
else
  echo "File not found, searching for pdfProcessor:"
  fd pdfProcessor
fi

Repository: juspay/neurolink

Length of output: 15532


🏁 Script executed:

# Check error patterns in src/lib/utils
echo "=== Errors in src/lib/utils with ErrorFactory vs generic Error ==="
rg -n "throw" src/lib/utils/ --type ts -B 1 -A 1 | head -50

Repository: juspay/neurolink

Length of output: 2533


🏁 Script executed:

# Search for all methods in ErrorFactory to see available options
echo "=== ErrorFactory method definitions ==="
sed -n '117,400p' src/lib/utils/errorHandling.ts | grep -E "^\s+(static\s+)?[a-zA-Z]+\(" | head -30

Repository: juspay/neurolink

Length of output: 717


🏁 Script executed:

# Check if there's a generic processingError or conversionError method
rg -n "conversionError|processingError|fileProcessing" src/lib/utils/errorHandling.ts

Repository: juspay/neurolink

Length of output: 42


Replace generic Error with ErrorFactory to comply with coding guidelines.

The throw new Error() on line 416 should use ErrorFactory instead, per the coding guidelines for src/lib/**/*.ts. The most appropriate option is ErrorFactory.invalidParameters("pdf-processor", new Error(...)) to match the validation pattern used elsewhere in the codebase. Alternatively, consider adding a dedicated PDF processing error method to ErrorFactory if PDF-specific error handling is expected to be reused.

The error re-wrapping in the catch block (line 434) is intentional and correct—the original message is preserved within the new context.

🤖 Prompt for AI Agents
In `@src/lib/utils/pdfProcessor.ts` around lines 414 - 417, Replace the plain
throw new Error(...) in the PDF page check with ErrorFactory.invalidParameters
to follow project error patterns: where images.length === 0 currently throws,
construct and throw ErrorFactory.invalidParameters("pdf-processor", new
Error("PDF has 0 pages. Cannot convert empty PDF to images.")); locate this in
the pdfProcessor.ts function that processes PDF pages and ensure the new
ErrorFactory call mirrors the message and type used elsewhere (or add a
dedicated ErrorFactory.pdfProcessing(...) helper if you expect reuse).


const conversionTimeMs = Date.now() - startTime;

logger.info("[PDF→Image] ✅ PDF conversion completed", {
Expand Down
85 changes: 84 additions & 1 deletion test/unit/utils/pdfProcessor.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,90 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi } from "vitest";
import { PDFProcessor } from "../../../src/lib/utils/pdfProcessor.js";

describe("PDFProcessor.convertToImages", () => {
describe("empty PDF validation", () => {
it("should throw error for PDF with 0 pages", async () => {
// Create a valid PDF header buffer that will pass initial validation
const validPdfHeader = Buffer.from(
"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Count 0/Kids[]>>endobj\nxref\n0 3\n0000000000 65535 f\n0000000009 00000 n\n0000000058 00000 n\ntrailer<</Size 3/Root 1 0 R>>\nstartxref\n150\n%%EOF",
);

// Mock pdf-to-img to return an empty async iterator (0 pages)
vi.doMock("pdf-to-img", () => ({
pdf: vi.fn().mockResolvedValue({
[Symbol.asyncIterator]: async function* () {
// Empty iterator - no pages
},
}),
}));

// Re-import to get the mocked version
const { PDFProcessor: MockedPDFProcessor } = await import(
"../../../src/lib/utils/pdfProcessor.js"
);

await expect(
MockedPDFProcessor.convertToImages(validPdfHeader),
).rejects.toThrow("PDF has 0 pages. Cannot convert empty PDF to images.");

vi.doUnmock("pdf-to-img");
});
Comment on lines +6 to +31

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🌐 Web query:

Vitest vi.doMock vi.resetModules module isolation best practices

💡 Result:

Short best-practices for module isolation with vi.doMock / vi.resetModules (Vitest)

  1. Know hoisting vs non-hoisting
  • vi.mock is hoisted (runs before imports). Use it when you want the module mocked for all imports in the file. (v3.vitest.dev)
  1. Use vi.doMock when you need the mock to run at runtime
  • vi.doMock is NOT hoisted and will only affect subsequent dynamic imports. Use it when the mock needs to reference variables defined in the test scope. (vitest.dev)
  1. Reset module cache to isolate module-local state
  • vi.resetModules() clears the module cache so subsequent dynamic imports are re-evaluated; call it in beforeEach or inside vi.hoisted/setup to ensure fresh modules per test. Top-level static imports cannot be re-evaluated. (vitest.dev)
  1. Reset mocks separate from module cache
  • vi.resetModules() does NOT clear mock registry. Use vi.unmock / vi.doUnmock or vi.resetAllMocks()/vi.restoreAllMocks() as appropriate to clear mocks between tests. (vitest.dev)
  1. Prefer dynamic import after reset/mock when you need isolation
  • Pattern: vi.resetModules(); vi.doMock(...) (if non-hoisted mocking needed); then await import('./module') so the import picks up the intended mocked or fresh implementation. (vitest.dev)
  1. Avoid importing the target module earlier (including in setup files)
  • Modules imported in setup files or earlier in the file will be cached and not affected by later doMock/resetModules; if you mock in setup, ensure you manage cache (vi.resetModules()) or avoid pre-importing. Real-world reports show unexpected failures when setup imports block later mocks. (v1.vitest.dev)
  1. For Jest parity / advanced isolation
  • Jest’s isolateModules/isolateModulesAsync provides per-callback registries; Vitest relies on resetModules + dynamic imports and doMock/hoisting semantics instead. Use the dynamic-import pattern for similar isolation. (jestjs.io)

Minimal example pattern

  • beforeEach(() => { vi.resetModules(); vi.resetAllMocks(); })
  • vi.doMock('./dep', () => ({ fn: vi.fn(()=>'x') })) // if non-hoisted needed
  • const mod = await import('./module') // will see mocked dep / fresh module. (vitest.dev)

If you want, I can convert these into copy-paste test examples (Common pitfalls + working examples).

Citations:


Add vi.resetModules() to ensure proper test isolation with dynamic mocks.

The test correctly verifies the exact error message for the 0-page case. However, vi.doUnmock() clears only the mock registry, not the module cache. Without vi.resetModules(), subsequent tests may reuse a cached module from the previous test rather than reimporting with the new mock applied. Add vi.resetModules() before each vi.doMock() to ensure each test gets a fresh module instance.

🔧 Required fix for test isolation
     it("should throw error for PDF with 0 pages", async () => {
       // Create a valid PDF header buffer that will pass initial validation
       const validPdfHeader = Buffer.from(
         "%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Count 0/Kids[]>>endobj\nxref\n0 3\n0000000000 65535 f\n0000000009 00000 n\n0000000058 00000 n\ntrailer<</Size 3/Root 1 0 R>>\nstartxref\n150\n%%EOF",
       );

+      // Reset module registry to ensure clean state
+      vi.resetModules();
+
       // Mock pdf-to-img to return an empty async iterator (0 pages)
       vi.doMock("pdf-to-img", () => ({

Apply the same pattern to the other two tests in this suite.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
it("should throw error for PDF with 0 pages", async () => {
// Create a valid PDF header buffer that will pass initial validation
const validPdfHeader = Buffer.from(
"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Count 0/Kids[]>>endobj\nxref\n0 3\n0000000000 65535 f\n0000000009 00000 n\n0000000058 00000 n\ntrailer<</Size 3/Root 1 0 R>>\nstartxref\n150\n%%EOF",
);
// Mock pdf-to-img to return an empty async iterator (0 pages)
vi.doMock("pdf-to-img", () => ({
pdf: vi.fn().mockResolvedValue({
[Symbol.asyncIterator]: async function* () {
// Empty iterator - no pages
},
}),
}));
// Re-import to get the mocked version
const { PDFProcessor: MockedPDFProcessor } = await import(
"../../../src/lib/utils/pdfProcessor.js"
);
await expect(
MockedPDFProcessor.convertToImages(validPdfHeader),
).rejects.toThrow("PDF has 0 pages. Cannot convert empty PDF to images.");
vi.doUnmock("pdf-to-img");
});
it("should throw error for PDF with 0 pages", async () => {
// Create a valid PDF header buffer that will pass initial validation
const validPdfHeader = Buffer.from(
"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Count 0/Kids[]>>endobj\nxref\n0 3\n0000000000 65535 f\n0000000009 00000 n\n0000000058 00000 n\ntrailer<</Size 3/Root 1 0 R>>\nstartxref\n150\n%%EOF",
);
// Reset module registry to ensure clean state
vi.resetModules();
// Mock pdf-to-img to return an empty async iterator (0 pages)
vi.doMock("pdf-to-img", () => ({
pdf: vi.fn().mockResolvedValue({
[Symbol.asyncIterator]: async function* () {
// Empty iterator - no pages
},
}),
}));
// Re-import to get the mocked version
const { PDFProcessor: MockedPDFProcessor } = await import(
"../../../src/lib/utils/pdfProcessor.js"
);
await expect(
MockedPDFProcessor.convertToImages(validPdfHeader),
).rejects.toThrow("PDF has 0 pages. Cannot convert empty PDF to images.");
vi.doUnmock("pdf-to-img");
});
🤖 Prompt for AI Agents
In `@test/unit/utils/pdfProcessor.test.ts` around lines 6 - 31, Add
vi.resetModules() before calling vi.doMock() in this test to clear the module
cache so importing "../../../src/lib/utils/pdfProcessor.js" picks up the mocked
"pdf-to-img"; specifically, insert vi.resetModules() immediately before
vi.doMock("pdf-to-img", ...) in the test that imports MockedPDFProcessor and
asserts on MockedPDFProcessor.convertToImages, and apply the same change to the
other two tests in this suite that use vi.doMock()/vi.doUnmock() so each test
re-imports a fresh module instance.


it("should succeed for PDF with at least 1 page", async () => {
const validPdfHeader = Buffer.from(
"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Count 1/Kids[3 0 R]>>endobj 3 0 obj<</Type/Page/MediaBox[0 0 612 792]/Parent 2 0 R/Resources<<>>>>endobj\nxref\n0 4\n0000000000 65535 f\n0000000009 00000 n\n0000000058 00000 n\n0000000115 00000 n\ntrailer<</Size 4/Root 1 0 R>>\nstartxref\n200\n%%EOF",
);

// Mock pdf-to-img to return a single page
vi.doMock("pdf-to-img", () => ({
pdf: vi.fn().mockResolvedValue({
[Symbol.asyncIterator]: async function* () {
yield Buffer.from("fake-png-data");
},
}),
}));

const { PDFProcessor: MockedPDFProcessor } = await import(
"../../../src/lib/utils/pdfProcessor.js"
);

const result = await MockedPDFProcessor.convertToImages(validPdfHeader);
expect(result.pageCount).toBe(1);
expect(result.images).toHaveLength(1);

vi.doUnmock("pdf-to-img");
});

it("should provide clear error message mentioning 0 pages", async () => {
const validPdfHeader = Buffer.from(
"%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj 2 0 obj<</Type/Pages/Count 0/Kids[]>>endobj\nxref\n0 3\n0000000000 65535 f\n0000000009 00000 n\n0000000058 00000 n\ntrailer<</Size 3/Root 1 0 R>>\nstartxref\n150\n%%EOF",
);

vi.doMock("pdf-to-img", () => ({
pdf: vi.fn().mockResolvedValue({
[Symbol.asyncIterator]: async function* () {
// Empty iterator
},
}),
}));

const { PDFProcessor: MockedPDFProcessor } = await import(
"../../../src/lib/utils/pdfProcessor.js"
);

try {
await MockedPDFProcessor.convertToImages(validPdfHeader);
expect.fail("Should have thrown an error");
} catch (error) {
const errorMessage = (error as Error).message;
expect(errorMessage).toContain("0 pages");
expect(errorMessage).toContain("empty PDF");
}

vi.doUnmock("pdf-to-img");
});
});

describe("format validation", () => {
// Create a minimal valid PDF buffer for testing
// This is a minimal PDF that won't actually render, but will help test validation
Expand Down
Loading