about summary refs log tree commit diff
path: root/src/lib/strings/url-helpers.ts
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/strings/url-helpers.ts')
-rw-r--r--src/lib/strings/url-helpers.ts30
1 files changed, 30 insertions, 0 deletions
diff --git a/src/lib/strings/url-helpers.ts b/src/lib/strings/url-helpers.ts
index 20c3fabbc..ad194714a 100644
--- a/src/lib/strings/url-helpers.ts
+++ b/src/lib/strings/url-helpers.ts
@@ -372,3 +372,33 @@ export function getServiceAuthAudFromUrl(url: string | URL): string | null {
   }
   return `did:web:${hostname}`
 }
+
+// passes URL.parse, and has a TLD etc
+export function definitelyUrl(maybeUrl: string) {
+  try {
+    if (maybeUrl.endsWith('.')) return null
+
+    // Prepend 'https://' if the input doesn't start with a protocol
+    if (!maybeUrl.startsWith('https://') && !maybeUrl.startsWith('http://')) {
+      maybeUrl = 'https://' + maybeUrl
+    }
+
+    const url = new URL(maybeUrl)
+
+    // Extract the hostname and split it into labels
+    const hostname = url.hostname
+    const labels = hostname.split('.')
+
+    // Ensure there are at least two labels (e.g., 'example' and 'com')
+    if (labels.length < 2) return null
+
+    const tld = labels[labels.length - 1]
+
+    // Check that the TLD is at least two characters long and contains only letters
+    if (!/^[a-z]{2,}$/i.test(tld)) return null
+
+    return url.toString()
+  } catch {
+    return null
+  }
+}