Fix up validatePageName routine (#912)

* Fix up validatePageName routine

File extensions can contain numbers too.
My main motivation was to enable myself hosting `woff2` files right from
my space, like I do for `ttf` files.

Also added some tests.

* Fix up typo and add more numeric samples

* Add missing semicolons

(sorry, I'm not really js/ts programmer)

* Make linter happy
pull/917/head
Semyon Novikov 2024-07-03 10:50:26 +05:00 committed by GitHub
parent 1e58d220eb
commit 09e7f1f906
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 23 additions and 3 deletions

View File

@ -1,5 +1,5 @@
import { encodePageRef, parsePageRef } from "./page_ref.ts";
import { assertEquals } from "$std/testing/asserts.ts";
import { encodePageRef, parsePageRef, validatePageName } from "./page_ref.ts";
import { assertEquals, assertThrows, AssertionError } from "$std/testing/asserts.ts";
Deno.test("Page utility functions", () => {
// Base cases
@ -26,4 +26,24 @@ Deno.test("Page utility functions", () => {
assertEquals(encodePageRef({ page: "foo", pos: 10 }), "foo@10");
assertEquals(encodePageRef({ page: "foo", anchor: "bar" }), "foo$bar");
assertEquals(encodePageRef({ page: "foo", header: "bar" }), "foo#bar");
// Page name validation
try {
validatePageName("perfectly fine page name");
} catch (error) {
throw new AssertionError(`Something is very wrong with the validatePageName function: ${error}`);
}
assertThrows(() => validatePageName(""), Error);
assertThrows(() => validatePageName(".hidden"), Error);
assertThrows(() => validatePageName(".."), Error);
for (const extension of ["md", "txt", "exe", "cc", "ts"]) {
assertThrows(() => validatePageName(`extensions-are-not-welcome.${extension}`), Error);
}
for (const extension of ["db2", "woff2", "sqlite3", "42", "0"]) {
assertThrows(() => validatePageName(`extensions-can-contain-numbers-too.${extension}`), Error);
}
});

View File

@ -6,7 +6,7 @@ export function validatePageName(name: string) {
if (name.startsWith(".")) {
throw new Error("Page name cannot start with a '.'");
}
if (/\.[a-zA-Z]+$/.test(name)) {
if (/\.[a-zA-Z0-9]+$/.test(name)) {
throw new Error("Page name can not end with a file extension");
}
}