From b98112e0187090421ed60bf3cd23635076fb12d6 Mon Sep 17 00:00:00 2001 From: Ninad Sheth Date: Mon, 16 Sep 2024 20:25:27 +0530 Subject: [PATCH] Fixed cookies parsing bug --- packages/core/src/discovery.js | 23 +++++++++++++++-------- packages/core/src/network.js | 4 ++-- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/packages/core/src/discovery.js b/packages/core/src/discovery.js index 743d90e44..d7930c4e1 100644 --- a/packages/core/src/discovery.js +++ b/packages/core/src/discovery.js @@ -78,6 +78,20 @@ function debugSnapshotOptions(snapshot) { } } +// parse browser cookies in correct format if flag is enabled +// it assumes that cookiesStr is string returned by document.cookie +function parseCookies(cookiesStr) { + if ( + process.env.PERCY_DO_NOT_USE_CAPTURED_COOKIES === 'true' || + !(typeof cookiesStr === 'string' && cookiesStr !== '') + ) return null; + + return cookiesStr.split('; ').map(c => { + const eqIdx = c.indexOf('='); + return { name: c.substring(0, eqIdx), value: c.substring(eqIdx + 1) }; + }); +} + // Wait for a page's asset discovery network to idle function waitForDiscoveryNetworkIdle(page, options) { let { allowedHostnames, networkIdleTimeout, captureResponsiveAssetsEnabled } = options; @@ -160,14 +174,7 @@ async function* captureSnapshotResources(page, snapshot, options) { const log = logger('core:discovery'); let { discovery, additionalSnapshots = [], ...baseSnapshot } = snapshot; let { capture, captureWidths, deviceScaleFactor, mobile, captureForDevices } = options; - let cookies; - if (process.env.PERCY_DO_NOT_USE_CAPTURED_COOKIES !== 'true') { - cookies = snapshot?.domSnapshot?.cookies; - } - if (typeof cookies === 'string' && cookies !== '') { - cookies = cookies.split('; ').map(c => c.split('=')); - cookies = cookies.map(([key, value]) => { return { name: key, value: value }; }); - } + let cookies = parseCookies(snapshot?.domSnapshot?.cookies); // iterate over device to trigger reqeusts and capture other dpr width async function* captureResponsiveAssets() { diff --git a/packages/core/src/network.js b/packages/core/src/network.js index 711518fd7..d2327799b 100644 --- a/packages/core/src/network.js +++ b/packages/core/src/network.js @@ -474,7 +474,7 @@ async function saveResponseResource(network, request) { // font anyway as font responses from the browser may not be properly encoded, // so request them directly. if (mimeType?.includes('font') || (detectedMime && detectedMime.includes('font'))) { - log.debug('- Requesting asset directly'); + log.debug('- Requesting asset directly', meta); body = await makeDirectRequest(network, request); } @@ -491,7 +491,7 @@ async function saveResponseResource(network, request) { log.debug(`- mimetype: ${resource.mimetype}`, meta); } catch (error) { log.debug(`Encountered an error processing resource: ${url}`, meta); - log.debug(error); + log.debug(error, meta); } }