@davmash/bygone 0.8.7 → 0.8.9

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.
@@ -9210,7 +9210,7 @@ var require_package = __commonJS({
9210
9210
  displayName: "Bygone",
9211
9211
  desktopName: "com.davidmashburn.bygone.desktop",
9212
9212
  description: "See how change happened. Visual diff and file history for VS Code.",
9213
- version: "0.8.7",
9213
+ version: "0.8.9",
9214
9214
  author: "David Mashburn",
9215
9215
  license: "MIT",
9216
9216
  private: false,
@@ -9398,7 +9398,7 @@ var require_package = __commonJS({
9398
9398
  "icons:generate": "node ./scripts/generate-icons.mjs",
9399
9399
  "package:vsix": "node ./scripts/check-vsix-contents.mjs && vsce package",
9400
9400
  "standalone:start": "npm run compile && node ./scripts/run-electron.mjs ./out/standalone-main.js",
9401
- "standalone:smoke": "npm run compile && node ./scripts/run-electron.mjs ./out/standalone-main.js --smoke-test && node ./scripts/run-electron.mjs ./out/standalone-main.js --smoke-test-multi && node ./scripts/run-electron.mjs ./out/standalone-main.js --smoke-test-directory",
9401
+ "standalone:smoke": "npm run compile && node ./scripts/run-electron.mjs ./out/standalone-main.js --smoke-test && node ./scripts/run-electron.mjs ./out/standalone-main.js --smoke-test-multi && node ./scripts/run-electron.mjs ./out/standalone-main.js --smoke-test-directory && node ./scripts/run-electron.mjs ./out/standalone-main.js --smoke-test-directory-history",
9402
9402
  "walkthrough:refresh": "node ./scripts/refresh-walkthrough-screenshots.mjs",
9403
9403
  "web:start": "npm run compile && node ./scripts/web-server.mjs",
9404
9404
  "package:desktop": "npm run package:desktop:mac",
@@ -9418,6 +9418,7 @@ var require_package = __commonJS({
9418
9418
  "bundle:check": "node ./scripts/check-bundle-size.mjs",
9419
9419
  "security:audit": "npm audit --audit-level=high",
9420
9420
  "dev:sync": "node ./scripts/dev-sync.mjs",
9421
+ reinstall: "node ./scripts/dev-sync.mjs --install-only",
9421
9422
  "release:check": "npm run security:audit && npm test && npm run bundle:check && npm run lint && npm run package:vsix && npm run package:npm && npm run package:npm:dry-run",
9422
9423
  "release:build": "node ./scripts/release.mjs",
9423
9424
  "release:publish": "node ./scripts/release.mjs --publish",
@@ -22481,7 +22482,7 @@ var commandLineToolPath = process.platform === "win32" ? path8.join(process.env.
22481
22482
  var gitHistoryService = new GitHistoryService2();
22482
22483
  var initialCliArgs = getCliArgs();
22483
22484
  var launchArguments = parseLaunchArgs(initialCliArgs);
22484
- var smokeTestMode = launchArguments.kind === "smoke" || launchArguments.kind === "smoke-multi" || launchArguments.kind === "smoke-directory";
22485
+ var smokeTestMode = launchArguments.kind === "smoke" || launchArguments.kind === "smoke-multi" || launchArguments.kind === "smoke-directory" || launchArguments.kind === "smoke-directory-history";
22485
22486
  var captureOutputPath = launchArguments.capturePath ? path8.resolve(launchArguments.capturePath) : null;
22486
22487
  var captureMode = Boolean(captureOutputPath);
22487
22488
  var launchWindowWidth = Number.isFinite(launchArguments.windowWidth) ? launchArguments.windowWidth : 1500;
@@ -22503,6 +22504,7 @@ var closingForSave = false;
22503
22504
  var fileWatchers = [];
22504
22505
  var session = createEmptySession();
22505
22506
  var smokeTimeout;
22507
+ var directoryHistorySmokeDrilldownStarted = false;
22506
22508
  var pendingOpenPaths = [];
22507
22509
  var historyIncludeStagedPreference = false;
22508
22510
  var historySkipUnchangedPreference = false;
@@ -23644,6 +23646,10 @@ async function routeLaunchTarget(launchTarget) {
23644
23646
  }
23645
23647
  if (launchTarget.kind === "smoke-directory") {
23646
23648
  await compareDirectoryTestFiles();
23649
+ return;
23650
+ }
23651
+ if (launchTarget.kind === "smoke-directory-history") {
23652
+ await compareDirectoryHistoryTestFiles();
23647
23653
  }
23648
23654
  }
23649
23655
  function sourceForLaunchTarget(launchTarget) {
@@ -23782,6 +23788,9 @@ function parseLaunchArgs(args) {
23782
23788
  if (filteredArgs[0] === "--smoke-test-directory") {
23783
23789
  return { kind: "smoke-directory", capturePath, windowWidth, windowHeight };
23784
23790
  }
23791
+ if (filteredArgs[0] === "--smoke-test-directory-history") {
23792
+ return { kind: "smoke-directory-history", capturePath, windowWidth, windowHeight };
23793
+ }
23785
23794
  if (filteredArgs.length >= 1 && !filteredArgs[0].startsWith("--")) {
23786
23795
  const resolvedPaths = filteredArgs.map((candidate) => resolveLaunchPath(candidate, cwd));
23787
23796
  const tourSelection = classifyAuthoredTourPaths2(resolvedPaths);
@@ -24725,9 +24734,13 @@ async function sendCurrentDirectoryHistoryEntry() {
24725
24734
  activePairIndex: pairs.length > 0 ? pairs.length - 1 : null,
24726
24735
  history: { ...history, fileName: relativePath },
24727
24736
  fileNavigation: buildDirectoryHistoryFileNavigationState(session.dirHistory, entry),
24728
- canReturnToDirectory: true
24737
+ canReturnToDirectory: true,
24738
+ revealFirstChangeInEachPanel: true
24729
24739
  });
24730
24740
  refreshSessionWindowTitle();
24741
+ if (launchArguments.kind === "smoke-directory-history") {
24742
+ pollDirectoryHistoryDrilldownSmoke();
24743
+ }
24731
24744
  scheduleCaptureIfNeeded();
24732
24745
  return;
24733
24746
  }
@@ -24752,6 +24765,12 @@ async function sendCurrentDirectoryHistoryEntry() {
24752
24765
  canMutate: true
24753
24766
  });
24754
24767
  refreshSessionWindowTitle();
24768
+ if (launchArguments.kind === "smoke-directory-history" && !directoryHistorySmokeDrilldownStarted && mainWindow && !mainWindow.isDestroyed()) {
24769
+ directoryHistorySmokeDrilldownStarted = true;
24770
+ setTimeout(() => {
24771
+ void mainWindow.webContents.executeJavaScript(`document.querySelector('.dir-entry[data-is-dir="false"]')?.click()`);
24772
+ }, 250);
24773
+ }
24755
24774
  scheduleCaptureIfNeeded();
24756
24775
  }
24757
24776
  function buildDirectoryHistoryViewState(dirHistory, entry) {
@@ -25920,20 +25939,30 @@ async function sendCurrentMultiDiff() {
25920
25939
  canReturnToDirectory: Boolean(session.returnDirectory),
25921
25940
  directoryNavigation: buildDirectoryDrilldownNavigationState(),
25922
25941
  fileNavigation: buildStandaloneFileNavigationState(),
25923
- mutationEnabled: !isDirectoryDrilldown
25942
+ mutationEnabled: !isDirectoryDrilldown,
25943
+ revealFirstChangeInEachPanel: isDirectoryDrilldown
25924
25944
  });
25925
25945
  refreshSessionWindowTitle();
25926
25946
  if (mainWindow && !mainWindow.isDestroyed()) {
25927
- setTimeout(() => {
25947
+ const inspectMultiDiff = () => {
25928
25948
  void mainWindow.webContents.executeJavaScript(`(() => ({
25929
25949
  fileInfo: document.getElementById('file-info')?.textContent,
25930
25950
  panelCount: document.querySelectorAll('.multi-pane').length,
25931
25951
  gutterCount: document.querySelectorAll('.multi-gutter').length,
25952
+ changePosition: document.getElementById('change-position')?.textContent,
25953
+ panelPositions: [...document.querySelectorAll('.multi-pane-position')].map((element) => element.textContent),
25954
+ decoratedLineCount: document.querySelectorAll('.bygone-paired-line, .bygone-one-sided-line').length,
25955
+ diffWorkerUrl: window.__BYGONE_HOST__?.diffWorkerUrl,
25932
25956
  activeDiffCount: document.querySelectorAll('.bygone-active-diff').length,
25933
25957
  adjacentEdgeCount: document.querySelectorAll('.bygone-paired-edge-left, .bygone-one-sided-edge-left').length,
25934
25958
  inlineAdjacentEdgeCount: document.querySelectorAll('.view-line span.bygone-paired-edge-left, .view-line span.bygone-one-sided-edge-left').length
25935
25959
  }))()`).then((snapshot) => {
25936
25960
  if (smokeTestMode) {
25961
+ const diffReady = /^1 \/ [1-9]\d*$/.test(snapshot.changePosition) && snapshot.panelPositions.some((position) => /^1 \/ [1-9]\d*$/.test(position)) && snapshot.decoratedLineCount > 0;
25962
+ if (!diffReady) {
25963
+ setTimeout(inspectMultiDiff, 100);
25964
+ return;
25965
+ }
25937
25966
  finalizeSmokeTest(snapshot);
25938
25967
  return;
25939
25968
  }
@@ -25947,7 +25976,8 @@ async function sendCurrentMultiDiff() {
25947
25976
  app.exit(1);
25948
25977
  }
25949
25978
  });
25950
- }, 400);
25979
+ };
25980
+ setTimeout(inspectMultiDiff, smokeTestMode ? 100 : 400);
25951
25981
  }
25952
25982
  }
25953
25983
  async function sendCurrentSession() {
@@ -26027,6 +26057,51 @@ async function compareDirectoryTestFiles() {
26027
26057
  fs7.writeFileSync(path8.join(right, "b.txt"), "right b\n", "utf8");
26028
26058
  await openDirectories([left, right], { source: { kind: "synthetic" } });
26029
26059
  }
26060
+ async function compareDirectoryHistoryTestFiles() {
26061
+ const root = fs7.mkdtempSync(path8.join(os.tmpdir(), "bygone-directory-history-smoke-"));
26062
+ const filePath = path8.join(root, "history-smoke.js");
26063
+ runGit(["init"], root);
26064
+ runGit(["config", "user.name", "Bygone Smoke Test"], root);
26065
+ runGit(["config", "user.email", "bygone-smoke@example.invalid"], root);
26066
+ const unchangedPrefix = Array.from({ length: 80 }, (_, index) => `const context${index} = true;`).join("\n");
26067
+ fs7.writeFileSync(filePath, `${unchangedPrefix}
26068
+ const alpha = 1;
26069
+ `, "utf8");
26070
+ runGit(["add", "history-smoke.js"], root);
26071
+ runGit(["commit", "-m", "initial"], root);
26072
+ fs7.writeFileSync(filePath, `${unchangedPrefix}
26073
+ const alpha = 2;
26074
+ `, "utf8");
26075
+ runGit(["add", "history-smoke.js"], root);
26076
+ runGit(["commit", "-m", "change history smoke fixture"], root);
26077
+ await openDirectoryHistory(root, false, { skipConfirm: true, source: { kind: "synthetic" } });
26078
+ }
26079
+ function pollDirectoryHistoryDrilldownSmoke() {
26080
+ if (!mainWindow || mainWindow.isDestroyed()) {
26081
+ return;
26082
+ }
26083
+ void mainWindow.webContents.executeJavaScript(`(() => ({
26084
+ directoryHistoryDrilldown: true,
26085
+ fileInfo: document.getElementById('file-info')?.textContent,
26086
+ changePosition: document.getElementById('change-position')?.textContent,
26087
+ panelPositions: [...document.querySelectorAll('.multi-pane-position')].map((element) => element.textContent),
26088
+ decoratedLineCount: document.querySelectorAll('.bygone-paired-line, .bygone-one-sided-line').length,
26089
+ visibleChangePaneCount: [...document.querySelectorAll('.multi-pane-content .view-lines')]
26090
+ .filter((element) => element.textContent.includes('alpha')).length,
26091
+ diffWorkerUrl: window.__BYGONE_HOST__?.diffWorkerUrl
26092
+ }))()`).then((snapshot) => {
26093
+ const ready = /^1 \/ [1-9]\d*$/.test(snapshot.changePosition) && snapshot.panelPositions.some((position) => /^1 \/ [1-9]\d*$/.test(position)) && snapshot.decoratedLineCount > 0 && snapshot.visibleChangePaneCount === 2;
26094
+ if (ready) {
26095
+ finalizeSmokeTest(snapshot);
26096
+ return;
26097
+ }
26098
+ setTimeout(pollDirectoryHistoryDrilldownSmoke, 100);
26099
+ }).catch((error) => {
26100
+ console.error(`Bygone directory history smoke test failed: ${getErrorMessage(error)}`);
26101
+ process.exitCode = 1;
26102
+ app.exit(1);
26103
+ });
26104
+ }
26030
26105
  async function sendCurrentDiff() {
26031
26106
  if (session.mode !== "diff") {
26032
26107
  return;
@@ -27398,7 +27473,7 @@ function shellQuote(value) {
27398
27473
  function finalizeSmokeTest(snapshot) {
27399
27474
  clearTimeout(smokeTimeout);
27400
27475
  smokeTimeout = void 0;
27401
- const passed = Boolean(snapshot && (snapshot.fileInfo === "Comparing test-file-1.js and test-file-2.js" && snapshot.file1 === "test-file-1.js" && snapshot.file2 === "test-file-2.js" && /^1 \/ \d+$/.test(snapshot.changePosition) && snapshot.pairedLineCount > 0 && snapshot.oneSidedLineCount > 0 && snapshot.inlineHighlightCount > 0 && snapshot.activeDiffCount === 0 && isVisibleBackground(snapshot.pairedLineBackground) && isVisibleBackground(snapshot.inlineHighlightBackground) && snapshot.pairedLineBackground !== snapshot.inlineHighlightBackground || snapshot.fileInfo === `Comparing ${snapshot.panelCount} files` && snapshot.panelCount >= 2 && snapshot.gutterCount === snapshot.panelCount - 1 && snapshot.activeDiffCount === 0 && snapshot.adjacentEdgeCount === 0 && snapshot.inlineAdjacentEdgeCount === 0 || snapshot.directoryRailVisible === true && snapshot.directoryRailItemCount === 2 && snapshot.directoryReturnVisible === true && snapshot.directorySidebarToggleVisible === true && snapshot.directorySidebarToggleWorked === true && snapshot.nextFileEnabled === true));
27476
+ const passed = Boolean(snapshot && (snapshot.fileInfo === "Comparing test-file-1.js and test-file-2.js" && snapshot.file1 === "test-file-1.js" && snapshot.file2 === "test-file-2.js" && /^1 \/ \d+$/.test(snapshot.changePosition) && snapshot.pairedLineCount > 0 && snapshot.oneSidedLineCount > 0 && snapshot.inlineHighlightCount > 0 && snapshot.activeDiffCount === 0 && isVisibleBackground(snapshot.pairedLineBackground) && isVisibleBackground(snapshot.inlineHighlightBackground) && snapshot.pairedLineBackground !== snapshot.inlineHighlightBackground || snapshot.fileInfo === `Comparing ${snapshot.panelCount} files` && snapshot.panelCount >= 2 && snapshot.gutterCount === snapshot.panelCount - 1 && /^1 \/ [1-9]\d*$/.test(snapshot.changePosition) && snapshot.panelPositions.some((position) => /^1 \/ [1-9]\d*$/.test(position)) && snapshot.decoratedLineCount > 0 && /\/media\/diff\.worker\.js$/.test(snapshot.diffWorkerUrl) && snapshot.activeDiffCount === 0 && snapshot.adjacentEdgeCount === 0 && snapshot.inlineAdjacentEdgeCount === 0 || snapshot.directoryRailVisible === true && snapshot.directoryRailItemCount === 2 && snapshot.directoryReturnVisible === true && snapshot.directorySidebarToggleVisible === true && snapshot.directorySidebarToggleWorked === true && snapshot.nextFileEnabled === true || snapshot.directoryHistoryDrilldown === true && snapshot.fileInfo === "Comparing 2 files" && /^1 \/ [1-9]\d*$/.test(snapshot.changePosition) && snapshot.panelPositions.some((position) => /^1 \/ [1-9]\d*$/.test(position)) && snapshot.decoratedLineCount > 0 && snapshot.visibleChangePaneCount === 2 && /\/media\/diff\.worker\.js$/.test(snapshot.diffWorkerUrl)));
27402
27477
  if (!passed) {
27403
27478
  console.error(`Bygone smoke test failed: unexpected diff DOM snapshot ${JSON.stringify(snapshot)}`);
27404
27479
  process.exitCode = 1;
@@ -3,6 +3,7 @@
3
3
  // standalone/preload.js
4
4
  var { contextBridge, ipcRenderer, webUtils } = require("electron");
5
5
  var editorWorkerUrl = new URL("../media/editor.worker.js", window.location.href).toString();
6
+ var diffWorkerUrl = new URL("../media/diff.worker.js", window.location.href).toString();
6
7
  ipcRenderer.on("bygone:host-message", (_event, payload) => {
7
8
  window.postMessage({
8
9
  __bygoneHostMessage: payload
@@ -11,6 +12,7 @@ ipcRenderer.on("bygone:host-message", (_event, payload) => {
11
12
  contextBridge.exposeInMainWorld("__BYGONE_HOST__", {
12
13
  environment: "standalone",
13
14
  editorWorkerUrl,
15
+ diffWorkerUrl,
14
16
  getPathForFile(file) {
15
17
  return webUtils.getPathForFile(file);
16
18
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@davmash/bygone",
3
- "version": "0.8.7",
3
+ "version": "0.8.9",
4
4
  "description": "See how change happened. Visual diff and file history.",
5
5
  "author": "David Mashburn",
6
6
  "license": "MIT",
package/web/web-host.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";(()=>{function Y(){}Y.prototype={diff:function(e,n){var r,o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=o.callback;typeof o=="function"&&(s=o,o={}),this.options=o;var l=this;function u(R){return s?(setTimeout(function(){s(void 0,R)},0),!0):R}e=this.castInput(e),n=this.castInput(n),e=this.removeEmpty(this.tokenize(e)),n=this.removeEmpty(this.tokenize(n));var d=n.length,m=e.length,p=1,a=d+m;o.maxEditLength&&(a=Math.min(a,o.maxEditLength));var I=(r=o.timeout)!==null&&r!==void 0?r:1/0,v=Date.now()+I,k=[{oldPos:-1,lastComponent:void 0}],E=this.extractCommon(k[0],n,e,0);if(k[0].oldPos+1>=m&&E+1>=d)return u([{value:this.join(n),count:n.length}]);var S=-1/0,w=1/0;function C(){for(var R=Math.max(S,-p);R<=Math.min(w,p);R+=2){var M=void 0,D=k[R-1],U=k[R+1];D&&(k[R-1]=void 0);var z=!1;if(U){var pe=U.oldPos-R;z=U&&0<=pe&&pe<d}var ie=D&&D.oldPos+1<m;if(!z&&!ie){k[R]=void 0;continue}if(!ie||z&&D.oldPos+1<U.oldPos?M=l.addToPath(U,!0,void 0,0):M=l.addToPath(D,void 0,!0,1),E=l.extractCommon(M,n,e,R),M.oldPos+1>=m&&E+1>=d)return u(xn(l,M.lastComponent,n,e,l.useLongestToken));k[R]=M,M.oldPos+1>=m&&(w=Math.min(w,R-1)),E+1>=d&&(S=Math.max(S,R+1))}p++}if(s)(function R(){setTimeout(function(){if(p>a||Date.now()>v)return s();C()||R()},0)})();else for(;p<=a&&Date.now()<=v;){var $=C();if($)return $}},addToPath:function(e,n,r,o){var s=e.lastComponent;return s&&s.added===n&&s.removed===r?{oldPos:e.oldPos+o,lastComponent:{count:s.count+1,added:n,removed:r,previousComponent:s.previousComponent}}:{oldPos:e.oldPos+o,lastComponent:{count:1,added:n,removed:r,previousComponent:s}}},extractCommon:function(e,n,r,o){for(var s=n.length,l=r.length,u=e.oldPos,d=u-o,m=0;d+1<s&&u+1<l&&this.equals(n[d+1],r[u+1]);)d++,u++,m++;return m&&(e.lastComponent={count:m,previousComponent:e.lastComponent}),e.oldPos=u,d},equals:function(e,n){return this.options.comparator?this.options.comparator(e,n):e===n||this.options.ignoreCase&&e.toLowerCase()===n.toLowerCase()},removeEmpty:function(e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(e[r]);return n},castInput:function(e){return e},tokenize:function(e){return e.split("")},join:function(e){return e.join("")}};function xn(t,e,n,r,o){for(var s=[],l;e;)s.push(e),l=e.previousComponent,delete e.previousComponent,e=l;s.reverse();for(var u=0,d=s.length,m=0,p=0;u<d;u++){var a=s[u];if(a.removed){if(a.value=t.join(r.slice(p,p+a.count)),p+=a.count,u&&s[u-1].added){var v=s[u-1];s[u-1]=s[u],s[u]=v}}else{if(!a.added&&o){var I=n.slice(m,m+a.count);I=I.map(function(E,S){var w=r[p+S];return w.length>E.length?w:E}),a.value=t.join(I)}else a.value=t.join(n.slice(m,m+a.count));m+=a.count,a.added||(p+=a.count)}}var k=s[d-1];return d>1&&typeof k.value=="string"&&(k.added||k.removed)&&t.equals("",k.value)&&(s[d-2].value+=k.value,s.pop()),s}var Sn=new Y;function pt(t,e,n){return Sn.diff(t,e,n)}var ht=/^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/,mt=/\S/,ze=new Y;ze.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!mt.test(t)&&!mt.test(e)};ze.tokenize=function(t){for(var e=t.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/),n=0;n<e.length-1;n++)!e[n+1]&&e[n+2]&&ht.test(e[n])&&ht.test(e[n+2])&&(e[n]+=e[n+2],e.splice(n+1,2),n--);return e};function bt(t,e,n){return ze.diff(t,e,n)}var yt=new Y;yt.tokenize=function(t){this.options.stripTrailingCr&&(t=t.replace(/\r\n/g,`
2
2
  `));var e=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(var r=0;r<n.length;r++){var o=n[r];r%2&&!this.options.newlineIsToken?e[e.length-1]+=o:(this.options.ignoreWhitespace&&(o=o.trim()),e.push(o))}return e};var vn=new Y;vn.tokenize=function(t){return t.split(/(\S.+?[.!?])(?=\s+|$)/)};var En=new Y;En.tokenize=function(t){return t.split(/([{}:;,]|\s+)/)};function ve(t){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?ve=function(e){return typeof e}:ve=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},ve(t)}var Tn=Object.prototype.toString,ge=new Y;ge.useLongestToken=!0;ge.tokenize=yt.tokenize;ge.castInput=function(t){var e=this.options,n=e.undefinedReplacement,r=e.stringifyReplacer,o=r===void 0?function(s,l){return typeof l>"u"?n:l}:r;return typeof t=="string"?t:JSON.stringify(Ge(t,null,null,o),o," ")};ge.equals=function(t,e){return Y.prototype.equals.call(ge,t.replace(/,([\r\n])/g,"$1"),e.replace(/,([\r\n])/g,"$1"))};function Ge(t,e,n,r,o){e=e||[],n=n||[],r&&(t=r(o,t));var s;for(s=0;s<e.length;s+=1)if(e[s]===t)return n[s];var l;if(Tn.call(t)==="[object Array]"){for(e.push(t),l=new Array(t.length),n.push(l),s=0;s<t.length;s+=1)l[s]=Ge(t[s],e,n,r,o);return e.pop(),n.pop(),l}if(t&&t.toJSON&&(t=t.toJSON()),ve(t)==="object"&&t!==null){e.push(t),l={},n.push(l);var u=[],d;for(d in t)t.hasOwnProperty(d)&&u.push(d);for(u.sort(),s=0;s<u.length;s+=1)d=u[s],l[d]=Ge(t[d],e,n,r,d);e.pop(),n.pop()}else l=t;return l}var Ee=new Y;Ee.tokenize=function(t){return t.slice()};Ee.join=Ee.removeEmpty=function(t){return t};function wt(t,e,n){return Ee.diff(t,e,n)}var Cn=500,Nn=100,It=Dt("BYGONE_MAX_INLINE_HIGHLIGHT_LINE_LENGTH",Cn),Ln=Dt("BYGONE_DIFF_TIMEOUT_MS",Nn);function ne(t,e,n={}){let r=xt(t),o=xt(e),s=wt(r,o,{timeout:n.timeoutMs??Ln});if(!s)return $n(r,o);let l=[],u=[],d=[],m=[],p=1,a=1;for(let v=0;v<s.length;v++){let k=s[v],E=k.removed?k.value:[],S=k.added?k.value:[];if(!k.added&&!k.removed){for(let w of k.value)u.push(Q("context",w,p)),d.push(Q("context",w,a)),l.push(ae(Z("context",w,p++),Z("context",w,a++)));continue}if(k.removed&&v+1<s.length&&s[v+1].added){let w=s[v+1],C=u.length,$=d.length,R=Mt(E,w.value);for(let{left:M,right:D}of R){let U,z;M!==void 0&&(U=Q("removed",M,p),u.push(U)),D!==void 0&&(z=Q("added",D,a),d.push(z)),U&&z&&Xn(U,z),l.push(ae(M===void 0?se():Z("removed",M,p++),D===void 0?se():Z("added",D,a++)))}m.push(Ne("replace",C,u.length,$,d.length)),v++;continue}if(k.removed){let w=u.length,C=d.length;for(let $ of E)u.push(Q("removed",$,p)),l.push(ae(Z("removed",$,p++),se()));m.push(Ne("delete",w,u.length,C,d.length));continue}if(k.added){let w=u.length,C=d.length;for(let $ of S)d.push(Q("added",$,a)),l.push(ae(se(),Z("added",$,a++)));m.push(Ne("insert",w,u.length,C,d.length))}}let I=l.some(v=>v.left.kind!=="context"||v.right.kind!=="context");return{rows:l,leftLines:u,rightLines:d,blocks:m,hasChanges:I}}function $n(t,e){let n=t.map((l,u)=>Q("removed",l,u+1)),r=e.map((l,u)=>Q("added",l,u+1)),o=[...t.map((l,u)=>ae(Z("removed",l,u+1),se())),...e.map((l,u)=>ae(se(),Z("added",l,u+1)))],s="replace";return t.length===0?s="insert":e.length===0&&(s="delete"),{rows:o,leftLines:n,rightLines:r,blocks:o.length===0?[]:[Ne(s,0,t.length,0,e.length)],hasChanges:o.length>0}}function xt(t){if(t.length===0)return[];let e=t.replace(/\r\n/g,`
3
3
  `).split(`
4
- `);return e[e.length-1]===""&&e.pop(),e}var Rt=1e4,St=2e3,Rn=.52,An=.35,At=.38,Fn=.33,Ft=.86,Le=.08,Te=.05,ke=-.12,vt=5e3,Mn=2e3,Et=4,Pn=8,Ve=4;function Mt(t,e){if(t.length===0)return e.map(d=>({right:d}));if(e.length===0)return t.map(d=>({left:d}));if(t.length===1&&e.length===1){let d=Ye(t[0],e[0]);return(d.eligible||d.score>=An)&&je(t[0],e[0])&&he(ee(t[0]))&&he(ee(e[0]))?[{left:t[0],right:e[0]}]:[{left:t[0]},{right:e[0]}]}if(t.length*e.length>Rt)return Bn(t,e);let n=Dn(t,e),r=Array.from({length:t.length+1},()=>new Array(e.length+1).fill(Number.NEGATIVE_INFINITY)),o=Array.from({length:t.length+1},()=>new Array(e.length+1).fill(null));r[0][0]=0;for(let d=1;d<=t.length;d++)r[d][0]=r[d-1][0]+ke,o[d][0]="left";for(let d=1;d<=e.length;d++)r[0][d]=r[0][d-1]+ke,o[0][d]="right";for(let d=1;d<=t.length;d++)for(let m=1;m<=e.length;m++){let p=n[d-1][m-1],I=[{move:"left",score:r[d-1][m]+ke},{move:"right",score:r[d][m-1]+ke},{move:"match",score:p===null?Number.NEGATIVE_INFINITY:r[d-1][m-1]+p}].reduce((v,k)=>k.score>v.score?k:v);r[d][m]=I.score,o[d][m]=I.move}let s=[],l=t.length,u=e.length;for(;l>0||u>0;){let d=o[l][u];d==="match"?s.push({left:t[--l],right:e[--u]}):d==="left"?s.push({left:t[--l]}):s.push({right:e[--u]})}return s.reverse()}function Ye(t,e){let n=ee(t),r=ee(e),o=he(n),s=he(r);if(!o||!s||n.length>St||r.length>St)return{score:0,eligible:!1,characterSimilarity:0,tokenSimilarity:0,lengthSimilarity:0};if(n===r)return{score:1,eligible:!0,characterSimilarity:1,tokenSimilarity:1,lengthSimilarity:1};let l=Xe(n),u=Xe(r),d=Kn(n,r),m=qn(l,u),p=Math.min(n.length,r.length)/Math.max(n.length,r.length),a=jn(l,u),I=d*.52+m*.32+p*.1+a*.06,v=d>=.52||m>=.45||d>=.48&&m>=.28;return{score:I,eligible:v&&I>=Rn,characterSimilarity:d,tokenSimilarity:m,lengthSimilarity:p}}function Dn(t,e){let n=t.map(E=>e.map(S=>Ye(E,S))),r=Pt(t,e),o=n.map(E=>qe(E)),s=e.map((E,S)=>qe(n.map(w=>w[S]))),l=n.map((E,S)=>E.map((w,C)=>{if(r.has(`${S}:${C}`))return Math.max(w.score,1);if(!w.eligible)return null;let $=o[S],R=s[C],M=w.score===$.best&&w.score===R.best,D=w.score>=Ft?Le/2:Le,U=$.best-$.second>=D,z=R.best-R.second>=D;return M&&U&&z?w.score:null}));if(Math.max(t.length,e.length)>Pn||Math.abs(t.length-e.length)>Ve)return l;let u=(E,S,w)=>E.score>=At&&je(t[S],e[w])&&Math.abs(S-w)<=Ve,d=n.map((E,S)=>Ce(E,(w,C)=>u(w,S,C))),m=e.map((E,S)=>Ce(n.map(w=>w[S]),(w,C)=>u(w,C,S))),p=(E,S,w)=>E.score>=Fn&&je(t[S],e[w])&&Math.abs(S-w)<=Ve,a=n.map((E,S)=>Ce(E,(w,C)=>p(w,S,C))),I=e.map((E,S)=>Ce(n.map(w=>w[S]),(w,C)=>p(w,C,S))),v=(E,S)=>{let w=n[E][S];if(!u(w,E,S))return!1;let C=d[E],$=m[S];return w.score===C.best&&w.score===$.best&&C.best-C.second>=Te&&$.best-$.second>=Te},k=(E,S)=>{let w=n[E][S];if(!p(w,E,S))return!1;let C=a[E],$=I[S];return w.score===C.best&&w.score===$.best&&C.best-C.second>=Te&&$.best-$.second>=Te};return l.map((E,S)=>E.map((w,C)=>{if(w!==null)return w;let $=v(S,C)&&(_n(l,S,C)||On(n,S,C,v)),R=Hn(n,S,C,(M,D)=>p(n[M][D],M,D),k);return!$&&!R?null:n[S][C].score}))}function _n(t,e,n){return e>0&&n>0&&t[e-1][n-1]!==null||e+1<t.length&&n+1<t[e+1].length&&t[e+1][n+1]!==null}function On(t,e,n,r){return e>0&&n>0&&r(e-1,n-1)||e+1<t.length&&n+1<t[e+1].length&&r(e+1,n+1)}function Hn(t,e,n,r,o){let s=e,l=n;for(;s>0&&l>0&&r(s-1,l-1);)s--,l--;let u=e,d=n,m=t[e][n].score,p=1;for(;u+1<t.length&&d+1<t[u+1].length&&r(u+1,d+1);)u++,d++,m+=t[u][d].score,p++;for(let a=e-1,I=n-1;a>=s&&I>=l;a--,I--)m+=t[a][I].score,p++;return p>=3&&m/p>=At&&o(s,l)&&o(u,d)}function Ce(t,e){let n=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;return t.forEach((o,s)=>{e(o,s)&&(o.score>n?(r=n,n=o.score):o.score>r&&(r=o.score))}),{best:n,second:r}}function qe(t){let e=Number.NEGATIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let r of t)r.eligible&&(r.score>e?(n=e,e=r.score):r.score>n&&(n=r.score));return{best:e,second:n}}function Bn(t,e){let n=Un(t,e),r=[],o=0,s=0;for(let l of n)Lt(r,t.slice(o,l.leftIndex),e.slice(s,l.rightIndex)),r.push({left:t[l.leftIndex],right:e[l.rightIndex]}),o=l.leftIndex+1,s=l.rightIndex+1;return Lt(r,t.slice(o),e.slice(s)),r}function Un(t,e){let n=Wn(t,e);if(n===null)return[];let r=Pt(t,e),o=n.map(({leftIndex:m,rightIndex:p,exact:a})=>({leftIndex:m,rightIndex:p,exact:a,structural:r.has(`${m}:${p}`),match:Ye(t[m],e[p])})).filter(m=>m.exact||m.structural||m.match.eligible),s=Ct(o,"leftIndex"),l=Ct(o,"rightIndex"),u=o.filter(m=>{if(m.exact||m.structural)return!0;let p=s.get(m.leftIndex),a=l.get(m.rightIndex);if(!p||!a||m.match.score!==p.best||m.match.score!==a.best)return!1;let I=m.match.score>=Ft?Le/2:Le;return p.best-p.second>=I&&a.best-a.second>=I}),d=zn(u,e.length);return d.length<=Mn?d:[]}function Wn(t,e){let n=Tt(t,ee),r=Tt(e,ee),o=new Map;for(let[u,d]of n){let m=r.get(u);if(!he(u)||d.length!==1||m?.length!==1)continue;let p=d[0],a=m[0];if(o.set(`${p}:${a}`,{leftIndex:p,rightIndex:a,exact:!0}),o.size>vt)return null}let s=kt(t),l=kt(e);for(let[u,d]of s){let m=l.get(u);if(!(!m||d.length>Et||m.length>Et))for(let p of d)for(let a of m){let I=`${p}:${a}`;if(!o.has(I)&&(o.set(I,{leftIndex:p,rightIndex:a,exact:!1}),o.size>vt))return null}}return[...o.values()]}function Tt(t,e){let n=new Map;return t.forEach((r,o)=>{let s=e(r),l=n.get(s)??[];l.push(o),n.set(s,l)}),n}function kt(t){let e=new Map;return t.forEach((n,r)=>{let o=new Set(Xe(ee(n)).filter(Gn));for(let s of o){let l=e.get(s)??[];l.push(r),e.set(s,l)}}),e}function Gn(t){return t.length>=2&&/[\p{L}\p{N}_$]/u.test(t)}function Ct(t,e){let n=new Map;for(let r of t){let o=n.get(r[e])??[];o.push(r.match),n.set(r[e],o)}return new Map([...n].map(([r,o])=>[r,qe(o)]))}function zn(t,e){let n=[...t].sort((m,p)=>m.leftIndex-p.leftIndex||m.rightIndex-p.rightIndex),r=new Array(e+2).fill(0),o=new Array(e+2).fill(-1),s=new Array(n.length).fill(0),l=new Array(n.length).fill(-1);for(let m=0;m<n.length;){let p=m+1;for(;p<n.length&&n[p].leftIndex===n[m].leftIndex;)p++;for(let a=m;a<p;a++){let I=Nt(r,o,n[a].rightIndex),v=n[a].exact||n[a].structural?.5:0;s[a]=I.score+n[a].match.score+v,l[a]=I.candidateIndex}for(let a=m;a<p;a++)Vn(r,o,n[a].rightIndex+1,s[a],a);m=p}let u=Nt(r,o,e+1),d=[];for(let m=u.candidateIndex;m>=0;m=l[m])d.push({leftIndex:n[m].leftIndex,rightIndex:n[m].rightIndex});return d.reverse()}function Nt(t,e,n){let r=0,o=-1;for(let s=n;s>0;s-=s&-s)t[s]>r&&(r=t[s],o=e[s]);return{score:r,candidateIndex:o}}function Vn(t,e,n,r,o){for(let s=n;s<t.length;s+=s&-s)r>t[s]&&(t[s]=r,e[s]=o)}function Lt(t,e,n){if(e.length*n.length<=Rt){t.push(...Mt(e,n));return}t.push(...e.map(r=>({left:r}))),t.push(...n.map(r=>({right:r})))}function ee(t){return t.trim().replace(/\s+/g," ")}function Pt(t,e){let n=$t(t),r=$t(e),o=new Set;for(let[s,l]of n){let u=r.get(s);l.length===1&&u?.length===1&&o.add(`${l[0]}:${u[0]}`)}return o}function $t(t){let e=new Map;return t.forEach((n,r)=>{let o=Ke(n);if(!o)return;let s=e.get(o)??[];s.push(r),e.set(o,s)}),e}function je(t,e){let n=Ke(t),r=Ke(e);return!n||!r?n===r:n.split(":",1)[0]===r.split(":",1)[0]}function Ke(t){let e=ee(t),n=[["function",/^(?:(?:export|default)\s+)*(?:async\s+)?function\s*\*?\s*([\p{L}_$][\p{L}\p{N}_$]*)\s*\(/u],["function",/^(?:async\s+)?def\s+([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["function",/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([\p{L}_][\p{L}\p{N}_]*)\s*(?:<[^>]*>)?\s*\(/u],["function",/^func\s+(?:\([^)]*\)\s*)?([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["class",/^(?:(?:export|default|abstract|public)\s+)*class\s+([\p{L}_$][\p{L}\p{N}_$]*)\b/u]];for(let[r,o]of n){let s=e.match(o);if(s)return`${r}:${s[1]}`}return null}function he(t){return t.length<3?!1:/[\p{L}\p{N}_$]/u.test(t)&&!/^[\s()[\]{};,.:+\-*/=>|&!?'"`]+$/.test(t)}function Xe(t){return t.toLowerCase().match(/[\p{L}_$][\p{L}\p{N}_$]*|\p{N}+(?:\.\p{N}+)?|[^\s\p{L}\p{N}_$]/gu)??[]}function qn(t,e){if(t.length+e.length===0)return 1;let n=new Map;t.forEach(o=>n.set(o,(n.get(o)??0)+1));let r=0;for(let o of e){let s=n.get(o)??0;s>0&&(r++,n.set(o,s-1))}return 2*r/(t.length+e.length)}function jn(t,e){if(t.length===0||e.length===0)return 0;let n=t[0]===e[0]?.5:0,r=t[t.length-1]===e[e.length-1]?.5:0;return n+r}function Kn(t,e){let n=t.length+e.length;return n===0?1:2*pt(t,e).filter(o=>!o.added&&!o.removed).reduce((o,s)=>o+s.value.length,0)/n}function Xn(t,e){if(t.content.length>It||e.content.length>It)return;let{leftSegments:n,rightSegments:r,hasInlineChanges:o}=Yn(t.content,e.content);o&&(t.segments=n,e.segments=r)}function Yn(t,e){let n=bt(t,e),r=[],o=[],s=!1;for(let l of n){let u=l.value;if(!l.added&&!l.removed){let m={kind:"context",text:u,emphasis:!1};r.push(m),o.push(m);continue}let d=/[^\s]/.test(u);s=s||d,l.removed&&r.push({kind:"removed",text:u,emphasis:d}),l.added&&o.push({kind:"added",text:u,emphasis:d})}return{leftSegments:r,rightSegments:o,hasInlineChanges:s}}function se(){return{kind:"placeholder",content:"",lineNumber:null}}function Z(t,e,n){return{kind:t,content:e,lineNumber:n}}function Q(t,e,n){return{kind:t,content:e,lineNumber:n}}function ae(t,e){return{left:t,right:e}}function Ne(t,e,n,r,o){return{kind:t,leftStart:e,leftEnd:n,rightStart:r,rightEnd:o}}function Dt(t,e){let n=typeof process<"u"?process.env?.[t]:void 0,r=Number.parseInt(n??"",10);return Number.isFinite(r)&&r>0?r:e}function _t(){return{leftFileName:"test-file-1.js",rightFileName:"test-file-2.js",leftContent:`// Test File 1 - Example JavaScript Code
4
+ `);return e[e.length-1]===""&&e.pop(),e}var Rt=1e4,St=2e3,Rn=.52,An=.35,At=.38,Fn=.33,Ft=.86,Le=.08,Te=.05,ke=-.12,vt=5e3,Mn=2e3,Et=4,Pn=8,Ve=4;function Mt(t,e){if(t.length===0)return e.map(d=>({right:d}));if(e.length===0)return t.map(d=>({left:d}));if(t.length===1&&e.length===1){let d=Ye(t[0],e[0]);return(d.eligible||d.score>=An)&&qe(t[0],e[0])&&he(ee(t[0]))&&he(ee(e[0]))?[{left:t[0],right:e[0]}]:[{left:t[0]},{right:e[0]}]}if(t.length*e.length>Rt)return Bn(t,e);let n=Dn(t,e),r=Array.from({length:t.length+1},()=>new Array(e.length+1).fill(Number.NEGATIVE_INFINITY)),o=Array.from({length:t.length+1},()=>new Array(e.length+1).fill(null));r[0][0]=0;for(let d=1;d<=t.length;d++)r[d][0]=r[d-1][0]+ke,o[d][0]="left";for(let d=1;d<=e.length;d++)r[0][d]=r[0][d-1]+ke,o[0][d]="right";for(let d=1;d<=t.length;d++)for(let m=1;m<=e.length;m++){let p=n[d-1][m-1],I=[{move:"left",score:r[d-1][m]+ke},{move:"right",score:r[d][m-1]+ke},{move:"match",score:p===null?Number.NEGATIVE_INFINITY:r[d-1][m-1]+p}].reduce((v,k)=>k.score>v.score?k:v);r[d][m]=I.score,o[d][m]=I.move}let s=[],l=t.length,u=e.length;for(;l>0||u>0;){let d=o[l][u];d==="match"?s.push({left:t[--l],right:e[--u]}):d==="left"?s.push({left:t[--l]}):s.push({right:e[--u]})}return s.reverse()}function Ye(t,e){let n=ee(t),r=ee(e),o=he(n),s=he(r);if(!o||!s||n.length>St||r.length>St)return{score:0,eligible:!1,characterSimilarity:0,tokenSimilarity:0,lengthSimilarity:0};if(n===r)return{score:1,eligible:!0,characterSimilarity:1,tokenSimilarity:1,lengthSimilarity:1};let l=Xe(n),u=Xe(r),d=Kn(n,r),m=jn(l,u),p=Math.min(n.length,r.length)/Math.max(n.length,r.length),a=qn(l,u),I=d*.52+m*.32+p*.1+a*.06,v=d>=.52||m>=.45||d>=.48&&m>=.28;return{score:I,eligible:v&&I>=Rn,characterSimilarity:d,tokenSimilarity:m,lengthSimilarity:p}}function Dn(t,e){let n=t.map(E=>e.map(S=>Ye(E,S))),r=Pt(t,e),o=n.map(E=>je(E)),s=e.map((E,S)=>je(n.map(w=>w[S]))),l=n.map((E,S)=>E.map((w,C)=>{if(r.has(`${S}:${C}`))return Math.max(w.score,1);if(!w.eligible)return null;let $=o[S],R=s[C],M=w.score===$.best&&w.score===R.best,D=w.score>=Ft?Le/2:Le,U=$.best-$.second>=D,z=R.best-R.second>=D;return M&&U&&z?w.score:null}));if(Math.max(t.length,e.length)>Pn||Math.abs(t.length-e.length)>Ve)return l;let u=(E,S,w)=>E.score>=At&&qe(t[S],e[w])&&Math.abs(S-w)<=Ve,d=n.map((E,S)=>Ce(E,(w,C)=>u(w,S,C))),m=e.map((E,S)=>Ce(n.map(w=>w[S]),(w,C)=>u(w,C,S))),p=(E,S,w)=>E.score>=Fn&&qe(t[S],e[w])&&Math.abs(S-w)<=Ve,a=n.map((E,S)=>Ce(E,(w,C)=>p(w,S,C))),I=e.map((E,S)=>Ce(n.map(w=>w[S]),(w,C)=>p(w,C,S))),v=(E,S)=>{let w=n[E][S];if(!u(w,E,S))return!1;let C=d[E],$=m[S];return w.score===C.best&&w.score===$.best&&C.best-C.second>=Te&&$.best-$.second>=Te},k=(E,S)=>{let w=n[E][S];if(!p(w,E,S))return!1;let C=a[E],$=I[S];return w.score===C.best&&w.score===$.best&&C.best-C.second>=Te&&$.best-$.second>=Te};return l.map((E,S)=>E.map((w,C)=>{if(w!==null)return w;let $=v(S,C)&&(_n(l,S,C)||On(n,S,C,v)),R=Hn(n,S,C,(M,D)=>p(n[M][D],M,D),k);return!$&&!R?null:n[S][C].score}))}function _n(t,e,n){return e>0&&n>0&&t[e-1][n-1]!==null||e+1<t.length&&n+1<t[e+1].length&&t[e+1][n+1]!==null}function On(t,e,n,r){return e>0&&n>0&&r(e-1,n-1)||e+1<t.length&&n+1<t[e+1].length&&r(e+1,n+1)}function Hn(t,e,n,r,o){let s=e,l=n;for(;s>0&&l>0&&r(s-1,l-1);)s--,l--;let u=e,d=n,m=t[e][n].score,p=1;for(;u+1<t.length&&d+1<t[u+1].length&&r(u+1,d+1);)u++,d++,m+=t[u][d].score,p++;for(let a=e-1,I=n-1;a>=s&&I>=l;a--,I--)m+=t[a][I].score,p++;return p>=3&&m/p>=At&&o(s,l)&&o(u,d)}function Ce(t,e){let n=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;return t.forEach((o,s)=>{e(o,s)&&(o.score>n?(r=n,n=o.score):o.score>r&&(r=o.score))}),{best:n,second:r}}function je(t){let e=Number.NEGATIVE_INFINITY,n=Number.NEGATIVE_INFINITY;for(let r of t)r.eligible&&(r.score>e?(n=e,e=r.score):r.score>n&&(n=r.score));return{best:e,second:n}}function Bn(t,e){let n=Un(t,e),r=[],o=0,s=0;for(let l of n)Lt(r,t.slice(o,l.leftIndex),e.slice(s,l.rightIndex)),r.push({left:t[l.leftIndex],right:e[l.rightIndex]}),o=l.leftIndex+1,s=l.rightIndex+1;return Lt(r,t.slice(o),e.slice(s)),r}function Un(t,e){let n=Wn(t,e);if(n===null)return[];let r=Pt(t,e),o=n.map(({leftIndex:m,rightIndex:p,exact:a})=>({leftIndex:m,rightIndex:p,exact:a,structural:r.has(`${m}:${p}`),match:Ye(t[m],e[p])})).filter(m=>m.exact||m.structural||m.match.eligible),s=Ct(o,"leftIndex"),l=Ct(o,"rightIndex"),u=o.filter(m=>{if(m.exact||m.structural)return!0;let p=s.get(m.leftIndex),a=l.get(m.rightIndex);if(!p||!a||m.match.score!==p.best||m.match.score!==a.best)return!1;let I=m.match.score>=Ft?Le/2:Le;return p.best-p.second>=I&&a.best-a.second>=I}),d=zn(u,e.length);return d.length<=Mn?d:[]}function Wn(t,e){let n=Tt(t,ee),r=Tt(e,ee),o=new Map;for(let[u,d]of n){let m=r.get(u);if(!he(u)||d.length!==1||m?.length!==1)continue;let p=d[0],a=m[0];if(o.set(`${p}:${a}`,{leftIndex:p,rightIndex:a,exact:!0}),o.size>vt)return null}let s=kt(t),l=kt(e);for(let[u,d]of s){let m=l.get(u);if(!(!m||d.length>Et||m.length>Et))for(let p of d)for(let a of m){let I=`${p}:${a}`;if(!o.has(I)&&(o.set(I,{leftIndex:p,rightIndex:a,exact:!1}),o.size>vt))return null}}return[...o.values()]}function Tt(t,e){let n=new Map;return t.forEach((r,o)=>{let s=e(r),l=n.get(s)??[];l.push(o),n.set(s,l)}),n}function kt(t){let e=new Map;return t.forEach((n,r)=>{let o=new Set(Xe(ee(n)).filter(Gn));for(let s of o){let l=e.get(s)??[];l.push(r),e.set(s,l)}}),e}function Gn(t){return t.length>=2&&/[\p{L}\p{N}_$]/u.test(t)}function Ct(t,e){let n=new Map;for(let r of t){let o=n.get(r[e])??[];o.push(r.match),n.set(r[e],o)}return new Map([...n].map(([r,o])=>[r,je(o)]))}function zn(t,e){let n=[...t].sort((m,p)=>m.leftIndex-p.leftIndex||m.rightIndex-p.rightIndex),r=new Array(e+2).fill(0),o=new Array(e+2).fill(-1),s=new Array(n.length).fill(0),l=new Array(n.length).fill(-1);for(let m=0;m<n.length;){let p=m+1;for(;p<n.length&&n[p].leftIndex===n[m].leftIndex;)p++;for(let a=m;a<p;a++){let I=Nt(r,o,n[a].rightIndex),v=n[a].exact||n[a].structural?.5:0;s[a]=I.score+n[a].match.score+v,l[a]=I.candidateIndex}for(let a=m;a<p;a++)Vn(r,o,n[a].rightIndex+1,s[a],a);m=p}let u=Nt(r,o,e+1),d=[];for(let m=u.candidateIndex;m>=0;m=l[m])d.push({leftIndex:n[m].leftIndex,rightIndex:n[m].rightIndex});return d.reverse()}function Nt(t,e,n){let r=0,o=-1;for(let s=n;s>0;s-=s&-s)t[s]>r&&(r=t[s],o=e[s]);return{score:r,candidateIndex:o}}function Vn(t,e,n,r,o){for(let s=n;s<t.length;s+=s&-s)r>t[s]&&(t[s]=r,e[s]=o)}function Lt(t,e,n){if(e.length*n.length<=Rt){t.push(...Mt(e,n));return}t.push(...e.map(r=>({left:r}))),t.push(...n.map(r=>({right:r})))}function ee(t){return t.trim().replace(/\s+/g," ")}function Pt(t,e){let n=$t(t),r=$t(e),o=new Set;for(let[s,l]of n){let u=r.get(s);l.length===1&&u?.length===1&&o.add(`${l[0]}:${u[0]}`)}return o}function $t(t){let e=new Map;return t.forEach((n,r)=>{let o=Ke(n);if(!o)return;let s=e.get(o)??[];s.push(r),e.set(o,s)}),e}function qe(t,e){let n=Ke(t),r=Ke(e);return!n||!r?n===r:n.split(":",1)[0]===r.split(":",1)[0]}function Ke(t){let e=ee(t),n=[["function",/^(?:(?:export|default)\s+)*(?:async\s+)?function\s*\*?\s*([\p{L}_$][\p{L}\p{N}_$]*)\s*\(/u],["function",/^(?:async\s+)?def\s+([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["function",/^(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?fn\s+([\p{L}_][\p{L}\p{N}_]*)\s*(?:<[^>]*>)?\s*\(/u],["function",/^func\s+(?:\([^)]*\)\s*)?([\p{L}_][\p{L}\p{N}_]*)\s*\(/u],["class",/^(?:(?:export|default|abstract|public)\s+)*class\s+([\p{L}_$][\p{L}\p{N}_$]*)\b/u]];for(let[r,o]of n){let s=e.match(o);if(s)return`${r}:${s[1]}`}return null}function he(t){return t.length<3?!1:/[\p{L}\p{N}_$]/u.test(t)&&!/^[\s()[\]{};,.:+\-*/=>|&!?'"`]+$/.test(t)}function Xe(t){return t.toLowerCase().match(/[\p{L}_$][\p{L}\p{N}_$]*|\p{N}+(?:\.\p{N}+)?|[^\s\p{L}\p{N}_$]/gu)??[]}function jn(t,e){if(t.length+e.length===0)return 1;let n=new Map;t.forEach(o=>n.set(o,(n.get(o)??0)+1));let r=0;for(let o of e){let s=n.get(o)??0;s>0&&(r++,n.set(o,s-1))}return 2*r/(t.length+e.length)}function qn(t,e){if(t.length===0||e.length===0)return 0;let n=t[0]===e[0]?.5:0,r=t[t.length-1]===e[e.length-1]?.5:0;return n+r}function Kn(t,e){let n=t.length+e.length;return n===0?1:2*pt(t,e).filter(o=>!o.added&&!o.removed).reduce((o,s)=>o+s.value.length,0)/n}function Xn(t,e){if(t.content.length>It||e.content.length>It)return;let{leftSegments:n,rightSegments:r,hasInlineChanges:o}=Yn(t.content,e.content);o&&(t.segments=n,e.segments=r)}function Yn(t,e){let n=bt(t,e),r=[],o=[],s=!1;for(let l of n){let u=l.value;if(!l.added&&!l.removed){let m={kind:"context",text:u,emphasis:!1};r.push(m),o.push(m);continue}let d=/[^\s]/.test(u);s=s||d,l.removed&&r.push({kind:"removed",text:u,emphasis:d}),l.added&&o.push({kind:"added",text:u,emphasis:d})}return{leftSegments:r,rightSegments:o,hasInlineChanges:s}}function se(){return{kind:"placeholder",content:"",lineNumber:null}}function Z(t,e,n){return{kind:t,content:e,lineNumber:n}}function Q(t,e,n){return{kind:t,content:e,lineNumber:n}}function ae(t,e){return{left:t,right:e}}function Ne(t,e,n,r,o){return{kind:t,leftStart:e,leftEnd:n,rightStart:r,rightEnd:o}}function Dt(t,e){let n=typeof process<"u"?process.env?.[t]:void 0,r=Number.parseInt(n??"",10);return Number.isFinite(r)&&r>0?r:e}function _t(){return{leftFileName:"test-file-1.js",rightFileName:"test-file-2.js",leftContent:`// Test File 1 - Example JavaScript Code
5
5
  const fs = require('fs');
6
6
  const path = require('path');
7
7
 
@@ -145,7 +145,7 @@ if (require.main === module) {
145
145
  }
146
146
 
147
147
  module.exports = FileProcessor;
148
- `}}function Ot(t){if(!O(t)||t.version!==1)throw new Error("Unsupported or missing change-tour manifest version.");if(L(t.title,"title"),L(t.generatedAt,"generatedAt"),t.windowTitle!==void 0&&L(t.windowTitle,"windowTitle"),t.sourceUrl!==void 0&&L(t.sourceUrl,"sourceUrl"),!O(t.range))throw new Error("Change-tour manifest range must be an object.");for(let r of["baseRef","headRef","mergeBaseOid","headOid"])L(t.range[r],`range.${r}`);if(!O(t.summary))throw new Error("Change-tour manifest summary must be an object.");for(let r of["changedFiles","includedScenes","additions","deletions","commitCount"])re(t.summary[r],`summary.${r}`);if(me(t.summary.omittedFiles,"summary.omittedFiles"),!Array.isArray(t.commits)||!Array.isArray(t.chapters)||!Array.isArray(t.scenes))throw new Error("Change-tour manifest commits, chapters, and scenes must be arrays.");if(t.files!==void 0&&!Array.isArray(t.files))throw new Error("Change-tour manifest files must be an array.");let e=new Set;for(let[r,o]of t.scenes.entries()){if(Ze(o,r),e.has(o.id))throw new Error(`Duplicate change-tour scene id: ${o.id}`);e.add(o.id)}for(let[r,o]of t.chapters.entries()){if(!O(o))throw new Error(`chapters[${r}] must be an object.`);L(o.id,`chapters[${r}].id`),L(o.title,`chapters[${r}].title`),me(o.sceneIds,`chapters[${r}].sceneIds`);for(let s of o.sceneIds)if(!e.has(s))throw new Error(`Chapter references unknown scene id: ${s}`)}if(t.summary.includedScenes!==t.scenes.length)throw new Error("summary.includedScenes must match the number of scenes.");let n=t.files===void 0?er(t.scenes):t.files.map((r,o)=>(Qn(r,o),r));if(t.files!==void 0&&t.summary.changedFiles!==n.length)throw new Error("summary.changedFiles must match the number of files.");return{...t,files:n}}function Ze(t,e){if(!O(t)||!["text-diff","discussion","walkthrough","stacked-diff","deconstructed-diff"].includes(String(t.kind)))throw new Error(`scenes[${e}] must be a text-diff, discussion, walkthrough, stacked-diff, or deconstructed-diff scene.`);for(let n of["id","title"])L(t[n],`scenes[${e}].${n}`);if(tr(t,`scenes[${e}]`),t.kind!=="discussion"){if(t.kind==="walkthrough"){if(!Array.isArray(t.steps)||t.steps.length===0)throw new Error(`scenes[${e}].steps must be a non-empty array.`);for(let[n,r]of t.steps.entries()){let o=`scenes[${e}].steps[${n}]`;if(!O(r)||!O(r.focus)||!O(r.diff))throw new Error(`${o} must contain focus and diff objects.`);for(let s of["id","title","body"])L(r[s],`${o}.${s}`);if(r.depth!==void 0&&!["mentioned","explained","contextualized"].includes(String(r.depth)))throw new Error(`${o}.depth must be mentioned, explained, or contextualized.`);if(Je(r.focus,`${o}.focus`),Ze(r.diff,e),r.diff.kind!=="text-diff")throw new Error(`${o}.diff must be a text-diff scene.`);if(r.connection!==void 0){if(!O(r.connection))throw new Error(`${o}.connection must be an object.`);L(r.connection.id,`${o}.connection.id`),L(r.connection.label,`${o}.connection.label`),Je(r.connection.from,`${o}.connection.from`),Je(r.connection.to,`${o}.connection.to`)}}return}if(t.kind==="stacked-diff"){Jn(t,e);return}if(t.kind==="deconstructed-diff"){Zn(t,e);return}for(let n of["path","leftLabel","rightLabel","leftContent","rightContent"])L(t[n],`scenes[${e}].${n}`);t.previousPath!==void 0&&L(t.previousPath,`scenes[${e}].previousPath`),L(t.changeKind,`scenes[${e}].changeKind`),re(t.additions,`scenes[${e}].additions`),re(t.deletions,`scenes[${e}].deletions`),t.focusChangeIndex!==void 0&&re(t.focusChangeIndex,`scenes[${e}].focusChangeIndex`)}}function Jn(t,e){if(!Array.isArray(t.stack)||t.stack.length<3||t.stack.length>6)throw new Error(`scenes[${e}].stack must contain between 3 and 6 revisions.`);for(let[n,r]of t.stack.entries()){if(!O(r))throw new Error(`scenes[${e}].stack[${n}] must be an object.`);for(let o of["id","ref","oid","label"])L(r[o],`scenes[${e}].stack[${n}].${o}`)}Ht(t.files,t.stack.length,e),Bt(t.steps,t.stack.length,e,!1)}function Zn(t,e){if(t.stageLabel!=="Explanation stages")throw new Error(`scenes[${e}].stageLabel must be Explanation stages.`);if(!O(t.realRange))throw new Error(`scenes[${e}].realRange must be an object.`);for(let r of["baseRef","targetRef","baseOid","targetOid"])L(t.realRange[r],`scenes[${e}].realRange.${r}`);if(!Array.isArray(t.panels)||t.panels.length<2||t.panels.length>13)throw new Error(`scenes[${e}].panels must contain a baseline and between 1 and 12 stages.`);let n=t.panels;for(let[r,o]of n.entries()){if(!O(o))throw new Error(`scenes[${e}].panels[${r}] must be an object.`);for(let l of["id","label","role"])L(o[l],`scenes[${e}].panels[${r}].${l}`);let s=r===0?"baseline":"stage";if(o.role!==s)throw new Error(`scenes[${e}].panels[${r}].role must be ${s}.`);r>0&&L(o.stageId,`scenes[${e}].panels[${r}].stageId`)}if(Ht(t.files,n.length,e),Bt(t.steps,n.length,e,!0),Array.isArray(t.steps)&&t.steps.length!==n.length-1)throw new Error(`scenes[${e}].steps must match the number of explanation stages.`);Array.isArray(t.steps)&&t.steps.forEach((r,o)=>{let s=n[o+1];if(!O(r)||!O(s)||s.stageId!==r.id)throw new Error(`scenes[${e}].panels must align with explanation stage ids.`)})}function Ht(t,e,n){if(!Array.isArray(t)||t.length===0)throw new Error(`scenes[${n}].files must be non-empty.`);for(let[r,o]of t.entries()){if(!O(o))throw new Error(`scenes[${n}].files[${r}] must be an object.`);if(L(o.path,`scenes[${n}].files[${r}].path`),!Array.isArray(o.panels)||o.panels.length!==e)throw new Error(`scenes[${n}].files[${r}].panels must match panel count.`);for(let[s,l]of o.panels.entries()){if(!O(l))throw new Error(`scenes[${n}].files[${r}].panels[${s}] must be an object.`);for(let u of["id","label","content"])L(l[u],`scenes[${n}].files[${r}].panels[${s}].${u}`);if(l.path!==void 0&&L(l.path,`scenes[${n}].files[${r}].panels[${s}].path`),typeof l.exists!="boolean")throw new Error(`scenes[${n}].files[${r}].panels[${s}].exists must be boolean.`)}}}function Bt(t,e,n,r){if(!Array.isArray(t)||t.length===0)throw new Error(`scenes[${n}].steps must be non-empty.`);for(let[o,s]of t.entries()){if(!O(s))throw new Error(`scenes[${n}].steps[${o}] must be an object.`);for(let l of["id","title","body","file","side"])L(s[l],`scenes[${n}].steps[${o}].${l}`);if(re(s.pairIndex,`scenes[${n}].steps[${o}].pairIndex`),Number(s.pairIndex)>=e-1)throw new Error(`scenes[${n}].steps[${o}].pairIndex is outside the panels.`);if(r){if(me(s.introducedHunks,`scenes[${n}].steps[${o}].introducedHunks`),s.introducedHunks.length===0)throw new Error(`scenes[${n}].steps[${o}].introducedHunks must be non-empty.`);if(Number(s.pairIndex)!==o)throw new Error(`scenes[${n}].steps[${o}].pairIndex must match its explanation stage.`)}if(s.side!=="left"&&s.side!=="right")throw new Error(`scenes[${n}].steps[${o}].side must be left or right.`);s.startLine!==void 0&&$e(s.startLine,`scenes[${n}].steps[${o}].startLine`),s.endLine!==void 0&&$e(s.endLine,`scenes[${n}].steps[${o}].endLine`)}}function Qn(t,e){if(!O(t))throw new Error(`files[${e}] must be an object.`);if(t.kind==="text-diff"){Ze(t,e);return}if(t.kind!=="omitted")throw new Error(`files[${e}].kind must be text-diff or omitted.`);for(let n of["id","title","path","changeKind","reason"])L(t[n],`files[${e}].${n}`);t.previousPath!==void 0&&L(t.previousPath,`files[${e}].previousPath`),re(t.additions,`files[${e}].additions`),re(t.deletions,`files[${e}].deletions`)}function er(t){let e=new Map;for(let n of t){if(n.kind==="text-diff"){e.has(n.path)||e.set(n.path,n);continue}if(n.kind==="walkthrough")for(let r of n.steps)e.has(r.diff.path)||e.set(r.diff.path,r.diff)}return[...e.values()].sort((n,r)=>n.path.localeCompare(r.path))}function Je(t,e){if(!O(t))throw new Error(`${e} must be an object.`);for(let n of["id","path","revision","excerpt"])L(t[n],`${e}.${n}`);if(t.revision!=="base"&&t.revision!=="head")throw new Error(`${e}.revision must be base or head.`);if($e(t.startLine,`${e}.startLine`),$e(t.endLine,`${e}.endLine`),Number(t.endLine)<Number(t.startLine))throw new Error(`${e}.endLine must not precede startLine.`)}function tr(t,e){L(t.summary,`${e}.summary`),me(t.bullets,`${e}.bullets`),me(t.tags,`${e}.tags`),L(t.takeaway,`${e}.takeaway`)}function O(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function L(t,e){if(typeof t!="string")throw new Error(`${e} must be a string.`)}function me(t,e){if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw new Error(`${e} must be an array of strings.`)}function re(t,e){if(!Number.isInteger(t)||Number(t)<0)throw new Error(`${e} must be a non-negative integer.`)}function $e(t,e){if(!Number.isInteger(t)||Number(t)<1)throw new Error(`${e} must be a positive integer.`)}function Wt(t,e,n){let r=t.findIndex(u=>u.id===e),o=r>=0?r:0,s=t[o];if(!s||s.kind!=="walkthrough"&&s.kind!=="stacked-diff"&&s.kind!=="deconstructed-diff"||!n)return{sceneIndex:o,stepIndex:0};let l=s.steps.findIndex(u=>u.id===n);return{sceneIndex:o,stepIndex:l>=0?l:0}}function Re(t,e,n){let r=t[e.sceneIndex];if(!r)return null;if(n>0)return(r.kind==="walkthrough"||r.kind==="stacked-diff"||r.kind==="deconstructed-diff")&&e.stepIndex<r.steps.length-1?{sceneIndex:e.sceneIndex,stepIndex:e.stepIndex+1}:e.sceneIndex<t.length-1?{sceneIndex:e.sceneIndex+1,stepIndex:0}:null;if((r.kind==="walkthrough"||r.kind==="stacked-diff"||r.kind==="deconstructed-diff")&&e.stepIndex>0)return{sceneIndex:e.sceneIndex,stepIndex:e.stepIndex-1};if(e.sceneIndex===0)return null;let o=t[e.sceneIndex-1];return{sceneIndex:e.sceneIndex-1,stepIndex:o.kind==="walkthrough"||o.kind==="stacked-diff"||o.kind==="deconstructed-diff"?o.steps.length-1:0}}function Gt(t,e,n){if(!e)return null;let r=t.map((u,d)=>({file:u,fileIndex:d})).filter(({file:u})=>u.kind==="text-diff"),o=r.findIndex(({file:u})=>u.path===e),s=o+n,l=o>=0?r[s]:null;return l?{fileIndex:l.fileIndex,path:l.file.path}:null}function zt(t,e,n){let r=t[e.sceneIndex],o=Ut(r,e.sceneIndex,e.stepIndex,n);if(o)return o;for(let s=0;s<t.length;s+=1){if(s===e.sceneIndex)continue;let l=Ut(t[s],s,0,n);if(l)return l}return null}function Ut(t,e,n,r){if(!t||t.kind!=="stacked-diff"&&t.kind!=="deconstructed-diff"||!t.files.some(l=>l.path===r))return null;let s=t.steps[n]?.file===r?n:t.steps.findIndex(l=>l.file===r);return{sceneIndex:e,stepIndex:s>=0?s:Math.max(n,0)}}function qt(t,e,n){let r=t.scenes[e.sceneIndex];if(!r)return null;let o=Qe(r)?Math.min(Math.max(e.stepIndex,0),r.steps.length-1):0,s={sceneIndex:e.sceneIndex,stepIndex:o},l=Qe(r)?r.steps[o]:void 0,u=[],d=!l||o===0,m=!!(l&&o>0&&n.entry==="playback-start");if(d){let v=t.chapters.find(k=>k.sceneIds.includes(r.id));v&&u.push({source:{field:"chapter"},text:v.title})}(d||m)&&u.push({source:{field:"scene-title"},text:r.title}),d&&(u.push({source:{field:"summary"},text:r.summary}),r.bullets.forEach((v,k)=>{u.push({source:{field:"bullet",itemIndex:k},text:v})})),l&&(u.push({source:{field:"step-title"},text:l.title}),u.push({source:{field:"step-body"},text:l.body}),"connection"in l&&l.connection?.label&&u.push({source:{field:"connection"},text:l.connection.label})),(!l||Qe(r)&&o===r.steps.length-1)&&u.push({source:{field:"takeaway"},text:r.takeaway});let p=`${r.id}:${l?.id||"scene"}`,a=n.segmentLimit??240,I=u.flatMap(v=>ir(p,v,a));return{id:p,position:s,segments:I}}function nr(t,e=240){if(!Number.isInteger(e)||e<40)throw new Error("Narration segment limit must be an integer of at least 40 characters.");return or(t).flatMap(r=>sr(t,r.startOffset,r.endOffset,e))}function rr(t){return t.replace(/https?:\/\/\S+/giu," ").replace(/\b(?=[0-9a-f]{7,40}\b)(?=[0-9a-f]*\d)[0-9a-f]+\b/giu," ").replace(/[`*_~]/gu,"").replace(/([\p{Ll}\d])(\p{Lu})/gu,"$1 $2").replace(/([\p{Lu}])(\p{Lu}\p{Ll})/gu,"$1 $2").replace(/\s+/gu," ").trim()}function ir(t,e,n){let r=e.source.itemIndex===void 0?e.source.field:`${e.source.field}-${e.source.itemIndex}`;return nr(e.text,n).map((o,s)=>({id:`${t}:${r}:${s}`,text:o.text,speechText:rr(o.text),source:e.source,startOffset:o.startOffset,endOffset:o.endOffset})).filter(o=>o.speechText.length>0)}function or(t){let e=[],n=0;for(let r=0;r<t.length;r+=1){if(!".!?".includes(t[r]))continue;let o=r+1;for(;o<t.length&&`"'\u201D\u2019)]}`.includes(t[o]);)o+=1;o<t.length&&!/\s/u.test(t[o])||(Ae(t,e,n,o),n=o)}return Ae(t,e,n,t.length),e}function sr(t,e,n,r){let o=[],s=e;for(;n-s>r;){let l=s+r,u=s+Math.floor(r*.55),d=Vt(t,u,l,/[;,:—–-]/u);d<=s&&(d=Vt(t,u,l,/\s/u)),d<=s&&(d=l),Ae(t,o,s,d),s=d}return Ae(t,o,s,n),o}function Vt(t,e,n,r){for(let o=n;o>=e;o-=1)if(r.test(t[o]))return o+1;return-1}function Ae(t,e,n,r){let o=n,s=r;for(;o<s&&/\s/u.test(t[o]);)o+=1;for(;s>o&&/\s/u.test(t[s-1]);)s-=1;o<s&&e.push({text:t.slice(o,s),startOffset:o,endOffset:s})}function Qe(t){return t.kind==="walkthrough"||t.kind==="stacked-diff"||t.kind==="deconstructed-diff"}var Fe=class{constructor(e,n){this.engine=e;this.callbacks=n;this.generation=0;this.continuous=!0;this.currentState={kind:"idle"}}get state(){return this.currentState}get engaged(){return this.currentState.kind==="playing"||this.currentState.kind==="paused"}start(e,n=!0){if(this.resetEngine(),this.continuous=n,e.segments.length===0){this.finishUnit(e);return}this.callbacks.claimAudio(),this.setState({kind:"playing",unit:e,segmentIndex:0}),this.speakCurrent()}togglePause(){if(this.currentState.kind==="playing"){this.engine.pause();let n={kind:"paused",unit:this.currentState.unit,segmentIndex:this.currentState.segmentIndex,pendingStart:!1};this.setState(n),this.callbacks.onSegmentChange(n.unit.segments[n.segmentIndex]||null,!0);return}if(this.currentState.kind!=="paused")return;this.callbacks.claimAudio();let e=this.currentState;this.setState({kind:"playing",unit:e.unit,segmentIndex:e.segmentIndex}),e.pendingStart?this.speakCurrent():(this.engine.resume(),this.callbacks.onSegmentChange(e.unit.segments[e.segmentIndex]||null,!1))}stop(){this.resetEngine(),this.setState({kind:"idle"}),this.callbacks.onSegmentChange(null,!1)}pauseForExternalOwner(){this.currentState.kind==="playing"&&this.togglePause()}canSkipSegment(e){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return!1;let n=this.currentState.segmentIndex+e;return n>=0&&n<this.currentState.unit.segments.length?!0:this.callbacks.canNavigateUnit(this.currentState.unit,e)}skipSegment(e){if(!this.canSkipSegment(e))return!1;let n=this.currentState,r=n.kind==="paused",o=n.unit,s=n.segmentIndex+e;if(s<0||s>=o.segments.length){let l=this.callbacks.navigateUnit(o,e);if(!l||l.segments.length===0)return!1;o=l,s=e<0?o.segments.length-1:0}return this.resetEngine(),r?(this.setState({kind:"paused",unit:o,segmentIndex:s,pendingStart:!0}),this.callbacks.onSegmentChange(o.segments[s]||null,!0)):(this.setState({kind:"playing",unit:o,segmentIndex:s}),this.speakCurrent()),!0}followLinearNavigation(e){this.currentState.kind==="playing"?this.start(e,this.continuous):this.currentState.kind==="paused"&&this.preparePaused(e)}followDirectNavigation(e){this.engaged&&this.preparePaused(e)}interruptForExploration(){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return;let e=this.currentState;this.resetEngine(),this.setState({kind:"paused",unit:e.unit,segmentIndex:e.segmentIndex,pendingStart:!0}),this.callbacks.onSegmentChange(e.unit.segments[e.segmentIndex]||null,!0)}dispose(){this.stop()}preparePaused(e){this.resetEngine(),this.setState({kind:"paused",unit:e,segmentIndex:0,pendingStart:!0}),this.callbacks.onSegmentChange(e.segments[0]||null,!0)}speakCurrent(){if(this.currentState.kind!=="playing")return;let e=this.generation,n=this.currentState.unit.segments[this.currentState.segmentIndex];if(!n){this.finishUnit(this.currentState.unit);return}this.callbacks.onSegmentChange(n,!1),this.engine.speak(n,{onEnd:()=>{if(e!==this.generation||this.currentState.kind!=="playing")return;let r=this.currentState.segmentIndex+1;r<this.currentState.unit.segments.length?(this.setState({kind:"playing",unit:this.currentState.unit,segmentIndex:r}),this.speakCurrent()):this.finishUnit(this.currentState.unit)},onError:r=>{e===this.generation&&(this.setState({kind:"error",message:r}),this.callbacks.onSegmentChange(null,!1))}})}finishUnit(e){if(this.continuous){let n=this.callbacks.navigateUnit(e,1);if(n){if(this.generation+=1,n.segments.length===0){this.finishUnit(n);return}this.setState({kind:"playing",unit:n,segmentIndex:0}),this.speakCurrent();return}}this.setState({kind:"completed"}),this.callbacks.onSegmentChange(null,!1)}resetEngine(){this.generation+=1,this.engine.cancel()}setState(e){this.currentState=e,this.callbacks.onStateChange(e)}};function Kt(t,e,n="all",r=300){let o=e.trim().toLocaleLowerCase();if(!o||r<=0)return[];let s=[];if(n!=="code"){let l=new Map;t.chapters.forEach(u=>u.sceneIds.forEach(d=>l.set(d,u.title))),t.scenes.forEach((u,d)=>{let m=[l.get(u.id),u.title,u.summary,...u.bullets,...u.tags,u.takeaway],p=jt(m,o);p&&s.push({kind:"narrative",sceneIndex:d,label:u.title,preview:p}),cr(u)&&u.steps.forEach((a,I)=>{let v=jt([a.title,a.body,"connection"in a?a.connection?.label:void 0],o);v&&s.push({kind:"narrative",sceneIndex:d,stepIndex:I,label:`${u.title} \xB7 ${a.title}`,preview:v})})})}if(n!=="narrative"&&s.length<r)for(let l=0;l<t.files.length;l+=1){let u=t.files[l];if(u.kind==="text-diff"){for(let[d,m]of[[0,u.leftContent],[1,u.rightContent]])for(let p of ar(m,o))if(s.push({kind:"code",fileIndex:l,sideIndex:d,label:`${u.path} \xB7 ${d===0?"base":"head"}`,...p}),s.length>=r)return s}}return s.slice(0,r)}function jt(t,e){return t.find(n=>n?.toLocaleLowerCase().includes(e))}function ar(t,e){let n=[];return t.replace(/\r\n/g,`
148
+ `}}function Ot(t){if(!O(t)||t.version!==1)throw new Error("Unsupported or missing change-tour manifest version.");if(L(t.title,"title"),L(t.generatedAt,"generatedAt"),t.windowTitle!==void 0&&L(t.windowTitle,"windowTitle"),t.sourceUrl!==void 0&&L(t.sourceUrl,"sourceUrl"),!O(t.range))throw new Error("Change-tour manifest range must be an object.");for(let r of["baseRef","headRef","mergeBaseOid","headOid"])L(t.range[r],`range.${r}`);if(!O(t.summary))throw new Error("Change-tour manifest summary must be an object.");for(let r of["changedFiles","includedScenes","additions","deletions","commitCount"])re(t.summary[r],`summary.${r}`);if(me(t.summary.omittedFiles,"summary.omittedFiles"),!Array.isArray(t.commits)||!Array.isArray(t.chapters)||!Array.isArray(t.scenes))throw new Error("Change-tour manifest commits, chapters, and scenes must be arrays.");if(t.files!==void 0&&!Array.isArray(t.files))throw new Error("Change-tour manifest files must be an array.");let e=new Set;for(let[r,o]of t.scenes.entries()){if(Ze(o,r),e.has(o.id))throw new Error(`Duplicate change-tour scene id: ${o.id}`);e.add(o.id)}for(let[r,o]of t.chapters.entries()){if(!O(o))throw new Error(`chapters[${r}] must be an object.`);L(o.id,`chapters[${r}].id`),L(o.title,`chapters[${r}].title`),me(o.sceneIds,`chapters[${r}].sceneIds`);for(let s of o.sceneIds)if(!e.has(s))throw new Error(`Chapter references unknown scene id: ${s}`)}if(t.summary.includedScenes!==t.scenes.length)throw new Error("summary.includedScenes must match the number of scenes.");let n=t.files===void 0?er(t.scenes):t.files.map((r,o)=>(Qn(r,o),r));if(t.files!==void 0&&t.summary.changedFiles!==n.length)throw new Error("summary.changedFiles must match the number of files.");return{...t,files:n}}function Ze(t,e){if(!O(t)||!["text-diff","discussion","walkthrough","stacked-diff","deconstructed-diff"].includes(String(t.kind)))throw new Error(`scenes[${e}] must be a text-diff, discussion, walkthrough, stacked-diff, or deconstructed-diff scene.`);for(let n of["id","title"])L(t[n],`scenes[${e}].${n}`);if(tr(t,`scenes[${e}]`),t.kind!=="discussion"){if(t.kind==="walkthrough"){if(!Array.isArray(t.steps)||t.steps.length===0)throw new Error(`scenes[${e}].steps must be a non-empty array.`);for(let[n,r]of t.steps.entries()){let o=`scenes[${e}].steps[${n}]`;if(!O(r)||!O(r.focus)||!O(r.diff))throw new Error(`${o} must contain focus and diff objects.`);for(let s of["id","title","body"])L(r[s],`${o}.${s}`);if(r.depth!==void 0&&!["mentioned","explained","contextualized"].includes(String(r.depth)))throw new Error(`${o}.depth must be mentioned, explained, or contextualized.`);if(Je(r.focus,`${o}.focus`),Ze(r.diff,e),r.diff.kind!=="text-diff")throw new Error(`${o}.diff must be a text-diff scene.`);if(r.connection!==void 0){if(!O(r.connection))throw new Error(`${o}.connection must be an object.`);L(r.connection.id,`${o}.connection.id`),L(r.connection.label,`${o}.connection.label`),Je(r.connection.from,`${o}.connection.from`),Je(r.connection.to,`${o}.connection.to`)}}return}if(t.kind==="stacked-diff"){Jn(t,e);return}if(t.kind==="deconstructed-diff"){Zn(t,e);return}for(let n of["path","leftLabel","rightLabel","leftContent","rightContent"])L(t[n],`scenes[${e}].${n}`);t.previousPath!==void 0&&L(t.previousPath,`scenes[${e}].previousPath`),L(t.changeKind,`scenes[${e}].changeKind`),re(t.additions,`scenes[${e}].additions`),re(t.deletions,`scenes[${e}].deletions`),t.focusChangeIndex!==void 0&&re(t.focusChangeIndex,`scenes[${e}].focusChangeIndex`)}}function Jn(t,e){if(!Array.isArray(t.stack)||t.stack.length<3||t.stack.length>6)throw new Error(`scenes[${e}].stack must contain between 3 and 6 revisions.`);for(let[n,r]of t.stack.entries()){if(!O(r))throw new Error(`scenes[${e}].stack[${n}] must be an object.`);for(let o of["id","ref","oid","label"])L(r[o],`scenes[${e}].stack[${n}].${o}`)}Ht(t.files,t.stack.length,e),Bt(t.steps,t.stack.length,e,!1)}function Zn(t,e){if(t.stageLabel!=="Explanation stages")throw new Error(`scenes[${e}].stageLabel must be Explanation stages.`);if(!O(t.realRange))throw new Error(`scenes[${e}].realRange must be an object.`);for(let r of["baseRef","targetRef","baseOid","targetOid"])L(t.realRange[r],`scenes[${e}].realRange.${r}`);if(!Array.isArray(t.panels)||t.panels.length<2||t.panels.length>13)throw new Error(`scenes[${e}].panels must contain a baseline and between 1 and 12 stages.`);let n=t.panels;for(let[r,o]of n.entries()){if(!O(o))throw new Error(`scenes[${e}].panels[${r}] must be an object.`);for(let l of["id","label","role"])L(o[l],`scenes[${e}].panels[${r}].${l}`);let s=r===0?"baseline":"stage";if(o.role!==s)throw new Error(`scenes[${e}].panels[${r}].role must be ${s}.`);r>0&&L(o.stageId,`scenes[${e}].panels[${r}].stageId`)}if(Ht(t.files,n.length,e),Bt(t.steps,n.length,e,!0),Array.isArray(t.steps)&&t.steps.length!==n.length-1)throw new Error(`scenes[${e}].steps must match the number of explanation stages.`);Array.isArray(t.steps)&&t.steps.forEach((r,o)=>{let s=n[o+1];if(!O(r)||!O(s)||s.stageId!==r.id)throw new Error(`scenes[${e}].panels must align with explanation stage ids.`)})}function Ht(t,e,n){if(!Array.isArray(t)||t.length===0)throw new Error(`scenes[${n}].files must be non-empty.`);for(let[r,o]of t.entries()){if(!O(o))throw new Error(`scenes[${n}].files[${r}] must be an object.`);if(L(o.path,`scenes[${n}].files[${r}].path`),!Array.isArray(o.panels)||o.panels.length!==e)throw new Error(`scenes[${n}].files[${r}].panels must match panel count.`);for(let[s,l]of o.panels.entries()){if(!O(l))throw new Error(`scenes[${n}].files[${r}].panels[${s}] must be an object.`);for(let u of["id","label","content"])L(l[u],`scenes[${n}].files[${r}].panels[${s}].${u}`);if(l.path!==void 0&&L(l.path,`scenes[${n}].files[${r}].panels[${s}].path`),typeof l.exists!="boolean")throw new Error(`scenes[${n}].files[${r}].panels[${s}].exists must be boolean.`)}}}function Bt(t,e,n,r){if(!Array.isArray(t)||t.length===0)throw new Error(`scenes[${n}].steps must be non-empty.`);for(let[o,s]of t.entries()){if(!O(s))throw new Error(`scenes[${n}].steps[${o}] must be an object.`);for(let l of["id","title","body","file","side"])L(s[l],`scenes[${n}].steps[${o}].${l}`);if(re(s.pairIndex,`scenes[${n}].steps[${o}].pairIndex`),Number(s.pairIndex)>=e-1)throw new Error(`scenes[${n}].steps[${o}].pairIndex is outside the panels.`);if(r){if(me(s.introducedHunks,`scenes[${n}].steps[${o}].introducedHunks`),s.introducedHunks.length===0)throw new Error(`scenes[${n}].steps[${o}].introducedHunks must be non-empty.`);if(Number(s.pairIndex)!==o)throw new Error(`scenes[${n}].steps[${o}].pairIndex must match its explanation stage.`)}if(s.side!=="left"&&s.side!=="right")throw new Error(`scenes[${n}].steps[${o}].side must be left or right.`);s.startLine!==void 0&&$e(s.startLine,`scenes[${n}].steps[${o}].startLine`),s.endLine!==void 0&&$e(s.endLine,`scenes[${n}].steps[${o}].endLine`)}}function Qn(t,e){if(!O(t))throw new Error(`files[${e}] must be an object.`);if(t.kind==="text-diff"){Ze(t,e);return}if(t.kind!=="omitted")throw new Error(`files[${e}].kind must be text-diff or omitted.`);for(let n of["id","title","path","changeKind","reason"])L(t[n],`files[${e}].${n}`);t.previousPath!==void 0&&L(t.previousPath,`files[${e}].previousPath`),re(t.additions,`files[${e}].additions`),re(t.deletions,`files[${e}].deletions`)}function er(t){let e=new Map;for(let n of t){if(n.kind==="text-diff"){e.has(n.path)||e.set(n.path,n);continue}if(n.kind==="walkthrough")for(let r of n.steps)e.has(r.diff.path)||e.set(r.diff.path,r.diff)}return[...e.values()].sort((n,r)=>n.path.localeCompare(r.path))}function Je(t,e){if(!O(t))throw new Error(`${e} must be an object.`);for(let n of["id","path","revision","excerpt"])L(t[n],`${e}.${n}`);if(t.revision!=="base"&&t.revision!=="head")throw new Error(`${e}.revision must be base or head.`);if($e(t.startLine,`${e}.startLine`),$e(t.endLine,`${e}.endLine`),Number(t.endLine)<Number(t.startLine))throw new Error(`${e}.endLine must not precede startLine.`)}function tr(t,e){L(t.summary,`${e}.summary`),me(t.bullets,`${e}.bullets`),me(t.tags,`${e}.tags`),L(t.takeaway,`${e}.takeaway`)}function O(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function L(t,e){if(typeof t!="string")throw new Error(`${e} must be a string.`)}function me(t,e){if(!Array.isArray(t)||t.some(n=>typeof n!="string"))throw new Error(`${e} must be an array of strings.`)}function re(t,e){if(!Number.isInteger(t)||Number(t)<0)throw new Error(`${e} must be a non-negative integer.`)}function $e(t,e){if(!Number.isInteger(t)||Number(t)<1)throw new Error(`${e} must be a positive integer.`)}function Wt(t,e,n){let r=t.findIndex(u=>u.id===e),o=r>=0?r:0,s=t[o];if(!s||s.kind!=="walkthrough"&&s.kind!=="stacked-diff"&&s.kind!=="deconstructed-diff"||!n)return{sceneIndex:o,stepIndex:0};let l=s.steps.findIndex(u=>u.id===n);return{sceneIndex:o,stepIndex:l>=0?l:0}}function Re(t,e,n){let r=t[e.sceneIndex];if(!r)return null;if(n>0)return(r.kind==="walkthrough"||r.kind==="stacked-diff"||r.kind==="deconstructed-diff")&&e.stepIndex<r.steps.length-1?{sceneIndex:e.sceneIndex,stepIndex:e.stepIndex+1}:e.sceneIndex<t.length-1?{sceneIndex:e.sceneIndex+1,stepIndex:0}:null;if((r.kind==="walkthrough"||r.kind==="stacked-diff"||r.kind==="deconstructed-diff")&&e.stepIndex>0)return{sceneIndex:e.sceneIndex,stepIndex:e.stepIndex-1};if(e.sceneIndex===0)return null;let o=t[e.sceneIndex-1];return{sceneIndex:e.sceneIndex-1,stepIndex:o.kind==="walkthrough"||o.kind==="stacked-diff"||o.kind==="deconstructed-diff"?o.steps.length-1:0}}function Gt(t,e,n){if(!e)return null;let r=t.map((u,d)=>({file:u,fileIndex:d})).filter(({file:u})=>u.kind==="text-diff"),o=r.findIndex(({file:u})=>u.path===e),s=o+n,l=o>=0?r[s]:null;return l?{fileIndex:l.fileIndex,path:l.file.path}:null}function zt(t,e,n){let r=t[e.sceneIndex],o=Ut(r,e.sceneIndex,e.stepIndex,n);if(o)return o;for(let s=0;s<t.length;s+=1){if(s===e.sceneIndex)continue;let l=Ut(t[s],s,0,n);if(l)return l}return null}function Ut(t,e,n,r){if(!t||t.kind!=="stacked-diff"&&t.kind!=="deconstructed-diff"||!t.files.some(l=>l.path===r))return null;let s=t.steps[n]?.file===r?n:t.steps.findIndex(l=>l.file===r);return{sceneIndex:e,stepIndex:s>=0?s:Math.max(n,0)}}function jt(t,e,n){let r=t.scenes[e.sceneIndex];if(!r)return null;let o=Qe(r)?Math.min(Math.max(e.stepIndex,0),r.steps.length-1):0,s={sceneIndex:e.sceneIndex,stepIndex:o},l=Qe(r)?r.steps[o]:void 0,u=[],d=!l||o===0,m=!!(l&&o>0&&n.entry==="playback-start");if(d){let v=t.chapters.find(k=>k.sceneIds.includes(r.id));v&&u.push({source:{field:"chapter"},text:v.title})}(d||m)&&u.push({source:{field:"scene-title"},text:r.title}),d&&(u.push({source:{field:"summary"},text:r.summary}),r.bullets.forEach((v,k)=>{u.push({source:{field:"bullet",itemIndex:k},text:v})})),l&&(u.push({source:{field:"step-title"},text:l.title}),u.push({source:{field:"step-body"},text:l.body}),"connection"in l&&l.connection?.label&&u.push({source:{field:"connection"},text:l.connection.label})),(!l||Qe(r)&&o===r.steps.length-1)&&u.push({source:{field:"takeaway"},text:r.takeaway});let p=`${r.id}:${l?.id||"scene"}`,a=n.segmentLimit??240,I=u.flatMap(v=>ir(p,v,a));return{id:p,position:s,segments:I}}function nr(t,e=240){if(!Number.isInteger(e)||e<40)throw new Error("Narration segment limit must be an integer of at least 40 characters.");return or(t).flatMap(r=>sr(t,r.startOffset,r.endOffset,e))}function rr(t){return t.replace(/https?:\/\/\S+/giu," ").replace(/\b(?=[0-9a-f]{7,40}\b)(?=[0-9a-f]*\d)[0-9a-f]+\b/giu," ").replace(/[`*_~]/gu,"").replace(/([\p{Ll}\d])(\p{Lu})/gu,"$1 $2").replace(/([\p{Lu}])(\p{Lu}\p{Ll})/gu,"$1 $2").replace(/\s+/gu," ").trim()}function ir(t,e,n){let r=e.source.itemIndex===void 0?e.source.field:`${e.source.field}-${e.source.itemIndex}`;return nr(e.text,n).map((o,s)=>({id:`${t}:${r}:${s}`,text:o.text,speechText:rr(o.text),source:e.source,startOffset:o.startOffset,endOffset:o.endOffset})).filter(o=>o.speechText.length>0)}function or(t){let e=[],n=0;for(let r=0;r<t.length;r+=1){if(!".!?".includes(t[r]))continue;let o=r+1;for(;o<t.length&&`"'\u201D\u2019)]}`.includes(t[o]);)o+=1;o<t.length&&!/\s/u.test(t[o])||(Ae(t,e,n,o),n=o)}return Ae(t,e,n,t.length),e}function sr(t,e,n,r){let o=[],s=e;for(;n-s>r;){let l=s+r,u=s+Math.floor(r*.55),d=Vt(t,u,l,/[;,:—–-]/u);d<=s&&(d=Vt(t,u,l,/\s/u)),d<=s&&(d=l),Ae(t,o,s,d),s=d}return Ae(t,o,s,n),o}function Vt(t,e,n,r){for(let o=n;o>=e;o-=1)if(r.test(t[o]))return o+1;return-1}function Ae(t,e,n,r){let o=n,s=r;for(;o<s&&/\s/u.test(t[o]);)o+=1;for(;s>o&&/\s/u.test(t[s-1]);)s-=1;o<s&&e.push({text:t.slice(o,s),startOffset:o,endOffset:s})}function Qe(t){return t.kind==="walkthrough"||t.kind==="stacked-diff"||t.kind==="deconstructed-diff"}var Fe=class{constructor(e,n){this.engine=e;this.callbacks=n;this.generation=0;this.continuous=!0;this.currentState={kind:"idle"}}get state(){return this.currentState}get engaged(){return this.currentState.kind==="playing"||this.currentState.kind==="paused"}start(e,n=!0){if(this.resetEngine(),this.continuous=n,e.segments.length===0){this.finishUnit(e);return}this.callbacks.claimAudio(),this.setState({kind:"playing",unit:e,segmentIndex:0}),this.speakCurrent()}togglePause(){if(this.currentState.kind==="playing"){this.engine.pause();let n={kind:"paused",unit:this.currentState.unit,segmentIndex:this.currentState.segmentIndex,pendingStart:!1};this.setState(n),this.callbacks.onSegmentChange(n.unit.segments[n.segmentIndex]||null,!0);return}if(this.currentState.kind!=="paused")return;this.callbacks.claimAudio();let e=this.currentState;this.setState({kind:"playing",unit:e.unit,segmentIndex:e.segmentIndex}),e.pendingStart?this.speakCurrent():(this.engine.resume(),this.callbacks.onSegmentChange(e.unit.segments[e.segmentIndex]||null,!1))}stop(){this.resetEngine(),this.setState({kind:"idle"}),this.callbacks.onSegmentChange(null,!1)}pauseForExternalOwner(){this.currentState.kind==="playing"&&this.togglePause()}canSkipSegment(e){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return!1;let n=this.currentState.segmentIndex+e;return n>=0&&n<this.currentState.unit.segments.length?!0:this.callbacks.canNavigateUnit(this.currentState.unit,e)}skipSegment(e){if(!this.canSkipSegment(e))return!1;let n=this.currentState,r=n.kind==="paused",o=n.unit,s=n.segmentIndex+e;if(s<0||s>=o.segments.length){let l=this.callbacks.navigateUnit(o,e);if(!l||l.segments.length===0)return!1;o=l,s=e<0?o.segments.length-1:0}return this.resetEngine(),r?(this.setState({kind:"paused",unit:o,segmentIndex:s,pendingStart:!0}),this.callbacks.onSegmentChange(o.segments[s]||null,!0)):(this.setState({kind:"playing",unit:o,segmentIndex:s}),this.speakCurrent()),!0}followLinearNavigation(e){this.currentState.kind==="playing"?this.start(e,this.continuous):this.currentState.kind==="paused"&&this.preparePaused(e)}followDirectNavigation(e){this.engaged&&this.preparePaused(e)}interruptForExploration(){if(this.currentState.kind!=="playing"&&this.currentState.kind!=="paused")return;let e=this.currentState;this.resetEngine(),this.setState({kind:"paused",unit:e.unit,segmentIndex:e.segmentIndex,pendingStart:!0}),this.callbacks.onSegmentChange(e.unit.segments[e.segmentIndex]||null,!0)}dispose(){this.stop()}preparePaused(e){this.resetEngine(),this.setState({kind:"paused",unit:e,segmentIndex:0,pendingStart:!0}),this.callbacks.onSegmentChange(e.segments[0]||null,!0)}speakCurrent(){if(this.currentState.kind!=="playing")return;let e=this.generation,n=this.currentState.unit.segments[this.currentState.segmentIndex];if(!n){this.finishUnit(this.currentState.unit);return}this.callbacks.onSegmentChange(n,!1),this.engine.speak(n,{onEnd:()=>{if(e!==this.generation||this.currentState.kind!=="playing")return;let r=this.currentState.segmentIndex+1;r<this.currentState.unit.segments.length?(this.setState({kind:"playing",unit:this.currentState.unit,segmentIndex:r}),this.speakCurrent()):this.finishUnit(this.currentState.unit)},onError:r=>{e===this.generation&&(this.setState({kind:"error",message:r}),this.callbacks.onSegmentChange(null,!1))}})}finishUnit(e){if(this.continuous){let n=this.callbacks.navigateUnit(e,1);if(n){if(this.generation+=1,n.segments.length===0){this.finishUnit(n);return}this.setState({kind:"playing",unit:n,segmentIndex:0}),this.speakCurrent();return}}this.setState({kind:"completed"}),this.callbacks.onSegmentChange(null,!1)}resetEngine(){this.generation+=1,this.engine.cancel()}setState(e){this.currentState=e,this.callbacks.onStateChange(e)}};function Kt(t,e,n="all",r=300){let o=e.trim().toLocaleLowerCase();if(!o||r<=0)return[];let s=[];if(n!=="code"){let l=new Map;t.chapters.forEach(u=>u.sceneIds.forEach(d=>l.set(d,u.title))),t.scenes.forEach((u,d)=>{let m=[l.get(u.id),u.title,u.summary,...u.bullets,...u.tags,u.takeaway],p=qt(m,o);p&&s.push({kind:"narrative",sceneIndex:d,label:u.title,preview:p}),cr(u)&&u.steps.forEach((a,I)=>{let v=qt([a.title,a.body,"connection"in a?a.connection?.label:void 0],o);v&&s.push({kind:"narrative",sceneIndex:d,stepIndex:I,label:`${u.title} \xB7 ${a.title}`,preview:v})})})}if(n!=="narrative"&&s.length<r)for(let l=0;l<t.files.length;l+=1){let u=t.files[l];if(u.kind==="text-diff"){for(let[d,m]of[[0,u.leftContent],[1,u.rightContent]])for(let p of ar(m,o))if(s.push({kind:"code",fileIndex:l,sideIndex:d,label:`${u.path} \xB7 ${d===0?"base":"head"}`,...p}),s.length>=r)return s}}return s.slice(0,r)}function qt(t,e){return t.find(n=>n?.toLocaleLowerCase().includes(e))}function ar(t,e){let n=[];return t.replace(/\r\n/g,`
149
149
  `).split(`
150
- `).forEach((r,o)=>{let s=r.toLocaleLowerCase(),l=0;for(;l<=s.length-e.length;){let u=s.indexOf(e,l);if(u<0)break;n.push({lineNumber:o+1,startColumn:u+1,endColumn:u+e.length+1,preview:r}),l=u+Math.max(e.length,1)}}),n}function cr(t){return t.kind==="walkthrough"||t.kind==="stacked-diff"||t.kind==="deconstructed-diff"}function Xt(t,e){let n=t?.blocks[0],r=e==="left"?t?.leftLines:t?.rightLines;if(!n||!r?.length)return;let o=e==="left"?n.leftStart:n.rightStart,s=e==="left"?n.leftEnd:n.rightEnd,l=r.slice(o,s),u=l[0]?.lineNumber??r[Math.min(o,r.length-1)]?.lineNumber;if(Number.isInteger(u))return{startLine:u,endLine:l.at(-1)?.lineNumber??u}}function Yt(t,e,n,r){let o=[];return t.scenes.forEach((s,l)=>{s.kind==="walkthrough"&&s.steps.forEach((u,d)=>{u.diff.path===e&&o.push({side:u.focus.revision==="base"?"left":"right",startLine:u.focus.startLine,endLine:u.focus.endLine,label:`${s.title} \xB7 ${u.title}: ${u.body}`,active:l===n&&d===r,jumpTarget:{sceneIndex:l,stepIndex:d}})})}),o}function Jt(t,e,n,r,o){let s=[];return t.scenes.forEach((l,u)=>{l.kind==="stacked-diff"&&l.steps.forEach((d,m)=>{if(d.file!==e)return;let p=d.startLine===void 0?o?.(d.pairIndex,d.side):{startLine:d.startLine,endLine:d.endLine??d.startLine};if(!p)return;let a=d.pairIndex+(d.side==="right"?1:0);s.push({pairIndex:d.pairIndex,panelIndex:a,side:d.side,startLine:p.startLine,endLine:p.endLine,label:`${l.title} \xB7 ${d.title}: ${d.body}`,active:u===n&&m===r,jumpTarget:{sceneIndex:u,stepIndex:m}})})}),s}function lr(t,e=120){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function Zt(t,e="Bygone"){let n=t?.windowTitle?.trim()||t?.title?.trim();return n?lr(n):`${e} Tour`}(function(){let e="bygone.tourSidebarWidth",o="bygone.tourNarrativeHeight",u="bygone.tourNarrationVoice",d="bygone.tourNarrationRate",m=new Set([.75,1,1.25,1.5]),p="speechSynthesis"in window&&"SpeechSynthesisUtterance"in window,a={mode:"empty",left:null,right:null,comparisonId:0,tour:null,activeSceneIndex:-1,activeStepIndex:0,activeTourFilePath:null,tourFocusFilePath:null,tourSidebarWidth:nn(),tourSidebarHidden:!1,tourNarrativeHeight:on(),narrationVoiceURI:window.localStorage.getItem(u)||"",narrationRate:w(),narrationVoices:[],renderedNarrationUnit:null},I=new Fe(C(),{claimAudio:pe,onStateChange:ie,onSegmentChange:Qt,canNavigateUnit:U,navigateUnit:z});window.__BYGONE_HOST__={environment:"web",editorWorkerUrl:"/media/editor.worker.js",postMessage(i){k(i)}},window.addEventListener("DOMContentLoaded",()=>{E(),X("Browser host ready.")});function v(i){window.dispatchEvent(new window.CustomEvent("bygone:host-message",{detail:i}))}async function k(i){if(!(!i||typeof i!="object")){if(i.type==="ready"){let c=new URLSearchParams(window.location.search),g=c.get("manifest");g?sn(g):c.get("demo")==="1"&&gt();return}if(i.type==="navigateFile"&&a.mode==="tour"){ln(i.direction==="previous"?-1:1);return}if(i.type==="navigateTourStep"&&a.mode==="tour"){let c=i.sceneIndex,g=i.stepIndex;Number.isInteger(c)&&Number.isInteger(g)&&oe(c,g);return}i.type==="recomputeDiff"&&a.mode==="diff"&&a.left&&a.right&&(a.left.content=i.leftContent,a.right.content=i.rightContent,v({type:"showDiff",file1:a.left.name,file2:a.right.name,comparisonId:`web-${a.comparisonId}`,leftContent:a.left.content,rightContent:a.right.content,diffModel:ne(a.left.content,a.right.content),history:null}))}}function E(){let i=document.getElementById("web-compare-test"),c=document.getElementById("web-open-diff"),g=document.getElementById("web-open-diff3"),h=document.getElementById("web-diff-input"),f=document.getElementById("web-diff3-input"),x=document.getElementById("tour-previous"),y=document.getElementById("tour-next"),T=document.getElementById("tour-return-focus"),N=document.getElementById("tour-search-input"),H=document.getElementById("tour-search-scope"),B=document.getElementById("tour-listen"),V=document.getElementById("tour-stop"),q=document.getElementById("tour-narration-skip-back"),P=document.getElementById("tour-narration-skip-ahead"),_=document.getElementById("tour-narration-voice"),K=document.getElementById("tour-narration-rate");tn(),rn(),S(),i?.addEventListener("click",()=>{gt()}),c?.addEventListener("click",()=>{h.value="",h.click()}),g?.addEventListener("click",()=>{f.value="",f.click()}),h?.addEventListener("change",async()=>{let b=Array.from(h.files||[]);if(b.length!==2){X("Select exactly 2 files for a diff.");return}await bn(b)}),f?.addEventListener("change",async()=>{let b=Array.from(f.files||[]);if(b.length<1){X("Select one or more files.");return}await yn(b)}),x?.addEventListener("click",()=>Ie(-1)),y?.addEventListener("click",()=>Ie(1)),T?.addEventListener("click",un),N?.addEventListener("input",Me),H?.addEventListener("change",Me),B?.addEventListener("click",M),V?.addEventListener("click",()=>I.stop()),q?.addEventListener("click",()=>I.skipSegment(-1)),P?.addEventListener("click",()=>I.skipSegment(1)),_?.addEventListener("change",()=>{a.narrationVoiceURI=_.value,window.localStorage.setItem(u,a.narrationVoiceURI)}),K&&(K.value=String(a.narrationRate),K.addEventListener("change",()=>{let b=Number(K.value);a.narrationRate=m.has(b)?b:1,K.value=String(a.narrationRate),window.localStorage.setItem(d,String(a.narrationRate))})),document.getElementById("tour-search-results")?.addEventListener("click",b=>{let G=b.target instanceof Element?b.target.closest("[data-tour-search-result]"):null;G&&en(Number(G.getAttribute("data-tour-search-result")))}),window.addEventListener("keydown",b=>{if(a.mode==="tour"&&(b.metaKey||b.ctrlKey)&&b.shiftKey&&b.key.toLocaleLowerCase()==="f"){b.preventDefault(),b.stopImmediatePropagation(),a.tourSidebarHidden&&De(!1),N?.focus(),N?.select();return}a.mode!=="tour"||b.metaKey||b.ctrlKey||b.altKey||mn(b.target)||(b.key==="PageUp"||b.key==="ArrowLeft"?(b.preventDefault(),Ie(-1)):(b.key==="PageDown"||b.key==="ArrowRight")&&(b.preventDefault(),Ie(1)))},!0),window.addEventListener("bygone:tour-command",b=>{b.detail==="toggleNarration"&&M(),b.detail==="pauseNarration"&&I.pauseForExternalOwner()}),window.addEventListener("beforeunload",()=>I.dispose(),{once:!0}),ie(I.state)}function S(){let i=document.getElementById("tour-narration-voice"),c=document.getElementById("tour-listen");if(!p){c&&(c.disabled=!0,c.title="Device narration is not supported by this browser."),i&&(i.disabled=!0),ce("Device narration unavailable");return}let g=()=>{if(a.narrationVoices=window.speechSynthesis.getVoices().slice().sort((h,f)=>Number(f.default)-Number(h.default)||h.lang.localeCompare(f.lang)||h.name.localeCompare(f.name)),a.narrationVoiceURI&&a.narrationVoices.length>0&&!a.narrationVoices.some(h=>h.voiceURI===a.narrationVoiceURI)&&(a.narrationVoiceURI="",window.localStorage.removeItem(u)),i){let h=document.createElement("option");h.value="",h.textContent="System default voice",i.replaceChildren(h,...a.narrationVoices.map(f=>{let x=document.createElement("option");return x.value=f.voiceURI,x.textContent=`${f.name} (${f.lang})${f.default?" \u2014 default":""}`,x})),i.value=a.narrationVoiceURI,i.disabled=a.narrationVoices.length===0}};g(),window.speechSynthesis.addEventListener("voiceschanged",g)}function w(){let i=Number(window.localStorage.getItem(d));return m.has(i)?i:1}function C(){let i=null;return{speak(c,g){if(!p){g.onError("Device narration is not supported by this browser.");return}let h=new window.SpeechSynthesisUtterance(c.speechText),f=a.narrationVoices.find(x=>x.voiceURI===a.narrationVoiceURI);f&&(h.voice=f),h.rate=a.narrationRate,h.onend=()=>{i===h&&(i=null),g.onEnd()},h.onerror=x=>{i===h&&(i=null),g.onError($(x.error))},i=h,window.speechSynthesis.speak(h)},pause(){p&&window.speechSynthesis.pause()},resume(){p&&window.speechSynthesis.resume()},cancel(){i=null,p&&window.speechSynthesis.cancel()}}}function $(i){return i==="not-allowed"?"Device narration needs permission to play audio.":i==="language-unavailable"||i==="voice-unavailable"?"The selected device voice is unavailable.":`Device narration failed${i?`: ${i}`:"."}`}function R(){if(!p||a.mode!=="tour")return;let i=D("playback-start");i&&(a.renderedNarrationUnit=i,pn(i),I.start(i,!0))}function M(){I.state.kind==="playing"||I.state.kind==="paused"?I.togglePause():R()}function D(i){return!a.tour||a.activeSceneIndex<0?null:qt(a.tour,{sceneIndex:a.activeSceneIndex,stepIndex:a.activeStepIndex},{entry:i})}function U(i,c){let g=a.tour;return!!(g&&Re(g.scenes,i.position,c))}function z(i,c){let g=a.tour;if(!g)return null;let h=Re(g.scenes,i.position,c);return h?oe(h.sceneIndex,h.stepIndex,{narrationNavigation:"controller",narrationEntry:"continuous"}):null}function pe(){fetch("/narration/claim",{method:"POST",cache:"no-store"}).catch(()=>{})}function ie(i){let c=document.getElementById("tour-listen"),g=document.getElementById("tour-stop"),h=document.getElementById("tour-narration-skip-back"),f=document.getElementById("tour-narration-skip-ahead");if(c){c.disabled=!p||a.mode!=="tour";let x=i.kind==="playing";c.querySelector(".tour-play-pause-icon")?.setAttribute("d",x?"M7 5h4v14H7zM13 5h4v14h-4z":"m8 5 11 7-11 7Z");let y=x?"Pause narration":i.kind==="paused"?"Resume narration":"Listen from the current tour item";c.title=y,c.setAttribute("aria-label",y)}if(g&&(g.disabled=i.kind!=="playing"&&i.kind!=="paused"),h&&(h.disabled=!I.canSkipSegment(-1)),f&&(f.disabled=!I.canSkipSegment(1)),i.kind==="playing"||i.kind==="paused"){let x=i.segmentIndex+1,y=i.unit.segments.length;ce(`${i.kind==="paused"?"Paused":"Speaking"} \xB7 segment ${x} of ${y}`)}else i.kind==="completed"?ce("Narration complete"):i.kind==="error"?ce(i.message):p&&ce("Device voice ready")}function ce(i){let c=document.getElementById("tour-narration-status");c&&(c.textContent=i)}function Qt(i,c){if(document.querySelectorAll(".tour-narration-segment.is-speaking").forEach(y=>{y.classList.remove("is-speaking","is-paused")}),!i)return;let g=[...document.querySelectorAll("[data-narration-segment-id]")].find(y=>y.dataset.narrationSegmentId===i.id);if(!g)return;g.classList.add("is-speaking"),g.classList.toggle("is-paused",c);let h=document.getElementById("tour-narrative");if(!h)return;let f=g.getBoundingClientRect(),x=h.getBoundingClientRect();(f.top<x.top||f.bottom>x.bottom)&&g.scrollIntoView({block:"nearest"})}let le=[];function Me(){let i=document.getElementById("tour-search-input"),c=document.getElementById("tour-search-scope"),g=document.getElementById("tour-search-status"),h=document.getElementById("tour-search-results");if(!(!a.tour||!i||!c||!g||!h)){if(le=Kt(a.tour,i.value,c.value),!i.value.trim()){g.textContent="Cmd/Ctrl+Shift+F",h.replaceChildren();return}g.textContent=`${le.length} result${le.length===1?"":"s"}`,h.replaceChildren(...le.map((f,x)=>{let y=document.createElement("button");y.type="button",y.className="tour-search-result",y.setAttribute("role","option"),y.dataset.tourSearchResult=String(x),y.title=`Open ${f.kind==="code"?`${f.label}:${f.lineNumber}`:f.label}`;let T=document.createElement("span");T.className="tour-search-location",T.textContent=f.kind==="code"?`${f.label}:${f.lineNumber}`:f.label;let N=document.createElement("span");return N.className="tour-search-preview",N.textContent=f.preview.trim(),y.append(T,N),y}))}}function en(i){let c=le[i];if(c){if(c.kind==="narrative"){oe(c.sceneIndex,c.stepIndex??0);return}ct(c.fileIndex)&&window.requestAnimationFrame(()=>v({type:"revealSearchResult",sideIndex:c.sideIndex,lineNumber:c.lineNumber,startColumn:c.startColumn,endColumn:c.endColumn}))}}function tn(){let i=document.getElementById("tour-shell"),c=document.getElementById("tour-sidebar-resizer"),g=document.getElementById("tour-sidebar-hide"),h=document.getElementById("tour-sidebar-show");!i||!c||!g||!h||(tt(),g.addEventListener("click",()=>De(!0)),h.addEventListener("click",()=>De(!1)),c.addEventListener("pointerdown",f=>{f.preventDefault(),document.body.classList.add("is-resizing-tour-sidebar"),c.setPointerCapture?.(f.pointerId);let x=T=>et(T.clientX),y=()=>{document.body.classList.remove("is-resizing-tour-sidebar"),window.removeEventListener("pointermove",x),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),window.localStorage.setItem(e,String(a.tourSidebarWidth))};window.addEventListener("pointermove",x),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y)}),c.addEventListener("keydown",f=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(f.key))return;f.preventDefault();let x=a.tourSidebarWidth;f.key==="Home"?x=240:f.key==="End"?x=Pe():x+=f.key==="ArrowLeft"?-16:16,et(x),window.localStorage.setItem(e,String(a.tourSidebarWidth))}))}function nn(){let i=Number.parseInt(window.localStorage.getItem(e)||"",10);return Number.isFinite(i)?Math.min(600,Math.max(240,i)):360}function Pe(){return Math.max(240,Math.min(600,Math.floor(window.innerWidth*.6)))}function et(i){a.tourSidebarWidth=Math.min(Pe(),Math.max(240,Math.round(i))),tt(),window.dispatchEvent(new Event("resize"))}function tt(){document.documentElement.style.setProperty("--tour-rail-width",`${a.tourSidebarWidth}px`);let i=document.getElementById("tour-sidebar-resizer");i?.setAttribute("aria-valuemax",String(Pe())),i?.setAttribute("aria-valuenow",String(a.tourSidebarWidth))}function De(i){a.tourSidebarHidden=i,document.body.classList.toggle("tour-sidebar-hidden",i);let c=document.getElementById("tour-sidebar-show");c&&(c.hidden=!i),window.dispatchEvent(new Event("resize"))}function rn(){let i=document.getElementById("tour-narrative-resizer");i&&(_e(),i.addEventListener("pointerdown",c=>{c.preventDefault(),document.body.classList.add("is-resizing-tour-narrative"),i.setPointerCapture?.(c.pointerId),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-start"));let g=document.getElementById("tour-narrative")?.getBoundingClientRect().top||0,h=x=>nt(x.clientY-g),f=()=>{document.body.classList.remove("is-resizing-tour-narrative"),window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",f),window.removeEventListener("pointercancel",f),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-end")),rt()};window.addEventListener("pointermove",h),window.addEventListener("pointerup",f),window.addEventListener("pointercancel",f)}),i.addEventListener("keydown",c=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(c.key))return;c.preventDefault();let g=c.key==="Home"?180:c.key==="End"?be():a.tourNarrativeHeight+(c.key==="ArrowUp"?-16:16);nt(g),rt()}),window.addEventListener("resize",()=>{a.tourNarrativeHeight=Math.min(be(),a.tourNarrativeHeight),_e()}))}function on(){let i=Number.parseInt(window.localStorage.getItem(o)||"",10);if(Number.isFinite(i))return Math.max(180,i);let c=Number.parseInt(window.getComputedStyle(document.documentElement).getPropertyValue("--tour-narrative-height"),10);return Number.isFinite(c)?c:296}function be(){let i=document.getElementById("tour-narrative")?.getBoundingClientRect().top||0;return Math.max(180,window.innerHeight-i-180)}function nt(i){a.tourNarrativeHeight=Math.min(be(),Math.max(180,Math.round(i))),_e(),window.dispatchEvent(new Event("resize"))}function _e(){document.documentElement.style.setProperty("--tour-narrative-height",`${a.tourNarrativeHeight}px`);let i=document.getElementById("tour-narrative-resizer");i?.setAttribute("aria-valuemax",String(be())),i?.setAttribute("aria-valuenow",String(a.tourNarrativeHeight))}function rt(){window.localStorage.setItem(o,String(a.tourNarrativeHeight))}async function sn(i){X("Loading change tour\u2026");try{I.stop();let c=await fetch(i,{cache:"no-store"});if(!c.ok)throw new Error(`Manifest request failed (${c.status}).`);a.tour=Ot(await c.json()),a.mode="tour",document.body.classList.add("tour-mode"),an(),Me();let g=new URLSearchParams(window.location.search),h=Wt(a.tour.scenes,g.get("scene"),g.get("step"));oe(h.sceneIndex,h.stepIndex),ie(I.state),X("")}catch(c){X(`Could not load change tour: ${c instanceof Error?c.message:String(c)}`)}}function an(){let i=a.tour;if(!i)return;let c=document.getElementById("tour-shell"),g=document.getElementById("tour-title"),h=document.getElementById("tour-source"),f=document.getElementById("tour-range"),x=document.getElementById("tour-stats"),y=document.getElementById("tour-scenes"),T=document.getElementById("tour-scene-count"),N=document.getElementById("tour-files"),H=document.getElementById("tour-file-count"),B=document.getElementById("tour-commits"),V=document.getElementById("tour-commits-summary");if(!c||!g||!h||!f||!x||!y||!T||!N||!H||!B||!V)throw new Error("Presenter UI is incomplete.");c.hidden=!1,g.textContent=i.title,document.title=Zt(i),i.sourceUrl?(h.href=i.sourceUrl,h.hidden=!1):h.hidden=!0;let q=Se(i.range.baseRef),P=Se(i.range.headRef),_=i.range.headOid.slice(0,7);f.textContent=`${q} \u2192 ${P}${P===_?"":` \xB7 ${_}`}`,x.textContent=`${fe(i.summary.changedFiles,"file")} \xB7 +${i.summary.additions} \u2212${i.summary.deletions} \xB7 ${fe(i.summary.commitCount,"commit")}`,T.textContent=String(i.scenes.length),H.textContent=String(i.files.length),V.textContent=fe(i.summary.commitCount,"commit"),y.replaceChildren();let K=new Map(i.scenes.map(b=>[b.id,b]));for(let b of i.chapters){let G=document.createElement("h2");G.className="tour-chapter-title",G.textContent=b.title,y.append(G);for(let A of b.sceneIds){let F=K.get(A);if(!F)continue;let j=i.scenes.indexOf(F),W=document.createElement("button");W.type="button",W.className="tour-scene",W.dataset.sceneId=F.id,W.title=`Open scene: ${F.kind==="text-diff"?F.path:F.title}`,W.addEventListener("click",()=>oe(j));let te=document.createElement("span");te.className="tour-scene-number",te.textContent=String(j+1).padStart(2,"0");let Ue=document.createElement("span");Ue.className="tour-scene-copy";for(let[wn,In]of[["tour-scene-title",F.title],["tour-scene-path",F.kind==="text-diff"?F.path:F.kind==="deconstructed-diff"?fe(F.steps.length,"explanation stage"):de(F)?fe(F.steps.length,"code step"):"Discussion"],["tour-scene-note",F.takeaway]]){let We=document.createElement("span");We.className=wn,We.textContent=In,Ue.append(We)}W.append(te,Ue),y.append(W)}}N.replaceChildren(...i.files.map((b,G)=>{let A=document.createElement("button");A.type="button",A.className=`tour-file${b.kind==="omitted"?" is-omitted":""}`,A.dataset.filePath=b.path,A.disabled=b.kind==="omitted",A.title=b.kind==="omitted"?`${b.path}: ${b.reason}`:`Open file: ${b.path}`,b.kind==="text-diff"&&A.addEventListener("click",()=>lt(G));let F=document.createElement("span");F.className="tour-file-marker",F.textContent=b.kind==="omitted"?"\xD7":fn(b.changeKind);let j=document.createElement("span");j.className="tour-file-copy";let W=document.createElement("span");W.className="tour-file-path",W.textContent=b.path;let te=document.createElement("span");return te.className="tour-file-meta",te.textContent=b.kind==="omitted"?`Not rendered \xB7 ${b.reason}`:`${gn(b.changeKind)} \xB7 +${b.additions} \u2212${b.deletions}`,j.append(W,te),A.append(F,j),A})),B.replaceChildren(...i.commits.map(b=>{let G=document.createElement("li"),A=document.createElement("span");return A.className="tour-commit-oid",A.textContent=b.shortOid,G.append(A,document.createTextNode(b.summary)),G}))}function oe(i,c=0,g={}){let h=a.tour;if(!h||i<0||i>=h.scenes.length)return null;let f=h.scenes[i];a.activeSceneIndex=i,a.activeStepIndex=de(f)?Math.min(Math.max(c,0),Math.max(f.steps.length-1,0)):0,a.tourFocusFilePath=f.kind==="text-diff"?f.path:f.kind==="walkthrough"?f.steps[a.activeStepIndex]?.diff.path??null:xe(f)?f.steps[a.activeStepIndex]?.file??null:null;let x=ut(h,i);document.querySelectorAll(".tour-scene").forEach(N=>{N.classList.toggle("is-active",N.dataset.sceneId===f.id)}),document.querySelector(`.tour-scene[data-scene-id="${f.id}"]`)?.scrollIntoView({block:"nearest"});let y=D(g.narrationEntry||"playback-start");a.renderedNarrationUnit=y,ft(f,x,y),y&&(g.narrationNavigation==="linear"?I.followLinearNavigation(y):g.narrationNavigation!=="controller"&&I.followDirectNavigation(y));let T=new URLSearchParams(window.location.search);return T.set("scene",f.id),de(f)?T.set("step",f.steps[a.activeStepIndex].id):T.delete("step"),window.history.replaceState(null,"",`${window.location.pathname}?${T.toString()}`),f.kind==="discussion"?(document.body.classList.add("tour-discussion"),Be(),y):(document.body.classList.remove("tour-discussion"),f.kind==="walkthrough"?(ot(f),y):xe(f)?(st(f),y):(we(f,ye(f.path)),y))}function ye(i){let c=a.tour;return!c||!i?[]:Yt(c,i,a.activeSceneIndex,a.activeStepIndex)}function cn(i,c){let g=a.tour;return!g||!i?[]:Jt(g,i,a.activeSceneIndex,a.activeStepIndex,(h,f)=>Xt(c?.[h]?.diffModel,f))}function Oe(i){return`file::${i}`}function we(i,c=[],g=Oe(i.path)){if(!a.tour)return;a.activeTourFilePath=i.path,Be();let f=ne(i.leftContent,i.rightContent),x=it(i,i.leftLabel,"base"),y=it(i,i.rightLabel,"head"),T=c.find(N=>N.active);v({type:"showDiff",file1:x,file2:y,comparisonId:`tour-${g}`,leftContent:i.leftContent,rightContent:i.rightContent,sourceInfo:{leftPath:i.path,rightPath:i.path},diffModel:f,history:null,fileNavigation:{canGoPrevious:!!ue(-1),canGoNext:!!ue(1)},editableSides:{left:!1,right:!1},comparisonSummary:`${i.path} \xB7 ${i.takeaway}`,initialChangeIndex:T?dt(f,T.side,T.startLine):i.focusChangeIndex,tourAnnotations:c})}function it(i,c,g){let h=c.startsWith(i.path)?c.slice(i.path.length).trim():c.trim();return h?`${g} ${h}`:g}function ot(i){let c=i.steps[a.activeStepIndex];c&&we(c.diff,ye(c.diff.path),Oe(c.diff.path))}function st(i){let c=i.steps[a.activeStepIndex];c&&at(i,c.file,c)}function at(i,c,g){let h=i.files.find(P=>P.path===c);if(!g||!h)return;a.activeTourFilePath=h.path,Be();let f=h.panels.map((P,_)=>({id:`${i.id}-${h.path}-${P.id}`,label:P.label,path:P.path||h.path,content:P.content,savedContent:P.content,dirty:!1,editable:!1,stackId:dn(i)[_].id})),x=f.slice(0,-1).map((P,_)=>({leftIndex:_,rightIndex:_+1,diffModel:ne(P.content,f[_+1].content)})),y=i.kind==="stacked-diff"?cn(h.path,x):[],T=y.find(P=>P.active),N=T?.pairIndex??g.pairIndex,H=T?.side??g.side,B=T?.startLine??g.startLine,V=x[N]?.diffModel,q=V&&B?dt(V,H,B):0;v({type:"showMultiDiff",panels:f,pairs:x,activePanelId:f[N+(H==="right"?1:0)]?.id,activePairIndex:N,initialChangeIndex:q,revealFirstChangeInEachPanel:i.kind==="deconstructed-diff",history:null,fileNavigation:{canGoPrevious:!!ue(-1),canGoNext:!!ue(1)},mutationEnabled:!1,comparisonSummary:i.kind==="deconstructed-diff"?`${i.stageLabel} \xB7 ${h.path} \xB7 ${Se(i.realRange.baseRef)} \u2192 ${Se(i.realRange.targetRef)}`:`${h.path} \xB7 ${i.takeaway}`,tourAnnotations:y})}function He(i){let c=a.tour;return!c||i!==-1&&i!==1?null:Re(c.scenes,{sceneIndex:a.activeSceneIndex,stepIndex:a.activeStepIndex},i)}function Ie(i){let c=He(i);return c?(oe(c.sceneIndex,c.stepIndex,{narrationNavigation:"linear",narrationEntry:"playback-start"}),!0):!1}function ue(i){let c=a.tour;return!c||i!==-1&&i!==1?null:Gt(c.files,a.activeTourFilePath,i)}function ln(i){let c=ue(i);return c?lt(c.fileIndex):!1}function ct(i,c=!0){let g=a.tour?.files[i];return!g||g.kind!=="text-diff"?!1:(c&&I.interruptForExploration(),we(g,ye(g.path),Oe(g.path)),!0)}function lt(i){let c=a.tour?.files[i];if(!c||c.kind!=="text-diff")return!1;if(I.interruptForExploration(),c?.kind==="text-diff"&&a.tour){let g=zt(a.tour.scenes,{sceneIndex:a.activeSceneIndex,stepIndex:a.activeStepIndex},c.path);if(g){let h=a.tour.scenes[g.sceneIndex],f=xe(h)?h.steps[g.stepIndex]:null;if(f)return at(h,c.path,f),!0}}return ct(i,!1)}function un(){let i=a.tour?.scenes[a.activeSceneIndex];if(!i||!a.tourFocusFilePath)return!1;if(i.kind==="walkthrough")ot(i);else if(xe(i))st(i);else if(i.kind==="text-diff")we(i,ye(i.path));else return!1;return!0}function Be(){document.querySelectorAll(".tour-file").forEach(c=>{c.classList.toggle("is-active",c.dataset.filePath===a.activeTourFilePath),c.classList.toggle("is-tour-focus",c.dataset.filePath===a.tourFocusFilePath)}),document.querySelector(".tour-file.is-active")?.scrollIntoView({block:"nearest"});let i=document.getElementById("tour-return-focus");i&&(i.hidden=!a.tourFocusFilePath||a.activeTourFilePath===a.tourFocusFilePath)}function de(i){return i.kind==="walkthrough"||i.kind==="stacked-diff"||i.kind==="deconstructed-diff"}function xe(i){return i.kind==="stacked-diff"||i.kind==="deconstructed-diff"}function dn(i){return i.kind==="deconstructed-diff"?i.panels:i.stack}function fn(i){return{added:"+",deleted:"\u2212",renamed:"\u2192",modified:"\u2022"}[i]||"\u2022"}function gn(i){return`${i.charAt(0).toUpperCase()}${i.slice(1)}`}function ut(i,c){let g=i.scenes[c],h=i.chapters.findIndex(T=>T.sceneIds.includes(g.id)),f=h>=0?i.chapters[h]:null,x=f?f.sceneIds.indexOf(g.id)+1:c+1,y=f?f.sceneIds.length:i.scenes.length;return{chapter:f,chapterIndex:h,chapterNumber:h>=0?h+1:c+1,sceneInChapter:x,scenesInChapter:y}}function hn(i,c,g){let h=[`Ch ${i.chapterNumber}`,`Scene ${i.sceneInChapter}/${i.scenesInChapter}`];return de(c)&&h.push(`Step ${g+1}/${c.steps.length}`),h.join(" \xB7 ")}function dt(i,c,g){let f=(c==="left"?i.leftLines:i.rightLines).findIndex(B=>B.lineNumber===g);if(f<0)return 0;let x=c==="left"?"leftStart":"rightStart",y=c==="left"?"leftEnd":"rightEnd",T=i.blocks.findIndex(B=>f>=B[x]&&f<B[y]);if(T>=0)return T;let N=0,H=Number.POSITIVE_INFINITY;return i.blocks.forEach((B,V)=>{let q=Math.min(Math.abs(f-B[x]),Math.abs(f-B[y]));q<H&&(N=V,H=q)}),N}function Se(i){return/^[0-9a-f]{40}$/i.test(i)?i.slice(0,7):i}function fe(i,c){return`${i} ${i===1?c:`${c}s`}`}function mn(i){return i instanceof Element&&!!i.closest('a, button, input, select, summary, textarea, [contenteditable="true"], [role="textbox"], .monaco-editor')}function pn(i){let c=a.tour?.scenes[a.activeSceneIndex];!a.tour||!c||ft(c,ut(a.tour,a.activeSceneIndex),i)}function ft(i,c,g){let h=document.getElementById("tour-narrative"),f=document.getElementById("tour-breadcrumb"),x=document.getElementById("tour-narrative-chapter"),y=document.getElementById("tour-narrative-title"),T=document.getElementById("tour-narrative-summary"),N=document.getElementById("tour-narrative-bullets"),H=document.getElementById("tour-narrative-tags"),B=document.getElementById("tour-narrative-takeaway"),V=document.getElementById("tour-step"),q=document.getElementById("tour-step-title"),P=document.getElementById("tour-step-body"),_=document.getElementById("tour-connection"),K=document.getElementById("tour-previous"),b=document.getElementById("tour-next");if(!h||!f||!x||!y||!T||!N||!H||!B||!V||!q||!P||!_||!K||!b)throw new Error("Tour narrative UI is incomplete.");h.hidden=!1,f.textContent=hn(c,i,a.activeStepIndex);let G=c.chapter?.title||"Change tour";J(x,G,{field:"chapter"},g,{suffix:i.kind==="deconstructed-diff"?` \xB7 ${i.stageLabel}`:""}),J(y,i.title,{field:"scene-title"},g),J(T,i.summary,{field:"summary"},g),N.replaceChildren(...i.bullets.map((F,j)=>{let W=document.createElement("li");return J(W,F,{field:"bullet",itemIndex:j},g),W})),H.replaceChildren(...i.tags.map(F=>{let j=document.createElement("span");return j.textContent=F,j})),J(B,i.takeaway,{field:"takeaway"},g);let A=de(i)?i.steps[a.activeStepIndex]:null;V.hidden=!A,A?(J(q,A.title,{field:"step-title"},g,{prefix:i.kind==="deconstructed-diff"?`Stage ${a.activeStepIndex+1}: `:""}),J(P,A.body,{field:"step-body"},g),"connection"in A&&A.connection?(_.hidden=!1,J(_,A.connection.label,{field:"connection"},g,{prefix:`${A.connection.from.path} \u2192 ${A.connection.to.path} \xB7 `})):(_.hidden=!0,_.textContent="")):(q.textContent="",P.textContent="",_.hidden=!0,_.textContent=""),K.disabled=!He(-1),b.disabled=!He(1)}function J(i,c,g,h,f={}){let x=h?.segments.filter(N=>N.source.field===g.field&&N.source.itemIndex===g.itemIndex)||[];if(x.length===0){i.textContent=`${f.prefix||""}${c}${f.suffix||""}`;return}let y=[];f.prefix&&y.push(document.createTextNode(f.prefix));let T=0;for(let N of x){N.startOffset>T&&y.push(document.createTextNode(c.slice(T,N.startOffset)));let H=document.createElement("span");H.className="tour-narration-segment",H.dataset.narrationSegmentId=N.id,H.textContent=c.slice(N.startOffset,N.endOffset),y.push(H),T=N.endOffset}T<c.length&&y.push(document.createTextNode(c.slice(T))),f.suffix&&y.push(document.createTextNode(f.suffix)),i.replaceChildren(...y)}function gt(){I.stop();let i=_t();a.mode="diff",a.comparisonId+=1,a.left={name:i.leftFileName,content:i.leftContent},a.right={name:i.rightFileName,content:i.rightContent},X("Loaded sample diff."),v({type:"showDiff",file1:a.left.name,file2:a.right.name,comparisonId:`web-${a.comparisonId}`,leftContent:a.left.content,rightContent:a.right.content,diffModel:ne(a.left.content,a.right.content),history:null})}async function bn(i){I.stop();let[c,g]=i,[h,f]=await Promise.all([c.text(),g.text()]);a.mode="diff",a.comparisonId+=1,a.left={name:c.name,content:h},a.right={name:g.name,content:f},X(`Loaded ${c.name} and ${g.name}.`),v({type:"showDiff",file1:c.name,file2:g.name,comparisonId:`web-${a.comparisonId}`,leftContent:h,rightContent:f,diffModel:ne(h,f),history:null})}async function yn(i){I.stop();let c=await Promise.all(i.map(async(g,h)=>{let f=await g.text();return{id:`web-panel-${h}`,label:g.name,content:f,savedContent:f,dirty:!1,editable:!0}}));a.mode="multi-diff",X(`Loaded ${c.length}-panel diff for ${c.map(g=>g.label).join(", ")}.`),v({type:"showMultiDiff",panels:c,pairs:c.slice(0,-1).map((g,h)=>({leftIndex:h,rightIndex:h+1,diffModel:ne(g.content,c[h+1].content)}))})}function X(i){let c=document.getElementById("web-status");c&&(c.textContent=i)}})();})();
150
+ `).forEach((r,o)=>{let s=r.toLocaleLowerCase(),l=0;for(;l<=s.length-e.length;){let u=s.indexOf(e,l);if(u<0)break;n.push({lineNumber:o+1,startColumn:u+1,endColumn:u+e.length+1,preview:r}),l=u+Math.max(e.length,1)}}),n}function cr(t){return t.kind==="walkthrough"||t.kind==="stacked-diff"||t.kind==="deconstructed-diff"}function Xt(t,e){let n=t?.blocks[0],r=e==="left"?t?.leftLines:t?.rightLines;if(!n||!r?.length)return;let o=e==="left"?n.leftStart:n.rightStart,s=e==="left"?n.leftEnd:n.rightEnd,l=r.slice(o,s),u=l[0]?.lineNumber??r[Math.min(o,r.length-1)]?.lineNumber;if(Number.isInteger(u))return{startLine:u,endLine:l.at(-1)?.lineNumber??u}}function Yt(t,e,n,r){let o=[];return t.scenes.forEach((s,l)=>{s.kind==="walkthrough"&&s.steps.forEach((u,d)=>{u.diff.path===e&&o.push({side:u.focus.revision==="base"?"left":"right",startLine:u.focus.startLine,endLine:u.focus.endLine,label:`${s.title} \xB7 ${u.title}: ${u.body}`,active:l===n&&d===r,jumpTarget:{sceneIndex:l,stepIndex:d}})})}),o}function Jt(t,e,n,r,o){let s=[];return t.scenes.forEach((l,u)=>{l.kind==="stacked-diff"&&l.steps.forEach((d,m)=>{if(d.file!==e)return;let p=d.startLine===void 0?o?.(d.pairIndex,d.side):{startLine:d.startLine,endLine:d.endLine??d.startLine};if(!p)return;let a=d.pairIndex+(d.side==="right"?1:0);s.push({pairIndex:d.pairIndex,panelIndex:a,side:d.side,startLine:p.startLine,endLine:p.endLine,label:`${l.title} \xB7 ${d.title}: ${d.body}`,active:u===n&&m===r,jumpTarget:{sceneIndex:u,stepIndex:m}})})}),s}function lr(t,e=120){return t.length<=e?t:`${t.slice(0,e-1)}\u2026`}function Zt(t,e="Bygone"){let n=t?.windowTitle?.trim()||t?.title?.trim();return n?lr(n):`${e} Tour`}(function(){let e="bygone.tourSidebarWidth",o="bygone.tourNarrativeHeight",u="bygone.tourNarrationVoice",d="bygone.tourNarrationRate",m=new Set([.75,1,1.25,1.5]),p="speechSynthesis"in window&&"SpeechSynthesisUtterance"in window,a={mode:"empty",left:null,right:null,comparisonId:0,tour:null,activeSceneIndex:-1,activeStepIndex:0,activeTourFilePath:null,tourFocusFilePath:null,tourSidebarWidth:nn(),tourSidebarHidden:!1,tourNarrativeHeight:on(),narrationVoiceURI:window.localStorage.getItem(u)||"",narrationRate:w(),narrationVoices:[],renderedNarrationUnit:null},I=new Fe(C(),{claimAudio:pe,onStateChange:ie,onSegmentChange:Qt,canNavigateUnit:U,navigateUnit:z});window.__BYGONE_HOST__={environment:"web",editorWorkerUrl:"/media/editor.worker.js",diffWorkerUrl:"/media/diff.worker.js",postMessage(i){k(i)}},window.addEventListener("DOMContentLoaded",()=>{E(),X("Browser host ready.")});function v(i){window.dispatchEvent(new window.CustomEvent("bygone:host-message",{detail:i}))}async function k(i){if(!(!i||typeof i!="object")){if(i.type==="ready"){let c=new URLSearchParams(window.location.search),g=c.get("manifest");g?sn(g):c.get("demo")==="1"&&gt();return}if(i.type==="navigateFile"&&a.mode==="tour"){ln(i.direction==="previous"?-1:1);return}if(i.type==="navigateTourStep"&&a.mode==="tour"){let c=i.sceneIndex,g=i.stepIndex;Number.isInteger(c)&&Number.isInteger(g)&&oe(c,g);return}i.type==="recomputeDiff"&&a.mode==="diff"&&a.left&&a.right&&(a.left.content=i.leftContent,a.right.content=i.rightContent,v({type:"showDiff",file1:a.left.name,file2:a.right.name,comparisonId:`web-${a.comparisonId}`,leftContent:a.left.content,rightContent:a.right.content,diffModel:ne(a.left.content,a.right.content),history:null}))}}function E(){let i=document.getElementById("web-compare-test"),c=document.getElementById("web-open-diff"),g=document.getElementById("web-open-diff3"),h=document.getElementById("web-diff-input"),f=document.getElementById("web-diff3-input"),x=document.getElementById("tour-previous"),y=document.getElementById("tour-next"),T=document.getElementById("tour-return-focus"),N=document.getElementById("tour-search-input"),H=document.getElementById("tour-search-scope"),B=document.getElementById("tour-listen"),V=document.getElementById("tour-stop"),j=document.getElementById("tour-narration-skip-back"),P=document.getElementById("tour-narration-skip-ahead"),_=document.getElementById("tour-narration-voice"),K=document.getElementById("tour-narration-rate");tn(),rn(),S(),i?.addEventListener("click",()=>{gt()}),c?.addEventListener("click",()=>{h.value="",h.click()}),g?.addEventListener("click",()=>{f.value="",f.click()}),h?.addEventListener("change",async()=>{let b=Array.from(h.files||[]);if(b.length!==2){X("Select exactly 2 files for a diff.");return}await bn(b)}),f?.addEventListener("change",async()=>{let b=Array.from(f.files||[]);if(b.length<1){X("Select one or more files.");return}await yn(b)}),x?.addEventListener("click",()=>Ie(-1)),y?.addEventListener("click",()=>Ie(1)),T?.addEventListener("click",un),N?.addEventListener("input",Me),H?.addEventListener("change",Me),B?.addEventListener("click",M),V?.addEventListener("click",()=>I.stop()),j?.addEventListener("click",()=>I.skipSegment(-1)),P?.addEventListener("click",()=>I.skipSegment(1)),_?.addEventListener("change",()=>{a.narrationVoiceURI=_.value,window.localStorage.setItem(u,a.narrationVoiceURI)}),K&&(K.value=String(a.narrationRate),K.addEventListener("change",()=>{let b=Number(K.value);a.narrationRate=m.has(b)?b:1,K.value=String(a.narrationRate),window.localStorage.setItem(d,String(a.narrationRate))})),document.getElementById("tour-search-results")?.addEventListener("click",b=>{let G=b.target instanceof Element?b.target.closest("[data-tour-search-result]"):null;G&&en(Number(G.getAttribute("data-tour-search-result")))}),window.addEventListener("keydown",b=>{if(a.mode==="tour"&&(b.metaKey||b.ctrlKey)&&b.shiftKey&&b.key.toLocaleLowerCase()==="f"){b.preventDefault(),b.stopImmediatePropagation(),a.tourSidebarHidden&&De(!1),N?.focus(),N?.select();return}a.mode!=="tour"||b.metaKey||b.ctrlKey||b.altKey||mn(b.target)||(b.key==="PageUp"||b.key==="ArrowLeft"?(b.preventDefault(),Ie(-1)):(b.key==="PageDown"||b.key==="ArrowRight")&&(b.preventDefault(),Ie(1)))},!0),window.addEventListener("bygone:tour-command",b=>{b.detail==="toggleNarration"&&M(),b.detail==="pauseNarration"&&I.pauseForExternalOwner()}),window.addEventListener("beforeunload",()=>I.dispose(),{once:!0}),ie(I.state)}function S(){let i=document.getElementById("tour-narration-voice"),c=document.getElementById("tour-listen");if(!p){c&&(c.disabled=!0,c.title="Device narration is not supported by this browser."),i&&(i.disabled=!0),ce("Device narration unavailable");return}let g=()=>{if(a.narrationVoices=window.speechSynthesis.getVoices().slice().sort((h,f)=>Number(f.default)-Number(h.default)||h.lang.localeCompare(f.lang)||h.name.localeCompare(f.name)),a.narrationVoiceURI&&a.narrationVoices.length>0&&!a.narrationVoices.some(h=>h.voiceURI===a.narrationVoiceURI)&&(a.narrationVoiceURI="",window.localStorage.removeItem(u)),i){let h=document.createElement("option");h.value="",h.textContent="System default voice",i.replaceChildren(h,...a.narrationVoices.map(f=>{let x=document.createElement("option");return x.value=f.voiceURI,x.textContent=`${f.name} (${f.lang})${f.default?" \u2014 default":""}`,x})),i.value=a.narrationVoiceURI,i.disabled=a.narrationVoices.length===0}};g(),window.speechSynthesis.addEventListener("voiceschanged",g)}function w(){let i=Number(window.localStorage.getItem(d));return m.has(i)?i:1}function C(){let i=null;return{speak(c,g){if(!p){g.onError("Device narration is not supported by this browser.");return}let h=new window.SpeechSynthesisUtterance(c.speechText),f=a.narrationVoices.find(x=>x.voiceURI===a.narrationVoiceURI);f&&(h.voice=f),h.rate=a.narrationRate,h.onend=()=>{i===h&&(i=null),g.onEnd()},h.onerror=x=>{i===h&&(i=null),g.onError($(x.error))},i=h,window.speechSynthesis.speak(h)},pause(){p&&window.speechSynthesis.pause()},resume(){p&&window.speechSynthesis.resume()},cancel(){i=null,p&&window.speechSynthesis.cancel()}}}function $(i){return i==="not-allowed"?"Device narration needs permission to play audio.":i==="language-unavailable"||i==="voice-unavailable"?"The selected device voice is unavailable.":`Device narration failed${i?`: ${i}`:"."}`}function R(){if(!p||a.mode!=="tour")return;let i=D("playback-start");i&&(a.renderedNarrationUnit=i,pn(i),I.start(i,!0))}function M(){I.state.kind==="playing"||I.state.kind==="paused"?I.togglePause():R()}function D(i){return!a.tour||a.activeSceneIndex<0?null:jt(a.tour,{sceneIndex:a.activeSceneIndex,stepIndex:a.activeStepIndex},{entry:i})}function U(i,c){let g=a.tour;return!!(g&&Re(g.scenes,i.position,c))}function z(i,c){let g=a.tour;if(!g)return null;let h=Re(g.scenes,i.position,c);return h?oe(h.sceneIndex,h.stepIndex,{narrationNavigation:"controller",narrationEntry:"continuous"}):null}function pe(){fetch("/narration/claim",{method:"POST",cache:"no-store"}).catch(()=>{})}function ie(i){let c=document.getElementById("tour-listen"),g=document.getElementById("tour-stop"),h=document.getElementById("tour-narration-skip-back"),f=document.getElementById("tour-narration-skip-ahead");if(c){c.disabled=!p||a.mode!=="tour";let x=i.kind==="playing";c.querySelector(".tour-play-pause-icon")?.setAttribute("d",x?"M7 5h4v14H7zM13 5h4v14h-4z":"m8 5 11 7-11 7Z");let y=x?"Pause narration":i.kind==="paused"?"Resume narration":"Listen from the current tour item";c.title=y,c.setAttribute("aria-label",y)}if(g&&(g.disabled=i.kind!=="playing"&&i.kind!=="paused"),h&&(h.disabled=!I.canSkipSegment(-1)),f&&(f.disabled=!I.canSkipSegment(1)),i.kind==="playing"||i.kind==="paused"){let x=i.segmentIndex+1,y=i.unit.segments.length;ce(`${i.kind==="paused"?"Paused":"Speaking"} \xB7 segment ${x} of ${y}`)}else i.kind==="completed"?ce("Narration complete"):i.kind==="error"?ce(i.message):p&&ce("Device voice ready")}function ce(i){let c=document.getElementById("tour-narration-status");c&&(c.textContent=i)}function Qt(i,c){if(document.querySelectorAll(".tour-narration-segment.is-speaking").forEach(y=>{y.classList.remove("is-speaking","is-paused")}),!i)return;let g=[...document.querySelectorAll("[data-narration-segment-id]")].find(y=>y.dataset.narrationSegmentId===i.id);if(!g)return;g.classList.add("is-speaking"),g.classList.toggle("is-paused",c);let h=document.getElementById("tour-narrative");if(!h)return;let f=g.getBoundingClientRect(),x=h.getBoundingClientRect();(f.top<x.top||f.bottom>x.bottom)&&g.scrollIntoView({block:"nearest"})}let le=[];function Me(){let i=document.getElementById("tour-search-input"),c=document.getElementById("tour-search-scope"),g=document.getElementById("tour-search-status"),h=document.getElementById("tour-search-results");if(!(!a.tour||!i||!c||!g||!h)){if(le=Kt(a.tour,i.value,c.value),!i.value.trim()){g.textContent="Cmd/Ctrl+Shift+F",h.replaceChildren();return}g.textContent=`${le.length} result${le.length===1?"":"s"}`,h.replaceChildren(...le.map((f,x)=>{let y=document.createElement("button");y.type="button",y.className="tour-search-result",y.setAttribute("role","option"),y.dataset.tourSearchResult=String(x),y.title=`Open ${f.kind==="code"?`${f.label}:${f.lineNumber}`:f.label}`;let T=document.createElement("span");T.className="tour-search-location",T.textContent=f.kind==="code"?`${f.label}:${f.lineNumber}`:f.label;let N=document.createElement("span");return N.className="tour-search-preview",N.textContent=f.preview.trim(),y.append(T,N),y}))}}function en(i){let c=le[i];if(c){if(c.kind==="narrative"){oe(c.sceneIndex,c.stepIndex??0);return}ct(c.fileIndex)&&window.requestAnimationFrame(()=>v({type:"revealSearchResult",sideIndex:c.sideIndex,lineNumber:c.lineNumber,startColumn:c.startColumn,endColumn:c.endColumn}))}}function tn(){let i=document.getElementById("tour-shell"),c=document.getElementById("tour-sidebar-resizer"),g=document.getElementById("tour-sidebar-hide"),h=document.getElementById("tour-sidebar-show");!i||!c||!g||!h||(tt(),g.addEventListener("click",()=>De(!0)),h.addEventListener("click",()=>De(!1)),c.addEventListener("pointerdown",f=>{f.preventDefault(),document.body.classList.add("is-resizing-tour-sidebar"),c.setPointerCapture?.(f.pointerId);let x=T=>et(T.clientX),y=()=>{document.body.classList.remove("is-resizing-tour-sidebar"),window.removeEventListener("pointermove",x),window.removeEventListener("pointerup",y),window.removeEventListener("pointercancel",y),window.localStorage.setItem(e,String(a.tourSidebarWidth))};window.addEventListener("pointermove",x),window.addEventListener("pointerup",y),window.addEventListener("pointercancel",y)}),c.addEventListener("keydown",f=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(f.key))return;f.preventDefault();let x=a.tourSidebarWidth;f.key==="Home"?x=240:f.key==="End"?x=Pe():x+=f.key==="ArrowLeft"?-16:16,et(x),window.localStorage.setItem(e,String(a.tourSidebarWidth))}))}function nn(){let i=Number.parseInt(window.localStorage.getItem(e)||"",10);return Number.isFinite(i)?Math.min(600,Math.max(240,i)):360}function Pe(){return Math.max(240,Math.min(600,Math.floor(window.innerWidth*.6)))}function et(i){a.tourSidebarWidth=Math.min(Pe(),Math.max(240,Math.round(i))),tt(),window.dispatchEvent(new Event("resize"))}function tt(){document.documentElement.style.setProperty("--tour-rail-width",`${a.tourSidebarWidth}px`);let i=document.getElementById("tour-sidebar-resizer");i?.setAttribute("aria-valuemax",String(Pe())),i?.setAttribute("aria-valuenow",String(a.tourSidebarWidth))}function De(i){a.tourSidebarHidden=i,document.body.classList.toggle("tour-sidebar-hidden",i);let c=document.getElementById("tour-sidebar-show");c&&(c.hidden=!i),window.dispatchEvent(new Event("resize"))}function rn(){let i=document.getElementById("tour-narrative-resizer");i&&(_e(),i.addEventListener("pointerdown",c=>{c.preventDefault(),document.body.classList.add("is-resizing-tour-narrative"),i.setPointerCapture?.(c.pointerId),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-start"));let g=document.getElementById("tour-narrative")?.getBoundingClientRect().top||0,h=x=>nt(x.clientY-g),f=()=>{document.body.classList.remove("is-resizing-tour-narrative"),window.removeEventListener("pointermove",h),window.removeEventListener("pointerup",f),window.removeEventListener("pointercancel",f),window.dispatchEvent(new CustomEvent("bygone:workspace-resize-end")),rt()};window.addEventListener("pointermove",h),window.addEventListener("pointerup",f),window.addEventListener("pointercancel",f)}),i.addEventListener("keydown",c=>{if(!["ArrowUp","ArrowDown","Home","End"].includes(c.key))return;c.preventDefault();let g=c.key==="Home"?180:c.key==="End"?be():a.tourNarrativeHeight+(c.key==="ArrowUp"?-16:16);nt(g),rt()}),window.addEventListener("resize",()=>{a.tourNarrativeHeight=Math.min(be(),a.tourNarrativeHeight),_e()}))}function on(){let i=Number.parseInt(window.localStorage.getItem(o)||"",10);if(Number.isFinite(i))return Math.max(180,i);let c=Number.parseInt(window.getComputedStyle(document.documentElement).getPropertyValue("--tour-narrative-height"),10);return Number.isFinite(c)?c:296}function be(){let i=document.getElementById("tour-narrative")?.getBoundingClientRect().top||0;return Math.max(180,window.innerHeight-i-180)}function nt(i){a.tourNarrativeHeight=Math.min(be(),Math.max(180,Math.round(i))),_e(),window.dispatchEvent(new Event("resize"))}function _e(){document.documentElement.style.setProperty("--tour-narrative-height",`${a.tourNarrativeHeight}px`);let i=document.getElementById("tour-narrative-resizer");i?.setAttribute("aria-valuemax",String(be())),i?.setAttribute("aria-valuenow",String(a.tourNarrativeHeight))}function rt(){window.localStorage.setItem(o,String(a.tourNarrativeHeight))}async function sn(i){X("Loading change tour\u2026");try{I.stop();let c=await fetch(i,{cache:"no-store"});if(!c.ok)throw new Error(`Manifest request failed (${c.status}).`);a.tour=Ot(await c.json()),a.mode="tour",document.body.classList.add("tour-mode"),an(),Me();let g=new URLSearchParams(window.location.search),h=Wt(a.tour.scenes,g.get("scene"),g.get("step"));oe(h.sceneIndex,h.stepIndex),ie(I.state),X("")}catch(c){X(`Could not load change tour: ${c instanceof Error?c.message:String(c)}`)}}function an(){let i=a.tour;if(!i)return;let c=document.getElementById("tour-shell"),g=document.getElementById("tour-title"),h=document.getElementById("tour-source"),f=document.getElementById("tour-range"),x=document.getElementById("tour-stats"),y=document.getElementById("tour-scenes"),T=document.getElementById("tour-scene-count"),N=document.getElementById("tour-files"),H=document.getElementById("tour-file-count"),B=document.getElementById("tour-commits"),V=document.getElementById("tour-commits-summary");if(!c||!g||!h||!f||!x||!y||!T||!N||!H||!B||!V)throw new Error("Presenter UI is incomplete.");c.hidden=!1,g.textContent=i.title,document.title=Zt(i),i.sourceUrl?(h.href=i.sourceUrl,h.hidden=!1):h.hidden=!0;let j=Se(i.range.baseRef),P=Se(i.range.headRef),_=i.range.headOid.slice(0,7);f.textContent=`${j} \u2192 ${P}${P===_?"":` \xB7 ${_}`}`,x.textContent=`${fe(i.summary.changedFiles,"file")} \xB7 +${i.summary.additions} \u2212${i.summary.deletions} \xB7 ${fe(i.summary.commitCount,"commit")}`,T.textContent=String(i.scenes.length),H.textContent=String(i.files.length),V.textContent=fe(i.summary.commitCount,"commit"),y.replaceChildren();let K=new Map(i.scenes.map(b=>[b.id,b]));for(let b of i.chapters){let G=document.createElement("h2");G.className="tour-chapter-title",G.textContent=b.title,y.append(G);for(let A of b.sceneIds){let F=K.get(A);if(!F)continue;let q=i.scenes.indexOf(F),W=document.createElement("button");W.type="button",W.className="tour-scene",W.dataset.sceneId=F.id,W.title=`Open scene: ${F.kind==="text-diff"?F.path:F.title}`,W.addEventListener("click",()=>oe(q));let te=document.createElement("span");te.className="tour-scene-number",te.textContent=String(q+1).padStart(2,"0");let Ue=document.createElement("span");Ue.className="tour-scene-copy";for(let[wn,In]of[["tour-scene-title",F.title],["tour-scene-path",F.kind==="text-diff"?F.path:F.kind==="deconstructed-diff"?fe(F.steps.length,"explanation stage"):de(F)?fe(F.steps.length,"code step"):"Discussion"],["tour-scene-note",F.takeaway]]){let We=document.createElement("span");We.className=wn,We.textContent=In,Ue.append(We)}W.append(te,Ue),y.append(W)}}N.replaceChildren(...i.files.map((b,G)=>{let A=document.createElement("button");A.type="button",A.className=`tour-file${b.kind==="omitted"?" is-omitted":""}`,A.dataset.filePath=b.path,A.disabled=b.kind==="omitted",A.title=b.kind==="omitted"?`${b.path}: ${b.reason}`:`Open file: ${b.path}`,b.kind==="text-diff"&&A.addEventListener("click",()=>lt(G));let F=document.createElement("span");F.className="tour-file-marker",F.textContent=b.kind==="omitted"?"\xD7":fn(b.changeKind);let q=document.createElement("span");q.className="tour-file-copy";let W=document.createElement("span");W.className="tour-file-path",W.textContent=b.path;let te=document.createElement("span");return te.className="tour-file-meta",te.textContent=b.kind==="omitted"?`Not rendered \xB7 ${b.reason}`:`${gn(b.changeKind)} \xB7 +${b.additions} \u2212${b.deletions}`,q.append(W,te),A.append(F,q),A})),B.replaceChildren(...i.commits.map(b=>{let G=document.createElement("li"),A=document.createElement("span");return A.className="tour-commit-oid",A.textContent=b.shortOid,G.append(A,document.createTextNode(b.summary)),G}))}function oe(i,c=0,g={}){let h=a.tour;if(!h||i<0||i>=h.scenes.length)return null;let f=h.scenes[i];a.activeSceneIndex=i,a.activeStepIndex=de(f)?Math.min(Math.max(c,0),Math.max(f.steps.length-1,0)):0,a.tourFocusFilePath=f.kind==="text-diff"?f.path:f.kind==="walkthrough"?f.steps[a.activeStepIndex]?.diff.path??null:xe(f)?f.steps[a.activeStepIndex]?.file??null:null;let x=ut(h,i);document.querySelectorAll(".tour-scene").forEach(N=>{N.classList.toggle("is-active",N.dataset.sceneId===f.id)}),document.querySelector(`.tour-scene[data-scene-id="${f.id}"]`)?.scrollIntoView({block:"nearest"});let y=D(g.narrationEntry||"playback-start");a.renderedNarrationUnit=y,ft(f,x,y),y&&(g.narrationNavigation==="linear"?I.followLinearNavigation(y):g.narrationNavigation!=="controller"&&I.followDirectNavigation(y));let T=new URLSearchParams(window.location.search);return T.set("scene",f.id),de(f)?T.set("step",f.steps[a.activeStepIndex].id):T.delete("step"),window.history.replaceState(null,"",`${window.location.pathname}?${T.toString()}`),f.kind==="discussion"?(document.body.classList.add("tour-discussion"),Be(),y):(document.body.classList.remove("tour-discussion"),f.kind==="walkthrough"?(ot(f),y):xe(f)?(st(f),y):(we(f,ye(f.path)),y))}function ye(i){let c=a.tour;return!c||!i?[]:Yt(c,i,a.activeSceneIndex,a.activeStepIndex)}function cn(i,c){let g=a.tour;return!g||!i?[]:Jt(g,i,a.activeSceneIndex,a.activeStepIndex,(h,f)=>Xt(c?.[h]?.diffModel,f))}function Oe(i){return`file::${i}`}function we(i,c=[],g=Oe(i.path)){if(!a.tour)return;a.activeTourFilePath=i.path,Be();let f=ne(i.leftContent,i.rightContent),x=it(i,i.leftLabel,"base"),y=it(i,i.rightLabel,"head"),T=c.find(N=>N.active);v({type:"showDiff",file1:x,file2:y,comparisonId:`tour-${g}`,leftContent:i.leftContent,rightContent:i.rightContent,sourceInfo:{leftPath:i.path,rightPath:i.path},diffModel:f,history:null,fileNavigation:{canGoPrevious:!!ue(-1),canGoNext:!!ue(1)},editableSides:{left:!1,right:!1},comparisonSummary:`${i.path} \xB7 ${i.takeaway}`,initialChangeIndex:T?dt(f,T.side,T.startLine):i.focusChangeIndex,tourAnnotations:c})}function it(i,c,g){let h=c.startsWith(i.path)?c.slice(i.path.length).trim():c.trim();return h?`${g} ${h}`:g}function ot(i){let c=i.steps[a.activeStepIndex];c&&we(c.diff,ye(c.diff.path),Oe(c.diff.path))}function st(i){let c=i.steps[a.activeStepIndex];c&&at(i,c.file,c)}function at(i,c,g){let h=i.files.find(P=>P.path===c);if(!g||!h)return;a.activeTourFilePath=h.path,Be();let f=h.panels.map((P,_)=>({id:`${i.id}-${h.path}-${P.id}`,label:P.label,path:P.path||h.path,content:P.content,savedContent:P.content,dirty:!1,editable:!1,stackId:dn(i)[_].id})),x=f.slice(0,-1).map((P,_)=>({leftIndex:_,rightIndex:_+1,diffModel:ne(P.content,f[_+1].content)})),y=i.kind==="stacked-diff"?cn(h.path,x):[],T=y.find(P=>P.active),N=T?.pairIndex??g.pairIndex,H=T?.side??g.side,B=T?.startLine??g.startLine,V=x[N]?.diffModel,j=V&&B?dt(V,H,B):0;v({type:"showMultiDiff",panels:f,pairs:x,activePanelId:f[N+(H==="right"?1:0)]?.id,activePairIndex:N,initialChangeIndex:j,revealFirstChangeInEachPanel:i.kind==="deconstructed-diff",history:null,fileNavigation:{canGoPrevious:!!ue(-1),canGoNext:!!ue(1)},mutationEnabled:!1,comparisonSummary:i.kind==="deconstructed-diff"?`${i.stageLabel} \xB7 ${h.path} \xB7 ${Se(i.realRange.baseRef)} \u2192 ${Se(i.realRange.targetRef)}`:`${h.path} \xB7 ${i.takeaway}`,tourAnnotations:y})}function He(i){let c=a.tour;return!c||i!==-1&&i!==1?null:Re(c.scenes,{sceneIndex:a.activeSceneIndex,stepIndex:a.activeStepIndex},i)}function Ie(i){let c=He(i);return c?(oe(c.sceneIndex,c.stepIndex,{narrationNavigation:"linear",narrationEntry:"playback-start"}),!0):!1}function ue(i){let c=a.tour;return!c||i!==-1&&i!==1?null:Gt(c.files,a.activeTourFilePath,i)}function ln(i){let c=ue(i);return c?lt(c.fileIndex):!1}function ct(i,c=!0){let g=a.tour?.files[i];return!g||g.kind!=="text-diff"?!1:(c&&I.interruptForExploration(),we(g,ye(g.path),Oe(g.path)),!0)}function lt(i){let c=a.tour?.files[i];if(!c||c.kind!=="text-diff")return!1;if(I.interruptForExploration(),c?.kind==="text-diff"&&a.tour){let g=zt(a.tour.scenes,{sceneIndex:a.activeSceneIndex,stepIndex:a.activeStepIndex},c.path);if(g){let h=a.tour.scenes[g.sceneIndex],f=xe(h)?h.steps[g.stepIndex]:null;if(f)return at(h,c.path,f),!0}}return ct(i,!1)}function un(){let i=a.tour?.scenes[a.activeSceneIndex];if(!i||!a.tourFocusFilePath)return!1;if(i.kind==="walkthrough")ot(i);else if(xe(i))st(i);else if(i.kind==="text-diff")we(i,ye(i.path));else return!1;return!0}function Be(){document.querySelectorAll(".tour-file").forEach(c=>{c.classList.toggle("is-active",c.dataset.filePath===a.activeTourFilePath),c.classList.toggle("is-tour-focus",c.dataset.filePath===a.tourFocusFilePath)}),document.querySelector(".tour-file.is-active")?.scrollIntoView({block:"nearest"});let i=document.getElementById("tour-return-focus");i&&(i.hidden=!a.tourFocusFilePath||a.activeTourFilePath===a.tourFocusFilePath)}function de(i){return i.kind==="walkthrough"||i.kind==="stacked-diff"||i.kind==="deconstructed-diff"}function xe(i){return i.kind==="stacked-diff"||i.kind==="deconstructed-diff"}function dn(i){return i.kind==="deconstructed-diff"?i.panels:i.stack}function fn(i){return{added:"+",deleted:"\u2212",renamed:"\u2192",modified:"\u2022"}[i]||"\u2022"}function gn(i){return`${i.charAt(0).toUpperCase()}${i.slice(1)}`}function ut(i,c){let g=i.scenes[c],h=i.chapters.findIndex(T=>T.sceneIds.includes(g.id)),f=h>=0?i.chapters[h]:null,x=f?f.sceneIds.indexOf(g.id)+1:c+1,y=f?f.sceneIds.length:i.scenes.length;return{chapter:f,chapterIndex:h,chapterNumber:h>=0?h+1:c+1,sceneInChapter:x,scenesInChapter:y}}function hn(i,c,g){let h=[`Ch ${i.chapterNumber}`,`Scene ${i.sceneInChapter}/${i.scenesInChapter}`];return de(c)&&h.push(`Step ${g+1}/${c.steps.length}`),h.join(" \xB7 ")}function dt(i,c,g){let f=(c==="left"?i.leftLines:i.rightLines).findIndex(B=>B.lineNumber===g);if(f<0)return 0;let x=c==="left"?"leftStart":"rightStart",y=c==="left"?"leftEnd":"rightEnd",T=i.blocks.findIndex(B=>f>=B[x]&&f<B[y]);if(T>=0)return T;let N=0,H=Number.POSITIVE_INFINITY;return i.blocks.forEach((B,V)=>{let j=Math.min(Math.abs(f-B[x]),Math.abs(f-B[y]));j<H&&(N=V,H=j)}),N}function Se(i){return/^[0-9a-f]{40}$/i.test(i)?i.slice(0,7):i}function fe(i,c){return`${i} ${i===1?c:`${c}s`}`}function mn(i){return i instanceof Element&&!!i.closest('a, button, input, select, summary, textarea, [contenteditable="true"], [role="textbox"], .monaco-editor')}function pn(i){let c=a.tour?.scenes[a.activeSceneIndex];!a.tour||!c||ft(c,ut(a.tour,a.activeSceneIndex),i)}function ft(i,c,g){let h=document.getElementById("tour-narrative"),f=document.getElementById("tour-breadcrumb"),x=document.getElementById("tour-narrative-chapter"),y=document.getElementById("tour-narrative-title"),T=document.getElementById("tour-narrative-summary"),N=document.getElementById("tour-narrative-bullets"),H=document.getElementById("tour-narrative-tags"),B=document.getElementById("tour-narrative-takeaway"),V=document.getElementById("tour-step"),j=document.getElementById("tour-step-title"),P=document.getElementById("tour-step-body"),_=document.getElementById("tour-connection"),K=document.getElementById("tour-previous"),b=document.getElementById("tour-next");if(!h||!f||!x||!y||!T||!N||!H||!B||!V||!j||!P||!_||!K||!b)throw new Error("Tour narrative UI is incomplete.");h.hidden=!1,f.textContent=hn(c,i,a.activeStepIndex);let G=c.chapter?.title||"Change tour";J(x,G,{field:"chapter"},g,{suffix:i.kind==="deconstructed-diff"?` \xB7 ${i.stageLabel}`:""}),J(y,i.title,{field:"scene-title"},g),J(T,i.summary,{field:"summary"},g),N.replaceChildren(...i.bullets.map((F,q)=>{let W=document.createElement("li");return J(W,F,{field:"bullet",itemIndex:q},g),W})),H.replaceChildren(...i.tags.map(F=>{let q=document.createElement("span");return q.textContent=F,q})),J(B,i.takeaway,{field:"takeaway"},g);let A=de(i)?i.steps[a.activeStepIndex]:null;V.hidden=!A,A?(J(j,A.title,{field:"step-title"},g,{prefix:i.kind==="deconstructed-diff"?`Stage ${a.activeStepIndex+1}: `:""}),J(P,A.body,{field:"step-body"},g),"connection"in A&&A.connection?(_.hidden=!1,J(_,A.connection.label,{field:"connection"},g,{prefix:`${A.connection.from.path} \u2192 ${A.connection.to.path} \xB7 `})):(_.hidden=!0,_.textContent="")):(j.textContent="",P.textContent="",_.hidden=!0,_.textContent=""),K.disabled=!He(-1),b.disabled=!He(1)}function J(i,c,g,h,f={}){let x=h?.segments.filter(N=>N.source.field===g.field&&N.source.itemIndex===g.itemIndex)||[];if(x.length===0){i.textContent=`${f.prefix||""}${c}${f.suffix||""}`;return}let y=[];f.prefix&&y.push(document.createTextNode(f.prefix));let T=0;for(let N of x){N.startOffset>T&&y.push(document.createTextNode(c.slice(T,N.startOffset)));let H=document.createElement("span");H.className="tour-narration-segment",H.dataset.narrationSegmentId=N.id,H.textContent=c.slice(N.startOffset,N.endOffset),y.push(H),T=N.endOffset}T<c.length&&y.push(document.createTextNode(c.slice(T))),f.suffix&&y.push(document.createTextNode(f.suffix)),i.replaceChildren(...y)}function gt(){I.stop();let i=_t();a.mode="diff",a.comparisonId+=1,a.left={name:i.leftFileName,content:i.leftContent},a.right={name:i.rightFileName,content:i.rightContent},X("Loaded sample diff."),v({type:"showDiff",file1:a.left.name,file2:a.right.name,comparisonId:`web-${a.comparisonId}`,leftContent:a.left.content,rightContent:a.right.content,diffModel:ne(a.left.content,a.right.content),history:null})}async function bn(i){I.stop();let[c,g]=i,[h,f]=await Promise.all([c.text(),g.text()]);a.mode="diff",a.comparisonId+=1,a.left={name:c.name,content:h},a.right={name:g.name,content:f},X(`Loaded ${c.name} and ${g.name}.`),v({type:"showDiff",file1:c.name,file2:g.name,comparisonId:`web-${a.comparisonId}`,leftContent:h,rightContent:f,diffModel:ne(h,f),history:null})}async function yn(i){I.stop();let c=await Promise.all(i.map(async(g,h)=>{let f=await g.text();return{id:`web-panel-${h}`,label:g.name,content:f,savedContent:f,dirty:!1,editable:!0}}));a.mode="multi-diff",X(`Loaded ${c.length}-panel diff for ${c.map(g=>g.label).join(", ")}.`),v({type:"showMultiDiff",panels:c,pairs:c.slice(0,-1).map((g,h)=>({leftIndex:h,rightIndex:h+1,diffModel:ne(g.content,c[h+1].content)}))})}function X(i){let c=document.getElementById("web-status");c&&(c.textContent=i)}})();})();
151
151
  //# sourceMappingURL=web-host.js.map