/** * Inline tests for the two text helpers that were each defined twice. * * `escapeLike` is a security helper: without it, a person's own search text * becomes a LIKE pattern. It is four characters of code and exactly the kind of * thing that gets "simplified" by someone who has not thought about `\`. * * `decodeEntities` had two copies that disagreed about ORDER, and the * disagreement was a real defect — see the `&lt;` case below. * * Run: npx tsx scripts/test/text-helpers.ts */ import { escapeLike } from "@/lib/sql-escape"; import { decodeEntities, escapeHtml } from "@/lib/escape-html"; function assert(condition: boolean, message: string): void { if (!condition) throw new Error(message); } let passed = 0; const check = (label: string, fn: () => void) => { fn(); passed += 1; console.log(` ✓ ${label}`); }; // ------------------------------------------------------------- escapeLike check("a percent in the search text matches a percent, not everything", () => { assert(escapeLike("100%") === "100\\%", `got ${escapeLike("100%")}`); }); check("an underscore matches an underscore, not any character", () => { assert(escapeLike("a_b") === "a\\_b", `got ${escapeLike("a_b")}`); }); check("the escape character itself is escaped", () => { // If `\` were left alone it would consume whatever followed it, so "\%" // would still reach the database as a live wildcard. assert(escapeLike("\\") === "\\\\", `got ${JSON.stringify(escapeLike("\\"))}`); assert(escapeLike("\\%") === "\\\\\\%", `got ${JSON.stringify(escapeLike("\\%"))}`); }); check("ordinary text is untouched", () => { assert(escapeLike("Elena Ruiz") === "Elena Ruiz", "escaped a name that needed nothing"); assert(escapeLike("") === "", "empty input changed"); }); // --------------------------------------------------------- decodeEntities check("the common entities decode", () => { assert(decodeEntities("A & B") === "A & B", "ampersand"); assert(decodeEntities("<tag>") === "", "angle brackets"); assert(decodeEntities(""q"") === '"q"', "double quote"); assert(decodeEntities("it's") === "it's", "'"); assert(decodeEntities("it's") === "it's", "'"); assert(decodeEntities("it's") === "it's", "'"); assert(decodeEntities("a b") === "a b", "non-breaking space"); }); check("& decodes LAST, so an escaped entity is not double-decoded", () => { // The whole reason one of the two copies was wrong. A site that deliberately // shows the text "<" writes "&lt;". Decoding & first turns that // into "<" and then into "<" — text the author escaped becoming markup. assert(decodeEntities("&lt;") === "<", `double-decoded: ${decodeEntities("&lt;")}`); assert(decodeEntities("&amp;") === "&", "double-decoded a nested ampersand"); }); check("a CDATA wrapper from an RSS feed is unwrapped", () => { assert(decodeEntities("") === "Hi & bye", "CDATA not unwrapped"); }); check("escapeHtml then decodeEntities round-trips", () => { for (const original of ["A & B", "