MCPcopy Create free account
hub / github.com/sindresorhus/query-string / stringifyUrl

Function stringifyUrl

base.js:704–765  ·  view source on GitHub ↗
(object, options)

Source from the content-addressed store, hash-verified

702}
703
704export function stringifyUrl(object, options) {
705 options = {
706 encode: true,
707 strict: true,
708 ...definedOptions(options),
709 };
710
711 // Leading and trailing whitespace is ignored, like `parseUrl()` does. `parse()` already trims the query, so whitespace after it disappeared, while whitespace before it or after the fragment identifier was written back, like `https://foo.bar/ ?a=1`.
712 const inputUrl = object.url.trim();
713
714 const url = getUrlWithoutQuery(removeHash(inputUrl));
715 const queryFromUrl = extract(inputUrl);
716
717 // When the output is not encoded, keep the existing query as-is instead of decoding it. Decoding without re-encoding would corrupt it.
718 // The query in the URL is written back from the plain string values, so `parseNumbers`, `parseBooleans`, and `types` passed along with the stringify options, like when the same options object is shared with `parseUrl()`, do not rewrite a value like `007` as `7`.
719 let query = parse(queryFromUrl, {
720 sort: false,
721 ...options,
722 decode: options.encode,
723 parseNumbers: false,
724 parseBooleans: false,
725 types: undefined,
726 });
727
728 const queryFromObject = Object.fromEntries(Object.entries(object.query ?? {}));
729
730 // The query in the URL is not decoded without encoding, so its keys are compared in their decoded form instead, like they are when the output is encoded. Otherwise a key like `%61` in the URL would not be overridden by an `a` in `query`.
731 if (!options.encode) {
732 const overrides = new Map();
733
734 for (const [key, value] of Object.entries(queryFromObject)) {
735 const decodedKey = decodeQueryKey(key);
736 if (!overrides.has(decodedKey)) {
737 overrides.set(decodedKey, {key, value});
738 }
739 }
740
741 query = Object.fromEntries(Object.entries(query).map(([key, value]) => {
742 const override = overrides.get(decodeQueryKey(key));
743 return override ? [override.key, override.value] : [key, value];
744 }));
745 }
746
747 let queryString = stringify({...query, ...queryFromObject}, options);
748 queryString &&= `?${queryString}`;
749
750 let hash = getHash(inputUrl);
751 if (typeof object.fragmentIdentifier === 'string') {
752 // An empty fragment identifier removes the fragment, like `url.hash = ''` does.
753 hash = object.fragmentIdentifier === '' ? '' : `#${object.fragmentIdentifier}`;
754
755 if (options.encode) {
756 // The fragment identifier is a decoded value, like the query values, so `parseUrl()` reads it back unchanged. That is what the `fragment` component of Go's `net/url`, Java's `URI`, and Swift's `URLComponents` does too. The `URL` hash setter instead expects an already-encoded fragment: it leaves `%` as-is, which would turn `100%` into an invalid URL and `%23top` into `#top` after parsing. So `%` is encoded here first. The URL parser also silently strips ASCII tab and newline from its input, so those are encoded first too. The setter then encodes the rest of the WHATWG fragment percent-encode set (controls, space, `"`, `<`, `>`, and backtick) and keeps `/`, `?`, and `#`, so hash routes like `#/users?id=1` stay readable. With `encode: false`, the fragment identifier is written as-is, like the query.
757 // The fragment percent-encode set does not depend on the scheme, so the caller's URL is deliberately not parsed here; it may not even be parseable.
758 const throwawayUrl = new URL('https://query-string.invalid');
759 throwawayUrl.hash = hash.replaceAll(/[\t\n\r%]/gv, character => `%${character.codePointAt(0).toString(16).toUpperCase().padStart(2, '0')}`);
760 hash = throwawayUrl.hash;
761 }

Callers 2

benchmark.jsFile · 0.85
pickFunction · 0.85

Calls 8

definedOptionsFunction · 0.85
getUrlWithoutQueryFunction · 0.85
removeHashFunction · 0.85
extractFunction · 0.85
parseFunction · 0.85
decodeQueryKeyFunction · 0.85
stringifyFunction · 0.85
getHashFunction · 0.85

Tested by

no test coverage detected