diff --git a/html-esc.js b/html-esc.js index 20a8268..b824b67 100644 --- a/html-esc.js +++ b/html-esc.js @@ -12,6 +12,13 @@ const markSafe = (str) => function htmlSanitize(rawText = "") { if (rawText?.__html_sanitized) return rawText; + if (typeof rawText !== "string") { + console.error( + `Bad interpolated value, expected type "string" received type "${typeof rawText}". Try serializing the value:`, + rawText, + ); + rawText = ""; + } return markSafe(esc(rawText)); } diff --git a/html-esc.test.js b/html-esc.test.js index ad0f5fc..3f5380f 100644 --- a/html-esc.test.js +++ b/html-esc.test.js @@ -42,6 +42,22 @@ test("html - supports interpolation of lists of tagged items", (t) => { `, ); }); +test("html - interpolation of objects is forbidden, console.error but doesn't crash", (t) => { + const mockConsoleError = t.mock.method(console, "error", () => {}); + t.assert.strictEqual( + html`
${{ hello: "world " }}
`.valueOf(), + `
`,
+  );
+  t.assert.strictEqual(mockConsoleError.mock.callCount(), 1);
+  t.assert.deepStrictEqual(mockConsoleError.mock.calls[0].arguments, [
+    'Bad interpolated value, expected type "string" received type "object". Try serializing the value:',
+    {
+      hello: "world ",
+    },
+  ]);
+
+  t.mock.reset();
+});
 test("html - doesn't break on bad payloads", (t) => {
   const badPayload = `">`;
 
diff --git a/package.json b/package.json
index b9bc6e8..5fa2299 100644
--- a/package.json
+++ b/package.json
@@ -9,7 +9,7 @@
   "scripts": {
     "dev": "node serve.js",
     "test": "node --test --experimental-test-coverage",
-    "lint": "npm run format -- -c",
+    "lint": "npm run format -- -c --no-write",
     "format": "prettier --write './**/*.{js,json,yml,md,html}'"
   },
   "homepage": "https://github.com/HugoDF/html-esc",