From 8077053100351d9396f68507466da9d5b3cceb7f Mon Sep 17 00:00:00 2001 From: Johannes Kirschbauer Date: Wed, 10 Jul 2024 16:57:13 +0200 Subject: [PATCH] Webview: improve error debug abilities --- pkgs/webview-ui/app/src/api.ts | 18 ++++++++++++++++++ pkgs/webview-ui/app/util.ts | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) create mode 100644 pkgs/webview-ui/app/util.ts diff --git a/pkgs/webview-ui/app/src/api.ts b/pkgs/webview-ui/app/src/api.ts index fd4d5dec9..a3c342863 100644 --- a/pkgs/webview-ui/app/src/api.ts +++ b/pkgs/webview-ui/app/src/api.ts @@ -94,12 +94,30 @@ type PyApi = { }; }; +function download(filename: string, text: string) { + const element = document.createElement("a"); + element.setAttribute( + "href", + "data:text/plain;charset=utf-8," + encodeURIComponent(text) + ); + element.setAttribute("download", filename); + + element.style.display = "none"; + document.body.appendChild(element); + + element.click(); + + document.body.removeChild(element); +} + const deserialize = (fn: (response: T) => void) => (str: string) => { try { fn(JSON.parse(str) as T); } catch (e) { + console.log("Error parsing JSON: ", e); + console.log({ download: () => download("error.json", str) }); console.error(str); alert(`Error parsing JSON: ${e}`); } diff --git a/pkgs/webview-ui/app/util.ts b/pkgs/webview-ui/app/util.ts new file mode 100644 index 000000000..eaeeab027 --- /dev/null +++ b/pkgs/webview-ui/app/util.ts @@ -0,0 +1,33 @@ +export function isValidHostname(value: string | null | undefined) { + if (typeof value !== "string") return false; + + const validHostnameChars = /^[a-zA-Z0-9-.]{1,253}\.?$/g; + + if (!validHostnameChars.test(value)) { + return false; + } + + if (value.endsWith(".")) { + value = value.slice(0, value.length - 1); + } + + if (value.length > 253) { + return false; + } + + const labels = value.split("."); + + const isValid = labels.every(function (label) { + const validLabelChars = /^([a-zA-Z0-9-]+)$/g; + + const validLabel = + validLabelChars.test(label) && + label.length < 64 && + !label.startsWith("-") && + !label.endsWith("-"); + + return validLabel; + }); + + return isValid; +}