@decocms/parity 0.35.23 → 0.35.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -75779,7 +75779,7 @@ import {
75779
75779
  registerCommands as registerCatalogCommands
75780
75780
  } from "@decocms/catalog";
75781
75781
  import { DESCRIPTION, registerCommands } from "@decocms/vtex-cms";
75782
- import chalk48 from "chalk";
75782
+ import chalk49 from "chalk";
75783
75783
  import { Command, InvalidArgumentError as InvalidArgumentError2 } from "commander";
75784
75784
 
75785
75785
  // src/commands/ab-detect.ts
@@ -76634,13 +76634,16 @@ function pairCaptures(prod, cand) {
76634
76634
  function captureKey(c) {
76635
76635
  if (c.pairKey)
76636
76636
  return `${c.pairKey}::${c.viewport}`;
76637
+ return urlPageKey(c.url, c.viewport);
76638
+ }
76639
+ function urlPageKey(url, viewport) {
76637
76640
  let path = "";
76638
76641
  try {
76639
- path = new URL(c.url).pathname || "/";
76642
+ path = new URL(url).pathname || "/";
76640
76643
  } catch {
76641
- path = c.url;
76644
+ path = url;
76642
76645
  }
76643
- return `${path}::${c.viewport}`;
76646
+ return `${path}::${viewport}`;
76644
76647
  }
76645
76648
 
76646
76649
  // src/checks/analytics-beacon-parity.ts
@@ -78177,15 +78180,21 @@ function detailFor(prod, cand, viewport) {
78177
78180
 
78178
78181
  // src/diff/console.ts
78179
78182
  var HYDRATION_PATTERNS = [
78180
- /hydrat/i,
78183
+ /hydration (?:failed|mismatch|error)/i,
78184
+ /(?:error|errors) (?:while|during) hydrat/i,
78185
+ /tree hydrat/i,
78181
78186
  /text content does not match/i,
78182
- /server rendered html/i,
78183
- /did not match/i,
78184
- /tree hydration/i,
78185
- /useDevice/i,
78186
- /usePlatform/i,
78187
+ /server[- ]rendered html/i,
78188
+ /(?:server|client|text content|prop|attribute|html)\b.{0,80}did(?: not|n't) match/i,
78187
78189
  /minified react error #(418|423|425)\b/i
78188
78190
  ];
78191
+ var SECTION_CRASH_PATTERNS = [/\bSection "[^"]+" crashed\b/, /\bSectionErrorBoundary\b/];
78192
+ var COMPONENT_ERROR_LINE = /The above error occurred in the <([^>\s]+)> component/i;
78193
+ function parseSectionCrash(text) {
78194
+ const section = text.match(/\bSection "([^"]+)" crashed/)?.[1] ?? text.match(COMPONENT_ERROR_LINE)?.[1];
78195
+ const raw = text.match(/\bcrashed:\s*([\s\S]*?)(?:\s+at\s+\S+\s+\(|\n\s*at\s|$)/)?.[1]?.trim();
78196
+ return { ...section ? { section } : {}, ...raw ? { error: raw } : {} };
78197
+ }
78189
78198
  var CSP_PATTERNS = [
78190
78199
  /content security policy/i,
78191
78200
  /violates the following content security/i,
@@ -78197,8 +78206,12 @@ var NOT_FOUND_PATTERNS = [
78197
78206
  /failed to load resource: the server responded with a status of 404/i
78198
78207
  ];
78199
78208
  function classify(entry) {
78209
+ if (SECTION_CRASH_PATTERNS.some((p) => p.test(entry.text)))
78210
+ return "section-crash";
78200
78211
  if (HYDRATION_PATTERNS.some((p) => p.test(entry.text)))
78201
78212
  return "hydration";
78213
+ if (COMPONENT_ERROR_LINE.test(entry.text))
78214
+ return "section-crash";
78202
78215
  if (CSP_PATTERNS.some((p) => p.test(entry.text)))
78203
78216
  return "csp";
78204
78217
  if (NOT_FOUND_PATTERNS.some((p) => p.test(entry.text)))
@@ -78302,6 +78315,7 @@ function registrableDomain(hostname) {
78302
78315
 
78303
78316
  // src/checks/console-errors.ts
78304
78317
  var BENIGN = [/\bTransition was (?:skipped|aborted)\b/i];
78318
+ var DETERMINISTIC = new Set(["hydration", "section-crash"]);
78305
78319
  function consoleErrorsBaseline(ctx) {
78306
78320
  const start = Date.now();
78307
78321
  const { pairs } = pairCaptures(ctx.prodPages, ctx.candPages);
@@ -78352,9 +78366,10 @@ function consoleErrorsBaseline(ctx) {
78352
78366
  const pageList = agg.pages.length <= 5 ? agg.pages.join(" · ") : `${agg.pages.slice(0, 5).join(" · ")} +${agg.pages.length - 5} more`;
78353
78367
  const pageSuffix = agg.pages.length === 1 ? `em ${agg.pages[0]}` : `em ${agg.pages.length} páginas (${pageList})`;
78354
78368
  const loads = [...candLoads.get(key) ?? []];
78355
- const verdict = prodKeys.has(key) ? "shared" : agg.stagingThirdParty ? "staging" : BENIGN.some((re) => re.test(agg.sampleText)) ? "benign" : agg.cls !== "hydration" && loads.length < 2 ? "unconfirmed" : "confirmed";
78356
- const severity = verdict !== "confirmed" ? "low" : agg.cls === "hydration" ? "critical" : "high";
78357
- const text = truncate(agg.sampleText, 160);
78369
+ const verdict = prodKeys.has(key) ? "shared" : agg.stagingThirdParty ? "staging" : BENIGN.some((re) => re.test(agg.sampleText)) ? "benign" : !DETERMINISTIC.has(agg.cls) && loads.length < 2 ? "unconfirmed" : "confirmed";
78370
+ const severity = verdict !== "confirmed" ? "low" : DETERMINISTIC.has(agg.cls) ? "critical" : "high";
78371
+ const crash = agg.cls === "section-crash" ? parseSectionCrash(agg.sampleText) : undefined;
78372
+ const text = crash?.section ? `Section "${crash.section}" crashed${crash.error ? `: ${truncate(crash.error, 160)}` : ""}` : truncate(agg.sampleText, 160);
78358
78373
  const summary = {
78359
78374
  confirmed: `[${agg.cls}] novo erro de console ${pageSuffix}: ${text}`,
78360
78375
  staging: `[${agg.cls}] novo erro de console ${pageSuffix}: ${text}`,
@@ -78369,6 +78384,7 @@ function consoleErrorsBaseline(ctx) {
78369
78384
  benign: "Known-benign browser message (View Transitions API aborting a transition when a navigation lands mid-animation).",
78370
78385
  unconfirmed: "Seen on cand in one flow only — the other flows did not show it and prod never did. Not reproduced; re-check by hand before treating it as a regression."
78371
78386
  }[verdict];
78387
+ const staleLines = /\.(?:tsx?|jsx?|mjs):\d+/.test(agg.sampleText) ? "Line numbers in this stack come from the candidate's build at capture time and may be stale against the working tree; find the code by the section and the thrown error, not by the line." : "";
78372
78388
  issues.push({
78373
78389
  id: `console:${hash(key)}`,
78374
78390
  severity,
@@ -78383,7 +78399,9 @@ Observed on: ${agg.pages.join(", ")}${agg.failedUrls.length > 0 ? `
78383
78399
 
78384
78400
  Failed URLs: ${agg.failedUrls.join(", ")}` : ""}${note ? `
78385
78401
 
78386
- ${note}` : ""}`,
78402
+ ${note}` : ""}${staleLines ? `
78403
+
78404
+ ${staleLines}` : ""}`,
78387
78405
  evidence: agg.sampleEvidence
78388
78406
  });
78389
78407
  }
@@ -78555,7 +78573,8 @@ function cookieCepModalCls(ctx) {
78555
78573
  category: "performance",
78556
78574
  check: "cookie-cep-modal-cls",
78557
78575
  summary: `[${cand.viewport}] CLS subiu de ${prodCls.toFixed(2)} (prod) para ${candCls.toFixed(2)} (cand) em página com modal — provável regressão de banner cookies/CEP`,
78558
- page: cand.url,
78576
+ page: captureKey(cand),
78577
+ details: `Page URL: ${cand.url}`,
78559
78578
  evidence: cand.screenshotPath ? [{ kind: "screenshot", path: cand.screenshotPath }] : []
78560
78579
  });
78561
78580
  } else if (prodCls > 0 && candCls / prodCls > CLS_REGRESSION_RATIO) {
@@ -78565,7 +78584,8 @@ function cookieCepModalCls(ctx) {
78565
78584
  category: "performance",
78566
78585
  check: "cookie-cep-modal-cls",
78567
78586
  summary: `[${cand.viewport}] CLS piorou ${((candCls / prodCls - 1) * 100).toFixed(0)}%: ${prodCls.toFixed(2)} → ${candCls.toFixed(2)}`,
78568
- page: cand.url
78587
+ page: captureKey(cand),
78588
+ details: `Page URL: ${cand.url}`
78569
78589
  });
78570
78590
  }
78571
78591
  }
@@ -78581,7 +78601,8 @@ function cookieCepModalCls(ctx) {
78581
78601
  category: "performance",
78582
78602
  check: "cookie-cep-modal-cls",
78583
78603
  summary: `[${page.viewport}] CLS=${cls.toFixed(2)} em página com modal — banner cookies/CEP pode estar deslocando layout`,
78584
- page: page.url
78604
+ page: captureKey(page),
78605
+ details: `Page URL: ${page.url}`
78585
78606
  });
78586
78607
  }
78587
78608
  }
@@ -78880,7 +78901,8 @@ async function footerLinksHealth(ctx) {
78880
78901
  category: "functional",
78881
78902
  check: "footer-links-health",
78882
78903
  summary: `Link de footer retornou HTTP ${r.status}: ${r.url}`,
78883
- page: home.url
78904
+ page: captureKey(home),
78905
+ details: `Page URL: ${home.url}`
78884
78906
  });
78885
78907
  }
78886
78908
  }
@@ -79160,6 +79182,59 @@ function originDelta(prod, cand) {
79160
79182
  return parts.length > 0 ? parts.join(", ") : null;
79161
79183
  }
79162
79184
 
79185
+ // src/checks/lib/captured.ts
79186
+ function isUncaptured(page) {
79187
+ return page.status === 0;
79188
+ }
79189
+ function uncapturedPairs(pairs) {
79190
+ const out = [];
79191
+ for (const pair of pairs) {
79192
+ const sides = [];
79193
+ if (isUncaptured(pair.prod))
79194
+ sides.push("prod");
79195
+ if (isUncaptured(pair.cand))
79196
+ sides.push("cand");
79197
+ if (sides.length)
79198
+ out.push({ pair, sides });
79199
+ }
79200
+ return out;
79201
+ }
79202
+ function uncapturedSummary(key, sides, durationMs) {
79203
+ const took = durationMs ? ` (capture gave up after ${Math.round(durationMs / 1000)}s)` : "";
79204
+ return `${key}: ${sides.join(" and ")} page was not captured${took}`;
79205
+ }
79206
+ function withCapturedPairs(check) {
79207
+ const guarded = async (ctx) => {
79208
+ const missing = uncapturedPairs(pairCaptures(ctx.prodPages, ctx.candPages).pairs);
79209
+ if (missing.length === 0)
79210
+ return check(ctx);
79211
+ const skip = new Set(missing.map((m) => m.pair.key));
79212
+ const keep = (pages) => pages.filter((p) => !skip.has(captureKey(p)));
79213
+ const result = await check({
79214
+ ...ctx,
79215
+ prodPages: keep(ctx.prodPages),
79216
+ candPages: keep(ctx.candPages)
79217
+ });
79218
+ const issues = missing.map(({ pair, sides }) => ({
79219
+ id: `${result.name}:not-captured:${pair.key}`,
79220
+ severity: "low",
79221
+ inconclusive: true,
79222
+ category: "functional",
79223
+ page: pair.key,
79224
+ check: result.name,
79225
+ summary: `${uncapturedSummary(pair.key, sides)} — not compared by ${result.name}`,
79226
+ details: "The capture recorded no HTTP answer (status 0), so this check had nothing to judge on that side. Not a finding about the page: re-run it against a warm server."
79227
+ }));
79228
+ return {
79229
+ ...result,
79230
+ status: result.status === "pass" ? "warn" : result.status,
79231
+ issues: [...result.issues, ...issues]
79232
+ };
79233
+ };
79234
+ Object.defineProperty(guarded, "name", { value: check.name });
79235
+ return guarded;
79236
+ }
79237
+
79163
79238
  // src/checks/http-status.ts
79164
79239
  function httpStatusParity(ctx) {
79165
79240
  const start = Date.now();
@@ -79177,7 +79252,28 @@ function httpStatusParity(ctx) {
79177
79252
  const { pairs, orphansProd, orphansCand } = pairCaptures(ctx.prodPages, ctx.candPages);
79178
79253
  const issues = [];
79179
79254
  const pairIssues = [];
79255
+ const uncaptured = uncapturedPairs(pairs);
79256
+ const skip = new Set(uncaptured.map((u) => u.pair.key));
79257
+ for (const { pair, sides } of uncaptured) {
79258
+ const durationMs = sides.map((s) => pair[s].durationMs).find(Boolean);
79259
+ issues.push({
79260
+ id: `http-status:not-captured:${pair.key}`,
79261
+ severity: "medium",
79262
+ inconclusive: true,
79263
+ category: "functional",
79264
+ page: pair.key,
79265
+ check: "http-status-parity",
79266
+ summary: uncapturedSummary(pair.key, sides, durationMs),
79267
+ details: "The capture recorded no HTTP answer (status 0: timeout or refused connection), so there is no status to compare. This is a measurement gap, not a status divergence; re-run the page against a warm server.",
79268
+ evidence: [
79269
+ { kind: "screenshot", path: pair.prod.screenshotPath, label: "prod" },
79270
+ { kind: "screenshot", path: pair.cand.screenshotPath, label: "cand" }
79271
+ ]
79272
+ });
79273
+ }
79180
79274
  for (const pair of pairs) {
79275
+ if (skip.has(pair.key))
79276
+ continue;
79181
79277
  if (pair.prod.status !== pair.cand.status) {
79182
79278
  pairIssues.push({
79183
79279
  id: `http-status:${pair.key}`,
@@ -79199,7 +79295,8 @@ function httpStatusParity(ctx) {
79199
79295
  id: `http-status:missing-cand:${p.url}`,
79200
79296
  severity: "high",
79201
79297
  category: "functional",
79202
- page: p.url,
79298
+ page: captureKey(p),
79299
+ details: `Page URL: ${p.url}`,
79203
79300
  check: "http-status-parity",
79204
79301
  summary: `Página presente em prod mas não capturada em cand: ${p.url}`,
79205
79302
  evidence: [{ kind: "screenshot", path: p.screenshotPath, label: "prod" }]
@@ -79210,7 +79307,8 @@ function httpStatusParity(ctx) {
79210
79307
  id: `http-status:missing-prod:${p.url}`,
79211
79308
  severity: "low",
79212
79309
  category: "functional",
79213
- page: p.url,
79310
+ page: captureKey(p),
79311
+ details: `Page URL: ${p.url}`,
79214
79312
  check: "http-status-parity",
79215
79313
  summary: `Página presente em cand mas não em prod: ${p.url}`,
79216
79314
  evidence: [{ kind: "screenshot", path: p.screenshotPath, label: "cand" }]
@@ -79221,14 +79319,20 @@ function httpStatusParity(ctx) {
79221
79319
  status: issues.some((i) => i.severity === "critical") ? "fail" : issues.length ? "warn" : "pass",
79222
79320
  severity: "critical",
79223
79321
  durationMs: Date.now() - start,
79224
- summary: `${pairs.length} pares verificados, ${issues.length} divergência(s)`,
79322
+ summary: `${pairs.length - skip.size} pares verificados, ${issues.length} divergência(s)${skip.size ? `, ${skip.size} par(es) não capturado(s)` : ""}`,
79225
79323
  issues,
79226
79324
  ...unitCounts({
79227
79325
  unit: "page-pair",
79228
- judged: pairs.map((p) => p.key),
79326
+ judged: pairs.filter((p) => !skip.has(p.key)).map((p) => p.key),
79327
+ unjudged: skip,
79229
79328
  issues: pairIssues
79230
79329
  }),
79231
- data: { pairs: pairs.length, orphansProd: orphansProd.length, orphansCand: orphansCand.length }
79330
+ data: {
79331
+ pairs: pairs.length - skip.size,
79332
+ uncaptured: skip.size,
79333
+ orphansProd: orphansProd.length,
79334
+ orphansCand: orphansCand.length
79335
+ }
79232
79336
  };
79233
79337
  }
79234
79338
 
@@ -80024,7 +80128,8 @@ function notFoundParity(ctx) {
80024
80128
  category: "functional",
80025
80129
  check: "not-found-parity",
80026
80130
  summary: `URL inválida retornou HTTP ${page.status} (esperado 404) — catch-all rota incorreta`,
80027
- page: page.url
80131
+ page: captureKey(page),
80132
+ details: `Page URL: ${page.url}`
80028
80133
  });
80029
80134
  }
80030
80135
  if (!hasNotFoundText(page)) {
@@ -80034,7 +80139,8 @@ function notFoundParity(ctx) {
80034
80139
  category: "functional",
80035
80140
  check: "not-found-parity",
80036
80141
  summary: "Página 404 não tem mensagem de erro reconhecível — UX prejudicada",
80037
- page: page.url
80142
+ page: captureKey(page),
80143
+ details: `Page URL: ${page.url}`
80038
80144
  });
80039
80145
  }
80040
80146
  } else {
@@ -80050,7 +80156,8 @@ function notFoundParity(ctx) {
80050
80156
  category: "functional",
80051
80157
  check: "not-found-parity",
80052
80158
  summary: `[${viewport}] URL inválida retornou HTTP ${c.status} em cand (prod retornou 404) — catch-all rota incorreta`,
80053
- page: c.url
80159
+ page: captureKey(c),
80160
+ details: `Page URL: ${c.url}`
80054
80161
  });
80055
80162
  } else if (p.status !== 404 && c.status === 404) {
80056
80163
  issues.push({
@@ -80059,7 +80166,8 @@ function notFoundParity(ctx) {
80059
80166
  category: "functional",
80060
80167
  check: "not-found-parity",
80061
80168
  summary: `[${viewport}] URL inválida retornou HTTP ${p.status} em prod (cand retornou 404) — prod pode ter catch-all 200`,
80062
- page: p.url
80169
+ page: captureKey(p),
80170
+ details: `Page URL: ${p.url}`
80063
80171
  });
80064
80172
  }
80065
80173
  const prodHasMsg = hasNotFoundText(p);
@@ -80294,7 +80402,8 @@ function pdpBreadcrumbs(ctx) {
80294
80402
  category: "seo",
80295
80403
  check: "pdp-breadcrumbs",
80296
80404
  summary: `[${page.viewport}] PDP sem breadcrumbs detectáveis (nem markup, nem JSON-LD BreadcrumbList) — ${page.url}`,
80297
- page: page.url
80405
+ page: captureKey(page),
80406
+ details: `Page URL: ${page.url}`
80298
80407
  });
80299
80408
  }
80300
80409
  } else if (pair) {
@@ -80306,7 +80415,8 @@ function pdpBreadcrumbs(ctx) {
80306
80415
  category: "seo",
80307
80416
  check: "pdp-breadcrumbs",
80308
80417
  summary: `[${page.viewport}] Breadcrumbs ausentes em cand (presentes em prod) — impacto em UX e em SEO estruturado (rich results)`,
80309
- page: page.url
80418
+ page: captureKey(page),
80419
+ details: `Page URL: ${page.url}`
80310
80420
  });
80311
80421
  }
80312
80422
  }
@@ -80386,7 +80496,8 @@ function pdpGalleryRelated(ctx) {
80386
80496
  category: "functional",
80387
80497
  check: "pdp-gallery-related",
80388
80498
  summary: `[${page.viewport}] PDP sem imagem principal de galeria detectável (${page.url})`,
80389
- page: page.url
80499
+ page: captureKey(page),
80500
+ details: `Page URL: ${page.url}`
80390
80501
  });
80391
80502
  }
80392
80503
  if (!matchAny(html, GALLERY_THUMB_PATTERNS)) {
@@ -80396,7 +80507,8 @@ function pdpGalleryRelated(ctx) {
80396
80507
  category: "functional",
80397
80508
  check: "pdp-gallery-related",
80398
80509
  summary: `[${page.viewport}] PDP sem thumbnails de galeria — usuário não consegue ver outras fotos`,
80399
- page: page.url
80510
+ page: captureKey(page),
80511
+ details: `Page URL: ${page.url}`
80400
80512
  });
80401
80513
  }
80402
80514
  if (!matchAny(html, RELATED_PATTERNS)) {
@@ -80406,7 +80518,8 @@ function pdpGalleryRelated(ctx) {
80406
80518
  category: "functional",
80407
80519
  check: "pdp-gallery-related",
80408
80520
  summary: `[${page.viewport}] PDP sem shelf "Related products" — cross-sell perdido`,
80409
- page: page.url
80521
+ page: captureKey(page),
80522
+ details: `Page URL: ${page.url}`
80410
80523
  });
80411
80524
  }
80412
80525
  }
@@ -80436,7 +80549,8 @@ function pdpGalleryRelated(ctx) {
80436
80549
  category: "functional",
80437
80550
  check: "pdp-gallery-related",
80438
80551
  summary: `[${cand.viewport}] Imagem principal de PDP ausente em cand (presente em prod)`,
80439
- page: cand.url
80552
+ page: captureKey(cand),
80553
+ details: `Page URL: ${cand.url}`
80440
80554
  });
80441
80555
  }
80442
80556
  if (lost(GALLERY_THUMB_PATTERNS)) {
@@ -80446,7 +80560,8 @@ function pdpGalleryRelated(ctx) {
80446
80560
  category: "functional",
80447
80561
  check: "pdp-gallery-related",
80448
80562
  summary: `[${cand.viewport}] Thumbnails de PDP ausentes em cand (presentes em prod)`,
80449
- page: cand.url
80563
+ page: captureKey(cand),
80564
+ details: `Page URL: ${cand.url}`
80450
80565
  });
80451
80566
  }
80452
80567
  if (lost(RELATED_PATTERNS)) {
@@ -80456,7 +80571,8 @@ function pdpGalleryRelated(ctx) {
80456
80571
  category: "functional",
80457
80572
  check: "pdp-gallery-related",
80458
80573
  summary: `[${cand.viewport}] Shelf "Related products" ausente em cand — cross-sell perdido`,
80459
- page: cand.url
80574
+ page: captureKey(cand),
80575
+ details: `Page URL: ${cand.url}`
80460
80576
  });
80461
80577
  }
80462
80578
  }
@@ -80489,7 +80605,8 @@ function unjudged(page, why) {
80489
80605
  category: "functional",
80490
80606
  check: "pdp-gallery-related",
80491
80607
  summary: `[${page.viewport}] Galeria/related da PDP não comparada — ${why} (${page.url})`,
80492
- page: page.url,
80608
+ page: captureKey(page),
80609
+ details: `Page URL: ${page.url}`,
80493
80610
  inconclusive: true
80494
80611
  };
80495
80612
  }
@@ -80955,7 +81072,8 @@ cand verify-pagination: ${JSON.stringify(candStep.detail ?? {})}`
80955
81072
  category: "functional",
80956
81073
  check: "plp-pagination",
80957
81074
  summary: `[${side}] page=${n} returned HTTP ${result.status} (expected 200) — pagination breaks under ?page=${n}`,
80958
- page: withPage(plp, n)
81075
+ page: urlPageKey(plp, PROBE_VIEWPORT),
81076
+ details: `Probed URL: ${withPage(plp, n)}`
80959
81077
  });
80960
81078
  }
80961
81079
  }
@@ -80968,8 +81086,9 @@ cand verify-pagination: ${JSON.stringify(candStep.detail ?? {})}`
80968
81086
  category: "functional",
80969
81087
  check: "plp-pagination",
80970
81088
  summary: `[${side}] page=2 shows the same ${page1.productPaths.length} products as page=1 (${(overlap * 100).toFixed(0)}% overlap) — ?page=N is being ignored`,
80971
- page: withPage(plp, 2),
80972
- details: `Page 1 first product: ${page1.productPaths[0] ?? "(none)"}
81089
+ page: urlPageKey(plp, PROBE_VIEWPORT),
81090
+ details: `Probed URL: ${withPage(plp, 2)}
81091
+ Page 1 first product: ${page1.productPaths[0] ?? "(none)"}
80973
81092
  Page 2 first product: ${page2.productPaths[0] ?? "(none)"}`
80974
81093
  });
80975
81094
  }
@@ -80983,7 +81102,8 @@ Page 2 first product: ${page2.productPaths[0] ?? "(none)"}`
80983
81102
  category: "functional",
80984
81103
  check: "plp-pagination",
80985
81104
  summary: `[${side}] page=3 shows the same products as page=2 (${(overlap * 100).toFixed(0)}% overlap) — pagination capped or broken`,
80986
- page: withPage(plp, 3)
81105
+ page: urlPageKey(plp, PROBE_VIEWPORT),
81106
+ details: `Probed URL: ${withPage(plp, 3)}`
80987
81107
  });
80988
81108
  }
80989
81109
  }
@@ -81016,6 +81136,7 @@ Page 2 first product: ${page2.productPaths[0] ?? "(none)"}`
81016
81136
  data
81017
81137
  };
81018
81138
  }
81139
+ var PROBE_VIEWPORT = "mobile";
81019
81140
  async function fetchPlpProducts(url) {
81020
81141
  try {
81021
81142
  const res = await fetch(url, {
@@ -81074,6 +81195,8 @@ function pickPlpFromHomeHtml(html, homeUrl) {
81074
81195
  const href = m[1];
81075
81196
  if (!href)
81076
81197
  continue;
81198
+ if (/\$\{|\{\{|%7B|<%/i.test(href))
81199
+ continue;
81077
81200
  if (/^https?:\/\//.test(href) || href.startsWith("#") || href === "/" || /\/(p|cart|carrinho|checkout|account|conta|login|wishlist|favoritos)(\/|$|\?)/i.test(href) || /\.(jpg|png|webp|css|js|svg|ico|woff)/i.test(href)) {
81078
81201
  continue;
81079
81202
  }
@@ -81251,7 +81374,8 @@ async function plpSorting(ctx) {
81251
81374
  category: "functional",
81252
81375
  check: "plp-sorting",
81253
81376
  summary: `Ordenação de PLP diverge entre os lados: prod ${applied.prod ? "aplicou" : "NÃO aplicou"} o sort, cand ${applied.cand ? "aplicou" : "NÃO aplicou"} — parâmetro de sort pode ter sido perdido/ignorado na migração`,
81254
- page: candPlp ?? prodPlp ?? undefined
81377
+ page: urlPageKey(candPlp ?? prodPlp, "mobile"),
81378
+ details: `PLP: ${candPlp ?? prodPlp}`
81255
81379
  });
81256
81380
  }
81257
81381
  const status = issues.length > 0 ? "warn" : "pass";
@@ -85791,8 +85915,38 @@ function buildMigrationPlan(input) {
85791
85915
  const { bundle, source, inventory } = input;
85792
85916
  const liveByKey = new Map;
85793
85917
  for (const c of bundle.components) {
85794
- liveByKey.set(key(c.role), { role: c.role, scope: c.scope, selector: c.selector });
85918
+ const k = key(c.role);
85919
+ const prev = liveByKey.get(k);
85920
+ if (prev?.extra.nameFrom === "manifest" && c.nameFrom === "manifest") {
85921
+ if (c.deferred === "fetched")
85922
+ prev.extra.deferred = "fetched";
85923
+ else if (c.deferred && !prev.extra.deferred)
85924
+ prev.extra.deferred = c.deferred;
85925
+ continue;
85926
+ }
85927
+ liveByKey.set(k, {
85928
+ role: c.role,
85929
+ scope: c.scope,
85930
+ selector: c.selector,
85931
+ extra: {
85932
+ ...c.liveType ? { liveType: c.liveType } : {},
85933
+ ...c.nameFrom ? { nameFrom: c.nameFrom } : {},
85934
+ ...c.deferred ? { deferred: c.deferred } : {},
85935
+ ...c.children?.length ? { children: c.children } : {},
85936
+ ...c.childrenOmitted ? { childrenOmitted: c.childrenOmitted } : {}
85937
+ }
85938
+ });
85795
85939
  }
85940
+ const perPage = bundle.pages.map((p) => {
85941
+ const counts = new Map;
85942
+ for (const c of p.components ?? []) {
85943
+ if (c.nameFrom !== "manifest")
85944
+ continue;
85945
+ counts.set(key(c.role), (counts.get(key(c.role)) ?? 0) + (c.repeated ?? 1));
85946
+ }
85947
+ return counts;
85948
+ });
85949
+ const pagesWith = (k) => perPage.filter((m) => m.has(k)).length;
85796
85950
  const srcByKey = new Map;
85797
85951
  for (const c of inventory.components)
85798
85952
  srcByKey.set(key(c.name), c);
@@ -85806,6 +85960,8 @@ function buildMigrationPlan(input) {
85806
85960
  status: "pending",
85807
85961
  file: c.file,
85808
85962
  selector: liveByKey.get(k)?.selector ?? null,
85963
+ ...liveByKey.get(k)?.extra ?? {},
85964
+ ...liveByKey.get(k)?.extra.nameFrom === "manifest" && pagesWith(k) > 0 ? { pages: pagesWith(k) } : {},
85809
85965
  reference: null,
85810
85966
  verified: null
85811
85967
  });
@@ -85821,6 +85977,8 @@ function buildMigrationPlan(input) {
85821
85977
  status: "pending",
85822
85978
  file: null,
85823
85979
  selector: c.selector,
85980
+ ...c.extra,
85981
+ ...c.extra.nameFrom === "manifest" && pagesWith(k) > 0 ? { pages: pagesWith(k) } : {},
85824
85982
  reference: null,
85825
85983
  verified: null
85826
85984
  });
@@ -85837,9 +85995,24 @@ function buildMigrationPlan(input) {
85837
85995
  ...input.project ? { project: input.project } : {}
85838
85996
  },
85839
85997
  target: { name: bundle.target ?? null },
85840
- pages: bundle.pages.map((p) => ({
85998
+ ...bundle.discovery ? { discovery: bundle.discovery } : {},
85999
+ pages: bundle.pages.map((p, i) => ({
85841
86000
  path: p.path,
85842
86001
  kind: p.kind,
86002
+ ...p.kindEvidence ? { kindEvidence: p.kindEvidence } : {},
86003
+ ...p.template ? { template: p.template } : {},
86004
+ ...p.deferral && p.deferral.found > 0 ? { deferral: p.deferral } : {},
86005
+ ...(() => {
86006
+ const many = [...perPage[i] ?? []].filter(([, n]) => n > 1);
86007
+ if (many.length === 0)
86008
+ return {};
86009
+ const names = {};
86010
+ for (const [k, n] of many) {
86011
+ const row = components.find((r) => key(r.name) === k);
86012
+ names[row?.name ?? k] = n;
86013
+ }
86014
+ return { instances: names };
86015
+ })(),
85843
86016
  status: "pending",
85844
86017
  components: dedupe((p.components ?? []).map((c) => components.find((row) => key(row.name) === key(c.role))?.name ?? c.role))
85845
86018
  })),
@@ -85900,6 +86073,8 @@ function mergePlanDecisions(fresh, previous) {
85900
86073
  }
85901
86074
  if (previous.telemetry)
85902
86075
  fresh.telemetry = previous.telemetry;
86076
+ if (!fresh.discovery && previous.discovery)
86077
+ fresh.discovery = previous.discovery;
85903
86078
  return { plan: fresh, carried, keptUncaptured, droppedWithDecisions: [] };
85904
86079
  }
85905
86080
  var PLAN_FILE = "migration-plan.json";
@@ -87539,7 +87714,9 @@ async function captureSectionScreenshot(page, selector, outPath, preCapturedFull
87539
87714
  const detached = await isDetachedFromScroll(loc);
87540
87715
  if (preCapturedFullPng && !detached) {
87541
87716
  const dpr = await page.evaluate(() => window.devicePixelRatio).catch(() => 1);
87542
- await writeFile(outPath, cropPngBuffer(preCapturedFullPng, box, dpr));
87717
+ const off = await page.evaluate(() => ({ x: window.pageXOffset, y: window.pageYOffset })).catch(() => null);
87718
+ const at = off && typeof off === "object" && Number.isFinite(off.x) && Number.isFinite(off.y) ? off : { x: 0, y: 0 };
87719
+ await writeFile(outPath, cropPngBuffer(preCapturedFullPng, { ...box, x: box.x + at.x, y: box.y + at.y }, dpr));
87543
87720
  return null;
87544
87721
  }
87545
87722
  if (detached)
@@ -89414,6 +89591,61 @@ function everyRegionImperceptible(heatmapPath, prod, cand, diffDir, prefix, view
89414
89591
  });
89415
89592
  return explainHotspots(all.hotspots, prod.side, cand.side, artifactPaths(diffDir, prefix, viewport), prod.boxTree, cand.boxTree).every(isImperceptible);
89416
89593
  }
89594
+ var HEIGHT_DIFF_TOLERANCE = {
89595
+ lowMaxPx: {
89596
+ value: 50,
89597
+ unit: "px",
89598
+ basis: "assumed",
89599
+ note: "under this and under lowMaxPct: margin / rounding"
89600
+ },
89601
+ lowMaxPct: {
89602
+ value: 2,
89603
+ unit: "% of prod height",
89604
+ basis: "assumed",
89605
+ note: "paired with lowMaxPx so a short page is not 'low' at 49 px"
89606
+ },
89607
+ highMinPct: {
89608
+ value: 10,
89609
+ unit: "% of prod height",
89610
+ basis: "assumed",
89611
+ note: "at or above: a block of content is missing or extra"
89612
+ }
89613
+ };
89614
+ function heightDiffSeverity(prodH, candH) {
89615
+ const delta = Math.abs(candH - prodH);
89616
+ const pct = prodH > 0 ? delta / prodH * 100 : 100;
89617
+ if (pct >= HEIGHT_DIFF_TOLERANCE.highMinPct.value)
89618
+ return "high";
89619
+ if (delta < HEIGHT_DIFF_TOLERANCE.lowMaxPx.value && pct < HEIGHT_DIFF_TOLERANCE.lowMaxPct.value) {
89620
+ return "low";
89621
+ }
89622
+ return "medium";
89623
+ }
89624
+ function sectionHeightDeltas(prod, cand, sections, dpr) {
89625
+ if (!prod?.found || !cand?.found)
89626
+ return [];
89627
+ const first = (nodes) => {
89628
+ const m = new Map;
89629
+ for (const n of nodes)
89630
+ if (n.label && sections.has(n.label) && !m.has(n.label))
89631
+ m.set(n.label, n);
89632
+ return m;
89633
+ };
89634
+ const c = first(cand.nodes);
89635
+ const out = [];
89636
+ for (const [name, p] of first(prod.nodes)) {
89637
+ const cn = c.get(name);
89638
+ if (!cn || Math.abs(cn.rect.height - p.rect.height) < 2)
89639
+ continue;
89640
+ out.push({
89641
+ name,
89642
+ prodH: Math.round(p.rect.height / dpr),
89643
+ candH: Math.round(cn.rect.height / dpr),
89644
+ y: p.rect.y
89645
+ });
89646
+ }
89647
+ return out.sort((a, b) => a.y - b.y).map(({ y: _y, ...rest }) => rest);
89648
+ }
89417
89649
  var WHERE_RE = / ?at \d+,\d+ — \d+×\d+/;
89418
89650
  function unionBox(a, b) {
89419
89651
  const x = Math.min(a.x, b.x);
@@ -89520,6 +89752,11 @@ async function visualRegressionKeyframes(ctx) {
89520
89752
  prodBoxTree: prod.boxTree,
89521
89753
  candBoxTree: cand.boxTree
89522
89754
  });
89755
+ const [pw, ph] = r.size.prod ?? [];
89756
+ const [cw, ch] = r.size.cand ?? [];
89757
+ const heightDiffers = r.verdict === "inconclusive" && !isUncaptured(pair.prod) && !isUncaptured(pair.cand) && pw != null && cw != null && ph != null && ch != null && pw === cw && ph !== ch;
89758
+ const sideMissing = isUncaptured(pair.prod) || isUncaptured(pair.cand) || !prodProbe || !candProbe || !prod.side.screenshot || !cand.side.screenshot;
89759
+ const notComparedKind = r.verdict !== "inconclusive" ? undefined : heightDiffers ? "height-differs" : sideMissing ? "not-captured" : "other";
89523
89760
  const prodSections = pair.prod.html ? snapshotDom(pair.prod.html).decoSectionsRendered : [];
89524
89761
  const candSections = pair.cand.html ? snapshotDom(pair.cand.html).decoSectionsRendered : [];
89525
89762
  const sectionsOnlyInProd = prodSections.filter((s) => !candSections.includes(s));
@@ -89568,14 +89805,38 @@ async function visualRegressionKeyframes(ctx) {
89568
89805
  ...r.diffPixels != null ? { diffPixels: r.diffPixels } : {},
89569
89806
  ...r.noiseFloorPixels != null ? { noiseFloorPixels: r.noiseFloorPixels } : {},
89570
89807
  ...r.maskedCoverage != null ? { maskedCoverage: r.maskedCoverage } : {},
89571
- ...reason ? { reason } : {}
89808
+ ...reason ? { reason } : {},
89809
+ ...notComparedKind ? { notComparedKind } : {}
89572
89810
  });
89573
89811
  const evidence = [
89574
89812
  { kind: "screenshot", path: pair.prod.screenshotPath, label: "prod" },
89575
89813
  { kind: "screenshot", path: pair.cand.screenshotPath, label: "cand" },
89576
89814
  ...r.heatmapPath ? [{ kind: "screenshot", path: r.heatmapPath, label: "diff" }] : []
89577
89815
  ];
89578
- if (r.verdict === "inconclusive") {
89816
+ if (heightDiffers && ph != null && ch != null) {
89817
+ const dpr = prod.side.devicePixelRatio || 1;
89818
+ const prodH = Math.round(ph / dpr);
89819
+ const candH = Math.round(ch / dpr);
89820
+ const delta = candH - prodH;
89821
+ const pct = prodH > 0 ? delta / prodH * 100 : 0;
89822
+ const signed = (n, d = 0) => `${n > 0 ? "+" : ""}${n.toFixed(d)}`;
89823
+ const named = sectionHeightDeltas(prod.boxTree, cand.boxTree, new Set([...prodSections, ...candSections]), dpr).slice(0, 3);
89824
+ issues.push({
89825
+ id: `visual:height:${pair.key}`,
89826
+ severity: heightDiffSeverity(ph, ch),
89827
+ category: "visual",
89828
+ page: pair.key,
89829
+ check: "visual-regression-keyframes",
89830
+ summary: `page height differs: prod ${prodH} px, cand ${candH} px (Δ ${signed(delta)} px, ${signed(pct, 1)}%)`,
89831
+ details: `Same width, different height — cand is ${delta < 0 ? "shorter" : "taller"} by ${Math.abs(delta)} px. The pixel diff is skipped for this page (it would only cover the intersection), so nothing below the first height difference has been compared.${named.length > 0 ? `
89832
+
89833
+ First section(s) whose height differs (prod → cand): ${named.map((n) => `${n.name} ${n.prodH} → ${n.candH} px`).join("; ")}.` : `
89834
+
89835
+ No section with a differing height could be named from the page's box trees.`}`,
89836
+ suggestedFix: "Find the cause with `parity section --box-tree` on each section (start with the sections above), fix the first height delta, then re-run: the pixel comparison starts as soon as the heights match.",
89837
+ evidence
89838
+ });
89839
+ } else if (r.verdict === "inconclusive") {
89579
89840
  issues.push({
89580
89841
  id: `visual:inconclusive:${pair.key}`,
89581
89842
  severity: "low",
@@ -89812,8 +90073,12 @@ var faviconParity2 = withHtmlSnapshot(faviconParity);
89812
90073
  var fontParity2 = withHtmlSnapshot(fontParity);
89813
90074
  var footerLinksHealth2 = withHtmlSnapshot(footerLinksHealth);
89814
90075
  var htmlStructuralDiff2 = withSameVariant(withHtmlSnapshot(htmlStructuralDiff));
89815
- var networkSummaryDelta2 = withSameVariant(networkSummaryDelta);
89816
- var webVitalsMobile2 = withSameVariant(webVitalsMobile);
90076
+ var networkSummaryDelta2 = withCapturedPairs(withSameVariant(networkSummaryDelta));
90077
+ var webVitalsMobile2 = withCapturedPairs(withSameVariant(webVitalsMobile));
90078
+ var analyticsBeaconParity2 = withCapturedPairs(analyticsBeaconParity);
90079
+ var consoleErrorsBaseline2 = withCapturedPairs(consoleErrorsBaseline);
90080
+ var redirectsParity2 = withCapturedPairs(redirectsParity);
90081
+ var thirdPartyScriptsParity2 = withCapturedPairs(thirdPartyScriptsParity);
89817
90082
  var imageLoadingHealth2 = withHtmlSnapshot(imageLoadingHealth);
89818
90083
  var lazySectionPresence2 = withHtmlSnapshot(lazySectionPresence);
89819
90084
  var metaSeoParity2 = withHtmlSnapshot(metaSeoParity);
@@ -89826,7 +90091,7 @@ var sectionOrderParity2 = withHtmlSnapshot(sectionOrderParity);
89826
90091
  var seoDeepAudit2 = withHtmlSnapshot(seoDeepAudit);
89827
90092
  var ALL_CHECKS = [
89828
90093
  httpStatusParity,
89829
- consoleErrorsBaseline,
90094
+ consoleErrorsBaseline2,
89830
90095
  htmlStructuralDiff2,
89831
90096
  metaSeoParity2,
89832
90097
  visualRegressionKeyframes,
@@ -89860,15 +90125,15 @@ var ALL_CHECKS = [
89860
90125
  contentStructureParity2,
89861
90126
  ssrNoJs,
89862
90127
  navLinksHealth2,
89863
- redirectsParity,
89864
- thirdPartyScriptsParity,
89865
- analyticsBeaconParity,
90128
+ redirectsParity2,
90129
+ thirdPartyScriptsParity2,
90130
+ analyticsBeaconParity2,
89866
90131
  sectionOrderParity2,
89867
90132
  sweepFlows
89868
90133
  ];
89869
90134
  var ALL_CHECKS_BY_NAME = {
89870
90135
  "http-status-parity": httpStatusParity,
89871
- "console-errors-baseline": consoleErrorsBaseline,
90136
+ "console-errors-baseline": consoleErrorsBaseline2,
89872
90137
  "html-structural-diff": htmlStructuralDiff2,
89873
90138
  "meta-seo-parity": metaSeoParity2,
89874
90139
  "visual-regression-keyframes": visualRegressionKeyframes,
@@ -89903,9 +90168,9 @@ var ALL_CHECKS_BY_NAME = {
89903
90168
  "content-structure": contentStructureParity2,
89904
90169
  "ssr-no-js": ssrNoJs,
89905
90170
  "nav-links-health": navLinksHealth2,
89906
- "redirects-parity": redirectsParity,
89907
- "third-party-scripts-parity": thirdPartyScriptsParity,
89908
- "analytics-beacon-parity": analyticsBeaconParity,
90171
+ "redirects-parity": redirectsParity2,
90172
+ "third-party-scripts-parity": thirdPartyScriptsParity2,
90173
+ "analytics-beacon-parity": analyticsBeaconParity2,
89909
90174
  "section-order-parity": sectionOrderParity2
89910
90175
  };
89911
90176
  var FLOW_DEPENDENT_CHECKS = new Set([
@@ -90420,7 +90685,8 @@ var VisualDiffPage = z2.object({
90420
90685
  diffPixels: z2.number().optional(),
90421
90686
  noiseFloorPixels: z2.number().optional(),
90422
90687
  maskedCoverage: z2.number().optional(),
90423
- reason: z2.string().optional()
90688
+ reason: z2.string().optional(),
90689
+ notComparedKind: z2.enum(["height-differs", "not-captured", "other"]).optional()
90424
90690
  });
90425
90691
  var VisualDiffSummary = z2.object({
90426
90692
  results: z2.array(VisualDiffPage),
@@ -90847,6 +91113,7 @@ function severityFor(cls, type) {
90847
91113
  return "low";
90848
91114
  switch (cls) {
90849
91115
  case "hydration":
91116
+ case "section-crash":
90850
91117
  return "critical";
90851
91118
  case "csp":
90852
91119
  return "high";
@@ -90874,6 +91141,7 @@ ${entry.text}`,
90874
91141
  }
90875
91142
  var HINTS = {
90876
91143
  hydration: "Hydration mismatch: o HTML do SSR não bate com o que o React tentou hidratar. " + "Causas comuns no Deco: useDevice() no client (não tem userAgent do SSR), Date.now() ou " + "Math.random() no render, dangerouslySetInnerHTML usando dados da request. Ações: encapsular " + "código client-only em useEffect, usar mesma seed nos dois lados, ou suppressHydrationWarning.",
91144
+ "section-crash": "A section or component threw while rendering and an error boundary caught it. This is a render " + "error in that component, not a server/client mismatch: fix the thrown error named in the message. " + "Line numbers come from the build at capture time and may be stale against the working tree.",
90877
91145
  csp: "Content-Security-Policy bloqueou um recurso. Adicionar o host à diretiva relevante " + "(script-src, connect-src, img-src, etc) ou remover o recurso. Atenção: bloqueio do " + "Google Analytics geralmente vem de ad-blocker do usuário, não é problema do site.",
90878
91146
  "not-found": "Recurso 404 (asset, script ou data fetch). Ações: confirmar que o arquivo existe no " + "deploy, checar paths absolutos vs relativos, verificar se cache está servindo path antigo.",
90879
91147
  "request-failed": "Request falhou em nível de network (não 404 — falha de conexão). Pode ser ERR_BLOCKED_BY_CLIENT " + "(ad blocker — não é bug), ERR_BLOCKED_BY_ORB (CORS-related), ERR_CONNECTION_REFUSED, ou DNS. " + "Investigar se é first-party (problema real) ou third-party trackers (geralmente ignorável).",
@@ -99953,6 +100221,36 @@ function rankTopIssues(issues, limit = 10) {
99953
100221
 
99954
100222
  // src/report/visual-prompt-builder.ts
99955
100223
  import { relative as relative4 } from "node:path";
100224
+
100225
+ // src/report/visual-split.ts
100226
+ function notComparedSplit(vd) {
100227
+ const out = { heightDiffers: 0, notCaptured: 0, other: 0 };
100228
+ for (const r of vd.results) {
100229
+ if (r.verdict !== "failed")
100230
+ continue;
100231
+ if (r.notComparedKind === "height-differs")
100232
+ out.heightDiffers++;
100233
+ else if (r.notComparedKind === "not-captured")
100234
+ out.notCaptured++;
100235
+ else
100236
+ out.other++;
100237
+ }
100238
+ return out;
100239
+ }
100240
+ function notComparedBreakdown(vd) {
100241
+ const s = notComparedSplit(vd);
100242
+ const parts = [
100243
+ s.heightDiffers ? `height differs: ${s.heightDiffers}` : "",
100244
+ s.notCaptured ? `not captured: ${s.notCaptured}` : "",
100245
+ s.other ? `other: ${s.other}` : ""
100246
+ ].filter(Boolean);
100247
+ return parts.length ? ` (${parts.join(", ")})` : "";
100248
+ }
100249
+ function notComparedText(vd) {
100250
+ return vd.pagesFailed === 0 ? "" : `${vd.pagesFailed} not compared${notComparedBreakdown(vd)}`;
100251
+ }
100252
+
100253
+ // src/report/visual-prompt-builder.ts
99956
100254
  var SEVERITY_ORDER2 = {
99957
100255
  critical: 0,
99958
100256
  high: 1,
@@ -100026,7 +100324,7 @@ function buildHeader(run, summary) {
100026
100324
  ""
100027
100325
  ];
100028
100326
  if (summary) {
100029
- lines.push("## Summary", "", `- **Pages compared:** ${summary.pagesChecked}`, `- **Identical:** ${summary.pagesPassed}`, `- **With differences:** ${summary.pagesWithDiffs}`, `- **Not compared (inconclusive):** ${summary.pagesFailed}`, "");
100327
+ lines.push("## Summary", "", `- **Pages compared:** ${summary.pagesChecked}`, `- **Identical:** ${summary.pagesPassed}`, `- **With differences:** ${summary.pagesWithDiffs}`, `- **Not compared (inconclusive):** ${summary.pagesFailed}${notComparedBreakdown(summary)}`, "");
100030
100328
  }
100031
100329
  return lines.join(`
100032
100330
  `);
@@ -100258,7 +100556,7 @@ function renderVisualParity(run) {
100258
100556
  const all = vd.pagesPassed === vd.pagesChecked;
100259
100557
  const rest = [
100260
100558
  vd.pagesWithDiffs > 0 ? `${vd.pagesWithDiffs} with differences` : "",
100261
- vd.pagesFailed > 0 ? `${vd.pagesFailed} not compared` : ""
100559
+ notComparedText(vd)
100262
100560
  ].filter(Boolean).join(", ");
100263
100561
  return `<div class="visual-parity" style="color:${all ? STATUS_COLOR.pass : STATUS_COLOR.warn}">
100264
100562
  <strong>Visual: ${vd.pagesPassed} of ${vd.pagesChecked} page${vd.pagesChecked === 1 ? "" : "s"} match prod</strong>
@@ -100413,7 +100711,7 @@ function buildTiles(run) {
100413
100711
  const value = vd ? `${vd.pagesPassed}/${vd.pagesChecked}` : visual.issues.length.toString();
100414
100712
  const layout = liveByCheck(run, "visual").filter((p) => !p.startsWith(`${visual.name} `));
100415
100713
  const layoutNote = layout.length > 0 ? ` · not pixel diffs: ${layout.join(", ")}` : "";
100416
- const pixelMeta = visual.status === "skipped" ? "not run" : vd && vd.pagesChecked > 0 ? vd.pagesWithDiffs > 0 ? `${vd.pagesWithDiffs} page(s) with diff` : vd.pagesFailed > 0 ? `${vd.pagesFailed} page(s) not compared` : "all pages identical" : visual.status === "pass" ? "no visual regression" : "nothing compared";
100714
+ const pixelMeta = visual.status === "skipped" ? "not run" : vd && vd.pagesChecked > 0 ? vd.pagesWithDiffs > 0 ? `${vd.pagesWithDiffs} page(s) with diff` : vd.pagesFailed > 0 ? notComparedText(vd) : "all pages identical" : visual.status === "pass" ? "no visual regression" : "nothing compared";
100417
100715
  tiles.push({
100418
100716
  icon: "\uD83D\uDDBC",
100419
100717
  label: "Visual",
@@ -101138,7 +101436,7 @@ function renderVisualDiffPanel(run, runDir) {
101138
101436
  <span class="vd-badge total">${vd.pagesChecked} pages</span>
101139
101437
  <span class="vd-badge warn">${vd.pagesWithDiffs} with diff</span>
101140
101438
  <span class="vd-badge good">${vd.pagesPassed} identical</span>
101141
- ${vd.pagesFailed > 0 ? `<span class="vd-badge inconclusive">${vd.pagesFailed} not compared</span>` : ""}
101439
+ ${vd.pagesFailed > 0 ? `<span class="vd-badge inconclusive">${escapeHtml(notComparedText(vd))}</span>` : ""}
101142
101440
  ${vd.llmCallsUsed > 0 ? `<span class="vd-badge info">${vd.llmCallsUsed} LLM Vision calls (legacy report)</span>` : ""}
101143
101441
  </div>
101144
101442
  <div class="vd-filters">
@@ -109646,20 +109944,325 @@ import { mkdirSync as mkdirSync19 } from "node:fs";
109646
109944
  import { resolve as resolve14 } from "node:path";
109647
109945
  import chalk22 from "chalk";
109648
109946
 
109947
+ // src/migrate/deferred.ts
109948
+ init_esm10();
109949
+
109950
+ // src/migrate/browser-fetch.ts
109951
+ async function browserFetchText(page, url) {
109952
+ try {
109953
+ const text = await page.evaluate(async (u) => {
109954
+ const res = await fetch(u);
109955
+ if (!res.ok)
109956
+ return null;
109957
+ return res.text();
109958
+ }, url);
109959
+ if (text != null)
109960
+ return text;
109961
+ } catch {}
109962
+ return nodeFetchText(url);
109963
+ }
109964
+ async function nodeFetchText(url) {
109965
+ try {
109966
+ const res = await fetch(url, {
109967
+ headers: {
109968
+ "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"
109969
+ },
109970
+ signal: AbortSignal.timeout(15000)
109971
+ });
109972
+ if (!res.ok)
109973
+ return null;
109974
+ return await res.text();
109975
+ } catch {
109976
+ return null;
109977
+ }
109978
+ }
109979
+
109980
+ // src/migrate/deferred.ts
109981
+ var DEFERRED_TRIGGER_SRC = "(^|,)\\s*(intersect|revealed|load)(?=[\\s\\[,]|$)";
109982
+ function sectionMarkupFromRender(response) {
109983
+ const $ = load(response);
109984
+ $("script").remove();
109985
+ const html = $("body").html()?.trim() ?? "";
109986
+ return html.length > 0 ? html : null;
109987
+ }
109988
+ function stripParityMarkers(html) {
109989
+ return html.replace(/ data-parity-(?:dfr-id|dfr-depth|dfr-next|deferred)="[^"]*"/g, "");
109990
+ }
109991
+ var DEFAULTS2 = { budgetMs: 1e4, maxDepth: 3, maxFetches: 60 };
109992
+ async function resolveDeferredContent(page, settle, opts = {}) {
109993
+ const { budgetMs, maxDepth, maxFetches } = { ...DEFAULTS2, ...opts };
109994
+ const seen = new Set;
109995
+ const fetched = new Set;
109996
+ const failed = new Map;
109997
+ const scan = async () => {
109998
+ const list = await pendingPlaceholders(page);
109999
+ for (const p of list)
110000
+ seen.add(p.id);
110001
+ return list;
110002
+ };
110003
+ await trackDeferred(page);
110004
+ await scan();
110005
+ await settle().catch(() => {
110006
+ return;
110007
+ });
110008
+ let pending = await scan();
110009
+ const deadline = Date.now() + budgetMs;
110010
+ while (pending.length > 0 && Date.now() < deadline) {
110011
+ await nudgeIntoView(page, pending.map((p) => p.id));
110012
+ await page.waitForTimeout(600).catch(() => {
110013
+ return;
110014
+ });
110015
+ pending = await scan();
110016
+ }
110017
+ const origin = new URL(page.url()).origin;
110018
+ let requests = 0;
110019
+ const fetchOne = async (p) => {
110020
+ if (p.depth >= maxDepth)
110021
+ return `nesting deeper than ${maxDepth} levels`;
110022
+ if (requests >= maxFetches)
110023
+ return `request cap (${maxFetches}) reached`;
110024
+ let abs;
110025
+ try {
110026
+ abs = new URL(p.url, page.url());
110027
+ } catch {
110028
+ return "hx-get is not a valid URL";
110029
+ }
110030
+ if (abs.origin !== origin)
110031
+ return "hx-get points at another origin; not requested";
110032
+ if (!await isStillPending(page, p.id))
110033
+ return null;
110034
+ requests++;
110035
+ const response = await browserFetchText(page, abs.toString());
110036
+ if (response === null)
110037
+ return "request failed (non-2xx or blocked)";
110038
+ const markup = sectionMarkupFromRender(response);
110039
+ if (!markup)
110040
+ return "response had no markup";
110041
+ const swapped = await injectSection(page, p, markup);
110042
+ if (swapped === "gone")
110043
+ return null;
110044
+ if (swapped === "unsupported")
110045
+ return "swap target not found, or an hx-swap mode other than innerHTML/outerHTML";
110046
+ fetched.add(p.id);
110047
+ return null;
110048
+ };
110049
+ for (let pass = 0;pass <= maxDepth && pending.length > 0; pass++) {
110050
+ for (const p of pending) {
110051
+ const why = await fetchOne(p);
110052
+ if (why)
110053
+ failed.set(p.id, { selector: p.selector, url: p.url, reason: why });
110054
+ }
110055
+ pending = (await scan()).filter((p) => !failed.has(p.id));
110056
+ }
110057
+ for (const p of pending) {
110058
+ failed.set(p.id, {
110059
+ selector: p.selector,
110060
+ url: p.url,
110061
+ reason: `still pending after ${maxDepth + 1} passes`
110062
+ });
110063
+ }
110064
+ const unresolved = [...failed.values()];
110065
+ const early = await page.evaluate(() => window.__parityDfrEarly ?? 0).catch(() => 0);
110066
+ return {
110067
+ found: seen.size + early,
110068
+ resolvedByFetch: fetched.size,
110069
+ resolvedByScroll: Math.max(0, seen.size - fetched.size - unresolved.length) + early,
110070
+ unresolved,
110071
+ complete: unresolved.length === 0
110072
+ };
110073
+ }
110074
+ function installObserver(src) {
110075
+ const w = window;
110076
+ if (w.__parityDfr)
110077
+ return;
110078
+ w.__parityDfr = true;
110079
+ w.__parityDfrEarly = 0;
110080
+ const re = new RegExp(src, "i");
110081
+ function isPending(e) {
110082
+ const hasGet = e.hasAttribute("hx-get") || e.hasAttribute("data-hx-get");
110083
+ return hasGet && re.test(e.getAttribute("hx-trigger") ?? e.getAttribute("data-hx-trigger") ?? "");
110084
+ }
110085
+ function pendingIn(n) {
110086
+ if (n.nodeType !== 1)
110087
+ return [];
110088
+ const e = n;
110089
+ const out = Array.from(e.querySelectorAll("[hx-get],[data-hx-get]")).filter(isPending);
110090
+ if (isPending(e))
110091
+ out.push(e);
110092
+ return out;
110093
+ }
110094
+ const observer = new MutationObserver((records) => {
110095
+ const parents = new Set;
110096
+ for (const r of records) {
110097
+ for (const n of Array.from(r.removedNodes)) {
110098
+ const hits = pendingIn(n);
110099
+ if (hits.length === 0)
110100
+ continue;
110101
+ parents.add(r.target);
110102
+ for (const h of hits)
110103
+ if (!h.hasAttribute("data-parity-dfr-id"))
110104
+ w.__parityDfrEarly = (w.__parityDfrEarly ?? 0) + 1;
110105
+ }
110106
+ }
110107
+ if (parents.size === 0)
110108
+ return;
110109
+ for (const r of records) {
110110
+ if (!parents.has(r.target))
110111
+ continue;
110112
+ for (const n of Array.from(r.addedNodes)) {
110113
+ if (n.nodeType === 1 && !n.hasAttribute("data-parity-deferred"))
110114
+ n.setAttribute("data-parity-deferred", "rendered");
110115
+ }
110116
+ }
110117
+ });
110118
+ observer.observe(document, { childList: true, subtree: true });
110119
+ w.__parityDfrObserver = observer;
110120
+ }
110121
+ async function trackDeferredFromStart(page) {
110122
+ await page.addInitScript(installObserver, DEFERRED_TRIGGER_SRC).catch(() => {
110123
+ return;
110124
+ });
110125
+ }
110126
+ async function trackDeferred(page) {
110127
+ await page.evaluate(installObserver, DEFERRED_TRIGGER_SRC).catch(() => {
110128
+ return;
110129
+ });
110130
+ }
110131
+ async function pendingPlaceholders(page) {
110132
+ return page.evaluate((src) => {
110133
+ const re = new RegExp(src, "i");
110134
+ const root = document.documentElement;
110135
+ let next = Number(root.getAttribute("data-parity-dfr-next") ?? "1");
110136
+ function pathOf(el) {
110137
+ const parts = [];
110138
+ let node = el;
110139
+ for (let d = 0;node && node.nodeType === 1 && d < 4; d++) {
110140
+ if (node.id) {
110141
+ parts.unshift(`#${CSS.escape(node.id)}`);
110142
+ break;
110143
+ }
110144
+ const parent = node.parentElement;
110145
+ let sel = node.tagName.toLowerCase();
110146
+ if (parent) {
110147
+ const same = Array.from(parent.children).filter((c) => c.tagName === node.tagName);
110148
+ if (same.length > 1)
110149
+ sel += `:nth-of-type(${same.indexOf(node) + 1})`;
110150
+ }
110151
+ parts.unshift(sel);
110152
+ node = parent;
110153
+ }
110154
+ return parts.join(" > ");
110155
+ }
110156
+ const out = [];
110157
+ for (const el of Array.from(document.querySelectorAll("[hx-get],[data-hx-get]"))) {
110158
+ const trigger = el.getAttribute("hx-trigger") ?? el.getAttribute("data-hx-trigger") ?? "";
110159
+ if (!re.test(trigger))
110160
+ continue;
110161
+ let id = el.getAttribute("data-parity-dfr-id");
110162
+ if (!id) {
110163
+ id = String(next++);
110164
+ el.setAttribute("data-parity-dfr-id", id);
110165
+ }
110166
+ const holder = el.closest("[data-parity-dfr-depth]");
110167
+ const target = el.getAttribute("hx-target") ?? el.getAttribute("data-hx-target");
110168
+ let shell = el;
110169
+ if (target?.startsWith("closest ")) {
110170
+ try {
110171
+ shell = el.closest(target.slice(8).trim()) ?? el;
110172
+ } catch {
110173
+ shell = el;
110174
+ }
110175
+ }
110176
+ out.push({
110177
+ id: Number(id),
110178
+ url: el.getAttribute("hx-get") ?? el.getAttribute("data-hx-get") ?? "",
110179
+ trigger,
110180
+ target,
110181
+ swap: el.getAttribute("hx-swap") ?? el.getAttribute("data-hx-swap"),
110182
+ depth: holder ? Number(holder.getAttribute("data-parity-dfr-depth") ?? "0") : 0,
110183
+ selector: pathOf(shell)
110184
+ });
110185
+ }
110186
+ root.setAttribute("data-parity-dfr-next", String(next));
110187
+ return out;
110188
+ }, DEFERRED_TRIGGER_SRC).catch(() => []);
110189
+ }
110190
+ async function isStillPending(page, id) {
110191
+ return page.evaluate((n) => document.querySelector(`[data-parity-dfr-id="${n}"]`) !== null, id).catch(() => true);
110192
+ }
110193
+ async function nudgeIntoView(page, ids) {
110194
+ await page.evaluate(async (list) => {
110195
+ for (const id of list) {
110196
+ const el = document.querySelector(`[data-parity-dfr-id="${id}"]`);
110197
+ if (!el)
110198
+ continue;
110199
+ el.scrollIntoView({ block: "center" });
110200
+ await new Promise((r) => setTimeout(r, 250));
110201
+ }
110202
+ }, ids).catch(() => {
110203
+ return;
110204
+ });
110205
+ }
110206
+ async function injectSection(page, p, markup) {
110207
+ return page.evaluate((a) => {
110208
+ const el = document.querySelector(`[data-parity-dfr-id="${a.id}"]`);
110209
+ if (!el)
110210
+ return "gone";
110211
+ const mode0 = (a.swap ?? "innerHTML").trim().split(/\s+/)[0];
110212
+ if (mode0 !== "outerHTML" && mode0 !== "innerHTML")
110213
+ return "unsupported";
110214
+ let target = el;
110215
+ const t = (a.target ?? "").trim();
110216
+ try {
110217
+ if (t.startsWith("closest "))
110218
+ target = el.closest(t.slice(8).trim());
110219
+ else if (t.startsWith("find "))
110220
+ target = el.querySelector(t.slice(5).trim());
110221
+ else if (t && t !== "this" && !/^(next|previous)\b/.test(t))
110222
+ target = document.querySelector(t);
110223
+ } catch {
110224
+ target = null;
110225
+ }
110226
+ if (!target)
110227
+ return "unsupported";
110228
+ const tpl = document.createElement("template");
110229
+ tpl.innerHTML = a.markup;
110230
+ const roots = Array.from(tpl.content.children);
110231
+ for (const r of roots) {
110232
+ r.setAttribute("data-parity-deferred", "fetched");
110233
+ r.setAttribute("data-parity-dfr-depth", String(a.depth + 1));
110234
+ }
110235
+ if (mode0 === "outerHTML")
110236
+ target.replaceWith(...Array.from(tpl.content.childNodes));
110237
+ else
110238
+ target.replaceChildren(...Array.from(tpl.content.childNodes));
110239
+ return "ok";
110240
+ }, { id: p.id, target: p.target, swap: p.swap, markup, depth: p.depth }).catch(() => "unsupported");
110241
+ }
110242
+
109649
110243
  // src/extract/detect-components.ts
109650
110244
  async function detectComponents(page, opts) {
109651
- const raw = await page.evaluate(collectCandidatesInPage);
109652
- const deduped = dedupeByContainment(raw);
110245
+ const raw = await page.evaluate(collectCandidatesInPage, DEFERRED_TRIGGER_SRC);
110246
+ const deduped = disambiguateLiveRoles(dedupeByContainment(applyManifestRoles(raw)));
109653
110247
  const components = deduped.map((c) => ({
109654
110248
  role: c.role,
109655
110249
  selector: c.selector,
109656
- boundingBox: c.rect
110250
+ boundingBox: c.rect,
110251
+ ...c.liveType ? { liveType: c.liveType, liveTypeAttr: c.liveTypeAttr } : {},
110252
+ ...c.nameFrom ? { nameFrom: c.nameFrom } : {},
110253
+ ...c.deferred ? { deferred: c.deferred } : {},
110254
+ ...c.wrapperSelector ? { wrapperSelector: c.wrapperSelector } : {},
110255
+ ...c.children?.length ? { children: c.children } : {},
110256
+ ...c.childrenOmitted ? { childrenOmitted: c.childrenOmitted } : {}
109657
110257
  }));
109658
110258
  if (opts?.llm && isComponentDetectionLlmAvailable()) {
109659
110259
  await Promise.resolve().then(() => init_component_refine());
109660
- const refined = await refineComponentsWithLlm(page, components);
109661
- if (refined)
109662
- return sanitizeDetectedComponents(refined);
110260
+ const guesses = components.filter((c) => c.nameFrom !== "manifest");
110261
+ const refined = guesses.length ? await refineComponentsWithLlm(page, guesses) : null;
110262
+ if (refined) {
110263
+ const bySelector = new Map(refined.map((c) => [c.selector, c.role]));
110264
+ return sanitizeDetectedComponents(components.map((c) => c.nameFrom === "manifest" ? c : { ...c, role: bySelector.get(c.selector) ?? c.role }));
110265
+ }
109663
110266
  }
109664
110267
  return sanitizeDetectedComponents(components);
109665
110268
  }
@@ -109717,7 +110320,7 @@ function sanitizeDetectedComponents(components) {
109717
110320
  const seenGlobal = new Set;
109718
110321
  const out = [];
109719
110322
  for (const c of components) {
109720
- if (isStructuralJunkRole(c.role))
110323
+ if (c.nameFrom !== "manifest" && isStructuralJunkRole(c.role))
109721
110324
  continue;
109722
110325
  const role = canonicalRole(c.role);
109723
110326
  if (role === "header" || role === "footer" || role === "nav") {
@@ -109732,16 +110335,66 @@ function sanitizeDetectedComponents(components) {
109732
110335
  var ZERO_AREA_ALLOWED = new Set(["header", "footer", "nav", "banner"]);
109733
110336
  function dedupeByContainment(candidates) {
109734
110337
  const valid = candidates.filter((c) => c.rect.width > 0 && c.rect.height > 0 || ZERO_AREA_ALLOWED.has(c.role));
109735
- const sorted = [...valid].sort((a, b) => boxArea(b.rect) - boxArea(a.rect));
110338
+ const bySize = [...valid].sort((a, b) => boxArea(b.rect) - boxArea(a.rect));
110339
+ const sorted = [...bySize.filter((c) => c.liveType), ...bySize.filter((c) => !c.liveType)];
109736
110340
  const accepted = [];
109737
110341
  for (const candidate of sorted) {
109738
- const containedInAccepted = boxArea(candidate.rect) > 0 && accepted.some((a) => boxArea(a.rect) > 0 && a.priority >= candidate.priority && containmentRatio(candidate.rect, a.rect) >= 0.9);
109739
- if (containedInAccepted)
110342
+ const declaredParent = candidate.within ? accepted.find((a) => a.liveType && a.selector === candidate.within) : undefined;
110343
+ const container = declaredParent ?? (boxArea(candidate.rect) > 0 ? accepted.find((a) => boxArea(a.rect) > 0 && a.priority >= candidate.priority && !(a.liveType && candidate.liveType) && containmentRatio(candidate.rect, a.rect) >= 0.9) : undefined);
110344
+ if (container) {
110345
+ if (container.liveType) {
110346
+ container.children ??= [];
110347
+ if (container.children.length < CHILDREN_CAP)
110348
+ container.children.push({ role: candidate.role, selector: candidate.selector });
110349
+ else
110350
+ container.childrenOmitted = (container.childrenOmitted ?? 0) + 1;
110351
+ }
109740
110352
  continue;
110353
+ }
109741
110354
  accepted.push(candidate);
109742
110355
  }
109743
110356
  return accepted.sort((a, b) => a.rect.y - b.rect.y);
109744
110357
  }
110358
+ var CHILDREN_CAP = 20;
110359
+ var LIVE_TYPE_DIR_NOISE = new Set([
110360
+ "site",
110361
+ "src",
110362
+ "app",
110363
+ "components",
110364
+ "sections",
110365
+ "islands",
110366
+ "blocks",
110367
+ "website"
110368
+ ]);
110369
+ function kebab(s) {
110370
+ return s.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "section";
110371
+ }
110372
+ function roleFromManifestKey(key) {
110373
+ const parts = key.split("/").filter(Boolean);
110374
+ let base = (parts[parts.length - 1] ?? "").replace(/\.[jt]sx?$/, "");
110375
+ if (/^(index|mod|main)$/i.test(base) && parts.length > 1)
110376
+ base = parts[parts.length - 2];
110377
+ return kebab(base);
110378
+ }
110379
+ function applyManifestRoles(candidates) {
110380
+ return candidates.map((c) => c.liveTypeAttr === "data-manifest-key" && c.liveType ? { ...c, role: roleFromManifestKey(c.liveType) } : c);
110381
+ }
110382
+ function disambiguateLiveRoles(candidates) {
110383
+ const types = new Map;
110384
+ for (const c of candidates) {
110385
+ if (c.liveTypeAttr !== "data-manifest-key" || !c.liveType)
110386
+ continue;
110387
+ const set = types.get(c.role) ?? new Set;
110388
+ set.add(c.liveType);
110389
+ types.set(c.role, set);
110390
+ }
110391
+ return candidates.map((c) => {
110392
+ if (c.liveTypeAttr !== "data-manifest-key" || !c.liveType || (types.get(c.role)?.size ?? 0) < 2)
110393
+ return c;
110394
+ const segs = c.liveType.replace(/\.[jt]sx?$/, "").split("/").filter((p) => !LIVE_TYPE_DIR_NOISE.has(p));
110395
+ return { ...c, role: kebab(segs.join("-")) };
110396
+ });
110397
+ }
109745
110398
  function boxArea(box) {
109746
110399
  return Math.max(0, box.width) * Math.max(0, box.height);
109747
110400
  }
@@ -109758,7 +110411,8 @@ function containmentRatio(inner, outer) {
109758
110411
  return 0;
109759
110412
  return boxOverlapArea(inner, outer) / innerArea;
109760
110413
  }
109761
- function collectCandidatesInPage() {
110414
+ function collectCandidatesInPage(deferredTriggerSrc) {
110415
+ const deferredRe = new RegExp(deferredTriggerSrc, "i");
109762
110416
  function cssPath(el) {
109763
110417
  if (el.id)
109764
110418
  return `#${CSS.escape(el.id)}`;
@@ -109805,16 +110459,26 @@ function collectCandidatesInPage() {
109805
110459
  };
109806
110460
  const seen = new Set;
109807
110461
  const out = [];
109808
- function push(role, el) {
110462
+ const elOf = new Map;
110463
+ const candOf = new Map;
110464
+ function push(role, el, live) {
109809
110465
  if (seen.has(el))
109810
110466
  return;
109811
110467
  seen.add(el);
109812
- out.push({
110468
+ const c = {
109813
110469
  role,
109814
110470
  selector: cssPath(el),
109815
110471
  rect: rectOf(el),
109816
110472
  priority: priorityByRole[role] ?? 30
109817
- });
110473
+ };
110474
+ if (live) {
110475
+ c.liveType = live.type;
110476
+ c.liveTypeAttr = live.attr;
110477
+ c.nameFrom = "manifest";
110478
+ }
110479
+ out.push(c);
110480
+ elOf.set(c, el);
110481
+ candOf.set(el, c);
109818
110482
  }
109819
110483
  for (const el of Array.from(document.querySelectorAll("header")))
109820
110484
  push("header", el);
@@ -109832,7 +110496,62 @@ function collectCandidatesInPage() {
109832
110496
  push("carousel", el);
109833
110497
  for (const el of Array.from(document.querySelectorAll("[data-section], [data-deco-section]"))) {
109834
110498
  const name = el.getAttribute("data-section") ?? el.getAttribute("data-deco-section") ?? "section";
109835
- push(`section-${slug(name)}`, el);
110499
+ push(`section-${slug(name)}`, el, {
110500
+ type: name,
110501
+ attr: el.hasAttribute("data-section") ? "data-section" : "data-deco-section"
110502
+ });
110503
+ }
110504
+ const IGNORABLE = /^(SCRIPT|STYLE|TEMPLATE|NOSCRIPT|LINK|META)$/;
110505
+ function contentChildren(el) {
110506
+ return Array.from(el.children).filter((c) => !IGNORABLE.test(c.tagName));
110507
+ }
110508
+ function throughTo(el, pred) {
110509
+ let cur = el;
110510
+ for (let i = 0;i < 8; i++) {
110511
+ const kids = contentChildren(cur);
110512
+ if (kids.length !== 1)
110513
+ return null;
110514
+ cur = kids[0];
110515
+ if (pred(cur))
110516
+ return cur;
110517
+ }
110518
+ return null;
110519
+ }
110520
+ function isPending(e) {
110521
+ const hasGet = e.hasAttribute("hx-get") || e.hasAttribute("data-hx-get");
110522
+ return hasGet && deferredRe.test(e.getAttribute("hx-trigger") ?? e.getAttribute("data-hx-trigger") ?? "");
110523
+ }
110524
+ const dropped = new Set;
110525
+ const wrapperOf = new Map;
110526
+ for (const el of Array.from(document.querySelectorAll("[data-manifest-key]"))) {
110527
+ if (isPending(el) || throughTo(el, isPending)) {
110528
+ dropped.add(el);
110529
+ continue;
110530
+ }
110531
+ const inner = throughTo(el, (e) => e.hasAttribute("data-manifest-key"));
110532
+ if (inner) {
110533
+ dropped.add(el);
110534
+ wrapperOf.set(inner, wrapperOf.get(el) ?? cssPath(el));
110535
+ continue;
110536
+ }
110537
+ const key = el.getAttribute("data-manifest-key") ?? "";
110538
+ if (!key)
110539
+ continue;
110540
+ const existing = candOf.get(el);
110541
+ if (!existing) {
110542
+ push("section", el, { type: key, attr: "data-manifest-key" });
110543
+ candOf.get(el).priority = 100;
110544
+ } else if (existing.liveTypeAttr === undefined) {
110545
+ existing.liveType = key;
110546
+ existing.liveTypeAttr = "data-manifest-key";
110547
+ existing.nameFrom = "manifest";
110548
+ existing.priority = 100;
110549
+ }
110550
+ }
110551
+ for (const [inner, wrapper] of wrapperOf) {
110552
+ const c = candOf.get(inner);
110553
+ if (c)
110554
+ c.wrapperSelector = wrapper;
109836
110555
  }
109837
110556
  const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
109838
110557
  const root = document.querySelector("main") ?? document.body;
@@ -109842,7 +110561,7 @@ function collectCandidatesInPage() {
109842
110561
  const tag = el.tagName.toLowerCase();
109843
110562
  if (["header", "footer", "nav", "script", "style"].includes(tag))
109844
110563
  continue;
109845
- if (seen.has(el))
110564
+ if (seen.has(el) || dropped.has(el))
109846
110565
  continue;
109847
110566
  const rect = rectOf(el);
109848
110567
  if (rect.width === 0 || rect.height === 0)
@@ -109897,6 +110616,23 @@ function collectCandidatesInPage() {
109897
110616
  if (footer)
109898
110617
  push("footer", footer);
109899
110618
  }
110619
+ for (const c of out) {
110620
+ const el = elOf.get(c);
110621
+ const via = el?.closest("[data-parity-deferred]")?.getAttribute("data-parity-deferred");
110622
+ if (via === "rendered" || via === "fetched")
110623
+ c.deferred = via;
110624
+ if (!c.nameFrom)
110625
+ c.nameFrom = "heuristic";
110626
+ if (!c.liveType && el) {
110627
+ for (let up = el.parentElement;up; up = up.parentElement) {
110628
+ const owner = candOf.get(up);
110629
+ if (owner?.liveType) {
110630
+ c.within = owner.selector;
110631
+ break;
110632
+ }
110633
+ }
110634
+ }
110635
+ }
109900
110636
  return out;
109901
110637
  }
109902
110638
 
@@ -110058,12 +110794,18 @@ async function extractComponent(page, component, opts) {
110058
110794
  const extracted = {
110059
110795
  role: component.role,
110060
110796
  selector: component.selector,
110061
- html: artifacts.html ?? "",
110797
+ html: stripParityMarkers(artifacts.html ?? ""),
110062
110798
  computedStyles,
110063
110799
  screenshotPath,
110064
110800
  assets: { images, backgroundImages, fonts },
110065
110801
  links: capLinks(links, LINK_CAP),
110066
- textContent
110802
+ textContent,
110803
+ ...component.liveType ? { liveType: component.liveType, liveTypeAttr: component.liveTypeAttr } : {},
110804
+ ...component.nameFrom ? { nameFrom: component.nameFrom } : {},
110805
+ ...component.deferred ? { deferred: component.deferred } : {},
110806
+ ...component.wrapperSelector ? { wrapperSelector: component.wrapperSelector } : {},
110807
+ ...component.children?.length ? { children: component.children } : {},
110808
+ ...component.childrenOmitted ? { childrenOmitted: component.childrenOmitted } : {}
110067
110809
  };
110068
110810
  writeFileSync25(`${opts.outDir}/component.html`, extracted.html, "utf8");
110069
110811
  writeFileSync25(`${opts.outDir}/styles.json`, `${JSON.stringify(computedStyles ?? {}, null, 2)}
@@ -110766,7 +111508,7 @@ async function htmlCommand(opts) {
110766
111508
  const browser = await launchBrowser({ headless: true });
110767
111509
  try {
110768
111510
  if (mode.kind === "single") {
110769
- const html = await fetchSnapshot(browser, mode.url, viewport, waitMs);
111511
+ const html = await fetchSnapshot(browser, mode.url, viewport, waitMs, opts.resolveDeferred !== false);
110770
111512
  const piece = extractSelector(html, opts.selector);
110771
111513
  if (piece.error) {
110772
111514
  console.error(chalk23.red(piece.error));
@@ -110788,8 +111530,8 @@ async function htmlCommand(opts) {
110788
111530
  return 0;
110789
111531
  }
110790
111532
  const [prodHtml, candHtml] = await Promise.all([
110791
- fetchSnapshot(browser, mode.prod, viewport, waitMs),
110792
- fetchSnapshot(browser, mode.cand, viewport, waitMs)
111533
+ fetchSnapshot(browser, mode.prod, viewport, waitMs, opts.resolveDeferred !== false),
111534
+ fetchSnapshot(browser, mode.cand, viewport, waitMs, opts.resolveDeferred !== false)
110793
111535
  ]);
110794
111536
  const prodPiece = extractSelector(prodHtml, opts.selector);
110795
111537
  const candPiece = extractSelector(candHtml, opts.selector);
@@ -110877,17 +111619,26 @@ function parseViewport4(raw) {
110877
111619
  return raw;
110878
111620
  return null;
110879
111621
  }
110880
- async function fetchSnapshot(browser, url, viewport, waitMs) {
111622
+ async function fetchSnapshot(browser, url, viewport, waitMs, resolveDeferred = true) {
110881
111623
  const ctx = await newContext(browser, { viewport });
110882
111624
  const page = await ctx.newPage();
110883
111625
  try {
111626
+ if (resolveDeferred)
111627
+ await trackDeferredFromStart(page);
110884
111628
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30000 });
110885
111629
  await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
110886
111630
  return;
110887
111631
  });
110888
111632
  if (waitMs > 0)
110889
111633
  await page.waitForTimeout(waitMs);
110890
- return await page.content();
111634
+ if (resolveDeferred) {
111635
+ const r = await resolveDeferredContent(page, async () => {
111636
+ return;
111637
+ });
111638
+ if (r.unresolved.length > 0)
111639
+ console.error(chalk23.yellow(` ⚠ ${url}: ${r.unresolved.length} deferred section(s) left unresolved (${r.unresolved.map((u) => u.selector).join(", ")}) — this HTML contains their placeholders`));
111640
+ }
111641
+ return stripParityMarkers(await page.content());
110891
111642
  } finally {
110892
111643
  await page.close().catch(() => {
110893
111644
  return;
@@ -112919,34 +113670,159 @@ function firstProductHref(html, baseUrl, platform) {
112919
113670
  return firstProductHrefFromPlpHtml(html, baseUrl);
112920
113671
  }
112921
113672
 
112922
- // src/migrate/browser-fetch.ts
112923
- async function browserFetchText(page, url) {
112924
- try {
112925
- const text = await page.evaluate(async (u) => {
112926
- const res = await fetch(u);
112927
- if (!res.ok)
112928
- return null;
112929
- return res.text();
112930
- }, url);
112931
- if (text != null)
112932
- return text;
112933
- } catch {}
112934
- return nodeFetchText(url);
113673
+ // src/migrate/routes.ts
113674
+ init_esm10();
113675
+ var ASSET_EXT = /\.(?:pdf|zip|jpe?g|png|gif|webp|avif|svg|ico|mp4|webm|mp3|xml|json|txt|css|js|woff2?|ttf|docx?|xlsx?|pptx?)$/i;
113676
+ function extractSameOriginLinks(html, pageUrl) {
113677
+ const base = new URL(pageUrl);
113678
+ const bare = (h) => h.replace(/^www\./i, "").toLowerCase();
113679
+ const $ = load(html);
113680
+ const seen = new Set;
113681
+ const byZone = { nav: [], footer: [], content: [] };
113682
+ $("a[href]").each((_, a) => {
113683
+ const href = ($(a).attr("href") ?? "").trim();
113684
+ if (!href || href.startsWith("#") || /^(mailto|tel|sms|javascript|data|whatsapp):/i.test(href))
113685
+ return;
113686
+ let u;
113687
+ try {
113688
+ u = new URL(href, base);
113689
+ } catch {
113690
+ return;
113691
+ }
113692
+ if (!/^https?:$/.test(u.protocol) || bare(u.hostname) !== bare(base.hostname))
113693
+ return;
113694
+ const path = u.pathname.replace(/\/+$/, "") || "/";
113695
+ if (path === "/" || ASSET_EXT.test(path) || seen.has(path))
113696
+ return;
113697
+ seen.add(path);
113698
+ const zone = $(a).closest("footer").length ? "footer" : $(a).closest("nav, header").length ? "nav" : "content";
113699
+ byZone[zone].push({ path, zone });
113700
+ });
113701
+ return [...byZone.nav, ...byZone.footer, ...byZone.content];
112935
113702
  }
112936
- async function nodeFetchText(url) {
113703
+ function isDisallowedByRobots(path, robots) {
113704
+ const rules = robots?.userAgents["*"];
113705
+ if (!rules)
113706
+ return false;
113707
+ const matchLen = (rule) => {
113708
+ if (!rule)
113709
+ return -1;
113710
+ const anchored = rule.endsWith("$");
113711
+ const body = (anchored ? rule.slice(0, -1) : rule).split("*").map((p) => p.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
113712
+ return new RegExp(`^${body}${anchored ? "$" : ""}`).test(path) ? rule.length : -1;
113713
+ };
113714
+ const dis = Math.max(-1, ...rules.disallow.map(matchLen));
113715
+ const allow = Math.max(-1, ...rules.allow.map(matchLen));
113716
+ return dis >= 0 && dis > allow;
113717
+ }
113718
+ var EXAMPLES_PER_TEMPLATE = 3;
113719
+ function templateOf(path) {
113720
+ const segs = path.split("/").filter(Boolean);
113721
+ if (segs.length <= 1)
113722
+ return path;
113723
+ return `/${segs[0]}/*`;
113724
+ }
113725
+ function groupTemplates(links) {
113726
+ const byTemplate = new Map;
113727
+ for (const l of links) {
113728
+ const key = templateOf(l.path);
113729
+ const t = byTemplate.get(key) ?? { template: key, count: 0, examples: [], zone: l.zone };
113730
+ t.count++;
113731
+ if (t.examples.length < EXAMPLES_PER_TEMPLATE)
113732
+ t.examples.push(l.path);
113733
+ byTemplate.set(key, t);
113734
+ }
113735
+ return [...byTemplate.values()];
113736
+ }
113737
+ var LINK_DISCOVERY = { maxPages: 12, maxFetches: 8, maxDepth: 2 };
113738
+ async function discoverRoutesFromLinks(page, homeUrl, homeHtml, robots, limits = LINK_DISCOVERY) {
113739
+ const all = new Map;
113740
+ const disallowed = new Set;
113741
+ const take = (links) => {
113742
+ for (const l of links) {
113743
+ if (all.has(l.path) || disallowed.has(l.path))
113744
+ continue;
113745
+ if (isDisallowedByRobots(l.path, robots))
113746
+ disallowed.add(l.path);
113747
+ else
113748
+ all.set(l.path, l);
113749
+ }
113750
+ };
113751
+ take(extractSameOriginLinks(homeHtml, homeUrl));
113752
+ let depth = 1;
113753
+ let fetchedPages = 0;
113754
+ let templates = groupTemplates([...all.values()]);
113755
+ if (limits.maxDepth >= 2 && templates.length < limits.maxPages) {
113756
+ depth = 2;
113757
+ for (const t of templates) {
113758
+ if (fetchedPages >= limits.maxFetches)
113759
+ break;
113760
+ const example = t.examples[0];
113761
+ if (!example)
113762
+ continue;
113763
+ const url = new URL(example, homeUrl).toString();
113764
+ const html = await browserFetchText(page, url);
113765
+ fetchedPages++;
113766
+ if (html)
113767
+ take(extractSameOriginLinks(html, url).map((l) => ({ ...l, zone: "content" })));
113768
+ }
113769
+ templates = groupTemplates([...all.values()]);
113770
+ }
113771
+ const kept = templates.slice(0, limits.maxPages);
113772
+ return {
113773
+ representatives: kept.map((t) => ({
113774
+ path: t.examples[0],
113775
+ url: new URL(t.examples[0], homeUrl).toString(),
113776
+ template: t.template
113777
+ })),
113778
+ discovery: {
113779
+ discovered: all.size,
113780
+ templates,
113781
+ robotsDisallowed: disallowed.size,
113782
+ depth,
113783
+ fetchedPages,
113784
+ cap: {
113785
+ limit: limits.maxPages,
113786
+ templatesDropped: Math.max(0, templates.length - kept.length)
113787
+ }
113788
+ }
113789
+ };
113790
+ }
113791
+ async function fetchRobotsViaPage(page, origin) {
113792
+ const txt = await browserFetchText(page, `${origin}/robots.txt`);
113793
+ return txt && !txt.trim().startsWith("<") ? parseRobots(txt) : null;
113794
+ }
113795
+ function decidePageKind(path, profile, profileEvidence) {
113796
+ const shaped = classifyPath(path);
113797
+ if (profile === "content" && (shaped === "plp" || shaped === "pdp")) {
113798
+ return {
113799
+ kind: "other",
113800
+ evidence: `URL shape reads as ${shaped}, but the site profile is content (${profileEvidence}) and nothing on the page marks it as a storefront ${shaped}; kept as other`
113801
+ };
113802
+ }
113803
+ return {
113804
+ kind: shaped,
113805
+ evidence: `URL shape reads as ${shaped}${shaped === "other" || shaped === "home" ? "" : `; site profile ${profile} (${profileEvidence})`}`
113806
+ };
113807
+ }
113808
+ function siteProfileWithEvidence(url, html) {
113809
+ const profile = detectSiteProfile({ url, html });
113810
+ const stack = classifyLiveStack(html);
113811
+ const platform = detectPlatform({ url, html });
113812
+ const evidence = profile === "commerce" ? stack.commerce !== "unknown" ? `commerce backend: ${stack.commerce}` : `commerce platform: ${platform}` : "no commerce backend or storefront platform signal in the home HTML";
113813
+ return { profile, evidence };
113814
+ }
113815
+ var TEMPLATED_URL = /\$\{|\{\{|%7B|<%/i;
113816
+ function autoUrlRejection(url, origin) {
113817
+ if (TEMPLATED_URL.test(url))
113818
+ return "contains template/placeholder syntax";
112937
113819
  try {
112938
- const res = await fetch(url, {
112939
- headers: {
112940
- "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1"
112941
- },
112942
- signal: AbortSignal.timeout(15000)
112943
- });
112944
- if (!res.ok)
112945
- return null;
112946
- return await res.text();
113820
+ if (new URL(url).origin !== origin)
113821
+ return "not same-origin";
112947
113822
  } catch {
112948
- return null;
113823
+ return "not a valid URL";
112949
113824
  }
113825
+ return null;
112950
113826
  }
112951
113827
 
112952
113828
  // src/migrate/exporters/json.ts
@@ -113740,6 +114616,15 @@ function buildMigrationPrompt(bundle, playbook, source) {
113740
114616
  md(`- **Captured**: ${bundle.timestamp} (${bundle.viewport})`);
113741
114617
  md(`- **Pages**: ${bundle.pages.map((p) => `${p.kind} (${p.path})`).join(", ") || "—"}`);
113742
114618
  md("");
114619
+ const partial = bundle.pages.filter((p) => p.deferral && !p.deferral.complete);
114620
+ if (partial.length) {
114621
+ md("> **Partial inventory.** Deferred sections on these pages could not be resolved, so the");
114622
+ md("> component list below is missing whatever they hold (selectors are in");
114623
+ md("> `migration-plan.json` → `pages[].deferral.unresolved`):");
114624
+ for (const p of partial)
114625
+ md(`> - \`${p.path}\`: ${p.deferral.unresolved.length} unresolved`);
114626
+ md("");
114627
+ }
113743
114628
  if (source?.playbook) {
113744
114629
  md(source.playbook);
113745
114630
  md("");
@@ -114927,22 +115812,36 @@ async function migrateCommand(opts) {
114927
115812
  }
114928
115813
  const sitemapPath = resolve19(runDir, "sitemap.json");
114929
115814
  let resolvedPages;
115815
+ let discovery;
114930
115816
  if (!opts.refresh && existsSync28(sitemapPath)) {
114931
- resolvedPages = readJson2(sitemapPath).pages;
115817
+ const cached = readJson2(sitemapPath);
115818
+ resolvedPages = cached.pages;
115819
+ discovery = cached.discovery;
114932
115820
  console.log(chalk31.dim(` phase 2 sitemap: cached (${resolvedPages.length} page(s))`));
114933
115821
  } else {
114934
115822
  console.log(chalk31.dim(" phase 2 sitemap: resolving pages…"));
114935
115823
  const ctx = await newContext(browser, { viewport: primaryViewport, ...auth });
114936
115824
  const page = await ctx.newPage();
114937
115825
  let sitemapUrls = [];
115826
+ let linkDiscovery = null;
115827
+ let profile = "commerce";
115828
+ let profileEvidence = "";
115829
+ let autoPages = {};
114938
115830
  try {
114939
115831
  await page.goto(opts.url, { waitUntil: "domcontentloaded", timeout: 30000 });
114940
115832
  await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
114941
115833
  return;
114942
115834
  });
114943
115835
  const homeHtml = await page.content().catch(() => "");
114944
- resolvedPages = await resolvePages2(page, opts.url, pageTokens, homeHtml, platform);
115836
+ ({ profile, evidence: profileEvidence } = siteProfileWithEvidence(opts.url, homeHtml));
115837
+ ({ pages: resolvedPages, auto: autoPages } = await resolvePages2(page, opts.url, pageTokens, homeHtml, platform, profile, profileEvidence));
114945
115838
  sitemapUrls = await discoverSitemapUrls(page, opts.url);
115839
+ if (sitemapUrls.length === 0 && !opts.pages) {
115840
+ await resolveDeferredContent(page, () => settlePage(page, { fonts: false, layoutStable: false }));
115841
+ const renderedHtml = await page.content().catch(() => homeHtml);
115842
+ const robots = await fetchRobotsViaPage(page, new URL(opts.url).origin);
115843
+ linkDiscovery = await discoverRoutesFromLinks(page, opts.url, renderedHtml, robots);
115844
+ }
114946
115845
  } finally {
114947
115846
  await page.close().catch(() => {
114948
115847
  return;
@@ -114952,8 +115851,34 @@ async function migrateCommand(opts) {
114952
115851
  });
114953
115852
  }
114954
115853
  const classified = sitemapUrls.slice(0, 500).map((u) => ({ url: u, kind: kindOf(u) }));
114955
- const sampled = sampleFromSitemap(classified, parseSample(opts.sample), resolvedPages);
114956
- resolvedPages = [...resolvedPages, ...sampled].slice(0, MAX_PAGES2);
115854
+ const sampled = sampleFromSitemap(classified, parseSample(opts.sample), resolvedPages).map((p) => ({ ...p, ...decidePageKind(pathOf6(p.url), profile, profileEvidence) }));
115855
+ resolvedPages = [...resolvedPages, ...sampled];
115856
+ if (linkDiscovery) {
115857
+ const have = new Set(resolvedPages.map((p) => pathOf6(p.url)));
115858
+ for (const r of linkDiscovery.representatives) {
115859
+ if (have.has(r.path))
115860
+ continue;
115861
+ have.add(r.path);
115862
+ resolvedPages.push({
115863
+ path: r.path,
115864
+ url: r.url,
115865
+ template: r.template,
115866
+ ...(() => {
115867
+ const d = decidePageKind(r.path, profile, profileEvidence);
115868
+ return { kind: d.kind, kindEvidence: d.evidence };
115869
+ })()
115870
+ });
115871
+ }
115872
+ console.log(chalk31.dim(` phase 2 links: no sitemap — ${linkDiscovery.discovery.discovered} same-origin path(s) in ${linkDiscovery.discovery.templates.length} template(s), ${linkDiscovery.representatives.length} sampled${linkDiscovery.discovery.cap.templatesDropped ? ` (${linkDiscovery.discovery.cap.templatesDropped} template(s) over the cap of ${linkDiscovery.discovery.cap.limit} NOT captured)` : ""}`));
115873
+ }
115874
+ resolvedPages = resolvedPages.slice(0, MAX_PAGES2);
115875
+ discovery = {
115876
+ pages: sitemapUrls.length ? "sitemap" : linkDiscovery ? "links" : "explicit",
115877
+ siteProfile: profile,
115878
+ profileEvidence,
115879
+ ...Object.keys(autoPages).length ? { autoPages } : {},
115880
+ ...linkDiscovery ? { links: linkDiscovery.discovery } : {}
115881
+ };
114957
115882
  if (sampled.length) {
114958
115883
  const byKind = sampled.reduce((a, p) => {
114959
115884
  a[p.kind] = (a[p.kind] ?? 0) + 1;
@@ -114961,7 +115886,7 @@ async function migrateCommand(opts) {
114961
115886
  }, {});
114962
115887
  console.log(chalk31.dim(` phase 2 sitemap: +${sampled.length} sampled (${Object.entries(byKind).map(([k, n]) => `${n} ${k}`).join(", ")})`));
114963
115888
  }
114964
- writeFileSync31(sitemapPath, `${JSON.stringify({ pages: resolvedPages, sitemapUrls: classified }, null, 2)}
115889
+ writeFileSync31(sitemapPath, `${JSON.stringify({ pages: resolvedPages, sitemapUrls: classified, discovery }, null, 2)}
114965
115890
  `, "utf8");
114966
115891
  }
114967
115892
  if (resolvedPages.length === 0) {
@@ -115012,6 +115937,7 @@ async function migrateCommand(opts) {
115012
115937
  theme,
115013
115938
  assets,
115014
115939
  vtex: vtexBlocks ? { blocks: vtexBlocks, map: mapVtexBlocksToFastStore(vtexBlocks) } : undefined,
115940
+ ...discovery ? { discovery } : {},
115015
115941
  pages,
115016
115942
  components
115017
115943
  };
@@ -115117,12 +116043,20 @@ async function capturePages(browser, viewport, resolvedPages, theme, cfg) {
115117
116043
  };
115118
116044
  const pageComponents = [];
115119
116045
  const capturedHere = [];
116046
+ let deferral;
115120
116047
  try {
116048
+ await trackDeferredFromStart(page);
115121
116049
  await page.goto(target.url, { waitUntil: "domcontentloaded", timeout: 30000 });
115122
116050
  await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
115123
116051
  return;
115124
116052
  });
115125
- await settlePage(page, { fonts: false, layoutStable: false });
116053
+ deferral = await resolveDeferredContent(page, () => settlePage(page, { fonts: false, layoutStable: false }));
116054
+ if (deferral.found > 0) {
116055
+ console.log(chalk31.dim(` ${target.path}: ${deferral.found} deferred placeholder(s) — ${deferral.resolvedByScroll} by scroll, ${deferral.resolvedByFetch} fetched, ${deferral.unresolved.length} unresolved`));
116056
+ }
116057
+ if (deferral.unresolved.length > 0) {
116058
+ console.warn(chalk31.yellow(` ⚠ ${target.path}: ${deferral.unresolved.length} deferred section(s) could NOT be resolved — this page's inventory is PARTIAL (${deferral.unresolved.map((u) => `${u.selector}: ${u.reason}`).join("; ")})`));
116059
+ }
115126
116060
  let detected = await detectComponents(page, { llm: cfg.llm });
115127
116061
  if (cfg.allowlist)
115128
116062
  detected = detected.filter((c) => matchesAllowlist2(c.role, cfg.allowlist));
@@ -115166,7 +116100,15 @@ async function capturePages(browser, viewport, resolvedPages, theme, cfg) {
115166
116100
  if (!global)
115167
116101
  pageComponents.push(migrated);
115168
116102
  }
115169
- pages.push({ url: target.url, path: target.path, kind: target.kind, components: pageComponents });
116103
+ pages.push({
116104
+ url: target.url,
116105
+ path: target.path,
116106
+ kind: target.kind,
116107
+ components: pageComponents,
116108
+ ...target.kindEvidence ? { kindEvidence: target.kindEvidence } : {},
116109
+ ...target.template ? { template: target.template } : {},
116110
+ ...deferral ? { deferral } : {}
116111
+ });
115170
116112
  const pageBlocks = cfg.vtexScrape ? await readVtexBlockTree(page) : null;
115171
116113
  if (pageBlocks) {
115172
116114
  const refMap = collectImageRefs(pageBlocks, cfg.baseUrl);
@@ -115218,11 +116160,13 @@ async function captureViewportVariants(browser, url, extraViewports, captured, r
115218
116160
  try {
115219
116161
  ctx = await newContext(browser, { viewport: vp, ...auth });
115220
116162
  page = await ctx.newPage();
116163
+ await trackDeferredFromStart(page);
115221
116164
  await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30000 });
115222
116165
  await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
115223
116166
  return;
115224
116167
  });
115225
- await settlePage(page, { fonts: false, layoutStable: false });
116168
+ const vpPage = page;
116169
+ await resolveDeferredContent(vpPage, () => settlePage(vpPage, { fonts: false, layoutStable: false }));
115226
116170
  const pageScreenshot = await page.screenshot({ fullPage: true, animations: "disabled", timeout: 15000 }).catch(() => {
115227
116171
  return;
115228
116172
  });
@@ -115292,20 +116236,54 @@ async function captureViewportVariants(browser, url, extraViewports, captured, r
115292
116236
  migrated.viewportVariants = variants;
115293
116237
  }
115294
116238
  }
115295
- async function resolvePages2(page, baseUrl, tokens, homeHtml, platform) {
116239
+ async function resolvePages2(page, baseUrl, tokens, homeHtml, platform, profile, profileEvidence) {
115296
116240
  const out = [];
115297
- const plp = pickPlpFromHomeHtml(homeHtml, baseUrl);
116241
+ const auto = {};
116242
+ const origin = new URL(baseUrl).origin;
116243
+ const notFound = (token, tried, reason) => {
116244
+ auto.notFound = [...auto.notFound ?? [], { token, tried, reason }];
116245
+ console.warn(chalk31.yellow(` ⚠ ${token}: ${reason}${tried.length ? ` (tried ${tried.join(", ")})` : ""}`));
116246
+ };
116247
+ const usable = async (url) => autoUrlRejection(url, origin) ?? (await browserFetchText(page, url) === null ? "did not answer 2xx" : null);
116248
+ const withKind = (path, url) => {
116249
+ const d = decidePageKind(pathOf6(url), profile, profileEvidence);
116250
+ return { path, url, kind: d.kind, kindEvidence: d.evidence };
116251
+ };
116252
+ const autoTokens = tokens.filter((t) => t === "category-auto" || t === "pdp-auto");
116253
+ const skipAuto = profile === "content" && autoTokens.length > 0;
116254
+ if (skipAuto) {
116255
+ auto.skipped = {
116256
+ tokens: [...new Set(autoTokens)],
116257
+ reason: `site profile is content (${profileEvidence}); there is no category or product page to auto-detect`
116258
+ };
116259
+ console.log(chalk31.dim(` ${auto.skipped.tokens.join(", ")}: skipped — ${auto.skipped.reason}`));
116260
+ }
116261
+ const plpCandidate = skipAuto ? null : pickPlpFromHomeHtml(homeHtml, baseUrl);
116262
+ let plp = null;
116263
+ let plpTried = [];
116264
+ if (plpCandidate) {
116265
+ plpTried = [plpCandidate];
116266
+ const why = await usable(plpCandidate);
116267
+ if (why === null)
116268
+ plp = plpCandidate;
116269
+ else
116270
+ plpTried = [`${plpCandidate} (${why})`];
116271
+ }
115298
116272
  for (const token of tokens) {
115299
116273
  if (token === "category-auto") {
116274
+ if (skipAuto)
116275
+ continue;
115300
116276
  if (plp)
115301
- out.push({ path: token, url: plp, kind: "plp" });
116277
+ out.push(withKind(token, plp));
115302
116278
  else
115303
- console.warn(chalk31.yellow(" ⚠ category-auto: nenhuma PLP descoberta na home"));
116279
+ notFound(token, plpTried, "no valid category page found on the home page");
115304
116280
  continue;
115305
116281
  }
115306
116282
  if (token === "pdp-auto") {
116283
+ if (skipAuto)
116284
+ continue;
115307
116285
  if (!plp) {
115308
- console.warn(chalk31.yellow(" ⚠ pdp-auto: sem PLP pra derivar PDP"));
116286
+ notFound(token, [], "no category page to derive a product page from");
115309
116287
  continue;
115310
116288
  }
115311
116289
  let html = null;
@@ -115319,18 +116297,31 @@ async function resolvePages2(page, baseUrl, tokens, homeHtml, platform) {
115319
116297
  html = await browserFetchText(page, plp);
115320
116298
  }
115321
116299
  const pdp = html ? firstProductHref(html, plp, platform) : null;
115322
- if (pdp)
115323
- out.push({ path: token, url: pdp, kind: "pdp" });
116300
+ const why = pdp ? await usable(pdp) : "no product link on the category page";
116301
+ if (pdp && why === null)
116302
+ out.push({
116303
+ path: token,
116304
+ url: pdp,
116305
+ kind: "pdp",
116306
+ kindEvidence: "first product link on the PLP found by pdp-auto"
116307
+ });
115324
116308
  else
115325
- console.warn(chalk31.yellow(" ⚠ pdp-auto: nenhum produto encontrado na PLP"));
116309
+ notFound(token, pdp ? [`${pdp} (${why})`] : [plp], why ?? "no product found");
115326
116310
  continue;
115327
116311
  }
115328
116312
  try {
115329
116313
  const url = new URL(token, baseUrl).toString();
115330
- out.push({ path: token, url, kind: kindOf(url) });
116314
+ out.push(withKind(token, url));
115331
116315
  } catch {}
115332
116316
  }
115333
- return out;
116317
+ return { pages: out, auto };
116318
+ }
116319
+ function pathOf6(url) {
116320
+ try {
116321
+ return new URL(url).pathname.replace(/\/+$/, "") || "/";
116322
+ } catch {
116323
+ return url;
116324
+ }
115334
116325
  }
115335
116326
  async function discoverSitemapUrls(page, baseUrl) {
115336
116327
  try {
@@ -115430,6 +116421,11 @@ function printResults4(runDir, bundle) {
115430
116421
  console.log(chalk31.dim(` vtex io: ${bundle.vtex.blocks.length} blocks (${withContent} with CMS content, ${contentImgs} content images local) · ${mapped}/${bundle.vtex.map.length} mapped`));
115431
116422
  }
115432
116423
  console.log(chalk31.dim(` pages: ${bundle.pages.map((p) => p.kind).join(", ") || "—"}`));
116424
+ if (bundle.discovery)
116425
+ console.log(chalk31.dim(` found by: ${bundle.discovery.pages}${bundle.discovery.siteProfile ? ` · profile ${bundle.discovery.siteProfile}` : ""}`));
116426
+ const partial = bundle.pages.filter((p) => p.deferral && !p.deferral.complete);
116427
+ if (partial.length)
116428
+ console.log(chalk31.yellow(` ⚠ PARTIAL inventory on ${partial.length} page(s): ${partial.map((p) => `${p.path} (${p.deferral.unresolved.length} unresolved)`).join(", ")} — see migration-plan.json pages[].deferral`));
115433
116429
  console.log(chalk31.dim(` out: ${runDir}`));
115434
116430
  console.log("");
115435
116431
  console.log(chalk31.bold(` ${bundle.components.length} component(s):`));
@@ -116653,6 +117649,65 @@ function saveCheckContext(dir, ctx, meta) {
116653
117649
  RecordedContext.parse(recorded);
116654
117650
  writeFileSync32(join44(dir, CONTEXT_FILE), JSON.stringify(recorded), "utf8");
116655
117651
  }
117652
+ function loadCheckContext(dir) {
117653
+ const file = join44(dir, CONTEXT_FILE);
117654
+ if (!existsSync29(file))
117655
+ throw new Error(`${dir} holds no recording (${CONTEXT_FILE} not found)`);
117656
+ const raw = JSON.parse(readFileSync38(file, "utf8"));
117657
+ if (raw.formatVersion !== FORMAT_VERSION) {
117658
+ throw new Error(`${file}: unsupported recording formatVersion ${JSON.stringify(raw.formatVersion)} (this parity reads ${FORMAT_VERSION})`);
117659
+ }
117660
+ const r = RecordedContext.parse(raw);
117661
+ const root = resolve20(dir);
117662
+ const abs = (p) => p === "" || isAbsolute(p) ? p : join44(root, p);
117663
+ const absOpt = (p) => p ? abs(p) : p;
117664
+ const page = (c) => ({ ...c, screenshotPath: abs(c.screenshotPath) });
117665
+ const step = (s) => ({
117666
+ ...s,
117667
+ screenshotPath: abs(s.screenshotPath),
117668
+ ...s.screenshotBeforePath !== undefined ? { screenshotBeforePath: abs(s.screenshotBeforePath) } : {}
117669
+ });
117670
+ const flow = (f) => ({
117671
+ ...f,
117672
+ pages: f.pages.map(page),
117673
+ ...f.steps ? { steps: f.steps.map(step) } : {}
117674
+ });
117675
+ const fetchFile = join44(dir, FETCH_FILE);
117676
+ if (!existsSync29(fetchFile)) {
117677
+ throw new Error(`${dir} is an incomplete recording: ${FETCH_FILE} is missing (the run stopped during checks?)`);
117678
+ }
117679
+ const fetchLog = FetchLogSchema.parse(JSON.parse(readFileSync38(fetchFile, "utf8")));
117680
+ return {
117681
+ ctx: {
117682
+ prodPages: r.prodPages.map(page),
117683
+ candPages: r.candPages.map(page),
117684
+ prodFlows: r.prodFlows.map(flow),
117685
+ candFlows: r.candFlows.map(flow),
117686
+ rc: r.rc,
117687
+ ignore: r.ignore,
117688
+ viewports: r.viewports,
117689
+ ...r.candIsProduction !== undefined ? { candIsProduction: r.candIsProduction } : {},
117690
+ visualProbes: r.visualProbes ? new Map(r.visualProbes.map(([k, v]) => [
117691
+ abs(k),
117692
+ {
117693
+ ...v,
117694
+ side: { ...v.side, screenshot: absOpt(v.side.screenshot) },
117695
+ repeatScreenshot: absOpt(v.repeatScreenshot)
117696
+ }
117697
+ ])) : undefined
117698
+ },
117699
+ meta: {
117700
+ prodUrl: r.prodUrl,
117701
+ candUrl: r.candUrl,
117702
+ recordedAt: r.recordedAt,
117703
+ ...r.checkNames ? { checkNames: r.checkNames } : {},
117704
+ ...r.parityVersion ? { parityVersion: r.parityVersion } : {}
117705
+ },
117706
+ fetchLog,
117707
+ missingFiles: r.missingFiles,
117708
+ omittedArtifacts: r.omittedArtifacts
117709
+ };
117710
+ }
116656
117711
  var FetchEntry = z4.object({
116657
117712
  method: z4.string(),
116658
117713
  url: z4.string(),
@@ -116732,6 +117787,61 @@ function saveFetchLog(dir, log) {
116732
117787
  writeFileSync32(join44(dir, FETCH_FILE), JSON.stringify(log), "utf8");
116733
117788
  }
116734
117789
 
117790
+ class UnrecordedFetchError extends Error {
117791
+ name = "UnrecordedFetchError";
117792
+ constructor(method, url) {
117793
+ super(`replay: ${method} ${url} was not made during the recorded run`);
117794
+ }
117795
+ }
117796
+ function createReplayFetch(log) {
117797
+ const queues = new Map;
117798
+ for (const e of log.entries) {
117799
+ const k = `${e.method} ${e.url}`;
117800
+ const q = queues.get(k);
117801
+ if (q)
117802
+ q.push(e);
117803
+ else
117804
+ queues.set(k, [e]);
117805
+ }
117806
+ const cursor = new Map;
117807
+ return async (input, init) => {
117808
+ const { method, url } = reqParts(input, init);
117809
+ const k = `${method} ${url}`;
117810
+ const q = queues.get(k);
117811
+ if (!q)
117812
+ throw new UnrecordedFetchError(method, url);
117813
+ const i = cursor.get(k) ?? 0;
117814
+ cursor.set(k, Math.min(i + 1, q.length - 1));
117815
+ const e = q[i];
117816
+ if (e.error) {
117817
+ const err = e.error.name === "TypeError" ? new TypeError(e.error.message) : new Error(e.error.message);
117818
+ err.name = e.error.name;
117819
+ if (e.error.cause)
117820
+ err.cause = { code: e.error.cause };
117821
+ throw err;
117822
+ }
117823
+ const status = e.status ?? 200;
117824
+ let body = null;
117825
+ if (e.bodyError) {
117826
+ const msg = e.bodyError;
117827
+ body = new ReadableStream({ start: (c) => c.error(new Error(msg)) });
117828
+ } else if (e.body && !NULL_BODY.has(status)) {
117829
+ body = "text" in e.body ? e.body.text : Buffer.from(e.body.base64, "base64");
117830
+ }
117831
+ const res = new Response(body, { status, statusText: e.statusText, headers: e.headers });
117832
+ Object.defineProperty(res, "url", { value: e.finalUrl ?? url });
117833
+ Object.defineProperty(res, "redirected", { value: e.redirected ?? false });
117834
+ return res;
117835
+ };
117836
+ }
117837
+ function replayFetch(log) {
117838
+ const orig = globalThis.fetch;
117839
+ globalThis.fetch = createReplayFetch(log);
117840
+ return () => {
117841
+ globalThis.fetch = orig;
117842
+ };
117843
+ }
117844
+
116735
117845
  // src/diff/score-band.ts
116736
117846
  var uniq = (xs) => [...new Set(xs)];
116737
117847
  function computeScoreBand(current, priors, opts = {}) {
@@ -116826,6 +117936,34 @@ function readLine2(prompt) {
116826
117936
  });
116827
117937
  }
116828
117938
 
117939
+ // src/engine/score-run.ts
117940
+ function scoreChecks(checks, ignore, pages) {
117941
+ const allIssues = checks.flatMap((c) => c.issues);
117942
+ const acceptance = applyAcceptedFindings(checks, ignore.expectedDivergences ?? []);
117943
+ const remainingChecks = withoutAccepted(checks);
117944
+ const remainingIssues = remainingChecks.flatMap((c) => c.issues);
117945
+ const pagesAnalyzed = pairCaptures(pages.prodPages, pages.candPages).pairs.length;
117946
+ const scoreOf = (c, i) => {
117947
+ const mv = computeModuleVerdicts(c, i);
117948
+ return {
117949
+ moduleVerdicts: mv,
117950
+ verdict: mv.length > 0 ? computeCompositeVerdict(mv, c, i) : computeVerdict(c, i, { pagesAnalyzed })
117951
+ };
117952
+ };
117953
+ const scored = scoreOf(remainingChecks, remainingIssues);
117954
+ if (acceptance.accepted > 0)
117955
+ scored.verdict.rawScore = scoreOf(checks, allIssues).verdict.score;
117956
+ return {
117957
+ allIssues,
117958
+ acceptance,
117959
+ remainingChecks,
117960
+ remainingIssues,
117961
+ pagesAnalyzed,
117962
+ moduleVerdicts: scored.moduleVerdicts,
117963
+ verdict: scored.verdict
117964
+ };
117965
+ }
117966
+
116829
117967
  // src/commands/run.ts
116830
117968
  init_client();
116831
117969
 
@@ -117072,6 +118210,18 @@ function detectRunCaveats(input) {
117072
118210
  detail: "cand está noutro host e marca noindex em todas as páginas que prod indexa: é o comportamento de um host de staging (deco marca noindex fora do domínio de produção). noindex/nofollow, terceiros ausentes e requests a terceiros que falham só em cand ficaram inconclusivos. Reconfira depois da troca de domínio, ou rode com --cand-is-production se cand já é o domínio final."
117073
118211
  });
117074
118212
  }
118213
+ for (const side of ["prod", "cand"]) {
118214
+ const keys = uncapturedKeys(side === "prod" ? input.prodPages : input.candPages);
118215
+ if (keys.length === 0)
118216
+ continue;
118217
+ const shown = `${keys.slice(0, 5).join(", ")}${keys.length > 5 ? `, … +${keys.length - 5}` : ""}`;
118218
+ out.push({
118219
+ id: `${side}-pages-not-captured`,
118220
+ level: "warn",
118221
+ summary: `${keys.length} ${side === "cand" ? "candidate" : "prod"} page(s) were not captured: ${shown}`,
118222
+ detail: `These captures recorded no HTTP answer (status 0: timeout or refused connection), so they were measured by nothing — not compared, and not a status divergence. Page-pair checks withheld them as inconclusive; the score does not include them, so it is optimistic by exactly these pages. Re-run against a warm server (a cold dev server is the usual cause). All: ${keys.join(", ")}.`
118223
+ });
118224
+ }
117075
118225
  const mismatched = pairedPathMismatches(input.prodPages, input.candPages);
117076
118226
  if (mismatched.length > 0) {
117077
118227
  out.push({
@@ -117130,6 +118280,12 @@ function detectRunCaveats(input) {
117130
118280
  }
117131
118281
  return out;
117132
118282
  }
118283
+ function uncapturedKeys(pages) {
118284
+ const last = new Map;
118285
+ for (const p of pages)
118286
+ last.set(captureKey(p), p);
118287
+ return [...last].filter(([, p]) => isUncaptured(p)).map(([k]) => k);
118288
+ }
117133
118289
  function pairedPathMismatches(prodPages, candPages) {
117134
118290
  const out = [];
117135
118291
  for (const cand of candPages) {
@@ -117138,14 +118294,14 @@ function pairedPathMismatches(prodPages, candPages) {
117138
118294
  const prod = prodPages.find((p) => p.pairKey === cand.pairKey);
117139
118295
  if (!prod)
117140
118296
  continue;
117141
- const prodPath = pathOf6(prod.url);
117142
- const candPath = pathOf6(cand.url);
118297
+ const prodPath = pathOf7(prod.url);
118298
+ const candPath = pathOf7(cand.url);
117143
118299
  if (prodPath && candPath && prodPath !== candPath)
117144
118300
  out.push(`${prodPath} → ${candPath}`);
117145
118301
  }
117146
118302
  return [...new Set(out)];
117147
118303
  }
117148
- function pathOf6(raw) {
118304
+ function pathOf7(raw) {
117149
118305
  try {
117150
118306
  return new URL(raw).pathname;
117151
118307
  } catch {
@@ -118139,26 +119295,17 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
118139
119295
  for (const c of checks)
118140
119296
  jsonl.write(checkToJsonl(runId, c));
118141
119297
  }
118142
- const allIssues = checks.flatMap((c) => c.issues);
118143
- const acceptance = applyAcceptedFindings(checks, ignore.expectedDivergences ?? []);
118144
- const remainingChecks = withoutAccepted(checks);
118145
- const remainingIssues = remainingChecks.flatMap((c) => c.issues);
119298
+ const {
119299
+ allIssues,
119300
+ acceptance,
119301
+ remainingIssues,
119302
+ moduleVerdicts,
119303
+ verdict: scored
119304
+ } = scoreChecks(checks, ignore, checkCtx);
118146
119305
  const topIssues = rankTopIssues(remainingIssues);
118147
119306
  currentPhase = "report";
118148
- const pagesAnalyzed = pairCaptures(checkCtx.prodPages, checkCtx.candPages).pairs.length;
118149
- const scoreOf = (c, i) => {
118150
- const mv = computeModuleVerdicts(c, i);
118151
- return {
118152
- moduleVerdicts: mv,
118153
- verdict: mv.length > 0 ? computeCompositeVerdict(mv, c, i) : computeVerdict(c, i, { pagesAnalyzed })
118154
- };
118155
- };
118156
- const scored = scoreOf(remainingChecks, remainingIssues);
118157
- const { moduleVerdicts } = scored;
118158
- if (acceptance.accepted > 0)
118159
- scored.verdict.rawScore = scoreOf(checks, allIssues).verdict.score;
118160
119307
  const pagePairs = explicitPaths ? measurePagePairs(explicitPaths, viewports, { prod: opts.prod, cand: opts.cand }, allPageCaptures) : undefined;
118161
- const verdict = verdictForPagePairs(scored.verdict, pagePairs);
119308
+ const verdict = verdictForPagePairs(scored, pagePairs);
118162
119309
  if (moduleDropReason) {
118163
119310
  verdict.modulesSkipped = [{ module: "e2e", reason: moduleDropReason }];
118164
119311
  }
@@ -118645,7 +119792,8 @@ function printSummary8(run, reportWhere, meta) {
118645
119792
  const parityIcon = vd.parityOk ? chalk34.green("✔") : chalk34.red("✖");
118646
119793
  const parityLabel = vd.parityOk ? chalk34.green("OK") : chalk34.red("DIFFS");
118647
119794
  const cacheNote = vd.pagesFromCache > 0 ? chalk34.dim(` · ${vd.pagesFromCache} cached`) : "";
118648
- console.log(` visual: ${parityIcon} parityOk=${parityLabel} · ${vd.pagesChecked} pages · ${chalk34.red(vd.pagesWithDiffs)} diffs · ${chalk34.green(vd.pagesPassed)} pass${cacheNote}`);
119795
+ const notCompared = vd.pagesFailed > 0 ? ` · ${chalk34.yellow(notComparedText(vd))}` : "";
119796
+ console.log(` visual: ${parityIcon} parityOk=${parityLabel} · ${vd.pagesChecked} pages · ${chalk34.red(vd.pagesWithDiffs)} diffs · ${chalk34.green(vd.pagesPassed)} pass${notCompared}${cacheNote}`);
118649
119797
  }
118650
119798
  if (run.topIssues.length > 0) {
118651
119799
  console.log("");
@@ -121090,7 +122238,7 @@ function extractVitalsSlice(run) {
121090
122238
  for (const p of fc.pages) {
121091
122239
  if (!p.vitals)
121092
122240
  continue;
121093
- const k = `${p.side}::${p.viewport}::${pathOf7(p.url)}`;
122241
+ const k = `${p.side}::${p.viewport}::${pathOf8(p.url)}`;
121094
122242
  out[k] = p.vitalsFullPage ? { ...p.vitals, fullPage: p.vitalsFullPage } : p.vitals;
121095
122243
  }
121096
122244
  }
@@ -121129,7 +122277,7 @@ function extractPagesSlice(run) {
121129
122277
  }
121130
122278
  return rows;
121131
122279
  }
121132
- function pathOf7(url) {
122280
+ function pathOf8(url) {
121133
122281
  try {
121134
122282
  return new URL(url).pathname || "/";
121135
122283
  } catch {
@@ -121517,24 +122665,229 @@ async function rerenderCommand(opts) {
121517
122665
  }
121518
122666
  }
121519
122667
 
121520
- // src/commands/serve.ts
121521
- import { existsSync as existsSync38 } from "node:fs";
122668
+ // src/commands/replay.ts
121522
122669
  import chalk41 from "chalk";
122670
+
122671
+ // src/replay/outcome.ts
122672
+ import { existsSync as existsSync38, readFileSync as readFileSync45, writeFileSync as writeFileSync38 } from "node:fs";
122673
+ import { join as join52 } from "node:path";
122674
+ import { z as z6 } from "zod";
122675
+ var EXPECTED_FILE = "expected.json";
122676
+ var ReplayOutcome = z6.object({
122677
+ formatVersion: z6.literal(1),
122678
+ parityVersion: z6.string(),
122679
+ generatedAt: z6.string(),
122680
+ checks: z6.record(z6.string(), z6.string()),
122681
+ issues: z6.array(z6.string()),
122682
+ verdict: z6.object({ status: z6.string(), score: z6.number() }),
122683
+ notes: z6.string().optional()
122684
+ });
122685
+ function buildOutcome(checks, issues, verdict, parityVersion) {
122686
+ const byName = Object.fromEntries([...checks].sort((a, b) => a.name.localeCompare(b.name)).map((c) => [c.name, c.status]));
122687
+ return {
122688
+ formatVersion: 1,
122689
+ parityVersion,
122690
+ generatedAt: new Date().toISOString(),
122691
+ checks: byName,
122692
+ issues: [...new Set(issues.map((i) => i.id))].sort(),
122693
+ verdict: { status: verdict.status, score: verdict.score }
122694
+ };
122695
+ }
122696
+ function readExpected(dir) {
122697
+ const file = join52(dir, EXPECTED_FILE);
122698
+ if (!existsSync38(file))
122699
+ throw new Error(`${file} not found (record the expectation with --update-expected)`);
122700
+ return ReplayOutcome.parse(JSON.parse(readFileSync45(file, "utf8")));
122701
+ }
122702
+ function writeExpected(dir, outcome) {
122703
+ const file = join52(dir, EXPECTED_FILE);
122704
+ const notes = existsSync38(file) ? readExpected(dir).notes : undefined;
122705
+ const { notes: _drop, ...rest } = outcome;
122706
+ writeFileSync38(file, `${JSON.stringify({ ...rest, ...notes !== undefined ? { notes } : {} }, null, 2)}
122707
+ `, "utf8");
122708
+ }
122709
+ function diffOutcome(expected, actual) {
122710
+ const names = [
122711
+ ...new Set([...Object.keys(expected.checks), ...Object.keys(actual.checks)])
122712
+ ].sort();
122713
+ const statusChanged = names.filter((n) => expected.checks[n] !== actual.checks[n]).map((check) => ({
122714
+ check,
122715
+ expected: expected.checks[check] ?? "(absent)",
122716
+ actual: actual.checks[check] ?? "(absent)"
122717
+ }));
122718
+ const exp = new Set(expected.issues);
122719
+ const act = new Set(actual.issues);
122720
+ return {
122721
+ statusChanged,
122722
+ issuesAdded: [...act].filter((i) => !exp.has(i)).sort(),
122723
+ issuesRemoved: [...exp].filter((i) => !act.has(i)).sort(),
122724
+ ...expected.verdict.status !== actual.verdict.status ? { verdictChanged: { expected: expected.verdict.status, actual: actual.verdict.status } } : {},
122725
+ ...expected.verdict.score !== actual.verdict.score ? { scoreChanged: { expected: expected.verdict.score, actual: actual.verdict.score } } : {}
122726
+ };
122727
+ }
122728
+ function outcomeMatches(d) {
122729
+ return d.statusChanged.length === 0 && d.issuesAdded.length === 0 && d.issuesRemoved.length === 0 && !d.verdictChanged;
122730
+ }
122731
+ function formatDiff(d) {
122732
+ return [
122733
+ ...d.statusChanged.map((s) => `check ${s.check}: ${s.expected} -> ${s.actual}`),
122734
+ ...d.issuesAdded.map((i) => `issue added: ${i}`),
122735
+ ...d.issuesRemoved.map((i) => `issue removed: ${i}`),
122736
+ ...d.verdictChanged ? [`verdict: ${d.verdictChanged.expected} -> ${d.verdictChanged.actual}`] : [],
122737
+ ...d.scoreChanged ? [`score (informational): ${d.scoreChanged.expected} -> ${d.scoreChanged.actual}`] : []
122738
+ ];
122739
+ }
122740
+
122741
+ // src/replay/replay.ts
122742
+ import { mkdirSync as mkdirSync24, mkdtempSync as mkdtempSync2, rmSync as rmSync6 } from "node:fs";
122743
+ import { tmpdir as tmpdir3 } from "node:os";
122744
+ import { join as join53 } from "node:path";
122745
+ class NothingToJudgeError extends Error {
122746
+ name = "NothingToJudgeError";
122747
+ }
122748
+ async function replayRecording(dir, opts = {}) {
122749
+ const rec = loadCheckContext(dir);
122750
+ const pagePairs = pairCaptures(rec.ctx.prodPages, rec.ctx.candPages).pairs.length;
122751
+ const flows = rec.ctx.prodFlows.length + rec.ctx.candFlows.length;
122752
+ if (pagePairs === 0 && flows === 0) {
122753
+ throw new NothingToJudgeError(`nothing was compared: ${dir} holds no page pairs and no flows`);
122754
+ }
122755
+ const ownsOutDir = opts.outDir === undefined;
122756
+ const outDir = opts.outDir ?? mkdtempSync2(join53(tmpdir3(), "parity-replay-"));
122757
+ mkdirSync24(outDir, { recursive: true });
122758
+ const ctx = { ...rec.ctx, outDir };
122759
+ const unrecorded = new Set;
122760
+ const restore = replayFetch(rec.fetchLog);
122761
+ const replayed = globalThis.fetch;
122762
+ globalThis.fetch = async (input, init) => {
122763
+ try {
122764
+ return await replayed(input, init);
122765
+ } catch (err) {
122766
+ if (err instanceof UnrecordedFetchError)
122767
+ unrecorded.add(err.message.replace(/^replay: /, ""));
122768
+ throw err;
122769
+ }
122770
+ };
122771
+ let checks;
122772
+ try {
122773
+ checks = await runAllChecks(ctx, undefined, rec.meta.checkNames ? new Set(rec.meta.checkNames) : undefined);
122774
+ } finally {
122775
+ restore();
122776
+ if (ownsOutDir)
122777
+ rmSync6(outDir, { recursive: true, force: true });
122778
+ }
122779
+ if (checks.length === 0) {
122780
+ throw new NothingToJudgeError(`nothing was compared: no check ran (recorded selection: ${rec.meta.checkNames?.join(", ") ?? "all"})`);
122781
+ }
122782
+ if (unrecorded.size === 0 && checks.every((c) => c.status === "skipped")) {
122783
+ throw new NothingToJudgeError(`nothing was compared: every check was skipped (${checks.length} checks)`);
122784
+ }
122785
+ const scored = scoreChecks(checks, ctx.ignore, ctx);
122786
+ return {
122787
+ checks,
122788
+ issues: scored.allIssues,
122789
+ verdict: scored.verdict,
122790
+ meta: rec.meta,
122791
+ missingFiles: rec.missingFiles,
122792
+ unrecordedFetches: [...unrecorded].sort(),
122793
+ incomplete: unrecorded.size > 0,
122794
+ pagePairs,
122795
+ outcome: buildOutcome(checks, scored.allIssues, scored.verdict, getPackageVersion())
122796
+ };
122797
+ }
122798
+
122799
+ // src/commands/replay.ts
122800
+ async function replayCommand(dir, opts) {
122801
+ const say = (s) => opts.json ? console.error(s) : console.log(s);
122802
+ if (opts.expect && opts.updateExpected) {
122803
+ console.error("replay: --expect and --update-expected are mutually exclusive");
122804
+ return 2;
122805
+ }
122806
+ let r;
122807
+ try {
122808
+ if (opts.expect)
122809
+ readExpected(dir);
122810
+ r = await replayRecording(dir, { outDir: opts.out });
122811
+ } catch (err) {
122812
+ console.error(chalk41.red(`replay: ${err.message}`));
122813
+ return 2;
122814
+ }
122815
+ if (r.incomplete) {
122816
+ if (opts.json) {
122817
+ console.log(JSON.stringify({ incomplete: true, unrecordedFetches: r.unrecordedFetches, meta: r.meta }, null, 2));
122818
+ }
122819
+ console.error(chalk41.red("replay: INCOMPLETE - the recording predates a request the checks now make; re-record it. Requests not in the recording:"));
122820
+ for (const u of r.unrecordedFetches)
122821
+ console.error(chalk41.red(` ${u}`));
122822
+ return 2;
122823
+ }
122824
+ let diffLines;
122825
+ let code = 0;
122826
+ if (opts.updateExpected) {
122827
+ try {
122828
+ writeExpected(dir, r.outcome);
122829
+ } catch (err) {
122830
+ console.error(chalk41.red(`replay: ${err.message}`));
122831
+ return 2;
122832
+ }
122833
+ } else if (opts.expect) {
122834
+ const d = diffOutcome(readExpected(dir), r.outcome);
122835
+ diffLines = formatDiff(d);
122836
+ if (!outcomeMatches(d))
122837
+ code = 1;
122838
+ }
122839
+ if (opts.json) {
122840
+ console.log(JSON.stringify({
122841
+ meta: r.meta,
122842
+ outcome: r.outcome,
122843
+ verdict: r.verdict,
122844
+ pagePairs: r.pagePairs,
122845
+ missingFiles: r.missingFiles,
122846
+ ...diffLines ? { matches: code === 0, diff: diffLines } : {}
122847
+ }, null, 2));
122848
+ return code;
122849
+ }
122850
+ const v = r.verdict;
122851
+ const mark = v.status === "inconclusive" ? chalk41.dim("○") : v.status === "pass" ? chalk41.green("✔") : v.status === "warn" ? chalk41.yellow("⚠") : chalk41.red("✖");
122852
+ const score = v.status === "inconclusive" ? "—" : v.score;
122853
+ say(` ${mark} parity ${v.status.toUpperCase()} · score ${score}/100 · ${r.pagePairs} page pairs`);
122854
+ say(` checks: ${v.checksPassed} pass · ${v.checksFailed} fail · ${v.checksSkipped} skipped`);
122855
+ say(` issues: ${v.critical} critical · ${v.high} high · ${v.medium} medium · ${v.low} low`);
122856
+ say(chalk41.dim(` recorded ${r.meta.recordedAt} with parity ${r.meta.parityVersion ?? "(unknown version)"}`));
122857
+ if (r.missingFiles.length > 0) {
122858
+ say(chalk41.yellow(` ${r.missingFiles.length} referenced file(s) were missing when this was recorded; checks that read them judged less than a full run`));
122859
+ }
122860
+ if (opts.updateExpected)
122861
+ say(chalk41.dim(" expected.json written"));
122862
+ if (diffLines) {
122863
+ if (code === 0)
122864
+ say(chalk41.green(" matches expected.json"));
122865
+ else
122866
+ say(chalk41.red(" differs from expected.json:"));
122867
+ for (const l of diffLines)
122868
+ say(` ${l}`);
122869
+ }
122870
+ return code;
122871
+ }
122872
+
122873
+ // src/commands/serve.ts
122874
+ import { existsSync as existsSync39 } from "node:fs";
122875
+ import chalk42 from "chalk";
121523
122876
  async function serveRunAndBlock(runDir, opts = {}) {
121524
122877
  let handle;
121525
122878
  try {
121526
122879
  handle = await startProxyServer(runDir, { port: opts.port });
121527
122880
  } catch (err) {
121528
- console.error(chalk41.red(` ✖ Falha ao iniciar servidor: ${err.message}`));
122881
+ console.error(chalk42.red(` ✖ Falha ao iniciar servidor: ${err.message}`));
121529
122882
  return 2;
121530
122883
  }
121531
122884
  const label = opts.label ?? "parity serve";
121532
122885
  console.log("");
121533
- console.log(chalk41.bold(` ${label}`));
121534
- console.log(` ${chalk41.green("●")} ${handle.url}`);
121535
- console.log(chalk41.dim(` Servindo: ${runDir}`));
121536
- console.log(chalk41.dim(` Proxy de iframes: ${handle.url}proxy?url=<encoded>`));
121537
- console.log(chalk41.dim(` Ctrl+C pra parar (2x pra forçar saída).
122886
+ console.log(chalk42.bold(` ${label}`));
122887
+ console.log(` ${chalk42.green("●")} ${handle.url}`);
122888
+ console.log(chalk42.dim(` Servindo: ${runDir}`));
122889
+ console.log(chalk42.dim(` Proxy de iframes: ${handle.url}proxy?url=<encoded>`));
122890
+ console.log(chalk42.dim(` Ctrl+C pra parar (2x pra forçar saída).
121538
122891
  `));
121539
122892
  if (opts.open !== false) {
121540
122893
  const { default: open } = await import("open");
@@ -121566,14 +122919,14 @@ async function serveRunAndBlock(runDir, opts = {}) {
121566
122919
  }
121567
122920
  async function serveCommand(runId, opts) {
121568
122921
  const paths = getRunPaths(opts.output, runId);
121569
- if (!existsSync38(paths.runDir)) {
121570
- console.error(chalk41.red(`✖ Run não encontrado: ${runId} (em ${opts.output})`));
122922
+ if (!existsSync39(paths.runDir)) {
122923
+ console.error(chalk42.red(`✖ Run não encontrado: ${runId} (em ${opts.output})`));
121571
122924
  return 1;
121572
122925
  }
121573
122926
  try {
121574
122927
  ensureReportHtml(paths);
121575
122928
  } catch (err) {
121576
- console.error(chalk41.red(`✖ não foi possível gerar report.html: ${err.message}`));
122929
+ console.error(chalk42.red(`✖ não foi possível gerar report.html: ${err.message}`));
121577
122930
  return 1;
121578
122931
  }
121579
122932
  return serveRunAndBlock(paths.runDir, {
@@ -121584,7 +122937,7 @@ async function serveCommand(runId, opts) {
121584
122937
  }
121585
122938
 
121586
122939
  // src/commands/states.ts
121587
- import chalk42 from "chalk";
122940
+ import chalk43 from "chalk";
121588
122941
  var ROOT_ATTR = "data-parity-states";
121589
122942
  var rootSelector = (i) => `[${ROOT_ATTR}="${i}"]`;
121590
122943
  function resolveStateRoots(args) {
@@ -121893,7 +123246,7 @@ function statesVerdict(counts) {
121893
123246
  async function statesCommand(opts) {
121894
123247
  const viewport = parseViewport(opts.viewport);
121895
123248
  if (!viewport) {
121896
- console.error(chalk42.red(`--viewport inválido: ${opts.viewport}`));
123249
+ console.error(chalk43.red(`--viewport inválido: ${opts.viewport}`));
121897
123250
  return 2;
121898
123251
  }
121899
123252
  const waitMs = Number.parseInt(opts.wait, 10) || 0;
@@ -121903,12 +123256,12 @@ async function statesCommand(opts) {
121903
123256
  const prodSelector = opts.prodSelector?.trim() || opts.selector?.trim();
121904
123257
  const candSelector = opts.candSelector?.trim() || opts.selector?.trim();
121905
123258
  if (!prodSelector || !candSelector) {
121906
- console.error(chalk42.red(" informe --selector (ambos os lados) ou --prod-selector e --cand-selector"));
123259
+ console.error(chalk43.red(" informe --selector (ambos os lados) ou --prod-selector e --cand-selector"));
121907
123260
  return 2;
121908
123261
  }
121909
123262
  const { aliases, note: aliasNote } = resolveAliases(opts.planDir);
121910
123263
  if (aliasNote)
121911
- console.log(chalk42.dim(` ${aliasNote}`));
123264
+ console.log(chalk43.dim(` ${aliasNote}`));
121912
123265
  const browser = await launchBrowser({ headless: true });
121913
123266
  try {
121914
123267
  const [prodSide, candSide] = await Promise.all([
@@ -121933,7 +123286,7 @@ async function statesCommand(opts) {
121933
123286
  ]);
121934
123287
  if (prodSide.baseError || candSide.baseError) {
121935
123288
  const which = prodSide.baseError ? `prod: ${prodSide.baseError}` : `cand: ${candSide.baseError}`;
121936
- console.error(chalk42.red(` não foi possível ler o componente — ${which}`));
123289
+ console.error(chalk43.red(` não foi possível ler o componente — ${which}`));
121937
123290
  return 2;
121938
123291
  }
121939
123292
  for (const [name, side, sel] of [
@@ -121942,13 +123295,13 @@ async function statesCommand(opts) {
121942
123295
  ]) {
121943
123296
  const r = side.resolution;
121944
123297
  if (r?.kind === "ambiguous") {
121945
- console.error(chalk42.red(` ${name}: ${sel} matches ${r.total} visible elements and none looks like a product card (image + link + price). Narrow it to one:`));
123298
+ console.error(chalk43.red(` ${name}: ${sel} matches ${r.total} visible elements and none looks like a product card (image + link + price). Narrow it to one:`));
121946
123299
  for (const sample of r.samples)
121947
- console.error(chalk42.dim(` ${sample}`));
123300
+ console.error(chalk43.dim(` ${sample}`));
121948
123301
  return 2;
121949
123302
  }
121950
123303
  if (!r || r.kind === "none") {
121951
- console.error(chalk42.red(` ${name}: ${sel} matches no visible element${r?.error ? ` — ${r.error}` : ""}`));
123304
+ console.error(chalk43.red(` ${name}: ${sel} matches no visible element${r?.error ? ` — ${r.error}` : ""}`));
121952
123305
  return 2;
121953
123306
  }
121954
123307
  }
@@ -122030,21 +123383,21 @@ async function statesCommand(opts) {
122030
123383
  ]) {
122031
123384
  const caveat = data.settle && formatSettleCaveat(name, data.settle);
122032
123385
  if (caveat)
122033
- console.log(chalk42.yellow(` ${caveat}`));
123386
+ console.log(chalk43.yellow(` ${caveat}`));
122034
123387
  }
122035
123388
  if (cardMode) {
122036
123389
  console.log("");
122037
- console.log(chalk42.bold(` Product cards: ${pairing.pairs.length} pair(s) — ${pairing.pairs.map(([p, c]) => `prod #${p + 1} ↔ cand #${c + 1}`).join(", ") || "none"}`));
123390
+ console.log(chalk43.bold(` Product cards: ${pairing.pairs.length} pair(s) — ${pairing.pairs.map(([p, c]) => `prod #${p + 1} ↔ cand #${c + 1}`).join(", ") || "none"}`));
122038
123391
  for (const [name, side] of [
122039
123392
  ["prod", prodSide],
122040
123393
  ["cand", candSide]
122041
123394
  ]) {
122042
123395
  const r = side.resolution;
122043
123396
  if (r?.kind === "cards" && r.ignored > 0) {
122044
- console.log(chalk42.dim(` ${name}: ${r.ignored} matched element(s) are not product cards and were ignored`));
123397
+ console.log(chalk43.dim(` ${name}: ${r.ignored} matched element(s) are not product cards and were ignored`));
122045
123398
  }
122046
123399
  if (r?.kind === "single" && !r.isCard) {
122047
- console.log(chalk42.yellow(` ${name}: the selector names one element that is not a product card; it is never paired with a card`));
123400
+ console.log(chalk43.yellow(` ${name}: the selector names one element that is not a product card; it is never paired with a card`));
122048
123401
  }
122049
123402
  }
122050
123403
  const unpaired = [
@@ -122052,65 +123405,65 @@ async function statesCommand(opts) {
122052
123405
  ...pairing.unpairedCand.map((i) => `cand #${i + 1}`)
122053
123406
  ];
122054
123407
  if (unpaired.length)
122055
- console.log(chalk42.dim(` UNPAIRED cards: ${unpaired.join(", ")} — not compared`));
123408
+ console.log(chalk43.dim(` UNPAIRED cards: ${unpaired.join(", ")} — not compared`));
122056
123409
  if (pairing.pairs.length === 0) {
122057
- console.log(chalk42.yellow(" INCONCLUSIVE — no card paired, so nothing was compared."));
123410
+ console.log(chalk43.yellow(" INCONCLUSIVE — no card paired, so nothing was compared."));
122058
123411
  }
122059
123412
  }
122060
123413
  console.log("");
122061
- console.log(chalk42.bold(" Declared motion"));
123414
+ console.log(chalk43.bold(" Declared motion"));
122062
123415
  if (!motion) {
122063
123416
  const err = prodFlat.motionError ?? candFlat.motionError ?? "nothing paired";
122064
- console.log(chalk42.yellow(` não foi possível comparar — ${err}`));
123417
+ console.log(chalk43.yellow(` não foi possível comparar — ${err}`));
122065
123418
  } else {
122066
123419
  for (const line of formatMotionDiff(motion).split(`
122067
123420
  `))
122068
123421
  console.log(` ${line}`);
122069
123422
  }
122070
123423
  console.log("");
122071
- console.log(chalk42.bold(` Hover effects (${prodFlat.effects.length} prod / ${candFlat.effects.length} cand)`));
123424
+ console.log(chalk43.bold(` Hover effects (${prodFlat.effects.length} prod / ${candFlat.effects.length} cand)`));
122072
123425
  const nothing = effects.lost.length === 0 && effects.changed.length === 0 && effects.added.length === 0 && effects.unpaired.length === 0;
122073
123426
  if (nothing && !exercised) {
122074
- console.log(chalk42.yellow(" INCONCLUSIVE — no hover changed anything on either side, so nothing was exercised. Check the selector holds an interactive element."));
123427
+ console.log(chalk43.yellow(" INCONCLUSIVE — no hover changed anything on either side, so nothing was exercised. Check the selector holds an interactive element."));
122075
123428
  } else if (nothing) {
122076
123429
  console.log(" clean — every hover that changes something in prod changes the same in cand");
122077
123430
  }
122078
123431
  for (const e of effects.lost) {
122079
- console.log(chalk42.red(` LOST ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; cand's element was hovered and moved nothing`));
123432
+ console.log(chalk43.red(` LOST ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; cand's element was hovered and moved nothing`));
122080
123433
  }
122081
123434
  for (const { prod, extra, notComparable, onElement } of effects.changed) {
122082
123435
  console.log(` DIFFERS ${prod.target}${prod.label ? ` (${prod.label})` : ""}`);
122083
123436
  if (onElement.length) {
122084
- console.log(chalk42.yellow(` prod also moves [${onElement.join(", ")}] on the element itself`));
123437
+ console.log(chalk43.yellow(` prod also moves [${onElement.join(", ")}] on the element itself`));
122085
123438
  }
122086
123439
  if (extra.length)
122087
123440
  console.log(` cand also moves [${extra.join(", ")}]`);
122088
123441
  if (notComparable.length) {
122089
- console.log(chalk42.dim(` not comparable: [${notComparable.join(", ")}] — prod's hover renumbered ${prod.renumberedNodes} of the changed paths, so these were read on elements that are not the same ones before and after. Bench the component, or pick a selector whose subtree the hover does not restructure.`));
123442
+ console.log(chalk43.dim(` not comparable: [${notComparable.join(", ")}] — prod's hover renumbered ${prod.renumberedNodes} of the changed paths, so these were read on elements that are not the same ones before and after. Bench the component, or pick a selector whose subtree the hover does not restructure.`));
122090
123443
  }
122091
123444
  if (onElement.length === 0 && extra.length === 0) {
122092
- console.log(chalk42.dim(" nothing comparable differs."));
123445
+ console.log(chalk43.dim(" nothing comparable differs."));
122093
123446
  }
122094
123447
  }
122095
123448
  for (const e of effects.unpaired) {
122096
- console.log(chalk42.dim(` UNPAIRED ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; no matching element found on the cand side (not a defect — the port may have changed the element, or it is outside --selector)`));
123449
+ console.log(chalk43.dim(` UNPAIRED ${e.target}${e.label ? ` (${e.label})` : ""} — prod moves [${e.properties.join(", ")}]; no matching element found on the cand side (not a defect — the port may have changed the element, or it is outside --selector)`));
122097
123450
  }
122098
123451
  for (const e of effects.added) {
122099
123452
  console.log(` ADDED ${e.target} — cand moves [${e.properties.join(", ")}]; prod does not`);
122100
123453
  }
122101
123454
  if (effects.unpaired.length > 0 && effects.lost.length === 0 && effects.changed.length === 0) {
122102
123455
  console.log("");
122103
- console.log(chalk42.yellow(` ${effects.unpaired.length} prod effect(s) had no counterpart and NOTHING paired. That is a pairing failure, not a set of defects — check --selector contains the same component on both sides, and that ported roots carry data-section.`));
123456
+ console.log(chalk43.yellow(` ${effects.unpaired.length} prod effect(s) had no counterpart and NOTHING paired. That is a pairing failure, not a set of defects — check --selector contains the same component on both sides, and that ported roots carry data-section.`));
122104
123457
  }
122105
123458
  const prodAmbient = prodSide.roots.reduce((n, r) => n + r.ambient, 0);
122106
123459
  const candAmbient = candSide.roots.reduce((n, r) => n + r.ambient, 0);
122107
123460
  if (prodAmbient > 0 || candAmbient > 0) {
122108
- console.log(chalk42.dim(` ${prodAmbient} prod / ${candAmbient} cand node+property pair(s) were moving with no interaction (carousel, autoplaying video, anything on a timer) and were subtracted. A large count means --selector contains something animating on its own; narrow it.`));
123461
+ console.log(chalk43.dim(` ${prodAmbient} prod / ${candAmbient} cand node+property pair(s) were moving with no interaction (carousel, autoplaying video, anything on a timer) and were subtracted. A large count means --selector contains something animating on its own; narrow it.`));
122109
123462
  }
122110
123463
  for (const cap of caps)
122111
- console.log(chalk42.yellow(` CAPPED — ${cap}; absence of a finding is not proof`));
123464
+ console.log(chalk43.yellow(` CAPPED — ${cap}; absence of a finding is not proof`));
122112
123465
  if (truncated) {
122113
- console.log(chalk42.dim(" TRUNCATED — box-tree or motion node cap hit; absence of a finding is not proof"));
123466
+ console.log(chalk43.dim(" TRUNCATED — box-tree or motion node cap hit; absence of a finding is not proof"));
122114
123467
  }
122115
123468
  return inconclusive || effects.lost.length > 0 || (motion?.findings.length ?? 0) > 0 ? 1 : 0;
122116
123469
  } finally {
@@ -122122,7 +123475,7 @@ async function statesCommand(opts) {
122122
123475
 
122123
123476
  // src/commands/stress.ts
122124
123477
  import { createHash as createHash3 } from "node:crypto";
122125
- import chalk43 from "chalk";
123478
+ import chalk44 from "chalk";
122126
123479
  var STATIC = /\.(png|jpe?g|webp|avif|gif|svg|woff2?|ttf|css|js|map|ico)(\?|$)/i;
122127
123480
  function analyzeStress(requests, extra) {
122128
123481
  const groups = new Map;
@@ -122152,7 +123505,7 @@ function analyzeStress(requests, extra) {
122152
123505
  }
122153
123506
  async function stressCommand(opts) {
122154
123507
  if (!opts.selector && !opts.text) {
122155
- console.error(chalk43.red("pass --selector or --text"));
123508
+ console.error(chalk44.red("pass --selector or --text"));
122156
123509
  return 2;
122157
123510
  }
122158
123511
  const browser = await launchBrowser({ headless: true });
@@ -122179,7 +123532,7 @@ async function stressCommand(opts) {
122179
123532
  const target = (opts.selector ? page.locator(opts.selector) : page.getByText(opts.text, { exact: true })).filter({ visible: true }).first();
122180
123533
  const box = await target.boundingBox().catch(() => null);
122181
123534
  if (!box) {
122182
- console.error(chalk43.yellow("target matched no visible element — nothing was stressed"));
123535
+ console.error(chalk44.yellow("target matched no visible element — nothing was stressed"));
122183
123536
  return 2;
122184
123537
  }
122185
123538
  const handle = await target.elementHandle().catch(() => null);
@@ -122230,17 +123583,17 @@ async function stressCommand(opts) {
122230
123583
  console.log(JSON.stringify({ url: opts.url, target: opts.selector ?? opts.text, ...report }));
122231
123584
  return 0;
122232
123585
  }
122233
- console.log(chalk43.bold(`
123586
+ console.log(chalk44.bold(`
122234
123587
  ${opts.times} clicks on ${opts.selector ?? `"${opts.text}"`}`));
122235
123588
  console.log(` ${report.requests} request(s), ${report.mutations} mutating · disabled after 1st click: ${report.disabledAfterFirstClick ?? "?"}`);
122236
123589
  for (const d of report.duplicates)
122237
- console.log(chalk43.yellow(` ×${d.count} ${d.method} ${d.url.slice(0, 110)} [${d.statuses.join(",")}]`));
123590
+ console.log(chalk44.yellow(` ×${d.count} ${d.method} ${d.url.slice(0, 110)} [${d.statuses.join(",")}]`));
122238
123591
  for (const f of report.failed.filter((f) => !report.duplicates.includes(f)))
122239
- console.log(chalk43.red(` failed ${f.method} ${f.url.slice(0, 110)} [${f.statuses.join(",")}]`));
123592
+ console.log(chalk44.red(` failed ${f.method} ${f.url.slice(0, 110)} [${f.statuses.join(",")}]`));
122240
123593
  for (const e of report.consoleErrors.slice(0, 5))
122241
- console.log(chalk43.red(` console: ${e}`));
123594
+ console.log(chalk44.red(` console: ${e}`));
122242
123595
  if (opts.screenshot)
122243
- console.log(chalk43.dim(` final state: ${opts.screenshot}`));
123596
+ console.log(chalk44.dim(` final state: ${opts.screenshot}`));
122244
123597
  return 0;
122245
123598
  } finally {
122246
123599
  await browser.close().catch(() => {
@@ -122251,18 +123604,18 @@ async function stressCommand(opts) {
122251
123604
 
122252
123605
  // src/commands/studio.ts
122253
123606
  import { execFileSync as execFileSync6 } from "node:child_process";
122254
- import chalk44 from "chalk";
123607
+ import chalk45 from "chalk";
122255
123608
  var CLOSED2 = new Set(["done", "archived", "merged"]);
122256
123609
  var PRIORITY_RANK = { urgent: 0, high: 1, medium: 2, low: 3, none: 4 };
122257
123610
  function config() {
122258
123611
  const cfg = studioConfigFromEnv();
122259
123612
  if (!cfg) {
122260
- console.error(chalk44.red(`Studio not configured — ${STUDIO_LOGIN_HINT}. The org comes from PARITY_STUDIO_URL (…/api/<org>/mcp/self) or PARITY_STUDIO_ORG.`));
123613
+ console.error(chalk45.red(`Studio not configured — ${STUDIO_LOGIN_HINT}. The org comes from PARITY_STUDIO_URL (…/api/<org>/mcp/self) or PARITY_STUDIO_ORG.`));
122261
123614
  }
122262
123615
  return cfg;
122263
123616
  }
122264
123617
  function fail2(err) {
122265
- console.error(chalk44.red(err instanceof Error ? err.message : String(err)));
123618
+ console.error(chalk45.red(err instanceof Error ? err.message : String(err)));
122266
123619
  return 1;
122267
123620
  }
122268
123621
  function seq(t) {
@@ -122270,7 +123623,7 @@ function seq(t) {
122270
123623
  }
122271
123624
  function line(t) {
122272
123625
  const tags = [t.type, t.priority && t.priority !== "none" ? t.priority : null].filter(Boolean).join("·");
122273
- return `${chalk44.bold(seq(t).padEnd(6))} ${t.status.padEnd(12)} ${chalk44.dim(`[${tags}]`.padEnd(16))} ${t.title}${t.repo ? chalk44.dim(` ${t.repo}`) : ""}`;
123626
+ return `${chalk45.bold(seq(t).padEnd(6))} ${t.status.padEnd(12)} ${chalk45.dim(`[${tags}]`.padEnd(16))} ${t.title}${t.repo ? chalk45.dim(` ${t.repo}`) : ""}`;
122274
123627
  }
122275
123628
  async function resolveTask(cfg, ref, call) {
122276
123629
  const board = await listTasks2(cfg, call);
@@ -122294,13 +123647,13 @@ async function studioTasksCommand(opts, call = callTool2) {
122294
123647
  return 0;
122295
123648
  }
122296
123649
  if (board.items.length === 0) {
122297
- console.log(chalk44.yellow("The board is empty."));
123650
+ console.log(chalk45.yellow("The board is empty."));
122298
123651
  return 0;
122299
123652
  }
122300
123653
  for (const t of limited)
122301
123654
  console.log(line(t));
122302
123655
  const hidden = board.items.length - shown.length;
122303
- console.log(chalk44.dim(` ${shown.length} of ${board.items.length} task(s)${limited.length < shown.length ? `, first ${limited.length} shown` : ""}${hidden > 0 && !statuses && !opts.all ? ` · ${hidden} done/archived/merged or filtered out (--all shows them)` : ""}`));
123656
+ console.log(chalk45.dim(` ${shown.length} of ${board.items.length} task(s)${limited.length < shown.length ? `, first ${limited.length} shown` : ""}${hidden > 0 && !statuses && !opts.all ? ` · ${hidden} done/archived/merged or filtered out (--all shows them)` : ""}`));
122304
123657
  return 0;
122305
123658
  } catch (err) {
122306
123659
  return fail2(err);
@@ -122324,23 +123677,23 @@ async function studioShowCommand(opts, call = callTool2) {
122324
123677
  return 0;
122325
123678
  }
122326
123679
  console.log(line(task));
122327
- console.log(chalk44.dim(` id ${task.id}${task.statusSince ? ` · in ${task.status} since ${task.statusSince}` : ""}`));
123680
+ console.log(chalk45.dim(` id ${task.id}${task.statusSince ? ` · in ${task.status} since ${task.statusSince}` : ""}`));
122328
123681
  if (task.description)
122329
123682
  console.log(`
122330
123683
  ${task.description}
122331
123684
  `);
122332
123685
  if (prs === null)
122333
- console.log(chalk44.dim(" (could not read linked PRs)"));
123686
+ console.log(chalk45.dim(" (could not read linked PRs)"));
122334
123687
  for (const pr of prs ?? []) {
122335
123688
  const state = pr.merged ? "merged" : pr.draft ? "draft" : pr.state ?? "?";
122336
- console.log(` PR ${state.padEnd(7)} ${pr.url}${pr.title ? chalk44.dim(` ${pr.title}`) : ""}`);
123689
+ console.log(` PR ${state.padEnd(7)} ${pr.url}${pr.title ? chalk45.dim(` ${pr.title}`) : ""}`);
122337
123690
  }
122338
123691
  const open = comments.filter((c) => !c.resolved);
122339
123692
  if (open.length)
122340
- console.log(chalk44.bold(`
123693
+ console.log(chalk45.bold(`
122341
123694
  Comments (${open.length} open)`));
122342
123695
  for (const c of open)
122343
- console.log(` ${chalk44.dim(c.createdAt)} ${c.body.replace(/\n/g, `
123696
+ console.log(` ${chalk45.dim(c.createdAt)} ${c.body.replace(/\n/g, `
122344
123697
  `)}`);
122345
123698
  return 0;
122346
123699
  } catch (err) {
@@ -122359,7 +123712,7 @@ async function guardedMove(cfg, task, columns, to, opts, call) {
122359
123712
  if (!valid.includes(to))
122360
123713
  return fail2(new Error(`"${to}" is not a column of this board: ${valid.join(", ")}.`));
122361
123714
  if (task.status === to) {
122362
- console.log(chalk44.dim(`${seq(task)} is already in ${to}.`));
123715
+ console.log(chalk45.dim(`${seq(task)} is already in ${to}.`));
122363
123716
  return 0;
122364
123717
  }
122365
123718
  const automated = await automatedColumns(cfg, call);
@@ -122367,16 +123720,16 @@ async function guardedMove(cfg, task, columns, to, opts, call) {
122367
123720
  return fail2(new Error(`The "${to}" column has an automation: landing ${seq(task)} there starts the board's agent on it. Pass --allow-automation if that is the point.`));
122368
123721
  }
122369
123722
  if (!opts.yes) {
122370
- console.log(chalk44.yellow("dry run — nothing changed. Pass --yes."));
123723
+ console.log(chalk45.yellow("dry run — nothing changed. Pass --yes."));
122371
123724
  console.log(` ${seq(task)} ${task.status} → ${to} ${task.title}`);
122372
123725
  if (opts.comment)
122373
- console.log(chalk44.dim(` and comment: ${PARITY_COMMENT_PREFIX} ${opts.comment}`));
123726
+ console.log(chalk45.dim(` and comment: ${PARITY_COMMENT_PREFIX} ${opts.comment}`));
122374
123727
  return 0;
122375
123728
  }
122376
123729
  await moveTask(cfg, task.id, to, call);
122377
123730
  if (opts.comment)
122378
123731
  await postParityComment(task.id, opts.comment, cfg, call);
122379
- console.log(`${chalk44.green("✓")} ${seq(task)} ${task.status} → ${to} ${task.title}`);
123732
+ console.log(`${chalk45.green("✓")} ${seq(task)} ${task.status} → ${to} ${task.title}`);
122380
123733
  return 0;
122381
123734
  }
122382
123735
  async function studioTakeCommand(opts, call = callTool2) {
@@ -122425,12 +123778,12 @@ async function studioCommentCommand(opts, call = callTool2) {
122425
123778
  if (found instanceof Error)
122426
123779
  return fail2(found);
122427
123780
  if (!opts.yes) {
122428
- console.log(chalk44.yellow("dry run — nothing posted. Pass --yes."));
123781
+ console.log(chalk45.yellow("dry run — nothing posted. Pass --yes."));
122429
123782
  console.log(` on ${seq(found.task)}: ${PARITY_COMMENT_PREFIX} ${body}`);
122430
123783
  return 0;
122431
123784
  }
122432
123785
  await postParityComment(found.task.id, body, cfg, call);
122433
- console.log(`${chalk44.green("✓")} commented on ${seq(found.task)}`);
123786
+ console.log(`${chalk45.green("✓")} commented on ${seq(found.task)}`);
122434
123787
  return 0;
122435
123788
  } catch (err) {
122436
123789
  return fail2(err);
@@ -122439,9 +123792,9 @@ async function studioCommentCommand(opts, call = callTool2) {
122439
123792
 
122440
123793
  // src/commands/drift.ts
122441
123794
  import { spawnSync as spawnSync3 } from "node:child_process";
122442
- import { existsSync as existsSync39, readFileSync as readFileSync45 } from "node:fs";
123795
+ import { existsSync as existsSync40, readFileSync as readFileSync46 } from "node:fs";
122443
123796
  import { resolve as resolve23 } from "node:path";
122444
- import chalk45 from "chalk";
123797
+ import chalk46 from "chalk";
122445
123798
  var DRIFT_EXCLUDES = [":!.deco"];
122446
123799
  var SHA_RE = /^[0-9a-f]{7,64}$/i;
122447
123800
  function resolveDriftInputs(state, flags) {
@@ -122559,7 +123912,7 @@ function computeDrift(inputs, opts) {
122559
123912
  const fail = (code, message) => ({ error: { code, message } });
122560
123913
  if (headRef.startsWith("-"))
122561
123914
  return fail("bad_head", `head "${headRef}" looks like a flag`);
122562
- if (!existsSync39(source))
123915
+ if (!existsSync40(source))
122563
123916
  return fail("not_a_repo", `${source} does not exist`);
122564
123917
  const inside = git(source, ["rev-parse", "--is-inside-work-tree"]);
122565
123918
  if (!inside.ok || inside.stdout.trim() !== "true") {
@@ -122627,10 +123980,10 @@ function computeDrift(inputs, opts) {
122627
123980
  };
122628
123981
  }
122629
123982
  function loadState(path) {
122630
- if (!existsSync39(path))
123983
+ if (!existsSync40(path))
122631
123984
  return null;
122632
123985
  try {
122633
- return JSON.parse(readFileSync45(path, "utf8"));
123986
+ return JSON.parse(readFileSync46(path, "utf8"));
122634
123987
  } catch (err) {
122635
123988
  return { error: { code: "state_unreadable", message: `${path}: ${err.message}` } };
122636
123989
  }
@@ -122654,7 +124007,7 @@ function driftCommand(flags) {
122654
124007
  if (flags.json)
122655
124008
  console.log(JSON.stringify({ error: r.error }));
122656
124009
  else
122657
- console.error(chalk45.red(` could not measure drift [${r.error.code}]: ${r.error.message}`));
124010
+ console.error(chalk46.red(` could not measure drift [${r.error.code}]: ${r.error.message}`));
122658
124011
  return 2;
122659
124012
  }
122660
124013
  if (flags.json) {
@@ -122673,7 +124026,7 @@ function driftCommand(flags) {
122673
124026
  }
122674
124027
 
122675
124028
  // src/commands/variance.ts
122676
- import chalk46 from "chalk";
124029
+ import chalk47 from "chalk";
122677
124030
 
122678
124031
  // src/diff/variance.ts
122679
124032
  var uniq2 = (xs) => [...new Set(xs)];
@@ -122777,7 +124130,7 @@ function formatVariance(report, opts = {}) {
122777
124130
  // src/commands/variance.ts
122778
124131
  function varianceCommand(opts) {
122779
124132
  if (opts.runIds.length < 2) {
122780
- console.error(chalk46.red(" informe pelo menos 2 runs: parity variance <runIdA> <runIdB> [...]"));
124133
+ console.error(chalk47.red(" informe pelo menos 2 runs: parity variance <runIdA> <runIdB> [...]"));
122781
124134
  return 2;
122782
124135
  }
122783
124136
  const budget = Number.parseFloat(opts.scoreBudget ?? "1");
@@ -122786,7 +124139,7 @@ function varianceCommand(opts) {
122786
124139
  try {
122787
124140
  runs.push(loadRun(opts.output, id));
122788
124141
  } catch (err) {
122789
- console.error(chalk46.red(` ✖ ${err.message}`));
124142
+ console.error(chalk47.red(` ✖ ${err.message}`));
122790
124143
  return 2;
122791
124144
  }
122792
124145
  }
@@ -122795,7 +124148,7 @@ function varianceCommand(opts) {
122795
124148
  console.log(JSON.stringify({ ...report, stable: isStable(report, budget), scoreBudget: budget }));
122796
124149
  } else {
122797
124150
  console.log("");
122798
- console.log(chalk46.bold(" Score variance"));
124151
+ console.log(chalk47.bold(" Score variance"));
122799
124152
  for (const line of formatVariance(report, { scoreBudget: budget }).split(`
122800
124153
  `)) {
122801
124154
  console.log(` ${line}`);
@@ -122807,10 +124160,10 @@ function varianceCommand(opts) {
122807
124160
  }
122808
124161
 
122809
124162
  // src/commands/vitals.ts
122810
- import { existsSync as existsSync40, readFileSync as readFileSync46, writeFileSync as writeFileSync38 } from "node:fs";
124163
+ import { existsSync as existsSync41, readFileSync as readFileSync47, writeFileSync as writeFileSync39 } from "node:fs";
122811
124164
  import { availableParallelism } from "node:os";
122812
- import { join as join52 } from "node:path";
122813
- import chalk47 from "chalk";
124165
+ import { join as join54 } from "node:path";
124166
+ import chalk48 from "chalk";
122814
124167
  import ora9 from "ora";
122815
124168
 
122816
124169
  // src/checks/agentic-nav.ts
@@ -123114,10 +124467,10 @@ async function vitalsCommand(opts) {
123114
124467
  const runId = newRunId();
123115
124468
  const paths = createRunDir(opts.output, runId);
123116
124469
  const t0 = Date.now();
123117
- console.log(chalk47.bold(`
124470
+ console.log(chalk48.bold(`
123118
124471
  parity vitals ${runId}`));
123119
- console.log(chalk47.dim(` prod: ${opts.prod}`));
123120
- console.log(chalk47.dim(` cand: ${opts.cand}`));
124472
+ console.log(chalk48.dim(` prod: ${opts.prod}`));
124473
+ console.log(chalk48.dim(` cand: ${opts.cand}`));
123121
124474
  const discoverSpinner = ora9("Descobrindo páginas…").start();
123122
124475
  const pagePaths = await discoverPagePaths2(opts.prod, opts);
123123
124476
  if (pagePaths.length === 0) {
@@ -123149,12 +124502,12 @@ async function vitalsCommand(opts) {
123149
124502
  completed++;
123150
124503
  const elapsed = ((Date.now() - t0) / 1000).toFixed(0);
123151
124504
  const etaSec = completed > 0 ? Math.round((Date.now() - t0) / completed * (total - completed) / 1000) : 0;
123152
- progress.text = `${completed}/${total} · ${elapsed}s · ETA ${etaSec}s · ${task.side === "prod" ? chalk47.cyan("prod") : chalk47.magenta("cand")} ${task.path} (${task.viewport})`;
124505
+ progress.text = `${completed}/${total} · ${elapsed}s · ETA ${etaSec}s · ${task.side === "prod" ? chalk48.cyan("prod") : chalk48.magenta("cand")} ${task.path} (${task.viewport})`;
123153
124506
  }
123154
124507
  });
123155
124508
  progress.succeed(`${total} capture(s) em ${((Date.now() - t0) / 1000).toFixed(1)}s`);
123156
124509
  if (opts.lighthouse !== false) {
123157
- const lhDir = join52(paths.runDir, "lighthouse");
124510
+ const lhDir = join54(paths.runDir, "lighthouse");
123158
124511
  const lhCap = opts.lighthouseConcurrency ?? Math.max(1, Math.min(2, Math.floor(availableParallelism() / 2)));
123159
124512
  const done = tasks.filter((t) => !!t.capture);
123160
124513
  const lhT0 = Date.now();
@@ -123178,7 +124531,7 @@ async function vitalsCommand(opts) {
123178
124531
  }
123179
124532
  lhCompleted++;
123180
124533
  const elapsed = ((Date.now() - lhT0) / 1000).toFixed(0);
123181
- lhProgress.text = `Lighthouse ${lhCompleted}/${done.length} · ${elapsed}s · ${task.side === "prod" ? chalk47.cyan("prod") : chalk47.magenta("cand")} ${task.path} (${task.viewport})`;
124534
+ lhProgress.text = `Lighthouse ${lhCompleted}/${done.length} · ${elapsed}s · ${task.side === "prod" ? chalk48.cyan("prod") : chalk48.magenta("cand")} ${task.path} (${task.viewport})`;
123182
124535
  });
123183
124536
  lhProgress.succeed(`Lighthouse ${done.length} página(s) em ${((Date.now() - lhT0) / 1000).toFixed(1)}s`);
123184
124537
  }
@@ -123243,7 +124596,7 @@ async function vitalsCommand(opts) {
123243
124596
  writeRunReportJson(paths.runDir, run);
123244
124597
  const html = renderHtmlReport(run, paths.runDir);
123245
124598
  writeRunReportHtml(paths.runDir, html);
123246
- writeFileSync38(join52(paths.runDir, "vitals.json"), `${JSON.stringify({
124599
+ writeFileSync39(join54(paths.runDir, "vitals.json"), `${JSON.stringify({
123247
124600
  schemaVersion: "0.1",
123248
124601
  prodUrl: opts.prod,
123249
124602
  candUrl: opts.cand,
@@ -123256,8 +124609,8 @@ async function vitalsCommand(opts) {
123256
124609
  `, "utf8");
123257
124610
  printSummary9(vitalsResult, cacheResult, scoresResult, oppsResult, agenticResult);
123258
124611
  console.log("");
123259
- console.log(chalk47.dim(` → ${paths.reportHtml}`));
123260
- console.log(chalk47.dim(` \uD83D\uDCA1 use 'parity serve ${runId}' pra preview iframe`));
124612
+ console.log(chalk48.dim(` → ${paths.reportHtml}`));
124613
+ console.log(chalk48.dim(` \uD83D\uDCA1 use 'parity serve ${runId}' pra preview iframe`));
123261
124614
  console.log("");
123262
124615
  if (opts.open) {
123263
124616
  const { default: open } = await import("open");
@@ -123349,15 +124702,15 @@ async function discoverPagePaths2(prodUrl, opts) {
123349
124702
  function parseUrlList(input) {
123350
124703
  if (input.startsWith("file:") || input.endsWith(".txt") || input.endsWith(".list")) {
123351
124704
  const path = input.replace(/^file:\/\//, "");
123352
- if (existsSync40(path)) {
123353
- return readFileSync46(path, "utf8").split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !s.startsWith("#")).map((s) => s.startsWith("/") ? s : `/${s}`);
124705
+ if (existsSync41(path)) {
124706
+ return readFileSync47(path, "utf8").split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !s.startsWith("#")).map((s) => s.startsWith("/") ? s : `/${s}`);
123354
124707
  }
123355
124708
  }
123356
124709
  return input.split(",").map((s) => s.trim()).filter(Boolean).map((s) => s.startsWith("/") || s.startsWith("http") ? s : `/${s}`);
123357
124710
  }
123358
124711
  function printSummary9(vitals, cache, scores, opportunities, agentic) {
123359
124712
  console.log("");
123360
- console.log(chalk47.bold(" Summary:"));
124713
+ console.log(chalk48.bold(" Summary:"));
123361
124714
  console.log(` ${vitals.summary}`);
123362
124715
  console.log(` ${cache.summary}`);
123363
124716
  if (scores.status !== "skipped")
@@ -123421,10 +124774,10 @@ sweep.addCommand(new Command("regress").description("Run only the store's tests/
123421
124774
  if (opts.json)
123422
124775
  console.log(JSON.stringify({ url: opts.url, issues }));
123423
124776
  else if (!issues.length)
123424
- console.log(chalk48.green(" regression suite: all passed"));
124777
+ console.log(chalk49.green(" regression suite: all passed"));
123425
124778
  else
123426
124779
  for (const i of issues)
123427
- console.log((i.inconclusive ? chalk48.yellow : chalk48.red)(` ${i.summary}`));
124780
+ console.log((i.inconclusive ? chalk49.yellow : chalk49.red)(` ${i.summary}`));
123428
124781
  process.exit(regressed ? 1 : unverified ? 2 : 0);
123429
124782
  }));
123430
124783
  sweep.addCommand(new Command("file").description("File an existing sweep run's findings on the Studio board (default: the newest sweep run). Merges <run>/sweeper-issues.json written by the `sweeper` agent. Dry run unless --yes.").option("--run <runId>", "Sweep run id (default: newest sweep in --output)").option("--output <dir>", "Output directory", "./parity-output").option("--board <name>", "Board: studio", "studio").option("--yes", "Actually create/update cards", false).option("--allow-automation", "File even if the board's triage column starts an agent", false).option("--min-severity <sev>", "critical|high|medium|low", "medium").option("--repo <owner/name>", "Repository to put on the cards").option("--artifacts-url <url>", "Public base URL for this run's artifacts").option("--json", "Emit JSON", false).action(async (opts) => {
@@ -123440,6 +124793,9 @@ program.command("baseline").description("Manage baselines").addCommand(new Comma
123440
124793
  })).addCommand(new Command("unset").argument("<name>", "Baseline name to remove").action((name) => {
123441
124794
  process.exit(baselineUnset(name));
123442
124795
  })).addCommand(buildCompareCommand("diff", false));
124796
+ program.command("replay").description("Re-run the checks on a recording made with `parity run --record <dir>`, with no browser. Exit 0 = replayed (and matched expected.json with --expect), 1 = differs from expected.json, 2 = nothing could be judged (not a recording, incomplete, nothing compared, no expected.json).").argument("<dir>", "Recording directory").option("--json", "Emit structured JSON", false).option("--out <dir>", "Keep artifacts (diff PNGs) here instead of a temp dir removed afterwards").option("--expect", "Compare the outcome with <dir>/expected.json", false).option("--update-expected", "Write <dir>/expected.json from this replay (keeps its notes)", false).action(async (dir, opts) => {
124797
+ process.exit(await replayCommand(dir, opts));
124798
+ });
123443
124799
  program.command("accept").description("Record findings the USER accepted as-is, in .parityignore. They stay in the report but leave the headline score (`rawScore` keeps them). Never run by an agent on its own — accepting is how a real gap disappears from view.").addCommand(new Command("add").description("Accept every finding in a scope. Scope = --check and/or --id, narrowed by --page and --match. No --page = every page.").option("--check <name>", "Check name (meta-seo-parity) or module (network)").option("--id <issueId>", "One issue id (only stable ids are worth accepting)").option("--page <key>", "Only this page key, e.g. /::desktop").option("--match <text>", "Only findings whose summary/details contain this (case-insensitive)").requiredOption("--note <why>", "Why the difference is accepted — required").action((opts) => {
123444
124800
  process.exit(acceptAdd(opts));
123445
124801
  })).addCommand(new Command("list").description("List recorded acceptances with their index").action(() => {
@@ -123637,7 +124993,7 @@ program.command("css-modules").description('Find CSS Module classes passed as li
123637
124993
  program.command("console").description("Single-page console capture. Boots Playwright on --url, waits for the page to settle, then prints any console errors/warnings + network failures. No LLM, no checks — designed for sub-10s debug loops (issue #31).").requiredOption("--url <url>", "URL to load").option("--viewport <viewport>", "mobile | desktop | tablet", "mobile").option("--wait <ms>", "Extra ms to wait after networkidle so client-side errors land", "2000").option("--filter <types>", "Comma-separated subset of error,warning,log,info,debug (default: error,warning)").option("--json", "Emit one-line JSON instead of human-readable text", false).action(async (opts) => {
123638
124994
  process.exit(await consoleCommand(opts));
123639
124995
  });
123640
- program.command("html").description("Dump page HTML or diff prod vs cand HTML for a section. No LLM, no checks — sub-10s debug loop (issue #31).").option("--url <url>", "Single-side mode: dump HTML of this URL").option("--prod <url>", "Diff mode: prod URL (use together with --cand --diff)").option("--cand <url>", "Diff mode: cand URL (use together with --prod --diff)").option("--selector <sel>", "Narrow output to a CSS selector (outer HTML of first match)").option("--pretty", "Format HTML with prettier", false).option("--diff", "Diff mode (required with --prod/--cand). Prints unified diff", false).option("--viewport <viewport>", "mobile | desktop | tablet", "mobile").option("--wait <ms>", "Extra ms after networkidle so SSR/hydration settles", (v) => Number(v), 2000).option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
124996
+ program.command("html").description("Dump page HTML or diff prod vs cand HTML for a section. No LLM, no checks — sub-10s debug loop (issue #31).").option("--url <url>", "Single-side mode: dump HTML of this URL").option("--prod <url>", "Diff mode: prod URL (use together with --cand --diff)").option("--cand <url>", "Diff mode: cand URL (use together with --prod --diff)").option("--selector <sel>", "Narrow output to a CSS selector (outer HTML of first match)").option("--pretty", "Format HTML with prettier", false).option("--diff", "Diff mode (required with --prod/--cand). Prints unified diff", false).option("--viewport <viewport>", "mobile | desktop | tablet", "mobile").option("--wait <ms>", "Extra ms after networkidle so SSR/hydration settles", (v) => Number(v), 2000).option("--no-resolve-deferred", "Do not resolve deferred (htmx hx-get + intersect/revealed/load) sections; the HTML keeps their placeholders").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
123641
124997
  process.exit(await htmlCommand(opts));
123642
124998
  });
123643
124999
  program.command("check").argument("<name>", "check name (kebab-case, e.g. console-errors-baseline)").description("Run a single check against a prod×cand pair on one page. Skips sitemap discovery, the other 13 checks, and the LLM aggregation. Sub-10s loop for verifying a single fix (issue #31). `content-freshness` is the exception: no prod, no browser — it compares the CMS content the candidate serves (/.decofile) with .deco/blocks at --ref in --repo. Run it instead of a deploy or `sync:kv` (issue #484).").option("--prod <url>", "Production URL (base). Required by every check but content-freshness").requiredOption("--cand <url>", "Candidate URL (base)").option("--viewports <list>", "Comma-separated mobile,desktop,tablet", "mobile").option("--page <path>", "Pathname to capture (e.g. /bota-tudao-2025)", "/").option("--repo <dir>", "content-freshness: target repo (read via git, never checked out)", ".").option("--ref <ref>", "content-freshness: git ref holding the expected .deco/blocks", "origin/main").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (name, opts) => {