Skip to content
// Clean the incoming lead and work out which website to look at.
const FREE_MAIL = ['gmail.com', 'yahoo.com', 'hotmail.com', 'outlook.com', 'icloud.com', 'aol.com', 'proton.me', 'protonmail.com', 'live.com', 'msn.com'];
const req = $('Enrich Lead').first().json;
const b = req.body ?? {};

const email = String(b.email ?? '').trim().toLowerCase();
const emailDomain = email.includes('@') ? email.split('@')[1] : '';
const freeEmail = FREE_MAIL.includes(emailDomain);

let website = String(b.website ?? '').trim();
if (!website && emailDomain && !freeEmail) website = emailDomain; // business email → guess the site
if (website && !/^https?:\/\//i.test(website)) website = 'https://' + website;

// Hostname without www (a regex: the Code sandbox may not provide URL())
const domain = website ? website.replace(/^https?:\/\//i, '').split(/[/:?#]/)[0].replace(/^www\./, '').toLowerCase() : '';

return [{
  json: {
    email,
    name: String(b.name ?? '').trim(),
    company: String(b.company ?? '').trim(),
    website,
    domain: domain || (freeEmail ? '' : emailDomain),
    free_email: freeEmail,
    valid: Boolean(email || website),
    dry_run: req.query?.dry_run === 'true',
    use_ai: req.query?.dry_run !== 'true' && req.query?.ai !== 'false',
  },
}];