index.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict';
  2. const Domain = require('./domain');
  3. const Email = require('./email');
  4. const Tlds = require('./tlds');
  5. const internals = {
  6. defaultTlds: { allow: Tlds, deny: null }
  7. };
  8. module.exports = {
  9. domain: {
  10. analyze(domain, options) {
  11. options = internals.options(options);
  12. return Domain.analyze(domain, options);
  13. },
  14. isValid(domain, options) {
  15. options = internals.options(options);
  16. return Domain.isValid(domain, options);
  17. }
  18. },
  19. email: {
  20. analyze(email, options) {
  21. options = internals.options(options);
  22. return Email.analyze(email, options);
  23. },
  24. isValid(email, options) {
  25. options = internals.options(options);
  26. return Email.isValid(email, options);
  27. }
  28. }
  29. };
  30. internals.options = function (options) {
  31. if (!options) {
  32. return { tlds: internals.defaultTlds };
  33. }
  34. if (options.tlds === false) { // Defaults to true
  35. return options;
  36. }
  37. if (!options.tlds ||
  38. options.tlds === true) {
  39. return Object.assign({}, options, { tlds: internals.defaultTlds });
  40. }
  41. if (typeof options.tlds !== 'object') {
  42. throw new Error('Invalid options: tlds must be a boolean or an object');
  43. }
  44. if (options.tlds.deny) {
  45. if (options.tlds.deny instanceof Set === false) {
  46. throw new Error('Invalid options: tlds.deny must be a Set object');
  47. }
  48. if (options.tlds.allow) {
  49. throw new Error('Invalid options: cannot specify both tlds.allow and tlds.deny lists');
  50. }
  51. return options;
  52. }
  53. if (options.tlds.allow === true) {
  54. return Object.assign({}, options, { tlds: internals.defaultTlds });
  55. }
  56. if (options.tlds.allow instanceof Set === false) {
  57. throw new Error('Invalid options: tlds.allow must be a Set object or true');
  58. }
  59. return options;
  60. };