export function isValidUrl (value) {
const regex =
/https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z]{2,}\b(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)(?:[-a-zA-Z0-9@:%._+~#=?!&/]*)/gi
return regex.test(value)
}
export function isPartialUrl (value) {
return /^https?:\/\/.+/i.test(value)
}
export function normalizeUrl (url) {
try {
return new URL(url).href
} catch (e) {
return url
}
}
export function getUrls (doc, fn) {
const urls = new Set()
function traverse (node) {
if (node.content) node.content.forEach(traverse)
if (node.marks) {
for (const mark of node.marks) {
if (mark.type !== 'link') continue
if (mark.attrs.href !== node.text) {
if (isValidUrl(node.text)) {
fn(node.text)
} else if (isPartialUrl(node.text)) {
fn(null)
continue
}
}
if (isValidUrl(mark.attrs.href)) {
urls.add(normalizeUrl(mark.attrs.href))
}
}
}
}
traverse(doc)
return urls
}