1 /*! https://mths.be/punycode v1.3.2 by @mathias */
4 /** Detect free variables */
5 var freeExports = typeof exports == 'object' && exports &&
6 !exports.nodeType && exports;
7 var freeModule = typeof module == 'object' && module &&
8 !module.nodeType && module;
9 var freeGlobal = typeof global == 'object' && global;
11 freeGlobal.global === freeGlobal ||
12 freeGlobal.window === freeGlobal ||
13 freeGlobal.self === freeGlobal
19 * The `punycode` object.
25 /** Highest positive signed 32-bit float value */
26 maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
28 /** Bootstring parameters */
35 initialN = 128, // 0x80
36 delimiter = '-', // '\x2D'
38 /** Regular expressions */
39 regexPunycode = /^xn--/,
40 regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
41 regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
45 'overflow': 'Overflow: input needs wider integers to process',
46 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
47 'invalid-input': 'Invalid input'
50 /** Convenience shortcuts */
51 baseMinusTMin = base - tMin,
53 stringFromCharCode = String.fromCharCode,
55 /** Temporary variable */
58 /*--------------------------------------------------------------------------*/
61 * A generic error utility function.
63 * @param {String} type The error type.
64 * @returns {Error} Throws a `RangeError` with the applicable error message.
66 function error(type) {
67 throw new RangeError(errors[type]);
71 * A generic `Array#map` utility function.
73 * @param {Array} array The array to iterate over.
74 * @param {Function} callback The function that gets called for every array
76 * @returns {Array} A new array of values returned by the callback function.
78 function map(array, fn) {
79 var length = array.length;
82 result[length] = fn(array[length]);
88 * A simple `Array#map`-like wrapper to work with domain name strings or email
91 * @param {String} domain The domain name or email address.
92 * @param {Function} callback The function that gets called for every
94 * @returns {Array} A new string of characters returned by the callback
97 function mapDomain(string, fn) {
98 var parts = string.split('@');
100 if (parts.length > 1) {
101 // In email addresses, only the domain name should be punycoded. Leave
102 // the local part (i.e. everything up to `@`) intact.
103 result = parts[0] + '@';
106 // Avoid `split(regex)` for IE8 compatibility. See #17.
107 string = string.replace(regexSeparators, '\x2E');
108 var labels = string.split('.');
109 var encoded = map(labels, fn).join('.');
110 return result + encoded;
114 * Creates an array containing the numeric code points of each Unicode
115 * character in the string. While JavaScript uses UCS-2 internally,
116 * this function will convert a pair of surrogate halves (each of which
117 * UCS-2 exposes as separate characters) into a single code point,
119 * @see `punycode.ucs2.encode`
120 * @see <https://mathiasbynens.be/notes/javascript-encoding>
121 * @memberOf punycode.ucs2
123 * @param {String} string The Unicode input string (UCS-2).
124 * @returns {Array} The new array of code points.
126 function ucs2decode(string) {
129 length = string.length,
132 while (counter < length) {
133 value = string.charCodeAt(counter++);
134 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
135 // high surrogate, and there is a next character
136 extra = string.charCodeAt(counter++);
137 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
138 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
140 // unmatched surrogate; only append this code unit, in case the next
141 // code unit is the high surrogate of a surrogate pair
153 * Creates a string based on an array of numeric code points.
154 * @see `punycode.ucs2.decode`
155 * @memberOf punycode.ucs2
157 * @param {Array} codePoints The array of numeric code points.
158 * @returns {String} The new Unicode string (UCS-2).
160 function ucs2encode(array) {
161 return map(array, function(value) {
163 if (value > 0xFFFF) {
165 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
166 value = 0xDC00 | value & 0x3FF;
168 output += stringFromCharCode(value);
174 * Converts a basic code point into a digit/integer.
175 * @see `digitToBasic()`
177 * @param {Number} codePoint The basic numeric code point value.
178 * @returns {Number} The numeric value of a basic code point (for use in
179 * representing integers) in the range `0` to `base - 1`, or `base` if
180 * the code point does not represent a value.
182 function basicToDigit(codePoint) {
183 if (codePoint - 48 < 10) {
184 return codePoint - 22;
186 if (codePoint - 65 < 26) {
187 return codePoint - 65;
189 if (codePoint - 97 < 26) {
190 return codePoint - 97;
196 * Converts a digit/integer into a basic code point.
197 * @see `basicToDigit()`
199 * @param {Number} digit The numeric value of a basic code point.
200 * @returns {Number} The basic code point whose value (when used for
201 * representing integers) is `digit`, which needs to be in the range
202 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
203 * used; else, the lowercase form is used. The behavior is undefined
204 * if `flag` is non-zero and `digit` has no uppercase form.
206 function digitToBasic(digit, flag) {
207 // 0..25 map to ASCII a..z or A..Z
208 // 26..35 map to ASCII 0..9
209 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
213 * Bias adaptation function as per section 3.4 of RFC 3492.
214 * https://tools.ietf.org/html/rfc3492#section-3.4
217 function adapt(delta, numPoints, firstTime) {
219 delta = firstTime ? floor(delta / damp) : delta >> 1;
220 delta += floor(delta / numPoints);
221 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
222 delta = floor(delta / baseMinusTMin);
224 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
228 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
231 * @param {String} input The Punycode string of ASCII-only symbols.
232 * @returns {String} The resulting string of Unicode symbols.
234 function decode(input) {
237 inputLength = input.length,
250 /** Cached calculation results */
253 // Handle the basic code points: let `basic` be the number of input code
254 // points before the last delimiter, or `0` if there is none, then copy
255 // the first basic code points to the output.
257 basic = input.lastIndexOf(delimiter);
262 for (j = 0; j < basic; ++j) {
263 // if it's not a basic code point
264 if (input.charCodeAt(j) >= 0x80) {
267 output.push(input.charCodeAt(j));
270 // Main decoding loop: start just after the last delimiter if any basic code
271 // points were copied; start at the beginning otherwise.
273 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
275 // `index` is the index of the next character to be consumed.
276 // Decode a generalized variable-length integer into `delta`,
277 // which gets added to `i`. The overflow checking is easier
278 // if we increase `i` as we go, then subtract off its starting
279 // value at the end to obtain `delta`.
280 for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
282 if (index >= inputLength) {
283 error('invalid-input');
286 digit = basicToDigit(input.charCodeAt(index++));
288 if (digit >= base || digit > floor((maxInt - i) / w)) {
293 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
299 baseMinusT = base - t;
300 if (w > floor(maxInt / baseMinusT)) {
308 out = output.length + 1;
309 bias = adapt(i - oldi, out, oldi == 0);
311 // `i` was supposed to wrap around from `out` to `0`,
312 // incrementing `n` each time, so we'll fix that now:
313 if (floor(i / out) > maxInt - n) {
320 // Insert `n` at position `i` of the output
321 output.splice(i++, 0, n);
325 return ucs2encode(output);
329 * Converts a string of Unicode symbols (e.g. a domain name label) to a
330 * Punycode string of ASCII-only symbols.
332 * @param {String} input The string of Unicode symbols.
333 * @returns {String} The resulting Punycode string of ASCII-only symbols.
335 function encode(input) {
348 /** `inputLength` will hold the number of code points in `input`. */
350 /** Cached calculation results */
351 handledCPCountPlusOne,
355 // Convert the input in UCS-2 to Unicode
356 input = ucs2decode(input);
359 inputLength = input.length;
361 // Initialize the state
366 // Handle the basic code points
367 for (j = 0; j < inputLength; ++j) {
368 currentValue = input[j];
369 if (currentValue < 0x80) {
370 output.push(stringFromCharCode(currentValue));
374 handledCPCount = basicLength = output.length;
376 // `handledCPCount` is the number of code points that have been handled;
377 // `basicLength` is the number of basic code points.
379 // Finish the basic string - if it is not empty - with a delimiter
381 output.push(delimiter);
384 // Main encoding loop:
385 while (handledCPCount < inputLength) {
387 // All non-basic code points < n have been handled already. Find the next
389 for (m = maxInt, j = 0; j < inputLength; ++j) {
390 currentValue = input[j];
391 if (currentValue >= n && currentValue < m) {
396 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
397 // but guard against overflow
398 handledCPCountPlusOne = handledCPCount + 1;
399 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
403 delta += (m - n) * handledCPCountPlusOne;
406 for (j = 0; j < inputLength; ++j) {
407 currentValue = input[j];
409 if (currentValue < n && ++delta > maxInt) {
413 if (currentValue == n) {
414 // Represent delta as a generalized variable-length integer
415 for (q = delta, k = base; /* no condition */; k += base) {
416 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
421 baseMinusT = base - t;
423 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
425 q = floor(qMinusT / baseMinusT);
428 output.push(stringFromCharCode(digitToBasic(q, 0)));
429 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
439 return output.join('');
443 * Converts a Punycode string representing a domain name or an email address
444 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
445 * it doesn't matter if you call it on a string that has already been
446 * converted to Unicode.
448 * @param {String} input The Punycoded domain name or email address to
449 * convert to Unicode.
450 * @returns {String} The Unicode representation of the given Punycode
453 function toUnicode(input) {
454 return mapDomain(input, function(string) {
455 return regexPunycode.test(string)
456 ? decode(string.slice(4).toLowerCase())
462 * Converts a Unicode string representing a domain name or an email address to
463 * Punycode. Only the non-ASCII parts of the domain name will be converted,
464 * i.e. it doesn't matter if you call it with a domain that's already in
467 * @param {String} input The domain name or email address to convert, as a
469 * @returns {String} The Punycode representation of the given domain name or
472 function toASCII(input) {
473 return mapDomain(input, function(string) {
474 return regexNonASCII.test(string)
475 ? 'xn--' + encode(string)
480 /*--------------------------------------------------------------------------*/
482 /** Define the public API */
485 * A string representing the current Punycode.js version number.
491 * An object of methods to convert from JavaScript's internal character
492 * representation (UCS-2) to Unicode code points, and back.
493 * @see <https://mathiasbynens.be/notes/javascript-encoding>
498 'decode': ucs2decode,
504 'toUnicode': toUnicode
507 /** Expose `punycode` */
508 // Some AMD build optimizers, like r.js, check for specific condition patterns
509 // like the following:
511 typeof define == 'function' &&
512 typeof define.amd == 'object' &&
515 define('punycode', function() {
518 } else if (freeExports && freeModule) {
519 if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+
520 freeModule.exports = punycode;
521 } else { // in Narwhal or RingoJS v0.7.0-
522 for (key in punycode) {
523 punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
526 } else { // in Rhino or a web browser
527 root.punycode = punycode;