@vantran-se/openchamber-web 1.22.1 → 1.22.2

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.
Files changed (163) hide show
  1. package/README.md +2 -3
  2. package/bin/cli.js +4 -1
  3. package/bin/cli.test.js +92 -0
  4. package/bin/lib/cli-startup.js +49 -0
  5. package/bin/lib/commands-startup.js +41 -6
  6. package/dist/assets/{CodeMirrorCommentWidgets-C53Q7pbX.js → CodeMirrorCommentWidgets-CV1HNV5l.js} +1 -1
  7. package/dist/assets/{DiffView-Dh1ey2x9.js → DiffView-DkkSa30n.js} +3 -3
  8. package/dist/assets/DirtyBranchSwitchDialog-DW4WaXPc.js +1 -0
  9. package/dist/assets/FilesView-DDu8zDy5.js +17 -0
  10. package/dist/assets/GitView-1Ixo8z-M.js +6 -0
  11. package/dist/assets/{JsonTreeView-Bl0lp9Rs.js → JsonTreeView-DvCLL7dT.js} +1 -1
  12. package/dist/assets/LinearIssuesView-Bs1rZrF2.js +1 -0
  13. package/dist/assets/{MarkdownImageGallery-bA0PS-tn.js → MarkdownImageGallery-DyJUc6h9.js} +1 -1
  14. package/dist/assets/MarkdownRendererImpl-Bdm8vMkS.js +12 -0
  15. package/dist/assets/{OnboardingScreen-D3kYJIb6.js → OnboardingScreen-Dg66B6oB.js} +1 -1
  16. package/dist/assets/{PatchDiff-D6NXAfJk.js → PatchDiff-CAduNjfZ.js} +1 -1
  17. package/dist/assets/{PierreDiffViewer-Ct2A13NO.js → PierreDiffViewer-CTIb1GYD.js} +2 -2
  18. package/dist/assets/PlanView-trDaszfq.js +5 -0
  19. package/dist/assets/SettingsView-DStMfBmy.js +28 -0
  20. package/dist/assets/{SettingsWindow-BiWDBRvb.js → SettingsWindow-DQQFnrSZ.js} +1 -1
  21. package/dist/assets/{ToolOutputDialog-BQexMQIm.js → ToolOutputDialog-SjY2XZlA.js} +6 -6
  22. package/dist/assets/ToolPartDiffPreview-DJdzUQPE.js +8 -0
  23. package/dist/assets/{VirtualizedFileDiff-Dpz2ra8h.js → VirtualizedFileDiff-Iehm4iMH.js} +1 -1
  24. package/dist/assets/{WalkthroughView-AX-u2pFg.js → WalkthroughView-BALp2d9O.js} +2 -2
  25. package/dist/assets/{computeVirtualFileMetrics-DtyozJdt.js → computeVirtualFileMetrics-BKZA43vN.js} +2 -2
  26. package/dist/assets/{contextPanelEmbeddedChat-C9EcRSDF.js → contextPanelEmbeddedChat-D2PM_pEv.js} +1 -1
  27. package/dist/assets/{de-DqVn5vme.js → de-DlSNLAcy.js} +6 -5
  28. package/dist/assets/{es-hj43Z53i.js → es-D1GbowZ3.js} +6 -5
  29. package/dist/assets/{fr-BmkZt2mF.js → fr-BPOLXIAY.js} +6 -5
  30. package/dist/assets/{index-DmhujXbT.js → index-Ce0LR32V.js} +1 -1
  31. package/dist/assets/index-D42fPvt4.css +1 -0
  32. package/dist/assets/index-DlFbCkEy.js +39 -0
  33. package/dist/assets/{isDiffPlainText-XyulMHxx.js → isDiffPlainText-DaB2u_Kv.js} +1 -1
  34. package/dist/assets/{isFilePlainText-B19Ddps1.js → isFilePlainText-yJZa2IAC.js} +1 -1
  35. package/dist/assets/{ja-DioMIEGF.js → ja-Dm2-m9io.js} +7 -6
  36. package/dist/assets/{ko-BqPgaQJb.js → ko-CIXlzQ5-.js} +7 -6
  37. package/dist/assets/main-B7qTsd_w.js +930 -0
  38. package/dist/assets/{main-B2a_JfKZ.js → main-CyQrD9dG.js} +2 -2
  39. package/dist/assets/{markdownCore-CWRCqSH2.js → markdownCore-CeEwGgEK.js} +2 -2
  40. package/dist/assets/{miniChat-B3CSU_Ps.js → miniChat-7cPEx4sV.js} +2 -2
  41. package/dist/assets/{mobile-QNcFIVCW.js → mobile-QtzkPTM8.js} +2 -2
  42. package/dist/assets/{patchFileDiff-BpMQZnYu.js → patchFileDiff-No55fDiD.js} +1 -1
  43. package/dist/assets/pl-B2zmkOpw.js +16 -0
  44. package/dist/assets/{pt-BR-BqH8fuCH.js → pt-BR-C-JE5H6y.js} +6 -5
  45. package/dist/assets/{renderElectronMiniChatApp-D77bmLqo.js → renderElectronMiniChatApp-ePTkBJNS.js} +2 -2
  46. package/dist/assets/renderMobileApp-D9RjB9DX.js +25 -0
  47. package/dist/assets/runtimeEndpointReset-DfJIWwwo.js +17 -0
  48. package/dist/assets/{scheduledTasksApi-BSRCtP6T.js → scheduledTasksApi-DuhdyYEa.js} +1 -1
  49. package/dist/assets/{shikiHighlight-DE-OwqGw.js → shikiHighlight-EHEg58-n.js} +1 -1
  50. package/dist/assets/tr-MJmRIzEY.js +7 -0
  51. package/dist/assets/{uk-BkkfxbOs.js → uk-BmD7eM8k.js} +6 -5
  52. package/dist/assets/{useAppFontEffects-COAeIX-D.js → useAppFontEffects-CuJPKtI1.js} +151 -180
  53. package/dist/assets/useInlineCommentController-DD7_7OP_.js +2 -0
  54. package/dist/assets/{useRootScrollLock-C0N9mCwz.js → useRootScrollLock-DRGAe8PN.js} +1 -1
  55. package/dist/assets/{vendor-codemirror-language-data-BG3v1Ghq.js → vendor-codemirror-language-data-9ZzoH0o0.js} +2 -2
  56. package/dist/assets/vendor-zod-CK21ihK-.js +39 -0
  57. package/dist/assets/{web-components-BNMwa0qm.js → web-components-PttKBrhi.js} +1 -1
  58. package/dist/assets/{zh-CN-C6FMdVgv.js → zh-CN-JJHl4ehT.js} +6 -5
  59. package/dist/assets/{zh-TW-CdcMjDxv.js → zh-TW-DPc4DEEW.js} +6 -5
  60. package/dist/index.html +5 -5
  61. package/dist/mini-chat.html +4 -4
  62. package/dist/mobile.html +4 -4
  63. package/package.json +8 -4
  64. package/server/index.js +38 -5
  65. package/server/lib/agent-tool/runtime.js +2 -19
  66. package/server/lib/changelog/update-notes.js +82 -0
  67. package/server/lib/changelog/update-notes.test.js +59 -0
  68. package/server/lib/dev-tunnel/DOCUMENTATION.md +13 -4
  69. package/server/lib/dev-tunnel/runtime.js +4 -4
  70. package/server/lib/dev-tunnel/tunnel.test.js +20 -0
  71. package/server/lib/fs/DOCUMENTATION.md +2 -0
  72. package/server/lib/fs/routes.js +32 -21
  73. package/server/lib/fs/routes.test.js +77 -0
  74. package/server/lib/git/DOCUMENTATION.md +3 -1
  75. package/server/lib/git/routes.js +16 -0
  76. package/server/lib/git/service.js +107 -17
  77. package/server/lib/git/service.test.js +171 -0
  78. package/server/lib/mcp-reconnect/DOCUMENTATION.md +55 -0
  79. package/server/lib/mcp-reconnect/runtime.js +122 -0
  80. package/server/lib/mcp-reconnect/runtime.test.js +140 -0
  81. package/server/lib/message-queue/DOCUMENTATION.md +158 -0
  82. package/server/lib/message-queue/runtime.js +870 -0
  83. package/server/lib/message-queue/runtime.test.js +482 -0
  84. package/server/lib/openchamber-sessions/routes.js +102 -0
  85. package/server/lib/openchamber-sessions/routes.test.js +88 -0
  86. package/server/lib/opencode/DOCUMENTATION.md +13 -5
  87. package/server/lib/opencode/config-paths.test.js +116 -0
  88. package/server/lib/opencode/core-routes.js +1 -0
  89. package/server/lib/opencode/feature-routes-runtime.js +5 -0
  90. package/server/lib/opencode/input-history-scope.js +14 -0
  91. package/server/lib/opencode/managed-plugin-config.js +35 -0
  92. package/server/lib/opencode/openchamber-routes.test.js +2 -2
  93. package/server/lib/opencode/plugins.js +2 -2
  94. package/server/lib/opencode/providers.js +44 -2
  95. package/server/lib/opencode/providers.test.js +131 -4
  96. package/server/lib/opencode/routes.js +4 -4
  97. package/server/lib/opencode/server-startup-runtime.js +1 -1
  98. package/server/lib/opencode/settings-helpers.js +28 -0
  99. package/server/lib/opencode/settings-helpers.test.js +177 -0
  100. package/server/lib/opencode/settings-runtime.js +2 -2
  101. package/server/lib/opencode/settings-runtime.test.js +29 -0
  102. package/server/lib/opencode/shared.js +4 -1
  103. package/server/lib/opencode/shutdown-runtime.js +2 -0
  104. package/server/lib/opencode/skill-routes.js +2 -1
  105. package/server/lib/opencode/snippets.js +1 -2
  106. package/server/lib/package-manager.js +4 -29
  107. package/server/lib/package-manager.test.js +2 -2
  108. package/server/lib/quota/DOCUMENTATION.md +2 -1
  109. package/server/lib/quota/credentials/providers.js +4 -0
  110. package/server/lib/quota/credentials/store.js +1 -1
  111. package/server/lib/quota/credentials/store.test.js +4 -4
  112. package/server/lib/quota/providers/exe-dev.js +75 -0
  113. package/server/lib/quota/providers/exe-dev.test.js +47 -0
  114. package/server/lib/quota/providers/index.js +7 -0
  115. package/server/lib/quota/providers/opencode-go.js +1 -0
  116. package/server/lib/quota/providers/opencode-go.test.js +5 -1
  117. package/server/lib/quota/routes.js +2 -0
  118. package/server/lib/quota/utils/auth.js +1 -1
  119. package/server/lib/relay/DOCUMENTATION.md +1 -1
  120. package/server/lib/relay/host-client.test.js +9 -1
  121. package/server/lib/relay/tunnel-host.js +3 -1
  122. package/server/lib/relay/tunnel-host.test.js +9 -1
  123. package/server/lib/security/request-security.js +21 -6
  124. package/server/lib/security/request-security.test.js +42 -8
  125. package/server/lib/session-assist/runtime.js +1 -0
  126. package/server/lib/session-goal/DOCUMENTATION.md +20 -7
  127. package/server/lib/session-goal/create.js +3 -1
  128. package/server/lib/session-goal/runtime.js +77 -11
  129. package/server/lib/session-goal/runtime.test.js +426 -0
  130. package/server/lib/skills-catalog/DOCUMENTATION.md +1 -1
  131. package/server/lib/skills-catalog/install.js +3 -2
  132. package/server/lib/small-model/DOCUMENTATION.md +4 -0
  133. package/server/lib/small-model/call.js +8 -2
  134. package/server/lib/small-model/call.test.js +23 -0
  135. package/server/lib/small-model/index.js +2 -1
  136. package/server/lib/small-model/routes.js +2 -1
  137. package/server/lib/system-prompt/runtime.js +2 -21
  138. package/server/lib/terminal/DOCUMENTATION.md +11 -7
  139. package/server/lib/terminal/runtime.js +180 -26
  140. package/server/lib/terminal/runtime.test.js +553 -26
  141. package/server/lib/terminal/shells.js +17 -0
  142. package/server/lib/terminal/shells.test.js +32 -1
  143. package/server/lib/ui-auth/ui-auth.js +4 -1
  144. package/server/lib/ui-auth/ui-auth.test.js +16 -0
  145. package/server/lib/walkthrough/index.js +1 -0
  146. package/server/lib/walkthrough/routes.test.js +26 -5
  147. package/dist/assets/CommitSection-X-f2RgYr.js +0 -1
  148. package/dist/assets/FilesView-3ZYP72ki.js +0 -17
  149. package/dist/assets/GitView-CMuN7z2Z.js +0 -6
  150. package/dist/assets/LinearIssuesView-CQiUDU8b.js +0 -1
  151. package/dist/assets/MarkdownRendererImpl-BGQi2PLq.js +0 -12
  152. package/dist/assets/PlanView-6AUjzNQn.js +0 -5
  153. package/dist/assets/SettingsView-CHI8fFaK.js +0 -28
  154. package/dist/assets/ToolPartDiffPreview-DPAATNn6.js +0 -8
  155. package/dist/assets/index-L_ncV-6H.css +0 -1
  156. package/dist/assets/index-qES19dlJ.js +0 -7
  157. package/dist/assets/main-CYgSu6dx.js +0 -928
  158. package/dist/assets/pl-slULBF4R.js +0 -15
  159. package/dist/assets/renderMobileApp-BQ3Kdm-d.js +0 -25
  160. package/dist/assets/runtimeEndpointReset-CRGn1gVj.js +0 -16
  161. package/dist/assets/tr-CjEbw1Aw.js +0 -6
  162. package/dist/assets/useInlineCommentController-JsBboQwt.js +0 -2
  163. package/dist/assets/vendor-zod-BLfBSgBh.js +0 -39
@@ -0,0 +1,6 @@
1
+ import{R as l,r as ve,j as t,f as Ct}from"./vendor-react-BUCujlKS.js";import{f as nt,y as rt,a1 as Dt,hV as _n,cV as Yt,cf as Qt,t as b,I as T,b6 as Ts,b3 as As,cT as Fr,b5 as Ls,cy as Os,cz as zs,cA as Gs,cB as _s,ct as Xt,cu as Zt,B as W,hW as $n,hX as Hn,bF as mt,bG as ht,bH as gt,bI as ft,bJ as bt,T as gr,a7 as es,a8 as ts,a9 as ss,hY as Wn,h as Se,hZ as Un,h_ as Kn,h$ as Jn,i0 as qn,b2 as Yn,ao as Qn,bQ as Xn,i1 as Zn,i2 as ea,i3 as ta,i4 as sa,i5 as ra,i6 as na,i7 as aa,c0 as Rr,bT as ia,bU as oa,bV as la,bW as ca,bX as da,i8 as ua,b_ as ma,bK as Es,eQ as ha,W as ga,ac as fa,ad as pa,ag as xa,ae as wa,bv as ya,i9 as ba,af as va,ia as ja,ib as Ca,ah as Na,ic as Sa,ai as ka,bO as Va,hO as Ia,id as Pa,l as Fa,b$ as Ra,g as Ba,cD as Da,an as fr,a2 as Ma,ie as Ea,ig as Bs}from"./useAppFontEffects-CuJPKtI1.js";import{a as Ta,b as Aa,d as La}from"./main-B7qTsd_w.js";import{F as Oa,E as za,A as Ga,a2 as _a,c as $a,a7 as Ha}from"./runtimeEndpointReset-DfJIWwwo.js";import{u as pr}from"./vendor-zustand-BAGL70zf.js";import{r as Wa,u as Rt}from"./index-DlFbCkEy.js";import{C as Ua,a as Ka,D as Ja}from"./DirtyBranchSwitchDialog-DW4WaXPc.js";import{P as qa}from"./PierreDiffViewer-CTIb1GYD.js";import"./vendor-scheduler-7OC5HNn7.js";import"./vendor-simplewebauthn-browser-VDA66rT_.js";import"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-base-ui-BeMD8X_w.js";import"./vendor-floating-ui-utils-D6FqdtJt.js";import"./vendor-floating-ui-react-dom-DxYCWdHj.js";import"./vendor-floating-ui-dom-BTvzWks8.js";import"./vendor-floating-ui-core-PuGzNPnN.js";import"./vendor-use-sync-external-store-D6wYuSt-.js";import"./contextPanelEmbeddedChat-D2PM_pEv.js";import"./vendor-class-variance-authority-5VPnzWs2.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-dnd-kit-core-BZknOX2w.js";import"./vendor-dnd-kit-utilities-B_MdXhJC.js";import"./vendor-dnd-kit-accessibility-BHxJPORy.js";import"./vendor-dnd-kit-sortable-CsEagZ81.js";import"./vendor-framer-motion-livSKyyV.js";import"./vendor-motion-dom-D_o3BTI3.js";import"./vendor-motion-utils-BGh8QBgx.js";import"./vendor-tanstack-react-virtual-g05Cx3z9.js";import"./vendor-tanstack-virtual-core-Dubg10g5.js";import"./vendor-sonner-DFyL3AvE.js";import"./vendor-cmdk-DgLInKvT.js";import"./vendor-radix-ui-react-dialog-B94Bt2qq.js";import"./vendor-radix-ui-primitive-Dc_FVRD7.js";import"./vendor-radix-ui-react-compose-refs-DcAh5WdT.js";import"./vendor-radix-ui-react-context-Czxm7Z62.js";import"./vendor-radix-ui-react-id-f5BLKEVw.js";import"./vendor-radix-ui-react-use-layout-effect-D_3IhJdJ.js";import"./vendor-radix-ui-react-use-controllable-state-BFT5YmkA.js";import"./vendor-radix-ui-react-dismissable-layer-D7kXcwgJ.js";import"./vendor-radix-ui-react-primitive-DhVoX9SD.js";import"./vendor-radix-ui-react-slot-BQgQOasS.js";import"./vendor-radix-ui-react-use-callback-ref-BZPnuXAC.js";import"./vendor-radix-ui-react-use-escape-keydown-oph88g-F.js";import"./vendor-radix-ui-react-focus-scope-CiaxW4dD.js";import"./vendor-radix-ui-react-portal-BMJYHWck.js";import"./vendor-radix-ui-react-presence-CNxf-uq4.js";import"./vendor-radix-ui-react-focus-guards-B6qJXYua.js";import"./vendor-react-remove-scroll-DO7dCTnK.js";import"./vendor-tslib-De9GV7Vy.js";import"./vendor-react-remove-scroll-bar-BcFYyj3E.js";import"./vendor-react-style-singleton-q6EMHnwf.js";import"./vendor-get-nonce-C-Z93AgS.js";import"./vendor-use-sidecar-zDC0RhA3.js";import"./vendor-use-callback-ref-D3RC8gqK.js";import"./vendor-aria-hidden-DvXkyWUv.js";import"./vendor-codemirror-language-BgPj_McA.js";import"./vendor-lezer-common-B3-cUCR_.js";import"./vendor-codemirror-state-C9awkmn-.js";import"./vendor-marijn-find-cluster-break-DXwl3gUT.js";import"./vendor-codemirror-view-CiLROUVV.js";import"./vendor-style-mod-NZ5MEPvj.js";import"./vendor-w3c-keyname-Vcq4gwWv.js";import"./vendor-crelt-C8TCjufn.js";import"./vendor-lezer-highlight-CDMHUZ74.js";import"./vendor-codemirror-lang-javascript-Cc2ZYbgX.js";import"./vendor-lezer-javascript-D7Tj24ot.js";import"./vendor-lezer-lr-bhwg1HMg.js";import"./vendor-codemirror-autocomplete-DzPz9Wgq.js";import"./vendor-codemirror-lang-json-CMBS2tG9.js";import"./vendor-lezer-json-Iaex0UN-.js";import"./vendor-codemirror-lang-css-O0cZX78y.js";import"./vendor-lezer-css-C5xB6jxd.js";import"./vendor-codemirror-lang-html-CfgK872x.js";import"./vendor-lezer-html-C0I1p52t.js";import"./vendor-codemirror-lang-markdown-BPGOH9ye.js";import"./vendor-lezer-markdown-C6g-d6P3.js";import"./vendor-codemirror-language-data-9ZzoH0o0.js";import"./vendor-codemirror-lang-python-HahnQaAS.js";import"./vendor-lezer-python-CvuFxeZl.js";import"./vendor-codemirror-commands-B7H_j0iU.js";import"./vendor-legendapp-list-gg7YLRW7.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./vendor-zod-CK21ihK-.js";import"./useRootScrollLock-DRGAe8PN.js";import"./scheduledTasksApi-DuhdyYEa.js";import"./vendor-cron-parser-CUcP7OfX.js";import"./vendor-luxon-BZ0puJYg.js";import"./vendor-opencode-sdk-BJ73u-bH.js";import"./web-components-PttKBrhi.js";import"./computeVirtualFileMetrics-BKZA43vN.js";import"./vendor-shiki-Bbf2GEcE.js";import"./vendor-shikijs-core-CGM_jqPK.js";import"./vendor-shikijs-types-CPSbSeK6.js";import"./vendor-shikijs-vscode-textmate-BgLrS_2D.js";import"./vendor-hast-util-to-html-BKBhbTDb.js";import"./vendor-html-void-elements-CkdplsNl.js";import"./vendor-property-information-rJCbAzvX.js";import"./vendor-zwitch-C2o2j-tx.js";import"./vendor-stringify-entities-CsH1VEn9.js";import"./vendor-character-entities-legacy-BpoLgcEt.js";import"./vendor-character-entities-html4-D7taRCQ7.js";import"./vendor-ccount-c2V3InAJ.js";import"./vendor-comma-separated-tokens-D8TqSuIK.js";import"./vendor-space-separated-tokens-DD3iYX1K.js";import"./vendor-hast-util-whitespace-D4Wp6AEg.js";import"./vendor-shikijs-engine-oniguruma-DPWuIF1G.js";import"./themeResolver-BmJyTmjJ.js";import"./vendor-pierre-theming-C6Z4M5_u.js";import"./vendor-shikijs-engine-javascript-Cme4830A.js";import"./vendor-oniguruma-to-es-DLBnFDCE.js";import"./vendor-oniguruma-parser-C0D4_9rT.js";import"./vendor-regex-BBWcyTkg.js";import"./vendor-regex-utilities-2BQyy0xI.js";import"./vendor-regex-recursion-JU4mF-dD.js";import"./vendor-shikijs-transformers-CZWsLLKm.js";import"./VirtualizedFileDiff-Iehm4iMH.js";import"./isDiffPlainText-DaB2u_Kv.js";import"./vendor-diff-C3JhlQdm.js";import"./Virtualizer-D_a8gKmg.js";import"./useInlineCommentController-DD7_7OP_.js";import"./appThemeRegistry-BK0dHKa6.js";import"./registerCustomTheme-BBXUCRnG.js";const Br="gitmojiCache",Ya=1e3*60*60*24*7,Dr="1",Qa="https://raw.githubusercontent.com/carloscuesta/gitmoji/master/packages/gitmojis/src/gitmojis.json",Mr=o=>{if(!o||typeof o!="object")return!1;const e=o;return typeof e.emoji=="string"&&typeof e.code=="string"&&typeof e.description=="string"},Ds=()=>{if(typeof window>"u")return null;try{const o=window.localStorage.getItem(Br);if(!o)return null;const e=JSON.parse(o);return!e||e.version!==Dr||typeof e.fetchedAt!="number"||!Array.isArray(e.gitmojis)?null:{gitmojis:e.gitmojis.filter(Mr),fetchedAt:e.fetchedAt,version:e.version}}catch{return null}},Xa=o=>{if(!(typeof window>"u"))try{const e={gitmojis:o,fetchedAt:Date.now(),version:Dr};window.localStorage.setItem(Br,JSON.stringify(e))}catch{return}},xr=o=>Date.now()-o.fetchedAt<Ya;let Jt=null;const Bt=new Set,wr=async()=>{if(Jt)return Jt;const o=(async()=>{try{const e=await fetch(Qa);if(!e.ok)throw new Error(`Failed to load gitmojis: ${e.statusText}`);const a=await e.json(),m=Array.isArray(a.gitmojis)?a.gitmojis.filter(Mr):[];return Xa(m),Bt.forEach(N=>N(m)),m}catch(e){console.warn("Failed to load gitmoji list:",e);const a=[];return Bt.forEach(m=>m(a)),a}finally{Jt=null}})();return Jt=o,o},Za=o=>{const[e,a]=l.useState(()=>o?Ds()?.gitmojis??[]:[]),[m,N]=l.useState(!1),f=l.useRef(o);f.current=o,l.useEffect(()=>{if(!o){Bt.delete(a),a([]),N(!1);return}const x=Ds();if(x&&(a(x.gitmojis),xr(x)))return;Bt.add(a),N(!0);let g=!1;return wr().finally(()=>{!g&&f.current&&N(!1)}),()=>{g=!0,Bt.delete(a)}},[o]);const p=l.useCallback(async()=>{if(!f.current)return[];if(e.length>0)return e;const x=Ds();return x&&xr(x)?x.gitmojis:wr()},[e]);return{gitmojis:e,isLoading:m,ensureLoaded:p}},Nt=async(o,e)=>{const a=await Wa(`/api/git/integrate/${o}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok){const m=await a.json().catch(()=>null);throw new Error(m?.error||`Git integrate request failed: ${a.statusText}`)}return a.json()};async function Ft(o){return Nt("plan",o)}async function ei(o){return Nt("conflict-details",{tempWorktreePath:o})}async function ti(o){return(await Nt("cherry-pick-status",{tempWorktreePath:o})).inProgress}async function si(o){return Nt("run",{plan:o})}async function ri(o){await Nt("abort",{state:o})}async function ni(o){return Nt("continue",{state:o})}const ai=({repoRoot:o,sourceBranch:e,worktreeMetadata:a,localBranches:m,defaultTargetBranch:N,refreshKey:f,onRefresh:p,showHeader:x=!0})=>{const{t:g}=nt(),w=rt(h=>h.currentSessionId),[M,v]=ve.useState(!1),[V,A]=ve.useState(""),S=ve.useRef(null),z=ve.useMemo(()=>Dt(m,V,h=>[h]),[m,V]),[C,y]=ve.useState(N);ve.useEffect(()=>{y(N)},[N]),ve.useEffect(()=>{if(M){const h=setTimeout(()=>{S.current?.focus()},0);return()=>clearTimeout(h)}},[M]);const D=!!(o&&e&&C&&C!=="HEAD"&&e!==C),[k,R]=ve.useState({kind:"idle"}),[P,F]=ve.useState(!1),[r,Y]=ve.useState([]),B=ve.useMemo(()=>w?`openchamber.integrate.conflict:${w}`:null,[w]);ve.useEffect(()=>{if(!B||typeof window>"u")return;const h=window.localStorage.getItem(B);if(!h)return;let d=!1;try{const I=JSON.parse(h);if(!I?.tempWorktreePath||I.repoRoot!==o){window.localStorage.removeItem(B);return}(async()=>{const L=await ti(I.tempWorktreePath).catch(()=>!1);if(d)return;if(!L){window.localStorage.removeItem(B);return}const q=await ei(I.tempWorktreePath).catch(()=>null);d||q&&R({kind:"conflict",state:I,details:q})})()}catch{window.localStorage.removeItem(B)}return()=>{d=!0}},[B,o]),ve.useEffect(()=>{if(!D){R({kind:"idle"});return}let h=!1;return R({kind:"loading"}),(async()=>{try{const d=await Ft({repoRoot:o,sourceBranch:e,targetBranch:C});if(h)return;if(R({kind:"ready",plan:d}),d.commits.length>0){const L=d.commits.slice(-50).reverse(),q=await _n(o,L);h||(Y(q),F(!1))}else h||(Y([]),F(!1))}catch{h||R({kind:"idle"})}})(),()=>{h=!0}},[D,o,e,C,f]);const u=ve.useCallback(h=>{w&&rt.getState().setWorktreeMetadata(w,{...a,createdFromBranch:h})},[w,a]),E=rt(h=>h.openNewSessionDraft),se=ve.useCallback(async h=>{const d=await Yt("git.integrate.cherrypick.resolve.visible",{current_commit:h.state.currentCommit,target_branch:h.state.targetBranch}),I=await Yt("git.integrate.cherrypick.resolve.instructions",{repo_root:h.state.repoRoot,temp_worktree_path:h.state.tempWorktreePath,source_branch:h.state.sourceBranch,target_branch:h.state.targetBranch,current_commit:h.state.currentCommit}),L=`Cherry-pick conflict context (JSON)
2
+ ${JSON.stringify({repoRoot:h.state.repoRoot,tempWorktreePath:h.state.tempWorktreePath,sourceBranch:h.state.sourceBranch,targetBranch:h.state.targetBranch,currentCommit:h.state.currentCommit,remainingCommits:h.state.remainingCommits,statusPorcelain:h.details.statusPorcelain,unmergedFiles:h.details.unmergedFiles,currentPatchMeta:h.details.currentPatchMeta,currentPatch:h.details.currentPatch,diff:h.details.diff},null,2)}`;return{visibleText:d,instructionsText:I,payloadText:L}},[]),U=Qt(h=>h.setPendingInputText),G=Qt(h=>h.setPendingSyntheticParts),$=ve.useCallback(async(h,d)=>{const I=await se(h);if(d){E({directoryOverride:h.state.tempWorktreePath,initialPrompt:I.visibleText,syntheticParts:[{text:I.instructionsText,synthetic:!0},{text:I.payloadText,synthetic:!0}]});return}if(!w){b.error(g("gitView.integrate.noActiveSession"),{description:g("gitView.integrate.noActiveSessionDescription")});return}U(I.visibleText,"replace"),G([{text:I.instructionsText,synthetic:!0},{text:I.payloadText,synthetic:!0}])},[w,se,E,U,G,g]),X=ve.useCallback(async()=>{if(k.kind==="ready"){if(k.plan.commits.length===0){b.message(g("gitView.integrate.noCommitsToMoveToast"));return}R({kind:"running",plan:k.plan});try{const h=await si(k.plan);if(h.kind==="success"){b.success(g("gitView.integrate.commitsMovedToast"),{description:h.moved===1?g("gitView.integrate.commitsMovedDescriptionSingle",{count:h.moved,branch:k.plan.targetBranch}):g("gitView.integrate.commitsMovedDescriptionPlural",{count:h.moved,branch:k.plan.targetBranch})});const d=await Ft(k.plan);R({kind:"ready",plan:d}),p?.();return}h.kind==="conflict"&&(b.error(g("gitView.integrate.cherryPickConflictToast"),{description:g("gitView.integrate.cherryPickConflictDescription")}),R({kind:"conflict",state:h.state,details:h.details}),B&&typeof window<"u"&&window.localStorage.setItem(B,JSON.stringify(h.state)))}catch(h){const d=h instanceof Error?h.message:String(h);b.error(g("gitView.integrate.failedToMoveToast"),{description:d});const I=await Ft({repoRoot:o,sourceBranch:e,targetBranch:C}).catch(()=>null);R(I?{kind:"ready",plan:I}:{kind:"idle"})}}},[k,p,o,e,C,B,g]),H=ve.useCallback(async()=>{if(k.kind==="conflict")try{await ri(k.state),b.message(g("gitView.integrate.cherryPickAbortedToast")),B&&typeof window<"u"&&window.localStorage.removeItem(B)}finally{const h=await Ft({repoRoot:o,sourceBranch:e,targetBranch:C}).catch(()=>null);R(h?{kind:"ready",plan:h}:{kind:"idle"})}},[k,o,e,C,B,g]),le=ve.useCallback(async()=>{if(k.kind==="conflict")try{const h=await ni(k.state);if(h.kind==="success"){b.success(g("gitView.integrate.cherryPickFinishedToast"));const d=await Ft({repoRoot:o,sourceBranch:e,targetBranch:C}).catch(()=>null);R(d?{kind:"ready",plan:d}:{kind:"idle"}),B&&typeof window<"u"&&window.localStorage.removeItem(B),p?.();return}h.kind==="conflict"&&(R({kind:"conflict",state:h.state,details:h.details}),B&&typeof window<"u"&&window.localStorage.setItem(B,JSON.stringify(h.state)))}catch(h){const d=h instanceof Error?h.message:String(h);b.error(g("gitView.integrate.cherryPickContinueFailedToast"),{description:d})}},[k,o,e,C,p,B,g]);return!o||!e?null:t.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[x?t.jsxs("div",{className:"px-0 py-3 border-b border-border/40 flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx(T,{name:"split-cells-horizontal",className:"size-4 text-muted-foreground"}),t.jsx("h3",{className:"typography-ui-header font-semibold text-foreground truncate",children:g("gitView.integrate.title")}),k.kind==="ready"&&k.plan.commits.length>0?t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:g("gitView.integrate.toMoveCount",{count:k.plan.commits.length})}):null]}),t.jsx("div",{className:"flex items-center gap-2",children:k.kind==="loading"||k.kind==="running"?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}):null})]}):null,t.jsxs("div",{className:"flex flex-col gap-3 py-3",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"typography-ui-label text-foreground",children:g("gitView.integrate.moveCommits")}),t.jsxs("div",{className:"typography-micro text-muted-foreground truncate",children:[e," → ",C]})]}),t.jsx("div",{className:"flex-1"}),t.jsxs(Ts,{open:M,onOpenChange:v,children:[t.jsx(As,{asChild:!0,children:t.jsxs("button",{type:"button",className:Fr({size:"default"}),children:[g("gitView.integrate.target"),t.jsx("span",{className:"max-w-[160px] truncate font-mono text-xs text-muted-foreground",children:C}),t.jsx(T,{name:"arrow-down-s",className:"size-4 opacity-60"})]})}),t.jsx(Ls,{align:"end",className:"w-72 p-0 max-h-[var(--available-height)] flex flex-col overflow-hidden",children:t.jsxs(Os,{className:"h-full min-h-0",shouldFilter:!1,children:[t.jsx(zs,{ref:S,placeholder:g("gitView.branch.searchPlaceholder"),value:V,onValueChange:A,onKeyDown:h=>h.stopPropagation()}),t.jsxs(Gs,{className:"h-full min-h-0",scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(_s,{children:g("gitView.branch.empty")}),t.jsx(Xt,{heading:g("gitView.branch.localBranches"),children:z.map(h=>t.jsx(Zt,{value:h,onSelect:()=>{y(h),u(h),v(!1),A("")},children:h},h))})]})]})})]}),k.kind==="ready"?t.jsx(W,{size:"sm",onClick:()=>{X()},disabled:!D||k.plan.commits.length===0,children:g("gitView.integrate.move")}):k.kind==="loading"?t.jsx(W,{size:"sm",variant:"outline",disabled:!0,children:g("gitView.integrate.checking")}):k.kind==="running"?t.jsx(W,{size:"sm",variant:"outline",disabled:!0,children:g("gitView.integrate.moving")}):null]}),k.kind==="ready"&&k.plan.commits.length===0&&t.jsx("div",{className:"typography-meta text-muted-foreground",children:g("gitView.integrate.noCommitsToMove")}),k.kind==="ready"&&k.plan.commits.length>0&&t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsxs("div",{className:"typography-meta text-foreground",children:[g("gitView.integrate.commitsToMove"),t.jsxs("span",{className:"text-muted-foreground",children:[" (",k.plan.commits.length,")"]})]}),r.length>0&&k.plan.commits.length>5&&t.jsx("button",{type:"button",onClick:()=>F(h=>!h),className:"typography-micro text-muted-foreground hover:text-foreground",children:g(P?"gitView.integrate.showLess":"gitView.integrate.showAll")})]}),t.jsxs("div",{className:"space-y-1",children:[(P?r:r.slice(0,5)).map(h=>t.jsxs("div",{className:"flex items-baseline gap-2 min-w-0",children:[t.jsx("span",{className:"font-mono text-xs text-muted-foreground flex-shrink-0",children:h.short}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:h.subject||h.sha})]},h.sha)),r.length===0&&t.jsx("div",{className:"typography-meta text-muted-foreground",children:g("gitView.integrate.previewUnavailable")}),k.plan.commits.length>r.length&&t.jsx("div",{className:"typography-micro text-muted-foreground/70",children:g("gitView.integrate.showingFirstCommits",{count:r.length})})]})]}),k.kind==="conflict"&&t.jsxs("div",{className:"rounded-md border border-border/60 bg-background/60 p-3 space-y-2",children:[t.jsx("div",{className:"typography-meta text-foreground",children:g("gitView.integrate.conflictsInFiles",{count:k.details.unmergedFiles.length})}),t.jsxs("div",{className:"typography-micro text-muted-foreground/80",children:[g("gitView.integrate.currentCommit"),": ",t.jsx("span",{className:"font-mono",children:k.state.currentCommit.slice(0,7)})]}),t.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[k.details.unmergedFiles.slice(0,6).map(h=>t.jsx("span",{className:"font-mono text-xs px-2 py-0.5 rounded bg-muted/40 text-muted-foreground",children:h},h)),k.details.unmergedFiles.length>6&&t.jsx("span",{className:"text-xs text-muted-foreground",children:g("gitView.integrate.moreFiles",{count:k.details.unmergedFiles.length-6})})]}),t.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[t.jsx(W,{size:"sm",variant:"ghost",className:"typography-meta",onClick:()=>{H()},children:g("gitView.operation.abort")}),t.jsxs(W,{size:"sm",variant:"secondary",className:"typography-meta gap-1",disabled:!w,onClick:()=>{$({state:k.state,details:k.details},!1)},children:[t.jsx(T,{name:"sparkling",className:"size-3.5"}),g("gitView.integrate.currentSession")]}),t.jsxs(W,{size:"sm",variant:"secondary",className:"typography-meta gap-1",onClick:()=>{$({state:k.state,details:k.details},!0)},children:[t.jsx(T,{name:"sparkling",className:"size-3.5"}),g("gitView.integrate.newSession")]}),t.jsx(W,{size:"sm",className:"typography-meta",onClick:()=>{le()},children:g("gitView.operation.continue")})]})]})]})]})},ii=({open:o,onOpenChange:e,directory:a,hasUncommittedChanges:m,hasStagedChanges:N=!1,uncommittedFileCount:f,onChanged:p})=>{const{t:x}=nt(),[g,w]=l.useState([]),[M,v]=l.useState(!1),[V,A]=l.useState(""),[S,z]=l.useState(""),[C,y]=l.useState(null),[D,k]=l.useState({}),R=l.useCallback(async()=>{if(a){v(!0);try{const u=await $n(a);w(u.stashes),k({})}catch(u){b.error(u instanceof Error?u.message:x("gitView.stashes.toast.loadFailed"))}finally{v(!1)}}},[a,x]);l.useEffect(()=>{o&&R()},[R,o]),l.useEffect(()=>{if(!o||!a||g.length===0)return;let u=!1;const E=g.map(se=>se.ref);return Hn(a,E).then(se=>{u||k(se.counts)}).catch(()=>{}),()=>{u=!0}},[a,o,g]);const P=l.useMemo(()=>Dt(g,V,u=>[u.message,u.ref,u.relativeTime]),[V,g]),F=l.useCallback(async u=>{await R(),await p?.(u)},[R,p]),r=async()=>{if(!(!a||C)){y("create");try{const u=await Wn(a,{message:S.trim()||void 0});u.created?(b.success(x("gitView.stashes.toast.created")),z("")):b.info(x("gitView.stashes.toast.noChanges")),await F({affectsIndex:!!(u.created&&N)})}catch(u){b.error(u instanceof Error?u.message:x("gitView.stashes.toast.createFailed"))}finally{y(null)}}},Y=async(u,E)=>{if(!(!a||C)&&!(E==="drop"&&!window.confirm(x("gitView.stashes.confirm.drop",{ref:u.ref})))){y(`${E}:${u.ref}`);try{E==="apply"&&await Un(a,{ref:u.ref}),E==="pop"&&await Kn(a,{ref:u.ref}),E==="drop"&&await Jn(a,{ref:u.ref});const se=E==="apply"?"gitView.stashes.toast.applySuccess":E==="pop"?"gitView.stashes.toast.popSuccess":"gitView.stashes.toast.dropSuccess";b.success(x(se)),await F({affectsIndex:E!=="drop"})}catch(se){const U=E==="apply"?"gitView.stashes.toast.applyFailed":E==="pop"?"gitView.stashes.toast.popFailed":"gitView.stashes.toast.dropFailed";b.error(se instanceof Error?se.message:x(U)),await F({affectsIndex:E!=="drop"})}finally{y(null)}}},B=C!==null;return t.jsx(mt,{open:o,onOpenChange:e,children:t.jsxs(ht,{className:"max-w-2xl max-h-[70vh] flex flex-col",children:[t.jsxs(gt,{children:[t.jsxs(ft,{className:"flex items-center gap-2",children:[t.jsx(T,{name:"archive-stack",className:"h-5 w-5"}),x("gitView.stashes.title")]}),t.jsx(bt,{children:x("gitView.stashes.description")})]}),t.jsxs("div",{className:"mt-2 rounded-lg border border-border/60 bg-[var(--surface-elevated)] p-3",children:[t.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row",children:[t.jsx(gr,{value:S,onChange:u=>z(u.target.value),placeholder:x("gitView.stashes.messagePlaceholder"),disabled:B||!m,className:"flex-1"}),t.jsxs(W,{onClick:r,disabled:!m||B||!a,children:[C==="create"?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"inbox-archive",className:"size-4"}),x("gitView.stashes.actions.stashCurrentWithCount",{count:f})]})]}),t.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:x("gitView.stashes.includeUntrackedHint")})]}),t.jsxs("div",{className:"relative mt-2",children:[t.jsx(T,{name:"search",className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx(gr,{value:V,onChange:u=>A(u.target.value),placeholder:x("gitView.stashes.searchPlaceholder"),className:"pl-9"})]}),t.jsx("div",{className:"flex-1 overflow-y-auto",children:M?t.jsx("div",{className:"flex items-center justify-center py-10 text-muted-foreground",children:t.jsx(T,{name:"loader-4",className:"size-5 animate-spin"})}):P.length===0?t.jsx("div",{className:"py-8 text-center text-muted-foreground",children:x(V?"gitView.stashes.empty.search":"gitView.stashes.empty.list")}):P.map((u,E)=>t.jsxs("div",{className:"group flex items-center gap-2 rounded py-1.5 transition-colors hover:bg-interactive-hover/30",children:[t.jsxs("div",{className:"min-w-0 flex-1 pl-2",children:[t.jsx("p",{className:"typography-small truncate text-foreground",children:u.message||x("gitView.stashes.untitled")}),t.jsxs("p",{className:"typography-meta truncate text-muted-foreground",children:[t.jsxs(es,{children:[t.jsx(ts,{asChild:!0,children:t.jsx("span",{children:E===0&&!V.trim()?x("gitView.stashes.latestLabel"):x("gitView.stashes.itemNumber",{number:E+1})})}),t.jsx(ss,{sideOffset:6,children:u.ref})]})," · ",u.relativeTime," · ",typeof D[u.ref]=="number"?x("gitView.stashes.fileCount",{count:D[u.ref]}):x("gitView.stashes.fileCountLoading")]})]}),t.jsxs("div",{className:"mr-2 flex shrink-0 items-center gap-1 opacity-100 sm:opacity-0 sm:group-hover:opacity-100",children:[t.jsx(Ms,{label:x("gitView.stashes.actions.apply"),loading:C===`apply:${u.ref}`,onClick:()=>Y(u,"apply"),disabled:B,children:t.jsx(T,{name:"inbox-unarchive",className:"size-4"})}),t.jsx(Ms,{label:x("gitView.stashes.actions.pop"),loading:C===`pop:${u.ref}`,onClick:()=>Y(u,"pop"),disabled:B,children:t.jsx(T,{name:"inbox-unarchive-fill",className:"size-4"})}),t.jsx(Ms,{label:x("gitView.stashes.actions.drop"),loading:C===`drop:${u.ref}`,onClick:()=>Y(u,"drop"),disabled:B,destructive:!0,children:t.jsx(T,{name:"delete-bin",className:"size-4"})})]})]},u.ref))})]})})},Ms=o=>{const e=Ct.c(17),{label:a,loading:m,disabled:N,destructive:f,onClick:p,children:x}=o,g=m||void 0,w=f?"text-[var(--status-error)] hover:text-[var(--status-error)]":"text-muted-foreground hover:text-foreground";let M;e[0]!==w?(M=Se("flex h-6 w-6 items-center justify-center transition-colors disabled:opacity-50",w),e[0]=w,e[1]=M):M=e[1];let v;e[2]!==x||e[3]!==m?(v=m?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):x,e[2]=x,e[3]=m,e[4]=v):v=e[4];let V;e[5]!==N||e[6]!==a||e[7]!==p||e[8]!==g||e[9]!==M||e[10]!==v?(V=t.jsx(ts,{asChild:!0,children:t.jsx("button",{type:"button","aria-label":a,"aria-busy":g,className:M,onClick:p,disabled:N,children:v})}),e[5]=N,e[6]=a,e[7]=p,e[8]=g,e[9]=M,e[10]=v,e[11]=V):V=e[11];let A;e[12]!==a?(A=t.jsx(ss,{sideOffset:6,children:a}),e[12]=a,e[13]=A):A=e[13];let S;return e[14]!==V||e[15]!==A?(S=t.jsxs(es,{children:[V,A]}),e[14]=V,e[15]=A,e[16]=S):S=e[16],S},oi=o=>{const e=Ct.c(16),{onOpenStashes:a}=o,{t:m}=nt();let N;e[0]===Symbol.for("react.memo_cache_sentinel")?(N=t.jsx(T,{name:"git-commit",className:"size-10 text-muted-foreground/70 mb-4"}),e[0]=N):N=e[0];let f;e[1]!==m?(f=m("gitView.empty.cleanTitle"),e[1]=m,e[2]=f):f=e[2];let p;e[3]!==f?(p=t.jsx("p",{className:"typography-ui-label font-semibold text-foreground mb-1",children:f}),e[3]=f,e[4]=p):p=e[4];let x;e[5]!==m?(x=m("gitView.empty.cleanDescription"),e[5]=m,e[6]=x):x=e[6];let g;e[7]!==x?(g=t.jsx("p",{className:"typography-meta text-muted-foreground mb-4",children:x}),e[7]=x,e[8]=g):g=e[8];let w;e[9]!==a||e[10]!==m?(w=a?t.jsxs(W,{type:"button",variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[t.jsx(T,{name:"archive-stack",className:"size-4"}),m("gitView.stashes.title")]}):null,e[9]=a,e[10]=m,e[11]=w):w=e[11];let M;return e[12]!==p||e[13]!==g||e[14]!==w?(M=t.jsxs("div",{className:"flex flex-col items-center justify-center py-10 px-4 text-center",children:[N,p,g,w]}),e[12]=p,e[13]=g,e[14]=w,e[15]=M):M=e[15],M},ut=8,li=o=>{const e=Ct.c(18),{laned:a,totalLanes:m,isExpanded:N}=o,{lane:f,color:p,connectors:x}=a,w=Math.max(m,f+1)*ut+ut/2,M=l.useRef(null),v=l.useRef(null);let V;e[0]!==p||e[1]!==x||e[2]!==f||e[3]!==w?(V=()=>{const y=M.current,D=v.current;if(!y||!D)return;const k=y.offsetHeight;if(k===0)return;const R=window.devicePixelRatio||1;D.width=w*R,D.height=k*R;const P=D.getContext("2d");if(!P)return;P.scale(R,R),P.clearRect(0,0,w,k);const F=k/2,r=f*ut+ut/2,Y=getComputedStyle(D),B=Y.getPropertyValue("--surface-muted-foreground").trim()||Y.color,u=U=>{if(!U.startsWith("var("))return U;const G=U.slice(4,-1).trim();return Y.getPropertyValue(G).trim()||B},E=[...x].sort(di);for(const U of E){const G=U.fromLane*ut+ut/2,$=U.toLane*ut+ut/2,X=U.type==="passing"?.72:U.type==="branch-out"||U.type==="merge-in"?.95:1;P.beginPath(),P.strokeStyle=u(U.color),P.globalAlpha=X,P.lineWidth=1.25,P.lineCap="round";e:switch(U.type){case"passing":case"commit-lane":{P.moveTo(G,0),P.lineTo(G,k);break e}case"top-stub":{P.moveTo(G,0),P.lineTo(G,F);break e}case"bottom-stub":{P.moveTo(G,F),P.lineTo(G,k);break e}case"branch-out":{const H=(F+k)/2;P.moveTo(r,F),P.bezierCurveTo(r,H,$,H,$,k);break e}case"merge-in":{const H=F/2;P.moveTo(G,0),P.bezierCurveTo(G,H,r,H,r,F);break e}default:continue}P.stroke(),P.globalAlpha=1}const se=Y.getPropertyValue("--background").trim()||Y.getPropertyValue("--surface-background").trim();P.beginPath(),P.arc(r,F,4,0,Math.PI*2),P.fillStyle=u(p),P.fill(),P.beginPath(),P.arc(r,F,5,0,Math.PI*2),P.strokeStyle=se||B,P.lineWidth=2,P.stroke()},e[0]=p,e[1]=x,e[2]=f,e[3]=w,e[4]=V):V=e[4];let A;e[5]!==p||e[6]!==x||e[7]!==N||e[8]!==f||e[9]!==a||e[10]!==m||e[11]!==w?(A=[a,f,p,x,m,N,w],e[5]=p,e[6]=x,e[7]=N,e[8]=f,e[9]=a,e[10]=m,e[11]=w,e[12]=A):A=e[12],l.useLayoutEffect(V,A);let S;e[13]!==w?(S={width:w,height:"100%",position:"relative",flexShrink:0,overflow:"hidden"},e[13]=w,e[14]=S):S=e[14];let z;e[15]===Symbol.for("react.memo_cache_sentinel")?(z=t.jsx("canvas",{ref:v,style:{position:"absolute",inset:0,width:"100%",height:"100%",display:"block"}}),e[15]=z):z=e[15];let C;return e[16]!==S?(C=t.jsx("div",{ref:M,style:S,children:z}),e[16]=S,e[17]=C):C=e[17],C};function ci(o){return o==="branch-out"||o==="merge-in"}function di(o,e){const a=ci;return(a(o.type)?1:0)-(a(e.type)?1:0)}const yr=15e3,br=500,vr=12,jr=8*1024*1024,Cr=o=>typeof o=="string"?0:(o.original?.length??0)+(o.modified?.length??0),Nr=o=>{if(o.size<=vr){let N=0;for(const f of o.values())N+=Cr(f);if(N<=jr)return o}const e=Array.from(o.entries()).reverse(),a=new Map;let m=0;for(const[N,f]of e){if(a.size>=vr)continue;const p=Cr(f);m+p>jr&&a.size>0||(a.set(N,f),m+=p)}return new Map(Array.from(a.entries()).reverse())};function Sr(o,e){const a=new Date(o);return Number.isNaN(a.getTime())?o:Xn(a,e,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ui(o){switch(o){case"A":return"text-[var(--status-success)]";case"D":return"text-[var(--status-error)]";case"M":return"text-[var(--status-warning)]";case"R":return"text-[var(--status-info)]";default:return"text-muted-foreground"}}function mi(o){return o?o.split(",").map(e=>e.trim()).filter(Boolean).map(e=>{const a=e.startsWith("HEAD ->");return{label:a?e.replace("HEAD -> ",""):e.replace("tag: ",""),isHead:a,isTag:e.startsWith("tag: ")}}):[]}const hi=l.memo(({entry:o,mode:e="history",laned:a,totalLanes:m,isExpanded:N,onToggle:f,files:p,isLoadingFiles:x,onCopyHash:g,directory:w,onConflict:M,onActionSuccess:v})=>{const{t:V}=nt(),A=Rt(d=>d.timeFormatPreference),S=e==="graph",[z,C]=l.useState(null),[y,D]=l.useState(!1),[k,R]=l.useState(""),[P,F]=l.useState(null),[r,Y]=l.useState(new Set),[B,u]=l.useState(new Map),[E,se]=l.useState(new Set),U=async()=>{if(w){C("checkout");try{await aa(w,o.hash),b.success(V("gitView.history.actions.detachedHead")),v?.()}catch(d){b.error(String(d.message))}finally{C(null)}}},G=async()=>{if(!(!w||!k.trim())){C("createBranch");try{await Zn(w,k.trim(),o.hash),D(!1),R(""),v?.()}catch(d){b.error(String(d.message))}finally{C(null)}}},$=async()=>{if(w){C("cherryPick");try{const d=await na(w,o.hash);d.conflict?M?.({conflict:!0,conflictFiles:d.conflictFiles,operation:"cherry-pick"}):v?.()}catch(d){b.error(String(d.message))}finally{C(null)}}},X=async()=>{if(w){C("revert");try{const d=await ra(w,o.hash);d.conflict?M?.({conflict:!0,conflictFiles:d.conflictFiles,operation:"revert"}):v?.()}catch(d){b.error(String(d.message))}finally{C(null)}}},H=async(d,I=!1)=>{if(!(!w||z!==null)){C("reset");try{await ea(w,o.hash,d,I),v?.()}catch(L){b.error(String(L.message))}finally{C(null)}}},le=async()=>{if(!P)return;const d=P;switch(F(null),d){case"checkout":return U();case"cherryPick":return $();case"revert":return X();case"merge":return ae();case"rebase":return ce();case"resetSoft":return H("soft");case"resetMixed":return H("mixed");case"resetHard":return H("hard",!0)}},ae=async()=>{if(w){C("merge");try{const d=await sa(w,{branch:o.hash});d.conflict?M?.({conflict:!0,conflictFiles:d.conflictFiles,operation:"merge"}):v?.()}catch(d){b.error(String(d.message))}finally{C(null)}}},ce=async()=>{if(w){C("rebase");try{const d=await ta(w,{onto:o.hash});d.conflict?M?.({conflict:!0,conflictFiles:d.conflictFiles,operation:"rebase"}):v?.()}catch(d){b.error(String(d.message))}finally{C(null)}}},ie=l.useCallback(async d=>{const I=d.path;if(!w){u(L=>new Map(L).set(I,"error"));return}u(L=>Nr(new Map(L).set(I,"loading")));try{const L=qn(w,o.hash,d.path,!1),q=new Promise((re,J)=>{setTimeout(()=>J(new Error(`Timed out after ${yr}ms`)),yr)}),ne=await Promise.race([L,q]);u(re=>Nr(new Map(re).set(I,ne)))}catch{u(L=>new Map(L).set(I,"error"))}},[w,o.hash]),h=l.useCallback(async d=>{const I=d.path;if(d.changeType==="R"||d.isBinary){Y(re=>{const J=new Set(re);return J.has(I)?J.delete(I):J.add(I),J});return}const L=B.get(I);if(r.has(I)&&L&&L!=="error"){Y(re=>{const J=new Set(re);return J.delete(I),J});return}Y(re=>{const J=new Set(re);return J.add(I),J}),!(L&&L!=="error"||d.insertions+d.deletions>br&&!E.has(I))&&await ie(d)},[B,E,ie,r]);return t.jsxs("li",{children:[t.jsxs("button",{type:"button",onClick:f,className:Se("w-full flex items-start gap-3 px-3 py-2 text-left transition-colors",S?"hover:bg-[var(--interactive-hover)]/40":N?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[S&&a&&m!==void 0?t.jsx("div",{className:"-my-2 shrink-0 self-stretch",children:t.jsx(li,{laned:a,totalLanes:m,isExpanded:N})}):t.jsx("div",{className:"h-2 w-2 translate-y-2 rounded-full shrink-0",style:{backgroundColor:"var(--status-success)"},"aria-hidden":!0}),t.jsxs("div",{className:"min-w-0 flex-1",children:[S?(()=>{const d=mi(o.refs);return d.length>0?t.jsx("div",{className:"flex flex-wrap gap-1 mb-0.5",children:d.map(I=>t.jsx("span",{className:Se("inline-flex items-center px-1.5 py-0 typography-micro rounded font-medium",I.isHead?"bg-[var(--chart-1)] text-[var(--primary-foreground)]":I.isTag?"bg-[var(--chart-5)] text-[var(--primary-foreground)]":"bg-[var(--interactive-hover)] text-[var(--foreground)]"),children:I.label},I.label))}):null})():null,t.jsx("p",{className:"typography-ui-label font-medium text-foreground line-clamp-1",children:o.message}),t.jsxs("div",{className:"flex items-center gap-1 typography-meta text-muted-foreground",children:[t.jsxs("div",{className:"flex items-center gap-1 min-w-0 truncate",children:[t.jsx("span",{className:"truncate min-w-[3ch]",title:o.author_name,children:o.author_name}),t.jsx("span",{className:"shrink-0",children:"·"}),t.jsx("span",{className:"truncate min-w-0",title:Sr(o.date,A),children:Sr(o.date,A)})]}),t.jsx("span",{className:"shrink-0",children:"·"}),t.jsx("code",{className:"shrink-0 font-mono",children:o.hash.slice(0,8)}),t.jsxs(es,{children:[t.jsx(ts,{asChild:!0,children:t.jsx(W,{variant:"ghost",size:"sm",className:"h-5 px-1 shrink-0",onClick:d=>{d.stopPropagation(),g(o.hash)},children:t.jsx(T,{name:"file-copy",className:"size-3"})})}),t.jsx(ss,{sideOffset:8,children:V("gitView.history.copySha")})]})]})]})]}),N&&t.jsxs("div",{className:"px-3 pb-2 pl-8 border-t border-border/40",children:[S&&P?t.jsxs("div",{className:"flex items-center gap-2 py-2 border-b border-border/30 mb-2",children:[t.jsx("span",{className:"typography-micro text-muted-foreground flex-1 min-w-0",children:V(`gitView.history.actions.${P}Confirm`)}),t.jsxs(W,{variant:"destructive",size:"xs",className:"h-6 shrink-0",disabled:z!==null,onClick:d=>{d.stopPropagation(),le()},children:[z!==null?t.jsx(T,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,V("gitView.history.actions.confirmButton")]}),t.jsx(W,{variant:"ghost",size:"xs",className:"h-6 shrink-0",disabled:z!==null,onClick:d=>{d.stopPropagation(),F(null)},children:V("gitView.history.actions.cancelButton")})]}):S?t.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 py-2 border-b border-border/30 mb-2",children:[t.jsx(W,{variant:"outline",size:"xs",className:"h-6",disabled:z!==null,onClick:d=>{d.stopPropagation(),F("checkout")},children:V("gitView.history.actions.checkout")}),y?t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx("input",{autoFocus:!0,value:k,onChange:d=>R(d.target.value),onKeyDown:d=>{d.key==="Enter"&&G(),d.key==="Escape"&&(D(!1),R(""))},placeholder:V("gitView.history.actions.createBranchPlaceholder"),className:"h-6 text-xs px-2 rounded border border-border/60 bg-background min-w-0 w-32"}),t.jsxs(W,{variant:"outline",size:"xs",className:"h-6",disabled:!k.trim()||z!==null,onClick:d=>{d.stopPropagation(),G()},children:[z==="createBranch"?t.jsx(T,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,V("gitView.history.actions.createBranchConfirm")]})]}):t.jsx(W,{variant:"outline",size:"xs",className:"h-6",onClick:d=>{d.stopPropagation(),D(!0)},children:V("gitView.history.actions.createBranch")}),t.jsx(W,{variant:"outline",size:"xs",className:"h-6",disabled:z!==null,onClick:d=>{d.stopPropagation(),F("cherryPick")},children:V("gitView.history.actions.cherryPick")}),t.jsx(W,{variant:"outline",size:"xs",className:"h-6",disabled:z!==null,onClick:d=>{d.stopPropagation(),F("revert")},children:V("gitView.history.actions.revert")}),t.jsxs(Ts,{children:[t.jsx(As,{asChild:!0,children:t.jsxs(W,{variant:"outline",size:"xs",className:"h-6",disabled:z!==null,onClick:d=>d.stopPropagation(),children:[z==="reset"?t.jsx(T,{name:"loader-4",className:"size-3 animate-spin mr-1"}):null,V("gitView.history.actions.reset")]})}),t.jsx(Ls,{align:"start",className:"min-w-max",children:["soft","mixed","hard"].map(d=>t.jsx(Yn,{disabled:z!==null,onSelect:I=>{I.stopPropagation(),F(`reset${d.charAt(0).toUpperCase()+d.slice(1)}`)},children:V(`gitView.history.actions.reset${d.charAt(0).toUpperCase()+d.slice(1)}`)},d))})]}),t.jsx(W,{variant:"outline",size:"xs",className:"h-6",disabled:z!==null,onClick:d=>{d.stopPropagation(),F("merge")},children:V("gitView.history.actions.merge")}),t.jsx(W,{variant:"outline",size:"xs",className:"h-6",disabled:z!==null,onClick:d=>{d.stopPropagation(),F("rebase")},children:V("gitView.history.actions.rebase")})]}):null,x?t.jsxs("div",{className:"flex items-center gap-2 py-2",children:[t.jsx(T,{name:"loader-4",className:"size-4 animate-spin text-muted-foreground"}),t.jsx("span",{className:"typography-micro text-muted-foreground",children:V("gitView.history.loadingFiles")})]}):p.length===0?t.jsx("p",{className:"typography-micro text-muted-foreground py-2",children:V("gitView.history.noFiles")}):t.jsx("ul",{className:"space-y-0.5 py-2",children:p.map(d=>t.jsxs("li",{children:[t.jsxs("button",{type:"button",onClick:()=>h(d),className:Se("w-full flex items-center gap-2 typography-micro text-left cursor-pointer transition-colors rounded px-1",r.has(d.path)?"bg-sidebar/90":"hover:bg-sidebar/40"),children:[t.jsx("span",{className:Se("font-semibold w-3 text-center shrink-0",ui(d.changeType)),children:d.changeType}),t.jsx("span",{className:"truncate text-foreground min-w-0",title:d.path,children:d.path}),!d.isBinary&&t.jsxs("span",{className:"shrink-0",children:[t.jsxs("span",{style:{color:"var(--status-success)"},children:["+",d.insertions]}),t.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),t.jsxs("span",{style:{color:"var(--status-error)"},children:["-",d.deletions]})]}),d.isBinary&&t.jsx("span",{className:"typography-micro text-muted-foreground shrink-0",children:V("gitView.history.binary")}),t.jsx(T,{name:r.has(d.path)?"arrow-down-s":"arrow-right-s",className:"size-3 shrink-0 text-muted-foreground"})]}),r.has(d.path)&&t.jsx("div",{className:"max-h-[400px] overflow-y-auto rounded border border-border/40 mx-2 mb-1","data-diff-virtual-root":!0,"data-diff-virtual-content":!0,children:d.changeType==="R"?t.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:V("gitView.history.renamedNoDiff")}):d.isBinary?t.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:V("gitView.history.binaryNoDiff")}):(()=>{const I=d.insertions+d.deletions;if(!E.has(d.path)&&I>br)return t.jsxs("div",{className:"flex flex-col items-start gap-1 px-3 py-2 text-sm text-muted-foreground",children:[t.jsx("div",{className:"typography-ui-label font-semibold text-foreground",children:V("gitView.history.largeDiffTitle",{count:I})}),t.jsx("div",{className:"typography-meta text-muted-foreground",children:V("gitView.history.largeDiffDescription")}),t.jsx(W,{type:"button",variant:"ghost",size:"xs",className:"h-6 px-0 text-primary hover:bg-transparent hover:underline",onClick:()=>{se(q=>new Set(q).add(d.path)),ie(d)},children:V("gitView.history.renderDiffAnyway")})]});const L=B.get(d.path);return L==="loading"||L===void 0?t.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:V("gitView.history.loadingDiff")}):L==="error"?t.jsx("button",{type:"button",onClick:()=>h(d),className:"w-full text-left px-3 py-2 text-sm text-muted-foreground hover:bg-[var(--interactive-hover)] transition-colors",children:V("gitView.history.diffError")}):t.jsx(qa,{original:L.original,modified:L.modified,language:Qn(d.path)||"",fileName:d.path,renderSideBySide:!1,layout:"inline",enableComments:!1})})()})]},d.path))})]})]})}),kr=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)","var(--syntax-keyword)","var(--syntax-string)","var(--status-info)"];function qt(o){return kr[o%kr.length]}function gi(o){if(o.length===0)return[];const e=[],a=[];for(let m=0;m<o.length;m++){const N=o[m],f=[];for(let S=0;S<e.length;S++)e[S]===N.hash&&f.push(S);let p=f.length>0?f[0]:-1;if(p===-1){const S=e.indexOf(null);S!==-1?p=S:(p=e.length,e.push(null))}const x=f.slice(1),g=qt(p),w=e[p]===N.hash,M=N.parents.length>0;M?e[p]=N.parents[0]:e[p]=null;const v=[],V=new Set;for(let S=1;S<N.parents.length;S++){const z=N.parents[S],C=e.indexOf(z);if(C!==-1)v.push(C);else{const y=e.indexOf(null);if(y!==-1)e[y]=z,v.push(y),V.add(y);else{const D=e.length;e.push(z),v.push(D),V.add(D)}}}const A=[];w&&M?A.push({fromLane:p,toLane:p,color:g,type:"commit-lane"}):w&&!M?A.push({fromLane:p,toLane:p,color:g,type:"top-stub"}):!w&&M&&A.push({fromLane:p,toLane:p,color:g,type:"bottom-stub"});for(const S of x)A.push({fromLane:S,toLane:p,color:qt(S),type:"merge-in"}),e[S]=null;for(const S of v)A.push({fromLane:p,toLane:S,color:qt(S),type:"branch-out"});for(let S=0;S<e.length;S++)e[S]!==null&&S!==p&&(V.has(S)||A.push({fromLane:S,toLane:S,color:qt(S),type:"passing"}));a.push({commit:N,lane:p,color:g,connectors:A})}return a}const fi=[{labelKey:"gitView.history.logSize25",value:25},{labelKey:"gitView.history.logSize50",value:50},{labelKey:"gitView.history.logSize100",value:100}],pi=o=>{const e=Ct.c(84),{mode:a,log:m,isLogLoading:N,logMaxCount:f,onLogMaxCountChange:p,expandedCommitHashes:x,onToggleCommit:g,commitFilesMap:w,loadingCommitHashes:M,onCopyHash:v,directory:V,showHeader:A,contentMaxHeightClassName:S,branchDivider:z,onConflict:C,onActionSuccess:y}=o,D=a===void 0?"history":a,k=A===void 0?!0:A,R=S===void 0?"max-h-[50vh]":S,P=z===void 0?null:z,{t:F}=nt(),[r,Y]=l.useState(!0),B=D==="graph";let u;e[0]!==B||e[1]!==m?(u=B&&m?gi(m.all):[],e[0]=B,e[1]=m,e[2]=u):u=e[2];const E=u;let se;e[3]!==E?(se=Math.max(1,...E.map(xi)),e[3]=E,e[4]=se):se=e[4];const U=se;let G;e[5]!==E?(G=new Map(E.map(wi)),e[5]=E,e[6]=G):G=e[6];const $=G;if(!m)return null;const X=P!==null&&P.insertBeforeIndex>0&&P.insertBeforeIndex<m.all.length,H=P!==null&&P.insertBeforeIndex===m.all.length,le=X||H;let ae;e[7]!==P||e[8]!==X||e[9]!==H||e[10]!==m.all?(ae=X?m.all.slice(0,P.insertBeforeIndex):H?m.all:[],e[7]=P,e[8]=X,e[9]=H,e[10]=m.all,e[11]=ae):ae=e[11];const ce=ae;let ie;if(e[12]!==P||e[13]!==w||e[14]!==R||e[15]!==V||e[16]!==x||e[17]!==X||e[18]!==le||e[19]!==B||e[20]!==N||e[21]!==$||e[22]!==M||e[23]!==m.all||e[24]!==f||e[25]!==U||e[26]!==D||e[27]!==y||e[28]!==C||e[29]!==v||e[30]!==p||e[31]!==g||e[32]!==F||e[33]!==ce){const K=X?m.all.slice(P.insertBeforeIndex):[];let de;e[35]!==P?.direction?(de=P?.direction==="down"?t.jsx(T,{name:"arrow-down-s",className:"size-3.5"}):t.jsx(T,{name:"arrow-up",className:"size-3.5"}),e[35]=P?.direction,e[36]=de):de=e[36];const ke=de;let ye;e[37]!==w||e[38]!==V||e[39]!==x||e[40]!==B||e[41]!==$||e[42]!==M||e[43]!==U||e[44]!==D||e[45]!==y||e[46]!==C||e[47]!==v||e[48]!==g?(ye=Re=>t.jsx("ul",{className:"divide-y divide-border/60",children:Re.map(ue=>t.jsx(hi,{entry:ue,mode:D,laned:B?$.get(ue.hash):void 0,totalLanes:B?U:void 0,isExpanded:x.has(ue.hash),onToggle:()=>g(ue.hash),files:w.get(ue.hash)??[],isLoadingFiles:M.has(ue.hash),onCopyHash:v,directory:V,onConflict:C,onActionSuccess:y},ue.hash))}),e[37]=w,e[38]=V,e[39]=x,e[40]=B,e[41]=$,e[42]=M,e[43]=U,e[44]=D,e[45]=y,e[46]=C,e[47]=v,e[48]=g,e[49]=ye):ye=e[49];const me=ye;let xe;e[50]!==N||e[51]!==m.all.length||e[52]!==f||e[53]!==p||e[54]!==F?(xe=m.all.length>=f?t.jsx("div",{className:"flex justify-center py-2 border-t border-border/40",children:t.jsx(W,{type:"button",variant:"ghost",size:"xs",onClick:()=>p(f+25),disabled:N,className:"px-3 text-muted-foreground hover:text-foreground",children:N?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx(T,{name:"loader-4",className:"size-3 animate-spin"}),F("gitView.history.loadingMore")]}):F("gitView.history.loadMore")})}):null,e[50]=N,e[51]=m.all.length,e[52]=f,e[53]=p,e[54]=F,e[55]=xe):xe=e[55];const Ve=xe;ie=t.jsx(Rr,{outerClassName:`min-h-0 ${R}`,className:"h-full w-full",children:m.all.length===0?t.jsx("div",{className:"flex h-full items-center justify-center p-4",children:t.jsx("p",{className:"typography-ui-label text-muted-foreground",children:F("gitView.history.noCommits")})}):le&&P?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-col gap-0",children:[ce.length>0?t.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:me(ce)}):null,t.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5","aria-hidden":!0,children:[t.jsx("span",{className:"h-px flex-1 bg-border/60"}),t.jsxs("span",{className:"inline-flex max-w-[80%] items-center gap-1 typography-micro text-muted-foreground",children:[t.jsx("span",{className:"truncate",title:P.branchName,children:P.branchName}),ke]}),t.jsx("span",{className:"h-px flex-1 bg-border/60"})]}),K.length>0?t.jsx("div",{className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:me(K)}):null]}),Ve]}):t.jsxs(t.Fragment,{children:[me(m.all),Ve]})}),e[12]=P,e[13]=w,e[14]=R,e[15]=V,e[16]=x,e[17]=X,e[18]=le,e[19]=B,e[20]=N,e[21]=$,e[22]=M,e[23]=m.all,e[24]=f,e[25]=U,e[26]=D,e[27]=y,e[28]=C,e[29]=v,e[30]=p,e[31]=g,e[32]=F,e[33]=ce,e[34]=ie}else ie=e[34];const h=ie;if(!k){if(le){let de;return e[56]!==h?(de=t.jsx("section",{className:"h-full min-h-0",children:h}),e[56]=h,e[57]=de):de=e[57],de}let K;return e[58]!==h?(K=t.jsx("section",{className:"h-full min-h-0 rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:h}),e[58]=h,e[59]=K):K=e[59],K}let d;e[60]!==F?(d=F("gitView.history.title"),e[60]=F,e[61]=d):d=e[61];let I;e[62]!==d?(I=t.jsx("h3",{className:"typography-ui-header font-semibold text-foreground",children:d}),e[62]=d,e[63]=I):I=e[63];let L;e[64]!==N||e[65]!==r||e[66]!==f||e[67]!==p||e[68]!==F?(L=r&&t.jsx("div",{onClick:yi,onPointerDown:bi,children:t.jsxs(ia,{value:String(f),onValueChange:K=>p(Number(K)),disabled:N,children:[t.jsx(oa,{size:"sm",className:"w-auto",disabled:N,children:t.jsx(la,{placeholder:F("gitView.history.commitsPlaceholder")})}),t.jsx(ca,{children:fi.map(K=>t.jsx(da,{value:String(K.value),children:F(K.labelKey)},K.value))})]})}),e[64]=N,e[65]=r,e[66]=f,e[67]=p,e[68]=F,e[69]=L):L=e[69];let q;e[70]!==r?(q=r?t.jsx(T,{name:"arrow-up-s",className:"size-4 text-muted-foreground"}):t.jsx(T,{name:"arrow-down-s",className:"size-4 text-muted-foreground"}),e[70]=r,e[71]=q):q=e[71];let ne;e[72]!==L||e[73]!==q?(ne=t.jsxs("div",{className:"flex items-center gap-2",children:[L,q]}),e[72]=L,e[73]=q,e[74]=ne):ne=e[74];let re;e[75]!==I||e[76]!==ne?(re=t.jsxs(Oa,{className:"flex w-full items-center justify-between px-3 h-10 hover:bg-transparent",children:[I,ne]}),e[75]=I,e[76]=ne,e[77]=re):re=e[77];let J;e[78]!==h?(J=t.jsx(za,{children:h}),e[78]=h,e[79]=J):J=e[79];let we;return e[80]!==r||e[81]!==re||e[82]!==J?(we=t.jsxs(Ga,{open:r,onOpenChange:Y,className:"rounded-xl border border-border/60 bg-background/70 overflow-hidden",children:[re,J]}),e[80]=r,e[81]=re,e[82]=J,e[83]=we):we=e[83],we};function xi(o){return o.lane+1}function wi(o){return[o.commit.hash,o]}function yi(o){return o.stopPropagation()}function bi(o){return o.stopPropagation()}const vi=o=>{const e=Ct.c(148),{open:a,onOpenChange:m,conflictFiles:N,directory:f,operation:p,onAbort:x,onClearState:g}=o;let w;e[0]!==N?(w=N===void 0?[]:N,e[0]=N,e[1]=w):w=e[1];const M=w,{t:v}=nt(),V=rt(ji),A=rt(Ci),S=Qt(Ni),z=Qt(Si),[C,y]=l.useState(!1),[D,k]=l.useState(null),[R,P]=l.useState(null);let F,r;e[2]!==f||e[3]!==a||e[4]!==v?(F=()=>{!a||!f||(y(!0),P(null),k(null),ua(f).then(ee=>{k(ee)}).catch(ee=>{const he=ee instanceof Error?ee.message:v("gitView.conflict.loadFailed");P(he)}).finally(()=>{y(!1)}))},r=[a,f,v],e[2]=f,e[3]=a,e[4]=v,e[5]=F,e[6]=r):(F=e[5],r=e[6]),l.useEffect(F,r);let Y;e[7]!==D||e[8]!==f||e[9]!==p?(Y=async()=>{if(!D)return null;const ee=p==="merge"?"merge":"rebase",he=D.headInfo||(p==="merge"?"MERGE_HEAD":"REBASE_HEAD"),Be=p==="merge"?"git commit --no-edit":"git rebase --continue",ge=await Yt("git.conflict.resolve.visible",{operation_label:ee,head_ref:he}),Ne=await Yt("git.conflict.resolve.instructions",{operation_label:ee,directory:f,operation:p,head_info:D.headInfo||"N/A",continue_cmd:Be}),Ie=`${ee} conflict context (JSON)
3
+ ${JSON.stringify({directory:f,operation:D.operation,headInfo:D.headInfo,statusPorcelain:D.statusPorcelain,unmergedFiles:D.unmergedFiles,diff:D.diff},null,2)}`;return{visibleText:ge,instructionsText:Ne,payloadText:Ie}},e[7]=D,e[8]=f,e[9]=p,e[10]=Y):Y=e[10];const B=Y;let u;e[11]!==x||e[12]!==m?(u=()=>{x(),m(!1)},e[11]=x,e[12]=m,e[13]=u):u=e[13];const E=u;let se;e[14]!==g||e[15]!==m?(se=()=>{g?.(),m(!1)},e[14]=g,e[15]=m,e[16]=se):se=e[16];const U=se;let G;e[17]!==B||e[18]!==A||e[19]!==g||e[20]!==m||e[21]!==S||e[22]!==z||e[23]!==v?(G=async()=>{const ee=await B();if(!ee){b.error(v("gitView.conflict.noDetailsAvailable"));return}if(!A){b.error(v("gitView.conflict.noActiveSession"),{description:v("gitView.conflict.noActiveSessionDescription")});return}S(ee.visibleText,"replace"),z([{text:ee.instructionsText,synthetic:!0},{text:ee.payloadText,synthetic:!0}]),g?.(),m(!1)},e[17]=B,e[18]=A,e[19]=g,e[20]=m,e[21]=S,e[22]=z,e[23]=v,e[24]=G):G=e[24];const $=G;let X;e[25]!==B||e[26]!==f||e[27]!==g||e[28]!==m||e[29]!==V||e[30]!==v?(X=async()=>{const ee=await B();if(!ee){b.error(v("gitView.conflict.noDetailsAvailable"));return}V({directoryOverride:f,initialPrompt:ee.visibleText,syntheticParts:[{text:ee.instructionsText,synthetic:!0},{text:ee.payloadText,synthetic:!0}]}),g?.(),m(!1)},e[25]=B,e[26]=f,e[27]=g,e[28]=m,e[29]=V,e[30]=v,e[31]=X):X=e[31];const H=X;let le,ae,ce,ie,h,d,I,L,q,ne,re,J,we,K,de,ke,ye,me,xe,Ve,Re,ue;if(e[32]!==D||e[33]!==M||e[34]!==A||e[35]!==E||e[36]!==U||e[37]!==$||e[38]!==H||e[39]!==C||e[40]!==R||e[41]!==m||e[42]!==a||e[43]!==p||e[44]!==v){const ee=v(p==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),he=D?.unmergedFiles||M;ce=mt,Re=a,ue=m,ae=ht,Ve="max-w-md w-[calc(100vw-2rem)]",K="flex flex-col gap-4 overflow-hidden";let Be;e[67]===Symbol.for("react.memo_cache_sentinel")?(Be=t.jsx(T,{name:"alert",className:"size-5 shrink-0 text-[var(--status-warning)]"}),e[67]=Be):Be=e[67];const ge=t.jsxs("div",{className:"flex items-center gap-2",children:[Be,t.jsx(ft,{children:v("gitView.conflict.detectedTitle",{operation:ee})})]});let Ne;e[68]!==p||e[69]!==v?(Ne=v("gitView.conflict.detectedDescription",{operation:p}),e[68]=p,e[69]=v,e[70]=Ne):Ne=e[70];let Ie;e[71]!==Ne?(Ie=t.jsx(bt,{children:Ne}),e[71]=Ne,e[72]=Ie):Ie=e[72],e[73]!==ge||e[74]!==Ie?(de=t.jsxs(gt,{children:[ge,Ie]}),e[73]=ge,e[74]=Ie,e[75]=de):de=e[75],e[76]!==C||e[77]!==v?(ke=C&&t.jsxs("div",{className:"flex items-center justify-center gap-2 py-4 text-muted-foreground",children:[t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),t.jsx("span",{className:"typography-meta",children:v("gitView.conflict.loading")})]}),e[76]=C,e[77]=v,e[78]=ke):ke=e[78],e[79]!==R||e[80]!==v?(ye=R&&t.jsx("div",{className:"rounded-lg bg-[var(--status-error-bg)] p-3 text-[var(--status-error)] typography-meta break-words",children:v("gitView.conflict.errorLoadingDetails",{message:R})}),e[79]=R,e[80]=v,e[81]=ye):ye=e[81],e[82]!==he||e[83]!==v?(me=he.length>0&&t.jsxs("div",{className:"space-y-2 overflow-hidden",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:v("gitView.conflict.conflictedFiles")}),t.jsx("span",{className:"typography-micro px-1.5 py-0.5 rounded bg-[var(--surface-elevated)] text-muted-foreground",children:he.length})]}),t.jsx("div",{className:"bg-[var(--surface-elevated)] rounded-lg p-3 max-h-40 overflow-y-auto overflow-x-hidden",children:t.jsx("ul",{className:"space-y-1",children:he.map(ki)})})]}),e[82]=he,e[83]=v,e[84]=me):me=e[84],e[85]!==D||e[86]!==v?(xe=D?.headInfo&&t.jsxs("div",{className:"space-y-1 overflow-hidden",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:v("gitView.conflict.headInfo")}),t.jsx("div",{className:"typography-micro text-foreground font-mono bg-[var(--surface-elevated)] rounded-lg p-3 max-h-24 overflow-y-auto break-words whitespace-pre-wrap",children:D.headInfo})]}),e[85]=D,e[86]=v,e[87]=xe):xe=e[87],re="flex flex-col gap-2 pt-2";let Te;e[88]!==H?(Te=()=>{H()},e[88]=H,e[89]=Te):Te=e[89];const oe=C||!D;let Pe;e[90]!==C?(Pe=C?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"add",className:"size-4"}),e[90]=C,e[91]=Pe):Pe=e[91];let Fe;e[92]!==v?(Fe=v("gitView.conflict.resolveNewSession"),e[92]=v,e[93]=Fe):Fe=e[93],e[94]!==Te||e[95]!==oe||e[96]!==Pe||e[97]!==Fe?(J=t.jsxs(W,{variant:"default",onClick:Te,disabled:oe,className:"w-full gap-2",children:[Pe,Fe]}),e[94]=Te,e[95]=oe,e[96]=Pe,e[97]=Fe,e[98]=J):J=e[98];let De;e[99]!==$?(De=()=>{$()},e[99]=$,e[100]=De):De=e[100];const Ue=C||!D||!A;let Ae;e[101]!==C?(Ae=C?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"chat-1",className:"size-4"}),e[101]=C,e[102]=Ae):Ae=e[102];let Q;e[103]!==v?(Q=v("gitView.conflict.resolveCurrentSession"),e[103]=v,e[104]=Q):Q=e[104],e[105]!==De||e[106]!==Ue||e[107]!==Ae||e[108]!==Q?(we=t.jsxs(W,{variant:"outline",onClick:De,disabled:Ue,className:"w-full gap-2",children:[Ae,Q]}),e[105]=De,e[106]=Ue,e[107]=Ae,e[108]=Q,e[109]=we):we=e[109],q="flex gap-2 pt-1";let fe;e[110]!==v?(fe=v("gitView.conflict.continueLater"),e[110]=v,e[111]=fe):fe=e[111],e[112]!==U||e[113]!==fe?(ne=t.jsx(W,{variant:"ghost",size:"sm",onClick:U,className:"flex-1",children:fe}),e[112]=U,e[113]=fe,e[114]=ne):ne=e[114],le=W,ie="destructive",h="sm",d=E,I="flex-1",L=v("gitView.conflict.abortOperation",{operation:ee}),e[32]=D,e[33]=M,e[34]=A,e[35]=E,e[36]=U,e[37]=$,e[38]=H,e[39]=C,e[40]=R,e[41]=m,e[42]=a,e[43]=p,e[44]=v,e[45]=le,e[46]=ae,e[47]=ce,e[48]=ie,e[49]=h,e[50]=d,e[51]=I,e[52]=L,e[53]=q,e[54]=ne,e[55]=re,e[56]=J,e[57]=we,e[58]=K,e[59]=de,e[60]=ke,e[61]=ye,e[62]=me,e[63]=xe,e[64]=Ve,e[65]=Re,e[66]=ue}else le=e[45],ae=e[46],ce=e[47],ie=e[48],h=e[49],d=e[50],I=e[51],L=e[52],q=e[53],ne=e[54],re=e[55],J=e[56],we=e[57],K=e[58],de=e[59],ke=e[60],ye=e[61],me=e[62],xe=e[63],Ve=e[64],Re=e[65],ue=e[66];let $e;e[115]!==le||e[116]!==ie||e[117]!==h||e[118]!==d||e[119]!==I||e[120]!==L?($e=t.jsx(le,{variant:ie,size:h,onClick:d,className:I,children:L}),e[115]=le,e[116]=ie,e[117]=h,e[118]=d,e[119]=I,e[120]=L,e[121]=$e):$e=e[121];let Oe;e[122]!==q||e[123]!==ne||e[124]!==$e?(Oe=t.jsxs("div",{className:q,children:[ne,$e]}),e[122]=q,e[123]=ne,e[124]=$e,e[125]=Oe):Oe=e[125];let je;e[126]!==re||e[127]!==J||e[128]!==we||e[129]!==Oe?(je=t.jsxs("div",{className:re,children:[J,we,Oe]}),e[126]=re,e[127]=J,e[128]=we,e[129]=Oe,e[130]=je):je=e[130];let be;e[131]!==K||e[132]!==de||e[133]!==ke||e[134]!==ye||e[135]!==me||e[136]!==xe||e[137]!==je?(be=t.jsxs("div",{className:K,children:[de,ke,ye,me,xe,je]}),e[131]=K,e[132]=de,e[133]=ke,e[134]=ye,e[135]=me,e[136]=xe,e[137]=je,e[138]=be):be=e[138];let Ce;e[139]!==ae||e[140]!==Ve||e[141]!==be?(Ce=t.jsx(ae,{className:Ve,children:be}),e[139]=ae,e[140]=Ve,e[141]=be,e[142]=Ce):Ce=e[142];let Ee;return e[143]!==ce||e[144]!==Re||e[145]!==ue||e[146]!==Ce?(Ee=t.jsx(ce,{open:Re,onOpenChange:ue,children:Ce}),e[143]=ce,e[144]=Re,e[145]=ue,e[146]=Ce,e[147]=Ee):Ee=e[147],Ee};function ji(o){return o.openNewSessionDraft}function Ci(o){return o.currentSessionId}function Ni(o){return o.setPendingInputText}function Si(o){return o.setPendingSyntheticParts}function ki(o){return t.jsx("li",{className:"typography-micro text-foreground font-mono truncate block",title:o,children:o},o)}const Vi=({open:o,onOpenChange:e,operation:a,targetBranch:m,onConfirm:N})=>{const{t:f}=nt(),[p,x]=l.useState(!0),[g,w]=l.useState(!1),M=f(a==="merge"?"gitView.operation.merge":"gitView.operation.rebase"),v=async()=>{w(!0);try{await N(p),e(!1)}catch(A){const S=A instanceof Error?A.message:`Failed to ${a}`;b.error(S)}finally{w(!1)}},V=()=>{g||e(!1)};return t.jsx(mt,{open:o,onOpenChange:g?void 0:e,children:t.jsxs(ht,{className:"max-w-md",children:[t.jsxs(gt,{children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(T,{name:"alert",className:"size-5 text-[var(--status-warning)]"}),t.jsx(ft,{children:f("gitView.stash.title")})]}),t.jsx(bt,{children:f("gitView.stash.description",{operation:a})})]}),t.jsxs("div",{className:"py-2",children:[t.jsx("p",{className:"typography-meta text-muted-foreground mb-3",children:f("gitView.stash.thisWill")}),t.jsxs("ol",{className:"list-decimal list-inside space-y-1 typography-meta text-foreground",children:[t.jsx("li",{children:f("gitView.stash.stepStash")}),t.jsxs("li",{children:[f(a==="merge"?"gitView.operation.merge":"gitView.operation.rebase")," ",f(a==="merge"?"gitView.stash.mergeWith":"gitView.stash.rebaseOnto")," ",t.jsx("span",{className:"font-mono text-primary",children:m})]}),p&&t.jsx("li",{children:f("gitView.stash.stepRestore")})]})]}),t.jsxs("div",{className:"flex items-center gap-2 py-2",children:[t.jsx(ma,{checked:p,onChange:x,disabled:g,ariaLabel:f("gitView.stash.restoreAria")}),t.jsx("span",{className:"typography-ui-label text-foreground cursor-pointer select-none",onClick:()=>!g&&x(!p),children:f("gitView.stash.restoreAfterOperation",{operation:a})})]}),t.jsxs(Es,{className:"gap-2",children:[t.jsx(W,{variant:"ghost",size:"sm",onClick:V,disabled:g,children:f("gitView.common.cancel")}),t.jsx(W,{variant:"default",size:"sm",onClick:v,disabled:g,className:"gap-1.5",children:g?t.jsxs(t.Fragment,{children:[t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),f("gitView.common.processing")]}):f("gitView.stash.confirmButton",{operation:M})})]})]})})},Ii=({mergeInProgress:o,rebaseInProgress:e,onContinue:a,onAbort:m,onResolveWithAI:N,conflictCount:f=0,isLoading:p=!1})=>{const{t:x}=nt(),[g,w]=l.useState(null),M=o&&o.head,v=e&&(e.headName||e.onto),V=M?"merge":v?"rebase":null;if(!V)return null;const A=async()=>{w("continue");try{await a()}finally{w(null)}},S=async()=>{w("abort");try{await m()}finally{w(null)}},z=g!==null,C=f>0,y=x(V==="merge"?"gitView.operation.merge":"gitView.operation.rebase");let D="";o?D=o.message?x("gitView.operation.mergingMessage",{message:o.message}):x("gitView.operation.mergeInProgressWithHead",{head:o.head}):e&&(D=e.headName?x("gitView.operation.rebasingOnto",{headName:e.headName,onto:e.onto||""}):x("gitView.operation.rebaseInProgress"));const k=C?f===1?x("gitView.operation.inProgressTitleOneConflict",{operation:y,count:f}):x("gitView.operation.inProgressTitleManyConflicts",{operation:y,count:f}):x("gitView.operation.inProgressTitle",{operation:y}),R=x(C?"gitView.operation.resolveConflictsHint":"gitView.operation.readyToContinueHint");return t.jsx("div",{className:"mx-4 mt-3 overflow-hidden rounded-lg border border-[var(--status-warning-border)]",children:t.jsxs("div",{className:"flex flex-col gap-3 p-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"typography-label text-[var(--status-warning)]",children:k}),D&&t.jsx("p",{className:"typography-micro break-words text-muted-foreground",children:D})]}),t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[t.jsx("p",{className:"typography-micro min-w-0 flex-1 text-muted-foreground",children:R}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[t.jsxs(W,{variant:"ghost",size:"sm",onClick:S,disabled:z||p,className:"gap-1.5",children:[g==="abort"?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"close",className:"size-4"}),x("gitView.operation.abort")]}),C?N&&t.jsx(W,{variant:"default",size:"sm",onClick:N,disabled:z||p,children:x("gitView.operation.resolveWithAi")}):t.jsxs(W,{variant:"default",size:"sm",onClick:A,disabled:z||p,className:"gap-1.5",children:[g==="continue"?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"check",className:"size-4"}),x("gitView.operation.continue")]})]})]})]})})},Pi=o=>{const e=Ct.c(104),{currentBranch:a,localBranches:m,remoteBranches:N,onMerge:f,onRebase:p,disabled:x,isOperating:g,operationLogs:w,onOperationComplete:M,mode:v,defaultTargetBranch:V}=o,A=x===void 0?!1:x,S=g===void 0?!1:g,z=w===void 0?[]:w,C=v===void 0?"dialog":v,{t:y}=nt(),[D,k]=l.useState(!1),[R,P]=l.useState("merge"),[F,r]=l.useState(null),[Y,B]=l.useState(!1),[u,E]=l.useState(""),se=l.useRef(null),U=l.useRef(null),G=A||S,$=a||y("gitView.branch.currentBranchFallback"),X=z.length>0&&z.every(Fi),H=z.some(Ri);let le;e[0]===Symbol.for("react.memo_cache_sentinel")?(le=()=>{U.current&&(U.current.scrollTop=U.current.scrollHeight)},e[0]=le):le=e[0],l.useEffect(le,[z]);let ae;e[1]!==N?(ae=new Set(N.map(Bi).filter(Boolean)),e[1]=N,e[2]=ae):ae=e[2];const ce=ae;let ie;if(e[3]!==u||e[4]!==a||e[5]!==m||e[6]!==ce){let Q;e[8]!==a||e[9]!==ce?(Q=Le=>Le!==a&&!ce.has(Le),e[8]=a,e[9]=ce,e[10]=Q):Q=e[10];const fe=m.filter(Q);ie=Dt(fe,u,Di),e[3]=u,e[4]=a,e[5]=m,e[6]=ce,e[7]=ie}else ie=e[7];const h=ie;let d;e[11]!==u||e[12]!==N?(d=Dt(N,u,Mi),e[11]=u,e[12]=N,e[13]=d):d=e[13];const I=d;let L;e[14]!==V||e[15]!==m||e[16]!==N?(L=()=>V&&(N.includes(V)||m.includes(V))?V:null,e[14]=V,e[15]=m,e[16]=N,e[17]=L):L=e[17];const q=L;let ne;e[18]!==q||e[19]!==k?(ne=()=>{k(!0),r(q()),P("merge"),E("")},e[18]=q,e[19]=k,e[20]=ne):ne=e[20];const re=ne;let J;e[21]===Symbol.for("react.memo_cache_sentinel")?(J=Q=>{r(Q),B(!1),E("")},e[21]=J):J=e[21];const we=J;let K;e[22]!==f||e[23]!==p||e[24]!==R||e[25]!==F?(K=()=>{F&&(R==="merge"?f(F):p(F))},e[22]=f,e[23]=p,e[24]=R,e[25]=F,e[26]=K):K=e[26];const de=K;let ke;e[27]!==S||e[28]!==k?(ke=()=>{S||(r(null),P("merge"),E(""),k(!1))},e[27]=S,e[28]=k,e[29]=ke):ke=e[29];const ye=ke,me=()=>{S&&!X||(X&&M?.(),r(null),P("merge"),E(""),k(!1))};let xe,Ve;e[30]!==Y?(xe=()=>{Y||E("")},Ve=[Y],e[30]=Y,e[31]=xe,e[32]=Ve):(xe=e[31],Ve=e[32]),l.useEffect(xe,Ve);let Re,ue;e[33]!==C||e[34]!==q||e[35]!==F?(Re=()=>{C==="dialog"||F||r(q())},ue=[C,q,F],e[33]=C,e[34]=q,e[35]=F,e[36]=Re,e[37]=ue):(Re=e[36],ue=e[37]),l.useEffect(Re,ue);const je=S?t.jsxs("div",{className:"space-y-3",children:[t.jsx("div",{ref:U,className:"rounded-lg border border-border bg-muted/30 p-3 max-h-48 overflow-y-auto",children:t.jsx("div",{className:"space-y-2",children:z.map(Ei)})}),X?C==="dialog"?t.jsx(Es,{children:t.jsx(W,{variant:"default",size:"sm",onClick:me,children:y(H?"gitView.common.close":"gitView.common.done")})}):t.jsx("div",{className:"flex justify-end",children:t.jsx(W,{variant:"default",size:"sm",onClick:me,children:y(H?"gitView.common.close":"gitView.common.done")})}):null]}):t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"space-y-3",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:y("gitView.branch.operation")}),t.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>P("merge"),className:Se("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",R==="merge"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(T,{name:"git-merge",className:Se("size-4",R==="merge"?"text-primary":"text-muted-foreground")}),t.jsx("span",{className:Se("typography-ui-label",R==="merge"?"text-foreground":"text-muted-foreground"),children:y("gitView.operation.merge")})]}),t.jsx("p",{className:"typography-micro text-muted-foreground",children:y("gitView.branch.mergeDescription")})]}),t.jsxs("button",{type:"button",onClick:()=>P("rebase"),className:Se("flex flex-col items-start gap-1 rounded-lg border p-3 text-left transition-colors",R==="rebase"?"border-primary bg-primary/5":"border-border hover:border-border/80 hover:bg-muted/50"),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(T,{name:"git-branch",className:Se("size-4",R==="rebase"?"text-primary":"text-muted-foreground")}),t.jsx("span",{className:Se("typography-ui-label",R==="rebase"?"text-foreground":"text-muted-foreground"),children:y("gitView.operation.rebase")})]}),t.jsx("p",{className:"typography-micro text-muted-foreground",children:y("gitView.branch.rebaseDescription")})]})]})]}),t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:R==="merge"?y("gitView.branch.branchToMergeInto",{branch:$}):y("gitView.branch.branchToRebaseOnto")}),t.jsxs(Ts,{open:Y,onOpenChange:B,modal:!1,children:[t.jsx(As,{asChild:!0,children:t.jsxs("button",{type:"button",className:Se(Fr({size:"default"}),"w-full"),children:[t.jsx("span",{className:Se("truncate",!F&&"text-muted-foreground"),children:F||y("gitView.branch.selectBranch")}),t.jsx(T,{name:"arrow-down-s",className:"size-4 opacity-60 shrink-0"})]})}),t.jsx(Ls,{align:"start",sideOffset:6,className:"w-[var(--anchor-width)] p-0 max-h-[min(var(--available-height),24rem)] flex flex-col overflow-hidden",children:t.jsxs(Os,{className:"h-full min-h-0",shouldFilter:!1,children:[t.jsx(zs,{ref:se,placeholder:y("gitView.branch.searchPlaceholder"),value:u,onValueChange:E,onKeyDown:Ti}),t.jsxs(Gs,{className:"h-full min-h-0",disableHorizontal:!0,children:[t.jsx(_s,{children:y("gitView.branch.empty")}),h.length>0&&t.jsx(Xt,{heading:y("gitView.branch.localBranches"),children:h.map(Q=>t.jsx(Zt,{onSelect:()=>we(Q),children:t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Q})},`local-${Q}`))}),h.length>0&&I.length>0?t.jsx(ha,{}):null,I.length>0&&t.jsx(Xt,{heading:y("gitView.branch.remoteBranches"),children:I.map(Q=>t.jsx(Zt,{onSelect:()=>we(Q),children:t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:Q})},`remote-${Q}`))})]})]})})]})]}),F?t.jsx("div",{className:"rounded-lg bg-muted/50 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:R==="merge"?t.jsxs(t.Fragment,{children:[y("gitView.branch.summaryMergePrefix")," ",t.jsx("span",{className:"font-mono text-foreground",children:F})," ",y("gitView.branch.summaryMergeInfix")," ",t.jsx("span",{className:"font-mono text-foreground",children:$})]}):t.jsxs(t.Fragment,{children:[y("gitView.branch.summaryRebasePrefix")," ",t.jsx("span",{className:"font-mono text-foreground",children:$})," ",y("gitView.branch.summaryRebaseInfix")," ",t.jsx("span",{className:"font-mono text-foreground",children:F})]})})}):null,C==="dialog"?t.jsxs(Es,{className:"gap-2 pt-1",children:[t.jsx(W,{variant:"ghost",size:"sm",onClick:ye,children:y("gitView.common.cancel")}),t.jsx(W,{variant:"default",size:"sm",onClick:de,disabled:!F,className:"gap-1.5",children:R==="merge"?t.jsxs(t.Fragment,{children:[t.jsx(T,{name:"git-merge",className:"size-4"}),y("gitView.operation.merge")]}):t.jsxs(t.Fragment,{children:[t.jsx(T,{name:"git-branch",className:"size-4"}),y("gitView.operation.rebase")]})})]}):t.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[t.jsx(W,{variant:"destructive",size:"sm",onClick:ye,disabled:G,children:y("gitView.common.reset")}),t.jsx("div",{className:"flex-1"}),t.jsx(W,{variant:"default",size:"sm",onClick:de,disabled:G||!F,children:y(R==="merge"?"gitView.operation.merge":"gitView.operation.rebase")})]})]});if(C==="bare")return je;if(C==="inline"){let Q;e[38]!==y?(Q=y("gitView.branch.updateTitle"),e[38]=y,e[39]=Q):Q=e[39];let fe;e[40]!==Q?(fe=t.jsx("div",{className:"typography-ui-header font-semibold text-foreground",children:Q}),e[40]=Q,e[41]=fe):fe=e[41];let Le;e[42]!==y?(Le=y("gitView.branch.updateDescriptionPrefix"),e[42]=y,e[43]=Le):Le=e[43];let et;e[44]!==$?(et=t.jsx("span",{className:"font-mono text-foreground",children:$}),e[44]=$,e[45]=et):et=e[45];let He;e[46]!==Le||e[47]!==et?(He=t.jsxs("div",{className:"typography-micro text-muted-foreground",children:[Le," ",et,"."]}),e[46]=Le,e[47]=et,e[48]=He):He=e[48];let Ke;e[49]!==fe||e[50]!==He?(Ke=t.jsx("header",{className:"border-b border-border/40 px-0 py-3",children:t.jsxs("div",{className:"space-y-1",children:[fe,He]})}),e[49]=fe,e[50]=He,e[51]=Ke):Ke=e[51];let We;e[52]!==je?(We=t.jsx("div",{className:"pt-3",children:je}),e[52]=je,e[53]=We):We=e[53];let pt;return e[54]!==Ke||e[55]!==We?(pt=t.jsxs("section",{className:"border-0 bg-transparent rounded-none",children:[Ke,We]}),e[54]=Ke,e[55]=We,e[56]=pt):pt=e[56],pt}let be;e[57]!==S?(be=S?t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(T,{name:"git-merge",className:"size-4"}),e[57]=S,e[58]=be):be=e[58];let Ce;e[59]!==y?(Ce=y("gitView.branch.mergeRebase"),e[59]=y,e[60]=Ce):Ce=e[60];let Ee;e[61]!==Ce?(Ee=t.jsx("span",{children:Ce}),e[61]=Ce,e[62]=Ee):Ee=e[62];let ee;e[63]!==re||e[64]!==G||e[65]!==be||e[66]!==Ee?(ee=t.jsx(ts,{asChild:!0,children:t.jsxs(W,{variant:"outline",size:"sm",className:"gap-1.5",onClick:re,disabled:G,children:[be,Ee]})}),e[63]=re,e[64]=G,e[65]=be,e[66]=Ee,e[67]=ee):ee=e[67];let he;e[68]!==y?(he=y("gitView.branch.mergeRebaseTooltip"),e[68]=y,e[69]=he):he=e[69];let Be;e[70]!==he?(Be=t.jsx(ss,{sideOffset:8,children:he}),e[70]=he,e[71]=Be):Be=e[71];let ge;e[72]!==ee||e[73]!==Be?(ge=t.jsxs(es,{children:[ee,Be]}),e[72]=ee,e[73]=Be,e[74]=ge):ge=e[74];let Ne;e[75]!==me||e[76]!==k?(Ne=Q=>{Q?k(!0):me()},e[75]=me,e[76]=k,e[77]=Ne):Ne=e[77];let Ie;e[78]!==y?(Ie=y("gitView.branch.updateTitle"),e[78]=y,e[79]=Ie):Ie=e[79];let Te;e[80]!==Ie?(Te=t.jsx(ft,{children:Ie}),e[80]=Ie,e[81]=Te):Te=e[81];let oe;e[82]!==H||e[83]!==S||e[84]!==R||e[85]!==X||e[86]!==y||e[87]!==$?(oe=S?y(X?H?"gitView.branch.operationFailed":"gitView.branch.operationCompleted":R==="merge"?"gitView.branch.mergingInProgress":"gitView.branch.rebasingInProgress"):t.jsxs(t.Fragment,{children:[y("gitView.branch.dialogDescriptionPrefix")," ",t.jsx("span",{className:"font-mono text-foreground",children:$}),"."]}),e[82]=H,e[83]=S,e[84]=R,e[85]=X,e[86]=y,e[87]=$,e[88]=oe):oe=e[88];let Pe;e[89]!==oe?(Pe=t.jsx(bt,{children:oe}),e[89]=oe,e[90]=Pe):Pe=e[90];let Fe;e[91]!==Te||e[92]!==Pe?(Fe=t.jsxs(gt,{children:[Te,Pe]}),e[91]=Te,e[92]=Pe,e[93]=Fe):Fe=e[93];let De;e[94]!==je||e[95]!==Fe?(De=t.jsxs(ht,{className:"max-w-md",children:[Fe,je]}),e[94]=je,e[95]=Fe,e[96]=De):De=e[96];let Ue;e[97]!==D||e[98]!==Ne||e[99]!==De?(Ue=t.jsx(mt,{open:D,onOpenChange:Ne,children:De}),e[97]=D,e[98]=Ne,e[99]=De,e[100]=Ue):Ue=e[100];let Ae;return e[101]!==ge||e[102]!==Ue?(Ae=t.jsxs(t.Fragment,{children:[ge,Ue]}),e[101]=ge,e[102]=Ue,e[103]=Ae):Ae=e[103],Ae};function Fi(o){return o.status==="done"||o.status==="error"}function Ri(o){return o.status==="error"}function Bi(o){return o.slice(o.indexOf("/")+1)}function Di(o){return[o]}function Mi(o){return[o]}function Ei(o,e){return t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsxs("div",{className:"mt-0.5 shrink-0",children:[o.status==="running"&&t.jsx(T,{name:"loader-4",className:"size-3.5 animate-spin text-primary"}),o.status==="done"&&t.jsx(T,{name:"check",className:"size-3.5 text-success"}),o.status==="error"&&t.jsx(T,{name:"close",className:"size-3.5 text-destructive"}),o.status==="pending"&&t.jsx("div",{className:"size-3.5 rounded-full border border-muted-foreground/30"})]}),t.jsx("span",{className:Se("typography-micro",o.status==="error"&&"text-destructive",o.status==="done"&&"text-muted-foreground",o.status==="running"&&"text-foreground",o.status==="pending"&&"text-muted-foreground/60"),children:o.message})]},e)}function Ti(o){return o.stopPropagation()}const Ai=({runMutation:o,onMutationComplete:e,onMutationError:a,onPathsComplete:m,scheduleFlush:N})=>{const f=[];let p=!1;return{enqueue:g=>{const w=f[f.length-1];if(w?.directory===g.directory&&w.direction===g.direction){g.paths.forEach(M=>w.paths.add(M));return}f.push(g)},flush:()=>{if(p)return;const g=f.shift();if(!g)return;p=!0;const w={directory:g.directory,direction:g.direction,paths:Array.from(g.paths),rollback:g.rollback};(async()=>{try{await o(w),e(w)}catch(M){a(w,M)}finally{m(w.paths),p=!1,f.length>0&&N()}})()},clear:()=>{f.length=0},size:()=>f.length,isRunning:()=>p}},Li=15e3,Oi=40,zi=20,Vr={feat:":sparkles:",feature:":sparkles:",fix:":bug:",bug:":bug:",hotfix:":ambulance:",docs:":memo:",documentation:":memo:",style:":lipstick:",refactor:":recycle:",perf:":zap:",performance:":zap:",test:":white_check_mark:",tests:":white_check_mark:",build:":construction_worker:",ci:":green_heart:",chore:":wrench:",revert:":rewind:",wip:":construction:",security:":lock:",release:":bookmark:",merge:":twisted_rightwards_arrows:",mv:":truck:",move:":truck:",rename:":truck:",remove:":fire:",delete:":fire:",add:":sparkles:",create:":sparkles:",implement:":sparkles:",update:":recycle:",improve:":zap:",optimize:":zap:",upgrade:":arrow_up:",downgrade:":arrow_down:",deploy:":rocket:",init:":tada:",initial:":tada:"},Ir=(o,e)=>{const a=o.toLowerCase(),m=/^([a-z]+)(?:\(.*\))?!?:/,N=a.match(m);if(N){const x=N[1],g=Vr[x];if(g)return e.find(w=>w.code===g)||null}const f=a.split(" ")[0],p=Vr[f];return p&&e.find(x=>x.code===p)||null},Gi=20,yt=new Map,_i=(o,e)=>{if(yt.delete(o),yt.set(o,e),yt.size>Gi){const a=yt.keys().next().value;a!==void 0&&yt.delete(a)}},Ze=o=>(o||"").replace(/\\/g,"/").replace(/\/+$/,""),Pr=o=>{const e=o.index?.trim();return!!(e&&e!=="?")},$i=o=>{const e=o.working_dir?.trim(),a=o.index?.trim();return!!(e||a==="?")},ic=({isActive:o})=>{const{t:e}=nt(),{git:a}=ga(),m=fa(),[N,f]=l.useState(null),[p,x]=l.useState(null),g=rt(s=>s.currentSessionId),w=rt(s=>s.newSessionDraft),M=rt(s=>s.setDraftBootstrapPendingDirectory),v=rt(s=>s.worktreeMetadata),V=rt(s=>s.availableWorktrees),A=Ze(m),S=l.useMemo(()=>{if(!A)return;const s=V.find(n=>Ze(n.path)===A);if(s)return s;for(const n of v.values())if(Ze(n.path)===A)return n},[V,A,v]),z=l.useMemo(()=>{if(g)return v.get(g)??S;if(w?.open)return S},[g,S,w?.open,v]),{profiles:C,globalIdentity:y,defaultGitIdentityId:D,loadProfiles:k,loadGlobalIdentity:R,loadDefaultGitIdentityId:P}=_a(pr(s=>({profiles:s.profiles,globalIdentity:s.globalIdentity,defaultGitIdentityId:s.defaultGitIdentityId,loadProfiles:s.loadProfiles,loadGlobalIdentity:s.loadGlobalIdentity,loadDefaultGitIdentityId:s.loadDefaultGitIdentityId}))),{rootIsGitRepo:F,gitDirectory:r,nestedRepos:Y}=pa(m??null,{enabled:o}),B=xa(r??null),u=wa(r??null),E=ya(s=>g?s.getAttachment(g):void 0),se=E?ba(E):[],U=E&&!E.degraded&&!E.legacy?E.worktreeRoot??void 0:void 0,G=Ta(m,z,u?.current??void 0),$=va(r??null),X=ja(r??null),H=Ca(r??null),le=Na(r??null),ae=Sa(r??null),{setActiveDirectory:ce,ensureAll:ie,fetchStatus:h,fetchBranches:d,fetchLog:I,setLogMaxCount:L,fetchIdentity:q,prefetchDiffs:ne,clearDiffCache:re,moveStatusPathsOptimistically:J,restoreStatus:we,bumpIndexRevision:K,ensureNestedRepos:de,selectNestedRepo:ke}=ka(pr(s=>({setActiveDirectory:s.setActiveDirectory,ensureAll:s.ensureAll,fetchStatus:s.fetchStatus,fetchBranches:s.fetchBranches,fetchLog:s.fetchLog,setLogMaxCount:s.setLogMaxCount,fetchIdentity:s.fetchIdentity,prefetchDiffs:s.prefetchDiffs,clearDiffCache:s.clearDiffCache,moveStatusPathsOptimistically:s.moveStatusPathsOptimistically,restoreStatus:s.restoreStatus,bumpIndexRevision:s.bumpIndexRevision,ensureNestedRepos:s.ensureNestedRepos,selectNestedRepo:s.selectNestedRepo}))),ye=Rt(s=>s.isMobile),me=Rt(s=>s.openContextDiff),xe=Rt(s=>s.openContextSurface),Ve=u?.current??null,Re=Va(s=>!r||!Ve?null:Ia(s.entries,r,Ve)),ue=Rt(s=>s.navigateToDiff),$e=l.useRef(null),Oe=l.useRef(null),je=l.useRef(null),be=l.useRef(!0);l.useEffect(()=>()=>{be.current=!1},[]);const Ce=l.useCallback(()=>{$e.current!==null&&(window.clearTimeout($e.current),$e.current=null)},[]),Ee=l.useCallback(s=>{Ce(),$e.current=window.setTimeout(()=>{$e.current=null,Ze(s)===Ze(r)&&h(s,a,{silent:!0})},Li)},[Ce,r,h,a]);l.useEffect(()=>Ce,[Ce]);const ee=l.useCallback(()=>{Oe.current!==null&&(window.clearTimeout(Oe.current),Oe.current=null)},[]),he=l.useCallback(()=>{Oe.current===null&&(Oe.current=window.setTimeout(()=>{Oe.current=null,je.current?.()},0))},[]),Be=l.useCallback(async(s,n,i)=>{if(n==="stage"){if(a.stageGitFiles){await a.stageGitFiles(s,i);return}await Promise.all(i.map(c=>a.stageGitFile(s,c)));return}if(a.unstageGitFiles){await a.unstageGitFiles(s,i);return}await Promise.all(i.map(c=>a.unstageGitFile(s,c)))},[a]),ge=l.useMemo(()=>Ai({runMutation:({directory:s,direction:n,paths:i})=>Be(s,n,i),onMutationComplete:({directory:s})=>{K(s),Ee(s)},onMutationError:({directory:s,direction:n,rollback:i},c)=>{i?.(),K(s),Ee(s);const j=e(n==="stage"?"gitView.toast.stageFileFailed":"gitView.toast.unstageFileFailed");b.error(c instanceof Error?c.message:j)},onPathsComplete:s=>{qs(n=>{const i=new Set(n);return s.forEach(c=>i.delete(c)),i})},scheduleFlush:he}),[K,Be,he,Ee,e]);l.useEffect(()=>(je.current=ge.flush,()=>{je.current=null}),[ge]),l.useEffect(()=>()=>ge.clear(),[ge]),l.useEffect(()=>ee,[ee]),l.useEffect(()=>{if(!o)return;if(!m){f(null);return}const s=Ze(m)??m;f({directory:s,status:null});let n=!1,i=null;const c=async()=>{try{const j=await Ea(m);if(n)return;f({directory:s,status:j.status}),j.status==="pending"&&(i=window.setTimeout(()=>{c()},500))}catch{n||f({directory:s,status:null})}};return c(),()=>{n=!0,i!==null&&window.clearTimeout(i)}},[o,m]);const Ne=Ze(w?.bootstrapPendingDirectory??null),Ie=!!(m&&Ne&&Ne===Ze(m)),Te=Pa(m??null),oe=Ze(m),Pe=N?.directory===oe?N.status:null,Fe=!!(m&&(Te||Pe==="pending"||Ie&&w?.pendingWorktreeRequestId)),De=!!(oe&&p?.directory===oe);l.useEffect(()=>{if(!oe)return;if(Pe==="failed"){M(null),x(n=>n?.directory===oe?null:n);return}if(Fe){x(n=>n?.directory===oe&&n.status==="refreshing"?n:{directory:oe,status:"refreshing"});return}if(p?.directory!==oe||p.status!=="refreshing"||!r||!a)return;let s=!1;return h(r,a,{force:!0,silent:!0,throwOnError:!0}).then(()=>{s||x(n=>n?.directory===oe?null:n)}).catch(()=>{s||x(n=>n?.directory===oe?{...n,status:"failed"}:n)}),()=>{s=!0}},[h,a,r,Fe,oe,Pe,p,M]);const Ue=Fe||De,Ae=De&&p?.status==="failed",Q=l.useMemo(()=>r?yt.get(r)??null:null,[r]),fe=Fa(s=>s.settingsGitmojiEnabled),[Le,et]=l.useState(null),{gitmojis:He}=Za(fe);l.useEffect(()=>{const s=U||G?.projectDirectory;if(!s){et(null);return}let n=!1;return Ra(s).then(i=>{if(n)return;const c=i.trim();et(c&&c!=="HEAD"?c:null)}).catch(()=>{n||et(null)}),()=>{n=!0}},[U,G?.projectDirectory]);const[Ke,We]=l.useState(Q?.commitMessage??""),[pt,Er]=l.useState([]),[Tr,rs]=l.useState(!1),$s=l.useRef(null),[Hs,Mt]=l.useState(null),[Ar,ns]=l.useState(!1),[Ws,Us]=l.useState(null),[Ye,Lr]=l.useState(25),[Or,Ks]=l.useState(!1),{triggerFireworks:zr}=Aa(),Js=l.useRef(new Map),Et=l.useRef(0),as=l.useCallback(()=>{Et.current+=1,be.current&&Ks(!0)},[]),is=l.useCallback(()=>{Et.current=Math.max(0,Et.current-1),be.current&&Et.current===0&&Ks(!1)},[]),[os,Tt]=l.useState(new Set),[Gr,qs]=l.useState(new Set),[ls,Ys]=l.useState(!1),[_r,$r]=l.useState(0),[Hr,Qs]=l.useState(!1),[cs,ds]=l.useState(Q?.generatedHighlights??[]),Wr=Gr.size>0||ge.size()>0||ge.isRunning(),Xs=l.useCallback(()=>{const s=$s.current;s&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{s.scrollTo({top:s.scrollHeight,behavior:"smooth"})})})},[]),us=U||G?.projectDirectory||null,ms=u?.current||null,Ur=l.useMemo(()=>{const s=u?.tracking;return s?s.startsWith("origin/"):!0},[u?.tracking]),Zs=l.useMemo(()=>{const s=G?.createdFromBranch,n=typeof s=="string"?s.trim():"",i=typeof u?.current=="string"?u.current.trim():"",c=typeof Le=="string"?Le.trim():"";return n?n===i&&n.startsWith("opencode/")&&c.length>0&&c!==n?c:n:c||i||"HEAD"},[G?.createdFromBranch,u,Le]),At=l.useCallback(()=>{ds([])},[]),[hs,Kr]=l.useState(new Set),[Lt,Jr]=l.useState(new Map),[Ot,gs]=l.useState(new Set),fs=l.useRef(Lt),St=l.useRef(Ot),[qr,vt]=l.useState(null),[xt,ps]=l.useState(null),[er,tr]=l.useState(""),[Me,zt]=l.useState(null),[Yr,sr]=l.useState(!1),[Qr,rr]=l.useState(!1),[xs,ws]=l.useState([]),[Xr,nr]=l.useState(null),[ar,ys]=l.useState(null),[Zr,Gt]=l.useState([]),[en,Qe]=l.useState(!1),[tn,tt]=l.useState([]),[_t,st]=l.useState("merge"),[sn,bs]=l.useState(null),[vs,ir]=l.useState(!1),[js,rn]=l.useState(100),[nn,an]=l.useState(0),Xe=l.useMemo(()=>g?`openchamber.conflict:${g}`:null,[g]),at=l.useCallback((s,n,i)=>{if(!Xe||typeof window>"u")return;const c={directory:s,conflictFiles:n,operation:i};window.localStorage.setItem(Xe,JSON.stringify(c))},[Xe]),Je=l.useCallback(()=>{!Xe||typeof window>"u"||window.localStorage.removeItem(Xe)},[Xe]);l.useEffect(()=>{if(!Xe||typeof window>"u"||!r)return;const s=window.localStorage.getItem(Xe);if(s)try{const n=JSON.parse(s);if(n.directory!==r){window.localStorage.removeItem(Xe);return}tt(n.conflictFiles??[]),st(n.operation??"merge"),Qe(!0)}catch{window.localStorage.removeItem(Xe)}},[Xe,r]);const[on,Cs]=l.useState(!1),[$t,kt]=l.useState(null),[Ns,or]=l.useState("merge"),[Ss,lr]=l.useState(""),ln=l.useCallback(s=>{Ba(s).then(n=>{if(n.ok){b.success(e("gitView.toast.commitHashCopied"));return}b.error(e("gitView.toast.copyFailed"))})},[e]),cn=l.useCallback(s=>{Kr(n=>{const i=new Set(n);return i.has(s)?i.delete(s):i.add(s),i})},[]);l.useEffect(()=>{fs.current=Lt},[Lt]),l.useEffect(()=>{St.current=Ot},[Ot]),l.useEffect(()=>{if(!r||!a)return;const s=Array.from(hs).filter(i=>!fs.current.has(i)&&!St.current.has(i));if(s.length===0)return;let n=!1;return gs(i=>{const c=new Set(i);for(const j of s)c.add(j);return St.current=c,c}),Promise.all(s.map(i=>a.getCommitFiles(r,i).then(c=>({hash:i,files:c.files})).catch(c=>(console.error("Failed to fetch commit files:",c),{hash:i,files:[]})))).then(i=>{n||(Jr(c=>{const j=new Map(c);for(const{hash:O,files:Z}of i)j.set(O,Z);return fs.current=j,j}),gs(c=>{const j=new Set(c);for(const{hash:O}of i)j.delete(O);return St.current=j,j}))}),()=>{n=!0,gs(i=>{let c=!1;const j=new Set(i);for(const O of s)j.delete(O)&&(c=!0);return c?(St.current=j,j):i})}},[hs,r,a]),l.useEffect(()=>{if(!r)return;const s=yt.get(r)??null;We(s?.commitMessage??""),ds(s?.generatedHighlights??[])},[r]),l.useEffect(()=>{r&&_i(r,{directory:r,commitMessage:Ke,generatedHighlights:cs})},[Ke,r,cs]),l.useEffect(()=>{o&&(k(),R(),P())},[o,k,R,P]),l.useEffect(()=>{if(!o)return;if(!r||!a?.getRemoteUrl||B!==!0){ps(null);return}let s=!1;return a.getRemoteUrl(r).then(n=>{s||ps(n)}).catch(()=>{s||ps(null)}),()=>{s=!0}},[o,r,a,B]);const Ht=l.useCallback(async()=>{if(!r||!a?.getRemotes||B!==!0){ws([]);return}try{const s=await a.getRemotes(r);be.current&&ws(s)}catch{be.current&&ws([])}},[r,a,B]);l.useEffect(()=>{o&&Ht()},[o,Ht]),l.useEffect(()=>{o&&m&&r&&(ce(m),ie(r,a))},[o,m,r,ce,ie,a]),l.useEffect(()=>{if(o&&r)return Da.onGitRefreshHint(s=>{Ze(s.directory)===Ze(r)&&(s.paths?.length&&re(r,s.paths),h(r,a,{silent:!0}))})},[o,re,r,h,a]);const te=l.useCallback(async(s=!0)=>{if(r)try{await Promise.all([h(r,a),d(r,a)])}catch(n){if(s){const i=n instanceof Error?n.message:e("gitView.toast.refreshRepositoryFailed");b.error(i)}}},[r,a,h,d,e]),pe=l.useCallback(async()=>{r&&await I(r,a,Ye)},[r,a,I,Ye]),ks=l.useCallback(async()=>{r&&await q(r,a)},[r,a,q]);l.useEffect(()=>{if(!o||!r||!a?.hasLocalIdentity||B!==!0)return;const s=typeof D=="string"?D.trim():"";if(!s||s==="global"||Js.current.get(r)===s)return;let i=!1;return(async()=>{try{const j=await a.hasLocalIdentity?.(r);if(i||j===!0)return;as(),await a.setGitIdentity(r,s),Js.current.set(r,s),await ks()}catch(j){console.warn("Failed to auto-apply default git identity:",j)}finally{i||is()}})(),()=>{i=!0}},[o,as,r,D,is,a,B,ks]);const it=l.useMemo(()=>u?[...u.files??[]].sort((n,i)=>n.path.localeCompare(i.path)):[],[u]),qe=l.useMemo(()=>it.filter(Pr),[it]),Vs=l.useMemo(()=>it.filter($i),[it]);l.useEffect(()=>{if(!r||it.length===0)return;const s=[],n=new Set,i=j=>{!j||n.has(j)||(n.add(j),s.push(j))};if(qe.forEach(j=>i(j.path)),pt.forEach(i),it.slice(0,zi).forEach(j=>i(j.path)),s.length===0)return;const c=window.setTimeout(()=>{ne(r,a,s,{maxFiles:Oi})},120);return()=>{window.clearTimeout(c)}},[it,r,a,ne,qe,pt]);const cr=s=>s?.pushed[0]?.remote||u?.tracking?.split("/")[0]||ze.find(n=>n.name==="origin")?.name||ze[0]?.name||"origin",dr=async(s,n)=>{if(r){Mt(s);try{const i=c=>{const j=`${c.name}/`,O=u?.tracking?.startsWith(j)?u.tracking.slice(j.length):void 0;return{remote:c.name,branch:O,rebase:!0}};if(s==="fetch"){if(!n)throw new Error("No remote available for fetch");await a.gitFetch(r,{remote:n.name}),b.success(e("gitView.toast.fetchedFromRemote",{name:n.name}))}else if(s==="pull"){if(!n)throw new Error("No remote available for pull");const c=await a.gitPull(r,i(n));b.success(c.files.length===1?e("gitView.toast.pulledFilesSingle",{count:c.files.length,name:n.name}):e("gitView.toast.pulledFilesPlural",{count:c.files.length,name:n.name}))}else if(s==="push"){const c=await a.gitPush(r);b.success(e("gitView.toast.pushedToUpstream",{name:cr(c)}))}else if(s==="sync"){if(!n)throw new Error("No remote available for sync");let c=0,j=!1;await a.gitFetch(r,{remote:n.name});const O=await a.getGitStatus(r);if((O.behind??0)>0){if((O.files?.length??0)>0){b.error(e("gitView.toast.commitOrStashBeforeSync"));return}c=(await a.gitPull(r,i(n))).files.length}((await a.getGitStatus(r)).ahead??0)>0&&(await a.gitPush(r),j=!0),c>0&&j?b.success(c===1?e("gitView.toast.syncedPulledSingleAndPushed",{count:c,name:n.name}):e("gitView.toast.syncedPulledPluralAndPushed",{count:c,name:n.name})):c>0?b.success(c===1?e("gitView.toast.pulledFilesSingle",{count:c,name:n.name}):e("gitView.toast.pulledFilesPlural",{count:c,name:n.name})):j?b.success(e("gitView.toast.pushedToUpstream",{name:n.name})):b.success(e("gitView.toast.alreadyUpToDate"))}await te(!1),await pe()}catch(i){const c=i instanceof Error?i.message:e("gitView.toast.syncActionFailed",{action:s==="sync"?e("gitView.sync.syncChanges"):s==="pull"?e("gitView.sync.pull"):s});b.error(c)}finally{Mt(null)}}},dn=l.useCallback(async s=>{if(!r)return;const n=s.name.trim();if(!n){b.error(e("gitView.toast.remoteNameRequired"));return}if(n==="origin"){b.error(e("gitView.toast.cannotRemoveOriginRemote"));return}nr(n);try{await a.removeRemote(r,{remote:n}),b.success(e("gitView.toast.removedRemote",{name:n})),await Promise.all([te(!1),Ht()])}catch(i){const c=i instanceof Error?i.message:`Failed to remove ${n}`;b.error(c)}finally{nr(null)}},[r,a,Ht,te,e]),ur=async(s={})=>{if(!r)return;if(!Ke.trim()){b.error(e("gitView.toast.enterCommitMessage"));return}const n=qe.map(c=>c.path).sort();if(n.length===0){b.error(e("gitView.toast.stageFileToCommit"));return}const i=s.pushAfter?"commitAndPush":"commit";Us(i);try{if(await a.createGitCommit(r,Ke.trim(),{files:n,stageFiles:[]}),K(r),b.success(e("gitView.toast.commitCreated")),We(""),At(),await te(),s.pushAfter){const c=u?.tracking?.split("/")[0],j=ze.find(Gn=>Gn.name===c)??ze[0];if(!j)throw new Error(e("mobile.changes.noRemote"));Mt("sync");const O=`${j.name}/`,Z=u?.tracking?.startsWith(O)?u.tracking.slice(O.length):void 0;await a.gitFetch(r,{remote:j.name});const _=await a.getGitStatus(r);if((_.behind??0)>0){if((_.files?.length??0)>0){b.error(e("gitView.toast.commitOrStashBeforeSync")),await te(!1);return}await a.gitPull(r,{remote:j.name,branch:Z,rebase:!0})}const _e=await a.getGitStatus(r);let jt;(_e.ahead??0)>0&&(jt=await a.gitPush(r)),b.success(e("gitView.toast.pushedToUpstream",{name:cr(jt)})),zr(),await te(!1)}else await te(!1);await pe(),$r(c=>c+1)}catch(c){const j=c instanceof Error?c.message:e("gitView.toast.createCommitFailed");b.error(j)}finally{Us(null),s.pushAfter&&Mt(null)}},un=l.useCallback(async()=>{if(!r)return;const s=qe.map(n=>n.path).sort();if(s.length===0){b.error(e("gitView.toast.stageFileToDescribe"));return}console.error("[git-generation][browser] generate button clicked",{directory:r,selectedFiles:s.length}),Qs(!0);try{const{message:n}=await fr(r,s),i=n.subject?.trim()??"",c=Array.isArray(n.highlights)?n.highlights:[];if(i){let j=i;if(fe&&He.length>0){const O=Ir(i,He);if(O){const{code:Z,emoji:_}=O;!i.startsWith(Z)&&!i.startsWith(_)&&(j=`${Z} ${i}`)}}We(j)}ds(c),Xs()}catch(n){console.error("[git-generation][browser] GitView generate handler failed",{message:n instanceof Error?n.message:String(n),error:n});const i=n instanceof Error?n.message:e("gitView.toast.generateCommitMessageFailed");b.error(i)}finally{Qs(!1)}},[r,qe,fe,He,Xs,e]),Is=s=>s.reason==="attention"?`${s.attentionReason} in progress`:s.reason==="missing"?"worktree is missing":"worktree is invalid",mn=async(s,n)=>{if(!r||!u)return;const i=Bs(E);if(i.length>0){b.error(e("gitView.toast.cannotCreateBranch",{reason:Is(i[0])}));return}const c=u.current??null,j=n?.name??"origin";try{await a.createBranch(r,s,c??"HEAD"),b.success(e("gitView.toast.createdBranch",{name:s})),await a.checkoutBranch(r,s);let O=!1;try{await a.gitPush(r,{remote:j,branch:s,options:["--set-upstream"]}),O=!0}catch(Z){const _=Z instanceof Error?Z.message:`Unable to push new branch to ${j}.`;b.warning(e("gitView.toast.branchCreatedLocally"),{description:t.jsxs("span",{className:"text-foreground/80 dark:text-foreground/70",children:["Upstream setup failed: ",_]})})}await te(),await pe(),O&&b.success(e("gitView.toast.upstreamSet",{branch:s,remote:j}))}catch(O){const Z=O instanceof Error?O.message:e("gitView.toast.createBranchFailed");throw b.error(Z),O}},hn=async(s,n)=>{if(!r)return;const i=Bs(E);if(i.length>0){b.error(e("gitView.toast.cannotRenameBranch",{reason:Is(i[0])}));return}try{await a.renameBranch(r,s,n),b.success(e("gitView.toast.renamedBranch",{oldName:s,newName:n})),await te(),await pe()}catch(c){const j=c instanceof Error?c.message:e("gitView.toast.renameBranchFailed",{oldName:s,newName:n});b.error(j)}},gn=async s=>{if(!r)return;const n=Bs(E);if(n.length>0){b.error(e("gitView.toast.cannotCheckout",{reason:Is(n[0])}));return}const i=s.replace(/^remotes\//,"");if(u?.current!==i){if((u?.files?.length??0)>0){kt(i);return}await Ps(i)}},Ps=async s=>{if(!r)return;const n=s;try{const i=await a.checkoutBranch(r,n);b.success(e("gitView.toast.checkedOut",{name:i?.branch||n})),await te(),await pe()}catch(i){const c=i instanceof Error?i.message:e("gitView.toast.checkoutFailed",{name:n});b.error(c)}},fn=async s=>{if(r){as();try{await a.setGitIdentity(r,s.id),b.success(e("gitView.toast.appliedIdentity",{name:s.name})),await ks()}catch(n){const i=n instanceof Error?n.message:e("gitView.toast.applyIdentityFailed");b.error(i)}finally{is()}}},Vt=l.useMemo(()=>$?.all?$.all.filter(s=>!s.startsWith("remotes/")).sort():[],[$]),ot=l.useMemo(()=>$?.all?$.all.filter(s=>s.startsWith("remotes/")).map(s=>s.replace(/^remotes\//,"")).sort():[],[$]),ze=l.useMemo(()=>{if(xs.length>0)return xs;const s=new Set,n=u?.tracking?.trim();n&&n.includes("/")&&s.add(n.split("/")[0]);for(const i of ot){const c=i.indexOf("/");c>0&&s.add(i.slice(0,c))}return s.size===0&&xt&&s.add("origin"),Array.from(s).map(i=>({name:i,fetchUrl:xt??"",pushUrl:xt??""}))},[xs,ot,xt,u?.tracking]),lt=u?.current??null,mr=l.useMemo(()=>{const s=u?.tracking?.trim().split("/")[0];return(s&&$?.defaultBranches?.[s])??$?.defaultBranches?.origin},[$,u?.tracking]),wt=l.useMemo(()=>La({remoteNames:new Set(ze.map(s=>s.name)),localBranches:Vt,worktreeCreatedFromBranch:G?.createdFromBranch,rootBranchHint:Le,defaultBranch:mr,headBranch:lt}),[lt,mr,ze,Vt,Le,G?.createdFromBranch]),pn=l.useMemo(()=>ze.map(i=>i.name).map(i=>`${i}/${wt}`).find(i=>ot.includes(i))??wt,[wt,ze,ot]),xn=l.useMemo(()=>{const s=new Map;y&&s.set(y.id,y);let n=null;if(xt)try{let i=xt.trim();i.startsWith("git@")&&(i=`https://${i.slice(4).replace(":","/")}`),i.endsWith(".git")&&(i=i.slice(0,-4));const c=new URL(i);n=c.hostname+c.pathname}catch{}for(const i of C){if(i.authType!=="token"){s.set(i.id,i);continue}const c=i.host;if(!c){s.set(i.id,i);continue}if(!c.includes("/")){s.set(i.id,i);continue}n&&n===c&&s.set(i.id,i)}return Array.from(s.values())},[C,y,xt]),wn=l.useMemo(()=>{if(H?.userName&&H?.userEmail){const s=C.find(n=>n.userName===H.userName&&n.userEmail===H.userEmail);return s||(y&&y.userName===H.userName&&y.userEmail===H.userEmail?y:{id:"local-config",name:H.userName,userName:H.userName,userEmail:H.userEmail,sshKey:H.sshCommand?.replace("ssh -i ","")??null,color:"info",icon:"user"})}return y??null},[H,C,y]),yn=qe.length,bn=le||Hs!==null||Ws!==null,vn=!!(G&&us&&ms&&Ur),hr=!!lt,ct=vn&&us&&ms&&G?{repoRoot:us,sourceBranch:ms,worktreeMetadata:G}:null;l.useEffect(()=>{if(!r||!a||!X?.all?.length||!lt||!wt||lt===wt){vt(null);return}let s=!1;return(async()=>{try{const i=await a.getGitLog(r,{from:wt,to:"HEAD",maxCount:Ye});if(s)return;const c=new Set((i?.all??[]).map(O=>O.hash).filter(O=>typeof O=="string"&&O.length>0));if(c.size===0){vt(null);return}const j=X.all.findIndex(O=>!c.has(O.hash));if(j===0){vt(null);return}if(j===-1){vt({insertBeforeIndex:X.all.length,branchName:lt,direction:"up"});return}vt({insertBeforeIndex:j,branchName:lt,direction:"up"})}catch{s||vt(null)}})(),()=>{s=!0}},[wt,lt,r,a,X,Ye]),l.useEffect(()=>{bs(null)},[r]),l.useEffect(()=>{if(Me!=="graph"||!r){Me!=="graph"&&bs(null);return}let s=!1;return ir(!0),a.getGitLog(r,{maxCount:js,all:!0}).then(n=>{s||bs(n)}).catch(n=>{console.error("Failed to fetch graph log:",n)}).finally(()=>{s||ir(!1)}),()=>{s=!0}},[Me,r,js,nn,a]);const It=l.useCallback((s,n)=>{if(!r||s.length===0)return;const i=Array.from(new Set(s));qs(j=>{const O=new Set(j);return i.forEach(Z=>O.add(Z)),O});const c=J(r,i,n);ge.enqueue({directory:r,direction:n,paths:new Set(i),rollback:()=>we(r,c)}),he()},[r,ge,J,we,he]),Fs=l.useCallback(async s=>{if(r){Tt(n=>{const i=new Set(n);return i.add(s),i});try{await a.revertGitFile(r,s,{scope:"working"}),b.success(e("gitView.toast.revertedFile",{path:s})),await te(!1)}catch(n){const i=n instanceof Error?n.message:e("gitView.toast.revertFailed");b.error(i)}finally{Tt(n=>{const i=new Set(n);return i.delete(s),i})}}},[r,te,a,e]),Pt=l.useCallback(async(s,n,i="all")=>{if(!r||s.length===0)return;const c=Array.from(new Set(s));if(ls||c.some(_=>os.has(_)))return;const j=new Set(qe.map(_=>_.path)),O=i==="all"&&c.some(_=>j.has(_));n&&Ys(!0),Tt(_=>{const _e=new Set(_);return c.forEach(jt=>_e.add(jt)),_e});const Z=[];try{if(await Promise.all(c.map(async _=>{try{await a.revertGitFile(r,_,{scope:i})}catch(_e){Z.push({path:_,message:_e instanceof Error?_e.message:e("gitView.toast.revertFailed")})}})),O&&Z.length<c.length&&K(r),await te(!1),Z.length===0)b.success(c.length===1?e("gitView.toast.revertedFilesSingle",{count:c.length}):e("gitView.toast.revertedFilesPlural",{count:c.length}));else if(Z.length===c.length)b.error(Z[0]?.message||e("gitView.toast.revertFailed"));else{const _=c.length-Z.length;b.warning(_===1?e("gitView.toast.revertedSomeSingle",{success:_,failed:Z.length}):e("gitView.toast.revertedSomePlural",{success:_,failed:Z.length}))}}finally{Tt(_=>{const _e=new Set(_);return c.forEach(jt=>_e.delete(jt)),_e}),n&&Ys(!1)}},[K,r,a,ls,te,os,qe,e]),jn=l.useCallback(async s=>{await Pt(s,!0)},[Pt]),Cn=l.useCallback(async s=>{await Pt(s,!1,"working")},[Pt]),Rs=l.useCallback((s,n)=>{if(m&&!ye){me(m,s,n);return}ue(s,n)},[m,ye,ue,me]),Nn=l.useCallback(()=>ns(!0),[]),Sn=l.useMemo(()=>{const s=[];return qe.length>0&&s.push({id:"staged",title:e("gitView.changes.stagedTitle"),entries:qe,actionSymbol:"-",actionAllLabel:e("gitView.changes.unstageAllAria"),getActionLabel:n=>e("gitView.changes.unstageFileAria",{path:n}),onActionFile:n=>{It([n],"unstage")},onActionAll:n=>{It(n,"unstage")},onViewDiff:n=>Rs(n,!0),onRevertFile:Fs,showRevertActions:!1,accent:!0}),Vs.length>0&&s.push({id:"unstaged",title:e("gitView.changes.title"),entries:Vs,actionSymbol:"+",actionAllLabel:e("gitView.changes.stageAllAria"),getActionLabel:n=>e("gitView.changes.stageFileAria",{path:n}),onActionFile:n=>{It([n],"stage")},onActionAll:n=>{It(n,"stage")},onViewDiff:n=>Rs(n,!1),onRevertFile:Fs}),s},[Fs,Rs,It,qe,e,Vs]),kn=l.useCallback(s=>{if(s.length===0)return;const n=s.map(i=>i.trim()).filter(Boolean);if(n.length===0){At();return}We(i=>{const c=i.trim(),j=c.length>0?`
4
+
5
+ `:"";return`${c}${j}${n.join(`
6
+ `)}`.trim()}),At()},[At]),Vn=l.useCallback((s,n)=>{const i=n||s;We(c=>{const j=c.trimStart();return j.startsWith(s)||n&&j.startsWith(n)?c:`${i.endsWith(" ")?i:`${i} `}${c}`.trimStart()}),tr(""),rs(!1)},[]),Wt=l.useCallback(s=>{const n=s instanceof Error?s.message.toLowerCase():"";return n.includes("uncommitted changes")||n.includes("local changes")||n.includes("your local changes would be overwritten")||n.includes("please commit your changes or stash them")||n.includes("cannot rebase: you have unstaged changes")||n.includes("error: cannot pull with rebase")},[]),dt=l.useCallback((s,n)=>{Gt(i=>[...i,{message:s,status:n,timestamp:Date.now()}])},[]),Ge=l.useCallback((s,n)=>{Gt(i=>{if(i.length===0)return i;const c=[...i];return c[c.length-1]={...c[c.length-1],status:s,...n?{message:n}:{}},c})},[]),Ut=l.useCallback(()=>{Gt([])},[]),In=l.useCallback(()=>{Gt([]),ys(null)},[]),Kt=l.useCallback(s=>{const n=s.trim(),i=new Set(ze.map(j=>j.name)),c=n.indexOf("/");if(c>0){const j=n.slice(0,c),O=n.slice(c+1);if(i.has(j)&&O)return{branch:n,remote:j,remoteBranch:O}}for(const j of ze){const O=`${j.name}/${n}`;if(ot.includes(O))return{branch:O,remote:j.name,remoteBranch:n}}return{branch:n,remote:null,remoteBranch:null}},[ze,ot]),Pn=l.useCallback(async s=>{if(!r)return;ys("merge"),Ut();const n=u?.current,i=Kt(s);try{i.remote&&i.remoteBranch&&(dt(`Fetching ${i.remote}/${i.remoteBranch}...`,"running"),await a.gitFetch(r,{remote:i.remote,branch:i.remoteBranch}),Ge("done",`Fetched ${i.remote}/${i.remoteBranch}`)),dt(`Merging ${i.branch} into ${n}...`,"running");const c=await a.merge(r,{branch:i.branch});c.conflict?(Ge("error","Merge conflicts detected"),tt(c.conflictFiles??[]),st("merge"),Qe(!0),at(r,c.conflictFiles??[],"merge")):(Ge("done",`Merged ${i.branch} into ${n}`),Je(),dt("Refreshing repository status...","running"),await te(),await pe(),Ge("done","Repository status updated"))}catch(c){if(Wt(c))Ge("error","Uncommitted changes detected"),or("merge"),lr(i.branch),Cs(!0);else{const j=c instanceof Error?c.message:`Failed to merge ${i.branch}`;Ge("error",j)}}},[r,a,u,Kt,te,pe,Wt,at,Je,dt,Ge,Ut]),Fn=l.useCallback(async s=>{if(!r)return;ys("rebase"),Ut();const n=u?.current,i=Kt(s);try{i.remote&&i.remoteBranch&&(dt(`Fetching ${i.remote}/${i.remoteBranch}...`,"running"),await a.gitFetch(r,{remote:i.remote,branch:i.remoteBranch}),Ge("done",`Fetched ${i.remote}/${i.remoteBranch}`)),dt(`Rebasing ${n} onto ${i.branch}...`,"running");const c=await a.rebase(r,{onto:i.branch});c.conflict?(Ge("error","Rebase conflicts detected"),tt(c.conflictFiles??[]),st("rebase"),Qe(!0),at(r,c.conflictFiles??[],"rebase")):(Ge("done",`Rebased ${n} onto ${i.branch}`),Je(),dt("Refreshing repository status...","running"),await te(),await pe(),Ge("done","Repository status updated"))}catch(c){if(Wt(c))Ge("error","Uncommitted changes detected"),or("rebase"),lr(i.branch),Cs(!0);else{const j=c instanceof Error?c.message:`Failed to rebase onto ${i.branch}`;Ge("error",j)}}},[r,a,u,Kt,te,pe,Wt,at,Je,dt,Ge,Ut]),Rn=l.useCallback(async()=>{if(r)try{_t==="merge"?(await a.abortMerge(r),b.success(e("gitView.toast.mergeAborted"))):(await a.abortRebase(r),b.success(e("gitView.toast.rebaseAborted"))),Je(),await te(),await pe()}catch(s){const n=s instanceof Error?s.message:`Failed to abort ${_t}`;b.error(n)}},[r,a,_t,te,pe,Je,e]),Bn=l.useMemo(()=>u?.files?u.files.filter(s=>s.index==="U"||s.working_dir==="U"||s.index==="A"&&s.working_dir==="A"||s.index==="D"&&s.working_dir==="D").length:0,[u?.files]),Dn=l.useCallback(async()=>{if(r)try{const s=!!u?.mergeInProgress?.head,n=!!(u?.rebaseInProgress?.headName||u?.rebaseInProgress?.onto);if(s){const i=await a.continueMerge(r);i.conflict?(tt(i.conflictFiles??[]),st("merge"),Qe(!0),at(r,i.conflictFiles??[],"merge"),b.error(e("gitView.toast.mergeConflictsDetected"))):(Je(),b.success(e("gitView.toast.mergeCompleted")),await te(),await pe())}else if(n){const i=await a.continueRebase(r);i.conflict?(tt(i.conflictFiles??[]),st("rebase"),Qe(!0),at(r,i.conflictFiles??[],"rebase"),b.error(e("gitView.toast.rebaseConflictsDetected"))):(Je(),b.success(e("gitView.toast.rebaseStepCompleted")),await te(),await pe())}}catch(s){const n=s instanceof Error?s.message:e("gitView.toast.continueOperationFailed");b.error(n)}},[r,a,u,te,pe,at,Je,e]),Mn=l.useCallback(async()=>{if(r)try{!!u?.mergeInProgress?.head?(await a.abortMerge(r),b.success(e("gitView.toast.mergeAborted"))):(await a.abortRebase(r),b.success(e("gitView.toast.rebaseAborted"))),Je(),await te(),await pe()}catch(s){const n=s instanceof Error?s.message:e("gitView.toast.abortOperationFailed");b.error(n)}},[r,a,u,te,pe,Je,e]),En=l.useCallback(()=>{if(!r)return;const n=!!u?.mergeInProgress?.head?"merge":"rebase",i=u?.files?.filter(c=>c.index==="U"||c.working_dir==="U").map(c=>c.path)??[];i.length>0&&tt(i),st(n),Qe(!0)},[r,u]),Tn=l.useCallback(async s=>{if(!r)return;const n=u?.current,i=Ns,c=Ss,j=(u?.files??[]).some(Pr);try{await a.stash(r,{message:`Auto-stash before ${i} with ${c}`,includeUntracked:!0}),j&&K(r)}catch(_){const _e=_ instanceof Error?_.message:"Failed to stash changes";b.error(_e);return}let O=!1,Z=!1;try{if(i==="merge"){const _=await a.merge(r,{branch:c});_.conflict?(Z=!0,tt(_.conflictFiles??[]),st("merge"),Qe(!0)):(O=!0,b.success(e("gitView.toast.mergedIntoBranch",{branch:c,currentBranch:n||""})))}else{const _=await a.rebase(r,{onto:c});_.conflict?(Z=!0,tt(_.conflictFiles??[]),st("rebase"),Qe(!0)):(O=!0,b.success(e("gitView.toast.rebasedOntoBranch",{currentBranch:n||"",branch:c})))}if(s&&O)try{await a.stashPop(r),K(r),b.success(e("gitView.toast.stashedRestored"))}catch(_){const _e=_ instanceof Error?_.message:e("gitView.toast.restoreStashFailed");b.error(_e)}else s&&Z&&b.info(e("gitView.toast.restoreStashManually"));await te(),await pe()}catch(_){if(s)try{await a.stashPop(r),K(r)}catch{}throw _}},[K,r,a,u,Ns,Ss,te,pe,e]),An=l.useCallback(s=>{Lr(s),r&&(L(r,s),I(r,a,s))},[r,I,a,L]),Ln=l.useCallback(s=>{rn(s)},[]),On=l.useCallback(()=>{zt(null),r&&(h(r,a),d(r,a),I(r,a,Ye))},[r,h,d,I,Ye,a]),zn=l.useCallback(s=>{if(s.conflict){if(s.operation==="cherry-pick"||s.operation==="revert"){b.error(e("gitView.history.actions.conflictToastTitle"),{description:e("gitView.history.actions.conflictToastDescription",{files:s.conflictFiles?.join(", ")??"unknown files"})}),r&&(h(r,a),d(r,a),I(r,a,Ye));return}tt(s.conflictFiles??[]),st(s.operation),Qe(!0),r&&at(r,s.conflictFiles??[],s.operation)}},[e,tt,st,Qe,at,r,h,d,I,Ye,a]);return m?Ue?t.jsxs("div",{className:"flex h-full flex-col items-center justify-center px-4 text-center",children:[Ae?null:t.jsx(T,{name:"loader-4",className:"mb-3 size-6 animate-spin text-muted-foreground"}),t.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e(Ae?"gitView.toast.refreshRepositoryFailed":"gitView.empty.worktreeSetupInProgress")}),Ae?t.jsx(W,{type:"button",variant:"outline",size:"sm",className:"mt-3",onClick:()=>{oe&&x({directory:oe,status:"refreshing"})},children:e("gitView.empty.retryDiscovery")}):t.jsx("p",{className:"typography-meta mt-1 text-muted-foreground",children:e("gitView.empty.worktreeSetupDescription")})]}):B===null||B===!0&&!u?t.jsx("div",{className:"flex h-full items-center justify-center",children:t.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[t.jsx(T,{name:"loader-4",className:"size-4 animate-spin"}),t.jsx("span",{className:"typography-ui-label",children:e("gitView.loading.checkingRepository")})]})}):B===!1?t.jsx($a,{rootIsGitRepo:F,resolvedIsGitRepo:B,nestedRepos:Y,onRetryDiscovery:()=>{m&&de(m,{force:!0})},emptyStateFooter:se.includes("open-without-worktree-features")?t.jsx("p",{className:"typography-meta mt-2 text-muted-foreground",children:e("gitView.empty.worktreeFeaturesUnavailable")}):void 0}):t.jsxs("div",{className:Se("flex h-full flex-col overflow-hidden"),children:[t.jsx(Ha,{directory:r??"",status:u,localBranches:Vt,remoteBranches:ot,branchInfo:$?.branches,syncAction:Hs,remotes:ze,onFetch:s=>dr("fetch",s),onSync:s=>dr("sync",s),onRemoveRemote:dn,removingRemoteName:Xr,onCheckoutBranch:gn,onCreateBranch:mn,onRenameBranch:hn,activeIdentityProfile:wn,availableIdentities:xn,onSelectIdentity:fn,isApplyingIdentity:Or,isWorktreeMode:!!G,onOpenHistory:()=>zt("history"),onOpenGraph:()=>zt("graph"),onOpenStashes:Nn,onOpenUpdateBranch:hr?()=>sr(!0):void 0,onOpenReintegrateCommits:ct?()=>rr(!0):void 0,pullRequest:Re?.pr??null,prChecks:Re?.checks??null,onOpenPullRequest:r?()=>xe(r,"pr"):void 0,repositoryOptions:r!==m&&Array.isArray(Y)?Y:void 0,selectedRepository:r!==m?r:null,onSelectRepository:r!==m&&m?s=>ke(m,s):void 0,repositoryRoot:r!==m?m:void 0}),m&&(u?.mergeInProgress?.head||u?.rebaseInProgress?.headName||u?.rebaseInProgress?.onto)&&t.jsx(Ii,{mergeInProgress:u?.mergeInProgress,rebaseInProgress:u?.rebaseInProgress,onContinue:Dn,onAbort:Mn,onResolveWithAI:En,conflictCount:Bn,isLoading:le}),t.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:t.jsx("div",{className:"h-full min-h-0 flex flex-col",children:t.jsx("div",{className:Se("min-w-0 min-h-0 h-full flex flex-col"),children:t.jsx(Rr,{as:Ma,ref:$s,outerClassName:"flex-1 min-h-0",className:Se("px-4","pt-1 pb-4"),disableHorizontal:!0,preventOverscroll:!0,children:t.jsx("div",{className:"flex h-full min-h-0 flex-col gap-3",children:(it?.length??0)>0?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:t.jsx(Ua,{groups:Sn,diffStats:u?.diffStats,revertingPaths:os,isRevertingAll:ls,onVisiblePathsChange:Er,onRevertAll:jn,onRevertDirectory:Cn,headerBackgroundClassName:"bg-background"})}),t.jsx(Ka,{stagedCount:yn,commitMessage:Ke,onCommitMessageChange:We,generatedHighlights:cs,onInsertHighlights:kn,onGenerateMessage:un,isGeneratingMessage:Hr,onCommit:()=>ur({pushAfter:!1}),onCommitAndPush:()=>ur({pushAfter:!0}),commitAction:Ws,hasPendingIndexMutation:Wr,gitmojiEnabled:fe,onOpenGitmojiPicker:()=>rs(!0)})]}):t.jsx(oi,{onOpenStashes:()=>ns(!0)})})})})})}),t.jsx(mt,{open:Yr,onOpenChange:s=>{!s&&ar!==null||sr(s)},children:t.jsxs(ht,{className:"max-w-2xl min-h-[26rem]",children:[t.jsxs(gt,{children:[t.jsx(ft,{children:e("gitView.branch.updateTitle")}),t.jsxs(bt,{children:[e("gitView.branch.updateDescriptionPrefix")," ",t.jsx("span",{className:"font-mono text-foreground",children:u?.current??""}),"."]})]}),hr?t.jsx(Pi,{mode:"bare",currentBranch:u?.current,localBranches:Vt,remoteBranches:ot,defaultTargetBranch:pn,onMerge:Pn,onRebase:Fn,disabled:bn,isOperating:ar!==null,operationLogs:Zr,onOperationComplete:In}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:e("gitView.branch.actionsUnavailable")})]})}),t.jsx(mt,{open:Qr,onOpenChange:rr,children:t.jsxs(ht,{className:"max-w-2xl min-h-[26rem]",children:[t.jsxs(gt,{children:[t.jsx(ft,{children:e("gitView.integrate.title")}),t.jsx(bt,{children:ct?t.jsxs("span",{className:"font-mono text-foreground",children:[ct.sourceBranch," → ",Zs]}):null})]}),ct?t.jsx(ai,{repoRoot:ct.repoRoot,sourceBranch:ct.sourceBranch,worktreeMetadata:ct.worktreeMetadata,localBranches:Vt,defaultTargetBranch:Zs,refreshKey:_r,showHeader:!1,onRefresh:()=>{r&&(h(r,a),d(r,a),I(r,a,Ye))}},ct.worktreeMetadata.path):null]})}),t.jsx(mt,{open:Me!==null,onOpenChange:s=>{s||zt(null)},children:t.jsxs(ht,{className:"max-w-5xl h-[90vh] max-h-[90vh] flex flex-col overflow-hidden",children:[t.jsxs(gt,{children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx(ft,{children:e(Me==="graph"?"gitView.graph.title":"gitView.history.title")}),t.jsxs(W,{type:"button",variant:"ghost",size:"sm",className:"mr-6 h-7 shrink-0 gap-1.5 px-2",onClick:()=>{if(Me==="graph"){an(s=>s+1);return}r&&I(r,a,Ye)},disabled:Me==="graph"?vs:ae,title:e("gitView.history.refresh"),"aria-label":e("gitView.history.refresh"),children:[t.jsx(T,{name:"refresh",className:Se("size-4",(Me==="graph"?vs:ae)&&"animate-spin")}),e("gitView.history.refresh")]})]}),t.jsx(bt,{children:e("gitView.history.dialogDescription")})]}),t.jsx("div",{className:"flex-1 min-h-0",children:t.jsx(pi,{mode:Me==="graph"?"graph":"history",log:Me==="graph"?sn??X:X,isLogLoading:Me==="graph"&&vs||ae,logMaxCount:Me==="graph"?js:Ye,onLogMaxCountChange:Me==="graph"?Ln:An,expandedCommitHashes:hs,onToggleCommit:cn,commitFilesMap:Lt,loadingCommitHashes:Ot,onCopyHash:ln,directory:r??void 0,showHeader:!1,contentMaxHeightClassName:"h-full max-h-none",branchDivider:Me==="graph"?null:qr,onConflict:Me==="graph"?zn:void 0,onActionSuccess:Me==="graph"?On:void 0})})]})}),t.jsx(ii,{open:Ar,onOpenChange:ns,directory:r,hasUncommittedChanges:(u?.files?.length??0)>0,hasStagedChanges:qe.length>0,uncommittedFileCount:u?.files?.length??0,onChanged:async s=>{r&&s?.affectsIndex&&K(r),await te(!1),await pe()}}),t.jsx(mt,{open:Tr,onOpenChange:rs,children:t.jsxs(ht,{className:"max-w-md p-0 overflow-hidden",children:[t.jsx(gt,{className:"px-4 pt-4",children:t.jsx(ft,{children:e("gitView.gitmoji.title")})}),t.jsxs(Os,{className:"h-[420px]",shouldFilter:!1,children:[t.jsx(zs,{placeholder:e("gitView.gitmoji.searchPlaceholder"),value:er,onValueChange:tr}),t.jsxs(Gs,{children:[t.jsx(_s,{children:e("gitView.gitmoji.empty")}),t.jsx(Xt,{children:Dt(He,er,s=>[s.code,s.description,s.emoji]).map(s=>t.jsxs(Zt,{onSelect:()=>Vn(s.emoji,s.code),children:[t.jsx("span",{className:"text-lg",children:s.emoji}),t.jsx("span",{className:"typography-ui-label text-foreground",children:s.code}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:s.description})]},s.code))})]})]})]})}),r&&t.jsx(vi,{open:en,onOpenChange:Qe,conflictFiles:tn,directory:r,operation:_t,onAbort:Rn,onClearState:Je}),t.jsx(Ja,{open:$t!==null,onOpenChange:s=>{s||kt(null)},targetBranch:$t??"",changedFileCount:u?.files?.length??0,onCommitAndSwitch:async(s,n)=>{const i=$t;if(!i||!r)return;const c=u?.current??null;await a.createGitCommit(r,s,{addAll:!0}),K(r);let j=null;if(n){const O=u?.tracking?.split("/")[0],Z=ze.find(_=>_.name===O)??ze[0];try{if(!Z)throw new Error(e("mobile.changes.noRemote"));await a.gitPush(r,u?.tracking?{remote:Z.name}:{remote:Z.name,branch:c??void 0,options:["--set-upstream"]}),j=Z.name}catch(_){console.error("Push after commit failed:",_),b.error(e("gitView.dirtySwitch.pushFailed")),await te(),await pe(),kt(null);return}}b.success(j?e("gitView.toast.pushedToUpstream",{name:j}):c?e("gitView.dirtySwitch.committedNotPushed",{branch:c}):e("gitView.toast.commitCreated")),await te(),await pe(),kt(null),await Ps(i)},onGenerateMessage:async()=>{if(!r)return"";const s=(u?.files??[]).map(c=>c.path).sort(),{message:n}=await fr(r,s),i=n.subject?.trim()??"";if(i&&fe&&He.length>0){const c=Ir(i,He);if(c&&!i.startsWith(c.code)&&!i.startsWith(c.emoji))return`${c.code} ${i}`}return i},onRevertAndSwitch:async()=>{const s=$t;if(!s||!r)return;const n=(u?.files??[]).map(c=>c.path);await Pt(n,!0,"all");const i=await a.getGitStatus(r);if(!i.isClean&&(i.files?.length??0)>0){b.error(e("gitView.dirtySwitch.revertIncomplete"));return}kt(null),await Ps(s)}}),t.jsx(Vi,{open:on,onOpenChange:Cs,operation:Ns,targetBranch:Ss,onConfirm:Tn})]}):t.jsx("div",{className:"flex h-full items-center justify-center px-4 text-center",children:t.jsx("p",{className:"typography-ui-label text-muted-foreground",children:e("gitView.empty.selectSessionOrDirectory")})})};export{ic as GitView};
@@ -1 +1 @@
1
- import{fn as M,hk as Z,hl as Fe,h5 as Ce,h6 as ke,h7 as Ie,h8 as ze,he as Ne,hd as Ve,f as Oe,B as ee,I as te,hB as Pe}from"./useAppFontEffects-COAeIX-D.js";import{b as ie,s as Be,d as Se,e as ne,i as ve,j as De,c as re,k as I,l as Ue,h as _e,g as We,f as je,R as Ge,I as $e,p as se,m as qe,n as Ke,o as Je,r as Ye,w as Xe,t as ae,u as Qe,A as Ze,v as et,x as tt,q as oe,S as it,y as nt,z as rt,B as st,a as ye,C as he,F as at}from"./web-components-BNMwa0qm.js";import{G as ot,u as ht,W as lt,a as dt,b as ct,n as le,t as ut}from"./Virtualizer-CZlLSacm.js";import{j as C,r as k,R as L}from"./vendor-react-BUCujlKS.js";import{n as ft,i as G,f as A,a as pt,o as de,s as gt,j as ce,d as mt,q as ue,b as Ct,t as B,u as fe}from"./computeVirtualFileMetrics-DtyozJdt.js";import{a as F,i as K,l as pe,h as St,r as vt}from"./isFilePlainText-B19Ddps1.js";import{t as H}from"./vendor-hast-util-to-html-BKBhbTDb.js";let yt=-1;var Tt=class{options;onRenderUpdate;workerManager;__id=`file-renderer:${++yt}`;highlighter;renderCache;computedLang="text";lineAnnotations={};lineCache;textDoucmentCache=new WeakMap;constructor(i={theme:M},e,t){this.options=i,this.onRenderUpdate=e,this.workerManager=t,t?.isWorkingPool()!==!0&&(this.highlighter=ie(i.theme??M)?ft():void 0)}setOptions(i){this.options=i}mergeOptions(i){this.options={...this.options,...i}}setLineAnnotations(i){this.lineAnnotations={};for(const e of i){const t=this.lineAnnotations[e.lineNumber]??[];this.lineAnnotations[e.lineNumber]=t,t.push(e)}}cleanUp(){this.recycle(),this.workerManager=void 0,this.onRenderUpdate=void 0}recycle(){this.clearRenderCache(),this.highlighter=void 0,this.workerManager?.cleanUpTasks(this),this.lineCache=void 0}clearRenderCache(){const i=this.renderCache;this.renderCache=void 0,i!=null&&i.isDirty===!0&&i.file.cacheKey!=null&&this.workerManager?.evictFileFromCache(i.file.cacheKey)}hydrate(i){const{options:e}=this.getRenderOptions(i),t=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());let n=this.workerManager?.getFileResultCache(i);n!=null&&!F(e,n.options)&&(n=void 0),this.renderCache??={file:i,options:e,highlighted:!t&&!K(i),result:t?void 0:n?.result,renderRange:void 0},this.workerManager?.isWorkingPool()===!0?this.renderCache.result==null&&!t&&this.workerManager.highlightFileAST(this,i):this.highlighter==null&&(this.computedLang=i.lang??G(i.name),this.initializeHighlighter())}getRenderOptions(i){const e=(()=>{if(this.workerManager?.isWorkingPool()===!0)return this.workerManager.getFileRenderOptions();const{theme:n=M,tokenizeMaxLineLength:r=1e3}=this.options;return{theme:n,useTokenTransformer:Be(this.options),tokenizeMaxLineLength:r}})(),{renderCache:t}=this;return t?.result==null?{options:e,forceHighlight:!0}:!A(i,t.file)||!F(e,t.options)?{options:e,forceHighlight:!0}:{options:e,forceHighlight:!1}}getOrCreateLineCache(i){if(i.cacheKey==null)return this.lineCache=void 0,pe(i.contents);let{lineCache:e}=this;return(e==null||e.cacheKey!==i.cacheKey)&&(e={cacheKey:i.cacheKey,lines:pe(i.contents)}),this.lineCache=e,e.lines}getLineCount(i){return this.textDoucmentCache.get(i)?.lineCount??this.getOrCreateLineCache(i).length}updateRenderCache(i,e){if(this.renderCache==null)return;const{result:t}=this.renderCache;if(t!=null){for(const[n,r]of i)t.code[n]={type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:r.map(([s,a,o])=>s===0&&a===""?o===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:o}:{type:"element",tagName:"span",properties:{"data-char":s,style:`--diffs-token-${e}:${a};`},children:[{type:"text",value:o}]})};t.baseThemeType=e,this.renderCache.isDirty=!0}}applyDocumentChange(i){if(this.renderCache==null)return;const{file:e,result:t}=this.renderCache;if(t!=null&&t.code.length!==i.lineCount){t.code.length=Math.min(t.code.length,i.lineCount);for(let n=t.code.length;n<i.lineCount;n++)t.code.push({type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:i.getLineText(n)}]}]});this.renderCache.isDirty=!0}this.textDoucmentCache.set(e,i)}renderFile(i=this.renderCache?.file,e=Z){if(i==null)return;let{options:t,forceHighlight:n}=this.getRenderOptions(i);const r=this.getMatchingWorkerResultCache(i,t);r!=null&&!this.hasHighlightedRenderCache(i,t)&&(this.renderCache={file:i,highlighted:!0,renderRange:void 0,...r},n=!1),this.renderCache??={file:i,highlighted:!1,options:t,result:void 0,renderRange:void 0};const s=this.getOrCreateLineCache(i),a=i.contents.length>0,o=!a||K(i)||$(s.length,this.getTokenizeMaxLength()),h=!A(i,this.renderCache.file),l=!Se(this.renderCache.renderRange,e);if(this.workerManager?.isWorkingPool()===!0)(o||this.renderCache.result==null||!this.renderCache.highlighted&&(h||l))&&(this.renderCache.file=i,this.renderCache.options=t,this.renderCache.highlighted=!1,(this.renderCache.result==null||h||l||n)&&(this.renderCache.result=this.workerManager.getPlainFileAST(i,e.startingLine,e.totalLines,s)),this.renderCache.renderRange=e),!o&&a&&(!this.renderCache.highlighted||n)&&this.workerManager.highlightFileAST(this,i);else{this.computedLang=i.lang??G(i.name);const d=this.highlighter!=null&&ie(t.theme),u=this.highlighter!=null&&ne(this.computedLang),c=!o&&u;if(this.highlighter!=null&&d&&(n||o||!this.renderCache.highlighted&&c||this.renderCache.result==null)){const{result:p,options:f}=this.renderFileWithHighlighter(i,this.highlighter,o||!u);this.renderCache={file:i,options:f,highlighted:c,result:p,renderRange:void 0}}(!d||!o&&!u)&&this.asyncHighlight(i).then(({result:p,options:f})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.onHighlightSuccess(i,p,f,!o)})}return this.renderCache.result!=null?this.processFileResult(this.renderCache.file,e,this.renderCache.result):void 0}async asyncRender(i,e=Z){const{result:t}=await this.asyncHighlight(i);return this.processFileResult(i,e,t)}async asyncHighlight(i){const e=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());this.computedLang=e?"text":i.lang??G(i.name);const t=this.highlighter!=null&&St(pt(this.options.theme)),n=e||this.highlighter!=null&&ne(this.computedLang);return(this.highlighter==null||!t||!n)&&(this.highlighter=await this.initializeHighlighter()),this.renderFileWithHighlighter(i,this.highlighter,e)}renderFileWithHighlighter(i,e,t=!1){const{options:n}=this.getRenderOptions(i);return{result:vt(i,e,n,{forcePlainText:t}),options:n}}processFileResult(i,e,{code:t,themeStyles:n,baseThemeType:r}){const s=this.getLineCount(i),{disableFileHeader:a=!1}=this.options,o=[],h=ue(),l=Math.min(e.startingLine+e.totalLines,s);let d=0;const u=ve(e)?De(this.lineAnnotations):void 0;u!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:-1,lineIndex:-1,annotations:u.map(c=>I(c))})),d++);for(let c=e.startingLine;c<l;c++){const p=c+1,f=t[c];if(f==null){const g="FileRenderer.processFileResult: Line doesnt exist";throw console.error(g,{name:i.name,lineIndex:c,lineNumber:p}),new Error(g)}h.children.push(gt("context",p,`${c}`)),o.push(f),d++;const S=this.lineAnnotations[p];S!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:0,lineIndex:p,annotations:S.map(g=>I(g))})),d++)}return h.properties.style=`grid-row: span ${d}`,{gutterAST:h.children??[],contentAST:o,preAST:this.createPreElement(s),headerAST:a?void 0:this.renderHeader(i),totalLines:s,rowCount:d,themeStyles:n,baseThemeType:r,bufferBefore:e.bufferBefore,bufferAfter:e.bufferAfter,css:""}}renderHeader(i){const{headerRenderMode:e="default",stickyHeader:t=!1}=this.options;return Ue({fileOrDiff:i,mode:e,stickyHeader:t})}renderFullHTML(i){return H(this.renderFullAST(i))}renderFullAST(i,e=[]){return e.push(ce({tagName:"code",children:this.renderCodeAST(i),properties:{"data-code":""}})),{...i.preAST,children:e}}renderCodeAST(i){const e=ue();return e.children=i.gutterAST,e.properties.style=`grid-row: span ${i.rowCount}`,[e,_e(i.contentAST,i.rowCount)]}renderPartialHTML(i,e=!1){return e?H(ce({tagName:"code",children:i,properties:{"data-code":""}})):H(i)}async initializeHighlighter(){return this.highlighter=await mt(We(this.computedLang,this.options)),this.highlighter}onHighlightSuccess(i,e,t,n=!0){if(this.renderCache==null)return;const r=!A(i,this.renderCache.file)||!this.renderCache.highlighted||!F(t,this.renderCache.options);this.renderCache={file:i,options:t,highlighted:n,result:e,renderRange:void 0},r&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(i,e){const t=this.workerManager?.getFileResultCache(i);if(!(t==null||!F(e,t.options)))return t}hasHighlightedRenderCache(i,e){const{renderCache:t}=this;return t?.result!=null&&t.highlighted&&A(i,t.file)&&F(e,t.options)}onHighlightError(i){console.error(i)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}createPreElement(i){const{disableLineNumbers:e=!1,overflow:t="scroll"}=this.options;return je({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers:e,overflow:t,split:!1,totalLines:i})}};function $(i,e){return i>e}function bt(i,e){return i.lineNumber===e.lineNumber&&i.metadata===e.metadata}function ge(i){return{theme:i?.theme,disableLineNumbers:i?.disableLineNumbers,overflow:i?.overflow,themeType:i?.themeType,collapsed:i?.collapsed,disableFileHeader:i?.disableFileHeader,disableVirtualizationBuffers:i?.disableVirtualizationBuffers,stickyHeader:i?.stickyHeader,preferredHighlighter:i?.preferredHighlighter,useCSSClasses:i?.useCSSClasses,useTokenTransformer:i?.useTokenTransformer,tokenizeMaxLineLength:i?.tokenizeMaxLineLength,tokenizeMaxLength:i?.tokenizeMaxLength,unsafeCSS:i?.unsafeCSS,headerRenderMode:i?.renderCustomHeader!=null?"custom":"default"}}const Rt=[""];let Lt=-1;var Te=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file:${++Lt}`;type="file";fileContainer;spriteSVG;pre;code;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;errorWrapper;placeHolder;lastRenderedHeaderHTML;cachedHeaderHTML;appliedPreAttributes;lastRowCount;mounted=!1;headerElement;headerCustom;headerPrefix;headerFilenameSuffix;headerMetadata;fileRenderer;resizeManager;interactionManager;annotationCache=new Map;lineAnnotations=[];managersDirty=!1;file;renderRange;enabled=!0;editor;constructor(e={theme:M},t,n=!1){this.options=e,this.workerManager=t,this.isContainerManaged=n,this.fileRenderer=new Tt(e,this.handleHighlightRender,this.workerManager),this.resizeManager=new Ge,this.interactionManager=new $e("file",se(e)),this.workerManager?.subscribeToThemeChanges(this)}handleHighlightRender=()=>{this.rerender()};rerender(){!this.enabled||this.file==null||this.render({file:this.file,forceRender:!0,renderRange:this.renderRange})}onThemeChange(){this.fileRenderer.clearRenderCache(),this.rerender()}setOptions(e){e!=null&&(this.options=e,this.cachedHeaderHTML=void 0,this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(se(this.options))}mergeOptions(e){this.options={...this.options,...e}}setThemeType(e){(this.options.themeType??"system")!==e&&(this.mergeOptions({themeType:e}),this.applyCachedThemeState(e))}applyCachedThemeState(e){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const t=this.appliedThemeCSS.baseThemeType??e;return this.appliedThemeCSS.themeType===t?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,e,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!Ct(this.appliedThemeCSS.theme,this.options.theme??M)}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(e){this.lineAnnotations=e}setSelectedLines(e,t){this.interactionManager.setSelection(e,t)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{overflow:e="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,e==="wrap"),this.managersDirty=!1}cleanUp(e=!1){this.emitPostRender(!0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,e||(this.lineAnnotations=[]),this.annotationCache.clear(),this.pre=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.lastRenderedHeaderHTML=void 0,e||(this.cachedHeaderHTML=void 0),this.errorWrapper=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.placeHolder=void 0,this.unsafeCSSStyle=void 0,e?this.fileRenderer.recycle():(this.fileRenderer.cleanUp(),this.workerManager=void 0,this.file=void 0),this.enabled=!1,this.editor?.cleanUp(),this.editor=void 0}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate(e){const{fileContainer:t,prerenderedHTML:n,preventEmit:r=!1,file:s,lineAnnotations:a}=e;this.hydrateElements(t,n),At(this.pre,s,this.options.collapsed)||Mt(this.headerElement,s,this.options.disableFileHeader)?this.render({...e,preventEmit:!0}):this.hydrationSetup({file:s,lineAnnotations:a}),r||this.emitPostRender()}hydrateElements(e,t){this.fileContainer!==e&&this.emitPostRender(!0),qe(e,t);for(const n of Array.from(e.shadowRoot?.children??[])){if(n instanceof SVGElement){this.spriteSVG=n;continue}if(n instanceof HTMLElement){if(n instanceof HTMLPreElement){this.pre=n,this.appliedPreAttributes=void 0;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-theme-css")){this.themeCSSStyle=n;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=n,this.appliedUnsafeCSS=n.textContent;continue}if("diffsHeader"in n.dataset){this.headerElement=n,this.lastRenderedHeaderHTML=void 0;continue}}}this.pre!=null&&(this.syncCodeNodeFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=e,this.hydrateMeasuredScrollbar()}hydrationSetup({file:e,lineAnnotations:t}){this.lineAnnotations=t??this.lineAnnotations,this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),this.pre!=null&&(this.fileRenderer.hydrate(e),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}getOrCreateLineCache(e=this.file){return e!=null?this.fileRenderer.getOrCreateLineCache(e):Rt}updateBuffers(e){this.pre!=null&&this.applyBuffers(this.pre,e)}syncRenderViewToEditor(){const e=this.editor,t=this.fileContainer,n=this.file;e!=null&&t!=null&&n!=null&&this.fileRenderer.initializeHighlighter().then(r=>{e.__syncRenderView(r,t,n,this.lineAnnotations,this.renderRange)})}attachEditor(e){return this.editor?.cleanUp(),this.editor=e,this.interactionManager.setEditorAttached(!0),this.syncRenderViewToEditor(),()=>{this.editor=void 0,this.interactionManager.setEditorAttached(!1)}}applyDocumentChange(e,t){this.fileRenderer.applyDocumentChange(e),t!=null&&t!==this.lineAnnotations&&this.file!=null&&(this.setLineAnnotations(t),this.fileRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations())}updateRenderCache(e,t){this.fileRenderer.updateRenderCache(e,t)}render({file:e,fileContainer:t,forceRender:n=!1,preventEmit:r=!1,containerWrapper:s,deferManagers:a=!1,lineAnnotations:o,renderRange:h}){if(!this.enabled)throw new Error("File.render: attempting to call render after cleaned up");this.editor?.__postponeBackgroundTokenizeToNextFrame();const{collapsed:l=!1,themeType:d="system"}=this.options,u=l?void 0:h,c=this.renderRange,p=this.hasThemeChanged(),f=o!=null&&(o.length>0||this.lineAnnotations.length>0)?o!==this.lineAnnotations:!1,S=!A(this.file,e);if(!l&&!n&&Se(u,this.renderRange)&&!S&&!f&&!p)return this.applyCachedThemeState(d);this.renderRange=u,S&&(this.cachedHeaderHTML=void 0),this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),o!=null&&this.setLineAnnotations(o),this.fileRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:g=!1,disableFileHeader:y=!1}=this.options;if(y&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),t=this.getOrCreateFileContainerNode(t,s),this.applyCachedThemeState(d),l){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const m=this.fileRenderer.renderFile(e,Fe);m!=null&&this.applyThemeState(t,m.themeStyles,d,m.baseThemeType),m?.headerAST!=null&&this.applyHeaderToDOM(m.headerAST,t),this.injectUnsafeCSS()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}try{const m=this.getOrCreatePreNode(t);if(!this.canPartiallyRender(n,f,S||p)||!this.applyPartialRender(c,u)){const v=this.fileRenderer.renderFile(e,u);if(v==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(t,v.themeStyles,d,v.baseThemeType),v.headerAST!=null&&this.applyHeaderToDOM(v.headerAST,t),this.applyFullRender(v,m)}this.applyBuffers(m,u),this.injectUnsafeCSS(),this.managersDirty=!0,a||this.flushManagers(),this.renderAnnotations(),this.renderGutterUtility(),this.editor!=null&&this.syncRenderViewToEditor()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}emitPostRender(e=!1){const{fileContainer:t,options:{onPostRender:n}}=this;if(e){if(!this.mounted||(this.mounted=!1,t==null))return;n?.(t,this,"unmount");return}if(t==null)return;const r=this.mounted?"update":"mount";this.mounted=!0,n?.(t,this,r)}removeRenderedCode(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.code?.remove(),this.code=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element:e}of this.annotationCache.values())e.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}canPartiallyRender(e,t,n){return!(e||t||n)}renderPlaceholder(e){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const t=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",t.appendChild(this.placeHolder)}return this.placeHolder.style.setProperty("height",`${e}px`),!0}primeHighlightCache(){const{file:e,workerManager:t}=this;e==null||e.cacheKey==null||t==null||K(e)||this.fileRenderer.getOrCreateLineCache(e).length>(this.options.tokenizeMaxLength??1e5)||t.primeFileHighlightCache(e)}cleanChildNodes(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.code?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.gutterUtilityContent?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.code=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.gutterUtilityContent=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(const{element:n}of this.annotationCache.values())n.remove();this.annotationCache.clear();return}const e=new Map(this.annotationCache),{renderAnnotation:t}=this.options;if(t!=null&&this.lineAnnotations.length>0)for(const[n,r]of this.lineAnnotations.entries()){const s=`${n}-${I(r)}`;let a=this.annotationCache.get(s);if(a==null||!bt(r,a.annotation)){a?.element.remove();const o=t(r);if(o==null)continue;a={element:Ke(I(r)),annotation:r},a.element.appendChild(o),this.fileContainer.appendChild(a.element),this.annotationCache.set(s,a)}e.delete(s)}for(const[n,{element:r}]of e.entries())this.annotationCache.delete(n),r.remove()}renderGutterUtility(){const{renderGutterUtility:e}=this.options;if(this.fileContainer==null||e==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const t=e(this.interactionManager.getHoveredLine);if(t!=null&&this.gutterUtilityContent!=null)return;if(t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const n=Je();n.appendChild(t),this.fileContainer.appendChild(n),this.gutterUtilityContent=n}injectUnsafeCSS(){const{unsafeCSS:e}=this.options,t=this.fileContainer?.shadowRoot;if(t!=null){if(e==null||e===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===t&&this.appliedUnsafeCSS===e||(this.unsafeCSSStyle??=Ye(),this.unsafeCSSStyle.parentNode!==t&&t.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=Xe(e),this.appliedUnsafeCSS=e)}}applyThemeState(e,t,n,r){const s=e.shadowRoot??e.attachShadow({mode:"open"}),a=r??n,o=this.options.theme??M,h=typeof o=="string"?o:{...o},l=ae(s);if(this.themeCSSStyle?.parentNode===s&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===l){this.appliedThemeCSS.theme=h;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===s){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:l};return}this.themeCSSStyle=Qe({shadowRoot:s,currentNode:this.themeCSSStyle,themeCSS:Ze(t,a,l)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:l}:void 0}hydrateMeasuredScrollbar(){const e=this.fileContainer?.shadowRoot;e==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=et(this.themeCSSStyle.textContent??"",ae(e)))}applyFullRender(e,t){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,e),this.code=tt({code:this.code});const n=this.fileRenderer.renderCodeAST(e);if(this.code.childElementCount>=2)for(let r=0;r<2;r++){const s=this.code.children[r],a=n[r];s.innerHTML=H(a.children),s.style.cssText=a.properties.style}else this.code.innerHTML=H(n);t.contains(this.code)||t.replaceChildren(this.code),this.lastRowCount=e.rowCount}applyPartialRender(e,t){if(e==null||t==null)return!1;const{file:n,code:r}=this,s=r!=null?this.getColumns(r):void 0;if(n==null||r==null||s==null)return!1;const a=e.startingLine,o=t.startingLine,h=e.totalLines===1/0?Number.POSITIVE_INFINITY:a+e.totalLines,l=t.totalLines===1/0?Number.POSITIVE_INFINITY:o+t.totalLines,d=Math.max(a,o),u=Math.min(h,l);if(u<=d||!this.trimDOMToOverlap(s.gutter,d,u)||!this.trimDOMToOverlap(s.content,d,u))return!1;let{length:c}=s.content.children;const p=(y,m)=>{if(!(m<=0))return this.fileRenderer.renderFile(n,{startingLine:y,totalLines:m,bufferBefore:0,bufferAfter:0})},f=o<d?p(o,d-o):void 0;if(f===void 0&&o<d)return!1;const S=l===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,l-u),g=l>u?p(u,S):void 0;return g===void 0&&l>u?!1:(this.cleanupErrorWrapper(),f!=null&&(s.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.gutterAST)),s.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.contentAST)),c+=f.rowCount),g!=null&&(s.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.gutterAST)),s.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.contentAST)),c+=g.rowCount),this.lastRowCount!==c&&(s.gutter.style.setProperty("grid-row",`span ${c}`),s.content.style.setProperty("grid-row",`span ${c}`),this.lastRowCount=c),!0)}getColumns(e){const t=e.children[0],n=e.children[1];if(!(!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||t.dataset.gutter==null||n.dataset.content==null))return{gutter:t,content:n}}trimDOMToOverlap(e,t,n){const r=this.getDOMBoundaryIndices(e,[t,n]),s=r.get(t)??e.children.length,a=r.get(n)??e.children.length;if(s>a)return!1;for(let o=e.children.length-1;o>=a;o-=1)e.children[o]?.remove();for(let o=s-1;o>=0;o-=1)e.children[o]?.remove();return!0}getDOMBoundaryIndices(e,t){const n=[...new Set(t)].sort((h,l)=>h-l),r=new Map;if(n.length===0)return r;let s=0,a=n[s];const{children:o}=e;a===0&&(r.set(0,0),s+=1,a=n[s]);for(let h=0;h<o.length;h+=1){const l=o[h];if(!(l instanceof HTMLElement))continue;const d=this.getLineIndexFromDOMNode(l);if(d!=null){for(;a!=null&&d>=a;)r.set(a,h),s+=1,a=n[s];if(s>=n.length)break}}for(const h of n)r.has(h)||r.set(h,o.length);return r}getLineIndexFromDOMNode(e){const t=e.dataset.lineIndex;if(t==null)return;const n=Number(t);return Number.isNaN(n)?void 0:n}applyBuffers(e,t){if(t==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}t.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",e.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${t.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),t.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",e.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${t.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyHeaderToDOM(e,t){const{file:n}=this;if(n==null)return;this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const r=this.cachedHeaderHTML??H(e);if(this.cachedHeaderHTML=r,r!==this.lastRenderedHeaderHTML){const l=document.createElement("div");l.innerHTML=r;const d=l.firstElementChild;if(!(d instanceof HTMLElement))return;this.headerElement!=null?t.shadowRoot?.replaceChild(d,this.headerElement):t.shadowRoot?.prepend(d),this.headerElement=d,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged)return;const{renderHeaderPrefix:s,renderHeaderFilenameSuffix:a,renderCustomHeader:o,renderHeaderMetadata:h}=this.options;if(o!=null){const l=o(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ce,l),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const l=s?.(n)??void 0,d=a?.(n)??void 0,u=h?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,ke,l),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,Ie,d),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,ze,u),this.headerCustom?.remove(),this.headerCustom=void 0}}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(e,t,n,r){if(r==null){t?.remove();return}const s=t??this.createHeaderSlotElement(n);return t==null&&e.appendChild(s),this.replaceHeaderSlotContent(s,r),s}replaceHeaderSlotContent(e,t){e.replaceChildren(),t instanceof Element?e.appendChild(t):e.innerText=`${t}`}createHeaderSlotElement(e){const t=document.createElement("div");return t.slot=e,t}getOrCreateFileContainerNode(e,t){const{fileContainer:n}=this,r=e??n??document.createElement("diffs-container"),s=n!==r;return s&&this.emitPostRender(!0),this.fileContainer=r,n!=null&&s&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),t!=null&&this.fileContainer.parentNode!==t&&t.appendChild(this.fileContainer),s&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(e){const{shadowRoot:t}=e;if(t!=null)for(const n of t.children)n instanceof SVGElement?this.spriteSVG??=n:oe(n)&&n.hasAttribute("data-theme-css")?(this.themeCSSStyle??=n,this.hasAdoptedThemeCSS=!0):oe(n)&&n.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=n,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});if(this.spriteSVG==null){const n=document.createElement("div");n.innerHTML=it;const r=n.firstChild;r instanceof SVGElement&&(this.spriteSVG=r)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==t&&t.appendChild(this.spriteSVG)}getOrCreatePreNode(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.code=void 0,t.appendChild(this.pre)):this.pre.parentNode!==t&&(e.shadowRoot?.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodeFromPre(e){this.code=void 0;for(const t of Array.from(e.children))if(t instanceof HTMLElement&&t.hasAttribute("data-code")){this.code=t;return}}applyPreNodeAttributes(e,{totalLines:t}){const{overflow:n="scroll",disableLineNumbers:r=!1}=this.options,s={type:"file",split:!1,overflow:n,disableLineNumbers:r,diffIndicators:"none",disableBackground:!0,totalLines:t};nt(s,this.appliedPreAttributes)||(rt(e,s),this.appliedPreAttributes=s)}applyErrorToDOM(e,t){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const n=t.shadowRoot??t.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",n.appendChild(this.errorWrapper);const r=document.createElement("div");r.dataset.errorMessage="",r.innerText=e.message,this.errorWrapper.appendChild(r);const s=document.createElement("pre");s.dataset.errorStack="",s.innerText=e.stack??"No Error Stack",this.errorWrapper.appendChild(s)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function At(i,e,t=!1){return!t&&i==null&&e!=null}function Mt(i,e,t=!1){return i==null&&e!=null&&!t}const Ht=5e3;let xt=-1;function wt(i,e){return(i.overflow??"scroll")!==(e.overflow??"scroll")||(i.collapsed??!1)!==(e.collapsed??!1)||(i.disableLineNumbers??!1)!==(e.disableLineNumbers??!1)||(i.disableFileHeader??!1)!==(e.disableFileHeader??!1)||i.unsafeCSS!==e.unsafeCSS}var Et=class extends Te{virtualizer;metrics;__id=`virtualized-file:${++xt}`;top;height=0;cache={heights:new Map,checkpoints:[],fileAnnotationHeight:0};isVisible=!1;isSetup=!1;layoutDirty=!0;forceRenderOverride;currentCollapsed;constructor(i,e,t=Ne,n,r=!1){super(i,n,r),this.virtualizer=e,this.metrics=t}setMetrics(i,e=!1){!e&&st(this.metrics,i)||(this.metrics=i,this.resetLayoutCache())}setLineAnnotations(i){this.syncLineAnnotations(i)&&this.resetLayoutCache()}syncLineAnnotations(i){return i==null||i===this.lineAnnotations||i.length===0&&this.lineAnnotations.length===0?!1:(super.setLineAnnotations(i),!0)}hasLineAnnotations(){return this.lineAnnotations.some(i=>i.lineNumber>0)}getLineHeight(i,e=!1){const t=this.cache.heights.get(i);if(t!=null)return t;const n=e?2:1;return this.metrics.lineHeight*n}setOptions(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(i==null)return;const{options:e}=this,t=!ye(e,i),n=wt(e,i);super.setOptions(i),n&&this.resetLayoutCache(!0),t&&(this.forceRenderOverride=!0),t&&this.virtualizer.instanceChanged(this,n)}setThemeType(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(i)}resetLayoutCache(i=!1){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heights.size>0&&this.cache.heights.clear(),this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.renderRange!=null&&(this.renderRange=void 0),i&&this.isSimpleMode()&&this.computeApproximateSize()}reconcileHeights(){let i=!1;if(this.fileContainer==null||this.file==null)return this.height!==0&&(i=!0),this.height=0,i;const{overflow:e="scroll"}=this.options;if(this.top=this.getVirtualizedTop(),e==="scroll"&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled()||this.code==null)return i;const t=this.code.children[1];if(!(t instanceof HTMLElement))return i;const n=he(this.lineAnnotations);if(this.renderRange!=null&&n&&ve(this.renderRange)){const r=Ft(t)??0;r!==this.cache.fileAnnotationHeight&&(this.cache.fileAnnotationHeight=r,i=!0)}else!n&&this.cache.fileAnnotationHeight!==0&&(this.cache.fileAnnotationHeight=0,i=!0);for(const r of t.children){if(!(r instanceof HTMLElement))continue;const s=r.dataset.lineIndex;if(s==null)continue;const a=Number(s);let o=r.getBoundingClientRect().height,h=!1;r.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in r.nextElementSibling.dataset||"noNewline"in r.nextElementSibling.dataset)&&("noNewline"in r.nextElementSibling.dataset&&(h=!0),o+=r.nextElementSibling.getBoundingClientRect().height);const l=this.getLineHeight(a,h);o!==l&&(i=!0,o===this.metrics.lineHeight*(h?2:1)?this.cache.heights.delete(a):this.cache.heights.set(a,o))}return(i||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),i}onRender=i=>this.fileContainer==null||this.file==null?!1:(i&&(this.top=this.getVirtualizedTop()),this.render({file:this.file}));prepareCodeViewItem(i,e,t,n){const r=this.syncLineAnnotations(n);let s=t?.resetFileLayoutCache===!0||r;t?.metrics!=null&&(this.metrics=t.metrics,s=!0);const{collapsed:a=!1}=this.options;return this.currentCollapsed!==a&&(this.currentCollapsed=a,s=!0),s&&this.resetLayoutCache(),this.file!==i&&(this.layoutDirty=!0),this.file=i,this.top=e,this.computeApproximateSize(),this.height}getLinePosition(i){if(this.file==null||i<1)return;const{disableFileHeader:e=!1,collapsed:t=!1}=this.options,n=this.fileRenderer.getLineCount(this.file)-1;let r=B(this.metrics,e);if(t||n<0)return{top:r,height:0};const s=Math.min(Math.max(i-1,0),n),{overflow:a="scroll"}=this.options,{lineHeight:o}=this.metrics;if(r+=this.cache.fileAnnotationHeight,a==="scroll"&&!this.hasLineAnnotations())return{top:r+s*o,height:o};const h=this.getLayoutCheckpointBeforeLineIndex(s);r=h?.top??r;for(let l=h?.lineIndex??0;l<s;l++)r+=this.getLineHeight(l,!1);return{top:r,height:this.getLineHeight(s,!1)}}getNumericScrollAnchor(i){if(this.file==null||this.renderRange==null)return;const{disableFileHeader:e=!1,collapsed:t=!1,overflow:n="scroll"}=this.options;if(t||this.renderRange.totalLines<=0)return;const r=this.fileRenderer.getLineCount(this.file)-1;if(r<0)return;const s=B(this.metrics,e),a=Math.min(this.renderRange.startingLine,r),o=Math.min(a+this.renderRange.totalLines-1,r);if(o<a)return;const{fileAnnotationHeight:h}=this.cache;if(n==="scroll"&&!this.hasLineAnnotations()){const{lineHeight:d}=this.metrics,u=s+(a===0?h:this.renderRange.bufferBefore),c=a+Math.max(Math.ceil((i-u)/d),0);return c>o?void 0:{lineNumber:c+1,top:s+h+c*d}}let l=s+(a===0?h:this.renderRange.bufferBefore);for(let d=a;d<=o;d++){if(l>=i)return{lineNumber:d+1,top:l};l+=this.getLineHeight(d)}}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(i){if(this.top==null||this.file==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const e=i!=null?this.computeRenderRangeFromWindow(this.file,this.top,i):this.renderRange;if(e==null)return;const{bufferBefore:t,bufferAfter:n,totalLines:r}=e;let s=0;if(r===0){const a=i??this.virtualizer.getWindowSpecs();this.top<a.top&&(s=n)}return{topOffset:this.top+t+s,height:this.height-(t+n)}}cleanUp(i=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),i||this.resetLayoutCache(),this.isSetup=!1,super.cleanUp(i)}computeApproximateSize(i=!1){const e=this.isResizeDebuggingEnabled();if(!i&&!this.layoutDirty&&!e)return;const t=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.file==null){this.layoutDirty=!1;return}const{disableFileHeader:n=!1,collapsed:r=!1,overflow:s="scroll"}=this.options,{lineHeight:a}=this.metrics,o=this.fileRenderer.getLineCount(this.file),h=B(this.metrics,n),l=fe(this.metrics);if(this.height+=h,r){this.layoutDirty=!1;return}if(this.height+=this.cache.fileAnnotationHeight,s==="scroll"&&!this.hasLineAnnotations())this.height+=o*a;else for(let d=0;d<o;d++)this.addLayoutCheckpoint(d,this.height),this.height+=this.getLineHeight(d,!1);if(o>0&&(this.height+=l),this.fileContainer!=null&&e&&!t){const d=this.fileContainer.getBoundingClientRect();d.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:this.file.name,elementHeight:d.height,computedHeight:this.height}):console.log("VirtualizedFile.computeApproximateSize: computed height IS CORRECT")}this.layoutDirty=!1}setVisibility(i){this.isAdvancedMode()||this.fileContainer==null||(i&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!i&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.file==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(i,e,t=!1){const{heights:n,checkpoints:r}=this.cache,s=this.renderRange;if(super.applyDocumentChange(i,e),this.getSimpleVirtualizer()?.markDOMDirty(),this.layoutDirty=!0,n.size>0&&n.clear(),r.length>0&&(r.length=0),this.isSimpleMode()&&this.computeApproximateSize(),t&&s!==void 0&&this.file!==void 0){const a=this.virtualizer.getWindowSpecs(),o=this.computeRenderRangeFromWindow(this.file,this.top??0,a);o.bufferAfter!==s.bufferAfter&&this.updateBuffers(o)}}render({fileContainer:i,file:e,forceRender:t=!1,lineAnnotations:n,...r}){const s=this.file==null||!A(this.file,e),{forceRenderOverride:a,isSetup:o}=this;this.forceRenderOverride=void 0;const h=this.syncLineAnnotations(n);if(h&&this.resetLayoutCache(),this.file=e,i=this.getOrCreateFileContainerNode(i),this.file==null)return console.error("VirtualizedFile.render: attempting to virtually render when we dont have file"),!1;if(o)this.top??=this.getVirtualizedTop(),s&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache(!0));else{this.computeApproximateSize();const c=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(c==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");c.connect(i,this),this.isVisible=c.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode())return this.renderPlaceholder(this.height);const l=this.virtualizer.getWindowSpecs(),d=this.top??0,u=this.computeRenderRangeFromWindow(this.file,d,l);return super.render({file:this.file,fileContainer:i,renderRange:u,lineAnnotations:n,forceRender:(a??t)||h,...r})}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}addLayoutCheckpoint(i,e){i%Ht===0&&this.cache.checkpoints.push({lineIndex:i,top:e})}getLayoutCheckpointBeforeLineIndex(i){if(i<=0||this.cache.checkpoints.length===0)return;let e=0,t=this.cache.checkpoints.length-1,n;for(;e<=t;){const r=e+t>>1,s=this.cache.checkpoints[r];if(s==null)throw new Error("VirtualizedFile: invalid checkpoint index");s.lineIndex<=i?(n=s,e=r+1):t=r-1}return n}getLayoutCheckpointBeforeTop(i,e){let t=0,n=this.cache.checkpoints.length-1,r=-1;for(;t<=n;){const s=t+n>>1,a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");a.top<=i?(r=s,t=s+1):n=s-1}if(e==null)return r>=0?this.cache.checkpoints[r]:void 0;for(let s=r;s>=0;s--){const a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");if(a.lineIndex%e===0)return a}}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}computeRenderRangeFromWindow(i,e,{top:t,bottom:n}){const{disableFileHeader:r=!1,overflow:s="scroll"}=this.options,{hunkLineCount:a,lineHeight:o}=this.metrics,h=this.fileRenderer.getLineCount(i),l=this.height,d=B(this.metrics,r),u=h>0?fe(this.metrics):0,{fileAnnotationHeight:c}=this.cache,p=d+c,f=Math.max(0,l-d-c-u),S=he(this.lineAnnotations),g=e+d,y=c>0&&S&&g<n&&g+c>t;if(e<t-l||e>n)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:l-d-u};if(h<=a)return{startingLine:0,totalLines:a,bufferBefore:0,bufferAfter:0};const m=Math.ceil(Math.max(n-t,0)/o),v=Math.ceil(m/a)*a+a*2,z=v/a,D=(t+n)/2;if(s==="scroll"&&!this.hasLineAnnotations()){const R=e+p,P=R+f;if(!y&&!(R<n&&P>t))return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:l-d-u};const w=Math.floor(y&&D<e+p?0:(D-(e+p))/o),b=Math.floor(w/a)-Math.floor(z/2),xe=Math.ceil(h/a),E=Math.max(0,Math.min(b,xe))*a,Q=b<0?v+b*a:v,we=E===0?0:c+E*o,Ee=Math.min(Q,h-E);return{startingLine:E,totalLines:Q,bufferBefore:we,bufferAfter:Math.max(0,(h-E-Ee)*o)}}const be=z,N=[],U=this.getLayoutCheckpointBeforeTop(Math.max(0,t-e-v*o*2),a);let T=e+(U?.top??p),_=U?.lineIndex??0,V,O,x;const Re=U?.lineIndex??0;for(let R=Re;R<h;R++){const P=_%a===0,w=Math.floor(_/a);if(P&&(N[w]=T-(e+p),x!=null)){if(x<=0)break;x--}const b=this.getLineHeight(R,!1);T>t-b&&T<n&&(V??=w),T+b>D&&(O??=w),x==null&&T>=n&&P&&(x=be),_++,T+=b}if(V==null)if(y)V=0,O=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:l-d-u};O??=V;const W=Math.round(O-z/2),Le=Math.max(0,Math.ceil(h/a)-z),j=Math.max(0,Math.min(W,Le)),J=j*a,Y=W<0?v+W*a:v,Ae=N[j]??0,Me=J===0?0:c+Ae,X=j+Y/a,He=X<N.length?f-N[X]:f-(T-e-p);return{startingLine:J,totalLines:Y,bufferBefore:Me,bufferAfter:Math.max(0,He)}}};function Ft(i){let e;for(const t of i.children)t instanceof HTMLElement&&t.dataset.lineAnnotation===at&&(e=Math.max(e??0,t.getBoundingClientRect().height));return e}function kt({file:i,renderCustomHeader:e,renderHeaderPrefix:t,renderHeaderFilenameSuffix:n,renderHeaderMetadata:r,renderAnnotation:s,lineAnnotations:a,renderGutterUtility:o,getHoveredLine:h}){const l=e?.(i),d=t?.(i),u=n?.(i),c=r?.(i);return C.jsxs(C.Fragment,{children:[l!=null?C.jsx("div",{slot:Ce,children:l}):C.jsxs(C.Fragment,{children:[d!=null&&C.jsx("div",{slot:"header-prefix",children:d}),u!=null&&C.jsx("div",{slot:"header-filename-suffix",children:u}),c!=null&&C.jsx("div",{slot:"header-metadata",children:c})]}),s!=null&&a?.map((p,f)=>C.jsx("div",{slot:I(p),children:s(p)},f)),o!=null&&C.jsx("div",{slot:"gutter-utility-slot",style:ot,children:o(h)})]})}const me=typeof window>"u"?k.useEffect:k.useLayoutEffect;function It({file:i,options:e,lineAnnotations:t,selectedLines:n,prerenderedHTML:r,metrics:s,hasGutterRenderUtility:a,hasCustomHeader:o,disableWorkerPool:h,contentEditable:l}){const d=ht(),u=n!==void 0,c=k.useContext(lt),p=dt(),f=k.useRef(null),S=ct(g=>{if(g!=null){if(f.current!=null)throw new Error("File: An instance should not already exist when a node is created");d!=null?f.current=new Et(q({controlledSelection:u,contentEditable:l,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),d,s,h?void 0:c,!0):f.current=new Te(q({controlledSelection:u,contentEditable:l,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),h?void 0:c,!0),f.current.hydrate({file:i,fileContainer:g,lineAnnotations:t,prerenderedHTML:r})}else{if(f.current==null)throw new Error("File: A File instance should exist when unmounting");f.current.cleanUp(),f.current=null}});return me(()=>{if(f.current==null)return;const g=q({controlledSelection:u,contentEditable:l,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),y=!ye(f.current.options,g);f.current.setOptions(g),f.current.render({file:i,lineAnnotations:t,forceRender:y}),n!==void 0&&f.current.setSelectedLines(n)}),me(()=>{if(l&&f.current!=null){if(p===void 0)throw new Error("File: Editor is not attached");return p.edit(f.current)}},[l,p]),{ref:S,getHoveredLine:k.useCallback(()=>f.current?.getHoveredLine(),[])}}function q({options:i,controlledSelection:e,contentEditable:t,hasCustomHeader:n,hasEditor:r,hasGutterRenderUtility:s}){const a=t&&r,o=e||s||n;if(!o&&!a)return i;let h={...i};return o&&(h={...h,controlledSelection:e,renderCustomHeader:n?le:i?.renderCustomHeader,renderGutterUtility:s?le:i?.renderGutterUtility}),a&&(h={...h,useTokenTransformer:!0,enableGutterUtility:!1,enableLineSelection:!1,lineHoverHighlight:"disabled"}),h}function _t({file:i,lineAnnotations:e,selectedLines:t,options:n,metrics:r,className:s,style:a,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:l,renderHeaderFilenameSuffix:d,renderHeaderMetadata:u,prerenderedHTML:c,renderGutterUtility:p,disableWorkerPool:f=!1,contentEditable:S=!1}){const{ref:g,getHoveredLine:y}=It({file:i,options:n,metrics:r,lineAnnotations:e,selectedLines:t,prerenderedHTML:c,hasGutterRenderUtility:p!=null,hasCustomHeader:h!=null,disableWorkerPool:f,contentEditable:S});return C.jsx(Ve,{ref:g,className:s,style:a,children:ut(kt({file:i,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:l,renderHeaderFilenameSuffix:d,renderHeaderMetadata:u,renderGutterUtility:p,lineAnnotations:e,getHoveredLine:y}),c)})}const Wt=L.memo(function({jsonString:e,className:t,maxHeight:n="100%",initiallyExpandedDepth:r=2}){const{t:s}=Oe(),a=L.useRef(null),[o,h]=L.useState(null),l=L.useMemo(()=>{try{const c=e.trim();if(!c)return h(s("jsonTreeView.error.emptyJson")),null;const p=JSON.parse(c);return h(null),p}catch(c){return h(c instanceof Error?c.message:s("jsonTreeView.error.invalidJson")),null}},[e,s]),d=L.useCallback(()=>{a.current?.expandAll()},[]),u=L.useCallback(()=>{a.current?.collapseAll()},[]);return o?C.jsx("div",{className:t,children:C.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] bg-[var(--syntax-base-background)] p-4",children:[C.jsx("div",{className:"mb-1 font-medium text-[var(--surface-foreground)]",children:s("jsonTreeView.error.invalidJsonTitle")}),C.jsx("div",{className:"font-mono text-xs text-[var(--surface-mutedForeground)]",children:o})]})}):l===null?null:C.jsxs("div",{className:t,children:[C.jsxs("div",{className:"flex items-center gap-1 border-b border-[var(--interactive-border)] px-2 py-1",children:[C.jsxs(ee,{variant:"ghost",size:"xs",onClick:d,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-down-s",className:"h-3 w-3"}),s("jsonTreeView.actions.expandAll")]}),C.jsxs(ee,{variant:"ghost",size:"xs",onClick:u,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-up-s",className:"h-3 w-3"}),s("jsonTreeView.actions.collapseAll")]})]}),C.jsx("div",{className:"bg-[var(--syntax-base-background)] py-1",style:{maxHeight:n,overflow:"auto"},children:C.jsx(Pe,{ref:a,data:l,maxHeight:n,initiallyExpandedDepth:r})})]})});export{_t as F,Wt as J};
1
+ import{fq as M,hk as Z,hl as Fe,h5 as Ce,h6 as ke,h7 as Ie,h8 as ze,he as Ne,hd as Ve,f as Oe,B as ee,I as te,hB as Pe}from"./useAppFontEffects-CuJPKtI1.js";import{b as ie,s as Be,d as Se,e as ne,i as ve,j as De,c as re,k as I,l as Ue,h as _e,g as We,f as je,R as Ge,I as $e,p as se,m as qe,n as Ke,o as Je,r as Ye,w as Xe,t as ae,u as Qe,A as Ze,v as et,x as tt,q as oe,S as it,y as nt,z as rt,B as st,a as ye,C as he,F as at}from"./web-components-PttKBrhi.js";import{G as ot,u as ht,W as lt,a as dt,b as ct,n as le,t as ut}from"./Virtualizer-CZlLSacm.js";import{j as C,r as k,R as L}from"./vendor-react-BUCujlKS.js";import{n as ft,i as G,f as A,a as pt,o as de,s as gt,j as ce,d as mt,q as ue,b as Ct,t as B,u as fe}from"./computeVirtualFileMetrics-BKZA43vN.js";import{a as F,i as K,l as pe,h as St,r as vt}from"./isFilePlainText-yJZa2IAC.js";import{t as H}from"./vendor-hast-util-to-html-BKBhbTDb.js";let yt=-1;var Tt=class{options;onRenderUpdate;workerManager;__id=`file-renderer:${++yt}`;highlighter;renderCache;computedLang="text";lineAnnotations={};lineCache;textDoucmentCache=new WeakMap;constructor(i={theme:M},e,t){this.options=i,this.onRenderUpdate=e,this.workerManager=t,t?.isWorkingPool()!==!0&&(this.highlighter=ie(i.theme??M)?ft():void 0)}setOptions(i){this.options=i}mergeOptions(i){this.options={...this.options,...i}}setLineAnnotations(i){this.lineAnnotations={};for(const e of i){const t=this.lineAnnotations[e.lineNumber]??[];this.lineAnnotations[e.lineNumber]=t,t.push(e)}}cleanUp(){this.recycle(),this.workerManager=void 0,this.onRenderUpdate=void 0}recycle(){this.clearRenderCache(),this.highlighter=void 0,this.workerManager?.cleanUpTasks(this),this.lineCache=void 0}clearRenderCache(){const i=this.renderCache;this.renderCache=void 0,i!=null&&i.isDirty===!0&&i.file.cacheKey!=null&&this.workerManager?.evictFileFromCache(i.file.cacheKey)}hydrate(i){const{options:e}=this.getRenderOptions(i),t=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());let n=this.workerManager?.getFileResultCache(i);n!=null&&!F(e,n.options)&&(n=void 0),this.renderCache??={file:i,options:e,highlighted:!t&&!K(i),result:t?void 0:n?.result,renderRange:void 0},this.workerManager?.isWorkingPool()===!0?this.renderCache.result==null&&!t&&this.workerManager.highlightFileAST(this,i):this.highlighter==null&&(this.computedLang=i.lang??G(i.name),this.initializeHighlighter())}getRenderOptions(i){const e=(()=>{if(this.workerManager?.isWorkingPool()===!0)return this.workerManager.getFileRenderOptions();const{theme:n=M,tokenizeMaxLineLength:r=1e3}=this.options;return{theme:n,useTokenTransformer:Be(this.options),tokenizeMaxLineLength:r}})(),{renderCache:t}=this;return t?.result==null?{options:e,forceHighlight:!0}:!A(i,t.file)||!F(e,t.options)?{options:e,forceHighlight:!0}:{options:e,forceHighlight:!1}}getOrCreateLineCache(i){if(i.cacheKey==null)return this.lineCache=void 0,pe(i.contents);let{lineCache:e}=this;return(e==null||e.cacheKey!==i.cacheKey)&&(e={cacheKey:i.cacheKey,lines:pe(i.contents)}),this.lineCache=e,e.lines}getLineCount(i){return this.textDoucmentCache.get(i)?.lineCount??this.getOrCreateLineCache(i).length}updateRenderCache(i,e){if(this.renderCache==null)return;const{result:t}=this.renderCache;if(t!=null){for(const[n,r]of i)t.code[n]={type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:r.map(([s,a,o])=>s===0&&a===""?o===""?{type:"element",tagName:"br",properties:{},children:[]}:{type:"text",value:o}:{type:"element",tagName:"span",properties:{"data-char":s,style:`--diffs-token-${e}:${a};`},children:[{type:"text",value:o}]})};t.baseThemeType=e,this.renderCache.isDirty=!0}}applyDocumentChange(i){if(this.renderCache==null)return;const{file:e,result:t}=this.renderCache;if(t!=null&&t.code.length!==i.lineCount){t.code.length=Math.min(t.code.length,i.lineCount);for(let n=t.code.length;n<i.lineCount;n++)t.code.push({type:"element",tagName:"div",properties:{"data-line":n+1,"data-line-type":"context","data-line-index":n},children:[{type:"element",tagName:"span",properties:{"data-char":0},children:[{type:"text",value:i.getLineText(n)}]}]});this.renderCache.isDirty=!0}this.textDoucmentCache.set(e,i)}renderFile(i=this.renderCache?.file,e=Z){if(i==null)return;let{options:t,forceHighlight:n}=this.getRenderOptions(i);const r=this.getMatchingWorkerResultCache(i,t);r!=null&&!this.hasHighlightedRenderCache(i,t)&&(this.renderCache={file:i,highlighted:!0,renderRange:void 0,...r},n=!1),this.renderCache??={file:i,highlighted:!1,options:t,result:void 0,renderRange:void 0};const s=this.getOrCreateLineCache(i),a=i.contents.length>0,o=!a||K(i)||$(s.length,this.getTokenizeMaxLength()),h=!A(i,this.renderCache.file),l=!Se(this.renderCache.renderRange,e);if(this.workerManager?.isWorkingPool()===!0)(o||this.renderCache.result==null||!this.renderCache.highlighted&&(h||l))&&(this.renderCache.file=i,this.renderCache.options=t,this.renderCache.highlighted=!1,(this.renderCache.result==null||h||l||n)&&(this.renderCache.result=this.workerManager.getPlainFileAST(i,e.startingLine,e.totalLines,s)),this.renderCache.renderRange=e),!o&&a&&(!this.renderCache.highlighted||n)&&this.workerManager.highlightFileAST(this,i);else{this.computedLang=i.lang??G(i.name);const d=this.highlighter!=null&&ie(t.theme),u=this.highlighter!=null&&ne(this.computedLang),c=!o&&u;if(this.highlighter!=null&&d&&(n||o||!this.renderCache.highlighted&&c||this.renderCache.result==null)){const{result:p,options:f}=this.renderFileWithHighlighter(i,this.highlighter,o||!u);this.renderCache={file:i,options:f,highlighted:c,result:p,renderRange:void 0}}(!d||!o&&!u)&&this.asyncHighlight(i).then(({result:p,options:f})=>{this.renderCache!=null&&(this.renderCache.highlighted=!1),this.onHighlightSuccess(i,p,f,!o)})}return this.renderCache.result!=null?this.processFileResult(this.renderCache.file,e,this.renderCache.result):void 0}async asyncRender(i,e=Z){const{result:t}=await this.asyncHighlight(i);return this.processFileResult(i,e,t)}async asyncHighlight(i){const e=$(this.getOrCreateLineCache(i).length,this.getTokenizeMaxLength());this.computedLang=e?"text":i.lang??G(i.name);const t=this.highlighter!=null&&St(pt(this.options.theme)),n=e||this.highlighter!=null&&ne(this.computedLang);return(this.highlighter==null||!t||!n)&&(this.highlighter=await this.initializeHighlighter()),this.renderFileWithHighlighter(i,this.highlighter,e)}renderFileWithHighlighter(i,e,t=!1){const{options:n}=this.getRenderOptions(i);return{result:vt(i,e,n,{forcePlainText:t}),options:n}}processFileResult(i,e,{code:t,themeStyles:n,baseThemeType:r}){const s=this.getLineCount(i),{disableFileHeader:a=!1}=this.options,o=[],h=ue(),l=Math.min(e.startingLine+e.totalLines,s);let d=0;const u=ve(e)?De(this.lineAnnotations):void 0;u!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:-1,lineIndex:-1,annotations:u.map(c=>I(c))})),d++);for(let c=e.startingLine;c<l;c++){const p=c+1,f=t[c];if(f==null){const g="FileRenderer.processFileResult: Line doesnt exist";throw console.error(g,{name:i.name,lineIndex:c,lineNumber:p}),new Error(g)}h.children.push(gt("context",p,`${c}`)),o.push(f),d++;const S=this.lineAnnotations[p];S!=null&&(h.children.push(de("context","annotation",1)),o.push(re({hunkIndex:0,lineIndex:p,annotations:S.map(g=>I(g))})),d++)}return h.properties.style=`grid-row: span ${d}`,{gutterAST:h.children??[],contentAST:o,preAST:this.createPreElement(s),headerAST:a?void 0:this.renderHeader(i),totalLines:s,rowCount:d,themeStyles:n,baseThemeType:r,bufferBefore:e.bufferBefore,bufferAfter:e.bufferAfter,css:""}}renderHeader(i){const{headerRenderMode:e="default",stickyHeader:t=!1}=this.options;return Ue({fileOrDiff:i,mode:e,stickyHeader:t})}renderFullHTML(i){return H(this.renderFullAST(i))}renderFullAST(i,e=[]){return e.push(ce({tagName:"code",children:this.renderCodeAST(i),properties:{"data-code":""}})),{...i.preAST,children:e}}renderCodeAST(i){const e=ue();return e.children=i.gutterAST,e.properties.style=`grid-row: span ${i.rowCount}`,[e,_e(i.contentAST,i.rowCount)]}renderPartialHTML(i,e=!1){return e?H(ce({tagName:"code",children:i,properties:{"data-code":""}})):H(i)}async initializeHighlighter(){return this.highlighter=await mt(We(this.computedLang,this.options)),this.highlighter}onHighlightSuccess(i,e,t,n=!0){if(this.renderCache==null)return;const r=!A(i,this.renderCache.file)||!this.renderCache.highlighted||!F(t,this.renderCache.options);this.renderCache={file:i,options:t,highlighted:n,result:e,renderRange:void 0},r&&this.onRenderUpdate?.()}getMatchingWorkerResultCache(i,e){const t=this.workerManager?.getFileResultCache(i);if(!(t==null||!F(e,t.options)))return t}hasHighlightedRenderCache(i,e){const{renderCache:t}=this;return t?.result!=null&&t.highlighted&&A(i,t.file)&&F(e,t.options)}onHighlightError(i){console.error(i)}getTokenizeMaxLength(){return this.options.tokenizeMaxLength??1e5}createPreElement(i){const{disableLineNumbers:e=!1,overflow:t="scroll"}=this.options;return je({type:"file",diffIndicators:"none",disableBackground:!0,disableLineNumbers:e,overflow:t,split:!1,totalLines:i})}};function $(i,e){return i>e}function bt(i,e){return i.lineNumber===e.lineNumber&&i.metadata===e.metadata}function ge(i){return{theme:i?.theme,disableLineNumbers:i?.disableLineNumbers,overflow:i?.overflow,themeType:i?.themeType,collapsed:i?.collapsed,disableFileHeader:i?.disableFileHeader,disableVirtualizationBuffers:i?.disableVirtualizationBuffers,stickyHeader:i?.stickyHeader,preferredHighlighter:i?.preferredHighlighter,useCSSClasses:i?.useCSSClasses,useTokenTransformer:i?.useTokenTransformer,tokenizeMaxLineLength:i?.tokenizeMaxLineLength,tokenizeMaxLength:i?.tokenizeMaxLength,unsafeCSS:i?.unsafeCSS,headerRenderMode:i?.renderCustomHeader!=null?"custom":"default"}}const Rt=[""];let Lt=-1;var Te=class{options;workerManager;isContainerManaged;static LoadedCustomComponent=!0;__id=`file:${++Lt}`;type="file";fileContainer;spriteSVG;pre;code;bufferBefore;bufferAfter;themeCSSStyle;appliedThemeCSS;hasAdoptedThemeCSS=!1;unsafeCSSStyle;appliedUnsafeCSS;gutterUtilityContent;errorWrapper;placeHolder;lastRenderedHeaderHTML;cachedHeaderHTML;appliedPreAttributes;lastRowCount;mounted=!1;headerElement;headerCustom;headerPrefix;headerFilenameSuffix;headerMetadata;fileRenderer;resizeManager;interactionManager;annotationCache=new Map;lineAnnotations=[];managersDirty=!1;file;renderRange;enabled=!0;editor;constructor(e={theme:M},t,n=!1){this.options=e,this.workerManager=t,this.isContainerManaged=n,this.fileRenderer=new Tt(e,this.handleHighlightRender,this.workerManager),this.resizeManager=new Ge,this.interactionManager=new $e("file",se(e)),this.workerManager?.subscribeToThemeChanges(this)}handleHighlightRender=()=>{this.rerender()};rerender(){!this.enabled||this.file==null||this.render({file:this.file,forceRender:!0,renderRange:this.renderRange})}onThemeChange(){this.fileRenderer.clearRenderCache(),this.rerender()}setOptions(e){e!=null&&(this.options=e,this.cachedHeaderHTML=void 0,this.syncInteractionOptions())}syncInteractionOptions(){this.interactionManager.setOptions(se(this.options))}mergeOptions(e){this.options={...this.options,...e}}setThemeType(e){(this.options.themeType??"system")!==e&&(this.mergeOptions({themeType:e}),this.applyCachedThemeState(e))}applyCachedThemeState(e){if(typeof this.options.theme=="string"||this.fileContainer==null||this.appliedThemeCSS==null)return!1;const t=this.appliedThemeCSS.baseThemeType??e;return this.appliedThemeCSS.themeType===t?!1:(this.applyThemeState(this.fileContainer,this.appliedThemeCSS.themeStyles,e,this.appliedThemeCSS.baseThemeType),!0)}hasThemeChanged(){return this.appliedThemeCSS!=null&&!Ct(this.appliedThemeCSS.theme,this.options.theme??M)}getHoveredLine=()=>this.interactionManager.getHoveredLine();setLineAnnotations(e){this.lineAnnotations=e}setSelectedLines(e,t){this.interactionManager.setSelection(e,t)}flushManagers(){if(!this.managersDirty||this.pre==null){this.managersDirty=!1;return}const{overflow:e="scroll"}=this.options;this.interactionManager.setup(this.pre),this.resizeManager.setup(this.pre,e==="wrap"),this.managersDirty=!1}cleanUp(e=!1){this.emitPostRender(!0),this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.managersDirty=!1,this.workerManager?.unsubscribeToThemeChanges(this),this.renderRange=void 0,this.isContainerManaged||this.fileContainer?.remove(),this.fileContainer=void 0,this.mounted=!1,e||(this.lineAnnotations=[]),this.annotationCache.clear(),this.pre=void 0,this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0,this.headerElement=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.lastRenderedHeaderHTML=void 0,e||(this.cachedHeaderHTML=void 0),this.errorWrapper=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.placeHolder=void 0,this.unsafeCSSStyle=void 0,e?this.fileRenderer.recycle():(this.fileRenderer.cleanUp(),this.workerManager=void 0,this.file=void 0),this.enabled=!1,this.editor?.cleanUp(),this.editor=void 0}virtualizedSetup(){this.enabled=!0,this.workerManager?.subscribeToThemeChanges(this)}hydrate(e){const{fileContainer:t,prerenderedHTML:n,preventEmit:r=!1,file:s,lineAnnotations:a}=e;this.hydrateElements(t,n),At(this.pre,s,this.options.collapsed)||Mt(this.headerElement,s,this.options.disableFileHeader)?this.render({...e,preventEmit:!0}):this.hydrationSetup({file:s,lineAnnotations:a}),r||this.emitPostRender()}hydrateElements(e,t){this.fileContainer!==e&&this.emitPostRender(!0),qe(e,t);for(const n of Array.from(e.shadowRoot?.children??[])){if(n instanceof SVGElement){this.spriteSVG=n;continue}if(n instanceof HTMLElement){if(n instanceof HTMLPreElement){this.pre=n,this.appliedPreAttributes=void 0;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-theme-css")){this.themeCSSStyle=n;continue}if(n instanceof HTMLStyleElement&&n.hasAttribute("data-unsafe-css")){this.unsafeCSSStyle=n,this.appliedUnsafeCSS=n.textContent;continue}if("diffsHeader"in n.dataset){this.headerElement=n,this.lastRenderedHeaderHTML=void 0;continue}}}this.pre!=null&&(this.syncCodeNodeFromPre(this.pre),this.pre.removeAttribute("data-dehydrated")),this.fileContainer=e,this.hydrateMeasuredScrollbar()}hydrationSetup({file:e,lineAnnotations:t}){this.lineAnnotations=t??this.lineAnnotations,this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),this.pre!=null&&(this.fileRenderer.hydrate(e),this.renderAnnotations(),this.renderGutterUtility(),this.injectUnsafeCSS(),this.managersDirty=!0,this.flushManagers())}getOrCreateLineCache(e=this.file){return e!=null?this.fileRenderer.getOrCreateLineCache(e):Rt}updateBuffers(e){this.pre!=null&&this.applyBuffers(this.pre,e)}syncRenderViewToEditor(){const e=this.editor,t=this.fileContainer,n=this.file;e!=null&&t!=null&&n!=null&&this.fileRenderer.initializeHighlighter().then(r=>{e.__syncRenderView(r,t,n,this.lineAnnotations,this.renderRange)})}attachEditor(e){return this.editor?.cleanUp(),this.editor=e,this.interactionManager.setEditorAttached(!0),this.syncRenderViewToEditor(),()=>{this.editor=void 0,this.interactionManager.setEditorAttached(!1)}}applyDocumentChange(e,t){this.fileRenderer.applyDocumentChange(e),t!=null&&t!==this.lineAnnotations&&this.file!=null&&(this.setLineAnnotations(t),this.fileRenderer.setLineAnnotations(this.lineAnnotations),this.renderAnnotations())}updateRenderCache(e,t){this.fileRenderer.updateRenderCache(e,t)}render({file:e,fileContainer:t,forceRender:n=!1,preventEmit:r=!1,containerWrapper:s,deferManagers:a=!1,lineAnnotations:o,renderRange:h}){if(!this.enabled)throw new Error("File.render: attempting to call render after cleaned up");this.editor?.__postponeBackgroundTokenizeToNextFrame();const{collapsed:l=!1,themeType:d="system"}=this.options,u=l?void 0:h,c=this.renderRange,p=this.hasThemeChanged(),f=o!=null&&(o.length>0||this.lineAnnotations.length>0)?o!==this.lineAnnotations:!1,S=!A(this.file,e);if(!l&&!n&&Se(u,this.renderRange)&&!S&&!f&&!p)return this.applyCachedThemeState(d);this.renderRange=u,S&&(this.cachedHeaderHTML=void 0),this.file=e,this.fileRenderer.setOptions(ge(this.options)),this.syncInteractionOptions(),o!=null&&this.setLineAnnotations(o),this.fileRenderer.setLineAnnotations(this.lineAnnotations);const{disableErrorHandling:g=!1,disableFileHeader:y=!1}=this.options;if(y&&(this.headerElement!=null&&(this.headerElement.remove(),this.headerElement=void 0,this.lastRenderedHeaderHTML=void 0),this.clearHeaderSlots()),t=this.getOrCreateFileContainerNode(t,s),this.applyCachedThemeState(d),l){this.removeRenderedCode(),this.clearAuxiliaryNodes();try{const m=this.fileRenderer.renderFile(e,Fe);m!=null&&this.applyThemeState(t,m.themeStyles,d,m.baseThemeType),m?.headerAST!=null&&this.applyHeaderToDOM(m.headerAST,t),this.injectUnsafeCSS()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}try{const m=this.getOrCreatePreNode(t);if(!this.canPartiallyRender(n,f,S||p)||!this.applyPartialRender(c,u)){const v=this.fileRenderer.renderFile(e,u);if(v==null)return this.workerManager?.isInitialized()===!1&&this.workerManager.initialize().then(()=>this.rerender()),!1;this.applyThemeState(t,v.themeStyles,d,v.baseThemeType),v.headerAST!=null&&this.applyHeaderToDOM(v.headerAST,t),this.applyFullRender(v,m)}this.applyBuffers(m,u),this.injectUnsafeCSS(),this.managersDirty=!0,a||this.flushManagers(),this.renderAnnotations(),this.renderGutterUtility(),this.editor!=null&&this.syncRenderViewToEditor()}catch(m){if(g)throw m;console.error(m),m instanceof Error&&this.applyErrorToDOM(m,t)}return r||this.emitPostRender(),!0}emitPostRender(e=!1){const{fileContainer:t,options:{onPostRender:n}}=this;if(e){if(!this.mounted||(this.mounted=!1,t==null))return;n?.(t,this,"unmount");return}if(t==null)return;const r=this.mounted?"update":"mount";this.mounted=!0,n?.(t,this,r)}removeRenderedCode(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferBefore?.remove(),this.bufferBefore=void 0,this.bufferAfter?.remove(),this.bufferAfter=void 0,this.code?.remove(),this.code=void 0,this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0,this.lastRowCount=void 0}clearAuxiliaryNodes(){for(const{element:e}of this.annotationCache.values())e.remove();this.annotationCache.clear(),this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0}canPartiallyRender(e,t,n){return!(e||t||n)}renderPlaceholder(e){if(this.fileContainer==null)return!1;if(this.emitPostRender(!0),this.cleanChildNodes(),this.placeHolder==null){const t=this.fileContainer.shadowRoot??this.fileContainer.attachShadow({mode:"open"});this.placeHolder=document.createElement("div"),this.placeHolder.dataset.placeholder="",t.appendChild(this.placeHolder)}return this.placeHolder.style.setProperty("height",`${e}px`),!0}primeHighlightCache(){const{file:e,workerManager:t}=this;e==null||e.cacheKey==null||t==null||K(e)||this.fileRenderer.getOrCreateLineCache(e).length>(this.options.tokenizeMaxLength??1e5)||t.primeFileHighlightCache(e)}cleanChildNodes(){this.resizeManager.cleanUp(),this.interactionManager.cleanUp(),this.bufferAfter?.remove(),this.bufferBefore?.remove(),this.code?.remove(),this.errorWrapper?.remove(),this.headerElement?.remove(),this.gutterUtilityContent?.remove(),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.pre?.remove(),this.spriteSVG?.remove(),this.themeCSSStyle?.remove(),this.unsafeCSSStyle?.remove(),this.bufferAfter=void 0,this.bufferBefore=void 0,this.code=void 0,this.errorWrapper=void 0,this.headerElement=void 0,this.gutterUtilityContent=void 0,this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0,this.pre=void 0,this.spriteSVG=void 0,this.themeCSSStyle=void 0,this.appliedThemeCSS=void 0,this.hasAdoptedThemeCSS=!1,this.unsafeCSSStyle=void 0,this.appliedUnsafeCSS=void 0,this.lastRenderedHeaderHTML=void 0,this.lastRowCount=void 0,this.mounted=!1}renderAnnotations(){if(this.isContainerManaged||this.fileContainer==null){for(const{element:n}of this.annotationCache.values())n.remove();this.annotationCache.clear();return}const e=new Map(this.annotationCache),{renderAnnotation:t}=this.options;if(t!=null&&this.lineAnnotations.length>0)for(const[n,r]of this.lineAnnotations.entries()){const s=`${n}-${I(r)}`;let a=this.annotationCache.get(s);if(a==null||!bt(r,a.annotation)){a?.element.remove();const o=t(r);if(o==null)continue;a={element:Ke(I(r)),annotation:r},a.element.appendChild(o),this.fileContainer.appendChild(a.element),this.annotationCache.set(s,a)}e.delete(s)}for(const[n,{element:r}]of e.entries())this.annotationCache.delete(n),r.remove()}renderGutterUtility(){const{renderGutterUtility:e}=this.options;if(this.fileContainer==null||e==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const t=e(this.interactionManager.getHoveredLine);if(t!=null&&this.gutterUtilityContent!=null)return;if(t==null){this.gutterUtilityContent?.remove(),this.gutterUtilityContent=void 0;return}const n=Je();n.appendChild(t),this.fileContainer.appendChild(n),this.gutterUtilityContent=n}injectUnsafeCSS(){const{unsafeCSS:e}=this.options,t=this.fileContainer?.shadowRoot;if(t!=null){if(e==null||e===""){this.unsafeCSSStyle!=null&&(this.unsafeCSSStyle.remove(),this.unsafeCSSStyle=void 0),this.appliedUnsafeCSS=void 0;return}this.unsafeCSSStyle?.parentNode===t&&this.appliedUnsafeCSS===e||(this.unsafeCSSStyle??=Ye(),this.unsafeCSSStyle.parentNode!==t&&t.appendChild(this.unsafeCSSStyle),this.unsafeCSSStyle.textContent=Xe(e),this.appliedUnsafeCSS=e)}}applyThemeState(e,t,n,r){const s=e.shadowRoot??e.attachShadow({mode:"open"}),a=r??n,o=this.options.theme??M,h=typeof o=="string"?o:{...o},l=ae(s);if(this.themeCSSStyle?.parentNode===s&&this.appliedThemeCSS?.themeStyles===t&&this.appliedThemeCSS.themeType===a&&this.appliedThemeCSS.scrollbarGutter===l){this.appliedThemeCSS.theme=h;return}if(this.hasAdoptedThemeCSS&&this.themeCSSStyle?.parentNode===s){this.hasAdoptedThemeCSS=!1,this.appliedThemeCSS={theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:l};return}this.themeCSSStyle=Qe({shadowRoot:s,currentNode:this.themeCSSStyle,themeCSS:Ze(t,a,l)}),this.appliedThemeCSS=this.themeCSSStyle!=null?{theme:h,themeStyles:t,themeType:a,baseThemeType:r,scrollbarGutter:l}:void 0}hydrateMeasuredScrollbar(){const e=this.fileContainer?.shadowRoot;e==null||this.themeCSSStyle==null||(this.themeCSSStyle.textContent=et(this.themeCSSStyle.textContent??"",ae(e)))}applyFullRender(e,t){this.cleanupErrorWrapper(),this.applyPreNodeAttributes(t,e),this.code=tt({code:this.code});const n=this.fileRenderer.renderCodeAST(e);if(this.code.childElementCount>=2)for(let r=0;r<2;r++){const s=this.code.children[r],a=n[r];s.innerHTML=H(a.children),s.style.cssText=a.properties.style}else this.code.innerHTML=H(n);t.contains(this.code)||t.replaceChildren(this.code),this.lastRowCount=e.rowCount}applyPartialRender(e,t){if(e==null||t==null)return!1;const{file:n,code:r}=this,s=r!=null?this.getColumns(r):void 0;if(n==null||r==null||s==null)return!1;const a=e.startingLine,o=t.startingLine,h=e.totalLines===1/0?Number.POSITIVE_INFINITY:a+e.totalLines,l=t.totalLines===1/0?Number.POSITIVE_INFINITY:o+t.totalLines,d=Math.max(a,o),u=Math.min(h,l);if(u<=d||!this.trimDOMToOverlap(s.gutter,d,u)||!this.trimDOMToOverlap(s.content,d,u))return!1;let{length:c}=s.content.children;const p=(y,m)=>{if(!(m<=0))return this.fileRenderer.renderFile(n,{startingLine:y,totalLines:m,bufferBefore:0,bufferAfter:0})},f=o<d?p(o,d-o):void 0;if(f===void 0&&o<d)return!1;const S=l===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:Math.max(0,l-u),g=l>u?p(u,S):void 0;return g===void 0&&l>u?!1:(this.cleanupErrorWrapper(),f!=null&&(s.gutter.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.gutterAST)),s.content.insertAdjacentHTML("afterbegin",this.fileRenderer.renderPartialHTML(f.contentAST)),c+=f.rowCount),g!=null&&(s.gutter.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.gutterAST)),s.content.insertAdjacentHTML("beforeend",this.fileRenderer.renderPartialHTML(g.contentAST)),c+=g.rowCount),this.lastRowCount!==c&&(s.gutter.style.setProperty("grid-row",`span ${c}`),s.content.style.setProperty("grid-row",`span ${c}`),this.lastRowCount=c),!0)}getColumns(e){const t=e.children[0],n=e.children[1];if(!(!(t instanceof HTMLElement)||!(n instanceof HTMLElement)||t.dataset.gutter==null||n.dataset.content==null))return{gutter:t,content:n}}trimDOMToOverlap(e,t,n){const r=this.getDOMBoundaryIndices(e,[t,n]),s=r.get(t)??e.children.length,a=r.get(n)??e.children.length;if(s>a)return!1;for(let o=e.children.length-1;o>=a;o-=1)e.children[o]?.remove();for(let o=s-1;o>=0;o-=1)e.children[o]?.remove();return!0}getDOMBoundaryIndices(e,t){const n=[...new Set(t)].sort((h,l)=>h-l),r=new Map;if(n.length===0)return r;let s=0,a=n[s];const{children:o}=e;a===0&&(r.set(0,0),s+=1,a=n[s]);for(let h=0;h<o.length;h+=1){const l=o[h];if(!(l instanceof HTMLElement))continue;const d=this.getLineIndexFromDOMNode(l);if(d!=null){for(;a!=null&&d>=a;)r.set(a,h),s+=1,a=n[s];if(s>=n.length)break}}for(const h of n)r.has(h)||r.set(h,o.length);return r}getLineIndexFromDOMNode(e){const t=e.dataset.lineIndex;if(t==null)return;const n=Number(t);return Number.isNaN(n)?void 0:n}applyBuffers(e,t){if(t==null||this.shouldDisableVirtualizationBuffers()){this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0);return}t.bufferBefore>0?(this.bufferBefore==null&&(this.bufferBefore=document.createElement("div"),this.bufferBefore.dataset.virtualizerBuffer="before",e.before(this.bufferBefore)),this.bufferBefore.style.setProperty("height",`${t.bufferBefore}px`),this.bufferBefore.style.setProperty("contain","strict")):this.bufferBefore!=null&&(this.bufferBefore.remove(),this.bufferBefore=void 0),t.bufferAfter>0?(this.bufferAfter==null&&(this.bufferAfter=document.createElement("div"),this.bufferAfter.dataset.virtualizerBuffer="after",e.after(this.bufferAfter)),this.bufferAfter.style.setProperty("height",`${t.bufferAfter}px`),this.bufferAfter.style.setProperty("contain","strict")):this.bufferAfter!=null&&(this.bufferAfter.remove(),this.bufferAfter=void 0)}shouldDisableVirtualizationBuffers(){return this.options.disableVirtualizationBuffers??!1}applyHeaderToDOM(e,t){const{file:n}=this;if(n==null)return;this.cleanupErrorWrapper(),this.placeHolder?.remove(),this.placeHolder=void 0;const r=this.cachedHeaderHTML??H(e);if(this.cachedHeaderHTML=r,r!==this.lastRenderedHeaderHTML){const l=document.createElement("div");l.innerHTML=r;const d=l.firstElementChild;if(!(d instanceof HTMLElement))return;this.headerElement!=null?t.shadowRoot?.replaceChild(d,this.headerElement):t.shadowRoot?.prepend(d),this.headerElement=d,this.lastRenderedHeaderHTML=r}if(this.isContainerManaged)return;const{renderHeaderPrefix:s,renderHeaderFilenameSuffix:a,renderCustomHeader:o,renderHeaderMetadata:h}=this.options;if(o!=null){const l=o(n)??void 0;this.headerCustom=this.upsertHeaderSlotElement(t,this.headerCustom,Ce,l),this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0}else{const l=s?.(n)??void 0,d=a?.(n)??void 0,u=h?.(n)??void 0;this.headerPrefix=this.upsertHeaderSlotElement(t,this.headerPrefix,ke,l),this.headerFilenameSuffix=this.upsertHeaderSlotElement(t,this.headerFilenameSuffix,Ie,d),this.headerMetadata=this.upsertHeaderSlotElement(t,this.headerMetadata,ze,u),this.headerCustom?.remove(),this.headerCustom=void 0}}clearHeaderSlots(){this.headerPrefix?.remove(),this.headerFilenameSuffix?.remove(),this.headerMetadata?.remove(),this.headerCustom?.remove(),this.headerPrefix=void 0,this.headerFilenameSuffix=void 0,this.headerMetadata=void 0,this.headerCustom=void 0}upsertHeaderSlotElement(e,t,n,r){if(r==null){t?.remove();return}const s=t??this.createHeaderSlotElement(n);return t==null&&e.appendChild(s),this.replaceHeaderSlotContent(s,r),s}replaceHeaderSlotContent(e,t){e.replaceChildren(),t instanceof Element?e.appendChild(t):e.innerText=`${t}`}createHeaderSlotElement(e){const t=document.createElement("div");return t.slot=e,t}getOrCreateFileContainerNode(e,t){const{fileContainer:n}=this,r=e??n??document.createElement("diffs-container"),s=n!==r;return s&&this.emitPostRender(!0),this.fileContainer=r,n!=null&&s&&(this.lastRenderedHeaderHTML=void 0,this.headerElement=void 0),t!=null&&this.fileContainer.parentNode!==t&&t.appendChild(this.fileContainer),s&&this.adoptReusableShellElements(this.fileContainer),this.ensureSpriteSVG(this.fileContainer),this.fileContainer}adoptReusableShellElements(e){const{shadowRoot:t}=e;if(t!=null)for(const n of t.children)n instanceof SVGElement?this.spriteSVG??=n:oe(n)&&n.hasAttribute("data-theme-css")?(this.themeCSSStyle??=n,this.hasAdoptedThemeCSS=!0):oe(n)&&n.hasAttribute("data-unsafe-css")&&(this.unsafeCSSStyle??=n,this.appliedUnsafeCSS??=this.options.unsafeCSS??void 0)}ensureSpriteSVG(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});if(this.spriteSVG==null){const n=document.createElement("div");n.innerHTML=it;const r=n.firstChild;r instanceof SVGElement&&(this.spriteSVG=r)}this.spriteSVG!=null&&this.spriteSVG.parentNode!==t&&t.appendChild(this.spriteSVG)}getOrCreatePreNode(e){const t=e.shadowRoot??e.attachShadow({mode:"open"});return this.pre==null?(this.pre=document.createElement("pre"),this.appliedPreAttributes=void 0,this.code=void 0,t.appendChild(this.pre)):this.pre.parentNode!==t&&(e.shadowRoot?.appendChild(this.pre),this.appliedPreAttributes=void 0),this.placeHolder?.remove(),this.placeHolder=void 0,this.pre}syncCodeNodeFromPre(e){this.code=void 0;for(const t of Array.from(e.children))if(t instanceof HTMLElement&&t.hasAttribute("data-code")){this.code=t;return}}applyPreNodeAttributes(e,{totalLines:t}){const{overflow:n="scroll",disableLineNumbers:r=!1}=this.options,s={type:"file",split:!1,overflow:n,disableLineNumbers:r,diffIndicators:"none",disableBackground:!0,totalLines:t};nt(s,this.appliedPreAttributes)||(rt(e,s),this.appliedPreAttributes=s)}applyErrorToDOM(e,t){this.cleanupErrorWrapper(),this.pre?.remove(),this.pre=void 0,this.appliedPreAttributes=void 0;const n=t.shadowRoot??t.attachShadow({mode:"open"});this.errorWrapper??=document.createElement("div"),this.errorWrapper.dataset.errorWrapper="",this.errorWrapper.textContent="",n.appendChild(this.errorWrapper);const r=document.createElement("div");r.dataset.errorMessage="",r.innerText=e.message,this.errorWrapper.appendChild(r);const s=document.createElement("pre");s.dataset.errorStack="",s.innerText=e.stack??"No Error Stack",this.errorWrapper.appendChild(s)}cleanupErrorWrapper(){this.errorWrapper?.remove(),this.errorWrapper=void 0}};function At(i,e,t=!1){return!t&&i==null&&e!=null}function Mt(i,e,t=!1){return i==null&&e!=null&&!t}const Ht=5e3;let xt=-1;function wt(i,e){return(i.overflow??"scroll")!==(e.overflow??"scroll")||(i.collapsed??!1)!==(e.collapsed??!1)||(i.disableLineNumbers??!1)!==(e.disableLineNumbers??!1)||(i.disableFileHeader??!1)!==(e.disableFileHeader??!1)||i.unsafeCSS!==e.unsafeCSS}var Et=class extends Te{virtualizer;metrics;__id=`virtualized-file:${++xt}`;top;height=0;cache={heights:new Map,checkpoints:[],fileAnnotationHeight:0};isVisible=!1;isSetup=!1;layoutDirty=!0;forceRenderOverride;currentCollapsed;constructor(i,e,t=Ne,n,r=!1){super(i,n,r),this.virtualizer=e,this.metrics=t}setMetrics(i,e=!1){!e&&st(this.metrics,i)||(this.metrics=i,this.resetLayoutCache())}setLineAnnotations(i){this.syncLineAnnotations(i)&&this.resetLayoutCache()}syncLineAnnotations(i){return i==null||i===this.lineAnnotations||i.length===0&&this.lineAnnotations.length===0?!1:(super.setLineAnnotations(i),!0)}hasLineAnnotations(){return this.lineAnnotations.some(i=>i.lineNumber>0)}getLineHeight(i,e=!1){const t=this.cache.heights.get(i);if(t!=null)return t;const n=e?2:1;return this.metrics.lineHeight*n}setOptions(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setOptions cannot be used inside CodeView. Update CodeView options instead.");if(i==null)return;const{options:e}=this,t=!ye(e,i),n=wt(e,i);super.setOptions(i),n&&this.resetLayoutCache(!0),t&&(this.forceRenderOverride=!0),t&&this.virtualizer.instanceChanged(this,n)}setThemeType(i){if(this.isAdvancedMode())throw new Error("VirtualizedFile.setThemeType cannot be used inside CodeView. Update CodeView options instead.");super.setThemeType(i)}resetLayoutCache(i=!1){this.layoutDirty=!0,this.cache.fileAnnotationHeight=0,this.cache.heights.size>0&&this.cache.heights.clear(),this.cache.checkpoints.length>0&&(this.cache.checkpoints.length=0),this.renderRange!=null&&(this.renderRange=void 0),i&&this.isSimpleMode()&&this.computeApproximateSize()}reconcileHeights(){let i=!1;if(this.fileContainer==null||this.file==null)return this.height!==0&&(i=!0),this.height=0,i;const{overflow:e="scroll"}=this.options;if(this.top=this.getVirtualizedTop(),e==="scroll"&&this.lineAnnotations.length===0&&!this.isResizeDebuggingEnabled()||this.code==null)return i;const t=this.code.children[1];if(!(t instanceof HTMLElement))return i;const n=he(this.lineAnnotations);if(this.renderRange!=null&&n&&ve(this.renderRange)){const r=Ft(t)??0;r!==this.cache.fileAnnotationHeight&&(this.cache.fileAnnotationHeight=r,i=!0)}else!n&&this.cache.fileAnnotationHeight!==0&&(this.cache.fileAnnotationHeight=0,i=!0);for(const r of t.children){if(!(r instanceof HTMLElement))continue;const s=r.dataset.lineIndex;if(s==null)continue;const a=Number(s);let o=r.getBoundingClientRect().height,h=!1;r.nextElementSibling instanceof HTMLElement&&("lineAnnotation"in r.nextElementSibling.dataset||"noNewline"in r.nextElementSibling.dataset)&&("noNewline"in r.nextElementSibling.dataset&&(h=!0),o+=r.nextElementSibling.getBoundingClientRect().height);const l=this.getLineHeight(a,h);o!==l&&(i=!0,o===this.metrics.lineHeight*(h?2:1)?this.cache.heights.delete(a):this.cache.heights.set(a,o))}return(i||this.isResizeDebuggingEnabled())&&this.computeApproximateSize(!0),i}onRender=i=>this.fileContainer==null||this.file==null?!1:(i&&(this.top=this.getVirtualizedTop()),this.render({file:this.file}));prepareCodeViewItem(i,e,t,n){const r=this.syncLineAnnotations(n);let s=t?.resetFileLayoutCache===!0||r;t?.metrics!=null&&(this.metrics=t.metrics,s=!0);const{collapsed:a=!1}=this.options;return this.currentCollapsed!==a&&(this.currentCollapsed=a,s=!0),s&&this.resetLayoutCache(),this.file!==i&&(this.layoutDirty=!0),this.file=i,this.top=e,this.computeApproximateSize(),this.height}getLinePosition(i){if(this.file==null||i<1)return;const{disableFileHeader:e=!1,collapsed:t=!1}=this.options,n=this.fileRenderer.getLineCount(this.file)-1;let r=B(this.metrics,e);if(t||n<0)return{top:r,height:0};const s=Math.min(Math.max(i-1,0),n),{overflow:a="scroll"}=this.options,{lineHeight:o}=this.metrics;if(r+=this.cache.fileAnnotationHeight,a==="scroll"&&!this.hasLineAnnotations())return{top:r+s*o,height:o};const h=this.getLayoutCheckpointBeforeLineIndex(s);r=h?.top??r;for(let l=h?.lineIndex??0;l<s;l++)r+=this.getLineHeight(l,!1);return{top:r,height:this.getLineHeight(s,!1)}}getNumericScrollAnchor(i){if(this.file==null||this.renderRange==null)return;const{disableFileHeader:e=!1,collapsed:t=!1,overflow:n="scroll"}=this.options;if(t||this.renderRange.totalLines<=0)return;const r=this.fileRenderer.getLineCount(this.file)-1;if(r<0)return;const s=B(this.metrics,e),a=Math.min(this.renderRange.startingLine,r),o=Math.min(a+this.renderRange.totalLines-1,r);if(o<a)return;const{fileAnnotationHeight:h}=this.cache;if(n==="scroll"&&!this.hasLineAnnotations()){const{lineHeight:d}=this.metrics,u=s+(a===0?h:this.renderRange.bufferBefore),c=a+Math.max(Math.ceil((i-u)/d),0);return c>o?void 0:{lineNumber:c+1,top:s+h+c*d}}let l=s+(a===0?h:this.renderRange.bufferBefore);for(let d=a;d<=o;d++){if(l>=i)return{lineNumber:d+1,top:l};l+=this.getLineHeight(d)}}getVirtualizedHeight(){return this.height}getAdvancedStickySpecs(i){if(this.top==null||this.file==null)return;if(this.options.collapsed===!0)return{topOffset:this.top,height:this.height};const e=i!=null?this.computeRenderRangeFromWindow(this.file,this.top,i):this.renderRange;if(e==null)return;const{bufferBefore:t,bufferAfter:n,totalLines:r}=e;let s=0;if(r===0){const a=i??this.virtualizer.getWindowSpecs();this.top<a.top&&(s=n)}return{topOffset:this.top+t+s,height:this.height-(t+n)}}cleanUp(i=!1){this.fileContainer!=null&&this.isSimpleMode()&&this.getSimpleVirtualizer()?.disconnect(this.fileContainer),i||this.resetLayoutCache(),this.isSetup=!1,super.cleanUp(i)}computeApproximateSize(i=!1){const e=this.isResizeDebuggingEnabled();if(!i&&!this.layoutDirty&&!e)return;const t=this.height===0;if(this.height=0,this.cache.checkpoints=[],this.file==null){this.layoutDirty=!1;return}const{disableFileHeader:n=!1,collapsed:r=!1,overflow:s="scroll"}=this.options,{lineHeight:a}=this.metrics,o=this.fileRenderer.getLineCount(this.file),h=B(this.metrics,n),l=fe(this.metrics);if(this.height+=h,r){this.layoutDirty=!1;return}if(this.height+=this.cache.fileAnnotationHeight,s==="scroll"&&!this.hasLineAnnotations())this.height+=o*a;else for(let d=0;d<o;d++)this.addLayoutCheckpoint(d,this.height),this.height+=this.getLineHeight(d,!1);if(o>0&&(this.height+=l),this.fileContainer!=null&&e&&!t){const d=this.fileContainer.getBoundingClientRect();d.height!==this.height?console.log("VirtualizedFile.computeApproximateSize: computed height doesnt match",{name:this.file.name,elementHeight:d.height,computedHeight:this.height}):console.log("VirtualizedFile.computeApproximateSize: computed height IS CORRECT")}this.layoutDirty=!1}setVisibility(i){this.isAdvancedMode()||this.fileContainer==null||(i&&!this.isVisible?(this.top=this.getVirtualizedTop(),this.isVisible=!0):!i&&this.isVisible&&(this.isVisible=!1,this.rerender()))}rerender(){!this.enabled||this.file==null||(this.forceRenderOverride=!0,this.virtualizer.instanceChanged(this,!1))}applyDocumentChange(i,e,t=!1){const{heights:n,checkpoints:r}=this.cache,s=this.renderRange;if(super.applyDocumentChange(i,e),this.getSimpleVirtualizer()?.markDOMDirty(),this.layoutDirty=!0,n.size>0&&n.clear(),r.length>0&&(r.length=0),this.isSimpleMode()&&this.computeApproximateSize(),t&&s!==void 0&&this.file!==void 0){const a=this.virtualizer.getWindowSpecs(),o=this.computeRenderRangeFromWindow(this.file,this.top??0,a);o.bufferAfter!==s.bufferAfter&&this.updateBuffers(o)}}render({fileContainer:i,file:e,forceRender:t=!1,lineAnnotations:n,...r}){const s=this.file==null||!A(this.file,e),{forceRenderOverride:a,isSetup:o}=this;this.forceRenderOverride=void 0;const h=this.syncLineAnnotations(n);if(h&&this.resetLayoutCache(),this.file=e,i=this.getOrCreateFileContainerNode(i),this.file==null)return console.error("VirtualizedFile.render: attempting to virtually render when we dont have file"),!1;if(o)this.top??=this.getVirtualizedTop(),s&&this.isSimpleMode()&&(this.getSimpleVirtualizer()?.markDOMDirty(),this.resetLayoutCache(!0));else{this.computeApproximateSize();const c=this.getSimpleVirtualizer();if(this.top??=this.getVirtualizedTop(),this.isAdvancedMode())this.isVisible=!0;else{if(c==null)throw new Error("VirtualizedFile.render: simple virtualizer is not available");c.connect(i,this),this.isVisible=c.isInstanceVisible(this.top??0,this.height)}this.isSetup=!0}if(!this.isVisible&&this.isSimpleMode())return this.renderPlaceholder(this.height);const l=this.virtualizer.getWindowSpecs(),d=this.top??0,u=this.computeRenderRangeFromWindow(this.file,d,l);return super.render({file:this.file,fileContainer:i,renderRange:u,lineAnnotations:n,forceRender:(a??t)||h,...r})}syncVirtualizedTop(){this.top=this.getVirtualizedTop()}shouldDisableVirtualizationBuffers(){return this.isAdvancedMode()||super.shouldDisableVirtualizationBuffers()}isSimpleMode(){return this.virtualizer.type==="simple"}isAdvancedMode(){return this.virtualizer.type==="advanced"}addLayoutCheckpoint(i,e){i%Ht===0&&this.cache.checkpoints.push({lineIndex:i,top:e})}getLayoutCheckpointBeforeLineIndex(i){if(i<=0||this.cache.checkpoints.length===0)return;let e=0,t=this.cache.checkpoints.length-1,n;for(;e<=t;){const r=e+t>>1,s=this.cache.checkpoints[r];if(s==null)throw new Error("VirtualizedFile: invalid checkpoint index");s.lineIndex<=i?(n=s,e=r+1):t=r-1}return n}getLayoutCheckpointBeforeTop(i,e){let t=0,n=this.cache.checkpoints.length-1,r=-1;for(;t<=n;){const s=t+n>>1,a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");a.top<=i?(r=s,t=s+1):n=s-1}if(e==null)return r>=0?this.cache.checkpoints[r]:void 0;for(let s=r;s>=0;s--){const a=this.cache.checkpoints[s];if(a==null)throw new Error("VirtualizedFile: invalid checkpoint index");if(a.lineIndex%e===0)return a}}getVirtualizedTop(){return this.virtualizer.type==="advanced"?this.virtualizer.getLocalTopForInstance(this):this.fileContainer!=null?this.virtualizer.getOffsetInScrollContainer(this.fileContainer):0}getSimpleVirtualizer(){return this.virtualizer.type==="simple"?this.virtualizer:void 0}isResizeDebuggingEnabled(){return this.getSimpleVirtualizer()?.config.resizeDebugging??!1}computeRenderRangeFromWindow(i,e,{top:t,bottom:n}){const{disableFileHeader:r=!1,overflow:s="scroll"}=this.options,{hunkLineCount:a,lineHeight:o}=this.metrics,h=this.fileRenderer.getLineCount(i),l=this.height,d=B(this.metrics,r),u=h>0?fe(this.metrics):0,{fileAnnotationHeight:c}=this.cache,p=d+c,f=Math.max(0,l-d-c-u),S=he(this.lineAnnotations),g=e+d,y=c>0&&S&&g<n&&g+c>t;if(e<t-l||e>n)return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:l-d-u};if(h<=a)return{startingLine:0,totalLines:a,bufferBefore:0,bufferAfter:0};const m=Math.ceil(Math.max(n-t,0)/o),v=Math.ceil(m/a)*a+a*2,z=v/a,D=(t+n)/2;if(s==="scroll"&&!this.hasLineAnnotations()){const R=e+p,P=R+f;if(!y&&!(R<n&&P>t))return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:l-d-u};const w=Math.floor(y&&D<e+p?0:(D-(e+p))/o),b=Math.floor(w/a)-Math.floor(z/2),xe=Math.ceil(h/a),E=Math.max(0,Math.min(b,xe))*a,Q=b<0?v+b*a:v,we=E===0?0:c+E*o,Ee=Math.min(Q,h-E);return{startingLine:E,totalLines:Q,bufferBefore:we,bufferAfter:Math.max(0,(h-E-Ee)*o)}}const be=z,N=[],U=this.getLayoutCheckpointBeforeTop(Math.max(0,t-e-v*o*2),a);let T=e+(U?.top??p),_=U?.lineIndex??0,V,O,x;const Re=U?.lineIndex??0;for(let R=Re;R<h;R++){const P=_%a===0,w=Math.floor(_/a);if(P&&(N[w]=T-(e+p),x!=null)){if(x<=0)break;x--}const b=this.getLineHeight(R,!1);T>t-b&&T<n&&(V??=w),T+b>D&&(O??=w),x==null&&T>=n&&P&&(x=be),_++,T+=b}if(V==null)if(y)V=0,O=0;else return{startingLine:0,totalLines:0,bufferBefore:0,bufferAfter:l-d-u};O??=V;const W=Math.round(O-z/2),Le=Math.max(0,Math.ceil(h/a)-z),j=Math.max(0,Math.min(W,Le)),J=j*a,Y=W<0?v+W*a:v,Ae=N[j]??0,Me=J===0?0:c+Ae,X=j+Y/a,He=X<N.length?f-N[X]:f-(T-e-p);return{startingLine:J,totalLines:Y,bufferBefore:Me,bufferAfter:Math.max(0,He)}}};function Ft(i){let e;for(const t of i.children)t instanceof HTMLElement&&t.dataset.lineAnnotation===at&&(e=Math.max(e??0,t.getBoundingClientRect().height));return e}function kt({file:i,renderCustomHeader:e,renderHeaderPrefix:t,renderHeaderFilenameSuffix:n,renderHeaderMetadata:r,renderAnnotation:s,lineAnnotations:a,renderGutterUtility:o,getHoveredLine:h}){const l=e?.(i),d=t?.(i),u=n?.(i),c=r?.(i);return C.jsxs(C.Fragment,{children:[l!=null?C.jsx("div",{slot:Ce,children:l}):C.jsxs(C.Fragment,{children:[d!=null&&C.jsx("div",{slot:"header-prefix",children:d}),u!=null&&C.jsx("div",{slot:"header-filename-suffix",children:u}),c!=null&&C.jsx("div",{slot:"header-metadata",children:c})]}),s!=null&&a?.map((p,f)=>C.jsx("div",{slot:I(p),children:s(p)},f)),o!=null&&C.jsx("div",{slot:"gutter-utility-slot",style:ot,children:o(h)})]})}const me=typeof window>"u"?k.useEffect:k.useLayoutEffect;function It({file:i,options:e,lineAnnotations:t,selectedLines:n,prerenderedHTML:r,metrics:s,hasGutterRenderUtility:a,hasCustomHeader:o,disableWorkerPool:h,contentEditable:l}){const d=ht(),u=n!==void 0,c=k.useContext(lt),p=dt(),f=k.useRef(null),S=ct(g=>{if(g!=null){if(f.current!=null)throw new Error("File: An instance should not already exist when a node is created");d!=null?f.current=new Et(q({controlledSelection:u,contentEditable:l,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),d,s,h?void 0:c,!0):f.current=new Te(q({controlledSelection:u,contentEditable:l,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),h?void 0:c,!0),f.current.hydrate({file:i,fileContainer:g,lineAnnotations:t,prerenderedHTML:r})}else{if(f.current==null)throw new Error("File: A File instance should exist when unmounting");f.current.cleanUp(),f.current=null}});return me(()=>{if(f.current==null)return;const g=q({controlledSelection:u,contentEditable:l,hasCustomHeader:o,hasEditor:p!==void 0,hasGutterRenderUtility:a,options:e}),y=!ye(f.current.options,g);f.current.setOptions(g),f.current.render({file:i,lineAnnotations:t,forceRender:y}),n!==void 0&&f.current.setSelectedLines(n)}),me(()=>{if(l&&f.current!=null){if(p===void 0)throw new Error("File: Editor is not attached");return p.edit(f.current)}},[l,p]),{ref:S,getHoveredLine:k.useCallback(()=>f.current?.getHoveredLine(),[])}}function q({options:i,controlledSelection:e,contentEditable:t,hasCustomHeader:n,hasEditor:r,hasGutterRenderUtility:s}){const a=t&&r,o=e||s||n;if(!o&&!a)return i;let h={...i};return o&&(h={...h,controlledSelection:e,renderCustomHeader:n?le:i?.renderCustomHeader,renderGutterUtility:s?le:i?.renderGutterUtility}),a&&(h={...h,useTokenTransformer:!0,enableGutterUtility:!1,enableLineSelection:!1,lineHoverHighlight:"disabled"}),h}function _t({file:i,lineAnnotations:e,selectedLines:t,options:n,metrics:r,className:s,style:a,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:l,renderHeaderFilenameSuffix:d,renderHeaderMetadata:u,prerenderedHTML:c,renderGutterUtility:p,disableWorkerPool:f=!1,contentEditable:S=!1}){const{ref:g,getHoveredLine:y}=It({file:i,options:n,metrics:r,lineAnnotations:e,selectedLines:t,prerenderedHTML:c,hasGutterRenderUtility:p!=null,hasCustomHeader:h!=null,disableWorkerPool:f,contentEditable:S});return C.jsx(Ve,{ref:g,className:s,style:a,children:ut(kt({file:i,renderAnnotation:o,renderCustomHeader:h,renderHeaderPrefix:l,renderHeaderFilenameSuffix:d,renderHeaderMetadata:u,renderGutterUtility:p,lineAnnotations:e,getHoveredLine:y}),c)})}const Wt=L.memo(function({jsonString:e,className:t,maxHeight:n="100%",initiallyExpandedDepth:r=2}){const{t:s}=Oe(),a=L.useRef(null),[o,h]=L.useState(null),l=L.useMemo(()=>{try{const c=e.trim();if(!c)return h(s("jsonTreeView.error.emptyJson")),null;const p=JSON.parse(c);return h(null),p}catch(c){return h(c instanceof Error?c.message:s("jsonTreeView.error.invalidJson")),null}},[e,s]),d=L.useCallback(()=>{a.current?.expandAll()},[]),u=L.useCallback(()=>{a.current?.collapseAll()},[]);return o?C.jsx("div",{className:t,children:C.jsxs("div",{className:"rounded-md border border-[var(--interactive-border)] bg-[var(--syntax-base-background)] p-4",children:[C.jsx("div",{className:"mb-1 font-medium text-[var(--surface-foreground)]",children:s("jsonTreeView.error.invalidJsonTitle")}),C.jsx("div",{className:"font-mono text-xs text-[var(--surface-mutedForeground)]",children:o})]})}):l===null?null:C.jsxs("div",{className:t,children:[C.jsxs("div",{className:"flex items-center gap-1 border-b border-[var(--interactive-border)] px-2 py-1",children:[C.jsxs(ee,{variant:"ghost",size:"xs",onClick:d,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-down-s",className:"h-3 w-3"}),s("jsonTreeView.actions.expandAll")]}),C.jsxs(ee,{variant:"ghost",size:"xs",onClick:u,className:"gap-1 text-xs text-muted-foreground",children:[C.jsx(te,{name:"arrow-up-s",className:"h-3 w-3"}),s("jsonTreeView.actions.collapseAll")]})]}),C.jsx("div",{className:"bg-[var(--syntax-base-background)] py-1",style:{maxHeight:n,overflow:"auto"},children:C.jsx(Pe,{ref:a,data:l,maxHeight:n,initiallyExpandedDepth:r})})]})});export{_t as F,Wt as J};