diff --git a/package.json b/package.json index b60b6831bc..c25f82af03 100644 --- a/package.json +++ b/package.json @@ -345,7 +345,7 @@ "@types/utf8": "^3.0.3", "@types/validator": "^13.15.10", "@types/yauzl": "^2.10.3", - "@types/yazl": "^2.4.6", + "@types/yazl": "^3.3.1", "@vitest/ui": "^4.1.8", "browserslist-to-esbuild": "^1.2.0", "concurrently": "^8.2.2", diff --git a/server/models/helpers/HTMLHelper.ts b/server/models/helpers/HTMLHelper.ts index a8fb468f03..a2ecae7578 100644 --- a/server/models/helpers/HTMLHelper.ts +++ b/server/models/helpers/HTMLHelper.ts @@ -30,24 +30,46 @@ export default class HTMLHelper { contentType: string | null | undefined, buffer: Buffer ): string | null { - if (!contentType?.startsWith("image/")) { - return null; - } - if (buffer.length === 0 || buffer.length > HTMLHelper.maxInlineImageSize) { - return null; - } - - const pattern = new RegExp(escapeRegExp(redirectUrl), "g"); - if ((html.match(pattern)?.length ?? 0) !== 1) { + if ( + !HTMLHelper.canInlineImage(html, redirectUrl, contentType, buffer.length) + ) { return null; } return html.replace( - pattern, + new RegExp(escapeRegExp(redirectUrl), "g"), `data:${contentType};base64,${buffer.toString("base64")}` ); } + /** + * Whether an image meets the criteria for inlining, determined from its + * size alone so that callers can avoid reading images into memory that + * would be written to the export as an external file regardless. + * + * @param html The HTML content referencing the image. + * @param redirectUrl The redirect URL of the image within the HTML. + * @param contentType The content type of the image, e.g. "image/png". + * @param size The size of the image in bytes. + * @returns True if the image is a candidate for inlining. + */ + public static canInlineImage( + html: string, + redirectUrl: string, + contentType: string | null | undefined, + size: number + ): boolean { + if (!contentType?.startsWith("image/")) { + return false; + } + if (size === 0 || size > HTMLHelper.maxInlineImageSize) { + return false; + } + + const pattern = new RegExp(escapeRegExp(redirectUrl), "g"); + return (html.match(pattern)?.length ?? 0) === 1; + } + /** * Move CSS styles from