@allons-y/actions-file-diff 0.2.0 → 0.3.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/index.js CHANGED
@@ -25678,7 +25678,7 @@ function getOctokit(token, options, ...additionalPlugins) {
25678
25678
 
25679
25679
  // src/changes.js
25680
25680
  import { execFile } from "node:child_process";
25681
- import { closeSync, openSync, readSync } from "node:fs";
25681
+ import { closeSync, mkdtempSync, openSync, readFileSync as readFileSync3, readSync, rmSync, writeFileSync } from "node:fs";
25682
25682
  import { devNull, tmpdir } from "node:os";
25683
25683
  import { join as join6 } from "node:path";
25684
25684
  import { promisify } from "node:util";
@@ -25885,7 +25885,7 @@ import * as os6 from "os";
25885
25885
  import * as path9 from "path";
25886
25886
  import assert3 from "assert";
25887
25887
 
25888
- // node_modules/brace-expansion/node_modules/balanced-match/dist/esm/index.js
25888
+ // node_modules/balanced-match/dist/esm/index.js
25889
25889
  var balanced = (a, b, str) => {
25890
25890
  const ma = a instanceof RegExp ? maybeMatch(a, str) : a;
25891
25891
  const mb = b instanceof RegExp ? maybeMatch(b, str) : b;
@@ -28482,7 +28482,7 @@ function buildReport({ headMap = /* @__PURE__ */ new Map(), baseMap = /* @__PURE
28482
28482
  summary2.push("No base branch to compare against.", "");
28483
28483
  } else if (hasChanged) {
28484
28484
  const percent = printPercentChange(headTotal, baseTotal);
28485
- summary2.push(`**Total change (\u0394)**: ${printChange(headTotal, baseTotal)}${percent ? ` (${percent})` : ""}`, "", `<small><em>Table reports on changes to a package's main file.${sections.length > 1 ? ` Other changes can be found in the collapsed <a href="#details">Details</a> section below.` : ""}</em></small>`, "");
28485
+ summary2.push(`**Total change (\u0394)**: ${printChange(headTotal, baseTotal)}${percent ? ` (${percent})` : ""}`, "", `<small><em>Table reports on changes to a package's main file.${sections.length > 1 ? ' Other changes can be found in the collapsed <a href="#details">Details</a> section below.' : ""}</em></small>`, "");
28486
28486
  } else {
28487
28487
  summary2.push("\u2705 **No change in file sizes**", "");
28488
28488
  }
@@ -28519,6 +28519,10 @@ var DIFF_CONCURRENCY = 4;
28519
28519
  var SNIFF_BYTES = 8e3;
28520
28520
  var COMPARE_CHUNK = 64 * 1024;
28521
28521
  var MAX_OUTPUT = 32 * 1024 * 1024;
28522
+ var IGNORED = "[ignored]";
28523
+ function ignoreMatches(text, patterns) {
28524
+ return patterns.reduce((out, pattern) => out.replace(pattern, IGNORED), text);
28525
+ }
28522
28526
  function isBinary(buffer) {
28523
28527
  return buffer.subarray(0, SNIFF_BYTES).includes(0);
28524
28528
  }
@@ -28599,7 +28603,7 @@ async function gitDiff({ basePath, headPath, git = "git", timeout = DIFF_TIMEOUT
28599
28603
  throw Object.assign(new Error(reason), { reason, cause: error2 });
28600
28604
  }
28601
28605
  }
28602
- async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), headRoot, baseRoot, extensions = [], maxDiffSize = DEFAULT_MAX_DIFF_SIZE, maxDiffLines = DEFAULT_MAX_DIFF_LINES, git = "git", diffTimeout = DIFF_TIMEOUT, diffTimeBudget = DIFF_TIME_BUDGET, core }) {
28606
+ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), headRoot, baseRoot, renames = /* @__PURE__ */ new Map(), ignorePatterns = [], extensions = [], maxDiffSize = DEFAULT_MAX_DIFF_SIZE, maxDiffLines = DEFAULT_MAX_DIFF_LINES, git = "git", diffTimeout = DIFF_TIMEOUT, diffTimeBudget = DIFF_TIME_BUDGET, core }) {
28603
28607
  const allowed = normalizeExtensions(extensions);
28604
28608
  const head = filterByExtensions(headMap, allowed);
28605
28609
  const base = filterByExtensions(baseMap, allowed);
@@ -28615,7 +28619,8 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28615
28619
  const status = changeStatus(headByteSize, baseByteSize);
28616
28620
  if (!status) return;
28617
28621
  const headPath = headByteSize != null ? join6(headRoot, file) : void 0;
28618
- const basePath = baseByteSize != null && baseRoot ? join6(baseRoot, file) : void 0;
28622
+ const from = renames.get(file);
28623
+ const basePath = baseByteSize != null && baseRoot ? join6(baseRoot, from ?? file) : void 0;
28619
28624
  let failure;
28620
28625
  if (status === "modified" && headByteSize === baseByteSize) {
28621
28626
  try {
@@ -28624,12 +28629,26 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28624
28629
  failure = error2;
28625
28630
  }
28626
28631
  }
28632
+ let ignored;
28633
+ const textFile = !isImage(file) || baseExtension(file) === "svg";
28634
+ if (status === "modified" && !failure && ignorePatterns.length > 0 && textFile && Math.max(headByteSize, baseByteSize) <= maxDiffSize) {
28635
+ try {
28636
+ const headContent = readFileSync3(headPath);
28637
+ const baseContent = readFileSync3(basePath);
28638
+ if (!isBinary(headContent) && !isBinary(baseContent)) {
28639
+ ignored = { head: ignoreMatches(headContent.toString("utf8"), ignorePatterns), base: ignoreMatches(baseContent.toString("utf8"), ignorePatterns) };
28640
+ if (ignored.head === ignored.base) return;
28641
+ }
28642
+ } catch (error2) {
28643
+ failure = error2;
28644
+ }
28645
+ }
28627
28646
  stats[status]++;
28628
28647
  if (isImage(file)) {
28629
- images.push({ file, status, headByteSize, baseByteSize, headPath, basePath });
28648
+ images.push({ file, status, headByteSize, baseByteSize, headPath, basePath, ...from ? { from } : {} });
28630
28649
  if (baseExtension(file) !== "svg") return;
28631
28650
  }
28632
- const change = { file, status, additions: 0, deletions: 0, hunks: [] };
28651
+ const change = { file, status, additions: 0, deletions: 0, hunks: [], ...from ? { from } : {} };
28633
28652
  text.push(change);
28634
28653
  if (!failure) {
28635
28654
  try {
@@ -28650,7 +28669,7 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28650
28669
  change.skipped = "file exceeds max-diff-size";
28651
28670
  return;
28652
28671
  }
28653
- pending.push({ change, headPath, basePath });
28672
+ pending.push({ change, headPath, basePath, ignored });
28654
28673
  });
28655
28674
  if (unreadable.length > 0) core?.warning?.(`Could not read ${unreadable.length} file${unreadable.length === 1 ? "" : "s"}; listed without a diff: ${unreadable.slice(0, 5).join(", ")}${unreadable.length > 5 ? ", \u2026" : ""}`);
28656
28675
  if (pending.length > 0 && !await hasGit(git)) {
@@ -28660,33 +28679,44 @@ async function collectChanges({ headMap, baseMap = /* @__PURE__ */ new Map(), he
28660
28679
  }
28661
28680
  const started = Date.now();
28662
28681
  let retained = 0;
28663
- for (let i = 0; i < pending.length; i += DIFF_CONCURRENCY * 8) {
28664
- const batch = pending.slice(i, i + DIFF_CONCURRENCY * 8);
28665
- const results = await mapLimit(batch, DIFF_CONCURRENCY, async ({ headPath, basePath }) => {
28666
- if (Date.now() - started > diffTimeBudget) return { reason: "diff time budget exhausted" };
28667
- try {
28668
- return await gitDiff({ basePath, headPath, git, timeout: diffTimeout });
28669
- } catch (error2) {
28670
- return { reason: error2.reason ?? error2.message };
28671
- }
28672
- });
28673
- results.forEach((result, index) => {
28674
- const { change } = batch[index];
28675
- if (result.reason) {
28676
- change.skipped = result.reason;
28677
- return;
28678
- }
28679
- change.additions = result.additions;
28680
- change.deletions = result.deletions;
28681
- stats.additions += result.additions;
28682
- stats.deletions += result.deletions;
28683
- const lines = result.hunks.reduce((sum, hunk) => sum + hunk.lines.length + 1, 0);
28684
- if (retained + lines > maxDiffLines) change.omitted = `the report's diff budget (${maxDiffLines.toLocaleString("en-US")} lines) is used up`;
28685
- else {
28686
- retained += lines;
28687
- change.hunks = result.hunks;
28688
- }
28689
- });
28682
+ const scratch = pending.some(({ ignored }) => ignored) ? mkdtempSync(join6(tmpdir(), "file-diff-")) : void 0;
28683
+ try {
28684
+ for (let i = 0; i < pending.length; i += DIFF_CONCURRENCY * 8) {
28685
+ const batch = pending.slice(i, i + DIFF_CONCURRENCY * 8);
28686
+ const results = await mapLimit(batch, DIFF_CONCURRENCY, async ({ headPath, basePath, ignored }, index) => {
28687
+ if (Date.now() - started > diffTimeBudget) return { reason: "diff time budget exhausted" };
28688
+ try {
28689
+ if (!ignored) return await gitDiff({ basePath, headPath, git, timeout: diffTimeout });
28690
+ const copy = (side) => {
28691
+ const path11 = join6(scratch, `${i + index}.${side}`);
28692
+ writeFileSync(path11, ignored[side]);
28693
+ return path11;
28694
+ };
28695
+ return await gitDiff({ basePath: copy("base"), headPath: copy("head"), git, timeout: diffTimeout });
28696
+ } catch (error2) {
28697
+ return { reason: error2.reason ?? error2.message };
28698
+ }
28699
+ });
28700
+ results.forEach((result, index) => {
28701
+ const { change } = batch[index];
28702
+ if (result.reason) {
28703
+ change.skipped = result.reason;
28704
+ return;
28705
+ }
28706
+ change.additions = result.additions;
28707
+ change.deletions = result.deletions;
28708
+ stats.additions += result.additions;
28709
+ stats.deletions += result.deletions;
28710
+ const lines = result.hunks.reduce((sum, hunk) => sum + hunk.lines.length + 1, 0);
28711
+ if (retained + lines > maxDiffLines) change.omitted = `the report's diff budget (${maxDiffLines.toLocaleString("en-US")} lines) is used up`;
28712
+ else {
28713
+ retained += lines;
28714
+ change.hunks = result.hunks;
28715
+ }
28716
+ });
28717
+ }
28718
+ } finally {
28719
+ if (scratch) rmSync(scratch, { recursive: true, force: true });
28690
28720
  }
28691
28721
  return { text, images, stats };
28692
28722
  }
@@ -28784,6 +28814,119 @@ async function publishToBranch({ octokit, owner, repo, branch, dir, files, messa
28784
28814
  }
28785
28815
  }
28786
28816
 
28817
+ // src/renames.js
28818
+ import { readFileSync as readFileSync4 } from "node:fs";
28819
+ import { join as join7 } from "node:path";
28820
+ var DEFAULT_RENAME_THRESHOLD = 50;
28821
+ var MAX_RENAME_CANDIDATES = 200;
28822
+ var MAX_RENAME_SIZE = 1024 * 1024;
28823
+ var RENAME_TIME_BUDGET = 3e4;
28824
+ var PLACEHOLDER = "[hash]";
28825
+ var CHUNK = 64;
28826
+ var BOUNDARY = /(?<=[\n}])/;
28827
+ function compileNamePatterns(lines = [], input = "normalize-names") {
28828
+ return lines.map((line) => String(line ?? "").trim()).filter(Boolean).map((line) => {
28829
+ try {
28830
+ return new RegExp(line, "g");
28831
+ } catch (error2) {
28832
+ throw new Error(`Invalid ${input} pattern "${line}": ${error2.message}`, { cause: error2 });
28833
+ }
28834
+ });
28835
+ }
28836
+ function normalizeName(path11, patterns) {
28837
+ return patterns.reduce((name, pattern) => name.replace(pattern, PLACEHOLDER), path11);
28838
+ }
28839
+ function chunkCounts(content) {
28840
+ const counts = /* @__PURE__ */ new Map();
28841
+ content.toString("latin1").split(BOUNDARY).forEach((piece) => {
28842
+ for (let i = 0; i < piece.length; i += CHUNK) {
28843
+ const chunk = piece.slice(i, i + CHUNK);
28844
+ counts.set(chunk, (counts.get(chunk) ?? 0) + 1);
28845
+ }
28846
+ });
28847
+ return counts;
28848
+ }
28849
+ function chunkSimilarity(sizeA, countsA, sizeB, countsB) {
28850
+ const larger = Math.max(sizeA, sizeB);
28851
+ if (larger === 0) return 100;
28852
+ const [small, big] = countsA.size <= countsB.size ? [countsA, countsB] : [countsB, countsA];
28853
+ let shared = 0;
28854
+ small.forEach((count, chunk) => {
28855
+ shared += Math.min(count, big.get(chunk) ?? 0) * chunk.length;
28856
+ });
28857
+ return Math.floor(shared / larger * 100);
28858
+ }
28859
+ function groupBy(paths, key) {
28860
+ const groups = /* @__PURE__ */ new Map();
28861
+ paths.forEach((path11) => {
28862
+ const k = key(path11);
28863
+ groups.set(k, [...groups.get(k) ?? [], path11]);
28864
+ });
28865
+ return groups;
28866
+ }
28867
+ function matchRenames({ headMap, baseMap, headRoot, baseRoot, normalizeNames = [], threshold = DEFAULT_RENAME_THRESHOLD, maxCandidates = MAX_RENAME_CANDIDATES, maxSize = MAX_RENAME_SIZE, timeBudget = RENAME_TIME_BUDGET, now = Date.now }) {
28868
+ const renames = /* @__PURE__ */ new Map();
28869
+ const deadline = now() + timeBudget;
28870
+ let timedOut = false;
28871
+ const onlyHead = new Set([...headMap.keys()].filter((path11) => !baseMap.has(path11)));
28872
+ const onlyBase = new Set([...baseMap.keys()].filter((path11) => !headMap.has(path11)));
28873
+ const pair = (head, base) => {
28874
+ renames.set(head, base);
28875
+ onlyHead.delete(head);
28876
+ onlyBase.delete(base);
28877
+ };
28878
+ if (normalizeNames.length > 0) {
28879
+ const heads = groupBy([...onlyHead], (path11) => normalizeName(path11, normalizeNames));
28880
+ groupBy([...onlyBase], (path11) => normalizeName(path11, normalizeNames)).forEach((bases, name) => {
28881
+ const matches = heads.get(name);
28882
+ if (bases.length === 1 && matches?.length === 1 && name !== bases[0]) pair(matches[0], bases[0]);
28883
+ });
28884
+ }
28885
+ if (threshold > 0 && onlyHead.size > 0 && onlyBase.size > 0) {
28886
+ const heads = groupBy([...onlyHead], baseExtension);
28887
+ groupBy([...onlyBase], baseExtension).forEach((bases, ext2) => {
28888
+ const candidates = heads.get(ext2) ?? [];
28889
+ if (timedOut || candidates.length === 0 || bases.length > maxCandidates || candidates.length > maxCandidates) return;
28890
+ const read = (root, map) => (path11) => {
28891
+ if (map.get(path11) > maxSize) return void 0;
28892
+ try {
28893
+ return readFileSync4(join7(root, path11));
28894
+ } catch {
28895
+ return void 0;
28896
+ }
28897
+ };
28898
+ const baseContent = new Map(bases.map((path11) => [path11, read(baseRoot, baseMap)(path11)]));
28899
+ const headContent = new Map(candidates.map((path11) => [path11, read(headRoot, headMap)(path11)]));
28900
+ const counts = new Map([...baseContent.values(), ...headContent.values()].filter((content) => content && !isBinary(content)).map((content) => [content, chunkCounts(content)]));
28901
+ const scores = [];
28902
+ baseContent.forEach((b, base) => {
28903
+ if (!b || timedOut) return;
28904
+ if (now() > deadline) {
28905
+ timedOut = true;
28906
+ return;
28907
+ }
28908
+ headContent.forEach((h, head) => {
28909
+ if (!h) return;
28910
+ if (Math.min(b.length, h.length) * 100 < threshold * Math.max(b.length, h.length)) return;
28911
+ const score = counts.has(b) && counts.has(h) ? chunkSimilarity(b.length, counts.get(b), h.length, counts.get(h)) : b.equals(h) ? 100 : 0;
28912
+ if (score >= threshold) scores.push({ base, head, score });
28913
+ });
28914
+ });
28915
+ scores.sort((x, y) => y.score - x.score || x.base.localeCompare(y.base) || x.head.localeCompare(y.head));
28916
+ scores.forEach(({ base, head }) => {
28917
+ if (onlyBase.has(base) && onlyHead.has(head)) pair(head, base);
28918
+ });
28919
+ });
28920
+ }
28921
+ if (renames.size === 0) return { baseMap, renames, timedOut };
28922
+ const remapped = new Map(baseMap);
28923
+ renames.forEach((base, head) => {
28924
+ remapped.delete(base);
28925
+ remapped.set(head, baseMap.get(base));
28926
+ });
28927
+ return { baseMap: remapped, renames, timedOut };
28928
+ }
28929
+
28787
28930
  // src/inputs.js
28788
28931
  var VISUAL_DIFF_MODES = ["summary", "branch", "none"];
28789
28932
  var BRANCH_NAME = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;
@@ -28801,6 +28944,8 @@ function readInputs(core) {
28801
28944
  if (!VISUAL_DIFF_MODES.includes(visualDiff)) throw new Error(`Invalid visual-diff "${visualDiff}"; expected one of: ${VISUAL_DIFF_MODES.join(", ")}.`);
28802
28945
  const reportBranch = text("report-branch", DEFAULT_REPORT_BRANCH);
28803
28946
  if (!BRANCH_NAME.test(reportBranch) || reportBranch.includes("..") || reportBranch.endsWith(".lock") || reportBranch.endsWith(".")) throw new Error(`Invalid report-branch "${reportBranch}"; use letters, digits, ".", "_", "-" and "/" in a valid git branch name.`);
28947
+ const renameThreshold = count("rename-threshold", DEFAULT_RENAME_THRESHOLD);
28948
+ if (renameThreshold > 100) throw new Error(`Invalid rename-threshold "${renameThreshold}"; expected a percentage from 0 to 100.`);
28804
28949
  const pagesUrl = text("pages-url");
28805
28950
  if (pagesUrl) {
28806
28951
  let url;
@@ -28826,12 +28971,15 @@ function readInputs(core) {
28826
28971
  reportBranch,
28827
28972
  pagesUrl,
28828
28973
  maxDiffSize: count("max-diff-size", DEFAULT_MAX_DIFF_SIZE),
28829
- maxDiffLines: count("max-diff-lines", DEFAULT_MAX_DIFF_LINES)
28974
+ maxDiffLines: count("max-diff-lines", DEFAULT_MAX_DIFF_LINES),
28975
+ normalizeNames: compileNamePatterns(core.getMultilineInput("normalize-names", { trimWhitespace: true })),
28976
+ ignorePatterns: compileNamePatterns(core.getMultilineInput("ignore-patterns", { trimWhitespace: true }), "ignore-patterns"),
28977
+ renameThreshold
28830
28978
  };
28831
28979
  }
28832
28980
 
28833
28981
  // src/page.js
28834
- import { readFileSync as readFileSync3 } from "node:fs";
28982
+ import { readFileSync as readFileSync5 } from "node:fs";
28835
28983
 
28836
28984
  // node_modules/diff/libesm/diff/base.js
28837
28985
  var Diff = class {
@@ -29324,8 +29472,8 @@ function fenceFor(content) {
29324
29472
  const longest = Math.max(0, ...(String(content).match(/`+/g) ?? []).map((run2) => run2.length));
29325
29473
  return "`".repeat(Math.max(3, longest + 1));
29326
29474
  }
29327
- function unifiedDiff({ file, status, hunks }) {
29328
- const from = status === "added" ? "/dev/null" : `a/${file}`;
29475
+ function unifiedDiff({ file, status, hunks, from: renamedFrom }) {
29476
+ const from = status === "added" ? "/dev/null" : `a/${renamedFrom ?? file}`;
29329
29477
  const to = status === "removed" ? "/dev/null" : `b/${file}`;
29330
29478
  const body = hunks.flatMap(({ oldStart, oldLines, newStart, newLines, lines }) => [`@@ -${oldStart},${oldLines} +${newStart},${newLines} @@`, ...lines]);
29331
29479
  return [`--- ${from}`, `+++ ${to}`, ...body].join("\n");
@@ -29360,7 +29508,8 @@ function renderSummaryMarkdown({ rows, hasBase, changes, budget = SUMMARY_BUDGET
29360
29508
  const truncated = [];
29361
29509
  changes.text.forEach((change) => {
29362
29510
  const counts = change.skipped ? "" : ` (+${change.additions} / \u2212${change.deletions})`;
29363
- const heading = `#### \`${change.file}\` \u2014 ${STATUS_LABEL[change.status]}${counts}`;
29511
+ const renamed = change.from ? ` (renamed from \`${change.from}\`)` : "";
29512
+ const heading = `#### \`${change.file}\` \u2014 ${STATUS_LABEL[change.status]}${renamed}${counts}`;
29364
29513
  if (change.skipped) {
29365
29514
  out.push(heading, "", `_Line diff skipped: ${change.skipped}._`, "");
29366
29515
  return;
@@ -29382,7 +29531,7 @@ function renderSummaryMarkdown({ rows, hasBase, changes, budget = SUMMARY_BUDGET
29382
29531
  });
29383
29532
  if (truncated.length > 0) {
29384
29533
  const where = reportUrl2 ? ` See the [full report](${reportUrl2}).` : "";
29385
- out.push(`> [!NOTE]`, `> ${truncated.length} diff(s) omitted to stay under GitHub's summary size limit: ${truncated.map((f) => `\`${f}\``).join(", ")}.${where}`, "");
29534
+ out.push("> [!NOTE]", `> ${truncated.length} diff(s) omitted to stay under GitHub's summary size limit: ${truncated.map((f) => `\`${f}\``).join(", ")}.${where}`, "");
29386
29535
  }
29387
29536
  out.push("</details>", "");
29388
29537
  if (changes.images.length > 0) {
@@ -29620,6 +29769,11 @@ kbd {
29620
29769
  color: var(--mod);
29621
29770
  }
29622
29771
 
29772
+ .pill.renamed {
29773
+ background: var(--surface-2);
29774
+ color: var(--muted);
29775
+ }
29776
+
29623
29777
  .ratio {
29624
29778
  display: block;
29625
29779
  block-size: 6px;
@@ -30513,7 +30667,7 @@ input[type="range"]:focus-visible {
30513
30667
  `;
30514
30668
 
30515
30669
  // src/report-page.client.js
30516
- var report_page_client_default = '/* Browser script for the visual diff page (inlined by page.js). */\n(() => {\n const $ = (sel, root = document) => root.querySelector(sel);\n const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];\n const store = {\n get(key) {\n try {\n return localStorage.getItem(`file-diff:${key}`);\n } catch {\n return null;\n }\n },\n set(key, value) {\n try {\n localStorage.setItem(`file-diff:${key}`, value);\n } catch {\n // Storage blocked; the choice still applies to this view.\n }\n },\n };\n\n const code = $(".code-main");\n\n /** Index an arrow, Home or End key moves to in a horizontal list, or undefined for other keys. */\n function targetIndex(key, i, length, rtl) {\n const step = { ArrowRight: rtl ? -1 : 1, ArrowLeft: rtl ? 1 : -1 }[key];\n if (step) return (i + step + length) % length;\n if (key === "Home") return 0;\n if (key === "End") return length - 1;\n return undefined;\n }\n\n /* ---- Tabs: selection follows focus, roving tabindex ------------------ */\n const tablist = $(\'[role="tablist"]\');\n const tabs = $$(\'[role="tab"]\', tablist);\n const panelFor = (tab) => document.getElementById(tab.id.replace(/^tab-/, "panel-"));\n\n function selectTab(tab, { focus = false, push = true } = {}) {\n tabs.forEach((t) => {\n const on = t === tab;\n t.setAttribute("aria-selected", String(on));\n t.tabIndex = on ? 0 : -1;\n const panel = panelFor(t);\n if (on) panel.removeAttribute("hidden");\n else panel.setAttribute("hidden", "until-found");\n });\n if (focus) tab.focus();\n tab.scrollIntoView({ block: "nearest", inline: "nearest" });\n if (push) history.replaceState(null, "", `#${tab.id.slice(4)}`);\n }\n\n tablist.addEventListener("click", (e) => {\n const tab = e.target.closest(\'[role="tab"]\');\n if (tab) selectTab(tab);\n });\n tablist.addEventListener("keydown", (e) => {\n const i = tabs.indexOf(document.activeElement);\n const next = i < 0 ? undefined : targetIndex(e.key, i, tabs.length, getComputedStyle(tablist).direction === "rtl");\n if (next === undefined) return;\n e.preventDefault();\n selectTab(tabs[next], { focus: true });\n });\n // Find-in-page revealed a hidden panel: select its tab.\n $$(\'[role="tabpanel"]\').forEach((panel) =>\n panel.addEventListener("beforematch", () => {\n const tab = document.getElementById(panel.getAttribute("aria-labelledby"));\n if (tab) selectTab(tab, { push: false });\n }),\n );\n\n /** Shows the tab holding an element, then scrolls to it. */\n function reveal(el) {\n const panel = el.closest(\'[role="tabpanel"]\');\n const tab = panel && document.getElementById(panel.getAttribute("aria-labelledby"));\n if (tab && tab.getAttribute("aria-selected") !== "true") selectTab(tab, { push: false });\n const details = el.querySelector("details");\n if (details) {\n details.open = true;\n renderFile(el);\n }\n el.scrollIntoView({ block: "start" });\n }\n\n document.addEventListener("click", (e) => {\n const link = e.target.closest(\'a[href^="#f-"]\');\n if (!link) return;\n const target = document.getElementById(link.hash.slice(1));\n if (!target) return;\n e.preventDefault();\n reveal(target);\n history.replaceState(null, "", link.hash);\n });\n\n /* ---- Toolbars: one tab stop, arrow keys move (focusgroup fallback) --- */\n $$(\'[role="toolbar"]\').forEach((bar) => {\n if ("focusGroup" in HTMLElement.prototype) return bar.setAttribute("focusgroup", "toolbar wrap");\n const items = () => $$("button", bar);\n items().forEach((b, i) => (b.tabIndex = i ? -1 : 0));\n bar.addEventListener("focusin", ({ target }) => {\n if (items().includes(target)) items().forEach((b) => (b.tabIndex = b === target ? 0 : -1));\n });\n bar.addEventListener("keydown", (e) => {\n const list = items();\n const i = list.indexOf(document.activeElement);\n const next = i < 0 ? undefined : targetIndex(e.key, i, list.length, getComputedStyle(bar).direction === "rtl");\n if (next === undefined) return;\n e.preventDefault();\n list[next].focus();\n });\n });\n\n /** Presses one button in a segmented group. */\n function press(group, button) {\n $$("button", group).forEach((b) => b.setAttribute("aria-pressed", String(b === button)));\n }\n\n /* ---- Code: rows are built from JSON when a file opens ----------------- */\n const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", \'"\': "&quot;", "\'": "&#39;" };\n const esc = (text) => text.replace(/[&<>"\']/g, (c) => ESCAPES[c]);\n\n /** Escapes a line, wrapping the changed `[start, end, \u2026]` ranges in <mark>. */\n function markup(text, ranges) {\n if (!ranges) return esc(text);\n let out = "";\n let at = 0;\n for (let k = 0; k < ranges.length; k += 2) {\n out += `${esc(text.slice(at, ranges[k]))}<mark>${esc(text.slice(ranges[k], ranges[k + 1]))}</mark>`;\n at = ranges[k + 1];\n }\n return out + esc(text.slice(at));\n }\n\n /** Old and new line numbers for every line of a hunk (null where a side has none). */\n function numbers({ o, n, l }) {\n let oldNo = o;\n let newNo = n;\n return l.map((line) => (line[0] === "-" ? [oldNo++, null] : line[0] === "+" ? [null, newNo++] : line[0] === "\\\\" ? [null, null] : [oldNo++, newNo++]));\n }\n\n const metaRow = (line, cols) => `<tr class="meta"><td colspan="${cols}">${esc(line)}</td></tr>`;\n\n function unifiedRows(hunk) {\n const nos = numbers(hunk);\n const rows = [`<tr class="hunk"><td colspan="3">${esc(hunk.h)}</td></tr>`];\n hunk.l.forEach((line, i) => {\n const sign = line[0];\n if (sign === "\\\\") return rows.push(metaRow(line, 3));\n const kind = sign === "-" ? "del" : sign === "+" ? "add" : "ctx";\n rows.push(`<tr class="${kind}"><td class="ln">${nos[i][0] ?? ""}</td><td class="ln">${nos[i][1] ?? ""}</td><td class="code"><span class="sign">${sign}</span>${markup(line.slice(1), hunk.m[i])}</td></tr>`);\n });\n return rows;\n }\n\n const EMPTY_CELLS = \'<td class="ln empty"></td><td class="code empty"></td>\';\n\n /** Side-by-side rows. Edited line pairs share a row; other changes fill the gaps between them. */\n function splitRows(hunk) {\n const nos = numbers(hunk);\n const pairOf = new Map(hunk.p);\n const cells = (i, kind, no) => (i < 0 ? EMPTY_CELLS : `<td class="ln ${kind}">${no}</td><td class="code ${kind}">${markup(hunk.l[i].slice(1), hunk.m[i])}</td>`);\n const rows = [`<tr class="hunk"><td colspan="4">${esc(hunk.h)}</td></tr>`];\n\n for (let i = 0; i < hunk.l.length; ) {\n const sign = hunk.l[i][0];\n if (sign === "\\\\") {\n rows.push(metaRow(hunk.l[i++], 4));\n } else if (sign !== "-" && sign !== "+") {\n const text = markup(hunk.l[i].slice(1));\n rows.push(`<tr class="ctx"><td class="ln">${nos[i][0]}</td><td class="code">${text}</td><td class="ln">${nos[i][1]}</td><td class="code">${text}</td></tr>`);\n i++;\n } else {\n const dels = [];\n const adds = [];\n const notes = [];\n while (hunk.l[i]?.[0] === "-") dels.push(i++);\n while (hunk.l[i]?.[0] === "\\\\") notes.push(i++);\n while (hunk.l[i]?.[0] === "+") adds.push(i++);\n\n const pairs = [];\n let di = 0;\n let ai = 0;\n const fill = (dEnd, aEnd) => {\n for (let k = 0, n = Math.max(dEnd - di, aEnd - ai); k < n; k++) pairs.push([di + k < dEnd ? dels[di + k] : -1, ai + k < aEnd ? adds[ai + k] : -1]);\n di = dEnd;\n ai = aEnd;\n };\n dels.forEach((d, dPos) => {\n const aPos = adds.indexOf(pairOf.get(d));\n if (aPos < ai) return;\n fill(dPos, aPos);\n pairs.push([d, adds[aPos]]);\n di = dPos + 1;\n ai = aPos + 1;\n });\n fill(dels.length, adds.length);\n\n pairs.forEach(([d, a]) => rows.push(`<tr>${cells(d, "del", nos[d]?.[0])}${cells(a, "add", nos[a]?.[1])}</tr>`));\n notes.forEach((n) => rows.push(metaRow(hunk.l[n], 4)));\n }\n }\n return rows;\n }\n\n const parsed = new WeakMap();\n\n /** Builds a file\'s diff table for the current layout, once per layout. */\n function renderFile(section) {\n const scroll = section && $(".diff-scroll", section);\n if (!scroll || !code) return;\n const view = code.dataset.view;\n if (scroll.dataset.view === view) return;\n if (!parsed.has(scroll)) parsed.set(scroll, JSON.parse($(\'script[type="application/json"]\', scroll).textContent));\n const rows = parsed.get(scroll).flatMap((hunk) => (view === "split" ? splitRows(hunk) : unifiedRows(hunk)));\n const table = view === "split" ? `<table class="diff split"><colgroup><col class="ln-col"><col><col class="ln-col"><col></colgroup>${rows.join("")}</table>` : `<table class="diff unified">${rows.join("")}</table>`;\n $(".rendered", scroll)?.remove();\n scroll.insertAdjacentHTML("beforeend", `<div class="rendered">${table}</div>`);\n scroll.dataset.view = view;\n }\n\n if (code) {\n const sections = $$(".file", code);\n const renderOpen = () => sections.filter((section) => $("details", section).open).forEach(renderFile);\n const layout = $(\'[aria-label="Diff layout"]\', code);\n const collapse = $(\'[data-action="collapse"]\', code);\n const syncCollapse = () => (collapse.textContent = sections.every((section) => $("details", section).open) ? "Collapse all" : "Expand all");\n\n const setView = (view) => {\n code.dataset.view = view;\n press(layout, $(`button[data-view="${view}"]`, code));\n renderOpen();\n };\n\n layout.addEventListener("click", (e) => {\n const b = e.target.closest("button[data-view]");\n if (!b) return;\n setView(b.dataset.view);\n store.set("view", b.dataset.view);\n });\n collapse.addEventListener("click", () => {\n const open = collapse.textContent.startsWith("Expand");\n sections.forEach((section) => ($("details", section).open = open));\n syncCollapse();\n });\n // `toggle` doesn\'t bubble, so listen while it travels down.\n code.addEventListener(\n "toggle",\n (e) => {\n if (e.target.open) renderFile(e.target.closest(".file"));\n syncCollapse();\n },\n true,\n );\n\n setView(store.get("view") === "split" ? "split" : "unified");\n syncCollapse();\n }\n\n /* ---- Visual: modes, sliders, swipe drag, zoom, pager ----------------- */\n const viewer = $(".viewer");\n if (viewer) {\n const items = $$(".image-item", viewer);\n const listButtons = $$(".filelist button", viewer.parentElement);\n const modes = $(".modes", viewer);\n let index = 0;\n\n const current = () => items[index];\n\n const FIT_HEIGHT = 420;\n\n /** Sizes both versions by one scale so stacked modes stay aligned. Fit fills the stage. */\n function applyZoom() {\n const item = current();\n const imgs = $$("img", item);\n if (!imgs.every((img) => img.complete && img.naturalWidth)) {\n imgs.forEach((img) => img.addEventListener("load", applyZoom, { once: true }));\n return;\n }\n const zoom = viewer.dataset.zoom;\n let scale = Number(zoom);\n if (zoom === "fit") {\n const stage = $(".stage", item);\n const pad = parseFloat(getComputedStyle(stage).paddingLeft) * 2;\n const columns = viewer.dataset.mode === "side" && !item.hasAttribute("data-single") ? 2 : 1;\n const width = (stage.clientWidth - pad - (columns - 1) * 16) / columns;\n // The stage has no size while its tab is hidden; the ResizeObserver reruns this once it shows.\n if (width <= 0) return;\n const maxW = Math.max(...imgs.map((img) => img.naturalWidth));\n const maxH = Math.max(...imgs.map((img) => img.naturalHeight));\n scale = Math.min(width / maxW, FIT_HEIGHT / maxH);\n }\n imgs.forEach((img) => {\n img.style.inlineSize = `${Math.round(img.naturalWidth * scale)}px`;\n img.classList.toggle("upscaled", scale > 1);\n });\n }\n new ResizeObserver(() => viewer.dataset.zoom === "fit" && applyZoom()).observe(viewer);\n\n function syncModes() {\n const single = current().hasAttribute("data-single");\n $$("button", modes).forEach((b) => {\n if (b.dataset.mode === "side") return;\n if (single) b.setAttribute("aria-disabled", "true");\n else b.removeAttribute("aria-disabled");\n });\n }\n\n function show(i) {\n index = (i + items.length) % items.length;\n items.forEach((item, k) => (item.hidden = k !== index));\n listButtons.forEach((b, k) => (k === index ? b.setAttribute("aria-current", "true") : b.removeAttribute("aria-current")));\n $(".pager-count", viewer).textContent = `${index + 1} of ${items.length}`;\n syncModes();\n applyZoom();\n }\n\n // Natural dimensions under each image header.\n items.forEach((item) =>\n $$("img", item).forEach((img) => {\n const write = () => {\n const out = $(`[data-dims="${img.dataset.side}"]`, item);\n if (out) out.textContent = `${img.dataset.side} ${img.naturalWidth}\xD7${img.naturalHeight}`;\n };\n if (img.complete && img.naturalWidth) write();\n else img.addEventListener("load", write, { once: true });\n }),\n );\n\n $(".toolbar", viewer).addEventListener("click", (e) => {\n const b = e.target.closest("button");\n if (!b || b.getAttribute("aria-disabled") === "true") return;\n for (const key of ["mode", "bg", "zoom"]) {\n if (b.dataset[key] === undefined) continue;\n viewer.dataset[key] = b.dataset[key];\n press(b.parentElement, b);\n if (key !== "bg") applyZoom();\n if (key !== "zoom") store.set(key, b.dataset[key]);\n }\n });\n for (const key of ["mode", "bg"]) {\n const saved = store.get(key);\n const b = saved && $(`button[data-${key}="${saved}"]`, viewer);\n if (b) {\n viewer.dataset[key] = saved;\n press(b.parentElement, b);\n }\n }\n\n // Range inputs drive --opacity / --pos; keep the filled track in sync.\n $$(\'input[type="range"]\', viewer).forEach((input) => {\n const output = input.nextElementSibling;\n const sync = () => {\n const v = Number(input.value);\n input.style.setProperty("--control-value", v);\n input.style.setProperty("--attr-min", input.min || 0);\n input.style.setProperty("--attr-max", input.max || 100);\n viewer.style.setProperty(input.dataset.control === "opacity" ? "--opacity" : "--pos", input.dataset.control === "opacity" ? v / 100 : `${v}%`);\n output.textContent = `${v}%`;\n };\n input.addEventListener("input", sync);\n sync();\n });\n\n // Drag directly on the image in swipe mode.\n const swipeInput = $(\'input[data-control="pos"]\', viewer);\n items.forEach((item) => {\n const layers = $(".layers", item);\n const move = (e) => {\n const box = layers.getBoundingClientRect();\n swipeInput.value = String(Math.round(Math.min(100, Math.max(0, ((e.clientX - box.left) / box.width) * 100))));\n swipeInput.dispatchEvent(new Event("input"));\n };\n layers.addEventListener("pointerdown", (e) => {\n if (viewer.dataset.mode !== "swipe" || item.hasAttribute("data-single")) return;\n layers.setPointerCapture(e.pointerId);\n move(e);\n layers.addEventListener("pointermove", move);\n // Fires after pointerup and pointercancel alike, so the listener never outlives the drag.\n layers.addEventListener("lostpointercapture", () => layers.removeEventListener("pointermove", move), { once: true });\n });\n });\n\n listButtons.forEach((b, k) => b.addEventListener("click", () => show(k)));\n $$("[data-step]", viewer).forEach((b) => b.addEventListener("click", () => show(index + Number(b.dataset.step))));\n document.addEventListener("keydown", (e) => {\n if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;\n if ($("#panel-visual")?.hidden || e.target.closest("input, textarea, select, [contenteditable]")) return;\n if (e.key === "j" || e.key === "k") show(index + (e.key === "j" ? 1 : -1));\n });\n\n show(0);\n }\n\n /* ---- Open the tab or file named in the URL ---------------------------- */\n const initial = location.hash.slice(1);\n const initialTab = document.getElementById(`tab-${initial}`);\n if (initialTab) selectTab(initialTab, { push: false });\n else if (initial && document.getElementById(initial)) reveal(document.getElementById(initial));\n})();\n';
30670
+ var report_page_client_default = '/**\n * SPDX-License-Identifier: MPL-2.0\n * Copyright 2025 Allons-y Studio\n */\n\n/* Browser script for the visual diff page (inlined by page.js). */\n(() => {\n const $ = (sel, root = document) => root.querySelector(sel);\n const $$ = (sel, root = document) => [...root.querySelectorAll(sel)];\n const store = {\n get(key) {\n try {\n return localStorage.getItem(`file-diff:${key}`);\n } catch {\n return null;\n }\n },\n set(key, value) {\n try {\n localStorage.setItem(`file-diff:${key}`, value);\n } catch {\n // Storage blocked; the choice still applies to this view.\n }\n },\n };\n\n const code = $(".code-main");\n\n /** Index an arrow, Home or End key moves to in a horizontal list, or undefined for other keys. */\n function targetIndex(key, i, length, rtl) {\n const step = { ArrowRight: rtl ? -1 : 1, ArrowLeft: rtl ? 1 : -1 }[key];\n if (step) return (i + step + length) % length;\n if (key === "Home") return 0;\n if (key === "End") return length - 1;\n return undefined;\n }\n\n /* ---- Tabs: selection follows focus, roving tabindex ------------------ */\n const tablist = $(\'[role="tablist"]\');\n const tabs = $$(\'[role="tab"]\', tablist);\n const panelFor = (tab) => document.getElementById(tab.id.replace(/^tab-/, "panel-"));\n\n function selectTab(tab, { focus = false, push = true } = {}) {\n tabs.forEach((t) => {\n const on = t === tab;\n t.setAttribute("aria-selected", String(on));\n t.tabIndex = on ? 0 : -1;\n const panel = panelFor(t);\n if (on) panel.removeAttribute("hidden");\n else panel.setAttribute("hidden", "until-found");\n });\n if (focus) tab.focus();\n tab.scrollIntoView({ block: "nearest", inline: "nearest" });\n if (push) history.replaceState(null, "", `#${tab.id.slice(4)}`);\n }\n\n tablist.addEventListener("click", (e) => {\n const tab = e.target.closest(\'[role="tab"]\');\n if (tab) selectTab(tab);\n });\n tablist.addEventListener("keydown", (e) => {\n const i = tabs.indexOf(document.activeElement);\n const next = i < 0 ? undefined : targetIndex(e.key, i, tabs.length, getComputedStyle(tablist).direction === "rtl");\n if (next === undefined) return;\n e.preventDefault();\n selectTab(tabs[next], { focus: true });\n });\n // Find-in-page revealed a hidden panel: select its tab.\n $$(\'[role="tabpanel"]\').forEach((panel) =>\n panel.addEventListener("beforematch", () => {\n const tab = document.getElementById(panel.getAttribute("aria-labelledby"));\n if (tab) selectTab(tab, { push: false });\n }),\n );\n\n /** Shows the tab holding an element, then scrolls to it. */\n function reveal(el) {\n const panel = el.closest(\'[role="tabpanel"]\');\n const tab = panel && document.getElementById(panel.getAttribute("aria-labelledby"));\n if (tab && tab.getAttribute("aria-selected") !== "true") selectTab(tab, { push: false });\n const details = el.querySelector("details");\n if (details) {\n details.open = true;\n renderFile(el);\n }\n el.scrollIntoView({ block: "start" });\n }\n\n document.addEventListener("click", (e) => {\n const link = e.target.closest(\'a[href^="#f-"]\');\n if (!link) return;\n const target = document.getElementById(link.hash.slice(1));\n if (!target) return;\n e.preventDefault();\n reveal(target);\n history.replaceState(null, "", link.hash);\n });\n\n /* ---- Toolbars: one tab stop, arrow keys move (focusgroup fallback) --- */\n $$(\'[role="toolbar"]\').forEach((bar) => {\n if ("focusGroup" in HTMLElement.prototype) return bar.setAttribute("focusgroup", "toolbar wrap");\n const items = () => $$("button", bar);\n items().forEach((b, i) => (b.tabIndex = i ? -1 : 0));\n bar.addEventListener("focusin", ({ target }) => {\n if (items().includes(target)) items().forEach((b) => (b.tabIndex = b === target ? 0 : -1));\n });\n bar.addEventListener("keydown", (e) => {\n const list = items();\n const i = list.indexOf(document.activeElement);\n const next = i < 0 ? undefined : targetIndex(e.key, i, list.length, getComputedStyle(bar).direction === "rtl");\n if (next === undefined) return;\n e.preventDefault();\n list[next].focus();\n });\n });\n\n /** Presses one button in a segmented group. */\n function press(group, button) {\n $$("button", group).forEach((b) => b.setAttribute("aria-pressed", String(b === button)));\n }\n\n /* ---- Code: rows are built from JSON when a file opens ----------------- */\n const ESCAPES = { "&": "&amp;", "<": "&lt;", ">": "&gt;", \'"\': "&quot;", "\'": "&#39;" };\n const esc = (text) => text.replace(/[&<>"\']/g, (c) => ESCAPES[c]);\n\n /** Escapes a line, wrapping the changed `[start, end, \u2026]` ranges in <mark>. */\n function markup(text, ranges) {\n if (!ranges) return esc(text);\n let out = "";\n let at = 0;\n for (let k = 0; k < ranges.length; k += 2) {\n out += `${esc(text.slice(at, ranges[k]))}<mark>${esc(text.slice(ranges[k], ranges[k + 1]))}</mark>`;\n at = ranges[k + 1];\n }\n return out + esc(text.slice(at));\n }\n\n /** Old and new line numbers for every line of a hunk (null where a side has none). */\n function numbers({ o, n, l }) {\n let oldNo = o;\n let newNo = n;\n return l.map((line) => (line[0] === "-" ? [oldNo++, null] : line[0] === "+" ? [null, newNo++] : line[0] === "\\\\" ? [null, null] : [oldNo++, newNo++]));\n }\n\n const metaRow = (line, cols) => `<tr class="meta"><td colspan="${cols}">${esc(line)}</td></tr>`;\n\n function unifiedRows(hunk) {\n const nos = numbers(hunk);\n const rows = [`<tr class="hunk"><td colspan="3">${esc(hunk.h)}</td></tr>`];\n hunk.l.forEach((line, i) => {\n const sign = line[0];\n if (sign === "\\\\") return rows.push(metaRow(line, 3));\n const kind = sign === "-" ? "del" : sign === "+" ? "add" : "ctx";\n rows.push(`<tr class="${kind}"><td class="ln">${nos[i][0] ?? ""}</td><td class="ln">${nos[i][1] ?? ""}</td><td class="code"><span class="sign">${sign}</span>${markup(line.slice(1), hunk.m[i])}</td></tr>`);\n });\n return rows;\n }\n\n const EMPTY_CELLS = \'<td class="ln empty"></td><td class="code empty"></td>\';\n\n /** Side-by-side rows. Edited line pairs share a row; other changes fill the gaps between them. */\n function splitRows(hunk) {\n const nos = numbers(hunk);\n const pairOf = new Map(hunk.p);\n const cells = (i, kind, no) => (i < 0 ? EMPTY_CELLS : `<td class="ln ${kind}">${no}</td><td class="code ${kind}">${markup(hunk.l[i].slice(1), hunk.m[i])}</td>`);\n const rows = [`<tr class="hunk"><td colspan="4">${esc(hunk.h)}</td></tr>`];\n\n for (let i = 0; i < hunk.l.length; ) {\n const sign = hunk.l[i][0];\n if (sign === "\\\\") {\n rows.push(metaRow(hunk.l[i++], 4));\n } else if (sign !== "-" && sign !== "+") {\n const text = markup(hunk.l[i].slice(1));\n rows.push(`<tr class="ctx"><td class="ln">${nos[i][0]}</td><td class="code">${text}</td><td class="ln">${nos[i][1]}</td><td class="code">${text}</td></tr>`);\n i++;\n } else {\n const dels = [];\n const adds = [];\n const notes = [];\n while (hunk.l[i]?.[0] === "-") dels.push(i++);\n while (hunk.l[i]?.[0] === "\\\\") notes.push(i++);\n while (hunk.l[i]?.[0] === "+") adds.push(i++);\n\n const pairs = [];\n let di = 0;\n let ai = 0;\n const fill = (dEnd, aEnd) => {\n for (let k = 0, n = Math.max(dEnd - di, aEnd - ai); k < n; k++) pairs.push([di + k < dEnd ? dels[di + k] : -1, ai + k < aEnd ? adds[ai + k] : -1]);\n di = dEnd;\n ai = aEnd;\n };\n dels.forEach((d, dPos) => {\n const aPos = adds.indexOf(pairOf.get(d));\n if (aPos < ai) return;\n fill(dPos, aPos);\n pairs.push([d, adds[aPos]]);\n di = dPos + 1;\n ai = aPos + 1;\n });\n fill(dels.length, adds.length);\n\n pairs.forEach(([d, a]) => rows.push(`<tr>${cells(d, "del", nos[d]?.[0])}${cells(a, "add", nos[a]?.[1])}</tr>`));\n notes.forEach((n) => rows.push(metaRow(hunk.l[n], 4)));\n }\n }\n return rows;\n }\n\n const parsed = new WeakMap();\n\n /** Builds a file\'s diff table for the current layout, once per layout. */\n function renderFile(section) {\n const scroll = section && $(".diff-scroll", section);\n if (!scroll || !code) return;\n const view = code.dataset.view;\n if (scroll.dataset.view === view) return;\n if (!parsed.has(scroll)) parsed.set(scroll, JSON.parse($(\'script[type="application/json"]\', scroll).textContent));\n const rows = parsed.get(scroll).flatMap((hunk) => (view === "split" ? splitRows(hunk) : unifiedRows(hunk)));\n const table = view === "split" ? `<table class="diff split"><colgroup><col class="ln-col"><col><col class="ln-col"><col></colgroup>${rows.join("")}</table>` : `<table class="diff unified">${rows.join("")}</table>`;\n $(".rendered", scroll)?.remove();\n scroll.insertAdjacentHTML("beforeend", `<div class="rendered">${table}</div>`);\n scroll.dataset.view = view;\n }\n\n if (code) {\n const sections = $$(".file", code);\n const renderOpen = () => sections.filter((section) => $("details", section).open).forEach(renderFile);\n const layout = $(\'[aria-label="Diff layout"]\', code);\n const collapse = $(\'[data-action="collapse"]\', code);\n const syncCollapse = () => (collapse.textContent = sections.every((section) => $("details", section).open) ? "Collapse all" : "Expand all");\n\n const setView = (view) => {\n code.dataset.view = view;\n press(layout, $(`button[data-view="${view}"]`, code));\n renderOpen();\n };\n\n layout.addEventListener("click", (e) => {\n const b = e.target.closest("button[data-view]");\n if (!b) return;\n setView(b.dataset.view);\n store.set("view", b.dataset.view);\n });\n collapse.addEventListener("click", () => {\n const open = collapse.textContent.startsWith("Expand");\n sections.forEach((section) => ($("details", section).open = open));\n syncCollapse();\n });\n // `toggle` doesn\'t bubble, so listen while it travels down.\n code.addEventListener(\n "toggle",\n (e) => {\n if (e.target.open) renderFile(e.target.closest(".file"));\n syncCollapse();\n },\n true,\n );\n\n setView(store.get("view") === "split" ? "split" : "unified");\n syncCollapse();\n }\n\n /* ---- Visual: modes, sliders, swipe drag, zoom, pager ----------------- */\n const viewer = $(".viewer");\n if (viewer) {\n const items = $$(".image-item", viewer);\n const listButtons = $$(".filelist button", viewer.parentElement);\n const modes = $(".modes", viewer);\n let index = 0;\n\n const current = () => items[index];\n\n const FIT_HEIGHT = 420;\n\n /** Sizes both versions by one scale so stacked modes stay aligned. Fit fills the stage. */\n function applyZoom() {\n const item = current();\n const imgs = $$("img", item);\n if (!imgs.every((img) => img.complete && img.naturalWidth)) {\n imgs.forEach((img) => img.addEventListener("load", applyZoom, { once: true }));\n return;\n }\n const zoom = viewer.dataset.zoom;\n let scale = Number(zoom);\n if (zoom === "fit") {\n const stage = $(".stage", item);\n const pad = parseFloat(getComputedStyle(stage).paddingLeft) * 2;\n const columns = viewer.dataset.mode === "side" && !item.hasAttribute("data-single") ? 2 : 1;\n const width = (stage.clientWidth - pad - (columns - 1) * 16) / columns;\n // The stage has no size while its tab is hidden; the ResizeObserver reruns this once it shows.\n if (width <= 0) return;\n const maxW = Math.max(...imgs.map((img) => img.naturalWidth));\n const maxH = Math.max(...imgs.map((img) => img.naturalHeight));\n scale = Math.min(width / maxW, FIT_HEIGHT / maxH);\n }\n imgs.forEach((img) => {\n img.style.inlineSize = `${Math.round(img.naturalWidth * scale)}px`;\n img.classList.toggle("upscaled", scale > 1);\n });\n }\n new ResizeObserver(() => viewer.dataset.zoom === "fit" && applyZoom()).observe(viewer);\n\n function syncModes() {\n const single = current().hasAttribute("data-single");\n $$("button", modes).forEach((b) => {\n if (b.dataset.mode === "side") return;\n if (single) b.setAttribute("aria-disabled", "true");\n else b.removeAttribute("aria-disabled");\n });\n }\n\n function show(i) {\n index = (i + items.length) % items.length;\n items.forEach((item, k) => (item.hidden = k !== index));\n listButtons.forEach((b, k) => (k === index ? b.setAttribute("aria-current", "true") : b.removeAttribute("aria-current")));\n $(".pager-count", viewer).textContent = `${index + 1} of ${items.length}`;\n syncModes();\n applyZoom();\n }\n\n // Natural dimensions under each image header.\n items.forEach((item) =>\n $$("img", item).forEach((img) => {\n const write = () => {\n const out = $(`[data-dims="${img.dataset.side}"]`, item);\n if (out) out.textContent = `${img.dataset.side} ${img.naturalWidth}\xD7${img.naturalHeight}`;\n };\n if (img.complete && img.naturalWidth) write();\n else img.addEventListener("load", write, { once: true });\n }),\n );\n\n $(".toolbar", viewer).addEventListener("click", (e) => {\n const b = e.target.closest("button");\n if (!b || b.getAttribute("aria-disabled") === "true") return;\n for (const key of ["mode", "bg", "zoom"]) {\n if (b.dataset[key] === undefined) continue;\n viewer.dataset[key] = b.dataset[key];\n press(b.parentElement, b);\n if (key !== "bg") applyZoom();\n if (key !== "zoom") store.set(key, b.dataset[key]);\n }\n });\n for (const key of ["mode", "bg"]) {\n const saved = store.get(key);\n const b = saved && $(`button[data-${key}="${saved}"]`, viewer);\n if (b) {\n viewer.dataset[key] = saved;\n press(b.parentElement, b);\n }\n }\n\n // Range inputs drive --opacity / --pos; keep the filled track in sync.\n $$(\'input[type="range"]\', viewer).forEach((input) => {\n const output = input.nextElementSibling;\n const sync = () => {\n const v = Number(input.value);\n input.style.setProperty("--control-value", v);\n input.style.setProperty("--attr-min", input.min || 0);\n input.style.setProperty("--attr-max", input.max || 100);\n viewer.style.setProperty(input.dataset.control === "opacity" ? "--opacity" : "--pos", input.dataset.control === "opacity" ? v / 100 : `${v}%`);\n output.textContent = `${v}%`;\n };\n input.addEventListener("input", sync);\n sync();\n });\n\n // Drag directly on the image in swipe mode.\n const swipeInput = $(\'input[data-control="pos"]\', viewer);\n items.forEach((item) => {\n const layers = $(".layers", item);\n const move = (e) => {\n const box = layers.getBoundingClientRect();\n swipeInput.value = String(Math.round(Math.min(100, Math.max(0, ((e.clientX - box.left) / box.width) * 100))));\n swipeInput.dispatchEvent(new Event("input"));\n };\n layers.addEventListener("pointerdown", (e) => {\n if (viewer.dataset.mode !== "swipe" || item.hasAttribute("data-single")) return;\n layers.setPointerCapture(e.pointerId);\n move(e);\n layers.addEventListener("pointermove", move);\n // Fires after pointerup and pointercancel alike, so the listener never outlives the drag.\n layers.addEventListener("lostpointercapture", () => layers.removeEventListener("pointermove", move), { once: true });\n });\n });\n\n listButtons.forEach((b, k) => b.addEventListener("click", () => show(k)));\n $$("[data-step]", viewer).forEach((b) => b.addEventListener("click", () => show(index + Number(b.dataset.step))));\n document.addEventListener("keydown", (e) => {\n if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey) return;\n if ($("#panel-visual")?.hidden || e.target.closest("input, textarea, select, [contenteditable]")) return;\n if (e.key === "j" || e.key === "k") show(index + (e.key === "j" ? 1 : -1));\n });\n\n show(0);\n }\n\n /* ---- Open the tab or file named in the URL ---------------------------- */\n const initial = location.hash.slice(1);\n const initialTab = document.getElementById(`tab-${initial}`);\n if (initialTab) selectTab(initialTab, { push: false });\n else if (initial && document.getElementById(initial)) reveal(document.getElementById(initial));\n})();\n';
30517
30671
 
30518
30672
  // src/page.js
30519
30673
  var INTRALINE_LIMIT = 1e3;
@@ -30686,6 +30840,7 @@ function renderFileList(items, label, buttons = false) {
30686
30840
  });
30687
30841
  return `<nav class="filelist" aria-label="${escapeHtml(label)}"><ul>${entries.join("")}</ul></nav>`;
30688
30842
  }
30843
+ var renamedPill = (from) => from ? `<span class="pill renamed" title="Renamed from ${escapeHtml(from)}">renamed</span>` : "";
30689
30844
  var OPEN_LINES = 800;
30690
30845
  function renderCode({ changes }, anchors) {
30691
30846
  if (changes.text.length === 0) return '<p class="empty-state">No text changes.</p>';
@@ -30704,7 +30859,8 @@ function renderCode({ changes }, anchors) {
30704
30859
  else if (c.omitted) body = `<p class="note">Diff left out because ${escapeHtml(c.omitted)}. Raise <code>max-diff-lines</code> to include it.</p>`;
30705
30860
  else if (c.hunks.length === 0) body = '<p class="note">No line changes.</p>';
30706
30861
  else body = `<div class="diff-scroll"><script type="application/json">${scriptJson(c.hunks.map(hunkData))}</script></div>`;
30707
- return `<section class="file" id="${anchors.get(c.file)}"><details${open2 ? " open" : ""}><summary><span class="chev">${ICON.chevron}</span><span class="pill ${c.status}">${c.status}</span><span class="path">${pathHtml(c.file)}</span><span class="meta">${counts(c)}</span></summary>${body}</details></section>`;
30862
+ if (c.from) body = `<p class="note">Renamed from <code>${escapeHtml(c.from)}</code>.</p>${body}`;
30863
+ return `<section class="file" id="${anchors.get(c.file)}"><details${open2 ? " open" : ""}><summary><span class="chev">${ICON.chevron}</span><span class="pill ${c.status}">${c.status}</span>${renamedPill(c.from)}<span class="path">${pathHtml(c.file)}</span><span class="meta">${counts(c)}</span></summary>${body}</details></section>`;
30708
30864
  }).join("");
30709
30865
  return `<div class="layout">${list}<div class="main code-main" data-view="unified">
30710
30866
  <div class="toolbar" role="toolbar" aria-label="Diff options">
@@ -30724,10 +30880,10 @@ function renderVisual({ changes, imageUrls = /* @__PURE__ */ new Map() }) {
30724
30880
  true
30725
30881
  );
30726
30882
  const figure = (side, url) => url ? `<figure class="layer ${side}"><img src="${escapeHtml(url)}" alt="${side === "base" ? "Base" : "Head"} version" decoding="async" data-side="${side}"><figcaption>${side === "base" ? "Base" : "Head"}</figcaption></figure>` : `<figure class="layer ${side} missing"><figcaption>${side === "base" ? "Base" : "Head"}: not available</figcaption></figure>`;
30727
- const viewers = items.map(({ id, file, status, urls, baseByteSize, headByteSize }, i) => {
30883
+ const viewers = items.map(({ id, file, status, from, urls, baseByteSize, headByteSize }, i) => {
30728
30884
  const single = !(urls.base && urls.head);
30729
30885
  return `<section class="image-item" id="${id}"${i ? " hidden" : ""}${single ? " data-single" : ""} aria-label="${escapeHtml(file)}">
30730
- <header class="image-head"><span class="pill ${status}">${status}</span><span class="path">${pathHtml(file)}</span><span class="meta">${escapeHtml(bytesToSize(baseByteSize))} \u2192 ${escapeHtml(bytesToSize(headByteSize))} ${deltaHtml(headByteSize, baseByteSize)}</span><span class="meta dims"><span data-dims="base"></span><span data-dims="head"></span></span></header>
30886
+ <header class="image-head"><span class="pill ${status}">${status}</span>${renamedPill(from)}<span class="path">${pathHtml(file)}</span><span class="meta">${escapeHtml(bytesToSize(baseByteSize))} \u2192 ${escapeHtml(bytesToSize(headByteSize))} ${deltaHtml(headByteSize, baseByteSize)}</span><span class="meta dims"><span data-dims="base"></span><span data-dims="head"></span></span></header>
30731
30887
  <div class="stage"><div class="layers">${figure("base", urls.base)}${figure("head", urls.head)}<span class="divider" aria-hidden="true"></span><span class="tag tag-base" aria-hidden="true">Base</span><span class="tag tag-head" aria-hidden="true">Head</span></div></div>
30732
30888
  ${single ? `<p class="note">${status === "added" ? "New image: there's no base version to compare." : status === "removed" ? "Removed image: there's no head version to compare." : "Only one version could be included."}</p>` : ""}
30733
30889
  </section>`;
@@ -30794,7 +30950,7 @@ function reportFiles(options) {
30794
30950
  ["base", image.basePath, image.baseByteSize]
30795
30951
  ].forEach(([side, path11, size]) => {
30796
30952
  if (!path11 || size > MAX_IMAGE_SIZE) return;
30797
- files.push({ path: `images/${side}/${image.file}`, content: readFileSync3(path11) });
30953
+ files.push({ path: `images/${side}/${image.file}`, content: readFileSync5(path11) });
30798
30954
  urls[side] = `images/${side}/${encodePath(image.file)}`;
30799
30955
  });
30800
30956
  imageUrls.set(image.file, urls);
@@ -30823,8 +30979,11 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
30823
30979
  core.info(sha ? `Removed ${dir}/ from ${inputs.reportBranch}.` : `Nothing to remove for ${dir}/ on ${inputs.reportBranch}.`);
30824
30980
  return;
30825
30981
  }
30826
- const [headMap, baseMap] = await Promise.all([fetchFilesAndSizes(inputs.headPath, inputs.fileGlobPattern, { core, required: true }), fetchFilesAndSizes(inputs.basePath, inputs.fileGlobPattern, { core, required: false })]);
30827
- const hasBase = baseMap.size > 0;
30982
+ const [headMap, measuredBase] = await Promise.all([fetchFilesAndSizes(inputs.headPath, inputs.fileGlobPattern, { core, required: true }), fetchFilesAndSizes(inputs.basePath, inputs.fileGlobPattern, { core, required: false })]);
30983
+ const hasBase = measuredBase.size > 0;
30984
+ const { baseMap, renames, timedOut } = hasBase ? matchRenames({ headMap, baseMap: measuredBase, headRoot: inputs.headPath, baseRoot: inputs.basePath, normalizeNames: inputs.normalizeNames, threshold: inputs.renameThreshold }) : { baseMap: measuredBase, renames: /* @__PURE__ */ new Map(), timedOut: false };
30985
+ if (timedOut) core.warning("Stopped matching renamed files after 30 seconds; some may show as added and removed. Add normalize-names patterns or narrow file-glob-pattern.");
30986
+ if (renames.size > 0) core.info(`Matched ${renames.size} renamed file${renames.size === 1 ? "" : "s"} between base and head.`);
30828
30987
  const reportOptions = { headMap, baseMap, hasBase, rootPath: inputs.headPath, buildDir: inputs.buildDir, mainFile: inputs.mainFile, readPackageJson: inputs.readPackageJson, extensions: inputs.extensions, core };
30829
30988
  const report = buildReport(reportOptions);
30830
30989
  const reportWithin = (limit) => report.text.length <= limit ? report : buildReport({ ...reportOptions, maxLength: limit });
@@ -30832,7 +30991,7 @@ async function run({ core, context: context3, getOctokit: getOctokit2, env = pro
30832
30991
  let link;
30833
30992
  let summaryMarkdown = "";
30834
30993
  if (inputs.visualDiff !== "none") {
30835
- changes = await collectChanges({ headMap, baseMap, headRoot: inputs.headPath, baseRoot: inputs.basePath, extensions: inputs.extensions, maxDiffSize: inputs.maxDiffSize, maxDiffLines: inputs.maxDiffLines, core });
30994
+ changes = await collectChanges({ headMap, baseMap, headRoot: inputs.headPath, baseRoot: inputs.basePath, renames, ignorePatterns: inputs.ignorePatterns, extensions: inputs.extensions, maxDiffSize: inputs.maxDiffSize, maxDiffLines: inputs.maxDiffLines, core });
30836
30995
  const rows = sizeRows(report.sections);
30837
30996
  const totals = { headTotal: report.headTotal, baseTotal: report.baseTotal };
30838
30997
  if (inputs.visualDiff === "branch") {
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "registry": "https://registry.npmjs.org/"
6
6
  },
7
7
  "name": "@allons-y/actions-file-diff",
8
- "version": "0.2.0",
8
+ "version": "0.3.0",
9
9
  "description": "Compare compiled assets between branches and report the diff back on the pull request.",
10
10
  "license": "MPL-2.0",
11
11
  "author": "Cassondra Roberts <castastrophe@users.noreply.github.com> (https://allons-y.studio)",
@@ -20,30 +20,19 @@
20
20
  "type": "module",
21
21
  "main": "dist/index.js",
22
22
  "files": [
23
- "dist/index.js",
24
- "src/changes.js",
25
- "src/index.js",
26
- "src/page.js",
27
- "src/publish.js",
28
- "src/render.js",
29
- "src/report-page.client.js",
30
- "src/report-page.css",
31
- "src/report.js",
32
- "src/utilities.js",
33
- "action.yml"
23
+ "dist"
34
24
  ],
35
25
  "scripts": {
36
26
  "build": "node scripts/build.js",
37
27
  "changeset": "opx release add",
38
28
  "ci": "yarn lint && yarn build && yarn test",
39
- "coverage": "NODE_OPTIONS=--experimental-vm-modules jest --coverage",
40
- "format": "prettier --write . && yarn lint --fix",
41
- "lint": "eslint --no-error-on-unmatched-pattern --no-warn-ignored --cache '**/*'",
42
- "precommit": "lint-staged",
29
+ "coverage": "vitest run --coverage",
30
+ "format": "opx lint --fix",
31
+ "lint": "opx lint",
43
32
  "prepare": "husky && envoy || true",
44
33
  "preview": "node scripts/preview.js",
45
34
  "release": "yarn build && opx release publish",
46
- "test": "NODE_OPTIONS=--experimental-vm-modules jest",
35
+ "test": "vitest run",
47
36
  "test:browser": "node --test test/browser.test.js",
48
37
  "version": "opx release version && yarn install --mode update-lockfile"
49
38
  },
@@ -56,26 +45,23 @@
56
45
  "devDependencies": {
57
46
  "@allons-y/envoy": "^1.1.0",
58
47
  "@allons-y/opx-cli": "^0.2.0",
48
+ "@allons-y/opx-lint-js": "^1.0.1",
49
+ "@allons-y/opx-lint-json": "^0.1.1",
50
+ "@allons-y/opx-lint-md": "^0.1.1",
59
51
  "@allons-y/opx-release": "^0.1.1",
60
52
  "@commitlint/cli": "^21.1.0",
61
53
  "@commitlint/config-conventional": "^21.1.0",
62
- "@eslint/compat": "^2.1.0",
63
- "@eslint/js": "^10.0.1",
64
- "@eslint/json": "^2.0.0",
65
- "@eslint/markdown": "^8.0.2",
66
- "@stylistic/eslint-plugin": "^5.10.0",
54
+ "@vitest/coverage-v8": "^5.0.5",
67
55
  "esbuild": "^0.28.2",
68
56
  "eslint": "^10.6.0",
69
- "eslint-config-prettier": "^10.1.8",
70
- "eslint-plugin-jest": "^29.15.3",
71
- "eslint-plugin-jsonc": "^3.2.0",
72
- "eslint-plugin-node": "^11.1.0",
57
+ "eslint-plugin-license-header": "^0.9.0",
73
58
  "globals": "^17.7.0",
74
59
  "husky": "^9.1.7",
75
- "jest": "^30.4.2",
76
- "lint-staged": "^17.0.8",
77
60
  "playwright-core": "^1.65.1",
78
- "prettier": "^3.8.5"
61
+ "prettier": "^3.8.5",
62
+ "typescript": "^5.9.0",
63
+ "vite": "^8.3.5",
64
+ "vitest": "^5.0.5"
79
65
  },
80
66
  "keywords": [
81
67
  "actions",
@@ -87,12 +73,5 @@
87
73
  "engines": {
88
74
  "node": ">=24"
89
75
  },
90
- "lint-staged": {
91
- "*": [
92
- "prettier --write --ignore-unknown",
93
- "eslint --fix --format stylish"
94
- ],
95
- ".github/renovate.json": "npx --yes --package renovate -- renovate-config-validator --strict"
96
- },
97
- "packageManager": "yarn@4.17.0"
76
+ "packageManager": "yarn@4.18.1"
98
77
  }