From 9637cea6e5b90ffc7a1319798c9eab85f01252c1 Mon Sep 17 00:00:00 2001 From: rinart73 Date: Mon, 10 Jul 2023 00:22:35 +0200 Subject: [PATCH] Fix handling search and hash in requests - Fix: Search or hash in a requested URL cause redirect loop even if though domain and pathname are correct. - Fix: Search isn't kept when redirecting to a corrected URL. --- src/index.test.ts | 18 ++++++++++++++++++ src/lib/index.ts | 13 +++++++++---- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/src/index.test.ts b/src/index.test.ts index f5453ab..1490bb5 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -392,6 +392,24 @@ describe('checkPage', () => { expect(checkPage(LP, 'ru')).toMatchObject([PageCheckResult.NotLocalized]); expect(consoleError).toHaveBeenCalledTimes(0); }); + it('handles URLs with search', () => { + initDefault(); + localizeParam(1, 'l_about', { + en: 'about-us', + ru: 'o-nas' + }); + let LP = localizePage( + new URL('http://foo.com/ru/o-nas?foo=bar'), + '/[[lang=lang]]/[l_about]' + ); + expect(checkPage(LP, 'ru')).toMatchObject([PageCheckResult.Success]); + LP = localizePage(new URL('http://foo.com/ru/about?foo=bar'), '/[[lang=lang]]/[l_about]'); + expect(checkPage(LP, 'ru')).toMatchObject([ + PageCheckResult.Corrected, + 'http://foo.com/ru/o-nas?foo=bar' + ]); + expect(consoleError).toHaveBeenCalledTimes(0); + }); }); describe('validatePage', () => { diff --git a/src/lib/index.ts b/src/lib/index.ts index b0bad54..e0812de 100644 --- a/src/lib/index.ts +++ b/src/lib/index.ts @@ -584,18 +584,23 @@ export function checkPage( page: LocalizedPage, locale: string ): [PageCheckResult.Corrected, string] | [PageCheckResult] { - const correctPath = href(page, locale, { + const correctHref = href(page, locale, { base: page._url.pathname, params: getPageParams(page, true) }); - if (!correctPath) { + + if (!correctHref) { // not available for this locale page._isNotAvailableForLocale = true; return [PageCheckResult.NotLocalized]; } - if (correctPath !== page._url.href) { - return [PageCheckResult.Corrected, correctPath]; + + const correctUrl = new URL(correctHref); + if (correctUrl.host !== page._url.host || correctUrl.pathname !== page._url.pathname) { + correctUrl.search = page._url.search; + return [PageCheckResult.Corrected, correctUrl.href]; } + return [PageCheckResult.Success]; }