Пример #1
0
export function normalizeUrlObj(urlObj) {
  let [hostname, port, pathname] = ['', '', ''];

  if (urlObj.hostname) {
    hostname = punycode
      // IDN to unicode.
      .toUnicode(urlObj.hostname)
      // Remove `www.`.
      .replace(/^www./, '');
  }

  if (urlObj.port) {
    // Remove default port.
    if (!(urlObj.protocol === 'http:'  && +urlObj.port === 80 ||
          urlObj.protocol === 'https:' && +urlObj.port === 443))
      port = ':' + urlObj.port;
  }

  if (urlObj.pathname) {
    pathname = urlObj.pathname
      .toLowerCase()
      // Replace duplicate slashes.
      .replace(/\/{2,}/g, '/')
      // Remove ending "/".
      .replace(/\/$/, '')
      // Remove default index file.
      .replace(/\/(?:default.(?:html?|aspx?)|index.(?:s?html?|php|jsp|asp))$/, '');
  }

  return hostname + port + pathname;
}
Пример #2
0
function validateLabel(label, processing_option) {
  if (label.substr(0, 4) === "xn--") {
    label = punycode.toUnicode(label);
    processing_option = PROCESSING_OPTIONS.NONTRANSITIONAL;
  }
  
  var error = false;
  
  if (label.normalize("NFC") !== label ||
      (label[3] === "-" && label[4] === "-") ||
      label[0] === "-" || label[label.length - 1] === "-" ||
      label.indexOf(".") !== -1 ||
      label.search(combiningMarksRegex) === 0) {
    error = true;
  }
  
  var len = countSymbols(label);
  for (var i = 0; i < len; ++i) {
    var status = findStatus(label.codePointAt(i));
    if ((processing === PROCESSING_OPTIONS.TRANSITIONAL && status[1] !== "valid") ||
        (processing === PROCESSING_OPTIONS.NONTRANSITIONAL &&
         status[1] !== "valid" && status[1] !== "deviation")) {
      error = true;
      break;
    }
  }
  
  return {
    label: label,
    error: error
  };
}
Пример #3
0
function normalize(url, opts) {
	opts = formatOpts(opts);

	var u = libUrl.parse(url);

	// Remove unused properties.
	// Prevents them being used by url.format()
	delete u.host;
	delete u.query;

	if (opts.excludeHash) {
		delete u.hash;
	}

	if (u.hostname) {
		u.hostname = punycode.toUnicode(u.hostname).toLowerCase();
	}

	// Remove default ports
	if (u.port == defaultPorts[u.protocol]) {
		u.port = null;
	}

	u.pathname = normalizePath(u.pathname, opts.ignoreIndex, opts.indexes);
	u.search = normalizeQuery(u.search, opts.ignoreParams);

	return libUrl.format(u);
}
Пример #4
0
/**
 * Creates new instance of URI authority component parser.
 * https://tools.ietf.org/html/rfc3986#section-3.2
 * @param {String?} authorityString URI authority component string.
 * @constructor
 */
function Authority(authorityString) {
	if (typeof(authorityString) === 'string' && authorityString.length > 0) {
		var firstAtIndex = authorityString.indexOf('@');
		if (firstAtIndex !== -1) {
			var userInfoString = authorityString.substring(0, firstAtIndex);
			this.userInfo = new UserInfo(userInfoString);
			authorityString = authorityString.substring(firstAtIndex + 1);
		}

		var lastColonIndex = authorityString.lastIndexOf(':');
		if (lastColonIndex !== -1) {
			var portString = authorityString.substring(lastColonIndex + 1);
			if (lastColonIndex === authorityString.length - 1) {
				this.port = '';
				authorityString = authorityString.substring(0, lastColonIndex);
			}else if (PORT_REGEXP.test(portString)) {
				this.port = portString;
				authorityString = authorityString.substring(0, lastColonIndex);
			}
		}

		this.host = punycode.toUnicode(
			percentEncodingHelper.decode(authorityString)
		);
	}
}
Пример #5
0
function dePunycodeDomain(d){
	d = d.toLowerCase();
	if (/xn--/.test(d)){
		return [d, punycode.toUnicode(d)];
	}
	return [d];
}
Пример #6
0
SMTPConnection.prototype._parseAddressCommand = function (name, command) {
    command = (command || '').toString();
    name = (name || '').toString().trim().toUpperCase();

    var parts = command.split(':');
    command = parts.shift().trim().toUpperCase();
    parts = parts.join(':').trim().split(/\s+/);

    var address = parts.shift();
    var args = false;
    var invalid = false;

    if (name !== command) {
        return false;
    }

    if (!/^<[^<>]*>$/.test(address)) {
        invalid = true;
    } else {
        address = address.substr(1, address.length - 2);
    }

    parts.forEach(function (part) {
        part = part.split('=');
        var key = part.shift().toUpperCase();
        var value = part.join('=') || true;

        if (typeof value === 'string') {
            // decode 'xtext'
            value = value.replace(/\+([0-9A-F]{2})/g, function (match, hex) {
                return unescape('%' + hex);
            });
        }

        if (!args) {
            args = {};
        }

        args[key] = value;
    });

    if (address) {
        // enforce unycode
        address = address.split('@');
        if (address.length !== 2 || !address[0] || !address[1]) { // really bad e-mail address validation. was not able to use joi because of the missing unicode support
            invalid = true;
        } else {
            address = [address[0] || '', '@', punycode.toUnicode(address[1] || '')].join('');
        }
    }

    return invalid ? false : {
        address: address,
        args: args
    };
};
Пример #7
0
 toUnicode: (test) => assert.strictEqual(
   punycode.toUnicode(
     regexNonASCII.test(test.decoded) ?
       `xn--${test.encoded}` :
       test.decoded
   ),
   regexNonASCII.test(test.decoded) ?
     test.decoded.toLowerCase() :
     test.decoded
 )
Пример #8
0
utils.addString = function (element, str) {
    if ((str !== undefined) && (str !=="") && (element.indexOf(str) === -1)) {
        try {
            element.push(punycode.toUnicode(str));
        } catch(e) {
            loggers.WARN(e);
            element.push(str);
        }
    }
    return element;
}
Пример #9
0
 var sniCallback = function(hostname, cb) {
   hostname = punycode.toUnicode(hostname);
   for (var key in SNI) {
     if (hostname.match(SNImatchers[key])) {
       if (cb) // since node 0.11.5
         return cb(null, SNI[key]);
       else
         return SNI[key];
     }
   }
   if (cb)
     return cb(null);
 };
Пример #10
0
function normalizeLinkText(url) {
    var parsed = mdurl.parse(url, true);

    if (parsed.hostname) {
        if (!parsed.protocol || PROTOCOLS.indexOf(parsed.protocol) >= 0) {
            try {
                parsed.hostname = punycode.toUnicode(parsed.hostname);
            } catch(er) {}
        }
    }

    return mdurl.decode(mdurl.format(parsed));
}
Пример #11
0
module.exports.getBaseDomain = function (hostname) {
  // decode punycode if exists
  if (hostname.indexOf('xn--') >= 0 &&
    checkASCII(hostname)) {
    try {
      hostname = punycode.toUnicode(hostname)
    } catch (e) {
      console.error('punnycode.toUnicode() failure:', e)
    }
  }

  let baseDomain = cachedBaseDomain.get(hostname)
  if (baseDomain) {
    return baseDomain
  }

  // search through PSL
  var prevDomains = []
  var curDomain = hostname
  var nextDot = curDomain.indexOf('.')
  var tld = 0
  var suffix

  while (true) {
    suffix = publicSuffixes[curDomain]
    if (typeof suffix !== 'undefined') {
      tld = suffix
      break
    }

    if (nextDot < 0) {
      tld = 1
      break
    }

    prevDomains.push(curDomain.substring(0, nextDot))
    curDomain = curDomain.substring(nextDot + 1)
    nextDot = curDomain.indexOf('.')
  }

  while (tld > 0 && prevDomains.length > 0) {
    curDomain = prevDomains.pop() + '.' + curDomain
    tld--
  }

  cachedBaseDomain.set(curDomain)

  return curDomain
}
Пример #12
0
 var sniCallback = (hostname, cb) => {
   hostname = punycode.toUnicode(hostname);
   for (var key in SNI) {
     if (hostname.match(SNImatchers[key])) {
       if (cb) // since node 0.11.5
         return cb(null, SNI[key]);
       else
         return SNI[key];
     }
   }
   if(this.fallbackSniCallback) {
     return this.fallbackSniCallback(hostname, cb, config.ssl);
   }
   return cb(null);
 };
Пример #13
0
 addresses.forEach(address => {
     address.name = (address.name || '').toString();
     if (address.name) {
         try {
             address.name = libmime.decodeWords(address.name);
         } catch (E) {
             //ignore, keep as is
         }
     }
     if (/@xn--/.test(address.address)) {
         address.address =
             address.address.substr(0, address.address.lastIndexOf('@') + 1) +
             punycode.toUnicode(address.address.substr(address.address.lastIndexOf('@') + 1));
     }
     if (address.group) {
         this.decodeAddresses(address.group);
     }
 });
Пример #14
0
function normalizeLinkText(url) {
  var parsed = mdurl.parse(url, true);

  if (parsed.hostname) {
    // Encode hostnames in urls like:
    // `http://host/`, `https://host/`, `mailto:user@host`, `//host/`
    //
    // We don't encode unknown schemas, because it's likely that we encode
    // something we shouldn't (e.g. `skype:name` treated as `skype:host`)
    //
    if (!parsed.protocol || RECODE_HOSTNAME_FOR.indexOf(parsed.protocol) >= 0) {
      try {
        parsed.hostname = punycode.toUnicode(parsed.hostname);
      } catch(er) {}
    }
  }

  return mdurl.decode(mdurl.format(parsed));
}
Пример #15
0
function get_hostname_pathname(full_url) {
    var ret = {
        original_url: full_url,
        err: null,
        hostname: '',
        pathname: ''
    };

    if (!full_url) {
        ret.err = 'Empty full_url';
        return ret;
    }

    try {
        var parsed_url = url.parse(full_url);

        var hostname = parsed_url.hostname || '';
        var pathname = (parsed_url.pathname || '').toLowerCase();

        if (!hostname_check.test(hostname)) {
            ret.err = 'Invalid hostname';
            return ret;
        }

        if (hostname.substr(0, 4) === 'xn--' || hostname.indexOf('.xn--') > 0) {
            hostname = punycode.toUnicode(hostname);
        }

        if (pathname.indexOf('%') >= 0) {
            pathname = decodeURIComponent(pathname);
        }

        ret.hostname = hostname;
        ret.pathname = pathname;
        return ret;
    }
    catch (e) {
        ret.err = e;
        return ret;
    }
}
Пример #16
0
exports.is_public_suffix = function (host) {
    if (!host) return false;
    host = host.toLowerCase();
    if (public_suffix_list[host]) return true;

    var up_one_level = host.split('.').slice(1).join('.'); // co.uk -> uk
    if (!up_one_level) return false;   // no dot?

    var wildHost = '*.' + up_one_level;
    if (public_suffix_list[wildHost]) {
        if (public_suffix_list['!'+host]) return false; // on exception list
        return true;           // matched a wildcard, ex: *.uk
    }

    var puny;
    try { puny = punycode.toUnicode(host); }
    catch(e) {}
    if (puny && public_suffix_list[puny]) return true;

    return false;
};
Пример #17
0
/*
 * Funktsioon vastab DNS päringutele
 * 
 * Sisendiks sõnaraamatu objekt, DNS päringu küsimus- ja vastusobjektid
 */
function DNSServerResponse(dict, req, res){
	
	// Seab DNS vastuse päise
	res.setHeader(req.header);
    res.header.qr = 1; // Question/Response
    res.header.aa = 1; // Authorative Answer
    res.header.rd = 0; // Recursion Desired

    var question,
    	translation;

    // töötle ükshaaval saabunud küsimused (peaks küll olema vaid 1)
    for (var i = 0; i < req.q.length; i++){
        res.addQuestion(req.q[i]); // Lisa kirje küsimuste sektsiooni

        // vorminda küsimus (punycode->unicode jne)
        question = punycode.toUnicode(req.q[i].name.toLowerCase().trim());
        
        // lae sõnaraamatu objektist tõlge
        translation = dict[question] || "";

        // väljasta tulemus konsoolile
        console.log(question+" -> "+translation);

        // kui tõlge on olemas, lisa vastuskirje
        if(translation){
        	res.addRR(
        	   punycode.toASCII(question), // name 
        	   60, // TTL 
        	   "IN", // CLASS 
        	   "TXT", // TYPE 
        	   iconv.convert(translation).toString("ASCII") // response
            );
        	res.header.ancount++; // Vastuse sektsiooni kaunter
        }
    }
    
    // saada päringu vastus
    res.send();
}
Пример #18
0
module.exports.getBaseDomain = function (hostname) {
  // decode punycode if exists
  if (hostname.indexOf('xn--') >= 0) {
    hostname = punycode.toUnicode(hostname)
  }

  // search through PSL
  var prevDomains = []
  var curDomain = hostname
  var nextDot = curDomain.indexOf('.')
  var tld = 0
  var suffix

  while (true) {
    suffix = publicSuffixes[curDomain]
    if (typeof suffix !== 'undefined') {
      tld = suffix
      break
    }

    if (nextDot < 0) {
      tld = 1
      break
    }

    prevDomains.push(curDomain.substring(0, nextDot))
    curDomain = curDomain.substring(nextDot + 1)
    nextDot = curDomain.indexOf('.')
  }

  while (tld > 0 && prevDomains.length > 0) {
    curDomain = prevDomains.pop() + '.' + curDomain
    tld--
  }

  return curDomain
}
Пример #19
0
module.exports = function (str, opts) {
	opts = objectAssign({
		normalizeProtocol: true,
		stripFragment: true,
		stripWWW: true,
		removeQueryParameters: [/^utm_\w+/i]
	}, opts);

	if (typeof str !== 'string') {
		throw new TypeError('Expected a string');
	}

	var hasRelativeProtocol = str.indexOf('//') === 0;

	// prepend protocol
	str = prependHttp(str.trim()).replace(/^\/\//, 'http://');

	var urlObj = url.parse(str);

	if (!urlObj.hostname && !urlObj.pathname) {
		throw new Error('Invalid URL');
	}

	// prevent these from being used by `url.format`
	delete urlObj.host;
	delete urlObj.query;

	// remove fragment
	if (opts.stripFragment) {
		delete urlObj.hash;
	}

	// remove default port
	var port = DEFAULT_PORTS[urlObj.protocol];
	if (Number(urlObj.port) === port) {
		delete urlObj.port;
	}

	// remove duplicate slashes
	if (urlObj.pathname) {
		urlObj.pathname = urlObj.pathname.replace(/\/{2,}/, '/');
	}

	// resolve relative paths, but only for slashed protocols
	if (slashedProtocol[urlObj.protocol]) {
		var domain = urlObj.protocol + '//' + urlObj.hostname;
		var relative = url.resolve(domain, urlObj.pathname);
		urlObj.pathname = relative.replace(domain, '');
	}

	if (urlObj.hostname) {
		// IDN to Unicode
		urlObj.hostname = punycode.toUnicode(urlObj.hostname).toLowerCase();

		// remove trailing dot
		urlObj.hostname = urlObj.hostname.replace(/\.$/, '');

		// remove `www.`
		if (opts.stripWWW) {
			urlObj.hostname = urlObj.hostname.replace(/^www\./, '');
		}
	}

	// remove URL with empty query string
	if (urlObj.search === '?') {
		delete urlObj.search;
	}

	var queryParameters = queryString.parse(urlObj.search);

	// remove query unwanted parameters
	if (Array.isArray(opts.removeQueryParameters)) {
		for (var key in queryParameters) {
			if (testQueryParameter(key, opts.removeQueryParameters)) {
				delete queryParameters[key];
			}
		}
	}

	// sort query parameters
	urlObj.search = queryString.stringify(sortKeys(queryParameters));

	// decode query parameters
	urlObj.search = decodeURIComponent(urlObj.search);

	// take advantage of many of the Node `url` normalizations
	str = url.format(urlObj);

	// remove ending `/`
	str = str.replace(/\/$/, '');

	// restore relative protocol, if applicable
	if (hasRelativeProtocol && !opts.normalizeProtocol) {
		str = str.replace(/^http:\/\//, '//');
	}

	return str;
};
Пример #20
0
 serialize: function (mailtoComponents, options) {
     const components = mailtoComponents;
     const to = toArray(mailtoComponents.to);
     if (to) {
         for (let x = 0, xl = to.length; x < xl; ++x) {
             const toAddr = String(to[x]);
             const atIdx = toAddr.lastIndexOf("@");
             const localPart = (toAddr.slice(0, atIdx)).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
             let domain = toAddr.slice(atIdx + 1);
             //convert IDN via punycode
             try {
                 domain = (!options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain));
             }
             catch (e) {
                 components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
             }
             to[x] = localPart + "@" + domain;
         }
         components.path = to.join(",");
     }
     const headers = mailtoComponents.headers = mailtoComponents.headers || {};
     if (mailtoComponents.subject)
         headers["subject"] = mailtoComponents.subject;
     if (mailtoComponents.body)
         headers["body"] = mailtoComponents.body;
     const fields = [];
     for (const name in headers) {
         if (headers[name] !== O[name]) {
             fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) +
                 "=" +
                 headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
         }
     }
     if (fields.length) {
         components.query = fields.join("&");
     }
     return components;
 }
// include the licence in the function since it gets written to pubsuffix.js
function getPublicSuffix(domain) {
  /*!
   * Copyright (c) 2015, Salesforce.com, Inc.
   * All rights reserved.
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice,
   * this list of conditions and the following disclaimer.
   *
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   * this list of conditions and the following disclaimer in the documentation
   * and/or other materials provided with the distribution.
   *
   * 3. Neither the name of Salesforce.com nor the names of its contributors may
   * be used to endorse or promote products derived from this software without
   * specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   * POSSIBILITY OF SUCH DAMAGE.
   */
  if (!domain) {
    return null;
  }
  if (domain.match(/^\./)) {
    return null;
  }
  var asciiDomain = punycode.toASCII(domain);
  var converted = false;
  if (asciiDomain !== domain) {
    domain = asciiDomain;
    converted = true;
  }
  if (index[domain]) {
    return null;
  }

  domain = domain.toLowerCase();
  var parts = domain.split('.').reverse();

  var suffix = '';
  var suffixLen = 0;
  for (var i=0; i<parts.length; i++) {
    var part = parts[i];
    var starstr = '*'+suffix;
    var partstr = part+suffix;

    if (index[starstr]) { // star rule matches
      suffixLen = i+1;
      if (index[partstr] === false) { // exception rule matches (NB: false, not undefined)
        suffixLen--;
      }
    } else if (index[partstr]) { // exact match, not exception
      suffixLen = i+1;
    }

    suffix = '.'+partstr;
  }

  if (index['*'+suffix]) { // *.domain exists (e.g. *.kyoto.jp for domain='kyoto.jp');
    return null;
  }

  suffixLen = suffixLen || 1;
  if (parts.length > suffixLen) {
    var publicSuffix = parts.slice(0,suffixLen+1).reverse().join('.');
    return converted ? punycode.toUnicode(publicSuffix) : publicSuffix;
  }

  return null;
}
Пример #22
0
tests.forEach((testCase) => {
  Object.keys(testBattery).forEach((key) => {
    try {
      testBattery[key](testCase);
    } catch (error) {
      handleError(error, key);
    }
  });
});

// BMP code point
assert.strictEqual(punycode.ucs2.encode([0x61]), 'a');
// supplementary code point (surrogate pair)
assert.strictEqual(punycode.ucs2.encode([0x1D306]), '\uD834\uDF06');
// high surrogate
assert.strictEqual(punycode.ucs2.encode([0xD800]), '\uD800');
// high surrogate followed by non-surrogates
assert.strictEqual(punycode.ucs2.encode([0xD800, 0x61, 0x62]), '\uD800ab');
// low surrogate
assert.strictEqual(punycode.ucs2.encode([0xDC00]), '\uDC00');
// low surrogate followed by non-surrogates
assert.strictEqual(punycode.ucs2.encode([0xDC00, 0x61, 0x62]), '\uDC00ab');

assert.strictEqual(errors, 0);

// test map domain
assert.strictEqual(punycode.toASCII('Bücher@日本語.com'),
                   'Bücher@xn--wgv71a119e.com');
assert.strictEqual(punycode.toUnicode('Bücher@xn--wgv71a119e.com'),
                   'Bücher@日本語.com');
Пример #23
0
function usingPunycode(val) {
  punycode.toUnicode(punycode.toASCII(val));
}
Пример #24
0
module.exports = function (str, opts) {
	opts = objectAssign({
		normalizeProtocol: true,
		stripFragment: true,
		stripWWW: true,
    queryWhitelist: [],
	}, opts);

	if (typeof str !== 'string') {
		throw new TypeError('Expected a string');
	}

	var hasRelativeProtocol = str.indexOf('//') === 0;

	// prepend protocol
	str = prependHttp(str.trim()).replace(/^\/\//, 'http://');

	var urlObj = url.parse(str);

	// prevent these from being used by `url.format`
	delete urlObj.host;
	delete urlObj.query;

	// remove fragment
	if (opts.stripFragment) {
		delete urlObj.hash;
	}

	// remove default port
	var port = DEFAULT_PORTS[urlObj.protocol];
	if (Number(urlObj.port) === port) {
		delete urlObj.port;
	}

	// remove duplicate slashes
	if (urlObj.pathname) {
		urlObj.pathname = urlObj.pathname.replace(/\/{2,}/, '/');
	}

	// resolve relative paths, but only for slashed protocols
	if (slashedProtocol[urlObj.protocol]) {
		var domain = urlObj.protocol + '//' + urlObj.hostname;
		var relative = url.resolve(domain, urlObj.pathname);
		urlObj.pathname = relative.replace(domain, '');
	}

	if (urlObj.hostname) {
		// IDN to Unicode
		urlObj.hostname = punycode.toUnicode(urlObj.hostname).toLowerCase();

		// remove `www.`
		if (opts.stripWWW) {
			urlObj.hostname = urlObj.hostname.replace(/^www\./, '');
		}
	}

	// remove URL with empty query string
	if (urlObj.search === '?') {
		delete urlObj.search;
	}

  var queryObj = queryString.parse(urlObj.search);

  // whitelist has been provided, strip everything else
  if (opts.queryWhitelist.length) {
    var whitelist = new Set(opts.queryWhitelist);
    Object.keys(queryObj).forEach(key => {
      if (whitelist.has(key)) return;
      delete queryObj[key];
    });
  }

	// sort query parameters
	urlObj.search = queryString.stringify(sortKeys(queryObj));

	// decode query parameters
	urlObj.search = decodeURIComponent(urlObj.search);

	// take advantage of many of the Node `url` normalizations
	str = url.format(urlObj);

	// remove ending `/`
	str = str.replace(/\/$/, '');

	// restore relative protocol, if applicable
	if (hasRelativeProtocol && !opts.normalizeProtocol) {
		str = str.replace(/^http:\/\//, '//');
	}

	return str;
};
Пример #25
0
common.hostname = function(host) {
  return punycode.toUnicode(host || window.location.hostname);
};
Пример #26
0
//		* console.log, console.warn, console.error, console.info, console.debug, console.dir, console.trace
//
//		* add require("./_log.js") to modules
//
//		Note: https://nodejs.org/docs/latest/api/punycode.html for conversions...
//			http://apps.timwhitlock.info/emoji/tables/unicode
//			https://www.punycoder.com/
//
//
var log = require('better-console');
var pc = require('punycode');

//
//	emoji adds
//
var EYES = pc.toUnicode('xn--lp8h');
var BUGS = pc.toUnicode('xn--jo8h');
var UHNO = pc.toUnicode('xn--738h')
var HOURGLASS = pc.toUnicode('xn--koh');
var MICROSCOPE = pc.toUnicode('xn--cw8h');
var BOMB = pc.toUnicode('xn--fs8h');

exports.log = function(msg) {
	if (msg.isArray) {
		msg = msg.toString();
	}
 	log.log(EYES + " " + msg);
};
exports.logWarn = function(msg) {
    log.warn(BOMB + " " + msg);
};
Пример #27
0
 /**
  * Normalize hostname
  *
  * @event
  */
 _normalizeHostname(hostname) {
     return punycode.toUnicode((hostname || '').toString().trim()).toLowerCase();
 }
Пример #28
0
var punycode = require('punycode');
// decode domain name parts
console.log(punycode.decode('maana-pta')); // 'mañana'
console.log(punycode.decode('--dqo34k')); // '☃-⌘'

console.log(punycode.encode('mañana')); // 'maana-pta'
console.log(punycode.encode('☃-⌘')); // '--dqo34k'

console.log(punycode.toUnicode('xn--maana-pta.com')); // 'mañana.com'
console.log(punycode.toUnicode('xn----dqo34k.com')); // '☃-⌘.com'

console.log(punycode.toASCII('mañana.com')); // 'xn--maana-pta.com'
console.log(punycode.toASCII('☃-⌘.com')); // 'xn----dqo34k.com'

console.log(punycode.ucs2.decode('abc')); // [97, 98, 99]
// surrogate pair for U+1D306 tetragram for centre:
console.log(punycode.ucs2.decode('\uD834\uDF06')); // [0x1D306]

console.log(punycode.ucs2.encode([97, 98, 99])); // 'abc'
console.log(punycode.ucs2.encode([0x1D306])); // '\uD834\uDF06'
Пример #29
0
 test: function() {
   wru.assert(true, punycode.toUnicode('xn--maana-pta.com') == 'mañana.com')
 }