@p4code/cli 0.0.47 → 0.0.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.mjs CHANGED
@@ -233,7 +233,7 @@ const make$71 = () => {
233
233
  const layer$67 = Layer.sync(NetService, make$71);
234
234
  //#endregion
235
235
  //#region package.json
236
- var version = "0.0.47";
236
+ var version = "0.0.49";
237
237
  //#endregion
238
238
  //#region src/config.ts
239
239
  /**
@@ -12763,8 +12763,8 @@ const noBrowserFlag = Flag.boolean("no-browser").pipe(Flag.withDescription("Disa
12763
12763
  const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(Flag.withSchema(Schema$1.Int), Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."), Flag.optional);
12764
12764
  const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(Flag.withDescription("Create a project for the current working directory on startup when missing."), Flag.optional);
12765
12765
  const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(Flag.withDescription("Emit server-side logs for outbound WebSocket push traffic (equivalent to P4CODE_LOG_WS_EVENTS)."), Flag.withAlias("log-ws-events"), Flag.optional);
12766
- const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(Flag.withDescription("Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet."), Flag.optional);
12767
- const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(Flag.withSchema(PortSchema), Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."), Flag.optional);
12766
+ const tailscaleServeFlag$1 = Flag.boolean("tailscale-serve").pipe(Flag.withDescription("Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet."), Flag.optional);
12767
+ const tailscaleServePortFlag$1 = Flag.integer("tailscale-serve-port").pipe(Flag.withSchema(PortSchema), Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."), Flag.optional);
12768
12768
  const EnvServerConfig = Config.all({
12769
12769
  logLevel: Config.logLevel("P4CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
12770
12770
  traceMinLevel: Config.logLevel("P4CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
@@ -12806,8 +12806,8 @@ const sharedServerCommandFlags = {
12806
12806
  bootstrapFd: bootstrapFdFlag,
12807
12807
  autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
12808
12808
  logWebSocketEvents: logWebSocketEventsFlag,
12809
- tailscaleServeEnabled: tailscaleServeFlag,
12810
- tailscaleServePort: tailscaleServePortFlag
12809
+ tailscaleServeEnabled: tailscaleServeFlag$1,
12810
+ tailscaleServePort: tailscaleServePortFlag$1
12811
12811
  };
12812
12812
  const authLocationFlags = sharedServerLocationFlags;
12813
12813
  const resolveOptionPrecedence = (...values) => Option.firstSomeOf(values);
@@ -24098,6 +24098,92 @@ const removePinnedRuntimeInstallation = Effect.fn("cloud.pinned_runtime.remove")
24098
24098
  cause
24099
24099
  }))));
24100
24100
  });
24101
+ //#endregion
24102
+ //#region src/service/serviceOptions.ts
24103
+ /**
24104
+ * The options a supervised server keeps between installs.
24105
+ *
24106
+ * The unit file is generated, not edited: `p4c service update` rewrites it on
24107
+ * every upgrade. So anything configured by hand in it — a bind host, Tailscale
24108
+ * Serve — disappears at the next update, silently, weeks after the person who
24109
+ * added it has forgotten it was there. That is a worse failure than not
24110
+ * supporting the option at all, because the machine works until it does not.
24111
+ *
24112
+ * These options are therefore stored beside the server's other state and read
24113
+ * back when the unit is rendered. `install`, `update` and `status` all go
24114
+ * through the same path, so an option set once survives every later upgrade,
24115
+ * and `status` notices when the file and the unit disagree — which is what
24116
+ * makes `update` rewrite the unit after an option changes.
24117
+ *
24118
+ * @module service/serviceOptions
24119
+ */
24120
+ /**
24121
+ * Tailscale Serve puts the server on HTTPS at the machine's MagicDNS name.
24122
+ *
24123
+ * Worth being an option rather than a default: it publishes the server to
24124
+ * everything on the tailnet, which is a decision about exposure and not a
24125
+ * detail of how the service is launched.
24126
+ */
24127
+ const TailscaleServeOptions = Schema$1.Struct({
24128
+ enabled: Schema$1.Boolean,
24129
+ port: Schema$1.Int.check(Schema$1.isGreaterThan(0), Schema$1.isLessThanOrEqualTo(65535))
24130
+ });
24131
+ const ServiceOptions = Schema$1.Struct({ tailscaleServe: Schema$1.optional(TailscaleServeOptions) });
24132
+ const EMPTY_SERVICE_OPTIONS = {};
24133
+ const OptionsFromJson = Schema$1.fromJsonString(ServiceOptions);
24134
+ const decodeOptions = Schema$1.decodeUnknownExit(OptionsFromJson);
24135
+ const encodeOptions = Schema$1.encodeSync(OptionsFromJson);
24136
+ const serviceOptionsPath = (input) => input.path.join(input.baseDir, "userdata", "service-options.json");
24137
+ /**
24138
+ * Read the stored options, or none.
24139
+ *
24140
+ * A missing file is the ordinary case — most machines never set an option — and
24141
+ * an unreadable or malformed one is treated the same way rather than failing
24142
+ * the install. The cost of ignoring it is a service that starts without an
24143
+ * option; the cost of failing is a machine with no service at all, and the
24144
+ * second is worse for a file nobody edits by hand.
24145
+ */
24146
+ const readServiceOptions = Effect.fn("service.readServiceOptions")(function* (input) {
24147
+ const fileSystem = yield* FileSystem.FileSystem;
24148
+ const path = yield* Path.Path;
24149
+ const contents = yield* fileSystem.readFileString(serviceOptionsPath({
24150
+ baseDir: input.baseDir,
24151
+ path
24152
+ })).pipe(Effect.orElseSucceed(() => void 0));
24153
+ if (contents === void 0) return EMPTY_SERVICE_OPTIONS;
24154
+ const decoded = decodeOptions(contents);
24155
+ return decoded._tag === "Success" ? decoded.value : EMPTY_SERVICE_OPTIONS;
24156
+ });
24157
+ const writeServiceOptions = Effect.fn("service.writeServiceOptions")(function* (input) {
24158
+ const fileSystem = yield* FileSystem.FileSystem;
24159
+ const path = yield* Path.Path;
24160
+ const filePath = serviceOptionsPath({
24161
+ baseDir: input.baseDir,
24162
+ path
24163
+ });
24164
+ yield* fileSystem.makeDirectory(path.dirname(filePath), { recursive: true }).pipe(Effect.ignore);
24165
+ yield* writeFileStringAtomically({
24166
+ filePath,
24167
+ contents: `${encodeOptions(input.options)}\n`
24168
+ });
24169
+ });
24170
+ /**
24171
+ * The environment the unit sets, derived from the options.
24172
+ *
24173
+ * Pairs rather than a record so the rendered unit is byte-stable: a record's
24174
+ * iteration order is stable in practice but nothing says so, and `status`
24175
+ * compares the rendered unit against the installed one to decide whether an
24176
+ * update is needed. A reordering would read as a change forever.
24177
+ */
24178
+ const serviceEnvironmentFor = (options) => {
24179
+ const pairs = [];
24180
+ const tailscale = options.tailscaleServe;
24181
+ if (tailscale?.enabled === true) {
24182
+ pairs.push(["P4CODE_TAILSCALE_SERVE", "1"]);
24183
+ if (tailscale.port !== 443) pairs.push(["P4CODE_TAILSCALE_SERVE_PORT", String(tailscale.port)]);
24184
+ }
24185
+ return pairs;
24186
+ };
24101
24187
  const BOOT_SERVICE_UNIT_FILE = `p4code.service`;
24102
24188
  const BOOT_SERVICE_UNIT_ENV = "P4_BOOT_SERVICE_UNIT";
24103
24189
  /**
@@ -24158,6 +24244,7 @@ function renderBootServiceUnit(plan) {
24158
24244
  "WorkingDirectory=%h",
24159
24245
  `Environment=P4CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
24160
24246
  `Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
24247
+ ...plan.serviceEnvironment.map(([name, value]) => `Environment=${name}=${quoteSystemdValue(value)}`),
24161
24248
  `ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.p4EntryPath)} serve`,
24162
24249
  "Restart=always",
24163
24250
  "RestartSec=5",
@@ -24204,6 +24291,7 @@ function renderLaunchAgentPlist(plan) {
24204
24291
  ` <string>${escapeXmlText(plan.baseDir)}</string>`,
24205
24292
  ` <key>${escapeXmlText(BOOT_SERVICE_UNIT_ENV)}</key>`,
24206
24293
  ` <string>${escapeXmlText(LAUNCH_AGENT_PLIST_FILE)}</string>`,
24294
+ ...plan.serviceEnvironment.flatMap(([name, value]) => [` <key>${escapeXmlText(name)}</key>`, ` <string>${escapeXmlText(value)}</string>`]),
24207
24295
  " </dict>",
24208
24296
  " <key>RunAtLoad</key>",
24209
24297
  " <true/>",
@@ -24332,13 +24420,15 @@ const make$51 = Effect.fn("cloud.boot_service.make")(function* (input) {
24332
24420
  }) : new BootServiceInstallError({ cause: error })), Effect.tapError((error) => DateTime.now.pipe(Effect.flatMap((now) => fs.writeFileString(logPath, `${DateTime.formatIso(now)} ${error.message}\n`, { flag: "a" })), Effect.ignore)));
24333
24421
  });
24334
24422
  const plannedEntryPath = isEphemeralCacheEntry(host.cliEntryPath) ? runtimePaths.entryPath : host.cliEntryPath;
24423
+ const serviceOptions = yield* readServiceOptions({ baseDir: input.baseDir });
24335
24424
  const plan = {
24336
24425
  nodePath: host.execPath,
24337
24426
  p4EntryPath: plannedEntryPath,
24338
24427
  baseDir: input.baseDir,
24339
24428
  logPath,
24340
24429
  unitPath,
24341
- workingDirectory: homeDir
24430
+ workingDirectory: homeDir,
24431
+ serviceEnvironment: serviceEnvironmentFor(serviceOptions)
24342
24432
  };
24343
24433
  const install = Effect.gen(function* () {
24344
24434
  yield* requireSupportedPlatform;
@@ -24643,7 +24733,8 @@ const make$50 = Effect.fn("cloud.server_self_update.make")(function* (options) {
24643
24733
  baseDir: serverConfig.baseDir,
24644
24734
  logPath: path.join(serverConfig.logsDir, "boot-service.log"),
24645
24735
  unitPath,
24646
- workingDirectory: homeDir
24736
+ workingDirectory: homeDir,
24737
+ serviceEnvironment: []
24647
24738
  });
24648
24739
  yield* writeUnitAtomically(unitPath, unit).pipe(Effect.mapError((cause) => failWith("Could not update the systemd unit.", cause)));
24649
24740
  const reloadSystemd = Effect.fn("cloud.server_self_update.reload_systemd")(function* () {
@@ -82730,13 +82821,51 @@ function formatServiceStatus(status, cliVersion) {
82730
82821
  ...status.current ? [] : [" Next: Run `p4c service update`."]
82731
82822
  ].join("\n");
82732
82823
  }
82733
- const runServiceCommand = Effect.fn("cli.service.run")(function* (flags, run) {
82824
+ const runServiceCommand = Effect.fn("cli.service.run")(function* (flags, run, prepare) {
82734
82825
  const config = yield* resolveCliAuthConfig(flags, yield* GlobalFlag.LogLevel);
82735
82826
  const baseDirNotice = yield* describeNonDefaultBaseDir(config.baseDir);
82736
82827
  if (baseDirNotice !== null) yield* Console.error(baseDirNotice);
82828
+ if (prepare !== void 0) yield* prepare(config);
82737
82829
  return yield* run.pipe(Effect.tapError((error) => isBootServiceCommandError(error) ? BootService.pipe(Effect.flatMap((service) => Console.error(`Details: ${service.logPath}`))) : Effect.void), Effect.provide(Layer.mergeAll(bootServiceLayer(config), layer$52)));
82738
82830
  });
82739
- const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe(Command.withDescription("Install P4Code as a background service for this user."), Command.withHandler((flags) => runServiceCommand(flags, Effect.gen(function* () {
82831
+ /**
82832
+ * Options the installed unit carries, rather than ones this command consumes.
82833
+ *
82834
+ * Optional on purpose. Absent means "leave whatever is stored alone", so
82835
+ * re-running install to pick up a new CLI build does not quietly switch
82836
+ * Tailscale Serve off — which a plain boolean flag, false when unspecified,
82837
+ * would do every time.
82838
+ */
82839
+ const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(Flag.withDescription("Expose this server over HTTPS on your tailnet at its MagicDNS name. Use --no-tailscale-serve to turn it off."), Flag.optional);
82840
+ const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(Flag.withDescription(`HTTPS port for Tailscale Serve (default 443).`), Flag.optional);
82841
+ /**
82842
+ * Fold the flags into what is already stored, and persist.
82843
+ *
82844
+ * Written before the unit is rendered, because the renderer reads this file —
82845
+ * so `install` and `update` both produce a unit that matches, and `status`
82846
+ * compares against the same thing.
82847
+ */
82848
+ const applyServiceOptionFlags = Effect.fn("cli.service.applyOptionFlags")(function* (input) {
82849
+ if (Option.isNone(input.tailscaleServe) && Option.isNone(input.tailscaleServePort)) return;
82850
+ const stored = yield* readServiceOptions({ baseDir: input.baseDir });
82851
+ const enabled = Option.getOrElse(input.tailscaleServe, () => stored.tailscaleServe?.enabled ?? false);
82852
+ const port = Option.getOrElse(input.tailscaleServePort, () => stored.tailscaleServe?.port ?? 443);
82853
+ yield* writeServiceOptions({
82854
+ baseDir: input.baseDir,
82855
+ options: {
82856
+ ...stored,
82857
+ tailscaleServe: {
82858
+ enabled,
82859
+ port
82860
+ }
82861
+ }
82862
+ });
82863
+ });
82864
+ const serviceInstallCommand = Command.make("install", {
82865
+ ...projectLocationFlags,
82866
+ tailscaleServe: tailscaleServeFlag,
82867
+ tailscaleServePort: tailscaleServePortFlag
82868
+ }).pipe(Command.withDescription("Install P4Code as a background service for this user."), Command.withHandler((flags) => runServiceCommand(flags, Effect.gen(function* () {
82740
82869
  const result = yield* reconcileService();
82741
82870
  if (!result.changed) {
82742
82871
  yield* Console.log(`P4Code service is already installed with @p4code/cli@${version}.`);
@@ -82748,6 +82877,10 @@ const serviceInstallCommand = Command.make("install", projectLocationFlags).pipe
82748
82877
  cliVersion: version,
82749
82878
  platform: yield* HostProcessPlatform
82750
82879
  }));
82880
+ }), (config) => applyServiceOptionFlags({
82881
+ baseDir: config.baseDir,
82882
+ tailscaleServe: flags.tailscaleServe,
82883
+ tailscaleServePort: flags.tailscaleServePort
82751
82884
  }))));
82752
82885
  const serviceUpdateCommand = Command.make("update", projectLocationFlags).pipe(Command.withDescription("Update or repair the background service so it runs this CLI build, then restart it."), Command.withHandler((flags) => runServiceCommand(flags, Effect.gen(function* () {
82753
82886
  const result = yield* reconcileService();
@@ -82767,6 +82900,24 @@ const serviceUninstallCommand = Command.make("uninstall", projectLocationFlags).
82767
82900
  const removed = yield* (yield* BootService).uninstall;
82768
82901
  yield* Console.log(removed ? "Removed the P4Code service." : "P4Code service is not installed.");
82769
82902
  }))));
82903
+ /**
82904
+ * Restart without rewriting the unit.
82905
+ *
82906
+ * `update` restarts too, but only after deciding the unit is out of date — and
82907
+ * a global `npm i -g` upgrades in place, so the rendered unit is byte-identical
82908
+ * and `update` correctly reports there is nothing to do while the running
82909
+ * process still holds the old code. The service already knew how to do this;
82910
+ * only the terminal had no way to ask.
82911
+ */
82912
+ const serviceRestartCommand = Command.make("restart", projectLocationFlags).pipe(Command.withDescription("Restart the background service without changing its configuration."), Command.withHandler((flags) => runServiceCommand(flags, Effect.gen(function* () {
82913
+ const service = yield* BootService;
82914
+ if (!(yield* service.status).installed) {
82915
+ yield* Console.error("P4Code service is not installed. Install it with: p4c service install");
82916
+ return;
82917
+ }
82918
+ yield* service.restart;
82919
+ yield* Console.log("Restarted the P4Code service.");
82920
+ }))));
82770
82921
  const serviceStatusCommand = Command.make("status", projectLocationFlags).pipe(Command.withDescription("Show whether the P4Code background service is installed."), Command.withHandler((flags) => runServiceCommand(flags, Effect.gen(function* () {
82771
82922
  const service = yield* BootService;
82772
82923
  yield* Console.log(formatServiceStatus(yield* service.status, version));
@@ -82790,6 +82941,7 @@ const serviceCommand = Command.make("service").pipe(Command.withDescription("Man
82790
82941
  serviceInstallCommand,
82791
82942
  serviceUninstallCommand,
82792
82943
  serviceUpdateCommand,
82944
+ serviceRestartCommand,
82793
82945
  serviceStatusCommand
82794
82946
  ]));
82795
82947
  //#endregion
@@ -1,4 +1,4 @@
1
- import{$a as e,Ai as t,Ao as n,As as r,Br as i,Ff as a,Go as o,Gr as s,H as c,Ho as l,If as u,Ir as d,Jr as f,Jt as p,Kr as m,Mr as h,No as g,Pt as _,Qs as v,Qt as y,R as b,Ts as x,Uo as S,Wf as C,Wo as ee,ap as w,bs as T,g as E,ls as D,m as O,ms as k,o as A,p as j,qr as te,rn as ne,ro as re,sp as M,u as ie,up as N,w as P,zr as ae}from"./textarea-DHdA8g53.js";import{t as oe}from"./arrow-right-BG7cUHWK.js";import{a as se,n as F,o as ce,s as le}from"./fileCommentAnnotations-dnvCAKlJ.js";import{$t as I,B as ue,Bn as de,C as fe,Fn as pe,G as me,Hn as he,I as ge,In as _e,Ir as ve,J as ye,K as be,Kn as L,L as xe,Ln as Se,Lr as Ce,Nn as we,Pn as Te,Q as Ee,Qt as R,R as De,Rn as Oe,Sr as ke,T as z,Un as Ae,Vn as je,W as B,X as Me,Xt as V,Y as Ne,Yn as Pe,Z as Fe,Zt as H,_ as Ie,_r as Le,an as Re,cn as U,en as W,fn as ze,gr as Be,h as Ve,hr as He,ln as Ue,nn as We,nt as G,on as Ge,pn as Ke,q as qe,tn as Je,w as K,wn as Ye,xr as Xe,yr as Ze,z as Qe,zn as $e,zr as et}from"./index-DjvMZjfP.js";var tt=o(`columns-2`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M12 3v18`,key:`108xh3`}]]),nt=o(`pilcrow`,[[`path`,{d:`M13 4v16`,key:`8vvj80`}],[`path`,{d:`M17 4v16`,key:`7dpous`}],[`path`,{d:`M19 4H9.5a4.5 4.5 0 0 0 0 9H13`,key:`sh4n9v`}]]),rt=o(`rows-3`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M21 9H3`,key:`1338ky`}],[`path`,{d:`M21 15H3`,key:`9uk58r`}]]);function q(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}function J(e){let t=window.devicePixelRatio??1;return Math.round(e*t)/t}var it=`theme.disableLineNumbers.overflow.themeType.disableFileHeader.disableVirtualizationBuffers.preferredHighlighter.useCSSClasses.useTokenTransformer.tokenizeMaxLineLength.tokenizeMaxLength.unsafeCSS.diffStyle.diffIndicators.disableBackground.expandUnchanged.collapsedContextThreshold.lineDiffType.maxLineDiffLength.expansionLineCount.lineHoverHighlight.enableTokenInteractionsOnWhitespace.enableGutterUtility.__debugPointerEvents.enableLineSelection.controlledSelection.disableErrorHandling`.split(`.`),at=[`theme`,`disableLineNumbers`,`overflow`,`themeType`,`disableFileHeader`,`disableVirtualizationBuffers`,`preferredHighlighter`,`useCSSClasses`,`useTokenTransformer`,`tokenizeMaxLineLength`,`tokenizeMaxLength`,`unsafeCSS`,`lineHoverHighlight`,`enableTokenInteractionsOnWhitespace`,`enableGutterUtility`,`__debugPointerEvents`,`enableLineSelection`,`controlledSelection`,`disableErrorHandling`],ot=[`renderCustomHeader`,`renderHeaderPrefix`,`renderHeaderMetadata`,`renderAnnotation`,`renderGutterUtility`,`onPostRender`,`onGutterUtilityClick`,`onLineClick`,`onLineNumberClick`,`onLineEnter`,`onLineLeave`,`onTokenClick`,`onTokenEnter`,`onTokenLeave`],st=[`onLineSelected`,`onLineSelectionStart`,`onLineSelectionChange`,`onLineSelectionEnd`],ct=Symbol(`CodeView.itemOptionsState`);function lt(e,t){Object.defineProperty(e,ct,{configurable:!1,enumerable:!1,value:t})}function ut(e){return e[ct]}function Y(e,t,n){Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get(){return n(this)}})}var dt=120,ft=`--diffs-overflow-override`,pt=12e6,mt=1e6,ht=2e6,X=pt-ht,gt=pt-mt,Z=(()=>{let{navigator:e}=globalThis,t=e.userAgent,n=/iP(?:hone|ad|od)/.test(t),r=e.platform===`MacIntel`&&e.maxTouchPoints>1;return(n||r)&&/AppleWebKit/.test(t)&&/Safari/.test(t)&&!/(CriOS|FxiOS|EdgiOS|OPiOS)/.test(t)})(),_t=class e{static __STOP=!1;static __lastScrollPosition=0;type=`advanced`;config={overscrollSize:200,intersectionObserverMargin:0,resizeDebugging:!1};items=[];idToItem=new Map;selectedLines=null;instanceToItem=new Map;layoutDirtyIndex;pendingLayoutReset;renderOptionsRevision=0;slotCoordinator;slotSnapshot;scrollListeners=new Set;scrollHeight=0;containerHeight=-1;scrollTop=0;scrollPageOffset=0;scrollDirty=!0;scrollInteractionFixTimer;pointerEventsDisabled=!1;codeOverflowFix=!1;height=0;heightDirty=!0;windowSpecs={top:0,bottom:0};renderState={scrollTop:-1,firstIndex:-1,lastIndex:-1,stickyHeight:0,stickyTop:-1,stickyBottom:-1};itemMetricsCache=Re;fileOptionsPrototype;diffOptionsPrototype;pendingScrollTarget;pendingLayoutAnchor;shouldFixContainerFocus=!1;scrollAnimation;root;resizeObserver;container=document.createElement(`div`);stickyContainer=document.createElement(`div`);stickyOffset=document.createElement(`div`);elementPool=[];elementPoolVersion=0;elementPoolTracker=new WeakMap;pendingElementPool=[];options;workerManager;isContainerManaged;constructor(e={theme:Ue},t,n=!1){this.options=e,this.computeMetricsCache(e.itemMetrics),this.fileOptionsPrototype=this.createFileOptionsPrototype(),this.diffOptionsPrototype=this.createDiffOptionsPrototype(),this.workerManager=t,this.isContainerManaged=n,this.stickyOffset.style.contain=`layout size`,this.stickyContainer.style.position=`sticky`,this.stickyContainer.style.width=`100%`,this.stickyContainer.style.contain=`layout style inline-size`,this.stickyContainer.style.isolation=`isolate`,this.stickyContainer.style.display=`flex`,this.stickyContainer.style.flexDirection=`column`}getLayout(){return this.options.layout??Ge}computeMetricsCache(e){return this.itemMetricsCache={hunkLineCount:e?.hunkLineCount??Re.hunkLineCount,lineHeight:e?.lineHeight??Re.lineHeight,diffHeaderHeight:e?.diffHeaderHeight??Re.diffHeaderHeight,hunkSeparatorHeight:e?.hunkSeparatorHeight,spacing:e?.spacing??Re.spacing,paddingTop:e?.paddingTop,paddingBottom:e?.paddingBottom},this.itemMetricsCache}getSmoothScrollSettings(){return this.options.smoothScrollSettings??U}shouldDisablePointerEvents(){return this.options.pointerEventsOnScroll!==!0}shouldValidateItemHeights(){return ze&&this.options.__devOnlyValidateItemHeights===!0}validateRenderedItemHeight(e){if(!this.shouldValidateItemHeights()||e.element==null)return;let t=e.instance.getAdvancedStickySpecs();if(t==null)return;let n=t.height,r=e.element.getBoundingClientRect().height;n!==r&&console.error(`CodeView: reconciled item height does not match DOM height`,{id:e.item.id,type:e.type,index:e.index,version:e.version,expectedHeight:n,actualHeight:r,delta:r-n,stickyTopOffset:t.topOffset,virtualizedHeight:e.instance.getVirtualizedHeight(),top:e.top,scrollTop:this.getScrollTop(),windowSpecs:{...this.windowSpecs},element:e.element,instance:e.instance})}validateStickyContainerHeight(){if(!this.shouldValidateItemHeights())return;let{firstIndex:e,lastIndex:t,stickyHeight:n,stickyTop:r,stickyBottom:i}=this.renderState;if(e===-1||t===-1)return;let a=this.stickyContainer.getBoundingClientRect().height;Math.abs(a-n)<1||console.error(`CodeView: sticky container height does not match computed layout`,{computedStickyHeight:n,actualStickyHeight:a,delta:a-n,stickyTop:r,stickyBottom:i,firstIndex:e,lastIndex:t,firstStickySpecs:this.items[e]?.instance.getAdvancedStickySpecs(),lastStickySpecs:this.items[t]?.instance.getAdvancedStickySpecs(),scrollTop:this.getScrollTop(),scrollPageOffset:this.scrollPageOffset,windowSpecs:{...this.windowSpecs},stickyContainer:this.stickyContainer})}clearScrollInteractionTimer(){this.scrollInteractionFixTimer!=null&&(clearTimeout(this.scrollInteractionFixTimer),this.scrollInteractionFixTimer=void 0)}suspendScrollInteractions(){this.clearScrollInteractionTimer(),this.shouldDisablePointerEvents()&&!this.pointerEventsDisabled&&(this.stickyContainer.style.pointerEvents=`none`,this.pointerEventsDisabled=!0),Z&&!this.codeOverflowFix&&(this.stickyContainer.style.setProperty(ft,`hidden`),this.codeOverflowFix=!0),this.scrollInteractionFixTimer=setTimeout(this.restoreScrollInteractions,dt)}restoreScrollInteractions=()=>{this.clearScrollInteractionTimer(),this.pointerEventsDisabled&&=(this.stickyContainer.style.removeProperty(`pointer-events`),!1),this.codeOverflowFix&&=(this.stickyContainer.style.setProperty(ft,`auto`),!1)};syncLayout(){let{gap:e,paddingBottom:t,paddingTop:n}=this.getLayout();this.stickyContainer.style.gap=`${e}px`,this.container?.style.setProperty(`margin-top`,`${n}px`),this.container?.style.setProperty(`margin-bottom`,`${t}px`)}setup(t){if(this.root!=null)throw Error(`CodeView.setup: already setup`);this.workerManager?.subscribeToThemeChanges(this),this.root=t,this.root.style.overflowAnchor=`none`,this.root.hasAttribute(`tabindex`)||(this.root.tabIndex=-1),this.container??=document.createElement(`div`),this.container.style.contain=`layout style`,this.syncLayout(),this.container.appendChild(this.stickyOffset),this.container.appendChild(this.stickyContainer),this.root.appendChild(this.container),this.scrollDirty=!0,this.heightDirty=!0,this.resizeObserver=new ResizeObserver(this.handleResize),this.resizeObserver.observe(this.stickyContainer),this.root.addEventListener(`scroll`,this.handleScroll,{passive:!0}),this.root.addEventListener(`wheel`,this.clearPendingScroll,{passive:!0}),this.root.addEventListener(`touchstart`,this.clearPendingScroll,{passive:!0}),this.root.addEventListener(`pointerdown`,this.clearPendingScroll,{passive:!0}),this.root.addEventListener(`keydown`,this.clearPendingScroll,{passive:!0}),this.resizeObserver.observe(this.root),this.render(!0),window.__INSTANCE=this,window.__TOGGLE=()=>{e.__STOP?(e.__STOP=!1,this.scrollTo({type:`position`,position:e.__lastScrollPosition,behavior:`instant`})):(e.__lastScrollPosition=this.getScrollTop(),e.__STOP=!0)}}reset(){this.restoreScrollInteractions(),this.cleanAllRenderedItems(),this.selectedLines=null,this.items.length=0,this.idToItem.clear(),this.instanceToItem.clear(),this.layoutDirtyIndex=void 0,this.pendingLayoutReset=void 0,this.stickyContainer.textContent=``,this.stickyOffset.style.height=``,this.container?.style.removeProperty(`height`),this.containerHeight=-1,this.windowSpecs={top:0,bottom:0},this.pendingLayoutAnchor=void 0,this.shouldFixContainerFocus=!1,this.height=0,this.scrollTop=0,this.scrollPageOffset=0,this.scrollHeight=0,this.scrollDirty=!0,this.heightDirty=!0,this.resetRenderState(),this.isContainerManaged||this.flushSlotCoordinator()}cleanUp(){this.reset(),this.clearElementPool(),this.restoreScrollInteractions(),this.workerManager?.unsubscribeToThemeChanges(this),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.root?.removeEventListener(`scroll`,this.handleScroll),this.root?.removeEventListener(`wheel`,this.clearPendingScroll),this.root?.removeEventListener(`touchstart`,this.clearPendingScroll),this.root?.removeEventListener(`pointerdown`,this.clearPendingScroll),this.root?.removeEventListener(`keydown`,this.clearPendingScroll),this.root?.style.removeProperty(`overflow-anchor`),this.container?.remove(),this.stickyOffset.remove(),this.stickyContainer.remove(),this.stickyContainer.textContent=``,this.root=void 0,this.container=void 0}cleanAllRenderedItems(){if(this.renderState.firstIndex!==-1)for(let e=this.renderState.firstIndex;e<=this.renderState.lastIndex;e++){let t=this.items[e];if(t==null)throw Error(`CodeView.cleanAllRenderedItems: Item does not exist at index: ${e}`);this.releaseRenderedItem(t)}}primeScrollTarget(e){e.type!==`position`&&this.idToItem.get(e.id)?.instance.primeHighlightCache()}getElementPoolLimit(){let e=this.getHeight()+this.config.overscrollSize*2,{diffHeaderHeight:t}=this.itemMetricsCache;return Math.max(8,Math.ceil(e/Math.max(t,10))+1)*(this.isContainerManaged?2:1)}acquireElement(){this.promotePendingPooledElements();let e=this.elementPool.pop();for(;e!=null&&!this.isElementPoolGenerationCurrent(e);)e=this.elementPool.pop();return e??=document.createElement(Ke),this.markElementPoolGenerationCurrent(e),e}releaseRenderedItem(e){let{element:t}=e;t!=null&&this.renderedItemOwnsFocus(t)&&(this.shouldFixContainerFocus=!0),e.instance.cleanUp(!0),e.element=void 0,t!=null&&(t.remove(),this.cleanElement(t),this.queueElementForPool(t))}renderedItemOwnsFocus(e){let{activeElement:t}=document;return t===e||e.contains(t)||e.shadowRoot?.activeElement!=null}fixContainerFocus(){this.shouldFixContainerFocus&&(this.shouldFixContainerFocus=!1,this.root?.focus({preventScroll:!0}))}cleanElement(e){let{shadowRoot:t}=e;if(t!=null)for(let e of Array.from(t.children))St(e)||e.remove();this.isContainerManaged||e.replaceChildren()}queueElementForPool(e){let t=this.getElementPoolLimit();!this.isElementPoolGenerationCurrent(e)||this.getElementPoolSize()>=t||(this.isElementClean(e)?this.elementPool.push(e):this.pendingElementPool.push(e))}promotePendingPooledElements(){if(this.pendingElementPool.length===0)return;let{pendingElementPool:e}=this;this.pendingElementPool=[];let t=this.getElementPoolLimit();for(let n of e)this.isElementPoolGenerationCurrent(n)&&this.isElementClean(n)&&this.elementPool.length<t?this.elementPool.push(n):this.isElementPoolGenerationCurrent(n)&&this.getElementPoolSize()<t&&this.pendingElementPool.push(n)}isElementClean(e){return e.childNodes.length===0}getElementPoolSize(){return this.elementPool.length+this.pendingElementPool.length}clearElementPool(){this.elementPool.length=0,this.pendingElementPool.length=0}invalidateElementPool(){this.elementPoolVersion++,this.clearElementPool()}markElementPoolGenerationCurrent(e){this.elementPoolTracker.set(e,this.elementPoolVersion)}isElementPoolGenerationCurrent(e){return this.elementPoolTracker.get(e)===this.elementPoolVersion}resolveEffectiveScrollBehavior(e,t){return q()?`instant`:e.behavior===`smooth-auto`?Math.abs(t-this.getScrollTop())<=this.getHeight()*10?`smooth`:`instant`:e.behavior??`instant`}scrollTo(e){if(this.root==null)return;let t=this.normalizeScrollTarget(e);if(t==null)return;let n=this.resolveScrollTargetTop(t);n!=null&&(this.primeScrollTarget(t),this.resolveEffectiveScrollBehavior(t,n)===`smooth`?this.scrollAnimation??={position:this.getScrollTop(),velocity:0,lastTimestamp:performance.now()}:this.scrollAnimation=void 0,this.suspendScrollInteractions(),this.pendingLayoutAnchor=void 0,this.pendingScrollTarget=t,this.render())}setSelectedLines(e,t){this.applySelectedLines(e,t)}getSelectedLines(){return this.selectedLines}clearSelectedLines(e){this.applySelectedLines(null,e)}getItem(e){return this.idToItem.get(e)?.item}updateItem(e){let t=this.idToItem.get(e.id);return t==null?(console.error(`CodeView.updateItem: unknown item id "${e.id}"`),!1):this.syncItemRecord(t,e)?(this.markItemLayoutDirty(t),this.scrollDirty=!0,this.render(),this.syncSelection(),!0):!1}updateItemId(e,t){if(e===t)return!0;let n=this.idToItem.get(e);return n==null?(console.error(`CodeView.updateItemId: unknown item id "${e}"`),!1):this.idToItem.has(t)?(console.error(`CodeView.updateItemId: duplicate item id "${t}"`),!1):(this.idToItem.delete(e),n.item.id=t,this.idToItem.set(t,n),this.updateItemOptionsId(n.instance.options,t),this.selectedLines?.id===e&&(this.selectedLines={...this.selectedLines,id:t},this.options.onSelectedLinesChange?.(this.selectedLines)),this.renamePendingScrollTarget(e,t),this.renamePendingLayoutAnchor(e,t),this.render(),!0)}addItem(e){this.addItems([e]),this.syncSelection()}addItems(e){this.appendItemsInternal(e),this.syncSelection()}setItems(e){e.length===0?this.reset():this.items.length===0?this.appendItemsInternal(e):this.tryAppendItems(e)||this.reconcileItems(e),this.syncSelection()}appendItemsInternal(e,t=!0){if(e.length===0)return;let n=this.getLayout(),r=this.items.length===0?0:this.scrollHeight+n.gap,i=r;for(let t=0;t<e.length;t++){let i=e[t];if(i==null)throw Error(`CodeView.appendItemsInternal: missing input item`);if(this.idToItem.has(i.id))throw Error(`CodeView.addItem: duplicate id "${i.id}"`);let a=this.createItem(i,this.items.length,r);this.items.push(a),this.idToItem.set(a.item.id,a),this.instanceToItem.set(a.instance,a),a.height=vt(a),r+=a.height+n.gap}this.scrollHeight=r-n.gap,this.scrollDirty=!0,t&&(this.canSkipRenderForAppend(i)?this.syncContainerHeight():this.render())}canSkipRenderForAppend(e){return this.container!=null&&this.renderState.firstIndex!==-1&&this.pendingScrollTarget==null&&this.scrollAnimation==null&&this.layoutDirtyIndex==null&&e>this.windowSpecs.bottom}onThemeChange(){this.invalidateElementPool()}setOptions(e){if(e==null)return;this.capturePendingLayoutAnchor();let{options:t}=this,n=this.getLayout(),{itemMetricsCache:r}=this;yt(t,e)&&this.invalidateElementPool(),this.options=e;let i=this.computeMetricsCache(e.itemMetrics),a=!W(r,i),o=!W(n,this.getLayout());o&&this.syncLayout();let s=a||bt(t,e);if(s){let n=this.pendingLayoutReset;this.pendingLayoutReset={metrics:a?i:n?.metrics,resetFileLayoutCache:!0,resetDiffLayoutCache:!0,includeEstimatedDiffHeights:n?.includeEstimatedDiffHeights===!0||a||xt(t,e)}}(o||s)&&(this.markLayoutDirtyFromIndex(0),this.scrollDirty=!0),R(t,e)||this.renderOptionsRevision++,!this.isContainerManaged&&this.items.length>0&&this.render()}capturePendingLayoutAnchor(){this.root==null||this.items.length===0||this.pendingScrollTarget!=null||(this.pendingLayoutAnchor=this.getScrollAnchor(this.getScrollTop()))}render(t=!1){e.__STOP||(t?(Je(this.computeRenderRangeAndEmit),this.computeRenderRangeAndEmit()):We(this.computeRenderRangeAndEmit))}instanceChanged(e,t){let n=this.instanceToItem.get(e);if(n==null)throw Error(`CodeView.instanceChanged: An instance has changed that is not registered`);t&&this.markItemLayoutDirty(n),this.render()}getWindowSpecs(){return this.windowSpecs}getContainerElement(){return this.root}getRenderedItems(){let{firstIndex:e,lastIndex:t}=this.renderState;if(e===-1||t===-1||t<e)return[];let n=[];for(let r=e;r<=t;r++){let e=this.items[r];e?.element!=null&&(e.type===`diff`?n.push({id:e.item.id,type:`diff`,item:e.item,version:e.version,element:e.element,instance:e.instance}):n.push({id:e.item.id,type:`file`,item:e.item,version:e.version,element:e.element,instance:e.instance}))}return n}setSlotCoordinator(e){return e===this.slotCoordinator?!1:(this.slotCoordinator=e,this.slotSnapshot=void 0,!0)}getSlotSnapshot(e){return Ot(this.getRenderedItems(),e)}subscribeToScroll(e){return this.scrollListeners.add(e),()=>{this.scrollListeners.delete(e)}}getLocalTopForInstance(e){let t=this.instanceToItem.get(e);if(t==null)throw Error(`CodeView.getLocalTopForInstance: unknown virtualized instance`);return t.top}getTopForItem(e){let t=this.idToItem.get(e);if(t!=null)return t.top+this.getLayout().paddingTop}createItem(e,t,n){let{itemMetricsCache:r}=this;if(e.type===`diff`){let i=new Ee(this.createDiffOptions(e.id),this,r,this.workerManager,this.isContainerManaged);return{type:`diff`,item:e,version:e.version,index:t,top:n,height:0,element:void 0,renderedOptionsRevision:this.renderOptionsRevision,instance:i}}let i=new le(this.createFileOptions(e.id),this,r,this.workerManager,this.isContainerManaged);return{type:`file`,item:e,version:e.version,index:t,top:n,height:0,element:void 0,renderedOptionsRevision:this.renderOptionsRevision,instance:i}}applySelectedLines(e,t){let{selectedLines:n}=this;e==null&&n==null||e!=null&&n?.id===e.id&&H(n.range,e.range)||(n!=null&&n.id!==e?.id&&this.idToItem.get(n.id)?.instance.setSelectedLines(null,{notify:!1}),this.selectedLines=e,this.idToItem.get(e?.id??``)?.instance.setSelectedLines(e?.range??null,t))}syncSelection(){if(this.selectedLines==null)return;let e=this.idToItem.get(this.selectedLines.id);if(e==null){this.selectedLines=null;return}e.instance.setSelectedLines(this.selectedLines.range,{notify:!1})}renamePendingScrollTarget(e,t){let{pendingScrollTarget:n}=this;n==null||n.type===`position`||n.id!==e||(this.pendingScrollTarget={...n,id:t})}renamePendingLayoutAnchor(e,t){this.pendingLayoutAnchor?.id===e&&(this.pendingLayoutAnchor.id=t)}createFileOptionsPrototype(){let e={};for(let t of at)Y(e,t,()=>this.options[t]);Y(e,`stickyHeader`,()=>this.options.stickyHeaders),Y(e,`collapsed`,e=>this.getItemOptions(ut(e),`file`)?.item.collapsed===!0);for(let t of ot)this.defineItemSharedCallback(e,`file`,t);for(let t of st)this.defineItemSelectionCallback(e,`file`,t);return e}createDiffOptionsPrototype(){let e={};for(let t of it)Y(e,t,()=>this.options[t]);Y(e,`stickyHeader`,()=>this.options.stickyHeaders),Y(e,`hunkSeparators`,()=>this.options.hunkSeparators),Y(e,`collapsed`,e=>this.getItemOptions(ut(e),`diff`)?.item.collapsed===!0);for(let t of ot)this.defineItemSharedCallback(e,`diff`,t);for(let t of st)this.defineItemSelectionCallback(e,`diff`,t);return e}createFileOptions(e){let t=Object.create(this.fileOptionsPrototype);return lt(t,{id:e}),t}createDiffOptions(e){let t=Object.create(this.diffOptionsPrototype);return lt(t,{id:e}),t}updateItemOptionsId(e,t){ut(e).id=t}getItemOptions(e,t){let n=this.idToItem.get(e.id);if(!(n==null||n.type!==t))return n}defineItemSharedCallback(e,t,n){Y(e,n,e=>{if(this.options[n]==null)return;let r=ut(e),i=r.callbackCache??={},a=i[n];return a??(a=((...e)=>{let i=this.getItemOptions(r,t);if(i==null)return;let a=this.options[n];return a?.(...e,i)}),i[n]=a),a})}defineItemSelectionCallback(e,t,n){Y(e,n,e=>{if(this.options.enableLineSelection!==!0)return;let r=ut(e),i=r.callbackCache??={},a=i[n];return a??(a=(e=>{let i=this.getItemOptions(r,t);if(i==null)return;let a=e==null?null:{id:i.item.id,range:e};this.options.controlledSelection!==!0&&(e!=null||this.selectedLines?.id===i.item.id)&&this.applySelectedLines(a,{notify:!1}),this.options.onSelectedLinesChange?.(a);let o=this.options[n];return o?.(e,i)}),i[n]=a),a})}markLayoutDirtyFromIndex(e){this.layoutDirtyIndex=Math.min(this.layoutDirtyIndex??e,e)}markItemLayoutDirty(e){if(this.items[e.index]!==e)throw Error(`CodeView.markItemLayoutDirty: unknown item id "${e.item.id}"`);this.markLayoutDirtyFromIndex(e.index)}tryAppendItems(e){if(e.length<=this.items.length)return!1;for(let t=0;t<this.items.length;t++){let n=this.items[t];if(n==null)throw Error(`CodeView.tryAppendItems: missing existing item`);let r=e[t];if(r==null||n.item.id!==r.id||n.type!==r.type)return!1}for(let t=0;t<this.items.length;t++){let n=this.items[t];if(n==null)throw Error(`CodeView.tryAppendItems: missing existing item`);let r=e[t];if(r==null)throw Error(`CodeView.tryAppendItems: append candidate missing prefix item`);this.syncItemRecord(n,r)&&this.markLayoutDirtyFromIndex(t)}return this.appendItemsInternal(e.slice(this.items.length),!1),this.scrollDirty=!0,this.render(),!0}reconcileItems(e){let{items:t,idToItem:n}=this,r=new Set(t),i=[],a=new Map,o=new Map,s;for(let c=0;c<e.length;c++){let l=e[c];if(l==null)throw Error(`CodeView.reconcileItems: missing input item`);if(a.has(l.id))throw Error(`CodeView.setItems: duplicate id "${l.id}"`);let u=n.get(l.id),d=u!=null&&u.type===l.type?u:this.createItem(l,c,0);d.index=c,u!=null&&u.type===l.type?(r.delete(u),this.syncItemRecord(d,l)&&(s=Math.min(s??c,c))):s=Math.min(s??c,c),t[c]!==d&&(s=Math.min(s??c,c)),i.push(d),a.set(l.id,d),o.set(d.instance,d)}for(let e=0;e<t.length;e++){let n=t[e];if(n==null||!r.has(n))continue;this.releaseRenderedItem(n);let a=Math.max(i.length-1,0);s=Math.min(s??a,a)}s!=null&&(this.items=i,this.idToItem=a,this.instanceToItem=o,this.renderState.firstIndex>=i.length?this.resetRenderState():this.renderState.lastIndex>=i.length&&(this.renderState.lastIndex=i.length-1),this.markLayoutDirtyFromIndex(s),this.scrollDirty=!0,this.render())}syncItemRecord(e,t){if(e.type!==t.type)throw Error(`CodeView.syncItemRecord: type mismatch for id "${t.id}"`);return e.version===t.version?!1:(e.item=t,e.version=t.version,e.renderedOptionsRevision=-1,!0)}getMaxScrollTopForHeight(e){let{paddingBottom:t,paddingTop:n}=this.getLayout();return Math.max(n+e+t-this.getHeight(),0)}getMaxScrollTop(){return this.getMaxScrollTopForHeight(this.getScrollHeight())}shouldRebaseScroll(){return this.getMaxScrollTop()>gt}getPagedScrollHeight(){return this.shouldRebaseScroll()?Math.min(this.getScrollHeight(),pt):this.getScrollHeight()}getMaxPagedScrollTop(){return this.getMaxScrollTopForHeight(this.getPagedScrollHeight())}clampPagedScrollTop(e){let t=this.getMaxPagedScrollTop();return Math.max(0,Math.min(e,t))}clampScrollTop(e){let t=this.getMaxScrollTop();return Math.max(0,Math.min(e,t))}getMaxScrollPageOffset(){return Math.max(this.getMaxScrollTop()-this.getMaxPagedScrollTop(),0)}clampScrollPageOffset(e){let t=this.getMaxScrollPageOffset();return Math.max(0,Math.min(e,t))}resolveScrollPageWindow(e,t){let n=J(this.clampPagedScrollTop(t)),r=this.clampScrollPageOffset(e-n);return n=J(this.clampPagedScrollTop(e-r)),r=this.clampScrollPageOffset(e-n),{pagedScrollTop:n,scrollPageOffset:r}}resolvePagedScrollPosition(e){if(!this.shouldRebaseScroll())return{pagedScrollTop:this.clampPagedScrollTop(e),scrollPageOffset:0};let t=this.clampScrollPageOffset(this.scrollPageOffset),n=e-t,r=this.getMaxPagedScrollTop(),i=this.getMaxScrollPageOffset(),a=n>gt&&t<i,o=n<mt&&t>0;return n<0||n>r||a||o?this.resolveScrollPageWindow(e,o?Math.min(X,r):ht):{pagedScrollTop:J(this.clampPagedScrollTop(n)),scrollPageOffset:t}}needsScrollPageUpdate(e){let t=J(this.clampScrollTop(e)),{scrollPageOffset:n}=this.resolvePagedScrollPosition(t);return n!==this.scrollPageOffset}getPagedLayoutTop(e){return this.shouldRebaseScroll()?Math.max(e-this.scrollPageOffset,0):e}getStickyHeaderOffset(){return this.options.stickyHeaders===!0&&this.options.disableFileHeader!==!0?this.itemMetricsCache.diffHeaderHeight:0}getScrollTargetRect(e){let t=this.idToItem.get(e.id);if(t==null){console.warn(`CodeView.scrollTo: unknown item id "${e.id}"`);return}if(e.type===`item`)return{top:t.top,height:t.height};if(e.type===`range`){let n=this.getRangeScrollPosition(t,e);if(n==null){console.warn(`CodeView.scrollTo: unable to resolve range ${Ct(e.range)} for item "${e.id}"`);return}return{top:t.top+n.top,height:n.height}}let n=this.getLineScrollPosition(t,e);if(n==null){console.warn(`CodeView.scrollTo: unable to resolve line ${e.lineNumber} for item "${e.id}"`);return}return{top:t.top+n.top,height:n.height}}normalizeScrollTarget(e){if(e.type===`position`||e.align!==`nearest`)return e;let t=this.getScrollTargetRect(e);if(t==null)return;let n=e.offset??0,r=this.getLayout().paddingTop+t.top,i=r+t.height,a=this.getScrollTop(),o=a+(e.type===`line`||e.type===`range`?this.getStickyHeaderOffset():0),s=a+this.getHeight();if(!(r-n<=o&&i+n>=s)){if(r-n<o)return{...e,align:`start`};if(i+n>s)return{...e,align:`end`}}}resolveScrollTargetTop(e){if(e.type===`position`){let t=this.clampScrollTop(e.position);return t===e.position?this.clampScrollTop(e.position-this.getStickyHeaderOffset()):t}let t=this.idToItem.get(e.id);if(t==null){console.warn(`CodeView.scrollTo: unknown item id "${e.id}"`);return}if(e.type===`item`)return this.clampScrollTop(this.resolveAlignedScrollPosition(t.top,t.height,e.align,e.offset));if(e.type===`range`){let n=this.getRangeScrollPosition(t,e);if(n==null){console.warn(`CodeView.scrollTo: unable to resolve range ${Ct(e.range)} for item "${e.id}"`);return}return this.clampScrollTop(this.resolveAlignedScrollPosition(t.top+n.top,n.height,e.align,e.offset,this.getStickyHeaderOffset()))}let n=this.getLineScrollPosition(t,e);if(n==null){console.warn(`CodeView.scrollTo: unable to resolve line ${e.lineNumber} for item "${e.id}"`);return}return this.clampScrollTop(this.resolveAlignedScrollPosition(t.top+n.top,n.height,e.align,e.offset,this.getStickyHeaderOffset()))}resolveAlignedScrollPosition(e,t,n,r=0,i=0){e+=this.getLayout().paddingTop;let a=this.getHeight();return n===`center`&&t+r<a?e-(a-t)/2+r:n===`end`?e-(a-t)+r:e-i-r}getLineScrollPosition(e,t){return e.type===`diff`?e.instance.getLinePosition(t.lineNumber,t.side):e.instance.getLinePosition(t.lineNumber)}getRangeScrollPosition(e,t){let{range:n}=t,r=this.getLineScrollPosition(e,{type:`line`,id:t.id,lineNumber:n.start,side:n.side}),i=this.getLineScrollPosition(e,{type:`line`,id:t.id,lineNumber:n.end,side:n.endSide??n.side});if(r==null||i==null)return;let a=r.top,o=a+r.height,s=i.top,c=s+i.height,l=Math.min(a,s);return{top:l,height:Math.max(o,c)-l}}computeTargetScrollTopForFrame(e,t){if(this.pendingScrollTarget==null)return e;let n=this.resolveScrollTargetTop(this.pendingScrollTarget);if(n==null)return e;let{scrollAnimation:r}=this;return r==null?n:this.computeSpringStep(r,n,t).position}computeSpringStep(e,t,n){let r=Math.max(0,n-e.lastTimestamp),{omega:i}=this.getSmoothScrollSettings(),a=Math.exp(-i*r),o=e.position-t,s=e.velocity+i*o;return{position:t+(o+s*r)*a,velocity:(s*(1-i*r)-i*o)*a}}advanceScrollAnimation(e,t){if(this.pendingScrollTarget==null)return;let n=this.resolveScrollTargetTop(this.pendingScrollTarget);if(n==null){this.pendingScrollTarget=void 0,this.scrollAnimation=void 0;return}let r=this.scrollAnimation;if(r==null)return n;r.position+=t;let{position:i,velocity:a}=this.computeSpringStep(r,n,e);r.lastTimestamp=e,r.position=i,r.velocity=a;let{positionEpsilon:o,velocityEpsilon:s}=this.getSmoothScrollSettings();return Math.abs(n-i)<=o&&Math.abs(a)<=s?(r.position=n,r.velocity=0,this.scrollAnimation=void 0,n):r.position}computeRenderRangeAndEmit=(t=performance.now())=>{if(e.__STOP||this.container==null)return;let n=this.getHeight(),r=this.getScrollTop(),i=r,a=this.pendingLayoutAnchor!=null,o=this.getScrollAnchor(i);if(this.layoutDirtyIndex!=null&&(this.recomputeLayout(this.layoutDirtyIndex,this.pendingLayoutReset),this.layoutDirtyIndex=void 0,this.pendingLayoutReset=void 0,a=!0),a&&o!=null){let e=this.resolveAnchoredScrollTop(o);if(e!=null){let t=e-i;i=e,this.scrollAnimation!=null&&(this.scrollAnimation.position+=t)}}a&&(i=this.clampScrollTop(i),this.syncContainerHeight());let s=this.computeTargetScrollTopForFrame(i,t),c=!a&&(this.renderState.scrollTop===-1||Math.abs(s-this.renderState.scrollTop)>n+this.config.overscrollSize*2);c&&(o=void 0),this.windowSpecs=V({scrollTop:s,height:n,scrollHeight:this.getScrollHeight(),fitPerfectly:c,fitPerfectlyOverscroll:this.getFitPerfectlyOverscroll(),overscrollSize:this.config.overscrollSize});let l=r;(this.pendingScrollTarget!=null&&s!==l||this.needsScrollPageUpdate(s))&&(this.applyScrollFix(s,l,this.windowSpecs),l=s);let{top:u,bottom:d}=this.windowSpecs,{firstIndex:f,lastIndex:p}=this.renderState;if(f>=0)for(let e=f;e<=p;e++){let t=this.items[e];if(t==null)throw Error(`CodeView.computeRenderRangeAndEmit: No item at index: ${e}`);t.top>u-t.height&&t.top<=d||this.releaseRenderedItem(t)}let m,h=new Set,g=this.findFirstVisibleIndex(u),_=this.findLastVisibleIndex(d);for(let e=g;e<=_;e++){let t=this.items[e];if(t==null)throw Error(`CodeView.computeRenderRangeAndEmit: missing item`);let{instance:n}=t;t.element==null?(t.element=this.acquireElement(),Et(this.stickyContainer,t.element,m),n.virtualizedSetup(),Tt(t,t.element)&&(t.renderedOptionsRevision=this.renderOptionsRevision,h.add(t)),m=t.element):(Et(this.stickyContainer,t.element,m),Tt(t,void 0,t.renderedOptionsRevision!==this.renderOptionsRevision)&&(t.renderedOptionsRevision=this.renderOptionsRevision,h.add(t)),m=t.element)}this.renderState.firstIndex=g<=_?g:-1,this.renderState.lastIndex=_,this.flushSlotCoordinator(),this.reconcileRenderedItems(h),this.syncContainerHeight(),this.updateStickyPositioning();let v=o==null?void 0:this.resolveAnchoredScrollTop(o);o===this.pendingLayoutAnchor&&(this.pendingLayoutAnchor=void 0);let y=v==null?0:v-i,b=s,x=!1;if(this.pendingScrollTarget!=null){let e=this.advanceScrollAnimation(t,y);e==null?b=i:(b=e,x=!0)}else b=v??s;b!==l&&(this.applyScrollFix(b,l,this.windowSpecs),l=b),x&&this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0),this.renderState.scrollTop=J(l),this.flushManagers(h),this.validateStickyContainerHeight(),this.fixContainerFocus(),(c||this.scrollAnimation!=null)&&this.render()};flushManagers(e){for(let t of e)t.instance.flushManagers()}syncContainerHeight(){let e=this.getPagedScrollHeight();this.container==null||this.containerHeight===e||(this.container.style.height=`${e}px`,this.containerHeight=e)}getStickyBounds(e){let{firstIndex:t,lastIndex:n}=e==null?this.renderState:{firstIndex:this.findFirstVisibleIndex(e.top),lastIndex:this.findLastVisibleIndex(e.bottom)};if(t===-1||n===-1||t>n)return;let r=this.items[t]?.instance.getAdvancedStickySpecs(e),i=this.items[n]?.instance.getAdvancedStickySpecs(e);if(!(r==null||i==null))return{stickyTop:this.getPagedLayoutTop(Math.max(r.topOffset,0)),stickyBottom:this.getPagedLayoutTop(i.topOffset+i.height)}}applyStickyPositioning({stickyTop:e,stickyBottom:t}){let n=this.getHeight(),{itemMetricsCache:r}=this,i=t-e;this.renderState.stickyHeight=i,this.renderState.stickyTop=e,this.renderState.stickyBottom=t,this.stickyOffset.style.height=`${e}px`;let a=(Math.random()*r.lineHeight>>0)*-1,o=-Math.max(i+a,0)+n;this.stickyContainer.style.top=`${o}px`,this.stickyContainer.style.bottom=`${o+r.diffHeaderHeight}px`}syncPagedScrollScaffolding(e){this.syncContainerHeight();let t=this.getStickyBounds(e);t!=null&&this.applyStickyPositioning(t)}reconcileRenderedItems(e){let{firstIndex:t,lastIndex:n}=this.renderState;if(t===-1)return;let r=-1,i=!1;for(let a=t;a<this.items.length&&!(!i&&a>n);a++){let t=this.items[a];if(t==null)throw Error(`CodeView.reconcileRenderedItems: Invalid item`);r===-1?r=t.top:t.top!==r&&(t.top=r,t.instance.syncVirtualizedTop(),i=!0),(e==null?a<=n:e.has(t))&&(t.instance.reconcileHeights()&&(i=!0,t.height=t.instance.getVirtualizedHeight()),this.validateRenderedItemHeight(t)),r+=t.instance.getVirtualizedHeight(),a<this.items.length-1&&(r+=this.getLayout().gap)}i&&r!=null&&(this.scrollDirty=!0,this.scrollHeight=r)}updateStickyPositioning(){let e=this.getStickyBounds();if(e==null)return;let{stickyTop:t,stickyBottom:n}=e;n-t===this.renderState.stickyHeight&&t===this.renderState.stickyTop&&n===this.renderState.stickyBottom||this.applyStickyPositioning(e)}handleScroll=()=>{e.__STOP||(this.suspendScrollInteractions(),this.scrollDirty=!0,this.notifyScroll(),this.render())};clearPendingScroll=()=>{this.pendingScrollTarget=void 0,this.pendingLayoutAnchor=void 0,this.scrollAnimation=void 0};handleResize=e=>{for(let t of e)if(t.target===this.stickyContainer){if(t.borderBoxSize[0].blockSize!==this.renderState.stickyHeight){let e=this.getScrollTop(),t=this.getScrollAnchor(e);this.reconcileRenderedItems(),this.updateStickyPositioning();let n=t==null?void 0:this.resolveAnchoredScrollTop(t);if(n!=null){let t=n-e;this.applyScrollFix(n,e,this.windowSpecs),this.scrollAnimation!=null&&(this.scrollAnimation.position+=t)}this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0)}}else this.scrollDirty=!0,this.heightDirty=!0,this.render()};getScrollAnchorViewportTop(e,t){return e<t?t+this.getStickyHeaderOffset():t}getScrollAnchor(e){if(this.pendingLayoutAnchor!=null)return this.pendingLayoutAnchor;let{firstIndex:t,lastIndex:n,stickyTop:r,stickyBottom:i}=this.renderState;if(t===-1||n===-1)return;let a=this.getHeight();if(!(r===-1||i===-1))for(let r=t;r<=n;r++){let t=this.items[r];if(t==null)continue;let n=this.getLayout().paddingTop+t.top;if(n+t.height<=e)continue;if(n>=e+a)break;if(n>=e)return{type:`item`,id:t.item.id,viewportOffset:n-e};let i=this.getScrollAnchorViewportTop(n,e)-n,o=t.instance.getNumericScrollAnchor(i);if(o!=null){let r=n+o.top;return{type:`line`,id:t.item.id,lineNumber:o.lineNumber,side:o.side,viewportOffset:r-e}}}}resolveAnchoredScrollTop(e){let t=this.idToItem.get(e.id);if(t==null)return;let{paddingTop:n}=this.getLayout();if(e.type===`item`){let r=n+t.top;return this.clampScrollTop(r-e.viewportOffset)}let r=t.type===`diff`?t.instance.getLinePosition(e.lineNumber,e.side):t.instance.getLinePosition(e.lineNumber);if(r==null)return;let i=n+t.top+r.top;return this.clampScrollTop(i-e.viewportOffset)}applyScrollFix(e,t,n){if(this.root==null)return;let r=J(this.clampScrollTop(e)),i=J(t),{scrollPageOffset:a}=this,o=J(this.clampPagedScrollTop(i-a)),{pagedScrollTop:s,scrollPageOffset:c}=this.resolvePagedScrollPosition(r),l=s,u=a!==c;r===this.renderState.scrollTop&&r===i&&l===o&&!u||(this.suspendScrollInteractions(),(l!==o||u)&&(this.scrollPageOffset=c,this.syncPagedScrollScaffolding(n)),l!==o&&this.root.scrollTo({top:l,behavior:`instant`}),this.renderState.scrollTop=r,this.scrollTop=r,this.scrollDirty=!1)}isPendingTargetSettled(e){let t=this.resolveScrollTargetTop(e);return t==null?!0:J(this.getScrollTop())===J(t)}getScrollTop(){if(!this.scrollDirty)return this.scrollTop;this.scrollDirty=!1;let e=this.root?.scrollTop??0;return this.scrollTop=this.clampScrollTop(e+this.scrollPageOffset),this.scrollTop}getHeight(){return this.heightDirty?(this.heightDirty=!1,this.height=this.root?.getBoundingClientRect().height??0,this.height):this.height}getScrollHeight(){return this.scrollHeight}flushSlotCoordinator(){if(this.slotCoordinator==null)return;let{onSnapshotChange:e}=this.slotCoordinator,t=Ot(this.getRenderedItems(),this.slotCoordinator);kt(this.slotSnapshot,t)||(this.slotSnapshot=t,e(t))}notifyScroll(){if(this.scrollListeners.size===0)return;let e=this.getScrollTop();for(let t of this.scrollListeners)t(e,this)}findFirstVisibleIndex(e){let t=0,n=this.items.length-1,r=this.items.length;for(;t<=n;){let i=t+n>>1,a=this.items[i];if(a==null)throw Error(`CodeView.findFirstVisibleIndex: invalid item index`);a.top+a.height>e?(r=i,n=i-1):t=i+1}return r}findLastVisibleIndex(e){let t=0,n=this.items.length-1,r=-1;for(;t<=n;){let i=t+n>>1,a=this.items[i];if(a==null)throw Error(`CodeView.findLastVisibleIndex: invalid item index`);a.top<=e?(r=i,t=i+1):n=i-1}return r}recomputeLayout(e=0,t){if(this.items.length===0){this.scrollHeight=0;return}let n=this.getLayout(),r=0;if(e>0){let t=this.items[e-1];if(t==null)throw Error(`CodeView.recomputeLayout: invalid dirty index`);r=t.top+t.height+n.gap}for(let i=e;i<this.items.length;i++){let e=this.items[i];if(e==null)throw Error(`CodeView.recomputeLayout: invalid item index`);e.top=r,e.type===`diff`?e.height=e.instance.prepareCodeViewItem(e.item.fileDiff,r,t,e.item.annotations??[]):e.height=e.instance.prepareCodeViewItem(e.item.file,r,t,e.item.annotations??[]),r+=e.height,i<this.items.length-1&&(r+=n.gap)}r!==this.scrollHeight&&(this.scrollDirty=!0),this.scrollHeight=r}resetRenderState(){this.renderState.scrollTop=-1,this.renderState.firstIndex=-1,this.renderState.lastIndex=-1,this.renderState.stickyHeight=0,this.renderState.stickyTop=-1,this.renderState.stickyBottom=-1}getFitPerfectlyOverscroll(){return this.getLayout().gap+this.itemMetricsCache.diffHeaderHeight}};function vt(e){return e.instance.cleanUp(!0),e.type===`diff`?e.instance.prepareCodeViewItem(e.item.fileDiff,e.top,void 0,e.item.annotations??[]):e.instance.prepareCodeViewItem(e.item.file,e.top,void 0,e.item.annotations??[])}function yt(e,t){return!I(e.theme??Ue,t.theme??Ue)||(e.themeType??`system`)!==(t.themeType??`system`)||e.unsafeCSS!==t.unsafeCSS}function bt(e,t){return(e.overflow??`scroll`)!==(t.overflow??`scroll`)||(e.disableLineNumbers??!1)!==(t.disableLineNumbers??!1)||(e.disableFileHeader??!1)!==(t.disableFileHeader??!1)||e.unsafeCSS!==t.unsafeCSS||(e.diffStyle??`split`)!==(t.diffStyle??`split`)||(e.diffIndicators??`bars`)!==(t.diffIndicators??`bars`)||(e.hunkSeparators??`line-info`)!==(t.hunkSeparators??`line-info`)||(e.expandUnchanged??!1)!==(t.expandUnchanged??!1)||(e.collapsedContextThreshold??1)!==(t.collapsedContextThreshold??1)}function xt(e,t){return(e.disableFileHeader??!1)!==(t.disableFileHeader??!1)||(e.hunkSeparators??`line-info`)!==(t.hunkSeparators??`line-info`)||(e.expandUnchanged??!1)!==(t.expandUnchanged??!1)||(e.collapsedContextThreshold??1)!==(t.collapsedContextThreshold??1)}function St(e){return e instanceof SVGElement?!0:G(e)&&(e.hasAttribute(`data-core-css`)||e.hasAttribute(`data-theme-css`)||e.hasAttribute(`data-unsafe-css`))}function Ct(e){let t=wt(e.start,e.side),n=wt(e.end,e.endSide??e.side);return t===n?t:`${t}-${n}`}function wt(e,t){return t==null?`${e}`:`${t===`deletions`?`D`:`A`}${e}`}function Tt(e,t,n=!1){return e.type===`diff`?e.instance.render({deferManagers:!0,fileContainer:t,fileDiff:e.item.fileDiff,forceRender:n,lineAnnotations:e.item.annotations??[]}):e.instance.render({deferManagers:!0,fileContainer:t,file:e.item.file,forceRender:n,lineAnnotations:e.item.annotations??[]})}function Et(e,t,n){if(n==null){e.firstChild!==t&&e.prepend(t);return}n.nextSibling!==t&&n.after(t)}function Dt(e){return(e.annotations?.length??0)>0}function Ot(e,{hasHeaderRenderers:t,hasAnnotationRenderer:n,hasGutterRenderer:r}){if(e.length===0)return;if(t||r)return e;if(!n)return;let i=[];for(let t of e)Dt(t.item)&&i.push(t);return i.length>0?i:void 0}function kt(e,t){if(e==null||t==null)return e===t;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r==null||i==null||r.id!==i.id||r.type!==i.type||r.element!==i.element||r.version!==i.version)return!1}return!0}function At(e,t){if(e==null||t==null)return e===t;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r==null||i==null||r.id!==i.id||r.type!==i.type||r.element!==i.element||r.version!==i.version)return!1}return!0}var Q=N(M(),1),$=C(),jt=N(w(),1),Mt=typeof window>`u`?Q.useEffect:Q.useLayoutEffect;function Nt(e){return{instance:void 0,items:void 0,controlled:e,managedOptions:void 0,disableFlushSync:!1,slotCoordinator:void 0}}function Pt(e,t){let{className:n,containerRef:r,disableWorkerPool:i=!1,initialItems:a,items:o,onScroll:s,onSelectedLinesChange:c,options:l,renderAnnotation:u,renderCustomHeader:d,renderGutterUtility:f,renderHeaderMetadata:p,renderHeaderPrefix:m,selectedLines:h,style:g}=e,_=o!==void 0,v=(0,Q.useContext)(fe),y=(0,Q.useRef)(Nt(_)),b=d!=null,x=u!=null,S=f!=null,C=b||m!=null||p!=null,ee=C||x||S,w=K(e=>{c?.(e)}),T=h!==void 0,E=(0,Q.useMemo)(()=>Bt({options:l,hasCustomHeader:b,hasGutterRenderer:S,onSelectedLinesChange:c==null?void 0:w,controlledSelection:T}),[l,b,S,c,w,T]),[D]=(0,Q.useState)(()=>zt()),[,O]=(0,Q.useState)({}),k=K(e=>{y.current.instance!=null&&(e==null||e!==y.current.instance.getContainerElement())&&(y.current.instance.cleanUp(),D.publish(void 0),y.current=Nt(_)),e!=null&&e!==y.current.instance?.getContainerElement()&&(y.current.instance=new _t(E,i?void 0:v,!0),y.current.instance.setup(e)),typeof r==`function`?r(e):r!=null&&(r.current=e)}),A=K(e=>{y.current.disableFlushSync?D.publish(e):(0,jt.flushSync)(()=>{D.publish(e)})}),j=(0,Q.useMemo)(()=>{if(!(!C&&!x&&!S))return{hasHeaderRenderers:C,hasAnnotationRenderer:x,hasGutterRenderer:S,onSnapshotChange:A}},[A,x,S,C]);return Mt(()=>s==null?void 0:y.current.instance?.subscribeToScroll(s)),Mt(()=>{let{instance:e,controlled:t,items:n,managedOptions:r,slotCoordinator:i}=y.current;if(e!=null)try{y.current.disableFlushSync=!0;let s=!1;if(R(E,r)||(y.current.managedOptions=E,e.setOptions(E),s=!0),t!==_){console.error(`CodeView: cannot switch between controlled and uncontrolled modes. Remount with a new key instead.`);return}if(_)o!==n&&(Lt(n,o)?y.current.items=o:It(n,o)?(y.current.items=o,e.addItems(o.slice(n.length))):(y.current.items=o,e.setItems(o),s=!0));else if(n==null){let t=a??[];y.current.items=t,t.length>0&&(e.setItems(t),s=!0)}h!==void 0&&e.setSelectedLines(h,{notify:!1});let c=e.setSlotCoordinator(j),l=!1;j!==i&&((j==null||i==null)&&(l=!0),y.current.slotCoordinator=j),(s||c)&&e.render(!0),c&&j==null&&D.publish(void 0),l&&O({})}finally{y.current.disableFlushSync=!1}}),(0,Q.useImperativeHandle)(t,()=>({addItems(e){let{controlled:t,instance:n}=y.current;Rt(t,`addItems`),n==null?console.error(`CodeView.addItems: no valid instance to append items with`,e):n.addItems(e)},getItem(e){let{instance:t}=y.current;if(t==null){console.error(`CodeView.getItem: no valid instance exists`,e);return}else return t.getItem(e)},updateItem(e){let{controlled:t,instance:n}=y.current;return Rt(t,`updateItem`),n==null?(console.error(`CodeView.updateItem: no valid instance to update item with`,e),!1):n.updateItem(e)},updateItemId(e,t){let{controlled:n,instance:r}=y.current;return Rt(n,`updateItemId`),r==null?(console.error(`CodeView.updateItemId: no valid instance to update item id with`,e,t),!1):r.updateItemId(e,t)},scrollTo(e){let{instance:t}=y.current;t==null?console.error(`CodeView.scrollTo: no valid instance to scroll with`,e):t.scrollTo(e)},setSelectedLines(e){let{instance:t}=y.current;t==null?console.error(`CodeView.setSelectedLines: no valid instance to update selection with`,e):(t.setSelectedLines(e,{notify:!1}),w(e))},getSelectedLines(){let{instance:e}=y.current;return e==null?(console.error(`CodeView.getSelectedLines: no valid instance exists`),null):e.getSelectedLines()},clearSelectedLines(){let{instance:e}=y.current;e==null?console.error(`CodeView.clearSelectedLines: no valid instance to update selection with`):(e.clearSelectedLines({notify:!1}),w(null))},getInstance(){return y.current.instance}}),[w]),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{ref:k,className:n,style:g}),ee&&(0,$.jsx)(Vt,{managedContentStore:D,renderCustomHeader:d,renderHeaderPrefix:m,renderHeaderMetadata:p,renderAnnotation:u,renderGutterUtility:f})]})}var Ft=(0,Q.forwardRef)(Pt);function It(e,t){if(e==null||t.length<=e.length)return!1;if(e.length===0)return!0;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function Lt(e,t){if(e==null||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Rt(e,t){if(e)throw Error(`CodeView.${t} cannot be used when CodeView is controlled. Use initialItems for imperative item updates.`)}function zt(){let e,t=new Set;return{getSnapshot(){return e},publish(n){if(!At(e,n)){e=n;for(let e of t)e()}},subscribe(e){return t.add(e),()=>{t.delete(e)}}}}function Bt({options:e,hasCustomHeader:t,hasGutterRenderer:n,onSelectedLinesChange:r,controlledSelection:i}){return!t&&!n&&r==null&&!i?e:(e={...e,controlledSelection:i,onSelectedLinesChange:r},t&&(e.renderCustomHeader=Ut),n&&(e.renderGutterUtility=Ut),e)}var Vt=(0,Q.memo)(function({managedContentStore:e,renderCustomHeader:t,renderHeaderPrefix:n,renderHeaderMetadata:r,renderAnnotation:i,renderGutterUtility:a}){let o=K(t=>e.subscribe(t)),s=K(()=>e.getSnapshot());return(0,Q.useSyncExternalStore)(o,s,s)?.map(e=>(0,jt.createPortal)(Ht({renderedItem:e,renderCustomHeader:t,renderHeaderPrefix:n,renderHeaderMetadata:r,renderAnnotation:i,renderGutterUtility:a}),e.element,e.id))});function Ht({renderedItem:e,renderCustomHeader:t,renderHeaderPrefix:n,renderHeaderMetadata:r,renderAnnotation:i,renderGutterUtility:a}){if(e.type===`diff`){let{item:o,instance:s}=e;return z({fileDiff:o.fileDiff,renderCustomHeader:t==null?void 0:()=>t(o),renderHeaderPrefix:n==null?void 0:()=>n(o),renderHeaderMetadata:r==null?void 0:()=>r(o),renderAnnotation:i==null?void 0:e=>i(e,o),lineAnnotations:o.annotations,renderGutterUtility:a==null?void 0:e=>a(e,o),getHoveredLine:s.getHoveredLine})}else{let{item:o,instance:s}=e;return ce({file:o.file,renderCustomHeader:t==null?void 0:()=>t(o),renderHeaderPrefix:n==null?void 0:()=>n(o),renderHeaderMetadata:r==null?void 0:()=>r(o),renderAnnotation:i==null?void 0:e=>i(e,o),lineAnnotations:o.annotations,renderGutterUtility:a==null?void 0:e=>a(e,o),getHoveredLine:s.getHoveredLine})}}function Ut(){}function Wt({threadRef:e,filePath:t,activeCwd:n,openInEditor:r}){if(e){A.getState().openFile(e,t);return}r(n?B(t,n):t)}var Gt=a();function Kt(e,t){let n=(0,Gt.c)(4),r=Ye(e,t),i;return n[0]!==r.data||n[1]!==r.error||n[2]!==r.isPending?(i={data:r.data,error:r.error,isPending:r.isPending},n[0]=r.data,n[1]=r.error,n[2]=r.isPending,n[3]=i):i=n[3],i}function qt(e,t){return e.length>0&&e.every(e=>t.has(e))}function Jt(e,t){return qt(e,t)?new Set:new Set(e)}function Yt(e){return _(`flex items-center justify-between gap-2 px-4`,et&&e!==`sheet`&&e!==`embedded`?`drag-region h-[52px] border-b border-border wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]`:`surface-subheader`)}function Xt(e){let t=(0,Gt.c)(10),n=et&&e.mode!==`sheet`&&e.mode!==`embedded`,r=e.mode===`inline`?`w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border`:`w-full`,i;t[0]===r?i=t[1]:(i=_(`flex h-full min-w-0 flex-col bg-background`,r),t[0]=r,t[1]=i);let a;t[2]!==e.header||t[3]!==e.mode||t[4]!==n?(a=n?(0,$.jsx)(`div`,{className:Yt(e.mode),children:e.header}):(0,$.jsx)(`div`,{className:Yt(e.mode),"data-surface-subheader":!0,children:e.header}),t[2]=e.header,t[3]=e.mode,t[4]=n,t[5]=a):a=t[5];let o;return t[6]!==e.children||t[7]!==i||t[8]!==a?(o=(0,$.jsxs)(`div`,{className:i,children:[a,e.children]}),t[6]=e.children,t[7]=i,t[8]=a,t[9]=o):o=t[9],o}function Zt(e){let t=(0,Gt.c)(7),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border/50 px-3 py-2`,children:[(0,$.jsx)(L,{className:`h-4 w-32 rounded-full`}),(0,$.jsx)(L,{className:`ml-auto h-4 w-20 rounded-full`})]}),t[0]=n):n=t[0];let r;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(L,{className:`h-3 w-full rounded-full`}),(0,$.jsx)(L,{className:`h-3 w-full rounded-full`}),(0,$.jsx)(L,{className:`h-3 w-10/12 rounded-full`}),(0,$.jsx)(L,{className:`h-3 w-11/12 rounded-full`}),(0,$.jsx)(L,{className:`h-3 w-9/12 rounded-full`})]}),t[1]=r):r=t[1];let i;t[2]===e.label?i=t[3]:(i=(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 px-3 py-4`,children:[r,(0,$.jsx)(`span`,{className:`sr-only`,children:e.label})]}),t[2]=e.label,t[3]=i);let a;return t[4]!==e.label||t[5]!==i?(a=(0,$.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col p-2`,children:(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border/60 bg-card/25`,role:`status`,"aria-live":`polite`,"aria-label":e.label,children:[n,i]})}),t[4]=e.label,t[5]=i,t[6]=a):a=t[6],a}var Qt=[];function $t(e){return(e.endSide??e.side)===`deletions`?`deletions`:`additions`}function en(e,t,n){let r=$t(t),i=e.findIndex(e=>e.side===r&&e.lineNumber===t.end);return i<0?[...e,{side:r,lineNumber:t.end,metadata:{entries:[n]}}]:e.map((e,t)=>t===i?{...e,metadata:{entries:[...e.metadata.entries,n]}}:e)}function tn(e){let t=(0,Gt.c)(50),{files:n,sectionId:r,sectionTitle:i,composerDraftTarget:a,options:o,viewerRef:s,className:c,renderHeaderPrefix:l}=e,u=p(sn),d=p(on),f;t[0]===a?f=t[1]:(f=e=>e.getComposerDraft(a)?.reviewComments??Qt,t[0]=a,t[1]=f);let m=p(f),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(null),b;t[2]===n?b=t[3]:(b=new Map(n.map(an)),t[2]=n,t[3]=b);let x=b,S;if(t[4]!==_||t[5]!==n||t[6]!==m||t[7]!==r){let e;t[9]!==_||t[10]!==m||t[11]!==r?(e=e=>{let{fileDiff:t,filePath:n,fileKey:i,collapsed:a}=e,o=m.filter(e=>e.sectionId===r&&e.filePath===n&&(e.fenceLanguage??`diff`)===`diff`).reduce((e,n)=>{let r=ne(t,n);return r?en(e,r,{id:n.id,kind:`comment`,range:r,rangeLabel:n.rangeLabel,text:n.text}):e},[]),s=_?.fileKey===i?[...o,_.annotation]:o;return{id:i,type:`diff`,fileDiff:t,annotations:s,collapsed:a,version:be(`${a?`1`:`0`}:${s.flatMap(nn).join(`:`)}`)}},t[9]=_,t[10]=m,t[11]=r,t[12]=e):e=t[12],S=n.map(e),t[4]=_,t[5]=n,t[6]=m,t[7]=r,t[8]=S}else S=t[8];let C=S,ee;t[13]!==a||t[14]!==_?.annotation||t[15]!==d?(ee=e=>{g(null),_?.annotation.metadata.entries.some(t=>t.id===e)?v(null):d(a,e)},t[13]=a,t[14]=_?.annotation,t[15]=d,t[16]=ee):ee=t[16];let w=ee,T;t[17]!==u||t[18]!==a||t[19]!==_||t[20]!==x||t[21]!==r||t[22]!==i?(T=(e,t)=>{let n=_?.annotation.metadata.entries.find(t=>t.id===e),o=_?x.get(_.fileKey):void 0;if(!n||!o)return;let s=y({id:n.id,sectionId:r,sectionTitle:i,filePath:o.filePath,fileDiff:o.fileDiff,range:n.range,text:t});s&&u(a,s),g(null),v(null)},t[17]=u,t[18]=a,t[19]=_,t[20]=x,t[21]=r,t[22]=i,t[23]=T):T=t[23];let E=T,D;t[24]!==x||t[25]!==r||t[26]!==i?(D=(e,t)=>{if(!e)return;let n=t.item;if(n.type!==`diff`)return;let a=x.get(n.id);if(!a)return;let o=F(),s=y({id:o,sectionId:r,sectionTitle:i,filePath:a.filePath,fileDiff:a.fileDiff,range:e,text:``});s&&v({fileKey:n.id,annotation:{side:$t(e),lineNumber:e.end,metadata:{entries:[{id:o,kind:`draft`,range:e,rangeLabel:s.rangeLabel,text:``}]}}})},t[24]=x,t[25]=r,t[26]=i,t[27]=D):D=t[27];let O=D,k=_!==null,A;t[28]===s?A=t[29]:(A=s?{ref:s}:{},t[28]=s,t[29]=A);let j;t[30]===c?j=t[31]:(j=c?{className:c}:{},t[30]=c,t[31]=j);let te=!k,re=!k,M;t[32]!==O||t[33]!==o||t[34]!==re||t[35]!==te?(M={...o,enableGutterUtility:te,enableLineSelection:re,onLineSelectionEnd:O},t[32]=O,t[33]=o,t[34]=re,t[35]=te,t[36]=M):M=t[36];let ie;t[37]===l?ie=t[38]:(ie=e=>e.type===`diff`?l(e.fileDiff,e.id,e.collapsed===!0):null,t[37]=l,t[38]=ie);let N;t[39]!==w||t[40]!==E?(N=e=>(0,$.jsx)(`div`,{className:`py-1`,children:e.metadata.entries.map(e=>(0,$.jsx)(se,{kind:e.kind,rangeLabel:e.rangeLabel,text:e.text,onCancel:()=>w(e.id),onComment:t=>E(e.id,t),onDelete:()=>w(e.id)},e.id))}),t[39]=w,t[40]=E,t[41]=N):N=t[41];let P;return t[42]!==C||t[43]!==h||t[44]!==M||t[45]!==ie||t[46]!==N||t[47]!==A||t[48]!==j?(P=(0,$.jsx)(Ft,{...A,...j,items:C,selectedLines:h,onSelectedLinesChange:g,options:M,renderHeaderPrefix:ie,renderAnnotation:N}),t[42]=C,t[43]=h,t[44]=M,t[45]=ie,t[46]=N,t[47]=A,t[48]=j,t[49]=P):P=t[49],P}function nn(e){return e.metadata.entries.map(rn)}function rn(e){return`${e.id}:${e.rangeLabel}:${e.text}`}function an(e){return[e.fileKey,e]}function on(e){return e.removeReviewComment}function sn(e){return e.addReviewComment}var cn=function(e){return e.disabled=`data-disabled`,e.orientation=`data-orientation`,e.multiple=`data-multiple`,e}({}),ln={multiple(e){return e?{[cn.multiple]:``}:null}},un=Q.forwardRef(function(r,i){let{defaultValue:a,disabled:o=!1,loopFocus:s=!0,onValueChange:c,orientation:l=`horizontal`,multiple:u=!1,value:d,className:f,render:p,style:m,...h}=r,_=t(!0),v=Q.useMemo(()=>d!==void 0||a!==void 0,[d,a]),y=(_?.disabled??!1)||o,[b,x]=re({controlled:d,default:d===void 0?a??g:void 0,name:`ToggleGroup`,state:`value`}),S=e((e,t,n)=>{let r;u?(r=b.slice(),t?r.push(e):r.splice(b.indexOf(e),1)):r=t?[e]:[],c?.(r,n),!n.isCanceled&&x(r)}),C={disabled:y,multiple:u,orientation:l},ee=Q.useMemo(()=>({disabled:y,orientation:l,setGroupValue:S,value:b,isValueInitialized:v}),[y,l,S,b,v]),w={role:`group`},T=n(`div`,r,{enabled:!!_,state:C,ref:i,props:[w,h],stateAttributesMapping:ln});return(0,$.jsx)(ue.Provider,{value:ee,children:_?T:(0,$.jsx)(we,{render:p,className:f,style:m,state:C,refs:[i],props:[w,h],stateAttributesMapping:ln,loopFocus:s,enableHomeAndEndKeys:!0,orientation:l})})}),dn=Q.createContext({size:`default`,variant:`default`});function fn(e){let t=(0,Gt.c)(24),n,r,i,a,o,s;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4],o=t[5],s=t[6]):({className:r,variant:a,size:o,orientation:s,children:n,...i}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a,t[5]=o,t[6]=s);let c=a===void 0?`default`:a,l=o===void 0?`default`:o,u=s===void 0?`horizontal`:s,d;t[7]!==l||t[8]!==c?(d={size:l,variant:c},t[7]=l,t[8]=c,t[9]=d):d=t[9];let f=d,p=u===`horizontal`?`*:pointer-coarse:after:min-w-auto`:`*:pointer-coarse:after:min-h-auto`,m=c==="default"?`gap-0.5`:u===`horizontal`?`*:not-first:not-data-[slot=separator]:before:-start-[0.5px] *:not-last:not-data-[slot=separator]:before:-end-[0.5px] *:not-first:rounded-s-none *:not-last:rounded-e-none *:not-first:border-s-0 *:not-last:border-e-0 *:not-first:before:rounded-s-none *:not-last:before:rounded-e-none`:`*:not-first:not-data-[slot=separator]:before:-top-[0.5px] *:not-last:not-data-[slot=separator]:before:-bottom-[0.5px] flex-col *:not-first:rounded-t-none *:not-last:rounded-b-none *:not-first:border-t-0 *:not-last:border-b-0 *:not-first:before:rounded-t-none *:not-last:before:rounded-b-none *:data-[slot=toggle]:not-last:before:hidden dark:*:last:before:hidden dark:*:first:before:block`,h;t[10]!==r||t[11]!==p||t[12]!==m?(h=_(`flex w-fit *:focus-visible:z-10 dark:*:[[data-slot=separator]:has(+[data-slot=toggle]:hover)]:before:bg-input/64 dark:*:[[data-slot=separator]:has(+[data-slot=toggle][data-pressed])]:before:bg-input dark:*:[[data-slot=toggle]:hover+[data-slot=separator]]:before:bg-input/64 dark:*:[[data-slot=toggle][data-pressed]+[data-slot=separator]]:before:bg-input`,p,m,r),t[10]=r,t[11]=p,t[12]=m,t[13]=h):h=t[13];let g;t[14]!==n||t[15]!==f?(g=(0,$.jsx)(dn,{value:f,children:n}),t[14]=n,t[15]=f,t[16]=g):g=t[16];let v;return t[17]!==u||t[18]!==i||t[19]!==l||t[20]!==h||t[21]!==g||t[22]!==c?(v=(0,$.jsx)(un,{className:h,"data-size":l,"data-slot":`toggle-group`,"data-variant":c,orientation:u,...i,children:g}),t[17]=u,t[18]=i,t[19]=l,t[20]=h,t[21]=g,t[22]=c,t[23]=v):v=t[23],v}function pn(e){let t=(0,Gt.c)(12),n,r,i,a,o;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4],o=t[5]):({className:r,children:n,variant:o,size:a,...i}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a,t[5]=o);let s=Q.use(dn),c=o??s.variant,l=a??s.size,u;return t[6]!==n||t[7]!==r||t[8]!==i||t[9]!==l||t[10]!==c?(u=(0,$.jsx)(Qe,{className:r,"data-size":l,"data-variant":c,size:l,variant:c,...i,children:n}),t[6]=n,t[7]=r,t[8]=i,t[9]=l,t[10]=c,t[11]=u):u=t[11],u}function mn(e){return{diffPreview:k(e,{label:`environment-data:review:diff-preview`,tag:v.reviewGetDiffPreview,staleTimeMs:5e3})}}var hn=mn(c);function gn(e){return e.remoteName&&e.name.startsWith(`${e.remoteName}/`)?e.name.slice(e.remoteName.length+1):e.name}function _n(e,t){let n=new Set(t),r=e.map(e=>{let r=t.filter(t=>n.has(t)&&gn(t)===e.name),i=r.find(e=>e.remoteName===`origin`)??r[0]??null;return i&&n.delete(i),{id:`local:${e.name}`,label:e.name,local:e,remote:i}}),i=t.filter(e=>n.has(e)).map(e=>({id:`remote:${e.name}`,label:e.name,local:null,remote:e}));return[...r,...i]}function vn(e,t){let n=t.trim().toLocaleLowerCase();return n.length===0?e:e.filter(e=>e.label.toLocaleLowerCase().includes(n)||e.local?.name.toLocaleLowerCase().includes(n)===!0||e.remote?.name.toLocaleLowerCase().includes(n)===!0)}var yn=`__automatic_base_ref__`,bn=new Set,xn=`
1
+ import{$a as e,Ai as t,Ao as n,As as r,Br as i,Ff as a,Go as o,Gr as s,H as c,Ho as l,If as u,Ir as d,Jr as f,Jt as p,Kr as m,Mr as h,No as g,Pt as _,Qs as v,Qt as y,R as b,Ts as x,Uo as S,Wf as C,Wo as ee,ap as w,bs as T,g as E,ls as D,m as O,ms as k,o as A,p as j,qr as te,rn as ne,ro as re,sp as M,u as ie,up as N,w as P,zr as ae}from"./textarea-DHdA8g53.js";import{t as oe}from"./arrow-right-BG7cUHWK.js";import{a as se,n as F,o as ce,s as le}from"./fileCommentAnnotations-DEIuuBiQ.js";import{$t as I,B as ue,Bn as de,C as fe,Fn as pe,G as me,Hn as he,I as ge,In as _e,Ir as ve,J as ye,K as be,Kn as L,L as xe,Ln as Se,Lr as Ce,Nn as we,Pn as Te,Q as Ee,Qt as R,R as De,Rn as Oe,Sr as ke,T as z,Un as Ae,Vn as je,W as B,X as Me,Xt as V,Y as Ne,Yn as Pe,Z as Fe,Zt as H,_ as Ie,_r as Le,an as Re,cn as U,en as W,fn as ze,gr as Be,h as Ve,hr as He,ln as Ue,nn as We,nt as G,on as Ge,pn as Ke,q as qe,tn as Je,w as K,wn as Ye,xr as Xe,yr as Ze,z as Qe,zn as $e,zr as et}from"./index-CNTBEOVF.js";var tt=o(`columns-2`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M12 3v18`,key:`108xh3`}]]),nt=o(`pilcrow`,[[`path`,{d:`M13 4v16`,key:`8vvj80`}],[`path`,{d:`M17 4v16`,key:`7dpous`}],[`path`,{d:`M19 4H9.5a4.5 4.5 0 0 0 0 9H13`,key:`sh4n9v`}]]),rt=o(`rows-3`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M21 9H3`,key:`1338ky`}],[`path`,{d:`M21 15H3`,key:`9uk58r`}]]);function q(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}function J(e){let t=window.devicePixelRatio??1;return Math.round(e*t)/t}var it=`theme.disableLineNumbers.overflow.themeType.disableFileHeader.disableVirtualizationBuffers.preferredHighlighter.useCSSClasses.useTokenTransformer.tokenizeMaxLineLength.tokenizeMaxLength.unsafeCSS.diffStyle.diffIndicators.disableBackground.expandUnchanged.collapsedContextThreshold.lineDiffType.maxLineDiffLength.expansionLineCount.lineHoverHighlight.enableTokenInteractionsOnWhitespace.enableGutterUtility.__debugPointerEvents.enableLineSelection.controlledSelection.disableErrorHandling`.split(`.`),at=[`theme`,`disableLineNumbers`,`overflow`,`themeType`,`disableFileHeader`,`disableVirtualizationBuffers`,`preferredHighlighter`,`useCSSClasses`,`useTokenTransformer`,`tokenizeMaxLineLength`,`tokenizeMaxLength`,`unsafeCSS`,`lineHoverHighlight`,`enableTokenInteractionsOnWhitespace`,`enableGutterUtility`,`__debugPointerEvents`,`enableLineSelection`,`controlledSelection`,`disableErrorHandling`],ot=[`renderCustomHeader`,`renderHeaderPrefix`,`renderHeaderMetadata`,`renderAnnotation`,`renderGutterUtility`,`onPostRender`,`onGutterUtilityClick`,`onLineClick`,`onLineNumberClick`,`onLineEnter`,`onLineLeave`,`onTokenClick`,`onTokenEnter`,`onTokenLeave`],st=[`onLineSelected`,`onLineSelectionStart`,`onLineSelectionChange`,`onLineSelectionEnd`],ct=Symbol(`CodeView.itemOptionsState`);function lt(e,t){Object.defineProperty(e,ct,{configurable:!1,enumerable:!1,value:t})}function ut(e){return e[ct]}function Y(e,t,n){Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get(){return n(this)}})}var dt=120,ft=`--diffs-overflow-override`,pt=12e6,mt=1e6,ht=2e6,X=pt-ht,gt=pt-mt,Z=(()=>{let{navigator:e}=globalThis,t=e.userAgent,n=/iP(?:hone|ad|od)/.test(t),r=e.platform===`MacIntel`&&e.maxTouchPoints>1;return(n||r)&&/AppleWebKit/.test(t)&&/Safari/.test(t)&&!/(CriOS|FxiOS|EdgiOS|OPiOS)/.test(t)})(),_t=class e{static __STOP=!1;static __lastScrollPosition=0;type=`advanced`;config={overscrollSize:200,intersectionObserverMargin:0,resizeDebugging:!1};items=[];idToItem=new Map;selectedLines=null;instanceToItem=new Map;layoutDirtyIndex;pendingLayoutReset;renderOptionsRevision=0;slotCoordinator;slotSnapshot;scrollListeners=new Set;scrollHeight=0;containerHeight=-1;scrollTop=0;scrollPageOffset=0;scrollDirty=!0;scrollInteractionFixTimer;pointerEventsDisabled=!1;codeOverflowFix=!1;height=0;heightDirty=!0;windowSpecs={top:0,bottom:0};renderState={scrollTop:-1,firstIndex:-1,lastIndex:-1,stickyHeight:0,stickyTop:-1,stickyBottom:-1};itemMetricsCache=Re;fileOptionsPrototype;diffOptionsPrototype;pendingScrollTarget;pendingLayoutAnchor;shouldFixContainerFocus=!1;scrollAnimation;root;resizeObserver;container=document.createElement(`div`);stickyContainer=document.createElement(`div`);stickyOffset=document.createElement(`div`);elementPool=[];elementPoolVersion=0;elementPoolTracker=new WeakMap;pendingElementPool=[];options;workerManager;isContainerManaged;constructor(e={theme:Ue},t,n=!1){this.options=e,this.computeMetricsCache(e.itemMetrics),this.fileOptionsPrototype=this.createFileOptionsPrototype(),this.diffOptionsPrototype=this.createDiffOptionsPrototype(),this.workerManager=t,this.isContainerManaged=n,this.stickyOffset.style.contain=`layout size`,this.stickyContainer.style.position=`sticky`,this.stickyContainer.style.width=`100%`,this.stickyContainer.style.contain=`layout style inline-size`,this.stickyContainer.style.isolation=`isolate`,this.stickyContainer.style.display=`flex`,this.stickyContainer.style.flexDirection=`column`}getLayout(){return this.options.layout??Ge}computeMetricsCache(e){return this.itemMetricsCache={hunkLineCount:e?.hunkLineCount??Re.hunkLineCount,lineHeight:e?.lineHeight??Re.lineHeight,diffHeaderHeight:e?.diffHeaderHeight??Re.diffHeaderHeight,hunkSeparatorHeight:e?.hunkSeparatorHeight,spacing:e?.spacing??Re.spacing,paddingTop:e?.paddingTop,paddingBottom:e?.paddingBottom},this.itemMetricsCache}getSmoothScrollSettings(){return this.options.smoothScrollSettings??U}shouldDisablePointerEvents(){return this.options.pointerEventsOnScroll!==!0}shouldValidateItemHeights(){return ze&&this.options.__devOnlyValidateItemHeights===!0}validateRenderedItemHeight(e){if(!this.shouldValidateItemHeights()||e.element==null)return;let t=e.instance.getAdvancedStickySpecs();if(t==null)return;let n=t.height,r=e.element.getBoundingClientRect().height;n!==r&&console.error(`CodeView: reconciled item height does not match DOM height`,{id:e.item.id,type:e.type,index:e.index,version:e.version,expectedHeight:n,actualHeight:r,delta:r-n,stickyTopOffset:t.topOffset,virtualizedHeight:e.instance.getVirtualizedHeight(),top:e.top,scrollTop:this.getScrollTop(),windowSpecs:{...this.windowSpecs},element:e.element,instance:e.instance})}validateStickyContainerHeight(){if(!this.shouldValidateItemHeights())return;let{firstIndex:e,lastIndex:t,stickyHeight:n,stickyTop:r,stickyBottom:i}=this.renderState;if(e===-1||t===-1)return;let a=this.stickyContainer.getBoundingClientRect().height;Math.abs(a-n)<1||console.error(`CodeView: sticky container height does not match computed layout`,{computedStickyHeight:n,actualStickyHeight:a,delta:a-n,stickyTop:r,stickyBottom:i,firstIndex:e,lastIndex:t,firstStickySpecs:this.items[e]?.instance.getAdvancedStickySpecs(),lastStickySpecs:this.items[t]?.instance.getAdvancedStickySpecs(),scrollTop:this.getScrollTop(),scrollPageOffset:this.scrollPageOffset,windowSpecs:{...this.windowSpecs},stickyContainer:this.stickyContainer})}clearScrollInteractionTimer(){this.scrollInteractionFixTimer!=null&&(clearTimeout(this.scrollInteractionFixTimer),this.scrollInteractionFixTimer=void 0)}suspendScrollInteractions(){this.clearScrollInteractionTimer(),this.shouldDisablePointerEvents()&&!this.pointerEventsDisabled&&(this.stickyContainer.style.pointerEvents=`none`,this.pointerEventsDisabled=!0),Z&&!this.codeOverflowFix&&(this.stickyContainer.style.setProperty(ft,`hidden`),this.codeOverflowFix=!0),this.scrollInteractionFixTimer=setTimeout(this.restoreScrollInteractions,dt)}restoreScrollInteractions=()=>{this.clearScrollInteractionTimer(),this.pointerEventsDisabled&&=(this.stickyContainer.style.removeProperty(`pointer-events`),!1),this.codeOverflowFix&&=(this.stickyContainer.style.setProperty(ft,`auto`),!1)};syncLayout(){let{gap:e,paddingBottom:t,paddingTop:n}=this.getLayout();this.stickyContainer.style.gap=`${e}px`,this.container?.style.setProperty(`margin-top`,`${n}px`),this.container?.style.setProperty(`margin-bottom`,`${t}px`)}setup(t){if(this.root!=null)throw Error(`CodeView.setup: already setup`);this.workerManager?.subscribeToThemeChanges(this),this.root=t,this.root.style.overflowAnchor=`none`,this.root.hasAttribute(`tabindex`)||(this.root.tabIndex=-1),this.container??=document.createElement(`div`),this.container.style.contain=`layout style`,this.syncLayout(),this.container.appendChild(this.stickyOffset),this.container.appendChild(this.stickyContainer),this.root.appendChild(this.container),this.scrollDirty=!0,this.heightDirty=!0,this.resizeObserver=new ResizeObserver(this.handleResize),this.resizeObserver.observe(this.stickyContainer),this.root.addEventListener(`scroll`,this.handleScroll,{passive:!0}),this.root.addEventListener(`wheel`,this.clearPendingScroll,{passive:!0}),this.root.addEventListener(`touchstart`,this.clearPendingScroll,{passive:!0}),this.root.addEventListener(`pointerdown`,this.clearPendingScroll,{passive:!0}),this.root.addEventListener(`keydown`,this.clearPendingScroll,{passive:!0}),this.resizeObserver.observe(this.root),this.render(!0),window.__INSTANCE=this,window.__TOGGLE=()=>{e.__STOP?(e.__STOP=!1,this.scrollTo({type:`position`,position:e.__lastScrollPosition,behavior:`instant`})):(e.__lastScrollPosition=this.getScrollTop(),e.__STOP=!0)}}reset(){this.restoreScrollInteractions(),this.cleanAllRenderedItems(),this.selectedLines=null,this.items.length=0,this.idToItem.clear(),this.instanceToItem.clear(),this.layoutDirtyIndex=void 0,this.pendingLayoutReset=void 0,this.stickyContainer.textContent=``,this.stickyOffset.style.height=``,this.container?.style.removeProperty(`height`),this.containerHeight=-1,this.windowSpecs={top:0,bottom:0},this.pendingLayoutAnchor=void 0,this.shouldFixContainerFocus=!1,this.height=0,this.scrollTop=0,this.scrollPageOffset=0,this.scrollHeight=0,this.scrollDirty=!0,this.heightDirty=!0,this.resetRenderState(),this.isContainerManaged||this.flushSlotCoordinator()}cleanUp(){this.reset(),this.clearElementPool(),this.restoreScrollInteractions(),this.workerManager?.unsubscribeToThemeChanges(this),this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.root?.removeEventListener(`scroll`,this.handleScroll),this.root?.removeEventListener(`wheel`,this.clearPendingScroll),this.root?.removeEventListener(`touchstart`,this.clearPendingScroll),this.root?.removeEventListener(`pointerdown`,this.clearPendingScroll),this.root?.removeEventListener(`keydown`,this.clearPendingScroll),this.root?.style.removeProperty(`overflow-anchor`),this.container?.remove(),this.stickyOffset.remove(),this.stickyContainer.remove(),this.stickyContainer.textContent=``,this.root=void 0,this.container=void 0}cleanAllRenderedItems(){if(this.renderState.firstIndex!==-1)for(let e=this.renderState.firstIndex;e<=this.renderState.lastIndex;e++){let t=this.items[e];if(t==null)throw Error(`CodeView.cleanAllRenderedItems: Item does not exist at index: ${e}`);this.releaseRenderedItem(t)}}primeScrollTarget(e){e.type!==`position`&&this.idToItem.get(e.id)?.instance.primeHighlightCache()}getElementPoolLimit(){let e=this.getHeight()+this.config.overscrollSize*2,{diffHeaderHeight:t}=this.itemMetricsCache;return Math.max(8,Math.ceil(e/Math.max(t,10))+1)*(this.isContainerManaged?2:1)}acquireElement(){this.promotePendingPooledElements();let e=this.elementPool.pop();for(;e!=null&&!this.isElementPoolGenerationCurrent(e);)e=this.elementPool.pop();return e??=document.createElement(Ke),this.markElementPoolGenerationCurrent(e),e}releaseRenderedItem(e){let{element:t}=e;t!=null&&this.renderedItemOwnsFocus(t)&&(this.shouldFixContainerFocus=!0),e.instance.cleanUp(!0),e.element=void 0,t!=null&&(t.remove(),this.cleanElement(t),this.queueElementForPool(t))}renderedItemOwnsFocus(e){let{activeElement:t}=document;return t===e||e.contains(t)||e.shadowRoot?.activeElement!=null}fixContainerFocus(){this.shouldFixContainerFocus&&(this.shouldFixContainerFocus=!1,this.root?.focus({preventScroll:!0}))}cleanElement(e){let{shadowRoot:t}=e;if(t!=null)for(let e of Array.from(t.children))St(e)||e.remove();this.isContainerManaged||e.replaceChildren()}queueElementForPool(e){let t=this.getElementPoolLimit();!this.isElementPoolGenerationCurrent(e)||this.getElementPoolSize()>=t||(this.isElementClean(e)?this.elementPool.push(e):this.pendingElementPool.push(e))}promotePendingPooledElements(){if(this.pendingElementPool.length===0)return;let{pendingElementPool:e}=this;this.pendingElementPool=[];let t=this.getElementPoolLimit();for(let n of e)this.isElementPoolGenerationCurrent(n)&&this.isElementClean(n)&&this.elementPool.length<t?this.elementPool.push(n):this.isElementPoolGenerationCurrent(n)&&this.getElementPoolSize()<t&&this.pendingElementPool.push(n)}isElementClean(e){return e.childNodes.length===0}getElementPoolSize(){return this.elementPool.length+this.pendingElementPool.length}clearElementPool(){this.elementPool.length=0,this.pendingElementPool.length=0}invalidateElementPool(){this.elementPoolVersion++,this.clearElementPool()}markElementPoolGenerationCurrent(e){this.elementPoolTracker.set(e,this.elementPoolVersion)}isElementPoolGenerationCurrent(e){return this.elementPoolTracker.get(e)===this.elementPoolVersion}resolveEffectiveScrollBehavior(e,t){return q()?`instant`:e.behavior===`smooth-auto`?Math.abs(t-this.getScrollTop())<=this.getHeight()*10?`smooth`:`instant`:e.behavior??`instant`}scrollTo(e){if(this.root==null)return;let t=this.normalizeScrollTarget(e);if(t==null)return;let n=this.resolveScrollTargetTop(t);n!=null&&(this.primeScrollTarget(t),this.resolveEffectiveScrollBehavior(t,n)===`smooth`?this.scrollAnimation??={position:this.getScrollTop(),velocity:0,lastTimestamp:performance.now()}:this.scrollAnimation=void 0,this.suspendScrollInteractions(),this.pendingLayoutAnchor=void 0,this.pendingScrollTarget=t,this.render())}setSelectedLines(e,t){this.applySelectedLines(e,t)}getSelectedLines(){return this.selectedLines}clearSelectedLines(e){this.applySelectedLines(null,e)}getItem(e){return this.idToItem.get(e)?.item}updateItem(e){let t=this.idToItem.get(e.id);return t==null?(console.error(`CodeView.updateItem: unknown item id "${e.id}"`),!1):this.syncItemRecord(t,e)?(this.markItemLayoutDirty(t),this.scrollDirty=!0,this.render(),this.syncSelection(),!0):!1}updateItemId(e,t){if(e===t)return!0;let n=this.idToItem.get(e);return n==null?(console.error(`CodeView.updateItemId: unknown item id "${e}"`),!1):this.idToItem.has(t)?(console.error(`CodeView.updateItemId: duplicate item id "${t}"`),!1):(this.idToItem.delete(e),n.item.id=t,this.idToItem.set(t,n),this.updateItemOptionsId(n.instance.options,t),this.selectedLines?.id===e&&(this.selectedLines={...this.selectedLines,id:t},this.options.onSelectedLinesChange?.(this.selectedLines)),this.renamePendingScrollTarget(e,t),this.renamePendingLayoutAnchor(e,t),this.render(),!0)}addItem(e){this.addItems([e]),this.syncSelection()}addItems(e){this.appendItemsInternal(e),this.syncSelection()}setItems(e){e.length===0?this.reset():this.items.length===0?this.appendItemsInternal(e):this.tryAppendItems(e)||this.reconcileItems(e),this.syncSelection()}appendItemsInternal(e,t=!0){if(e.length===0)return;let n=this.getLayout(),r=this.items.length===0?0:this.scrollHeight+n.gap,i=r;for(let t=0;t<e.length;t++){let i=e[t];if(i==null)throw Error(`CodeView.appendItemsInternal: missing input item`);if(this.idToItem.has(i.id))throw Error(`CodeView.addItem: duplicate id "${i.id}"`);let a=this.createItem(i,this.items.length,r);this.items.push(a),this.idToItem.set(a.item.id,a),this.instanceToItem.set(a.instance,a),a.height=vt(a),r+=a.height+n.gap}this.scrollHeight=r-n.gap,this.scrollDirty=!0,t&&(this.canSkipRenderForAppend(i)?this.syncContainerHeight():this.render())}canSkipRenderForAppend(e){return this.container!=null&&this.renderState.firstIndex!==-1&&this.pendingScrollTarget==null&&this.scrollAnimation==null&&this.layoutDirtyIndex==null&&e>this.windowSpecs.bottom}onThemeChange(){this.invalidateElementPool()}setOptions(e){if(e==null)return;this.capturePendingLayoutAnchor();let{options:t}=this,n=this.getLayout(),{itemMetricsCache:r}=this;yt(t,e)&&this.invalidateElementPool(),this.options=e;let i=this.computeMetricsCache(e.itemMetrics),a=!W(r,i),o=!W(n,this.getLayout());o&&this.syncLayout();let s=a||bt(t,e);if(s){let n=this.pendingLayoutReset;this.pendingLayoutReset={metrics:a?i:n?.metrics,resetFileLayoutCache:!0,resetDiffLayoutCache:!0,includeEstimatedDiffHeights:n?.includeEstimatedDiffHeights===!0||a||xt(t,e)}}(o||s)&&(this.markLayoutDirtyFromIndex(0),this.scrollDirty=!0),R(t,e)||this.renderOptionsRevision++,!this.isContainerManaged&&this.items.length>0&&this.render()}capturePendingLayoutAnchor(){this.root==null||this.items.length===0||this.pendingScrollTarget!=null||(this.pendingLayoutAnchor=this.getScrollAnchor(this.getScrollTop()))}render(t=!1){e.__STOP||(t?(Je(this.computeRenderRangeAndEmit),this.computeRenderRangeAndEmit()):We(this.computeRenderRangeAndEmit))}instanceChanged(e,t){let n=this.instanceToItem.get(e);if(n==null)throw Error(`CodeView.instanceChanged: An instance has changed that is not registered`);t&&this.markItemLayoutDirty(n),this.render()}getWindowSpecs(){return this.windowSpecs}getContainerElement(){return this.root}getRenderedItems(){let{firstIndex:e,lastIndex:t}=this.renderState;if(e===-1||t===-1||t<e)return[];let n=[];for(let r=e;r<=t;r++){let e=this.items[r];e?.element!=null&&(e.type===`diff`?n.push({id:e.item.id,type:`diff`,item:e.item,version:e.version,element:e.element,instance:e.instance}):n.push({id:e.item.id,type:`file`,item:e.item,version:e.version,element:e.element,instance:e.instance}))}return n}setSlotCoordinator(e){return e===this.slotCoordinator?!1:(this.slotCoordinator=e,this.slotSnapshot=void 0,!0)}getSlotSnapshot(e){return Ot(this.getRenderedItems(),e)}subscribeToScroll(e){return this.scrollListeners.add(e),()=>{this.scrollListeners.delete(e)}}getLocalTopForInstance(e){let t=this.instanceToItem.get(e);if(t==null)throw Error(`CodeView.getLocalTopForInstance: unknown virtualized instance`);return t.top}getTopForItem(e){let t=this.idToItem.get(e);if(t!=null)return t.top+this.getLayout().paddingTop}createItem(e,t,n){let{itemMetricsCache:r}=this;if(e.type===`diff`){let i=new Ee(this.createDiffOptions(e.id),this,r,this.workerManager,this.isContainerManaged);return{type:`diff`,item:e,version:e.version,index:t,top:n,height:0,element:void 0,renderedOptionsRevision:this.renderOptionsRevision,instance:i}}let i=new le(this.createFileOptions(e.id),this,r,this.workerManager,this.isContainerManaged);return{type:`file`,item:e,version:e.version,index:t,top:n,height:0,element:void 0,renderedOptionsRevision:this.renderOptionsRevision,instance:i}}applySelectedLines(e,t){let{selectedLines:n}=this;e==null&&n==null||e!=null&&n?.id===e.id&&H(n.range,e.range)||(n!=null&&n.id!==e?.id&&this.idToItem.get(n.id)?.instance.setSelectedLines(null,{notify:!1}),this.selectedLines=e,this.idToItem.get(e?.id??``)?.instance.setSelectedLines(e?.range??null,t))}syncSelection(){if(this.selectedLines==null)return;let e=this.idToItem.get(this.selectedLines.id);if(e==null){this.selectedLines=null;return}e.instance.setSelectedLines(this.selectedLines.range,{notify:!1})}renamePendingScrollTarget(e,t){let{pendingScrollTarget:n}=this;n==null||n.type===`position`||n.id!==e||(this.pendingScrollTarget={...n,id:t})}renamePendingLayoutAnchor(e,t){this.pendingLayoutAnchor?.id===e&&(this.pendingLayoutAnchor.id=t)}createFileOptionsPrototype(){let e={};for(let t of at)Y(e,t,()=>this.options[t]);Y(e,`stickyHeader`,()=>this.options.stickyHeaders),Y(e,`collapsed`,e=>this.getItemOptions(ut(e),`file`)?.item.collapsed===!0);for(let t of ot)this.defineItemSharedCallback(e,`file`,t);for(let t of st)this.defineItemSelectionCallback(e,`file`,t);return e}createDiffOptionsPrototype(){let e={};for(let t of it)Y(e,t,()=>this.options[t]);Y(e,`stickyHeader`,()=>this.options.stickyHeaders),Y(e,`hunkSeparators`,()=>this.options.hunkSeparators),Y(e,`collapsed`,e=>this.getItemOptions(ut(e),`diff`)?.item.collapsed===!0);for(let t of ot)this.defineItemSharedCallback(e,`diff`,t);for(let t of st)this.defineItemSelectionCallback(e,`diff`,t);return e}createFileOptions(e){let t=Object.create(this.fileOptionsPrototype);return lt(t,{id:e}),t}createDiffOptions(e){let t=Object.create(this.diffOptionsPrototype);return lt(t,{id:e}),t}updateItemOptionsId(e,t){ut(e).id=t}getItemOptions(e,t){let n=this.idToItem.get(e.id);if(!(n==null||n.type!==t))return n}defineItemSharedCallback(e,t,n){Y(e,n,e=>{if(this.options[n]==null)return;let r=ut(e),i=r.callbackCache??={},a=i[n];return a??(a=((...e)=>{let i=this.getItemOptions(r,t);if(i==null)return;let a=this.options[n];return a?.(...e,i)}),i[n]=a),a})}defineItemSelectionCallback(e,t,n){Y(e,n,e=>{if(this.options.enableLineSelection!==!0)return;let r=ut(e),i=r.callbackCache??={},a=i[n];return a??(a=(e=>{let i=this.getItemOptions(r,t);if(i==null)return;let a=e==null?null:{id:i.item.id,range:e};this.options.controlledSelection!==!0&&(e!=null||this.selectedLines?.id===i.item.id)&&this.applySelectedLines(a,{notify:!1}),this.options.onSelectedLinesChange?.(a);let o=this.options[n];return o?.(e,i)}),i[n]=a),a})}markLayoutDirtyFromIndex(e){this.layoutDirtyIndex=Math.min(this.layoutDirtyIndex??e,e)}markItemLayoutDirty(e){if(this.items[e.index]!==e)throw Error(`CodeView.markItemLayoutDirty: unknown item id "${e.item.id}"`);this.markLayoutDirtyFromIndex(e.index)}tryAppendItems(e){if(e.length<=this.items.length)return!1;for(let t=0;t<this.items.length;t++){let n=this.items[t];if(n==null)throw Error(`CodeView.tryAppendItems: missing existing item`);let r=e[t];if(r==null||n.item.id!==r.id||n.type!==r.type)return!1}for(let t=0;t<this.items.length;t++){let n=this.items[t];if(n==null)throw Error(`CodeView.tryAppendItems: missing existing item`);let r=e[t];if(r==null)throw Error(`CodeView.tryAppendItems: append candidate missing prefix item`);this.syncItemRecord(n,r)&&this.markLayoutDirtyFromIndex(t)}return this.appendItemsInternal(e.slice(this.items.length),!1),this.scrollDirty=!0,this.render(),!0}reconcileItems(e){let{items:t,idToItem:n}=this,r=new Set(t),i=[],a=new Map,o=new Map,s;for(let c=0;c<e.length;c++){let l=e[c];if(l==null)throw Error(`CodeView.reconcileItems: missing input item`);if(a.has(l.id))throw Error(`CodeView.setItems: duplicate id "${l.id}"`);let u=n.get(l.id),d=u!=null&&u.type===l.type?u:this.createItem(l,c,0);d.index=c,u!=null&&u.type===l.type?(r.delete(u),this.syncItemRecord(d,l)&&(s=Math.min(s??c,c))):s=Math.min(s??c,c),t[c]!==d&&(s=Math.min(s??c,c)),i.push(d),a.set(l.id,d),o.set(d.instance,d)}for(let e=0;e<t.length;e++){let n=t[e];if(n==null||!r.has(n))continue;this.releaseRenderedItem(n);let a=Math.max(i.length-1,0);s=Math.min(s??a,a)}s!=null&&(this.items=i,this.idToItem=a,this.instanceToItem=o,this.renderState.firstIndex>=i.length?this.resetRenderState():this.renderState.lastIndex>=i.length&&(this.renderState.lastIndex=i.length-1),this.markLayoutDirtyFromIndex(s),this.scrollDirty=!0,this.render())}syncItemRecord(e,t){if(e.type!==t.type)throw Error(`CodeView.syncItemRecord: type mismatch for id "${t.id}"`);return e.version===t.version?!1:(e.item=t,e.version=t.version,e.renderedOptionsRevision=-1,!0)}getMaxScrollTopForHeight(e){let{paddingBottom:t,paddingTop:n}=this.getLayout();return Math.max(n+e+t-this.getHeight(),0)}getMaxScrollTop(){return this.getMaxScrollTopForHeight(this.getScrollHeight())}shouldRebaseScroll(){return this.getMaxScrollTop()>gt}getPagedScrollHeight(){return this.shouldRebaseScroll()?Math.min(this.getScrollHeight(),pt):this.getScrollHeight()}getMaxPagedScrollTop(){return this.getMaxScrollTopForHeight(this.getPagedScrollHeight())}clampPagedScrollTop(e){let t=this.getMaxPagedScrollTop();return Math.max(0,Math.min(e,t))}clampScrollTop(e){let t=this.getMaxScrollTop();return Math.max(0,Math.min(e,t))}getMaxScrollPageOffset(){return Math.max(this.getMaxScrollTop()-this.getMaxPagedScrollTop(),0)}clampScrollPageOffset(e){let t=this.getMaxScrollPageOffset();return Math.max(0,Math.min(e,t))}resolveScrollPageWindow(e,t){let n=J(this.clampPagedScrollTop(t)),r=this.clampScrollPageOffset(e-n);return n=J(this.clampPagedScrollTop(e-r)),r=this.clampScrollPageOffset(e-n),{pagedScrollTop:n,scrollPageOffset:r}}resolvePagedScrollPosition(e){if(!this.shouldRebaseScroll())return{pagedScrollTop:this.clampPagedScrollTop(e),scrollPageOffset:0};let t=this.clampScrollPageOffset(this.scrollPageOffset),n=e-t,r=this.getMaxPagedScrollTop(),i=this.getMaxScrollPageOffset(),a=n>gt&&t<i,o=n<mt&&t>0;return n<0||n>r||a||o?this.resolveScrollPageWindow(e,o?Math.min(X,r):ht):{pagedScrollTop:J(this.clampPagedScrollTop(n)),scrollPageOffset:t}}needsScrollPageUpdate(e){let t=J(this.clampScrollTop(e)),{scrollPageOffset:n}=this.resolvePagedScrollPosition(t);return n!==this.scrollPageOffset}getPagedLayoutTop(e){return this.shouldRebaseScroll()?Math.max(e-this.scrollPageOffset,0):e}getStickyHeaderOffset(){return this.options.stickyHeaders===!0&&this.options.disableFileHeader!==!0?this.itemMetricsCache.diffHeaderHeight:0}getScrollTargetRect(e){let t=this.idToItem.get(e.id);if(t==null){console.warn(`CodeView.scrollTo: unknown item id "${e.id}"`);return}if(e.type===`item`)return{top:t.top,height:t.height};if(e.type===`range`){let n=this.getRangeScrollPosition(t,e);if(n==null){console.warn(`CodeView.scrollTo: unable to resolve range ${Ct(e.range)} for item "${e.id}"`);return}return{top:t.top+n.top,height:n.height}}let n=this.getLineScrollPosition(t,e);if(n==null){console.warn(`CodeView.scrollTo: unable to resolve line ${e.lineNumber} for item "${e.id}"`);return}return{top:t.top+n.top,height:n.height}}normalizeScrollTarget(e){if(e.type===`position`||e.align!==`nearest`)return e;let t=this.getScrollTargetRect(e);if(t==null)return;let n=e.offset??0,r=this.getLayout().paddingTop+t.top,i=r+t.height,a=this.getScrollTop(),o=a+(e.type===`line`||e.type===`range`?this.getStickyHeaderOffset():0),s=a+this.getHeight();if(!(r-n<=o&&i+n>=s)){if(r-n<o)return{...e,align:`start`};if(i+n>s)return{...e,align:`end`}}}resolveScrollTargetTop(e){if(e.type===`position`){let t=this.clampScrollTop(e.position);return t===e.position?this.clampScrollTop(e.position-this.getStickyHeaderOffset()):t}let t=this.idToItem.get(e.id);if(t==null){console.warn(`CodeView.scrollTo: unknown item id "${e.id}"`);return}if(e.type===`item`)return this.clampScrollTop(this.resolveAlignedScrollPosition(t.top,t.height,e.align,e.offset));if(e.type===`range`){let n=this.getRangeScrollPosition(t,e);if(n==null){console.warn(`CodeView.scrollTo: unable to resolve range ${Ct(e.range)} for item "${e.id}"`);return}return this.clampScrollTop(this.resolveAlignedScrollPosition(t.top+n.top,n.height,e.align,e.offset,this.getStickyHeaderOffset()))}let n=this.getLineScrollPosition(t,e);if(n==null){console.warn(`CodeView.scrollTo: unable to resolve line ${e.lineNumber} for item "${e.id}"`);return}return this.clampScrollTop(this.resolveAlignedScrollPosition(t.top+n.top,n.height,e.align,e.offset,this.getStickyHeaderOffset()))}resolveAlignedScrollPosition(e,t,n,r=0,i=0){e+=this.getLayout().paddingTop;let a=this.getHeight();return n===`center`&&t+r<a?e-(a-t)/2+r:n===`end`?e-(a-t)+r:e-i-r}getLineScrollPosition(e,t){return e.type===`diff`?e.instance.getLinePosition(t.lineNumber,t.side):e.instance.getLinePosition(t.lineNumber)}getRangeScrollPosition(e,t){let{range:n}=t,r=this.getLineScrollPosition(e,{type:`line`,id:t.id,lineNumber:n.start,side:n.side}),i=this.getLineScrollPosition(e,{type:`line`,id:t.id,lineNumber:n.end,side:n.endSide??n.side});if(r==null||i==null)return;let a=r.top,o=a+r.height,s=i.top,c=s+i.height,l=Math.min(a,s);return{top:l,height:Math.max(o,c)-l}}computeTargetScrollTopForFrame(e,t){if(this.pendingScrollTarget==null)return e;let n=this.resolveScrollTargetTop(this.pendingScrollTarget);if(n==null)return e;let{scrollAnimation:r}=this;return r==null?n:this.computeSpringStep(r,n,t).position}computeSpringStep(e,t,n){let r=Math.max(0,n-e.lastTimestamp),{omega:i}=this.getSmoothScrollSettings(),a=Math.exp(-i*r),o=e.position-t,s=e.velocity+i*o;return{position:t+(o+s*r)*a,velocity:(s*(1-i*r)-i*o)*a}}advanceScrollAnimation(e,t){if(this.pendingScrollTarget==null)return;let n=this.resolveScrollTargetTop(this.pendingScrollTarget);if(n==null){this.pendingScrollTarget=void 0,this.scrollAnimation=void 0;return}let r=this.scrollAnimation;if(r==null)return n;r.position+=t;let{position:i,velocity:a}=this.computeSpringStep(r,n,e);r.lastTimestamp=e,r.position=i,r.velocity=a;let{positionEpsilon:o,velocityEpsilon:s}=this.getSmoothScrollSettings();return Math.abs(n-i)<=o&&Math.abs(a)<=s?(r.position=n,r.velocity=0,this.scrollAnimation=void 0,n):r.position}computeRenderRangeAndEmit=(t=performance.now())=>{if(e.__STOP||this.container==null)return;let n=this.getHeight(),r=this.getScrollTop(),i=r,a=this.pendingLayoutAnchor!=null,o=this.getScrollAnchor(i);if(this.layoutDirtyIndex!=null&&(this.recomputeLayout(this.layoutDirtyIndex,this.pendingLayoutReset),this.layoutDirtyIndex=void 0,this.pendingLayoutReset=void 0,a=!0),a&&o!=null){let e=this.resolveAnchoredScrollTop(o);if(e!=null){let t=e-i;i=e,this.scrollAnimation!=null&&(this.scrollAnimation.position+=t)}}a&&(i=this.clampScrollTop(i),this.syncContainerHeight());let s=this.computeTargetScrollTopForFrame(i,t),c=!a&&(this.renderState.scrollTop===-1||Math.abs(s-this.renderState.scrollTop)>n+this.config.overscrollSize*2);c&&(o=void 0),this.windowSpecs=V({scrollTop:s,height:n,scrollHeight:this.getScrollHeight(),fitPerfectly:c,fitPerfectlyOverscroll:this.getFitPerfectlyOverscroll(),overscrollSize:this.config.overscrollSize});let l=r;(this.pendingScrollTarget!=null&&s!==l||this.needsScrollPageUpdate(s))&&(this.applyScrollFix(s,l,this.windowSpecs),l=s);let{top:u,bottom:d}=this.windowSpecs,{firstIndex:f,lastIndex:p}=this.renderState;if(f>=0)for(let e=f;e<=p;e++){let t=this.items[e];if(t==null)throw Error(`CodeView.computeRenderRangeAndEmit: No item at index: ${e}`);t.top>u-t.height&&t.top<=d||this.releaseRenderedItem(t)}let m,h=new Set,g=this.findFirstVisibleIndex(u),_=this.findLastVisibleIndex(d);for(let e=g;e<=_;e++){let t=this.items[e];if(t==null)throw Error(`CodeView.computeRenderRangeAndEmit: missing item`);let{instance:n}=t;t.element==null?(t.element=this.acquireElement(),Et(this.stickyContainer,t.element,m),n.virtualizedSetup(),Tt(t,t.element)&&(t.renderedOptionsRevision=this.renderOptionsRevision,h.add(t)),m=t.element):(Et(this.stickyContainer,t.element,m),Tt(t,void 0,t.renderedOptionsRevision!==this.renderOptionsRevision)&&(t.renderedOptionsRevision=this.renderOptionsRevision,h.add(t)),m=t.element)}this.renderState.firstIndex=g<=_?g:-1,this.renderState.lastIndex=_,this.flushSlotCoordinator(),this.reconcileRenderedItems(h),this.syncContainerHeight(),this.updateStickyPositioning();let v=o==null?void 0:this.resolveAnchoredScrollTop(o);o===this.pendingLayoutAnchor&&(this.pendingLayoutAnchor=void 0);let y=v==null?0:v-i,b=s,x=!1;if(this.pendingScrollTarget!=null){let e=this.advanceScrollAnimation(t,y);e==null?b=i:(b=e,x=!0)}else b=v??s;b!==l&&(this.applyScrollFix(b,l,this.windowSpecs),l=b),x&&this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0),this.renderState.scrollTop=J(l),this.flushManagers(h),this.validateStickyContainerHeight(),this.fixContainerFocus(),(c||this.scrollAnimation!=null)&&this.render()};flushManagers(e){for(let t of e)t.instance.flushManagers()}syncContainerHeight(){let e=this.getPagedScrollHeight();this.container==null||this.containerHeight===e||(this.container.style.height=`${e}px`,this.containerHeight=e)}getStickyBounds(e){let{firstIndex:t,lastIndex:n}=e==null?this.renderState:{firstIndex:this.findFirstVisibleIndex(e.top),lastIndex:this.findLastVisibleIndex(e.bottom)};if(t===-1||n===-1||t>n)return;let r=this.items[t]?.instance.getAdvancedStickySpecs(e),i=this.items[n]?.instance.getAdvancedStickySpecs(e);if(!(r==null||i==null))return{stickyTop:this.getPagedLayoutTop(Math.max(r.topOffset,0)),stickyBottom:this.getPagedLayoutTop(i.topOffset+i.height)}}applyStickyPositioning({stickyTop:e,stickyBottom:t}){let n=this.getHeight(),{itemMetricsCache:r}=this,i=t-e;this.renderState.stickyHeight=i,this.renderState.stickyTop=e,this.renderState.stickyBottom=t,this.stickyOffset.style.height=`${e}px`;let a=(Math.random()*r.lineHeight>>0)*-1,o=-Math.max(i+a,0)+n;this.stickyContainer.style.top=`${o}px`,this.stickyContainer.style.bottom=`${o+r.diffHeaderHeight}px`}syncPagedScrollScaffolding(e){this.syncContainerHeight();let t=this.getStickyBounds(e);t!=null&&this.applyStickyPositioning(t)}reconcileRenderedItems(e){let{firstIndex:t,lastIndex:n}=this.renderState;if(t===-1)return;let r=-1,i=!1;for(let a=t;a<this.items.length&&!(!i&&a>n);a++){let t=this.items[a];if(t==null)throw Error(`CodeView.reconcileRenderedItems: Invalid item`);r===-1?r=t.top:t.top!==r&&(t.top=r,t.instance.syncVirtualizedTop(),i=!0),(e==null?a<=n:e.has(t))&&(t.instance.reconcileHeights()&&(i=!0,t.height=t.instance.getVirtualizedHeight()),this.validateRenderedItemHeight(t)),r+=t.instance.getVirtualizedHeight(),a<this.items.length-1&&(r+=this.getLayout().gap)}i&&r!=null&&(this.scrollDirty=!0,this.scrollHeight=r)}updateStickyPositioning(){let e=this.getStickyBounds();if(e==null)return;let{stickyTop:t,stickyBottom:n}=e;n-t===this.renderState.stickyHeight&&t===this.renderState.stickyTop&&n===this.renderState.stickyBottom||this.applyStickyPositioning(e)}handleScroll=()=>{e.__STOP||(this.suspendScrollInteractions(),this.scrollDirty=!0,this.notifyScroll(),this.render())};clearPendingScroll=()=>{this.pendingScrollTarget=void 0,this.pendingLayoutAnchor=void 0,this.scrollAnimation=void 0};handleResize=e=>{for(let t of e)if(t.target===this.stickyContainer){if(t.borderBoxSize[0].blockSize!==this.renderState.stickyHeight){let e=this.getScrollTop(),t=this.getScrollAnchor(e);this.reconcileRenderedItems(),this.updateStickyPositioning();let n=t==null?void 0:this.resolveAnchoredScrollTop(t);if(n!=null){let t=n-e;this.applyScrollFix(n,e,this.windowSpecs),this.scrollAnimation!=null&&(this.scrollAnimation.position+=t)}this.pendingScrollTarget!=null&&this.isPendingTargetSettled(this.pendingScrollTarget)&&(this.pendingScrollTarget=void 0,this.scrollAnimation=void 0)}}else this.scrollDirty=!0,this.heightDirty=!0,this.render()};getScrollAnchorViewportTop(e,t){return e<t?t+this.getStickyHeaderOffset():t}getScrollAnchor(e){if(this.pendingLayoutAnchor!=null)return this.pendingLayoutAnchor;let{firstIndex:t,lastIndex:n,stickyTop:r,stickyBottom:i}=this.renderState;if(t===-1||n===-1)return;let a=this.getHeight();if(!(r===-1||i===-1))for(let r=t;r<=n;r++){let t=this.items[r];if(t==null)continue;let n=this.getLayout().paddingTop+t.top;if(n+t.height<=e)continue;if(n>=e+a)break;if(n>=e)return{type:`item`,id:t.item.id,viewportOffset:n-e};let i=this.getScrollAnchorViewportTop(n,e)-n,o=t.instance.getNumericScrollAnchor(i);if(o!=null){let r=n+o.top;return{type:`line`,id:t.item.id,lineNumber:o.lineNumber,side:o.side,viewportOffset:r-e}}}}resolveAnchoredScrollTop(e){let t=this.idToItem.get(e.id);if(t==null)return;let{paddingTop:n}=this.getLayout();if(e.type===`item`){let r=n+t.top;return this.clampScrollTop(r-e.viewportOffset)}let r=t.type===`diff`?t.instance.getLinePosition(e.lineNumber,e.side):t.instance.getLinePosition(e.lineNumber);if(r==null)return;let i=n+t.top+r.top;return this.clampScrollTop(i-e.viewportOffset)}applyScrollFix(e,t,n){if(this.root==null)return;let r=J(this.clampScrollTop(e)),i=J(t),{scrollPageOffset:a}=this,o=J(this.clampPagedScrollTop(i-a)),{pagedScrollTop:s,scrollPageOffset:c}=this.resolvePagedScrollPosition(r),l=s,u=a!==c;r===this.renderState.scrollTop&&r===i&&l===o&&!u||(this.suspendScrollInteractions(),(l!==o||u)&&(this.scrollPageOffset=c,this.syncPagedScrollScaffolding(n)),l!==o&&this.root.scrollTo({top:l,behavior:`instant`}),this.renderState.scrollTop=r,this.scrollTop=r,this.scrollDirty=!1)}isPendingTargetSettled(e){let t=this.resolveScrollTargetTop(e);return t==null?!0:J(this.getScrollTop())===J(t)}getScrollTop(){if(!this.scrollDirty)return this.scrollTop;this.scrollDirty=!1;let e=this.root?.scrollTop??0;return this.scrollTop=this.clampScrollTop(e+this.scrollPageOffset),this.scrollTop}getHeight(){return this.heightDirty?(this.heightDirty=!1,this.height=this.root?.getBoundingClientRect().height??0,this.height):this.height}getScrollHeight(){return this.scrollHeight}flushSlotCoordinator(){if(this.slotCoordinator==null)return;let{onSnapshotChange:e}=this.slotCoordinator,t=Ot(this.getRenderedItems(),this.slotCoordinator);kt(this.slotSnapshot,t)||(this.slotSnapshot=t,e(t))}notifyScroll(){if(this.scrollListeners.size===0)return;let e=this.getScrollTop();for(let t of this.scrollListeners)t(e,this)}findFirstVisibleIndex(e){let t=0,n=this.items.length-1,r=this.items.length;for(;t<=n;){let i=t+n>>1,a=this.items[i];if(a==null)throw Error(`CodeView.findFirstVisibleIndex: invalid item index`);a.top+a.height>e?(r=i,n=i-1):t=i+1}return r}findLastVisibleIndex(e){let t=0,n=this.items.length-1,r=-1;for(;t<=n;){let i=t+n>>1,a=this.items[i];if(a==null)throw Error(`CodeView.findLastVisibleIndex: invalid item index`);a.top<=e?(r=i,t=i+1):n=i-1}return r}recomputeLayout(e=0,t){if(this.items.length===0){this.scrollHeight=0;return}let n=this.getLayout(),r=0;if(e>0){let t=this.items[e-1];if(t==null)throw Error(`CodeView.recomputeLayout: invalid dirty index`);r=t.top+t.height+n.gap}for(let i=e;i<this.items.length;i++){let e=this.items[i];if(e==null)throw Error(`CodeView.recomputeLayout: invalid item index`);e.top=r,e.type===`diff`?e.height=e.instance.prepareCodeViewItem(e.item.fileDiff,r,t,e.item.annotations??[]):e.height=e.instance.prepareCodeViewItem(e.item.file,r,t,e.item.annotations??[]),r+=e.height,i<this.items.length-1&&(r+=n.gap)}r!==this.scrollHeight&&(this.scrollDirty=!0),this.scrollHeight=r}resetRenderState(){this.renderState.scrollTop=-1,this.renderState.firstIndex=-1,this.renderState.lastIndex=-1,this.renderState.stickyHeight=0,this.renderState.stickyTop=-1,this.renderState.stickyBottom=-1}getFitPerfectlyOverscroll(){return this.getLayout().gap+this.itemMetricsCache.diffHeaderHeight}};function vt(e){return e.instance.cleanUp(!0),e.type===`diff`?e.instance.prepareCodeViewItem(e.item.fileDiff,e.top,void 0,e.item.annotations??[]):e.instance.prepareCodeViewItem(e.item.file,e.top,void 0,e.item.annotations??[])}function yt(e,t){return!I(e.theme??Ue,t.theme??Ue)||(e.themeType??`system`)!==(t.themeType??`system`)||e.unsafeCSS!==t.unsafeCSS}function bt(e,t){return(e.overflow??`scroll`)!==(t.overflow??`scroll`)||(e.disableLineNumbers??!1)!==(t.disableLineNumbers??!1)||(e.disableFileHeader??!1)!==(t.disableFileHeader??!1)||e.unsafeCSS!==t.unsafeCSS||(e.diffStyle??`split`)!==(t.diffStyle??`split`)||(e.diffIndicators??`bars`)!==(t.diffIndicators??`bars`)||(e.hunkSeparators??`line-info`)!==(t.hunkSeparators??`line-info`)||(e.expandUnchanged??!1)!==(t.expandUnchanged??!1)||(e.collapsedContextThreshold??1)!==(t.collapsedContextThreshold??1)}function xt(e,t){return(e.disableFileHeader??!1)!==(t.disableFileHeader??!1)||(e.hunkSeparators??`line-info`)!==(t.hunkSeparators??`line-info`)||(e.expandUnchanged??!1)!==(t.expandUnchanged??!1)||(e.collapsedContextThreshold??1)!==(t.collapsedContextThreshold??1)}function St(e){return e instanceof SVGElement?!0:G(e)&&(e.hasAttribute(`data-core-css`)||e.hasAttribute(`data-theme-css`)||e.hasAttribute(`data-unsafe-css`))}function Ct(e){let t=wt(e.start,e.side),n=wt(e.end,e.endSide??e.side);return t===n?t:`${t}-${n}`}function wt(e,t){return t==null?`${e}`:`${t===`deletions`?`D`:`A`}${e}`}function Tt(e,t,n=!1){return e.type===`diff`?e.instance.render({deferManagers:!0,fileContainer:t,fileDiff:e.item.fileDiff,forceRender:n,lineAnnotations:e.item.annotations??[]}):e.instance.render({deferManagers:!0,fileContainer:t,file:e.item.file,forceRender:n,lineAnnotations:e.item.annotations??[]})}function Et(e,t,n){if(n==null){e.firstChild!==t&&e.prepend(t);return}n.nextSibling!==t&&n.after(t)}function Dt(e){return(e.annotations?.length??0)>0}function Ot(e,{hasHeaderRenderers:t,hasAnnotationRenderer:n,hasGutterRenderer:r}){if(e.length===0)return;if(t||r)return e;if(!n)return;let i=[];for(let t of e)Dt(t.item)&&i.push(t);return i.length>0?i:void 0}function kt(e,t){if(e==null||t==null)return e===t;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r==null||i==null||r.id!==i.id||r.type!==i.type||r.element!==i.element||r.version!==i.version)return!1}return!0}function At(e,t){if(e==null||t==null)return e===t;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r==null||i==null||r.id!==i.id||r.type!==i.type||r.element!==i.element||r.version!==i.version)return!1}return!0}var Q=N(M(),1),$=C(),jt=N(w(),1),Mt=typeof window>`u`?Q.useEffect:Q.useLayoutEffect;function Nt(e){return{instance:void 0,items:void 0,controlled:e,managedOptions:void 0,disableFlushSync:!1,slotCoordinator:void 0}}function Pt(e,t){let{className:n,containerRef:r,disableWorkerPool:i=!1,initialItems:a,items:o,onScroll:s,onSelectedLinesChange:c,options:l,renderAnnotation:u,renderCustomHeader:d,renderGutterUtility:f,renderHeaderMetadata:p,renderHeaderPrefix:m,selectedLines:h,style:g}=e,_=o!==void 0,v=(0,Q.useContext)(fe),y=(0,Q.useRef)(Nt(_)),b=d!=null,x=u!=null,S=f!=null,C=b||m!=null||p!=null,ee=C||x||S,w=K(e=>{c?.(e)}),T=h!==void 0,E=(0,Q.useMemo)(()=>Bt({options:l,hasCustomHeader:b,hasGutterRenderer:S,onSelectedLinesChange:c==null?void 0:w,controlledSelection:T}),[l,b,S,c,w,T]),[D]=(0,Q.useState)(()=>zt()),[,O]=(0,Q.useState)({}),k=K(e=>{y.current.instance!=null&&(e==null||e!==y.current.instance.getContainerElement())&&(y.current.instance.cleanUp(),D.publish(void 0),y.current=Nt(_)),e!=null&&e!==y.current.instance?.getContainerElement()&&(y.current.instance=new _t(E,i?void 0:v,!0),y.current.instance.setup(e)),typeof r==`function`?r(e):r!=null&&(r.current=e)}),A=K(e=>{y.current.disableFlushSync?D.publish(e):(0,jt.flushSync)(()=>{D.publish(e)})}),j=(0,Q.useMemo)(()=>{if(!(!C&&!x&&!S))return{hasHeaderRenderers:C,hasAnnotationRenderer:x,hasGutterRenderer:S,onSnapshotChange:A}},[A,x,S,C]);return Mt(()=>s==null?void 0:y.current.instance?.subscribeToScroll(s)),Mt(()=>{let{instance:e,controlled:t,items:n,managedOptions:r,slotCoordinator:i}=y.current;if(e!=null)try{y.current.disableFlushSync=!0;let s=!1;if(R(E,r)||(y.current.managedOptions=E,e.setOptions(E),s=!0),t!==_){console.error(`CodeView: cannot switch between controlled and uncontrolled modes. Remount with a new key instead.`);return}if(_)o!==n&&(Lt(n,o)?y.current.items=o:It(n,o)?(y.current.items=o,e.addItems(o.slice(n.length))):(y.current.items=o,e.setItems(o),s=!0));else if(n==null){let t=a??[];y.current.items=t,t.length>0&&(e.setItems(t),s=!0)}h!==void 0&&e.setSelectedLines(h,{notify:!1});let c=e.setSlotCoordinator(j),l=!1;j!==i&&((j==null||i==null)&&(l=!0),y.current.slotCoordinator=j),(s||c)&&e.render(!0),c&&j==null&&D.publish(void 0),l&&O({})}finally{y.current.disableFlushSync=!1}}),(0,Q.useImperativeHandle)(t,()=>({addItems(e){let{controlled:t,instance:n}=y.current;Rt(t,`addItems`),n==null?console.error(`CodeView.addItems: no valid instance to append items with`,e):n.addItems(e)},getItem(e){let{instance:t}=y.current;if(t==null){console.error(`CodeView.getItem: no valid instance exists`,e);return}else return t.getItem(e)},updateItem(e){let{controlled:t,instance:n}=y.current;return Rt(t,`updateItem`),n==null?(console.error(`CodeView.updateItem: no valid instance to update item with`,e),!1):n.updateItem(e)},updateItemId(e,t){let{controlled:n,instance:r}=y.current;return Rt(n,`updateItemId`),r==null?(console.error(`CodeView.updateItemId: no valid instance to update item id with`,e,t),!1):r.updateItemId(e,t)},scrollTo(e){let{instance:t}=y.current;t==null?console.error(`CodeView.scrollTo: no valid instance to scroll with`,e):t.scrollTo(e)},setSelectedLines(e){let{instance:t}=y.current;t==null?console.error(`CodeView.setSelectedLines: no valid instance to update selection with`,e):(t.setSelectedLines(e,{notify:!1}),w(e))},getSelectedLines(){let{instance:e}=y.current;return e==null?(console.error(`CodeView.getSelectedLines: no valid instance exists`),null):e.getSelectedLines()},clearSelectedLines(){let{instance:e}=y.current;e==null?console.error(`CodeView.clearSelectedLines: no valid instance to update selection with`):(e.clearSelectedLines({notify:!1}),w(null))},getInstance(){return y.current.instance}}),[w]),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{ref:k,className:n,style:g}),ee&&(0,$.jsx)(Vt,{managedContentStore:D,renderCustomHeader:d,renderHeaderPrefix:m,renderHeaderMetadata:p,renderAnnotation:u,renderGutterUtility:f})]})}var Ft=(0,Q.forwardRef)(Pt);function It(e,t){if(e==null||t.length<=e.length)return!1;if(e.length===0)return!0;for(let n=0;n<e.length;n++)if(t[n]!==e[n])return!1;return!0}function Lt(e,t){if(e==null||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Rt(e,t){if(e)throw Error(`CodeView.${t} cannot be used when CodeView is controlled. Use initialItems for imperative item updates.`)}function zt(){let e,t=new Set;return{getSnapshot(){return e},publish(n){if(!At(e,n)){e=n;for(let e of t)e()}},subscribe(e){return t.add(e),()=>{t.delete(e)}}}}function Bt({options:e,hasCustomHeader:t,hasGutterRenderer:n,onSelectedLinesChange:r,controlledSelection:i}){return!t&&!n&&r==null&&!i?e:(e={...e,controlledSelection:i,onSelectedLinesChange:r},t&&(e.renderCustomHeader=Ut),n&&(e.renderGutterUtility=Ut),e)}var Vt=(0,Q.memo)(function({managedContentStore:e,renderCustomHeader:t,renderHeaderPrefix:n,renderHeaderMetadata:r,renderAnnotation:i,renderGutterUtility:a}){let o=K(t=>e.subscribe(t)),s=K(()=>e.getSnapshot());return(0,Q.useSyncExternalStore)(o,s,s)?.map(e=>(0,jt.createPortal)(Ht({renderedItem:e,renderCustomHeader:t,renderHeaderPrefix:n,renderHeaderMetadata:r,renderAnnotation:i,renderGutterUtility:a}),e.element,e.id))});function Ht({renderedItem:e,renderCustomHeader:t,renderHeaderPrefix:n,renderHeaderMetadata:r,renderAnnotation:i,renderGutterUtility:a}){if(e.type===`diff`){let{item:o,instance:s}=e;return z({fileDiff:o.fileDiff,renderCustomHeader:t==null?void 0:()=>t(o),renderHeaderPrefix:n==null?void 0:()=>n(o),renderHeaderMetadata:r==null?void 0:()=>r(o),renderAnnotation:i==null?void 0:e=>i(e,o),lineAnnotations:o.annotations,renderGutterUtility:a==null?void 0:e=>a(e,o),getHoveredLine:s.getHoveredLine})}else{let{item:o,instance:s}=e;return ce({file:o.file,renderCustomHeader:t==null?void 0:()=>t(o),renderHeaderPrefix:n==null?void 0:()=>n(o),renderHeaderMetadata:r==null?void 0:()=>r(o),renderAnnotation:i==null?void 0:e=>i(e,o),lineAnnotations:o.annotations,renderGutterUtility:a==null?void 0:e=>a(e,o),getHoveredLine:s.getHoveredLine})}}function Ut(){}function Wt({threadRef:e,filePath:t,activeCwd:n,openInEditor:r}){if(e){A.getState().openFile(e,t);return}r(n?B(t,n):t)}var Gt=a();function Kt(e,t){let n=(0,Gt.c)(4),r=Ye(e,t),i;return n[0]!==r.data||n[1]!==r.error||n[2]!==r.isPending?(i={data:r.data,error:r.error,isPending:r.isPending},n[0]=r.data,n[1]=r.error,n[2]=r.isPending,n[3]=i):i=n[3],i}function qt(e,t){return e.length>0&&e.every(e=>t.has(e))}function Jt(e,t){return qt(e,t)?new Set:new Set(e)}function Yt(e){return _(`flex items-center justify-between gap-2 px-4`,et&&e!==`sheet`&&e!==`embedded`?`drag-region h-[52px] border-b border-border wco:h-[env(titlebar-area-height)] wco:pr-[calc(100vw-env(titlebar-area-width)-env(titlebar-area-x)+1em)]`:`surface-subheader`)}function Xt(e){let t=(0,Gt.c)(10),n=et&&e.mode!==`sheet`&&e.mode!==`embedded`,r=e.mode===`inline`?`w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border`:`w-full`,i;t[0]===r?i=t[1]:(i=_(`flex h-full min-w-0 flex-col bg-background`,r),t[0]=r,t[1]=i);let a;t[2]!==e.header||t[3]!==e.mode||t[4]!==n?(a=n?(0,$.jsx)(`div`,{className:Yt(e.mode),children:e.header}):(0,$.jsx)(`div`,{className:Yt(e.mode),"data-surface-subheader":!0,children:e.header}),t[2]=e.header,t[3]=e.mode,t[4]=n,t[5]=a):a=t[5];let o;return t[6]!==e.children||t[7]!==i||t[8]!==a?(o=(0,$.jsxs)(`div`,{className:i,children:[a,e.children]}),t[6]=e.children,t[7]=i,t[8]=a,t[9]=o):o=t[9],o}function Zt(e){let t=(0,Gt.c)(7),n;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(n=(0,$.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border/50 px-3 py-2`,children:[(0,$.jsx)(L,{className:`h-4 w-32 rounded-full`}),(0,$.jsx)(L,{className:`ml-auto h-4 w-20 rounded-full`})]}),t[0]=n):n=t[0];let r;t[1]===Symbol.for(`react.memo_cache_sentinel`)?(r=(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(L,{className:`h-3 w-full rounded-full`}),(0,$.jsx)(L,{className:`h-3 w-full rounded-full`}),(0,$.jsx)(L,{className:`h-3 w-10/12 rounded-full`}),(0,$.jsx)(L,{className:`h-3 w-11/12 rounded-full`}),(0,$.jsx)(L,{className:`h-3 w-9/12 rounded-full`})]}),t[1]=r):r=t[1];let i;t[2]===e.label?i=t[3]:(i=(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-4 px-3 py-4`,children:[r,(0,$.jsx)(`span`,{className:`sr-only`,children:e.label})]}),t[2]=e.label,t[3]=i);let a;return t[4]!==e.label||t[5]!==i?(a=(0,$.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col p-2`,children:(0,$.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border/60 bg-card/25`,role:`status`,"aria-live":`polite`,"aria-label":e.label,children:[n,i]})}),t[4]=e.label,t[5]=i,t[6]=a):a=t[6],a}var Qt=[];function $t(e){return(e.endSide??e.side)===`deletions`?`deletions`:`additions`}function en(e,t,n){let r=$t(t),i=e.findIndex(e=>e.side===r&&e.lineNumber===t.end);return i<0?[...e,{side:r,lineNumber:t.end,metadata:{entries:[n]}}]:e.map((e,t)=>t===i?{...e,metadata:{entries:[...e.metadata.entries,n]}}:e)}function tn(e){let t=(0,Gt.c)(50),{files:n,sectionId:r,sectionTitle:i,composerDraftTarget:a,options:o,viewerRef:s,className:c,renderHeaderPrefix:l}=e,u=p(sn),d=p(on),f;t[0]===a?f=t[1]:(f=e=>e.getComposerDraft(a)?.reviewComments??Qt,t[0]=a,t[1]=f);let m=p(f),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(null),b;t[2]===n?b=t[3]:(b=new Map(n.map(an)),t[2]=n,t[3]=b);let x=b,S;if(t[4]!==_||t[5]!==n||t[6]!==m||t[7]!==r){let e;t[9]!==_||t[10]!==m||t[11]!==r?(e=e=>{let{fileDiff:t,filePath:n,fileKey:i,collapsed:a}=e,o=m.filter(e=>e.sectionId===r&&e.filePath===n&&(e.fenceLanguage??`diff`)===`diff`).reduce((e,n)=>{let r=ne(t,n);return r?en(e,r,{id:n.id,kind:`comment`,range:r,rangeLabel:n.rangeLabel,text:n.text}):e},[]),s=_?.fileKey===i?[...o,_.annotation]:o;return{id:i,type:`diff`,fileDiff:t,annotations:s,collapsed:a,version:be(`${a?`1`:`0`}:${s.flatMap(nn).join(`:`)}`)}},t[9]=_,t[10]=m,t[11]=r,t[12]=e):e=t[12],S=n.map(e),t[4]=_,t[5]=n,t[6]=m,t[7]=r,t[8]=S}else S=t[8];let C=S,ee;t[13]!==a||t[14]!==_?.annotation||t[15]!==d?(ee=e=>{g(null),_?.annotation.metadata.entries.some(t=>t.id===e)?v(null):d(a,e)},t[13]=a,t[14]=_?.annotation,t[15]=d,t[16]=ee):ee=t[16];let w=ee,T;t[17]!==u||t[18]!==a||t[19]!==_||t[20]!==x||t[21]!==r||t[22]!==i?(T=(e,t)=>{let n=_?.annotation.metadata.entries.find(t=>t.id===e),o=_?x.get(_.fileKey):void 0;if(!n||!o)return;let s=y({id:n.id,sectionId:r,sectionTitle:i,filePath:o.filePath,fileDiff:o.fileDiff,range:n.range,text:t});s&&u(a,s),g(null),v(null)},t[17]=u,t[18]=a,t[19]=_,t[20]=x,t[21]=r,t[22]=i,t[23]=T):T=t[23];let E=T,D;t[24]!==x||t[25]!==r||t[26]!==i?(D=(e,t)=>{if(!e)return;let n=t.item;if(n.type!==`diff`)return;let a=x.get(n.id);if(!a)return;let o=F(),s=y({id:o,sectionId:r,sectionTitle:i,filePath:a.filePath,fileDiff:a.fileDiff,range:e,text:``});s&&v({fileKey:n.id,annotation:{side:$t(e),lineNumber:e.end,metadata:{entries:[{id:o,kind:`draft`,range:e,rangeLabel:s.rangeLabel,text:``}]}}})},t[24]=x,t[25]=r,t[26]=i,t[27]=D):D=t[27];let O=D,k=_!==null,A;t[28]===s?A=t[29]:(A=s?{ref:s}:{},t[28]=s,t[29]=A);let j;t[30]===c?j=t[31]:(j=c?{className:c}:{},t[30]=c,t[31]=j);let te=!k,re=!k,M;t[32]!==O||t[33]!==o||t[34]!==re||t[35]!==te?(M={...o,enableGutterUtility:te,enableLineSelection:re,onLineSelectionEnd:O},t[32]=O,t[33]=o,t[34]=re,t[35]=te,t[36]=M):M=t[36];let ie;t[37]===l?ie=t[38]:(ie=e=>e.type===`diff`?l(e.fileDiff,e.id,e.collapsed===!0):null,t[37]=l,t[38]=ie);let N;t[39]!==w||t[40]!==E?(N=e=>(0,$.jsx)(`div`,{className:`py-1`,children:e.metadata.entries.map(e=>(0,$.jsx)(se,{kind:e.kind,rangeLabel:e.rangeLabel,text:e.text,onCancel:()=>w(e.id),onComment:t=>E(e.id,t),onDelete:()=>w(e.id)},e.id))}),t[39]=w,t[40]=E,t[41]=N):N=t[41];let P;return t[42]!==C||t[43]!==h||t[44]!==M||t[45]!==ie||t[46]!==N||t[47]!==A||t[48]!==j?(P=(0,$.jsx)(Ft,{...A,...j,items:C,selectedLines:h,onSelectedLinesChange:g,options:M,renderHeaderPrefix:ie,renderAnnotation:N}),t[42]=C,t[43]=h,t[44]=M,t[45]=ie,t[46]=N,t[47]=A,t[48]=j,t[49]=P):P=t[49],P}function nn(e){return e.metadata.entries.map(rn)}function rn(e){return`${e.id}:${e.rangeLabel}:${e.text}`}function an(e){return[e.fileKey,e]}function on(e){return e.removeReviewComment}function sn(e){return e.addReviewComment}var cn=function(e){return e.disabled=`data-disabled`,e.orientation=`data-orientation`,e.multiple=`data-multiple`,e}({}),ln={multiple(e){return e?{[cn.multiple]:``}:null}},un=Q.forwardRef(function(r,i){let{defaultValue:a,disabled:o=!1,loopFocus:s=!0,onValueChange:c,orientation:l=`horizontal`,multiple:u=!1,value:d,className:f,render:p,style:m,...h}=r,_=t(!0),v=Q.useMemo(()=>d!==void 0||a!==void 0,[d,a]),y=(_?.disabled??!1)||o,[b,x]=re({controlled:d,default:d===void 0?a??g:void 0,name:`ToggleGroup`,state:`value`}),S=e((e,t,n)=>{let r;u?(r=b.slice(),t?r.push(e):r.splice(b.indexOf(e),1)):r=t?[e]:[],c?.(r,n),!n.isCanceled&&x(r)}),C={disabled:y,multiple:u,orientation:l},ee=Q.useMemo(()=>({disabled:y,orientation:l,setGroupValue:S,value:b,isValueInitialized:v}),[y,l,S,b,v]),w={role:`group`},T=n(`div`,r,{enabled:!!_,state:C,ref:i,props:[w,h],stateAttributesMapping:ln});return(0,$.jsx)(ue.Provider,{value:ee,children:_?T:(0,$.jsx)(we,{render:p,className:f,style:m,state:C,refs:[i],props:[w,h],stateAttributesMapping:ln,loopFocus:s,enableHomeAndEndKeys:!0,orientation:l})})}),dn=Q.createContext({size:`default`,variant:`default`});function fn(e){let t=(0,Gt.c)(24),n,r,i,a,o,s;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4],o=t[5],s=t[6]):({className:r,variant:a,size:o,orientation:s,children:n,...i}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a,t[5]=o,t[6]=s);let c=a===void 0?`default`:a,l=o===void 0?`default`:o,u=s===void 0?`horizontal`:s,d;t[7]!==l||t[8]!==c?(d={size:l,variant:c},t[7]=l,t[8]=c,t[9]=d):d=t[9];let f=d,p=u===`horizontal`?`*:pointer-coarse:after:min-w-auto`:`*:pointer-coarse:after:min-h-auto`,m=c==="default"?`gap-0.5`:u===`horizontal`?`*:not-first:not-data-[slot=separator]:before:-start-[0.5px] *:not-last:not-data-[slot=separator]:before:-end-[0.5px] *:not-first:rounded-s-none *:not-last:rounded-e-none *:not-first:border-s-0 *:not-last:border-e-0 *:not-first:before:rounded-s-none *:not-last:before:rounded-e-none`:`*:not-first:not-data-[slot=separator]:before:-top-[0.5px] *:not-last:not-data-[slot=separator]:before:-bottom-[0.5px] flex-col *:not-first:rounded-t-none *:not-last:rounded-b-none *:not-first:border-t-0 *:not-last:border-b-0 *:not-first:before:rounded-t-none *:not-last:before:rounded-b-none *:data-[slot=toggle]:not-last:before:hidden dark:*:last:before:hidden dark:*:first:before:block`,h;t[10]!==r||t[11]!==p||t[12]!==m?(h=_(`flex w-fit *:focus-visible:z-10 dark:*:[[data-slot=separator]:has(+[data-slot=toggle]:hover)]:before:bg-input/64 dark:*:[[data-slot=separator]:has(+[data-slot=toggle][data-pressed])]:before:bg-input dark:*:[[data-slot=toggle]:hover+[data-slot=separator]]:before:bg-input/64 dark:*:[[data-slot=toggle][data-pressed]+[data-slot=separator]]:before:bg-input`,p,m,r),t[10]=r,t[11]=p,t[12]=m,t[13]=h):h=t[13];let g;t[14]!==n||t[15]!==f?(g=(0,$.jsx)(dn,{value:f,children:n}),t[14]=n,t[15]=f,t[16]=g):g=t[16];let v;return t[17]!==u||t[18]!==i||t[19]!==l||t[20]!==h||t[21]!==g||t[22]!==c?(v=(0,$.jsx)(un,{className:h,"data-size":l,"data-slot":`toggle-group`,"data-variant":c,orientation:u,...i,children:g}),t[17]=u,t[18]=i,t[19]=l,t[20]=h,t[21]=g,t[22]=c,t[23]=v):v=t[23],v}function pn(e){let t=(0,Gt.c)(12),n,r,i,a,o;t[0]===e?(n=t[1],r=t[2],i=t[3],a=t[4],o=t[5]):({className:r,children:n,variant:o,size:a,...i}=e,t[0]=e,t[1]=n,t[2]=r,t[3]=i,t[4]=a,t[5]=o);let s=Q.use(dn),c=o??s.variant,l=a??s.size,u;return t[6]!==n||t[7]!==r||t[8]!==i||t[9]!==l||t[10]!==c?(u=(0,$.jsx)(Qe,{className:r,"data-size":l,"data-variant":c,size:l,variant:c,...i,children:n}),t[6]=n,t[7]=r,t[8]=i,t[9]=l,t[10]=c,t[11]=u):u=t[11],u}function mn(e){return{diffPreview:k(e,{label:`environment-data:review:diff-preview`,tag:v.reviewGetDiffPreview,staleTimeMs:5e3})}}var hn=mn(c);function gn(e){return e.remoteName&&e.name.startsWith(`${e.remoteName}/`)?e.name.slice(e.remoteName.length+1):e.name}function _n(e,t){let n=new Set(t),r=e.map(e=>{let r=t.filter(t=>n.has(t)&&gn(t)===e.name),i=r.find(e=>e.remoteName===`origin`)??r[0]??null;return i&&n.delete(i),{id:`local:${e.name}`,label:e.name,local:e,remote:i}}),i=t.filter(e=>n.has(e)).map(e=>({id:`remote:${e.name}`,label:e.name,local:null,remote:e}));return[...r,...i]}function vn(e,t){let n=t.trim().toLocaleLowerCase();return n.length===0?e:e.filter(e=>e.label.toLocaleLowerCase().includes(n)||e.local?.name.toLocaleLowerCase().includes(n)===!0||e.remote?.name.toLocaleLowerCase().includes(n)===!0)}var yn=`__automatic_base_ref__`,bn=new Set,xn=`
2
2
  [data-diffs-header],
3
3
  [data-diff],
4
4
  [data-file],
@@ -95,4 +95,4 @@ import{$a as e,Ai as t,Ao as n,As as r,Br as i,Ff as a,Go as o,Gr as s,H as c,Ho
95
95
  text-decoration-color: currentColor;
96
96
  }
97
97
  `;function Sn({mode:e=`inline`,composerDraftTarget:t,initialGitScope:n}){let{resolvedTheme:a}=he(),o=Ze(),[c]=(0,Q.useState)(n),[p,g]=(0,Q.useState)(`stacked`),[v,y]=(0,Q.useState)(o.wordWrap),[C,w]=(0,Q.useState)(o.diffIgnoreWhitespace),[k,A]=(0,Q.useState)(``),[ne,re]=(0,Q.useState)(()=>({scopeKey:null,fileKeys:bn})),M=(0,Q.useRef)(null),N=u({strict:!1,select:e=>ie(e)}),se=N?.threadId??null,F=Le(N),ce=F?.projectId??null,le=Be(F&&ce?{environmentId:F.environmentId,projectId:ce}:null),I=F?.worktreePath??le?.workspaceRoot,ue=D(b.configValueAtom(F?.environmentId??null)),fe=Ae(F?.environmentId??null,ue?.availableEditors??[]),be=P(F!=null&&I!=null?He.status({environmentId:F.environmentId,input:{cwd:I}}):null),L=De(e=>xe(e.byThreadKey,N,c===`unstaged`)),we=be.data?.isRepo??!0,{turnDiffSummaries:Ee,inferredCheckpointTurnCountByTurnId:R}=ge(F),z=(0,Q.useMemo)(()=>[...Ee].toSorted((e,t)=>{let n=e.checkpointTurnCount??R[e.turnId]??0,r=t.checkpointTurnCount??R[t.turnId]??0;return n===r?t.completedAt.localeCompare(e.completedAt):r-n}),[R,Ee]);(0,Q.useEffect)(()=>{!N||L.kind!==`turn`||De.getState().reconcileTurnSelection(N,z.map(e=>e.turnId))},[L,z,N]);let B=L.kind===`turn`?L.turnId:null,V=L.kind===`unstaged`?`unstaged`:`branch`,H=L.kind===`branch`?L.baseRef:null,Ie=L.kind===`turn`?L.filePath:null,Re=L.kind===`turn`?L.revealRequestId:0,U=B===null?void 0:z.find(e=>e.turnId===B)??z[0],W=U&&(U.checkpointTurnCount??R[U.turnId]),ze=z[0],Ue=B===null?V===`unstaged`?`Working tree`:`Branch changes`:U?.turnId===ze?.turnId?`Latest turn`:`Turn ${W??`?`}`,We=U?`turn:${U.turnId}`:V,G=N?`${N.environmentId}:${N.threadId}:${We}`:null,Ge=ne.scopeKey===G?ne.fileKeys:bn,Ke=U?`Turn ${W??`?`}`:V===`unstaged`?`Working tree`:`Branch changes`,Je=(0,Q.useMemo)(()=>typeof W==`number`?{fromTurnCount:Math.max(0,W-1),toTurnCount:W}:null,[W]),K=Kt({environmentId:F?.environmentId??null,threadId:se,fromTurnCount:Je?.fromTurnCount??null,toTurnCount:Je?.toTurnCount??null,ignoreWhitespace:C,cacheScope:U?`turn:${U.turnId}`:null},{enabled:we&&U!==void 0}),Ye=P(B===null&&F&&I?hn.diffPreview({environmentId:F.environmentId,input:{cwd:I,...H?{baseRef:H}:{},ignoreWhitespace:C}}):null),Qe=B===null&&Ye.error?.includes(`configured workspace root`)===!0&&ue?.cwd!==void 0&&ue.cwd!==I,et=P(Qe&&F&&ue?hn.diffPreview({environmentId:F.environmentId,input:{cwd:ue.cwd,...H?{baseRef:H}:{},ignoreWhitespace:C}}):null),q=Qe?et:Ye,J=q.data?.sources.find(e=>e.kind===(V===`unstaged`?`working-tree`:`branch-range`)),it=P(B===null&&V===`branch`&&F&&q.data?.cwd?He.listRefs({environmentId:F.environmentId,input:{cwd:q.data.cwd,includeMatchingRemoteRefs:!0,refKind:`local`,...k.trim().length>0?{query:k.trim()}:{},limit:100}}):null),at=P(B===null&&V===`branch`&&F&&q.data?.cwd?He.listRefs({environmentId:F.environmentId,input:{cwd:q.data.cwd,includeMatchingRemoteRefs:!0,refKind:`remote`,...k.trim().length>0?{query:k.trim()}:{},limit:100}}):null),ot=_n(it.data?.refs.filter(e=>e.name!==J?.headRef)??[],at.data?.refs??[]),st=vn(ot,k),ct=e=>H&&H===e.remote?.name?H:e.local?.name??e.remote?.name??e.id,lt=[yn,...ot.map(ct)],ut=[...k.trim().length===0?[yn]:[],...st.map(ct)],Y=J?.diff,dt=U?K.data?.diff:Y,ft=!U&&J?.truncated===!0,pt=U?K.isPending:q.isPending,mt=U?K.error:q.error,ht=typeof dt==`string`&&dt.trim().length===0,X=(0,Q.useMemo)(()=>Ne(dt,`diff-panel:${a}`,{compactPartialHunkOffsets:B===null}),[a,dt,B]),gt=(0,Q.useMemo)(()=>!X||X.kind!==`files`?[]:X.files.toSorted((e,t)=>Fe(e).localeCompare(Fe(t),void 0,{numeric:!0,sensitivity:`base`})),[X]),Z=(0,Q.useMemo)(()=>gt.map(e=>{let t=me(e);return{fileDiff:e,filePath:Fe(e),fileKey:t,collapsed:Ge.has(t)}}),[Ge,gt]),_t=(0,Q.useMemo)(()=>Z.map(e=>e.fileKey),[Z]),vt=qt(_t,Ge),yt=(0,Q.useMemo)(()=>ye(gt),[gt]);(0,Q.useEffect)(()=>{if(!Ie)return;let e=Z.find(e=>e.filePath===Ie);e&&M.current?.scrollTo({type:`item`,id:e.fileKey,align:`start`})},[Z,Ie,Re]);let bt=(0,Q.useCallback)(e=>{Wt({threadRef:N,filePath:e,activeCwd:I,openInEditor:e=>{(async()=>{let t=await fe(e);t._tag===`Failure`&&!T(t)&&console.warn(`Failed to open diff file in editor.`,{operation:`open-diff-file`,...N?{environmentId:N.environmentId,threadId:N.threadId}:{},...r(x(t))})})()}})},[I,fe,N]),xt=(0,Q.useCallback)(e=>{re(t=>{let n=new Set(t.scopeKey===G?t.fileKeys:[]);return n.has(e)?n.delete(e):n.add(e),{scopeKey:G,fileKeys:n}})},[G]),St=(0,Q.useCallback)(()=>{re(e=>{let t=e.scopeKey===G?e.fileKeys:bn;return{scopeKey:G,fileKeys:Jt(_t,t)}})},[G,_t]),Ct=e=>{N&&De.getState().selectTurn(N,e)},wt=e=>{N&&De.getState().selectGitScope(N,e)},Tt=e=>{N&&De.getState().selectBranchBaseRef(N,e)};return(0,$.jsx)(Xt,{mode:e,header:(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center gap-3 [-webkit-app-region:no-drag]`,children:[(0,$.jsxs)(d,{children:[(0,$.jsxs)(f,{className:`inline-flex h-6 max-w-full items-center gap-1 rounded-md bg-muted/70 px-2 text-xs font-medium text-foreground outline-none transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring`,"aria-label":`Diff scope: ${Ue}`,children:[(0,$.jsx)(`span`,{className:`truncate`,children:Ue}),(0,$.jsx)(S,{className:`size-3.5 shrink-0 text-muted-foreground`})]}),(0,$.jsxs)(i,{align:`start`,className:`w-60`,children:[(0,$.jsx)(ae,{className:B===null&&V===`unstaged`?`bg-foreground/[0.08]`:void 0,onClick:()=>wt(`unstaged`),children:(0,$.jsx)(`span`,{children:`Working tree`})}),(0,$.jsx)(ae,{className:B===null&&V===`branch`?`bg-foreground/[0.08]`:void 0,onClick:()=>wt(`branch`),children:(0,$.jsx)(`span`,{children:`Branch changes`})}),(0,$.jsx)(ae,{className:B!==null&&U?.turnId===ze?.turnId?`bg-foreground/[0.08]`:void 0,onClick:()=>{ze&&Ct(ze.turnId)},children:(0,$.jsx)(`span`,{children:`Latest turn`})}),(0,$.jsxs)(s,{children:[(0,$.jsx)(te,{children:`Turn`}),(0,$.jsx)(m,{className:`w-64`,children:z.map(e=>{let t=e.checkpointTurnCount??R[e.turnId]??`?`;return(0,$.jsxs)(ae,{className:e.turnId===U?.turnId?`bg-foreground/[0.08]`:void 0,onClick:()=>Ct(e.turnId),children:[(0,$.jsxs)(`span`,{children:[`Turn `,t]}),(0,$.jsx)(`span`,{className:`ml-auto text-xs tabular-nums text-muted-foreground`,children:Pe(e.completedAt,o.timestampFormat)})]},e.turnId)})})]})]})]}),B===null&&V===`branch`&&J?.baseRef&&(0,$.jsxs)(`div`,{className:`flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground`,title:`${J.headRef??`HEAD`} → ${J.baseRef}`,"aria-label":`Comparing ${J.headRef??`HEAD`} against ${J.baseRef}`,children:[(0,$.jsx)(`span`,{className:`min-w-0 max-w-48 truncate`,children:J.headRef??`HEAD`}),(0,$.jsx)(oe,{className:`size-3.5 shrink-0 opacity-70`}),(0,$.jsxs)(pe,{items:lt,filteredItems:ut,value:H??yn,onOpenChange:e=>{e||A(``)},onValueChange:e=>{e&&Tt(e===yn?null:e)},children:[(0,$.jsxs)(je,{className:`inline-flex min-w-0 max-w-48 items-center gap-1 overflow-hidden rounded-md px-1.5 py-1 outline-none transition-colors hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring`,"aria-label":`Change comparison target. Currently ${J.baseRef}`,children:[(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:J.baseRef}),(0,$.jsx)(S,{className:`size-3.5 shrink-0 opacity-70`})]}),(0,$.jsxs)(de,{align:`start`,className:`w-72 min-w-0 max-w-[calc(100vw-1rem)] overflow-hidden [&>[data-slot=combobox-popup]]:min-w-0 [&>[data-slot=combobox-popup]]:overflow-hidden`,children:[(0,$.jsx)(`div`,{className:`min-w-0 shrink-0 px-3 pt-2.5`,children:(0,$.jsxs)(`div`,{className:`relative -translate-y-px border-b border-border/70 pb-1.5 transition-colors focus-within:border-ring`,children:[(0,$.jsx)(ke,{"aria-hidden":`true`,className:`pointer-events-none absolute top-1.5 left-0 size-4 shrink-0 text-muted-foreground/55`}),(0,$.jsx)(Se,{className:`[&_input]:h-6.5 [&_input]:ps-5 [&_input]:font-sans [&_input]:leading-6.5`,inputClassName:`rounded-none bg-transparent text-sm`,placeholder:`Search refs...`,showTrigger:!1,size:`sm`,unstyled:!0,value:k,onChange:e=>A(e.target.value)})]})}),(0,$.jsxs)(`div`,{className:`grid shrink-0 grid-cols-[1rem_minmax(0,1fr)] items-center gap-2 border-b border-border/70 ps-3 pe-6.5 pt-2 pb-1.5 font-medium text-[10px] text-muted-foreground uppercase tracking-wide`,children:[(0,$.jsx)(`span`,{"aria-hidden":`true`}),(0,$.jsxs)(`div`,{className:`grid min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center`,children:[(0,$.jsx)(`span`,{children:`Branch`}),(0,$.jsx)(`span`,{className:`text-right`,children:`Remote`})]})]}),(0,$.jsx)(_e,{children:`No matching refs.`}),(0,$.jsxs)($e,{className:`max-h-64 min-w-0 overflow-x-hidden`,children:[(0,$.jsx)(Oe,{className:`h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0`,contentClassName:`w-full min-w-0 overflow-hidden`,value:yn,children:(0,$.jsx)(`span`,{className:`block min-w-0 truncate`,children:`Automatic`})}),ot.map(e=>{let t=ct(e),n=e.local!==null&&e.remote!==null,r=e.remote?.name===t;return(0,$.jsx)(Oe,{className:`h-8 w-full min-w-0 grid-cols-[1rem_minmax(0,1fr)] py-0`,contentClassName:`w-full min-w-0 overflow-hidden`,value:t,children:(0,$.jsxs)(`div`,{className:`grid w-full min-w-0 grid-cols-[minmax(0,1fr)_2rem] items-center overflow-hidden`,children:[(0,$.jsx)(`span`,{className:`block min-w-0 truncate pe-2`,children:e.label}),n?(0,$.jsx)(`div`,{className:`flex justify-end`,onClick:e=>e.stopPropagation(),onPointerDown:e=>e.stopPropagation(),children:(0,$.jsx)(Te,{"aria-label":`Use remote version of ${e.label}`,checked:r,className:`[--thumb-size:--spacing(3)]`,onCheckedChange:t=>{let n=t?e.remote?.name:e.local?.name;n&&Tt(n)}})}):e.remote?(0,$.jsx)(`span`,{className:`flex justify-end text-muted-foreground`,title:`Remote only`,children:(0,$.jsx)(ee,{"aria-hidden":`true`,className:`size-3`})}):null]})},e.id)})]})]})]})]})]}),(0,$.jsxs)(`div`,{className:`flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]`,children:[Z.length>0&&(0,$.jsx)(Ve,{additions:yt.additions,deletions:yt.deletions,className:`mr-1 text-[11px]`,layout:`inline`}),Z.length>0&&(0,$.jsxs)(j,{children:[(0,$.jsx)(E,{render:(0,$.jsx)(h,{type:`button`,size:`icon-xs`,variant:`outline`,"aria-label":vt?`Expand all files`:`Collapse all files`,onClick:St}),children:vt?(0,$.jsx)(ve,{className:`size-3`}):(0,$.jsx)(Ce,{className:`size-3`})}),(0,$.jsx)(O,{side:`top`,children:vt?`Expand all files`:`Collapse all files`})]}),(0,$.jsxs)(fn,{className:`shrink-0`,variant:`outline`,size:`xs`,value:[p],onValueChange:e=>{let t=e[0];(t===`stacked`||t===`split`)&&g(t)},children:[(0,$.jsx)(pn,{"aria-label":`Stacked diff view`,value:`stacked`,children:(0,$.jsx)(rt,{className:`size-3`})}),(0,$.jsx)(pn,{"aria-label":`Split diff view`,value:`split`,children:(0,$.jsx)(tt,{className:`size-3`})})]}),(0,$.jsxs)(j,{children:[(0,$.jsx)(E,{render:(0,$.jsx)(pn,{"aria-label":v?`Disable diff line wrapping`:`Enable diff line wrapping`,variant:`outline`,size:`xs`,pressed:v,onPressedChange:e=>{y(!!e)}}),children:(0,$.jsx)(Xe,{className:`size-3`})}),(0,$.jsx)(O,{side:`top`,children:v?`Disable line wrapping`:`Enable line wrapping`})]}),(0,$.jsxs)(j,{children:[(0,$.jsx)(E,{render:(0,$.jsx)(pn,{"aria-label":C?`Show whitespace changes`:`Hide whitespace changes`,variant:`outline`,size:`xs`,pressed:C,onPressedChange:e=>{w(!!e)}}),children:(0,$.jsx)(nt,{className:`size-3`})}),(0,$.jsx)(O,{side:`top`,children:C?`Show whitespace changes`:`Hide whitespace changes`})]})]})]}),children:F?we?B!==null&&z.length===0?(0,$.jsx)(`div`,{className:`flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70`,children:`No completed turns yet.`}):(0,$.jsx)($.Fragment,{children:(0,$.jsxs)(`div`,{className:`diff-panel-viewport flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:[ft&&(0,$.jsx)(`p`,{className:`shrink-0 border-b border-border/70 bg-muted/40 px-3 py-1.5 text-[11px] text-muted-foreground`,children:`This diff was truncated because it exceeded the preview limit. The changes shown are incomplete.`}),mt&&!X&&(0,$.jsx)(`div`,{className:`px-3`,children:(0,$.jsx)(`p`,{className:`mb-2 text-[11px] text-red-500/80`,children:mt})}),X?X.kind===`files`?(0,$.jsx)(`div`,{className:`min-h-0 flex-1`,onClickCapture:e=>{let t=(e.nativeEvent.composedPath?.()??[]).find(e=>e instanceof HTMLElement&&e.hasAttribute(`data-title`))?.textContent?.trim();t&&bt(t)},children:(0,$.jsx)(tn,{viewerRef:M,className:`diff-render-surface h-full min-h-0 overflow-auto`,files:Z,sectionId:We,sectionTitle:Ke,composerDraftTarget:t,renderHeaderPrefix:(e,t,n)=>{let r=Fe(e);return(0,$.jsxs)(j,{children:[(0,$.jsx)(E,{render:(0,$.jsx)(`button`,{type:`button`,className:_(`inline-flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-sm border-0 bg-transparent p-0 transition-colors hover:bg-foreground/10 focus-visible:outline-hidden`,qe(e)),"aria-label":n?`Expand ${r}`:`Collapse ${r}`,"aria-expanded":!n,onClick:e=>{e.stopPropagation(),xt(t)}}),children:n?(0,$.jsx)(l,{className:`size-4`}):(0,$.jsx)(S,{className:`size-4`})}),(0,$.jsx)(O,{side:`top`,children:n?`Expand diff`:`Collapse diff`})]})},options:{diffStyle:p===`split`?`split`:`unified`,lineDiffType:`none`,overflow:v?`wrap`:`scroll`,theme:Me(a),themeType:a,unsafeCSS:xn,stickyHeaders:!0,itemMetrics:{diffHeaderHeight:33},layout:{paddingTop:0,paddingBottom:8,gap:8}}},G??We)}):(0,$.jsx)(`div`,{className:`min-h-0 flex-1 overflow-auto p-2`,children:(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsx)(`p`,{className:`text-[11px] text-muted-foreground/75`,children:X.reason}),(0,$.jsx)(`pre`,{className:_(`max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90`,v?`overflow-auto whitespace-pre-wrap wrap-break-word`:`overflow-auto`),children:X.text})]})}):pt?(0,$.jsx)(Zt,{label:U?`Loading checkpoint diff...`:V===`unstaged`?`Loading working tree diff...`:`Loading branch diff...`}):(0,$.jsx)(`div`,{className:`flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70`,children:(0,$.jsx)(`p`,{children:ht?`No net changes in this selection.`:`No patch available for this selection.`})})]})}):(0,$.jsx)(`div`,{className:`flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70`,children:`Turn diffs are unavailable because this project is not a git repository.`}):(0,$.jsx)(`div`,{className:`flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70`,children:`Select a thread to inspect turn diffs.`})})}export{Ie as DiffWorkerPoolProvider,Sn as default};
98
- //# sourceMappingURL=DiffPanel-ChInQIhf.js.map
98
+ //# sourceMappingURL=DiffPanel-Byg3lT0_.js.map