import fs from 'fs'; import path from 'path'; import { spawnSync } from 'child_process'; import globToRegExp from 'glob-to-regexp'; import logger from '@percy/logger'; import { diffLockfileDeps } from './lockfileDiff.js'; import { renderGraphTraceHtml } from './graphTrace.js'; const NULL_CHAR = String.fromCharCode(0); /* istanbul ignore next */ const stripNull = s => (typeof s === 'string' ? s.split(NULL_CHAR).join('') : s); const POLL_INTERVAL_MS = 5000; const POLL_ATTEMPTS = 12; const GLOB_CHARS = /[*?{}[\]]/; const MAX_PATTERN_LENGTH = 500; // Share of stats modules that may have unresolved ids before the dependency // graph is treated as too incomplete to filter on. const MAX_DROPPED_MODULE_RATIO = 0.1; const regexCache = new Map(); function patternToRegex(pattern) { /* istanbul ignore next */ if (typeof pattern !== 'string' || pattern.length > MAX_PATTERN_LENGTH) { throw new Error('Invalid pattern: must be a string with max length of 500 characters'); } let regex = regexCache.get(pattern); if (!regex) { regex = globToRegExp(pattern, { extended: true, globstar: true }); regexCache.set(pattern, regex); } return regex; } // Callers must have cleared `pattern` through `patternError` first -- a glob that // fails to compile is reported there (bail for `bailOnChanges`, warn-and-skip for // `untraced`) rather than being swallowed into a silent non-match here. function matchesPattern(str, pattern) { if (GLOB_CHARS.test(pattern)) return patternToRegex(pattern).test(str); return str === pattern; } // Returns the compile error for a glob, or null when it is usable. Patterns are // validated up front rather than relying on `matchesPattern` swallowing the // throw, so a typo is reported even when nothing happens to be compared to it. function patternError(pattern) { if (!GLOB_CHARS.test(pattern)) return null; try { patternToRegex(pattern); return null; } catch (e) { return e; } } const ROOT_DIR_TOKEN = '/'; // `git diff --name-only` always emits repo-root-relative paths, whatever the // cwd. User patterns are interpreted relative to the invocation directory -- // the same basis as the `importPath` normalization in `applyIntelliStory`, and // the basis a user editing `.percy.yml` beside their config files expects -- so // they have to be rebased onto the repo root before they can match. A // `/` prefix opts out and anchors the pattern to the repo root. // // `rebased` is null when the pattern resolves outside the repo, which no diff // path can ever match; callers report that rather than matching nothing. export function resolvePattern(raw, projectRoot, invocationDir) { const toPosix = p => p.split(path.sep).join('/'); if (raw.startsWith(ROOT_DIR_TOKEN)) { return { raw, rebased: toPosix(raw.slice(ROOT_DIR_TOKEN.length)), anchored: true }; } const abs = path.isAbsolute(raw) ? raw : path.resolve(invocationDir, raw); const rel = path.relative(projectRoot, abs); if (!rel || rel.startsWith('..')) return { raw, rebased: null, anchored: false }; return { raw, rebased: toPosix(rel), anchored: false }; } // Whether `raw` would have matched something under the repo-root reading that // the (correct) invocation-relative reading missed. Used to report the one // mistake this design can still produce -- a pattern written repo-relative -- // instead of letting it silently match nothing. function rootReadingHit(affectedNodes, { raw, rebased, anchored }) { if (anchored || raw === rebased || patternError(raw)) return null; if (affectedNodes.some(p => matchesPattern(p, rebased))) return null; return affectedNodes.find(p => matchesPattern(p, raw)) ?? null; } function describeInvocation(projectRoot, invocationDir) { return path.relative(projectRoot, invocationDir).split(path.sep).join('/') || '.'; } // How to spell a repo-root-relative pattern so it means the same thing under // the invocation-relative contract. Used only in the "you probably meant the // repo root" advice, so it falls back to the `/` form when the target // is not reachable from the invocation directory without escaping it. function suggestRewrite(raw, projectRoot, invocationDir) { const rel = path.relative(invocationDir, path.resolve(projectRoot, raw)).split(path.sep).join('/'); const anchored = `"${ROOT_DIR_TOKEN}${raw}"`; if (!rel || rel.startsWith('..')) return anchored; return `"${rel}" (relative to the invocation directory) or ${anchored}`; } export class IntelliStoryBailError extends Error { constructor(message) { super(message); this.name = 'IntelliStoryBailError'; } } function git(args) { let res; try { res = spawnSync('git', args, { encoding: 'utf8' }); } catch (e) { /* istanbul ignore next */ throw new IntelliStoryBailError(`IntelliStory: git ${args.join(' ')} failed to spawn: ${e.message}; running full snapshot set`); } if (res.status !== 0) { /* istanbul ignore next */ throw new IntelliStoryBailError(`IntelliStory: git ${args.join(' ')} failed: ${res.stderr || res.stdout || `exit ${res.status}`}; running full snapshot set`); } return res.stdout; } function assertSafeRef(ref) { if (typeof ref !== 'string' || !/^[A-Za-z0-9_./][A-Za-z0-9_./-]*$/.test(ref)) { throw new IntelliStoryBailError(`IntelliStory: unsafe baseline ref "${ref}"; running full snapshot set`); } } function gitDiffNames(ref) { assertSafeRef(ref); return git(['-c', 'core.quotepath=false', 'diff', '--name-only', ref, 'HEAD', '--']).split('\n').filter(Boolean); } function gitProjectRoot() { return git(['rev-parse', '--show-toplevel']).trim(); } export function getAffectedFileLocations(baseRef, files) { assertSafeRef(baseRef); const diff = git(['-c', 'core.quotepath=false', 'diff', '--unified=0', '--no-color', '--no-renames', baseRef, 'HEAD', '--']); const toPosix = p => p.split(path.sep).join('/'); const indexByPath = new Map(files.map((f, i) => [toPosix(f), i])); const HUNK = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/; const locations = {}; let currentIdx; for (const line of diff.split('\n')) { if (line.startsWith('+++ ')) { const p = line.slice(4); if (p === '/dev/null') { currentIdx = undefined; continue; } /* istanbul ignore next */ const rel = p.startsWith('b/') ? p.slice(2) : p; currentIdx = indexByPath.get(rel); continue; } if (currentIdx === undefined) continue; const m = HUNK.exec(line); if (!m) continue; const start = parseInt(m[1], 10); const count = m[2] === undefined ? 1 : parseInt(m[2], 10); if (count === 0) continue; if (!locations[currentIdx]) locations[currentIdx] = []; locations[currentIdx].push([start, start + count - 1]); } return locations; } export const DEFAULT_CONFIG_DIR = '.storybook'; // Storybook's config directory is configurable (`-c`), so the literal // `.storybook` cannot be the only thing recognised. `configDirs` always carries // the default alongside any configured directory: recognising one directory too // many only costs snapshots, while missing the real one loses comparisons. // // A single-segment name matches at any depth — a `.storybook` anywhere is a // Storybook config directory, including in a sibling package — while a // multi-segment path (`config/storybook`) is matched as a path prefix so it // cannot also match `config/storybook-old`. function isInsideDirs(relPath, dirs) { const segs = relPath.split(/[/\\]/).filter(Boolean); return dirs.some(dir => { const d = dir.split(/[/\\]/).filter(Boolean); if (!d.length) return false; if (d.length === 1) return segs.includes(d[0]); return d.length <= segs.length && d.every((s, i) => segs[i] === s); }); } const isExcluded = (relPath, configDirs) => ( isInsideDirs(relPath, ['node_modules', ...configDirs]) ); function resolveAndIndex(value, fileIndex, projectRoot, configDirs) { const clean = stripNull(value); if (!path.isAbsolute(clean)) return clean; const rel = path.relative(projectRoot, clean); if (isExcluded(rel, configDirs)) return rel; let idx = fileIndex.get(rel); if (idx === undefined) { idx = fileIndex.size; fileIndex.set(rel, idx); } return idx; } // Returns `{ module }` when the module made it into the graph, or `{ dropped }` // with the reason it did not. The two reasons are not equivalent: `excluded` is // this module deliberately ignoring node_modules and the Storybook config // directory, while `unresolved` is a synthetic or virtual id we could not place // on disk — a hole in the graph, and the only one worth counting. function transformModule(m, fileIndex, projectRoot, configDirs) { const out = {}; if (m.id != null) out.id = resolveAndIndex(m.id, fileIndex, projectRoot, configDirs); if (typeof out.id === 'string') { return { dropped: path.isAbsolute(stripNull(m.id)) ? 'excluded' : 'unresolved' }; } const mapEntry = (e) => { const copy = { ...e }; if (copy.type === 'src' && typeof copy.source === 'string') { copy.source = resolveAndIndex(copy.source, fileIndex, projectRoot, configDirs); } if (Array.isArray(copy.loc)) { copy.loc = copy.loc.map(l => [l.start, l.end]); } return copy; }; if (Array.isArray(m.imports)) out.imports = m.imports.map(mapEntry); if (Array.isArray(m.passThroughExports)) out.passThroughExports = m.passThroughExports.map(mapEntry); if (Array.isArray(m.nonPassThroughExports)) out.nonPassThroughExports = m.nonPassThroughExports; return { module: out }; } function readStats(statsFile, projectRoot, log, configDirs) { const fileIndex = new Map(); const modules = []; let stats; try { stats = JSON.parse(fs.readFileSync(statsFile, 'utf8')); } catch (e) { throw new IntelliStoryBailError(`IntelliStory: failed to parse stats file ${statsFile}: ${e.message}; running full snapshot set`); } /* istanbul ignore next */ const rawModules = stats.modules || []; let unresolved = 0; let excluded = 0; for (const m of rawModules) { const { module, dropped } = transformModule(m, fileIndex, projectRoot, configDirs); if (module) modules.push(module); else if (dropped === 'unresolved') unresolved++; else excluded++; } if (excluded) log?.debug(`IntelliStory: skipped ${excluded} module(s) in node_modules or the Storybook config directory`); // An unresolved module is a missing edge, and a missing edge is exactly what // makes the API judge a story unaffected. A few synthetic ids are normal for // some builders, so this warns rather than bails -- but past the threshold the // graph is degraded enough that filtering on it is not trustworthy. Only // resolvable candidates count towards the ratio: deliberately excluded modules // are not a gap, and including them would bail on healthy builds whose stats // happen to carry a lot of node_modules. if (unresolved) { // at least `unresolved` modules were candidates, so this cannot divide by zero const candidates = rawModules.length - excluded; const ratio = unresolved / candidates; if (ratio > MAX_DROPPED_MODULE_RATIO) { throw new IntelliStoryBailError(`IntelliStory: ${unresolved} of ${candidates} stats modules have unresolved (non-absolute) ids (${Math.round(ratio * 100)}%, limit ${Math.round(MAX_DROPPED_MODULE_RATIO * 100)}%); the dependency graph would be incomplete; running full snapshot set`); } log?.warn(`IntelliStory: dropped ${unresolved} of ${candidates} module(s) with unresolved (non-absolute) ids; the dependency graph may be missing edges for them`); } const files = [...fileIndex.entries()] .sort((a, b) => a[1] - b[1]) .map(([p]) => p); return { files, modules, buildId: stats.buildId }; } // Every other failure mode in this module — git, fs, config, lockfile, glob, // degraded graph — is converted to IntelliStoryBailError so the caller can // degrade to a full snapshot run. API and network failures are no different: a // 403 means the organization is not entitled to IntelliStory, and a 5xx / // timeout / connection reset is transient. Neither should hard-fail the // storybook command, which is what a bare Error does once @percy/storybook // catches IntelliStoryBailError specifically. function isNotAllowed(e) { return e?.response?.statusCode === 403; } function apiBailError(e, action) { if (isNotAllowed(e)) { return new IntelliStoryBailError(`IntelliStory: not enabled for this organization (${action} was not allowed); running full snapshot set`); } return new IntelliStoryBailError(`IntelliStory: ${action} failed: ${e?.message}; running full snapshot set`); } async function pollGraphStatus(percy, buildId, log) { for (let i = 0; i < POLL_ATTEMPTS; i++) { let res; try { res = await percy.client.getStatus('intelli_story_graph', [buildId]); } catch (e) { // A 403 will not resolve by polling again, so stop immediately rather // than burning the full POLL_ATTEMPTS window on it. Anything else is // treated as "not done yet" and retried; if it never clears, the caller's // timed-out bail covers it. if (isNotAllowed(e)) throw apiBailError(e, 'graph status poll'); log.debug(`IntelliStory: graph status (attempt ${i + 1}) errored: ${e?.message}`); if (i < POLL_ATTEMPTS - 1) await new Promise(r => setTimeout(r, POLL_INTERVAL_MS)); continue; } const status = res?.status; log.debug(`IntelliStory: graph status (attempt ${i + 1}) = ${status}`); if (status === 'done' || status === 'failed') return { status, data: res?.data }; if (i < POLL_ATTEMPTS - 1) await new Promise(r => setTimeout(r, POLL_INTERVAL_MS)); } return { status: null }; } export async function validateAndReadStats(buildDir, statsFile, projectRoot, log, configDirs = [DEFAULT_CONFIG_DIR]) { const statsName = path.basename(statsFile || 'enriched-stats.json'); if (!/^[\w.-]+\.json$/i.test(statsName)) { throw new IntelliStoryBailError(`IntelliStory: invalid statsFile "${statsName}" — must be a .json filename; running full snapshot set`); } const resolvedStatsPath = path.join(path.resolve(buildDir), statsName); let statsStat; try { statsStat = fs.statSync(resolvedStatsPath); } catch { throw new IntelliStoryBailError(`IntelliStory: stats file "${statsName}" not found in build directory ${buildDir}; running full snapshot set`); } if (!statsStat.isFile()) { throw new IntelliStoryBailError(`IntelliStory: stats file "${statsName}" in ${buildDir} is not a regular file; running full snapshot set`); } log.debug(`IntelliStory: parsing stats file ${resolvedStatsPath}`); // The graph is keyed by the Percy build id, not the stats-file `buildId`, so a // missing `buildId` here is not fatal — it is logged only so a support ticket // can be tied back to the Storybook build that produced this stats file. const { files, modules, buildId } = await readStats(resolvedStatsPath, projectRoot, log, configDirs); log.debug(`IntelliStory: stats file buildId = ${buildId}`); return { files, modules }; } export async function getBaselineAndAffectedNodes(percy, baseline, log) { let baseRef; // Always look up the base build: its `browsers_changed_from_base` flag forces // a full snapshot run regardless of whether an explicit baseline was configured. let baseLookup; try { baseLookup = await percy.client.getIntelliStorySnapshotNameToCommit(percy.build?.id); } catch (e) { throw apiBailError(e, 'base build lookup'); } log.debug(`IntelliStory: base lookup ${JSON.stringify(baseLookup)}`); if (baseLookup?.browsers_changed_from_base) { throw new IntelliStoryBailError('IntelliStory: This build has to take all snapshots by fallback because this build corresponds to a browser upgrade'); } if (baseline) { log.debug(`IntelliStory: diffing against explicit baseline "${baseline}"`); baseRef = baseline; } else { if (!baseLookup?.base_build_commit_sha) { throw new IntelliStoryBailError('IntelliStory: API could not predict a base build commit and no explicit baseline was set; running full snapshot set'); } log.debug(`IntelliStory: diffing against predicted base build commit "${baseLookup.base_build_commit_sha}"`); baseRef = baseLookup.base_build_commit_sha; } assertSafeRef(baseRef); const affectedNodes = gitDiffNames(baseRef); return { baseRef, affectedNodes }; } export function assertNoDotStorybookChange(affectedNodes, configDirs = [DEFAULT_CONFIG_DIR]) { const hit = affectedNodes.find(p => isInsideDirs(p, configDirs)); if (hit) { throw new IntelliStoryBailError(`IntelliStory: change to "${hit}" inside the Storybook config directory affects all stories; running full snapshot set`); } } // The config directory the user gave us, on the same repo-root basis as // everything else. Interpreted relative to the invocation directory, matching // `bailOnChanges`/`untraced`; the default is kept alongside it so a project that // has both a custom directory and a stray `.storybook` is covered either way. export function resolveConfigDirs(configDir, projectRoot, invocationDir, log) { const dirs = new Set([DEFAULT_CONFIG_DIR]); if (!configDir || configDir === DEFAULT_CONFIG_DIR) return [...dirs]; const { rebased } = resolvePattern(configDir, projectRoot, invocationDir); if (rebased == null) { log?.warn(`IntelliStory: configDir "${configDir}" resolves outside the project root; falling back to "${DEFAULT_CONFIG_DIR}"`); return [...dirs]; } // Unlike a glob, a config directory has to exist -- so a directory written on // the wrong basis is detectable here rather than silently matching nothing // later. When only the repo-root reading exists, recognise it as well: // recognising one directory too many costs snapshots, missing the real one // loses comparisons. if (!fs.existsSync(path.resolve(projectRoot, rebased))) { const asRootRelative = configDir.split(path.sep).join('/'); if (!path.isAbsolute(configDir) && fs.existsSync(path.resolve(projectRoot, configDir))) { log?.warn(`IntelliStory: configDir "${configDir}" does not exist relative to the invocation directory ("${describeInvocation(projectRoot, invocationDir)}") but does relative to the project root; recognising both. Write it relative to the invocation directory to make this explicit.`); dirs.add(asRootRelative); } else { log?.warn(`IntelliStory: configDir "${configDir}" resolves to "${rebased}", which does not exist; it is interpreted relative to the invocation directory, not the project root`); } } dirs.add(rebased); return [...dirs]; } // `bailOnChanges` is the user's escape hatch for changes the graph cannot // reason about, so every failure mode here resolves towards bailing: a pattern // that cannot be evaluated is a disabled safety valve, and a pattern that only // matches under the repo-root reading still bails (loudly) rather than being // treated as a non-match. export function assertNoBailOnChanges(affectedNodes, bailOnChanges, { projectRoot = process.cwd(), invocationDir = projectRoot, log } = {}) { if (!bailOnChanges?.length) return; for (const raw of bailOnChanges) { const resolved = resolvePattern(raw, projectRoot, invocationDir); if (resolved.rebased == null) { throw new IntelliStoryBailError(`IntelliStory: bailOnChanges pattern "${raw}" resolves outside the project root and can never match a changed file; running full snapshot set`); } const err = patternError(resolved.rebased); if (err) { throw new IntelliStoryBailError(`IntelliStory: bailOnChanges pattern "${raw}" is not a valid glob (${err.message}); running full snapshot set`); } let bailed = affectedNodes.find(p => matchesPattern(p, resolved.rebased)); if (!bailed) { const rootHit = rootReadingHit(affectedNodes, resolved); if (!rootHit) continue; log?.warn(`IntelliStory: bailOnChanges pattern "${raw}" matched "${rootHit}" only when read relative to the project root. Patterns are relative to the invocation directory ("${describeInvocation(projectRoot, invocationDir)}"); bailing anyway, but write it as ${suggestRewrite(raw, projectRoot, invocationDir)} to make this explicit.`); bailed = rootHit; } throw new IntelliStoryBailError(`IntelliStory: change to "${bailed}" matched bailOnChanges; running full snapshot set`); } } // `untraced` drops files from the affected set, so honouring an ambiguous // reading here would remove snapshots -- the opposite direction of harm from // `bailOnChanges`. Only the invocation-relative reading is applied; a pattern // that looks repo-relative is reported and left unapplied, since keeping a file // traced never loses a comparison. export function enforceUntraced(affectedNodes, untraced, { projectRoot = process.cwd(), invocationDir = projectRoot, log } = {}) { if (!untraced?.length) return affectedNodes; const resolved = []; for (const raw of untraced) { const r = resolvePattern(raw, projectRoot, invocationDir); if (r.rebased == null) { log?.warn(`IntelliStory: ignoring untraced pattern "${raw}" — it resolves outside the project root and can never match a changed file`); continue; } const err = patternError(r.rebased); if (err) { log?.warn(`IntelliStory: ignoring untraced pattern "${raw}" — not a valid glob (${err.message})`); continue; } const rootHit = rootReadingHit(affectedNodes, r); if (rootHit) { log?.warn(`IntelliStory: untraced pattern "${raw}" matches "${rootHit}" only when read relative to the project root. Patterns are relative to the invocation directory ("${describeInvocation(projectRoot, invocationDir)}") — not applied; write it as ${suggestRewrite(raw, projectRoot, invocationDir)}.`); continue; } resolved.push(r); } return affectedNodes.filter(p => !resolved.some(({ rebased }) => matchesPattern(p, rebased))); } export async function getAffectedPackages(affectedNodes, baseRef, projectRoot, log) { assertSafeRef(baseRef); const MANIFEST_PATHS = new Set(['package.json', 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']); const manifestHits = affectedNodes.filter(p => MANIFEST_PATHS.has(path.basename(p))); if (manifestHits.length === 0) return []; const uniqueDirs = [...new Set(manifestHits.map(p => path.dirname(p)))]; if (uniqueDirs.length > 1) { throw new IntelliStoryBailError(`IntelliStory: manifest changes span multiple directories (${uniqueDirs.join(', ')}); running full snapshot set`); } const manifestDir = uniqueDirs[0]; const absManifestDir = path.resolve(projectRoot, manifestDir); const LOCKFILE_NAMES = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml']; const presentLockfiles = LOCKFILE_NAMES.filter(n => fs.existsSync(path.join(absManifestDir, n))); if (presentLockfiles.length === 0) { throw new IntelliStoryBailError(`IntelliStory: manifest changed in "${manifestDir}" but no lockfile present there; running full snapshot set`); } if (presentLockfiles.length > 1) { throw new IntelliStoryBailError(`IntelliStory: multiple lockfiles in "${manifestDir}" (${presentLockfiles.join(', ')}); cannot pick canonical; running full snapshot set`); } const lockfileName = presentLockfiles[0]; const lockfileRepoPath = manifestDir === '.' ? lockfileName : `${manifestDir}/${lockfileName}`; let oldLockfile; try { oldLockfile = git(['show', `${baseRef}:${lockfileRepoPath}`]); } catch { throw new IntelliStoryBailError(`IntelliStory: lockfile "${lockfileRepoPath}" not present at base ref ${baseRef}; running full snapshot set`); } let newLockfile; try { newLockfile = fs.readFileSync(path.join(absManifestDir, lockfileName), 'utf8'); } catch { throw new IntelliStoryBailError(`IntelliStory: failed to read lockfile "${lockfileName}" in "${manifestDir}"; running full snapshot set`); } if (oldLockfile === newLockfile) return []; let packageJson; try { packageJson = fs.readFileSync(path.join(absManifestDir, 'package.json'), 'utf8'); } catch { throw new IntelliStoryBailError(`IntelliStory: failed to read "package.json" in "${manifestDir}"; running full snapshot set`); } const packageJsonRepoPath = manifestDir === '.' ? 'package.json' : `${manifestDir}/package.json`; const oldPackageJson = git(['show', `${baseRef}:${packageJsonRepoPath}`]); try { const packageAffected = await diffLockfileDeps({ packageJson, oldLockfile, newLockfile, lockfileType: lockfileName, oldPackageJson }); /* istanbul ignore next */ log.debug(`IntelliStory: lockfile diff produced ${packageAffected.length} affected packages: ${packageAffected.join(', ')}`); /* istanbul ignore next */ return packageAffected; } catch (e) { /* istanbul ignore else */ if (e.code === 'SNYK_LOCKFILE_PARSER_UNAVAILABLE') { throw new IntelliStoryBailError(`IntelliStory: ${e.message}; running full snapshot set`); } /* istanbul ignore next */ throw e; } } export function extractStorybookPaths(snapshots, normalizeImportPath, log) { const storybookPaths = [...new Set(snapshots.map(s => normalizeImportPath(s.importPath)).filter(Boolean))]; const snapshotsWithImportPath = snapshots.filter(s => s.importPath).length; log.debug(`IntelliStory: ${snapshotsWithImportPath}/${snapshots.length} snapshots have importPath; ${storybookPaths.length} unique storybookPaths`); if (storybookPaths.length === 0) { log.warn(`IntelliStory: no snapshots have importPath set — check Storybook story extraction. Sample snapshot: ${JSON.stringify({ id: snapshots[0]?.id, name: snapshots[0]?.name, importPath: snapshots[0]?.importPath, keys: snapshots[0] ? Object.keys(snapshots[0]) : [] })}`); } else { log.debug(`IntelliStory: storybookPaths sample: ${storybookPaths.slice(0, 3).join(', ')}`); } return storybookPaths; } export async function runGraphGeneration(percy, buildId, payload, log) { const { files, modules, storybookPaths, affectedNodes, affectedFileLocations } = payload; log.debug(`IntelliStory: starting graph generation job ${JSON.stringify({ buildId, files, modules, storybookPaths, affectedNodes, affectedFileLocations })}`); try { await percy.client.generateIntelliStoryGraph(buildId, { files, modules, storybookPaths, affectedNodes, affectedFileLocations }); } catch (e) { throw apiBailError(e, 'graph generation request'); } const { status } = await pollGraphStatus(percy, buildId, log); if (status !== 'done') { throw new IntelliStoryBailError(`IntelliStory: graph generation did not complete (status: ${status ?? 'timed out'}); running full snapshot set`); } } export function maybeWriteTrace(trace, data, log) { if (trace && data?.vertices && data?.edges && data?.transitive_closure_matrix_sparse) { const tracePath = path.resolve(process.cwd(), 'trace.html'); try { const html = renderGraphTraceHtml({ vertices: data.vertices, edges: data.edges, transitiveClosureMatrixSparse: data.transitive_closure_matrix_sparse }); fs.writeFileSync(tracePath, html); log.info(`IntelliStory: trace written to ${tracePath}`); } catch (e) { log.warn(`IntelliStory: failed to write trace.html: ${e.message}`); } } } export async function applyIntelliStory(percy, snapshots, intelliStoryConfig, buildDir) { const log = logger('storybook:intelliStory'); const { baseline, untraced, bailOnChanges, statsFile, configDir } = intelliStoryConfig || {}; if (!buildDir) { throw new IntelliStoryBailError('IntelliStory requires the Storybook build directory (e.g. `percy storybook ./storybook-static`); URL and `start` modes are not supported. Running full snapshot set'); } // The graph is keyed by the real Percy build id. The build is created up // front for IntelliStory runs (see @percy/storybook); if it is not present // (e.g. a dry run, or build creation failed) there is nothing to key on. const buildId = percy.build?.id; if (!buildId) { throw new IntelliStoryBailError('IntelliStory: Percy build was not created (dry run or build creation failed); running full snapshot set'); } const projectRoot = gitProjectRoot(); const invocationDir = process.cwd(); const patternOpts = { projectRoot, invocationDir, log }; log.debug(`IntelliStory: project root ${projectRoot}, invoked from "${describeInvocation(projectRoot, invocationDir)}" — user patterns and configDir are relative to the invocation directory`); const configDirs = resolveConfigDirs(configDir, projectRoot, invocationDir, log); log.debug(`IntelliStory: Storybook config directories: ${configDirs.map(d => `"${d}"`).join(', ')}`); const { files, modules } = await validateAndReadStats(buildDir, statsFile, projectRoot, log, configDirs); let { baseRef, affectedNodes } = await getBaselineAndAffectedNodes(percy, baseline, log); assertNoDotStorybookChange(affectedNodes, configDirs); assertNoBailOnChanges(affectedNodes, bailOnChanges, patternOpts); affectedNodes = enforceUntraced(affectedNodes, untraced, patternOpts); const packageAffectedNodes = await getAffectedPackages(affectedNodes, baseRef, projectRoot, log); if (!affectedNodes.length && !packageAffectedNodes.length) { throw new IntelliStoryBailError('IntelliStory: no affected files or packages detected after filtering; running full snapshot set'); } const dotPosix = './'; const dotPlatform = `.${path.sep}`; const normalizeImportPath = p => { if (typeof p !== 'string' || !p) return p; let rel = p; /* istanbul ignore next */ if (rel.startsWith(dotPlatform)) rel = rel.slice(dotPlatform.length); else if (rel.startsWith(dotPosix)) rel = rel.slice(dotPosix.length); const abs = path.resolve(invocationDir, rel); const projRel = path.relative(projectRoot, abs); /* istanbul ignore next */ return projRel || rel; }; const storybookPaths = extractStorybookPaths(snapshots, normalizeImportPath, log); /* istanbul ignore next */ if (packageAffectedNodes.length) { affectedNodes = [...affectedNodes, ...packageAffectedNodes]; } const affectedFileLocations = getAffectedFileLocations(baseRef, files); // Enqueue the affected-story graph against the Percy build. Snapshot // selection now happens server-side (when snapshots are posted), so we no // longer read affected_stories back here or write the trace — we only kick // off generation and surface a failure by bailing to the full set. await runGraphGeneration(percy, buildId, { files, modules, storybookPaths, affectedNodes, affectedFileLocations }, log); // Tag every snapshot with `intelliStory` and its normalized `storybookPath` // so the API can perform affected-story selection when each is posted. The // API is the sole arbiter of what can be skipped — including whether a // snapshot has a usable baseline to carry forward. // // The one exception is a story with no resolvable source path: selection is // keyed by that path, so the API rejects `intelli-story` without it (400). // Leave those untagged and they are simply captured as normal. return snapshots.map(s => { const storybookPath = normalizeImportPath(s.importPath); return { ...s, intelliStory: !!storybookPath, storybookPath }; }); } // Called after the build has been finalized. At that point the graph job's // data (vertices/edges/transitive closure) is available from job status, so we // fetch it once more and write the trace when `trace` is enabled. export async function writeIntelliStoryTrace(percy, intelliStoryConfig, log = logger('storybook:intelliStory')) { const { trace } = intelliStoryConfig || {}; if (!trace) return; const buildId = percy.build?.id; if (!buildId) return; log.debug(`IntelliStory: fetching finalized graph data for build ${buildId} to write trace`); const { status, data } = await pollGraphStatus(percy, buildId, log); if (status !== 'done') { log.debug(`IntelliStory: graph status "${status ?? 'timed out'}" after finalize; skipping trace`); return; } maybeWriteTrace(trace, data, log); }