diff --git a/src/lib/utils/embed.ts b/src/lib/utils/embed.ts index 73ce7fbfe..b2a9255ea 100644 --- a/src/lib/utils/embed.ts +++ b/src/lib/utils/embed.ts @@ -74,7 +74,7 @@ export function getEmbedSettings(searchParams: URLSearchParams): EmbedSettings { return embedSettings; } -function truthy( +export function truthy( value: string | number | boolean | null | undefined, ): boolean | number { if (value === undefined) return false; @@ -82,7 +82,16 @@ function truthy( if (typeof value === "boolean") return value; if (typeof value === "number") return value; - if (typeof value === "string") return JSON.parse(value); + if (typeof value === "string") { + try { + const jsonValue = JSON.parse(value); + if (typeof jsonValue === "boolean") return jsonValue; + if (typeof jsonValue === "number") return jsonValue; + return true; + } catch { + return false; + } + } return false; } diff --git a/src/lib/utils/tests/embed.test.ts b/src/lib/utils/tests/embed.test.ts index 216a3325b..fb47d996b 100644 --- a/src/lib/utils/tests/embed.test.ts +++ b/src/lib/utils/tests/embed.test.ts @@ -6,6 +6,7 @@ import { defaultSettings, isEmbed, reroute, + truthy, } from "../embed"; describe("embed settings", () => { @@ -78,3 +79,34 @@ describe("embed utilities", () => { } }); }); + +test("truthy", () => { + // Test undefined + expect(truthy(undefined)).toBe(false); + + // Test null + expect(truthy(null)).toBe(false); + + // Test boolean inputs + expect(truthy(true)).toBe(true); + expect(truthy(false)).toBe(false); + + // Test number inputs + expect(truthy(1)).toBe(1); + expect(truthy(0)).toBe(0); + + // Test string inputs for boolean values + expect(truthy("true")).toBe(true); + expect(truthy("false")).toBe(false); + + // Test string inputs for number values + expect(truthy("1")).toBe(1); + expect(truthy("0")).toBe(0); + + // Test JSON parsing + expect(truthy('{"key": "value"}')).toEqual(true); + expect(truthy("[1, 2, 3]")).toEqual(true); + + // Test invalid JSON string + expect(truthy("invalid")).toBe(false); +});