import logger from '@percy/logger'; import Queue from './queue.js'; import Page from './page.js'; import { normalizeURL, hostnameMatches, createResource, createRootResource, createPercyCSSResource, yieldAll, snapshotLogName, waitForTimeout, withRetries, waitForSelectorInsideBrowser, isGzipped, maybeScrollToBottom, assertNotMetadataTarget } from './utils.js'; import { ByteLRU, entrySize, DiskSpillStore, createSpillDir } from './cache/byte-lru.js'; import { sha256hash } from '@percy/client/utils'; import Pako from 'pako'; import { MAX_RESOURCE_SIZE, logAssetInstrumentation } from './network.js'; // Logs verbose debug logs detailing various snapshot options. function debugSnapshotOptions(snapshot) { let log = logger('core:snapshot'); // log snapshot info log.debug('---------', snapshot.meta); log.debug(`Received snapshot: ${snapshot.name}`, snapshot.meta); // will log debug info for an object property if its value is defined let debugProp = (obj, prop, format = String) => { let val = prop.split('.').reduce((o, k) => o?.[k], obj); if (val != null) { // join formatted array values with a space val = [].concat(val).map(format).join(', '); log.debug(`- ${prop}: ${val}`, snapshot.meta); } }; debugProp(snapshot, 'url'); debugProp(snapshot, 'scope'); debugProp(snapshot, 'widths', v => `${v}px`); debugProp(snapshot, 'minHeight', v => `${v}px`); debugProp(snapshot, 'enableJavaScript'); debugProp(snapshot, 'cliEnableJavaScript'); debugProp(snapshot, 'disableShadowDOM'); debugProp(snapshot, 'forceShadowAsLightDOM'); debugProp(snapshot, 'enableLayout'); debugProp(snapshot, 'domTransformation'); debugProp(snapshot, 'reshuffleInvalidTags'); debugProp(snapshot, 'deviceScaleFactor'); debugProp(snapshot, 'waitForTimeout'); debugProp(snapshot, 'waitForSelector'); debugProp(snapshot, 'scopeOptions.scroll'); debugProp(snapshot, 'browsers'); debugProp(snapshot, 'execute.afterNavigation'); debugProp(snapshot, 'execute.beforeResize'); debugProp(snapshot, 'execute.afterResize'); debugProp(snapshot, 'execute.beforeSnapshot'); debugProp(snapshot, 'discovery.allowedHostnames'); debugProp(snapshot, 'discovery.disallowedHostnames'); debugProp(snapshot, 'discovery.devicePixelRatio'); debugProp(snapshot, 'discovery.requestHeaders', JSON.stringify); debugProp(snapshot, 'discovery.authorization', JSON.stringify); debugProp(snapshot, 'discovery.disableCache'); debugProp(snapshot, 'discovery.captureMockedServiceWorker'); debugProp(snapshot, 'discovery.captureSrcset'); debugProp(snapshot, 'discovery.userAgent'); debugProp(snapshot, 'clientInfo'); debugProp(snapshot, 'environmentInfo'); debugProp(snapshot, 'domSnapshot', Boolean); debugProp(snapshot, 'discovery.scrollToBottom'); debugProp(snapshot, 'ignoreCanvasSerializationErrors'); debugProp(snapshot, 'ignoreStyleSheetSerializationErrors'); debugProp(snapshot, 'pseudoClassEnabledElements', JSON.stringify); debugProp(snapshot, 'enablePseudoClassSerialization'); debugProp(snapshot, 'discovery.autoConfigureAllowedHostnames'); if (Array.isArray(snapshot.domSnapshot)) { debugProp(snapshot, 'domSnapshot.0.userAgent'); } else { debugProp(snapshot, 'domSnapshot.userAgent'); } for (let added of (snapshot.additionalSnapshots || [])) { log.debug(`Additional snapshot: ${added.name}`, snapshot.meta); debugProp(added, 'waitForTimeout'); debugProp(added, 'waitForSelector'); debugProp(added, 'execute'); } } // parse browser cookies in correct format if flag is enabled function parseCookies(cookies) { if (process.env.PERCY_DO_NOT_USE_CAPTURED_COOKIES === 'true') return null; // If cookies is collected via SDK if (Array.isArray(cookies) && cookies.every(item => typeof item === 'object' && 'name' in item && 'value' in item)) { // omit other fields reason sometimes expiry comes as actual date where we expect it to be double return cookies.map(c => ({ name: c.name, value: c.value, secure: c.secure, domain: c.domain })); } if (!(typeof cookies === 'string' && cookies !== '')) return null; // it assumes that cookiesStr is string returned by document.cookie const cookiesStr = cookies; return cookiesStr.split('; ').map(c => { const eqIdx = c.indexOf('='); const name = c.substring(0, eqIdx); const value = c.substring(eqIdx + 1); const cookieObj = { name, value }; if (name.startsWith('__Secure')) { cookieObj.secure = true; } return cookieObj; }); } // Wait for a page's asset discovery network to idle function waitForDiscoveryNetworkIdle(page, options) { let { allowedHostnames, networkIdleTimeout, captureResponsiveAssetsEnabled } = options; let filter = r => hostnameMatches(allowedHostnames, r.url); return page.network.idle(filter, networkIdleTimeout, captureResponsiveAssetsEnabled); } async function waitForFontLoading(page) { return await logger.measure('core:discovery', 'waitForFontLoading', undefined, async () => { return await Promise.race([ page.eval('await document.fonts.ready;'), new Promise((res) => setTimeout(res, 5000)) ]); }); } // Creates an initial resource map for a snapshot containing serialized DOM function parseDomResources({ url, domSnapshot }) { const map = new Map(); if (!domSnapshot) return map; let allRootResources = new Set(); let allResources = new Set(); if (!Array.isArray(domSnapshot)) { domSnapshot = [domSnapshot]; } for (let dom of domSnapshot) { let isHTML = typeof dom === 'string'; let { html, resources = [] } = isHTML ? { html: dom } : dom; resources.forEach(r => allResources.add(r)); const attrs = dom.width ? { widths: [dom.width] } : {}; let rootResource = createRootResource(url, html, attrs); allRootResources.add(rootResource); } allRootResources = Array.from(allRootResources); map.set(allRootResources[0].url, allRootResources); allResources = Array.from(allResources); // reduce the array of resources into a keyed map return allResources.reduce((map, { url, content, mimetype }) => { // serialized resource contents are base64 encoded content = Buffer.from(content, mimetype.includes('text') ? 'utf8' : 'base64'); // specify the resource as provided to prevent overwriting during asset discovery let resource = createResource(url, content, mimetype, { provided: true }); // key the resource by its url and return the map return map.set(resource.url, resource); // the initial map is created with at least a root resource }, map); } function createAndApplyPercyCSS({ percyCSS, roots }) { let css = createPercyCSSResource(roots[0].url, percyCSS); // replace root contents and associated properties roots.forEach(root => { Object.assign(root, createRootResource(root.url, ( root.content.replace(/(<\/body>)(?!.*\1)/is, ( `` ) + '$&')))); }); return css; } // Calls the provided callback with additional resources function processSnapshotResources({ domSnapshot, resources, ...snapshot }) { let log = logger('core:snapshot'); resources = [...(resources?.values() ?? [])]; // find any root resource matching the provided dom snapshot // since root resources are stored as array let roots = resources.find(r => Array.isArray(r)); // initialize root resources if needed if (!roots) { let domResources = parseDomResources({ ...snapshot, domSnapshot }); resources = [...domResources.values(), ...resources]; roots = resources.find(r => Array.isArray(r)); } // inject Percy CSS if (snapshot.percyCSS) { // check @percy/dom/serialize-dom.js let domSnapshotHints = domSnapshot?.hints ?? []; if (domSnapshotHints.includes('DOM elements found outside ')) { log.warn('DOM elements found outside , percyCSS might not work'); } const percyCSSReource = createAndApplyPercyCSS({ percyCSS: snapshot.percyCSS, roots }); resources.push(percyCSSReource); } // For multi dom root resources are stored as array resources = resources.flat(); if (process.env.PERCY_GZIP) { const kept = []; for (let index = 0; index < resources.length; index++) { const resource = resources[index]; // Never compress in place: these objects are shared with the resource // cache, which must keep replaying the original bytes to the browser. let uploaded = resource; try { /* istanbul ignore else: an already-gzipped resource is very hard to mock */ if (!isGzipped(resource.content)) { const content = Pako.gzip(resource.content); uploaded = { ...resource, content, sha: sha256hash(content) }; log.debug(`- Gzipped resource: ${resource.url}`); } } catch (error) { // One bad resource must not fail the whole snapshot. logAssetInstrumentation(log, 'asset_load_missing', 'network_error', { url: resource.url, snapshot: snapshot.meta?.snapshot, error: error.message }); log.warn(`- Skipping resource: gzip failed for ${resource.url} - ${error.message}`); continue; } // Either the gzipped copy or, when already gzipped, the resource itself. const size = uploaded.content.length; // Root (DOM HTML) and log resources are required for a valid snapshot; // shipping an oversized one and letting the API surface a clear error // is better than silently dropping it here. if (size > MAX_RESOURCE_SIZE && !resource.root && !resource.log) { logAssetInstrumentation(log, 'asset_not_uploaded', 'resource_too_large', { url: resource.url, size, snapshot: snapshot.meta?.snapshot }); log.debug( `- Skipping resource larger than allowed size after gzip (${size} bytes)`, { url: resource.url } ); continue; } kept.push(uploaded); } resources = kept; } return { ...snapshot, resources }; } // Triggers the capture of resource requests for a page by iterating over snapshot widths to resize // the page and calling any provided execute options. 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 = snapshot.domSnapshot?.cookies || snapshot.domSnapshot?.[0]?.cookies; cookies = parseCookies(cookies); // iterate over device to trigger requests and capture other dpr width async function* captureResponsiveAssets() { for (const device of captureForDevices) { discovery = { ...discovery, captureResponsiveAssetsEnabled: true }; // We are not adding these widths and pixels ratios in loop below because we want to explicitly reload the page after resize which we dont do below yield* captureSnapshotResources(page, { ...snapshot, discovery, widths: [device.width] }, { deviceScaleFactor: device.deviceScaleFactor, mobile: true }); yield waitForFontLoading(page); yield waitForDiscoveryNetworkIdle(page, discovery); } } // used to take snapshots and remove any discovered root resource async function* takeSnapshot(options, width) { if (captureWidths) options = { ...options, width }; let captured = await page.snapshot(options); yield* captureResponsiveAssets(); captured.resources.delete(normalizeURL(captured.url)); capture(processSnapshotResources(captured)); return captured; }; // used to resize the using capture options let resizePage = width => { page.network.intercept.currentWidth = width; return page.resize({ height: snapshot.minHeight, deviceScaleFactor, mobile, width }); }; // navigate to the url yield resizePage(snapshot.widths[0]); // refuse to navigate the top-level snapshot URL to a cloud metadata endpoint assertNotMetadataTarget(snapshot.url); yield page.goto(snapshot.url, { cookies, forceReload: discovery.captureResponsiveAssetsEnabled }); // wait for any specified timeout if (snapshot.discovery.waitForTimeout && page.enableJavaScript) { log.debug(`Wait for ${snapshot.discovery.waitForTimeout}ms timeout`); await waitForTimeout(snapshot.discovery.waitForTimeout); } // wait for any specified selector if (snapshot.discovery.waitForSelector && page.enableJavaScript) { log.debug(`Wait for selector: ${snapshot.discovery.waitForSelector}`); await waitForSelectorInsideBrowser(page, snapshot.discovery.waitForSelector, Page.TIMEOUT); } if (snapshot.execute) { // when any execute options are provided, inject snapshot options /* istanbul ignore next: cannot detect coverage of injected code */ yield page.eval((_, s) => (window.__PERCY__.snapshot = s), snapshot); yield page.evaluate(snapshot.execute.afterNavigation); } yield* maybeScrollToBottom(page, discovery); // Running before page idle since this will trigger many network calls // so need to run as early as possible. plus it is just reading urls from dom srcset // which will be already loaded after navigation complete // Don't run incase of responsiveSnapshotCapture since we are running discovery for all widths so images will get captured in all required widths if (!snapshot.responsiveSnapshotCapture && discovery.captureSrcset) { await page.insertPercyDom(); yield page.eval('window.PercyDOM.loadAllSrcsetLinks()'); } // iterate over additional snapshots for proper DOM capturing for (let additionalSnapshot of [baseSnapshot, ...additionalSnapshots]) { let isBaseSnapshot = additionalSnapshot === baseSnapshot; let snap = { ...baseSnapshot, ...additionalSnapshot }; let { widths, execute } = snap; let [width] = widths; // iterate over widths to trigger requests and capture other widths if (isBaseSnapshot || captureWidths) { for (let i = 0; i < widths.length - 1; i++) { if (captureWidths) yield* takeSnapshot(snap, width); yield page.evaluate(execute?.beforeResize); yield waitForFontLoading(page); yield waitForDiscoveryNetworkIdle(page, discovery); yield resizePage(width = widths[i + 1]); if (snapshot.responsiveSnapshotCapture) { yield page.goto(snapshot.url, { cookies, forceReload: true }); } yield page.evaluate(execute?.afterResize); yield* maybeScrollToBottom(page, discovery); } } if (capture && !snapshot.domSnapshot) { // capture this snapshot and update the base snapshot after capture let captured = yield* takeSnapshot(snap, width); if (isBaseSnapshot) baseSnapshot = captured; // resize back to the initial width when capturing additional snapshot widths if (captureWidths && additionalSnapshots.length) { let l = additionalSnapshots.indexOf(additionalSnapshot) + 1; if (l < additionalSnapshots.length) yield resizePage(snapshot.widths[0]); } } } // recursively trigger resource requests for any alternate device pixel ratio if (discovery.devicePixelRatio) { log.deprecated('discovery.devicePixelRatio is deprecated percy will now auto capture resource in all devicePixelRatio, Ignoring configuration'); } // wait for final network idle when not capturing DOM if (capture && snapshot.domSnapshot) { yield waitForFontLoading(page); yield waitForDiscoveryNetworkIdle(page, discovery); yield* captureResponsiveAssets(); capture(processSnapshotResources(snapshot)); } } // Pushes all provided snapshots to a discovery queue with the provided callback, yielding to each // one concurrently. When skipping asset discovery, the callback is called immediately for each // snapshot, also processing snapshot resources when not dry-running. export async function* discoverSnapshotResources(queue, options, callback) { let { snapshots, skipDiscovery, dryRun, checkAndUpdateConcurrency } = options; yield* yieldAll(snapshots.reduce((all, snapshot) => { debugSnapshotOptions(snapshot); if (skipDiscovery) { let { additionalSnapshots, ...baseSnapshot } = snapshot; additionalSnapshots = (dryRun && additionalSnapshots) || []; for (let snap of [baseSnapshot, ...additionalSnapshots]) { callback(dryRun ? snap : processSnapshotResources(snap)); } } else { // update concurrency before pushing new job in discovery queue // if case of monitoring is stopped due to in-activity, // it can take upto 1 sec to execute this fun checkAndUpdateConcurrency(); all.push(queue.push(snapshot, callback)); } return all; }, [])); } export const RESOURCE_CACHE_KEY = Symbol('resource-cache'); export const CACHE_STATS_KEY = Symbol('resource-cache-stats'); export const DISK_SPILL_KEY = Symbol('resource-cache-disk-spill'); const BYTES_PER_MB = 1_000_000; // MAX_RESOURCE_SIZE in network.js is 25MB; caps below that would skip every // resource, so we clamp. MIN_REASONABLE_CAP_MB warns on near-useless caps. const MAX_RESOURCE_SIZE_MB = 25; const MIN_REASONABLE_CAP_MB = 50; const DEFAULT_WARN_THRESHOLD_BYTES = 500 * BYTES_PER_MB; function makeCacheStats() { return { effectiveMaxCacheRamMB: null, oversizeSkipped: 0, firstEvictionEventFired: false, warningFired: false, unsetModeBytes: 0 }; } function readWarnThresholdBytes() { const raw = Number(process.env.PERCY_CACHE_WARN_THRESHOLD_BYTES); return Number.isFinite(raw) && raw > 0 ? raw : DEFAULT_WARN_THRESHOLD_BYTES; } // Cache lookup shared by the network intercept path. RAM miss falls through // to the disk tier; read failures return undefined so the browser refetches. // Also resolves the array-valued root-resource shape used for multi-width // DOM snapshots, regardless of which tier returned it. // // Disk hits are promoted back to RAM so a hot URL that was evicted once does // not pay the readFileSync cost on every subsequent access — the typical // two-tier-cache promotion pattern. ByteLRU's own eviction will then re-spill // the actual coldest entry if needed. DISK_SPILL_KEY is only set when the // ByteLRU tier is active (see createDiscoveryQueue 'start' handler), so the // cache here is guaranteed to be a ByteLRU when we enter this branch. export function lookupCacheResource(percy, snapshotResources, cache, url, width, rootUrl) { let resource = snapshotResources.get(url); // @percy/dom keys the resources it fabricates by a root-relative URL // (/__serialized__/.) so no host or scheme is baked into the // snapshot; the discovery browser requests the resolved absolute form. // Match on the origin-less form (path + query), but only for requests from // the snapshot's own origin: a root-relative href can resolve nowhere else, // and an allowed cross-origin request must never be answered with the // snapshot's bytes. Both snapshot lookups run before the shared cache so a // snapshot's own provided bytes always win over whatever an earlier fetch // of the same URL left cached. if (!resource && rootUrl) { try { let { origin, pathname, search } = new URL(url); if (origin === new URL(rootUrl).origin) { resource = snapshotResources.get(pathname + search); } } catch (e) { // url is not absolute -- nothing further to try } } if (!resource) resource = cache.get(url); const disk = percy[DISK_SPILL_KEY]; if (!resource && disk) { resource = disk.get(url); if (resource) { percy.log.debug( `cache disk-hit: ${url} (disk=${disk.size}/` + `${Math.round(disk.bytes / BYTES_PER_MB)}MB)` ); // Promote back to RAM and drop the disk copy. cache.set may itself // evict the LRU entry (which spills back to disk) — that's the // intended LRU dance, not a bug. cache.set(url, resource, entrySize(resource)); disk.delete(url); } } if (resource && Array.isArray(resource) && resource[0].root) { const rootResource = resource.find(r => r.widths?.includes(width)); resource = rootResource || resource[0]; } return resource; } // Fire-and-forget wrapper around the shared telemetry egress on Percy. // onEvict callbacks are sync; the microtask hop keeps even sendCacheTelemetry's // pre-await synchronous work (header construction, payload serialization) off // the eviction-loop hot path. function fireCacheEventSafe(percy, message, extra) { // sendCacheTelemetry already swallows pager errors. The trailing .catch is // belt-and-suspenders against Node 14's unhandled-rejection-as-fatal mode // if the catch arm itself ever throws (e.g. log.debug stub explodes). Promise.resolve() .then(() => percy.sendCacheTelemetry(message, extra)) .catch(() => {}); } // Creates an asset discovery queue that uses the percy browser instance to create a page for each // snapshot which is used to intercept and capture snapshot resource requests. export function createDiscoveryQueue(percy) { let { concurrency } = percy.config.discovery; let queue = new Queue('discovery'); let cache; let capBytes = null; // Read once: saveResource consults this on every call. const warnThreshold = readWarnThresholdBytes(); return queue .set({ concurrency }) .handle('start', async () => { const configuredMaxCacheRamMB = percy.config.discovery.maxCacheRam; let effectiveMaxCacheRamMB = configuredMaxCacheRamMB; // Cache stores raw bodies; under PERCY_GZIP individual resources can // exceed the default 25MB floor, so the floor must track the active cap. const minCacheRamMB = process.env.PERCY_GZIP ? 50 : MAX_RESOURCE_SIZE_MB; // User's config is not mutated; the post-clamp value lives on stats. if (configuredMaxCacheRamMB != null) { if (configuredMaxCacheRamMB < minCacheRamMB) { percy.log.warn( `--max-cache-ram=${configuredMaxCacheRamMB}MB is below the ${minCacheRamMB}MB minimum ` + `(individual resources up to ${minCacheRamMB}MB would otherwise be dropped). ` + `Continuing with the minimum: ${minCacheRamMB}MB.` ); effectiveMaxCacheRamMB = minCacheRamMB; } else if (configuredMaxCacheRamMB < MIN_REASONABLE_CAP_MB) { percy.log.warn( `--max-cache-ram=${configuredMaxCacheRamMB}MB is very small; ` + 'most resources will not fit and hit rate will be near zero.' ); } if (percy.config.discovery.disableCache) { percy.log.info('--max-cache-ram is ignored because --disable-cache is set.'); } capBytes = effectiveMaxCacheRamMB * BYTES_PER_MB; } if (warnThreshold !== DEFAULT_WARN_THRESHOLD_BYTES) { percy.log.debug( `PERCY_CACHE_WARN_THRESHOLD_BYTES override active: ${warnThreshold} bytes ` + `(default ${DEFAULT_WARN_THRESHOLD_BYTES}).` ); } percy[CACHE_STATS_KEY] = makeCacheStats(); percy[CACHE_STATS_KEY].effectiveMaxCacheRamMB = capBytes != null ? effectiveMaxCacheRamMB : null; if (capBytes != null) { // Overflow tier: RAM evictions spill here. diskStore.set returns // false on any I/O failure → caller falls back to drop automatically. const diskStore = new DiskSpillStore(createSpillDir(), { log: percy.log }); percy[DISK_SPILL_KEY] = diskStore; cache = percy[RESOURCE_CACHE_KEY] = new ByteLRU(capBytes, { onEvict: (key, reason, value) => { if (reason === 'too-big') { percy[CACHE_STATS_KEY].oversizeSkipped++; percy.log.debug(`cache skip (oversize): ${key}`); return; } const spilled = diskStore.set(key, value); percy.log.debug( `cache ${spilled ? 'spill' : 'evict'}: ${key} ` + `(cache ${Math.round(cache.calculatedSize / BYTES_PER_MB)}` + `/${effectiveMaxCacheRamMB}MB, entries=${cache.size}, ` + `disk=${diskStore.size}/${Math.round(diskStore.bytes / BYTES_PER_MB)}MB)` ); const stats = percy[CACHE_STATS_KEY]; if (stats && !stats.firstEvictionEventFired) { stats.firstEvictionEventFired = true; percy.log.info( 'Cache eviction active — cap reached, oldest entries spilling to disk.' ); fireCacheEventSafe(percy, 'cache_eviction_started', { cache_budget_ram_mb: effectiveMaxCacheRamMB, cache_peak_bytes_seen: cache.stats.peakBytes, eviction_count: cache.stats.evictions, disk_spill_enabled: diskStore.ready }); } } }); } else { cache = percy[RESOURCE_CACHE_KEY] = new Map(); } await percy.browser.launch(); queue.run(); }) .handle('end', async () => { // Disk-spill cleanup must run even if browser.close() throws — otherwise // the per-run temp dir under os.tmpdir() leaks. CACHE_STATS_KEY is set // alongside DISK_SPILL_KEY in 'start', so the snapshot is always safe. try { await percy.browser.close(); } finally { const diskStore = percy[DISK_SPILL_KEY]; if (diskStore) { percy[CACHE_STATS_KEY].finalDiskStats = { ...diskStore.stats, ready: diskStore.ready }; diskStore.destroy(); delete percy[DISK_SPILL_KEY]; } } }) // snapshots are unique by name and testCase; when deferred also by widths .handle('find', ({ name, testCase, widths }, snapshot) => ( snapshot.testCase === testCase && snapshot.name === name && (!percy.deferUploads || ( !widths || widths.join() === snapshot.widths.join())) )) // initialize the resources for DOM snapshots .handle('push', snapshot => { let resources = parseDomResources(snapshot); return { ...snapshot, resources }; }) // discovery resources for snapshots and call the callback for each discovered snapshot .handle('task', async function*(snapshot, callback) { await logger.measure('asset-discovery', snapshot.name, snapshot.meta, async () => { percy.log.debug(`Discovering resources: ${snapshot.name}`, snapshot.meta); // expectation explained in tests /* istanbul ignore next: tested, but coverage is stripped */ let assetDiscoveryPageEnableJS = (snapshot.cliEnableJavaScript && !snapshot.domSnapshot) || (snapshot.enableJavaScript ?? !snapshot.domSnapshot); percy.log.debug(`Asset discovery Browser Page enable JS: ${assetDiscoveryPageEnableJS}`, snapshot.meta); await withRetries(async function*() { // create a new browser page let page = yield percy.browser.page({ enableJavaScript: assetDiscoveryPageEnableJS, networkIdleTimeout: snapshot.discovery.networkIdleTimeout, requestHeaders: snapshot.discovery.requestHeaders, authorization: snapshot.discovery.authorization, userAgent: snapshot.discovery.userAgent, fontDomains: snapshot.discovery.fontDomains, captureMockedServiceWorker: snapshot.discovery.captureMockedServiceWorker, meta: { ...snapshot.meta, snapshotURL: snapshot.url }, // pass domain validation context for auto-allowlisting domainValidation: percy.domainValidation, client: percy.client, autoConfigureAllowedHostnames: snapshot.discovery.autoConfigureAllowedHostnames, // enable network inteception intercept: { enableJavaScript: snapshot.enableJavaScript, disableCache: snapshot.discovery.disableCache, allowedHostnames: snapshot.discovery.allowedHostnames, disallowedHostnames: snapshot.discovery.disallowedHostnames, getResource: (u, width = null) => ( lookupCacheResource(percy, snapshot.resources, cache, u, width, snapshot.url) ), saveResource: r => { const limitResources = process.env.LIMIT_SNAPSHOT_RESOURCES || false; const MAX_RESOURCES = Number(process.env.MAX_SNAPSHOT_RESOURCES) || 749; if (limitResources && snapshot.resources.size >= MAX_RESOURCES) { percy.log.debug(`Skipping resource ${r.url} — resource limit reached`); return; } snapshot.resources.set(r.url, r); if (snapshot.discovery.disableCache) return; // Fresh write supersedes any prior spill — prevents races // where getResource could serve a stale disk copy. if (percy[DISK_SPILL_KEY]?.has(r.url)) { percy[DISK_SPILL_KEY].delete(r.url); } if (capBytes != null) { // ByteLRU fires onEvict('too-big') for oversize entries; // the oversize_skipped stat + debug log live there. cache.set(r.url, r, entrySize(r)); } else { // Subtract the prior entry's footprint before overwriting so // the byte counter tracks current cache contents rather than // cumulative writes. Without this, the same shared CSS saved // across N snapshots would inflate unsetModeBytes by N×. const stats = percy[CACHE_STATS_KEY]; const prior = cache.get(r.url); if (prior) stats.unsetModeBytes -= entrySize(prior); cache.set(r.url, r); stats.unsetModeBytes += entrySize(r); if (!stats.warningFired && stats.unsetModeBytes >= warnThreshold) { stats.warningFired = true; percy.log.warn( `Percy cache is using ${(stats.unsetModeBytes / BYTES_PER_MB).toFixed(1)}MB. ` + 'If your CI is memory-constrained, set --max-cache-ram. ' + 'See https://www.browserstack.com/docs/percy/cli/managing-cache-memory' ); } } } } }); try { yield* captureSnapshotResources(page, snapshot, { captureWidths: !snapshot.domSnapshot && percy.deferUploads, capture: callback, captureForDevices: percy.deviceDetails || [] }); } finally { // always close the page when done await page.close(); } }, { count: snapshot.discovery.retry ? 3 : 1, onRetry: async (error) => { percy.log.info(`Retrying snapshot: ${snapshotLogName(snapshot.name, snapshot.meta)}`, snapshot.meta); // If browser disconnected or crashed, restart it before retrying if (error?.message?.includes('Browser not connected') || error?.message?.includes('Browser closed') || error?.message?.includes('Session closed') || error?.message?.includes('Session crashed')) { percy.log.warn('Detected browser disconnection, restarting browser before retry'); try { await percy.browser.restart(); } catch (restartError) { percy.log.error(`Failed to restart browser: ${restartError}`); throw restartError; } } }, signal: snapshot._ctrl.signal, throwOn: ['AbortError'] }); }); }) .handle('error', async ({ name, meta }, error) => { if (error.name === 'AbortError' && queue.readyState < 3) { // only error about aborted snapshots when not closed let errMsg = 'Received a duplicate snapshot, ' + ( `the previous snapshot was aborted: ${snapshotLogName(name, meta)}`); percy.log.error(errMsg, { snapshotLevel: true, snapshotName: name }); await percy.suggestionsForFix(errMsg, meta); } else { // log all other encountered errors let errMsg = `Encountered an error taking snapshot: ${name}`; percy.log.error(errMsg, meta); percy.log.error(error, meta); let assetDiscoveryErrors = [ { message: errMsg, meta }, { message: error?.message, meta } ]; await percy.suggestionsForFix( assetDiscoveryErrors, { snapshotLevel: true, snapshotName: name } ); } }); }