Skip to content

Commit d8bf56e

Browse files
committed
Fix PDF filename fallback handling
1 parent 1a8be83 commit d8bf56e

2 files changed

Lines changed: 30 additions & 7 deletions

File tree

shared/src/filename-sanitizer.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,20 @@ describe("safePdfFileName", () => {
3838
}),
3939
).toBe("Mueller_Buero.pdf");
4040
});
41+
42+
it("uses the configured fallback when the PDF stem is empty", () => {
43+
expect(
44+
safePdfFileName("!!!.pdf", {
45+
fallbackBase: "Design Resume",
46+
}),
47+
).toBe("Design_Resume.pdf");
48+
});
49+
50+
it("falls back to Unknown when the PDF stem and fallback are both unsafe", () => {
51+
expect(
52+
safePdfFileName("", {
53+
fallbackBase: "!!!",
54+
}),
55+
).toBe("Unknown.pdf");
56+
});
4157
});

shared/src/filename-sanitizer.ts

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -151,15 +151,19 @@ function transliterate(
151151
}).join("");
152152
}
153153

154-
export function safeFilenamePart(
155-
value: string,
156-
options: FilenameOptions = {},
157-
): string {
154+
function sanitizeFilenamePart(value: string, options: FilenameOptions = {}) {
158155
const cleaned = transliterate(value, options.language).replace(
159156
/[^a-z0-9]/gi,
160157
"_",
161158
);
162-
if (cleaned.replace(/_/g, "") === "") return "Unknown";
159+
return cleaned.replace(/_/g, "") === "" ? "" : cleaned;
160+
}
161+
162+
export function safeFilenamePart(
163+
value: string,
164+
options: FilenameOptions = {},
165+
): string {
166+
const cleaned = sanitizeFilenamePart(value, options);
163167
return cleaned || "Unknown";
164168
}
165169

@@ -168,8 +172,11 @@ export function safePdfFileName(
168172
options: PdfFilenameOptions = {},
169173
): string {
170174
const baseValue = value.trim().replace(/\.pdf$/i, "");
171-
const sanitized = safeFilenamePart(baseValue, {
175+
const sanitized = sanitizeFilenamePart(baseValue, {
176+
language: options.language,
177+
}).replace(/^_+|_+$/g, "");
178+
const fallback = sanitizeFilenamePart(options.fallbackBase ?? "Unknown", {
172179
language: options.language,
173180
}).replace(/^_+|_+$/g, "");
174-
return `${sanitized || options.fallbackBase || "Unknown"}.pdf`;
181+
return `${sanitized || fallback || "Unknown"}.pdf`;
175182
}

0 commit comments

Comments
 (0)