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
5 changes: 5 additions & 0 deletions .changeset/quiet-paths-smile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@react-pdf/image": patch
---

Replace deprecated url.parse usage in local image path resolution.
36 changes: 22 additions & 14 deletions packages/image/src/resolve.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from 'fs';
import url from 'url';
import { fileURLToPath } from 'url';
import path from 'path';

import PNG from './png';
Expand Down Expand Up @@ -36,22 +36,30 @@ const getAbsoluteLocalPath = (src: string) => {
throw new Error('Cannot check local paths in client-side environment');
}

const {
protocol,
auth,
host,
port,
hostname,
path: pathname,
} = url.parse(src);
try {
const parsed = new URL(src);

const absolutePath = pathname ? path.resolve(src) : undefined;
if (
parsed.protocol !== 'file:' ||
parsed.username ||
parsed.password ||
parsed.host
) {
return undefined;
}

if ((protocol && protocol !== 'file:') || auth || host || port || hostname) {
return undefined;
}
return fileURLToPath(parsed.href);
} catch {
if (!src) {
return undefined;
}

return absolutePath;
if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.test(src)) {
return undefined;
}

return path.resolve(src);
}
};

const fetchLocalFile = (src: LocalImageSrc): Promise<Buffer> =>
Expand Down
11 changes: 11 additions & 0 deletions packages/image/tests/resolve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,17 @@ describe('image resolveImage', () => {
expect(image?.height).toBeGreaterThan(0);
});

test('Should render a local image from file URL', async () => {
const absolutePath = path.join(__dirname, './assets/test.jpg');
const image = await resolveImage({
uri: url.pathToFileURL(absolutePath).href,
});

expect(image?.data).toBeTruthy();
expect(image?.width).toBeGreaterThan(0);
expect(image?.height).toBeGreaterThan(0);
});

test('Should render a local image from relative path', async () => {
const image = await resolveImage({
uri: 'packages/layout/tests/assets/test.jpg',
Expand Down