@decocms/parity 0.17.9 → 0.19.0

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
@@ -7549,14 +7549,14 @@ class Tokenizer2 {
7549
7549
  }
7550
7550
  }
7551
7551
  _emitEOFToken() {
7552
- const location = this.getCurrentLocation(0);
7553
- if (location) {
7554
- location.endLine = location.startLine;
7555
- location.endCol = location.startCol;
7556
- location.endOffset = location.startOffset;
7557
- }
7558
- this._emitCurrentCharacterToken(location);
7559
- this.handler.onEof({ type: TokenType.EOF, location });
7552
+ const location2 = this.getCurrentLocation(0);
7553
+ if (location2) {
7554
+ location2.endLine = location2.startLine;
7555
+ location2.endCol = location2.startCol;
7556
+ location2.endOffset = location2.startOffset;
7557
+ }
7558
+ this._emitCurrentCharacterToken(location2);
7559
+ this.handler.onEof({ type: TokenType.EOF, location: location2 });
7560
7560
  this.active = false;
7561
7561
  }
7562
7562
  _appendCharToCurrentCharacterToken(type, ch) {
@@ -10278,8 +10278,8 @@ var init_default = __esm(() => {
10278
10278
  isElementNode(node2) {
10279
10279
  return Object.prototype.hasOwnProperty.call(node2, "tagName");
10280
10280
  },
10281
- setNodeSourceCodeLocation(node2, location) {
10282
- node2.sourceCodeLocation = location;
10281
+ setNodeSourceCodeLocation(node2, location2) {
10282
+ node2.sourceCodeLocation = location2;
10283
10283
  },
10284
10284
  getNodeSourceCodeLocation(node2) {
10285
10285
  return node2.sourceCodeLocation;
@@ -10796,11 +10796,11 @@ class Parser2 {
10796
10796
  }
10797
10797
  }
10798
10798
  }
10799
- _attachElementToTree(element, location) {
10799
+ _attachElementToTree(element, location2) {
10800
10800
  if (this.options.sourceCodeLocationInfo) {
10801
- const loc = location && {
10802
- ...location,
10803
- startTag: location
10801
+ const loc = location2 && {
10802
+ ...location2,
10803
+ startTag: location2
10804
10804
  };
10805
10805
  this.treeAdapter.setNodeSourceCodeLocation(element, loc);
10806
10806
  }
@@ -11084,11 +11084,11 @@ class Parser2 {
11084
11084
  return { parent: this.openElements.items[0], beforeElement: null };
11085
11085
  }
11086
11086
  _fosterParentElement(element) {
11087
- const location = this._findFosterParentingLocation();
11088
- if (location.beforeElement) {
11089
- this.treeAdapter.insertBefore(location.parent, element, location.beforeElement);
11087
+ const location2 = this._findFosterParentingLocation();
11088
+ if (location2.beforeElement) {
11089
+ this.treeAdapter.insertBefore(location2.parent, element, location2.beforeElement);
11090
11090
  } else {
11091
- this.treeAdapter.appendChild(location.parent, element);
11091
+ this.treeAdapter.appendChild(location2.parent, element);
11092
11092
  }
11093
11093
  }
11094
11094
  _isSpecialElement(element, id) {
@@ -13940,12 +13940,12 @@ var init_dist2 = __esm(() => {
13940
13940
  isDocumentTypeNode(node2) {
13941
13941
  return isDirective(node2) && node2.name === "!doctype";
13942
13942
  },
13943
- setNodeSourceCodeLocation(node2, location) {
13944
- if (location) {
13945
- node2.startIndex = location.startOffset;
13946
- node2.endIndex = location.endOffset;
13943
+ setNodeSourceCodeLocation(node2, location2) {
13944
+ if (location2) {
13945
+ node2.startIndex = location2.startOffset;
13946
+ node2.endIndex = location2.endOffset;
13947
13947
  }
13948
- node2.sourceCodeLocation = location;
13948
+ node2.sourceCodeLocation = location2;
13949
13949
  },
13950
13950
  getNodeSourceCodeLocation(node2) {
13951
13951
  return node2.sourceCodeLocation;
@@ -18479,17 +18479,17 @@ var require_util2 = __commonJS((exports, module) => {
18479
18479
  if (!redirectStatusSet.has(response.status)) {
18480
18480
  return null;
18481
18481
  }
18482
- let location = response.headersList.get("location", true);
18483
- if (location !== null && isValidHeaderValue(location)) {
18484
- if (!isValidEncodedURL(location)) {
18485
- location = normalizeBinaryStringToUtf8(location);
18482
+ let location2 = response.headersList.get("location", true);
18483
+ if (location2 !== null && isValidHeaderValue(location2)) {
18484
+ if (!isValidEncodedURL(location2)) {
18485
+ location2 = normalizeBinaryStringToUtf8(location2);
18486
18486
  }
18487
- location = new URL(location, responseURL(response));
18487
+ location2 = new URL(location2, responseURL(response));
18488
18488
  }
18489
- if (location && !location.hash) {
18490
- location.hash = requestFragment;
18489
+ if (location2 && !location2.hash) {
18490
+ location2.hash = requestFragment;
18491
18491
  }
18492
- return location;
18492
+ return location2;
18493
18493
  }
18494
18494
  function isValidEncodedURL(url) {
18495
18495
  for (let i = 0;i < url.length; ++i) {
@@ -32547,9 +32547,9 @@ var require_fetch = __commonJS((exports, module) => {
32547
32547
  headersList.append(nameStr, value.toString("latin1"), true);
32548
32548
  }
32549
32549
  }
32550
- const location = headersList.get("location", true);
32550
+ const location2 = headersList.get("location", true);
32551
32551
  this.body = new Readable({ read: resume });
32552
- const willFollow = location && request.redirect === "follow" && redirectStatusSet.has(status);
32552
+ const willFollow = location2 && request.redirect === "follow" && redirectStatusSet.has(status);
32553
32553
  const decoders = [];
32554
32554
  if (request.method !== "HEAD" && request.method !== "CONNECT" && !nullBodyStatus.includes(status) && !willFollow) {
32555
32555
  const contentEncoding = headersList.get("content-encoding", true);
@@ -44427,6 +44427,34 @@ function withPage(url, n) {
44427
44427
  return `${url}${sep}page=${n}`;
44428
44428
  }
44429
44429
  }
44430
+ function pickPlpFromHomeHtml(html3, homeUrl) {
44431
+ const candidates = new Set;
44432
+ const re = /href="([^"]+)"/gi;
44433
+ for (;; ) {
44434
+ const m = re.exec(html3);
44435
+ if (!m)
44436
+ break;
44437
+ const href = m[1];
44438
+ if (!href)
44439
+ continue;
44440
+ 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)) {
44441
+ continue;
44442
+ }
44443
+ const segments = href.split("?")[0].split("/").filter(Boolean);
44444
+ if (segments.length === 0 || segments.length > 3)
44445
+ continue;
44446
+ candidates.add(href.split("?")[0]);
44447
+ }
44448
+ const sorted = Array.from(candidates).sort((a, b) => a.length - b.length);
44449
+ const pick = sorted[0];
44450
+ if (!pick)
44451
+ return null;
44452
+ try {
44453
+ return new URL(pick, new URL(homeUrl)).toString();
44454
+ } catch {
44455
+ return null;
44456
+ }
44457
+ }
44430
44458
  async function discoverPlpFromHome(homeUrl) {
44431
44459
  try {
44432
44460
  const res = await fetch(homeUrl, {
@@ -44437,30 +44465,7 @@ async function discoverPlpFromHome(homeUrl) {
44437
44465
  });
44438
44466
  if (!res.ok)
44439
44467
  return null;
44440
- const html3 = await res.text();
44441
- const candidates = new Set;
44442
- const re = /href="([^"]+)"/gi;
44443
- for (;; ) {
44444
- const m = re.exec(html3);
44445
- if (!m)
44446
- break;
44447
- const href = m[1];
44448
- if (!href)
44449
- continue;
44450
- 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)) {
44451
- continue;
44452
- }
44453
- const segments = href.split("?")[0].split("/").filter(Boolean);
44454
- if (segments.length === 0 || segments.length > 3)
44455
- continue;
44456
- candidates.add(href.split("?")[0]);
44457
- }
44458
- const sorted = Array.from(candidates).sort((a, b) => a.length - b.length);
44459
- const home = new URL(homeUrl);
44460
- const pick = sorted[0];
44461
- if (!pick)
44462
- return null;
44463
- return new URL(pick, home).toString();
44468
+ return pickPlpFromHomeHtml(await res.text(), homeUrl);
44464
44469
  } catch {
44465
44470
  return null;
44466
44471
  }
@@ -55271,6 +55276,9 @@ function detectFromHeaders(headers) {
55271
55276
  }
55272
55277
  function detectFromHtml(html3) {
55273
55278
  try {
55279
+ if (html3.includes("demandware.static") || html3.includes("/on/demandware.store/")) {
55280
+ return "salesforce-commerce";
55281
+ }
55274
55282
  const $2 = load(html3);
55275
55283
  const fsClasses = $2('[class*="fs-"], [data-fs-]').length;
55276
55284
  if (fsClasses > 5)
@@ -55295,6 +55303,8 @@ function detectFromHtml(html3) {
55295
55303
  return "vtex";
55296
55304
  if (generator.includes("shopify"))
55297
55305
  return "shopify";
55306
+ if (generator.includes("demandware") || generator.includes("salesforce"))
55307
+ return "salesforce-commerce";
55298
55308
  if (generator.includes("deco"))
55299
55309
  return "deco";
55300
55310
  } catch {}
@@ -56193,9 +56203,14 @@ var SECTION_STYLE_KEYS = [
56193
56203
  "border",
56194
56204
  "font-size",
56195
56205
  "font-weight",
56206
+ "line-height",
56207
+ "letter-spacing",
56208
+ "text-transform",
56196
56209
  "color",
56197
56210
  "background-color",
56198
56211
  "background-image",
56212
+ "border-radius",
56213
+ "box-shadow",
56199
56214
  "flex-direction",
56200
56215
  "justify-content",
56201
56216
  "align-items",
@@ -58401,74 +58416,43 @@ function listCommand(output) {
58401
58416
  return 0;
58402
58417
  }
58403
58418
 
58404
- // src/commands/pr.ts
58405
- import { existsSync as existsSync14, readFileSync as readFileSync15, writeFileSync as writeFileSync16 } from "node:fs";
58406
- import { join as join19 } from "node:path";
58407
- import chalk18 from "chalk";
58408
-
58409
- // src/commands/run.ts
58410
- import { existsSync as existsSync13, readFileSync as readFileSync14, unlinkSync as unlinkSync3 } from "node:fs";
58411
- import { join as join18 } from "node:path";
58412
- import chalk17 from "chalk";
58413
- import ora6 from "ora";
58419
+ // src/commands/migrate.ts
58420
+ import { existsSync as existsSync11, mkdirSync as mkdirSync14, readFileSync as readFileSync14, writeFileSync as writeFileSync20 } from "node:fs";
58421
+ import { resolve as resolve3 } from "node:path";
58422
+ import chalk16 from "chalk";
58423
+ import open from "open";
58414
58424
 
58415
- // src/engine/interactive-module-prompt.ts
58416
- import { createInterface } from "node:readline";
58417
- var ALL_MODULE_NAMES2 = Object.keys(MODULES);
58418
- async function promptForModuleSelection() {
58419
- console.log("");
58420
- console.log(" Select modules to run (all checked by default):");
58421
- console.log("");
58422
- ALL_MODULE_NAMES2.forEach((name, i) => {
58423
- const def = MODULES[name];
58424
- console.log(` [x] ${i + 1}. ${name.padEnd(8)} — ${def.description}`);
58425
- });
58426
- console.log("");
58427
- const answer = await readLine(" Type numbers to UNCHECK (comma-separated), or press Enter to run all: ");
58428
- if (answer === null) {
58429
- console.log(" (aborted — running all modules)");
58430
- return ALL_MODULE_NAMES2;
58431
- }
58432
- const trimmed = answer.trim();
58433
- if (!trimmed)
58434
- return ALL_MODULE_NAMES2;
58435
- const uncheckIdx = new Set(trimmed.split(",").map((s) => Number.parseInt(s.trim(), 10)).filter((n) => Number.isInteger(n) && n >= 1 && n <= ALL_MODULE_NAMES2.length));
58436
- const selected = ALL_MODULE_NAMES2.filter((_name, i) => !uncheckIdx.has(i + 1));
58437
- if (selected.length === 0) {
58438
- console.log(" (everything unchecked — running all modules instead)");
58439
- return ALL_MODULE_NAMES2;
58425
+ // src/migrate/pdp-discovery.ts
58426
+ var PLATFORM_PATTERNS = {
58427
+ "salesforce-commerce": [
58428
+ /href="([^"]*-[A-Za-z]?\d{3,}\.html)"/gi,
58429
+ /href="([^"]*Product-(?:Show|Detail)[^"]*[?&]pid=[^"&]+[^"]*)"/gi
58430
+ ],
58431
+ shopify: [/href="([^"]*\/products\/[^"]+)"/gi],
58432
+ vtex: [/href="([^"]*\/p(?:\?[^"]*|\/[^"]+|))"/gi],
58433
+ "vtex-fs": [/href="([^"]*\/p(?:\?[^"]*|\/[^"]+|))"/gi]
58434
+ };
58435
+ var ACTION_URL = /(Wishlist|Cart|MiniCart|Login|Account|Address|Order|Compare)-|add-?to-?/i;
58436
+ function acceptProductUrl(href, baseUrl) {
58437
+ if (ACTION_URL.test(href))
58438
+ return null;
58439
+ try {
58440
+ return new URL(href, baseUrl).toString();
58441
+ } catch {
58442
+ return null;
58440
58443
  }
58441
- console.log(` running: ${selected.join(", ")}`);
58442
- return selected;
58443
- }
58444
- function readLine(prompt) {
58445
- return new Promise((resolveLine) => {
58446
- const rl = createInterface({ input: process.stdin, output: process.stdout });
58447
- rl.question(prompt, (ans) => {
58448
- rl.close();
58449
- resolveLine(ans);
58450
- });
58451
- rl.on("SIGINT", () => {
58452
- rl.close();
58453
- resolveLine(null);
58454
- });
58455
- });
58456
58444
  }
58457
-
58458
- // src/engine/interactive-selector-prompt.ts
58459
- init_client();
58460
- var forceDisabled = false;
58461
- function disableInteractive() {
58462
- forceDisabled = true;
58463
- }
58464
- function isInteractiveMode() {
58465
- if (forceDisabled)
58466
- return false;
58467
- if (!process.stdout.isTTY || !process.stdin.isTTY)
58468
- return false;
58469
- if (isLlmAvailable())
58470
- return false;
58471
- return true;
58445
+ function firstProductHref(html3, baseUrl, platform) {
58446
+ const patterns = platform ? PLATFORM_PATTERNS[platform] ?? [] : [];
58447
+ for (const re of patterns) {
58448
+ re.lastIndex = 0;
58449
+ for (let m = re.exec(html3);m; m = re.exec(html3)) {
58450
+ const url = m[1] ? acceptProductUrl(m[1], baseUrl) : null;
58451
+ if (url)
58452
+ return url;
58453
+ }
58454
+ }
58455
+ return firstProductHrefFromPlpHtml(html3, baseUrl);
58472
58456
  }
58473
58457
 
58474
58458
  // src/engine/sitemap-discover.ts
@@ -58550,6 +58534,2043 @@ async function discoverPagesFromSitemap(prodUrl, opts = {}) {
58550
58534
  return result;
58551
58535
  }
58552
58536
 
58537
+ // src/migrate/assets.ts
58538
+ import { mkdirSync as mkdirSync12, writeFileSync as writeFileSync16 } from "node:fs";
58539
+ import { join as join17 } from "node:path";
58540
+ function aggregateIcons(icons) {
58541
+ const byKey = new Map;
58542
+ for (const icon of icons) {
58543
+ const id = icon.id.trim();
58544
+ if (!id)
58545
+ continue;
58546
+ const key = `${icon.kind} ${id}`;
58547
+ const existing = byKey.get(key);
58548
+ if (existing)
58549
+ existing.count += icon.count;
58550
+ else
58551
+ byKey.set(key, { ...icon, id });
58552
+ }
58553
+ return [...byKey.values()].sort((a, b) => b.count - a.count);
58554
+ }
58555
+ async function collectSiteAssets(page) {
58556
+ const raw = await page.evaluate(() => {
58557
+ const abs = (href) => {
58558
+ if (!href)
58559
+ return null;
58560
+ try {
58561
+ return new URL(href, location.href).href;
58562
+ } catch {
58563
+ return null;
58564
+ }
58565
+ };
58566
+ const linkHref = (sel) => abs(document.querySelector(sel)?.getAttribute("href"));
58567
+ const favicon = linkHref("link[rel='icon']") || linkHref("link[rel='shortcut icon']") || abs("/favicon.ico");
58568
+ const appleTouchIcon = linkHref("link[rel='apple-touch-icon']");
58569
+ const manifest = linkHref("link[rel='manifest']");
58570
+ const ogImage = abs(document.querySelector("meta[property='og:image']")?.getAttribute("content"));
58571
+ const fontUrls = new Set;
58572
+ for (const l of Array.from(document.querySelectorAll("link[rel='preload'][as='font']"))) {
58573
+ const u = abs(l.getAttribute("href"));
58574
+ if (u)
58575
+ fontUrls.add(u);
58576
+ }
58577
+ for (const sheet of Array.from(document.styleSheets)) {
58578
+ let rules;
58579
+ try {
58580
+ rules = sheet.cssRules;
58581
+ } catch {
58582
+ continue;
58583
+ }
58584
+ for (const rule of Array.from(rules)) {
58585
+ if (rule.constructor.name !== "CSSFontFaceRule")
58586
+ continue;
58587
+ const src = rule.style.getPropertyValue("src");
58588
+ for (const m of src.matchAll(/url\((['"]?)([^'")]+)\1\)/gi)) {
58589
+ const u = abs(m[2]);
58590
+ if (u && /\.(woff2?|ttf|otf)(\?|$)/i.test(u))
58591
+ fontUrls.add(u);
58592
+ }
58593
+ }
58594
+ }
58595
+ const fonts = [...fontUrls].slice(0, 20);
58596
+ const header = document.querySelector("header, [role='banner']") || document.body;
58597
+ let logo = null;
58598
+ if (header) {
58599
+ const hinted = Array.from(header.querySelectorAll("img, svg")).find((el2) => {
58600
+ const bag = `${el2.getAttribute("alt") ?? ""} ${el2.getAttribute("class") ?? ""} ${el2.getAttribute("aria-label") ?? ""} ${el2.closest("a")?.getAttribute("href") ?? ""}`.toLowerCase();
58601
+ return bag.includes("logo") || bag.includes("brand");
58602
+ });
58603
+ const el = hinted ?? header.querySelector("a[href='/'] img, a[href='/'] svg") ?? header.querySelector("img, svg");
58604
+ if (el) {
58605
+ el.setAttribute("data-parity-logo", "1");
58606
+ if (el.tagName.toLowerCase() === "img") {
58607
+ const url = abs(el.getAttribute("src"));
58608
+ if (url)
58609
+ logo = { type: "img", url };
58610
+ } else {
58611
+ logo = { type: "svg", markup: el.outerHTML.slice(0, 20000) };
58612
+ }
58613
+ }
58614
+ }
58615
+ const icons = [];
58616
+ for (const use of Array.from(document.querySelectorAll("use"))) {
58617
+ const href = use.getAttribute("href") || use.getAttribute("xlink:href") || "";
58618
+ const id = href.startsWith("#") ? href.slice(1) : href.split("#")[1] || "";
58619
+ if (id)
58620
+ icons.push({ kind: "svg-use", id, count: 1 });
58621
+ }
58622
+ for (const svg of Array.from(document.querySelectorAll("svg"))) {
58623
+ if (svg.querySelector("use"))
58624
+ continue;
58625
+ const label = svg.getAttribute("aria-label") || svg.querySelector("title")?.textContent?.trim() || svg.getAttribute("class") || "unnamed";
58626
+ icons.push({ kind: "inline-svg", id: label.slice(0, 40), count: 1 });
58627
+ }
58628
+ const iconClassRe = /\b(icon(?![a-z])|fa-[a-z0-9-]+|material-icons|ph-[a-z0-9-]+|glyphicon-[a-z0-9-]+)\b/i;
58629
+ for (const el of Array.from(document.querySelectorAll("i, span"))) {
58630
+ const cls = el.getAttribute("class") ?? "";
58631
+ const m = cls.match(iconClassRe);
58632
+ if (m?.[1])
58633
+ icons.push({ kind: "icon-font", id: m[1], count: 1 });
58634
+ }
58635
+ return { favicon, appleTouchIcon, manifest, ogImage, fonts, logo, icons };
58636
+ });
58637
+ return { ...raw, icons: aggregateIcons(raw.icons) };
58638
+ }
58639
+ async function browserFetchBytes(page, url) {
58640
+ try {
58641
+ const r = await page.evaluate(async (u) => {
58642
+ const res = await fetch(u);
58643
+ if (!res.ok)
58644
+ return null;
58645
+ const bytes = new Uint8Array(await res.arrayBuffer());
58646
+ let binary = "";
58647
+ for (let i = 0;i < bytes.length; i++)
58648
+ binary += String.fromCharCode(bytes[i]);
58649
+ return { b64: btoa(binary), ct: res.headers.get("content-type") };
58650
+ }, url);
58651
+ if (!r)
58652
+ return null;
58653
+ return { buf: Buffer.from(r.b64, "base64"), contentType: r.ct };
58654
+ } catch {
58655
+ return null;
58656
+ }
58657
+ }
58658
+ async function nodeFetchBytes(url) {
58659
+ try {
58660
+ const res = await fetch(url, { signal: AbortSignal.timeout(15000) });
58661
+ if (!res.ok)
58662
+ return null;
58663
+ return { buf: Buffer.from(await res.arrayBuffer()), contentType: res.headers.get("content-type") };
58664
+ } catch {
58665
+ return null;
58666
+ }
58667
+ }
58668
+ async function downloadTo(url, dir, name, fetchBytes) {
58669
+ const got = await fetchBytes(url);
58670
+ if (!got)
58671
+ return null;
58672
+ const ext = extFromUrlOrType(url, got.contentType);
58673
+ const file = `${name}${ext}`;
58674
+ writeFileSync16(join17(dir, file), got.buf);
58675
+ return `assets/${file}`;
58676
+ }
58677
+ function extFromUrlOrType(url, contentType) {
58678
+ try {
58679
+ const m = new URL(url).pathname.match(/\.[a-z0-9]{2,5}$/i);
58680
+ if (m)
58681
+ return m[0];
58682
+ } catch {}
58683
+ if (contentType?.includes("svg"))
58684
+ return ".svg";
58685
+ if (contentType?.includes("png"))
58686
+ return ".png";
58687
+ if (contentType?.includes("jpeg"))
58688
+ return ".jpg";
58689
+ if (contentType?.includes("webp"))
58690
+ return ".webp";
58691
+ if (contentType?.includes("json"))
58692
+ return ".json";
58693
+ return "";
58694
+ }
58695
+ async function downloadSiteAssets(raw, runDir, fetchBytes) {
58696
+ const dir = join17(runDir, "assets");
58697
+ mkdirSync12(dir, { recursive: true });
58698
+ let logo = null;
58699
+ let logoSource = null;
58700
+ if (raw.logo?.type === "img") {
58701
+ logoSource = raw.logo.url;
58702
+ logo = await downloadTo(raw.logo.url, dir, "logo", fetchBytes);
58703
+ } else if (raw.logo?.type === "svg") {
58704
+ writeFileSync16(join17(dir, "logo.svg"), raw.logo.markup, "utf8");
58705
+ logo = "assets/logo.svg";
58706
+ logoSource = "inline-svg";
58707
+ }
58708
+ const [favicon, appleTouchIcon, ogImage] = await Promise.all([
58709
+ raw.favicon ? downloadTo(raw.favicon, dir, "favicon", fetchBytes) : Promise.resolve(null),
58710
+ raw.appleTouchIcon ? downloadTo(raw.appleTouchIcon, dir, "apple-touch-icon", fetchBytes) : Promise.resolve(null),
58711
+ raw.ogImage ? downloadTo(raw.ogImage, dir, "og-image", fetchBytes) : Promise.resolve(null)
58712
+ ]);
58713
+ const fontsDir = join17(dir, "fonts");
58714
+ mkdirSync12(fontsDir, { recursive: true });
58715
+ const fontFiles = [];
58716
+ for (const [i, url] of raw.fonts.entries()) {
58717
+ const got = await fetchBytes(url);
58718
+ if (!got)
58719
+ continue;
58720
+ const base = safeFontName(url, i);
58721
+ writeFileSync16(join17(fontsDir, base), got.buf);
58722
+ fontFiles.push(`assets/fonts/${base}`);
58723
+ }
58724
+ return {
58725
+ logo,
58726
+ logoSource,
58727
+ favicon,
58728
+ faviconSource: raw.favicon,
58729
+ appleTouchIcon,
58730
+ ogImage,
58731
+ manifest: raw.manifest,
58732
+ fonts: raw.fonts,
58733
+ fontFiles,
58734
+ icons: raw.icons
58735
+ };
58736
+ }
58737
+ function safeFontName(url, i) {
58738
+ try {
58739
+ const base = new URL(url).pathname.split("/").pop() ?? "";
58740
+ if (/^[\w.-]+\.(woff2?|ttf|otf)$/i.test(base))
58741
+ return base;
58742
+ const ext = base.match(/\.(woff2?|ttf|otf)$/i)?.[0] ?? ".woff2";
58743
+ return `font-${i}${ext}`;
58744
+ } catch {
58745
+ return `font-${i}.woff2`;
58746
+ }
58747
+ }
58748
+
58749
+ // src/migrate/browser-fetch.ts
58750
+ async function browserFetchText(page, url) {
58751
+ try {
58752
+ const text3 = await page.evaluate(async (u) => {
58753
+ const res = await fetch(u);
58754
+ if (!res.ok)
58755
+ return null;
58756
+ return res.text();
58757
+ }, url);
58758
+ if (text3 != null)
58759
+ return text3;
58760
+ } catch {}
58761
+ return nodeFetchText(url);
58762
+ }
58763
+ async function nodeFetchText(url) {
58764
+ try {
58765
+ const res = await fetch(url, {
58766
+ headers: {
58767
+ "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"
58768
+ },
58769
+ signal: AbortSignal.timeout(15000)
58770
+ });
58771
+ if (!res.ok)
58772
+ return null;
58773
+ return await res.text();
58774
+ } catch {
58775
+ return null;
58776
+ }
58777
+ }
58778
+
58779
+ // src/migrate/bundle.ts
58780
+ init_esm10();
58781
+ init_html_compact();
58782
+
58783
+ // src/migrate/tailwind.ts
58784
+ var SPACING = {
58785
+ "0px": "0",
58786
+ "2px": "0.5",
58787
+ "4px": "1",
58788
+ "6px": "1.5",
58789
+ "8px": "2",
58790
+ "10px": "2.5",
58791
+ "12px": "3",
58792
+ "14px": "3.5",
58793
+ "16px": "4",
58794
+ "20px": "5",
58795
+ "24px": "6",
58796
+ "28px": "7",
58797
+ "32px": "8",
58798
+ "36px": "9",
58799
+ "40px": "10",
58800
+ "44px": "11",
58801
+ "48px": "12",
58802
+ "56px": "14",
58803
+ "64px": "16",
58804
+ "80px": "20",
58805
+ "96px": "24"
58806
+ };
58807
+ var FONT_SIZE = {
58808
+ "12px": "text-xs",
58809
+ "14px": "text-sm",
58810
+ "16px": "text-base",
58811
+ "18px": "text-lg",
58812
+ "20px": "text-xl",
58813
+ "24px": "text-2xl",
58814
+ "30px": "text-3xl",
58815
+ "36px": "text-4xl",
58816
+ "48px": "text-5xl",
58817
+ "60px": "text-6xl",
58818
+ "72px": "text-7xl",
58819
+ "96px": "text-8xl",
58820
+ "128px": "text-9xl"
58821
+ };
58822
+ var FONT_WEIGHT = {
58823
+ "100": "font-thin",
58824
+ "200": "font-extralight",
58825
+ "300": "font-light",
58826
+ "400": "font-normal",
58827
+ "500": "font-medium",
58828
+ "600": "font-semibold",
58829
+ "700": "font-bold",
58830
+ "800": "font-extrabold",
58831
+ "900": "font-black"
58832
+ };
58833
+ var RADIUS = {
58834
+ "0px": "rounded-none",
58835
+ "2px": "rounded-sm",
58836
+ "4px": "rounded",
58837
+ "6px": "rounded-md",
58838
+ "8px": "rounded-lg",
58839
+ "12px": "rounded-xl",
58840
+ "16px": "rounded-2xl",
58841
+ "24px": "rounded-3xl",
58842
+ "9999px": "rounded-full"
58843
+ };
58844
+ var DISPLAY = {
58845
+ flex: "flex",
58846
+ "inline-flex": "inline-flex",
58847
+ grid: "grid",
58848
+ "inline-grid": "inline-grid",
58849
+ block: "block",
58850
+ "inline-block": "inline-block",
58851
+ inline: "inline",
58852
+ none: "hidden"
58853
+ };
58854
+ var FLEX_DIR = {
58855
+ row: "flex-row",
58856
+ "row-reverse": "flex-row-reverse",
58857
+ column: "flex-col",
58858
+ "column-reverse": "flex-col-reverse"
58859
+ };
58860
+ var JUSTIFY = {
58861
+ "flex-start": "justify-start",
58862
+ "flex-end": "justify-end",
58863
+ center: "justify-center",
58864
+ "space-between": "justify-between",
58865
+ "space-around": "justify-around",
58866
+ "space-evenly": "justify-evenly"
58867
+ };
58868
+ var ALIGN = {
58869
+ "flex-start": "items-start",
58870
+ "flex-end": "items-end",
58871
+ center: "items-center",
58872
+ baseline: "items-baseline",
58873
+ stretch: "items-stretch"
58874
+ };
58875
+ var TEXT_TRANSFORM = {
58876
+ uppercase: "uppercase",
58877
+ lowercase: "lowercase",
58878
+ capitalize: "capitalize"
58879
+ };
58880
+ var POSITION = {
58881
+ relative: "relative",
58882
+ absolute: "absolute",
58883
+ fixed: "fixed",
58884
+ sticky: "sticky"
58885
+ };
58886
+ var OVERFLOW = {
58887
+ hidden: "overflow-hidden",
58888
+ auto: "overflow-auto",
58889
+ scroll: "overflow-scroll"
58890
+ };
58891
+ function normalizeColor(value) {
58892
+ return value.trim().replace(/\s+/g, "");
58893
+ }
58894
+ function spacingClass(prefix, value) {
58895
+ const step = SPACING[value.trim()];
58896
+ return step !== undefined ? `${prefix}-${step}` : `${prefix}-[${value.trim()}]`;
58897
+ }
58898
+ function boxSpacing(prop2, value) {
58899
+ const parts = value.trim().split(/\s+/);
58900
+ if (parts.length === 1 && parts[0])
58901
+ return [spacingClass(prop2, parts[0])];
58902
+ if (parts.length === 2 && parts[0] && parts[1]) {
58903
+ return [spacingClass(`${prop2}y`, parts[0]), spacingClass(`${prop2}x`, parts[1])];
58904
+ }
58905
+ return [];
58906
+ }
58907
+ function sizeClass(prefix, value) {
58908
+ const v = value.trim();
58909
+ if (v === "auto" || v === "")
58910
+ return null;
58911
+ if (v === "100%")
58912
+ return `${prefix}-full`;
58913
+ if (prefix === "w" && v === "100vw")
58914
+ return "w-screen";
58915
+ if (prefix === "h" && v === "100vh")
58916
+ return "h-screen";
58917
+ const step = SPACING[v];
58918
+ return step !== undefined ? `${prefix}-${step}` : `${prefix}-[${v}]`;
58919
+ }
58920
+ function colorClass(prefix, value, tokenByValue) {
58921
+ const v = value.trim();
58922
+ if (!v || v === "transparent" || v === "rgba(0, 0, 0, 0)" || v === "currentcolor")
58923
+ return null;
58924
+ const token = tokenByValue.get(v);
58925
+ if (token)
58926
+ return `${prefix}-${token}`;
58927
+ return `${prefix}-[${normalizeColor(v)}]`;
58928
+ }
58929
+ function stylesToTailwind(styles, themeTokens) {
58930
+ const tokenByValue = new Map;
58931
+ if (themeTokens) {
58932
+ for (const [token, value] of Object.entries(themeTokens)) {
58933
+ tokenByValue.set(value.trim(), token);
58934
+ }
58935
+ }
58936
+ const out = [];
58937
+ const push = (c) => {
58938
+ if (c && !out.includes(c))
58939
+ out.push(c);
58940
+ };
58941
+ const g = (k) => (styles[k] ?? "").trim();
58942
+ const display = g("display");
58943
+ push(DISPLAY[display]);
58944
+ if (display === "flex" || display === "inline-flex") {
58945
+ push(FLEX_DIR[g("flex-direction")]);
58946
+ }
58947
+ push(JUSTIFY[g("justify-content")]);
58948
+ push(ALIGN[g("align-items")]);
58949
+ const gap = g("gap");
58950
+ if (gap && gap !== "normal")
58951
+ push(spacingClass("gap", gap.split(/\s+/)[0] ?? gap));
58952
+ for (const c of boxSpacing("p", g("padding")))
58953
+ push(c);
58954
+ for (const c of boxSpacing("m", g("margin")))
58955
+ push(c);
58956
+ push(sizeClass("w", g("width")));
58957
+ push(sizeClass("h", g("height")));
58958
+ push(FONT_SIZE[g("font-size")] ?? (g("font-size") ? `text-[${g("font-size")}]` : null));
58959
+ push(FONT_WEIGHT[g("font-weight")]);
58960
+ push(TEXT_TRANSFORM[g("text-transform")]);
58961
+ push(colorClass("text", g("color"), tokenByValue));
58962
+ push(colorClass("bg", g("background-color"), tokenByValue));
58963
+ const radius = g("border-radius");
58964
+ if (radius)
58965
+ push(RADIUS[radius] ?? `rounded-[${radius}]`);
58966
+ const shadow = g("box-shadow");
58967
+ if (shadow && shadow !== "none")
58968
+ push("shadow");
58969
+ push(POSITION[g("position")]);
58970
+ push(OVERFLOW[g("overflow")]);
58971
+ return out;
58972
+ }
58973
+
58974
+ // src/migrate/bundle.ts
58975
+ var GLOBAL_ROLE_PREFIXES = ["header", "footer", "nav", "minicart"];
58976
+ function isGlobalRole(role) {
58977
+ const r = role.toLowerCase();
58978
+ return GLOBAL_ROLE_PREFIXES.some((p) => r === p || r.startsWith(`${p}-`));
58979
+ }
58980
+ function toMigratedComponent(c, interactions, scope, themeTokens, repeated) {
58981
+ return {
58982
+ ...c,
58983
+ tailwind: stylesToTailwind(c.computedStyles ?? {}, themeTokens),
58984
+ interactions,
58985
+ scope,
58986
+ ...repeated && repeated > 1 ? { repeated } : {}
58987
+ };
58988
+ }
58989
+ function planComponentDedup(items) {
58990
+ const firstAt = new Map;
58991
+ const plan = [];
58992
+ items.forEach((item, index2) => {
58993
+ const key = `${item.role}\x00${item.signature}`;
58994
+ const existing = firstAt.get(key);
58995
+ if (existing === undefined) {
58996
+ firstAt.set(key, plan.length);
58997
+ plan.push({ index: index2, repeated: 1 });
58998
+ } else {
58999
+ plan[existing].repeated += 1;
59000
+ }
59001
+ });
59002
+ return plan;
59003
+ }
59004
+ var COLLAPSE_THRESHOLD = 3;
59005
+ function dedupeRepeatedChildren(html3) {
59006
+ let collapsed = 0;
59007
+ try {
59008
+ const $2 = load(html3, null, false);
59009
+ $2("*").each((_, parent2) => {
59010
+ const children2 = $2(parent2).children().toArray();
59011
+ if (children2.length < COLLAPSE_THRESHOLD)
59012
+ return;
59013
+ const groups = new Map;
59014
+ for (const child of children2) {
59015
+ const fp = computeHtmlFingerprint($2.html(child) ?? "");
59016
+ const list = groups.get(fp) ?? [];
59017
+ list.push(child);
59018
+ groups.set(fp, list);
59019
+ }
59020
+ for (const list of groups.values()) {
59021
+ if (list.length < COLLAPSE_THRESHOLD)
59022
+ continue;
59023
+ const [first2, ...rest] = list;
59024
+ for (const el of rest)
59025
+ $2(el).remove();
59026
+ collapsed += rest.length;
59027
+ $2(first2).after(`<!-- ×${list.length} itens idênticos omitidos -->`);
59028
+ }
59029
+ });
59030
+ return { html: $2.html() ?? html3, collapsed };
59031
+ } catch {
59032
+ return { html: html3, collapsed: 0 };
59033
+ }
59034
+ }
59035
+ var COMPONENT_HTML_MAX_CHARS = 6000;
59036
+ function compactComponentHtml(html3, maxChars = COMPONENT_HTML_MAX_CHARS) {
59037
+ let stripped = html3;
59038
+ try {
59039
+ const $2 = load(html3);
59040
+ $2("script, style, noscript, svg, template, link[rel='stylesheet']").remove();
59041
+ $2("*").each((_, node2) => {
59042
+ const attrs = node2.attribs;
59043
+ if (!attrs)
59044
+ return;
59045
+ for (const name of Object.keys(attrs)) {
59046
+ if (name === "style") {
59047
+ delete attrs[name];
59048
+ continue;
59049
+ }
59050
+ if (/^data-(event|track|analytics)/.test(name) && (attrs[name]?.length ?? 0) > 100) {
59051
+ attrs[name] = "[…]";
59052
+ }
59053
+ if ((name === "src" || name === "srcset") && attrs[name]?.startsWith("data:")) {
59054
+ attrs[name] = "[data-uri]";
59055
+ }
59056
+ }
59057
+ if (attrs.class) {
59058
+ const kept = attrs.class.split(/\s+/).filter((t) => t && isSemanticClassToken(t));
59059
+ if (kept.length)
59060
+ attrs.class = kept.join(" ");
59061
+ else
59062
+ delete attrs.class;
59063
+ }
59064
+ });
59065
+ stripped = $2.html() ?? html3;
59066
+ } catch {}
59067
+ const { html: deduped, collapsed } = dedupeRepeatedChildren(stripped);
59068
+ const truncated = deduped.length > maxChars;
59069
+ return {
59070
+ html: truncated ? `${deduped.slice(0, maxChars)}
59071
+ <!-- TRUNCATED -->` : deduped,
59072
+ collapsed,
59073
+ truncated
59074
+ };
59075
+ }
59076
+
59077
+ // src/migrate/exporters/json.ts
59078
+ import { writeFileSync as writeFileSync17 } from "node:fs";
59079
+ import { join as join18 } from "node:path";
59080
+ var jsonExporter2 = {
59081
+ name: "json",
59082
+ async export(bundle, outDir) {
59083
+ writeFileSync17(join18(outDir, "manifest.json"), `${JSON.stringify(bundle, null, 2)}
59084
+ `, "utf8");
59085
+ }
59086
+ };
59087
+
59088
+ // src/migrate/exporters/markdown.ts
59089
+ import { mkdirSync as mkdirSync13, writeFileSync as writeFileSync18 } from "node:fs";
59090
+ import { join as join19 } from "node:path";
59091
+ var markdownExporter2 = {
59092
+ name: "markdown",
59093
+ async export(bundle, outDir) {
59094
+ const dirNames = bundle.components.map((c, i) => componentDirName(c.role, i + 1));
59095
+ const notes = [];
59096
+ bundle.components.forEach((component, i) => {
59097
+ const dirName = dirNames[i];
59098
+ const componentDir = join19(outDir, "components", dirName);
59099
+ mkdirSync13(componentDir, { recursive: true });
59100
+ const compact = compactComponentHtml(component.html);
59101
+ if (compact.collapsed > 0)
59102
+ notes.push(`\`${dirName}\`: collapsed ${compact.collapsed} repeated child element(s)`);
59103
+ if (compact.truncated)
59104
+ notes.push(`\`${dirName}\`: HTML truncated to fit the per-component token ceiling`);
59105
+ writeFileSync18(join19(componentDir, "README.md"), renderComponentReadme2(bundle.url, component, compact.html), "utf8");
59106
+ });
59107
+ writeFileSync18(join19(outDir, "index.md"), renderIndex2(bundle, dirNames, notes), "utf8");
59108
+ }
59109
+ };
59110
+ function renderIndex2(bundle, dirNames, notes) {
59111
+ const lines = [];
59112
+ const md = lines.push.bind(lines);
59113
+ md(`# Migration snapshot: ${bundle.url}`);
59114
+ md("");
59115
+ md("AI-ready, token-lean snapshot for migrating this storefront. Theme + component");
59116
+ md("map below; per-component detail (Tailwind, interactions, e2e selectors) lives in");
59117
+ md("each `components/<folder>/README.md`. Full raw HTML/CSS is in `manifest.json`.");
59118
+ md("");
59119
+ md("## Site");
59120
+ md("");
59121
+ md(`- **URL**: ${bundle.url}`);
59122
+ md(`- **Source platform**: ${bundle.platform}`);
59123
+ if (bundle.target)
59124
+ md(`- **Target**: ${bundle.target} (see MIGRATION_PROMPT.md)`);
59125
+ md(`- **Captured**: ${bundle.timestamp} (${bundle.viewport})`);
59126
+ md(`- **Pages**: ${bundle.pages.map((p) => `${p.kind} \`${p.path}\``).join(", ") || "—"}`);
59127
+ md("");
59128
+ if (bundle.screenshots?.length) {
59129
+ md("## Screenshots by viewport");
59130
+ md("");
59131
+ for (const s of bundle.screenshots)
59132
+ md(`- **${s.viewport}**: ![${s.viewport}](${s.path})`);
59133
+ md("");
59134
+ }
59135
+ renderTheme(md, bundle.theme);
59136
+ renderAssets(md, bundle.assets);
59137
+ if (bundle.vtex) {
59138
+ md("## VTEX IO → FastStore blocks");
59139
+ md("");
59140
+ md(`_${bundle.vtex.blocks.length} block instances from the store runtime · ${bundle.vtex.blocks.filter((x) => x.props).length} carry CMS content (props) → \`blocks.json\`. \`confidence\` (0–1) = how sure the deterministic mapper is; \`custom-component\` = build from captured DOM/CSS. See component-map.json._`);
59141
+ md("");
59142
+ md("| VTEX block | → FastStore | confidence | count |");
59143
+ md("|---|---|---|---|");
59144
+ for (const m of bundle.vtex.map.slice(0, 40)) {
59145
+ md(`| \`${m.vtex}\` | ${m.faststore ? `\`${m.faststore}\`` : "_custom-component_"} | ${m.confidence || "—"} | ${m.count} |`);
59146
+ }
59147
+ md("");
59148
+ }
59149
+ md("## Components");
59150
+ md("");
59151
+ md("| Scope | Role | e2e keys | Folder |");
59152
+ md("|---|---|---|---|");
59153
+ bundle.components.forEach((c, i) => {
59154
+ const keys = c.interactions.map((x) => x.e2eKey).filter((k) => Boolean(k));
59155
+ const uniqueKeys = [...new Set(keys)];
59156
+ const roleCell = c.repeated && c.repeated > 1 ? `\`${c.role}\` ×${c.repeated}` : `\`${c.role}\``;
59157
+ md(`| ${c.scope} | ${roleCell} | ${uniqueKeys.length ? uniqueKeys.map((k) => `\`${k}\``).join(", ") : "—"} | [${dirNames[i]}](./components/${dirNames[i]}/README.md) |`);
59158
+ });
59159
+ md("");
59160
+ if (notes.length) {
59161
+ md("## Compaction notes");
59162
+ md("");
59163
+ md("_The lean artifact shrank these components; the full data is in `manifest.json`._");
59164
+ md("");
59165
+ for (const n of notes)
59166
+ md(`- ${n}`);
59167
+ md("");
59168
+ }
59169
+ return lines.join(`
59170
+ `);
59171
+ }
59172
+ function renderTheme(md, theme) {
59173
+ md("## Theme");
59174
+ md("");
59175
+ md("| Token | Value |");
59176
+ md("|---|---|");
59177
+ for (const [token, value] of Object.entries(theme.tokens)) {
59178
+ md(`| \`${token}\` | \`${value}\` |`);
59179
+ }
59180
+ md("");
59181
+ md(`- **Fonts**: ${listOrNone2(theme.typography.fontFamilies)}`);
59182
+ md(`- **Font sizes**: ${listOrNone2(theme.typography.sizeScale)}`);
59183
+ md(`- **Spacing scale**: ${listOrNone2(theme.spacingScale)}`);
59184
+ md(`- **Radii**: ${listOrNone2(theme.radii)}`);
59185
+ md(`- **Breakpoints**: ${listOrNone2(theme.breakpoints)}`);
59186
+ md(`- **Motion**: durations ${listOrNone2(theme.motion.durations)} · easings ${listOrNone2(theme.motion.easings)}`);
59187
+ md(`- **Shadows**: ${theme.shadows.length}`);
59188
+ md("");
59189
+ }
59190
+ function renderAssets(md, assets) {
59191
+ md("## Brand assets");
59192
+ md("");
59193
+ md(`- **Logo**: ${assets.logo ? `\`${assets.logo}\`${assets.logoSource ? ` (from ${assets.logoSource})` : ""}` : "_not found_"}`);
59194
+ md(`- **Favicon**: ${assets.favicon ? `\`${assets.favicon}\`` : "_not found_"}`);
59195
+ md(`- **Apple touch icon**: ${assets.appleTouchIcon ? `\`${assets.appleTouchIcon}\`` : "—"}`);
59196
+ md(`- **OG image**: ${assets.ogImage ? `\`${assets.ogImage}\`` : "—"}`);
59197
+ md(`- **Web app manifest**: ${assets.manifest ? assets.manifest : "—"}`);
59198
+ md(`- **Web fonts**: ${assets.fontFiles.length}/${assets.fonts.length} downloaded${assets.fontFiles.length ? ` → ${listOrNone2(assets.fontFiles)}` : ""}`);
59199
+ md("");
59200
+ if (assets.icons.length) {
59201
+ md(`## Icons (${assets.icons.length})`);
59202
+ md("");
59203
+ md("_Map these to the target's icon set (e.g. FastStore uses Phosphor `<Icon>`)._");
59204
+ md("");
59205
+ md("| Kind | Id | Count |");
59206
+ md("|---|---|---|");
59207
+ for (const icon of assets.icons.slice(0, 60)) {
59208
+ md(`| ${icon.kind} | \`${escapePipes2(icon.id)}\` | ${icon.count} |`);
59209
+ }
59210
+ md("");
59211
+ }
59212
+ }
59213
+ function renderComponentReadme2(url, c, compactHtml) {
59214
+ const lines = [];
59215
+ const md = lines.push.bind(lines);
59216
+ md(`# Component: \`${c.role}\` (${c.scope})`);
59217
+ md("");
59218
+ if (c.repeated && c.repeated > 1) {
59219
+ md(`> ${c.repeated} structurally-identical instances on the page — one shown here.`);
59220
+ md("");
59221
+ }
59222
+ md(`- **Site**: ${url}`);
59223
+ md(`- **Selector**: \`${c.selector}\``);
59224
+ md(`- **Screenshot**: ![${c.role}](screenshot.png)`);
59225
+ md("");
59226
+ md("## Tailwind (suggested)");
59227
+ md("");
59228
+ md(c.tailwind.length ? `\`\`\`
59229
+ ${c.tailwind.join(" ")}
59230
+ \`\`\`` : "_none inferred_");
59231
+ md("");
59232
+ if (c.interactions.length) {
59233
+ md("## Interactions & e2e selectors");
59234
+ md("");
59235
+ md("| Selector | Kind | Label | e2e key | States |");
59236
+ md("|---|---|---|---|---|");
59237
+ for (const it of c.interactions) {
59238
+ const states = [
59239
+ it.hasHoverRule ? "hover" : "",
59240
+ it.hasFocusRule ? "focus" : "",
59241
+ it.animation ? "anim" : ""
59242
+ ].filter(Boolean).join(", ");
59243
+ md(`| \`${escapePipes2(it.selector)}\` | ${it.kind} | ${escapePipes2(it.label) || "—"} | ${it.e2eKey ? `\`${it.e2eKey}\`` : "—"} | ${states || "—"} |`);
59244
+ }
59245
+ md("");
59246
+ }
59247
+ md("## Assets");
59248
+ md("");
59249
+ md(`- **Images** (${c.assets.images.length}): ${listOrNone2(c.assets.images)}`);
59250
+ md(`- **Fonts**: ${listOrNone2(c.assets.fonts)}`);
59251
+ md("");
59252
+ if (c.textContent.length) {
59253
+ md("## Notable text");
59254
+ md("");
59255
+ for (const t of c.textContent.slice(0, 15))
59256
+ md(`- ${t}`);
59257
+ md("");
59258
+ }
59259
+ md("## HTML (compacted)");
59260
+ md("");
59261
+ md("```html");
59262
+ md(compactHtml);
59263
+ md("```");
59264
+ md("");
59265
+ return lines.join(`
59266
+ `);
59267
+ }
59268
+ function listOrNone2(items) {
59269
+ if (items.length === 0)
59270
+ return "_none_";
59271
+ return items.slice(0, 10).map((i) => `\`${i}\``).join(", ");
59272
+ }
59273
+ function escapePipes2(s) {
59274
+ return s.replace(/\|/g, "\\|");
59275
+ }
59276
+
59277
+ // src/migrate/exporters/html.ts
59278
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync19 } from "node:fs";
59279
+ import { join as join20 } from "node:path";
59280
+ var htmlExporter = {
59281
+ name: "html",
59282
+ async export(bundle, outDir) {
59283
+ writeFileSync19(join20(outDir, "index.html"), renderHtml(bundle, (p) => p ?? null), "utf8");
59284
+ const inline = (p) => p ? dataUri(join20(outDir, p)) ?? p : null;
59285
+ writeFileSync19(join20(outDir, "report.html"), renderHtml(bundle, inline), "utf8");
59286
+ }
59287
+ };
59288
+ var MIME = {
59289
+ ".png": "image/png",
59290
+ ".jpg": "image/jpeg",
59291
+ ".jpeg": "image/jpeg",
59292
+ ".webp": "image/webp",
59293
+ ".gif": "image/gif",
59294
+ ".svg": "image/svg+xml",
59295
+ ".ico": "image/x-icon"
59296
+ };
59297
+ function dataUri(absPath) {
59298
+ try {
59299
+ const ext = absPath.slice(absPath.lastIndexOf(".")).toLowerCase();
59300
+ const mime = MIME[ext];
59301
+ if (!mime)
59302
+ return null;
59303
+ return `data:${mime};base64,${readFileSync13(absPath).toString("base64")}`;
59304
+ } catch {
59305
+ return null;
59306
+ }
59307
+ }
59308
+ function esc(s) {
59309
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
59310
+ }
59311
+ function swatch(label, value) {
59312
+ if (!value)
59313
+ return `<div class="sw"><div class="chip empty"></div><b>${label}</b><span>—</span></div>`;
59314
+ return `<div class="sw"><div class="chip" style="background:${esc(value)}"></div><b>${label}</b><span>${esc(value)}</span></div>`;
59315
+ }
59316
+ function chips(items) {
59317
+ return items.length ? items.map((i) => `<code>${esc(i)}</code>`).join(" ") : "<em>none</em>";
59318
+ }
59319
+ function renderHtml(b, embed) {
59320
+ const t = b.theme;
59321
+ const shots = (b.screenshots ?? []).map((s) => {
59322
+ const src = embed(s.path);
59323
+ return src ? `<figure><figcaption>${esc(s.viewport)}</figcaption><img src="${esc(src)}" alt="${esc(s.viewport)}"></figure>` : "";
59324
+ }).join("");
59325
+ const componentRows = b.components.map((c, i) => {
59326
+ const keys = [...new Set(c.interactions.map((x) => x.e2eKey).filter(Boolean))];
59327
+ const folder = componentDirName(c.role, i + 1);
59328
+ return `<tr><td>${esc(c.scope)}</td><td><code>${esc(c.role)}</code>${c.repeated && c.repeated > 1 ? ` <span class="badge">×${c.repeated}</span>` : ""}</td><td>${c.tailwind.length}</td><td>${c.interactions.length}</td><td>${keys.length ? keys.map((k) => `<code>${esc(String(k))}</code>`).join(" ") : "—"}</td><td><a href="components/${esc(folder)}/README.md">${esc(folder)}</a></td></tr>`;
59329
+ }).join("");
59330
+ const vtexRows = b.vtex ? b.vtex.map.slice(0, 80).map((m) => `<tr><td><code>${esc(m.vtex)}</code></td><td>${m.faststore ? `<code>${esc(m.faststore)}</code>` : "<em>custom-component</em>"}</td><td>${m.confidence || "—"}</td><td>${m.count}</td></tr>`).join("") : "";
59331
+ const iconRows = t && b.assets.icons.length ? b.assets.icons.slice(0, 40).map((ic) => `<tr><td>${esc(ic.kind)}</td><td><code>${esc(ic.id)}</code></td><td>${ic.count}</td></tr>`).join("") : "";
59332
+ return `<!doctype html>
59333
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
59334
+ <title>parity migrate — ${esc(b.url)}</title>
59335
+ <style>
59336
+ :root { --bg:#0d1117; --card:#161b22; --line:#30363d; --fg:#e6edf3; --dim:#8b949e; --accent:#2f81f7; }
59337
+ * { box-sizing:border-box; }
59338
+ body { margin:0; background:var(--bg); color:var(--fg); font:14px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif; }
59339
+ header { padding:24px 32px; border-bottom:1px solid var(--line); }
59340
+ h1 { margin:0 0 6px; font-size:20px; }
59341
+ h2 { font-size:15px; text-transform:uppercase; letter-spacing:.04em; color:var(--dim); margin:0 0 12px; }
59342
+ .meta { color:var(--dim); font-size:13px; }
59343
+ .meta code { color:var(--fg); }
59344
+ main { padding:24px 32px; max-width:1100px; margin:0 auto; display:grid; gap:24px; }
59345
+ .card { background:var(--card); border:1px solid var(--line); border-radius:10px; padding:20px; }
59346
+ .swatches { display:flex; gap:20px; flex-wrap:wrap; }
59347
+ .sw { display:flex; flex-direction:column; gap:4px; }
59348
+ .sw b { font-size:12px; } .sw span { color:var(--dim); font-size:12px; font-family:monospace; }
59349
+ .chip { width:64px; height:64px; border-radius:8px; border:1px solid var(--line); }
59350
+ .chip.empty { background:repeating-linear-gradient(45deg,#222,#222 6px,#333 6px,#333 12px); }
59351
+ figure { margin:0; } figure img { max-width:100%; border:1px solid var(--line); border-radius:8px; display:block; }
59352
+ figcaption { color:var(--dim); font-size:12px; margin-bottom:6px; text-transform:capitalize; }
59353
+ .shots { display:grid; grid-template-columns:repeat(auto-fit,minmax(280px,1fr)); gap:16px; }
59354
+ table { width:100%; border-collapse:collapse; font-size:13px; }
59355
+ th,td { text-align:left; padding:6px 10px; border-bottom:1px solid var(--line); vertical-align:top; }
59356
+ th { color:var(--dim); font-weight:600; }
59357
+ code { background:#0b0f14; padding:1px 5px; border-radius:4px; font-size:12px; }
59358
+ a { color:var(--accent); text-decoration:none; } a:hover { text-decoration:underline; }
59359
+ .badge { background:#1f6feb33; color:#79c0ff; padding:0 6px; border-radius:10px; font-size:11px; }
59360
+ .assets { display:flex; gap:24px; align-items:center; flex-wrap:wrap; }
59361
+ .assets img { max-height:48px; max-width:200px; background:#fff; padding:6px; border-radius:6px; }
59362
+ ul.kv { list-style:none; padding:0; margin:0; display:grid; gap:6px; }
59363
+ .links a { margin-right:16px; }
59364
+ .dim { color:var(--dim); }
59365
+ </style></head>
59366
+ <body>
59367
+ <header>
59368
+ <h1>parity migrate — ${esc(b.url)}</h1>
59369
+ <div class="meta">
59370
+ <code>${esc(b.platform)}</code>${b.target ? ` → <code>${esc(b.target)}</code>` : ""}
59371
+ · viewports: <code>${esc((b.viewports ?? [b.viewport]).join(", "))}</code>
59372
+ · pages: ${b.pages.map((p) => `<code>${esc(p.kind)}</code>`).join(" ") || "—"}
59373
+ · <span class="dim">${esc(b.timestamp)}</span>
59374
+ </div>
59375
+ </header>
59376
+ <main>
59377
+
59378
+ <section class="card">
59379
+ <h2>Theme</h2>
59380
+ <div class="swatches">
59381
+ ${swatch("primary", t.colors.primary)}
59382
+ ${swatch("secondary", t.colors.secondary)}
59383
+ ${swatch("background", t.colors.background)}
59384
+ ${swatch("text", t.colors.text)}
59385
+ </div>
59386
+ <ul class="kv" style="margin-top:16px">
59387
+ <li><b>Fonts:</b> ${chips(t.typography.fontFamilies)}</li>
59388
+ <li><b>Font sizes:</b> ${chips(t.typography.sizeScale)}</li>
59389
+ <li><b>Spacing:</b> ${chips(t.spacingScale)}</li>
59390
+ <li><b>Radii:</b> ${chips(t.radii)}</li>
59391
+ <li><b>Breakpoints:</b> ${chips(t.breakpoints)}</li>
59392
+ <li><b>Motion:</b> ${chips([...t.motion.durations, ...t.motion.easings])}</li>
59393
+ </ul>
59394
+ </section>
59395
+
59396
+ ${shots ? `<section class="card"><h2>Screenshots by viewport</h2><div class="shots">${shots}</div></section>` : ""}
59397
+
59398
+ <section class="card">
59399
+ <h2>Brand assets</h2>
59400
+ <div class="assets">
59401
+ ${(() => {
59402
+ const s = embed(b.assets.logo);
59403
+ return s ? `<div><div class="dim">logo</div><img src="${esc(s)}" alt="logo"></div>` : '<span class="dim">no logo</span>';
59404
+ })()}
59405
+ ${(() => {
59406
+ const s = embed(b.assets.favicon);
59407
+ return s ? `<div><div class="dim">favicon</div><img src="${esc(s)}" alt="favicon" style="max-height:32px"></div>` : "";
59408
+ })()}
59409
+ <div class="dim">${b.assets.icons.length} icons · ${b.assets.fontFiles.length}/${b.assets.fonts.length} web fonts downloaded${b.assets.fontFiles.length ? " → assets/fonts/" : ""}</div>
59410
+ </div>
59411
+ ${iconRows ? `<table style="margin-top:16px"><tr><th>kind</th><th>id</th><th>count</th></tr>${iconRows}</table>` : ""}
59412
+ </section>
59413
+
59414
+ ${b.vtex ? `<section class="card"><h2>VTEX IO → FastStore blocks</h2><p class="dim">${b.vtex.blocks.length} block instances from the store runtime · ${b.vtex.blocks.filter((x) => x.props).length} carry CMS content (props) → see <code>blocks.json</code>. <b>confidence</b> = how sure the deterministic mapper is (0–1).</p><table><tr><th>VTEX block</th><th>→ FastStore</th><th>confidence</th><th>count</th></tr>${vtexRows}</table></section>` : ""}
59415
+
59416
+ <section class="card">
59417
+ <h2>Components (${b.components.length})</h2>
59418
+ <table>
59419
+ <tr><th>scope</th><th>role</th><th>tw</th><th>interactions</th><th>e2e keys</th><th>folder</th></tr>
59420
+ ${componentRows}
59421
+ </table>
59422
+ </section>
59423
+
59424
+ <section class="card links">
59425
+ <h2>Files</h2>
59426
+ <a href="MIGRATION_PROMPT.md">MIGRATION_PROMPT.md</a>
59427
+ <a href="index.md">index.md</a>
59428
+ ${b.target === "faststore" ? '<a href="custom-theme.scss">custom-theme.scss</a>' : ""}
59429
+ ${b.vtex ? '<a href="component-map.json">component-map.json</a> <a href="blocks.json">blocks.json</a>' : ""}
59430
+ <a href="manifest.json">manifest.json (full)</a>
59431
+ </section>
59432
+
59433
+ </main></body></html>`;
59434
+ }
59435
+
59436
+ // src/migrate/prompt.ts
59437
+ function buildMigrationPrompt(bundle, playbook) {
59438
+ const lines = [];
59439
+ const md = lines.push.bind(lines);
59440
+ md(`# Migration prompt: ${bundle.url}`);
59441
+ md("");
59442
+ md("You are migrating this storefront to a new framework. This folder is an");
59443
+ md("AI-ready snapshot of the live site — theme, page structure, and per-component");
59444
+ md("detail (suggested Tailwind classes, interaction hints, e2e selectors).");
59445
+ md("");
59446
+ md(`- **Source platform**: ${bundle.platform}`);
59447
+ md(`- **Captured**: ${bundle.timestamp} (${bundle.viewport})`);
59448
+ md(`- **Pages**: ${bundle.pages.map((p) => `${p.kind} (${p.path})`).join(", ") || "—"}`);
59449
+ md("");
59450
+ md("## How to work");
59451
+ md("");
59452
+ md("1. Read `index.md` for the theme tokens and the component map.");
59453
+ md("2. Start with **global** components (header/footer/minicart) — they appear on");
59454
+ md(" every page — then do page components per page kind (home → PLP → PDP).");
59455
+ md("3. For each component, open its `components/<folder>/README.md`: use the");
59456
+ md(" suggested Tailwind classes as the styling source of truth, keep the raw HTML");
59457
+ md(" only as a structure reference, and wire the listed e2e selectors.");
59458
+ md("4. Apply the theme tokens once, globally, then reference them (`bg-primary`).");
59459
+ md("");
59460
+ const globals = bundle.components.filter((c) => c.scope === "global");
59461
+ const pageComps = bundle.components.filter((c) => c.scope === "page");
59462
+ const row = (role, i) => `- \`${role}\` → components/${componentDirName(role, i + 1)}/README.md`;
59463
+ if (globals.length) {
59464
+ md("### Global components");
59465
+ bundle.components.forEach((c, i) => c.scope === "global" && md(row(c.role, i)));
59466
+ md("");
59467
+ }
59468
+ if (pageComps.length) {
59469
+ md("### Page components");
59470
+ bundle.components.forEach((c, i) => c.scope === "page" && md(row(c.role, i)));
59471
+ md("");
59472
+ }
59473
+ if (playbook) {
59474
+ md("---");
59475
+ md("");
59476
+ md(playbook);
59477
+ md("");
59478
+ }
59479
+ return lines.join(`
59480
+ `);
59481
+ }
59482
+
59483
+ // src/migrate/targets/faststore.ts
59484
+ function pickBreakpointTiers(breakpoints) {
59485
+ const px = breakpoints.map((b) => ({ raw: b, n: Number.parseFloat(b) })).filter((b) => Number.isFinite(b.n));
59486
+ const used = new Set;
59487
+ const nearest = (target) => {
59488
+ let best = null;
59489
+ for (const b of px) {
59490
+ if (used.has(b.raw))
59491
+ continue;
59492
+ const d = Math.abs(b.n - target);
59493
+ if (!best || d < best.d)
59494
+ best = { raw: b.raw, d };
59495
+ }
59496
+ if (best)
59497
+ used.add(best.raw);
59498
+ return best?.raw ?? null;
59499
+ };
59500
+ return {
59501
+ phone: nearest(480),
59502
+ tablet: nearest(768),
59503
+ notebook: nearest(1024),
59504
+ desktop: nearest(1280)
59505
+ };
59506
+ }
59507
+ function buildFastStoreTheme(theme) {
59508
+ const lines = [];
59509
+ const put = (token, value) => {
59510
+ if (value)
59511
+ lines.push(` ${token}: ${value};`);
59512
+ };
59513
+ const fonts = theme.typography.fontFamilies;
59514
+ const radii = theme.radii;
59515
+ const bp = theme.breakpoints;
59516
+ put("--fs-color-primary-bkg", theme.colors.primary);
59517
+ put("--fs-color-accent-0", theme.colors.secondary);
59518
+ put("--fs-color-text", theme.colors.text);
59519
+ put("--fs-color-body-bkg", theme.colors.background);
59520
+ put("--fs-text-face-body", fonts[0]);
59521
+ put("--fs-text-face-title", fonts[1] ?? fonts[0]);
59522
+ put("--fs-border-radius-medium", radii[Math.floor(radii.length / 2)]);
59523
+ put("--fs-shadow", theme.shadows[0]);
59524
+ const tiers = pickBreakpointTiers(bp);
59525
+ put("--fs-grid-breakpoint-phone", tiers.phone);
59526
+ put("--fs-grid-breakpoint-tablet", tiers.tablet);
59527
+ put("--fs-grid-breakpoint-notebook", tiers.notebook);
59528
+ put("--fs-grid-breakpoint-desktop", tiers.desktop);
59529
+ return [
59530
+ "// custom-theme.scss — starter generated by `parity migrate --target faststore`.",
59531
+ "// Brand tokens only; adjust and extend against @faststore/ui global tokens.",
59532
+ ".theme {",
59533
+ ...lines,
59534
+ "}",
59535
+ ""
59536
+ ].join(`
59537
+ `);
59538
+ }
59539
+ var faststore = `## Target: VTEX FastStore (v4)
59540
+
59541
+ Generate the migrated storefront as a FastStore v4 project. Do NOT hand-roll the
59542
+ scaffold — use the official CLI, then fill in sections from the components below.
59543
+
59544
+ ### Setup (once)
59545
+ - Requirements + project setup: https://developers.vtex.com/docs/guides/faststore/getting-started-requirements
59546
+ - Project structure overview: https://developers.vtex.com/docs/guides/faststore/project-structure-overview
59547
+ - \`yarn install\` then \`yarn dev\` → dev store at http://localhost:3000
59548
+
59549
+ ### CLI (@faststore/cli)
59550
+ - \`faststore dev\` — local dev server (localhost:3000)
59551
+ - \`faststore build\` — production build
59552
+ - \`faststore generate\` — regenerate schema + TS types after changes
59553
+ - \`faststore cms-sync\` — sync the \`cms/\` folder with the Headless CMS
59554
+
59555
+ ### Styling — IMPORTANT: FastStore does NOT use Tailwind
59556
+ FastStore v4 styles with **SCSS design tokens + \`data-fs-*\` attributes**, not
59557
+ utility classes. The Tailwind classes in each component README are a convenience
59558
+ approximation — treat the **raw computed styles in manifest.json as the source
59559
+ of truth** for exact values. Package split: \`@faststore/components\` (structure/
59560
+ behavior, unstyled) · \`@faststore/ui\` (styles + design tokens) · \`@faststore/core\`
59561
+ (sections/pages).
59562
+
59563
+ - **Theme** → a starter \`custom-theme.scss\` was generated in this snapshot from
59564
+ the extracted brand tokens. Drop it in \`src/themes/\` and refine. Token map used:
59565
+
59566
+ | Extracted | FastStore global token |
59567
+ | --- | --- |
59568
+ | primary | \`--fs-color-primary-bkg\` |
59569
+ | secondary | \`--fs-color-accent-0\` |
59570
+ | text | \`--fs-color-text\` |
59571
+ | background | \`--fs-color-body-bkg\` |
59572
+ | font (body/title) | \`--fs-text-face-body\` / \`--fs-text-face-title\` |
59573
+ | radius | \`--fs-border-radius-medium\` |
59574
+ | shadow | \`--fs-shadow\` |
59575
+ | breakpoints | \`--fs-grid-breakpoint-phone|tablet|notebook|desktop\` |
59576
+
59577
+ Do NOT override \`--fs-spacing-*\`/\`--fs-text-size-*\` (structural scale).
59578
+ Global tokens: https://developers.vtex.com/docs/guides/faststore/global-tokens-overview
59579
+ - **Per-component styling** → override via each component's \`data-fs-*\` attribute
59580
+ in SCSS (e.g. \`[data-fs-product-shelf]\`), not utility classes.
59581
+ Styling a component: https://developers.vtex.com/docs/guides/faststore/using-themes-components
59582
+
59583
+ ### Icons — Phosphor
59584
+ FastStore ships Phosphor icons via the \`<Icon>\` component (\`data-fs-icon\`, \`weight\`
59585
+ prop: thin|light|regular|bold). Map each entry in this snapshot's **icon inventory**
59586
+ to a Phosphor icon id; add any missing ones as custom icons.
59587
+ - Iconography: https://developers.vtex.com/docs/guides/faststore/reference-icons
59588
+ - Adding custom icons: https://developers.vtex.com/docs/guides/faststore/atoms-icon
59589
+
59590
+ ### Brand assets
59591
+ - Logo + favicon (and apple-touch-icon / OG image) were downloaded to \`assets/\`
59592
+ in this snapshot — drop them into the FastStore project's \`public/\` and wire the
59593
+ logo into the Navbar/Header section.
59594
+
59595
+ ### Where components go — section structure
59596
+ Each detected component → a FastStore section:
59597
+ - \`src/components/<SectionName>.tsx\` (the React section)
59598
+ - register it in \`src/components/index.tsx\` (the components entry)
59599
+ - add its schema to \`cms/faststore/sections.json\` (form editors use in the CMS)
59600
+ - **Global components** (header/footer/minicart) render on every page;
59601
+ **page components** (home/PLP/PDP) go into the matching page content type.
59602
+ - After adding/editing sections: \`faststore generate\` then \`faststore cms-sync\`.
59603
+ - Splitting a legacy CMS structure into components/content-types is supported by
59604
+ \`vtex content split-components\` and \`vtex content split-content-types\`.
59605
+ - Creating a section: https://developers.vtex.com/docs/guides/faststore/building-sections-creating-a-new-section
59606
+ - Headless CMS model: https://developers.vtex.com/docs/guides/faststore/headless-cms-overview
59607
+ - Creating sections: https://developers.vtex.com/docs/guides/faststore/creating-a-new-section-and-content-type
59608
+
59609
+ ### e2e
59610
+ Use the suggested selectors (per component, mapped to known commerce keys) to
59611
+ seed Playwright/Cypress smoke tests on the migrated store.`;
59612
+
59613
+ // src/migrate/targets/index.ts
59614
+ var TARGETS = {
59615
+ faststore
59616
+ };
59617
+ function getTargetPlaybook(name) {
59618
+ return Object.hasOwn(TARGETS, name) ? TARGETS[name] : undefined;
59619
+ }
59620
+ var TARGET_NAMES = Object.keys(TARGETS);
59621
+
59622
+ // src/migrate/theme.ts
59623
+ var TRANSPARENT = new Set(["transparent", "rgba(0, 0, 0, 0)", "rgba(0,0,0,0)"]);
59624
+ function parseRgb(color) {
59625
+ const m = color.trim().match(/rgba?\(([^)]+)\)/i);
59626
+ if (!m || !m[1])
59627
+ return null;
59628
+ const parts = m[1].split(",").map((p) => Number.parseFloat(p.trim()));
59629
+ if (parts.length < 3 || parts.some((n) => Number.isNaN(n)))
59630
+ return null;
59631
+ return { r: parts[0], g: parts[1], b: parts[2], a: parts[3] ?? 1 };
59632
+ }
59633
+ function isNeutral(color) {
59634
+ const c = parseRgb(color);
59635
+ if (!c)
59636
+ return false;
59637
+ if (c.a < 0.1)
59638
+ return true;
59639
+ const max = Math.max(c.r, c.g, c.b);
59640
+ const min = Math.min(c.r, c.g, c.b);
59641
+ return max - min < 18;
59642
+ }
59643
+ function rank(values) {
59644
+ const counts = new Map;
59645
+ for (const v of values) {
59646
+ const key = v.trim();
59647
+ if (!key || TRANSPARENT.has(key))
59648
+ continue;
59649
+ counts.set(key, (counts.get(key) ?? 0) + 1);
59650
+ }
59651
+ return new Map([...counts.entries()].sort((a, b) => b[1] - a[1]));
59652
+ }
59653
+ function isPlausibleFontFamily(f) {
59654
+ const v = f.trim();
59655
+ return v.length > 0 && v.length < 120 && !v.includes("=") && !v.includes("&");
59656
+ }
59657
+ function sortByPx(values) {
59658
+ const uniq = [...new Set(values.map((v) => v.trim()).filter(Boolean))];
59659
+ return uniq.sort((a, b) => (Number.parseFloat(a) || 0) - (Number.parseFloat(b) || 0));
59660
+ }
59661
+ function mergeRawThemeSamples(list) {
59662
+ const first2 = list[0];
59663
+ const concat = (key) => list.flatMap((s) => s[key]);
59664
+ return {
59665
+ bodyBackground: first2.bodyBackground,
59666
+ bodyText: first2.bodyText,
59667
+ bodyFontFamily: first2.bodyFontFamily,
59668
+ colors: concat("colors"),
59669
+ backgrounds: concat("backgrounds"),
59670
+ interactiveBackgrounds: concat("interactiveBackgrounds"),
59671
+ fontFamilies: concat("fontFamilies"),
59672
+ fontSizes: concat("fontSizes"),
59673
+ radii: concat("radii"),
59674
+ shadows: concat("shadows"),
59675
+ spacings: concat("spacings"),
59676
+ breakpoints: concat("breakpoints"),
59677
+ motionDurations: concat("motionDurations"),
59678
+ motionEasings: concat("motionEasings")
59679
+ };
59680
+ }
59681
+ function plausibleDuration(d) {
59682
+ const v = d.trim();
59683
+ if (!v || v === "0s" || v === "0ms")
59684
+ return false;
59685
+ const n = Number.parseFloat(v);
59686
+ if (Number.isNaN(n))
59687
+ return false;
59688
+ const seconds = v.endsWith("ms") ? n / 1000 : n;
59689
+ return seconds > 0 && seconds <= 10;
59690
+ }
59691
+ function isOpaque(color) {
59692
+ const c = parseRgb(color);
59693
+ return !c || c.a >= 0.5;
59694
+ }
59695
+ function aggregateTheme(raw) {
59696
+ const paletteRanked = rank([...raw.colors, ...raw.backgrounds]);
59697
+ const chromaticRanked = rank([
59698
+ ...raw.colors,
59699
+ ...raw.backgrounds,
59700
+ ...raw.interactiveBackgrounds
59701
+ ]);
59702
+ const chromatic = [...chromaticRanked.keys()].filter((c) => !isNeutral(c) && isOpaque(c));
59703
+ const primary = chromatic[0] ?? null;
59704
+ const secondary = chromatic.find((c) => c !== primary) ?? null;
59705
+ const tokens = {};
59706
+ if (primary)
59707
+ tokens.primary = primary;
59708
+ if (secondary)
59709
+ tokens.secondary = secondary;
59710
+ const bodyBg = raw.bodyBackground.trim();
59711
+ const background = bodyBg && !TRANSPARENT.has(bodyBg) && isOpaque(bodyBg) ? bodyBg : [...rank(raw.backgrounds).keys()].find((c) => isOpaque(c)) ?? null;
59712
+ if (background)
59713
+ tokens.background = background;
59714
+ if (raw.bodyText)
59715
+ tokens.text = raw.bodyText.trim();
59716
+ const palette = [...paletteRanked.entries()].map(([value, count]) => ({
59717
+ value,
59718
+ count,
59719
+ token: Object.entries(tokens).find(([, v]) => v === value)?.[0] ?? (isNeutral(value) ? "neutral" : "accent")
59720
+ }));
59721
+ return {
59722
+ colors: {
59723
+ primary,
59724
+ secondary,
59725
+ background: tokens.background ?? null,
59726
+ text: tokens.text ?? null,
59727
+ palette
59728
+ },
59729
+ typography: {
59730
+ fontFamilies: [...rank(raw.fontFamilies).keys()].filter(isPlausibleFontFamily),
59731
+ sizeScale: sortByPx(raw.fontSizes)
59732
+ },
59733
+ spacingScale: sortByPx(raw.spacings),
59734
+ radii: sortByPx(raw.radii).filter((r) => r !== "0px"),
59735
+ shadows: [...new Set(raw.shadows.map((s) => s.trim()))].filter((s) => s && s !== "none"),
59736
+ breakpoints: sortByPx([...rank(raw.breakpoints).keys()].slice(0, 14)),
59737
+ motion: {
59738
+ durations: [...new Set(raw.motionDurations.map((d) => d.trim()))].filter(plausibleDuration),
59739
+ easings: [...new Set(raw.motionEasings.map((e) => e.trim()))].filter((e) => e && e !== "ease" && e !== "linear")
59740
+ },
59741
+ tokens
59742
+ };
59743
+ }
59744
+ async function scrapeThemeSamples(page) {
59745
+ return page.evaluate(() => {
59746
+ const cap = 2000;
59747
+ const els = Array.from(document.querySelectorAll("*")).slice(0, cap);
59748
+ const colors = [];
59749
+ const backgrounds = [];
59750
+ const interactiveBackgrounds = [];
59751
+ const fontFamilies = [];
59752
+ const fontSizes = [];
59753
+ const radii = [];
59754
+ const shadows = [];
59755
+ const spacings = [];
59756
+ const motionDurations = [];
59757
+ const motionEasings = [];
59758
+ const transparent = new Set(["transparent", "rgba(0, 0, 0, 0)"]);
59759
+ for (const el of els) {
59760
+ const cs = getComputedStyle(el);
59761
+ colors.push(cs.color);
59762
+ const bg = cs.backgroundColor;
59763
+ if (!transparent.has(bg))
59764
+ backgrounds.push(bg);
59765
+ fontFamilies.push(cs.fontFamily);
59766
+ fontSizes.push(cs.fontSize);
59767
+ if (cs.borderRadius)
59768
+ radii.push(cs.borderRadius);
59769
+ if (cs.boxShadow && cs.boxShadow !== "none")
59770
+ shadows.push(cs.boxShadow);
59771
+ if (cs.gap && cs.gap !== "normal")
59772
+ spacings.push(cs.gap.split(/\s+/)[0] ?? cs.gap);
59773
+ const pad = cs.padding.split(/\s+/);
59774
+ if (pad.length === 1 && pad[0] && pad[0] !== "0px")
59775
+ spacings.push(pad[0]);
59776
+ for (const d of cs.transitionDuration.split(","))
59777
+ if (d.trim())
59778
+ motionDurations.push(d.trim());
59779
+ for (const d of cs.animationDuration.split(","))
59780
+ if (d.trim())
59781
+ motionDurations.push(d.trim());
59782
+ for (const e of cs.transitionTimingFunction.split(","))
59783
+ if (e.trim())
59784
+ motionEasings.push(e.trim());
59785
+ const tag = el.tagName.toLowerCase();
59786
+ const role = el.getAttribute("role");
59787
+ const isInteractive = tag === "button" || tag === "a" || role === "button";
59788
+ if (isInteractive && !transparent.has(bg))
59789
+ interactiveBackgrounds.push(bg);
59790
+ }
59791
+ const breakpoints = [];
59792
+ for (const sheet of Array.from(document.styleSheets)) {
59793
+ let rules;
59794
+ try {
59795
+ rules = sheet.cssRules;
59796
+ } catch {
59797
+ continue;
59798
+ }
59799
+ for (const rule of Array.from(rules)) {
59800
+ const media = rule.media?.mediaText;
59801
+ if (!media)
59802
+ continue;
59803
+ const re = /(?:min|max)-width:\s*(\d+(?:\.\d+)?)px/g;
59804
+ let m;
59805
+ while ((m = re.exec(media)) !== null)
59806
+ breakpoints.push(`${m[1]}px`);
59807
+ }
59808
+ }
59809
+ const body = getComputedStyle(document.body);
59810
+ return {
59811
+ bodyBackground: getComputedStyle(document.documentElement).backgroundColor || body.backgroundColor,
59812
+ bodyText: body.color,
59813
+ bodyFontFamily: body.fontFamily,
59814
+ colors,
59815
+ backgrounds,
59816
+ interactiveBackgrounds,
59817
+ fontFamilies,
59818
+ fontSizes,
59819
+ radii,
59820
+ shadows,
59821
+ spacings,
59822
+ breakpoints,
59823
+ motionDurations,
59824
+ motionEasings
59825
+ };
59826
+ });
59827
+ }
59828
+
59829
+ // src/migrate/vtex/faststore-map.ts
59830
+ var TABLE = {
59831
+ "product-summary": { faststore: "ProductCard", confidence: 0.95 },
59832
+ shelf: { faststore: "ProductShelf", confidence: 0.9 },
59833
+ "product-shelf": { faststore: "ProductShelf", confidence: 0.92 },
59834
+ "flex-layout": { faststore: "FlexLayout", confidence: 0.9 },
59835
+ "rich-text": { faststore: "RichText", confidence: 0.97 },
59836
+ "responsive-layout": { faststore: "FlexLayout", confidence: 0.7 },
59837
+ image: { faststore: "Image", confidence: 0.9 },
59838
+ "list-context": { faststore: "ProductShelf", confidence: 0.6 },
59839
+ "slider-layout": { faststore: "Carousel", confidence: 0.85 },
59840
+ carousel: { faststore: "Carousel", confidence: 0.85 },
59841
+ "search-bar": { faststore: "SearchInput", confidence: 0.9 },
59842
+ "search-result": { faststore: "ProductGallery", confidence: 0.8 },
59843
+ minicart: { faststore: "Minicart", confidence: 0.9 },
59844
+ "add-to-cart-button": { faststore: "BuyButton", confidence: 0.9 },
59845
+ menu: { faststore: "Navbar", confidence: 0.7 },
59846
+ header: { faststore: "Navbar", confidence: 0.75 },
59847
+ footer: { faststore: "Footer", confidence: 0.9 },
59848
+ breadcrumb: { faststore: "Breadcrumb", confidence: 0.95 },
59849
+ "product-price": { faststore: "Price", confidence: 0.9 },
59850
+ "product-selling-price": { faststore: "Price", confidence: 0.85 },
59851
+ "product-list-price": { faststore: "Price", confidence: 0.85 },
59852
+ "product-images": { faststore: "ImageGallery", confidence: 0.85 },
59853
+ "sku-selector": { faststore: "SkuSelector", confidence: 0.85 },
59854
+ "product-name": { faststore: "ProductTitle", confidence: 0.85 }
59855
+ };
59856
+ function lookup(blockName) {
59857
+ if (TABLE[blockName])
59858
+ return TABLE[blockName];
59859
+ const head = blockName.split(".")[0];
59860
+ return TABLE[head] ?? null;
59861
+ }
59862
+ function mapVtexBlocksToFastStore(blocks) {
59863
+ const counts = new Map;
59864
+ for (const b of blocks)
59865
+ counts.set(b.blockName, (counts.get(b.blockName) ?? 0) + 1);
59866
+ const out = [];
59867
+ for (const [vtex, count] of counts) {
59868
+ const entry = lookup(vtex);
59869
+ if (entry) {
59870
+ out.push({ vtex, faststore: entry.faststore, confidence: entry.confidence, strategy: "mapped", count });
59871
+ } else {
59872
+ out.push({ vtex, faststore: null, confidence: 0, strategy: "custom-component", count });
59873
+ }
59874
+ }
59875
+ return out.sort((a, b) => b.count - a.count);
59876
+ }
59877
+
59878
+ // src/migrate/vtex/runtime.ts
59879
+ function blockNameFromTreePath(treePath) {
59880
+ const leaf = treePath.split("/").pop() ?? treePath;
59881
+ const noInstance = leaf.split("#")[0] ?? leaf;
59882
+ return noInstance.includes(":") ? noInstance.slice(noInstance.lastIndexOf(":") + 1) : noInstance;
59883
+ }
59884
+ function parentTreePath(treePath) {
59885
+ const i = treePath.lastIndexOf("/");
59886
+ return i > 0 ? treePath.slice(0, i) : null;
59887
+ }
59888
+ async function readVtexBlockTree(page) {
59889
+ let paths;
59890
+ try {
59891
+ paths = await page.evaluate(() => {
59892
+ const rt = window.__RUNTIME__;
59893
+ if (!rt || !rt.extensions || typeof rt.extensions !== "object")
59894
+ return null;
59895
+ return Object.entries(rt.extensions).map(([treePath, ext]) => {
59896
+ const e = ext && typeof ext === "object" ? ext : {};
59897
+ let props = null;
59898
+ if (e.props && typeof e.props === "object") {
59899
+ try {
59900
+ const clean = JSON.parse(JSON.stringify(e.props));
59901
+ for (const k of ["children", "__context", "context"])
59902
+ delete clean[k];
59903
+ props = Object.keys(clean).length ? clean : null;
59904
+ } catch {
59905
+ props = null;
59906
+ }
59907
+ }
59908
+ return { treePath, component: e.component ?? null, props };
59909
+ });
59910
+ });
59911
+ } catch {
59912
+ return null;
59913
+ }
59914
+ if (!paths || paths.length === 0)
59915
+ return null;
59916
+ return paths.map((p) => ({
59917
+ treePath: p.treePath,
59918
+ blockName: blockNameFromTreePath(p.treePath),
59919
+ component: p.component,
59920
+ parent: parentTreePath(p.treePath),
59921
+ props: p.props
59922
+ })).filter((b) => b.blockName.length > 0 && !b.blockName.startsWith("$"));
59923
+ }
59924
+
59925
+ // src/migrate/interactions.ts
59926
+ var MAX_INTERACTIONS = 40;
59927
+ function classifyE2eKey(hint, kind) {
59928
+ const h = hint.toLowerCase();
59929
+ const has2 = (...words) => words.some((w) => h.includes(w));
59930
+ if (has2("add to cart", "add-to-cart", "adicionar", "comprar", "buy"))
59931
+ return "buyButton";
59932
+ if (has2("checkout", "finalizar compra", "fechar pedido"))
59933
+ return "checkoutButton";
59934
+ if (kind === "input" && has2("search", "buscar", "pesquis", "q="))
59935
+ return "searchInput";
59936
+ if (has2("search", "buscar", "pesquis"))
59937
+ return "searchTrigger";
59938
+ if (has2("minicart", "mini-cart", "cart", "carrinho", "sacola", "bag", "basket"))
59939
+ return "minicartTrigger";
59940
+ if (kind === "input" && has2("email", "e-mail"))
59941
+ return "loginEmailInput";
59942
+ if (kind === "input" && has2("password", "senha"))
59943
+ return "loginPasswordInput";
59944
+ if (has2("login", "sign in", "entrar", "minha conta", "my account"))
59945
+ return "loginTrigger";
59946
+ if (has2("load more", "ver mais", "carregar mais", "show more"))
59947
+ return "loadMoreButton";
59948
+ if (has2("next", "próxima", "proxima", "próximo"))
59949
+ return "paginationNext";
59950
+ if (has2("increment", "increase", "aumentar", "qty-plus", "plus"))
59951
+ return "quantityIncrement";
59952
+ if (has2("remove", "remover", "excluir", "delete"))
59953
+ return "cartRemoveItem";
59954
+ if (has2("coupon", "cupom", "promo code"))
59955
+ return "cartCouponInput";
59956
+ return null;
59957
+ }
59958
+ async function captureInteractions(page, selector) {
59959
+ let raw;
59960
+ try {
59961
+ raw = await page.evaluate(({ sel, cap }) => {
59962
+ const root2 = document.querySelector(sel);
59963
+ if (!root2)
59964
+ return [];
59965
+ const hoverBases = [];
59966
+ const focusBases = [];
59967
+ const splitBases = (selectorText, pseudo, out) => {
59968
+ for (const part of selectorText.split(",")) {
59969
+ if (part.includes(pseudo)) {
59970
+ const base = part.split(pseudo)[0]?.trim();
59971
+ if (base)
59972
+ out.push(base);
59973
+ }
59974
+ }
59975
+ };
59976
+ for (const sheet of Array.from(document.styleSheets)) {
59977
+ let rules;
59978
+ try {
59979
+ rules = sheet.cssRules;
59980
+ } catch {
59981
+ continue;
59982
+ }
59983
+ for (const rule of Array.from(rules)) {
59984
+ const text3 = rule.selectorText;
59985
+ if (!text3)
59986
+ continue;
59987
+ if (text3.includes(":hover"))
59988
+ splitBases(text3, ":hover", hoverBases);
59989
+ if (text3.includes(":focus"))
59990
+ splitBases(text3, ":focus", focusBases);
59991
+ }
59992
+ }
59993
+ const matchesAny = (el, bases) => bases.some((b) => {
59994
+ try {
59995
+ return el.matches(b);
59996
+ } catch {
59997
+ return false;
59998
+ }
59999
+ });
60000
+ const cssEscape = (s) => window.CSS?.escape ? window.CSS.escape(s) : s.replace(/[^a-zA-Z0-9_-]/g, "\\$&");
60001
+ const suggestSelector = (el) => {
60002
+ const tag = el.tagName.toLowerCase();
60003
+ if (el.id)
60004
+ return `#${cssEscape(el.id)}`;
60005
+ const testid = el.getAttribute("data-testid");
60006
+ if (testid)
60007
+ return `[data-testid="${testid}"]`;
60008
+ for (const attr2 of Array.from(el.attributes)) {
60009
+ if (attr2.name.startsWith("data-") && attr2.value) {
60010
+ return `${tag}[${attr2.name}="${attr2.value}"]`;
60011
+ }
60012
+ }
60013
+ const aria = el.getAttribute("aria-label");
60014
+ if (aria)
60015
+ return `${tag}[aria-label="${aria}"]`;
60016
+ const semantic = Array.from(el.classList).find((c) => !/[:[\]/]/.test(c) && !/\d/.test(c) && c.length > 2);
60017
+ return semantic ? `${tag}.${cssEscape(semantic)}` : tag;
60018
+ };
60019
+ const nodes = Array.from(root2.querySelectorAll("a, button, input, select, [role='button'], [onclick]")).slice(0, cap);
60020
+ return nodes.map((el) => {
60021
+ const tag = el.tagName.toLowerCase();
60022
+ const role = el.getAttribute("role");
60023
+ const kind = tag === "input" ? "input" : tag === "select" ? "select" : tag === "a" ? "link" : tag === "button" || role === "button" ? "button" : "clickable";
60024
+ const cs = getComputedStyle(el);
60025
+ const transition = cs.transitionProperty && cs.transitionProperty !== "all" && cs.transitionProperty !== "none" ? `transition: ${cs.transitionProperty} ${cs.transitionDuration}` : cs.animationName && cs.animationName !== "none" ? `animation: ${cs.animationName} ${cs.animationDuration}` : null;
60026
+ const label = (el.getAttribute("aria-label") || (el.textContent ?? "").trim()).replace(/\s+/g, " ").slice(0, 80);
60027
+ const hint = [
60028
+ label,
60029
+ el.getAttribute("aria-label") ?? "",
60030
+ el.getAttribute("name") ?? "",
60031
+ el.getAttribute("placeholder") ?? "",
60032
+ el.getAttribute("type") ?? "",
60033
+ el.getAttribute("href") ?? "",
60034
+ el.className && typeof el.className === "string" ? el.className : ""
60035
+ ].join(" ").toLowerCase();
60036
+ return {
60037
+ selector: suggestSelector(el),
60038
+ kind,
60039
+ label,
60040
+ animation: transition,
60041
+ hasHoverRule: matchesAny(el, hoverBases),
60042
+ hasFocusRule: matchesAny(el, focusBases),
60043
+ hint
60044
+ };
60045
+ });
60046
+ }, { sel: selector, cap: MAX_INTERACTIONS });
60047
+ } catch {
60048
+ return [];
60049
+ }
60050
+ return raw.map((r) => ({
60051
+ selector: r.selector,
60052
+ kind: r.kind,
60053
+ label: r.label,
60054
+ e2eKey: classifyE2eKey(r.hint, r.kind),
60055
+ animation: r.animation,
60056
+ hasHoverRule: r.hasHoverRule,
60057
+ hasFocusRule: r.hasFocusRule
60058
+ }));
60059
+ }
60060
+
60061
+ // src/commands/migrate.ts
60062
+ async function migrateCommand(opts) {
60063
+ const viewport = parseViewport3(opts.viewport);
60064
+ if (!viewport) {
60065
+ console.error(chalk16.red(`viewport inválido: ${opts.viewport} (use mobile|desktop|tablet)`));
60066
+ return 2;
60067
+ }
60068
+ const viewports = (opts.viewports ? opts.viewports.split(",") : [opts.viewport]).map((v) => parseViewport3(v.trim())).filter((v) => Boolean(v));
60069
+ if (viewports.length === 0) {
60070
+ console.error(chalk16.red(`--viewports inválido: ${opts.viewports}`));
60071
+ return 2;
60072
+ }
60073
+ const primaryViewport = viewports[0];
60074
+ if (!isValidUrl4(opts.url)) {
60075
+ console.error(chalk16.red(`--url inválido: ${opts.url}`));
60076
+ return 2;
60077
+ }
60078
+ const format = normalizeFormat2(opts.format);
60079
+ if (!format) {
60080
+ console.error(chalk16.red(`--format inválido: ${opts.format} (use md|json|both)`));
60081
+ return 2;
60082
+ }
60083
+ let playbook;
60084
+ if (opts.target) {
60085
+ playbook = getTargetPlaybook(opts.target);
60086
+ if (!playbook) {
60087
+ console.error(chalk16.red(`--target inválido: ${opts.target} (disponíveis: ${TARGET_NAMES.join(", ")})`));
60088
+ return 2;
60089
+ }
60090
+ }
60091
+ const allowlist = parseAllowlist2(opts.components);
60092
+ const host = safeHost5(opts.url);
60093
+ const runDir = resolve3(opts.outDir, host);
60094
+ mkdirSync14(runDir, { recursive: true });
60095
+ const browser = await launchBrowser({ headless: true });
60096
+ try {
60097
+ const themePath = resolve3(runDir, "theme.json");
60098
+ const assetsPath = resolve3(runDir, "assets.json");
60099
+ const blocksPath = resolve3(runDir, "blocks.json");
60100
+ let theme;
60101
+ let platform;
60102
+ let assets;
60103
+ let screenshots;
60104
+ let vtexBlocks = null;
60105
+ if (!opts.refresh && existsSync11(themePath) && existsSync11(assetsPath)) {
60106
+ theme = readJson(themePath);
60107
+ const meta = readJson(assetsPath);
60108
+ platform = meta.platform;
60109
+ assets = meta.assets;
60110
+ screenshots = meta.screenshots ?? [];
60111
+ if (existsSync11(blocksPath))
60112
+ vtexBlocks = readJson(blocksPath);
60113
+ console.log(chalk16.dim(" phase 1 theme+assets: cached"));
60114
+ } else {
60115
+ console.log(chalk16.dim(` phase 1 theme+assets: scraping (${viewports.join(", ")})…`));
60116
+ mkdirSync14(resolve3(runDir, "screenshots"), { recursive: true });
60117
+ const samples = [];
60118
+ screenshots = [];
60119
+ let platformSeen = null;
60120
+ let assetsResolved = null;
60121
+ for (const vp of viewports) {
60122
+ const ctx = await newContext(browser, { viewport: vp });
60123
+ const page = await ctx.newPage();
60124
+ try {
60125
+ await page.goto(opts.url, { waitUntil: "domcontentloaded", timeout: 30000 });
60126
+ await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
60127
+ return;
60128
+ });
60129
+ await Promise.race([stabilizeCarousels(page).catch(() => {
60130
+ return;
60131
+ }), sleep2(3000)]);
60132
+ await Promise.race([scrollFullPage(page, 30000).catch(() => {
60133
+ return;
60134
+ }), sleep2(32000)]);
60135
+ await Promise.race([
60136
+ waitForSkeletonsToResolve(page, 5000).catch(() => {
60137
+ return;
60138
+ }),
60139
+ sleep2(5000)
60140
+ ]);
60141
+ samples.push(await scrapeThemeSamples(page));
60142
+ const shot = resolve3(runDir, "screenshots", `${vp}.png`);
60143
+ await page.screenshot({ path: shot, fullPage: true, animations: "disabled", timeout: 15000 }).then(() => screenshots.push({ viewport: vp, path: `screenshots/${vp}.png` })).catch(() => {
60144
+ return;
60145
+ });
60146
+ if (!assetsResolved) {
60147
+ platformSeen = detectPlatform({ url: opts.url, html: await page.content().catch(() => "") });
60148
+ const rawAssets = await collectSiteAssets(page);
60149
+ const fetchBytes = async (url) => await browserFetchBytes(page, url) ?? await nodeFetchBytes(url);
60150
+ assetsResolved = await downloadSiteAssets(rawAssets, runDir, fetchBytes);
60151
+ if (rawAssets.logo) {
60152
+ const logoPng = resolve3(runDir, "assets", "logo.png");
60153
+ const ok = await page.locator("[data-parity-logo]").first().screenshot({ path: logoPng, timeout: 8000 }).then(() => true).catch(() => false);
60154
+ if (ok) {
60155
+ assetsResolved.logo = "assets/logo.png";
60156
+ assetsResolved.logoSource = assetsResolved.logoSource ?? "screenshot";
60157
+ }
60158
+ }
60159
+ vtexBlocks = await readVtexBlockTree(page);
60160
+ }
60161
+ } finally {
60162
+ await page.close().catch(() => {
60163
+ return;
60164
+ });
60165
+ await ctx.close().catch(() => {
60166
+ return;
60167
+ });
60168
+ }
60169
+ }
60170
+ theme = aggregateTheme(mergeRawThemeSamples(samples));
60171
+ platform = platformSeen ?? "custom";
60172
+ assets = assetsResolved;
60173
+ writeFileSync20(themePath, `${JSON.stringify(theme, null, 2)}
60174
+ `, "utf8");
60175
+ writeFileSync20(assetsPath, `${JSON.stringify({ platform, assets, screenshots }, null, 2)}
60176
+ `, "utf8");
60177
+ if (vtexBlocks) {
60178
+ writeFileSync20(blocksPath, `${JSON.stringify(vtexBlocks, null, 2)}
60179
+ `, "utf8");
60180
+ console.log(chalk16.dim(` vtex io: ${vtexBlocks.length} blocks read from runtime`));
60181
+ }
60182
+ }
60183
+ const sitemapPath = resolve3(runDir, "sitemap.json");
60184
+ let resolvedPages;
60185
+ if (!opts.refresh && existsSync11(sitemapPath)) {
60186
+ resolvedPages = readJson(sitemapPath).pages;
60187
+ console.log(chalk16.dim(` phase 2 sitemap: cached (${resolvedPages.length} page(s))`));
60188
+ } else {
60189
+ console.log(chalk16.dim(" phase 2 sitemap: resolving pages…"));
60190
+ const ctx = await newContext(browser, { viewport: primaryViewport });
60191
+ const page = await ctx.newPage();
60192
+ let sitemapUrls = [];
60193
+ try {
60194
+ await page.goto(opts.url, { waitUntil: "domcontentloaded", timeout: 30000 });
60195
+ await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
60196
+ return;
60197
+ });
60198
+ const homeHtml = await page.content().catch(() => "");
60199
+ resolvedPages = await resolvePages2(page, opts.url, opts.pages, homeHtml, platform);
60200
+ sitemapUrls = await discoverSitemapUrls(page, opts.url);
60201
+ } finally {
60202
+ await page.close().catch(() => {
60203
+ return;
60204
+ });
60205
+ await ctx.close().catch(() => {
60206
+ return;
60207
+ });
60208
+ }
60209
+ const classified = sitemapUrls.slice(0, 500).map((u) => ({ url: u, kind: kindOf(u) }));
60210
+ writeFileSync20(sitemapPath, `${JSON.stringify({ pages: resolvedPages, sitemapUrls: classified }, null, 2)}
60211
+ `, "utf8");
60212
+ }
60213
+ if (resolvedPages.length === 0) {
60214
+ console.error(chalk16.red("nenhuma página resolvida a partir de --pages"));
60215
+ return 1;
60216
+ }
60217
+ const capturePath = resolve3(runDir, "capture.json");
60218
+ let pages;
60219
+ let components;
60220
+ if (!opts.refresh && existsSync11(capturePath)) {
60221
+ const cached = readJson(capturePath);
60222
+ pages = cached.pages;
60223
+ components = cached.components;
60224
+ console.log(chalk16.dim(` phase 3 components: cached (${components.length})`));
60225
+ } else {
60226
+ console.log(chalk16.dim(" phase 3 components: capturing…"));
60227
+ ({ pages, components } = await capturePages(browser, primaryViewport, resolvedPages, theme, {
60228
+ allowlist,
60229
+ llm: !opts.noLlm,
60230
+ runDir
60231
+ }));
60232
+ writeFileSync20(capturePath, `${JSON.stringify({ pages, components }, null, 2)}
60233
+ `, "utf8");
60234
+ }
60235
+ const bundle = {
60236
+ url: opts.url,
60237
+ timestamp: new Date().toISOString(),
60238
+ viewport: primaryViewport,
60239
+ viewports,
60240
+ screenshots,
60241
+ platform,
60242
+ target: opts.target,
60243
+ theme,
60244
+ assets,
60245
+ vtex: vtexBlocks ? { blocks: vtexBlocks, map: mapVtexBlocksToFastStore(vtexBlocks) } : undefined,
60246
+ pages,
60247
+ components
60248
+ };
60249
+ if (format === "json" || format === "both")
60250
+ await jsonExporter2.export(bundle, runDir);
60251
+ if (format === "md" || format === "both") {
60252
+ await markdownExporter2.export(bundle, runDir);
60253
+ await htmlExporter.export(bundle, runDir);
60254
+ writeFileSync20(resolve3(runDir, "MIGRATION_PROMPT.md"), buildMigrationPrompt(bundle, playbook), "utf8");
60255
+ }
60256
+ if (opts.target === "faststore") {
60257
+ writeFileSync20(resolve3(runDir, "custom-theme.scss"), buildFastStoreTheme(theme), "utf8");
60258
+ }
60259
+ if (bundle.vtex) {
60260
+ writeFileSync20(resolve3(runDir, "component-map.json"), `${JSON.stringify(bundle.vtex.map, null, 2)}
60261
+ `, "utf8");
60262
+ }
60263
+ if (opts.json) {
60264
+ console.log(JSON.stringify({ outDir: runDir, componentCount: components.length, bundle }));
60265
+ return 0;
60266
+ }
60267
+ printResults4(runDir, bundle);
60268
+ if (opts.open && format !== "json") {
60269
+ await open(resolve3(runDir, "report.html")).catch(() => {
60270
+ return;
60271
+ });
60272
+ }
60273
+ return 0;
60274
+ } finally {
60275
+ await browser.close().catch(() => {
60276
+ return;
60277
+ });
60278
+ }
60279
+ }
60280
+ async function capturePages(browser, viewport, resolvedPages, theme, cfg) {
60281
+ const pages = [];
60282
+ const components = [];
60283
+ const seenGlobalRoles = new Set;
60284
+ for (const target of resolvedPages) {
60285
+ const ctx = await newContext(browser, { viewport });
60286
+ const page = await ctx.newPage();
60287
+ const pageComponents = [];
60288
+ try {
60289
+ await page.goto(target.url, { waitUntil: "domcontentloaded", timeout: 30000 });
60290
+ await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
60291
+ return;
60292
+ });
60293
+ await Promise.race([stabilizeCarousels(page).catch(() => {
60294
+ return;
60295
+ }), sleep2(3000)]);
60296
+ await Promise.race([scrollFullPage(page, 30000).catch(() => {
60297
+ return;
60298
+ }), sleep2(32000)]);
60299
+ await Promise.race([
60300
+ waitForSkeletonsToResolve(page, 5000).catch(() => {
60301
+ return;
60302
+ }),
60303
+ sleep2(5000)
60304
+ ]);
60305
+ let detected = await detectComponents(page, { llm: cfg.llm });
60306
+ if (cfg.allowlist)
60307
+ detected = detected.filter((c) => matchesAllowlist2(c.role, cfg.allowlist));
60308
+ const signatures = await structuralSignatures(page, detected.map((d) => d.selector));
60309
+ const plan = planComponentDedup(detected.map((d, i) => ({ role: d.role, signature: signatures[i] ?? "" })));
60310
+ const pageScreenshot = await page.screenshot({ fullPage: true, animations: "disabled", timeout: 15000 }).catch(() => {
60311
+ return;
60312
+ });
60313
+ for (const { index: index2, repeated } of plan) {
60314
+ const component = detected[index2];
60315
+ const global = isGlobalRole(component.role);
60316
+ if (global && seenGlobalRoles.has(component.role))
60317
+ continue;
60318
+ if (global)
60319
+ seenGlobalRoles.add(component.role);
60320
+ const idx = components.length + 1;
60321
+ const componentDir = resolve3(cfg.runDir, "components", componentDirName(component.role, idx));
60322
+ const extracted = await extractComponent(page, component, {
60323
+ outDir: componentDir,
60324
+ index: idx,
60325
+ pageScreenshot
60326
+ });
60327
+ const interactions = await captureInteractions(page, component.selector);
60328
+ const migrated = toMigratedComponent(extracted, interactions, global ? "global" : "page", theme.tokens, repeated);
60329
+ components.push(migrated);
60330
+ if (!global)
60331
+ pageComponents.push(migrated);
60332
+ }
60333
+ pages.push({ url: target.url, path: target.path, kind: target.kind, components: pageComponents });
60334
+ } finally {
60335
+ await page.close().catch(() => {
60336
+ return;
60337
+ });
60338
+ await ctx.close().catch(() => {
60339
+ return;
60340
+ });
60341
+ }
60342
+ }
60343
+ return { pages, components };
60344
+ }
60345
+ async function resolvePages2(page, baseUrl, pagesSpec, homeHtml, platform) {
60346
+ const tokens = (pagesSpec ?? "/,category-auto,pdp-auto").split(",").map((s) => s.trim()).filter(Boolean);
60347
+ const out = [];
60348
+ const plp = pickPlpFromHomeHtml(homeHtml, baseUrl);
60349
+ for (const token of tokens) {
60350
+ if (token === "category-auto") {
60351
+ if (plp)
60352
+ out.push({ path: token, url: plp, kind: "plp" });
60353
+ else
60354
+ console.warn(chalk16.yellow(" ⚠ category-auto: nenhuma PLP descoberta na home"));
60355
+ continue;
60356
+ }
60357
+ if (token === "pdp-auto") {
60358
+ if (!plp) {
60359
+ console.warn(chalk16.yellow(" ⚠ pdp-auto: sem PLP pra derivar PDP"));
60360
+ continue;
60361
+ }
60362
+ let html3 = null;
60363
+ try {
60364
+ await page.goto(plp, { waitUntil: "domcontentloaded", timeout: 30000 });
60365
+ await page.waitForLoadState("networkidle", { timeout: 8000 }).catch(() => {
60366
+ return;
60367
+ });
60368
+ html3 = await page.content();
60369
+ } catch {
60370
+ html3 = await browserFetchText(page, plp);
60371
+ }
60372
+ const pdp = html3 ? firstProductHref(html3, plp, platform) : null;
60373
+ if (pdp)
60374
+ out.push({ path: token, url: pdp, kind: "pdp" });
60375
+ else
60376
+ console.warn(chalk16.yellow(" ⚠ pdp-auto: nenhum produto encontrado na PLP"));
60377
+ continue;
60378
+ }
60379
+ try {
60380
+ const url = new URL(token, baseUrl).toString();
60381
+ out.push({ path: token, url, kind: kindOf(url) });
60382
+ } catch {}
60383
+ }
60384
+ return out;
60385
+ }
60386
+ async function discoverSitemapUrls(page, baseUrl) {
60387
+ try {
60388
+ const origin = new URL(baseUrl).origin;
60389
+ const rootXml = await browserFetchText(page, `${origin}/sitemap.xml`);
60390
+ if (!rootXml)
60391
+ return [];
60392
+ const root2 = parseSitemap(rootXml);
60393
+ if (!root2.isIndex)
60394
+ return root2.urls;
60395
+ const urls = [];
60396
+ for (const child of root2.childSitemaps.slice(0, 5)) {
60397
+ const xml2 = await browserFetchText(page, child);
60398
+ if (xml2)
60399
+ urls.push(...parseSitemap(xml2).urls);
60400
+ if (urls.length >= 500)
60401
+ break;
60402
+ }
60403
+ return urls;
60404
+ } catch {
60405
+ return [];
60406
+ }
60407
+ }
60408
+ async function structuralSignatures(page, selectors) {
60409
+ try {
60410
+ return await page.evaluate((sels) => {
60411
+ return sels.map((s) => {
60412
+ let el = null;
60413
+ try {
60414
+ el = document.querySelector(s);
60415
+ } catch {
60416
+ return "";
60417
+ }
60418
+ if (!el)
60419
+ return "";
60420
+ const cls = Array.from(el.classList).filter((c) => !/\d/.test(c)).sort().join(".");
60421
+ return `${el.tagName}|${cls}|${el.children.length}`;
60422
+ });
60423
+ }, selectors);
60424
+ } catch {
60425
+ return selectors.map(() => "");
60426
+ }
60427
+ }
60428
+ function kindOf(url) {
60429
+ try {
60430
+ return classifyPath2(new URL(url).pathname);
60431
+ } catch {
60432
+ return "other";
60433
+ }
60434
+ }
60435
+ function printResults4(runDir, bundle) {
60436
+ console.log(chalk16.bold(`
60437
+ parity migrate`));
60438
+ console.log(chalk16.dim(` url: ${bundle.url}`));
60439
+ console.log(chalk16.dim(` platform: ${bundle.platform}${bundle.target ? ` → ${bundle.target}` : ""}`));
60440
+ console.log(chalk16.dim(` viewports:${(bundle.viewports ?? [bundle.viewport]).join(", ")}`));
60441
+ console.log(chalk16.dim(` theme: primary=${bundle.theme.colors.primary ?? "—"} text=${bundle.theme.colors.text ?? "—"}`));
60442
+ console.log(chalk16.dim(` assets: logo=${bundle.assets.logo ? "✓" : "✗"} favicon=${bundle.assets.favicon ? "✓" : "✗"} icons=${bundle.assets.icons.length} fonts=${bundle.assets.fontFiles.length}`));
60443
+ if (bundle.vtex) {
60444
+ const mapped = bundle.vtex.map.filter((m) => m.strategy === "mapped").length;
60445
+ const withContent = bundle.vtex.blocks.filter((x) => x.props).length;
60446
+ console.log(chalk16.dim(` vtex io: ${bundle.vtex.blocks.length} blocks (${withContent} with CMS content) · ${mapped}/${bundle.vtex.map.length} block types mapped to FastStore`));
60447
+ }
60448
+ console.log(chalk16.dim(` pages: ${bundle.pages.map((p) => p.kind).join(", ") || "—"}`));
60449
+ console.log(chalk16.dim(` out: ${runDir}`));
60450
+ console.log("");
60451
+ console.log(chalk16.bold(` ${bundle.components.length} component(s):`));
60452
+ for (const c of bundle.components) {
60453
+ console.log(` ${chalk16.cyan(`${c.scope}/${c.role}`.padEnd(28))} ${chalk16.dim(`${c.tailwind.length} tw · ${c.interactions.length} interactions`)}`);
60454
+ }
60455
+ console.log("");
60456
+ }
60457
+ function readJson(path) {
60458
+ try {
60459
+ return JSON.parse(readFileSync14(path, "utf8"));
60460
+ } catch {
60461
+ return null;
60462
+ }
60463
+ }
60464
+ function parseAllowlist2(spec) {
60465
+ if (!spec || spec.trim().length === 0)
60466
+ return null;
60467
+ const set = new Set(spec.split(",").map((s) => s.trim().toLowerCase()).filter(Boolean));
60468
+ return set.size > 0 ? set : null;
60469
+ }
60470
+ function matchesAllowlist2(role, allowlist) {
60471
+ const lower = role.toLowerCase();
60472
+ if (allowlist.has(lower))
60473
+ return true;
60474
+ for (const name of allowlist) {
60475
+ if (lower.startsWith(`${name}-`))
60476
+ return true;
60477
+ }
60478
+ return false;
60479
+ }
60480
+ function normalizeFormat2(raw) {
60481
+ if (raw === "md" || raw === "json" || raw === "both")
60482
+ return raw;
60483
+ return null;
60484
+ }
60485
+ function safeHost5(url) {
60486
+ try {
60487
+ return new URL(url).host || "site";
60488
+ } catch {
60489
+ return "site";
60490
+ }
60491
+ }
60492
+ function isValidUrl4(s) {
60493
+ try {
60494
+ new URL(s);
60495
+ return true;
60496
+ } catch {
60497
+ return false;
60498
+ }
60499
+ }
60500
+ function sleep2(ms) {
60501
+ return new Promise((resolveTimeout) => setTimeout(resolveTimeout, ms));
60502
+ }
60503
+
60504
+ // src/commands/pr.ts
60505
+ import { existsSync as existsSync15, readFileSync as readFileSync17, writeFileSync as writeFileSync21 } from "node:fs";
60506
+ import { join as join23 } from "node:path";
60507
+ import chalk19 from "chalk";
60508
+
60509
+ // src/commands/run.ts
60510
+ import { existsSync as existsSync14, readFileSync as readFileSync16, unlinkSync as unlinkSync3 } from "node:fs";
60511
+ import { join as join22 } from "node:path";
60512
+ import chalk18 from "chalk";
60513
+ import ora6 from "ora";
60514
+
60515
+ // src/engine/interactive-module-prompt.ts
60516
+ import { createInterface } from "node:readline";
60517
+ var ALL_MODULE_NAMES2 = Object.keys(MODULES);
60518
+ async function promptForModuleSelection() {
60519
+ console.log("");
60520
+ console.log(" Select modules to run (all checked by default):");
60521
+ console.log("");
60522
+ ALL_MODULE_NAMES2.forEach((name, i) => {
60523
+ const def = MODULES[name];
60524
+ console.log(` [x] ${i + 1}. ${name.padEnd(8)} — ${def.description}`);
60525
+ });
60526
+ console.log("");
60527
+ const answer = await readLine(" Type numbers to UNCHECK (comma-separated), or press Enter to run all: ");
60528
+ if (answer === null) {
60529
+ console.log(" (aborted — running all modules)");
60530
+ return ALL_MODULE_NAMES2;
60531
+ }
60532
+ const trimmed = answer.trim();
60533
+ if (!trimmed)
60534
+ return ALL_MODULE_NAMES2;
60535
+ const uncheckIdx = new Set(trimmed.split(",").map((s) => Number.parseInt(s.trim(), 10)).filter((n) => Number.isInteger(n) && n >= 1 && n <= ALL_MODULE_NAMES2.length));
60536
+ const selected = ALL_MODULE_NAMES2.filter((_name, i) => !uncheckIdx.has(i + 1));
60537
+ if (selected.length === 0) {
60538
+ console.log(" (everything unchecked — running all modules instead)");
60539
+ return ALL_MODULE_NAMES2;
60540
+ }
60541
+ console.log(` running: ${selected.join(", ")}`);
60542
+ return selected;
60543
+ }
60544
+ function readLine(prompt) {
60545
+ return new Promise((resolveLine) => {
60546
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
60547
+ rl.question(prompt, (ans) => {
60548
+ rl.close();
60549
+ resolveLine(ans);
60550
+ });
60551
+ rl.on("SIGINT", () => {
60552
+ rl.close();
60553
+ resolveLine(null);
60554
+ });
60555
+ });
60556
+ }
60557
+
60558
+ // src/engine/interactive-selector-prompt.ts
60559
+ init_client();
60560
+ var forceDisabled = false;
60561
+ function disableInteractive() {
60562
+ forceDisabled = true;
60563
+ }
60564
+ function isInteractiveMode() {
60565
+ if (forceDisabled)
60566
+ return false;
60567
+ if (!process.stdout.isTTY || !process.stdin.isTTY)
60568
+ return false;
60569
+ if (isLlmAvailable())
60570
+ return false;
60571
+ return true;
60572
+ }
60573
+
58553
60574
  // src/llm/aggregate-issues.ts
58554
60575
  init_client();
58555
60576
  var REPORT_ISSUES_TOOL = {
@@ -58963,14 +60984,14 @@ function formatMs(ms) {
58963
60984
  }
58964
60985
 
58965
60986
  // src/commands/serve.ts
58966
- import { existsSync as existsSync12 } from "node:fs";
58967
- import chalk16 from "chalk";
60987
+ import { existsSync as existsSync13 } from "node:fs";
60988
+ import chalk17 from "chalk";
58968
60989
 
58969
60990
  // src/server/proxy-server.ts
58970
- import { existsSync as existsSync11, readFileSync as readFileSync13, statSync } from "node:fs";
60991
+ import { existsSync as existsSync12, readFileSync as readFileSync15, statSync } from "node:fs";
58971
60992
  import { createServer } from "node:http";
58972
- import { extname, join as join17, normalize as normalize3, resolve as resolve3, sep } from "node:path";
58973
- var MIME = {
60993
+ import { extname, join as join21, normalize as normalize3, resolve as resolve4, sep } from "node:path";
60994
+ var MIME2 = {
58974
60995
  ".html": "text/html; charset=utf-8",
58975
60996
  ".css": "text/css; charset=utf-8",
58976
60997
  ".js": "application/javascript; charset=utf-8",
@@ -59005,8 +61026,8 @@ var STRIPPED_REQUEST_HEADERS = new Set([
59005
61026
  "origin"
59006
61027
  ]);
59007
61028
  async function startProxyServer(runDir, opts = {}) {
59008
- const absRunDir = resolve3(runDir);
59009
- if (!existsSync11(absRunDir)) {
61029
+ const absRunDir = resolve4(runDir);
61030
+ if (!existsSync12(absRunDir)) {
59010
61031
  throw new Error(`Run directory not found: ${runDir}`);
59011
61032
  }
59012
61033
  const server = createServer((req, res) => {
@@ -59017,9 +61038,9 @@ async function startProxyServer(runDir, opts = {}) {
59017
61038
  } catch {}
59018
61039
  });
59019
61040
  });
59020
- await new Promise((resolve4, reject) => {
61041
+ await new Promise((resolve5, reject) => {
59021
61042
  server.once("error", reject);
59022
- server.listen(opts.port ?? 0, opts.host ?? "127.0.0.1", () => resolve4());
61043
+ server.listen(opts.port ?? 0, opts.host ?? "127.0.0.1", () => resolve5());
59023
61044
  });
59024
61045
  const addr = server.address();
59025
61046
  const port = typeof addr === "object" && addr ? addr.port : 0;
@@ -59027,13 +61048,13 @@ async function startProxyServer(runDir, opts = {}) {
59027
61048
  return {
59028
61049
  port,
59029
61050
  url: `http://${host}:${port}/`,
59030
- close: () => new Promise((resolve4) => {
61051
+ close: () => new Promise((resolve5) => {
59031
61052
  try {
59032
61053
  server.closeAllConnections?.();
59033
61054
  server.closeIdleConnections?.();
59034
61055
  } catch {}
59035
- server.close(() => resolve4());
59036
- setTimeout(() => resolve4(), 1000);
61056
+ server.close(() => resolve5());
61057
+ setTimeout(() => resolve5(), 1000);
59037
61058
  })
59038
61059
  };
59039
61060
  }
@@ -59063,13 +61084,13 @@ async function handleRequest(req, res, runDir) {
59063
61084
  return serveStatic(res, runDir, path);
59064
61085
  }
59065
61086
  function serveReportHtml(res, runDir) {
59066
- const filePath = join17(runDir, "report.html");
59067
- if (!existsSync11(filePath)) {
61087
+ const filePath = join21(runDir, "report.html");
61088
+ if (!existsSync12(filePath)) {
59068
61089
  res.statusCode = 404;
59069
61090
  res.end("report.html not found");
59070
61091
  return;
59071
61092
  }
59072
- const html3 = readFileSync13(filePath, "utf8");
61093
+ const html3 = readFileSync15(filePath, "utf8");
59073
61094
  const inject = `<script>window.__parity_proxy = "/proxy?url=";</script>`;
59074
61095
  const out = html3.includes("</head>") ? html3.replace("</head>", `${inject}</head>`) : `${inject}${html3}`;
59075
61096
  res.statusCode = 200;
@@ -59079,13 +61100,13 @@ function serveReportHtml(res, runDir) {
59079
61100
  }
59080
61101
  function serveStatic(res, runDir, path) {
59081
61102
  const safePath2 = normalize3(path).replace(/^[/\\]+/, "");
59082
- const filePath = resolve3(runDir, safePath2);
61103
+ const filePath = resolve4(runDir, safePath2);
59083
61104
  if (!filePath.startsWith(runDir + sep) && filePath !== runDir) {
59084
61105
  res.statusCode = 403;
59085
61106
  res.end("forbidden");
59086
61107
  return;
59087
61108
  }
59088
- if (!existsSync11(filePath)) {
61109
+ if (!existsSync12(filePath)) {
59089
61110
  res.statusCode = 404;
59090
61111
  res.end("not found");
59091
61112
  return;
@@ -59098,9 +61119,9 @@ function serveStatic(res, runDir, path) {
59098
61119
  }
59099
61120
  const ext = extname(filePath).toLowerCase();
59100
61121
  res.statusCode = 200;
59101
- res.setHeader("content-type", MIME[ext] ?? "application/octet-stream");
61122
+ res.setHeader("content-type", MIME2[ext] ?? "application/octet-stream");
59102
61123
  res.setHeader("cache-control", "no-store");
59103
- res.end(readFileSync13(filePath));
61124
+ res.end(readFileSync15(filePath));
59104
61125
  }
59105
61126
  async function proxyRequest(req, res, targetUrl, opts = {}) {
59106
61127
  let target;
@@ -59198,20 +61219,20 @@ async function serveRunAndBlock(runDir, opts = {}) {
59198
61219
  try {
59199
61220
  handle = await startProxyServer(runDir, { port: opts.port });
59200
61221
  } catch (err) {
59201
- console.error(chalk16.red(` ✖ Falha ao iniciar servidor: ${err.message}`));
61222
+ console.error(chalk17.red(` ✖ Falha ao iniciar servidor: ${err.message}`));
59202
61223
  return 2;
59203
61224
  }
59204
61225
  const label = opts.label ?? "parity serve";
59205
61226
  console.log("");
59206
- console.log(chalk16.bold(` ${label}`));
59207
- console.log(` ${chalk16.green("●")} ${handle.url}`);
59208
- console.log(chalk16.dim(` Servindo: ${runDir}`));
59209
- console.log(chalk16.dim(` Proxy de iframes: ${handle.url}proxy?url=<encoded>`));
59210
- console.log(chalk16.dim(` Ctrl+C pra parar (2x pra forçar saída).
61227
+ console.log(chalk17.bold(` ${label}`));
61228
+ console.log(` ${chalk17.green("●")} ${handle.url}`);
61229
+ console.log(chalk17.dim(` Servindo: ${runDir}`));
61230
+ console.log(chalk17.dim(` Proxy de iframes: ${handle.url}proxy?url=<encoded>`));
61231
+ console.log(chalk17.dim(` Ctrl+C pra parar (2x pra forçar saída).
59211
61232
  `));
59212
61233
  if (opts.open !== false) {
59213
- const { default: open } = await import("open");
59214
- await open(handle.url).catch(() => {
61234
+ const { default: open2 } = await import("open");
61235
+ await open2(handle.url).catch(() => {
59215
61236
  return;
59216
61237
  });
59217
61238
  }
@@ -59239,12 +61260,12 @@ async function serveRunAndBlock(runDir, opts = {}) {
59239
61260
  }
59240
61261
  async function serveCommand(runId, opts) {
59241
61262
  const paths = getRunPaths(opts.output, runId);
59242
- if (!existsSync12(paths.runDir)) {
59243
- console.error(chalk16.red(`✖ Run não encontrado: ${runId} (em ${opts.output})`));
61263
+ if (!existsSync13(paths.runDir)) {
61264
+ console.error(chalk17.red(`✖ Run não encontrado: ${runId} (em ${opts.output})`));
59244
61265
  return 1;
59245
61266
  }
59246
- if (!existsSync12(paths.reportHtml)) {
59247
- console.error(chalk16.red(`✖ report.html não existe em ${paths.runDir}`));
61267
+ if (!existsSync13(paths.reportHtml)) {
61268
+ console.error(chalk17.red(`✖ report.html não existe em ${paths.runDir}`));
59248
61269
  return 1;
59249
61270
  }
59250
61271
  return serveRunAndBlock(paths.runDir, {
@@ -59375,14 +61396,14 @@ function evaluateFailOnGate(allIssues, failOn) {
59375
61396
  async function runCommand(rawOpts) {
59376
61397
  if (!rawOpts.prod) {
59377
61398
  const target = rawOpts.cand ?? "<url>";
59378
- console.error(`${chalk17.yellow("Single-site run?")} \`parity run\` compares two URLs (prod↔cand).
59379
- For one site, use: ${chalk17.cyan(`parity e2e --url ${target}`)}
61399
+ console.error(`${chalk18.yellow("Single-site run?")} \`parity run\` compares two URLs (prod↔cand).
61400
+ For one site, use: ${chalk18.cyan(`parity e2e --url ${target}`)}
59380
61401
  (runs the functional flows + all checks in single-site mode — no prod baseline needed).`);
59381
61402
  return 2;
59382
61403
  }
59383
61404
  let opts = applyPreset(rawOpts);
59384
61405
  if (rawOpts.preset) {
59385
- console.log(chalk17.dim(` preset: ${rawOpts.preset}`));
61406
+ console.log(chalk18.dim(` preset: ${rawOpts.preset}`));
59386
61407
  }
59387
61408
  if (opts.pt)
59388
61409
  setLlmLanguage("pt");
@@ -59390,14 +61411,14 @@ async function runCommand(rawOpts) {
59390
61411
  disableInteractive();
59391
61412
  const llmCfgErr = applyLlmOptions(opts);
59392
61413
  if (llmCfgErr) {
59393
- console.error(chalk17.red(` ${llmCfgErr}`));
61414
+ console.error(chalk18.red(` ${llmCfgErr}`));
59394
61415
  return 2;
59395
61416
  }
59396
61417
  const llmStillAvailable = isLlmAvailable();
59397
61418
  const preSmart = opts;
59398
61419
  opts = applySmartDefaults(opts, llmStillAvailable);
59399
61420
  if (!llmStillAvailable && opts.visualPages !== preSmart.visualPages) {
59400
- console.log(chalk17.dim(" visual-pages auto-set to 0 (no LLM available — analysis layer would be skipped; opt in with --visual-pages N)"));
61421
+ console.log(chalk18.dim(" visual-pages auto-set to 0 (no LLM available — analysis layer would be skipped; opt in with --visual-pages N)"));
59401
61422
  }
59402
61423
  let interactivePromptShown = false;
59403
61424
  if (!opts.only && !opts.skip && !rawOpts.preset) {
@@ -59411,10 +61432,10 @@ async function runCommand(rawOpts) {
59411
61432
  }
59412
61433
  const selection = resolveSelection({ only: opts.only, skip: opts.skip });
59413
61434
  if (selection.errors.length > 0) {
59414
- console.error(chalk17.red(" --only/--skip: invalid value(s):"));
61435
+ console.error(chalk18.red(" --only/--skip: invalid value(s):"));
59415
61436
  for (const e of selection.errors)
59416
- console.error(chalk17.red(` - ${e}`));
59417
- console.error(chalk17.dim(`
61437
+ console.error(chalk18.red(` - ${e}`));
61438
+ console.error(chalk18.dim(`
59418
61439
  valid modules: ${Object.keys(MODULES).join(", ")}`));
59419
61440
  return 2;
59420
61441
  }
@@ -59425,16 +61446,16 @@ async function runCommand(rawOpts) {
59425
61446
  if (hasSelection) {
59426
61447
  const explicitFlows = userSetFlows ? opts.flows.split(",").map((s) => s.trim()).filter(Boolean) : [];
59427
61448
  flows2 = Array.from(new Set([...explicitFlows, ...selection.flows]));
59428
- console.log(chalk17.dim(` modules: ${selection.modules.join(", ") || "(none)"} → flows: ${flows2.join(",")}`));
61449
+ console.log(chalk18.dim(` modules: ${selection.modules.join(", ") || "(none)"} → flows: ${flows2.join(",")}`));
59429
61450
  } else {
59430
61451
  flows2 = opts.flows.split(",").map((s) => s.trim());
59431
61452
  if (!interactivePromptShown) {
59432
- console.log(chalk17.dim(" no --only/--skip given — running ALL modules; pass --only to scope the run for a lighter/faster result"));
61453
+ console.log(chalk18.dim(" no --only/--skip given — running ALL modules; pass --only to scope the run for a lighter/faster result"));
59433
61454
  }
59434
61455
  }
59435
61456
  const pagesScopeWarning = pagesFlowsScopeWarning(opts, flows2);
59436
61457
  if (pagesScopeWarning) {
59437
- console.log(chalk17.dim(` ${pagesScopeWarning}`));
61458
+ console.log(chalk18.dim(` ${pagesScopeWarning}`));
59438
61459
  }
59439
61460
  if (hasSelection) {
59440
61461
  const needsSitemapPages = selection.modules.some((m) => MODULES[m].needsSitemapPages);
@@ -59443,12 +61464,12 @@ async function runCommand(rawOpts) {
59443
61464
  const VISUAL_PAGES_DEFAULT = 5;
59444
61465
  if (!needsSitemapPages && opts.vitalsPages === VITALS_PAGES_DEFAULT) {
59445
61466
  opts.vitalsPages = 0;
59446
- console.log(chalk17.dim(" vitals-pages auto-set to 0 (no selected module needs sitemap-page crawling)"));
61467
+ console.log(chalk18.dim(" vitals-pages auto-set to 0 (no selected module needs sitemap-page crawling)"));
59447
61468
  }
59448
61469
  if (!needsLlmPass && opts.visualPages === VISUAL_PAGES_DEFAULT) {
59449
61470
  opts.visualPages = 0;
59450
61471
  opts.noVisualDiff = true;
59451
- console.log(chalk17.dim(" visual-pages auto-set to 0 (no selected module needs the visual-diff pass)"));
61472
+ console.log(chalk18.dim(" visual-pages auto-set to 0 (no selected module needs the visual-diff pass)"));
59452
61473
  }
59453
61474
  }
59454
61475
  const viewports = opts.viewports.split(",").map((s) => s.trim());
@@ -59460,38 +61481,38 @@ async function runCommand(rawOpts) {
59460
61481
  }
59461
61482
  const ignore = loadParityIgnore();
59462
61483
  if (opts.clearCache) {
59463
- const cacheFile = join18(opts.output, "cache", "verdicts.json");
59464
- if (existsSync13(cacheFile)) {
61484
+ const cacheFile = join22(opts.output, "cache", "verdicts.json");
61485
+ if (existsSync14(cacheFile)) {
59465
61486
  try {
59466
61487
  unlinkSync3(cacheFile);
59467
- console.log(chalk17.dim(` cache wiped: ${cacheFile}`));
61488
+ console.log(chalk18.dim(` cache wiped: ${cacheFile}`));
59468
61489
  } catch (err) {
59469
- console.log(chalk17.yellow(` cache wipe falhou: ${err.message}`));
61490
+ console.log(chalk18.yellow(` cache wipe falhou: ${err.message}`));
59470
61491
  }
59471
61492
  }
59472
61493
  }
59473
61494
  const llmTimeoutRaw = opts.llmTimeout ?? 60;
59474
61495
  if (!Number.isFinite(llmTimeoutRaw)) {
59475
- console.error(chalk17.red(` --llm-timeout inválido: "${opts.llmTimeout}" não é um número`));
61496
+ console.error(chalk18.red(` --llm-timeout inválido: "${opts.llmTimeout}" não é um número`));
59476
61497
  return 2;
59477
61498
  }
59478
61499
  const llmTimeoutSec = Math.max(5, Math.floor(llmTimeoutRaw));
59479
61500
  if (isLlmAvailable()) {
59480
- console.log(chalk17.dim(` llm: ${providerLabel()} (timeout=${llmTimeoutSec}s)`));
61501
+ console.log(chalk18.dim(` llm: ${providerLabel()} (timeout=${llmTimeoutSec}s)`));
59481
61502
  } else {
59482
- console.log(chalk17.dim(" llm: offline (LLM keys ausentes — agregação heurística)"));
61503
+ console.log(chalk18.dim(" llm: offline (LLM keys ausentes — agregação heurística)"));
59483
61504
  }
59484
61505
  if (isInteractiveMode()) {
59485
- console.log(chalk17.dim(" interactive: enabled — TTY + no LLM. Missing selectors will pause to prompt (disable with --no-interactive). Issue #72."));
61506
+ console.log(chalk18.dim(" interactive: enabled — TTY + no LLM. Missing selectors will pause to prompt (disable with --no-interactive). Issue #72."));
59486
61507
  }
59487
61508
  const primaryViewport = viewports[0] ?? "mobile";
59488
61509
  const preflight = await preflightCheck(opts.prod, opts.cand, primaryViewport);
59489
61510
  if (!preflight.ok) {
59490
- console.error(chalk17.red(`
61511
+ console.error(chalk18.red(`
59491
61512
  ✖ pre-flight falhou:`));
59492
61513
  for (const err of preflight.errors)
59493
- console.error(chalk17.red(` - ${err}`));
59494
- console.error(chalk17.dim(`
61514
+ console.error(chalk18.red(` - ${err}`));
61515
+ console.error(chalk18.dim(`
59495
61516
  dica: verifique se as URLs estão corretas e acessíveis`));
59496
61517
  return 2;
59497
61518
  }
@@ -59502,7 +61523,7 @@ async function runCommand(rawOpts) {
59502
61523
  if (prodHomeHtml) {
59503
61524
  platform = detectPlatform({ url: opts.prod, html: prodHomeHtml });
59504
61525
  if (platform !== "custom") {
59505
- console.log(chalk17.dim(` Detected platform: ${platform}`));
61526
+ console.log(chalk18.dim(` Detected platform: ${platform}`));
59506
61527
  }
59507
61528
  }
59508
61529
  const prodHost = hostOf3(opts.prod);
@@ -59537,11 +61558,11 @@ async function runCommand(rawOpts) {
59537
61558
  viewports,
59538
61559
  timestamp
59539
61560
  });
59540
- console.log(chalk17.bold(`
61561
+ console.log(chalk18.bold(`
59541
61562
  parity run ${runId}`));
59542
- console.log(chalk17.dim(` prod: ${opts.prod}`));
59543
- console.log(chalk17.dim(` cand: ${opts.cand}`));
59544
- console.log(chalk17.dim(` flows: ${flows2.join(", ")} · viewports: ${viewports.join(", ")} · CEP: ${rc.cep}
61563
+ console.log(chalk18.dim(` prod: ${opts.prod}`));
61564
+ console.log(chalk18.dim(` cand: ${opts.cand}`));
61565
+ console.log(chalk18.dim(` flows: ${flows2.join(", ")} · viewports: ${viewports.join(", ")} · CEP: ${rc.cep}
59545
61566
  `));
59546
61567
  const spinner = ora6("Launching browser…").start();
59547
61568
  let browser = null;
@@ -59553,7 +61574,7 @@ async function runCommand(rawOpts) {
59553
61574
  const min = Math.floor(elapsedSec / 60);
59554
61575
  const sec = elapsedSec % 60;
59555
61576
  const mmss = `${min.toString().padStart(2, "0")}:${sec.toString().padStart(2, "0")}`;
59556
- spinner.text = `${chalk17.dim(`⏱ ${mmss} ·`)} ${currentSpinnerLabel}`;
61577
+ spinner.text = `${chalk18.dim(`⏱ ${mmss} ·`)} ${currentSpinnerLabel}`;
59557
61578
  };
59558
61579
  const setSpinnerLabel = (label) => {
59559
61580
  currentSpinnerLabel = label;
@@ -59578,7 +61599,7 @@ async function runCommand(rawOpts) {
59578
61599
  b.close().catch(() => {
59579
61600
  return;
59580
61601
  }),
59581
- new Promise((resolve4) => setTimeout(resolve4, capMs))
61602
+ new Promise((resolve5) => setTimeout(resolve5, capMs))
59582
61603
  ]);
59583
61604
  };
59584
61605
  const shutdown = async (reason) => {
@@ -59657,8 +61678,8 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
59657
61678
  const traceEnabled = process.env.PARITY_TRACE === "1";
59658
61679
  const runOneSide = async (viewport, side) => {
59659
61680
  const baseUrl = side === "prod" ? opts.prod : opts.cand;
59660
- const harPath = join18(paths.harDir, `${viewport}-${side}.har`);
59661
- const tracePath = traceEnabled ? join18(paths.tracesDir, `${viewport}-${side}.zip`) : null;
61681
+ const harPath = join22(paths.harDir, `${viewport}-${side}.har`);
61682
+ const tracePath = traceEnabled ? join22(paths.tracesDir, `${viewport}-${side}.zip`) : null;
59662
61683
  const ctx = await newContext(browser, {
59663
61684
  viewport,
59664
61685
  harPath,
@@ -59673,8 +61694,8 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
59673
61694
  for (const flow of flows2) {
59674
61695
  const flowStart = Date.now();
59675
61696
  let lastStepTotal = 0;
59676
- const sideTag = side === "prod" ? chalk17.cyan("prod") : chalk17.magenta("cand");
59677
- const prefix = `${chalk17.dim(`[${viewport}/`)}${sideTag}${chalk17.dim("]")}`;
61697
+ const sideTag = side === "prod" ? chalk18.cyan("prod") : chalk18.magenta("cand");
61698
+ const prefix = `${chalk18.dim(`[${viewport}/`)}${sideTag}${chalk18.dim("]")}`;
59678
61699
  setSpinnerLabel(`${prefix} ${flow}: starting…`);
59679
61700
  const cap = await runFlow(flow, {
59680
61701
  baseUrl,
@@ -59691,7 +61712,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
59691
61712
  onStep: (event) => {
59692
61713
  if (event.phase === "start") {
59693
61714
  lastStepTotal = event.total;
59694
- setSpinnerLabel(`${prefix} ${flow} ${chalk17.dim(`${event.index}/${event.total}`)} ${event.name}…`);
61715
+ setSpinnerLabel(`${prefix} ${flow} ${chalk18.dim(`${event.index}/${event.total}`)} ${event.name}…`);
59695
61716
  }
59696
61717
  }
59697
61718
  });
@@ -59700,18 +61721,18 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
59700
61721
  const target = lastStepTotal || recorded;
59701
61722
  const failed = cap.steps?.find((s) => s.status === "failed");
59702
61723
  const lastStep = cap.steps?.[cap.steps.length - 1];
59703
- const elapsedDim = chalk17.dim(`${((Date.now() - flowStart) / 1000).toFixed(1)}s`);
59704
- const counts = target > 0 ? chalk17.dim(`${okSteps}/${target}`) : "";
61724
+ const elapsedDim = chalk18.dim(`${((Date.now() - flowStart) / 1000).toFixed(1)}s`);
61725
+ const counts = target > 0 ? chalk18.dim(`${okSteps}/${target}`) : "";
59705
61726
  let glyph;
59706
61727
  let detail;
59707
61728
  if (failed) {
59708
- glyph = chalk17.red("✗");
59709
- detail = `stopped at ${chalk17.yellow(failed.name)}`;
61729
+ glyph = chalk18.red("✗");
61730
+ detail = `stopped at ${chalk18.yellow(failed.name)}`;
59710
61731
  } else if (target > 0 && okSteps < target) {
59711
- glyph = chalk17.yellow("▴");
59712
- detail = lastStep ? `ended at ${chalk17.dim(lastStep.name)}` : "incomplete";
61732
+ glyph = chalk18.yellow("▴");
61733
+ detail = lastStep ? `ended at ${chalk18.dim(lastStep.name)}` : "incomplete";
59713
61734
  } else {
59714
- glyph = chalk17.green("✓");
61735
+ glyph = chalk18.green("✓");
59715
61736
  detail = "";
59716
61737
  }
59717
61738
  const summary = `${glyph} ${prefix} ${flow} ${counts} ${detail} ${elapsedDim}`.replace(/\s+/g, " ").trim();
@@ -59773,7 +61794,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
59773
61794
  const vitalsPagesLimit = opts.vitalsPages ?? vitalsPagesDefault;
59774
61795
  const vitalsRuns = Math.max(1, Number.parseInt(opts.runs, 10) || 1);
59775
61796
  if (candIsDevServer && vitalsPagesLimit > 0) {
59776
- console.log(chalk17.dim(` cand=localhost detectado — vitals-pages=${vitalsPagesLimit}, networkidle desabilitado (issue #55)`));
61797
+ console.log(chalk18.dim(` cand=localhost detectado — vitals-pages=${vitalsPagesLimit}, networkidle desabilitado (issue #55)`));
59777
61798
  }
59778
61799
  if (browser && vitalsPagesLimit > 0) {
59779
61800
  currentPhase = "vitals-pages";
@@ -59854,8 +61875,8 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
59854
61875
  noNetworkIdle: targetIsDevServer,
59855
61876
  runs: vitalsRuns
59856
61877
  }),
59857
- new Promise((resolve4) => {
59858
- const t = setTimeout(() => resolve4(null), PER_TASK_WALLCLOCK_MS);
61878
+ new Promise((resolve5) => {
61879
+ const t = setTimeout(() => resolve5(null), PER_TASK_WALLCLOCK_MS);
59859
61880
  t.unref?.();
59860
61881
  })
59861
61882
  ]);
@@ -59974,7 +61995,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
59974
61995
  setSpinnerLabel("Rodando checks…");
59975
61996
  spinner.start();
59976
61997
  const checksHb = attachSpinnerHeartbeat(spinner, { baseText: "Rodando checks…" });
59977
- const cacheDir = join18(opts.output, "cache");
61998
+ const cacheDir = join22(opts.output, "cache");
59978
61999
  const checkCtx = {
59979
62000
  prodPages: allPageCaptures.filter((p) => p.side === "prod"),
59980
62001
  candPages: allPageCaptures.filter((p) => p.side === "cand"),
@@ -60096,7 +62117,7 @@ ${formatTimingsSummary(partialTimings, buildFlowBreakdown(allFlowCaptures))}
60096
62117
  ${formatTimingsSummary(runTimings, buildFlowBreakdown(allFlowCaptures))}`);
60097
62118
  const failOnGate = evaluateFailOnGate(allIssues, failOn);
60098
62119
  if (failOnGate.exitCode === 1) {
60099
- console.log(chalk17.red(failOnGate.message));
62120
+ console.log(chalk18.red(failOnGate.message));
60100
62121
  return 1;
60101
62122
  }
60102
62123
  if (opts.open) {
@@ -60156,10 +62177,10 @@ function buildPartialRun(args) {
60156
62177
  }
60157
62178
  function resolveExplicitPages(pagesFile, pagesList) {
60158
62179
  if (pagesFile) {
60159
- if (!existsSync13(pagesFile)) {
62180
+ if (!existsSync14(pagesFile)) {
60160
62181
  throw new Error(`--pages-file não encontrado: ${pagesFile}`);
60161
62182
  }
60162
- const raw = readFileSync14(pagesFile, "utf-8");
62183
+ const raw = readFileSync16(pagesFile, "utf-8");
60163
62184
  const lines = raw.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0 && !l.startsWith("#"));
60164
62185
  return lines.map(normalizePath);
60165
62186
  }
@@ -60310,44 +62331,44 @@ function hostOf3(url) {
60310
62331
  }
60311
62332
  function printSummary5(run, htmlPath, meta) {
60312
62333
  const { verdict: verdict2 } = run;
60313
- const emoji = verdict2.status === "pass" ? chalk17.green("✔") : verdict2.status === "warn" ? chalk17.yellow("⚠") : chalk17.red("✖");
60314
- const score = verdict2.status === "pass" ? chalk17.green(verdict2.score) : verdict2.status === "warn" ? chalk17.yellow(verdict2.score) : chalk17.red(verdict2.score);
62334
+ const emoji = verdict2.status === "pass" ? chalk18.green("✔") : verdict2.status === "warn" ? chalk18.yellow("⚠") : chalk18.red("✖");
62335
+ const score = verdict2.status === "pass" ? chalk18.green(verdict2.score) : verdict2.status === "warn" ? chalk18.yellow(verdict2.score) : chalk18.red(verdict2.score);
60315
62336
  const prev2 = run.previousRun;
60316
- const scoreDelta = !prev2 ? chalk17.dim(" (sem run anterior comparável)") : prev2.scoreDelta > 0 ? chalk17.green(` (+${prev2.scoreDelta} vs run anterior: ${prev2.score})`) : prev2.scoreDelta < 0 ? chalk17.red(` (${prev2.scoreDelta} vs run anterior: ${prev2.score})`) : chalk17.dim(` (= run anterior: ${prev2.score})`);
62337
+ const scoreDelta = !prev2 ? chalk18.dim(" (sem run anterior comparável)") : prev2.scoreDelta > 0 ? chalk18.green(` (+${prev2.scoreDelta} vs run anterior: ${prev2.score})`) : prev2.scoreDelta < 0 ? chalk18.red(` (${prev2.scoreDelta} vs run anterior: ${prev2.score})`) : chalk18.dim(` (= run anterior: ${prev2.score})`);
60317
62338
  console.log("");
60318
62339
  console.log(` ${emoji} parity ${verdict2.status.toUpperCase()} · score ${score}/100${scoreDelta}`);
60319
- console.log(` checks: ${chalk17.green(verdict2.checksPassed)} pass · ${chalk17.red(verdict2.checksFailed)} fail · ${chalk17.dim(`${verdict2.checksSkipped} skipped`)}`);
60320
- console.log(` issues: ${chalk17.red(verdict2.critical)} critical · ${chalk17.yellow(verdict2.high)} high · ${verdict2.medium} medium · ${chalk17.dim(`${verdict2.low} low`)}`);
62340
+ console.log(` checks: ${chalk18.green(verdict2.checksPassed)} pass · ${chalk18.red(verdict2.checksFailed)} fail · ${chalk18.dim(`${verdict2.checksSkipped} skipped`)}`);
62341
+ console.log(` issues: ${chalk18.red(verdict2.critical)} critical · ${chalk18.yellow(verdict2.high)} high · ${verdict2.medium} medium · ${chalk18.dim(`${verdict2.low} low`)}`);
60321
62342
  if (run.moduleVerdicts && run.moduleVerdicts.length > 0) {
60322
62343
  const perModule = run.moduleVerdicts.map((mv) => {
60323
- const colored = mv.status === "pass" ? chalk17.green(mv.score) : mv.status === "warn" ? chalk17.yellow(mv.score) : chalk17.red(mv.score);
62344
+ const colored = mv.status === "pass" ? chalk18.green(mv.score) : mv.status === "warn" ? chalk18.yellow(mv.score) : chalk18.red(mv.score);
60324
62345
  return `${mv.module} ${colored}`;
60325
62346
  }).join(" · ");
60326
62347
  console.log(` modules: ${perModule} → composite ${score}`);
60327
62348
  }
60328
62349
  if (run.visualDiff) {
60329
62350
  const vd = run.visualDiff;
60330
- const parityIcon = vd.parityOk ? chalk17.green("✔") : chalk17.red("✖");
60331
- const parityLabel = vd.parityOk ? chalk17.green("OK") : chalk17.red("DIFFS");
60332
- const cacheNote = vd.pagesFromCache > 0 ? chalk17.dim(` · ${vd.pagesFromCache} cached`) : "";
60333
- console.log(` visual: ${parityIcon} parityOk=${parityLabel} · ${vd.pagesChecked} pages · ${chalk17.red(vd.pagesWithDiffs)} diffs · ${chalk17.green(vd.pagesPassed)} pass${cacheNote}`);
62351
+ const parityIcon = vd.parityOk ? chalk18.green("✔") : chalk18.red("✖");
62352
+ const parityLabel = vd.parityOk ? chalk18.green("OK") : chalk18.red("DIFFS");
62353
+ const cacheNote = vd.pagesFromCache > 0 ? chalk18.dim(` · ${vd.pagesFromCache} cached`) : "";
62354
+ console.log(` visual: ${parityIcon} parityOk=${parityLabel} · ${vd.pagesChecked} pages · ${chalk18.red(vd.pagesWithDiffs)} diffs · ${chalk18.green(vd.pagesPassed)} pass${cacheNote}`);
60334
62355
  }
60335
62356
  if (run.topIssues.length > 0) {
60336
62357
  console.log("");
60337
- console.log(chalk17.bold(" Top issues:"));
62358
+ console.log(chalk18.bold(" Top issues:"));
60338
62359
  for (const g of groupIssues(run.topIssues).slice(0, 5)) {
60339
62360
  const i = g.sample;
60340
- const sev = i.severity === "critical" ? chalk17.red(`[${i.severity}]`) : i.severity === "high" ? chalk17.yellow(`[${i.severity}]`) : chalk17.dim(`[${i.severity}]`);
60341
- const pagesNote = g.pages.length > 1 ? chalk17.dim(` (${g.pages.length} páginas)`) : "";
62361
+ const sev = i.severity === "critical" ? chalk18.red(`[${i.severity}]`) : i.severity === "high" ? chalk18.yellow(`[${i.severity}]`) : chalk18.dim(`[${i.severity}]`);
62362
+ const pagesNote = g.pages.length > 1 ? chalk18.dim(` (${g.pages.length} páginas)`) : "";
60342
62363
  console.log(` ${sev} ${i.summary}${pagesNote}`);
60343
62364
  }
60344
62365
  }
60345
62366
  if (meta.promotedCount > 0 || meta.deprecatedCount > 0) {
60346
62367
  console.log("");
60347
- console.log(chalk17.dim(` \uD83D\uDCDA learned-selectors [${meta.platform}]: ${chalk17.green(`+${meta.promotedCount}`)} promoted · ${chalk17.yellow(meta.deprecatedCount)} deprecated`));
62368
+ console.log(chalk18.dim(` \uD83D\uDCDA learned-selectors [${meta.platform}]: ${chalk18.green(`+${meta.promotedCount}`)} promoted · ${chalk18.yellow(meta.deprecatedCount)} deprecated`));
60348
62369
  }
60349
62370
  console.log("");
60350
- console.log(chalk17.dim(` → ${htmlPath}`));
62371
+ console.log(chalk18.dim(` → ${htmlPath}`));
60351
62372
  console.log("");
60352
62373
  }
60353
62374
 
@@ -60371,26 +62392,26 @@ async function prCommand(opts) {
60371
62392
  preset: opts.preset ?? "ci",
60372
62393
  open: false
60373
62394
  };
60374
- console.log(chalk18.dim(` prod : ${opts.prod}`));
60375
- console.log(chalk18.dim(` preview : ${opts.preview}`));
62395
+ console.log(chalk19.dim(` prod : ${opts.prod}`));
62396
+ console.log(chalk19.dim(` preview : ${opts.preview}`));
60376
62397
  console.log("");
60377
62398
  const runCode = await runCommand(runOpts);
60378
62399
  const runs = listRuns(opts.output);
60379
62400
  if (runs.length === 0) {
60380
- console.error(chalk18.red("no run was produced — cannot build PR comment"));
62401
+ console.error(chalk19.red("no run was produced — cannot build PR comment"));
60381
62402
  return runCode || 1;
60382
62403
  }
60383
62404
  const latest = runs[0];
60384
- const reportJsonPath = join19(opts.output, "runs", latest.id, "report.json");
60385
- if (!existsSync14(reportJsonPath)) {
60386
- console.error(chalk18.red(`report.json not found at ${reportJsonPath}`));
62405
+ const reportJsonPath = join23(opts.output, "runs", latest.id, "report.json");
62406
+ if (!existsSync15(reportJsonPath)) {
62407
+ console.error(chalk19.red(`report.json not found at ${reportJsonPath}`));
60387
62408
  return runCode || 1;
60388
62409
  }
60389
- const run = JSON.parse(readFileSync15(reportJsonPath, "utf8"));
62410
+ const run = JSON.parse(readFileSync17(reportJsonPath, "utf8"));
60390
62411
  const markdown = buildPrComment(run, opts);
60391
62412
  if (opts.out) {
60392
- writeFileSync16(opts.out, markdown, "utf8");
60393
- console.log(chalk18.dim(` wrote PR comment: ${opts.out}`));
62413
+ writeFileSync21(opts.out, markdown, "utf8");
62414
+ console.log(chalk19.dim(` wrote PR comment: ${opts.out}`));
60394
62415
  } else {
60395
62416
  process.stdout.write(`
60396
62417
  ${markdown}
@@ -60398,9 +62419,9 @@ ${markdown}
60398
62419
  }
60399
62420
  if (opts.github && process.env.GITHUB_STEP_SUMMARY) {
60400
62421
  try {
60401
- writeFileSync16(process.env.GITHUB_STEP_SUMMARY, markdown, { flag: "a" });
62422
+ writeFileSync21(process.env.GITHUB_STEP_SUMMARY, markdown, { flag: "a" });
60402
62423
  } catch (err) {
60403
- console.error(chalk18.yellow(`failed to write GITHUB_STEP_SUMMARY: ${err.message}`));
62424
+ console.error(chalk19.yellow(`failed to write GITHUB_STEP_SUMMARY: ${err.message}`));
60404
62425
  }
60405
62426
  }
60406
62427
  return runCode;
@@ -60459,14 +62480,14 @@ function buildPrComment(run, opts) {
60459
62480
  }
60460
62481
 
60461
62482
  // src/commands/prompt.ts
60462
- import { existsSync as existsSync15, writeFileSync as writeFileSync17 } from "node:fs";
60463
- import chalk19 from "chalk";
62483
+ import { existsSync as existsSync16, writeFileSync as writeFileSync22 } from "node:fs";
62484
+ import chalk20 from "chalk";
60464
62485
  function promptCommand(runId, opts) {
60465
62486
  let run;
60466
62487
  try {
60467
62488
  run = loadRun(opts.output, runId);
60468
62489
  } catch (err) {
60469
- console.error(chalk19.red(`✖ ${err.message}`));
62490
+ console.error(chalk20.red(`✖ ${err.message}`));
60470
62491
  return 1;
60471
62492
  }
60472
62493
  const md = buildLlmPrompt(run, {
@@ -60474,11 +62495,11 @@ function promptCommand(runId, opts) {
60474
62495
  limit: opts.limit
60475
62496
  });
60476
62497
  if (opts.out) {
60477
- writeFileSync17(opts.out, md, "utf8");
60478
- console.log(chalk19.green(`✔ prompt salvo em ${opts.out}`));
60479
- if (existsSync15(opts.out)) {
62498
+ writeFileSync22(opts.out, md, "utf8");
62499
+ console.log(chalk20.green(`✔ prompt salvo em ${opts.out}`));
62500
+ if (existsSync16(opts.out)) {
60480
62501
  const sizeKb = (md.length / 1024).toFixed(1);
60481
- console.log(chalk19.dim(` ${md.length} chars (${sizeKb} KB)`));
62502
+ console.log(chalk20.dim(` ${md.length} chars (${sizeKb} KB)`));
60482
62503
  }
60483
62504
  } else {
60484
62505
  process.stdout.write(md);
@@ -60487,9 +62508,9 @@ function promptCommand(runId, opts) {
60487
62508
  }
60488
62509
 
60489
62510
  // src/commands/report.ts
60490
- import { existsSync as existsSync16, readFileSync as readFileSync16 } from "node:fs";
60491
- import chalk20 from "chalk";
60492
- import open from "open";
62511
+ import { existsSync as existsSync17, readFileSync as readFileSync18 } from "node:fs";
62512
+ import chalk21 from "chalk";
62513
+ import open2 from "open";
60493
62514
 
60494
62515
  // src/report/extract-section.ts
60495
62516
  function extractReportSection(input) {
@@ -60637,41 +62658,41 @@ async function reportCommand(runId, opts) {
60637
62658
  const run = loadRun(opts.output, runId);
60638
62659
  const payload = extractReportSection({ kind: "json", section: opts.section, run });
60639
62660
  if (payload === null) {
60640
- console.error(chalk20.red(`section "${opts.section}" not present in this run`));
62661
+ console.error(chalk21.red(`section "${opts.section}" not present in this run`));
60641
62662
  return 1;
60642
62663
  }
60643
62664
  process.stdout.write(`${JSON.stringify(payload, null, 2)}
60644
62665
  `);
60645
62666
  return 0;
60646
62667
  } catch (err) {
60647
- console.error(chalk20.red(`failed to load run: ${err.message}`));
62668
+ console.error(chalk21.red(`failed to load run: ${err.message}`));
60648
62669
  return 1;
60649
62670
  }
60650
62671
  }
60651
- if (!existsSync16(paths.reportHtml)) {
60652
- console.error(chalk20.red(`report.html not found at ${paths.reportHtml}`));
62672
+ if (!existsSync17(paths.reportHtml)) {
62673
+ console.error(chalk21.red(`report.html not found at ${paths.reportHtml}`));
60653
62674
  return 1;
60654
62675
  }
60655
- const html3 = readFileSync16(paths.reportHtml, "utf8");
62676
+ const html3 = readFileSync18(paths.reportHtml, "utf8");
60656
62677
  const slice2 = extractReportSection({ kind: "html", section: opts.section, html: html3 });
60657
62678
  if (slice2 === null) {
60658
- console.error(chalk20.red(`section "${opts.section}" not present in this report`));
62679
+ console.error(chalk21.red(`section "${opts.section}" not present in this report`));
60659
62680
  return 1;
60660
62681
  }
60661
62682
  process.stdout.write(slice2);
60662
62683
  return 0;
60663
62684
  }
60664
- console.log(chalk20.dim(`opening ${paths.reportHtml}`));
60665
- await open(paths.reportHtml).catch((err) => {
60666
- console.error(chalk20.red(`failed to open: ${err.message}`));
62685
+ console.log(chalk21.dim(`opening ${paths.reportHtml}`));
62686
+ await open2(paths.reportHtml).catch((err) => {
62687
+ console.error(chalk21.red(`failed to open: ${err.message}`));
60667
62688
  });
60668
62689
  return 0;
60669
62690
  }
60670
62691
 
60671
62692
  // src/commands/vitals.ts
60672
- import { existsSync as existsSync17, readFileSync as readFileSync17, writeFileSync as writeFileSync18 } from "node:fs";
60673
- import { join as join20 } from "node:path";
60674
- import chalk21 from "chalk";
62693
+ import { existsSync as existsSync18, readFileSync as readFileSync19, writeFileSync as writeFileSync23 } from "node:fs";
62694
+ import { join as join24 } from "node:path";
62695
+ import chalk22 from "chalk";
60675
62696
  import ora7 from "ora";
60676
62697
  async function vitalsCommand(opts) {
60677
62698
  const viewports = opts.viewports.split(",").map((s) => s.trim()).filter((s) => s === "mobile" || s === "desktop");
@@ -60679,10 +62700,10 @@ async function vitalsCommand(opts) {
60679
62700
  const runId = newRunId();
60680
62701
  const paths = createRunDir(opts.output, runId);
60681
62702
  const t0 = Date.now();
60682
- console.log(chalk21.bold(`
62703
+ console.log(chalk22.bold(`
60683
62704
  parity vitals ${runId}`));
60684
- console.log(chalk21.dim(` prod: ${opts.prod}`));
60685
- console.log(chalk21.dim(` cand: ${opts.cand}`));
62705
+ console.log(chalk22.dim(` prod: ${opts.prod}`));
62706
+ console.log(chalk22.dim(` cand: ${opts.cand}`));
60686
62707
  const discoverSpinner = ora7("Descobrindo páginas…").start();
60687
62708
  const pagePaths = await discoverPagePaths2(opts.prod, opts);
60688
62709
  if (pagePaths.length === 0) {
@@ -60714,7 +62735,7 @@ async function vitalsCommand(opts) {
60714
62735
  completed++;
60715
62736
  const elapsed = ((Date.now() - t0) / 1000).toFixed(0);
60716
62737
  const etaSec = completed > 0 ? Math.round((Date.now() - t0) / completed * (total - completed) / 1000) : 0;
60717
- progress.text = `${completed}/${total} · ${elapsed}s · ETA ${etaSec}s · ${task.side === "prod" ? chalk21.cyan("prod") : chalk21.magenta("cand")} ${task.path} (${task.viewport})`;
62738
+ progress.text = `${completed}/${total} · ${elapsed}s · ETA ${etaSec}s · ${task.side === "prod" ? chalk22.cyan("prod") : chalk22.magenta("cand")} ${task.path} (${task.viewport})`;
60718
62739
  }
60719
62740
  });
60720
62741
  progress.succeed(`${total} capture(s) em ${((Date.now() - t0) / 1000).toFixed(1)}s`);
@@ -60778,7 +62799,7 @@ async function vitalsCommand(opts) {
60778
62799
  writeRunReportJson(paths.runDir, run);
60779
62800
  const html3 = renderHtmlReport(run, paths.runDir);
60780
62801
  writeRunReportHtml(paths.runDir, html3);
60781
- writeFileSync18(join20(paths.runDir, "vitals.json"), `${JSON.stringify({
62802
+ writeFileSync23(join24(paths.runDir, "vitals.json"), `${JSON.stringify({
60782
62803
  schemaVersion: "0.1",
60783
62804
  prodUrl: opts.prod,
60784
62805
  candUrl: opts.cand,
@@ -60789,12 +62810,12 @@ async function vitalsCommand(opts) {
60789
62810
  `, "utf8");
60790
62811
  printSummary6(vitalsResult, cacheResult);
60791
62812
  console.log("");
60792
- console.log(chalk21.dim(` → ${paths.reportHtml}`));
60793
- console.log(chalk21.dim(` \uD83D\uDCA1 use 'parity serve ${runId}' pra preview iframe`));
62813
+ console.log(chalk22.dim(` → ${paths.reportHtml}`));
62814
+ console.log(chalk22.dim(` \uD83D\uDCA1 use 'parity serve ${runId}' pra preview iframe`));
60794
62815
  console.log("");
60795
62816
  if (opts.open) {
60796
- const { default: open2 } = await import("open");
60797
- await open2(paths.reportHtml).catch(() => {
62817
+ const { default: open3 } = await import("open");
62818
+ await open3(paths.reportHtml).catch(() => {
60798
62819
  return;
60799
62820
  });
60800
62821
  }
@@ -60877,8 +62898,8 @@ async function discoverPagePaths2(prodUrl, opts) {
60877
62898
  function parseUrlList(input) {
60878
62899
  if (input.startsWith("file:") || input.endsWith(".txt") || input.endsWith(".list")) {
60879
62900
  const path = input.replace(/^file:\/\//, "");
60880
- if (existsSync17(path)) {
60881
- return readFileSync17(path, "utf8").split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !s.startsWith("#")).map((s) => s.startsWith("/") ? s : `/${s}`);
62901
+ if (existsSync18(path)) {
62902
+ return readFileSync19(path, "utf8").split(/\r?\n/).map((s) => s.trim()).filter((s) => s && !s.startsWith("#")).map((s) => s.startsWith("/") ? s : `/${s}`);
60882
62903
  }
60883
62904
  }
60884
62905
  return input.split(",").map((s) => s.trim()).filter(Boolean).map((s) => s.startsWith("/") || s.startsWith("http") ? s : `/${s}`);
@@ -60896,22 +62917,22 @@ async function runWithConcurrency3(items, workers, fn) {
60896
62917
  }
60897
62918
  function printSummary6(vitals, cache) {
60898
62919
  console.log("");
60899
- console.log(chalk21.bold(" Summary:"));
62920
+ console.log(chalk22.bold(" Summary:"));
60900
62921
  console.log(` ${vitals.summary}`);
60901
62922
  console.log(` ${cache.summary}`);
60902
62923
  }
60903
62924
 
60904
62925
  // src/util/version.ts
60905
- import { readFileSync as readFileSync18 } from "node:fs";
60906
- import { dirname as dirname5, resolve as resolve4 } from "node:path";
62926
+ import { readFileSync as readFileSync20 } from "node:fs";
62927
+ import { dirname as dirname5, resolve as resolve5 } from "node:path";
60907
62928
  import { fileURLToPath } from "node:url";
60908
62929
  function getPackageVersion() {
60909
62930
  try {
60910
62931
  const here = dirname5(fileURLToPath(import.meta.url));
60911
62932
  for (const up of ["..", "../..", "../../.."]) {
60912
62933
  try {
60913
- const pkgPath = resolve4(here, up, "package.json");
60914
- const raw = readFileSync18(pkgPath, "utf8");
62934
+ const pkgPath = resolve5(here, up, "package.json");
62935
+ const raw = readFileSync20(pkgPath, "utf8");
60915
62936
  const parsed = JSON.parse(raw);
60916
62937
  if (parsed.name === "@decocms/parity" && typeof parsed.version === "string") {
60917
62938
  return parsed.version;
@@ -60924,7 +62945,7 @@ function getPackageVersion() {
60924
62945
 
60925
62946
  // src/cli.ts
60926
62947
  var program = new Command;
60927
- program.name("parity").description("E2E parity validator for Fresh -> TanStack site migrations").version(getPackageVersion());
62948
+ program.name("parity").description("E2E parity validator + migration capture for site migrations").version(getPackageVersion());
60928
62949
  program.command("run").description([
60929
62950
  "Compare two URLs and produce a parity report.",
60930
62951
  "",
@@ -61096,6 +63117,22 @@ program.command("extract").description("Single-site AI-ready component extractio
61096
63117
  json: opts.json
61097
63118
  }));
61098
63119
  });
63120
+ program.command("migrate").description("Single-site, phased migration capture (theme → sitemap → components). No prod×cand comparison — produces a target-agnostic, token-lean bundle + prompt for a migration agent: site theme (colors/typography/spacing as Tailwind tokens), classified pages, and per-component detail (suggested Tailwind classes, interaction hints, e2e selectors). Works whether or not the source code exists. Pass --target faststore to append a target playbook. Resumable: re-runs skip a completed phase unless --refresh.").requiredOption("--url <url>", "Site to migrate from").option("--pages <list>", 'Comma-separated pages: literal paths/URLs, and/or "category-auto"/"pdp-auto". Default: "/,category-auto,pdp-auto" (home + a PLP + a PDP).').option("--components <list>", "Comma-separated role allowlist, e.g. header,footer,nav,shelf,minicart. Default: all detected.").option("--target <name>", "Target playbook to append to the prompt (e.g. faststore)").option("--viewport <viewport>", "Primary viewport for component capture: mobile | desktop | tablet", "mobile").option("--viewports <list>", "Comma-separated viewports for theme + site screenshots (e.g. mobile,desktop). Default: --viewport only.").option("--format <fmt>", "md | json | both", "both").option("--out <dir>", "Output directory (stable per host, for resume)", "./parity-migrate").option("--refresh", "Re-run all phases even if cached artifacts exist", false).option("--open", "Open the generated index.html visual report in the browser", false).option("--no-llm", "Skip the optional LLM component-relabeling pass (heuristic detection always runs regardless).").option("--json", "Emit one-line JSON instead of pretty text", false).action(async (opts) => {
63121
+ process.exit(await migrateCommand({
63122
+ url: opts.url,
63123
+ pages: opts.pages,
63124
+ components: opts.components,
63125
+ target: opts.target,
63126
+ viewport: opts.viewport,
63127
+ viewports: opts.viewports,
63128
+ format: opts.format,
63129
+ outDir: opts.out,
63130
+ refresh: opts.refresh,
63131
+ open: opts.open,
63132
+ noLlm: !opts.llm,
63133
+ json: opts.json
63134
+ }));
63135
+ });
61099
63136
  program.command("learned").description("Inspect the learned-selectors library").addCommand(new Command("stats").description("Print learned-selectors stats per platform").action(() => {
61100
63137
  process.exit(learnedStats());
61101
63138
  })).addCommand(new Command("validate").description("Debug: run selector discovery + live-validation against a single URL and print a table (not part of `parity run`)").requiredOption("--url <url>", "URL to fetch + discover + validate").action(async (opts) => {