Debian Codegraph @

closure-library/closure/goog/uri/utils.js

raw
1 // Copyright 2008 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Simple utilities for dealing with URI strings.
17 *
18 * This is intended to be a lightweight alternative to constructing goog.Uri
19 * objects. Whereas goog.Uri adds several kilobytes to the binary regardless
20 * of how much of its functionality you use, this is designed to be a set of
21 * mostly-independent utilities so that the compiler includes only what is
22 * necessary for the task. Estimated savings of porting is 5k pre-gzip and
23 * 1.5k post-gzip. To ensure the savings remain, future developers should
24 * avoid adding new functionality to existing functions, but instead create
25 * new ones and factor out shared code.
26 *
27 * Many of these utilities have limited functionality, tailored to common
28 * cases. The query parameter utilities assume that the parameter keys are
29 * already encoded, since most keys are compile-time alphanumeric strings. The
30 * query parameter mutation utilities also do not tolerate fragment identifiers.
31 *
32 * By design, these functions can be slower than goog.Uri equivalents.
33 * Repeated calls to some of functions may be quadratic in behavior for IE,
34 * although the effect is somewhat limited given the 2kb limit.
35 *
36 * One advantage of the limited functionality here is that this approach is
37 * less sensitive to differences in URI encodings than goog.Uri, since these
38 * functions operate on strings directly, rather than decoding them and
39 * then re-encoding.
40 *
41 * Uses features of RFC 3986 for parsing/formatting URIs:
42 * http://www.ietf.org/rfc/rfc3986.txt
43 *
44 * @author [email protected] (Garrett Boyer) - The "lightened" design.
45 * @author [email protected] (Mike Samuel) - Domain knowledge and regexes.
46 */
47
48 goog.provide('goog.uri.utils');
49 goog.provide('goog.uri.utils.ComponentIndex');
50 goog.provide('goog.uri.utils.QueryArray');
51 goog.provide('goog.uri.utils.QueryValue');
52 goog.provide('goog.uri.utils.StandardQueryParam');
53
54 goog.require('goog.array');
55 goog.require('goog.asserts');
56 goog.require('goog.string');
57
58
59 /**
60 * Character codes inlined to avoid object allocations due to charCode.
61 * @enum {number}
62 * @private
63 */
64 goog.uri.utils.CharCode_ = {
65 AMPERSAND: 38,
66 EQUAL: 61,
67 HASH: 35,
68 QUESTION: 63
69 };
70
71
72 /**
73 * Builds a URI string from already-encoded parts.
74 *
75 * No encoding is performed. Any component may be omitted as either null or
76 * undefined.
77 *
78 * @param {?string=} opt_scheme The scheme such as 'http'.
79 * @param {?string=} opt_userInfo The user name before the '@'.
80 * @param {?string=} opt_domain The domain such as 'www.google.com', already
81 * URI-encoded.
82 * @param {(string|number|null)=} opt_port The port number.
83 * @param {?string=} opt_path The path, already URI-encoded. If it is not
84 * empty, it must begin with a slash.
85 * @param {?string=} opt_queryData The URI-encoded query data.
86 * @param {?string=} opt_fragment The URI-encoded fragment identifier.
87 * @return {string} The fully combined URI.
88 */
89 goog.uri.utils.buildFromEncodedParts = function(
90 opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData,
91 opt_fragment) {
92 var out = '';
93
94 if (opt_scheme) {
95 out += opt_scheme + ':';
96 }
97
98 if (opt_domain) {
99 out += '//';
100
101 if (opt_userInfo) {
102 out += opt_userInfo + '@';
103 }
104
105 out += opt_domain;
106
107 if (opt_port) {
108 out += ':' + opt_port;
109 }
110 }
111
112 if (opt_path) {
113 out += opt_path;
114 }
115
116 if (opt_queryData) {
117 out += '?' + opt_queryData;
118 }
119
120 if (opt_fragment) {
121 out += '#' + opt_fragment;
122 }
123
124 return out;
125 };
126
127
128 /**
129 * A regular expression for breaking a URI into its component parts.
130 *
131 * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B
132 * As the "first-match-wins" algorithm is identical to the "greedy"
133 * disambiguation method used by POSIX regular expressions, it is natural and
134 * commonplace to use a regular expression for parsing the potential five
135 * components of a URI reference.
136 *
137 * The following line is the regular expression for breaking-down a
138 * well-formed URI reference into its components.
139 *
140 * <pre>
141 * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
142 * 12 3 4 5 6 7 8 9
143 * </pre>
144 *
145 * The numbers in the second line above are only to assist readability; they
146 * indicate the reference points for each subexpression (i.e., each paired
147 * parenthesis). We refer to the value matched for subexpression <n> as $<n>.
148 * For example, matching the above expression to
149 * <pre>
150 * http://www.ics.uci.edu/pub/ietf/uri/#Related
151 * </pre>
152 * results in the following subexpression matches:
153 * <pre>
154 * $1 = http:
155 * $2 = http
156 * $3 = //www.ics.uci.edu
157 * $4 = www.ics.uci.edu
158 * $5 = /pub/ietf/uri/
159 * $6 = <undefined>
160 * $7 = <undefined>
161 * $8 = #Related
162 * $9 = Related
163 * </pre>
164 * where <undefined> indicates that the component is not present, as is the
165 * case for the query component in the above example. Therefore, we can
166 * determine the value of the five components as
167 * <pre>
168 * scheme = $2
169 * authority = $4
170 * path = $5
171 * query = $7
172 * fragment = $9
173 * </pre>
174 *
175 * The regular expression has been modified slightly to expose the
176 * userInfo, domain, and port separately from the authority.
177 * The modified version yields
178 * <pre>
179 * $1 = http scheme
180 * $2 = <undefined> userInfo -\
181 * $3 = www.ics.uci.edu domain | authority
182 * $4 = <undefined> port -/
183 * $5 = /pub/ietf/uri/ path
184 * $6 = <undefined> query without ?
185 * $7 = Related fragment without #
186 * </pre>
187 * @type {!RegExp}
188 * @private
189 */
190 goog.uri.utils.splitRe_ = new RegExp(
191 '^' +
192 '(?:' +
193 '([^:/?#.]+)' + // scheme - ignore special characters
194 // used by other URL parts such as :,
195 // ?, /, #, and .
196 ':)?' +
197 '(?://' +
198 '(?:([^/?#]*)@)?' + // userInfo
199 '([^/#?]*?)' + // domain
200 '(?::([0-9]+))?' + // port
201 '(?=[/#?]|$)' + // authority-terminating character
202 ')?' +
203 '([^?#]+)?' + // path
204 '(?:\\?([^#]*))?' + // query
205 '(?:#([\\s\\S]*))?' + // fragment
206 '$');
207
208
209 /**
210 * The index of each URI component in the return value of goog.uri.utils.split.
211 * @enum {number}
212 */
213 goog.uri.utils.ComponentIndex = {
214 SCHEME: 1,
215 USER_INFO: 2,
216 DOMAIN: 3,
217 PORT: 4,
218 PATH: 5,
219 QUERY_DATA: 6,
220 FRAGMENT: 7
221 };
222
223
224 /**
225 * Splits a URI into its component parts.
226 *
227 * Each component can be accessed via the component indices; for example:
228 * <pre>
229 * goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA];
230 * </pre>
231 *
232 * @param {string} uri The URI string to examine.
233 * @return {!Array<string|undefined>} Each component still URI-encoded.
234 * Each component that is present will contain the encoded value, whereas
235 * components that are not present will be undefined or empty, depending
236 * on the browser's regular expression implementation. Never null, since
237 * arbitrary strings may still look like path names.
238 */
239 goog.uri.utils.split = function(uri) {
240 // See @return comment -- never null.
241 return /** @type {!Array<string|undefined>} */ (
242 uri.match(goog.uri.utils.splitRe_));
243 };
244
245
246 /**
247 * @param {?string} uri A possibly null string.
248 * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986
249 * reserved characters will not be removed.
250 * @return {?string} The string URI-decoded, or null if uri is null.
251 * @private
252 */
253 goog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) {
254 if (!uri) {
255 return uri;
256 }
257
258 return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri);
259 };
260
261
262 /**
263 * Gets a URI component by index.
264 *
265 * It is preferred to use the getPathEncoded() variety of functions ahead,
266 * since they are more readable.
267 *
268 * @param {goog.uri.utils.ComponentIndex} componentIndex The component index.
269 * @param {string} uri The URI to examine.
270 * @return {?string} The still-encoded component, or null if the component
271 * is not present.
272 * @private
273 */
274 goog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) {
275 // Convert undefined, null, and empty string into null.
276 return goog.uri.utils.split(uri)[componentIndex] || null;
277 };
278
279
280 /**
281 * @param {string} uri The URI to examine.
282 * @return {?string} The protocol or scheme, or null if none. Does not
283 * include trailing colons or slashes.
284 */
285 goog.uri.utils.getScheme = function(uri) {
286 return goog.uri.utils.getComponentByIndex_(
287 goog.uri.utils.ComponentIndex.SCHEME, uri);
288 };
289
290
291 /**
292 * Gets the effective scheme for the URL. If the URL is relative then the
293 * scheme is derived from the page's location.
294 * @param {string} uri The URI to examine.
295 * @return {string} The protocol or scheme, always lower case.
296 */
297 goog.uri.utils.getEffectiveScheme = function(uri) {
298 var scheme = goog.uri.utils.getScheme(uri);
299 if (!scheme && goog.global.self && goog.global.self.location) {
300 var protocol = goog.global.self.location.protocol;
301 scheme = protocol.substr(0, protocol.length - 1);
302 }
303 // NOTE: When called from a web worker in Firefox 3.5, location maybe null.
304 // All other browsers with web workers support self.location from the worker.
305 return scheme ? scheme.toLowerCase() : '';
306 };
307
308
309 /**
310 * @param {string} uri The URI to examine.
311 * @return {?string} The user name still encoded, or null if none.
312 */
313 goog.uri.utils.getUserInfoEncoded = function(uri) {
314 return goog.uri.utils.getComponentByIndex_(
315 goog.uri.utils.ComponentIndex.USER_INFO, uri);
316 };
317
318
319 /**
320 * @param {string} uri The URI to examine.
321 * @return {?string} The decoded user info, or null if none.
322 */
323 goog.uri.utils.getUserInfo = function(uri) {
324 return goog.uri.utils.decodeIfPossible_(
325 goog.uri.utils.getUserInfoEncoded(uri));
326 };
327
328
329 /**
330 * @param {string} uri The URI to examine.
331 * @return {?string} The domain name still encoded, or null if none.
332 */
333 goog.uri.utils.getDomainEncoded = function(uri) {
334 return goog.uri.utils.getComponentByIndex_(
335 goog.uri.utils.ComponentIndex.DOMAIN, uri);
336 };
337
338
339 /**
340 * @param {string} uri The URI to examine.
341 * @return {?string} The decoded domain, or null if none.
342 */
343 goog.uri.utils.getDomain = function(uri) {
344 return goog.uri.utils.decodeIfPossible_(
345 goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */);
346 };
347
348
349 /**
350 * @param {string} uri The URI to examine.
351 * @return {?number} The port number, or null if none.
352 */
353 goog.uri.utils.getPort = function(uri) {
354 // Coerce to a number. If the result of getComponentByIndex_ is null or
355 // non-numeric, the number coersion yields NaN. This will then return
356 // null for all non-numeric cases (though also zero, which isn't a relevant
357 // port number).
358 return Number(
359 goog.uri.utils.getComponentByIndex_(
360 goog.uri.utils.ComponentIndex.PORT, uri)) ||
361 null;
362 };
363
364
365 /**
366 * @param {string} uri The URI to examine.
367 * @return {?string} The path still encoded, or null if none. Includes the
368 * leading slash, if any.
369 */
370 goog.uri.utils.getPathEncoded = function(uri) {
371 return goog.uri.utils.getComponentByIndex_(
372 goog.uri.utils.ComponentIndex.PATH, uri);
373 };
374
375
376 /**
377 * @param {string} uri The URI to examine.
378 * @return {?string} The decoded path, or null if none. Includes the leading
379 * slash, if any.
380 */
381 goog.uri.utils.getPath = function(uri) {
382 return goog.uri.utils.decodeIfPossible_(
383 goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */);
384 };
385
386
387 /**
388 * @param {string} uri The URI to examine.
389 * @return {?string} The query data still encoded, or null if none. Does not
390 * include the question mark itself.
391 */
392 goog.uri.utils.getQueryData = function(uri) {
393 return goog.uri.utils.getComponentByIndex_(
394 goog.uri.utils.ComponentIndex.QUERY_DATA, uri);
395 };
396
397
398 /**
399 * @param {string} uri The URI to examine.
400 * @return {?string} The fragment identifier, or null if none. Does not
401 * include the hash mark itself.
402 */
403 goog.uri.utils.getFragmentEncoded = function(uri) {
404 // The hash mark may not appear in any other part of the URL.
405 var hashIndex = uri.indexOf('#');
406 return hashIndex < 0 ? null : uri.substr(hashIndex + 1);
407 };
408
409
410 /**
411 * @param {string} uri The URI to examine.
412 * @param {?string} fragment The encoded fragment identifier, or null if none.
413 * Does not include the hash mark itself.
414 * @return {string} The URI with the fragment set.
415 */
416 goog.uri.utils.setFragmentEncoded = function(uri, fragment) {
417 return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : '');
418 };
419
420
421 /**
422 * @param {string} uri The URI to examine.
423 * @return {?string} The decoded fragment identifier, or null if none. Does
424 * not include the hash mark.
425 */
426 goog.uri.utils.getFragment = function(uri) {
427 return goog.uri.utils.decodeIfPossible_(
428 goog.uri.utils.getFragmentEncoded(uri));
429 };
430
431
432 /**
433 * Extracts everything up to the port of the URI.
434 * @param {string} uri The URI string.
435 * @return {string} Everything up to and including the port.
436 */
437 goog.uri.utils.getHost = function(uri) {
438 var pieces = goog.uri.utils.split(uri);
439 return goog.uri.utils.buildFromEncodedParts(
440 pieces[goog.uri.utils.ComponentIndex.SCHEME],
441 pieces[goog.uri.utils.ComponentIndex.USER_INFO],
442 pieces[goog.uri.utils.ComponentIndex.DOMAIN],
443 pieces[goog.uri.utils.ComponentIndex.PORT]);
444 };
445
446
447 /**
448 * Returns the origin for a given URL.
449 * @param {string} uri The URI string.
450 * @return {string} Everything up to and including the port.
451 */
452 goog.uri.utils.getOrigin = function(uri) {
453 var pieces = goog.uri.utils.split(uri);
454 return goog.uri.utils.buildFromEncodedParts(
455 pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */,
456 pieces[goog.uri.utils.ComponentIndex.DOMAIN],
457 pieces[goog.uri.utils.ComponentIndex.PORT]);
458 };
459
460
461 /**
462 * Extracts the path of the URL and everything after.
463 * @param {string} uri The URI string.
464 * @return {string} The URI, starting at the path and including the query
465 * parameters and fragment identifier.
466 */
467 goog.uri.utils.getPathAndAfter = function(uri) {
468 var pieces = goog.uri.utils.split(uri);
469 return goog.uri.utils.buildFromEncodedParts(
470 null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH],
471 pieces[goog.uri.utils.ComponentIndex.QUERY_DATA],
472 pieces[goog.uri.utils.ComponentIndex.FRAGMENT]);
473 };
474
475
476 /**
477 * Gets the URI with the fragment identifier removed.
478 * @param {string} uri The URI to examine.
479 * @return {string} Everything preceding the hash mark.
480 */
481 goog.uri.utils.removeFragment = function(uri) {
482 // The hash mark may not appear in any other part of the URL.
483 var hashIndex = uri.indexOf('#');
484 return hashIndex < 0 ? uri : uri.substr(0, hashIndex);
485 };
486
487
488 /**
489 * Ensures that two URI's have the exact same domain, scheme, and port.
490 *
491 * Unlike the version in goog.Uri, this checks protocol, and therefore is
492 * suitable for checking against the browser's same-origin policy.
493 *
494 * @param {string} uri1 The first URI.
495 * @param {string} uri2 The second URI.
496 * @return {boolean} Whether they have the same scheme, domain and port.
497 */
498 goog.uri.utils.haveSameDomain = function(uri1, uri2) {
499 var pieces1 = goog.uri.utils.split(uri1);
500 var pieces2 = goog.uri.utils.split(uri2);
501 return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==
502 pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&
503 pieces1[goog.uri.utils.ComponentIndex.SCHEME] ==
504 pieces2[goog.uri.utils.ComponentIndex.SCHEME] &&
505 pieces1[goog.uri.utils.ComponentIndex.PORT] ==
506 pieces2[goog.uri.utils.ComponentIndex.PORT];
507 };
508
509
510 /**
511 * Asserts that there are no fragment or query identifiers, only in uncompiled
512 * mode.
513 * @param {string} uri The URI to examine.
514 * @private
515 */
516 goog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) {
517 goog.asserts.assert(
518 uri.indexOf('#') < 0 && uri.indexOf('?') < 0,
519 'goog.uri.utils: Fragment or query identifiers are not supported: [%s]',
520 uri);
521 };
522
523
524 /**
525 * Supported query parameter values by the parameter serializing utilities.
526 *
527 * If a value is null or undefined, the key-value pair is skipped, as an easy
528 * way to omit parameters conditionally. Non-array parameters are converted
529 * to a string and URI encoded. Array values are expanded into multiple
530 * &key=value pairs, with each element stringized and URI-encoded.
531 *
532 * @typedef {*}
533 */
534 goog.uri.utils.QueryValue;
535
536
537 /**
538 * An array representing a set of query parameters with alternating keys
539 * and values.
540 *
541 * Keys are assumed to be URI encoded already and live at even indices. See
542 * goog.uri.utils.QueryValue for details on how parameter values are encoded.
543 *
544 * Example:
545 * <pre>
546 * var data = [
547 * // Simple param: ?name=BobBarker
548 * 'name', 'BobBarker',
549 * // Conditional param -- may be omitted entirely.
550 * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,
551 * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null
552 * 'house', ['LosAngeles', 'NewYork', null]
553 * ];
554 * </pre>
555 *
556 * @typedef {!Array<string|goog.uri.utils.QueryValue>}
557 */
558 goog.uri.utils.QueryArray;
559
560
561 /**
562 * Parses encoded query parameters and calls callback function for every
563 * parameter found in the string.
564 *
565 * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an
566 * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means
567 * that “…&=&…” and “…&&…” will result in an empty key and value.
568 *
569 * @param {string} encodedQuery Encoded query string excluding question mark at
570 * the beginning.
571 * @param {function(string, string)} callback Function called for every
572 * parameter found in query string. The first argument (name) will not be
573 * urldecoded (so the function is consistent with buildQueryData), but the
574 * second will. If the parameter has no value (i.e. “=” was not present)
575 * the second argument (value) will be an empty string.
576 */
577 goog.uri.utils.parseQueryData = function(encodedQuery, callback) {
578 if (!encodedQuery) {
579 return;
580 }
581 var pairs = encodedQuery.split('&');
582 for (var i = 0; i < pairs.length; i++) {
583 var indexOfEquals = pairs[i].indexOf('=');
584 var name = null;
585 var value = null;
586 if (indexOfEquals >= 0) {
587 name = pairs[i].substring(0, indexOfEquals);
588 value = pairs[i].substring(indexOfEquals + 1);
589 } else {
590 name = pairs[i];
591 }
592 callback(name, value ? goog.string.urlDecode(value) : '');
593 }
594 };
595
596
597 /**
598 * Split the URI into 3 parts where the [1] is the queryData without a leading
599 * '?'. For example, the URI http://foo.com/bar?a=b#abc returns
600 * ['http://foo.com/bar','a=b','#abc'].
601 * @param {string} uri The URI to parse.
602 * @return {!Array<string>} An array representation of uri of length 3 where the
603 * middle value is the queryData without a leading '?'.
604 * @private
605 */
606 goog.uri.utils.splitQueryData_ = function(uri) {
607 // Find the query data and and hash.
608 var hashIndex = uri.indexOf('#');
609 if (hashIndex < 0) {
610 hashIndex = uri.length;
611 }
612 var questionIndex = uri.indexOf('?');
613 var queryData;
614 if (questionIndex < 0 || questionIndex > hashIndex) {
615 questionIndex = hashIndex;
616 queryData = '';
617 } else {
618 queryData = uri.substring(questionIndex + 1, hashIndex);
619 }
620 return [uri.substr(0, questionIndex), queryData, uri.substr(hashIndex)];
621 };
622
623
624 /**
625 * Join an array created by splitQueryData_ back into a URI.
626 * @param {!Array<string>} parts A URI in the form generated by splitQueryData_.
627 * @return {string} The joined URI.
628 * @private
629 */
630 goog.uri.utils.joinQueryData_ = function(parts) {
631 return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2];
632 };
633
634
635 /**
636 * @param {string} queryData
637 * @param {string} newData
638 * @return {string}
639 * @private
640 */
641 goog.uri.utils.appendQueryData_ = function(queryData, newData) {
642 if (!newData) {
643 return queryData;
644 }
645 return queryData ? queryData + '&' + newData : newData;
646 };
647
648
649 /**
650 * @param {string} uri
651 * @param {string} queryData
652 * @return {string}
653 * @private
654 */
655 goog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) {
656 if (!queryData) {
657 return uri;
658 }
659 var parts = goog.uri.utils.splitQueryData_(uri);
660 parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData);
661 return goog.uri.utils.joinQueryData_(parts);
662 };
663
664
665 /**
666 * Appends key=value pairs to an array, supporting multi-valued objects.
667 * @param {*} key The key prefix.
668 * @param {goog.uri.utils.QueryValue} value The value to serialize.
669 * @param {!Array<string>} pairs The array to which the 'key=value' strings
670 * should be appended.
671 * @private
672 */
673 goog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) {
674 goog.asserts.assertString(key);
675 if (goog.isArray(value)) {
676 // Convince the compiler it's an array.
677 goog.asserts.assertArray(value);
678 for (var j = 0; j < value.length; j++) {
679 // Convert to string explicitly, to short circuit the null and array
680 // logic in this function -- this ensures that null and undefined get
681 // written as literal 'null' and 'undefined', and arrays don't get
682 // expanded out but instead encoded in the default way.
683 goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);
684 }
685 } else if (value != null) {
686 // Skip a top-level null or undefined entirely.
687 pairs.push(
688 key +
689 // Check for empty string. Zero gets encoded into the url as literal
690 // strings. For empty string, skip the equal sign, to be consistent
691 // with UriBuilder.java.
692 (value === '' ? '' : '=' + goog.string.urlEncode(value)));
693 }
694 };
695
696
697 /**
698 * Builds a query data string from a sequence of alternating keys and values.
699 * Currently generates "&key&" for empty args.
700 *
701 * @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues
702 * Alternating keys and values. See the QueryArray typedef.
703 * @param {number=} opt_startIndex A start offset into the arary, defaults to 0.
704 * @return {string} The encoded query string, in the form 'a=1&b=2'.
705 */
706 goog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {
707 goog.asserts.assert(
708 Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0,
709 'goog.uri.utils: Key/value lists must be even in length.');
710
711 var params = [];
712 for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) {
713 var key = /** @type {string} */ (keysAndValues[i]);
714 goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params);
715 }
716 return params.join('&');
717 };
718
719
720 /**
721 * Builds a query data string from a map.
722 * Currently generates "&key&" for empty args.
723 *
724 * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys
725 * are URI-encoded parameter keys, and the values are arbitrary types
726 * or arrays. Keys with a null value are dropped.
727 * @return {string} The encoded query string, in the form 'a=1&b=2'.
728 */
729 goog.uri.utils.buildQueryDataFromMap = function(map) {
730 var params = [];
731 for (var key in map) {
732 goog.uri.utils.appendKeyValuePairs_(key, map[key], params);
733 }
734 return params.join('&');
735 };
736
737
738 /**
739 * Appends URI parameters to an existing URI.
740 *
741 * The variable arguments may contain alternating keys and values. Keys are
742 * assumed to be already URI encoded. The values should not be URI-encoded,
743 * and will instead be encoded by this function.
744 * <pre>
745 * appendParams('http://www.foo.com?existing=true',
746 * 'key1', 'value1',
747 * 'key2', 'value?willBeEncoded',
748 * 'key3', ['valueA', 'valueB', 'valueC'],
749 * 'key4', null);
750 * result: 'http://www.foo.com?existing=true&' +
751 * 'key1=value1&' +
752 * 'key2=value%3FwillBeEncoded&' +
753 * 'key3=valueA&key3=valueB&key3=valueC'
754 * </pre>
755 *
756 * A single call to this function will not exhibit quadratic behavior in IE,
757 * whereas multiple repeated calls may, although the effect is limited by
758 * fact that URL's generally can't exceed 2kb.
759 *
760 * @param {string} uri The original URI, which may already have query data.
761 * @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)}
762 * var_args
763 * An array or argument list conforming to goog.uri.utils.QueryArray.
764 * @return {string} The URI with all query parameters added.
765 */
766 goog.uri.utils.appendParams = function(uri, var_args) {
767 var queryData = arguments.length == 2 ?
768 goog.uri.utils.buildQueryData(arguments[1], 0) :
769 goog.uri.utils.buildQueryData(arguments, 1);
770 return goog.uri.utils.appendQueryDataToUri_(uri, queryData);
771 };
772
773
774 /**
775 * Appends query parameters from a map.
776 *
777 * @param {string} uri The original URI, which may already have query data.
778 * @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are
779 * URI-encoded parameter keys, and the values are arbitrary types or arrays.
780 * Keys with a null value are dropped.
781 * @return {string} The new parameters.
782 */
783 goog.uri.utils.appendParamsFromMap = function(uri, map) {
784 var queryData = goog.uri.utils.buildQueryDataFromMap(map);
785 return goog.uri.utils.appendQueryDataToUri_(uri, queryData);
786 };
787
788
789 /**
790 * Appends a single URI parameter.
791 *
792 * Repeated calls to this can exhibit quadratic behavior in IE6 due to the
793 * way string append works, though it should be limited given the 2kb limit.
794 *
795 * @param {string} uri The original URI, which may already have query data.
796 * @param {string} key The key, which must already be URI encoded.
797 * @param {*=} opt_value The value, which will be stringized and encoded
798 * (assumed not already to be encoded). If omitted, undefined, or null, the
799 * key will be added as a valueless parameter.
800 * @return {string} The URI with the query parameter added.
801 */
802 goog.uri.utils.appendParam = function(uri, key, opt_value) {
803 var value = goog.isDefAndNotNull(opt_value) ?
804 '=' + goog.string.urlEncode(opt_value) :
805 '';
806 return goog.uri.utils.appendQueryDataToUri_(uri, key + value);
807 };
808
809
810 /**
811 * Finds the next instance of a query parameter with the specified name.
812 *
813 * Does not instantiate any objects.
814 *
815 * @param {string} uri The URI to search. May contain a fragment identifier
816 * if opt_hashIndex is specified.
817 * @param {number} startIndex The index to begin searching for the key at. A
818 * match may be found even if this is one character after the ampersand.
819 * @param {string} keyEncoded The URI-encoded key.
820 * @param {number} hashOrEndIndex Index to stop looking at. If a hash
821 * mark is present, it should be its index, otherwise it should be the
822 * length of the string.
823 * @return {number} The position of the first character in the key's name,
824 * immediately after either a question mark or a dot.
825 * @private
826 */
827 goog.uri.utils.findParam_ = function(
828 uri, startIndex, keyEncoded, hashOrEndIndex) {
829 var index = startIndex;
830 var keyLength = keyEncoded.length;
831
832 // Search for the key itself and post-filter for surronuding punctuation,
833 // rather than expensively building a regexp.
834 while ((index = uri.indexOf(keyEncoded, index)) >= 0 &&
835 index < hashOrEndIndex) {
836 var precedingChar = uri.charCodeAt(index - 1);
837 // Ensure that the preceding character is '&' or '?'.
838 if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND ||
839 precedingChar == goog.uri.utils.CharCode_.QUESTION) {
840 // Ensure the following character is '&', '=', '#', or NaN
841 // (end of string).
842 var followingChar = uri.charCodeAt(index + keyLength);
843 if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL ||
844 followingChar == goog.uri.utils.CharCode_.AMPERSAND ||
845 followingChar == goog.uri.utils.CharCode_.HASH) {
846 return index;
847 }
848 }
849 index += keyLength + 1;
850 }
851
852 return -1;
853 };
854
855
856 /**
857 * Regular expression for finding a hash mark or end of string.
858 * @type {RegExp}
859 * @private
860 */
861 goog.uri.utils.hashOrEndRe_ = /#|$/;
862
863
864 /**
865 * Determines if the URI contains a specific key.
866 *
867 * Performs no object instantiations.
868 *
869 * @param {string} uri The URI to process. May contain a fragment
870 * identifier.
871 * @param {string} keyEncoded The URI-encoded key. Case-sensitive.
872 * @return {boolean} Whether the key is present.
873 */
874 goog.uri.utils.hasParam = function(uri, keyEncoded) {
875 return goog.uri.utils.findParam_(
876 uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0;
877 };
878
879
880 /**
881 * Gets the first value of a query parameter.
882 * @param {string} uri The URI to process. May contain a fragment.
883 * @param {string} keyEncoded The URI-encoded key. Case-sensitive.
884 * @return {?string} The first value of the parameter (URI-decoded), or null
885 * if the parameter is not found.
886 */
887 goog.uri.utils.getParamValue = function(uri, keyEncoded) {
888 var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
889 var foundIndex =
890 goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex);
891
892 if (foundIndex < 0) {
893 return null;
894 } else {
895 var endPosition = uri.indexOf('&', foundIndex);
896 if (endPosition < 0 || endPosition > hashOrEndIndex) {
897 endPosition = hashOrEndIndex;
898 }
899 // Progress forth to the end of the "key=" or "key&" substring.
900 foundIndex += keyEncoded.length + 1;
901 // Use substr, because it (unlike substring) will return empty string
902 // if foundIndex > endPosition.
903 return goog.string.urlDecode(
904 uri.substr(foundIndex, endPosition - foundIndex));
905 }
906 };
907
908
909 /**
910 * Gets all values of a query parameter.
911 * @param {string} uri The URI to process. May contain a fragment.
912 * @param {string} keyEncoded The URI-encoded key. Case-sensitive.
913 * @return {!Array<string>} All URI-decoded values with the given key.
914 * If the key is not found, this will have length 0, but never be null.
915 */
916 goog.uri.utils.getParamValues = function(uri, keyEncoded) {
917 var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
918 var position = 0;
919 var foundIndex;
920 var result = [];
921
922 while ((foundIndex = goog.uri.utils.findParam_(
923 uri, position, keyEncoded, hashOrEndIndex)) >= 0) {
924 // Find where this parameter ends, either the '&' or the end of the
925 // query parameters.
926 position = uri.indexOf('&', foundIndex);
927 if (position < 0 || position > hashOrEndIndex) {
928 position = hashOrEndIndex;
929 }
930
931 // Progress forth to the end of the "key=" or "key&" substring.
932 foundIndex += keyEncoded.length + 1;
933 // Use substr, because it (unlike substring) will return empty string
934 // if foundIndex > position.
935 result.push(
936 goog.string.urlDecode(uri.substr(foundIndex, position - foundIndex)));
937 }
938
939 return result;
940 };
941
942
943 /**
944 * Regexp to find trailing question marks and ampersands.
945 * @type {RegExp}
946 * @private
947 */
948 goog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/;
949
950
951 /**
952 * Removes all instances of a query parameter.
953 * @param {string} uri The URI to process. Must not contain a fragment.
954 * @param {string} keyEncoded The URI-encoded key.
955 * @return {string} The URI with all instances of the parameter removed.
956 */
957 goog.uri.utils.removeParam = function(uri, keyEncoded) {
958 var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);
959 var position = 0;
960 var foundIndex;
961 var buffer = [];
962
963 // Look for a query parameter.
964 while ((foundIndex = goog.uri.utils.findParam_(
965 uri, position, keyEncoded, hashOrEndIndex)) >= 0) {
966 // Get the portion of the query string up to, but not including, the ?
967 // or & starting the parameter.
968 buffer.push(uri.substring(position, foundIndex));
969 // Progress to immediately after the '&'. If not found, go to the end.
970 // Avoid including the hash mark.
971 position = Math.min(
972 (uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex);
973 }
974
975 // Append everything that is remaining.
976 buffer.push(uri.substr(position));
977
978 // Join the buffer, and remove trailing punctuation that remains.
979 return buffer.join('').replace(
980 goog.uri.utils.trailingQueryPunctuationRe_, '$1');
981 };
982
983
984 /**
985 * Replaces all existing definitions of a parameter with a single definition.
986 *
987 * Repeated calls to this can exhibit quadratic behavior due to the need to
988 * find existing instances and reconstruct the string, though it should be
989 * limited given the 2kb limit. Consider using appendParams or setParamsFromMap
990 * to update multiple parameters in bulk.
991 *
992 * @param {string} uri The original URI, which may already have query data.
993 * @param {string} keyEncoded The key, which must already be URI encoded.
994 * @param {*} value The value, which will be stringized and encoded (assumed
995 * not already to be encoded).
996 * @return {string} The URI with the query parameter added.
997 */
998 goog.uri.utils.setParam = function(uri, keyEncoded, value) {
999 return goog.uri.utils.appendParam(
1000 goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value);
1001 };
1002
1003
1004 /**
1005 * Effeciently set or remove multiple query parameters in a URI. Order of
1006 * unchanged parameters will not be modified, all updated parameters will be
1007 * appended to the end of the query. Params with values of null or undefined are
1008 * removed.
1009 *
1010 * @param {string} uri The URI to process.
1011 * @param {!Object<string, goog.uri.utils.QueryValue>} params A list of
1012 * parameters to update. If null or undefined, the param will be removed.
1013 * @return {string} An updated URI where the query data has been updated with
1014 * the params.
1015 */
1016 goog.uri.utils.setParamsFromMap = function(uri, params) {
1017 var parts = goog.uri.utils.splitQueryData_(uri);
1018 var queryData = parts[1];
1019 var buffer = [];
1020 if (queryData) {
1021 goog.array.forEach(queryData.split('&'), function(pair) {
1022 var indexOfEquals = pair.indexOf('=');
1023 var name = indexOfEquals >= 0 ? pair.substr(0, indexOfEquals) : pair;
1024 if (!params.hasOwnProperty(name)) {
1025 buffer.push(pair);
1026 }
1027 });
1028 }
1029 parts[1] = goog.uri.utils.appendQueryData_(
1030 buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params));
1031 return goog.uri.utils.joinQueryData_(parts);
1032 };
1033
1034
1035 /**
1036 * Generates a URI path using a given URI and a path with checks to
1037 * prevent consecutive "//". The baseUri passed in must not contain
1038 * query or fragment identifiers. The path to append may not contain query or
1039 * fragment identifiers.
1040 *
1041 * @param {string} baseUri URI to use as the base.
1042 * @param {string} path Path to append.
1043 * @return {string} Updated URI.
1044 */
1045 goog.uri.utils.appendPath = function(baseUri, path) {
1046 goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);
1047
1048 // Remove any trailing '/'
1049 if (goog.string.endsWith(baseUri, '/')) {
1050 baseUri = baseUri.substr(0, baseUri.length - 1);
1051 }
1052 // Remove any leading '/'
1053 if (goog.string.startsWith(path, '/')) {
1054 path = path.substr(1);
1055 }
1056 return goog.string.buildString(baseUri, '/', path);
1057 };
1058
1059
1060 /**
1061 * Replaces the path.
1062 * @param {string} uri URI to use as the base.
1063 * @param {string} path New path.
1064 * @return {string} Updated URI.
1065 */
1066 goog.uri.utils.setPath = function(uri, path) {
1067 // Add any missing '/'.
1068 if (!goog.string.startsWith(path, '/')) {
1069 path = '/' + path;
1070 }
1071 var parts = goog.uri.utils.split(uri);
1072 return goog.uri.utils.buildFromEncodedParts(
1073 parts[goog.uri.utils.ComponentIndex.SCHEME],
1074 parts[goog.uri.utils.ComponentIndex.USER_INFO],
1075 parts[goog.uri.utils.ComponentIndex.DOMAIN],
1076 parts[goog.uri.utils.ComponentIndex.PORT], path,
1077 parts[goog.uri.utils.ComponentIndex.QUERY_DATA],
1078 parts[goog.uri.utils.ComponentIndex.FRAGMENT]);
1079 };
1080
1081
1082 /**
1083 * Standard supported query parameters.
1084 * @enum {string}
1085 */
1086 goog.uri.utils.StandardQueryParam = {
1087
1088 /** Unused parameter for unique-ifying. */
1089 RANDOM: 'zx'
1090 };
1091
1092
1093 /**
1094 * Sets the zx parameter of a URI to a random value.
1095 * @param {string} uri Any URI.
1096 * @return {string} That URI with the "zx" parameter added or replaced to
1097 * contain a random string.
1098 */
1099 goog.uri.utils.makeUnique = function(uri) {
1100 return goog.uri.utils.setParam(
1101 uri, goog.uri.utils.StandardQueryParam.RANDOM,
1102 goog.string.getRandomString());
1103 };