Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
function process_link(raw_data) {
const DESCRIPTION_PREFIX = ' - ';
validate(!!raw_data.url, "URL shouldn't be empty");
validate(!!raw_data.texts.inside, "URL text shouldn't be empty");
if( ! normalize_url.is_url(raw_data.url) ) {
return null;
}
// validate(raw_data.texts.before==='', "URL shouldn't be preceded by any text");
if( raw_data.texts.before!=='' ) {
return null;
}
validate(validator.isURL(raw_data.url,{allow_underscores: true}), "Doesn't seem to be an URL: `"+raw_data.url+"`");
const resource_url = raw_data.url;
const dn = normalize_url(resource_url).split('/')[0];
validate(validator.isFQDN(dn), "Doesn't seem to be a valid domain: `"+dn+"`");
validate(tlds.includes(dn.split('.').slice(-1)[0]), "Doesn't seem to be a valid TLD for: `"+dn+"`");
const title = raw_data.texts.inside;
let description = raw_data.texts.after;
if( description.startsWith(DESCRIPTION_PREFIX) ) {
description = description.slice(DESCRIPTION_PREFIX.length);
}
delete raw_data;
return {
resource_url,
title,
description,
};
function validate(passed, msg){
function validate_normalized_url(val, {Thing}) {
const dn = val.split('/')[0];
const dn_msg = "Domain name `"+dn+"`"+(dn!==val?" (of `"+val+"`)":"");
if( ! dn.includes('.') ) {
throw new Thing.ValidationError(dn_msg+" is missing a dot. The domain name needs to have at least one dot like in `example.org`.");
}
if( ! validator.isFQDN(dn) ) {
throw new Thing.ValidationError(dn_msg+" doesn't seem to exist.");
}
const tld = dn.split('.').slice(-1)[0];
if( ! tlds.includes(tld) ) {
throw new Thing.ValidationError("The root `"+tld+"` (in the domain name `"+dn+"`"+(dn!==val?(" of `"+val+"`"):"")+") doesn't seem to exist.");
}
if( val.endsWith('/') ) {
return false;
}
return true;
}
return matches.reduce((urls, match) => {
if (!protocolRegex.test(match)) {
match = `https://${match}`;
}
let matchUrl: url.URL;
try {
matchUrl = new url.URL(match);
} catch (e) {
return urls;
}
const hostnameParts = matchUrl.hostname.split(".");
const tld = hostnameParts[hostnameParts.length - 1];
if (tlds.includes(tld)) {
urls.push(matchUrl);
}
return urls;
}, []);
}