claude-code-session-manager 0.21.0 → 0.21.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{TiptapBody-DtTU-6tZ.js → TiptapBody-C46DacIO.js} +1 -1
- package/dist/assets/{cssMode-FA1uC6B_.js → cssMode-CauFS5Bp.js} +1 -1
- package/dist/assets/{freemarker2-DYaF01LX.js → freemarker2-BxIPNQn-.js} +1 -1
- package/dist/assets/{handlebars-Da7b36Lf.js → handlebars-DnEVFUsu.js} +1 -1
- package/dist/assets/{html-CEBCag3L.js → html-S8NXUTqc.js} +1 -1
- package/dist/assets/{htmlMode-1_WYf3Br.js → htmlMode-rSEyII9x.js} +1 -1
- package/dist/assets/{index-BzEG1CLO.js → index-DMobTczM.js} +5 -5
- package/dist/assets/{javascript-DKWzZR-I.js → javascript-BiWR68QP.js} +1 -1
- package/dist/assets/{jsonMode-BbyLfnM7.js → jsonMode-1FAJaHiX.js} +1 -1
- package/dist/assets/{liquid-BbbdIZ5H.js → liquid-CEtOkbwI.js} +1 -1
- package/dist/assets/{lspLanguageFeatures-COiniR1D.js → lspLanguageFeatures-CRF3U0x3.js} +1 -1
- package/dist/assets/{mdx-BKuETQUL.js → mdx-C7C95Bzt.js} +1 -1
- package/dist/assets/{python-BiJja-9i.js → python-CXvKcjLk.js} +1 -1
- package/dist/assets/{razor-DnGCqquD.js → razor-tzZHfRy2.js} +1 -1
- package/dist/assets/{tsMode-CtpaN11s.js → tsMode-CLQIVays.js} +1 -1
- package/dist/assets/{typescript-Cx21wAbo.js → typescript-LxhyM9W2.js} +1 -1
- package/dist/assets/{xml-BgafHH5c.js → xml-VS_m20VE.js} +1 -1
- package/dist/assets/{yaml-BtU-Gr1g.js → yaml-BsjggdVD.js} +1 -1
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/main/scheduler.cjs +24 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./cssMode-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./cssMode-CauFS5Bp.js","./lspLanguageFeatures-CRF3U0x3.js","./htmlMode-rSEyII9x.js","./jsonMode-1FAJaHiX.js","./javascript-BiWR68QP.js","./typescript-LxhyM9W2.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var _Ve=Object.defineProperty;var vVe=(s,e,i)=>e in s?_Ve(s,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):s[e]=i;var kn=(s,e,i)=>vVe(s,typeof e!="symbol"?e+"":e,i);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const a of o.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&n(a)}).observe(document,{childList:!0,subtree:!0});function i(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(r){if(r.ep)return;r.ep=!0;const o=i(r);fetch(r.href,o)}})();var hj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function oo(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var dK={exports:{}},sM={},uK={exports:{}},xs={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -950,11 +950,11 @@ ${e.toString()}`}}class tH{constructor(e=new oR,i=!1,n,r=BLt){this._services=e,t
|
|
|
950
950
|
`:`\r
|
|
951
951
|
`}};Hce=ev([go(0,Oi)],Hce);class XLt{publicLog2(){}}const k3=class k3{constructor(){const e=ni.from({scheme:k3.SCHEME,authority:"model",path:"/"});this.workspace={id:o5e,folders:[new uut({uri:e,name:"",index:0})]}}getWorkspace(){return this.workspace}getWorkspaceFolder(e){return e&&e.scheme===k3.SCHEME?this.workspace.folders[0]:null}};k3.SCHEME="inmemory";let Vce=k3;function nH(s,e,i){if(!e||!(s instanceof iH))return;const n=[];Object.keys(e).forEach(r=>{Iut(r)&&n.push([`editor.${r}`,e[r]]),i&&Nut(r)&&n.push([`diffEditor.${r}`,e[r]])}),n.length>0&&s.updateValues(n)}let zce=class{constructor(e){this._modelService=e}hasPreviewHandler(){return!1}async apply(e,i){const n=Array.isArray(e)?e:Fge.convert(e),r=new Map;for(const l of n){if(!(l instanceof B0))throw new Error("bad edit - only text edits are supported");const c=this._modelService.getModel(l.resource);if(!c)throw new Error("bad edit - model not found");if(typeof l.versionId=="number"&&c.getVersionId()!==l.versionId)throw new Error("bad state - model changed in the meantime");let d=r.get(c);d||(d=[],r.set(c,d)),d.push(Nr.replaceMove(oe.lift(l.textEdit.range),l.textEdit.text))}let o=0,a=0;for(const[l,c]of r)l.pushStackElement(),l.pushEditOperations([],c,()=>[]),l.pushStackElement(),a+=1,o+=c.length;return{ariaSummary:Qk(Oae.bulkEditServiceSummary,o,a),isApplied:o>0}}};zce=ev([go(0,mr)],zce);class ZLt{getUriLabel(e,i){return e.scheme==="file"?e.fsPath:e.path}getUriBasenameLabel(e){return yf(e)}}let Uce=class extends fkt{constructor(e,i){super(e),this._codeEditorService=i}showContextView(e,i,n){if(!i){const r=this._codeEditorService.getFocusedCodeEditor()||this._codeEditorService.getActiveCodeEditor();r&&(i=r.getContainerDomNode())}return super.showContextView(e,i,n)}};Uce=ev([go(0,Z_),go(1,Rn)],Uce);class QLt{constructor(){this._neverEmitter=new Ce,this.onDidChangeTrust=this._neverEmitter.event}isWorkspaceTrusted(){return!0}}class JLt extends oce{constructor(){super()}}class eEt extends VLt{constructor(){super(new nKe)}}let qce=class extends cce{constructor(e,i,n,r,o,a){super(e,i,n,r,o,a),this.configure({blockMouse:!1})}};qce=ev([go(0,ql),go(1,Or),go(2,Ry),go(3,$n),go(4,Lf),go(5,_i)],qce);const tEt={esmModuleLocation:void 0,label:"editorWorkerService"};let Gce=class extends Kle{constructor(e,i,n,r,o){super(tEt,e,i,n,r,o)}};Gce=ev([go(0,mr),go(1,Gq),go(2,Bs),go(3,_r),go(4,jt)],Gce);class iEt{async playSignal(e,i){}}fn(Bs,eEt,0);fn(Oi,iH,0);fn(Gq,Wce,0);fn(ije,Hce,0);fn(my,Vce,0);fn(CL,ZLt,0);fn(ql,XLt,0);fn(GF,KLt,0);fn(qge,GLt,0);fn(Or,jce,0);fn(Q_,WC,0);fn(Pr,JLt,0);fn(kh,rSt,0);fn(mr,pce,0);fn(_fe,gce,0);fn(_i,Oce,0);fn(A3e,qLt,0);fn(gy,Bce,0);fn(kc,Kct,0);fn(Pd,Gce,0);fn(PF,zce,0);fn(gje,QLt,0);fn(Sc,Fce,0);fn(Ua,Rce,0);fn(If,npt,0);fn(js,$ce,0);fn($n,mN,0);fn(zl,Ice,0);fn(Ry,Uce,0);fn(Ay,fce,0);fn(Su,Mce,0);fn(Sh,qce,0);fn(Lf,mse,0);fn(Iy,iEt,0);fn(ige,zLt,0);fn(oPe,aKe,0);fn(Ppe,bvt,0);var ki;(function(s){const e=new oR;for(const[c,d]of Nbe())e.set(c,d);const i=new tH(e,!0);e.set(Gt,i);function n(c){r||a({});const d=e.get(c);if(!d)throw new Error("Missing service "+c);return d instanceof s_?i.invokeFunction(u=>u.get(c)):d}s.get=n;let r=!1;const o=new Ce;function a(c){if(r)return i;r=!0;for(const[u,h]of Nbe())e.get(u)||e.set(u,h);for(const u in c)if(c.hasOwnProperty(u)){const h=Qi(u);e.get(h)instanceof s_&&e.set(h,c[u])}const d=hht();for(const u of d)try{i.createInstance(u)}catch(h){Si(h)}return o.fire(),i}s.initialize=a;function l(c){if(r)return c();const d=new Ue,u=d.add(o.event(()=>{u.dispose(),d.add(c())}));return d}s.withServices=l})(ki||(ki={}));var nEt=function(s,e,i,n){var r=arguments.length,o=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,i,n);else for(var l=s.length-1;l>=0;l--)(a=s[l])&&(o=(r<3?a(o):r>3?a(e,i,o):a(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o},lSe=function(s,e){return function(i,n){e(i,n,s)}},x8,qk;let Kce=(qk=class{constructor(e,i){this._configurationService=e,this._languageService=i}async renderCodeBlock(e,i,n){var u;const r=Jp(n.context)?n.context:void 0;let o;e?o=this._languageService.getLanguageIdByLanguageName(e):r&&(o=(u=r.getModel())==null?void 0:u.getLanguageId()),o||(o=_h);const a=await drt(this._languageService,i,o),l=x8._ttpTokenizer?x8._ttpTokenizer.createHTML(a)??a:a,c=document.createElement("span");c.innerHTML=l;const d=c.querySelector(".monaco-tokenized-source");return Mr(d)?(Ca(d,this.getFontInfo(r)),c):document.createElement("span")}getFontInfo(e){return e?e.getOption(59):$Xe({fontFamily:this._configurationService.getValue("editor").fontFamily},1)}},x8=qk,qk._ttpTokenizer=Y_("tokenizeToString",{createHTML(e){return e}}),qk);Kce=x8=nEt([lSe(0,Oi),lSe(1,Pr)],Kce);var fme=function(s,e,i,n){var r=arguments.length,o=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,i,n);else for(var l=s.length-1;l>=0;l--)(a=s[l])&&(o=(r<3?a(o):r>3?a(e,i,o):a(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o},ks=function(s,e){return function(i,n){e(i,n,s)}};let sEt=0,cSe=!1;function rEt(s){if(!s){if(cSe)return;cSe=!0}xGe(s||ls.document.body)}let sH=class extends aL{constructor(e,i,n,r,o,a,l,c,d,u,h,f,g,p){const _={...i};_.ariaLabel=_.ariaLabel||Mae.editorViewAccessibleLabel,super(e,_,{},n,r,o,a,d,u,h,f,g),c instanceof mN?this._standaloneKeybindingService=c:this._standaloneKeybindingService=null,rEt(_.ariaContainerElement),Xrt((m,b)=>n.createInstance(J2,m,{instantHover:b},{})),olt(l),p.setDefaultCodeBlockRenderer(n.createInstance(Kce))}addCommand(e,i,n){if(!this._standaloneKeybindingService)return console.warn("Cannot add command because the editor is configured with an unrecognized KeybindingService"),null;const r="DYNAMIC_"+ ++sEt,o=Qe.deserialize(n);return this._standaloneKeybindingService.addDynamicKeybinding(r,e,i,o),r}createContextKey(e,i){return this._contextKeyService.createKey(e,i)}addAction(e){if(typeof e.id!="string"||typeof e.label!="string"||typeof e.run!="function")throw new Error("Invalid action descriptor, `id`, `label` and `run` are required properties!");if(!this._standaloneKeybindingService)return console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService"),Le.None;const i=e.id,n=e.label,r=Qe.and(Qe.equals("editorId",this.getId()),Qe.deserialize(e.precondition)),o=e.keybindings,a=Qe.and(r,Qe.deserialize(e.keybindingContext)),l=e.contextMenuGroupId||null,c=e.contextMenuOrder||0,d=(g,...p)=>Promise.resolve(e.run(this,...p)),u=new Ue,h=this.getId()+":"+i;if(u.add(Ln.registerCommand(h,d)),l){const g={command:{id:h,title:n},when:r,group:l,order:c};u.add(xa.appendMenuItem(Wt.EditorContext,g))}if(Array.isArray(o))for(const g of o)u.add(this._standaloneKeybindingService.addDynamicKeybinding(h,g,d,a));const f=new i3e(h,n,n,void 0,r,(...g)=>Promise.resolve(e.run(this,...g)),this._contextKeyService);return this._actions.set(i,f),u.add(Ht(()=>{this._actions.delete(i)})),u}_triggerCommand(e,i){if(this._codeEditorService instanceof U7)try{this._codeEditorService.setActiveCodeEditor(this),super._triggerCommand(e,i)}finally{this._codeEditorService.setActiveCodeEditor(null)}else super._triggerCommand(e,i)}};sH=fme([ks(2,Gt),ks(3,Rn),ks(4,js),ks(5,_i),ks(6,sd),ks(7,$n),ks(8,kr),ks(9,Or),ks(10,Ua),ks(11,_r),ks(12,jt),ks(13,Ag)],sH);let Yce=class extends sH{constructor(e,i,n,r,o,a,l,c,d,u,h,f,g,p,_,m,b){const y={...i};nH(h,y,!1);const x=d.registerEditorContainer(e);typeof y.theme=="string"&&d.setTheme(y.theme),typeof y.autoDetectHighContrast<"u"&&d.setAutoDetectHighContrast(!!y.autoDetectHighContrast);const S=y.model;delete y.model,super(e,y,n,r,o,a,l,c,d,u,f,_,m,b),this._configurationService=h,this._standaloneThemeService=d,this._register(x);let k;if(typeof S>"u"){const D=p.getLanguageIdByMimeType(y.language)||y.language||_h;k=o$e(g,p,y.value||"",D,void 0),this._ownsModel=!0}else k=S,this._ownsModel=!1;if(this._attachModel(k),k){const D={oldModelUrl:null,newModelUrl:k.uri};this._onDidChangeModel.fire(D)}}dispose(){super.dispose()}updateOptions(e){nH(this._configurationService,e,!1),typeof e.theme=="string"&&this._standaloneThemeService.setTheme(e.theme),typeof e.autoDetectHighContrast<"u"&&this._standaloneThemeService.setAutoDetectHighContrast(!!e.autoDetectHighContrast),super.updateOptions(e)}_postDetachModelCleanup(e){super._postDetachModelCleanup(e),e&&this._ownsModel&&(e.dispose(),this._ownsModel=!1)}};Yce=fme([ks(2,Gt),ks(3,Rn),ks(4,js),ks(5,_i),ks(6,sd),ks(7,$n),ks(8,kh),ks(9,Or),ks(10,Oi),ks(11,Ua),ks(12,mr),ks(13,Pr),ks(14,_r),ks(15,jt),ks(16,Ag)],Yce);let Xce=class extends j_{constructor(e,i,n,r,o,a,l,c,d,u,h,f){const g={...i};nH(c,g,!0);const p=a.registerEditorContainer(e);typeof g.theme=="string"&&a.setTheme(g.theme),typeof g.autoDetectHighContrast<"u"&&a.setAutoDetectHighContrast(!!g.autoDetectHighContrast),super(e,g,{},r,n,o,f,u),this._configurationService=c,this._standaloneThemeService=a,this._register(p)}dispose(){super.dispose()}updateOptions(e){nH(this._configurationService,e,!0),typeof e.theme=="string"&&this._standaloneThemeService.setTheme(e.theme),typeof e.autoDetectHighContrast<"u"&&this._standaloneThemeService.setAutoDetectHighContrast(!!e.autoDetectHighContrast),super.updateOptions(e)}_createInnerEditor(e,i,n){return e.createInstance(sH,i,n)}getOriginalEditor(){return super.getOriginalEditor()}getModifiedEditor(){return super.getModifiedEditor()}addCommand(e,i,n){return this.getModifiedEditor().addCommand(e,i,n)}createContextKey(e,i){return this.getModifiedEditor().createContextKey(e,i)}addAction(e){return this.getModifiedEditor().addAction(e)}};Xce=fme([ks(2,Gt),ks(3,_i),ks(4,Rn),ks(5,kh),ks(6,Or),ks(7,Oi),ks(8,Sh),ks(9,gy),ks(10,Su),ks(11,Iy)],Xce);function o$e(s,e,i,n,r){if(i=i||"",!n){const o=i.indexOf(`
|
|
952
952
|
`);let a=i;return o!==-1&&(a=i.substring(0,o)),dSe(s,i,e.createByFilepathOrFirstLine(r||null,a),r)}return dSe(s,i,e.createById(n),r)}function dSe(s,e,i,n){return s.createModel(e,i,n)}fe("multiDiffEditor.headerBackground",{dark:"#262626",light:"tab.inactiveBackground",hcDark:"tab.inactiveBackground",hcLight:"tab.inactiveBackground"},I(142,"The background color of the diff editor's header"));fe("multiDiffEditor.background",io,I(143,"The background color of the multi file diff editor"));fe("multiDiffEditor.border",{dark:"sideBarSectionHeader.border",light:"#cccccc",hcDark:"sideBarSectionHeader.border",hcLight:"#cccccc"},I(144,"The border color of the multi file diff editor"));var oEt=function(s,e,i,n){var r=arguments.length,o=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,i,n);else for(var l=s.length-1;l>=0;l--)(a=s[l])&&(o=(r<3?a(o):r>3?a(e,i,o):a(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o},uSe=function(s,e){return function(i,n){e(i,n,s)}};class aEt{constructor(e,i){this.viewModel=e,this.deltaScrollVertical=i}getId(){return this.viewModel}}let Zce=class extends Le{constructor(e,i,n,r,o){super(),this._container=e,this._overflowWidgetsDomNode=i,this._workbenchUIElementFactory=n,this._instantiationService=r,this._viewModel=mi(this,void 0),this._collapsed=Xe(this,c=>{var d;return(d=this._viewModel.read(c))==null?void 0:d.collapsed.read(c)}),this._editorContentHeight=mi(this,500),this.contentHeight=Xe(this,c=>(this._collapsed.read(c)?0:this._editorContentHeight.read(c))+this._outerEditorHeight),this._modifiedContentWidth=mi(this,0),this._modifiedWidth=mi(this,0),this._originalContentWidth=mi(this,0),this._originalWidth=mi(this,0),this.maxScroll=Xe(this,c=>{const d=this._modifiedContentWidth.read(c)-this._modifiedWidth.read(c),u=this._originalContentWidth.read(c)-this._originalWidth.read(c);return d>u?{maxScroll:d,width:this._modifiedWidth.read(c)}:{maxScroll:u,width:this._originalWidth.read(c)}}),this._elements=In("div.multiDiffEntry",[In("div.header@header",[In("div.header-content",[In("div.collapse-button@collapseButton"),In("div.file-path",[In("div.title.modified.show-file-icons@primaryPath",[]),In("div.status.deleted@status",["R"]),In("div.title.original.show-file-icons@secondaryPath",[])]),In("div.actions@actions")])]),In("div.editorParent",[In("div.editorContainer@editor")])]),this.editor=this._register(this._instantiationService.createInstance(j_,this._elements.editor,{overflowWidgetsDomNode:this._overflowWidgetsDomNode,fixedOverflowWidgets:!0},{})),this.isModifedFocused=gr(this.editor.getModifiedEditor()).isFocused,this.isOriginalFocused=gr(this.editor.getOriginalEditor()).isFocused,this.isFocused=Xe(this,c=>this.isModifedFocused.read(c)||this.isOriginalFocused.read(c)),this._resourceLabel=this._workbenchUIElementFactory.createResourceLabel?this._register(this._workbenchUIElementFactory.createResourceLabel(this._elements.primaryPath)):void 0,this._resourceLabel2=this._workbenchUIElementFactory.createResourceLabel?this._register(this._workbenchUIElementFactory.createResourceLabel(this._elements.secondaryPath)):void 0,this._dataStore=this._register(new Ue),this._headerHeight=40,this._lastScrollTop=-1,this._isSettingScrollTop=!1;const a=new v9(this._elements.collapseButton,{});this._register(hi(c=>{a.element.className="",a.icon=this._collapsed.read(c)?nt.chevronRight:nt.chevronDown})),this._register(a.onDidClick(()=>{var c;(c=this._viewModel.get())==null||c.collapsed.set(!this._collapsed.get(),void 0)})),this._register(hi(c=>{this._elements.editor.style.display=this._collapsed.read(c)?"none":"block"})),this._register(this.editor.getModifiedEditor().onDidLayoutChange(c=>{const d=this.editor.getModifiedEditor().getLayoutInfo().contentWidth;this._modifiedWidth.set(d,void 0)})),this._register(this.editor.getOriginalEditor().onDidLayoutChange(c=>{const d=this.editor.getOriginalEditor().getLayoutInfo().contentWidth;this._originalWidth.set(d,void 0)})),this._register(this.editor.onDidContentSizeChange(c=>{CP(d=>{this._editorContentHeight.set(c.contentHeight,d),this._modifiedContentWidth.set(this.editor.getModifiedEditor().getContentWidth(),d),this._originalContentWidth.set(this.editor.getOriginalEditor().getContentWidth(),d)})})),this._register(this.editor.getOriginalEditor().onDidScrollChange(c=>{if(this._isSettingScrollTop||!c.scrollTopChanged||!this._data)return;const d=c.scrollTop-this._lastScrollTop;this._data.deltaScrollVertical(d)})),this._register(hi(c=>{var u;const d=(u=this._viewModel.read(c))==null?void 0:u.isActive.read(c);this._elements.root.classList.toggle("active",d)})),this._container.appendChild(this._elements.root),this._outerEditorHeight=this._headerHeight,this._contextKeyService=this._register(o.createScoped(this._elements.actions));const l=this._register(this._instantiationService.createChild(new oR([_i,this._contextKeyService])));this._register(l.createInstance(S4,this._elements.actions,Wt.MultiDiffEditorFileToolbar,{actionRunner:this._register(new q4e(()=>{var c,d;return((c=this._viewModel.get())==null?void 0:c.modifiedUri)??((d=this._viewModel.get())==null?void 0:d.originalUri)})),menuOptions:{shouldForwardArgs:!0},toolbarOptions:{primaryGroup:c=>c.startsWith("navigation")},actionViewItemProvider:(c,d)=>Pge(l,c,d)}))}setScrollLeft(e){this._modifiedContentWidth.get()-this._modifiedWidth.get()>this._originalContentWidth.get()-this._originalWidth.get()?this.editor.getModifiedEditor().setScrollLeft(e):this.editor.getOriginalEditor().setScrollLeft(e)}setData(e){this._data=e;function i(r){return{...r,scrollBeyondLastLine:!1,hideUnchangedRegions:{enabled:!0},scrollbar:{vertical:"hidden",horizontal:"hidden",handleMouseWheel:!1,useShadows:!1},renderOverviewRuler:!1,fixedOverflowWidgets:!0,overviewRulerBorder:!1}}if(!e){CP(r=>{this._viewModel.set(void 0,r),this.editor.setDiffModel(null,r),this._dataStore.clear()});return}const n=e.viewModel.documentDiffItem;if(CP(r=>{var d,u;(d=this._resourceLabel)==null||d.setUri(e.viewModel.modifiedUri??e.viewModel.originalUri,{strikethrough:e.viewModel.modifiedUri===void 0});let o=!1,a=!1,l=!1,c="";e.viewModel.modifiedUri&&e.viewModel.originalUri&&e.viewModel.modifiedUri.path!==e.viewModel.originalUri.path?(c="R",o=!0):e.viewModel.modifiedUri?e.viewModel.originalUri||(c="A",l=!0):(c="D",a=!0),this._elements.status.classList.toggle("renamed",o),this._elements.status.classList.toggle("deleted",a),this._elements.status.classList.toggle("added",l),this._elements.status.innerText=c,(u=this._resourceLabel2)==null||u.setUri(o?e.viewModel.originalUri:void 0,{strikethrough:!0}),this._dataStore.clear(),this._viewModel.set(e.viewModel,r),this.editor.setDiffModel(e.viewModel.diffEditorViewModelRef,r),this.editor.updateOptions(i(n.options??{}))}),n.onOptionsDidChange&&this._dataStore.add(n.onOptionsDidChange(()=>{this.editor.updateOptions(i(n.options??{}))})),e.viewModel.isAlive.recomputeInitiallyAndOnChange(this._dataStore,r=>{r||this.setData(void 0)}),e.viewModel.documentDiffItem.contextKeys)for(const[r,o]of Object.entries(e.viewModel.documentDiffItem.contextKeys))this._contextKeyService.createKey(r,o)}render(e,i,n,r){this._elements.root.style.visibility="visible",this._elements.root.style.top=`${e.start}px`,this._elements.root.style.height=`${e.length}px`,this._elements.root.style.width=`${i}px`,this._elements.root.style.position="absolute";const o=e.length-this._headerHeight,a=Math.max(0,Math.min(r.start-e.start,o));this._elements.header.style.transform=`translateY(${a}px)`,CP(l=>{this.editor.layout({width:i-16-2,height:e.length-this._outerEditorHeight})});try{this._isSettingScrollTop=!0,this._lastScrollTop=n,this.editor.getOriginalEditor().setScrollTop(n)}finally{this._isSettingScrollTop=!1}this._elements.header.classList.toggle("shadow",a>0||n>0),this._elements.header.classList.toggle("collapsed",a===o)}hide(){this._elements.root.style.top="-100000px",this._elements.root.style.visibility="hidden"}};Zce=oEt([uSe(3,Gt),uSe(4,_i)],Zce);class lEt{constructor(e){this._create=e,this._unused=new Set,this._used=new Set,this._itemData=new Map}getUnusedObj(e){let i;if(this._unused.size===0)i=this._create(e),this._itemData.set(i,e);else{const n=[...this._unused.values()];i=n.find(r=>this._itemData.get(r).getId()===e.getId())??n[0],this._unused.delete(i),this._itemData.set(i,e),i.setData(e)}return this._used.add(i),{object:i,dispose:()=>{this._used.delete(i),this._unused.size>5?i.dispose():this._unused.add(i)}}}dispose(){for(const e of this._used)e.dispose();for(const e of this._unused)e.dispose();this._used.clear(),this._unused.clear()}}var cEt=function(s,e,i,n){var r=arguments.length,o=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,i,n);else for(var l=s.length-1;l>=0;l--)(a=s[l])&&(o=(r<3?a(o):r>3?a(e,i,o):a(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o},hSe=function(s,e){return function(i,n){e(i,n,s)}};let Qce=class extends Le{constructor(e,i,n,r,o,a){super(),this._element=e,this._dimension=i,this._viewModel=n,this._workbenchUIElementFactory=r,this._parentContextKeyService=o,this._parentInstantiationService=a,this._scrollableElements=In("div.scrollContent",[In("div@content",{style:{overflow:"hidden"}}),In("div.monaco-editor@overflowWidgetsDomNode",{})]),this._scrollable=this._register(new sR({forceIntegerValues:!1,scheduleAtNextAnimationFrame:d=>Id(Xt(this._element),d),smoothScrollDuration:100})),this._scrollableElement=this._register(new sq(this._scrollableElements.root,{vertical:1,horizontal:1,useShadows:!1},this._scrollable)),this._elements=In("div.monaco-component.multiDiffEditor",{},[In("div",{},[this._scrollableElement.getDomNode()]),In("div.placeholder@placeholder",{},[In("div")])]),this._sizeObserver=this._register(new L4e(this._element,void 0)),this._objectPool=this._register(new lEt(d=>{const u=this._instantiationService.createInstance(Zce,this._scrollableElements.content,this._scrollableElements.overflowWidgetsDomNode,this._workbenchUIElementFactory);return u.setData(d),u})),this.scrollTop=Gn(this,this._scrollableElement.onScroll,()=>this._scrollableElement.getScrollPosition().scrollTop),this.scrollLeft=Gn(this,this._scrollableElement.onScroll,()=>this._scrollableElement.getScrollPosition().scrollLeft),this._viewItemsInfo=Xe(this,d=>{const u=this._viewModel.read(d);if(!u)return{items:[],getItem:p=>{throw new si}};const h=u.items.read(d),f=new Map;return{items:h.map(p=>{var b;const _=d.store.add(new uEt(p,this._objectPool,this.scrollLeft,y=>{this._scrollableElement.setScrollPosition({scrollTop:this._scrollableElement.getScrollPosition().scrollTop+y})})),m=(b=this._lastDocStates)==null?void 0:b[_.getKey()];return m&&Ls(y=>{_.setViewState(m,y)}),f.set(p,_),_}),getItem:p=>f.get(p)}}),this._viewItems=this._viewItemsInfo.map(this,d=>d.items),this._spaceBetweenPx=0,this._totalHeight=this._viewItems.map(this,(d,u)=>d.reduce((h,f)=>h+f.contentHeight.read(u)+this._spaceBetweenPx,0)),this.activeControl=Xe(this,d=>{var f,g;const u=(f=this._viewModel.read(d))==null?void 0:f.activeDiffItem.read(d);return u?(g=this._viewItemsInfo.read(d).getItem(u).template.read(d))==null?void 0:g.editor:void 0}),this._contextKeyService=this._register(this._parentContextKeyService.createScoped(this._element)),this._instantiationService=this._register(this._parentInstantiationService.createChild(new oR([_i,this._contextKeyService]))),this._contextKeyService.createKey(pe.inMultiDiffEditor.key,!0),this._lastDocStates={},this._register(Wl((d,u)=>{const h=this._viewModel.read(d);if(h&&h.contextKeys)for(const[f,g]of Object.entries(h.contextKeys)){const p=this._contextKeyService.createKey(f,void 0);p.set(g),u.add(Ht(()=>p.reset()))}}));const l=this._parentContextKeyService.createKey(pe.multiDiffEditorAllCollapsed.key,!1);this._register(hi(d=>{const u=this._viewModel.read(d);if(u){const h=u.items.read(d).every(f=>f.collapsed.read(d));l.set(h)}})),this._register(hi(d=>{const u=this._dimension.read(d);this._sizeObserver.observe(u)}));const c=Xe(d=>{if(this._viewItems.read(d).length>0)return;const h=this._viewModel.read(d);return!h||h.isLoading.read(d)?I(145,"Loading..."):I(146,"No Changed Files")});this._register(hi(d=>{const u=c.read(d);this._elements.placeholder.innerText=u??"",this._elements.placeholder.classList.toggle("visible",!!u)})),this._scrollableElements.content.style.position="relative",this._register(hi(d=>{const u=this._sizeObserver.height.read(d);this._scrollableElements.root.style.height=`${u}px`;const h=this._totalHeight.read(d);this._scrollableElements.content.style.height=`${h}px`;const f=this._sizeObserver.width.read(d);let g=f;const p=this._viewItems.read(d),_=Ofe(p,ml(m=>m.maxScroll.read(d).maxScroll,pu));if(_){const m=_.maxScroll.read(d);g=f+m.maxScroll}this._scrollableElement.setScrollDimensions({width:f,height:u,scrollHeight:h,scrollWidth:g})})),e.replaceChildren(this._elements.root),this._register(Ht(()=>{e.replaceChildren()})),this._register(hi(d=>{const u=this._viewModel.read(d);if(u&&!u.isLoading.read(d)){if(u.items.read(d).length===0||u.activeDiffItem.read(d))return;this.goToNextChange()}})),this._register(this._register(hi(d=>{CP(u=>{this.render(d)})})))}reveal(e,i){var d;const n=this._viewItems.get(),r=n.findIndex(u=>{var h,f,g,p;return((h=u.viewModel.originalUri)==null?void 0:h.toString())===((f=e.original)==null?void 0:f.toString())&&((g=u.viewModel.modifiedUri)==null?void 0:g.toString())===((p=e.modified)==null?void 0:p.toString())});if(r===-1)throw new si("Resource not found in diff editor");const o=n[r];this._viewModel.get().activeDiffItem.setCache(o.viewModel,void 0);let a=0;for(let u=0;u<r;u++)a+=n[u].contentHeight.get()+this._spaceBetweenPx;this._scrollableElement.setScrollPosition({scrollTop:a});const l=(d=o.template.get())==null?void 0:d.editor,c="original"in e?l==null?void 0:l.getOriginalEditor():l==null?void 0:l.getModifiedEditor();c&&(i!=null&&i.range)&&(c.revealRangeInCenter(i.range),dEt(c,i.range))}goToNextChange(){this._navigateToChange("next")}_navigateToChange(e){var c,d,u,h,f;const i=this._viewItems.get();if(i.length===0)return;const n=(c=this._viewModel.get())==null?void 0:c.activeDiffItem.get(),r=n?i.findIndex(g=>g.viewModel===n):-1;if(r===-1){this._goToFile(0,"first");return}const o=i[r];o.viewModel.collapsed.get()&&o.viewModel.collapsed.set(!1,void 0);const a=(d=o.template.get())==null?void 0:d.editor;if((h=(u=a==null?void 0:a.getDiffComputationResult())==null?void 0:u.changes2)!=null&&h.length){const g=((f=a.getModifiedEditor().getPosition())==null?void 0:f.lineNumber)||1,p=a.getDiffComputationResult().changes2;if(e==="next"?p.some(m=>m.modified.startLineNumber>g):p.some(m=>m.modified.endLineNumberExclusive<=g)){a.goToDiff(e);return}}const l=(r+(e==="next"?1:-1)+i.length)%i.length;this._goToFile(l,e==="next"?"first":"last")}_goToFile(e,i){var o,a,l;const n=this._viewItems.get()[e];n.viewModel.collapsed.get()&&n.viewModel.collapsed.set(!1,void 0),this.reveal({original:n.viewModel.originalUri,modified:n.viewModel.modifiedUri});const r=(o=n.template.get())==null?void 0:o.editor;if((l=(a=r==null?void 0:r.getDiffComputationResult())==null?void 0:a.changes2)!=null&&l.length)if(i==="first")r.revealFirstDiff();else{const c=r.getDiffComputationResult().changes2.at(-1),d=r.getModifiedEditor();d.setPosition({lineNumber:c.modified.startLineNumber,column:1}),d.revealLineInCenter(c.modified.startLineNumber)}r==null||r.focus()}render(e){const i=this.scrollTop.read(e);let n=0,r=0,o=0;const a=this._sizeObserver.height.read(e),l=qt.ofStartAndLength(i,a),c=this._sizeObserver.width.read(e);for(const d of this._viewItems.read(e)){const u=d.contentHeight.read(e),h=Math.min(u,a),f=qt.ofStartAndLength(r,h),g=qt.ofStartAndLength(o,u);if(g.isBefore(l))n-=u-h,d.hide();else if(g.isAfter(l))d.hide();else{const p=Math.max(0,Math.min(l.start-g.start,u-h));n-=p;const _=qt.ofStartAndLength(i+n,a);d.render(f,p,c,_)}r+=h+this._spaceBetweenPx,o+=u+this._spaceBetweenPx}this._scrollableElements.content.style.transform=`translateY(${-(i+n)}px)`}};Qce=cEt([hSe(4,_i),hSe(5,Gt)],Qce);function dEt(s,e){const i=s.getModel(),n=s.createDecorationsCollection([{range:e,options:{description:"symbol-navigate-action-highlight",className:"symbolHighlight"}}]);setTimeout(()=>{s.getModel()===i&&n.clear()},350)}class uEt extends Le{constructor(e,i,n,r){super(),this.viewModel=e,this._objectPool=i,this._scrollLeft=n,this._deltaScrollVertical=r,this._templateRef=this._register(Qhe(this,void 0)),this.contentHeight=Xe(this,o=>{var a,l;return((l=(a=this._templateRef.read(o))==null?void 0:a.object.contentHeight)==null?void 0:l.read(o))??this.viewModel.lastTemplateData.read(o).contentHeight}),this.maxScroll=Xe(this,o=>{var a;return((a=this._templateRef.read(o))==null?void 0:a.object.maxScroll.read(o))??{maxScroll:0,scrollWidth:0}}),this.template=Xe(this,o=>{var a;return(a=this._templateRef.read(o))==null?void 0:a.object}),this._isHidden=mi(this,!1),this._isFocused=Xe(this,o=>{var a;return((a=this.template.read(o))==null?void 0:a.isFocused.read(o))??!1}),this.viewModel.setIsFocused(this._isFocused,void 0),this._register(hi(o=>{var l;const a=this._scrollLeft.read(o);(l=this._templateRef.read(o))==null||l.object.setScrollLeft(a)})),this._register(hi(o=>{const a=this._templateRef.read(o);!a||!this._isHidden.read(o)||a.object.isFocused.read(o)||this._clear()}))}dispose(){this._clear(),super.dispose()}toString(){var e;return`VirtualViewItem(${(e=this.viewModel.documentDiffItem.modified)==null?void 0:e.uri.toString()})`}getKey(){return this.viewModel.getKey()}setViewState(e,i){var a;this.viewModel.collapsed.set(e.collapsed,i),this._updateTemplateData(i);const n=this.viewModel.lastTemplateData.get(),r=(a=e.selections)==null?void 0:a.map(Mt.liftSelection);this.viewModel.lastTemplateData.set({...n,selections:r},i);const o=this._templateRef.get();o&&r&&o.object.editor.setSelections(r)}_updateTemplateData(e){const i=this._templateRef.get();i&&this.viewModel.lastTemplateData.set({contentHeight:i.object.contentHeight.get(),selections:i.object.editor.getSelections()??void 0},e)}_clear(){const e=this._templateRef.get();e&&Ls(i=>{this._updateTemplateData(i),e.object.hide(),this._templateRef.set(void 0,i)})}hide(){this._isHidden.set(!0,void 0)}render(e,i,n,r){this._isHidden.set(!1,void 0);let o=this._templateRef.get();if(!o){o=this._objectPool.getUnusedObj(new aEt(this.viewModel,this._deltaScrollVertical)),this._templateRef.set(o,void 0);const a=this.viewModel.lastTemplateData.get().selections;a&&o.object.editor.setSelections(a)}o.object.render(e,n,i,r)}}var hEt=function(s,e,i,n){var r=arguments.length,o=r<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,i):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,i,n);else for(var l=s.length-1;l>=0;l--)(a=s[l])&&(o=(r<3?a(o):r>3?a(e,i,o):a(e,i))||o);return r>3&&o&&Object.defineProperty(e,i,o),o},fEt=function(s,e){return function(i,n){e(i,n,s)}};let Jce=class extends Le{constructor(e,i,n){super(),this._element=e,this._workbenchUIElementFactory=i,this._instantiationService=n,this._dimension=mi(this,void 0),this._viewModel=mi(this,void 0),this._widgetImpl=Xe(this,r=>r.store.add(this._instantiationService.createInstance(Xv(Qce),this._element,this._dimension,this._viewModel,this._workbenchUIElementFactory))),this._register(O2(this._widgetImpl))}};Jce=hEt([fEt(2,Gt)],Jce);function gEt(s,e,i){return ki.initialize(i||{}).createInstance(Yce,s,e)}function pEt(s){return ki.get(Rn).onCodeEditorAdd(i=>{s(i)})}function mEt(s){return ki.get(Rn).onDiffEditorAdd(i=>{s(i)})}function _Et(){return ki.get(Rn).listCodeEditors()}function vEt(){return ki.get(Rn).listDiffEditors()}function bEt(s,e,i){return ki.initialize(i||{}).createInstance(Xce,s,e)}function yEt(s,e){const i=ki.initialize(e||{});return new Jce(s,{},i)}function wEt(s){if(typeof s.id!="string"||typeof s.run!="function")throw new Error("Invalid command descriptor, `id` and `run` are required properties!");return Ln.registerCommand(s.id,s.run)}function xEt(s){if(typeof s.id!="string"||typeof s.label!="string"||typeof s.run!="function")throw new Error("Invalid action descriptor, `id`, `label` and `run` are required properties!");const e=Qe.deserialize(s.precondition),i=(r,...o)=>qo.runEditorCommand(r,o,e,(a,l,c)=>Promise.resolve(s.run(l,...c))),n=new Ue;if(n.add(Ln.registerCommand(s.id,i)),s.contextMenuGroupId){const r={command:{id:s.id,title:s.label},when:e,group:s.contextMenuGroupId,order:s.contextMenuOrder||0};n.add(xa.appendMenuItem(Wt.EditorContext,r))}if(Array.isArray(s.keybindings)){const r=ki.get($n);if(!(r instanceof mN))console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService");else{const o=Qe.and(e,Qe.deserialize(s.keybindingContext));n.add(r.addDynamicKeybindings(s.keybindings.map(a=>({keybinding:a,command:s.id,when:o}))))}}return n}function CEt(s){return a$e([s])}function a$e(s){const e=ki.get($n);return e instanceof mN?e.addDynamicKeybindings(s.map(i=>({keybinding:i.keybinding,command:i.command,commandArgs:i.commandArgs,when:Qe.deserialize(i.when)}))):(console.warn("Cannot add keybinding because the editor is configured with an unrecognized KeybindingService"),Le.None)}function SEt(s,e,i){const n=ki.get(Pr),r=n.getLanguageIdByMimeType(e)||e;return o$e(ki.get(mr),n,s,r,i)}function kEt(s,e){const i=ki.get(Pr),n=i.getLanguageIdByMimeType(e)||e||_h;s.setLanguage(i.createById(n))}function LEt(s,e,i){s&&ki.get(Q_).changeOne(e,s.uri,i)}function EEt(s){ki.get(Q_).changeAll(s,[])}function DEt(s){return ki.get(Q_).read(s)}function TEt(s){return ki.get(Q_).onMarkerChanged(s)}function IEt(s){return ki.get(mr).getModel(s)}function NEt(){return ki.get(mr).getModels()}function REt(s){return ki.get(mr).onModelAdded(s)}function AEt(s){return ki.get(mr).onModelRemoved(s)}function MEt(s){return ki.get(mr).onModelLanguageChanged(i=>{s({model:i.model,oldLanguage:i.oldLanguageId})})}function PEt(s){return WSt(ki.get(mr),s)}function OEt(s,e){const i=ki.get(Pr),n=ki.get(kh);return lme.colorizeElement(n,i,s,e).then(()=>{n.registerEditorContainer(s)})}function FEt(s,e,i){const n=ki.get(Pr);return ki.get(kh).registerEditorContainer(ls.document.body),lme.colorize(n,s,e,i)}function BEt(s,e,i=4){return ki.get(kh).registerEditorContainer(ls.document.body),lme.colorizeModelLine(s,e,i)}function jEt(s){const e=Ir.get(s);return e||{getInitialState:()=>X2,tokenize:(i,n,r)=>tge(s,r)}}function $Et(s,e){Ir.getOrCreate(e);const i=jEt(e),n=wu(s),r=[];let o=i.getInitialState();for(let a=0,l=n.length;a<l;a++){const c=n[a],d=i.tokenize(c,!0,o);r[a]=d.tokens,o=d.endState}return r}function WEt(s,e){ki.get(kh).defineTheme(s,e)}function HEt(s){ki.get(kh).setTheme(s)}function VEt(){Mie.clearAllFontInfos()}function zEt(s,e){return Ln.registerCommand({id:s,handler:e})}function UEt(s){return ki.get(Ay).registerOpener({async open(i){return typeof i=="string"&&(i=ni.parse(i)),s.open(i)}})}function qEt(s){return ki.get(Rn).registerCodeEditorOpenHandler(async(i,n,r)=>{var l;if(!n)return null;const o=(l=i.options)==null?void 0:l.selection;let a;return o&&typeof o.endLineNumber=="number"&&typeof o.endColumn=="number"?a=o:o&&(a={lineNumber:o.startLineNumber,column:o.startColumn}),await s.openCodeEditor(n,i.resource,a)?n:null})}function GEt(){return{create:gEt,getEditors:_Et,getDiffEditors:vEt,onDidCreateEditor:pEt,onDidCreateDiffEditor:mEt,createDiffEditor:bEt,addCommand:wEt,addEditorAction:xEt,addKeybindingRule:CEt,addKeybindingRules:a$e,createModel:SEt,setModelLanguage:kEt,setModelMarkers:LEt,getModelMarkers:DEt,removeAllMarkers:EEt,onDidChangeMarkers:TEt,getModels:NEt,getModel:IEt,onDidCreateModel:REt,onWillDisposeModel:AEt,onDidChangeModelLanguage:MEt,createWebWorker:PEt,colorizeElement:OEt,colorize:FEt,colorizeModelLine:BEt,tokenize:$Et,defineTheme:WEt,setTheme:HEt,remeasureFonts:VEt,registerCommand:zEt,registerLinkOpener:UEt,registerEditorOpener:qEt,AccessibilitySupport:Yae,ContentWidgetPositionPreference:tle,CursorChangeReason:ile,DefaultEndOfLine:nle,EditorAutoIndentStrategy:rle,EditorOption:ole,EndOfLinePreference:ale,EndOfLineSequence:lle,MinimapPosition:yle,MinimapSectionHeaderStyle:wle,MouseTargetType:xle,OverlayWidgetPositionPreference:kle,OverviewRulerLane:Lle,GlyphMarginLane:cle,RenderLineNumbersType:Tle,RenderMinimap:Ile,ScrollbarVisibility:Rle,ScrollType:Nle,TextEditorCursorBlinkingStyle:jle,TextEditorCursorStyle:$le,TrackedRangeStickiness:Wle,WrappingIndent:Hle,InjectedTextCursorStops:hle,PositionAffinity:Dle,ShowLightbulbIconMode:Mle,TextDirection:Ble,ConfigurationChangedEvent:FPe,BareFontInfo:tL,FontInfo:mW,TextModelResolvedOptions:U6,FindMatch:W3,ApplyUpdateResult:sO,EditorZoom:of,createMultiFileDiffEditor:yEt,EditorType:kF,EditorOptions:pc}}function KEt(s,e){if(!e||!Array.isArray(e))return!1;for(const i of e)if(!s(i))return!1;return!0}function j$(s,e){return typeof s=="boolean"?s:e}function fSe(s,e){return typeof s=="string"?s:e}function YEt(s){const e={};for(const i of s)e[i]=!0;return e}function gSe(s,e=!1){e&&(s=s.map(function(n){return n.toLowerCase()}));const i=YEt(s);return e?function(n){return i[n.toLowerCase()]!==void 0&&i.hasOwnProperty(n.toLowerCase())}:function(n){return i[n]!==void 0&&i.hasOwnProperty(n)}}function ede(s,e,i){e=e.replace(/@@/g,"");let n=0,r;do r=!1,e=e.replace(/@(\w+)/g,function(a,l){r=!0;let c="";if(typeof s[l]=="string")c=s[l];else if(s[l]&&s[l]instanceof RegExp)c=s[l].source;else throw s[l]===void 0?Qs(s,"language definition does not contain attribute '"+l+"', used at: "+e):Qs(s,"attribute reference '"+l+"' must be a string, used at: "+e);return jC(c)?"":"(?:"+c+")"}),n++;while(r&&n<5);e=e.replace(/\x01/g,"@");const o=(s.ignoreCase?"i":"")+(s.unicode?"u":"");if(i&&e.match(/\$[sS](\d\d?)/g)){let l=null,c=null;return d=>(c&&l===d||(l=d,c=new RegExp(qSt(s,e,d),o)),c)}return new RegExp(e,o)}function XEt(s,e,i,n){if(n<0)return s;if(n<e.length)return e[n];if(n>=100){n=n-100;const r=i.split(".");if(r.unshift(i),n<r.length)return r[n]}return null}function ZEt(s,e,i,n){let r=-1,o=i,a=i.match(/^\$(([sS]?)(\d\d?)|#)(.*)$/);a&&(a[3]&&(r=parseInt(a[3]),a[2]&&(r=r+100)),o=a[4]);let l="~",c=o;!o||o.length===0?(l="!=",c=""):/^\w*$/.test(c)?l="==":(a=o.match(/^(@|!@|~|!~|==|!=)(.*)$/),a&&(l=a[1],c=a[2]));let d;if((l==="~"||l==="!~")&&/^(\w|\|)*$/.test(c)){const u=gSe(c.split("|"),s.ignoreCase);d=function(h){return l==="~"?u(h):!u(h)}}else if(l==="@"||l==="!@"){const u=s[c];if(!u)throw Qs(s,"the @ match target '"+c+"' is not defined, in rule: "+e);if(!KEt(function(f){return typeof f=="string"},u))throw Qs(s,"the @ match target '"+c+"' must be an array of strings, in rule: "+e);const h=gSe(u,s.ignoreCase);d=function(f){return l==="@"?h(f):!h(f)}}else if(l==="~"||l==="!~")if(c.indexOf("$")<0){const u=ede(s,"^"+c+"$",!1);d=function(h){return l==="~"?u.test(h):!u.test(h)}}else d=function(u,h,f,g){return ede(s,"^"+a0(s,c,h,f,g)+"$",!1).test(u)};else if(c.indexOf("$")<0){const u=Qb(s,c);d=function(h){return l==="=="?h===u:h!==u}}else{const u=Qb(s,c);d=function(h,f,g,p,_){const m=a0(s,u,f,g,p);return l==="=="?h===m:h!==m}}return r===-1?{name:i,value:n,test:function(u,h,f,g){return d(u,u,h,f,g)}}:{name:i,value:n,test:function(u,h,f,g){const p=XEt(u,h,f,r);return d(p||"",u,h,f,g)}}}function tde(s,e,i){if(i){if(typeof i=="string")return i;if(i.token||i.token===""){if(typeof i.token!="string")throw Qs(s,"a 'token' attribute must be of type string, in rule: "+e);{const n={token:i.token};if(i.token.indexOf("$")>=0&&(n.tokenSubst=!0),typeof i.bracket=="string")if(i.bracket==="@open")n.bracket=1;else if(i.bracket==="@close")n.bracket=-1;else throw Qs(s,"a 'bracket' attribute must be either '@open' or '@close', in rule: "+e);if(i.next){if(typeof i.next!="string")throw Qs(s,"the next state must be a string value in rule: "+e);{let r=i.next;if(!/^(@pop|@push|@popall)$/.test(r)&&(r[0]==="@"&&(r=r.substr(1)),r.indexOf("$")<0&&!GSt(s,a0(s,r,"",[],""))))throw Qs(s,"the next state '"+i.next+"' is not defined in rule: "+e);n.next=r}}return typeof i.goBack=="number"&&(n.goBack=i.goBack),typeof i.switchTo=="string"&&(n.switchTo=i.switchTo),typeof i.log=="string"&&(n.log=i.log),typeof i.nextEmbedded=="string"&&(n.nextEmbedded=i.nextEmbedded,s.usesEmbedded=!0),n}}else if(Array.isArray(i)){const n=[];for(let r=0,o=i.length;r<o;r++)n[r]=tde(s,e,i[r]);return{group:n}}else if(i.cases){const n=[];let r=!1;for(const a in i.cases)if(i.cases.hasOwnProperty(a)){const l=tde(s,e,i.cases[a]);a==="@default"||a==="@"||a===""?n.push({test:void 0,value:l,name:a}):a==="@eos"?n.push({test:function(c,d,u,h){return h},value:l,name:a}):n.push(ZEt(s,e,a,l)),r||(r=!sa(l)&&(l.hasEmbeddedEndInCases||["@pop","@popall"].includes(l.nextEmbedded||"")))}const o=s.defaultToken;return{hasEmbeddedEndInCases:r,test:function(a,l,c,d){for(const u of n)if(!u.test||u.test(a,l,c,d))return u.value;return o}}}else throw Qs(s,"an action must be a string, an object with a 'token' or 'cases' attribute, or an array of actions; in rule: "+e)}else return{token:""}}class QEt{constructor(e){this.regex=new RegExp(""),this.action={token:""},this.matchOnlyAtLineStart=!1,this.name="",this.name=e}setRegex(e,i){let n;if(typeof i=="string")n=i;else if(i instanceof RegExp)n=i.source;else throw Qs(e,"rules must start with a match string or regular expression: "+this.name);this.matchOnlyAtLineStart=n.length>0&&n[0]==="^",this.name=this.name+": "+n,this.regex=ede(e,"^(?:"+(this.matchOnlyAtLineStart?n.substr(1):n)+")",!0)}setAction(e,i){this.action=tde(e,this.name,i)}resolveRegex(e){return this.regex instanceof RegExp?this.regex:this.regex(e)}}function l$e(s,e){if(!e||typeof e!="object")throw new Error("Monarch: expecting a language definition object");const i={languageId:s,includeLF:j$(e.includeLF,!1),noThrow:!1,maxStack:100,start:typeof e.start=="string"?e.start:null,ignoreCase:j$(e.ignoreCase,!1),unicode:j$(e.unicode,!1),tokenPostfix:fSe(e.tokenPostfix,"."+s),defaultToken:fSe(e.defaultToken,"source"),usesEmbedded:!1,stateNames:{},tokenizer:{},brackets:[]},n=e;n.languageId=s,n.includeLF=i.includeLF,n.ignoreCase=i.ignoreCase,n.unicode=i.unicode,n.noThrow=i.noThrow,n.usesEmbedded=i.usesEmbedded,n.stateNames=e.tokenizer,n.defaultToken=i.defaultToken;function r(a,l,c){for(const d of c){let u=d.include;if(u){if(typeof u!="string")throw Qs(i,"an 'include' attribute must be a string at: "+a);if(u[0]==="@"&&(u=u.substr(1)),!e.tokenizer[u])throw Qs(i,"include target '"+u+"' is not defined at: "+a);r(a+"."+u,l,e.tokenizer[u])}else{const h=new QEt(a);if(Array.isArray(d)&&d.length>=1&&d.length<=3)if(h.setRegex(n,d[0]),d.length>=3)if(typeof d[1]=="string")h.setAction(n,{token:d[1],next:d[2]});else if(typeof d[1]=="object"){const f=d[1];f.next=d[2],h.setAction(n,f)}else throw Qs(i,"a next state as the last element of a rule can only be given if the action is either an object or a string, at: "+a);else h.setAction(n,d[1]);else{if(!d.regex)throw Qs(i,"a rule must either be an array, or an object with a 'regex' or 'include' field at: "+a);d.name&&typeof d.name=="string"&&(h.name=d.name),d.matchOnlyAtStart&&(h.matchOnlyAtLineStart=j$(d.matchOnlyAtLineStart,!1)),h.setRegex(n,d.regex),h.setAction(n,d.action)}l.push(h)}}}if(!e.tokenizer||typeof e.tokenizer!="object")throw Qs(i,"a language definition must define the 'tokenizer' attribute as an object");i.tokenizer=[];for(const a in e.tokenizer)if(e.tokenizer.hasOwnProperty(a)){i.start||(i.start=a);const l=e.tokenizer[a];i.tokenizer[a]=new Array,r("tokenizer."+a,i.tokenizer[a],l)}if(i.usesEmbedded=n.usesEmbedded,e.brackets){if(!Array.isArray(e.brackets))throw Qs(i,"the 'brackets' attribute must be defined as an array")}else e.brackets=[{open:"{",close:"}",token:"delimiter.curly"},{open:"[",close:"]",token:"delimiter.square"},{open:"(",close:")",token:"delimiter.parenthesis"},{open:"<",close:">",token:"delimiter.angle"}];const o=[];for(const a of e.brackets){let l=a;if(l&&Array.isArray(l)&&l.length===3&&(l={token:l[2],open:l[0],close:l[1]}),l.open===l.close)throw Qs(i,"open and close brackets in a 'brackets' attribute must be different: "+l.open+`
|
|
953
|
-
hint: use the 'bracket' attribute if matching on equal brackets is required.`);if(typeof l.open=="string"&&typeof l.token=="string"&&typeof l.close=="string")o.push({token:l.token+i.tokenPostfix,open:Qb(i,l.open),close:Qb(i,l.close)});else throw Qs(i,"every element in the 'brackets' array must be a '{open,close,token}' object or array")}return i.brackets=o,i.noThrow=!0,i}function JEt(s){B2.registerLanguage(s)}function eDt(){let s=[];return s=s.concat(B2.getLanguages()),s}function tDt(s){return ki.get(Pr).languageIdCodec.encodeLanguageId(s)}function iDt(s,e){return ki.withServices(()=>{const n=ki.get(Pr).onDidRequestRichLanguageFeatures(r=>{r===s&&(n.dispose(),e())});return n})}function nDt(s,e){return ki.withServices(()=>{const n=ki.get(Pr).onDidRequestBasicLanguageFeatures(r=>{r===s&&(n.dispose(),e())});return n})}function sDt(s,e){if(!ki.get(Pr).isRegisteredLanguageId(s))throw new Error(`Cannot set configuration for unknown language ${s}`);return ki.get(_r).register(s,e,100)}class rDt{constructor(e,i){this._languageId=e,this._actual=i}dispose(){}getInitialState(){return this._actual.getInitialState()}tokenize(e,i,n){if(typeof this._actual.tokenize=="function")return _5.adaptTokenize(this._languageId,this._actual,e,n);throw new Error("Not supported!")}tokenizeEncoded(e,i,n){const r=this._actual.tokenizeEncoded(e,n);return new lq(r.tokens,r.endState)}}class _5{constructor(e,i,n,r){this._languageId=e,this._actual=i,this._languageService=n,this._standaloneThemeService=r}dispose(){}getInitialState(){return this._actual.getInitialState()}static _toClassicTokens(e,i){const n=[];let r=0;for(let o=0,a=e.length;o<a;o++){const l=e[o];let c=l.startIndex;o===0?c=0:c<r&&(c=r),n[o]=new t4(c,l.scopes,i),r=c}return n}static adaptTokenize(e,i,n,r){const o=i.tokenize(n,r),a=_5._toClassicTokens(o.tokens,e);let l;return o.endState.equals(r)?l=r:l=o.endState,new Ffe(a,l)}tokenize(e,i,n){return _5.adaptTokenize(this._languageId,this._actual,e,n)}_toBinaryTokens(e,i){const n=e.encodeLanguageId(this._languageId),r=this._standaloneThemeService.getColorTheme().tokenTheme,o=[];let a=0,l=0;for(let d=0,u=i.length;d<u;d++){const h=i[d],f=r.match(n,h.scopes)|1024;if(a>0&&o[a-1]===f)continue;let g=h.startIndex;d===0?g=0:g<l&&(g=l),o[a++]=g,o[a++]=f,l=g}const c=new Uint32Array(a);for(let d=0;d<a;d++)c[d]=o[d];return c}tokenizeEncoded(e,i,n){const r=this._actual.tokenize(e,n),o=this._toBinaryTokens(this._languageService.languageIdCodec,r.tokens);let a;return r.endState.equals(n)?a=n:a=r.endState,new lq(o,a)}}function oDt(s){return typeof s.getInitialState=="function"}function aDt(s){return"tokenizeEncoded"in s}function c$e(s){return s&&typeof s.then=="function"}function lDt(s){const e=ki.get(kh);if(s){const i=[null];for(let n=1,r=s.length;n<r;n++)i[n]=Ye.fromHex(s[n]);e.setColorMapOverride(i)}else e.setColorMapOverride(null)}function d$e(s,e){return aDt(e)?new rDt(s,e):new _5(s,e,ki.get(Pr),ki.get(kh))}function gme(s,e){const i=new stt(async()=>{const n=await Promise.resolve(e.create());return n?oDt(n)?d$e(s,n):new d5(ki.get(Pr),ki.get(kh),s,l$e(s,n),ki.get(Oi)):null});return Ir.registerFactory(s,i)}function cDt(s,e){if(!ki.get(Pr).isRegisteredLanguageId(s))throw new Error(`Cannot set tokens provider for unknown language ${s}`);return c$e(e)?gme(s,{create:()=>e}):Ir.register(s,d$e(s,e))}function dDt(s,e){const i=n=>new d5(ki.get(Pr),ki.get(kh),s,l$e(s,n),ki.get(Oi));return c$e(e)?gme(s,{create:()=>e}):Ir.register(s,i(e))}function uDt(s,e){return ki.get(jt).referenceProvider.register(s,e)}function hDt(s,e){return ki.get(jt).renameProvider.register(s,e)}function fDt(s,e){return ki.get(jt).newSymbolNamesProvider.register(s,e)}function gDt(s,e){return ki.get(jt).signatureHelpProvider.register(s,e)}function pDt(s,e){return ki.get(jt).hoverProvider.register(s,{provideHover:async(n,r,o,a)=>{const l=n.getWordAtPosition(r);return Promise.resolve(e.provideHover(n,r,o,a)).then(c=>{if(c)return!c.range&&l&&(c.range=new oe(r.lineNumber,l.startColumn,r.lineNumber,l.endColumn)),c.range||(c.range=new oe(r.lineNumber,r.column,r.lineNumber,r.column)),c})}})}function mDt(s,e){return ki.get(jt).documentSymbolProvider.register(s,e)}function _Dt(s,e){return ki.get(jt).documentHighlightProvider.register(s,e)}function vDt(s,e){return ki.get(jt).linkedEditingRangeProvider.register(s,e)}function bDt(s,e){return ki.get(jt).definitionProvider.register(s,e)}function yDt(s,e){return ki.get(jt).implementationProvider.register(s,e)}function wDt(s,e){return ki.get(jt).typeDefinitionProvider.register(s,e)}function xDt(s,e){return ki.get(jt).codeLensProvider.register(s,e)}function CDt(s,e,i){return ki.get(jt).codeActionProvider.register(s,{providedCodeActionKinds:i==null?void 0:i.providedCodeActionKinds,documentation:i==null?void 0:i.documentation,provideCodeActions:(r,o,a,l)=>{const d=ki.get(Q_).read({resource:r.uri}).filter(u=>oe.areIntersectingOrTouching(u,o));return e.provideCodeActions(r,o,{markers:d,only:a.only,trigger:a.trigger},l)},resolveCodeAction:e.resolveCodeAction})}function SDt(s,e){return ki.get(jt).documentFormattingEditProvider.register(s,e)}function kDt(s,e){return ki.get(jt).documentRangeFormattingEditProvider.register(s,e)}function LDt(s,e){return ki.get(jt).onTypeFormattingEditProvider.register(s,e)}function EDt(s,e){return ki.get(jt).linkProvider.register(s,e)}function DDt(s,e){return ki.get(jt).completionProvider.register(s,e)}function TDt(s,e){return ki.get(jt).colorProvider.register(s,e)}function IDt(s,e){return ki.get(jt).foldingRangeProvider.register(s,e)}function NDt(s,e){return ki.get(jt).declarationProvider.register(s,e)}function RDt(s,e){return ki.get(jt).selectionRangeProvider.register(s,e)}function ADt(s,e){return ki.get(jt).documentSemanticTokensProvider.register(s,e)}function MDt(s,e){return ki.get(jt).documentRangeSemanticTokensProvider.register(s,e)}function PDt(s,e){return ki.get(jt).inlineCompletionsProvider.register(s,e)}function ODt(s,e){return ki.get(jt).inlayHintsProvider.register(s,e)}function FDt(){return{register:JEt,getLanguages:eDt,onLanguage:iDt,onLanguageEncountered:nDt,getEncodedLanguageId:tDt,setLanguageConfiguration:sDt,setColorMap:lDt,registerTokensProviderFactory:gme,setTokensProvider:cDt,setMonarchTokensProvider:dDt,registerReferenceProvider:uDt,registerRenameProvider:hDt,registerNewSymbolNameProvider:fDt,registerCompletionItemProvider:DDt,registerSignatureHelpProvider:gDt,registerHoverProvider:pDt,registerDocumentSymbolProvider:mDt,registerDocumentHighlightProvider:_Dt,registerLinkedEditingRangeProvider:vDt,registerDefinitionProvider:bDt,registerImplementationProvider:yDt,registerTypeDefinitionProvider:wDt,registerCodeLensProvider:xDt,registerCodeActionProvider:CDt,registerDocumentFormattingEditProvider:SDt,registerDocumentRangeFormattingEditProvider:kDt,registerOnTypeFormattingEditProvider:LDt,registerLinkProvider:EDt,registerColorProvider:TDt,registerFoldingRangeProvider:IDt,registerDeclarationProvider:NDt,registerSelectionRangeProvider:RDt,registerDocumentSemanticTokensProvider:ADt,registerDocumentRangeSemanticTokensProvider:MDt,registerInlineCompletionsProvider:PDt,registerInlayHintsProvider:ODt,DocumentHighlightKind:sle,CompletionItemKind:Qae,CompletionItemTag:Jae,CompletionItemInsertTextRule:Zae,SymbolKind:Ole,SymbolTag:Fle,IndentAction:ule,CompletionTriggerKind:ele,SignatureHelpTriggerKind:Ple,InlayHintKind:fle,InlineCompletionTriggerKind:mle,CodeActionTriggerType:Xae,NewSymbolNameTag:Cle,NewSymbolNameTriggerKind:Sle,PartialAcceptTriggerKind:Ele,HoverVerbosityAction:dle,InlineCompletionEndOfLifeReasonKind:gle,InlineCompletionHintStyle:ple,FoldingRangeKind:qL,SelectedSuggestionInfo:WOe,EditDeltaInfo:f4}}pc.wrappingIndent.defaultValue=0;pc.glyphMargin.defaultValue=!1;pc.autoIndent.defaultValue=3;pc.overviewRulerLanes.defaultValue=2;H4.setFormatterSelector((s,e,i)=>Promise.resolve(s[0]));const od=Fje();od.editor=GEt();od.languages=FDt();const u$e=od.CancellationTokenSource,L1=od.Emitter,h$e=od.KeyCode,f$e=od.KeyMod,Fy=od.Position,mR=od.Range,g$e=od.Selection,p$e=od.SelectionDirection,pg=od.MarkerSeverity,rH=od.MarkerTag,iG=od.Uri,m$e=od.Token,D_=od.editor,Bt=od.languages,$X=She(),e2=globalThis;($X!=null&&$X.globalAPI||typeof e2.define=="function"&&e2.define.amd)&&(e2.monaco=od);typeof e2.require<"u"&&typeof e2.require.config=="function"&&e2.require.config({ignoreDuplicateModules:["vscode-languageserver-types","vscode-languageserver-types/main","vscode-languageserver-textdocument","vscode-languageserver-textdocument/main","vscode-nls","vscode-nls/vscode-nls","jsonc-parser","jsonc-parser/main","vscode-uri","vscode-uri/index","vs/basic-languages/typescript/typescript"]});const BDt=Object.freeze(Object.defineProperty({__proto__:null,CancellationTokenSource:u$e,Emitter:L1,KeyCode:h$e,KeyMod:f$e,MarkerSeverity:pg,MarkerTag:rH,Position:Fy,Range:mR,Selection:g$e,SelectionDirection:p$e,Token:m$e,Uri:iG,editor:D_,languages:Bt},Symbol.toStringTag,{value:"Module"}));let pme=class{constructor(e,i,n){this._onDidChange=new L1,this._languageId=e,this.setOptions(i),this.setModeConfiguration(n)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get modeConfiguration(){return this._modeConfiguration}get diagnosticsOptions(){return this.options}get options(){return this._options}setOptions(e){this._options=e||Object.create(null),this._onDidChange.fire(this)}setDiagnosticsOptions(e){this.setOptions(e)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}};const mme={validate:!0,lint:{compatibleVendorPrefixes:"ignore",vendorPrefix:"warning",duplicateProperties:"warning",emptyRules:"warning",importStatement:"ignore",boxModel:"ignore",universalSelector:"ignore",zeroUnits:"ignore",fontFaceProperties:"warning",hexColorLength:"error",argumentsInColorFunction:"error",unknownProperties:"warning",ieHack:"ignore",unknownVendorSpecificProperties:"ignore",propertyIgnoredDueToDisplay:"warning",important:"ignore",float:"ignore",idSelector:"ignore"},data:{useDefaultDataProvider:!0},format:{newlineBetweenSelectors:!0,newlineBetweenRules:!0,spaceAroundSelectorSeparator:!1,braceStyle:"collapse",maxPreserveNewLines:void 0,preserveNewLines:!0}},_me={completionItems:!0,hovers:!0,documentSymbols:!0,definitions:!0,references:!0,documentHighlights:!0,rename:!0,colors:!0,foldingRanges:!0,diagnostics:!0,selectionRanges:!0,documentFormattingEdits:!0,documentRangeFormattingEdits:!0},_$e=new pme("css",mme,_me),v$e=new pme("scss",mme,_me),b$e=new pme("less",mme,_me);function vme(){return ei(()=>import("./cssMode-FA1uC6B_.js"),__vite__mapDeps([0,1]),import.meta.url)}Bt.onLanguage("less",()=>{vme().then(s=>s.setupMode(b$e))});Bt.onLanguage("scss",()=>{vme().then(s=>s.setupMode(v$e))});Bt.onLanguage("css",()=>{vme().then(s=>s.setupMode(_$e))});const y$e=Object.freeze(Object.defineProperty({__proto__:null,cssDefaults:_$e,lessDefaults:b$e,scssDefaults:v$e},Symbol.toStringTag,{value:"Module"}));let jDt=class{constructor(e,i,n){this._onDidChange=new L1,this._languageId=e,this.setOptions(i),this.setModeConfiguration(n)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get options(){return this._options}get modeConfiguration(){return this._modeConfiguration}setOptions(e){this._options=e||Object.create(null),this._onDidChange.fire(this)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}};const $Dt={tabSize:4,insertSpaces:!1,wrapLineLength:120,unformatted:'default": "a, abbr, acronym, b, bdo, big, br, button, cite, code, dfn, em, i, img, input, kbd, label, map, object, q, samp, select, small, span, strong, sub, sup, textarea, tt, var',contentUnformatted:"pre",indentInnerHtml:!1,preserveNewLines:!0,maxPreserveNewLines:void 0,indentHandlebars:!1,endWithNewline:!1,extraLiners:"head, body, /html",wrapAttributes:"auto"},nG={format:$Dt,suggest:{},data:{useDefaultDataProvider:!0}};function sG(s){return{completionItems:!0,hovers:!0,documentSymbols:!0,links:!0,documentHighlights:!0,rename:!0,colors:!0,foldingRanges:!0,selectionRanges:!0,diagnostics:s===qO,documentFormattingEdits:s===qO,documentRangeFormattingEdits:s===qO}}const qO="html",pSe="handlebars",mSe="razor",w$e=rG(qO,nG,sG(qO)),WDt=w$e.defaults,x$e=rG(pSe,nG,sG(pSe)),HDt=x$e.defaults,C$e=rG(mSe,nG,sG(mSe)),VDt=C$e.defaults;function zDt(){return ei(()=>import("./htmlMode-1_WYf3Br.js"),__vite__mapDeps([2,1]),import.meta.url)}function rG(s,e=nG,i=sG(s)){const n=new jDt(s,e,i);let r;const o=Bt.onLanguage(s,async()=>{r=(await zDt()).setupMode(n)});return{defaults:n,dispose(){o.dispose(),r==null||r.dispose(),r=void 0}}}const S$e=Object.freeze(Object.defineProperty({__proto__:null,handlebarDefaults:HDt,handlebarLanguageService:x$e,htmlDefaults:WDt,htmlLanguageService:w$e,razorDefaults:VDt,razorLanguageService:C$e,registerHTMLLanguageService:rG},Symbol.toStringTag,{value:"Module"}));let UDt=class{constructor(e,i,n){this._onDidChange=new L1,this._languageId=e,this.setDiagnosticsOptions(i),this.setModeConfiguration(n)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get modeConfiguration(){return this._modeConfiguration}get diagnosticsOptions(){return this._diagnosticsOptions}setDiagnosticsOptions(e){this._diagnosticsOptions=e||Object.create(null),this._onDidChange.fire(this)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}};const qDt={validate:!0,allowComments:!0,schemas:[],enableSchemaRequest:!1,schemaRequest:"warning",schemaValidation:"warning",comments:"error",trailingCommas:"error"},GDt={documentFormattingEdits:!0,documentRangeFormattingEdits:!0,completionItems:!0,hovers:!0,documentSymbols:!0,tokens:!0,colors:!0,foldingRanges:!0,diagnostics:!0,selectionRanges:!0},k$e=new UDt("json",qDt,GDt),KDt=()=>L$e().then(s=>s.getWorker());function L$e(){return ei(()=>import("./jsonMode-BbyLfnM7.js"),__vite__mapDeps([3,1]),import.meta.url)}Bt.register({id:"json",extensions:[".json",".bowerrc",".jshintrc",".jscsrc",".eslintrc",".babelrc",".har"],aliases:["JSON","json"],mimetypes:["application/json"]});Bt.onLanguage("json",()=>{L$e().then(s=>s.setupMode(k$e))});const E$e=Object.freeze(Object.defineProperty({__proto__:null,getWorker:KDt,jsonDefaults:k$e},Symbol.toStringTag,{value:"Module"})),YDt="5.9.3";var D$e=(s=>(s[s.None=0]="None",s[s.CommonJS=1]="CommonJS",s[s.AMD=2]="AMD",s[s.UMD=3]="UMD",s[s.System=4]="System",s[s.ES2015=5]="ES2015",s[s.ESNext=99]="ESNext",s))(D$e||{}),T$e=(s=>(s[s.None=0]="None",s[s.Preserve=1]="Preserve",s[s.React=2]="React",s[s.ReactNative=3]="ReactNative",s[s.ReactJSX=4]="ReactJSX",s[s.ReactJSXDev=5]="ReactJSXDev",s))(T$e||{}),I$e=(s=>(s[s.CarriageReturnLineFeed=0]="CarriageReturnLineFeed",s[s.LineFeed=1]="LineFeed",s))(I$e||{}),N$e=(s=>(s[s.ES3=0]="ES3",s[s.ES5=1]="ES5",s[s.ES2015=2]="ES2015",s[s.ES2016=3]="ES2016",s[s.ES2017=4]="ES2017",s[s.ES2018=5]="ES2018",s[s.ES2019=6]="ES2019",s[s.ES2020=7]="ES2020",s[s.ESNext=99]="ESNext",s[s.JSON=100]="JSON",s[s.Latest=99]="Latest",s))(N$e||{}),R$e=(s=>(s[s.Classic=1]="Classic",s[s.NodeJs=2]="NodeJs",s))(R$e||{});class A$e{constructor(e,i,n,r,o){this._onDidChange=new L1,this._onDidExtraLibsChange=new L1,this._extraLibs=Object.create(null),this._removedExtraLibs=Object.create(null),this._eagerModelSync=!1,this.setCompilerOptions(e),this.setDiagnosticsOptions(i),this.setWorkerOptions(n),this.setInlayHintsOptions(r),this.setModeConfiguration(o),this._onDidExtraLibsChangeTimeout=-1}get onDidChange(){return this._onDidChange.event}get onDidExtraLibsChange(){return this._onDidExtraLibsChange.event}get modeConfiguration(){return this._modeConfiguration}get workerOptions(){return this._workerOptions}get inlayHintsOptions(){return this._inlayHintsOptions}getExtraLibs(){return this._extraLibs}addExtraLib(e,i){let n;if(typeof i>"u"?n=`ts:extralib-${Math.random().toString(36).substring(2,15)}`:n=i,this._extraLibs[n]&&this._extraLibs[n].content===e)return{dispose:()=>{}};let r=1;return this._removedExtraLibs[n]&&(r=this._removedExtraLibs[n]+1),this._extraLibs[n]&&(r=this._extraLibs[n].version+1),this._extraLibs[n]={content:e,version:r},this._fireOnDidExtraLibsChangeSoon(),{dispose:()=>{let o=this._extraLibs[n];o&&o.version===r&&(delete this._extraLibs[n],this._removedExtraLibs[n]=r,this._fireOnDidExtraLibsChangeSoon())}}}setExtraLibs(e){for(const i in this._extraLibs)this._removedExtraLibs[i]=this._extraLibs[i].version;if(this._extraLibs=Object.create(null),e&&e.length>0)for(const i of e){const n=i.filePath||`ts:extralib-${Math.random().toString(36).substring(2,15)}`,r=i.content;let o=1;this._removedExtraLibs[n]&&(o=this._removedExtraLibs[n]+1),this._extraLibs[n]={content:r,version:o}}this._fireOnDidExtraLibsChangeSoon()}_fireOnDidExtraLibsChangeSoon(){this._onDidExtraLibsChangeTimeout===-1&&(this._onDidExtraLibsChangeTimeout=window.setTimeout(()=>{this._onDidExtraLibsChangeTimeout=-1,this._onDidExtraLibsChange.fire(void 0)},0))}getCompilerOptions(){return this._compilerOptions}setCompilerOptions(e){this._compilerOptions=e||Object.create(null),this._onDidChange.fire(void 0)}getDiagnosticsOptions(){return this._diagnosticsOptions}setDiagnosticsOptions(e){this._diagnosticsOptions=e||Object.create(null),this._onDidChange.fire(void 0)}setWorkerOptions(e){this._workerOptions=e||Object.create(null),this._onDidChange.fire(void 0)}setInlayHintsOptions(e){this._inlayHintsOptions=e||Object.create(null),this._onDidChange.fire(void 0)}setMaximumWorkerIdleTime(e){}setEagerModelSync(e){this._eagerModelSync=e}getEagerModelSync(){return this._eagerModelSync}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(void 0)}}const XDt=YDt,M$e={completionItems:!0,hovers:!0,documentSymbols:!0,definitions:!0,references:!0,documentHighlights:!0,rename:!0,diagnostics:!0,documentRangeFormattingEdits:!0,signatureHelp:!0,onTypeFormattingEdits:!0,codeActions:!0,inlayHints:!0},P$e=new A$e({allowNonTsExtensions:!0,target:99},{noSemanticValidation:!1,noSyntaxValidation:!1,onlyVisible:!1},{},{},M$e),O$e=new A$e({allowNonTsExtensions:!0,allowJs:!0,target:99},{noSemanticValidation:!0,noSyntaxValidation:!1,onlyVisible:!1},{},{},M$e),ZDt=()=>oG().then(s=>s.getTypeScriptWorker()),QDt=()=>oG().then(s=>s.getJavaScriptWorker());function oG(){return ei(()=>import("./tsMode-CtpaN11s.js"),[],import.meta.url)}Bt.onLanguage("typescript",()=>oG().then(s=>s.setupTypeScript(P$e)));Bt.onLanguage("javascript",()=>oG().then(s=>s.setupJavaScript(O$e)));const F$e=Object.freeze(Object.defineProperty({__proto__:null,JsxEmit:T$e,ModuleKind:D$e,ModuleResolutionKind:R$e,NewLineKind:I$e,ScriptTarget:N$e,getJavaScriptWorker:QDt,getTypeScriptWorker:ZDt,javascriptDefaults:O$e,typescriptDefaults:P$e,typescriptVersion:XDt},Symbol.toStringTag,{value:"Module"})),B$e={},WX={};class bme{static getOrCreate(e){return WX[e]||(WX[e]=new bme(e)),WX[e]}constructor(e){this._languageId=e,this._loadingTriggered=!1,this._lazyLoadPromise=new Promise((i,n)=>{this._lazyLoadPromiseResolve=i,this._lazyLoadPromiseReject=n})}load(){return this._loadingTriggered||(this._loadingTriggered=!0,B$e[this._languageId].loader().then(e=>this._lazyLoadPromiseResolve(e),e=>this._lazyLoadPromiseReject(e))),this._lazyLoadPromise}}function di(s){const e=s.id;B$e[e]=s,Bt.register(s);const i=bme.getOrCreate(e);Bt.registerTokensProviderFactory(e,{create:async()=>(await i.load()).language}),Bt.onLanguageEncountered(e,async()=>{const n=await i.load();Bt.setLanguageConfiguration(e,n.conf)})}di({id:"abap",extensions:[".abap"],aliases:["abap","ABAP"],loader:()=>ei(()=>import("./abap-DLDM7-KI.js"),[],import.meta.url)});di({id:"apex",extensions:[".cls"],aliases:["Apex","apex"],mimetypes:["text/x-apex-source","text/x-apex"],loader:()=>ei(()=>import("./apex-DNDY2TF8.js"),[],import.meta.url)});di({id:"azcli",extensions:[".azcli"],aliases:["Azure CLI","azcli"],loader:()=>ei(()=>import("./azcli-Y6nb8tq_.js"),[],import.meta.url)});di({id:"bat",extensions:[".bat",".cmd"],aliases:["Batch","bat"],loader:()=>ei(()=>import("./bat-BwHxbl9M.js"),[],import.meta.url)});di({id:"bicep",extensions:[".bicep"],aliases:["Bicep"],loader:()=>ei(()=>import("./bicep-CFznDFnq.js"),[],import.meta.url)});di({id:"cameligo",extensions:[".mligo"],aliases:["Cameligo"],loader:()=>ei(()=>import("./cameligo-Bf6VGUru.js"),[],import.meta.url)});di({id:"clojure",extensions:[".clj",".cljs",".cljc",".edn"],aliases:["clojure","Clojure"],loader:()=>ei(()=>import("./clojure-Dnu-v4kV.js"),[],import.meta.url)});di({id:"coffeescript",extensions:[".coffee"],aliases:["CoffeeScript","coffeescript","coffee"],mimetypes:["text/x-coffeescript","text/coffeescript"],loader:()=>ei(()=>import("./coffee-Bd8akH9Z.js"),[],import.meta.url)});di({id:"c",extensions:[".c",".h"],aliases:["C","c"],loader:()=>ei(()=>import("./cpp-BbWJElDN.js"),[],import.meta.url)});di({id:"cpp",extensions:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],aliases:["C++","Cpp","cpp"],loader:()=>ei(()=>import("./cpp-BbWJElDN.js"),[],import.meta.url)});di({id:"csharp",extensions:[".cs",".csx",".cake"],aliases:["C#","csharp"],loader:()=>ei(()=>import("./csharp-Co3qMtFm.js"),[],import.meta.url)});di({id:"csp",extensions:[".csp"],aliases:["CSP","csp"],loader:()=>ei(()=>import("./csp-D-4FJmMZ.js"),[],import.meta.url)});di({id:"css",extensions:[".css"],aliases:["CSS","css"],mimetypes:["text/css"],loader:()=>ei(()=>import("./css-DdJfP1eB.js"),[],import.meta.url)});di({id:"cypher",extensions:[".cypher",".cyp"],aliases:["Cypher","OpenCypher"],loader:()=>ei(()=>import("./cypher-cTPe9QuQ.js"),[],import.meta.url)});di({id:"dart",extensions:[".dart"],aliases:["Dart","dart"],mimetypes:["text/x-dart-source","text/x-dart"],loader:()=>ei(()=>import("./dart-BOtBlQCF.js"),[],import.meta.url)});di({id:"dockerfile",extensions:[".dockerfile"],filenames:["Dockerfile"],aliases:["Dockerfile"],loader:()=>ei(()=>import("./dockerfile-BG73LgW2.js"),[],import.meta.url)});di({id:"ecl",extensions:[".ecl"],aliases:["ECL","Ecl","ecl"],loader:()=>ei(()=>import("./ecl-BEgZUVRK.js"),[],import.meta.url)});di({id:"elixir",extensions:[".ex",".exs"],aliases:["Elixir","elixir","ex"],loader:()=>ei(()=>import("./elixir-BkW5O-1t.js"),[],import.meta.url)});di({id:"flow9",extensions:[".flow"],aliases:["Flow9","Flow","flow9","flow"],loader:()=>ei(()=>import("./flow9-BeJ5waoc.js"),[],import.meta.url)});di({id:"fsharp",extensions:[".fs",".fsi",".ml",".mli",".fsx",".fsscript"],aliases:["F#","FSharp","fsharp"],loader:()=>ei(()=>import("./fsharp-PahG7c26.js"),[],import.meta.url)});di({id:"freemarker2",extensions:[".ftl",".ftlh",".ftlx"],aliases:["FreeMarker2","Apache FreeMarker2"],loader:()=>ei(()=>import("./freemarker2-DYaF01LX.js"),[],import.meta.url).then(s=>s.TagAutoInterpolationDollar)});di({id:"freemarker2.tag-angle.interpolation-dollar",aliases:["FreeMarker2 (Angle/Dollar)","Apache FreeMarker2 (Angle/Dollar)"],loader:()=>ei(()=>import("./freemarker2-DYaF01LX.js"),[],import.meta.url).then(s=>s.TagAngleInterpolationDollar)});di({id:"freemarker2.tag-bracket.interpolation-dollar",aliases:["FreeMarker2 (Bracket/Dollar)","Apache FreeMarker2 (Bracket/Dollar)"],loader:()=>ei(()=>import("./freemarker2-DYaF01LX.js"),[],import.meta.url).then(s=>s.TagBracketInterpolationDollar)});di({id:"freemarker2.tag-angle.interpolation-bracket",aliases:["FreeMarker2 (Angle/Bracket)","Apache FreeMarker2 (Angle/Bracket)"],loader:()=>ei(()=>import("./freemarker2-DYaF01LX.js"),[],import.meta.url).then(s=>s.TagAngleInterpolationBracket)});di({id:"freemarker2.tag-bracket.interpolation-bracket",aliases:["FreeMarker2 (Bracket/Bracket)","Apache FreeMarker2 (Bracket/Bracket)"],loader:()=>ei(()=>import("./freemarker2-DYaF01LX.js"),[],import.meta.url).then(s=>s.TagBracketInterpolationBracket)});di({id:"freemarker2.tag-auto.interpolation-dollar",aliases:["FreeMarker2 (Auto/Dollar)","Apache FreeMarker2 (Auto/Dollar)"],loader:()=>ei(()=>import("./freemarker2-DYaF01LX.js"),[],import.meta.url).then(s=>s.TagAutoInterpolationDollar)});di({id:"freemarker2.tag-auto.interpolation-bracket",aliases:["FreeMarker2 (Auto/Bracket)","Apache FreeMarker2 (Auto/Bracket)"],loader:()=>ei(()=>import("./freemarker2-DYaF01LX.js"),[],import.meta.url).then(s=>s.TagAutoInterpolationBracket)});di({id:"go",extensions:[".go"],aliases:["Go"],loader:()=>ei(()=>import("./go-acbASCJo.js"),[],import.meta.url)});di({id:"graphql",extensions:[".graphql",".gql"],aliases:["GraphQL","graphql","gql"],mimetypes:["application/graphql"],loader:()=>ei(()=>import("./graphql-BxJiqAUM.js"),[],import.meta.url)});di({id:"handlebars",extensions:[".handlebars",".hbs"],aliases:["Handlebars","handlebars","hbs"],mimetypes:["text/x-handlebars-template"],loader:()=>ei(()=>import("./handlebars-Da7b36Lf.js"),[],import.meta.url)});di({id:"hcl",extensions:[".tf",".tfvars",".hcl"],aliases:["Terraform","tf","HCL","hcl"],loader:()=>ei(()=>import("./hcl-DtV1sZF8.js"),[],import.meta.url)});di({id:"html",extensions:[".html",".htm",".shtml",".xhtml",".mdoc",".jsp",".asp",".aspx",".jshtm"],aliases:["HTML","htm","html","xhtml"],mimetypes:["text/html","text/x-jshtm","text/template","text/ng-template"],loader:()=>ei(()=>import("./html-CEBCag3L.js"),[],import.meta.url)});di({id:"ini",extensions:[".ini",".properties",".gitconfig"],filenames:["config",".gitattributes",".gitconfig",".editorconfig"],aliases:["Ini","ini"],loader:()=>ei(()=>import("./ini-Kd9XrMLS.js"),[],import.meta.url)});di({id:"java",extensions:[".java",".jav"],aliases:["Java","java"],mimetypes:["text/x-java-source","text/x-java"],loader:()=>ei(()=>import("./java-CXBNlu9o.js"),[],import.meta.url)});di({id:"javascript",extensions:[".js",".es6",".jsx",".mjs",".cjs"],firstLine:"^#!.*\\bnode",filenames:["jakefile"],aliases:["JavaScript","javascript","js"],mimetypes:["text/javascript"],loader:()=>ei(()=>import("./javascript-DKWzZR-I.js"),__vite__mapDeps([4,5]),import.meta.url)});di({id:"julia",extensions:[".jl"],aliases:["julia","Julia"],loader:()=>ei(()=>import("./julia-cl7-CwDS.js"),[],import.meta.url)});di({id:"kotlin",extensions:[".kt",".kts"],aliases:["Kotlin","kotlin"],mimetypes:["text/x-kotlin-source","text/x-kotlin"],loader:()=>ei(()=>import("./kotlin-s7OhZKlX.js"),[],import.meta.url)});di({id:"less",extensions:[".less"],aliases:["Less","less"],mimetypes:["text/x-less","text/less"],loader:()=>ei(()=>import("./less-9HpZscsL.js"),[],import.meta.url)});di({id:"lexon",extensions:[".lex"],aliases:["Lexon"],loader:()=>ei(()=>import("./lexon-OrD6JF1K.js"),[],import.meta.url)});di({id:"lua",extensions:[".lua"],aliases:["Lua","lua"],loader:()=>ei(()=>import("./lua-Cyyb5UIc.js"),[],import.meta.url)});di({id:"liquid",extensions:[".liquid",".html.liquid"],aliases:["Liquid","liquid"],mimetypes:["application/liquid"],loader:()=>ei(()=>import("./liquid-BbbdIZ5H.js"),[],import.meta.url)});di({id:"m3",extensions:[".m3",".i3",".mg",".ig"],aliases:["Modula-3","Modula3","modula3","m3"],loader:()=>ei(()=>import("./m3-B8OfTtLu.js"),[],import.meta.url)});di({id:"markdown",extensions:[".md",".markdown",".mdown",".mkdn",".mkd",".mdwn",".mdtxt",".mdtext"],aliases:["Markdown","markdown"],loader:()=>ei(()=>import("./markdown-BFxVWTOG.js"),[],import.meta.url)});di({id:"mdx",extensions:[".mdx"],aliases:["MDX","mdx"],loader:()=>ei(()=>import("./mdx-BKuETQUL.js"),[],import.meta.url)});di({id:"mips",extensions:[".s"],aliases:["MIPS","MIPS-V"],mimetypes:["text/x-mips","text/mips","text/plaintext"],loader:()=>ei(()=>import("./mips-CiqrrVzr.js"),[],import.meta.url)});di({id:"msdax",extensions:[".dax",".msdax"],aliases:["DAX","MSDAX"],loader:()=>ei(()=>import("./msdax-DmeGPVcC.js"),[],import.meta.url)});di({id:"mysql",extensions:[],aliases:["MySQL","mysql"],loader:()=>ei(()=>import("./mysql-C_tMU-Nz.js"),[],import.meta.url)});di({id:"objective-c",extensions:[".m"],aliases:["Objective-C"],loader:()=>ei(()=>import("./objective-c-BDtDVThU.js"),[],import.meta.url)});di({id:"pascal",extensions:[".pas",".p",".pp"],aliases:["Pascal","pas"],mimetypes:["text/x-pascal-source","text/x-pascal"],loader:()=>ei(()=>import("./pascal-vHIfCaH5.js"),[],import.meta.url)});di({id:"pascaligo",extensions:[".ligo"],aliases:["Pascaligo","ligo"],loader:()=>ei(()=>import("./pascaligo-DtZ0uQbO.js"),[],import.meta.url)});di({id:"perl",extensions:[".pl",".pm"],aliases:["Perl","pl"],loader:()=>ei(()=>import("./perl-Ub6l9XKa.js"),[],import.meta.url)});di({id:"pgsql",extensions:[],aliases:["PostgreSQL","postgres","pg","postgre"],loader:()=>ei(()=>import("./pgsql-BlNEE0v7.js"),[],import.meta.url)});di({id:"php",extensions:[".php",".php4",".php5",".phtml",".ctp"],aliases:["PHP","php"],mimetypes:["application/x-php"],loader:()=>ei(()=>import("./php-BBUBE1dy.js"),[],import.meta.url)});di({id:"pla",extensions:[".pla"],loader:()=>ei(()=>import("./pla-DSh2-awV.js"),[],import.meta.url)});di({id:"postiats",extensions:[".dats",".sats",".hats"],aliases:["ATS","ATS/Postiats"],loader:()=>ei(()=>import("./postiats-CocnycG-.js"),[],import.meta.url)});di({id:"powerquery",extensions:[".pq",".pqm"],aliases:["PQ","M","Power Query","Power Query M"],loader:()=>ei(()=>import("./powerquery-tScXyioY.js"),[],import.meta.url)});di({id:"powershell",extensions:[".ps1",".psm1",".psd1"],aliases:["PowerShell","powershell","ps","ps1"],loader:()=>ei(()=>import("./powershell-COWaemsV.js"),[],import.meta.url)});di({id:"proto",extensions:[".proto"],aliases:["protobuf","Protocol Buffers"],loader:()=>ei(()=>import("./protobuf-Brw8urJB.js"),[],import.meta.url)});di({id:"pug",extensions:[".jade",".pug"],aliases:["Pug","Jade","jade"],loader:()=>ei(()=>import("./pug-8SOpv6rk.js"),[],import.meta.url)});di({id:"python",extensions:[".py",".rpy",".pyw",".cpy",".gyp",".gypi"],aliases:["Python","py"],firstLine:"^#!/.*\\bpython[0-9.-]*\\b",loader:()=>ei(()=>import("./python-BiJja-9i.js"),[],import.meta.url)});di({id:"qsharp",extensions:[".qs"],aliases:["Q#","qsharp"],loader:()=>ei(()=>import("./qsharp-Bw9ernYp.js"),[],import.meta.url)});di({id:"r",extensions:[".r",".rhistory",".rmd",".rprofile",".rt"],aliases:["R","r"],loader:()=>ei(()=>import("./r-j7ic8hl3.js"),[],import.meta.url)});di({id:"razor",extensions:[".cshtml"],aliases:["Razor","razor"],mimetypes:["text/x-cshtml"],loader:()=>ei(()=>import("./razor-DnGCqquD.js"),[],import.meta.url)});di({id:"redis",extensions:[".redis"],aliases:["redis"],loader:()=>ei(()=>import("./redis-Bu5POkcn.js"),[],import.meta.url)});di({id:"redshift",extensions:[],aliases:["Redshift","redshift"],loader:()=>ei(()=>import("./redshift-Bs9aos_-.js"),[],import.meta.url)});di({id:"restructuredtext",extensions:[".rst"],aliases:["reStructuredText","restructuredtext"],loader:()=>ei(()=>import("./restructuredtext-CqXO7rUv.js"),[],import.meta.url)});di({id:"ruby",extensions:[".rb",".rbx",".rjs",".gemspec",".pp"],filenames:["rakefile","Gemfile"],aliases:["Ruby","rb"],loader:()=>ei(()=>import("./ruby-zBfavPgS.js"),[],import.meta.url)});di({id:"rust",extensions:[".rs",".rlib"],aliases:["Rust","rust"],loader:()=>ei(()=>import("./rust-BzKRNQWT.js"),[],import.meta.url)});di({id:"sb",extensions:[".sb"],aliases:["Small Basic","sb"],loader:()=>ei(()=>import("./sb-BBc9UKZt.js"),[],import.meta.url)});di({id:"scala",extensions:[".scala",".sc",".sbt"],aliases:["Scala","scala","SBT","Sbt","sbt","Dotty","dotty"],mimetypes:["text/x-scala-source","text/x-scala","text/x-sbt","text/x-dotty"],loader:()=>ei(()=>import("./scala-D9hQfWCl.js"),[],import.meta.url)});di({id:"scheme",extensions:[".scm",".ss",".sch",".rkt"],aliases:["scheme","Scheme"],loader:()=>ei(()=>import("./scheme-BPhDTwHR.js"),[],import.meta.url)});di({id:"scss",extensions:[".scss"],aliases:["Sass","sass","scss"],mimetypes:["text/x-scss","text/scss"],loader:()=>ei(()=>import("./scss-CBJaRo0y.js"),[],import.meta.url)});di({id:"shell",extensions:[".sh",".bash"],aliases:["Shell","sh"],loader:()=>ei(()=>import("./shell-DiJ1NA_G.js"),[],import.meta.url)});di({id:"sol",extensions:[".sol"],aliases:["sol","solidity","Solidity"],loader:()=>ei(()=>import("./solidity-Db0IVjzk.js"),[],import.meta.url)});di({id:"aes",extensions:[".aes"],aliases:["aes","sophia","Sophia"],loader:()=>ei(()=>import("./sophia-CnS9iZB_.js"),[],import.meta.url)});di({id:"sparql",extensions:[".rq"],aliases:["sparql","SPARQL"],loader:()=>ei(()=>import("./sparql-CJmd_6j2.js"),[],import.meta.url)});di({id:"sql",extensions:[".sql"],aliases:["SQL"],loader:()=>ei(()=>import("./sql-ClhHkBeG.js"),[],import.meta.url)});di({id:"st",extensions:[".st",".iecst",".iecplc",".lc3lib",".TcPOU",".TcDUT",".TcGVL",".TcIO"],aliases:["StructuredText","scl","stl"],loader:()=>ei(()=>import("./st-CHwy0fLd.js"),[],import.meta.url)});di({id:"swift",aliases:["Swift","swift"],extensions:[".swift"],mimetypes:["text/swift"],loader:()=>ei(()=>import("./swift-Bqt4WxQ4.js"),[],import.meta.url)});di({id:"systemverilog",extensions:[".sv",".svh"],aliases:["SV","sv","SystemVerilog","systemverilog"],loader:()=>ei(()=>import("./systemverilog-Bs9z6M-B.js"),[],import.meta.url)});di({id:"verilog",extensions:[".v",".vh"],aliases:["V","v","Verilog","verilog"],loader:()=>ei(()=>import("./systemverilog-Bs9z6M-B.js"),[],import.meta.url)});di({id:"tcl",extensions:[".tcl"],aliases:["tcl","Tcl","tcltk","TclTk","tcl/tk","Tcl/Tk"],loader:()=>ei(()=>import("./tcl-Dm6ycUr_.js"),[],import.meta.url)});di({id:"twig",extensions:[".twig"],aliases:["Twig","twig"],mimetypes:["text/x-twig"],loader:()=>ei(()=>import("./twig-Csy3S7wG.js"),[],import.meta.url)});di({id:"typescript",extensions:[".ts",".tsx",".cts",".mts"],aliases:["TypeScript","ts","typescript"],mimetypes:["text/typescript"],loader:()=>ei(()=>import("./typescript-Cx21wAbo.js"),[],import.meta.url)});di({id:"typespec",extensions:[".tsp"],aliases:["TypeSpec"],loader:()=>ei(()=>import("./typespec-Btyra-wh.js"),[],import.meta.url)});di({id:"vb",extensions:[".vb"],aliases:["Visual Basic","vb"],loader:()=>ei(()=>import("./vb-Db0cS2oM.js"),[],import.meta.url)});di({id:"wgsl",extensions:[".wgsl"],aliases:["WebGPU Shading Language","WGSL","wgsl"],loader:()=>ei(()=>import("./wgsl-BTesnYfV.js"),[],import.meta.url)});di({id:"xml",extensions:[".xml",".xsd",".dtd",".ascx",".csproj",".config",".props",".targets",".wxi",".wxl",".wxs",".xaml",".svg",".svgz",".opf",".xslt",".xsl"],firstLine:"(\\<\\?xml.*)|(\\<svg)|(\\<\\!doctype\\s+svg)",aliases:["XML","xml"],mimetypes:["text/xml","application/xml","application/xaml+xml","application/xml-dtd"],loader:()=>ei(()=>import("./xml-BgafHH5c.js"),[],import.meta.url)});di({id:"yaml",extensions:[".yaml",".yml"],aliases:["YAML","yaml","YML","yml"],mimetypes:["application/x-yaml","text/x-yaml"],loader:()=>ei(()=>import("./yaml-BtU-Gr1g.js"),[],import.meta.url)});var JDt=Object.defineProperty,eTt=(s,e,i)=>e in s?JDt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):s[e]=i,ri=(s,e,i)=>eTt(s,typeof e!="symbol"?e+"":e,i),$$,_Se,W$,HX,H$;function tTt(s){return s.method!==void 0}var vSe;(function(s){function e(i){return i}s.create=e})(vSe||(vSe={}));var dg;(function(s){s.parseError=-32700,s.invalidRequest=-32600,s.methodNotFound=-32601,s.invalidParams=-32602,s.internalError=-32603;function e(o){return-32099<=o&&o<=-32e3}s.isServerError=e;function i(o){if(!e(o))throw new Error("Invalid range for a server error.");return o}s.serverError=i,s.unexpectedServerError=-32e3;function n(o){return!0}s.isApplicationError=n;function r(o){return o}s.applicationError=r,s.genericApplicationError=-320100})(dg||(dg={}));var yme=class{constructor(){ri(this,"listeners",new Set),ri(this,"event",e=>(this.listeners.add(e),{dispose:()=>{this.listeners.delete(e)}}))}fire(e){this.listeners.forEach(i=>i(e))}},iTt=class{constructor(s){ri(this,"_value"),ri(this,"eventEmitter"),this._value=s,this.eventEmitter=new yme}get value(){return this._value}set value(s){this._value!==s&&(this._value=s,this.eventEmitter.fire(s))}get onChange(){return this.eventEmitter.event}};function nTt(s,e){const i=setTimeout(e,s);return{dispose:()=>clearTimeout(i)}}function VX(s,e,i){return s instanceof Set?(s.add(e),{dispose:()=>s.delete(e)}):(s.set(e,i),{dispose:()=>s.delete(e)})}var sTt=class{constructor(){ri(this,"_state","none"),ri(this,"promise"),ri(this,"resolve",()=>{}),ri(this,"reject",()=>{}),this.promise=new Promise((s,e)=>{this.resolve=s,this.reject=e})}get state(){return this._state}},j$e=($$=class{constructor(){ri(this,"_unprocessedMessages",[]),ri(this,"_messageListener"),ri(this,"id",$$.id++),ri(this,"_state",new iTt({state:"open"})),ri(this,"state",this._state)}setListener(s){if(this._messageListener=s,!!s)for(;this._unprocessedMessages.length>0&&this._messageListener!==void 0;){const e=this._unprocessedMessages.shift();this._messageListener(e)}}send(s){return this._sendImpl(s)}_dispatchReceivedMessage(s){this._unprocessedMessages.length===0&&this._messageListener?this._messageListener(s):this._unprocessedMessages.push(s)}_onConnectionClosed(){this._state.value={state:"closed",error:void 0}}log(s){return new rTt(this,s??new oTt)}},ri($$,"id",0),$$),rTt=class{constructor(s,e){ri(this,"baseStream"),ri(this,"logger"),this.baseStream=s,this.logger=e}get state(){return this.baseStream.state}setListener(s){if(s===void 0){this.baseStream.setListener(void 0);return}this.baseStream.setListener(e=>{this.logger.log(this.baseStream,"incoming",e),s(e)})}send(s){return this.logger.log(this.baseStream,"outgoing",s),this.baseStream.send(s)}toString(){return`StreamLogger/${this.baseStream.toString()}`}},oTt=class{log(s,e,i){console.log(`${e==="incoming"?"<-":"->"} [${s.toString()}] ${JSON.stringify(i)}`)}},aTt=class $$e{constructor(e){ri(this,"connect"),this.connect=e}mapContext(e){return new $$e(i=>this.connect(i?lTt(i,e):void 0))}};function lTt(s,e){return{handleNotification:(i,n)=>s.handleNotification(i,e(n)),handleRequest:(i,n,r)=>s.handleRequest(i,n,e(r))}}var cTt=class W$e{constructor(e,i,n){ri(this,"_stream"),ri(this,"_listener"),ri(this,"_logger"),ri(this,"_unprocessedResponses",new Map),ri(this,"_lastUsedRequestId",0),this._stream=e,this._listener=i,this._logger=n,this._stream.setListener(r=>{tTt(r)?r.id===void 0?this._processNotification(r):this._processRequest(r):this._processResponse(r)})}static createChannel(e,i){let n=!1;return new aTt(r=>{if(n)throw new Error(`A channel to the stream ${e} was already constructed!`);return n=!0,new W$e(e,r,i)})}get state(){return this._stream.state}async _processNotification(e){if(e.id!==void 0)throw new Error;if(!this._listener){this._logger&&this._logger.debug({text:"Notification ignored",message:e});return}try{await this._listener.handleNotification({method:e.method,params:e.params||null})}catch(i){this._logger&&this._logger.warn({text:`Exception was thrown while handling notification: ${i}`,exception:i,message:e})}}async _processRequest(e){if(e.id===void 0)throw new Error;let i;if(this._listener)try{i=await this._listener.handleRequest({method:e.method,params:e.params||null},e.id)}catch(r){this._logger&&this._logger.warn({text:`Exception was thrown while handling request: ${r}`,message:e,exception:r}),i={error:{code:dg.internalError,message:"An unexpected exception was thrown.",data:void 0}}}else this._logger&&this._logger.debug({text:"Received request even though not listening for requests",message:e}),i={error:{code:dg.methodNotFound,message:"This endpoint does not listen for requests or notifications.",data:void 0}};let n;"result"in i?n={jsonrpc:"2.0",id:e.id,result:i.result}:n={jsonrpc:"2.0",id:e.id,error:i.error},await this._stream.send(n)}_processResponse(e){const i=""+e.id,n=this._unprocessedResponses.get(i);if(!n){this._logger&&this._logger.debug({text:"Got an unexpected response message",message:e});return}this._unprocessedResponses.delete(i),n(e)}_newRequestId(){return this._lastUsedRequestId++}sendRequest(e,i,n){const r={jsonrpc:"2.0",id:this._newRequestId(),method:e.method,params:e.params||void 0};return n&&n(r.id),new Promise((o,a)=>{const l=""+r.id;this._unprocessedResponses.set(l,c=>{"result"in c?o({result:c.result}):(c.error||a(new Error("Response had neither 'result' nor 'error' field set.")),o({error:c.error}))}),this._stream.send(r).then(void 0,c=>{this._unprocessedResponses.delete(l),a(c)})})}sendNotification(e,i){const n={jsonrpc:"2.0",id:void 0,method:e.method,params:e.params||void 0};return this._stream.send(n)}toString(){return"StreamChannel/"+this._stream.toString()}},t2;(function(s){function e(){return{deserializeFromJson:r=>({hasErrors:!1,value:r}),serializeToJson:r=>r}}s.sAny=e;function i(){return{deserializeFromJson:r=>({hasErrors:!1,value:{}}),serializeToJson:r=>({})}}s.sEmptyObject=i;function n(){return{deserializeFromJson:r=>({hasErrors:!1,value:void 0}),serializeToJson:r=>null}}s.sVoidFromNull=n})(t2||(t2={}));const H$e=Symbol("OptionalMethodNotFound");var V$e=class{contextualize(s){return new dTt(this,s)}},dTt=class extends V$e{constructor(s,e){super(),ri(this,"underylingTypedChannel"),ri(this,"converters"),this.underylingTypedChannel=s,this.converters=e}async request(s,e,i){const n=await this.converters.getSendContext(i);return this.underylingTypedChannel.request(s,e,n)}async notify(s,e,i){const n=await this.converters.getSendContext(i);return this.underylingTypedChannel.notify(s,e,n)}registerNotificationHandler(s,e){return this.underylingTypedChannel.registerNotificationHandler(s,async(i,n)=>await e(i,await this.converters.getNewContext(n)))}registerRequestHandler(s,e){return this.underylingTypedChannel.registerRequestHandler(s,async(i,n,r)=>await e(i,n,await this.converters.getNewContext(r)))}},ide=class z$e extends V$e{constructor(e,i={}){super(),ri(this,"channelCtor"),ri(this,"_requestSender"),ri(this,"_handler",new Map),ri(this,"_unknownNotificationHandler",new Set),ri(this,"_timeout"),ri(this,"sendExceptionDetails",!1),ri(this,"_logger"),ri(this,"listeningDeferred",new sTt),ri(this,"onListening",this.listeningDeferred.promise),ri(this,"_requestDidErrorEventEmitter",new yme),ri(this,"onRequestDidError",this._requestDidErrorEventEmitter.event),this.channelCtor=e,this._logger=i.logger,this.sendExceptionDetails=!!i.sendExceptionDetails,this._timeout=nTt(1e3,()=>{this._requestSender||console.warn(`"${this.startListen.name}" has not been called within 1 second after construction of this channel. Did you forget to call it?`,this)})}static fromTransport(e,i={}){return new z$e(cTt.createChannel(e,i.logger),i)}startListen(){if(this._requestSender)throw new Error(`"${this.startListen.name}" can be called only once, but it already has been called.`);this._timeout&&(this._timeout.dispose(),this._timeout=void 0),this._requestSender=this.channelCtor.connect({handleRequest:(e,i,n)=>this.handleRequest(e,i,n),handleNotification:(e,i)=>this.handleNotification(e,i)}),this.listeningDeferred.resolve()}checkChannel(e){if(!e)throw new Error(`"${this.startListen.name}" must be called before any messages can be sent or received.`);return!0}async handleRequest(e,i,n){const r=this._handler.get(e.method);if(!r)return this._logger&&this._logger.debug({text:`No request handler for "${e.method}".`,data:{requestObject:e}}),{error:{code:dg.methodNotFound,message:`No request handler for "${e.method}".`,data:{method:e.method}}};if(r.kind!="request"){const a=`"${e.method}" is registered as notification, but was sent as request.`;return this._logger&&this._logger.debug({text:a,data:{requestObject:e}}),{error:{code:dg.invalidRequest,message:a,data:{method:e.method}}}}const o=r.requestType.paramsSerializer.deserializeFromJson(e.params);if(o.hasErrors){const a=`Got invalid params: ${o.errorMessage}`;return this._logger&&this._logger.debug({text:a,data:{requestObject:e,errorMessage:o.errorMessage}}),{error:{code:dg.invalidParams,message:a,data:{errors:o.errorMessage}}}}else{const a=o.value;let l;try{const c=await r.handler(a,i,n);if("error"in c||"errorMessage"in c){const d=c.error?r.requestType.errorSerializer.serializeToJson(c.error):void 0;l={error:{code:c.errorCode||dg.genericApplicationError,message:c.errorMessage||"An error was returned",data:d}}}else l={result:r.requestType.resultSerializer.serializeToJson(c.ok)}}catch(c){c instanceof ySe?l={error:{code:c.code,message:c.message}}:(this._logger&&this._logger.warn({text:`An exception was thrown while handling a request: ${c}.`,exception:c,data:{requestObject:e}}),l={error:{code:dg.unexpectedServerError,message:this.sendExceptionDetails?`An exception was thrown while handling a request: ${c}.`:"Server has thrown an unexpected exception"}})}return l}}async handleNotification(e,i){const n=this._handler.get(e.method);if(!n){for(const a of this._unknownNotificationHandler)a(e);this._unknownNotificationHandler.size===0&&this._logger&&this._logger.debug({text:`Unhandled notification "${e.method}"`,data:{requestObject:e}});return}if(n.kind!="notification"){this._logger&&this._logger.debug({text:`"${e.method}" is registered as request, but was sent as notification.`,data:{requestObject:e}});return}const r=n.notificationType.paramsSerializer.deserializeFromJson(e.params);if(r.hasErrors){this._logger&&this._logger.debug({text:`Got invalid params: ${r}`,data:{requestObject:e,errorMessage:r.errorMessage}});return}const o=r.value;for(const a of n.handlers)try{a(o,i)}catch(l){this._logger&&this._logger.warn({text:`An exception was thrown while handling a notification: ${l}.`,exception:l,data:{requestObject:e}})}}registerUnknownNotificationHandler(e){return VX(this._unknownNotificationHandler,e)}registerRequestHandler(e,i){if(this._handler.get(e.method))throw new Error(`Handler with method "${e.method}" already registered.`);return VX(this._handler,e.method,{kind:"request",requestType:e,handler:i})}registerNotificationHandler(e,i){let n=this._handler.get(e.method);if(!n)n={kind:"notification",notificationType:e,handlers:new Set},this._handler.set(e.method,n);else{if(n.kind!=="notification")throw new Error(`Method "${e.method}" was already registered as request handler.`);if(n.notificationType!==e)throw new Error(`Method "${e.method}" was registered for a different type.`)}return VX(n.handlers,i)}getRegisteredTypes(){const e=[];for(const i of this._handler.values())i.kind==="notification"?e.push(i.notificationType):i.kind==="request"&&e.push(i.requestType);return e}async request(e,i,n){if(!this.checkChannel(this._requestSender))throw new Error("Impossible");const r=e.paramsSerializer.serializeToJson(i);bSe(r);const o=await this._requestSender.sendRequest({method:e.method,params:r},n);if("error"in o){if(e.isOptional&&o.error.code===dg.methodNotFound)return H$e;let a;if(o.error.data!==void 0){const c=e.errorSerializer.deserializeFromJson(o.error.data);if(c.hasErrors)throw new Error(c.errorMessage);a=c.value}else a=void 0;const l=new ySe(o.error.message,a,o.error.code);throw this._requestDidErrorEventEmitter.fire({error:l}),l}else{const a=e.resultSerializer.deserializeFromJson(o.result);if(a.hasErrors)throw new Error("Could not deserialize response: "+a.errorMessage+`
|
|
953
|
+
hint: use the 'bracket' attribute if matching on equal brackets is required.`);if(typeof l.open=="string"&&typeof l.token=="string"&&typeof l.close=="string")o.push({token:l.token+i.tokenPostfix,open:Qb(i,l.open),close:Qb(i,l.close)});else throw Qs(i,"every element in the 'brackets' array must be a '{open,close,token}' object or array")}return i.brackets=o,i.noThrow=!0,i}function JEt(s){B2.registerLanguage(s)}function eDt(){let s=[];return s=s.concat(B2.getLanguages()),s}function tDt(s){return ki.get(Pr).languageIdCodec.encodeLanguageId(s)}function iDt(s,e){return ki.withServices(()=>{const n=ki.get(Pr).onDidRequestRichLanguageFeatures(r=>{r===s&&(n.dispose(),e())});return n})}function nDt(s,e){return ki.withServices(()=>{const n=ki.get(Pr).onDidRequestBasicLanguageFeatures(r=>{r===s&&(n.dispose(),e())});return n})}function sDt(s,e){if(!ki.get(Pr).isRegisteredLanguageId(s))throw new Error(`Cannot set configuration for unknown language ${s}`);return ki.get(_r).register(s,e,100)}class rDt{constructor(e,i){this._languageId=e,this._actual=i}dispose(){}getInitialState(){return this._actual.getInitialState()}tokenize(e,i,n){if(typeof this._actual.tokenize=="function")return _5.adaptTokenize(this._languageId,this._actual,e,n);throw new Error("Not supported!")}tokenizeEncoded(e,i,n){const r=this._actual.tokenizeEncoded(e,n);return new lq(r.tokens,r.endState)}}class _5{constructor(e,i,n,r){this._languageId=e,this._actual=i,this._languageService=n,this._standaloneThemeService=r}dispose(){}getInitialState(){return this._actual.getInitialState()}static _toClassicTokens(e,i){const n=[];let r=0;for(let o=0,a=e.length;o<a;o++){const l=e[o];let c=l.startIndex;o===0?c=0:c<r&&(c=r),n[o]=new t4(c,l.scopes,i),r=c}return n}static adaptTokenize(e,i,n,r){const o=i.tokenize(n,r),a=_5._toClassicTokens(o.tokens,e);let l;return o.endState.equals(r)?l=r:l=o.endState,new Ffe(a,l)}tokenize(e,i,n){return _5.adaptTokenize(this._languageId,this._actual,e,n)}_toBinaryTokens(e,i){const n=e.encodeLanguageId(this._languageId),r=this._standaloneThemeService.getColorTheme().tokenTheme,o=[];let a=0,l=0;for(let d=0,u=i.length;d<u;d++){const h=i[d],f=r.match(n,h.scopes)|1024;if(a>0&&o[a-1]===f)continue;let g=h.startIndex;d===0?g=0:g<l&&(g=l),o[a++]=g,o[a++]=f,l=g}const c=new Uint32Array(a);for(let d=0;d<a;d++)c[d]=o[d];return c}tokenizeEncoded(e,i,n){const r=this._actual.tokenize(e,n),o=this._toBinaryTokens(this._languageService.languageIdCodec,r.tokens);let a;return r.endState.equals(n)?a=n:a=r.endState,new lq(o,a)}}function oDt(s){return typeof s.getInitialState=="function"}function aDt(s){return"tokenizeEncoded"in s}function c$e(s){return s&&typeof s.then=="function"}function lDt(s){const e=ki.get(kh);if(s){const i=[null];for(let n=1,r=s.length;n<r;n++)i[n]=Ye.fromHex(s[n]);e.setColorMapOverride(i)}else e.setColorMapOverride(null)}function d$e(s,e){return aDt(e)?new rDt(s,e):new _5(s,e,ki.get(Pr),ki.get(kh))}function gme(s,e){const i=new stt(async()=>{const n=await Promise.resolve(e.create());return n?oDt(n)?d$e(s,n):new d5(ki.get(Pr),ki.get(kh),s,l$e(s,n),ki.get(Oi)):null});return Ir.registerFactory(s,i)}function cDt(s,e){if(!ki.get(Pr).isRegisteredLanguageId(s))throw new Error(`Cannot set tokens provider for unknown language ${s}`);return c$e(e)?gme(s,{create:()=>e}):Ir.register(s,d$e(s,e))}function dDt(s,e){const i=n=>new d5(ki.get(Pr),ki.get(kh),s,l$e(s,n),ki.get(Oi));return c$e(e)?gme(s,{create:()=>e}):Ir.register(s,i(e))}function uDt(s,e){return ki.get(jt).referenceProvider.register(s,e)}function hDt(s,e){return ki.get(jt).renameProvider.register(s,e)}function fDt(s,e){return ki.get(jt).newSymbolNamesProvider.register(s,e)}function gDt(s,e){return ki.get(jt).signatureHelpProvider.register(s,e)}function pDt(s,e){return ki.get(jt).hoverProvider.register(s,{provideHover:async(n,r,o,a)=>{const l=n.getWordAtPosition(r);return Promise.resolve(e.provideHover(n,r,o,a)).then(c=>{if(c)return!c.range&&l&&(c.range=new oe(r.lineNumber,l.startColumn,r.lineNumber,l.endColumn)),c.range||(c.range=new oe(r.lineNumber,r.column,r.lineNumber,r.column)),c})}})}function mDt(s,e){return ki.get(jt).documentSymbolProvider.register(s,e)}function _Dt(s,e){return ki.get(jt).documentHighlightProvider.register(s,e)}function vDt(s,e){return ki.get(jt).linkedEditingRangeProvider.register(s,e)}function bDt(s,e){return ki.get(jt).definitionProvider.register(s,e)}function yDt(s,e){return ki.get(jt).implementationProvider.register(s,e)}function wDt(s,e){return ki.get(jt).typeDefinitionProvider.register(s,e)}function xDt(s,e){return ki.get(jt).codeLensProvider.register(s,e)}function CDt(s,e,i){return ki.get(jt).codeActionProvider.register(s,{providedCodeActionKinds:i==null?void 0:i.providedCodeActionKinds,documentation:i==null?void 0:i.documentation,provideCodeActions:(r,o,a,l)=>{const d=ki.get(Q_).read({resource:r.uri}).filter(u=>oe.areIntersectingOrTouching(u,o));return e.provideCodeActions(r,o,{markers:d,only:a.only,trigger:a.trigger},l)},resolveCodeAction:e.resolveCodeAction})}function SDt(s,e){return ki.get(jt).documentFormattingEditProvider.register(s,e)}function kDt(s,e){return ki.get(jt).documentRangeFormattingEditProvider.register(s,e)}function LDt(s,e){return ki.get(jt).onTypeFormattingEditProvider.register(s,e)}function EDt(s,e){return ki.get(jt).linkProvider.register(s,e)}function DDt(s,e){return ki.get(jt).completionProvider.register(s,e)}function TDt(s,e){return ki.get(jt).colorProvider.register(s,e)}function IDt(s,e){return ki.get(jt).foldingRangeProvider.register(s,e)}function NDt(s,e){return ki.get(jt).declarationProvider.register(s,e)}function RDt(s,e){return ki.get(jt).selectionRangeProvider.register(s,e)}function ADt(s,e){return ki.get(jt).documentSemanticTokensProvider.register(s,e)}function MDt(s,e){return ki.get(jt).documentRangeSemanticTokensProvider.register(s,e)}function PDt(s,e){return ki.get(jt).inlineCompletionsProvider.register(s,e)}function ODt(s,e){return ki.get(jt).inlayHintsProvider.register(s,e)}function FDt(){return{register:JEt,getLanguages:eDt,onLanguage:iDt,onLanguageEncountered:nDt,getEncodedLanguageId:tDt,setLanguageConfiguration:sDt,setColorMap:lDt,registerTokensProviderFactory:gme,setTokensProvider:cDt,setMonarchTokensProvider:dDt,registerReferenceProvider:uDt,registerRenameProvider:hDt,registerNewSymbolNameProvider:fDt,registerCompletionItemProvider:DDt,registerSignatureHelpProvider:gDt,registerHoverProvider:pDt,registerDocumentSymbolProvider:mDt,registerDocumentHighlightProvider:_Dt,registerLinkedEditingRangeProvider:vDt,registerDefinitionProvider:bDt,registerImplementationProvider:yDt,registerTypeDefinitionProvider:wDt,registerCodeLensProvider:xDt,registerCodeActionProvider:CDt,registerDocumentFormattingEditProvider:SDt,registerDocumentRangeFormattingEditProvider:kDt,registerOnTypeFormattingEditProvider:LDt,registerLinkProvider:EDt,registerColorProvider:TDt,registerFoldingRangeProvider:IDt,registerDeclarationProvider:NDt,registerSelectionRangeProvider:RDt,registerDocumentSemanticTokensProvider:ADt,registerDocumentRangeSemanticTokensProvider:MDt,registerInlineCompletionsProvider:PDt,registerInlayHintsProvider:ODt,DocumentHighlightKind:sle,CompletionItemKind:Qae,CompletionItemTag:Jae,CompletionItemInsertTextRule:Zae,SymbolKind:Ole,SymbolTag:Fle,IndentAction:ule,CompletionTriggerKind:ele,SignatureHelpTriggerKind:Ple,InlayHintKind:fle,InlineCompletionTriggerKind:mle,CodeActionTriggerType:Xae,NewSymbolNameTag:Cle,NewSymbolNameTriggerKind:Sle,PartialAcceptTriggerKind:Ele,HoverVerbosityAction:dle,InlineCompletionEndOfLifeReasonKind:gle,InlineCompletionHintStyle:ple,FoldingRangeKind:qL,SelectedSuggestionInfo:WOe,EditDeltaInfo:f4}}pc.wrappingIndent.defaultValue=0;pc.glyphMargin.defaultValue=!1;pc.autoIndent.defaultValue=3;pc.overviewRulerLanes.defaultValue=2;H4.setFormatterSelector((s,e,i)=>Promise.resolve(s[0]));const od=Fje();od.editor=GEt();od.languages=FDt();const u$e=od.CancellationTokenSource,L1=od.Emitter,h$e=od.KeyCode,f$e=od.KeyMod,Fy=od.Position,mR=od.Range,g$e=od.Selection,p$e=od.SelectionDirection,pg=od.MarkerSeverity,rH=od.MarkerTag,iG=od.Uri,m$e=od.Token,D_=od.editor,Bt=od.languages,$X=She(),e2=globalThis;($X!=null&&$X.globalAPI||typeof e2.define=="function"&&e2.define.amd)&&(e2.monaco=od);typeof e2.require<"u"&&typeof e2.require.config=="function"&&e2.require.config({ignoreDuplicateModules:["vscode-languageserver-types","vscode-languageserver-types/main","vscode-languageserver-textdocument","vscode-languageserver-textdocument/main","vscode-nls","vscode-nls/vscode-nls","jsonc-parser","jsonc-parser/main","vscode-uri","vscode-uri/index","vs/basic-languages/typescript/typescript"]});const BDt=Object.freeze(Object.defineProperty({__proto__:null,CancellationTokenSource:u$e,Emitter:L1,KeyCode:h$e,KeyMod:f$e,MarkerSeverity:pg,MarkerTag:rH,Position:Fy,Range:mR,Selection:g$e,SelectionDirection:p$e,Token:m$e,Uri:iG,editor:D_,languages:Bt},Symbol.toStringTag,{value:"Module"}));let pme=class{constructor(e,i,n){this._onDidChange=new L1,this._languageId=e,this.setOptions(i),this.setModeConfiguration(n)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get modeConfiguration(){return this._modeConfiguration}get diagnosticsOptions(){return this.options}get options(){return this._options}setOptions(e){this._options=e||Object.create(null),this._onDidChange.fire(this)}setDiagnosticsOptions(e){this.setOptions(e)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}};const mme={validate:!0,lint:{compatibleVendorPrefixes:"ignore",vendorPrefix:"warning",duplicateProperties:"warning",emptyRules:"warning",importStatement:"ignore",boxModel:"ignore",universalSelector:"ignore",zeroUnits:"ignore",fontFaceProperties:"warning",hexColorLength:"error",argumentsInColorFunction:"error",unknownProperties:"warning",ieHack:"ignore",unknownVendorSpecificProperties:"ignore",propertyIgnoredDueToDisplay:"warning",important:"ignore",float:"ignore",idSelector:"ignore"},data:{useDefaultDataProvider:!0},format:{newlineBetweenSelectors:!0,newlineBetweenRules:!0,spaceAroundSelectorSeparator:!1,braceStyle:"collapse",maxPreserveNewLines:void 0,preserveNewLines:!0}},_me={completionItems:!0,hovers:!0,documentSymbols:!0,definitions:!0,references:!0,documentHighlights:!0,rename:!0,colors:!0,foldingRanges:!0,diagnostics:!0,selectionRanges:!0,documentFormattingEdits:!0,documentRangeFormattingEdits:!0},_$e=new pme("css",mme,_me),v$e=new pme("scss",mme,_me),b$e=new pme("less",mme,_me);function vme(){return ei(()=>import("./cssMode-CauFS5Bp.js"),__vite__mapDeps([0,1]),import.meta.url)}Bt.onLanguage("less",()=>{vme().then(s=>s.setupMode(b$e))});Bt.onLanguage("scss",()=>{vme().then(s=>s.setupMode(v$e))});Bt.onLanguage("css",()=>{vme().then(s=>s.setupMode(_$e))});const y$e=Object.freeze(Object.defineProperty({__proto__:null,cssDefaults:_$e,lessDefaults:b$e,scssDefaults:v$e},Symbol.toStringTag,{value:"Module"}));let jDt=class{constructor(e,i,n){this._onDidChange=new L1,this._languageId=e,this.setOptions(i),this.setModeConfiguration(n)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get options(){return this._options}get modeConfiguration(){return this._modeConfiguration}setOptions(e){this._options=e||Object.create(null),this._onDidChange.fire(this)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}};const $Dt={tabSize:4,insertSpaces:!1,wrapLineLength:120,unformatted:'default": "a, abbr, acronym, b, bdo, big, br, button, cite, code, dfn, em, i, img, input, kbd, label, map, object, q, samp, select, small, span, strong, sub, sup, textarea, tt, var',contentUnformatted:"pre",indentInnerHtml:!1,preserveNewLines:!0,maxPreserveNewLines:void 0,indentHandlebars:!1,endWithNewline:!1,extraLiners:"head, body, /html",wrapAttributes:"auto"},nG={format:$Dt,suggest:{},data:{useDefaultDataProvider:!0}};function sG(s){return{completionItems:!0,hovers:!0,documentSymbols:!0,links:!0,documentHighlights:!0,rename:!0,colors:!0,foldingRanges:!0,selectionRanges:!0,diagnostics:s===qO,documentFormattingEdits:s===qO,documentRangeFormattingEdits:s===qO}}const qO="html",pSe="handlebars",mSe="razor",w$e=rG(qO,nG,sG(qO)),WDt=w$e.defaults,x$e=rG(pSe,nG,sG(pSe)),HDt=x$e.defaults,C$e=rG(mSe,nG,sG(mSe)),VDt=C$e.defaults;function zDt(){return ei(()=>import("./htmlMode-rSEyII9x.js"),__vite__mapDeps([2,1]),import.meta.url)}function rG(s,e=nG,i=sG(s)){const n=new jDt(s,e,i);let r;const o=Bt.onLanguage(s,async()=>{r=(await zDt()).setupMode(n)});return{defaults:n,dispose(){o.dispose(),r==null||r.dispose(),r=void 0}}}const S$e=Object.freeze(Object.defineProperty({__proto__:null,handlebarDefaults:HDt,handlebarLanguageService:x$e,htmlDefaults:WDt,htmlLanguageService:w$e,razorDefaults:VDt,razorLanguageService:C$e,registerHTMLLanguageService:rG},Symbol.toStringTag,{value:"Module"}));let UDt=class{constructor(e,i,n){this._onDidChange=new L1,this._languageId=e,this.setDiagnosticsOptions(i),this.setModeConfiguration(n)}get onDidChange(){return this._onDidChange.event}get languageId(){return this._languageId}get modeConfiguration(){return this._modeConfiguration}get diagnosticsOptions(){return this._diagnosticsOptions}setDiagnosticsOptions(e){this._diagnosticsOptions=e||Object.create(null),this._onDidChange.fire(this)}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(this)}};const qDt={validate:!0,allowComments:!0,schemas:[],enableSchemaRequest:!1,schemaRequest:"warning",schemaValidation:"warning",comments:"error",trailingCommas:"error"},GDt={documentFormattingEdits:!0,documentRangeFormattingEdits:!0,completionItems:!0,hovers:!0,documentSymbols:!0,tokens:!0,colors:!0,foldingRanges:!0,diagnostics:!0,selectionRanges:!0},k$e=new UDt("json",qDt,GDt),KDt=()=>L$e().then(s=>s.getWorker());function L$e(){return ei(()=>import("./jsonMode-1FAJaHiX.js"),__vite__mapDeps([3,1]),import.meta.url)}Bt.register({id:"json",extensions:[".json",".bowerrc",".jshintrc",".jscsrc",".eslintrc",".babelrc",".har"],aliases:["JSON","json"],mimetypes:["application/json"]});Bt.onLanguage("json",()=>{L$e().then(s=>s.setupMode(k$e))});const E$e=Object.freeze(Object.defineProperty({__proto__:null,getWorker:KDt,jsonDefaults:k$e},Symbol.toStringTag,{value:"Module"})),YDt="5.9.3";var D$e=(s=>(s[s.None=0]="None",s[s.CommonJS=1]="CommonJS",s[s.AMD=2]="AMD",s[s.UMD=3]="UMD",s[s.System=4]="System",s[s.ES2015=5]="ES2015",s[s.ESNext=99]="ESNext",s))(D$e||{}),T$e=(s=>(s[s.None=0]="None",s[s.Preserve=1]="Preserve",s[s.React=2]="React",s[s.ReactNative=3]="ReactNative",s[s.ReactJSX=4]="ReactJSX",s[s.ReactJSXDev=5]="ReactJSXDev",s))(T$e||{}),I$e=(s=>(s[s.CarriageReturnLineFeed=0]="CarriageReturnLineFeed",s[s.LineFeed=1]="LineFeed",s))(I$e||{}),N$e=(s=>(s[s.ES3=0]="ES3",s[s.ES5=1]="ES5",s[s.ES2015=2]="ES2015",s[s.ES2016=3]="ES2016",s[s.ES2017=4]="ES2017",s[s.ES2018=5]="ES2018",s[s.ES2019=6]="ES2019",s[s.ES2020=7]="ES2020",s[s.ESNext=99]="ESNext",s[s.JSON=100]="JSON",s[s.Latest=99]="Latest",s))(N$e||{}),R$e=(s=>(s[s.Classic=1]="Classic",s[s.NodeJs=2]="NodeJs",s))(R$e||{});class A$e{constructor(e,i,n,r,o){this._onDidChange=new L1,this._onDidExtraLibsChange=new L1,this._extraLibs=Object.create(null),this._removedExtraLibs=Object.create(null),this._eagerModelSync=!1,this.setCompilerOptions(e),this.setDiagnosticsOptions(i),this.setWorkerOptions(n),this.setInlayHintsOptions(r),this.setModeConfiguration(o),this._onDidExtraLibsChangeTimeout=-1}get onDidChange(){return this._onDidChange.event}get onDidExtraLibsChange(){return this._onDidExtraLibsChange.event}get modeConfiguration(){return this._modeConfiguration}get workerOptions(){return this._workerOptions}get inlayHintsOptions(){return this._inlayHintsOptions}getExtraLibs(){return this._extraLibs}addExtraLib(e,i){let n;if(typeof i>"u"?n=`ts:extralib-${Math.random().toString(36).substring(2,15)}`:n=i,this._extraLibs[n]&&this._extraLibs[n].content===e)return{dispose:()=>{}};let r=1;return this._removedExtraLibs[n]&&(r=this._removedExtraLibs[n]+1),this._extraLibs[n]&&(r=this._extraLibs[n].version+1),this._extraLibs[n]={content:e,version:r},this._fireOnDidExtraLibsChangeSoon(),{dispose:()=>{let o=this._extraLibs[n];o&&o.version===r&&(delete this._extraLibs[n],this._removedExtraLibs[n]=r,this._fireOnDidExtraLibsChangeSoon())}}}setExtraLibs(e){for(const i in this._extraLibs)this._removedExtraLibs[i]=this._extraLibs[i].version;if(this._extraLibs=Object.create(null),e&&e.length>0)for(const i of e){const n=i.filePath||`ts:extralib-${Math.random().toString(36).substring(2,15)}`,r=i.content;let o=1;this._removedExtraLibs[n]&&(o=this._removedExtraLibs[n]+1),this._extraLibs[n]={content:r,version:o}}this._fireOnDidExtraLibsChangeSoon()}_fireOnDidExtraLibsChangeSoon(){this._onDidExtraLibsChangeTimeout===-1&&(this._onDidExtraLibsChangeTimeout=window.setTimeout(()=>{this._onDidExtraLibsChangeTimeout=-1,this._onDidExtraLibsChange.fire(void 0)},0))}getCompilerOptions(){return this._compilerOptions}setCompilerOptions(e){this._compilerOptions=e||Object.create(null),this._onDidChange.fire(void 0)}getDiagnosticsOptions(){return this._diagnosticsOptions}setDiagnosticsOptions(e){this._diagnosticsOptions=e||Object.create(null),this._onDidChange.fire(void 0)}setWorkerOptions(e){this._workerOptions=e||Object.create(null),this._onDidChange.fire(void 0)}setInlayHintsOptions(e){this._inlayHintsOptions=e||Object.create(null),this._onDidChange.fire(void 0)}setMaximumWorkerIdleTime(e){}setEagerModelSync(e){this._eagerModelSync=e}getEagerModelSync(){return this._eagerModelSync}setModeConfiguration(e){this._modeConfiguration=e||Object.create(null),this._onDidChange.fire(void 0)}}const XDt=YDt,M$e={completionItems:!0,hovers:!0,documentSymbols:!0,definitions:!0,references:!0,documentHighlights:!0,rename:!0,diagnostics:!0,documentRangeFormattingEdits:!0,signatureHelp:!0,onTypeFormattingEdits:!0,codeActions:!0,inlayHints:!0},P$e=new A$e({allowNonTsExtensions:!0,target:99},{noSemanticValidation:!1,noSyntaxValidation:!1,onlyVisible:!1},{},{},M$e),O$e=new A$e({allowNonTsExtensions:!0,allowJs:!0,target:99},{noSemanticValidation:!0,noSyntaxValidation:!1,onlyVisible:!1},{},{},M$e),ZDt=()=>oG().then(s=>s.getTypeScriptWorker()),QDt=()=>oG().then(s=>s.getJavaScriptWorker());function oG(){return ei(()=>import("./tsMode-CLQIVays.js"),[],import.meta.url)}Bt.onLanguage("typescript",()=>oG().then(s=>s.setupTypeScript(P$e)));Bt.onLanguage("javascript",()=>oG().then(s=>s.setupJavaScript(O$e)));const F$e=Object.freeze(Object.defineProperty({__proto__:null,JsxEmit:T$e,ModuleKind:D$e,ModuleResolutionKind:R$e,NewLineKind:I$e,ScriptTarget:N$e,getJavaScriptWorker:QDt,getTypeScriptWorker:ZDt,javascriptDefaults:O$e,typescriptDefaults:P$e,typescriptVersion:XDt},Symbol.toStringTag,{value:"Module"})),B$e={},WX={};class bme{static getOrCreate(e){return WX[e]||(WX[e]=new bme(e)),WX[e]}constructor(e){this._languageId=e,this._loadingTriggered=!1,this._lazyLoadPromise=new Promise((i,n)=>{this._lazyLoadPromiseResolve=i,this._lazyLoadPromiseReject=n})}load(){return this._loadingTriggered||(this._loadingTriggered=!0,B$e[this._languageId].loader().then(e=>this._lazyLoadPromiseResolve(e),e=>this._lazyLoadPromiseReject(e))),this._lazyLoadPromise}}function di(s){const e=s.id;B$e[e]=s,Bt.register(s);const i=bme.getOrCreate(e);Bt.registerTokensProviderFactory(e,{create:async()=>(await i.load()).language}),Bt.onLanguageEncountered(e,async()=>{const n=await i.load();Bt.setLanguageConfiguration(e,n.conf)})}di({id:"abap",extensions:[".abap"],aliases:["abap","ABAP"],loader:()=>ei(()=>import("./abap-DLDM7-KI.js"),[],import.meta.url)});di({id:"apex",extensions:[".cls"],aliases:["Apex","apex"],mimetypes:["text/x-apex-source","text/x-apex"],loader:()=>ei(()=>import("./apex-DNDY2TF8.js"),[],import.meta.url)});di({id:"azcli",extensions:[".azcli"],aliases:["Azure CLI","azcli"],loader:()=>ei(()=>import("./azcli-Y6nb8tq_.js"),[],import.meta.url)});di({id:"bat",extensions:[".bat",".cmd"],aliases:["Batch","bat"],loader:()=>ei(()=>import("./bat-BwHxbl9M.js"),[],import.meta.url)});di({id:"bicep",extensions:[".bicep"],aliases:["Bicep"],loader:()=>ei(()=>import("./bicep-CFznDFnq.js"),[],import.meta.url)});di({id:"cameligo",extensions:[".mligo"],aliases:["Cameligo"],loader:()=>ei(()=>import("./cameligo-Bf6VGUru.js"),[],import.meta.url)});di({id:"clojure",extensions:[".clj",".cljs",".cljc",".edn"],aliases:["clojure","Clojure"],loader:()=>ei(()=>import("./clojure-Dnu-v4kV.js"),[],import.meta.url)});di({id:"coffeescript",extensions:[".coffee"],aliases:["CoffeeScript","coffeescript","coffee"],mimetypes:["text/x-coffeescript","text/coffeescript"],loader:()=>ei(()=>import("./coffee-Bd8akH9Z.js"),[],import.meta.url)});di({id:"c",extensions:[".c",".h"],aliases:["C","c"],loader:()=>ei(()=>import("./cpp-BbWJElDN.js"),[],import.meta.url)});di({id:"cpp",extensions:[".cpp",".cc",".cxx",".hpp",".hh",".hxx"],aliases:["C++","Cpp","cpp"],loader:()=>ei(()=>import("./cpp-BbWJElDN.js"),[],import.meta.url)});di({id:"csharp",extensions:[".cs",".csx",".cake"],aliases:["C#","csharp"],loader:()=>ei(()=>import("./csharp-Co3qMtFm.js"),[],import.meta.url)});di({id:"csp",extensions:[".csp"],aliases:["CSP","csp"],loader:()=>ei(()=>import("./csp-D-4FJmMZ.js"),[],import.meta.url)});di({id:"css",extensions:[".css"],aliases:["CSS","css"],mimetypes:["text/css"],loader:()=>ei(()=>import("./css-DdJfP1eB.js"),[],import.meta.url)});di({id:"cypher",extensions:[".cypher",".cyp"],aliases:["Cypher","OpenCypher"],loader:()=>ei(()=>import("./cypher-cTPe9QuQ.js"),[],import.meta.url)});di({id:"dart",extensions:[".dart"],aliases:["Dart","dart"],mimetypes:["text/x-dart-source","text/x-dart"],loader:()=>ei(()=>import("./dart-BOtBlQCF.js"),[],import.meta.url)});di({id:"dockerfile",extensions:[".dockerfile"],filenames:["Dockerfile"],aliases:["Dockerfile"],loader:()=>ei(()=>import("./dockerfile-BG73LgW2.js"),[],import.meta.url)});di({id:"ecl",extensions:[".ecl"],aliases:["ECL","Ecl","ecl"],loader:()=>ei(()=>import("./ecl-BEgZUVRK.js"),[],import.meta.url)});di({id:"elixir",extensions:[".ex",".exs"],aliases:["Elixir","elixir","ex"],loader:()=>ei(()=>import("./elixir-BkW5O-1t.js"),[],import.meta.url)});di({id:"flow9",extensions:[".flow"],aliases:["Flow9","Flow","flow9","flow"],loader:()=>ei(()=>import("./flow9-BeJ5waoc.js"),[],import.meta.url)});di({id:"fsharp",extensions:[".fs",".fsi",".ml",".mli",".fsx",".fsscript"],aliases:["F#","FSharp","fsharp"],loader:()=>ei(()=>import("./fsharp-PahG7c26.js"),[],import.meta.url)});di({id:"freemarker2",extensions:[".ftl",".ftlh",".ftlx"],aliases:["FreeMarker2","Apache FreeMarker2"],loader:()=>ei(()=>import("./freemarker2-BxIPNQn-.js"),[],import.meta.url).then(s=>s.TagAutoInterpolationDollar)});di({id:"freemarker2.tag-angle.interpolation-dollar",aliases:["FreeMarker2 (Angle/Dollar)","Apache FreeMarker2 (Angle/Dollar)"],loader:()=>ei(()=>import("./freemarker2-BxIPNQn-.js"),[],import.meta.url).then(s=>s.TagAngleInterpolationDollar)});di({id:"freemarker2.tag-bracket.interpolation-dollar",aliases:["FreeMarker2 (Bracket/Dollar)","Apache FreeMarker2 (Bracket/Dollar)"],loader:()=>ei(()=>import("./freemarker2-BxIPNQn-.js"),[],import.meta.url).then(s=>s.TagBracketInterpolationDollar)});di({id:"freemarker2.tag-angle.interpolation-bracket",aliases:["FreeMarker2 (Angle/Bracket)","Apache FreeMarker2 (Angle/Bracket)"],loader:()=>ei(()=>import("./freemarker2-BxIPNQn-.js"),[],import.meta.url).then(s=>s.TagAngleInterpolationBracket)});di({id:"freemarker2.tag-bracket.interpolation-bracket",aliases:["FreeMarker2 (Bracket/Bracket)","Apache FreeMarker2 (Bracket/Bracket)"],loader:()=>ei(()=>import("./freemarker2-BxIPNQn-.js"),[],import.meta.url).then(s=>s.TagBracketInterpolationBracket)});di({id:"freemarker2.tag-auto.interpolation-dollar",aliases:["FreeMarker2 (Auto/Dollar)","Apache FreeMarker2 (Auto/Dollar)"],loader:()=>ei(()=>import("./freemarker2-BxIPNQn-.js"),[],import.meta.url).then(s=>s.TagAutoInterpolationDollar)});di({id:"freemarker2.tag-auto.interpolation-bracket",aliases:["FreeMarker2 (Auto/Bracket)","Apache FreeMarker2 (Auto/Bracket)"],loader:()=>ei(()=>import("./freemarker2-BxIPNQn-.js"),[],import.meta.url).then(s=>s.TagAutoInterpolationBracket)});di({id:"go",extensions:[".go"],aliases:["Go"],loader:()=>ei(()=>import("./go-acbASCJo.js"),[],import.meta.url)});di({id:"graphql",extensions:[".graphql",".gql"],aliases:["GraphQL","graphql","gql"],mimetypes:["application/graphql"],loader:()=>ei(()=>import("./graphql-BxJiqAUM.js"),[],import.meta.url)});di({id:"handlebars",extensions:[".handlebars",".hbs"],aliases:["Handlebars","handlebars","hbs"],mimetypes:["text/x-handlebars-template"],loader:()=>ei(()=>import("./handlebars-DnEVFUsu.js"),[],import.meta.url)});di({id:"hcl",extensions:[".tf",".tfvars",".hcl"],aliases:["Terraform","tf","HCL","hcl"],loader:()=>ei(()=>import("./hcl-DtV1sZF8.js"),[],import.meta.url)});di({id:"html",extensions:[".html",".htm",".shtml",".xhtml",".mdoc",".jsp",".asp",".aspx",".jshtm"],aliases:["HTML","htm","html","xhtml"],mimetypes:["text/html","text/x-jshtm","text/template","text/ng-template"],loader:()=>ei(()=>import("./html-S8NXUTqc.js"),[],import.meta.url)});di({id:"ini",extensions:[".ini",".properties",".gitconfig"],filenames:["config",".gitattributes",".gitconfig",".editorconfig"],aliases:["Ini","ini"],loader:()=>ei(()=>import("./ini-Kd9XrMLS.js"),[],import.meta.url)});di({id:"java",extensions:[".java",".jav"],aliases:["Java","java"],mimetypes:["text/x-java-source","text/x-java"],loader:()=>ei(()=>import("./java-CXBNlu9o.js"),[],import.meta.url)});di({id:"javascript",extensions:[".js",".es6",".jsx",".mjs",".cjs"],firstLine:"^#!.*\\bnode",filenames:["jakefile"],aliases:["JavaScript","javascript","js"],mimetypes:["text/javascript"],loader:()=>ei(()=>import("./javascript-BiWR68QP.js"),__vite__mapDeps([4,5]),import.meta.url)});di({id:"julia",extensions:[".jl"],aliases:["julia","Julia"],loader:()=>ei(()=>import("./julia-cl7-CwDS.js"),[],import.meta.url)});di({id:"kotlin",extensions:[".kt",".kts"],aliases:["Kotlin","kotlin"],mimetypes:["text/x-kotlin-source","text/x-kotlin"],loader:()=>ei(()=>import("./kotlin-s7OhZKlX.js"),[],import.meta.url)});di({id:"less",extensions:[".less"],aliases:["Less","less"],mimetypes:["text/x-less","text/less"],loader:()=>ei(()=>import("./less-9HpZscsL.js"),[],import.meta.url)});di({id:"lexon",extensions:[".lex"],aliases:["Lexon"],loader:()=>ei(()=>import("./lexon-OrD6JF1K.js"),[],import.meta.url)});di({id:"lua",extensions:[".lua"],aliases:["Lua","lua"],loader:()=>ei(()=>import("./lua-Cyyb5UIc.js"),[],import.meta.url)});di({id:"liquid",extensions:[".liquid",".html.liquid"],aliases:["Liquid","liquid"],mimetypes:["application/liquid"],loader:()=>ei(()=>import("./liquid-CEtOkbwI.js"),[],import.meta.url)});di({id:"m3",extensions:[".m3",".i3",".mg",".ig"],aliases:["Modula-3","Modula3","modula3","m3"],loader:()=>ei(()=>import("./m3-B8OfTtLu.js"),[],import.meta.url)});di({id:"markdown",extensions:[".md",".markdown",".mdown",".mkdn",".mkd",".mdwn",".mdtxt",".mdtext"],aliases:["Markdown","markdown"],loader:()=>ei(()=>import("./markdown-BFxVWTOG.js"),[],import.meta.url)});di({id:"mdx",extensions:[".mdx"],aliases:["MDX","mdx"],loader:()=>ei(()=>import("./mdx-C7C95Bzt.js"),[],import.meta.url)});di({id:"mips",extensions:[".s"],aliases:["MIPS","MIPS-V"],mimetypes:["text/x-mips","text/mips","text/plaintext"],loader:()=>ei(()=>import("./mips-CiqrrVzr.js"),[],import.meta.url)});di({id:"msdax",extensions:[".dax",".msdax"],aliases:["DAX","MSDAX"],loader:()=>ei(()=>import("./msdax-DmeGPVcC.js"),[],import.meta.url)});di({id:"mysql",extensions:[],aliases:["MySQL","mysql"],loader:()=>ei(()=>import("./mysql-C_tMU-Nz.js"),[],import.meta.url)});di({id:"objective-c",extensions:[".m"],aliases:["Objective-C"],loader:()=>ei(()=>import("./objective-c-BDtDVThU.js"),[],import.meta.url)});di({id:"pascal",extensions:[".pas",".p",".pp"],aliases:["Pascal","pas"],mimetypes:["text/x-pascal-source","text/x-pascal"],loader:()=>ei(()=>import("./pascal-vHIfCaH5.js"),[],import.meta.url)});di({id:"pascaligo",extensions:[".ligo"],aliases:["Pascaligo","ligo"],loader:()=>ei(()=>import("./pascaligo-DtZ0uQbO.js"),[],import.meta.url)});di({id:"perl",extensions:[".pl",".pm"],aliases:["Perl","pl"],loader:()=>ei(()=>import("./perl-Ub6l9XKa.js"),[],import.meta.url)});di({id:"pgsql",extensions:[],aliases:["PostgreSQL","postgres","pg","postgre"],loader:()=>ei(()=>import("./pgsql-BlNEE0v7.js"),[],import.meta.url)});di({id:"php",extensions:[".php",".php4",".php5",".phtml",".ctp"],aliases:["PHP","php"],mimetypes:["application/x-php"],loader:()=>ei(()=>import("./php-BBUBE1dy.js"),[],import.meta.url)});di({id:"pla",extensions:[".pla"],loader:()=>ei(()=>import("./pla-DSh2-awV.js"),[],import.meta.url)});di({id:"postiats",extensions:[".dats",".sats",".hats"],aliases:["ATS","ATS/Postiats"],loader:()=>ei(()=>import("./postiats-CocnycG-.js"),[],import.meta.url)});di({id:"powerquery",extensions:[".pq",".pqm"],aliases:["PQ","M","Power Query","Power Query M"],loader:()=>ei(()=>import("./powerquery-tScXyioY.js"),[],import.meta.url)});di({id:"powershell",extensions:[".ps1",".psm1",".psd1"],aliases:["PowerShell","powershell","ps","ps1"],loader:()=>ei(()=>import("./powershell-COWaemsV.js"),[],import.meta.url)});di({id:"proto",extensions:[".proto"],aliases:["protobuf","Protocol Buffers"],loader:()=>ei(()=>import("./protobuf-Brw8urJB.js"),[],import.meta.url)});di({id:"pug",extensions:[".jade",".pug"],aliases:["Pug","Jade","jade"],loader:()=>ei(()=>import("./pug-8SOpv6rk.js"),[],import.meta.url)});di({id:"python",extensions:[".py",".rpy",".pyw",".cpy",".gyp",".gypi"],aliases:["Python","py"],firstLine:"^#!/.*\\bpython[0-9.-]*\\b",loader:()=>ei(()=>import("./python-CXvKcjLk.js"),[],import.meta.url)});di({id:"qsharp",extensions:[".qs"],aliases:["Q#","qsharp"],loader:()=>ei(()=>import("./qsharp-Bw9ernYp.js"),[],import.meta.url)});di({id:"r",extensions:[".r",".rhistory",".rmd",".rprofile",".rt"],aliases:["R","r"],loader:()=>ei(()=>import("./r-j7ic8hl3.js"),[],import.meta.url)});di({id:"razor",extensions:[".cshtml"],aliases:["Razor","razor"],mimetypes:["text/x-cshtml"],loader:()=>ei(()=>import("./razor-tzZHfRy2.js"),[],import.meta.url)});di({id:"redis",extensions:[".redis"],aliases:["redis"],loader:()=>ei(()=>import("./redis-Bu5POkcn.js"),[],import.meta.url)});di({id:"redshift",extensions:[],aliases:["Redshift","redshift"],loader:()=>ei(()=>import("./redshift-Bs9aos_-.js"),[],import.meta.url)});di({id:"restructuredtext",extensions:[".rst"],aliases:["reStructuredText","restructuredtext"],loader:()=>ei(()=>import("./restructuredtext-CqXO7rUv.js"),[],import.meta.url)});di({id:"ruby",extensions:[".rb",".rbx",".rjs",".gemspec",".pp"],filenames:["rakefile","Gemfile"],aliases:["Ruby","rb"],loader:()=>ei(()=>import("./ruby-zBfavPgS.js"),[],import.meta.url)});di({id:"rust",extensions:[".rs",".rlib"],aliases:["Rust","rust"],loader:()=>ei(()=>import("./rust-BzKRNQWT.js"),[],import.meta.url)});di({id:"sb",extensions:[".sb"],aliases:["Small Basic","sb"],loader:()=>ei(()=>import("./sb-BBc9UKZt.js"),[],import.meta.url)});di({id:"scala",extensions:[".scala",".sc",".sbt"],aliases:["Scala","scala","SBT","Sbt","sbt","Dotty","dotty"],mimetypes:["text/x-scala-source","text/x-scala","text/x-sbt","text/x-dotty"],loader:()=>ei(()=>import("./scala-D9hQfWCl.js"),[],import.meta.url)});di({id:"scheme",extensions:[".scm",".ss",".sch",".rkt"],aliases:["scheme","Scheme"],loader:()=>ei(()=>import("./scheme-BPhDTwHR.js"),[],import.meta.url)});di({id:"scss",extensions:[".scss"],aliases:["Sass","sass","scss"],mimetypes:["text/x-scss","text/scss"],loader:()=>ei(()=>import("./scss-CBJaRo0y.js"),[],import.meta.url)});di({id:"shell",extensions:[".sh",".bash"],aliases:["Shell","sh"],loader:()=>ei(()=>import("./shell-DiJ1NA_G.js"),[],import.meta.url)});di({id:"sol",extensions:[".sol"],aliases:["sol","solidity","Solidity"],loader:()=>ei(()=>import("./solidity-Db0IVjzk.js"),[],import.meta.url)});di({id:"aes",extensions:[".aes"],aliases:["aes","sophia","Sophia"],loader:()=>ei(()=>import("./sophia-CnS9iZB_.js"),[],import.meta.url)});di({id:"sparql",extensions:[".rq"],aliases:["sparql","SPARQL"],loader:()=>ei(()=>import("./sparql-CJmd_6j2.js"),[],import.meta.url)});di({id:"sql",extensions:[".sql"],aliases:["SQL"],loader:()=>ei(()=>import("./sql-ClhHkBeG.js"),[],import.meta.url)});di({id:"st",extensions:[".st",".iecst",".iecplc",".lc3lib",".TcPOU",".TcDUT",".TcGVL",".TcIO"],aliases:["StructuredText","scl","stl"],loader:()=>ei(()=>import("./st-CHwy0fLd.js"),[],import.meta.url)});di({id:"swift",aliases:["Swift","swift"],extensions:[".swift"],mimetypes:["text/swift"],loader:()=>ei(()=>import("./swift-Bqt4WxQ4.js"),[],import.meta.url)});di({id:"systemverilog",extensions:[".sv",".svh"],aliases:["SV","sv","SystemVerilog","systemverilog"],loader:()=>ei(()=>import("./systemverilog-Bs9z6M-B.js"),[],import.meta.url)});di({id:"verilog",extensions:[".v",".vh"],aliases:["V","v","Verilog","verilog"],loader:()=>ei(()=>import("./systemverilog-Bs9z6M-B.js"),[],import.meta.url)});di({id:"tcl",extensions:[".tcl"],aliases:["tcl","Tcl","tcltk","TclTk","tcl/tk","Tcl/Tk"],loader:()=>ei(()=>import("./tcl-Dm6ycUr_.js"),[],import.meta.url)});di({id:"twig",extensions:[".twig"],aliases:["Twig","twig"],mimetypes:["text/x-twig"],loader:()=>ei(()=>import("./twig-Csy3S7wG.js"),[],import.meta.url)});di({id:"typescript",extensions:[".ts",".tsx",".cts",".mts"],aliases:["TypeScript","ts","typescript"],mimetypes:["text/typescript"],loader:()=>ei(()=>import("./typescript-LxhyM9W2.js"),[],import.meta.url)});di({id:"typespec",extensions:[".tsp"],aliases:["TypeSpec"],loader:()=>ei(()=>import("./typespec-Btyra-wh.js"),[],import.meta.url)});di({id:"vb",extensions:[".vb"],aliases:["Visual Basic","vb"],loader:()=>ei(()=>import("./vb-Db0cS2oM.js"),[],import.meta.url)});di({id:"wgsl",extensions:[".wgsl"],aliases:["WebGPU Shading Language","WGSL","wgsl"],loader:()=>ei(()=>import("./wgsl-BTesnYfV.js"),[],import.meta.url)});di({id:"xml",extensions:[".xml",".xsd",".dtd",".ascx",".csproj",".config",".props",".targets",".wxi",".wxl",".wxs",".xaml",".svg",".svgz",".opf",".xslt",".xsl"],firstLine:"(\\<\\?xml.*)|(\\<svg)|(\\<\\!doctype\\s+svg)",aliases:["XML","xml"],mimetypes:["text/xml","application/xml","application/xaml+xml","application/xml-dtd"],loader:()=>ei(()=>import("./xml-VS_m20VE.js"),[],import.meta.url)});di({id:"yaml",extensions:[".yaml",".yml"],aliases:["YAML","yaml","YML","yml"],mimetypes:["application/x-yaml","text/x-yaml"],loader:()=>ei(()=>import("./yaml-BsjggdVD.js"),[],import.meta.url)});var JDt=Object.defineProperty,eTt=(s,e,i)=>e in s?JDt(s,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):s[e]=i,ri=(s,e,i)=>eTt(s,typeof e!="symbol"?e+"":e,i),$$,_Se,W$,HX,H$;function tTt(s){return s.method!==void 0}var vSe;(function(s){function e(i){return i}s.create=e})(vSe||(vSe={}));var dg;(function(s){s.parseError=-32700,s.invalidRequest=-32600,s.methodNotFound=-32601,s.invalidParams=-32602,s.internalError=-32603;function e(o){return-32099<=o&&o<=-32e3}s.isServerError=e;function i(o){if(!e(o))throw new Error("Invalid range for a server error.");return o}s.serverError=i,s.unexpectedServerError=-32e3;function n(o){return!0}s.isApplicationError=n;function r(o){return o}s.applicationError=r,s.genericApplicationError=-320100})(dg||(dg={}));var yme=class{constructor(){ri(this,"listeners",new Set),ri(this,"event",e=>(this.listeners.add(e),{dispose:()=>{this.listeners.delete(e)}}))}fire(e){this.listeners.forEach(i=>i(e))}},iTt=class{constructor(s){ri(this,"_value"),ri(this,"eventEmitter"),this._value=s,this.eventEmitter=new yme}get value(){return this._value}set value(s){this._value!==s&&(this._value=s,this.eventEmitter.fire(s))}get onChange(){return this.eventEmitter.event}};function nTt(s,e){const i=setTimeout(e,s);return{dispose:()=>clearTimeout(i)}}function VX(s,e,i){return s instanceof Set?(s.add(e),{dispose:()=>s.delete(e)}):(s.set(e,i),{dispose:()=>s.delete(e)})}var sTt=class{constructor(){ri(this,"_state","none"),ri(this,"promise"),ri(this,"resolve",()=>{}),ri(this,"reject",()=>{}),this.promise=new Promise((s,e)=>{this.resolve=s,this.reject=e})}get state(){return this._state}},j$e=($$=class{constructor(){ri(this,"_unprocessedMessages",[]),ri(this,"_messageListener"),ri(this,"id",$$.id++),ri(this,"_state",new iTt({state:"open"})),ri(this,"state",this._state)}setListener(s){if(this._messageListener=s,!!s)for(;this._unprocessedMessages.length>0&&this._messageListener!==void 0;){const e=this._unprocessedMessages.shift();this._messageListener(e)}}send(s){return this._sendImpl(s)}_dispatchReceivedMessage(s){this._unprocessedMessages.length===0&&this._messageListener?this._messageListener(s):this._unprocessedMessages.push(s)}_onConnectionClosed(){this._state.value={state:"closed",error:void 0}}log(s){return new rTt(this,s??new oTt)}},ri($$,"id",0),$$),rTt=class{constructor(s,e){ri(this,"baseStream"),ri(this,"logger"),this.baseStream=s,this.logger=e}get state(){return this.baseStream.state}setListener(s){if(s===void 0){this.baseStream.setListener(void 0);return}this.baseStream.setListener(e=>{this.logger.log(this.baseStream,"incoming",e),s(e)})}send(s){return this.logger.log(this.baseStream,"outgoing",s),this.baseStream.send(s)}toString(){return`StreamLogger/${this.baseStream.toString()}`}},oTt=class{log(s,e,i){console.log(`${e==="incoming"?"<-":"->"} [${s.toString()}] ${JSON.stringify(i)}`)}},aTt=class $$e{constructor(e){ri(this,"connect"),this.connect=e}mapContext(e){return new $$e(i=>this.connect(i?lTt(i,e):void 0))}};function lTt(s,e){return{handleNotification:(i,n)=>s.handleNotification(i,e(n)),handleRequest:(i,n,r)=>s.handleRequest(i,n,e(r))}}var cTt=class W$e{constructor(e,i,n){ri(this,"_stream"),ri(this,"_listener"),ri(this,"_logger"),ri(this,"_unprocessedResponses",new Map),ri(this,"_lastUsedRequestId",0),this._stream=e,this._listener=i,this._logger=n,this._stream.setListener(r=>{tTt(r)?r.id===void 0?this._processNotification(r):this._processRequest(r):this._processResponse(r)})}static createChannel(e,i){let n=!1;return new aTt(r=>{if(n)throw new Error(`A channel to the stream ${e} was already constructed!`);return n=!0,new W$e(e,r,i)})}get state(){return this._stream.state}async _processNotification(e){if(e.id!==void 0)throw new Error;if(!this._listener){this._logger&&this._logger.debug({text:"Notification ignored",message:e});return}try{await this._listener.handleNotification({method:e.method,params:e.params||null})}catch(i){this._logger&&this._logger.warn({text:`Exception was thrown while handling notification: ${i}`,exception:i,message:e})}}async _processRequest(e){if(e.id===void 0)throw new Error;let i;if(this._listener)try{i=await this._listener.handleRequest({method:e.method,params:e.params||null},e.id)}catch(r){this._logger&&this._logger.warn({text:`Exception was thrown while handling request: ${r}`,message:e,exception:r}),i={error:{code:dg.internalError,message:"An unexpected exception was thrown.",data:void 0}}}else this._logger&&this._logger.debug({text:"Received request even though not listening for requests",message:e}),i={error:{code:dg.methodNotFound,message:"This endpoint does not listen for requests or notifications.",data:void 0}};let n;"result"in i?n={jsonrpc:"2.0",id:e.id,result:i.result}:n={jsonrpc:"2.0",id:e.id,error:i.error},await this._stream.send(n)}_processResponse(e){const i=""+e.id,n=this._unprocessedResponses.get(i);if(!n){this._logger&&this._logger.debug({text:"Got an unexpected response message",message:e});return}this._unprocessedResponses.delete(i),n(e)}_newRequestId(){return this._lastUsedRequestId++}sendRequest(e,i,n){const r={jsonrpc:"2.0",id:this._newRequestId(),method:e.method,params:e.params||void 0};return n&&n(r.id),new Promise((o,a)=>{const l=""+r.id;this._unprocessedResponses.set(l,c=>{"result"in c?o({result:c.result}):(c.error||a(new Error("Response had neither 'result' nor 'error' field set.")),o({error:c.error}))}),this._stream.send(r).then(void 0,c=>{this._unprocessedResponses.delete(l),a(c)})})}sendNotification(e,i){const n={jsonrpc:"2.0",id:void 0,method:e.method,params:e.params||void 0};return this._stream.send(n)}toString(){return"StreamChannel/"+this._stream.toString()}},t2;(function(s){function e(){return{deserializeFromJson:r=>({hasErrors:!1,value:r}),serializeToJson:r=>r}}s.sAny=e;function i(){return{deserializeFromJson:r=>({hasErrors:!1,value:{}}),serializeToJson:r=>({})}}s.sEmptyObject=i;function n(){return{deserializeFromJson:r=>({hasErrors:!1,value:void 0}),serializeToJson:r=>null}}s.sVoidFromNull=n})(t2||(t2={}));const H$e=Symbol("OptionalMethodNotFound");var V$e=class{contextualize(s){return new dTt(this,s)}},dTt=class extends V$e{constructor(s,e){super(),ri(this,"underylingTypedChannel"),ri(this,"converters"),this.underylingTypedChannel=s,this.converters=e}async request(s,e,i){const n=await this.converters.getSendContext(i);return this.underylingTypedChannel.request(s,e,n)}async notify(s,e,i){const n=await this.converters.getSendContext(i);return this.underylingTypedChannel.notify(s,e,n)}registerNotificationHandler(s,e){return this.underylingTypedChannel.registerNotificationHandler(s,async(i,n)=>await e(i,await this.converters.getNewContext(n)))}registerRequestHandler(s,e){return this.underylingTypedChannel.registerRequestHandler(s,async(i,n,r)=>await e(i,n,await this.converters.getNewContext(r)))}},ide=class z$e extends V$e{constructor(e,i={}){super(),ri(this,"channelCtor"),ri(this,"_requestSender"),ri(this,"_handler",new Map),ri(this,"_unknownNotificationHandler",new Set),ri(this,"_timeout"),ri(this,"sendExceptionDetails",!1),ri(this,"_logger"),ri(this,"listeningDeferred",new sTt),ri(this,"onListening",this.listeningDeferred.promise),ri(this,"_requestDidErrorEventEmitter",new yme),ri(this,"onRequestDidError",this._requestDidErrorEventEmitter.event),this.channelCtor=e,this._logger=i.logger,this.sendExceptionDetails=!!i.sendExceptionDetails,this._timeout=nTt(1e3,()=>{this._requestSender||console.warn(`"${this.startListen.name}" has not been called within 1 second after construction of this channel. Did you forget to call it?`,this)})}static fromTransport(e,i={}){return new z$e(cTt.createChannel(e,i.logger),i)}startListen(){if(this._requestSender)throw new Error(`"${this.startListen.name}" can be called only once, but it already has been called.`);this._timeout&&(this._timeout.dispose(),this._timeout=void 0),this._requestSender=this.channelCtor.connect({handleRequest:(e,i,n)=>this.handleRequest(e,i,n),handleNotification:(e,i)=>this.handleNotification(e,i)}),this.listeningDeferred.resolve()}checkChannel(e){if(!e)throw new Error(`"${this.startListen.name}" must be called before any messages can be sent or received.`);return!0}async handleRequest(e,i,n){const r=this._handler.get(e.method);if(!r)return this._logger&&this._logger.debug({text:`No request handler for "${e.method}".`,data:{requestObject:e}}),{error:{code:dg.methodNotFound,message:`No request handler for "${e.method}".`,data:{method:e.method}}};if(r.kind!="request"){const a=`"${e.method}" is registered as notification, but was sent as request.`;return this._logger&&this._logger.debug({text:a,data:{requestObject:e}}),{error:{code:dg.invalidRequest,message:a,data:{method:e.method}}}}const o=r.requestType.paramsSerializer.deserializeFromJson(e.params);if(o.hasErrors){const a=`Got invalid params: ${o.errorMessage}`;return this._logger&&this._logger.debug({text:a,data:{requestObject:e,errorMessage:o.errorMessage}}),{error:{code:dg.invalidParams,message:a,data:{errors:o.errorMessage}}}}else{const a=o.value;let l;try{const c=await r.handler(a,i,n);if("error"in c||"errorMessage"in c){const d=c.error?r.requestType.errorSerializer.serializeToJson(c.error):void 0;l={error:{code:c.errorCode||dg.genericApplicationError,message:c.errorMessage||"An error was returned",data:d}}}else l={result:r.requestType.resultSerializer.serializeToJson(c.ok)}}catch(c){c instanceof ySe?l={error:{code:c.code,message:c.message}}:(this._logger&&this._logger.warn({text:`An exception was thrown while handling a request: ${c}.`,exception:c,data:{requestObject:e}}),l={error:{code:dg.unexpectedServerError,message:this.sendExceptionDetails?`An exception was thrown while handling a request: ${c}.`:"Server has thrown an unexpected exception"}})}return l}}async handleNotification(e,i){const n=this._handler.get(e.method);if(!n){for(const a of this._unknownNotificationHandler)a(e);this._unknownNotificationHandler.size===0&&this._logger&&this._logger.debug({text:`Unhandled notification "${e.method}"`,data:{requestObject:e}});return}if(n.kind!="notification"){this._logger&&this._logger.debug({text:`"${e.method}" is registered as request, but was sent as notification.`,data:{requestObject:e}});return}const r=n.notificationType.paramsSerializer.deserializeFromJson(e.params);if(r.hasErrors){this._logger&&this._logger.debug({text:`Got invalid params: ${r}`,data:{requestObject:e,errorMessage:r.errorMessage}});return}const o=r.value;for(const a of n.handlers)try{a(o,i)}catch(l){this._logger&&this._logger.warn({text:`An exception was thrown while handling a notification: ${l}.`,exception:l,data:{requestObject:e}})}}registerUnknownNotificationHandler(e){return VX(this._unknownNotificationHandler,e)}registerRequestHandler(e,i){if(this._handler.get(e.method))throw new Error(`Handler with method "${e.method}" already registered.`);return VX(this._handler,e.method,{kind:"request",requestType:e,handler:i})}registerNotificationHandler(e,i){let n=this._handler.get(e.method);if(!n)n={kind:"notification",notificationType:e,handlers:new Set},this._handler.set(e.method,n);else{if(n.kind!=="notification")throw new Error(`Method "${e.method}" was already registered as request handler.`);if(n.notificationType!==e)throw new Error(`Method "${e.method}" was registered for a different type.`)}return VX(n.handlers,i)}getRegisteredTypes(){const e=[];for(const i of this._handler.values())i.kind==="notification"?e.push(i.notificationType):i.kind==="request"&&e.push(i.requestType);return e}async request(e,i,n){if(!this.checkChannel(this._requestSender))throw new Error("Impossible");const r=e.paramsSerializer.serializeToJson(i);bSe(r);const o=await this._requestSender.sendRequest({method:e.method,params:r},n);if("error"in o){if(e.isOptional&&o.error.code===dg.methodNotFound)return H$e;let a;if(o.error.data!==void 0){const c=e.errorSerializer.deserializeFromJson(o.error.data);if(c.hasErrors)throw new Error(c.errorMessage);a=c.value}else a=void 0;const l=new ySe(o.error.message,a,o.error.code);throw this._requestDidErrorEventEmitter.fire({error:l}),l}else{const a=e.resultSerializer.deserializeFromJson(o.result);if(a.hasErrors)throw new Error("Could not deserialize response: "+a.errorMessage+`
|
|
954
954
|
|
|
955
955
|
${JSON.stringify(o,null,2)}`);return a.value}}async notify(e,i,n){if(!this.checkChannel(this._requestSender))throw new Error;const r=e.paramsSerializer.serializeToJson(i);bSe(r),this._requestSender.sendNotification({method:e.method,params:r},n)}};function bSe(s){if(s!==null&&Array.isArray(s)&&typeof s!="object")throw new Error("Invalid value! Only null, array and object is allowed.")}var ySe=class U$e extends Error{constructor(e,i,n=dg.genericApplicationError){super(e),ri(this,"data"),ri(this,"code"),this.data=i,this.code=n,Object.setPrototypeOf(this,U$e.prototype)}},uTt=class nde{constructor(e,i,n,r,o=!1){ri(this,"method"),ri(this,"paramsSerializer"),ri(this,"resultSerializer"),ri(this,"errorSerializer"),ri(this,"isOptional"),ri(this,"kind","request"),this.method=e,this.paramsSerializer=i,this.resultSerializer=n,this.errorSerializer=r,this.isOptional=o}withMethod(e){return new nde(e,this.paramsSerializer,this.resultSerializer,this.errorSerializer)}optional(){return new nde(this.method,this.paramsSerializer,this.resultSerializer,this.errorSerializer,!0)}},hTt=class q$e{constructor(e,i){ri(this,"method"),ri(this,"paramsSerializer"),ri(this,"kind","notification"),this.method=e,this.paramsSerializer=i}withMethod(e){return new q$e(e,this.paramsSerializer)}};function Hi(s){return new uTt((s||{}).method,t2.sAny(),t2.sAny(),t2.sAny())}function Zr(s){return new hTt((s||{}).method,t2.sAny())}const fTt=Symbol();var wSe=(_Se=fTt,W$=class{constructor(s){ri(this,"error"),ri(this,_Se),this.error=s}},ri(W$,"factory",s=>new W$(s)),W$);function gTt(s){const e=xSe(s.server),i=xSe(s.client);return new pTt(s.tags||[],e,i)}function xSe(s){const e={};for(const[i,n]of Object.entries(s)){const r=n.method?n.method:i;e[i]=n.withMethod(r)}return e}var pTt=class G$e{constructor(e=[],i,n){ri(this,"tags"),ri(this,"server"),ri(this,"client"),this.tags=e,this.server=i,this.client=n}_onlyDesignTime(){return new Error("This property is not meant to be accessed at runtime")}get TContractObject(){throw this._onlyDesignTime()}get TClientInterface(){throw this._onlyDesignTime()}get TServerInterface(){throw this._onlyDesignTime()}get TClientHandler(){throw this._onlyDesignTime()}get TServerHandler(){throw this._onlyDesignTime()}get TTags(){throw this._onlyDesignTime()}getInterface(e,i,n,r){const o=this.buildCounterpart(e,n),a=this.registerHandlers(e,i,r,o);return{counterpart:o,dispose:()=>a.dispose()}}buildCounterpart(e,i){const n={};for(const[r,o]of Object.entries(i)){let a;o.kind==="request"?o.isOptional?a=async(l,c)=>{l===void 0&&(l={});try{return await e.request(o,l,c)}catch(d){if(d&&d.code===dg.methodNotFound)return H$e;throw d}}:a=(l,c)=>(l===void 0&&(l={}),e.request(o,l,c)):a=(l,c)=>(l===void 0&&(l={}),e.notify(o,l,c)),n[r]=a}return n}registerHandlers(e,i,n,r){const o=[];for(const[a,l]of Object.entries(i))if(l.kind==="request"){let c=n[a];if(!c)continue;const d=this.createRequestHandler(r,c);o.push(e.registerRequestHandler(l,d))}else{const c=n[a];c&&o.push(e.registerNotificationHandler(l,(d,u)=>{c(d,{context:u,counterpart:r})}))}return{dispose:()=>o.forEach(a=>a.dispose())}}createRequestHandler(e,i){return async(n,r,o)=>{const a=await i(n,{context:o,counterpart:e,newErr:wSe.factory,requestId:r});return a instanceof wSe?a.error:{ok:a}}}static getServerFromStream(e,i,n,r){const o=ide.fromTransport(i,n),{server:a}=e.getServer(o,r);return o.startListen(),{channel:o,server:a}}static registerServerToStream(e,i,n,r){const o=ide.fromTransport(i,n),{client:a}=e.registerServer(o,r);return o.startListen(),{channel:o,client:a}}getServer(e,i){const{counterpart:n,dispose:r}=this.getInterface(e,this.client,this.server,i);return{server:n,dispose:r}}registerServer(e,i){const{counterpart:n,dispose:r}=this.getInterface(e,this.server,this.client,i);return{client:n,dispose:r}}withContext(){return new G$e(this.tags,this.server,this.client)}};let i2=(function(s){return s.Comment="comment",s.Imports="imports",s.Region="region",s})({}),Co=(function(s){return s[s.File=1]="File",s[s.Module=2]="Module",s[s.Namespace=3]="Namespace",s[s.Package=4]="Package",s[s.Class=5]="Class",s[s.Method=6]="Method",s[s.Property=7]="Property",s[s.Field=8]="Field",s[s.Constructor=9]="Constructor",s[s.Enum=10]="Enum",s[s.Interface=11]="Interface",s[s.Function=12]="Function",s[s.Variable=13]="Variable",s[s.Constant=14]="Constant",s[s.String=15]="String",s[s.Number=16]="Number",s[s.Boolean=17]="Boolean",s[s.Array=18]="Array",s[s.Object=19]="Object",s[s.Key=20]="Key",s[s.Null=21]="Null",s[s.EnumMember=22]="EnumMember",s[s.Struct=23]="Struct",s[s.Event=24]="Event",s[s.Operator=25]="Operator",s[s.TypeParameter=26]="TypeParameter",s})({}),K$e=(function(s){return s[s.Deprecated=1]="Deprecated",s})({}),CSe=(function(s){return s[s.Type=1]="Type",s[s.Parameter=2]="Parameter",s})({}),mTt=(function(s){return s[s.None=0]="None",s[s.Full=1]="Full",s[s.Incremental=2]="Incremental",s})({}),No=(function(s){return s[s.Text=1]="Text",s[s.Method=2]="Method",s[s.Function=3]="Function",s[s.Constructor=4]="Constructor",s[s.Field=5]="Field",s[s.Variable=6]="Variable",s[s.Class=7]="Class",s[s.Interface=8]="Interface",s[s.Module=9]="Module",s[s.Property=10]="Property",s[s.Unit=11]="Unit",s[s.Value=12]="Value",s[s.Enum=13]="Enum",s[s.Keyword=14]="Keyword",s[s.Snippet=15]="Snippet",s[s.Color=16]="Color",s[s.File=17]="File",s[s.Reference=18]="Reference",s[s.Folder=19]="Folder",s[s.EnumMember=20]="EnumMember",s[s.Constant=21]="Constant",s[s.Struct=22]="Struct",s[s.Event=23]="Event",s[s.Operator=24]="Operator",s[s.TypeParameter=25]="TypeParameter",s})({}),_Tt=(function(s){return s[s.Deprecated=1]="Deprecated",s})({}),vTt=(function(s){return s[s.PlainText=1]="PlainText",s[s.Snippet=2]="Snippet",s})({}),zX=(function(s){return s[s.Text=1]="Text",s[s.Read=2]="Read",s[s.Write=3]="Write",s})({}),Bv=(function(s){return s.Empty="",s.QuickFix="quickfix",s.Refactor="refactor",s.RefactorExtract="refactor.extract",s.RefactorInline="refactor.inline",s.RefactorRewrite="refactor.rewrite",s.Source="source",s.SourceOrganizeImports="source.organizeImports",s.SourceFixAll="source.fixAll",s})({}),oH=(function(s){return s.PlainText="plaintext",s.Markdown="markdown",s})({}),Rb=(function(s){return s[s.Error=1]="Error",s[s.Warning=2]="Warning",s[s.Information=3]="Information",s[s.Hint=4]="Hint",s})({}),SSe=(function(s){return s[s.Unnecessary=1]="Unnecessary",s[s.Deprecated=2]="Deprecated",s})({}),C8=(function(s){return s[s.Invoked=1]="Invoked",s[s.TriggerCharacter=2]="TriggerCharacter",s[s.TriggerForIncompleteCompletions=3]="TriggerForIncompleteCompletions",s})({}),S8=(function(s){return s[s.Invoked=1]="Invoked",s[s.TriggerCharacter=2]="TriggerCharacter",s[s.ContentChange=3]="ContentChange",s})({}),sde=(function(s){return s[s.Invoked=1]="Invoked",s[s.Automatic=2]="Automatic",s})({}),bTt=(function(s){return s.Relative="relative",s})({});var Wn=class{constructor(s){this.method=s}};const _n={textDocumentImplementation:new Wn("textDocument/implementation"),textDocumentTypeDefinition:new Wn("textDocument/typeDefinition"),textDocumentDocumentColor:new Wn("textDocument/documentColor"),textDocumentColorPresentation:new Wn("textDocument/colorPresentation"),textDocumentFoldingRange:new Wn("textDocument/foldingRange"),textDocumentDeclaration:new Wn("textDocument/declaration"),textDocumentSelectionRange:new Wn("textDocument/selectionRange"),textDocumentPrepareCallHierarchy:new Wn("textDocument/prepareCallHierarchy"),textDocumentSemanticTokensFull:new Wn("textDocument/semanticTokens/full"),textDocumentSemanticTokensFullDelta:new Wn("textDocument/semanticTokens/full/delta"),textDocumentLinkedEditingRange:new Wn("textDocument/linkedEditingRange"),workspaceWillCreateFiles:new Wn("workspace/willCreateFiles"),workspaceWillRenameFiles:new Wn("workspace/willRenameFiles"),workspaceWillDeleteFiles:new Wn("workspace/willDeleteFiles"),textDocumentMoniker:new Wn("textDocument/moniker"),textDocumentPrepareTypeHierarchy:new Wn("textDocument/prepareTypeHierarchy"),textDocumentInlineValue:new Wn("textDocument/inlineValue"),textDocumentInlayHint:new Wn("textDocument/inlayHint"),textDocumentDiagnostic:new Wn("textDocument/diagnostic"),textDocumentInlineCompletion:new Wn("textDocument/inlineCompletion"),textDocumentWillSaveWaitUntil:new Wn("textDocument/willSaveWaitUntil"),textDocumentCompletion:new Wn("textDocument/completion"),textDocumentHover:new Wn("textDocument/hover"),textDocumentSignatureHelp:new Wn("textDocument/signatureHelp"),textDocumentDefinition:new Wn("textDocument/definition"),textDocumentReferences:new Wn("textDocument/references"),textDocumentDocumentHighlight:new Wn("textDocument/documentHighlight"),textDocumentDocumentSymbol:new Wn("textDocument/documentSymbol"),textDocumentCodeAction:new Wn("textDocument/codeAction"),workspaceSymbol:new Wn("workspace/symbol"),textDocumentCodeLens:new Wn("textDocument/codeLens"),textDocumentDocumentLink:new Wn("textDocument/documentLink"),textDocumentFormatting:new Wn("textDocument/formatting"),textDocumentRangeFormatting:new Wn("textDocument/rangeFormatting"),textDocumentRangesFormatting:new Wn("textDocument/rangesFormatting"),textDocumentOnTypeFormatting:new Wn("textDocument/onTypeFormatting"),textDocumentRename:new Wn("textDocument/rename"),workspaceExecuteCommand:new Wn("workspace/executeCommand"),workspaceDidCreateFiles:new Wn("workspace/didCreateFiles"),workspaceDidRenameFiles:new Wn("workspace/didRenameFiles"),workspaceDidDeleteFiles:new Wn("workspace/didDeleteFiles"),workspaceDidChangeConfiguration:new Wn("workspace/didChangeConfiguration"),textDocumentDidOpen:new Wn("textDocument/didOpen"),textDocumentDidChange:new Wn("textDocument/didChange"),textDocumentDidClose:new Wn("textDocument/didClose"),textDocumentDidSave:new Wn("textDocument/didSave"),textDocumentWillSave:new Wn("textDocument/willSave"),workspaceDidChangeWatchedFiles:new Wn("workspace/didChangeWatchedFiles")},v5=gTt({server:{textDocumentImplementation:Hi({method:"textDocument/implementation"}),textDocumentTypeDefinition:Hi({method:"textDocument/typeDefinition"}),textDocumentDocumentColor:Hi({method:"textDocument/documentColor"}),textDocumentColorPresentation:Hi({method:"textDocument/colorPresentation"}),textDocumentFoldingRange:Hi({method:"textDocument/foldingRange"}),textDocumentDeclaration:Hi({method:"textDocument/declaration"}),textDocumentSelectionRange:Hi({method:"textDocument/selectionRange"}),textDocumentPrepareCallHierarchy:Hi({method:"textDocument/prepareCallHierarchy"}),callHierarchyIncomingCalls:Hi({method:"callHierarchy/incomingCalls"}),callHierarchyOutgoingCalls:Hi({method:"callHierarchy/outgoingCalls"}),textDocumentSemanticTokensFull:Hi({method:"textDocument/semanticTokens/full"}),textDocumentSemanticTokensFullDelta:Hi({method:"textDocument/semanticTokens/full/delta"}),textDocumentSemanticTokensRange:Hi({method:"textDocument/semanticTokens/range"}),textDocumentLinkedEditingRange:Hi({method:"textDocument/linkedEditingRange"}),workspaceWillCreateFiles:Hi({method:"workspace/willCreateFiles"}),workspaceWillRenameFiles:Hi({method:"workspace/willRenameFiles"}),workspaceWillDeleteFiles:Hi({method:"workspace/willDeleteFiles"}),textDocumentMoniker:Hi({method:"textDocument/moniker"}),textDocumentPrepareTypeHierarchy:Hi({method:"textDocument/prepareTypeHierarchy"}),typeHierarchySupertypes:Hi({method:"typeHierarchy/supertypes"}),typeHierarchySubtypes:Hi({method:"typeHierarchy/subtypes"}),textDocumentInlineValue:Hi({method:"textDocument/inlineValue"}),textDocumentInlayHint:Hi({method:"textDocument/inlayHint"}),inlayHintResolve:Hi({method:"inlayHint/resolve"}),textDocumentDiagnostic:Hi({method:"textDocument/diagnostic"}),workspaceDiagnostic:Hi({method:"workspace/diagnostic"}),textDocumentInlineCompletion:Hi({method:"textDocument/inlineCompletion"}),initialize:Hi({method:"initialize"}),shutdown:Hi({method:"shutdown"}),textDocumentWillSaveWaitUntil:Hi({method:"textDocument/willSaveWaitUntil"}),textDocumentCompletion:Hi({method:"textDocument/completion"}),completionItemResolve:Hi({method:"completionItem/resolve"}),textDocumentHover:Hi({method:"textDocument/hover"}),textDocumentSignatureHelp:Hi({method:"textDocument/signatureHelp"}),textDocumentDefinition:Hi({method:"textDocument/definition"}),textDocumentReferences:Hi({method:"textDocument/references"}),textDocumentDocumentHighlight:Hi({method:"textDocument/documentHighlight"}),textDocumentDocumentSymbol:Hi({method:"textDocument/documentSymbol"}),textDocumentCodeAction:Hi({method:"textDocument/codeAction"}),codeActionResolve:Hi({method:"codeAction/resolve"}),workspaceSymbol:Hi({method:"workspace/symbol"}),workspaceSymbolResolve:Hi({method:"workspaceSymbol/resolve"}),textDocumentCodeLens:Hi({method:"textDocument/codeLens"}),codeLensResolve:Hi({method:"codeLens/resolve"}),textDocumentDocumentLink:Hi({method:"textDocument/documentLink"}),documentLinkResolve:Hi({method:"documentLink/resolve"}),textDocumentFormatting:Hi({method:"textDocument/formatting"}),textDocumentRangeFormatting:Hi({method:"textDocument/rangeFormatting"}),textDocumentRangesFormatting:Hi({method:"textDocument/rangesFormatting"}),textDocumentOnTypeFormatting:Hi({method:"textDocument/onTypeFormatting"}),textDocumentRename:Hi({method:"textDocument/rename"}),textDocumentPrepareRename:Hi({method:"textDocument/prepareRename"}),workspaceExecuteCommand:Hi({method:"workspace/executeCommand"}),workspaceDidChangeWorkspaceFolders:Zr({method:"workspace/didChangeWorkspaceFolders"}),windowWorkDoneProgressCancel:Zr({method:"window/workDoneProgress/cancel"}),workspaceDidCreateFiles:Zr({method:"workspace/didCreateFiles"}),workspaceDidRenameFiles:Zr({method:"workspace/didRenameFiles"}),workspaceDidDeleteFiles:Zr({method:"workspace/didDeleteFiles"}),notebookDocumentDidOpen:Zr({method:"notebookDocument/didOpen"}),notebookDocumentDidChange:Zr({method:"notebookDocument/didChange"}),notebookDocumentDidSave:Zr({method:"notebookDocument/didSave"}),notebookDocumentDidClose:Zr({method:"notebookDocument/didClose"}),initialized:Zr({method:"initialized"}),exit:Zr({method:"exit"}),workspaceDidChangeConfiguration:Zr({method:"workspace/didChangeConfiguration"}),textDocumentDidOpen:Zr({method:"textDocument/didOpen"}),textDocumentDidChange:Zr({method:"textDocument/didChange"}),textDocumentDidClose:Zr({method:"textDocument/didClose"}),textDocumentDidSave:Zr({method:"textDocument/didSave"}),textDocumentWillSave:Zr({method:"textDocument/willSave"}),workspaceDidChangeWatchedFiles:Zr({method:"workspace/didChangeWatchedFiles"}),setTrace:Zr({method:"$/setTrace"}),cancelRequest:Zr({method:"$/cancelRequest"}),progress:Zr({method:"$/progress"})},client:{workspaceWorkspaceFolders:Hi({method:"workspace/workspaceFolders"}).optional(),workspaceConfiguration:Hi({method:"workspace/configuration"}).optional(),workspaceFoldingRangeRefresh:Hi({method:"workspace/foldingRange/refresh"}).optional(),windowWorkDoneProgressCreate:Hi({method:"window/workDoneProgress/create"}).optional(),workspaceSemanticTokensRefresh:Hi({method:"workspace/semanticTokens/refresh"}).optional(),windowShowDocument:Hi({method:"window/showDocument"}).optional(),workspaceInlineValueRefresh:Hi({method:"workspace/inlineValue/refresh"}).optional(),workspaceInlayHintRefresh:Hi({method:"workspace/inlayHint/refresh"}).optional(),workspaceDiagnosticRefresh:Hi({method:"workspace/diagnostic/refresh"}).optional(),clientRegisterCapability:Hi({method:"client/registerCapability"}).optional(),clientUnregisterCapability:Hi({method:"client/unregisterCapability"}).optional(),windowShowMessageRequest:Hi({method:"window/showMessageRequest"}).optional(),workspaceCodeLensRefresh:Hi({method:"workspace/codeLens/refresh"}).optional(),workspaceApplyEdit:Hi({method:"workspace/applyEdit"}).optional(),windowShowMessage:Zr({method:"window/showMessage"}),windowLogMessage:Zr({method:"window/logMessage"}),telemetryEvent:Zr({method:"telemetry/event"}),textDocumentPublishDiagnostics:Zr({method:"textDocument/publishDiagnostics"}),logTrace:Zr({method:"$/logTrace"}),cancelRequest:Zr({method:"$/cancelRequest"}),progress:Zr({method:"$/progress"})}});function $S(s,e){if(s.textModel!==e)throw new Error(`Expected text model to be ${e}, but got ${s.textModel}`);return s}var Do=(HX=class{constructor(){ri(this,"_store",new wme)}dispose(){this._store.dispose()}_register(s){if(s===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(s)}},ri(HX,"None",Object.freeze({dispose(){}})),HX),wme=(H$=class{constructor(){ri(this,"_toDispose",new Set),ri(this,"_isDisposed",!1)}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}clear(){if(this._toDispose.size!==0)try{for(const s of this._toDispose)s.dispose()}finally{this._toDispose.clear()}}add(s){if(!s)return s;if(s===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?H$.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(s),s}},ri(H$,"DISABLE_DISPOSED_WARNING",!1),H$);const Y$e=new Map([[Bv.Empty,""],[Bv.QuickFix,"quickfix"],[Bv.Refactor,"refactor"],[Bv.RefactorExtract,"refactor.extract"],[Bv.RefactorInline,"refactor.inline"],[Bv.RefactorRewrite,"refactor.rewrite"],[Bv.Source,"source"],[Bv.SourceOrganizeImports,"source.organizeImports"],[Bv.SourceFixAll,"source.fixAll"]]);function yTt(s){if(s)return Y$e.get(s)??s}const wTt=new Map([[Bt.CodeActionTriggerType.Invoke,sde.Invoked],[Bt.CodeActionTriggerType.Auto,sde.Automatic]]);function xTt(s){return wTt.get(s)??sde.Invoked}const X$e=new Map([[No.Text,Bt.CompletionItemKind.Text],[No.Method,Bt.CompletionItemKind.Method],[No.Function,Bt.CompletionItemKind.Function],[No.Constructor,Bt.CompletionItemKind.Constructor],[No.Field,Bt.CompletionItemKind.Field],[No.Variable,Bt.CompletionItemKind.Variable],[No.Class,Bt.CompletionItemKind.Class],[No.Interface,Bt.CompletionItemKind.Interface],[No.Module,Bt.CompletionItemKind.Module],[No.Property,Bt.CompletionItemKind.Property],[No.Unit,Bt.CompletionItemKind.Unit],[No.Value,Bt.CompletionItemKind.Value],[No.Enum,Bt.CompletionItemKind.Enum],[No.Keyword,Bt.CompletionItemKind.Keyword],[No.Snippet,Bt.CompletionItemKind.Snippet],[No.Color,Bt.CompletionItemKind.Color],[No.File,Bt.CompletionItemKind.File],[No.Reference,Bt.CompletionItemKind.Reference],[No.Folder,Bt.CompletionItemKind.Folder],[No.EnumMember,Bt.CompletionItemKind.EnumMember],[No.Constant,Bt.CompletionItemKind.Constant],[No.Struct,Bt.CompletionItemKind.Struct],[No.Event,Bt.CompletionItemKind.Event],[No.Operator,Bt.CompletionItemKind.Operator],[No.TypeParameter,Bt.CompletionItemKind.TypeParameter]]);function CTt(s){return s?X$e.get(s)??Bt.CompletionItemKind.Text:Bt.CompletionItemKind.Text}const Z$e=new Map([[_Tt.Deprecated,Bt.CompletionItemTag.Deprecated]]);function STt(s){return Z$e.get(s)}const kTt=new Map([[Bt.CompletionTriggerKind.Invoke,C8.Invoked],[Bt.CompletionTriggerKind.TriggerCharacter,C8.TriggerCharacter],[Bt.CompletionTriggerKind.TriggerForIncompleteCompletions,C8.TriggerForIncompleteCompletions]]);function LTt(s){return kTt.get(s)??C8.Invoked}const ETt=new Map([[vTt.Snippet,Bt.CompletionItemInsertTextRule.InsertAsSnippet]]);function DTt(s){if(s)return ETt.get(s)}const Q$e=new Map([[Co.File,Bt.SymbolKind.File],[Co.Module,Bt.SymbolKind.Module],[Co.Namespace,Bt.SymbolKind.Namespace],[Co.Package,Bt.SymbolKind.Package],[Co.Class,Bt.SymbolKind.Class],[Co.Method,Bt.SymbolKind.Method],[Co.Property,Bt.SymbolKind.Property],[Co.Field,Bt.SymbolKind.Field],[Co.Constructor,Bt.SymbolKind.Constructor],[Co.Enum,Bt.SymbolKind.Enum],[Co.Interface,Bt.SymbolKind.Interface],[Co.Function,Bt.SymbolKind.Function],[Co.Variable,Bt.SymbolKind.Variable],[Co.Constant,Bt.SymbolKind.Constant],[Co.String,Bt.SymbolKind.String],[Co.Number,Bt.SymbolKind.Number],[Co.Boolean,Bt.SymbolKind.Boolean],[Co.Array,Bt.SymbolKind.Array],[Co.Object,Bt.SymbolKind.Object],[Co.Key,Bt.SymbolKind.Key],[Co.Null,Bt.SymbolKind.Null],[Co.EnumMember,Bt.SymbolKind.EnumMember],[Co.Struct,Bt.SymbolKind.Struct],[Co.Event,Bt.SymbolKind.Event],[Co.Operator,Bt.SymbolKind.Operator],[Co.TypeParameter,Bt.SymbolKind.TypeParameter]]);function J$e(s){return Q$e.get(s)??Bt.SymbolKind.File}const TTt=new Map([[K$e.Deprecated,Bt.SymbolTag.Deprecated]]);function e6e(s){return TTt.get(s)}const ITt=new Map([[zX.Text,Bt.DocumentHighlightKind.Text],[zX.Read,Bt.DocumentHighlightKind.Read],[zX.Write,Bt.DocumentHighlightKind.Write]]);function NTt(s){return s?ITt.get(s)??Bt.DocumentHighlightKind.Text:Bt.DocumentHighlightKind.Text}const RTt=new Map([[i2.Comment,Bt.FoldingRangeKind.Comment],[i2.Imports,Bt.FoldingRangeKind.Imports],[i2.Region,Bt.FoldingRangeKind.Region]]);function ATt(s){if(s)return RTt.get(s)}const MTt=new Map([[pg.Error,Rb.Error],[pg.Warning,Rb.Warning],[pg.Info,Rb.Information],[pg.Hint,Rb.Hint]]);function PTt(s){return MTt.get(s)??Rb.Error}const OTt=new Map([[Rb.Error,pg.Error],[Rb.Warning,pg.Warning],[Rb.Information,pg.Info],[Rb.Hint,pg.Hint]]);function FTt(s){return s?OTt.get(s)??pg.Error:pg.Error}const t6e=new Map([[SSe.Unnecessary,rH.Unnecessary],[SSe.Deprecated,rH.Deprecated]]);function BTt(s){return t6e.get(s)}const jTt=new Map([[Bt.SignatureHelpTriggerKind.Invoke,S8.Invoked],[Bt.SignatureHelpTriggerKind.TriggerCharacter,S8.TriggerCharacter],[Bt.SignatureHelpTriggerKind.ContentChange,S8.ContentChange]]);function $Tt(s){return jTt.get(s)??S8.Invoked}function n2(s){if(s)return{id:s.command,title:s.title,arguments:s.arguments}}const WTt=new Map([[CSe.Type,Bt.InlayHintKind.Type],[CSe.Parameter,Bt.InlayHintKind.Parameter]]);function HTt(s){return s?WTt.get(s)??Bt.InlayHintKind.Type:Bt.InlayHintKind.Type}function E1(s,e){if("targetUri"in s){const i=e.bridge.translateBackRange({uri:s.targetUri},s.targetRange);return{uri:i.textModel.uri,range:i.range,originSelectionRange:s.originSelectionRange?e.bridge.translateBackRange({uri:s.targetUri},s.originSelectionRange).range:void 0,targetSelectionRange:s.targetSelectionRange?e.bridge.translateBackRange({uri:s.targetUri},s.targetSelectionRange).range:void 0}}else{const i=e.bridge.translateBackRange({uri:s.uri},s.range);return{uri:i.textModel.uri,range:i.range}}}function Ga(s){return!s||s.length===0?{language:"*"}:s.map(e=>"notebook"in e?typeof e.notebook=="string"?{notebookType:e.notebook,language:e.language}:{notebookType:e.notebook.notebookType,language:e.language,pattern:e.notebook.pattern,scheme:e.notebook.scheme}:{language:e.language,pattern:e.pattern,scheme:e.scheme})}function VTt(s,e){if(!e)return!0;const i=s.getLanguageId();if(s.uri.toString(!0),!e||e.length===0)return!0;for(const n of e)if(!(n.language&&n.language!=="*"&&n.language!==i))return!0;return!1}function rde(s){var i;const e={severity:FTt(s.severity),startLineNumber:s.range.start.line+1,startColumn:s.range.start.character+1,endLineNumber:s.range.end.line+1,endColumn:s.range.end.character+1,message:s.message,source:s.source,code:typeof s.code=="string"?s.code:(i=s.code)==null?void 0:i.toString()};return s.tags&&(e.tags=s.tags.map(n=>BTt(n)).filter(n=>n!==void 0)),s.relatedInformation&&(e.relatedInformation=s.relatedInformation.map(n=>({resource:iG.parse(n.location.uri),startLineNumber:n.location.range.start.line+1,startColumn:n.location.range.start.character+1,endLineNumber:n.location.range.end.line+1,endColumn:n.location.range.end.character+1,message:n.message}))),e}var zTt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{completion:{dynamicRegistration:!0,contextSupport:!0,completionItemKind:{valueSet:Array.from(X$e.keys())},completionItem:{tagSupport:{valueSet:Array.from(Z$e.keys())},commitCharactersSupport:!0,deprecatedSupport:!0,preselectSupport:!0}}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentCompletion,!0,e=>Bt.registerCompletionItemProvider(Ga(e.documentSelector),new UTt(this._connection,e))))}},UTt=class{constructor(s,e){ri(this,"resolveCompletionItem"),this._client=s,this._capabilities=e,e.resolveProvider&&(this.resolveCompletionItem=async(i,n)=>(i6e(i,await this._client.server.completionItemResolve(i._lspItem),this._client.bridge,i._translated,i._model),i))}get triggerCharacters(){return this._capabilities.triggerCharacters}async provideCompletionItems(s,e,i,n){const r=this._client.bridge.translate(s,e),o=await this._client.server.textDocumentCompletion({textDocument:r.textDocument,position:r.position,context:i.triggerCharacter?{triggerKind:LTt(i.triggerKind),triggerCharacter:i.triggerCharacter}:void 0});return o?{suggestions:(Array.isArray(o)?o:o.items).map(a=>({...qTt(a,this._client.bridge,r,s,e),_lspItem:a,_translated:r,_model:s}))}:{suggestions:[]}}};function qTt(s,e,i,n,r){let o=s.insertText||s.label,a;s.textEdit&&("range"in s.textEdit?(o=s.textEdit.newText,a=$S(e.translateBackRange(i.textDocument,s.textEdit.range),n).range):(o=s.textEdit.newText,a={insert:$S(e.translateBackRange(i.textDocument,s.textEdit.insert),n).range,replace:$S(e.translateBackRange(i.textDocument,s.textEdit.replace),n).range})),a||(a=mR.fromPositions(r,r));const l={label:s.label,kind:CTt(s.kind),insertText:o,sortText:s.sortText,filterText:s.filterText,preselect:s.preselect,commitCharacters:s.commitCharacters,range:a};return i6e(l,s,e,i,n),l}function i6e(s,e,i,n,r){e.detail!==void 0&&(s.detail=e.detail),e.documentation!==void 0&&(s.documentation=GTt(e.documentation)),e.insertTextFormat!==void 0&&(s.insertTextRules=DTt(e.insertTextFormat)),e.tags&&e.tags.length>0&&(s.tags=e.tags.map(STt).filter(o=>o!==void 0)),e.additionalTextEdits&&e.additionalTextEdits.length>0&&(s.additionalTextEdits=e.additionalTextEdits.map(o=>({range:$S(i.translateBackRange(n.textDocument,o.range),r).range,text:o.newText}))),e.command&&(s.command=n2(e.command))}function GTt(s){if(s)return typeof s=="string"?s:{value:s.value,isTrusted:!0}}var KTt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{hover:{dynamicRegistration:!0,contentFormat:[oH.Markdown,oH.PlainText]}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentHover,!0,e=>Bt.registerHoverProvider(Ga(e.documentSelector),new YTt(this._connection,e))))}},YTt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideHover(s,e,i){const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentHover({textDocument:n.textDocument,position:n.position});return!r||!r.contents?null:{contents:XTt(r.contents),range:r.range?this._client.bridge.translateBackRange(n.textDocument,r.range).range:void 0}}};function XTt(s){return Array.isArray(s)?s.map(e=>kSe(e)):[kSe(s)]}function kSe(s){return typeof s=="string"?{value:s,isTrusted:!0}:"kind"in s?{value:s.value,isTrusted:!0}:{value:`\`\`\`${s.language}
|
|
956
956
|
${s.value}
|
|
957
|
-
\`\`\``,isTrusted:!0}}var ZTt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{signatureHelp:{dynamicRegistration:!0,contextSupport:!0,signatureInformation:{documentationFormat:[oH.Markdown,oH.PlainText],parameterInformation:{labelOffsetSupport:!0},activeParameterSupport:!0}}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentSignatureHelp,!0,e=>Bt.registerSignatureHelpProvider(Ga(e.documentSelector),new QTt(this._connection,e))))}},QTt=class{constructor(s,e){ri(this,"signatureHelpTriggerCharacters"),ri(this,"signatureHelpRetriggerCharacters"),this._client=s,this._capabilities=e,this.signatureHelpTriggerCharacters=e.triggerCharacters,this.signatureHelpRetriggerCharacters=e.retriggerCharacters}async provideSignatureHelp(s,e,i,n){const r=this._client.bridge.translate(s,e),o=await this._client.server.textDocumentSignatureHelp({textDocument:r.textDocument,position:r.position,context:{triggerKind:$Tt(n.triggerKind),triggerCharacter:n.triggerCharacter,isRetrigger:n.isRetrigger}});return o?{value:{signatures:o.signatures.map(a=>{var l;return{label:a.label,documentation:LSe(a.documentation),parameters:((l=a.parameters)==null?void 0:l.map(c=>({label:c.label,documentation:LSe(c.documentation)})))||[],activeParameter:a.activeParameter}}),activeSignature:o.activeSignature||0,activeParameter:o.activeParameter||0},dispose:()=>{}}:null}};function LSe(s){if(s)return typeof s=="string"?s:{value:s.value,isTrusted:!0}}var JTt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{definition:{dynamicRegistration:!0,linkSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDefinition,!0,e=>Bt.registerDefinitionProvider(Ga(e.documentSelector),new eIt(this._connection,e))))}},eIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDefinition(s,e,i){const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentDefinition({textDocument:n.textDocument,position:n.position});return r?Array.isArray(r)?r.map(o=>E1(o,this._client)):E1(r,this._client):null}},tIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{declaration:{dynamicRegistration:!0,linkSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDeclaration,!0,e=>Bt.registerDeclarationProvider(Ga(e.documentSelector),new iIt(this._connection,e))))}},iIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDeclaration(s,e,i){const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentDeclaration({textDocument:n.textDocument,position:n.position});return r?Array.isArray(r)?r.map(o=>E1(o,this._client)):E1(r,this._client):null}},nIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{typeDefinition:{dynamicRegistration:!0,linkSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentTypeDefinition,!0,e=>Bt.registerTypeDefinitionProvider(Ga(e.documentSelector),new sIt(this._connection,e))))}},sIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideTypeDefinition(s,e,i){const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentTypeDefinition({textDocument:n.textDocument,position:n.position});return r?Array.isArray(r)?r.map(o=>E1(o,this._client)):E1(r,this._client):null}},rIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{implementation:{dynamicRegistration:!0,linkSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentImplementation,!0,e=>Bt.registerImplementationProvider(Ga(e.documentSelector),new oIt(this._connection,e))))}},oIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideImplementation(s,e,i){const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentImplementation({textDocument:n.textDocument,position:n.position});return r?Array.isArray(r)?r.map(o=>E1(o,this._client)):E1(r,this._client):null}},aIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{references:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentReferences,!0,e=>Bt.registerReferenceProvider(Ga(e.documentSelector),new lIt(this._connection,e))))}},lIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideReferences(s,e,i,n){const r=this._client.bridge.translate(s,e),o=await this._client.server.textDocumentReferences({textDocument:r.textDocument,position:r.position,context:{includeDeclaration:i.includeDeclaration}});return o?o.map(a=>{const l=this._client.bridge.translateBackRange({uri:a.uri},a.range);return{uri:l.textModel.uri,range:l.range}}):null}},cIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{documentHighlight:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDocumentHighlight,!0,e=>Bt.registerDocumentHighlightProvider(Ga(e.documentSelector),new dIt(this._connection,e))))}},dIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDocumentHighlights(s,e,i){const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentDocumentHighlight({textDocument:n.textDocument,position:n.position});return r?r.map(o=>({range:this._client.bridge.translateBackRange(n.textDocument,o.range).range,kind:NTt(o.kind)})):null}},uIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{documentSymbol:{dynamicRegistration:!0,hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:Array.from(Q$e.keys())},tagSupport:{valueSet:[K$e.Deprecated]}}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDocumentSymbol,!0,e=>Bt.registerDocumentSymbolProvider(Ga(e.documentSelector),new hIt(this._connection,e))))}},hIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDocumentSymbols(s,e){const i=this._client.bridge.translate(s,new Fy(1,1)),n=await this._client.server.textDocumentDocumentSymbol({textDocument:i.textDocument});return n?Array.isArray(n)&&n.length>0?"location"in n[0]?n.map(r=>fIt(r,this._client)):n.map(r=>n6e(r,this._client,i.textDocument)):[]:null}};function n6e(s,e,i){var n,r;return{name:s.name,detail:s.detail||"",kind:J$e(s.kind),tags:((n=s.tags)==null?void 0:n.map(o=>e6e(o)).filter(o=>o!==void 0))||[],range:e.bridge.translateBackRange(i,s.range).range,selectionRange:e.bridge.translateBackRange(i,s.selectionRange).range,children:((r=s.children)==null?void 0:r.map(o=>n6e(o,e,i)))||[]}}function fIt(s,e){var i;return{name:s.name,detail:"",kind:J$e(s.kind),tags:((i=s.tags)==null?void 0:i.map(n=>e6e(n)).filter(n=>n!==void 0))||[],range:e.bridge.translateBackRange({uri:s.location.uri},s.location.range).range,selectionRange:e.bridge.translateBackRange({uri:s.location.uri},s.location.range).range,children:[]}}var gIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{rename:{dynamicRegistration:!0,prepareSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentRename,!0,e=>Bt.registerRenameProvider(Ga(e.documentSelector),new pIt(this._connection,e))))}},pIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideRenameEdits(s,e,i,n){const r=this._client.bridge.translate(s,e),o=await this._client.server.textDocumentRename({textDocument:r.textDocument,position:r.position,newName:i});return o?mIt(o,this._client):null}async resolveRenameLocation(s,e,i){if(!this._capabilities.prepareProvider)return null;const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentPrepareRename({textDocument:n.textDocument,position:n.position});if(!r)return null;if("range"in r&&"placeholder"in r)return{range:this._client.bridge.translateBackRange(n.textDocument,r.range).range,text:r.placeholder};if("defaultBehavior"in r)return null;if("start"in r&&"end"in r){const o=this._client.bridge.translateBackRange(n.textDocument,r).range;return{range:o,text:s.getValueInRange(o)}}return null}};function mIt(s,e){const i=[];if(s.changes)for(const n in s.changes){const r=s.changes[n];for(const o of r){const a=e.bridge.translateBackRange({uri:n},o.range);i.push({resource:a.textModel.uri,versionId:void 0,textEdit:{range:a.range,text:o.newText}})}}if(s.documentChanges){for(const n of s.documentChanges)if("textDocument"in n){const r=n.textDocument.uri;for(const o of n.edits){const a=e.bridge.translateBackRange({uri:r},o.range);i.push({resource:a.textModel.uri,versionId:n.textDocument.version,textEdit:{range:a.range,text:o.newText}})}}}return{edits:i}}var _It=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{codeAction:{dynamicRegistration:!0,codeActionLiteralSupport:{codeActionKind:{valueSet:Array.from(Y$e.keys())}},isPreferredSupport:!0,disabledSupport:!0,dataSupport:!0,resolveSupport:{properties:["edit"]}}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentCodeAction,!0,e=>Bt.registerCodeActionProvider(Ga(e.documentSelector),new vIt(this._connection,e))))}},vIt=class{constructor(s,e){ri(this,"resolveCodeAction"),this._client=s,this._capabilities=e,e.resolveProvider&&(this.resolveCodeAction=async(i,n)=>{if(i._lspAction){const r=await this._client.server.codeActionResolve(i._lspAction);r.edit&&(i.edit=ESe(r.edit,this._client)),r.command&&(i.command=n2(r.command))}return i})}async provideCodeActions(s,e,i,n){const r=this._client.bridge.translate(s,e.getStartPosition()),o=await this._client.server.textDocumentCodeAction({textDocument:r.textDocument,range:this._client.bridge.translateRange(s,e),context:{diagnostics:i.markers.map(a=>({range:this._client.bridge.translateRange(s,mR.lift(a)),message:a.message,severity:PTt(a.severity)})),triggerKind:xTt(i.trigger)}});return o?{actions:(Array.isArray(o)?o:[o]).map(a=>{var l;if("title"in a&&!("kind"in a)){const c=a;return{title:c.title,command:n2(c)}}else{const c=a;return{title:c.title,kind:yTt(c.kind),isPreferred:c.isPreferred,disabled:(l=c.disabled)==null?void 0:l.reason,edit:c.edit?ESe(c.edit,this._client):void 0,command:n2(c.command),_lspAction:c}}}),dispose:()=>{}}:null}};function ESe(s,e){const i=[];if(s.changes)for(const n in s.changes){const r=s.changes[n];for(const o of r){const a=e.bridge.translateBackRange({uri:n},o.range);i.push({resource:a.textModel.uri,versionId:void 0,textEdit:{range:a.range,text:o.newText}})}}if(s.documentChanges){for(const n of s.documentChanges)if("textDocument"in n){const r=n.textDocument.uri;for(const o of n.edits){const a=e.bridge.translateBackRange({uri:r},o.range);i.push({resource:a.textModel.uri,versionId:n.textDocument.version??void 0,textEdit:{range:a.range,text:o.newText}})}}}return{edits:i}}var bIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{codeLens:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentCodeLens,!0,e=>Bt.registerCodeLensProvider(Ga(e.documentSelector),new yIt(this._connection,e))))}},yIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideCodeLenses(s,e){const i=this._client.bridge.translate(s,new Fy(1,1)),n=await this._client.server.textDocumentCodeLens({textDocument:i.textDocument});return n?{lenses:n.map(r=>({range:$S(this._client.bridge.translateBackRange(i.textDocument,r.range),s).range,command:n2(r.command),_lspCodeLens:r})),dispose:()=>{}}:null}async resolveCodeLens(s,e,i){if(!this._capabilities.resolveProvider||!e._lspCodeLens)return e;const n=await this._client.server.codeLensResolve(e._lspCodeLens);return n.command&&(e.command={id:n.command.command,title:n.command.title,arguments:n.command.arguments}),e}},wIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{documentLink:{dynamicRegistration:!0,tooltipSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDocumentLink,!0,e=>Bt.registerLinkProvider(Ga(e.documentSelector),new xIt(this._connection,e))))}},xIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideLinks(s,e){const i=this._client.bridge.translate(s,new Fy(1,1)),n=await this._client.server.textDocumentDocumentLink({textDocument:i.textDocument});return n?{links:n.map(r=>({range:this._client.bridge.translateBackRange(i.textDocument,r.range).range,url:r.target,tooltip:r.tooltip}))}:null}async resolveLink(s,e){return this._capabilities.resolveProvider,s}},CIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{formatting:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentFormatting,!0,e=>Bt.registerDocumentFormattingEditProvider(Ga(e.documentSelector),new SIt(this._connection,e))))}},SIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDocumentFormattingEdits(s,e,i){const n=this._client.bridge.translate(s,new Fy(1,1)),r=await this._client.server.textDocumentFormatting({textDocument:n.textDocument,options:{tabSize:e.tabSize,insertSpaces:e.insertSpaces}});return r?r.map(o=>({range:this._client.bridge.translateBackRange(n.textDocument,o.range).range,text:o.newText})):null}},kIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{rangeFormatting:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentRangeFormatting,!0,e=>Bt.registerDocumentRangeFormattingEditProvider(Ga(e.documentSelector),new LIt(this._connection,e))))}},LIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDocumentRangeFormattingEdits(s,e,i,n){const r=this._client.bridge.translate(s,e.getStartPosition()),o=await this._client.server.textDocumentRangeFormatting({textDocument:r.textDocument,range:this._client.bridge.translateRange(s,e),options:{tabSize:i.tabSize,insertSpaces:i.insertSpaces}});return o?o.map(a=>({range:this._client.bridge.translateBackRange(r.textDocument,a.range).range,text:a.newText})):null}},EIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{onTypeFormatting:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentOnTypeFormatting,!0,e=>Bt.registerOnTypeFormattingEditProvider(Ga(e.documentSelector),new DIt(this._connection,e))))}},DIt=class{constructor(s,e){ri(this,"autoFormatTriggerCharacters"),this._client=s,this._capabilities=e,this.autoFormatTriggerCharacters=[e.firstTriggerCharacter,...e.moreTriggerCharacter||[]]}async provideOnTypeFormattingEdits(s,e,i,n,r){const o=this._client.bridge.translate(s,e),a=await this._client.server.textDocumentOnTypeFormatting({textDocument:o.textDocument,position:o.position,ch:i,options:{tabSize:n.tabSize,insertSpaces:n.insertSpaces}});return a?a.map(l=>({range:this._client.bridge.translateBackRange(o.textDocument,l.range).range,text:l.newText})):null}},TIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{foldingRange:{dynamicRegistration:!0,rangeLimit:5e3,lineFoldingOnly:!1,foldingRangeKind:{valueSet:[i2.Comment,i2.Imports,i2.Region]}}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentFoldingRange,!0,e=>Bt.registerFoldingRangeProvider(Ga(e.documentSelector),new IIt(this._connection,e))))}},IIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideFoldingRanges(s,e,i){const n=this._client.bridge.translate(s,new Fy(1,1)),r=await this._client.server.textDocumentFoldingRange({textDocument:n.textDocument});return r?r.map(o=>({start:o.startLine+1,end:o.endLine+1,kind:ATt(o.kind)})):null}},NIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{selectionRange:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentSelectionRange,!0,e=>Bt.registerSelectionRangeProvider(Ga(e.documentSelector),new RIt(this._connection,e))))}},RIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideSelectionRanges(s,e,i){const n=this._client.bridge.translate(s,e[0]),r=await this._client.server.textDocumentSelectionRange({textDocument:n.textDocument,positions:e.map(o=>this._client.bridge.translate(s,o).position)});return r?r.map(o=>this.convertSelectionRange(o,n.textDocument)):null}convertSelectionRange(s,e){const i=[];let n=s;for(;n;)i.push({range:this._client.bridge.translateBackRange(e,n.range).range}),n=n.parent;return i}},AIt=class extends Do{constructor(s){super(),ri(this,"_providers",new Set),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{inlayHint:{dynamicRegistration:!0,resolveSupport:{properties:["tooltip","textEdits","label.tooltip","label.location","label.command"]}}},workspace:{inlayHint:{refreshSupport:!0}}})),this._register(this._connection.connection.registerRequestHandler(v5.client.workspaceInlayHintRefresh,async()=>{for(const e of this._providers)e.refresh();return{ok:null}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentInlayHint,!0,e=>{const i=new MIt(this._connection,e);this._providers.add(i);const n=Bt.registerInlayHintsProvider(Ga(e.documentSelector),i);return{dispose:()=>{this._providers.delete(i),n.dispose()}}}))}},MIt=class{constructor(s,e){ri(this,"_onDidChangeInlayHints",new L1),ri(this,"onDidChangeInlayHints",this._onDidChangeInlayHints.event),ri(this,"resolveInlayHint"),this._client=s,this._capabilities=e,e.resolveProvider&&(this.resolveInlayHint=async(i,n)=>{const r=await this._client.server.inlayHintResolve(i._lspInlayHint);return r.tooltip&&(i.tooltip=ode(r.tooltip)),r.label!==i._lspInlayHint.label&&(i.label=DSe(r.label)),r.textEdits&&(i.textEdits=r.textEdits.map(o=>({range:this._client.bridge.translateBackRange({uri:i._targetUri},o.range).range,text:o.newText}))),i})}refresh(){this._onDidChangeInlayHints.fire()}async provideInlayHints(s,e,i){const n=this._client.bridge.translate(s,e.getStartPosition()),r=await PIt(async()=>await this._client.server.textDocumentInlayHint({textDocument:n.textDocument,range:this._client.bridge.translateRange(s,e)}));return r?{hints:r.map(o=>{var a;return{label:DSe(o.label),position:$S(this._client.bridge.translateBack(n.textDocument,o.position),s).position,kind:HTt(o.kind),tooltip:ode(o.tooltip),paddingLeft:o.paddingLeft,paddingRight:o.paddingRight,textEdits:(a=o.textEdits)==null?void 0:a.map(l=>({range:$S(this._client.bridge.translateBackRange(n.textDocument,l.range),s).range,text:l.newText})),_lspInlayHint:o,_targetUri:n.textDocument.uri}}),dispose:()=>{}}:null}};async function PIt(s){for(let e=3;;e--)try{return await s()}catch(i){if(i.message==="content modified"&&e>0)continue;throw i}}function DSe(s){return typeof s=="string"?s:s.map(e=>{const i={label:e.value,tooltip:ode(e.tooltip),command:n2(e.command)};return e.location&&(i.location={uri:iG.parse(e.location.uri),range:new mR(e.location.range.start.line+1,e.location.range.start.character+1,e.location.range.end.line+1,e.location.range.end.character+1)}),i})}function ode(s){if(s)return typeof s=="string"?s:{value:s.value,isTrusted:!0}}var OIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{semanticTokens:{dynamicRegistration:!0,requests:{range:!0,full:{delta:!0}},tokenTypes:["namespace","type","class","enum","interface","struct","typeParameter","parameter","variable","property","enumMember","event","function","method","macro","keyword","modifier","comment","string","number","regexp","operator","decorator"],tokenModifiers:["declaration","definition","readonly","static","deprecated","abstract","async","modification","documentation","defaultLibrary"],formats:[bTt.Relative],overlappingTokenSupport:!1,multilineTokenSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentSemanticTokensFull,!0,e=>Bt.registerDocumentSemanticTokensProvider(Ga(e.documentSelector),new FIt(this._connection,e))))}},FIt=class{constructor(s,e){this._client=s,this._capabilities=e}getLegend(){return{tokenTypes:this._capabilities.legend.tokenTypes,tokenModifiers:this._capabilities.legend.tokenModifiers}}releaseDocumentSemanticTokens(s){}async provideDocumentSemanticTokens(s,e,i){const n=this._client.bridge.translate(s,s.getPositionAt(0)),r=this._capabilities.full;if(e&&r&&typeof r=="object"&&r.delta){const a=await this._client.server.textDocumentSemanticTokensFullDelta({textDocument:n.textDocument,previousResultId:e});return a?"edits"in a?{resultId:a.resultId,edits:a.edits.map(l=>({start:l.start,deleteCount:l.deleteCount,data:l.data?new Uint32Array(l.data):void 0}))}:{resultId:a.resultId,data:new Uint32Array(a.data)}:null}const o=await this._client.server.textDocumentSemanticTokensFull({textDocument:n.textDocument});return o?{resultId:o.resultId,data:new Uint32Array(o.data)}:null}async provideDocumentSemanticTokensEdits(s,e,i){return this.provideDocumentSemanticTokens(s,e,i)}},BIt=class extends Do{constructor(s){super(),ri(this,"_diagnosticsMarkerOwner","lsp"),ri(this,"_pullDiagnosticProviders",new Map),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{publishDiagnostics:{relatedInformation:!0,tagSupport:{valueSet:[...t6e.keys()]},versionSupport:!0,codeDescriptionSupport:!0,dataSupport:!0},diagnostic:{dynamicRegistration:!0,relatedDocumentSupport:!0}}}));debugger;this._register(this._connection.connection.registerNotificationHandler(v5.client.textDocumentPublishDiagnostics,e=>this._handlePublishDiagnostics(e))),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDiagnostic,!0,e=>{const i=new wme;for(const n of D_.getModels())this._addPullDiagnosticProvider(n,e,i);return i.add(D_.onDidCreateModel(n=>{this._addPullDiagnosticProvider(n,e,i)})),i}))}_addPullDiagnosticProvider(s,e,i){if(s.getLanguageId(),!VTt(s,e.documentSelector))return;const n=new jIt(s,this._connection,this._diagnosticsMarkerOwner,e);this._pullDiagnosticProviders.set(s,n),i.add(n),i.add(s.onWillDispose(()=>{this._pullDiagnosticProviders.delete(s)}))}_handlePublishDiagnostics(s){const e=s.uri;try{const i=this._connection.bridge.translateBack({uri:e},{line:0,character:0}).textModel;if(!i||i.isDisposed())return;const n=s.diagnostics.map(r=>rde(r));D_.setModelMarkers(i,this._diagnosticsMarkerOwner,n)}catch(i){console.debug(`Could not set diagnostics for ${e}:`,i)}}},jIt=class extends Do{constructor(s,e,i,n){super(),ri(this,"_updateHandle"),ri(this,"_previousResultId"),this._model=s,this._connection=e,this._markerOwner=i,this._capability=n,this._register(this._model.onDidChangeContent(()=>{this._scheduleDiagnosticUpdate()})),this._scheduleDiagnosticUpdate()}_scheduleDiagnosticUpdate(){this._updateHandle!==void 0&&clearTimeout(this._updateHandle),this._updateHandle=window.setTimeout(()=>{this._updateHandle=void 0,this._requestDiagnostics()},500)}async _requestDiagnostics(){if(!this._model.isDisposed())try{const s=this._connection.bridge.translate(this._model,new Fy(1,1)),e=await this._connection.server.textDocumentDiagnostic({textDocument:s.textDocument,identifier:this._capability.identifier,previousResultId:this._previousResultId});if(this._model.isDisposed())return;this._handleDiagnosticReport(e)}catch(s){console.error("Error requesting diagnostics:",s)}}_handleDiagnosticReport(s){if(s.kind==="full"){this._previousResultId=s.resultId;const e=s.items.map(i=>rde(i));D_.setModelMarkers(this._model,this._markerOwner,e),"relatedDocuments"in s&&s.relatedDocuments&&this._handleRelatedDocuments(s.relatedDocuments)}else s.kind==="unchanged"&&(this._previousResultId=s.resultId)}_handleRelatedDocuments(s){for(const[e,i]of Object.entries(s))try{const n=this._connection.bridge.translateBack({uri:e},{line:0,character:0}).textModel;if(!n||n.isDisposed())continue;if(i.kind==="full"){const r=i.items.map(o=>rde(o));D_.setModelMarkers(n,this._markerOwner,r)}}catch(n){console.debug(`Could not set related diagnostics for ${e}:`,n)}}dispose(){this._updateHandle!==void 0&&(clearTimeout(this._updateHandle),this._updateHandle=void 0),super.dispose()}},$It=class{constructor(s,e,i,n){this.server=s,this.bridge=e,this.capabilities=i,this.connection=n}},WIt=class extends Do{constructor(s){super(),ri(this,"_staticCapabilities",new Set),ri(this,"_dynamicFromStatic",zIt.create()),ri(this,"_registrations",new Map),ri(this,"_serverCapabilities"),this._connection=s,this._register(this._connection.registerRequestHandler(v5.client.clientRegisterCapability,async e=>{for(const i of e.registrations){const n=ISe(i.method),r=new TSe(i.id,n,i.registerOptions,!1);this._registerCapabilityOptions(r)}return{ok:null}})),this._register(this._connection.registerRequestHandler(v5.client.clientUnregisterCapability,async e=>{for(const i of e.unregisterations){const n=ISe(i.method),r=this._registrations.get(n),o=r==null?void 0:r.registrations.get(i.id);if(!o)throw new Error(`No registration for method ${i.method} with id ${i.id}`);o==null||o.handlerDisposables.forEach(a=>a.dispose()),r==null||r.registrations.delete(i.id)}return{ok:null}}))}_registerCapabilityOptions(s){let e=this._registrations.get(s.capability);if(e||(e=new NSe,this._registrations.set(s.capability,e)),e.registrations.has(s.id))throw new Error(`Handler for method ${s.capability.method} with id ${s.id} already registered`);e.registrations.set(s.id,s);for(const i of e.handlers)!i.handleStaticCapability&&s.isFromStatic||s.handlerDisposables.set(i,i.handler(s.options))}setServerCapabilities(s){if(this._serverCapabilities)throw new Error("Server capabilities already set");this._serverCapabilities=s;for(const e of Object.values(_n)){const i=this._dynamicFromStatic.getOptions(e,s);i&&this._registerCapabilityOptions(new TSe(e.method,e,i,!0))}}getClientCapabilities(){const s={};for(const e of this._staticCapabilities)r6e(s,e.cap);return s}addStaticClientCapabilities(s){const e={cap:s};return this._staticCapabilities.add(e),{dispose:()=>{this._staticCapabilities.delete(e)}}}registerCapabilityHandler(s,e,i){let n=this._registrations.get(s);n||(n=new NSe,this._registrations.set(s,n));const r=new HIt(s,e,i);n.handlers.add(r);for(const o of n.registrations.values())!r.handleStaticCapability&&o.isFromStatic||o.handlerDisposables.set(r,i(o.options));return{dispose:()=>{n.handlers.delete(r);for(const o of n.registrations.values()){const a=o.handlerDisposables.get(r);a&&(a.dispose(),o.handlerDisposables.delete(r))}}}}},HIt=class{constructor(s,e,i){this.capability=s,this.handleStaticCapability=e,this.handler=i}},TSe=class{constructor(s,e,i,n){ri(this,"handlerDisposables",new Map),this.id=s,this.capability=e,this.options=i,this.isFromStatic=n}};const VIt=new Map([...Object.values(_n)].map(s=>[s.method,s]));function ISe(s){const e=VIt.get(s);if(!e)throw new Error(`No capability found for method ${s}`);return e}var NSe=class{constructor(){ri(this,"handlers",new Set),ri(this,"registrations",new Map)}},zIt=class s6e{constructor(){ri(this,"_mappings",new Map)}static create(){const e=new s6e;return e.set(_n.textDocumentDidChange,i=>{if(i.textDocumentSync!==void 0)return typeof i.textDocumentSync=="object"?{syncKind:i.textDocumentSync.change??mTt.None,documentSelector:null}:{syncKind:i.textDocumentSync,documentSelector:null}}),e.set(_n.textDocumentCompletion,i=>i.completionProvider),e.set(_n.textDocumentHover,i=>i.hoverProvider),e.set(_n.textDocumentSignatureHelp,i=>i.signatureHelpProvider),e.set(_n.textDocumentDefinition,i=>i.definitionProvider),e.set(_n.textDocumentReferences,i=>i.referencesProvider),e.set(_n.textDocumentDocumentHighlight,i=>i.documentHighlightProvider),e.set(_n.textDocumentDocumentSymbol,i=>i.documentSymbolProvider),e.set(_n.textDocumentCodeAction,i=>i.codeActionProvider),e.set(_n.textDocumentCodeLens,i=>i.codeLensProvider),e.set(_n.textDocumentDocumentLink,i=>i.documentLinkProvider),e.set(_n.textDocumentFormatting,i=>i.documentFormattingProvider),e.set(_n.textDocumentRangeFormatting,i=>i.documentRangeFormattingProvider),e.set(_n.textDocumentOnTypeFormatting,i=>i.documentOnTypeFormattingProvider),e.set(_n.textDocumentRename,i=>i.renameProvider),e.set(_n.textDocumentFoldingRange,i=>i.foldingRangeProvider),e.set(_n.textDocumentDeclaration,i=>i.declarationProvider),e.set(_n.textDocumentTypeDefinition,i=>i.typeDefinitionProvider),e.set(_n.textDocumentImplementation,i=>i.implementationProvider),e.set(_n.textDocumentDocumentColor,i=>i.colorProvider),e.set(_n.textDocumentSelectionRange,i=>i.selectionRangeProvider),e.set(_n.textDocumentLinkedEditingRange,i=>i.linkedEditingRangeProvider),e.set(_n.textDocumentPrepareCallHierarchy,i=>i.callHierarchyProvider),e.set(_n.textDocumentSemanticTokensFull,i=>i.semanticTokensProvider),e.set(_n.textDocumentInlayHint,i=>i.inlayHintProvider),e.set(_n.textDocumentInlineValue,i=>i.inlineValueProvider),e.set(_n.textDocumentDiagnostic,i=>i.diagnosticProvider),e.set(_n.textDocumentMoniker,i=>i.monikerProvider),e.set(_n.textDocumentPrepareTypeHierarchy,i=>i.typeHierarchyProvider),e.set(_n.workspaceSymbol,i=>i.workspaceSymbolProvider),e.set(_n.workspaceExecuteCommand,i=>i.executeCommandProvider),e}set(e,i){if(this._mappings.has(e.method))throw new Error(`Capability for method ${e.method} already registered`);this._mappings.set(e.method,i)}getOptions(e,i){const n=this._mappings.get(e.method);if(n)return n(i)}};function r6e(s,e){for(const i of Object.keys(e)){const n=e[i];if(n===void 0)continue;const r=s[i];if(r===void 0){s[i]=n;continue}if(typeof n!="object"||n===null){s[i]=n;continue}if(typeof r!="object"||r===null){s[i]=n;continue}r6e(r,n)}}var UIt=class extends Do{constructor(s,e){super(),ri(this,"_managedModels",new Map),ri(this,"_managedModelsReverse",new Map),ri(this,"_started",!1),this._server=s,this._capabilities=e,this._register(this._capabilities.addStaticClientCapabilities({textDocument:{synchronization:{dynamicRegistration:!0,willSave:!1,willSaveWaitUntil:!1,didSave:!1}}})),this._register(e.registerCapabilityHandler(_n.textDocumentDidChange,!0,i=>{if(this._started)return{dispose:()=>{}};this._started=!0,this._register(D_.onDidCreateModel(n=>{this._getOrCreateManagedModel(n)}));for(const n of D_.getModels())this._getOrCreateManagedModel(n);return{dispose:()=>{}}}))}_getOrCreateManagedModel(s){if(!this._started)throw new Error("Not started");const e=s.uri.toString(!0).toLowerCase();let i=this._managedModels.get(s);return i||(i=new qIt(s,this._server),this._managedModels.set(s,i),this._managedModelsReverse.set(e,s)),s.onWillDispose(()=>{i.dispose(),this._managedModels.delete(s),this._managedModelsReverse.delete(e)}),i}translateBack(s,e){const i=s.uri.toLowerCase(),n=this._managedModelsReverse.get(i);if(!n)throw new Error(`No text model for uri ${i}`);return{textModel:n,position:new Fy(e.line+1,e.character+1)}}translateBackRange(s,e){const i=s.uri.toLowerCase(),n=this._managedModelsReverse.get(i);if(!n)throw new Error(`No text model for uri ${i}`);return{textModel:n,range:new mR(e.start.line+1,e.start.character+1,e.end.line+1,e.end.character+1)}}translate(s,e){return{textDocument:{uri:s.uri.toString(!0)},position:{line:e.lineNumber-1,character:e.column-1}}}translateRange(s,e){return{start:{line:e.startLineNumber-1,character:e.startColumn-1},end:{line:e.endLineNumber-1,character:e.endColumn-1}}}},qIt=class extends Do{constructor(s,e){super(),this._textModel=s,this._api=e;const i=s.uri.toString(!0).toLowerCase();this._api.textDocumentDidOpen({textDocument:{languageId:s.getLanguageId(),uri:i,version:s.getVersionId(),text:s.getValue()}}),this._register(s.onDidChangeContent(n=>{const r=n.changes.map(o=>GIt(o));this._api.textDocumentDidChange({textDocument:{uri:i,version:s.getVersionId()},contentChanges:r})})),this._register({dispose:()=>{this._api.textDocumentDidClose({textDocument:{uri:i}})}})}};function GIt(s){return{range:KIt(s.range),rangeLength:s.rangeLength,text:s.text}}function KIt(s){return{start:{line:s.startLineNumber-1,character:s.startColumn-1},end:{line:s.endLineNumber-1,character:s.endColumn-1}}}var YIt=class{constructor(s){ri(this,"_connection"),ri(this,"_capabilitiesRegistry"),ri(this,"_bridge"),ri(this,"_initPromise");const e=ide.fromTransport(s),i=v5.getServer(e,{});e.startListen(),this._capabilitiesRegistry=new WIt(e),this._bridge=new UIt(i.server,this._capabilitiesRegistry),this._connection=new $It(i.server,this._bridge,this._capabilitiesRegistry,e),this.createFeatures(),this._initPromise=this._init()}async _init(){const s=await this._connection.server.initialize({processId:null,capabilities:this._capabilitiesRegistry.getClientCapabilities(),rootUri:null});this._connection.server.initialized({}),this._capabilitiesRegistry.setServerCapabilities(s.capabilities)}createFeatures(){const s=new wme;return s.add(new zTt(this._connection)),s.add(new KTt(this._connection)),s.add(new ZTt(this._connection)),s.add(new JTt(this._connection)),s.add(new tIt(this._connection)),s.add(new nIt(this._connection)),s.add(new rIt(this._connection)),s.add(new aIt(this._connection)),s.add(new cIt(this._connection)),s.add(new uIt(this._connection)),s.add(new gIt(this._connection)),s.add(new _It(this._connection)),s.add(new bIt(this._connection)),s.add(new wIt(this._connection)),s.add(new CIt(this._connection)),s.add(new kIt(this._connection)),s.add(new EIt(this._connection)),s.add(new TIt(this._connection)),s.add(new NIt(this._connection)),s.add(new AIt(this._connection)),s.add(new OIt(this._connection)),s.add(new BIt(this._connection)),s}},PT=null;typeof WebSocket<"u"?PT=WebSocket:typeof MozWebSocket<"u"?PT=MozWebSocket:typeof global<"u"?PT=global.WebSocket||global.MozWebSocket:typeof window<"u"?PT=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(PT=self.WebSocket||self.MozWebSocket);var XIt=PT;function ZIt(s){return"host"in s?{address:`${s.forceTls?"wss":"ws"}://${s.host}:${s.port}`}:s}var QIt=class ade extends j$e{constructor(e){super(),ri(this,"socket"),ri(this,"errorEmitter",new yme),ri(this,"onError",this.errorEmitter),this.socket=e,e.onmessage=i=>{try{const n=i.data;if(typeof n=="string"){const r=JSON.parse(n);this._dispatchReceivedMessage(r)}else throw new Error("Not supported")}catch(n){this.errorEmitter.fire({error:n})}},e.onclose=i=>{this._onConnectionClosed()}}static connectTo(e){const i=new XIt(ZIt(e).address);return new Promise((n,r)=>{i.onerror=o=>{r(o)},i.onopen=()=>{n(new ade(i))}})}static fromWebSocket(e){return new ade(e)}close(){this.socket.close()}dispose(){this.close()}_sendImpl(e){const i=JSON.stringify(e);return new Promise((n,r)=>{this.socket.send(i,o=>{o?r(o):n()})})}toString(){return`${this.id}@${this.socket.url}`}},o6e=class extends j$e{constructor(s,e=void 0,i=void 0){super(),ri(this,"_windowLike"),ri(this,"_source"),ri(this,"_loadingState"),ri(this,"_disposed",!1),ri(this,"_messageHandler",({data:n,source:r})=>{this._source&&r!==this._source||typeof n=="object"&&n&&this._dispatchReceivedMessage(n)}),this._windowLike=s,this._source=e,this._loadingState=i,this._windowLike.addEventListener("message",this._messageHandler)}async _sendImpl(s){if(this._disposed)throw new Error("Transport is disposed");this._loadingState&&!this._loadingState.loaded&&await this._loadingState.onLoaded,this._windowLike.postMessage(s)}toString(){return`${this.id}@${this._windowLike}`}dispose(){this._disposed||(this._disposed=!0,this._windowLike.removeEventListener("message",this._messageHandler))}};function JIt(s){if(typeof window>"u")throw new Error("call this function from the main browser thread");return new o6e(s)}function e2t(s){if(typeof window>"u")throw new Error("call this function from the main browser thread");return new o6e(s.contentWindow,s.contentWindow,{loaded:window.document.readyState==="complete",onLoaded:new Promise(e=>{window.addEventListener("load",()=>e())})})}const t2t=Object.freeze(Object.defineProperty({__proto__:null,MonacoLspClient:YIt,WebSocketTransport:QIt,createTransportToIFrame:e2t,createTransportToWorker:JIt},Symbol.toStringTag,{value:"Module"}));function i2t(s,e){var n;const i=globalThis.MonacoEnvironment;if(i!=null&&i.createTrustedTypesPolicy)try{return i.createTrustedTypesPolicy(s,e)}catch(r){console.error(r);return}try{return(n=globalThis.trustedTypes)==null?void 0:n.createPolicy(s,e)}catch(r){console.error(r);return}}let aH;typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope"&&globalThis.workerttPolicy!==void 0?aH=globalThis.workerttPolicy:aH=i2t("defaultWorkerFactory",{createScriptURL:s=>s});function n2t(s){const e=s.label,i=globalThis.MonacoEnvironment;if(i){if(typeof i.getWorker=="function")return i.getWorker("workerMain.js",e);if(typeof i.getWorkerUrl=="function"){const n=i.getWorkerUrl("workerMain.js",e);return new Worker(aH?aH.createScriptURL(n):n,{name:e,type:"module"})}}if(s.createWorker)return s.createWorker();throw new Error("You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker")}function s2t(s){const e=Promise.resolve(n2t({label:s.label??"monaco-editor-worker",moduleId:s.moduleId,createWorker:s.createWorker})).then(i=>(i.postMessage("ignore"),i.postMessage(s.createData),i));return D_.createWebWorker({worker:e,host:s.host,keepIdleModels:s.keepIdleModels})}function a6e(){return BDt}const UX=globalThis.MonacoEnvironment;UX!=null&&UX.globalAPI&&(globalThis.monaco=a6e());const aG=a6e();aG.languages.css=y$e;aG.languages.html=S$e;aG.languages.typescript=F$e;aG.languages.json=E$e;const xme=Object.freeze(Object.defineProperty({__proto__:null,CancellationTokenSource:u$e,Emitter:L1,KeyCode:h$e,KeyMod:f$e,MarkerSeverity:pg,MarkerTag:rH,Position:Fy,Range:mR,Selection:g$e,SelectionDirection:p$e,Token:m$e,Uri:iG,createWebWorker:s2t,css:y$e,editor:D_,html:S$e,json:E$e,languages:Bt,lsp:t2t,typescript:F$e},Symbol.toStringTag,{value:"Module"})),RSe=s=>{let e;const i=new Set,n=(d,u)=>{const h=typeof d=="function"?d(e):d;if(!Object.is(h,e)){const f=e;e=u??(typeof h!="object"||h===null)?h:Object.assign({},e,h),i.forEach(g=>g(e,f))}},r=()=>e,l={setState:n,getState:r,getInitialState:()=>c,subscribe:d=>(i.add(d),()=>i.delete(d))},c=e=s(n,r,l);return l},r2t=(s=>s?RSe(s):RSe),o2t=s=>s;function a2t(s,e=o2t){const i=at.useSyncExternalStore(s.subscribe,at.useCallback(()=>e(s.getState()),[s,e]),at.useCallback(()=>e(s.getInitialState()),[s,e]));return at.useDebugValue(i),i}const ASe=s=>{const e=r2t(s),i=n=>a2t(e,n);return Object.assign(i,e),i},Ka=(s=>s?ASe(s):ASe);function im(s){return"'"+s.replace(/'/g,"'\\''")+"'"}const qX=({sessionId:s})=>`claude --dangerously-skip-permissions --session-id ${im(s)}`,MSe=({sessionId:s})=>`claude --session-id ${im(s)}`,l2t=()=>"claude --resume",l6e=[{id:"sm-dangerous",label:"Session Manager (skip perms)",description:"claude --dangerously-skip-permissions in this project",category:"build",cwd:"app-cwd",command:qX},{id:"sm-safe",label:"Session Manager (safe)",description:"claude with normal permission prompts in this project",category:"build",cwd:"app-cwd",command:MSe},{id:"home-dangerous",label:"Home (skip perms)",description:"claude --dangerously-skip-permissions in ~",category:"build",cwd:"home",command:qX},{id:"pick-dangerous",label:"Pick directory (skip perms)…",description:"Choose a folder, launch claude --dangerously-skip-permissions",category:"build",cwd:"pick",command:qX},{id:"pick-safe",label:"Pick directory (safe)…",description:"Choose a folder, launch claude with normal prompts",category:"build",cwd:"pick",command:MSe},{id:"pick-resume",label:"Pick directory + resume…",description:"Choose a folder, then pick a past session to resume",category:"build",cwd:"pick",command:l2t},{id:"pick-shell",label:"Pick directory (shell only)…",description:"Bare interactive shell, no claude auto-launch",category:"build",cwd:"pick",command:null}];let Uf=null;async function c2t(){if(Uf)return Uf;try{const s=await window.api.app.engageRulesPath();if(!s)return Uf=[],Uf;const e=await window.api.config.readJson(s);if(!e.exists||e.parseError||!e.data)return Uf=[],Uf;const i=e.data;if(!i.presets||!Array.isArray(i.presets))return Uf=[],Uf;const n=i.projectPath;return Uf=i.presets.map(r=>({id:r.id,label:r.label,description:r.description,category:"engage",cwd:n,platform:r.platform,pipeline:r.pipeline,rules:r.rules,command:()=>`cd ${im(n)} && ${r.cliEntry}`})),Uf}catch(s){return console.warn("[presets] Failed to load engage presets:",s),Uf=[],Uf}}async function c6e(s){const e=l6e.find(n=>n.id===s);return e||((await c2t()).find(n=>n.id===s)??null)}async function d2t(s){return s.cwd==="app-cwd"?window.api.app.cwd():s.cwd==="home"?window.api.app.homeDir():s.cwd==="pick"?window.api.app.pickDirectory():s.cwd}function d6e(s,e){return s.command?s.command(e):null}function u2t(s){const e=s.split("/").filter(Boolean);return e[e.length-1]||s}const hn=Ka((s,e)=>({tabs:[],activeTabId:null,hydrated:!1,addTab:({id:i,cwd:n,startupCommand:r,presetId:o=null,label:a})=>{const l=i??crypto.randomUUID();if(e().tabs.find(u=>u.id===l))return s({activeTabId:l}),l;const d={id:l,claudeSessionId:l,label:a??u2t(n),cwd:n,pid:null,status:"spawning",exitCode:null,startupCommand:r,presetId:o,generation:0};return s({tabs:[...e().tabs,d],activeTabId:l}),l},setTabRunning:(i,n)=>s({tabs:e().tabs.map(r=>r.id===i?{...r,pid:n,status:"running"}:r)}),setTabExited:(i,n)=>s({tabs:e().tabs.map(r=>r.id===i?{...r,status:"exited",exitCode:n}:r)}),closeTab:i=>{var o;window.api.pty.kill(i),window.api.watchers.killTab(i).catch(()=>{});const n=e().tabs.filter(a=>a.id!==i),r=e().activeTabId===i?((o=n[n.length-1])==null?void 0:o.id)??null:e().activeTabId;s({tabs:n,activeTabId:r})},setActive:i=>s({activeTabId:i}),restartTab:i=>{const n=e().tabs.find(a=>a.id===i);if(!n)return;window.api.pty.kill(i);const r=crypto.randomUUID(),o=a=>{s({tabs:e().tabs.map(l=>l.id===i?{...l,claudeSessionId:r,pid:null,status:"spawning",exitCode:null,startupCommand:a,generation:l.generation+1}:l)})};n.presetId?c6e(n.presetId).then(a=>{o(a?d6e(a,{sessionId:r,cwd:n.cwd}):`claude --dangerously-skip-permissions --session-id ${im(r)}`)}):o(`claude --dangerously-skip-permissions --session-id ${im(r)}`)},reorderTab:(i,n)=>{const r=[...e().tabs];if(i<0||i>=r.length||n<0||n>=r.length||i===n)return;const[o]=r.splice(i,1);r.splice(n,0,o),s({tabs:r})},restoreTabs:(i,n)=>s({tabs:i,activeTabId:n,hydrated:!0})}));async function u6e(){var i;if(hn.getState().hydrated)return;try{const{tabs:n,activeTabId:r,freshStart:o}=await window.api.sessions.load();if(n.length>0){const a=await Promise.all(n.map(async c=>{let d=!o;if(d){const h=await window.api.transcripts.pathFor(c.cwd,c.claudeSessionId);d=await window.api.config.exists(h)}const u=d?c.claudeSessionId:crypto.randomUUID();return{id:c.id,claudeSessionId:u,cwd:c.cwd,label:c.label,presetId:c.presetId,pid:null,status:"spawning",exitCode:null,startupCommand:d?`claude --dangerously-skip-permissions --resume ${im(u)}`:`claude --dangerously-skip-permissions --session-id ${im(u)}`,generation:0}})),l=r&&a.find(c=>c.id===r)?r:((i=a[0])==null?void 0:i.id)??null;hn.getState().restoreTabs(a,l)}else hn.setState({hydrated:!0})}catch(n){console.warn("[sessions] hydrate failed:",n),hn.setState({hydrated:!0})}const s=()=>{const{tabs:n,activeTabId:r}=hn.getState(),o=n.map(a=>({id:a.id,claudeSessionId:a.claudeSessionId,cwd:a.cwd,label:a.label,presetId:a.presetId}));window.api.sessions.save({tabs:o,activeTabId:r}).catch(a=>{console.warn("[sessions] save failed:",a)})};let e=null;hn.subscribe((n,r)=>{n.hydrated&&(n.tabs===r.tabs&&n.activeTabId===r.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(s,200)))}),s()}const h2t=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:u6e,useSessions:hn},Symbol.toStringTag,{value:"Module"})),f2t=5,PSe=100,g2t=5e3,lde=new Map;function OSe(s){const e=lde.get(s);e!==void 0&&(clearTimeout(e),lde.delete(s))}function p2t(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`t-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}const s2=Ka((s,e)=>({toasts:[],history:[],unreadCount:0,show:(i,n)=>{const r=p2t(),o=Date.now();s(l=>{const c=[...l.toasts,{id:r,kind:i,message:n,createdAt:o}];for(;c.length>f2t;){const h=c.shift();h&&OSe(h.id)}const u=[{id:r,kind:i,message:n,createdAt:o,read:!1},...l.history];return u.length>PSe&&(u.length=PSe),{toasts:c,history:u,unreadCount:l.unreadCount+1}});const a=setTimeout(()=>e().dismiss(r),g2t);return lde.set(r,a),r},dismiss:i=>{OSe(i),s(n=>({toasts:n.toasts.filter(r=>r.id!==i)}))},markAllRead:()=>{s(i=>i.unreadCount===0?i:{history:i.history.map(n=>n.read?n:{...n,read:!0}),unreadCount:0})},clearHistory:()=>{s({history:[],unreadCount:0})},dismissHistoryEntry:i=>{s(n=>{const r=n.history.filter(a=>a.id!==i);if(r.length===n.history.length)return n;const o=n.history.find(a=>a.id===i&&!a.read);return{history:r,unreadCount:o?Math.max(0,n.unreadCount-1):n.unreadCount}})}})),Kt={info:s=>s2.getState().show("info",s),warn:s=>s2.getState().show("warn",s),error:s=>s2.getState().show("error",s)},h6e=Object.freeze(Object.defineProperty({__proto__:null,toast:Kt,useToast:s2},Symbol.toStringTag,{value:"Module"})),FSe=200,m2t=/\x1b\[[0-9;]*m/g;function _2t(s){return s.replace(m2t,"")}const GO=Ka((s,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(s({initialized:!0}),window.api.watchers.onLine(i=>e().ingestLine(i)),window.api.watchers.onClosed(({watcherId:i})=>e().closed(i)))},add:async({tabId:i,label:n,command:r,cwd:o})=>{try{const a=await window.api.watchers.add({tabId:i,label:n,command:r,cwd:o??null}),l={watcherId:a.watcherId,tabId:a.tabId,label:a.label,command:a.command,cwd:a.cwd,pid:a.pid,startedAt:a.startedAt,lineCount:0,lines:[],lastLineAt:null};return s({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(a){return console.error("[watchers] add failed:",a),Kt.error("Failed to add watcher"),null}},remove:async i=>{try{await window.api.watchers.remove(i)}catch(r){console.error("[watchers] remove failed:",r);const o=r instanceof Error?r.message:String(r);Kt.error(`Could not remove watcher: ${o}`)}const n={...e().watchers};delete n[i],s({watchers:n})},watchersForTab:i=>Object.values(e().watchers).filter(n=>n.tabId===i),ingestLine:i=>{const n=e().watchers[i.watcherId];if(!n)return;const r=_2t(i.line),o=n.lines.length>=FSe?[...n.lines.slice(n.lines.length-FSe+1),{line:r,ts:i.ts}]:[...n.lines,{line:r,ts:i.ts}];s({watchers:{...e().watchers,[i.watcherId]:{...n,lines:o,lineCount:n.lineCount+1,lastLineAt:i.ts}}})},closed:i=>{if(!e().watchers[i])return;const n={...e().watchers};delete n[i],s({watchers:n})}})),v2t=4,BSe=40,jSe=6;function b2t(s){const{onReorder:e,onActivate:i}=s,n=z.useRef(null),r=z.useRef(null),o=z.useRef(0),a=z.useRef(0),[l,c]=z.useState(!1),[,d]=z.useState(0),u=z.useRef(i);u.current=i;const h=z.useCallback(()=>n.current?Array.from(n.current.querySelectorAll("[data-drag-index]")):[],[]),f=z.useCallback((m,b,y)=>{for(let x=0;x<b.length;x++){const S=b[x].left+b[x].width/2;if(m<S)return x<=y?x:x-1}return b.length-1},[]),g=z.useCallback(()=>{const m=r.current,b=n.current;if(!(m!=null&&m.active)||!b)return;const y=b.getBoundingClientRect(),x=m.startX+m.deltaX,S=x-y.left,k=y.right-x;S<BSe?b.scrollLeft-=jSe:k<BSe&&(b.scrollLeft+=jSe),o.current=requestAnimationFrame(g)},[]);z.useEffect(()=>{const m=n.current;if(!m)return;let b=!1;const y=()=>{b||(b=!0,a.current=requestAnimationFrame(()=>{b=!1,d(k=>k+1)}))},x=k=>{var O;const D=r.current;if(!D)return;const T=k.clientX-D.startX;if(!D.active&&Math.abs(T)<v2t)return;if(!D.active){D.active=!0,D.tabRects=h().map($=>$.getBoundingClientRect()),c(!0);try{(O=n.current)==null||O.setPointerCapture(D.pointerId)}catch{}o.current=requestAnimationFrame(g)}D.deltaX=T;const N=D.tabRects[D.fromIndex],A=N.left+N.width/2+T;D.currentIndex=f(A,D.tabRects,D.fromIndex),y()},S=k=>{const D=r.current;if(D&&D.pointerId===k.pointerId){cancelAnimationFrame(o.current),cancelAnimationFrame(a.current);try{m.releasePointerCapture(D.pointerId)}catch{}D.active&&D.fromIndex!==D.currentIndex?e(D.fromIndex,D.currentIndex):u.current(D.fromIndex),r.current=null,c(!1),d(T=>T+1)}};return m.addEventListener("pointermove",x),m.addEventListener("pointerup",S),m.addEventListener("pointercancel",S),()=>{m.removeEventListener("pointermove",x),m.removeEventListener("pointerup",S),m.removeEventListener("pointercancel",S),cancelAnimationFrame(o.current),cancelAnimationFrame(a.current)}},[e,h,f,g]);const p=z.useCallback((m,b)=>{m.button!==0||m.target.closest("button")||(r.current={active:!1,fromIndex:b,currentIndex:b,startX:m.clientX,deltaX:0,tabRects:[],pointerId:m.pointerId})},[]);return{getTabDragProps:z.useCallback(m=>{var x;const b=r.current,y={};if(b!=null&&b.active)if(m===b.fromIndex)y.transform=`translateX(${b.deltaX}px) scale(1.03)`,y.zIndex=10,y.opacity=.85,y.boxShadow="0 2px 8px rgba(0,0,0,0.4)",y.position="relative",y.pointerEvents="none";else{const S=b.fromIndex,k=b.currentIndex,T=(((x=b.tabRects[S])==null?void 0:x.width)??0)+4;y.transition="transform 0.15s ease",S<k&&m>S&&m<=k?y.transform=`translateX(-${T}px)`:S>k&&m>=k&&m<S?y.transform=`translateX(${T}px)`:y.transform="translateX(0)"}return{onPointerDown:S=>p(S,m),style:y,"data-drag-index":m}},[p]),isDragging:l,containerRef:n}}const y2t=3e4;function w2t(){const s=hn(g=>g.tabs),e=hn(g=>g.activeTabId),i=hn(g=>g.closeTab),n=hn(g=>g.setActive),r=hn(g=>g.reorderTab),o=GO(g=>g.watchers),[a,l]=z.useState(()=>Date.now());z.useEffect(()=>{const g=window.setInterval(()=>l(Date.now()),1e3);return()=>window.clearInterval(g)},[]);const c=g=>{for(const p of Object.values(o))if(p.tabId===g&&p.lastLineAt&&a-p.lastLineAt<y2t)return!0;return!1},{getTabDragProps:d,isDragging:u,containerRef:h}=b2t({tabCount:s.length,onReorder:r,onActivate:g=>{const p=s[g];p&&n(p.id)}}),f=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return v.jsxs("div",{className:"h-11 bg-bg-elev border-b border-line flex items-end px-3 gap-0 shrink-0 relative","data-testid":"tour-tabbar",children:[v.jsx("div",{ref:h,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${u?"cursor-grabbing":""}`,children:s.map((g,p)=>{const _=g.id===e,m=d(p),b=f[p%f.length];return v.jsxs("div",{...m,style:m.style,className:`group flex items-center gap-2 px-3.5 pt-1.5 pb-2 rounded-t-[10px] text-[13px] shrink-0 transition-colors ${u?"":"cursor-grab"} ${_?"bg-bg text-fg font-medium relative z-10 -mb-px border border-b-0 border-line":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,title:g.cwd,"aria-current":_?"true":void 0,children:[v.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:b,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:g.status==="spawning"?.55:1}}),v.jsx("span",{className:"truncate max-w-[200px]",children:g.label}),g.status==="spawning"&&v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),c(g.id)&&v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"watcher emitted a line in the last 30s","data-testid":"tab-watcher-dot"}),v.jsx("button",{onClick:y=>{y.stopPropagation(),i(g.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${g.label}`,children:"×"})]},g.id)})}),v.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[v.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),v.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.21.0"]})]})]})}function x2t(s,e,i){return e?s.map(n=>n.id===e?{...n,lastActivityAt:i}:n):s}function C2t(s,e,i){return{tabId:s,sessionUuid:i,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const k8=Ka((s,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(i,n,r)=>{const o={...e().refs};if(o[i]=(o[i]??0)+1,s({refs:o}),o[i]>1)return;s({tabs:{...e().tabs,[i]:C2t(i,n,r)}});const a=window.api.transcripts.onEvent(i,l=>e().ingest(i,l));s({unsubs:{...e().unsubs,[i]:a}}),window.api.transcripts.subscribe({tabId:i,cwd:n,sessionUuid:r}).then(async l=>{const c=e().tabs[i];if(!c)return;if(!l.ok){const{toast:u}=await ei(async()=>{const{toast:h}=await Promise.resolve().then(()=>h6e);return{toast:h}},void 0,import.meta.url);u.error(`Live view unavailable: ${l.error??"subscribe failed"}`),s({tabs:{...e().tabs,[i]:{...c,path:null}}});return}s({tabs:{...e().tabs,[i]:{...c,path:l.path}}});const d=await window.api.transcripts.buffer(i);for(const u of d)e().ingest(i,u,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",i,l))},unsubscribe:i=>{const n={...e().refs};if(!n[i])return;if(n[i]--,n[i]>0){s({refs:n});return}delete n[i];const r=e().unsubs[i];r==null||r();const o={...e().unsubs};delete o[i];const a={...e().tabs};delete a[i],window.api.transcripts.unsubscribe(i),s({refs:n,unsubs:o,tabs:a})},ingest:(i,n,r)=>{const o=e().tabs[i];if(!o)return;const a=Date.now(),l={...o,lastEventAt:r!=null&&r.replay?o.lastEventAt:a},c=[],d=(u,h)=>u.length>h?u.slice(0,h-1)+"…":u;switch(n.kind){case"todo_write":{const u=Array.isArray(n.data)?n.data:[];l.todos=u,r!=null&&r.replay||c.push({id:0,kind:"todo-update",at:a,label:`Todos · ${u.length} item${u.length!==1?"s":""}`});break}case"tool_use":{const u=n.data;if(l.lastToolUses=[{id:u.id,name:u.name,input:u.input,at:a},...o.lastToolUses].slice(0,50),!(r!=null&&r.replay)){const h=u.input,f=["Edit","Write","NotebookEdit"].includes(u.name),g=typeof(h==null?void 0:h.file_path)=="string"?h.file_path:void 0,p=typeof(h==null?void 0:h.command)=="string"?h.command:void 0,_=g?g.split("/").pop()??g:p?d(p,28):"";c.push({id:0,kind:"tool-use",at:a,label:_?`${u.name} · ${_}`:u.name,target:g??p,toolName:u.name}),f&&g&&c.push({id:0,kind:"file-edit",at:a,label:`${u.name} · ${d(g.split("/").pop()??g,34)}`,target:g,toolName:u.name})}break}case"plan":{const u=n.data,h=typeof u=="string"?u:(u==null?void 0:u.plan)??JSON.stringify(u);l.plans=[{at:a,content:h??""},...o.plans].slice(0,50),r!=null&&r.replay||c.push({id:0,kind:"plan-revision",at:a,label:"Plan revised"});break}case"agent_spawn":{const u=n.data;l.agents=[{id:u==null?void 0:u.toolUseId,at:a,subagentType:u==null?void 0:u.subagent_type,description:u==null?void 0:u.description,lastActivityAt:a},...o.agents].slice(0,50),r!=null&&r.replay||c.push({id:0,kind:"agent-spawn",at:a,label:u!=null&&u.subagent_type?`Agent: ${d(u.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const u=n.data,h=(o.usage.inputTokens||0)+(o.usage.outputTokens||0),f=u.input_tokens??u.inputTokens??0,g=u.output_tokens??u.outputTokens??0,p=h+f+g;l.usage={inputTokens:(o.usage.inputTokens||0)+f,outputTokens:(o.usage.outputTokens||0)+g,cacheCreationInputTokens:(o.usage.cacheCreationInputTokens||0)+(u.cache_creation_input_tokens??u.cacheCreationInputTokens??0),cacheReadInputTokens:(o.usage.cacheReadInputTokens||0)+(u.cache_read_input_tokens??u.cacheReadInputTokens??0)},!(r!=null&&r.replay)&&Math.floor(p/1e3)>Math.floor(h/1e3)&&c.push({id:0,kind:"usage-tick",at:a,label:`${Math.floor(p/1e3)}k tokens`});break}case"tool_result":{const u=n.data;l.agents=x2t(o.agents,u==null?void 0:u.toolUseId,a);break}}if(c.length>0){let u=o.activitySeq;const h=c.map(f=>({...f,id:++u}));l.activitySeq=u,l.activityRing=[...o.activityRing,...h].slice(-32)}s({tabs:{...e().tabs,[i]:l}})}}));function KF(s){const e=k8(r=>r.subscribe),i=k8(r=>r.unsubscribe),n=k8(r=>s?r.tabs[s.id]:void 0);return z.useEffect(()=>{if(s)return e(s.id,s.cwd,s.claudeSessionId),()=>i(s.id)},[s==null?void 0:s.id,s==null?void 0:s.cwd,s==null?void 0:s.claudeSessionId,e,i]),n}var GX={},$M={},$Se;function f6e(){if($Se)return $M;$Se=1,Object.defineProperty($M,"__esModule",{value:!0}),$M.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let i="/";return e&&(i=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),$M.baseAssetPath=i,$M}var WM={},WSe;function Cme(){if(WSe)return WM;WSe=1,Object.defineProperty(WM,"__esModule",{value:!0}),WM.defaultModelFetcher=void 0;const s=e=>fetch(e).then(i=>i.arrayBuffer());return WM.defaultModelFetcher=s,WM}var jv={},HM={},HSe;function YF(){if(HSe)return HM;HSe=1,Object.defineProperty(HM,"__esModule",{value:!0}),HM.log=void 0;const s=e=>i=>{console.log(`VAD | ${e} >`,i)};return HM.log={error:s("error"),debug:s("debug"),warn:s("warn")},HM}var VM={},VSe;function lG(){if(VSe)return VM;VSe=1,Object.defineProperty(VM,"__esModule",{value:!0}),VM.Message=void 0;var s;return(function(e){e.AudioFrame="AUDIO_FRAME",e.SpeechStart="SPEECH_START",e.VADMisfire="VAD_MISFIRE",e.SpeechEnd="SPEECH_END",e.SpeechStop="SPEECH_STOP",e.SpeechRealStart="SPEECH_REAL_START",e.FrameProcessed="FRAME_PROCESSED"})(s||(VM.Message=s={})),VM}var zSe;function Sme(){if(zSe)return jv;zSe=1,Object.defineProperty(jv,"__esModule",{value:!0}),jv.FrameProcessor=jv.validateOptions=jv.defaultFrameProcessorOptions=void 0;const s=YF(),e=lG();jv.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function i(a){(a.positiveSpeechThreshold<0||a.positiveSpeechThreshold>1)&&s.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(a.negativeSpeechThreshold<0||a.negativeSpeechThreshold>a.positiveSpeechThreshold)&&s.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),a.preSpeechPadMs<0&&s.log.error("preSpeechPadMs should be positive"),a.redemptionMs<0&&s.log.error("redemptionMs should be positive"),a.minSpeechMs<0&&s.log.error("minSpeechMs should be positive")}jv.validateOptions=i;const n=a=>{const l=a.reduce((d,u)=>(d.push(d.at(-1)+u.length),d),[0]),c=new Float32Array(l.at(-1));return a.forEach((d,u)=>{const h=l[u];c.set(d,h)}),c};function r(a,l){const c=Math.floor(a.redemptionMs/l),d=Math.floor(a.preSpeechPadMs/l),u=Math.floor(a.minSpeechMs/l);return{redemptionFrames:c,preSpeechPadFrames:d,minSpeechFrames:u}}class o{constructor(l,c,d,u){this.modelProcessFunc=l,this.modelResetFunc=c,this.options=d,this.msPerFrame=u,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=p=>{this.options={...this.options,...p};const{redemptionFrames:_,preSpeechPadFrames:m,minSpeechFrames:b}=r(this.options,this.msPerFrame);this.redemptionFrames=_,this.preSpeechPadFrames=m,this.minSpeechFrames=b},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=p=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(p):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=p=>{const _=this.audioBuffer;this.audioBuffer=[];const m=this.speaking;if(this.reset(),m)if(_.reduce((y,x)=>x.isSpeech?y+1:y,0)>=this.minSpeechFrames){const y=n(_.map(x=>x.frame));p({msg:e.Message.SpeechEnd,audio:y})}else p({msg:e.Message.VADMisfire});return{}},this.process=async(p,_)=>{if(!this.active)return;const m=await this.modelProcessFunc(p),b=m.isSpeech>=this.options.positiveSpeechThreshold;if(_({probs:m,msg:e.Message.FrameProcessed,frame:p}),this.audioBuffer.push({frame:p,isSpeech:b}),b&&(this.speechFrameCount++,this.redemptionCounter=0),b&&!this.speaking&&(this.speaking=!0,_({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,_({msg:e.Message.SpeechRealStart})),m.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const y=this.audioBuffer;if(this.audioBuffer=[],y.reduce((S,k)=>k.isSpeech?S+1:S,0)>=this.minSpeechFrames){const S=n(y.map(k=>k.frame));_({msg:e.Message.SpeechEnd,audio:S})}else _({msg:e.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:h,preSpeechPadFrames:f,minSpeechFrames:g}=r(this.options,this.msPerFrame);this.redemptionFrames=h,this.preSpeechPadFrames=f,this.minSpeechFrames=g,this.reset()}}return jv.FrameProcessor=o,jv}var $v={};function ug(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var KX={exports:{}};/*!
|
|
957
|
+
\`\`\``,isTrusted:!0}}var ZTt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{signatureHelp:{dynamicRegistration:!0,contextSupport:!0,signatureInformation:{documentationFormat:[oH.Markdown,oH.PlainText],parameterInformation:{labelOffsetSupport:!0},activeParameterSupport:!0}}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentSignatureHelp,!0,e=>Bt.registerSignatureHelpProvider(Ga(e.documentSelector),new QTt(this._connection,e))))}},QTt=class{constructor(s,e){ri(this,"signatureHelpTriggerCharacters"),ri(this,"signatureHelpRetriggerCharacters"),this._client=s,this._capabilities=e,this.signatureHelpTriggerCharacters=e.triggerCharacters,this.signatureHelpRetriggerCharacters=e.retriggerCharacters}async provideSignatureHelp(s,e,i,n){const r=this._client.bridge.translate(s,e),o=await this._client.server.textDocumentSignatureHelp({textDocument:r.textDocument,position:r.position,context:{triggerKind:$Tt(n.triggerKind),triggerCharacter:n.triggerCharacter,isRetrigger:n.isRetrigger}});return o?{value:{signatures:o.signatures.map(a=>{var l;return{label:a.label,documentation:LSe(a.documentation),parameters:((l=a.parameters)==null?void 0:l.map(c=>({label:c.label,documentation:LSe(c.documentation)})))||[],activeParameter:a.activeParameter}}),activeSignature:o.activeSignature||0,activeParameter:o.activeParameter||0},dispose:()=>{}}:null}};function LSe(s){if(s)return typeof s=="string"?s:{value:s.value,isTrusted:!0}}var JTt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{definition:{dynamicRegistration:!0,linkSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDefinition,!0,e=>Bt.registerDefinitionProvider(Ga(e.documentSelector),new eIt(this._connection,e))))}},eIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDefinition(s,e,i){const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentDefinition({textDocument:n.textDocument,position:n.position});return r?Array.isArray(r)?r.map(o=>E1(o,this._client)):E1(r,this._client):null}},tIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{declaration:{dynamicRegistration:!0,linkSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDeclaration,!0,e=>Bt.registerDeclarationProvider(Ga(e.documentSelector),new iIt(this._connection,e))))}},iIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDeclaration(s,e,i){const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentDeclaration({textDocument:n.textDocument,position:n.position});return r?Array.isArray(r)?r.map(o=>E1(o,this._client)):E1(r,this._client):null}},nIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{typeDefinition:{dynamicRegistration:!0,linkSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentTypeDefinition,!0,e=>Bt.registerTypeDefinitionProvider(Ga(e.documentSelector),new sIt(this._connection,e))))}},sIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideTypeDefinition(s,e,i){const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentTypeDefinition({textDocument:n.textDocument,position:n.position});return r?Array.isArray(r)?r.map(o=>E1(o,this._client)):E1(r,this._client):null}},rIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{implementation:{dynamicRegistration:!0,linkSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentImplementation,!0,e=>Bt.registerImplementationProvider(Ga(e.documentSelector),new oIt(this._connection,e))))}},oIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideImplementation(s,e,i){const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentImplementation({textDocument:n.textDocument,position:n.position});return r?Array.isArray(r)?r.map(o=>E1(o,this._client)):E1(r,this._client):null}},aIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{references:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentReferences,!0,e=>Bt.registerReferenceProvider(Ga(e.documentSelector),new lIt(this._connection,e))))}},lIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideReferences(s,e,i,n){const r=this._client.bridge.translate(s,e),o=await this._client.server.textDocumentReferences({textDocument:r.textDocument,position:r.position,context:{includeDeclaration:i.includeDeclaration}});return o?o.map(a=>{const l=this._client.bridge.translateBackRange({uri:a.uri},a.range);return{uri:l.textModel.uri,range:l.range}}):null}},cIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{documentHighlight:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDocumentHighlight,!0,e=>Bt.registerDocumentHighlightProvider(Ga(e.documentSelector),new dIt(this._connection,e))))}},dIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDocumentHighlights(s,e,i){const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentDocumentHighlight({textDocument:n.textDocument,position:n.position});return r?r.map(o=>({range:this._client.bridge.translateBackRange(n.textDocument,o.range).range,kind:NTt(o.kind)})):null}},uIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{documentSymbol:{dynamicRegistration:!0,hierarchicalDocumentSymbolSupport:!0,symbolKind:{valueSet:Array.from(Q$e.keys())},tagSupport:{valueSet:[K$e.Deprecated]}}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDocumentSymbol,!0,e=>Bt.registerDocumentSymbolProvider(Ga(e.documentSelector),new hIt(this._connection,e))))}},hIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDocumentSymbols(s,e){const i=this._client.bridge.translate(s,new Fy(1,1)),n=await this._client.server.textDocumentDocumentSymbol({textDocument:i.textDocument});return n?Array.isArray(n)&&n.length>0?"location"in n[0]?n.map(r=>fIt(r,this._client)):n.map(r=>n6e(r,this._client,i.textDocument)):[]:null}};function n6e(s,e,i){var n,r;return{name:s.name,detail:s.detail||"",kind:J$e(s.kind),tags:((n=s.tags)==null?void 0:n.map(o=>e6e(o)).filter(o=>o!==void 0))||[],range:e.bridge.translateBackRange(i,s.range).range,selectionRange:e.bridge.translateBackRange(i,s.selectionRange).range,children:((r=s.children)==null?void 0:r.map(o=>n6e(o,e,i)))||[]}}function fIt(s,e){var i;return{name:s.name,detail:"",kind:J$e(s.kind),tags:((i=s.tags)==null?void 0:i.map(n=>e6e(n)).filter(n=>n!==void 0))||[],range:e.bridge.translateBackRange({uri:s.location.uri},s.location.range).range,selectionRange:e.bridge.translateBackRange({uri:s.location.uri},s.location.range).range,children:[]}}var gIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{rename:{dynamicRegistration:!0,prepareSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentRename,!0,e=>Bt.registerRenameProvider(Ga(e.documentSelector),new pIt(this._connection,e))))}},pIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideRenameEdits(s,e,i,n){const r=this._client.bridge.translate(s,e),o=await this._client.server.textDocumentRename({textDocument:r.textDocument,position:r.position,newName:i});return o?mIt(o,this._client):null}async resolveRenameLocation(s,e,i){if(!this._capabilities.prepareProvider)return null;const n=this._client.bridge.translate(s,e),r=await this._client.server.textDocumentPrepareRename({textDocument:n.textDocument,position:n.position});if(!r)return null;if("range"in r&&"placeholder"in r)return{range:this._client.bridge.translateBackRange(n.textDocument,r.range).range,text:r.placeholder};if("defaultBehavior"in r)return null;if("start"in r&&"end"in r){const o=this._client.bridge.translateBackRange(n.textDocument,r).range;return{range:o,text:s.getValueInRange(o)}}return null}};function mIt(s,e){const i=[];if(s.changes)for(const n in s.changes){const r=s.changes[n];for(const o of r){const a=e.bridge.translateBackRange({uri:n},o.range);i.push({resource:a.textModel.uri,versionId:void 0,textEdit:{range:a.range,text:o.newText}})}}if(s.documentChanges){for(const n of s.documentChanges)if("textDocument"in n){const r=n.textDocument.uri;for(const o of n.edits){const a=e.bridge.translateBackRange({uri:r},o.range);i.push({resource:a.textModel.uri,versionId:n.textDocument.version,textEdit:{range:a.range,text:o.newText}})}}}return{edits:i}}var _It=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{codeAction:{dynamicRegistration:!0,codeActionLiteralSupport:{codeActionKind:{valueSet:Array.from(Y$e.keys())}},isPreferredSupport:!0,disabledSupport:!0,dataSupport:!0,resolveSupport:{properties:["edit"]}}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentCodeAction,!0,e=>Bt.registerCodeActionProvider(Ga(e.documentSelector),new vIt(this._connection,e))))}},vIt=class{constructor(s,e){ri(this,"resolveCodeAction"),this._client=s,this._capabilities=e,e.resolveProvider&&(this.resolveCodeAction=async(i,n)=>{if(i._lspAction){const r=await this._client.server.codeActionResolve(i._lspAction);r.edit&&(i.edit=ESe(r.edit,this._client)),r.command&&(i.command=n2(r.command))}return i})}async provideCodeActions(s,e,i,n){const r=this._client.bridge.translate(s,e.getStartPosition()),o=await this._client.server.textDocumentCodeAction({textDocument:r.textDocument,range:this._client.bridge.translateRange(s,e),context:{diagnostics:i.markers.map(a=>({range:this._client.bridge.translateRange(s,mR.lift(a)),message:a.message,severity:PTt(a.severity)})),triggerKind:xTt(i.trigger)}});return o?{actions:(Array.isArray(o)?o:[o]).map(a=>{var l;if("title"in a&&!("kind"in a)){const c=a;return{title:c.title,command:n2(c)}}else{const c=a;return{title:c.title,kind:yTt(c.kind),isPreferred:c.isPreferred,disabled:(l=c.disabled)==null?void 0:l.reason,edit:c.edit?ESe(c.edit,this._client):void 0,command:n2(c.command),_lspAction:c}}}),dispose:()=>{}}:null}};function ESe(s,e){const i=[];if(s.changes)for(const n in s.changes){const r=s.changes[n];for(const o of r){const a=e.bridge.translateBackRange({uri:n},o.range);i.push({resource:a.textModel.uri,versionId:void 0,textEdit:{range:a.range,text:o.newText}})}}if(s.documentChanges){for(const n of s.documentChanges)if("textDocument"in n){const r=n.textDocument.uri;for(const o of n.edits){const a=e.bridge.translateBackRange({uri:r},o.range);i.push({resource:a.textModel.uri,versionId:n.textDocument.version??void 0,textEdit:{range:a.range,text:o.newText}})}}}return{edits:i}}var bIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{codeLens:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentCodeLens,!0,e=>Bt.registerCodeLensProvider(Ga(e.documentSelector),new yIt(this._connection,e))))}},yIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideCodeLenses(s,e){const i=this._client.bridge.translate(s,new Fy(1,1)),n=await this._client.server.textDocumentCodeLens({textDocument:i.textDocument});return n?{lenses:n.map(r=>({range:$S(this._client.bridge.translateBackRange(i.textDocument,r.range),s).range,command:n2(r.command),_lspCodeLens:r})),dispose:()=>{}}:null}async resolveCodeLens(s,e,i){if(!this._capabilities.resolveProvider||!e._lspCodeLens)return e;const n=await this._client.server.codeLensResolve(e._lspCodeLens);return n.command&&(e.command={id:n.command.command,title:n.command.title,arguments:n.command.arguments}),e}},wIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{documentLink:{dynamicRegistration:!0,tooltipSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDocumentLink,!0,e=>Bt.registerLinkProvider(Ga(e.documentSelector),new xIt(this._connection,e))))}},xIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideLinks(s,e){const i=this._client.bridge.translate(s,new Fy(1,1)),n=await this._client.server.textDocumentDocumentLink({textDocument:i.textDocument});return n?{links:n.map(r=>({range:this._client.bridge.translateBackRange(i.textDocument,r.range).range,url:r.target,tooltip:r.tooltip}))}:null}async resolveLink(s,e){return this._capabilities.resolveProvider,s}},CIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{formatting:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentFormatting,!0,e=>Bt.registerDocumentFormattingEditProvider(Ga(e.documentSelector),new SIt(this._connection,e))))}},SIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDocumentFormattingEdits(s,e,i){const n=this._client.bridge.translate(s,new Fy(1,1)),r=await this._client.server.textDocumentFormatting({textDocument:n.textDocument,options:{tabSize:e.tabSize,insertSpaces:e.insertSpaces}});return r?r.map(o=>({range:this._client.bridge.translateBackRange(n.textDocument,o.range).range,text:o.newText})):null}},kIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{rangeFormatting:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentRangeFormatting,!0,e=>Bt.registerDocumentRangeFormattingEditProvider(Ga(e.documentSelector),new LIt(this._connection,e))))}},LIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideDocumentRangeFormattingEdits(s,e,i,n){const r=this._client.bridge.translate(s,e.getStartPosition()),o=await this._client.server.textDocumentRangeFormatting({textDocument:r.textDocument,range:this._client.bridge.translateRange(s,e),options:{tabSize:i.tabSize,insertSpaces:i.insertSpaces}});return o?o.map(a=>({range:this._client.bridge.translateBackRange(r.textDocument,a.range).range,text:a.newText})):null}},EIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{onTypeFormatting:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentOnTypeFormatting,!0,e=>Bt.registerOnTypeFormattingEditProvider(Ga(e.documentSelector),new DIt(this._connection,e))))}},DIt=class{constructor(s,e){ri(this,"autoFormatTriggerCharacters"),this._client=s,this._capabilities=e,this.autoFormatTriggerCharacters=[e.firstTriggerCharacter,...e.moreTriggerCharacter||[]]}async provideOnTypeFormattingEdits(s,e,i,n,r){const o=this._client.bridge.translate(s,e),a=await this._client.server.textDocumentOnTypeFormatting({textDocument:o.textDocument,position:o.position,ch:i,options:{tabSize:n.tabSize,insertSpaces:n.insertSpaces}});return a?a.map(l=>({range:this._client.bridge.translateBackRange(o.textDocument,l.range).range,text:l.newText})):null}},TIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{foldingRange:{dynamicRegistration:!0,rangeLimit:5e3,lineFoldingOnly:!1,foldingRangeKind:{valueSet:[i2.Comment,i2.Imports,i2.Region]}}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentFoldingRange,!0,e=>Bt.registerFoldingRangeProvider(Ga(e.documentSelector),new IIt(this._connection,e))))}},IIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideFoldingRanges(s,e,i){const n=this._client.bridge.translate(s,new Fy(1,1)),r=await this._client.server.textDocumentFoldingRange({textDocument:n.textDocument});return r?r.map(o=>({start:o.startLine+1,end:o.endLine+1,kind:ATt(o.kind)})):null}},NIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{selectionRange:{dynamicRegistration:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentSelectionRange,!0,e=>Bt.registerSelectionRangeProvider(Ga(e.documentSelector),new RIt(this._connection,e))))}},RIt=class{constructor(s,e){this._client=s,this._capabilities=e}async provideSelectionRanges(s,e,i){const n=this._client.bridge.translate(s,e[0]),r=await this._client.server.textDocumentSelectionRange({textDocument:n.textDocument,positions:e.map(o=>this._client.bridge.translate(s,o).position)});return r?r.map(o=>this.convertSelectionRange(o,n.textDocument)):null}convertSelectionRange(s,e){const i=[];let n=s;for(;n;)i.push({range:this._client.bridge.translateBackRange(e,n.range).range}),n=n.parent;return i}},AIt=class extends Do{constructor(s){super(),ri(this,"_providers",new Set),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{inlayHint:{dynamicRegistration:!0,resolveSupport:{properties:["tooltip","textEdits","label.tooltip","label.location","label.command"]}}},workspace:{inlayHint:{refreshSupport:!0}}})),this._register(this._connection.connection.registerRequestHandler(v5.client.workspaceInlayHintRefresh,async()=>{for(const e of this._providers)e.refresh();return{ok:null}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentInlayHint,!0,e=>{const i=new MIt(this._connection,e);this._providers.add(i);const n=Bt.registerInlayHintsProvider(Ga(e.documentSelector),i);return{dispose:()=>{this._providers.delete(i),n.dispose()}}}))}},MIt=class{constructor(s,e){ri(this,"_onDidChangeInlayHints",new L1),ri(this,"onDidChangeInlayHints",this._onDidChangeInlayHints.event),ri(this,"resolveInlayHint"),this._client=s,this._capabilities=e,e.resolveProvider&&(this.resolveInlayHint=async(i,n)=>{const r=await this._client.server.inlayHintResolve(i._lspInlayHint);return r.tooltip&&(i.tooltip=ode(r.tooltip)),r.label!==i._lspInlayHint.label&&(i.label=DSe(r.label)),r.textEdits&&(i.textEdits=r.textEdits.map(o=>({range:this._client.bridge.translateBackRange({uri:i._targetUri},o.range).range,text:o.newText}))),i})}refresh(){this._onDidChangeInlayHints.fire()}async provideInlayHints(s,e,i){const n=this._client.bridge.translate(s,e.getStartPosition()),r=await PIt(async()=>await this._client.server.textDocumentInlayHint({textDocument:n.textDocument,range:this._client.bridge.translateRange(s,e)}));return r?{hints:r.map(o=>{var a;return{label:DSe(o.label),position:$S(this._client.bridge.translateBack(n.textDocument,o.position),s).position,kind:HTt(o.kind),tooltip:ode(o.tooltip),paddingLeft:o.paddingLeft,paddingRight:o.paddingRight,textEdits:(a=o.textEdits)==null?void 0:a.map(l=>({range:$S(this._client.bridge.translateBackRange(n.textDocument,l.range),s).range,text:l.newText})),_lspInlayHint:o,_targetUri:n.textDocument.uri}}),dispose:()=>{}}:null}};async function PIt(s){for(let e=3;;e--)try{return await s()}catch(i){if(i.message==="content modified"&&e>0)continue;throw i}}function DSe(s){return typeof s=="string"?s:s.map(e=>{const i={label:e.value,tooltip:ode(e.tooltip),command:n2(e.command)};return e.location&&(i.location={uri:iG.parse(e.location.uri),range:new mR(e.location.range.start.line+1,e.location.range.start.character+1,e.location.range.end.line+1,e.location.range.end.character+1)}),i})}function ode(s){if(s)return typeof s=="string"?s:{value:s.value,isTrusted:!0}}var OIt=class extends Do{constructor(s){super(),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{semanticTokens:{dynamicRegistration:!0,requests:{range:!0,full:{delta:!0}},tokenTypes:["namespace","type","class","enum","interface","struct","typeParameter","parameter","variable","property","enumMember","event","function","method","macro","keyword","modifier","comment","string","number","regexp","operator","decorator"],tokenModifiers:["declaration","definition","readonly","static","deprecated","abstract","async","modification","documentation","defaultLibrary"],formats:[bTt.Relative],overlappingTokenSupport:!1,multilineTokenSupport:!0}}})),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentSemanticTokensFull,!0,e=>Bt.registerDocumentSemanticTokensProvider(Ga(e.documentSelector),new FIt(this._connection,e))))}},FIt=class{constructor(s,e){this._client=s,this._capabilities=e}getLegend(){return{tokenTypes:this._capabilities.legend.tokenTypes,tokenModifiers:this._capabilities.legend.tokenModifiers}}releaseDocumentSemanticTokens(s){}async provideDocumentSemanticTokens(s,e,i){const n=this._client.bridge.translate(s,s.getPositionAt(0)),r=this._capabilities.full;if(e&&r&&typeof r=="object"&&r.delta){const a=await this._client.server.textDocumentSemanticTokensFullDelta({textDocument:n.textDocument,previousResultId:e});return a?"edits"in a?{resultId:a.resultId,edits:a.edits.map(l=>({start:l.start,deleteCount:l.deleteCount,data:l.data?new Uint32Array(l.data):void 0}))}:{resultId:a.resultId,data:new Uint32Array(a.data)}:null}const o=await this._client.server.textDocumentSemanticTokensFull({textDocument:n.textDocument});return o?{resultId:o.resultId,data:new Uint32Array(o.data)}:null}async provideDocumentSemanticTokensEdits(s,e,i){return this.provideDocumentSemanticTokens(s,e,i)}},BIt=class extends Do{constructor(s){super(),ri(this,"_diagnosticsMarkerOwner","lsp"),ri(this,"_pullDiagnosticProviders",new Map),this._connection=s,this._register(this._connection.capabilities.addStaticClientCapabilities({textDocument:{publishDiagnostics:{relatedInformation:!0,tagSupport:{valueSet:[...t6e.keys()]},versionSupport:!0,codeDescriptionSupport:!0,dataSupport:!0},diagnostic:{dynamicRegistration:!0,relatedDocumentSupport:!0}}}));debugger;this._register(this._connection.connection.registerNotificationHandler(v5.client.textDocumentPublishDiagnostics,e=>this._handlePublishDiagnostics(e))),this._register(this._connection.capabilities.registerCapabilityHandler(_n.textDocumentDiagnostic,!0,e=>{const i=new wme;for(const n of D_.getModels())this._addPullDiagnosticProvider(n,e,i);return i.add(D_.onDidCreateModel(n=>{this._addPullDiagnosticProvider(n,e,i)})),i}))}_addPullDiagnosticProvider(s,e,i){if(s.getLanguageId(),!VTt(s,e.documentSelector))return;const n=new jIt(s,this._connection,this._diagnosticsMarkerOwner,e);this._pullDiagnosticProviders.set(s,n),i.add(n),i.add(s.onWillDispose(()=>{this._pullDiagnosticProviders.delete(s)}))}_handlePublishDiagnostics(s){const e=s.uri;try{const i=this._connection.bridge.translateBack({uri:e},{line:0,character:0}).textModel;if(!i||i.isDisposed())return;const n=s.diagnostics.map(r=>rde(r));D_.setModelMarkers(i,this._diagnosticsMarkerOwner,n)}catch(i){console.debug(`Could not set diagnostics for ${e}:`,i)}}},jIt=class extends Do{constructor(s,e,i,n){super(),ri(this,"_updateHandle"),ri(this,"_previousResultId"),this._model=s,this._connection=e,this._markerOwner=i,this._capability=n,this._register(this._model.onDidChangeContent(()=>{this._scheduleDiagnosticUpdate()})),this._scheduleDiagnosticUpdate()}_scheduleDiagnosticUpdate(){this._updateHandle!==void 0&&clearTimeout(this._updateHandle),this._updateHandle=window.setTimeout(()=>{this._updateHandle=void 0,this._requestDiagnostics()},500)}async _requestDiagnostics(){if(!this._model.isDisposed())try{const s=this._connection.bridge.translate(this._model,new Fy(1,1)),e=await this._connection.server.textDocumentDiagnostic({textDocument:s.textDocument,identifier:this._capability.identifier,previousResultId:this._previousResultId});if(this._model.isDisposed())return;this._handleDiagnosticReport(e)}catch(s){console.error("Error requesting diagnostics:",s)}}_handleDiagnosticReport(s){if(s.kind==="full"){this._previousResultId=s.resultId;const e=s.items.map(i=>rde(i));D_.setModelMarkers(this._model,this._markerOwner,e),"relatedDocuments"in s&&s.relatedDocuments&&this._handleRelatedDocuments(s.relatedDocuments)}else s.kind==="unchanged"&&(this._previousResultId=s.resultId)}_handleRelatedDocuments(s){for(const[e,i]of Object.entries(s))try{const n=this._connection.bridge.translateBack({uri:e},{line:0,character:0}).textModel;if(!n||n.isDisposed())continue;if(i.kind==="full"){const r=i.items.map(o=>rde(o));D_.setModelMarkers(n,this._markerOwner,r)}}catch(n){console.debug(`Could not set related diagnostics for ${e}:`,n)}}dispose(){this._updateHandle!==void 0&&(clearTimeout(this._updateHandle),this._updateHandle=void 0),super.dispose()}},$It=class{constructor(s,e,i,n){this.server=s,this.bridge=e,this.capabilities=i,this.connection=n}},WIt=class extends Do{constructor(s){super(),ri(this,"_staticCapabilities",new Set),ri(this,"_dynamicFromStatic",zIt.create()),ri(this,"_registrations",new Map),ri(this,"_serverCapabilities"),this._connection=s,this._register(this._connection.registerRequestHandler(v5.client.clientRegisterCapability,async e=>{for(const i of e.registrations){const n=ISe(i.method),r=new TSe(i.id,n,i.registerOptions,!1);this._registerCapabilityOptions(r)}return{ok:null}})),this._register(this._connection.registerRequestHandler(v5.client.clientUnregisterCapability,async e=>{for(const i of e.unregisterations){const n=ISe(i.method),r=this._registrations.get(n),o=r==null?void 0:r.registrations.get(i.id);if(!o)throw new Error(`No registration for method ${i.method} with id ${i.id}`);o==null||o.handlerDisposables.forEach(a=>a.dispose()),r==null||r.registrations.delete(i.id)}return{ok:null}}))}_registerCapabilityOptions(s){let e=this._registrations.get(s.capability);if(e||(e=new NSe,this._registrations.set(s.capability,e)),e.registrations.has(s.id))throw new Error(`Handler for method ${s.capability.method} with id ${s.id} already registered`);e.registrations.set(s.id,s);for(const i of e.handlers)!i.handleStaticCapability&&s.isFromStatic||s.handlerDisposables.set(i,i.handler(s.options))}setServerCapabilities(s){if(this._serverCapabilities)throw new Error("Server capabilities already set");this._serverCapabilities=s;for(const e of Object.values(_n)){const i=this._dynamicFromStatic.getOptions(e,s);i&&this._registerCapabilityOptions(new TSe(e.method,e,i,!0))}}getClientCapabilities(){const s={};for(const e of this._staticCapabilities)r6e(s,e.cap);return s}addStaticClientCapabilities(s){const e={cap:s};return this._staticCapabilities.add(e),{dispose:()=>{this._staticCapabilities.delete(e)}}}registerCapabilityHandler(s,e,i){let n=this._registrations.get(s);n||(n=new NSe,this._registrations.set(s,n));const r=new HIt(s,e,i);n.handlers.add(r);for(const o of n.registrations.values())!r.handleStaticCapability&&o.isFromStatic||o.handlerDisposables.set(r,i(o.options));return{dispose:()=>{n.handlers.delete(r);for(const o of n.registrations.values()){const a=o.handlerDisposables.get(r);a&&(a.dispose(),o.handlerDisposables.delete(r))}}}}},HIt=class{constructor(s,e,i){this.capability=s,this.handleStaticCapability=e,this.handler=i}},TSe=class{constructor(s,e,i,n){ri(this,"handlerDisposables",new Map),this.id=s,this.capability=e,this.options=i,this.isFromStatic=n}};const VIt=new Map([...Object.values(_n)].map(s=>[s.method,s]));function ISe(s){const e=VIt.get(s);if(!e)throw new Error(`No capability found for method ${s}`);return e}var NSe=class{constructor(){ri(this,"handlers",new Set),ri(this,"registrations",new Map)}},zIt=class s6e{constructor(){ri(this,"_mappings",new Map)}static create(){const e=new s6e;return e.set(_n.textDocumentDidChange,i=>{if(i.textDocumentSync!==void 0)return typeof i.textDocumentSync=="object"?{syncKind:i.textDocumentSync.change??mTt.None,documentSelector:null}:{syncKind:i.textDocumentSync,documentSelector:null}}),e.set(_n.textDocumentCompletion,i=>i.completionProvider),e.set(_n.textDocumentHover,i=>i.hoverProvider),e.set(_n.textDocumentSignatureHelp,i=>i.signatureHelpProvider),e.set(_n.textDocumentDefinition,i=>i.definitionProvider),e.set(_n.textDocumentReferences,i=>i.referencesProvider),e.set(_n.textDocumentDocumentHighlight,i=>i.documentHighlightProvider),e.set(_n.textDocumentDocumentSymbol,i=>i.documentSymbolProvider),e.set(_n.textDocumentCodeAction,i=>i.codeActionProvider),e.set(_n.textDocumentCodeLens,i=>i.codeLensProvider),e.set(_n.textDocumentDocumentLink,i=>i.documentLinkProvider),e.set(_n.textDocumentFormatting,i=>i.documentFormattingProvider),e.set(_n.textDocumentRangeFormatting,i=>i.documentRangeFormattingProvider),e.set(_n.textDocumentOnTypeFormatting,i=>i.documentOnTypeFormattingProvider),e.set(_n.textDocumentRename,i=>i.renameProvider),e.set(_n.textDocumentFoldingRange,i=>i.foldingRangeProvider),e.set(_n.textDocumentDeclaration,i=>i.declarationProvider),e.set(_n.textDocumentTypeDefinition,i=>i.typeDefinitionProvider),e.set(_n.textDocumentImplementation,i=>i.implementationProvider),e.set(_n.textDocumentDocumentColor,i=>i.colorProvider),e.set(_n.textDocumentSelectionRange,i=>i.selectionRangeProvider),e.set(_n.textDocumentLinkedEditingRange,i=>i.linkedEditingRangeProvider),e.set(_n.textDocumentPrepareCallHierarchy,i=>i.callHierarchyProvider),e.set(_n.textDocumentSemanticTokensFull,i=>i.semanticTokensProvider),e.set(_n.textDocumentInlayHint,i=>i.inlayHintProvider),e.set(_n.textDocumentInlineValue,i=>i.inlineValueProvider),e.set(_n.textDocumentDiagnostic,i=>i.diagnosticProvider),e.set(_n.textDocumentMoniker,i=>i.monikerProvider),e.set(_n.textDocumentPrepareTypeHierarchy,i=>i.typeHierarchyProvider),e.set(_n.workspaceSymbol,i=>i.workspaceSymbolProvider),e.set(_n.workspaceExecuteCommand,i=>i.executeCommandProvider),e}set(e,i){if(this._mappings.has(e.method))throw new Error(`Capability for method ${e.method} already registered`);this._mappings.set(e.method,i)}getOptions(e,i){const n=this._mappings.get(e.method);if(n)return n(i)}};function r6e(s,e){for(const i of Object.keys(e)){const n=e[i];if(n===void 0)continue;const r=s[i];if(r===void 0){s[i]=n;continue}if(typeof n!="object"||n===null){s[i]=n;continue}if(typeof r!="object"||r===null){s[i]=n;continue}r6e(r,n)}}var UIt=class extends Do{constructor(s,e){super(),ri(this,"_managedModels",new Map),ri(this,"_managedModelsReverse",new Map),ri(this,"_started",!1),this._server=s,this._capabilities=e,this._register(this._capabilities.addStaticClientCapabilities({textDocument:{synchronization:{dynamicRegistration:!0,willSave:!1,willSaveWaitUntil:!1,didSave:!1}}})),this._register(e.registerCapabilityHandler(_n.textDocumentDidChange,!0,i=>{if(this._started)return{dispose:()=>{}};this._started=!0,this._register(D_.onDidCreateModel(n=>{this._getOrCreateManagedModel(n)}));for(const n of D_.getModels())this._getOrCreateManagedModel(n);return{dispose:()=>{}}}))}_getOrCreateManagedModel(s){if(!this._started)throw new Error("Not started");const e=s.uri.toString(!0).toLowerCase();let i=this._managedModels.get(s);return i||(i=new qIt(s,this._server),this._managedModels.set(s,i),this._managedModelsReverse.set(e,s)),s.onWillDispose(()=>{i.dispose(),this._managedModels.delete(s),this._managedModelsReverse.delete(e)}),i}translateBack(s,e){const i=s.uri.toLowerCase(),n=this._managedModelsReverse.get(i);if(!n)throw new Error(`No text model for uri ${i}`);return{textModel:n,position:new Fy(e.line+1,e.character+1)}}translateBackRange(s,e){const i=s.uri.toLowerCase(),n=this._managedModelsReverse.get(i);if(!n)throw new Error(`No text model for uri ${i}`);return{textModel:n,range:new mR(e.start.line+1,e.start.character+1,e.end.line+1,e.end.character+1)}}translate(s,e){return{textDocument:{uri:s.uri.toString(!0)},position:{line:e.lineNumber-1,character:e.column-1}}}translateRange(s,e){return{start:{line:e.startLineNumber-1,character:e.startColumn-1},end:{line:e.endLineNumber-1,character:e.endColumn-1}}}},qIt=class extends Do{constructor(s,e){super(),this._textModel=s,this._api=e;const i=s.uri.toString(!0).toLowerCase();this._api.textDocumentDidOpen({textDocument:{languageId:s.getLanguageId(),uri:i,version:s.getVersionId(),text:s.getValue()}}),this._register(s.onDidChangeContent(n=>{const r=n.changes.map(o=>GIt(o));this._api.textDocumentDidChange({textDocument:{uri:i,version:s.getVersionId()},contentChanges:r})})),this._register({dispose:()=>{this._api.textDocumentDidClose({textDocument:{uri:i}})}})}};function GIt(s){return{range:KIt(s.range),rangeLength:s.rangeLength,text:s.text}}function KIt(s){return{start:{line:s.startLineNumber-1,character:s.startColumn-1},end:{line:s.endLineNumber-1,character:s.endColumn-1}}}var YIt=class{constructor(s){ri(this,"_connection"),ri(this,"_capabilitiesRegistry"),ri(this,"_bridge"),ri(this,"_initPromise");const e=ide.fromTransport(s),i=v5.getServer(e,{});e.startListen(),this._capabilitiesRegistry=new WIt(e),this._bridge=new UIt(i.server,this._capabilitiesRegistry),this._connection=new $It(i.server,this._bridge,this._capabilitiesRegistry,e),this.createFeatures(),this._initPromise=this._init()}async _init(){const s=await this._connection.server.initialize({processId:null,capabilities:this._capabilitiesRegistry.getClientCapabilities(),rootUri:null});this._connection.server.initialized({}),this._capabilitiesRegistry.setServerCapabilities(s.capabilities)}createFeatures(){const s=new wme;return s.add(new zTt(this._connection)),s.add(new KTt(this._connection)),s.add(new ZTt(this._connection)),s.add(new JTt(this._connection)),s.add(new tIt(this._connection)),s.add(new nIt(this._connection)),s.add(new rIt(this._connection)),s.add(new aIt(this._connection)),s.add(new cIt(this._connection)),s.add(new uIt(this._connection)),s.add(new gIt(this._connection)),s.add(new _It(this._connection)),s.add(new bIt(this._connection)),s.add(new wIt(this._connection)),s.add(new CIt(this._connection)),s.add(new kIt(this._connection)),s.add(new EIt(this._connection)),s.add(new TIt(this._connection)),s.add(new NIt(this._connection)),s.add(new AIt(this._connection)),s.add(new OIt(this._connection)),s.add(new BIt(this._connection)),s}},PT=null;typeof WebSocket<"u"?PT=WebSocket:typeof MozWebSocket<"u"?PT=MozWebSocket:typeof global<"u"?PT=global.WebSocket||global.MozWebSocket:typeof window<"u"?PT=window.WebSocket||window.MozWebSocket:typeof self<"u"&&(PT=self.WebSocket||self.MozWebSocket);var XIt=PT;function ZIt(s){return"host"in s?{address:`${s.forceTls?"wss":"ws"}://${s.host}:${s.port}`}:s}var QIt=class ade extends j$e{constructor(e){super(),ri(this,"socket"),ri(this,"errorEmitter",new yme),ri(this,"onError",this.errorEmitter),this.socket=e,e.onmessage=i=>{try{const n=i.data;if(typeof n=="string"){const r=JSON.parse(n);this._dispatchReceivedMessage(r)}else throw new Error("Not supported")}catch(n){this.errorEmitter.fire({error:n})}},e.onclose=i=>{this._onConnectionClosed()}}static connectTo(e){const i=new XIt(ZIt(e).address);return new Promise((n,r)=>{i.onerror=o=>{r(o)},i.onopen=()=>{n(new ade(i))}})}static fromWebSocket(e){return new ade(e)}close(){this.socket.close()}dispose(){this.close()}_sendImpl(e){const i=JSON.stringify(e);return new Promise((n,r)=>{this.socket.send(i,o=>{o?r(o):n()})})}toString(){return`${this.id}@${this.socket.url}`}},o6e=class extends j$e{constructor(s,e=void 0,i=void 0){super(),ri(this,"_windowLike"),ri(this,"_source"),ri(this,"_loadingState"),ri(this,"_disposed",!1),ri(this,"_messageHandler",({data:n,source:r})=>{this._source&&r!==this._source||typeof n=="object"&&n&&this._dispatchReceivedMessage(n)}),this._windowLike=s,this._source=e,this._loadingState=i,this._windowLike.addEventListener("message",this._messageHandler)}async _sendImpl(s){if(this._disposed)throw new Error("Transport is disposed");this._loadingState&&!this._loadingState.loaded&&await this._loadingState.onLoaded,this._windowLike.postMessage(s)}toString(){return`${this.id}@${this._windowLike}`}dispose(){this._disposed||(this._disposed=!0,this._windowLike.removeEventListener("message",this._messageHandler))}};function JIt(s){if(typeof window>"u")throw new Error("call this function from the main browser thread");return new o6e(s)}function e2t(s){if(typeof window>"u")throw new Error("call this function from the main browser thread");return new o6e(s.contentWindow,s.contentWindow,{loaded:window.document.readyState==="complete",onLoaded:new Promise(e=>{window.addEventListener("load",()=>e())})})}const t2t=Object.freeze(Object.defineProperty({__proto__:null,MonacoLspClient:YIt,WebSocketTransport:QIt,createTransportToIFrame:e2t,createTransportToWorker:JIt},Symbol.toStringTag,{value:"Module"}));function i2t(s,e){var n;const i=globalThis.MonacoEnvironment;if(i!=null&&i.createTrustedTypesPolicy)try{return i.createTrustedTypesPolicy(s,e)}catch(r){console.error(r);return}try{return(n=globalThis.trustedTypes)==null?void 0:n.createPolicy(s,e)}catch(r){console.error(r);return}}let aH;typeof self=="object"&&self.constructor&&self.constructor.name==="DedicatedWorkerGlobalScope"&&globalThis.workerttPolicy!==void 0?aH=globalThis.workerttPolicy:aH=i2t("defaultWorkerFactory",{createScriptURL:s=>s});function n2t(s){const e=s.label,i=globalThis.MonacoEnvironment;if(i){if(typeof i.getWorker=="function")return i.getWorker("workerMain.js",e);if(typeof i.getWorkerUrl=="function"){const n=i.getWorkerUrl("workerMain.js",e);return new Worker(aH?aH.createScriptURL(n):n,{name:e,type:"module"})}}if(s.createWorker)return s.createWorker();throw new Error("You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker")}function s2t(s){const e=Promise.resolve(n2t({label:s.label??"monaco-editor-worker",moduleId:s.moduleId,createWorker:s.createWorker})).then(i=>(i.postMessage("ignore"),i.postMessage(s.createData),i));return D_.createWebWorker({worker:e,host:s.host,keepIdleModels:s.keepIdleModels})}function a6e(){return BDt}const UX=globalThis.MonacoEnvironment;UX!=null&&UX.globalAPI&&(globalThis.monaco=a6e());const aG=a6e();aG.languages.css=y$e;aG.languages.html=S$e;aG.languages.typescript=F$e;aG.languages.json=E$e;const xme=Object.freeze(Object.defineProperty({__proto__:null,CancellationTokenSource:u$e,Emitter:L1,KeyCode:h$e,KeyMod:f$e,MarkerSeverity:pg,MarkerTag:rH,Position:Fy,Range:mR,Selection:g$e,SelectionDirection:p$e,Token:m$e,Uri:iG,createWebWorker:s2t,css:y$e,editor:D_,html:S$e,json:E$e,languages:Bt,lsp:t2t,typescript:F$e},Symbol.toStringTag,{value:"Module"})),RSe=s=>{let e;const i=new Set,n=(d,u)=>{const h=typeof d=="function"?d(e):d;if(!Object.is(h,e)){const f=e;e=u??(typeof h!="object"||h===null)?h:Object.assign({},e,h),i.forEach(g=>g(e,f))}},r=()=>e,l={setState:n,getState:r,getInitialState:()=>c,subscribe:d=>(i.add(d),()=>i.delete(d))},c=e=s(n,r,l);return l},r2t=(s=>s?RSe(s):RSe),o2t=s=>s;function a2t(s,e=o2t){const i=at.useSyncExternalStore(s.subscribe,at.useCallback(()=>e(s.getState()),[s,e]),at.useCallback(()=>e(s.getInitialState()),[s,e]));return at.useDebugValue(i),i}const ASe=s=>{const e=r2t(s),i=n=>a2t(e,n);return Object.assign(i,e),i},Ka=(s=>s?ASe(s):ASe);function im(s){return"'"+s.replace(/'/g,"'\\''")+"'"}const qX=({sessionId:s})=>`claude --dangerously-skip-permissions --session-id ${im(s)}`,MSe=({sessionId:s})=>`claude --session-id ${im(s)}`,l2t=()=>"claude --resume",l6e=[{id:"sm-dangerous",label:"Session Manager (skip perms)",description:"claude --dangerously-skip-permissions in this project",category:"build",cwd:"app-cwd",command:qX},{id:"sm-safe",label:"Session Manager (safe)",description:"claude with normal permission prompts in this project",category:"build",cwd:"app-cwd",command:MSe},{id:"home-dangerous",label:"Home (skip perms)",description:"claude --dangerously-skip-permissions in ~",category:"build",cwd:"home",command:qX},{id:"pick-dangerous",label:"Pick directory (skip perms)…",description:"Choose a folder, launch claude --dangerously-skip-permissions",category:"build",cwd:"pick",command:qX},{id:"pick-safe",label:"Pick directory (safe)…",description:"Choose a folder, launch claude with normal prompts",category:"build",cwd:"pick",command:MSe},{id:"pick-resume",label:"Pick directory + resume…",description:"Choose a folder, then pick a past session to resume",category:"build",cwd:"pick",command:l2t},{id:"pick-shell",label:"Pick directory (shell only)…",description:"Bare interactive shell, no claude auto-launch",category:"build",cwd:"pick",command:null}];let Uf=null;async function c2t(){if(Uf)return Uf;try{const s=await window.api.app.engageRulesPath();if(!s)return Uf=[],Uf;const e=await window.api.config.readJson(s);if(!e.exists||e.parseError||!e.data)return Uf=[],Uf;const i=e.data;if(!i.presets||!Array.isArray(i.presets))return Uf=[],Uf;const n=i.projectPath;return Uf=i.presets.map(r=>({id:r.id,label:r.label,description:r.description,category:"engage",cwd:n,platform:r.platform,pipeline:r.pipeline,rules:r.rules,command:()=>`cd ${im(n)} && ${r.cliEntry}`})),Uf}catch(s){return console.warn("[presets] Failed to load engage presets:",s),Uf=[],Uf}}async function c6e(s){const e=l6e.find(n=>n.id===s);return e||((await c2t()).find(n=>n.id===s)??null)}async function d2t(s){return s.cwd==="app-cwd"?window.api.app.cwd():s.cwd==="home"?window.api.app.homeDir():s.cwd==="pick"?window.api.app.pickDirectory():s.cwd}function d6e(s,e){return s.command?s.command(e):null}function u2t(s){const e=s.split("/").filter(Boolean);return e[e.length-1]||s}const hn=Ka((s,e)=>({tabs:[],activeTabId:null,hydrated:!1,addTab:({id:i,cwd:n,startupCommand:r,presetId:o=null,label:a})=>{const l=i??crypto.randomUUID();if(e().tabs.find(u=>u.id===l))return s({activeTabId:l}),l;const d={id:l,claudeSessionId:l,label:a??u2t(n),cwd:n,pid:null,status:"spawning",exitCode:null,startupCommand:r,presetId:o,generation:0};return s({tabs:[...e().tabs,d],activeTabId:l}),l},setTabRunning:(i,n)=>s({tabs:e().tabs.map(r=>r.id===i?{...r,pid:n,status:"running"}:r)}),setTabExited:(i,n)=>s({tabs:e().tabs.map(r=>r.id===i?{...r,status:"exited",exitCode:n}:r)}),closeTab:i=>{var o;window.api.pty.kill(i),window.api.watchers.killTab(i).catch(()=>{});const n=e().tabs.filter(a=>a.id!==i),r=e().activeTabId===i?((o=n[n.length-1])==null?void 0:o.id)??null:e().activeTabId;s({tabs:n,activeTabId:r})},setActive:i=>s({activeTabId:i}),restartTab:i=>{const n=e().tabs.find(a=>a.id===i);if(!n)return;window.api.pty.kill(i);const r=crypto.randomUUID(),o=a=>{s({tabs:e().tabs.map(l=>l.id===i?{...l,claudeSessionId:r,pid:null,status:"spawning",exitCode:null,startupCommand:a,generation:l.generation+1}:l)})};n.presetId?c6e(n.presetId).then(a=>{o(a?d6e(a,{sessionId:r,cwd:n.cwd}):`claude --dangerously-skip-permissions --session-id ${im(r)}`)}):o(`claude --dangerously-skip-permissions --session-id ${im(r)}`)},reorderTab:(i,n)=>{const r=[...e().tabs];if(i<0||i>=r.length||n<0||n>=r.length||i===n)return;const[o]=r.splice(i,1);r.splice(n,0,o),s({tabs:r})},restoreTabs:(i,n)=>s({tabs:i,activeTabId:n,hydrated:!0})}));async function u6e(){var i;if(hn.getState().hydrated)return;try{const{tabs:n,activeTabId:r,freshStart:o}=await window.api.sessions.load();if(n.length>0){const a=await Promise.all(n.map(async c=>{let d=!o;if(d){const h=await window.api.transcripts.pathFor(c.cwd,c.claudeSessionId);d=await window.api.config.exists(h)}const u=d?c.claudeSessionId:crypto.randomUUID();return{id:c.id,claudeSessionId:u,cwd:c.cwd,label:c.label,presetId:c.presetId,pid:null,status:"spawning",exitCode:null,startupCommand:d?`claude --dangerously-skip-permissions --resume ${im(u)}`:`claude --dangerously-skip-permissions --session-id ${im(u)}`,generation:0}})),l=r&&a.find(c=>c.id===r)?r:((i=a[0])==null?void 0:i.id)??null;hn.getState().restoreTabs(a,l)}else hn.setState({hydrated:!0})}catch(n){console.warn("[sessions] hydrate failed:",n),hn.setState({hydrated:!0})}const s=()=>{const{tabs:n,activeTabId:r}=hn.getState(),o=n.map(a=>({id:a.id,claudeSessionId:a.claudeSessionId,cwd:a.cwd,label:a.label,presetId:a.presetId}));window.api.sessions.save({tabs:o,activeTabId:r}).catch(a=>{console.warn("[sessions] save failed:",a)})};let e=null;hn.subscribe((n,r)=>{n.hydrated&&(n.tabs===r.tabs&&n.activeTabId===r.activeTabId||(e!==null&&window.clearTimeout(e),e=window.setTimeout(s,200)))}),s()}const h2t=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:u6e,useSessions:hn},Symbol.toStringTag,{value:"Module"})),f2t=5,PSe=100,g2t=5e3,lde=new Map;function OSe(s){const e=lde.get(s);e!==void 0&&(clearTimeout(e),lde.delete(s))}function p2t(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`t-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}const s2=Ka((s,e)=>({toasts:[],history:[],unreadCount:0,show:(i,n)=>{const r=p2t(),o=Date.now();s(l=>{const c=[...l.toasts,{id:r,kind:i,message:n,createdAt:o}];for(;c.length>f2t;){const h=c.shift();h&&OSe(h.id)}const u=[{id:r,kind:i,message:n,createdAt:o,read:!1},...l.history];return u.length>PSe&&(u.length=PSe),{toasts:c,history:u,unreadCount:l.unreadCount+1}});const a=setTimeout(()=>e().dismiss(r),g2t);return lde.set(r,a),r},dismiss:i=>{OSe(i),s(n=>({toasts:n.toasts.filter(r=>r.id!==i)}))},markAllRead:()=>{s(i=>i.unreadCount===0?i:{history:i.history.map(n=>n.read?n:{...n,read:!0}),unreadCount:0})},clearHistory:()=>{s({history:[],unreadCount:0})},dismissHistoryEntry:i=>{s(n=>{const r=n.history.filter(a=>a.id!==i);if(r.length===n.history.length)return n;const o=n.history.find(a=>a.id===i&&!a.read);return{history:r,unreadCount:o?Math.max(0,n.unreadCount-1):n.unreadCount}})}})),Kt={info:s=>s2.getState().show("info",s),warn:s=>s2.getState().show("warn",s),error:s=>s2.getState().show("error",s)},h6e=Object.freeze(Object.defineProperty({__proto__:null,toast:Kt,useToast:s2},Symbol.toStringTag,{value:"Module"})),FSe=200,m2t=/\x1b\[[0-9;]*m/g;function _2t(s){return s.replace(m2t,"")}const GO=Ka((s,e)=>({watchers:{},initialized:!1,init:()=>{e().initialized||(s({initialized:!0}),window.api.watchers.onLine(i=>e().ingestLine(i)),window.api.watchers.onClosed(({watcherId:i})=>e().closed(i)))},add:async({tabId:i,label:n,command:r,cwd:o})=>{try{const a=await window.api.watchers.add({tabId:i,label:n,command:r,cwd:o??null}),l={watcherId:a.watcherId,tabId:a.tabId,label:a.label,command:a.command,cwd:a.cwd,pid:a.pid,startedAt:a.startedAt,lineCount:0,lines:[],lastLineAt:null};return s({watchers:{...e().watchers,[l.watcherId]:l}}),l}catch(a){return console.error("[watchers] add failed:",a),Kt.error("Failed to add watcher"),null}},remove:async i=>{try{await window.api.watchers.remove(i)}catch(r){console.error("[watchers] remove failed:",r);const o=r instanceof Error?r.message:String(r);Kt.error(`Could not remove watcher: ${o}`)}const n={...e().watchers};delete n[i],s({watchers:n})},watchersForTab:i=>Object.values(e().watchers).filter(n=>n.tabId===i),ingestLine:i=>{const n=e().watchers[i.watcherId];if(!n)return;const r=_2t(i.line),o=n.lines.length>=FSe?[...n.lines.slice(n.lines.length-FSe+1),{line:r,ts:i.ts}]:[...n.lines,{line:r,ts:i.ts}];s({watchers:{...e().watchers,[i.watcherId]:{...n,lines:o,lineCount:n.lineCount+1,lastLineAt:i.ts}}})},closed:i=>{if(!e().watchers[i])return;const n={...e().watchers};delete n[i],s({watchers:n})}})),v2t=4,BSe=40,jSe=6;function b2t(s){const{onReorder:e,onActivate:i}=s,n=z.useRef(null),r=z.useRef(null),o=z.useRef(0),a=z.useRef(0),[l,c]=z.useState(!1),[,d]=z.useState(0),u=z.useRef(i);u.current=i;const h=z.useCallback(()=>n.current?Array.from(n.current.querySelectorAll("[data-drag-index]")):[],[]),f=z.useCallback((m,b,y)=>{for(let x=0;x<b.length;x++){const S=b[x].left+b[x].width/2;if(m<S)return x<=y?x:x-1}return b.length-1},[]),g=z.useCallback(()=>{const m=r.current,b=n.current;if(!(m!=null&&m.active)||!b)return;const y=b.getBoundingClientRect(),x=m.startX+m.deltaX,S=x-y.left,k=y.right-x;S<BSe?b.scrollLeft-=jSe:k<BSe&&(b.scrollLeft+=jSe),o.current=requestAnimationFrame(g)},[]);z.useEffect(()=>{const m=n.current;if(!m)return;let b=!1;const y=()=>{b||(b=!0,a.current=requestAnimationFrame(()=>{b=!1,d(k=>k+1)}))},x=k=>{var O;const D=r.current;if(!D)return;const T=k.clientX-D.startX;if(!D.active&&Math.abs(T)<v2t)return;if(!D.active){D.active=!0,D.tabRects=h().map($=>$.getBoundingClientRect()),c(!0);try{(O=n.current)==null||O.setPointerCapture(D.pointerId)}catch{}o.current=requestAnimationFrame(g)}D.deltaX=T;const N=D.tabRects[D.fromIndex],A=N.left+N.width/2+T;D.currentIndex=f(A,D.tabRects,D.fromIndex),y()},S=k=>{const D=r.current;if(D&&D.pointerId===k.pointerId){cancelAnimationFrame(o.current),cancelAnimationFrame(a.current);try{m.releasePointerCapture(D.pointerId)}catch{}D.active&&D.fromIndex!==D.currentIndex?e(D.fromIndex,D.currentIndex):u.current(D.fromIndex),r.current=null,c(!1),d(T=>T+1)}};return m.addEventListener("pointermove",x),m.addEventListener("pointerup",S),m.addEventListener("pointercancel",S),()=>{m.removeEventListener("pointermove",x),m.removeEventListener("pointerup",S),m.removeEventListener("pointercancel",S),cancelAnimationFrame(o.current),cancelAnimationFrame(a.current)}},[e,h,f,g]);const p=z.useCallback((m,b)=>{m.button!==0||m.target.closest("button")||(r.current={active:!1,fromIndex:b,currentIndex:b,startX:m.clientX,deltaX:0,tabRects:[],pointerId:m.pointerId})},[]);return{getTabDragProps:z.useCallback(m=>{var x;const b=r.current,y={};if(b!=null&&b.active)if(m===b.fromIndex)y.transform=`translateX(${b.deltaX}px) scale(1.03)`,y.zIndex=10,y.opacity=.85,y.boxShadow="0 2px 8px rgba(0,0,0,0.4)",y.position="relative",y.pointerEvents="none";else{const S=b.fromIndex,k=b.currentIndex,T=(((x=b.tabRects[S])==null?void 0:x.width)??0)+4;y.transition="transform 0.15s ease",S<k&&m>S&&m<=k?y.transform=`translateX(-${T}px)`:S>k&&m>=k&&m<S?y.transform=`translateX(${T}px)`:y.transform="translateX(0)"}return{onPointerDown:S=>p(S,m),style:y,"data-drag-index":m}},[p]),isDragging:l,containerRef:n}}const y2t=3e4;function w2t(){const s=hn(g=>g.tabs),e=hn(g=>g.activeTabId),i=hn(g=>g.closeTab),n=hn(g=>g.setActive),r=hn(g=>g.reorderTab),o=GO(g=>g.watchers),[a,l]=z.useState(()=>Date.now());z.useEffect(()=>{const g=window.setInterval(()=>l(Date.now()),1e3);return()=>window.clearInterval(g)},[]);const c=g=>{for(const p of Object.values(o))if(p.tabId===g&&p.lastLineAt&&a-p.lastLineAt<y2t)return!0;return!1},{getTabDragProps:d,isDragging:u,containerRef:h}=b2t({tabCount:s.length,onReorder:r,onActivate:g=>{const p=s[g];p&&n(p.id)}}),f=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return v.jsxs("div",{className:"h-11 bg-bg-elev border-b border-line flex items-end px-3 gap-0 shrink-0 relative","data-testid":"tour-tabbar",children:[v.jsx("div",{ref:h,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${u?"cursor-grabbing":""}`,children:s.map((g,p)=>{const _=g.id===e,m=d(p),b=f[p%f.length];return v.jsxs("div",{...m,style:m.style,className:`group flex items-center gap-2 px-3.5 pt-1.5 pb-2 rounded-t-[10px] text-[13px] shrink-0 transition-colors ${u?"":"cursor-grab"} ${_?"bg-bg text-fg font-medium relative z-10 -mb-px border border-b-0 border-line":"text-fg-dim hover:text-fg hover:bg-bg-hi/40"}`,title:g.cwd,"aria-current":_?"true":void 0,children:[v.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:b,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:g.status==="spawning"?.55:1}}),v.jsx("span",{className:"truncate max-w-[200px]",children:g.label}),g.status==="spawning"&&v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),c(g.id)&&v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"watcher emitted a line in the last 30s","data-testid":"tab-watcher-dot"}),v.jsx("button",{onClick:y=>{y.stopPropagation(),i(g.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${g.label}`,children:"×"})]},g.id)})}),v.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[v.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),v.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.21.1"]})]})]})}function x2t(s,e,i){return e?s.map(n=>n.id===e?{...n,lastActivityAt:i}:n):s}function C2t(s,e,i){return{tabId:s,sessionUuid:i,cwd:e,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const k8=Ka((s,e)=>({tabs:{},refs:{},unsubs:{},subscribe:(i,n,r)=>{const o={...e().refs};if(o[i]=(o[i]??0)+1,s({refs:o}),o[i]>1)return;s({tabs:{...e().tabs,[i]:C2t(i,n,r)}});const a=window.api.transcripts.onEvent(i,l=>e().ingest(i,l));s({unsubs:{...e().unsubs,[i]:a}}),window.api.transcripts.subscribe({tabId:i,cwd:n,sessionUuid:r}).then(async l=>{const c=e().tabs[i];if(!c)return;if(!l.ok){const{toast:u}=await ei(async()=>{const{toast:h}=await Promise.resolve().then(()=>h6e);return{toast:h}},void 0,import.meta.url);u.error(`Live view unavailable: ${l.error??"subscribe failed"}`),s({tabs:{...e().tabs,[i]:{...c,path:null}}});return}s({tabs:{...e().tabs,[i]:{...c,path:l.path}}});const d=await window.api.transcripts.buffer(i);for(const u of d)e().ingest(i,u,{replay:!0})}).catch(l=>console.error("[live] transcripts.subscribe failed:",i,l))},unsubscribe:i=>{const n={...e().refs};if(!n[i])return;if(n[i]--,n[i]>0){s({refs:n});return}delete n[i];const r=e().unsubs[i];r==null||r();const o={...e().unsubs};delete o[i];const a={...e().tabs};delete a[i],window.api.transcripts.unsubscribe(i),s({refs:n,unsubs:o,tabs:a})},ingest:(i,n,r)=>{const o=e().tabs[i];if(!o)return;const a=Date.now(),l={...o,lastEventAt:r!=null&&r.replay?o.lastEventAt:a},c=[],d=(u,h)=>u.length>h?u.slice(0,h-1)+"…":u;switch(n.kind){case"todo_write":{const u=Array.isArray(n.data)?n.data:[];l.todos=u,r!=null&&r.replay||c.push({id:0,kind:"todo-update",at:a,label:`Todos · ${u.length} item${u.length!==1?"s":""}`});break}case"tool_use":{const u=n.data;if(l.lastToolUses=[{id:u.id,name:u.name,input:u.input,at:a},...o.lastToolUses].slice(0,50),!(r!=null&&r.replay)){const h=u.input,f=["Edit","Write","NotebookEdit"].includes(u.name),g=typeof(h==null?void 0:h.file_path)=="string"?h.file_path:void 0,p=typeof(h==null?void 0:h.command)=="string"?h.command:void 0,_=g?g.split("/").pop()??g:p?d(p,28):"";c.push({id:0,kind:"tool-use",at:a,label:_?`${u.name} · ${_}`:u.name,target:g??p,toolName:u.name}),f&&g&&c.push({id:0,kind:"file-edit",at:a,label:`${u.name} · ${d(g.split("/").pop()??g,34)}`,target:g,toolName:u.name})}break}case"plan":{const u=n.data,h=typeof u=="string"?u:(u==null?void 0:u.plan)??JSON.stringify(u);l.plans=[{at:a,content:h??""},...o.plans].slice(0,50),r!=null&&r.replay||c.push({id:0,kind:"plan-revision",at:a,label:"Plan revised"});break}case"agent_spawn":{const u=n.data;l.agents=[{id:u==null?void 0:u.toolUseId,at:a,subagentType:u==null?void 0:u.subagent_type,description:u==null?void 0:u.description,lastActivityAt:a},...o.agents].slice(0,50),r!=null&&r.replay||c.push({id:0,kind:"agent-spawn",at:a,label:u!=null&&u.subagent_type?`Agent: ${d(u.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const u=n.data,h=(o.usage.inputTokens||0)+(o.usage.outputTokens||0),f=u.input_tokens??u.inputTokens??0,g=u.output_tokens??u.outputTokens??0,p=h+f+g;l.usage={inputTokens:(o.usage.inputTokens||0)+f,outputTokens:(o.usage.outputTokens||0)+g,cacheCreationInputTokens:(o.usage.cacheCreationInputTokens||0)+(u.cache_creation_input_tokens??u.cacheCreationInputTokens??0),cacheReadInputTokens:(o.usage.cacheReadInputTokens||0)+(u.cache_read_input_tokens??u.cacheReadInputTokens??0)},!(r!=null&&r.replay)&&Math.floor(p/1e3)>Math.floor(h/1e3)&&c.push({id:0,kind:"usage-tick",at:a,label:`${Math.floor(p/1e3)}k tokens`});break}case"tool_result":{const u=n.data;l.agents=x2t(o.agents,u==null?void 0:u.toolUseId,a);break}}if(c.length>0){let u=o.activitySeq;const h=c.map(f=>({...f,id:++u}));l.activitySeq=u,l.activityRing=[...o.activityRing,...h].slice(-32)}s({tabs:{...e().tabs,[i]:l}})}}));function KF(s){const e=k8(r=>r.subscribe),i=k8(r=>r.unsubscribe),n=k8(r=>s?r.tabs[s.id]:void 0);return z.useEffect(()=>{if(s)return e(s.id,s.cwd,s.claudeSessionId),()=>i(s.id)},[s==null?void 0:s.id,s==null?void 0:s.cwd,s==null?void 0:s.claudeSessionId,e,i]),n}var GX={},$M={},$Se;function f6e(){if($Se)return $M;$Se=1,Object.defineProperty($M,"__esModule",{value:!0}),$M.baseAssetPath=void 0;const e=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let i="/";return e&&(i=e.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),$M.baseAssetPath=i,$M}var WM={},WSe;function Cme(){if(WSe)return WM;WSe=1,Object.defineProperty(WM,"__esModule",{value:!0}),WM.defaultModelFetcher=void 0;const s=e=>fetch(e).then(i=>i.arrayBuffer());return WM.defaultModelFetcher=s,WM}var jv={},HM={},HSe;function YF(){if(HSe)return HM;HSe=1,Object.defineProperty(HM,"__esModule",{value:!0}),HM.log=void 0;const s=e=>i=>{console.log(`VAD | ${e} >`,i)};return HM.log={error:s("error"),debug:s("debug"),warn:s("warn")},HM}var VM={},VSe;function lG(){if(VSe)return VM;VSe=1,Object.defineProperty(VM,"__esModule",{value:!0}),VM.Message=void 0;var s;return(function(e){e.AudioFrame="AUDIO_FRAME",e.SpeechStart="SPEECH_START",e.VADMisfire="VAD_MISFIRE",e.SpeechEnd="SPEECH_END",e.SpeechStop="SPEECH_STOP",e.SpeechRealStart="SPEECH_REAL_START",e.FrameProcessed="FRAME_PROCESSED"})(s||(VM.Message=s={})),VM}var zSe;function Sme(){if(zSe)return jv;zSe=1,Object.defineProperty(jv,"__esModule",{value:!0}),jv.FrameProcessor=jv.validateOptions=jv.defaultFrameProcessorOptions=void 0;const s=YF(),e=lG();jv.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function i(a){(a.positiveSpeechThreshold<0||a.positiveSpeechThreshold>1)&&s.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(a.negativeSpeechThreshold<0||a.negativeSpeechThreshold>a.positiveSpeechThreshold)&&s.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),a.preSpeechPadMs<0&&s.log.error("preSpeechPadMs should be positive"),a.redemptionMs<0&&s.log.error("redemptionMs should be positive"),a.minSpeechMs<0&&s.log.error("minSpeechMs should be positive")}jv.validateOptions=i;const n=a=>{const l=a.reduce((d,u)=>(d.push(d.at(-1)+u.length),d),[0]),c=new Float32Array(l.at(-1));return a.forEach((d,u)=>{const h=l[u];c.set(d,h)}),c};function r(a,l){const c=Math.floor(a.redemptionMs/l),d=Math.floor(a.preSpeechPadMs/l),u=Math.floor(a.minSpeechMs/l);return{redemptionFrames:c,preSpeechPadFrames:d,minSpeechFrames:u}}class o{constructor(l,c,d,u){this.modelProcessFunc=l,this.modelResetFunc=c,this.options=d,this.msPerFrame=u,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=p=>{this.options={...this.options,...p};const{redemptionFrames:_,preSpeechPadFrames:m,minSpeechFrames:b}=r(this.options,this.msPerFrame);this.redemptionFrames=_,this.preSpeechPadFrames=m,this.minSpeechFrames=b},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=p=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(p):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=p=>{const _=this.audioBuffer;this.audioBuffer=[];const m=this.speaking;if(this.reset(),m)if(_.reduce((y,x)=>x.isSpeech?y+1:y,0)>=this.minSpeechFrames){const y=n(_.map(x=>x.frame));p({msg:e.Message.SpeechEnd,audio:y})}else p({msg:e.Message.VADMisfire});return{}},this.process=async(p,_)=>{if(!this.active)return;const m=await this.modelProcessFunc(p),b=m.isSpeech>=this.options.positiveSpeechThreshold;if(_({probs:m,msg:e.Message.FrameProcessed,frame:p}),this.audioBuffer.push({frame:p,isSpeech:b}),b&&(this.speechFrameCount++,this.redemptionCounter=0),b&&!this.speaking&&(this.speaking=!0,_({msg:e.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,_({msg:e.Message.SpeechRealStart})),m.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const y=this.audioBuffer;if(this.audioBuffer=[],y.reduce((S,k)=>k.isSpeech?S+1:S,0)>=this.minSpeechFrames){const S=n(y.map(k=>k.frame));_({msg:e.Message.SpeechEnd,audio:S})}else _({msg:e.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:h,preSpeechPadFrames:f,minSpeechFrames:g}=r(this.options,this.msPerFrame);this.redemptionFrames=h,this.preSpeechPadFrames=f,this.minSpeechFrames=g,this.reset()}}return jv.FrameProcessor=o,jv}var $v={};function ug(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var KX={exports:{}};/*!
|
|
958
958
|
* ONNX Runtime Web v1.26.0
|
|
959
959
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
960
960
|
* Licensed under the MIT License.
|
|
@@ -3808,7 +3808,7 @@ ${V}`,Y=R.createShaderModule({code:U,label:w.name});ts("verbose",()=>`[WebGPU] $
|
|
|
3808
3808
|
* ONNX Runtime Web v1.26.0
|
|
3809
3809
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
3810
3810
|
* Licensed under the MIT License.
|
|
3811
|
-
*/var JSe;function I2t(){return JSe||(JSe=1,(function(s,e){var i=(()=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,l=(de=>typeof ug<"u"?ug:typeof Proxy<"u"?new Proxy(de,{get:(be,Ne)=>(typeof ug<"u"?ug:be)[Ne]}):de)(function(de){if(typeof ug<"u")return ug.apply(this,arguments);throw Error('Dynamic require of "'+de+'" is not supported')}),c=(de,be)=>()=>(de&&(be=de(de=0)),be),d=(de,be)=>{for(var Ne in be)n(de,Ne,{get:be[Ne],enumerable:!0})},u=(de,be,Ne,Ve)=>{if(be&&typeof be=="object"||typeof be=="function")for(let Oe of o(be))!a.call(de,Oe)&&Oe!==Ne&&n(de,Oe,{get:()=>be[Oe],enumerable:!(Ve=r(be,Oe))||Ve.enumerable});return de},h=de=>u(n({},"__esModule",{value:!0}),de),f,g,p,_,m,b=c(()=>{f=new Map,g=[],p=(de,be,Ne)=>{if(be&&typeof be.init=="function"&&typeof be.createInferenceSessionHandler=="function"){let Ve=f.get(de);if(Ve===void 0)f.set(de,{backend:be,priority:Ne});else{if(Ve.priority>Ne)return;if(Ve.priority===Ne&&Ve.backend!==be)throw new Error(`cannot register backend "${de}" using priority ${Ne}`)}if(Ne>=0){let Oe=g.indexOf(de);Oe!==-1&&g.splice(Oe,1);for(let rt=0;rt<g.length;rt++)if(f.get(g[rt]).priority<=Ne){g.splice(rt,0,de);return}g.push(de)}return}throw new TypeError("not a valid backend")},_=async de=>{let be=f.get(de);if(!be)return"backend not found.";if(be.initialized)return be.backend;if(be.aborted)return be.error;{let Ne=!!be.initPromise;try{return Ne||(be.initPromise=be.backend.init(de)),await be.initPromise,be.initialized=!0,be.backend}catch(Ve){return Ne||(be.error=`${Ve}`,be.aborted=!0),be.error}finally{delete be.initPromise}}},m=async de=>{let be=de.executionProviders||[],Ne=be.map(dt=>typeof dt=="string"?dt:dt.name),Ve=Ne.length===0?g:Ne,Oe,rt=[],qe=new Set;for(let dt of Ve){let Tt=await _(dt);typeof Tt=="string"?rt.push({name:dt,err:Tt}):(Oe||(Oe=Tt),Oe===Tt&&qe.add(dt))}if(!Oe)throw new Error(`no available backend found. ERR: ${rt.map(dt=>`[${dt.name}] ${dt.err}`).join(", ")}`);for(let{name:dt,err:Tt}of rt)Ne.includes(dt)&&console.warn(`removing requested execution provider "${dt}" from session options because it is not available: ${Tt}`);let Ge=be.filter(dt=>qe.has(typeof dt=="string"?dt:dt.name));return[Oe,new Proxy(de,{get:(dt,Tt)=>Tt==="executionProviders"?Ge:Reflect.get(dt,Tt)})]}}),y=c(()=>{b()}),x,S=c(()=>{x="1.26.0"}),k,D,T=c(()=>{S(),k="warning",D={wasm:{},webgl:{},webgpu:{},versions:{common:x},set logLevel(de){if(de!==void 0){if(typeof de!="string"||["verbose","info","warning","error","fatal"].indexOf(de)===-1)throw new Error(`Unsupported logging level: ${de}`);k=de}},get logLevel(){return k}},Object.defineProperty(D,"logLevel",{enumerable:!0})}),N,A=c(()=>{T(),N=D}),O,$,P=c(()=>{O=(de,be)=>{let Ne=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);Ne.width=de.dims[3],Ne.height=de.dims[2];let Ve=Ne.getContext("2d");if(Ve!=null){let Oe,rt;(be==null?void 0:be.tensorLayout)!==void 0&&be.tensorLayout==="NHWC"?(Oe=de.dims[2],rt=de.dims[3]):(Oe=de.dims[3],rt=de.dims[2]);let qe=(be==null?void 0:be.format)!==void 0?be.format:"RGB",Ge=be==null?void 0:be.norm,dt,Tt;Ge===void 0||Ge.mean===void 0?dt=[255,255,255,255]:typeof Ge.mean=="number"?dt=[Ge.mean,Ge.mean,Ge.mean,Ge.mean]:(dt=[Ge.mean[0],Ge.mean[1],Ge.mean[2],0],Ge.mean[3]!==void 0&&(dt[3]=Ge.mean[3])),Ge===void 0||Ge.bias===void 0?Tt=[0,0,0,0]:typeof Ge.bias=="number"?Tt=[Ge.bias,Ge.bias,Ge.bias,Ge.bias]:(Tt=[Ge.bias[0],Ge.bias[1],Ge.bias[2],0],Ge.bias[3]!==void 0&&(Tt[3]=Ge.bias[3]));let $t=rt*Oe,Nt=0,wt=$t,Pi=$t*2,it=-1;qe==="RGBA"?(Nt=0,wt=$t,Pi=$t*2,it=$t*3):qe==="RGB"?(Nt=0,wt=$t,Pi=$t*2):qe==="RBG"&&(Nt=0,Pi=$t,wt=$t*2);for(let Qt=0;Qt<rt;Qt++)for(let hr=0;hr<Oe;hr++){let xn=(de.data[Nt++]-Tt[0])*dt[0],Cn=(de.data[wt++]-Tt[1])*dt[1],fr=(de.data[Pi++]-Tt[2])*dt[2],Yi=it===-1?255:(de.data[it++]-Tt[3])*dt[3];Ve.fillStyle="rgba("+xn+","+Cn+","+fr+","+Yi+")",Ve.fillRect(hr,Qt,1,1)}if("toDataURL"in Ne)return Ne.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},$=(de,be)=>{let Ne=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Ve;if(Ne!=null){let Oe,rt,qe;(be==null?void 0:be.tensorLayout)!==void 0&&be.tensorLayout==="NHWC"?(Oe=de.dims[2],rt=de.dims[1],qe=de.dims[3]):(Oe=de.dims[3],rt=de.dims[2],qe=de.dims[1]);let Ge=be!==void 0&&be.format!==void 0?be.format:"RGB",dt=be==null?void 0:be.norm,Tt,$t;dt===void 0||dt.mean===void 0?Tt=[255,255,255,255]:typeof dt.mean=="number"?Tt=[dt.mean,dt.mean,dt.mean,dt.mean]:(Tt=[dt.mean[0],dt.mean[1],dt.mean[2],255],dt.mean[3]!==void 0&&(Tt[3]=dt.mean[3])),dt===void 0||dt.bias===void 0?$t=[0,0,0,0]:typeof dt.bias=="number"?$t=[dt.bias,dt.bias,dt.bias,dt.bias]:($t=[dt.bias[0],dt.bias[1],dt.bias[2],0],dt.bias[3]!==void 0&&($t[3]=dt.bias[3]));let Nt=rt*Oe;if(be!==void 0&&(be.format!==void 0&&qe===4&&be.format!=="RGBA"||qe===3&&be.format!=="RGB"&&be.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let wt=4,Pi=0,it=1,Qt=2,hr=3,xn=0,Cn=Nt,fr=Nt*2,Yi=-1;Ge==="RGBA"?(xn=0,Cn=Nt,fr=Nt*2,Yi=Nt*3):Ge==="RGB"?(xn=0,Cn=Nt,fr=Nt*2):Ge==="RBG"&&(xn=0,fr=Nt,Cn=Nt*2),Ve=Ne.createImageData(Oe,rt);for(let Fr=0;Fr<rt*Oe;Pi+=wt,it+=wt,Qt+=wt,hr+=wt,Fr++)Ve.data[Pi]=(de.data[xn++]-$t[0])*Tt[0],Ve.data[it]=(de.data[Cn++]-$t[1])*Tt[1],Ve.data[Qt]=(de.data[fr++]-$t[2])*Tt[2],Ve.data[hr]=Yi===-1?255:(de.data[Yi++]-$t[3])*Tt[3]}else throw new Error("Can not access image data");return Ve}}),B,W,q,G,re,ie,K=c(()=>{Te(),B=(de,be)=>{if(de===void 0)throw new Error("Image buffer must be defined");if(be.height===void 0||be.width===void 0)throw new Error("Image height and width must be defined");if(be.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:Ne,width:Ve}=be,Oe=be.norm??{mean:255,bias:0},rt,qe;typeof Oe.mean=="number"?rt=[Oe.mean,Oe.mean,Oe.mean,Oe.mean]:rt=[Oe.mean[0],Oe.mean[1],Oe.mean[2],Oe.mean[3]??255],typeof Oe.bias=="number"?qe=[Oe.bias,Oe.bias,Oe.bias,Oe.bias]:qe=[Oe.bias[0],Oe.bias[1],Oe.bias[2],Oe.bias[3]??0];let Ge=be.format!==void 0?be.format:"RGBA",dt=be.tensorFormat!==void 0&&be.tensorFormat!==void 0?be.tensorFormat:"RGB",Tt=Ne*Ve,$t=dt==="RGBA"?new Float32Array(Tt*4):new Float32Array(Tt*3),Nt=4,wt=0,Pi=1,it=2,Qt=3,hr=0,xn=Tt,Cn=Tt*2,fr=-1;Ge==="RGB"&&(Nt=3,wt=0,Pi=1,it=2,Qt=-1),dt==="RGBA"?fr=Tt*3:dt==="RBG"?(hr=0,Cn=Tt,xn=Tt*2):dt==="BGR"&&(Cn=0,xn=Tt,hr=Tt*2);for(let Yi=0;Yi<Tt;Yi++,wt+=Nt,it+=Nt,Pi+=Nt,Qt+=Nt)$t[hr++]=(de[wt]+qe[0])/rt[0],$t[xn++]=(de[Pi]+qe[1])/rt[1],$t[Cn++]=(de[it]+qe[2])/rt[2],fr!==-1&&Qt!==-1&&($t[fr++]=(de[Qt]+qe[3])/rt[3]);return dt==="RGBA"?new ae("float32",$t,[1,4,Ne,Ve]):new ae("float32",$t,[1,3,Ne,Ve])},W=async(de,be)=>{let Ne=typeof HTMLImageElement<"u"&&de instanceof HTMLImageElement,Ve=typeof ImageData<"u"&&de instanceof ImageData,Oe=typeof ImageBitmap<"u"&&de instanceof ImageBitmap,rt=typeof de=="string",qe,Ge=be??{},dt=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},Tt=$t=>typeof HTMLCanvasElement<"u"&&$t instanceof HTMLCanvasElement||$t instanceof OffscreenCanvas?$t.getContext("2d"):null;if(Ne){let $t=dt();$t.width=de.width,$t.height=de.height;let Nt=Tt($t);if(Nt!=null){let wt=de.height,Pi=de.width;if(be!==void 0&&be.resizedHeight!==void 0&&be.resizedWidth!==void 0&&(wt=be.resizedHeight,Pi=be.resizedWidth),be!==void 0){if(Ge=be,be.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ge.tensorFormat="RGBA",Ge.height=wt,Ge.width=Pi}else Ge.tensorFormat="RGBA",Ge.height=wt,Ge.width=Pi;Nt.drawImage(de,0,0),qe=Nt.getImageData(0,0,Pi,wt).data}else throw new Error("Can not access image data")}else if(Ve){let $t,Nt;if(be!==void 0&&be.resizedWidth!==void 0&&be.resizedHeight!==void 0?($t=be.resizedHeight,Nt=be.resizedWidth):($t=de.height,Nt=de.width),be!==void 0&&(Ge=be),Ge.format="RGBA",Ge.height=$t,Ge.width=Nt,be!==void 0){let wt=dt();wt.width=Nt,wt.height=$t;let Pi=Tt(wt);if(Pi!=null)Pi.putImageData(de,0,0),qe=Pi.getImageData(0,0,Nt,$t).data;else throw new Error("Can not access image data")}else qe=de.data}else if(Oe){if(be===void 0)throw new Error("Please provide image config with format for Imagebitmap");let $t=dt();$t.width=de.width,$t.height=de.height;let Nt=Tt($t);if(Nt!=null){let wt=de.height,Pi=de.width;return Nt.drawImage(de,0,0,Pi,wt),qe=Nt.getImageData(0,0,Pi,wt).data,Ge.height=wt,Ge.width=Pi,B(qe,Ge)}else throw new Error("Can not access image data")}else{if(rt)return new Promise(($t,Nt)=>{let wt=dt(),Pi=Tt(wt);if(!de||!Pi)return Nt();let it=new Image;it.crossOrigin="Anonymous",it.src=de,it.onload=()=>{wt.width=it.width,wt.height=it.height,Pi.drawImage(it,0,0,wt.width,wt.height);let Qt=Pi.getImageData(0,0,wt.width,wt.height);Ge.height=wt.height,Ge.width=wt.width,$t(B(Qt.data,Ge))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(qe!==void 0)return B(qe,Ge);throw new Error("Input data provided is not supported - aborted tensor creation")},q=(de,be)=>{let{width:Ne,height:Ve,download:Oe,dispose:rt}=be,qe=[1,Ve,Ne,4];return new ae({location:"texture",type:"float32",texture:de,dims:qe,download:Oe,dispose:rt})},G=(de,be)=>{let{dataType:Ne,dims:Ve,download:Oe,dispose:rt}=be;return new ae({location:"gpu-buffer",type:Ne??"float32",gpuBuffer:de,dims:Ve,download:Oe,dispose:rt})},re=(de,be)=>{let{dataType:Ne,dims:Ve,download:Oe,dispose:rt}=be;return new ae({location:"ml-tensor",type:Ne??"float32",mlTensor:de,dims:Ve,download:Oe,dispose:rt})},ie=(de,be,Ne)=>new ae({location:"cpu-pinned",type:de,data:be,dims:Ne??[be.length]})}),Z,Q,ne,ge,Se=c(()=>{Z=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ne=!1,ge=()=>{if(!ne){ne=!0;let de=typeof BigInt64Array<"u"&&BigInt64Array.from,be=typeof BigUint64Array<"u"&&BigUint64Array.from,Ne=globalThis.Float16Array,Ve=typeof Ne<"u"&&Ne.from;de&&(Z.set("int64",BigInt64Array),Q.set(BigInt64Array,"int64")),be&&(Z.set("uint64",BigUint64Array),Q.set(BigUint64Array,"uint64")),Ve?(Z.set("float16",Ne),Q.set(Ne,"float16")):Z.set("float16",Uint16Array)}}}),Ee,$e,De=c(()=>{Te(),Ee=de=>{let be=1;for(let Ne=0;Ne<de.length;Ne++){let Ve=de[Ne];if(typeof Ve!="number"||!Number.isSafeInteger(Ve))throw new TypeError(`dims[${Ne}] must be an integer, got: ${Ve}`);if(Ve<0)throw new RangeError(`dims[${Ne}] must be a non-negative integer, got: ${Ve}`);be*=Ve}return be},$e=(de,be)=>{switch(de.location){case"cpu":return new ae(de.type,de.data,be);case"cpu-pinned":return new ae({location:"cpu-pinned",data:de.data,type:de.type,dims:be});case"texture":return new ae({location:"texture",texture:de.texture,type:de.type,dims:be});case"gpu-buffer":return new ae({location:"gpu-buffer",gpuBuffer:de.gpuBuffer,type:de.type,dims:be});case"ml-tensor":return new ae({location:"ml-tensor",mlTensor:de.mlTensor,type:de.type,dims:be});default:throw new Error(`tensorReshape: tensor location ${de.location} is not supported`)}}}),ae,Te=c(()=>{P(),K(),Se(),De(),ae=class{constructor(de,be,Ne){ge();let Ve,Oe;if(typeof de=="object"&&"location"in de)switch(this.dataLocation=de.location,Ve=de.type,Oe=de.dims,de.location){case"cpu-pinned":{let qe=Z.get(Ve);if(!qe)throw new TypeError(`unsupported type "${Ve}" to create tensor from pinned buffer`);if(!(de.data instanceof qe))throw new TypeError(`buffer should be of type ${qe.name}`);this.cpuData=de.data;break}case"texture":{if(Ve!=="float32")throw new TypeError(`unsupported type "${Ve}" to create tensor from texture`);this.gpuTextureData=de.texture,this.downloader=de.download,this.disposer=de.dispose;break}case"gpu-buffer":{if(Ve!=="float32"&&Ve!=="float16"&&Ve!=="int32"&&Ve!=="int64"&&Ve!=="uint32"&&Ve!=="uint8"&&Ve!=="bool"&&Ve!=="uint4"&&Ve!=="int4")throw new TypeError(`unsupported type "${Ve}" to create tensor from gpu buffer`);this.gpuBufferData=de.gpuBuffer,this.downloader=de.download,this.disposer=de.dispose;break}case"ml-tensor":{if(Ve!=="float32"&&Ve!=="float16"&&Ve!=="int32"&&Ve!=="int64"&&Ve!=="uint32"&&Ve!=="uint64"&&Ve!=="int8"&&Ve!=="uint8"&&Ve!=="bool"&&Ve!=="uint4"&&Ve!=="int4")throw new TypeError(`unsupported type "${Ve}" to create tensor from MLTensor`);this.mlTensorData=de.mlTensor,this.downloader=de.download,this.disposer=de.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let qe,Ge;if(typeof de=="string")if(Ve=de,Ge=Ne,de==="string"){if(!Array.isArray(be))throw new TypeError("A string tensor's data must be a string array.");qe=be}else{let dt=Z.get(de);if(dt===void 0)throw new TypeError(`Unsupported tensor type: ${de}.`);if(Array.isArray(be)){if(de==="float16"&&dt===Uint16Array||de==="uint4"||de==="int4")throw new TypeError(`Creating a ${de} tensor from number array is not supported. Please use ${dt.name} as data.`);de==="uint64"||de==="int64"?qe=dt.from(be,BigInt):qe=dt.from(be)}else if(be instanceof dt)qe=be;else if(be instanceof Uint8ClampedArray)if(de==="uint8")qe=Uint8Array.from(be);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(de==="float16"&&be instanceof Uint16Array&&dt!==Uint16Array)qe=new globalThis.Float16Array(be.buffer,be.byteOffset,be.length);else throw new TypeError(`A ${Ve} tensor's data must be type of ${dt}`)}else if(Ge=be,Array.isArray(de)){if(de.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let dt=typeof de[0];if(dt==="string")Ve="string",qe=de;else if(dt==="boolean")Ve="bool",qe=Uint8Array.from(de);else throw new TypeError(`Invalid element type of data array: ${dt}.`)}else if(de instanceof Uint8ClampedArray)Ve="uint8",qe=Uint8Array.from(de);else{let dt=Q.get(de.constructor);if(dt===void 0)throw new TypeError(`Unsupported type for tensor data: ${de.constructor}.`);Ve=dt,qe=de}if(Ge===void 0)Ge=[qe.length];else if(!Array.isArray(Ge))throw new TypeError("A tensor's dims must be a number array");Oe=Ge,this.cpuData=qe,this.dataLocation="cpu"}let rt=Ee(Oe);if(this.cpuData&&rt!==this.cpuData.length&&!((Ve==="uint4"||Ve==="int4")&&Math.ceil(rt/2)===this.cpuData.length))throw new Error(`Tensor's size(${rt}) does not match data length(${this.cpuData.length}).`);this.type=Ve,this.dims=Oe,this.size=rt}static async fromImage(de,be){return W(de,be)}static fromTexture(de,be){return q(de,be)}static fromGpuBuffer(de,be){return G(de,be)}static fromMLTensor(de,be){return re(de,be)}static fromPinnedBuffer(de,be,Ne){return ie(de,be,Ne)}toDataURL(de){return O(this,de)}toImageData(de){return $(this,de)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(de){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let be=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=be,de&&this.disposer&&(this.disposer(),this.disposer=void 0),be}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(de){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return $e(this,de)}}}),Ie,st=c(()=>{Te(),Ie=ae}),He,lt,Je,Ct,Ft,Ot,En=c(()=>{T(),He=(de,be)=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||console.timeStamp(`${de}::ORT::${be}`)},lt=(de,be)=>{var Oe;let Ne=((Oe=new Error().stack)==null?void 0:Oe.split(/\r\n|\r|\n/g))||[],Ve=!1;for(let rt=0;rt<Ne.length;rt++){if(Ve&&!Ne[rt].includes("TRACE_FUNC")){let qe=`FUNC_${de}::${Ne[rt].trim().split(" ")[1]}`;be&&(qe+=`::${be}`),He("CPU",qe);return}Ne[rt].includes("TRACE_FUNC")&&(Ve=!0)}},Je=de=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||lt("BEGIN",de)},Ct=de=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||lt("END",de)},Ft=de=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||console.time(`ORT::${de}`)},Ot=de=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||console.timeEnd(`ORT::${de}`)}}),Ji,cn=c(()=>{b(),st(),En(),Ji=class v6e{constructor(be){this.handler=be}async run(be,Ne,Ve){Je(),Ft("InferenceSession.run");let Oe={},rt={};if(typeof be!="object"||be===null||be instanceof Ie||Array.isArray(be))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let qe=!0;if(typeof Ne=="object"){if(Ne===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(Ne instanceof Ie)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(Ne)){if(Ne.length===0)throw new TypeError("'fetches' cannot be an empty array.");qe=!1;for(let Tt of Ne){if(typeof Tt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(Tt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${Tt}.`);Oe[Tt]=null}if(typeof Ve=="object"&&Ve!==null)rt=Ve;else if(typeof Ve<"u")throw new TypeError("'options' must be an object.")}else{let Tt=!1,$t=Object.getOwnPropertyNames(Ne);for(let Nt of this.outputNames)if($t.indexOf(Nt)!==-1){let wt=Ne[Nt];(wt===null||wt instanceof Ie)&&(Tt=!0,qe=!1,Oe[Nt]=wt)}if(Tt){if(typeof Ve=="object"&&Ve!==null)rt=Ve;else if(typeof Ve<"u")throw new TypeError("'options' must be an object.")}else rt=Ne}}else if(typeof Ne<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let Tt of this.inputNames)if(typeof be[Tt]>"u")throw new Error(`input '${Tt}' is missing in 'feeds'.`);if(qe)for(let Tt of this.outputNames)Oe[Tt]=null;let Ge=await this.handler.run(be,Oe,rt),dt={};for(let Tt in Ge)if(Object.hasOwnProperty.call(Ge,Tt)){let $t=Ge[Tt];$t instanceof Ie?dt[Tt]=$t:dt[Tt]=new Ie($t.type,$t.data,$t.dims)}return Ot("InferenceSession.run"),Ct(),dt}async release(){return this.handler.dispose()}static async create(be,Ne,Ve,Oe){Je(),Ft("InferenceSession.create");let rt,qe={};if(typeof be=="string"){if(rt=be,typeof Ne=="object"&&Ne!==null)qe=Ne;else if(typeof Ne<"u")throw new TypeError("'options' must be an object.")}else if(be instanceof Uint8Array){if(rt=be,typeof Ne=="object"&&Ne!==null)qe=Ne;else if(typeof Ne<"u")throw new TypeError("'options' must be an object.")}else if(be instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&be instanceof SharedArrayBuffer){let $t=be,Nt=0,wt=be.byteLength;if(typeof Ne=="object"&&Ne!==null)qe=Ne;else if(typeof Ne=="number"){if(Nt=Ne,!Number.isSafeInteger(Nt))throw new RangeError("'byteOffset' must be an integer.");if(Nt<0||Nt>=$t.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${$t.byteLength}).`);if(wt=be.byteLength-Nt,typeof Ve=="number"){if(wt=Ve,!Number.isSafeInteger(wt))throw new RangeError("'byteLength' must be an integer.");if(wt<=0||Nt+wt>$t.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${$t.byteLength-Nt}].`);if(typeof Oe=="object"&&Oe!==null)qe=Oe;else if(typeof Oe<"u")throw new TypeError("'options' must be an object.")}else if(typeof Ve<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof Ne<"u")throw new TypeError("'options' must be an object.");rt=new Uint8Array($t,Nt,wt)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ge,dt]=await m(qe),Tt=await Ge.createInferenceSessionHandler(rt,dt);return Ot("InferenceSession.create"),Ct(),new v6e(Tt)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Tn,Ts=c(()=>{cn(),Tn=Ji}),ds=c(()=>{}),rr=c(()=>{}),Is=c(()=>{}),vo=c(()=>{}),Ko={};d(Ko,{InferenceSession:()=>Tn,TRACE:()=>He,TRACE_EVENT_BEGIN:()=>Ft,TRACE_EVENT_END:()=>Ot,TRACE_FUNC_BEGIN:()=>Je,TRACE_FUNC_END:()=>Ct,Tensor:()=>Ie,env:()=>N,registerBackend:()=>p});var es=c(()=>{y(),A(),Ts(),st(),ds(),rr(),En(),Is(),vo()}),ii=c(()=>{}),bi={};d(bi,{default:()=>ys});var Fi,Ni,ys,Gr=c(()=>{var de;sv(),Da(),Kr(),Fi="ort-wasm-proxy-worker",Ni=((de=globalThis.self)==null?void 0:de.name)===Fi,Ni&&(self.onmessage=be=>{let{type:Ne,in:Ve}=be.data;try{switch(Ne){case"init-wasm":Kl(Ve.wasm).then(()=>{Ja(Ve).then(()=>{postMessage({type:Ne})},Oe=>{postMessage({type:Ne,err:Oe})})},Oe=>{postMessage({type:Ne,err:Oe})});break;case"init-ep":{let{epName:Oe,env:rt}=Ve;Fd(rt,Oe).then(()=>{postMessage({type:Ne})},qe=>{postMessage({type:Ne,err:qe})});break}case"copy-from":{let{buffer:Oe}=Ve,rt=ts(Oe);postMessage({type:Ne,out:rt});break}case"create":{let{model:Oe,options:rt}=Ve;jd(Oe,rt).then(qe=>{postMessage({type:Ne,out:qe})},qe=>{postMessage({type:Ne,err:qe})});break}case"release":lm(Ve),postMessage({type:Ne});break;case"run":{let{sessionId:Oe,inputIndices:rt,inputs:qe,outputIndices:Ge,options:dt}=Ve;St(Oe,rt,qe,Ge,new Array(Ge.length).fill(null),dt).then(Tt=>{Tt.some($t=>$t[3]!=="cpu")?postMessage({type:Ne,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:Ne,out:Tt},Vy([...qe,...Tt]))},Tt=>{postMessage({type:Ne,err:Tt})});break}case"end-profiling":Ru(Ve),postMessage({type:Ne});break;default:}}catch(Oe){postMessage({type:Ne,err:Oe})}}),ys=Ni?null:be=>new Worker(be??fs,{type:"classic",name:Fi})}),xl,La,fs,Ea,bo,ft,Dt,xi,An,Ns,Hn,Ks,Cl,Kr=c(()=>{ii(),xl=typeof location>"u"?void 0:location.origin,La=()=>{var de,be;return typeof document<"u"?(de=document.currentScript)==null?void 0:de.src:typeof self<"u"?(be=self.location)==null?void 0:be.href:void 0},fs=La(),Ea=()=>{if(fs&&!fs.startsWith("blob:"))return fs.substring(0,fs.lastIndexOf("/")+1)},bo=(de,be)=>{try{let Ne=be??fs;return(Ne?new URL(de,Ne):new URL(de)).origin===xl}catch{return!1}},ft=(de,be)=>{let Ne=be??fs;try{return(Ne?new URL(de,Ne):new URL(de)).href}catch{return}},Dt=(de,be)=>`${be??"./"}${de}`,xi=async de=>{let be=await(await fetch(de,{credentials:"same-origin"})).blob();return URL.createObjectURL(be)},An=async de=>(await import(de)).default,Ns=(Gr(),h(bi)).default,Hn=async()=>{if(!fs)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(bo(fs))return[void 0,Ns()];let de=await xi(fs);return[de,Ns(de)]},Ks=void 0,Cl=async(de,be,Ne,Ve)=>{let Oe=Ks&&!(de||be);if(Oe)if(fs)Oe=bo(fs)||Ve&&!Ne;else if(Ve&&!Ne)Oe=!0;else throw new Error("cannot determine the script source URL.");if(Oe)return[void 0,Ks];{let rt="ort-wasm-simd-threaded.mjs",qe=de??ft(rt,be),Ge=Ne&&qe&&!bo(qe,be),dt=Ge?await xi(qe):qe??Dt(rt,be);return[Ge?dt:void 0,await An(dt)]}}}),Ya,Xa,gs,la,Za,ca,Ec,Kl,Gi,Da=c(()=>{Kr(),Xa=!1,gs=!1,la=!1,Za=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},ca=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Ec=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Kl=async de=>{if(Xa)return Promise.resolve();if(gs)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(la)throw new Error("previous call to 'initializeWebAssembly()' failed.");gs=!0;let be=de.initTimeout,Ne=de.numThreads;if(de.simd!==!1){if(de.simd==="relaxed"){if(!Ec())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ca())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Ve=Za();Ne>1&&!Ve&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+Ne+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),de.numThreads=Ne=1);let Oe=de.wasmPaths,rt=typeof Oe=="string"?Oe:void 0,qe=Oe==null?void 0:Oe.mjs,Ge=(qe==null?void 0:qe.href)??qe,dt=Oe==null?void 0:Oe.wasm,Tt=(dt==null?void 0:dt.href)??dt,$t=de.wasmBinary,[Nt,wt]=await Cl(Ge,rt,Ne>1,!!$t||!!Tt),Pi=!1,it=[];if(be>0&&it.push(new Promise(Qt=>{setTimeout(()=>{Pi=!0,Qt()},be)})),it.push(new Promise((Qt,hr)=>{let xn={numThreads:Ne};if($t)xn.wasmBinary=$t,xn.locateFile=Cn=>Cn;else if(Tt||rt)xn.locateFile=Cn=>Tt??rt+Cn;else if(Ge&&Ge.indexOf("blob:")!==0)xn.locateFile=Cn=>new URL(Cn,Ge).href;else if(Nt){let Cn=Ea();Cn&&(xn.locateFile=fr=>Cn+fr)}wt(xn).then(Cn=>{gs=!1,Xa=!0,Ya=Cn,Qt(),Nt&&URL.revokeObjectURL(Nt)},Cn=>{gs=!1,la=!0,hr(Cn)})})),await Promise.race(it),Pi)throw new Error(`WebAssembly backend initializing failed due to timeout: ${be}ms`)},Gi=()=>{if(Xa&&Ya)return Ya;throw new Error("WebAssembly is not initialized yet.")}}),Vn,da,Ii,ld=c(()=>{Da(),Vn=(de,be)=>{let Ne=Gi(),Ve=Ne.lengthBytesUTF8(de)+1,Oe=Ne._malloc(Ve);return Ne.stringToUTF8(de,Oe,Ve),be.push(Oe),Oe},da=(de,be,Ne,Ve)=>{if(typeof de=="object"&&de!==null){if(Ne.has(de))throw new Error("Circular reference in options");Ne.add(de)}Object.entries(de).forEach(([Oe,rt])=>{let qe=be?be+Oe:Oe;if(typeof rt=="object")da(rt,qe+".",Ne,Ve);else if(typeof rt=="string"||typeof rt=="number")Ve(qe,rt.toString());else if(typeof rt=="boolean")Ve(qe,rt?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof rt}`)})},Ii=de=>{let be=Gi(),Ne=be.stackSave();try{let Ve=be.PTR_SIZE,Oe=be.stackAlloc(2*Ve);be._OrtGetLastError(Oe,Oe+Ve);let rt=Number(be.getValue(Oe,Ve===4?"i32":"i64")),qe=be.getValue(Oe+Ve,"*"),Ge=qe?be.UTF8ToString(qe):"";throw new Error(`${de} ERROR_CODE: ${rt}, ERROR_MESSAGE: ${Ge}`)}finally{be.stackRestore(Ne)}}}),Od,Nf=c(()=>{Da(),ld(),Od=de=>{let be=Gi(),Ne=0,Ve=[],Oe=de||{};try{if((de==null?void 0:de.logSeverityLevel)===void 0)Oe.logSeverityLevel=2;else if(typeof de.logSeverityLevel!="number"||!Number.isInteger(de.logSeverityLevel)||de.logSeverityLevel<0||de.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${de.logSeverityLevel}`);if((de==null?void 0:de.logVerbosityLevel)===void 0)Oe.logVerbosityLevel=0;else if(typeof de.logVerbosityLevel!="number"||!Number.isInteger(de.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${de.logVerbosityLevel}`);(de==null?void 0:de.terminate)===void 0&&(Oe.terminate=!1);let rt=0;return(de==null?void 0:de.tag)!==void 0&&(rt=Vn(de.tag,Ve)),Ne=be._OrtCreateRunOptions(Oe.logSeverityLevel,Oe.logVerbosityLevel,!!Oe.terminate,rt),Ne===0&&Ii("Can't create run options."),(de==null?void 0:de.extra)!==void 0&&da(de.extra,"",new WeakSet,(qe,Ge)=>{let dt=Vn(qe,Ve),Tt=Vn(Ge,Ve);be._OrtAddRunConfigEntry(Ne,dt,Tt)!==0&&Ii(`Can't set a run config entry: ${qe} - ${Ge}.`)}),[Ne,Ve]}catch(rt){throw Ne!==0&&be._OrtReleaseRunOptions(Ne),Ve.forEach(qe=>be._free(qe)),rt}}}),Mi,Ke,zt,vi,$s,yo,Fn=c(()=>{Da(),ld(),Mi=de=>{switch(de){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${de}`)}},Ke=de=>{switch(de){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${de}`)}},zt=de=>{de.extra||(de.extra={}),de.extra.session||(de.extra.session={});let be=de.extra.session;be.use_ort_model_bytes_directly||(be.use_ort_model_bytes_directly="1"),de.executionProviders&&de.executionProviders.some(Ne=>(typeof Ne=="string"?Ne:Ne.name)==="webgpu")&&(de.enableMemPattern=!1)},vi=(de,be,Ne,Ve)=>{let Oe=Vn(be,Ve),rt=Vn(Ne,Ve);Gi()._OrtAddSessionConfigEntry(de,Oe,rt)!==0&&Ii(`Can't set a session config entry: ${be} - ${Ne}.`)},$s=async(de,be,Ne)=>{let Ve=be.executionProviders;for(let Oe of Ve){let rt=typeof Oe=="string"?Oe:Oe.name,qe=[];switch(rt){case"webnn":if(rt="WEBNN",vi(de,"session.disable_quant_qdq","1",Ne),vi(de,"session.disable_qdq_constant_folding","1",Ne),typeof Oe!="string"){let Nt=Oe==null?void 0:Oe.deviceType;Nt&&vi(de,"deviceType",Nt,Ne)}break;case"webgpu":if(rt="JS",typeof Oe!="string"){let Nt=Oe;if(Nt!=null&&Nt.preferredLayout){if(Nt.preferredLayout!=="NCHW"&&Nt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${Nt.preferredLayout}`);vi(de,"preferredLayout",Nt.preferredLayout,Ne)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${rt}`)}let Ge=Vn(rt,Ne),dt=qe.length,Tt=0,$t=0;if(dt>0){Tt=Gi()._malloc(dt*Gi().PTR_SIZE),Ne.push(Tt),$t=Gi()._malloc(dt*Gi().PTR_SIZE),Ne.push($t);for(let Nt=0;Nt<dt;Nt++)Gi().setValue(Tt+Nt*Gi().PTR_SIZE,qe[Nt][0],"*"),Gi().setValue($t+Nt*Gi().PTR_SIZE,qe[Nt][1],"*")}await Gi()._OrtAppendExecutionProvider(de,Ge,Tt,$t,dt)!==0&&Ii(`Can't append execution provider: ${rt}.`)}},yo=async de=>{let be=Gi(),Ne=0,Ve=[],Oe=de||{};zt(Oe);try{let rt=Mi(Oe.graphOptimizationLevel??"all"),qe=Ke(Oe.executionMode??"sequential"),Ge=typeof Oe.logId=="string"?Vn(Oe.logId,Ve):0,dt=Oe.logSeverityLevel??2;if(!Number.isInteger(dt)||dt<0||dt>4)throw new Error(`log severity level is not valid: ${dt}`);let Tt=Oe.logVerbosityLevel??0;if(!Number.isInteger(Tt)||Tt<0||Tt>4)throw new Error(`log verbosity level is not valid: ${Tt}`);let $t=typeof Oe.optimizedModelFilePath=="string"?Vn(Oe.optimizedModelFilePath,Ve):0;if(Ne=be._OrtCreateSessionOptions(rt,!!Oe.enableCpuMemArena,!!Oe.enableMemPattern,qe,!!Oe.enableProfiling,0,Ge,dt,Tt,$t),Ne===0&&Ii("Can't create session options."),Oe.executionProviders&&await $s(Ne,Oe,Ve),Oe.enableGraphCapture!==void 0){if(typeof Oe.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Oe.enableGraphCapture}`);vi(Ne,"enableGraphCapture",Oe.enableGraphCapture.toString(),Ve)}if(Oe.freeDimensionOverrides)for(let[Nt,wt]of Object.entries(Oe.freeDimensionOverrides)){if(typeof Nt!="string")throw new Error(`free dimension override name must be a string: ${Nt}`);if(typeof wt!="number"||!Number.isInteger(wt)||wt<0)throw new Error(`free dimension override value must be a non-negative integer: ${wt}`);let Pi=Vn(Nt,Ve);be._OrtAddFreeDimensionOverride(Ne,Pi,wt)!==0&&Ii(`Can't set a free dimension override: ${Nt} - ${wt}.`)}return Oe.extra!==void 0&&da(Oe.extra,"",new WeakSet,(Nt,wt)=>{vi(Ne,Nt,wt,Ve)}),[Ne,Ve]}catch(rt){throw Ne!==0&&be._OrtReleaseSessionOptions(Ne)!==0&&Ii("Can't release session options."),Ve.forEach(qe=>be._free(qe)),rt}}}),Ys,or,vr,Ci,Re,It,ui,Bn,Jt=c(()=>{Ys=de=>{switch(de){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${de}`)}},or=de=>{switch(de){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${de}`)}},vr=(de,be)=>{let Ne=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][de],Ve=typeof be=="number"?be:be.reduce((Oe,rt)=>Oe*rt,1);return Ne>0?Math.ceil(Ve*Ne):void 0},Ci=de=>{switch(de){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${de}`)}},Re=de=>{switch(de){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${de}`)}},It=de=>de==="float32"||de==="float16"||de==="int32"||de==="int64"||de==="uint32"||de==="uint8"||de==="bool"||de==="uint4"||de==="int4",ui=de=>de==="float32"||de==="float16"||de==="int32"||de==="int64"||de==="uint32"||de==="uint64"||de==="int8"||de==="uint8"||de==="bool"||de==="uint4"||de==="int4",Bn=de=>{switch(de){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${de}`)}}}),zn,ao=c(()=>{ii(),zn=async de=>{if(typeof de=="string"){let be=await fetch(de);if(!be.ok)throw new Error(`failed to load external data file: ${de}`);let Ne=be.headers.get("Content-Length"),Ve=Ne?parseInt(Ne,10):0;if(Ve<1073741824)return new Uint8Array(await be.arrayBuffer());{if(!be.body)throw new Error(`failed to load external data file: ${de}, no response body.`);let Oe=be.body.getReader(),rt;try{rt=new ArrayBuffer(Ve)}catch(Ge){if(Ge instanceof RangeError){let dt=Math.ceil(Ve/65536);rt=new WebAssembly.Memory({initial:dt,maximum:dt}).buffer}else throw Ge}let qe=0;for(;;){let{done:Ge,value:dt}=await Oe.read();if(Ge)break;let Tt=dt.byteLength;new Uint8Array(rt,qe,Tt).set(dt),qe+=Tt}return new Uint8Array(rt,0,Ve)}}else return de instanceof Blob?new Uint8Array(await de.arrayBuffer()):de instanceof Uint8Array?de:new Uint8Array(de)}}),Qa,Ja,Fd,Xs,Bd,Nu,ts,jd,lm,Dh,St,Ru,Vy,sv=c(()=>{es(),Nf(),Fn(),Jt(),Da(),ld(),ao(),Qa=(de,be)=>{Gi()._OrtInit(de,be)!==0&&Ii("Can't initialize onnxruntime.")},Ja=async de=>{Qa(de.wasm.numThreads,Re(de.logLevel))},Fd=async(de,be)=>{var Ve,Oe;(Oe=(Ve=Gi()).asyncInit)==null||Oe.call(Ve);let Ne=de.webgpu.adapter;if(be==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(Ne){if(typeof Ne.limits!="object"||typeof Ne.features!="object"||typeof Ne.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let rt=de.webgpu.powerPreference;if(rt!==void 0&&rt!=="low-power"&&rt!=="high-performance")throw new Error(`Invalid powerPreference setting: "${rt}"`);let qe=de.webgpu.forceFallbackAdapter;if(qe!==void 0&&typeof qe!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${qe}"`);if(Ne=await navigator.gpu.requestAdapter({powerPreference:rt,forceFallbackAdapter:qe}),!Ne)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(be==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Xs=new Map,Bd=de=>{let be=Gi(),Ne=be.stackSave();try{let Ve=be.PTR_SIZE,Oe=be.stackAlloc(2*Ve);be._OrtGetInputOutputCount(de,Oe,Oe+Ve)!==0&&Ii("Can't get session input/output count.");let rt=Ve===4?"i32":"i64";return[Number(be.getValue(Oe,rt)),Number(be.getValue(Oe+Ve,rt))]}finally{be.stackRestore(Ne)}},Nu=(de,be)=>{let Ne=Gi(),Ve=Ne.stackSave(),Oe=0;try{let rt=Ne.PTR_SIZE,qe=Ne.stackAlloc(2*rt);Ne._OrtGetInputOutputMetadata(de,be,qe,qe+rt)!==0&&Ii("Can't get session input/output metadata.");let Ge=Number(Ne.getValue(qe,"*"));Oe=Number(Ne.getValue(qe+rt,"*"));let dt=Ne.HEAP32[Oe/4];if(dt===0)return[Ge,0];let Tt=Ne.HEAPU32[Oe/4+1],$t=[];for(let Nt=0;Nt<Tt;Nt++){let wt=Number(Ne.getValue(Oe+8+Nt*rt,"*"));$t.push(wt!==0?Ne.UTF8ToString(wt):Number(Ne.getValue(Oe+8+(Nt+Tt)*rt,"*")))}return[Ge,dt,$t]}finally{Ne.stackRestore(Ve),Oe!==0&&Ne._OrtFree(Oe)}},ts=de=>{let be=Gi(),Ne=be._malloc(de.byteLength);if(Ne===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${de.byteLength}.`);return be.HEAPU8.set(de,Ne),[Ne,de.byteLength]},jd=async(de,be)=>{var $t,Nt,wt;let Ne,Ve,Oe=Gi();Array.isArray(de)?[Ne,Ve]=de:de.buffer===Oe.HEAPU8.buffer?[Ne,Ve]=[de.byteOffset,de.byteLength]:[Ne,Ve]=ts(de);let rt=0,qe=0,Ge=[],dt=[],Tt=[];try{if([qe,Ge]=await yo(be),(be==null?void 0:be.externalData)&&Oe.mountExternalData){let Fr=[];for(let ps of be.externalData){let Ta=typeof ps=="string"?ps:ps.path;Fr.push(zn(typeof ps=="string"?ps:ps.data).then(kl=>{Oe.mountExternalData(Ta,kl)}))}await Promise.all(Fr)}for(let Fr of(be==null?void 0:be.executionProviders)??[])if((typeof Fr=="string"?Fr:Fr.name)==="webnn"){if(Oe.shouldTransferToMLTensor=!1,typeof Fr!="string"){let ps=Fr,Ta=ps==null?void 0:ps.context,kl=ps==null?void 0:ps.gpuDevice,Yl=ps==null?void 0:ps.deviceType,ov=ps==null?void 0:ps.powerPreference;Ta?Oe.currentContext=Ta:kl?Oe.currentContext=await Oe.webnnCreateMLContext(kl):Oe.currentContext=await Oe.webnnCreateMLContext({deviceType:Yl,powerPreference:ov})}else Oe.currentContext=await Oe.webnnCreateMLContext();break}rt=await Oe._OrtCreateSession(Ne,Ve,qe),($t=Oe.webgpuOnCreateSession)==null||$t.call(Oe,rt),rt===0&&Ii("Can't create a session."),(Nt=Oe.jsepOnCreateSession)==null||Nt.call(Oe),Oe.currentContext&&(Oe.webnnRegisterMLContext(rt,Oe.currentContext),Oe.currentContext=void 0,Oe.shouldTransferToMLTensor=!0);let[Pi,it]=Bd(rt),Qt=!!(be!=null&&be.enableGraphCapture),hr=[],xn=[],Cn=[],fr=[],Yi=[];for(let Fr=0;Fr<Pi;Fr++){let[ps,Ta,kl]=Nu(rt,Fr);ps===0&&Ii("Can't get an input name."),dt.push(ps);let Yl=Oe.UTF8ToString(ps);hr.push(Yl),Cn.push(Ta===0?{name:Yl,isTensor:!1}:{name:Yl,isTensor:!0,type:or(Ta),shape:kl})}for(let Fr=0;Fr<it;Fr++){let[ps,Ta,kl]=Nu(rt,Fr+Pi);ps===0&&Ii("Can't get an output name."),Tt.push(ps);let Yl=Oe.UTF8ToString(ps);xn.push(Yl),fr.push(Ta===0?{name:Yl,isTensor:!1}:{name:Yl,isTensor:!0,type:or(Ta),shape:kl})}return Xs.set(rt,[rt,dt,Tt,null,Qt,!1]),[rt,hr,xn,Cn,fr]}catch(Pi){throw dt.forEach(it=>Oe._OrtFree(it)),Tt.forEach(it=>Oe._OrtFree(it)),rt!==0&&Oe._OrtReleaseSession(rt)!==0&&Ii("Can't release session."),Pi}finally{Oe._free(Ne),qe!==0&&Oe._OrtReleaseSessionOptions(qe)!==0&&Ii("Can't release session options."),Ge.forEach(Pi=>Oe._free(Pi)),(wt=Oe.unmountExternalData)==null||wt.call(Oe)}},lm=de=>{var dt,Tt,$t;let be=Gi(),Ne=Xs.get(de);if(!Ne)throw new Error(`cannot release session. invalid session id: ${de}`);let[Ve,Oe,rt,qe,Ge]=Ne;qe&&(Ge&&be._OrtClearBoundOutputs(qe.handle)!==0&&Ii("Can't clear bound outputs."),be._OrtReleaseBinding(qe.handle)!==0&&Ii("Can't release IO binding.")),(dt=be.jsepOnReleaseSession)==null||dt.call(be,de),(Tt=be.webnnOnReleaseSession)==null||Tt.call(be,de),($t=be.webgpuOnReleaseSession)==null||$t.call(be,de),Oe.forEach(Nt=>be._OrtFree(Nt)),rt.forEach(Nt=>be._OrtFree(Nt)),be._OrtReleaseSession(Ve)!==0&&Ii("Can't release session."),Xs.delete(de)},Dh=async(de,be,Ne,Ve,Oe,rt,qe=!1)=>{if(!de){be.push(0);return}let Ge=Gi(),dt=Ge.PTR_SIZE,Tt=de[0],$t=de[1],Nt=de[3],wt=Nt,Pi,it;if(Tt==="string"&&(Nt==="gpu-buffer"||Nt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(qe&&Nt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${rt} when enableGraphCapture is true.`);if(Nt==="gpu-buffer"){let xn=de[2].gpuBuffer;it=vr(Ys(Tt),$t);{let Cn=Ge.jsepRegisterBuffer;if(!Cn)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Pi=Cn(Ve,rt,xn,it)}}else if(Nt==="ml-tensor"){let xn=de[2].mlTensor;it=vr(Ys(Tt),$t);let Cn=Ge.webnnRegisterMLTensor;if(!Cn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Pi=Cn(Ve,xn,Ys(Tt),$t)}else{let xn=de[2];if(Array.isArray(xn)){it=dt*xn.length,Pi=Ge._malloc(it),Ne.push(Pi);for(let Cn=0;Cn<xn.length;Cn++){if(typeof xn[Cn]!="string")throw new TypeError(`tensor data at index ${Cn} is not a string`);Ge.setValue(Pi+Cn*dt,Vn(xn[Cn],Ne),"*")}}else{let Cn=Ge.webnnIsGraphInput,fr=Ge.webnnIsGraphOutput;if(Tt!=="string"&&Cn&&fr){let Yi=Ge.UTF8ToString(Oe);if(Cn(Ve,Yi)||fr(Ve,Yi)){let Fr=Ys(Tt);it=vr(Fr,$t),wt="ml-tensor";let ps=Ge.webnnCreateTemporaryTensor,Ta=Ge.webnnUploadTensor;if(!ps||!Ta)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let kl=await ps(Ve,Fr,$t);Ta(kl,new Uint8Array(xn.buffer,xn.byteOffset,xn.byteLength)),Pi=kl}else it=xn.byteLength,Pi=Ge._malloc(it),Ne.push(Pi),Ge.HEAPU8.set(new Uint8Array(xn.buffer,xn.byteOffset,it),Pi)}else it=xn.byteLength,Pi=Ge._malloc(it),Ne.push(Pi),Ge.HEAPU8.set(new Uint8Array(xn.buffer,xn.byteOffset,it),Pi)}}let Qt=Ge.stackSave(),hr=Ge.stackAlloc(4*$t.length);try{$t.forEach((Cn,fr)=>Ge.setValue(hr+fr*dt,Cn,dt===4?"i32":"i64"));let xn=Ge._OrtCreateTensor(Ys(Tt),Pi,it,hr,$t.length,Bn(wt));xn===0&&Ii(`Can't create tensor for input/output. session=${Ve}, index=${rt}.`),be.push(xn)}finally{Ge.stackRestore(Qt)}},St=async(de,be,Ne,Ve,Oe,rt)=>{var Xl,Ky,X1;let qe=Gi(),Ge=qe.PTR_SIZE,dt=Xs.get(de);if(!dt)throw new Error(`cannot run inference. invalid session id: ${de}`);let Tt=dt[0],$t=dt[1],Nt=dt[2],wt=dt[3],Pi=dt[4];dt[5];let it=be.length,Qt=Ve.length,hr=0,xn=[],Cn=[],fr=[],Yi=[],Fr=[],ps=qe.stackSave(),Ta=qe.stackAlloc(it*Ge),kl=qe.stackAlloc(it*Ge),Yl=qe.stackAlloc(Qt*Ge),ov=qe.stackAlloc(Qt*Ge);try{[hr,xn]=Od(rt),Ft("wasm prepareInputOutputTensor");for(let is=0;is<it;is++)await Dh(Ne[is],Cn,Yi,de,$t[be[is]],be[is],Pi);for(let is=0;is<Qt;is++)await Dh(Oe[is],fr,Yi,de,Nt[Ve[is]],it+Ve[is],Pi);Ot("wasm prepareInputOutputTensor");for(let is=0;is<it;is++)qe.setValue(Ta+is*Ge,Cn[is],"*"),qe.setValue(kl+is*Ge,$t[be[is]],"*");for(let is=0;is<Qt;is++)qe.setValue(Yl+is*Ge,fr[is],"*"),qe.setValue(ov+is*Ge,Nt[Ve[is]],"*");(Xl=qe.jsepOnRunStart)==null||Xl.call(qe,Tt),(Ky=qe.webnnOnRunStart)==null||Ky.call(qe,Tt);let Ia;Ia=await qe._OrtRun(Tt,kl,Ta,it,ov,Qt,Yl,hr),Ia!==0&&Ii("failed to call OrtRun().");let Mu=[],Z1=[];Ft("wasm ProcessOutputTensor");for(let is=0;is<Qt;is++){let Hd=Number(qe.getValue(Yl+is*Ge,"*"));if(Hd===fr[is]||Fr.includes(fr[is])){Mu.push(Oe[is]),Hd!==fr[is]&&qe._OrtReleaseTensor(Hd)!==0&&Ii("Can't release tensor.");continue}let hE=qe.stackSave(),Rh=qe.stackAlloc(4*Ge),dm=!1,Yo,Zl=0;try{qe._OrtGetTensorData(Hd,Rh,Rh+Ge,Rh+2*Ge,Rh+3*Ge)!==0&&Ii(`Can't access output tensor data on index ${is}.`);let Yy=Ge===4?"i32":"i64",Ql=Number(qe.getValue(Rh,Yy));Zl=qe.getValue(Rh+Ge,"*");let Q1=qe.getValue(Rh+Ge*2,"*"),fE=Number(qe.getValue(Rh+Ge*3,Yy)),Ah=[];for(let Xo=0;Xo<fE;Xo++)Ah.push(Number(qe.getValue(Q1+Xo*Ge,Yy)));qe._OrtFree(Q1)!==0&&Ii("Can't free memory for tensor dims.");let Vd=Ah.reduce((Xo,lo)=>Xo*lo,1);Yo=or(Ql);let Pu=wt==null?void 0:wt.outputPreferredLocations[Ve[is]];if(Yo==="string"){if(Pu==="gpu-buffer"||Pu==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Xo=[];for(let lo=0;lo<Vd;lo++){let zd=qe.getValue(Zl+lo*Ge,"*"),J1=qe.getValue(Zl+(lo+1)*Ge,"*"),ex=lo===Vd-1?void 0:J1-zd;Xo.push(qe.UTF8ToString(zd,ex))}Mu.push([Yo,Ah,Xo,"cpu"])}else if(Pu==="gpu-buffer"&&Vd>0){let Xo=qe.jsepGetBuffer;if(!Xo)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let lo=Xo(Zl),zd=vr(Ql,Vd);if(zd===void 0||!It(Yo))throw new Error(`Unsupported data type: ${Yo}`);dm=!0,Mu.push([Yo,Ah,{gpuBuffer:lo,download:qe.jsepCreateDownloader(lo,zd,Yo),dispose:()=>{qe._OrtReleaseTensor(Hd)!==0&&Ii("Can't release tensor.")}},"gpu-buffer"])}else if(Pu==="ml-tensor"&&Vd>0){let Xo=qe.webnnEnsureTensor,lo=qe.webnnIsGraphInputOutputTypeSupported;if(!Xo||!lo)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(vr(Ql,Vd)===void 0||!ui(Yo))throw new Error(`Unsupported data type: ${Yo}`);if(!lo(de,Yo,!1))throw new Error(`preferredLocation "ml-tensor" for ${Yo} output is not supported by current WebNN Context.`);let zd=await Xo(de,Zl,Ql,Ah,!1);dm=!0,Mu.push([Yo,Ah,{mlTensor:zd,download:qe.webnnCreateMLTensorDownloader(Zl,Yo),dispose:()=>{qe.webnnReleaseTensorId(Zl),qe._OrtReleaseTensor(Hd)}},"ml-tensor"])}else if(Pu==="ml-tensor-cpu-output"&&Vd>0){let Xo=qe.webnnCreateMLTensorDownloader(Zl,Yo)(),lo=Mu.length;dm=!0,Z1.push((async()=>{let zd=[lo,await Xo];return qe.webnnReleaseTensorId(Zl),qe._OrtReleaseTensor(Hd),zd})()),Mu.push([Yo,Ah,[],"cpu"])}else{let Xo=Ci(Yo),lo=new Xo(Vd);new Uint8Array(lo.buffer,lo.byteOffset,lo.byteLength).set(qe.HEAPU8.subarray(Zl,Zl+lo.byteLength)),Mu.push([Yo,Ah,lo,"cpu"])}}finally{qe.stackRestore(hE),Yo==="string"&&Zl&&qe._free(Zl),dm||qe._OrtReleaseTensor(Hd)}}wt&&!Pi&&(qe._OrtClearBoundOutputs(wt.handle)!==0&&Ii("Can't clear bound outputs."),Xs.set(de,[Tt,$t,Nt,wt,Pi,!1]));for(let[is,Hd]of await Promise.all(Z1))Mu[is][2]=Hd;return Ot("wasm ProcessOutputTensor"),Mu}finally{(X1=qe.webnnOnRunEnd)==null||X1.call(qe,Tt),qe.stackRestore(ps),Cn.forEach(Ia=>qe._OrtReleaseTensor(Ia)),fr.forEach(Ia=>qe._OrtReleaseTensor(Ia)),Yi.forEach(Ia=>qe._free(Ia)),hr!==0&&qe._OrtReleaseRunOptions(hr),xn.forEach(Ia=>qe._free(Ia))}},Ru=de=>{let be=Gi(),Ne=Xs.get(de);if(!Ne)throw new Error("invalid session id");let Ve=Ne[0],Oe=be._OrtEndProfiling(Ve);Oe===0&&Ii("Can't get an profile file name."),be._OrtFree(Oe)},Vy=de=>{let be=[];for(let Ne of de){let Ve=Ne[2];!Array.isArray(Ve)&&"buffer"in Ve&&be.push(Ve.buffer)}return be}}),us,Ki,Th,Rf,Af,Fg,cm,Bg,cd,Sl,$d,Wd,Mf,jg,Au,uE,$g,Wg,G1=c(()=>{es(),sv(),Da(),Kr(),us=()=>!!N.wasm.proxy&&typeof document<"u",Th=!1,Rf=!1,Af=!1,Bg=new Map,cd=(de,be)=>{let Ne=Bg.get(de);Ne?Ne.push(be):Bg.set(de,[be])},Sl=()=>{if(Th||!Rf||Af||!Ki)throw new Error("worker not ready")},$d=de=>{switch(de.data.type){case"init-wasm":Th=!1,de.data.err?(Af=!0,cm[1](de.data.err)):(Rf=!0,cm[0]()),Fg&&(URL.revokeObjectURL(Fg),Fg=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let be=Bg.get(de.data.type);de.data.err?be.shift()[1](de.data.err):be.shift()[0](de.data.out);break}}},Wd=async()=>{if(!Rf){if(Th)throw new Error("multiple calls to 'initWasm()' detected.");if(Af)throw new Error("previous call to 'initWasm()' failed.");if(Th=!0,us())return new Promise((de,be)=>{Ki==null||Ki.terminate(),Hn().then(([Ne,Ve])=>{try{Ki=Ve,Ki.onerror=rt=>be(rt),Ki.onmessage=$d,cm=[de,be];let Oe={type:"init-wasm",in:N};if(!Oe.in.wasm.wasmPaths&&Ne){let rt=Ea();rt&&(Oe.in.wasm.wasmPaths=rt)}Ki.postMessage(Oe),Fg=Ne}catch(Oe){be(Oe)}},be)});try{await Kl(N.wasm),await Ja(N),Rf=!0}catch(de){throw Af=!0,de}finally{Th=!1}}},Mf=async de=>{if(us())return Sl(),new Promise((be,Ne)=>{cd("init-ep",[be,Ne]);let Ve={type:"init-ep",in:{epName:de,env:N}};Ki.postMessage(Ve)});await Fd(N,de)},jg=async de=>us()?(Sl(),new Promise((be,Ne)=>{cd("copy-from",[be,Ne]);let Ve={type:"copy-from",in:{buffer:de}};Ki.postMessage(Ve,[de.buffer])})):ts(de),Au=async(de,be)=>{if(us()){if(be!=null&&be.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Sl(),new Promise((Ne,Ve)=>{cd("create",[Ne,Ve]);let Oe={type:"create",in:{model:de,options:{...be}}},rt=[];de instanceof Uint8Array&&rt.push(de.buffer),Ki.postMessage(Oe,rt)})}else return jd(de,be)},uE=async de=>{if(us())return Sl(),new Promise((be,Ne)=>{cd("release",[be,Ne]);let Ve={type:"release",in:de};Ki.postMessage(Ve)});lm(de)},$g=async(de,be,Ne,Ve,Oe,rt)=>{if(us()){if(Ne.some(qe=>qe[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Oe.some(qe=>qe))throw new Error("pre-allocated output tensor is not supported for proxy.");return Sl(),new Promise((qe,Ge)=>{cd("run",[qe,Ge]);let dt=Ne,Tt={type:"run",in:{sessionId:de,inputIndices:be,inputs:dt,outputIndices:Ve,options:rt}};Ki.postMessage(Tt,Vy(dt))})}else return St(de,be,Ne,Ve,Oe,rt)},Wg=async de=>{if(us())return Sl(),new Promise((be,Ne)=>{cd("end-profiling",[be,Ne]);let Ve={type:"end-profiling",in:de};Ki.postMessage(Ve)});Ru(de)}}),zy,Hg,rv,Uy=c(()=>{es(),G1(),Jt(),ii(),ao(),zy=(de,be)=>{switch(de.location){case"cpu":return[de.type,de.dims,de.data,"cpu"];case"gpu-buffer":return[de.type,de.dims,{gpuBuffer:de.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[de.type,de.dims,{mlTensor:de.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${de.location} for ${be()}`)}},Hg=de=>{switch(de[3]){case"cpu":return new Ie(de[0],de[2],de[1]);case"gpu-buffer":{let be=de[0];if(!It(be))throw new Error(`not supported data type: ${be} for deserializing GPU tensor`);let{gpuBuffer:Ne,download:Ve,dispose:Oe}=de[2];return Ie.fromGpuBuffer(Ne,{dataType:be,dims:de[1],download:Ve,dispose:Oe})}case"ml-tensor":{let be=de[0];if(!ui(be))throw new Error(`not supported data type: ${be} for deserializing MLTensor tensor`);let{mlTensor:Ne,download:Ve,dispose:Oe}=de[2];return Ie.fromMLTensor(Ne,{dataType:be,dims:de[1],download:Ve,dispose:Oe})}default:throw new Error(`invalid data location: ${de[3]}`)}},rv=class{async fetchModelAndCopyToWasmMemory(de){return jg(await zn(de))}async loadModel(de,be){Je();let Ne;typeof de=="string"?Ne=await this.fetchModelAndCopyToWasmMemory(de):Ne=de,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Au(Ne,be),Ct()}async dispose(){return uE(this.sessionId)}async run(de,be,Ne){Je();let Ve=[],Oe=[];Object.entries(de).forEach(Nt=>{let wt=Nt[0],Pi=Nt[1],it=this.inputNames.indexOf(wt);if(it===-1)throw new Error(`invalid input '${wt}'`);Ve.push(Pi),Oe.push(it)});let rt=[],qe=[];Object.entries(be).forEach(Nt=>{let wt=Nt[0],Pi=Nt[1],it=this.outputNames.indexOf(wt);if(it===-1)throw new Error(`invalid output '${wt}'`);rt.push(Pi),qe.push(it)});let Ge=Ve.map((Nt,wt)=>zy(Nt,()=>`input "${this.inputNames[Oe[wt]]}"`)),dt=rt.map((Nt,wt)=>Nt?zy(Nt,()=>`output "${this.outputNames[qe[wt]]}"`):null),Tt=await $g(this.sessionId,Oe,Ge,qe,dt,Ne),$t={};for(let Nt=0;Nt<Tt.length;Nt++)$t[this.outputNames[qe[Nt]]]=rt[Nt]??Hg(Tt[Nt]);return Ct(),$t}startProfiling(){}endProfiling(){Wg(this.sessionId)}}}),Ih={};d(Ih,{OnnxruntimeWebAssemblyBackend:()=>Nh,initializeFlags:()=>Pf,wasmBackend:()=>Vg});var Pf,Nh,Vg,K1=c(()=>{es(),G1(),Uy(),Pf=()=>{(typeof N.wasm.initTimeout!="number"||N.wasm.initTimeout<0)&&(N.wasm.initTimeout=0);let de=N.wasm.simd;if(typeof de!="boolean"&&de!==void 0&&de!=="fixed"&&de!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${de}". Reset it to \`false\` and ignore SIMD feature checking.`),N.wasm.simd=!1),typeof N.wasm.proxy!="boolean"&&(N.wasm.proxy=!1),typeof N.wasm.trace!="boolean"&&(N.wasm.trace=!1),typeof N.wasm.numThreads!="number"||!Number.isInteger(N.wasm.numThreads)||N.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)N.wasm.numThreads=1;else{let be=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;N.wasm.numThreads=Math.min(4,Math.ceil((be||1)/2))}},Nh=class{async init(de){Pf(),await Wd(),await Mf(de)}async createInferenceSessionHandler(de,be){let Ne=new rv;return await Ne.loadModel(de,be),Ne}},Vg=new Nh}),Y1={};d(Y1,{InferenceSession:()=>Tn,TRACE:()=>He,TRACE_EVENT_BEGIN:()=>Ft,TRACE_EVENT_END:()=>Ot,TRACE_FUNC_BEGIN:()=>Je,TRACE_FUNC_END:()=>Ct,Tensor:()=>Ie,default:()=>Gy,env:()=>N,registerBackend:()=>p}),es(),es(),es();var qy="1.26.0",Gy=Ko;{let de=(K1(),h(Ih)).wasmBackend;p("cpu",de,10),p("wasm",de,10)}return Object.defineProperty(N.versions,"web",{value:qy,enumerable:!0}),h(Y1)})();s.exports=i})(XX)),XX.exports}var eke;function N2t(){return eke||(eke=1,(function(s){var e=Wv&&Wv.__createBinding||(Object.create?(function(x,S,k,D){D===void 0&&(D=k);var T=Object.getOwnPropertyDescriptor(S,k);(!T||("get"in T?!S.__esModule:T.writable||T.configurable))&&(T={enumerable:!0,get:function(){return S[k]}}),Object.defineProperty(x,D,T)}):(function(x,S,k,D){D===void 0&&(D=k),x[D]=S[k]})),i=Wv&&Wv.__setModuleDefault||(Object.create?(function(x,S){Object.defineProperty(x,"default",{enumerable:!0,value:S})}):function(x,S){x.default=S}),n=Wv&&Wv.__importStar||function(x){if(x&&x.__esModule)return x;var S={};if(x!=null)for(var k in x)k!=="default"&&Object.prototype.hasOwnProperty.call(x,k)&&e(S,x,k);return i(S,x),S};Object.defineProperty(s,"__esModule",{value:!0}),s.MicVAD=s.getDefaultRealTimeVADOptions=s.ort=s.DEFAULT_MODEL=void 0;const r=n(I2t()),o=Cme(),a=Sme(),l=YF(),c=lG(),d=m6e(),u=_6e();s.DEFAULT_MODEL="legacy",s.ort=r;const h="vad.worklet.bundle.min.js",f="silero_vad_v5.onnx",g="silero_vad_legacy.onnx",p=x=>({...a.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:x,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async S=>{S.getTracks().forEach(k=>{k.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:S=>{S.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});s.getDefaultRealTimeVADOptions=p;const _=x=>"audioWorklet"in x&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function m(x,S,k,D,T){await k.audioWorklet.addModule(x),S.processorOptions={...S.processorOptions??{},frameSamples:D};const N=new AudioWorkletNode(k,"vad-helper-worklet",S);return N.port.onmessage=async A=>{const O=A.data;if(!(typeof O=="object"&&O&&"message"in O)){console.error("Invalid message event",O);return}switch(O.message){case c.Message.AudioFrame:{if(!("data"in O&&O.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const $=new Float32Array(O.data);await T($);break}}},N}async function b(x,S,k){const D=new u.Resampler({nativeSampleRate:x.sampleRate,targetSampleRate:16e3,targetFrameSize:S});l.log.debug("using script processor");const N=x.createScriptProcessor(4096,1,1);let A=!1;return N.onaudioprocess=async O=>{if(!A){A=!0;try{const $=O.inputBuffer.getChannelData(0);O.outputBuffer.getChannelData(0).fill(0);const B=D.process($);for(const W of B)await k(W)}catch($){console.error("Error processing audio:",$)}finally{A=!1}}},N.connect(x.destination),N}class y{constructor(S,k,D,T,N=!1,A=null,O=null,$=null,P=null,B=null,W=null,q="uninitialized",G=!1){this.options=S,this.frameProcessor=k,this.model=D,this.frameSamples=T,this.listening=N,this.errored=A,this._stream=O,this._audioContext=$,this._vadNode=P,this._mediaStreamAudioSourceNode=B,this._audioProcessorAdapterType=W,this.initializationState=q,this.ownsAudioContext=G,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=re=>{this.initializationState="errored",this.errored=re},this.start=async()=>{switch(this.initializationState){case"uninitialized":{l.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(re){throw re instanceof Error?this.setErrored(re.message):this.setErrored(String(re)),re}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?_(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await m(this.options.baseAssetPath+h,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await b(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),l.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{l.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:re,audioContext:ie,vadNode:K}=this.getAudioInstances();this._stream=await this.options.resumeStream(re);const Z=new MediaStreamAudioSourceNode(ie,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Z,Z.connect(K);break}case"destroyed":{l.log.warn("start called after destroyed");break}case"errored":{l.log.error("start called after errored");break}default:{l.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:re,mediaStreamAudioSourceNode:ie}=this.getAudioInstances();await this.options.pauseStream(re),ie.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var ie;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:re}=this.getAudioInstances();re instanceof AudioWorkletNode&&re.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((ie=this._audioContext)==null?void 0:ie.close())},this.setOptions=re=>{this.frameProcessor.setOptions(re)},this.processFrame=async re=>{await this.frameProcessor.process(re,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=re=>{switch(re.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(re.probs,re.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd(re.audio);break}}}static async new(S={}){const k={...(0,s.getDefaultRealTimeVADOptions)(S.model??s.DEFAULT_MODEL),...S};(0,a.validateOptions)(k),s.ort.env.wasm.wasmPaths=k.onnxWASMBasePath,k.ortConfig!==void 0&&k.ortConfig(s.ort);const D=k.model==="v5"?f:g,T=k.baseAssetPath+D,N=k.model==="v5"?d.SileroV5.new:d.SileroLegacy.new;let A;try{A=await N(s.ort,()=>(0,o.defaultModelFetcher)(T))}catch(W){throw console.error(`Encountered an error while loading model file ${T}`),W}const O=k.model==="v5"?512:1536,$=O/16,P=new a.FrameProcessor(A.process,A.reset_state,{positiveSpeechThreshold:k.positiveSpeechThreshold,negativeSpeechThreshold:k.negativeSpeechThreshold,redemptionMs:k.redemptionMs,preSpeechPadMs:k.preSpeechPadMs,minSpeechMs:k.minSpeechMs,submitUserSpeechOnPause:k.submitUserSpeechOnPause},$),B=new y(k,P,A,O);if(k.startOnLoad)try{await B.start()}catch(W){throw console.error("Error starting micVad",W),W}return B}}s.MicVAD=y})(Wv)),Wv}var tke;function R2t(){return tke||(tke=1,(function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.getDefaultRealTimeVADOptions=s.MicVAD=s.DEFAULT_MODEL=s.utils=s.NonRealTimeVAD=s.Message=s.FrameProcessor=s.defaultModelFetcher=s.baseAssetPath=void 0;var e=f6e();Object.defineProperty(s,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var i=Cme();Object.defineProperty(s,"defaultModelFetcher",{enumerable:!0,get:function(){return i.defaultModelFetcher}});var n=Sme();Object.defineProperty(s,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var r=lG();Object.defineProperty(s,"Message",{enumerable:!0,get:function(){return r.Message}});var o=D2t();Object.defineProperty(s,"NonRealTimeVAD",{enumerable:!0,get:function(){return o.NonRealTimeVAD}});const a=T2t();s.utils={audioFileToArray:a.audioFileToArray,minFramesForTargetMS:a.minFramesForTargetMS,arrayBufferToBase64:a.arrayBufferToBase64,encodeWAV:a.encodeWAV};var l=N2t();Object.defineProperty(s,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(s,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(s,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(GX)),GX}var A2t=R2t();function V$(s,e,i,n){var o,a;try{(a=(o=window.api)==null?void 0:o.logs)==null||a.write(s,e,i,n)}catch{}const r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`[${s}]`,i,n):r(`[${s}]`,i)}const ti={debug:(s,e,i)=>V$(s,"debug",e,i),info:(s,e,i)=>V$(s,"info",e,i),warn:(s,e,i)=>V$(s,"warn",e,i),error:(s,e,i)=>V$(s,"error",e,i)},b6e=16e3,M2t=6,pT=b6e*M2t,P2t=400,O2t=b6e*P2t/1e3,ike=300,nke=2e3,ske=1500,rke=3e3,F2t=600,y6e=.5,w6e=.35,oke=.85,ake=.7;let ih=null,T_=!1,fu=!1;const cde=new Set;function z$(s){for(const e of Array.from(cde))try{e(s)}catch(i){ti.warn("speech","workerDeath listener threw",{error:i instanceof Error?i.message:String(i)})}}let ZX=0;const lke=2;let r2=!1,x6e=!1;function C6e(s){s.addEventListener("message",e=>{var n;if(((n=e.data)==null?void 0:n.type)!=="log")return;const i=e.data.level||"info";ti[i]("whisperWorker",e.data.message??"",e.data.meta)}),s.addEventListener("error",e=>{ti.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),B2t(`error:${e.message||"unknown"}`)})}function lH(){return ih||(ih=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),C6e(ih),ti.info("speech","worker spawned"),ih)}let U$=!1;function B2t(s){if(!r2){if(U$){ti.warn("speech","respawnWorker: already in flight, ignoring",{reason:s});return}if(U$=!0,ZX+=1,x6e=!0,ti.warn("speech","respawnWorker: starting",{reason:s,attempt:ZX}),z$({reason:s,respawned:!1,finalOnly:!0}),ZX>lke){if(r2=!0,ti.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:lke}),ih)try{ih.terminate()}catch{}ih=null,T_=!1,fu=!1,z$({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),U$=!1;return}if(ih)try{ih.terminate()}catch{}ih=null,T_=!1,fu=!1;try{ih=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),C6e(ih),fu=!0,ih.postMessage({type:"load"}),ti.info("speech","respawnWorker: new worker spawned, load posted"),z$({reason:s,respawned:!0,finalOnly:!0})}catch(e){r2=!0,ti.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),z$({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{U$=!1}}}function j2t(s,e){if(T_||fu)return;fu=!0;const i=lH();ti.info("speech","preloadModel: posting load");const n=r=>{r.data.type==="status"?(s==null||s(r.data.status,r.data.message),r.data.status==="ready"&&(T_=!0,fu=!1,ti.info("speech","preloadModel: ready"),i.removeEventListener("message",n))):r.data.type==="progress"?e==null||e(r.data.pct):r.data.type==="error"&&(fu=!1,ti.error("speech","preloadModel: worker reported error",{error:r.data.error}),s==null||s("error",r.data.error),i.removeEventListener("message",n))};i.addEventListener("message",n),i.postMessage({type:"load"})}function $2t(){ti.info("speech","resetModel: clearing load flags"),T_=!1,fu=!1}function kme(){var s;return typeof Worker<"u"&&!!((s=navigator.mediaDevices)!=null&&s.getUserMedia)&&typeof AudioWorkletNode<"u"}function W2t(s){const e=lH();return!T_&&!fu&&(fu=!0,e.postMessage({type:"load"})),new Promise((i,n)=>{const r=o=>{var a,l,c;((a=o.data)==null?void 0:a.type)==="result"?(e.removeEventListener("message",r),i((o.data.text??"").trim())):((l=o.data)==null?void 0:l.type)==="error"?(e.removeEventListener("message",r),n(new Error(String(o.data.error??"Transcription failed")))):((c=o.data)==null?void 0:c.type)==="status"&&o.data.status==="ready"&&(T_=!0,fu=!1)};e.addEventListener("message",r),e.postMessage({type:"transcribe",audio:s},[s.buffer])})}function H2t(s){let e=lH(),i=!1,n=null,r=null,o=null,a=null,l=null;const c=[],d=new Set;let u=null,h=0,f=!1,g=0,p=!1,_=!1,m=0,b=0,y=0,x=-1,S=ike,k=0,D=null,T="",N="",A=!1,O=0;function $(ge,Se){const Ee=Math.min(ge.length,Se.length);let $e=0;for(;$e<Ee&&ge.charCodeAt($e)===Se.charCodeAt($e);)$e++;return $e}function P(ge){const Se=$(T,ge);return T=ge,Se>N.length&&(N=ge.slice(0,Se)),N.length>ge.length&&(N=ge),N}const B=()=>(u||(u=new Float32Array(pT)),u),W=()=>{h=0},q=ge=>{const Se=B(),Ee=ge.length;if(Ee>=pT){Se.set(ge.subarray(Ee-pT)),h=pT;return}if(h+Ee<=pT){Se.set(ge,h),h+=Ee;return}const $e=h+Ee-pT;Se.copyWithin(0,$e,h),h-=$e,Se.set(ge,h),h+=Ee},G=()=>{D&&(clearTimeout(D),D=null)},re=()=>{G(),f=!1,p=!1,_=!1,S=ike,T="",N="",A=!1,O=0,W()},ie=()=>{if(i||!f||_||p||D)return;if(h<O2t){D=setTimeout(()=>{D=null,ie()},S);return}const ge=performance.now()-m;if(ge<S&&m!==0){D=setTimeout(()=>{D=null,ie()},S-ge);return}if(x6e||r2||s.partialsEnabled&&!s.partialsEnabled())return;const Se=B(),Ee=new Float32Array(h);Ee.set(Se.subarray(0,h)),b+=1,y=b,p=!0,k=performance.now(),m=k,e.postMessage({type:"transcribe-partial",audio:Ee,seq:b},[Ee.buffer])},K=ge=>ge.length===0?Promise.resolve():r2?(ti.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),i||s.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(Se=>{c.push(Se),b+=1;const Ee=b;x=Ee,e.postMessage({type:"transcribe",audio:ge,seq:Ee},[ge.buffer])}),Z=ge=>{const Se=K(ge);return d.add(Se),Se.finally(()=>{d.delete(Se)}),Se},Q=ge=>{var Se,Ee,$e,De,ae;if(ge.data.type==="result"){const Te=ge.data.text,Ie=ge.data.seq??0;Ie&&Ie<x&&ti.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:Ie,latestFinalSeq:x}),!i&&Te&&s.onFinal(Te),(Se=c.shift())==null||Se()}else if(ge.data.type==="partial"){const Te=ge.data.seq??0,Ie=ge.data.text??"",st=performance.now()-k;p=!1,st>=rke?(_=!0,ti.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(st),seq:Te})):st>=ske&&(S=Math.min(S*2,nke),ti.warn("speech","partials.slowdown",{elapsedMs:Math.round(st),newIntervalMs:S,seq:Te})),A||(A=!0,st>F2t&&S<500&&(S=500,ti.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(st),newIntervalMs:500})));const He=Te!==y||Te<=x;if(!i&&!He&&Ie){const lt=P(Ie);lt&&((Ee=s.onPartial)==null||Ee.call(s,lt),O===0&&(O=performance.now(),ti.info("speech","partial.first",{msSinceSpeechStart:Math.round(O-g)})))}ie()}else if(ge.data.type==="partial-error"){const Te=performance.now()-k;p=!1,Te>=rke?(_=!0,ti.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Te),seq:ge.data.seq})):Te>=ske&&(S=Math.min(S*2,nke),ti.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Te),newIntervalMs:S,seq:ge.data.seq})),ti.warn("speech","partial encode failed",{error:ge.data.error,seq:ge.data.seq}),ie()}else ge.data.type==="error"?(i||s.onError(ge.data.error),($e=c.shift())==null||$e()):ge.data.type==="status"?(i||(De=s.onModelStatus)==null||De.call(s,ge.data.status,ge.data.message),ge.data.status==="ready"&&(T_=!0,fu=!1)):ge.data.type==="progress"&&(i||(ae=s.onProgress)==null||ae.call(s,ge.data.pct))};e.addEventListener("message",Q);const ne=ge=>{var Se,Ee;if(!i){for(ti.warn("speech","createRecognition: worker death event",ge),(Se=s.onStatusChange)==null||Se.call(s,"restarting");c.length;)(Ee=c.shift())==null||Ee();if(d.clear(),G(),p=!1,ge.respawned){try{e.removeEventListener("message",Q)}catch{}e=lH(),e.addEventListener("message",Q)}}};return cde.add(ne),{start:async()=>{if(!i){if(r2){s.onError("Speech recognition disabled — please reload the app.");return}!T_&&!fu&&(fu=!0,ti.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),ti.info("speech","createRecognition.start: initializing VAD",{modelReady:T_,modelLoading:fu});try{const ge=new URL("vad/",document.baseURI).href,Se=s.inputDeviceId||null,Ee={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};Se&&(Ee.deviceId={exact:Se}),ti.info("speech","getUserMedia",{hasDeviceId:!!Se,deviceIdPrefix:Se?Se.slice(0,8):null});const $e=await navigator.mediaDevices.getUserMedia({audio:Ee});r=$e,o=new AudioContext;for(const De of $e.getAudioTracks())De.addEventListener("ended",()=>{i||(ti.warn("speech","mic track ended (permission revoked or device removed)"),s.onError("Microphone disconnected or permission revoked"))});try{l=o.createMediaStreamSource(r),a=o.createAnalyser(),a.fftSize=2048,a.smoothingTimeConstant=.3,l.connect(a)}catch(De){ti.warn("speech","analyser init failed",{error:De instanceof Error?De.message:String(De)}),l=null,a=null}n=await A2t.MicVAD.new({audioContext:o,getStream:async()=>$e,resumeStream:async()=>$e,pauseStream:async()=>{},baseAssetPath:ge,onnxWASMBasePath:ge,model:"v5",positiveSpeechThreshold:y6e,negativeSpeechThreshold:w6e,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(De,ae)=>{var Te;i||((Te=s.onFrame)==null||Te.call(s,De),f&&(q(ae),ie()))},onSpeechStart:()=>{var De;i||(re(),f=!0,g=performance.now(),(De=s.onSpeechStart)==null||De.call(s))},onSpeechEnd:De=>{var ae;i||((ae=s.onStatusChange)==null||ae.call(s,"transcribing"),re(),Z(De))},onVADMisfire:()=>{var De,ae;i||((De=s.onStatusChange)==null||De.call(s,"idle"),re(),(ae=s.onMisfire)==null||ae.call(s))}}),n.start()}catch(ge){const Se=ge instanceof Error?ge.message:"Microphone access denied",Ee=ge instanceof Error?ge.stack:"";if(ti.error("speech","createRecognition.start: VAD init failed",{error:Se,stack:Ee}),a){try{a.disconnect()}catch{}a=null}if(l){try{l.disconnect()}catch{}l=null}if(r){try{r.getTracks().forEach($e=>$e.stop())}catch{}r=null}if(o){try{await o.close()}catch{}o=null}s.onError(Se)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for(re();d.size>0;)await Promise.all(Array.from(d));if(n){try{await n.destroy()}catch{}n=null}if(a){try{a.disconnect()}catch{}a=null}if(l){try{l.disconnect()}catch{}l=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}if(o){try{await o.close()}catch{}o=null}},setVadThresholds:(ge,Se)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ge,negativeSpeechThreshold:Se})}catch(Ee){ti.warn("speech","setVadThresholds failed",{error:Ee instanceof Error?Ee.message:String(Ee)})}},getAnalyser:()=>a,destroy:()=>{if(i=!0,re(),n){try{n.destroy()}catch{}n=null}if(a){try{a.disconnect()}catch{}a=null}if(l){try{l.disconnect()}catch{}l=null}if(o){try{o.close()}catch{}o=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}cde.delete(ne),e.removeEventListener("message",Q)}}}let KO=null;const dde=new Set,ude=new Set;function V2t(){for(const s of dde)try{s()}catch{}}function hde(){for(const s of ude)try{s()}catch{}}function z2t(s){return s.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function U2t(s){if(!window.speechSynthesis)return;const e=z2t(s);if(!e)return;const i=new SpeechSynthesisUtterance(e);i.rate=1,i.pitch=1,i.onstart=()=>{KO=performance.now(),V2t()},i.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(KO=null,hde())},i.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(KO=null,hde())},window.speechSynthesis.speak(i)}function S6e(){window.speechSynthesis&&(window.speechSynthesis.cancel(),KO=null,hde())}function k6e(){var s;return((s=window.speechSynthesis)==null?void 0:s.speaking)??!1}function q2t(){return KO}function G2t(s){return dde.add(s),()=>{dde.delete(s)}}function K2t(s){return ude.add(s),()=>{ude.delete(s)}}function Y2t(s){k6e()&&(s.setVadThresholds(oke,ake),ti.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=G2t(()=>{s.setVadThresholds(oke,ake),ti.info("voice","tts.duck.on")}),i=K2t(()=>{s.setVadThresholds(y6e,w6e),ti.info("voice","tts.duck.off")});return()=>{e(),i()}}const X2t=[{match:/^(send|submit|enter)\.?$/i,data:"\r",label:"send"},{match:/^(cancel|escape)\.?$/i,data:"\x1B",label:"cancel"},{match:/^clear( line)?\.?$/i,data:"",label:"clear"}];function Z2t(s){const e=s.trim();return X2t.find(i=>i.match.test(e))??null}const Q2t=4e4;let bS=null;function o2(){bS&&clearTimeout(bS),bS=setTimeout(()=>{bS=null,zi.getState().stopRecording()},Q2t)}function q$(){bS&&(clearTimeout(bS),bS=null)}let D0=null,c0=null;const J2t=.04,eNt=.3;let cH=0,fde=0;function tNt(s){c0!==null&&cancelAnimationFrame(c0);const e=()=>{if(D0===null||zi.getState().submitCountdownStartAt===null){c0=null;return}const i=performance.now();if(i-fde<200&&cH>eNt){const r=i-s;ti.info("voice","submit.preempted_by_voice",{reason:"vad",prob:cH.toFixed(2),msIntoCountdown:Math.round(r)}),Vw(),o2();return}const n=L6e();if(n){const r=new Uint8Array(n.fftSize);n.getByteTimeDomainData(r);let o=0;for(let l=0;l<r.length;l++){const c=(r[l]-128)/128;o+=c*c}const a=Math.sqrt(o/r.length);if(a>J2t){const l=i-s;ti.info("voice","submit.preempted_by_voice",{reason:"rms",rms:a.toFixed(3),msIntoCountdown:Math.round(l)}),Vw(),o2();return}}c0=requestAnimationFrame(e)};c0=requestAnimationFrame(e)}function iNt(s){D0&&clearTimeout(D0);const e=zi.getState().submitDelayMs,i=performance.now();zi.setState({submitCountdownStartAt:i}),D0=setTimeout(()=>{D0=null,zi.setState({submitCountdownStartAt:null});try{window.api.pty.write({tabId:s,data:"\r"})}catch(n){ti.warn("voice","submit pty.write failed",{error:n instanceof Error?n.message:String(n)})}o2()},e),tNt(i)}function Vw(){c0!==null&&(cancelAnimationFrame(c0),c0=null),D0&&(clearTimeout(D0),D0=null),zi.getState().submitCountdownStartAt!==null&&zi.setState({submitCountdownStartAt:null})}let cc=null,gd=null;function L6e(){var s;return((s=cc==null?void 0:cc.getAnalyser)==null?void 0:s.call(cc))??null}const G$=1e4;let YO=null;function K$(){YO&&(clearTimeout(YO),YO=null)}let E8=null,D8=null;function Y$(){E8=null,D8&&(D8(),D8=null)}const nNt=1500,sNt=9e4;let X$=0,T8=null,gde=-1;function Z$(){T8&&(clearTimeout(T8),T8=null,gde=-1)}const rNt=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),zi=Ka((s,e)=>({isRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;ti.info("voice","initModel: kicking off preload"),s({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const i=++X$,n=()=>{i===X$&&(Z$(),gde=i,T8=setTimeout(()=>{gde===i&&e().modelStatus==="loading"&&(ti.warn("voice","mic.gate.timeout: no progress within 90s"),s({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},sNt))};n(),j2t((r,o)=>{i===X$&&(r==="ready"?(Z$(),ti.info("voice","modelStatus -> ready"),s({modelStatus:"ready",loadingProgress:100,errorKind:null})):r==="error"?(Z$(),ti.error("voice","modelStatus -> error",{msg:o}),s({modelStatus:"error",error:o,errorKind:"load"})):(n(),s({modelStatus:"loading"})))},r=>{i===X$&&(n(),s({loadingProgress:Math.round(r)}))})},resetAndRetryModel:()=>{ti.info("voice","mic.gate.retry"),Z$(),$2t(),s({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:i=>{if(e().isRecording)return;if(cc){ti.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!kme()){s({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const n=r=>{try{const o=H2t({inputDeviceId:r,onStatusChange:a=>{s(a==="transcribing"?{statusPill:"transcribing"}:a==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:a=>{e().partialsEnabled&&s({lastPartial:a})},partialsEnabled:()=>e().partialsEnabled,onFrame:a=>{cH=a.isSpeech,fde=performance.now()},onSpeechStart:()=>{if(s({statusPill:"listening",lastPartial:""}),q$(),Vw(),k6e()){const l=q2t(),c=l!==null?performance.now()-l:null;S6e(),s({lastBargeInAt:performance.now()}),ti.info("voice","barge-in",{tabId:i,utteranceOffsetMs:c})}else ti.debug("voice","barge-in.no-op",{tabId:i})},onMisfire:()=>{s({lastPartial:"",statusPill:"idle"}),o2();const a=e().lastBargeInAt;a!==null&&performance.now()-a<600&&ti.warn("voice","barge-in.misfire",{tabId:i,sinceBargeInMs:Math.round(performance.now()-a)})},onFinal:a=>{o2();const l=a.trim();if(!l||rNt.has(l)){s({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}const c=Z2t(l);if(c){ti.info("voice","voice-command",{tabId:i,label:c.label,transcript:l}),window.api.pty.write({tabId:i,data:c.data}),s({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Vw();const u=window;u.__transcripts&&(u.__transcripts.push({tabId:i,text:l}),u.__transcripts.length>500&&u.__transcripts.shift());return}window.api.pty.write({tabId:i,data:l}),s({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&iNt(i);const d=window;d.__transcripts&&(d.__transcripts.push({tabId:i,text:l}),d.__transcripts.length>500&&d.__transcripts.shift())},onError:a=>{ti.error("voice","recognition error",{err:a}),Vw(),s({error:a,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),gd==null||gd(),gd=null,q$(),cc==null||cc.destroy(),cc=null,Kt.error(`Microphone error: ${a}`)},onModelStatus:a=>{a==="ready"?s({modelStatus:"ready",loadingProgress:100}):a==="loading"&&s({modelStatus:"loading"})},onProgress:a=>s({loadingProgress:Math.round(a)})});cc=o,s({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),o2(),o.start().then(()=>{cc===o&&(gd==null||gd(),gd=Y2t(o))}).catch(a=>{const l=a instanceof Error?a.message:String(a);ti.error("voice","handle.start() failed",{error:l}),Kt.error(`Could not start mic: ${l}`)})}catch(o){s({error:o instanceof Error?o.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var r,o,a;return((a=(o=(r=window.api)==null?void 0:r.voice)==null?void 0:o.getDevicePref)==null?void 0:a.call(o))??Promise.resolve(null)}).then(r=>n((r==null?void 0:r.selectedDeviceId)??null)).catch(r=>{ti.warn("voice","getDevicePref failed; using default device",{error:r instanceof Error?r.message:String(r)}),n(null)})},stopRecording:()=>{const i=cc;i&&(q$(),Vw(),cH=0,fde=0,gd==null||gd(),gd=null,s({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),i.stop().finally(()=>{i.destroy(),cc===i&&(cc=null),e().hotkeyState==="stopping"&&(K$(),s({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const i=cc;if(!i)return;q$(),gd==null||gd(),gd=null,s({isRecording:!1,lastTranscript:"",lastPartial:""});try{await i.stop()}catch(o){ti.warn("voice","restartWithDevice: drain rejected",{error:o instanceof Error?o.message:String(o)})}i.destroy(),cc===i&&(cc=null);const{useSessions:n}=await ei(async()=>{const{useSessions:o}=await Promise.resolve().then(()=>h2t);return{useSessions:o}},[],import.meta.url),r=n.getState().activeTabId;r&&e().startRecording(r)},toggleTTS:()=>s(i=>({ttsEnabled:!i.ttsEnabled})),setAutoSubmit:i=>s({autoSubmit:i}),setSubmitDelayMs:i=>s({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(i)))}),cancelSubmit:()=>Vw(),setPartialsEnabled:i=>{e().partialsEnabled!==i&&(s({partialsEnabled:i}),i||s({lastPartial:""}))},clearError:()=>s({error:null,errorKind:null}),setPermissionState:i=>{e().permissionState!==i&&(ti.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:i}),s({permissionState:i}))},setLevelMeterEnabled:i=>{e().levelMeterEnabled!==i&&s({levelMeterEnabled:i})},setTurnDetectorRuntimeState:i=>{e().turnDetectorState!==i&&(s({turnDetectorState:i}),i==="load_failed"?ti.warn("voice-turn","voice-turn.load_failed"):i==="runtime_error"?ti.warn("voice-turn","voice-turn.runtime_error"):i==="disabled"&&ti.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:i=>{e().wizardArmed!==i&&s({wizardArmed:i})},openWizard:()=>{e().wizardOpen||s({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&s({wizardOpen:!1})},armHotkey:({phase:i,source:n,mode:r,tabId:o})=>{const a=e(),{canRecord:l,reason:c}=pde(a);if(i==="down"){if(c==="error"||c==="load-timeout"){a.resetAndRetryModel(),ti.info("voice-hotkey","down.retry",{source:n,reason:c});return}if(!l&&c!=="loading"){ti.warn("voice-hotkey","miss-model-loading",{modelStatus:a.modelStatus,reason:c});return}if(a.hotkeyState==="recording"||a.isRecording){(r==="toggle"||n==="global")&&(s({hotkeyState:"stopping"}),K$(),YO=setTimeout(()=>{e().hotkeyState==="stopping"&&(ti.warn("voice-hotkey","drain-timeout",{durationMs:G$}),s({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&s({hotkeyState:"idle"})},0))},G$),a.stopRecording());return}if(c==="loading"){a.hotkeyState!=="armed"&&(s({hotkeyState:"armed"}),ti.info("voice-hotkey","armed",{source:n,modelStatus:a.modelStatus})),Y$(),E8={tabId:o,source:n,mode:r},D8=zi.subscribe((d,u)=>{if(E8&&d.modelStatus==="ready"&&u.modelStatus!=="ready"&&d.hotkeyState==="armed"){const h=E8;if(Y$(),!h.tabId){ti.warn("voice-hotkey","armed-promote-no-tab",{source:h.source}),s({hotkeyState:"idle"});return}ti.info("voice-hotkey","armed-promote",h),s({hotkeyState:"recording"}),zi.getState().startRecording(h.tabId)}});return}if(!o){ti.warn("voice-hotkey","no-active-tab",{source:n});return}ti.info("voice-hotkey","start",{source:n,mode:r,tabId:o}),a.startRecording(o),e().isRecording?s({hotkeyState:"recording"}):(ti.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),s({hotkeyState:"idle"}));return}if(!(r!=="hold"||n==="global")){if(a.hotkeyState==="armed"){Y$(),ti.info("voice-hotkey","miss-model-loading-armed-up"),s({hotkeyState:"idle"});return}a.hotkeyState==="recording"&&(s({hotkeyState:"stopping"}),K$(),YO=setTimeout(()=>{e().hotkeyState==="stopping"&&(ti.warn("voice-hotkey","drain-timeout",{durationMs:G$}),s({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&s({hotkeyState:"idle"})},0))},G$),a.stopRecording())}},destroyHotkey:()=>{const i=e();if(Y$(),Vw(),i.hotkeyState==="recording"){ti.warn("voice-hotkey","destroyed-mid-recording"),s({hotkeyState:"destroyed"});try{i.stopRecording()}catch{}}else(i.hotkeyState==="armed"||i.hotkeyState==="stopping")&&(K$(),s({hotkeyState:"destroyed"}))}})),oNt=s=>({isRecording:s.isRecording,statusPill:s.statusPill,lastPartial:s.lastPartial,lastTranscript:s.lastTranscript,submitCountdownStartAt:s.submitCountdownStartAt}),pde=s=>kme()?s.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:s.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:s.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:s.modelStatus==="error"?{canRecord:!1,reason:s.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const s=window;s.__voice=zi,s.__transcripts=[]}function Lme(s,e,i){return new Promise((n,r)=>{const o=setTimeout(()=>r(new Error(`${i} timed out after ${e}ms`)),e);s.then(a=>{clearTimeout(o),n(a)},a=>{clearTimeout(o),r(a)})})}const aNt=5e3,D1=Ka(()=>({snapshot:null,loaded:!1}));let cke=!1,dke=!1;async function lNt(){if(!cke){cke=!0;try{const s=await Lme(window.api.schedule.state(),aNt,"schedule.state");D1.setState({snapshot:s,loaded:!0})}catch(s){if(!dke){dke=!0;const e=s instanceof Error?s.message:String(s);Kt.error(`Scheduler state hydrate failed: ${e}`)}}window.api.schedule.onState(s=>{D1.setState({snapshot:s,loaded:!0})})}}const cNt=6e4,dNt=5e3,WS=Ka(()=>({data:null,refreshing:!1}));let uke=!1,I8=null,hke=null,fke=!1;async function Eme(){WS.setState({refreshing:!0});let s=cNt;try{const e=await Lme(window.api.billing.fetch(),dNt,"billing.fetch");WS.setState({data:e,refreshing:!1}),e.kind==="transient"?s=hke==="transient"?3e4:5e3:e.kind==="auth"&&(s=3e4),hke=e.kind}catch(e){if(WS.setState({refreshing:!1}),!fke){fke=!0;const i=e instanceof Error?e.message:String(e);Kt.warn(`Billing usage fetch failed: ${i}`)}}I8=setTimeout(Eme,s)}function uNt(){uke||(uke=!0,Eme())}function XF(s){return s?s.kind==="ok"||s.kind==="ok-stale"?s.data:s.kind==="auth"&&s.cached?s.cached:null:null}function hNt(s){var e,i;return((i=(e=XF(s))==null?void 0:e.usage.five_hour)==null?void 0:i.utilization)??0}function dH(){I8!==null&&(clearTimeout(I8),I8=null),Eme()}function wy({name:s,size:e=17,stroke:i=1.6,className:n}){const r={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",className:n};switch(s){case"home":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M4 11l8-7 8 7"}),v.jsx("path",{d:"M6 10v9h12v-9"}),v.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),v.jsx("path",{d:"M7 10l3 2-3 2"}),v.jsx("path",{d:"M13 14h4"})]});case"agents":case"subagents":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"7",cy:"9",r:"2.5"}),v.jsx("circle",{cx:"17",cy:"9",r:"2.5"}),v.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),v.jsx("path",{d:"M8.6 11l2.8 4M15.4 11l-2.8 4M9.5 9h5"})]});case"agent-view":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"12",r:"9"}),v.jsx("circle",{cx:"12",cy:"12",r:"3"}),v.jsx("path",{d:"M3 12h2M19 12h2M12 3v2M12 19v2"})]});case"skills":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M12 3l2.5 5.5L20 9l-4 4 1 6-5-3-5 3 1-6-4-4 5.5-.5z"})});case"history":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"12",r:"8"}),v.jsx("path",{d:"M12 7v5l3 2"}),v.jsx("path",{d:"M4 6l2 2"})]});case"usage":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"hive":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M8 4h8l4 7-4 7H8l-4-7z"}),v.jsx("circle",{cx:"12",cy:"11",r:"2.5"})]});case"knowledge-graph":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"6",cy:"7",r:"2.2"}),v.jsx("circle",{cx:"18",cy:"6",r:"2.2"}),v.jsx("circle",{cx:"17",cy:"18",r:"2.2"}),v.jsx("circle",{cx:"7",cy:"17",r:"2.2"}),v.jsx("path",{d:"M8 8l8 8M8 16l8-9M8 7h8"})]});case"plugins":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),v.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),v.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),v.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),v.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"8",cy:"12",r:"4"}),v.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"plans":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),v.jsx("path",{d:"M8 9h8M8 13h8M8 17h5"})]});case"tasks":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"3",y:"4",width:"7",height:"7",rx:"1.5"}),v.jsx("rect",{x:"3",y:"13",width:"7",height:"7",rx:"1.5"}),v.jsx("path",{d:"M14 6h7M14 10h5M14 15h7M14 19h5"})]});case"projects":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"docs":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M6 3h8l4 4v14H6z"}),v.jsx("path",{d:"M14 3v4h4M9 13h6M9 17h6M9 9h3"})]});case"memory":case"agent-memory":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M9 4a4 4 0 00-4 4v1a3 3 0 000 6v1a4 4 0 004 4h6a4 4 0 004-4v-1a3 3 0 000-6V8a4 4 0 00-4-4z"}),v.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"11",cy:"11",r:"6"}),v.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return v.jsx("svg",{...r,children:v.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M7 3h7l4 4v14H7z"}),v.jsx("path",{d:"M14 3v4h4"})]});case"play":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),v.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"12",r:"8"}),v.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),v.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),v.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"12",r:"3"}),v.jsx("path",{d:"M12 2v3M12 19v3M4 12H1M23 12h-3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"})]});case"mic":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),v.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"12",r:"8"}),v.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),v.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"orchestrator":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"6",r:"2.5"}),v.jsx("circle",{cx:"5",cy:"17",r:"2.5"}),v.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),v.jsx("circle",{cx:"19",cy:"17",r:"2.5"}),v.jsx("path",{d:"M12 8.5v6M12 14.5l-7 0M12 14.5l7 0"})]});case"race":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M5 4v16M5 5h7l-1 3h7v6h-7l-1 3H5"})});case"background":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M3 4h18v4H3zM3 10h18v4H3zM3 16h18v4H3z"}),v.jsx("circle",{cx:"6",cy:"6",r:".75",fill:"currentColor",stroke:"none"}),v.jsx("circle",{cx:"6",cy:"12",r:".75",fill:"currentColor",stroke:"none"}),v.jsx("circle",{cx:"6",cy:"18",r:".75",fill:"currentColor",stroke:"none"})]});case"repoviz":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"6",cy:"12",r:"3"}),v.jsx("circle",{cx:"18",cy:"6",r:"3"}),v.jsx("circle",{cx:"18",cy:"18",r:"3"}),v.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),v.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),v.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),v.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M14 4a4 4 0 014 4l-7 7-4-4 7-7zM7 11l-3 3 6 6 3-3"})});case"quick-open":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),v.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),v.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});default:return null}}const E6e=s=>`sm.fileTree.expanded:${s}`;function fNt(s){try{const e=localStorage.getItem(E6e(s)),i=e?JSON.parse(e):[];return Array.isArray(i)?i.filter(n=>typeof n=="string"):[]}catch{return[]}}function gNt(s,e){try{localStorage.setItem(E6e(s),JSON.stringify([...e].slice(0,500)))}catch{}}function QX(s,e){const i=e+"/";let n=!1;const r=new Set;for(const o of s){if(o===e||o.startsWith(i)){n=!0;continue}r.add(o)}return n?r:s}const JX={modified:{color:"#e2a93d",label:"M"},added:{color:"#3fb950",label:"A"},deleted:{color:"#f85149",label:"D"},renamed:{color:"#a371f7",label:"R"},untracked:{color:"#8b949e",label:"U"},staged:{color:"#3fb950",label:"S"},conflict:{color:"#f85149",label:"!"}},pNt=new Set(["md","txt","json","jsonl","ndjson","js","jsx","ts","tsx","py","go","rs","rb","c","cpp","h","hpp","java","sh","bash","css","scss","html","xml","yaml","yml","toml","ini","conf","env","log","sql","gitignore","png","jpg","jpeg","gif","svg","webp"]);function mNt(s){const e=s.toLowerCase().split(".").pop()||"";return pNt.has(e)}function _Nt(s,e){if(e)return"#d97757";switch(s.toLowerCase().split(".").pop()||""){case"ts":case"tsx":return"#3178c6";case"js":case"jsx":return"#f7df1e";case"json":return"#cbcb41";case"md":return"#8a93a0";case"css":case"scss":return"#cc6699";case"py":return"#3776ab";case"go":return"#00add8";case"rs":return"#dea584";case"sh":case"bash":return"#89e051";case"png":case"jpg":case"jpeg":case"gif":case"svg":return"#a4c639";default:return"#8a93a0"}}async function Q$(s){var e;try{const i=window.api;return(e=i==null?void 0:i.git)!=null&&e.fileStatus?await i.git.fileStatus(s):{}}catch{return{}}}function vNt({cwd:s,onPreviewFile:e,onSendToChat:i,activeTabId:n}){const[r,o]=z.useState([]),[a,l]=z.useState(new Set),c=z.useRef(a);c.current=a;const[d,u]=z.useState(""),[h,f]=z.useState(!1),[g,p]=z.useState(!1),[_,m]=z.useState(null),[b,y]=z.useState({}),[x,S]=z.useState(null),[k,D]=z.useState(null),[T,N]=z.useState(""),[A,O]=z.useState(null),[$,P]=z.useState(""),[B,W]=z.useState(null),q=z.useRef(null),G=z.useRef(null),re=z.useRef(0),ie=z.useCallback(async()=>{if(!s)return;const Je=++re.current;p(!0),m(null);const Ct=await window.api.files.list(s,h);re.current===Je&&(Ct.ok?o(Ct.entries.map(Ft=>({...Ft}))):(m(Ct.error??"failed to list"),o([])),p(!1))},[s,h]),K=z.useCallback(async Je=>{const Ct=re.current,Ft=new Map;for(const En of Je){const Ji=En.split("/").length,cn=Ft.get(Ji);cn?cn.push(En):Ft.set(Ji,[En])}const Ot=[];for(const En of[...Ft.keys()].sort((Ji,cn)=>Ji-cn)){const Ji=Ft.get(En),cn=await Promise.all(Ji.map(async Tn=>({p:Tn,result:await window.api.files.list(Tn,h)})));if(re.current!==Ct)return Ot;for(const{p:Tn,result:Ts}of cn)Ts.ok?o(ds=>N8(ds,Tn,Ts.entries.map(rr=>({...rr})))):Ot.push(Tn)}return Ot},[h]),Z=z.useCallback(async Je=>(await ie(),Je.length?K(Je):[]),[ie,K]);z.useEffect(()=>{u(""),D(null),S(null),O(null),W(null),y({});const Je=fNt(s),Ct=new Set(Je);c.current=Ct,l(Ct);let Ft=!1;return(async()=>{const Ot=await Z(Je);Ft||!Ot.length||ne(En=>{const Ji=new Set;let cn=!1;for(const Tn of En){if(Ot.some(Ts=>Tn===Ts||Tn.startsWith(Ts+"/"))){cn=!0;continue}Ji.add(Tn)}return cn?Ji:En})})(),Q$(s).then(Ot=>{Ft||y(Ot)}),()=>{Ft=!0}},[s]);const Q=z.useRef(!0);z.useEffect(()=>{if(Q.current){Q.current=!1;return}Z([...c.current])},[h]),z.useEffect(()=>{if(!s)return;const Je=window.setInterval(()=>{Q$(s).then(y)},5e3);return()=>window.clearInterval(Je)},[s]),z.useEffect(()=>{if(!x)return;const Je=()=>S(null),Ct=Ft=>{Ft.key==="Escape"&&S(null)};return window.addEventListener("mousedown",Je),window.addEventListener("keydown",Ct),()=>{window.removeEventListener("mousedown",Je),window.removeEventListener("keydown",Ct)}},[x]),z.useEffect(()=>{k&&setTimeout(()=>{var Je;return(Je=q.current)==null?void 0:Je.select()},30)},[k]),z.useEffect(()=>{A&&setTimeout(()=>{var Je;return(Je=G.current)==null?void 0:Je.focus()},30)},[A]);const ne=z.useCallback(Je=>{const Ct=c.current,Ft=Je(Ct);Ft!==Ct&&(c.current=Ft,l(Ft),gNt(s,Ft))},[s]),ge=z.useCallback(async Je=>{if(a.has(Je.path)){ne(Ft=>QX(Ft,Je.path));return}if(ne(Ft=>new Set(Ft).add(Je.path)),Je.children)return;const Ct=await window.api.files.list(Je.path,h);Ct.ok&&o(Ft=>N8(Ft,Je.path,Ct.entries.map(Ot=>({...Ot}))))},[a,h,ne]),Se=z.useCallback(async Je=>{if(Je===s){await ie();return}const Ct=await window.api.files.list(Je,h);Ct.ok&&o(Ft=>N8(Ft,Je,Ct.entries.map(Ot=>({...Ot}))))},[s,ie,h]),Ee=z.useCallback(Je=>{if(Je.isDirectory){ge(Je);return}mNt(Je.name)&&e?e(Je.path):window.api.files.openExternal(Je.path)},[ge,e]),$e=z.useCallback(Je=>{if(i){i(Je);return}if(n){const Ct=Je.startsWith(s+"/")?Je.slice(s.length+1):Je;window.api.pty.write({tabId:n,data:`@${Ct} `})}},[i,n,s]),De=z.useCallback((Je,Ct)=>{Je.preventDefault(),Je.stopPropagation(),S({x:Je.clientX,y:Je.clientY,node:Ct})},[]),ae=Je=>{D(Je.path),N(Je.name)},Te=async()=>{if(!k)return;const Je=T.trim();if(!Je){D(null);return}const Ct=await window.api.files.rename(k,Je);if(D(null),Ct.ok){const Ft=k.slice(0,k.lastIndexOf("/"));ne(Ot=>QX(Ot,k)),await Se(Ft||s),Q$(s).then(y)}else m(Ct.error??"rename failed")},Ie=async()=>{if(!A)return;const Je=$.trim();if(!Je){O(null),P("");return}const Ct=await window.api.files.create(A.parent,Je,A.kind);O(null),P(""),Ct.ok?(await Se(A.parent),A.kind==="folder"&&ne(Ft=>new Set(Ft).add(A.parent))):m(Ct.error??"create failed")},st=async()=>{if(!B)return;const Je=await window.api.files.delete(B.path),Ct=B.path.slice(0,B.path.lastIndexOf("/"));W(null),Je.ok?(ne(Ft=>QX(Ft,B.path)),await Se(Ct||s),Q$(s).then(y)):m(Je.error??"delete failed")},He=z.useMemo(()=>{if(!d.trim())return r;const Je=d.toLowerCase();return r.filter(Ct=>Ct.name.toLowerCase().includes(Je))},[r,d]),lt=(s==null?void 0:s.split("/").filter(Boolean).pop())||"project";return v.jsxs("div",{className:"w-60 h-full flex flex-col bg-bg-elev border-r border-line text-fg",children:[v.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[v.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[v.jsx(T6e,{size:14,className:"shrink-0 text-accent"}),v.jsxs("div",{className:"flex-1 min-w-0",children:[v.jsx("p",{className:"text-xs font-medium text-fg truncate",children:lt}),v.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:s,children:s})]}),v.jsx("button",{onClick:ie,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:g,children:v.jsx(SNt,{size:12,className:g?"animate-spin":""})})]}),v.jsx("div",{className:"relative",children:v.jsx("input",{value:d,onChange:Je=>u(Je.target.value),placeholder:"Search files…",className:"w-full px-2 py-1 text-xs bg-bg-hi border border-line rounded text-fg placeholder-fg-faint focus:outline-none focus:border-accent/40"})})]}),v.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[v.jsx("button",{onClick:()=>O({parent:s,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:v.jsx(kNt,{size:12})}),v.jsx("button",{onClick:()=>O({parent:s,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:v.jsx(LNt,{size:12})}),v.jsx("div",{className:"flex-1"}),v.jsx("button",{onClick:()=>f(Je=>!Je),className:`p-1.5 rounded transition-colors ${h?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:h?"Hide hidden files":"Show hidden files",children:h?v.jsx(ENt,{size:12}):v.jsx(DNt,{size:12})})]}),v.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[_&&v.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:_}),!_&&He.length===0&&!g&&v.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:d?"no matches":"empty folder"}),!_&&v.jsx(D6e,{nodes:He,depth:0,expanded:a,gitStatus:b,renaming:k,renameValue:T,renameInputRef:q,onRenameChange:N,onRenameCommit:Te,onRenameCancel:()=>D(null),onToggleDir:ge,onFileClick:Ee,onSendToChat:$e,onContextMenu:De})]}),v.jsx("div",{className:"px-3 py-1.5 border-t border-line text-[10px] text-fg-faint shrink-0",children:"Click to preview · Double-click external · Right-click for more"}),x&&v.jsx(bNt,{x:x.x,y:x.y,node:x.node,onClose:()=>S(null),onRename:()=>{ae(x.node),S(null)},onDelete:()=>{W(x.node),S(null)},onNewFile:()=>{O({parent:x.node.path,kind:"file"}),S(null)},onNewFolder:()=>{O({parent:x.node.path,kind:"folder"}),S(null)},onOpenExternal:()=>{window.api.files.openExternal(x.node.path),S(null)},onShowInFinder:()=>{window.api.files.showInFinder(x.node.path),S(null)},onCopyPath:()=>{var Je;(Je=navigator.clipboard)==null||Je.writeText(x.node.path),S(null)},onSendToChat:()=>{$e(x.node.path),S(null)}}),A&&v.jsx(gke,{title:`New ${A.kind}`,subtitle:`in ${yNt(A.parent)}`,onCancel:()=>{O(null),P("")},onConfirm:Ie,confirmLabel:"Create",confirmDisabled:!$.trim(),children:v.jsx("input",{ref:G,value:$,onChange:Je=>P(Je.target.value),onKeyDown:Je=>{Je.key==="Enter"&&Ie(),Je.key==="Escape"&&(O(null),P(""))},placeholder:A.kind==="file"?"filename.txt":"folder-name",className:"w-full px-3 py-2 rounded bg-bg-hi border border-line text-fg text-sm placeholder-fg-faint focus:outline-none focus:border-accent/50"})}),B&&v.jsx(gke,{title:`Delete ${B.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>W(null),onConfirm:st,confirmLabel:"Delete",danger:!0,children:v.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",v.jsxs("span",{className:"text-fg font-medium",children:['"',B.name,'"']})," to the trash?",B.isDirectory&&v.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function D6e(s){const{nodes:e,depth:i,expanded:n,gitStatus:r,renaming:o,onContextMenu:a}=s;return v.jsx(v.Fragment,{children:e.map(l=>{const c=n.has(l.path),d=o===l.path,u=r[l.path],h=_Nt(l.name,l.isDirectory);return v.jsxs("div",{children:[v.jsxs("div",{className:"group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi",style:{paddingLeft:`${8+i*14}px`},onClick:()=>{d||(l.isDirectory?s.onToggleDir(l):s.onFileClick(l))},onDoubleClick:()=>{l.isDirectory||window.api.files.openExternal(l.path)},onContextMenu:f=>a(f,l),children:[l.isDirectory?v.jsx(CNt,{size:10,className:`shrink-0 text-fg-faint transition-transform ${c?"rotate-90":""}`}):v.jsx("span",{className:"w-[10px] shrink-0"}),l.isDirectory?c?v.jsx(wNt,{size:12,color:h}):v.jsx(T6e,{size:12,color:h}):v.jsx(xNt,{size:12,color:h}),d?v.jsx("input",{ref:s.renameInputRef,value:s.renameValue,onChange:f=>s.onRenameChange(f.target.value),onClick:f=>f.stopPropagation(),onBlur:s.onRenameCommit,onKeyDown:f=>{f.key==="Enter"&&s.onRenameCommit(),f.key==="Escape"&&s.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):v.jsx("span",{className:`flex-1 truncate text-xs ${l.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:l.name}),u&&v.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:JX[u].color,backgroundColor:`${JX[u].color}20`},title:u,children:JX[u].label}),!l.isDirectory&&v.jsx("button",{onClick:f=>{f.stopPropagation(),s.onSendToChat(l.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:v.jsx(TNt,{size:10})})]}),l.isDirectory&&c&&l.children&&v.jsx(D6e,{...s,nodes:l.children,depth:i+1})]},l.path)})})}function bNt(s){const{x:e,y:i,node:n}=s;return v.jsxs("div",{onMouseDown:r=>r.stopPropagation(),className:"fixed z-[300] w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1",style:{left:e,top:i},children:[!n.isDirectory&&v.jsx(Ew,{label:"Send to chat",onClick:s.onSendToChat}),v.jsx(Ew,{label:"Open in default app",onClick:s.onOpenExternal}),v.jsx(Ew,{label:"Reveal in OS",onClick:s.onShowInFinder}),v.jsx(eZ,{}),v.jsx(Ew,{label:"Copy path",onClick:s.onCopyPath}),v.jsx(Ew,{label:"Rename",onClick:s.onRename}),n.isDirectory&&v.jsxs(v.Fragment,{children:[v.jsx(eZ,{}),v.jsx(Ew,{label:"New file",onClick:s.onNewFile}),v.jsx(Ew,{label:"New folder",onClick:s.onNewFolder})]}),v.jsx(eZ,{}),v.jsx(Ew,{label:"Delete",onClick:s.onDelete,danger:!0})]})}function Ew({label:s,onClick:e,danger:i}){return v.jsx("button",{onClick:e,className:`w-full text-left px-3 py-1.5 hover:bg-bg-hi transition-colors ${i?"text-red-400":"text-fg-dim hover:text-fg"}`,children:s})}function eZ(){return v.jsx("div",{className:"my-1 border-t border-line"})}function gke(s){return v.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:e=>{e.target===e.currentTarget&&s.onCancel()},children:v.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[v.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:s.title}),s.subtitle&&v.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:s.subtitle}),v.jsx("div",{className:"mb-4",children:s.children}),v.jsxs("div",{className:"flex justify-end gap-2",children:[v.jsx("button",{onClick:s.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),v.jsx("button",{onClick:s.onConfirm,disabled:!!s.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${s.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:s.confirmLabel??"OK"})]})]})})}function yNt(s){return s.split("/").filter(Boolean).pop()||s}function N8(s,e,i){return s.map(n=>n.path===e?{...n,children:i}:n.children?{...n,children:N8(n.children,e,i)}:n)}function tv({size:s,children:e,className:i,color:n}){return v.jsx("svg",{width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:n||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:i,children:e})}function T6e({size:s,className:e,color:i}){return v.jsx(tv,{size:s,className:e,color:i,children:v.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function wNt({size:s,className:e,color:i}){return v.jsx(tv,{size:s,className:e,color:i,children:v.jsx("path",{d:"M6 14l1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2"})})}function xNt({size:s,className:e,color:i}){return v.jsxs(tv,{size:s,className:e,color:i,children:[v.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),v.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function CNt({size:s,className:e}){return v.jsx(tv,{size:s,className:e,children:v.jsx("polyline",{points:"9 18 15 12 9 6"})})}function SNt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("polyline",{points:"23 4 23 10 17 10"}),v.jsx("polyline",{points:"1 20 1 14 7 14"}),v.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function kNt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),v.jsx("polyline",{points:"14 2 14 8 20 8"}),v.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),v.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function LNt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"}),v.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),v.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function ENt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),v.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function DNt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),v.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function TNt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),v.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function INt(s,e={}){switch(s){case"ready":return e.isRecording?"Stop voice input":"Start voice input (local Whisper, offline)";case"idle":return"Microphone — speech model not started";case"loading":return`Microphone — loading speech model, ${typeof e.loadingPct=="number"?Math.round(e.loadingPct):0} percent`;case"error":return e.errorMessage?`Microphone — speech model error: ${e.errorMessage}. Activate to retry.`:"Microphone — speech model error. Activate to retry.";case"load-timeout":return"Microphone — model load timed out. Activate to retry.";case"permission-denied":return"Microphone — permission denied. Open OS settings.";case"unsupported":return"Microphone — voice input not supported in this build."}}const pke=s=>Symbol.iterator in s,mke=s=>"entries"in s,_ke=(s,e)=>{const i=s instanceof Map?s:new Map(s.entries()),n=e instanceof Map?e:new Map(e.entries());if(i.size!==n.size)return!1;for(const[r,o]of i)if(!n.has(r)||!Object.is(o,n.get(r)))return!1;return!0},NNt=(s,e)=>{const i=s[Symbol.iterator](),n=e[Symbol.iterator]();let r=i.next(),o=n.next();for(;!r.done&&!o.done;){if(!Object.is(r.value,o.value))return!1;r=i.next(),o=n.next()}return!!r.done&&!!o.done};function RNt(s,e){return Object.is(s,e)?!0:typeof s!="object"||s===null||typeof e!="object"||e===null||Object.getPrototypeOf(s)!==Object.getPrototypeOf(e)?!1:pke(s)&&pke(e)?mke(s)&&mke(e)?_ke(s,e):NNt(s,e):_ke({entries:()=>Object.entries(s)},{entries:()=>Object.entries(e)})}function I6e(s){const e=at.useRef(void 0);return i=>{const n=s(i);return RNt(e.current,n)?e.current:e.current=n}}let vke=0;const ANt=1e3;function MNt(s){const e=performance.now();e-vke<ANt||(vke=e,ti.debug("voice","mic.gate.click_rejected",{reason:s}))}function N6e(){const s=zi(d=>d.isRecording),e=zi(d=>d.error),i=zi(d=>d.loadingProgress),n=zi(I6e(pde)),r=()=>{const d=zi.getState(),{canRecord:u,reason:h}=pde(d);if(d.isRecording)return d.stopRecording();if(d.wizardArmed&&!d.wizardOpen){d.openWizard();return}if(h==="error"||h==="load-timeout"){d.resetAndRetryModel();return}if(!u)return MNt(h);const f=hn.getState().activeTabId;f&&d.startRecording(f)},o=INt(n.reason,{loadingPct:i,errorMessage:e,isRecording:s}),a=n.reason==="unsupported",l=!n.canRecord,c=n.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":n.reason==="error"||n.reason==="load-timeout"?"text-red-400 cursor-pointer":n.reason==="permission-denied"?"text-amber-400 cursor-pointer":n.reason==="idle"?"text-fg-faint cursor-pointer":n.reason==="unsupported"?"text-fg-faint cursor-not-allowed":s?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return v.jsx("button",{onClick:r,disabled:a,"aria-disabled":l,"aria-label":o,title:o,"data-testid":"mic-button","data-state":n.reason,className:`p-1.5 rounded transition-colors ${c}`,children:v.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[v.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),v.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),v.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),v.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function PNt(){const s=zi(i=>i.ttsEnabled),e=zi(i=>i.toggleTTS);return v.jsxs("button",{onClick:e,title:s?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${s?"text-accent":"text-fg-dim hover:text-fg"}`,children:[v.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[v.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s?v.jsxs(v.Fragment,{children:[v.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),v.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):v.jsxs(v.Fragment,{children:[v.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),v.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),v.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}const bke=[{key:"overview",label:"Home",icon:"home",hint:"Today's sessions + the 5-hour window"},{key:"terminal",label:"Terminal",icon:"terminal",hint:"Live Claude Code, in-app"},{key:"agent-view",label:"Agent-View",icon:"agent-view",liveKind:"agentView",hint:"Workshop scene of the active session"},{key:"subagents",label:"Subagents",icon:"hive",liveKind:"subagents",hint:"Sub-agents working in parallel"},{key:"scheduler",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Author PRDs + run them as claude -p jobs"},{key:"prompts",label:"Prompts",icon:"book",hint:"Click-to-insert prompt library"},{key:"tasks",label:"Tasks",icon:"tasks",liveKind:"tasks",hint:"Active to-dos across sessions"},{key:"history",label:"History",icon:"history",hint:"Every session, ever — resumable"},{key:"usage",label:"Usage",icon:"usage",hint:"Tokens, cost, sessions per day"},{key:"knowledge-graph",label:"Knowledge Graph",icon:"knowledge-graph",hint:"Distilled graph + Q&A over your prompt log"}],yke=[{key:"skills",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads"},{key:"plugins",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code"},{key:"mcp",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations"},{key:"hooks",label:"Hooks",icon:"hooks",hint:"Run scripts on session events"},{key:"keybindings",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override"},{key:"doc-editor",label:"Doc Editor",icon:"docs",hint:"Edit CLAUDE.md and friends"},{key:"memory",label:"Memory",icon:"memory",hint:"Workspace memory store"},{key:"projects",label:"Projects",icon:"projects",hint:"All known project folders"},{key:"system-prompt",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior"},{key:"permissions",label:"Permissions",icon:"permissions",hint:"Allow / deny rules"},{key:"settings",label:"Settings",icon:"settings",hint:"Theme, voice, billing window"},{key:"remote",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default"}],wke=[{key:"voice",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk"},{key:"dispatch",label:"Dispatch",icon:"orchestrator",hint:"Boss · Orchestrate · Race · Hives"},{key:"repoviz",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map"},{key:"search",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content"}],mde="sm.almanac.sidebarWidth",R6e=180,A6e=480,_de=252;function ONt(){try{const s=parseInt(localStorage.getItem(mde)??"",10);if(Number.isFinite(s))return Math.min(A6e,Math.max(R6e,s))}catch{}return _de}const M6e="sm.almanac.sidebarMode";function FNt(){try{return localStorage.getItem(M6e)==="files"?"files":"nav"}catch{return"nav"}}const P6e="sm.almanac.collapsedGroups";function BNt(){try{const s=localStorage.getItem(P6e);if(!s)return new Set;const e=JSON.parse(s);return Array.isArray(e)?new Set(e.filter(i=>i==="Workspace"||i==="Configure"||i==="Tools")):new Set}catch{return new Set}}function jNt(){const s=k8(o=>o.tabs),e=D1(o=>{var a;return(((a=o.snapshot)==null?void 0:a.jobs)??[]).some(l=>l.status==="running")}),[i,n]=z.useState(()=>Date.now());z.useEffect(()=>{const o=setInterval(()=>n(Date.now()),5e3);return()=>clearInterval(o)},[]);const r=Object.values(s);return{subagents:r.some(o=>o.agents.some(a=>i-a.at<6e4)),tasks:r.some(o=>o.todos.some(a=>a.status==="in_progress")),agentView:r.some(o=>o.lastEventAt>0&&i-o.lastEventAt<5e3),scheduler:e}}function $Nt({active:s,onNavigate:e,onNewSession:i,onOpenFile:n}){const[r,o]=z.useState(()=>FNt()),a=z.useCallback(x=>{o(x);try{localStorage.setItem(M6e,x)}catch{}},[]),[l,c]=z.useState(()=>BNt()),d=z.useCallback(x=>{c(S=>{const k=new Set(S);k.has(x)?k.delete(x):k.add(x);try{localStorage.setItem(P6e,JSON.stringify(Array.from(k)))}catch{}return k})},[]),u=hn(x=>x.tabs),h=hn(x=>x.activeTabId),f=u.find(x=>x.id===h)??null,g=jNt(),[p,_]=z.useState(()=>ONt()),m=z.useRef(p);m.current=p;const b=z.useCallback(x=>{x.preventDefault();const S=x.clientX,k=m.current;let D=k;const T=A=>{D=Math.min(A6e,Math.max(R6e,k+(A.clientX-S))),_(D)},N=()=>{window.removeEventListener("pointermove",T),window.removeEventListener("pointerup",N),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(mde,String(D))}catch{}};window.addEventListener("pointermove",T),window.addEventListener("pointerup",N),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),y=z.useCallback(()=>{_(_de);try{localStorage.setItem(mde,String(_de))}catch{}},[]);return v.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative",style:{width:p},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[v.jsx(WNt,{tab:f,onNewSession:i}),v.jsx("div",{className:"px-3.5 pt-3 pb-2 flex gap-1",children:["nav","files"].map(x=>v.jsx("button",{onClick:()=>a(x),"aria-pressed":r===x,className:`flex-1 py-1.5 rounded-md text-[12px] font-semibold tracking-[0.02em] transition-colors ${r===x?"bg-bg-hi text-fg border border-line":"text-fg-faint hover:text-fg-dim border border-transparent"}`,children:x==="nav"?"Navigate":"Files"},x))}),v.jsx("div",{className:"flex-1 min-h-0 overflow-auto px-2 pb-3",children:r==="nav"?v.jsxs(v.Fragment,{children:[v.jsx(tZ,{label:"Workspace",collapsed:l.has("Workspace"),count:bke.length,onToggle:()=>d("Workspace")}),!l.has("Workspace")&&bke.map(x=>v.jsx(xke,{item:x,active:s===x.key,live:x.liveKind?g[x.liveKind]:!1,onClick:()=>e(x.key)},x.key)),v.jsx(tZ,{label:"Configure",collapsed:l.has("Configure"),count:yke.length,onToggle:()=>d("Configure")}),!l.has("Configure")&&yke.map(x=>v.jsx(xke,{item:x,active:s===x.key,live:!1,onClick:()=>e(x.key)},x.key)),v.jsx(tZ,{label:"Tools",collapsed:l.has("Tools"),count:wke.length,onToggle:()=>d("Tools")}),!l.has("Tools")&&wke.map(x=>v.jsx(zNt,{tool:x,active:s===x.key,onClick:()=>e(x.key)},x.key))]}):v.jsx(UNt,{tab:f,onOpenFile:n})}),v.jsx(GNt,{}),v.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:b,onDoubleClick:y,className:"absolute top-0 right-0 h-full w-1.5 translate-x-1/2 z-10 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"})]})}function WNt({tab:s,onNewSession:e}){const i=(s==null?void 0:s.label)??"no session",n=VNt((s==null?void 0:s.cwd)??null);return v.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[v.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),v.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[v.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),v.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(s==null?void 0:s.cwd)??"",children:i})]}),v.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:n?`⌥${n}`:s?s.cwd:"—"}),v.jsxs("div",{className:"mt-3 flex items-stretch gap-1.5",children:[v.jsxs("button",{onClick:e,"data-testid":"tour-new-session",className:"flex-1 px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center gap-1.5",children:[v.jsx(wy,{name:"plus",size:13,stroke:1.8}),"New session"]}),v.jsx("div",{className:"flex items-center rounded-md bg-bg-hi border border-line",children:v.jsx(N6e,{})})]})]})}const J$=new Map,HNt=3e4;function VNt(s){const[e,i]=z.useState(()=>{var n;return s?((n=J$.get(s))==null?void 0:n.value)??null:null});return z.useEffect(()=>{if(!s){i(null);return}let n=!1;return(async()=>{const o=J$.get(s);if(o&&Date.now()-o.ts<HNt){n||i(o.value);return}try{const a=await window.api.app.gitBranch(s);if(n)return;J$.set(s,{value:a,ts:Date.now()}),i(a)}catch{if(n)return;J$.set(s,{value:null,ts:Date.now()}),i(null)}})(),()=>{n=!0}},[s]),e}function tZ({label:s,collapsed:e,count:i,onToggle:n}){return v.jsxs("button",{onClick:n,"aria-expanded":!e,title:e?`Expand ${s}`:`Collapse ${s}`,className:"group w-full flex items-center gap-1.5 px-3 pt-3.5 pb-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[v.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:e?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),v.jsx("span",{className:"flex-1",children:s}),e&&v.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:i})]})}function xke({item:s,active:e,live:i,onClick:n}){return v.jsxs("button",{onClick:n,title:s.hint,className:`relative w-full flex items-center gap-3 px-3.5 py-[9px] rounded-[10px] text-left text-[14px] mb-0.5 transition-colors ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&v.jsx("span",{"aria-hidden":!0,className:"absolute -left-[10px] top-3 bottom-3 w-[3px] rounded-sm bg-accent"}),v.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:v.jsx(wy,{name:s.icon,size:17,stroke:1.6})}),v.jsx("span",{className:"flex-1 truncate",children:s.label}),i&&v.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"})]})}function zNt({tool:s,active:e,onClick:i}){return v.jsxs("button",{onClick:i,title:s.hint,className:`relative w-full flex items-center gap-3 px-3.5 py-[7px] rounded-[10px] text-left text-[13px] mb-0.5 transition-colors ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&v.jsx("span",{"aria-hidden":!0,className:"absolute -left-[10px] top-2 bottom-2 w-[3px] rounded-sm bg-accent"}),v.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:v.jsx(wy,{name:s.icon,size:15,stroke:1.6})}),v.jsx("span",{className:"flex-1 truncate",children:s.label})]})}function UNt({tab:s,onOpenFile:e}){return s?v.jsxs("div",{className:"pt-1",children:[v.jsx("div",{className:"px-3 pb-2 text-[11.5px] text-fg-faint font-mono truncate",title:s.cwd,children:qNt(s.cwd)}),v.jsx(vNt,{cwd:s.cwd,activeTabId:s.id,onPreviewFile:e})]}):v.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:"No session selected."})}function qNt(s){const e="/home/";if(s.startsWith(e)){const i=s.slice(e.length).split("/").slice(1).join("/");return i?`~/${i}`:"~"}return s}function GNt(){const s=zi(a=>a.isRecording),e=hn(a=>a.tabs),i=hn(a=>a.activeTabId),n=e.find(a=>a.id===i)??null,[r,o]=z.useState(null);return z.useEffect(()=>{let a=!1;if(!(n!=null&&n.presetId)){o(null);return}return c6e(n.presetId).then(l=>{a||o((l==null?void 0:l.model)??null)}).catch(()=>{a||o(null)}),()=>{a=!0}},[n==null?void 0:n.presetId]),v.jsxs("div",{className:"px-3.5 py-2.5 border-t border-rule flex items-center gap-2 text-[11.5px] text-fg-dim font-mono",children:[v.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${s?"bg-red-500 animate-pulse":"bg-sage"}`,title:s?"recording":"idle"}),v.jsx("span",{className:"truncate",title:r??"",children:s?"recording…":r?`Claude · ${KNt(r)}`:"Claude Code"})]})}function KNt(s){var i,n,r,o,a,l;const e=s.toLowerCase();if(e.includes("opus")){const c=(n=(i=s.match(/(\d+[-.]?\d*)/))==null?void 0:i[1])==null?void 0:n.replace("-",".");return c?`Opus ${c}`:"Opus"}if(e.includes("sonnet")){const c=(o=(r=s.match(/(\d+[-.]?\d*)/))==null?void 0:r[1])==null?void 0:o.replace("-",".");return c?`Sonnet ${c}`:"Sonnet"}if(e.includes("haiku")){const c=(l=(a=s.match(/(\d+[-.]?\d*)/))==null?void 0:a[1])==null?void 0:l.replace("-",".");return c?`Haiku ${c}`:"Haiku"}return s}function YNt({onNavigate:s}){const e=hn(_=>_.tabs),i=hn(_=>_.activeTabId),n=e.find(_=>_.id===i)??null,r=KF(n),o=(r==null?void 0:r.lastEventAt)??0,a=WS(_=>_.data),[l,c]=z.useState(null),[,d]=z.useState(0);z.useEffect(()=>{const _=setInterval(()=>d(m=>m+1),6e4);return()=>clearInterval(_)},[]),z.useEffect(()=>{let _=!1;if(!(n!=null&&n.cwd)){c(null);return}return window.api.app.gitBranch(n.cwd).then(m=>{_||c(m)}).catch(()=>{_||c(null)}),()=>{_=!0}},[n==null?void 0:n.cwd]);const u=XF(a),h=(u==null?void 0:u.usage.five_hour)??null,f=h?Math.round(h.utilization):null,g=(a==null?void 0:a.kind)==="ok"||(a==null?void 0:a.kind)==="ok-stale",p=o>0?XNt(Date.now()-o):"—";return v.jsxs("div",{className:"h-[30px] shrink-0 bg-bg-elev border-t border-line flex items-center gap-4 px-[18px] font-mono text-[11.5px] text-fg-dim","data-testid":"tour-statusbar",children:[v.jsxs("button",{onClick:()=>s==null?void 0:s("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:g?"Connected to Anthropic":"Disconnected",children:[v.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${g?"bg-sage":"bg-fg-faint"}`}),v.jsx("span",{children:g?"connected":"offline"})]}),v.jsx("button",{onClick:()=>s==null?void 0:s("usage"),className:"hover:text-fg transition-colors",title:"Open Usage",children:f!=null?`${f}% of 5h window used`:"5h —"}),n&&v.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,l&&v.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",l]})]}),v.jsxs("span",{className:"text-fg-faint",children:["last activity: ",v.jsx("span",{className:"text-fg-dim",children:p})]}),v.jsx("span",{className:"flex-1"}),v.jsxs("span",{className:"text-fg-faint",children:["v","0.21.0"]})]})}function XNt(s){const e=Math.max(0,Math.floor(s/1e3));if(e<60)return`${e}s ago`;const i=Math.floor(e/60);return i<60?`${i}m ago`:`${Math.floor(i/60)}h ago`}var iZ={exports:{}},Cke;function ZNt(){return Cke||(Cke=1,(function(s,e){(function(i,n){s.exports=n()})(globalThis,(()=>(()=>{var i={4567:function(a,l,c){var d=this&&this.__decorate||function(y,x,S,k){var D,T=arguments.length,N=T<3?x:k===null?k=Object.getOwnPropertyDescriptor(x,S):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(y,x,S,k);else for(var A=y.length-1;A>=0;A--)(D=y[A])&&(N=(T<3?D(N):T>3?D(x,S,N):D(x,S))||N);return T>3&&N&&Object.defineProperty(x,S,N),N},u=this&&this.__param||function(y,x){return function(S,k){x(S,k,y)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const h=c(9042),f=c(9924),g=c(844),p=c(4725),_=c(2585),m=c(3656);let b=l.AccessibilityManager=class extends g.Disposable{constructor(y,x,S,k){super(),this._terminal=y,this._coreBrowserService=S,this._renderService=k,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let D=0;D<this._terminal.rows;D++)this._rowElements[D]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[D]);if(this._topBoundaryFocusListener=D=>this._handleBoundaryFocus(D,0),this._bottomBoundaryFocusListener=D=>this._handleBoundaryFocus(D,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new f.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((D=>this._handleResize(D.rows)))),this.register(this._terminal.onRender((D=>this._refreshRows(D.start,D.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((D=>this._handleChar(D)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3811
|
+
*/var JSe;function I2t(){return JSe||(JSe=1,(function(s,e){var i=(()=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,l=(de=>typeof ug<"u"?ug:typeof Proxy<"u"?new Proxy(de,{get:(be,Ne)=>(typeof ug<"u"?ug:be)[Ne]}):de)(function(de){if(typeof ug<"u")return ug.apply(this,arguments);throw Error('Dynamic require of "'+de+'" is not supported')}),c=(de,be)=>()=>(de&&(be=de(de=0)),be),d=(de,be)=>{for(var Ne in be)n(de,Ne,{get:be[Ne],enumerable:!0})},u=(de,be,Ne,Ve)=>{if(be&&typeof be=="object"||typeof be=="function")for(let Oe of o(be))!a.call(de,Oe)&&Oe!==Ne&&n(de,Oe,{get:()=>be[Oe],enumerable:!(Ve=r(be,Oe))||Ve.enumerable});return de},h=de=>u(n({},"__esModule",{value:!0}),de),f,g,p,_,m,b=c(()=>{f=new Map,g=[],p=(de,be,Ne)=>{if(be&&typeof be.init=="function"&&typeof be.createInferenceSessionHandler=="function"){let Ve=f.get(de);if(Ve===void 0)f.set(de,{backend:be,priority:Ne});else{if(Ve.priority>Ne)return;if(Ve.priority===Ne&&Ve.backend!==be)throw new Error(`cannot register backend "${de}" using priority ${Ne}`)}if(Ne>=0){let Oe=g.indexOf(de);Oe!==-1&&g.splice(Oe,1);for(let rt=0;rt<g.length;rt++)if(f.get(g[rt]).priority<=Ne){g.splice(rt,0,de);return}g.push(de)}return}throw new TypeError("not a valid backend")},_=async de=>{let be=f.get(de);if(!be)return"backend not found.";if(be.initialized)return be.backend;if(be.aborted)return be.error;{let Ne=!!be.initPromise;try{return Ne||(be.initPromise=be.backend.init(de)),await be.initPromise,be.initialized=!0,be.backend}catch(Ve){return Ne||(be.error=`${Ve}`,be.aborted=!0),be.error}finally{delete be.initPromise}}},m=async de=>{let be=de.executionProviders||[],Ne=be.map(dt=>typeof dt=="string"?dt:dt.name),Ve=Ne.length===0?g:Ne,Oe,rt=[],qe=new Set;for(let dt of Ve){let Tt=await _(dt);typeof Tt=="string"?rt.push({name:dt,err:Tt}):(Oe||(Oe=Tt),Oe===Tt&&qe.add(dt))}if(!Oe)throw new Error(`no available backend found. ERR: ${rt.map(dt=>`[${dt.name}] ${dt.err}`).join(", ")}`);for(let{name:dt,err:Tt}of rt)Ne.includes(dt)&&console.warn(`removing requested execution provider "${dt}" from session options because it is not available: ${Tt}`);let Ge=be.filter(dt=>qe.has(typeof dt=="string"?dt:dt.name));return[Oe,new Proxy(de,{get:(dt,Tt)=>Tt==="executionProviders"?Ge:Reflect.get(dt,Tt)})]}}),y=c(()=>{b()}),x,S=c(()=>{x="1.26.0"}),k,D,T=c(()=>{S(),k="warning",D={wasm:{},webgl:{},webgpu:{},versions:{common:x},set logLevel(de){if(de!==void 0){if(typeof de!="string"||["verbose","info","warning","error","fatal"].indexOf(de)===-1)throw new Error(`Unsupported logging level: ${de}`);k=de}},get logLevel(){return k}},Object.defineProperty(D,"logLevel",{enumerable:!0})}),N,A=c(()=>{T(),N=D}),O,$,P=c(()=>{O=(de,be)=>{let Ne=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);Ne.width=de.dims[3],Ne.height=de.dims[2];let Ve=Ne.getContext("2d");if(Ve!=null){let Oe,rt;(be==null?void 0:be.tensorLayout)!==void 0&&be.tensorLayout==="NHWC"?(Oe=de.dims[2],rt=de.dims[3]):(Oe=de.dims[3],rt=de.dims[2]);let qe=(be==null?void 0:be.format)!==void 0?be.format:"RGB",Ge=be==null?void 0:be.norm,dt,Tt;Ge===void 0||Ge.mean===void 0?dt=[255,255,255,255]:typeof Ge.mean=="number"?dt=[Ge.mean,Ge.mean,Ge.mean,Ge.mean]:(dt=[Ge.mean[0],Ge.mean[1],Ge.mean[2],0],Ge.mean[3]!==void 0&&(dt[3]=Ge.mean[3])),Ge===void 0||Ge.bias===void 0?Tt=[0,0,0,0]:typeof Ge.bias=="number"?Tt=[Ge.bias,Ge.bias,Ge.bias,Ge.bias]:(Tt=[Ge.bias[0],Ge.bias[1],Ge.bias[2],0],Ge.bias[3]!==void 0&&(Tt[3]=Ge.bias[3]));let $t=rt*Oe,Nt=0,wt=$t,Pi=$t*2,it=-1;qe==="RGBA"?(Nt=0,wt=$t,Pi=$t*2,it=$t*3):qe==="RGB"?(Nt=0,wt=$t,Pi=$t*2):qe==="RBG"&&(Nt=0,Pi=$t,wt=$t*2);for(let Qt=0;Qt<rt;Qt++)for(let hr=0;hr<Oe;hr++){let xn=(de.data[Nt++]-Tt[0])*dt[0],Cn=(de.data[wt++]-Tt[1])*dt[1],fr=(de.data[Pi++]-Tt[2])*dt[2],Yi=it===-1?255:(de.data[it++]-Tt[3])*dt[3];Ve.fillStyle="rgba("+xn+","+Cn+","+fr+","+Yi+")",Ve.fillRect(hr,Qt,1,1)}if("toDataURL"in Ne)return Ne.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},$=(de,be)=>{let Ne=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Ve;if(Ne!=null){let Oe,rt,qe;(be==null?void 0:be.tensorLayout)!==void 0&&be.tensorLayout==="NHWC"?(Oe=de.dims[2],rt=de.dims[1],qe=de.dims[3]):(Oe=de.dims[3],rt=de.dims[2],qe=de.dims[1]);let Ge=be!==void 0&&be.format!==void 0?be.format:"RGB",dt=be==null?void 0:be.norm,Tt,$t;dt===void 0||dt.mean===void 0?Tt=[255,255,255,255]:typeof dt.mean=="number"?Tt=[dt.mean,dt.mean,dt.mean,dt.mean]:(Tt=[dt.mean[0],dt.mean[1],dt.mean[2],255],dt.mean[3]!==void 0&&(Tt[3]=dt.mean[3])),dt===void 0||dt.bias===void 0?$t=[0,0,0,0]:typeof dt.bias=="number"?$t=[dt.bias,dt.bias,dt.bias,dt.bias]:($t=[dt.bias[0],dt.bias[1],dt.bias[2],0],dt.bias[3]!==void 0&&($t[3]=dt.bias[3]));let Nt=rt*Oe;if(be!==void 0&&(be.format!==void 0&&qe===4&&be.format!=="RGBA"||qe===3&&be.format!=="RGB"&&be.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let wt=4,Pi=0,it=1,Qt=2,hr=3,xn=0,Cn=Nt,fr=Nt*2,Yi=-1;Ge==="RGBA"?(xn=0,Cn=Nt,fr=Nt*2,Yi=Nt*3):Ge==="RGB"?(xn=0,Cn=Nt,fr=Nt*2):Ge==="RBG"&&(xn=0,fr=Nt,Cn=Nt*2),Ve=Ne.createImageData(Oe,rt);for(let Fr=0;Fr<rt*Oe;Pi+=wt,it+=wt,Qt+=wt,hr+=wt,Fr++)Ve.data[Pi]=(de.data[xn++]-$t[0])*Tt[0],Ve.data[it]=(de.data[Cn++]-$t[1])*Tt[1],Ve.data[Qt]=(de.data[fr++]-$t[2])*Tt[2],Ve.data[hr]=Yi===-1?255:(de.data[Yi++]-$t[3])*Tt[3]}else throw new Error("Can not access image data");return Ve}}),B,W,q,G,re,ie,K=c(()=>{Te(),B=(de,be)=>{if(de===void 0)throw new Error("Image buffer must be defined");if(be.height===void 0||be.width===void 0)throw new Error("Image height and width must be defined");if(be.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:Ne,width:Ve}=be,Oe=be.norm??{mean:255,bias:0},rt,qe;typeof Oe.mean=="number"?rt=[Oe.mean,Oe.mean,Oe.mean,Oe.mean]:rt=[Oe.mean[0],Oe.mean[1],Oe.mean[2],Oe.mean[3]??255],typeof Oe.bias=="number"?qe=[Oe.bias,Oe.bias,Oe.bias,Oe.bias]:qe=[Oe.bias[0],Oe.bias[1],Oe.bias[2],Oe.bias[3]??0];let Ge=be.format!==void 0?be.format:"RGBA",dt=be.tensorFormat!==void 0&&be.tensorFormat!==void 0?be.tensorFormat:"RGB",Tt=Ne*Ve,$t=dt==="RGBA"?new Float32Array(Tt*4):new Float32Array(Tt*3),Nt=4,wt=0,Pi=1,it=2,Qt=3,hr=0,xn=Tt,Cn=Tt*2,fr=-1;Ge==="RGB"&&(Nt=3,wt=0,Pi=1,it=2,Qt=-1),dt==="RGBA"?fr=Tt*3:dt==="RBG"?(hr=0,Cn=Tt,xn=Tt*2):dt==="BGR"&&(Cn=0,xn=Tt,hr=Tt*2);for(let Yi=0;Yi<Tt;Yi++,wt+=Nt,it+=Nt,Pi+=Nt,Qt+=Nt)$t[hr++]=(de[wt]+qe[0])/rt[0],$t[xn++]=(de[Pi]+qe[1])/rt[1],$t[Cn++]=(de[it]+qe[2])/rt[2],fr!==-1&&Qt!==-1&&($t[fr++]=(de[Qt]+qe[3])/rt[3]);return dt==="RGBA"?new ae("float32",$t,[1,4,Ne,Ve]):new ae("float32",$t,[1,3,Ne,Ve])},W=async(de,be)=>{let Ne=typeof HTMLImageElement<"u"&&de instanceof HTMLImageElement,Ve=typeof ImageData<"u"&&de instanceof ImageData,Oe=typeof ImageBitmap<"u"&&de instanceof ImageBitmap,rt=typeof de=="string",qe,Ge=be??{},dt=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},Tt=$t=>typeof HTMLCanvasElement<"u"&&$t instanceof HTMLCanvasElement||$t instanceof OffscreenCanvas?$t.getContext("2d"):null;if(Ne){let $t=dt();$t.width=de.width,$t.height=de.height;let Nt=Tt($t);if(Nt!=null){let wt=de.height,Pi=de.width;if(be!==void 0&&be.resizedHeight!==void 0&&be.resizedWidth!==void 0&&(wt=be.resizedHeight,Pi=be.resizedWidth),be!==void 0){if(Ge=be,be.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Ge.tensorFormat="RGBA",Ge.height=wt,Ge.width=Pi}else Ge.tensorFormat="RGBA",Ge.height=wt,Ge.width=Pi;Nt.drawImage(de,0,0),qe=Nt.getImageData(0,0,Pi,wt).data}else throw new Error("Can not access image data")}else if(Ve){let $t,Nt;if(be!==void 0&&be.resizedWidth!==void 0&&be.resizedHeight!==void 0?($t=be.resizedHeight,Nt=be.resizedWidth):($t=de.height,Nt=de.width),be!==void 0&&(Ge=be),Ge.format="RGBA",Ge.height=$t,Ge.width=Nt,be!==void 0){let wt=dt();wt.width=Nt,wt.height=$t;let Pi=Tt(wt);if(Pi!=null)Pi.putImageData(de,0,0),qe=Pi.getImageData(0,0,Nt,$t).data;else throw new Error("Can not access image data")}else qe=de.data}else if(Oe){if(be===void 0)throw new Error("Please provide image config with format for Imagebitmap");let $t=dt();$t.width=de.width,$t.height=de.height;let Nt=Tt($t);if(Nt!=null){let wt=de.height,Pi=de.width;return Nt.drawImage(de,0,0,Pi,wt),qe=Nt.getImageData(0,0,Pi,wt).data,Ge.height=wt,Ge.width=Pi,B(qe,Ge)}else throw new Error("Can not access image data")}else{if(rt)return new Promise(($t,Nt)=>{let wt=dt(),Pi=Tt(wt);if(!de||!Pi)return Nt();let it=new Image;it.crossOrigin="Anonymous",it.src=de,it.onload=()=>{wt.width=it.width,wt.height=it.height,Pi.drawImage(it,0,0,wt.width,wt.height);let Qt=Pi.getImageData(0,0,wt.width,wt.height);Ge.height=wt.height,Ge.width=wt.width,$t(B(Qt.data,Ge))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(qe!==void 0)return B(qe,Ge);throw new Error("Input data provided is not supported - aborted tensor creation")},q=(de,be)=>{let{width:Ne,height:Ve,download:Oe,dispose:rt}=be,qe=[1,Ve,Ne,4];return new ae({location:"texture",type:"float32",texture:de,dims:qe,download:Oe,dispose:rt})},G=(de,be)=>{let{dataType:Ne,dims:Ve,download:Oe,dispose:rt}=be;return new ae({location:"gpu-buffer",type:Ne??"float32",gpuBuffer:de,dims:Ve,download:Oe,dispose:rt})},re=(de,be)=>{let{dataType:Ne,dims:Ve,download:Oe,dispose:rt}=be;return new ae({location:"ml-tensor",type:Ne??"float32",mlTensor:de,dims:Ve,download:Oe,dispose:rt})},ie=(de,be,Ne)=>new ae({location:"cpu-pinned",type:de,data:be,dims:Ne??[be.length]})}),Z,Q,ne,ge,Se=c(()=>{Z=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),Q=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),ne=!1,ge=()=>{if(!ne){ne=!0;let de=typeof BigInt64Array<"u"&&BigInt64Array.from,be=typeof BigUint64Array<"u"&&BigUint64Array.from,Ne=globalThis.Float16Array,Ve=typeof Ne<"u"&&Ne.from;de&&(Z.set("int64",BigInt64Array),Q.set(BigInt64Array,"int64")),be&&(Z.set("uint64",BigUint64Array),Q.set(BigUint64Array,"uint64")),Ve?(Z.set("float16",Ne),Q.set(Ne,"float16")):Z.set("float16",Uint16Array)}}}),Ee,$e,De=c(()=>{Te(),Ee=de=>{let be=1;for(let Ne=0;Ne<de.length;Ne++){let Ve=de[Ne];if(typeof Ve!="number"||!Number.isSafeInteger(Ve))throw new TypeError(`dims[${Ne}] must be an integer, got: ${Ve}`);if(Ve<0)throw new RangeError(`dims[${Ne}] must be a non-negative integer, got: ${Ve}`);be*=Ve}return be},$e=(de,be)=>{switch(de.location){case"cpu":return new ae(de.type,de.data,be);case"cpu-pinned":return new ae({location:"cpu-pinned",data:de.data,type:de.type,dims:be});case"texture":return new ae({location:"texture",texture:de.texture,type:de.type,dims:be});case"gpu-buffer":return new ae({location:"gpu-buffer",gpuBuffer:de.gpuBuffer,type:de.type,dims:be});case"ml-tensor":return new ae({location:"ml-tensor",mlTensor:de.mlTensor,type:de.type,dims:be});default:throw new Error(`tensorReshape: tensor location ${de.location} is not supported`)}}}),ae,Te=c(()=>{P(),K(),Se(),De(),ae=class{constructor(de,be,Ne){ge();let Ve,Oe;if(typeof de=="object"&&"location"in de)switch(this.dataLocation=de.location,Ve=de.type,Oe=de.dims,de.location){case"cpu-pinned":{let qe=Z.get(Ve);if(!qe)throw new TypeError(`unsupported type "${Ve}" to create tensor from pinned buffer`);if(!(de.data instanceof qe))throw new TypeError(`buffer should be of type ${qe.name}`);this.cpuData=de.data;break}case"texture":{if(Ve!=="float32")throw new TypeError(`unsupported type "${Ve}" to create tensor from texture`);this.gpuTextureData=de.texture,this.downloader=de.download,this.disposer=de.dispose;break}case"gpu-buffer":{if(Ve!=="float32"&&Ve!=="float16"&&Ve!=="int32"&&Ve!=="int64"&&Ve!=="uint32"&&Ve!=="uint8"&&Ve!=="bool"&&Ve!=="uint4"&&Ve!=="int4")throw new TypeError(`unsupported type "${Ve}" to create tensor from gpu buffer`);this.gpuBufferData=de.gpuBuffer,this.downloader=de.download,this.disposer=de.dispose;break}case"ml-tensor":{if(Ve!=="float32"&&Ve!=="float16"&&Ve!=="int32"&&Ve!=="int64"&&Ve!=="uint32"&&Ve!=="uint64"&&Ve!=="int8"&&Ve!=="uint8"&&Ve!=="bool"&&Ve!=="uint4"&&Ve!=="int4")throw new TypeError(`unsupported type "${Ve}" to create tensor from MLTensor`);this.mlTensorData=de.mlTensor,this.downloader=de.download,this.disposer=de.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let qe,Ge;if(typeof de=="string")if(Ve=de,Ge=Ne,de==="string"){if(!Array.isArray(be))throw new TypeError("A string tensor's data must be a string array.");qe=be}else{let dt=Z.get(de);if(dt===void 0)throw new TypeError(`Unsupported tensor type: ${de}.`);if(Array.isArray(be)){if(de==="float16"&&dt===Uint16Array||de==="uint4"||de==="int4")throw new TypeError(`Creating a ${de} tensor from number array is not supported. Please use ${dt.name} as data.`);de==="uint64"||de==="int64"?qe=dt.from(be,BigInt):qe=dt.from(be)}else if(be instanceof dt)qe=be;else if(be instanceof Uint8ClampedArray)if(de==="uint8")qe=Uint8Array.from(be);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(de==="float16"&&be instanceof Uint16Array&&dt!==Uint16Array)qe=new globalThis.Float16Array(be.buffer,be.byteOffset,be.length);else throw new TypeError(`A ${Ve} tensor's data must be type of ${dt}`)}else if(Ge=be,Array.isArray(de)){if(de.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let dt=typeof de[0];if(dt==="string")Ve="string",qe=de;else if(dt==="boolean")Ve="bool",qe=Uint8Array.from(de);else throw new TypeError(`Invalid element type of data array: ${dt}.`)}else if(de instanceof Uint8ClampedArray)Ve="uint8",qe=Uint8Array.from(de);else{let dt=Q.get(de.constructor);if(dt===void 0)throw new TypeError(`Unsupported type for tensor data: ${de.constructor}.`);Ve=dt,qe=de}if(Ge===void 0)Ge=[qe.length];else if(!Array.isArray(Ge))throw new TypeError("A tensor's dims must be a number array");Oe=Ge,this.cpuData=qe,this.dataLocation="cpu"}let rt=Ee(Oe);if(this.cpuData&&rt!==this.cpuData.length&&!((Ve==="uint4"||Ve==="int4")&&Math.ceil(rt/2)===this.cpuData.length))throw new Error(`Tensor's size(${rt}) does not match data length(${this.cpuData.length}).`);this.type=Ve,this.dims=Oe,this.size=rt}static async fromImage(de,be){return W(de,be)}static fromTexture(de,be){return q(de,be)}static fromGpuBuffer(de,be){return G(de,be)}static fromMLTensor(de,be){return re(de,be)}static fromPinnedBuffer(de,be,Ne){return ie(de,be,Ne)}toDataURL(de){return O(this,de)}toImageData(de){return $(this,de)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(de){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let be=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=be,de&&this.disposer&&(this.disposer(),this.disposer=void 0),be}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(de){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return $e(this,de)}}}),Ie,st=c(()=>{Te(),Ie=ae}),He,lt,Je,Ct,Ft,Ot,En=c(()=>{T(),He=(de,be)=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||console.timeStamp(`${de}::ORT::${be}`)},lt=(de,be)=>{var Oe;let Ne=((Oe=new Error().stack)==null?void 0:Oe.split(/\r\n|\r|\n/g))||[],Ve=!1;for(let rt=0;rt<Ne.length;rt++){if(Ve&&!Ne[rt].includes("TRACE_FUNC")){let qe=`FUNC_${de}::${Ne[rt].trim().split(" ")[1]}`;be&&(qe+=`::${be}`),He("CPU",qe);return}Ne[rt].includes("TRACE_FUNC")&&(Ve=!0)}},Je=de=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||lt("BEGIN",de)},Ct=de=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||lt("END",de)},Ft=de=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||console.time(`ORT::${de}`)},Ot=de=>{(typeof D.trace>"u"?!D.wasm.trace:!D.trace)||console.timeEnd(`ORT::${de}`)}}),Ji,cn=c(()=>{b(),st(),En(),Ji=class v6e{constructor(be){this.handler=be}async run(be,Ne,Ve){Je(),Ft("InferenceSession.run");let Oe={},rt={};if(typeof be!="object"||be===null||be instanceof Ie||Array.isArray(be))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let qe=!0;if(typeof Ne=="object"){if(Ne===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(Ne instanceof Ie)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(Ne)){if(Ne.length===0)throw new TypeError("'fetches' cannot be an empty array.");qe=!1;for(let Tt of Ne){if(typeof Tt!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(Tt)===-1)throw new RangeError(`'fetches' contains invalid output name: ${Tt}.`);Oe[Tt]=null}if(typeof Ve=="object"&&Ve!==null)rt=Ve;else if(typeof Ve<"u")throw new TypeError("'options' must be an object.")}else{let Tt=!1,$t=Object.getOwnPropertyNames(Ne);for(let Nt of this.outputNames)if($t.indexOf(Nt)!==-1){let wt=Ne[Nt];(wt===null||wt instanceof Ie)&&(Tt=!0,qe=!1,Oe[Nt]=wt)}if(Tt){if(typeof Ve=="object"&&Ve!==null)rt=Ve;else if(typeof Ve<"u")throw new TypeError("'options' must be an object.")}else rt=Ne}}else if(typeof Ne<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let Tt of this.inputNames)if(typeof be[Tt]>"u")throw new Error(`input '${Tt}' is missing in 'feeds'.`);if(qe)for(let Tt of this.outputNames)Oe[Tt]=null;let Ge=await this.handler.run(be,Oe,rt),dt={};for(let Tt in Ge)if(Object.hasOwnProperty.call(Ge,Tt)){let $t=Ge[Tt];$t instanceof Ie?dt[Tt]=$t:dt[Tt]=new Ie($t.type,$t.data,$t.dims)}return Ot("InferenceSession.run"),Ct(),dt}async release(){return this.handler.dispose()}static async create(be,Ne,Ve,Oe){Je(),Ft("InferenceSession.create");let rt,qe={};if(typeof be=="string"){if(rt=be,typeof Ne=="object"&&Ne!==null)qe=Ne;else if(typeof Ne<"u")throw new TypeError("'options' must be an object.")}else if(be instanceof Uint8Array){if(rt=be,typeof Ne=="object"&&Ne!==null)qe=Ne;else if(typeof Ne<"u")throw new TypeError("'options' must be an object.")}else if(be instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&be instanceof SharedArrayBuffer){let $t=be,Nt=0,wt=be.byteLength;if(typeof Ne=="object"&&Ne!==null)qe=Ne;else if(typeof Ne=="number"){if(Nt=Ne,!Number.isSafeInteger(Nt))throw new RangeError("'byteOffset' must be an integer.");if(Nt<0||Nt>=$t.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${$t.byteLength}).`);if(wt=be.byteLength-Nt,typeof Ve=="number"){if(wt=Ve,!Number.isSafeInteger(wt))throw new RangeError("'byteLength' must be an integer.");if(wt<=0||Nt+wt>$t.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${$t.byteLength-Nt}].`);if(typeof Oe=="object"&&Oe!==null)qe=Oe;else if(typeof Oe<"u")throw new TypeError("'options' must be an object.")}else if(typeof Ve<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof Ne<"u")throw new TypeError("'options' must be an object.");rt=new Uint8Array($t,Nt,wt)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Ge,dt]=await m(qe),Tt=await Ge.createInferenceSessionHandler(rt,dt);return Ot("InferenceSession.create"),Ct(),new v6e(Tt)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),Tn,Ts=c(()=>{cn(),Tn=Ji}),ds=c(()=>{}),rr=c(()=>{}),Is=c(()=>{}),vo=c(()=>{}),Ko={};d(Ko,{InferenceSession:()=>Tn,TRACE:()=>He,TRACE_EVENT_BEGIN:()=>Ft,TRACE_EVENT_END:()=>Ot,TRACE_FUNC_BEGIN:()=>Je,TRACE_FUNC_END:()=>Ct,Tensor:()=>Ie,env:()=>N,registerBackend:()=>p});var es=c(()=>{y(),A(),Ts(),st(),ds(),rr(),En(),Is(),vo()}),ii=c(()=>{}),bi={};d(bi,{default:()=>ys});var Fi,Ni,ys,Gr=c(()=>{var de;sv(),Da(),Kr(),Fi="ort-wasm-proxy-worker",Ni=((de=globalThis.self)==null?void 0:de.name)===Fi,Ni&&(self.onmessage=be=>{let{type:Ne,in:Ve}=be.data;try{switch(Ne){case"init-wasm":Kl(Ve.wasm).then(()=>{Ja(Ve).then(()=>{postMessage({type:Ne})},Oe=>{postMessage({type:Ne,err:Oe})})},Oe=>{postMessage({type:Ne,err:Oe})});break;case"init-ep":{let{epName:Oe,env:rt}=Ve;Fd(rt,Oe).then(()=>{postMessage({type:Ne})},qe=>{postMessage({type:Ne,err:qe})});break}case"copy-from":{let{buffer:Oe}=Ve,rt=ts(Oe);postMessage({type:Ne,out:rt});break}case"create":{let{model:Oe,options:rt}=Ve;jd(Oe,rt).then(qe=>{postMessage({type:Ne,out:qe})},qe=>{postMessage({type:Ne,err:qe})});break}case"release":lm(Ve),postMessage({type:Ne});break;case"run":{let{sessionId:Oe,inputIndices:rt,inputs:qe,outputIndices:Ge,options:dt}=Ve;St(Oe,rt,qe,Ge,new Array(Ge.length).fill(null),dt).then(Tt=>{Tt.some($t=>$t[3]!=="cpu")?postMessage({type:Ne,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:Ne,out:Tt},Vy([...qe,...Tt]))},Tt=>{postMessage({type:Ne,err:Tt})});break}case"end-profiling":Ru(Ve),postMessage({type:Ne});break;default:}}catch(Oe){postMessage({type:Ne,err:Oe})}}),ys=Ni?null:be=>new Worker(be??fs,{type:"classic",name:Fi})}),xl,La,fs,Ea,bo,ft,Dt,xi,An,Ns,Hn,Ks,Cl,Kr=c(()=>{ii(),xl=typeof location>"u"?void 0:location.origin,La=()=>{var de,be;return typeof document<"u"?(de=document.currentScript)==null?void 0:de.src:typeof self<"u"?(be=self.location)==null?void 0:be.href:void 0},fs=La(),Ea=()=>{if(fs&&!fs.startsWith("blob:"))return fs.substring(0,fs.lastIndexOf("/")+1)},bo=(de,be)=>{try{let Ne=be??fs;return(Ne?new URL(de,Ne):new URL(de)).origin===xl}catch{return!1}},ft=(de,be)=>{let Ne=be??fs;try{return(Ne?new URL(de,Ne):new URL(de)).href}catch{return}},Dt=(de,be)=>`${be??"./"}${de}`,xi=async de=>{let be=await(await fetch(de,{credentials:"same-origin"})).blob();return URL.createObjectURL(be)},An=async de=>(await import(de)).default,Ns=(Gr(),h(bi)).default,Hn=async()=>{if(!fs)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(bo(fs))return[void 0,Ns()];let de=await xi(fs);return[de,Ns(de)]},Ks=void 0,Cl=async(de,be,Ne,Ve)=>{let Oe=Ks&&!(de||be);if(Oe)if(fs)Oe=bo(fs)||Ve&&!Ne;else if(Ve&&!Ne)Oe=!0;else throw new Error("cannot determine the script source URL.");if(Oe)return[void 0,Ks];{let rt="ort-wasm-simd-threaded.mjs",qe=de??ft(rt,be),Ge=Ne&&qe&&!bo(qe,be),dt=Ge?await xi(qe):qe??Dt(rt,be);return[Ge?dt:void 0,await An(dt)]}}}),Ya,Xa,gs,la,Za,ca,Ec,Kl,Gi,Da=c(()=>{Kr(),Xa=!1,gs=!1,la=!1,Za=()=>{if(typeof SharedArrayBuffer>"u")return!1;try{return typeof MessageChannel<"u"&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},ca=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},Ec=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},Kl=async de=>{if(Xa)return Promise.resolve();if(gs)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(la)throw new Error("previous call to 'initializeWebAssembly()' failed.");gs=!0;let be=de.initTimeout,Ne=de.numThreads;if(de.simd!==!1){if(de.simd==="relaxed"){if(!Ec())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!ca())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Ve=Za();Ne>1&&!Ve&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+Ne+", but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info."),console.warn("WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading."),de.numThreads=Ne=1);let Oe=de.wasmPaths,rt=typeof Oe=="string"?Oe:void 0,qe=Oe==null?void 0:Oe.mjs,Ge=(qe==null?void 0:qe.href)??qe,dt=Oe==null?void 0:Oe.wasm,Tt=(dt==null?void 0:dt.href)??dt,$t=de.wasmBinary,[Nt,wt]=await Cl(Ge,rt,Ne>1,!!$t||!!Tt),Pi=!1,it=[];if(be>0&&it.push(new Promise(Qt=>{setTimeout(()=>{Pi=!0,Qt()},be)})),it.push(new Promise((Qt,hr)=>{let xn={numThreads:Ne};if($t)xn.wasmBinary=$t,xn.locateFile=Cn=>Cn;else if(Tt||rt)xn.locateFile=Cn=>Tt??rt+Cn;else if(Ge&&Ge.indexOf("blob:")!==0)xn.locateFile=Cn=>new URL(Cn,Ge).href;else if(Nt){let Cn=Ea();Cn&&(xn.locateFile=fr=>Cn+fr)}wt(xn).then(Cn=>{gs=!1,Xa=!0,Ya=Cn,Qt(),Nt&&URL.revokeObjectURL(Nt)},Cn=>{gs=!1,la=!0,hr(Cn)})})),await Promise.race(it),Pi)throw new Error(`WebAssembly backend initializing failed due to timeout: ${be}ms`)},Gi=()=>{if(Xa&&Ya)return Ya;throw new Error("WebAssembly is not initialized yet.")}}),Vn,da,Ii,ld=c(()=>{Da(),Vn=(de,be)=>{let Ne=Gi(),Ve=Ne.lengthBytesUTF8(de)+1,Oe=Ne._malloc(Ve);return Ne.stringToUTF8(de,Oe,Ve),be.push(Oe),Oe},da=(de,be,Ne,Ve)=>{if(typeof de=="object"&&de!==null){if(Ne.has(de))throw new Error("Circular reference in options");Ne.add(de)}Object.entries(de).forEach(([Oe,rt])=>{let qe=be?be+Oe:Oe;if(typeof rt=="object")da(rt,qe+".",Ne,Ve);else if(typeof rt=="string"||typeof rt=="number")Ve(qe,rt.toString());else if(typeof rt=="boolean")Ve(qe,rt?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof rt}`)})},Ii=de=>{let be=Gi(),Ne=be.stackSave();try{let Ve=be.PTR_SIZE,Oe=be.stackAlloc(2*Ve);be._OrtGetLastError(Oe,Oe+Ve);let rt=Number(be.getValue(Oe,Ve===4?"i32":"i64")),qe=be.getValue(Oe+Ve,"*"),Ge=qe?be.UTF8ToString(qe):"";throw new Error(`${de} ERROR_CODE: ${rt}, ERROR_MESSAGE: ${Ge}`)}finally{be.stackRestore(Ne)}}}),Od,Nf=c(()=>{Da(),ld(),Od=de=>{let be=Gi(),Ne=0,Ve=[],Oe=de||{};try{if((de==null?void 0:de.logSeverityLevel)===void 0)Oe.logSeverityLevel=2;else if(typeof de.logSeverityLevel!="number"||!Number.isInteger(de.logSeverityLevel)||de.logSeverityLevel<0||de.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${de.logSeverityLevel}`);if((de==null?void 0:de.logVerbosityLevel)===void 0)Oe.logVerbosityLevel=0;else if(typeof de.logVerbosityLevel!="number"||!Number.isInteger(de.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${de.logVerbosityLevel}`);(de==null?void 0:de.terminate)===void 0&&(Oe.terminate=!1);let rt=0;return(de==null?void 0:de.tag)!==void 0&&(rt=Vn(de.tag,Ve)),Ne=be._OrtCreateRunOptions(Oe.logSeverityLevel,Oe.logVerbosityLevel,!!Oe.terminate,rt),Ne===0&&Ii("Can't create run options."),(de==null?void 0:de.extra)!==void 0&&da(de.extra,"",new WeakSet,(qe,Ge)=>{let dt=Vn(qe,Ve),Tt=Vn(Ge,Ve);be._OrtAddRunConfigEntry(Ne,dt,Tt)!==0&&Ii(`Can't set a run config entry: ${qe} - ${Ge}.`)}),[Ne,Ve]}catch(rt){throw Ne!==0&&be._OrtReleaseRunOptions(Ne),Ve.forEach(qe=>be._free(qe)),rt}}}),Mi,Ke,zt,vi,$s,yo,Fn=c(()=>{Da(),ld(),Mi=de=>{switch(de){case"disabled":return 0;case"basic":return 1;case"extended":return 2;case"layout":return 3;case"all":return 99;default:throw new Error(`unsupported graph optimization level: ${de}`)}},Ke=de=>{switch(de){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${de}`)}},zt=de=>{de.extra||(de.extra={}),de.extra.session||(de.extra.session={});let be=de.extra.session;be.use_ort_model_bytes_directly||(be.use_ort_model_bytes_directly="1"),de.executionProviders&&de.executionProviders.some(Ne=>(typeof Ne=="string"?Ne:Ne.name)==="webgpu")&&(de.enableMemPattern=!1)},vi=(de,be,Ne,Ve)=>{let Oe=Vn(be,Ve),rt=Vn(Ne,Ve);Gi()._OrtAddSessionConfigEntry(de,Oe,rt)!==0&&Ii(`Can't set a session config entry: ${be} - ${Ne}.`)},$s=async(de,be,Ne)=>{let Ve=be.executionProviders;for(let Oe of Ve){let rt=typeof Oe=="string"?Oe:Oe.name,qe=[];switch(rt){case"webnn":if(rt="WEBNN",vi(de,"session.disable_quant_qdq","1",Ne),vi(de,"session.disable_qdq_constant_folding","1",Ne),typeof Oe!="string"){let Nt=Oe==null?void 0:Oe.deviceType;Nt&&vi(de,"deviceType",Nt,Ne)}break;case"webgpu":if(rt="JS",typeof Oe!="string"){let Nt=Oe;if(Nt!=null&&Nt.preferredLayout){if(Nt.preferredLayout!=="NCHW"&&Nt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${Nt.preferredLayout}`);vi(de,"preferredLayout",Nt.preferredLayout,Ne)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${rt}`)}let Ge=Vn(rt,Ne),dt=qe.length,Tt=0,$t=0;if(dt>0){Tt=Gi()._malloc(dt*Gi().PTR_SIZE),Ne.push(Tt),$t=Gi()._malloc(dt*Gi().PTR_SIZE),Ne.push($t);for(let Nt=0;Nt<dt;Nt++)Gi().setValue(Tt+Nt*Gi().PTR_SIZE,qe[Nt][0],"*"),Gi().setValue($t+Nt*Gi().PTR_SIZE,qe[Nt][1],"*")}await Gi()._OrtAppendExecutionProvider(de,Ge,Tt,$t,dt)!==0&&Ii(`Can't append execution provider: ${rt}.`)}},yo=async de=>{let be=Gi(),Ne=0,Ve=[],Oe=de||{};zt(Oe);try{let rt=Mi(Oe.graphOptimizationLevel??"all"),qe=Ke(Oe.executionMode??"sequential"),Ge=typeof Oe.logId=="string"?Vn(Oe.logId,Ve):0,dt=Oe.logSeverityLevel??2;if(!Number.isInteger(dt)||dt<0||dt>4)throw new Error(`log severity level is not valid: ${dt}`);let Tt=Oe.logVerbosityLevel??0;if(!Number.isInteger(Tt)||Tt<0||Tt>4)throw new Error(`log verbosity level is not valid: ${Tt}`);let $t=typeof Oe.optimizedModelFilePath=="string"?Vn(Oe.optimizedModelFilePath,Ve):0;if(Ne=be._OrtCreateSessionOptions(rt,!!Oe.enableCpuMemArena,!!Oe.enableMemPattern,qe,!!Oe.enableProfiling,0,Ge,dt,Tt,$t),Ne===0&&Ii("Can't create session options."),Oe.executionProviders&&await $s(Ne,Oe,Ve),Oe.enableGraphCapture!==void 0){if(typeof Oe.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Oe.enableGraphCapture}`);vi(Ne,"enableGraphCapture",Oe.enableGraphCapture.toString(),Ve)}if(Oe.freeDimensionOverrides)for(let[Nt,wt]of Object.entries(Oe.freeDimensionOverrides)){if(typeof Nt!="string")throw new Error(`free dimension override name must be a string: ${Nt}`);if(typeof wt!="number"||!Number.isInteger(wt)||wt<0)throw new Error(`free dimension override value must be a non-negative integer: ${wt}`);let Pi=Vn(Nt,Ve);be._OrtAddFreeDimensionOverride(Ne,Pi,wt)!==0&&Ii(`Can't set a free dimension override: ${Nt} - ${wt}.`)}return Oe.extra!==void 0&&da(Oe.extra,"",new WeakSet,(Nt,wt)=>{vi(Ne,Nt,wt,Ve)}),[Ne,Ve]}catch(rt){throw Ne!==0&&be._OrtReleaseSessionOptions(Ne)!==0&&Ii("Can't release session options."),Ve.forEach(qe=>be._free(qe)),rt}}}),Ys,or,vr,Ci,Re,It,ui,Bn,Jt=c(()=>{Ys=de=>{switch(de){case"int8":return 3;case"uint8":return 2;case"bool":return 9;case"int16":return 5;case"uint16":return 4;case"int32":return 6;case"uint32":return 12;case"float16":return 10;case"float32":return 1;case"float64":return 11;case"string":return 8;case"int64":return 7;case"uint64":return 13;case"int4":return 22;case"uint4":return 21;default:throw new Error(`unsupported data type: ${de}`)}},or=de=>{switch(de){case 3:return"int8";case 2:return"uint8";case 9:return"bool";case 5:return"int16";case 4:return"uint16";case 6:return"int32";case 12:return"uint32";case 10:return"float16";case 1:return"float32";case 11:return"float64";case 8:return"string";case 7:return"int64";case 13:return"uint64";case 22:return"int4";case 21:return"uint4";default:throw new Error(`unsupported data type: ${de}`)}},vr=(de,be)=>{let Ne=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][de],Ve=typeof be=="number"?be:be.reduce((Oe,rt)=>Oe*rt,1);return Ne>0?Math.ceil(Ve*Ne):void 0},Ci=de=>{switch(de){case"float16":return typeof Float16Array<"u"&&Float16Array.from?Float16Array:Uint16Array;case"float32":return Float32Array;case"uint8":return Uint8Array;case"int8":return Int8Array;case"uint16":return Uint16Array;case"int16":return Int16Array;case"int32":return Int32Array;case"bool":return Uint8Array;case"float64":return Float64Array;case"uint32":return Uint32Array;case"int64":return BigInt64Array;case"uint64":return BigUint64Array;default:throw new Error(`unsupported type: ${de}`)}},Re=de=>{switch(de){case"verbose":return 0;case"info":return 1;case"warning":return 2;case"error":return 3;case"fatal":return 4;default:throw new Error(`unsupported logging level: ${de}`)}},It=de=>de==="float32"||de==="float16"||de==="int32"||de==="int64"||de==="uint32"||de==="uint8"||de==="bool"||de==="uint4"||de==="int4",ui=de=>de==="float32"||de==="float16"||de==="int32"||de==="int64"||de==="uint32"||de==="uint64"||de==="int8"||de==="uint8"||de==="bool"||de==="uint4"||de==="int4",Bn=de=>{switch(de){case"none":return 0;case"cpu":return 1;case"cpu-pinned":return 2;case"texture":return 3;case"gpu-buffer":return 4;case"ml-tensor":return 5;default:throw new Error(`unsupported data location: ${de}`)}}}),zn,ao=c(()=>{ii(),zn=async de=>{if(typeof de=="string"){let be=await fetch(de);if(!be.ok)throw new Error(`failed to load external data file: ${de}`);let Ne=be.headers.get("Content-Length"),Ve=Ne?parseInt(Ne,10):0;if(Ve<1073741824)return new Uint8Array(await be.arrayBuffer());{if(!be.body)throw new Error(`failed to load external data file: ${de}, no response body.`);let Oe=be.body.getReader(),rt;try{rt=new ArrayBuffer(Ve)}catch(Ge){if(Ge instanceof RangeError){let dt=Math.ceil(Ve/65536);rt=new WebAssembly.Memory({initial:dt,maximum:dt}).buffer}else throw Ge}let qe=0;for(;;){let{done:Ge,value:dt}=await Oe.read();if(Ge)break;let Tt=dt.byteLength;new Uint8Array(rt,qe,Tt).set(dt),qe+=Tt}return new Uint8Array(rt,0,Ve)}}else return de instanceof Blob?new Uint8Array(await de.arrayBuffer()):de instanceof Uint8Array?de:new Uint8Array(de)}}),Qa,Ja,Fd,Xs,Bd,Nu,ts,jd,lm,Dh,St,Ru,Vy,sv=c(()=>{es(),Nf(),Fn(),Jt(),Da(),ld(),ao(),Qa=(de,be)=>{Gi()._OrtInit(de,be)!==0&&Ii("Can't initialize onnxruntime.")},Ja=async de=>{Qa(de.wasm.numThreads,Re(de.logLevel))},Fd=async(de,be)=>{var Ve,Oe;(Oe=(Ve=Gi()).asyncInit)==null||Oe.call(Ve);let Ne=de.webgpu.adapter;if(be==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(Ne){if(typeof Ne.limits!="object"||typeof Ne.features!="object"||typeof Ne.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let rt=de.webgpu.powerPreference;if(rt!==void 0&&rt!=="low-power"&&rt!=="high-performance")throw new Error(`Invalid powerPreference setting: "${rt}"`);let qe=de.webgpu.forceFallbackAdapter;if(qe!==void 0&&typeof qe!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${qe}"`);if(Ne=await navigator.gpu.requestAdapter({powerPreference:rt,forceFallbackAdapter:qe}),!Ne)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(be==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Xs=new Map,Bd=de=>{let be=Gi(),Ne=be.stackSave();try{let Ve=be.PTR_SIZE,Oe=be.stackAlloc(2*Ve);be._OrtGetInputOutputCount(de,Oe,Oe+Ve)!==0&&Ii("Can't get session input/output count.");let rt=Ve===4?"i32":"i64";return[Number(be.getValue(Oe,rt)),Number(be.getValue(Oe+Ve,rt))]}finally{be.stackRestore(Ne)}},Nu=(de,be)=>{let Ne=Gi(),Ve=Ne.stackSave(),Oe=0;try{let rt=Ne.PTR_SIZE,qe=Ne.stackAlloc(2*rt);Ne._OrtGetInputOutputMetadata(de,be,qe,qe+rt)!==0&&Ii("Can't get session input/output metadata.");let Ge=Number(Ne.getValue(qe,"*"));Oe=Number(Ne.getValue(qe+rt,"*"));let dt=Ne.HEAP32[Oe/4];if(dt===0)return[Ge,0];let Tt=Ne.HEAPU32[Oe/4+1],$t=[];for(let Nt=0;Nt<Tt;Nt++){let wt=Number(Ne.getValue(Oe+8+Nt*rt,"*"));$t.push(wt!==0?Ne.UTF8ToString(wt):Number(Ne.getValue(Oe+8+(Nt+Tt)*rt,"*")))}return[Ge,dt,$t]}finally{Ne.stackRestore(Ve),Oe!==0&&Ne._OrtFree(Oe)}},ts=de=>{let be=Gi(),Ne=be._malloc(de.byteLength);if(Ne===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${de.byteLength}.`);return be.HEAPU8.set(de,Ne),[Ne,de.byteLength]},jd=async(de,be)=>{var $t,Nt,wt;let Ne,Ve,Oe=Gi();Array.isArray(de)?[Ne,Ve]=de:de.buffer===Oe.HEAPU8.buffer?[Ne,Ve]=[de.byteOffset,de.byteLength]:[Ne,Ve]=ts(de);let rt=0,qe=0,Ge=[],dt=[],Tt=[];try{if([qe,Ge]=await yo(be),(be==null?void 0:be.externalData)&&Oe.mountExternalData){let Fr=[];for(let ps of be.externalData){let Ta=typeof ps=="string"?ps:ps.path;Fr.push(zn(typeof ps=="string"?ps:ps.data).then(kl=>{Oe.mountExternalData(Ta,kl)}))}await Promise.all(Fr)}for(let Fr of(be==null?void 0:be.executionProviders)??[])if((typeof Fr=="string"?Fr:Fr.name)==="webnn"){if(Oe.shouldTransferToMLTensor=!1,typeof Fr!="string"){let ps=Fr,Ta=ps==null?void 0:ps.context,kl=ps==null?void 0:ps.gpuDevice,Yl=ps==null?void 0:ps.deviceType,ov=ps==null?void 0:ps.powerPreference;Ta?Oe.currentContext=Ta:kl?Oe.currentContext=await Oe.webnnCreateMLContext(kl):Oe.currentContext=await Oe.webnnCreateMLContext({deviceType:Yl,powerPreference:ov})}else Oe.currentContext=await Oe.webnnCreateMLContext();break}rt=await Oe._OrtCreateSession(Ne,Ve,qe),($t=Oe.webgpuOnCreateSession)==null||$t.call(Oe,rt),rt===0&&Ii("Can't create a session."),(Nt=Oe.jsepOnCreateSession)==null||Nt.call(Oe),Oe.currentContext&&(Oe.webnnRegisterMLContext(rt,Oe.currentContext),Oe.currentContext=void 0,Oe.shouldTransferToMLTensor=!0);let[Pi,it]=Bd(rt),Qt=!!(be!=null&&be.enableGraphCapture),hr=[],xn=[],Cn=[],fr=[],Yi=[];for(let Fr=0;Fr<Pi;Fr++){let[ps,Ta,kl]=Nu(rt,Fr);ps===0&&Ii("Can't get an input name."),dt.push(ps);let Yl=Oe.UTF8ToString(ps);hr.push(Yl),Cn.push(Ta===0?{name:Yl,isTensor:!1}:{name:Yl,isTensor:!0,type:or(Ta),shape:kl})}for(let Fr=0;Fr<it;Fr++){let[ps,Ta,kl]=Nu(rt,Fr+Pi);ps===0&&Ii("Can't get an output name."),Tt.push(ps);let Yl=Oe.UTF8ToString(ps);xn.push(Yl),fr.push(Ta===0?{name:Yl,isTensor:!1}:{name:Yl,isTensor:!0,type:or(Ta),shape:kl})}return Xs.set(rt,[rt,dt,Tt,null,Qt,!1]),[rt,hr,xn,Cn,fr]}catch(Pi){throw dt.forEach(it=>Oe._OrtFree(it)),Tt.forEach(it=>Oe._OrtFree(it)),rt!==0&&Oe._OrtReleaseSession(rt)!==0&&Ii("Can't release session."),Pi}finally{Oe._free(Ne),qe!==0&&Oe._OrtReleaseSessionOptions(qe)!==0&&Ii("Can't release session options."),Ge.forEach(Pi=>Oe._free(Pi)),(wt=Oe.unmountExternalData)==null||wt.call(Oe)}},lm=de=>{var dt,Tt,$t;let be=Gi(),Ne=Xs.get(de);if(!Ne)throw new Error(`cannot release session. invalid session id: ${de}`);let[Ve,Oe,rt,qe,Ge]=Ne;qe&&(Ge&&be._OrtClearBoundOutputs(qe.handle)!==0&&Ii("Can't clear bound outputs."),be._OrtReleaseBinding(qe.handle)!==0&&Ii("Can't release IO binding.")),(dt=be.jsepOnReleaseSession)==null||dt.call(be,de),(Tt=be.webnnOnReleaseSession)==null||Tt.call(be,de),($t=be.webgpuOnReleaseSession)==null||$t.call(be,de),Oe.forEach(Nt=>be._OrtFree(Nt)),rt.forEach(Nt=>be._OrtFree(Nt)),be._OrtReleaseSession(Ve)!==0&&Ii("Can't release session."),Xs.delete(de)},Dh=async(de,be,Ne,Ve,Oe,rt,qe=!1)=>{if(!de){be.push(0);return}let Ge=Gi(),dt=Ge.PTR_SIZE,Tt=de[0],$t=de[1],Nt=de[3],wt=Nt,Pi,it;if(Tt==="string"&&(Nt==="gpu-buffer"||Nt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(qe&&Nt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${rt} when enableGraphCapture is true.`);if(Nt==="gpu-buffer"){let xn=de[2].gpuBuffer;it=vr(Ys(Tt),$t);{let Cn=Ge.jsepRegisterBuffer;if(!Cn)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');Pi=Cn(Ve,rt,xn,it)}}else if(Nt==="ml-tensor"){let xn=de[2].mlTensor;it=vr(Ys(Tt),$t);let Cn=Ge.webnnRegisterMLTensor;if(!Cn)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');Pi=Cn(Ve,xn,Ys(Tt),$t)}else{let xn=de[2];if(Array.isArray(xn)){it=dt*xn.length,Pi=Ge._malloc(it),Ne.push(Pi);for(let Cn=0;Cn<xn.length;Cn++){if(typeof xn[Cn]!="string")throw new TypeError(`tensor data at index ${Cn} is not a string`);Ge.setValue(Pi+Cn*dt,Vn(xn[Cn],Ne),"*")}}else{let Cn=Ge.webnnIsGraphInput,fr=Ge.webnnIsGraphOutput;if(Tt!=="string"&&Cn&&fr){let Yi=Ge.UTF8ToString(Oe);if(Cn(Ve,Yi)||fr(Ve,Yi)){let Fr=Ys(Tt);it=vr(Fr,$t),wt="ml-tensor";let ps=Ge.webnnCreateTemporaryTensor,Ta=Ge.webnnUploadTensor;if(!ps||!Ta)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let kl=await ps(Ve,Fr,$t);Ta(kl,new Uint8Array(xn.buffer,xn.byteOffset,xn.byteLength)),Pi=kl}else it=xn.byteLength,Pi=Ge._malloc(it),Ne.push(Pi),Ge.HEAPU8.set(new Uint8Array(xn.buffer,xn.byteOffset,it),Pi)}else it=xn.byteLength,Pi=Ge._malloc(it),Ne.push(Pi),Ge.HEAPU8.set(new Uint8Array(xn.buffer,xn.byteOffset,it),Pi)}}let Qt=Ge.stackSave(),hr=Ge.stackAlloc(4*$t.length);try{$t.forEach((Cn,fr)=>Ge.setValue(hr+fr*dt,Cn,dt===4?"i32":"i64"));let xn=Ge._OrtCreateTensor(Ys(Tt),Pi,it,hr,$t.length,Bn(wt));xn===0&&Ii(`Can't create tensor for input/output. session=${Ve}, index=${rt}.`),be.push(xn)}finally{Ge.stackRestore(Qt)}},St=async(de,be,Ne,Ve,Oe,rt)=>{var Xl,Ky,X1;let qe=Gi(),Ge=qe.PTR_SIZE,dt=Xs.get(de);if(!dt)throw new Error(`cannot run inference. invalid session id: ${de}`);let Tt=dt[0],$t=dt[1],Nt=dt[2],wt=dt[3],Pi=dt[4];dt[5];let it=be.length,Qt=Ve.length,hr=0,xn=[],Cn=[],fr=[],Yi=[],Fr=[],ps=qe.stackSave(),Ta=qe.stackAlloc(it*Ge),kl=qe.stackAlloc(it*Ge),Yl=qe.stackAlloc(Qt*Ge),ov=qe.stackAlloc(Qt*Ge);try{[hr,xn]=Od(rt),Ft("wasm prepareInputOutputTensor");for(let is=0;is<it;is++)await Dh(Ne[is],Cn,Yi,de,$t[be[is]],be[is],Pi);for(let is=0;is<Qt;is++)await Dh(Oe[is],fr,Yi,de,Nt[Ve[is]],it+Ve[is],Pi);Ot("wasm prepareInputOutputTensor");for(let is=0;is<it;is++)qe.setValue(Ta+is*Ge,Cn[is],"*"),qe.setValue(kl+is*Ge,$t[be[is]],"*");for(let is=0;is<Qt;is++)qe.setValue(Yl+is*Ge,fr[is],"*"),qe.setValue(ov+is*Ge,Nt[Ve[is]],"*");(Xl=qe.jsepOnRunStart)==null||Xl.call(qe,Tt),(Ky=qe.webnnOnRunStart)==null||Ky.call(qe,Tt);let Ia;Ia=await qe._OrtRun(Tt,kl,Ta,it,ov,Qt,Yl,hr),Ia!==0&&Ii("failed to call OrtRun().");let Mu=[],Z1=[];Ft("wasm ProcessOutputTensor");for(let is=0;is<Qt;is++){let Hd=Number(qe.getValue(Yl+is*Ge,"*"));if(Hd===fr[is]||Fr.includes(fr[is])){Mu.push(Oe[is]),Hd!==fr[is]&&qe._OrtReleaseTensor(Hd)!==0&&Ii("Can't release tensor.");continue}let hE=qe.stackSave(),Rh=qe.stackAlloc(4*Ge),dm=!1,Yo,Zl=0;try{qe._OrtGetTensorData(Hd,Rh,Rh+Ge,Rh+2*Ge,Rh+3*Ge)!==0&&Ii(`Can't access output tensor data on index ${is}.`);let Yy=Ge===4?"i32":"i64",Ql=Number(qe.getValue(Rh,Yy));Zl=qe.getValue(Rh+Ge,"*");let Q1=qe.getValue(Rh+Ge*2,"*"),fE=Number(qe.getValue(Rh+Ge*3,Yy)),Ah=[];for(let Xo=0;Xo<fE;Xo++)Ah.push(Number(qe.getValue(Q1+Xo*Ge,Yy)));qe._OrtFree(Q1)!==0&&Ii("Can't free memory for tensor dims.");let Vd=Ah.reduce((Xo,lo)=>Xo*lo,1);Yo=or(Ql);let Pu=wt==null?void 0:wt.outputPreferredLocations[Ve[is]];if(Yo==="string"){if(Pu==="gpu-buffer"||Pu==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let Xo=[];for(let lo=0;lo<Vd;lo++){let zd=qe.getValue(Zl+lo*Ge,"*"),J1=qe.getValue(Zl+(lo+1)*Ge,"*"),ex=lo===Vd-1?void 0:J1-zd;Xo.push(qe.UTF8ToString(zd,ex))}Mu.push([Yo,Ah,Xo,"cpu"])}else if(Pu==="gpu-buffer"&&Vd>0){let Xo=qe.jsepGetBuffer;if(!Xo)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let lo=Xo(Zl),zd=vr(Ql,Vd);if(zd===void 0||!It(Yo))throw new Error(`Unsupported data type: ${Yo}`);dm=!0,Mu.push([Yo,Ah,{gpuBuffer:lo,download:qe.jsepCreateDownloader(lo,zd,Yo),dispose:()=>{qe._OrtReleaseTensor(Hd)!==0&&Ii("Can't release tensor.")}},"gpu-buffer"])}else if(Pu==="ml-tensor"&&Vd>0){let Xo=qe.webnnEnsureTensor,lo=qe.webnnIsGraphInputOutputTypeSupported;if(!Xo||!lo)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(vr(Ql,Vd)===void 0||!ui(Yo))throw new Error(`Unsupported data type: ${Yo}`);if(!lo(de,Yo,!1))throw new Error(`preferredLocation "ml-tensor" for ${Yo} output is not supported by current WebNN Context.`);let zd=await Xo(de,Zl,Ql,Ah,!1);dm=!0,Mu.push([Yo,Ah,{mlTensor:zd,download:qe.webnnCreateMLTensorDownloader(Zl,Yo),dispose:()=>{qe.webnnReleaseTensorId(Zl),qe._OrtReleaseTensor(Hd)}},"ml-tensor"])}else if(Pu==="ml-tensor-cpu-output"&&Vd>0){let Xo=qe.webnnCreateMLTensorDownloader(Zl,Yo)(),lo=Mu.length;dm=!0,Z1.push((async()=>{let zd=[lo,await Xo];return qe.webnnReleaseTensorId(Zl),qe._OrtReleaseTensor(Hd),zd})()),Mu.push([Yo,Ah,[],"cpu"])}else{let Xo=Ci(Yo),lo=new Xo(Vd);new Uint8Array(lo.buffer,lo.byteOffset,lo.byteLength).set(qe.HEAPU8.subarray(Zl,Zl+lo.byteLength)),Mu.push([Yo,Ah,lo,"cpu"])}}finally{qe.stackRestore(hE),Yo==="string"&&Zl&&qe._free(Zl),dm||qe._OrtReleaseTensor(Hd)}}wt&&!Pi&&(qe._OrtClearBoundOutputs(wt.handle)!==0&&Ii("Can't clear bound outputs."),Xs.set(de,[Tt,$t,Nt,wt,Pi,!1]));for(let[is,Hd]of await Promise.all(Z1))Mu[is][2]=Hd;return Ot("wasm ProcessOutputTensor"),Mu}finally{(X1=qe.webnnOnRunEnd)==null||X1.call(qe,Tt),qe.stackRestore(ps),Cn.forEach(Ia=>qe._OrtReleaseTensor(Ia)),fr.forEach(Ia=>qe._OrtReleaseTensor(Ia)),Yi.forEach(Ia=>qe._free(Ia)),hr!==0&&qe._OrtReleaseRunOptions(hr),xn.forEach(Ia=>qe._free(Ia))}},Ru=de=>{let be=Gi(),Ne=Xs.get(de);if(!Ne)throw new Error("invalid session id");let Ve=Ne[0],Oe=be._OrtEndProfiling(Ve);Oe===0&&Ii("Can't get an profile file name."),be._OrtFree(Oe)},Vy=de=>{let be=[];for(let Ne of de){let Ve=Ne[2];!Array.isArray(Ve)&&"buffer"in Ve&&be.push(Ve.buffer)}return be}}),us,Ki,Th,Rf,Af,Fg,cm,Bg,cd,Sl,$d,Wd,Mf,jg,Au,uE,$g,Wg,G1=c(()=>{es(),sv(),Da(),Kr(),us=()=>!!N.wasm.proxy&&typeof document<"u",Th=!1,Rf=!1,Af=!1,Bg=new Map,cd=(de,be)=>{let Ne=Bg.get(de);Ne?Ne.push(be):Bg.set(de,[be])},Sl=()=>{if(Th||!Rf||Af||!Ki)throw new Error("worker not ready")},$d=de=>{switch(de.data.type){case"init-wasm":Th=!1,de.data.err?(Af=!0,cm[1](de.data.err)):(Rf=!0,cm[0]()),Fg&&(URL.revokeObjectURL(Fg),Fg=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let be=Bg.get(de.data.type);de.data.err?be.shift()[1](de.data.err):be.shift()[0](de.data.out);break}}},Wd=async()=>{if(!Rf){if(Th)throw new Error("multiple calls to 'initWasm()' detected.");if(Af)throw new Error("previous call to 'initWasm()' failed.");if(Th=!0,us())return new Promise((de,be)=>{Ki==null||Ki.terminate(),Hn().then(([Ne,Ve])=>{try{Ki=Ve,Ki.onerror=rt=>be(rt),Ki.onmessage=$d,cm=[de,be];let Oe={type:"init-wasm",in:N};if(!Oe.in.wasm.wasmPaths&&Ne){let rt=Ea();rt&&(Oe.in.wasm.wasmPaths=rt)}Ki.postMessage(Oe),Fg=Ne}catch(Oe){be(Oe)}},be)});try{await Kl(N.wasm),await Ja(N),Rf=!0}catch(de){throw Af=!0,de}finally{Th=!1}}},Mf=async de=>{if(us())return Sl(),new Promise((be,Ne)=>{cd("init-ep",[be,Ne]);let Ve={type:"init-ep",in:{epName:de,env:N}};Ki.postMessage(Ve)});await Fd(N,de)},jg=async de=>us()?(Sl(),new Promise((be,Ne)=>{cd("copy-from",[be,Ne]);let Ve={type:"copy-from",in:{buffer:de}};Ki.postMessage(Ve,[de.buffer])})):ts(de),Au=async(de,be)=>{if(us()){if(be!=null&&be.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Sl(),new Promise((Ne,Ve)=>{cd("create",[Ne,Ve]);let Oe={type:"create",in:{model:de,options:{...be}}},rt=[];de instanceof Uint8Array&&rt.push(de.buffer),Ki.postMessage(Oe,rt)})}else return jd(de,be)},uE=async de=>{if(us())return Sl(),new Promise((be,Ne)=>{cd("release",[be,Ne]);let Ve={type:"release",in:de};Ki.postMessage(Ve)});lm(de)},$g=async(de,be,Ne,Ve,Oe,rt)=>{if(us()){if(Ne.some(qe=>qe[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Oe.some(qe=>qe))throw new Error("pre-allocated output tensor is not supported for proxy.");return Sl(),new Promise((qe,Ge)=>{cd("run",[qe,Ge]);let dt=Ne,Tt={type:"run",in:{sessionId:de,inputIndices:be,inputs:dt,outputIndices:Ve,options:rt}};Ki.postMessage(Tt,Vy(dt))})}else return St(de,be,Ne,Ve,Oe,rt)},Wg=async de=>{if(us())return Sl(),new Promise((be,Ne)=>{cd("end-profiling",[be,Ne]);let Ve={type:"end-profiling",in:de};Ki.postMessage(Ve)});Ru(de)}}),zy,Hg,rv,Uy=c(()=>{es(),G1(),Jt(),ii(),ao(),zy=(de,be)=>{switch(de.location){case"cpu":return[de.type,de.dims,de.data,"cpu"];case"gpu-buffer":return[de.type,de.dims,{gpuBuffer:de.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[de.type,de.dims,{mlTensor:de.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${de.location} for ${be()}`)}},Hg=de=>{switch(de[3]){case"cpu":return new Ie(de[0],de[2],de[1]);case"gpu-buffer":{let be=de[0];if(!It(be))throw new Error(`not supported data type: ${be} for deserializing GPU tensor`);let{gpuBuffer:Ne,download:Ve,dispose:Oe}=de[2];return Ie.fromGpuBuffer(Ne,{dataType:be,dims:de[1],download:Ve,dispose:Oe})}case"ml-tensor":{let be=de[0];if(!ui(be))throw new Error(`not supported data type: ${be} for deserializing MLTensor tensor`);let{mlTensor:Ne,download:Ve,dispose:Oe}=de[2];return Ie.fromMLTensor(Ne,{dataType:be,dims:de[1],download:Ve,dispose:Oe})}default:throw new Error(`invalid data location: ${de[3]}`)}},rv=class{async fetchModelAndCopyToWasmMemory(de){return jg(await zn(de))}async loadModel(de,be){Je();let Ne;typeof de=="string"?Ne=await this.fetchModelAndCopyToWasmMemory(de):Ne=de,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Au(Ne,be),Ct()}async dispose(){return uE(this.sessionId)}async run(de,be,Ne){Je();let Ve=[],Oe=[];Object.entries(de).forEach(Nt=>{let wt=Nt[0],Pi=Nt[1],it=this.inputNames.indexOf(wt);if(it===-1)throw new Error(`invalid input '${wt}'`);Ve.push(Pi),Oe.push(it)});let rt=[],qe=[];Object.entries(be).forEach(Nt=>{let wt=Nt[0],Pi=Nt[1],it=this.outputNames.indexOf(wt);if(it===-1)throw new Error(`invalid output '${wt}'`);rt.push(Pi),qe.push(it)});let Ge=Ve.map((Nt,wt)=>zy(Nt,()=>`input "${this.inputNames[Oe[wt]]}"`)),dt=rt.map((Nt,wt)=>Nt?zy(Nt,()=>`output "${this.outputNames[qe[wt]]}"`):null),Tt=await $g(this.sessionId,Oe,Ge,qe,dt,Ne),$t={};for(let Nt=0;Nt<Tt.length;Nt++)$t[this.outputNames[qe[Nt]]]=rt[Nt]??Hg(Tt[Nt]);return Ct(),$t}startProfiling(){}endProfiling(){Wg(this.sessionId)}}}),Ih={};d(Ih,{OnnxruntimeWebAssemblyBackend:()=>Nh,initializeFlags:()=>Pf,wasmBackend:()=>Vg});var Pf,Nh,Vg,K1=c(()=>{es(),G1(),Uy(),Pf=()=>{(typeof N.wasm.initTimeout!="number"||N.wasm.initTimeout<0)&&(N.wasm.initTimeout=0);let de=N.wasm.simd;if(typeof de!="boolean"&&de!==void 0&&de!=="fixed"&&de!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${de}". Reset it to \`false\` and ignore SIMD feature checking.`),N.wasm.simd=!1),typeof N.wasm.proxy!="boolean"&&(N.wasm.proxy=!1),typeof N.wasm.trace!="boolean"&&(N.wasm.trace=!1),typeof N.wasm.numThreads!="number"||!Number.isInteger(N.wasm.numThreads)||N.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)N.wasm.numThreads=1;else{let be=typeof navigator>"u"?l("node:os").cpus().length:navigator.hardwareConcurrency;N.wasm.numThreads=Math.min(4,Math.ceil((be||1)/2))}},Nh=class{async init(de){Pf(),await Wd(),await Mf(de)}async createInferenceSessionHandler(de,be){let Ne=new rv;return await Ne.loadModel(de,be),Ne}},Vg=new Nh}),Y1={};d(Y1,{InferenceSession:()=>Tn,TRACE:()=>He,TRACE_EVENT_BEGIN:()=>Ft,TRACE_EVENT_END:()=>Ot,TRACE_FUNC_BEGIN:()=>Je,TRACE_FUNC_END:()=>Ct,Tensor:()=>Ie,default:()=>Gy,env:()=>N,registerBackend:()=>p}),es(),es(),es();var qy="1.26.0",Gy=Ko;{let de=(K1(),h(Ih)).wasmBackend;p("cpu",de,10),p("wasm",de,10)}return Object.defineProperty(N.versions,"web",{value:qy,enumerable:!0}),h(Y1)})();s.exports=i})(XX)),XX.exports}var eke;function N2t(){return eke||(eke=1,(function(s){var e=Wv&&Wv.__createBinding||(Object.create?(function(x,S,k,D){D===void 0&&(D=k);var T=Object.getOwnPropertyDescriptor(S,k);(!T||("get"in T?!S.__esModule:T.writable||T.configurable))&&(T={enumerable:!0,get:function(){return S[k]}}),Object.defineProperty(x,D,T)}):(function(x,S,k,D){D===void 0&&(D=k),x[D]=S[k]})),i=Wv&&Wv.__setModuleDefault||(Object.create?(function(x,S){Object.defineProperty(x,"default",{enumerable:!0,value:S})}):function(x,S){x.default=S}),n=Wv&&Wv.__importStar||function(x){if(x&&x.__esModule)return x;var S={};if(x!=null)for(var k in x)k!=="default"&&Object.prototype.hasOwnProperty.call(x,k)&&e(S,x,k);return i(S,x),S};Object.defineProperty(s,"__esModule",{value:!0}),s.MicVAD=s.getDefaultRealTimeVADOptions=s.ort=s.DEFAULT_MODEL=void 0;const r=n(I2t()),o=Cme(),a=Sme(),l=YF(),c=lG(),d=m6e(),u=_6e();s.DEFAULT_MODEL="legacy",s.ort=r;const h="vad.worklet.bundle.min.js",f="silero_vad_v5.onnx",g="silero_vad_legacy.onnx",p=x=>({...a.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{l.log.debug("VAD misfire")},onSpeechStart:()=>{l.log.debug("Detected speech start")},onSpeechEnd:()=>{l.log.debug("Detected speech end")},onSpeechRealStart:()=>{l.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:x,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async S=>{S.getTracks().forEach(k=>{k.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:S=>{S.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});s.getDefaultRealTimeVADOptions=p;const _=x=>"audioWorklet"in x&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function m(x,S,k,D,T){await k.audioWorklet.addModule(x),S.processorOptions={...S.processorOptions??{},frameSamples:D};const N=new AudioWorkletNode(k,"vad-helper-worklet",S);return N.port.onmessage=async A=>{const O=A.data;if(!(typeof O=="object"&&O&&"message"in O)){console.error("Invalid message event",O);return}switch(O.message){case c.Message.AudioFrame:{if(!("data"in O&&O.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const $=new Float32Array(O.data);await T($);break}}},N}async function b(x,S,k){const D=new u.Resampler({nativeSampleRate:x.sampleRate,targetSampleRate:16e3,targetFrameSize:S});l.log.debug("using script processor");const N=x.createScriptProcessor(4096,1,1);let A=!1;return N.onaudioprocess=async O=>{if(!A){A=!0;try{const $=O.inputBuffer.getChannelData(0);O.outputBuffer.getChannelData(0).fill(0);const B=D.process($);for(const W of B)await k(W)}catch($){console.error("Error processing audio:",$)}finally{A=!1}}},N.connect(x.destination),N}class y{constructor(S,k,D,T,N=!1,A=null,O=null,$=null,P=null,B=null,W=null,q="uninitialized",G=!1){this.options=S,this.frameProcessor=k,this.model=D,this.frameSamples=T,this.listening=N,this.errored=A,this._stream=O,this._audioContext=$,this._vadNode=P,this._mediaStreamAudioSourceNode=B,this._audioProcessorAdapterType=W,this.initializationState=q,this.ownsAudioContext=G,this.getAudioInstances=()=>{if(this._stream===null||this._audioContext===null||this._vadNode==null||this._mediaStreamAudioSourceNode==null)throw new Error("MicVAD has null stream, audio context, or processor adapter");return{stream:this._stream,audioContext:this._audioContext,vadNode:this._vadNode,mediaStreamAudioSourceNode:this._mediaStreamAudioSourceNode}},this.setErrored=re=>{this.initializationState="errored",this.errored=re},this.start=async()=>{switch(this.initializationState){case"uninitialized":{l.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(re){throw re instanceof Error?this.setErrored(re.message):this.setErrored(String(re)),re}if(this.options.audioContext?(console.log("using custom audio context"),this._audioContext=this.options.audioContext):(console.log("using default audio context"),this._audioContext=new AudioContext,this.ownsAudioContext=!0),!this._audioContext)throw this.setErrored("Audio context is null"),Error("Audio context is null");switch(this._audioProcessorAdapterType=this.options.processorType=="auto"?_(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await m(this.options.baseAssetPath+h,this.options.workletOptions,this._audioContext,this.frameSamples,this.processFrame);break;case"ScriptProcessor":this._vadNode=await b(this._audioContext,this.frameSamples,this.processFrame);break;default:throw new Error(`Unsupported audio processor adapter type: ${this._audioProcessorAdapterType}`)}this._mediaStreamAudioSourceNode=new MediaStreamAudioSourceNode(this._audioContext,{mediaStream:this._stream}),this._mediaStreamAudioSourceNode.connect(this._vadNode),l.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{l.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:re,audioContext:ie,vadNode:K}=this.getAudioInstances();this._stream=await this.options.resumeStream(re);const Z=new MediaStreamAudioSourceNode(ie,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Z,Z.connect(K);break}case"destroyed":{l.log.warn("start called after destroyed");break}case"errored":{l.log.error("start called after errored");break}default:{l.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:re,mediaStreamAudioSourceNode:ie}=this.getAudioInstances();await this.options.pauseStream(re),ie.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var ie;l.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:re}=this.getAudioInstances();re instanceof AudioWorkletNode&&re.port.postMessage(c.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((ie=this._audioContext)==null?void 0:ie.close())},this.setOptions=re=>{this.frameProcessor.setOptions(re)},this.processFrame=async re=>{await this.frameProcessor.process(re,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=re=>{switch(re.msg){case c.Message.FrameProcessed:this.options.onFrameProcessed(re.probs,re.frame);break;case c.Message.SpeechStart:this.options.onSpeechStart();break;case c.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case c.Message.VADMisfire:this.options.onVADMisfire();break;case c.Message.SpeechEnd:this.options.onSpeechEnd(re.audio);break}}}static async new(S={}){const k={...(0,s.getDefaultRealTimeVADOptions)(S.model??s.DEFAULT_MODEL),...S};(0,a.validateOptions)(k),s.ort.env.wasm.wasmPaths=k.onnxWASMBasePath,k.ortConfig!==void 0&&k.ortConfig(s.ort);const D=k.model==="v5"?f:g,T=k.baseAssetPath+D,N=k.model==="v5"?d.SileroV5.new:d.SileroLegacy.new;let A;try{A=await N(s.ort,()=>(0,o.defaultModelFetcher)(T))}catch(W){throw console.error(`Encountered an error while loading model file ${T}`),W}const O=k.model==="v5"?512:1536,$=O/16,P=new a.FrameProcessor(A.process,A.reset_state,{positiveSpeechThreshold:k.positiveSpeechThreshold,negativeSpeechThreshold:k.negativeSpeechThreshold,redemptionMs:k.redemptionMs,preSpeechPadMs:k.preSpeechPadMs,minSpeechMs:k.minSpeechMs,submitUserSpeechOnPause:k.submitUserSpeechOnPause},$),B=new y(k,P,A,O);if(k.startOnLoad)try{await B.start()}catch(W){throw console.error("Error starting micVad",W),W}return B}}s.MicVAD=y})(Wv)),Wv}var tke;function R2t(){return tke||(tke=1,(function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.getDefaultRealTimeVADOptions=s.MicVAD=s.DEFAULT_MODEL=s.utils=s.NonRealTimeVAD=s.Message=s.FrameProcessor=s.defaultModelFetcher=s.baseAssetPath=void 0;var e=f6e();Object.defineProperty(s,"baseAssetPath",{enumerable:!0,get:function(){return e.baseAssetPath}});var i=Cme();Object.defineProperty(s,"defaultModelFetcher",{enumerable:!0,get:function(){return i.defaultModelFetcher}});var n=Sme();Object.defineProperty(s,"FrameProcessor",{enumerable:!0,get:function(){return n.FrameProcessor}});var r=lG();Object.defineProperty(s,"Message",{enumerable:!0,get:function(){return r.Message}});var o=D2t();Object.defineProperty(s,"NonRealTimeVAD",{enumerable:!0,get:function(){return o.NonRealTimeVAD}});const a=T2t();s.utils={audioFileToArray:a.audioFileToArray,minFramesForTargetMS:a.minFramesForTargetMS,arrayBufferToBase64:a.arrayBufferToBase64,encodeWAV:a.encodeWAV};var l=N2t();Object.defineProperty(s,"DEFAULT_MODEL",{enumerable:!0,get:function(){return l.DEFAULT_MODEL}}),Object.defineProperty(s,"MicVAD",{enumerable:!0,get:function(){return l.MicVAD}}),Object.defineProperty(s,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return l.getDefaultRealTimeVADOptions}})})(GX)),GX}var A2t=R2t();function V$(s,e,i,n){var o,a;try{(a=(o=window.api)==null?void 0:o.logs)==null||a.write(s,e,i,n)}catch{}const r=e==="error"?console.error:e==="warn"?console.warn:console.log;n!==void 0?r(`[${s}]`,i,n):r(`[${s}]`,i)}const ti={debug:(s,e,i)=>V$(s,"debug",e,i),info:(s,e,i)=>V$(s,"info",e,i),warn:(s,e,i)=>V$(s,"warn",e,i),error:(s,e,i)=>V$(s,"error",e,i)},b6e=16e3,M2t=6,pT=b6e*M2t,P2t=400,O2t=b6e*P2t/1e3,ike=300,nke=2e3,ske=1500,rke=3e3,F2t=600,y6e=.5,w6e=.35,oke=.85,ake=.7;let ih=null,T_=!1,fu=!1;const cde=new Set;function z$(s){for(const e of Array.from(cde))try{e(s)}catch(i){ti.warn("speech","workerDeath listener threw",{error:i instanceof Error?i.message:String(i)})}}let ZX=0;const lke=2;let r2=!1,x6e=!1;function C6e(s){s.addEventListener("message",e=>{var n;if(((n=e.data)==null?void 0:n.type)!=="log")return;const i=e.data.level||"info";ti[i]("whisperWorker",e.data.message??"",e.data.meta)}),s.addEventListener("error",e=>{ti.error("whisperWorker","worker error event (fatal)",{message:e.message,filename:e.filename,lineno:e.lineno}),B2t(`error:${e.message||"unknown"}`)})}function lH(){return ih||(ih=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),C6e(ih),ti.info("speech","worker spawned"),ih)}let U$=!1;function B2t(s){if(!r2){if(U$){ti.warn("speech","respawnWorker: already in flight, ignoring",{reason:s});return}if(U$=!0,ZX+=1,x6e=!0,ti.warn("speech","respawnWorker: starting",{reason:s,attempt:ZX}),z$({reason:s,respawned:!1,finalOnly:!0}),ZX>lke){if(r2=!0,ti.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:lke}),ih)try{ih.terminate()}catch{}ih=null,T_=!1,fu=!1,z$({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),U$=!1;return}if(ih)try{ih.terminate()}catch{}ih=null,T_=!1,fu=!1;try{ih=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),C6e(ih),fu=!0,ih.postMessage({type:"load"}),ti.info("speech","respawnWorker: new worker spawned, load posted"),z$({reason:s,respawned:!0,finalOnly:!0})}catch(e){r2=!0,ti.error("speech","respawnWorker: spawn failed, disabling speech",{error:e instanceof Error?e.message:String(e)}),z$({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{U$=!1}}}function j2t(s,e){if(T_||fu)return;fu=!0;const i=lH();ti.info("speech","preloadModel: posting load");const n=r=>{r.data.type==="status"?(s==null||s(r.data.status,r.data.message),r.data.status==="ready"&&(T_=!0,fu=!1,ti.info("speech","preloadModel: ready"),i.removeEventListener("message",n))):r.data.type==="progress"?e==null||e(r.data.pct):r.data.type==="error"&&(fu=!1,ti.error("speech","preloadModel: worker reported error",{error:r.data.error}),s==null||s("error",r.data.error),i.removeEventListener("message",n))};i.addEventListener("message",n),i.postMessage({type:"load"})}function $2t(){ti.info("speech","resetModel: clearing load flags"),T_=!1,fu=!1}function kme(){var s;return typeof Worker<"u"&&!!((s=navigator.mediaDevices)!=null&&s.getUserMedia)&&typeof AudioWorkletNode<"u"}function W2t(s){const e=lH();return!T_&&!fu&&(fu=!0,e.postMessage({type:"load"})),new Promise((i,n)=>{const r=o=>{var a,l,c;((a=o.data)==null?void 0:a.type)==="result"?(e.removeEventListener("message",r),i((o.data.text??"").trim())):((l=o.data)==null?void 0:l.type)==="error"?(e.removeEventListener("message",r),n(new Error(String(o.data.error??"Transcription failed")))):((c=o.data)==null?void 0:c.type)==="status"&&o.data.status==="ready"&&(T_=!0,fu=!1)};e.addEventListener("message",r),e.postMessage({type:"transcribe",audio:s},[s.buffer])})}function H2t(s){let e=lH(),i=!1,n=null,r=null,o=null,a=null,l=null;const c=[],d=new Set;let u=null,h=0,f=!1,g=0,p=!1,_=!1,m=0,b=0,y=0,x=-1,S=ike,k=0,D=null,T="",N="",A=!1,O=0;function $(ge,Se){const Ee=Math.min(ge.length,Se.length);let $e=0;for(;$e<Ee&&ge.charCodeAt($e)===Se.charCodeAt($e);)$e++;return $e}function P(ge){const Se=$(T,ge);return T=ge,Se>N.length&&(N=ge.slice(0,Se)),N.length>ge.length&&(N=ge),N}const B=()=>(u||(u=new Float32Array(pT)),u),W=()=>{h=0},q=ge=>{const Se=B(),Ee=ge.length;if(Ee>=pT){Se.set(ge.subarray(Ee-pT)),h=pT;return}if(h+Ee<=pT){Se.set(ge,h),h+=Ee;return}const $e=h+Ee-pT;Se.copyWithin(0,$e,h),h-=$e,Se.set(ge,h),h+=Ee},G=()=>{D&&(clearTimeout(D),D=null)},re=()=>{G(),f=!1,p=!1,_=!1,S=ike,T="",N="",A=!1,O=0,W()},ie=()=>{if(i||!f||_||p||D)return;if(h<O2t){D=setTimeout(()=>{D=null,ie()},S);return}const ge=performance.now()-m;if(ge<S&&m!==0){D=setTimeout(()=>{D=null,ie()},S-ge);return}if(x6e||r2||s.partialsEnabled&&!s.partialsEnabled())return;const Se=B(),Ee=new Float32Array(h);Ee.set(Se.subarray(0,h)),b+=1,y=b,p=!0,k=performance.now(),m=k,e.postMessage({type:"transcribe-partial",audio:Ee,seq:b},[Ee.buffer])},K=ge=>ge.length===0?Promise.resolve():r2?(ti.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),i||s.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(Se=>{c.push(Se),b+=1;const Ee=b;x=Ee,e.postMessage({type:"transcribe",audio:ge,seq:Ee},[ge.buffer])}),Z=ge=>{const Se=K(ge);return d.add(Se),Se.finally(()=>{d.delete(Se)}),Se},Q=ge=>{var Se,Ee,$e,De,ae;if(ge.data.type==="result"){const Te=ge.data.text,Ie=ge.data.seq??0;Ie&&Ie<x&&ti.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:Ie,latestFinalSeq:x}),!i&&Te&&s.onFinal(Te),(Se=c.shift())==null||Se()}else if(ge.data.type==="partial"){const Te=ge.data.seq??0,Ie=ge.data.text??"",st=performance.now()-k;p=!1,st>=rke?(_=!0,ti.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(st),seq:Te})):st>=ske&&(S=Math.min(S*2,nke),ti.warn("speech","partials.slowdown",{elapsedMs:Math.round(st),newIntervalMs:S,seq:Te})),A||(A=!0,st>F2t&&S<500&&(S=500,ti.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(st),newIntervalMs:500})));const He=Te!==y||Te<=x;if(!i&&!He&&Ie){const lt=P(Ie);lt&&((Ee=s.onPartial)==null||Ee.call(s,lt),O===0&&(O=performance.now(),ti.info("speech","partial.first",{msSinceSpeechStart:Math.round(O-g)})))}ie()}else if(ge.data.type==="partial-error"){const Te=performance.now()-k;p=!1,Te>=rke?(_=!0,ti.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(Te),seq:ge.data.seq})):Te>=ske&&(S=Math.min(S*2,nke),ti.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(Te),newIntervalMs:S,seq:ge.data.seq})),ti.warn("speech","partial encode failed",{error:ge.data.error,seq:ge.data.seq}),ie()}else ge.data.type==="error"?(i||s.onError(ge.data.error),($e=c.shift())==null||$e()):ge.data.type==="status"?(i||(De=s.onModelStatus)==null||De.call(s,ge.data.status,ge.data.message),ge.data.status==="ready"&&(T_=!0,fu=!1)):ge.data.type==="progress"&&(i||(ae=s.onProgress)==null||ae.call(s,ge.data.pct))};e.addEventListener("message",Q);const ne=ge=>{var Se,Ee;if(!i){for(ti.warn("speech","createRecognition: worker death event",ge),(Se=s.onStatusChange)==null||Se.call(s,"restarting");c.length;)(Ee=c.shift())==null||Ee();if(d.clear(),G(),p=!1,ge.respawned){try{e.removeEventListener("message",Q)}catch{}e=lH(),e.addEventListener("message",Q)}}};return cde.add(ne),{start:async()=>{if(!i){if(r2){s.onError("Speech recognition disabled — please reload the app.");return}!T_&&!fu&&(fu=!0,ti.info("speech","createRecognition.start: triggering model load"),e.postMessage({type:"load"})),ti.info("speech","createRecognition.start: initializing VAD",{modelReady:T_,modelLoading:fu});try{const ge=new URL("vad/",document.baseURI).href,Se=s.inputDeviceId||null,Ee={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};Se&&(Ee.deviceId={exact:Se}),ti.info("speech","getUserMedia",{hasDeviceId:!!Se,deviceIdPrefix:Se?Se.slice(0,8):null});const $e=await navigator.mediaDevices.getUserMedia({audio:Ee});r=$e,o=new AudioContext;for(const De of $e.getAudioTracks())De.addEventListener("ended",()=>{i||(ti.warn("speech","mic track ended (permission revoked or device removed)"),s.onError("Microphone disconnected or permission revoked"))});try{l=o.createMediaStreamSource(r),a=o.createAnalyser(),a.fftSize=2048,a.smoothingTimeConstant=.3,l.connect(a)}catch(De){ti.warn("speech","analyser init failed",{error:De instanceof Error?De.message:String(De)}),l=null,a=null}n=await A2t.MicVAD.new({audioContext:o,getStream:async()=>$e,resumeStream:async()=>$e,pauseStream:async()=>{},baseAssetPath:ge,onnxWASMBasePath:ge,model:"v5",positiveSpeechThreshold:y6e,negativeSpeechThreshold:w6e,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(De,ae)=>{var Te;i||((Te=s.onFrame)==null||Te.call(s,De),f&&(q(ae),ie()))},onSpeechStart:()=>{var De;i||(re(),f=!0,g=performance.now(),(De=s.onSpeechStart)==null||De.call(s))},onSpeechEnd:De=>{var ae;i||((ae=s.onStatusChange)==null||ae.call(s,"transcribing"),re(),Z(De))},onVADMisfire:()=>{var De,ae;i||((De=s.onStatusChange)==null||De.call(s,"idle"),re(),(ae=s.onMisfire)==null||ae.call(s))}}),n.start()}catch(ge){const Se=ge instanceof Error?ge.message:"Microphone access denied",Ee=ge instanceof Error?ge.stack:"";if(ti.error("speech","createRecognition.start: VAD init failed",{error:Se,stack:Ee}),a){try{a.disconnect()}catch{}a=null}if(l){try{l.disconnect()}catch{}l=null}if(r){try{r.getTracks().forEach($e=>$e.stop())}catch{}r=null}if(o){try{await o.close()}catch{}o=null}s.onError(Se)}}},stop:async()=>{if(n)try{await n.pause()}catch{}for(re();d.size>0;)await Promise.all(Array.from(d));if(n){try{await n.destroy()}catch{}n=null}if(a){try{a.disconnect()}catch{}a=null}if(l){try{l.disconnect()}catch{}l=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}if(o){try{await o.close()}catch{}o=null}},setVadThresholds:(ge,Se)=>{if(n)try{n.setOptions({positiveSpeechThreshold:ge,negativeSpeechThreshold:Se})}catch(Ee){ti.warn("speech","setVadThresholds failed",{error:Ee instanceof Error?Ee.message:String(Ee)})}},getAnalyser:()=>a,destroy:()=>{if(i=!0,re(),n){try{n.destroy()}catch{}n=null}if(a){try{a.disconnect()}catch{}a=null}if(l){try{l.disconnect()}catch{}l=null}if(o){try{o.close()}catch{}o=null}if(r){try{r.getTracks().forEach(ge=>ge.stop())}catch{}r=null}cde.delete(ne),e.removeEventListener("message",Q)}}}let KO=null;const dde=new Set,ude=new Set;function V2t(){for(const s of dde)try{s()}catch{}}function hde(){for(const s of ude)try{s()}catch{}}function z2t(s){return s.replace(/```[\s\S]*?```/g,"").replace(/`([^`]+)`/g,"$1").replace(/^#{1,6}\s+/gm,"").replace(/\*{1,3}([^*]+)\*{1,3}/g,"$1").replace(/_{1,3}([^_]+)_{1,3}/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/^[-*_]{3,}\s*$/gm,"").replace(/^>\s?/gm,"").replace(/^[\s]*[-*+]\s/gm,"").replace(/^[\s]*\d+\.\s/gm,"").trim()}function U2t(s){if(!window.speechSynthesis)return;const e=z2t(s);if(!e)return;const i=new SpeechSynthesisUtterance(e);i.rate=1,i.pitch=1,i.onstart=()=>{KO=performance.now(),V2t()},i.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(KO=null,hde())},i.onerror=n=>{n.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(KO=null,hde())},window.speechSynthesis.speak(i)}function S6e(){window.speechSynthesis&&(window.speechSynthesis.cancel(),KO=null,hde())}function k6e(){var s;return((s=window.speechSynthesis)==null?void 0:s.speaking)??!1}function q2t(){return KO}function G2t(s){return dde.add(s),()=>{dde.delete(s)}}function K2t(s){return ude.add(s),()=>{ude.delete(s)}}function Y2t(s){k6e()&&(s.setVadThresholds(oke,ake),ti.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const e=G2t(()=>{s.setVadThresholds(oke,ake),ti.info("voice","tts.duck.on")}),i=K2t(()=>{s.setVadThresholds(y6e,w6e),ti.info("voice","tts.duck.off")});return()=>{e(),i()}}const X2t=[{match:/^(send|submit|enter)\.?$/i,data:"\r",label:"send"},{match:/^(cancel|escape)\.?$/i,data:"\x1B",label:"cancel"},{match:/^clear( line)?\.?$/i,data:"",label:"clear"}];function Z2t(s){const e=s.trim();return X2t.find(i=>i.match.test(e))??null}const Q2t=4e4;let bS=null;function o2(){bS&&clearTimeout(bS),bS=setTimeout(()=>{bS=null,zi.getState().stopRecording()},Q2t)}function q$(){bS&&(clearTimeout(bS),bS=null)}let D0=null,c0=null;const J2t=.04,eNt=.3;let cH=0,fde=0;function tNt(s){c0!==null&&cancelAnimationFrame(c0);const e=()=>{if(D0===null||zi.getState().submitCountdownStartAt===null){c0=null;return}const i=performance.now();if(i-fde<200&&cH>eNt){const r=i-s;ti.info("voice","submit.preempted_by_voice",{reason:"vad",prob:cH.toFixed(2),msIntoCountdown:Math.round(r)}),Vw(),o2();return}const n=L6e();if(n){const r=new Uint8Array(n.fftSize);n.getByteTimeDomainData(r);let o=0;for(let l=0;l<r.length;l++){const c=(r[l]-128)/128;o+=c*c}const a=Math.sqrt(o/r.length);if(a>J2t){const l=i-s;ti.info("voice","submit.preempted_by_voice",{reason:"rms",rms:a.toFixed(3),msIntoCountdown:Math.round(l)}),Vw(),o2();return}}c0=requestAnimationFrame(e)};c0=requestAnimationFrame(e)}function iNt(s){D0&&clearTimeout(D0);const e=zi.getState().submitDelayMs,i=performance.now();zi.setState({submitCountdownStartAt:i}),D0=setTimeout(()=>{D0=null,zi.setState({submitCountdownStartAt:null});try{window.api.pty.write({tabId:s,data:"\r"})}catch(n){ti.warn("voice","submit pty.write failed",{error:n instanceof Error?n.message:String(n)})}o2()},e),tNt(i)}function Vw(){c0!==null&&(cancelAnimationFrame(c0),c0=null),D0&&(clearTimeout(D0),D0=null),zi.getState().submitCountdownStartAt!==null&&zi.setState({submitCountdownStartAt:null})}let cc=null,gd=null;function L6e(){var s;return((s=cc==null?void 0:cc.getAnalyser)==null?void 0:s.call(cc))??null}const G$=1e4;let YO=null;function K$(){YO&&(clearTimeout(YO),YO=null)}let E8=null,D8=null;function Y$(){E8=null,D8&&(D8(),D8=null)}const nNt=1500,sNt=9e4;let X$=0,T8=null,gde=-1;function Z$(){T8&&(clearTimeout(T8),T8=null,gde=-1)}const rNt=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),zi=Ka((s,e)=>({isRecording:!1,ttsEnabled:!1,autoSubmit:!0,submitDelayMs:8e3,submitCountdownStartAt:null,lastTranscript:"",lastPartial:"",statusPill:"idle",partialsEnabled:!0,error:null,errorKind:null,modelStatus:"idle",loadingProgress:0,permissionState:"unknown",lastBargeInAt:null,hotkeyState:"idle",levelMeterEnabled:!0,turnDetectorState:"disabled",turnDetectorMode:"off",wizardArmed:!1,wizardOpen:!1,initModel:()=>{if(e().modelStatus!=="idle")return;ti.info("voice","initModel: kicking off preload"),s({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const i=++X$,n=()=>{i===X$&&(Z$(),gde=i,T8=setTimeout(()=>{gde===i&&e().modelStatus==="loading"&&(ti.warn("voice","mic.gate.timeout: no progress within 90s"),s({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},sNt))};n(),j2t((r,o)=>{i===X$&&(r==="ready"?(Z$(),ti.info("voice","modelStatus -> ready"),s({modelStatus:"ready",loadingProgress:100,errorKind:null})):r==="error"?(Z$(),ti.error("voice","modelStatus -> error",{msg:o}),s({modelStatus:"error",error:o,errorKind:"load"})):(n(),s({modelStatus:"loading"})))},r=>{i===X$&&(n(),s({loadingProgress:Math.round(r)}))})},resetAndRetryModel:()=>{ti.info("voice","mic.gate.retry"),Z$(),$2t(),s({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),e().initModel()},startRecording:i=>{if(e().isRecording)return;if(cc){ti.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!kme()){s({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const n=r=>{try{const o=H2t({inputDeviceId:r,onStatusChange:a=>{s(a==="transcribing"?{statusPill:"transcribing"}:a==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:a=>{e().partialsEnabled&&s({lastPartial:a})},partialsEnabled:()=>e().partialsEnabled,onFrame:a=>{cH=a.isSpeech,fde=performance.now()},onSpeechStart:()=>{if(s({statusPill:"listening",lastPartial:""}),q$(),Vw(),k6e()){const l=q2t(),c=l!==null?performance.now()-l:null;S6e(),s({lastBargeInAt:performance.now()}),ti.info("voice","barge-in",{tabId:i,utteranceOffsetMs:c})}else ti.debug("voice","barge-in.no-op",{tabId:i})},onMisfire:()=>{s({lastPartial:"",statusPill:"idle"}),o2();const a=e().lastBargeInAt;a!==null&&performance.now()-a<600&&ti.warn("voice","barge-in.misfire",{tabId:i,sinceBargeInMs:Math.round(performance.now()-a)})},onFinal:a=>{o2();const l=a.trim();if(!l||rNt.has(l)){s({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}const c=Z2t(l);if(c){ti.info("voice","voice-command",{tabId:i,label:c.label,transcript:l}),window.api.pty.write({tabId:i,data:c.data}),s({lastTranscript:"",lastPartial:"",statusPill:"idle"}),Vw();const u=window;u.__transcripts&&(u.__transcripts.push({tabId:i,text:l}),u.__transcripts.length>500&&u.__transcripts.shift());return}window.api.pty.write({tabId:i,data:l}),s({lastTranscript:"",lastPartial:"",statusPill:"idle"}),e().autoSubmit&&iNt(i);const d=window;d.__transcripts&&(d.__transcripts.push({tabId:i,text:l}),d.__transcripts.length>500&&d.__transcripts.shift())},onError:a=>{ti.error("voice","recognition error",{err:a}),Vw(),s({error:a,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),gd==null||gd(),gd=null,q$(),cc==null||cc.destroy(),cc=null,Kt.error(`Microphone error: ${a}`)},onModelStatus:a=>{a==="ready"?s({modelStatus:"ready",loadingProgress:100}):a==="loading"&&s({modelStatus:"loading"})},onProgress:a=>s({loadingProgress:Math.round(a)})});cc=o,s({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),o2(),o.start().then(()=>{cc===o&&(gd==null||gd(),gd=Y2t(o))}).catch(a=>{const l=a instanceof Error?a.message:String(a);ti.error("voice","handle.start() failed",{error:l}),Kt.error(`Could not start mic: ${l}`)})}catch(o){s({error:o instanceof Error?o.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var r,o,a;return((a=(o=(r=window.api)==null?void 0:r.voice)==null?void 0:o.getDevicePref)==null?void 0:a.call(o))??Promise.resolve(null)}).then(r=>n((r==null?void 0:r.selectedDeviceId)??null)).catch(r=>{ti.warn("voice","getDevicePref failed; using default device",{error:r instanceof Error?r.message:String(r)}),n(null)})},stopRecording:()=>{const i=cc;i&&(q$(),Vw(),cH=0,fde=0,gd==null||gd(),gd=null,s({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),i.stop().finally(()=>{i.destroy(),cc===i&&(cc=null),e().hotkeyState==="stopping"&&(K$(),s({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!e().isRecording)return;const i=cc;if(!i)return;q$(),gd==null||gd(),gd=null,s({isRecording:!1,lastTranscript:"",lastPartial:""});try{await i.stop()}catch(o){ti.warn("voice","restartWithDevice: drain rejected",{error:o instanceof Error?o.message:String(o)})}i.destroy(),cc===i&&(cc=null);const{useSessions:n}=await ei(async()=>{const{useSessions:o}=await Promise.resolve().then(()=>h2t);return{useSessions:o}},[],import.meta.url),r=n.getState().activeTabId;r&&e().startRecording(r)},toggleTTS:()=>s(i=>({ttsEnabled:!i.ttsEnabled})),setAutoSubmit:i=>s({autoSubmit:i}),setSubmitDelayMs:i=>s({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(i)))}),cancelSubmit:()=>Vw(),setPartialsEnabled:i=>{e().partialsEnabled!==i&&(s({partialsEnabled:i}),i||s({lastPartial:""}))},clearError:()=>s({error:null,errorKind:null}),setPermissionState:i=>{e().permissionState!==i&&(ti.info("voice","mic.gate.permission_changed",{from:e().permissionState,to:i}),s({permissionState:i}))},setLevelMeterEnabled:i=>{e().levelMeterEnabled!==i&&s({levelMeterEnabled:i})},setTurnDetectorRuntimeState:i=>{e().turnDetectorState!==i&&(s({turnDetectorState:i}),i==="load_failed"?ti.warn("voice-turn","voice-turn.load_failed"):i==="runtime_error"?ti.warn("voice-turn","voice-turn.runtime_error"):i==="disabled"&&ti.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:i=>{e().wizardArmed!==i&&s({wizardArmed:i})},openWizard:()=>{e().wizardOpen||s({wizardOpen:!0})},closeWizard:()=>{e().wizardOpen&&s({wizardOpen:!1})},armHotkey:({phase:i,source:n,mode:r,tabId:o})=>{const a=e(),{canRecord:l,reason:c}=pde(a);if(i==="down"){if(c==="error"||c==="load-timeout"){a.resetAndRetryModel(),ti.info("voice-hotkey","down.retry",{source:n,reason:c});return}if(!l&&c!=="loading"){ti.warn("voice-hotkey","miss-model-loading",{modelStatus:a.modelStatus,reason:c});return}if(a.hotkeyState==="recording"||a.isRecording){(r==="toggle"||n==="global")&&(s({hotkeyState:"stopping"}),K$(),YO=setTimeout(()=>{e().hotkeyState==="stopping"&&(ti.warn("voice-hotkey","drain-timeout",{durationMs:G$}),s({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&s({hotkeyState:"idle"})},0))},G$),a.stopRecording());return}if(c==="loading"){a.hotkeyState!=="armed"&&(s({hotkeyState:"armed"}),ti.info("voice-hotkey","armed",{source:n,modelStatus:a.modelStatus})),Y$(),E8={tabId:o,source:n,mode:r},D8=zi.subscribe((d,u)=>{if(E8&&d.modelStatus==="ready"&&u.modelStatus!=="ready"&&d.hotkeyState==="armed"){const h=E8;if(Y$(),!h.tabId){ti.warn("voice-hotkey","armed-promote-no-tab",{source:h.source}),s({hotkeyState:"idle"});return}ti.info("voice-hotkey","armed-promote",h),s({hotkeyState:"recording"}),zi.getState().startRecording(h.tabId)}});return}if(!o){ti.warn("voice-hotkey","no-active-tab",{source:n});return}ti.info("voice-hotkey","start",{source:n,mode:r,tabId:o}),a.startRecording(o),e().isRecording?s({hotkeyState:"recording"}):(ti.warn("voice-hotkey","start: recording did not engage",{errorKind:e().errorKind}),s({hotkeyState:"idle"}));return}if(!(r!=="hold"||n==="global")){if(a.hotkeyState==="armed"){Y$(),ti.info("voice-hotkey","miss-model-loading-armed-up"),s({hotkeyState:"idle"});return}a.hotkeyState==="recording"&&(s({hotkeyState:"stopping"}),K$(),YO=setTimeout(()=>{e().hotkeyState==="stopping"&&(ti.warn("voice-hotkey","drain-timeout",{durationMs:G$}),s({hotkeyState:"aborted"}),setTimeout(()=>{e().hotkeyState==="aborted"&&s({hotkeyState:"idle"})},0))},G$),a.stopRecording())}},destroyHotkey:()=>{const i=e();if(Y$(),Vw(),i.hotkeyState==="recording"){ti.warn("voice-hotkey","destroyed-mid-recording"),s({hotkeyState:"destroyed"});try{i.stopRecording()}catch{}}else(i.hotkeyState==="armed"||i.hotkeyState==="stopping")&&(K$(),s({hotkeyState:"destroyed"}))}})),oNt=s=>({isRecording:s.isRecording,statusPill:s.statusPill,lastPartial:s.lastPartial,lastTranscript:s.lastTranscript,submitCountdownStartAt:s.submitCountdownStartAt}),pde=s=>kme()?s.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:s.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:s.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:s.modelStatus==="error"?{canRecord:!1,reason:s.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const s=window;s.__voice=zi,s.__transcripts=[]}function Lme(s,e,i){return new Promise((n,r)=>{const o=setTimeout(()=>r(new Error(`${i} timed out after ${e}ms`)),e);s.then(a=>{clearTimeout(o),n(a)},a=>{clearTimeout(o),r(a)})})}const aNt=5e3,D1=Ka(()=>({snapshot:null,loaded:!1}));let cke=!1,dke=!1;async function lNt(){if(!cke){cke=!0;try{const s=await Lme(window.api.schedule.state(),aNt,"schedule.state");D1.setState({snapshot:s,loaded:!0})}catch(s){if(!dke){dke=!0;const e=s instanceof Error?s.message:String(s);Kt.error(`Scheduler state hydrate failed: ${e}`)}}window.api.schedule.onState(s=>{D1.setState({snapshot:s,loaded:!0})})}}const cNt=6e4,dNt=5e3,WS=Ka(()=>({data:null,refreshing:!1}));let uke=!1,I8=null,hke=null,fke=!1;async function Eme(){WS.setState({refreshing:!0});let s=cNt;try{const e=await Lme(window.api.billing.fetch(),dNt,"billing.fetch");WS.setState({data:e,refreshing:!1}),e.kind==="transient"?s=hke==="transient"?3e4:5e3:e.kind==="auth"&&(s=3e4),hke=e.kind}catch(e){if(WS.setState({refreshing:!1}),!fke){fke=!0;const i=e instanceof Error?e.message:String(e);Kt.warn(`Billing usage fetch failed: ${i}`)}}I8=setTimeout(Eme,s)}function uNt(){uke||(uke=!0,Eme())}function XF(s){return s?s.kind==="ok"||s.kind==="ok-stale"?s.data:s.kind==="auth"&&s.cached?s.cached:null:null}function hNt(s){var e,i;return((i=(e=XF(s))==null?void 0:e.usage.five_hour)==null?void 0:i.utilization)??0}function dH(){I8!==null&&(clearTimeout(I8),I8=null),Eme()}function wy({name:s,size:e=17,stroke:i=1.6,className:n}){const r={width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:i,strokeLinecap:"round",strokeLinejoin:"round",className:n};switch(s){case"home":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M4 11l8-7 8 7"}),v.jsx("path",{d:"M6 10v9h12v-9"}),v.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),v.jsx("path",{d:"M7 10l3 2-3 2"}),v.jsx("path",{d:"M13 14h4"})]});case"agents":case"subagents":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"7",cy:"9",r:"2.5"}),v.jsx("circle",{cx:"17",cy:"9",r:"2.5"}),v.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),v.jsx("path",{d:"M8.6 11l2.8 4M15.4 11l-2.8 4M9.5 9h5"})]});case"agent-view":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"12",r:"9"}),v.jsx("circle",{cx:"12",cy:"12",r:"3"}),v.jsx("path",{d:"M3 12h2M19 12h2M12 3v2M12 19v2"})]});case"skills":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M12 3l2.5 5.5L20 9l-4 4 1 6-5-3-5 3 1-6-4-4 5.5-.5z"})});case"history":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"12",r:"8"}),v.jsx("path",{d:"M12 7v5l3 2"}),v.jsx("path",{d:"M4 6l2 2"})]});case"usage":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"hive":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M8 4h8l4 7-4 7H8l-4-7z"}),v.jsx("circle",{cx:"12",cy:"11",r:"2.5"})]});case"knowledge-graph":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"6",cy:"7",r:"2.2"}),v.jsx("circle",{cx:"18",cy:"6",r:"2.2"}),v.jsx("circle",{cx:"17",cy:"18",r:"2.2"}),v.jsx("circle",{cx:"7",cy:"17",r:"2.2"}),v.jsx("path",{d:"M8 8l8 8M8 16l8-9M8 7h8"})]});case"plugins":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),v.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),v.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),v.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),v.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"8",cy:"12",r:"4"}),v.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"plans":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),v.jsx("path",{d:"M8 9h8M8 13h8M8 17h5"})]});case"tasks":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"3",y:"4",width:"7",height:"7",rx:"1.5"}),v.jsx("rect",{x:"3",y:"13",width:"7",height:"7",rx:"1.5"}),v.jsx("path",{d:"M14 6h7M14 10h5M14 15h7M14 19h5"})]});case"projects":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"docs":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M6 3h8l4 4v14H6z"}),v.jsx("path",{d:"M14 3v4h4M9 13h6M9 17h6M9 9h3"})]});case"memory":case"agent-memory":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M9 4a4 4 0 00-4 4v1a3 3 0 000 6v1a4 4 0 004 4h6a4 4 0 004-4v-1a3 3 0 000-6V8a4 4 0 00-4-4z"}),v.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"11",cy:"11",r:"6"}),v.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return v.jsx("svg",{...r,children:v.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M7 3h7l4 4v14H7z"}),v.jsx("path",{d:"M14 3v4h4"})]});case"play":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),v.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"12",r:"8"}),v.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),v.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),v.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"12",r:"3"}),v.jsx("path",{d:"M12 2v3M12 19v3M4 12H1M23 12h-3M5.6 5.6l2.1 2.1M16.3 16.3l2.1 2.1M5.6 18.4l2.1-2.1M16.3 7.7l2.1-2.1"})]});case"mic":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),v.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"12",r:"8"}),v.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),v.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"orchestrator":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"12",cy:"6",r:"2.5"}),v.jsx("circle",{cx:"5",cy:"17",r:"2.5"}),v.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),v.jsx("circle",{cx:"19",cy:"17",r:"2.5"}),v.jsx("path",{d:"M12 8.5v6M12 14.5l-7 0M12 14.5l7 0"})]});case"race":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M5 4v16M5 5h7l-1 3h7v6h-7l-1 3H5"})});case"background":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M3 4h18v4H3zM3 10h18v4H3zM3 16h18v4H3z"}),v.jsx("circle",{cx:"6",cy:"6",r:".75",fill:"currentColor",stroke:"none"}),v.jsx("circle",{cx:"6",cy:"12",r:".75",fill:"currentColor",stroke:"none"}),v.jsx("circle",{cx:"6",cy:"18",r:".75",fill:"currentColor",stroke:"none"})]});case"repoviz":return v.jsxs("svg",{...r,children:[v.jsx("circle",{cx:"6",cy:"12",r:"3"}),v.jsx("circle",{cx:"18",cy:"6",r:"3"}),v.jsx("circle",{cx:"18",cy:"18",r:"3"}),v.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),v.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),v.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),v.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return v.jsx("svg",{...r,children:v.jsx("path",{d:"M14 4a4 4 0 014 4l-7 7-4-4 7-7zM7 11l-3 3 6 6 3-3"})});case"quick-open":return v.jsxs("svg",{...r,children:[v.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),v.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return v.jsxs("svg",{...r,children:[v.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),v.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});default:return null}}const E6e=s=>`sm.fileTree.expanded:${s}`;function fNt(s){try{const e=localStorage.getItem(E6e(s)),i=e?JSON.parse(e):[];return Array.isArray(i)?i.filter(n=>typeof n=="string"):[]}catch{return[]}}function gNt(s,e){try{localStorage.setItem(E6e(s),JSON.stringify([...e].slice(0,500)))}catch{}}function QX(s,e){const i=e+"/";let n=!1;const r=new Set;for(const o of s){if(o===e||o.startsWith(i)){n=!0;continue}r.add(o)}return n?r:s}const JX={modified:{color:"#e2a93d",label:"M"},added:{color:"#3fb950",label:"A"},deleted:{color:"#f85149",label:"D"},renamed:{color:"#a371f7",label:"R"},untracked:{color:"#8b949e",label:"U"},staged:{color:"#3fb950",label:"S"},conflict:{color:"#f85149",label:"!"}},pNt=new Set(["md","txt","json","jsonl","ndjson","js","jsx","ts","tsx","py","go","rs","rb","c","cpp","h","hpp","java","sh","bash","css","scss","html","xml","yaml","yml","toml","ini","conf","env","log","sql","gitignore","png","jpg","jpeg","gif","svg","webp"]);function mNt(s){const e=s.toLowerCase().split(".").pop()||"";return pNt.has(e)}function _Nt(s,e){if(e)return"#d97757";switch(s.toLowerCase().split(".").pop()||""){case"ts":case"tsx":return"#3178c6";case"js":case"jsx":return"#f7df1e";case"json":return"#cbcb41";case"md":return"#8a93a0";case"css":case"scss":return"#cc6699";case"py":return"#3776ab";case"go":return"#00add8";case"rs":return"#dea584";case"sh":case"bash":return"#89e051";case"png":case"jpg":case"jpeg":case"gif":case"svg":return"#a4c639";default:return"#8a93a0"}}async function Q$(s){var e;try{const i=window.api;return(e=i==null?void 0:i.git)!=null&&e.fileStatus?await i.git.fileStatus(s):{}}catch{return{}}}function vNt({cwd:s,onPreviewFile:e,onSendToChat:i,activeTabId:n}){const[r,o]=z.useState([]),[a,l]=z.useState(new Set),c=z.useRef(a);c.current=a;const[d,u]=z.useState(""),[h,f]=z.useState(!1),[g,p]=z.useState(!1),[_,m]=z.useState(null),[b,y]=z.useState({}),[x,S]=z.useState(null),[k,D]=z.useState(null),[T,N]=z.useState(""),[A,O]=z.useState(null),[$,P]=z.useState(""),[B,W]=z.useState(null),q=z.useRef(null),G=z.useRef(null),re=z.useRef(0),ie=z.useCallback(async()=>{if(!s)return;const Je=++re.current;p(!0),m(null);const Ct=await window.api.files.list(s,h);re.current===Je&&(Ct.ok?o(Ct.entries.map(Ft=>({...Ft}))):(m(Ct.error??"failed to list"),o([])),p(!1))},[s,h]),K=z.useCallback(async Je=>{const Ct=re.current,Ft=new Map;for(const En of Je){const Ji=En.split("/").length,cn=Ft.get(Ji);cn?cn.push(En):Ft.set(Ji,[En])}const Ot=[];for(const En of[...Ft.keys()].sort((Ji,cn)=>Ji-cn)){const Ji=Ft.get(En),cn=await Promise.all(Ji.map(async Tn=>({p:Tn,result:await window.api.files.list(Tn,h)})));if(re.current!==Ct)return Ot;for(const{p:Tn,result:Ts}of cn)Ts.ok?o(ds=>N8(ds,Tn,Ts.entries.map(rr=>({...rr})))):Ot.push(Tn)}return Ot},[h]),Z=z.useCallback(async Je=>(await ie(),Je.length?K(Je):[]),[ie,K]);z.useEffect(()=>{u(""),D(null),S(null),O(null),W(null),y({});const Je=fNt(s),Ct=new Set(Je);c.current=Ct,l(Ct);let Ft=!1;return(async()=>{const Ot=await Z(Je);Ft||!Ot.length||ne(En=>{const Ji=new Set;let cn=!1;for(const Tn of En){if(Ot.some(Ts=>Tn===Ts||Tn.startsWith(Ts+"/"))){cn=!0;continue}Ji.add(Tn)}return cn?Ji:En})})(),Q$(s).then(Ot=>{Ft||y(Ot)}),()=>{Ft=!0}},[s]);const Q=z.useRef(!0);z.useEffect(()=>{if(Q.current){Q.current=!1;return}Z([...c.current])},[h]),z.useEffect(()=>{if(!s)return;const Je=window.setInterval(()=>{Q$(s).then(y)},5e3);return()=>window.clearInterval(Je)},[s]),z.useEffect(()=>{if(!x)return;const Je=()=>S(null),Ct=Ft=>{Ft.key==="Escape"&&S(null)};return window.addEventListener("mousedown",Je),window.addEventListener("keydown",Ct),()=>{window.removeEventListener("mousedown",Je),window.removeEventListener("keydown",Ct)}},[x]),z.useEffect(()=>{k&&setTimeout(()=>{var Je;return(Je=q.current)==null?void 0:Je.select()},30)},[k]),z.useEffect(()=>{A&&setTimeout(()=>{var Je;return(Je=G.current)==null?void 0:Je.focus()},30)},[A]);const ne=z.useCallback(Je=>{const Ct=c.current,Ft=Je(Ct);Ft!==Ct&&(c.current=Ft,l(Ft),gNt(s,Ft))},[s]),ge=z.useCallback(async Je=>{if(a.has(Je.path)){ne(Ft=>QX(Ft,Je.path));return}if(ne(Ft=>new Set(Ft).add(Je.path)),Je.children)return;const Ct=await window.api.files.list(Je.path,h);Ct.ok&&o(Ft=>N8(Ft,Je.path,Ct.entries.map(Ot=>({...Ot}))))},[a,h,ne]),Se=z.useCallback(async Je=>{if(Je===s){await ie();return}const Ct=await window.api.files.list(Je,h);Ct.ok&&o(Ft=>N8(Ft,Je,Ct.entries.map(Ot=>({...Ot}))))},[s,ie,h]),Ee=z.useCallback(Je=>{if(Je.isDirectory){ge(Je);return}mNt(Je.name)&&e?e(Je.path):window.api.files.openExternal(Je.path)},[ge,e]),$e=z.useCallback(Je=>{if(i){i(Je);return}if(n){const Ct=Je.startsWith(s+"/")?Je.slice(s.length+1):Je;window.api.pty.write({tabId:n,data:`@${Ct} `})}},[i,n,s]),De=z.useCallback((Je,Ct)=>{Je.preventDefault(),Je.stopPropagation(),S({x:Je.clientX,y:Je.clientY,node:Ct})},[]),ae=Je=>{D(Je.path),N(Je.name)},Te=async()=>{if(!k)return;const Je=T.trim();if(!Je){D(null);return}const Ct=await window.api.files.rename(k,Je);if(D(null),Ct.ok){const Ft=k.slice(0,k.lastIndexOf("/"));ne(Ot=>QX(Ot,k)),await Se(Ft||s),Q$(s).then(y)}else m(Ct.error??"rename failed")},Ie=async()=>{if(!A)return;const Je=$.trim();if(!Je){O(null),P("");return}const Ct=await window.api.files.create(A.parent,Je,A.kind);O(null),P(""),Ct.ok?(await Se(A.parent),A.kind==="folder"&&ne(Ft=>new Set(Ft).add(A.parent))):m(Ct.error??"create failed")},st=async()=>{if(!B)return;const Je=await window.api.files.delete(B.path),Ct=B.path.slice(0,B.path.lastIndexOf("/"));W(null),Je.ok?(ne(Ft=>QX(Ft,B.path)),await Se(Ct||s),Q$(s).then(y)):m(Je.error??"delete failed")},He=z.useMemo(()=>{if(!d.trim())return r;const Je=d.toLowerCase();return r.filter(Ct=>Ct.name.toLowerCase().includes(Je))},[r,d]),lt=(s==null?void 0:s.split("/").filter(Boolean).pop())||"project";return v.jsxs("div",{className:"w-60 h-full flex flex-col bg-bg-elev border-r border-line text-fg",children:[v.jsxs("div",{className:"p-3 border-b border-line shrink-0",children:[v.jsxs("div",{className:"flex items-center gap-2 mb-2 min-w-0",children:[v.jsx(T6e,{size:14,className:"shrink-0 text-accent"}),v.jsxs("div",{className:"flex-1 min-w-0",children:[v.jsx("p",{className:"text-xs font-medium text-fg truncate",children:lt}),v.jsx("p",{className:"text-[10px] text-fg-faint truncate",title:s,children:s})]}),v.jsx("button",{onClick:ie,className:"p-1 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"Refresh",disabled:g,children:v.jsx(SNt,{size:12,className:g?"animate-spin":""})})]}),v.jsx("div",{className:"relative",children:v.jsx("input",{value:d,onChange:Je=>u(Je.target.value),placeholder:"Search files…",className:"w-full px-2 py-1 text-xs bg-bg-hi border border-line rounded text-fg placeholder-fg-faint focus:outline-none focus:border-accent/40"})})]}),v.jsxs("div",{className:"flex items-center gap-1 px-3 py-1.5 border-b border-line shrink-0",children:[v.jsx("button",{onClick:()=>O({parent:s,kind:"file"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New file",children:v.jsx(kNt,{size:12})}),v.jsx("button",{onClick:()=>O({parent:s,kind:"folder"}),className:"p-1.5 rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",title:"New folder",children:v.jsx(LNt,{size:12})}),v.jsx("div",{className:"flex-1"}),v.jsx("button",{onClick:()=>f(Je=>!Je),className:`p-1.5 rounded transition-colors ${h?"text-accent":"text-fg-faint hover:text-fg"} hover:bg-bg-hi`,title:h?"Hide hidden files":"Show hidden files",children:h?v.jsx(ENt,{size:12}):v.jsx(DNt,{size:12})})]}),v.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[_&&v.jsx("div",{className:"px-3 py-2 text-[11px] text-red-400",children:_}),!_&&He.length===0&&!g&&v.jsx("div",{className:"p-4 text-center text-[11px] text-fg-faint",children:d?"no matches":"empty folder"}),!_&&v.jsx(D6e,{nodes:He,depth:0,expanded:a,gitStatus:b,renaming:k,renameValue:T,renameInputRef:q,onRenameChange:N,onRenameCommit:Te,onRenameCancel:()=>D(null),onToggleDir:ge,onFileClick:Ee,onSendToChat:$e,onContextMenu:De})]}),v.jsx("div",{className:"px-3 py-1.5 border-t border-line text-[10px] text-fg-faint shrink-0",children:"Click to preview · Double-click external · Right-click for more"}),x&&v.jsx(bNt,{x:x.x,y:x.y,node:x.node,onClose:()=>S(null),onRename:()=>{ae(x.node),S(null)},onDelete:()=>{W(x.node),S(null)},onNewFile:()=>{O({parent:x.node.path,kind:"file"}),S(null)},onNewFolder:()=>{O({parent:x.node.path,kind:"folder"}),S(null)},onOpenExternal:()=>{window.api.files.openExternal(x.node.path),S(null)},onShowInFinder:()=>{window.api.files.showInFinder(x.node.path),S(null)},onCopyPath:()=>{var Je;(Je=navigator.clipboard)==null||Je.writeText(x.node.path),S(null)},onSendToChat:()=>{$e(x.node.path),S(null)}}),A&&v.jsx(gke,{title:`New ${A.kind}`,subtitle:`in ${yNt(A.parent)}`,onCancel:()=>{O(null),P("")},onConfirm:Ie,confirmLabel:"Create",confirmDisabled:!$.trim(),children:v.jsx("input",{ref:G,value:$,onChange:Je=>P(Je.target.value),onKeyDown:Je=>{Je.key==="Enter"&&Ie(),Je.key==="Escape"&&(O(null),P(""))},placeholder:A.kind==="file"?"filename.txt":"folder-name",className:"w-full px-3 py-2 rounded bg-bg-hi border border-line text-fg text-sm placeholder-fg-faint focus:outline-none focus:border-accent/50"})}),B&&v.jsx(gke,{title:`Delete ${B.isDirectory?"folder":"file"}`,subtitle:null,onCancel:()=>W(null),onConfirm:st,confirmLabel:"Delete",danger:!0,children:v.jsxs("p",{className:"text-sm text-fg-dim",children:["Move ",v.jsxs("span",{className:"text-fg font-medium",children:['"',B.name,'"']})," to the trash?",B.isDirectory&&v.jsx("span",{className:"block text-xs text-fg-faint mt-1",children:"All contents will be moved with it."})]})})]})}function D6e(s){const{nodes:e,depth:i,expanded:n,gitStatus:r,renaming:o,onContextMenu:a}=s;return v.jsx(v.Fragment,{children:e.map(l=>{const c=n.has(l.path),d=o===l.path,u=r[l.path],h=_Nt(l.name,l.isDirectory);return v.jsxs("div",{children:[v.jsxs("div",{className:"group flex items-center gap-1.5 py-0.5 pr-2 cursor-pointer transition-colors hover:bg-bg-hi",style:{paddingLeft:`${8+i*14}px`},onClick:()=>{d||(l.isDirectory?s.onToggleDir(l):s.onFileClick(l))},onDoubleClick:()=>{l.isDirectory||window.api.files.openExternal(l.path)},onContextMenu:f=>a(f,l),children:[l.isDirectory?v.jsx(CNt,{size:10,className:`shrink-0 text-fg-faint transition-transform ${c?"rotate-90":""}`}):v.jsx("span",{className:"w-[10px] shrink-0"}),l.isDirectory?c?v.jsx(wNt,{size:12,color:h}):v.jsx(T6e,{size:12,color:h}):v.jsx(xNt,{size:12,color:h}),d?v.jsx("input",{ref:s.renameInputRef,value:s.renameValue,onChange:f=>s.onRenameChange(f.target.value),onClick:f=>f.stopPropagation(),onBlur:s.onRenameCommit,onKeyDown:f=>{f.key==="Enter"&&s.onRenameCommit(),f.key==="Escape"&&s.onRenameCancel()},className:"flex-1 min-w-0 px-1 py-0 text-xs bg-bg border border-accent/40 rounded text-fg focus:outline-none"}):v.jsx("span",{className:`flex-1 truncate text-xs ${l.name.startsWith(".")?"text-fg-faint":"text-fg-dim"}`,children:l.name}),u&&v.jsx("span",{className:"shrink-0 text-[9px] font-bold px-1 rounded",style:{color:JX[u].color,backgroundColor:`${JX[u].color}20`},title:u,children:JX[u].label}),!l.isDirectory&&v.jsx("button",{onClick:f=>{f.stopPropagation(),s.onSendToChat(l.path)},title:"Send @path to active terminal",className:"opacity-0 group-hover:opacity-100 p-0.5 rounded text-fg-faint hover:text-accent hover:bg-bg transition-all shrink-0",children:v.jsx(TNt,{size:10})})]}),l.isDirectory&&c&&l.children&&v.jsx(D6e,{...s,nodes:l.children,depth:i+1})]},l.path)})})}function bNt(s){const{x:e,y:i,node:n}=s;return v.jsxs("div",{onMouseDown:r=>r.stopPropagation(),className:"fixed z-[300] w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1",style:{left:e,top:i},children:[!n.isDirectory&&v.jsx(Ew,{label:"Send to chat",onClick:s.onSendToChat}),v.jsx(Ew,{label:"Open in default app",onClick:s.onOpenExternal}),v.jsx(Ew,{label:"Reveal in OS",onClick:s.onShowInFinder}),v.jsx(eZ,{}),v.jsx(Ew,{label:"Copy path",onClick:s.onCopyPath}),v.jsx(Ew,{label:"Rename",onClick:s.onRename}),n.isDirectory&&v.jsxs(v.Fragment,{children:[v.jsx(eZ,{}),v.jsx(Ew,{label:"New file",onClick:s.onNewFile}),v.jsx(Ew,{label:"New folder",onClick:s.onNewFolder})]}),v.jsx(eZ,{}),v.jsx(Ew,{label:"Delete",onClick:s.onDelete,danger:!0})]})}function Ew({label:s,onClick:e,danger:i}){return v.jsx("button",{onClick:e,className:`w-full text-left px-3 py-1.5 hover:bg-bg-hi transition-colors ${i?"text-red-400":"text-fg-dim hover:text-fg"}`,children:s})}function eZ(){return v.jsx("div",{className:"my-1 border-t border-line"})}function gke(s){return v.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:e=>{e.target===e.currentTarget&&s.onCancel()},children:v.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[v.jsx("h3",{className:"text-sm font-medium text-fg mb-1",children:s.title}),s.subtitle&&v.jsx("p",{className:"text-[11px] text-fg-faint mb-3 truncate",children:s.subtitle}),v.jsx("div",{className:"mb-4",children:s.children}),v.jsxs("div",{className:"flex justify-end gap-2",children:[v.jsx("button",{onClick:s.onCancel,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded transition-colors",children:"Cancel"}),v.jsx("button",{onClick:s.onConfirm,disabled:!!s.confirmDisabled,className:`px-3 py-1 text-xs text-white rounded transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${s.danger?"bg-red-600 hover:bg-red-500":"bg-accent hover:bg-accent/90"}`,children:s.confirmLabel??"OK"})]})]})})}function yNt(s){return s.split("/").filter(Boolean).pop()||s}function N8(s,e,i){return s.map(n=>n.path===e?{...n,children:i}:n.children?{...n,children:N8(n.children,e,i)}:n)}function tv({size:s,children:e,className:i,color:n}){return v.jsx("svg",{width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:n||"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",className:i,children:e})}function T6e({size:s,className:e,color:i}){return v.jsx(tv,{size:s,className:e,color:i,children:v.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function wNt({size:s,className:e,color:i}){return v.jsx(tv,{size:s,className:e,color:i,children:v.jsx("path",{d:"M6 14l1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2"})})}function xNt({size:s,className:e,color:i}){return v.jsxs(tv,{size:s,className:e,color:i,children:[v.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),v.jsx("polyline",{points:"14 2 14 8 20 8"})]})}function CNt({size:s,className:e}){return v.jsx(tv,{size:s,className:e,children:v.jsx("polyline",{points:"9 18 15 12 9 6"})})}function SNt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("polyline",{points:"23 4 23 10 17 10"}),v.jsx("polyline",{points:"1 20 1 14 7 14"}),v.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function kNt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),v.jsx("polyline",{points:"14 2 14 8 20 8"}),v.jsx("line",{x1:"12",y1:"18",x2:"12",y2:"12"}),v.jsx("line",{x1:"9",y1:"15",x2:"15",y2:"15"})]})}function LNt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"}),v.jsx("line",{x1:"12",y1:"11",x2:"12",y2:"17"}),v.jsx("line",{x1:"9",y1:"14",x2:"15",y2:"14"})]})}function ENt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),v.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function DNt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("path",{d:"M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"}),v.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function TNt({size:s,className:e}){return v.jsxs(tv,{size:s,className:e,children:[v.jsx("line",{x1:"22",y1:"2",x2:"11",y2:"13"}),v.jsx("polygon",{points:"22 2 15 22 11 13 2 9 22 2"})]})}function INt(s,e={}){switch(s){case"ready":return e.isRecording?"Stop voice input":"Start voice input (local Whisper, offline)";case"idle":return"Microphone — speech model not started";case"loading":return`Microphone — loading speech model, ${typeof e.loadingPct=="number"?Math.round(e.loadingPct):0} percent`;case"error":return e.errorMessage?`Microphone — speech model error: ${e.errorMessage}. Activate to retry.`:"Microphone — speech model error. Activate to retry.";case"load-timeout":return"Microphone — model load timed out. Activate to retry.";case"permission-denied":return"Microphone — permission denied. Open OS settings.";case"unsupported":return"Microphone — voice input not supported in this build."}}const pke=s=>Symbol.iterator in s,mke=s=>"entries"in s,_ke=(s,e)=>{const i=s instanceof Map?s:new Map(s.entries()),n=e instanceof Map?e:new Map(e.entries());if(i.size!==n.size)return!1;for(const[r,o]of i)if(!n.has(r)||!Object.is(o,n.get(r)))return!1;return!0},NNt=(s,e)=>{const i=s[Symbol.iterator](),n=e[Symbol.iterator]();let r=i.next(),o=n.next();for(;!r.done&&!o.done;){if(!Object.is(r.value,o.value))return!1;r=i.next(),o=n.next()}return!!r.done&&!!o.done};function RNt(s,e){return Object.is(s,e)?!0:typeof s!="object"||s===null||typeof e!="object"||e===null||Object.getPrototypeOf(s)!==Object.getPrototypeOf(e)?!1:pke(s)&&pke(e)?mke(s)&&mke(e)?_ke(s,e):NNt(s,e):_ke({entries:()=>Object.entries(s)},{entries:()=>Object.entries(e)})}function I6e(s){const e=at.useRef(void 0);return i=>{const n=s(i);return RNt(e.current,n)?e.current:e.current=n}}let vke=0;const ANt=1e3;function MNt(s){const e=performance.now();e-vke<ANt||(vke=e,ti.debug("voice","mic.gate.click_rejected",{reason:s}))}function N6e(){const s=zi(d=>d.isRecording),e=zi(d=>d.error),i=zi(d=>d.loadingProgress),n=zi(I6e(pde)),r=()=>{const d=zi.getState(),{canRecord:u,reason:h}=pde(d);if(d.isRecording)return d.stopRecording();if(d.wizardArmed&&!d.wizardOpen){d.openWizard();return}if(h==="error"||h==="load-timeout"){d.resetAndRetryModel();return}if(!u)return MNt(h);const f=hn.getState().activeTabId;f&&d.startRecording(f)},o=INt(n.reason,{loadingPct:i,errorMessage:e,isRecording:s}),a=n.reason==="unsupported",l=!n.canRecord,c=n.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":n.reason==="error"||n.reason==="load-timeout"?"text-red-400 cursor-pointer":n.reason==="permission-denied"?"text-amber-400 cursor-pointer":n.reason==="idle"?"text-fg-faint cursor-pointer":n.reason==="unsupported"?"text-fg-faint cursor-not-allowed":s?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return v.jsx("button",{onClick:r,disabled:a,"aria-disabled":l,"aria-label":o,title:o,"data-testid":"mic-button","data-state":n.reason,className:`p-1.5 rounded transition-colors ${c}`,children:v.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[v.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),v.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),v.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),v.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function PNt(){const s=zi(i=>i.ttsEnabled),e=zi(i=>i.toggleTTS);return v.jsxs("button",{onClick:e,title:s?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${s?"text-accent":"text-fg-dim hover:text-fg"}`,children:[v.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[v.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s?v.jsxs(v.Fragment,{children:[v.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),v.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):v.jsxs(v.Fragment,{children:[v.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),v.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),v.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}const bke=[{key:"overview",label:"Home",icon:"home",hint:"Today's sessions + the 5-hour window"},{key:"terminal",label:"Terminal",icon:"terminal",hint:"Live Claude Code, in-app"},{key:"agent-view",label:"Agent-View",icon:"agent-view",liveKind:"agentView",hint:"Workshop scene of the active session"},{key:"subagents",label:"Subagents",icon:"hive",liveKind:"subagents",hint:"Sub-agents working in parallel"},{key:"scheduler",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Author PRDs + run them as claude -p jobs"},{key:"prompts",label:"Prompts",icon:"book",hint:"Click-to-insert prompt library"},{key:"tasks",label:"Tasks",icon:"tasks",liveKind:"tasks",hint:"Active to-dos across sessions"},{key:"history",label:"History",icon:"history",hint:"Every session, ever — resumable"},{key:"usage",label:"Usage",icon:"usage",hint:"Tokens, cost, sessions per day"},{key:"knowledge-graph",label:"Knowledge Graph",icon:"knowledge-graph",hint:"Distilled graph + Q&A over your prompt log"}],yke=[{key:"skills",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads"},{key:"plugins",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code"},{key:"mcp",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations"},{key:"hooks",label:"Hooks",icon:"hooks",hint:"Run scripts on session events"},{key:"keybindings",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override"},{key:"doc-editor",label:"Doc Editor",icon:"docs",hint:"Edit CLAUDE.md and friends"},{key:"memory",label:"Memory",icon:"memory",hint:"Workspace memory store"},{key:"projects",label:"Projects",icon:"projects",hint:"All known project folders"},{key:"system-prompt",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior"},{key:"permissions",label:"Permissions",icon:"permissions",hint:"Allow / deny rules"},{key:"settings",label:"Settings",icon:"settings",hint:"Theme, voice, billing window"},{key:"remote",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default"}],wke=[{key:"voice",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk"},{key:"dispatch",label:"Dispatch",icon:"orchestrator",hint:"Boss · Orchestrate · Race · Hives"},{key:"repoviz",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map"},{key:"search",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content"}],mde="sm.almanac.sidebarWidth",R6e=180,A6e=480,_de=252;function ONt(){try{const s=parseInt(localStorage.getItem(mde)??"",10);if(Number.isFinite(s))return Math.min(A6e,Math.max(R6e,s))}catch{}return _de}const M6e="sm.almanac.sidebarMode";function FNt(){try{return localStorage.getItem(M6e)==="files"?"files":"nav"}catch{return"nav"}}const P6e="sm.almanac.collapsedGroups";function BNt(){try{const s=localStorage.getItem(P6e);if(!s)return new Set;const e=JSON.parse(s);return Array.isArray(e)?new Set(e.filter(i=>i==="Workspace"||i==="Configure"||i==="Tools")):new Set}catch{return new Set}}function jNt(){const s=k8(o=>o.tabs),e=D1(o=>{var a;return(((a=o.snapshot)==null?void 0:a.jobs)??[]).some(l=>l.status==="running")}),[i,n]=z.useState(()=>Date.now());z.useEffect(()=>{const o=setInterval(()=>n(Date.now()),5e3);return()=>clearInterval(o)},[]);const r=Object.values(s);return{subagents:r.some(o=>o.agents.some(a=>i-a.at<6e4)),tasks:r.some(o=>o.todos.some(a=>a.status==="in_progress")),agentView:r.some(o=>o.lastEventAt>0&&i-o.lastEventAt<5e3),scheduler:e}}function $Nt({active:s,onNavigate:e,onNewSession:i,onOpenFile:n}){const[r,o]=z.useState(()=>FNt()),a=z.useCallback(x=>{o(x);try{localStorage.setItem(M6e,x)}catch{}},[]),[l,c]=z.useState(()=>BNt()),d=z.useCallback(x=>{c(S=>{const k=new Set(S);k.has(x)?k.delete(x):k.add(x);try{localStorage.setItem(P6e,JSON.stringify(Array.from(k)))}catch{}return k})},[]),u=hn(x=>x.tabs),h=hn(x=>x.activeTabId),f=u.find(x=>x.id===h)??null,g=jNt(),[p,_]=z.useState(()=>ONt()),m=z.useRef(p);m.current=p;const b=z.useCallback(x=>{x.preventDefault();const S=x.clientX,k=m.current;let D=k;const T=A=>{D=Math.min(A6e,Math.max(R6e,k+(A.clientX-S))),_(D)},N=()=>{window.removeEventListener("pointermove",T),window.removeEventListener("pointerup",N),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(mde,String(D))}catch{}};window.addEventListener("pointermove",T),window.addEventListener("pointerup",N),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),y=z.useCallback(()=>{_(_de);try{localStorage.setItem(mde,String(_de))}catch{}},[]);return v.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative",style:{width:p},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[v.jsx(WNt,{tab:f,onNewSession:i}),v.jsx("div",{className:"px-3.5 pt-3 pb-2 flex gap-1",children:["nav","files"].map(x=>v.jsx("button",{onClick:()=>a(x),"aria-pressed":r===x,className:`flex-1 py-1.5 rounded-md text-[12px] font-semibold tracking-[0.02em] transition-colors ${r===x?"bg-bg-hi text-fg border border-line":"text-fg-faint hover:text-fg-dim border border-transparent"}`,children:x==="nav"?"Navigate":"Files"},x))}),v.jsx("div",{className:"flex-1 min-h-0 overflow-auto px-2 pb-3",children:r==="nav"?v.jsxs(v.Fragment,{children:[v.jsx(tZ,{label:"Workspace",collapsed:l.has("Workspace"),count:bke.length,onToggle:()=>d("Workspace")}),!l.has("Workspace")&&bke.map(x=>v.jsx(xke,{item:x,active:s===x.key,live:x.liveKind?g[x.liveKind]:!1,onClick:()=>e(x.key)},x.key)),v.jsx(tZ,{label:"Configure",collapsed:l.has("Configure"),count:yke.length,onToggle:()=>d("Configure")}),!l.has("Configure")&&yke.map(x=>v.jsx(xke,{item:x,active:s===x.key,live:!1,onClick:()=>e(x.key)},x.key)),v.jsx(tZ,{label:"Tools",collapsed:l.has("Tools"),count:wke.length,onToggle:()=>d("Tools")}),!l.has("Tools")&&wke.map(x=>v.jsx(zNt,{tool:x,active:s===x.key,onClick:()=>e(x.key)},x.key))]}):v.jsx(UNt,{tab:f,onOpenFile:n})}),v.jsx(GNt,{}),v.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:b,onDoubleClick:y,className:"absolute top-0 right-0 h-full w-1.5 translate-x-1/2 z-10 cursor-col-resize hover:bg-accent/40 active:bg-accent/60 transition-colors"})]})}function WNt({tab:s,onNewSession:e}){const i=(s==null?void 0:s.label)??"no session",n=VNt((s==null?void 0:s.cwd)??null);return v.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[v.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),v.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[v.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),v.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(s==null?void 0:s.cwd)??"",children:i})]}),v.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:n?`⌥${n}`:s?s.cwd:"—"}),v.jsxs("div",{className:"mt-3 flex items-stretch gap-1.5",children:[v.jsxs("button",{onClick:e,"data-testid":"tour-new-session",className:"flex-1 px-3 py-1.5 rounded-md bg-bg-hi border border-line text-fg text-[12.5px] font-medium hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center gap-1.5",children:[v.jsx(wy,{name:"plus",size:13,stroke:1.8}),"New session"]}),v.jsx("div",{className:"flex items-center rounded-md bg-bg-hi border border-line",children:v.jsx(N6e,{})})]})]})}const J$=new Map,HNt=3e4;function VNt(s){const[e,i]=z.useState(()=>{var n;return s?((n=J$.get(s))==null?void 0:n.value)??null:null});return z.useEffect(()=>{if(!s){i(null);return}let n=!1;return(async()=>{const o=J$.get(s);if(o&&Date.now()-o.ts<HNt){n||i(o.value);return}try{const a=await window.api.app.gitBranch(s);if(n)return;J$.set(s,{value:a,ts:Date.now()}),i(a)}catch{if(n)return;J$.set(s,{value:null,ts:Date.now()}),i(null)}})(),()=>{n=!0}},[s]),e}function tZ({label:s,collapsed:e,count:i,onToggle:n}){return v.jsxs("button",{onClick:n,"aria-expanded":!e,title:e?`Expand ${s}`:`Collapse ${s}`,className:"group w-full flex items-center gap-1.5 px-3 pt-3.5 pb-1.5 font-serif italic text-[11px] font-bold tracking-[0.07em] uppercase text-fg-faint hover:text-fg-dim transition-colors text-left",children:[v.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:e?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),v.jsx("span",{className:"flex-1",children:s}),e&&v.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:i})]})}function xke({item:s,active:e,live:i,onClick:n}){return v.jsxs("button",{onClick:n,title:s.hint,className:`relative w-full flex items-center gap-3 px-3.5 py-[9px] rounded-[10px] text-left text-[14px] mb-0.5 transition-colors ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&v.jsx("span",{"aria-hidden":!0,className:"absolute -left-[10px] top-3 bottom-3 w-[3px] rounded-sm bg-accent"}),v.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:v.jsx(wy,{name:s.icon,size:17,stroke:1.6})}),v.jsx("span",{className:"flex-1 truncate",children:s.label}),i&&v.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"})]})}function zNt({tool:s,active:e,onClick:i}){return v.jsxs("button",{onClick:i,title:s.hint,className:`relative w-full flex items-center gap-3 px-3.5 py-[7px] rounded-[10px] text-left text-[13px] mb-0.5 transition-colors ${e?"bg-bg-hi text-fg font-semibold border border-line":"text-fg-dim hover:bg-bg-hi/50 hover:text-fg border border-transparent"}`,children:[e&&v.jsx("span",{"aria-hidden":!0,className:"absolute -left-[10px] top-2 bottom-2 w-[3px] rounded-sm bg-accent"}),v.jsx("span",{className:`inline-flex ${e?"text-accent":"text-fg-faint"}`,children:v.jsx(wy,{name:s.icon,size:15,stroke:1.6})}),v.jsx("span",{className:"flex-1 truncate",children:s.label})]})}function UNt({tab:s,onOpenFile:e}){return s?v.jsxs("div",{className:"pt-1",children:[v.jsx("div",{className:"px-3 pb-2 text-[11.5px] text-fg-faint font-mono truncate",title:s.cwd,children:qNt(s.cwd)}),v.jsx(vNt,{cwd:s.cwd,activeTabId:s.id,onPreviewFile:e})]}):v.jsx("div",{className:"px-3 py-6 text-center text-[12px] text-fg-faint",children:"No session selected."})}function qNt(s){const e="/home/";if(s.startsWith(e)){const i=s.slice(e.length).split("/").slice(1).join("/");return i?`~/${i}`:"~"}return s}function GNt(){const s=zi(a=>a.isRecording),e=hn(a=>a.tabs),i=hn(a=>a.activeTabId),n=e.find(a=>a.id===i)??null,[r,o]=z.useState(null);return z.useEffect(()=>{let a=!1;if(!(n!=null&&n.presetId)){o(null);return}return c6e(n.presetId).then(l=>{a||o((l==null?void 0:l.model)??null)}).catch(()=>{a||o(null)}),()=>{a=!0}},[n==null?void 0:n.presetId]),v.jsxs("div",{className:"px-3.5 py-2.5 border-t border-rule flex items-center gap-2 text-[11.5px] text-fg-dim font-mono",children:[v.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${s?"bg-red-500 animate-pulse":"bg-sage"}`,title:s?"recording":"idle"}),v.jsx("span",{className:"truncate",title:r??"",children:s?"recording…":r?`Claude · ${KNt(r)}`:"Claude Code"})]})}function KNt(s){var i,n,r,o,a,l;const e=s.toLowerCase();if(e.includes("opus")){const c=(n=(i=s.match(/(\d+[-.]?\d*)/))==null?void 0:i[1])==null?void 0:n.replace("-",".");return c?`Opus ${c}`:"Opus"}if(e.includes("sonnet")){const c=(o=(r=s.match(/(\d+[-.]?\d*)/))==null?void 0:r[1])==null?void 0:o.replace("-",".");return c?`Sonnet ${c}`:"Sonnet"}if(e.includes("haiku")){const c=(l=(a=s.match(/(\d+[-.]?\d*)/))==null?void 0:a[1])==null?void 0:l.replace("-",".");return c?`Haiku ${c}`:"Haiku"}return s}function YNt({onNavigate:s}){const e=hn(_=>_.tabs),i=hn(_=>_.activeTabId),n=e.find(_=>_.id===i)??null,r=KF(n),o=(r==null?void 0:r.lastEventAt)??0,a=WS(_=>_.data),[l,c]=z.useState(null),[,d]=z.useState(0);z.useEffect(()=>{const _=setInterval(()=>d(m=>m+1),6e4);return()=>clearInterval(_)},[]),z.useEffect(()=>{let _=!1;if(!(n!=null&&n.cwd)){c(null);return}return window.api.app.gitBranch(n.cwd).then(m=>{_||c(m)}).catch(()=>{_||c(null)}),()=>{_=!0}},[n==null?void 0:n.cwd]);const u=XF(a),h=(u==null?void 0:u.usage.five_hour)??null,f=h?Math.round(h.utilization):null,g=(a==null?void 0:a.kind)==="ok"||(a==null?void 0:a.kind)==="ok-stale",p=o>0?XNt(Date.now()-o):"—";return v.jsxs("div",{className:"h-[30px] shrink-0 bg-bg-elev border-t border-line flex items-center gap-4 px-[18px] font-mono text-[11.5px] text-fg-dim","data-testid":"tour-statusbar",children:[v.jsxs("button",{onClick:()=>s==null?void 0:s("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:g?"Connected to Anthropic":"Disconnected",children:[v.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${g?"bg-sage":"bg-fg-faint"}`}),v.jsx("span",{children:g?"connected":"offline"})]}),v.jsx("button",{onClick:()=>s==null?void 0:s("usage"),className:"hover:text-fg transition-colors",title:"Open Usage",children:f!=null?`${f}% of 5h window used`:"5h —"}),n&&v.jsxs("span",{className:"text-fg-faint",title:n.cwd,children:[n.label,l&&v.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",l]})]}),v.jsxs("span",{className:"text-fg-faint",children:["last activity: ",v.jsx("span",{className:"text-fg-dim",children:p})]}),v.jsx("span",{className:"flex-1"}),v.jsxs("span",{className:"text-fg-faint",children:["v","0.21.1"]})]})}function XNt(s){const e=Math.max(0,Math.floor(s/1e3));if(e<60)return`${e}s ago`;const i=Math.floor(e/60);return i<60?`${i}m ago`:`${Math.floor(i/60)}h ago`}var iZ={exports:{}},Cke;function ZNt(){return Cke||(Cke=1,(function(s,e){(function(i,n){s.exports=n()})(globalThis,(()=>(()=>{var i={4567:function(a,l,c){var d=this&&this.__decorate||function(y,x,S,k){var D,T=arguments.length,N=T<3?x:k===null?k=Object.getOwnPropertyDescriptor(x,S):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")N=Reflect.decorate(y,x,S,k);else for(var A=y.length-1;A>=0;A--)(D=y[A])&&(N=(T<3?D(N):T>3?D(x,S,N):D(x,S))||N);return T>3&&N&&Object.defineProperty(x,S,N),N},u=this&&this.__param||function(y,x){return function(S,k){x(S,k,y)}};Object.defineProperty(l,"__esModule",{value:!0}),l.AccessibilityManager=void 0;const h=c(9042),f=c(9924),g=c(844),p=c(4725),_=c(2585),m=c(3656);let b=l.AccessibilityManager=class extends g.Disposable{constructor(y,x,S,k){super(),this._terminal=y,this._coreBrowserService=S,this._renderService=k,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let D=0;D<this._terminal.rows;D++)this._rowElements[D]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[D]);if(this._topBoundaryFocusListener=D=>this._handleBoundaryFocus(D,0),this._bottomBoundaryFocusListener=D=>this._handleBoundaryFocus(D,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new f.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((D=>this._handleResize(D.rows)))),this.register(this._terminal.onRender((D=>this._refreshRows(D.start,D.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((D=>this._handleChar(D)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
3812
3812
|
`)))),this.register(this._terminal.onA11yTab((D=>this._handleTab(D)))),this.register(this._terminal.onKey((D=>this._handleKey(D.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,m.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,g.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(y){for(let x=0;x<y;x++)this._handleChar(" ")}_handleChar(y){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==y&&(this._charsToAnnounce+=y):this._charsToAnnounce+=y,y===`
|
|
3813
3813
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=h.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(y){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(y)||this._charsToConsume.push(y)}_refreshRows(y,x){this._liveRegionDebouncer.refresh(y,x,this._terminal.rows)}_renderRows(y,x){const S=this._terminal.buffer,k=S.lines.length.toString();for(let D=y;D<=x;D++){const T=S.lines.get(S.ydisp+D),N=[],A=(T==null?void 0:T.translateToString(!0,void 0,void 0,N))||"",O=(S.ydisp+D+1).toString(),$=this._rowElements[D];$&&(A.length===0?($.innerText=" ",this._rowColumns.set($,[0,1])):($.textContent=A,this._rowColumns.set($,N)),$.setAttribute("aria-posinset",O),$.setAttribute("aria-setsize",k))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(y,x){const S=y.target,k=this._rowElements[x===0?1:this._rowElements.length-2];if(S.getAttribute("aria-posinset")===(x===0?"1":`${this._terminal.buffer.lines.length}`)||y.relatedTarget!==k)return;let D,T;if(x===0?(D=S,T=this._rowElements.pop(),this._rowContainer.removeChild(T)):(D=this._rowElements.shift(),T=S,this._rowContainer.removeChild(D)),D.removeEventListener("focus",this._topBoundaryFocusListener),T.removeEventListener("focus",this._bottomBoundaryFocusListener),x===0){const N=this._createAccessibilityTreeNode();this._rowElements.unshift(N),this._rowContainer.insertAdjacentElement("afterbegin",N)}else{const N=this._createAccessibilityTreeNode();this._rowElements.push(N),this._rowContainer.appendChild(N)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(x===0?-1:1),this._rowElements[x===0?1:this._rowElements.length-2].focus(),y.preventDefault(),y.stopImmediatePropagation()}_handleSelectionChange(){var A;if(this._rowElements.length===0)return;const y=document.getSelection();if(!y)return;if(y.isCollapsed)return void(this._rowContainer.contains(y.anchorNode)&&this._terminal.clearSelection());if(!y.anchorNode||!y.focusNode)return void console.error("anchorNode and/or focusNode are null");let x={node:y.anchorNode,offset:y.anchorOffset},S={node:y.focusNode,offset:y.focusOffset};if((x.node.compareDocumentPosition(S.node)&Node.DOCUMENT_POSITION_PRECEDING||x.node===S.node&&x.offset>S.offset)&&([x,S]=[S,x]),x.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(x={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(x.node))return;const k=this._rowElements.slice(-1)[0];if(S.node.compareDocumentPosition(k)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(S={node:k,offset:((A=k.textContent)==null?void 0:A.length)??0}),!this._rowContainer.contains(S.node))return;const D=({node:O,offset:$})=>{const P=O instanceof Text?O.parentNode:O;let B=parseInt(P==null?void 0:P.getAttribute("aria-posinset"),10)-1;if(isNaN(B))return console.warn("row is invalid. Race condition?"),null;const W=this._rowColumns.get(P);if(!W)return console.warn("columns is null. Race condition?"),null;let q=$<W.length?W[$]:W.slice(-1)[0]+1;return q>=this._terminal.cols&&(++B,q=0),{row:B,column:q}},T=D(x),N=D(S);if(T&&N){if(T.row>N.row||T.row===N.row&&T.column>=N.column)throw new Error("invalid range");this._terminal.select(T.column,T.row,(N.row-T.row)*this._terminal.cols-T.column+N.column)}}_handleResize(y){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let x=this._rowContainer.children.length;x<this._terminal.rows;x++)this._rowElements[x]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[x]);for(;this._rowElements.length>y;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const y=this._coreBrowserService.mainDocument.createElement("div");return y.setAttribute("role","listitem"),y.tabIndex=-1,this._refreshRowDimensions(y),y}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let y=0;y<this._terminal.rows;y++)this._refreshRowDimensions(this._rowElements[y])}}_refreshRowDimensions(y){y.style.height=`${this._renderService.dimensions.css.cell.height}px`}};l.AccessibilityManager=b=d([u(1,_.IInstantiationService),u(2,p.ICoreBrowserService),u(3,p.IRenderService)],b)},3614:(a,l)=>{function c(f){return f.replace(/\r?\n/g,"\r")}function d(f,g){return g?"\x1B[200~"+f+"\x1B[201~":f}function u(f,g,p,_){f=d(f=c(f),p.decPrivateModes.bracketedPasteMode&&_.rawOptions.ignoreBracketedPasteMode!==!0),p.triggerDataEvent(f,!0),g.value=""}function h(f,g,p){const _=p.getBoundingClientRect(),m=f.clientX-_.left-10,b=f.clientY-_.top-10;g.style.width="20px",g.style.height="20px",g.style.left=`${m}px`,g.style.top=`${b}px`,g.style.zIndex="1000",g.focus()}Object.defineProperty(l,"__esModule",{value:!0}),l.rightClickHandler=l.moveTextAreaUnderMouseCursor=l.paste=l.handlePasteEvent=l.copyHandler=l.bracketTextForPaste=l.prepareTextForTerminal=void 0,l.prepareTextForTerminal=c,l.bracketTextForPaste=d,l.copyHandler=function(f,g){f.clipboardData&&f.clipboardData.setData("text/plain",g.selectionText),f.preventDefault()},l.handlePasteEvent=function(f,g,p,_){f.stopPropagation(),f.clipboardData&&u(f.clipboardData.getData("text/plain"),g,p,_)},l.paste=u,l.moveTextAreaUnderMouseCursor=h,l.rightClickHandler=function(f,g,p,_,m){h(f,g,p),m&&_.rightClickSelect(f),g.value=_.selectionText,g.select()}},7239:(a,l,c)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.ColorContrastCache=void 0;const d=c(1505);l.ColorContrastCache=class{constructor(){this._color=new d.TwoKeyMap,this._css=new d.TwoKeyMap}setCss(u,h,f){this._css.set(u,h,f)}getCss(u,h){return this._css.get(u,h)}setColor(u,h,f){this._color.set(u,h,f)}getColor(u,h){return this._color.get(u,h)}clear(){this._color.clear(),this._css.clear()}}},3656:(a,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.addDisposableDomListener=void 0,l.addDisposableDomListener=function(c,d,u,h){c.addEventListener(d,u,h);let f=!1;return{dispose:()=>{f||(f=!0,c.removeEventListener(d,u,h))}}}},3551:function(a,l,c){var d=this&&this.__decorate||function(b,y,x,S){var k,D=arguments.length,T=D<3?y:S===null?S=Object.getOwnPropertyDescriptor(y,x):S;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(b,y,x,S);else for(var N=b.length-1;N>=0;N--)(k=b[N])&&(T=(D<3?k(T):D>3?k(y,x,T):k(y,x))||T);return D>3&&T&&Object.defineProperty(y,x,T),T},u=this&&this.__param||function(b,y){return function(x,S){y(x,S,b)}};Object.defineProperty(l,"__esModule",{value:!0}),l.Linkifier=void 0;const h=c(3656),f=c(8460),g=c(844),p=c(2585),_=c(4725);let m=l.Linkifier=class extends g.Disposable{get currentLink(){return this._currentLink}constructor(b,y,x,S,k){super(),this._element=b,this._mouseService=y,this._renderService=x,this._bufferService=S,this._linkProviderService=k,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new f.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new f.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,g.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,g.toDisposable)((()=>{var D;this._lastMouseEvent=void 0,(D=this._activeProviderReplies)==null||D.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,h.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,h.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,h.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,h.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(b){this._lastMouseEvent=b;const y=this._positionFromMouseEvent(b,this._element,this._mouseService);if(!y)return;this._isMouseOut=!1;const x=b.composedPath();for(let S=0;S<x.length;S++){const k=x[S];if(k.classList.contains("xterm"))break;if(k.classList.contains("xterm-hover"))return}this._lastBufferCell&&y.x===this._lastBufferCell.x&&y.y===this._lastBufferCell.y||(this._handleHover(y),this._lastBufferCell=y)}_handleHover(b){if(this._activeLine!==b.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(b,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,b)||(this._clearCurrentLink(),this._askForLink(b,!0))}_askForLink(b,y){var S,k;this._activeProviderReplies&&y||((S=this._activeProviderReplies)==null||S.forEach((D=>{D==null||D.forEach((T=>{T.link.dispose&&T.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=b.y);let x=!1;for(const[D,T]of this._linkProviderService.linkProviders.entries())y?(k=this._activeProviderReplies)!=null&&k.get(D)&&(x=this._checkLinkProviderResult(D,b,x)):T.provideLinks(b.y,(N=>{var O,$;if(this._isMouseOut)return;const A=N==null?void 0:N.map((P=>({link:P})));(O=this._activeProviderReplies)==null||O.set(D,A),x=this._checkLinkProviderResult(D,b,x),(($=this._activeProviderReplies)==null?void 0:$.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(b.y,this._activeProviderReplies)}))}_removeIntersectingLinks(b,y){const x=new Set;for(let S=0;S<y.size;S++){const k=y.get(S);if(k)for(let D=0;D<k.length;D++){const T=k[D],N=T.link.range.start.y<b?0:T.link.range.start.x,A=T.link.range.end.y>b?this._bufferService.cols:T.link.range.end.x;for(let O=N;O<=A;O++){if(x.has(O)){k.splice(D--,1);break}x.add(O)}}}}_checkLinkProviderResult(b,y,x){var D;if(!this._activeProviderReplies)return x;const S=this._activeProviderReplies.get(b);let k=!1;for(let T=0;T<b;T++)this._activeProviderReplies.has(T)&&!this._activeProviderReplies.get(T)||(k=!0);if(!k&&S){const T=S.find((N=>this._linkAtPosition(N.link,y)));T&&(x=!0,this._handleNewLink(T))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!x)for(let T=0;T<this._activeProviderReplies.size;T++){const N=(D=this._activeProviderReplies.get(T))==null?void 0:D.find((A=>this._linkAtPosition(A.link,y)));if(N){x=!0,this._handleNewLink(N);break}}return x}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(b){if(!this._currentLink)return;const y=this._positionFromMouseEvent(b,this._element,this._mouseService);y&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,y)&&this._currentLink.link.activate(b,this._currentLink.link.text)}_clearCurrentLink(b,y){this._currentLink&&this._lastMouseEvent&&(!b||!y||this._currentLink.link.range.start.y>=b&&this._currentLink.link.range.end.y<=y)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,g.disposeArray)(this._linkCacheDisposables))}_handleNewLink(b){if(!this._lastMouseEvent)return;const y=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);y&&this._linkAtPosition(b.link,y)&&(this._currentLink=b,this._currentLink.state={decorations:{underline:b.link.decorations===void 0||b.link.decorations.underline,pointerCursor:b.link.decorations===void 0||b.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,b.link,this._lastMouseEvent),b.link.decorations={},Object.defineProperties(b.link.decorations,{pointerCursor:{get:()=>{var x,S;return(S=(x=this._currentLink)==null?void 0:x.state)==null?void 0:S.decorations.pointerCursor},set:x=>{var S;(S=this._currentLink)!=null&&S.state&&this._currentLink.state.decorations.pointerCursor!==x&&(this._currentLink.state.decorations.pointerCursor=x,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",x))}},underline:{get:()=>{var x,S;return(S=(x=this._currentLink)==null?void 0:x.state)==null?void 0:S.decorations.underline},set:x=>{var S,k,D;(S=this._currentLink)!=null&&S.state&&((D=(k=this._currentLink)==null?void 0:k.state)==null?void 0:D.decorations.underline)!==x&&(this._currentLink.state.decorations.underline=x,this._currentLink.state.isHovered&&this._fireUnderlineEvent(b.link,x))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((x=>{if(!this._currentLink)return;const S=x.start===0?0:x.start+1+this._bufferService.buffer.ydisp,k=this._bufferService.buffer.ydisp+1+x.end;if(this._currentLink.link.range.start.y>=S&&this._currentLink.link.range.end.y<=k&&(this._clearCurrentLink(S,k),this._lastMouseEvent)){const D=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);D&&this._askForLink(D,!1)}}))))}_linkHover(b,y,x){var S;(S=this._currentLink)!=null&&S.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(y,!0),this._currentLink.state.decorations.pointerCursor&&b.classList.add("xterm-cursor-pointer")),y.hover&&y.hover(x,y.text)}_fireUnderlineEvent(b,y){const x=b.range,S=this._bufferService.buffer.ydisp,k=this._createLinkUnderlineEvent(x.start.x-1,x.start.y-S-1,x.end.x,x.end.y-S-1,void 0);(y?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(k)}_linkLeave(b,y,x){var S;(S=this._currentLink)!=null&&S.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(y,!1),this._currentLink.state.decorations.pointerCursor&&b.classList.remove("xterm-cursor-pointer")),y.leave&&y.leave(x,y.text)}_linkAtPosition(b,y){const x=b.range.start.y*this._bufferService.cols+b.range.start.x,S=b.range.end.y*this._bufferService.cols+b.range.end.x,k=y.y*this._bufferService.cols+y.x;return x<=k&&k<=S}_positionFromMouseEvent(b,y,x){const S=x.getCoords(b,y,this._bufferService.cols,this._bufferService.rows);if(S)return{x:S[0],y:S[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(b,y,x,S,k){return{x1:b,y1:y,x2:x,y2:S,cols:this._bufferService.cols,fg:k}}};l.Linkifier=m=d([u(1,_.IMouseService),u(2,_.IRenderService),u(3,p.IBufferService),u(4,_.ILinkProviderService)],m)},9042:(a,l)=>{Object.defineProperty(l,"__esModule",{value:!0}),l.tooMuchOutput=l.promptLabel=void 0,l.promptLabel="Terminal input",l.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(a,l,c){var d=this&&this.__decorate||function(_,m,b,y){var x,S=arguments.length,k=S<3?m:y===null?y=Object.getOwnPropertyDescriptor(m,b):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(_,m,b,y);else for(var D=_.length-1;D>=0;D--)(x=_[D])&&(k=(S<3?x(k):S>3?x(m,b,k):x(m,b))||k);return S>3&&k&&Object.defineProperty(m,b,k),k},u=this&&this.__param||function(_,m){return function(b,y){m(b,y,_)}};Object.defineProperty(l,"__esModule",{value:!0}),l.OscLinkProvider=void 0;const h=c(511),f=c(2585);let g=l.OscLinkProvider=class{constructor(_,m,b){this._bufferService=_,this._optionsService=m,this._oscLinkService=b}provideLinks(_,m){var A;const b=this._bufferService.buffer.lines.get(_-1);if(!b)return void m(void 0);const y=[],x=this._optionsService.rawOptions.linkHandler,S=new h.CellData,k=b.getTrimmedLength();let D=-1,T=-1,N=!1;for(let O=0;O<k;O++)if(T!==-1||b.hasContent(O)){if(b.loadCell(O,S),S.hasExtendedAttrs()&&S.extended.urlId){if(T===-1){T=O,D=S.extended.urlId;continue}N=S.extended.urlId!==D}else T!==-1&&(N=!0);if(N||T!==-1&&O===k-1){const $=(A=this._oscLinkService.getLinkData(D))==null?void 0:A.uri;if($){const P={start:{x:T+1,y:_},end:{x:O+(N||O!==k-1?0:1),y:_}};let B=!1;if(!(x!=null&&x.allowNonHttpProtocols))try{const W=new URL($);["http:","https:"].includes(W.protocol)||(B=!0)}catch{B=!0}B||y.push({text:$,range:P,activate:(W,q)=>x?x.activate(W,q,P):p(0,q),hover:(W,q)=>{var G;return(G=x==null?void 0:x.hover)==null?void 0:G.call(x,W,q,P)},leave:(W,q)=>{var G;return(G=x==null?void 0:x.leave)==null?void 0:G.call(x,W,q,P)}})}N=!1,S.hasExtendedAttrs()&&S.extended.urlId?(T=O,D=S.extended.urlId):(T=-1,D=-1)}}m(y)}};function p(_,m){if(confirm(`Do you want to navigate to ${m}?
|
|
3814
3814
|
|
|
@@ -4410,7 +4410,7 @@ Invoke the \`security-review\` skill on the currently staged diff. Walk OWASP To
|
|
|
4410
4410
|
`,tni="---\nid: security/secret-credential-scan\ntitle: Secret + credential scan with remediation plan\ncategory: Security\nsendMode: auto-fire\ndescription: Greps the tree for hardcoded secrets, checks git history, and orders rotate → redact → gitignore.\n---\nGrep the working tree for hardcoded secrets — API keys, OAuth tokens, JWTs, private keys, database URLs with embedded passwords, and webhook signing secrets. Use both pattern matching (e.g., `sk-`, `xoxb-`, `AKIA`, `-----BEGIN`, `Bearer `) and entropy heuristics on string literals over 20 chars. For each finding report file:line, the secret type, whether it is in tracked git history (`git log -S`), and a remediation order: rotate first, then redact, then add to `.gitignore`/secret manager. Do not print the secret value in clear — show a masked prefix only.\n",ini=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,nni=["id","title","category","sendMode","description"];function ZHe(s){const e=s.match(ini);if(!e)return console.error("[promptFrontmatter] no frontmatter block found"),null;const i=e[1],n=(e[2]??"").trim(),r={};for(const a of i.split(/\r?\n/)){const l=a.indexOf(":");if(l<0||a.startsWith(" ")||a.startsWith(" "))continue;const c=a.slice(0,l).trim(),d=a.slice(l+1).trim();c&&(r[c]=d)}for(const a of nni)if(!r[a])return console.error(`[promptFrontmatter] missing required key "${a}" in: ${s.slice(0,120).replace(/\n/g,"\\n")}`),null;const o=r.sendMode==="auto-fire"?"auto-fire":"paste";return{id:r.id,title:r.title,category:r.category,sendMode:o,description:r.description,body:n}}const sni=Object.assign({"../../seed/prompts/code-review/ac-coverage-check.md":dii,"../../seed/prompts/code-review/correctness-only.md":uii,"../../seed/prompts/code-review/full-spectrum-high.md":hii,"../../seed/prompts/code-review/hallucination-check.md":fii,"../../seed/prompts/code-review/public-api-compat.md":gii,"../../seed/prompts/code-review/readability-naming.md":pii,"../../seed/prompts/debugging/bug-as-failing-test.md":mii,"../../seed/prompts/debugging/git-bisect-regression.md":_ii,"../../seed/prompts/debugging/instrument-intermittent-bug.md":vii,"../../seed/prompts/debugging/localize-pipeline-failure.md":bii,"../../seed/prompts/debugging/reproduce-then-diagnose.md":yii,"../../seed/prompts/documentation/adr-from-change.md":wii,"../../seed/prompts/documentation/module-readme.md":xii,"../../seed/prompts/documentation/onboarding-plan.md":Cii,"../../seed/prompts/documentation/refresh-claude-md.md":Sii,"../../seed/prompts/documentation/tsdoc-public-exports.md":kii,"../../seed/prompts/git-pr/conventional-commit.md":Lii,"../../seed/prompts/git-pr/draft-pr-title-body.md":Eii,"../../seed/prompts/git-pr/pre-commit-safety-sweep.md":Dii,"../../seed/prompts/git-pr/release-notes-block.md":Tii,"../../seed/prompts/git-pr/split-large-pr.md":Iii,"../../seed/prompts/performance/bundle-startup-audit.md":Nii,"../../seed/prompts/performance/complexity-audit.md":Rii,"../../seed/prompts/performance/cpu-profile-hot-path.md":Aii,"../../seed/prompts/performance/db-query-plan-review.md":Mii,"../../seed/prompts/performance/memory-leak-hunt.md":Pii,"../../seed/prompts/qa/api-contract-tests.md":Oii,"../../seed/prompts/qa/e2e-critical-path.md":Fii,"../../seed/prompts/qa/failing-test-for-bug.md":Bii,"../../seed/prompts/qa/find-missing-test-coverage.md":jii,"../../seed/prompts/qa/stabilize-flaky-test.md":$ii,"../../seed/prompts/qa/tdd-red-first.md":Wii,"../../seed/prompts/qa/visual-regression-review.md":Hii,"../../seed/prompts/qa/wcag-axe-scan.md":Vii,"../../seed/prompts/refactoring/dead-code-sweep.md":zii,"../../seed/prompts/refactoring/extract-duplicated-pattern.md":Uii,"../../seed/prompts/refactoring/modernize-legacy-file.md":qii,"../../seed/prompts/refactoring/reduce-cyclomatic-complexity.md":Gii,"../../seed/prompts/refactoring/tighten-module-boundaries.md":Kii,"../../seed/prompts/security/authz-audit.md":Yii,"../../seed/prompts/security/crypto-correctness.md":Xii,"../../seed/prompts/security/cwe-top-25-hunt.md":Zii,"../../seed/prompts/security/dependency-audit.md":Qii,"../../seed/prompts/security/ipc-boundary-hardening.md":Jii,"../../seed/prompts/security/owasp-top-10-staged-diff.md":eni,"../../seed/prompts/security/secret-credential-scan.md":tni});function rni(){const s=[];for(const[,e]of Object.entries(sni)){const i=ZHe(e);i&&s.push(i)}return s}const _b=rni();let R6=null;async function QHe(){return R6||(R6=await window.api.app.homeDir(),R6)}function JHe(s,e){return`${s}/.claude/session-manager/prompts/${e}.md`}function oni(s,e){return["---",`id: ${s.id}`,`title: ${s.title}`,`category: ${s.category}`,`sendMode: ${s.sendMode}`,`description: ${s.description}`,"---",e].join(`
|
|
4411
4411
|
`)}async function Ate(s){const e=_b.find(i=>i.id===s);if(!e)throw new Error(`[promptsStore] unknown prompt id: ${s}`);try{const i=await QHe(),n=JHe(i,s),r=await window.api.config.readText(n);if(r.exists&&r.text){const o=ZHe(r.text);if(o)return o}}catch{}return e}async function eVe(s,e){const i=_b.find(o=>o.id===s);if(!i)throw new Error(`[promptsStore] unknown prompt id: ${s}`);const n=await QHe(),r=JHe(n,s);await window.api.config.writeText(r,oni(i,e))}async function ani(s){const e=_b.find(i=>i.id===s);if(!e)throw new Error(`[promptsStore] unknown prompt id: ${s}`);await eVe(s,e.body)}function lni({prompt:s,open:e,activeTabId:i,onClose:n}){const[r,o]=z.useState(s.body),[a,l]=z.useState(s.sendMode),[c,d]=z.useState(s.id);s.id!==c&&(d(s.id),o(s.body),l(s.sendMode));function u(){if(!i)return;const h=a==="auto-fire"?r+`
|
|
4412
4412
|
`:r;window.api.pty.write({tabId:i,data:h}),n(),Kt.info(`Sent to terminal (${a})`)}return v.jsxs(Og,{open:e,onClose:n,title:`Tweak: ${s.title}`,size:"lg",children:[v.jsx("textarea",{value:r,onChange:h=>o(h.target.value),rows:12,className:"w-full bg-bg border border-line rounded px-3 py-2 text-xs font-mono text-fg resize-y focus:outline-none focus:border-accent/60","aria-label":"Prompt body"}),v.jsxs("div",{className:"mt-3 flex items-center gap-4 text-xs text-fg-dim",children:[v.jsx("span",{className:"font-medium text-fg",children:"Send mode:"}),["paste","auto-fire"].map(h=>v.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[v.jsx("input",{type:"radio",name:"sendMode",value:h,checked:a===h,onChange:()=>l(h),className:"accent-accent"}),v.jsx("span",{className:a===h?"text-fg":"",children:h})]},h)),a==="paste"&&v.jsx("span",{className:"text-fg-faint italic",children:"— you hit Enter to submit"}),a==="auto-fire"&&v.jsx("span",{className:"text-fg-faint italic",children:"— submits immediately"})]}),v.jsxs("div",{className:"mt-4 flex items-center justify-end gap-3",children:[v.jsx("button",{onClick:n,className:"text-xs text-fg-dim hover:text-fg transition-colors",children:"Cancel"}),v.jsx("button",{onClick:u,disabled:!i,title:i?void 0:"Open a terminal session first",className:"px-4 py-1.5 rounded bg-accent text-white text-xs font-medium hover:bg-accent/80 transition-colors disabled:opacity-40 disabled:cursor-not-allowed",children:"Send to terminal"})]})]})}const vAe=["Security","QA","Performance","Code Review","Debugging","Refactoring","Documentation","Git / PR"],cni={Security:"bg-red-500/10 text-red-400 border-red-500/20",QA:"bg-green-500/10 text-green-400 border-green-500/20",Performance:"bg-orange-500/10 text-orange-400 border-orange-500/20","Code Review":"bg-blue-500/10 text-blue-400 border-blue-500/20",Debugging:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",Refactoring:"bg-purple-500/10 text-purple-400 border-purple-500/20",Documentation:"bg-cyan-500/10 text-cyan-400 border-cyan-500/20","Git / PR":"bg-pink-500/10 text-pink-400 border-pink-500/20"},dni={paste:"bg-fg-faint/10 text-fg-faint border-fg-faint/20","auto-fire":"bg-accent/10 text-accent border-accent/20"};function uni(){const[s,e]=z.useState(""),[i,n]=z.useState(()=>{var P;return((P=_b[0])==null?void 0:P.id)??null}),[r,o]=z.useState(!1),[a,l]=z.useState(!1),[c,d]=z.useState(null),[u,h]=z.useState(!1),[f,g]=z.useState(""),[p,_]=z.useState(!1),[m,b]=z.useState(!1),[y,x]=z.useState(null),S=hn(P=>P.activeTabId);z.useEffect(()=>{if(!i){d(null);return}let P=!1;return h(!0),Ate(i).then(B=>{P||(d(B),h(!1))}).catch(()=>{if(!P){const B=_b.find(W=>W.id===i)??null;d(B),h(!1)}}),()=>{P=!0}},[i]),z.useEffect(()=>{a&&c&&(g(c.body),_(!1),x(null))},[a,c]);const k=z.useMemo(()=>{var P;return((P=_b.find(B=>B.id===i))==null?void 0:P.body)??null},[i]),D=c!==null&&k!==null&&c.body!==k,T=z.useMemo(()=>{const P=s.toLowerCase();return vAe.map(B=>({category:B,items:_b.filter(W=>W.category===B&&(!P||W.title.toLowerCase().includes(P)||W.description.toLowerCase().includes(P)))})).filter(B=>B.items.length>0)},[s]),N=z.useCallback(P=>{P!==i&&(n(P),l(!1),_(!1),x(null))},[i]);async function A(){if(i){b(!0),x(null);try{await eVe(i,f);const P=await Ate(i);d(P),_(!1),l(!1)}catch(P){x(P instanceof Error?P.message:"save failed")}finally{b(!1)}}}async function O(){if(i){b(!0),x(null);try{await ani(i);const P=await Ate(i);d(P),l(!1),_(!1)}catch(P){x(P instanceof Error?P.message:"reset failed")}finally{b(!1)}}}const $=i?_b.find(P=>P.id===i)??null:null;return v.jsxs(zr,{toolbar:v.jsxs("span",{className:"text-fg-faint",children:[_b.length," prompts across ",vAe.length," categories"]}),footer:a&&i?v.jsx($1,{dirty:p,busy:m,parseError:y,lastSavedAt:null,onSave:A,onRevert:()=>{g((c==null?void 0:c.body)??($==null?void 0:$.body)??""),_(!1),x(null)}}):null,children:[v.jsx(sE,{sidebarWidth:"17rem",sidebar:v.jsxs("div",{className:"py-1",children:[v.jsx("div",{className:"px-2 pb-2 pt-1",children:v.jsx("input",{value:s,onChange:P=>e(P.target.value),placeholder:"filter…",className:"w-full bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"})}),T.length===0?v.jsx("div",{className:"px-3 py-2 text-xs text-fg-faint italic",children:"no matches"}):T.map(({category:P,items:B})=>v.jsxs("div",{className:"mb-2",children:[v.jsx("div",{className:"px-3 py-1 text-[10.5px] uppercase tracking-wider text-fg-faint font-semibold",children:P}),B.map(W=>v.jsx("button",{onClick:()=>N(W.id),title:W.description,className:`w-full px-3 py-1.5 text-xs text-left truncate transition-colors ${i===W.id?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi/50"}`,children:W.title},W.id))]},P))]}),detail:u||!c||!$?v.jsx(Ui,{title:u?"loading…":"select a prompt"}):a?v.jsx(fni,{draft:f,onChange:P=>{g(P),_(!0)},onCancel:()=>{l(!1),_(!1)}}):v.jsx(hni,{effective:c,seed:$,isCustomized:D,activeTabId:S,onUsePrompt:()=>o(!0),onEdit:()=>l(!0),onReset:O})}),r&&c&&v.jsx(lni,{prompt:c,open:r,activeTabId:S,onClose:()=>o(!1)},c.id)]})}function hni({effective:s,isCustomized:e,activeTabId:i,onUsePrompt:n,onEdit:r,onReset:o}){const a=cni[s.category]??"bg-fg-faint/10 text-fg-faint border-fg-faint/20",l=dni[s.sendMode];return v.jsxs("div",{className:"p-4 flex flex-col gap-3",children:[v.jsxs("div",{className:"flex items-start gap-2 flex-wrap",children:[v.jsx("h2",{className:"text-sm font-semibold text-fg flex-1 min-w-0",children:s.title}),v.jsx("span",{className:`shrink-0 text-[10.5px] px-1.5 py-0.5 rounded border font-mono ${a}`,children:s.category}),v.jsx("span",{className:`shrink-0 text-[10.5px] px-1.5 py-0.5 rounded border font-mono ${l}`,children:s.sendMode})]}),v.jsx("p",{className:"text-xs text-fg-dim",children:s.description}),v.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[12.5px] bg-bg-elev border border-line rounded p-3 text-fg overflow-x-auto",children:s.body}),v.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[v.jsxs("button",{onClick:n,className:"px-3 py-1.5 rounded bg-accent text-white text-xs font-medium hover:bg-accent/80 transition-colors",children:["Use prompt",!i&&v.jsx("span",{className:"ml-1 opacity-60 font-normal",children:"(no session)"})]}),v.jsx("button",{onClick:r,className:"px-3 py-1.5 rounded bg-bg-hi border border-line text-fg text-xs hover:bg-bg-hi/70 transition-colors",children:"Edit root template"}),e&&v.jsx("button",{onClick:o,className:"ml-auto px-3 py-1.5 rounded border border-line text-xs text-fg-dim hover:text-fg hover:border-accent/40 transition-colors",children:"Reset to default"})]})]})}function fni({draft:s,onChange:e,onCancel:i}){return v.jsxs("div",{className:"p-4 flex flex-col gap-3 h-full",children:[v.jsxs("div",{className:"flex items-center justify-between",children:[v.jsx("span",{className:"text-xs font-medium text-fg",children:"Edit root template"}),v.jsx("button",{onClick:i,className:"text-xs text-fg-dim hover:text-fg transition-colors",children:"Cancel"})]}),v.jsx("textarea",{value:s,onChange:n=>e(n.target.value),className:"flex-1 min-h-[16rem] w-full bg-bg border border-line rounded px-3 py-2 text-xs font-mono text-fg resize-y focus:outline-none focus:border-accent/60","aria-label":"Edit prompt body"}),v.jsxs("p",{className:"text-[11px] text-fg-faint",children:["Saves to ",v.jsx("code",{children:"~/.claude/session-manager/prompts/…"})," — overrides the seed on future opens."]})]})}function gni(){const s=Mg(),e=KF(s);if(!s)return v.jsx(zr,{children:v.jsx(Ui,{title:"no active session",hint:"open a terminal tab and run claude to see tasks"})});const i=(e==null?void 0:e.todos)??[],n={completed:i.filter(r=>r.status==="completed").length,in_progress:i.filter(r=>r.status==="in_progress").length,pending:i.filter(r=>r.status==="pending").length};return v.jsx(zr,{toolbar:v.jsxs(v.Fragment,{children:[v.jsxs("span",{className:"text-fg-faint",children:["session ",s.claudeSessionId.slice(0,8)]}),v.jsx("div",{className:"flex-1"}),v.jsxs("span",{className:"text-fg-faint",children:[v.jsx("span",{className:"text-green-400",children:n.completed})," done ·"," ",v.jsx("span",{className:"text-accent",children:n.in_progress})," active ·"," ",v.jsx("span",{className:"text-fg-dim",children:n.pending})," pending"]})]}),children:i.length===0?v.jsx(Ui,{title:"no todos yet",hint:"todos appear when claude calls TodoWrite"}):v.jsx("ul",{className:"p-4 space-y-1 max-w-3xl",children:i.map((r,o)=>v.jsxs("li",{className:`flex items-start gap-3 py-1.5 px-2 rounded text-xs ${r.status==="in_progress"?"bg-bg-elev":""}`,children:[v.jsx(pni,{status:r.status}),v.jsx("span",{className:`flex-1 ${r.status==="completed"?"text-fg-faint line-through":r.status==="in_progress"?"text-fg":"text-fg-dim"}`,children:r.status==="in_progress"&&r.activeForm?r.activeForm:r.content})]},o))})})}function pni({status:s}){return s==="completed"?v.jsx("span",{className:"text-green-400 w-4 shrink-0",children:"✓"}):s==="in_progress"?v.jsx("span",{className:"text-accent w-4 shrink-0",children:v.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-accent animate-pulse"})}):v.jsx("span",{className:"text-fg-faint w-4 shrink-0",children:"○"})}const tVe="~/.claude/session-manager/projects-prefs.json",mni={project:"asc",sessions:"desc",last:"desc",size:"desc"};function Nw(s){const e=s(),i={pinned:e.pinned,sort:e.sort,recentFilter:e.recentFilter,hasRemote:e.hasRemote,hasClaudemd:e.hasClaudemd,pinnedOnly:e.pinnedOnly,search:e.search,editor:e.editor};window.api.config.writeJson(tVe,i).catch(()=>{})}const bAe=Ka((s,e)=>({pinned:{},sort:{col:"last",dir:"desc"},recentFilter:"all",hasRemote:null,hasClaudemd:null,pinnedOnly:!1,search:"",editor:"auto",hydrated:!1,hydrate:async()=>{try{const i=await window.api.config.readJson(tVe);if(i.exists&&i.data&&typeof i.data=="object"){const n=i.data;s({pinned:n.pinned??{},sort:n.sort??{col:"last",dir:"desc"},recentFilter:n.recentFilter??"all",hasRemote:n.hasRemote??null,hasClaudemd:n.hasClaudemd??null,pinnedOnly:n.pinnedOnly??!1,search:n.search??"",editor:n.editor??"auto",hydrated:!0});return}}catch{}s({hydrated:!0})},togglePin:i=>{const n={...e().pinned,[i]:!e().pinned[i]};s({pinned:n}),Nw(e)},setSort:i=>{const n=e(),r=n.sort.col===i?n.sort.dir==="asc"?"desc":"asc":mni[i];s({sort:{col:i,dir:r}}),Nw(e)},setRecentFilter:i=>{s({recentFilter:i}),Nw(e)},setHasRemote:i=>{s({hasRemote:i}),Nw(e)},setHasClaudemd:i=>{s({hasClaudemd:i}),Nw(e)},setPinnedOnly:i=>{s({pinnedOnly:i}),Nw(e)},setSearch:i=>{s({search:i}),Nw(e)},setEditor:i=>{s({editor:i}),Nw(e)}}));async function _ni(s){const e={};try{const i=await window.api.config.readJson(`${s}/package.json`);if(i.exists&&i.data){const n=i.data.name;typeof n=="string"&&(e.name=n)}}catch{}try{const i=await window.api.config.readText(`${s}/.git/config`);if(i.exists&&i.text){const n=i.text.match(/\[remote "origin"\][^\[]*url\s*=\s*([^\n]+)/);if(n){let r=n[1].trim();r=r.replace(/^git@([^:]+):/,"$1/").replace(/\.git$/,"").replace(/^https?:\/\//,""),e.gitRemote=r}}}catch{}try{const i=await window.api.config.readText(`${s}/.git/HEAD`);if(i.exists&&i.text){const n=i.text.match(/ref: refs\/heads\/(.+)/);n&&(e.lastBranch=n[1].trim())}}catch{}try{const i=await window.api.config.readText(`${s}/CLAUDE.md`);i.exists&&i.text&&(e.claudemdPreview=i.text.slice(0,200))}catch{}if(!e.name){const i=s.split("/");e.name=i[i.length-1]||s}return e}function vni({cwd:s,projectName:e,onClose:i}){const[n,r]=z.useState(null),[o,a]=z.useState(!0),l=z.useRef(null);z.useEffect(()=>{a(!0),r(null),window.api.config.readText(`${s}/CLAUDE.md`).then(d=>{r(d.exists&&d.text?d.text:null),a(!1)}).catch(()=>{r(null),a(!1)})},[s]),z.useEffect(()=>{const d=u=>{u.key==="Escape"&&(u.stopPropagation(),i())};return document.addEventListener("keydown",d,{capture:!0}),()=>document.removeEventListener("keydown",d,{capture:!0})},[i]);const c=d=>{d.target===l.current&&i()};return v.jsx("div",{ref:l,className:"absolute inset-0 z-20",onClick:c,children:v.jsxs("div",{className:"absolute right-0 top-0 bottom-0 w-2/5 bg-bg-elev border-l border-line shadow-2xl z-30 flex flex-col",onClick:d=>d.stopPropagation(),children:[v.jsxs("header",{className:"shrink-0 flex items-center gap-2 px-3 py-2 border-b border-line bg-bg-elev",children:[v.jsxs("div",{className:"flex-1 min-w-0",children:[v.jsx("div",{className:"text-fg text-xs font-medium truncate",children:e}),v.jsxs("div",{className:"text-fg-faint text-[10px] font-mono truncate",children:[s,"/CLAUDE.md"]})]}),v.jsx("button",{onClick:i,className:"shrink-0 text-fg-faint hover:text-fg px-1.5 py-0.5 rounded hover:bg-bg-hi text-xs",title:"Close (Escape)",children:"✕"})]}),v.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:o?v.jsx(Ui,{title:"loading…"}):n==null?v.jsx(Ui,{title:"No CLAUDE.md found"}):v.jsx(jy,{value:n,onChange:()=>{},path:`${s}/CLAUDE.md`,readOnly:!0})})]})})}function Mte(s){return s.replace(/-/g,"/")}async function Pte(s){const i=(await window.api.config.listDir(s,{filesOnly:!0})).entries.filter(n=>n.name.endsWith(".jsonl")).sort((n,r)=>n.size-r.size);for(const n of i){const r=await window.api.config.readText(n.path);if(!(!r.exists||!r.text)){for(const o of r.text.split(`
|
|
4413
|
-
`))if(o.includes('"cwd"'))try{const a=JSON.parse(o);if(typeof a.cwd=="string"&&a.cwd.length>0)return a.cwd}catch{}}}return null}function bni(s){if(!s)return"—";const i=(Date.now()-s)/864e5;return i<1?"today":i<2?"yesterday":i<7?`${Math.floor(i)}d ago`:i<30?`${Math.floor(i/7)}w ago`:new Date(s).toLocaleDateString()}function Ote(){return v.jsx("span",{className:"inline-block h-3 w-12 rounded bg-bg-hi animate-pulse","aria-hidden":!0})}function Rw({label:s,active:e,onClick:i,tip:n}){return v.jsx(w_,{content:n,align:"bottom-center",children:v.jsx("button",{onClick:i,title:n,className:`px-2 py-0.5 rounded text-[10px] border transition-colors ${e?"border-blue-500 text-blue-400 bg-blue-500/10":"border-line text-fg-faint hover:text-fg hover:border-fg-faint"}`,children:s})})}function kT({tip:s,onClick:e,disabled:i,danger:n,children:r}){return v.jsx(w_,{content:s,children:v.jsx("button",{onClick:o=>{o.stopPropagation(),i||e()},title:s,disabled:i,className:`px-1.5 py-0.5 rounded text-sm leading-none transition-colors ${i?"text-fg-faint/30 cursor-not-allowed":n?"text-red-400/60 hover:text-red-400 hover:bg-red-950/30":"text-fg-faint hover:text-fg hover:bg-bg-hi"}`,children:r})})}const Fte=7*864e5,yni=30*864e5,wni=[{value:"auto",label:"auto"},{value:"code",label:"VS Code"},{value:"cursor",label:"Cursor"},{value:"subl",label:"Sublime"},{value:"nano",label:"nano"}];function xni(){var Ea,bo;const s=Go(),[e,i]=z.useState([]),[n,r]=z.useState(!0),[o,a]=z.useState({}),[l,c]=z.useState(""),[d,u]=z.useState(""),[h,f]=z.useState(new Set),[g,p]=z.useState(null),[_,m]=z.useState(null),[b,y]=z.useState(!1),[x,S]=z.useState(null),[k,D]=z.useState(null),T=z.useRef(null),N=z.useRef(null),A=hn(ft=>ft.addTab),{hydrated:O,hydrate:$,pinned:P,togglePin:B,sort:W,setSort:q,recentFilter:G,setRecentFilter:re,hasRemote:ie,setHasRemote:K,hasClaudemd:Z,setHasClaudemd:Q,pinnedOnly:ne,setPinnedOnly:ge,setSearch:Se,editor:Ee,setEditor:$e}=bAe();z.useEffect(()=>{$()},[]);const De=z.useRef(!1);z.useEffect(()=>{if(O&&!De.current){De.current=!0;const ft=bAe.getState().search;c(ft),u(ft)}},[O]),z.useEffect(()=>{if(!De.current)return;const ft=setTimeout(()=>{u(l),Se(l)},200);return()=>clearTimeout(ft)},[l,Se]),z.useEffect(()=>{if(!x)return;const ft=setTimeout(()=>S(null),3e3);return()=>clearTimeout(ft)},[x]),z.useEffect(()=>{if(!s)return;let ft=!1;return(async()=>{r(!0);try{const Dt=await window.api.config.listDir(`${s}/.claude/projects`,{dirsOnly:!0});if(ft)return;const xi=[];for(const An of Dt.entries){if(ft)return;const Hn=(await window.api.config.listDir(An.path,{filesOnly:!0})).entries.filter(Kr=>Kr.name.endsWith(".jsonl")),Ks=Hn.reduce((Kr,Ya)=>Math.max(Kr,Ya.mtimeMs),0),Cl=Hn.reduce((Kr,Ya)=>Kr+Ya.size,0);xi.push({encoded:An.name,displayPath:Mte(An.name),sessionCount:Hn.length,lastSession:Ks,path:An.path,sizeBytes:Cl})}xi.sort((An,Ns)=>Ns.lastSession-An.lastSession),ft||(i(xi),a({}),f(new Set))}catch(Dt){console.error("[Projects] scan failed:",Dt)}finally{ft||r(!1)}})(),()=>{ft=!0}},[s]),z.useEffect(()=>{if(!e.length)return;let ft=!1;const Dt=e.slice();let xi=0;const An=()=>{for(;!ft&&xi<6&&Dt.length;){const Ns=Dt.shift();xi++,Pte(Ns.path).then(async Hn=>{if(ft)return;const Ks=Hn?await _ni(Hn):{};ft||a(Cl=>({...Cl,[Ns.encoded]:{cwd:Hn??null,...Ks}}))}).catch(()=>{ft||a(Hn=>({...Hn,[Ns.encoded]:{cwd:null}}))}).finally(()=>{xi--,ft||An()})}};return An(),()=>{ft=!0}},[e]);const ae=Object.keys(o).length>=e.length,Te=Object.values(o).some(ft=>ft.gitRemote),Ie=Object.values(o).some(ft=>ft.lastBranch),st=e.length>0&&(Te||!ae),He=e.length>0&&(Ie||!ae),lt=Date.now(),Je=e.filter(ft=>{var xi,An,Ns,Hn;if(G==="7d"&<-ft.lastSession>Fte||G==="30d"&<-ft.lastSession>yni||ne&&!P[ft.encoded])return!1;const Dt=o[ft.encoded];if(Dt&&(ie===!0&&!Dt.gitRemote||ie===!1&&Dt.gitRemote||Z===!0&&!Dt.claudemdPreview||Z===!1&&Dt.claudemdPreview))return!1;if(d){const Ks=d.toLowerCase();if(!(ft.displayPath.toLowerCase().includes(Ks)||(((xi=Dt==null?void 0:Dt.cwd)==null?void 0:xi.toLowerCase().includes(Ks))??!1)||(((An=Dt==null?void 0:Dt.name)==null?void 0:An.toLowerCase().includes(Ks))??!1)||(((Ns=Dt==null?void 0:Dt.gitRemote)==null?void 0:Ns.toLowerCase().includes(Ks))??!1)||(((Hn=Dt==null?void 0:Dt.claudemdPreview)==null?void 0:Hn.toLowerCase().includes(Ks))??!1)))return!1}return!0}),Ct=[...Je].sort((ft,Dt)=>{var Hn,Ks;const xi=P[ft.encoded]?1:0,An=P[Dt.encoded]?1:0;if(xi!==An)return An-xi;let Ns=0;switch(W.col){case"project":{const Cl=((Hn=o[ft.encoded])==null?void 0:Hn.cwd)??ft.displayPath,Kr=((Ks=o[Dt.encoded])==null?void 0:Ks.cwd)??Dt.displayPath;Ns=Cl.localeCompare(Kr);break}case"sessions":Ns=ft.sessionCount-Dt.sessionCount;break;case"last":Ns=ft.lastSession-Dt.lastSession;break;case"size":Ns=ft.sizeBytes-Dt.sizeBytes;break}return W.dir==="asc"?Ns:-Ns}),Ft=Ct.length>0&&Ct.every(ft=>h.has(ft.encoded)),Ot=Ct.some(ft=>h.has(ft.encoded));z.useEffect(()=>{N.current&&(N.current.indeterminate=Ot&&!Ft)},[Ot,Ft]);const En=()=>{f(Ft?ft=>{const Dt=new Set(ft);return Ct.forEach(xi=>Dt.delete(xi.encoded)),Dt}:ft=>{const Dt=new Set(ft);return Ct.forEach(xi=>Dt.add(xi.encoded)),Dt})},Ji=async ft=>{var Dt;return((Dt=o[ft.encoded])==null?void 0:Dt.cwd)??await Pte(ft.path)},cn=ft=>S(ft),Tn=async ft=>{var An;let Dt=((An=o[ft.encoded])==null?void 0:An.cwd)??null;if(Dt||(Dt=await Pte(ft.path)),!Dt&&(Dt=await window.api.app.pickDirectory(),!Dt))return;const xi=crypto.randomUUID();A({id:xi,cwd:Dt,startupCommand:`claude --dangerously-skip-permissions --session-id ${im(xi)}`,presetId:"projects-tab"})},Ts=async ft=>{const Dt=await Ji(ft);if(!Dt){cn("Project directory not yet resolved");return}const xi=await window.api.app.openInEditor(Dt,Ee||null);xi.ok||cn(xi.error??"No editor found")},ds=async ft=>{const Dt=await Ji(ft);if(!Dt){cn("Project directory not yet resolved");return}const xi=await window.api.app.openInFinder(Dt);xi.ok||cn(xi.error??"Failed to open file manager")},rr=async ft=>{const Dt=await Ji(ft);if(!Dt){cn("Project directory not yet resolved");return}const xi=await window.api.app.openInTerminal(Dt);xi.ok||cn(xi.error??"No terminal emulator found")},Is=ft=>{p(ft.encoded)},vo=async ft=>{m(null),y(!0);const Dt=[];for(const xi of ft)try{const An=await window.api.app.archiveProject(xi);An.ok?Dt.push(xi):cn(An.error??`Failed to archive ${xi}`)}catch(An){cn(An instanceof Error?An.message:"Archive failed")}Dt.length&&(i(xi=>xi.filter(An=>!Dt.includes(An.encoded))),f(xi=>{const An=new Set(xi);return Dt.forEach(Ns=>An.delete(Ns)),An}),g&&Dt.includes(g)&&p(null)),y(!1)},Ko=e.length,es=e.filter(ft=>lt-ft.lastSession<Fte).length,ii=e.reduce((ft,Dt)=>ft+Dt.sessionCount,0),bi=e.reduce((ft,Dt)=>ft+Dt.sizeBytes,0),Fi=[...e].filter(ft=>lt-ft.lastSession<Fte).sort((ft,Dt)=>Dt.sessionCount-ft.sessionCount).slice(0,3),Ni=ft=>{var xi;const Dt=(xi=T.current)==null?void 0:xi.querySelector(`[data-row-key="${ft}"]`);Dt==null||Dt.scrollIntoView({behavior:"smooth",block:"center"}),D(ft),setTimeout(()=>D(null),2e3)},ys=(ft,Dt)=>v.jsx(w_,{content:`Sort by ${Dt}`,align:"bottom-center",children:v.jsxs("button",{onClick:()=>q(ft),title:`Sort by ${Dt}`,className:"flex items-center gap-1 hover:text-fg w-full uppercase tracking-wider",children:[v.jsx("span",{children:Dt}),W.col===ft&&v.jsx("span",{className:"text-[10px] leading-none",children:W.dir==="asc"?"▲":"▼"})]})}),Gr=g?((Ea=o[g])==null?void 0:Ea.cwd)??null:null,xl=g?((bo=o[g])==null?void 0:bo.cwd)??`/${Mte(g)}`:"",La=[];He&&La.push({key:"branch",header:"branch",width:"8rem",render:ft=>{const Dt=o[ft.encoded];return Dt?Dt.lastBranch?v.jsx("span",{className:"font-mono text-fg-faint truncate block",children:Dt.lastBranch}):v.jsx("span",{className:"text-fg-faint",children:"—"}):v.jsx(Ote,{})}}),st&&La.push({key:"remote",header:"remote",render:ft=>{const Dt=o[ft.encoded];return Dt?Dt.gitRemote?v.jsx("span",{className:"font-mono text-fg-faint truncate block text-[10px]",children:Dt.gitRemote}):v.jsx("span",{className:"text-fg-faint",children:"—"}):v.jsx(Ote,{})}});const fs=[{key:"select",header:v.jsx("input",{ref:N,type:"checkbox",checked:Ft,onChange:En,className:"accent-accent cursor-pointer",title:"Select all visible",onClick:ft=>ft.stopPropagation()}),width:"2rem",className:"px-1",render:ft=>v.jsx("input",{type:"checkbox",checked:h.has(ft.encoded),onChange:()=>{f(Dt=>{const xi=new Set(Dt);return xi.has(ft.encoded)?xi.delete(ft.encoded):xi.add(ft.encoded),xi})},onClick:Dt=>Dt.stopPropagation(),className:"accent-accent cursor-pointer"})},{key:"pin",header:"",width:"2rem",className:"px-1",render:ft=>v.jsx(w_,{content:P[ft.encoded]?"Unpin":"Pin to top",children:v.jsx("button",{onClick:Dt=>{Dt.stopPropagation(),B(ft.encoded)},title:P[ft.encoded]?"Unpin":"Pin to top",className:`text-sm leading-none transition-colors ${P[ft.encoded]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:P[ft.encoded]?"★":"☆"})})},{key:"path",header:ys("project","project"),render:ft=>{const Dt=o[ft.encoded],xi=(Dt==null?void 0:Dt.cwd)??`/${ft.displayPath}`,An=v.jsx("span",{className:"font-mono text-fg-dim truncate block max-w-[22rem]",children:xi});return Dt!=null&&Dt.claudemdPreview?v.jsx(w_,{content:v.jsx("span",{className:"font-mono text-[9px] whitespace-pre-wrap",children:Dt.claudemdPreview}),align:"bottom-center",children:An}):An}},{key:"name",header:"name",width:"7rem",render:ft=>{const Dt=o[ft.encoded];return Dt?v.jsx("span",{className:"text-fg-dim truncate block",children:Dt.name??"—"}):v.jsx(Ote,{})}},{key:"sessions",header:ys("sessions","sessions"),width:"6rem",render:ft=>v.jsx("span",{className:"text-fg-dim",children:ft.sessionCount})},{key:"size",header:ys("size","size"),width:"6rem",render:ft=>v.jsx("span",{className:"text-fg-faint",children:OL(ft.sizeBytes)})},{key:"last",header:ys("last","last active"),width:"9rem",render:ft=>v.jsx("span",{className:"text-fg-faint",children:bni(ft.lastSession)})},...La,{key:"action",header:"",width:"11rem",render:ft=>{const Dt=o[ft.encoded],xi=!!(Dt!=null&&Dt.claudemdPreview);return v.jsxs("div",{className:"flex items-center gap-0.5",children:[v.jsx(kT,{tip:"Open in new terminal session",onClick:()=>Tn(ft),children:"▷"}),v.jsx(kT,{tip:"Open in editor",onClick:()=>Ts(ft),children:"✏"}),v.jsx(kT,{tip:"Open in file manager",onClick:()=>ds(ft),children:"⌂"}),v.jsx(kT,{tip:"Open in terminal",onClick:()=>rr(ft),children:"⊞"}),v.jsx(kT,{tip:xi?"Preview CLAUDE.md":"No CLAUDE.md",onClick:()=>Is(ft),disabled:!xi,children:"Ⓜ"}),v.jsx(kT,{tip:"Archive project",onClick:()=>m([ft.encoded]),danger:!0,children:"⊗"})]})}}];return v.jsxs("div",{className:"h-full flex flex-col",children:[!n&&e.length>0&&v.jsxs("div",{className:"shrink-0 border-b border-line bg-bg px-3 py-1.5 flex items-center gap-4 text-[10px] text-fg-faint flex-wrap",children:[v.jsxs("span",{children:[v.jsx("span",{className:"text-fg-dim font-medium",children:Ko})," projects"]}),v.jsxs("span",{children:[v.jsx("span",{className:"text-fg-dim font-medium",children:es})," active 7d"]}),v.jsxs("span",{children:[v.jsx("span",{className:"text-fg-dim font-medium",children:ii})," sessions"]}),v.jsxs("span",{children:[v.jsx("span",{className:"text-fg-dim font-medium",children:OL(bi)})," on disk"]}),Fi.length>0&&v.jsxs("span",{className:"flex items-center gap-1 flex-wrap",children:[v.jsx("span",{className:"text-fg-faint",children:"most active:"}),Fi.map(ft=>{var xi,An,Ns;const Dt=((An=(xi=o[ft.encoded])==null?void 0:xi.cwd)==null?void 0:An.split("/").pop())??ft.displayPath.split("/").pop()??ft.encoded;return v.jsx("button",{onClick:()=>Ni(ft.encoded),className:"px-1.5 py-0 rounded border border-line hover:border-fg-faint hover:text-fg transition-colors font-mono",title:((Ns=o[ft.encoded])==null?void 0:Ns.cwd)??ft.displayPath,children:Dt},ft.encoded)})]})]}),v.jsx("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 text-xs",children:v.jsxs("div",{className:"flex flex-col gap-1.5 w-full py-0.5",children:[v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("input",{type:"search",placeholder:"search projects…",value:l,onChange:ft=>c(ft.target.value),className:"h-6 px-2 bg-bg border border-line rounded text-xs text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint w-48"}),v.jsx("span",{className:"text-fg-faint",children:Je.length===e.length?`${e.length} projects`:`${Je.length} of ${e.length}`}),v.jsx("div",{className:"flex-1"}),v.jsx(w_,{content:"Preferred editor for 'Open in editor' action",children:v.jsx("select",{value:Ee,onChange:ft=>$e(ft.target.value),className:"h-6 bg-bg border border-line rounded text-xs text-fg-dim px-1 focus:outline-none focus:border-fg-faint",children:wni.map(ft=>v.jsxs("option",{value:ft.value,children:["Editor: ",ft.label]},ft.value))})}),v.jsx("span",{className:"text-fg-faint font-mono truncate",children:"~/.claude/projects/"})]}),v.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[v.jsx(Rw,{label:"All",active:G==="all",onClick:()=>re("all"),tip:"Show all projects"}),v.jsx(Rw,{label:"≤7d",active:G==="7d",onClick:()=>re("7d"),tip:"Active in last 7 days"}),v.jsx(Rw,{label:"≤30d",active:G==="30d",onClick:()=>re("30d"),tip:"Active in last 30 days"}),v.jsx("span",{className:"w-px h-3 bg-line mx-0.5 shrink-0"}),v.jsx(Rw,{label:"Has remote",active:ie===!0,onClick:()=>K(ie===!0?null:!0),tip:"Only projects with a git remote"}),v.jsx(Rw,{label:"No remote",active:ie===!1,onClick:()=>K(ie===!1?null:!1),tip:"Only projects without a git remote"}),v.jsx("span",{className:"w-px h-3 bg-line mx-0.5 shrink-0"}),v.jsx(Rw,{label:"Has CLAUDE.md",active:Z===!0,onClick:()=>Q(Z===!0?null:!0),tip:"Only projects with a CLAUDE.md"}),v.jsx(Rw,{label:"No CLAUDE.md",active:Z===!1,onClick:()=>Q(Z===!1?null:!1),tip:"Only projects without a CLAUDE.md"}),v.jsx("span",{className:"w-px h-3 bg-line mx-0.5 shrink-0"}),v.jsx(Rw,{label:"Pinned",active:ne,onClick:()=>ge(!ne),tip:"Only pinned projects"})]})]})}),v.jsxs("div",{className:"flex-1 min-h-0 flex relative",children:[v.jsx("div",{className:"flex-1 min-w-0 overflow-auto",ref:T,children:n?v.jsx(Ui,{title:"scanning projects…"}):v.jsx(Rme,{columns:fs,rows:Ct,getKey:ft=>ft.encoded,activeKey:k,empty:"no projects with claude session history"})}),g&&Gr&&v.jsx(vni,{cwd:Gr,projectName:xl,onClose:()=>p(null)})]}),h.size>0&&v.jsxs("div",{className:"shrink-0 border-t border-line bg-bg-elev px-3 py-2 flex items-center gap-2 text-xs",children:[v.jsxs("span",{className:"text-fg-faint",children:[h.size," selected"]}),v.jsx("div",{className:"flex-1"}),b&&v.jsx("span",{className:"text-fg-faint animate-pulse",children:"archiving…"}),v.jsxs("button",{onClick:()=>m(Array.from(h)),disabled:b,className:"px-2 py-1 border border-red-900/50 text-red-400/80 rounded hover:bg-red-950/30 hover:text-red-400 disabled:opacity-40 transition-colors",children:["Archive ",h.size]}),v.jsx("button",{onClick:async()=>{const ft=e.filter(Dt=>h.has(Dt.encoded));for(const Dt of ft)await Ts(Dt)},disabled:b,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 transition-colors",children:"Open all in editor"}),v.jsx("button",{onClick:()=>f(new Set),className:"px-2 py-1 border border-line rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",children:"Cancel"})]}),v.jsxs(Og,{open:!!_,onClose:()=>m(null),title:"Archive projects?",children:[v.jsxs("p",{className:"text-sm text-fg-dim mb-1",children:["Move ",(_==null?void 0:_.length)??0," project",((_==null?void 0:_.length)??0)!==1?"s":""," to"]}),v.jsx("p",{className:"text-xs text-fg-faint font-mono mb-4",children:"~/.claude/projects-archive/"}),_&&_.length<=5&&v.jsx("ul",{className:"mb-4 space-y-0.5 text-[10px] font-mono text-fg-faint",children:_.map(ft=>{var Dt;return v.jsx("li",{className:"truncate",children:((Dt=o[ft])==null?void 0:Dt.cwd)??`/${Mte(ft)}`},ft)})}),v.jsxs("div",{className:"flex gap-2 justify-end",children:[v.jsx("button",{onClick:()=>m(null),className:"px-3 py-1.5 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Cancel"}),v.jsx("button",{onClick:()=>_&&vo(_),className:"px-3 py-1.5 text-xs border border-red-900/50 rounded text-red-400 hover:bg-red-950/30",children:"Archive"})]})]}),x&&v.jsx("div",{role:"alert",className:"pointer-events-none fixed bottom-4 right-4 z-50 bg-red-950 border border-red-900/60 text-red-300 text-xs px-3 py-1.5 rounded shadow-lg max-w-xs",children:x})]})}const vhe="~/.config/session-manager/doc-editor.json",Cni=20;let Bte=null;function bP(s){Bte&&clearTimeout(Bte),Bte=setTimeout(async()=>{const e=s();try{const i=await window.api.config.readJson(vhe).catch(()=>null),n=(i==null?void 0:i.data)??{};await window.api.config.writeJson(vhe,{...n,recents:e.recents,openPaths:Object.keys(e.docs),viewModes:e.viewModes})}catch(i){console.warn("[docEditor] persist failed:",i)}},500)}function yAe(s,e){return[e,...s.filter(i=>i!==e)].slice(0,Cni)}const Hh=Ka((s,e)=>({docs:{},activePath:null,recents:[],viewModes:{},hydrated:!1,open:async i=>{if(e().docs[i]){s({activePath:i});return}const r=await window.api.docEditor.readFile(i);if(!r.ok){Kt.warn(`Could not open ${i.split("/").pop()}: ${r.error??"unknown error"}`),s(a=>({recents:a.recents.filter(l=>l!==i)})),bP(e);return}const o={path:i,diskText:r.text??"",bufferText:r.text??"",mtimeMs:r.mtimeMs??0,loadedAt:Date.now()};s(a=>({docs:{...a.docs,[i]:o},activePath:i,recents:yAe(a.recents,i)})),bP(e)},close:i=>{var l;const n=e(),r=n.docs[i];if(!r)return;if(r.bufferText!==r.diskText){const c=i.split("/").pop()??i;if(!window.confirm(`"${c}" has unsaved changes. Close without saving?`))return}const o={...n.docs};delete o[i];let a=n.activePath;n.activePath===i&&(a=((l=Object.values(o).sort((d,u)=>u.loadedAt-d.loadedAt)[0])==null?void 0:l.path)??null),s({docs:o,activePath:a}),bP(e)},setActive:i=>{s({activePath:i})},setViewMode:(i,n)=>{s(r=>({viewModes:{...r.viewModes,[i]:n}})),bP(e)},edit:(i,n)=>{const r=e().docs[i];r&&s(o=>({docs:{...o.docs,[i]:{...r,bufferText:n}}}))},save:async i=>{const n=e().docs[i];if(!n)return;const r=n.bufferText,o=await window.api.docEditor.writeFile(i,r);if(!o.ok){Kt.error(`Save failed for ${i.split("/").pop()}: ${o.error??"unknown"}`);return}s(a=>{const l=a.docs[i];return l?{docs:{...a.docs,[i]:{...l,diskText:r,mtimeMs:o.mtimeMs??l.mtimeMs}},recents:yAe(a.recents,i)}:{}}),bP(e)},saveAll:async()=>{const i=Object.values(e().docs).filter(n=>n.bufferText!==n.diskText).map(n=>n.path);await Promise.all(i.map(n=>e().save(n)))},hydrate:async()=>{if(!e().hydrated){s({hydrated:!0});try{const n=(await window.api.config.readJson(vhe)).data??{},r=Array.isArray(n.recents)?n.recents:[],o=Array.isArray(n.openPaths)?n.openPaths:[],a=n.viewModes??{},l={};for(const[c,d]of Object.entries(a))(d==="wysiwyg"||d==="source")&&(l[c]=d);s({recents:r,viewModes:l});for(const c of o)await e().open(c)}catch(i){console.warn("[docEditor] hydrate failed:",i)}}}}));window.__docEditor=Hh;const Sni={json:"json",ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",cjs:"javascript",mjs:"javascript",py:"python",sh:"shell",bash:"shell",yaml:"yaml",yml:"yaml",toml:"ini",css:"css",html:"html",xml:"xml",sql:"sql",rs:"rust",go:"go",md:"markdown",markdown:"markdown"},wAe={Dockerfile:"dockerfile",Makefile:"makefile"};function kni(s){const e=s.split("/").pop()??s;if(wAe[e])return wAe[e];const i=e.lastIndexOf(".");if(i===-1)return null;const n=e.slice(i+1);return Sni[n]??null}const Lni=z.lazy(()=>ei(()=>import("./TiptapBody-DtTU-6tZ.js"),[],import.meta.url).then(s=>({default:s.TiptapBody})));function Eni(s){return s.split("/").pop()??s}function Dni(s){return s.endsWith(".md")||s.endsWith(".markdown")}function Tni({docs:s,activePath:e,onSetActive:i,onClose:n}){const r=Object.keys(s);return v.jsx("div",{className:"h-9 bg-bg-elev border-b border-line flex items-center overflow-x-auto shrink-0 px-2 gap-1","data-testid":"doc-tab-strip",children:r.map(o=>{const a=s[o],l=a.bufferText!==a.diskText,c=Eni(o),d=o===e;return v.jsxs("div",{className:`group px-3 py-1 flex items-center gap-1 rounded-t text-xs shrink-0 cursor-pointer transition-colors ${d?"bg-bg-hi text-fg font-semibold border border-b-0 border-accent border-t-2 -mb-px relative z-10":"bg-bg-elev text-fg-dim border border-line hover:text-fg hover:bg-bg"}`,onClick:()=>i(o),title:o,"data-testid":`doc-tab-${c}`,children:[l&&v.jsx("span",{className:"text-amber-400","aria-label":"unsaved changes","data-testid":"doc-tab-dirty",children:"●"}),v.jsx("span",{children:c}),v.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),n(o)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1",title:`Close ${c}`,"aria-label":`Close ${c}`,"data-testid":`doc-x-${c}`,children:"×"})]},o)})})}function Ini({path:s,value:e,onChange:i,language:n}){const r=z.useRef(null),o=z.useRef(s);o.current=s;const a=async l=>{r.current=l;const c=await ei(()=>Promise.resolve().then(()=>xme),void 0,import.meta.url);l.addCommand(c.KeyMod.CtrlCmd|c.KeyCode.KeyS,()=>{Hh.getState().save(o.current)})};return v.jsx(vU,{path:`file://${s}`,language:n,value:e,onChange:l=>i(l??""),onMount:a,theme:"vs-dark",options:{minimap:{enabled:!1},fontSize:12,fontFamily:"JetBrains Mono, ui-monospace, Menlo, monospace",lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}function Nni({path:s,value:e,onChange:i}){const n=kni(s);if(!n){const r=s.split("/").pop()??s;return v.jsx("textarea",{className:"w-full h-full resize-none bg-bg text-fg font-mono text-sm p-3 focus:outline-none leading-relaxed",value:e,onChange:o=>i(o.target.value),spellCheck:!1,"data-testid":"doc-textarea","aria-label":`Edit ${r}`},s)}return v.jsx(Ini,{path:s,value:e,onChange:i,language:n})}function Rni(){const s=Hh(m=>m.docs),e=Hh(m=>m.activePath),i=Hh(m=>m.viewModes),n=Hh(m=>m.open),r=Hh(m=>m.close),o=Hh(m=>m.setActive),a=Hh(m=>m.edit),l=Hh(m=>m.save),c=Hh(m=>m.saveAll),d=Hh(m=>m.setViewMode),u=Hh(m=>m.hydrate);z.useEffect(()=>{u()},[u]);const h=e?s[e]??null:null,f=Object.values(s).some(m=>m.bufferText!==m.diskText),g=e?i[e]??"wysiwyg":"wysiwyg",p=e?Dni(e):!1,_=async()=>{const m=e?e.split("/").slice(0,-1).join("/"):void 0,b=await window.api.docEditor.pickFile(m?{lastDir:m}:void 0);b.path&&await n(b.path)};return e===null?v.jsx(Ui,{title:"No document open",hint:v.jsxs("span",{children:["Click ",v.jsx("strong",{children:"Open…"})," or use"," ",v.jsx("kbd",{className:"px-1 py-0.5 border border-line rounded font-mono text-[10px]",children:"Cmd-K"})," ","and type ",v.jsx("code",{children:"doc:open"})]})}):v.jsxs("div",{className:"h-full flex flex-col",onKeyDown:m=>{(m.ctrlKey||m.metaKey)&&m.key.toLowerCase()==="s"&&!m.shiftKey&&(m.preventDefault(),e&&l(e)),(m.ctrlKey||m.metaKey)&&m.key.toLowerCase()==="w"&&!m.shiftKey&&(m.preventDefault(),e&&r(e))},"data-testid":"doc-editor-panel",children:[v.jsx(Tni,{docs:s,activePath:e,onSetActive:o,onClose:r}),v.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-2 text-xs",children:[v.jsx("button",{type:"button",onClick:_,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi transition-colors","data-testid":"doc-open-btn",children:"Open…"}),v.jsx("button",{type:"button",onClick:()=>e&&l(e),disabled:!h||h.bufferText===h.diskText,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi transition-colors disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"doc-save-btn",children:"Save"}),v.jsx("button",{type:"button",onClick:()=>c(),disabled:!f,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi transition-colors disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"doc-save-all-btn",children:"Save All"}),p&&e&&v.jsxs("div",{className:"flex items-center border border-line rounded overflow-hidden text-[11px]","data-testid":"view-mode-toggle",children:[v.jsx("button",{type:"button",onClick:()=>d(e,"wysiwyg"),className:`px-2 py-0.5 transition-colors ${g==="wysiwyg"?"bg-accent text-bg font-semibold":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,"data-testid":"view-mode-wysiwyg",children:"WYSIWYG"}),v.jsx("button",{type:"button",onClick:()=>d(e,"source"),className:`px-2 py-0.5 transition-colors ${g==="source"?"bg-accent text-bg font-semibold":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,"data-testid":"view-mode-source",children:"Source"})]}),e&&v.jsx("span",{className:"ml-2 text-fg-faint truncate flex-1 font-mono text-[11px]",title:e,children:e})]}),v.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:p&&g==="wysiwyg"&&e&&h?v.jsx(z.Suspense,{fallback:v.jsx("div",{className:"p-4 text-fg-faint text-sm",children:"Loading editor…"}),children:v.jsx(Lni,{value:h.bufferText,onChange:m=>a(e,m)},e)}):p&&e&&h?v.jsx(jy,{path:e,value:h.bufferText,onChange:m=>a(e,m)},e):e&&h?v.jsx(Nni,{path:e,value:h.bufferText,onChange:m=>a(e,m)}):null})]})}const Ani=5e3;let A6=null,yP=null;async function bhe(s){const e=Date.now();return!(s!=null&&s.fresh)&&A6&&e-A6.at<Ani?A6.result:yP||(yP=(async()=>{try{const i=await window.api.schedule.lintQueue();return A6={result:i,at:Date.now()},i}finally{yP=null}})(),yP)}const xAe=2e3;function Mni(s){return s.is_error===!0||s.error!=null&&s.error!==""||s.type==="result"&&s.subtype!=="success"&&s.subtype!=null}function Pni(s){return typeof s.error=="string"&&s.error?s.error:typeof s.result=="string"&&s.result?s.result:typeof s.subtype=="string"?s.subtype:JSON.stringify(s).slice(0,200)}function Oni(s){if(typeof s.text=="string")return s.text.slice(0,200);if(typeof s.content=="string")return s.content.slice(0,200);if(Array.isArray(s.content)){for(const i of s.content)if(i&&typeof i=="object"&&"text"in i&&typeof i.text=="string")return i.text.slice(0,200)}const e=s.message;if(e&&typeof e=="object"){const i=e;if(typeof i.content=="string")return i.content.slice(0,200);if(Array.isArray(i.content)){for(const n of i.content)if(n&&typeof n=="object"&&"text"in n&&typeof n.text=="string")return n.text.slice(0,200)}}return typeof s.result=="string"&&s.result?s.result.slice(0,200):typeof s.subtype=="string"?s.subtype:JSON.stringify(s).slice(0,200)}function Fni(s){if(!s||!s.trim())return{events:[],errors:{count:0,firstMessage:null},rawLineCount:0,truncated:!1};const i=s.split(`
|
|
4413
|
+
`))if(o.includes('"cwd"'))try{const a=JSON.parse(o);if(typeof a.cwd=="string"&&a.cwd.length>0)return a.cwd}catch{}}}return null}function bni(s){if(!s)return"—";const i=(Date.now()-s)/864e5;return i<1?"today":i<2?"yesterday":i<7?`${Math.floor(i)}d ago`:i<30?`${Math.floor(i/7)}w ago`:new Date(s).toLocaleDateString()}function Ote(){return v.jsx("span",{className:"inline-block h-3 w-12 rounded bg-bg-hi animate-pulse","aria-hidden":!0})}function Rw({label:s,active:e,onClick:i,tip:n}){return v.jsx(w_,{content:n,align:"bottom-center",children:v.jsx("button",{onClick:i,title:n,className:`px-2 py-0.5 rounded text-[10px] border transition-colors ${e?"border-blue-500 text-blue-400 bg-blue-500/10":"border-line text-fg-faint hover:text-fg hover:border-fg-faint"}`,children:s})})}function kT({tip:s,onClick:e,disabled:i,danger:n,children:r}){return v.jsx(w_,{content:s,children:v.jsx("button",{onClick:o=>{o.stopPropagation(),i||e()},title:s,disabled:i,className:`px-1.5 py-0.5 rounded text-sm leading-none transition-colors ${i?"text-fg-faint/30 cursor-not-allowed":n?"text-red-400/60 hover:text-red-400 hover:bg-red-950/30":"text-fg-faint hover:text-fg hover:bg-bg-hi"}`,children:r})})}const Fte=7*864e5,yni=30*864e5,wni=[{value:"auto",label:"auto"},{value:"code",label:"VS Code"},{value:"cursor",label:"Cursor"},{value:"subl",label:"Sublime"},{value:"nano",label:"nano"}];function xni(){var Ea,bo;const s=Go(),[e,i]=z.useState([]),[n,r]=z.useState(!0),[o,a]=z.useState({}),[l,c]=z.useState(""),[d,u]=z.useState(""),[h,f]=z.useState(new Set),[g,p]=z.useState(null),[_,m]=z.useState(null),[b,y]=z.useState(!1),[x,S]=z.useState(null),[k,D]=z.useState(null),T=z.useRef(null),N=z.useRef(null),A=hn(ft=>ft.addTab),{hydrated:O,hydrate:$,pinned:P,togglePin:B,sort:W,setSort:q,recentFilter:G,setRecentFilter:re,hasRemote:ie,setHasRemote:K,hasClaudemd:Z,setHasClaudemd:Q,pinnedOnly:ne,setPinnedOnly:ge,setSearch:Se,editor:Ee,setEditor:$e}=bAe();z.useEffect(()=>{$()},[]);const De=z.useRef(!1);z.useEffect(()=>{if(O&&!De.current){De.current=!0;const ft=bAe.getState().search;c(ft),u(ft)}},[O]),z.useEffect(()=>{if(!De.current)return;const ft=setTimeout(()=>{u(l),Se(l)},200);return()=>clearTimeout(ft)},[l,Se]),z.useEffect(()=>{if(!x)return;const ft=setTimeout(()=>S(null),3e3);return()=>clearTimeout(ft)},[x]),z.useEffect(()=>{if(!s)return;let ft=!1;return(async()=>{r(!0);try{const Dt=await window.api.config.listDir(`${s}/.claude/projects`,{dirsOnly:!0});if(ft)return;const xi=[];for(const An of Dt.entries){if(ft)return;const Hn=(await window.api.config.listDir(An.path,{filesOnly:!0})).entries.filter(Kr=>Kr.name.endsWith(".jsonl")),Ks=Hn.reduce((Kr,Ya)=>Math.max(Kr,Ya.mtimeMs),0),Cl=Hn.reduce((Kr,Ya)=>Kr+Ya.size,0);xi.push({encoded:An.name,displayPath:Mte(An.name),sessionCount:Hn.length,lastSession:Ks,path:An.path,sizeBytes:Cl})}xi.sort((An,Ns)=>Ns.lastSession-An.lastSession),ft||(i(xi),a({}),f(new Set))}catch(Dt){console.error("[Projects] scan failed:",Dt)}finally{ft||r(!1)}})(),()=>{ft=!0}},[s]),z.useEffect(()=>{if(!e.length)return;let ft=!1;const Dt=e.slice();let xi=0;const An=()=>{for(;!ft&&xi<6&&Dt.length;){const Ns=Dt.shift();xi++,Pte(Ns.path).then(async Hn=>{if(ft)return;const Ks=Hn?await _ni(Hn):{};ft||a(Cl=>({...Cl,[Ns.encoded]:{cwd:Hn??null,...Ks}}))}).catch(()=>{ft||a(Hn=>({...Hn,[Ns.encoded]:{cwd:null}}))}).finally(()=>{xi--,ft||An()})}};return An(),()=>{ft=!0}},[e]);const ae=Object.keys(o).length>=e.length,Te=Object.values(o).some(ft=>ft.gitRemote),Ie=Object.values(o).some(ft=>ft.lastBranch),st=e.length>0&&(Te||!ae),He=e.length>0&&(Ie||!ae),lt=Date.now(),Je=e.filter(ft=>{var xi,An,Ns,Hn;if(G==="7d"&<-ft.lastSession>Fte||G==="30d"&<-ft.lastSession>yni||ne&&!P[ft.encoded])return!1;const Dt=o[ft.encoded];if(Dt&&(ie===!0&&!Dt.gitRemote||ie===!1&&Dt.gitRemote||Z===!0&&!Dt.claudemdPreview||Z===!1&&Dt.claudemdPreview))return!1;if(d){const Ks=d.toLowerCase();if(!(ft.displayPath.toLowerCase().includes(Ks)||(((xi=Dt==null?void 0:Dt.cwd)==null?void 0:xi.toLowerCase().includes(Ks))??!1)||(((An=Dt==null?void 0:Dt.name)==null?void 0:An.toLowerCase().includes(Ks))??!1)||(((Ns=Dt==null?void 0:Dt.gitRemote)==null?void 0:Ns.toLowerCase().includes(Ks))??!1)||(((Hn=Dt==null?void 0:Dt.claudemdPreview)==null?void 0:Hn.toLowerCase().includes(Ks))??!1)))return!1}return!0}),Ct=[...Je].sort((ft,Dt)=>{var Hn,Ks;const xi=P[ft.encoded]?1:0,An=P[Dt.encoded]?1:0;if(xi!==An)return An-xi;let Ns=0;switch(W.col){case"project":{const Cl=((Hn=o[ft.encoded])==null?void 0:Hn.cwd)??ft.displayPath,Kr=((Ks=o[Dt.encoded])==null?void 0:Ks.cwd)??Dt.displayPath;Ns=Cl.localeCompare(Kr);break}case"sessions":Ns=ft.sessionCount-Dt.sessionCount;break;case"last":Ns=ft.lastSession-Dt.lastSession;break;case"size":Ns=ft.sizeBytes-Dt.sizeBytes;break}return W.dir==="asc"?Ns:-Ns}),Ft=Ct.length>0&&Ct.every(ft=>h.has(ft.encoded)),Ot=Ct.some(ft=>h.has(ft.encoded));z.useEffect(()=>{N.current&&(N.current.indeterminate=Ot&&!Ft)},[Ot,Ft]);const En=()=>{f(Ft?ft=>{const Dt=new Set(ft);return Ct.forEach(xi=>Dt.delete(xi.encoded)),Dt}:ft=>{const Dt=new Set(ft);return Ct.forEach(xi=>Dt.add(xi.encoded)),Dt})},Ji=async ft=>{var Dt;return((Dt=o[ft.encoded])==null?void 0:Dt.cwd)??await Pte(ft.path)},cn=ft=>S(ft),Tn=async ft=>{var An;let Dt=((An=o[ft.encoded])==null?void 0:An.cwd)??null;if(Dt||(Dt=await Pte(ft.path)),!Dt&&(Dt=await window.api.app.pickDirectory(),!Dt))return;const xi=crypto.randomUUID();A({id:xi,cwd:Dt,startupCommand:`claude --dangerously-skip-permissions --session-id ${im(xi)}`,presetId:"projects-tab"})},Ts=async ft=>{const Dt=await Ji(ft);if(!Dt){cn("Project directory not yet resolved");return}const xi=await window.api.app.openInEditor(Dt,Ee||null);xi.ok||cn(xi.error??"No editor found")},ds=async ft=>{const Dt=await Ji(ft);if(!Dt){cn("Project directory not yet resolved");return}const xi=await window.api.app.openInFinder(Dt);xi.ok||cn(xi.error??"Failed to open file manager")},rr=async ft=>{const Dt=await Ji(ft);if(!Dt){cn("Project directory not yet resolved");return}const xi=await window.api.app.openInTerminal(Dt);xi.ok||cn(xi.error??"No terminal emulator found")},Is=ft=>{p(ft.encoded)},vo=async ft=>{m(null),y(!0);const Dt=[];for(const xi of ft)try{const An=await window.api.app.archiveProject(xi);An.ok?Dt.push(xi):cn(An.error??`Failed to archive ${xi}`)}catch(An){cn(An instanceof Error?An.message:"Archive failed")}Dt.length&&(i(xi=>xi.filter(An=>!Dt.includes(An.encoded))),f(xi=>{const An=new Set(xi);return Dt.forEach(Ns=>An.delete(Ns)),An}),g&&Dt.includes(g)&&p(null)),y(!1)},Ko=e.length,es=e.filter(ft=>lt-ft.lastSession<Fte).length,ii=e.reduce((ft,Dt)=>ft+Dt.sessionCount,0),bi=e.reduce((ft,Dt)=>ft+Dt.sizeBytes,0),Fi=[...e].filter(ft=>lt-ft.lastSession<Fte).sort((ft,Dt)=>Dt.sessionCount-ft.sessionCount).slice(0,3),Ni=ft=>{var xi;const Dt=(xi=T.current)==null?void 0:xi.querySelector(`[data-row-key="${ft}"]`);Dt==null||Dt.scrollIntoView({behavior:"smooth",block:"center"}),D(ft),setTimeout(()=>D(null),2e3)},ys=(ft,Dt)=>v.jsx(w_,{content:`Sort by ${Dt}`,align:"bottom-center",children:v.jsxs("button",{onClick:()=>q(ft),title:`Sort by ${Dt}`,className:"flex items-center gap-1 hover:text-fg w-full uppercase tracking-wider",children:[v.jsx("span",{children:Dt}),W.col===ft&&v.jsx("span",{className:"text-[10px] leading-none",children:W.dir==="asc"?"▲":"▼"})]})}),Gr=g?((Ea=o[g])==null?void 0:Ea.cwd)??null:null,xl=g?((bo=o[g])==null?void 0:bo.cwd)??`/${Mte(g)}`:"",La=[];He&&La.push({key:"branch",header:"branch",width:"8rem",render:ft=>{const Dt=o[ft.encoded];return Dt?Dt.lastBranch?v.jsx("span",{className:"font-mono text-fg-faint truncate block",children:Dt.lastBranch}):v.jsx("span",{className:"text-fg-faint",children:"—"}):v.jsx(Ote,{})}}),st&&La.push({key:"remote",header:"remote",render:ft=>{const Dt=o[ft.encoded];return Dt?Dt.gitRemote?v.jsx("span",{className:"font-mono text-fg-faint truncate block text-[10px]",children:Dt.gitRemote}):v.jsx("span",{className:"text-fg-faint",children:"—"}):v.jsx(Ote,{})}});const fs=[{key:"select",header:v.jsx("input",{ref:N,type:"checkbox",checked:Ft,onChange:En,className:"accent-accent cursor-pointer",title:"Select all visible",onClick:ft=>ft.stopPropagation()}),width:"2rem",className:"px-1",render:ft=>v.jsx("input",{type:"checkbox",checked:h.has(ft.encoded),onChange:()=>{f(Dt=>{const xi=new Set(Dt);return xi.has(ft.encoded)?xi.delete(ft.encoded):xi.add(ft.encoded),xi})},onClick:Dt=>Dt.stopPropagation(),className:"accent-accent cursor-pointer"})},{key:"pin",header:"",width:"2rem",className:"px-1",render:ft=>v.jsx(w_,{content:P[ft.encoded]?"Unpin":"Pin to top",children:v.jsx("button",{onClick:Dt=>{Dt.stopPropagation(),B(ft.encoded)},title:P[ft.encoded]?"Unpin":"Pin to top",className:`text-sm leading-none transition-colors ${P[ft.encoded]?"text-yellow-400":"text-fg-faint hover:text-fg-dim"}`,children:P[ft.encoded]?"★":"☆"})})},{key:"path",header:ys("project","project"),render:ft=>{const Dt=o[ft.encoded],xi=(Dt==null?void 0:Dt.cwd)??`/${ft.displayPath}`,An=v.jsx("span",{className:"font-mono text-fg-dim truncate block max-w-[22rem]",children:xi});return Dt!=null&&Dt.claudemdPreview?v.jsx(w_,{content:v.jsx("span",{className:"font-mono text-[9px] whitespace-pre-wrap",children:Dt.claudemdPreview}),align:"bottom-center",children:An}):An}},{key:"name",header:"name",width:"7rem",render:ft=>{const Dt=o[ft.encoded];return Dt?v.jsx("span",{className:"text-fg-dim truncate block",children:Dt.name??"—"}):v.jsx(Ote,{})}},{key:"sessions",header:ys("sessions","sessions"),width:"6rem",render:ft=>v.jsx("span",{className:"text-fg-dim",children:ft.sessionCount})},{key:"size",header:ys("size","size"),width:"6rem",render:ft=>v.jsx("span",{className:"text-fg-faint",children:OL(ft.sizeBytes)})},{key:"last",header:ys("last","last active"),width:"9rem",render:ft=>v.jsx("span",{className:"text-fg-faint",children:bni(ft.lastSession)})},...La,{key:"action",header:"",width:"11rem",render:ft=>{const Dt=o[ft.encoded],xi=!!(Dt!=null&&Dt.claudemdPreview);return v.jsxs("div",{className:"flex items-center gap-0.5",children:[v.jsx(kT,{tip:"Open in new terminal session",onClick:()=>Tn(ft),children:"▷"}),v.jsx(kT,{tip:"Open in editor",onClick:()=>Ts(ft),children:"✏"}),v.jsx(kT,{tip:"Open in file manager",onClick:()=>ds(ft),children:"⌂"}),v.jsx(kT,{tip:"Open in terminal",onClick:()=>rr(ft),children:"⊞"}),v.jsx(kT,{tip:xi?"Preview CLAUDE.md":"No CLAUDE.md",onClick:()=>Is(ft),disabled:!xi,children:"Ⓜ"}),v.jsx(kT,{tip:"Archive project",onClick:()=>m([ft.encoded]),danger:!0,children:"⊗"})]})}}];return v.jsxs("div",{className:"h-full flex flex-col",children:[!n&&e.length>0&&v.jsxs("div",{className:"shrink-0 border-b border-line bg-bg px-3 py-1.5 flex items-center gap-4 text-[10px] text-fg-faint flex-wrap",children:[v.jsxs("span",{children:[v.jsx("span",{className:"text-fg-dim font-medium",children:Ko})," projects"]}),v.jsxs("span",{children:[v.jsx("span",{className:"text-fg-dim font-medium",children:es})," active 7d"]}),v.jsxs("span",{children:[v.jsx("span",{className:"text-fg-dim font-medium",children:ii})," sessions"]}),v.jsxs("span",{children:[v.jsx("span",{className:"text-fg-dim font-medium",children:OL(bi)})," on disk"]}),Fi.length>0&&v.jsxs("span",{className:"flex items-center gap-1 flex-wrap",children:[v.jsx("span",{className:"text-fg-faint",children:"most active:"}),Fi.map(ft=>{var xi,An,Ns;const Dt=((An=(xi=o[ft.encoded])==null?void 0:xi.cwd)==null?void 0:An.split("/").pop())??ft.displayPath.split("/").pop()??ft.encoded;return v.jsx("button",{onClick:()=>Ni(ft.encoded),className:"px-1.5 py-0 rounded border border-line hover:border-fg-faint hover:text-fg transition-colors font-mono",title:((Ns=o[ft.encoded])==null?void 0:Ns.cwd)??ft.displayPath,children:Dt},ft.encoded)})]})]}),v.jsx("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 text-xs",children:v.jsxs("div",{className:"flex flex-col gap-1.5 w-full py-0.5",children:[v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("input",{type:"search",placeholder:"search projects…",value:l,onChange:ft=>c(ft.target.value),className:"h-6 px-2 bg-bg border border-line rounded text-xs text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint w-48"}),v.jsx("span",{className:"text-fg-faint",children:Je.length===e.length?`${e.length} projects`:`${Je.length} of ${e.length}`}),v.jsx("div",{className:"flex-1"}),v.jsx(w_,{content:"Preferred editor for 'Open in editor' action",children:v.jsx("select",{value:Ee,onChange:ft=>$e(ft.target.value),className:"h-6 bg-bg border border-line rounded text-xs text-fg-dim px-1 focus:outline-none focus:border-fg-faint",children:wni.map(ft=>v.jsxs("option",{value:ft.value,children:["Editor: ",ft.label]},ft.value))})}),v.jsx("span",{className:"text-fg-faint font-mono truncate",children:"~/.claude/projects/"})]}),v.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[v.jsx(Rw,{label:"All",active:G==="all",onClick:()=>re("all"),tip:"Show all projects"}),v.jsx(Rw,{label:"≤7d",active:G==="7d",onClick:()=>re("7d"),tip:"Active in last 7 days"}),v.jsx(Rw,{label:"≤30d",active:G==="30d",onClick:()=>re("30d"),tip:"Active in last 30 days"}),v.jsx("span",{className:"w-px h-3 bg-line mx-0.5 shrink-0"}),v.jsx(Rw,{label:"Has remote",active:ie===!0,onClick:()=>K(ie===!0?null:!0),tip:"Only projects with a git remote"}),v.jsx(Rw,{label:"No remote",active:ie===!1,onClick:()=>K(ie===!1?null:!1),tip:"Only projects without a git remote"}),v.jsx("span",{className:"w-px h-3 bg-line mx-0.5 shrink-0"}),v.jsx(Rw,{label:"Has CLAUDE.md",active:Z===!0,onClick:()=>Q(Z===!0?null:!0),tip:"Only projects with a CLAUDE.md"}),v.jsx(Rw,{label:"No CLAUDE.md",active:Z===!1,onClick:()=>Q(Z===!1?null:!1),tip:"Only projects without a CLAUDE.md"}),v.jsx("span",{className:"w-px h-3 bg-line mx-0.5 shrink-0"}),v.jsx(Rw,{label:"Pinned",active:ne,onClick:()=>ge(!ne),tip:"Only pinned projects"})]})]})}),v.jsxs("div",{className:"flex-1 min-h-0 flex relative",children:[v.jsx("div",{className:"flex-1 min-w-0 overflow-auto",ref:T,children:n?v.jsx(Ui,{title:"scanning projects…"}):v.jsx(Rme,{columns:fs,rows:Ct,getKey:ft=>ft.encoded,activeKey:k,empty:"no projects with claude session history"})}),g&&Gr&&v.jsx(vni,{cwd:Gr,projectName:xl,onClose:()=>p(null)})]}),h.size>0&&v.jsxs("div",{className:"shrink-0 border-t border-line bg-bg-elev px-3 py-2 flex items-center gap-2 text-xs",children:[v.jsxs("span",{className:"text-fg-faint",children:[h.size," selected"]}),v.jsx("div",{className:"flex-1"}),b&&v.jsx("span",{className:"text-fg-faint animate-pulse",children:"archiving…"}),v.jsxs("button",{onClick:()=>m(Array.from(h)),disabled:b,className:"px-2 py-1 border border-red-900/50 text-red-400/80 rounded hover:bg-red-950/30 hover:text-red-400 disabled:opacity-40 transition-colors",children:["Archive ",h.size]}),v.jsx("button",{onClick:async()=>{const ft=e.filter(Dt=>h.has(Dt.encoded));for(const Dt of ft)await Ts(Dt)},disabled:b,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 transition-colors",children:"Open all in editor"}),v.jsx("button",{onClick:()=>f(new Set),className:"px-2 py-1 border border-line rounded text-fg-faint hover:text-fg hover:bg-bg-hi transition-colors",children:"Cancel"})]}),v.jsxs(Og,{open:!!_,onClose:()=>m(null),title:"Archive projects?",children:[v.jsxs("p",{className:"text-sm text-fg-dim mb-1",children:["Move ",(_==null?void 0:_.length)??0," project",((_==null?void 0:_.length)??0)!==1?"s":""," to"]}),v.jsx("p",{className:"text-xs text-fg-faint font-mono mb-4",children:"~/.claude/projects-archive/"}),_&&_.length<=5&&v.jsx("ul",{className:"mb-4 space-y-0.5 text-[10px] font-mono text-fg-faint",children:_.map(ft=>{var Dt;return v.jsx("li",{className:"truncate",children:((Dt=o[ft])==null?void 0:Dt.cwd)??`/${Mte(ft)}`},ft)})}),v.jsxs("div",{className:"flex gap-2 justify-end",children:[v.jsx("button",{onClick:()=>m(null),className:"px-3 py-1.5 text-xs border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"Cancel"}),v.jsx("button",{onClick:()=>_&&vo(_),className:"px-3 py-1.5 text-xs border border-red-900/50 rounded text-red-400 hover:bg-red-950/30",children:"Archive"})]})]}),x&&v.jsx("div",{role:"alert",className:"pointer-events-none fixed bottom-4 right-4 z-50 bg-red-950 border border-red-900/60 text-red-300 text-xs px-3 py-1.5 rounded shadow-lg max-w-xs",children:x})]})}const vhe="~/.config/session-manager/doc-editor.json",Cni=20;let Bte=null;function bP(s){Bte&&clearTimeout(Bte),Bte=setTimeout(async()=>{const e=s();try{const i=await window.api.config.readJson(vhe).catch(()=>null),n=(i==null?void 0:i.data)??{};await window.api.config.writeJson(vhe,{...n,recents:e.recents,openPaths:Object.keys(e.docs),viewModes:e.viewModes})}catch(i){console.warn("[docEditor] persist failed:",i)}},500)}function yAe(s,e){return[e,...s.filter(i=>i!==e)].slice(0,Cni)}const Hh=Ka((s,e)=>({docs:{},activePath:null,recents:[],viewModes:{},hydrated:!1,open:async i=>{if(e().docs[i]){s({activePath:i});return}const r=await window.api.docEditor.readFile(i);if(!r.ok){Kt.warn(`Could not open ${i.split("/").pop()}: ${r.error??"unknown error"}`),s(a=>({recents:a.recents.filter(l=>l!==i)})),bP(e);return}const o={path:i,diskText:r.text??"",bufferText:r.text??"",mtimeMs:r.mtimeMs??0,loadedAt:Date.now()};s(a=>({docs:{...a.docs,[i]:o},activePath:i,recents:yAe(a.recents,i)})),bP(e)},close:i=>{var l;const n=e(),r=n.docs[i];if(!r)return;if(r.bufferText!==r.diskText){const c=i.split("/").pop()??i;if(!window.confirm(`"${c}" has unsaved changes. Close without saving?`))return}const o={...n.docs};delete o[i];let a=n.activePath;n.activePath===i&&(a=((l=Object.values(o).sort((d,u)=>u.loadedAt-d.loadedAt)[0])==null?void 0:l.path)??null),s({docs:o,activePath:a}),bP(e)},setActive:i=>{s({activePath:i})},setViewMode:(i,n)=>{s(r=>({viewModes:{...r.viewModes,[i]:n}})),bP(e)},edit:(i,n)=>{const r=e().docs[i];r&&s(o=>({docs:{...o.docs,[i]:{...r,bufferText:n}}}))},save:async i=>{const n=e().docs[i];if(!n)return;const r=n.bufferText,o=await window.api.docEditor.writeFile(i,r);if(!o.ok){Kt.error(`Save failed for ${i.split("/").pop()}: ${o.error??"unknown"}`);return}s(a=>{const l=a.docs[i];return l?{docs:{...a.docs,[i]:{...l,diskText:r,mtimeMs:o.mtimeMs??l.mtimeMs}},recents:yAe(a.recents,i)}:{}}),bP(e)},saveAll:async()=>{const i=Object.values(e().docs).filter(n=>n.bufferText!==n.diskText).map(n=>n.path);await Promise.all(i.map(n=>e().save(n)))},hydrate:async()=>{if(!e().hydrated){s({hydrated:!0});try{const n=(await window.api.config.readJson(vhe)).data??{},r=Array.isArray(n.recents)?n.recents:[],o=Array.isArray(n.openPaths)?n.openPaths:[],a=n.viewModes??{},l={};for(const[c,d]of Object.entries(a))(d==="wysiwyg"||d==="source")&&(l[c]=d);s({recents:r,viewModes:l});for(const c of o)await e().open(c)}catch(i){console.warn("[docEditor] hydrate failed:",i)}}}}));window.__docEditor=Hh;const Sni={json:"json",ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",cjs:"javascript",mjs:"javascript",py:"python",sh:"shell",bash:"shell",yaml:"yaml",yml:"yaml",toml:"ini",css:"css",html:"html",xml:"xml",sql:"sql",rs:"rust",go:"go",md:"markdown",markdown:"markdown"},wAe={Dockerfile:"dockerfile",Makefile:"makefile"};function kni(s){const e=s.split("/").pop()??s;if(wAe[e])return wAe[e];const i=e.lastIndexOf(".");if(i===-1)return null;const n=e.slice(i+1);return Sni[n]??null}const Lni=z.lazy(()=>ei(()=>import("./TiptapBody-C46DacIO.js"),[],import.meta.url).then(s=>({default:s.TiptapBody})));function Eni(s){return s.split("/").pop()??s}function Dni(s){return s.endsWith(".md")||s.endsWith(".markdown")}function Tni({docs:s,activePath:e,onSetActive:i,onClose:n}){const r=Object.keys(s);return v.jsx("div",{className:"h-9 bg-bg-elev border-b border-line flex items-center overflow-x-auto shrink-0 px-2 gap-1","data-testid":"doc-tab-strip",children:r.map(o=>{const a=s[o],l=a.bufferText!==a.diskText,c=Eni(o),d=o===e;return v.jsxs("div",{className:`group px-3 py-1 flex items-center gap-1 rounded-t text-xs shrink-0 cursor-pointer transition-colors ${d?"bg-bg-hi text-fg font-semibold border border-b-0 border-accent border-t-2 -mb-px relative z-10":"bg-bg-elev text-fg-dim border border-line hover:text-fg hover:bg-bg"}`,onClick:()=>i(o),title:o,"data-testid":`doc-tab-${c}`,children:[l&&v.jsx("span",{className:"text-amber-400","aria-label":"unsaved changes","data-testid":"doc-tab-dirty",children:"●"}),v.jsx("span",{children:c}),v.jsx("button",{type:"button",onClick:u=>{u.stopPropagation(),n(o)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1",title:`Close ${c}`,"aria-label":`Close ${c}`,"data-testid":`doc-x-${c}`,children:"×"})]},o)})})}function Ini({path:s,value:e,onChange:i,language:n}){const r=z.useRef(null),o=z.useRef(s);o.current=s;const a=async l=>{r.current=l;const c=await ei(()=>Promise.resolve().then(()=>xme),void 0,import.meta.url);l.addCommand(c.KeyMod.CtrlCmd|c.KeyCode.KeyS,()=>{Hh.getState().save(o.current)})};return v.jsx(vU,{path:`file://${s}`,language:n,value:e,onChange:l=>i(l??""),onMount:a,theme:"vs-dark",options:{minimap:{enabled:!1},fontSize:12,fontFamily:"JetBrains Mono, ui-monospace, Menlo, monospace",lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}function Nni({path:s,value:e,onChange:i}){const n=kni(s);if(!n){const r=s.split("/").pop()??s;return v.jsx("textarea",{className:"w-full h-full resize-none bg-bg text-fg font-mono text-sm p-3 focus:outline-none leading-relaxed",value:e,onChange:o=>i(o.target.value),spellCheck:!1,"data-testid":"doc-textarea","aria-label":`Edit ${r}`},s)}return v.jsx(Ini,{path:s,value:e,onChange:i,language:n})}function Rni(){const s=Hh(m=>m.docs),e=Hh(m=>m.activePath),i=Hh(m=>m.viewModes),n=Hh(m=>m.open),r=Hh(m=>m.close),o=Hh(m=>m.setActive),a=Hh(m=>m.edit),l=Hh(m=>m.save),c=Hh(m=>m.saveAll),d=Hh(m=>m.setViewMode),u=Hh(m=>m.hydrate);z.useEffect(()=>{u()},[u]);const h=e?s[e]??null:null,f=Object.values(s).some(m=>m.bufferText!==m.diskText),g=e?i[e]??"wysiwyg":"wysiwyg",p=e?Dni(e):!1,_=async()=>{const m=e?e.split("/").slice(0,-1).join("/"):void 0,b=await window.api.docEditor.pickFile(m?{lastDir:m}:void 0);b.path&&await n(b.path)};return e===null?v.jsx(Ui,{title:"No document open",hint:v.jsxs("span",{children:["Click ",v.jsx("strong",{children:"Open…"})," or use"," ",v.jsx("kbd",{className:"px-1 py-0.5 border border-line rounded font-mono text-[10px]",children:"Cmd-K"})," ","and type ",v.jsx("code",{children:"doc:open"})]})}):v.jsxs("div",{className:"h-full flex flex-col",onKeyDown:m=>{(m.ctrlKey||m.metaKey)&&m.key.toLowerCase()==="s"&&!m.shiftKey&&(m.preventDefault(),e&&l(e)),(m.ctrlKey||m.metaKey)&&m.key.toLowerCase()==="w"&&!m.shiftKey&&(m.preventDefault(),e&&r(e))},"data-testid":"doc-editor-panel",children:[v.jsx(Tni,{docs:s,activePath:e,onSetActive:o,onClose:r}),v.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-2 text-xs",children:[v.jsx("button",{type:"button",onClick:_,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi transition-colors","data-testid":"doc-open-btn",children:"Open…"}),v.jsx("button",{type:"button",onClick:()=>e&&l(e),disabled:!h||h.bufferText===h.diskText,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi transition-colors disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"doc-save-btn",children:"Save"}),v.jsx("button",{type:"button",onClick:()=>c(),disabled:!f,className:"px-2 py-1 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi transition-colors disabled:opacity-40 disabled:cursor-not-allowed","data-testid":"doc-save-all-btn",children:"Save All"}),p&&e&&v.jsxs("div",{className:"flex items-center border border-line rounded overflow-hidden text-[11px]","data-testid":"view-mode-toggle",children:[v.jsx("button",{type:"button",onClick:()=>d(e,"wysiwyg"),className:`px-2 py-0.5 transition-colors ${g==="wysiwyg"?"bg-accent text-bg font-semibold":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,"data-testid":"view-mode-wysiwyg",children:"WYSIWYG"}),v.jsx("button",{type:"button",onClick:()=>d(e,"source"),className:`px-2 py-0.5 transition-colors ${g==="source"?"bg-accent text-bg font-semibold":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,"data-testid":"view-mode-source",children:"Source"})]}),e&&v.jsx("span",{className:"ml-2 text-fg-faint truncate flex-1 font-mono text-[11px]",title:e,children:e})]}),v.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:p&&g==="wysiwyg"&&e&&h?v.jsx(z.Suspense,{fallback:v.jsx("div",{className:"p-4 text-fg-faint text-sm",children:"Loading editor…"}),children:v.jsx(Lni,{value:h.bufferText,onChange:m=>a(e,m)},e)}):p&&e&&h?v.jsx(jy,{path:e,value:h.bufferText,onChange:m=>a(e,m)},e):e&&h?v.jsx(Nni,{path:e,value:h.bufferText,onChange:m=>a(e,m)}):null})]})}const Ani=5e3;let A6=null,yP=null;async function bhe(s){const e=Date.now();return!(s!=null&&s.fresh)&&A6&&e-A6.at<Ani?A6.result:yP||(yP=(async()=>{try{const i=await window.api.schedule.lintQueue();return A6={result:i,at:Date.now()},i}finally{yP=null}})(),yP)}const xAe=2e3;function Mni(s){return s.is_error===!0||s.error!=null&&s.error!==""||s.type==="result"&&s.subtype!=="success"&&s.subtype!=null}function Pni(s){return typeof s.error=="string"&&s.error?s.error:typeof s.result=="string"&&s.result?s.result:typeof s.subtype=="string"?s.subtype:JSON.stringify(s).slice(0,200)}function Oni(s){if(typeof s.text=="string")return s.text.slice(0,200);if(typeof s.content=="string")return s.content.slice(0,200);if(Array.isArray(s.content)){for(const i of s.content)if(i&&typeof i=="object"&&"text"in i&&typeof i.text=="string")return i.text.slice(0,200)}const e=s.message;if(e&&typeof e=="object"){const i=e;if(typeof i.content=="string")return i.content.slice(0,200);if(Array.isArray(i.content)){for(const n of i.content)if(n&&typeof n=="object"&&"text"in n&&typeof n.text=="string")return n.text.slice(0,200)}}return typeof s.result=="string"&&s.result?s.result.slice(0,200):typeof s.subtype=="string"?s.subtype:JSON.stringify(s).slice(0,200)}function Fni(s){if(!s||!s.trim())return{events:[],errors:{count:0,firstMessage:null},rawLineCount:0,truncated:!1};const i=s.split(`
|
|
4414
4414
|
`).filter(d=>d.trim().length>0),n=i.length,r=n>xAe,o=r?i.slice(0,xAe):i,a=[];let l=0,c=null;for(const d of o){let u=null;try{const h=JSON.parse(d);h!==null&&typeof h=="object"&&!Array.isArray(h)&&"type"in h&&(u=h)}catch{}if(u!==null){const h=typeof u.type=="string"?u.type:"unknown",f=Mni(u);f&&(l++,c===null&&(c=Pni(u))),a.push({type:h,raw:d,preview:Oni(u),isError:f})}else a.push({type:"raw",raw:d,preview:d.slice(0,200),isError:!1})}return{events:a,errors:{count:l,firstMessage:c},rawLineCount:n,truncated:r}}const Bni={assistant:"accent",user:"default",system:"dim",result:"warn",tool_use:"default",tool_result:"default",raw:"dim"};function jni(s){return Bni[s]??"default"}function iVe({runId:s,slug:e,title:i,onClose:n}){const[r,o]=z.useState(!0),[a,l]=z.useState(null),[c,d]=z.useState(""),[u,h]=z.useState(null),[f,g]=z.useState("parsed");return z.useEffect(()=>{o(!0),l(null),window.api.schedule.readLog(s,e).then(p=>{if(p.ok){const _=p.text??"";d(_),h(Fni(_))}else{const _=p.error??"Failed to read log";l(_),Kt.error(`Log read failed: ${_}`)}}).catch(p=>{const _=p instanceof Error?p.message:String(p);l(_),Kt.error(`Log read failed: ${_}`)}).finally(()=>o(!1))},[s,e]),v.jsx(Og,{open:!0,onClose:n,size:"xl",fillHeight:!0,noPadding:!0,title:i,children:v.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[v.jsxs("div",{className:"shrink-0 flex items-center gap-2 px-4 py-2 border-b border-line",children:[v.jsx("button",{type:"button",onClick:()=>g("parsed"),className:`text-[10px] px-2 py-0.5 rounded border ${f==="parsed"?"bg-accent/20 text-accent border-accent/40":"text-fg-faint border-line hover:text-fg-dim hover:border-fg-faint"}`,children:"Parsed"}),v.jsx("button",{type:"button",onClick:()=>g("raw"),className:`text-[10px] px-2 py-0.5 rounded border ${f==="raw"?"bg-accent/20 text-accent border-accent/40":"text-fg-faint border-line hover:text-fg-dim hover:border-fg-faint"}`,children:"Raw"}),v.jsxs("span",{className:"ml-auto text-[10px] text-fg-faint font-mono",children:[e," · ",s.slice(0,8)]}),v.jsx("button",{type:"button",onClick:n,className:"text-fg-faint hover:text-fg-dim text-sm leading-none ml-1","aria-label":"Close",children:"×"})]}),v.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[r&&v.jsx("div",{className:"flex-1 flex items-center justify-center text-[11px] text-fg-faint",children:"Loading log…"}),!r&&a&&v.jsx("div",{className:"flex-1 flex items-center justify-center",children:v.jsx("div",{className:"text-[11px] text-red-300 px-6 text-center max-w-md",children:a})}),!r&&!a&&f==="raw"&&v.jsx("pre",{className:"flex-1 overflow-auto p-4 text-[10px] font-mono text-fg-dim whitespace-pre-wrap break-all leading-relaxed",children:c||v.jsx("span",{className:"text-fg-faint italic",children:"log is empty"})}),!r&&!a&&f==="parsed"&&u&&v.jsx($ni,{parsed:u,onSwitchRaw:()=>g("raw")})]})]})})}function $ni({parsed:s,onSwitchRaw:e}){const{events:i,errors:n,rawLineCount:r,truncated:o}=s;return i.length===0?v.jsx("div",{className:"flex-1 flex items-center justify-center text-[11px] text-fg-faint italic",children:"log is empty"}):v.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[v.jsx("div",{className:`shrink-0 px-4 py-2 border-b border-line text-[11px] ${n.count>0?"bg-red-950/20":"bg-bg-elev/50"}`,children:n.count>0?v.jsxs("span",{className:"text-red-300",children:[v.jsxs("span",{className:"font-medium",children:[n.count," error",n.count===1?"":"s"," detected"]}),n.firstMessage&&v.jsx("span",{className:"text-red-300/70 ml-2 font-mono",children:n.firstMessage.slice(0,120)})]}):v.jsx("span",{className:"text-green-400/70",children:"no errors detected"})}),o&&v.jsxs("div",{className:"shrink-0 px-4 py-1.5 border-b border-line bg-yellow-950/20 text-[10px] text-yellow-400/80",children:["showing first ",i.length," of ",r," events —"," ",v.jsx("button",{type:"button",onClick:e,className:"underline hover:text-yellow-300",children:"open Raw for full"})]}),v.jsx("div",{className:"flex-1 overflow-y-auto",children:i.map((a,l)=>v.jsx(Wni,{event:a},l))})]})}function Wni({event:s}){const[e,i]=z.useState(!1),n=s.type==="raw";return v.jsxs("div",{className:`flex items-start gap-2 px-3 py-1 border-b border-line/30 cursor-pointer hover:bg-bg-hi ${s.isError?"bg-red-950/10":""}`,onClick:()=>i(r=>!r),children:[v.jsx("div",{className:"shrink-0 pt-0.5 w-16",children:n?v.jsx("span",{className:"text-[9px] text-fg-faint/50 font-mono",children:"raw"}):v.jsx(Qc,{tone:jni(s.type),className:"text-[9px]",children:s.type})}),v.jsx("div",{className:"flex-1 min-w-0",children:e?v.jsx("pre",{className:"text-[10px] font-mono text-fg-dim whitespace-pre-wrap break-all",children:s.raw}):v.jsx("span",{className:`text-[10px] truncate block ${n?"text-fg-faint/60 font-mono":"text-fg-dim"}`,children:s.preview||v.jsx("span",{className:"italic text-fg-faint/40",children:"(empty)"})})})]})}const CAe=["#6f7d52","#b85c34","#8a7a60","#e4b85a","#5f6f86","#4f7d72","#8a5a6e"];function Hni(s){let e=0;for(let i=0;i<s.length;i++)e=e*31+s.charCodeAt(i)>>>0;return e}function Vni(s,e){const i=s?s.split("/").filter(Boolean).pop()??"":e??"";return CAe[Hni(i)%CAe.length]}const zni={running:"bg-accent text-white",pending:"bg-bg text-fg-dim border border-line",completed:"bg-sage/20 text-sage",needs_review:"bg-butter/25 text-fg-dim",failed:"bg-accent/15 text-accent"},Uni={pending:"○",completed:"✓",needs_review:"!",failed:"✕"};function nVe({status:s}){const e=Uni[s];return v.jsxs("span",{className:`inline-flex items-center gap-1.5 shrink-0 px-2.5 py-1 rounded-lg min-w-[104px] justify-center text-xs font-semibold tracking-wide ${zni[s]}`,role:"status","aria-label":`Status: ${s.replace("_"," ")}`,children:[s==="running"?v.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-white animate-pulse","aria-hidden":"true"}):e&&v.jsx("span",{"aria-hidden":"true",children:e}),s.replace("_"," ")]})}function ove({cwd:s,name:e}){const i=e??(s?s.split("/").filter(Boolean).pop()??s:"—"),n=Vni(s,e);return v.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono text-xs text-fg-faint",children:[v.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:n},"aria-hidden":"true"}),i]})}function I0({label:s,children:e}){return v.jsxs("div",{children:[v.jsx("div",{className:"text-[11px] font-bold tracking-[0.7px] uppercase text-fg-faint mb-2",children:s}),v.jsx("div",{className:"grid gap-1.5",children:e})]})}function fc({k:s,v:e,wrap:i}){return v.jsxs("div",{className:"flex gap-2 font-mono text-xs leading-relaxed",children:[v.jsx("span",{className:"text-fg-faint shrink-0 w-14",children:s}),v.jsx("span",{className:`text-fg ${i?"break-all":""}`,children:e})]})}function jte({dotClass:s,n:e,label:i}){return v.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[13px] text-fg-dim",children:[v.jsx("span",{className:`w-2 h-2 rounded-full ${s}`,"aria-hidden":"true"}),v.jsx("strong",{className:"text-fg font-mono text-[13.5px]",children:e})," ",i]})}const qni={running:{bg:"bg-butter/30",text:"text-fg-dim",border:!1,label:"running"},queued:{bg:"bg-sage/25",text:"text-sage",border:!1,label:"queued"},ready:{bg:"bg-bg",text:"text-fg-dim",border:!0,label:"ready to run"},draft:{bg:"bg-bg",text:"text-fg-faint",border:!0,label:"draft"}},Gni=5,Kni=1440*60*1e3,sVe="sm.scheduler.hiddenCompletedSlugs",$te="sm.scheduler.focusedJobIndex",rVe="sm.scheduler.queueFilter",Yni=["all","running","pending","completed","needs_review","failed"];function Xni(){try{const s=localStorage.getItem(rVe);if(!s)return{text:"",status:"all"};const e=JSON.parse(s);return{text:"",status:Yni.includes(e.status)?e.status:"all"}}catch{return{text:"",status:"all"}}}function Zni(s){try{localStorage.setItem(rVe,JSON.stringify({status:s.status}))}catch{}}function Qni(s,e){if(e.status==="all"&&!e.text)return s;const i=e.text.toLowerCase();return s.filter(n=>{if(e.status!=="all"&&n.status!==e.status)return!1;if(!i)return!0;const r=esi(n.cwd)??"";return n.title.toLowerCase().includes(i)||n.slug.toLowerCase().includes(i)||r.toLowerCase().includes(i)})}const SAe={halt:"verifier halted",deps_unmet:"dependencies unmet",transcript_errors:"transcript had errors",verify_unavailable:"verify unavailable",uncommitted_changes:"uncommitted changes"};function Jni(){try{const s=localStorage.getItem(sVe);if(!s)return new Set;const e=JSON.parse(s);return Array.isArray(e)?new Set(e.filter(i=>typeof i=="string")):new Set}catch{return new Set}}function kAe(s){try{localStorage.setItem(sVe,JSON.stringify([...s]))}catch{}}function esi(s){if(!s)return null;const e=s.replace(/\/+$/,"").split("/");return e[e.length-1]||s}function tsi(){const s=D1(Ee=>Ee.snapshot),[e,i]=z.useState(null),[n,r]=z.useState(!1),[o,a]=z.useState(()=>Date.now()),[l,c]=z.useState(()=>Jni()),[d,u]=z.useState(!1),[h,f]=z.useState(()=>Xni()),[g,p]=z.useState(!1),[_,m]=z.useState("queue"),b=z.useRef(null),[y,x]=z.useState(()=>{try{return Number(localStorage.getItem($te))||0}catch{return 0}}),[S,k]=z.useState("");z.useEffect(()=>(window.api.schedule.health().then(i).catch(()=>{}),window.api.schedule.onState(()=>{window.api.schedule.health().then(i).catch(()=>{})})),[]),z.useEffect(()=>{const Ee=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(Ee)},[]);const D=z.useMemo(()=>{if(!s)return 15e4;const Ee=[];for(const $e of s.jobs)if($e.status==="completed"&&$e.startedAt&&$e.finishedAt){const De=Date.parse($e.finishedAt)-Date.parse($e.startedAt);De>0&&Ee.push(De)}return Ee.length===0?15e4:Ee.reduce(($e,De)=>$e+De,0)/Ee.length},[s]),T=z.useRef(new Map);if(z.useEffect(()=>{if(!s)return;const Ee=[];for(const $e of s.jobs){const De=T.current.get($e.slug);De&&De!==$e.status&&Ee.push(`${$e.title}: ${De} → ${$e.status}`),T.current.set($e.slug,$e.status)}Ee.length>0&&k(Ee.join("; "))},[s]),!s)return null;if(_==="supervisor")return v.jsx(dsi,{supervisorConfig:s.config.supervisor,onSetConfig:Ee=>window.api.schedule.setConfig({supervisor:Ee}),onBack:()=>m("queue")});const{config:N,jobs:A,paused:O,lastRunAt:$,nextReset:P}=s,B={pending:0,running:0,completed:0,needs_review:0,failed:0};for(const Ee of A)Ee.status in B&&B[Ee.status]++;const W=A.filter(Ee=>Ee.status==="running"),q=isi({snap:s,now:o,avgDurationMs:D,runningJobs:W}),G=Qni(A,h),re=nsi(G),{inline:ie,collapsedCount:K}=ssi(G,l,o,d),Z=()=>{const Ee=new Set(l);for(const $e of A)($e.status==="completed"||$e.status==="failed")&&Ee.add($e.slug);c(Ee),kAe(Ee)},Q=async()=>{const Ee=A.filter(ae=>ae.status!=="running").length;if(Ee===0)return;const $e=`Archive ${Ee} non-running PRD${Ee===1?"":"s"} and remove from the queue?
|
|
4415
4415
|
|
|
4416
4416
|
Files are moved to prds-archived/<timestamp>/ and can be restored from disk. Running jobs are kept.`;if(!window.confirm($e))return;const De=await window.api.schedule.clearQueue();De.ok||Kt.error(`Clear queue failed: ${De.error??"unknown error"}`)},ne=()=>{c(new Set),kAe(new Set),u(!1)},ge=ie.some(Ee=>Ee.status==="completed"),Se=z.useCallback(Ee=>{var De,ae,Te;const $e=(De=b.current)==null?void 0:De.querySelectorAll("[data-job-row]");if(!(!$e||$e.length===0)){if(Ee.key==="ArrowDown"){Ee.preventDefault();const Ie=Math.min(y+1,$e.length-1);x(Ie);try{localStorage.setItem($te,String(Ie))}catch{}(ae=$e[Ie])==null||ae.focus()}else if(Ee.key==="ArrowUp"){Ee.preventDefault();const Ie=Math.max(y-1,0);x(Ie);try{localStorage.setItem($te,String(Ie))}catch{}(Te=$e[Ie])==null||Te.focus()}}},[y]);return v.jsxs("div",{className:"overflow-y-auto h-full",children:[v.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:S}),v.jsxs("div",{className:"px-9 py-6 max-w-[1100px] mx-auto space-y-4",children:[v.jsxs("div",{className:`flex flex-wrap items-center gap-3 px-4 py-3 rounded-xl border ${osi(q.kind)}`,title:q.tooltip,children:[v.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[v.jsx(rsi,{kind:q.kind}),v.jsxs("div",{className:"min-w-0",children:[v.jsx("div",{className:"text-[13px] font-medium text-fg truncate",children:q.line1}),q.line2&&v.jsx("div",{className:"text-[11.5px] text-fg-faint font-mono mt-0.5 truncate",children:q.line2})]})]}),q.action&&v.jsx("button",{type:"button",onClick:q.action.onClick,className:"text-[12px] px-3 py-1.5 border border-line hover:border-fg-faint rounded-lg shrink-0 hover:bg-bg-hi text-fg-dim hover:text-fg",title:q.action.title,children:q.action.label})]}),e&&e.consecutiveFailures>5&&e.lastFailureKind==="meter_rate_limited"&&!O&&!g&&v.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 bg-amber-400/15 border border-amber-400/30 rounded-xl",children:[v.jsx("span",{className:"text-[12.5px] text-amber-400 font-medium",children:"Meter rate-limited — firing on heuristic"}),v.jsx("button",{type:"button",onClick:()=>p(!0),className:"text-[12px] text-amber-400/70 hover:text-amber-400 shrink-0",title:"Dismiss this banner. The scheduler continues firing normally.",children:"Dismiss"})]}),v.jsxs("div",{className:"flex items-center gap-[18px] flex-wrap bg-bg-elev border border-line rounded-xl px-4 py-3",children:[v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("span",{className:"text-[13px] text-fg-dim",children:"Start jobs"}),v.jsxs("select",{value:N.firePolicy??"when-available",onChange:Ee=>window.api.schedule.setConfig({firePolicy:Ee.target.value}),className:"appearance-none border border-line bg-bg-hi rounded-lg px-2.5 py-1.5 font-sans text-[13px] text-fg font-medium",title:"when-available: poll usage and fire when tokens are below threshold. on-reset: fire after each 5h reset. manual: only on Run now.",children:[v.jsx("option",{value:"when-available",children:"when available"}),v.jsx("option",{value:"on-reset",children:"only on reset"}),v.jsx("option",{value:"manual",children:"manually"})]})]}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("span",{className:"text-[13px] text-fg-dim",children:"Up to"}),v.jsx("input",{type:"number",min:1,max:20,value:N.concurrencyCap,onChange:Ee=>window.api.schedule.setConfig({concurrencyCap:Number(Ee.target.value)}),className:"w-11 text-center border border-line bg-bg-hi rounded-lg py-1.5 font-mono text-[13px] text-fg",title:"Max simultaneous jobs within a parallel group"}),v.jsx("span",{className:"text-[13px] text-fg-dim",children:"at once"})]}),(N.firePolicy??"when-available")==="when-available"&&v.jsxs("div",{className:"flex items-center gap-2",children:[v.jsx("span",{className:"text-[13px] text-fg-dim",children:"Pause above"}),v.jsx("input",{type:"number",min:0,max:100,value:N.utilizationThreshold??90,onChange:Ee=>window.api.schedule.setConfig({utilizationThreshold:Number(Ee.target.value)}),className:"w-11 text-center border border-line bg-bg-hi rounded-lg py-1.5 font-mono text-[13px] text-fg",title:"Fire only when 5h utilization is below this percent"}),v.jsx("span",{className:"text-[13px] text-fg-dim",children:"% of window"})]}),v.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[v.jsx("button",{type:"button",onClick:()=>window.api.schedule.forceTick(),disabled:B.pending===0&&B.running===0,className:"bg-accent text-white rounded-lg px-4 py-2 text-[13px] font-semibold whitespace-nowrap disabled:opacity-40 disabled:cursor-not-allowed hover:opacity-90",title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress.",children:"Fire next batch now"}),v.jsx("button",{type:"button",onClick:()=>window.api.schedule.rescan(),className:"bg-bg-hi border border-line text-fg-dim hover:text-fg rounded-lg px-3.5 py-2 text-[13px] font-medium",title:"Re-scan the prds/ folder. Use when you've added or edited PRDs on disk and want the queue to reflect them immediately.",children:"Refresh"})]})]}),W.length>0&&(()=>{var ae;const Ee=N.concurrencyCap??4,$e=(ae=W[0])==null?void 0:ae.parallelGroup,De=A.filter(Te=>Te.status==="pending"&&Te.parallelGroup===$e).length;return v.jsxs("div",{className:"flex items-center gap-2 text-[12px] font-mono",children:[v.jsxs("span",{className:"px-2 py-0.5 rounded bg-amber-400/20 text-amber-400 shrink-0",children:[W.length,"/",Ee," running"]}),De>0&&v.jsxs("span",{className:"text-fg-faint",children:["+",De," ready in this group"]})]})})(),A.length>0&&v.jsx(csi,{filter:h,onChange:Ee=>{f(Ee),Zni(Ee)}}),v.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[v.jsxs("div",{className:"flex items-center justify-between px-[18px] py-3 bg-bg-elev",children:[v.jsxs("span",{className:"font-serif text-base font-semibold text-fg",children:[G.length," job",G.length!==1?"s":""]}),v.jsxs("div",{className:"flex items-center gap-3",children:[v.jsxs("span",{className:"font-mono text-[12px] text-fg-faint",children:[B.pending,"p · ",B.running,"r · ",B.completed,"d",B.failed>0&&v.jsxs("span",{className:"text-accent",children:[" · ",B.failed,"f"]})]}),ge&&v.jsx("button",{type:"button",onClick:Z,className:"text-[12.5px] text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer font-medium",title:"Hide completed jobs from this view (queue.json unchanged — they remain in history)",children:"Clear completed"}),v.jsx("button",{type:"button",onClick:Q,disabled:A.every(Ee=>Ee.status==="running"),className:"text-[12.5px] text-fg-dim hover:text-accent bg-transparent border-0 cursor-pointer font-medium disabled:opacity-40 disabled:cursor-not-allowed",title:"Archive every non-running PRD (moved to prds-archived/<timestamp>/) and remove them from the queue. Running jobs are kept.",children:"Clear queue"})]})]}),A.length===0&&v.jsxs("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint italic",children:["No PRDs queued. Drop .md files in:",v.jsx("button",{type:"button",onClick:()=>window.api.schedule.openFolder(),className:"block mt-1 text-fg-dim hover:text-fg underline truncate w-full text-left",children:"~/.claude/session-manager/scheduled-plans/prds/"})]}),A.length>0&&ie.length===0&&K===0&&v.jsx("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint italic",children:"no matching jobs"}),v.jsx("div",{ref:b,role:"list","aria-label":"Job queue",onKeyDown:Se,children:ie.map((Ee,$e)=>v.jsx(lsi,{job:Ee,eta:asi(Ee,A,re.get(Ee.slug)??0,D,q.kind,o),now:o,avgDurationMs:D,listIndex:$e},Ee.slug))}),K>0&&v.jsxs("button",{type:"button",onClick:()=>u(Ee=>!Ee),className:"w-full text-left text-[12px] text-fg-faint hover:text-fg-dim px-[18px] py-3 border-t border-line",title:d?"Re-collapse old/cleared completed":"Show all completed (incl. cleared and >24h)",children:[d?"▾":"▸"," ",K," more completed",l.size>0&&v.jsx("span",{className:"ml-2 underline",onClick:Ee=>{Ee.stopPropagation(),ne()},children:"un-hide"})]})]}),v.jsx(fsi,{snap:s}),v.jsx(hsi,{health:e,now:o,showHealth:n,setShowHealth:r}),v.jsxs("div",{className:"flex items-center justify-between text-[12px] text-fg-faint pt-1 border-t border-line",children:[v.jsxs("span",{children:[P&&v.jsxs("span",{title:`next 5h reset: ${P}`,children:["reset ",R_(Date.parse(P)-o)]}),$&&v.jsxs("span",{className:"ml-2",title:$,children:["last run ",R_(o-Date.parse($))," ago"]})]}),v.jsxs("div",{className:"flex items-center gap-3",children:[v.jsx("button",{type:"button",onClick:()=>m("supervisor"),className:"hover:text-fg-dim underline",title:"Open supervisor log and settings",children:"supervisor"}),v.jsx("button",{type:"button",onClick:()=>window.api.schedule.openFolder(),className:"hover:text-fg-dim underline",children:"folder"})]})]})]})]})}function isi({snap:s,now:e,avgDurationMs:i,runningJobs:n}){const{config:r,jobs:o,paused:a,nextReset:l,utilization:c}=s;let d=0,u=0;for(const m of o)m.status==="pending"?d++:m.status==="completed"&&u++;const h=n.length,f=d+h,g=r.concurrencyCap??4;if(h>0){const m=n.reduce((k,D)=>(k.startedAt??"")<(D.startedAt??"")?k:D),b=m.startedAt?e-Date.parse(m.startedAt):0,y=u+h,x=u+f,S=h>1?` · ${h}/${g} parallel`:"";return{kind:"running",line1:`Running ${y}/${x}${S} · ${J5(b)}`,line2:h===1?m.title:n.map(k=>k.title).join(", "),tooltip:n.map(k=>`${k.slug} (g${k.parallelGroup})`).join("; ")}}if(a){const m=a.resumeAt?Date.parse(a.resumeAt)-e:null;return{kind:"paused",line1:{rate_limit:"Paused — tokens exhausted",auth:"Paused — authentication failed",network:"Paused — network unreachable",reset_failure:"Paused — billing data unavailable",manual:"Paused — manual"}[a.reason]??`Paused — ${a.reason}`,line2:a.reason==="auth"?"Run `claude` in any terminal to refresh credentials, then Resume":m!==null&&m>0?`auto-resume ${f2(Date.parse(a.resumeAt))} (in ${R_(m)})`:a.resumeAt?"resuming…":"no auto-resume scheduled",tooltip:a.resumeAt??"",action:{label:"Resume",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately"}}}if(f===0)return{kind:"idle",line1:"No work queued",line2:null};const p=r.firePolicy??"when-available";if(p==="manual")return{kind:"manual",line1:`Manual · ${d} pending`,line2:"click Fire next batch now to fire",action:{label:"Fire next batch now",onClick:()=>window.api.schedule.forceTick(),title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress."}};if(p==="on-reset"){if(!l)return{kind:"on-reset",line1:"On-reset · waiting for billing data",line2:null};const m=Date.parse(l)+r.offsetMinutes*6e4,b=m-e;return{kind:"on-reset",line1:`On-reset · ${d} pending`,line2:b>0?`fires ${f2(m)} (in ${R_(b)})`:"firing now…"}}const _=r.utilizationThreshold??90;if(c==null)return{kind:"auto-soon",line1:`Auto · ${d} pending`,line2:"checking token availability…"};if(c>=_){const m=l?Date.parse(l)-e:null;return{kind:"auto-throttled",line1:`Auto · throttled (util ${c.toFixed(0)}% ≥ ${_}%)`,line2:m&&m>0?`next reset ${f2(Date.parse(l))} (in ${R_(m)})`:"will fire when usage drops"}}return{kind:"auto-soon",line1:`Auto · ${d} pending · util ${c.toFixed(0)}%`,line2:"fires within 2 min (poll cycle)"}}function nsi(s){const e=s.filter(n=>n.status==="running"||n.status==="pending").sort((n,r)=>n.parallelGroup-r.parallelGroup||n.slug.localeCompare(r.slug)),i=new Map;return e.forEach((n,r)=>i.set(n.slug,r)),i}function ssi(s,e,i,n){if(n)return{inline:s,collapsedCount:0};const r=s.filter(d=>d.status==="completed").sort((d,u)=>{const h=d.finishedAt?Date.parse(d.finishedAt):0;return(u.finishedAt?Date.parse(u.finishedAt):0)-h}),o=new Set;let a=0;for(const d of r){if(a>=Gni)break;e.has(d.slug)||d.finishedAt&&i-Date.parse(d.finishedAt)>Kni||(o.add(d.slug),a++)}const l=[];let c=0;for(const d of s){if(d.status==="failed"&&e.has(d.slug)){c++;continue}if(d.status!=="completed"){l.push(d);continue}o.has(d.slug)?l.push(d):c++}return{inline:l,collapsedCount:c}}function rsi({kind:s}){return s==="running"?v.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-400 animate-pulse shrink-0"}):s==="paused"?v.jsx("span",{className:"text-[13px] shrink-0",title:"paused",children:"⏸"}):s==="manual"?v.jsx("span",{className:"text-[13px] shrink-0",title:"manual",children:"✋"}):s==="on-reset"||s==="auto-soon"?v.jsx("span",{className:"text-[13px] shrink-0",title:"auto",children:"⏰"}):s==="auto-throttled"?v.jsx("span",{className:"text-[13px] shrink-0",title:"throttled",children:"⏳"}):v.jsx("span",{className:"w-2 h-2 rounded-full bg-fg-faint/40 shrink-0"})}function osi(s){return s==="running"?"bg-amber-400/10 border-amber-400/25":s==="paused"?"bg-amber-500/10 border-amber-500/25":s==="auto-throttled"?"bg-amber-500/5 border-amber-500/15":"bg-bg-elev border-line"}function asi(s,e,i,n,r,o){if(s.status!=="pending"||r==="paused"||r==="manual"||r==="auto-throttled")return null;let a=i*n;if(i>0){const l=e.find(c=>c.status==="running"&&c.startedAt);l&&l.startedAt&&(a-=Math.min(n,o-Date.parse(l.startedAt)))}return a<=5e3?"~now":`~${J5(a)}`}function lsi({job:s,eta:e,now:i,avgDurationMs:n,listIndex:r}){const[o,a]=z.useState(!1),[l,c]=z.useState(!1),d=s.status==="running",u=s.status==="failed";let h=null;d&&s.startedAt?h=`${kNe(i-Date.parse(s.startedAt))} elapsed`:s.status==="completed"&&s.startedAt&&s.finishedAt?h=`took ${J5(Date.parse(s.finishedAt)-Date.parse(s.startedAt))}`:e&&(h=e);const f=s.error??null,g=u&&f?f.split(`
|