claude-code-session-manager 0.38.1 → 0.38.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{TiptapBody-DlPTesio.js → TiptapBody-UWL5KIJG.js} +1 -1
- package/dist/assets/{index-CBSyk1aI.js → index-CZPF8Qve.js} +35 -35
- package/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/main/__tests__/scheduler-notify-originating-tab.test.cjs +99 -0
- package/src/main/chatRunner.cjs +44 -0
- package/src/main/index.cjs +2 -1
- package/src/main/ipcSchemas.cjs +20 -0
- package/src/main/lib/prdCreate.cjs +4 -1
- package/src/main/scheduler/prdParser.cjs +5 -0
- package/src/main/scheduler.cjs +69 -1
- package/src/main/webRemote.cjs +10 -0
- package/src/preload/api.d.ts +11 -0
- package/src/preload/index.cjs +7 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./TiptapBody-UWL5KIJG.js","./monaco-editor-BW5C4Iv1.js","./monaco-editor-BTnBOi8r.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
var vN=Object.defineProperty;var bN=(e,n,r)=>n in e?vN(e,n,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[n]=r;var Fn=(e,n,r)=>bN(e,typeof n!="symbol"?n+"":n,r);import{_ as Jm}from"./monaco-editor-BW5C4Iv1.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))i(o);new MutationObserver(o=>{for(const l of o)if(l.type==="childList")for(const d of l.addedNodes)d.tagName==="LINK"&&d.rel==="modulepreload"&&i(d)}).observe(document,{childList:!0,subtree:!0});function r(o){const l={};return o.integrity&&(l.integrity=o.integrity),o.referrerPolicy&&(l.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?l.credentials="include":o.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function i(o){if(o.ep)return;o.ep=!0;const l=r(o);fetch(o.href,l)}})();function Gy(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var kv={exports:{}},Bp={},Sv={exports:{}},pn={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react.production.min.js
|
|
@@ -15,7 +15,7 @@ var vN=Object.defineProperty;var bN=(e,n,r)=>n in e?vN(e,n,{enumerable:!0,config
|
|
|
15
15
|
*
|
|
16
16
|
* This source code is licensed under the MIT license found in the
|
|
17
17
|
* LICENSE file in the root directory of this source tree.
|
|
18
|
-
*/var J0;function _N(){if(J0)return Bp;J0=1;var e=Xw(),n=Symbol.for("react.element"),r=Symbol.for("react.fragment"),i=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function d(u,h,m){var x,g={},v=null,S=null;m!==void 0&&(v=""+m),h.key!==void 0&&(v=""+h.key),h.ref!==void 0&&(S=h.ref);for(x in h)i.call(h,x)&&!l.hasOwnProperty(x)&&(g[x]=h[x]);if(u&&u.defaultProps)for(x in h=u.defaultProps,h)g[x]===void 0&&(g[x]=h[x]);return{$$typeof:n,type:u,key:v,ref:S,props:g,_owner:o.current}}return Bp.Fragment=r,Bp.jsx=d,Bp.jsxs=d,Bp}var Q0;function kN(){return Q0||(Q0=1,kv.exports=_N()),kv.exports}var s=kN(),ix={},Cv={exports:{}},
|
|
18
|
+
*/var J0;function _N(){if(J0)return Bp;J0=1;var e=Xw(),n=Symbol.for("react.element"),r=Symbol.for("react.fragment"),i=Object.prototype.hasOwnProperty,o=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,l={key:!0,ref:!0,__self:!0,__source:!0};function d(u,h,m){var x,g={},v=null,S=null;m!==void 0&&(v=""+m),h.key!==void 0&&(v=""+h.key),h.ref!==void 0&&(S=h.ref);for(x in h)i.call(h,x)&&!l.hasOwnProperty(x)&&(g[x]=h[x]);if(u&&u.defaultProps)for(x in h=u.defaultProps,h)g[x]===void 0&&(g[x]=h[x]);return{$$typeof:n,type:u,key:v,ref:S,props:g,_owner:o.current}}return Bp.Fragment=r,Bp.jsx=d,Bp.jsxs=d,Bp}var Q0;function kN(){return Q0||(Q0=1,kv.exports=_N()),kv.exports}var s=kN(),ix={},Cv={exports:{}},mi={},jv={exports:{}},Ev={};/**
|
|
19
19
|
* @license React
|
|
20
20
|
* scheduler.production.min.js
|
|
21
21
|
*
|
|
@@ -31,20 +31,20 @@ var vN=Object.defineProperty;var bN=(e,n,r)=>n in e?vN(e,n,{enumerable:!0,config
|
|
|
31
31
|
*
|
|
32
32
|
* This source code is licensed under the MIT license found in the
|
|
33
33
|
* LICENSE file in the root directory of this source tree.
|
|
34
|
-
*/var t_;function jN(){if(t_)return
|
|
34
|
+
*/var t_;function jN(){if(t_)return mi;t_=1;var e=Xw(),n=CN();function r(c){for(var p="https://reactjs.org/docs/error-decoder.html?invariant="+c,k=1;k<arguments.length;k++)p+="&args[]="+encodeURIComponent(arguments[k]);return"Minified React error #"+c+"; visit "+p+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var i=new Set,o={};function l(c,p){d(c,p),d(c+"Capture",p)}function d(c,p){for(o[c]=p,c=0;c<p.length;c++)i.add(p[c])}var u=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),h=Object.prototype.hasOwnProperty,m=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,x={},g={};function v(c){return h.call(g,c)?!0:h.call(x,c)?!1:m.test(c)?g[c]=!0:(x[c]=!0,!1)}function S(c,p,k,M){if(k!==null&&k.type===0)return!1;switch(typeof p){case"function":case"symbol":return!0;case"boolean":return M?!1:k!==null?!k.acceptsBooleans:(c=c.toLowerCase().slice(0,5),c!=="data-"&&c!=="aria-");default:return!1}}function E(c,p,k,M){if(p===null||typeof p>"u"||S(c,p,k,M))return!0;if(M)return!1;if(k!==null)switch(k.type){case 3:return!p;case 4:return p===!1;case 5:return isNaN(p);case 6:return isNaN(p)||1>p}return!1}function j(c,p,k,M,F,K,de){this.acceptsBooleans=p===2||p===3||p===4,this.attributeName=M,this.attributeNamespace=F,this.mustUseProperty=k,this.propertyName=c,this.type=p,this.sanitizeURL=K,this.removeEmptyString=de}var y={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(c){y[c]=new j(c,0,!1,c,null,!1,!1)}),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(c){var p=c[0];y[p]=new j(p,1,!1,c[1],null,!1,!1)}),["contentEditable","draggable","spellCheck","value"].forEach(function(c){y[c]=new j(c,2,!1,c.toLowerCase(),null,!1,!1)}),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(c){y[c]=new j(c,2,!1,c,null,!1,!1)}),"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(c){y[c]=new j(c,3,!1,c.toLowerCase(),null,!1,!1)}),["checked","multiple","muted","selected"].forEach(function(c){y[c]=new j(c,3,!0,c,null,!1,!1)}),["capture","download"].forEach(function(c){y[c]=new j(c,4,!1,c,null,!1,!1)}),["cols","rows","size","span"].forEach(function(c){y[c]=new j(c,6,!1,c,null,!1,!1)}),["rowSpan","start"].forEach(function(c){y[c]=new j(c,5,!1,c.toLowerCase(),null,!1,!1)});var b=/[\-:]([a-z])/g;function _(c){return c[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(c){var p=c.replace(b,_);y[p]=new j(p,1,!1,c,null,!1,!1)}),"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(c){var p=c.replace(b,_);y[p]=new j(p,1,!1,c,"http://www.w3.org/1999/xlink",!1,!1)}),["xml:base","xml:lang","xml:space"].forEach(function(c){var p=c.replace(b,_);y[p]=new j(p,1,!1,c,"http://www.w3.org/XML/1998/namespace",!1,!1)}),["tabIndex","crossOrigin"].forEach(function(c){y[c]=new j(c,1,!1,c.toLowerCase(),null,!1,!1)}),y.xlinkHref=new j("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1),["src","href","action","formAction"].forEach(function(c){y[c]=new j(c,1,!1,c.toLowerCase(),null,!0,!0)});function C(c,p,k,M){var F=y.hasOwnProperty(p)?y[p]:null;(F!==null?F.type!==0:M||!(2<p.length)||p[0]!=="o"&&p[0]!=="O"||p[1]!=="n"&&p[1]!=="N")&&(E(p,k,F,M)&&(k=null),M||F===null?v(p)&&(k===null?c.removeAttribute(p):c.setAttribute(p,""+k)):F.mustUseProperty?c[F.propertyName]=k===null?F.type===3?!1:"":k:(p=F.attributeName,M=F.attributeNamespace,k===null?c.removeAttribute(p):(F=F.type,k=F===3||F===4&&k===!0?"":""+k,M?c.setAttributeNS(M,p,k):c.setAttribute(p,k))))}var N=e.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,$=Symbol.for("react.element"),R=Symbol.for("react.portal"),O=Symbol.for("react.fragment"),I=Symbol.for("react.strict_mode"),z=Symbol.for("react.profiler"),U=Symbol.for("react.provider"),W=Symbol.for("react.context"),Y=Symbol.for("react.forward_ref"),V=Symbol.for("react.suspense"),H=Symbol.for("react.suspense_list"),te=Symbol.for("react.memo"),ae=Symbol.for("react.lazy"),oe=Symbol.for("react.offscreen"),ie=Symbol.iterator;function X(c){return c===null||typeof c!="object"?null:(c=ie&&c[ie]||c["@@iterator"],typeof c=="function"?c:null)}var Q=Object.assign,J;function le(c){if(J===void 0)try{throw Error()}catch(k){var p=k.stack.trim().match(/\n( *(at )?)/);J=p&&p[1]||""}return`
|
|
35
35
|
`+J+c}var ce=!1;function pe(c,p){if(!c||ce)return"";ce=!0;var k=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(p)if(p=function(){throw Error()},Object.defineProperty(p.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(p,[])}catch(qe){var M=qe}Reflect.construct(c,[],p)}else{try{p.call()}catch(qe){M=qe}c.call(p.prototype)}else{try{throw Error()}catch(qe){M=qe}c()}}catch(qe){if(qe&&M&&typeof qe.stack=="string"){for(var F=qe.stack.split(`
|
|
36
36
|
`),K=M.stack.split(`
|
|
37
37
|
`),de=F.length-1,_e=K.length-1;1<=de&&0<=_e&&F[de]!==K[_e];)_e--;for(;1<=de&&0<=_e;de--,_e--)if(F[de]!==K[_e]){if(de!==1||_e!==1)do if(de--,_e--,0>_e||F[de]!==K[_e]){var $e=`
|
|
38
|
-
`+F[de].replace(" at new "," at ");return c.displayName&&$e.includes("<anonymous>")&&($e=$e.replace("<anonymous>",c.displayName)),$e}while(1<=de&&0<=_e);break}}}finally{ce=!1,Error.prepareStackTrace=k}return(c=c?c.displayName||c.name:"")?le(c):""}function Ae(c){switch(c.tag){case 5:return le(c.type);case 16:return le("Lazy");case 13:return le("Suspense");case 19:return le("SuspenseList");case 0:case 2:case 15:return c=pe(c.type,!1),c;case 11:return c=pe(c.type.render,!1),c;case 1:return c=pe(c.type,!0),c;default:return""}}function Se(c){if(c==null)return null;if(typeof c=="function")return c.displayName||c.name||null;if(typeof c=="string")return c;switch(c){case O:return"Fragment";case R:return"Portal";case z:return"Profiler";case I:return"StrictMode";case V:return"Suspense";case H:return"SuspenseList"}if(typeof c=="object")switch(c.$$typeof){case W:return(c.displayName||"Context")+".Consumer";case U:return(c._context.displayName||"Context")+".Provider";case Y:var p=c.render;return c=c.displayName,c||(c=p.displayName||p.name||"",c=c!==""?"ForwardRef("+c+")":"ForwardRef"),c;case te:return p=c.displayName||null,p!==null?p:Se(c.type)||"Memo";case ae:p=c._payload,c=c._init;try{return Se(c(p))}catch{}}return null}function ye(c){var p=c.type;switch(c.tag){case 24:return"Cache";case 9:return(p.displayName||"Context")+".Consumer";case 10:return(p._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return c=p.render,c=c.displayName||c.name||"",p.displayName||(c!==""?"ForwardRef("+c+")":"ForwardRef");case 7:return"Fragment";case 5:return p;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Se(p);case 8:return p===I?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof p=="function")return p.displayName||p.name||null;if(typeof p=="string")return p}return null}function ne(c){switch(typeof c){case"boolean":case"number":case"string":case"undefined":return c;case"object":return c;default:return""}}function we(c){var p=c.type;return(c=c.nodeName)&&c.toLowerCase()==="input"&&(p==="checkbox"||p==="radio")}function Ne(c){var p=we(c)?"checked":"value",k=Object.getOwnPropertyDescriptor(c.constructor.prototype,p),M=""+c[p];if(!c.hasOwnProperty(p)&&typeof k<"u"&&typeof k.get=="function"&&typeof k.set=="function"){var F=k.get,K=k.set;return Object.defineProperty(c,p,{configurable:!0,get:function(){return F.call(this)},set:function(de){M=""+de,K.call(this,de)}}),Object.defineProperty(c,p,{enumerable:k.enumerable}),{getValue:function(){return M},setValue:function(de){M=""+de},stopTracking:function(){c._valueTracker=null,delete c[p]}}}}function Je(c){c._valueTracker||(c._valueTracker=Ne(c))}function lt(c){if(!c)return!1;var p=c._valueTracker;if(!p)return!0;var k=p.getValue(),M="";return c&&(M=we(c)?c.checked?"true":"false":c.value),c=M,c!==k?(p.setValue(c),!0):!1}function xt(c){if(c=c||(typeof document<"u"?document:void 0),typeof c>"u")return null;try{return c.activeElement||c.body}catch{return c.body}}function Rt(c,p){var k=p.checked;return Q({},p,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:k??c._wrapperState.initialChecked})}function He(c,p){var k=p.defaultValue==null?"":p.defaultValue,M=p.checked!=null?p.checked:p.defaultChecked;k=ne(p.value!=null?p.value:k),c._wrapperState={initialChecked:M,initialValue:k,controlled:p.type==="checkbox"||p.type==="radio"?p.checked!=null:p.value!=null}}function vt(c,p){p=p.checked,p!=null&&C(c,"checked",p,!1)}function st(c,p){vt(c,p);var k=ne(p.value),M=p.type;if(k!=null)M==="number"?(k===0&&c.value===""||c.value!=k)&&(c.value=""+k):c.value!==""+k&&(c.value=""+k);else if(M==="submit"||M==="reset"){c.removeAttribute("value");return}p.hasOwnProperty("value")?sn(c,p.type,k):p.hasOwnProperty("defaultValue")&&sn(c,p.type,ne(p.defaultValue)),p.checked==null&&p.defaultChecked!=null&&(c.defaultChecked=!!p.defaultChecked)}function an(c,p,k){if(p.hasOwnProperty("value")||p.hasOwnProperty("defaultValue")){var M=p.type;if(!(M!=="submit"&&M!=="reset"||p.value!==void 0&&p.value!==null))return;p=""+c._wrapperState.initialValue,k||p===c.value||(c.value=p),c.defaultValue=p}k=c.name,k!==""&&(c.name=""),c.defaultChecked=!!c._wrapperState.initialChecked,k!==""&&(c.name=k)}function sn(c,p,k){(p!=="number"||xt(c.ownerDocument)!==c)&&(k==null?c.defaultValue=""+c._wrapperState.initialValue:c.defaultValue!==""+k&&(c.defaultValue=""+k))}var Ye=Array.isArray;function yt(c,p,k,M){if(c=c.options,p){p={};for(var F=0;F<k.length;F++)p["$"+k[F]]=!0;for(k=0;k<c.length;k++)F=p.hasOwnProperty("$"+c[k].value),c[k].selected!==F&&(c[k].selected=F),F&&M&&(c[k].defaultSelected=!0)}else{for(k=""+ne(k),p=null,F=0;F<c.length;F++){if(c[F].value===k){c[F].selected=!0,M&&(c[F].defaultSelected=!0);return}p!==null||c[F].disabled||(p=c[F])}p!==null&&(p.selected=!0)}}function kt(c,p){if(p.dangerouslySetInnerHTML!=null)throw Error(r(91));return Q({},p,{value:void 0,defaultValue:void 0,children:""+c._wrapperState.initialValue})}function Kt(c,p){var k=p.value;if(k==null){if(k=p.children,p=p.defaultValue,k!=null){if(p!=null)throw Error(r(92));if(Ye(k)){if(1<k.length)throw Error(r(93));k=k[0]}p=k}p==null&&(p=""),k=p}c._wrapperState={initialValue:ne(k)}}function On(c,p){var k=ne(p.value),M=ne(p.defaultValue);k!=null&&(k=""+k,k!==c.value&&(c.value=k),p.defaultValue==null&&c.defaultValue!==k&&(c.defaultValue=k)),M!=null&&(c.defaultValue=""+M)}function Rn(c){var p=c.textContent;p===c._wrapperState.initialValue&&p!==""&&p!==null&&(c.value=p)}function Br(c){switch(c){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Tr(c,p){return c==null||c==="http://www.w3.org/1999/xhtml"?Br(p):c==="http://www.w3.org/2000/svg"&&p==="foreignObject"?"http://www.w3.org/1999/xhtml":c}var nt,St=(function(c){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(p,k,M,F){MSApp.execUnsafeLocalFunction(function(){return c(p,k,M,F)})}:c})(function(c,p){if(c.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in c)c.innerHTML=p;else{for(nt=nt||document.createElement("div"),nt.innerHTML="<svg>"+p.valueOf().toString()+"</svg>",p=nt.firstChild;c.firstChild;)c.removeChild(c.firstChild);for(;p.firstChild;)c.appendChild(p.firstChild)}});function Tt(c,p){if(p){var k=c.firstChild;if(k&&k===c.lastChild&&k.nodeType===3){k.nodeValue=p;return}}c.textContent=p}var cn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},nn=["Webkit","ms","Moz","O"];Object.keys(cn).forEach(function(c){nn.forEach(function(p){p=p+c.charAt(0).toUpperCase()+c.substring(1),cn[p]=cn[c]})});function $r(c,p,k){return p==null||typeof p=="boolean"||p===""?"":k||typeof p!="number"||p===0||cn.hasOwnProperty(c)&&cn[c]?(""+p).trim():p+"px"}function Ta(c,p){c=c.style;for(var k in p)if(p.hasOwnProperty(k)){var M=k.indexOf("--")===0,F=$r(k,p[k],M);k==="float"&&(k="cssFloat"),M?c.setProperty(k,F):c[k]=F}}var Vo=Q({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function vi(c,p){if(p){if(Vo[c]&&(p.children!=null||p.dangerouslySetInnerHTML!=null))throw Error(r(137,c));if(p.dangerouslySetInnerHTML!=null){if(p.children!=null)throw Error(r(60));if(typeof p.dangerouslySetInnerHTML!="object"||!("__html"in p.dangerouslySetInnerHTML))throw Error(r(61))}if(p.style!=null&&typeof p.style!="object")throw Error(r(62))}}function yn(c,p){if(c.indexOf("-")===-1)return typeof p.is=="string";switch(c){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Fr=null;function Zn(c){return c=c.target||c.srcElement||window,c.correspondingUseElement&&(c=c.correspondingUseElement),c.nodeType===3?c.parentNode:c}var bi=null,Ms=null,as=null;function Fi(c){if(c=Pl(c)){if(typeof bi!="function")throw Error(r(280));var p=c.stateNode;p&&(p=Bc(p),bi(c.stateNode,c.type,p))}}function wi(c){Ms?as?as.push(c):as=[c]:Ms=c}function _i(){if(Ms){var c=Ms,p=as;if(as=Ms=null,Fi(c),p)for(c=0;c<p.length;c++)Fi(p[c])}}function Is(c,p){return c(p)}function Ar(){}var Ur=!1;function Js(c,p,k){if(Ur)return c(p,k);Ur=!0;try{return Is(c,p,k)}finally{Ur=!1,(Ms!==null||as!==null)&&(Ar(),_i())}}function Rr(c,p){var k=c.stateNode;if(k===null)return null;var M=Bc(k);if(M===null)return null;k=M[p];e:switch(p){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(M=!M.disabled)||(c=c.type,M=!(c==="button"||c==="input"||c==="select"||c==="textarea")),c=!M;break e;default:c=!1}if(c)return null;if(k&&typeof k!="function")throw Error(r(231,p,typeof k));return k}var ls=!1;if(u)try{var js={};Object.defineProperty(js,"passive",{get:function(){ls=!0}}),window.addEventListener("test",js,js),window.removeEventListener("test",js,js)}catch{ls=!1}function ho(c,p,k,M,F,K,de,_e,$e){var qe=Array.prototype.slice.call(arguments,3);try{p.apply(k,qe)}catch(at){this.onError(at)}}var Qs=!1,Zs=null,ei=!1,zt=null,Hr={onError:function(c){Qs=!0,Zs=c}};function Hn(c,p,k,M,F,K,de,_e,$e){Qs=!1,Zs=null,ho.apply(Hr,arguments)}function _n(c,p,k,M,F,K,de,_e,$e){if(Hn.apply(this,arguments),Qs){if(Qs){var qe=Zs;Qs=!1,Zs=null}else throw Error(r(198));ei||(ei=!0,zt=qe)}}function Ct(c){var p=c,k=c;if(c.alternate)for(;p.return;)p=p.return;else{c=p;do p=c,(p.flags&4098)!==0&&(k=p.return),c=p.return;while(c)}return p.tag===3?k:null}function Ui(c){if(c.tag===13){var p=c.memoizedState;if(p===null&&(c=c.alternate,c!==null&&(p=c.memoizedState)),p!==null)return p.dehydrated}return null}function fo(c){if(Ct(c)!==c)throw Error(r(188))}function $a(c){var p=c.alternate;if(!p){if(p=Ct(c),p===null)throw Error(r(188));return p!==c?null:c}for(var k=c,M=p;;){var F=k.return;if(F===null)break;var K=F.alternate;if(K===null){if(M=F.return,M!==null){k=M;continue}break}if(F.child===K.child){for(K=F.child;K;){if(K===k)return fo(F),c;if(K===M)return fo(F),p;K=K.sibling}throw Error(r(188))}if(k.return!==M.return)k=F,M=K;else{for(var de=!1,_e=F.child;_e;){if(_e===k){de=!0,k=F,M=K;break}if(_e===M){de=!0,M=F,k=K;break}_e=_e.sibling}if(!de){for(_e=K.child;_e;){if(_e===k){de=!0,k=K,M=F;break}if(_e===M){de=!0,M=K,k=F;break}_e=_e.sibling}if(!de)throw Error(r(189))}}if(k.alternate!==M)throw Error(r(190))}if(k.tag!==3)throw Error(r(188));return k.stateNode.current===k?c:p}function po(c){return c=$a(c),c!==null?mo(c):null}function mo(c){if(c.tag===5||c.tag===6)return c;for(c=c.child;c!==null;){var p=mo(c);if(p!==null)return p;c=c.sibling}return null}var Go=n.unstable_scheduleCallback,Sr=n.unstable_cancelCallback,Aa=n.unstable_shouldYield,Ra=n.unstable_requestPaint,kn=n.unstable_now,Mr=n.unstable_getCurrentPriorityLevel,Vn=n.unstable_ImmediatePriority,Ir=n.unstable_UserBlockingPriority,ti=n.unstable_NormalPriority,Hi=n.unstable_LowPriority,ki=n.unstable_IdlePriority,cs=null,gr=null;function Bt(c){if(gr&&typeof gr.onCommitFiberRoot=="function")try{gr.onCommitFiberRoot(cs,c,void 0,(c.current.flags&128)===128)}catch{}}var Gn=Math.clz32?Math.clz32:Ko,Si=Math.log,us=Math.LN2;function Ko(c){return c>>>=0,c===0?32:31-(Si(c)/us|0)|0}var Ci=64,Wr=4194304;function Ps(c){switch(c&-c){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return c&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return c&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return c}}function ji(c,p){var k=c.pendingLanes;if(k===0)return 0;var M=0,F=c.suspendedLanes,K=c.pingedLanes,de=k&268435455;if(de!==0){var _e=de&~F;_e!==0?M=Ps(_e):(K&=de,K!==0&&(M=Ps(K)))}else de=k&~F,de!==0?M=Ps(de):K!==0&&(M=Ps(K));if(M===0)return 0;if(p!==0&&p!==M&&(p&F)===0&&(F=M&-M,K=p&-p,F>=K||F===16&&(K&4194240)!==0))return p;if((M&4)!==0&&(M|=k&16),p=c.entangledLanes,p!==0)for(c=c.entanglements,p&=M;0<p;)k=31-Gn(p),F=1<<k,M|=c[k],p&=~F;return M}function on(c,p){switch(c){case 1:case 2:case 4:return p+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return p+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ds(c,p){for(var k=c.suspendedLanes,M=c.pingedLanes,F=c.expirationTimes,K=c.pendingLanes;0<K;){var de=31-Gn(K),_e=1<<de,$e=F[de];$e===-1?((_e&k)===0||(_e&M)!==0)&&(F[de]=on(_e,p)):$e<=p&&(c.expiredLanes|=_e),K&=~_e}}function Wi(c){return c=c.pendingLanes&-1073741825,c!==0?c:c&1073741824?1073741824:0}function Es(){var c=Ci;return Ci<<=1,(Ci&4194240)===0&&(Ci=64),c}function Ke(c){for(var p=[],k=0;31>k;k++)p.push(c);return p}function qr(c,p,k){c.pendingLanes|=p,p!==536870912&&(c.suspendedLanes=0,c.pingedLanes=0),c=c.eventTimes,p=31-Gn(p),c[p]=k}function ft(c,p){var k=c.pendingLanes&~p;c.pendingLanes=p,c.suspendedLanes=0,c.pingedLanes=0,c.expiredLanes&=p,c.mutableReadLanes&=p,c.entangledLanes&=p,p=c.entanglements;var M=c.eventTimes;for(c=c.expirationTimes;0<k;){var F=31-Gn(k),K=1<<F;p[F]=0,M[F]=-1,c[F]=-1,k&=~K}}function be(c,p){var k=c.entangledLanes|=p;for(c=c.entanglements;k;){var M=31-Gn(k),F=1<<M;F&p|c[M]&p&&(c[M]|=p),k&=~F}}var Pe=0;function Qe(c){return c&=-c,1<c?4<c?(c&268435455)!==0?16:536870912:4:1}var Et,en,ln,$n,En,er=!1,Ln=[],sr=null,Nn=null,Ds=null,qi=new Map,go=new Map,ni=[],Vu="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function xo(c,p){switch(c){case"focusin":case"focusout":sr=null;break;case"dragenter":case"dragleave":Nn=null;break;case"mouseover":case"mouseout":Ds=null;break;case"pointerover":case"pointerout":qi.delete(p.pointerId);break;case"gotpointercapture":case"lostpointercapture":go.delete(p.pointerId)}}function yo(c,p,k,M,F,K){return c===null||c.nativeEvent!==K?(c={blockedOn:p,domEventName:k,eventSystemFlags:M,nativeEvent:K,targetContainers:[F]},p!==null&&(p=Pl(p),p!==null&&en(p)),c):(c.eventSystemFlags|=M,p=c.targetContainers,F!==null&&p.indexOf(F)===-1&&p.push(F),c)}function Sc(c,p,k,M,F){switch(p){case"focusin":return sr=yo(sr,c,p,k,M,F),!0;case"dragenter":return Nn=yo(Nn,c,p,k,M,F),!0;case"mouseover":return Ds=yo(Ds,c,p,k,M,F),!0;case"pointerover":var K=F.pointerId;return qi.set(K,yo(qi.get(K)||null,c,p,k,M,F)),!0;case"gotpointercapture":return K=F.pointerId,go.set(K,yo(go.get(K)||null,c,p,k,M,F)),!0}return!1}function bl(c){var p=Jo(c.target);if(p!==null){var k=Ct(p);if(k!==null){if(p=k.tag,p===13){if(p=Ui(k),p!==null){c.blockedOn=p,En(c.priority,function(){ln(k)});return}}else if(p===3&&k.stateNode.current.memoizedState.isDehydrated){c.blockedOn=k.tag===3?k.stateNode.containerInfo:null;return}}}c.blockedOn=null}function vo(c){if(c.blockedOn!==null)return!1;for(var p=c.targetContainers;0<p.length;){var k=re(c.domEventName,c.eventSystemFlags,p[0],c.nativeEvent);if(k===null){k=c.nativeEvent;var M=new k.constructor(k.type,k);Fr=M,k.target.dispatchEvent(M),Fr=null}else return p=Pl(k),p!==null&&en(p),c.blockedOn=k,!1;p.shift()}return!0}function Ma(c,p,k){vo(c)&&k.delete(p)}function wl(){er=!1,sr!==null&&vo(sr)&&(sr=null),Nn!==null&&vo(Nn)&&(Nn=null),Ds!==null&&vo(Ds)&&(Ds=null),qi.forEach(Ma),go.forEach(Ma)}function Ei(c,p){c.blockedOn===p&&(c.blockedOn=null,er||(er=!0,n.unstable_scheduleCallback(n.unstable_NormalPriority,wl)))}function Vi(c){function p(F){return Ei(F,c)}if(0<Ln.length){Ei(Ln[0],c);for(var k=1;k<Ln.length;k++){var M=Ln[k];M.blockedOn===c&&(M.blockedOn=null)}}for(sr!==null&&Ei(sr,c),Nn!==null&&Ei(Nn,c),Ds!==null&&Ei(Ds,c),qi.forEach(p),go.forEach(p),k=0;k<ni.length;k++)M=ni[k],M.blockedOn===c&&(M.blockedOn=null);for(;0<ni.length&&(k=ni[0],k.blockedOn===null);)bl(k),k.blockedOn===null&&ni.shift()}var Ni=N.ReactCurrentBatchConfig,bo=!0;function Cc(c,p,k,M){var F=Pe,K=Ni.transition;Ni.transition=null;try{Pe=1,_l(c,p,k,M)}finally{Pe=F,Ni.transition=K}}function jc(c,p,k,M){var F=Pe,K=Ni.transition;Ni.transition=null;try{Pe=4,_l(c,p,k,M)}finally{Pe=F,Ni.transition=K}}function _l(c,p,k,M){if(bo){var F=re(c,p,k,M);if(F===null)od(c,p,M,kl,k),xo(c,M);else if(Sc(F,c,p,k,M))M.stopPropagation();else if(xo(c,M),p&4&&-1<Vu.indexOf(c)){for(;F!==null;){var K=Pl(F);if(K!==null&&Et(K),K=re(c,p,k,M),K===null&&od(c,p,M,kl,k),K===F)break;F=K}F!==null&&M.stopPropagation()}else od(c,p,M,null,k)}}var kl=null;function re(c,p,k,M){if(kl=null,c=Zn(M),c=Jo(c),c!==null)if(p=Ct(c),p===null)c=null;else if(k=p.tag,k===13){if(c=Ui(p),c!==null)return c;c=null}else if(k===3){if(p.stateNode.current.memoizedState.isDehydrated)return p.tag===3?p.stateNode.containerInfo:null;c=null}else p!==c&&(c=null);return kl=c,null}function fe(c){switch(c){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(Mr()){case Vn:return 1;case Ir:return 4;case ti:case Hi:return 16;case ki:return 536870912;default:return 16}default:return 16}}var ve=null,Te=null,Ce=null;function Be(){if(Ce)return Ce;var c,p=Te,k=p.length,M,F="value"in ve?ve.value:ve.textContent,K=F.length;for(c=0;c<k&&p[c]===F[c];c++);var de=k-c;for(M=1;M<=de&&p[k-M]===F[K-M];M++);return Ce=F.slice(c,1<M?1-M:void 0)}function Re(c){var p=c.keyCode;return"charCode"in c?(c=c.charCode,c===0&&p===13&&(c=13)):c=p,c===10&&(c=13),32<=c||c===13?c:0}function Me(){return!0}function Fe(){return!1}function et(c){function p(k,M,F,K,de){this._reactName=k,this._targetInst=F,this.type=M,this.nativeEvent=K,this.target=de,this.currentTarget=null;for(var _e in c)c.hasOwnProperty(_e)&&(k=c[_e],this[_e]=k?k(K):K[_e]);return this.isDefaultPrevented=(K.defaultPrevented!=null?K.defaultPrevented:K.returnValue===!1)?Me:Fe,this.isPropagationStopped=Fe,this}return Q(p.prototype,{preventDefault:function(){this.defaultPrevented=!0;var k=this.nativeEvent;k&&(k.preventDefault?k.preventDefault():typeof k.returnValue!="unknown"&&(k.returnValue=!1),this.isDefaultPrevented=Me)},stopPropagation:function(){var k=this.nativeEvent;k&&(k.stopPropagation?k.stopPropagation():typeof k.cancelBubble!="unknown"&&(k.cancelBubble=!0),this.isPropagationStopped=Me)},persist:function(){},isPersistent:Me}),p}var it={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(c){return c.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},tt=et(it),Xe=Q({},it,{view:0,detail:0}),At=et(Xe),ze,ut,Cn,Jt=Q({},Xe,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:un,button:0,buttons:0,relatedTarget:function(c){return c.relatedTarget===void 0?c.fromElement===c.srcElement?c.toElement:c.fromElement:c.relatedTarget},movementX:function(c){return"movementX"in c?c.movementX:(c!==Cn&&(Cn&&c.type==="mousemove"?(ze=c.screenX-Cn.screenX,ut=c.screenY-Cn.screenY):ut=ze=0,Cn=c),ze)},movementY:function(c){return"movementY"in c?c.movementY:ut}}),Qt=et(Jt),jn=Q({},Jt,{dataTransfer:0}),Ot=et(jn),Mn=Q({},Xe,{relatedTarget:0}),hn=et(Mn),xr=Q({},it,{animationName:0,elapsedTime:0,pseudoElement:0}),Pr=et(xr),Vr=Q({},it,{clipboardData:function(c){return"clipboardData"in c?c.clipboardData:window.clipboardData}}),Ia=et(Vr),Gr=Q({},it,{data:0}),Sl=et(Gr),Ec={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},yr={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},ri={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Nc(c){var p=this.nativeEvent;return p.getModifierState?p.getModifierState(c):(c=ri[c])?!!p[c]:!1}function un(){return Nc}var Os=Q({},Xe,{key:function(c){if(c.key){var p=Ec[c.key]||c.key;if(p!=="Unidentified")return p}return c.type==="keypress"?(c=Re(c),c===13?"Enter":String.fromCharCode(c)):c.type==="keydown"||c.type==="keyup"?yr[c.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:un,charCode:function(c){return c.type==="keypress"?Re(c):0},keyCode:function(c){return c.type==="keydown"||c.type==="keyup"?c.keyCode:0},which:function(c){return c.type==="keypress"?Re(c):c.type==="keydown"||c.type==="keyup"?c.keyCode:0}}),Gu=et(Os),Ti=Q({},Jt,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Xo=et(Ti),ir=Q({},Xe,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:un}),Kr=et(ir),Cl=Q({},it,{propertyName:0,elapsedTime:0,pseudoElement:0}),Xr=et(Cl),Tc=Q({},Jt,{deltaX:function(c){return"deltaX"in c?c.deltaX:"wheelDeltaX"in c?-c.wheelDeltaX:0},deltaY:function(c){return"deltaY"in c?c.deltaY:"wheelDeltaY"in c?-c.wheelDeltaY:"wheelDelta"in c?-c.wheelDelta:0},deltaZ:0,deltaMode:0}),Ku=et(Tc),$i=[9,13,27,32],Ls=u&&"CompositionEvent"in window,si=null;u&&"documentMode"in document&&(si=document.documentMode);var or=u&&"TextEvent"in window&&!si,Wn=u&&(!Ls||si&&8<si&&11>=si),zs=" ",$c=!1;function Ac(c,p){switch(c){case"keyup":return $i.indexOf(p.keyCode)!==-1;case"keydown":return p.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function lg(c){return c=c.detail,typeof c=="object"&&"data"in c?c.data:null}var Yr=!1;function cg(c,p){switch(c){case"compositionend":return lg(p);case"keypress":return p.which!==32?null:($c=!0,zs);case"textInput":return c=p.data,c===zs&&$c?null:c;default:return null}}function Xu(c,p){if(Yr)return c==="compositionend"||!Ls&&Ac(c,p)?(c=Be(),Ce=Te=ve=null,Yr=!1,c):null;switch(c){case"paste":return null;case"keypress":if(!(p.ctrlKey||p.altKey||p.metaKey)||p.ctrlKey&&p.altKey){if(p.char&&1<p.char.length)return p.char;if(p.which)return String.fromCharCode(p.which)}return null;case"compositionend":return Wn&&p.locale!=="ko"?null:p.data;default:return null}}var af={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function ii(c){var p=c&&c.nodeName&&c.nodeName.toLowerCase();return p==="input"?!!af[c.type]:p==="textarea"}function lf(c,p,k,M){wi(M),p=Pc(p,"onChange"),0<p.length&&(k=new tt("onChange","change",null,k,M),c.push({event:k,listeners:p}))}var jl=null,El=null;function ug(c){Sf(c,0)}function Rc(c){var p=Oa(c);if(lt(p))return c}function dg(c,p){if(c==="change")return p}var cf=!1;if(u){var Yu;if(u){var Ju="oninput"in document;if(!Ju){var uf=document.createElement("div");uf.setAttribute("oninput","return;"),Ju=typeof uf.oninput=="function"}Yu=Ju}else Yu=!1;cf=Yu&&(!document.documentMode||9<document.documentMode)}function oi(){jl&&(jl.detachEvent("onpropertychange",df),El=jl=null)}function df(c){if(c.propertyName==="value"&&Rc(El)){var p=[];lf(p,El,c,Zn(c)),Js(ug,p)}}function hg(c,p,k){c==="focusin"?(oi(),jl=p,El=k,jl.attachEvent("onpropertychange",df)):c==="focusout"&&oi()}function fg(c){if(c==="selectionchange"||c==="keyup"||c==="keydown")return Rc(El)}function pg(c,p){if(c==="click")return Rc(p)}function mg(c,p){if(c==="input"||c==="change")return Rc(p)}function gg(c,p){return c===p&&(c!==0||1/c===1/p)||c!==c&&p!==p}var ai=typeof Object.is=="function"?Object.is:gg;function Nl(c,p){if(ai(c,p))return!0;if(typeof c!="object"||c===null||typeof p!="object"||p===null)return!1;var k=Object.keys(c),M=Object.keys(p);if(k.length!==M.length)return!1;for(M=0;M<k.length;M++){var F=k[M];if(!h.call(p,F)||!ai(c[F],p[F]))return!1}return!0}function hf(c){for(;c&&c.firstChild;)c=c.firstChild;return c}function ff(c,p){var k=hf(c);c=0;for(var M;k;){if(k.nodeType===3){if(M=c+k.textContent.length,c<=p&&M>=p)return{node:k,offset:p-c};c=M}e:{for(;k;){if(k.nextSibling){k=k.nextSibling;break e}k=k.parentNode}k=void 0}k=hf(k)}}function Qu(c,p){return c&&p?c===p?!0:c&&c.nodeType===3?!1:p&&p.nodeType===3?Qu(c,p.parentNode):"contains"in c?c.contains(p):c.compareDocumentPosition?!!(c.compareDocumentPosition(p)&16):!1:!1}function Zu(){for(var c=window,p=xt();p instanceof c.HTMLIFrameElement;){try{var k=typeof p.contentWindow.location.href=="string"}catch{k=!1}if(k)c=p.contentWindow;else break;p=xt(c.document)}return p}function ed(c){var p=c&&c.nodeName&&c.nodeName.toLowerCase();return p&&(p==="input"&&(c.type==="text"||c.type==="search"||c.type==="tel"||c.type==="url"||c.type==="password")||p==="textarea"||c.contentEditable==="true")}function xg(c){var p=Zu(),k=c.focusedElem,M=c.selectionRange;if(p!==k&&k&&k.ownerDocument&&Qu(k.ownerDocument.documentElement,k)){if(M!==null&&ed(k)){if(p=M.start,c=M.end,c===void 0&&(c=p),"selectionStart"in k)k.selectionStart=p,k.selectionEnd=Math.min(c,k.value.length);else if(c=(p=k.ownerDocument||document)&&p.defaultView||window,c.getSelection){c=c.getSelection();var F=k.textContent.length,K=Math.min(M.start,F);M=M.end===void 0?K:Math.min(M.end,F),!c.extend&&K>M&&(F=M,M=K,K=F),F=ff(k,K);var de=ff(k,M);F&&de&&(c.rangeCount!==1||c.anchorNode!==F.node||c.anchorOffset!==F.offset||c.focusNode!==de.node||c.focusOffset!==de.offset)&&(p=p.createRange(),p.setStart(F.node,F.offset),c.removeAllRanges(),K>M?(c.addRange(p),c.extend(de.node,de.offset)):(p.setEnd(de.node,de.offset),c.addRange(p)))}}for(p=[],c=k;c=c.parentNode;)c.nodeType===1&&p.push({element:c,left:c.scrollLeft,top:c.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;k<p.length;k++)c=p[k],c.element.scrollLeft=c.left,c.element.scrollTop=c.top}}var pf=u&&"documentMode"in document&&11>=document.documentMode,Tl=null,td=null,Yo=null,nd=!1;function mf(c,p,k){var M=k.window===k?k.document:k.nodeType===9?k:k.ownerDocument;nd||Tl==null||Tl!==xt(M)||(M=Tl,"selectionStart"in M&&ed(M)?M={start:M.selectionStart,end:M.selectionEnd}:(M=(M.ownerDocument&&M.ownerDocument.defaultView||window).getSelection(),M={anchorNode:M.anchorNode,anchorOffset:M.anchorOffset,focusNode:M.focusNode,focusOffset:M.focusOffset}),Yo&&Nl(Yo,M)||(Yo=M,M=Pc(td,"onSelect"),0<M.length&&(p=new tt("onSelect","select",null,p,k),c.push({event:p,listeners:M}),p.target=Tl)))}function Mc(c,p){var k={};return k[c.toLowerCase()]=p.toLowerCase(),k["Webkit"+c]="webkit"+p,k["Moz"+c]="moz"+p,k}var Gi={animationend:Mc("Animation","AnimationEnd"),animationiteration:Mc("Animation","AnimationIteration"),animationstart:Mc("Animation","AnimationStart"),transitionend:Mc("Transition","TransitionEnd")},rd={},gf={};u&&(gf=document.createElement("div").style,"AnimationEvent"in window||(delete Gi.animationend.animation,delete Gi.animationiteration.animation,delete Gi.animationstart.animation),"TransitionEvent"in window||delete Gi.transitionend.transition);function $l(c){if(rd[c])return rd[c];if(!Gi[c])return c;var p=Gi[c],k;for(k in p)if(p.hasOwnProperty(k)&&k in gf)return rd[c]=p[k];return c}var xf=$l("animationend"),yf=$l("animationiteration"),vf=$l("animationstart"),bf=$l("transitionend"),yg=new Map,wf="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function wo(c,p){yg.set(c,p),l(p,[c])}for(var sd=0;sd<wf.length;sd++){var _f=wf[sd],vg=_f.toLowerCase(),mn=_f[0].toUpperCase()+_f.slice(1);wo(vg,"on"+mn)}wo(xf,"onAnimationEnd"),wo(yf,"onAnimationIteration"),wo(vf,"onAnimationStart"),wo("dblclick","onDoubleClick"),wo("focusin","onFocus"),wo("focusout","onBlur"),wo(bf,"onTransitionEnd"),d("onMouseEnter",["mouseout","mouseover"]),d("onMouseLeave",["mouseout","mouseover"]),d("onPointerEnter",["pointerout","pointerover"]),d("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Al="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),bg=new Set("cancel close invalid load scroll toggle".split(" ").concat(Al));function kf(c,p,k){var M=c.type||"unknown-event";c.currentTarget=k,_n(M,p,void 0,c),c.currentTarget=null}function Sf(c,p){p=(p&4)!==0;for(var k=0;k<c.length;k++){var M=c[k],F=M.event;M=M.listeners;e:{var K=void 0;if(p)for(var de=M.length-1;0<=de;de--){var _e=M[de],$e=_e.instance,qe=_e.currentTarget;if(_e=_e.listener,$e!==K&&F.isPropagationStopped())break e;kf(F,_e,qe),K=$e}else for(de=0;de<M.length;de++){if(_e=M[de],$e=_e.instance,qe=_e.currentTarget,_e=_e.listener,$e!==K&&F.isPropagationStopped())break e;kf(F,_e,qe),K=$e}}}if(ei)throw c=zt,ei=!1,zt=null,c}function zn(c,p){var k=p[hd];k===void 0&&(k=p[hd]=new Set);var M=c+"__bubble";k.has(M)||(Cf(p,c,2,!1),k.add(M))}function id(c,p,k){var M=0;p&&(M|=4),Cf(k,c,M,p)}var Ic="_reactListening"+Math.random().toString(36).slice(2);function Rl(c){if(!c[Ic]){c[Ic]=!0,i.forEach(function(k){k!=="selectionchange"&&(bg.has(k)||id(k,!1,c),id(k,!0,c))});var p=c.nodeType===9?c:c.ownerDocument;p===null||p[Ic]||(p[Ic]=!0,id("selectionchange",!1,p))}}function Cf(c,p,k,M){switch(fe(p)){case 1:var F=Cc;break;case 4:F=jc;break;default:F=_l}k=F.bind(null,p,k,c),F=void 0,!ls||p!=="touchstart"&&p!=="touchmove"&&p!=="wheel"||(F=!0),M?F!==void 0?c.addEventListener(p,k,{capture:!0,passive:F}):c.addEventListener(p,k,!0):F!==void 0?c.addEventListener(p,k,{passive:F}):c.addEventListener(p,k,!1)}function od(c,p,k,M,F){var K=M;if((p&1)===0&&(p&2)===0&&M!==null)e:for(;;){if(M===null)return;var de=M.tag;if(de===3||de===4){var _e=M.stateNode.containerInfo;if(_e===F||_e.nodeType===8&&_e.parentNode===F)break;if(de===4)for(de=M.return;de!==null;){var $e=de.tag;if(($e===3||$e===4)&&($e=de.stateNode.containerInfo,$e===F||$e.nodeType===8&&$e.parentNode===F))return;de=de.return}for(;_e!==null;){if(de=Jo(_e),de===null)return;if($e=de.tag,$e===5||$e===6){M=K=de;continue e}_e=_e.parentNode}}M=M.return}Js(function(){var qe=K,at=Zn(k),ct=[];e:{var ot=yg.get(c);if(ot!==void 0){var jt=tt,Pt=c;switch(c){case"keypress":if(Re(k)===0)break e;case"keydown":case"keyup":jt=Gu;break;case"focusin":Pt="focus",jt=hn;break;case"focusout":Pt="blur",jt=hn;break;case"beforeblur":case"afterblur":jt=hn;break;case"click":if(k.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":jt=Qt;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":jt=Ot;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":jt=Kr;break;case xf:case yf:case vf:jt=Pr;break;case bf:jt=Xr;break;case"scroll":jt=At;break;case"wheel":jt=Ku;break;case"copy":case"cut":case"paste":jt=Ia;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":jt=Xo}var Dt=(p&4)!==0,Pn=!Dt&&c==="scroll",Ue=Dt?ot!==null?ot+"Capture":null:ot;Dt=[];for(var Ie=qe,Ve;Ie!==null;){Ve=Ie;var ht=Ve.stateNode;if(Ve.tag===5&&ht!==null&&(Ve=ht,Ue!==null&&(ht=Rr(Ie,Ue),ht!=null&&Dt.push(Ml(Ie,ht,Ve)))),Pn)break;Ie=Ie.return}0<Dt.length&&(ot=new jt(ot,Pt,null,k,at),ct.push({event:ot,listeners:Dt}))}}if((p&7)===0){e:{if(ot=c==="mouseover"||c==="pointerover",jt=c==="mouseout"||c==="pointerout",ot&&k!==Fr&&(Pt=k.relatedTarget||k.fromElement)&&(Jo(Pt)||Pt[Ri]))break e;if((jt||ot)&&(ot=at.window===at?at:(ot=at.ownerDocument)?ot.defaultView||ot.parentWindow:window,jt?(Pt=k.relatedTarget||k.toElement,jt=qe,Pt=Pt?Jo(Pt):null,Pt!==null&&(Pn=Ct(Pt),Pt!==Pn||Pt.tag!==5&&Pt.tag!==6)&&(Pt=null)):(jt=null,Pt=qe),jt!==Pt)){if(Dt=Qt,ht="onMouseLeave",Ue="onMouseEnter",Ie="mouse",(c==="pointerout"||c==="pointerover")&&(Dt=Xo,ht="onPointerLeave",Ue="onPointerEnter",Ie="pointer"),Pn=jt==null?ot:Oa(jt),Ve=Pt==null?ot:Oa(Pt),ot=new Dt(ht,Ie+"leave",jt,k,at),ot.target=Pn,ot.relatedTarget=Ve,ht=null,Jo(at)===qe&&(Dt=new Dt(Ue,Ie+"enter",Pt,k,at),Dt.target=Ve,Dt.relatedTarget=Pn,ht=Dt),Pn=ht,jt&&Pt)t:{for(Dt=jt,Ue=Pt,Ie=0,Ve=Dt;Ve;Ve=Pa(Ve))Ie++;for(Ve=0,ht=Ue;ht;ht=Pa(ht))Ve++;for(;0<Ie-Ve;)Dt=Pa(Dt),Ie--;for(;0<Ve-Ie;)Ue=Pa(Ue),Ve--;for(;Ie--;){if(Dt===Ue||Ue!==null&&Dt===Ue.alternate)break t;Dt=Pa(Dt),Ue=Pa(Ue)}Dt=null}else Dt=null;jt!==null&&jf(ct,ot,jt,Dt,!1),Pt!==null&&Pn!==null&&jf(ct,Pn,Pt,Dt,!0)}}e:{if(ot=qe?Oa(qe):window,jt=ot.nodeName&&ot.nodeName.toLowerCase(),jt==="select"||jt==="input"&&ot.type==="file")var Ft=dg;else if(ii(ot))if(cf)Ft=mg;else{Ft=fg;var Xt=hg}else(jt=ot.nodeName)&&jt.toLowerCase()==="input"&&(ot.type==="checkbox"||ot.type==="radio")&&(Ft=pg);if(Ft&&(Ft=Ft(c,qe))){lf(ct,Ft,k,at);break e}Xt&&Xt(c,ot,qe),c==="focusout"&&(Xt=ot._wrapperState)&&Xt.controlled&&ot.type==="number"&&sn(ot,"number",ot.value)}switch(Xt=qe?Oa(qe):window,c){case"focusin":(ii(Xt)||Xt.contentEditable==="true")&&(Tl=Xt,td=qe,Yo=null);break;case"focusout":Yo=td=Tl=null;break;case"mousedown":nd=!0;break;case"contextmenu":case"mouseup":case"dragend":nd=!1,mf(ct,k,at);break;case"selectionchange":if(pf)break;case"keydown":case"keyup":mf(ct,k,at)}var Yt;if(Ls)e:{switch(c){case"compositionstart":var rn="onCompositionStart";break e;case"compositionend":rn="onCompositionEnd";break e;case"compositionupdate":rn="onCompositionUpdate";break e}rn=void 0}else Yr?Ac(c,k)&&(rn="onCompositionEnd"):c==="keydown"&&k.keyCode===229&&(rn="onCompositionStart");rn&&(Wn&&k.locale!=="ko"&&(Yr||rn!=="onCompositionStart"?rn==="onCompositionEnd"&&Yr&&(Yt=Be()):(ve=at,Te="value"in ve?ve.value:ve.textContent,Yr=!0)),Xt=Pc(qe,rn),0<Xt.length&&(rn=new Sl(rn,c,null,k,at),ct.push({event:rn,listeners:Xt}),Yt?rn.data=Yt:(Yt=lg(k),Yt!==null&&(rn.data=Yt)))),(Yt=or?cg(c,k):Xu(c,k))&&(qe=Pc(qe,"onBeforeInput"),0<qe.length&&(at=new Sl("onBeforeInput","beforeinput",null,k,at),ct.push({event:at,listeners:qe}),at.data=Yt))}Sf(ct,p)})}function Ml(c,p,k){return{instance:c,listener:p,currentTarget:k}}function Pc(c,p){for(var k=p+"Capture",M=[];c!==null;){var F=c,K=F.stateNode;F.tag===5&&K!==null&&(F=K,K=Rr(c,k),K!=null&&M.unshift(Ml(c,K,F)),K=Rr(c,p),K!=null&&M.push(Ml(c,K,F))),c=c.return}return M}function Pa(c){if(c===null)return null;do c=c.return;while(c&&c.tag!==5);return c||null}function jf(c,p,k,M,F){for(var K=p._reactName,de=[];k!==null&&k!==M;){var _e=k,$e=_e.alternate,qe=_e.stateNode;if($e!==null&&$e===M)break;_e.tag===5&&qe!==null&&(_e=qe,F?($e=Rr(k,K),$e!=null&&de.unshift(Ml(k,$e,_e))):F||($e=Rr(k,K),$e!=null&&de.push(Ml(k,$e,_e)))),k=k.return}de.length!==0&&c.push({event:p,listeners:de})}var Dc=/\r\n?/g,wg=/\u0000|\uFFFD/g;function Oc(c){return(typeof c=="string"?c:""+c).replace(Dc,`
|
|
39
|
-
`).replace(wg,"")}function Lc(c,p,k){if(p=Oc(p),Oc(c)!==p&&k)throw Error(r(425))}function zc(){}var ad=null,ld=null;function cd(c,p){return c==="textarea"||c==="noscript"||typeof p.children=="string"||typeof p.children=="number"||typeof p.dangerouslySetInnerHTML=="object"&&p.dangerouslySetInnerHTML!==null&&p.dangerouslySetInnerHTML.__html!=null}var ud=typeof setTimeout=="function"?setTimeout:void 0,_g=typeof clearTimeout=="function"?clearTimeout:void 0,Ef=typeof Promise=="function"?Promise:void 0,kg=typeof queueMicrotask=="function"?queueMicrotask:typeof Ef<"u"?function(c){return Ef.resolve(null).then(c).catch(Sg)}:ud;function Sg(c){setTimeout(function(){throw c})}function dd(c,p){var k=p,M=0;do{var F=k.nextSibling;if(c.removeChild(k),F&&F.nodeType===8)if(k=F.data,k==="/$"){if(M===0){c.removeChild(F),Vi(p);return}M--}else k!=="$"&&k!=="$?"&&k!=="$!"||M++;k=F}while(k);Vi(p)}function _o(c){for(;c!=null;c=c.nextSibling){var p=c.nodeType;if(p===1||p===3)break;if(p===8){if(p=c.data,p==="$"||p==="$!"||p==="$?")break;if(p==="/$")return null}}return c}function Nf(c){c=c.previousSibling;for(var p=0;c;){if(c.nodeType===8){var k=c.data;if(k==="$"||k==="$!"||k==="$?"){if(p===0)return c;p--}else k==="/$"&&p++}c=c.previousSibling}return null}var Da=Math.random().toString(36).slice(2),Ai="__reactFiber$"+Da,Il="__reactProps$"+Da,Ri="__reactContainer$"+Da,hd="__reactEvents$"+Da,Tf="__reactListeners$"+Da,$f="__reactHandles$"+Da;function Jo(c){var p=c[Ai];if(p)return p;for(var k=c.parentNode;k;){if(p=k[Ri]||k[Ai]){if(k=p.alternate,p.child!==null||k!==null&&k.child!==null)for(c=Nf(c);c!==null;){if(k=c[Ai])return k;c=Nf(c)}return p}c=k,k=c.parentNode}return null}function Pl(c){return c=c[Ai]||c[Ri],!c||c.tag!==5&&c.tag!==6&&c.tag!==13&&c.tag!==3?null:c}function Oa(c){if(c.tag===5||c.tag===6)return c.stateNode;throw Error(r(33))}function Bc(c){return c[Il]||null}var fd=[],La=-1;function Ki(c){return{current:c}}function Bn(c){0>La||(c.current=fd[La],fd[La]=null,La--)}function In(c,p){La++,fd[La]=c.current,c.current=p}var ko={},Jr=Ki(ko),hs=Ki(!1),Qo=ko;function Qr(c,p){var k=c.type.contextTypes;if(!k)return ko;var M=c.stateNode;if(M&&M.__reactInternalMemoizedUnmaskedChildContext===p)return M.__reactInternalMemoizedMaskedChildContext;var F={},K;for(K in k)F[K]=p[K];return M&&(c=c.stateNode,c.__reactInternalMemoizedUnmaskedChildContext=p,c.__reactInternalMemoizedMaskedChildContext=F),F}function fs(c){return c=c.childContextTypes,c!=null}function Fc(){Bn(hs),Bn(Jr)}function Af(c,p,k){if(Jr.current!==ko)throw Error(r(168));In(Jr,p),In(hs,k)}function Rf(c,p,k){var M=c.stateNode;if(p=p.childContextTypes,typeof M.getChildContext!="function")return k;M=M.getChildContext();for(var F in M)if(!(F in p))throw Error(r(108,ye(c)||"Unknown",F));return Q({},k,M)}function Uc(c){return c=(c=c.stateNode)&&c.__reactInternalMemoizedMergedChildContext||ko,Qo=Jr.current,In(Jr,c),In(hs,hs.current),!0}function Mf(c,p,k){var M=c.stateNode;if(!M)throw Error(r(169));k?(c=Rf(c,p,Qo),M.__reactInternalMemoizedMergedChildContext=c,Bn(hs),Bn(Jr),In(Jr,c)):Bn(hs),In(hs,k)}var Xi=null,Hc=!1,pd=!1;function If(c){Xi===null?Xi=[c]:Xi.push(c)}function fv(c){Hc=!0,If(c)}function So(){if(!pd&&Xi!==null){pd=!0;var c=0,p=Pe;try{var k=Xi;for(Pe=1;c<k.length;c++){var M=k[c];do M=M(!0);while(M!==null)}Xi=null,Hc=!1}catch(F){throw Xi!==null&&(Xi=Xi.slice(c+1)),Go(Vn,So),F}finally{Pe=p,pd=!1}}return null}var za=[],Ba=0,Wc=null,qc=0,Bs=[],li=0,Fs=null,ps=1,ms="";function Co(c,p){za[Ba++]=qc,za[Ba++]=Wc,Wc=c,qc=p}function Zo(c,p,k){Bs[li++]=ps,Bs[li++]=ms,Bs[li++]=Fs,Fs=c;var M=ps;c=ms;var F=32-Gn(M)-1;M&=~(1<<F),k+=1;var K=32-Gn(p)+F;if(30<K){var de=F-F%5;K=(M&(1<<de)-1).toString(32),M>>=de,F-=de,ps=1<<32-Gn(p)+F|k<<F|M,ms=K+c}else ps=1<<K|k<<F|M,ms=c}function ur(c){c.return!==null&&(Co(c,1),Zo(c,1,0))}function md(c){for(;c===Wc;)Wc=za[--Ba],za[Ba]=null,qc=za[--Ba],za[Ba]=null;for(;c===Fs;)Fs=Bs[--li],Bs[li]=null,ms=Bs[--li],Bs[li]=null,ps=Bs[--li],Bs[li]=null}var gs=null,Ns=null,Kn=!1,xs=null;function gd(c,p){var k=$s(5,null,null,0);k.elementType="DELETED",k.stateNode=p,k.return=c,p=c.deletions,p===null?(c.deletions=[k],c.flags|=16):p.push(k)}function xd(c,p){switch(c.tag){case 5:var k=c.type;return p=p.nodeType!==1||k.toLowerCase()!==p.nodeName.toLowerCase()?null:p,p!==null?(c.stateNode=p,gs=c,Ns=_o(p.firstChild),!0):!1;case 6:return p=c.pendingProps===""||p.nodeType!==3?null:p,p!==null?(c.stateNode=p,gs=c,Ns=null,!0):!1;case 13:return p=p.nodeType!==8?null:p,p!==null?(k=Fs!==null?{id:ps,overflow:ms}:null,c.memoizedState={dehydrated:p,treeContext:k,retryLane:1073741824},k=$s(18,null,null,0),k.stateNode=p,k.return=c,c.child=k,gs=c,Ns=null,!0):!1;default:return!1}}function yd(c){return(c.mode&1)!==0&&(c.flags&128)===0}function vd(c){if(Kn){var p=Ns;if(p){var k=p;if(!xd(c,p)){if(yd(c))throw Error(r(418));p=_o(k.nextSibling);var M=gs;p&&xd(c,p)?gd(M,k):(c.flags=c.flags&-4097|2,Kn=!1,gs=c)}}else{if(yd(c))throw Error(r(418));c.flags=c.flags&-4097|2,Kn=!1,gs=c}}}function bd(c){for(c=c.return;c!==null&&c.tag!==5&&c.tag!==3&&c.tag!==13;)c=c.return;gs=c}function Dl(c){if(c!==gs)return!1;if(!Kn)return bd(c),Kn=!0,!1;var p;if((p=c.tag!==3)&&!(p=c.tag!==5)&&(p=c.type,p=p!=="head"&&p!=="body"&&!cd(c.type,c.memoizedProps)),p&&(p=Ns)){if(yd(c))throw Pf(),Error(r(418));for(;p;)gd(c,p),p=_o(p.nextSibling)}if(bd(c),c.tag===13){if(c=c.memoizedState,c=c!==null?c.dehydrated:null,!c)throw Error(r(317));e:{for(c=c.nextSibling,p=0;c;){if(c.nodeType===8){var k=c.data;if(k==="/$"){if(p===0){Ns=_o(c.nextSibling);break e}p--}else k!=="$"&&k!=="$!"&&k!=="$?"||p++}c=c.nextSibling}Ns=null}}else Ns=gs?_o(c.stateNode.nextSibling):null;return!0}function Pf(){for(var c=Ns;c;)c=_o(c.nextSibling)}function ea(){Ns=gs=null,Kn=!1}function wd(c){xs===null?xs=[c]:xs.push(c)}var _d=N.ReactCurrentBatchConfig;function Fa(c,p,k){if(c=k.ref,c!==null&&typeof c!="function"&&typeof c!="object"){if(k._owner){if(k=k._owner,k){if(k.tag!==1)throw Error(r(309));var M=k.stateNode}if(!M)throw Error(r(147,c));var F=M,K=""+c;return p!==null&&p.ref!==null&&typeof p.ref=="function"&&p.ref._stringRef===K?p.ref:(p=function(de){var _e=F.refs;de===null?delete _e[K]:_e[K]=de},p._stringRef=K,p)}if(typeof c!="string")throw Error(r(284));if(!k._owner)throw Error(r(290,c))}return c}function Vc(c,p){throw c=Object.prototype.toString.call(p),Error(r(31,c==="[object Object]"?"object with keys {"+Object.keys(p).join(", ")+"}":c))}function Df(c){var p=c._init;return p(c._payload)}function Cg(c){function p(Ue,Ie){if(c){var Ve=Ue.deletions;Ve===null?(Ue.deletions=[Ie],Ue.flags|=16):Ve.push(Ie)}}function k(Ue,Ie){if(!c)return null;for(;Ie!==null;)p(Ue,Ie),Ie=Ie.sibling;return null}function M(Ue,Ie){for(Ue=new Map;Ie!==null;)Ie.key!==null?Ue.set(Ie.key,Ie):Ue.set(Ie.index,Ie),Ie=Ie.sibling;return Ue}function F(Ue,Ie){return Ue=Mo(Ue,Ie),Ue.index=0,Ue.sibling=null,Ue}function K(Ue,Ie,Ve){return Ue.index=Ve,c?(Ve=Ue.alternate,Ve!==null?(Ve=Ve.index,Ve<Ie?(Ue.flags|=2,Ie):Ve):(Ue.flags|=2,Ie)):(Ue.flags|=1048576,Ie)}function de(Ue){return c&&Ue.alternate===null&&(Ue.flags|=2),Ue}function _e(Ue,Ie,Ve,ht){return Ie===null||Ie.tag!==6?(Ie=vh(Ve,Ue.mode,ht),Ie.return=Ue,Ie):(Ie=F(Ie,Ve),Ie.return=Ue,Ie)}function $e(Ue,Ie,Ve,ht){var Ft=Ve.type;return Ft===O?at(Ue,Ie,Ve.props.children,ht,Ve.key):Ie!==null&&(Ie.elementType===Ft||typeof Ft=="object"&&Ft!==null&&Ft.$$typeof===ae&&Df(Ft)===Ie.type)?(ht=F(Ie,Ve.props),ht.ref=Fa(Ue,Ie,Ve),ht.return=Ue,ht):(ht=pu(Ve.type,Ve.key,Ve.props,null,Ue.mode,ht),ht.ref=Fa(Ue,Ie,Ve),ht.return=Ue,ht)}function qe(Ue,Ie,Ve,ht){return Ie===null||Ie.tag!==4||Ie.stateNode.containerInfo!==Ve.containerInfo||Ie.stateNode.implementation!==Ve.implementation?(Ie=bh(Ve,Ue.mode,ht),Ie.return=Ue,Ie):(Ie=F(Ie,Ve.children||[]),Ie.return=Ue,Ie)}function at(Ue,Ie,Ve,ht,Ft){return Ie===null||Ie.tag!==7?(Ie=Ja(Ve,Ue.mode,ht,Ft),Ie.return=Ue,Ie):(Ie=F(Ie,Ve),Ie.return=Ue,Ie)}function ct(Ue,Ie,Ve){if(typeof Ie=="string"&&Ie!==""||typeof Ie=="number")return Ie=vh(""+Ie,Ue.mode,Ve),Ie.return=Ue,Ie;if(typeof Ie=="object"&&Ie!==null){switch(Ie.$$typeof){case $:return Ve=pu(Ie.type,Ie.key,Ie.props,null,Ue.mode,Ve),Ve.ref=Fa(Ue,null,Ie),Ve.return=Ue,Ve;case R:return Ie=bh(Ie,Ue.mode,Ve),Ie.return=Ue,Ie;case ae:var ht=Ie._init;return ct(Ue,ht(Ie._payload),Ve)}if(Ye(Ie)||X(Ie))return Ie=Ja(Ie,Ue.mode,Ve,null),Ie.return=Ue,Ie;Vc(Ue,Ie)}return null}function ot(Ue,Ie,Ve,ht){var Ft=Ie!==null?Ie.key:null;if(typeof Ve=="string"&&Ve!==""||typeof Ve=="number")return Ft!==null?null:_e(Ue,Ie,""+Ve,ht);if(typeof Ve=="object"&&Ve!==null){switch(Ve.$$typeof){case $:return Ve.key===Ft?$e(Ue,Ie,Ve,ht):null;case R:return Ve.key===Ft?qe(Ue,Ie,Ve,ht):null;case ae:return Ft=Ve._init,ot(Ue,Ie,Ft(Ve._payload),ht)}if(Ye(Ve)||X(Ve))return Ft!==null?null:at(Ue,Ie,Ve,ht,null);Vc(Ue,Ve)}return null}function jt(Ue,Ie,Ve,ht,Ft){if(typeof ht=="string"&&ht!==""||typeof ht=="number")return Ue=Ue.get(Ve)||null,_e(Ie,Ue,""+ht,Ft);if(typeof ht=="object"&&ht!==null){switch(ht.$$typeof){case $:return Ue=Ue.get(ht.key===null?Ve:ht.key)||null,$e(Ie,Ue,ht,Ft);case R:return Ue=Ue.get(ht.key===null?Ve:ht.key)||null,qe(Ie,Ue,ht,Ft);case ae:var Xt=ht._init;return jt(Ue,Ie,Ve,Xt(ht._payload),Ft)}if(Ye(ht)||X(ht))return Ue=Ue.get(Ve)||null,at(Ie,Ue,ht,Ft,null);Vc(Ie,ht)}return null}function Pt(Ue,Ie,Ve,ht){for(var Ft=null,Xt=null,Yt=Ie,rn=Ie=0,wr=null;Yt!==null&&rn<Ve.length;rn++){Yt.index>rn?(wr=Yt,Yt=null):wr=Yt.sibling;var vn=ot(Ue,Yt,Ve[rn],ht);if(vn===null){Yt===null&&(Yt=wr);break}c&&Yt&&vn.alternate===null&&p(Ue,Yt),Ie=K(vn,Ie,rn),Xt===null?Ft=vn:Xt.sibling=vn,Xt=vn,Yt=wr}if(rn===Ve.length)return k(Ue,Yt),Kn&&Co(Ue,rn),Ft;if(Yt===null){for(;rn<Ve.length;rn++)Yt=ct(Ue,Ve[rn],ht),Yt!==null&&(Ie=K(Yt,Ie,rn),Xt===null?Ft=Yt:Xt.sibling=Yt,Xt=Yt);return Kn&&Co(Ue,rn),Ft}for(Yt=M(Ue,Yt);rn<Ve.length;rn++)wr=jt(Yt,Ue,rn,Ve[rn],ht),wr!==null&&(c&&wr.alternate!==null&&Yt.delete(wr.key===null?rn:wr.key),Ie=K(wr,Ie,rn),Xt===null?Ft=wr:Xt.sibling=wr,Xt=wr);return c&&Yt.forEach(function(eo){return p(Ue,eo)}),Kn&&Co(Ue,rn),Ft}function Dt(Ue,Ie,Ve,ht){var Ft=X(Ve);if(typeof Ft!="function")throw Error(r(150));if(Ve=Ft.call(Ve),Ve==null)throw Error(r(151));for(var Xt=Ft=null,Yt=Ie,rn=Ie=0,wr=null,vn=Ve.next();Yt!==null&&!vn.done;rn++,vn=Ve.next()){Yt.index>rn?(wr=Yt,Yt=null):wr=Yt.sibling;var eo=ot(Ue,Yt,vn.value,ht);if(eo===null){Yt===null&&(Yt=wr);break}c&&Yt&&eo.alternate===null&&p(Ue,Yt),Ie=K(eo,Ie,rn),Xt===null?Ft=eo:Xt.sibling=eo,Xt=eo,Yt=wr}if(vn.done)return k(Ue,Yt),Kn&&Co(Ue,rn),Ft;if(Yt===null){for(;!vn.done;rn++,vn=Ve.next())vn=ct(Ue,vn.value,ht),vn!==null&&(Ie=K(vn,Ie,rn),Xt===null?Ft=vn:Xt.sibling=vn,Xt=vn);return Kn&&Co(Ue,rn),Ft}for(Yt=M(Ue,Yt);!vn.done;rn++,vn=Ve.next())vn=jt(Yt,Ue,rn,vn.value,ht),vn!==null&&(c&&vn.alternate!==null&&Yt.delete(vn.key===null?rn:vn.key),Ie=K(vn,Ie,rn),Xt===null?Ft=vn:Xt.sibling=vn,Xt=vn);return c&&Yt.forEach(function(sx){return p(Ue,sx)}),Kn&&Co(Ue,rn),Ft}function Pn(Ue,Ie,Ve,ht){if(typeof Ve=="object"&&Ve!==null&&Ve.type===O&&Ve.key===null&&(Ve=Ve.props.children),typeof Ve=="object"&&Ve!==null){switch(Ve.$$typeof){case $:e:{for(var Ft=Ve.key,Xt=Ie;Xt!==null;){if(Xt.key===Ft){if(Ft=Ve.type,Ft===O){if(Xt.tag===7){k(Ue,Xt.sibling),Ie=F(Xt,Ve.props.children),Ie.return=Ue,Ue=Ie;break e}}else if(Xt.elementType===Ft||typeof Ft=="object"&&Ft!==null&&Ft.$$typeof===ae&&Df(Ft)===Xt.type){k(Ue,Xt.sibling),Ie=F(Xt,Ve.props),Ie.ref=Fa(Ue,Xt,Ve),Ie.return=Ue,Ue=Ie;break e}k(Ue,Xt);break}else p(Ue,Xt);Xt=Xt.sibling}Ve.type===O?(Ie=Ja(Ve.props.children,Ue.mode,ht,Ve.key),Ie.return=Ue,Ue=Ie):(ht=pu(Ve.type,Ve.key,Ve.props,null,Ue.mode,ht),ht.ref=Fa(Ue,Ie,Ve),ht.return=Ue,Ue=ht)}return de(Ue);case R:e:{for(Xt=Ve.key;Ie!==null;){if(Ie.key===Xt)if(Ie.tag===4&&Ie.stateNode.containerInfo===Ve.containerInfo&&Ie.stateNode.implementation===Ve.implementation){k(Ue,Ie.sibling),Ie=F(Ie,Ve.children||[]),Ie.return=Ue,Ue=Ie;break e}else{k(Ue,Ie);break}else p(Ue,Ie);Ie=Ie.sibling}Ie=bh(Ve,Ue.mode,ht),Ie.return=Ue,Ue=Ie}return de(Ue);case ae:return Xt=Ve._init,Pn(Ue,Ie,Xt(Ve._payload),ht)}if(Ye(Ve))return Pt(Ue,Ie,Ve,ht);if(X(Ve))return Dt(Ue,Ie,Ve,ht);Vc(Ue,Ve)}return typeof Ve=="string"&&Ve!==""||typeof Ve=="number"?(Ve=""+Ve,Ie!==null&&Ie.tag===6?(k(Ue,Ie.sibling),Ie=F(Ie,Ve),Ie.return=Ue,Ue=Ie):(k(Ue,Ie),Ie=vh(Ve,Ue.mode,ht),Ie.return=Ue,Ue=Ie),de(Ue)):k(Ue,Ie)}return Pn}var Ua=Cg(!0),kd=Cg(!1),ta=Ki(null),Gc=null,na=null,Sd=null;function Cd(){Sd=na=Gc=null}function jd(c){var p=ta.current;Bn(ta),c._currentValue=p}function Of(c,p,k){for(;c!==null;){var M=c.alternate;if((c.childLanes&p)!==p?(c.childLanes|=p,M!==null&&(M.childLanes|=p)):M!==null&&(M.childLanes&p)!==p&&(M.childLanes|=p),c===k)break;c=c.return}}function Ha(c,p){Gc=c,Sd=na=null,c=c.dependencies,c!==null&&c.firstContext!==null&&((c.lanes&p)!==0&&(ys=!0),c.firstContext=null)}function Us(c){var p=c._currentValue;if(Sd!==c)if(c={context:c,memoizedValue:p,next:null},na===null){if(Gc===null)throw Error(r(308));na=c,Gc.dependencies={lanes:0,firstContext:c}}else na=na.next=c;return p}var Wa=null;function Ed(c){Wa===null?Wa=[c]:Wa.push(c)}function Kc(c,p,k,M){var F=p.interleaved;return F===null?(k.next=k,Ed(p)):(k.next=F.next,F.next=k),p.interleaved=k,Yi(c,M)}function Yi(c,p){c.lanes|=p;var k=c.alternate;for(k!==null&&(k.lanes|=p),k=c,c=c.return;c!==null;)c.childLanes|=p,k=c.alternate,k!==null&&(k.childLanes|=p),k=c,c=c.return;return k.tag===3?k.stateNode:null}var Mi=!1;function Xc(c){c.updateQueue={baseState:c.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Nd(c,p){c=c.updateQueue,p.updateQueue===c&&(p.updateQueue={baseState:c.baseState,firstBaseUpdate:c.firstBaseUpdate,lastBaseUpdate:c.lastBaseUpdate,shared:c.shared,effects:c.effects})}function Ji(c,p){return{eventTime:c,lane:p,tag:0,payload:null,callback:null,next:null}}function jo(c,p,k){var M=c.updateQueue;if(M===null)return null;if(M=M.shared,(gn&2)!==0){var F=M.pending;return F===null?p.next=p:(p.next=F.next,F.next=p),M.pending=p,Yi(c,k)}return F=M.interleaved,F===null?(p.next=p,Ed(M)):(p.next=F.next,F.next=p),M.interleaved=p,Yi(c,k)}function Ol(c,p,k){if(p=p.updateQueue,p!==null&&(p=p.shared,(k&4194240)!==0)){var M=p.lanes;M&=c.pendingLanes,k|=M,p.lanes=k,be(c,k)}}function jg(c,p){var k=c.updateQueue,M=c.alternate;if(M!==null&&(M=M.updateQueue,k===M)){var F=null,K=null;if(k=k.firstBaseUpdate,k!==null){do{var de={eventTime:k.eventTime,lane:k.lane,tag:k.tag,payload:k.payload,callback:k.callback,next:null};K===null?F=K=de:K=K.next=de,k=k.next}while(k!==null);K===null?F=K=p:K=K.next=p}else F=K=p;k={baseState:M.baseState,firstBaseUpdate:F,lastBaseUpdate:K,shared:M.shared,effects:M.effects},c.updateQueue=k;return}c=k.lastBaseUpdate,c===null?k.firstBaseUpdate=p:c.next=p,k.lastBaseUpdate=p}function Yc(c,p,k,M){var F=c.updateQueue;Mi=!1;var K=F.firstBaseUpdate,de=F.lastBaseUpdate,_e=F.shared.pending;if(_e!==null){F.shared.pending=null;var $e=_e,qe=$e.next;$e.next=null,de===null?K=qe:de.next=qe,de=$e;var at=c.alternate;at!==null&&(at=at.updateQueue,_e=at.lastBaseUpdate,_e!==de&&(_e===null?at.firstBaseUpdate=qe:_e.next=qe,at.lastBaseUpdate=$e))}if(K!==null){var ct=F.baseState;de=0,at=qe=$e=null,_e=K;do{var ot=_e.lane,jt=_e.eventTime;if((M&ot)===ot){at!==null&&(at=at.next={eventTime:jt,lane:0,tag:_e.tag,payload:_e.payload,callback:_e.callback,next:null});e:{var Pt=c,Dt=_e;switch(ot=p,jt=k,Dt.tag){case 1:if(Pt=Dt.payload,typeof Pt=="function"){ct=Pt.call(jt,ct,ot);break e}ct=Pt;break e;case 3:Pt.flags=Pt.flags&-65537|128;case 0:if(Pt=Dt.payload,ot=typeof Pt=="function"?Pt.call(jt,ct,ot):Pt,ot==null)break e;ct=Q({},ct,ot);break e;case 2:Mi=!0}}_e.callback!==null&&_e.lane!==0&&(c.flags|=64,ot=F.effects,ot===null?F.effects=[_e]:ot.push(_e))}else jt={eventTime:jt,lane:ot,tag:_e.tag,payload:_e.payload,callback:_e.callback,next:null},at===null?(qe=at=jt,$e=ct):at=at.next=jt,de|=ot;if(_e=_e.next,_e===null){if(_e=F.shared.pending,_e===null)break;ot=_e,_e=ot.next,ot.next=null,F.lastBaseUpdate=ot,F.shared.pending=null}}while(!0);if(at===null&&($e=ct),F.baseState=$e,F.firstBaseUpdate=qe,F.lastBaseUpdate=at,p=F.shared.interleaved,p!==null){F=p;do de|=F.lane,F=F.next;while(F!==p)}else K===null&&(F.shared.lanes=0);la|=de,c.lanes=de,c.memoizedState=ct}}function Eg(c,p,k){if(c=p.effects,p.effects=null,c!==null)for(p=0;p<c.length;p++){var M=c[p],F=M.callback;if(F!==null){if(M.callback=null,M=k,typeof F!="function")throw Error(r(191,F));F.call(M)}}}var Ll={},Ii=Ki(Ll),zl=Ki(Ll),qa=Ki(Ll);function ra(c){if(c===Ll)throw Error(r(174));return c}function Td(c,p){switch(In(qa,p),In(zl,c),In(Ii,Ll),c=p.nodeType,c){case 9:case 11:p=(p=p.documentElement)?p.namespaceURI:Tr(null,"");break;default:c=c===8?p.parentNode:p,p=c.namespaceURI||null,c=c.tagName,p=Tr(p,c)}Bn(Ii),In(Ii,p)}function sa(){Bn(Ii),Bn(zl),Bn(qa)}function Lf(c){ra(qa.current);var p=ra(Ii.current),k=Tr(p,c.type);p!==k&&(In(zl,c),In(Ii,k))}function $d(c){zl.current===c&&(Bn(Ii),Bn(zl))}var Yn=Ki(0);function Jc(c){for(var p=c;p!==null;){if(p.tag===13){var k=p.memoizedState;if(k!==null&&(k=k.dehydrated,k===null||k.data==="$?"||k.data==="$!"))return p}else if(p.tag===19&&p.memoizedProps.revealOrder!==void 0){if((p.flags&128)!==0)return p}else if(p.child!==null){p.child.return=p,p=p.child;continue}if(p===c)break;for(;p.sibling===null;){if(p.return===null||p.return===c)return null;p=p.return}p.sibling.return=p.return,p=p.sibling}return null}var Ad=[];function Rd(){for(var c=0;c<Ad.length;c++)Ad[c]._workInProgressVersionPrimary=null;Ad.length=0}var Md=N.ReactCurrentDispatcher,Id=N.ReactCurrentBatchConfig,ia=0,Xn=null,dr=null,vr=null,Pd=!1,oa=!1,Eo=0,zf=0;function Dr(){throw Error(r(321))}function Dd(c,p){if(p===null)return!1;for(var k=0;k<p.length&&k<c.length;k++)if(!ai(c[k],p[k]))return!1;return!0}function Od(c,p,k,M,F,K){if(ia=K,Xn=p,p.memoizedState=null,p.updateQueue=null,p.lanes=0,Md.current=c===null||c.memoizedState===null?Mg:Ig,c=k(M,F),oa){K=0;do{if(oa=!1,Eo=0,25<=K)throw Error(r(301));K+=1,vr=dr=null,p.updateQueue=null,Md.current=mv,c=k(M,F)}while(oa)}if(Md.current=tu,p=dr!==null&&dr.next!==null,ia=0,vr=dr=Xn=null,Pd=!1,p)throw Error(r(300));return c}function Ld(){var c=Eo!==0;return Eo=0,c}function ci(){var c={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return vr===null?Xn.memoizedState=vr=c:vr=vr.next=c,vr}function Hs(){if(dr===null){var c=Xn.alternate;c=c!==null?c.memoizedState:null}else c=dr.next;var p=vr===null?Xn.memoizedState:vr.next;if(p!==null)vr=p,dr=c;else{if(c===null)throw Error(r(310));dr=c,c={memoizedState:dr.memoizedState,baseState:dr.baseState,baseQueue:dr.baseQueue,queue:dr.queue,next:null},vr===null?Xn.memoizedState=vr=c:vr=vr.next=c}return vr}function Bl(c,p){return typeof p=="function"?p(c):p}function zd(c){var p=Hs(),k=p.queue;if(k===null)throw Error(r(311));k.lastRenderedReducer=c;var M=dr,F=M.baseQueue,K=k.pending;if(K!==null){if(F!==null){var de=F.next;F.next=K.next,K.next=de}M.baseQueue=F=K,k.pending=null}if(F!==null){K=F.next,M=M.baseState;var _e=de=null,$e=null,qe=K;do{var at=qe.lane;if((ia&at)===at)$e!==null&&($e=$e.next={lane:0,action:qe.action,hasEagerState:qe.hasEagerState,eagerState:qe.eagerState,next:null}),M=qe.hasEagerState?qe.eagerState:c(M,qe.action);else{var ct={lane:at,action:qe.action,hasEagerState:qe.hasEagerState,eagerState:qe.eagerState,next:null};$e===null?(_e=$e=ct,de=M):$e=$e.next=ct,Xn.lanes|=at,la|=at}qe=qe.next}while(qe!==null&&qe!==K);$e===null?de=M:$e.next=_e,ai(M,p.memoizedState)||(ys=!0),p.memoizedState=M,p.baseState=de,p.baseQueue=$e,k.lastRenderedState=M}if(c=k.interleaved,c!==null){F=c;do K=F.lane,Xn.lanes|=K,la|=K,F=F.next;while(F!==c)}else F===null&&(k.lanes=0);return[p.memoizedState,k.dispatch]}function Bf(c){var p=Hs(),k=p.queue;if(k===null)throw Error(r(311));k.lastRenderedReducer=c;var M=k.dispatch,F=k.pending,K=p.memoizedState;if(F!==null){k.pending=null;var de=F=F.next;do K=c(K,de.action),de=de.next;while(de!==F);ai(K,p.memoizedState)||(ys=!0),p.memoizedState=K,p.baseQueue===null&&(p.baseState=K),k.lastRenderedState=K}return[K,M]}function Ff(){}function Bd(c,p){var k=Xn,M=Hs(),F=p(),K=!ai(M.memoizedState,F);if(K&&(M.memoizedState=F,ys=!0),M=M.queue,Xf(Wf.bind(null,k,M,c),[c]),M.getSnapshot!==p||K||vr!==null&&vr.memoizedState.tag&1){if(k.flags|=2048,Qc(9,Hf.bind(null,k,M,F,p),void 0,null),fr===null)throw Error(r(349));(ia&30)!==0||Uf(k,p,F)}return F}function Uf(c,p,k){c.flags|=16384,c={getSnapshot:p,value:k},p=Xn.updateQueue,p===null?(p={lastEffect:null,stores:null},Xn.updateQueue=p,p.stores=[c]):(k=p.stores,k===null?p.stores=[c]:k.push(c))}function Hf(c,p,k,M){p.value=k,p.getSnapshot=M,Ng(p)&&qf(c)}function Wf(c,p,k){return k(function(){Ng(p)&&qf(c)})}function Ng(c){var p=c.getSnapshot;c=c.value;try{var k=p();return!ai(c,k)}catch{return!0}}function qf(c){var p=Yi(c,1);p!==null&&hi(p,c,1,-1)}function Vf(c){var p=ci();return typeof c=="function"&&(c=c()),p.memoizedState=p.baseState=c,c={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Bl,lastRenderedState:c},p.queue=c,c=c.dispatch=Ag.bind(null,Xn,c),[p.memoizedState,c]}function Qc(c,p,k,M){return c={tag:c,create:p,destroy:k,deps:M,next:null},p=Xn.updateQueue,p===null?(p={lastEffect:null,stores:null},Xn.updateQueue=p,p.lastEffect=c.next=c):(k=p.lastEffect,k===null?p.lastEffect=c.next=c:(M=k.next,k.next=c,c.next=M,p.lastEffect=c)),c}function Gf(){return Hs().memoizedState}function Zc(c,p,k,M){var F=ci();Xn.flags|=c,F.memoizedState=Qc(1|p,k,void 0,M===void 0?null:M)}function eu(c,p,k,M){var F=Hs();M=M===void 0?null:M;var K=void 0;if(dr!==null){var de=dr.memoizedState;if(K=de.destroy,M!==null&&Dd(M,de.deps)){F.memoizedState=Qc(p,k,K,M);return}}Xn.flags|=c,F.memoizedState=Qc(1|p,k,K,M)}function Kf(c,p){return Zc(8390656,8,c,p)}function Xf(c,p){return eu(2048,8,c,p)}function Yf(c,p){return eu(4,2,c,p)}function Jf(c,p){return eu(4,4,c,p)}function Qf(c,p){if(typeof p=="function")return c=c(),p(c),function(){p(null)};if(p!=null)return c=c(),p.current=c,function(){p.current=null}}function Tg(c,p,k){return k=k!=null?k.concat([c]):null,eu(4,4,Qf.bind(null,p,c),k)}function Fd(){}function Zf(c,p){var k=Hs();p=p===void 0?null:p;var M=k.memoizedState;return M!==null&&p!==null&&Dd(p,M[1])?M[0]:(k.memoizedState=[c,p],c)}function ep(c,p){var k=Hs();p=p===void 0?null:p;var M=k.memoizedState;return M!==null&&p!==null&&Dd(p,M[1])?M[0]:(c=c(),k.memoizedState=[c,p],c)}function tp(c,p,k){return(ia&21)===0?(c.baseState&&(c.baseState=!1,ys=!0),c.memoizedState=k):(ai(k,p)||(k=Es(),Xn.lanes|=k,la|=k,c.baseState=!0),p)}function pv(c,p){var k=Pe;Pe=k!==0&&4>k?k:4,c(!0);var M=Id.transition;Id.transition={};try{c(!1),p()}finally{Pe=k,Id.transition=M}}function np(){return Hs().memoizedState}function $g(c,p,k){var M=Ao(c);if(k={lane:M,action:k,hasEagerState:!1,eagerState:null,next:null},rp(c))Rg(p,k);else if(k=Kc(c,p,k,M),k!==null){var F=es();hi(k,c,M,F),sp(k,p,M)}}function Ag(c,p,k){var M=Ao(c),F={lane:M,action:k,hasEagerState:!1,eagerState:null,next:null};if(rp(c))Rg(p,F);else{var K=c.alternate;if(c.lanes===0&&(K===null||K.lanes===0)&&(K=p.lastRenderedReducer,K!==null))try{var de=p.lastRenderedState,_e=K(de,k);if(F.hasEagerState=!0,F.eagerState=_e,ai(_e,de)){var $e=p.interleaved;$e===null?(F.next=F,Ed(p)):(F.next=$e.next,$e.next=F),p.interleaved=F;return}}catch{}finally{}k=Kc(c,p,F,M),k!==null&&(F=es(),hi(k,c,M,F),sp(k,p,M))}}function rp(c){var p=c.alternate;return c===Xn||p!==null&&p===Xn}function Rg(c,p){oa=Pd=!0;var k=c.pending;k===null?p.next=p:(p.next=k.next,k.next=p),c.pending=p}function sp(c,p,k){if((k&4194240)!==0){var M=p.lanes;M&=c.pendingLanes,k|=M,p.lanes=k,be(c,k)}}var tu={readContext:Us,useCallback:Dr,useContext:Dr,useEffect:Dr,useImperativeHandle:Dr,useInsertionEffect:Dr,useLayoutEffect:Dr,useMemo:Dr,useReducer:Dr,useRef:Dr,useState:Dr,useDebugValue:Dr,useDeferredValue:Dr,useTransition:Dr,useMutableSource:Dr,useSyncExternalStore:Dr,useId:Dr,unstable_isNewReconciler:!1},Mg={readContext:Us,useCallback:function(c,p){return ci().memoizedState=[c,p===void 0?null:p],c},useContext:Us,useEffect:Kf,useImperativeHandle:function(c,p,k){return k=k!=null?k.concat([c]):null,Zc(4194308,4,Qf.bind(null,p,c),k)},useLayoutEffect:function(c,p){return Zc(4194308,4,c,p)},useInsertionEffect:function(c,p){return Zc(4,2,c,p)},useMemo:function(c,p){var k=ci();return p=p===void 0?null:p,c=c(),k.memoizedState=[c,p],c},useReducer:function(c,p,k){var M=ci();return p=k!==void 0?k(p):p,M.memoizedState=M.baseState=p,c={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:c,lastRenderedState:p},M.queue=c,c=c.dispatch=$g.bind(null,Xn,c),[M.memoizedState,c]},useRef:function(c){var p=ci();return c={current:c},p.memoizedState=c},useState:Vf,useDebugValue:Fd,useDeferredValue:function(c){return ci().memoizedState=c},useTransition:function(){var c=Vf(!1),p=c[0];return c=pv.bind(null,c[1]),ci().memoizedState=c,[p,c]},useMutableSource:function(){},useSyncExternalStore:function(c,p,k){var M=Xn,F=ci();if(Kn){if(k===void 0)throw Error(r(407));k=k()}else{if(k=p(),fr===null)throw Error(r(349));(ia&30)!==0||Uf(M,p,k)}F.memoizedState=k;var K={value:k,getSnapshot:p};return F.queue=K,Kf(Wf.bind(null,M,K,c),[c]),M.flags|=2048,Qc(9,Hf.bind(null,M,K,k,p),void 0,null),k},useId:function(){var c=ci(),p=fr.identifierPrefix;if(Kn){var k=ms,M=ps;k=(M&~(1<<32-Gn(M)-1)).toString(32)+k,p=":"+p+"R"+k,k=Eo++,0<k&&(p+="H"+k.toString(32)),p+=":"}else k=zf++,p=":"+p+"r"+k.toString(32)+":";return c.memoizedState=p},unstable_isNewReconciler:!1},Ig={readContext:Us,useCallback:Zf,useContext:Us,useEffect:Xf,useImperativeHandle:Tg,useInsertionEffect:Yf,useLayoutEffect:Jf,useMemo:ep,useReducer:zd,useRef:Gf,useState:function(){return zd(Bl)},useDebugValue:Fd,useDeferredValue:function(c){var p=Hs();return tp(p,dr.memoizedState,c)},useTransition:function(){var c=zd(Bl)[0],p=Hs().memoizedState;return[c,p]},useMutableSource:Ff,useSyncExternalStore:Bd,useId:np,unstable_isNewReconciler:!1},mv={readContext:Us,useCallback:Zf,useContext:Us,useEffect:Xf,useImperativeHandle:Tg,useInsertionEffect:Yf,useLayoutEffect:Jf,useMemo:ep,useReducer:Bf,useRef:Gf,useState:function(){return Bf(Bl)},useDebugValue:Fd,useDeferredValue:function(c){var p=Hs();return dr===null?p.memoizedState=c:tp(p,dr.memoizedState,c)},useTransition:function(){var c=Bf(Bl)[0],p=Hs().memoizedState;return[c,p]},useMutableSource:Ff,useSyncExternalStore:Bd,useId:np,unstable_isNewReconciler:!1};function hr(c,p){if(c&&c.defaultProps){p=Q({},p),c=c.defaultProps;for(var k in c)p[k]===void 0&&(p[k]=c[k]);return p}return p}function Pi(c,p,k,M){p=c.memoizedState,k=k(M,p),k=k==null?p:Q({},p,k),c.memoizedState=k,c.lanes===0&&(c.updateQueue.baseState=k)}var Qi={isMounted:function(c){return(c=c._reactInternals)?Ct(c)===c:!1},enqueueSetState:function(c,p,k){c=c._reactInternals;var M=es(),F=Ao(c),K=Ji(M,F);K.payload=p,k!=null&&(K.callback=k),p=jo(c,K,F),p!==null&&(hi(p,c,F,M),Ol(p,c,F))},enqueueReplaceState:function(c,p,k){c=c._reactInternals;var M=es(),F=Ao(c),K=Ji(M,F);K.tag=1,K.payload=p,k!=null&&(K.callback=k),p=jo(c,K,F),p!==null&&(hi(p,c,F,M),Ol(p,c,F))},enqueueForceUpdate:function(c,p){c=c._reactInternals;var k=es(),M=Ao(c),F=Ji(k,M);F.tag=2,p!=null&&(F.callback=p),p=jo(c,F,M),p!==null&&(hi(p,c,M,k),Ol(p,c,M))}};function aa(c,p,k,M,F,K,de){return c=c.stateNode,typeof c.shouldComponentUpdate=="function"?c.shouldComponentUpdate(M,K,de):p.prototype&&p.prototype.isPureReactComponent?!Nl(k,M)||!Nl(F,K):!0}function ip(c,p,k){var M=!1,F=ko,K=p.contextType;return typeof K=="object"&&K!==null?K=Us(K):(F=fs(p)?Qo:Jr.current,M=p.contextTypes,K=(M=M!=null)?Qr(c,F):ko),p=new p(k,K),c.memoizedState=p.state!==null&&p.state!==void 0?p.state:null,p.updater=Qi,c.stateNode=p,p._reactInternals=c,M&&(c=c.stateNode,c.__reactInternalMemoizedUnmaskedChildContext=F,c.__reactInternalMemoizedMaskedChildContext=K),p}function op(c,p,k,M){c=p.state,typeof p.componentWillReceiveProps=="function"&&p.componentWillReceiveProps(k,M),typeof p.UNSAFE_componentWillReceiveProps=="function"&&p.UNSAFE_componentWillReceiveProps(k,M),p.state!==c&&Qi.enqueueReplaceState(p,p.state,null)}function Ud(c,p,k,M){var F=c.stateNode;F.props=k,F.state=c.memoizedState,F.refs={},Xc(c);var K=p.contextType;typeof K=="object"&&K!==null?F.context=Us(K):(K=fs(p)?Qo:Jr.current,F.context=Qr(c,K)),F.state=c.memoizedState,K=p.getDerivedStateFromProps,typeof K=="function"&&(Pi(c,p,K,k),F.state=c.memoizedState),typeof p.getDerivedStateFromProps=="function"||typeof F.getSnapshotBeforeUpdate=="function"||typeof F.UNSAFE_componentWillMount!="function"&&typeof F.componentWillMount!="function"||(p=F.state,typeof F.componentWillMount=="function"&&F.componentWillMount(),typeof F.UNSAFE_componentWillMount=="function"&&F.UNSAFE_componentWillMount(),p!==F.state&&Qi.enqueueReplaceState(F,F.state,null),Yc(c,k,F,M),F.state=c.memoizedState),typeof F.componentDidMount=="function"&&(c.flags|=4194308)}function Va(c,p){try{var k="",M=p;do k+=Ae(M),M=M.return;while(M);var F=k}catch(K){F=`
|
|
38
|
+
`+F[de].replace(" at new "," at ");return c.displayName&&$e.includes("<anonymous>")&&($e=$e.replace("<anonymous>",c.displayName)),$e}while(1<=de&&0<=_e);break}}}finally{ce=!1,Error.prepareStackTrace=k}return(c=c?c.displayName||c.name:"")?le(c):""}function Ae(c){switch(c.tag){case 5:return le(c.type);case 16:return le("Lazy");case 13:return le("Suspense");case 19:return le("SuspenseList");case 0:case 2:case 15:return c=pe(c.type,!1),c;case 11:return c=pe(c.type.render,!1),c;case 1:return c=pe(c.type,!0),c;default:return""}}function Se(c){if(c==null)return null;if(typeof c=="function")return c.displayName||c.name||null;if(typeof c=="string")return c;switch(c){case O:return"Fragment";case R:return"Portal";case z:return"Profiler";case I:return"StrictMode";case V:return"Suspense";case H:return"SuspenseList"}if(typeof c=="object")switch(c.$$typeof){case W:return(c.displayName||"Context")+".Consumer";case U:return(c._context.displayName||"Context")+".Provider";case Y:var p=c.render;return c=c.displayName,c||(c=p.displayName||p.name||"",c=c!==""?"ForwardRef("+c+")":"ForwardRef"),c;case te:return p=c.displayName||null,p!==null?p:Se(c.type)||"Memo";case ae:p=c._payload,c=c._init;try{return Se(c(p))}catch{}}return null}function ye(c){var p=c.type;switch(c.tag){case 24:return"Cache";case 9:return(p.displayName||"Context")+".Consumer";case 10:return(p._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return c=p.render,c=c.displayName||c.name||"",p.displayName||(c!==""?"ForwardRef("+c+")":"ForwardRef");case 7:return"Fragment";case 5:return p;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Se(p);case 8:return p===I?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof p=="function")return p.displayName||p.name||null;if(typeof p=="string")return p}return null}function ne(c){switch(typeof c){case"boolean":case"number":case"string":case"undefined":return c;case"object":return c;default:return""}}function we(c){var p=c.type;return(c=c.nodeName)&&c.toLowerCase()==="input"&&(p==="checkbox"||p==="radio")}function Ne(c){var p=we(c)?"checked":"value",k=Object.getOwnPropertyDescriptor(c.constructor.prototype,p),M=""+c[p];if(!c.hasOwnProperty(p)&&typeof k<"u"&&typeof k.get=="function"&&typeof k.set=="function"){var F=k.get,K=k.set;return Object.defineProperty(c,p,{configurable:!0,get:function(){return F.call(this)},set:function(de){M=""+de,K.call(this,de)}}),Object.defineProperty(c,p,{enumerable:k.enumerable}),{getValue:function(){return M},setValue:function(de){M=""+de},stopTracking:function(){c._valueTracker=null,delete c[p]}}}}function Je(c){c._valueTracker||(c._valueTracker=Ne(c))}function lt(c){if(!c)return!1;var p=c._valueTracker;if(!p)return!0;var k=p.getValue(),M="";return c&&(M=we(c)?c.checked?"true":"false":c.value),c=M,c!==k?(p.setValue(c),!0):!1}function xt(c){if(c=c||(typeof document<"u"?document:void 0),typeof c>"u")return null;try{return c.activeElement||c.body}catch{return c.body}}function Rt(c,p){var k=p.checked;return Q({},p,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:k??c._wrapperState.initialChecked})}function He(c,p){var k=p.defaultValue==null?"":p.defaultValue,M=p.checked!=null?p.checked:p.defaultChecked;k=ne(p.value!=null?p.value:k),c._wrapperState={initialChecked:M,initialValue:k,controlled:p.type==="checkbox"||p.type==="radio"?p.checked!=null:p.value!=null}}function vt(c,p){p=p.checked,p!=null&&C(c,"checked",p,!1)}function st(c,p){vt(c,p);var k=ne(p.value),M=p.type;if(k!=null)M==="number"?(k===0&&c.value===""||c.value!=k)&&(c.value=""+k):c.value!==""+k&&(c.value=""+k);else if(M==="submit"||M==="reset"){c.removeAttribute("value");return}p.hasOwnProperty("value")?sn(c,p.type,k):p.hasOwnProperty("defaultValue")&&sn(c,p.type,ne(p.defaultValue)),p.checked==null&&p.defaultChecked!=null&&(c.defaultChecked=!!p.defaultChecked)}function an(c,p,k){if(p.hasOwnProperty("value")||p.hasOwnProperty("defaultValue")){var M=p.type;if(!(M!=="submit"&&M!=="reset"||p.value!==void 0&&p.value!==null))return;p=""+c._wrapperState.initialValue,k||p===c.value||(c.value=p),c.defaultValue=p}k=c.name,k!==""&&(c.name=""),c.defaultChecked=!!c._wrapperState.initialChecked,k!==""&&(c.name=k)}function sn(c,p,k){(p!=="number"||xt(c.ownerDocument)!==c)&&(k==null?c.defaultValue=""+c._wrapperState.initialValue:c.defaultValue!==""+k&&(c.defaultValue=""+k))}var Ye=Array.isArray;function yt(c,p,k,M){if(c=c.options,p){p={};for(var F=0;F<k.length;F++)p["$"+k[F]]=!0;for(k=0;k<c.length;k++)F=p.hasOwnProperty("$"+c[k].value),c[k].selected!==F&&(c[k].selected=F),F&&M&&(c[k].defaultSelected=!0)}else{for(k=""+ne(k),p=null,F=0;F<c.length;F++){if(c[F].value===k){c[F].selected=!0,M&&(c[F].defaultSelected=!0);return}p!==null||c[F].disabled||(p=c[F])}p!==null&&(p.selected=!0)}}function kt(c,p){if(p.dangerouslySetInnerHTML!=null)throw Error(r(91));return Q({},p,{value:void 0,defaultValue:void 0,children:""+c._wrapperState.initialValue})}function Kt(c,p){var k=p.value;if(k==null){if(k=p.children,p=p.defaultValue,k!=null){if(p!=null)throw Error(r(92));if(Ye(k)){if(1<k.length)throw Error(r(93));k=k[0]}p=k}p==null&&(p=""),k=p}c._wrapperState={initialValue:ne(k)}}function On(c,p){var k=ne(p.value),M=ne(p.defaultValue);k!=null&&(k=""+k,k!==c.value&&(c.value=k),p.defaultValue==null&&c.defaultValue!==k&&(c.defaultValue=k)),M!=null&&(c.defaultValue=""+M)}function Rn(c){var p=c.textContent;p===c._wrapperState.initialValue&&p!==""&&p!==null&&(c.value=p)}function Br(c){switch(c){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Tr(c,p){return c==null||c==="http://www.w3.org/1999/xhtml"?Br(p):c==="http://www.w3.org/2000/svg"&&p==="foreignObject"?"http://www.w3.org/1999/xhtml":c}var nt,St=(function(c){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(p,k,M,F){MSApp.execUnsafeLocalFunction(function(){return c(p,k,M,F)})}:c})(function(c,p){if(c.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in c)c.innerHTML=p;else{for(nt=nt||document.createElement("div"),nt.innerHTML="<svg>"+p.valueOf().toString()+"</svg>",p=nt.firstChild;c.firstChild;)c.removeChild(c.firstChild);for(;p.firstChild;)c.appendChild(p.firstChild)}});function Tt(c,p){if(p){var k=c.firstChild;if(k&&k===c.lastChild&&k.nodeType===3){k.nodeValue=p;return}}c.textContent=p}var cn={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},nn=["Webkit","ms","Moz","O"];Object.keys(cn).forEach(function(c){nn.forEach(function(p){p=p+c.charAt(0).toUpperCase()+c.substring(1),cn[p]=cn[c]})});function $r(c,p,k){return p==null||typeof p=="boolean"||p===""?"":k||typeof p!="number"||p===0||cn.hasOwnProperty(c)&&cn[c]?(""+p).trim():p+"px"}function Ta(c,p){c=c.style;for(var k in p)if(p.hasOwnProperty(k)){var M=k.indexOf("--")===0,F=$r(k,p[k],M);k==="float"&&(k="cssFloat"),M?c.setProperty(k,F):c[k]=F}}var Vo=Q({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function vi(c,p){if(p){if(Vo[c]&&(p.children!=null||p.dangerouslySetInnerHTML!=null))throw Error(r(137,c));if(p.dangerouslySetInnerHTML!=null){if(p.children!=null)throw Error(r(60));if(typeof p.dangerouslySetInnerHTML!="object"||!("__html"in p.dangerouslySetInnerHTML))throw Error(r(61))}if(p.style!=null&&typeof p.style!="object")throw Error(r(62))}}function yn(c,p){if(c.indexOf("-")===-1)return typeof p.is=="string";switch(c){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var Fr=null;function Zn(c){return c=c.target||c.srcElement||window,c.correspondingUseElement&&(c=c.correspondingUseElement),c.nodeType===3?c.parentNode:c}var bi=null,Ms=null,as=null;function Fi(c){if(c=Pl(c)){if(typeof bi!="function")throw Error(r(280));var p=c.stateNode;p&&(p=Bc(p),bi(c.stateNode,c.type,p))}}function wi(c){Ms?as?as.push(c):as=[c]:Ms=c}function _i(){if(Ms){var c=Ms,p=as;if(as=Ms=null,Fi(c),p)for(c=0;c<p.length;c++)Fi(p[c])}}function Is(c,p){return c(p)}function Ar(){}var Ur=!1;function Qs(c,p,k){if(Ur)return c(p,k);Ur=!0;try{return Is(c,p,k)}finally{Ur=!1,(Ms!==null||as!==null)&&(Ar(),_i())}}function Rr(c,p){var k=c.stateNode;if(k===null)return null;var M=Bc(k);if(M===null)return null;k=M[p];e:switch(p){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(M=!M.disabled)||(c=c.type,M=!(c==="button"||c==="input"||c==="select"||c==="textarea")),c=!M;break e;default:c=!1}if(c)return null;if(k&&typeof k!="function")throw Error(r(231,p,typeof k));return k}var ls=!1;if(u)try{var js={};Object.defineProperty(js,"passive",{get:function(){ls=!0}}),window.addEventListener("test",js,js),window.removeEventListener("test",js,js)}catch{ls=!1}function ho(c,p,k,M,F,K,de,_e,$e){var qe=Array.prototype.slice.call(arguments,3);try{p.apply(k,qe)}catch(at){this.onError(at)}}var Zs=!1,ei=null,ti=!1,zt=null,Hr={onError:function(c){Zs=!0,ei=c}};function Hn(c,p,k,M,F,K,de,_e,$e){Zs=!1,ei=null,ho.apply(Hr,arguments)}function _n(c,p,k,M,F,K,de,_e,$e){if(Hn.apply(this,arguments),Zs){if(Zs){var qe=ei;Zs=!1,ei=null}else throw Error(r(198));ti||(ti=!0,zt=qe)}}function Ct(c){var p=c,k=c;if(c.alternate)for(;p.return;)p=p.return;else{c=p;do p=c,(p.flags&4098)!==0&&(k=p.return),c=p.return;while(c)}return p.tag===3?k:null}function Ui(c){if(c.tag===13){var p=c.memoizedState;if(p===null&&(c=c.alternate,c!==null&&(p=c.memoizedState)),p!==null)return p.dehydrated}return null}function fo(c){if(Ct(c)!==c)throw Error(r(188))}function $a(c){var p=c.alternate;if(!p){if(p=Ct(c),p===null)throw Error(r(188));return p!==c?null:c}for(var k=c,M=p;;){var F=k.return;if(F===null)break;var K=F.alternate;if(K===null){if(M=F.return,M!==null){k=M;continue}break}if(F.child===K.child){for(K=F.child;K;){if(K===k)return fo(F),c;if(K===M)return fo(F),p;K=K.sibling}throw Error(r(188))}if(k.return!==M.return)k=F,M=K;else{for(var de=!1,_e=F.child;_e;){if(_e===k){de=!0,k=F,M=K;break}if(_e===M){de=!0,M=F,k=K;break}_e=_e.sibling}if(!de){for(_e=K.child;_e;){if(_e===k){de=!0,k=K,M=F;break}if(_e===M){de=!0,M=K,k=F;break}_e=_e.sibling}if(!de)throw Error(r(189))}}if(k.alternate!==M)throw Error(r(190))}if(k.tag!==3)throw Error(r(188));return k.stateNode.current===k?c:p}function po(c){return c=$a(c),c!==null?mo(c):null}function mo(c){if(c.tag===5||c.tag===6)return c;for(c=c.child;c!==null;){var p=mo(c);if(p!==null)return p;c=c.sibling}return null}var Go=n.unstable_scheduleCallback,Sr=n.unstable_cancelCallback,Aa=n.unstable_shouldYield,Ra=n.unstable_requestPaint,kn=n.unstable_now,Mr=n.unstable_getCurrentPriorityLevel,Vn=n.unstable_ImmediatePriority,Ir=n.unstable_UserBlockingPriority,ni=n.unstable_NormalPriority,Hi=n.unstable_LowPriority,ki=n.unstable_IdlePriority,cs=null,gr=null;function Bt(c){if(gr&&typeof gr.onCommitFiberRoot=="function")try{gr.onCommitFiberRoot(cs,c,void 0,(c.current.flags&128)===128)}catch{}}var Gn=Math.clz32?Math.clz32:Ko,Si=Math.log,us=Math.LN2;function Ko(c){return c>>>=0,c===0?32:31-(Si(c)/us|0)|0}var Ci=64,Wr=4194304;function Ps(c){switch(c&-c){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return c&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return c&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return c}}function ji(c,p){var k=c.pendingLanes;if(k===0)return 0;var M=0,F=c.suspendedLanes,K=c.pingedLanes,de=k&268435455;if(de!==0){var _e=de&~F;_e!==0?M=Ps(_e):(K&=de,K!==0&&(M=Ps(K)))}else de=k&~F,de!==0?M=Ps(de):K!==0&&(M=Ps(K));if(M===0)return 0;if(p!==0&&p!==M&&(p&F)===0&&(F=M&-M,K=p&-p,F>=K||F===16&&(K&4194240)!==0))return p;if((M&4)!==0&&(M|=k&16),p=c.entangledLanes,p!==0)for(c=c.entanglements,p&=M;0<p;)k=31-Gn(p),F=1<<k,M|=c[k],p&=~F;return M}function on(c,p){switch(c){case 1:case 2:case 4:return p+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return p+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function ds(c,p){for(var k=c.suspendedLanes,M=c.pingedLanes,F=c.expirationTimes,K=c.pendingLanes;0<K;){var de=31-Gn(K),_e=1<<de,$e=F[de];$e===-1?((_e&k)===0||(_e&M)!==0)&&(F[de]=on(_e,p)):$e<=p&&(c.expiredLanes|=_e),K&=~_e}}function Wi(c){return c=c.pendingLanes&-1073741825,c!==0?c:c&1073741824?1073741824:0}function Es(){var c=Ci;return Ci<<=1,(Ci&4194240)===0&&(Ci=64),c}function Ke(c){for(var p=[],k=0;31>k;k++)p.push(c);return p}function qr(c,p,k){c.pendingLanes|=p,p!==536870912&&(c.suspendedLanes=0,c.pingedLanes=0),c=c.eventTimes,p=31-Gn(p),c[p]=k}function ft(c,p){var k=c.pendingLanes&~p;c.pendingLanes=p,c.suspendedLanes=0,c.pingedLanes=0,c.expiredLanes&=p,c.mutableReadLanes&=p,c.entangledLanes&=p,p=c.entanglements;var M=c.eventTimes;for(c=c.expirationTimes;0<k;){var F=31-Gn(k),K=1<<F;p[F]=0,M[F]=-1,c[F]=-1,k&=~K}}function be(c,p){var k=c.entangledLanes|=p;for(c=c.entanglements;k;){var M=31-Gn(k),F=1<<M;F&p|c[M]&p&&(c[M]|=p),k&=~F}}var Pe=0;function Qe(c){return c&=-c,1<c?4<c?(c&268435455)!==0?16:536870912:4:1}var Et,en,ln,$n,En,er=!1,Ln=[],sr=null,Nn=null,Ds=null,qi=new Map,go=new Map,ri=[],Vu="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function xo(c,p){switch(c){case"focusin":case"focusout":sr=null;break;case"dragenter":case"dragleave":Nn=null;break;case"mouseover":case"mouseout":Ds=null;break;case"pointerover":case"pointerout":qi.delete(p.pointerId);break;case"gotpointercapture":case"lostpointercapture":go.delete(p.pointerId)}}function yo(c,p,k,M,F,K){return c===null||c.nativeEvent!==K?(c={blockedOn:p,domEventName:k,eventSystemFlags:M,nativeEvent:K,targetContainers:[F]},p!==null&&(p=Pl(p),p!==null&&en(p)),c):(c.eventSystemFlags|=M,p=c.targetContainers,F!==null&&p.indexOf(F)===-1&&p.push(F),c)}function Sc(c,p,k,M,F){switch(p){case"focusin":return sr=yo(sr,c,p,k,M,F),!0;case"dragenter":return Nn=yo(Nn,c,p,k,M,F),!0;case"mouseover":return Ds=yo(Ds,c,p,k,M,F),!0;case"pointerover":var K=F.pointerId;return qi.set(K,yo(qi.get(K)||null,c,p,k,M,F)),!0;case"gotpointercapture":return K=F.pointerId,go.set(K,yo(go.get(K)||null,c,p,k,M,F)),!0}return!1}function bl(c){var p=Jo(c.target);if(p!==null){var k=Ct(p);if(k!==null){if(p=k.tag,p===13){if(p=Ui(k),p!==null){c.blockedOn=p,En(c.priority,function(){ln(k)});return}}else if(p===3&&k.stateNode.current.memoizedState.isDehydrated){c.blockedOn=k.tag===3?k.stateNode.containerInfo:null;return}}}c.blockedOn=null}function vo(c){if(c.blockedOn!==null)return!1;for(var p=c.targetContainers;0<p.length;){var k=re(c.domEventName,c.eventSystemFlags,p[0],c.nativeEvent);if(k===null){k=c.nativeEvent;var M=new k.constructor(k.type,k);Fr=M,k.target.dispatchEvent(M),Fr=null}else return p=Pl(k),p!==null&&en(p),c.blockedOn=k,!1;p.shift()}return!0}function Ma(c,p,k){vo(c)&&k.delete(p)}function wl(){er=!1,sr!==null&&vo(sr)&&(sr=null),Nn!==null&&vo(Nn)&&(Nn=null),Ds!==null&&vo(Ds)&&(Ds=null),qi.forEach(Ma),go.forEach(Ma)}function Ei(c,p){c.blockedOn===p&&(c.blockedOn=null,er||(er=!0,n.unstable_scheduleCallback(n.unstable_NormalPriority,wl)))}function Vi(c){function p(F){return Ei(F,c)}if(0<Ln.length){Ei(Ln[0],c);for(var k=1;k<Ln.length;k++){var M=Ln[k];M.blockedOn===c&&(M.blockedOn=null)}}for(sr!==null&&Ei(sr,c),Nn!==null&&Ei(Nn,c),Ds!==null&&Ei(Ds,c),qi.forEach(p),go.forEach(p),k=0;k<ri.length;k++)M=ri[k],M.blockedOn===c&&(M.blockedOn=null);for(;0<ri.length&&(k=ri[0],k.blockedOn===null);)bl(k),k.blockedOn===null&&ri.shift()}var Ni=N.ReactCurrentBatchConfig,bo=!0;function Cc(c,p,k,M){var F=Pe,K=Ni.transition;Ni.transition=null;try{Pe=1,_l(c,p,k,M)}finally{Pe=F,Ni.transition=K}}function jc(c,p,k,M){var F=Pe,K=Ni.transition;Ni.transition=null;try{Pe=4,_l(c,p,k,M)}finally{Pe=F,Ni.transition=K}}function _l(c,p,k,M){if(bo){var F=re(c,p,k,M);if(F===null)od(c,p,M,kl,k),xo(c,M);else if(Sc(F,c,p,k,M))M.stopPropagation();else if(xo(c,M),p&4&&-1<Vu.indexOf(c)){for(;F!==null;){var K=Pl(F);if(K!==null&&Et(K),K=re(c,p,k,M),K===null&&od(c,p,M,kl,k),K===F)break;F=K}F!==null&&M.stopPropagation()}else od(c,p,M,null,k)}}var kl=null;function re(c,p,k,M){if(kl=null,c=Zn(M),c=Jo(c),c!==null)if(p=Ct(c),p===null)c=null;else if(k=p.tag,k===13){if(c=Ui(p),c!==null)return c;c=null}else if(k===3){if(p.stateNode.current.memoizedState.isDehydrated)return p.tag===3?p.stateNode.containerInfo:null;c=null}else p!==c&&(c=null);return kl=c,null}function fe(c){switch(c){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(Mr()){case Vn:return 1;case Ir:return 4;case ni:case Hi:return 16;case ki:return 536870912;default:return 16}default:return 16}}var ve=null,Te=null,Ce=null;function Be(){if(Ce)return Ce;var c,p=Te,k=p.length,M,F="value"in ve?ve.value:ve.textContent,K=F.length;for(c=0;c<k&&p[c]===F[c];c++);var de=k-c;for(M=1;M<=de&&p[k-M]===F[K-M];M++);return Ce=F.slice(c,1<M?1-M:void 0)}function Re(c){var p=c.keyCode;return"charCode"in c?(c=c.charCode,c===0&&p===13&&(c=13)):c=p,c===10&&(c=13),32<=c||c===13?c:0}function Me(){return!0}function Fe(){return!1}function et(c){function p(k,M,F,K,de){this._reactName=k,this._targetInst=F,this.type=M,this.nativeEvent=K,this.target=de,this.currentTarget=null;for(var _e in c)c.hasOwnProperty(_e)&&(k=c[_e],this[_e]=k?k(K):K[_e]);return this.isDefaultPrevented=(K.defaultPrevented!=null?K.defaultPrevented:K.returnValue===!1)?Me:Fe,this.isPropagationStopped=Fe,this}return Q(p.prototype,{preventDefault:function(){this.defaultPrevented=!0;var k=this.nativeEvent;k&&(k.preventDefault?k.preventDefault():typeof k.returnValue!="unknown"&&(k.returnValue=!1),this.isDefaultPrevented=Me)},stopPropagation:function(){var k=this.nativeEvent;k&&(k.stopPropagation?k.stopPropagation():typeof k.cancelBubble!="unknown"&&(k.cancelBubble=!0),this.isPropagationStopped=Me)},persist:function(){},isPersistent:Me}),p}var it={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(c){return c.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},tt=et(it),Xe=Q({},it,{view:0,detail:0}),At=et(Xe),ze,ut,Cn,Jt=Q({},Xe,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:un,button:0,buttons:0,relatedTarget:function(c){return c.relatedTarget===void 0?c.fromElement===c.srcElement?c.toElement:c.fromElement:c.relatedTarget},movementX:function(c){return"movementX"in c?c.movementX:(c!==Cn&&(Cn&&c.type==="mousemove"?(ze=c.screenX-Cn.screenX,ut=c.screenY-Cn.screenY):ut=ze=0,Cn=c),ze)},movementY:function(c){return"movementY"in c?c.movementY:ut}}),Qt=et(Jt),jn=Q({},Jt,{dataTransfer:0}),Ot=et(jn),Mn=Q({},Xe,{relatedTarget:0}),hn=et(Mn),xr=Q({},it,{animationName:0,elapsedTime:0,pseudoElement:0}),Pr=et(xr),Vr=Q({},it,{clipboardData:function(c){return"clipboardData"in c?c.clipboardData:window.clipboardData}}),Ia=et(Vr),Gr=Q({},it,{data:0}),Sl=et(Gr),Ec={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},yr={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},si={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Nc(c){var p=this.nativeEvent;return p.getModifierState?p.getModifierState(c):(c=si[c])?!!p[c]:!1}function un(){return Nc}var Os=Q({},Xe,{key:function(c){if(c.key){var p=Ec[c.key]||c.key;if(p!=="Unidentified")return p}return c.type==="keypress"?(c=Re(c),c===13?"Enter":String.fromCharCode(c)):c.type==="keydown"||c.type==="keyup"?yr[c.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:un,charCode:function(c){return c.type==="keypress"?Re(c):0},keyCode:function(c){return c.type==="keydown"||c.type==="keyup"?c.keyCode:0},which:function(c){return c.type==="keypress"?Re(c):c.type==="keydown"||c.type==="keyup"?c.keyCode:0}}),Gu=et(Os),Ti=Q({},Jt,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Xo=et(Ti),ir=Q({},Xe,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:un}),Kr=et(ir),Cl=Q({},it,{propertyName:0,elapsedTime:0,pseudoElement:0}),Xr=et(Cl),Tc=Q({},Jt,{deltaX:function(c){return"deltaX"in c?c.deltaX:"wheelDeltaX"in c?-c.wheelDeltaX:0},deltaY:function(c){return"deltaY"in c?c.deltaY:"wheelDeltaY"in c?-c.wheelDeltaY:"wheelDelta"in c?-c.wheelDelta:0},deltaZ:0,deltaMode:0}),Ku=et(Tc),$i=[9,13,27,32],Ls=u&&"CompositionEvent"in window,ii=null;u&&"documentMode"in document&&(ii=document.documentMode);var or=u&&"TextEvent"in window&&!ii,Wn=u&&(!Ls||ii&&8<ii&&11>=ii),zs=" ",$c=!1;function Ac(c,p){switch(c){case"keyup":return $i.indexOf(p.keyCode)!==-1;case"keydown":return p.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function lg(c){return c=c.detail,typeof c=="object"&&"data"in c?c.data:null}var Yr=!1;function cg(c,p){switch(c){case"compositionend":return lg(p);case"keypress":return p.which!==32?null:($c=!0,zs);case"textInput":return c=p.data,c===zs&&$c?null:c;default:return null}}function Xu(c,p){if(Yr)return c==="compositionend"||!Ls&&Ac(c,p)?(c=Be(),Ce=Te=ve=null,Yr=!1,c):null;switch(c){case"paste":return null;case"keypress":if(!(p.ctrlKey||p.altKey||p.metaKey)||p.ctrlKey&&p.altKey){if(p.char&&1<p.char.length)return p.char;if(p.which)return String.fromCharCode(p.which)}return null;case"compositionend":return Wn&&p.locale!=="ko"?null:p.data;default:return null}}var af={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function oi(c){var p=c&&c.nodeName&&c.nodeName.toLowerCase();return p==="input"?!!af[c.type]:p==="textarea"}function lf(c,p,k,M){wi(M),p=Pc(p,"onChange"),0<p.length&&(k=new tt("onChange","change",null,k,M),c.push({event:k,listeners:p}))}var jl=null,El=null;function ug(c){Sf(c,0)}function Rc(c){var p=Oa(c);if(lt(p))return c}function dg(c,p){if(c==="change")return p}var cf=!1;if(u){var Yu;if(u){var Ju="oninput"in document;if(!Ju){var uf=document.createElement("div");uf.setAttribute("oninput","return;"),Ju=typeof uf.oninput=="function"}Yu=Ju}else Yu=!1;cf=Yu&&(!document.documentMode||9<document.documentMode)}function ai(){jl&&(jl.detachEvent("onpropertychange",df),El=jl=null)}function df(c){if(c.propertyName==="value"&&Rc(El)){var p=[];lf(p,El,c,Zn(c)),Qs(ug,p)}}function hg(c,p,k){c==="focusin"?(ai(),jl=p,El=k,jl.attachEvent("onpropertychange",df)):c==="focusout"&&ai()}function fg(c){if(c==="selectionchange"||c==="keyup"||c==="keydown")return Rc(El)}function pg(c,p){if(c==="click")return Rc(p)}function mg(c,p){if(c==="input"||c==="change")return Rc(p)}function gg(c,p){return c===p&&(c!==0||1/c===1/p)||c!==c&&p!==p}var li=typeof Object.is=="function"?Object.is:gg;function Nl(c,p){if(li(c,p))return!0;if(typeof c!="object"||c===null||typeof p!="object"||p===null)return!1;var k=Object.keys(c),M=Object.keys(p);if(k.length!==M.length)return!1;for(M=0;M<k.length;M++){var F=k[M];if(!h.call(p,F)||!li(c[F],p[F]))return!1}return!0}function hf(c){for(;c&&c.firstChild;)c=c.firstChild;return c}function ff(c,p){var k=hf(c);c=0;for(var M;k;){if(k.nodeType===3){if(M=c+k.textContent.length,c<=p&&M>=p)return{node:k,offset:p-c};c=M}e:{for(;k;){if(k.nextSibling){k=k.nextSibling;break e}k=k.parentNode}k=void 0}k=hf(k)}}function Qu(c,p){return c&&p?c===p?!0:c&&c.nodeType===3?!1:p&&p.nodeType===3?Qu(c,p.parentNode):"contains"in c?c.contains(p):c.compareDocumentPosition?!!(c.compareDocumentPosition(p)&16):!1:!1}function Zu(){for(var c=window,p=xt();p instanceof c.HTMLIFrameElement;){try{var k=typeof p.contentWindow.location.href=="string"}catch{k=!1}if(k)c=p.contentWindow;else break;p=xt(c.document)}return p}function ed(c){var p=c&&c.nodeName&&c.nodeName.toLowerCase();return p&&(p==="input"&&(c.type==="text"||c.type==="search"||c.type==="tel"||c.type==="url"||c.type==="password")||p==="textarea"||c.contentEditable==="true")}function xg(c){var p=Zu(),k=c.focusedElem,M=c.selectionRange;if(p!==k&&k&&k.ownerDocument&&Qu(k.ownerDocument.documentElement,k)){if(M!==null&&ed(k)){if(p=M.start,c=M.end,c===void 0&&(c=p),"selectionStart"in k)k.selectionStart=p,k.selectionEnd=Math.min(c,k.value.length);else if(c=(p=k.ownerDocument||document)&&p.defaultView||window,c.getSelection){c=c.getSelection();var F=k.textContent.length,K=Math.min(M.start,F);M=M.end===void 0?K:Math.min(M.end,F),!c.extend&&K>M&&(F=M,M=K,K=F),F=ff(k,K);var de=ff(k,M);F&&de&&(c.rangeCount!==1||c.anchorNode!==F.node||c.anchorOffset!==F.offset||c.focusNode!==de.node||c.focusOffset!==de.offset)&&(p=p.createRange(),p.setStart(F.node,F.offset),c.removeAllRanges(),K>M?(c.addRange(p),c.extend(de.node,de.offset)):(p.setEnd(de.node,de.offset),c.addRange(p)))}}for(p=[],c=k;c=c.parentNode;)c.nodeType===1&&p.push({element:c,left:c.scrollLeft,top:c.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;k<p.length;k++)c=p[k],c.element.scrollLeft=c.left,c.element.scrollTop=c.top}}var pf=u&&"documentMode"in document&&11>=document.documentMode,Tl=null,td=null,Yo=null,nd=!1;function mf(c,p,k){var M=k.window===k?k.document:k.nodeType===9?k:k.ownerDocument;nd||Tl==null||Tl!==xt(M)||(M=Tl,"selectionStart"in M&&ed(M)?M={start:M.selectionStart,end:M.selectionEnd}:(M=(M.ownerDocument&&M.ownerDocument.defaultView||window).getSelection(),M={anchorNode:M.anchorNode,anchorOffset:M.anchorOffset,focusNode:M.focusNode,focusOffset:M.focusOffset}),Yo&&Nl(Yo,M)||(Yo=M,M=Pc(td,"onSelect"),0<M.length&&(p=new tt("onSelect","select",null,p,k),c.push({event:p,listeners:M}),p.target=Tl)))}function Mc(c,p){var k={};return k[c.toLowerCase()]=p.toLowerCase(),k["Webkit"+c]="webkit"+p,k["Moz"+c]="moz"+p,k}var Gi={animationend:Mc("Animation","AnimationEnd"),animationiteration:Mc("Animation","AnimationIteration"),animationstart:Mc("Animation","AnimationStart"),transitionend:Mc("Transition","TransitionEnd")},rd={},gf={};u&&(gf=document.createElement("div").style,"AnimationEvent"in window||(delete Gi.animationend.animation,delete Gi.animationiteration.animation,delete Gi.animationstart.animation),"TransitionEvent"in window||delete Gi.transitionend.transition);function $l(c){if(rd[c])return rd[c];if(!Gi[c])return c;var p=Gi[c],k;for(k in p)if(p.hasOwnProperty(k)&&k in gf)return rd[c]=p[k];return c}var xf=$l("animationend"),yf=$l("animationiteration"),vf=$l("animationstart"),bf=$l("transitionend"),yg=new Map,wf="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function wo(c,p){yg.set(c,p),l(p,[c])}for(var sd=0;sd<wf.length;sd++){var _f=wf[sd],vg=_f.toLowerCase(),mn=_f[0].toUpperCase()+_f.slice(1);wo(vg,"on"+mn)}wo(xf,"onAnimationEnd"),wo(yf,"onAnimationIteration"),wo(vf,"onAnimationStart"),wo("dblclick","onDoubleClick"),wo("focusin","onFocus"),wo("focusout","onBlur"),wo(bf,"onTransitionEnd"),d("onMouseEnter",["mouseout","mouseover"]),d("onMouseLeave",["mouseout","mouseover"]),d("onPointerEnter",["pointerout","pointerover"]),d("onPointerLeave",["pointerout","pointerover"]),l("onChange","change click focusin focusout input keydown keyup selectionchange".split(" ")),l("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" ")),l("onBeforeInput",["compositionend","keypress","textInput","paste"]),l("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" ")),l("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Al="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),bg=new Set("cancel close invalid load scroll toggle".split(" ").concat(Al));function kf(c,p,k){var M=c.type||"unknown-event";c.currentTarget=k,_n(M,p,void 0,c),c.currentTarget=null}function Sf(c,p){p=(p&4)!==0;for(var k=0;k<c.length;k++){var M=c[k],F=M.event;M=M.listeners;e:{var K=void 0;if(p)for(var de=M.length-1;0<=de;de--){var _e=M[de],$e=_e.instance,qe=_e.currentTarget;if(_e=_e.listener,$e!==K&&F.isPropagationStopped())break e;kf(F,_e,qe),K=$e}else for(de=0;de<M.length;de++){if(_e=M[de],$e=_e.instance,qe=_e.currentTarget,_e=_e.listener,$e!==K&&F.isPropagationStopped())break e;kf(F,_e,qe),K=$e}}}if(ti)throw c=zt,ti=!1,zt=null,c}function zn(c,p){var k=p[hd];k===void 0&&(k=p[hd]=new Set);var M=c+"__bubble";k.has(M)||(Cf(p,c,2,!1),k.add(M))}function id(c,p,k){var M=0;p&&(M|=4),Cf(k,c,M,p)}var Ic="_reactListening"+Math.random().toString(36).slice(2);function Rl(c){if(!c[Ic]){c[Ic]=!0,i.forEach(function(k){k!=="selectionchange"&&(bg.has(k)||id(k,!1,c),id(k,!0,c))});var p=c.nodeType===9?c:c.ownerDocument;p===null||p[Ic]||(p[Ic]=!0,id("selectionchange",!1,p))}}function Cf(c,p,k,M){switch(fe(p)){case 1:var F=Cc;break;case 4:F=jc;break;default:F=_l}k=F.bind(null,p,k,c),F=void 0,!ls||p!=="touchstart"&&p!=="touchmove"&&p!=="wheel"||(F=!0),M?F!==void 0?c.addEventListener(p,k,{capture:!0,passive:F}):c.addEventListener(p,k,!0):F!==void 0?c.addEventListener(p,k,{passive:F}):c.addEventListener(p,k,!1)}function od(c,p,k,M,F){var K=M;if((p&1)===0&&(p&2)===0&&M!==null)e:for(;;){if(M===null)return;var de=M.tag;if(de===3||de===4){var _e=M.stateNode.containerInfo;if(_e===F||_e.nodeType===8&&_e.parentNode===F)break;if(de===4)for(de=M.return;de!==null;){var $e=de.tag;if(($e===3||$e===4)&&($e=de.stateNode.containerInfo,$e===F||$e.nodeType===8&&$e.parentNode===F))return;de=de.return}for(;_e!==null;){if(de=Jo(_e),de===null)return;if($e=de.tag,$e===5||$e===6){M=K=de;continue e}_e=_e.parentNode}}M=M.return}Qs(function(){var qe=K,at=Zn(k),ct=[];e:{var ot=yg.get(c);if(ot!==void 0){var jt=tt,Pt=c;switch(c){case"keypress":if(Re(k)===0)break e;case"keydown":case"keyup":jt=Gu;break;case"focusin":Pt="focus",jt=hn;break;case"focusout":Pt="blur",jt=hn;break;case"beforeblur":case"afterblur":jt=hn;break;case"click":if(k.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":jt=Qt;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":jt=Ot;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":jt=Kr;break;case xf:case yf:case vf:jt=Pr;break;case bf:jt=Xr;break;case"scroll":jt=At;break;case"wheel":jt=Ku;break;case"copy":case"cut":case"paste":jt=Ia;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":jt=Xo}var Dt=(p&4)!==0,Pn=!Dt&&c==="scroll",Ue=Dt?ot!==null?ot+"Capture":null:ot;Dt=[];for(var Ie=qe,Ve;Ie!==null;){Ve=Ie;var ht=Ve.stateNode;if(Ve.tag===5&&ht!==null&&(Ve=ht,Ue!==null&&(ht=Rr(Ie,Ue),ht!=null&&Dt.push(Ml(Ie,ht,Ve)))),Pn)break;Ie=Ie.return}0<Dt.length&&(ot=new jt(ot,Pt,null,k,at),ct.push({event:ot,listeners:Dt}))}}if((p&7)===0){e:{if(ot=c==="mouseover"||c==="pointerover",jt=c==="mouseout"||c==="pointerout",ot&&k!==Fr&&(Pt=k.relatedTarget||k.fromElement)&&(Jo(Pt)||Pt[Ri]))break e;if((jt||ot)&&(ot=at.window===at?at:(ot=at.ownerDocument)?ot.defaultView||ot.parentWindow:window,jt?(Pt=k.relatedTarget||k.toElement,jt=qe,Pt=Pt?Jo(Pt):null,Pt!==null&&(Pn=Ct(Pt),Pt!==Pn||Pt.tag!==5&&Pt.tag!==6)&&(Pt=null)):(jt=null,Pt=qe),jt!==Pt)){if(Dt=Qt,ht="onMouseLeave",Ue="onMouseEnter",Ie="mouse",(c==="pointerout"||c==="pointerover")&&(Dt=Xo,ht="onPointerLeave",Ue="onPointerEnter",Ie="pointer"),Pn=jt==null?ot:Oa(jt),Ve=Pt==null?ot:Oa(Pt),ot=new Dt(ht,Ie+"leave",jt,k,at),ot.target=Pn,ot.relatedTarget=Ve,ht=null,Jo(at)===qe&&(Dt=new Dt(Ue,Ie+"enter",Pt,k,at),Dt.target=Ve,Dt.relatedTarget=Pn,ht=Dt),Pn=ht,jt&&Pt)t:{for(Dt=jt,Ue=Pt,Ie=0,Ve=Dt;Ve;Ve=Pa(Ve))Ie++;for(Ve=0,ht=Ue;ht;ht=Pa(ht))Ve++;for(;0<Ie-Ve;)Dt=Pa(Dt),Ie--;for(;0<Ve-Ie;)Ue=Pa(Ue),Ve--;for(;Ie--;){if(Dt===Ue||Ue!==null&&Dt===Ue.alternate)break t;Dt=Pa(Dt),Ue=Pa(Ue)}Dt=null}else Dt=null;jt!==null&&jf(ct,ot,jt,Dt,!1),Pt!==null&&Pn!==null&&jf(ct,Pn,Pt,Dt,!0)}}e:{if(ot=qe?Oa(qe):window,jt=ot.nodeName&&ot.nodeName.toLowerCase(),jt==="select"||jt==="input"&&ot.type==="file")var Ft=dg;else if(oi(ot))if(cf)Ft=mg;else{Ft=fg;var Xt=hg}else(jt=ot.nodeName)&&jt.toLowerCase()==="input"&&(ot.type==="checkbox"||ot.type==="radio")&&(Ft=pg);if(Ft&&(Ft=Ft(c,qe))){lf(ct,Ft,k,at);break e}Xt&&Xt(c,ot,qe),c==="focusout"&&(Xt=ot._wrapperState)&&Xt.controlled&&ot.type==="number"&&sn(ot,"number",ot.value)}switch(Xt=qe?Oa(qe):window,c){case"focusin":(oi(Xt)||Xt.contentEditable==="true")&&(Tl=Xt,td=qe,Yo=null);break;case"focusout":Yo=td=Tl=null;break;case"mousedown":nd=!0;break;case"contextmenu":case"mouseup":case"dragend":nd=!1,mf(ct,k,at);break;case"selectionchange":if(pf)break;case"keydown":case"keyup":mf(ct,k,at)}var Yt;if(Ls)e:{switch(c){case"compositionstart":var rn="onCompositionStart";break e;case"compositionend":rn="onCompositionEnd";break e;case"compositionupdate":rn="onCompositionUpdate";break e}rn=void 0}else Yr?Ac(c,k)&&(rn="onCompositionEnd"):c==="keydown"&&k.keyCode===229&&(rn="onCompositionStart");rn&&(Wn&&k.locale!=="ko"&&(Yr||rn!=="onCompositionStart"?rn==="onCompositionEnd"&&Yr&&(Yt=Be()):(ve=at,Te="value"in ve?ve.value:ve.textContent,Yr=!0)),Xt=Pc(qe,rn),0<Xt.length&&(rn=new Sl(rn,c,null,k,at),ct.push({event:rn,listeners:Xt}),Yt?rn.data=Yt:(Yt=lg(k),Yt!==null&&(rn.data=Yt)))),(Yt=or?cg(c,k):Xu(c,k))&&(qe=Pc(qe,"onBeforeInput"),0<qe.length&&(at=new Sl("onBeforeInput","beforeinput",null,k,at),ct.push({event:at,listeners:qe}),at.data=Yt))}Sf(ct,p)})}function Ml(c,p,k){return{instance:c,listener:p,currentTarget:k}}function Pc(c,p){for(var k=p+"Capture",M=[];c!==null;){var F=c,K=F.stateNode;F.tag===5&&K!==null&&(F=K,K=Rr(c,k),K!=null&&M.unshift(Ml(c,K,F)),K=Rr(c,p),K!=null&&M.push(Ml(c,K,F))),c=c.return}return M}function Pa(c){if(c===null)return null;do c=c.return;while(c&&c.tag!==5);return c||null}function jf(c,p,k,M,F){for(var K=p._reactName,de=[];k!==null&&k!==M;){var _e=k,$e=_e.alternate,qe=_e.stateNode;if($e!==null&&$e===M)break;_e.tag===5&&qe!==null&&(_e=qe,F?($e=Rr(k,K),$e!=null&&de.unshift(Ml(k,$e,_e))):F||($e=Rr(k,K),$e!=null&&de.push(Ml(k,$e,_e)))),k=k.return}de.length!==0&&c.push({event:p,listeners:de})}var Dc=/\r\n?/g,wg=/\u0000|\uFFFD/g;function Oc(c){return(typeof c=="string"?c:""+c).replace(Dc,`
|
|
39
|
+
`).replace(wg,"")}function Lc(c,p,k){if(p=Oc(p),Oc(c)!==p&&k)throw Error(r(425))}function zc(){}var ad=null,ld=null;function cd(c,p){return c==="textarea"||c==="noscript"||typeof p.children=="string"||typeof p.children=="number"||typeof p.dangerouslySetInnerHTML=="object"&&p.dangerouslySetInnerHTML!==null&&p.dangerouslySetInnerHTML.__html!=null}var ud=typeof setTimeout=="function"?setTimeout:void 0,_g=typeof clearTimeout=="function"?clearTimeout:void 0,Ef=typeof Promise=="function"?Promise:void 0,kg=typeof queueMicrotask=="function"?queueMicrotask:typeof Ef<"u"?function(c){return Ef.resolve(null).then(c).catch(Sg)}:ud;function Sg(c){setTimeout(function(){throw c})}function dd(c,p){var k=p,M=0;do{var F=k.nextSibling;if(c.removeChild(k),F&&F.nodeType===8)if(k=F.data,k==="/$"){if(M===0){c.removeChild(F),Vi(p);return}M--}else k!=="$"&&k!=="$?"&&k!=="$!"||M++;k=F}while(k);Vi(p)}function _o(c){for(;c!=null;c=c.nextSibling){var p=c.nodeType;if(p===1||p===3)break;if(p===8){if(p=c.data,p==="$"||p==="$!"||p==="$?")break;if(p==="/$")return null}}return c}function Nf(c){c=c.previousSibling;for(var p=0;c;){if(c.nodeType===8){var k=c.data;if(k==="$"||k==="$!"||k==="$?"){if(p===0)return c;p--}else k==="/$"&&p++}c=c.previousSibling}return null}var Da=Math.random().toString(36).slice(2),Ai="__reactFiber$"+Da,Il="__reactProps$"+Da,Ri="__reactContainer$"+Da,hd="__reactEvents$"+Da,Tf="__reactListeners$"+Da,$f="__reactHandles$"+Da;function Jo(c){var p=c[Ai];if(p)return p;for(var k=c.parentNode;k;){if(p=k[Ri]||k[Ai]){if(k=p.alternate,p.child!==null||k!==null&&k.child!==null)for(c=Nf(c);c!==null;){if(k=c[Ai])return k;c=Nf(c)}return p}c=k,k=c.parentNode}return null}function Pl(c){return c=c[Ai]||c[Ri],!c||c.tag!==5&&c.tag!==6&&c.tag!==13&&c.tag!==3?null:c}function Oa(c){if(c.tag===5||c.tag===6)return c.stateNode;throw Error(r(33))}function Bc(c){return c[Il]||null}var fd=[],La=-1;function Ki(c){return{current:c}}function Bn(c){0>La||(c.current=fd[La],fd[La]=null,La--)}function In(c,p){La++,fd[La]=c.current,c.current=p}var ko={},Jr=Ki(ko),hs=Ki(!1),Qo=ko;function Qr(c,p){var k=c.type.contextTypes;if(!k)return ko;var M=c.stateNode;if(M&&M.__reactInternalMemoizedUnmaskedChildContext===p)return M.__reactInternalMemoizedMaskedChildContext;var F={},K;for(K in k)F[K]=p[K];return M&&(c=c.stateNode,c.__reactInternalMemoizedUnmaskedChildContext=p,c.__reactInternalMemoizedMaskedChildContext=F),F}function fs(c){return c=c.childContextTypes,c!=null}function Fc(){Bn(hs),Bn(Jr)}function Af(c,p,k){if(Jr.current!==ko)throw Error(r(168));In(Jr,p),In(hs,k)}function Rf(c,p,k){var M=c.stateNode;if(p=p.childContextTypes,typeof M.getChildContext!="function")return k;M=M.getChildContext();for(var F in M)if(!(F in p))throw Error(r(108,ye(c)||"Unknown",F));return Q({},k,M)}function Uc(c){return c=(c=c.stateNode)&&c.__reactInternalMemoizedMergedChildContext||ko,Qo=Jr.current,In(Jr,c),In(hs,hs.current),!0}function Mf(c,p,k){var M=c.stateNode;if(!M)throw Error(r(169));k?(c=Rf(c,p,Qo),M.__reactInternalMemoizedMergedChildContext=c,Bn(hs),Bn(Jr),In(Jr,c)):Bn(hs),In(hs,k)}var Xi=null,Hc=!1,pd=!1;function If(c){Xi===null?Xi=[c]:Xi.push(c)}function fv(c){Hc=!0,If(c)}function So(){if(!pd&&Xi!==null){pd=!0;var c=0,p=Pe;try{var k=Xi;for(Pe=1;c<k.length;c++){var M=k[c];do M=M(!0);while(M!==null)}Xi=null,Hc=!1}catch(F){throw Xi!==null&&(Xi=Xi.slice(c+1)),Go(Vn,So),F}finally{Pe=p,pd=!1}}return null}var za=[],Ba=0,Wc=null,qc=0,Bs=[],ci=0,Fs=null,ps=1,ms="";function Co(c,p){za[Ba++]=qc,za[Ba++]=Wc,Wc=c,qc=p}function Zo(c,p,k){Bs[ci++]=ps,Bs[ci++]=ms,Bs[ci++]=Fs,Fs=c;var M=ps;c=ms;var F=32-Gn(M)-1;M&=~(1<<F),k+=1;var K=32-Gn(p)+F;if(30<K){var de=F-F%5;K=(M&(1<<de)-1).toString(32),M>>=de,F-=de,ps=1<<32-Gn(p)+F|k<<F|M,ms=K+c}else ps=1<<K|k<<F|M,ms=c}function ur(c){c.return!==null&&(Co(c,1),Zo(c,1,0))}function md(c){for(;c===Wc;)Wc=za[--Ba],za[Ba]=null,qc=za[--Ba],za[Ba]=null;for(;c===Fs;)Fs=Bs[--ci],Bs[ci]=null,ms=Bs[--ci],Bs[ci]=null,ps=Bs[--ci],Bs[ci]=null}var gs=null,Ns=null,Kn=!1,xs=null;function gd(c,p){var k=$s(5,null,null,0);k.elementType="DELETED",k.stateNode=p,k.return=c,p=c.deletions,p===null?(c.deletions=[k],c.flags|=16):p.push(k)}function xd(c,p){switch(c.tag){case 5:var k=c.type;return p=p.nodeType!==1||k.toLowerCase()!==p.nodeName.toLowerCase()?null:p,p!==null?(c.stateNode=p,gs=c,Ns=_o(p.firstChild),!0):!1;case 6:return p=c.pendingProps===""||p.nodeType!==3?null:p,p!==null?(c.stateNode=p,gs=c,Ns=null,!0):!1;case 13:return p=p.nodeType!==8?null:p,p!==null?(k=Fs!==null?{id:ps,overflow:ms}:null,c.memoizedState={dehydrated:p,treeContext:k,retryLane:1073741824},k=$s(18,null,null,0),k.stateNode=p,k.return=c,c.child=k,gs=c,Ns=null,!0):!1;default:return!1}}function yd(c){return(c.mode&1)!==0&&(c.flags&128)===0}function vd(c){if(Kn){var p=Ns;if(p){var k=p;if(!xd(c,p)){if(yd(c))throw Error(r(418));p=_o(k.nextSibling);var M=gs;p&&xd(c,p)?gd(M,k):(c.flags=c.flags&-4097|2,Kn=!1,gs=c)}}else{if(yd(c))throw Error(r(418));c.flags=c.flags&-4097|2,Kn=!1,gs=c}}}function bd(c){for(c=c.return;c!==null&&c.tag!==5&&c.tag!==3&&c.tag!==13;)c=c.return;gs=c}function Dl(c){if(c!==gs)return!1;if(!Kn)return bd(c),Kn=!0,!1;var p;if((p=c.tag!==3)&&!(p=c.tag!==5)&&(p=c.type,p=p!=="head"&&p!=="body"&&!cd(c.type,c.memoizedProps)),p&&(p=Ns)){if(yd(c))throw Pf(),Error(r(418));for(;p;)gd(c,p),p=_o(p.nextSibling)}if(bd(c),c.tag===13){if(c=c.memoizedState,c=c!==null?c.dehydrated:null,!c)throw Error(r(317));e:{for(c=c.nextSibling,p=0;c;){if(c.nodeType===8){var k=c.data;if(k==="/$"){if(p===0){Ns=_o(c.nextSibling);break e}p--}else k!=="$"&&k!=="$!"&&k!=="$?"||p++}c=c.nextSibling}Ns=null}}else Ns=gs?_o(c.stateNode.nextSibling):null;return!0}function Pf(){for(var c=Ns;c;)c=_o(c.nextSibling)}function ea(){Ns=gs=null,Kn=!1}function wd(c){xs===null?xs=[c]:xs.push(c)}var _d=N.ReactCurrentBatchConfig;function Fa(c,p,k){if(c=k.ref,c!==null&&typeof c!="function"&&typeof c!="object"){if(k._owner){if(k=k._owner,k){if(k.tag!==1)throw Error(r(309));var M=k.stateNode}if(!M)throw Error(r(147,c));var F=M,K=""+c;return p!==null&&p.ref!==null&&typeof p.ref=="function"&&p.ref._stringRef===K?p.ref:(p=function(de){var _e=F.refs;de===null?delete _e[K]:_e[K]=de},p._stringRef=K,p)}if(typeof c!="string")throw Error(r(284));if(!k._owner)throw Error(r(290,c))}return c}function Vc(c,p){throw c=Object.prototype.toString.call(p),Error(r(31,c==="[object Object]"?"object with keys {"+Object.keys(p).join(", ")+"}":c))}function Df(c){var p=c._init;return p(c._payload)}function Cg(c){function p(Ue,Ie){if(c){var Ve=Ue.deletions;Ve===null?(Ue.deletions=[Ie],Ue.flags|=16):Ve.push(Ie)}}function k(Ue,Ie){if(!c)return null;for(;Ie!==null;)p(Ue,Ie),Ie=Ie.sibling;return null}function M(Ue,Ie){for(Ue=new Map;Ie!==null;)Ie.key!==null?Ue.set(Ie.key,Ie):Ue.set(Ie.index,Ie),Ie=Ie.sibling;return Ue}function F(Ue,Ie){return Ue=Mo(Ue,Ie),Ue.index=0,Ue.sibling=null,Ue}function K(Ue,Ie,Ve){return Ue.index=Ve,c?(Ve=Ue.alternate,Ve!==null?(Ve=Ve.index,Ve<Ie?(Ue.flags|=2,Ie):Ve):(Ue.flags|=2,Ie)):(Ue.flags|=1048576,Ie)}function de(Ue){return c&&Ue.alternate===null&&(Ue.flags|=2),Ue}function _e(Ue,Ie,Ve,ht){return Ie===null||Ie.tag!==6?(Ie=vh(Ve,Ue.mode,ht),Ie.return=Ue,Ie):(Ie=F(Ie,Ve),Ie.return=Ue,Ie)}function $e(Ue,Ie,Ve,ht){var Ft=Ve.type;return Ft===O?at(Ue,Ie,Ve.props.children,ht,Ve.key):Ie!==null&&(Ie.elementType===Ft||typeof Ft=="object"&&Ft!==null&&Ft.$$typeof===ae&&Df(Ft)===Ie.type)?(ht=F(Ie,Ve.props),ht.ref=Fa(Ue,Ie,Ve),ht.return=Ue,ht):(ht=pu(Ve.type,Ve.key,Ve.props,null,Ue.mode,ht),ht.ref=Fa(Ue,Ie,Ve),ht.return=Ue,ht)}function qe(Ue,Ie,Ve,ht){return Ie===null||Ie.tag!==4||Ie.stateNode.containerInfo!==Ve.containerInfo||Ie.stateNode.implementation!==Ve.implementation?(Ie=bh(Ve,Ue.mode,ht),Ie.return=Ue,Ie):(Ie=F(Ie,Ve.children||[]),Ie.return=Ue,Ie)}function at(Ue,Ie,Ve,ht,Ft){return Ie===null||Ie.tag!==7?(Ie=Ja(Ve,Ue.mode,ht,Ft),Ie.return=Ue,Ie):(Ie=F(Ie,Ve),Ie.return=Ue,Ie)}function ct(Ue,Ie,Ve){if(typeof Ie=="string"&&Ie!==""||typeof Ie=="number")return Ie=vh(""+Ie,Ue.mode,Ve),Ie.return=Ue,Ie;if(typeof Ie=="object"&&Ie!==null){switch(Ie.$$typeof){case $:return Ve=pu(Ie.type,Ie.key,Ie.props,null,Ue.mode,Ve),Ve.ref=Fa(Ue,null,Ie),Ve.return=Ue,Ve;case R:return Ie=bh(Ie,Ue.mode,Ve),Ie.return=Ue,Ie;case ae:var ht=Ie._init;return ct(Ue,ht(Ie._payload),Ve)}if(Ye(Ie)||X(Ie))return Ie=Ja(Ie,Ue.mode,Ve,null),Ie.return=Ue,Ie;Vc(Ue,Ie)}return null}function ot(Ue,Ie,Ve,ht){var Ft=Ie!==null?Ie.key:null;if(typeof Ve=="string"&&Ve!==""||typeof Ve=="number")return Ft!==null?null:_e(Ue,Ie,""+Ve,ht);if(typeof Ve=="object"&&Ve!==null){switch(Ve.$$typeof){case $:return Ve.key===Ft?$e(Ue,Ie,Ve,ht):null;case R:return Ve.key===Ft?qe(Ue,Ie,Ve,ht):null;case ae:return Ft=Ve._init,ot(Ue,Ie,Ft(Ve._payload),ht)}if(Ye(Ve)||X(Ve))return Ft!==null?null:at(Ue,Ie,Ve,ht,null);Vc(Ue,Ve)}return null}function jt(Ue,Ie,Ve,ht,Ft){if(typeof ht=="string"&&ht!==""||typeof ht=="number")return Ue=Ue.get(Ve)||null,_e(Ie,Ue,""+ht,Ft);if(typeof ht=="object"&&ht!==null){switch(ht.$$typeof){case $:return Ue=Ue.get(ht.key===null?Ve:ht.key)||null,$e(Ie,Ue,ht,Ft);case R:return Ue=Ue.get(ht.key===null?Ve:ht.key)||null,qe(Ie,Ue,ht,Ft);case ae:var Xt=ht._init;return jt(Ue,Ie,Ve,Xt(ht._payload),Ft)}if(Ye(ht)||X(ht))return Ue=Ue.get(Ve)||null,at(Ie,Ue,ht,Ft,null);Vc(Ie,ht)}return null}function Pt(Ue,Ie,Ve,ht){for(var Ft=null,Xt=null,Yt=Ie,rn=Ie=0,wr=null;Yt!==null&&rn<Ve.length;rn++){Yt.index>rn?(wr=Yt,Yt=null):wr=Yt.sibling;var vn=ot(Ue,Yt,Ve[rn],ht);if(vn===null){Yt===null&&(Yt=wr);break}c&&Yt&&vn.alternate===null&&p(Ue,Yt),Ie=K(vn,Ie,rn),Xt===null?Ft=vn:Xt.sibling=vn,Xt=vn,Yt=wr}if(rn===Ve.length)return k(Ue,Yt),Kn&&Co(Ue,rn),Ft;if(Yt===null){for(;rn<Ve.length;rn++)Yt=ct(Ue,Ve[rn],ht),Yt!==null&&(Ie=K(Yt,Ie,rn),Xt===null?Ft=Yt:Xt.sibling=Yt,Xt=Yt);return Kn&&Co(Ue,rn),Ft}for(Yt=M(Ue,Yt);rn<Ve.length;rn++)wr=jt(Yt,Ue,rn,Ve[rn],ht),wr!==null&&(c&&wr.alternate!==null&&Yt.delete(wr.key===null?rn:wr.key),Ie=K(wr,Ie,rn),Xt===null?Ft=wr:Xt.sibling=wr,Xt=wr);return c&&Yt.forEach(function(eo){return p(Ue,eo)}),Kn&&Co(Ue,rn),Ft}function Dt(Ue,Ie,Ve,ht){var Ft=X(Ve);if(typeof Ft!="function")throw Error(r(150));if(Ve=Ft.call(Ve),Ve==null)throw Error(r(151));for(var Xt=Ft=null,Yt=Ie,rn=Ie=0,wr=null,vn=Ve.next();Yt!==null&&!vn.done;rn++,vn=Ve.next()){Yt.index>rn?(wr=Yt,Yt=null):wr=Yt.sibling;var eo=ot(Ue,Yt,vn.value,ht);if(eo===null){Yt===null&&(Yt=wr);break}c&&Yt&&eo.alternate===null&&p(Ue,Yt),Ie=K(eo,Ie,rn),Xt===null?Ft=eo:Xt.sibling=eo,Xt=eo,Yt=wr}if(vn.done)return k(Ue,Yt),Kn&&Co(Ue,rn),Ft;if(Yt===null){for(;!vn.done;rn++,vn=Ve.next())vn=ct(Ue,vn.value,ht),vn!==null&&(Ie=K(vn,Ie,rn),Xt===null?Ft=vn:Xt.sibling=vn,Xt=vn);return Kn&&Co(Ue,rn),Ft}for(Yt=M(Ue,Yt);!vn.done;rn++,vn=Ve.next())vn=jt(Yt,Ue,rn,vn.value,ht),vn!==null&&(c&&vn.alternate!==null&&Yt.delete(vn.key===null?rn:vn.key),Ie=K(vn,Ie,rn),Xt===null?Ft=vn:Xt.sibling=vn,Xt=vn);return c&&Yt.forEach(function(sx){return p(Ue,sx)}),Kn&&Co(Ue,rn),Ft}function Pn(Ue,Ie,Ve,ht){if(typeof Ve=="object"&&Ve!==null&&Ve.type===O&&Ve.key===null&&(Ve=Ve.props.children),typeof Ve=="object"&&Ve!==null){switch(Ve.$$typeof){case $:e:{for(var Ft=Ve.key,Xt=Ie;Xt!==null;){if(Xt.key===Ft){if(Ft=Ve.type,Ft===O){if(Xt.tag===7){k(Ue,Xt.sibling),Ie=F(Xt,Ve.props.children),Ie.return=Ue,Ue=Ie;break e}}else if(Xt.elementType===Ft||typeof Ft=="object"&&Ft!==null&&Ft.$$typeof===ae&&Df(Ft)===Xt.type){k(Ue,Xt.sibling),Ie=F(Xt,Ve.props),Ie.ref=Fa(Ue,Xt,Ve),Ie.return=Ue,Ue=Ie;break e}k(Ue,Xt);break}else p(Ue,Xt);Xt=Xt.sibling}Ve.type===O?(Ie=Ja(Ve.props.children,Ue.mode,ht,Ve.key),Ie.return=Ue,Ue=Ie):(ht=pu(Ve.type,Ve.key,Ve.props,null,Ue.mode,ht),ht.ref=Fa(Ue,Ie,Ve),ht.return=Ue,Ue=ht)}return de(Ue);case R:e:{for(Xt=Ve.key;Ie!==null;){if(Ie.key===Xt)if(Ie.tag===4&&Ie.stateNode.containerInfo===Ve.containerInfo&&Ie.stateNode.implementation===Ve.implementation){k(Ue,Ie.sibling),Ie=F(Ie,Ve.children||[]),Ie.return=Ue,Ue=Ie;break e}else{k(Ue,Ie);break}else p(Ue,Ie);Ie=Ie.sibling}Ie=bh(Ve,Ue.mode,ht),Ie.return=Ue,Ue=Ie}return de(Ue);case ae:return Xt=Ve._init,Pn(Ue,Ie,Xt(Ve._payload),ht)}if(Ye(Ve))return Pt(Ue,Ie,Ve,ht);if(X(Ve))return Dt(Ue,Ie,Ve,ht);Vc(Ue,Ve)}return typeof Ve=="string"&&Ve!==""||typeof Ve=="number"?(Ve=""+Ve,Ie!==null&&Ie.tag===6?(k(Ue,Ie.sibling),Ie=F(Ie,Ve),Ie.return=Ue,Ue=Ie):(k(Ue,Ie),Ie=vh(Ve,Ue.mode,ht),Ie.return=Ue,Ue=Ie),de(Ue)):k(Ue,Ie)}return Pn}var Ua=Cg(!0),kd=Cg(!1),ta=Ki(null),Gc=null,na=null,Sd=null;function Cd(){Sd=na=Gc=null}function jd(c){var p=ta.current;Bn(ta),c._currentValue=p}function Of(c,p,k){for(;c!==null;){var M=c.alternate;if((c.childLanes&p)!==p?(c.childLanes|=p,M!==null&&(M.childLanes|=p)):M!==null&&(M.childLanes&p)!==p&&(M.childLanes|=p),c===k)break;c=c.return}}function Ha(c,p){Gc=c,Sd=na=null,c=c.dependencies,c!==null&&c.firstContext!==null&&((c.lanes&p)!==0&&(ys=!0),c.firstContext=null)}function Us(c){var p=c._currentValue;if(Sd!==c)if(c={context:c,memoizedValue:p,next:null},na===null){if(Gc===null)throw Error(r(308));na=c,Gc.dependencies={lanes:0,firstContext:c}}else na=na.next=c;return p}var Wa=null;function Ed(c){Wa===null?Wa=[c]:Wa.push(c)}function Kc(c,p,k,M){var F=p.interleaved;return F===null?(k.next=k,Ed(p)):(k.next=F.next,F.next=k),p.interleaved=k,Yi(c,M)}function Yi(c,p){c.lanes|=p;var k=c.alternate;for(k!==null&&(k.lanes|=p),k=c,c=c.return;c!==null;)c.childLanes|=p,k=c.alternate,k!==null&&(k.childLanes|=p),k=c,c=c.return;return k.tag===3?k.stateNode:null}var Mi=!1;function Xc(c){c.updateQueue={baseState:c.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Nd(c,p){c=c.updateQueue,p.updateQueue===c&&(p.updateQueue={baseState:c.baseState,firstBaseUpdate:c.firstBaseUpdate,lastBaseUpdate:c.lastBaseUpdate,shared:c.shared,effects:c.effects})}function Ji(c,p){return{eventTime:c,lane:p,tag:0,payload:null,callback:null,next:null}}function jo(c,p,k){var M=c.updateQueue;if(M===null)return null;if(M=M.shared,(gn&2)!==0){var F=M.pending;return F===null?p.next=p:(p.next=F.next,F.next=p),M.pending=p,Yi(c,k)}return F=M.interleaved,F===null?(p.next=p,Ed(M)):(p.next=F.next,F.next=p),M.interleaved=p,Yi(c,k)}function Ol(c,p,k){if(p=p.updateQueue,p!==null&&(p=p.shared,(k&4194240)!==0)){var M=p.lanes;M&=c.pendingLanes,k|=M,p.lanes=k,be(c,k)}}function jg(c,p){var k=c.updateQueue,M=c.alternate;if(M!==null&&(M=M.updateQueue,k===M)){var F=null,K=null;if(k=k.firstBaseUpdate,k!==null){do{var de={eventTime:k.eventTime,lane:k.lane,tag:k.tag,payload:k.payload,callback:k.callback,next:null};K===null?F=K=de:K=K.next=de,k=k.next}while(k!==null);K===null?F=K=p:K=K.next=p}else F=K=p;k={baseState:M.baseState,firstBaseUpdate:F,lastBaseUpdate:K,shared:M.shared,effects:M.effects},c.updateQueue=k;return}c=k.lastBaseUpdate,c===null?k.firstBaseUpdate=p:c.next=p,k.lastBaseUpdate=p}function Yc(c,p,k,M){var F=c.updateQueue;Mi=!1;var K=F.firstBaseUpdate,de=F.lastBaseUpdate,_e=F.shared.pending;if(_e!==null){F.shared.pending=null;var $e=_e,qe=$e.next;$e.next=null,de===null?K=qe:de.next=qe,de=$e;var at=c.alternate;at!==null&&(at=at.updateQueue,_e=at.lastBaseUpdate,_e!==de&&(_e===null?at.firstBaseUpdate=qe:_e.next=qe,at.lastBaseUpdate=$e))}if(K!==null){var ct=F.baseState;de=0,at=qe=$e=null,_e=K;do{var ot=_e.lane,jt=_e.eventTime;if((M&ot)===ot){at!==null&&(at=at.next={eventTime:jt,lane:0,tag:_e.tag,payload:_e.payload,callback:_e.callback,next:null});e:{var Pt=c,Dt=_e;switch(ot=p,jt=k,Dt.tag){case 1:if(Pt=Dt.payload,typeof Pt=="function"){ct=Pt.call(jt,ct,ot);break e}ct=Pt;break e;case 3:Pt.flags=Pt.flags&-65537|128;case 0:if(Pt=Dt.payload,ot=typeof Pt=="function"?Pt.call(jt,ct,ot):Pt,ot==null)break e;ct=Q({},ct,ot);break e;case 2:Mi=!0}}_e.callback!==null&&_e.lane!==0&&(c.flags|=64,ot=F.effects,ot===null?F.effects=[_e]:ot.push(_e))}else jt={eventTime:jt,lane:ot,tag:_e.tag,payload:_e.payload,callback:_e.callback,next:null},at===null?(qe=at=jt,$e=ct):at=at.next=jt,de|=ot;if(_e=_e.next,_e===null){if(_e=F.shared.pending,_e===null)break;ot=_e,_e=ot.next,ot.next=null,F.lastBaseUpdate=ot,F.shared.pending=null}}while(!0);if(at===null&&($e=ct),F.baseState=$e,F.firstBaseUpdate=qe,F.lastBaseUpdate=at,p=F.shared.interleaved,p!==null){F=p;do de|=F.lane,F=F.next;while(F!==p)}else K===null&&(F.shared.lanes=0);la|=de,c.lanes=de,c.memoizedState=ct}}function Eg(c,p,k){if(c=p.effects,p.effects=null,c!==null)for(p=0;p<c.length;p++){var M=c[p],F=M.callback;if(F!==null){if(M.callback=null,M=k,typeof F!="function")throw Error(r(191,F));F.call(M)}}}var Ll={},Ii=Ki(Ll),zl=Ki(Ll),qa=Ki(Ll);function ra(c){if(c===Ll)throw Error(r(174));return c}function Td(c,p){switch(In(qa,p),In(zl,c),In(Ii,Ll),c=p.nodeType,c){case 9:case 11:p=(p=p.documentElement)?p.namespaceURI:Tr(null,"");break;default:c=c===8?p.parentNode:p,p=c.namespaceURI||null,c=c.tagName,p=Tr(p,c)}Bn(Ii),In(Ii,p)}function sa(){Bn(Ii),Bn(zl),Bn(qa)}function Lf(c){ra(qa.current);var p=ra(Ii.current),k=Tr(p,c.type);p!==k&&(In(zl,c),In(Ii,k))}function $d(c){zl.current===c&&(Bn(Ii),Bn(zl))}var Yn=Ki(0);function Jc(c){for(var p=c;p!==null;){if(p.tag===13){var k=p.memoizedState;if(k!==null&&(k=k.dehydrated,k===null||k.data==="$?"||k.data==="$!"))return p}else if(p.tag===19&&p.memoizedProps.revealOrder!==void 0){if((p.flags&128)!==0)return p}else if(p.child!==null){p.child.return=p,p=p.child;continue}if(p===c)break;for(;p.sibling===null;){if(p.return===null||p.return===c)return null;p=p.return}p.sibling.return=p.return,p=p.sibling}return null}var Ad=[];function Rd(){for(var c=0;c<Ad.length;c++)Ad[c]._workInProgressVersionPrimary=null;Ad.length=0}var Md=N.ReactCurrentDispatcher,Id=N.ReactCurrentBatchConfig,ia=0,Xn=null,dr=null,vr=null,Pd=!1,oa=!1,Eo=0,zf=0;function Dr(){throw Error(r(321))}function Dd(c,p){if(p===null)return!1;for(var k=0;k<p.length&&k<c.length;k++)if(!li(c[k],p[k]))return!1;return!0}function Od(c,p,k,M,F,K){if(ia=K,Xn=p,p.memoizedState=null,p.updateQueue=null,p.lanes=0,Md.current=c===null||c.memoizedState===null?Mg:Ig,c=k(M,F),oa){K=0;do{if(oa=!1,Eo=0,25<=K)throw Error(r(301));K+=1,vr=dr=null,p.updateQueue=null,Md.current=mv,c=k(M,F)}while(oa)}if(Md.current=tu,p=dr!==null&&dr.next!==null,ia=0,vr=dr=Xn=null,Pd=!1,p)throw Error(r(300));return c}function Ld(){var c=Eo!==0;return Eo=0,c}function ui(){var c={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return vr===null?Xn.memoizedState=vr=c:vr=vr.next=c,vr}function Hs(){if(dr===null){var c=Xn.alternate;c=c!==null?c.memoizedState:null}else c=dr.next;var p=vr===null?Xn.memoizedState:vr.next;if(p!==null)vr=p,dr=c;else{if(c===null)throw Error(r(310));dr=c,c={memoizedState:dr.memoizedState,baseState:dr.baseState,baseQueue:dr.baseQueue,queue:dr.queue,next:null},vr===null?Xn.memoizedState=vr=c:vr=vr.next=c}return vr}function Bl(c,p){return typeof p=="function"?p(c):p}function zd(c){var p=Hs(),k=p.queue;if(k===null)throw Error(r(311));k.lastRenderedReducer=c;var M=dr,F=M.baseQueue,K=k.pending;if(K!==null){if(F!==null){var de=F.next;F.next=K.next,K.next=de}M.baseQueue=F=K,k.pending=null}if(F!==null){K=F.next,M=M.baseState;var _e=de=null,$e=null,qe=K;do{var at=qe.lane;if((ia&at)===at)$e!==null&&($e=$e.next={lane:0,action:qe.action,hasEagerState:qe.hasEagerState,eagerState:qe.eagerState,next:null}),M=qe.hasEagerState?qe.eagerState:c(M,qe.action);else{var ct={lane:at,action:qe.action,hasEagerState:qe.hasEagerState,eagerState:qe.eagerState,next:null};$e===null?(_e=$e=ct,de=M):$e=$e.next=ct,Xn.lanes|=at,la|=at}qe=qe.next}while(qe!==null&&qe!==K);$e===null?de=M:$e.next=_e,li(M,p.memoizedState)||(ys=!0),p.memoizedState=M,p.baseState=de,p.baseQueue=$e,k.lastRenderedState=M}if(c=k.interleaved,c!==null){F=c;do K=F.lane,Xn.lanes|=K,la|=K,F=F.next;while(F!==c)}else F===null&&(k.lanes=0);return[p.memoizedState,k.dispatch]}function Bf(c){var p=Hs(),k=p.queue;if(k===null)throw Error(r(311));k.lastRenderedReducer=c;var M=k.dispatch,F=k.pending,K=p.memoizedState;if(F!==null){k.pending=null;var de=F=F.next;do K=c(K,de.action),de=de.next;while(de!==F);li(K,p.memoizedState)||(ys=!0),p.memoizedState=K,p.baseQueue===null&&(p.baseState=K),k.lastRenderedState=K}return[K,M]}function Ff(){}function Bd(c,p){var k=Xn,M=Hs(),F=p(),K=!li(M.memoizedState,F);if(K&&(M.memoizedState=F,ys=!0),M=M.queue,Xf(Wf.bind(null,k,M,c),[c]),M.getSnapshot!==p||K||vr!==null&&vr.memoizedState.tag&1){if(k.flags|=2048,Qc(9,Hf.bind(null,k,M,F,p),void 0,null),fr===null)throw Error(r(349));(ia&30)!==0||Uf(k,p,F)}return F}function Uf(c,p,k){c.flags|=16384,c={getSnapshot:p,value:k},p=Xn.updateQueue,p===null?(p={lastEffect:null,stores:null},Xn.updateQueue=p,p.stores=[c]):(k=p.stores,k===null?p.stores=[c]:k.push(c))}function Hf(c,p,k,M){p.value=k,p.getSnapshot=M,Ng(p)&&qf(c)}function Wf(c,p,k){return k(function(){Ng(p)&&qf(c)})}function Ng(c){var p=c.getSnapshot;c=c.value;try{var k=p();return!li(c,k)}catch{return!0}}function qf(c){var p=Yi(c,1);p!==null&&fi(p,c,1,-1)}function Vf(c){var p=ui();return typeof c=="function"&&(c=c()),p.memoizedState=p.baseState=c,c={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Bl,lastRenderedState:c},p.queue=c,c=c.dispatch=Ag.bind(null,Xn,c),[p.memoizedState,c]}function Qc(c,p,k,M){return c={tag:c,create:p,destroy:k,deps:M,next:null},p=Xn.updateQueue,p===null?(p={lastEffect:null,stores:null},Xn.updateQueue=p,p.lastEffect=c.next=c):(k=p.lastEffect,k===null?p.lastEffect=c.next=c:(M=k.next,k.next=c,c.next=M,p.lastEffect=c)),c}function Gf(){return Hs().memoizedState}function Zc(c,p,k,M){var F=ui();Xn.flags|=c,F.memoizedState=Qc(1|p,k,void 0,M===void 0?null:M)}function eu(c,p,k,M){var F=Hs();M=M===void 0?null:M;var K=void 0;if(dr!==null){var de=dr.memoizedState;if(K=de.destroy,M!==null&&Dd(M,de.deps)){F.memoizedState=Qc(p,k,K,M);return}}Xn.flags|=c,F.memoizedState=Qc(1|p,k,K,M)}function Kf(c,p){return Zc(8390656,8,c,p)}function Xf(c,p){return eu(2048,8,c,p)}function Yf(c,p){return eu(4,2,c,p)}function Jf(c,p){return eu(4,4,c,p)}function Qf(c,p){if(typeof p=="function")return c=c(),p(c),function(){p(null)};if(p!=null)return c=c(),p.current=c,function(){p.current=null}}function Tg(c,p,k){return k=k!=null?k.concat([c]):null,eu(4,4,Qf.bind(null,p,c),k)}function Fd(){}function Zf(c,p){var k=Hs();p=p===void 0?null:p;var M=k.memoizedState;return M!==null&&p!==null&&Dd(p,M[1])?M[0]:(k.memoizedState=[c,p],c)}function ep(c,p){var k=Hs();p=p===void 0?null:p;var M=k.memoizedState;return M!==null&&p!==null&&Dd(p,M[1])?M[0]:(c=c(),k.memoizedState=[c,p],c)}function tp(c,p,k){return(ia&21)===0?(c.baseState&&(c.baseState=!1,ys=!0),c.memoizedState=k):(li(k,p)||(k=Es(),Xn.lanes|=k,la|=k,c.baseState=!0),p)}function pv(c,p){var k=Pe;Pe=k!==0&&4>k?k:4,c(!0);var M=Id.transition;Id.transition={};try{c(!1),p()}finally{Pe=k,Id.transition=M}}function np(){return Hs().memoizedState}function $g(c,p,k){var M=Ao(c);if(k={lane:M,action:k,hasEagerState:!1,eagerState:null,next:null},rp(c))Rg(p,k);else if(k=Kc(c,p,k,M),k!==null){var F=es();fi(k,c,M,F),sp(k,p,M)}}function Ag(c,p,k){var M=Ao(c),F={lane:M,action:k,hasEagerState:!1,eagerState:null,next:null};if(rp(c))Rg(p,F);else{var K=c.alternate;if(c.lanes===0&&(K===null||K.lanes===0)&&(K=p.lastRenderedReducer,K!==null))try{var de=p.lastRenderedState,_e=K(de,k);if(F.hasEagerState=!0,F.eagerState=_e,li(_e,de)){var $e=p.interleaved;$e===null?(F.next=F,Ed(p)):(F.next=$e.next,$e.next=F),p.interleaved=F;return}}catch{}finally{}k=Kc(c,p,F,M),k!==null&&(F=es(),fi(k,c,M,F),sp(k,p,M))}}function rp(c){var p=c.alternate;return c===Xn||p!==null&&p===Xn}function Rg(c,p){oa=Pd=!0;var k=c.pending;k===null?p.next=p:(p.next=k.next,k.next=p),c.pending=p}function sp(c,p,k){if((k&4194240)!==0){var M=p.lanes;M&=c.pendingLanes,k|=M,p.lanes=k,be(c,k)}}var tu={readContext:Us,useCallback:Dr,useContext:Dr,useEffect:Dr,useImperativeHandle:Dr,useInsertionEffect:Dr,useLayoutEffect:Dr,useMemo:Dr,useReducer:Dr,useRef:Dr,useState:Dr,useDebugValue:Dr,useDeferredValue:Dr,useTransition:Dr,useMutableSource:Dr,useSyncExternalStore:Dr,useId:Dr,unstable_isNewReconciler:!1},Mg={readContext:Us,useCallback:function(c,p){return ui().memoizedState=[c,p===void 0?null:p],c},useContext:Us,useEffect:Kf,useImperativeHandle:function(c,p,k){return k=k!=null?k.concat([c]):null,Zc(4194308,4,Qf.bind(null,p,c),k)},useLayoutEffect:function(c,p){return Zc(4194308,4,c,p)},useInsertionEffect:function(c,p){return Zc(4,2,c,p)},useMemo:function(c,p){var k=ui();return p=p===void 0?null:p,c=c(),k.memoizedState=[c,p],c},useReducer:function(c,p,k){var M=ui();return p=k!==void 0?k(p):p,M.memoizedState=M.baseState=p,c={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:c,lastRenderedState:p},M.queue=c,c=c.dispatch=$g.bind(null,Xn,c),[M.memoizedState,c]},useRef:function(c){var p=ui();return c={current:c},p.memoizedState=c},useState:Vf,useDebugValue:Fd,useDeferredValue:function(c){return ui().memoizedState=c},useTransition:function(){var c=Vf(!1),p=c[0];return c=pv.bind(null,c[1]),ui().memoizedState=c,[p,c]},useMutableSource:function(){},useSyncExternalStore:function(c,p,k){var M=Xn,F=ui();if(Kn){if(k===void 0)throw Error(r(407));k=k()}else{if(k=p(),fr===null)throw Error(r(349));(ia&30)!==0||Uf(M,p,k)}F.memoizedState=k;var K={value:k,getSnapshot:p};return F.queue=K,Kf(Wf.bind(null,M,K,c),[c]),M.flags|=2048,Qc(9,Hf.bind(null,M,K,k,p),void 0,null),k},useId:function(){var c=ui(),p=fr.identifierPrefix;if(Kn){var k=ms,M=ps;k=(M&~(1<<32-Gn(M)-1)).toString(32)+k,p=":"+p+"R"+k,k=Eo++,0<k&&(p+="H"+k.toString(32)),p+=":"}else k=zf++,p=":"+p+"r"+k.toString(32)+":";return c.memoizedState=p},unstable_isNewReconciler:!1},Ig={readContext:Us,useCallback:Zf,useContext:Us,useEffect:Xf,useImperativeHandle:Tg,useInsertionEffect:Yf,useLayoutEffect:Jf,useMemo:ep,useReducer:zd,useRef:Gf,useState:function(){return zd(Bl)},useDebugValue:Fd,useDeferredValue:function(c){var p=Hs();return tp(p,dr.memoizedState,c)},useTransition:function(){var c=zd(Bl)[0],p=Hs().memoizedState;return[c,p]},useMutableSource:Ff,useSyncExternalStore:Bd,useId:np,unstable_isNewReconciler:!1},mv={readContext:Us,useCallback:Zf,useContext:Us,useEffect:Xf,useImperativeHandle:Tg,useInsertionEffect:Yf,useLayoutEffect:Jf,useMemo:ep,useReducer:Bf,useRef:Gf,useState:function(){return Bf(Bl)},useDebugValue:Fd,useDeferredValue:function(c){var p=Hs();return dr===null?p.memoizedState=c:tp(p,dr.memoizedState,c)},useTransition:function(){var c=Bf(Bl)[0],p=Hs().memoizedState;return[c,p]},useMutableSource:Ff,useSyncExternalStore:Bd,useId:np,unstable_isNewReconciler:!1};function hr(c,p){if(c&&c.defaultProps){p=Q({},p),c=c.defaultProps;for(var k in c)p[k]===void 0&&(p[k]=c[k]);return p}return p}function Pi(c,p,k,M){p=c.memoizedState,k=k(M,p),k=k==null?p:Q({},p,k),c.memoizedState=k,c.lanes===0&&(c.updateQueue.baseState=k)}var Qi={isMounted:function(c){return(c=c._reactInternals)?Ct(c)===c:!1},enqueueSetState:function(c,p,k){c=c._reactInternals;var M=es(),F=Ao(c),K=Ji(M,F);K.payload=p,k!=null&&(K.callback=k),p=jo(c,K,F),p!==null&&(fi(p,c,F,M),Ol(p,c,F))},enqueueReplaceState:function(c,p,k){c=c._reactInternals;var M=es(),F=Ao(c),K=Ji(M,F);K.tag=1,K.payload=p,k!=null&&(K.callback=k),p=jo(c,K,F),p!==null&&(fi(p,c,F,M),Ol(p,c,F))},enqueueForceUpdate:function(c,p){c=c._reactInternals;var k=es(),M=Ao(c),F=Ji(k,M);F.tag=2,p!=null&&(F.callback=p),p=jo(c,F,M),p!==null&&(fi(p,c,M,k),Ol(p,c,M))}};function aa(c,p,k,M,F,K,de){return c=c.stateNode,typeof c.shouldComponentUpdate=="function"?c.shouldComponentUpdate(M,K,de):p.prototype&&p.prototype.isPureReactComponent?!Nl(k,M)||!Nl(F,K):!0}function ip(c,p,k){var M=!1,F=ko,K=p.contextType;return typeof K=="object"&&K!==null?K=Us(K):(F=fs(p)?Qo:Jr.current,M=p.contextTypes,K=(M=M!=null)?Qr(c,F):ko),p=new p(k,K),c.memoizedState=p.state!==null&&p.state!==void 0?p.state:null,p.updater=Qi,c.stateNode=p,p._reactInternals=c,M&&(c=c.stateNode,c.__reactInternalMemoizedUnmaskedChildContext=F,c.__reactInternalMemoizedMaskedChildContext=K),p}function op(c,p,k,M){c=p.state,typeof p.componentWillReceiveProps=="function"&&p.componentWillReceiveProps(k,M),typeof p.UNSAFE_componentWillReceiveProps=="function"&&p.UNSAFE_componentWillReceiveProps(k,M),p.state!==c&&Qi.enqueueReplaceState(p,p.state,null)}function Ud(c,p,k,M){var F=c.stateNode;F.props=k,F.state=c.memoizedState,F.refs={},Xc(c);var K=p.contextType;typeof K=="object"&&K!==null?F.context=Us(K):(K=fs(p)?Qo:Jr.current,F.context=Qr(c,K)),F.state=c.memoizedState,K=p.getDerivedStateFromProps,typeof K=="function"&&(Pi(c,p,K,k),F.state=c.memoizedState),typeof p.getDerivedStateFromProps=="function"||typeof F.getSnapshotBeforeUpdate=="function"||typeof F.UNSAFE_componentWillMount!="function"&&typeof F.componentWillMount!="function"||(p=F.state,typeof F.componentWillMount=="function"&&F.componentWillMount(),typeof F.UNSAFE_componentWillMount=="function"&&F.UNSAFE_componentWillMount(),p!==F.state&&Qi.enqueueReplaceState(F,F.state,null),Yc(c,k,F,M),F.state=c.memoizedState),typeof F.componentDidMount=="function"&&(c.flags|=4194308)}function Va(c,p){try{var k="",M=p;do k+=Ae(M),M=M.return;while(M);var F=k}catch(K){F=`
|
|
40
40
|
Error generating stack: `+K.message+`
|
|
41
|
-
`+K.stack}return{value:c,source:p,stack:F,digest:null}}function Hd(c,p,k){return{value:c,source:null,stack:k??null,digest:p??null}}function Wd(c,p){try{console.error(p.value)}catch(k){setTimeout(function(){throw k})}}var Pg=typeof WeakMap=="function"?WeakMap:Map;function ap(c,p,k){k=Ji(-1,k),k.tag=3,k.payload={element:null};var M=p.value;return k.callback=function(){cu||(cu=!0,dh=M),Wd(c,p)},k}function lp(c,p,k){k=Ji(-1,k),k.tag=3;var M=c.type.getDerivedStateFromError;if(typeof M=="function"){var F=p.value;k.payload=function(){return M(F)},k.callback=function(){Wd(c,p)}}var K=c.stateNode;return K!==null&&typeof K.componentDidCatch=="function"&&(k.callback=function(){Wd(c,p),typeof M!="function"&&($o===null?$o=new Set([this]):$o.add(this));var de=p.stack;this.componentDidCatch(p.value,{componentStack:de!==null?de:""})}),k}function cp(c,p,k){var M=c.pingCache;if(M===null){M=c.pingCache=new Pg;var F=new Set;M.set(p,F)}else F=M.get(p),F===void 0&&(F=new Set,M.set(p,F));F.has(k)||(F.add(k),c=Gg.bind(null,c,p,k),p.then(c,c))}function Dg(c){do{var p;if((p=c.tag===13)&&(p=c.memoizedState,p=p!==null?p.dehydrated!==null:!0),p)return c;c=c.return}while(c!==null);return null}function Zr(c,p,k,M,F){return(c.mode&1)===0?(c===p?c.flags|=65536:(c.flags|=128,k.flags|=131072,k.flags&=-52805,k.tag===1&&(k.alternate===null?k.tag=17:(p=Ji(-1,1),p.tag=2,jo(k,p,1))),k.lanes|=1),c):(c.flags|=65536,c.lanes=F,c)}var Og=N.ReactCurrentOwner,ys=!1;function Or(c,p,k,M){p.child=c===null?kd(p,null,k,M):Ua(p,c.child,k,M)}function up(c,p,k,M,F){k=k.render;var K=p.ref;return Ha(p,F),M=Od(c,p,k,M,K,F),k=Ld(),c!==null&&!ys?(p.updateQueue=c.updateQueue,p.flags&=-2053,c.lanes&=~F,Zi(c,p,F)):(Kn&&k&&ur(p),p.flags|=1,Or(c,p,M,F),p.child)}function Fl(c,p,k,M,F){if(c===null){var K=k.type;return typeof K=="function"&&!yh(K)&&K.defaultProps===void 0&&k.compare===null&&k.defaultProps===void 0?(p.tag=15,p.type=K,dp(c,p,K,M,F)):(c=pu(k.type,null,M,p,p.mode,F),c.ref=p.ref,c.return=p,p.child=c)}if(K=c.child,(c.lanes&F)===0){var de=K.memoizedProps;if(k=k.compare,k=k!==null?k:Nl,k(de,M)&&c.ref===p.ref)return Zi(c,p,F)}return p.flags|=1,c=Mo(K,M),c.ref=p.ref,c.return=p,p.child=c}function dp(c,p,k,M,F){if(c!==null){var K=c.memoizedProps;if(Nl(K,M)&&c.ref===p.ref)if(ys=!1,p.pendingProps=M=K,(c.lanes&F)!==0)(c.flags&131072)!==0&&(ys=!0);else return p.lanes=c.lanes,Zi(c,p,F)}return qd(c,p,k,M,F)}function hp(c,p,k){var M=p.pendingProps,F=M.children,K=c!==null?c.memoizedState:null;if(M.mode==="hidden")if((p.mode&1)===0)p.memoizedState={baseLanes:0,cachePool:null,transitions:null},In(Ka,Ts),Ts|=k;else{if((k&1073741824)===0)return c=K!==null?K.baseLanes|k:k,p.lanes=p.childLanes=1073741824,p.memoizedState={baseLanes:c,cachePool:null,transitions:null},p.updateQueue=null,In(Ka,Ts),Ts|=c,null;p.memoizedState={baseLanes:0,cachePool:null,transitions:null},M=K!==null?K.baseLanes:k,In(Ka,Ts),Ts|=M}else K!==null?(M=K.baseLanes|k,p.memoizedState=null):M=k,In(Ka,Ts),Ts|=M;return Or(c,p,F,k),p.child}function fp(c,p){var k=p.ref;(c===null&&k!==null||c!==null&&c.ref!==k)&&(p.flags|=512,p.flags|=2097152)}function qd(c,p,k,M,F){var K=fs(k)?Qo:Jr.current;return K=Qr(p,K),Ha(p,F),k=Od(c,p,k,M,K,F),M=Ld(),c!==null&&!ys?(p.updateQueue=c.updateQueue,p.flags&=-2053,c.lanes&=~F,Zi(c,p,F)):(Kn&&M&&ur(p),p.flags|=1,Or(c,p,k,F),p.child)}function pp(c,p,k,M,F){if(fs(k)){var K=!0;Uc(p)}else K=!1;if(Ha(p,F),p.stateNode===null)ru(c,p),ip(p,k,M),Ud(p,k,M,F),M=!0;else if(c===null){var de=p.stateNode,_e=p.memoizedProps;de.props=_e;var $e=de.context,qe=k.contextType;typeof qe=="object"&&qe!==null?qe=Us(qe):(qe=fs(k)?Qo:Jr.current,qe=Qr(p,qe));var at=k.getDerivedStateFromProps,ct=typeof at=="function"||typeof de.getSnapshotBeforeUpdate=="function";ct||typeof de.UNSAFE_componentWillReceiveProps!="function"&&typeof de.componentWillReceiveProps!="function"||(_e!==M||$e!==qe)&&op(p,de,M,qe),Mi=!1;var ot=p.memoizedState;de.state=ot,Yc(p,M,de,F),$e=p.memoizedState,_e!==M||ot!==$e||hs.current||Mi?(typeof at=="function"&&(Pi(p,k,at,M),$e=p.memoizedState),(_e=Mi||aa(p,k,_e,M,ot,$e,qe))?(ct||typeof de.UNSAFE_componentWillMount!="function"&&typeof de.componentWillMount!="function"||(typeof de.componentWillMount=="function"&&de.componentWillMount(),typeof de.UNSAFE_componentWillMount=="function"&&de.UNSAFE_componentWillMount()),typeof de.componentDidMount=="function"&&(p.flags|=4194308)):(typeof de.componentDidMount=="function"&&(p.flags|=4194308),p.memoizedProps=M,p.memoizedState=$e),de.props=M,de.state=$e,de.context=qe,M=_e):(typeof de.componentDidMount=="function"&&(p.flags|=4194308),M=!1)}else{de=p.stateNode,Nd(c,p),_e=p.memoizedProps,qe=p.type===p.elementType?_e:hr(p.type,_e),de.props=qe,ct=p.pendingProps,ot=de.context,$e=k.contextType,typeof $e=="object"&&$e!==null?$e=Us($e):($e=fs(k)?Qo:Jr.current,$e=Qr(p,$e));var jt=k.getDerivedStateFromProps;(at=typeof jt=="function"||typeof de.getSnapshotBeforeUpdate=="function")||typeof de.UNSAFE_componentWillReceiveProps!="function"&&typeof de.componentWillReceiveProps!="function"||(_e!==ct||ot!==$e)&&op(p,de,M,$e),Mi=!1,ot=p.memoizedState,de.state=ot,Yc(p,M,de,F);var Pt=p.memoizedState;_e!==ct||ot!==Pt||hs.current||Mi?(typeof jt=="function"&&(Pi(p,k,jt,M),Pt=p.memoizedState),(qe=Mi||aa(p,k,qe,M,ot,Pt,$e)||!1)?(at||typeof de.UNSAFE_componentWillUpdate!="function"&&typeof de.componentWillUpdate!="function"||(typeof de.componentWillUpdate=="function"&&de.componentWillUpdate(M,Pt,$e),typeof de.UNSAFE_componentWillUpdate=="function"&&de.UNSAFE_componentWillUpdate(M,Pt,$e)),typeof de.componentDidUpdate=="function"&&(p.flags|=4),typeof de.getSnapshotBeforeUpdate=="function"&&(p.flags|=1024)):(typeof de.componentDidUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=4),typeof de.getSnapshotBeforeUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=1024),p.memoizedProps=M,p.memoizedState=Pt),de.props=M,de.state=Pt,de.context=$e,M=qe):(typeof de.componentDidUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=4),typeof de.getSnapshotBeforeUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=1024),M=!1)}return Vd(c,p,k,M,K,F)}function Vd(c,p,k,M,F,K){fp(c,p);var de=(p.flags&128)!==0;if(!M&&!de)return F&&Mf(p,k,!1),Zi(c,p,K);M=p.stateNode,Og.current=p;var _e=de&&typeof k.getDerivedStateFromError!="function"?null:M.render();return p.flags|=1,c!==null&&de?(p.child=Ua(p,c.child,null,K),p.child=Ua(p,null,_e,K)):Or(c,p,_e,K),p.memoizedState=M.state,F&&Mf(p,k,!0),p.child}function Gd(c){var p=c.stateNode;p.pendingContext?Af(c,p.pendingContext,p.pendingContext!==p.context):p.context&&Af(c,p.context,!1),Td(c,p.containerInfo)}function mp(c,p,k,M,F){return ea(),wd(F),p.flags|=256,Or(c,p,k,M),p.child}var Kd={dehydrated:null,treeContext:null,retryLane:0};function Xd(c){return{baseLanes:c,cachePool:null,transitions:null}}function gp(c,p,k){var M=p.pendingProps,F=Yn.current,K=!1,de=(p.flags&128)!==0,_e;if((_e=de)||(_e=c!==null&&c.memoizedState===null?!1:(F&2)!==0),_e?(K=!0,p.flags&=-129):(c===null||c.memoizedState!==null)&&(F|=1),In(Yn,F&1),c===null)return vd(p),c=p.memoizedState,c!==null&&(c=c.dehydrated,c!==null)?((p.mode&1)===0?p.lanes=1:c.data==="$!"?p.lanes=8:p.lanes=1073741824,null):(de=M.children,c=M.fallback,K?(M=p.mode,K=p.child,de={mode:"hidden",children:de},(M&1)===0&&K!==null?(K.childLanes=0,K.pendingProps=de):K=mu(de,M,0,null),c=Ja(c,M,k,null),K.return=p,c.return=p,K.sibling=c,p.child=K,p.child.memoizedState=Xd(k),p.memoizedState=Kd,c):Ul(p,de));if(F=c.memoizedState,F!==null&&(_e=F.dehydrated,_e!==null))return Lg(c,p,de,M,_e,F,k);if(K){K=M.fallback,de=p.mode,F=c.child,_e=F.sibling;var $e={mode:"hidden",children:M.children};return(de&1)===0&&p.child!==F?(M=p.child,M.childLanes=0,M.pendingProps=$e,p.deletions=null):(M=Mo(F,$e),M.subtreeFlags=F.subtreeFlags&14680064),_e!==null?K=Mo(_e,K):(K=Ja(K,de,k,null),K.flags|=2),K.return=p,M.return=p,M.sibling=K,p.child=M,M=K,K=p.child,de=c.child.memoizedState,de=de===null?Xd(k):{baseLanes:de.baseLanes|k,cachePool:null,transitions:de.transitions},K.memoizedState=de,K.childLanes=c.childLanes&~k,p.memoizedState=Kd,M}return K=c.child,c=K.sibling,M=Mo(K,{mode:"visible",children:M.children}),(p.mode&1)===0&&(M.lanes=k),M.return=p,M.sibling=null,c!==null&&(k=p.deletions,k===null?(p.deletions=[c],p.flags|=16):k.push(c)),p.child=M,p.memoizedState=null,M}function Ul(c,p){return p=mu({mode:"visible",children:p},c.mode,0,null),p.return=c,c.child=p}function nu(c,p,k,M){return M!==null&&wd(M),Ua(p,c.child,null,k),c=Ul(p,p.pendingProps.children),c.flags|=2,p.memoizedState=null,c}function Lg(c,p,k,M,F,K,de){if(k)return p.flags&256?(p.flags&=-257,M=Hd(Error(r(422))),nu(c,p,de,M)):p.memoizedState!==null?(p.child=c.child,p.flags|=128,null):(K=M.fallback,F=p.mode,M=mu({mode:"visible",children:M.children},F,0,null),K=Ja(K,F,de,null),K.flags|=2,M.return=p,K.return=p,M.sibling=K,p.child=M,(p.mode&1)!==0&&Ua(p,c.child,null,de),p.child.memoizedState=Xd(de),p.memoizedState=Kd,K);if((p.mode&1)===0)return nu(c,p,de,null);if(F.data==="$!"){if(M=F.nextSibling&&F.nextSibling.dataset,M)var _e=M.dgst;return M=_e,K=Error(r(419)),M=Hd(K,M,void 0),nu(c,p,de,M)}if(_e=(de&c.childLanes)!==0,ys||_e){if(M=fr,M!==null){switch(de&-de){case 4:F=2;break;case 16:F=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:F=32;break;case 536870912:F=268435456;break;default:F=0}F=(F&(M.suspendedLanes|de))!==0?0:F,F!==0&&F!==K.retryLane&&(K.retryLane=F,Yi(c,F),hi(M,c,F,-1))}return xh(),M=Hd(Error(r(421))),nu(c,p,de,M)}return F.data==="$?"?(p.flags|=128,p.child=c.child,p=Xg.bind(null,c),F._reactRetry=p,null):(c=K.treeContext,Ns=_o(F.nextSibling),gs=p,Kn=!0,xs=null,c!==null&&(Bs[li++]=ps,Bs[li++]=ms,Bs[li++]=Fs,ps=c.id,ms=c.overflow,Fs=p),p=Ul(p,M.children),p.flags|=4096,p)}function xp(c,p,k){c.lanes|=p;var M=c.alternate;M!==null&&(M.lanes|=p),Of(c.return,p,k)}function Yd(c,p,k,M,F){var K=c.memoizedState;K===null?c.memoizedState={isBackwards:p,rendering:null,renderingStartTime:0,last:M,tail:k,tailMode:F}:(K.isBackwards=p,K.rendering=null,K.renderingStartTime=0,K.last=M,K.tail=k,K.tailMode=F)}function Jd(c,p,k){var M=p.pendingProps,F=M.revealOrder,K=M.tail;if(Or(c,p,M.children,k),M=Yn.current,(M&2)!==0)M=M&1|2,p.flags|=128;else{if(c!==null&&(c.flags&128)!==0)e:for(c=p.child;c!==null;){if(c.tag===13)c.memoizedState!==null&&xp(c,k,p);else if(c.tag===19)xp(c,k,p);else if(c.child!==null){c.child.return=c,c=c.child;continue}if(c===p)break e;for(;c.sibling===null;){if(c.return===null||c.return===p)break e;c=c.return}c.sibling.return=c.return,c=c.sibling}M&=1}if(In(Yn,M),(p.mode&1)===0)p.memoizedState=null;else switch(F){case"forwards":for(k=p.child,F=null;k!==null;)c=k.alternate,c!==null&&Jc(c)===null&&(F=k),k=k.sibling;k=F,k===null?(F=p.child,p.child=null):(F=k.sibling,k.sibling=null),Yd(p,!1,F,k,K);break;case"backwards":for(k=null,F=p.child,p.child=null;F!==null;){if(c=F.alternate,c!==null&&Jc(c)===null){p.child=F;break}c=F.sibling,F.sibling=k,k=F,F=c}Yd(p,!0,k,null,K);break;case"together":Yd(p,!1,null,null,void 0);break;default:p.memoizedState=null}return p.child}function ru(c,p){(p.mode&1)===0&&c!==null&&(c.alternate=null,p.alternate=null,p.flags|=2)}function Zi(c,p,k){if(c!==null&&(p.dependencies=c.dependencies),la|=p.lanes,(k&p.childLanes)===0)return null;if(c!==null&&p.child!==c.child)throw Error(r(153));if(p.child!==null){for(c=p.child,k=Mo(c,c.pendingProps),p.child=k,k.return=p;c.sibling!==null;)c=c.sibling,k=k.sibling=Mo(c,c.pendingProps),k.return=p;k.sibling=null}return p.child}function gv(c,p,k){switch(p.tag){case 3:Gd(p),ea();break;case 5:Lf(p);break;case 1:fs(p.type)&&Uc(p);break;case 4:Td(p,p.stateNode.containerInfo);break;case 10:var M=p.type._context,F=p.memoizedProps.value;In(ta,M._currentValue),M._currentValue=F;break;case 13:if(M=p.memoizedState,M!==null)return M.dehydrated!==null?(In(Yn,Yn.current&1),p.flags|=128,null):(k&p.child.childLanes)!==0?gp(c,p,k):(In(Yn,Yn.current&1),c=Zi(c,p,k),c!==null?c.sibling:null);In(Yn,Yn.current&1);break;case 19:if(M=(k&p.childLanes)!==0,(c.flags&128)!==0){if(M)return Jd(c,p,k);p.flags|=128}if(F=p.memoizedState,F!==null&&(F.rendering=null,F.tail=null,F.lastEffect=null),In(Yn,Yn.current),M)break;return null;case 22:case 23:return p.lanes=0,hp(c,p,k)}return Zi(c,p,k)}var Qd,Zd,yp,vp;Qd=function(c,p){for(var k=p.child;k!==null;){if(k.tag===5||k.tag===6)c.appendChild(k.stateNode);else if(k.tag!==4&&k.child!==null){k.child.return=k,k=k.child;continue}if(k===p)break;for(;k.sibling===null;){if(k.return===null||k.return===p)return;k=k.return}k.sibling.return=k.return,k=k.sibling}},Zd=function(){},yp=function(c,p,k,M){var F=c.memoizedProps;if(F!==M){c=p.stateNode,ra(Ii.current);var K=null;switch(k){case"input":F=Rt(c,F),M=Rt(c,M),K=[];break;case"select":F=Q({},F,{value:void 0}),M=Q({},M,{value:void 0}),K=[];break;case"textarea":F=kt(c,F),M=kt(c,M),K=[];break;default:typeof F.onClick!="function"&&typeof M.onClick=="function"&&(c.onclick=zc)}vi(k,M);var de;k=null;for(qe in F)if(!M.hasOwnProperty(qe)&&F.hasOwnProperty(qe)&&F[qe]!=null)if(qe==="style"){var _e=F[qe];for(de in _e)_e.hasOwnProperty(de)&&(k||(k={}),k[de]="")}else qe!=="dangerouslySetInnerHTML"&&qe!=="children"&&qe!=="suppressContentEditableWarning"&&qe!=="suppressHydrationWarning"&&qe!=="autoFocus"&&(o.hasOwnProperty(qe)?K||(K=[]):(K=K||[]).push(qe,null));for(qe in M){var $e=M[qe];if(_e=F!=null?F[qe]:void 0,M.hasOwnProperty(qe)&&$e!==_e&&($e!=null||_e!=null))if(qe==="style")if(_e){for(de in _e)!_e.hasOwnProperty(de)||$e&&$e.hasOwnProperty(de)||(k||(k={}),k[de]="");for(de in $e)$e.hasOwnProperty(de)&&_e[de]!==$e[de]&&(k||(k={}),k[de]=$e[de])}else k||(K||(K=[]),K.push(qe,k)),k=$e;else qe==="dangerouslySetInnerHTML"?($e=$e?$e.__html:void 0,_e=_e?_e.__html:void 0,$e!=null&&_e!==$e&&(K=K||[]).push(qe,$e)):qe==="children"?typeof $e!="string"&&typeof $e!="number"||(K=K||[]).push(qe,""+$e):qe!=="suppressContentEditableWarning"&&qe!=="suppressHydrationWarning"&&(o.hasOwnProperty(qe)?($e!=null&&qe==="onScroll"&&zn("scroll",c),K||_e===$e||(K=[])):(K=K||[]).push(qe,$e))}k&&(K=K||[]).push("style",k);var qe=K;(p.updateQueue=qe)&&(p.flags|=4)}},vp=function(c,p,k,M){k!==M&&(p.flags|=4)};function su(c,p){if(!Kn)switch(c.tailMode){case"hidden":p=c.tail;for(var k=null;p!==null;)p.alternate!==null&&(k=p),p=p.sibling;k===null?c.tail=null:k.sibling=null;break;case"collapsed":k=c.tail;for(var M=null;k!==null;)k.alternate!==null&&(M=k),k=k.sibling;M===null?p||c.tail===null?c.tail=null:c.tail.sibling=null:M.sibling=null}}function Lr(c){var p=c.alternate!==null&&c.alternate.child===c.child,k=0,M=0;if(p)for(var F=c.child;F!==null;)k|=F.lanes|F.childLanes,M|=F.subtreeFlags&14680064,M|=F.flags&14680064,F.return=c,F=F.sibling;else for(F=c.child;F!==null;)k|=F.lanes|F.childLanes,M|=F.subtreeFlags,M|=F.flags,F.return=c,F=F.sibling;return c.subtreeFlags|=M,c.childLanes=k,p}function zg(c,p,k){var M=p.pendingProps;switch(md(p),p.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Lr(p),null;case 1:return fs(p.type)&&Fc(),Lr(p),null;case 3:return M=p.stateNode,sa(),Bn(hs),Bn(Jr),Rd(),M.pendingContext&&(M.context=M.pendingContext,M.pendingContext=null),(c===null||c.child===null)&&(Dl(p)?p.flags|=4:c===null||c.memoizedState.isDehydrated&&(p.flags&256)===0||(p.flags|=1024,xs!==null&&(ph(xs),xs=null))),Zd(c,p),Lr(p),null;case 5:$d(p);var F=ra(qa.current);if(k=p.type,c!==null&&p.stateNode!=null)yp(c,p,k,M,F),c.ref!==p.ref&&(p.flags|=512,p.flags|=2097152);else{if(!M){if(p.stateNode===null)throw Error(r(166));return Lr(p),null}if(c=ra(Ii.current),Dl(p)){M=p.stateNode,k=p.type;var K=p.memoizedProps;switch(M[Ai]=p,M[Il]=K,c=(p.mode&1)!==0,k){case"dialog":zn("cancel",M),zn("close",M);break;case"iframe":case"object":case"embed":zn("load",M);break;case"video":case"audio":for(F=0;F<Al.length;F++)zn(Al[F],M);break;case"source":zn("error",M);break;case"img":case"image":case"link":zn("error",M),zn("load",M);break;case"details":zn("toggle",M);break;case"input":He(M,K),zn("invalid",M);break;case"select":M._wrapperState={wasMultiple:!!K.multiple},zn("invalid",M);break;case"textarea":Kt(M,K),zn("invalid",M)}vi(k,K),F=null;for(var de in K)if(K.hasOwnProperty(de)){var _e=K[de];de==="children"?typeof _e=="string"?M.textContent!==_e&&(K.suppressHydrationWarning!==!0&&Lc(M.textContent,_e,c),F=["children",_e]):typeof _e=="number"&&M.textContent!==""+_e&&(K.suppressHydrationWarning!==!0&&Lc(M.textContent,_e,c),F=["children",""+_e]):o.hasOwnProperty(de)&&_e!=null&&de==="onScroll"&&zn("scroll",M)}switch(k){case"input":Je(M),an(M,K,!0);break;case"textarea":Je(M),Rn(M);break;case"select":case"option":break;default:typeof K.onClick=="function"&&(M.onclick=zc)}M=F,p.updateQueue=M,M!==null&&(p.flags|=4)}else{de=F.nodeType===9?F:F.ownerDocument,c==="http://www.w3.org/1999/xhtml"&&(c=Br(k)),c==="http://www.w3.org/1999/xhtml"?k==="script"?(c=de.createElement("div"),c.innerHTML="<script><\/script>",c=c.removeChild(c.firstChild)):typeof M.is=="string"?c=de.createElement(k,{is:M.is}):(c=de.createElement(k),k==="select"&&(de=c,M.multiple?de.multiple=!0:M.size&&(de.size=M.size))):c=de.createElementNS(c,k),c[Ai]=p,c[Il]=M,Qd(c,p,!1,!1),p.stateNode=c;e:{switch(de=yn(k,M),k){case"dialog":zn("cancel",c),zn("close",c),F=M;break;case"iframe":case"object":case"embed":zn("load",c),F=M;break;case"video":case"audio":for(F=0;F<Al.length;F++)zn(Al[F],c);F=M;break;case"source":zn("error",c),F=M;break;case"img":case"image":case"link":zn("error",c),zn("load",c),F=M;break;case"details":zn("toggle",c),F=M;break;case"input":He(c,M),F=Rt(c,M),zn("invalid",c);break;case"option":F=M;break;case"select":c._wrapperState={wasMultiple:!!M.multiple},F=Q({},M,{value:void 0}),zn("invalid",c);break;case"textarea":Kt(c,M),F=kt(c,M),zn("invalid",c);break;default:F=M}vi(k,F),_e=F;for(K in _e)if(_e.hasOwnProperty(K)){var $e=_e[K];K==="style"?Ta(c,$e):K==="dangerouslySetInnerHTML"?($e=$e?$e.__html:void 0,$e!=null&&St(c,$e)):K==="children"?typeof $e=="string"?(k!=="textarea"||$e!=="")&&Tt(c,$e):typeof $e=="number"&&Tt(c,""+$e):K!=="suppressContentEditableWarning"&&K!=="suppressHydrationWarning"&&K!=="autoFocus"&&(o.hasOwnProperty(K)?$e!=null&&K==="onScroll"&&zn("scroll",c):$e!=null&&C(c,K,$e,de))}switch(k){case"input":Je(c),an(c,M,!1);break;case"textarea":Je(c),Rn(c);break;case"option":M.value!=null&&c.setAttribute("value",""+ne(M.value));break;case"select":c.multiple=!!M.multiple,K=M.value,K!=null?yt(c,!!M.multiple,K,!1):M.defaultValue!=null&&yt(c,!!M.multiple,M.defaultValue,!0);break;default:typeof F.onClick=="function"&&(c.onclick=zc)}switch(k){case"button":case"input":case"select":case"textarea":M=!!M.autoFocus;break e;case"img":M=!0;break e;default:M=!1}}M&&(p.flags|=4)}p.ref!==null&&(p.flags|=512,p.flags|=2097152)}return Lr(p),null;case 6:if(c&&p.stateNode!=null)vp(c,p,c.memoizedProps,M);else{if(typeof M!="string"&&p.stateNode===null)throw Error(r(166));if(k=ra(qa.current),ra(Ii.current),Dl(p)){if(M=p.stateNode,k=p.memoizedProps,M[Ai]=p,(K=M.nodeValue!==k)&&(c=gs,c!==null))switch(c.tag){case 3:Lc(M.nodeValue,k,(c.mode&1)!==0);break;case 5:c.memoizedProps.suppressHydrationWarning!==!0&&Lc(M.nodeValue,k,(c.mode&1)!==0)}K&&(p.flags|=4)}else M=(k.nodeType===9?k:k.ownerDocument).createTextNode(M),M[Ai]=p,p.stateNode=M}return Lr(p),null;case 13:if(Bn(Yn),M=p.memoizedState,c===null||c.memoizedState!==null&&c.memoizedState.dehydrated!==null){if(Kn&&Ns!==null&&(p.mode&1)!==0&&(p.flags&128)===0)Pf(),ea(),p.flags|=98560,K=!1;else if(K=Dl(p),M!==null&&M.dehydrated!==null){if(c===null){if(!K)throw Error(r(318));if(K=p.memoizedState,K=K!==null?K.dehydrated:null,!K)throw Error(r(317));K[Ai]=p}else ea(),(p.flags&128)===0&&(p.memoizedState=null),p.flags|=4;Lr(p),K=!1}else xs!==null&&(ph(xs),xs=null),K=!0;if(!K)return p.flags&65536?p:null}return(p.flags&128)!==0?(p.lanes=k,p):(M=M!==null,M!==(c!==null&&c.memoizedState!==null)&&M&&(p.child.flags|=8192,(p.mode&1)!==0&&(c===null||(Yn.current&1)!==0?br===0&&(br=3):xh())),p.updateQueue!==null&&(p.flags|=4),Lr(p),null);case 4:return sa(),Zd(c,p),c===null&&Rl(p.stateNode.containerInfo),Lr(p),null;case 10:return jd(p.type._context),Lr(p),null;case 17:return fs(p.type)&&Fc(),Lr(p),null;case 19:if(Bn(Yn),K=p.memoizedState,K===null)return Lr(p),null;if(M=(p.flags&128)!==0,de=K.rendering,de===null)if(M)su(K,!1);else{if(br!==0||c!==null&&(c.flags&128)!==0)for(c=p.child;c!==null;){if(de=Jc(c),de!==null){for(p.flags|=128,su(K,!1),M=de.updateQueue,M!==null&&(p.updateQueue=M,p.flags|=4),p.subtreeFlags=0,M=k,k=p.child;k!==null;)K=k,c=M,K.flags&=14680066,de=K.alternate,de===null?(K.childLanes=0,K.lanes=c,K.child=null,K.subtreeFlags=0,K.memoizedProps=null,K.memoizedState=null,K.updateQueue=null,K.dependencies=null,K.stateNode=null):(K.childLanes=de.childLanes,K.lanes=de.lanes,K.child=de.child,K.subtreeFlags=0,K.deletions=null,K.memoizedProps=de.memoizedProps,K.memoizedState=de.memoizedState,K.updateQueue=de.updateQueue,K.type=de.type,c=de.dependencies,K.dependencies=c===null?null:{lanes:c.lanes,firstContext:c.firstContext}),k=k.sibling;return In(Yn,Yn.current&1|2),p.child}c=c.sibling}K.tail!==null&&kn()>Xa&&(p.flags|=128,M=!0,su(K,!1),p.lanes=4194304)}else{if(!M)if(c=Jc(de),c!==null){if(p.flags|=128,M=!0,k=c.updateQueue,k!==null&&(p.updateQueue=k,p.flags|=4),su(K,!0),K.tail===null&&K.tailMode==="hidden"&&!de.alternate&&!Kn)return Lr(p),null}else 2*kn()-K.renderingStartTime>Xa&&k!==1073741824&&(p.flags|=128,M=!0,su(K,!1),p.lanes=4194304);K.isBackwards?(de.sibling=p.child,p.child=de):(k=K.last,k!==null?k.sibling=de:p.child=de,K.last=de)}return K.tail!==null?(p=K.tail,K.rendering=p,K.tail=p.sibling,K.renderingStartTime=kn(),p.sibling=null,k=Yn.current,In(Yn,M?k&1|2:k&1),p):(Lr(p),null);case 22:case 23:return gh(),M=p.memoizedState!==null,c!==null&&c.memoizedState!==null!==M&&(p.flags|=8192),M&&(p.mode&1)!==0?(Ts&1073741824)!==0&&(Lr(p),p.subtreeFlags&6&&(p.flags|=8192)):Lr(p),null;case 24:return null;case 25:return null}throw Error(r(156,p.tag))}function Bg(c,p){switch(md(p),p.tag){case 1:return fs(p.type)&&Fc(),c=p.flags,c&65536?(p.flags=c&-65537|128,p):null;case 3:return sa(),Bn(hs),Bn(Jr),Rd(),c=p.flags,(c&65536)!==0&&(c&128)===0?(p.flags=c&-65537|128,p):null;case 5:return $d(p),null;case 13:if(Bn(Yn),c=p.memoizedState,c!==null&&c.dehydrated!==null){if(p.alternate===null)throw Error(r(340));ea()}return c=p.flags,c&65536?(p.flags=c&-65537|128,p):null;case 19:return Bn(Yn),null;case 4:return sa(),null;case 10:return jd(p.type._context),null;case 22:case 23:return gh(),null;case 24:return null;default:return null}}var eh=!1,zr=!1,Fg=typeof WeakSet=="function"?WeakSet:Set,It=null;function Ga(c,p){var k=c.ref;if(k!==null)if(typeof k=="function")try{k(null)}catch(M){Jn(c,p,M)}else k.current=null}function th(c,p,k){try{k()}catch(M){Jn(c,p,M)}}var bp=!1;function Ug(c,p){if(ad=bo,c=Zu(),ed(c)){if("selectionStart"in c)var k={start:c.selectionStart,end:c.selectionEnd};else e:{k=(k=c.ownerDocument)&&k.defaultView||window;var M=k.getSelection&&k.getSelection();if(M&&M.rangeCount!==0){k=M.anchorNode;var F=M.anchorOffset,K=M.focusNode;M=M.focusOffset;try{k.nodeType,K.nodeType}catch{k=null;break e}var de=0,_e=-1,$e=-1,qe=0,at=0,ct=c,ot=null;t:for(;;){for(var jt;ct!==k||F!==0&&ct.nodeType!==3||(_e=de+F),ct!==K||M!==0&&ct.nodeType!==3||($e=de+M),ct.nodeType===3&&(de+=ct.nodeValue.length),(jt=ct.firstChild)!==null;)ot=ct,ct=jt;for(;;){if(ct===c)break t;if(ot===k&&++qe===F&&(_e=de),ot===K&&++at===M&&($e=de),(jt=ct.nextSibling)!==null)break;ct=ot,ot=ct.parentNode}ct=jt}k=_e===-1||$e===-1?null:{start:_e,end:$e}}else k=null}k=k||{start:0,end:0}}else k=null;for(ld={focusedElem:c,selectionRange:k},bo=!1,It=p;It!==null;)if(p=It,c=p.child,(p.subtreeFlags&1028)!==0&&c!==null)c.return=p,It=c;else for(;It!==null;){p=It;try{var Pt=p.alternate;if((p.flags&1024)!==0)switch(p.tag){case 0:case 11:case 15:break;case 1:if(Pt!==null){var Dt=Pt.memoizedProps,Pn=Pt.memoizedState,Ue=p.stateNode,Ie=Ue.getSnapshotBeforeUpdate(p.elementType===p.type?Dt:hr(p.type,Dt),Pn);Ue.__reactInternalSnapshotBeforeUpdate=Ie}break;case 3:var Ve=p.stateNode.containerInfo;Ve.nodeType===1?Ve.textContent="":Ve.nodeType===9&&Ve.documentElement&&Ve.removeChild(Ve.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(r(163))}}catch(ht){Jn(p,p.return,ht)}if(c=p.sibling,c!==null){c.return=p.return,It=c;break}It=p.return}return Pt=bp,bp=!1,Pt}function Hl(c,p,k){var M=p.updateQueue;if(M=M!==null?M.lastEffect:null,M!==null){var F=M=M.next;do{if((F.tag&c)===c){var K=F.destroy;F.destroy=void 0,K!==void 0&&th(p,k,K)}F=F.next}while(F!==M)}}function nh(c,p){if(p=p.updateQueue,p=p!==null?p.lastEffect:null,p!==null){var k=p=p.next;do{if((k.tag&c)===c){var M=k.create;k.destroy=M()}k=k.next}while(k!==p)}}function rh(c){var p=c.ref;if(p!==null){var k=c.stateNode;switch(c.tag){case 5:c=k;break;default:c=k}typeof p=="function"?p(c):p.current=c}}function wp(c){var p=c.alternate;p!==null&&(c.alternate=null,wp(p)),c.child=null,c.deletions=null,c.sibling=null,c.tag===5&&(p=c.stateNode,p!==null&&(delete p[Ai],delete p[Il],delete p[hd],delete p[Tf],delete p[$f])),c.stateNode=null,c.return=null,c.dependencies=null,c.memoizedProps=null,c.memoizedState=null,c.pendingProps=null,c.stateNode=null,c.updateQueue=null}function _p(c){return c.tag===5||c.tag===3||c.tag===4}function kp(c){e:for(;;){for(;c.sibling===null;){if(c.return===null||_p(c.return))return null;c=c.return}for(c.sibling.return=c.return,c=c.sibling;c.tag!==5&&c.tag!==6&&c.tag!==18;){if(c.flags&2||c.child===null||c.tag===4)continue e;c.child.return=c,c=c.child}if(!(c.flags&2))return c.stateNode}}function sh(c,p,k){var M=c.tag;if(M===5||M===6)c=c.stateNode,p?k.nodeType===8?k.parentNode.insertBefore(c,p):k.insertBefore(c,p):(k.nodeType===8?(p=k.parentNode,p.insertBefore(c,k)):(p=k,p.appendChild(c)),k=k._reactRootContainer,k!=null||p.onclick!==null||(p.onclick=zc));else if(M!==4&&(c=c.child,c!==null))for(sh(c,p,k),c=c.sibling;c!==null;)sh(c,p,k),c=c.sibling}function ih(c,p,k){var M=c.tag;if(M===5||M===6)c=c.stateNode,p?k.insertBefore(c,p):k.appendChild(c);else if(M!==4&&(c=c.child,c!==null))for(ih(c,p,k),c=c.sibling;c!==null;)ih(c,p,k),c=c.sibling}var Cr=null,ui=!1;function No(c,p,k){for(k=k.child;k!==null;)Hg(c,p,k),k=k.sibling}function Hg(c,p,k){if(gr&&typeof gr.onCommitFiberUnmount=="function")try{gr.onCommitFiberUnmount(cs,k)}catch{}switch(k.tag){case 5:zr||Ga(k,p);case 6:var M=Cr,F=ui;Cr=null,No(c,p,k),Cr=M,ui=F,Cr!==null&&(ui?(c=Cr,k=k.stateNode,c.nodeType===8?c.parentNode.removeChild(k):c.removeChild(k)):Cr.removeChild(k.stateNode));break;case 18:Cr!==null&&(ui?(c=Cr,k=k.stateNode,c.nodeType===8?dd(c.parentNode,k):c.nodeType===1&&dd(c,k),Vi(c)):dd(Cr,k.stateNode));break;case 4:M=Cr,F=ui,Cr=k.stateNode.containerInfo,ui=!0,No(c,p,k),Cr=M,ui=F;break;case 0:case 11:case 14:case 15:if(!zr&&(M=k.updateQueue,M!==null&&(M=M.lastEffect,M!==null))){F=M=M.next;do{var K=F,de=K.destroy;K=K.tag,de!==void 0&&((K&2)!==0||(K&4)!==0)&&th(k,p,de),F=F.next}while(F!==M)}No(c,p,k);break;case 1:if(!zr&&(Ga(k,p),M=k.stateNode,typeof M.componentWillUnmount=="function"))try{M.props=k.memoizedProps,M.state=k.memoizedState,M.componentWillUnmount()}catch(_e){Jn(k,p,_e)}No(c,p,k);break;case 21:No(c,p,k);break;case 22:k.mode&1?(zr=(M=zr)||k.memoizedState!==null,No(c,p,k),zr=M):No(c,p,k);break;default:No(c,p,k)}}function Wl(c){var p=c.updateQueue;if(p!==null){c.updateQueue=null;var k=c.stateNode;k===null&&(k=c.stateNode=new Fg),p.forEach(function(M){var F=Yg.bind(null,c,M);k.has(M)||(k.add(M),M.then(F,F))})}}function Ws(c,p){var k=p.deletions;if(k!==null)for(var M=0;M<k.length;M++){var F=k[M];try{var K=c,de=p,_e=de;e:for(;_e!==null;){switch(_e.tag){case 5:Cr=_e.stateNode,ui=!1;break e;case 3:Cr=_e.stateNode.containerInfo,ui=!0;break e;case 4:Cr=_e.stateNode.containerInfo,ui=!0;break e}_e=_e.return}if(Cr===null)throw Error(r(160));Hg(K,de,F),Cr=null,ui=!1;var $e=F.alternate;$e!==null&&($e.return=null),F.return=null}catch(qe){Jn(F,p,qe)}}if(p.subtreeFlags&12854)for(p=p.child;p!==null;)oh(p,c),p=p.sibling}function oh(c,p){var k=c.alternate,M=c.flags;switch(c.tag){case 0:case 11:case 14:case 15:if(Ws(p,c),di(c),M&4){try{Hl(3,c,c.return),nh(3,c)}catch(Dt){Jn(c,c.return,Dt)}try{Hl(5,c,c.return)}catch(Dt){Jn(c,c.return,Dt)}}break;case 1:Ws(p,c),di(c),M&512&&k!==null&&Ga(k,k.return);break;case 5:if(Ws(p,c),di(c),M&512&&k!==null&&Ga(k,k.return),c.flags&32){var F=c.stateNode;try{Tt(F,"")}catch(Dt){Jn(c,c.return,Dt)}}if(M&4&&(F=c.stateNode,F!=null)){var K=c.memoizedProps,de=k!==null?k.memoizedProps:K,_e=c.type,$e=c.updateQueue;if(c.updateQueue=null,$e!==null)try{_e==="input"&&K.type==="radio"&&K.name!=null&&vt(F,K),yn(_e,de);var qe=yn(_e,K);for(de=0;de<$e.length;de+=2){var at=$e[de],ct=$e[de+1];at==="style"?Ta(F,ct):at==="dangerouslySetInnerHTML"?St(F,ct):at==="children"?Tt(F,ct):C(F,at,ct,qe)}switch(_e){case"input":st(F,K);break;case"textarea":On(F,K);break;case"select":var ot=F._wrapperState.wasMultiple;F._wrapperState.wasMultiple=!!K.multiple;var jt=K.value;jt!=null?yt(F,!!K.multiple,jt,!1):ot!==!!K.multiple&&(K.defaultValue!=null?yt(F,!!K.multiple,K.defaultValue,!0):yt(F,!!K.multiple,K.multiple?[]:"",!1))}F[Il]=K}catch(Dt){Jn(c,c.return,Dt)}}break;case 6:if(Ws(p,c),di(c),M&4){if(c.stateNode===null)throw Error(r(162));F=c.stateNode,K=c.memoizedProps;try{F.nodeValue=K}catch(Dt){Jn(c,c.return,Dt)}}break;case 3:if(Ws(p,c),di(c),M&4&&k!==null&&k.memoizedState.isDehydrated)try{Vi(p.containerInfo)}catch(Dt){Jn(c,c.return,Dt)}break;case 4:Ws(p,c),di(c);break;case 13:Ws(p,c),di(c),F=c.child,F.flags&8192&&(K=F.memoizedState!==null,F.stateNode.isHidden=K,!K||F.alternate!==null&&F.alternate.memoizedState!==null||(uh=kn())),M&4&&Wl(c);break;case 22:if(at=k!==null&&k.memoizedState!==null,c.mode&1?(zr=(qe=zr)||at,Ws(p,c),zr=qe):Ws(p,c),di(c),M&8192){if(qe=c.memoizedState!==null,(c.stateNode.isHidden=qe)&&!at&&(c.mode&1)!==0)for(It=c,at=c.child;at!==null;){for(ct=It=at;It!==null;){switch(ot=It,jt=ot.child,ot.tag){case 0:case 11:case 14:case 15:Hl(4,ot,ot.return);break;case 1:Ga(ot,ot.return);var Pt=ot.stateNode;if(typeof Pt.componentWillUnmount=="function"){M=ot,k=ot.return;try{p=M,Pt.props=p.memoizedProps,Pt.state=p.memoizedState,Pt.componentWillUnmount()}catch(Dt){Jn(M,k,Dt)}}break;case 5:Ga(ot,ot.return);break;case 22:if(ot.memoizedState!==null){ah(ct);continue}}jt!==null?(jt.return=ot,It=jt):ah(ct)}at=at.sibling}e:for(at=null,ct=c;;){if(ct.tag===5){if(at===null){at=ct;try{F=ct.stateNode,qe?(K=F.style,typeof K.setProperty=="function"?K.setProperty("display","none","important"):K.display="none"):(_e=ct.stateNode,$e=ct.memoizedProps.style,de=$e!=null&&$e.hasOwnProperty("display")?$e.display:null,_e.style.display=$r("display",de))}catch(Dt){Jn(c,c.return,Dt)}}}else if(ct.tag===6){if(at===null)try{ct.stateNode.nodeValue=qe?"":ct.memoizedProps}catch(Dt){Jn(c,c.return,Dt)}}else if((ct.tag!==22&&ct.tag!==23||ct.memoizedState===null||ct===c)&&ct.child!==null){ct.child.return=ct,ct=ct.child;continue}if(ct===c)break e;for(;ct.sibling===null;){if(ct.return===null||ct.return===c)break e;at===ct&&(at=null),ct=ct.return}at===ct&&(at=null),ct.sibling.return=ct.return,ct=ct.sibling}}break;case 19:Ws(p,c),di(c),M&4&&Wl(c);break;case 21:break;default:Ws(p,c),di(c)}}function di(c){var p=c.flags;if(p&2){try{e:{for(var k=c.return;k!==null;){if(_p(k)){var M=k;break e}k=k.return}throw Error(r(160))}switch(M.tag){case 5:var F=M.stateNode;M.flags&32&&(Tt(F,""),M.flags&=-33);var K=kp(c);ih(c,K,F);break;case 3:case 4:var de=M.stateNode.containerInfo,_e=kp(c);sh(c,_e,de);break;default:throw Error(r(161))}}catch($e){Jn(c,c.return,$e)}c.flags&=-3}p&4096&&(c.flags&=-4097)}function Sp(c,p,k){It=c,Cp(c)}function Cp(c,p,k){for(var M=(c.mode&1)!==0;It!==null;){var F=It,K=F.child;if(F.tag===22&&M){var de=F.memoizedState!==null||eh;if(!de){var _e=F.alternate,$e=_e!==null&&_e.memoizedState!==null||zr;_e=eh;var qe=zr;if(eh=de,(zr=$e)&&!qe)for(It=F;It!==null;)de=It,$e=de.child,de.tag===22&&de.memoizedState!==null?lh(F):$e!==null?($e.return=de,It=$e):lh(F);for(;K!==null;)It=K,Cp(K),K=K.sibling;It=F,eh=_e,zr=qe}jp(c)}else(F.subtreeFlags&8772)!==0&&K!==null?(K.return=F,It=K):jp(c)}}function jp(c){for(;It!==null;){var p=It;if((p.flags&8772)!==0){var k=p.alternate;try{if((p.flags&8772)!==0)switch(p.tag){case 0:case 11:case 15:zr||nh(5,p);break;case 1:var M=p.stateNode;if(p.flags&4&&!zr)if(k===null)M.componentDidMount();else{var F=p.elementType===p.type?k.memoizedProps:hr(p.type,k.memoizedProps);M.componentDidUpdate(F,k.memoizedState,M.__reactInternalSnapshotBeforeUpdate)}var K=p.updateQueue;K!==null&&Eg(p,K,M);break;case 3:var de=p.updateQueue;if(de!==null){if(k=null,p.child!==null)switch(p.child.tag){case 5:k=p.child.stateNode;break;case 1:k=p.child.stateNode}Eg(p,de,k)}break;case 5:var _e=p.stateNode;if(k===null&&p.flags&4){k=_e;var $e=p.memoizedProps;switch(p.type){case"button":case"input":case"select":case"textarea":$e.autoFocus&&k.focus();break;case"img":$e.src&&(k.src=$e.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(p.memoizedState===null){var qe=p.alternate;if(qe!==null){var at=qe.memoizedState;if(at!==null){var ct=at.dehydrated;ct!==null&&Vi(ct)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(r(163))}zr||p.flags&512&&rh(p)}catch(ot){Jn(p,p.return,ot)}}if(p===c){It=null;break}if(k=p.sibling,k!==null){k.return=p.return,It=k;break}It=p.return}}function ah(c){for(;It!==null;){var p=It;if(p===c){It=null;break}var k=p.sibling;if(k!==null){k.return=p.return,It=k;break}It=p.return}}function lh(c){for(;It!==null;){var p=It;try{switch(p.tag){case 0:case 11:case 15:var k=p.return;try{nh(4,p)}catch($e){Jn(p,k,$e)}break;case 1:var M=p.stateNode;if(typeof M.componentDidMount=="function"){var F=p.return;try{M.componentDidMount()}catch($e){Jn(p,F,$e)}}var K=p.return;try{rh(p)}catch($e){Jn(p,K,$e)}break;case 5:var de=p.return;try{rh(p)}catch($e){Jn(p,de,$e)}}}catch($e){Jn(p,p.return,$e)}if(p===c){It=null;break}var _e=p.sibling;if(_e!==null){_e.return=p.return,It=_e;break}It=p.return}}var Wg=Math.ceil,iu=N.ReactCurrentDispatcher,ou=N.ReactCurrentOwner,qs=N.ReactCurrentBatchConfig,gn=0,fr=null,ar=null,jr=0,Ts=0,Ka=Ki(0),br=0,ql=null,la=0,au=0,ch=0,lu=null,vs=null,uh=0,Xa=1/0,To=null,cu=!1,dh=null,$o=null,uu=!1,ca=null,du=0,Vl=0,hh=null,Gl=-1,hu=0;function es(){return(gn&6)!==0?kn():Gl!==-1?Gl:Gl=kn()}function Ao(c){return(c.mode&1)===0?1:(gn&2)!==0&&jr!==0?jr&-jr:_d.transition!==null?(hu===0&&(hu=Es()),hu):(c=Pe,c!==0||(c=window.event,c=c===void 0?16:fe(c.type)),c)}function hi(c,p,k,M){if(50<Vl)throw Vl=0,hh=null,Error(r(185));qr(c,k,M),((gn&2)===0||c!==fr)&&(c===fr&&((gn&2)===0&&(au|=k),br===4&&Ro(c,jr)),bs(c,M),k===1&&gn===0&&(p.mode&1)===0&&(Xa=kn()+500,Hc&&So()))}function bs(c,p){var k=c.callbackNode;ds(c,p);var M=ji(c,c===fr?jr:0);if(M===0)k!==null&&Sr(k),c.callbackNode=null,c.callbackPriority=0;else if(p=M&-M,c.callbackPriority!==p){if(k!=null&&Sr(k),p===1)c.tag===0?fv(Tp.bind(null,c)):If(Tp.bind(null,c)),kg(function(){(gn&6)===0&&So()}),k=null;else{switch(Qe(M)){case 1:k=Vn;break;case 4:k=Ir;break;case 16:k=ti;break;case 536870912:k=ki;break;default:k=ti}k=Pp(k,Ep.bind(null,c))}c.callbackPriority=p,c.callbackNode=k}}function Ep(c,p){if(Gl=-1,hu=0,(gn&6)!==0)throw Error(r(327));var k=c.callbackNode;if(Ya()&&c.callbackNode!==k)return null;var M=ji(c,c===fr?jr:0);if(M===0)return null;if((M&30)!==0||(M&c.expiredLanes)!==0||p)p=fu(c,M);else{p=M;var F=gn;gn|=2;var K=qg();(fr!==c||jr!==p)&&(To=null,Xa=kn()+500,da(c,p));do try{xv();break}catch(_e){$p(c,_e)}while(!0);Cd(),iu.current=K,gn=F,ar!==null?p=0:(fr=null,jr=0,p=br)}if(p!==0){if(p===2&&(F=Wi(c),F!==0&&(M=F,p=fh(c,F))),p===1)throw k=ql,da(c,0),Ro(c,M),bs(c,kn()),k;if(p===6)Ro(c,M);else{if(F=c.current.alternate,(M&30)===0&&!Np(F)&&(p=fu(c,M),p===2&&(K=Wi(c),K!==0&&(M=K,p=fh(c,K))),p===1))throw k=ql,da(c,0),Ro(c,M),bs(c,kn()),k;switch(c.finishedWork=F,c.finishedLanes=M,p){case 0:case 1:throw Error(r(345));case 2:ha(c,vs,To);break;case 3:if(Ro(c,M),(M&130023424)===M&&(p=uh+500-kn(),10<p)){if(ji(c,0)!==0)break;if(F=c.suspendedLanes,(F&M)!==M){es(),c.pingedLanes|=c.suspendedLanes&F;break}c.timeoutHandle=ud(ha.bind(null,c,vs,To),p);break}ha(c,vs,To);break;case 4:if(Ro(c,M),(M&4194240)===M)break;for(p=c.eventTimes,F=-1;0<M;){var de=31-Gn(M);K=1<<de,de=p[de],de>F&&(F=de),M&=~K}if(M=F,M=kn()-M,M=(120>M?120:480>M?480:1080>M?1080:1920>M?1920:3e3>M?3e3:4320>M?4320:1960*Wg(M/1960))-M,10<M){c.timeoutHandle=ud(ha.bind(null,c,vs,To),M);break}ha(c,vs,To);break;case 5:ha(c,vs,To);break;default:throw Error(r(329))}}}return bs(c,kn()),c.callbackNode===k?Ep.bind(null,c):null}function fh(c,p){var k=lu;return c.current.memoizedState.isDehydrated&&(da(c,p).flags|=256),c=fu(c,p),c!==2&&(p=vs,vs=k,p!==null&&ph(p)),c}function ph(c){vs===null?vs=c:vs.push.apply(vs,c)}function Np(c){for(var p=c;;){if(p.flags&16384){var k=p.updateQueue;if(k!==null&&(k=k.stores,k!==null))for(var M=0;M<k.length;M++){var F=k[M],K=F.getSnapshot;F=F.value;try{if(!ai(K(),F))return!1}catch{return!1}}}if(k=p.child,p.subtreeFlags&16384&&k!==null)k.return=p,p=k;else{if(p===c)break;for(;p.sibling===null;){if(p.return===null||p.return===c)return!0;p=p.return}p.sibling.return=p.return,p=p.sibling}}return!0}function Ro(c,p){for(p&=~ch,p&=~au,c.suspendedLanes|=p,c.pingedLanes&=~p,c=c.expirationTimes;0<p;){var k=31-Gn(p),M=1<<k;c[k]=-1,p&=~M}}function Tp(c){if((gn&6)!==0)throw Error(r(327));Ya();var p=ji(c,0);if((p&1)===0)return bs(c,kn()),null;var k=fu(c,p);if(c.tag!==0&&k===2){var M=Wi(c);M!==0&&(p=M,k=fh(c,M))}if(k===1)throw k=ql,da(c,0),Ro(c,p),bs(c,kn()),k;if(k===6)throw Error(r(345));return c.finishedWork=c.current.alternate,c.finishedLanes=p,ha(c,vs,To),bs(c,kn()),null}function mh(c,p){var k=gn;gn|=1;try{return c(p)}finally{gn=k,gn===0&&(Xa=kn()+500,Hc&&So())}}function ua(c){ca!==null&&ca.tag===0&&(gn&6)===0&&Ya();var p=gn;gn|=1;var k=qs.transition,M=Pe;try{if(qs.transition=null,Pe=1,c)return c()}finally{Pe=M,qs.transition=k,gn=p,(gn&6)===0&&So()}}function gh(){Ts=Ka.current,Bn(Ka)}function da(c,p){c.finishedWork=null,c.finishedLanes=0;var k=c.timeoutHandle;if(k!==-1&&(c.timeoutHandle=-1,_g(k)),ar!==null)for(k=ar.return;k!==null;){var M=k;switch(md(M),M.tag){case 1:M=M.type.childContextTypes,M!=null&&Fc();break;case 3:sa(),Bn(hs),Bn(Jr),Rd();break;case 5:$d(M);break;case 4:sa();break;case 13:Bn(Yn);break;case 19:Bn(Yn);break;case 10:jd(M.type._context);break;case 22:case 23:gh()}k=k.return}if(fr=c,ar=c=Mo(c.current,null),jr=Ts=p,br=0,ql=null,ch=au=la=0,vs=lu=null,Wa!==null){for(p=0;p<Wa.length;p++)if(k=Wa[p],M=k.interleaved,M!==null){k.interleaved=null;var F=M.next,K=k.pending;if(K!==null){var de=K.next;K.next=F,M.next=de}k.pending=M}Wa=null}return c}function $p(c,p){do{var k=ar;try{if(Cd(),Md.current=tu,Pd){for(var M=Xn.memoizedState;M!==null;){var F=M.queue;F!==null&&(F.pending=null),M=M.next}Pd=!1}if(ia=0,vr=dr=Xn=null,oa=!1,Eo=0,ou.current=null,k===null||k.return===null){br=1,ql=p,ar=null;break}e:{var K=c,de=k.return,_e=k,$e=p;if(p=jr,_e.flags|=32768,$e!==null&&typeof $e=="object"&&typeof $e.then=="function"){var qe=$e,at=_e,ct=at.tag;if((at.mode&1)===0&&(ct===0||ct===11||ct===15)){var ot=at.alternate;ot?(at.updateQueue=ot.updateQueue,at.memoizedState=ot.memoizedState,at.lanes=ot.lanes):(at.updateQueue=null,at.memoizedState=null)}var jt=Dg(de);if(jt!==null){jt.flags&=-257,Zr(jt,de,_e,K,p),jt.mode&1&&cp(K,qe,p),p=jt,$e=qe;var Pt=p.updateQueue;if(Pt===null){var Dt=new Set;Dt.add($e),p.updateQueue=Dt}else Pt.add($e);break e}else{if((p&1)===0){cp(K,qe,p),xh();break e}$e=Error(r(426))}}else if(Kn&&_e.mode&1){var Pn=Dg(de);if(Pn!==null){(Pn.flags&65536)===0&&(Pn.flags|=256),Zr(Pn,de,_e,K,p),wd(Va($e,_e));break e}}K=$e=Va($e,_e),br!==4&&(br=2),lu===null?lu=[K]:lu.push(K),K=de;do{switch(K.tag){case 3:K.flags|=65536,p&=-p,K.lanes|=p;var Ue=ap(K,$e,p);jg(K,Ue);break e;case 1:_e=$e;var Ie=K.type,Ve=K.stateNode;if((K.flags&128)===0&&(typeof Ie.getDerivedStateFromError=="function"||Ve!==null&&typeof Ve.componentDidCatch=="function"&&($o===null||!$o.has(Ve)))){K.flags|=65536,p&=-p,K.lanes|=p;var ht=lp(K,_e,p);jg(K,ht);break e}}K=K.return}while(K!==null)}Kl(k)}catch(Ft){p=Ft,ar===k&&k!==null&&(ar=k=k.return);continue}break}while(!0)}function qg(){var c=iu.current;return iu.current=tu,c===null?tu:c}function xh(){(br===0||br===3||br===2)&&(br=4),fr===null||(la&268435455)===0&&(au&268435455)===0||Ro(fr,jr)}function fu(c,p){var k=gn;gn|=2;var M=qg();(fr!==c||jr!==p)&&(To=null,da(c,p));do try{Vg();break}catch(F){$p(c,F)}while(!0);if(Cd(),gn=k,iu.current=M,ar!==null)throw Error(r(261));return fr=null,jr=0,br}function Vg(){for(;ar!==null;)Ap(ar)}function xv(){for(;ar!==null&&!Aa();)Ap(ar)}function Ap(c){var p=Ip(c.alternate,c,Ts);c.memoizedProps=c.pendingProps,p===null?Kl(c):ar=p,ou.current=null}function Kl(c){var p=c;do{var k=p.alternate;if(c=p.return,(p.flags&32768)===0){if(k=zg(k,p,Ts),k!==null){ar=k;return}}else{if(k=Bg(k,p),k!==null){k.flags&=32767,ar=k;return}if(c!==null)c.flags|=32768,c.subtreeFlags=0,c.deletions=null;else{br=6,ar=null;return}}if(p=p.sibling,p!==null){ar=p;return}ar=p=c}while(p!==null);br===0&&(br=5)}function ha(c,p,k){var M=Pe,F=qs.transition;try{qs.transition=null,Pe=1,Rp(c,p,k,M)}finally{qs.transition=F,Pe=M}return null}function Rp(c,p,k,M){do Ya();while(ca!==null);if((gn&6)!==0)throw Error(r(327));k=c.finishedWork;var F=c.finishedLanes;if(k===null)return null;if(c.finishedWork=null,c.finishedLanes=0,k===c.current)throw Error(r(177));c.callbackNode=null,c.callbackPriority=0;var K=k.lanes|k.childLanes;if(ft(c,K),c===fr&&(ar=fr=null,jr=0),(k.subtreeFlags&2064)===0&&(k.flags&2064)===0||uu||(uu=!0,Pp(ti,function(){return Ya(),null})),K=(k.flags&15990)!==0,(k.subtreeFlags&15990)!==0||K){K=qs.transition,qs.transition=null;var de=Pe;Pe=1;var _e=gn;gn|=4,ou.current=null,Ug(c,k),oh(k,c),xg(ld),bo=!!ad,ld=ad=null,c.current=k,Sp(k),Ra(),gn=_e,Pe=de,qs.transition=K}else c.current=k;if(uu&&(uu=!1,ca=c,du=F),K=c.pendingLanes,K===0&&($o=null),Bt(k.stateNode),bs(c,kn()),p!==null)for(M=c.onRecoverableError,k=0;k<p.length;k++)F=p[k],M(F.value,{componentStack:F.stack,digest:F.digest});if(cu)throw cu=!1,c=dh,dh=null,c;return(du&1)!==0&&c.tag!==0&&Ya(),K=c.pendingLanes,(K&1)!==0?c===hh?Vl++:(Vl=0,hh=c):Vl=0,So(),null}function Ya(){if(ca!==null){var c=Qe(du),p=qs.transition,k=Pe;try{if(qs.transition=null,Pe=16>c?16:c,ca===null)var M=!1;else{if(c=ca,ca=null,du=0,(gn&6)!==0)throw Error(r(331));var F=gn;for(gn|=4,It=c.current;It!==null;){var K=It,de=K.child;if((It.flags&16)!==0){var _e=K.deletions;if(_e!==null){for(var $e=0;$e<_e.length;$e++){var qe=_e[$e];for(It=qe;It!==null;){var at=It;switch(at.tag){case 0:case 11:case 15:Hl(8,at,K)}var ct=at.child;if(ct!==null)ct.return=at,It=ct;else for(;It!==null;){at=It;var ot=at.sibling,jt=at.return;if(wp(at),at===qe){It=null;break}if(ot!==null){ot.return=jt,It=ot;break}It=jt}}}var Pt=K.alternate;if(Pt!==null){var Dt=Pt.child;if(Dt!==null){Pt.child=null;do{var Pn=Dt.sibling;Dt.sibling=null,Dt=Pn}while(Dt!==null)}}It=K}}if((K.subtreeFlags&2064)!==0&&de!==null)de.return=K,It=de;else e:for(;It!==null;){if(K=It,(K.flags&2048)!==0)switch(K.tag){case 0:case 11:case 15:Hl(9,K,K.return)}var Ue=K.sibling;if(Ue!==null){Ue.return=K.return,It=Ue;break e}It=K.return}}var Ie=c.current;for(It=Ie;It!==null;){de=It;var Ve=de.child;if((de.subtreeFlags&2064)!==0&&Ve!==null)Ve.return=de,It=Ve;else e:for(de=Ie;It!==null;){if(_e=It,(_e.flags&2048)!==0)try{switch(_e.tag){case 0:case 11:case 15:nh(9,_e)}}catch(Ft){Jn(_e,_e.return,Ft)}if(_e===de){It=null;break e}var ht=_e.sibling;if(ht!==null){ht.return=_e.return,It=ht;break e}It=_e.return}}if(gn=F,So(),gr&&typeof gr.onPostCommitFiberRoot=="function")try{gr.onPostCommitFiberRoot(cs,c)}catch{}M=!0}return M}finally{Pe=k,qs.transition=p}}return!1}function Mp(c,p,k){p=Va(k,p),p=ap(c,p,1),c=jo(c,p,1),p=es(),c!==null&&(qr(c,1,p),bs(c,p))}function Jn(c,p,k){if(c.tag===3)Mp(c,c,k);else for(;p!==null;){if(p.tag===3){Mp(p,c,k);break}else if(p.tag===1){var M=p.stateNode;if(typeof p.type.getDerivedStateFromError=="function"||typeof M.componentDidCatch=="function"&&($o===null||!$o.has(M))){c=Va(k,c),c=lp(p,c,1),p=jo(p,c,1),c=es(),p!==null&&(qr(p,1,c),bs(p,c));break}}p=p.return}}function Gg(c,p,k){var M=c.pingCache;M!==null&&M.delete(p),p=es(),c.pingedLanes|=c.suspendedLanes&k,fr===c&&(jr&k)===k&&(br===4||br===3&&(jr&130023424)===jr&&500>kn()-uh?da(c,0):ch|=k),bs(c,p)}function Kg(c,p){p===0&&((c.mode&1)===0?p=1:(p=Wr,Wr<<=1,(Wr&130023424)===0&&(Wr=4194304)));var k=es();c=Yi(c,p),c!==null&&(qr(c,p,k),bs(c,k))}function Xg(c){var p=c.memoizedState,k=0;p!==null&&(k=p.retryLane),Kg(c,k)}function Yg(c,p){var k=0;switch(c.tag){case 13:var M=c.stateNode,F=c.memoizedState;F!==null&&(k=F.retryLane);break;case 19:M=c.stateNode;break;default:throw Error(r(314))}M!==null&&M.delete(p),Kg(c,k)}var Ip;Ip=function(c,p,k){if(c!==null)if(c.memoizedProps!==p.pendingProps||hs.current)ys=!0;else{if((c.lanes&k)===0&&(p.flags&128)===0)return ys=!1,gv(c,p,k);ys=(c.flags&131072)!==0}else ys=!1,Kn&&(p.flags&1048576)!==0&&Zo(p,qc,p.index);switch(p.lanes=0,p.tag){case 2:var M=p.type;ru(c,p),c=p.pendingProps;var F=Qr(p,Jr.current);Ha(p,k),F=Od(null,p,M,c,F,k);var K=Ld();return p.flags|=1,typeof F=="object"&&F!==null&&typeof F.render=="function"&&F.$$typeof===void 0?(p.tag=1,p.memoizedState=null,p.updateQueue=null,fs(M)?(K=!0,Uc(p)):K=!1,p.memoizedState=F.state!==null&&F.state!==void 0?F.state:null,Xc(p),F.updater=Qi,p.stateNode=F,F._reactInternals=p,Ud(p,M,c,k),p=Vd(null,p,M,!0,K,k)):(p.tag=0,Kn&&K&&ur(p),Or(null,p,F,k),p=p.child),p;case 16:M=p.elementType;e:{switch(ru(c,p),c=p.pendingProps,F=M._init,M=F(M._payload),p.type=M,F=p.tag=Jg(M),c=hr(M,c),F){case 0:p=qd(null,p,M,c,k);break e;case 1:p=pp(null,p,M,c,k);break e;case 11:p=up(null,p,M,c,k);break e;case 14:p=Fl(null,p,M,hr(M.type,c),k);break e}throw Error(r(306,M,""))}return p;case 0:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),qd(c,p,M,F,k);case 1:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),pp(c,p,M,F,k);case 3:e:{if(Gd(p),c===null)throw Error(r(387));M=p.pendingProps,K=p.memoizedState,F=K.element,Nd(c,p),Yc(p,M,null,k);var de=p.memoizedState;if(M=de.element,K.isDehydrated)if(K={element:M,isDehydrated:!1,cache:de.cache,pendingSuspenseBoundaries:de.pendingSuspenseBoundaries,transitions:de.transitions},p.updateQueue.baseState=K,p.memoizedState=K,p.flags&256){F=Va(Error(r(423)),p),p=mp(c,p,M,k,F);break e}else if(M!==F){F=Va(Error(r(424)),p),p=mp(c,p,M,k,F);break e}else for(Ns=_o(p.stateNode.containerInfo.firstChild),gs=p,Kn=!0,xs=null,k=kd(p,null,M,k),p.child=k;k;)k.flags=k.flags&-3|4096,k=k.sibling;else{if(ea(),M===F){p=Zi(c,p,k);break e}Or(c,p,M,k)}p=p.child}return p;case 5:return Lf(p),c===null&&vd(p),M=p.type,F=p.pendingProps,K=c!==null?c.memoizedProps:null,de=F.children,cd(M,F)?de=null:K!==null&&cd(M,K)&&(p.flags|=32),fp(c,p),Or(c,p,de,k),p.child;case 6:return c===null&&vd(p),null;case 13:return gp(c,p,k);case 4:return Td(p,p.stateNode.containerInfo),M=p.pendingProps,c===null?p.child=Ua(p,null,M,k):Or(c,p,M,k),p.child;case 11:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),up(c,p,M,F,k);case 7:return Or(c,p,p.pendingProps,k),p.child;case 8:return Or(c,p,p.pendingProps.children,k),p.child;case 12:return Or(c,p,p.pendingProps.children,k),p.child;case 10:e:{if(M=p.type._context,F=p.pendingProps,K=p.memoizedProps,de=F.value,In(ta,M._currentValue),M._currentValue=de,K!==null)if(ai(K.value,de)){if(K.children===F.children&&!hs.current){p=Zi(c,p,k);break e}}else for(K=p.child,K!==null&&(K.return=p);K!==null;){var _e=K.dependencies;if(_e!==null){de=K.child;for(var $e=_e.firstContext;$e!==null;){if($e.context===M){if(K.tag===1){$e=Ji(-1,k&-k),$e.tag=2;var qe=K.updateQueue;if(qe!==null){qe=qe.shared;var at=qe.pending;at===null?$e.next=$e:($e.next=at.next,at.next=$e),qe.pending=$e}}K.lanes|=k,$e=K.alternate,$e!==null&&($e.lanes|=k),Of(K.return,k,p),_e.lanes|=k;break}$e=$e.next}}else if(K.tag===10)de=K.type===p.type?null:K.child;else if(K.tag===18){if(de=K.return,de===null)throw Error(r(341));de.lanes|=k,_e=de.alternate,_e!==null&&(_e.lanes|=k),Of(de,k,p),de=K.sibling}else de=K.child;if(de!==null)de.return=K;else for(de=K;de!==null;){if(de===p){de=null;break}if(K=de.sibling,K!==null){K.return=de.return,de=K;break}de=de.return}K=de}Or(c,p,F.children,k),p=p.child}return p;case 9:return F=p.type,M=p.pendingProps.children,Ha(p,k),F=Us(F),M=M(F),p.flags|=1,Or(c,p,M,k),p.child;case 14:return M=p.type,F=hr(M,p.pendingProps),F=hr(M.type,F),Fl(c,p,M,F,k);case 15:return dp(c,p,p.type,p.pendingProps,k);case 17:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),ru(c,p),p.tag=1,fs(M)?(c=!0,Uc(p)):c=!1,Ha(p,k),ip(p,M,F),Ud(p,M,F,k),Vd(null,p,M,!0,c,k);case 19:return Jd(c,p,k);case 22:return hp(c,p,k)}throw Error(r(156,p.tag))};function Pp(c,p){return Go(c,p)}function yv(c,p,k,M){this.tag=c,this.key=k,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=p,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=M,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function $s(c,p,k,M){return new yv(c,p,k,M)}function yh(c){return c=c.prototype,!(!c||!c.isReactComponent)}function Jg(c){if(typeof c=="function")return yh(c)?1:0;if(c!=null){if(c=c.$$typeof,c===Y)return 11;if(c===te)return 14}return 2}function Mo(c,p){var k=c.alternate;return k===null?(k=$s(c.tag,p,c.key,c.mode),k.elementType=c.elementType,k.type=c.type,k.stateNode=c.stateNode,k.alternate=c,c.alternate=k):(k.pendingProps=p,k.type=c.type,k.flags=0,k.subtreeFlags=0,k.deletions=null),k.flags=c.flags&14680064,k.childLanes=c.childLanes,k.lanes=c.lanes,k.child=c.child,k.memoizedProps=c.memoizedProps,k.memoizedState=c.memoizedState,k.updateQueue=c.updateQueue,p=c.dependencies,k.dependencies=p===null?null:{lanes:p.lanes,firstContext:p.firstContext},k.sibling=c.sibling,k.index=c.index,k.ref=c.ref,k}function pu(c,p,k,M,F,K){var de=2;if(M=c,typeof c=="function")yh(c)&&(de=1);else if(typeof c=="string")de=5;else e:switch(c){case O:return Ja(k.children,F,K,p);case I:de=8,F|=8;break;case z:return c=$s(12,k,p,F|2),c.elementType=z,c.lanes=K,c;case V:return c=$s(13,k,p,F),c.elementType=V,c.lanes=K,c;case H:return c=$s(19,k,p,F),c.elementType=H,c.lanes=K,c;case oe:return mu(k,F,K,p);default:if(typeof c=="object"&&c!==null)switch(c.$$typeof){case U:de=10;break e;case W:de=9;break e;case Y:de=11;break e;case te:de=14;break e;case ae:de=16,M=null;break e}throw Error(r(130,c==null?c:typeof c,""))}return p=$s(de,k,p,F),p.elementType=c,p.type=M,p.lanes=K,p}function Ja(c,p,k,M){return c=$s(7,c,M,p),c.lanes=k,c}function mu(c,p,k,M){return c=$s(22,c,M,p),c.elementType=oe,c.lanes=k,c.stateNode={isHidden:!1},c}function vh(c,p,k){return c=$s(6,c,null,p),c.lanes=k,c}function bh(c,p,k){return p=$s(4,c.children!==null?c.children:[],c.key,p),p.lanes=k,p.stateNode={containerInfo:c.containerInfo,pendingChildren:null,implementation:c.implementation},p}function vv(c,p,k,M,F){this.tag=p,this.containerInfo=c,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ke(0),this.expirationTimes=Ke(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ke(0),this.identifierPrefix=M,this.onRecoverableError=F,this.mutableSourceEagerHydrationData=null}function wh(c,p,k,M,F,K,de,_e,$e){return c=new vv(c,p,k,_e,$e),p===1?(p=1,K===!0&&(p|=8)):p=0,K=$s(3,null,null,p),c.current=K,K.stateNode=c,K.memoizedState={element:M,isDehydrated:k,cache:null,transitions:null,pendingSuspenseBoundaries:null},Xc(K),c}function bv(c,p,k){var M=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:R,key:M==null?null:""+M,children:c,containerInfo:p,implementation:k}}function Dp(c){if(!c)return ko;c=c._reactInternals;e:{if(Ct(c)!==c||c.tag!==1)throw Error(r(170));var p=c;do{switch(p.tag){case 3:p=p.stateNode.context;break e;case 1:if(fs(p.type)){p=p.stateNode.__reactInternalMemoizedMergedChildContext;break e}}p=p.return}while(p!==null);throw Error(r(171))}if(c.tag===1){var k=c.type;if(fs(k))return Rf(c,k,p)}return p}function Qg(c,p,k,M,F,K,de,_e,$e){return c=wh(k,M,!0,c,F,K,de,_e,$e),c.context=Dp(null),k=c.current,M=es(),F=Ao(k),K=Ji(M,F),K.callback=p??null,jo(k,K,F),c.current.lanes=F,qr(c,F,M),bs(c,M),c}function gu(c,p,k,M){var F=p.current,K=es(),de=Ao(F);return k=Dp(k),p.context===null?p.context=k:p.pendingContext=k,p=Ji(K,de),p.payload={element:c},M=M===void 0?null:M,M!==null&&(p.callback=M),c=jo(F,p,de),c!==null&&(hi(c,F,de,K),Ol(c,F,de)),de}function xu(c){if(c=c.current,!c.child)return null;switch(c.child.tag){case 5:return c.child.stateNode;default:return c.child.stateNode}}function Op(c,p){if(c=c.memoizedState,c!==null&&c.dehydrated!==null){var k=c.retryLane;c.retryLane=k!==0&&k<p?k:p}}function _h(c,p){Op(c,p),(c=c.alternate)&&Op(c,p)}function Zg(){return null}var ex=typeof reportError=="function"?reportError:function(c){console.error(c)};function kh(c){this._internalRoot=c}Qa.prototype.render=kh.prototype.render=function(c){var p=this._internalRoot;if(p===null)throw Error(r(409));gu(c,p,null,null)},Qa.prototype.unmount=kh.prototype.unmount=function(){var c=this._internalRoot;if(c!==null){this._internalRoot=null;var p=c.containerInfo;ua(function(){gu(null,c,null,null)}),p[Ri]=null}};function Qa(c){this._internalRoot=c}Qa.prototype.unstable_scheduleHydration=function(c){if(c){var p=$n();c={blockedOn:null,target:c,priority:p};for(var k=0;k<ni.length&&p!==0&&p<ni[k].priority;k++);ni.splice(k,0,c),k===0&&bl(c)}};function Sh(c){return!(!c||c.nodeType!==1&&c.nodeType!==9&&c.nodeType!==11)}function yu(c){return!(!c||c.nodeType!==1&&c.nodeType!==9&&c.nodeType!==11&&(c.nodeType!==8||c.nodeValue!==" react-mount-point-unstable "))}function tx(){}function nx(c,p,k,M,F){if(F){if(typeof M=="function"){var K=M;M=function(){var qe=xu(de);K.call(qe)}}var de=Qg(p,M,c,0,null,!1,!1,"",tx);return c._reactRootContainer=de,c[Ri]=de.current,Rl(c.nodeType===8?c.parentNode:c),ua(),de}for(;F=c.lastChild;)c.removeChild(F);if(typeof M=="function"){var _e=M;M=function(){var qe=xu($e);_e.call(qe)}}var $e=wh(c,0,!1,null,null,!1,!1,"",tx);return c._reactRootContainer=$e,c[Ri]=$e.current,Rl(c.nodeType===8?c.parentNode:c),ua(function(){gu(p,$e,k,M)}),$e}function Xl(c,p,k,M,F){var K=k._reactRootContainer;if(K){var de=K;if(typeof F=="function"){var _e=F;F=function(){var $e=xu(de);_e.call($e)}}gu(p,de,c,F)}else de=nx(k,p,c,F,M);return xu(de)}Et=function(c){switch(c.tag){case 3:var p=c.stateNode;if(p.current.memoizedState.isDehydrated){var k=Ps(p.pendingLanes);k!==0&&(be(p,k|1),bs(p,kn()),(gn&6)===0&&(Xa=kn()+500,So()))}break;case 13:ua(function(){var M=Yi(c,1);if(M!==null){var F=es();hi(M,c,1,F)}}),_h(c,1)}},en=function(c){if(c.tag===13){var p=Yi(c,134217728);if(p!==null){var k=es();hi(p,c,134217728,k)}_h(c,134217728)}},ln=function(c){if(c.tag===13){var p=Ao(c),k=Yi(c,p);if(k!==null){var M=es();hi(k,c,p,M)}_h(c,p)}},$n=function(){return Pe},En=function(c,p){var k=Pe;try{return Pe=c,p()}finally{Pe=k}},bi=function(c,p,k){switch(p){case"input":if(st(c,k),p=k.name,k.type==="radio"&&p!=null){for(k=c;k.parentNode;)k=k.parentNode;for(k=k.querySelectorAll("input[name="+JSON.stringify(""+p)+'][type="radio"]'),p=0;p<k.length;p++){var M=k[p];if(M!==c&&M.form===c.form){var F=Bc(M);if(!F)throw Error(r(90));lt(M),st(M,F)}}}break;case"textarea":On(c,k);break;case"select":p=k.value,p!=null&&yt(c,!!k.multiple,p,!1)}},Is=mh,Ar=ua;var Lp={usingClientEntryPoint:!1,Events:[Pl,Oa,Bc,wi,_i,mh]},fi={findFiberByHostInstance:Jo,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},rx={bundleType:fi.bundleType,version:fi.version,rendererPackageName:fi.rendererPackageName,rendererConfig:fi.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:N.ReactCurrentDispatcher,findHostInstanceByFiber:function(c){return c=po(c),c===null?null:c.stateNode},findFiberByHostInstance:fi.findFiberByHostInstance||Zg,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Yl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Yl.isDisabled&&Yl.supportsFiber)try{cs=Yl.inject(rx),gr=Yl}catch{}}return pi.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Lp,pi.createPortal=function(c,p){var k=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Sh(p))throw Error(r(200));return bv(c,p,null,k)},pi.createRoot=function(c,p){if(!Sh(c))throw Error(r(299));var k=!1,M="",F=ex;return p!=null&&(p.unstable_strictMode===!0&&(k=!0),p.identifierPrefix!==void 0&&(M=p.identifierPrefix),p.onRecoverableError!==void 0&&(F=p.onRecoverableError)),p=wh(c,1,!1,null,null,k,!1,M,F),c[Ri]=p.current,Rl(c.nodeType===8?c.parentNode:c),new kh(p)},pi.findDOMNode=function(c){if(c==null)return null;if(c.nodeType===1)return c;var p=c._reactInternals;if(p===void 0)throw typeof c.render=="function"?Error(r(188)):(c=Object.keys(c).join(","),Error(r(268,c)));return c=po(p),c=c===null?null:c.stateNode,c},pi.flushSync=function(c){return ua(c)},pi.hydrate=function(c,p,k){if(!yu(p))throw Error(r(200));return Xl(null,c,p,!0,k)},pi.hydrateRoot=function(c,p,k){if(!Sh(c))throw Error(r(405));var M=k!=null&&k.hydratedSources||null,F=!1,K="",de=ex;if(k!=null&&(k.unstable_strictMode===!0&&(F=!0),k.identifierPrefix!==void 0&&(K=k.identifierPrefix),k.onRecoverableError!==void 0&&(de=k.onRecoverableError)),p=Qg(p,null,c,1,k??null,F,!1,K,de),c[Ri]=p.current,Rl(c),M)for(c=0;c<M.length;c++)k=M[c],F=k._getVersion,F=F(k._source),p.mutableSourceEagerHydrationData==null?p.mutableSourceEagerHydrationData=[k,F]:p.mutableSourceEagerHydrationData.push(k,F);return new Qa(p)},pi.render=function(c,p,k){if(!yu(p))throw Error(r(200));return Xl(null,c,p,!1,k)},pi.unmountComponentAtNode=function(c){if(!yu(c))throw Error(r(40));return c._reactRootContainer?(ua(function(){Xl(null,null,c,!1,function(){c._reactRootContainer=null,c[Ri]=null})}),!0):!1},pi.unstable_batchedUpdates=mh,pi.unstable_renderSubtreeIntoContainer=function(c,p,k,M){if(!yu(k))throw Error(r(200));if(c==null||c._reactInternals===void 0)throw Error(r(38));return Xl(c,p,k,!1,M)},pi.version="18.3.1-next-f1338f8080-20240426",pi}var n_;function _2(){if(n_)return Cv.exports;n_=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(n){console.error(n)}}return e(),Cv.exports=jN(),Cv.exports}var r_;function EN(){if(r_)return ix;r_=1;var e=_2();return ix.createRoot=e.createRoot,ix.hydrateRoot=e.hydrateRoot,ix}var NN=EN();const TN=Gy(NN);var L=Xw();const co=Gy(L),s_=e=>{let n;const r=new Set,i=(m,x)=>{const g=typeof m=="function"?m(n):m;if(!Object.is(g,n)){const v=n;n=x??(typeof g!="object"||g===null)?g:Object.assign({},n,g),r.forEach(S=>S(n,v))}},o=()=>n,u={setState:i,getState:o,getInitialState:()=>h,subscribe:m=>(r.add(m),()=>r.delete(m))},h=n=e(i,o,u);return u},$N=(e=>e?s_(e):s_),AN=e=>e;function RN(e,n=AN){const r=co.useSyncExternalStore(e.subscribe,co.useCallback(()=>n(e.getState()),[e,n]),co.useCallback(()=>n(e.getInitialState()),[e,n]));return co.useDebugValue(r),r}const i_=e=>{const n=$N(e),r=i=>RN(n,i);return Object.assign(r,n),r},cr=(e=>e?i_(e):i_);function Ho(e){return"'"+e.replace(/'/g,"'\\''")+"'"}const Nv=({sessionId:e})=>`claude --dangerously-skip-permissions --session-id ${Ho(e)}`,o_=({sessionId:e})=>`claude --session-id ${Ho(e)}`,MN=()=>"claude --resume",k2=[{id:"sm-dangerous",label:"Session Manager (skip perms)",description:"claude --dangerously-skip-permissions in this project",category:"build",cwd:"app-cwd",command:Nv},{id:"sm-safe",label:"Session Manager (safe)",description:"claude with normal permission prompts in this project",category:"build",cwd:"app-cwd",command:o_},{id:"home-dangerous",label:"Home (skip perms)",description:"claude --dangerously-skip-permissions in ~",category:"build",cwd:"home",command:Nv},{id:"pick-dangerous",label:"Pick directory (skip perms)…",description:"Choose a folder, launch claude --dangerously-skip-permissions",category:"build",cwd:"pick",command:Nv},{id:"pick-safe",label:"Pick directory (safe)…",description:"Choose a folder, launch claude with normal prompts",category:"build",cwd:"pick",command:o_},{id:"pick-resume",label:"Pick directory + resume…",description:"Choose a folder, then pick a past session to resume",category:"build",cwd:"pick",command:MN},{id:"pick-shell",label:"Pick directory (shell only)…",description:"Bare interactive shell, no claude auto-launch",category:"build",cwd:"pick",command:null}];let to=null;async function IN(){if(to)return to;try{const e=await window.api.app.engageRulesPath();if(!e)return to=[],to;const n=await window.api.config.readJson(e);if(!n.exists||n.parseError||!n.data)return to=[],to;const r=n.data;if(!r.presets||!Array.isArray(r.presets))return to=[],to;const i=r.projectPath;return to=r.presets.map(o=>({id:o.id,label:o.label,description:o.description,category:"engage",cwd:i,platform:o.platform,pipeline:o.pipeline,rules:o.rules,command:()=>`cd ${Ho(i)} && ${o.cliEntry}`})),to}catch(e){return console.warn("[presets] Failed to load engage presets:",e),to=[],to}}async function S2(e){const n=k2.find(i=>i.id===e);return n||((await IN()).find(i=>i.id===e)??null)}async function a_(e){return e.cwd==="app-cwd"?window.api.app.cwd():e.cwd==="home"?window.api.app.homeDir():e.cwd==="pick"?window.api.app.pickDirectory():e.cwd}function C2(e,n){return e.command?e.command(n):null}const Yw=["opus","sonnet","haiku"],j2="sm.rawSessionModel",PN="opus";function DN(e){return Yw.includes(e)}function ON(){try{const e=localStorage.getItem(j2);if(e&&DN(e))return e}catch{}return PN}let zh=ON();const Pb=new Set;function E2(){return zh}function LN(e){if(e!==zh){zh=e;try{localStorage.setItem(j2,e)}catch{}Pb.forEach(n=>n(e))}}function zN(){const[e,n]=L.useState(zh);L.useEffect(()=>{const i=o=>n(o);return Pb.add(i),zh!==e&&n(zh),()=>{Pb.delete(i)}},[]);const r=L.useCallback(i=>LN(i),[]);return{model:e,setModel:r}}async function N2(e,n){const r=await window.api.transcripts.pathFor(e,n);return window.api.config.exists(r)}const BN=5,l_=100,FN=5e3,Db=new Map;function c_(e){const n=Db.get(e);n!==void 0&&(clearTimeout(n),Db.delete(e))}function UN(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`t-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}const Eu=cr((e,n)=>({toasts:[],history:[],unreadCount:0,show:(r,i)=>{const o=UN(),l=Date.now();e(u=>{const h=[...u.toasts,{id:o,kind:r,message:i,createdAt:l}];for(;h.length>BN;){const g=h.shift();g&&c_(g.id)}const x=[{id:o,kind:r,message:i,createdAt:l,read:!1},...u.history];return x.length>l_&&(x.length=l_),{toasts:h,history:x,unreadCount:u.unreadCount+1}});const d=setTimeout(()=>n().dismiss(o),FN);return Db.set(o,d),o},dismiss:r=>{c_(r),e(i=>({toasts:i.toasts.filter(o=>o.id!==r)}))},markAllRead:()=>{e(r=>r.unreadCount===0?r:{history:r.history.map(i=>i.read?i:{...i,read:!0}),unreadCount:0})},clearHistory:()=>{e({history:[],unreadCount:0})},dismissHistoryEntry:r=>{e(i=>{const o=i.history.filter(d=>d.id!==r);if(o.length===i.history.length)return i;const l=i.history.find(d=>d.id===r&&!d.read);return{history:o,unreadCount:l?Math.max(0,i.unreadCount-1):i.unreadCount}})}})),Le={info:e=>Eu.getState().show("info",e),warn:e=>Eu.getState().show("warn",e),error:e=>Eu.getState().show("error",e),fromOutcome:e=>Eu.getState().show(e.kind??(e.ok?"info":"warn"),e.message)},T2=Object.freeze(Object.defineProperty({__proto__:null,toast:Le,useToast:Eu},Symbol.toStringTag,{value:"Module"}));async function HN(e){var n,r;if(typeof window>"u"||typeof((r=(n=window.api)==null?void 0:n.chat)==null?void 0:r.classifyTicket)!="function")return"inline";try{return await window.api.chat.classifyTicket({text:e})==="develop"?"develop":"inline"}catch{return"inline"}}const Nu={turns:[],running:!1,queuedPosition:0,started:!1,stream:"",liveToolUses:[],queue:[],activeTicket:null,ticketHistory:[]},u_=20;function Jw(e,n){const r=[...e,n];return r.length>u_?r.slice(r.length-u_):r}let d_=0;function fl(){return d_+=1,`t${Date.now().toString(36)}-${d_}`}const gi=cr((e,n)=>({chats:{},hydratedTabs:{},get:r=>n().chats[r]??Nu,hydrate:async({tabId:r,cwd:i,sessionId:o})=>{var l,d,u;if(!n().hydratedTabs[r]&&(e({hydratedTabs:{...n().hydratedTabs,[r]:!0}}),!(typeof window>"u"||!((l=window.api)!=null&&l.exchanges))))try{const h=await window.api.exchanges.list({cwd:i,sessionId:o});if(!h.length)return;const m=[];for(const g of[...h].reverse()){const v=new Date(g.ts).getTime();m.push({id:fl(),role:"user",text:g.prompt,at:v}),m.push({id:fl(),role:"assistant",text:g.result,at:v})}const x=n().chats[r]??Nu;e({chats:{...n().chats,[r]:{...x,turns:[...m,...x.turns],started:!0}}})}catch(h){const m=h instanceof Error?h.message:String(h);(u=(d=window.api)==null?void 0:d.logs)==null||u.write("chat","warn",`exchange hydration failed for tab ${r}: ${m}`)}},send:({tabId:r,sessionId:i,cwd:o,prompt:l})=>{const d=l.trim();if(!d)return;const u=n().chats[r]??Nu;if(u.running){const h={id:crypto.randomUUID(),tabId:r,sessionId:i,cwd:o,text:d,status:"queued",createdAt:Date.now()};e({chats:{...n().chats,[r]:{...u,queue:[...u.queue,h]}}});return}$2({tabId:r,sessionId:i,cwd:o,text:d})},resetThread:r=>{e({chats:{...n().chats,[r]:{...Nu}}})},pushNotice:(r,i)=>{Qw(r,"",i)}}));function zo(e,n){const r=gi.getState().chats[e]??Nu;gi.setState({chats:{...gi.getState().chats,[e]:n(r)}})}function Gx(e,n,r={}){zo(e,i=>{const o=i.activeTicket?Jw(i.ticketHistory??[],{...i.activeTicket,status:"done",completedAt:Date.now()}):i.ticketHistory??[];return{...i,turns:[...i.turns,{...n,toolUses:i.liveToolUses}],running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:o,...r}}),A2(e)}function $2(e){const{tabId:n,sessionId:r,cwd:i,text:o,promptId:l}=e,d=gi.getState().chats[n]??Nu,u={id:fl(),role:"user",text:o,at:Date.now()};gi.setState({chats:{...gi.getState().chats,[n]:{...d,turns:[...d.turns,u],running:!0,queuedPosition:0,stream:""}}}),N2(i,r).catch(h=>{var x,g;const m=h instanceof Error?h.message:String(h);return(g=(x=window.api)==null?void 0:x.logs)==null||g.write("chat","warn",`transcript-exists check failed for tab ${n}: ${m}`),d.started}).then(h=>window.api.chat.run({tabId:n,sessionId:r,prompt:o,cwd:i,resume:h,promptId:l})).catch(h=>{const m=h instanceof Error?h.message:String(h);R2(n,r,m)})}function A2(e){const n=gi.getState().chats[e]??Nu;if(n.queue.length===0)return;const[r,...i]=n.queue;zo(e,o=>({...o,queue:i,running:!0,queuedPosition:0,activeTicket:r})),HN(r.text).then(o=>{if(o==="develop"){const d={...r,status:"dispatched-to-prd",completedAt:Date.now()};Qw(e,d.sessionId,`→ dispatched to /develop for PRD decomposition (ticket ${d.id})`),zo(e,u=>({...u,running:!1,queuedPosition:0,activeTicket:null,ticketHistory:Jw(u.ticketHistory??[],d)})),A2(e);return}const l={...r,status:"running",startedAt:Date.now()};zo(e,d=>({...d,activeTicket:l})),$2({tabId:l.tabId,sessionId:l.sessionId,cwd:l.cwd,text:l.text,promptId:l.id})})}function R2(e,n,r){zo(e,i=>i.activeTicket?{...i,activeTicket:null,ticketHistory:Jw(i.ticketHistory??[],{...i.activeTicket,status:"failed",completedAt:Date.now()})}:i),Gx(e,{id:fl(),role:"error",text:r,at:Date.now()}),Le.error(r)}function Qw(e,n,r){zo(e,i=>({...i,turns:[...i.turns,{id:fl(),role:"notice",text:r,at:Date.now()}]}))}var w2;typeof window<"u"&&((w2=window.api)!=null&&w2.chat)&&(window.api.chat.onQueued(({tabId:e,position:n})=>{zo(e,r=>({...r,running:!0,queuedPosition:n}))}),window.api.chat.onRunStarted(({tabId:e})=>{zo(e,n=>({...n,running:!0,started:!0,queuedPosition:0,stream:"",liveToolUses:[]}))}),window.api.chat.onOutput(({tabId:e,delta:n})=>{zo(e,r=>({...r,stream:r.stream+n}))}),window.api.chat.onToolUse(({tabId:e,id:n,kind:r,label:i})=>{zo(e,o=>({...o,liveToolUses:[...o.liveToolUses,{id:n,kind:r,label:i}]}))}),window.api.chat.onComplete(({tabId:e,finalMessage:n})=>{Gx(e,{id:fl(),role:"assistant",text:n,at:Date.now()})}),window.api.chat.onNeedsInput(({tabId:e,questions:n,answerBody:r})=>{if(r&&r.trim()){zo(e,i=>({...i,turns:[...i.turns,{id:fl(),role:"assistant",text:r,at:Date.now(),toolUses:i.liveToolUses}],liveToolUses:[]})),Gx(e,{id:fl(),role:"question",text:n.join(`
|
|
41
|
+
`+K.stack}return{value:c,source:p,stack:F,digest:null}}function Hd(c,p,k){return{value:c,source:null,stack:k??null,digest:p??null}}function Wd(c,p){try{console.error(p.value)}catch(k){setTimeout(function(){throw k})}}var Pg=typeof WeakMap=="function"?WeakMap:Map;function ap(c,p,k){k=Ji(-1,k),k.tag=3,k.payload={element:null};var M=p.value;return k.callback=function(){cu||(cu=!0,dh=M),Wd(c,p)},k}function lp(c,p,k){k=Ji(-1,k),k.tag=3;var M=c.type.getDerivedStateFromError;if(typeof M=="function"){var F=p.value;k.payload=function(){return M(F)},k.callback=function(){Wd(c,p)}}var K=c.stateNode;return K!==null&&typeof K.componentDidCatch=="function"&&(k.callback=function(){Wd(c,p),typeof M!="function"&&($o===null?$o=new Set([this]):$o.add(this));var de=p.stack;this.componentDidCatch(p.value,{componentStack:de!==null?de:""})}),k}function cp(c,p,k){var M=c.pingCache;if(M===null){M=c.pingCache=new Pg;var F=new Set;M.set(p,F)}else F=M.get(p),F===void 0&&(F=new Set,M.set(p,F));F.has(k)||(F.add(k),c=Gg.bind(null,c,p,k),p.then(c,c))}function Dg(c){do{var p;if((p=c.tag===13)&&(p=c.memoizedState,p=p!==null?p.dehydrated!==null:!0),p)return c;c=c.return}while(c!==null);return null}function Zr(c,p,k,M,F){return(c.mode&1)===0?(c===p?c.flags|=65536:(c.flags|=128,k.flags|=131072,k.flags&=-52805,k.tag===1&&(k.alternate===null?k.tag=17:(p=Ji(-1,1),p.tag=2,jo(k,p,1))),k.lanes|=1),c):(c.flags|=65536,c.lanes=F,c)}var Og=N.ReactCurrentOwner,ys=!1;function Or(c,p,k,M){p.child=c===null?kd(p,null,k,M):Ua(p,c.child,k,M)}function up(c,p,k,M,F){k=k.render;var K=p.ref;return Ha(p,F),M=Od(c,p,k,M,K,F),k=Ld(),c!==null&&!ys?(p.updateQueue=c.updateQueue,p.flags&=-2053,c.lanes&=~F,Zi(c,p,F)):(Kn&&k&&ur(p),p.flags|=1,Or(c,p,M,F),p.child)}function Fl(c,p,k,M,F){if(c===null){var K=k.type;return typeof K=="function"&&!yh(K)&&K.defaultProps===void 0&&k.compare===null&&k.defaultProps===void 0?(p.tag=15,p.type=K,dp(c,p,K,M,F)):(c=pu(k.type,null,M,p,p.mode,F),c.ref=p.ref,c.return=p,p.child=c)}if(K=c.child,(c.lanes&F)===0){var de=K.memoizedProps;if(k=k.compare,k=k!==null?k:Nl,k(de,M)&&c.ref===p.ref)return Zi(c,p,F)}return p.flags|=1,c=Mo(K,M),c.ref=p.ref,c.return=p,p.child=c}function dp(c,p,k,M,F){if(c!==null){var K=c.memoizedProps;if(Nl(K,M)&&c.ref===p.ref)if(ys=!1,p.pendingProps=M=K,(c.lanes&F)!==0)(c.flags&131072)!==0&&(ys=!0);else return p.lanes=c.lanes,Zi(c,p,F)}return qd(c,p,k,M,F)}function hp(c,p,k){var M=p.pendingProps,F=M.children,K=c!==null?c.memoizedState:null;if(M.mode==="hidden")if((p.mode&1)===0)p.memoizedState={baseLanes:0,cachePool:null,transitions:null},In(Ka,Ts),Ts|=k;else{if((k&1073741824)===0)return c=K!==null?K.baseLanes|k:k,p.lanes=p.childLanes=1073741824,p.memoizedState={baseLanes:c,cachePool:null,transitions:null},p.updateQueue=null,In(Ka,Ts),Ts|=c,null;p.memoizedState={baseLanes:0,cachePool:null,transitions:null},M=K!==null?K.baseLanes:k,In(Ka,Ts),Ts|=M}else K!==null?(M=K.baseLanes|k,p.memoizedState=null):M=k,In(Ka,Ts),Ts|=M;return Or(c,p,F,k),p.child}function fp(c,p){var k=p.ref;(c===null&&k!==null||c!==null&&c.ref!==k)&&(p.flags|=512,p.flags|=2097152)}function qd(c,p,k,M,F){var K=fs(k)?Qo:Jr.current;return K=Qr(p,K),Ha(p,F),k=Od(c,p,k,M,K,F),M=Ld(),c!==null&&!ys?(p.updateQueue=c.updateQueue,p.flags&=-2053,c.lanes&=~F,Zi(c,p,F)):(Kn&&M&&ur(p),p.flags|=1,Or(c,p,k,F),p.child)}function pp(c,p,k,M,F){if(fs(k)){var K=!0;Uc(p)}else K=!1;if(Ha(p,F),p.stateNode===null)ru(c,p),ip(p,k,M),Ud(p,k,M,F),M=!0;else if(c===null){var de=p.stateNode,_e=p.memoizedProps;de.props=_e;var $e=de.context,qe=k.contextType;typeof qe=="object"&&qe!==null?qe=Us(qe):(qe=fs(k)?Qo:Jr.current,qe=Qr(p,qe));var at=k.getDerivedStateFromProps,ct=typeof at=="function"||typeof de.getSnapshotBeforeUpdate=="function";ct||typeof de.UNSAFE_componentWillReceiveProps!="function"&&typeof de.componentWillReceiveProps!="function"||(_e!==M||$e!==qe)&&op(p,de,M,qe),Mi=!1;var ot=p.memoizedState;de.state=ot,Yc(p,M,de,F),$e=p.memoizedState,_e!==M||ot!==$e||hs.current||Mi?(typeof at=="function"&&(Pi(p,k,at,M),$e=p.memoizedState),(_e=Mi||aa(p,k,_e,M,ot,$e,qe))?(ct||typeof de.UNSAFE_componentWillMount!="function"&&typeof de.componentWillMount!="function"||(typeof de.componentWillMount=="function"&&de.componentWillMount(),typeof de.UNSAFE_componentWillMount=="function"&&de.UNSAFE_componentWillMount()),typeof de.componentDidMount=="function"&&(p.flags|=4194308)):(typeof de.componentDidMount=="function"&&(p.flags|=4194308),p.memoizedProps=M,p.memoizedState=$e),de.props=M,de.state=$e,de.context=qe,M=_e):(typeof de.componentDidMount=="function"&&(p.flags|=4194308),M=!1)}else{de=p.stateNode,Nd(c,p),_e=p.memoizedProps,qe=p.type===p.elementType?_e:hr(p.type,_e),de.props=qe,ct=p.pendingProps,ot=de.context,$e=k.contextType,typeof $e=="object"&&$e!==null?$e=Us($e):($e=fs(k)?Qo:Jr.current,$e=Qr(p,$e));var jt=k.getDerivedStateFromProps;(at=typeof jt=="function"||typeof de.getSnapshotBeforeUpdate=="function")||typeof de.UNSAFE_componentWillReceiveProps!="function"&&typeof de.componentWillReceiveProps!="function"||(_e!==ct||ot!==$e)&&op(p,de,M,$e),Mi=!1,ot=p.memoizedState,de.state=ot,Yc(p,M,de,F);var Pt=p.memoizedState;_e!==ct||ot!==Pt||hs.current||Mi?(typeof jt=="function"&&(Pi(p,k,jt,M),Pt=p.memoizedState),(qe=Mi||aa(p,k,qe,M,ot,Pt,$e)||!1)?(at||typeof de.UNSAFE_componentWillUpdate!="function"&&typeof de.componentWillUpdate!="function"||(typeof de.componentWillUpdate=="function"&&de.componentWillUpdate(M,Pt,$e),typeof de.UNSAFE_componentWillUpdate=="function"&&de.UNSAFE_componentWillUpdate(M,Pt,$e)),typeof de.componentDidUpdate=="function"&&(p.flags|=4),typeof de.getSnapshotBeforeUpdate=="function"&&(p.flags|=1024)):(typeof de.componentDidUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=4),typeof de.getSnapshotBeforeUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=1024),p.memoizedProps=M,p.memoizedState=Pt),de.props=M,de.state=Pt,de.context=$e,M=qe):(typeof de.componentDidUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=4),typeof de.getSnapshotBeforeUpdate!="function"||_e===c.memoizedProps&&ot===c.memoizedState||(p.flags|=1024),M=!1)}return Vd(c,p,k,M,K,F)}function Vd(c,p,k,M,F,K){fp(c,p);var de=(p.flags&128)!==0;if(!M&&!de)return F&&Mf(p,k,!1),Zi(c,p,K);M=p.stateNode,Og.current=p;var _e=de&&typeof k.getDerivedStateFromError!="function"?null:M.render();return p.flags|=1,c!==null&&de?(p.child=Ua(p,c.child,null,K),p.child=Ua(p,null,_e,K)):Or(c,p,_e,K),p.memoizedState=M.state,F&&Mf(p,k,!0),p.child}function Gd(c){var p=c.stateNode;p.pendingContext?Af(c,p.pendingContext,p.pendingContext!==p.context):p.context&&Af(c,p.context,!1),Td(c,p.containerInfo)}function mp(c,p,k,M,F){return ea(),wd(F),p.flags|=256,Or(c,p,k,M),p.child}var Kd={dehydrated:null,treeContext:null,retryLane:0};function Xd(c){return{baseLanes:c,cachePool:null,transitions:null}}function gp(c,p,k){var M=p.pendingProps,F=Yn.current,K=!1,de=(p.flags&128)!==0,_e;if((_e=de)||(_e=c!==null&&c.memoizedState===null?!1:(F&2)!==0),_e?(K=!0,p.flags&=-129):(c===null||c.memoizedState!==null)&&(F|=1),In(Yn,F&1),c===null)return vd(p),c=p.memoizedState,c!==null&&(c=c.dehydrated,c!==null)?((p.mode&1)===0?p.lanes=1:c.data==="$!"?p.lanes=8:p.lanes=1073741824,null):(de=M.children,c=M.fallback,K?(M=p.mode,K=p.child,de={mode:"hidden",children:de},(M&1)===0&&K!==null?(K.childLanes=0,K.pendingProps=de):K=mu(de,M,0,null),c=Ja(c,M,k,null),K.return=p,c.return=p,K.sibling=c,p.child=K,p.child.memoizedState=Xd(k),p.memoizedState=Kd,c):Ul(p,de));if(F=c.memoizedState,F!==null&&(_e=F.dehydrated,_e!==null))return Lg(c,p,de,M,_e,F,k);if(K){K=M.fallback,de=p.mode,F=c.child,_e=F.sibling;var $e={mode:"hidden",children:M.children};return(de&1)===0&&p.child!==F?(M=p.child,M.childLanes=0,M.pendingProps=$e,p.deletions=null):(M=Mo(F,$e),M.subtreeFlags=F.subtreeFlags&14680064),_e!==null?K=Mo(_e,K):(K=Ja(K,de,k,null),K.flags|=2),K.return=p,M.return=p,M.sibling=K,p.child=M,M=K,K=p.child,de=c.child.memoizedState,de=de===null?Xd(k):{baseLanes:de.baseLanes|k,cachePool:null,transitions:de.transitions},K.memoizedState=de,K.childLanes=c.childLanes&~k,p.memoizedState=Kd,M}return K=c.child,c=K.sibling,M=Mo(K,{mode:"visible",children:M.children}),(p.mode&1)===0&&(M.lanes=k),M.return=p,M.sibling=null,c!==null&&(k=p.deletions,k===null?(p.deletions=[c],p.flags|=16):k.push(c)),p.child=M,p.memoizedState=null,M}function Ul(c,p){return p=mu({mode:"visible",children:p},c.mode,0,null),p.return=c,c.child=p}function nu(c,p,k,M){return M!==null&&wd(M),Ua(p,c.child,null,k),c=Ul(p,p.pendingProps.children),c.flags|=2,p.memoizedState=null,c}function Lg(c,p,k,M,F,K,de){if(k)return p.flags&256?(p.flags&=-257,M=Hd(Error(r(422))),nu(c,p,de,M)):p.memoizedState!==null?(p.child=c.child,p.flags|=128,null):(K=M.fallback,F=p.mode,M=mu({mode:"visible",children:M.children},F,0,null),K=Ja(K,F,de,null),K.flags|=2,M.return=p,K.return=p,M.sibling=K,p.child=M,(p.mode&1)!==0&&Ua(p,c.child,null,de),p.child.memoizedState=Xd(de),p.memoizedState=Kd,K);if((p.mode&1)===0)return nu(c,p,de,null);if(F.data==="$!"){if(M=F.nextSibling&&F.nextSibling.dataset,M)var _e=M.dgst;return M=_e,K=Error(r(419)),M=Hd(K,M,void 0),nu(c,p,de,M)}if(_e=(de&c.childLanes)!==0,ys||_e){if(M=fr,M!==null){switch(de&-de){case 4:F=2;break;case 16:F=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:F=32;break;case 536870912:F=268435456;break;default:F=0}F=(F&(M.suspendedLanes|de))!==0?0:F,F!==0&&F!==K.retryLane&&(K.retryLane=F,Yi(c,F),fi(M,c,F,-1))}return xh(),M=Hd(Error(r(421))),nu(c,p,de,M)}return F.data==="$?"?(p.flags|=128,p.child=c.child,p=Xg.bind(null,c),F._reactRetry=p,null):(c=K.treeContext,Ns=_o(F.nextSibling),gs=p,Kn=!0,xs=null,c!==null&&(Bs[ci++]=ps,Bs[ci++]=ms,Bs[ci++]=Fs,ps=c.id,ms=c.overflow,Fs=p),p=Ul(p,M.children),p.flags|=4096,p)}function xp(c,p,k){c.lanes|=p;var M=c.alternate;M!==null&&(M.lanes|=p),Of(c.return,p,k)}function Yd(c,p,k,M,F){var K=c.memoizedState;K===null?c.memoizedState={isBackwards:p,rendering:null,renderingStartTime:0,last:M,tail:k,tailMode:F}:(K.isBackwards=p,K.rendering=null,K.renderingStartTime=0,K.last=M,K.tail=k,K.tailMode=F)}function Jd(c,p,k){var M=p.pendingProps,F=M.revealOrder,K=M.tail;if(Or(c,p,M.children,k),M=Yn.current,(M&2)!==0)M=M&1|2,p.flags|=128;else{if(c!==null&&(c.flags&128)!==0)e:for(c=p.child;c!==null;){if(c.tag===13)c.memoizedState!==null&&xp(c,k,p);else if(c.tag===19)xp(c,k,p);else if(c.child!==null){c.child.return=c,c=c.child;continue}if(c===p)break e;for(;c.sibling===null;){if(c.return===null||c.return===p)break e;c=c.return}c.sibling.return=c.return,c=c.sibling}M&=1}if(In(Yn,M),(p.mode&1)===0)p.memoizedState=null;else switch(F){case"forwards":for(k=p.child,F=null;k!==null;)c=k.alternate,c!==null&&Jc(c)===null&&(F=k),k=k.sibling;k=F,k===null?(F=p.child,p.child=null):(F=k.sibling,k.sibling=null),Yd(p,!1,F,k,K);break;case"backwards":for(k=null,F=p.child,p.child=null;F!==null;){if(c=F.alternate,c!==null&&Jc(c)===null){p.child=F;break}c=F.sibling,F.sibling=k,k=F,F=c}Yd(p,!0,k,null,K);break;case"together":Yd(p,!1,null,null,void 0);break;default:p.memoizedState=null}return p.child}function ru(c,p){(p.mode&1)===0&&c!==null&&(c.alternate=null,p.alternate=null,p.flags|=2)}function Zi(c,p,k){if(c!==null&&(p.dependencies=c.dependencies),la|=p.lanes,(k&p.childLanes)===0)return null;if(c!==null&&p.child!==c.child)throw Error(r(153));if(p.child!==null){for(c=p.child,k=Mo(c,c.pendingProps),p.child=k,k.return=p;c.sibling!==null;)c=c.sibling,k=k.sibling=Mo(c,c.pendingProps),k.return=p;k.sibling=null}return p.child}function gv(c,p,k){switch(p.tag){case 3:Gd(p),ea();break;case 5:Lf(p);break;case 1:fs(p.type)&&Uc(p);break;case 4:Td(p,p.stateNode.containerInfo);break;case 10:var M=p.type._context,F=p.memoizedProps.value;In(ta,M._currentValue),M._currentValue=F;break;case 13:if(M=p.memoizedState,M!==null)return M.dehydrated!==null?(In(Yn,Yn.current&1),p.flags|=128,null):(k&p.child.childLanes)!==0?gp(c,p,k):(In(Yn,Yn.current&1),c=Zi(c,p,k),c!==null?c.sibling:null);In(Yn,Yn.current&1);break;case 19:if(M=(k&p.childLanes)!==0,(c.flags&128)!==0){if(M)return Jd(c,p,k);p.flags|=128}if(F=p.memoizedState,F!==null&&(F.rendering=null,F.tail=null,F.lastEffect=null),In(Yn,Yn.current),M)break;return null;case 22:case 23:return p.lanes=0,hp(c,p,k)}return Zi(c,p,k)}var Qd,Zd,yp,vp;Qd=function(c,p){for(var k=p.child;k!==null;){if(k.tag===5||k.tag===6)c.appendChild(k.stateNode);else if(k.tag!==4&&k.child!==null){k.child.return=k,k=k.child;continue}if(k===p)break;for(;k.sibling===null;){if(k.return===null||k.return===p)return;k=k.return}k.sibling.return=k.return,k=k.sibling}},Zd=function(){},yp=function(c,p,k,M){var F=c.memoizedProps;if(F!==M){c=p.stateNode,ra(Ii.current);var K=null;switch(k){case"input":F=Rt(c,F),M=Rt(c,M),K=[];break;case"select":F=Q({},F,{value:void 0}),M=Q({},M,{value:void 0}),K=[];break;case"textarea":F=kt(c,F),M=kt(c,M),K=[];break;default:typeof F.onClick!="function"&&typeof M.onClick=="function"&&(c.onclick=zc)}vi(k,M);var de;k=null;for(qe in F)if(!M.hasOwnProperty(qe)&&F.hasOwnProperty(qe)&&F[qe]!=null)if(qe==="style"){var _e=F[qe];for(de in _e)_e.hasOwnProperty(de)&&(k||(k={}),k[de]="")}else qe!=="dangerouslySetInnerHTML"&&qe!=="children"&&qe!=="suppressContentEditableWarning"&&qe!=="suppressHydrationWarning"&&qe!=="autoFocus"&&(o.hasOwnProperty(qe)?K||(K=[]):(K=K||[]).push(qe,null));for(qe in M){var $e=M[qe];if(_e=F!=null?F[qe]:void 0,M.hasOwnProperty(qe)&&$e!==_e&&($e!=null||_e!=null))if(qe==="style")if(_e){for(de in _e)!_e.hasOwnProperty(de)||$e&&$e.hasOwnProperty(de)||(k||(k={}),k[de]="");for(de in $e)$e.hasOwnProperty(de)&&_e[de]!==$e[de]&&(k||(k={}),k[de]=$e[de])}else k||(K||(K=[]),K.push(qe,k)),k=$e;else qe==="dangerouslySetInnerHTML"?($e=$e?$e.__html:void 0,_e=_e?_e.__html:void 0,$e!=null&&_e!==$e&&(K=K||[]).push(qe,$e)):qe==="children"?typeof $e!="string"&&typeof $e!="number"||(K=K||[]).push(qe,""+$e):qe!=="suppressContentEditableWarning"&&qe!=="suppressHydrationWarning"&&(o.hasOwnProperty(qe)?($e!=null&&qe==="onScroll"&&zn("scroll",c),K||_e===$e||(K=[])):(K=K||[]).push(qe,$e))}k&&(K=K||[]).push("style",k);var qe=K;(p.updateQueue=qe)&&(p.flags|=4)}},vp=function(c,p,k,M){k!==M&&(p.flags|=4)};function su(c,p){if(!Kn)switch(c.tailMode){case"hidden":p=c.tail;for(var k=null;p!==null;)p.alternate!==null&&(k=p),p=p.sibling;k===null?c.tail=null:k.sibling=null;break;case"collapsed":k=c.tail;for(var M=null;k!==null;)k.alternate!==null&&(M=k),k=k.sibling;M===null?p||c.tail===null?c.tail=null:c.tail.sibling=null:M.sibling=null}}function Lr(c){var p=c.alternate!==null&&c.alternate.child===c.child,k=0,M=0;if(p)for(var F=c.child;F!==null;)k|=F.lanes|F.childLanes,M|=F.subtreeFlags&14680064,M|=F.flags&14680064,F.return=c,F=F.sibling;else for(F=c.child;F!==null;)k|=F.lanes|F.childLanes,M|=F.subtreeFlags,M|=F.flags,F.return=c,F=F.sibling;return c.subtreeFlags|=M,c.childLanes=k,p}function zg(c,p,k){var M=p.pendingProps;switch(md(p),p.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Lr(p),null;case 1:return fs(p.type)&&Fc(),Lr(p),null;case 3:return M=p.stateNode,sa(),Bn(hs),Bn(Jr),Rd(),M.pendingContext&&(M.context=M.pendingContext,M.pendingContext=null),(c===null||c.child===null)&&(Dl(p)?p.flags|=4:c===null||c.memoizedState.isDehydrated&&(p.flags&256)===0||(p.flags|=1024,xs!==null&&(ph(xs),xs=null))),Zd(c,p),Lr(p),null;case 5:$d(p);var F=ra(qa.current);if(k=p.type,c!==null&&p.stateNode!=null)yp(c,p,k,M,F),c.ref!==p.ref&&(p.flags|=512,p.flags|=2097152);else{if(!M){if(p.stateNode===null)throw Error(r(166));return Lr(p),null}if(c=ra(Ii.current),Dl(p)){M=p.stateNode,k=p.type;var K=p.memoizedProps;switch(M[Ai]=p,M[Il]=K,c=(p.mode&1)!==0,k){case"dialog":zn("cancel",M),zn("close",M);break;case"iframe":case"object":case"embed":zn("load",M);break;case"video":case"audio":for(F=0;F<Al.length;F++)zn(Al[F],M);break;case"source":zn("error",M);break;case"img":case"image":case"link":zn("error",M),zn("load",M);break;case"details":zn("toggle",M);break;case"input":He(M,K),zn("invalid",M);break;case"select":M._wrapperState={wasMultiple:!!K.multiple},zn("invalid",M);break;case"textarea":Kt(M,K),zn("invalid",M)}vi(k,K),F=null;for(var de in K)if(K.hasOwnProperty(de)){var _e=K[de];de==="children"?typeof _e=="string"?M.textContent!==_e&&(K.suppressHydrationWarning!==!0&&Lc(M.textContent,_e,c),F=["children",_e]):typeof _e=="number"&&M.textContent!==""+_e&&(K.suppressHydrationWarning!==!0&&Lc(M.textContent,_e,c),F=["children",""+_e]):o.hasOwnProperty(de)&&_e!=null&&de==="onScroll"&&zn("scroll",M)}switch(k){case"input":Je(M),an(M,K,!0);break;case"textarea":Je(M),Rn(M);break;case"select":case"option":break;default:typeof K.onClick=="function"&&(M.onclick=zc)}M=F,p.updateQueue=M,M!==null&&(p.flags|=4)}else{de=F.nodeType===9?F:F.ownerDocument,c==="http://www.w3.org/1999/xhtml"&&(c=Br(k)),c==="http://www.w3.org/1999/xhtml"?k==="script"?(c=de.createElement("div"),c.innerHTML="<script><\/script>",c=c.removeChild(c.firstChild)):typeof M.is=="string"?c=de.createElement(k,{is:M.is}):(c=de.createElement(k),k==="select"&&(de=c,M.multiple?de.multiple=!0:M.size&&(de.size=M.size))):c=de.createElementNS(c,k),c[Ai]=p,c[Il]=M,Qd(c,p,!1,!1),p.stateNode=c;e:{switch(de=yn(k,M),k){case"dialog":zn("cancel",c),zn("close",c),F=M;break;case"iframe":case"object":case"embed":zn("load",c),F=M;break;case"video":case"audio":for(F=0;F<Al.length;F++)zn(Al[F],c);F=M;break;case"source":zn("error",c),F=M;break;case"img":case"image":case"link":zn("error",c),zn("load",c),F=M;break;case"details":zn("toggle",c),F=M;break;case"input":He(c,M),F=Rt(c,M),zn("invalid",c);break;case"option":F=M;break;case"select":c._wrapperState={wasMultiple:!!M.multiple},F=Q({},M,{value:void 0}),zn("invalid",c);break;case"textarea":Kt(c,M),F=kt(c,M),zn("invalid",c);break;default:F=M}vi(k,F),_e=F;for(K in _e)if(_e.hasOwnProperty(K)){var $e=_e[K];K==="style"?Ta(c,$e):K==="dangerouslySetInnerHTML"?($e=$e?$e.__html:void 0,$e!=null&&St(c,$e)):K==="children"?typeof $e=="string"?(k!=="textarea"||$e!=="")&&Tt(c,$e):typeof $e=="number"&&Tt(c,""+$e):K!=="suppressContentEditableWarning"&&K!=="suppressHydrationWarning"&&K!=="autoFocus"&&(o.hasOwnProperty(K)?$e!=null&&K==="onScroll"&&zn("scroll",c):$e!=null&&C(c,K,$e,de))}switch(k){case"input":Je(c),an(c,M,!1);break;case"textarea":Je(c),Rn(c);break;case"option":M.value!=null&&c.setAttribute("value",""+ne(M.value));break;case"select":c.multiple=!!M.multiple,K=M.value,K!=null?yt(c,!!M.multiple,K,!1):M.defaultValue!=null&&yt(c,!!M.multiple,M.defaultValue,!0);break;default:typeof F.onClick=="function"&&(c.onclick=zc)}switch(k){case"button":case"input":case"select":case"textarea":M=!!M.autoFocus;break e;case"img":M=!0;break e;default:M=!1}}M&&(p.flags|=4)}p.ref!==null&&(p.flags|=512,p.flags|=2097152)}return Lr(p),null;case 6:if(c&&p.stateNode!=null)vp(c,p,c.memoizedProps,M);else{if(typeof M!="string"&&p.stateNode===null)throw Error(r(166));if(k=ra(qa.current),ra(Ii.current),Dl(p)){if(M=p.stateNode,k=p.memoizedProps,M[Ai]=p,(K=M.nodeValue!==k)&&(c=gs,c!==null))switch(c.tag){case 3:Lc(M.nodeValue,k,(c.mode&1)!==0);break;case 5:c.memoizedProps.suppressHydrationWarning!==!0&&Lc(M.nodeValue,k,(c.mode&1)!==0)}K&&(p.flags|=4)}else M=(k.nodeType===9?k:k.ownerDocument).createTextNode(M),M[Ai]=p,p.stateNode=M}return Lr(p),null;case 13:if(Bn(Yn),M=p.memoizedState,c===null||c.memoizedState!==null&&c.memoizedState.dehydrated!==null){if(Kn&&Ns!==null&&(p.mode&1)!==0&&(p.flags&128)===0)Pf(),ea(),p.flags|=98560,K=!1;else if(K=Dl(p),M!==null&&M.dehydrated!==null){if(c===null){if(!K)throw Error(r(318));if(K=p.memoizedState,K=K!==null?K.dehydrated:null,!K)throw Error(r(317));K[Ai]=p}else ea(),(p.flags&128)===0&&(p.memoizedState=null),p.flags|=4;Lr(p),K=!1}else xs!==null&&(ph(xs),xs=null),K=!0;if(!K)return p.flags&65536?p:null}return(p.flags&128)!==0?(p.lanes=k,p):(M=M!==null,M!==(c!==null&&c.memoizedState!==null)&&M&&(p.child.flags|=8192,(p.mode&1)!==0&&(c===null||(Yn.current&1)!==0?br===0&&(br=3):xh())),p.updateQueue!==null&&(p.flags|=4),Lr(p),null);case 4:return sa(),Zd(c,p),c===null&&Rl(p.stateNode.containerInfo),Lr(p),null;case 10:return jd(p.type._context),Lr(p),null;case 17:return fs(p.type)&&Fc(),Lr(p),null;case 19:if(Bn(Yn),K=p.memoizedState,K===null)return Lr(p),null;if(M=(p.flags&128)!==0,de=K.rendering,de===null)if(M)su(K,!1);else{if(br!==0||c!==null&&(c.flags&128)!==0)for(c=p.child;c!==null;){if(de=Jc(c),de!==null){for(p.flags|=128,su(K,!1),M=de.updateQueue,M!==null&&(p.updateQueue=M,p.flags|=4),p.subtreeFlags=0,M=k,k=p.child;k!==null;)K=k,c=M,K.flags&=14680066,de=K.alternate,de===null?(K.childLanes=0,K.lanes=c,K.child=null,K.subtreeFlags=0,K.memoizedProps=null,K.memoizedState=null,K.updateQueue=null,K.dependencies=null,K.stateNode=null):(K.childLanes=de.childLanes,K.lanes=de.lanes,K.child=de.child,K.subtreeFlags=0,K.deletions=null,K.memoizedProps=de.memoizedProps,K.memoizedState=de.memoizedState,K.updateQueue=de.updateQueue,K.type=de.type,c=de.dependencies,K.dependencies=c===null?null:{lanes:c.lanes,firstContext:c.firstContext}),k=k.sibling;return In(Yn,Yn.current&1|2),p.child}c=c.sibling}K.tail!==null&&kn()>Xa&&(p.flags|=128,M=!0,su(K,!1),p.lanes=4194304)}else{if(!M)if(c=Jc(de),c!==null){if(p.flags|=128,M=!0,k=c.updateQueue,k!==null&&(p.updateQueue=k,p.flags|=4),su(K,!0),K.tail===null&&K.tailMode==="hidden"&&!de.alternate&&!Kn)return Lr(p),null}else 2*kn()-K.renderingStartTime>Xa&&k!==1073741824&&(p.flags|=128,M=!0,su(K,!1),p.lanes=4194304);K.isBackwards?(de.sibling=p.child,p.child=de):(k=K.last,k!==null?k.sibling=de:p.child=de,K.last=de)}return K.tail!==null?(p=K.tail,K.rendering=p,K.tail=p.sibling,K.renderingStartTime=kn(),p.sibling=null,k=Yn.current,In(Yn,M?k&1|2:k&1),p):(Lr(p),null);case 22:case 23:return gh(),M=p.memoizedState!==null,c!==null&&c.memoizedState!==null!==M&&(p.flags|=8192),M&&(p.mode&1)!==0?(Ts&1073741824)!==0&&(Lr(p),p.subtreeFlags&6&&(p.flags|=8192)):Lr(p),null;case 24:return null;case 25:return null}throw Error(r(156,p.tag))}function Bg(c,p){switch(md(p),p.tag){case 1:return fs(p.type)&&Fc(),c=p.flags,c&65536?(p.flags=c&-65537|128,p):null;case 3:return sa(),Bn(hs),Bn(Jr),Rd(),c=p.flags,(c&65536)!==0&&(c&128)===0?(p.flags=c&-65537|128,p):null;case 5:return $d(p),null;case 13:if(Bn(Yn),c=p.memoizedState,c!==null&&c.dehydrated!==null){if(p.alternate===null)throw Error(r(340));ea()}return c=p.flags,c&65536?(p.flags=c&-65537|128,p):null;case 19:return Bn(Yn),null;case 4:return sa(),null;case 10:return jd(p.type._context),null;case 22:case 23:return gh(),null;case 24:return null;default:return null}}var eh=!1,zr=!1,Fg=typeof WeakSet=="function"?WeakSet:Set,It=null;function Ga(c,p){var k=c.ref;if(k!==null)if(typeof k=="function")try{k(null)}catch(M){Jn(c,p,M)}else k.current=null}function th(c,p,k){try{k()}catch(M){Jn(c,p,M)}}var bp=!1;function Ug(c,p){if(ad=bo,c=Zu(),ed(c)){if("selectionStart"in c)var k={start:c.selectionStart,end:c.selectionEnd};else e:{k=(k=c.ownerDocument)&&k.defaultView||window;var M=k.getSelection&&k.getSelection();if(M&&M.rangeCount!==0){k=M.anchorNode;var F=M.anchorOffset,K=M.focusNode;M=M.focusOffset;try{k.nodeType,K.nodeType}catch{k=null;break e}var de=0,_e=-1,$e=-1,qe=0,at=0,ct=c,ot=null;t:for(;;){for(var jt;ct!==k||F!==0&&ct.nodeType!==3||(_e=de+F),ct!==K||M!==0&&ct.nodeType!==3||($e=de+M),ct.nodeType===3&&(de+=ct.nodeValue.length),(jt=ct.firstChild)!==null;)ot=ct,ct=jt;for(;;){if(ct===c)break t;if(ot===k&&++qe===F&&(_e=de),ot===K&&++at===M&&($e=de),(jt=ct.nextSibling)!==null)break;ct=ot,ot=ct.parentNode}ct=jt}k=_e===-1||$e===-1?null:{start:_e,end:$e}}else k=null}k=k||{start:0,end:0}}else k=null;for(ld={focusedElem:c,selectionRange:k},bo=!1,It=p;It!==null;)if(p=It,c=p.child,(p.subtreeFlags&1028)!==0&&c!==null)c.return=p,It=c;else for(;It!==null;){p=It;try{var Pt=p.alternate;if((p.flags&1024)!==0)switch(p.tag){case 0:case 11:case 15:break;case 1:if(Pt!==null){var Dt=Pt.memoizedProps,Pn=Pt.memoizedState,Ue=p.stateNode,Ie=Ue.getSnapshotBeforeUpdate(p.elementType===p.type?Dt:hr(p.type,Dt),Pn);Ue.__reactInternalSnapshotBeforeUpdate=Ie}break;case 3:var Ve=p.stateNode.containerInfo;Ve.nodeType===1?Ve.textContent="":Ve.nodeType===9&&Ve.documentElement&&Ve.removeChild(Ve.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(r(163))}}catch(ht){Jn(p,p.return,ht)}if(c=p.sibling,c!==null){c.return=p.return,It=c;break}It=p.return}return Pt=bp,bp=!1,Pt}function Hl(c,p,k){var M=p.updateQueue;if(M=M!==null?M.lastEffect:null,M!==null){var F=M=M.next;do{if((F.tag&c)===c){var K=F.destroy;F.destroy=void 0,K!==void 0&&th(p,k,K)}F=F.next}while(F!==M)}}function nh(c,p){if(p=p.updateQueue,p=p!==null?p.lastEffect:null,p!==null){var k=p=p.next;do{if((k.tag&c)===c){var M=k.create;k.destroy=M()}k=k.next}while(k!==p)}}function rh(c){var p=c.ref;if(p!==null){var k=c.stateNode;switch(c.tag){case 5:c=k;break;default:c=k}typeof p=="function"?p(c):p.current=c}}function wp(c){var p=c.alternate;p!==null&&(c.alternate=null,wp(p)),c.child=null,c.deletions=null,c.sibling=null,c.tag===5&&(p=c.stateNode,p!==null&&(delete p[Ai],delete p[Il],delete p[hd],delete p[Tf],delete p[$f])),c.stateNode=null,c.return=null,c.dependencies=null,c.memoizedProps=null,c.memoizedState=null,c.pendingProps=null,c.stateNode=null,c.updateQueue=null}function _p(c){return c.tag===5||c.tag===3||c.tag===4}function kp(c){e:for(;;){for(;c.sibling===null;){if(c.return===null||_p(c.return))return null;c=c.return}for(c.sibling.return=c.return,c=c.sibling;c.tag!==5&&c.tag!==6&&c.tag!==18;){if(c.flags&2||c.child===null||c.tag===4)continue e;c.child.return=c,c=c.child}if(!(c.flags&2))return c.stateNode}}function sh(c,p,k){var M=c.tag;if(M===5||M===6)c=c.stateNode,p?k.nodeType===8?k.parentNode.insertBefore(c,p):k.insertBefore(c,p):(k.nodeType===8?(p=k.parentNode,p.insertBefore(c,k)):(p=k,p.appendChild(c)),k=k._reactRootContainer,k!=null||p.onclick!==null||(p.onclick=zc));else if(M!==4&&(c=c.child,c!==null))for(sh(c,p,k),c=c.sibling;c!==null;)sh(c,p,k),c=c.sibling}function ih(c,p,k){var M=c.tag;if(M===5||M===6)c=c.stateNode,p?k.insertBefore(c,p):k.appendChild(c);else if(M!==4&&(c=c.child,c!==null))for(ih(c,p,k),c=c.sibling;c!==null;)ih(c,p,k),c=c.sibling}var Cr=null,di=!1;function No(c,p,k){for(k=k.child;k!==null;)Hg(c,p,k),k=k.sibling}function Hg(c,p,k){if(gr&&typeof gr.onCommitFiberUnmount=="function")try{gr.onCommitFiberUnmount(cs,k)}catch{}switch(k.tag){case 5:zr||Ga(k,p);case 6:var M=Cr,F=di;Cr=null,No(c,p,k),Cr=M,di=F,Cr!==null&&(di?(c=Cr,k=k.stateNode,c.nodeType===8?c.parentNode.removeChild(k):c.removeChild(k)):Cr.removeChild(k.stateNode));break;case 18:Cr!==null&&(di?(c=Cr,k=k.stateNode,c.nodeType===8?dd(c.parentNode,k):c.nodeType===1&&dd(c,k),Vi(c)):dd(Cr,k.stateNode));break;case 4:M=Cr,F=di,Cr=k.stateNode.containerInfo,di=!0,No(c,p,k),Cr=M,di=F;break;case 0:case 11:case 14:case 15:if(!zr&&(M=k.updateQueue,M!==null&&(M=M.lastEffect,M!==null))){F=M=M.next;do{var K=F,de=K.destroy;K=K.tag,de!==void 0&&((K&2)!==0||(K&4)!==0)&&th(k,p,de),F=F.next}while(F!==M)}No(c,p,k);break;case 1:if(!zr&&(Ga(k,p),M=k.stateNode,typeof M.componentWillUnmount=="function"))try{M.props=k.memoizedProps,M.state=k.memoizedState,M.componentWillUnmount()}catch(_e){Jn(k,p,_e)}No(c,p,k);break;case 21:No(c,p,k);break;case 22:k.mode&1?(zr=(M=zr)||k.memoizedState!==null,No(c,p,k),zr=M):No(c,p,k);break;default:No(c,p,k)}}function Wl(c){var p=c.updateQueue;if(p!==null){c.updateQueue=null;var k=c.stateNode;k===null&&(k=c.stateNode=new Fg),p.forEach(function(M){var F=Yg.bind(null,c,M);k.has(M)||(k.add(M),M.then(F,F))})}}function Ws(c,p){var k=p.deletions;if(k!==null)for(var M=0;M<k.length;M++){var F=k[M];try{var K=c,de=p,_e=de;e:for(;_e!==null;){switch(_e.tag){case 5:Cr=_e.stateNode,di=!1;break e;case 3:Cr=_e.stateNode.containerInfo,di=!0;break e;case 4:Cr=_e.stateNode.containerInfo,di=!0;break e}_e=_e.return}if(Cr===null)throw Error(r(160));Hg(K,de,F),Cr=null,di=!1;var $e=F.alternate;$e!==null&&($e.return=null),F.return=null}catch(qe){Jn(F,p,qe)}}if(p.subtreeFlags&12854)for(p=p.child;p!==null;)oh(p,c),p=p.sibling}function oh(c,p){var k=c.alternate,M=c.flags;switch(c.tag){case 0:case 11:case 14:case 15:if(Ws(p,c),hi(c),M&4){try{Hl(3,c,c.return),nh(3,c)}catch(Dt){Jn(c,c.return,Dt)}try{Hl(5,c,c.return)}catch(Dt){Jn(c,c.return,Dt)}}break;case 1:Ws(p,c),hi(c),M&512&&k!==null&&Ga(k,k.return);break;case 5:if(Ws(p,c),hi(c),M&512&&k!==null&&Ga(k,k.return),c.flags&32){var F=c.stateNode;try{Tt(F,"")}catch(Dt){Jn(c,c.return,Dt)}}if(M&4&&(F=c.stateNode,F!=null)){var K=c.memoizedProps,de=k!==null?k.memoizedProps:K,_e=c.type,$e=c.updateQueue;if(c.updateQueue=null,$e!==null)try{_e==="input"&&K.type==="radio"&&K.name!=null&&vt(F,K),yn(_e,de);var qe=yn(_e,K);for(de=0;de<$e.length;de+=2){var at=$e[de],ct=$e[de+1];at==="style"?Ta(F,ct):at==="dangerouslySetInnerHTML"?St(F,ct):at==="children"?Tt(F,ct):C(F,at,ct,qe)}switch(_e){case"input":st(F,K);break;case"textarea":On(F,K);break;case"select":var ot=F._wrapperState.wasMultiple;F._wrapperState.wasMultiple=!!K.multiple;var jt=K.value;jt!=null?yt(F,!!K.multiple,jt,!1):ot!==!!K.multiple&&(K.defaultValue!=null?yt(F,!!K.multiple,K.defaultValue,!0):yt(F,!!K.multiple,K.multiple?[]:"",!1))}F[Il]=K}catch(Dt){Jn(c,c.return,Dt)}}break;case 6:if(Ws(p,c),hi(c),M&4){if(c.stateNode===null)throw Error(r(162));F=c.stateNode,K=c.memoizedProps;try{F.nodeValue=K}catch(Dt){Jn(c,c.return,Dt)}}break;case 3:if(Ws(p,c),hi(c),M&4&&k!==null&&k.memoizedState.isDehydrated)try{Vi(p.containerInfo)}catch(Dt){Jn(c,c.return,Dt)}break;case 4:Ws(p,c),hi(c);break;case 13:Ws(p,c),hi(c),F=c.child,F.flags&8192&&(K=F.memoizedState!==null,F.stateNode.isHidden=K,!K||F.alternate!==null&&F.alternate.memoizedState!==null||(uh=kn())),M&4&&Wl(c);break;case 22:if(at=k!==null&&k.memoizedState!==null,c.mode&1?(zr=(qe=zr)||at,Ws(p,c),zr=qe):Ws(p,c),hi(c),M&8192){if(qe=c.memoizedState!==null,(c.stateNode.isHidden=qe)&&!at&&(c.mode&1)!==0)for(It=c,at=c.child;at!==null;){for(ct=It=at;It!==null;){switch(ot=It,jt=ot.child,ot.tag){case 0:case 11:case 14:case 15:Hl(4,ot,ot.return);break;case 1:Ga(ot,ot.return);var Pt=ot.stateNode;if(typeof Pt.componentWillUnmount=="function"){M=ot,k=ot.return;try{p=M,Pt.props=p.memoizedProps,Pt.state=p.memoizedState,Pt.componentWillUnmount()}catch(Dt){Jn(M,k,Dt)}}break;case 5:Ga(ot,ot.return);break;case 22:if(ot.memoizedState!==null){ah(ct);continue}}jt!==null?(jt.return=ot,It=jt):ah(ct)}at=at.sibling}e:for(at=null,ct=c;;){if(ct.tag===5){if(at===null){at=ct;try{F=ct.stateNode,qe?(K=F.style,typeof K.setProperty=="function"?K.setProperty("display","none","important"):K.display="none"):(_e=ct.stateNode,$e=ct.memoizedProps.style,de=$e!=null&&$e.hasOwnProperty("display")?$e.display:null,_e.style.display=$r("display",de))}catch(Dt){Jn(c,c.return,Dt)}}}else if(ct.tag===6){if(at===null)try{ct.stateNode.nodeValue=qe?"":ct.memoizedProps}catch(Dt){Jn(c,c.return,Dt)}}else if((ct.tag!==22&&ct.tag!==23||ct.memoizedState===null||ct===c)&&ct.child!==null){ct.child.return=ct,ct=ct.child;continue}if(ct===c)break e;for(;ct.sibling===null;){if(ct.return===null||ct.return===c)break e;at===ct&&(at=null),ct=ct.return}at===ct&&(at=null),ct.sibling.return=ct.return,ct=ct.sibling}}break;case 19:Ws(p,c),hi(c),M&4&&Wl(c);break;case 21:break;default:Ws(p,c),hi(c)}}function hi(c){var p=c.flags;if(p&2){try{e:{for(var k=c.return;k!==null;){if(_p(k)){var M=k;break e}k=k.return}throw Error(r(160))}switch(M.tag){case 5:var F=M.stateNode;M.flags&32&&(Tt(F,""),M.flags&=-33);var K=kp(c);ih(c,K,F);break;case 3:case 4:var de=M.stateNode.containerInfo,_e=kp(c);sh(c,_e,de);break;default:throw Error(r(161))}}catch($e){Jn(c,c.return,$e)}c.flags&=-3}p&4096&&(c.flags&=-4097)}function Sp(c,p,k){It=c,Cp(c)}function Cp(c,p,k){for(var M=(c.mode&1)!==0;It!==null;){var F=It,K=F.child;if(F.tag===22&&M){var de=F.memoizedState!==null||eh;if(!de){var _e=F.alternate,$e=_e!==null&&_e.memoizedState!==null||zr;_e=eh;var qe=zr;if(eh=de,(zr=$e)&&!qe)for(It=F;It!==null;)de=It,$e=de.child,de.tag===22&&de.memoizedState!==null?lh(F):$e!==null?($e.return=de,It=$e):lh(F);for(;K!==null;)It=K,Cp(K),K=K.sibling;It=F,eh=_e,zr=qe}jp(c)}else(F.subtreeFlags&8772)!==0&&K!==null?(K.return=F,It=K):jp(c)}}function jp(c){for(;It!==null;){var p=It;if((p.flags&8772)!==0){var k=p.alternate;try{if((p.flags&8772)!==0)switch(p.tag){case 0:case 11:case 15:zr||nh(5,p);break;case 1:var M=p.stateNode;if(p.flags&4&&!zr)if(k===null)M.componentDidMount();else{var F=p.elementType===p.type?k.memoizedProps:hr(p.type,k.memoizedProps);M.componentDidUpdate(F,k.memoizedState,M.__reactInternalSnapshotBeforeUpdate)}var K=p.updateQueue;K!==null&&Eg(p,K,M);break;case 3:var de=p.updateQueue;if(de!==null){if(k=null,p.child!==null)switch(p.child.tag){case 5:k=p.child.stateNode;break;case 1:k=p.child.stateNode}Eg(p,de,k)}break;case 5:var _e=p.stateNode;if(k===null&&p.flags&4){k=_e;var $e=p.memoizedProps;switch(p.type){case"button":case"input":case"select":case"textarea":$e.autoFocus&&k.focus();break;case"img":$e.src&&(k.src=$e.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(p.memoizedState===null){var qe=p.alternate;if(qe!==null){var at=qe.memoizedState;if(at!==null){var ct=at.dehydrated;ct!==null&&Vi(ct)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(r(163))}zr||p.flags&512&&rh(p)}catch(ot){Jn(p,p.return,ot)}}if(p===c){It=null;break}if(k=p.sibling,k!==null){k.return=p.return,It=k;break}It=p.return}}function ah(c){for(;It!==null;){var p=It;if(p===c){It=null;break}var k=p.sibling;if(k!==null){k.return=p.return,It=k;break}It=p.return}}function lh(c){for(;It!==null;){var p=It;try{switch(p.tag){case 0:case 11:case 15:var k=p.return;try{nh(4,p)}catch($e){Jn(p,k,$e)}break;case 1:var M=p.stateNode;if(typeof M.componentDidMount=="function"){var F=p.return;try{M.componentDidMount()}catch($e){Jn(p,F,$e)}}var K=p.return;try{rh(p)}catch($e){Jn(p,K,$e)}break;case 5:var de=p.return;try{rh(p)}catch($e){Jn(p,de,$e)}}}catch($e){Jn(p,p.return,$e)}if(p===c){It=null;break}var _e=p.sibling;if(_e!==null){_e.return=p.return,It=_e;break}It=p.return}}var Wg=Math.ceil,iu=N.ReactCurrentDispatcher,ou=N.ReactCurrentOwner,qs=N.ReactCurrentBatchConfig,gn=0,fr=null,ar=null,jr=0,Ts=0,Ka=Ki(0),br=0,ql=null,la=0,au=0,ch=0,lu=null,vs=null,uh=0,Xa=1/0,To=null,cu=!1,dh=null,$o=null,uu=!1,ca=null,du=0,Vl=0,hh=null,Gl=-1,hu=0;function es(){return(gn&6)!==0?kn():Gl!==-1?Gl:Gl=kn()}function Ao(c){return(c.mode&1)===0?1:(gn&2)!==0&&jr!==0?jr&-jr:_d.transition!==null?(hu===0&&(hu=Es()),hu):(c=Pe,c!==0||(c=window.event,c=c===void 0?16:fe(c.type)),c)}function fi(c,p,k,M){if(50<Vl)throw Vl=0,hh=null,Error(r(185));qr(c,k,M),((gn&2)===0||c!==fr)&&(c===fr&&((gn&2)===0&&(au|=k),br===4&&Ro(c,jr)),bs(c,M),k===1&&gn===0&&(p.mode&1)===0&&(Xa=kn()+500,Hc&&So()))}function bs(c,p){var k=c.callbackNode;ds(c,p);var M=ji(c,c===fr?jr:0);if(M===0)k!==null&&Sr(k),c.callbackNode=null,c.callbackPriority=0;else if(p=M&-M,c.callbackPriority!==p){if(k!=null&&Sr(k),p===1)c.tag===0?fv(Tp.bind(null,c)):If(Tp.bind(null,c)),kg(function(){(gn&6)===0&&So()}),k=null;else{switch(Qe(M)){case 1:k=Vn;break;case 4:k=Ir;break;case 16:k=ni;break;case 536870912:k=ki;break;default:k=ni}k=Pp(k,Ep.bind(null,c))}c.callbackPriority=p,c.callbackNode=k}}function Ep(c,p){if(Gl=-1,hu=0,(gn&6)!==0)throw Error(r(327));var k=c.callbackNode;if(Ya()&&c.callbackNode!==k)return null;var M=ji(c,c===fr?jr:0);if(M===0)return null;if((M&30)!==0||(M&c.expiredLanes)!==0||p)p=fu(c,M);else{p=M;var F=gn;gn|=2;var K=qg();(fr!==c||jr!==p)&&(To=null,Xa=kn()+500,da(c,p));do try{xv();break}catch(_e){$p(c,_e)}while(!0);Cd(),iu.current=K,gn=F,ar!==null?p=0:(fr=null,jr=0,p=br)}if(p!==0){if(p===2&&(F=Wi(c),F!==0&&(M=F,p=fh(c,F))),p===1)throw k=ql,da(c,0),Ro(c,M),bs(c,kn()),k;if(p===6)Ro(c,M);else{if(F=c.current.alternate,(M&30)===0&&!Np(F)&&(p=fu(c,M),p===2&&(K=Wi(c),K!==0&&(M=K,p=fh(c,K))),p===1))throw k=ql,da(c,0),Ro(c,M),bs(c,kn()),k;switch(c.finishedWork=F,c.finishedLanes=M,p){case 0:case 1:throw Error(r(345));case 2:ha(c,vs,To);break;case 3:if(Ro(c,M),(M&130023424)===M&&(p=uh+500-kn(),10<p)){if(ji(c,0)!==0)break;if(F=c.suspendedLanes,(F&M)!==M){es(),c.pingedLanes|=c.suspendedLanes&F;break}c.timeoutHandle=ud(ha.bind(null,c,vs,To),p);break}ha(c,vs,To);break;case 4:if(Ro(c,M),(M&4194240)===M)break;for(p=c.eventTimes,F=-1;0<M;){var de=31-Gn(M);K=1<<de,de=p[de],de>F&&(F=de),M&=~K}if(M=F,M=kn()-M,M=(120>M?120:480>M?480:1080>M?1080:1920>M?1920:3e3>M?3e3:4320>M?4320:1960*Wg(M/1960))-M,10<M){c.timeoutHandle=ud(ha.bind(null,c,vs,To),M);break}ha(c,vs,To);break;case 5:ha(c,vs,To);break;default:throw Error(r(329))}}}return bs(c,kn()),c.callbackNode===k?Ep.bind(null,c):null}function fh(c,p){var k=lu;return c.current.memoizedState.isDehydrated&&(da(c,p).flags|=256),c=fu(c,p),c!==2&&(p=vs,vs=k,p!==null&&ph(p)),c}function ph(c){vs===null?vs=c:vs.push.apply(vs,c)}function Np(c){for(var p=c;;){if(p.flags&16384){var k=p.updateQueue;if(k!==null&&(k=k.stores,k!==null))for(var M=0;M<k.length;M++){var F=k[M],K=F.getSnapshot;F=F.value;try{if(!li(K(),F))return!1}catch{return!1}}}if(k=p.child,p.subtreeFlags&16384&&k!==null)k.return=p,p=k;else{if(p===c)break;for(;p.sibling===null;){if(p.return===null||p.return===c)return!0;p=p.return}p.sibling.return=p.return,p=p.sibling}}return!0}function Ro(c,p){for(p&=~ch,p&=~au,c.suspendedLanes|=p,c.pingedLanes&=~p,c=c.expirationTimes;0<p;){var k=31-Gn(p),M=1<<k;c[k]=-1,p&=~M}}function Tp(c){if((gn&6)!==0)throw Error(r(327));Ya();var p=ji(c,0);if((p&1)===0)return bs(c,kn()),null;var k=fu(c,p);if(c.tag!==0&&k===2){var M=Wi(c);M!==0&&(p=M,k=fh(c,M))}if(k===1)throw k=ql,da(c,0),Ro(c,p),bs(c,kn()),k;if(k===6)throw Error(r(345));return c.finishedWork=c.current.alternate,c.finishedLanes=p,ha(c,vs,To),bs(c,kn()),null}function mh(c,p){var k=gn;gn|=1;try{return c(p)}finally{gn=k,gn===0&&(Xa=kn()+500,Hc&&So())}}function ua(c){ca!==null&&ca.tag===0&&(gn&6)===0&&Ya();var p=gn;gn|=1;var k=qs.transition,M=Pe;try{if(qs.transition=null,Pe=1,c)return c()}finally{Pe=M,qs.transition=k,gn=p,(gn&6)===0&&So()}}function gh(){Ts=Ka.current,Bn(Ka)}function da(c,p){c.finishedWork=null,c.finishedLanes=0;var k=c.timeoutHandle;if(k!==-1&&(c.timeoutHandle=-1,_g(k)),ar!==null)for(k=ar.return;k!==null;){var M=k;switch(md(M),M.tag){case 1:M=M.type.childContextTypes,M!=null&&Fc();break;case 3:sa(),Bn(hs),Bn(Jr),Rd();break;case 5:$d(M);break;case 4:sa();break;case 13:Bn(Yn);break;case 19:Bn(Yn);break;case 10:jd(M.type._context);break;case 22:case 23:gh()}k=k.return}if(fr=c,ar=c=Mo(c.current,null),jr=Ts=p,br=0,ql=null,ch=au=la=0,vs=lu=null,Wa!==null){for(p=0;p<Wa.length;p++)if(k=Wa[p],M=k.interleaved,M!==null){k.interleaved=null;var F=M.next,K=k.pending;if(K!==null){var de=K.next;K.next=F,M.next=de}k.pending=M}Wa=null}return c}function $p(c,p){do{var k=ar;try{if(Cd(),Md.current=tu,Pd){for(var M=Xn.memoizedState;M!==null;){var F=M.queue;F!==null&&(F.pending=null),M=M.next}Pd=!1}if(ia=0,vr=dr=Xn=null,oa=!1,Eo=0,ou.current=null,k===null||k.return===null){br=1,ql=p,ar=null;break}e:{var K=c,de=k.return,_e=k,$e=p;if(p=jr,_e.flags|=32768,$e!==null&&typeof $e=="object"&&typeof $e.then=="function"){var qe=$e,at=_e,ct=at.tag;if((at.mode&1)===0&&(ct===0||ct===11||ct===15)){var ot=at.alternate;ot?(at.updateQueue=ot.updateQueue,at.memoizedState=ot.memoizedState,at.lanes=ot.lanes):(at.updateQueue=null,at.memoizedState=null)}var jt=Dg(de);if(jt!==null){jt.flags&=-257,Zr(jt,de,_e,K,p),jt.mode&1&&cp(K,qe,p),p=jt,$e=qe;var Pt=p.updateQueue;if(Pt===null){var Dt=new Set;Dt.add($e),p.updateQueue=Dt}else Pt.add($e);break e}else{if((p&1)===0){cp(K,qe,p),xh();break e}$e=Error(r(426))}}else if(Kn&&_e.mode&1){var Pn=Dg(de);if(Pn!==null){(Pn.flags&65536)===0&&(Pn.flags|=256),Zr(Pn,de,_e,K,p),wd(Va($e,_e));break e}}K=$e=Va($e,_e),br!==4&&(br=2),lu===null?lu=[K]:lu.push(K),K=de;do{switch(K.tag){case 3:K.flags|=65536,p&=-p,K.lanes|=p;var Ue=ap(K,$e,p);jg(K,Ue);break e;case 1:_e=$e;var Ie=K.type,Ve=K.stateNode;if((K.flags&128)===0&&(typeof Ie.getDerivedStateFromError=="function"||Ve!==null&&typeof Ve.componentDidCatch=="function"&&($o===null||!$o.has(Ve)))){K.flags|=65536,p&=-p,K.lanes|=p;var ht=lp(K,_e,p);jg(K,ht);break e}}K=K.return}while(K!==null)}Kl(k)}catch(Ft){p=Ft,ar===k&&k!==null&&(ar=k=k.return);continue}break}while(!0)}function qg(){var c=iu.current;return iu.current=tu,c===null?tu:c}function xh(){(br===0||br===3||br===2)&&(br=4),fr===null||(la&268435455)===0&&(au&268435455)===0||Ro(fr,jr)}function fu(c,p){var k=gn;gn|=2;var M=qg();(fr!==c||jr!==p)&&(To=null,da(c,p));do try{Vg();break}catch(F){$p(c,F)}while(!0);if(Cd(),gn=k,iu.current=M,ar!==null)throw Error(r(261));return fr=null,jr=0,br}function Vg(){for(;ar!==null;)Ap(ar)}function xv(){for(;ar!==null&&!Aa();)Ap(ar)}function Ap(c){var p=Ip(c.alternate,c,Ts);c.memoizedProps=c.pendingProps,p===null?Kl(c):ar=p,ou.current=null}function Kl(c){var p=c;do{var k=p.alternate;if(c=p.return,(p.flags&32768)===0){if(k=zg(k,p,Ts),k!==null){ar=k;return}}else{if(k=Bg(k,p),k!==null){k.flags&=32767,ar=k;return}if(c!==null)c.flags|=32768,c.subtreeFlags=0,c.deletions=null;else{br=6,ar=null;return}}if(p=p.sibling,p!==null){ar=p;return}ar=p=c}while(p!==null);br===0&&(br=5)}function ha(c,p,k){var M=Pe,F=qs.transition;try{qs.transition=null,Pe=1,Rp(c,p,k,M)}finally{qs.transition=F,Pe=M}return null}function Rp(c,p,k,M){do Ya();while(ca!==null);if((gn&6)!==0)throw Error(r(327));k=c.finishedWork;var F=c.finishedLanes;if(k===null)return null;if(c.finishedWork=null,c.finishedLanes=0,k===c.current)throw Error(r(177));c.callbackNode=null,c.callbackPriority=0;var K=k.lanes|k.childLanes;if(ft(c,K),c===fr&&(ar=fr=null,jr=0),(k.subtreeFlags&2064)===0&&(k.flags&2064)===0||uu||(uu=!0,Pp(ni,function(){return Ya(),null})),K=(k.flags&15990)!==0,(k.subtreeFlags&15990)!==0||K){K=qs.transition,qs.transition=null;var de=Pe;Pe=1;var _e=gn;gn|=4,ou.current=null,Ug(c,k),oh(k,c),xg(ld),bo=!!ad,ld=ad=null,c.current=k,Sp(k),Ra(),gn=_e,Pe=de,qs.transition=K}else c.current=k;if(uu&&(uu=!1,ca=c,du=F),K=c.pendingLanes,K===0&&($o=null),Bt(k.stateNode),bs(c,kn()),p!==null)for(M=c.onRecoverableError,k=0;k<p.length;k++)F=p[k],M(F.value,{componentStack:F.stack,digest:F.digest});if(cu)throw cu=!1,c=dh,dh=null,c;return(du&1)!==0&&c.tag!==0&&Ya(),K=c.pendingLanes,(K&1)!==0?c===hh?Vl++:(Vl=0,hh=c):Vl=0,So(),null}function Ya(){if(ca!==null){var c=Qe(du),p=qs.transition,k=Pe;try{if(qs.transition=null,Pe=16>c?16:c,ca===null)var M=!1;else{if(c=ca,ca=null,du=0,(gn&6)!==0)throw Error(r(331));var F=gn;for(gn|=4,It=c.current;It!==null;){var K=It,de=K.child;if((It.flags&16)!==0){var _e=K.deletions;if(_e!==null){for(var $e=0;$e<_e.length;$e++){var qe=_e[$e];for(It=qe;It!==null;){var at=It;switch(at.tag){case 0:case 11:case 15:Hl(8,at,K)}var ct=at.child;if(ct!==null)ct.return=at,It=ct;else for(;It!==null;){at=It;var ot=at.sibling,jt=at.return;if(wp(at),at===qe){It=null;break}if(ot!==null){ot.return=jt,It=ot;break}It=jt}}}var Pt=K.alternate;if(Pt!==null){var Dt=Pt.child;if(Dt!==null){Pt.child=null;do{var Pn=Dt.sibling;Dt.sibling=null,Dt=Pn}while(Dt!==null)}}It=K}}if((K.subtreeFlags&2064)!==0&&de!==null)de.return=K,It=de;else e:for(;It!==null;){if(K=It,(K.flags&2048)!==0)switch(K.tag){case 0:case 11:case 15:Hl(9,K,K.return)}var Ue=K.sibling;if(Ue!==null){Ue.return=K.return,It=Ue;break e}It=K.return}}var Ie=c.current;for(It=Ie;It!==null;){de=It;var Ve=de.child;if((de.subtreeFlags&2064)!==0&&Ve!==null)Ve.return=de,It=Ve;else e:for(de=Ie;It!==null;){if(_e=It,(_e.flags&2048)!==0)try{switch(_e.tag){case 0:case 11:case 15:nh(9,_e)}}catch(Ft){Jn(_e,_e.return,Ft)}if(_e===de){It=null;break e}var ht=_e.sibling;if(ht!==null){ht.return=_e.return,It=ht;break e}It=_e.return}}if(gn=F,So(),gr&&typeof gr.onPostCommitFiberRoot=="function")try{gr.onPostCommitFiberRoot(cs,c)}catch{}M=!0}return M}finally{Pe=k,qs.transition=p}}return!1}function Mp(c,p,k){p=Va(k,p),p=ap(c,p,1),c=jo(c,p,1),p=es(),c!==null&&(qr(c,1,p),bs(c,p))}function Jn(c,p,k){if(c.tag===3)Mp(c,c,k);else for(;p!==null;){if(p.tag===3){Mp(p,c,k);break}else if(p.tag===1){var M=p.stateNode;if(typeof p.type.getDerivedStateFromError=="function"||typeof M.componentDidCatch=="function"&&($o===null||!$o.has(M))){c=Va(k,c),c=lp(p,c,1),p=jo(p,c,1),c=es(),p!==null&&(qr(p,1,c),bs(p,c));break}}p=p.return}}function Gg(c,p,k){var M=c.pingCache;M!==null&&M.delete(p),p=es(),c.pingedLanes|=c.suspendedLanes&k,fr===c&&(jr&k)===k&&(br===4||br===3&&(jr&130023424)===jr&&500>kn()-uh?da(c,0):ch|=k),bs(c,p)}function Kg(c,p){p===0&&((c.mode&1)===0?p=1:(p=Wr,Wr<<=1,(Wr&130023424)===0&&(Wr=4194304)));var k=es();c=Yi(c,p),c!==null&&(qr(c,p,k),bs(c,k))}function Xg(c){var p=c.memoizedState,k=0;p!==null&&(k=p.retryLane),Kg(c,k)}function Yg(c,p){var k=0;switch(c.tag){case 13:var M=c.stateNode,F=c.memoizedState;F!==null&&(k=F.retryLane);break;case 19:M=c.stateNode;break;default:throw Error(r(314))}M!==null&&M.delete(p),Kg(c,k)}var Ip;Ip=function(c,p,k){if(c!==null)if(c.memoizedProps!==p.pendingProps||hs.current)ys=!0;else{if((c.lanes&k)===0&&(p.flags&128)===0)return ys=!1,gv(c,p,k);ys=(c.flags&131072)!==0}else ys=!1,Kn&&(p.flags&1048576)!==0&&Zo(p,qc,p.index);switch(p.lanes=0,p.tag){case 2:var M=p.type;ru(c,p),c=p.pendingProps;var F=Qr(p,Jr.current);Ha(p,k),F=Od(null,p,M,c,F,k);var K=Ld();return p.flags|=1,typeof F=="object"&&F!==null&&typeof F.render=="function"&&F.$$typeof===void 0?(p.tag=1,p.memoizedState=null,p.updateQueue=null,fs(M)?(K=!0,Uc(p)):K=!1,p.memoizedState=F.state!==null&&F.state!==void 0?F.state:null,Xc(p),F.updater=Qi,p.stateNode=F,F._reactInternals=p,Ud(p,M,c,k),p=Vd(null,p,M,!0,K,k)):(p.tag=0,Kn&&K&&ur(p),Or(null,p,F,k),p=p.child),p;case 16:M=p.elementType;e:{switch(ru(c,p),c=p.pendingProps,F=M._init,M=F(M._payload),p.type=M,F=p.tag=Jg(M),c=hr(M,c),F){case 0:p=qd(null,p,M,c,k);break e;case 1:p=pp(null,p,M,c,k);break e;case 11:p=up(null,p,M,c,k);break e;case 14:p=Fl(null,p,M,hr(M.type,c),k);break e}throw Error(r(306,M,""))}return p;case 0:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),qd(c,p,M,F,k);case 1:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),pp(c,p,M,F,k);case 3:e:{if(Gd(p),c===null)throw Error(r(387));M=p.pendingProps,K=p.memoizedState,F=K.element,Nd(c,p),Yc(p,M,null,k);var de=p.memoizedState;if(M=de.element,K.isDehydrated)if(K={element:M,isDehydrated:!1,cache:de.cache,pendingSuspenseBoundaries:de.pendingSuspenseBoundaries,transitions:de.transitions},p.updateQueue.baseState=K,p.memoizedState=K,p.flags&256){F=Va(Error(r(423)),p),p=mp(c,p,M,k,F);break e}else if(M!==F){F=Va(Error(r(424)),p),p=mp(c,p,M,k,F);break e}else for(Ns=_o(p.stateNode.containerInfo.firstChild),gs=p,Kn=!0,xs=null,k=kd(p,null,M,k),p.child=k;k;)k.flags=k.flags&-3|4096,k=k.sibling;else{if(ea(),M===F){p=Zi(c,p,k);break e}Or(c,p,M,k)}p=p.child}return p;case 5:return Lf(p),c===null&&vd(p),M=p.type,F=p.pendingProps,K=c!==null?c.memoizedProps:null,de=F.children,cd(M,F)?de=null:K!==null&&cd(M,K)&&(p.flags|=32),fp(c,p),Or(c,p,de,k),p.child;case 6:return c===null&&vd(p),null;case 13:return gp(c,p,k);case 4:return Td(p,p.stateNode.containerInfo),M=p.pendingProps,c===null?p.child=Ua(p,null,M,k):Or(c,p,M,k),p.child;case 11:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),up(c,p,M,F,k);case 7:return Or(c,p,p.pendingProps,k),p.child;case 8:return Or(c,p,p.pendingProps.children,k),p.child;case 12:return Or(c,p,p.pendingProps.children,k),p.child;case 10:e:{if(M=p.type._context,F=p.pendingProps,K=p.memoizedProps,de=F.value,In(ta,M._currentValue),M._currentValue=de,K!==null)if(li(K.value,de)){if(K.children===F.children&&!hs.current){p=Zi(c,p,k);break e}}else for(K=p.child,K!==null&&(K.return=p);K!==null;){var _e=K.dependencies;if(_e!==null){de=K.child;for(var $e=_e.firstContext;$e!==null;){if($e.context===M){if(K.tag===1){$e=Ji(-1,k&-k),$e.tag=2;var qe=K.updateQueue;if(qe!==null){qe=qe.shared;var at=qe.pending;at===null?$e.next=$e:($e.next=at.next,at.next=$e),qe.pending=$e}}K.lanes|=k,$e=K.alternate,$e!==null&&($e.lanes|=k),Of(K.return,k,p),_e.lanes|=k;break}$e=$e.next}}else if(K.tag===10)de=K.type===p.type?null:K.child;else if(K.tag===18){if(de=K.return,de===null)throw Error(r(341));de.lanes|=k,_e=de.alternate,_e!==null&&(_e.lanes|=k),Of(de,k,p),de=K.sibling}else de=K.child;if(de!==null)de.return=K;else for(de=K;de!==null;){if(de===p){de=null;break}if(K=de.sibling,K!==null){K.return=de.return,de=K;break}de=de.return}K=de}Or(c,p,F.children,k),p=p.child}return p;case 9:return F=p.type,M=p.pendingProps.children,Ha(p,k),F=Us(F),M=M(F),p.flags|=1,Or(c,p,M,k),p.child;case 14:return M=p.type,F=hr(M,p.pendingProps),F=hr(M.type,F),Fl(c,p,M,F,k);case 15:return dp(c,p,p.type,p.pendingProps,k);case 17:return M=p.type,F=p.pendingProps,F=p.elementType===M?F:hr(M,F),ru(c,p),p.tag=1,fs(M)?(c=!0,Uc(p)):c=!1,Ha(p,k),ip(p,M,F),Ud(p,M,F,k),Vd(null,p,M,!0,c,k);case 19:return Jd(c,p,k);case 22:return hp(c,p,k)}throw Error(r(156,p.tag))};function Pp(c,p){return Go(c,p)}function yv(c,p,k,M){this.tag=c,this.key=k,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=p,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=M,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function $s(c,p,k,M){return new yv(c,p,k,M)}function yh(c){return c=c.prototype,!(!c||!c.isReactComponent)}function Jg(c){if(typeof c=="function")return yh(c)?1:0;if(c!=null){if(c=c.$$typeof,c===Y)return 11;if(c===te)return 14}return 2}function Mo(c,p){var k=c.alternate;return k===null?(k=$s(c.tag,p,c.key,c.mode),k.elementType=c.elementType,k.type=c.type,k.stateNode=c.stateNode,k.alternate=c,c.alternate=k):(k.pendingProps=p,k.type=c.type,k.flags=0,k.subtreeFlags=0,k.deletions=null),k.flags=c.flags&14680064,k.childLanes=c.childLanes,k.lanes=c.lanes,k.child=c.child,k.memoizedProps=c.memoizedProps,k.memoizedState=c.memoizedState,k.updateQueue=c.updateQueue,p=c.dependencies,k.dependencies=p===null?null:{lanes:p.lanes,firstContext:p.firstContext},k.sibling=c.sibling,k.index=c.index,k.ref=c.ref,k}function pu(c,p,k,M,F,K){var de=2;if(M=c,typeof c=="function")yh(c)&&(de=1);else if(typeof c=="string")de=5;else e:switch(c){case O:return Ja(k.children,F,K,p);case I:de=8,F|=8;break;case z:return c=$s(12,k,p,F|2),c.elementType=z,c.lanes=K,c;case V:return c=$s(13,k,p,F),c.elementType=V,c.lanes=K,c;case H:return c=$s(19,k,p,F),c.elementType=H,c.lanes=K,c;case oe:return mu(k,F,K,p);default:if(typeof c=="object"&&c!==null)switch(c.$$typeof){case U:de=10;break e;case W:de=9;break e;case Y:de=11;break e;case te:de=14;break e;case ae:de=16,M=null;break e}throw Error(r(130,c==null?c:typeof c,""))}return p=$s(de,k,p,F),p.elementType=c,p.type=M,p.lanes=K,p}function Ja(c,p,k,M){return c=$s(7,c,M,p),c.lanes=k,c}function mu(c,p,k,M){return c=$s(22,c,M,p),c.elementType=oe,c.lanes=k,c.stateNode={isHidden:!1},c}function vh(c,p,k){return c=$s(6,c,null,p),c.lanes=k,c}function bh(c,p,k){return p=$s(4,c.children!==null?c.children:[],c.key,p),p.lanes=k,p.stateNode={containerInfo:c.containerInfo,pendingChildren:null,implementation:c.implementation},p}function vv(c,p,k,M,F){this.tag=p,this.containerInfo=c,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ke(0),this.expirationTimes=Ke(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ke(0),this.identifierPrefix=M,this.onRecoverableError=F,this.mutableSourceEagerHydrationData=null}function wh(c,p,k,M,F,K,de,_e,$e){return c=new vv(c,p,k,_e,$e),p===1?(p=1,K===!0&&(p|=8)):p=0,K=$s(3,null,null,p),c.current=K,K.stateNode=c,K.memoizedState={element:M,isDehydrated:k,cache:null,transitions:null,pendingSuspenseBoundaries:null},Xc(K),c}function bv(c,p,k){var M=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:R,key:M==null?null:""+M,children:c,containerInfo:p,implementation:k}}function Dp(c){if(!c)return ko;c=c._reactInternals;e:{if(Ct(c)!==c||c.tag!==1)throw Error(r(170));var p=c;do{switch(p.tag){case 3:p=p.stateNode.context;break e;case 1:if(fs(p.type)){p=p.stateNode.__reactInternalMemoizedMergedChildContext;break e}}p=p.return}while(p!==null);throw Error(r(171))}if(c.tag===1){var k=c.type;if(fs(k))return Rf(c,k,p)}return p}function Qg(c,p,k,M,F,K,de,_e,$e){return c=wh(k,M,!0,c,F,K,de,_e,$e),c.context=Dp(null),k=c.current,M=es(),F=Ao(k),K=Ji(M,F),K.callback=p??null,jo(k,K,F),c.current.lanes=F,qr(c,F,M),bs(c,M),c}function gu(c,p,k,M){var F=p.current,K=es(),de=Ao(F);return k=Dp(k),p.context===null?p.context=k:p.pendingContext=k,p=Ji(K,de),p.payload={element:c},M=M===void 0?null:M,M!==null&&(p.callback=M),c=jo(F,p,de),c!==null&&(fi(c,F,de,K),Ol(c,F,de)),de}function xu(c){if(c=c.current,!c.child)return null;switch(c.child.tag){case 5:return c.child.stateNode;default:return c.child.stateNode}}function Op(c,p){if(c=c.memoizedState,c!==null&&c.dehydrated!==null){var k=c.retryLane;c.retryLane=k!==0&&k<p?k:p}}function _h(c,p){Op(c,p),(c=c.alternate)&&Op(c,p)}function Zg(){return null}var ex=typeof reportError=="function"?reportError:function(c){console.error(c)};function kh(c){this._internalRoot=c}Qa.prototype.render=kh.prototype.render=function(c){var p=this._internalRoot;if(p===null)throw Error(r(409));gu(c,p,null,null)},Qa.prototype.unmount=kh.prototype.unmount=function(){var c=this._internalRoot;if(c!==null){this._internalRoot=null;var p=c.containerInfo;ua(function(){gu(null,c,null,null)}),p[Ri]=null}};function Qa(c){this._internalRoot=c}Qa.prototype.unstable_scheduleHydration=function(c){if(c){var p=$n();c={blockedOn:null,target:c,priority:p};for(var k=0;k<ri.length&&p!==0&&p<ri[k].priority;k++);ri.splice(k,0,c),k===0&&bl(c)}};function Sh(c){return!(!c||c.nodeType!==1&&c.nodeType!==9&&c.nodeType!==11)}function yu(c){return!(!c||c.nodeType!==1&&c.nodeType!==9&&c.nodeType!==11&&(c.nodeType!==8||c.nodeValue!==" react-mount-point-unstable "))}function tx(){}function nx(c,p,k,M,F){if(F){if(typeof M=="function"){var K=M;M=function(){var qe=xu(de);K.call(qe)}}var de=Qg(p,M,c,0,null,!1,!1,"",tx);return c._reactRootContainer=de,c[Ri]=de.current,Rl(c.nodeType===8?c.parentNode:c),ua(),de}for(;F=c.lastChild;)c.removeChild(F);if(typeof M=="function"){var _e=M;M=function(){var qe=xu($e);_e.call(qe)}}var $e=wh(c,0,!1,null,null,!1,!1,"",tx);return c._reactRootContainer=$e,c[Ri]=$e.current,Rl(c.nodeType===8?c.parentNode:c),ua(function(){gu(p,$e,k,M)}),$e}function Xl(c,p,k,M,F){var K=k._reactRootContainer;if(K){var de=K;if(typeof F=="function"){var _e=F;F=function(){var $e=xu(de);_e.call($e)}}gu(p,de,c,F)}else de=nx(k,p,c,F,M);return xu(de)}Et=function(c){switch(c.tag){case 3:var p=c.stateNode;if(p.current.memoizedState.isDehydrated){var k=Ps(p.pendingLanes);k!==0&&(be(p,k|1),bs(p,kn()),(gn&6)===0&&(Xa=kn()+500,So()))}break;case 13:ua(function(){var M=Yi(c,1);if(M!==null){var F=es();fi(M,c,1,F)}}),_h(c,1)}},en=function(c){if(c.tag===13){var p=Yi(c,134217728);if(p!==null){var k=es();fi(p,c,134217728,k)}_h(c,134217728)}},ln=function(c){if(c.tag===13){var p=Ao(c),k=Yi(c,p);if(k!==null){var M=es();fi(k,c,p,M)}_h(c,p)}},$n=function(){return Pe},En=function(c,p){var k=Pe;try{return Pe=c,p()}finally{Pe=k}},bi=function(c,p,k){switch(p){case"input":if(st(c,k),p=k.name,k.type==="radio"&&p!=null){for(k=c;k.parentNode;)k=k.parentNode;for(k=k.querySelectorAll("input[name="+JSON.stringify(""+p)+'][type="radio"]'),p=0;p<k.length;p++){var M=k[p];if(M!==c&&M.form===c.form){var F=Bc(M);if(!F)throw Error(r(90));lt(M),st(M,F)}}}break;case"textarea":On(c,k);break;case"select":p=k.value,p!=null&&yt(c,!!k.multiple,p,!1)}},Is=mh,Ar=ua;var Lp={usingClientEntryPoint:!1,Events:[Pl,Oa,Bc,wi,_i,mh]},pi={findFiberByHostInstance:Jo,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},rx={bundleType:pi.bundleType,version:pi.version,rendererPackageName:pi.rendererPackageName,rendererConfig:pi.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:N.ReactCurrentDispatcher,findHostInstanceByFiber:function(c){return c=po(c),c===null?null:c.stateNode},findFiberByHostInstance:pi.findFiberByHostInstance||Zg,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Yl=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Yl.isDisabled&&Yl.supportsFiber)try{cs=Yl.inject(rx),gr=Yl}catch{}}return mi.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Lp,mi.createPortal=function(c,p){var k=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!Sh(p))throw Error(r(200));return bv(c,p,null,k)},mi.createRoot=function(c,p){if(!Sh(c))throw Error(r(299));var k=!1,M="",F=ex;return p!=null&&(p.unstable_strictMode===!0&&(k=!0),p.identifierPrefix!==void 0&&(M=p.identifierPrefix),p.onRecoverableError!==void 0&&(F=p.onRecoverableError)),p=wh(c,1,!1,null,null,k,!1,M,F),c[Ri]=p.current,Rl(c.nodeType===8?c.parentNode:c),new kh(p)},mi.findDOMNode=function(c){if(c==null)return null;if(c.nodeType===1)return c;var p=c._reactInternals;if(p===void 0)throw typeof c.render=="function"?Error(r(188)):(c=Object.keys(c).join(","),Error(r(268,c)));return c=po(p),c=c===null?null:c.stateNode,c},mi.flushSync=function(c){return ua(c)},mi.hydrate=function(c,p,k){if(!yu(p))throw Error(r(200));return Xl(null,c,p,!0,k)},mi.hydrateRoot=function(c,p,k){if(!Sh(c))throw Error(r(405));var M=k!=null&&k.hydratedSources||null,F=!1,K="",de=ex;if(k!=null&&(k.unstable_strictMode===!0&&(F=!0),k.identifierPrefix!==void 0&&(K=k.identifierPrefix),k.onRecoverableError!==void 0&&(de=k.onRecoverableError)),p=Qg(p,null,c,1,k??null,F,!1,K,de),c[Ri]=p.current,Rl(c),M)for(c=0;c<M.length;c++)k=M[c],F=k._getVersion,F=F(k._source),p.mutableSourceEagerHydrationData==null?p.mutableSourceEagerHydrationData=[k,F]:p.mutableSourceEagerHydrationData.push(k,F);return new Qa(p)},mi.render=function(c,p,k){if(!yu(p))throw Error(r(200));return Xl(null,c,p,!1,k)},mi.unmountComponentAtNode=function(c){if(!yu(c))throw Error(r(40));return c._reactRootContainer?(ua(function(){Xl(null,null,c,!1,function(){c._reactRootContainer=null,c[Ri]=null})}),!0):!1},mi.unstable_batchedUpdates=mh,mi.unstable_renderSubtreeIntoContainer=function(c,p,k,M){if(!yu(k))throw Error(r(200));if(c==null||c._reactInternals===void 0)throw Error(r(38));return Xl(c,p,k,!1,M)},mi.version="18.3.1-next-f1338f8080-20240426",mi}var n_;function _2(){if(n_)return Cv.exports;n_=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(n){console.error(n)}}return e(),Cv.exports=jN(),Cv.exports}var r_;function EN(){if(r_)return ix;r_=1;var e=_2();return ix.createRoot=e.createRoot,ix.hydrateRoot=e.hydrateRoot,ix}var NN=EN();const TN=Gy(NN);var L=Xw();const co=Gy(L),s_=e=>{let n;const r=new Set,i=(m,x)=>{const g=typeof m=="function"?m(n):m;if(!Object.is(g,n)){const v=n;n=x??(typeof g!="object"||g===null)?g:Object.assign({},n,g),r.forEach(S=>S(n,v))}},o=()=>n,u={setState:i,getState:o,getInitialState:()=>h,subscribe:m=>(r.add(m),()=>r.delete(m))},h=n=e(i,o,u);return u},$N=(e=>e?s_(e):s_),AN=e=>e;function RN(e,n=AN){const r=co.useSyncExternalStore(e.subscribe,co.useCallback(()=>n(e.getState()),[e,n]),co.useCallback(()=>n(e.getInitialState()),[e,n]));return co.useDebugValue(r),r}const i_=e=>{const n=$N(e),r=i=>RN(n,i);return Object.assign(r,n),r},cr=(e=>e?i_(e):i_);function Ho(e){return"'"+e.replace(/'/g,"'\\''")+"'"}const Nv=({sessionId:e})=>`claude --dangerously-skip-permissions --session-id ${Ho(e)}`,o_=({sessionId:e})=>`claude --session-id ${Ho(e)}`,MN=()=>"claude --resume",k2=[{id:"sm-dangerous",label:"Session Manager (skip perms)",description:"claude --dangerously-skip-permissions in this project",category:"build",cwd:"app-cwd",command:Nv},{id:"sm-safe",label:"Session Manager (safe)",description:"claude with normal permission prompts in this project",category:"build",cwd:"app-cwd",command:o_},{id:"home-dangerous",label:"Home (skip perms)",description:"claude --dangerously-skip-permissions in ~",category:"build",cwd:"home",command:Nv},{id:"pick-dangerous",label:"Pick directory (skip perms)…",description:"Choose a folder, launch claude --dangerously-skip-permissions",category:"build",cwd:"pick",command:Nv},{id:"pick-safe",label:"Pick directory (safe)…",description:"Choose a folder, launch claude with normal prompts",category:"build",cwd:"pick",command:o_},{id:"pick-resume",label:"Pick directory + resume…",description:"Choose a folder, then pick a past session to resume",category:"build",cwd:"pick",command:MN},{id:"pick-shell",label:"Pick directory (shell only)…",description:"Bare interactive shell, no claude auto-launch",category:"build",cwd:"pick",command:null}];let to=null;async function IN(){if(to)return to;try{const e=await window.api.app.engageRulesPath();if(!e)return to=[],to;const n=await window.api.config.readJson(e);if(!n.exists||n.parseError||!n.data)return to=[],to;const r=n.data;if(!r.presets||!Array.isArray(r.presets))return to=[],to;const i=r.projectPath;return to=r.presets.map(o=>({id:o.id,label:o.label,description:o.description,category:"engage",cwd:i,platform:o.platform,pipeline:o.pipeline,rules:o.rules,command:()=>`cd ${Ho(i)} && ${o.cliEntry}`})),to}catch(e){return console.warn("[presets] Failed to load engage presets:",e),to=[],to}}async function S2(e){const n=k2.find(i=>i.id===e);return n||((await IN()).find(i=>i.id===e)??null)}async function a_(e){return e.cwd==="app-cwd"?window.api.app.cwd():e.cwd==="home"?window.api.app.homeDir():e.cwd==="pick"?window.api.app.pickDirectory():e.cwd}function C2(e,n){return e.command?e.command(n):null}const Yw=["opus","sonnet","haiku"],j2="sm.rawSessionModel",PN="opus";function DN(e){return Yw.includes(e)}function ON(){try{const e=localStorage.getItem(j2);if(e&&DN(e))return e}catch{}return PN}let zh=ON();const Pb=new Set;function E2(){return zh}function LN(e){if(e!==zh){zh=e;try{localStorage.setItem(j2,e)}catch{}Pb.forEach(n=>n(e))}}function zN(){const[e,n]=L.useState(zh);L.useEffect(()=>{const i=o=>n(o);return Pb.add(i),zh!==e&&n(zh),()=>{Pb.delete(i)}},[]);const r=L.useCallback(i=>LN(i),[]);return{model:e,setModel:r}}async function N2(e,n){const r=await window.api.transcripts.pathFor(e,n);return window.api.config.exists(r)}const BN=5,l_=100,FN=5e3,Db=new Map;function c_(e){const n=Db.get(e);n!==void 0&&(clearTimeout(n),Db.delete(e))}function UN(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`t-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}const Eu=cr((e,n)=>({toasts:[],history:[],unreadCount:0,show:(r,i)=>{const o=UN(),l=Date.now();e(u=>{const h=[...u.toasts,{id:o,kind:r,message:i,createdAt:l}];for(;h.length>BN;){const g=h.shift();g&&c_(g.id)}const x=[{id:o,kind:r,message:i,createdAt:l,read:!1},...u.history];return x.length>l_&&(x.length=l_),{toasts:h,history:x,unreadCount:u.unreadCount+1}});const d=setTimeout(()=>n().dismiss(o),FN);return Db.set(o,d),o},dismiss:r=>{c_(r),e(i=>({toasts:i.toasts.filter(o=>o.id!==r)}))},markAllRead:()=>{e(r=>r.unreadCount===0?r:{history:r.history.map(i=>i.read?i:{...i,read:!0}),unreadCount:0})},clearHistory:()=>{e({history:[],unreadCount:0})},dismissHistoryEntry:r=>{e(i=>{const o=i.history.filter(d=>d.id!==r);if(o.length===i.history.length)return i;const l=i.history.find(d=>d.id===r&&!d.read);return{history:o,unreadCount:l?Math.max(0,i.unreadCount-1):i.unreadCount}})}})),Le={info:e=>Eu.getState().show("info",e),warn:e=>Eu.getState().show("warn",e),error:e=>Eu.getState().show("error",e),fromOutcome:e=>Eu.getState().show(e.kind??(e.ok?"info":"warn"),e.message)},T2=Object.freeze(Object.defineProperty({__proto__:null,toast:Le,useToast:Eu},Symbol.toStringTag,{value:"Module"}));async function HN(e){var n,r;if(typeof window>"u"||typeof((r=(n=window.api)==null?void 0:n.chat)==null?void 0:r.classifyTicket)!="function")return"inline";try{return await window.api.chat.classifyTicket({text:e})==="develop"?"develop":"inline"}catch{return"inline"}}const Nu={turns:[],running:!1,queuedPosition:0,started:!1,stream:"",liveToolUses:[],queue:[],activeTicket:null,ticketHistory:[]},u_=20;function Jw(e,n){const r=[...e,n];return r.length>u_?r.slice(r.length-u_):r}let d_=0;function fl(){return d_+=1,`t${Date.now().toString(36)}-${d_}`}const Gs=cr((e,n)=>({chats:{},hydratedTabs:{},get:r=>n().chats[r]??Nu,hydrate:async({tabId:r,cwd:i,sessionId:o})=>{var l,d,u;if(!n().hydratedTabs[r]&&(e({hydratedTabs:{...n().hydratedTabs,[r]:!0}}),!(typeof window>"u"||!((l=window.api)!=null&&l.exchanges))))try{const h=await window.api.exchanges.list({cwd:i,sessionId:o});if(!h.length)return;const m=[];for(const g of[...h].reverse()){const v=new Date(g.ts).getTime();m.push({id:fl(),role:"user",text:g.prompt,at:v}),m.push({id:fl(),role:"assistant",text:g.result,at:v})}const x=n().chats[r]??Nu;e({chats:{...n().chats,[r]:{...x,turns:[...m,...x.turns],started:!0}}})}catch(h){const m=h instanceof Error?h.message:String(h);(u=(d=window.api)==null?void 0:d.logs)==null||u.write("chat","warn",`exchange hydration failed for tab ${r}: ${m}`)}},send:({tabId:r,sessionId:i,cwd:o,prompt:l})=>{const d=l.trim();if(!d)return;const u=n().chats[r]??Nu;if(u.running){const h={id:crypto.randomUUID(),tabId:r,sessionId:i,cwd:o,text:d,status:"queued",createdAt:Date.now()};e({chats:{...n().chats,[r]:{...u,queue:[...u.queue,h]}}});return}$2({tabId:r,sessionId:i,cwd:o,text:d})},resetThread:r=>{e({chats:{...n().chats,[r]:{...Nu}}})},pushNotice:(r,i)=>{Qw(r,"",i)}}));function zo(e,n){const r=Gs.getState().chats[e]??Nu;Gs.setState({chats:{...Gs.getState().chats,[e]:n(r)}})}function Gx(e,n,r={}){zo(e,i=>{const o=i.activeTicket?Jw(i.ticketHistory??[],{...i.activeTicket,status:"done",completedAt:Date.now()}):i.ticketHistory??[];return{...i,turns:[...i.turns,{...n,toolUses:i.liveToolUses}],running:!1,queuedPosition:0,stream:"",liveToolUses:[],activeTicket:null,ticketHistory:o,...r}}),A2(e)}function $2(e){const{tabId:n,sessionId:r,cwd:i,text:o,promptId:l}=e,d=Gs.getState().chats[n]??Nu,u={id:fl(),role:"user",text:o,at:Date.now()},h=d.activeTicket??{id:l??crypto.randomUUID(),tabId:n,sessionId:r,cwd:i,text:o,status:"running",createdAt:Date.now(),startedAt:Date.now()};Gs.setState({chats:{...Gs.getState().chats,[n]:{...d,turns:[...d.turns,u],running:!0,queuedPosition:0,stream:"",activeTicket:h}}}),N2(i,r).catch(m=>{var g,v;const x=m instanceof Error?m.message:String(m);return(v=(g=window.api)==null?void 0:g.logs)==null||v.write("chat","warn",`transcript-exists check failed for tab ${n}: ${x}`),d.started}).then(m=>window.api.chat.run({tabId:n,sessionId:r,prompt:o,cwd:i,resume:m,promptId:l})).catch(m=>{const x=m instanceof Error?m.message:String(m);R2(n,r,x)})}function A2(e){const n=Gs.getState().chats[e]??Nu;if(n.queue.length===0)return;const[r,...i]=n.queue;zo(e,o=>({...o,queue:i,running:!0,queuedPosition:0,activeTicket:r})),HN(r.text).then(o=>{if(o==="develop"){const d={...r,status:"dispatched-to-prd",completedAt:Date.now()};Qw(e,d.sessionId,`→ dispatched to /develop for PRD decomposition (ticket ${d.id})`),zo(e,u=>({...u,running:!1,queuedPosition:0,activeTicket:null,ticketHistory:Jw(u.ticketHistory??[],d)})),A2(e);return}const l={...r,status:"running",startedAt:Date.now()};zo(e,d=>({...d,activeTicket:l})),$2({tabId:l.tabId,sessionId:l.sessionId,cwd:l.cwd,text:l.text,promptId:l.id})})}function R2(e,n,r){zo(e,i=>i.activeTicket?{...i,activeTicket:null,ticketHistory:Jw(i.ticketHistory??[],{...i.activeTicket,status:"failed",completedAt:Date.now()})}:i),Gx(e,{id:fl(),role:"error",text:r,at:Date.now()}),Le.error(r)}function Qw(e,n,r){zo(e,i=>({...i,turns:[...i.turns,{id:fl(),role:"notice",text:r,at:Date.now()}]}))}var w2;typeof window<"u"&&((w2=window.api)!=null&&w2.chat)&&(window.api.chat.onQueued(({tabId:e,position:n})=>{zo(e,r=>({...r,running:!0,queuedPosition:n}))}),window.api.chat.onRunStarted(({tabId:e})=>{zo(e,n=>({...n,running:!0,started:!0,queuedPosition:0,stream:"",liveToolUses:[]}))}),window.api.chat.onOutput(({tabId:e,delta:n})=>{zo(e,r=>({...r,stream:r.stream+n}))}),window.api.chat.onToolUse(({tabId:e,id:n,kind:r,label:i})=>{zo(e,o=>({...o,liveToolUses:[...o.liveToolUses,{id:n,kind:r,label:i}]}))}),window.api.chat.onComplete(({tabId:e,finalMessage:n})=>{Gx(e,{id:fl(),role:"assistant",text:n,at:Date.now()})}),window.api.chat.onNeedsInput(({tabId:e,questions:n,answerBody:r})=>{if(r&&r.trim()){zo(e,i=>({...i,turns:[...i.turns,{id:fl(),role:"assistant",text:r,at:Date.now(),toolUses:i.liveToolUses}],liveToolUses:[]})),Gx(e,{id:fl(),role:"question",text:n.join(`
|
|
42
42
|
`),questions:n,at:Date.now()});return}Gx(e,{id:fl(),role:"question",text:n.join(`
|
|
43
|
-
`),questions:n,at:Date.now()})}),window.api.chat.onError(({tabId:e,sessionId:n,message:r})=>{R2(e,n,r)}),window.api.chat.onNotice(({tabId:e,sessionId:n,message:r})=>{Qw(e,n,r)}));function WN(e){const n=e.split("/").filter(Boolean);return n[n.length-1]||e}async function M2(e,n=!1,r=E2()){let i=!n;i&&(i=await N2(e.cwd,e.sessionId));const o=n&&!i?crypto.randomUUID():e.sessionId,l=i?`claude --dangerously-skip-permissions --resume ${Ho(o)} --model ${r}`:`claude --dangerously-skip-permissions --session-id ${Ho(o)} --model ${r}`;return{sessionId:o,startupCommand:l}}const bt=cr((e,n)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(r,i)=>{e(o=>({pendingRawCommand:{...o.pendingRawCommand,[r]:i}}))},consumeRawCommand:r=>{const i=n().pendingRawCommand[r];return i===void 0?null:(e(o=>{const l={...o.pendingRawCommand};return delete l[r],{pendingRawCommand:l}}),i)},addTab:({id:r,cwd:i,startupCommand:o,presetId:l=null,label:d})=>{const u=r??crypto.randomUUID();if(n().tabs.find(x=>x.id===u))return e({activeTabId:u}),u;const m={id:u,sessionId:u,label:d??WN(i),cwd:i,pid:null,status:"spawning",exitCode:null,startupCommand:o,presetId:l,generation:0};return e({tabs:[...n().tabs,m],activeTabId:u}),u},setTabRunning:(r,i)=>e({tabs:n().tabs.map(o=>o.id===r?{...o,pid:i,status:"running"}:o)}),setTabExited:(r,i)=>e({tabs:n().tabs.map(o=>o.id===r?{...o,status:"exited",exitCode:i}:o)}),closeTab:r=>{var l;window.api.pty.kill(r),window.api.watchers.killTab(r).catch(()=>{}),window.api.transcripts.closeTab(r).catch(()=>{});const i=n().tabs.filter(d=>d.id!==r),o=n().activeTabId===r?((l=i[i.length-1])==null?void 0:l.id)??null:n().activeTabId;e({tabs:i,activeTabId:o})},setActive:r=>e({activeTabId:r}),restartTab:r=>{const i=n().tabs.find(d=>d.id===r);if(!i)return;window.api.pty.kill(r);const o=crypto.randomUUID(),l=d=>{e({tabs:n().tabs.map(u=>u.id===r?{...u,sessionId:o,pid:null,status:"spawning",exitCode:null,startupCommand:d,generation:u.generation+1}:u)})};i.presetId?S2(i.presetId).then(d=>{l(d?C2(d,{sessionId:o,cwd:i.cwd}):`claude --dangerously-skip-permissions --session-id ${Ho(o)}`)}):l(`claude --dangerously-skip-permissions --session-id ${Ho(o)}`)},reorderTab:(r,i)=>{const o=[...n().tabs];if(r<0||r>=o.length||i<0||i>=o.length||r===i)return;const[l]=o.splice(r,1);o.splice(i,0,l),e({tabs:o})},restoreTabs:(r,i)=>e({tabs:r,activeTabId:i,hydrated:!0}),wakeTab:async(r,i)=>{var u;const o=n().tabs.find(h=>h.id===r);if(!o||o.status!=="dormant")return;(u=gi.getState().chats[r])!=null&&u.running&&(await window.api.chat.cancel(r),Le.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:l,startupCommand:d}=await M2({cwd:o.cwd,sessionId:o.sessionId},!1,i??E2());e({tabs:n().tabs.map(h=>h.id===r?{...h,sessionId:l,status:"spawning",startupCommand:d,generation:h.generation+1}:h)})},sleepTab:r=>{const i=n().tabs.find(o=>o.id===r);!i||i.status==="dormant"||(window.api.pty.kill(r),e({tabs:n().tabs.map(o=>o.id===r?{...o,pid:null,status:"dormant"}:o)}))},newSession:r=>{n().tabs.find(o=>o.id===r)&&e({tabs:n().tabs.map(o=>o.id===r?{...o,sessionId:crypto.randomUUID()}:o)})}}));async function Ob(){var r;if(bt.getState().hydrated)return;try{const{tabs:i,activeTabId:o,freshStart:l}=await window.api.sessions.load();if(i.length>0){const u=(await Promise.all(i.map(async m=>{try{const{sessionId:x}=await M2(m,l);return{id:m.id,sessionId:x,cwd:m.cwd,label:m.label,presetId:m.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(x){return console.warn("[sessions] dropping malformed persisted tab:",m==null?void 0:m.id,x),null}}))).filter(m=>m!==null),h=o&&u.find(m=>m.id===o)?o:((r=u[0])==null?void 0:r.id)??null;bt.getState().restoreTabs(u,h)}else bt.setState({hydrated:!0})}catch(i){console.warn("[sessions] hydrate failed:",i),bt.setState({hydrated:!0})}const e=()=>{const{tabs:i,activeTabId:o}=bt.getState(),l=i.map(d=>({id:d.id,sessionId:d.sessionId,cwd:d.cwd,label:d.label,presetId:d.presetId}));window.api.sessions.save({tabs:l,activeTabId:o}).catch(d=>{console.warn("[sessions] save failed:",d)})};let n=null;bt.subscribe((i,o)=>{i.hydrated&&(i.tabs===o.tabs&&i.activeTabId===o.activeTabId||(n!==null&&window.clearTimeout(n),n=window.setTimeout(e,200)))}),e()}const qN=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:Ob,useSessions:bt},Symbol.toStringTag,{value:"Module"})),h_=200,VN=/\x1b\[[0-9;]*m/g;function GN(e){return e.replace(VN,"")}const Tm=cr((e,n)=>({watchers:{},initialized:!1,init:()=>{n().initialized||(e({initialized:!0}),window.api.watchers.onLine(r=>n().ingestLine(r)),window.api.watchers.onClosed(({watcherId:r})=>n().closed(r)))},add:async({tabId:r,label:i,command:o,cwd:l})=>{try{const d=await window.api.watchers.add({tabId:r,label:i,command:o,cwd:l??null}),u={watcherId:d.watcherId,tabId:d.tabId,label:d.label,command:d.command,cwd:d.cwd,pid:d.pid,startedAt:d.startedAt,lineCount:0,lines:[],lastLineAt:null};return e({watchers:{...n().watchers,[u.watcherId]:u}}),u}catch(d){return console.error("[watchers] add failed:",d),Le.error("Failed to add watcher"),null}},remove:async r=>{try{await window.api.watchers.remove(r)}catch(o){console.error("[watchers] remove failed:",o);const l=o instanceof Error?o.message:String(o);Le.error(`Could not remove watcher: ${l}`)}const i={...n().watchers};delete i[r],e({watchers:i})},watchersForTab:r=>Object.values(n().watchers).filter(i=>i.tabId===r),ingestLine:r=>{const i=n().watchers[r.watcherId];if(!i)return;const o=GN(r.line),l=i.lines.length>=h_?[...i.lines.slice(i.lines.length-h_+1),{line:o,ts:r.ts}]:[...i.lines,{line:o,ts:r.ts}];e({watchers:{...n().watchers,[r.watcherId]:{...i,lines:l,lineCount:i.lineCount+1,lastLineAt:r.ts}}})},closed:r=>{if(!n().watchers[r])return;const i={...n().watchers};delete i[r],e({watchers:i})}})),KN="~/.claude/session-manager/browser/history.json",f_="~/.claude/session-manager/browser/bookmarks.json",XN=.25,YN=3,p_=.1,m_=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let g_=0;function JN(){const e=m_[g_%m_.length];return g_+=1,e}const hy=new Map;function QN(e){if(hy.has(e))return;const n=window.api.browser.onNavState(e,r=>{Mt.setState(i=>({tabs:i.tabs.map(o=>o.viewId===e?{...o,url:r.url,title:r.title||o.title,canGoBack:r.canGoBack,canGoForward:r.canGoForward,loading:r.loading,isSecure:r.isSecure}:o)}))});hy.set(e,n)}function ZN(e){const n=hy.get(e);n&&(n(),hy.delete(e))}const Lb=new Map;let Kx=null;function x_(e){const n=Lb.get(e);n&&(n(),Lb.delete(e))}function y_(){Kx&&(clearInterval(Kx),Kx=null)}const zb=new Map;function Tv(e){const n=zb.get(e);n&&(n(),zb.delete(e))}const Mt=cr((e,n)=>({tabs:[],activeTabId:null,openTab:r=>{const i=crypto.randomUUID(),o=i,l={id:i,viewId:o,title:"New Tab",url:(r==null?void 0:r.url)??"about:blank",color:(r==null?void 0:r.color)??JN(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return e(d=>({tabs:[...d.tabs,l],activeTabId:i})),QN(o),window.api.browser.create({viewId:o,partition:"persist:browser"}).then(()=>{r!=null&&r.url&&window.api.browser.navigate({viewId:o,url:r.url}).catch(()=>{})}).catch(d=>{var h,m;const u=d instanceof Error?d.message:String(d);(m=(h=window.api)==null?void 0:h.logs)==null||m.write("browser","error",`browser:create failed for viewId ${o}: ${u}`)}),i},closeTab:r=>{const i=n().tabs.find(o=>o.id===r);i&&(ZN(i.viewId),Tv(i.viewId),window.api.browser.destroy(i.viewId).catch(()=>{}),e(o=>{const l=o.tabs.filter(u=>u.id!==r),d=o.activeTabId===r?l.length?l[l.length-1].id:null:o.activeTabId;return{tabs:l,activeTabId:d}}))},setActive:r=>{e({activeTabId:r})},navigate:(r,i)=>{const o=n().tabs.find(l=>l.id===r);o&&window.api.browser.navigate({viewId:o.viewId,url:i}).catch(()=>{})},back:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.back(i.viewId).catch(()=>{})},forward:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.forward(i.viewId).catch(()=>{})},reload:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.reload(i.viewId).catch(()=>{})},stop:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.stop(i.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:r=>e(i=>({mode:r,captured:r==="capture"?i.captured:null})),setCaptureMode:r=>e({captureMode:r,captured:null}),onVerb:r=>{const{mode:i}=n();if(r==="shot"){e({mode:"capture",captureMode:"shot",captured:null});return}if(i===r){e({mode:"browse",captured:r==="capture"?null:n().captured});return}e({mode:r,captureMode:r==="capture"?"agent":n().captureMode,captured:r==="capture"?n().captured:null})},captured:null,capture:async r=>{const{activeTabId:i,tabs:o,captureMode:l}=n(),d=o.find(h=>h.id===i);if(!d)throw new Error("No active browser tab");if(l==="shot"){const h=await window.api.browser.captureShot(d.viewId);if(!h.ok)throw new Error(h.error);e({captured:{mode:l,url:h.url,title:h.title,dataUrl:h.dataUrl,at:Date.now()}});return}if(!r||!r.length)throw new Error("No element selected");const u=await window.api.browser.capture({viewId:d.viewId,selectors:r,mode:l});if(!u.ok)throw new Error(u.error);e({captured:{mode:l,url:d.url,title:d.title,text:u.text,meta:u.meta,selectors:r,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:r=>{if(n().recorderActive)return;e({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(r).catch(()=>{}),x_(r);const i=window.api.browser.onRecordStep(r,o=>{Mt.getState().recording&&Mt.setState(l=>({recorderSteps:[...l.recorderSteps,o]}))});Lb.set(r,i),y_(),Kx=setInterval(()=>{Mt.getState().recording&&Mt.setState(o=>({recorderElapsedSec:o.recorderElapsedSec+1}))},1e3)},stopRecording:r=>{n().recorderActive&&(window.api.browser.recordStop(r).catch(()=>{}),x_(r),y_(),e({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{n().recorderActive&&e(r=>({recording:!r.recording}))},toggleStepVariable:r=>{e(i=>({recorderSteps:i.recorderSteps.map(o=>o.n===r?{...o,variable:o.variable?null:o.variableSuggestion||"value"}:o)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!n().bookmarksHydrated)try{const r=await window.api.config.readJson(f_),i=r.exists&&Array.isArray(r.data)?r.data:[];e({bookmarks:i,bookmarksHydrated:!0})}catch{e({bookmarksHydrated:!0})}},toggleBookmark:r=>{const i=n().tabs.find(u=>u.id===r);if(!i||!i.url||i.url==="about:blank")return;const o=n().bookmarks,d=o.some(u=>u.url===i.url)?o.filter(u=>u.url!==i.url):[{url:i.url,title:i.title,ts:Date.now()},...o];e({bookmarks:d}),window.api.config.writeJson(f_,d).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const r=await window.api.config.readJson(KN),i=r.exists&&Array.isArray(r.data)?r.data:[];e({historyEntries:i})}catch{}},setZoom:(r,i)=>{const o=n().tabs.find(d=>d.id===r);if(!o)return;const l=Math.min(YN,Math.max(XN,i));e(d=>({tabs:d.tabs.map(u=>u.id===r?{...u,zoomFactor:l}:u)})),window.api.browser.setZoom({viewId:o.viewId,factor:l}).catch(()=>{})},zoomIn:r=>{const i=n().tabs.find(o=>o.id===r);i&&n().setZoom(r,i.zoomFactor+p_)},zoomOut:r=>{const i=n().tabs.find(o=>o.id===r);i&&n().setZoom(r,i.zoomFactor-p_)},zoomReset:r=>n().setZoom(r,1),findOpen:!1,findText:"",findMatches:null,openFind:r=>{const i=n().tabs.find(l=>l.id===r);if(!i)return;e({findOpen:!0,findText:"",findMatches:null}),Tv(i.viewId);const o=window.api.browser.onFindResult(i.viewId,l=>{Mt.setState({findMatches:l})});zb.set(i.viewId,o)},closeFind:r=>{const i=n().tabs.find(o=>o.id===r);e({findOpen:!1,findText:"",findMatches:null}),i&&(Tv(i.viewId),window.api.browser.stopFind(i.viewId).catch(()=>{}))},setFindText:(r,i)=>{const o=n().tabs.find(l=>l.id===r);if(e({findText:i}),!!o){if(!i){window.api.browser.find({viewId:o.viewId,text:""}).catch(()=>{});return}window.api.browser.find({viewId:o.viewId,text:i,forward:!0}).catch(()=>{})}},findNext:r=>{const i=n().tabs.find(l=>l.id===r),{findText:o}=n();!i||!o||window.api.browser.find({viewId:i.viewId,text:o,forward:!0}).catch(()=>{})},findPrev:r=>{const i=n().tabs.find(l=>l.id===r),{findText:o}=n();!i||!o||window.api.browser.find({viewId:i.viewId,text:o,forward:!1}).catch(()=>{})}})),eT=4,v_=40,b_=6;function tT(e){const{onReorder:n,onActivate:r}=e,i=L.useRef(null),o=L.useRef(null),l=L.useRef(0),d=L.useRef(0),[u,h]=L.useState(!1),[,m]=L.useState(0),x=L.useRef(r);x.current=r;const g=L.useCallback(()=>i.current?Array.from(i.current.querySelectorAll("[data-drag-index]")):[],[]),v=L.useCallback((y,b,_)=>{for(let C=0;C<b.length;C++){const N=b[C].left+b[C].width/2;if(y<N)return C<=_?C:C-1}return b.length-1},[]),S=L.useCallback(()=>{const y=o.current,b=i.current;if(!(y!=null&&y.active)||!b)return;const _=b.getBoundingClientRect(),C=y.startX+y.deltaX,N=C-_.left,$=_.right-C;N<v_?b.scrollLeft-=b_:$<v_&&(b.scrollLeft+=b_),l.current=requestAnimationFrame(S)},[]);L.useEffect(()=>{const y=i.current;if(!y)return;let b=!1;const _=()=>{b||(b=!0,d.current=requestAnimationFrame(()=>{b=!1,m($=>$+1)}))},C=$=>{var U;const R=o.current;if(!R)return;const O=$.clientX-R.startX;if(!R.active&&Math.abs(O)<eT)return;if(!R.active){R.active=!0,R.tabRects=g().map(W=>W.getBoundingClientRect()),h(!0);try{(U=i.current)==null||U.setPointerCapture(R.pointerId)}catch{}l.current=requestAnimationFrame(S)}R.deltaX=O;const I=R.tabRects[R.fromIndex],z=I.left+I.width/2+O;R.currentIndex=v(z,R.tabRects,R.fromIndex),_()},N=$=>{const R=o.current;if(R&&R.pointerId===$.pointerId){cancelAnimationFrame(l.current),cancelAnimationFrame(d.current);try{y.releasePointerCapture(R.pointerId)}catch{}R.active&&R.fromIndex!==R.currentIndex?n(R.fromIndex,R.currentIndex):x.current(R.fromIndex),o.current=null,h(!1),m(O=>O+1)}};return y.addEventListener("pointermove",C),y.addEventListener("pointerup",N),y.addEventListener("pointercancel",N),()=>{y.removeEventListener("pointermove",C),y.removeEventListener("pointerup",N),y.removeEventListener("pointercancel",N),cancelAnimationFrame(l.current),cancelAnimationFrame(d.current)}},[n,g,v,S]);const E=L.useCallback((y,b)=>{y.button!==0||y.target.closest("button")||(o.current={active:!1,fromIndex:b,currentIndex:b,startX:y.clientX,deltaX:0,tabRects:[],pointerId:y.pointerId})},[]);return{getTabDragProps:L.useCallback(y=>{var C;const b=o.current,_={};if(b!=null&&b.active)if(y===b.fromIndex)_.transform=`translateX(${b.deltaX}px) scale(1.03)`,_.zIndex=10,_.opacity=.85,_.boxShadow="0 2px 8px rgba(0,0,0,0.4)",_.position="relative",_.pointerEvents="none";else{const N=b.fromIndex,$=b.currentIndex,O=(((C=b.tabRects[N])==null?void 0:C.width)??0)+4;_.transition="transform 0.15s ease",N<$&&y>N&&y<=$?_.transform=`translateX(-${O}px)`:N>$&&y>=$&&y<N?_.transform=`translateX(${O}px)`:_.transform="translateX(0)"}return{onPointerDown:N=>E(N,y),style:_,"data-drag-index":y}},[E]),isDragging:u,containerRef:i}}const nT=3e4;function rT({onToggleSplitView:e,splitViewActive:n}={}){const r=bt(b=>b.tabs),i=bt(b=>b.activeTabId),o=bt(b=>b.closeTab),l=bt(b=>b.setActive),d=bt(b=>b.reorderTab),u=Tm(b=>b.watchers),h=Mt(b=>b.tabs.length>0),m=i!=null&&h,[x,g]=L.useState(()=>Date.now());L.useEffect(()=>{const b=window.setInterval(()=>g(Date.now()),1e3);return()=>window.clearInterval(b)},[]);const v=b=>{for(const _ of Object.values(u))if(_.tabId===b&&_.lastLineAt&&x-_.lastLineAt<nT)return!0;return!1},{getTabDragProps:S,isDragging:E,containerRef:j}=tT({tabCount:r.length,onReorder:d,onActivate:b=>{const _=r[b];_&&l(_.id)}}),y=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return s.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:[s.jsx("div",{ref:j,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${E?"cursor-grabbing":""}`,children:r.map((b,_)=>{const C=b.id===i,N=S(_),$=y[_%y.length];return s.jsxs("div",{...N,style:N.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 ${E?"":"cursor-grab"} ${C?"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:b.cwd,"aria-current":C?"true":void 0,children:[s.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:$,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:b.status==="spawning"?.55:1}}),s.jsx("span",{className:"truncate max-w-[200px]",children:b.label}),b.status==="spawning"&&s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),v(b.id)&&s.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"}),s.jsx("button",{onClick:R=>{R.stopPropagation(),o(b.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${b.label}`,children:"×"})]},b.id)})}),s.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[m&&e&&s.jsxs("button",{onClick:e,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-line hover:bg-bg-hi/40 ${n?"text-accent border-accent":"text-fg-faint hover:text-fg"}`,title:"Split view: agent terminal + browser","aria-pressed":n??!1,children:[s.jsx("span",{"aria-hidden":"true",children:"⇄"}),s.jsx("span",{children:"Split view"})]}),s.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),s.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.38.1"]})]})]})}function sT(e,n,r){return n?e.map(i=>i.id===n?{...i,lastActivityAt:r}:i):e}function iT(e,n,r){return{tabId:e,sessionUuid:r,cwd:n,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const $m=cr((e,n)=>({tabs:{},refs:{},unsubs:{},subscribe:(r,i,o)=>{const l={...n().refs};if(l[r]=(l[r]??0)+1,e({refs:l}),l[r]>1)return;e({tabs:{...n().tabs,[r]:iT(r,i,o)}});const d=window.api.transcripts.onEvent(r,u=>n().ingest(r,u));e({unsubs:{...n().unsubs,[r]:d}}),window.api.transcripts.subscribe({tabId:r,cwd:i,sessionUuid:o}).then(async u=>{const h=n().tabs[r];if(!h)return;if(!u.ok){const{toast:x}=await Jm(async()=>{const{toast:g}=await Promise.resolve().then(()=>T2);return{toast:g}},void 0,import.meta.url);x.error(`Live view unavailable: ${u.error??"subscribe failed"}`),e({tabs:{...n().tabs,[r]:{...h,path:null}}});return}e({tabs:{...n().tabs,[r]:{...h,path:u.path}}});const m=await window.api.transcripts.buffer(r);for(const x of m)n().ingest(r,x,{replay:!0})}).catch(u=>console.error("[live] transcripts.subscribe failed:",r,u))},unsubscribe:r=>{const i={...n().refs};if(!i[r])return;if(i[r]--,i[r]>0){e({refs:i});return}delete i[r];const o=n().unsubs[r];o==null||o();const l={...n().unsubs};delete l[r];const d={...n().tabs};delete d[r],window.api.transcripts.unsubscribe(r),e({refs:i,unsubs:l,tabs:d})},ingest:(r,i,o)=>{const l=n().tabs[r];if(!l)return;const d=Date.now(),u={...l,lastEventAt:o!=null&&o.replay?l.lastEventAt:d},h=[],m=(x,g)=>x.length>g?x.slice(0,g-1)+"…":x;switch(i.kind){case"todo_write":{const x=Array.isArray(i.data)?i.data:[];u.todos=x,o!=null&&o.replay||h.push({id:0,kind:"todo-update",at:d,label:`Todos · ${x.length} item${x.length!==1?"s":""}`});break}case"tool_use":{const x=i.data,g=x.input,v={};for(const S of["command","file_path","pattern","url","query","subagent_type","description"])g&&S in g&&(v[S]=g[S]);if(u.lastToolUses=[{id:x.id,name:x.name,input:v,at:d},...l.lastToolUses].slice(0,50),!(o!=null&&o.replay)){const S=x.input,E=["Edit","Write","NotebookEdit"].includes(x.name),j=typeof(S==null?void 0:S.file_path)=="string"?S.file_path:void 0,y=typeof(S==null?void 0:S.command)=="string"?S.command:void 0,b=j?j.split("/").pop()??j:y?m(y,28):"";h.push({id:0,kind:"tool-use",at:d,label:b?`${x.name} · ${b}`:x.name,target:j??y,toolName:x.name}),E&&j&&h.push({id:0,kind:"file-edit",at:d,label:`${x.name} · ${m(j.split("/").pop()??j,34)}`,target:j,toolName:x.name})}break}case"plan":{const x=i.data,g=typeof x=="string"?x:(x==null?void 0:x.plan)??JSON.stringify(x);u.plans=[{at:d,content:g??""},...l.plans].slice(0,50),o!=null&&o.replay||h.push({id:0,kind:"plan-revision",at:d,label:"Plan revised"});break}case"agent_spawn":{const x=i.data;u.agents=[{id:x==null?void 0:x.toolUseId,at:d,subagentType:x==null?void 0:x.subagent_type,description:x==null?void 0:x.description,lastActivityAt:d},...l.agents].slice(0,50),o!=null&&o.replay||h.push({id:0,kind:"agent-spawn",at:d,label:x!=null&&x.subagent_type?`Agent: ${m(x.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const x=i.data,g=(l.usage.inputTokens||0)+(l.usage.outputTokens||0),v=x.input_tokens??x.inputTokens??0,S=x.output_tokens??x.outputTokens??0,E=g+v+S;u.usage={inputTokens:(l.usage.inputTokens||0)+v,outputTokens:(l.usage.outputTokens||0)+S,cacheCreationInputTokens:(l.usage.cacheCreationInputTokens||0)+(x.cache_creation_input_tokens??x.cacheCreationInputTokens??0),cacheReadInputTokens:(l.usage.cacheReadInputTokens||0)+(x.cache_read_input_tokens??x.cacheReadInputTokens??0)},!(o!=null&&o.replay)&&Math.floor(E/1e3)>Math.floor(g/1e3)&&h.push({id:0,kind:"usage-tick",at:d,label:`${Math.floor(E/1e3)}k tokens`});break}case"tool_result":{const x=i.data;u.agents=sT(l.agents,x==null?void 0:x.toolUseId,d);break}}if(h.length>0){let x=l.activitySeq;const g=h.map(v=>({...v,id:++x}));u.activitySeq=x,u.activityRing=[...l.activityRing,...g].slice(-32)}e({tabs:{...n().tabs,[r]:u}})}}));function I2(e){const n=$m(o=>o.subscribe),r=$m(o=>o.unsubscribe),i=$m(o=>e?o.tabs[e.id]:void 0);return L.useEffect(()=>{if(e)return n(e.id,e.cwd,e.sessionId),()=>r(e.id)},[e==null?void 0:e.id,e==null?void 0:e.cwd,e==null?void 0:e.sessionId,n,r]),i}var $v={},Fp={},w_;function P2(){if(w_)return Fp;w_=1,Object.defineProperty(Fp,"__esModule",{value:!0}),Fp.baseAssetPath=void 0;const n=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let r="/";return n&&(r=n.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Fp.baseAssetPath=r,Fp}var Up={},__;function Zw(){if(__)return Up;__=1,Object.defineProperty(Up,"__esModule",{value:!0}),Up.defaultModelFetcher=void 0;const e=n=>fetch(n).then(r=>r.arrayBuffer());return Up.defaultModelFetcher=e,Up}var tl={},Hp={},k_;function Qm(){if(k_)return Hp;k_=1,Object.defineProperty(Hp,"__esModule",{value:!0}),Hp.log=void 0;const e=n=>r=>{console.log(`VAD | ${n} >`,r)};return Hp.log={error:e("error"),debug:e("debug"),warn:e("warn")},Hp}var Wp={},S_;function Ky(){if(S_)return Wp;S_=1,Object.defineProperty(Wp,"__esModule",{value:!0}),Wp.Message=void 0;var e;return(function(n){n.AudioFrame="AUDIO_FRAME",n.SpeechStart="SPEECH_START",n.VADMisfire="VAD_MISFIRE",n.SpeechEnd="SPEECH_END",n.SpeechStop="SPEECH_STOP",n.SpeechRealStart="SPEECH_REAL_START",n.FrameProcessed="FRAME_PROCESSED"})(e||(Wp.Message=e={})),Wp}var C_;function e0(){if(C_)return tl;C_=1,Object.defineProperty(tl,"__esModule",{value:!0}),tl.FrameProcessor=tl.validateOptions=tl.defaultFrameProcessorOptions=void 0;const e=Qm(),n=Ky();tl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function r(d){(d.positiveSpeechThreshold<0||d.positiveSpeechThreshold>1)&&e.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(d.negativeSpeechThreshold<0||d.negativeSpeechThreshold>d.positiveSpeechThreshold)&&e.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),d.preSpeechPadMs<0&&e.log.error("preSpeechPadMs should be positive"),d.redemptionMs<0&&e.log.error("redemptionMs should be positive"),d.minSpeechMs<0&&e.log.error("minSpeechMs should be positive")}tl.validateOptions=r;const i=d=>{const u=d.reduce((m,x)=>(m.push(m.at(-1)+x.length),m),[0]),h=new Float32Array(u.at(-1));return d.forEach((m,x)=>{const g=u[x];h.set(m,g)}),h};function o(d,u){const h=Math.floor(d.redemptionMs/u),m=Math.floor(d.preSpeechPadMs/u),x=Math.floor(d.minSpeechMs/u);return{redemptionFrames:h,preSpeechPadFrames:m,minSpeechFrames:x}}class l{constructor(u,h,m,x){this.modelProcessFunc=u,this.modelResetFunc=h,this.options=m,this.msPerFrame=x,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=E=>{this.options={...this.options,...E};const{redemptionFrames:j,preSpeechPadFrames:y,minSpeechFrames:b}=o(this.options,this.msPerFrame);this.redemptionFrames=j,this.preSpeechPadFrames=y,this.minSpeechFrames=b},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=E=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(E):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=E=>{const j=this.audioBuffer;this.audioBuffer=[];const y=this.speaking;if(this.reset(),y)if(j.reduce((_,C)=>C.isSpeech?_+1:_,0)>=this.minSpeechFrames){const _=i(j.map(C=>C.frame));E({msg:n.Message.SpeechEnd,audio:_})}else E({msg:n.Message.VADMisfire});return{}},this.process=async(E,j)=>{if(!this.active)return;const y=await this.modelProcessFunc(E),b=y.isSpeech>=this.options.positiveSpeechThreshold;if(j({probs:y,msg:n.Message.FrameProcessed,frame:E}),this.audioBuffer.push({frame:E,isSpeech:b}),b&&(this.speechFrameCount++,this.redemptionCounter=0),b&&!this.speaking&&(this.speaking=!0,j({msg:n.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,j({msg:n.Message.SpeechRealStart})),y.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const _=this.audioBuffer;if(this.audioBuffer=[],_.reduce((N,$)=>$.isSpeech?N+1:N,0)>=this.minSpeechFrames){const N=i(_.map($=>$.frame));j({msg:n.Message.SpeechEnd,audio:N})}else j({msg:n.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:g,preSpeechPadFrames:v,minSpeechFrames:S}=o(this.options,this.msPerFrame);this.redemptionFrames=g,this.preSpeechPadFrames=v,this.minSpeechFrames=S,this.reset()}}return tl.FrameProcessor=l,tl}var nl={};function oo(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Av={exports:{}};/*!
|
|
43
|
+
`),questions:n,at:Date.now()})}),window.api.chat.onError(({tabId:e,sessionId:n,message:r})=>{R2(e,n,r)}),window.api.chat.onNotice(({tabId:e,sessionId:n,message:r})=>{Qw(e,n,r)}),window.api.chat.onExternalSend(({tabId:e,prompt:n})=>{var i,o;const r=bt.getState().tabs.find(l=>l.id===e);if(!r){(o=(i=window.api)==null?void 0:i.logs)==null||o.write("chat","warn",`external send ignored: tab ${e} is not open`);return}Gs.getState().send({tabId:e,sessionId:r.sessionId,cwd:r.cwd,prompt:n})}));function WN(e){const n=e.split("/").filter(Boolean);return n[n.length-1]||e}async function M2(e,n=!1,r=E2()){let i=!n;i&&(i=await N2(e.cwd,e.sessionId));const o=n&&!i?crypto.randomUUID():e.sessionId,l=i?`claude --dangerously-skip-permissions --resume ${Ho(o)} --model ${r}`:`claude --dangerously-skip-permissions --session-id ${Ho(o)} --model ${r}`;return{sessionId:o,startupCommand:l}}const bt=cr((e,n)=>({tabs:[],activeTabId:null,hydrated:!1,pendingRawCommand:{},queueRawCommand:(r,i)=>{e(o=>({pendingRawCommand:{...o.pendingRawCommand,[r]:i}}))},consumeRawCommand:r=>{const i=n().pendingRawCommand[r];return i===void 0?null:(e(o=>{const l={...o.pendingRawCommand};return delete l[r],{pendingRawCommand:l}}),i)},addTab:({id:r,cwd:i,startupCommand:o,presetId:l=null,label:d})=>{const u=r??crypto.randomUUID();if(n().tabs.find(x=>x.id===u))return e({activeTabId:u}),u;const m={id:u,sessionId:u,label:d??WN(i),cwd:i,pid:null,status:"spawning",exitCode:null,startupCommand:o,presetId:l,generation:0};return e({tabs:[...n().tabs,m],activeTabId:u}),u},setTabRunning:(r,i)=>e({tabs:n().tabs.map(o=>o.id===r?{...o,pid:i,status:"running"}:o)}),setTabExited:(r,i)=>e({tabs:n().tabs.map(o=>o.id===r?{...o,status:"exited",exitCode:i}:o)}),closeTab:r=>{var l;window.api.pty.kill(r),window.api.watchers.killTab(r).catch(()=>{}),window.api.transcripts.closeTab(r).catch(()=>{});const i=n().tabs.filter(d=>d.id!==r),o=n().activeTabId===r?((l=i[i.length-1])==null?void 0:l.id)??null:n().activeTabId;e({tabs:i,activeTabId:o})},setActive:r=>e({activeTabId:r}),restartTab:r=>{const i=n().tabs.find(d=>d.id===r);if(!i)return;window.api.pty.kill(r);const o=crypto.randomUUID(),l=d=>{e({tabs:n().tabs.map(u=>u.id===r?{...u,sessionId:o,pid:null,status:"spawning",exitCode:null,startupCommand:d,generation:u.generation+1}:u)})};i.presetId?S2(i.presetId).then(d=>{l(d?C2(d,{sessionId:o,cwd:i.cwd}):`claude --dangerously-skip-permissions --session-id ${Ho(o)}`)}):l(`claude --dangerously-skip-permissions --session-id ${Ho(o)}`)},reorderTab:(r,i)=>{const o=[...n().tabs];if(r<0||r>=o.length||i<0||i>=o.length||r===i)return;const[l]=o.splice(r,1);o.splice(i,0,l),e({tabs:o})},restoreTabs:(r,i)=>e({tabs:r,activeTabId:i,hydrated:!0}),wakeTab:async(r,i)=>{var u;const o=n().tabs.find(h=>h.id===r);if(!o||o.status!=="dormant")return;(u=Gs.getState().chats[r])!=null&&u.running&&(await window.api.chat.cancel(r),Le.info("Cancelled the in-progress chat run to open a live session."));const{sessionId:l,startupCommand:d}=await M2({cwd:o.cwd,sessionId:o.sessionId},!1,i??E2());e({tabs:n().tabs.map(h=>h.id===r?{...h,sessionId:l,status:"spawning",startupCommand:d,generation:h.generation+1}:h)})},sleepTab:r=>{const i=n().tabs.find(o=>o.id===r);!i||i.status==="dormant"||(window.api.pty.kill(r),e({tabs:n().tabs.map(o=>o.id===r?{...o,pid:null,status:"dormant"}:o)}))},newSession:r=>{n().tabs.find(o=>o.id===r)&&e({tabs:n().tabs.map(o=>o.id===r?{...o,sessionId:crypto.randomUUID()}:o)})}}));async function Ob(){var r;if(bt.getState().hydrated)return;try{const{tabs:i,activeTabId:o,freshStart:l}=await window.api.sessions.load();if(i.length>0){const u=(await Promise.all(i.map(async m=>{try{const{sessionId:x}=await M2(m,l);return{id:m.id,sessionId:x,cwd:m.cwd,label:m.label,presetId:m.presetId,pid:null,status:"dormant",exitCode:null,startupCommand:null,generation:0}}catch(x){return console.warn("[sessions] dropping malformed persisted tab:",m==null?void 0:m.id,x),null}}))).filter(m=>m!==null),h=o&&u.find(m=>m.id===o)?o:((r=u[0])==null?void 0:r.id)??null;bt.getState().restoreTabs(u,h)}else bt.setState({hydrated:!0})}catch(i){console.warn("[sessions] hydrate failed:",i),bt.setState({hydrated:!0})}const e=()=>{const{tabs:i,activeTabId:o}=bt.getState(),l=i.map(d=>({id:d.id,sessionId:d.sessionId,cwd:d.cwd,label:d.label,presetId:d.presetId}));window.api.sessions.save({tabs:l,activeTabId:o}).catch(d=>{console.warn("[sessions] save failed:",d)})};let n=null;bt.subscribe((i,o)=>{i.hydrated&&(i.tabs===o.tabs&&i.activeTabId===o.activeTabId||(n!==null&&window.clearTimeout(n),n=window.setTimeout(e,200)))}),e()}const qN=Object.freeze(Object.defineProperty({__proto__:null,hydrateSessions:Ob,useSessions:bt},Symbol.toStringTag,{value:"Module"})),h_=200,VN=/\x1b\[[0-9;]*m/g;function GN(e){return e.replace(VN,"")}const Tm=cr((e,n)=>({watchers:{},initialized:!1,init:()=>{n().initialized||(e({initialized:!0}),window.api.watchers.onLine(r=>n().ingestLine(r)),window.api.watchers.onClosed(({watcherId:r})=>n().closed(r)))},add:async({tabId:r,label:i,command:o,cwd:l})=>{try{const d=await window.api.watchers.add({tabId:r,label:i,command:o,cwd:l??null}),u={watcherId:d.watcherId,tabId:d.tabId,label:d.label,command:d.command,cwd:d.cwd,pid:d.pid,startedAt:d.startedAt,lineCount:0,lines:[],lastLineAt:null};return e({watchers:{...n().watchers,[u.watcherId]:u}}),u}catch(d){return console.error("[watchers] add failed:",d),Le.error("Failed to add watcher"),null}},remove:async r=>{try{await window.api.watchers.remove(r)}catch(o){console.error("[watchers] remove failed:",o);const l=o instanceof Error?o.message:String(o);Le.error(`Could not remove watcher: ${l}`)}const i={...n().watchers};delete i[r],e({watchers:i})},watchersForTab:r=>Object.values(n().watchers).filter(i=>i.tabId===r),ingestLine:r=>{const i=n().watchers[r.watcherId];if(!i)return;const o=GN(r.line),l=i.lines.length>=h_?[...i.lines.slice(i.lines.length-h_+1),{line:o,ts:r.ts}]:[...i.lines,{line:o,ts:r.ts}];e({watchers:{...n().watchers,[r.watcherId]:{...i,lines:l,lineCount:i.lineCount+1,lastLineAt:r.ts}}})},closed:r=>{if(!n().watchers[r])return;const i={...n().watchers};delete i[r],e({watchers:i})}})),KN="~/.claude/session-manager/browser/history.json",f_="~/.claude/session-manager/browser/bookmarks.json",XN=.25,YN=3,p_=.1,m_=["#b85c34","#6f7d52","#e4b85a","#5f6f86","#8a5a6e","#4f7d72"];let g_=0;function JN(){const e=m_[g_%m_.length];return g_+=1,e}const hy=new Map;function QN(e){if(hy.has(e))return;const n=window.api.browser.onNavState(e,r=>{Mt.setState(i=>({tabs:i.tabs.map(o=>o.viewId===e?{...o,url:r.url,title:r.title||o.title,canGoBack:r.canGoBack,canGoForward:r.canGoForward,loading:r.loading,isSecure:r.isSecure}:o)}))});hy.set(e,n)}function ZN(e){const n=hy.get(e);n&&(n(),hy.delete(e))}const Lb=new Map;let Kx=null;function x_(e){const n=Lb.get(e);n&&(n(),Lb.delete(e))}function y_(){Kx&&(clearInterval(Kx),Kx=null)}const zb=new Map;function Tv(e){const n=zb.get(e);n&&(n(),zb.delete(e))}const Mt=cr((e,n)=>({tabs:[],activeTabId:null,openTab:r=>{const i=crypto.randomUUID(),o=i,l={id:i,viewId:o,title:"New Tab",url:(r==null?void 0:r.url)??"about:blank",color:(r==null?void 0:r.color)??JN(),canGoBack:!1,canGoForward:!1,loading:!1,isSecure:!1,zoomFactor:1};return e(d=>({tabs:[...d.tabs,l],activeTabId:i})),QN(o),window.api.browser.create({viewId:o,partition:"persist:browser"}).then(()=>{r!=null&&r.url&&window.api.browser.navigate({viewId:o,url:r.url}).catch(()=>{})}).catch(d=>{var h,m;const u=d instanceof Error?d.message:String(d);(m=(h=window.api)==null?void 0:h.logs)==null||m.write("browser","error",`browser:create failed for viewId ${o}: ${u}`)}),i},closeTab:r=>{const i=n().tabs.find(o=>o.id===r);i&&(ZN(i.viewId),Tv(i.viewId),window.api.browser.destroy(i.viewId).catch(()=>{}),e(o=>{const l=o.tabs.filter(u=>u.id!==r),d=o.activeTabId===r?l.length?l[l.length-1].id:null:o.activeTabId;return{tabs:l,activeTabId:d}}))},setActive:r=>{e({activeTabId:r})},navigate:(r,i)=>{const o=n().tabs.find(l=>l.id===r);o&&window.api.browser.navigate({viewId:o.viewId,url:i}).catch(()=>{})},back:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.back(i.viewId).catch(()=>{})},forward:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.forward(i.viewId).catch(()=>{})},reload:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.reload(i.viewId).catch(()=>{})},stop:r=>{const i=n().tabs.find(o=>o.id===r);i&&window.api.browser.stop(i.viewId).catch(()=>{})},mode:"browse",captureMode:"agent",setMode:r=>e(i=>({mode:r,captured:r==="capture"?i.captured:null})),setCaptureMode:r=>e({captureMode:r,captured:null}),onVerb:r=>{const{mode:i}=n();if(r==="shot"){e({mode:"capture",captureMode:"shot",captured:null});return}if(i===r){e({mode:"browse",captured:r==="capture"?null:n().captured});return}e({mode:r,captureMode:r==="capture"?"agent":n().captureMode,captured:r==="capture"?n().captured:null})},captured:null,capture:async r=>{const{activeTabId:i,tabs:o,captureMode:l}=n(),d=o.find(h=>h.id===i);if(!d)throw new Error("No active browser tab");if(l==="shot"){const h=await window.api.browser.captureShot(d.viewId);if(!h.ok)throw new Error(h.error);e({captured:{mode:l,url:h.url,title:h.title,dataUrl:h.dataUrl,at:Date.now()}});return}if(!r||!r.length)throw new Error("No element selected");const u=await window.api.browser.capture({viewId:d.viewId,selectors:r,mode:l});if(!u.ok)throw new Error(u.error);e({captured:{mode:l,url:d.url,title:d.title,text:u.text,meta:u.meta,selectors:r,at:Date.now()}})},recorderActive:!1,recording:!1,recorderElapsedSec:0,recorderSteps:[],startRecording:r=>{if(n().recorderActive)return;e({recorderActive:!0,recording:!0,recorderElapsedSec:0,recorderSteps:[]}),window.api.browser.recordStart(r).catch(()=>{}),x_(r);const i=window.api.browser.onRecordStep(r,o=>{Mt.getState().recording&&Mt.setState(l=>({recorderSteps:[...l.recorderSteps,o]}))});Lb.set(r,i),y_(),Kx=setInterval(()=>{Mt.getState().recording&&Mt.setState(o=>({recorderElapsedSec:o.recorderElapsedSec+1}))},1e3)},stopRecording:r=>{n().recorderActive&&(window.api.browser.recordStop(r).catch(()=>{}),x_(r),y_(),e({recorderActive:!1,recording:!1}))},toggleRecordingPause:()=>{n().recorderActive&&e(r=>({recording:!r.recording}))},toggleStepVariable:r=>{e(i=>({recorderSteps:i.recorderSteps.map(o=>o.n===r?{...o,variable:o.variable?null:o.variableSuggestion||"value"}:o)}))},bookmarks:[],bookmarksHydrated:!1,hydrateBookmarks:async()=>{if(!n().bookmarksHydrated)try{const r=await window.api.config.readJson(f_),i=r.exists&&Array.isArray(r.data)?r.data:[];e({bookmarks:i,bookmarksHydrated:!0})}catch{e({bookmarksHydrated:!0})}},toggleBookmark:r=>{const i=n().tabs.find(u=>u.id===r);if(!i||!i.url||i.url==="about:blank")return;const o=n().bookmarks,d=o.some(u=>u.url===i.url)?o.filter(u=>u.url!==i.url):[{url:i.url,title:i.title,ts:Date.now()},...o];e({bookmarks:d}),window.api.config.writeJson(f_,d).catch(()=>{})},historyEntries:[],refreshHistory:async()=>{try{const r=await window.api.config.readJson(KN),i=r.exists&&Array.isArray(r.data)?r.data:[];e({historyEntries:i})}catch{}},setZoom:(r,i)=>{const o=n().tabs.find(d=>d.id===r);if(!o)return;const l=Math.min(YN,Math.max(XN,i));e(d=>({tabs:d.tabs.map(u=>u.id===r?{...u,zoomFactor:l}:u)})),window.api.browser.setZoom({viewId:o.viewId,factor:l}).catch(()=>{})},zoomIn:r=>{const i=n().tabs.find(o=>o.id===r);i&&n().setZoom(r,i.zoomFactor+p_)},zoomOut:r=>{const i=n().tabs.find(o=>o.id===r);i&&n().setZoom(r,i.zoomFactor-p_)},zoomReset:r=>n().setZoom(r,1),findOpen:!1,findText:"",findMatches:null,openFind:r=>{const i=n().tabs.find(l=>l.id===r);if(!i)return;e({findOpen:!0,findText:"",findMatches:null}),Tv(i.viewId);const o=window.api.browser.onFindResult(i.viewId,l=>{Mt.setState({findMatches:l})});zb.set(i.viewId,o)},closeFind:r=>{const i=n().tabs.find(o=>o.id===r);e({findOpen:!1,findText:"",findMatches:null}),i&&(Tv(i.viewId),window.api.browser.stopFind(i.viewId).catch(()=>{}))},setFindText:(r,i)=>{const o=n().tabs.find(l=>l.id===r);if(e({findText:i}),!!o){if(!i){window.api.browser.find({viewId:o.viewId,text:""}).catch(()=>{});return}window.api.browser.find({viewId:o.viewId,text:i,forward:!0}).catch(()=>{})}},findNext:r=>{const i=n().tabs.find(l=>l.id===r),{findText:o}=n();!i||!o||window.api.browser.find({viewId:i.viewId,text:o,forward:!0}).catch(()=>{})},findPrev:r=>{const i=n().tabs.find(l=>l.id===r),{findText:o}=n();!i||!o||window.api.browser.find({viewId:i.viewId,text:o,forward:!1}).catch(()=>{})}})),eT=4,v_=40,b_=6;function tT(e){const{onReorder:n,onActivate:r}=e,i=L.useRef(null),o=L.useRef(null),l=L.useRef(0),d=L.useRef(0),[u,h]=L.useState(!1),[,m]=L.useState(0),x=L.useRef(r);x.current=r;const g=L.useCallback(()=>i.current?Array.from(i.current.querySelectorAll("[data-drag-index]")):[],[]),v=L.useCallback((y,b,_)=>{for(let C=0;C<b.length;C++){const N=b[C].left+b[C].width/2;if(y<N)return C<=_?C:C-1}return b.length-1},[]),S=L.useCallback(()=>{const y=o.current,b=i.current;if(!(y!=null&&y.active)||!b)return;const _=b.getBoundingClientRect(),C=y.startX+y.deltaX,N=C-_.left,$=_.right-C;N<v_?b.scrollLeft-=b_:$<v_&&(b.scrollLeft+=b_),l.current=requestAnimationFrame(S)},[]);L.useEffect(()=>{const y=i.current;if(!y)return;let b=!1;const _=()=>{b||(b=!0,d.current=requestAnimationFrame(()=>{b=!1,m($=>$+1)}))},C=$=>{var U;const R=o.current;if(!R)return;const O=$.clientX-R.startX;if(!R.active&&Math.abs(O)<eT)return;if(!R.active){R.active=!0,R.tabRects=g().map(W=>W.getBoundingClientRect()),h(!0);try{(U=i.current)==null||U.setPointerCapture(R.pointerId)}catch{}l.current=requestAnimationFrame(S)}R.deltaX=O;const I=R.tabRects[R.fromIndex],z=I.left+I.width/2+O;R.currentIndex=v(z,R.tabRects,R.fromIndex),_()},N=$=>{const R=o.current;if(R&&R.pointerId===$.pointerId){cancelAnimationFrame(l.current),cancelAnimationFrame(d.current);try{y.releasePointerCapture(R.pointerId)}catch{}R.active&&R.fromIndex!==R.currentIndex?n(R.fromIndex,R.currentIndex):x.current(R.fromIndex),o.current=null,h(!1),m(O=>O+1)}};return y.addEventListener("pointermove",C),y.addEventListener("pointerup",N),y.addEventListener("pointercancel",N),()=>{y.removeEventListener("pointermove",C),y.removeEventListener("pointerup",N),y.removeEventListener("pointercancel",N),cancelAnimationFrame(l.current),cancelAnimationFrame(d.current)}},[n,g,v,S]);const E=L.useCallback((y,b)=>{y.button!==0||y.target.closest("button")||(o.current={active:!1,fromIndex:b,currentIndex:b,startX:y.clientX,deltaX:0,tabRects:[],pointerId:y.pointerId})},[]);return{getTabDragProps:L.useCallback(y=>{var C;const b=o.current,_={};if(b!=null&&b.active)if(y===b.fromIndex)_.transform=`translateX(${b.deltaX}px) scale(1.03)`,_.zIndex=10,_.opacity=.85,_.boxShadow="0 2px 8px rgba(0,0,0,0.4)",_.position="relative",_.pointerEvents="none";else{const N=b.fromIndex,$=b.currentIndex,O=(((C=b.tabRects[N])==null?void 0:C.width)??0)+4;_.transition="transform 0.15s ease",N<$&&y>N&&y<=$?_.transform=`translateX(-${O}px)`:N>$&&y>=$&&y<N?_.transform=`translateX(${O}px)`:_.transform="translateX(0)"}return{onPointerDown:N=>E(N,y),style:_,"data-drag-index":y}},[E]),isDragging:u,containerRef:i}}const nT=3e4;function rT({onToggleSplitView:e,splitViewActive:n}={}){const r=bt(b=>b.tabs),i=bt(b=>b.activeTabId),o=bt(b=>b.closeTab),l=bt(b=>b.setActive),d=bt(b=>b.reorderTab),u=Tm(b=>b.watchers),h=Mt(b=>b.tabs.length>0),m=i!=null&&h,[x,g]=L.useState(()=>Date.now());L.useEffect(()=>{const b=window.setInterval(()=>g(Date.now()),1e3);return()=>window.clearInterval(b)},[]);const v=b=>{for(const _ of Object.values(u))if(_.tabId===b&&_.lastLineAt&&x-_.lastLineAt<nT)return!0;return!1},{getTabDragProps:S,isDragging:E,containerRef:j}=tT({tabCount:r.length,onReorder:d,onActivate:b=>{const _=r[b];_&&l(_.id)}}),y=["#6f7d52","#b85c34","#a39079","#7a8466","#5b4a36"];return s.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:[s.jsx("div",{ref:j,className:`flex items-end gap-0.5 overflow-x-auto min-w-0 flex-1 select-none ${E?"cursor-grabbing":""}`,children:r.map((b,_)=>{const C=b.id===i,N=S(_),$=y[_%y.length];return s.jsxs("div",{...N,style:N.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 ${E?"":"cursor-grab"} ${C?"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:b.cwd,"aria-current":C?"true":void 0,children:[s.jsx("span",{className:"w-2 h-2 rounded-full",style:{background:$,boxShadow:"inset 0 0 0 0.5px rgba(0,0,0,0.15)",opacity:b.status==="spawning"?.55:1}}),s.jsx("span",{className:"truncate max-w-[200px]",children:b.label}),b.status==="spawning"&&s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-butter animate-pulse",title:"spawning"}),v(b.id)&&s.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"}),s.jsx("button",{onClick:R=>{R.stopPropagation(),o(b.id)},className:"text-fg-faint opacity-0 group-hover:opacity-100 hover:text-fg ml-1 leading-none",title:"Close session","aria-label":`Close ${b.label}`,children:"×"})]},b.id)})}),s.jsxs("div",{className:"flex items-center gap-2 pb-2 pl-3 text-[12px] text-fg-faint shrink-0",children:[m&&e&&s.jsxs("button",{onClick:e,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[11px] border border-line hover:bg-bg-hi/40 ${n?"text-accent border-accent":"text-fg-faint hover:text-fg"}`,title:"Split view: agent terminal + browser","aria-pressed":n??!1,children:[s.jsx("span",{"aria-hidden":"true",children:"⇄"}),s.jsx("span",{children:"Split view"})]}),s.jsx("span",{className:"font-semibold text-fg-dim",children:"Claude Session Manager"}),s.jsxs("span",{className:"font-mono text-[11px] text-fg-faint",children:["v","0.38.2"]})]})]})}function sT(e,n,r){return n?e.map(i=>i.id===n?{...i,lastActivityAt:r}:i):e}function iT(e,n,r){return{tabId:e,sessionUuid:r,cwd:n,path:null,todos:[],lastToolUses:[],plans:[],agents:[],usage:{inputTokens:0,outputTokens:0},lastEventAt:0,activityRing:[],activitySeq:0}}const $m=cr((e,n)=>({tabs:{},refs:{},unsubs:{},subscribe:(r,i,o)=>{const l={...n().refs};if(l[r]=(l[r]??0)+1,e({refs:l}),l[r]>1)return;e({tabs:{...n().tabs,[r]:iT(r,i,o)}});const d=window.api.transcripts.onEvent(r,u=>n().ingest(r,u));e({unsubs:{...n().unsubs,[r]:d}}),window.api.transcripts.subscribe({tabId:r,cwd:i,sessionUuid:o}).then(async u=>{const h=n().tabs[r];if(!h)return;if(!u.ok){const{toast:x}=await Jm(async()=>{const{toast:g}=await Promise.resolve().then(()=>T2);return{toast:g}},void 0,import.meta.url);x.error(`Live view unavailable: ${u.error??"subscribe failed"}`),e({tabs:{...n().tabs,[r]:{...h,path:null}}});return}e({tabs:{...n().tabs,[r]:{...h,path:u.path}}});const m=await window.api.transcripts.buffer(r);for(const x of m)n().ingest(r,x,{replay:!0})}).catch(u=>console.error("[live] transcripts.subscribe failed:",r,u))},unsubscribe:r=>{const i={...n().refs};if(!i[r])return;if(i[r]--,i[r]>0){e({refs:i});return}delete i[r];const o=n().unsubs[r];o==null||o();const l={...n().unsubs};delete l[r];const d={...n().tabs};delete d[r],window.api.transcripts.unsubscribe(r),e({refs:i,unsubs:l,tabs:d})},ingest:(r,i,o)=>{const l=n().tabs[r];if(!l)return;const d=Date.now(),u={...l,lastEventAt:o!=null&&o.replay?l.lastEventAt:d},h=[],m=(x,g)=>x.length>g?x.slice(0,g-1)+"…":x;switch(i.kind){case"todo_write":{const x=Array.isArray(i.data)?i.data:[];u.todos=x,o!=null&&o.replay||h.push({id:0,kind:"todo-update",at:d,label:`Todos · ${x.length} item${x.length!==1?"s":""}`});break}case"tool_use":{const x=i.data,g=x.input,v={};for(const S of["command","file_path","pattern","url","query","subagent_type","description"])g&&S in g&&(v[S]=g[S]);if(u.lastToolUses=[{id:x.id,name:x.name,input:v,at:d},...l.lastToolUses].slice(0,50),!(o!=null&&o.replay)){const S=x.input,E=["Edit","Write","NotebookEdit"].includes(x.name),j=typeof(S==null?void 0:S.file_path)=="string"?S.file_path:void 0,y=typeof(S==null?void 0:S.command)=="string"?S.command:void 0,b=j?j.split("/").pop()??j:y?m(y,28):"";h.push({id:0,kind:"tool-use",at:d,label:b?`${x.name} · ${b}`:x.name,target:j??y,toolName:x.name}),E&&j&&h.push({id:0,kind:"file-edit",at:d,label:`${x.name} · ${m(j.split("/").pop()??j,34)}`,target:j,toolName:x.name})}break}case"plan":{const x=i.data,g=typeof x=="string"?x:(x==null?void 0:x.plan)??JSON.stringify(x);u.plans=[{at:d,content:g??""},...l.plans].slice(0,50),o!=null&&o.replay||h.push({id:0,kind:"plan-revision",at:d,label:"Plan revised"});break}case"agent_spawn":{const x=i.data;u.agents=[{id:x==null?void 0:x.toolUseId,at:d,subagentType:x==null?void 0:x.subagent_type,description:x==null?void 0:x.description,lastActivityAt:d},...l.agents].slice(0,50),o!=null&&o.replay||h.push({id:0,kind:"agent-spawn",at:d,label:x!=null&&x.subagent_type?`Agent: ${m(x.subagent_type,32)}`:"Agent spawned"});break}case"usage":{const x=i.data,g=(l.usage.inputTokens||0)+(l.usage.outputTokens||0),v=x.input_tokens??x.inputTokens??0,S=x.output_tokens??x.outputTokens??0,E=g+v+S;u.usage={inputTokens:(l.usage.inputTokens||0)+v,outputTokens:(l.usage.outputTokens||0)+S,cacheCreationInputTokens:(l.usage.cacheCreationInputTokens||0)+(x.cache_creation_input_tokens??x.cacheCreationInputTokens??0),cacheReadInputTokens:(l.usage.cacheReadInputTokens||0)+(x.cache_read_input_tokens??x.cacheReadInputTokens??0)},!(o!=null&&o.replay)&&Math.floor(E/1e3)>Math.floor(g/1e3)&&h.push({id:0,kind:"usage-tick",at:d,label:`${Math.floor(E/1e3)}k tokens`});break}case"tool_result":{const x=i.data;u.agents=sT(l.agents,x==null?void 0:x.toolUseId,d);break}}if(h.length>0){let x=l.activitySeq;const g=h.map(v=>({...v,id:++x}));u.activitySeq=x,u.activityRing=[...l.activityRing,...g].slice(-32)}e({tabs:{...n().tabs,[r]:u}})}}));function I2(e){const n=$m(o=>o.subscribe),r=$m(o=>o.unsubscribe),i=$m(o=>e?o.tabs[e.id]:void 0);return L.useEffect(()=>{if(e)return n(e.id,e.cwd,e.sessionId),()=>r(e.id)},[e==null?void 0:e.id,e==null?void 0:e.cwd,e==null?void 0:e.sessionId,n,r]),i}var $v={},Fp={},w_;function P2(){if(w_)return Fp;w_=1,Object.defineProperty(Fp,"__esModule",{value:!0}),Fp.baseAssetPath=void 0;const n=typeof window<"u"&&typeof window.document<"u"?window.document.currentScript:null;let r="/";return n&&(r=n.src.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^/]+$/,"/")),Fp.baseAssetPath=r,Fp}var Up={},__;function Zw(){if(__)return Up;__=1,Object.defineProperty(Up,"__esModule",{value:!0}),Up.defaultModelFetcher=void 0;const e=n=>fetch(n).then(r=>r.arrayBuffer());return Up.defaultModelFetcher=e,Up}var tl={},Hp={},k_;function Qm(){if(k_)return Hp;k_=1,Object.defineProperty(Hp,"__esModule",{value:!0}),Hp.log=void 0;const e=n=>r=>{console.log(`VAD | ${n} >`,r)};return Hp.log={error:e("error"),debug:e("debug"),warn:e("warn")},Hp}var Wp={},S_;function Ky(){if(S_)return Wp;S_=1,Object.defineProperty(Wp,"__esModule",{value:!0}),Wp.Message=void 0;var e;return(function(n){n.AudioFrame="AUDIO_FRAME",n.SpeechStart="SPEECH_START",n.VADMisfire="VAD_MISFIRE",n.SpeechEnd="SPEECH_END",n.SpeechStop="SPEECH_STOP",n.SpeechRealStart="SPEECH_REAL_START",n.FrameProcessed="FRAME_PROCESSED"})(e||(Wp.Message=e={})),Wp}var C_;function e0(){if(C_)return tl;C_=1,Object.defineProperty(tl,"__esModule",{value:!0}),tl.FrameProcessor=tl.validateOptions=tl.defaultFrameProcessorOptions=void 0;const e=Qm(),n=Ky();tl.defaultFrameProcessorOptions={positiveSpeechThreshold:.3,negativeSpeechThreshold:.25,preSpeechPadMs:800,redemptionMs:1400,minSpeechMs:400,submitUserSpeechOnPause:!1};function r(d){(d.positiveSpeechThreshold<0||d.positiveSpeechThreshold>1)&&e.log.error("positiveSpeechThreshold should be a number between 0 and 1"),(d.negativeSpeechThreshold<0||d.negativeSpeechThreshold>d.positiveSpeechThreshold)&&e.log.error("negativeSpeechThreshold should be between 0 and positiveSpeechThreshold"),d.preSpeechPadMs<0&&e.log.error("preSpeechPadMs should be positive"),d.redemptionMs<0&&e.log.error("redemptionMs should be positive"),d.minSpeechMs<0&&e.log.error("minSpeechMs should be positive")}tl.validateOptions=r;const i=d=>{const u=d.reduce((m,x)=>(m.push(m.at(-1)+x.length),m),[0]),h=new Float32Array(u.at(-1));return d.forEach((m,x)=>{const g=u[x];h.set(m,g)}),h};function o(d,u){const h=Math.floor(d.redemptionMs/u),m=Math.floor(d.preSpeechPadMs/u),x=Math.floor(d.minSpeechMs/u);return{redemptionFrames:h,preSpeechPadFrames:m,minSpeechFrames:x}}class l{constructor(u,h,m,x){this.modelProcessFunc=u,this.modelResetFunc=h,this.options=m,this.msPerFrame=x,this.speaking=!1,this.redemptionCounter=0,this.speechFrameCount=0,this.active=!1,this.speechRealStartFired=!1,this.setOptions=E=>{this.options={...this.options,...E};const{redemptionFrames:j,preSpeechPadFrames:y,minSpeechFrames:b}=o(this.options,this.msPerFrame);this.redemptionFrames=j,this.preSpeechPadFrames=y,this.minSpeechFrames=b},this.reset=()=>{this.speaking=!1,this.speechRealStartFired=!1,this.audioBuffer=[],this.modelResetFunc(),this.redemptionCounter=0,this.speechFrameCount=0},this.pause=E=>{this.active=!1,this.options.submitUserSpeechOnPause?this.endSegment(E):this.reset()},this.resume=()=>{this.active=!0},this.endSegment=E=>{const j=this.audioBuffer;this.audioBuffer=[];const y=this.speaking;if(this.reset(),y)if(j.reduce((_,C)=>C.isSpeech?_+1:_,0)>=this.minSpeechFrames){const _=i(j.map(C=>C.frame));E({msg:n.Message.SpeechEnd,audio:_})}else E({msg:n.Message.VADMisfire});return{}},this.process=async(E,j)=>{if(!this.active)return;const y=await this.modelProcessFunc(E),b=y.isSpeech>=this.options.positiveSpeechThreshold;if(j({probs:y,msg:n.Message.FrameProcessed,frame:E}),this.audioBuffer.push({frame:E,isSpeech:b}),b&&(this.speechFrameCount++,this.redemptionCounter=0),b&&!this.speaking&&(this.speaking=!0,j({msg:n.Message.SpeechStart})),this.speaking&&this.speechFrameCount===this.minSpeechFrames&&!this.speechRealStartFired&&(this.speechRealStartFired=!0,j({msg:n.Message.SpeechRealStart})),y.isSpeech<this.options.negativeSpeechThreshold&&this.speaking&&++this.redemptionCounter>=this.redemptionFrames){this.redemptionCounter=0,this.speechFrameCount=0,this.speaking=!1,this.speechRealStartFired=!1;const _=this.audioBuffer;if(this.audioBuffer=[],_.reduce((N,$)=>$.isSpeech?N+1:N,0)>=this.minSpeechFrames){const N=i(_.map($=>$.frame));j({msg:n.Message.SpeechEnd,audio:N})}else j({msg:n.Message.VADMisfire})}if(!this.speaking){for(;this.audioBuffer.length>this.preSpeechPadFrames;)this.audioBuffer.shift();this.speechFrameCount=0}},this.audioBuffer=[];const{redemptionFrames:g,preSpeechPadFrames:v,minSpeechFrames:S}=o(this.options,this.msPerFrame);this.redemptionFrames=g,this.preSpeechPadFrames=v,this.minSpeechFrames=S,this.reset()}}return tl.FrameProcessor=l,tl}var nl={};function oo(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Av={exports:{}};/*!
|
|
44
44
|
* ONNX Runtime Web v1.26.0
|
|
45
45
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
46
46
|
* Licensed under the MIT License.
|
|
47
|
-
*/var j_;function oT(){return j_||(j_=1,(function(e,n){var r=(()=>{var i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,u=(a=>typeof oo<"u"?oo:typeof Proxy<"u"?new Proxy(a,{get:(f,w)=>(typeof oo<"u"?oo:f)[w]}):a)(function(a){if(typeof oo<"u")return oo.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')}),h=(a,f)=>()=>(a&&(f=a(a=0)),f),m=(a,f)=>{for(var w in f)i(a,w,{get:f[w],enumerable:!0})},x=(a,f,w,T)=>{if(f&&typeof f=="object"||typeof f=="function")for(let A of l(f))!d.call(a,A)&&A!==w&&i(a,A,{get:()=>f[A],enumerable:!(T=o(f,A))||T.enumerable});return a},g=a=>x(i({},"__esModule",{value:!0}),a),v,S,E,j,y,b=h(()=>{v=new Map,S=[],E=(a,f,w)=>{if(f&&typeof f.init=="function"&&typeof f.createInferenceSessionHandler=="function"){let T=v.get(a);if(T===void 0)v.set(a,{backend:f,priority:w});else{if(T.priority>w)return;if(T.priority===w&&T.backend!==f)throw new Error(`cannot register backend "${a}" using priority ${w}`)}if(w>=0){let A=S.indexOf(a);A!==-1&&S.splice(A,1);for(let P=0;P<S.length;P++)if(v.get(S[P]).priority<=w){S.splice(P,0,a);return}S.push(a)}return}throw new TypeError("not a valid backend")},j=async a=>{let f=v.get(a);if(!f)return"backend not found.";if(f.initialized)return f.backend;if(f.aborted)return f.error;{let w=!!f.initPromise;try{return w||(f.initPromise=f.backend.init(a)),await f.initPromise,f.initialized=!0,f.backend}catch(T){return w||(f.error=`${T}`,f.aborted=!0),f.error}finally{delete f.initPromise}}},y=async a=>{let f=a.executionProviders||[],w=f.map(q=>typeof q=="string"?q:q.name),T=w.length===0?S:w,A,P=[],D=new Set;for(let q of T){let G=await j(q);typeof G=="string"?P.push({name:q,err:G}):(A||(A=G),A===G&&D.add(q))}if(!A)throw new Error(`no available backend found. ERR: ${P.map(q=>`[${q.name}] ${q.err}`).join(", ")}`);for(let{name:q,err:G}of P)w.includes(q)&&console.warn(`removing requested execution provider "${q}" from session options because it is not available: ${G}`);let B=f.filter(q=>D.has(typeof q=="string"?q:q.name));return[A,new Proxy(a,{get:(q,G)=>G==="executionProviders"?B:Reflect.get(q,G)})]}}),_=h(()=>{b()}),C,N=h(()=>{C="1.26.0"}),$,R,O=h(()=>{N(),$="warning",R={wasm:{},webgl:{},webgpu:{},versions:{common:C},set logLevel(a){if(a!==void 0){if(typeof a!="string"||["verbose","info","warning","error","fatal"].indexOf(a)===-1)throw new Error(`Unsupported logging level: ${a}`);$=a}},get logLevel(){return $}},Object.defineProperty(R,"logLevel",{enumerable:!0})}),I,z=h(()=>{O(),I=R}),U,W,Y=h(()=>{U=(a,f)=>{let w=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);w.width=a.dims[3],w.height=a.dims[2];let T=w.getContext("2d");if(T!=null){let A,P;(f==null?void 0:f.tensorLayout)!==void 0&&f.tensorLayout==="NHWC"?(A=a.dims[2],P=a.dims[3]):(A=a.dims[3],P=a.dims[2]);let D=(f==null?void 0:f.format)!==void 0?f.format:"RGB",B=f==null?void 0:f.norm,q,G;B===void 0||B.mean===void 0?q=[255,255,255,255]:typeof B.mean=="number"?q=[B.mean,B.mean,B.mean,B.mean]:(q=[B.mean[0],B.mean[1],B.mean[2],0],B.mean[3]!==void 0&&(q[3]=B.mean[3])),B===void 0||B.bias===void 0?G=[0,0,0,0]:typeof B.bias=="number"?G=[B.bias,B.bias,B.bias,B.bias]:(G=[B.bias[0],B.bias[1],B.bias[2],0],B.bias[3]!==void 0&&(G[3]=B.bias[3]));let Z=P*A,ee=0,se=Z,ue=Z*2,he=-1;D==="RGBA"?(ee=0,se=Z,ue=Z*2,he=Z*3):D==="RGB"?(ee=0,se=Z,ue=Z*2):D==="RBG"&&(ee=0,ue=Z,se=Z*2);for(let ge=0;ge<P;ge++)for(let ke=0;ke<A;ke++){let xe=(a.data[ee++]-G[0])*q[0],me=(a.data[se++]-G[1])*q[1],Ee=(a.data[ue++]-G[2])*q[2],je=he===-1?255:(a.data[he++]-G[3])*q[3];T.fillStyle="rgba("+xe+","+me+","+Ee+","+je+")",T.fillRect(ke,ge,1,1)}if("toDataURL"in w)return w.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},W=(a,f)=>{let w=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),T;if(w!=null){let A,P,D;(f==null?void 0:f.tensorLayout)!==void 0&&f.tensorLayout==="NHWC"?(A=a.dims[2],P=a.dims[1],D=a.dims[3]):(A=a.dims[3],P=a.dims[2],D=a.dims[1]);let B=f!==void 0&&f.format!==void 0?f.format:"RGB",q=f==null?void 0:f.norm,G,Z;q===void 0||q.mean===void 0?G=[255,255,255,255]:typeof q.mean=="number"?G=[q.mean,q.mean,q.mean,q.mean]:(G=[q.mean[0],q.mean[1],q.mean[2],255],q.mean[3]!==void 0&&(G[3]=q.mean[3])),q===void 0||q.bias===void 0?Z=[0,0,0,0]:typeof q.bias=="number"?Z=[q.bias,q.bias,q.bias,q.bias]:(Z=[q.bias[0],q.bias[1],q.bias[2],0],q.bias[3]!==void 0&&(Z[3]=q.bias[3]));let ee=P*A;if(f!==void 0&&(f.format!==void 0&&D===4&&f.format!=="RGBA"||D===3&&f.format!=="RGB"&&f.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let se=4,ue=0,he=1,ge=2,ke=3,xe=0,me=ee,Ee=ee*2,je=-1;B==="RGBA"?(xe=0,me=ee,Ee=ee*2,je=ee*3):B==="RGB"?(xe=0,me=ee,Ee=ee*2):B==="RBG"&&(xe=0,Ee=ee,me=ee*2),T=w.createImageData(A,P);for(let Oe=0;Oe<P*A;ue+=se,he+=se,ge+=se,ke+=se,Oe++)T.data[ue]=(a.data[xe++]-Z[0])*G[0],T.data[he]=(a.data[me++]-Z[1])*G[1],T.data[ge]=(a.data[Ee++]-Z[2])*G[2],T.data[ke]=je===-1?255:(a.data[je++]-Z[3])*G[3]}else throw new Error("Can not access image data");return T}}),V,H,te,ae,oe,ie,X=h(()=>{we(),V=(a,f)=>{if(a===void 0)throw new Error("Image buffer must be defined");if(f.height===void 0||f.width===void 0)throw new Error("Image height and width must be defined");if(f.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:w,width:T}=f,A=f.norm??{mean:255,bias:0},P,D;typeof A.mean=="number"?P=[A.mean,A.mean,A.mean,A.mean]:P=[A.mean[0],A.mean[1],A.mean[2],A.mean[3]??255],typeof A.bias=="number"?D=[A.bias,A.bias,A.bias,A.bias]:D=[A.bias[0],A.bias[1],A.bias[2],A.bias[3]??0];let B=f.format!==void 0?f.format:"RGBA",q=f.tensorFormat!==void 0&&f.tensorFormat!==void 0?f.tensorFormat:"RGB",G=w*T,Z=q==="RGBA"?new Float32Array(G*4):new Float32Array(G*3),ee=4,se=0,ue=1,he=2,ge=3,ke=0,xe=G,me=G*2,Ee=-1;B==="RGB"&&(ee=3,se=0,ue=1,he=2,ge=-1),q==="RGBA"?Ee=G*3:q==="RBG"?(ke=0,me=G,xe=G*2):q==="BGR"&&(me=0,xe=G,ke=G*2);for(let je=0;je<G;je++,se+=ee,he+=ee,ue+=ee,ge+=ee)Z[ke++]=(a[se]+D[0])/P[0],Z[xe++]=(a[ue]+D[1])/P[1],Z[me++]=(a[he]+D[2])/P[2],Ee!==-1&&ge!==-1&&(Z[Ee++]=(a[ge]+D[3])/P[3]);return q==="RGBA"?new ne("float32",Z,[1,4,w,T]):new ne("float32",Z,[1,3,w,T])},H=async(a,f)=>{let w=typeof HTMLImageElement<"u"&&a instanceof HTMLImageElement,T=typeof ImageData<"u"&&a instanceof ImageData,A=typeof ImageBitmap<"u"&&a instanceof ImageBitmap,P=typeof a=="string",D,B=f??{},q=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},G=Z=>typeof HTMLCanvasElement<"u"&&Z instanceof HTMLCanvasElement||Z instanceof OffscreenCanvas?Z.getContext("2d"):null;if(w){let Z=q();Z.width=a.width,Z.height=a.height;let ee=G(Z);if(ee!=null){let se=a.height,ue=a.width;if(f!==void 0&&f.resizedHeight!==void 0&&f.resizedWidth!==void 0&&(se=f.resizedHeight,ue=f.resizedWidth),f!==void 0){if(B=f,f.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");B.tensorFormat="RGBA",B.height=se,B.width=ue}else B.tensorFormat="RGBA",B.height=se,B.width=ue;ee.drawImage(a,0,0),D=ee.getImageData(0,0,ue,se).data}else throw new Error("Can not access image data")}else if(T){let Z,ee;if(f!==void 0&&f.resizedWidth!==void 0&&f.resizedHeight!==void 0?(Z=f.resizedHeight,ee=f.resizedWidth):(Z=a.height,ee=a.width),f!==void 0&&(B=f),B.format="RGBA",B.height=Z,B.width=ee,f!==void 0){let se=q();se.width=ee,se.height=Z;let ue=G(se);if(ue!=null)ue.putImageData(a,0,0),D=ue.getImageData(0,0,ee,Z).data;else throw new Error("Can not access image data")}else D=a.data}else if(A){if(f===void 0)throw new Error("Please provide image config with format for Imagebitmap");let Z=q();Z.width=a.width,Z.height=a.height;let ee=G(Z);if(ee!=null){let se=a.height,ue=a.width;return ee.drawImage(a,0,0,ue,se),D=ee.getImageData(0,0,ue,se).data,B.height=se,B.width=ue,V(D,B)}else throw new Error("Can not access image data")}else{if(P)return new Promise((Z,ee)=>{let se=q(),ue=G(se);if(!a||!ue)return ee();let he=new Image;he.crossOrigin="Anonymous",he.src=a,he.onload=()=>{se.width=he.width,se.height=he.height,ue.drawImage(he,0,0,se.width,se.height);let ge=ue.getImageData(0,0,se.width,se.height);B.height=se.height,B.width=se.width,Z(V(ge.data,B))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(D!==void 0)return V(D,B);throw new Error("Input data provided is not supported - aborted tensor creation")},te=(a,f)=>{let{width:w,height:T,download:A,dispose:P}=f,D=[1,T,w,4];return new ne({location:"texture",type:"float32",texture:a,dims:D,download:A,dispose:P})},ae=(a,f)=>{let{dataType:w,dims:T,download:A,dispose:P}=f;return new ne({location:"gpu-buffer",type:w??"float32",gpuBuffer:a,dims:T,download:A,dispose:P})},oe=(a,f)=>{let{dataType:w,dims:T,download:A,dispose:P}=f;return new ne({location:"ml-tensor",type:w??"float32",mlTensor:a,dims:T,download:A,dispose:P})},ie=(a,f,w)=>new ne({location:"cpu-pinned",type:a,data:f,dims:w??[f.length]})}),Q,J,le,ce,pe=h(()=>{Q=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),J=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),le=!1,ce=()=>{if(!le){le=!0;let a=typeof BigInt64Array<"u"&&BigInt64Array.from,f=typeof BigUint64Array<"u"&&BigUint64Array.from,w=globalThis.Float16Array,T=typeof w<"u"&&w.from;a&&(Q.set("int64",BigInt64Array),J.set(BigInt64Array,"int64")),f&&(Q.set("uint64",BigUint64Array),J.set(BigUint64Array,"uint64")),T?(Q.set("float16",w),J.set(w,"float16")):Q.set("float16",Uint16Array)}}}),Ae,Se,ye=h(()=>{we(),Ae=a=>{let f=1;for(let w=0;w<a.length;w++){let T=a[w];if(typeof T!="number"||!Number.isSafeInteger(T))throw new TypeError(`dims[${w}] must be an integer, got: ${T}`);if(T<0)throw new RangeError(`dims[${w}] must be a non-negative integer, got: ${T}`);f*=T}return f},Se=(a,f)=>{switch(a.location){case"cpu":return new ne(a.type,a.data,f);case"cpu-pinned":return new ne({location:"cpu-pinned",data:a.data,type:a.type,dims:f});case"texture":return new ne({location:"texture",texture:a.texture,type:a.type,dims:f});case"gpu-buffer":return new ne({location:"gpu-buffer",gpuBuffer:a.gpuBuffer,type:a.type,dims:f});case"ml-tensor":return new ne({location:"ml-tensor",mlTensor:a.mlTensor,type:a.type,dims:f});default:throw new Error(`tensorReshape: tensor location ${a.location} is not supported`)}}}),ne,we=h(()=>{Y(),X(),pe(),ye(),ne=class{constructor(a,f,w){ce();let T,A;if(typeof a=="object"&&"location"in a)switch(this.dataLocation=a.location,T=a.type,A=a.dims,a.location){case"cpu-pinned":{let D=Q.get(T);if(!D)throw new TypeError(`unsupported type "${T}" to create tensor from pinned buffer`);if(!(a.data instanceof D))throw new TypeError(`buffer should be of type ${D.name}`);this.cpuData=a.data;break}case"texture":{if(T!=="float32")throw new TypeError(`unsupported type "${T}" to create tensor from texture`);this.gpuTextureData=a.texture,this.downloader=a.download,this.disposer=a.dispose;break}case"gpu-buffer":{if(T!=="float32"&&T!=="float16"&&T!=="int32"&&T!=="int64"&&T!=="uint32"&&T!=="uint8"&&T!=="bool"&&T!=="uint4"&&T!=="int4")throw new TypeError(`unsupported type "${T}" to create tensor from gpu buffer`);this.gpuBufferData=a.gpuBuffer,this.downloader=a.download,this.disposer=a.dispose;break}case"ml-tensor":{if(T!=="float32"&&T!=="float16"&&T!=="int32"&&T!=="int64"&&T!=="uint32"&&T!=="uint64"&&T!=="int8"&&T!=="uint8"&&T!=="bool"&&T!=="uint4"&&T!=="int4")throw new TypeError(`unsupported type "${T}" to create tensor from MLTensor`);this.mlTensorData=a.mlTensor,this.downloader=a.download,this.disposer=a.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let D,B;if(typeof a=="string")if(T=a,B=w,a==="string"){if(!Array.isArray(f))throw new TypeError("A string tensor's data must be a string array.");D=f}else{let q=Q.get(a);if(q===void 0)throw new TypeError(`Unsupported tensor type: ${a}.`);if(Array.isArray(f)){if(a==="float16"&&q===Uint16Array||a==="uint4"||a==="int4")throw new TypeError(`Creating a ${a} tensor from number array is not supported. Please use ${q.name} as data.`);a==="uint64"||a==="int64"?D=q.from(f,BigInt):D=q.from(f)}else if(f instanceof q)D=f;else if(f instanceof Uint8ClampedArray)if(a==="uint8")D=Uint8Array.from(f);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(a==="float16"&&f instanceof Uint16Array&&q!==Uint16Array)D=new globalThis.Float16Array(f.buffer,f.byteOffset,f.length);else throw new TypeError(`A ${T} tensor's data must be type of ${q}`)}else if(B=f,Array.isArray(a)){if(a.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let q=typeof a[0];if(q==="string")T="string",D=a;else if(q==="boolean")T="bool",D=Uint8Array.from(a);else throw new TypeError(`Invalid element type of data array: ${q}.`)}else if(a instanceof Uint8ClampedArray)T="uint8",D=Uint8Array.from(a);else{let q=J.get(a.constructor);if(q===void 0)throw new TypeError(`Unsupported type for tensor data: ${a.constructor}.`);T=q,D=a}if(B===void 0)B=[D.length];else if(!Array.isArray(B))throw new TypeError("A tensor's dims must be a number array");A=B,this.cpuData=D,this.dataLocation="cpu"}let P=Ae(A);if(this.cpuData&&P!==this.cpuData.length&&!((T==="uint4"||T==="int4")&&Math.ceil(P/2)===this.cpuData.length))throw new Error(`Tensor's size(${P}) does not match data length(${this.cpuData.length}).`);this.type=T,this.dims=A,this.size=P}static async fromImage(a,f){return H(a,f)}static fromTexture(a,f){return te(a,f)}static fromGpuBuffer(a,f){return ae(a,f)}static fromMLTensor(a,f){return oe(a,f)}static fromPinnedBuffer(a,f,w){return ie(a,f,w)}toDataURL(a){return U(this,a)}toImageData(a){return W(this,a)}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(a){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 f=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=f,a&&this.disposer&&(this.disposer(),this.disposer=void 0),f}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(a){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Se(this,a)}}}),Ne,Je=h(()=>{we(),Ne=ne}),lt,xt,Rt,He,vt,st,an=h(()=>{O(),lt=(a,f)=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeStamp(`${a}::ORT::${f}`)},xt=(a,f)=>{var A;let w=((A=new Error().stack)==null?void 0:A.split(/\r\n|\r|\n/g))||[],T=!1;for(let P=0;P<w.length;P++){if(T&&!w[P].includes("TRACE_FUNC")){let D=`FUNC_${a}::${w[P].trim().split(" ")[1]}`;f&&(D+=`::${f}`),lt("CPU",D);return}w[P].includes("TRACE_FUNC")&&(T=!0)}},Rt=a=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("BEGIN",a)},He=a=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("END",a)},vt=a=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.time(`ORT::${a}`)},st=a=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeEnd(`ORT::${a}`)}}),sn,Ye=h(()=>{b(),Je(),an(),sn=class D2{constructor(f){this.handler=f}async run(f,w,T){Rt(),vt("InferenceSession.run");let A={},P={};if(typeof f!="object"||f===null||f instanceof Ne||Array.isArray(f))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let D=!0;if(typeof w=="object"){if(w===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(w instanceof Ne)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(w)){if(w.length===0)throw new TypeError("'fetches' cannot be an empty array.");D=!1;for(let G of w){if(typeof G!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(G)===-1)throw new RangeError(`'fetches' contains invalid output name: ${G}.`);A[G]=null}if(typeof T=="object"&&T!==null)P=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else{let G=!1,Z=Object.getOwnPropertyNames(w);for(let ee of this.outputNames)if(Z.indexOf(ee)!==-1){let se=w[ee];(se===null||se instanceof Ne)&&(G=!0,D=!1,A[ee]=se)}if(G){if(typeof T=="object"&&T!==null)P=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else P=w}}else if(typeof w<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let G of this.inputNames)if(typeof f[G]>"u")throw new Error(`input '${G}' is missing in 'feeds'.`);if(D)for(let G of this.outputNames)A[G]=null;let B=await this.handler.run(f,A,P),q={};for(let G in B)if(Object.hasOwnProperty.call(B,G)){let Z=B[G];Z instanceof Ne?q[G]=Z:q[G]=new Ne(Z.type,Z.data,Z.dims)}return st("InferenceSession.run"),He(),q}async release(){return this.handler.dispose()}static async create(f,w,T,A){Rt(),vt("InferenceSession.create");let P,D={};if(typeof f=="string"){if(P=f,typeof w=="object"&&w!==null)D=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else if(f instanceof Uint8Array){if(P=f,typeof w=="object"&&w!==null)D=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else if(f instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&f instanceof SharedArrayBuffer){let Z=f,ee=0,se=f.byteLength;if(typeof w=="object"&&w!==null)D=w;else if(typeof w=="number"){if(ee=w,!Number.isSafeInteger(ee))throw new RangeError("'byteOffset' must be an integer.");if(ee<0||ee>=Z.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${Z.byteLength}).`);if(se=f.byteLength-ee,typeof T=="number"){if(se=T,!Number.isSafeInteger(se))throw new RangeError("'byteLength' must be an integer.");if(se<=0||ee+se>Z.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${Z.byteLength-ee}].`);if(typeof A=="object"&&A!==null)D=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(typeof T<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof w<"u")throw new TypeError("'options' must be an object.");P=new Uint8Array(Z,ee,se)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[B,q]=await y(D),G=await B.createInferenceSessionHandler(P,q);return st("InferenceSession.create"),He(),new D2(G)}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}}}),yt,kt=h(()=>{Ye(),yt=sn}),Kt=h(()=>{}),On=h(()=>{}),Rn=h(()=>{}),Br=h(()=>{}),Tr={};m(Tr,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>vt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,env:()=>I,registerBackend:()=>E});var nt=h(()=>{_(),z(),kt(),Je(),Kt(),On(),an(),Rn(),Br()}),St=h(()=>{}),Tt={};m(Tt,{default:()=>$r});var cn,nn,$r,Ta=h(()=>{var a;_e(),Hr(),Ur(),cn="ort-wasm-proxy-worker",nn=((a=globalThis.self)==null?void 0:a.name)===cn,nn&&(self.onmessage=f=>{let{type:w,in:T}=f.data;try{switch(w){case"init-wasm":ei(T.wasm).then(()=>{Xl(T).then(()=>{postMessage({type:w})},A=>{postMessage({type:w,err:A})})},A=>{postMessage({type:w,err:A})});break;case"init-ep":{let{epName:A,env:P}=T;Lp(P,A).then(()=>{postMessage({type:w})},D=>{postMessage({type:w,err:D})});break}case"copy-from":{let{buffer:A}=T,P=c(A);postMessage({type:w,out:P});break}case"create":{let{model:A,options:P}=T;p(A,P).then(D=>{postMessage({type:w,out:D})},D=>{postMessage({type:w,err:D})});break}case"release":k(T),postMessage({type:w});break;case"run":{let{sessionId:A,inputIndices:P,inputs:D,outputIndices:B,options:q}=T;F(A,P,D,B,new Array(B.length).fill(null),q).then(G=>{G.some(Z=>Z[3]!=="cpu")?postMessage({type:w,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:w,out:G},de([...D,...G]))},G=>{postMessage({type:w,err:G})});break}case"end-profiling":K(T),postMessage({type:w});break;default:}}catch(A){postMessage({type:w,err:A})}}),$r=nn?null:f=>new Worker(f??yn,{type:"classic",name:cn})}),Vo,vi,yn,Fr,Zn,bi,Ms,as,Fi,wi,_i,Is,Ar,Ur=h(()=>{St(),Vo=typeof location>"u"?void 0:location.origin,vi=()=>{var a,f;return typeof document<"u"?(a=document.currentScript)==null?void 0:a.src:typeof self<"u"?(f=self.location)==null?void 0:f.href:void 0},yn=vi(),Fr=()=>{if(yn&&!yn.startsWith("blob:"))return yn.substring(0,yn.lastIndexOf("/")+1)},Zn=(a,f)=>{try{let w=f??yn;return(w?new URL(a,w):new URL(a)).origin===Vo}catch{return!1}},bi=(a,f)=>{let w=f??yn;try{return(w?new URL(a,w):new URL(a)).href}catch{return}},Ms=(a,f)=>`${f??"./"}${a}`,as=async a=>{let f=await(await fetch(a,{credentials:"same-origin"})).blob();return URL.createObjectURL(f)},Fi=async a=>(await import(a)).default,wi=(Ta(),g(Tt)).default,_i=async()=>{if(!yn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Zn(yn))return[void 0,wi()];let a=await as(yn);return[a,wi(a)]},Is=void 0,Ar=async(a,f,w,T)=>{let A=Is&&!(a||f);if(A)if(yn)A=Zn(yn)||T&&!w;else if(T&&!w)A=!0;else throw new Error("cannot determine the script source URL.");if(A)return[void 0,Is];{let P="ort-wasm-simd-threaded.jsep.mjs",D=a??bi(P,f),B=w&&D&&!Zn(D,f),q=B?await as(D):D??Ms(P,f);return[B?q:void 0,await Fi(q)]}}}),Js,Rr,ls,js,ho,Qs,Zs,ei,zt,Hr=h(()=>{Ur(),Rr=!1,ls=!1,js=!1,ho=()=>{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}},Qs=()=>{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}},Zs=()=>{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}},ei=async a=>{if(Rr)return Promise.resolve();if(ls)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(js)throw new Error("previous call to 'initializeWebAssembly()' failed.");ls=!0;let f=a.initTimeout,w=a.numThreads;if(a.simd!==!1){if(a.simd==="relaxed"){if(!Zs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Qs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let T=ho();w>1&&!T&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+w+", 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."),a.numThreads=w=1);let A=a.wasmPaths,P=typeof A=="string"?A:void 0,D=A==null?void 0:A.mjs,B=(D==null?void 0:D.href)??D,q=A==null?void 0:A.wasm,G=(q==null?void 0:q.href)??q,Z=a.wasmBinary,[ee,se]=await Ar(B,P,w>1,!!Z||!!G),ue=!1,he=[];if(f>0&&he.push(new Promise(ge=>{setTimeout(()=>{ue=!0,ge()},f)})),he.push(new Promise((ge,ke)=>{let xe={numThreads:w};if(Z)xe.wasmBinary=Z,xe.locateFile=me=>me;else if(G||P)xe.locateFile=me=>G??P+me;else if(B&&B.indexOf("blob:")!==0)xe.locateFile=me=>new URL(me,B).href;else if(ee){let me=Fr();me&&(xe.locateFile=Ee=>me+Ee)}se(xe).then(me=>{ls=!1,Rr=!0,Js=me,ge(),ee&&URL.revokeObjectURL(ee)},me=>{ls=!1,js=!0,ke(me)})})),await Promise.race(he),ue)throw new Error(`WebAssembly backend initializing failed due to timeout: ${f}ms`)},zt=()=>{if(Rr&&Js)return Js;throw new Error("WebAssembly is not initialized yet.")}}),Hn,_n,Ct,Ui=h(()=>{Hr(),Hn=(a,f)=>{let w=zt(),T=w.lengthBytesUTF8(a)+1,A=w._malloc(T);return w.stringToUTF8(a,A,T),f.push(A),A},_n=(a,f,w,T)=>{if(typeof a=="object"&&a!==null){if(w.has(a))throw new Error("Circular reference in options");w.add(a)}Object.entries(a).forEach(([A,P])=>{let D=f?f+A:A;if(typeof P=="object")_n(P,D+".",w,T);else if(typeof P=="string"||typeof P=="number")T(D,P.toString());else if(typeof P=="boolean")T(D,P?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof P}`)})},Ct=a=>{let f=zt(),w=f.stackSave();try{let T=f.PTR_SIZE,A=f.stackAlloc(2*T);f._OrtGetLastError(A,A+T);let P=Number(f.getValue(A,T===4?"i32":"i64")),D=f.getValue(A+T,"*"),B=D?f.UTF8ToString(D):"";throw new Error(`${a} ERROR_CODE: ${P}, ERROR_MESSAGE: ${B}`)}finally{f.stackRestore(w)}}}),fo,$a=h(()=>{Hr(),Ui(),fo=a=>{let f=zt(),w=0,T=[],A=a||{};try{if((a==null?void 0:a.logSeverityLevel)===void 0)A.logSeverityLevel=2;else if(typeof a.logSeverityLevel!="number"||!Number.isInteger(a.logSeverityLevel)||a.logSeverityLevel<0||a.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${a.logSeverityLevel}`);if((a==null?void 0:a.logVerbosityLevel)===void 0)A.logVerbosityLevel=0;else if(typeof a.logVerbosityLevel!="number"||!Number.isInteger(a.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${a.logVerbosityLevel}`);(a==null?void 0:a.terminate)===void 0&&(A.terminate=!1);let P=0;return(a==null?void 0:a.tag)!==void 0&&(P=Hn(a.tag,T)),w=f._OrtCreateRunOptions(A.logSeverityLevel,A.logVerbosityLevel,!!A.terminate,P),w===0&&Ct("Can't create run options."),(a==null?void 0:a.extra)!==void 0&&_n(a.extra,"",new WeakSet,(D,B)=>{let q=Hn(D,T),G=Hn(B,T);f._OrtAddRunConfigEntry(w,q,G)!==0&&Ct(`Can't set a run config entry: ${D} - ${B}.`)}),[w,T]}catch(P){throw w!==0&&f._OrtReleaseRunOptions(w),T.forEach(D=>f._free(D)),P}}}),po,mo,Go,Sr,Aa,Ra,kn=h(()=>{Hr(),Ui(),po=a=>{switch(a){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: ${a}`)}},mo=a=>{switch(a){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${a}`)}},Go=a=>{a.extra||(a.extra={}),a.extra.session||(a.extra.session={});let f=a.extra.session;f.use_ort_model_bytes_directly||(f.use_ort_model_bytes_directly="1"),a.executionProviders&&a.executionProviders.some(w=>(typeof w=="string"?w:w.name)==="webgpu")&&(a.enableMemPattern=!1)},Sr=(a,f,w,T)=>{let A=Hn(f,T),P=Hn(w,T);zt()._OrtAddSessionConfigEntry(a,A,P)!==0&&Ct(`Can't set a session config entry: ${f} - ${w}.`)},Aa=async(a,f,w)=>{let T=f.executionProviders;for(let A of T){let P=typeof A=="string"?A:A.name,D=[];switch(P){case"webnn":if(P="WEBNN",Sr(a,"session.disable_quant_qdq","1",w),Sr(a,"session.disable_qdq_constant_folding","1",w),typeof A!="string"){let ee=A==null?void 0:A.deviceType;ee&&Sr(a,"deviceType",ee,w)}break;case"webgpu":if(P="JS",typeof A!="string"){let ee=A;if(ee!=null&&ee.preferredLayout){if(ee.preferredLayout!=="NCHW"&&ee.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${ee.preferredLayout}`);Sr(a,"preferredLayout",ee.preferredLayout,w)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${P}`)}let B=Hn(P,w),q=D.length,G=0,Z=0;if(q>0){G=zt()._malloc(q*zt().PTR_SIZE),w.push(G),Z=zt()._malloc(q*zt().PTR_SIZE),w.push(Z);for(let ee=0;ee<q;ee++)zt().setValue(G+ee*zt().PTR_SIZE,D[ee][0],"*"),zt().setValue(Z+ee*zt().PTR_SIZE,D[ee][1],"*")}await zt()._OrtAppendExecutionProvider(a,B,G,Z,q)!==0&&Ct(`Can't append execution provider: ${P}.`)}},Ra=async a=>{let f=zt(),w=0,T=[],A=a||{};Go(A);try{let P=po(A.graphOptimizationLevel??"all"),D=mo(A.executionMode??"sequential"),B=typeof A.logId=="string"?Hn(A.logId,T):0,q=A.logSeverityLevel??2;if(!Number.isInteger(q)||q<0||q>4)throw new Error(`log severity level is not valid: ${q}`);let G=A.logVerbosityLevel??0;if(!Number.isInteger(G)||G<0||G>4)throw new Error(`log verbosity level is not valid: ${G}`);let Z=typeof A.optimizedModelFilePath=="string"?Hn(A.optimizedModelFilePath,T):0;if(w=f._OrtCreateSessionOptions(P,!!A.enableCpuMemArena,!!A.enableMemPattern,D,!!A.enableProfiling,0,B,q,G,Z),w===0&&Ct("Can't create session options."),A.executionProviders&&await Aa(w,A,T),A.enableGraphCapture!==void 0){if(typeof A.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${A.enableGraphCapture}`);Sr(w,"enableGraphCapture",A.enableGraphCapture.toString(),T)}if(A.freeDimensionOverrides)for(let[ee,se]of Object.entries(A.freeDimensionOverrides)){if(typeof ee!="string")throw new Error(`free dimension override name must be a string: ${ee}`);if(typeof se!="number"||!Number.isInteger(se)||se<0)throw new Error(`free dimension override value must be a non-negative integer: ${se}`);let ue=Hn(ee,T);f._OrtAddFreeDimensionOverride(w,ue,se)!==0&&Ct(`Can't set a free dimension override: ${ee} - ${se}.`)}return A.extra!==void 0&&_n(A.extra,"",new WeakSet,(ee,se)=>{Sr(w,ee,se,T)}),[w,T]}catch(P){throw w!==0&&f._OrtReleaseSessionOptions(w)!==0&&Ct("Can't release session options."),T.forEach(D=>f._free(D)),P}}}),Mr,Vn,Ir,ti,Hi,ki,cs,gr,Bt=h(()=>{Mr=a=>{switch(a){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: ${a}`)}},Vn=a=>{switch(a){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: ${a}`)}},Ir=(a,f)=>{let w=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][a],T=typeof f=="number"?f:f.reduce((A,P)=>A*P,1);return w>0?Math.ceil(T*w):void 0},ti=a=>{switch(a){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: ${a}`)}},Hi=a=>{switch(a){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: ${a}`)}},ki=a=>a==="float32"||a==="float16"||a==="int32"||a==="int64"||a==="uint32"||a==="uint8"||a==="bool"||a==="uint4"||a==="int4",cs=a=>a==="float32"||a==="float16"||a==="int32"||a==="int64"||a==="uint32"||a==="uint64"||a==="int8"||a==="uint8"||a==="bool"||a==="uint4"||a==="int4",gr=a=>{switch(a){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: ${a}`)}}}),Gn,Si=h(()=>{St(),Gn=async a=>{if(typeof a=="string"){let f=await fetch(a);if(!f.ok)throw new Error(`failed to load external data file: ${a}`);let w=f.headers.get("Content-Length"),T=w?parseInt(w,10):0;if(T<1073741824)return new Uint8Array(await f.arrayBuffer());{if(!f.body)throw new Error(`failed to load external data file: ${a}, no response body.`);let A=f.body.getReader(),P;try{P=new ArrayBuffer(T)}catch(B){if(B instanceof RangeError){let q=Math.ceil(T/65536);P=new WebAssembly.Memory({initial:q,maximum:q}).buffer}else throw B}let D=0;for(;;){let{done:B,value:q}=await A.read();if(B)break;let G=q.byteLength;new Uint8Array(P,D,G).set(q),D+=G}return new Uint8Array(P,0,T)}}else return a instanceof Blob?new Uint8Array(await a.arrayBuffer()):a instanceof Uint8Array?a:new Uint8Array(a)}}),us,Ko,Ci,Wr,Ps,ji,on,ds=h(()=>{Bt(),us=["V","I","W","E","F"],Ko=(a,f)=>{console.log(`[${us[a]},${new Date().toISOString()}]${f}`)},Ps=(a,f)=>{Ci=a,Wr=f},ji=(a,f)=>{let w=Hi(a),T=Hi(Ci);w>=T&&Ko(w,typeof f=="function"?f():f)},on=(...a)=>{Wr&&ji(...a)}}),Wi,Es,Ke,qr,ft,be,Pe,Qe=h(()=>{Wi=class{static calcMatMulShape(a,f){return a[1]!==f[0]?void 0:[a[0],f[1]]}},Es=class{static calcShape(a,f,w=!1){let T=a.length,A=f.length;if(T===0)return f;if(A===0)return a;let P=Math.max(a.length,f.length),D=new Array(P);if(w){if(T<2||A<2)return;let B=Wi.calcMatMulShape([a[T-2],a[T-1]],[f[A-2],f[A-1]]);if(B===void 0)return;[D[P-2],D[P-1]]=B}for(let B=w?3:1;B<=P;B++){let q=T-B<0?1:a[T-B],G=A-B<0?1:f[A-B];if(q!==G&&q>1&&G>1)return;let Z=Math.max(q,G);if(q&&G)D[P-B]=Math.max(q,G);else{if(Z>1)return;D[P-B]=0}}return D}static isValidBroadcast(a,f){let w=a.length,T=f.length;if(w>T)return!1;for(let A=1;A<=w;A++)if(a[w-A]!==1&&a[w-A]!==f[T-A])return!1;return!0}},Ke=class Xx{static size(f){return Xx.getSizeFromDimensionRange(f,0,f.length)}static convertShape(f,w=4){let T=f.length;if(T===0)return[];let A=new Array(T),P=T-1;for(;P>=0;){if(f[P]%w===0){A[P]=f[P]/w;break}if(w%f[P]!==0)throw new Error("cannot convert shape");A[P]=1,w/=f[P],P--}for(P--;P>=0;P--)A[P]=f[P];return A}static sizeFromDimension(f,w){if(w<0||w>f.length)throw new Error(`invalid dimension of ${w} for sizeFromDimension as Tensor has ${f.length} dimensions.`);return Xx.getSizeFromDimensionRange(f,w,f.length)}static sizeToDimension(f,w){if(w<0||w>f.length)throw new Error(`invalid dimension of ${w} for sizeToDimension as Tensor has ${f.length} dimensions.`);return Xx.getSizeFromDimensionRange(f,0,w)}static getSizeFromDimensionRange(f,w,T){let A=1;for(let P=w;P<T;P++){if(f[P]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");A*=Number(f[P])}return A}static computeStrides(f){let w=f.length;if(w===0)return[];if(w===1)return[1];let T=new Array(w);T[w-1]=1,T[w-2]=f[w-1];for(let A=w-3;A>=0;--A)T[A]=T[A+1]*f[A+1];return T}static normalizeAxis(f,w){if(f<-w&&f>=w)throw new Error("unsupported axis for this operation.");return f<0?f+w:f}static normalizeAxes(f,w){return f.map(T=>this.normalizeAxis(T,w??f.length))}static sortBasedOnPerm(f,w){return w?w.map(T=>f[T]):f.slice().reverse()}static padShape(f,w){let T=f.length;return f.map((A,P)=>A+w[P]+w[P+T])}static areEqual(f,w){return f.length!==w.length?!1:f.every((T,A)=>T===w[A])}},qr=class vm{static adjustPoolAttributes(f,w,T,A,P,D){if(!f&&T.length!==w.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(f)for(let B=0;B<w.length-2;B++)B>=T.length?T.push(w[B+2]):T[B]=w[B+2];for(let B=0;B<T.length;B++)if(B<A.length){if(A[B]<0)throw new Error("strides should be greater than or equal to 1")}else A.push(1);for(let B=0;B<T.length;B++)if(B<P.length){if(P[B]<0)throw new Error("dilations should be greater than or equal to 1")}else P.push(1);for(let B=0;B<T.length*2;B++)if(B<D.length){if(D[B]<0)throw new Error("pad should be greater than or equal to 1")}else D.push(0);for(let B=0;B<T.length;B++){if(T[B]<=0)throw new Error("kernel shapes need to be greater than 0");if(D[B]>=T[B]||D[B+T.length]>=T[B])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(f,w,T,A,P,D,B){if(B){if(P.length!==2*(f.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(w.length!==f.length-2)throw new Error("length of strides should be the length of data dimensions");if(A.length!==f.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let q=0;q<f.length-2;q++)vm.adjustPadAndReturnShape(f[q+(D?1:2)],w[q],T[q],A[q],P,q,q+f.length-2,B)}}static computePoolOutputShape(f,w,T,A,P,D,B){if(w.length<=0)throw new Error("input shape must be of size greater than 0");let q=[w[0],w[1]];return vm.computeShapeHelper(f,w,q,T,A,P,D,B),q}static computeConvOutputShape(f,w,T,A,P,D,B){if(f.length<=0||w.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let q=[f[0],w[0]];return vm.computeShapeHelper(!1,f,q,T,A,P,D,B),q}static computeShapeHelper(f,w,T,A,P,D,B,q){if(f)for(let G=0;G<w.length-2;G++)T.push(1);else for(let G=0;G<w.length-2;G++)T.push(vm.adjustPadAndReturnShape(w[G+2],A[G],P[G],D[G],B,G,G+w.length-2,q))}static adjustPadAndReturnShape(f,w,T,A,P,D,B,q){let G=T*(A-1)+1;if(q&&q!=="NOTSET")switch(q){case"VALID":return P[D]=0,P[B]=0,Math.floor((f-G)/w+1);case"SAME_LOWER":case"SAME_UPPER":if(T!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let Z=((f+w-1)/w-1)*w+A-f;return P[D]=Math.floor(q==="SAME_LOWER"?(Z+1)/2:Z/2),P[B]=Z-P[D],Math.floor((f+Z-A)/w+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((f+P[D]+P[B]-G)/w+1)}},ft=class{static getShapeOfGemmResult(a,f,w,T,A){if(a.length!==2||w.length!==2)throw new Error("shape need to be of size 2");let P,D,B;f?(P=a[1],D=a[0]):(P=a[0],D=a[1]);let q=-1;if(T?(B=w[0],q=1):(B=w[1],q=0),w[q]!==D)throw new Error("dimension mismatch");if(P<=0||B<=0||D<=0)throw new Error("invalid shape specified");if(A&&!Es.isValidBroadcast(A,[P,B]))throw new Error("gemm: invalid bias shape for broadcast");return[P,B,D]}},be=-34028234663852886e22,Pe=34028234663852886e22}),Et,en=h(()=>{Bt(),Et=(a,f)=>new(ti(f))(a)}),ln,$n,En,er,Ln,sr,Nn,Ds,qi,go,ni,Vu=h(()=>{Bt(),ds(),ln=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),$n=(a,f)=>{if(f==="int32")return a;let w=ln.get(f);if(!w)throw new Error(`WebNN backend does not support data type: ${f}`);let T=w/8;if(a.byteLength%T!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${T}.`);let A=a.byteLength/T,P=new(ti(f))(a.buffer,a.byteOffset,A);switch(f){case"int64":case"uint64":{let D=new Int32Array(A);for(let B=0;B<A;B++){let q=P[B];if(q>2147483647n||q<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");D[B]=Number(q)}return new Uint8Array(D.buffer)}case"int8":case"uint8":case"uint32":{if(f==="uint32"&&P.some(B=>B>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let D=Int32Array.from(P,Number);return new Uint8Array(D.buffer)}default:throw new Error(`Unsupported data conversion from ${f} to 'int32'`)}},En=(a,f)=>{if(f==="int32")return a;if(a.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let w=a.byteLength/4,T=new Int32Array(a.buffer,a.byteOffset,w);switch(f){case"int64":{let A=BigInt64Array.from(T,BigInt);return new Uint8Array(A.buffer)}case"uint64":{if(T.some(P=>P<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let A=BigUint64Array.from(T,BigInt);return new Uint8Array(A.buffer)}case"int8":{if(T.some(P=>P<-128||P>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let A=Int8Array.from(T,Number);return new Uint8Array(A.buffer)}case"uint8":{if(T.some(A=>A<0||A>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(T,Number)}case"uint32":{if(T.some(P=>P<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let A=Uint32Array.from(T,Number);return new Uint8Array(A.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${f}`)}},er=1,Ln=()=>er++,sr=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Nn=(a,f)=>{let w=ln.get(a);if(!w)throw new Error(`WebNN backend does not support data type: ${a}`);return f.length>0?Math.ceil(f.reduce((T,A)=>T*A)*w/8):0},Ds=class{constructor(a){this.isDataConverted=!1;let{sessionId:f,context:w,tensor:T,dataType:A,shape:P,fallbackDataType:D}=a;this.sessionId=f,this.mlContext=w,this.mlTensor=T,this.dataType=A,this.tensorShape=P,this.fallbackDataType=D}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Nn(this.dataType,this.tensorShape)}destroy(){on("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(a){this.mlContext.writeTensor(this.mlTensor,a)}async read(a){if(this.fallbackDataType){let f=await this.mlContext.readTensor(this.mlTensor),w=En(new Uint8Array(f),this.dataType);if(a){(a instanceof ArrayBuffer?new Uint8Array(a):new Uint8Array(a.buffer,a.byteOffset,a.byteLength)).set(w);return}else return w.buffer}else return a?this.mlContext.readTensor(this.mlTensor,a):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(a,f,w){return this.mlContext===a&&this.dataType===f&&this.tensorShape.length===w.length&&this.tensorShape.every((T,A)=>T===w[A])}setIsDataConverted(a){this.isDataConverted=a}},qi=class{constructor(a,f){this.tensorManager=a,this.wrapper=f}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(a,f,w,T){let A=this.tensorManager.getMLContext(a),P=this.tensorManager.getMLOpSupportLimits(a),D;if(!(P!=null&&P.input.dataTypes.includes(f))){if(D=sr.get(f),!D||(P==null?void 0:P.input.dataTypes.includes(D)))throw new Error(`WebNN backend does not support data type: ${f}`);on("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${f} to ${D}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(A,f,w))return this.wrapper.tensor;if(T){if(this.wrapper.byteLength!==Nn(f,w))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let B=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(a,f,w,B,!0,!0,D),T&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(a){let f=a;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")f=$n(a,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(a.byteLength===this.wrapper.byteLength){this.wrapper.write(f);return}else on("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(f):this.activeUpload=new Uint8Array(f)}async download(a){var f,w;if(this.activeUpload){let T=(f=this.wrapper)!=null&&f.isDataConverted?En(this.activeUpload,(w=this.wrapper)==null?void 0:w.type):this.activeUpload;if(a){a instanceof ArrayBuffer?new Uint8Array(a).set(T):new Uint8Array(a.buffer,a.byteOffset,a.byteLength).set(T);return}else return T.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return a?this.wrapper.read(a):this.wrapper.read()}},go=class{constructor(a){this.backend=a,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(a){let f=this.backend.getMLContext(a);if(!f)throw new Error("MLContext not found for session.");return f}getMLOpSupportLimits(a){return this.backend.getMLOpSupportLimits(a)}reserveTensorId(){let a=Ln();return this.tensorTrackersById.set(a,new qi(this)),a}releaseTensorId(a){let f=this.tensorTrackersById.get(a);f&&(this.tensorTrackersById.delete(a),f.tensorWrapper&&this.releaseTensor(f.tensorWrapper))}async ensureTensor(a,f,w,T,A){on("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${f}, dataType: ${w}, shape: ${T}, copyOld: ${A}}`);let P=this.tensorTrackersById.get(f);if(!P)throw new Error("Tensor not found.");return P.ensureTensor(a,w,T,A)}upload(a,f){let w=this.tensorTrackersById.get(a);if(!w)throw new Error("Tensor not found.");w.upload(f)}async download(a,f){on("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${a}, dstBuffer: ${f==null?void 0:f.byteLength}}`);let w=this.tensorTrackersById.get(a);if(!w)throw new Error("Tensor not found.");return w.download(f)}releaseTensorsForSession(a){for(let f of this.freeTensors)f.sessionId===a&&f.destroy();this.freeTensors=this.freeTensors.filter(f=>f.sessionId!==a)}registerTensor(a,f,w,T){let A=this.getMLContext(a),P=Ln(),D=new Ds({sessionId:a,context:A,tensor:f,dataType:w,shape:T});return this.tensorTrackersById.set(P,new qi(this,D)),this.externalTensors.add(D),P}async getCachedTensor(a,f,w,T,A,P,D){let B=this.getMLContext(a);for(let[G,Z]of this.freeTensors.entries())if(Z.canReuseTensor(B,f,w)){on("verbose",()=>`[WebNN] Reusing tensor {dataType: ${f}, ${D?`fallbackDataType: ${D},`:""} shape: ${w}`);let ee=this.freeTensors.splice(G,1)[0];return ee.sessionId=a,ee}on("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${f}, ${D?`fallbackDataType: ${D},`:""} shape: ${w}}`);let q=await B.createTensor({dataType:D??f,shape:w,dimensions:w,usage:T,writable:A,readable:P});return new Ds({sessionId:a,context:B,tensor:q,dataType:f,shape:w,fallbackDataType:D})}releaseTensor(a){this.externalTensors.has(a)&&this.externalTensors.delete(a),this.freeTensors.push(a)}},ni=(...a)=>new go(...a)}),xo,yo,Sc,bl=h(()=>{Bt(),Hr(),en(),Vu(),ds(),xo=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),yo=(a,f)=>{if(a===f)return!0;if(a===void 0||f===void 0)return!1;let w=Object.keys(a).sort(),T=Object.keys(f).sort();return w.length===T.length&&w.every((A,P)=>A===T[P]&&a[A]===f[A])},Sc=class{constructor(a){this.tensorManager=ni(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,Ps(a.logLevel,!!a.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(a){on("verbose",()=>`[WebNN] onRunStart {sessionId: ${a}}`),this.activeSessionId=a}onRunEnd(a){on("verbose",()=>`[WebNN] onRunEnd {sessionId: ${a}}`);let f=this.temporarySessionTensorIds.get(a);if(f){for(let w of f)on("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${w}}`),this.tensorManager.releaseTensorId(w);this.temporarySessionTensorIds.delete(a),this.activeSessionId=void 0}}async createMLContext(a){if(a instanceof GPUDevice){let w=this.mlContextCache.findIndex(T=>T.gpuDevice===a);if(w!==-1)return this.mlContextCache[w].mlContext;{let T=await navigator.ml.createContext(a);return this.mlContextCache.push({gpuDevice:a,mlContext:T}),T}}else if(a===void 0){let w=this.mlContextCache.findIndex(T=>T.options===void 0&&T.gpuDevice===void 0);if(w!==-1)return this.mlContextCache[w].mlContext;{let T=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:T}),T}}let f=this.mlContextCache.findIndex(w=>yo(w.options,a));if(f!==-1)return this.mlContextCache[f].mlContext;{let w=await navigator.ml.createContext(a);return this.mlContextCache.push({options:a,mlContext:w}),w}}registerMLContext(a,f){this.mlContextBySessionId.set(a,f);let w=this.sessionIdsByMLContext.get(f);w||(w=new Set,this.sessionIdsByMLContext.set(f,w)),w.add(a),this.mlOpSupportLimitsBySessionId.has(a)||this.mlOpSupportLimitsBySessionId.set(a,f.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(a,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(a,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(a){this.sessionGraphInputs.delete(a),this.sessionGraphOutputs.delete(a);let f=this.mlContextBySessionId.get(a);if(!f)return;this.tensorManager.releaseTensorsForSession(a),this.mlContextBySessionId.delete(a),this.mlOpSupportLimitsBySessionId.delete(a);let w=this.sessionIdsByMLContext.get(f);if(w.delete(a),w.size===0){this.sessionIdsByMLContext.delete(f);let T=this.mlContextCache.findIndex(A=>A.mlContext===f);T!==-1&&this.mlContextCache.splice(T,1)}}getMLContext(a){return this.mlContextBySessionId.get(a)}getMLOpSupportLimits(a){return this.mlOpSupportLimitsBySessionId.get(a)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(a){on("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${a}}`),this.tensorManager.releaseTensorId(a)}async ensureTensor(a,f,w,T,A){let P=xo.get(w);if(!P)throw new Error(`Unsupported ONNX data type: ${w}`);return this.tensorManager.ensureTensor(a??this.currentSessionId,f,P,T,A)}async createTemporaryTensor(a,f,w){on("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${f}, shape: ${w}}`);let T=xo.get(f);if(!T)throw new Error(`Unsupported ONNX data type: ${f}`);let A=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(a,A,T,w,!1);let P=this.temporarySessionTensorIds.get(a);return P?P.push(A):this.temporarySessionTensorIds.set(a,[A]),A}uploadTensor(a,f){if(!zt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");on("verbose",()=>`[WebNN] uploadTensor {tensorId: ${a}, data: ${f.byteLength}}`),this.tensorManager.upload(a,f)}async downloadTensor(a,f){return this.tensorManager.download(a,f)}createMLTensorDownloader(a,f){return async()=>{let w=await this.tensorManager.download(a);return Et(w,f)}}registerMLTensor(a,f,w,T){let A=xo.get(w);if(!A)throw new Error(`Unsupported ONNX data type: ${w}`);let P=this.tensorManager.registerTensor(a,f,A,T);return on("verbose",()=>`[WebNN] registerMLTensor {tensor: ${f}, dataType: ${A}, dimensions: ${T}} -> {tensorId: ${P}}`),P}registerMLConstant(a,f,w,T,A,P,D=!1){if(!P)throw new Error("External mounted files are not available.");let B=a;a.startsWith("./")&&(B=a.substring(2));let q=P.get(B);if(!q)throw new Error(`File with name ${B} not found in preloaded files.`);if(f+w>q.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let G=q.slice(f,f+w).buffer,Z;switch(A.dataType){case"float32":Z=new Float32Array(G);break;case"float16":Z=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(G):new Uint16Array(G);break;case"int32":Z=new Int32Array(G);break;case"uint32":Z=new Uint32Array(G);break;case"int64":if(D){let ee=$n(new Uint8Array(G),"int64");Z=new Int32Array(ee.buffer),A.dataType="int32"}else Z=new BigInt64Array(G);break;case"uint64":Z=new BigUint64Array(G);break;case"int8":Z=new Int8Array(G);break;case"int4":case"uint4":case"uint8":Z=new Uint8Array(G);break;default:throw new Error(`Unsupported data type: ${A.dataType} in creating WebNN Constant from external data.`)}return on("verbose",()=>`[WebNN] registerMLConstant {dataType: ${A.dataType}, shape: ${A.shape}}} ${D?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),T.constant(A,Z)}registerGraphInput(a){this.temporaryGraphInputs.push(a)}registerGraphOutput(a){this.temporaryGraphOutputs.push(a)}isGraphInput(a,f){let w=this.sessionGraphInputs.get(a);return w?w.includes(f):!1}isGraphOutput(a,f){let w=this.sessionGraphOutputs.get(a);return w?w.includes(f):!1}isGraphInputOutputTypeSupported(a,f,w=!0){let T=xo.get(Mr(f)),A=this.mlOpSupportLimitsBySessionId.get(a);return typeof T>"u"?!1:w?!!(A!=null&&A.input.dataTypes.includes(T)):!!(A!=null&&A.output.dataTypes.includes(T))}flush(){}}}),vo=h(()=>{}),Ma,wl,Ei,Vi,Ni,bo,Cc,jc,_l,kl=h(()=>{ds(),vo(),Ma=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),wl=[],Ei=a=>Math.ceil(Number(a)/16)*16,Vi=a=>{for(let f=0;f<wl.length;f++){let w=wl[f];if(a<=w)return w}return Math.ceil(a/16)*16},Ni=1,bo=()=>Ni++,Cc=async(a,f,w,T)=>{let A=Ei(w),P=a.device.createBuffer({size:A,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let D=a.getCommandEncoder();a.endComputePass(),D.copyBufferToBuffer(f,0,P,0,A),a.flush(),await P.mapAsync(GPUMapMode.READ);let B=P.getMappedRange();if(T){let q=T();return q.set(new Uint8Array(B,0,w)),q}else return new Uint8Array(B.slice(0,w))}finally{P.destroy()}},jc=class{constructor(a){this.backend=a,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[f]of Ma)wl.push(f),this.freeBuffers.set(f,[]),this.freeUniformBuffers.set(f,[]);this.sessionCount=0}upload(a,f){let w=f.buffer,T=f.byteOffset,A=f.byteLength,P=Ei(A),D=this.storageCache.get(a);if(!D)throw new Error("gpu data for uploading does not exist");if(Number(D.originalSize)!==A)throw new Error(`inconsistent data size. gpu data size=${D.originalSize}, data size=${A}`);let B=this.backend.device.createBuffer({mappedAtCreation:!0,size:P,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),q=B.getMappedRange();new Uint8Array(q).set(new Uint8Array(w,T,A)),B.unmap();let G=this.backend.device.createCommandEncoder();G.copyBufferToBuffer(B,0,D.gpuData.buffer,0,P),this.backend.device.queue.submit([G.finish()]),B.destroy(),on("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${a})`)}memcpy(a,f){let w=this.storageCache.get(a);if(!w)throw new Error("source gpu data for memcpy does not exist");let T=this.storageCache.get(f);if(!T)throw new Error("destination gpu data for memcpy does not exist");if(w.originalSize!==T.originalSize)throw new Error("inconsistent source and destination gpu data size");let A=Ei(w.originalSize),P=this.backend.getCommandEncoder();this.backend.endComputePass(),P.copyBufferToBuffer(w.gpuData.buffer,0,T.gpuData.buffer,0,A)}registerExternalBuffer(a,f,w){let T;if(w){if(T=w[0],a===w[1])return on("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${f}) => id=${T}, buffer is the same, skip.`),T;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.
|
|
47
|
+
*/var j_;function oT(){return j_||(j_=1,(function(e,n){var r=(()=>{var i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,u=(a=>typeof oo<"u"?oo:typeof Proxy<"u"?new Proxy(a,{get:(f,w)=>(typeof oo<"u"?oo:f)[w]}):a)(function(a){if(typeof oo<"u")return oo.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')}),h=(a,f)=>()=>(a&&(f=a(a=0)),f),m=(a,f)=>{for(var w in f)i(a,w,{get:f[w],enumerable:!0})},x=(a,f,w,T)=>{if(f&&typeof f=="object"||typeof f=="function")for(let A of l(f))!d.call(a,A)&&A!==w&&i(a,A,{get:()=>f[A],enumerable:!(T=o(f,A))||T.enumerable});return a},g=a=>x(i({},"__esModule",{value:!0}),a),v,S,E,j,y,b=h(()=>{v=new Map,S=[],E=(a,f,w)=>{if(f&&typeof f.init=="function"&&typeof f.createInferenceSessionHandler=="function"){let T=v.get(a);if(T===void 0)v.set(a,{backend:f,priority:w});else{if(T.priority>w)return;if(T.priority===w&&T.backend!==f)throw new Error(`cannot register backend "${a}" using priority ${w}`)}if(w>=0){let A=S.indexOf(a);A!==-1&&S.splice(A,1);for(let P=0;P<S.length;P++)if(v.get(S[P]).priority<=w){S.splice(P,0,a);return}S.push(a)}return}throw new TypeError("not a valid backend")},j=async a=>{let f=v.get(a);if(!f)return"backend not found.";if(f.initialized)return f.backend;if(f.aborted)return f.error;{let w=!!f.initPromise;try{return w||(f.initPromise=f.backend.init(a)),await f.initPromise,f.initialized=!0,f.backend}catch(T){return w||(f.error=`${T}`,f.aborted=!0),f.error}finally{delete f.initPromise}}},y=async a=>{let f=a.executionProviders||[],w=f.map(q=>typeof q=="string"?q:q.name),T=w.length===0?S:w,A,P=[],D=new Set;for(let q of T){let G=await j(q);typeof G=="string"?P.push({name:q,err:G}):(A||(A=G),A===G&&D.add(q))}if(!A)throw new Error(`no available backend found. ERR: ${P.map(q=>`[${q.name}] ${q.err}`).join(", ")}`);for(let{name:q,err:G}of P)w.includes(q)&&console.warn(`removing requested execution provider "${q}" from session options because it is not available: ${G}`);let B=f.filter(q=>D.has(typeof q=="string"?q:q.name));return[A,new Proxy(a,{get:(q,G)=>G==="executionProviders"?B:Reflect.get(q,G)})]}}),_=h(()=>{b()}),C,N=h(()=>{C="1.26.0"}),$,R,O=h(()=>{N(),$="warning",R={wasm:{},webgl:{},webgpu:{},versions:{common:C},set logLevel(a){if(a!==void 0){if(typeof a!="string"||["verbose","info","warning","error","fatal"].indexOf(a)===-1)throw new Error(`Unsupported logging level: ${a}`);$=a}},get logLevel(){return $}},Object.defineProperty(R,"logLevel",{enumerable:!0})}),I,z=h(()=>{O(),I=R}),U,W,Y=h(()=>{U=(a,f)=>{let w=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);w.width=a.dims[3],w.height=a.dims[2];let T=w.getContext("2d");if(T!=null){let A,P;(f==null?void 0:f.tensorLayout)!==void 0&&f.tensorLayout==="NHWC"?(A=a.dims[2],P=a.dims[3]):(A=a.dims[3],P=a.dims[2]);let D=(f==null?void 0:f.format)!==void 0?f.format:"RGB",B=f==null?void 0:f.norm,q,G;B===void 0||B.mean===void 0?q=[255,255,255,255]:typeof B.mean=="number"?q=[B.mean,B.mean,B.mean,B.mean]:(q=[B.mean[0],B.mean[1],B.mean[2],0],B.mean[3]!==void 0&&(q[3]=B.mean[3])),B===void 0||B.bias===void 0?G=[0,0,0,0]:typeof B.bias=="number"?G=[B.bias,B.bias,B.bias,B.bias]:(G=[B.bias[0],B.bias[1],B.bias[2],0],B.bias[3]!==void 0&&(G[3]=B.bias[3]));let Z=P*A,ee=0,se=Z,ue=Z*2,he=-1;D==="RGBA"?(ee=0,se=Z,ue=Z*2,he=Z*3):D==="RGB"?(ee=0,se=Z,ue=Z*2):D==="RBG"&&(ee=0,ue=Z,se=Z*2);for(let ge=0;ge<P;ge++)for(let ke=0;ke<A;ke++){let xe=(a.data[ee++]-G[0])*q[0],me=(a.data[se++]-G[1])*q[1],Ee=(a.data[ue++]-G[2])*q[2],je=he===-1?255:(a.data[he++]-G[3])*q[3];T.fillStyle="rgba("+xe+","+me+","+Ee+","+je+")",T.fillRect(ke,ge,1,1)}if("toDataURL"in w)return w.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},W=(a,f)=>{let w=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),T;if(w!=null){let A,P,D;(f==null?void 0:f.tensorLayout)!==void 0&&f.tensorLayout==="NHWC"?(A=a.dims[2],P=a.dims[1],D=a.dims[3]):(A=a.dims[3],P=a.dims[2],D=a.dims[1]);let B=f!==void 0&&f.format!==void 0?f.format:"RGB",q=f==null?void 0:f.norm,G,Z;q===void 0||q.mean===void 0?G=[255,255,255,255]:typeof q.mean=="number"?G=[q.mean,q.mean,q.mean,q.mean]:(G=[q.mean[0],q.mean[1],q.mean[2],255],q.mean[3]!==void 0&&(G[3]=q.mean[3])),q===void 0||q.bias===void 0?Z=[0,0,0,0]:typeof q.bias=="number"?Z=[q.bias,q.bias,q.bias,q.bias]:(Z=[q.bias[0],q.bias[1],q.bias[2],0],q.bias[3]!==void 0&&(Z[3]=q.bias[3]));let ee=P*A;if(f!==void 0&&(f.format!==void 0&&D===4&&f.format!=="RGBA"||D===3&&f.format!=="RGB"&&f.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let se=4,ue=0,he=1,ge=2,ke=3,xe=0,me=ee,Ee=ee*2,je=-1;B==="RGBA"?(xe=0,me=ee,Ee=ee*2,je=ee*3):B==="RGB"?(xe=0,me=ee,Ee=ee*2):B==="RBG"&&(xe=0,Ee=ee,me=ee*2),T=w.createImageData(A,P);for(let Oe=0;Oe<P*A;ue+=se,he+=se,ge+=se,ke+=se,Oe++)T.data[ue]=(a.data[xe++]-Z[0])*G[0],T.data[he]=(a.data[me++]-Z[1])*G[1],T.data[ge]=(a.data[Ee++]-Z[2])*G[2],T.data[ke]=je===-1?255:(a.data[je++]-Z[3])*G[3]}else throw new Error("Can not access image data");return T}}),V,H,te,ae,oe,ie,X=h(()=>{we(),V=(a,f)=>{if(a===void 0)throw new Error("Image buffer must be defined");if(f.height===void 0||f.width===void 0)throw new Error("Image height and width must be defined");if(f.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:w,width:T}=f,A=f.norm??{mean:255,bias:0},P,D;typeof A.mean=="number"?P=[A.mean,A.mean,A.mean,A.mean]:P=[A.mean[0],A.mean[1],A.mean[2],A.mean[3]??255],typeof A.bias=="number"?D=[A.bias,A.bias,A.bias,A.bias]:D=[A.bias[0],A.bias[1],A.bias[2],A.bias[3]??0];let B=f.format!==void 0?f.format:"RGBA",q=f.tensorFormat!==void 0&&f.tensorFormat!==void 0?f.tensorFormat:"RGB",G=w*T,Z=q==="RGBA"?new Float32Array(G*4):new Float32Array(G*3),ee=4,se=0,ue=1,he=2,ge=3,ke=0,xe=G,me=G*2,Ee=-1;B==="RGB"&&(ee=3,se=0,ue=1,he=2,ge=-1),q==="RGBA"?Ee=G*3:q==="RBG"?(ke=0,me=G,xe=G*2):q==="BGR"&&(me=0,xe=G,ke=G*2);for(let je=0;je<G;je++,se+=ee,he+=ee,ue+=ee,ge+=ee)Z[ke++]=(a[se]+D[0])/P[0],Z[xe++]=(a[ue]+D[1])/P[1],Z[me++]=(a[he]+D[2])/P[2],Ee!==-1&&ge!==-1&&(Z[Ee++]=(a[ge]+D[3])/P[3]);return q==="RGBA"?new ne("float32",Z,[1,4,w,T]):new ne("float32",Z,[1,3,w,T])},H=async(a,f)=>{let w=typeof HTMLImageElement<"u"&&a instanceof HTMLImageElement,T=typeof ImageData<"u"&&a instanceof ImageData,A=typeof ImageBitmap<"u"&&a instanceof ImageBitmap,P=typeof a=="string",D,B=f??{},q=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},G=Z=>typeof HTMLCanvasElement<"u"&&Z instanceof HTMLCanvasElement||Z instanceof OffscreenCanvas?Z.getContext("2d"):null;if(w){let Z=q();Z.width=a.width,Z.height=a.height;let ee=G(Z);if(ee!=null){let se=a.height,ue=a.width;if(f!==void 0&&f.resizedHeight!==void 0&&f.resizedWidth!==void 0&&(se=f.resizedHeight,ue=f.resizedWidth),f!==void 0){if(B=f,f.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");B.tensorFormat="RGBA",B.height=se,B.width=ue}else B.tensorFormat="RGBA",B.height=se,B.width=ue;ee.drawImage(a,0,0),D=ee.getImageData(0,0,ue,se).data}else throw new Error("Can not access image data")}else if(T){let Z,ee;if(f!==void 0&&f.resizedWidth!==void 0&&f.resizedHeight!==void 0?(Z=f.resizedHeight,ee=f.resizedWidth):(Z=a.height,ee=a.width),f!==void 0&&(B=f),B.format="RGBA",B.height=Z,B.width=ee,f!==void 0){let se=q();se.width=ee,se.height=Z;let ue=G(se);if(ue!=null)ue.putImageData(a,0,0),D=ue.getImageData(0,0,ee,Z).data;else throw new Error("Can not access image data")}else D=a.data}else if(A){if(f===void 0)throw new Error("Please provide image config with format for Imagebitmap");let Z=q();Z.width=a.width,Z.height=a.height;let ee=G(Z);if(ee!=null){let se=a.height,ue=a.width;return ee.drawImage(a,0,0,ue,se),D=ee.getImageData(0,0,ue,se).data,B.height=se,B.width=ue,V(D,B)}else throw new Error("Can not access image data")}else{if(P)return new Promise((Z,ee)=>{let se=q(),ue=G(se);if(!a||!ue)return ee();let he=new Image;he.crossOrigin="Anonymous",he.src=a,he.onload=()=>{se.width=he.width,se.height=he.height,ue.drawImage(he,0,0,se.width,se.height);let ge=ue.getImageData(0,0,se.width,se.height);B.height=se.height,B.width=se.width,Z(V(ge.data,B))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(D!==void 0)return V(D,B);throw new Error("Input data provided is not supported - aborted tensor creation")},te=(a,f)=>{let{width:w,height:T,download:A,dispose:P}=f,D=[1,T,w,4];return new ne({location:"texture",type:"float32",texture:a,dims:D,download:A,dispose:P})},ae=(a,f)=>{let{dataType:w,dims:T,download:A,dispose:P}=f;return new ne({location:"gpu-buffer",type:w??"float32",gpuBuffer:a,dims:T,download:A,dispose:P})},oe=(a,f)=>{let{dataType:w,dims:T,download:A,dispose:P}=f;return new ne({location:"ml-tensor",type:w??"float32",mlTensor:a,dims:T,download:A,dispose:P})},ie=(a,f,w)=>new ne({location:"cpu-pinned",type:a,data:f,dims:w??[f.length]})}),Q,J,le,ce,pe=h(()=>{Q=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),J=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),le=!1,ce=()=>{if(!le){le=!0;let a=typeof BigInt64Array<"u"&&BigInt64Array.from,f=typeof BigUint64Array<"u"&&BigUint64Array.from,w=globalThis.Float16Array,T=typeof w<"u"&&w.from;a&&(Q.set("int64",BigInt64Array),J.set(BigInt64Array,"int64")),f&&(Q.set("uint64",BigUint64Array),J.set(BigUint64Array,"uint64")),T?(Q.set("float16",w),J.set(w,"float16")):Q.set("float16",Uint16Array)}}}),Ae,Se,ye=h(()=>{we(),Ae=a=>{let f=1;for(let w=0;w<a.length;w++){let T=a[w];if(typeof T!="number"||!Number.isSafeInteger(T))throw new TypeError(`dims[${w}] must be an integer, got: ${T}`);if(T<0)throw new RangeError(`dims[${w}] must be a non-negative integer, got: ${T}`);f*=T}return f},Se=(a,f)=>{switch(a.location){case"cpu":return new ne(a.type,a.data,f);case"cpu-pinned":return new ne({location:"cpu-pinned",data:a.data,type:a.type,dims:f});case"texture":return new ne({location:"texture",texture:a.texture,type:a.type,dims:f});case"gpu-buffer":return new ne({location:"gpu-buffer",gpuBuffer:a.gpuBuffer,type:a.type,dims:f});case"ml-tensor":return new ne({location:"ml-tensor",mlTensor:a.mlTensor,type:a.type,dims:f});default:throw new Error(`tensorReshape: tensor location ${a.location} is not supported`)}}}),ne,we=h(()=>{Y(),X(),pe(),ye(),ne=class{constructor(a,f,w){ce();let T,A;if(typeof a=="object"&&"location"in a)switch(this.dataLocation=a.location,T=a.type,A=a.dims,a.location){case"cpu-pinned":{let D=Q.get(T);if(!D)throw new TypeError(`unsupported type "${T}" to create tensor from pinned buffer`);if(!(a.data instanceof D))throw new TypeError(`buffer should be of type ${D.name}`);this.cpuData=a.data;break}case"texture":{if(T!=="float32")throw new TypeError(`unsupported type "${T}" to create tensor from texture`);this.gpuTextureData=a.texture,this.downloader=a.download,this.disposer=a.dispose;break}case"gpu-buffer":{if(T!=="float32"&&T!=="float16"&&T!=="int32"&&T!=="int64"&&T!=="uint32"&&T!=="uint8"&&T!=="bool"&&T!=="uint4"&&T!=="int4")throw new TypeError(`unsupported type "${T}" to create tensor from gpu buffer`);this.gpuBufferData=a.gpuBuffer,this.downloader=a.download,this.disposer=a.dispose;break}case"ml-tensor":{if(T!=="float32"&&T!=="float16"&&T!=="int32"&&T!=="int64"&&T!=="uint32"&&T!=="uint64"&&T!=="int8"&&T!=="uint8"&&T!=="bool"&&T!=="uint4"&&T!=="int4")throw new TypeError(`unsupported type "${T}" to create tensor from MLTensor`);this.mlTensorData=a.mlTensor,this.downloader=a.download,this.disposer=a.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let D,B;if(typeof a=="string")if(T=a,B=w,a==="string"){if(!Array.isArray(f))throw new TypeError("A string tensor's data must be a string array.");D=f}else{let q=Q.get(a);if(q===void 0)throw new TypeError(`Unsupported tensor type: ${a}.`);if(Array.isArray(f)){if(a==="float16"&&q===Uint16Array||a==="uint4"||a==="int4")throw new TypeError(`Creating a ${a} tensor from number array is not supported. Please use ${q.name} as data.`);a==="uint64"||a==="int64"?D=q.from(f,BigInt):D=q.from(f)}else if(f instanceof q)D=f;else if(f instanceof Uint8ClampedArray)if(a==="uint8")D=Uint8Array.from(f);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(a==="float16"&&f instanceof Uint16Array&&q!==Uint16Array)D=new globalThis.Float16Array(f.buffer,f.byteOffset,f.length);else throw new TypeError(`A ${T} tensor's data must be type of ${q}`)}else if(B=f,Array.isArray(a)){if(a.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let q=typeof a[0];if(q==="string")T="string",D=a;else if(q==="boolean")T="bool",D=Uint8Array.from(a);else throw new TypeError(`Invalid element type of data array: ${q}.`)}else if(a instanceof Uint8ClampedArray)T="uint8",D=Uint8Array.from(a);else{let q=J.get(a.constructor);if(q===void 0)throw new TypeError(`Unsupported type for tensor data: ${a.constructor}.`);T=q,D=a}if(B===void 0)B=[D.length];else if(!Array.isArray(B))throw new TypeError("A tensor's dims must be a number array");A=B,this.cpuData=D,this.dataLocation="cpu"}let P=Ae(A);if(this.cpuData&&P!==this.cpuData.length&&!((T==="uint4"||T==="int4")&&Math.ceil(P/2)===this.cpuData.length))throw new Error(`Tensor's size(${P}) does not match data length(${this.cpuData.length}).`);this.type=T,this.dims=A,this.size=P}static async fromImage(a,f){return H(a,f)}static fromTexture(a,f){return te(a,f)}static fromGpuBuffer(a,f){return ae(a,f)}static fromMLTensor(a,f){return oe(a,f)}static fromPinnedBuffer(a,f,w){return ie(a,f,w)}toDataURL(a){return U(this,a)}toImageData(a){return W(this,a)}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(a){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 f=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=f,a&&this.disposer&&(this.disposer(),this.disposer=void 0),f}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(a){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Se(this,a)}}}),Ne,Je=h(()=>{we(),Ne=ne}),lt,xt,Rt,He,vt,st,an=h(()=>{O(),lt=(a,f)=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeStamp(`${a}::ORT::${f}`)},xt=(a,f)=>{var A;let w=((A=new Error().stack)==null?void 0:A.split(/\r\n|\r|\n/g))||[],T=!1;for(let P=0;P<w.length;P++){if(T&&!w[P].includes("TRACE_FUNC")){let D=`FUNC_${a}::${w[P].trim().split(" ")[1]}`;f&&(D+=`::${f}`),lt("CPU",D);return}w[P].includes("TRACE_FUNC")&&(T=!0)}},Rt=a=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("BEGIN",a)},He=a=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("END",a)},vt=a=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.time(`ORT::${a}`)},st=a=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeEnd(`ORT::${a}`)}}),sn,Ye=h(()=>{b(),Je(),an(),sn=class D2{constructor(f){this.handler=f}async run(f,w,T){Rt(),vt("InferenceSession.run");let A={},P={};if(typeof f!="object"||f===null||f instanceof Ne||Array.isArray(f))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let D=!0;if(typeof w=="object"){if(w===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(w instanceof Ne)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(w)){if(w.length===0)throw new TypeError("'fetches' cannot be an empty array.");D=!1;for(let G of w){if(typeof G!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(G)===-1)throw new RangeError(`'fetches' contains invalid output name: ${G}.`);A[G]=null}if(typeof T=="object"&&T!==null)P=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else{let G=!1,Z=Object.getOwnPropertyNames(w);for(let ee of this.outputNames)if(Z.indexOf(ee)!==-1){let se=w[ee];(se===null||se instanceof Ne)&&(G=!0,D=!1,A[ee]=se)}if(G){if(typeof T=="object"&&T!==null)P=T;else if(typeof T<"u")throw new TypeError("'options' must be an object.")}else P=w}}else if(typeof w<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let G of this.inputNames)if(typeof f[G]>"u")throw new Error(`input '${G}' is missing in 'feeds'.`);if(D)for(let G of this.outputNames)A[G]=null;let B=await this.handler.run(f,A,P),q={};for(let G in B)if(Object.hasOwnProperty.call(B,G)){let Z=B[G];Z instanceof Ne?q[G]=Z:q[G]=new Ne(Z.type,Z.data,Z.dims)}return st("InferenceSession.run"),He(),q}async release(){return this.handler.dispose()}static async create(f,w,T,A){Rt(),vt("InferenceSession.create");let P,D={};if(typeof f=="string"){if(P=f,typeof w=="object"&&w!==null)D=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else if(f instanceof Uint8Array){if(P=f,typeof w=="object"&&w!==null)D=w;else if(typeof w<"u")throw new TypeError("'options' must be an object.")}else if(f instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&f instanceof SharedArrayBuffer){let Z=f,ee=0,se=f.byteLength;if(typeof w=="object"&&w!==null)D=w;else if(typeof w=="number"){if(ee=w,!Number.isSafeInteger(ee))throw new RangeError("'byteOffset' must be an integer.");if(ee<0||ee>=Z.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${Z.byteLength}).`);if(se=f.byteLength-ee,typeof T=="number"){if(se=T,!Number.isSafeInteger(se))throw new RangeError("'byteLength' must be an integer.");if(se<=0||ee+se>Z.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${Z.byteLength-ee}].`);if(typeof A=="object"&&A!==null)D=A;else if(typeof A<"u")throw new TypeError("'options' must be an object.")}else if(typeof T<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof w<"u")throw new TypeError("'options' must be an object.");P=new Uint8Array(Z,ee,se)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[B,q]=await y(D),G=await B.createInferenceSessionHandler(P,q);return st("InferenceSession.create"),He(),new D2(G)}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}}}),yt,kt=h(()=>{Ye(),yt=sn}),Kt=h(()=>{}),On=h(()=>{}),Rn=h(()=>{}),Br=h(()=>{}),Tr={};m(Tr,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>vt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,env:()=>I,registerBackend:()=>E});var nt=h(()=>{_(),z(),kt(),Je(),Kt(),On(),an(),Rn(),Br()}),St=h(()=>{}),Tt={};m(Tt,{default:()=>$r});var cn,nn,$r,Ta=h(()=>{var a;_e(),Hr(),Ur(),cn="ort-wasm-proxy-worker",nn=((a=globalThis.self)==null?void 0:a.name)===cn,nn&&(self.onmessage=f=>{let{type:w,in:T}=f.data;try{switch(w){case"init-wasm":ti(T.wasm).then(()=>{Xl(T).then(()=>{postMessage({type:w})},A=>{postMessage({type:w,err:A})})},A=>{postMessage({type:w,err:A})});break;case"init-ep":{let{epName:A,env:P}=T;Lp(P,A).then(()=>{postMessage({type:w})},D=>{postMessage({type:w,err:D})});break}case"copy-from":{let{buffer:A}=T,P=c(A);postMessage({type:w,out:P});break}case"create":{let{model:A,options:P}=T;p(A,P).then(D=>{postMessage({type:w,out:D})},D=>{postMessage({type:w,err:D})});break}case"release":k(T),postMessage({type:w});break;case"run":{let{sessionId:A,inputIndices:P,inputs:D,outputIndices:B,options:q}=T;F(A,P,D,B,new Array(B.length).fill(null),q).then(G=>{G.some(Z=>Z[3]!=="cpu")?postMessage({type:w,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:w,out:G},de([...D,...G]))},G=>{postMessage({type:w,err:G})});break}case"end-profiling":K(T),postMessage({type:w});break;default:}}catch(A){postMessage({type:w,err:A})}}),$r=nn?null:f=>new Worker(f??yn,{type:"classic",name:cn})}),Vo,vi,yn,Fr,Zn,bi,Ms,as,Fi,wi,_i,Is,Ar,Ur=h(()=>{St(),Vo=typeof location>"u"?void 0:location.origin,vi=()=>{var a,f;return typeof document<"u"?(a=document.currentScript)==null?void 0:a.src:typeof self<"u"?(f=self.location)==null?void 0:f.href:void 0},yn=vi(),Fr=()=>{if(yn&&!yn.startsWith("blob:"))return yn.substring(0,yn.lastIndexOf("/")+1)},Zn=(a,f)=>{try{let w=f??yn;return(w?new URL(a,w):new URL(a)).origin===Vo}catch{return!1}},bi=(a,f)=>{let w=f??yn;try{return(w?new URL(a,w):new URL(a)).href}catch{return}},Ms=(a,f)=>`${f??"./"}${a}`,as=async a=>{let f=await(await fetch(a,{credentials:"same-origin"})).blob();return URL.createObjectURL(f)},Fi=async a=>(await import(a)).default,wi=(Ta(),g(Tt)).default,_i=async()=>{if(!yn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Zn(yn))return[void 0,wi()];let a=await as(yn);return[a,wi(a)]},Is=void 0,Ar=async(a,f,w,T)=>{let A=Is&&!(a||f);if(A)if(yn)A=Zn(yn)||T&&!w;else if(T&&!w)A=!0;else throw new Error("cannot determine the script source URL.");if(A)return[void 0,Is];{let P="ort-wasm-simd-threaded.jsep.mjs",D=a??bi(P,f),B=w&&D&&!Zn(D,f),q=B?await as(D):D??Ms(P,f);return[B?q:void 0,await Fi(q)]}}}),Qs,Rr,ls,js,ho,Zs,ei,ti,zt,Hr=h(()=>{Ur(),Rr=!1,ls=!1,js=!1,ho=()=>{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}},Zs=()=>{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}},ei=()=>{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}},ti=async a=>{if(Rr)return Promise.resolve();if(ls)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(js)throw new Error("previous call to 'initializeWebAssembly()' failed.");ls=!0;let f=a.initTimeout,w=a.numThreads;if(a.simd!==!1){if(a.simd==="relaxed"){if(!ei())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Zs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let T=ho();w>1&&!T&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+w+", 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."),a.numThreads=w=1);let A=a.wasmPaths,P=typeof A=="string"?A:void 0,D=A==null?void 0:A.mjs,B=(D==null?void 0:D.href)??D,q=A==null?void 0:A.wasm,G=(q==null?void 0:q.href)??q,Z=a.wasmBinary,[ee,se]=await Ar(B,P,w>1,!!Z||!!G),ue=!1,he=[];if(f>0&&he.push(new Promise(ge=>{setTimeout(()=>{ue=!0,ge()},f)})),he.push(new Promise((ge,ke)=>{let xe={numThreads:w};if(Z)xe.wasmBinary=Z,xe.locateFile=me=>me;else if(G||P)xe.locateFile=me=>G??P+me;else if(B&&B.indexOf("blob:")!==0)xe.locateFile=me=>new URL(me,B).href;else if(ee){let me=Fr();me&&(xe.locateFile=Ee=>me+Ee)}se(xe).then(me=>{ls=!1,Rr=!0,Qs=me,ge(),ee&&URL.revokeObjectURL(ee)},me=>{ls=!1,js=!0,ke(me)})})),await Promise.race(he),ue)throw new Error(`WebAssembly backend initializing failed due to timeout: ${f}ms`)},zt=()=>{if(Rr&&Qs)return Qs;throw new Error("WebAssembly is not initialized yet.")}}),Hn,_n,Ct,Ui=h(()=>{Hr(),Hn=(a,f)=>{let w=zt(),T=w.lengthBytesUTF8(a)+1,A=w._malloc(T);return w.stringToUTF8(a,A,T),f.push(A),A},_n=(a,f,w,T)=>{if(typeof a=="object"&&a!==null){if(w.has(a))throw new Error("Circular reference in options");w.add(a)}Object.entries(a).forEach(([A,P])=>{let D=f?f+A:A;if(typeof P=="object")_n(P,D+".",w,T);else if(typeof P=="string"||typeof P=="number")T(D,P.toString());else if(typeof P=="boolean")T(D,P?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof P}`)})},Ct=a=>{let f=zt(),w=f.stackSave();try{let T=f.PTR_SIZE,A=f.stackAlloc(2*T);f._OrtGetLastError(A,A+T);let P=Number(f.getValue(A,T===4?"i32":"i64")),D=f.getValue(A+T,"*"),B=D?f.UTF8ToString(D):"";throw new Error(`${a} ERROR_CODE: ${P}, ERROR_MESSAGE: ${B}`)}finally{f.stackRestore(w)}}}),fo,$a=h(()=>{Hr(),Ui(),fo=a=>{let f=zt(),w=0,T=[],A=a||{};try{if((a==null?void 0:a.logSeverityLevel)===void 0)A.logSeverityLevel=2;else if(typeof a.logSeverityLevel!="number"||!Number.isInteger(a.logSeverityLevel)||a.logSeverityLevel<0||a.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${a.logSeverityLevel}`);if((a==null?void 0:a.logVerbosityLevel)===void 0)A.logVerbosityLevel=0;else if(typeof a.logVerbosityLevel!="number"||!Number.isInteger(a.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${a.logVerbosityLevel}`);(a==null?void 0:a.terminate)===void 0&&(A.terminate=!1);let P=0;return(a==null?void 0:a.tag)!==void 0&&(P=Hn(a.tag,T)),w=f._OrtCreateRunOptions(A.logSeverityLevel,A.logVerbosityLevel,!!A.terminate,P),w===0&&Ct("Can't create run options."),(a==null?void 0:a.extra)!==void 0&&_n(a.extra,"",new WeakSet,(D,B)=>{let q=Hn(D,T),G=Hn(B,T);f._OrtAddRunConfigEntry(w,q,G)!==0&&Ct(`Can't set a run config entry: ${D} - ${B}.`)}),[w,T]}catch(P){throw w!==0&&f._OrtReleaseRunOptions(w),T.forEach(D=>f._free(D)),P}}}),po,mo,Go,Sr,Aa,Ra,kn=h(()=>{Hr(),Ui(),po=a=>{switch(a){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: ${a}`)}},mo=a=>{switch(a){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${a}`)}},Go=a=>{a.extra||(a.extra={}),a.extra.session||(a.extra.session={});let f=a.extra.session;f.use_ort_model_bytes_directly||(f.use_ort_model_bytes_directly="1"),a.executionProviders&&a.executionProviders.some(w=>(typeof w=="string"?w:w.name)==="webgpu")&&(a.enableMemPattern=!1)},Sr=(a,f,w,T)=>{let A=Hn(f,T),P=Hn(w,T);zt()._OrtAddSessionConfigEntry(a,A,P)!==0&&Ct(`Can't set a session config entry: ${f} - ${w}.`)},Aa=async(a,f,w)=>{let T=f.executionProviders;for(let A of T){let P=typeof A=="string"?A:A.name,D=[];switch(P){case"webnn":if(P="WEBNN",Sr(a,"session.disable_quant_qdq","1",w),Sr(a,"session.disable_qdq_constant_folding","1",w),typeof A!="string"){let ee=A==null?void 0:A.deviceType;ee&&Sr(a,"deviceType",ee,w)}break;case"webgpu":if(P="JS",typeof A!="string"){let ee=A;if(ee!=null&&ee.preferredLayout){if(ee.preferredLayout!=="NCHW"&&ee.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${ee.preferredLayout}`);Sr(a,"preferredLayout",ee.preferredLayout,w)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${P}`)}let B=Hn(P,w),q=D.length,G=0,Z=0;if(q>0){G=zt()._malloc(q*zt().PTR_SIZE),w.push(G),Z=zt()._malloc(q*zt().PTR_SIZE),w.push(Z);for(let ee=0;ee<q;ee++)zt().setValue(G+ee*zt().PTR_SIZE,D[ee][0],"*"),zt().setValue(Z+ee*zt().PTR_SIZE,D[ee][1],"*")}await zt()._OrtAppendExecutionProvider(a,B,G,Z,q)!==0&&Ct(`Can't append execution provider: ${P}.`)}},Ra=async a=>{let f=zt(),w=0,T=[],A=a||{};Go(A);try{let P=po(A.graphOptimizationLevel??"all"),D=mo(A.executionMode??"sequential"),B=typeof A.logId=="string"?Hn(A.logId,T):0,q=A.logSeverityLevel??2;if(!Number.isInteger(q)||q<0||q>4)throw new Error(`log severity level is not valid: ${q}`);let G=A.logVerbosityLevel??0;if(!Number.isInteger(G)||G<0||G>4)throw new Error(`log verbosity level is not valid: ${G}`);let Z=typeof A.optimizedModelFilePath=="string"?Hn(A.optimizedModelFilePath,T):0;if(w=f._OrtCreateSessionOptions(P,!!A.enableCpuMemArena,!!A.enableMemPattern,D,!!A.enableProfiling,0,B,q,G,Z),w===0&&Ct("Can't create session options."),A.executionProviders&&await Aa(w,A,T),A.enableGraphCapture!==void 0){if(typeof A.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${A.enableGraphCapture}`);Sr(w,"enableGraphCapture",A.enableGraphCapture.toString(),T)}if(A.freeDimensionOverrides)for(let[ee,se]of Object.entries(A.freeDimensionOverrides)){if(typeof ee!="string")throw new Error(`free dimension override name must be a string: ${ee}`);if(typeof se!="number"||!Number.isInteger(se)||se<0)throw new Error(`free dimension override value must be a non-negative integer: ${se}`);let ue=Hn(ee,T);f._OrtAddFreeDimensionOverride(w,ue,se)!==0&&Ct(`Can't set a free dimension override: ${ee} - ${se}.`)}return A.extra!==void 0&&_n(A.extra,"",new WeakSet,(ee,se)=>{Sr(w,ee,se,T)}),[w,T]}catch(P){throw w!==0&&f._OrtReleaseSessionOptions(w)!==0&&Ct("Can't release session options."),T.forEach(D=>f._free(D)),P}}}),Mr,Vn,Ir,ni,Hi,ki,cs,gr,Bt=h(()=>{Mr=a=>{switch(a){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: ${a}`)}},Vn=a=>{switch(a){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: ${a}`)}},Ir=(a,f)=>{let w=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][a],T=typeof f=="number"?f:f.reduce((A,P)=>A*P,1);return w>0?Math.ceil(T*w):void 0},ni=a=>{switch(a){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: ${a}`)}},Hi=a=>{switch(a){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: ${a}`)}},ki=a=>a==="float32"||a==="float16"||a==="int32"||a==="int64"||a==="uint32"||a==="uint8"||a==="bool"||a==="uint4"||a==="int4",cs=a=>a==="float32"||a==="float16"||a==="int32"||a==="int64"||a==="uint32"||a==="uint64"||a==="int8"||a==="uint8"||a==="bool"||a==="uint4"||a==="int4",gr=a=>{switch(a){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: ${a}`)}}}),Gn,Si=h(()=>{St(),Gn=async a=>{if(typeof a=="string"){let f=await fetch(a);if(!f.ok)throw new Error(`failed to load external data file: ${a}`);let w=f.headers.get("Content-Length"),T=w?parseInt(w,10):0;if(T<1073741824)return new Uint8Array(await f.arrayBuffer());{if(!f.body)throw new Error(`failed to load external data file: ${a}, no response body.`);let A=f.body.getReader(),P;try{P=new ArrayBuffer(T)}catch(B){if(B instanceof RangeError){let q=Math.ceil(T/65536);P=new WebAssembly.Memory({initial:q,maximum:q}).buffer}else throw B}let D=0;for(;;){let{done:B,value:q}=await A.read();if(B)break;let G=q.byteLength;new Uint8Array(P,D,G).set(q),D+=G}return new Uint8Array(P,0,T)}}else return a instanceof Blob?new Uint8Array(await a.arrayBuffer()):a instanceof Uint8Array?a:new Uint8Array(a)}}),us,Ko,Ci,Wr,Ps,ji,on,ds=h(()=>{Bt(),us=["V","I","W","E","F"],Ko=(a,f)=>{console.log(`[${us[a]},${new Date().toISOString()}]${f}`)},Ps=(a,f)=>{Ci=a,Wr=f},ji=(a,f)=>{let w=Hi(a),T=Hi(Ci);w>=T&&Ko(w,typeof f=="function"?f():f)},on=(...a)=>{Wr&&ji(...a)}}),Wi,Es,Ke,qr,ft,be,Pe,Qe=h(()=>{Wi=class{static calcMatMulShape(a,f){return a[1]!==f[0]?void 0:[a[0],f[1]]}},Es=class{static calcShape(a,f,w=!1){let T=a.length,A=f.length;if(T===0)return f;if(A===0)return a;let P=Math.max(a.length,f.length),D=new Array(P);if(w){if(T<2||A<2)return;let B=Wi.calcMatMulShape([a[T-2],a[T-1]],[f[A-2],f[A-1]]);if(B===void 0)return;[D[P-2],D[P-1]]=B}for(let B=w?3:1;B<=P;B++){let q=T-B<0?1:a[T-B],G=A-B<0?1:f[A-B];if(q!==G&&q>1&&G>1)return;let Z=Math.max(q,G);if(q&&G)D[P-B]=Math.max(q,G);else{if(Z>1)return;D[P-B]=0}}return D}static isValidBroadcast(a,f){let w=a.length,T=f.length;if(w>T)return!1;for(let A=1;A<=w;A++)if(a[w-A]!==1&&a[w-A]!==f[T-A])return!1;return!0}},Ke=class Xx{static size(f){return Xx.getSizeFromDimensionRange(f,0,f.length)}static convertShape(f,w=4){let T=f.length;if(T===0)return[];let A=new Array(T),P=T-1;for(;P>=0;){if(f[P]%w===0){A[P]=f[P]/w;break}if(w%f[P]!==0)throw new Error("cannot convert shape");A[P]=1,w/=f[P],P--}for(P--;P>=0;P--)A[P]=f[P];return A}static sizeFromDimension(f,w){if(w<0||w>f.length)throw new Error(`invalid dimension of ${w} for sizeFromDimension as Tensor has ${f.length} dimensions.`);return Xx.getSizeFromDimensionRange(f,w,f.length)}static sizeToDimension(f,w){if(w<0||w>f.length)throw new Error(`invalid dimension of ${w} for sizeToDimension as Tensor has ${f.length} dimensions.`);return Xx.getSizeFromDimensionRange(f,0,w)}static getSizeFromDimensionRange(f,w,T){let A=1;for(let P=w;P<T;P++){if(f[P]<0)throw new Error("cannot get valid size from specified dimension range. Most likely the range contains negative values in them.");A*=Number(f[P])}return A}static computeStrides(f){let w=f.length;if(w===0)return[];if(w===1)return[1];let T=new Array(w);T[w-1]=1,T[w-2]=f[w-1];for(let A=w-3;A>=0;--A)T[A]=T[A+1]*f[A+1];return T}static normalizeAxis(f,w){if(f<-w&&f>=w)throw new Error("unsupported axis for this operation.");return f<0?f+w:f}static normalizeAxes(f,w){return f.map(T=>this.normalizeAxis(T,w??f.length))}static sortBasedOnPerm(f,w){return w?w.map(T=>f[T]):f.slice().reverse()}static padShape(f,w){let T=f.length;return f.map((A,P)=>A+w[P]+w[P+T])}static areEqual(f,w){return f.length!==w.length?!1:f.every((T,A)=>T===w[A])}},qr=class vm{static adjustPoolAttributes(f,w,T,A,P,D){if(!f&&T.length!==w.length-2)throw new Error("length of specified kernel shapes should be 2 less than length of input dimensions");if(f)for(let B=0;B<w.length-2;B++)B>=T.length?T.push(w[B+2]):T[B]=w[B+2];for(let B=0;B<T.length;B++)if(B<A.length){if(A[B]<0)throw new Error("strides should be greater than or equal to 1")}else A.push(1);for(let B=0;B<T.length;B++)if(B<P.length){if(P[B]<0)throw new Error("dilations should be greater than or equal to 1")}else P.push(1);for(let B=0;B<T.length*2;B++)if(B<D.length){if(D[B]<0)throw new Error("pad should be greater than or equal to 1")}else D.push(0);for(let B=0;B<T.length;B++){if(T[B]<=0)throw new Error("kernel shapes need to be greater than 0");if(D[B]>=T[B]||D[B+T.length]>=T[B])throw new Error("pads should be smaller than kernel")}}static adjustPadsBasedOnAutoPad(f,w,T,A,P,D,B){if(B){if(P.length!==2*(f.length-2))throw new Error("length of pads should be twice the length of data dimensions");if(w.length!==f.length-2)throw new Error("length of strides should be the length of data dimensions");if(A.length!==f.length-2)throw new Error("length of kernel shapes should be the length of data dimensions");for(let q=0;q<f.length-2;q++)vm.adjustPadAndReturnShape(f[q+(D?1:2)],w[q],T[q],A[q],P,q,q+f.length-2,B)}}static computePoolOutputShape(f,w,T,A,P,D,B){if(w.length<=0)throw new Error("input shape must be of size greater than 0");let q=[w[0],w[1]];return vm.computeShapeHelper(f,w,q,T,A,P,D,B),q}static computeConvOutputShape(f,w,T,A,P,D,B){if(f.length<=0||w.length<=0)throw new Error("invalid input tensor dims or invalid filter tensor dims");let q=[f[0],w[0]];return vm.computeShapeHelper(!1,f,q,T,A,P,D,B),q}static computeShapeHelper(f,w,T,A,P,D,B,q){if(f)for(let G=0;G<w.length-2;G++)T.push(1);else for(let G=0;G<w.length-2;G++)T.push(vm.adjustPadAndReturnShape(w[G+2],A[G],P[G],D[G],B,G,G+w.length-2,q))}static adjustPadAndReturnShape(f,w,T,A,P,D,B,q){let G=T*(A-1)+1;if(q&&q!=="NOTSET")switch(q){case"VALID":return P[D]=0,P[B]=0,Math.floor((f-G)/w+1);case"SAME_LOWER":case"SAME_UPPER":if(T!==1)throw new Error("Dilation not supported for SAME_UPPER or SAME_LOWER");{let Z=((f+w-1)/w-1)*w+A-f;return P[D]=Math.floor(q==="SAME_LOWER"?(Z+1)/2:Z/2),P[B]=Z-P[D],Math.floor((f+Z-A)/w+1)}default:throw new Error("Unsupported AutoPad type")}else return Math.floor((f+P[D]+P[B]-G)/w+1)}},ft=class{static getShapeOfGemmResult(a,f,w,T,A){if(a.length!==2||w.length!==2)throw new Error("shape need to be of size 2");let P,D,B;f?(P=a[1],D=a[0]):(P=a[0],D=a[1]);let q=-1;if(T?(B=w[0],q=1):(B=w[1],q=0),w[q]!==D)throw new Error("dimension mismatch");if(P<=0||B<=0||D<=0)throw new Error("invalid shape specified");if(A&&!Es.isValidBroadcast(A,[P,B]))throw new Error("gemm: invalid bias shape for broadcast");return[P,B,D]}},be=-34028234663852886e22,Pe=34028234663852886e22}),Et,en=h(()=>{Bt(),Et=(a,f)=>new(ni(f))(a)}),ln,$n,En,er,Ln,sr,Nn,Ds,qi,go,ri,Vu=h(()=>{Bt(),ds(),ln=new Map([["float32",32],["float16",16],["int32",32],["uint32",32],["int64",64],["uint64",64],["int8",8],["uint8",8],["int4",4],["uint4",4]]),$n=(a,f)=>{if(f==="int32")return a;let w=ln.get(f);if(!w)throw new Error(`WebNN backend does not support data type: ${f}`);let T=w/8;if(a.byteLength%T!==0)throw new Error(`Invalid Uint8Array length - must be a multiple of ${T}.`);let A=a.byteLength/T,P=new(ni(f))(a.buffer,a.byteOffset,A);switch(f){case"int64":case"uint64":{let D=new Int32Array(A);for(let B=0;B<A;B++){let q=P[B];if(q>2147483647n||q<-2147483648n)throw new Error("Can not convert int64 data to int32 - value out of range.");D[B]=Number(q)}return new Uint8Array(D.buffer)}case"int8":case"uint8":case"uint32":{if(f==="uint32"&&P.some(B=>B>2147483647))throw new Error("Can not convert uint32 data to int32 - value out of range.");let D=Int32Array.from(P,Number);return new Uint8Array(D.buffer)}default:throw new Error(`Unsupported data conversion from ${f} to 'int32'`)}},En=(a,f)=>{if(f==="int32")return a;if(a.byteLength%4!==0)throw new Error("Invalid Uint8Array length - must be a multiple of 4 (int32).");let w=a.byteLength/4,T=new Int32Array(a.buffer,a.byteOffset,w);switch(f){case"int64":{let A=BigInt64Array.from(T,BigInt);return new Uint8Array(A.buffer)}case"uint64":{if(T.some(P=>P<0))throw new Error("Can not convert int32 data to uin64 - negative value found.");let A=BigUint64Array.from(T,BigInt);return new Uint8Array(A.buffer)}case"int8":{if(T.some(P=>P<-128||P>127))throw new Error("Can not convert int32 data to int8 - value out of range.");let A=Int8Array.from(T,Number);return new Uint8Array(A.buffer)}case"uint8":{if(T.some(A=>A<0||A>255))throw new Error("Can not convert int32 data to uint8 - value out of range.");return Uint8Array.from(T,Number)}case"uint32":{if(T.some(P=>P<0))throw new Error("Can not convert int32 data to uint32 - negative value found.");let A=Uint32Array.from(T,Number);return new Uint8Array(A.buffer)}default:throw new Error(`Unsupported data conversion from 'int32' to ${f}`)}},er=1,Ln=()=>er++,sr=new Map([["int8","int32"],["uint8","int32"],["uint32","int32"],["int64","int32"]]),Nn=(a,f)=>{let w=ln.get(a);if(!w)throw new Error(`WebNN backend does not support data type: ${a}`);return f.length>0?Math.ceil(f.reduce((T,A)=>T*A)*w/8):0},Ds=class{constructor(a){this.isDataConverted=!1;let{sessionId:f,context:w,tensor:T,dataType:A,shape:P,fallbackDataType:D}=a;this.sessionId=f,this.mlContext=w,this.mlTensor=T,this.dataType=A,this.tensorShape=P,this.fallbackDataType=D}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return Nn(this.dataType,this.tensorShape)}destroy(){on("verbose",()=>"[WebNN] TensorWrapper.destroy"),this.mlTensor.destroy()}write(a){this.mlContext.writeTensor(this.mlTensor,a)}async read(a){if(this.fallbackDataType){let f=await this.mlContext.readTensor(this.mlTensor),w=En(new Uint8Array(f),this.dataType);if(a){(a instanceof ArrayBuffer?new Uint8Array(a):new Uint8Array(a.buffer,a.byteOffset,a.byteLength)).set(w);return}else return w.buffer}else return a?this.mlContext.readTensor(this.mlTensor,a):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(a,f,w){return this.mlContext===a&&this.dataType===f&&this.tensorShape.length===w.length&&this.tensorShape.every((T,A)=>T===w[A])}setIsDataConverted(a){this.isDataConverted=a}},qi=class{constructor(a,f){this.tensorManager=a,this.wrapper=f}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(a,f,w,T){let A=this.tensorManager.getMLContext(a),P=this.tensorManager.getMLOpSupportLimits(a),D;if(!(P!=null&&P.input.dataTypes.includes(f))){if(D=sr.get(f),!D||(P==null?void 0:P.input.dataTypes.includes(D)))throw new Error(`WebNN backend does not support data type: ${f}`);on("verbose",()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${f} to ${D}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(A,f,w))return this.wrapper.tensor;if(T){if(this.wrapper.byteLength!==Nn(f,w))throw new Error("Unable to copy data to tensor with different size.");this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let B=typeof MLTensorUsage>"u"?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(a,f,w,B,!0,!0,D),T&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(a){let f=a;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType==="int32")f=$n(a,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw new Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(a.byteLength===this.wrapper.byteLength){this.wrapper.write(f);return}else on("verbose",()=>"Data size does not match tensor size. Releasing tensor."),this.releaseTensor()}this.activeUpload?this.activeUpload.set(f):this.activeUpload=new Uint8Array(f)}async download(a){var f,w;if(this.activeUpload){let T=(f=this.wrapper)!=null&&f.isDataConverted?En(this.activeUpload,(w=this.wrapper)==null?void 0:w.type):this.activeUpload;if(a){a instanceof ArrayBuffer?new Uint8Array(a).set(T):new Uint8Array(a.buffer,a.byteOffset,a.byteLength).set(T);return}else return T.buffer}if(!this.wrapper)throw new Error("Tensor has not been created.");return a?this.wrapper.read(a):this.wrapper.read()}},go=class{constructor(a){this.backend=a,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(a){let f=this.backend.getMLContext(a);if(!f)throw new Error("MLContext not found for session.");return f}getMLOpSupportLimits(a){return this.backend.getMLOpSupportLimits(a)}reserveTensorId(){let a=Ln();return this.tensorTrackersById.set(a,new qi(this)),a}releaseTensorId(a){let f=this.tensorTrackersById.get(a);f&&(this.tensorTrackersById.delete(a),f.tensorWrapper&&this.releaseTensor(f.tensorWrapper))}async ensureTensor(a,f,w,T,A){on("verbose",()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${f}, dataType: ${w}, shape: ${T}, copyOld: ${A}}`);let P=this.tensorTrackersById.get(f);if(!P)throw new Error("Tensor not found.");return P.ensureTensor(a,w,T,A)}upload(a,f){let w=this.tensorTrackersById.get(a);if(!w)throw new Error("Tensor not found.");w.upload(f)}async download(a,f){on("verbose",()=>`[WebNN] TensorManager.download {tensorId: ${a}, dstBuffer: ${f==null?void 0:f.byteLength}}`);let w=this.tensorTrackersById.get(a);if(!w)throw new Error("Tensor not found.");return w.download(f)}releaseTensorsForSession(a){for(let f of this.freeTensors)f.sessionId===a&&f.destroy();this.freeTensors=this.freeTensors.filter(f=>f.sessionId!==a)}registerTensor(a,f,w,T){let A=this.getMLContext(a),P=Ln(),D=new Ds({sessionId:a,context:A,tensor:f,dataType:w,shape:T});return this.tensorTrackersById.set(P,new qi(this,D)),this.externalTensors.add(D),P}async getCachedTensor(a,f,w,T,A,P,D){let B=this.getMLContext(a);for(let[G,Z]of this.freeTensors.entries())if(Z.canReuseTensor(B,f,w)){on("verbose",()=>`[WebNN] Reusing tensor {dataType: ${f}, ${D?`fallbackDataType: ${D},`:""} shape: ${w}`);let ee=this.freeTensors.splice(G,1)[0];return ee.sessionId=a,ee}on("verbose",()=>`[WebNN] MLContext.createTensor {dataType: ${f}, ${D?`fallbackDataType: ${D},`:""} shape: ${w}}`);let q=await B.createTensor({dataType:D??f,shape:w,dimensions:w,usage:T,writable:A,readable:P});return new Ds({sessionId:a,context:B,tensor:q,dataType:f,shape:w,fallbackDataType:D})}releaseTensor(a){this.externalTensors.has(a)&&this.externalTensors.delete(a),this.freeTensors.push(a)}},ri=(...a)=>new go(...a)}),xo,yo,Sc,bl=h(()=>{Bt(),Hr(),en(),Vu(),ds(),xo=new Map([[1,"float32"],[10,"float16"],[6,"int32"],[12,"uint32"],[7,"int64"],[13,"uint64"],[22,"int4"],[21,"uint4"],[3,"int8"],[2,"uint8"],[9,"uint8"]]),yo=(a,f)=>{if(a===f)return!0;if(a===void 0||f===void 0)return!1;let w=Object.keys(a).sort(),T=Object.keys(f).sort();return w.length===T.length&&w.every((A,P)=>A===T[P]&&a[A]===f[A])},Sc=class{constructor(a){this.tensorManager=ri(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,Ps(a.logLevel,!!a.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw new Error("No active session");return this.activeSessionId}onRunStart(a){on("verbose",()=>`[WebNN] onRunStart {sessionId: ${a}}`),this.activeSessionId=a}onRunEnd(a){on("verbose",()=>`[WebNN] onRunEnd {sessionId: ${a}}`);let f=this.temporarySessionTensorIds.get(a);if(f){for(let w of f)on("verbose",()=>`[WebNN] releasing temporary tensor {tensorId: ${w}}`),this.tensorManager.releaseTensorId(w);this.temporarySessionTensorIds.delete(a),this.activeSessionId=void 0}}async createMLContext(a){if(a instanceof GPUDevice){let w=this.mlContextCache.findIndex(T=>T.gpuDevice===a);if(w!==-1)return this.mlContextCache[w].mlContext;{let T=await navigator.ml.createContext(a);return this.mlContextCache.push({gpuDevice:a,mlContext:T}),T}}else if(a===void 0){let w=this.mlContextCache.findIndex(T=>T.options===void 0&&T.gpuDevice===void 0);if(w!==-1)return this.mlContextCache[w].mlContext;{let T=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:T}),T}}let f=this.mlContextCache.findIndex(w=>yo(w.options,a));if(f!==-1)return this.mlContextCache[f].mlContext;{let w=await navigator.ml.createContext(a);return this.mlContextCache.push({options:a,mlContext:w}),w}}registerMLContext(a,f){this.mlContextBySessionId.set(a,f);let w=this.sessionIdsByMLContext.get(f);w||(w=new Set,this.sessionIdsByMLContext.set(f,w)),w.add(a),this.mlOpSupportLimitsBySessionId.has(a)||this.mlOpSupportLimitsBySessionId.set(a,f.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(a,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(a,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(a){this.sessionGraphInputs.delete(a),this.sessionGraphOutputs.delete(a);let f=this.mlContextBySessionId.get(a);if(!f)return;this.tensorManager.releaseTensorsForSession(a),this.mlContextBySessionId.delete(a),this.mlOpSupportLimitsBySessionId.delete(a);let w=this.sessionIdsByMLContext.get(f);if(w.delete(a),w.size===0){this.sessionIdsByMLContext.delete(f);let T=this.mlContextCache.findIndex(A=>A.mlContext===f);T!==-1&&this.mlContextCache.splice(T,1)}}getMLContext(a){return this.mlContextBySessionId.get(a)}getMLOpSupportLimits(a){return this.mlOpSupportLimitsBySessionId.get(a)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(a){on("verbose",()=>`[WebNN] releaseTensorId {tensorId: ${a}}`),this.tensorManager.releaseTensorId(a)}async ensureTensor(a,f,w,T,A){let P=xo.get(w);if(!P)throw new Error(`Unsupported ONNX data type: ${w}`);return this.tensorManager.ensureTensor(a??this.currentSessionId,f,P,T,A)}async createTemporaryTensor(a,f,w){on("verbose",()=>`[WebNN] createTemporaryTensor {onnxDataType: ${f}, shape: ${w}}`);let T=xo.get(f);if(!T)throw new Error(`Unsupported ONNX data type: ${f}`);let A=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(a,A,T,w,!1);let P=this.temporarySessionTensorIds.get(a);return P?P.push(A):this.temporarySessionTensorIds.set(a,[A]),A}uploadTensor(a,f){if(!zt().shouldTransferToMLTensor)throw new Error("Trying to upload to a MLTensor while shouldTransferToMLTensor is false");on("verbose",()=>`[WebNN] uploadTensor {tensorId: ${a}, data: ${f.byteLength}}`),this.tensorManager.upload(a,f)}async downloadTensor(a,f){return this.tensorManager.download(a,f)}createMLTensorDownloader(a,f){return async()=>{let w=await this.tensorManager.download(a);return Et(w,f)}}registerMLTensor(a,f,w,T){let A=xo.get(w);if(!A)throw new Error(`Unsupported ONNX data type: ${w}`);let P=this.tensorManager.registerTensor(a,f,A,T);return on("verbose",()=>`[WebNN] registerMLTensor {tensor: ${f}, dataType: ${A}, dimensions: ${T}} -> {tensorId: ${P}}`),P}registerMLConstant(a,f,w,T,A,P,D=!1){if(!P)throw new Error("External mounted files are not available.");let B=a;a.startsWith("./")&&(B=a.substring(2));let q=P.get(B);if(!q)throw new Error(`File with name ${B} not found in preloaded files.`);if(f+w>q.byteLength)throw new Error("Out of bounds: data offset and length exceed the external file data size.");let G=q.slice(f,f+w).buffer,Z;switch(A.dataType){case"float32":Z=new Float32Array(G);break;case"float16":Z=typeof Float16Array<"u"&&Float16Array.from?new Float16Array(G):new Uint16Array(G);break;case"int32":Z=new Int32Array(G);break;case"uint32":Z=new Uint32Array(G);break;case"int64":if(D){let ee=$n(new Uint8Array(G),"int64");Z=new Int32Array(ee.buffer),A.dataType="int32"}else Z=new BigInt64Array(G);break;case"uint64":Z=new BigUint64Array(G);break;case"int8":Z=new Int8Array(G);break;case"int4":case"uint4":case"uint8":Z=new Uint8Array(G);break;default:throw new Error(`Unsupported data type: ${A.dataType} in creating WebNN Constant from external data.`)}return on("verbose",()=>`[WebNN] registerMLConstant {dataType: ${A.dataType}, shape: ${A.shape}}} ${D?"(Note: it was int64 data type and registered to int32 as workaround)":""}`),T.constant(A,Z)}registerGraphInput(a){this.temporaryGraphInputs.push(a)}registerGraphOutput(a){this.temporaryGraphOutputs.push(a)}isGraphInput(a,f){let w=this.sessionGraphInputs.get(a);return w?w.includes(f):!1}isGraphOutput(a,f){let w=this.sessionGraphOutputs.get(a);return w?w.includes(f):!1}isGraphInputOutputTypeSupported(a,f,w=!0){let T=xo.get(Mr(f)),A=this.mlOpSupportLimitsBySessionId.get(a);return typeof T>"u"?!1:w?!!(A!=null&&A.input.dataTypes.includes(T)):!!(A!=null&&A.output.dataTypes.includes(T))}flush(){}}}),vo=h(()=>{}),Ma,wl,Ei,Vi,Ni,bo,Cc,jc,_l,kl=h(()=>{ds(),vo(),Ma=new Map([[64,250],[128,200],[256,200],[512,200],[2048,230],[4096,200],[8192,50],[16384,50],[32768,50],[65536,50],[131072,50],[262144,50],[524288,50],[1048576,50],[2097152,30],[4194304,20],[8388608,10],[12582912,10],[16777216,10],[26214400,15],[33554432,22],[44236800,2],[58982400,6],[67108864,6],[134217728,6],[167772160,6]]),wl=[],Ei=a=>Math.ceil(Number(a)/16)*16,Vi=a=>{for(let f=0;f<wl.length;f++){let w=wl[f];if(a<=w)return w}return Math.ceil(a/16)*16},Ni=1,bo=()=>Ni++,Cc=async(a,f,w,T)=>{let A=Ei(w),P=a.device.createBuffer({size:A,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});try{let D=a.getCommandEncoder();a.endComputePass(),D.copyBufferToBuffer(f,0,P,0,A),a.flush(),await P.mapAsync(GPUMapMode.READ);let B=P.getMappedRange();if(T){let q=T();return q.set(new Uint8Array(B,0,w)),q}else return new Uint8Array(B.slice(0,w))}finally{P.destroy()}},jc=class{constructor(a){this.backend=a,this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.buffersPending=[],this.capturedPendingBuffers=new Map;for(let[f]of Ma)wl.push(f),this.freeBuffers.set(f,[]),this.freeUniformBuffers.set(f,[]);this.sessionCount=0}upload(a,f){let w=f.buffer,T=f.byteOffset,A=f.byteLength,P=Ei(A),D=this.storageCache.get(a);if(!D)throw new Error("gpu data for uploading does not exist");if(Number(D.originalSize)!==A)throw new Error(`inconsistent data size. gpu data size=${D.originalSize}, data size=${A}`);let B=this.backend.device.createBuffer({mappedAtCreation:!0,size:P,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC}),q=B.getMappedRange();new Uint8Array(q).set(new Uint8Array(w,T,A)),B.unmap();let G=this.backend.device.createCommandEncoder();G.copyBufferToBuffer(B,0,D.gpuData.buffer,0,P),this.backend.device.queue.submit([G.finish()]),B.destroy(),on("verbose",()=>`[WebGPU] GpuDataManager.upload(id=${a})`)}memcpy(a,f){let w=this.storageCache.get(a);if(!w)throw new Error("source gpu data for memcpy does not exist");let T=this.storageCache.get(f);if(!T)throw new Error("destination gpu data for memcpy does not exist");if(w.originalSize!==T.originalSize)throw new Error("inconsistent source and destination gpu data size");let A=Ei(w.originalSize),P=this.backend.getCommandEncoder();this.backend.endComputePass(),P.copyBufferToBuffer(w.gpuData.buffer,0,T.gpuData.buffer,0,A)}registerExternalBuffer(a,f,w){let T;if(w){if(T=w[0],a===w[1])return on("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${f}) => id=${T}, buffer is the same, skip.`),T;if(this.backend.capturedCommandList.has(this.backend.currentSessionId))throw new Error(`Registering a different external buffer under graph capture mode is not supported yet.
|
|
48
48
|
Please use the previous external buffer!`)}else T=bo();return this.storageCache.set(T,{gpuData:{id:T,type:0,buffer:a},originalSize:f}),on("verbose",()=>`[WebGPU] GpuDataManager.registerExternalBuffer(size=${f}) => id=${T}, registered.`),T}unregisterExternalBuffer(a){a!==void 0&&(this.storageCache.delete(a),on("verbose",()=>`[WebGPU] GpuDataManager.unregisterExternalBuffer() => id=${a}`))}create(a,f=GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST){let w=Vi(a),T,A=(f&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE,P=(f&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM;if(A||P){let B=(A?this.freeBuffers:this.freeUniformBuffers).get(w);B?B.length>0?T=B.pop():T=this.backend.device.createBuffer({size:w,usage:f}):T=this.backend.device.createBuffer({size:w,usage:f})}else T=this.backend.device.createBuffer({size:w,usage:f});let D={id:bo(),type:0,buffer:T};return this.storageCache.set(D.id,{gpuData:D,originalSize:Number(a)}),on("verbose",()=>`[WebGPU] GpuDataManager.create(size=${a}) => id=${D.id}`),D}get(a){var f;return(f=this.storageCache.get(a))==null?void 0:f.gpuData}release(a){let f=typeof a=="bigint"?Number(a):a,w=this.storageCache.get(f);if(!w){if(this.storageCache.size===0)return 0;throw new Error("releasing data does not exist")}return on("verbose",()=>`[WebGPU] GpuDataManager.release(id=${f}), gpuDataId=${w.gpuData.id}`),this.storageCache.delete(f),this.buffersPending.push(w.gpuData.buffer),w.originalSize}async download(a,f){let w=this.storageCache.get(Number(a));if(!w)throw new Error("data does not exist");await Cc(this.backend,w.gpuData.buffer,w.originalSize,f)}refreshPendingBuffers(){if(this.buffersPending.length!==0)if(this.backend.sessionStatus==="default"){for(let a of this.buffersPending){let f=Ma.get(a.size);if((a.usage&GPUBufferUsage.STORAGE)===GPUBufferUsage.STORAGE){let w=this.freeBuffers.get(a.size)||[];f===void 0||w.length>=f?a.destroy():w.push(a)}else if((a.usage&GPUBufferUsage.UNIFORM)===GPUBufferUsage.UNIFORM){let w=this.freeUniformBuffers.get(a.size)||[];f===void 0||w.length>=f?a.destroy():w.push(a)}else a.destroy()}this.buffersPending=[]}else{let a=this.capturedPendingBuffers.get(this.backend.currentSessionId);a||(a=[],this.capturedPendingBuffers.set(this.backend.currentSessionId,a));for(let f of this.buffersPending)a.push(f);this.buffersPending=[]}}dispose(){this.freeBuffers.forEach(a=>{a.forEach(f=>{f.destroy()})}),this.freeUniformBuffers.forEach(a=>{a.forEach(f=>{f.destroy()})}),this.storageCache.forEach(a=>{a.gpuData.buffer.destroy()}),this.capturedPendingBuffers.forEach(a=>{a.forEach(f=>{f.destroy()})}),this.storageCache=new Map,this.freeBuffers=new Map,this.freeUniformBuffers=new Map,this.capturedPendingBuffers=new Map}onCreateSession(){this.sessionCount+=1}onReleaseSession(a){let f=this.capturedPendingBuffers.get(a);f&&(f.forEach(w=>{w.destroy()}),this.capturedPendingBuffers.delete(a)),this.sessionCount-=1,this.sessionCount===0&&(on("warning",()=>"[WebGPU] Clearing webgpu buffer cache"),this.storageCache.forEach(w=>{w.gpuData.buffer.destroy()}),this.storageCache=new Map)}},_l=(...a)=>new jc(...a)}),re,fe,ve=h(()=>{re=class{constructor(a){Object.assign(this,a)}get cacheKey(){return this.key||(this.key=Object.getOwnPropertyNames(this).sort().map(a=>`${this[a]}`).join(";")),this.key}},fe=a=>new re(a)}),Te,Ce,Be,Re,Me,Fe,et,it,tt,Xe,At,ze,ut,Cn,Jt,Qt,jn,Ot=h(()=>{Bt(),Qe(),Te=64,Ce=(a,f)=>{if(f===3)throw new Error("vec3 has same alignment as vec4, use vec4 instead");switch(Number(a)){case 10:return f>1?`vec${f}<f16>`:"f16";case 1:return f>1?`vec${f}<f32>`:"f32";case 6:return f>1?`vec${f}<i32>`:"i32";case 12:return f>1?`vec${f}<u32>`:"u32";case 7:if(f>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","i32"];case 13:if(f>1)throw new Error("currently not supported vecX of uint64 yet");return["vec2<u32>","u32"];case 9:if(f!==4)throw new Error("bool must be vec4");return["u32","vec4<bool>"];case 22:return"i32";case 21:return"u32";default:throw new Error(`Unknown data type: ${a}`)}},Be=(a,f=1)=>{let w=Ce(a,f);return typeof w=="string"?w:w[0]},Re=(a,f=1)=>{let w=Ce(a,f);return typeof w=="string"?w:w[1]},Me=(...a)=>{let f=[];return a.forEach(w=>{w.length!==0&&f.push({type:12,data:w},{type:12,data:Ke.computeStrides(w)})}),f},Fe=a=>a%4===0?4:a%2===0?2:1,et=(a="f32",f,w="0")=>!f||f===1?`${a}(${w})`:`vec${f}<${a}>(${w})`,it=(a,f,w)=>a==="f32"?w:f===1?`f32(${w})`:`vec${f}<f32>(${w})`,tt=(a,f)=>f===4?`(${a}.x + ${a}.y + ${a}.z + ${a}.w)`:f===2?`(${a}.x + ${a}.y)`:f===3?`(${a}.x + ${a}.y + ${a}.z)`:a,Xe=(a,f,w,T)=>a.startsWith("uniforms.")&&w>4?typeof f=="string"?T==="f16"?`${a}[(${f}) / 8][(${f}) % 8 / 4][(${f}) % 8 % 4]`:`${a}[(${f}) / 4][(${f}) % 4]`:T==="f16"?`${a}[${Math.floor(f/8)}][${Math.floor(f%8/4)}][${f%8%4}]`:`${a}[${Math.floor(f/4)}][${f%4}]`:w>1?`${a}[${f}]`:a,At=(a,f,w,T,A)=>{let P=typeof w=="number",D=P?w:w.length,B=[...new Array(D).keys()],q=D<2?"u32":D<=4?`vec${D}<u32>`:`array<u32, ${D}>`,G=Ce(f,A),Z=typeof G=="string"?G:G[1],ee=typeof G=="string"?G:G[0],se={indices:q,value:Z,storage:ee,tensor:f},ue=pt=>typeof pt=="string"?pt:`${pt}u`,he={offsetToIndices:!1,indicesToOffset:!1,broadcastedIndicesToOffset:!1,set:!1,setByIndices:!1,get:!1,getByIndices:!1},ge=P?"uniforms.":"",ke=`${ge}${a}_shape`,xe=`${ge}${a}_strides`,me="";for(let pt=0;pt<D-1;pt++)me+=`
|
|
49
49
|
let dim${pt} = current / ${Xe(xe,pt,D)};
|
|
50
50
|
let rest${pt} = current % ${Xe(xe,pt,D)};
|
|
@@ -129,7 +129,7 @@ Error generating stack: `+K.message+`
|
|
|
129
129
|
let aIndices = perm(indices);
|
|
130
130
|
|
|
131
131
|
${ke.setByOffset("global_idx",ge.getByIndices("aIndices"))}
|
|
132
|
-
}`},{name:"Transpose",shaderCache:{hint:`${f}`,inputDependencies:["rank"]},getRunData:()=>{let he=Ke.size(P);return{outputs:[{dims:P,dataType:a.dataType}],dispatchGroup:{x:Math.ceil(he/64)},programUniforms:[{type:12,data:he},...Me(D,B)]}},getShaderSource:G}},Sl=(a,f)=>{Mn(a.inputs,f.perm),a.compute(Gr(a.inputs[0],f.perm))},Ec=a=>fe({perm:a.perm})}),
|
|
132
|
+
}`},{name:"Transpose",shaderCache:{hint:`${f}`,inputDependencies:["rank"]},getRunData:()=>{let he=Ke.size(P);return{outputs:[{dims:P,dataType:a.dataType}],dispatchGroup:{x:Math.ceil(he/64)},programUniforms:[{type:12,data:he},...Me(D,B)]}},getShaderSource:G}},Sl=(a,f)=>{Mn(a.inputs,f.perm),a.compute(Gr(a.inputs[0],f.perm))},Ec=a=>fe({perm:a.perm})}),si,Nc,un,Os,Gu,Ti,Xo,ir,Kr,Cl,Xr,Tc,Ku,$i,Ls,ii,or,Wn,zs,$c,Ac,lg=h(()=>{Bt(),Qe(),Ot(),Qu(),yr(),si={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate * candidate",logSumExp:"bestValue + exp(candidate)",l1:"bestValue + abs(candidate)",l2:"bestValue + candidate * candidate",logSum:"bestValue + candidate"},Nc={max:"select(bestValue, candidate, candidate > bestValue)",min:"select(bestValue, candidate, candidate < bestValue)",mean:"bestValue + candidate",sum:"bestValue + candidate",prod:"bestValue * candidate",sumSquare:"bestValue + candidate",logSumExp:"bestValue + candidate",l1:"bestValue + candidate",l2:"bestValue + candidate",logSum:"bestValue + candidate"},un={max:"_A[offset]",min:"_A[offset]",mean:"0",sum:"0",prod:"1",sumSquare:"0",logSumExp:"0",l1:"0",l2:"0",logSum:"0"},Os={max:"bestValue",min:"bestValue",sum:"bestValue",prod:"bestValue",sumSquare:"bestValue",logSumExp:"log(bestValue)",l1:"bestValue",l2:"sqrt(bestValue)",logSum:"log(bestValue)"},Gu=(a,f)=>{let w=[];for(let T=f-a;T<f;++T)w.push(T);return w},Ti=(a,f)=>{let w=[],T=a.length;for(let P=0;P<T;P++)f.indexOf(P)===-1&&w.push(a[P]);let A=f.map(P=>a[P]);return[w,A]},Xo=(a,f)=>{let w=a.length+f.length,T=[],A=0;for(let P=0;P<w;P++)f.indexOf(P)===-1?T.push(a[A++]):T.push(1);return T},ir=(a,f)=>{for(let w=0;w<a.length;++w)if(a[a.length-w-1]!==f-1-w)return!1;return!0},Kr=(a,f)=>{let w=[];if(!ir(a,f)){for(let T=0;T<f;++T)a.indexOf(T)===-1&&w.push(T);a.forEach(T=>w.push(T))}return w},Cl=(a,f,w,T,A,P,D)=>{let B=w[0].dims,q=Ke.size(P),G=Ke.size(D),Z=ze("_A",w[0].dataType,B),ee=ut("output",A,P),se=64;q===1&&(se=256);let ue=`
|
|
133
133
|
var<workgroup> aBestValues : array<f32, ${se}>;
|
|
134
134
|
`,he=ge=>`
|
|
135
135
|
${ge.registerUniform("reduceSize","u32").declareVariables(Z,ee)}
|
|
@@ -146,7 +146,7 @@ Error generating stack: `+K.message+`
|
|
|
146
146
|
let Length = uniforms.reduceSize;
|
|
147
147
|
for (var k = local_idx; k < Length; k = k + ${se}) {
|
|
148
148
|
let candidate = f32(${Z.getByOffset("offset + k")});
|
|
149
|
-
bestValue = ${
|
|
149
|
+
bestValue = ${si[T]};
|
|
150
150
|
}
|
|
151
151
|
aBestValues[local_idx] = bestValue;
|
|
152
152
|
workgroupBarrier();
|
|
@@ -167,7 +167,7 @@ Error generating stack: `+K.message+`
|
|
|
167
167
|
if (local_idx == 0u) {
|
|
168
168
|
${ee.setByOffset("outputIndex",`${T==="mean"?`${ee.type.storage}(bestValue / f32(uniforms.reduceSize))`:`${ee.type.storage}(${Os[T]})`}`)};
|
|
169
169
|
}
|
|
170
|
-
}`;return{name:a,shaderCache:{hint:`${f};${se}`,inputDependencies:["type"]},getShaderSource:he,getRunData:()=>({outputs:[{dims:P,dataType:A}],dispatchGroup:{x:q},programUniforms:[{type:12,data:G}]})}},Xr=(a,f,w,T)=>{let A=a.inputs.length===1?w:af(a.inputs,w),P=A.axes;P.length===0&&!A.noopWithEmptyAxes&&(P=a.inputs[0].dims.map((ue,he)=>he));let D=Ke.normalizeAxes(P,a.inputs[0].dims.length),B=D,q=a.inputs[0],G=Kr(B,a.inputs[0].dims.length);G.length>0&&(q=a.compute(Gr(a.inputs[0],G),{inputs:[0],outputs:[-1]})[0],B=Gu(B.length,q.dims.length));let[Z,ee]=Ti(q.dims,B),se=Z;A.keepDims&&(se=Xo(Z,D)),a.compute(Cl(f,A.cacheKey,[q],T,a.inputs[0].dataType,se,ee),{inputs:[q]})},Tc=(a,f)=>{Xr(a,"ReduceMeanShared",f,"mean")},Ku=(a,f)=>{Xr(a,"ReduceL1Shared",f,"l1")},$i=(a,f)=>{Xr(a,"ReduceL2Shared",f,"l2")},Ls=(a,f)=>{Xr(a,"ReduceLogSumExpShared",f,"logSumExp")},
|
|
170
|
+
}`;return{name:a,shaderCache:{hint:`${f};${se}`,inputDependencies:["type"]},getShaderSource:he,getRunData:()=>({outputs:[{dims:P,dataType:A}],dispatchGroup:{x:q},programUniforms:[{type:12,data:G}]})}},Xr=(a,f,w,T)=>{let A=a.inputs.length===1?w:af(a.inputs,w),P=A.axes;P.length===0&&!A.noopWithEmptyAxes&&(P=a.inputs[0].dims.map((ue,he)=>he));let D=Ke.normalizeAxes(P,a.inputs[0].dims.length),B=D,q=a.inputs[0],G=Kr(B,a.inputs[0].dims.length);G.length>0&&(q=a.compute(Gr(a.inputs[0],G),{inputs:[0],outputs:[-1]})[0],B=Gu(B.length,q.dims.length));let[Z,ee]=Ti(q.dims,B),se=Z;A.keepDims&&(se=Xo(Z,D)),a.compute(Cl(f,A.cacheKey,[q],T,a.inputs[0].dataType,se,ee),{inputs:[q]})},Tc=(a,f)=>{Xr(a,"ReduceMeanShared",f,"mean")},Ku=(a,f)=>{Xr(a,"ReduceL1Shared",f,"l1")},$i=(a,f)=>{Xr(a,"ReduceL2Shared",f,"l2")},Ls=(a,f)=>{Xr(a,"ReduceLogSumExpShared",f,"logSumExp")},ii=(a,f)=>{Xr(a,"ReduceMaxShared",f,"max")},or=(a,f)=>{Xr(a,"ReduceMinShared",f,"min")},Wn=(a,f)=>{Xr(a,"ReduceProdShared",f,"prod")},zs=(a,f)=>{Xr(a,"ReduceSumShared",f,"sum")},$c=(a,f)=>{Xr(a,"ReduceSumSquareShared",f,"sumSquare")},Ac=(a,f)=>{Xr(a,"ReduceLogSumShared",f,"logSum")}}),Yr,cg,Xu,af,oi,lf,jl,El,ug,Rc,dg,cf,Yu,Ju,uf,ai,df,hg,fg,pg,mg,gg,li,Nl,hf,ff,Qu=h(()=>{Bt(),Qe(),ve(),Ot(),lg(),Yr=a=>{if(!a||a.length===0||a.length>2)throw new Error("Reduce op requires 1 or 2 inputs.");if(a.length===2&&a[1].dims.length!==1)throw new Error("Invalid axes input dims.")},cg=a=>["","",`var value = ${a.getByIndices("input_indices")};`,""],Xu=(a,f,w,T,A,P,D=!1,B=!1)=>{let q=[],G=w[0].dims,Z=G.length,ee=Ke.normalizeAxes(A,Z),se=!B&&ee.length===0;G.forEach((ge,ke)=>{se||ee.indexOf(ke)>=0?D&&q.push(1):q.push(ge)});let ue=q.length,he=Ke.size(q);return{name:a,shaderCache:f,getShaderSource:ge=>{let ke=[],xe=ze("_A",w[0].dataType,Z),me=ut("output",P,ue),Ee=T(xe,me,ee),je=Ee[2];for(let Oe=0,Ge=0;Oe<Z;Oe++)se||ee.indexOf(Oe)>=0?(D&&Ge++,je=`for(var j${Oe}: u32 = 0; j${Oe} < ${G[Oe]}; j${Oe}++) {
|
|
171
171
|
${Ee[2].includes("last_index")?`let last_index = j${Oe};`:""}
|
|
172
172
|
${xe.indicesSet("input_indices",Oe,`j${Oe}`)}
|
|
173
173
|
${je}
|
|
@@ -188,9 +188,9 @@ Error generating stack: `+K.message+`
|
|
|
188
188
|
${Ee[3]}
|
|
189
189
|
${Ee.length===4?me.setByOffset("global_idx","value"):Ee.slice(4).join(`
|
|
190
190
|
`)}
|
|
191
|
-
}`},getRunData:()=>({outputs:[{dims:q,dataType:P}],dispatchGroup:{x:Math.ceil(he/64)},programUniforms:[{type:12,data:he},...Me(G,q)]})}},af=(a,f)=>{let w=[];return a[1].dims[0]>0&&a[1].getBigInt64Array().forEach(T=>w.push(Number(T))),fe({axes:w,keepDims:f.keepDims,noopWithEmptyAxes:f.noopWithEmptyAxes})},
|
|
192
|
-
`)}`,`var value = ${w.getByIndices("input_indices")};`,`value = max(value, ${w.getByIndices("input_indices")});`,""]})},dg=(a,f)=>{Yr(a.inputs),
|
|
193
|
-
`)}`,`var value = ${w.getByIndices("input_indices")};`,`value = min(value, ${w.getByIndices("input_indices")});`,""]})},Yu=(a,f)=>{Yr(a.inputs),
|
|
191
|
+
}`},getRunData:()=>({outputs:[{dims:q,dataType:P}],dispatchGroup:{x:Math.ceil(he/64)},programUniforms:[{type:12,data:he},...Me(G,q)]})}},af=(a,f)=>{let w=[];return a[1].dims[0]>0&&a[1].getBigInt64Array().forEach(T=>w.push(Number(T))),fe({axes:w,keepDims:f.keepDims,noopWithEmptyAxes:f.noopWithEmptyAxes})},oi=(a,f,w,T)=>{let A=a.inputs,P=A.length===1?w:af(A,w);a.compute(Xu(f,{hint:P.cacheKey,inputDependencies:["rank"]},[A[0]],P.noopWithEmptyAxes&&P.axes.length===0?cg:T,P.axes,A[0].dataType,P.keepDims,P.noopWithEmptyAxes),{inputs:[0]})},lf=(a,f)=>{Yr(a.inputs),oi(a,"ReduceLogSum",f,(w,T)=>[`var value = ${T.type.storage}(0);`,"",`value += ${w.getByIndices("input_indices")};`,"value = log(value);"])},jl=(a,f)=>{Yr(a.inputs),oi(a,"ReduceL1",f,(w,T)=>[`var value = ${T.type.storage}(0);`,"",`value += abs(${w.getByIndices("input_indices")});`,""])},El=(a,f)=>{Yr(a.inputs),oi(a,"ReduceL2",f,(w,T)=>[`var t = ${T.type.value}(0); var value = ${T.type.value}(0);`,"",`t = ${w.getByIndices("input_indices")}; value += (t * t);`,"value = sqrt(value);"])},ug=(a,f)=>{Yr(a.inputs),oi(a,"ReduceLogSumExp",f,(w,T)=>[`var value = ${T.type.storage}(0);`,"",`value += exp(${w.getByIndices("input_indices")});`,"value = log(value);"])},Rc=(a,f)=>{Yr(a.inputs),oi(a,"ReduceMax",f,(w,T,A)=>{let P=[];for(let D=0;D<w.rank;D++)(A.indexOf(D)>=0||A.length===0)&&P.push(w.indicesSet("input_indices",D,0));return[`${P.join(`
|
|
192
|
+
`)}`,`var value = ${w.getByIndices("input_indices")};`,`value = max(value, ${w.getByIndices("input_indices")});`,""]})},dg=(a,f)=>{Yr(a.inputs),oi(a,"ReduceMean",f,(w,T,A)=>{let P=1;for(let D=0;D<w.rank;D++)(A.indexOf(D)>=0||A.length===0)&&(P*=a.inputs[0].dims[D]);return["var sum = f32(0);","",`sum += f32(${w.getByIndices("input_indices")});`,`let value = ${T.type.value}(sum / ${P});`]})},cf=(a,f)=>{Yr(a.inputs),oi(a,"ReduceMin",f,(w,T,A)=>{let P=[];for(let D=0;D<w.rank;D++)(A.indexOf(D)>=0||A.length===0)&&P.push(`input_indices[${D}] = 0;`);return[`${P.join(`
|
|
193
|
+
`)}`,`var value = ${w.getByIndices("input_indices")};`,`value = min(value, ${w.getByIndices("input_indices")});`,""]})},Yu=(a,f)=>{Yr(a.inputs),oi(a,"ReduceProd",f,(w,T)=>[`var value = ${T.type.storage}(1);`,"",`value *= ${w.getByIndices("input_indices")};`,""])},Ju=(a,f)=>{Yr(a.inputs),oi(a,"ReduceSum",f,(w,T)=>[`var value = ${T.type.storage}(0);`,"",`value += ${w.getByIndices("input_indices")};`,""])},uf=(a,f)=>{Yr(a.inputs),oi(a,"ReduceSumSquare",f,(w,T)=>[`var t = ${T.type.value}(0); var value = ${T.type.value}(0);`,"",`t = ${w.getByIndices("input_indices")}; value += t * t;`,""])},ai=(a,f,w)=>{if(f.length===0)return w;let T=1,A=1;for(let P=0;P<f.length;P++)f.indexOf(P)===-1?T*=a[P]:A*=a[P];return A<32&&T>1024},df=(a,f)=>{ai(a.inputs[0].dims,f.axes,f.noopWithEmptyAxes)?dg(a,f):Tc(a,f)},hg=(a,f)=>{ai(a.inputs[0].dims,f.axes,f.noopWithEmptyAxes)?jl(a,f):Ku(a,f)},fg=(a,f)=>{ai(a.inputs[0].dims,f.axes,f.noopWithEmptyAxes)?El(a,f):$i(a,f)},pg=(a,f)=>{ai(a.inputs[0].dims,f.axes,f.noopWithEmptyAxes)?ug(a,f):Ls(a,f)},mg=(a,f)=>{ai(a.inputs[0].dims,f.axes,f.noopWithEmptyAxes)?Rc(a,f):ii(a,f)},gg=(a,f)=>{ai(a.inputs[0].dims,f.axes,f.noopWithEmptyAxes)?cf(a,f):or(a,f)},li=(a,f)=>{ai(a.inputs[0].dims,f.axes,f.noopWithEmptyAxes)?Yu(a,f):Wn(a,f)},Nl=(a,f)=>{ai(a.inputs[0].dims,f.axes,f.noopWithEmptyAxes)?Ju(a,f):zs(a,f)},hf=(a,f)=>{ai(a.inputs[0].dims,f.axes,f.noopWithEmptyAxes)?uf(a,f):$c(a,f)},ff=(a,f)=>{ai(a.inputs[0].dims,f.axes,f.noopWithEmptyAxes)?lf(a,f):Ac(a,f)}}),Zu,ed,xg,pf,Tl=h(()=>{Bt(),ve(),Qu(),Zu=a=>{if(!a||a.length===0||a.length>2)throw new Error("ArgMinMaxOp op requires 1 or 2 inputs.");if(a[0].dataType!==1)throw new Error("Invalid input type.")},ed=(a,f)=>{Zu(a.inputs);let w=(T,A,P)=>{let D=[];for(let B=0;B<T.rank;B++)(P.indexOf(B)>=0||P.length===0)&&D.push(`input_indices[${B}] = 0;`);return[`${D.join(`
|
|
194
194
|
`)}`,`var value = ${T.getByIndices("input_indices")};
|
|
195
195
|
var best_index : i32 = 0;`,`if (${T.getByIndices("input_indices")} ${f.selectLastIndex>0?"<=":"<"} value) {
|
|
196
196
|
value = ${T.getByIndices("input_indices")};
|
|
@@ -577,7 +577,7 @@ fn quick_gelu_impl(x: vec4<${a}>) -> vec4<${a}> {
|
|
|
577
577
|
// TODO: implement vectorized pow
|
|
578
578
|
return vec4<${f}>(pow_custom(a.x, b.x), pow_custom(a.y, b.y), pow_custom(a.z, b.z), pow_custom(a.w, b.w));
|
|
579
579
|
}
|
|
580
|
-
`)},Mf=a=>{Qr(a,"Sub",(f,w)=>`${f}-${w}`)},Xi=a=>{Qr(a,"Greater",{scalar:(f,w)=>`u32(${f}>${w})`,vector:(f,w)=>`vec4<u32>(${f}>${w})`},void 0,void 0,9)},Hc=a=>{Qr(a,"Less",{scalar:(f,w)=>`u32(${f}<${w})`,vector:(f,w)=>`vec4<u32>(${f}<${w})`},void 0,void 0,9)},pd=a=>{Qr(a,"GreaterOrEqual",{scalar:(f,w)=>`u32(${f}>=${w})`,vector:(f,w)=>`vec4<u32>(${f}>=${w})`},void 0,void 0,9)},If=a=>{Qr(a,"LessOrEqual",{scalar:(f,w)=>`u32(${f}<=${w})`,vector:(f,w)=>`vec4<u32>(${f}<=${w})`},void 0,void 0,9)}}),So,za,Ba,Wc,qc,Bs,
|
|
580
|
+
`)},Mf=a=>{Qr(a,"Sub",(f,w)=>`${f}-${w}`)},Xi=a=>{Qr(a,"Greater",{scalar:(f,w)=>`u32(${f}>${w})`,vector:(f,w)=>`vec4<u32>(${f}>${w})`},void 0,void 0,9)},Hc=a=>{Qr(a,"Less",{scalar:(f,w)=>`u32(${f}<${w})`,vector:(f,w)=>`vec4<u32>(${f}<${w})`},void 0,void 0,9)},pd=a=>{Qr(a,"GreaterOrEqual",{scalar:(f,w)=>`u32(${f}>=${w})`,vector:(f,w)=>`vec4<u32>(${f}>=${w})`},void 0,void 0,9)},If=a=>{Qr(a,"LessOrEqual",{scalar:(f,w)=>`u32(${f}<=${w})`,vector:(f,w)=>`vec4<u32>(${f}<=${w})`},void 0,void 0,9)}}),So,za,Ba,Wc,qc,Bs,ci=h(()=>{Bt(),Qe(),ve(),Ot(),So=(a,f)=>{if(!a||a.length<1)throw new Error("too few inputs");let w=0,T=a[w],A=T.dataType,P=T.dims.length;a.forEach((D,B)=>{if(B!==w){if(D.dataType!==A)throw new Error("input tensors should be one type");if(D.dims.length!==P)throw new Error("input tensors should have the same shape");D.dims.forEach((q,G)=>{if(G!==f&&q!==T.dims[G])throw new Error("non concat dimensions must match")})}})},za=(a,f)=>`
|
|
581
581
|
fn calculateInputIndex(index: u32) -> u32 {
|
|
582
582
|
let sizeInConcatAxis = array<u32, ${a}u>(${f});
|
|
583
583
|
for (var i: u32 = 0u; i < ${a}; i += 1u ) {
|
|
@@ -1358,8 +1358,8 @@ fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
|
1358
1358
|
let aIndices = perm(indices);
|
|
1359
1359
|
|
|
1360
1360
|
${ge.setByOffset("global_idx",he.getByIndices("aIndices"))}
|
|
1361
|
-
}`;return{name:"DepthToSpace",shaderCache:{hint:`${a.dims};${f.blocksize};${f.mode}`,inputDependencies:["rank"]},getRunData:xe=>{let me=q?[w,T*G,A*G,P/G**2]:[w,P/G**2,T*G,A*G],Ee=Ke.size(me),je=ee.dims,Oe=Ke.sortBasedOnPerm(je,B);return{outputs:[{dims:me,dataType:xe[0].dataType}],dispatchGroup:{x:Math.ceil(Ee/64)},programUniforms:[{type:12,data:Ee},...Me(je,Oe)]}},getShaderSource:ke}},dr=(a,f)=>{Id(a.inputs),a.compute(Xn(a.inputs[0],f))},vr=a=>fe({blocksize:a.blocksize,mode:a.mode,format:a.format})}),oa,Eo,zf,Dr,Dd,Od,Ld,
|
|
1362
|
-
${G.registerUniforms(B.map(je=>({name:`${
|
|
1361
|
+
}`;return{name:"DepthToSpace",shaderCache:{hint:`${a.dims};${f.blocksize};${f.mode}`,inputDependencies:["rank"]},getRunData:xe=>{let me=q?[w,T*G,A*G,P/G**2]:[w,P/G**2,T*G,A*G],Ee=Ke.size(me),je=ee.dims,Oe=Ke.sortBasedOnPerm(je,B);return{outputs:[{dims:me,dataType:xe[0].dataType}],dispatchGroup:{x:Math.ceil(Ee/64)},programUniforms:[{type:12,data:Ee},...Me(je,Oe)]}},getShaderSource:ke}},dr=(a,f)=>{Id(a.inputs),a.compute(Xn(a.inputs[0],f))},vr=a=>fe({blocksize:a.blocksize,mode:a.mode,format:a.format})}),oa,Eo,zf,Dr,Dd,Od,Ld,ui,Hs,Bl,zd,Bf=h(()=>{Bt(),Qe(),ve(),Ot(),oa="[a-zA-Z]|\\.\\.\\.",Eo="("+oa+")+",zf="^"+Eo+"$",Dr="("+Eo+",)*"+Eo,Dd="^"+Dr+"$",Od=class{constructor(a=-1){this.symbolToIndices=new Map,this.inputIndex=a}addSymbol(a,f){let w=this.symbolToIndices.get(a);w===void 0?w=[f]:w.push(f),this.symbolToIndices.set(a,w)}},Ld=class{constructor(a,f){var A;this.equation=f,this.hasEllipsis=!1,this.symbolToInfo=new Map,this.lhs=new Array,this.outputDims=[];let[w,T]=f.includes("->")?f.split("->",2):[f,""];if(!w.match(RegExp(Dd)))throw new Error("Invalid LHS term");if(w.split(",").forEach((P,D)=>{let B=a[D].dims.slice();if(!P.match(RegExp(zf)))throw new Error("Invalid LHS term");let q=this.processTerm(P,!0,B,D);this.lhs.push(q)}),T==="")T+=[...this.symbolToInfo.entries()].filter(([P,D])=>D.count===1||P==="...").map(([P])=>P).join("");else if(!T.match(RegExp(Eo)))throw new Error("Invalid RHS");(A=T.match(RegExp(oa,"g")))==null||A.forEach(P=>{if(P==="...")this.outputDims=this.outputDims.concat(this.ellipsisDims);else{let D=this.symbolToInfo.get(P);if(D===void 0)throw new Error("Invalid RHS symbol");this.outputDims.push(D.dimValue)}}),this.rhs=this.processTerm(T,!1,this.outputDims)}addSymbol(a,f,w){let T=this.symbolToInfo.get(a);if(T!==void 0){if(T.dimValue!==f&&T.count!==1)throw new Error("Dimension mismatch");T.count++,T.inputIndices.push(w)}else T={count:1,dimValue:f,inputIndices:[w]};this.symbolToInfo.set(a,T)}processTerm(a,f,w,T=-1){let A=w.length,P=!1,D=[],B=0;if(!a.match(RegExp(zf))&&!f&&a!=="")throw new Error("Invalid LHS term");let q=a.match(RegExp(oa,"g")),G=new Od(T);return q==null||q.forEach((Z,ee)=>{if(Z==="..."){if(P)throw new Error("Only one ellipsis is allowed per input term");P=!0;let se=A-q.length+1;if(se<0)throw new Error("Ellipsis out of bounds");if(D=w.slice(B,B+se),this.hasEllipsis){if(this.ellipsisDims.length!==D.length||this.ellipsisDims.toString()!==D.toString())throw new Error("Ellipsis dimensions mismatch")}else if(f)this.hasEllipsis=!0,this.ellipsisDims=D;else throw new Error("Ellipsis must be specified in the LHS");for(let ue=0;ue<D.length;ue++){let he=String.fromCharCode(48+ue);G.addSymbol(he,ee+ue),this.addSymbol(he,w[B++],T)}}else G.addSymbol(Z,ee+(this.hasEllipsis?this.ellipsisDims.length-1:0)),this.addSymbol(Z,w[B++],T)}),G}},ui=a=>a+"_max",Hs=(a,f,w,T)=>{let A=a.map(G=>G.length).map((G,Z)=>ze(`input${Z}`,f,G)),P=Ke.size(T),D=ut("output",f,T.length),B=[...w.symbolToInfo.keys()].filter(G=>!w.rhs.symbolToIndices.has(G)),q=G=>{let Z=[],ee="var prod = 1.0;",se="var sum = 0.0;",ue="sum += prod;",he=[],ge=[],ke=[],xe=[],me=w.symbolToInfo.size===w.rhs.symbolToIndices.size;w.symbolToInfo.forEach((je,Oe)=>{var Ge;if(w.rhs.symbolToIndices.has(Oe)){let We=(Ge=w.rhs.symbolToIndices.get(Oe))==null?void 0:Ge[0];We!==void 0&&w.lhs.forEach((Ze,rt)=>{if(je.inputIndices.includes(rt)){let gt=Ze.symbolToIndices.get(Oe);if(gt===void 0)throw new Error("Invalid symbol error");gt.forEach(qt=>{Z.push(`${A[rt].indicesSet(`input${rt}Indices`,qt,D.indicesGet("outputIndices",We))}`)})}})}else w.lhs.forEach((We,Ze)=>{if(je.inputIndices.includes(Ze)){let rt=We.symbolToIndices.get(Oe);if(rt===void 0)throw new Error("Invalid symbol error");rt.forEach(gt=>{he.push(`${A[Ze].indicesSet(`input${Ze}Indices`,gt,`${Oe}`)}`)}),xe.push(`prod *= ${A[Ze].getByIndices(`input${Ze}Indices`)};`)}}),ge.push(`for(var ${Oe}: u32 = 0; ${Oe} < uniforms.${ui(Oe)}; ${Oe}++) {`),ke.push("}")});let Ee=me?[...Z,`let sum = ${A.map((je,Oe)=>je.getByIndices(`input${Oe}Indices`)).join(" * ")};`]:[...Z,se,...ge,...he,ee,...xe,ue,...ke];return`
|
|
1362
|
+
${G.registerUniforms(B.map(je=>({name:`${ui(je)}`,type:"u32"}))).registerUniform("outputSize","u32").declareVariables(...A,D)}
|
|
1363
1363
|
|
|
1364
1364
|
${G.mainStart()}
|
|
1365
1365
|
${G.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.outputSize")}
|
|
@@ -2125,7 +2125,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2125
2125
|
${wt.setByIndices(`${wt.type.indices}(batch, row, col + local_idx)`,"output_value")}
|
|
2126
2126
|
}
|
|
2127
2127
|
}
|
|
2128
|
-
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${f.blockSize};${ee};${se};${ke};${ge}`,inputDependencies:Array(a.length).fill("rank")},getRunData:()=>({outputs:[{dims:ue,dataType:Z}],dispatchGroup:{x:Oe},programUniforms:Ge}),getShaderSource:gt}},Ug=(a,f)=>{Ga(a.inputs,f),f.blockSize===32&&a.adapterInfo.isVendor("intel")&&a.adapterInfo.isArchitecture("gen-12lp")?a.compute(bp(a.inputs,f)):a.compute(th(a.inputs,f))},Hl=a=>fe(a)}),rh,wp,_p,kp,sh,ih,Cr,
|
|
2128
|
+
}`};return{name:"BlockwiseMatMulNBits32",shaderCache:{hint:`${f.blockSize};${ee};${se};${ke};${ge}`,inputDependencies:Array(a.length).fill("rank")},getRunData:()=>({outputs:[{dims:ue,dataType:Z}],dispatchGroup:{x:Oe},programUniforms:Ge}),getShaderSource:gt}},Ug=(a,f)=>{Ga(a.inputs,f),f.blockSize===32&&a.adapterInfo.isVendor("intel")&&a.adapterInfo.isArchitecture("gen-12lp")?a.compute(bp(a.inputs,f)):a.compute(th(a.inputs,f))},Hl=a=>fe(a)}),rh,wp,_p,kp,sh,ih,Cr,di,No,Hg=h(()=>{Bt(),Qe(),Ot(),rh=a=>{if(!a||a.length<1)throw new Error("Too few inputs");if(a[0].dataType!==1&&a[0].dataType!==10)throw new Error("Input type must be float or float16.");if(a.length>=2){let f=a[0].dims.length*2===a[1].dims[0];if(a.length===4&&(f=a[3].dims[0]*2===a[1].dims[0]),!f)throw new Error("The pads should be a 1D tensor of shape [2 * input_rank] or [2 * num_axes].")}},wp=(a,f,w)=>{let T="";for(let A=f-1;A>=0;--A)T+=`
|
|
2129
2129
|
k = i32(${a.indicesGet("indices",A)}) - ${Xe("uniforms.pads",A,w)};
|
|
2130
2130
|
if (k < 0) {
|
|
2131
2131
|
break;
|
|
@@ -2198,7 +2198,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2198
2198
|
var value = ${se}(0);
|
|
2199
2199
|
${ue}
|
|
2200
2200
|
output[global_idx] = value;
|
|
2201
|
-
}`};return{name:"Pad",shaderCache:{hint:`${f.mode}${D}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:w,dataType:a[0].dataType}],dispatchGroup:{x:Math.ceil(Ke.size(w)/64)},programUniforms:P}),getShaderSource:q}},
|
|
2201
|
+
}`};return{name:"Pad",shaderCache:{hint:`${f.mode}${D}`,inputDependencies:B},getRunData:()=>({outputs:[{dims:w,dataType:a[0].dataType}],dispatchGroup:{x:Math.ceil(Ke.size(w)/64)},programUniforms:P}),getShaderSource:q}},di=(a,f)=>{if(a.length>1){let w=a[1].getBigInt64Array(),T=a.length>=3&&a[2].data?a[2].dataType===10?a[2].getUint16Array()[0]:a[2].getFloat32Array()[0]:0,A=a[0].dims.length,P=new Int32Array(2*A).fill(0);if(a.length>=4){let B=a[3].getBigInt64Array();for(let q=0;q<B.length;q++)P[Number(B[q])]=Number(w[q]),P[Number(B[q])+A]=Number(w[q+B.length])}else w.forEach((B,q)=>P[Number(q)]=Number(B));let D=[];return P.forEach(B=>D.push(B)),{mode:f.mode,value:T,pads:D}}else return f},No=(a,f)=>{rh(a.inputs);let w=di(a.inputs,f);a.compute(Cr(a.inputs,w),{inputs:[0]})}}),Wl,Ws,oh,hi,Sp,Cp,jp,ah,lh,Wg,iu,ou,qs,gn,fr,ar,jr,Ts,Ka,br=h(()=>{nt(),Bt(),Qe(),Ot(),Wl=a=>{if(I.webgpu.validateInputContent&&(!a||a.length!==1))throw new Error("Pool ops requires 1 input.")},Ws=(a,f,w)=>{let T=f.format==="NHWC",A=a.dims.slice();T&&A.splice(1,0,A.pop());let P=Object.hasOwnProperty.call(f,"dilations"),D=f.kernelShape.slice(),B=f.strides.slice(),q=P?f.dilations.slice():[],G=f.pads.slice();qr.adjustPoolAttributes(w,A,D,B,q,G);let Z=qr.computePoolOutputShape(w,A,B,q,D,G,f.autoPad),ee=Object.assign({},f);P?Object.assign(ee,{kernelShape:D,strides:B,pads:G,dilations:q,cacheKey:f.cacheKey}):Object.assign(ee,{kernelShape:D,strides:B,pads:G,cacheKey:f.cacheKey});let se=Z.slice();return se.push(se.splice(1,1)[0]),[ee,T?se:Z]},oh=(a,f)=>{let w=f.format==="NHWC",T=Ke.size(a),A=Ke.size(f.kernelShape),P=[{type:12,data:T},{type:12,data:A}],D=[{name:"outputSize",type:"u32"},{name:"kernelSize",type:"u32"}];if(f.kernelShape.length<=2){let B=f.kernelShape[f.kernelShape.length-1],q=f.strides[f.strides.length-1],G=f.pads[f.pads.length/2-1],Z=f.pads[f.pads.length-1],ee=!!(G+Z);P.push({type:12,data:B},{type:12,data:q},{type:12,data:G},{type:12,data:Z}),D.push({name:"kw",type:"u32"},{name:"sw",type:"u32"},{name:"pwStart",type:"u32"},{name:"pwEnd",type:"u32"});let se=!1;if(f.kernelShape.length===2){let ue=f.kernelShape[f.kernelShape.length-2],he=f.strides[f.strides.length-2],ge=f.pads[f.pads.length/2-2],ke=f.pads[f.pads.length-2];se=!!(ge+ke),P.push({type:12,data:ue},{type:12,data:he},{type:12,data:ge},{type:12,data:ke}),D.push({name:"kh",type:"u32"},{name:"sh",type:"u32"},{name:"phStart",type:"u32"},{name:"phEnd",type:"u32"})}return[P,D,!0,ee,se]}else{if(w)throw new Error("Pooling with kernelShape.length > 2 is not supported for NHWC format.");let B=Ke.computeStrides(f.kernelShape);P.push({type:12,data:B},{type:12,data:f.pads},{type:12,data:f.strides}),D.push({name:"kernelStrides",type:"u32",length:B.length},{name:"pads",type:"u32",length:f.pads.length},{name:"strides",type:"u32",length:f.strides.length});let q=f.pads.reduce((G,Z)=>G+Z);return[P,D,!!q,!1,!1]}},hi=(a,f,w,T,A,P,D,B,q,G,Z,ee)=>{let se=A.format==="NHWC",ue=f.type.value,he=ut("output",f.type.tensor,T);if(A.kernelShape.length<=2){let ge="",ke="",xe="",me=w-(se?2:1);if(Z?ge=`
|
|
2202
2202
|
for (var i: u32 = 0u; i < uniforms.kw; i++) {
|
|
2203
2203
|
xIndices[${me}] = indices[${me}] * uniforms.sw - uniforms.pwStart + i;
|
|
2204
2204
|
if (xIndices[${me}] < 0 || xIndices[${me}]
|
|
@@ -2287,9 +2287,9 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2287
2287
|
${D}
|
|
2288
2288
|
|
|
2289
2289
|
output[global_idx] = value;
|
|
2290
|
-
}`}},Sp=a=>`${a.format};${a.ceilMode};${a.autoPad};${a.kernelShape.length}`,Cp=a=>`${Sp(a)};${a.countIncludePad}`,jp=a=>`${Sp(a)};${a.storageOrder};${a.dilations}`,ah=a=>({format:a.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][a.auto_pad],ceilMode:a.ceil_mode,kernelShape:a.kernel_shape,strides:a.strides,pads:a.pads}),lh=(a,f,w,T)=>{let[A,P]=Ws(f,T,w),D=ze("x",f.dataType,f.dims.length),B=D.type.value,q="value += x_val;",G="";A.countIncludePad?G+=`value /= ${B}(uniforms.kernelSize);`:G+=`value /= ${B}(i32(uniforms.kernelSize) - pad);`;let[Z,ee,se,ue,he]=oh(P,A);Z.push(...Me(f.dims,P));let ge=["rank"];return{name:a,shaderCache:{hint:`${T.cacheKey};${se};${ue};${he}`,inputDependencies:ge},getRunData:()=>({outputs:[{dims:P,dataType:f.dataType}],dispatchGroup:{x:Math.ceil(Ke.size(P)/64)},programUniforms:Z}),getShaderSource:ke=>
|
|
2290
|
+
}`}},Sp=a=>`${a.format};${a.ceilMode};${a.autoPad};${a.kernelShape.length}`,Cp=a=>`${Sp(a)};${a.countIncludePad}`,jp=a=>`${Sp(a)};${a.storageOrder};${a.dilations}`,ah=a=>({format:a.format,autoPad:["NOTSET","VALID","SAME_UPPER","SAME_LOWER"][a.auto_pad],ceilMode:a.ceil_mode,kernelShape:a.kernel_shape,strides:a.strides,pads:a.pads}),lh=(a,f,w,T)=>{let[A,P]=Ws(f,T,w),D=ze("x",f.dataType,f.dims.length),B=D.type.value,q="value += x_val;",G="";A.countIncludePad?G+=`value /= ${B}(uniforms.kernelSize);`:G+=`value /= ${B}(i32(uniforms.kernelSize) - pad);`;let[Z,ee,se,ue,he]=oh(P,A);Z.push(...Me(f.dims,P));let ge=["rank"];return{name:a,shaderCache:{hint:`${T.cacheKey};${se};${ue};${he}`,inputDependencies:ge},getRunData:()=>({outputs:[{dims:P,dataType:f.dataType}],dispatchGroup:{x:Math.ceil(Ke.size(P)/64)},programUniforms:Z}),getShaderSource:ke=>hi(ke,D,f.dims.length,P.length,A,q,G,0,ee,se,ue,he)}},Wg=a=>{let f=a.count_include_pad!==0,w=ah(a);if(w.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for AveragePool");let T={countIncludePad:f,...w,cacheKey:""};return{...T,cacheKey:Cp(T)}},iu=(a,f)=>{Wl(a.inputs),a.compute(lh("AveragePool",a.inputs[0],!1,f))},ou={autoPad:"",ceilMode:0,countIncludePad:!1,kernelShape:[],strides:[],pads:[],storageOrder:0,dilations:[]},qs=a=>{let f=a.format;return{format:f,...ou,cacheKey:f}},gn=(a,f)=>{Wl(a.inputs),a.compute(lh("GlobalAveragePool",a.inputs[0],!0,f))},fr=(a,f,w,T)=>{let[A,P]=Ws(f,T,w),D=`
|
|
2291
2291
|
value = max(x_val, value);
|
|
2292
|
-
`,B="",q=ze("x",f.dataType,f.dims.length),G=["rank"],[Z,ee,se,ue,he]=oh(P,A);return Z.push(...Me(f.dims,P)),{name:a,shaderCache:{hint:`${T.cacheKey};${se};${ue};${he}`,inputDependencies:G},getRunData:()=>({outputs:[{dims:P,dataType:f.dataType}],dispatchGroup:{x:Math.ceil(Ke.size(P)/64)},programUniforms:Z}),getShaderSource:ge=>
|
|
2292
|
+
`,B="",q=ze("x",f.dataType,f.dims.length),G=["rank"],[Z,ee,se,ue,he]=oh(P,A);return Z.push(...Me(f.dims,P)),{name:a,shaderCache:{hint:`${T.cacheKey};${se};${ue};${he}`,inputDependencies:G},getRunData:()=>({outputs:[{dims:P,dataType:f.dataType}],dispatchGroup:{x:Math.ceil(Ke.size(P)/64)},programUniforms:Z}),getShaderSource:ge=>hi(ge,q,f.dims.length,P.length,A,D,B,f.dataType===10?-65504:-1e5,ee,se,ue,he)}},ar=(a,f)=>{Wl(a.inputs),a.compute(fr("MaxPool",a.inputs[0],!1,f))},jr=a=>{let f=a.storage_order,w=a.dilations,T=ah(a);if(f!==0)throw new Error("column major storage order is not yet supported for MaxPool");if(T.ceilMode!==0)throw new Error("using ceil() in shape computation is not yet supported for MaxPool");let A={storageOrder:f,dilations:w,...T,cacheKey:""};return{...A,cacheKey:jp(A)}},Ts=a=>{let f=a.format;return{format:f,...ou,cacheKey:f}},Ka=(a,f)=>{Wl(a.inputs),a.compute(fr("GlobalMaxPool",a.inputs[0],!0,f))}}),ql,la,au,ch,lu=h(()=>{Bt(),Qe(),ve(),Ot(),ql=(a,f)=>{if(a.length<2||a.length>3)throw new Error("DequantizeLinear requires 2 or 3 inputs.");if(a.length===3&&a[1].dims===a[2].dims)throw new Error("x-scale and x-zero-point must have the same shape.");if(a.length===3&&a[0].dataType!==a[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(a[1].dims.length!==0&&a[1].dims.length!==1&&a[1].dims.length!==a[0].dims.length)throw new Error("scale input must be a scalar, a 1D tensor, or have the same rank as the input tensor.");if(a.length>2){if(a[0].dataType!==a[2].dataType)throw new Error("x and x-zero-point must have the same data type.");if(a[1].dims.length!==a[2].dims.length)throw new Error("scale and zero-point inputs must have the same rank.");if(!a[1].dims.map((w,T)=>w===a[2].dims[T]).reduce((w,T)=>w&&T,!0))throw new Error("scale and zero-point inputs must have the same shape.")}if(f.blockSize>0){if(a[1].dims.length===0||a[1].dims.length===1&&a[1].dims[0]===1)throw new Error("blockSize must be set only for block quantization.");if(!a[1].dims.map((A,P)=>P===f.axis||A===a[0].dims[P]).reduce((A,P)=>A&&P,!0))throw new Error("For block qunatization, scale input shape to match the input shape except for the axis");if(a[1].dims.length!==a[0].dims.length)throw new Error("For block qunatization the scale input rank must be the same as the x rank.");let w=a[0].dims[f.axis],T=a[1].dims[f.axis];if(f.blockSize<Math.ceil(w/T)||f.blockSize>Math.ceil(w/(T-1)-1))throw new Error("blockSize must be with in the range [ceil(dI / Si), ceil(dI / (Si - 1) - 1)].")}},la=(a,f)=>{let w=Ke.normalizeAxis(f.axis,a[0].dims.length),T=a[0].dataType,A=T===3,P=a[0].dims,D=a[1].dataType,B=Ke.size(P),q=T===3||T===2,G=q?[Math.ceil(Ke.size(a[0].dims)/4)]:a[0].dims,Z=a[1].dims,ee=a.length>2?a[2]:void 0,se=ee?q?[Math.ceil(Ke.size(ee.dims)/4)]:ee.dims:void 0,ue=Z.length===0||Z.length===1&&Z[0]===1,he=ue===!1&&Z.length===1,ge=Fe(B),ke=ue&&(!q||ge===4),xe=ke?ge:1,me=ke&&!q?ge:1,Ee=ze("input",q?12:T,G.length,me),je=ze("scale",D,Z.length),Oe=ee?ze("zero_point",q?12:T,se.length):void 0,Ge=ut("output",D,P.length,xe),We=[Ee,je];Oe&&We.push(Oe);let Ze=[G,Z];ee&&Ze.push(se);let rt=[{type:12,data:B/xe},{type:12,data:w},{type:12,data:f.blockSize},...Me(...Ze,P)],gt=qt=>{let Ut=[{name:"output_size",type:"u32"},{name:"axis",type:"u32"},{name:"block_size",type:"u32"}];return`
|
|
2293
2293
|
${qt.registerUniforms(Ut).declareVariables(...We,Ge)}
|
|
2294
2294
|
${qt.mainStart()}
|
|
2295
2295
|
${qt.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.output_size")}
|
|
@@ -2378,7 +2378,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2378
2378
|
${cu(f.reduction,"output[data_offset + i]","value",he.type.value)}
|
|
2379
2379
|
}
|
|
2380
2380
|
|
|
2381
|
-
}`};return{name:"ScatterND",shaderCache:{hint:`${f.cacheKey}_${f.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:A,dataType:a[0].dataType}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:G}),getShaderSource:Z}},$o=a=>fe({reduction:a.reduction}),uu=(a,f)=>{a.compute(dh(a.inputs,f),{inputs:[a.inputs[1],a.inputs[2]],outputs:[]})}}),du,Vl,hh,Gl,hu,es,Ao,
|
|
2381
|
+
}`};return{name:"ScatterND",shaderCache:{hint:`${f.cacheKey}_${f.reduction}`,inputDependencies:["rank","rank"]},getRunData:()=>({outputs:[{dims:A,dataType:a[0].dataType}],dispatchGroup:{x:Math.ceil(D/64)},programUniforms:G}),getShaderSource:Z}},$o=a=>fe({reduction:a.reduction}),uu=(a,f)=>{a.compute(dh(a.inputs,f),{inputs:[a.inputs[1],a.inputs[2]],outputs:[]})}}),du,Vl,hh,Gl,hu,es,Ao,fi,bs,Ep,fh,ph,Np,Ro,Tp,mh,ua,gh,da,$p,qg=h(()=>{Bt(),Qe(),ve(),Ot(),du=(a,f)=>{if(a.every(w=>w>0||(()=>{throw new Error("Resize requires scales input values to be positive")})),a.length>0){if(f.mode==="linear"){if(!(a.length===2||a.length===3||a.length===4&&a[0]===1&&a[1]===1||a.length===4&&a[0]===1&&a[3]===1||a.length===5&&a[0]===1&&a[1]===1))throw new Error(`For linear mode, Resize requires scales to be 2D, 3D, 4D with either two outermost or one innermost and
|
|
2382
2382
|
one outermost scale values equal to 1, or 5D with two outermost scale values equal to 1`)}else if(f.mode==="cubic"&&!(a.length===2||a.length===4&&a[0]===1&&a[1]===1||a.length===4&&a[0]===1&&a[3]===1))throw new Error("Resize requires scales input size to be 2 or 4 for cubic mode")}},Vl=(a,f,w)=>{f.every(A=>A>=0&&A<w||(()=>{throw new Error("Resize requires axes input values to be positive and less than rank")}));let T=new Array(w).fill(1);return f.forEach((A,P)=>T[A]=a[P]),T},hh=(a,f,w,T,A,P)=>{let[D,B,q]=w>10?[1,2,3]:[-1,a.length>1?1:-1,-1],G=a[0].dims.length;if(D>0&&a.length>D&&a[D].dims.length>0)a[D].getFloat32Array().forEach(Z=>P.push(Z));else if(f.coordinateTransformMode==="tf_crop_and_resize")throw new Error("Resize requires RoI input to be specified when coordinateTransformMode is tfCropAndResize");if(B>0&&a.length>B&&a[B].dims.length===1&&a[B].dims[0]>0){if(a[B].getFloat32Array().forEach(Z=>T.push(Z)),T.length!==0&&T.length!==G&&w>=18&&T.length!==f.axes.length)throw new Error("Resize requires scales input size to be same as input rank or axes size for opset 18 and up");du(T,f),f.axes.length>0&&Vl(T,f.axes,G).forEach((Z,ee)=>T[ee]=Z)}if(q>0&&a.length>q&&a[q].dims.length===1&&a[q].dims[0]>0&&(a[q].getBigInt64Array().forEach(Z=>A.push(Number(Z))),A.length!==0&&A.length!==G&&w>=18&&A.length!==f.axes.length))throw new Error("Resize requires sizes input size to be same as input rank or axes size for opset 18 and up");if(f.axes.length>0){if(T.length!==0&&T.length!==f.axes.length)throw new Error('Resize requires "scales" input size to be of axes rank when axes attributes is specified');if(A.length!==0&&A.length!==f.axes.length)throw new Error('Resize requires "sizes" input size to be of rank axes rank when axes attributes is specified')}if(typeof T<"u"&&typeof A<"u"&&T.length>0&&A.length>G)throw new Error("Resize requires only of scales or sizes to be specified")},Gl=(a,f,w,T)=>`
|
|
2383
2383
|
// The whole part and the fractional part are calculated separately due to inaccuracy of floating
|
|
2384
2384
|
// point division. As an example, f32(21) / f32(7) may evaluate to 2.99... instead of 3, causing an
|
|
@@ -2412,7 +2412,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2412
2412
|
const adjustment = ${f}(lengthResized) / outputWidth;
|
|
2413
2413
|
const center = ${f}(lengthOriginal) / 2;
|
|
2414
2414
|
const offset = center * (1 - adjustment);
|
|
2415
|
-
return offset + ((${f}(xResized) + 0.5) / ${f}(xScale)) - 0.5;`;case"half_pixel":return`return ((${f}(xResized) + 0.5) / ${f}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${a} is not supported`)}})()+"}",es=(a,f,w)=>`fn getNearestPixelFromOriginal(xOriginal: ${w}, isDownSample: bool) -> ${w} {`+(()=>{switch(a){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(f<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${a} is not supported`)}})()+"}",Ao=(a,f,w)=>{let T=new Array(w).fill(0).concat(new Array(w).fill(1)),A=a.length===0?T:a.slice();return f.length>0?(f.forEach((P,D)=>{T[P]=A[D],T[D+w]=A[f.length+D]}),T):A},
|
|
2415
|
+
return offset + ((${f}(xResized) + 0.5) / ${f}(xScale)) - 0.5;`;case"half_pixel":return`return ((${f}(xResized) + 0.5) / ${f}(xScale)) - 0.5;`;default:throw new Error(`Coordinate transform mode ${a} is not supported`)}})()+"}",es=(a,f,w)=>`fn getNearestPixelFromOriginal(xOriginal: ${w}, isDownSample: bool) -> ${w} {`+(()=>{switch(a){case"round_prefer_ceil":return"if (fract(xOriginal) == 0.5) { return ceil(xOriginal); } else { return round(xOriginal); }";case"floor":return"return floor(xOriginal);";case"ceil":return"return ceil(xOriginal);";case"round_prefer_floor":return"if (fract(xOriginal) == 0.5) { return floor(xOriginal); } else { return round(xOriginal); }";case"simple":default:if(f<11)return"if (isDownSample) { return ceil(xOriginal); } else { return xOriginal; }";throw new Error(`Nearest mode ${a} is not supported`)}})()+"}",Ao=(a,f,w)=>{let T=new Array(w).fill(0).concat(new Array(w).fill(1)),A=a.length===0?T:a.slice();return f.length>0?(f.forEach((P,D)=>{T[P]=A[D],T[D+w]=A[f.length+D]}),T):A},fi=(a,f,w,T)=>{let A=[];if(w.length>0)if(T.length>0){if(a.forEach(P=>A.push(P)),Math.max(...T)>a.length)throw new Error("axes is out of bound");T.forEach((P,D)=>A[P]=w[D])}else w.forEach(P=>A.push(P));else{if(f.length===0)throw new Error("Resize requires either scales or sizes.");A=a.map((P,D)=>Math.round(P*f[D]))}return A},bs=(a,f,w)=>{let T=(()=>{switch(w.keepAspectRatioPolicy){case"not_larger":return w.axes.length>0?Math.min(...w.axes.map(P=>f[P]),Number.MAX_VALUE):Math.min(...f,Number.MAX_VALUE);case"not_smaller":return w.axes.length>0?Math.max(...w.axes.map(P=>f[P]),Number.MIN_VALUE):Math.max(...f,Number.MIN_VALUE);default:throw new Error(`Keep aspect ratio policy ${w.keepAspectRatioPolicy} is not supported`)}})();f.fill(1,0,f.length);let A=a.slice();return w.axes.length>0?(w.axes.forEach(P=>f[P]=T),w.axes.forEach(P=>A[P]=Math.round(a[P]*f[P]))):(f.fill(T,0,f.length),A.forEach((P,D)=>A[D]=Math.round(P*f[D]))),A},Ep=(a,f,w,T,A)=>`
|
|
2416
2416
|
fn calculateOriginalIndicesFromOutputIndices(output_indices: ${a.type.indices}) -> array<${a.type.value}, ${w.length}> {
|
|
2417
2417
|
var original_indices: array<${a.type.value}, ${w.length}>;
|
|
2418
2418
|
for (var i:u32 = 0; i < ${w.length}; i++) {
|
|
@@ -2621,7 +2621,7 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2621
2621
|
}
|
|
2622
2622
|
return (x111 * dx2 * dy2 * dz2 + x112 * dx2 * dy2 * dz1 + x121 * dx2 * dy1 *dz2 + x122 * dx2 * dy1 * dz1 +
|
|
2623
2623
|
x211 * dx1 * dy2 * dz2 + x212 * dx1 * dy2 * dz1 + x221 * dx1 * dy1 *dz2 + x222 * dx1 * dy1 * dz1);
|
|
2624
|
-
}`},ua=(a,f,w,T,A,P)=>{let D=a.dims,B=Ao(P,f.axes,D.length),q=
|
|
2624
|
+
}`},ua=(a,f,w,T,A,P)=>{let D=a.dims,B=Ao(P,f.axes,D.length),q=fi(D,T,A,f.axes),G=T.slice();T.length===0&&(G=D.map((me,Ee)=>me===0?1:q[Ee]/me),f.keepAspectRatioPolicy!=="stretch"&&(q=bs(D,G,f)));let Z=ut("output",a.dataType,q.length),ee=ze("input",a.dataType,D.length),se=Ke.size(q),ue=D.length===q.length&&D.every((me,Ee)=>me===q[Ee]),he=f.coordinateTransformMode==="tf_crop_and_resize",ge=f.extrapolationValue,ke=ee.type.value,xe=me=>`
|
|
2625
2625
|
${ue?"":`
|
|
2626
2626
|
${hu(f.coordinateTransformMode,ke)};
|
|
2627
2627
|
${(()=>{switch(f.mode){case"nearest":return`
|
|
@@ -2842,10 +2842,10 @@ fn calculateOutputIndex(index: u32) -> u32 {
|
|
|
2842
2842
|
${a.mainStart()}
|
|
2843
2843
|
${a.guardAgainstOutOfBoundsWorkgroupSizes("uniforms.vec_size")}
|
|
2844
2844
|
${G}
|
|
2845
|
-
}`},vh=a=>{let f=a[1].dims,w=a[2].dims,T=a[0].dims,A=a[1].dataType,P=!(Ke.areEqual(f,w)&&Ke.areEqual(w,T)),D=f,B=Ke.size(f);if(P){let G=Es.calcShape(Es.calcShape(f,w,!1),T,!1);if(!G)throw new Error("Can't perform where op on the given tensors");D=G,B=Ke.size(D)}let q=Math.ceil(B/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:G=>mu(G,a,D,P,A),getRunData:()=>({outputs:[{dims:D,dataType:A}],dispatchGroup:{x:Math.ceil(B/64/4)},programUniforms:[{type:12,data:q},...Me(T,f,w,D)]})}},bh=a=>{a.compute(vh(a.inputs))}}),wh,bv=h(()=>{Tl(),$l(),yg(),_f(),Jr(),fv(),
|
|
2845
|
+
}`},vh=a=>{let f=a[1].dims,w=a[2].dims,T=a[0].dims,A=a[1].dataType,P=!(Ke.areEqual(f,w)&&Ke.areEqual(w,T)),D=f,B=Ke.size(f);if(P){let G=Es.calcShape(Es.calcShape(f,w,!1),T,!1);if(!G)throw new Error("Can't perform where op on the given tensors");D=G,B=Ke.size(D)}let q=Math.ceil(B/4);return{name:"Where",shaderCache:{inputDependencies:["rank","rank","rank"]},getShaderSource:G=>mu(G,a,D,P,A),getRunData:()=>({outputs:[{dims:D,dataType:A}],dispatchGroup:{x:Math.ceil(B/64/4)},programUniforms:[{type:12,data:q},...Me(T,f,w,D)]})}},bh=a=>{a.compute(vh(a.inputs))}}),wh,bv=h(()=>{Tl(),$l(),yg(),_f(),Jr(),fv(),ci(),jg(),Yn(),Md(),Pd(),Bf(),Ng(),Qc(),Xf(),Tg(),pv(),Rg(),mv(),Dg(),gv(),su(),eh(),It(),nh(),hp(),Hg(),br(),lu(),To(),ca(),Qu(),qg(),Lg(),xv(),Kg(),yv(),Xd(),Ja(),yr(),Ki(),vv(),wh=new Map([["Abs",[Al]],["Acos",[bg]],["Acosh",[kf]],["Add",[fs]],["ArgMax",[xg,pf]],["ArgMin",[ed,pf]],["Asin",[Sf]],["Asinh",[zn]],["Atan",[id]],["Atanh",[Ic]],["Attention",[gf]],["AveragePool",[iu,Wg]],["BatchNormalization",[bf]],["BiasAdd",[sd]],["BiasSplitGelu",[ko]],["Cast",[Cf,Rl]],["Ceil",[Pc]],["Clip",[Ml]],["Concat",[qc,Bs]],["Conv",[Ol,Xc]],["ConvTranspose",[$d,ra]],["Cos",[Pa]],["Cosh",[jf]],["CumSum",[Ad,Rd]],["DepthToSpace",[dr,vr]],["DequantizeLinear",[au,ch]],["Div",[Fc]],["Einsum",[Bl,zd]],["Elu",[wg,Dc]],["Equal",[Af]],["Erf",[Lc]],["Exp",[zc]],["Expand",[Wf]],["FastGelu",[Vf]],["Floor",[ad]],["FusedConv",[Ol,Xc]],["Gather",[Kf,eu]],["GatherElements",[rp,Ag]],["GatherBlockQuantized",[ep,tp]],["GatherND",[Jf,Qf]],["Gelu",[ld]],["Gemm",[Ig,Mg]],["GlobalAveragePool",[gn,qs]],["GlobalMaxPool",[Ka,Ts]],["Greater",[Xi]],["GreaterOrEqual",[pd]],["GridSample",[lp,cp]],["GroupQueryAttention",[Zi]],["HardSigmoid",[_o,dd]],["InstanceNormalization",[vp]],["LayerNormalization",[Bg]],["LeakyRelu",[cd,Dc]],["Less",[Hc]],["LessOrEqual",[If]],["Log",[Oa]],["MatMul",[Fg]],["MatMulNBits",[Ug,Hl]],["MaxPool",[ar,jr]],["Mul",[Rf]],["MultiHeadAttention",[dp,ys]],["Neg",[_g]],["Not",[ud]],["Pad",[No]],["Pow",[Uc]],["QuickGelu",[La,Dc]],["Range",[Xa]],["Reciprocal",[Ef]],["ReduceMin",[gg]],["ReduceMean",[df]],["ReduceMax",[mg]],["ReduceSum",[Nl]],["ReduceProd",[li]],["ReduceL1",[hg]],["ReduceL2",[fg]],["ReduceLogSum",[ff]],["ReduceLogSumExp",[pg]],["ReduceSumSquare",[hf]],["Relu",[kg]],["Resize",[da,$p]],["RotaryEmbedding",[nu]],["ScatterND",[uu,$o]],["Sigmoid",[Sg]],["Sin",[Nf]],["Sinh",[Da]],["Slice",[Jn,Gg]],["SkipLayerNormalization",[Vg]],["Split",[mp,Kd]],["Sqrt",[Ai]],["Softmax",[Ip,Pp]],["Sub",[Mf]],["Tan",[Il]],["Tanh",[hd]],["ThresholdedRelu",[Pl,Dc]],["Tile",[pu]],["Transpose",[Sl,Ec]],["Where",[bh]]])}),Dp,Qg=h(()=>{nt(),ds(),Ot(),Dp=class{constructor(a){this.backend=a,this.repo=new Map,this.attributesBound=!1}getArtifact(a){return this.repo.get(a)}setArtifact(a,f){this.repo.set(a,f)}run(a,f,w,T,A){Rt(a.programInfo.name);let P=this.backend.device,D=this.backend.getComputePassEncoder();this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2);let B=[];for(let G of f)B.push({binding:B.length,resource:{buffer:G.buffer}});for(let G of w)B.push({binding:B.length,resource:{buffer:G.buffer}});A&&B.push({binding:B.length,resource:A});let q=P.createBindGroup({layout:a.computePipeline.getBindGroupLayout(0),entries:B,label:a.programInfo.name});if(this.backend.sessionStatus==="capturing"){let G={kernelId:this.backend.currentKernelId,computePipeline:a.computePipeline,bindGroup:q,dispatchGroup:T};this.backend.capturedCommandList.get(this.backend.currentSessionId).push(G)}D.setPipeline(a.computePipeline),D.setBindGroup(0,q),D.dispatchWorkgroups(...T),this.backend.writeTimestamp(this.backend.pendingDispatchNumber*2+1),this.backend.pendingDispatchNumber++,(this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber||this.backend.queryType==="at-passes")&&this.backend.endComputePass(),this.backend.pendingDispatchNumber>=this.backend.maxDispatchNumber&&this.backend.flush(),He(a.programInfo.name)}dispose(){}build(a,f){Rt(a.name);let w=this.backend.device,T=[];[{feature:"shader-f16",extension:"f16"},{feature:"subgroups",extension:"subgroups"}].forEach(G=>{w.features.has(G.feature)&&T.push(`enable ${G.extension};`)});let A=jn(f,this.backend.device.limits),P=a.getShaderSource(A),D=`${T.join(`
|
|
2846
2846
|
`)}
|
|
2847
2847
|
${A.additionalImplementations}
|
|
2848
|
-
${P}`,B=w.createShaderModule({code:D,label:a.name});on("verbose",()=>`[WebGPU] ${a.name} shader code: ${D}`);let q=w.createComputePipeline({compute:{module:B,entryPoint:"main"},layout:"auto",label:a.name});return He(a.name),{programInfo:a,computePipeline:q,uniformVariablesInfo:A.variablesInfo}}normalizeDispatchGroupSize(a){let f=typeof a=="number"?a:a.x,w=typeof a=="number"?1:a.y||1,T=typeof a=="number"?1:a.z||1,A=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(f<=A&&w<=A&&T<=A)return[f,w,T];let P=f*w*T,D=Math.ceil(Math.sqrt(P));if(D>A){if(D=Math.ceil(Math.cbrt(P)),D>A)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[D,D,D]}else return[D,D,1]}}}),gu={};m(gu,{WebGpuBackend:()=>Zg});var xu,Op,_h,Zg,ex=h(()=>{nt(),Bt(),ds(),en(),kl(),bv(),Qg(),xu=(a,f)=>{if(f.length!==a.length)throw new Error(`inputDependencies length ${f.length} is not equal to inputTensors length ${a.length}.`);let w=[];for(let T=0;T<a.length;++T){let A=a[T].dataType;switch(f[T]){case"none":{w.push("");break}case"type":{w.push(`${A}`);break}case"rank":{let P=a[T].dims.length;w.push(`${A};${P}`);break}case"dims":{let P=a[T].dims.join(",");w.push(`${A};${P}`);break}default:throw new Error(`unsupported input dependency: ${f[T]}`)}}return w.join("|")},Op=(a,f,w)=>{var A,P;let T=a.name;return(A=a.shaderCache)!=null&&A.hint&&(T+="["+a.shaderCache.hint+"]"),T+=":"+w+`:${xu(f,((P=a.shaderCache)==null?void 0:P.inputDependencies)??new Array(f.length).fill("dims"))}`,T},_h=class{constructor(a){a&&(this.architecture=a.architecture,this.vendor=a.vendor)}isArchitecture(a){return this.architecture===a}isVendor(a){return this.vendor===a}},Zg=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let a=this.kernelCustomData.get(this.currentKernelId);return a||(a={},this.kernelCustomData.set(this.currentKernelId,a)),a}async initialize(a,f){this.env=a;let w=[],T={requiredLimits:{maxComputeWorkgroupStorageSize:f.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:f.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:f.limits.maxStorageBufferBindingSize,maxBufferSize:f.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:f.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:f.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:f.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:f.limits.maxComputeWorkgroupSizeZ},requiredFeatures:w},A=P=>f.features.has(P)&&w.push(P)&&!0;A("chromium-experimental-timestamp-query-inside-passes")||A("timestamp-query"),A("shader-f16"),A("subgroups"),this.device=await f.requestDevice(T),this.adapterInfo=new _h(f.info||await f.requestAdapterInfo()),this.gpuDataManager=_l(this),this.programManager=new Dp(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ps(a.logLevel,!!a.debug),this.device.onuncapturederror=P=>{P.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${P.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:f,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){var a;typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&((a=this.env)!=null&&a.webgpu)&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let a=this.getCommandEncoder(),f={};this.queryType==="at-passes"&&(f.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=a.beginComputePass(f)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Rt(),this.endComputePass();let a;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),a=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(a,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,a,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&a.mapAsync(GPUMapMode.READ).then(()=>{var T;let f=new BigUint64Array(a.getMappedRange()),w=this.pendingQueries.get(a);for(let A=0;A<f.length/2;A++){let P=w[A],D=P.kernelId,B=this.kernels.get(D),q=B.kernelType,G=B.kernelName,Z=P.programName,ee=P.inputTensorViews,se=P.outputTensorViews,ue=f[A*2],he=f[A*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=ue);let ge=Number(ue-this.queryTimeBase),ke=Number(he-this.queryTimeBase);if(!Number.isSafeInteger(ge)||!Number.isSafeInteger(ke))throw new RangeError("incorrect timestamp range");if((T=this.env.webgpu.profiling)!=null&&T.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:ee.map(xe=>({dims:xe.dims,dataType:Vn(xe.dataType)})),outputsMetadata:se.map(xe=>({dims:xe.dims,dataType:Vn(xe.dataType)})),kernelId:D,kernelType:q,kernelName:G,programName:Z,startTime:ge,endTime:ke});else{let xe="";ee.forEach((Ee,je)=>{xe+=`input[${je}]: [${Ee.dims}] | ${Vn(Ee.dataType)}, `});let me="";se.forEach((Ee,je)=>{me+=`output[${je}]: [${Ee.dims}] | ${Vn(Ee.dataType)}, `}),console.log(`[profiling] kernel "${D}|${q}|${G}|${Z}" ${xe}${me}start time: ${ge} ns, execution time: ${ke-ge} ns`)}lt("GPU",`${Z}::${ue}::${he}`)}a.unmap(),this.pendingQueries.delete(a)}),He()}run(a,f,w,T,A,P){Rt(a.name);let D=[];for(let me=0;me<f.length;++me){let Ee=f[me].data;if(Ee===0)continue;let je=this.gpuDataManager.get(Ee);if(!je)throw new Error(`no GPU data for input: ${Ee}`);D.push(je)}let{outputs:B,dispatchGroup:q,programUniforms:G}=a.getRunData(f),Z=w.length===0?B.map((me,Ee)=>Ee):w;if(Z.length!==B.length)throw new Error(`Output size ${Z.length} must be equal to ${B.length}.`);let ee=[],se=[];for(let me=0;me<B.length;++me){if(!Number.isInteger(Z[me])||Z[me]<-3||Z[me]>=P)throw new Error(`Invalid output index: ${Z[me]}`);if(Z[me]===-3)continue;let Ee=Z[me]===-1,je=Z[me]===-2,Oe=Ee||je?A(B[me].dataType,B[me].dims):T(Z[me],B[me].dataType,B[me].dims);if(ee.push(Oe),Oe.data===0)continue;let Ge=this.gpuDataManager.get(Oe.data);if(!Ge)throw new Error(`no GPU data for output: ${Oe.data}`);if(Ee&&this.temporaryData.push(Ge),je){let We=this.kernelPersistentData.get(this.currentKernelId);We||(We=[],this.kernelPersistentData.set(this.currentKernelId,We)),We.push(Ge)}se.push(Ge)}if(D.length!==f.length||se.length!==ee.length){if(se.length===0)return He(a.name),ee;throw new Error(`Program ${a.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let ue;if(G){let me=0,Ee=[];G.forEach(We=>{let Ze=typeof We.data=="number"?[We.data]:We.data;if(Ze.length===0)return;let rt=We.type===10?2:4,gt,qt;We.type===10?(qt=Ze.length>4?16:Ze.length>2?8:Ze.length*rt,gt=Ze.length>4?16:rt*Ze.length):(qt=Ze.length<=2?Ze.length*rt:16,gt=16),me=Math.ceil(me/qt)*qt,Ee.push(me);let Ut=We.type===10?8:4;me+=Ze.length>4?Math.ceil(Ze.length/Ut)*gt:Ze.length*rt});let je=16;me=Math.ceil(me/je)*je;let Oe=new ArrayBuffer(me);G.forEach((We,Ze)=>{let rt=Ee[Ze],gt=typeof We.data=="number"?[We.data]:We.data;if(We.type===6)new Int32Array(Oe,rt,gt.length).set(gt);else if(We.type===12)new Uint32Array(Oe,rt,gt.length).set(gt);else if(We.type===10)new Uint16Array(Oe,rt,gt.length).set(gt);else if(We.type===1)new Float32Array(Oe,rt,gt.length).set(gt);else throw new Error(`Unsupported uniform type: ${Vn(We.type)}`)});let Ge=this.gpuDataManager.create(me,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ge.buffer,0,Oe,0,me),this.gpuDataManager.release(Ge.id),ue={offset:0,size:me,buffer:Ge.buffer}}let he=this.programManager.normalizeDispatchGroupSize(q),ge=he[1]===1&&he[2]===1,ke=Op(a,f,ge),xe=this.programManager.getArtifact(ke);if(xe||(xe=this.programManager.build(a,he),this.programManager.setArtifact(ke,xe),on("info",()=>`[artifact] key: ${ke}, programName: ${a.name}`)),G&&xe.uniformVariablesInfo){if(G.length!==xe.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${xe.uniformVariablesInfo.length}, got ${G.length} in program "${xe.programInfo.name}".`);for(let me=0;me<G.length;me++){let Ee=G[me],je=Ee.type,Oe=typeof Ee.data=="number"?1:Ee.data.length,[Ge,We]=xe.uniformVariablesInfo[me];if(je!==Ge||Oe!==We)throw new Error(`Uniform variable ${me} mismatch: expect type ${Ge} with size ${We}, got type ${je} with size ${Oe} in program "${xe.programInfo.name}".`)}}if(on("info",()=>`[ProgramManager] run "${a.name}" (key=${ke}) with ${he[0]}x${he[1]}x${he[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let me={kernelId:this.currentKernelId,programName:xe.programInfo.name,inputTensorViews:f,outputTensorViews:ee};this.pendingKernels.push(me),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(me)}return this.programManager.run(xe,D,se,he,ue),He(a.name),ee}upload(a,f){this.gpuDataManager.upload(a,f)}memcpy(a,f){this.gpuDataManager.memcpy(a,f)}async download(a,f){await this.gpuDataManager.download(a,f)}alloc(a){return this.gpuDataManager.create(a).id}free(a){return this.gpuDataManager.release(a)}createKernel(a,f,w,T){let A=wh.get(a);if(!A)throw new Error(`kernel not implemented: ${a}`);let P={kernelType:a,kernelName:T,kernelEntry:A[0],attributes:[A[1],w]};this.kernels.set(f,P)}releaseKernel(a){let f=this.kernelPersistentData.get(a);if(f){for(let w of f)this.gpuDataManager.release(w.id);this.kernelPersistentData.delete(a)}this.kernelCustomData.delete(a),this.kernels.delete(a)}computeKernel(a,f,w){let T=this.kernels.get(a);if(!T)throw new Error(`kernel not created: ${a}`);let A=T.kernelType,P=T.kernelName,D=T.kernelEntry,B=T.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${A}] ${P}" is not allowed to be called recursively`);this.currentKernelId=a,B[0]&&(B[1]=B[0](B[1]),B[0]=void 0),on("info",()=>`[WebGPU] Start to run kernel "[${A}] ${P}"...`);let q=this.env.debug;this.temporaryData=[];try{return q&&this.device.pushErrorScope("validation"),D(f,B[1]),0}catch(G){return w.push(Promise.resolve(`[WebGPU] Kernel "[${A}] ${P}" failed. ${G}`)),1}finally{q&&w.push(this.device.popErrorScope().then(G=>G?`GPU validation error for kernel "[${A}] ${P}": ${G.message}`:null));for(let G of this.temporaryData)this.gpuDataManager.release(G.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(a,f,w,T){let A=this.sessionExternalDataMapping.get(a);A||(A=new Map,this.sessionExternalDataMapping.set(a,A));let P=A.get(f),D=this.gpuDataManager.registerExternalBuffer(w,T,P);return A.set(f,[D,w]),D}unregisterBuffers(a){let f=this.sessionExternalDataMapping.get(a);f&&(f.forEach(w=>this.gpuDataManager.unregisterExternalBuffer(w[0])),this.sessionExternalDataMapping.delete(a))}getBuffer(a){let f=this.gpuDataManager.get(a);if(!f)throw new Error(`no GPU data for buffer: ${a}`);return f.buffer}createDownloader(a,f,w){return async()=>{let T=await Cc(this,a,f);return Et(T.buffer,w)}}writeTimestamp(a){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,a)}setQueryType(){var a;this.queryType="none",(((a=this.env.webgpu.profiling)==null?void 0:a.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){on("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){on("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){on("info","replay"),this.sessionStatus="replaying";let a=this.capturedCommandList.get(this.currentSessionId),f=this.capturedPendingKernels.get(this.currentSessionId),w=a.length;this.pendingKernels=[];for(let T=0;T<w;T++){let A=this.getComputePassEncoder(),P=a[T];this.writeTimestamp(this.pendingDispatchNumber*2),A.setPipeline(P.computePipeline),A.setBindGroup(0,P.bindGroup),A.dispatchWorkgroups(...P.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(f[T]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(a){this.unregisterBuffers(a),this.capturedCommandList.has(a)&&this.capturedCommandList.delete(a),this.capturedPendingKernels.has(a)&&this.capturedPendingKernels.delete(a),this.gpuDataManager.onReleaseSession(a)}onRunStart(a){this.currentSessionId=a,this.setQueryType()}}}),kh={};m(kh,{init:()=>yu});var Qa,Sh,yu,tx=h(()=>{Bt(),ds(),Qe(),bl(),Qa=class O2{constructor(f,w,T,A){this.module=f,this.dataType=w,this.data=T,this.dims=A}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let f=Ke.size(this.dims);return f===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,f)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let f=Ke.size(this.dims);return f===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,f)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let f=Ke.size(this.dims);return f===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,f)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let f=Ke.size(this.dims);return f===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,f)}reshape(f){if(Ke.size(f)!==Ke.size(this.dims))throw new Error("Invalid new shape");return new O2(this.module,this.dataType,this.data,f)}},Sh=class{constructor(a,f,w){this.module=a,this.backend=f,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=f.adapterInfo;let T=a.PTR_SIZE,A=w/a.PTR_SIZE,P=T===4?"i32":"i64";this.opKernelContext=Number(a.getValue(T*A++,P));let D=Number(a.getValue(T*A++,P));this.outputCount=Number(a.getValue(T*A++,P)),this.customDataOffset=Number(a.getValue(T*A++,"*")),this.customDataSize=Number(a.getValue(T*A++,P));let B=[];for(let q=0;q<D;q++){let G=Number(a.getValue(T*A++,P)),Z=Number(a.getValue(T*A++,"*")),ee=Number(a.getValue(T*A++,P)),se=[];for(let ue=0;ue<ee;ue++)se.push(Number(a.getValue(T*A++,P)));B.push(new Qa(a,G,Z,se))}this.inputs=B}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(a,f){var D;let w=((D=f==null?void 0:f.inputs)==null?void 0:D.map(B=>typeof B=="number"?this.inputs[B]:B))??this.inputs,T=(f==null?void 0:f.outputs)??[],A=(B,q,G)=>new Qa(this.module,q,this.output(B,G),G),P=(B,q)=>{let G=Ir(B,q);if(!G)throw new Error(`Unsupported data type: ${B}`);let Z=G>0?this.backend.gpuDataManager.create(G).id:0;return new Qa(this.module,B,Z,q)};return this.backend.run(a,w,T,A,P,this.outputCount)}output(a,f){let w=this.module.stackSave();try{let T=this.module.PTR_SIZE,A=T===4?"i32":"i64",P=this.module.stackAlloc((1+f.length)*T);this.module.setValue(P,f.length,A);for(let D=0;D<f.length;D++)this.module.setValue(P+T*(D+1),f[D],A);return this.module._JsepOutput(this.opKernelContext,a,P)}catch(T){throw new Error(`Failed to generate kernel's output[${a}] with dims [${f}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${T}`)}finally{this.module.stackRestore(w)}}},yu=async(a,f,w,T)=>{let A=f.jsepInit;if(!A)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(a==="webgpu"){let P=(ex(),g(gu)).WebGpuBackend,D=new P;await D.initialize(w,T),A("webgpu",[D,B=>D.alloc(Number(B)),B=>D.free(B),(B,q,G,Z=!1)=>{if(Z)on("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(B)}, dst=${Number(q)}, size=${Number(G)}`),D.memcpy(Number(B),Number(q));else{on("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(B)}, gpuDataId=${Number(q)}, size=${Number(G)}`);let ee=f.HEAPU8.subarray(Number(B>>>0),Number(B>>>0)+Number(G));D.upload(Number(q),ee)}},async(B,q,G)=>{on("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${B}, dataOffset=${q}, size=${G}`),await D.download(Number(B),()=>f.HEAPU8.subarray(Number(q)>>>0,Number(q+G)>>>0))},(B,q,G)=>D.createKernel(B,Number(q),G,f.UTF8ToString(f._JsepGetNodeName(Number(q)))),B=>D.releaseKernel(B),(B,q,G,Z)=>{on("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${G}, kernel=${B}, contextDataOffset=${q}`);let ee=new Sh(f,D,Number(q));return D.computeKernel(Number(B),ee,Z)},()=>D.captureBegin(),()=>D.captureEnd(),()=>D.replay()])}else{let P=new Sc(w);A("webnn",[P,()=>P.reserveTensorId(),D=>P.releaseTensorId(D),async(D,B,q,G,Z)=>P.ensureTensor(D,B,q,G,Z),(D,B)=>{P.uploadTensor(D,B)},async(D,B)=>P.downloadTensor(D,B),(D,B)=>P.registerMLContext(D,B),!!w.trace])}}}),nx,Xl,Lp,fi,rx,Yl,c,p,k,M,F,K,de,_e=h(()=>{nt(),$a(),kn(),Bt(),Hr(),Ui(),Si(),nx=(a,f)=>{zt()._OrtInit(a,f)!==0&&Ct("Can't initialize onnxruntime.")},Xl=async a=>{nx(a.wasm.numThreads,Hi(a.logLevel))},Lp=async(a,f)=>{var T,A;(A=(T=zt()).asyncInit)==null||A.call(T);let w=a.webgpu.adapter;if(f==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(w){if(typeof w.limits!="object"||typeof w.features!="object"||typeof w.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let P=a.webgpu.powerPreference;if(P!==void 0&&P!=="low-power"&&P!=="high-performance")throw new Error(`Invalid powerPreference setting: "${P}"`);let D=a.webgpu.forceFallbackAdapter;if(D!==void 0&&typeof D!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${D}"`);if(w=await navigator.gpu.requestAdapter({powerPreference:P,forceFallbackAdapter:D}),!w)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(f==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let P=(tx(),g(kh)).init;f==="webgpu"&&await P("webgpu",zt(),a,w),f==="webnn"&&await P("webnn",zt(),a)}},fi=new Map,rx=a=>{let f=zt(),w=f.stackSave();try{let T=f.PTR_SIZE,A=f.stackAlloc(2*T);f._OrtGetInputOutputCount(a,A,A+T)!==0&&Ct("Can't get session input/output count.");let P=T===4?"i32":"i64";return[Number(f.getValue(A,P)),Number(f.getValue(A+T,P))]}finally{f.stackRestore(w)}},Yl=(a,f)=>{let w=zt(),T=w.stackSave(),A=0;try{let P=w.PTR_SIZE,D=w.stackAlloc(2*P);w._OrtGetInputOutputMetadata(a,f,D,D+P)!==0&&Ct("Can't get session input/output metadata.");let B=Number(w.getValue(D,"*"));A=Number(w.getValue(D+P,"*"));let q=w.HEAP32[A/4];if(q===0)return[B,0];let G=w.HEAPU32[A/4+1],Z=[];for(let ee=0;ee<G;ee++){let se=Number(w.getValue(A+8+ee*P,"*"));Z.push(se!==0?w.UTF8ToString(se):Number(w.getValue(A+8+(ee+G)*P,"*")))}return[B,q,Z]}finally{w.stackRestore(T),A!==0&&w._OrtFree(A)}},c=a=>{let f=zt(),w=f._malloc(a.byteLength);if(w===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${a.byteLength}.`);return f.HEAPU8.set(a,w),[w,a.byteLength]},p=async(a,f)=>{var ee,se,ue,he;let w,T,A=zt();Array.isArray(a)?[w,T]=a:a.buffer===A.HEAPU8.buffer?[w,T]=[a.byteOffset,a.byteLength]:[w,T]=c(a);let P=0,D=0,B=0,q=[],G=[],Z=[];try{if([D,q]=await Ra(f),(f==null?void 0:f.externalData)&&A.mountExternalData){let Ze=[];for(let rt of f.externalData){let gt=typeof rt=="string"?rt:rt.path;Ze.push(Gn(typeof rt=="string"?rt:rt.data).then(qt=>{A.mountExternalData(gt,qt)}))}await Promise.all(Ze)}for(let Ze of(f==null?void 0:f.executionProviders)??[])if((typeof Ze=="string"?Ze:Ze.name)==="webnn"){if(A.shouldTransferToMLTensor=!1,typeof Ze!="string"){let rt=Ze,gt=rt==null?void 0:rt.context,qt=rt==null?void 0:rt.gpuDevice,Ut=rt==null?void 0:rt.deviceType,Ht=rt==null?void 0:rt.powerPreference;gt?A.currentContext=gt:qt?A.currentContext=await A.webnnCreateMLContext(qt):A.currentContext=await A.webnnCreateMLContext({deviceType:Ut,powerPreference:Ht})}else A.currentContext=await A.webnnCreateMLContext();break}P=await A._OrtCreateSession(w,T,D),(ee=A.webgpuOnCreateSession)==null||ee.call(A,P),P===0&&Ct("Can't create a session."),(se=A.jsepOnCreateSession)==null||se.call(A),A.currentContext&&(A.webnnRegisterMLContext(P,A.currentContext),A.currentContext=void 0,A.shouldTransferToMLTensor=!0);let[ge,ke]=rx(P),xe=!!(f!=null&&f.enableGraphCapture),me=[],Ee=[],je=[],Oe=[],Ge=[];for(let Ze=0;Ze<ge;Ze++){let[rt,gt,qt]=Yl(P,Ze);rt===0&&Ct("Can't get an input name."),G.push(rt);let Ut=A.UTF8ToString(rt);me.push(Ut),je.push(gt===0?{name:Ut,isTensor:!1}:{name:Ut,isTensor:!0,type:Vn(gt),shape:qt})}for(let Ze=0;Ze<ke;Ze++){let[rt,gt,qt]=Yl(P,Ze+ge);rt===0&&Ct("Can't get an output name."),Z.push(rt);let Ut=A.UTF8ToString(rt);Ee.push(Ut),Oe.push(gt===0?{name:Ut,isTensor:!1}:{name:Ut,isTensor:!0,type:Vn(gt),shape:qt});{if(xe&&(f==null?void 0:f.preferredOutputLocation)===void 0){Ge.push("gpu-buffer");continue}let Ht=typeof(f==null?void 0:f.preferredOutputLocation)=="string"?f.preferredOutputLocation:((ue=f==null?void 0:f.preferredOutputLocation)==null?void 0:ue[Ut])??"cpu",fn=A.webnnIsGraphOutput;if(Ht==="cpu"&&fn&&fn(P,Ut)){Ge.push("ml-tensor-cpu-output");continue}if(Ht!=="cpu"&&Ht!=="cpu-pinned"&&Ht!=="gpu-buffer"&&Ht!=="ml-tensor")throw new Error(`Not supported preferred output location: ${Ht}.`);if(xe&&Ht!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${Ht}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);Ge.push(Ht)}}let We=null;return Ge.some(Ze=>Ze==="gpu-buffer"||Ze==="ml-tensor"||Ze==="ml-tensor-cpu-output")&&(B=A._OrtCreateBinding(P),B===0&&Ct("Can't create IO binding."),We={handle:B,outputPreferredLocations:Ge,outputPreferredLocationsEncoded:Ge.map(Ze=>Ze==="ml-tensor-cpu-output"?"ml-tensor":Ze).map(Ze=>gr(Ze))}),fi.set(P,[P,G,Z,We,xe,!1]),[P,me,Ee,je,Oe]}catch(ge){throw G.forEach(ke=>A._OrtFree(ke)),Z.forEach(ke=>A._OrtFree(ke)),B!==0&&A._OrtReleaseBinding(B)!==0&&Ct("Can't release IO binding."),P!==0&&A._OrtReleaseSession(P)!==0&&Ct("Can't release session."),ge}finally{A._free(w),D!==0&&A._OrtReleaseSessionOptions(D)!==0&&Ct("Can't release session options."),q.forEach(ge=>A._free(ge)),(he=A.unmountExternalData)==null||he.call(A)}},k=a=>{var q,G,Z;let f=zt(),w=fi.get(a);if(!w)throw new Error(`cannot release session. invalid session id: ${a}`);let[T,A,P,D,B]=w;D&&(B&&f._OrtClearBoundOutputs(D.handle)!==0&&Ct("Can't clear bound outputs."),f._OrtReleaseBinding(D.handle)!==0&&Ct("Can't release IO binding.")),(q=f.jsepOnReleaseSession)==null||q.call(f,a),(G=f.webnnOnReleaseSession)==null||G.call(f,a),(Z=f.webgpuOnReleaseSession)==null||Z.call(f,a),A.forEach(ee=>f._OrtFree(ee)),P.forEach(ee=>f._OrtFree(ee)),f._OrtReleaseSession(T)!==0&&Ct("Can't release session."),fi.delete(a)},M=async(a,f,w,T,A,P,D=!1)=>{if(!a){f.push(0);return}let B=zt(),q=B.PTR_SIZE,G=a[0],Z=a[1],ee=a[3],se=ee,ue,he;if(G==="string"&&(ee==="gpu-buffer"||ee==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(D&&ee!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${P} when enableGraphCapture is true.`);if(ee==="gpu-buffer"){let xe=a[2].gpuBuffer;he=Ir(Mr(G),Z);{let me=B.jsepRegisterBuffer;if(!me)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');ue=me(T,P,xe,he)}}else if(ee==="ml-tensor"){let xe=a[2].mlTensor;he=Ir(Mr(G),Z);let me=B.webnnRegisterMLTensor;if(!me)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');ue=me(T,xe,Mr(G),Z)}else{let xe=a[2];if(Array.isArray(xe)){he=q*xe.length,ue=B._malloc(he),w.push(ue);for(let me=0;me<xe.length;me++){if(typeof xe[me]!="string")throw new TypeError(`tensor data at index ${me} is not a string`);B.setValue(ue+me*q,Hn(xe[me],w),"*")}}else{let me=B.webnnIsGraphInput,Ee=B.webnnIsGraphOutput;if(G!=="string"&&me&&Ee){let je=B.UTF8ToString(A);if(me(T,je)||Ee(T,je)){let Oe=Mr(G);he=Ir(Oe,Z),se="ml-tensor";let Ge=B.webnnCreateTemporaryTensor,We=B.webnnUploadTensor;if(!Ge||!We)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Ze=await Ge(T,Oe,Z);We(Ze,new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength)),ue=Ze}else he=xe.byteLength,ue=B._malloc(he),w.push(ue),B.HEAPU8.set(new Uint8Array(xe.buffer,xe.byteOffset,he),ue)}else he=xe.byteLength,ue=B._malloc(he),w.push(ue),B.HEAPU8.set(new Uint8Array(xe.buffer,xe.byteOffset,he),ue)}}let ge=B.stackSave(),ke=B.stackAlloc(4*Z.length);try{Z.forEach((me,Ee)=>B.setValue(ke+Ee*q,me,q===4?"i32":"i64"));let xe=B._OrtCreateTensor(Mr(G),ue,he,ke,Z.length,gr(se));xe===0&&Ct(`Can't create tensor for input/output. session=${T}, index=${P}.`),f.push(xe)}finally{B.stackRestore(ge)}},F=async(a,f,w,T,A,P)=>{var Ut,Ht,fn,xn;let D=zt(),B=D.PTR_SIZE,q=fi.get(a);if(!q)throw new Error(`cannot run inference. invalid session id: ${a}`);let G=q[0],Z=q[1],ee=q[2],se=q[3],ue=q[4],he=q[5],ge=f.length,ke=T.length,xe=0,me=[],Ee=[],je=[],Oe=[],Ge=[],We=D.stackSave(),Ze=D.stackAlloc(ge*B),rt=D.stackAlloc(ge*B),gt=D.stackAlloc(ke*B),qt=D.stackAlloc(ke*B);try{[xe,me]=fo(P),vt("wasm prepareInputOutputTensor");for(let wt=0;wt<ge;wt++)await M(w[wt],Ee,Oe,a,Z[f[wt]],f[wt],ue);for(let wt=0;wt<ke;wt++)await M(A[wt],je,Oe,a,ee[T[wt]],ge+T[wt],ue);st("wasm prepareInputOutputTensor");for(let wt=0;wt<ge;wt++)D.setValue(Ze+wt*B,Ee[wt],"*"),D.setValue(rt+wt*B,Z[f[wt]],"*");for(let wt=0;wt<ke;wt++)D.setValue(gt+wt*B,je[wt],"*"),D.setValue(qt+wt*B,ee[T[wt]],"*");if(se&&!he){let{handle:wt,outputPreferredLocations:bn,outputPreferredLocationsEncoded:pt}=se;if(Z.length!==ge)throw new Error(`input count from feeds (${ge}) is expected to be always equal to model's input count (${Z.length}).`);vt("wasm bindInputsOutputs");for(let Nt=0;Nt<ge;Nt++){let Lt=f[Nt];await D._OrtBindInput(wt,Z[Lt],Ee[Nt])!==0&&Ct(`Can't bind input[${Nt}] for session=${a}.`)}for(let Nt=0;Nt<ke;Nt++){let Lt=T[Nt];(Ut=A[Nt])!=null&&Ut[3]?(Ge.push(je[Nt]),D._OrtBindOutput(wt,ee[Lt],je[Nt],0)!==0&&Ct(`Can't bind pre-allocated output[${Nt}] for session=${a}.`)):D._OrtBindOutput(wt,ee[Lt],0,pt[Lt])!==0&&Ct(`Can't bind output[${Nt}] to ${bn[Nt]} for session=${a}.`)}st("wasm bindInputsOutputs"),fi.set(a,[G,Z,ee,se,ue,!0])}(Ht=D.jsepOnRunStart)==null||Ht.call(D,G),(fn=D.webnnOnRunStart)==null||fn.call(D,G);let Wt;se?Wt=await D._OrtRunWithBinding(G,se.handle,ke,gt,xe):Wt=await D._OrtRun(G,rt,Ze,ge,qt,ke,gt,xe),Wt!==0&&Ct("failed to call OrtRun().");let Zt=[],_r=[];vt("wasm ProcessOutputTensor");for(let wt=0;wt<ke;wt++){let bn=Number(D.getValue(gt+wt*B,"*"));if(bn===je[wt]||Ge.includes(je[wt])){Zt.push(A[wt]),bn!==je[wt]&&D._OrtReleaseTensor(bn)!==0&&Ct("Can't release tensor.");continue}let pt=D.stackSave(),Nt=D.stackAlloc(4*B),Lt=!1,_t,Dn=0;try{D._OrtGetTensorData(bn,Nt,Nt+B,Nt+2*B,Nt+3*B)!==0&&Ct(`Can't access output tensor data on index ${wt}.`);let Za=B===4?"i32":"i64",ws=Number(D.getValue(Nt,Za));Dn=D.getValue(Nt+B,"*");let Io=D.getValue(Nt+B*2,"*"),Po=Number(D.getValue(Nt+B*3,Za)),Jl=[];for(let ts=0;ts<Po;ts++)Jl.push(Number(D.getValue(Io+ts*B,Za)));D._OrtFree(Io)!==0&&Ct("Can't free memory for tensor dims.");let Ql=Jl.reduce((ts,kr)=>ts*kr,1);_t=Vn(ws);let zp=se==null?void 0:se.outputPreferredLocations[T[wt]];if(_t==="string"){if(zp==="gpu-buffer"||zp==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ts=[];for(let kr=0;kr<Ql;kr++){let el=D.getValue(Dn+kr*B,"*"),xN=D.getValue(Dn+(kr+1)*B,"*"),yN=kr===Ql-1?void 0:xN-el;ts.push(D.UTF8ToString(el,yN))}Zt.push([_t,Jl,ts,"cpu"])}else if(zp==="gpu-buffer"&&Ql>0){let ts=D.jsepGetBuffer;if(!ts)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let kr=ts(Dn),el=Ir(ws,Ql);if(el===void 0||!ki(_t))throw new Error(`Unsupported data type: ${_t}`);Lt=!0,Zt.push([_t,Jl,{gpuBuffer:kr,download:D.jsepCreateDownloader(kr,el,_t),dispose:()=>{D._OrtReleaseTensor(bn)!==0&&Ct("Can't release tensor.")}},"gpu-buffer"])}else if(zp==="ml-tensor"&&Ql>0){let ts=D.webnnEnsureTensor,kr=D.webnnIsGraphInputOutputTypeSupported;if(!ts||!kr)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ir(ws,Ql)===void 0||!cs(_t))throw new Error(`Unsupported data type: ${_t}`);if(!kr(a,_t,!1))throw new Error(`preferredLocation "ml-tensor" for ${_t} output is not supported by current WebNN Context.`);let el=await ts(a,Dn,ws,Jl,!1);Lt=!0,Zt.push([_t,Jl,{mlTensor:el,download:D.webnnCreateMLTensorDownloader(Dn,_t),dispose:()=>{D.webnnReleaseTensorId(Dn),D._OrtReleaseTensor(bn)}},"ml-tensor"])}else if(zp==="ml-tensor-cpu-output"&&Ql>0){let ts=D.webnnCreateMLTensorDownloader(Dn,_t)(),kr=Zt.length;Lt=!0,_r.push((async()=>{let el=[kr,await ts];return D.webnnReleaseTensorId(Dn),D._OrtReleaseTensor(bn),el})()),Zt.push([_t,Jl,[],"cpu"])}else{let ts=ti(_t),kr=new ts(Ql);new Uint8Array(kr.buffer,kr.byteOffset,kr.byteLength).set(D.HEAPU8.subarray(Dn,Dn+kr.byteLength)),Zt.push([_t,Jl,kr,"cpu"])}}finally{D.stackRestore(pt),_t==="string"&&Dn&&D._free(Dn),Lt||D._OrtReleaseTensor(bn)}}se&&!ue&&(D._OrtClearBoundOutputs(se.handle)!==0&&Ct("Can't clear bound outputs."),fi.set(a,[G,Z,ee,se,ue,!1]));for(let[wt,bn]of await Promise.all(_r))Zt[wt][2]=bn;return st("wasm ProcessOutputTensor"),Zt}finally{(xn=D.webnnOnRunEnd)==null||xn.call(D,G),D.stackRestore(We),Ee.forEach(Wt=>D._OrtReleaseTensor(Wt)),je.forEach(Wt=>D._OrtReleaseTensor(Wt)),Oe.forEach(Wt=>D._free(Wt)),xe!==0&&D._OrtReleaseRunOptions(xe),me.forEach(Wt=>D._free(Wt))}},K=a=>{let f=zt(),w=fi.get(a);if(!w)throw new Error("invalid session id");let T=w[0],A=f._OrtEndProfiling(T);A===0&&Ct("Can't get an profile file name."),f._OrtFree(A)},de=a=>{let f=[];for(let w of a){let T=w[2];!Array.isArray(T)&&"buffer"in T&&f.push(T.buffer)}return f}}),$e,qe,at,ct,ot,jt,Pt,Dt,Pn,Ue,Ie,Ve,ht,Ft,Xt,Yt,rn,wr,vn=h(()=>{nt(),_e(),Hr(),Ur(),$e=()=>!!I.wasm.proxy&&typeof document<"u",at=!1,ct=!1,ot=!1,Dt=new Map,Pn=(a,f)=>{let w=Dt.get(a);w?w.push(f):Dt.set(a,[f])},Ue=()=>{if(at||!ct||ot||!qe)throw new Error("worker not ready")},Ie=a=>{switch(a.data.type){case"init-wasm":at=!1,a.data.err?(ot=!0,Pt[1](a.data.err)):(ct=!0,Pt[0]()),jt&&(URL.revokeObjectURL(jt),jt=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let f=Dt.get(a.data.type);a.data.err?f.shift()[1](a.data.err):f.shift()[0](a.data.out);break}}},Ve=async()=>{if(!ct){if(at)throw new Error("multiple calls to 'initWasm()' detected.");if(ot)throw new Error("previous call to 'initWasm()' failed.");if(at=!0,$e())return new Promise((a,f)=>{qe==null||qe.terminate(),_i().then(([w,T])=>{try{qe=T,qe.onerror=P=>f(P),qe.onmessage=Ie,Pt=[a,f];let A={type:"init-wasm",in:I};if(!A.in.wasm.wasmPaths&&w){let P=Fr();P&&(A.in.wasm.wasmPaths=P)}qe.postMessage(A),jt=w}catch(A){f(A)}},f)});try{await ei(I.wasm),await Xl(I),ct=!0}catch(a){throw ot=!0,a}finally{at=!1}}},ht=async a=>{if($e())return Ue(),new Promise((f,w)=>{Pn("init-ep",[f,w]);let T={type:"init-ep",in:{epName:a,env:I}};qe.postMessage(T)});await Lp(I,a)},Ft=async a=>$e()?(Ue(),new Promise((f,w)=>{Pn("copy-from",[f,w]);let T={type:"copy-from",in:{buffer:a}};qe.postMessage(T,[a.buffer])})):c(a),Xt=async(a,f)=>{if($e()){if(f!=null&&f.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ue(),new Promise((w,T)=>{Pn("create",[w,T]);let A={type:"create",in:{model:a,options:{...f}}},P=[];a instanceof Uint8Array&&P.push(a.buffer),qe.postMessage(A,P)})}else return p(a,f)},Yt=async a=>{if($e())return Ue(),new Promise((f,w)=>{Pn("release",[f,w]);let T={type:"release",in:a};qe.postMessage(T)});k(a)},rn=async(a,f,w,T,A,P)=>{if($e()){if(w.some(D=>D[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(A.some(D=>D))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ue(),new Promise((D,B)=>{Pn("run",[D,B]);let q=w,G={type:"run",in:{sessionId:a,inputIndices:f,inputs:q,outputIndices:T,options:P}};qe.postMessage(G,de(q))})}else return F(a,f,w,T,A,P)},wr=async a=>{if($e())return Ue(),new Promise((f,w)=>{Pn("end-profiling",[f,w]);let T={type:"end-profiling",in:a};qe.postMessage(T)});K(a)}}),eo,sx,q0,fN=h(()=>{nt(),vn(),Bt(),St(),Si(),eo=(a,f)=>{switch(a.location){case"cpu":return[a.type,a.dims,a.data,"cpu"];case"gpu-buffer":return[a.type,a.dims,{gpuBuffer:a.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[a.type,a.dims,{mlTensor:a.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${a.location} for ${f()}`)}},sx=a=>{switch(a[3]){case"cpu":return new Ne(a[0],a[2],a[1]);case"gpu-buffer":{let f=a[0];if(!ki(f))throw new Error(`not supported data type: ${f} for deserializing GPU tensor`);let{gpuBuffer:w,download:T,dispose:A}=a[2];return Ne.fromGpuBuffer(w,{dataType:f,dims:a[1],download:T,dispose:A})}case"ml-tensor":{let f=a[0];if(!cs(f))throw new Error(`not supported data type: ${f} for deserializing MLTensor tensor`);let{mlTensor:w,download:T,dispose:A}=a[2];return Ne.fromMLTensor(w,{dataType:f,dims:a[1],download:T,dispose:A})}default:throw new Error(`invalid data location: ${a[3]}`)}},q0=class{async fetchModelAndCopyToWasmMemory(a){return Ft(await Gn(a))}async loadModel(a,f){Rt();let w;typeof a=="string"?w=await this.fetchModelAndCopyToWasmMemory(a):w=a,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Xt(w,f),He()}async dispose(){return Yt(this.sessionId)}async run(a,f,w){Rt();let T=[],A=[];Object.entries(a).forEach(ee=>{let se=ee[0],ue=ee[1],he=this.inputNames.indexOf(se);if(he===-1)throw new Error(`invalid input '${se}'`);T.push(ue),A.push(he)});let P=[],D=[];Object.entries(f).forEach(ee=>{let se=ee[0],ue=ee[1],he=this.outputNames.indexOf(se);if(he===-1)throw new Error(`invalid output '${se}'`);P.push(ue),D.push(he)});let B=T.map((ee,se)=>eo(ee,()=>`input "${this.inputNames[A[se]]}"`)),q=P.map((ee,se)=>ee?eo(ee,()=>`output "${this.outputNames[D[se]]}"`):null),G=await rn(this.sessionId,A,B,D,q,w),Z={};for(let ee=0;ee<G.length;ee++)Z[this.outputNames[D[ee]]]=P[ee]??sx(G[ee]);return He(),Z}startProfiling(){}endProfiling(){wr(this.sessionId)}}}),V0={};m(V0,{OnnxruntimeWebAssemblyBackend:()=>_v,initializeFlags:()=>wv,wasmBackend:()=>G0});var wv,_v,G0,pN=h(()=>{nt(),vn(),fN(),wv=()=>{(typeof I.wasm.initTimeout!="number"||I.wasm.initTimeout<0)&&(I.wasm.initTimeout=0);let a=I.wasm.simd;if(typeof a!="boolean"&&a!==void 0&&a!=="fixed"&&a!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${a}". Reset it to \`false\` and ignore SIMD feature checking.`),I.wasm.simd=!1),typeof I.wasm.proxy!="boolean"&&(I.wasm.proxy=!1),typeof I.wasm.trace!="boolean"&&(I.wasm.trace=!1),typeof I.wasm.numThreads!="number"||!Number.isInteger(I.wasm.numThreads)||I.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)I.wasm.numThreads=1;else{let f=typeof navigator>"u"?u("node:os").cpus().length:navigator.hardwareConcurrency;I.wasm.numThreads=Math.min(4,Math.ceil((f||1)/2))}},_v=class{async init(a){wv(),await Ve(),await ht(a)}async createInferenceSessionHandler(a,f){let w=new q0;return await w.loadModel(a,f),w}},G0=new _v}),K0={};m(K0,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>vt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,default:()=>gN,env:()=>I,registerBackend:()=>E}),nt(),nt(),nt();var mN="1.26.0",gN=Tr;{let a=(pN(),g(V0)).wasmBackend;E("webgpu",a,5),E("webnn",a,5),E("cpu",a,10),E("wasm",a,10)}return Object.defineProperty(I.versions,"web",{value:mN,enumerable:!0}),g(K0)})();/**
|
|
2848
|
+
${P}`,B=w.createShaderModule({code:D,label:a.name});on("verbose",()=>`[WebGPU] ${a.name} shader code: ${D}`);let q=w.createComputePipeline({compute:{module:B,entryPoint:"main"},layout:"auto",label:a.name});return He(a.name),{programInfo:a,computePipeline:q,uniformVariablesInfo:A.variablesInfo}}normalizeDispatchGroupSize(a){let f=typeof a=="number"?a:a.x,w=typeof a=="number"?1:a.y||1,T=typeof a=="number"?1:a.z||1,A=this.backend.device.limits.maxComputeWorkgroupsPerDimension;if(f<=A&&w<=A&&T<=A)return[f,w,T];let P=f*w*T,D=Math.ceil(Math.sqrt(P));if(D>A){if(D=Math.ceil(Math.cbrt(P)),D>A)throw new Error("Total dispatch size exceeds WebGPU maximum.");return[D,D,D]}else return[D,D,1]}}}),gu={};m(gu,{WebGpuBackend:()=>Zg});var xu,Op,_h,Zg,ex=h(()=>{nt(),Bt(),ds(),en(),kl(),bv(),Qg(),xu=(a,f)=>{if(f.length!==a.length)throw new Error(`inputDependencies length ${f.length} is not equal to inputTensors length ${a.length}.`);let w=[];for(let T=0;T<a.length;++T){let A=a[T].dataType;switch(f[T]){case"none":{w.push("");break}case"type":{w.push(`${A}`);break}case"rank":{let P=a[T].dims.length;w.push(`${A};${P}`);break}case"dims":{let P=a[T].dims.join(",");w.push(`${A};${P}`);break}default:throw new Error(`unsupported input dependency: ${f[T]}`)}}return w.join("|")},Op=(a,f,w)=>{var A,P;let T=a.name;return(A=a.shaderCache)!=null&&A.hint&&(T+="["+a.shaderCache.hint+"]"),T+=":"+w+`:${xu(f,((P=a.shaderCache)==null?void 0:P.inputDependencies)??new Array(f.length).fill("dims"))}`,T},_h=class{constructor(a){a&&(this.architecture=a.architecture,this.vendor=a.vendor)}isArchitecture(a){return this.architecture===a}isVendor(a){return this.vendor===a}},Zg=class{constructor(){this.currentSessionId=null,this.currentKernelId=null,this.commandEncoder=null,this.computePassEncoder=null,this.maxDispatchNumber=16,this.pendingDispatchNumber=0,this.pendingKernels=[],this.pendingQueries=new Map,this.sessionStatus="default",this.capturedCommandList=new Map,this.capturedPendingKernels=new Map,this.sessionExternalDataMapping=new Map}get currentKernelCustomData(){if(this.currentKernelId===null)throw new Error("currentKernelCustomData(): currentKernelId is null. (should not happen)");let a=this.kernelCustomData.get(this.currentKernelId);return a||(a={},this.kernelCustomData.set(this.currentKernelId,a)),a}async initialize(a,f){this.env=a;let w=[],T={requiredLimits:{maxComputeWorkgroupStorageSize:f.limits.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:f.limits.maxComputeWorkgroupsPerDimension,maxStorageBufferBindingSize:f.limits.maxStorageBufferBindingSize,maxBufferSize:f.limits.maxBufferSize,maxComputeInvocationsPerWorkgroup:f.limits.maxComputeInvocationsPerWorkgroup,maxComputeWorkgroupSizeX:f.limits.maxComputeWorkgroupSizeX,maxComputeWorkgroupSizeY:f.limits.maxComputeWorkgroupSizeY,maxComputeWorkgroupSizeZ:f.limits.maxComputeWorkgroupSizeZ},requiredFeatures:w},A=P=>f.features.has(P)&&w.push(P)&&!0;A("chromium-experimental-timestamp-query-inside-passes")||A("timestamp-query"),A("shader-f16"),A("subgroups"),this.device=await f.requestDevice(T),this.adapterInfo=new _h(f.info||await f.requestAdapterInfo()),this.gpuDataManager=_l(this),this.programManager=new Dp(this),this.kernels=new Map,this.kernelPersistentData=new Map,this.kernelCustomData=new Map,Ps(a.logLevel,!!a.debug),this.device.onuncapturederror=P=>{P.error instanceof GPUValidationError&&console.error(`An uncaught WebGPU validation error was raised: ${P.error.message}`)},Object.defineProperty(this.env.webgpu,"device",{value:this.device,writable:!1,enumerable:!0,configurable:!0}),Object.defineProperty(this.env.webgpu,"adapter",{value:f,writable:!1,enumerable:!0,configurable:!1}),this.setQueryType()}dispose(){var a;typeof this.querySet<"u"&&this.querySet.destroy(),this.gpuDataManager.dispose(),this.device&&((a=this.env)!=null&&a.webgpu)&&this.device.lost.then(()=>{delete this.env.webgpu.device})}getCommandEncoder(){return this.commandEncoder||(this.commandEncoder=this.device.createCommandEncoder()),this.commandEncoder}getComputePassEncoder(){if(!this.computePassEncoder){let a=this.getCommandEncoder(),f={};this.queryType==="at-passes"&&(f.timestampWrites={querySet:this.querySet,beginningOfPassWriteIndex:this.pendingDispatchNumber*2,endOfPassWriteIndex:this.pendingDispatchNumber*2+1}),this.computePassEncoder=a.beginComputePass(f)}return this.computePassEncoder}endComputePass(){this.computePassEncoder&&(this.computePassEncoder.end(),this.computePassEncoder=null)}flush(){if(!this.commandEncoder)return;Rt(),this.endComputePass();let a;this.queryType!=="none"&&(this.commandEncoder.resolveQuerySet(this.querySet,0,this.pendingDispatchNumber*2,this.queryResolveBuffer,0),a=this.device.createBuffer({size:this.pendingDispatchNumber*2*8,usage:GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST}),this.pendingQueries.set(a,this.pendingKernels),this.pendingKernels=[],this.commandEncoder.copyBufferToBuffer(this.queryResolveBuffer,0,a,0,this.pendingDispatchNumber*2*8)),this.device.queue.submit([this.commandEncoder.finish()]),this.gpuDataManager.refreshPendingBuffers(),this.commandEncoder=null,this.pendingDispatchNumber=0,this.queryType!=="none"&&a.mapAsync(GPUMapMode.READ).then(()=>{var T;let f=new BigUint64Array(a.getMappedRange()),w=this.pendingQueries.get(a);for(let A=0;A<f.length/2;A++){let P=w[A],D=P.kernelId,B=this.kernels.get(D),q=B.kernelType,G=B.kernelName,Z=P.programName,ee=P.inputTensorViews,se=P.outputTensorViews,ue=f[A*2],he=f[A*2+1];typeof this.queryTimeBase>"u"&&(this.queryTimeBase=ue);let ge=Number(ue-this.queryTimeBase),ke=Number(he-this.queryTimeBase);if(!Number.isSafeInteger(ge)||!Number.isSafeInteger(ke))throw new RangeError("incorrect timestamp range");if((T=this.env.webgpu.profiling)!=null&&T.ondata)this.env.webgpu.profiling.ondata({version:1,inputsMetadata:ee.map(xe=>({dims:xe.dims,dataType:Vn(xe.dataType)})),outputsMetadata:se.map(xe=>({dims:xe.dims,dataType:Vn(xe.dataType)})),kernelId:D,kernelType:q,kernelName:G,programName:Z,startTime:ge,endTime:ke});else{let xe="";ee.forEach((Ee,je)=>{xe+=`input[${je}]: [${Ee.dims}] | ${Vn(Ee.dataType)}, `});let me="";se.forEach((Ee,je)=>{me+=`output[${je}]: [${Ee.dims}] | ${Vn(Ee.dataType)}, `}),console.log(`[profiling] kernel "${D}|${q}|${G}|${Z}" ${xe}${me}start time: ${ge} ns, execution time: ${ke-ge} ns`)}lt("GPU",`${Z}::${ue}::${he}`)}a.unmap(),this.pendingQueries.delete(a)}),He()}run(a,f,w,T,A,P){Rt(a.name);let D=[];for(let me=0;me<f.length;++me){let Ee=f[me].data;if(Ee===0)continue;let je=this.gpuDataManager.get(Ee);if(!je)throw new Error(`no GPU data for input: ${Ee}`);D.push(je)}let{outputs:B,dispatchGroup:q,programUniforms:G}=a.getRunData(f),Z=w.length===0?B.map((me,Ee)=>Ee):w;if(Z.length!==B.length)throw new Error(`Output size ${Z.length} must be equal to ${B.length}.`);let ee=[],se=[];for(let me=0;me<B.length;++me){if(!Number.isInteger(Z[me])||Z[me]<-3||Z[me]>=P)throw new Error(`Invalid output index: ${Z[me]}`);if(Z[me]===-3)continue;let Ee=Z[me]===-1,je=Z[me]===-2,Oe=Ee||je?A(B[me].dataType,B[me].dims):T(Z[me],B[me].dataType,B[me].dims);if(ee.push(Oe),Oe.data===0)continue;let Ge=this.gpuDataManager.get(Oe.data);if(!Ge)throw new Error(`no GPU data for output: ${Oe.data}`);if(Ee&&this.temporaryData.push(Ge),je){let We=this.kernelPersistentData.get(this.currentKernelId);We||(We=[],this.kernelPersistentData.set(this.currentKernelId,We)),We.push(Ge)}se.push(Ge)}if(D.length!==f.length||se.length!==ee.length){if(se.length===0)return He(a.name),ee;throw new Error(`Program ${a.name} has zero-sized tensor(s) in inputs or outputs. This is not supported now.`)}let ue;if(G){let me=0,Ee=[];G.forEach(We=>{let Ze=typeof We.data=="number"?[We.data]:We.data;if(Ze.length===0)return;let rt=We.type===10?2:4,gt,qt;We.type===10?(qt=Ze.length>4?16:Ze.length>2?8:Ze.length*rt,gt=Ze.length>4?16:rt*Ze.length):(qt=Ze.length<=2?Ze.length*rt:16,gt=16),me=Math.ceil(me/qt)*qt,Ee.push(me);let Ut=We.type===10?8:4;me+=Ze.length>4?Math.ceil(Ze.length/Ut)*gt:Ze.length*rt});let je=16;me=Math.ceil(me/je)*je;let Oe=new ArrayBuffer(me);G.forEach((We,Ze)=>{let rt=Ee[Ze],gt=typeof We.data=="number"?[We.data]:We.data;if(We.type===6)new Int32Array(Oe,rt,gt.length).set(gt);else if(We.type===12)new Uint32Array(Oe,rt,gt.length).set(gt);else if(We.type===10)new Uint16Array(Oe,rt,gt.length).set(gt);else if(We.type===1)new Float32Array(Oe,rt,gt.length).set(gt);else throw new Error(`Unsupported uniform type: ${Vn(We.type)}`)});let Ge=this.gpuDataManager.create(me,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);this.device.queue.writeBuffer(Ge.buffer,0,Oe,0,me),this.gpuDataManager.release(Ge.id),ue={offset:0,size:me,buffer:Ge.buffer}}let he=this.programManager.normalizeDispatchGroupSize(q),ge=he[1]===1&&he[2]===1,ke=Op(a,f,ge),xe=this.programManager.getArtifact(ke);if(xe||(xe=this.programManager.build(a,he),this.programManager.setArtifact(ke,xe),on("info",()=>`[artifact] key: ${ke}, programName: ${a.name}`)),G&&xe.uniformVariablesInfo){if(G.length!==xe.uniformVariablesInfo.length)throw new Error(`Uniform variables count mismatch: expect ${xe.uniformVariablesInfo.length}, got ${G.length} in program "${xe.programInfo.name}".`);for(let me=0;me<G.length;me++){let Ee=G[me],je=Ee.type,Oe=typeof Ee.data=="number"?1:Ee.data.length,[Ge,We]=xe.uniformVariablesInfo[me];if(je!==Ge||Oe!==We)throw new Error(`Uniform variable ${me} mismatch: expect type ${Ge} with size ${We}, got type ${je} with size ${Oe} in program "${xe.programInfo.name}".`)}}if(on("info",()=>`[ProgramManager] run "${a.name}" (key=${ke}) with ${he[0]}x${he[1]}x${he[2]}`),this.queryType!=="none"||this.sessionStatus==="capturing"){let me={kernelId:this.currentKernelId,programName:xe.programInfo.name,inputTensorViews:f,outputTensorViews:ee};this.pendingKernels.push(me),this.sessionStatus==="capturing"&&this.capturedPendingKernels.get(this.currentSessionId).push(me)}return this.programManager.run(xe,D,se,he,ue),He(a.name),ee}upload(a,f){this.gpuDataManager.upload(a,f)}memcpy(a,f){this.gpuDataManager.memcpy(a,f)}async download(a,f){await this.gpuDataManager.download(a,f)}alloc(a){return this.gpuDataManager.create(a).id}free(a){return this.gpuDataManager.release(a)}createKernel(a,f,w,T){let A=wh.get(a);if(!A)throw new Error(`kernel not implemented: ${a}`);let P={kernelType:a,kernelName:T,kernelEntry:A[0],attributes:[A[1],w]};this.kernels.set(f,P)}releaseKernel(a){let f=this.kernelPersistentData.get(a);if(f){for(let w of f)this.gpuDataManager.release(w.id);this.kernelPersistentData.delete(a)}this.kernelCustomData.delete(a),this.kernels.delete(a)}computeKernel(a,f,w){let T=this.kernels.get(a);if(!T)throw new Error(`kernel not created: ${a}`);let A=T.kernelType,P=T.kernelName,D=T.kernelEntry,B=T.attributes;if(this.currentKernelId!==null)throw new Error(`kernel "[${A}] ${P}" is not allowed to be called recursively`);this.currentKernelId=a,B[0]&&(B[1]=B[0](B[1]),B[0]=void 0),on("info",()=>`[WebGPU] Start to run kernel "[${A}] ${P}"...`);let q=this.env.debug;this.temporaryData=[];try{return q&&this.device.pushErrorScope("validation"),D(f,B[1]),0}catch(G){return w.push(Promise.resolve(`[WebGPU] Kernel "[${A}] ${P}" failed. ${G}`)),1}finally{q&&w.push(this.device.popErrorScope().then(G=>G?`GPU validation error for kernel "[${A}] ${P}": ${G.message}`:null));for(let G of this.temporaryData)this.gpuDataManager.release(G.id);this.temporaryData=[],this.currentKernelId=null}}registerBuffer(a,f,w,T){let A=this.sessionExternalDataMapping.get(a);A||(A=new Map,this.sessionExternalDataMapping.set(a,A));let P=A.get(f),D=this.gpuDataManager.registerExternalBuffer(w,T,P);return A.set(f,[D,w]),D}unregisterBuffers(a){let f=this.sessionExternalDataMapping.get(a);f&&(f.forEach(w=>this.gpuDataManager.unregisterExternalBuffer(w[0])),this.sessionExternalDataMapping.delete(a))}getBuffer(a){let f=this.gpuDataManager.get(a);if(!f)throw new Error(`no GPU data for buffer: ${a}`);return f.buffer}createDownloader(a,f,w){return async()=>{let T=await Cc(this,a,f);return Et(T.buffer,w)}}writeTimestamp(a){this.queryType==="inside-passes"&&this.computePassEncoder.writeTimestamp(this.querySet,a)}setQueryType(){var a;this.queryType="none",(((a=this.env.webgpu.profiling)==null?void 0:a.mode)==="default"||(typeof this.env.trace>"u"?this.env.wasm.trace:this.env.trace))&&(this.device.features.has("chromium-experimental-timestamp-query-inside-passes")?this.queryType="inside-passes":this.device.features.has("timestamp-query")&&(this.queryType="at-passes"),this.queryType!=="none"&&typeof this.querySet>"u"&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxDispatchNumber*2}),this.queryResolveBuffer=this.device.createBuffer({size:this.maxDispatchNumber*2*8,usage:GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE})))}captureBegin(){on("info","captureBegin"),this.capturedCommandList.get(this.currentSessionId)||this.capturedCommandList.set(this.currentSessionId,[]),this.capturedPendingKernels.get(this.currentSessionId)||this.capturedPendingKernels.set(this.currentSessionId,[]),this.flush(),this.sessionStatus="capturing"}captureEnd(){on("info","captureEnd"),this.flush(),this.sessionStatus="default"}replay(){on("info","replay"),this.sessionStatus="replaying";let a=this.capturedCommandList.get(this.currentSessionId),f=this.capturedPendingKernels.get(this.currentSessionId),w=a.length;this.pendingKernels=[];for(let T=0;T<w;T++){let A=this.getComputePassEncoder(),P=a[T];this.writeTimestamp(this.pendingDispatchNumber*2),A.setPipeline(P.computePipeline),A.setBindGroup(0,P.bindGroup),A.dispatchWorkgroups(...P.dispatchGroup),this.writeTimestamp(this.pendingDispatchNumber*2+1),this.pendingDispatchNumber++,this.queryType!=="none"&&this.pendingKernels.push(f[T]),(this.pendingDispatchNumber>=this.maxDispatchNumber||this.queryType==="at-passes")&&this.endComputePass(),this.pendingDispatchNumber>=this.maxDispatchNumber&&this.flush()}this.flush(),this.sessionStatus="default"}onCreateSession(){this.gpuDataManager.onCreateSession()}onReleaseSession(a){this.unregisterBuffers(a),this.capturedCommandList.has(a)&&this.capturedCommandList.delete(a),this.capturedPendingKernels.has(a)&&this.capturedPendingKernels.delete(a),this.gpuDataManager.onReleaseSession(a)}onRunStart(a){this.currentSessionId=a,this.setQueryType()}}}),kh={};m(kh,{init:()=>yu});var Qa,Sh,yu,tx=h(()=>{Bt(),ds(),Qe(),bl(),Qa=class O2{constructor(f,w,T,A){this.module=f,this.dataType=w,this.data=T,this.dims=A}getFloat32Array(){if(this.dataType!==1)throw new Error("Invalid data type");let f=Ke.size(this.dims);return f===0?new Float32Array:new Float32Array(this.module.HEAP8.buffer,this.data,f)}getBigInt64Array(){if(this.dataType!==7)throw new Error("Invalid data type");let f=Ke.size(this.dims);return f===0?new BigInt64Array:new BigInt64Array(this.module.HEAP8.buffer,this.data,f)}getInt32Array(){if(this.dataType!==6)throw new Error("Invalid data type");let f=Ke.size(this.dims);return f===0?new Int32Array:new Int32Array(this.module.HEAP8.buffer,this.data,f)}getUint16Array(){if(this.dataType!==10&&this.dataType!==4)throw new Error("Invalid data type");let f=Ke.size(this.dims);return f===0?new Uint16Array:new Uint16Array(this.module.HEAP8.buffer,this.data,f)}reshape(f){if(Ke.size(f)!==Ke.size(this.dims))throw new Error("Invalid new shape");return new O2(this.module,this.dataType,this.data,f)}},Sh=class{constructor(a,f,w){this.module=a,this.backend=f,this.customDataOffset=0,this.customDataSize=0,this.adapterInfo=f.adapterInfo;let T=a.PTR_SIZE,A=w/a.PTR_SIZE,P=T===4?"i32":"i64";this.opKernelContext=Number(a.getValue(T*A++,P));let D=Number(a.getValue(T*A++,P));this.outputCount=Number(a.getValue(T*A++,P)),this.customDataOffset=Number(a.getValue(T*A++,"*")),this.customDataSize=Number(a.getValue(T*A++,P));let B=[];for(let q=0;q<D;q++){let G=Number(a.getValue(T*A++,P)),Z=Number(a.getValue(T*A++,"*")),ee=Number(a.getValue(T*A++,P)),se=[];for(let ue=0;ue<ee;ue++)se.push(Number(a.getValue(T*A++,P)));B.push(new Qa(a,G,Z,se))}this.inputs=B}get kernelCustomData(){return this.backend.currentKernelCustomData}get customDataBuffer(){return this.module.HEAPU8.subarray(this.customDataOffset,this.customDataOffset+this.customDataSize)}compute(a,f){var D;let w=((D=f==null?void 0:f.inputs)==null?void 0:D.map(B=>typeof B=="number"?this.inputs[B]:B))??this.inputs,T=(f==null?void 0:f.outputs)??[],A=(B,q,G)=>new Qa(this.module,q,this.output(B,G),G),P=(B,q)=>{let G=Ir(B,q);if(!G)throw new Error(`Unsupported data type: ${B}`);let Z=G>0?this.backend.gpuDataManager.create(G).id:0;return new Qa(this.module,B,Z,q)};return this.backend.run(a,w,T,A,P,this.outputCount)}output(a,f){let w=this.module.stackSave();try{let T=this.module.PTR_SIZE,A=T===4?"i32":"i64",P=this.module.stackAlloc((1+f.length)*T);this.module.setValue(P,f.length,A);for(let D=0;D<f.length;D++)this.module.setValue(P+T*(D+1),f[D],A);return this.module._JsepOutput(this.opKernelContext,a,P)}catch(T){throw new Error(`Failed to generate kernel's output[${a}] with dims [${f}]. If you are running with pre-allocated output, please make sure the output type/dims are correct. Error: ${T}`)}finally{this.module.stackRestore(w)}}},yu=async(a,f,w,T)=>{let A=f.jsepInit;if(!A)throw new Error("Failed to initialize JSEP. The WebAssembly module is not built with JSEP support.");if(a==="webgpu"){let P=(ex(),g(gu)).WebGpuBackend,D=new P;await D.initialize(w,T),A("webgpu",[D,B=>D.alloc(Number(B)),B=>D.free(B),(B,q,G,Z=!1)=>{if(Z)on("verbose",()=>`[WebGPU] jsepCopyGpuToGpu: src=${Number(B)}, dst=${Number(q)}, size=${Number(G)}`),D.memcpy(Number(B),Number(q));else{on("verbose",()=>`[WebGPU] jsepCopyCpuToGpu: dataOffset=${Number(B)}, gpuDataId=${Number(q)}, size=${Number(G)}`);let ee=f.HEAPU8.subarray(Number(B>>>0),Number(B>>>0)+Number(G));D.upload(Number(q),ee)}},async(B,q,G)=>{on("verbose",()=>`[WebGPU] jsepCopyGpuToCpu: gpuDataId=${B}, dataOffset=${q}, size=${G}`),await D.download(Number(B),()=>f.HEAPU8.subarray(Number(q)>>>0,Number(q+G)>>>0))},(B,q,G)=>D.createKernel(B,Number(q),G,f.UTF8ToString(f._JsepGetNodeName(Number(q)))),B=>D.releaseKernel(B),(B,q,G,Z)=>{on("verbose",()=>`[WebGPU] jsepRun: sessionHandle=${G}, kernel=${B}, contextDataOffset=${q}`);let ee=new Sh(f,D,Number(q));return D.computeKernel(Number(B),ee,Z)},()=>D.captureBegin(),()=>D.captureEnd(),()=>D.replay()])}else{let P=new Sc(w);A("webnn",[P,()=>P.reserveTensorId(),D=>P.releaseTensorId(D),async(D,B,q,G,Z)=>P.ensureTensor(D,B,q,G,Z),(D,B)=>{P.uploadTensor(D,B)},async(D,B)=>P.downloadTensor(D,B),(D,B)=>P.registerMLContext(D,B),!!w.trace])}}}),nx,Xl,Lp,pi,rx,Yl,c,p,k,M,F,K,de,_e=h(()=>{nt(),$a(),kn(),Bt(),Hr(),Ui(),Si(),nx=(a,f)=>{zt()._OrtInit(a,f)!==0&&Ct("Can't initialize onnxruntime.")},Xl=async a=>{nx(a.wasm.numThreads,Hi(a.logLevel))},Lp=async(a,f)=>{var T,A;(A=(T=zt()).asyncInit)==null||A.call(T);let w=a.webgpu.adapter;if(f==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(w){if(typeof w.limits!="object"||typeof w.features!="object"||typeof w.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let P=a.webgpu.powerPreference;if(P!==void 0&&P!=="low-power"&&P!=="high-performance")throw new Error(`Invalid powerPreference setting: "${P}"`);let D=a.webgpu.forceFallbackAdapter;if(D!==void 0&&typeof D!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${D}"`);if(w=await navigator.gpu.requestAdapter({powerPreference:P,forceFallbackAdapter:D}),!w)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(f==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment");{let P=(tx(),g(kh)).init;f==="webgpu"&&await P("webgpu",zt(),a,w),f==="webnn"&&await P("webnn",zt(),a)}},pi=new Map,rx=a=>{let f=zt(),w=f.stackSave();try{let T=f.PTR_SIZE,A=f.stackAlloc(2*T);f._OrtGetInputOutputCount(a,A,A+T)!==0&&Ct("Can't get session input/output count.");let P=T===4?"i32":"i64";return[Number(f.getValue(A,P)),Number(f.getValue(A+T,P))]}finally{f.stackRestore(w)}},Yl=(a,f)=>{let w=zt(),T=w.stackSave(),A=0;try{let P=w.PTR_SIZE,D=w.stackAlloc(2*P);w._OrtGetInputOutputMetadata(a,f,D,D+P)!==0&&Ct("Can't get session input/output metadata.");let B=Number(w.getValue(D,"*"));A=Number(w.getValue(D+P,"*"));let q=w.HEAP32[A/4];if(q===0)return[B,0];let G=w.HEAPU32[A/4+1],Z=[];for(let ee=0;ee<G;ee++){let se=Number(w.getValue(A+8+ee*P,"*"));Z.push(se!==0?w.UTF8ToString(se):Number(w.getValue(A+8+(ee+G)*P,"*")))}return[B,q,Z]}finally{w.stackRestore(T),A!==0&&w._OrtFree(A)}},c=a=>{let f=zt(),w=f._malloc(a.byteLength);if(w===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${a.byteLength}.`);return f.HEAPU8.set(a,w),[w,a.byteLength]},p=async(a,f)=>{var ee,se,ue,he;let w,T,A=zt();Array.isArray(a)?[w,T]=a:a.buffer===A.HEAPU8.buffer?[w,T]=[a.byteOffset,a.byteLength]:[w,T]=c(a);let P=0,D=0,B=0,q=[],G=[],Z=[];try{if([D,q]=await Ra(f),(f==null?void 0:f.externalData)&&A.mountExternalData){let Ze=[];for(let rt of f.externalData){let gt=typeof rt=="string"?rt:rt.path;Ze.push(Gn(typeof rt=="string"?rt:rt.data).then(qt=>{A.mountExternalData(gt,qt)}))}await Promise.all(Ze)}for(let Ze of(f==null?void 0:f.executionProviders)??[])if((typeof Ze=="string"?Ze:Ze.name)==="webnn"){if(A.shouldTransferToMLTensor=!1,typeof Ze!="string"){let rt=Ze,gt=rt==null?void 0:rt.context,qt=rt==null?void 0:rt.gpuDevice,Ut=rt==null?void 0:rt.deviceType,Ht=rt==null?void 0:rt.powerPreference;gt?A.currentContext=gt:qt?A.currentContext=await A.webnnCreateMLContext(qt):A.currentContext=await A.webnnCreateMLContext({deviceType:Ut,powerPreference:Ht})}else A.currentContext=await A.webnnCreateMLContext();break}P=await A._OrtCreateSession(w,T,D),(ee=A.webgpuOnCreateSession)==null||ee.call(A,P),P===0&&Ct("Can't create a session."),(se=A.jsepOnCreateSession)==null||se.call(A),A.currentContext&&(A.webnnRegisterMLContext(P,A.currentContext),A.currentContext=void 0,A.shouldTransferToMLTensor=!0);let[ge,ke]=rx(P),xe=!!(f!=null&&f.enableGraphCapture),me=[],Ee=[],je=[],Oe=[],Ge=[];for(let Ze=0;Ze<ge;Ze++){let[rt,gt,qt]=Yl(P,Ze);rt===0&&Ct("Can't get an input name."),G.push(rt);let Ut=A.UTF8ToString(rt);me.push(Ut),je.push(gt===0?{name:Ut,isTensor:!1}:{name:Ut,isTensor:!0,type:Vn(gt),shape:qt})}for(let Ze=0;Ze<ke;Ze++){let[rt,gt,qt]=Yl(P,Ze+ge);rt===0&&Ct("Can't get an output name."),Z.push(rt);let Ut=A.UTF8ToString(rt);Ee.push(Ut),Oe.push(gt===0?{name:Ut,isTensor:!1}:{name:Ut,isTensor:!0,type:Vn(gt),shape:qt});{if(xe&&(f==null?void 0:f.preferredOutputLocation)===void 0){Ge.push("gpu-buffer");continue}let Ht=typeof(f==null?void 0:f.preferredOutputLocation)=="string"?f.preferredOutputLocation:((ue=f==null?void 0:f.preferredOutputLocation)==null?void 0:ue[Ut])??"cpu",fn=A.webnnIsGraphOutput;if(Ht==="cpu"&&fn&&fn(P,Ut)){Ge.push("ml-tensor-cpu-output");continue}if(Ht!=="cpu"&&Ht!=="cpu-pinned"&&Ht!=="gpu-buffer"&&Ht!=="ml-tensor")throw new Error(`Not supported preferred output location: ${Ht}.`);if(xe&&Ht!=="gpu-buffer")throw new Error(`Not supported preferred output location: ${Ht}. Only 'gpu-buffer' location is supported when enableGraphCapture is true.`);Ge.push(Ht)}}let We=null;return Ge.some(Ze=>Ze==="gpu-buffer"||Ze==="ml-tensor"||Ze==="ml-tensor-cpu-output")&&(B=A._OrtCreateBinding(P),B===0&&Ct("Can't create IO binding."),We={handle:B,outputPreferredLocations:Ge,outputPreferredLocationsEncoded:Ge.map(Ze=>Ze==="ml-tensor-cpu-output"?"ml-tensor":Ze).map(Ze=>gr(Ze))}),pi.set(P,[P,G,Z,We,xe,!1]),[P,me,Ee,je,Oe]}catch(ge){throw G.forEach(ke=>A._OrtFree(ke)),Z.forEach(ke=>A._OrtFree(ke)),B!==0&&A._OrtReleaseBinding(B)!==0&&Ct("Can't release IO binding."),P!==0&&A._OrtReleaseSession(P)!==0&&Ct("Can't release session."),ge}finally{A._free(w),D!==0&&A._OrtReleaseSessionOptions(D)!==0&&Ct("Can't release session options."),q.forEach(ge=>A._free(ge)),(he=A.unmountExternalData)==null||he.call(A)}},k=a=>{var q,G,Z;let f=zt(),w=pi.get(a);if(!w)throw new Error(`cannot release session. invalid session id: ${a}`);let[T,A,P,D,B]=w;D&&(B&&f._OrtClearBoundOutputs(D.handle)!==0&&Ct("Can't clear bound outputs."),f._OrtReleaseBinding(D.handle)!==0&&Ct("Can't release IO binding.")),(q=f.jsepOnReleaseSession)==null||q.call(f,a),(G=f.webnnOnReleaseSession)==null||G.call(f,a),(Z=f.webgpuOnReleaseSession)==null||Z.call(f,a),A.forEach(ee=>f._OrtFree(ee)),P.forEach(ee=>f._OrtFree(ee)),f._OrtReleaseSession(T)!==0&&Ct("Can't release session."),pi.delete(a)},M=async(a,f,w,T,A,P,D=!1)=>{if(!a){f.push(0);return}let B=zt(),q=B.PTR_SIZE,G=a[0],Z=a[1],ee=a[3],se=ee,ue,he;if(G==="string"&&(ee==="gpu-buffer"||ee==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(D&&ee!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${P} when enableGraphCapture is true.`);if(ee==="gpu-buffer"){let xe=a[2].gpuBuffer;he=Ir(Mr(G),Z);{let me=B.jsepRegisterBuffer;if(!me)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');ue=me(T,P,xe,he)}}else if(ee==="ml-tensor"){let xe=a[2].mlTensor;he=Ir(Mr(G),Z);let me=B.webnnRegisterMLTensor;if(!me)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');ue=me(T,xe,Mr(G),Z)}else{let xe=a[2];if(Array.isArray(xe)){he=q*xe.length,ue=B._malloc(he),w.push(ue);for(let me=0;me<xe.length;me++){if(typeof xe[me]!="string")throw new TypeError(`tensor data at index ${me} is not a string`);B.setValue(ue+me*q,Hn(xe[me],w),"*")}}else{let me=B.webnnIsGraphInput,Ee=B.webnnIsGraphOutput;if(G!=="string"&&me&&Ee){let je=B.UTF8ToString(A);if(me(T,je)||Ee(T,je)){let Oe=Mr(G);he=Ir(Oe,Z),se="ml-tensor";let Ge=B.webnnCreateTemporaryTensor,We=B.webnnUploadTensor;if(!Ge||!We)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Ze=await Ge(T,Oe,Z);We(Ze,new Uint8Array(xe.buffer,xe.byteOffset,xe.byteLength)),ue=Ze}else he=xe.byteLength,ue=B._malloc(he),w.push(ue),B.HEAPU8.set(new Uint8Array(xe.buffer,xe.byteOffset,he),ue)}else he=xe.byteLength,ue=B._malloc(he),w.push(ue),B.HEAPU8.set(new Uint8Array(xe.buffer,xe.byteOffset,he),ue)}}let ge=B.stackSave(),ke=B.stackAlloc(4*Z.length);try{Z.forEach((me,Ee)=>B.setValue(ke+Ee*q,me,q===4?"i32":"i64"));let xe=B._OrtCreateTensor(Mr(G),ue,he,ke,Z.length,gr(se));xe===0&&Ct(`Can't create tensor for input/output. session=${T}, index=${P}.`),f.push(xe)}finally{B.stackRestore(ge)}},F=async(a,f,w,T,A,P)=>{var Ut,Ht,fn,xn;let D=zt(),B=D.PTR_SIZE,q=pi.get(a);if(!q)throw new Error(`cannot run inference. invalid session id: ${a}`);let G=q[0],Z=q[1],ee=q[2],se=q[3],ue=q[4],he=q[5],ge=f.length,ke=T.length,xe=0,me=[],Ee=[],je=[],Oe=[],Ge=[],We=D.stackSave(),Ze=D.stackAlloc(ge*B),rt=D.stackAlloc(ge*B),gt=D.stackAlloc(ke*B),qt=D.stackAlloc(ke*B);try{[xe,me]=fo(P),vt("wasm prepareInputOutputTensor");for(let wt=0;wt<ge;wt++)await M(w[wt],Ee,Oe,a,Z[f[wt]],f[wt],ue);for(let wt=0;wt<ke;wt++)await M(A[wt],je,Oe,a,ee[T[wt]],ge+T[wt],ue);st("wasm prepareInputOutputTensor");for(let wt=0;wt<ge;wt++)D.setValue(Ze+wt*B,Ee[wt],"*"),D.setValue(rt+wt*B,Z[f[wt]],"*");for(let wt=0;wt<ke;wt++)D.setValue(gt+wt*B,je[wt],"*"),D.setValue(qt+wt*B,ee[T[wt]],"*");if(se&&!he){let{handle:wt,outputPreferredLocations:bn,outputPreferredLocationsEncoded:pt}=se;if(Z.length!==ge)throw new Error(`input count from feeds (${ge}) is expected to be always equal to model's input count (${Z.length}).`);vt("wasm bindInputsOutputs");for(let Nt=0;Nt<ge;Nt++){let Lt=f[Nt];await D._OrtBindInput(wt,Z[Lt],Ee[Nt])!==0&&Ct(`Can't bind input[${Nt}] for session=${a}.`)}for(let Nt=0;Nt<ke;Nt++){let Lt=T[Nt];(Ut=A[Nt])!=null&&Ut[3]?(Ge.push(je[Nt]),D._OrtBindOutput(wt,ee[Lt],je[Nt],0)!==0&&Ct(`Can't bind pre-allocated output[${Nt}] for session=${a}.`)):D._OrtBindOutput(wt,ee[Lt],0,pt[Lt])!==0&&Ct(`Can't bind output[${Nt}] to ${bn[Nt]} for session=${a}.`)}st("wasm bindInputsOutputs"),pi.set(a,[G,Z,ee,se,ue,!0])}(Ht=D.jsepOnRunStart)==null||Ht.call(D,G),(fn=D.webnnOnRunStart)==null||fn.call(D,G);let Wt;se?Wt=await D._OrtRunWithBinding(G,se.handle,ke,gt,xe):Wt=await D._OrtRun(G,rt,Ze,ge,qt,ke,gt,xe),Wt!==0&&Ct("failed to call OrtRun().");let Zt=[],_r=[];vt("wasm ProcessOutputTensor");for(let wt=0;wt<ke;wt++){let bn=Number(D.getValue(gt+wt*B,"*"));if(bn===je[wt]||Ge.includes(je[wt])){Zt.push(A[wt]),bn!==je[wt]&&D._OrtReleaseTensor(bn)!==0&&Ct("Can't release tensor.");continue}let pt=D.stackSave(),Nt=D.stackAlloc(4*B),Lt=!1,_t,Dn=0;try{D._OrtGetTensorData(bn,Nt,Nt+B,Nt+2*B,Nt+3*B)!==0&&Ct(`Can't access output tensor data on index ${wt}.`);let Za=B===4?"i32":"i64",ws=Number(D.getValue(Nt,Za));Dn=D.getValue(Nt+B,"*");let Io=D.getValue(Nt+B*2,"*"),Po=Number(D.getValue(Nt+B*3,Za)),Jl=[];for(let ts=0;ts<Po;ts++)Jl.push(Number(D.getValue(Io+ts*B,Za)));D._OrtFree(Io)!==0&&Ct("Can't free memory for tensor dims.");let Ql=Jl.reduce((ts,kr)=>ts*kr,1);_t=Vn(ws);let zp=se==null?void 0:se.outputPreferredLocations[T[wt]];if(_t==="string"){if(zp==="gpu-buffer"||zp==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let ts=[];for(let kr=0;kr<Ql;kr++){let el=D.getValue(Dn+kr*B,"*"),xN=D.getValue(Dn+(kr+1)*B,"*"),yN=kr===Ql-1?void 0:xN-el;ts.push(D.UTF8ToString(el,yN))}Zt.push([_t,Jl,ts,"cpu"])}else if(zp==="gpu-buffer"&&Ql>0){let ts=D.jsepGetBuffer;if(!ts)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let kr=ts(Dn),el=Ir(ws,Ql);if(el===void 0||!ki(_t))throw new Error(`Unsupported data type: ${_t}`);Lt=!0,Zt.push([_t,Jl,{gpuBuffer:kr,download:D.jsepCreateDownloader(kr,el,_t),dispose:()=>{D._OrtReleaseTensor(bn)!==0&&Ct("Can't release tensor.")}},"gpu-buffer"])}else if(zp==="ml-tensor"&&Ql>0){let ts=D.webnnEnsureTensor,kr=D.webnnIsGraphInputOutputTypeSupported;if(!ts||!kr)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ir(ws,Ql)===void 0||!cs(_t))throw new Error(`Unsupported data type: ${_t}`);if(!kr(a,_t,!1))throw new Error(`preferredLocation "ml-tensor" for ${_t} output is not supported by current WebNN Context.`);let el=await ts(a,Dn,ws,Jl,!1);Lt=!0,Zt.push([_t,Jl,{mlTensor:el,download:D.webnnCreateMLTensorDownloader(Dn,_t),dispose:()=>{D.webnnReleaseTensorId(Dn),D._OrtReleaseTensor(bn)}},"ml-tensor"])}else if(zp==="ml-tensor-cpu-output"&&Ql>0){let ts=D.webnnCreateMLTensorDownloader(Dn,_t)(),kr=Zt.length;Lt=!0,_r.push((async()=>{let el=[kr,await ts];return D.webnnReleaseTensorId(Dn),D._OrtReleaseTensor(bn),el})()),Zt.push([_t,Jl,[],"cpu"])}else{let ts=ni(_t),kr=new ts(Ql);new Uint8Array(kr.buffer,kr.byteOffset,kr.byteLength).set(D.HEAPU8.subarray(Dn,Dn+kr.byteLength)),Zt.push([_t,Jl,kr,"cpu"])}}finally{D.stackRestore(pt),_t==="string"&&Dn&&D._free(Dn),Lt||D._OrtReleaseTensor(bn)}}se&&!ue&&(D._OrtClearBoundOutputs(se.handle)!==0&&Ct("Can't clear bound outputs."),pi.set(a,[G,Z,ee,se,ue,!1]));for(let[wt,bn]of await Promise.all(_r))Zt[wt][2]=bn;return st("wasm ProcessOutputTensor"),Zt}finally{(xn=D.webnnOnRunEnd)==null||xn.call(D,G),D.stackRestore(We),Ee.forEach(Wt=>D._OrtReleaseTensor(Wt)),je.forEach(Wt=>D._OrtReleaseTensor(Wt)),Oe.forEach(Wt=>D._free(Wt)),xe!==0&&D._OrtReleaseRunOptions(xe),me.forEach(Wt=>D._free(Wt))}},K=a=>{let f=zt(),w=pi.get(a);if(!w)throw new Error("invalid session id");let T=w[0],A=f._OrtEndProfiling(T);A===0&&Ct("Can't get an profile file name."),f._OrtFree(A)},de=a=>{let f=[];for(let w of a){let T=w[2];!Array.isArray(T)&&"buffer"in T&&f.push(T.buffer)}return f}}),$e,qe,at,ct,ot,jt,Pt,Dt,Pn,Ue,Ie,Ve,ht,Ft,Xt,Yt,rn,wr,vn=h(()=>{nt(),_e(),Hr(),Ur(),$e=()=>!!I.wasm.proxy&&typeof document<"u",at=!1,ct=!1,ot=!1,Dt=new Map,Pn=(a,f)=>{let w=Dt.get(a);w?w.push(f):Dt.set(a,[f])},Ue=()=>{if(at||!ct||ot||!qe)throw new Error("worker not ready")},Ie=a=>{switch(a.data.type){case"init-wasm":at=!1,a.data.err?(ot=!0,Pt[1](a.data.err)):(ct=!0,Pt[0]()),jt&&(URL.revokeObjectURL(jt),jt=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let f=Dt.get(a.data.type);a.data.err?f.shift()[1](a.data.err):f.shift()[0](a.data.out);break}}},Ve=async()=>{if(!ct){if(at)throw new Error("multiple calls to 'initWasm()' detected.");if(ot)throw new Error("previous call to 'initWasm()' failed.");if(at=!0,$e())return new Promise((a,f)=>{qe==null||qe.terminate(),_i().then(([w,T])=>{try{qe=T,qe.onerror=P=>f(P),qe.onmessage=Ie,Pt=[a,f];let A={type:"init-wasm",in:I};if(!A.in.wasm.wasmPaths&&w){let P=Fr();P&&(A.in.wasm.wasmPaths=P)}qe.postMessage(A),jt=w}catch(A){f(A)}},f)});try{await ti(I.wasm),await Xl(I),ct=!0}catch(a){throw ot=!0,a}finally{at=!1}}},ht=async a=>{if($e())return Ue(),new Promise((f,w)=>{Pn("init-ep",[f,w]);let T={type:"init-ep",in:{epName:a,env:I}};qe.postMessage(T)});await Lp(I,a)},Ft=async a=>$e()?(Ue(),new Promise((f,w)=>{Pn("copy-from",[f,w]);let T={type:"copy-from",in:{buffer:a}};qe.postMessage(T,[a.buffer])})):c(a),Xt=async(a,f)=>{if($e()){if(f!=null&&f.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return Ue(),new Promise((w,T)=>{Pn("create",[w,T]);let A={type:"create",in:{model:a,options:{...f}}},P=[];a instanceof Uint8Array&&P.push(a.buffer),qe.postMessage(A,P)})}else return p(a,f)},Yt=async a=>{if($e())return Ue(),new Promise((f,w)=>{Pn("release",[f,w]);let T={type:"release",in:a};qe.postMessage(T)});k(a)},rn=async(a,f,w,T,A,P)=>{if($e()){if(w.some(D=>D[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(A.some(D=>D))throw new Error("pre-allocated output tensor is not supported for proxy.");return Ue(),new Promise((D,B)=>{Pn("run",[D,B]);let q=w,G={type:"run",in:{sessionId:a,inputIndices:f,inputs:q,outputIndices:T,options:P}};qe.postMessage(G,de(q))})}else return F(a,f,w,T,A,P)},wr=async a=>{if($e())return Ue(),new Promise((f,w)=>{Pn("end-profiling",[f,w]);let T={type:"end-profiling",in:a};qe.postMessage(T)});K(a)}}),eo,sx,q0,fN=h(()=>{nt(),vn(),Bt(),St(),Si(),eo=(a,f)=>{switch(a.location){case"cpu":return[a.type,a.dims,a.data,"cpu"];case"gpu-buffer":return[a.type,a.dims,{gpuBuffer:a.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[a.type,a.dims,{mlTensor:a.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${a.location} for ${f()}`)}},sx=a=>{switch(a[3]){case"cpu":return new Ne(a[0],a[2],a[1]);case"gpu-buffer":{let f=a[0];if(!ki(f))throw new Error(`not supported data type: ${f} for deserializing GPU tensor`);let{gpuBuffer:w,download:T,dispose:A}=a[2];return Ne.fromGpuBuffer(w,{dataType:f,dims:a[1],download:T,dispose:A})}case"ml-tensor":{let f=a[0];if(!cs(f))throw new Error(`not supported data type: ${f} for deserializing MLTensor tensor`);let{mlTensor:w,download:T,dispose:A}=a[2];return Ne.fromMLTensor(w,{dataType:f,dims:a[1],download:T,dispose:A})}default:throw new Error(`invalid data location: ${a[3]}`)}},q0=class{async fetchModelAndCopyToWasmMemory(a){return Ft(await Gn(a))}async loadModel(a,f){Rt();let w;typeof a=="string"?w=await this.fetchModelAndCopyToWasmMemory(a):w=a,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await Xt(w,f),He()}async dispose(){return Yt(this.sessionId)}async run(a,f,w){Rt();let T=[],A=[];Object.entries(a).forEach(ee=>{let se=ee[0],ue=ee[1],he=this.inputNames.indexOf(se);if(he===-1)throw new Error(`invalid input '${se}'`);T.push(ue),A.push(he)});let P=[],D=[];Object.entries(f).forEach(ee=>{let se=ee[0],ue=ee[1],he=this.outputNames.indexOf(se);if(he===-1)throw new Error(`invalid output '${se}'`);P.push(ue),D.push(he)});let B=T.map((ee,se)=>eo(ee,()=>`input "${this.inputNames[A[se]]}"`)),q=P.map((ee,se)=>ee?eo(ee,()=>`output "${this.outputNames[D[se]]}"`):null),G=await rn(this.sessionId,A,B,D,q,w),Z={};for(let ee=0;ee<G.length;ee++)Z[this.outputNames[D[ee]]]=P[ee]??sx(G[ee]);return He(),Z}startProfiling(){}endProfiling(){wr(this.sessionId)}}}),V0={};m(V0,{OnnxruntimeWebAssemblyBackend:()=>_v,initializeFlags:()=>wv,wasmBackend:()=>G0});var wv,_v,G0,pN=h(()=>{nt(),vn(),fN(),wv=()=>{(typeof I.wasm.initTimeout!="number"||I.wasm.initTimeout<0)&&(I.wasm.initTimeout=0);let a=I.wasm.simd;if(typeof a!="boolean"&&a!==void 0&&a!=="fixed"&&a!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${a}". Reset it to \`false\` and ignore SIMD feature checking.`),I.wasm.simd=!1),typeof I.wasm.proxy!="boolean"&&(I.wasm.proxy=!1),typeof I.wasm.trace!="boolean"&&(I.wasm.trace=!1),typeof I.wasm.numThreads!="number"||!Number.isInteger(I.wasm.numThreads)||I.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)I.wasm.numThreads=1;else{let f=typeof navigator>"u"?u("node:os").cpus().length:navigator.hardwareConcurrency;I.wasm.numThreads=Math.min(4,Math.ceil((f||1)/2))}},_v=class{async init(a){wv(),await Ve(),await ht(a)}async createInferenceSessionHandler(a,f){let w=new q0;return await w.loadModel(a,f),w}},G0=new _v}),K0={};m(K0,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>vt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,default:()=>gN,env:()=>I,registerBackend:()=>E}),nt(),nt(),nt();var mN="1.26.0",gN=Tr;{let a=(pN(),g(V0)).wasmBackend;E("webgpu",a,5),E("webnn",a,5),E("cpu",a,10),E("wasm",a,10)}return Object.defineProperty(I.versions,"web",{value:mN,enumerable:!0}),g(K0)})();/**
|
|
2849
2849
|
* @license
|
|
2850
2850
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
2851
2851
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
@@ -2894,7 +2894,7 @@ ${P}`,B=w.createShaderModule({code:D,label:a.name});on("verbose",()=>`[WebGPU] $
|
|
|
2894
2894
|
* ONNX Runtime Web v1.26.0
|
|
2895
2895
|
* Copyright (c) Microsoft Corporation. All rights reserved.
|
|
2896
2896
|
* Licensed under the MIT License.
|
|
2897
|
-
*/var I_;function hT(){return I_||(I_=1,(function(e,n){var r=(()=>{var i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,u=(re=>typeof oo<"u"?oo:typeof Proxy<"u"?new Proxy(re,{get:(fe,ve)=>(typeof oo<"u"?oo:fe)[ve]}):re)(function(re){if(typeof oo<"u")return oo.apply(this,arguments);throw Error('Dynamic require of "'+re+'" is not supported')}),h=(re,fe)=>()=>(re&&(fe=re(re=0)),fe),m=(re,fe)=>{for(var ve in fe)i(re,ve,{get:fe[ve],enumerable:!0})},x=(re,fe,ve,Te)=>{if(fe&&typeof fe=="object"||typeof fe=="function")for(let Ce of l(fe))!d.call(re,Ce)&&Ce!==ve&&i(re,Ce,{get:()=>fe[Ce],enumerable:!(Te=o(fe,Ce))||Te.enumerable});return re},g=re=>x(i({},"__esModule",{value:!0}),re),v,S,E,j,y,b=h(()=>{v=new Map,S=[],E=(re,fe,ve)=>{if(fe&&typeof fe.init=="function"&&typeof fe.createInferenceSessionHandler=="function"){let Te=v.get(re);if(Te===void 0)v.set(re,{backend:fe,priority:ve});else{if(Te.priority>ve)return;if(Te.priority===ve&&Te.backend!==fe)throw new Error(`cannot register backend "${re}" using priority ${ve}`)}if(ve>=0){let Ce=S.indexOf(re);Ce!==-1&&S.splice(Ce,1);for(let Be=0;Be<S.length;Be++)if(v.get(S[Be]).priority<=ve){S.splice(Be,0,re);return}S.push(re)}return}throw new TypeError("not a valid backend")},j=async re=>{let fe=v.get(re);if(!fe)return"backend not found.";if(fe.initialized)return fe.backend;if(fe.aborted)return fe.error;{let ve=!!fe.initPromise;try{return ve||(fe.initPromise=fe.backend.init(re)),await fe.initPromise,fe.initialized=!0,fe.backend}catch(Te){return ve||(fe.error=`${Te}`,fe.aborted=!0),fe.error}finally{delete fe.initPromise}}},y=async re=>{let fe=re.executionProviders||[],ve=fe.map(Fe=>typeof Fe=="string"?Fe:Fe.name),Te=ve.length===0?S:ve,Ce,Be=[],Re=new Set;for(let Fe of Te){let et=await j(Fe);typeof et=="string"?Be.push({name:Fe,err:et}):(Ce||(Ce=et),Ce===et&&Re.add(Fe))}if(!Ce)throw new Error(`no available backend found. ERR: ${Be.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:et}of Be)ve.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${et}`);let Me=fe.filter(Fe=>Re.has(typeof Fe=="string"?Fe:Fe.name));return[Ce,new Proxy(re,{get:(Fe,et)=>et==="executionProviders"?Me:Reflect.get(Fe,et)})]}}),_=h(()=>{b()}),C,N=h(()=>{C="1.26.0"}),$,R,O=h(()=>{N(),$="warning",R={wasm:{},webgl:{},webgpu:{},versions:{common:C},set logLevel(re){if(re!==void 0){if(typeof re!="string"||["verbose","info","warning","error","fatal"].indexOf(re)===-1)throw new Error(`Unsupported logging level: ${re}`);$=re}},get logLevel(){return $}},Object.defineProperty(R,"logLevel",{enumerable:!0})}),I,z=h(()=>{O(),I=R}),U,W,Y=h(()=>{U=(re,fe)=>{let ve=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);ve.width=re.dims[3],ve.height=re.dims[2];let Te=ve.getContext("2d");if(Te!=null){let Ce,Be;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ce=re.dims[2],Be=re.dims[3]):(Ce=re.dims[3],Be=re.dims[2]);let Re=(fe==null?void 0:fe.format)!==void 0?fe.format:"RGB",Me=fe==null?void 0:fe.norm,Fe,et;Me===void 0||Me.mean===void 0?Fe=[255,255,255,255]:typeof Me.mean=="number"?Fe=[Me.mean,Me.mean,Me.mean,Me.mean]:(Fe=[Me.mean[0],Me.mean[1],Me.mean[2],0],Me.mean[3]!==void 0&&(Fe[3]=Me.mean[3])),Me===void 0||Me.bias===void 0?et=[0,0,0,0]:typeof Me.bias=="number"?et=[Me.bias,Me.bias,Me.bias,Me.bias]:(et=[Me.bias[0],Me.bias[1],Me.bias[2],0],Me.bias[3]!==void 0&&(et[3]=Me.bias[3]));let it=Be*Ce,tt=0,Xe=it,At=it*2,ze=-1;Re==="RGBA"?(tt=0,Xe=it,At=it*2,ze=it*3):Re==="RGB"?(tt=0,Xe=it,At=it*2):Re==="RBG"&&(tt=0,At=it,Xe=it*2);for(let ut=0;ut<Be;ut++)for(let Cn=0;Cn<Ce;Cn++){let Jt=(re.data[tt++]-et[0])*Fe[0],Qt=(re.data[Xe++]-et[1])*Fe[1],jn=(re.data[At++]-et[2])*Fe[2],Ot=ze===-1?255:(re.data[ze++]-et[3])*Fe[3];Te.fillStyle="rgba("+Jt+","+Qt+","+jn+","+Ot+")",Te.fillRect(Cn,ut,1,1)}if("toDataURL"in ve)return ve.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},W=(re,fe)=>{let ve=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Te;if(ve!=null){let Ce,Be,Re;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ce=re.dims[2],Be=re.dims[1],Re=re.dims[3]):(Ce=re.dims[3],Be=re.dims[2],Re=re.dims[1]);let Me=fe!==void 0&&fe.format!==void 0?fe.format:"RGB",Fe=fe==null?void 0:fe.norm,et,it;Fe===void 0||Fe.mean===void 0?et=[255,255,255,255]:typeof Fe.mean=="number"?et=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(et=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(et[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?it=[0,0,0,0]:typeof Fe.bias=="number"?it=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(it=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(it[3]=Fe.bias[3]));let tt=Be*Ce;if(fe!==void 0&&(fe.format!==void 0&&Re===4&&fe.format!=="RGBA"||Re===3&&fe.format!=="RGB"&&fe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,At=0,ze=1,ut=2,Cn=3,Jt=0,Qt=tt,jn=tt*2,Ot=-1;Me==="RGBA"?(Jt=0,Qt=tt,jn=tt*2,Ot=tt*3):Me==="RGB"?(Jt=0,Qt=tt,jn=tt*2):Me==="RBG"&&(Jt=0,jn=tt,Qt=tt*2),Te=ve.createImageData(Ce,Be);for(let Mn=0;Mn<Be*Ce;At+=Xe,ze+=Xe,ut+=Xe,Cn+=Xe,Mn++)Te.data[At]=(re.data[Jt++]-it[0])*et[0],Te.data[ze]=(re.data[Qt++]-it[1])*et[1],Te.data[ut]=(re.data[jn++]-it[2])*et[2],Te.data[Cn]=Ot===-1?255:(re.data[Ot++]-it[3])*et[3]}else throw new Error("Can not access image data");return Te}}),V,H,te,ae,oe,ie,X=h(()=>{we(),V=(re,fe)=>{if(re===void 0)throw new Error("Image buffer must be defined");if(fe.height===void 0||fe.width===void 0)throw new Error("Image height and width must be defined");if(fe.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:ve,width:Te}=fe,Ce=fe.norm??{mean:255,bias:0},Be,Re;typeof Ce.mean=="number"?Be=[Ce.mean,Ce.mean,Ce.mean,Ce.mean]:Be=[Ce.mean[0],Ce.mean[1],Ce.mean[2],Ce.mean[3]??255],typeof Ce.bias=="number"?Re=[Ce.bias,Ce.bias,Ce.bias,Ce.bias]:Re=[Ce.bias[0],Ce.bias[1],Ce.bias[2],Ce.bias[3]??0];let Me=fe.format!==void 0?fe.format:"RGBA",Fe=fe.tensorFormat!==void 0&&fe.tensorFormat!==void 0?fe.tensorFormat:"RGB",et=ve*Te,it=Fe==="RGBA"?new Float32Array(et*4):new Float32Array(et*3),tt=4,Xe=0,At=1,ze=2,ut=3,Cn=0,Jt=et,Qt=et*2,jn=-1;Me==="RGB"&&(tt=3,Xe=0,At=1,ze=2,ut=-1),Fe==="RGBA"?jn=et*3:Fe==="RBG"?(Cn=0,Qt=et,Jt=et*2):Fe==="BGR"&&(Qt=0,Jt=et,Cn=et*2);for(let Ot=0;Ot<et;Ot++,Xe+=tt,ze+=tt,At+=tt,ut+=tt)it[Cn++]=(re[Xe]+Re[0])/Be[0],it[Jt++]=(re[At]+Re[1])/Be[1],it[Qt++]=(re[ze]+Re[2])/Be[2],jn!==-1&&ut!==-1&&(it[jn++]=(re[ut]+Re[3])/Be[3]);return Fe==="RGBA"?new ne("float32",it,[1,4,ve,Te]):new ne("float32",it,[1,3,ve,Te])},H=async(re,fe)=>{let ve=typeof HTMLImageElement<"u"&&re instanceof HTMLImageElement,Te=typeof ImageData<"u"&&re instanceof ImageData,Ce=typeof ImageBitmap<"u"&&re instanceof ImageBitmap,Be=typeof re=="string",Re,Me=fe??{},Fe=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},et=it=>typeof HTMLCanvasElement<"u"&&it instanceof HTMLCanvasElement||it instanceof OffscreenCanvas?it.getContext("2d"):null;if(ve){let it=Fe();it.width=re.width,it.height=re.height;let tt=et(it);if(tt!=null){let Xe=re.height,At=re.width;if(fe!==void 0&&fe.resizedHeight!==void 0&&fe.resizedWidth!==void 0&&(Xe=fe.resizedHeight,At=fe.resizedWidth),fe!==void 0){if(Me=fe,fe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Me.tensorFormat="RGBA",Me.height=Xe,Me.width=At}else Me.tensorFormat="RGBA",Me.height=Xe,Me.width=At;tt.drawImage(re,0,0),Re=tt.getImageData(0,0,At,Xe).data}else throw new Error("Can not access image data")}else if(Te){let it,tt;if(fe!==void 0&&fe.resizedWidth!==void 0&&fe.resizedHeight!==void 0?(it=fe.resizedHeight,tt=fe.resizedWidth):(it=re.height,tt=re.width),fe!==void 0&&(Me=fe),Me.format="RGBA",Me.height=it,Me.width=tt,fe!==void 0){let Xe=Fe();Xe.width=tt,Xe.height=it;let At=et(Xe);if(At!=null)At.putImageData(re,0,0),Re=At.getImageData(0,0,tt,it).data;else throw new Error("Can not access image data")}else Re=re.data}else if(Ce){if(fe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let it=Fe();it.width=re.width,it.height=re.height;let tt=et(it);if(tt!=null){let Xe=re.height,At=re.width;return tt.drawImage(re,0,0,At,Xe),Re=tt.getImageData(0,0,At,Xe).data,Me.height=Xe,Me.width=At,V(Re,Me)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((it,tt)=>{let Xe=Fe(),At=et(Xe);if(!re||!At)return tt();let ze=new Image;ze.crossOrigin="Anonymous",ze.src=re,ze.onload=()=>{Xe.width=ze.width,Xe.height=ze.height,At.drawImage(ze,0,0,Xe.width,Xe.height);let ut=At.getImageData(0,0,Xe.width,Xe.height);Me.height=Xe.height,Me.width=Xe.width,it(V(ut.data,Me))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Re!==void 0)return V(Re,Me);throw new Error("Input data provided is not supported - aborted tensor creation")},te=(re,fe)=>{let{width:ve,height:Te,download:Ce,dispose:Be}=fe,Re=[1,Te,ve,4];return new ne({location:"texture",type:"float32",texture:re,dims:Re,download:Ce,dispose:Be})},ae=(re,fe)=>{let{dataType:ve,dims:Te,download:Ce,dispose:Be}=fe;return new ne({location:"gpu-buffer",type:ve??"float32",gpuBuffer:re,dims:Te,download:Ce,dispose:Be})},oe=(re,fe)=>{let{dataType:ve,dims:Te,download:Ce,dispose:Be}=fe;return new ne({location:"ml-tensor",type:ve??"float32",mlTensor:re,dims:Te,download:Ce,dispose:Be})},ie=(re,fe,ve)=>new ne({location:"cpu-pinned",type:re,data:fe,dims:ve??[fe.length]})}),Q,J,le,ce,pe=h(()=>{Q=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),J=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),le=!1,ce=()=>{if(!le){le=!0;let re=typeof BigInt64Array<"u"&&BigInt64Array.from,fe=typeof BigUint64Array<"u"&&BigUint64Array.from,ve=globalThis.Float16Array,Te=typeof ve<"u"&&ve.from;re&&(Q.set("int64",BigInt64Array),J.set(BigInt64Array,"int64")),fe&&(Q.set("uint64",BigUint64Array),J.set(BigUint64Array,"uint64")),Te?(Q.set("float16",ve),J.set(ve,"float16")):Q.set("float16",Uint16Array)}}}),Ae,Se,ye=h(()=>{we(),Ae=re=>{let fe=1;for(let ve=0;ve<re.length;ve++){let Te=re[ve];if(typeof Te!="number"||!Number.isSafeInteger(Te))throw new TypeError(`dims[${ve}] must be an integer, got: ${Te}`);if(Te<0)throw new RangeError(`dims[${ve}] must be a non-negative integer, got: ${Te}`);fe*=Te}return fe},Se=(re,fe)=>{switch(re.location){case"cpu":return new ne(re.type,re.data,fe);case"cpu-pinned":return new ne({location:"cpu-pinned",data:re.data,type:re.type,dims:fe});case"texture":return new ne({location:"texture",texture:re.texture,type:re.type,dims:fe});case"gpu-buffer":return new ne({location:"gpu-buffer",gpuBuffer:re.gpuBuffer,type:re.type,dims:fe});case"ml-tensor":return new ne({location:"ml-tensor",mlTensor:re.mlTensor,type:re.type,dims:fe});default:throw new Error(`tensorReshape: tensor location ${re.location} is not supported`)}}}),ne,we=h(()=>{Y(),X(),pe(),ye(),ne=class{constructor(re,fe,ve){ce();let Te,Ce;if(typeof re=="object"&&"location"in re)switch(this.dataLocation=re.location,Te=re.type,Ce=re.dims,re.location){case"cpu-pinned":{let Re=Q.get(Te);if(!Re)throw new TypeError(`unsupported type "${Te}" to create tensor from pinned buffer`);if(!(re.data instanceof Re))throw new TypeError(`buffer should be of type ${Re.name}`);this.cpuData=re.data;break}case"texture":{if(Te!=="float32")throw new TypeError(`unsupported type "${Te}" to create tensor from texture`);this.gpuTextureData=re.texture,this.downloader=re.download,this.disposer=re.dispose;break}case"gpu-buffer":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from gpu buffer`);this.gpuBufferData=re.gpuBuffer,this.downloader=re.download,this.disposer=re.dispose;break}case"ml-tensor":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint64"&&Te!=="int8"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from MLTensor`);this.mlTensorData=re.mlTensor,this.downloader=re.download,this.disposer=re.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Re,Me;if(typeof re=="string")if(Te=re,Me=ve,re==="string"){if(!Array.isArray(fe))throw new TypeError("A string tensor's data must be a string array.");Re=fe}else{let Fe=Q.get(re);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${re}.`);if(Array.isArray(fe)){if(re==="float16"&&Fe===Uint16Array||re==="uint4"||re==="int4")throw new TypeError(`Creating a ${re} tensor from number array is not supported. Please use ${Fe.name} as data.`);re==="uint64"||re==="int64"?Re=Fe.from(fe,BigInt):Re=Fe.from(fe)}else if(fe instanceof Fe)Re=fe;else if(fe instanceof Uint8ClampedArray)if(re==="uint8")Re=Uint8Array.from(fe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(re==="float16"&&fe instanceof Uint16Array&&Fe!==Uint16Array)Re=new globalThis.Float16Array(fe.buffer,fe.byteOffset,fe.length);else throw new TypeError(`A ${Te} tensor's data must be type of ${Fe}`)}else if(Me=fe,Array.isArray(re)){if(re.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof re[0];if(Fe==="string")Te="string",Re=re;else if(Fe==="boolean")Te="bool",Re=Uint8Array.from(re);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(re instanceof Uint8ClampedArray)Te="uint8",Re=Uint8Array.from(re);else{let Fe=J.get(re.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${re.constructor}.`);Te=Fe,Re=re}if(Me===void 0)Me=[Re.length];else if(!Array.isArray(Me))throw new TypeError("A tensor's dims must be a number array");Ce=Me,this.cpuData=Re,this.dataLocation="cpu"}let Be=Ae(Ce);if(this.cpuData&&Be!==this.cpuData.length&&!((Te==="uint4"||Te==="int4")&&Math.ceil(Be/2)===this.cpuData.length))throw new Error(`Tensor's size(${Be}) does not match data length(${this.cpuData.length}).`);this.type=Te,this.dims=Ce,this.size=Be}static async fromImage(re,fe){return H(re,fe)}static fromTexture(re,fe){return te(re,fe)}static fromGpuBuffer(re,fe){return ae(re,fe)}static fromMLTensor(re,fe){return oe(re,fe)}static fromPinnedBuffer(re,fe,ve){return ie(re,fe,ve)}toDataURL(re){return U(this,re)}toImageData(re){return W(this,re)}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(re){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 fe=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=fe,re&&this.disposer&&(this.disposer(),this.disposer=void 0),fe}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(re){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Se(this,re)}}}),Ne,Je=h(()=>{we(),Ne=ne}),lt,xt,Rt,He,vt,st,an=h(()=>{O(),lt=(re,fe)=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeStamp(`${re}::ORT::${fe}`)},xt=(re,fe)=>{var Ce;let ve=((Ce=new Error().stack)==null?void 0:Ce.split(/\r\n|\r|\n/g))||[],Te=!1;for(let Be=0;Be<ve.length;Be++){if(Te&&!ve[Be].includes("TRACE_FUNC")){let Re=`FUNC_${re}::${ve[Be].trim().split(" ")[1]}`;fe&&(Re+=`::${fe}`),lt("CPU",Re);return}ve[Be].includes("TRACE_FUNC")&&(Te=!0)}},Rt=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("BEGIN",re)},He=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("END",re)},vt=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.time(`ORT::${re}`)},st=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeEnd(`ORT::${re}`)}}),sn,Ye=h(()=>{b(),Je(),an(),sn=class B2{constructor(fe){this.handler=fe}async run(fe,ve,Te){Rt(),vt("InferenceSession.run");let Ce={},Be={};if(typeof fe!="object"||fe===null||fe instanceof Ne||Array.isArray(fe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Re=!0;if(typeof ve=="object"){if(ve===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(ve instanceof Ne)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(ve)){if(ve.length===0)throw new TypeError("'fetches' cannot be an empty array.");Re=!1;for(let et of ve){if(typeof et!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(et)===-1)throw new RangeError(`'fetches' contains invalid output name: ${et}.`);Ce[et]=null}if(typeof Te=="object"&&Te!==null)Be=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else{let et=!1,it=Object.getOwnPropertyNames(ve);for(let tt of this.outputNames)if(it.indexOf(tt)!==-1){let Xe=ve[tt];(Xe===null||Xe instanceof Ne)&&(et=!0,Re=!1,Ce[tt]=Xe)}if(et){if(typeof Te=="object"&&Te!==null)Be=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else Be=ve}}else if(typeof ve<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let et of this.inputNames)if(typeof fe[et]>"u")throw new Error(`input '${et}' is missing in 'feeds'.`);if(Re)for(let et of this.outputNames)Ce[et]=null;let Me=await this.handler.run(fe,Ce,Be),Fe={};for(let et in Me)if(Object.hasOwnProperty.call(Me,et)){let it=Me[et];it instanceof Ne?Fe[et]=it:Fe[et]=new Ne(it.type,it.data,it.dims)}return st("InferenceSession.run"),He(),Fe}async release(){return this.handler.dispose()}static async create(fe,ve,Te,Ce){Rt(),vt("InferenceSession.create");let Be,Re={};if(typeof fe=="string"){if(Be=fe,typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof Uint8Array){if(Be=fe,typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&fe instanceof SharedArrayBuffer){let it=fe,tt=0,Xe=fe.byteLength;if(typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve=="number"){if(tt=ve,!Number.isSafeInteger(tt))throw new RangeError("'byteOffset' must be an integer.");if(tt<0||tt>=it.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${it.byteLength}).`);if(Xe=fe.byteLength-tt,typeof Te=="number"){if(Xe=Te,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||tt+Xe>it.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${it.byteLength-tt}].`);if(typeof Ce=="object"&&Ce!==null)Re=Ce;else if(typeof Ce<"u")throw new TypeError("'options' must be an object.")}else if(typeof Te<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof ve<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(it,tt,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Me,Fe]=await y(Re),et=await Me.createInferenceSessionHandler(Be,Fe);return st("InferenceSession.create"),He(),new B2(et)}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}}}),yt,kt=h(()=>{Ye(),yt=sn}),Kt=h(()=>{}),On=h(()=>{}),Rn=h(()=>{}),Br=h(()=>{}),Tr={};m(Tr,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>vt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,env:()=>I,registerBackend:()=>E});var nt=h(()=>{_(),z(),kt(),Je(),Kt(),On(),an(),Rn(),Br()}),St=h(()=>{}),Tt={};m(Tt,{default:()=>$r});var cn,nn,$r,Ta=h(()=>{var re;be(),Hr(),Ur(),cn="ort-wasm-proxy-worker",nn=((re=globalThis.self)==null?void 0:re.name)===cn,nn&&(self.onmessage=fe=>{let{type:ve,in:Te}=fe.data;try{switch(ve){case"init-wasm":ei(Te.wasm).then(()=>{Ko(Te).then(()=>{postMessage({type:ve})},Ce=>{postMessage({type:ve,err:Ce})})},Ce=>{postMessage({type:ve,err:Ce})});break;case"init-ep":{let{epName:Ce,env:Be}=Te;Ci(Be,Ce).then(()=>{postMessage({type:ve})},Re=>{postMessage({type:ve,err:Re})});break}case"copy-from":{let{buffer:Ce}=Te,Be=on(Ce);postMessage({type:ve,out:Be});break}case"create":{let{model:Ce,options:Be}=Te;ds(Ce,Be).then(Re=>{postMessage({type:ve,out:Re})},Re=>{postMessage({type:ve,err:Re})});break}case"release":Wi(Te),postMessage({type:ve});break;case"run":{let{sessionId:Ce,inputIndices:Be,inputs:Re,outputIndices:Me,options:Fe}=Te;Ke(Ce,Be,Re,Me,new Array(Me.length).fill(null),Fe).then(et=>{et.some(it=>it[3]!=="cpu")?postMessage({type:ve,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:ve,out:et},ft([...Re,...et]))},et=>{postMessage({type:ve,err:et})});break}case"end-profiling":qr(Te),postMessage({type:ve});break;default:}}catch(Ce){postMessage({type:ve,err:Ce})}}),$r=nn?null:fe=>new Worker(fe??yn,{type:"classic",name:cn})}),Vo,vi,yn,Fr,Zn,bi,Ms,as,Fi,wi,_i,Is,Ar,Ur=h(()=>{St(),Vo=typeof location>"u"?void 0:location.origin,vi=()=>{var re,fe;return typeof document<"u"?(re=document.currentScript)==null?void 0:re.src:typeof self<"u"?(fe=self.location)==null?void 0:fe.href:void 0},yn=vi(),Fr=()=>{if(yn&&!yn.startsWith("blob:"))return yn.substring(0,yn.lastIndexOf("/")+1)},Zn=(re,fe)=>{try{let ve=fe??yn;return(ve?new URL(re,ve):new URL(re)).origin===Vo}catch{return!1}},bi=(re,fe)=>{let ve=fe??yn;try{return(ve?new URL(re,ve):new URL(re)).href}catch{return}},Ms=(re,fe)=>`${fe??"./"}${re}`,as=async re=>{let fe=await(await fetch(re,{credentials:"same-origin"})).blob();return URL.createObjectURL(fe)},Fi=async re=>(await import(re)).default,wi=(Ta(),g(Tt)).default,_i=async()=>{if(!yn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Zn(yn))return[void 0,wi()];let re=await as(yn);return[re,wi(re)]},Is=void 0,Ar=async(re,fe,ve,Te)=>{let Ce=Is&&!(re||fe);if(Ce)if(yn)Ce=Zn(yn)||Te&&!ve;else if(Te&&!ve)Ce=!0;else throw new Error("cannot determine the script source URL.");if(Ce)return[void 0,Is];{let Be="ort-wasm-simd-threaded.mjs",Re=re??bi(Be,fe),Me=ve&&Re&&!Zn(Re,fe),Fe=Me?await as(Re):Re??Ms(Be,fe);return[Me?Fe:void 0,await Fi(Fe)]}}}),Js,Rr,ls,js,ho,Qs,Zs,ei,zt,Hr=h(()=>{Ur(),Rr=!1,ls=!1,js=!1,ho=()=>{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}},Qs=()=>{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}},Zs=()=>{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}},ei=async re=>{if(Rr)return Promise.resolve();if(ls)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(js)throw new Error("previous call to 'initializeWebAssembly()' failed.");ls=!0;let fe=re.initTimeout,ve=re.numThreads;if(re.simd!==!1){if(re.simd==="relaxed"){if(!Zs())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Qs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Te=ho();ve>1&&!Te&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+ve+", 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."),re.numThreads=ve=1);let Ce=re.wasmPaths,Be=typeof Ce=="string"?Ce:void 0,Re=Ce==null?void 0:Ce.mjs,Me=(Re==null?void 0:Re.href)??Re,Fe=Ce==null?void 0:Ce.wasm,et=(Fe==null?void 0:Fe.href)??Fe,it=re.wasmBinary,[tt,Xe]=await Ar(Me,Be,ve>1,!!it||!!et),At=!1,ze=[];if(fe>0&&ze.push(new Promise(ut=>{setTimeout(()=>{At=!0,ut()},fe)})),ze.push(new Promise((ut,Cn)=>{let Jt={numThreads:ve};if(it)Jt.wasmBinary=it,Jt.locateFile=Qt=>Qt;else if(et||Be)Jt.locateFile=Qt=>et??Be+Qt;else if(Me&&Me.indexOf("blob:")!==0)Jt.locateFile=Qt=>new URL(Qt,Me).href;else if(tt){let Qt=Fr();Qt&&(Jt.locateFile=jn=>Qt+jn)}Xe(Jt).then(Qt=>{ls=!1,Rr=!0,Js=Qt,ut(),tt&&URL.revokeObjectURL(tt)},Qt=>{ls=!1,js=!0,Cn(Qt)})})),await Promise.race(ze),At)throw new Error(`WebAssembly backend initializing failed due to timeout: ${fe}ms`)},zt=()=>{if(Rr&&Js)return Js;throw new Error("WebAssembly is not initialized yet.")}}),Hn,_n,Ct,Ui=h(()=>{Hr(),Hn=(re,fe)=>{let ve=zt(),Te=ve.lengthBytesUTF8(re)+1,Ce=ve._malloc(Te);return ve.stringToUTF8(re,Ce,Te),fe.push(Ce),Ce},_n=(re,fe,ve,Te)=>{if(typeof re=="object"&&re!==null){if(ve.has(re))throw new Error("Circular reference in options");ve.add(re)}Object.entries(re).forEach(([Ce,Be])=>{let Re=fe?fe+Ce:Ce;if(typeof Be=="object")_n(Be,Re+".",ve,Te);else if(typeof Be=="string"||typeof Be=="number")Te(Re,Be.toString());else if(typeof Be=="boolean")Te(Re,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Ct=re=>{let fe=zt(),ve=fe.stackSave();try{let Te=fe.PTR_SIZE,Ce=fe.stackAlloc(2*Te);fe._OrtGetLastError(Ce,Ce+Te);let Be=Number(fe.getValue(Ce,Te===4?"i32":"i64")),Re=fe.getValue(Ce+Te,"*"),Me=Re?fe.UTF8ToString(Re):"";throw new Error(`${re} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${Me}`)}finally{fe.stackRestore(ve)}}}),fo,$a=h(()=>{Hr(),Ui(),fo=re=>{let fe=zt(),ve=0,Te=[],Ce=re||{};try{if((re==null?void 0:re.logSeverityLevel)===void 0)Ce.logSeverityLevel=2;else if(typeof re.logSeverityLevel!="number"||!Number.isInteger(re.logSeverityLevel)||re.logSeverityLevel<0||re.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${re.logSeverityLevel}`);if((re==null?void 0:re.logVerbosityLevel)===void 0)Ce.logVerbosityLevel=0;else if(typeof re.logVerbosityLevel!="number"||!Number.isInteger(re.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${re.logVerbosityLevel}`);(re==null?void 0:re.terminate)===void 0&&(Ce.terminate=!1);let Be=0;return(re==null?void 0:re.tag)!==void 0&&(Be=Hn(re.tag,Te)),ve=fe._OrtCreateRunOptions(Ce.logSeverityLevel,Ce.logVerbosityLevel,!!Ce.terminate,Be),ve===0&&Ct("Can't create run options."),(re==null?void 0:re.extra)!==void 0&&_n(re.extra,"",new WeakSet,(Re,Me)=>{let Fe=Hn(Re,Te),et=Hn(Me,Te);fe._OrtAddRunConfigEntry(ve,Fe,et)!==0&&Ct(`Can't set a run config entry: ${Re} - ${Me}.`)}),[ve,Te]}catch(Be){throw ve!==0&&fe._OrtReleaseRunOptions(ve),Te.forEach(Re=>fe._free(Re)),Be}}}),po,mo,Go,Sr,Aa,Ra,kn=h(()=>{Hr(),Ui(),po=re=>{switch(re){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: ${re}`)}},mo=re=>{switch(re){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${re}`)}},Go=re=>{re.extra||(re.extra={}),re.extra.session||(re.extra.session={});let fe=re.extra.session;fe.use_ort_model_bytes_directly||(fe.use_ort_model_bytes_directly="1"),re.executionProviders&&re.executionProviders.some(ve=>(typeof ve=="string"?ve:ve.name)==="webgpu")&&(re.enableMemPattern=!1)},Sr=(re,fe,ve,Te)=>{let Ce=Hn(fe,Te),Be=Hn(ve,Te);zt()._OrtAddSessionConfigEntry(re,Ce,Be)!==0&&Ct(`Can't set a session config entry: ${fe} - ${ve}.`)},Aa=async(re,fe,ve)=>{let Te=fe.executionProviders;for(let Ce of Te){let Be=typeof Ce=="string"?Ce:Ce.name,Re=[];switch(Be){case"webnn":if(Be="WEBNN",Sr(re,"session.disable_quant_qdq","1",ve),Sr(re,"session.disable_qdq_constant_folding","1",ve),typeof Ce!="string"){let tt=Ce==null?void 0:Ce.deviceType;tt&&Sr(re,"deviceType",tt,ve)}break;case"webgpu":if(Be="JS",typeof Ce!="string"){let tt=Ce;if(tt!=null&&tt.preferredLayout){if(tt.preferredLayout!=="NCHW"&&tt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${tt.preferredLayout}`);Sr(re,"preferredLayout",tt.preferredLayout,ve)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let Me=Hn(Be,ve),Fe=Re.length,et=0,it=0;if(Fe>0){et=zt()._malloc(Fe*zt().PTR_SIZE),ve.push(et),it=zt()._malloc(Fe*zt().PTR_SIZE),ve.push(it);for(let tt=0;tt<Fe;tt++)zt().setValue(et+tt*zt().PTR_SIZE,Re[tt][0],"*"),zt().setValue(it+tt*zt().PTR_SIZE,Re[tt][1],"*")}await zt()._OrtAppendExecutionProvider(re,Me,et,it,Fe)!==0&&Ct(`Can't append execution provider: ${Be}.`)}},Ra=async re=>{let fe=zt(),ve=0,Te=[],Ce=re||{};Go(Ce);try{let Be=po(Ce.graphOptimizationLevel??"all"),Re=mo(Ce.executionMode??"sequential"),Me=typeof Ce.logId=="string"?Hn(Ce.logId,Te):0,Fe=Ce.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let et=Ce.logVerbosityLevel??0;if(!Number.isInteger(et)||et<0||et>4)throw new Error(`log verbosity level is not valid: ${et}`);let it=typeof Ce.optimizedModelFilePath=="string"?Hn(Ce.optimizedModelFilePath,Te):0;if(ve=fe._OrtCreateSessionOptions(Be,!!Ce.enableCpuMemArena,!!Ce.enableMemPattern,Re,!!Ce.enableProfiling,0,Me,Fe,et,it),ve===0&&Ct("Can't create session options."),Ce.executionProviders&&await Aa(ve,Ce,Te),Ce.enableGraphCapture!==void 0){if(typeof Ce.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Ce.enableGraphCapture}`);Sr(ve,"enableGraphCapture",Ce.enableGraphCapture.toString(),Te)}if(Ce.freeDimensionOverrides)for(let[tt,Xe]of Object.entries(Ce.freeDimensionOverrides)){if(typeof tt!="string")throw new Error(`free dimension override name must be a string: ${tt}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let At=Hn(tt,Te);fe._OrtAddFreeDimensionOverride(ve,At,Xe)!==0&&Ct(`Can't set a free dimension override: ${tt} - ${Xe}.`)}return Ce.extra!==void 0&&_n(Ce.extra,"",new WeakSet,(tt,Xe)=>{Sr(ve,tt,Xe,Te)}),[ve,Te]}catch(Be){throw ve!==0&&fe._OrtReleaseSessionOptions(ve)!==0&&Ct("Can't release session options."),Te.forEach(Re=>fe._free(Re)),Be}}}),Mr,Vn,Ir,ti,Hi,ki,cs,gr,Bt=h(()=>{Mr=re=>{switch(re){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: ${re}`)}},Vn=re=>{switch(re){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: ${re}`)}},Ir=(re,fe)=>{let ve=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][re],Te=typeof fe=="number"?fe:fe.reduce((Ce,Be)=>Ce*Be,1);return ve>0?Math.ceil(Te*ve):void 0},ti=re=>{switch(re){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: ${re}`)}},Hi=re=>{switch(re){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: ${re}`)}},ki=re=>re==="float32"||re==="float16"||re==="int32"||re==="int64"||re==="uint32"||re==="uint8"||re==="bool"||re==="uint4"||re==="int4",cs=re=>re==="float32"||re==="float16"||re==="int32"||re==="int64"||re==="uint32"||re==="uint64"||re==="int8"||re==="uint8"||re==="bool"||re==="uint4"||re==="int4",gr=re=>{switch(re){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: ${re}`)}}}),Gn,Si=h(()=>{St(),Gn=async re=>{if(typeof re=="string"){let fe=await fetch(re);if(!fe.ok)throw new Error(`failed to load external data file: ${re}`);let ve=fe.headers.get("Content-Length"),Te=ve?parseInt(ve,10):0;if(Te<1073741824)return new Uint8Array(await fe.arrayBuffer());{if(!fe.body)throw new Error(`failed to load external data file: ${re}, no response body.`);let Ce=fe.body.getReader(),Be;try{Be=new ArrayBuffer(Te)}catch(Me){if(Me instanceof RangeError){let Fe=Math.ceil(Te/65536);Be=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw Me}let Re=0;for(;;){let{done:Me,value:Fe}=await Ce.read();if(Me)break;let et=Fe.byteLength;new Uint8Array(Be,Re,et).set(Fe),Re+=et}return new Uint8Array(Be,0,Te)}}else return re instanceof Blob?new Uint8Array(await re.arrayBuffer()):re instanceof Uint8Array?re:new Uint8Array(re)}}),us,Ko,Ci,Wr,Ps,ji,on,ds,Wi,Es,Ke,qr,ft,be=h(()=>{nt(),$a(),kn(),Bt(),Hr(),Ui(),Si(),us=(re,fe)=>{zt()._OrtInit(re,fe)!==0&&Ct("Can't initialize onnxruntime.")},Ko=async re=>{us(re.wasm.numThreads,Hi(re.logLevel))},Ci=async(re,fe)=>{var Te,Ce;(Ce=(Te=zt()).asyncInit)==null||Ce.call(Te);let ve=re.webgpu.adapter;if(fe==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(ve){if(typeof ve.limits!="object"||typeof ve.features!="object"||typeof ve.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=re.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let Re=re.webgpu.forceFallbackAdapter;if(Re!==void 0&&typeof Re!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Re}"`);if(ve=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:Re}),!ve)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(fe==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Wr=new Map,Ps=re=>{let fe=zt(),ve=fe.stackSave();try{let Te=fe.PTR_SIZE,Ce=fe.stackAlloc(2*Te);fe._OrtGetInputOutputCount(re,Ce,Ce+Te)!==0&&Ct("Can't get session input/output count.");let Be=Te===4?"i32":"i64";return[Number(fe.getValue(Ce,Be)),Number(fe.getValue(Ce+Te,Be))]}finally{fe.stackRestore(ve)}},ji=(re,fe)=>{let ve=zt(),Te=ve.stackSave(),Ce=0;try{let Be=ve.PTR_SIZE,Re=ve.stackAlloc(2*Be);ve._OrtGetInputOutputMetadata(re,fe,Re,Re+Be)!==0&&Ct("Can't get session input/output metadata.");let Me=Number(ve.getValue(Re,"*"));Ce=Number(ve.getValue(Re+Be,"*"));let Fe=ve.HEAP32[Ce/4];if(Fe===0)return[Me,0];let et=ve.HEAPU32[Ce/4+1],it=[];for(let tt=0;tt<et;tt++){let Xe=Number(ve.getValue(Ce+8+tt*Be,"*"));it.push(Xe!==0?ve.UTF8ToString(Xe):Number(ve.getValue(Ce+8+(tt+et)*Be,"*")))}return[Me,Fe,it]}finally{ve.stackRestore(Te),Ce!==0&&ve._OrtFree(Ce)}},on=re=>{let fe=zt(),ve=fe._malloc(re.byteLength);if(ve===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${re.byteLength}.`);return fe.HEAPU8.set(re,ve),[ve,re.byteLength]},ds=async(re,fe)=>{var it,tt,Xe;let ve,Te,Ce=zt();Array.isArray(re)?[ve,Te]=re:re.buffer===Ce.HEAPU8.buffer?[ve,Te]=[re.byteOffset,re.byteLength]:[ve,Te]=on(re);let Be=0,Re=0,Me=[],Fe=[],et=[];try{if([Re,Me]=await Ra(fe),(fe==null?void 0:fe.externalData)&&Ce.mountExternalData){let Mn=[];for(let hn of fe.externalData){let xr=typeof hn=="string"?hn:hn.path;Mn.push(Gn(typeof hn=="string"?hn:hn.data).then(Pr=>{Ce.mountExternalData(xr,Pr)}))}await Promise.all(Mn)}for(let Mn of(fe==null?void 0:fe.executionProviders)??[])if((typeof Mn=="string"?Mn:Mn.name)==="webnn"){if(Ce.shouldTransferToMLTensor=!1,typeof Mn!="string"){let hn=Mn,xr=hn==null?void 0:hn.context,Pr=hn==null?void 0:hn.gpuDevice,Vr=hn==null?void 0:hn.deviceType,Ia=hn==null?void 0:hn.powerPreference;xr?Ce.currentContext=xr:Pr?Ce.currentContext=await Ce.webnnCreateMLContext(Pr):Ce.currentContext=await Ce.webnnCreateMLContext({deviceType:Vr,powerPreference:Ia})}else Ce.currentContext=await Ce.webnnCreateMLContext();break}Be=await Ce._OrtCreateSession(ve,Te,Re),(it=Ce.webgpuOnCreateSession)==null||it.call(Ce,Be),Be===0&&Ct("Can't create a session."),(tt=Ce.jsepOnCreateSession)==null||tt.call(Ce),Ce.currentContext&&(Ce.webnnRegisterMLContext(Be,Ce.currentContext),Ce.currentContext=void 0,Ce.shouldTransferToMLTensor=!0);let[At,ze]=Ps(Be),ut=!!(fe!=null&&fe.enableGraphCapture),Cn=[],Jt=[],Qt=[],jn=[],Ot=[];for(let Mn=0;Mn<At;Mn++){let[hn,xr,Pr]=ji(Be,Mn);hn===0&&Ct("Can't get an input name."),Fe.push(hn);let Vr=Ce.UTF8ToString(hn);Cn.push(Vr),Qt.push(xr===0?{name:Vr,isTensor:!1}:{name:Vr,isTensor:!0,type:Vn(xr),shape:Pr})}for(let Mn=0;Mn<ze;Mn++){let[hn,xr,Pr]=ji(Be,Mn+At);hn===0&&Ct("Can't get an output name."),et.push(hn);let Vr=Ce.UTF8ToString(hn);Jt.push(Vr),jn.push(xr===0?{name:Vr,isTensor:!1}:{name:Vr,isTensor:!0,type:Vn(xr),shape:Pr})}return Wr.set(Be,[Be,Fe,et,null,ut,!1]),[Be,Cn,Jt,Qt,jn]}catch(At){throw Fe.forEach(ze=>Ce._OrtFree(ze)),et.forEach(ze=>Ce._OrtFree(ze)),Be!==0&&Ce._OrtReleaseSession(Be)!==0&&Ct("Can't release session."),At}finally{Ce._free(ve),Re!==0&&Ce._OrtReleaseSessionOptions(Re)!==0&&Ct("Can't release session options."),Me.forEach(At=>Ce._free(At)),(Xe=Ce.unmountExternalData)==null||Xe.call(Ce)}},Wi=re=>{var Fe,et,it;let fe=zt(),ve=Wr.get(re);if(!ve)throw new Error(`cannot release session. invalid session id: ${re}`);let[Te,Ce,Be,Re,Me]=ve;Re&&(Me&&fe._OrtClearBoundOutputs(Re.handle)!==0&&Ct("Can't clear bound outputs."),fe._OrtReleaseBinding(Re.handle)!==0&&Ct("Can't release IO binding.")),(Fe=fe.jsepOnReleaseSession)==null||Fe.call(fe,re),(et=fe.webnnOnReleaseSession)==null||et.call(fe,re),(it=fe.webgpuOnReleaseSession)==null||it.call(fe,re),Ce.forEach(tt=>fe._OrtFree(tt)),Be.forEach(tt=>fe._OrtFree(tt)),fe._OrtReleaseSession(Te)!==0&&Ct("Can't release session."),Wr.delete(re)},Es=async(re,fe,ve,Te,Ce,Be,Re=!1)=>{if(!re){fe.push(0);return}let Me=zt(),Fe=Me.PTR_SIZE,et=re[0],it=re[1],tt=re[3],Xe=tt,At,ze;if(et==="string"&&(tt==="gpu-buffer"||tt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Re&&tt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(tt==="gpu-buffer"){let Jt=re[2].gpuBuffer;ze=Ir(Mr(et),it);{let Qt=Me.jsepRegisterBuffer;if(!Qt)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');At=Qt(Te,Be,Jt,ze)}}else if(tt==="ml-tensor"){let Jt=re[2].mlTensor;ze=Ir(Mr(et),it);let Qt=Me.webnnRegisterMLTensor;if(!Qt)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');At=Qt(Te,Jt,Mr(et),it)}else{let Jt=re[2];if(Array.isArray(Jt)){ze=Fe*Jt.length,At=Me._malloc(ze),ve.push(At);for(let Qt=0;Qt<Jt.length;Qt++){if(typeof Jt[Qt]!="string")throw new TypeError(`tensor data at index ${Qt} is not a string`);Me.setValue(At+Qt*Fe,Hn(Jt[Qt],ve),"*")}}else{let Qt=Me.webnnIsGraphInput,jn=Me.webnnIsGraphOutput;if(et!=="string"&&Qt&&jn){let Ot=Me.UTF8ToString(Ce);if(Qt(Te,Ot)||jn(Te,Ot)){let Mn=Mr(et);ze=Ir(Mn,it),Xe="ml-tensor";let hn=Me.webnnCreateTemporaryTensor,xr=Me.webnnUploadTensor;if(!hn||!xr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Pr=await hn(Te,Mn,it);xr(Pr,new Uint8Array(Jt.buffer,Jt.byteOffset,Jt.byteLength)),At=Pr}else ze=Jt.byteLength,At=Me._malloc(ze),ve.push(At),Me.HEAPU8.set(new Uint8Array(Jt.buffer,Jt.byteOffset,ze),At)}else ze=Jt.byteLength,At=Me._malloc(ze),ve.push(At),Me.HEAPU8.set(new Uint8Array(Jt.buffer,Jt.byteOffset,ze),At)}}let ut=Me.stackSave(),Cn=Me.stackAlloc(4*it.length);try{it.forEach((Qt,jn)=>Me.setValue(Cn+jn*Fe,Qt,Fe===4?"i32":"i64"));let Jt=Me._OrtCreateTensor(Mr(et),At,ze,Cn,it.length,gr(Xe));Jt===0&&Ct(`Can't create tensor for input/output. session=${Te}, index=${Be}.`),fe.push(Jt)}finally{Me.stackRestore(ut)}},Ke=async(re,fe,ve,Te,Ce,Be)=>{var Gr,Sl,Ec;let Re=zt(),Me=Re.PTR_SIZE,Fe=Wr.get(re);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${re}`);let et=Fe[0],it=Fe[1],tt=Fe[2],Xe=Fe[3],At=Fe[4];Fe[5];let ze=fe.length,ut=Te.length,Cn=0,Jt=[],Qt=[],jn=[],Ot=[],Mn=[],hn=Re.stackSave(),xr=Re.stackAlloc(ze*Me),Pr=Re.stackAlloc(ze*Me),Vr=Re.stackAlloc(ut*Me),Ia=Re.stackAlloc(ut*Me);try{[Cn,Jt]=fo(Be),vt("wasm prepareInputOutputTensor");for(let un=0;un<ze;un++)await Es(ve[un],Qt,Ot,re,it[fe[un]],fe[un],At);for(let un=0;un<ut;un++)await Es(Ce[un],jn,Ot,re,tt[Te[un]],ze+Te[un],At);st("wasm prepareInputOutputTensor");for(let un=0;un<ze;un++)Re.setValue(xr+un*Me,Qt[un],"*"),Re.setValue(Pr+un*Me,it[fe[un]],"*");for(let un=0;un<ut;un++)Re.setValue(Vr+un*Me,jn[un],"*"),Re.setValue(Ia+un*Me,tt[Te[un]],"*");(Gr=Re.jsepOnRunStart)==null||Gr.call(Re,et),(Sl=Re.webnnOnRunStart)==null||Sl.call(Re,et);let yr;yr=await Re._OrtRun(et,Pr,xr,ze,Ia,ut,Vr,Cn),yr!==0&&Ct("failed to call OrtRun().");let ri=[],Nc=[];vt("wasm ProcessOutputTensor");for(let un=0;un<ut;un++){let Os=Number(Re.getValue(Vr+un*Me,"*"));if(Os===jn[un]||Mn.includes(jn[un])){ri.push(Ce[un]),Os!==jn[un]&&Re._OrtReleaseTensor(Os)!==0&&Ct("Can't release tensor.");continue}let Gu=Re.stackSave(),Ti=Re.stackAlloc(4*Me),Xo=!1,ir,Kr=0;try{Re._OrtGetTensorData(Os,Ti,Ti+Me,Ti+2*Me,Ti+3*Me)!==0&&Ct(`Can't access output tensor data on index ${un}.`);let Cl=Me===4?"i32":"i64",Xr=Number(Re.getValue(Ti,Cl));Kr=Re.getValue(Ti+Me,"*");let Tc=Re.getValue(Ti+Me*2,"*"),Ku=Number(Re.getValue(Ti+Me*3,Cl)),$i=[];for(let or=0;or<Ku;or++)$i.push(Number(Re.getValue(Tc+or*Me,Cl)));Re._OrtFree(Tc)!==0&&Ct("Can't free memory for tensor dims.");let Ls=$i.reduce((or,Wn)=>or*Wn,1);ir=Vn(Xr);let si=Xe==null?void 0:Xe.outputPreferredLocations[Te[un]];if(ir==="string"){if(si==="gpu-buffer"||si==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let or=[];for(let Wn=0;Wn<Ls;Wn++){let zs=Re.getValue(Kr+Wn*Me,"*"),$c=Re.getValue(Kr+(Wn+1)*Me,"*"),Ac=Wn===Ls-1?void 0:$c-zs;or.push(Re.UTF8ToString(zs,Ac))}ri.push([ir,$i,or,"cpu"])}else if(si==="gpu-buffer"&&Ls>0){let or=Re.jsepGetBuffer;if(!or)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Wn=or(Kr),zs=Ir(Xr,Ls);if(zs===void 0||!ki(ir))throw new Error(`Unsupported data type: ${ir}`);Xo=!0,ri.push([ir,$i,{gpuBuffer:Wn,download:Re.jsepCreateDownloader(Wn,zs,ir),dispose:()=>{Re._OrtReleaseTensor(Os)!==0&&Ct("Can't release tensor.")}},"gpu-buffer"])}else if(si==="ml-tensor"&&Ls>0){let or=Re.webnnEnsureTensor,Wn=Re.webnnIsGraphInputOutputTypeSupported;if(!or||!Wn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ir(Xr,Ls)===void 0||!cs(ir))throw new Error(`Unsupported data type: ${ir}`);if(!Wn(re,ir,!1))throw new Error(`preferredLocation "ml-tensor" for ${ir} output is not supported by current WebNN Context.`);let zs=await or(re,Kr,Xr,$i,!1);Xo=!0,ri.push([ir,$i,{mlTensor:zs,download:Re.webnnCreateMLTensorDownloader(Kr,ir),dispose:()=>{Re.webnnReleaseTensorId(Kr),Re._OrtReleaseTensor(Os)}},"ml-tensor"])}else if(si==="ml-tensor-cpu-output"&&Ls>0){let or=Re.webnnCreateMLTensorDownloader(Kr,ir)(),Wn=ri.length;Xo=!0,Nc.push((async()=>{let zs=[Wn,await or];return Re.webnnReleaseTensorId(Kr),Re._OrtReleaseTensor(Os),zs})()),ri.push([ir,$i,[],"cpu"])}else{let or=ti(ir),Wn=new or(Ls);new Uint8Array(Wn.buffer,Wn.byteOffset,Wn.byteLength).set(Re.HEAPU8.subarray(Kr,Kr+Wn.byteLength)),ri.push([ir,$i,Wn,"cpu"])}}finally{Re.stackRestore(Gu),ir==="string"&&Kr&&Re._free(Kr),Xo||Re._OrtReleaseTensor(Os)}}Xe&&!At&&(Re._OrtClearBoundOutputs(Xe.handle)!==0&&Ct("Can't clear bound outputs."),Wr.set(re,[et,it,tt,Xe,At,!1]));for(let[un,Os]of await Promise.all(Nc))ri[un][2]=Os;return st("wasm ProcessOutputTensor"),ri}finally{(Ec=Re.webnnOnRunEnd)==null||Ec.call(Re,et),Re.stackRestore(hn),Qt.forEach(yr=>Re._OrtReleaseTensor(yr)),jn.forEach(yr=>Re._OrtReleaseTensor(yr)),Ot.forEach(yr=>Re._free(yr)),Cn!==0&&Re._OrtReleaseRunOptions(Cn),Jt.forEach(yr=>Re._free(yr))}},qr=re=>{let fe=zt(),ve=Wr.get(re);if(!ve)throw new Error("invalid session id");let Te=ve[0],Ce=fe._OrtEndProfiling(Te);Ce===0&&Ct("Can't get an profile file name."),fe._OrtFree(Ce)},ft=re=>{let fe=[];for(let ve of re){let Te=ve[2];!Array.isArray(Te)&&"buffer"in Te&&fe.push(Te.buffer)}return fe}}),Pe,Qe,Et,en,ln,$n,En,er,Ln,sr,Nn,Ds,qi,go,ni,Vu,xo,yo,Sc=h(()=>{nt(),be(),Hr(),Ur(),Pe=()=>!!I.wasm.proxy&&typeof document<"u",Et=!1,en=!1,ln=!1,er=new Map,Ln=(re,fe)=>{let ve=er.get(re);ve?ve.push(fe):er.set(re,[fe])},sr=()=>{if(Et||!en||ln||!Qe)throw new Error("worker not ready")},Nn=re=>{switch(re.data.type){case"init-wasm":Et=!1,re.data.err?(ln=!0,En[1](re.data.err)):(en=!0,En[0]()),$n&&(URL.revokeObjectURL($n),$n=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let fe=er.get(re.data.type);re.data.err?fe.shift()[1](re.data.err):fe.shift()[0](re.data.out);break}}},Ds=async()=>{if(!en){if(Et)throw new Error("multiple calls to 'initWasm()' detected.");if(ln)throw new Error("previous call to 'initWasm()' failed.");if(Et=!0,Pe())return new Promise((re,fe)=>{Qe==null||Qe.terminate(),_i().then(([ve,Te])=>{try{Qe=Te,Qe.onerror=Be=>fe(Be),Qe.onmessage=Nn,En=[re,fe];let Ce={type:"init-wasm",in:I};if(!Ce.in.wasm.wasmPaths&&ve){let Be=Fr();Be&&(Ce.in.wasm.wasmPaths=Be)}Qe.postMessage(Ce),$n=ve}catch(Ce){fe(Ce)}},fe)});try{await ei(I.wasm),await Ko(I),en=!0}catch(re){throw ln=!0,re}finally{Et=!1}}},qi=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("init-ep",[fe,ve]);let Te={type:"init-ep",in:{epName:re,env:I}};Qe.postMessage(Te)});await Ci(I,re)},go=async re=>Pe()?(sr(),new Promise((fe,ve)=>{Ln("copy-from",[fe,ve]);let Te={type:"copy-from",in:{buffer:re}};Qe.postMessage(Te,[re.buffer])})):on(re),ni=async(re,fe)=>{if(Pe()){if(fe!=null&&fe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return sr(),new Promise((ve,Te)=>{Ln("create",[ve,Te]);let Ce={type:"create",in:{model:re,options:{...fe}}},Be=[];re instanceof Uint8Array&&Be.push(re.buffer),Qe.postMessage(Ce,Be)})}else return ds(re,fe)},Vu=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("release",[fe,ve]);let Te={type:"release",in:re};Qe.postMessage(Te)});Wi(re)},xo=async(re,fe,ve,Te,Ce,Be)=>{if(Pe()){if(ve.some(Re=>Re[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ce.some(Re=>Re))throw new Error("pre-allocated output tensor is not supported for proxy.");return sr(),new Promise((Re,Me)=>{Ln("run",[Re,Me]);let Fe=ve,et={type:"run",in:{sessionId:re,inputIndices:fe,inputs:Fe,outputIndices:Te,options:Be}};Qe.postMessage(et,ft(Fe))})}else return Ke(re,fe,ve,Te,Ce,Be)},yo=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("end-profiling",[fe,ve]);let Te={type:"end-profiling",in:re};Qe.postMessage(Te)});qr(re)}}),bl,vo,Ma,wl=h(()=>{nt(),Sc(),Bt(),St(),Si(),bl=(re,fe)=>{switch(re.location){case"cpu":return[re.type,re.dims,re.data,"cpu"];case"gpu-buffer":return[re.type,re.dims,{gpuBuffer:re.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[re.type,re.dims,{mlTensor:re.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${re.location} for ${fe()}`)}},vo=re=>{switch(re[3]){case"cpu":return new Ne(re[0],re[2],re[1]);case"gpu-buffer":{let fe=re[0];if(!ki(fe))throw new Error(`not supported data type: ${fe} for deserializing GPU tensor`);let{gpuBuffer:ve,download:Te,dispose:Ce}=re[2];return Ne.fromGpuBuffer(ve,{dataType:fe,dims:re[1],download:Te,dispose:Ce})}case"ml-tensor":{let fe=re[0];if(!cs(fe))throw new Error(`not supported data type: ${fe} for deserializing MLTensor tensor`);let{mlTensor:ve,download:Te,dispose:Ce}=re[2];return Ne.fromMLTensor(ve,{dataType:fe,dims:re[1],download:Te,dispose:Ce})}default:throw new Error(`invalid data location: ${re[3]}`)}},Ma=class{async fetchModelAndCopyToWasmMemory(re){return go(await Gn(re))}async loadModel(re,fe){Rt();let ve;typeof re=="string"?ve=await this.fetchModelAndCopyToWasmMemory(re):ve=re,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ni(ve,fe),He()}async dispose(){return Vu(this.sessionId)}async run(re,fe,ve){Rt();let Te=[],Ce=[];Object.entries(re).forEach(tt=>{let Xe=tt[0],At=tt[1],ze=this.inputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid input '${Xe}'`);Te.push(At),Ce.push(ze)});let Be=[],Re=[];Object.entries(fe).forEach(tt=>{let Xe=tt[0],At=tt[1],ze=this.outputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid output '${Xe}'`);Be.push(At),Re.push(ze)});let Me=Te.map((tt,Xe)=>bl(tt,()=>`input "${this.inputNames[Ce[Xe]]}"`)),Fe=Be.map((tt,Xe)=>tt?bl(tt,()=>`output "${this.outputNames[Re[Xe]]}"`):null),et=await xo(this.sessionId,Ce,Me,Re,Fe,ve),it={};for(let tt=0;tt<et.length;tt++)it[this.outputNames[Re[tt]]]=Be[tt]??vo(et[tt]);return He(),it}startProfiling(){}endProfiling(){yo(this.sessionId)}}}),Ei={};m(Ei,{OnnxruntimeWebAssemblyBackend:()=>Ni,initializeFlags:()=>Vi,wasmBackend:()=>bo});var Vi,Ni,bo,Cc=h(()=>{nt(),Sc(),wl(),Vi=()=>{(typeof I.wasm.initTimeout!="number"||I.wasm.initTimeout<0)&&(I.wasm.initTimeout=0);let re=I.wasm.simd;if(typeof re!="boolean"&&re!==void 0&&re!=="fixed"&&re!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${re}". Reset it to \`false\` and ignore SIMD feature checking.`),I.wasm.simd=!1),typeof I.wasm.proxy!="boolean"&&(I.wasm.proxy=!1),typeof I.wasm.trace!="boolean"&&(I.wasm.trace=!1),typeof I.wasm.numThreads!="number"||!Number.isInteger(I.wasm.numThreads)||I.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)I.wasm.numThreads=1;else{let fe=typeof navigator>"u"?u("node:os").cpus().length:navigator.hardwareConcurrency;I.wasm.numThreads=Math.min(4,Math.ceil((fe||1)/2))}},Ni=class{async init(re){Vi(),await Ds(),await qi(re)}async createInferenceSessionHandler(re,fe){let ve=new Ma;return await ve.loadModel(re,fe),ve}},bo=new Ni}),jc={};m(jc,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>vt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,default:()=>kl,env:()=>I,registerBackend:()=>E}),nt(),nt(),nt();var _l="1.26.0",kl=Tr;{let re=(Cc(),g(Ei)).wasmBackend;E("cpu",re,10),E("wasm",re,10)}return Object.defineProperty(I.versions,"web",{value:_l,enumerable:!0}),g(jc)})();e.exports=r})(Mv)),Mv.exports}var P_;function fT(){return P_||(P_=1,(function(e){var n=rl&&rl.__createBinding||(Object.create?(function(C,N,$,R){R===void 0&&(R=$);var O=Object.getOwnPropertyDescriptor(N,$);(!O||("get"in O?!N.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return N[$]}}),Object.defineProperty(C,R,O)}):(function(C,N,$,R){R===void 0&&(R=$),C[R]=N[$]})),r=rl&&rl.__setModuleDefault||(Object.create?(function(C,N){Object.defineProperty(C,"default",{enumerable:!0,value:N})}):function(C,N){C.default=N}),i=rl&&rl.__importStar||function(C){if(C&&C.__esModule)return C;var N={};if(C!=null)for(var $ in C)$!=="default"&&Object.prototype.hasOwnProperty.call(C,$)&&n(N,C,$);return r(N,C),N};Object.defineProperty(e,"__esModule",{value:!0}),e.MicVAD=e.getDefaultRealTimeVADOptions=e.ort=e.DEFAULT_MODEL=void 0;const o=i(hT()),l=Zw(),d=e0(),u=Qm(),h=Ky(),m=L2(),x=z2();e.DEFAULT_MODEL="legacy",e.ort=o;const g="vad.worklet.bundle.min.js",v="silero_vad_v5.onnx",S="silero_vad_legacy.onnx",E=C=>({...d.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{u.log.debug("VAD misfire")},onSpeechStart:()=>{u.log.debug("Detected speech start")},onSpeechEnd:()=>{u.log.debug("Detected speech end")},onSpeechRealStart:()=>{u.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:C,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async N=>{N.getTracks().forEach($=>{$.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:N=>{N.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});e.getDefaultRealTimeVADOptions=E;const j=C=>"audioWorklet"in C&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function y(C,N,$,R,O){await $.audioWorklet.addModule(C),N.processorOptions={...N.processorOptions??{},frameSamples:R};const I=new AudioWorkletNode($,"vad-helper-worklet",N);return I.port.onmessage=async z=>{const U=z.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case h.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const W=new Float32Array(U.data);await O(W);break}}},I}async function b(C,N,$){const R=new x.Resampler({nativeSampleRate:C.sampleRate,targetSampleRate:16e3,targetFrameSize:N});u.log.debug("using script processor");const I=C.createScriptProcessor(4096,1,1);let z=!1;return I.onaudioprocess=async U=>{if(!z){z=!0;try{const W=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const V=R.process(W);for(const H of V)await $(H)}catch(W){console.error("Error processing audio:",W)}finally{z=!1}}},I.connect(C.destination),I}class _{constructor(N,$,R,O,I=!1,z=null,U=null,W=null,Y=null,V=null,H=null,te="uninitialized",ae=!1){this.options=N,this.frameProcessor=$,this.model=R,this.frameSamples=O,this.listening=I,this.errored=z,this._stream=U,this._audioContext=W,this._vadNode=Y,this._mediaStreamAudioSourceNode=V,this._audioProcessorAdapterType=H,this.initializationState=te,this.ownsAudioContext=ae,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=oe=>{this.initializationState="errored",this.errored=oe},this.start=async()=>{switch(this.initializationState){case"uninitialized":{u.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(oe){throw oe instanceof Error?this.setErrored(oe.message):this.setErrored(String(oe)),oe}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"?j(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await y(this.options.baseAssetPath+g,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),u.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{u.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:oe,audioContext:ie,vadNode:X}=this.getAudioInstances();this._stream=await this.options.resumeStream(oe);const Q=new MediaStreamAudioSourceNode(ie,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Q,Q.connect(X);break}case"destroyed":{u.log.warn("start called after destroyed");break}case"errored":{u.log.error("start called after errored");break}default:{u.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:oe,mediaStreamAudioSourceNode:ie}=this.getAudioInstances();await this.options.pauseStream(oe),ie.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var ie;u.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:oe}=this.getAudioInstances();oe instanceof AudioWorkletNode&&oe.port.postMessage(h.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((ie=this._audioContext)==null?void 0:ie.close())},this.setOptions=oe=>{this.frameProcessor.setOptions(oe)},this.processFrame=async oe=>{await this.frameProcessor.process(oe,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=oe=>{switch(oe.msg){case h.Message.FrameProcessed:this.options.onFrameProcessed(oe.probs,oe.frame);break;case h.Message.SpeechStart:this.options.onSpeechStart();break;case h.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case h.Message.VADMisfire:this.options.onVADMisfire();break;case h.Message.SpeechEnd:this.options.onSpeechEnd(oe.audio);break}}}static async new(N={}){const $={...(0,e.getDefaultRealTimeVADOptions)(N.model??e.DEFAULT_MODEL),...N};(0,d.validateOptions)($),e.ort.env.wasm.wasmPaths=$.onnxWASMBasePath,$.ortConfig!==void 0&&$.ortConfig(e.ort);const R=$.model==="v5"?v:S,O=$.baseAssetPath+R,I=$.model==="v5"?m.SileroV5.new:m.SileroLegacy.new;let z;try{z=await I(e.ort,()=>(0,l.defaultModelFetcher)(O))}catch(H){throw console.error(`Encountered an error while loading model file ${O}`),H}const U=$.model==="v5"?512:1536,W=U/16,Y=new d.FrameProcessor(z.process,z.reset_state,{positiveSpeechThreshold:$.positiveSpeechThreshold,negativeSpeechThreshold:$.negativeSpeechThreshold,redemptionMs:$.redemptionMs,preSpeechPadMs:$.preSpeechPadMs,minSpeechMs:$.minSpeechMs,submitUserSpeechOnPause:$.submitUserSpeechOnPause},W),V=new _($,Y,z,U);if($.startOnLoad)try{await V.start()}catch(H){throw console.error("Error starting micVad",H),H}return V}}e.MicVAD=_})(rl)),rl}var D_;function pT(){return D_||(D_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getDefaultRealTimeVADOptions=e.MicVAD=e.DEFAULT_MODEL=e.utils=e.NonRealTimeVAD=e.Message=e.FrameProcessor=e.defaultModelFetcher=e.baseAssetPath=void 0;var n=P2();Object.defineProperty(e,"baseAssetPath",{enumerable:!0,get:function(){return n.baseAssetPath}});var r=Zw();Object.defineProperty(e,"defaultModelFetcher",{enumerable:!0,get:function(){return r.defaultModelFetcher}});var i=e0();Object.defineProperty(e,"FrameProcessor",{enumerable:!0,get:function(){return i.FrameProcessor}});var o=Ky();Object.defineProperty(e,"Message",{enumerable:!0,get:function(){return o.Message}});var l=uT();Object.defineProperty(e,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const d=dT();e.utils={audioFileToArray:d.audioFileToArray,minFramesForTargetMS:d.minFramesForTargetMS,arrayBufferToBase64:d.arrayBufferToBase64,encodeWAV:d.encodeWAV};var u=fT();Object.defineProperty(e,"DEFAULT_MODEL",{enumerable:!0,get:function(){return u.DEFAULT_MODEL}}),Object.defineProperty(e,"MicVAD",{enumerable:!0,get:function(){return u.MicVAD}}),Object.defineProperty(e,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return u.getDefaultRealTimeVADOptions}})})($v)),$v}var mT=pT();function ox(e,n,r,i){var l,d;try{(d=(l=window.api)==null?void 0:l.logs)==null||d.write(e,n,r,i)}catch{}const o=n==="error"?console.error:n==="warn"?console.warn:console.log;i!==void 0?o(`[${e}]`,r,i):o(`[${e}]`,r)}const dt={debug:(e,n,r)=>ox(e,"debug",n,r),info:(e,n,r)=>ox(e,"info",n,r),warn:(e,n,r)=>ox(e,"warn",n,r),error:(e,n,r)=>ox(e,"error",n,r)},F2=16e3,gT=6,Ch=F2*gT,xT=400,yT=F2*xT/1e3,O_=300,L_=2e3,z_=1500,B_=3e3,vT=600,U2=.5,H2=.35,F_=.85,U_=.7;let mi=null,wa=!1,Ks=!1;const Bb=new Set;function ax(e){for(const n of Array.from(Bb))try{n(e)}catch(r){dt.warn("speech","workerDeath listener threw",{error:r instanceof Error?r.message:String(r)})}}let Iv=0;const H_=2;let Bh=!1,W2=!1;function q2(e){e.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.type)!=="log")return;const r=n.data.level||"info";dt[r]("whisperWorker",n.data.message??"",n.data.meta)}),e.addEventListener("error",n=>{dt.error("whisperWorker","worker error event (fatal)",{message:n.message,filename:n.filename,lineno:n.lineno}),bT(`error:${n.message||"unknown"}`)})}function fy(){return mi||(mi=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),q2(mi),dt.info("speech","worker spawned"),mi)}let lx=!1;function bT(e){if(!Bh){if(lx){dt.warn("speech","respawnWorker: already in flight, ignoring",{reason:e});return}if(lx=!0,Iv+=1,W2=!0,dt.warn("speech","respawnWorker: starting",{reason:e,attempt:Iv}),ax({reason:e,respawned:!1,finalOnly:!0}),Iv>H_){if(Bh=!0,dt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:H_}),mi)try{mi.terminate()}catch{}mi=null,wa=!1,Ks=!1,ax({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),lx=!1;return}if(mi)try{mi.terminate()}catch{}mi=null,wa=!1,Ks=!1;try{mi=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),q2(mi),Ks=!0,mi.postMessage({type:"load"}),dt.info("speech","respawnWorker: new worker spawned, load posted"),ax({reason:e,respawned:!0,finalOnly:!0})}catch(n){Bh=!0,dt.error("speech","respawnWorker: spawn failed, disabling speech",{error:n instanceof Error?n.message:String(n)}),ax({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{lx=!1}}}function wT(e,n){if(wa||Ks)return;Ks=!0;const r=fy();dt.info("speech","preloadModel: posting load");const i=o=>{o.data.type==="status"?(e==null||e(o.data.status,o.data.message),o.data.status==="ready"&&(wa=!0,Ks=!1,dt.info("speech","preloadModel: ready"),r.removeEventListener("message",i))):o.data.type==="progress"?n==null||n(o.data.pct):o.data.type==="error"&&(Ks=!1,dt.error("speech","preloadModel: worker reported error",{error:o.data.error}),e==null||e("error",o.data.error),r.removeEventListener("message",i))};r.addEventListener("message",i),r.postMessage({type:"load"})}function _T(){dt.info("speech","resetModel: clearing load flags"),wa=!1,Ks=!1}function Xy(){var e;return typeof Worker<"u"&&!!((e=navigator.mediaDevices)!=null&&e.getUserMedia)&&typeof AudioWorkletNode<"u"}function kT(e){const n=fy();return!wa&&!Ks&&(Ks=!0,n.postMessage({type:"load"})),new Promise((r,i)=>{const o=l=>{var d,u,h;((d=l.data)==null?void 0:d.type)==="result"?(n.removeEventListener("message",o),r((l.data.text??"").trim())):((u=l.data)==null?void 0:u.type)==="error"?(n.removeEventListener("message",o),i(new Error(String(l.data.error??"Transcription failed")))):((h=l.data)==null?void 0:h.type)==="status"&&l.data.status==="ready"&&(wa=!0,Ks=!1)};n.addEventListener("message",o),n.postMessage({type:"transcribe",audio:e},[e.buffer])})}function V2(e){let n=fy(),r=!1,i=null,o=null,l=null,d=null,u=null;const h=[],m=new Set;let x=null,g=0,v=!1,S=0,E=!1,j=!1,y=0,b=0,_=0,C=-1,N=O_,$=0,R=null,O="",I="",z=!1,U=0;function W(ce,pe){const Ae=Math.min(ce.length,pe.length);let Se=0;for(;Se<Ae&&ce.charCodeAt(Se)===pe.charCodeAt(Se);)Se++;return Se}function Y(ce){const pe=W(O,ce);return O=ce,pe>I.length&&(I=ce.slice(0,pe)),I.length>ce.length&&(I=ce),I}const V=()=>(x||(x=new Float32Array(Ch)),x),H=()=>{g=0},te=ce=>{const pe=V(),Ae=ce.length;if(Ae>=Ch){pe.set(ce.subarray(Ae-Ch)),g=Ch;return}if(g+Ae<=Ch){pe.set(ce,g),g+=Ae;return}const Se=g+Ae-Ch;pe.copyWithin(0,Se,g),g-=Se,pe.set(ce,g),g+=Ae},ae=()=>{R&&(clearTimeout(R),R=null)},oe=()=>{ae(),v=!1,E=!1,j=!1,N=O_,O="",I="",z=!1,U=0,H()},ie=()=>{if(r||!v||j||E||R)return;if(g<yT){R=setTimeout(()=>{R=null,ie()},N);return}const ce=performance.now()-y;if(ce<N&&y!==0){R=setTimeout(()=>{R=null,ie()},N-ce);return}if(W2||Bh||e.partialsEnabled&&!e.partialsEnabled())return;const pe=V(),Ae=new Float32Array(g);Ae.set(pe.subarray(0,g)),b+=1,_=b,E=!0,$=performance.now(),y=$,n.postMessage({type:"transcribe-partial",audio:Ae,seq:b},[Ae.buffer])},X=ce=>ce.length===0?Promise.resolve():Bh?(dt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),r||e.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(pe=>{h.push(pe),b+=1;const Ae=b;C=Ae,n.postMessage({type:"transcribe",audio:ce,seq:Ae},[ce.buffer])}),Q=ce=>{const pe=X(ce);return m.add(pe),pe.finally(()=>{m.delete(pe)}),pe},J=ce=>{var pe,Ae,Se,ye,ne;if(ce.data.type==="result"){const we=ce.data.text,Ne=ce.data.seq??0;Ne&&Ne<C&&dt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:Ne,latestFinalSeq:C}),!r&&we&&e.onFinal(we),(pe=h.shift())==null||pe()}else if(ce.data.type==="partial"){const we=ce.data.seq??0,Ne=ce.data.text??"",Je=performance.now()-$;E=!1,Je>=B_?(j=!0,dt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Je),seq:we})):Je>=z_&&(N=Math.min(N*2,L_),dt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Je),newIntervalMs:N,seq:we})),z||(z=!0,Je>vT&&N<500&&(N=500,dt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Je),newIntervalMs:500})));const lt=we!==_||we<=C;if(!r&&!lt&&Ne){const xt=Y(Ne);xt&&((Ae=e.onPartial)==null||Ae.call(e,xt),U===0&&(U=performance.now(),dt.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-S)})))}ie()}else if(ce.data.type==="partial-error"){const we=performance.now()-$;E=!1,we>=B_?(j=!0,dt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(we),seq:ce.data.seq})):we>=z_&&(N=Math.min(N*2,L_),dt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(we),newIntervalMs:N,seq:ce.data.seq})),dt.warn("speech","partial encode failed",{error:ce.data.error,seq:ce.data.seq}),ie()}else ce.data.type==="error"?(r||e.onError(ce.data.error),(Se=h.shift())==null||Se()):ce.data.type==="status"?(r||(ye=e.onModelStatus)==null||ye.call(e,ce.data.status,ce.data.message),ce.data.status==="ready"&&(wa=!0,Ks=!1)):ce.data.type==="progress"&&(r||(ne=e.onProgress)==null||ne.call(e,ce.data.pct))};n.addEventListener("message",J);const le=ce=>{var pe,Ae;if(!r){for(dt.warn("speech","createRecognition: worker death event",ce),(pe=e.onStatusChange)==null||pe.call(e,"restarting");h.length;)(Ae=h.shift())==null||Ae();if(m.clear(),ae(),E=!1,ce.respawned){try{n.removeEventListener("message",J)}catch{}n=fy(),n.addEventListener("message",J)}}};return Bb.add(le),{start:async()=>{if(!r){if(Bh){e.onError("Speech recognition disabled — please reload the app.");return}!wa&&!Ks&&(Ks=!0,dt.info("speech","createRecognition.start: triggering model load"),n.postMessage({type:"load"})),dt.info("speech","createRecognition.start: initializing VAD",{modelReady:wa,modelLoading:Ks});try{const ce=new URL("vad/",document.baseURI).href,pe=e.inputDeviceId||null,Ae={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};pe&&(Ae.deviceId={exact:pe}),dt.info("speech","getUserMedia",{hasDeviceId:!!pe,deviceIdPrefix:pe?pe.slice(0,8):null});const Se=await navigator.mediaDevices.getUserMedia({audio:Ae});o=Se,l=new AudioContext;for(const ye of Se.getAudioTracks())ye.addEventListener("ended",()=>{r||(dt.warn("speech","mic track ended (permission revoked or device removed)"),e.onError("Microphone disconnected or permission revoked"))});try{u=l.createMediaStreamSource(o),d=l.createAnalyser(),d.fftSize=2048,d.smoothingTimeConstant=.3,u.connect(d)}catch(ye){dt.warn("speech","analyser init failed",{error:ye instanceof Error?ye.message:String(ye)}),u=null,d=null}i=await mT.MicVAD.new({audioContext:l,getStream:async()=>Se,resumeStream:async()=>Se,pauseStream:async()=>{},baseAssetPath:ce,onnxWASMBasePath:ce,model:"v5",positiveSpeechThreshold:U2,negativeSpeechThreshold:H2,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ye,ne)=>{var we;r||((we=e.onFrame)==null||we.call(e,ye),v&&(te(ne),ie()))},onSpeechStart:()=>{var ye;r||(oe(),v=!0,S=performance.now(),(ye=e.onSpeechStart)==null||ye.call(e))},onSpeechEnd:ye=>{var ne;r||((ne=e.onStatusChange)==null||ne.call(e,"transcribing"),oe(),Q(ye))},onVADMisfire:()=>{var ye,ne;r||((ye=e.onStatusChange)==null||ye.call(e,"idle"),oe(),(ne=e.onMisfire)==null||ne.call(e))}}),i.start()}catch(ce){const pe=ce instanceof Error?ce.message:"Microphone access denied",Ae=ce instanceof Error?ce.stack:"";if(dt.error("speech","createRecognition.start: VAD init failed",{error:pe,stack:Ae}),d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(o){try{o.getTracks().forEach(Se=>Se.stop())}catch{}o=null}if(l){try{await l.close()}catch{}l=null}e.onError(pe)}}},stop:async()=>{if(i)try{await i.pause()}catch{}for(oe();m.size>0;)await Promise.all(Array.from(m));if(i){try{await i.destroy()}catch{}i=null}if(d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(o){try{o.getTracks().forEach(ce=>ce.stop())}catch{}o=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ce,pe)=>{if(i)try{i.setOptions({positiveSpeechThreshold:ce,negativeSpeechThreshold:pe})}catch(Ae){dt.warn("speech","setVadThresholds failed",{error:Ae instanceof Error?Ae.message:String(Ae)})}},getAnalyser:()=>d,destroy:()=>{if(r=!0,oe(),i){try{i.destroy()}catch{}i=null}if(d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.close()}catch{}l=null}if(o){try{o.getTracks().forEach(ce=>ce.stop())}catch{}o=null}Bb.delete(le),n.removeEventListener("message",J)}}}let Am=null;const Fb=new Set,Ub=new Set;function ST(){for(const e of Fb)try{e()}catch{}}function Hb(){for(const e of Ub)try{e()}catch{}}function CT(e){return e.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 jT(e){if(!window.speechSynthesis)return;const n=CT(e);if(!n)return;const r=new SpeechSynthesisUtterance(n);r.rate=1,r.pitch=1,r.onstart=()=>{Am=performance.now(),ST()},r.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Am=null,Hb())},r.onerror=i=>{i.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Am=null,Hb())},window.speechSynthesis.speak(r)}function G2(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Am=null,Hb())}function K2(){var e;return((e=window.speechSynthesis)==null?void 0:e.speaking)??!1}function ET(){return Am}function NT(e){return Fb.add(e),()=>{Fb.delete(e)}}function TT(e){return Ub.add(e),()=>{Ub.delete(e)}}function $T(e){K2()&&(e.setVadThresholds(F_,U_),dt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const n=NT(()=>{e.setVadThresholds(F_,U_),dt.info("voice","tts.duck.on")}),r=TT(()=>{e.setVadThresholds(U2,H2),dt.info("voice","tts.duck.off")});return()=>{n(),r()}}const AT=[{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 RT(e){const n=e.trim();return AT.find(r=>r.match.test(n))??null}const MT=4e4;let Tu=null;function Fh(){Tu&&clearTimeout(Tu),Tu=setTimeout(()=>{Tu=null,$t.getState().stopRecording()},MT)}function cx(){Tu&&(clearTimeout(Tu),Tu=null)}let mc=null,fc=null;const IT=.04,PT=.3;let py=0,Wb=0;function DT(e){fc!==null&&cancelAnimationFrame(fc);const n=()=>{if(mc===null||$t.getState().submitCountdownStartAt===null){fc=null;return}const r=performance.now();if(r-Wb<200&&py>PT){const o=r-e;dt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:py.toFixed(2),msIntoCountdown:Math.round(o)}),lc(),Fh();return}const i=X2();if(i){const o=new Uint8Array(i.fftSize);i.getByteTimeDomainData(o);let l=0;for(let u=0;u<o.length;u++){const h=(o[u]-128)/128;l+=h*h}const d=Math.sqrt(l/o.length);if(d>IT){const u=r-e;dt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:d.toFixed(3),msIntoCountdown:Math.round(u)}),lc(),Fh();return}}fc=requestAnimationFrame(n)};fc=requestAnimationFrame(n)}function OT(e){mc&&clearTimeout(mc);const n=$t.getState().submitDelayMs,r=performance.now();$t.setState({submitCountdownStartAt:r}),mc=setTimeout(()=>{mc=null,$t.setState({submitCountdownStartAt:null});try{window.api.pty.write({tabId:e,data:"\r"})}catch(i){dt.warn("voice","submit pty.write failed",{error:i instanceof Error?i.message:String(i)})}Fh()},n),DT(r)}function lc(){fc!==null&&(cancelAnimationFrame(fc),fc=null),mc&&(clearTimeout(mc),mc=null),$t.getState().submitCountdownStartAt!==null&&$t.setState({submitCountdownStartAt:null})}let rs=null,As=null;function X2(){var e;return((e=rs==null?void 0:rs.getAnalyser)==null?void 0:e.call(rs))??null}const ux=1e4;let Rm=null;function dx(){Rm&&(clearTimeout(Rm),Rm=null)}let Yx=null,Jx=null;function hx(){Yx=null,Jx&&(Jx(),Jx=null)}const LT=1500,zT=9e4;let fx=0,Qx=null,qb=-1;function px(){Qx&&(clearTimeout(Qx),Qx=null,qb=-1)}const BT=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),$t=cr((e,n)=>({isRecording:!1,externalRecording:!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(n().modelStatus!=="idle")return;dt.info("voice","initModel: kicking off preload"),e({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const r=++fx,i=()=>{r===fx&&(px(),qb=r,Qx=setTimeout(()=>{qb===r&&n().modelStatus==="loading"&&(dt.warn("voice","mic.gate.timeout: no progress within 90s"),e({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},zT))};i(),wT((o,l)=>{r===fx&&(o==="ready"?(px(),dt.info("voice","modelStatus -> ready"),e({modelStatus:"ready",loadingProgress:100,errorKind:null})):o==="error"?(px(),dt.error("voice","modelStatus -> error",{msg:l}),e({modelStatus:"error",error:l,errorKind:"load"})):(i(),e({modelStatus:"loading"})))},o=>{r===fx&&(i(),e({loadingProgress:Math.round(o)}))})},resetAndRetryModel:()=>{dt.info("voice","mic.gate.retry"),px(),_T(),e({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),n().initModel()},startRecording:r=>{if(n().isRecording)return;if(rs){dt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Xy()){e({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const i=o=>{try{const l=V2({inputDeviceId:o,onStatusChange:d=>{e(d==="transcribing"?{statusPill:"transcribing"}:d==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:d=>{n().partialsEnabled&&e({lastPartial:d})},partialsEnabled:()=>n().partialsEnabled,onFrame:d=>{py=d.isSpeech,Wb=performance.now()},onSpeechStart:()=>{if(e({statusPill:"listening",lastPartial:""}),cx(),lc(),K2()){const u=ET(),h=u!==null?performance.now()-u:null;G2(),e({lastBargeInAt:performance.now()}),dt.info("voice","barge-in",{tabId:r,utteranceOffsetMs:h})}else dt.debug("voice","barge-in.no-op",{tabId:r})},onMisfire:()=>{e({lastPartial:"",statusPill:"idle"}),Fh();const d=n().lastBargeInAt;d!==null&&performance.now()-d<600&&dt.warn("voice","barge-in.misfire",{tabId:r,sinceBargeInMs:Math.round(performance.now()-d)})},onFinal:d=>{Fh();const u=d.trim();if(!u||BT.has(u)){e({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}const h=RT(u);if(h){dt.info("voice","voice-command",{tabId:r,label:h.label,transcript:u}),window.api.pty.write({tabId:r,data:h.data}),e({lastTranscript:"",lastPartial:"",statusPill:"idle"}),lc();const x=window;x.__transcripts&&(x.__transcripts.push({tabId:r,text:u}),x.__transcripts.length>500&&x.__transcripts.shift());return}window.api.pty.write({tabId:r,data:u}),e({lastTranscript:"",lastPartial:"",statusPill:"idle"}),n().autoSubmit&&OT(r);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:r,text:u}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:d=>{dt.error("voice","recognition error",{err:d}),lc(),e({error:d,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),As==null||As(),As=null,cx(),rs==null||rs.destroy(),rs=null,Le.error(`Microphone error: ${d}`)},onModelStatus:d=>{d==="ready"?e({modelStatus:"ready",loadingProgress:100}):d==="loading"&&e({modelStatus:"loading"})},onProgress:d=>e({loadingProgress:Math.round(d)})});rs=l,e({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Fh(),l.start().then(()=>{rs===l&&(As==null||As(),As=$T(l))}).catch(d=>{const u=d instanceof Error?d.message:String(d);dt.error("voice","handle.start() failed",{error:u}),Le.error(`Could not start mic: ${u}`)})}catch(l){e({error:l instanceof Error?l.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var o,l,d;return((d=(l=(o=window.api)==null?void 0:o.voice)==null?void 0:l.getDevicePref)==null?void 0:d.call(l))??Promise.resolve(null)}).then(o=>i((o==null?void 0:o.selectedDeviceId)??null)).catch(o=>{dt.warn("voice","getDevicePref failed; using default device",{error:o instanceof Error?o.message:String(o)}),i(null)})},stopRecording:()=>{const r=rs;r&&(cx(),lc(),py=0,Wb=0,As==null||As(),As=null,e({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),r.stop().finally(()=>{r.destroy(),rs===r&&(rs=null),n().hotkeyState==="stopping"&&(dx(),e({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!n().isRecording)return;const r=rs;if(!r)return;cx(),As==null||As(),As=null,e({isRecording:!1,lastTranscript:"",lastPartial:""});try{await r.stop()}catch(l){dt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}r.destroy(),rs===r&&(rs=null);const{useSessions:i}=await Jm(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>qN);return{useSessions:l}},[],import.meta.url),o=i.getState().activeTabId;o&&n().startRecording(o)},setExternalRecording:r=>e({externalRecording:r}),toggleTTS:()=>e(r=>({ttsEnabled:!r.ttsEnabled})),setAutoSubmit:r=>e({autoSubmit:r}),setSubmitDelayMs:r=>e({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(r)))}),cancelSubmit:()=>lc(),setPartialsEnabled:r=>{n().partialsEnabled!==r&&(e({partialsEnabled:r}),r||e({lastPartial:""}))},clearError:()=>e({error:null,errorKind:null}),setPermissionState:r=>{n().permissionState!==r&&(dt.info("voice","mic.gate.permission_changed",{from:n().permissionState,to:r}),e({permissionState:r}))},setLevelMeterEnabled:r=>{n().levelMeterEnabled!==r&&e({levelMeterEnabled:r})},setTurnDetectorRuntimeState:r=>{n().turnDetectorState!==r&&(e({turnDetectorState:r}),r==="load_failed"?dt.warn("voice-turn","voice-turn.load_failed"):r==="runtime_error"?dt.warn("voice-turn","voice-turn.runtime_error"):r==="disabled"&&dt.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:r=>{n().wizardArmed!==r&&e({wizardArmed:r})},openWizard:()=>{n().wizardOpen||e({wizardOpen:!0})},closeWizard:()=>{n().wizardOpen&&e({wizardOpen:!1})},armHotkey:({phase:r,source:i,mode:o,tabId:l})=>{const d=n(),{canRecord:u,reason:h}=Vb(d);if(r==="down"){if(h==="error"||h==="load-timeout"){d.resetAndRetryModel(),dt.info("voice-hotkey","down.retry",{source:i,reason:h});return}if(!u&&h!=="loading"){dt.warn("voice-hotkey","miss-model-loading",{modelStatus:d.modelStatus,reason:h});return}if(d.hotkeyState==="recording"||d.isRecording){(o==="toggle"||i==="global")&&(e({hotkeyState:"stopping"}),dx(),Rm=setTimeout(()=>{n().hotkeyState==="stopping"&&(dt.warn("voice-hotkey","drain-timeout",{durationMs:ux}),e({hotkeyState:"aborted"}),setTimeout(()=>{n().hotkeyState==="aborted"&&e({hotkeyState:"idle"})},0))},ux),d.stopRecording());return}if(h==="loading"){d.hotkeyState!=="armed"&&(e({hotkeyState:"armed"}),dt.info("voice-hotkey","armed",{source:i,modelStatus:d.modelStatus})),hx(),Yx={tabId:l,source:i,mode:o},Jx=$t.subscribe((m,x)=>{if(Yx&&m.modelStatus==="ready"&&x.modelStatus!=="ready"&&m.hotkeyState==="armed"){const g=Yx;if(hx(),!g.tabId){dt.warn("voice-hotkey","armed-promote-no-tab",{source:g.source}),e({hotkeyState:"idle"});return}dt.info("voice-hotkey","armed-promote",g),e({hotkeyState:"recording"}),$t.getState().startRecording(g.tabId)}});return}if(!l){dt.warn("voice-hotkey","no-active-tab",{source:i});return}dt.info("voice-hotkey","start",{source:i,mode:o,tabId:l}),d.startRecording(l),n().isRecording?e({hotkeyState:"recording"}):(dt.warn("voice-hotkey","start: recording did not engage",{errorKind:n().errorKind}),e({hotkeyState:"idle"}));return}if(!(o!=="hold"||i==="global")){if(d.hotkeyState==="armed"){hx(),dt.info("voice-hotkey","miss-model-loading-armed-up"),e({hotkeyState:"idle"});return}d.hotkeyState==="recording"&&(e({hotkeyState:"stopping"}),dx(),Rm=setTimeout(()=>{n().hotkeyState==="stopping"&&(dt.warn("voice-hotkey","drain-timeout",{durationMs:ux}),e({hotkeyState:"aborted"}),setTimeout(()=>{n().hotkeyState==="aborted"&&e({hotkeyState:"idle"})},0))},ux),d.stopRecording())}},destroyHotkey:()=>{const r=n();if(hx(),lc(),r.hotkeyState==="recording"){dt.warn("voice-hotkey","destroyed-mid-recording"),e({hotkeyState:"destroyed"});try{r.stopRecording()}catch{}}else(r.hotkeyState==="armed"||r.hotkeyState==="stopping")&&(dx(),e({hotkeyState:"destroyed"}))}})),FT=e=>({isRecording:e.isRecording,statusPill:e.statusPill,lastPartial:e.lastPartial,lastTranscript:e.lastTranscript,submitCountdownStartAt:e.submitCountdownStartAt}),Vb=e=>Xy()?e.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:e.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:e.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:e.modelStatus==="error"?{canRecord:!1,reason:e.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const e=window;e.__voice=$t,e.__transcripts=[]}function t0(e,n,r){return new Promise((i,o)=>{const l=setTimeout(()=>o(new Error(`${r} timed out after ${n}ms`)),n);e.then(d=>{clearTimeout(l),i(d)},d=>{clearTimeout(l),o(d)})})}const UT=5e3,vc=cr(()=>({snapshot:null,loaded:!1}));let W_=!1,q_=!1,Kp;async function HT(){var e;if(!W_){W_=!0;try{const n=await t0(window.api.schedule.state(),UT,"schedule.state");vc.setState({snapshot:n,loaded:!0}),Kp=((e=n.paused)==null?void 0:e.reason)??null}catch(n){if(!q_){q_=!0;const r=n instanceof Error?n.message:String(n);Le.error(`Scheduler state hydrate failed: ${r}`)}Kp=null}window.api.schedule.onState(n=>{var i;const r=((i=n.paused)==null?void 0:i.reason)??null;Kp!==void 0&&r!==Kp&&(r==="auth"?Le.error("Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume."):r==="network"&&Le.error("Scheduler paused: billing endpoint unreachable. Will auto-resume in 30 minutes.")),Kp=r,vc.setState({snapshot:n,loaded:!0})})}}const WT=6e4,qT=5e3,Uh=cr(()=>({data:null,refreshing:!1}));let V_=!1,Zx=null,G_=null,K_=!1;async function n0(){Uh.setState({refreshing:!0});let e=WT;try{const n=await t0(window.api.billing.fetch(),qT,"billing.fetch");Uh.setState({data:n,refreshing:!1}),n.kind==="transient"?e=G_==="transient"?3e4:5e3:(n.kind==="auth"||n.kind==="meter_rate_limited")&&(e=3e4),G_=n.kind}catch(n){if(Uh.setState({refreshing:!1}),!K_){K_=!0;const r=n instanceof Error?n.message:String(n);Le.warn(`Billing usage fetch failed: ${r}`)}}Zx=setTimeout(n0,e)}function VT(){V_||(V_=!0,n0())}function Yy(e){return e?e.kind==="ok"||e.kind==="ok-stale"?e.data:(e.kind==="auth"||e.kind==="meter_rate_limited")&&e.cached?e.cached:null:null}function my(){Zx!==null&&(clearTimeout(Zx),Zx=null),n0()}function dn({name:e,size:n=17,stroke:r=1.6,className:i}){const o={width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round",className:i};switch(e){case"home":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 11l8-7 8 7"}),s.jsx("path",{d:"M6 10v9h12v-9"}),s.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M7 10l3 2-3 2"}),s.jsx("path",{d:"M13 14h4"})]});case"agents":case"subagents":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"7",cy:"9",r:"2.5"}),s.jsx("circle",{cx:"17",cy:"9",r:"2.5"}),s.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),s.jsx("path",{d:"M8.6 11l2.8 4M15.4 11l-2.8 4M9.5 9h5"})]});case"skills":return s.jsx("svg",{...o,children:s.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 s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M12 7v5l3 2"}),s.jsx("path",{d:"M4 6l2 2"})]});case"usage":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"hive":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M8 4h8l4 7-4 7H8l-4-7z"}),s.jsx("circle",{cx:"12",cy:"11",r:"2.5"})]});case"plugins":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),s.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),s.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),s.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),s.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"8",cy:"12",r:"4"}),s.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"plans":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),s.jsx("path",{d:"M8 9h8M8 13h8M8 17h5"})]});case"tasks":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"4",width:"7",height:"7",rx:"1.5"}),s.jsx("rect",{x:"3",y:"13",width:"7",height:"7",rx:"1.5"}),s.jsx("path",{d:"M14 6h7M14 10h5M14 15h7M14 19h5"})]});case"projects":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return s.jsxs("svg",{...o,children:[s.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"}),s.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"11",cy:"11",r:"6"}),s.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return s.jsx("svg",{...o,children:s.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M7 3h7l4 4v14H7z"}),s.jsx("path",{d:"M14 3v4h4"})]});case"play":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),s.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),s.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),s.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.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 s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),s.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),s.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"orchestrator":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"6",r:"2.5"}),s.jsx("circle",{cx:"5",cy:"17",r:"2.5"}),s.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),s.jsx("circle",{cx:"19",cy:"17",r:"2.5"}),s.jsx("path",{d:"M12 8.5v6M12 14.5l-7 0M12 14.5l7 0"})]});case"race":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 4v16M5 5h7l-1 3h7v6h-7l-1 3H5"})});case"background":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M3 4h18v4H3zM3 10h18v4H3zM3 16h18v4H3z"}),s.jsx("circle",{cx:"6",cy:"6",r:".75",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"12",r:".75",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:".75",fill:"currentColor",stroke:"none"})]});case"repoviz":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"6",cy:"12",r:"3"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"18",cy:"18",r:"3"}),s.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),s.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),s.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),s.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return s.jsx("svg",{...o,children:s.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 s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),s.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});case"wifi":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),s.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M9 12h6"}),s.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),s.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"browser":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("ellipse",{cx:"12",cy:"12",rx:"3.2",ry:"8"}),s.jsx("path",{d:"M4 12h16"})]});case"target":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),s.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"record":return s.jsx("svg",{...o,children:s.jsx("circle",{cx:"12",cy:"12",r:"7",fill:"currentColor",stroke:"none"})});case"eye":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"camera":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),s.jsx("circle",{cx:"12",cy:"13.5",r:"3.5"})]});case"arrowleft":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),s.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),s.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return s.jsx("svg",{...o,children:s.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 3l2.6 5.6 6.1.6-4.6 4.1 1.3 6-5.4-3.2-5.4 3.2 1.3-6-4.6-4.1 6.1-.6z"})});case"minus":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12h14"})});default:return null}}function GT(e,n={}){switch(e){case"ready":return n.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 n.loadingPct=="number"?Math.round(n.loadingPct):0} percent`;case"error":return n.errorMessage?`Microphone — speech model error: ${n.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 X_=e=>Symbol.iterator in e,Y_=e=>"entries"in e,J_=(e,n)=>{const r=e instanceof Map?e:new Map(e.entries()),i=n instanceof Map?n:new Map(n.entries());if(r.size!==i.size)return!1;for(const[o,l]of r)if(!i.has(o)||!Object.is(l,i.get(o)))return!1;return!0},KT=(e,n)=>{const r=e[Symbol.iterator](),i=n[Symbol.iterator]();let o=r.next(),l=i.next();for(;!o.done&&!l.done;){if(!Object.is(o.value,l.value))return!1;o=r.next(),l=i.next()}return!!o.done&&!!l.done};function XT(e,n){return Object.is(e,n)?!0:typeof e!="object"||e===null||typeof n!="object"||n===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(n)?!1:X_(e)&&X_(n)?Y_(e)&&Y_(n)?J_(e,n):KT(e,n):J_({entries:()=>Object.entries(e)},{entries:()=>Object.entries(n)})}function Y2(e){const n=co.useRef(void 0);return r=>{const i=e(r);return XT(n.current,i)?n.current:n.current=i}}let Q_=0;const YT=1e3;function JT(e){const n=performance.now();n-Q_<YT||(Q_=n,dt.debug("voice","mic.gate.click_rejected",{reason:e}))}function J2(){const e=$t(m=>m.isRecording),n=$t(m=>m.error),r=$t(m=>m.loadingProgress),i=$t(Y2(Vb)),o=()=>{const m=$t.getState(),{canRecord:x,reason:g}=Vb(m);if(m.isRecording)return m.stopRecording();if(m.wizardArmed&&!m.wizardOpen){m.openWizard();return}if(g==="error"||g==="load-timeout"){m.resetAndRetryModel();return}if(!x)return JT(g);const v=bt.getState().activeTabId;v&&m.startRecording(v)},l=GT(i.reason,{loadingPct:r,errorMessage:n,isRecording:e}),d=i.reason==="unsupported",u=!i.canRecord,h=i.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":i.reason==="error"||i.reason==="load-timeout"?"text-red-400 cursor-pointer":i.reason==="permission-denied"?"text-amber-400 cursor-pointer":i.reason==="idle"?"text-fg-faint cursor-pointer":i.reason==="unsupported"?"text-fg-faint cursor-not-allowed":e?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return s.jsx("button",{onClick:o,disabled:d,"aria-disabled":u,"aria-label":l,title:l,"data-testid":"mic-button","data-state":i.reason,className:`p-1.5 rounded transition-colors ${h}`,children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),s.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function QT(){const e=$t(r=>r.ttsEnabled),n=$t(r=>r.toggleTTS);return s.jsxs("button",{onClick:n,title:e?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${e?"text-accent":"text-fg-dim hover:text-fg"}`,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e?s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):s.jsxs(s.Fragment,{children:[s.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),s.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),s.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function Zm(e){if(!e||e==="—"||e==="unknown")return e;const n=/\[(\dm)\]/.exec(e),r=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(e);if(!r)return e;const i=r[1].charAt(0).toUpperCase()+r[1].slice(1).toLowerCase(),o=r[3]?`${r[2]}.${r[3]}`:r[2];return n?`${i} ${o} ${n[1]}`:`${i} ${o}`}const mx=new Map,ZT=3e4;function Q2(e){const[n,r]=L.useState(()=>{var i;return e?((i=mx.get(e))==null?void 0:i.value)??null:null});return L.useEffect(()=>{if(!e){r(null);return}let i=!1;return(async()=>{const l=mx.get(e);if(l&&Date.now()-l.ts<ZT){i||r(l.value);return}try{const d=await window.api.app.gitBranch(e);if(i)return;mx.set(e,{value:d,ts:Date.now()}),r(d)}catch{if(i)return;mx.set(e,{value:null,ts:Date.now()}),r(null)}})(),()=>{i=!0}},[e]),n}const Jy=[{key:"overview",group:"Workspace",label:"Home",icon:"home",hint:"Today's sessions + the 5-hour window"},{key:"terminal",group:"Workspace",label:"Terminal",icon:"terminal",hint:"Live Claude Code, in-app"},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences"},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit, per project"},{key:"subagents",group:"Workspace",label:"Subagents",icon:"hive",liveKind:"subagents",hint:"Fan out work: Hive · Orchestrate · Race · Boss"},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Author PRDs + run them as claude -p jobs"},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable"},{key:"usage",group:"Workspace",label:"Usage",icon:"usage",hint:"Tokens, cost, sessions per day"},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads"},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code"},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations"},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events"},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override"},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store"},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior"},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules"},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window"},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default"},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk"},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map"},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content"}],e$=Object.fromEntries(Jy.map(e=>[e.key,e.group])),Pv={Workspace:"Where you do the work — sessions, files, and everything currently running.",Configure:"How Claude behaves — changes here apply to every session you start.",Tools:"One-off utilities — not configuration, just things you reach for sometimes."},Z_=Jy.filter(e=>e.group==="Workspace"),e1=Jy.filter(e=>e.group==="Configure"),t1=Jy.filter(e=>e.group==="Tools").map(({key:e,label:n,icon:r,hint:i})=>({key:e,label:n,icon:r,hint:i})),Gb="sm.almanac.sidebarWidth",Z2=180,eC=480,Kb=252;function t$(){try{const e=parseInt(localStorage.getItem(Gb)??"",10);if(Number.isFinite(e))return Math.min(eC,Math.max(Z2,e))}catch{}return Kb}const n$=52,tC="sm.almanac.sidebarCollapsed";function r$(){try{return localStorage.getItem(tC)==="1"}catch{}return!1}const nC="sm.almanac.collapsedGroups";function s$(){try{const e=localStorage.getItem(nC);if(!e)return new Set;const n=JSON.parse(e);return Array.isArray(n)?new Set(n.filter(r=>r==="Workspace"||r==="Configure"||r==="Tools")):new Set}catch{return new Set}}function i$(){const e=$m(l=>l.tabs),n=vc(l=>{var d;return(((d=l.snapshot)==null?void 0:d.jobs)??[]).some(u=>u.status==="running")}),[r,i]=L.useState(()=>Date.now());return L.useEffect(()=>{const l=setInterval(()=>i(Date.now()),5e3);return()=>clearInterval(l)},[]),{subagents:Object.values(e).some(l=>l.agents.some(d=>r-d.at<6e4)),scheduler:n}}function o$({active:e,onNavigate:n,onNewSession:r}){const[i,o]=L.useState(()=>s$()),l=L.useCallback(_=>{o(C=>{const N=new Set(C);N.has(_)?N.delete(_):N.add(_);try{localStorage.setItem(nC,JSON.stringify(Array.from(N)))}catch{}return N})},[]),[d,u]=L.useState(()=>r$()),h=L.useCallback(()=>{u(_=>{const C=!_;try{localStorage.setItem(tC,C?"1":"0")}catch{}return C})},[]),m=bt(_=>_.tabs),x=bt(_=>_.activeTabId),g=m.find(_=>_.id===x)??null,v=i$(),[S,E]=L.useState(()=>t$()),j=L.useRef(S);j.current=S;const y=L.useCallback(_=>{_.preventDefault();const C=_.clientX,N=j.current;let $=N;const R=I=>{$=Math.min(eC,Math.max(Z2,N+(I.clientX-C))),E($)},O=()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",O),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(Gb,String($))}catch{}};window.addEventListener("pointermove",R),window.addEventListener("pointerup",O),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),b=L.useCallback(()=>{E(Kb);try{localStorage.setItem(Gb,String(Kb))}catch{}},[]);return s.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:d?n$:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[s.jsx(a$,{tab:g,onNewSession:r,rail:d,onToggleRail:h}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:d?"4px":"8px"},children:s.jsxs(s.Fragment,{children:[!d&&s.jsx(Dv,{label:"Workspace",desc:Pv.Workspace,collapsed:i.has("Workspace"),count:Z_.length,onToggle:()=>l("Workspace")}),(d||!i.has("Workspace"))&&Z_.map(_=>s.jsx(n1,{item:_,active:e===_.key,live:_.liveKind?v[_.liveKind]:!1,onClick:()=>n(_.key),rail:d},_.key)),!d&&s.jsx(Dv,{label:"Configure",desc:Pv.Configure,collapsed:i.has("Configure"),count:e1.length,onToggle:()=>l("Configure")}),(d||!i.has("Configure"))&&e1.map(_=>s.jsx(n1,{item:_,active:e===_.key,live:!1,onClick:()=>n(_.key),rail:d},_.key)),!d&&s.jsx(Dv,{label:"Tools",desc:Pv.Tools,collapsed:i.has("Tools"),count:t1.length,onToggle:()=>l("Tools")}),(d||!i.has("Tools"))&&t1.map(_=>s.jsx(l$,{tool:_,active:e===_.key,onClick:()=>n(_.key),rail:d},_.key))]})}),s.jsx(c$,{rail:d}),!d&&s.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:y,onDoubleClick:b,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 a$({tab:e,onNewSession:n,rail:r,onToggleRail:i}){const o=(e==null?void 0:e.label)??"no session",l=Q2((e==null?void 0:e.cwd)??null);return r?s.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[s.jsx("button",{onClick:n,"data-testid":"tour-new-session",title:"New session",className:"w-9 h-9 rounded-md bg-bg-hi border border-line text-fg hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center",children:s.jsx(dn,{name:"plus",size:15,stroke:1.8})}),s.jsx("button",{onClick:i,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:s.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:s.jsx(dn,{name:"chevron",size:15,stroke:1.8})})})]}):s.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),s.jsx("button",{onClick:i,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:s.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:s.jsx(dn,{name:"chevron",size:13,stroke:1.8})})})]}),s.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[s.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),s.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(e==null?void 0:e.cwd)??"",children:o})]}),s.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:l?`⌥${l}`:e?e.cwd:"—"}),s.jsxs("div",{className:"mt-3 flex items-stretch gap-1.5",children:[s.jsxs("button",{onClick:n,"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:[s.jsx(dn,{name:"plus",size:13,stroke:1.8}),"New session"]}),s.jsx("div",{className:"flex items-center rounded-md bg-bg-hi border border-line",children:s.jsx(J2,{})})]})]})}function Dv({label:e,desc:n,collapsed:r,count:i,onToggle:o}){return s.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[s.jsxs("button",{onClick:o,"aria-expanded":!r,title:r?`Expand ${e}`:`Collapse ${e}`,className:"group w-full flex items-center gap-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:[s.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:r?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),s.jsx("span",{className:"flex-1",children:e}),r&&s.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:i})]}),!r&&s.jsx("p",{className:"mt-0.5 pl-3.5 text-[11px] leading-[1.35] text-fg-faint/80 normal-case tracking-normal font-sans not-italic line-clamp-2",children:n})]})}function n1({item:e,active:n,live:r,onClick:i,rail:o}){return s.jsxs("button",{onClick:i,title:e.hint,"data-testid":e.key==="scheduler"?"tour-scheduler":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${o?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${n?"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:[n&&s.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${o?"-left-[4px]":"-left-[10px]"}`}),s.jsx("span",{className:`inline-flex ${n?"text-accent":"text-fg-faint"}`,children:s.jsx(dn,{name:e.icon,size:17,stroke:1.6})}),!o&&s.jsxs("span",{className:"flex-1 min-w-0",children:[s.jsx("span",{className:"block truncate",children:e.label}),e.hint&&s.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:e.hint})]}),!o&&r&&s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),o&&r&&s.jsx("span",{className:"absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"})]})}function l$({tool:e,active:n,onClick:r,rail:i}){return s.jsxs("button",{onClick:r,title:e.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${i?"justify-center px-0 py-[7px]":"gap-3 px-3.5 py-[7px] text-[13px]"} ${n?"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:[n&&s.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${i?"-left-[4px]":"-left-[10px]"}`}),s.jsx("span",{className:`inline-flex ${n?"text-accent":"text-fg-faint"}`,children:s.jsx(dn,{name:e.icon,size:15,stroke:1.6})}),!i&&s.jsxs("span",{className:"flex-1 min-w-0",children:[s.jsx("span",{className:"block truncate",children:e.label}),e.hint&&s.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:e.hint})]})]})}function c$({rail:e}){const n=$t(u=>u.isRecording),r=bt(u=>u.tabs),i=bt(u=>u.activeTabId),o=r.find(u=>u.id===i)??null,[l,d]=L.useState(null);return L.useEffect(()=>{let u=!1;if(!(o!=null&&o.presetId)){d(null);return}return S2(o.presetId).then(h=>{u||d((h==null?void 0:h.model)??null)}).catch(()=>{u||d(null)}),()=>{u=!0}},[o==null?void 0:o.presetId]),e?s.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${n?"bg-red-500 animate-pulse":"bg-sage"}`,title:n?"recording":"idle"})}):s.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:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${n?"bg-red-500 animate-pulse":"bg-sage"}`,title:n?"recording":"idle"}),s.jsx("span",{className:"truncate",title:l??"",children:n?"recording…":l?`Claude · ${Zm(l)}`:"Claude Code"})]})}function u$({onNavigate:e}){const n=bt(C=>C.tabs),r=bt(C=>C.activeTabId),i=n.find(C=>C.id===r)??null,o=I2(i),l=(o==null?void 0:o.lastEventAt)??0,d=Uh(C=>C.data),u=vc(C=>{var N;return((N=C.snapshot)==null?void 0:N.paused)??null}),h=Q2((i==null?void 0:i.cwd)??null),[,m]=L.useState(0);L.useEffect(()=>{const C=setInterval(()=>m(N=>N+1),6e4);return()=>clearInterval(C)},[]);const x=(o==null?void 0:o.todos)??[],[g,v]=L.useState(!1),S=L.useRef(null);L.useEffect(()=>{if(!g)return;const C=N=>{S.current&&!S.current.contains(N.target)&&v(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[g]),L.useEffect(()=>{x.length===0&&v(!1)},[x.length]);const E=Yy(d),j=(E==null?void 0:E.usage.five_hour)??null,y=j?Math.round(j.utilization):null,b=(d==null?void 0:d.kind)==="ok"||(d==null?void 0:d.kind)==="ok-stale",_=l>0?f$(Date.now()-l):"—";return s.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:[s.jsxs("button",{onClick:()=>e==null?void 0:e("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:b?"Connected to Anthropic":"Disconnected",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${b?"bg-sage":"bg-fg-faint"}`}),s.jsx("span",{children:b?"connected":"offline"})]}),s.jsx("button",{onClick:()=>e==null?void 0:e("usage"),className:"hover:text-fg transition-colors",title:"Open Usage",children:y!=null?`${y}% of 5h window used`:"5h —"}),u&&s.jsxs("button",{onClick:()=>e==null?void 0:e("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${u.reason==="auth"||u.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",u.reason]}),i&&s.jsxs("span",{className:"text-fg-faint",title:i.cwd,children:[i.label,h&&s.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",h]})]}),s.jsxs("span",{className:"text-fg-faint",children:["last activity: ",s.jsx("span",{className:"text-fg-dim",children:_})]}),x.length>0&&s.jsx(d$,{ref:S,todos:x,open:g,onToggle:()=>v(C=>!C)}),s.jsx("span",{className:"flex-1"}),s.jsxs("span",{className:"text-fg-faint",children:["v","0.38.1"]})]})}const d$=L.forwardRef(function({todos:n,open:r,onToggle:i},o){const l={completed:n.filter(d=>d.status==="completed").length,in_progress:n.filter(d=>d.status==="in_progress").length,pending:n.filter(d=>d.status==="pending").length};return s.jsxs("div",{ref:o,className:"relative",children:[s.jsxs("button",{onClick:i,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[s.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),s.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),s.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),s.jsxs("span",{className:"text-fg-faint",children:["todos ",r?"▾":"▴"]})]}),r&&s.jsx("div",{className:"absolute bottom-full left-0 mb-1.5 w-80 max-h-72 overflow-auto bg-bg-elev border border-line rounded shadow-xl p-2 z-50","data-testid":"footer-todos-popover",children:s.jsx("ul",{className:"space-y-0.5",children:n.map((d,u)=>s.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${d.status==="in_progress"?"bg-bg-hi":""}`,children:[s.jsx(h$,{status:d.status}),s.jsx("span",{className:d.status==="completed"?"text-fg-faint line-through":d.status==="in_progress"?"text-fg":"text-fg-dim",children:d.status==="in_progress"&&d.activeForm?d.activeForm:d.content})]},u))})})]})});function h$({status:e}){return e==="completed"?s.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):e==="in_progress"?s.jsx("span",{className:"w-3 shrink-0",children:s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function f$(e){const n=Math.max(0,Math.floor(e/1e3));if(n<60)return`${n}s ago`;const r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}var Ov={exports:{}},r1;function p$(){return r1||(r1=1,(function(e,n){(function(r,i){e.exports=i()})(globalThis,(()=>(()=>{var r={4567:function(d,u,h){var m=this&&this.__decorate||function(_,C,N,$){var R,O=arguments.length,I=O<3?C:$===null?$=Object.getOwnPropertyDescriptor(C,N):$;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(_,C,N,$);else for(var z=_.length-1;z>=0;z--)(R=_[z])&&(I=(O<3?R(I):O>3?R(C,N,I):R(C,N))||I);return O>3&&I&&Object.defineProperty(C,N,I),I},x=this&&this.__param||function(_,C){return function(N,$){C(N,$,_)}};Object.defineProperty(u,"__esModule",{value:!0}),u.AccessibilityManager=void 0;const g=h(9042),v=h(9924),S=h(844),E=h(4725),j=h(2585),y=h(3656);let b=u.AccessibilityManager=class extends S.Disposable{constructor(_,C,N,$){super(),this._terminal=_,this._coreBrowserService=N,this._renderService=$,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 R=0;R<this._terminal.rows;R++)this._rowElements[R]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[R]);if(this._topBoundaryFocusListener=R=>this._handleBoundaryFocus(R,0),this._bottomBoundaryFocusListener=R=>this._handleBoundaryFocus(R,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 v.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((R=>this._handleResize(R.rows)))),this.register(this._terminal.onRender((R=>this._refreshRows(R.start,R.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((R=>this._handleChar(R)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
2897
|
+
*/var I_;function hT(){return I_||(I_=1,(function(e,n){var r=(()=>{var i=Object.defineProperty,o=Object.getOwnPropertyDescriptor,l=Object.getOwnPropertyNames,d=Object.prototype.hasOwnProperty,u=(re=>typeof oo<"u"?oo:typeof Proxy<"u"?new Proxy(re,{get:(fe,ve)=>(typeof oo<"u"?oo:fe)[ve]}):re)(function(re){if(typeof oo<"u")return oo.apply(this,arguments);throw Error('Dynamic require of "'+re+'" is not supported')}),h=(re,fe)=>()=>(re&&(fe=re(re=0)),fe),m=(re,fe)=>{for(var ve in fe)i(re,ve,{get:fe[ve],enumerable:!0})},x=(re,fe,ve,Te)=>{if(fe&&typeof fe=="object"||typeof fe=="function")for(let Ce of l(fe))!d.call(re,Ce)&&Ce!==ve&&i(re,Ce,{get:()=>fe[Ce],enumerable:!(Te=o(fe,Ce))||Te.enumerable});return re},g=re=>x(i({},"__esModule",{value:!0}),re),v,S,E,j,y,b=h(()=>{v=new Map,S=[],E=(re,fe,ve)=>{if(fe&&typeof fe.init=="function"&&typeof fe.createInferenceSessionHandler=="function"){let Te=v.get(re);if(Te===void 0)v.set(re,{backend:fe,priority:ve});else{if(Te.priority>ve)return;if(Te.priority===ve&&Te.backend!==fe)throw new Error(`cannot register backend "${re}" using priority ${ve}`)}if(ve>=0){let Ce=S.indexOf(re);Ce!==-1&&S.splice(Ce,1);for(let Be=0;Be<S.length;Be++)if(v.get(S[Be]).priority<=ve){S.splice(Be,0,re);return}S.push(re)}return}throw new TypeError("not a valid backend")},j=async re=>{let fe=v.get(re);if(!fe)return"backend not found.";if(fe.initialized)return fe.backend;if(fe.aborted)return fe.error;{let ve=!!fe.initPromise;try{return ve||(fe.initPromise=fe.backend.init(re)),await fe.initPromise,fe.initialized=!0,fe.backend}catch(Te){return ve||(fe.error=`${Te}`,fe.aborted=!0),fe.error}finally{delete fe.initPromise}}},y=async re=>{let fe=re.executionProviders||[],ve=fe.map(Fe=>typeof Fe=="string"?Fe:Fe.name),Te=ve.length===0?S:ve,Ce,Be=[],Re=new Set;for(let Fe of Te){let et=await j(Fe);typeof et=="string"?Be.push({name:Fe,err:et}):(Ce||(Ce=et),Ce===et&&Re.add(Fe))}if(!Ce)throw new Error(`no available backend found. ERR: ${Be.map(Fe=>`[${Fe.name}] ${Fe.err}`).join(", ")}`);for(let{name:Fe,err:et}of Be)ve.includes(Fe)&&console.warn(`removing requested execution provider "${Fe}" from session options because it is not available: ${et}`);let Me=fe.filter(Fe=>Re.has(typeof Fe=="string"?Fe:Fe.name));return[Ce,new Proxy(re,{get:(Fe,et)=>et==="executionProviders"?Me:Reflect.get(Fe,et)})]}}),_=h(()=>{b()}),C,N=h(()=>{C="1.26.0"}),$,R,O=h(()=>{N(),$="warning",R={wasm:{},webgl:{},webgpu:{},versions:{common:C},set logLevel(re){if(re!==void 0){if(typeof re!="string"||["verbose","info","warning","error","fatal"].indexOf(re)===-1)throw new Error(`Unsupported logging level: ${re}`);$=re}},get logLevel(){return $}},Object.defineProperty(R,"logLevel",{enumerable:!0})}),I,z=h(()=>{O(),I=R}),U,W,Y=h(()=>{U=(re,fe)=>{let ve=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);ve.width=re.dims[3],ve.height=re.dims[2];let Te=ve.getContext("2d");if(Te!=null){let Ce,Be;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ce=re.dims[2],Be=re.dims[3]):(Ce=re.dims[3],Be=re.dims[2]);let Re=(fe==null?void 0:fe.format)!==void 0?fe.format:"RGB",Me=fe==null?void 0:fe.norm,Fe,et;Me===void 0||Me.mean===void 0?Fe=[255,255,255,255]:typeof Me.mean=="number"?Fe=[Me.mean,Me.mean,Me.mean,Me.mean]:(Fe=[Me.mean[0],Me.mean[1],Me.mean[2],0],Me.mean[3]!==void 0&&(Fe[3]=Me.mean[3])),Me===void 0||Me.bias===void 0?et=[0,0,0,0]:typeof Me.bias=="number"?et=[Me.bias,Me.bias,Me.bias,Me.bias]:(et=[Me.bias[0],Me.bias[1],Me.bias[2],0],Me.bias[3]!==void 0&&(et[3]=Me.bias[3]));let it=Be*Ce,tt=0,Xe=it,At=it*2,ze=-1;Re==="RGBA"?(tt=0,Xe=it,At=it*2,ze=it*3):Re==="RGB"?(tt=0,Xe=it,At=it*2):Re==="RBG"&&(tt=0,At=it,Xe=it*2);for(let ut=0;ut<Be;ut++)for(let Cn=0;Cn<Ce;Cn++){let Jt=(re.data[tt++]-et[0])*Fe[0],Qt=(re.data[Xe++]-et[1])*Fe[1],jn=(re.data[At++]-et[2])*Fe[2],Ot=ze===-1?255:(re.data[ze++]-et[3])*Fe[3];Te.fillStyle="rgba("+Jt+","+Qt+","+jn+","+Ot+")",Te.fillRect(Cn,ut,1,1)}if("toDataURL"in ve)return ve.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")},W=(re,fe)=>{let ve=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),Te;if(ve!=null){let Ce,Be,Re;(fe==null?void 0:fe.tensorLayout)!==void 0&&fe.tensorLayout==="NHWC"?(Ce=re.dims[2],Be=re.dims[1],Re=re.dims[3]):(Ce=re.dims[3],Be=re.dims[2],Re=re.dims[1]);let Me=fe!==void 0&&fe.format!==void 0?fe.format:"RGB",Fe=fe==null?void 0:fe.norm,et,it;Fe===void 0||Fe.mean===void 0?et=[255,255,255,255]:typeof Fe.mean=="number"?et=[Fe.mean,Fe.mean,Fe.mean,Fe.mean]:(et=[Fe.mean[0],Fe.mean[1],Fe.mean[2],255],Fe.mean[3]!==void 0&&(et[3]=Fe.mean[3])),Fe===void 0||Fe.bias===void 0?it=[0,0,0,0]:typeof Fe.bias=="number"?it=[Fe.bias,Fe.bias,Fe.bias,Fe.bias]:(it=[Fe.bias[0],Fe.bias[1],Fe.bias[2],0],Fe.bias[3]!==void 0&&(it[3]=Fe.bias[3]));let tt=Be*Ce;if(fe!==void 0&&(fe.format!==void 0&&Re===4&&fe.format!=="RGBA"||Re===3&&fe.format!=="RGB"&&fe.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let Xe=4,At=0,ze=1,ut=2,Cn=3,Jt=0,Qt=tt,jn=tt*2,Ot=-1;Me==="RGBA"?(Jt=0,Qt=tt,jn=tt*2,Ot=tt*3):Me==="RGB"?(Jt=0,Qt=tt,jn=tt*2):Me==="RBG"&&(Jt=0,jn=tt,Qt=tt*2),Te=ve.createImageData(Ce,Be);for(let Mn=0;Mn<Be*Ce;At+=Xe,ze+=Xe,ut+=Xe,Cn+=Xe,Mn++)Te.data[At]=(re.data[Jt++]-it[0])*et[0],Te.data[ze]=(re.data[Qt++]-it[1])*et[1],Te.data[ut]=(re.data[jn++]-it[2])*et[2],Te.data[Cn]=Ot===-1?255:(re.data[Ot++]-it[3])*et[3]}else throw new Error("Can not access image data");return Te}}),V,H,te,ae,oe,ie,X=h(()=>{we(),V=(re,fe)=>{if(re===void 0)throw new Error("Image buffer must be defined");if(fe.height===void 0||fe.width===void 0)throw new Error("Image height and width must be defined");if(fe.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:ve,width:Te}=fe,Ce=fe.norm??{mean:255,bias:0},Be,Re;typeof Ce.mean=="number"?Be=[Ce.mean,Ce.mean,Ce.mean,Ce.mean]:Be=[Ce.mean[0],Ce.mean[1],Ce.mean[2],Ce.mean[3]??255],typeof Ce.bias=="number"?Re=[Ce.bias,Ce.bias,Ce.bias,Ce.bias]:Re=[Ce.bias[0],Ce.bias[1],Ce.bias[2],Ce.bias[3]??0];let Me=fe.format!==void 0?fe.format:"RGBA",Fe=fe.tensorFormat!==void 0&&fe.tensorFormat!==void 0?fe.tensorFormat:"RGB",et=ve*Te,it=Fe==="RGBA"?new Float32Array(et*4):new Float32Array(et*3),tt=4,Xe=0,At=1,ze=2,ut=3,Cn=0,Jt=et,Qt=et*2,jn=-1;Me==="RGB"&&(tt=3,Xe=0,At=1,ze=2,ut=-1),Fe==="RGBA"?jn=et*3:Fe==="RBG"?(Cn=0,Qt=et,Jt=et*2):Fe==="BGR"&&(Qt=0,Jt=et,Cn=et*2);for(let Ot=0;Ot<et;Ot++,Xe+=tt,ze+=tt,At+=tt,ut+=tt)it[Cn++]=(re[Xe]+Re[0])/Be[0],it[Jt++]=(re[At]+Re[1])/Be[1],it[Qt++]=(re[ze]+Re[2])/Be[2],jn!==-1&&ut!==-1&&(it[jn++]=(re[ut]+Re[3])/Be[3]);return Fe==="RGBA"?new ne("float32",it,[1,4,ve,Te]):new ne("float32",it,[1,3,ve,Te])},H=async(re,fe)=>{let ve=typeof HTMLImageElement<"u"&&re instanceof HTMLImageElement,Te=typeof ImageData<"u"&&re instanceof ImageData,Ce=typeof ImageBitmap<"u"&&re instanceof ImageBitmap,Be=typeof re=="string",Re,Me=fe??{},Fe=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},et=it=>typeof HTMLCanvasElement<"u"&&it instanceof HTMLCanvasElement||it instanceof OffscreenCanvas?it.getContext("2d"):null;if(ve){let it=Fe();it.width=re.width,it.height=re.height;let tt=et(it);if(tt!=null){let Xe=re.height,At=re.width;if(fe!==void 0&&fe.resizedHeight!==void 0&&fe.resizedWidth!==void 0&&(Xe=fe.resizedHeight,At=fe.resizedWidth),fe!==void 0){if(Me=fe,fe.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");Me.tensorFormat="RGBA",Me.height=Xe,Me.width=At}else Me.tensorFormat="RGBA",Me.height=Xe,Me.width=At;tt.drawImage(re,0,0),Re=tt.getImageData(0,0,At,Xe).data}else throw new Error("Can not access image data")}else if(Te){let it,tt;if(fe!==void 0&&fe.resizedWidth!==void 0&&fe.resizedHeight!==void 0?(it=fe.resizedHeight,tt=fe.resizedWidth):(it=re.height,tt=re.width),fe!==void 0&&(Me=fe),Me.format="RGBA",Me.height=it,Me.width=tt,fe!==void 0){let Xe=Fe();Xe.width=tt,Xe.height=it;let At=et(Xe);if(At!=null)At.putImageData(re,0,0),Re=At.getImageData(0,0,tt,it).data;else throw new Error("Can not access image data")}else Re=re.data}else if(Ce){if(fe===void 0)throw new Error("Please provide image config with format for Imagebitmap");let it=Fe();it.width=re.width,it.height=re.height;let tt=et(it);if(tt!=null){let Xe=re.height,At=re.width;return tt.drawImage(re,0,0,At,Xe),Re=tt.getImageData(0,0,At,Xe).data,Me.height=Xe,Me.width=At,V(Re,Me)}else throw new Error("Can not access image data")}else{if(Be)return new Promise((it,tt)=>{let Xe=Fe(),At=et(Xe);if(!re||!At)return tt();let ze=new Image;ze.crossOrigin="Anonymous",ze.src=re,ze.onload=()=>{Xe.width=ze.width,Xe.height=ze.height,At.drawImage(ze,0,0,Xe.width,Xe.height);let ut=At.getImageData(0,0,Xe.width,Xe.height);Me.height=Xe.height,Me.width=Xe.width,it(V(ut.data,Me))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(Re!==void 0)return V(Re,Me);throw new Error("Input data provided is not supported - aborted tensor creation")},te=(re,fe)=>{let{width:ve,height:Te,download:Ce,dispose:Be}=fe,Re=[1,Te,ve,4];return new ne({location:"texture",type:"float32",texture:re,dims:Re,download:Ce,dispose:Be})},ae=(re,fe)=>{let{dataType:ve,dims:Te,download:Ce,dispose:Be}=fe;return new ne({location:"gpu-buffer",type:ve??"float32",gpuBuffer:re,dims:Te,download:Ce,dispose:Be})},oe=(re,fe)=>{let{dataType:ve,dims:Te,download:Ce,dispose:Be}=fe;return new ne({location:"ml-tensor",type:ve??"float32",mlTensor:re,dims:Te,download:Ce,dispose:Be})},ie=(re,fe,ve)=>new ne({location:"cpu-pinned",type:re,data:fe,dims:ve??[fe.length]})}),Q,J,le,ce,pe=h(()=>{Q=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]),J=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]),le=!1,ce=()=>{if(!le){le=!0;let re=typeof BigInt64Array<"u"&&BigInt64Array.from,fe=typeof BigUint64Array<"u"&&BigUint64Array.from,ve=globalThis.Float16Array,Te=typeof ve<"u"&&ve.from;re&&(Q.set("int64",BigInt64Array),J.set(BigInt64Array,"int64")),fe&&(Q.set("uint64",BigUint64Array),J.set(BigUint64Array,"uint64")),Te?(Q.set("float16",ve),J.set(ve,"float16")):Q.set("float16",Uint16Array)}}}),Ae,Se,ye=h(()=>{we(),Ae=re=>{let fe=1;for(let ve=0;ve<re.length;ve++){let Te=re[ve];if(typeof Te!="number"||!Number.isSafeInteger(Te))throw new TypeError(`dims[${ve}] must be an integer, got: ${Te}`);if(Te<0)throw new RangeError(`dims[${ve}] must be a non-negative integer, got: ${Te}`);fe*=Te}return fe},Se=(re,fe)=>{switch(re.location){case"cpu":return new ne(re.type,re.data,fe);case"cpu-pinned":return new ne({location:"cpu-pinned",data:re.data,type:re.type,dims:fe});case"texture":return new ne({location:"texture",texture:re.texture,type:re.type,dims:fe});case"gpu-buffer":return new ne({location:"gpu-buffer",gpuBuffer:re.gpuBuffer,type:re.type,dims:fe});case"ml-tensor":return new ne({location:"ml-tensor",mlTensor:re.mlTensor,type:re.type,dims:fe});default:throw new Error(`tensorReshape: tensor location ${re.location} is not supported`)}}}),ne,we=h(()=>{Y(),X(),pe(),ye(),ne=class{constructor(re,fe,ve){ce();let Te,Ce;if(typeof re=="object"&&"location"in re)switch(this.dataLocation=re.location,Te=re.type,Ce=re.dims,re.location){case"cpu-pinned":{let Re=Q.get(Te);if(!Re)throw new TypeError(`unsupported type "${Te}" to create tensor from pinned buffer`);if(!(re.data instanceof Re))throw new TypeError(`buffer should be of type ${Re.name}`);this.cpuData=re.data;break}case"texture":{if(Te!=="float32")throw new TypeError(`unsupported type "${Te}" to create tensor from texture`);this.gpuTextureData=re.texture,this.downloader=re.download,this.disposer=re.dispose;break}case"gpu-buffer":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from gpu buffer`);this.gpuBufferData=re.gpuBuffer,this.downloader=re.download,this.disposer=re.dispose;break}case"ml-tensor":{if(Te!=="float32"&&Te!=="float16"&&Te!=="int32"&&Te!=="int64"&&Te!=="uint32"&&Te!=="uint64"&&Te!=="int8"&&Te!=="uint8"&&Te!=="bool"&&Te!=="uint4"&&Te!=="int4")throw new TypeError(`unsupported type "${Te}" to create tensor from MLTensor`);this.mlTensorData=re.mlTensor,this.downloader=re.download,this.disposer=re.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let Re,Me;if(typeof re=="string")if(Te=re,Me=ve,re==="string"){if(!Array.isArray(fe))throw new TypeError("A string tensor's data must be a string array.");Re=fe}else{let Fe=Q.get(re);if(Fe===void 0)throw new TypeError(`Unsupported tensor type: ${re}.`);if(Array.isArray(fe)){if(re==="float16"&&Fe===Uint16Array||re==="uint4"||re==="int4")throw new TypeError(`Creating a ${re} tensor from number array is not supported. Please use ${Fe.name} as data.`);re==="uint64"||re==="int64"?Re=Fe.from(fe,BigInt):Re=Fe.from(fe)}else if(fe instanceof Fe)Re=fe;else if(fe instanceof Uint8ClampedArray)if(re==="uint8")Re=Uint8Array.from(fe);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(re==="float16"&&fe instanceof Uint16Array&&Fe!==Uint16Array)Re=new globalThis.Float16Array(fe.buffer,fe.byteOffset,fe.length);else throw new TypeError(`A ${Te} tensor's data must be type of ${Fe}`)}else if(Me=fe,Array.isArray(re)){if(re.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let Fe=typeof re[0];if(Fe==="string")Te="string",Re=re;else if(Fe==="boolean")Te="bool",Re=Uint8Array.from(re);else throw new TypeError(`Invalid element type of data array: ${Fe}.`)}else if(re instanceof Uint8ClampedArray)Te="uint8",Re=Uint8Array.from(re);else{let Fe=J.get(re.constructor);if(Fe===void 0)throw new TypeError(`Unsupported type for tensor data: ${re.constructor}.`);Te=Fe,Re=re}if(Me===void 0)Me=[Re.length];else if(!Array.isArray(Me))throw new TypeError("A tensor's dims must be a number array");Ce=Me,this.cpuData=Re,this.dataLocation="cpu"}let Be=Ae(Ce);if(this.cpuData&&Be!==this.cpuData.length&&!((Te==="uint4"||Te==="int4")&&Math.ceil(Be/2)===this.cpuData.length))throw new Error(`Tensor's size(${Be}) does not match data length(${this.cpuData.length}).`);this.type=Te,this.dims=Ce,this.size=Be}static async fromImage(re,fe){return H(re,fe)}static fromTexture(re,fe){return te(re,fe)}static fromGpuBuffer(re,fe){return ae(re,fe)}static fromMLTensor(re,fe){return oe(re,fe)}static fromPinnedBuffer(re,fe,ve){return ie(re,fe,ve)}toDataURL(re){return U(this,re)}toImageData(re){return W(this,re)}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(re){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 fe=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=fe,re&&this.disposer&&(this.disposer(),this.disposer=void 0),fe}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(re){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return Se(this,re)}}}),Ne,Je=h(()=>{we(),Ne=ne}),lt,xt,Rt,He,vt,st,an=h(()=>{O(),lt=(re,fe)=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeStamp(`${re}::ORT::${fe}`)},xt=(re,fe)=>{var Ce;let ve=((Ce=new Error().stack)==null?void 0:Ce.split(/\r\n|\r|\n/g))||[],Te=!1;for(let Be=0;Be<ve.length;Be++){if(Te&&!ve[Be].includes("TRACE_FUNC")){let Re=`FUNC_${re}::${ve[Be].trim().split(" ")[1]}`;fe&&(Re+=`::${fe}`),lt("CPU",Re);return}ve[Be].includes("TRACE_FUNC")&&(Te=!0)}},Rt=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("BEGIN",re)},He=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||xt("END",re)},vt=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.time(`ORT::${re}`)},st=re=>{(typeof R.trace>"u"?!R.wasm.trace:!R.trace)||console.timeEnd(`ORT::${re}`)}}),sn,Ye=h(()=>{b(),Je(),an(),sn=class B2{constructor(fe){this.handler=fe}async run(fe,ve,Te){Rt(),vt("InferenceSession.run");let Ce={},Be={};if(typeof fe!="object"||fe===null||fe instanceof Ne||Array.isArray(fe))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let Re=!0;if(typeof ve=="object"){if(ve===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(ve instanceof Ne)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(ve)){if(ve.length===0)throw new TypeError("'fetches' cannot be an empty array.");Re=!1;for(let et of ve){if(typeof et!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(et)===-1)throw new RangeError(`'fetches' contains invalid output name: ${et}.`);Ce[et]=null}if(typeof Te=="object"&&Te!==null)Be=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else{let et=!1,it=Object.getOwnPropertyNames(ve);for(let tt of this.outputNames)if(it.indexOf(tt)!==-1){let Xe=ve[tt];(Xe===null||Xe instanceof Ne)&&(et=!0,Re=!1,Ce[tt]=Xe)}if(et){if(typeof Te=="object"&&Te!==null)Be=Te;else if(typeof Te<"u")throw new TypeError("'options' must be an object.")}else Be=ve}}else if(typeof ve<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let et of this.inputNames)if(typeof fe[et]>"u")throw new Error(`input '${et}' is missing in 'feeds'.`);if(Re)for(let et of this.outputNames)Ce[et]=null;let Me=await this.handler.run(fe,Ce,Be),Fe={};for(let et in Me)if(Object.hasOwnProperty.call(Me,et)){let it=Me[et];it instanceof Ne?Fe[et]=it:Fe[et]=new Ne(it.type,it.data,it.dims)}return st("InferenceSession.run"),He(),Fe}async release(){return this.handler.dispose()}static async create(fe,ve,Te,Ce){Rt(),vt("InferenceSession.create");let Be,Re={};if(typeof fe=="string"){if(Be=fe,typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof Uint8Array){if(Be=fe,typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve<"u")throw new TypeError("'options' must be an object.")}else if(fe instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&fe instanceof SharedArrayBuffer){let it=fe,tt=0,Xe=fe.byteLength;if(typeof ve=="object"&&ve!==null)Re=ve;else if(typeof ve=="number"){if(tt=ve,!Number.isSafeInteger(tt))throw new RangeError("'byteOffset' must be an integer.");if(tt<0||tt>=it.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${it.byteLength}).`);if(Xe=fe.byteLength-tt,typeof Te=="number"){if(Xe=Te,!Number.isSafeInteger(Xe))throw new RangeError("'byteLength' must be an integer.");if(Xe<=0||tt+Xe>it.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${it.byteLength-tt}].`);if(typeof Ce=="object"&&Ce!==null)Re=Ce;else if(typeof Ce<"u")throw new TypeError("'options' must be an object.")}else if(typeof Te<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof ve<"u")throw new TypeError("'options' must be an object.");Be=new Uint8Array(it,tt,Xe)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[Me,Fe]=await y(Re),et=await Me.createInferenceSessionHandler(Be,Fe);return st("InferenceSession.create"),He(),new B2(et)}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}}}),yt,kt=h(()=>{Ye(),yt=sn}),Kt=h(()=>{}),On=h(()=>{}),Rn=h(()=>{}),Br=h(()=>{}),Tr={};m(Tr,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>vt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,env:()=>I,registerBackend:()=>E});var nt=h(()=>{_(),z(),kt(),Je(),Kt(),On(),an(),Rn(),Br()}),St=h(()=>{}),Tt={};m(Tt,{default:()=>$r});var cn,nn,$r,Ta=h(()=>{var re;be(),Hr(),Ur(),cn="ort-wasm-proxy-worker",nn=((re=globalThis.self)==null?void 0:re.name)===cn,nn&&(self.onmessage=fe=>{let{type:ve,in:Te}=fe.data;try{switch(ve){case"init-wasm":ti(Te.wasm).then(()=>{Ko(Te).then(()=>{postMessage({type:ve})},Ce=>{postMessage({type:ve,err:Ce})})},Ce=>{postMessage({type:ve,err:Ce})});break;case"init-ep":{let{epName:Ce,env:Be}=Te;Ci(Be,Ce).then(()=>{postMessage({type:ve})},Re=>{postMessage({type:ve,err:Re})});break}case"copy-from":{let{buffer:Ce}=Te,Be=on(Ce);postMessage({type:ve,out:Be});break}case"create":{let{model:Ce,options:Be}=Te;ds(Ce,Be).then(Re=>{postMessage({type:ve,out:Re})},Re=>{postMessage({type:ve,err:Re})});break}case"release":Wi(Te),postMessage({type:ve});break;case"run":{let{sessionId:Ce,inputIndices:Be,inputs:Re,outputIndices:Me,options:Fe}=Te;Ke(Ce,Be,Re,Me,new Array(Me.length).fill(null),Fe).then(et=>{et.some(it=>it[3]!=="cpu")?postMessage({type:ve,err:"Proxy does not support non-cpu tensor location."}):postMessage({type:ve,out:et},ft([...Re,...et]))},et=>{postMessage({type:ve,err:et})});break}case"end-profiling":qr(Te),postMessage({type:ve});break;default:}}catch(Ce){postMessage({type:ve,err:Ce})}}),$r=nn?null:fe=>new Worker(fe??yn,{type:"classic",name:cn})}),Vo,vi,yn,Fr,Zn,bi,Ms,as,Fi,wi,_i,Is,Ar,Ur=h(()=>{St(),Vo=typeof location>"u"?void 0:location.origin,vi=()=>{var re,fe;return typeof document<"u"?(re=document.currentScript)==null?void 0:re.src:typeof self<"u"?(fe=self.location)==null?void 0:fe.href:void 0},yn=vi(),Fr=()=>{if(yn&&!yn.startsWith("blob:"))return yn.substring(0,yn.lastIndexOf("/")+1)},Zn=(re,fe)=>{try{let ve=fe??yn;return(ve?new URL(re,ve):new URL(re)).origin===Vo}catch{return!1}},bi=(re,fe)=>{let ve=fe??yn;try{return(ve?new URL(re,ve):new URL(re)).href}catch{return}},Ms=(re,fe)=>`${fe??"./"}${re}`,as=async re=>{let fe=await(await fetch(re,{credentials:"same-origin"})).blob();return URL.createObjectURL(fe)},Fi=async re=>(await import(re)).default,wi=(Ta(),g(Tt)).default,_i=async()=>{if(!yn)throw new Error("Failed to load proxy worker: cannot determine the script source URL.");if(Zn(yn))return[void 0,wi()];let re=await as(yn);return[re,wi(re)]},Is=void 0,Ar=async(re,fe,ve,Te)=>{let Ce=Is&&!(re||fe);if(Ce)if(yn)Ce=Zn(yn)||Te&&!ve;else if(Te&&!ve)Ce=!0;else throw new Error("cannot determine the script source URL.");if(Ce)return[void 0,Is];{let Be="ort-wasm-simd-threaded.mjs",Re=re??bi(Be,fe),Me=ve&&Re&&!Zn(Re,fe),Fe=Me?await as(Re):Re??Ms(Be,fe);return[Me?Fe:void 0,await Fi(Fe)]}}}),Qs,Rr,ls,js,ho,Zs,ei,ti,zt,Hr=h(()=>{Ur(),Rr=!1,ls=!1,js=!1,ho=()=>{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}},Zs=()=>{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}},ei=()=>{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}},ti=async re=>{if(Rr)return Promise.resolve();if(ls)throw new Error("multiple calls to 'initializeWebAssembly()' detected.");if(js)throw new Error("previous call to 'initializeWebAssembly()' failed.");ls=!0;let fe=re.initTimeout,ve=re.numThreads;if(re.simd!==!1){if(re.simd==="relaxed"){if(!ei())throw new Error("Relaxed WebAssembly SIMD is not supported in the current environment.")}else if(!Zs())throw new Error("WebAssembly SIMD is not supported in the current environment.")}let Te=ho();ve>1&&!Te&&(typeof self<"u"&&!self.crossOriginIsolated&&console.warn("env.wasm.numThreads is set to "+ve+", 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."),re.numThreads=ve=1);let Ce=re.wasmPaths,Be=typeof Ce=="string"?Ce:void 0,Re=Ce==null?void 0:Ce.mjs,Me=(Re==null?void 0:Re.href)??Re,Fe=Ce==null?void 0:Ce.wasm,et=(Fe==null?void 0:Fe.href)??Fe,it=re.wasmBinary,[tt,Xe]=await Ar(Me,Be,ve>1,!!it||!!et),At=!1,ze=[];if(fe>0&&ze.push(new Promise(ut=>{setTimeout(()=>{At=!0,ut()},fe)})),ze.push(new Promise((ut,Cn)=>{let Jt={numThreads:ve};if(it)Jt.wasmBinary=it,Jt.locateFile=Qt=>Qt;else if(et||Be)Jt.locateFile=Qt=>et??Be+Qt;else if(Me&&Me.indexOf("blob:")!==0)Jt.locateFile=Qt=>new URL(Qt,Me).href;else if(tt){let Qt=Fr();Qt&&(Jt.locateFile=jn=>Qt+jn)}Xe(Jt).then(Qt=>{ls=!1,Rr=!0,Qs=Qt,ut(),tt&&URL.revokeObjectURL(tt)},Qt=>{ls=!1,js=!0,Cn(Qt)})})),await Promise.race(ze),At)throw new Error(`WebAssembly backend initializing failed due to timeout: ${fe}ms`)},zt=()=>{if(Rr&&Qs)return Qs;throw new Error("WebAssembly is not initialized yet.")}}),Hn,_n,Ct,Ui=h(()=>{Hr(),Hn=(re,fe)=>{let ve=zt(),Te=ve.lengthBytesUTF8(re)+1,Ce=ve._malloc(Te);return ve.stringToUTF8(re,Ce,Te),fe.push(Ce),Ce},_n=(re,fe,ve,Te)=>{if(typeof re=="object"&&re!==null){if(ve.has(re))throw new Error("Circular reference in options");ve.add(re)}Object.entries(re).forEach(([Ce,Be])=>{let Re=fe?fe+Ce:Ce;if(typeof Be=="object")_n(Be,Re+".",ve,Te);else if(typeof Be=="string"||typeof Be=="number")Te(Re,Be.toString());else if(typeof Be=="boolean")Te(Re,Be?"1":"0");else throw new Error(`Can't handle extra config type: ${typeof Be}`)})},Ct=re=>{let fe=zt(),ve=fe.stackSave();try{let Te=fe.PTR_SIZE,Ce=fe.stackAlloc(2*Te);fe._OrtGetLastError(Ce,Ce+Te);let Be=Number(fe.getValue(Ce,Te===4?"i32":"i64")),Re=fe.getValue(Ce+Te,"*"),Me=Re?fe.UTF8ToString(Re):"";throw new Error(`${re} ERROR_CODE: ${Be}, ERROR_MESSAGE: ${Me}`)}finally{fe.stackRestore(ve)}}}),fo,$a=h(()=>{Hr(),Ui(),fo=re=>{let fe=zt(),ve=0,Te=[],Ce=re||{};try{if((re==null?void 0:re.logSeverityLevel)===void 0)Ce.logSeverityLevel=2;else if(typeof re.logSeverityLevel!="number"||!Number.isInteger(re.logSeverityLevel)||re.logSeverityLevel<0||re.logSeverityLevel>4)throw new Error(`log severity level is not valid: ${re.logSeverityLevel}`);if((re==null?void 0:re.logVerbosityLevel)===void 0)Ce.logVerbosityLevel=0;else if(typeof re.logVerbosityLevel!="number"||!Number.isInteger(re.logVerbosityLevel))throw new Error(`log verbosity level is not valid: ${re.logVerbosityLevel}`);(re==null?void 0:re.terminate)===void 0&&(Ce.terminate=!1);let Be=0;return(re==null?void 0:re.tag)!==void 0&&(Be=Hn(re.tag,Te)),ve=fe._OrtCreateRunOptions(Ce.logSeverityLevel,Ce.logVerbosityLevel,!!Ce.terminate,Be),ve===0&&Ct("Can't create run options."),(re==null?void 0:re.extra)!==void 0&&_n(re.extra,"",new WeakSet,(Re,Me)=>{let Fe=Hn(Re,Te),et=Hn(Me,Te);fe._OrtAddRunConfigEntry(ve,Fe,et)!==0&&Ct(`Can't set a run config entry: ${Re} - ${Me}.`)}),[ve,Te]}catch(Be){throw ve!==0&&fe._OrtReleaseRunOptions(ve),Te.forEach(Re=>fe._free(Re)),Be}}}),po,mo,Go,Sr,Aa,Ra,kn=h(()=>{Hr(),Ui(),po=re=>{switch(re){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: ${re}`)}},mo=re=>{switch(re){case"sequential":return 0;case"parallel":return 1;default:throw new Error(`unsupported execution mode: ${re}`)}},Go=re=>{re.extra||(re.extra={}),re.extra.session||(re.extra.session={});let fe=re.extra.session;fe.use_ort_model_bytes_directly||(fe.use_ort_model_bytes_directly="1"),re.executionProviders&&re.executionProviders.some(ve=>(typeof ve=="string"?ve:ve.name)==="webgpu")&&(re.enableMemPattern=!1)},Sr=(re,fe,ve,Te)=>{let Ce=Hn(fe,Te),Be=Hn(ve,Te);zt()._OrtAddSessionConfigEntry(re,Ce,Be)!==0&&Ct(`Can't set a session config entry: ${fe} - ${ve}.`)},Aa=async(re,fe,ve)=>{let Te=fe.executionProviders;for(let Ce of Te){let Be=typeof Ce=="string"?Ce:Ce.name,Re=[];switch(Be){case"webnn":if(Be="WEBNN",Sr(re,"session.disable_quant_qdq","1",ve),Sr(re,"session.disable_qdq_constant_folding","1",ve),typeof Ce!="string"){let tt=Ce==null?void 0:Ce.deviceType;tt&&Sr(re,"deviceType",tt,ve)}break;case"webgpu":if(Be="JS",typeof Ce!="string"){let tt=Ce;if(tt!=null&&tt.preferredLayout){if(tt.preferredLayout!=="NCHW"&&tt.preferredLayout!=="NHWC")throw new Error(`preferredLayout must be either 'NCHW' or 'NHWC': ${tt.preferredLayout}`);Sr(re,"preferredLayout",tt.preferredLayout,ve)}}break;case"wasm":case"cpu":continue;default:throw new Error(`not supported execution provider: ${Be}`)}let Me=Hn(Be,ve),Fe=Re.length,et=0,it=0;if(Fe>0){et=zt()._malloc(Fe*zt().PTR_SIZE),ve.push(et),it=zt()._malloc(Fe*zt().PTR_SIZE),ve.push(it);for(let tt=0;tt<Fe;tt++)zt().setValue(et+tt*zt().PTR_SIZE,Re[tt][0],"*"),zt().setValue(it+tt*zt().PTR_SIZE,Re[tt][1],"*")}await zt()._OrtAppendExecutionProvider(re,Me,et,it,Fe)!==0&&Ct(`Can't append execution provider: ${Be}.`)}},Ra=async re=>{let fe=zt(),ve=0,Te=[],Ce=re||{};Go(Ce);try{let Be=po(Ce.graphOptimizationLevel??"all"),Re=mo(Ce.executionMode??"sequential"),Me=typeof Ce.logId=="string"?Hn(Ce.logId,Te):0,Fe=Ce.logSeverityLevel??2;if(!Number.isInteger(Fe)||Fe<0||Fe>4)throw new Error(`log severity level is not valid: ${Fe}`);let et=Ce.logVerbosityLevel??0;if(!Number.isInteger(et)||et<0||et>4)throw new Error(`log verbosity level is not valid: ${et}`);let it=typeof Ce.optimizedModelFilePath=="string"?Hn(Ce.optimizedModelFilePath,Te):0;if(ve=fe._OrtCreateSessionOptions(Be,!!Ce.enableCpuMemArena,!!Ce.enableMemPattern,Re,!!Ce.enableProfiling,0,Me,Fe,et,it),ve===0&&Ct("Can't create session options."),Ce.executionProviders&&await Aa(ve,Ce,Te),Ce.enableGraphCapture!==void 0){if(typeof Ce.enableGraphCapture!="boolean")throw new Error(`enableGraphCapture must be a boolean value: ${Ce.enableGraphCapture}`);Sr(ve,"enableGraphCapture",Ce.enableGraphCapture.toString(),Te)}if(Ce.freeDimensionOverrides)for(let[tt,Xe]of Object.entries(Ce.freeDimensionOverrides)){if(typeof tt!="string")throw new Error(`free dimension override name must be a string: ${tt}`);if(typeof Xe!="number"||!Number.isInteger(Xe)||Xe<0)throw new Error(`free dimension override value must be a non-negative integer: ${Xe}`);let At=Hn(tt,Te);fe._OrtAddFreeDimensionOverride(ve,At,Xe)!==0&&Ct(`Can't set a free dimension override: ${tt} - ${Xe}.`)}return Ce.extra!==void 0&&_n(Ce.extra,"",new WeakSet,(tt,Xe)=>{Sr(ve,tt,Xe,Te)}),[ve,Te]}catch(Be){throw ve!==0&&fe._OrtReleaseSessionOptions(ve)!==0&&Ct("Can't release session options."),Te.forEach(Re=>fe._free(Re)),Be}}}),Mr,Vn,Ir,ni,Hi,ki,cs,gr,Bt=h(()=>{Mr=re=>{switch(re){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: ${re}`)}},Vn=re=>{switch(re){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: ${re}`)}},Ir=(re,fe)=>{let ve=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][re],Te=typeof fe=="number"?fe:fe.reduce((Ce,Be)=>Ce*Be,1);return ve>0?Math.ceil(Te*ve):void 0},ni=re=>{switch(re){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: ${re}`)}},Hi=re=>{switch(re){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: ${re}`)}},ki=re=>re==="float32"||re==="float16"||re==="int32"||re==="int64"||re==="uint32"||re==="uint8"||re==="bool"||re==="uint4"||re==="int4",cs=re=>re==="float32"||re==="float16"||re==="int32"||re==="int64"||re==="uint32"||re==="uint64"||re==="int8"||re==="uint8"||re==="bool"||re==="uint4"||re==="int4",gr=re=>{switch(re){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: ${re}`)}}}),Gn,Si=h(()=>{St(),Gn=async re=>{if(typeof re=="string"){let fe=await fetch(re);if(!fe.ok)throw new Error(`failed to load external data file: ${re}`);let ve=fe.headers.get("Content-Length"),Te=ve?parseInt(ve,10):0;if(Te<1073741824)return new Uint8Array(await fe.arrayBuffer());{if(!fe.body)throw new Error(`failed to load external data file: ${re}, no response body.`);let Ce=fe.body.getReader(),Be;try{Be=new ArrayBuffer(Te)}catch(Me){if(Me instanceof RangeError){let Fe=Math.ceil(Te/65536);Be=new WebAssembly.Memory({initial:Fe,maximum:Fe}).buffer}else throw Me}let Re=0;for(;;){let{done:Me,value:Fe}=await Ce.read();if(Me)break;let et=Fe.byteLength;new Uint8Array(Be,Re,et).set(Fe),Re+=et}return new Uint8Array(Be,0,Te)}}else return re instanceof Blob?new Uint8Array(await re.arrayBuffer()):re instanceof Uint8Array?re:new Uint8Array(re)}}),us,Ko,Ci,Wr,Ps,ji,on,ds,Wi,Es,Ke,qr,ft,be=h(()=>{nt(),$a(),kn(),Bt(),Hr(),Ui(),Si(),us=(re,fe)=>{zt()._OrtInit(re,fe)!==0&&Ct("Can't initialize onnxruntime.")},Ko=async re=>{us(re.wasm.numThreads,Hi(re.logLevel))},Ci=async(re,fe)=>{var Te,Ce;(Ce=(Te=zt()).asyncInit)==null||Ce.call(Te);let ve=re.webgpu.adapter;if(fe==="webgpu"){if(typeof navigator>"u"||!navigator.gpu)throw new Error("WebGPU is not supported in current environment");if(ve){if(typeof ve.limits!="object"||typeof ve.features!="object"||typeof ve.requestDevice!="function")throw new Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let Be=re.webgpu.powerPreference;if(Be!==void 0&&Be!=="low-power"&&Be!=="high-performance")throw new Error(`Invalid powerPreference setting: "${Be}"`);let Re=re.webgpu.forceFallbackAdapter;if(Re!==void 0&&typeof Re!="boolean")throw new Error(`Invalid forceFallbackAdapter setting: "${Re}"`);if(ve=await navigator.gpu.requestAdapter({powerPreference:Be,forceFallbackAdapter:Re}),!ve)throw new Error('Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.')}}if(fe==="webnn"&&(typeof navigator>"u"||!navigator.ml))throw new Error("WebNN is not supported in current environment")},Wr=new Map,Ps=re=>{let fe=zt(),ve=fe.stackSave();try{let Te=fe.PTR_SIZE,Ce=fe.stackAlloc(2*Te);fe._OrtGetInputOutputCount(re,Ce,Ce+Te)!==0&&Ct("Can't get session input/output count.");let Be=Te===4?"i32":"i64";return[Number(fe.getValue(Ce,Be)),Number(fe.getValue(Ce+Te,Be))]}finally{fe.stackRestore(ve)}},ji=(re,fe)=>{let ve=zt(),Te=ve.stackSave(),Ce=0;try{let Be=ve.PTR_SIZE,Re=ve.stackAlloc(2*Be);ve._OrtGetInputOutputMetadata(re,fe,Re,Re+Be)!==0&&Ct("Can't get session input/output metadata.");let Me=Number(ve.getValue(Re,"*"));Ce=Number(ve.getValue(Re+Be,"*"));let Fe=ve.HEAP32[Ce/4];if(Fe===0)return[Me,0];let et=ve.HEAPU32[Ce/4+1],it=[];for(let tt=0;tt<et;tt++){let Xe=Number(ve.getValue(Ce+8+tt*Be,"*"));it.push(Xe!==0?ve.UTF8ToString(Xe):Number(ve.getValue(Ce+8+(tt+et)*Be,"*")))}return[Me,Fe,it]}finally{ve.stackRestore(Te),Ce!==0&&ve._OrtFree(Ce)}},on=re=>{let fe=zt(),ve=fe._malloc(re.byteLength);if(ve===0)throw new Error(`Can't create a session. failed to allocate a buffer of size ${re.byteLength}.`);return fe.HEAPU8.set(re,ve),[ve,re.byteLength]},ds=async(re,fe)=>{var it,tt,Xe;let ve,Te,Ce=zt();Array.isArray(re)?[ve,Te]=re:re.buffer===Ce.HEAPU8.buffer?[ve,Te]=[re.byteOffset,re.byteLength]:[ve,Te]=on(re);let Be=0,Re=0,Me=[],Fe=[],et=[];try{if([Re,Me]=await Ra(fe),(fe==null?void 0:fe.externalData)&&Ce.mountExternalData){let Mn=[];for(let hn of fe.externalData){let xr=typeof hn=="string"?hn:hn.path;Mn.push(Gn(typeof hn=="string"?hn:hn.data).then(Pr=>{Ce.mountExternalData(xr,Pr)}))}await Promise.all(Mn)}for(let Mn of(fe==null?void 0:fe.executionProviders)??[])if((typeof Mn=="string"?Mn:Mn.name)==="webnn"){if(Ce.shouldTransferToMLTensor=!1,typeof Mn!="string"){let hn=Mn,xr=hn==null?void 0:hn.context,Pr=hn==null?void 0:hn.gpuDevice,Vr=hn==null?void 0:hn.deviceType,Ia=hn==null?void 0:hn.powerPreference;xr?Ce.currentContext=xr:Pr?Ce.currentContext=await Ce.webnnCreateMLContext(Pr):Ce.currentContext=await Ce.webnnCreateMLContext({deviceType:Vr,powerPreference:Ia})}else Ce.currentContext=await Ce.webnnCreateMLContext();break}Be=await Ce._OrtCreateSession(ve,Te,Re),(it=Ce.webgpuOnCreateSession)==null||it.call(Ce,Be),Be===0&&Ct("Can't create a session."),(tt=Ce.jsepOnCreateSession)==null||tt.call(Ce),Ce.currentContext&&(Ce.webnnRegisterMLContext(Be,Ce.currentContext),Ce.currentContext=void 0,Ce.shouldTransferToMLTensor=!0);let[At,ze]=Ps(Be),ut=!!(fe!=null&&fe.enableGraphCapture),Cn=[],Jt=[],Qt=[],jn=[],Ot=[];for(let Mn=0;Mn<At;Mn++){let[hn,xr,Pr]=ji(Be,Mn);hn===0&&Ct("Can't get an input name."),Fe.push(hn);let Vr=Ce.UTF8ToString(hn);Cn.push(Vr),Qt.push(xr===0?{name:Vr,isTensor:!1}:{name:Vr,isTensor:!0,type:Vn(xr),shape:Pr})}for(let Mn=0;Mn<ze;Mn++){let[hn,xr,Pr]=ji(Be,Mn+At);hn===0&&Ct("Can't get an output name."),et.push(hn);let Vr=Ce.UTF8ToString(hn);Jt.push(Vr),jn.push(xr===0?{name:Vr,isTensor:!1}:{name:Vr,isTensor:!0,type:Vn(xr),shape:Pr})}return Wr.set(Be,[Be,Fe,et,null,ut,!1]),[Be,Cn,Jt,Qt,jn]}catch(At){throw Fe.forEach(ze=>Ce._OrtFree(ze)),et.forEach(ze=>Ce._OrtFree(ze)),Be!==0&&Ce._OrtReleaseSession(Be)!==0&&Ct("Can't release session."),At}finally{Ce._free(ve),Re!==0&&Ce._OrtReleaseSessionOptions(Re)!==0&&Ct("Can't release session options."),Me.forEach(At=>Ce._free(At)),(Xe=Ce.unmountExternalData)==null||Xe.call(Ce)}},Wi=re=>{var Fe,et,it;let fe=zt(),ve=Wr.get(re);if(!ve)throw new Error(`cannot release session. invalid session id: ${re}`);let[Te,Ce,Be,Re,Me]=ve;Re&&(Me&&fe._OrtClearBoundOutputs(Re.handle)!==0&&Ct("Can't clear bound outputs."),fe._OrtReleaseBinding(Re.handle)!==0&&Ct("Can't release IO binding.")),(Fe=fe.jsepOnReleaseSession)==null||Fe.call(fe,re),(et=fe.webnnOnReleaseSession)==null||et.call(fe,re),(it=fe.webgpuOnReleaseSession)==null||it.call(fe,re),Ce.forEach(tt=>fe._OrtFree(tt)),Be.forEach(tt=>fe._OrtFree(tt)),fe._OrtReleaseSession(Te)!==0&&Ct("Can't release session."),Wr.delete(re)},Es=async(re,fe,ve,Te,Ce,Be,Re=!1)=>{if(!re){fe.push(0);return}let Me=zt(),Fe=Me.PTR_SIZE,et=re[0],it=re[1],tt=re[3],Xe=tt,At,ze;if(et==="string"&&(tt==="gpu-buffer"||tt==="ml-tensor"))throw new Error("String tensor is not supported on GPU.");if(Re&&tt!=="gpu-buffer")throw new Error(`External buffer must be provided for input/output index ${Be} when enableGraphCapture is true.`);if(tt==="gpu-buffer"){let Jt=re[2].gpuBuffer;ze=Ir(Mr(et),it);{let Qt=Me.jsepRegisterBuffer;if(!Qt)throw new Error('Tensor location "gpu-buffer" is not supported without using WebGPU.');At=Qt(Te,Be,Jt,ze)}}else if(tt==="ml-tensor"){let Jt=re[2].mlTensor;ze=Ir(Mr(et),it);let Qt=Me.webnnRegisterMLTensor;if(!Qt)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');At=Qt(Te,Jt,Mr(et),it)}else{let Jt=re[2];if(Array.isArray(Jt)){ze=Fe*Jt.length,At=Me._malloc(ze),ve.push(At);for(let Qt=0;Qt<Jt.length;Qt++){if(typeof Jt[Qt]!="string")throw new TypeError(`tensor data at index ${Qt} is not a string`);Me.setValue(At+Qt*Fe,Hn(Jt[Qt],ve),"*")}}else{let Qt=Me.webnnIsGraphInput,jn=Me.webnnIsGraphOutput;if(et!=="string"&&Qt&&jn){let Ot=Me.UTF8ToString(Ce);if(Qt(Te,Ot)||jn(Te,Ot)){let Mn=Mr(et);ze=Ir(Mn,it),Xe="ml-tensor";let hn=Me.webnnCreateTemporaryTensor,xr=Me.webnnUploadTensor;if(!hn||!xr)throw new Error('Tensor location "ml-tensor" is not supported without using WebNN.');let Pr=await hn(Te,Mn,it);xr(Pr,new Uint8Array(Jt.buffer,Jt.byteOffset,Jt.byteLength)),At=Pr}else ze=Jt.byteLength,At=Me._malloc(ze),ve.push(At),Me.HEAPU8.set(new Uint8Array(Jt.buffer,Jt.byteOffset,ze),At)}else ze=Jt.byteLength,At=Me._malloc(ze),ve.push(At),Me.HEAPU8.set(new Uint8Array(Jt.buffer,Jt.byteOffset,ze),At)}}let ut=Me.stackSave(),Cn=Me.stackAlloc(4*it.length);try{it.forEach((Qt,jn)=>Me.setValue(Cn+jn*Fe,Qt,Fe===4?"i32":"i64"));let Jt=Me._OrtCreateTensor(Mr(et),At,ze,Cn,it.length,gr(Xe));Jt===0&&Ct(`Can't create tensor for input/output. session=${Te}, index=${Be}.`),fe.push(Jt)}finally{Me.stackRestore(ut)}},Ke=async(re,fe,ve,Te,Ce,Be)=>{var Gr,Sl,Ec;let Re=zt(),Me=Re.PTR_SIZE,Fe=Wr.get(re);if(!Fe)throw new Error(`cannot run inference. invalid session id: ${re}`);let et=Fe[0],it=Fe[1],tt=Fe[2],Xe=Fe[3],At=Fe[4];Fe[5];let ze=fe.length,ut=Te.length,Cn=0,Jt=[],Qt=[],jn=[],Ot=[],Mn=[],hn=Re.stackSave(),xr=Re.stackAlloc(ze*Me),Pr=Re.stackAlloc(ze*Me),Vr=Re.stackAlloc(ut*Me),Ia=Re.stackAlloc(ut*Me);try{[Cn,Jt]=fo(Be),vt("wasm prepareInputOutputTensor");for(let un=0;un<ze;un++)await Es(ve[un],Qt,Ot,re,it[fe[un]],fe[un],At);for(let un=0;un<ut;un++)await Es(Ce[un],jn,Ot,re,tt[Te[un]],ze+Te[un],At);st("wasm prepareInputOutputTensor");for(let un=0;un<ze;un++)Re.setValue(xr+un*Me,Qt[un],"*"),Re.setValue(Pr+un*Me,it[fe[un]],"*");for(let un=0;un<ut;un++)Re.setValue(Vr+un*Me,jn[un],"*"),Re.setValue(Ia+un*Me,tt[Te[un]],"*");(Gr=Re.jsepOnRunStart)==null||Gr.call(Re,et),(Sl=Re.webnnOnRunStart)==null||Sl.call(Re,et);let yr;yr=await Re._OrtRun(et,Pr,xr,ze,Ia,ut,Vr,Cn),yr!==0&&Ct("failed to call OrtRun().");let si=[],Nc=[];vt("wasm ProcessOutputTensor");for(let un=0;un<ut;un++){let Os=Number(Re.getValue(Vr+un*Me,"*"));if(Os===jn[un]||Mn.includes(jn[un])){si.push(Ce[un]),Os!==jn[un]&&Re._OrtReleaseTensor(Os)!==0&&Ct("Can't release tensor.");continue}let Gu=Re.stackSave(),Ti=Re.stackAlloc(4*Me),Xo=!1,ir,Kr=0;try{Re._OrtGetTensorData(Os,Ti,Ti+Me,Ti+2*Me,Ti+3*Me)!==0&&Ct(`Can't access output tensor data on index ${un}.`);let Cl=Me===4?"i32":"i64",Xr=Number(Re.getValue(Ti,Cl));Kr=Re.getValue(Ti+Me,"*");let Tc=Re.getValue(Ti+Me*2,"*"),Ku=Number(Re.getValue(Ti+Me*3,Cl)),$i=[];for(let or=0;or<Ku;or++)$i.push(Number(Re.getValue(Tc+or*Me,Cl)));Re._OrtFree(Tc)!==0&&Ct("Can't free memory for tensor dims.");let Ls=$i.reduce((or,Wn)=>or*Wn,1);ir=Vn(Xr);let ii=Xe==null?void 0:Xe.outputPreferredLocations[Te[un]];if(ir==="string"){if(ii==="gpu-buffer"||ii==="ml-tensor")throw new Error("String tensor is not supported on GPU.");let or=[];for(let Wn=0;Wn<Ls;Wn++){let zs=Re.getValue(Kr+Wn*Me,"*"),$c=Re.getValue(Kr+(Wn+1)*Me,"*"),Ac=Wn===Ls-1?void 0:$c-zs;or.push(Re.UTF8ToString(zs,Ac))}si.push([ir,$i,or,"cpu"])}else if(ii==="gpu-buffer"&&Ls>0){let or=Re.jsepGetBuffer;if(!or)throw new Error('preferredLocation "gpu-buffer" is not supported without using WebGPU.');let Wn=or(Kr),zs=Ir(Xr,Ls);if(zs===void 0||!ki(ir))throw new Error(`Unsupported data type: ${ir}`);Xo=!0,si.push([ir,$i,{gpuBuffer:Wn,download:Re.jsepCreateDownloader(Wn,zs,ir),dispose:()=>{Re._OrtReleaseTensor(Os)!==0&&Ct("Can't release tensor.")}},"gpu-buffer"])}else if(ii==="ml-tensor"&&Ls>0){let or=Re.webnnEnsureTensor,Wn=Re.webnnIsGraphInputOutputTypeSupported;if(!or||!Wn)throw new Error('preferredLocation "ml-tensor" is not supported without using WebNN.');if(Ir(Xr,Ls)===void 0||!cs(ir))throw new Error(`Unsupported data type: ${ir}`);if(!Wn(re,ir,!1))throw new Error(`preferredLocation "ml-tensor" for ${ir} output is not supported by current WebNN Context.`);let zs=await or(re,Kr,Xr,$i,!1);Xo=!0,si.push([ir,$i,{mlTensor:zs,download:Re.webnnCreateMLTensorDownloader(Kr,ir),dispose:()=>{Re.webnnReleaseTensorId(Kr),Re._OrtReleaseTensor(Os)}},"ml-tensor"])}else if(ii==="ml-tensor-cpu-output"&&Ls>0){let or=Re.webnnCreateMLTensorDownloader(Kr,ir)(),Wn=si.length;Xo=!0,Nc.push((async()=>{let zs=[Wn,await or];return Re.webnnReleaseTensorId(Kr),Re._OrtReleaseTensor(Os),zs})()),si.push([ir,$i,[],"cpu"])}else{let or=ni(ir),Wn=new or(Ls);new Uint8Array(Wn.buffer,Wn.byteOffset,Wn.byteLength).set(Re.HEAPU8.subarray(Kr,Kr+Wn.byteLength)),si.push([ir,$i,Wn,"cpu"])}}finally{Re.stackRestore(Gu),ir==="string"&&Kr&&Re._free(Kr),Xo||Re._OrtReleaseTensor(Os)}}Xe&&!At&&(Re._OrtClearBoundOutputs(Xe.handle)!==0&&Ct("Can't clear bound outputs."),Wr.set(re,[et,it,tt,Xe,At,!1]));for(let[un,Os]of await Promise.all(Nc))si[un][2]=Os;return st("wasm ProcessOutputTensor"),si}finally{(Ec=Re.webnnOnRunEnd)==null||Ec.call(Re,et),Re.stackRestore(hn),Qt.forEach(yr=>Re._OrtReleaseTensor(yr)),jn.forEach(yr=>Re._OrtReleaseTensor(yr)),Ot.forEach(yr=>Re._free(yr)),Cn!==0&&Re._OrtReleaseRunOptions(Cn),Jt.forEach(yr=>Re._free(yr))}},qr=re=>{let fe=zt(),ve=Wr.get(re);if(!ve)throw new Error("invalid session id");let Te=ve[0],Ce=fe._OrtEndProfiling(Te);Ce===0&&Ct("Can't get an profile file name."),fe._OrtFree(Ce)},ft=re=>{let fe=[];for(let ve of re){let Te=ve[2];!Array.isArray(Te)&&"buffer"in Te&&fe.push(Te.buffer)}return fe}}),Pe,Qe,Et,en,ln,$n,En,er,Ln,sr,Nn,Ds,qi,go,ri,Vu,xo,yo,Sc=h(()=>{nt(),be(),Hr(),Ur(),Pe=()=>!!I.wasm.proxy&&typeof document<"u",Et=!1,en=!1,ln=!1,er=new Map,Ln=(re,fe)=>{let ve=er.get(re);ve?ve.push(fe):er.set(re,[fe])},sr=()=>{if(Et||!en||ln||!Qe)throw new Error("worker not ready")},Nn=re=>{switch(re.data.type){case"init-wasm":Et=!1,re.data.err?(ln=!0,En[1](re.data.err)):(en=!0,En[0]()),$n&&(URL.revokeObjectURL($n),$n=void 0);break;case"init-ep":case"copy-from":case"create":case"release":case"run":case"end-profiling":{let fe=er.get(re.data.type);re.data.err?fe.shift()[1](re.data.err):fe.shift()[0](re.data.out);break}}},Ds=async()=>{if(!en){if(Et)throw new Error("multiple calls to 'initWasm()' detected.");if(ln)throw new Error("previous call to 'initWasm()' failed.");if(Et=!0,Pe())return new Promise((re,fe)=>{Qe==null||Qe.terminate(),_i().then(([ve,Te])=>{try{Qe=Te,Qe.onerror=Be=>fe(Be),Qe.onmessage=Nn,En=[re,fe];let Ce={type:"init-wasm",in:I};if(!Ce.in.wasm.wasmPaths&&ve){let Be=Fr();Be&&(Ce.in.wasm.wasmPaths=Be)}Qe.postMessage(Ce),$n=ve}catch(Ce){fe(Ce)}},fe)});try{await ti(I.wasm),await Ko(I),en=!0}catch(re){throw ln=!0,re}finally{Et=!1}}},qi=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("init-ep",[fe,ve]);let Te={type:"init-ep",in:{epName:re,env:I}};Qe.postMessage(Te)});await Ci(I,re)},go=async re=>Pe()?(sr(),new Promise((fe,ve)=>{Ln("copy-from",[fe,ve]);let Te={type:"copy-from",in:{buffer:re}};Qe.postMessage(Te,[re.buffer])})):on(re),ri=async(re,fe)=>{if(Pe()){if(fe!=null&&fe.preferredOutputLocation)throw new Error('session option "preferredOutputLocation" is not supported for proxy.');return sr(),new Promise((ve,Te)=>{Ln("create",[ve,Te]);let Ce={type:"create",in:{model:re,options:{...fe}}},Be=[];re instanceof Uint8Array&&Be.push(re.buffer),Qe.postMessage(Ce,Be)})}else return ds(re,fe)},Vu=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("release",[fe,ve]);let Te={type:"release",in:re};Qe.postMessage(Te)});Wi(re)},xo=async(re,fe,ve,Te,Ce,Be)=>{if(Pe()){if(ve.some(Re=>Re[3]!=="cpu"))throw new Error("input tensor on GPU is not supported for proxy.");if(Ce.some(Re=>Re))throw new Error("pre-allocated output tensor is not supported for proxy.");return sr(),new Promise((Re,Me)=>{Ln("run",[Re,Me]);let Fe=ve,et={type:"run",in:{sessionId:re,inputIndices:fe,inputs:Fe,outputIndices:Te,options:Be}};Qe.postMessage(et,ft(Fe))})}else return Ke(re,fe,ve,Te,Ce,Be)},yo=async re=>{if(Pe())return sr(),new Promise((fe,ve)=>{Ln("end-profiling",[fe,ve]);let Te={type:"end-profiling",in:re};Qe.postMessage(Te)});qr(re)}}),bl,vo,Ma,wl=h(()=>{nt(),Sc(),Bt(),St(),Si(),bl=(re,fe)=>{switch(re.location){case"cpu":return[re.type,re.dims,re.data,"cpu"];case"gpu-buffer":return[re.type,re.dims,{gpuBuffer:re.gpuBuffer},"gpu-buffer"];case"ml-tensor":return[re.type,re.dims,{mlTensor:re.mlTensor},"ml-tensor"];default:throw new Error(`invalid data location: ${re.location} for ${fe()}`)}},vo=re=>{switch(re[3]){case"cpu":return new Ne(re[0],re[2],re[1]);case"gpu-buffer":{let fe=re[0];if(!ki(fe))throw new Error(`not supported data type: ${fe} for deserializing GPU tensor`);let{gpuBuffer:ve,download:Te,dispose:Ce}=re[2];return Ne.fromGpuBuffer(ve,{dataType:fe,dims:re[1],download:Te,dispose:Ce})}case"ml-tensor":{let fe=re[0];if(!cs(fe))throw new Error(`not supported data type: ${fe} for deserializing MLTensor tensor`);let{mlTensor:ve,download:Te,dispose:Ce}=re[2];return Ne.fromMLTensor(ve,{dataType:fe,dims:re[1],download:Te,dispose:Ce})}default:throw new Error(`invalid data location: ${re[3]}`)}},Ma=class{async fetchModelAndCopyToWasmMemory(re){return go(await Gn(re))}async loadModel(re,fe){Rt();let ve;typeof re=="string"?ve=await this.fetchModelAndCopyToWasmMemory(re):ve=re,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await ri(ve,fe),He()}async dispose(){return Vu(this.sessionId)}async run(re,fe,ve){Rt();let Te=[],Ce=[];Object.entries(re).forEach(tt=>{let Xe=tt[0],At=tt[1],ze=this.inputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid input '${Xe}'`);Te.push(At),Ce.push(ze)});let Be=[],Re=[];Object.entries(fe).forEach(tt=>{let Xe=tt[0],At=tt[1],ze=this.outputNames.indexOf(Xe);if(ze===-1)throw new Error(`invalid output '${Xe}'`);Be.push(At),Re.push(ze)});let Me=Te.map((tt,Xe)=>bl(tt,()=>`input "${this.inputNames[Ce[Xe]]}"`)),Fe=Be.map((tt,Xe)=>tt?bl(tt,()=>`output "${this.outputNames[Re[Xe]]}"`):null),et=await xo(this.sessionId,Ce,Me,Re,Fe,ve),it={};for(let tt=0;tt<et.length;tt++)it[this.outputNames[Re[tt]]]=Be[tt]??vo(et[tt]);return He(),it}startProfiling(){}endProfiling(){yo(this.sessionId)}}}),Ei={};m(Ei,{OnnxruntimeWebAssemblyBackend:()=>Ni,initializeFlags:()=>Vi,wasmBackend:()=>bo});var Vi,Ni,bo,Cc=h(()=>{nt(),Sc(),wl(),Vi=()=>{(typeof I.wasm.initTimeout!="number"||I.wasm.initTimeout<0)&&(I.wasm.initTimeout=0);let re=I.wasm.simd;if(typeof re!="boolean"&&re!==void 0&&re!=="fixed"&&re!=="relaxed"&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${re}". Reset it to \`false\` and ignore SIMD feature checking.`),I.wasm.simd=!1),typeof I.wasm.proxy!="boolean"&&(I.wasm.proxy=!1),typeof I.wasm.trace!="boolean"&&(I.wasm.trace=!1),typeof I.wasm.numThreads!="number"||!Number.isInteger(I.wasm.numThreads)||I.wasm.numThreads<=0)if(typeof self<"u"&&!self.crossOriginIsolated)I.wasm.numThreads=1;else{let fe=typeof navigator>"u"?u("node:os").cpus().length:navigator.hardwareConcurrency;I.wasm.numThreads=Math.min(4,Math.ceil((fe||1)/2))}},Ni=class{async init(re){Vi(),await Ds(),await qi(re)}async createInferenceSessionHandler(re,fe){let ve=new Ma;return await ve.loadModel(re,fe),ve}},bo=new Ni}),jc={};m(jc,{InferenceSession:()=>yt,TRACE:()=>lt,TRACE_EVENT_BEGIN:()=>vt,TRACE_EVENT_END:()=>st,TRACE_FUNC_BEGIN:()=>Rt,TRACE_FUNC_END:()=>He,Tensor:()=>Ne,default:()=>kl,env:()=>I,registerBackend:()=>E}),nt(),nt(),nt();var _l="1.26.0",kl=Tr;{let re=(Cc(),g(Ei)).wasmBackend;E("cpu",re,10),E("wasm",re,10)}return Object.defineProperty(I.versions,"web",{value:_l,enumerable:!0}),g(jc)})();e.exports=r})(Mv)),Mv.exports}var P_;function fT(){return P_||(P_=1,(function(e){var n=rl&&rl.__createBinding||(Object.create?(function(C,N,$,R){R===void 0&&(R=$);var O=Object.getOwnPropertyDescriptor(N,$);(!O||("get"in O?!N.__esModule:O.writable||O.configurable))&&(O={enumerable:!0,get:function(){return N[$]}}),Object.defineProperty(C,R,O)}):(function(C,N,$,R){R===void 0&&(R=$),C[R]=N[$]})),r=rl&&rl.__setModuleDefault||(Object.create?(function(C,N){Object.defineProperty(C,"default",{enumerable:!0,value:N})}):function(C,N){C.default=N}),i=rl&&rl.__importStar||function(C){if(C&&C.__esModule)return C;var N={};if(C!=null)for(var $ in C)$!=="default"&&Object.prototype.hasOwnProperty.call(C,$)&&n(N,C,$);return r(N,C),N};Object.defineProperty(e,"__esModule",{value:!0}),e.MicVAD=e.getDefaultRealTimeVADOptions=e.ort=e.DEFAULT_MODEL=void 0;const o=i(hT()),l=Zw(),d=e0(),u=Qm(),h=Ky(),m=L2(),x=z2();e.DEFAULT_MODEL="legacy",e.ort=o;const g="vad.worklet.bundle.min.js",v="silero_vad_v5.onnx",S="silero_vad_legacy.onnx",E=C=>({...d.defaultFrameProcessorOptions,onFrameProcessed:()=>{},onVADMisfire:()=>{u.log.debug("VAD misfire")},onSpeechStart:()=>{u.log.debug("Detected speech start")},onSpeechEnd:()=>{u.log.debug("Detected speech end")},onSpeechRealStart:()=>{u.log.debug("Detected real speech start")},baseAssetPath:"./",onnxWASMBasePath:"./",model:C,workletOptions:{},getStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),pauseStream:async N=>{N.getTracks().forEach($=>{$.stop()})},resumeStream:async()=>await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0}}),ortConfig:N=>{N.env.logLevel="error"},startOnLoad:!0,processorType:"auto"});e.getDefaultRealTimeVADOptions=E;const j=C=>"audioWorklet"in C&&typeof AudioWorkletNode=="function"?"AudioWorklet":"ScriptProcessor";async function y(C,N,$,R,O){await $.audioWorklet.addModule(C),N.processorOptions={...N.processorOptions??{},frameSamples:R};const I=new AudioWorkletNode($,"vad-helper-worklet",N);return I.port.onmessage=async z=>{const U=z.data;if(!(typeof U=="object"&&U&&"message"in U)){console.error("Invalid message event",U);return}switch(U.message){case h.Message.AudioFrame:{if(!("data"in U&&U.data instanceof ArrayBuffer)){console.log("Audio frame message has no data");return}const W=new Float32Array(U.data);await O(W);break}}},I}async function b(C,N,$){const R=new x.Resampler({nativeSampleRate:C.sampleRate,targetSampleRate:16e3,targetFrameSize:N});u.log.debug("using script processor");const I=C.createScriptProcessor(4096,1,1);let z=!1;return I.onaudioprocess=async U=>{if(!z){z=!0;try{const W=U.inputBuffer.getChannelData(0);U.outputBuffer.getChannelData(0).fill(0);const V=R.process(W);for(const H of V)await $(H)}catch(W){console.error("Error processing audio:",W)}finally{z=!1}}},I.connect(C.destination),I}class _{constructor(N,$,R,O,I=!1,z=null,U=null,W=null,Y=null,V=null,H=null,te="uninitialized",ae=!1){this.options=N,this.frameProcessor=$,this.model=R,this.frameSamples=O,this.listening=I,this.errored=z,this._stream=U,this._audioContext=W,this._vadNode=Y,this._mediaStreamAudioSourceNode=V,this._audioProcessorAdapterType=H,this.initializationState=te,this.ownsAudioContext=ae,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=oe=>{this.initializationState="errored",this.errored=oe},this.start=async()=>{switch(this.initializationState){case"uninitialized":{u.log.debug("initializing micVAD"),this.initializationState="initializing",this.frameProcessor.resume();try{this._stream=await this.options.getStream()}catch(oe){throw oe instanceof Error?this.setErrored(oe.message):this.setErrored(String(oe)),oe}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"?j(this._audioContext):this.options.processorType,this._audioProcessorAdapterType){case"AudioWorklet":this._vadNode=await y(this.options.baseAssetPath+g,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),u.log.debug("started micVAD"),this.listening=!0,this.initializationState="initialized";break}case"initializing":{u.log.warn("start called while initializing");break}case"initialized":{if(this.listening)return;this.listening=!0,this.frameProcessor.resume();const{stream:oe,audioContext:ie,vadNode:X}=this.getAudioInstances();this._stream=await this.options.resumeStream(oe);const Q=new MediaStreamAudioSourceNode(ie,{mediaStream:this._stream});this._mediaStreamAudioSourceNode=Q,Q.connect(X);break}case"destroyed":{u.log.warn("start called after destroyed");break}case"errored":{u.log.error("start called after errored");break}default:{u.log.warn("weird initialization state");break}}},this.pause=async()=>{if(!this.listening)return;this.listening=!1;const{stream:oe,mediaStreamAudioSourceNode:ie}=this.getAudioInstances();await this.options.pauseStream(oe),ie.disconnect(),this.frameProcessor.pause(this.handleFrameProcessorEvent)},this.destroy=async()=>{var ie;u.log.debug("destroy called"),this.initializationState="destroyed";const{vadNode:oe}=this.getAudioInstances();oe instanceof AudioWorkletNode&&oe.port.postMessage(h.Message.SpeechStop),this.listening&&await this.pause(),await this.model.release(),this.ownsAudioContext&&await((ie=this._audioContext)==null?void 0:ie.close())},this.setOptions=oe=>{this.frameProcessor.setOptions(oe)},this.processFrame=async oe=>{await this.frameProcessor.process(oe,this.handleFrameProcessorEvent)},this.handleFrameProcessorEvent=oe=>{switch(oe.msg){case h.Message.FrameProcessed:this.options.onFrameProcessed(oe.probs,oe.frame);break;case h.Message.SpeechStart:this.options.onSpeechStart();break;case h.Message.SpeechRealStart:this.options.onSpeechRealStart();break;case h.Message.VADMisfire:this.options.onVADMisfire();break;case h.Message.SpeechEnd:this.options.onSpeechEnd(oe.audio);break}}}static async new(N={}){const $={...(0,e.getDefaultRealTimeVADOptions)(N.model??e.DEFAULT_MODEL),...N};(0,d.validateOptions)($),e.ort.env.wasm.wasmPaths=$.onnxWASMBasePath,$.ortConfig!==void 0&&$.ortConfig(e.ort);const R=$.model==="v5"?v:S,O=$.baseAssetPath+R,I=$.model==="v5"?m.SileroV5.new:m.SileroLegacy.new;let z;try{z=await I(e.ort,()=>(0,l.defaultModelFetcher)(O))}catch(H){throw console.error(`Encountered an error while loading model file ${O}`),H}const U=$.model==="v5"?512:1536,W=U/16,Y=new d.FrameProcessor(z.process,z.reset_state,{positiveSpeechThreshold:$.positiveSpeechThreshold,negativeSpeechThreshold:$.negativeSpeechThreshold,redemptionMs:$.redemptionMs,preSpeechPadMs:$.preSpeechPadMs,minSpeechMs:$.minSpeechMs,submitUserSpeechOnPause:$.submitUserSpeechOnPause},W),V=new _($,Y,z,U);if($.startOnLoad)try{await V.start()}catch(H){throw console.error("Error starting micVad",H),H}return V}}e.MicVAD=_})(rl)),rl}var D_;function pT(){return D_||(D_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.getDefaultRealTimeVADOptions=e.MicVAD=e.DEFAULT_MODEL=e.utils=e.NonRealTimeVAD=e.Message=e.FrameProcessor=e.defaultModelFetcher=e.baseAssetPath=void 0;var n=P2();Object.defineProperty(e,"baseAssetPath",{enumerable:!0,get:function(){return n.baseAssetPath}});var r=Zw();Object.defineProperty(e,"defaultModelFetcher",{enumerable:!0,get:function(){return r.defaultModelFetcher}});var i=e0();Object.defineProperty(e,"FrameProcessor",{enumerable:!0,get:function(){return i.FrameProcessor}});var o=Ky();Object.defineProperty(e,"Message",{enumerable:!0,get:function(){return o.Message}});var l=uT();Object.defineProperty(e,"NonRealTimeVAD",{enumerable:!0,get:function(){return l.NonRealTimeVAD}});const d=dT();e.utils={audioFileToArray:d.audioFileToArray,minFramesForTargetMS:d.minFramesForTargetMS,arrayBufferToBase64:d.arrayBufferToBase64,encodeWAV:d.encodeWAV};var u=fT();Object.defineProperty(e,"DEFAULT_MODEL",{enumerable:!0,get:function(){return u.DEFAULT_MODEL}}),Object.defineProperty(e,"MicVAD",{enumerable:!0,get:function(){return u.MicVAD}}),Object.defineProperty(e,"getDefaultRealTimeVADOptions",{enumerable:!0,get:function(){return u.getDefaultRealTimeVADOptions}})})($v)),$v}var mT=pT();function ox(e,n,r,i){var l,d;try{(d=(l=window.api)==null?void 0:l.logs)==null||d.write(e,n,r,i)}catch{}const o=n==="error"?console.error:n==="warn"?console.warn:console.log;i!==void 0?o(`[${e}]`,r,i):o(`[${e}]`,r)}const dt={debug:(e,n,r)=>ox(e,"debug",n,r),info:(e,n,r)=>ox(e,"info",n,r),warn:(e,n,r)=>ox(e,"warn",n,r),error:(e,n,r)=>ox(e,"error",n,r)},F2=16e3,gT=6,Ch=F2*gT,xT=400,yT=F2*xT/1e3,O_=300,L_=2e3,z_=1500,B_=3e3,vT=600,U2=.5,H2=.35,F_=.85,U_=.7;let gi=null,wa=!1,Xs=!1;const Bb=new Set;function ax(e){for(const n of Array.from(Bb))try{n(e)}catch(r){dt.warn("speech","workerDeath listener threw",{error:r instanceof Error?r.message:String(r)})}}let Iv=0;const H_=2;let Bh=!1,W2=!1;function q2(e){e.addEventListener("message",n=>{var i;if(((i=n.data)==null?void 0:i.type)!=="log")return;const r=n.data.level||"info";dt[r]("whisperWorker",n.data.message??"",n.data.meta)}),e.addEventListener("error",n=>{dt.error("whisperWorker","worker error event (fatal)",{message:n.message,filename:n.filename,lineno:n.lineno}),bT(`error:${n.message||"unknown"}`)})}function fy(){return gi||(gi=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),q2(gi),dt.info("speech","worker spawned"),gi)}let lx=!1;function bT(e){if(!Bh){if(lx){dt.warn("speech","respawnWorker: already in flight, ignoring",{reason:e});return}if(lx=!0,Iv+=1,W2=!0,dt.warn("speech","respawnWorker: starting",{reason:e,attempt:Iv}),ax({reason:e,respawned:!1,finalOnly:!0}),Iv>H_){if(Bh=!0,dt.error("speech","respawnWorker: limit exceeded, disabling speech",{limit:H_}),gi)try{gi.terminate()}catch{}gi=null,wa=!1,Xs=!1,ax({reason:"respawn-limit-exceeded",respawned:!1,finalOnly:!0}),lx=!1;return}if(gi)try{gi.terminate()}catch{}gi=null,wa=!1,Xs=!1;try{gi=new Worker(new URL(""+new URL("whisperWorker-Dbia1OpC.js",import.meta.url).href,import.meta.url),{type:"module"}),q2(gi),Xs=!0,gi.postMessage({type:"load"}),dt.info("speech","respawnWorker: new worker spawned, load posted"),ax({reason:e,respawned:!0,finalOnly:!0})}catch(n){Bh=!0,dt.error("speech","respawnWorker: spawn failed, disabling speech",{error:n instanceof Error?n.message:String(n)}),ax({reason:"spawn-failed",respawned:!1,finalOnly:!0})}finally{lx=!1}}}function wT(e,n){if(wa||Xs)return;Xs=!0;const r=fy();dt.info("speech","preloadModel: posting load");const i=o=>{o.data.type==="status"?(e==null||e(o.data.status,o.data.message),o.data.status==="ready"&&(wa=!0,Xs=!1,dt.info("speech","preloadModel: ready"),r.removeEventListener("message",i))):o.data.type==="progress"?n==null||n(o.data.pct):o.data.type==="error"&&(Xs=!1,dt.error("speech","preloadModel: worker reported error",{error:o.data.error}),e==null||e("error",o.data.error),r.removeEventListener("message",i))};r.addEventListener("message",i),r.postMessage({type:"load"})}function _T(){dt.info("speech","resetModel: clearing load flags"),wa=!1,Xs=!1}function Xy(){var e;return typeof Worker<"u"&&!!((e=navigator.mediaDevices)!=null&&e.getUserMedia)&&typeof AudioWorkletNode<"u"}function kT(e){const n=fy();return!wa&&!Xs&&(Xs=!0,n.postMessage({type:"load"})),new Promise((r,i)=>{const o=l=>{var d,u,h;((d=l.data)==null?void 0:d.type)==="result"?(n.removeEventListener("message",o),r((l.data.text??"").trim())):((u=l.data)==null?void 0:u.type)==="error"?(n.removeEventListener("message",o),i(new Error(String(l.data.error??"Transcription failed")))):((h=l.data)==null?void 0:h.type)==="status"&&l.data.status==="ready"&&(wa=!0,Xs=!1)};n.addEventListener("message",o),n.postMessage({type:"transcribe",audio:e},[e.buffer])})}function V2(e){let n=fy(),r=!1,i=null,o=null,l=null,d=null,u=null;const h=[],m=new Set;let x=null,g=0,v=!1,S=0,E=!1,j=!1,y=0,b=0,_=0,C=-1,N=O_,$=0,R=null,O="",I="",z=!1,U=0;function W(ce,pe){const Ae=Math.min(ce.length,pe.length);let Se=0;for(;Se<Ae&&ce.charCodeAt(Se)===pe.charCodeAt(Se);)Se++;return Se}function Y(ce){const pe=W(O,ce);return O=ce,pe>I.length&&(I=ce.slice(0,pe)),I.length>ce.length&&(I=ce),I}const V=()=>(x||(x=new Float32Array(Ch)),x),H=()=>{g=0},te=ce=>{const pe=V(),Ae=ce.length;if(Ae>=Ch){pe.set(ce.subarray(Ae-Ch)),g=Ch;return}if(g+Ae<=Ch){pe.set(ce,g),g+=Ae;return}const Se=g+Ae-Ch;pe.copyWithin(0,Se,g),g-=Se,pe.set(ce,g),g+=Ae},ae=()=>{R&&(clearTimeout(R),R=null)},oe=()=>{ae(),v=!1,E=!1,j=!1,N=O_,O="",I="",z=!1,U=0,H()},ie=()=>{if(r||!v||j||E||R)return;if(g<yT){R=setTimeout(()=>{R=null,ie()},N);return}const ce=performance.now()-y;if(ce<N&&y!==0){R=setTimeout(()=>{R=null,ie()},N-ce);return}if(W2||Bh||e.partialsEnabled&&!e.partialsEnabled())return;const pe=V(),Ae=new Float32Array(g);Ae.set(pe.subarray(0,g)),b+=1,_=b,E=!0,$=performance.now(),y=$,n.postMessage({type:"transcribe-partial",audio:Ae,seq:b},[Ae.buffer])},X=ce=>ce.length===0?Promise.resolve():Bh?(dt.warn("speech","transcribeAudio: speech disabled (worker respawn limit hit)"),r||e.onError("Speech recognition disabled — please reload the app."),Promise.resolve()):new Promise(pe=>{h.push(pe),b+=1;const Ae=b;C=Ae,n.postMessage({type:"transcribe",audio:ce,seq:Ae},[ce.buffer])}),Q=ce=>{const pe=X(ce);return m.add(pe),pe.finally(()=>{m.delete(pe)}),pe},J=ce=>{var pe,Ae,Se,ye,ne;if(ce.data.type==="result"){const we=ce.data.text,Ne=ce.data.seq??0;Ne&&Ne<C&&dt.warn("speech","result: seq below latestFinalSeq (delivering anyway)",{seq:Ne,latestFinalSeq:C}),!r&&we&&e.onFinal(we),(pe=h.shift())==null||pe()}else if(ce.data.type==="partial"){const we=ce.data.seq??0,Ne=ce.data.text??"",Je=performance.now()-$;E=!1,Je>=B_?(j=!0,dt.warn("speech","partials.disabled.budget",{elapsedMs:Math.round(Je),seq:we})):Je>=z_&&(N=Math.min(N*2,L_),dt.warn("speech","partials.slowdown",{elapsedMs:Math.round(Je),newIntervalMs:N,seq:we})),z||(z=!0,Je>vT&&N<500&&(N=500,dt.info("speech","partials.probe.slow_host",{elapsedMs:Math.round(Je),newIntervalMs:500})));const lt=we!==_||we<=C;if(!r&&!lt&&Ne){const xt=Y(Ne);xt&&((Ae=e.onPartial)==null||Ae.call(e,xt),U===0&&(U=performance.now(),dt.info("speech","partial.first",{msSinceSpeechStart:Math.round(U-S)})))}ie()}else if(ce.data.type==="partial-error"){const we=performance.now()-$;E=!1,we>=B_?(j=!0,dt.warn("speech","partials.disabled.budget (after error)",{elapsedMs:Math.round(we),seq:ce.data.seq})):we>=z_&&(N=Math.min(N*2,L_),dt.warn("speech","partials.slowdown (after error)",{elapsedMs:Math.round(we),newIntervalMs:N,seq:ce.data.seq})),dt.warn("speech","partial encode failed",{error:ce.data.error,seq:ce.data.seq}),ie()}else ce.data.type==="error"?(r||e.onError(ce.data.error),(Se=h.shift())==null||Se()):ce.data.type==="status"?(r||(ye=e.onModelStatus)==null||ye.call(e,ce.data.status,ce.data.message),ce.data.status==="ready"&&(wa=!0,Xs=!1)):ce.data.type==="progress"&&(r||(ne=e.onProgress)==null||ne.call(e,ce.data.pct))};n.addEventListener("message",J);const le=ce=>{var pe,Ae;if(!r){for(dt.warn("speech","createRecognition: worker death event",ce),(pe=e.onStatusChange)==null||pe.call(e,"restarting");h.length;)(Ae=h.shift())==null||Ae();if(m.clear(),ae(),E=!1,ce.respawned){try{n.removeEventListener("message",J)}catch{}n=fy(),n.addEventListener("message",J)}}};return Bb.add(le),{start:async()=>{if(!r){if(Bh){e.onError("Speech recognition disabled — please reload the app.");return}!wa&&!Xs&&(Xs=!0,dt.info("speech","createRecognition.start: triggering model load"),n.postMessage({type:"load"})),dt.info("speech","createRecognition.start: initializing VAD",{modelReady:wa,modelLoading:Xs});try{const ce=new URL("vad/",document.baseURI).href,pe=e.inputDeviceId||null,Ae={channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0};pe&&(Ae.deviceId={exact:pe}),dt.info("speech","getUserMedia",{hasDeviceId:!!pe,deviceIdPrefix:pe?pe.slice(0,8):null});const Se=await navigator.mediaDevices.getUserMedia({audio:Ae});o=Se,l=new AudioContext;for(const ye of Se.getAudioTracks())ye.addEventListener("ended",()=>{r||(dt.warn("speech","mic track ended (permission revoked or device removed)"),e.onError("Microphone disconnected or permission revoked"))});try{u=l.createMediaStreamSource(o),d=l.createAnalyser(),d.fftSize=2048,d.smoothingTimeConstant=.3,u.connect(d)}catch(ye){dt.warn("speech","analyser init failed",{error:ye instanceof Error?ye.message:String(ye)}),u=null,d=null}i=await mT.MicVAD.new({audioContext:l,getStream:async()=>Se,resumeStream:async()=>Se,pauseStream:async()=>{},baseAssetPath:ce,onnxWASMBasePath:ce,model:"v5",positiveSpeechThreshold:U2,negativeSpeechThreshold:H2,minSpeechMs:300,redemptionMs:1500,preSpeechPadMs:300,submitUserSpeechOnPause:!0,onFrameProcessed:(ye,ne)=>{var we;r||((we=e.onFrame)==null||we.call(e,ye),v&&(te(ne),ie()))},onSpeechStart:()=>{var ye;r||(oe(),v=!0,S=performance.now(),(ye=e.onSpeechStart)==null||ye.call(e))},onSpeechEnd:ye=>{var ne;r||((ne=e.onStatusChange)==null||ne.call(e,"transcribing"),oe(),Q(ye))},onVADMisfire:()=>{var ye,ne;r||((ye=e.onStatusChange)==null||ye.call(e,"idle"),oe(),(ne=e.onMisfire)==null||ne.call(e))}}),i.start()}catch(ce){const pe=ce instanceof Error?ce.message:"Microphone access denied",Ae=ce instanceof Error?ce.stack:"";if(dt.error("speech","createRecognition.start: VAD init failed",{error:pe,stack:Ae}),d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(o){try{o.getTracks().forEach(Se=>Se.stop())}catch{}o=null}if(l){try{await l.close()}catch{}l=null}e.onError(pe)}}},stop:async()=>{if(i)try{await i.pause()}catch{}for(oe();m.size>0;)await Promise.all(Array.from(m));if(i){try{await i.destroy()}catch{}i=null}if(d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(o){try{o.getTracks().forEach(ce=>ce.stop())}catch{}o=null}if(l){try{await l.close()}catch{}l=null}},setVadThresholds:(ce,pe)=>{if(i)try{i.setOptions({positiveSpeechThreshold:ce,negativeSpeechThreshold:pe})}catch(Ae){dt.warn("speech","setVadThresholds failed",{error:Ae instanceof Error?Ae.message:String(Ae)})}},getAnalyser:()=>d,destroy:()=>{if(r=!0,oe(),i){try{i.destroy()}catch{}i=null}if(d){try{d.disconnect()}catch{}d=null}if(u){try{u.disconnect()}catch{}u=null}if(l){try{l.close()}catch{}l=null}if(o){try{o.getTracks().forEach(ce=>ce.stop())}catch{}o=null}Bb.delete(le),n.removeEventListener("message",J)}}}let Am=null;const Fb=new Set,Ub=new Set;function ST(){for(const e of Fb)try{e()}catch{}}function Hb(){for(const e of Ub)try{e()}catch{}}function CT(e){return e.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 jT(e){if(!window.speechSynthesis)return;const n=CT(e);if(!n)return;const r=new SpeechSynthesisUtterance(n);r.rate=1,r.pitch=1,r.onstart=()=>{Am=performance.now(),ST()},r.onend=()=>{!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Am=null,Hb())},r.onerror=i=>{i.error!=="canceled"&&!window.speechSynthesis.speaking&&!window.speechSynthesis.pending&&(Am=null,Hb())},window.speechSynthesis.speak(r)}function G2(){window.speechSynthesis&&(window.speechSynthesis.cancel(),Am=null,Hb())}function K2(){var e;return((e=window.speechSynthesis)==null?void 0:e.speaking)??!1}function ET(){return Am}function NT(e){return Fb.add(e),()=>{Fb.delete(e)}}function TT(e){return Ub.add(e),()=>{Ub.delete(e)}}function $T(e){K2()&&(e.setVadThresholds(F_,U_),dt.info("voice","tts.duck.on",{reason:"already-speaking-on-attach"}));const n=NT(()=>{e.setVadThresholds(F_,U_),dt.info("voice","tts.duck.on")}),r=TT(()=>{e.setVadThresholds(U2,H2),dt.info("voice","tts.duck.off")});return()=>{n(),r()}}const AT=[{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 RT(e){const n=e.trim();return AT.find(r=>r.match.test(n))??null}const MT=4e4;let Tu=null;function Fh(){Tu&&clearTimeout(Tu),Tu=setTimeout(()=>{Tu=null,$t.getState().stopRecording()},MT)}function cx(){Tu&&(clearTimeout(Tu),Tu=null)}let mc=null,fc=null;const IT=.04,PT=.3;let py=0,Wb=0;function DT(e){fc!==null&&cancelAnimationFrame(fc);const n=()=>{if(mc===null||$t.getState().submitCountdownStartAt===null){fc=null;return}const r=performance.now();if(r-Wb<200&&py>PT){const o=r-e;dt.info("voice","submit.preempted_by_voice",{reason:"vad",prob:py.toFixed(2),msIntoCountdown:Math.round(o)}),lc(),Fh();return}const i=X2();if(i){const o=new Uint8Array(i.fftSize);i.getByteTimeDomainData(o);let l=0;for(let u=0;u<o.length;u++){const h=(o[u]-128)/128;l+=h*h}const d=Math.sqrt(l/o.length);if(d>IT){const u=r-e;dt.info("voice","submit.preempted_by_voice",{reason:"rms",rms:d.toFixed(3),msIntoCountdown:Math.round(u)}),lc(),Fh();return}}fc=requestAnimationFrame(n)};fc=requestAnimationFrame(n)}function OT(e){mc&&clearTimeout(mc);const n=$t.getState().submitDelayMs,r=performance.now();$t.setState({submitCountdownStartAt:r}),mc=setTimeout(()=>{mc=null,$t.setState({submitCountdownStartAt:null});try{window.api.pty.write({tabId:e,data:"\r"})}catch(i){dt.warn("voice","submit pty.write failed",{error:i instanceof Error?i.message:String(i)})}Fh()},n),DT(r)}function lc(){fc!==null&&(cancelAnimationFrame(fc),fc=null),mc&&(clearTimeout(mc),mc=null),$t.getState().submitCountdownStartAt!==null&&$t.setState({submitCountdownStartAt:null})}let rs=null,As=null;function X2(){var e;return((e=rs==null?void 0:rs.getAnalyser)==null?void 0:e.call(rs))??null}const ux=1e4;let Rm=null;function dx(){Rm&&(clearTimeout(Rm),Rm=null)}let Yx=null,Jx=null;function hx(){Yx=null,Jx&&(Jx(),Jx=null)}const LT=1500,zT=9e4;let fx=0,Qx=null,qb=-1;function px(){Qx&&(clearTimeout(Qx),Qx=null,qb=-1)}const BT=new Set(["you","You","Thank you.","Thanks for watching.","Thanks for watching!","Thank you for watching.","Thank you for watching!",".","Bye.","Bye!"]),$t=cr((e,n)=>({isRecording:!1,externalRecording:!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(n().modelStatus!=="idle")return;dt.info("voice","initModel: kicking off preload"),e({modelStatus:"loading",error:null,errorKind:null,loadingProgress:0});const r=++fx,i=()=>{r===fx&&(px(),qb=r,Qx=setTimeout(()=>{qb===r&&n().modelStatus==="loading"&&(dt.warn("voice","mic.gate.timeout: no progress within 90s"),e({modelStatus:"error",error:"Model load timed out",errorKind:"timeout"}))},zT))};i(),wT((o,l)=>{r===fx&&(o==="ready"?(px(),dt.info("voice","modelStatus -> ready"),e({modelStatus:"ready",loadingProgress:100,errorKind:null})):o==="error"?(px(),dt.error("voice","modelStatus -> error",{msg:l}),e({modelStatus:"error",error:l,errorKind:"load"})):(i(),e({modelStatus:"loading"})))},o=>{r===fx&&(i(),e({loadingProgress:Math.round(o)}))})},resetAndRetryModel:()=>{dt.info("voice","mic.gate.retry"),px(),_T(),e({modelStatus:"idle",error:null,errorKind:null,loadingProgress:0}),n().initModel()},startRecording:r=>{if(n().isRecording)return;if(rs){dt.warn("voice","startRecording: prior handle still draining, ignoring");return}if(!Xy()){e({error:"Microphone or Web Worker not available",errorKind:"recording"});return}const i=o=>{try{const l=V2({inputDeviceId:o,onStatusChange:d=>{e(d==="transcribing"?{statusPill:"transcribing"}:d==="restarting"?{statusPill:"restarting"}:{statusPill:"idle"})},onPartial:d=>{n().partialsEnabled&&e({lastPartial:d})},partialsEnabled:()=>n().partialsEnabled,onFrame:d=>{py=d.isSpeech,Wb=performance.now()},onSpeechStart:()=>{if(e({statusPill:"listening",lastPartial:""}),cx(),lc(),K2()){const u=ET(),h=u!==null?performance.now()-u:null;G2(),e({lastBargeInAt:performance.now()}),dt.info("voice","barge-in",{tabId:r,utteranceOffsetMs:h})}else dt.debug("voice","barge-in.no-op",{tabId:r})},onMisfire:()=>{e({lastPartial:"",statusPill:"idle"}),Fh();const d=n().lastBargeInAt;d!==null&&performance.now()-d<600&&dt.warn("voice","barge-in.misfire",{tabId:r,sinceBargeInMs:Math.round(performance.now()-d)})},onFinal:d=>{Fh();const u=d.trim();if(!u||BT.has(u)){e({lastTranscript:"",lastPartial:"",statusPill:"idle"});return}const h=RT(u);if(h){dt.info("voice","voice-command",{tabId:r,label:h.label,transcript:u}),window.api.pty.write({tabId:r,data:h.data}),e({lastTranscript:"",lastPartial:"",statusPill:"idle"}),lc();const x=window;x.__transcripts&&(x.__transcripts.push({tabId:r,text:u}),x.__transcripts.length>500&&x.__transcripts.shift());return}window.api.pty.write({tabId:r,data:u}),e({lastTranscript:"",lastPartial:"",statusPill:"idle"}),n().autoSubmit&&OT(r);const m=window;m.__transcripts&&(m.__transcripts.push({tabId:r,text:u}),m.__transcripts.length>500&&m.__transcripts.shift())},onError:d=>{dt.error("voice","recognition error",{err:d}),lc(),e({error:d,errorKind:"recording",isRecording:!1,lastPartial:"",statusPill:"idle"}),As==null||As(),As=null,cx(),rs==null||rs.destroy(),rs=null,Le.error(`Microphone error: ${d}`)},onModelStatus:d=>{d==="ready"?e({modelStatus:"ready",loadingProgress:100}):d==="loading"&&e({modelStatus:"loading"})},onProgress:d=>e({loadingProgress:Math.round(d)})});rs=l,e({isRecording:!0,error:null,lastTranscript:"",lastPartial:"",statusPill:"listening"}),Fh(),l.start().then(()=>{rs===l&&(As==null||As(),As=$T(l))}).catch(d=>{const u=d instanceof Error?d.message:String(d);dt.error("voice","handle.start() failed",{error:u}),Le.error(`Could not start mic: ${u}`)})}catch(l){e({error:l instanceof Error?l.message:"Failed to start recording",errorKind:"recording"})}};Promise.resolve().then(()=>{var o,l,d;return((d=(l=(o=window.api)==null?void 0:o.voice)==null?void 0:l.getDevicePref)==null?void 0:d.call(l))??Promise.resolve(null)}).then(o=>i((o==null?void 0:o.selectedDeviceId)??null)).catch(o=>{dt.warn("voice","getDevicePref failed; using default device",{error:o instanceof Error?o.message:String(o)}),i(null)})},stopRecording:()=>{const r=rs;r&&(cx(),lc(),py=0,Wb=0,As==null||As(),As=null,e({isRecording:!1,lastTranscript:"",lastPartial:"",statusPill:"idle"}),r.stop().finally(()=>{r.destroy(),rs===r&&(rs=null),n().hotkeyState==="stopping"&&(dx(),e({hotkeyState:"idle"}))}))},restartWithDevice:async()=>{if(!n().isRecording)return;const r=rs;if(!r)return;cx(),As==null||As(),As=null,e({isRecording:!1,lastTranscript:"",lastPartial:""});try{await r.stop()}catch(l){dt.warn("voice","restartWithDevice: drain rejected",{error:l instanceof Error?l.message:String(l)})}r.destroy(),rs===r&&(rs=null);const{useSessions:i}=await Jm(async()=>{const{useSessions:l}=await Promise.resolve().then(()=>qN);return{useSessions:l}},[],import.meta.url),o=i.getState().activeTabId;o&&n().startRecording(o)},setExternalRecording:r=>e({externalRecording:r}),toggleTTS:()=>e(r=>({ttsEnabled:!r.ttsEnabled})),setAutoSubmit:r=>e({autoSubmit:r}),setSubmitDelayMs:r=>e({submitDelayMs:Math.max(500,Math.min(13e3,Math.floor(r)))}),cancelSubmit:()=>lc(),setPartialsEnabled:r=>{n().partialsEnabled!==r&&(e({partialsEnabled:r}),r||e({lastPartial:""}))},clearError:()=>e({error:null,errorKind:null}),setPermissionState:r=>{n().permissionState!==r&&(dt.info("voice","mic.gate.permission_changed",{from:n().permissionState,to:r}),e({permissionState:r}))},setLevelMeterEnabled:r=>{n().levelMeterEnabled!==r&&e({levelMeterEnabled:r})},setTurnDetectorRuntimeState:r=>{n().turnDetectorState!==r&&(e({turnDetectorState:r}),r==="load_failed"?dt.warn("voice-turn","voice-turn.load_failed"):r==="runtime_error"?dt.warn("voice-turn","voice-turn.runtime_error"):r==="disabled"&&dt.info("voice-turn","voice-turn.fallback_to_vad"))},setWizardArmed:r=>{n().wizardArmed!==r&&e({wizardArmed:r})},openWizard:()=>{n().wizardOpen||e({wizardOpen:!0})},closeWizard:()=>{n().wizardOpen&&e({wizardOpen:!1})},armHotkey:({phase:r,source:i,mode:o,tabId:l})=>{const d=n(),{canRecord:u,reason:h}=Vb(d);if(r==="down"){if(h==="error"||h==="load-timeout"){d.resetAndRetryModel(),dt.info("voice-hotkey","down.retry",{source:i,reason:h});return}if(!u&&h!=="loading"){dt.warn("voice-hotkey","miss-model-loading",{modelStatus:d.modelStatus,reason:h});return}if(d.hotkeyState==="recording"||d.isRecording){(o==="toggle"||i==="global")&&(e({hotkeyState:"stopping"}),dx(),Rm=setTimeout(()=>{n().hotkeyState==="stopping"&&(dt.warn("voice-hotkey","drain-timeout",{durationMs:ux}),e({hotkeyState:"aborted"}),setTimeout(()=>{n().hotkeyState==="aborted"&&e({hotkeyState:"idle"})},0))},ux),d.stopRecording());return}if(h==="loading"){d.hotkeyState!=="armed"&&(e({hotkeyState:"armed"}),dt.info("voice-hotkey","armed",{source:i,modelStatus:d.modelStatus})),hx(),Yx={tabId:l,source:i,mode:o},Jx=$t.subscribe((m,x)=>{if(Yx&&m.modelStatus==="ready"&&x.modelStatus!=="ready"&&m.hotkeyState==="armed"){const g=Yx;if(hx(),!g.tabId){dt.warn("voice-hotkey","armed-promote-no-tab",{source:g.source}),e({hotkeyState:"idle"});return}dt.info("voice-hotkey","armed-promote",g),e({hotkeyState:"recording"}),$t.getState().startRecording(g.tabId)}});return}if(!l){dt.warn("voice-hotkey","no-active-tab",{source:i});return}dt.info("voice-hotkey","start",{source:i,mode:o,tabId:l}),d.startRecording(l),n().isRecording?e({hotkeyState:"recording"}):(dt.warn("voice-hotkey","start: recording did not engage",{errorKind:n().errorKind}),e({hotkeyState:"idle"}));return}if(!(o!=="hold"||i==="global")){if(d.hotkeyState==="armed"){hx(),dt.info("voice-hotkey","miss-model-loading-armed-up"),e({hotkeyState:"idle"});return}d.hotkeyState==="recording"&&(e({hotkeyState:"stopping"}),dx(),Rm=setTimeout(()=>{n().hotkeyState==="stopping"&&(dt.warn("voice-hotkey","drain-timeout",{durationMs:ux}),e({hotkeyState:"aborted"}),setTimeout(()=>{n().hotkeyState==="aborted"&&e({hotkeyState:"idle"})},0))},ux),d.stopRecording())}},destroyHotkey:()=>{const r=n();if(hx(),lc(),r.hotkeyState==="recording"){dt.warn("voice-hotkey","destroyed-mid-recording"),e({hotkeyState:"destroyed"});try{r.stopRecording()}catch{}}else(r.hotkeyState==="armed"||r.hotkeyState==="stopping")&&(dx(),e({hotkeyState:"destroyed"}))}})),FT=e=>({isRecording:e.isRecording,statusPill:e.statusPill,lastPartial:e.lastPartial,lastTranscript:e.lastTranscript,submitCountdownStartAt:e.submitCountdownStartAt}),Vb=e=>Xy()?e.permissionState==="denied"?{canRecord:!1,reason:"permission-denied"}:e.modelStatus==="ready"?{canRecord:!0,reason:"ready"}:e.modelStatus==="loading"?{canRecord:!1,reason:"loading"}:e.modelStatus==="error"?{canRecord:!1,reason:e.errorKind==="timeout"?"load-timeout":"error"}:{canRecord:!1,reason:"idle"}:{canRecord:!1,reason:"unsupported"};if(typeof window<"u"){const e=window;e.__voice=$t,e.__transcripts=[]}function t0(e,n,r){return new Promise((i,o)=>{const l=setTimeout(()=>o(new Error(`${r} timed out after ${n}ms`)),n);e.then(d=>{clearTimeout(l),i(d)},d=>{clearTimeout(l),o(d)})})}const UT=5e3,vc=cr(()=>({snapshot:null,loaded:!1}));let W_=!1,q_=!1,Kp;async function HT(){var e;if(!W_){W_=!0;try{const n=await t0(window.api.schedule.state(),UT,"schedule.state");vc.setState({snapshot:n,loaded:!0}),Kp=((e=n.paused)==null?void 0:e.reason)??null}catch(n){if(!q_){q_=!0;const r=n instanceof Error?n.message:String(n);Le.error(`Scheduler state hydrate failed: ${r}`)}Kp=null}window.api.schedule.onState(n=>{var i;const r=((i=n.paused)==null?void 0:i.reason)??null;Kp!==void 0&&r!==Kp&&(r==="auth"?Le.error("Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume."):r==="network"&&Le.error("Scheduler paused: billing endpoint unreachable. Will auto-resume in 30 minutes.")),Kp=r,vc.setState({snapshot:n,loaded:!0})})}}const WT=6e4,qT=5e3,Uh=cr(()=>({data:null,refreshing:!1}));let V_=!1,Zx=null,G_=null,K_=!1;async function n0(){Uh.setState({refreshing:!0});let e=WT;try{const n=await t0(window.api.billing.fetch(),qT,"billing.fetch");Uh.setState({data:n,refreshing:!1}),n.kind==="transient"?e=G_==="transient"?3e4:5e3:(n.kind==="auth"||n.kind==="meter_rate_limited")&&(e=3e4),G_=n.kind}catch(n){if(Uh.setState({refreshing:!1}),!K_){K_=!0;const r=n instanceof Error?n.message:String(n);Le.warn(`Billing usage fetch failed: ${r}`)}}Zx=setTimeout(n0,e)}function VT(){V_||(V_=!0,n0())}function Yy(e){return e?e.kind==="ok"||e.kind==="ok-stale"?e.data:(e.kind==="auth"||e.kind==="meter_rate_limited")&&e.cached?e.cached:null:null}function my(){Zx!==null&&(clearTimeout(Zx),Zx=null),n0()}function dn({name:e,size:n=17,stroke:r=1.6,className:i}){const o={width:n,height:n,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:r,strokeLinecap:"round",strokeLinejoin:"round",className:i};switch(e){case"home":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 11l8-7 8 7"}),s.jsx("path",{d:"M6 10v9h12v-9"}),s.jsx("path",{d:"M10 19v-5h4v5"})]});case"terminal":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M7 10l3 2-3 2"}),s.jsx("path",{d:"M13 14h4"})]});case"agents":case"subagents":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"7",cy:"9",r:"2.5"}),s.jsx("circle",{cx:"17",cy:"9",r:"2.5"}),s.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),s.jsx("path",{d:"M8.6 11l2.8 4M15.4 11l-2.8 4M9.5 9h5"})]});case"skills":return s.jsx("svg",{...o,children:s.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 s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M12 7v5l3 2"}),s.jsx("path",{d:"M4 6l2 2"})]});case"usage":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 19V8M10 19V5M16 19v-7M22 19H2"})});case"hive":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M8 4h8l4 7-4 7H8l-4-7z"}),s.jsx("circle",{cx:"12",cy:"11",r:"2.5"})]});case"plugins":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M9 3v4M15 3v4M5 7h14v6a5 5 0 01-5 5h-4a5 5 0 01-5-5V7z"})});case"mcp":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"6",rx:"1.5"}),s.jsx("rect",{x:"3",y:"14",width:"18",height:"6",rx:"1.5"}),s.jsx("circle",{cx:"6.5",cy:"7",r:".5",fill:"currentColor"}),s.jsx("circle",{cx:"6.5",cy:"17",r:".5",fill:"currentColor"})]});case"hooks":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M12 4v9a3 3 0 003 3h5"}),s.jsx("path",{d:"M9 17l3 3 3-3"})]});case"keys":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"8",cy:"12",r:"4"}),s.jsx("path",{d:"M12 12h9M17 12v3M20 12v2"})]});case"plans":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"}),s.jsx("path",{d:"M8 9h8M8 13h8M8 17h5"})]});case"tasks":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"4",width:"7",height:"7",rx:"1.5"}),s.jsx("rect",{x:"3",y:"13",width:"7",height:"7",rx:"1.5"}),s.jsx("path",{d:"M14 6h7M14 10h5M14 15h7M14 19h5"})]});case"projects":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"memory":case"agent-memory":return s.jsxs("svg",{...o,children:[s.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"}),s.jsx("path",{d:"M9 9v6M12 6v12M15 9v6"})]});case"search":case"global-search":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"11",cy:"11",r:"6"}),s.jsx("path",{d:"M16 16l4 4"})]});case"chevron":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M9 6l6 6-6 6"})});case"caret":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M6 9l6 6 6-6"})});case"dot":return s.jsx("svg",{...o,children:s.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})});case"plus":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 5v14M5 12h14"})});case"folder":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M3 7l3-3h4l2 2h9v13H3z"})});case"file":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M7 3h7l4 4v14H7z"}),s.jsx("path",{d:"M14 3v4h4"})]});case"play":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M8 5l11 7-11 7z",fill:"currentColor",stroke:"none"})});case"pause":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"7",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"}),s.jsx("rect",{x:"13.5",y:"5",width:"3.5",height:"14",fill:"currentColor",stroke:"none",rx:"0.5"})]});case"sparkle":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 4v6M12 14v6M4 12h6M14 12h6"})});case"book":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 5a2 2 0 012-2h6v18H6a2 2 0 01-2-2zM12 3h6a2 2 0 012 2v14H12z"})});case"compass":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M15 9l-2 5-5 2 2-5z",fill:"currentColor",stroke:"none"})]});case"scheduler":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"15",rx:"2"}),s.jsx("path",{d:"M3 10h18M8 3v4M16 3v4"}),s.jsx("path",{d:"M8 14l2 2 4-4"})]});case"settings":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.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 s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"9",y:"3",width:"6",height:"12",rx:"3"}),s.jsx("path",{d:"M5 11a7 7 0 0014 0M12 18v3M9 21h6"})]});case"clock":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("path",{d:"M12 7v5l3 2"})]});case"leaf":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M20 4c-9 0-14 5-14 11 0 3 2 5 5 5 6 0 9-5 9-14z"}),s.jsx("path",{d:"M6 20c2-5 5-8 11-11"})]});case"orchestrator":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"6",r:"2.5"}),s.jsx("circle",{cx:"5",cy:"17",r:"2.5"}),s.jsx("circle",{cx:"12",cy:"17",r:"2.5"}),s.jsx("circle",{cx:"19",cy:"17",r:"2.5"}),s.jsx("path",{d:"M12 8.5v6M12 14.5l-7 0M12 14.5l7 0"})]});case"race":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 4v16M5 5h7l-1 3h7v6h-7l-1 3H5"})});case"background":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M3 4h18v4H3zM3 10h18v4H3zM3 16h18v4H3z"}),s.jsx("circle",{cx:"6",cy:"6",r:".75",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"12",r:".75",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:".75",fill:"currentColor",stroke:"none"})]});case"repoviz":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"6",cy:"12",r:"3"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"18",cy:"18",r:"3"}),s.jsx("path",{d:"M8.5 10.5L15.5 7.5M8.5 13.5L15.5 16.5"})]});case"system-prompt":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"4",y:"4",width:"16",height:"14",rx:"2"}),s.jsx("path",{d:"M8 10h8M8 14h5M9 18l-2 3M15 18l2 3"})]});case"permissions":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),s.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"}),s.jsx("circle",{cx:"12",cy:"15.5",r:"1.2",fill:"currentColor",stroke:"none"})]});case"tool":return s.jsx("svg",{...o,children:s.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 s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("path",{d:"M3 9h18M7 13h10M7 16h6"})]});case"remote":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M5 12.5a7 7 0 0114 0M1.5 9a11 11 0 0121 0M8.5 16a3.5 3.5 0 017 0"}),s.jsx("circle",{cx:"12",cy:"20",r:"1",fill:"currentColor",stroke:"none"})]});case"wifi":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12.5a10 10 0 0114 0M8 15.5a6 6 0 018 0M12 18.5h.01"})});case"shield":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"}),s.jsx("path",{d:"M9 12l2 2 4-4"})]});case"link":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M9 12h6"}),s.jsx("path",{d:"M10 8H7a4 4 0 000 8h3M14 8h3a4 4 0 010 8h-3"})]});case"copy":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"9",y:"9",width:"11",height:"11",rx:"2"}),s.jsx("path",{d:"M5 15V5a2 2 0 012-2h8"})]});case"check":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12l5 5 9-10"})});case"x":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M6 6l12 12M18 6L6 18"})});case"send":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M4 11l17-7-7 17-3-7z"})});case"browser":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("ellipse",{cx:"12",cy:"12",rx:"3.2",ry:"8"}),s.jsx("path",{d:"M4 12h16"})]});case"target":return s.jsxs("svg",{...o,children:[s.jsx("circle",{cx:"12",cy:"12",r:"8"}),s.jsx("circle",{cx:"12",cy:"12",r:"3.5"}),s.jsx("path",{d:"M12 2v3M12 19v3M2 12h3M19 12h3"})]});case"record":return s.jsx("svg",{...o,children:s.jsx("circle",{cx:"12",cy:"12",r:"7",fill:"currentColor",stroke:"none"})});case"eye":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]});case"camera":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 8h3l2-2h6l2 2h3v11H4z"}),s.jsx("circle",{cx:"12",cy:"13.5",r:"3.5"})]});case"arrowleft":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M19 12H5M11 6l-6 6 6 6"})});case"arrowright":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12h14M13 6l6 6-6 6"})});case"reload":return s.jsxs("svg",{...o,children:[s.jsx("path",{d:"M4 12a8 8 0 0114-5.3M20 12a8 8 0 01-14 5.3"}),s.jsx("path",{d:"M18 3v4h-4M6 21v-4h4"})]});case"lock":return s.jsxs("svg",{...o,children:[s.jsx("rect",{x:"5",y:"11",width:"14",height:"9",rx:"2"}),s.jsx("path",{d:"M8 11V8a4 4 0 018 0v3"})]});case"stop":return s.jsx("svg",{...o,children:s.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1.5",fill:"currentColor",stroke:"none"})});case"star":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M12 3l2.6 5.6 6.1.6-4.6 4.1 1.3 6-5.4-3.2-5.4 3.2 1.3-6-4.6-4.1 6.1-.6z"})});case"minus":return s.jsx("svg",{...o,children:s.jsx("path",{d:"M5 12h14"})});default:return null}}function GT(e,n={}){switch(e){case"ready":return n.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 n.loadingPct=="number"?Math.round(n.loadingPct):0} percent`;case"error":return n.errorMessage?`Microphone — speech model error: ${n.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 X_=e=>Symbol.iterator in e,Y_=e=>"entries"in e,J_=(e,n)=>{const r=e instanceof Map?e:new Map(e.entries()),i=n instanceof Map?n:new Map(n.entries());if(r.size!==i.size)return!1;for(const[o,l]of r)if(!i.has(o)||!Object.is(l,i.get(o)))return!1;return!0},KT=(e,n)=>{const r=e[Symbol.iterator](),i=n[Symbol.iterator]();let o=r.next(),l=i.next();for(;!o.done&&!l.done;){if(!Object.is(o.value,l.value))return!1;o=r.next(),l=i.next()}return!!o.done&&!!l.done};function XT(e,n){return Object.is(e,n)?!0:typeof e!="object"||e===null||typeof n!="object"||n===null||Object.getPrototypeOf(e)!==Object.getPrototypeOf(n)?!1:X_(e)&&X_(n)?Y_(e)&&Y_(n)?J_(e,n):KT(e,n):J_({entries:()=>Object.entries(e)},{entries:()=>Object.entries(n)})}function Y2(e){const n=co.useRef(void 0);return r=>{const i=e(r);return XT(n.current,i)?n.current:n.current=i}}let Q_=0;const YT=1e3;function JT(e){const n=performance.now();n-Q_<YT||(Q_=n,dt.debug("voice","mic.gate.click_rejected",{reason:e}))}function J2(){const e=$t(m=>m.isRecording),n=$t(m=>m.error),r=$t(m=>m.loadingProgress),i=$t(Y2(Vb)),o=()=>{const m=$t.getState(),{canRecord:x,reason:g}=Vb(m);if(m.isRecording)return m.stopRecording();if(m.wizardArmed&&!m.wizardOpen){m.openWizard();return}if(g==="error"||g==="load-timeout"){m.resetAndRetryModel();return}if(!x)return JT(g);const v=bt.getState().activeTabId;v&&m.startRecording(v)},l=GT(i.reason,{loadingPct:r,errorMessage:n,isRecording:e}),d=i.reason==="unsupported",u=!i.canRecord,h=i.reason==="loading"?"text-fg-faint animate-pulse cursor-wait":i.reason==="error"||i.reason==="load-timeout"?"text-red-400 cursor-pointer":i.reason==="permission-denied"?"text-amber-400 cursor-pointer":i.reason==="idle"?"text-fg-faint cursor-pointer":i.reason==="unsupported"?"text-fg-faint cursor-not-allowed":e?"text-red-400 ring-2 ring-red-400 animate-pulse":"text-fg-dim hover:text-fg";return s.jsx("button",{onClick:o,disabled:d,"aria-disabled":u,"aria-label":l,title:l,"data-testid":"mic-button","data-state":i.reason,className:`p-1.5 rounded transition-colors ${h}`,children:s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"9",y:"1",width:"6",height:"12",rx:"3"}),s.jsx("path",{d:"M5 10a7 7 0 0 0 14 0"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"})]})})}function QT(){const e=$t(r=>r.ttsEnabled),n=$t(r=>r.toggleTTS);return s.jsxs("button",{onClick:n,title:e?"Read Claude replies aloud: ON":"Read Claude replies aloud: OFF",className:`px-1.5 py-1 rounded transition-colors flex items-center gap-1 ${e?"text-accent":"text-fg-dim hover:text-fg"}`,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),e?s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14"})]}):s.jsxs(s.Fragment,{children:[s.jsx("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),s.jsx("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]})]}),s.jsx("span",{className:"text-[10px] font-medium tracking-wide",children:"TTS"})]})}function Zm(e){if(!e||e==="—"||e==="unknown")return e;const n=/\[(\dm)\]/.exec(e),r=/(opus|sonnet|haiku)[-_](\d+)[-_.]?(\d+)?/i.exec(e);if(!r)return e;const i=r[1].charAt(0).toUpperCase()+r[1].slice(1).toLowerCase(),o=r[3]?`${r[2]}.${r[3]}`:r[2];return n?`${i} ${o} ${n[1]}`:`${i} ${o}`}const mx=new Map,ZT=3e4;function Q2(e){const[n,r]=L.useState(()=>{var i;return e?((i=mx.get(e))==null?void 0:i.value)??null:null});return L.useEffect(()=>{if(!e){r(null);return}let i=!1;return(async()=>{const l=mx.get(e);if(l&&Date.now()-l.ts<ZT){i||r(l.value);return}try{const d=await window.api.app.gitBranch(e);if(i)return;mx.set(e,{value:d,ts:Date.now()}),r(d)}catch{if(i)return;mx.set(e,{value:null,ts:Date.now()}),r(null)}})(),()=>{i=!0}},[e]),n}const Jy=[{key:"overview",group:"Workspace",label:"Home",icon:"home",hint:"Today's sessions + the 5-hour window"},{key:"terminal",group:"Workspace",label:"Terminal",icon:"terminal",hint:"Live Claude Code, in-app"},{key:"browser",group:"Workspace",label:"Browser",icon:"browser",hint:"Embedded dev browser — capture DOM, record click-sequences"},{key:"projects",group:"Workspace",label:"File Explorer",icon:"projects",hint:"Browse files + edit, per project"},{key:"subagents",group:"Workspace",label:"Subagents",icon:"hive",liveKind:"subagents",hint:"Fan out work: Hive · Orchestrate · Race · Boss"},{key:"scheduler",group:"Workspace",label:"Scheduler",icon:"scheduler",liveKind:"scheduler",hint:"Author PRDs + run them as claude -p jobs"},{key:"history",group:"Workspace",label:"History",icon:"history",hint:"Every session, ever — resumable"},{key:"usage",group:"Workspace",label:"Usage",icon:"usage",hint:"Tokens, cost, sessions per day"},{key:"skills",group:"Configure",label:"Skills",icon:"skills",hint:"Reusable instructions Claude loads"},{key:"plugins",group:"Configure",label:"Plugins",icon:"plugins",hint:"Extensions for Claude Code"},{key:"mcp",group:"Configure",label:"MCP Servers",icon:"mcp",hint:"External tools and integrations"},{key:"hooks",group:"Configure",label:"Hooks",icon:"hooks",hint:"Run scripts on session events"},{key:"keybindings",group:"Configure",label:"Keybindings",icon:"keys",hint:"Shortcuts you can override"},{key:"memory",group:"Configure",label:"Memory",icon:"memory",hint:"Workspace memory store"},{key:"system-prompt",group:"Configure",label:"System Prompt",icon:"system-prompt",hint:"Personality and behavior"},{key:"permissions",group:"Configure",label:"Permissions",icon:"permissions",hint:"Allow / deny rules"},{key:"settings",group:"Configure",label:"Settings",icon:"settings",hint:"Theme, voice, billing window"},{key:"remote",group:"Configure",label:"Remote",icon:"remote",hint:"Web remote control — disabled by default"},{key:"voice",group:"Tools",label:"Voice",icon:"mic",hint:"Whisper transcription + push-to-talk"},{key:"repoviz",group:"Tools",label:"Repo Viz",icon:"repoviz",hint:"Language + directory map"},{key:"search",group:"Tools",label:"Search",icon:"global-search",hint:"⌘P file · ⌘⇧F content"}],e$=Object.fromEntries(Jy.map(e=>[e.key,e.group])),Pv={Workspace:"Where you do the work — sessions, files, and everything currently running.",Configure:"How Claude behaves — changes here apply to every session you start.",Tools:"One-off utilities — not configuration, just things you reach for sometimes."},Z_=Jy.filter(e=>e.group==="Workspace"),e1=Jy.filter(e=>e.group==="Configure"),t1=Jy.filter(e=>e.group==="Tools").map(({key:e,label:n,icon:r,hint:i})=>({key:e,label:n,icon:r,hint:i})),Gb="sm.almanac.sidebarWidth",Z2=180,eC=480,Kb=252;function t$(){try{const e=parseInt(localStorage.getItem(Gb)??"",10);if(Number.isFinite(e))return Math.min(eC,Math.max(Z2,e))}catch{}return Kb}const n$=52,tC="sm.almanac.sidebarCollapsed";function r$(){try{return localStorage.getItem(tC)==="1"}catch{}return!1}const nC="sm.almanac.collapsedGroups";function s$(){try{const e=localStorage.getItem(nC);if(!e)return new Set;const n=JSON.parse(e);return Array.isArray(n)?new Set(n.filter(r=>r==="Workspace"||r==="Configure"||r==="Tools")):new Set}catch{return new Set}}function i$(){const e=$m(l=>l.tabs),n=vc(l=>{var d;return(((d=l.snapshot)==null?void 0:d.jobs)??[]).some(u=>u.status==="running")}),[r,i]=L.useState(()=>Date.now());return L.useEffect(()=>{const l=setInterval(()=>i(Date.now()),5e3);return()=>clearInterval(l)},[]),{subagents:Object.values(e).some(l=>l.agents.some(d=>r-d.at<6e4)),scheduler:n}}function o$({active:e,onNavigate:n,onNewSession:r}){const[i,o]=L.useState(()=>s$()),l=L.useCallback(_=>{o(C=>{const N=new Set(C);N.has(_)?N.delete(_):N.add(_);try{localStorage.setItem(nC,JSON.stringify(Array.from(N)))}catch{}return N})},[]),[d,u]=L.useState(()=>r$()),h=L.useCallback(()=>{u(_=>{const C=!_;try{localStorage.setItem(tC,C?"1":"0")}catch{}return C})},[]),m=bt(_=>_.tabs),x=bt(_=>_.activeTabId),g=m.find(_=>_.id===x)??null,v=i$(),[S,E]=L.useState(()=>t$()),j=L.useRef(S);j.current=S;const y=L.useCallback(_=>{_.preventDefault();const C=_.clientX,N=j.current;let $=N;const R=I=>{$=Math.min(eC,Math.max(Z2,N+(I.clientX-C))),E($)},O=()=>{window.removeEventListener("pointermove",R),window.removeEventListener("pointerup",O),document.body.style.cursor="",document.body.style.userSelect="";try{localStorage.setItem(Gb,String($))}catch{}};window.addEventListener("pointermove",R),window.addEventListener("pointerup",O),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),b=L.useCallback(()=>{E(Kb);try{localStorage.setItem(Gb,String(Kb))}catch{}},[]);return s.jsxs("aside",{className:"shrink-0 bg-bg-elev border-r border-line flex flex-col relative transition-[width] duration-150",style:{width:d?n$:S},"data-testid":"tour-leftnav","aria-label":"Primary navigation",children:[s.jsx(a$,{tab:g,onNewSession:r,rail:d,onToggleRail:h}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto pb-3",style:{paddingInline:d?"4px":"8px"},children:s.jsxs(s.Fragment,{children:[!d&&s.jsx(Dv,{label:"Workspace",desc:Pv.Workspace,collapsed:i.has("Workspace"),count:Z_.length,onToggle:()=>l("Workspace")}),(d||!i.has("Workspace"))&&Z_.map(_=>s.jsx(n1,{item:_,active:e===_.key,live:_.liveKind?v[_.liveKind]:!1,onClick:()=>n(_.key),rail:d},_.key)),!d&&s.jsx(Dv,{label:"Configure",desc:Pv.Configure,collapsed:i.has("Configure"),count:e1.length,onToggle:()=>l("Configure")}),(d||!i.has("Configure"))&&e1.map(_=>s.jsx(n1,{item:_,active:e===_.key,live:!1,onClick:()=>n(_.key),rail:d},_.key)),!d&&s.jsx(Dv,{label:"Tools",desc:Pv.Tools,collapsed:i.has("Tools"),count:t1.length,onToggle:()=>l("Tools")}),(d||!i.has("Tools"))&&t1.map(_=>s.jsx(l$,{tool:_,active:e===_.key,onClick:()=>n(_.key),rail:d},_.key))]})}),s.jsx(c$,{rail:d}),!d&&s.jsx("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize sidebar",title:"Drag to resize · double-click to reset",onPointerDown:y,onDoubleClick:b,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 a$({tab:e,onNewSession:n,rail:r,onToggleRail:i}){const o=(e==null?void 0:e.label)??"no session",l=Q2((e==null?void 0:e.cwd)??null);return r?s.jsxs("div",{className:"flex flex-col items-center gap-1.5 pt-2 pb-2 border-b border-rule",children:[s.jsx("button",{onClick:n,"data-testid":"tour-new-session",title:"New session",className:"w-9 h-9 rounded-md bg-bg-hi border border-line text-fg hover:bg-bg-hi/80 hover:border-accent/40 transition-colors flex items-center justify-center",children:s.jsx(dn,{name:"plus",size:15,stroke:1.8})}),s.jsx("button",{onClick:i,title:"Expand sidebar","data-testid":"sidebar-rail-toggle",className:"w-9 h-9 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:s.jsx("span",{style:{display:"inline-flex",transform:"rotate(0deg)"},children:s.jsx(dn,{name:"chevron",size:15,stroke:1.8})})})]}):s.jsxs("div",{className:"px-[18px] pt-[14px] pb-[10px] border-b border-rule",children:[s.jsxs("div",{className:"flex items-center justify-between",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.06em] text-fg-faint uppercase",children:"Project"}),s.jsx("button",{onClick:i,title:"Collapse sidebar","data-testid":"sidebar-rail-toggle",className:"w-6 h-6 rounded-md text-fg-faint hover:text-fg hover:bg-bg-hi/50 transition-colors flex items-center justify-center",children:s.jsx("span",{style:{display:"inline-flex",transform:"rotate(180deg)"},children:s.jsx(dn,{name:"chevron",size:13,stroke:1.8})})})]}),s.jsxs("div",{className:"flex items-baseline gap-2 mt-1",children:[s.jsx("span",{className:"self-center w-2 h-2 rounded-full bg-sage"}),s.jsx("span",{className:"font-serif text-[18px] font-medium text-fg truncate",title:(e==null?void 0:e.cwd)??"",children:o})]}),s.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:l?`⌥${l}`:e?e.cwd:"—"}),s.jsxs("div",{className:"mt-3 flex items-stretch gap-1.5",children:[s.jsxs("button",{onClick:n,"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:[s.jsx(dn,{name:"plus",size:13,stroke:1.8}),"New session"]}),s.jsx("div",{className:"flex items-center rounded-md bg-bg-hi border border-line",children:s.jsx(J2,{})})]})]})}function Dv({label:e,desc:n,collapsed:r,count:i,onToggle:o}){return s.jsxs("div",{className:"px-3 pt-3.5 pb-1.5",children:[s.jsxs("button",{onClick:o,"aria-expanded":!r,title:r?`Expand ${e}`:`Collapse ${e}`,className:"group w-full flex items-center gap-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:[s.jsx("span",{"aria-hidden":!0,className:"inline-block w-2 text-[9px] not-italic transition-transform",style:{transform:r?"rotate(-90deg)":"rotate(0deg)"},children:"▾"}),s.jsx("span",{className:"flex-1",children:e}),r&&s.jsx("span",{className:"not-italic text-[10px] font-mono text-fg-faint/70 normal-case tracking-normal",children:i})]}),!r&&s.jsx("p",{className:"mt-0.5 pl-3.5 text-[11px] leading-[1.35] text-fg-faint/80 normal-case tracking-normal font-sans not-italic line-clamp-2",children:n})]})}function n1({item:e,active:n,live:r,onClick:i,rail:o}){return s.jsxs("button",{onClick:i,title:e.hint,"data-testid":e.key==="scheduler"?"tour-scheduler":void 0,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${o?"justify-center px-0 py-[9px]":"gap-3 px-3.5 py-[9px] text-[14px]"} ${n?"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:[n&&s.jsx("span",{"aria-hidden":!0,className:`absolute top-2 bottom-2 w-[3px] rounded-sm bg-accent ${o?"-left-[4px]":"-left-[10px]"}`}),s.jsx("span",{className:`inline-flex ${n?"text-accent":"text-fg-faint"}`,children:s.jsx(dn,{name:e.icon,size:17,stroke:1.6})}),!o&&s.jsxs("span",{className:"flex-1 min-w-0",children:[s.jsx("span",{className:"block truncate",children:e.label}),e.hint&&s.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:e.hint})]}),!o&&r&&s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"}),o&&r&&s.jsx("span",{className:"absolute top-1.5 right-1.5 w-1.5 h-1.5 rounded-full bg-accent animate-pulse",title:"live activity"})]})}function l$({tool:e,active:n,onClick:r,rail:i}){return s.jsxs("button",{onClick:r,title:e.hint,className:`relative w-full flex items-center rounded-[10px] text-left mb-0.5 transition-colors ${i?"justify-center px-0 py-[7px]":"gap-3 px-3.5 py-[7px] text-[13px]"} ${n?"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:[n&&s.jsx("span",{"aria-hidden":!0,className:`absolute top-1.5 bottom-1.5 w-[3px] rounded-sm bg-accent ${i?"-left-[4px]":"-left-[10px]"}`}),s.jsx("span",{className:`inline-flex ${n?"text-accent":"text-fg-faint"}`,children:s.jsx(dn,{name:e.icon,size:15,stroke:1.6})}),!i&&s.jsxs("span",{className:"flex-1 min-w-0",children:[s.jsx("span",{className:"block truncate",children:e.label}),e.hint&&s.jsx("span",{className:"block text-[11px] leading-[1.3] text-fg-faint/80 font-normal truncate",children:e.hint})]})]})}function c$({rail:e}){const n=$t(u=>u.isRecording),r=bt(u=>u.tabs),i=bt(u=>u.activeTabId),o=r.find(u=>u.id===i)??null,[l,d]=L.useState(null);return L.useEffect(()=>{let u=!1;if(!(o!=null&&o.presetId)){d(null);return}return S2(o.presetId).then(h=>{u||d((h==null?void 0:h.model)??null)}).catch(()=>{u||d(null)}),()=>{u=!0}},[o==null?void 0:o.presetId]),e?s.jsx("div",{className:"py-2.5 border-t border-rule flex justify-center",children:s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${n?"bg-red-500 animate-pulse":"bg-sage"}`,title:n?"recording":"idle"})}):s.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:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${n?"bg-red-500 animate-pulse":"bg-sage"}`,title:n?"recording":"idle"}),s.jsx("span",{className:"truncate",title:l??"",children:n?"recording…":l?`Claude · ${Zm(l)}`:"Claude Code"})]})}function u$({onNavigate:e}){const n=bt(C=>C.tabs),r=bt(C=>C.activeTabId),i=n.find(C=>C.id===r)??null,o=I2(i),l=(o==null?void 0:o.lastEventAt)??0,d=Uh(C=>C.data),u=vc(C=>{var N;return((N=C.snapshot)==null?void 0:N.paused)??null}),h=Q2((i==null?void 0:i.cwd)??null),[,m]=L.useState(0);L.useEffect(()=>{const C=setInterval(()=>m(N=>N+1),6e4);return()=>clearInterval(C)},[]);const x=(o==null?void 0:o.todos)??[],[g,v]=L.useState(!1),S=L.useRef(null);L.useEffect(()=>{if(!g)return;const C=N=>{S.current&&!S.current.contains(N.target)&&v(!1)};return document.addEventListener("mousedown",C),()=>document.removeEventListener("mousedown",C)},[g]),L.useEffect(()=>{x.length===0&&v(!1)},[x.length]);const E=Yy(d),j=(E==null?void 0:E.usage.five_hour)??null,y=j?Math.round(j.utilization):null,b=(d==null?void 0:d.kind)==="ok"||(d==null?void 0:d.kind)==="ok-stale",_=l>0?f$(Date.now()-l):"—";return s.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:[s.jsxs("button",{onClick:()=>e==null?void 0:e("settings"),className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:b?"Connected to Anthropic":"Disconnected",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${b?"bg-sage":"bg-fg-faint"}`}),s.jsx("span",{children:b?"connected":"offline"})]}),s.jsx("button",{onClick:()=>e==null?void 0:e("usage"),className:"hover:text-fg transition-colors",title:"Open Usage",children:y!=null?`${y}% of 5h window used`:"5h —"}),u&&s.jsxs("button",{onClick:()=>e==null?void 0:e("scheduler"),title:"Scheduler is paused — click to open Scheduler",className:`flex items-center gap-1 px-1.5 py-0.5 rounded border font-mono text-[10.5px] transition-colors ${u.reason==="auth"||u.reason==="network"?"border-red-700/60 text-red-300 hover:bg-red-900/20":"border-amber-700/60 text-amber-300 hover:bg-amber-900/20"}`,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-current opacity-80"}),"Scheduler paused · ",u.reason]}),i&&s.jsxs("span",{className:"text-fg-faint",title:i.cwd,children:[i.label,h&&s.jsxs("span",{className:"text-fg-dim",children:[" · ⌥",h]})]}),s.jsxs("span",{className:"text-fg-faint",children:["last activity: ",s.jsx("span",{className:"text-fg-dim",children:_})]}),x.length>0&&s.jsx(d$,{ref:S,todos:x,open:g,onToggle:()=>v(C=>!C)}),s.jsx("span",{className:"flex-1"}),s.jsxs("span",{className:"text-fg-faint",children:["v","0.38.2"]})]})}const d$=L.forwardRef(function({todos:n,open:r,onToggle:i},o){const l={completed:n.filter(d=>d.status==="completed").length,in_progress:n.filter(d=>d.status==="in_progress").length,pending:n.filter(d=>d.status==="pending").length};return s.jsxs("div",{ref:o,className:"relative",children:[s.jsxs("button",{onClick:i,className:"flex items-center gap-1.5 hover:text-fg transition-colors",title:"Live to-dos for this session","data-testid":"footer-todos",children:[s.jsxs("span",{className:"text-green-400",children:["✓",l.completed]}),s.jsxs("span",{className:"text-accent",children:["●",l.in_progress]}),s.jsxs("span",{className:"text-fg-dim",children:["○",l.pending]}),s.jsxs("span",{className:"text-fg-faint",children:["todos ",r?"▾":"▴"]})]}),r&&s.jsx("div",{className:"absolute bottom-full left-0 mb-1.5 w-80 max-h-72 overflow-auto bg-bg-elev border border-line rounded shadow-xl p-2 z-50","data-testid":"footer-todos-popover",children:s.jsx("ul",{className:"space-y-0.5",children:n.map((d,u)=>s.jsxs("li",{className:`flex items-start gap-2 py-1 px-1.5 rounded ${d.status==="in_progress"?"bg-bg-hi":""}`,children:[s.jsx(h$,{status:d.status}),s.jsx("span",{className:d.status==="completed"?"text-fg-faint line-through":d.status==="in_progress"?"text-fg":"text-fg-dim",children:d.status==="in_progress"&&d.activeForm?d.activeForm:d.content})]},u))})})]})});function h$({status:e}){return e==="completed"?s.jsx("span",{className:"text-green-400 w-3 shrink-0",children:"✓"}):e==="in_progress"?s.jsx("span",{className:"w-3 shrink-0",children:s.jsx("span",{className:"inline-block w-1.5 h-1.5 rounded-full bg-accent animate-pulse"})}):s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:"○"})}function f$(e){const n=Math.max(0,Math.floor(e/1e3));if(n<60)return`${n}s ago`;const r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}var Ov={exports:{}},r1;function p$(){return r1||(r1=1,(function(e,n){(function(r,i){e.exports=i()})(globalThis,(()=>(()=>{var r={4567:function(d,u,h){var m=this&&this.__decorate||function(_,C,N,$){var R,O=arguments.length,I=O<3?C:$===null?$=Object.getOwnPropertyDescriptor(C,N):$;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")I=Reflect.decorate(_,C,N,$);else for(var z=_.length-1;z>=0;z--)(R=_[z])&&(I=(O<3?R(I):O>3?R(C,N,I):R(C,N))||I);return O>3&&I&&Object.defineProperty(C,N,I),I},x=this&&this.__param||function(_,C){return function(N,$){C(N,$,_)}};Object.defineProperty(u,"__esModule",{value:!0}),u.AccessibilityManager=void 0;const g=h(9042),v=h(9924),S=h(844),E=h(4725),j=h(2585),y=h(3656);let b=u.AccessibilityManager=class extends S.Disposable{constructor(_,C,N,$){super(),this._terminal=_,this._coreBrowserService=N,this._renderService=$,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 R=0;R<this._terminal.rows;R++)this._rowElements[R]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[R]);if(this._topBoundaryFocusListener=R=>this._handleBoundaryFocus(R,0),this._bottomBoundaryFocusListener=R=>this._handleBoundaryFocus(R,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 v.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((R=>this._handleResize(R.rows)))),this.register(this._terminal.onRender((R=>this._refreshRows(R.start,R.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((R=>this._handleChar(R)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(`
|
|
2898
2898
|
`)))),this.register(this._terminal.onA11yTab((R=>this._handleTab(R)))),this.register(this._terminal.onKey((R=>this._handleKey(R.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,y.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,S.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(_){for(let C=0;C<_;C++)this._handleChar(" ")}_handleChar(_){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==_&&(this._charsToAnnounce+=_):this._charsToAnnounce+=_,_===`
|
|
2899
2899
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=g.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(_){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(_)||this._charsToConsume.push(_)}_refreshRows(_,C){this._liveRegionDebouncer.refresh(_,C,this._terminal.rows)}_renderRows(_,C){const N=this._terminal.buffer,$=N.lines.length.toString();for(let R=_;R<=C;R++){const O=N.lines.get(N.ydisp+R),I=[],z=(O==null?void 0:O.translateToString(!0,void 0,void 0,I))||"",U=(N.ydisp+R+1).toString(),W=this._rowElements[R];W&&(z.length===0?(W.innerText=" ",this._rowColumns.set(W,[0,1])):(W.textContent=z,this._rowColumns.set(W,I)),W.setAttribute("aria-posinset",U),W.setAttribute("aria-setsize",$))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(_,C){const N=_.target,$=this._rowElements[C===0?1:this._rowElements.length-2];if(N.getAttribute("aria-posinset")===(C===0?"1":`${this._terminal.buffer.lines.length}`)||_.relatedTarget!==$)return;let R,O;if(C===0?(R=N,O=this._rowElements.pop(),this._rowContainer.removeChild(O)):(R=this._rowElements.shift(),O=N,this._rowContainer.removeChild(R)),R.removeEventListener("focus",this._topBoundaryFocusListener),O.removeEventListener("focus",this._bottomBoundaryFocusListener),C===0){const I=this._createAccessibilityTreeNode();this._rowElements.unshift(I),this._rowContainer.insertAdjacentElement("afterbegin",I)}else{const I=this._createAccessibilityTreeNode();this._rowElements.push(I),this._rowContainer.appendChild(I)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(C===0?-1:1),this._rowElements[C===0?1:this._rowElements.length-2].focus(),_.preventDefault(),_.stopImmediatePropagation()}_handleSelectionChange(){var z;if(this._rowElements.length===0)return;const _=document.getSelection();if(!_)return;if(_.isCollapsed)return void(this._rowContainer.contains(_.anchorNode)&&this._terminal.clearSelection());if(!_.anchorNode||!_.focusNode)return void console.error("anchorNode and/or focusNode are null");let C={node:_.anchorNode,offset:_.anchorOffset},N={node:_.focusNode,offset:_.focusOffset};if((C.node.compareDocumentPosition(N.node)&Node.DOCUMENT_POSITION_PRECEDING||C.node===N.node&&C.offset>N.offset)&&([C,N]=[N,C]),C.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(C={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(C.node))return;const $=this._rowElements.slice(-1)[0];if(N.node.compareDocumentPosition($)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(N={node:$,offset:((z=$.textContent)==null?void 0:z.length)??0}),!this._rowContainer.contains(N.node))return;const R=({node:U,offset:W})=>{const Y=U instanceof Text?U.parentNode:U;let V=parseInt(Y==null?void 0:Y.getAttribute("aria-posinset"),10)-1;if(isNaN(V))return console.warn("row is invalid. Race condition?"),null;const H=this._rowColumns.get(Y);if(!H)return console.warn("columns is null. Race condition?"),null;let te=W<H.length?H[W]:H.slice(-1)[0]+1;return te>=this._terminal.cols&&(++V,te=0),{row:V,column:te}},O=R(C),I=R(N);if(O&&I){if(O.row>I.row||O.row===I.row&&O.column>=I.column)throw new Error("invalid range");this._terminal.select(O.column,O.row,(I.row-O.row)*this._terminal.cols-O.column+I.column)}}_handleResize(_){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let C=this._rowContainer.children.length;C<this._terminal.rows;C++)this._rowElements[C]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[C]);for(;this._rowElements.length>_;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const _=this._coreBrowserService.mainDocument.createElement("div");return _.setAttribute("role","listitem"),_.tabIndex=-1,this._refreshRowDimensions(_),_}_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 _=0;_<this._terminal.rows;_++)this._refreshRowDimensions(this._rowElements[_])}}_refreshRowDimensions(_){_.style.height=`${this._renderService.dimensions.css.cell.height}px`}};u.AccessibilityManager=b=m([x(1,j.IInstantiationService),x(2,E.ICoreBrowserService),x(3,E.IRenderService)],b)},3614:(d,u)=>{function h(v){return v.replace(/\r?\n/g,"\r")}function m(v,S){return S?"\x1B[200~"+v+"\x1B[201~":v}function x(v,S,E,j){v=m(v=h(v),E.decPrivateModes.bracketedPasteMode&&j.rawOptions.ignoreBracketedPasteMode!==!0),E.triggerDataEvent(v,!0),S.value=""}function g(v,S,E){const j=E.getBoundingClientRect(),y=v.clientX-j.left-10,b=v.clientY-j.top-10;S.style.width="20px",S.style.height="20px",S.style.left=`${y}px`,S.style.top=`${b}px`,S.style.zIndex="1000",S.focus()}Object.defineProperty(u,"__esModule",{value:!0}),u.rightClickHandler=u.moveTextAreaUnderMouseCursor=u.paste=u.handlePasteEvent=u.copyHandler=u.bracketTextForPaste=u.prepareTextForTerminal=void 0,u.prepareTextForTerminal=h,u.bracketTextForPaste=m,u.copyHandler=function(v,S){v.clipboardData&&v.clipboardData.setData("text/plain",S.selectionText),v.preventDefault()},u.handlePasteEvent=function(v,S,E,j){v.stopPropagation(),v.clipboardData&&x(v.clipboardData.getData("text/plain"),S,E,j)},u.paste=x,u.moveTextAreaUnderMouseCursor=g,u.rightClickHandler=function(v,S,E,j,y){g(v,S,E),y&&j.rightClickSelect(v),S.value=j.selectionText,S.select()}},7239:(d,u,h)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.ColorContrastCache=void 0;const m=h(1505);u.ColorContrastCache=class{constructor(){this._color=new m.TwoKeyMap,this._css=new m.TwoKeyMap}setCss(x,g,v){this._css.set(x,g,v)}getCss(x,g){return this._css.get(x,g)}setColor(x,g,v){this._color.set(x,g,v)}getColor(x,g){return this._color.get(x,g)}clear(){this._color.clear(),this._css.clear()}}},3656:(d,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.addDisposableDomListener=void 0,u.addDisposableDomListener=function(h,m,x,g){h.addEventListener(m,x,g);let v=!1;return{dispose:()=>{v||(v=!0,h.removeEventListener(m,x,g))}}}},3551:function(d,u,h){var m=this&&this.__decorate||function(b,_,C,N){var $,R=arguments.length,O=R<3?_:N===null?N=Object.getOwnPropertyDescriptor(_,C):N;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")O=Reflect.decorate(b,_,C,N);else for(var I=b.length-1;I>=0;I--)($=b[I])&&(O=(R<3?$(O):R>3?$(_,C,O):$(_,C))||O);return R>3&&O&&Object.defineProperty(_,C,O),O},x=this&&this.__param||function(b,_){return function(C,N){_(C,N,b)}};Object.defineProperty(u,"__esModule",{value:!0}),u.Linkifier=void 0;const g=h(3656),v=h(8460),S=h(844),E=h(2585),j=h(4725);let y=u.Linkifier=class extends S.Disposable{get currentLink(){return this._currentLink}constructor(b,_,C,N,$){super(),this._element=b,this._mouseService=_,this._renderService=C,this._bufferService=N,this._linkProviderService=$,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new v.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new v.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,S.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,S.toDisposable)((()=>{var R;this._lastMouseEvent=void 0,(R=this._activeProviderReplies)==null||R.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,g.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,g.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,g.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(b){this._lastMouseEvent=b;const _=this._positionFromMouseEvent(b,this._element,this._mouseService);if(!_)return;this._isMouseOut=!1;const C=b.composedPath();for(let N=0;N<C.length;N++){const $=C[N];if($.classList.contains("xterm"))break;if($.classList.contains("xterm-hover"))return}this._lastBufferCell&&_.x===this._lastBufferCell.x&&_.y===this._lastBufferCell.y||(this._handleHover(_),this._lastBufferCell=_)}_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,_){var N,$;this._activeProviderReplies&&_||((N=this._activeProviderReplies)==null||N.forEach((R=>{R==null||R.forEach((O=>{O.link.dispose&&O.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=b.y);let C=!1;for(const[R,O]of this._linkProviderService.linkProviders.entries())_?($=this._activeProviderReplies)!=null&&$.get(R)&&(C=this._checkLinkProviderResult(R,b,C)):O.provideLinks(b.y,(I=>{var U,W;if(this._isMouseOut)return;const z=I==null?void 0:I.map((Y=>({link:Y})));(U=this._activeProviderReplies)==null||U.set(R,z),C=this._checkLinkProviderResult(R,b,C),((W=this._activeProviderReplies)==null?void 0:W.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(b.y,this._activeProviderReplies)}))}_removeIntersectingLinks(b,_){const C=new Set;for(let N=0;N<_.size;N++){const $=_.get(N);if($)for(let R=0;R<$.length;R++){const O=$[R],I=O.link.range.start.y<b?0:O.link.range.start.x,z=O.link.range.end.y>b?this._bufferService.cols:O.link.range.end.x;for(let U=I;U<=z;U++){if(C.has(U)){$.splice(R--,1);break}C.add(U)}}}}_checkLinkProviderResult(b,_,C){var R;if(!this._activeProviderReplies)return C;const N=this._activeProviderReplies.get(b);let $=!1;for(let O=0;O<b;O++)this._activeProviderReplies.has(O)&&!this._activeProviderReplies.get(O)||($=!0);if(!$&&N){const O=N.find((I=>this._linkAtPosition(I.link,_)));O&&(C=!0,this._handleNewLink(O))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!C)for(let O=0;O<this._activeProviderReplies.size;O++){const I=(R=this._activeProviderReplies.get(O))==null?void 0:R.find((z=>this._linkAtPosition(z.link,_)));if(I){C=!0,this._handleNewLink(I);break}}return C}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(b){if(!this._currentLink)return;const _=this._positionFromMouseEvent(b,this._element,this._mouseService);_&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,_)&&this._currentLink.link.activate(b,this._currentLink.link.text)}_clearCurrentLink(b,_){this._currentLink&&this._lastMouseEvent&&(!b||!_||this._currentLink.link.range.start.y>=b&&this._currentLink.link.range.end.y<=_)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,S.disposeArray)(this._linkCacheDisposables))}_handleNewLink(b){if(!this._lastMouseEvent)return;const _=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);_&&this._linkAtPosition(b.link,_)&&(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 C,N;return(N=(C=this._currentLink)==null?void 0:C.state)==null?void 0:N.decorations.pointerCursor},set:C=>{var N;(N=this._currentLink)!=null&&N.state&&this._currentLink.state.decorations.pointerCursor!==C&&(this._currentLink.state.decorations.pointerCursor=C,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",C))}},underline:{get:()=>{var C,N;return(N=(C=this._currentLink)==null?void 0:C.state)==null?void 0:N.decorations.underline},set:C=>{var N,$,R;(N=this._currentLink)!=null&&N.state&&((R=($=this._currentLink)==null?void 0:$.state)==null?void 0:R.decorations.underline)!==C&&(this._currentLink.state.decorations.underline=C,this._currentLink.state.isHovered&&this._fireUnderlineEvent(b.link,C))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((C=>{if(!this._currentLink)return;const N=C.start===0?0:C.start+1+this._bufferService.buffer.ydisp,$=this._bufferService.buffer.ydisp+1+C.end;if(this._currentLink.link.range.start.y>=N&&this._currentLink.link.range.end.y<=$&&(this._clearCurrentLink(N,$),this._lastMouseEvent)){const R=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);R&&this._askForLink(R,!1)}}))))}_linkHover(b,_,C){var N;(N=this._currentLink)!=null&&N.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(_,!0),this._currentLink.state.decorations.pointerCursor&&b.classList.add("xterm-cursor-pointer")),_.hover&&_.hover(C,_.text)}_fireUnderlineEvent(b,_){const C=b.range,N=this._bufferService.buffer.ydisp,$=this._createLinkUnderlineEvent(C.start.x-1,C.start.y-N-1,C.end.x,C.end.y-N-1,void 0);(_?this._onShowLinkUnderline:this._onHideLinkUnderline).fire($)}_linkLeave(b,_,C){var N;(N=this._currentLink)!=null&&N.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(_,!1),this._currentLink.state.decorations.pointerCursor&&b.classList.remove("xterm-cursor-pointer")),_.leave&&_.leave(C,_.text)}_linkAtPosition(b,_){const C=b.range.start.y*this._bufferService.cols+b.range.start.x,N=b.range.end.y*this._bufferService.cols+b.range.end.x,$=_.y*this._bufferService.cols+_.x;return C<=$&&$<=N}_positionFromMouseEvent(b,_,C){const N=C.getCoords(b,_,this._bufferService.cols,this._bufferService.rows);if(N)return{x:N[0],y:N[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(b,_,C,N,$){return{x1:b,y1:_,x2:C,y2:N,cols:this._bufferService.cols,fg:$}}};u.Linkifier=y=m([x(1,j.IMouseService),x(2,j.IRenderService),x(3,E.IBufferService),x(4,j.ILinkProviderService)],y)},9042:(d,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.tooMuchOutput=u.promptLabel=void 0,u.promptLabel="Terminal input",u.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(d,u,h){var m=this&&this.__decorate||function(j,y,b,_){var C,N=arguments.length,$=N<3?y:_===null?_=Object.getOwnPropertyDescriptor(y,b):_;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")$=Reflect.decorate(j,y,b,_);else for(var R=j.length-1;R>=0;R--)(C=j[R])&&($=(N<3?C($):N>3?C(y,b,$):C(y,b))||$);return N>3&&$&&Object.defineProperty(y,b,$),$},x=this&&this.__param||function(j,y){return function(b,_){y(b,_,j)}};Object.defineProperty(u,"__esModule",{value:!0}),u.OscLinkProvider=void 0;const g=h(511),v=h(2585);let S=u.OscLinkProvider=class{constructor(j,y,b){this._bufferService=j,this._optionsService=y,this._oscLinkService=b}provideLinks(j,y){var z;const b=this._bufferService.buffer.lines.get(j-1);if(!b)return void y(void 0);const _=[],C=this._optionsService.rawOptions.linkHandler,N=new g.CellData,$=b.getTrimmedLength();let R=-1,O=-1,I=!1;for(let U=0;U<$;U++)if(O!==-1||b.hasContent(U)){if(b.loadCell(U,N),N.hasExtendedAttrs()&&N.extended.urlId){if(O===-1){O=U,R=N.extended.urlId;continue}I=N.extended.urlId!==R}else O!==-1&&(I=!0);if(I||O!==-1&&U===$-1){const W=(z=this._oscLinkService.getLinkData(R))==null?void 0:z.uri;if(W){const Y={start:{x:O+1,y:j},end:{x:U+(I||U!==$-1?0:1),y:j}};let V=!1;if(!(C!=null&&C.allowNonHttpProtocols))try{const H=new URL(W);["http:","https:"].includes(H.protocol)||(V=!0)}catch{V=!0}V||_.push({text:W,range:Y,activate:(H,te)=>C?C.activate(H,te,Y):E(0,te),hover:(H,te)=>{var ae;return(ae=C==null?void 0:C.hover)==null?void 0:ae.call(C,H,te,Y)},leave:(H,te)=>{var ae;return(ae=C==null?void 0:C.leave)==null?void 0:ae.call(C,H,te,Y)}})}I=!1,N.hasExtendedAttrs()&&N.extended.urlId?(O=U,R=N.extended.urlId):(O=-1,R=-1)}}y(_)}};function E(j,y){if(confirm(`Do you want to navigate to ${y}?
|
|
2900
2900
|
|
|
@@ -2958,8 +2958,8 @@ ${n}</tr>
|
|
|
2958
2958
|
`}strong({tokens:n}){return`<strong>${this.parser.parseInline(n)}</strong>`}em({tokens:n}){return`<em>${this.parser.parseInline(n)}</em>`}codespan({text:n}){return`<code>${n}</code>`}br(n){return"<br>"}del({tokens:n}){return`<del>${this.parser.parseInline(n)}</del>`}link({href:n,title:r,tokens:i}){const o=this.parser.parseInline(i),l=d1(n);if(l===null)return o;n=l;let d='<a href="'+n+'"';return r&&(d+=' title="'+r+'"'),d+=">"+o+"</a>",d}image({href:n,title:r,text:i}){const o=d1(n);if(o===null)return i;n=o;let l=`<img src="${n}" alt="${i}"`;return r&&(l+=` title="${r}"`),l+=">",l}text(n){return"tokens"in n&&n.tokens?this.parser.parseInline(n.tokens):n.text}}class u0{strong({text:n}){return n}em({text:n}){return n}codespan({text:n}){return n}del({text:n}){return n}html({text:n}){return n}text({text:n}){return n}link({text:n}){return""+n}image({text:n}){return""+n}br(){return""}}class va{constructor(n){Fn(this,"options");Fn(this,"renderer");Fn(this,"textRenderer");this.options=n||Bu,this.options.renderer=this.options.renderer||new vy,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new u0}static parse(n,r){return new va(r).parse(n)}static parseInline(n,r){return new va(r).parseInline(n)}parse(n,r=!0){let i="";for(let o=0;o<n.length;o++){const l=n[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[l.type]){const u=l,h=this.options.extensions.renderers[u.type].call({parser:this},u);if(h!==!1||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(u.type)){i+=h||"";continue}}const d=l;switch(d.type){case"space":{i+=this.renderer.space(d);continue}case"hr":{i+=this.renderer.hr(d);continue}case"heading":{i+=this.renderer.heading(d);continue}case"code":{i+=this.renderer.code(d);continue}case"table":{i+=this.renderer.table(d);continue}case"blockquote":{i+=this.renderer.blockquote(d);continue}case"list":{i+=this.renderer.list(d);continue}case"html":{i+=this.renderer.html(d);continue}case"paragraph":{i+=this.renderer.paragraph(d);continue}case"text":{let u=d,h=this.renderer.text(u);for(;o+1<n.length&&n[o+1].type==="text";)u=n[++o],h+=`
|
|
2959
2959
|
`+this.renderer.text(u);r?i+=this.renderer.paragraph({type:"paragraph",raw:h,text:h,tokens:[{type:"text",raw:h,text:h}]}):i+=h;continue}default:{const u='Token with "'+d.type+'" type was not found.';if(this.options.silent)return console.error(u),"";throw new Error(u)}}}return i}parseInline(n,r){r=r||this.renderer;let i="";for(let o=0;o<n.length;o++){const l=n[o];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[l.type]){const u=this.options.extensions.renderers[l.type].call({parser:this},l);if(u!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(l.type)){i+=u||"";continue}}const d=l;switch(d.type){case"escape":{i+=r.text(d);break}case"html":{i+=r.html(d);break}case"link":{i+=r.link(d);break}case"image":{i+=r.image(d);break}case"strong":{i+=r.strong(d);break}case"em":{i+=r.em(d);break}case"codespan":{i+=r.codespan(d);break}case"br":{i+=r.br(d);break}case"del":{i+=r.del(d);break}case"text":{i+=r.text(d);break}default:{const u='Token with "'+d.type+'" type was not found.';if(this.options.silent)return console.error(u),"";throw new Error(u)}}}return i}}class Im{constructor(n){Fn(this,"options");this.options=n||Bu}preprocess(n){return n}postprocess(n){return n}processAllTokens(n){return n}}Fn(Im,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens"]));class w3{constructor(...n){Fn(this,"defaults",s0());Fn(this,"options",this.setOptions);Fn(this,"parse",this.parseMarkdown(ya.lex,va.parse));Fn(this,"parseInline",this.parseMarkdown(ya.lexInline,va.parseInline));Fn(this,"Parser",va);Fn(this,"Renderer",vy);Fn(this,"TextRenderer",u0);Fn(this,"Lexer",ya);Fn(this,"Tokenizer",xy);Fn(this,"Hooks",Im);this.use(...n)}walkTokens(n,r){var o,l;let i=[];for(const d of n)switch(i=i.concat(r.call(this,d)),d.type){case"table":{const u=d;for(const h of u.header)i=i.concat(this.walkTokens(h.tokens,r));for(const h of u.rows)for(const m of h)i=i.concat(this.walkTokens(m.tokens,r));break}case"list":{const u=d;i=i.concat(this.walkTokens(u.items,r));break}default:{const u=d;(l=(o=this.defaults.extensions)==null?void 0:o.childTokens)!=null&&l[u.type]?this.defaults.extensions.childTokens[u.type].forEach(h=>{const m=u[h].flat(1/0);i=i.concat(this.walkTokens(m,r))}):u.tokens&&(i=i.concat(this.walkTokens(u.tokens,r)))}}return i}use(...n){const r=this.defaults.extensions||{renderers:{},childTokens:{}};return n.forEach(i=>{const o={...i};if(o.async=this.defaults.async||o.async||!1,i.extensions&&(i.extensions.forEach(l=>{if(!l.name)throw new Error("extension name required");if("renderer"in l){const d=r.renderers[l.name];d?r.renderers[l.name]=function(...u){let h=l.renderer.apply(this,u);return h===!1&&(h=d.apply(this,u)),h}:r.renderers[l.name]=l.renderer}if("tokenizer"in l){if(!l.level||l.level!=="block"&&l.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");const d=r[l.level];d?d.unshift(l.tokenizer):r[l.level]=[l.tokenizer],l.start&&(l.level==="block"?r.startBlock?r.startBlock.push(l.start):r.startBlock=[l.start]:l.level==="inline"&&(r.startInline?r.startInline.push(l.start):r.startInline=[l.start]))}"childTokens"in l&&l.childTokens&&(r.childTokens[l.name]=l.childTokens)}),o.extensions=r),i.renderer){const l=this.defaults.renderer||new vy(this.defaults);for(const d in i.renderer){if(!(d in l))throw new Error(`renderer '${d}' does not exist`);if(["options","parser"].includes(d))continue;const u=d,h=i.renderer[u],m=l[u];l[u]=(...x)=>{let g=h.apply(l,x);return g===!1&&(g=m.apply(l,x)),g||""}}o.renderer=l}if(i.tokenizer){const l=this.defaults.tokenizer||new xy(this.defaults);for(const d in i.tokenizer){if(!(d in l))throw new Error(`tokenizer '${d}' does not exist`);if(["options","rules","lexer"].includes(d))continue;const u=d,h=i.tokenizer[u],m=l[u];l[u]=(...x)=>{let g=h.apply(l,x);return g===!1&&(g=m.apply(l,x)),g}}o.tokenizer=l}if(i.hooks){const l=this.defaults.hooks||new Im;for(const d in i.hooks){if(!(d in l))throw new Error(`hook '${d}' does not exist`);if(d==="options")continue;const u=d,h=i.hooks[u],m=l[u];Im.passThroughHooks.has(d)?l[u]=x=>{if(this.defaults.async)return Promise.resolve(h.call(l,x)).then(v=>m.call(l,v));const g=h.call(l,x);return m.call(l,g)}:l[u]=(...x)=>{let g=h.apply(l,x);return g===!1&&(g=m.apply(l,x)),g}}o.hooks=l}if(i.walkTokens){const l=this.defaults.walkTokens,d=i.walkTokens;o.walkTokens=function(u){let h=[];return h.push(d.call(this,u)),l&&(h=h.concat(l.call(this,u))),h}}this.defaults={...this.defaults,...o}}),this}setOptions(n){return this.defaults={...this.defaults,...n},this}lexer(n,r){return ya.lex(n,r??this.defaults)}parser(n,r){return va.parse(n,r??this.defaults)}parseMarkdown(n,r){return(o,l)=>{const d={...l},u={...this.defaults,...d},h=this.onError(!!u.silent,!!u.async);if(this.defaults.async===!0&&d.async===!1)return h(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof o>"u"||o===null)return h(new Error("marked(): input parameter is undefined or null"));if(typeof o!="string")return h(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(o)+", string expected"));if(u.hooks&&(u.hooks.options=u),u.async)return Promise.resolve(u.hooks?u.hooks.preprocess(o):o).then(m=>n(m,u)).then(m=>u.hooks?u.hooks.processAllTokens(m):m).then(m=>u.walkTokens?Promise.all(this.walkTokens(m,u.walkTokens)).then(()=>m):m).then(m=>r(m,u)).then(m=>u.hooks?u.hooks.postprocess(m):m).catch(h);try{u.hooks&&(o=u.hooks.preprocess(o));let m=n(o,u);u.hooks&&(m=u.hooks.processAllTokens(m)),u.walkTokens&&this.walkTokens(m,u.walkTokens);let x=r(m,u);return u.hooks&&(x=u.hooks.postprocess(x)),x}catch(m){return h(m)}}}onError(n,r){return i=>{if(i.message+=`
|
|
2960
2960
|
Please report this to https://github.com/markedjs/marked.`,n){const o="<p>An error occurred:</p><pre>"+Oi(i.message+"",!0)+"</pre>";return r?Promise.resolve(o):o}if(r)return Promise.reject(i);throw i}}}const Lu=new w3;function wn(e,n){return Lu.parse(e,n)}wn.options=wn.setOptions=function(e){return Lu.setOptions(e),wn.defaults=Lu.defaults,mC(wn.defaults),wn};wn.getDefaults=s0;wn.defaults=Bu;wn.use=function(...e){return Lu.use(...e),wn.defaults=Lu.defaults,mC(wn.defaults),wn};wn.walkTokens=function(e,n){return Lu.walkTokens(e,n)};wn.parseInline=Lu.parseInline;wn.Parser=va;wn.parser=va.parse;wn.Renderer=vy;wn.TextRenderer=u0;wn.Lexer=ya;wn.lexer=ya.lex;wn.Tokenizer=xy;wn.Hooks=Im;wn.parse=wn;wn.options;wn.setOptions;wn.use;wn.walkTokens;wn.parseInline;va.parse;ya.lex;/*! @license DOMPurify 3.4.11 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.11/LICENSE */function m1(e,n){(n==null||n>e.length)&&(n=e.length);for(var r=0,i=Array(n);r<n;r++)i[r]=e[r];return i}function _3(e){if(Array.isArray(e))return e}function k3(e,n){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var i,o,l,d,u=[],h=!0,m=!1;try{if(l=(r=r.call(e)).next,n!==0)for(;!(h=(i=l.call(r)).done)&&(u.push(i.value),u.length!==n);h=!0);}catch(x){m=!0,o=x}finally{try{if(!h&&r.return!=null&&(d=r.return(),Object(d)!==d))return}finally{if(m)throw o}}return u}}function S3(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
2961
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function C3(e,n){return _3(e)||k3(e,n)||j3(e,n)||S3()}function j3(e,n){if(e){if(typeof e=="string")return m1(e,n);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?m1(e,n):void 0}}const CC=Object.entries,g1=Object.setPrototypeOf,E3=Object.isFrozen,N3=Object.getPrototypeOf,T3=Object.getOwnPropertyDescriptor;let ks=Object.freeze,Ss=Object.seal,Ih=Object.create,jC=typeof Reflect<"u"&&Reflect,tw=jC.apply,nw=jC.construct;ks||(ks=function(n){return n});Ss||(Ss=function(n){return n});tw||(tw=function(n,r){for(var i=arguments.length,o=new Array(i>2?i-2:0),l=2;l<i;l++)o[l-2]=arguments[l];return n.apply(r,o)});nw||(nw=function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;o<r;o++)i[o-1]=arguments[o];return new n(...i)});const Jp=Nr(Array.prototype.forEach),$3=Nr(Array.prototype.lastIndexOf),x1=Nr(Array.prototype.pop),Eh=Nr(Array.prototype.push),A3=Nr(Array.prototype.splice),pc=Array.isArray,bm=Nr(String.prototype.toLowerCase),Bv=Nr(String.prototype.toString),y1=Nr(String.prototype.match),Qp=Nr(String.prototype.replace),v1=Nr(String.prototype.indexOf),R3=Nr(String.prototype.trim),M3=Nr(Number.prototype.toString),I3=Nr(Boolean.prototype.toString),b1=typeof BigInt>"u"?null:Nr(BigInt.prototype.toString),w1=typeof Symbol>"u"?null:Nr(Symbol.prototype.toString),ns=Nr(Object.prototype.hasOwnProperty),Zp=Nr(Object.prototype.toString),_s=Nr(RegExp.prototype.test),bu=P3(TypeError);function Nr(e){return function(n){n instanceof RegExp&&(n.lastIndex=0);for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;o<r;o++)i[o-1]=arguments[o];return tw(e,n,i)}}function P3(e){return function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return nw(e,r)}}function Sn(e,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:bm;if(g1&&g1(e,null),!pc(n))return e;let i=n.length;for(;i--;){let o=n[i];if(typeof o=="string"){const l=r(o);l!==o&&(E3(n)||(n[i]=l),o=l)}e[o]=!0}return e}function D3(e){for(let n=0;n<e.length;n++)ns(e,n)||(e[n]=null);return e}function Vs(e){const n=Ih(null);for(const i of CC(e)){var r=C3(i,2);const o=r[0],l=r[1];ns(e,o)&&(pc(l)?n[o]=D3(l):l&&typeof l=="object"&&l.constructor===Object?n[o]=Vs(l):n[o]=l)}return n}function O3(e){switch(typeof e){case"string":return e;case"number":return M3(e);case"boolean":return I3(e);case"bigint":return b1?b1(e):"0";case"symbol":return w1?w1(e):"Symbol()";case"undefined":return Zp(e);case"function":case"object":{if(e===null)return Zp(e);const n=e,r=pa(n,"toString");if(typeof r=="function"){const i=r(n);return typeof i=="string"?i:Zp(i)}return Zp(e)}default:return Zp(e)}}function pa(e,n){for(;e!==null;){const i=T3(e,n);if(i){if(i.get)return Nr(i.get);if(typeof i.value=="function")return Nr(i.value)}e=N3(e)}function r(){return null}return r}function L3(e){try{return _s(e,""),!0}catch{return!1}}const _1=ks(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Fv=ks(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Uv=ks(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),z3=ks(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Hv=ks(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),B3=ks(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),k1=ks(["#text"]),S1=ks(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Wv=ks(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),C1=ks(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),vx=ks(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),F3=Ss(/{{[\w\W]*|^[\w\W]*}}/g),U3=Ss(/<%[\w\W]*|^[\w\W]*%>/g),H3=Ss(/\${[\w\W]*/g),W3=Ss(/^data-[\-\w.\u00B7-\uFFFF]+$/),q3=Ss(/^aria-[\-\w]+$/),j1=Ss(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),V3=Ss(/^(?:\w+script|data):/i),G3=Ss(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),K3=Ss(/^html$/i),X3=Ss(/^[a-z][.\w]*(-[.\w]+)+$/i),E1=Ss(/<[/\w!]/g),Y3=Ss(/<[/\w]/g),J3=Ss(/<\/no(script|embed|frames)/i),Q3=Ss(/\/>/i),fa={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Z3=function(){return typeof window>"u"?null:window},eA=function(n,r){if(typeof n!="object"||typeof n.createPolicy!="function")return null;let i=null;const o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(i=r.getAttribute(o));const l="dompurify"+(i?"#"+i:"");try{return n.createPolicy(l,{createHTML(d){return d},createScriptURL(d){return d}})}catch{return console.warn("TrustedTypes policy "+l+" could not be created."),null}},N1=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Zl=function(n,r,i,o){return ns(n,r)&&pc(n[r])?Sn(o.base?Vs(o.base):{},n[r],o.transform):i};function EC(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Z3();const n=ft=>EC(ft);if(n.version="3.4.11",n.removed=[],!e||!e.document||e.document.nodeType!==fa.document||!e.Element)return n.isSupported=!1,n;let r=e.document;const i=r,o=i.currentScript;e.DocumentFragment;const l=e.HTMLTemplateElement,d=e.Node,u=e.Element,h=e.NodeFilter,m=e.NamedNodeMap;m===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const x=e.DOMParser,g=e.trustedTypes,v=u.prototype,S=pa(v,"cloneNode"),E=pa(v,"remove"),j=pa(v,"nextSibling"),y=pa(v,"childNodes"),b=pa(v,"parentNode"),_=pa(v,"shadowRoot"),C=pa(v,"attributes"),N=d&&d.prototype?pa(d.prototype,"nodeType"):null,$=d&&d.prototype?pa(d.prototype,"nodeName"):null;if(typeof l=="function"){const ft=r.createElement("template");ft.content&&ft.content.ownerDocument&&(r=ft.content.ownerDocument)}let R,O="",I,z=!1,U=0;const W=function(){if(U>0)throw bu('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},Y=function(be){W(),U++;try{return R.createHTML(be)}finally{U--}},V=function(be){W(),U++;try{return R.createScriptURL(be)}finally{U--}},H=function(){return z||(I=eA(g,o),z=!0),I},te=r,ae=te.implementation,oe=te.createNodeIterator,ie=te.createDocumentFragment,X=te.getElementsByTagName,Q=i.importNode;let J=N1();n.isSupported=typeof CC=="function"&&typeof b=="function"&&ae&&ae.createHTMLDocument!==void 0;const le=F3,ce=U3,pe=H3,Ae=W3,Se=q3,ye=V3,ne=G3,we=X3;let Ne=j1,Je=null;const lt=Sn({},[..._1,...Fv,...Uv,...Hv,...k1]);let xt=null;const Rt=Sn({},[...S1,...Wv,...C1,...vx]);let He=Object.seal(Ih(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),vt=null,st=null;const an=Object.seal(Ih(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let sn=!0,Ye=!0,yt=!1,kt=!0,Kt=!1,On=!0,Rn=!1,Br=!1,Tr=null,nt=null,St=!1,Tt=!1,cn=!1,nn=!1,$r=!0,Ta=!1;const Vo="user-content-";let vi=!0,yn=!1,Fr={},Zn=null;const bi=Sn({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Ms=null;const as=Sn({},["audio","video","img","source","image","track"]);let Fi=null;const wi=Sn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),_i="http://www.w3.org/1998/Math/MathML",Is="http://www.w3.org/2000/svg",Ar="http://www.w3.org/1999/xhtml";let Ur=Ar,Js=!1,Rr=null;const ls=Sn({},[_i,Is,Ar],Bv),js=ks(["mi","mo","mn","ms","mtext"]);let ho=Sn({},js);const Qs=ks(["annotation-xml"]);let Zs=Sn({},Qs);const ei=Sn({},["title","style","font","a","script"]);let zt=null;const Hr=["application/xhtml+xml","text/html"],Hn="text/html";let _n=null,Ct=null;const Ui=r.createElement("form"),fo=function(be){return be instanceof RegExp||be instanceof Function},$a=function(){let be=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Ct&&Ct===be)return;(!be||typeof be!="object")&&(be={}),be=Vs(be),zt=Hr.indexOf(be.PARSER_MEDIA_TYPE)===-1?Hn:be.PARSER_MEDIA_TYPE,_n=zt==="application/xhtml+xml"?Bv:bm,Je=Zl(be,"ALLOWED_TAGS",lt,{transform:_n}),xt=Zl(be,"ALLOWED_ATTR",Rt,{transform:_n}),Rr=Zl(be,"ALLOWED_NAMESPACES",ls,{transform:Bv}),Fi=Zl(be,"ADD_URI_SAFE_ATTR",wi,{transform:_n,base:wi}),Ms=Zl(be,"ADD_DATA_URI_TAGS",as,{transform:_n,base:as}),Zn=Zl(be,"FORBID_CONTENTS",bi,{transform:_n}),vt=Zl(be,"FORBID_TAGS",Vs({}),{transform:_n}),st=Zl(be,"FORBID_ATTR",Vs({}),{transform:_n}),Fr=ns(be,"USE_PROFILES")?be.USE_PROFILES&&typeof be.USE_PROFILES=="object"?Vs(be.USE_PROFILES):be.USE_PROFILES:!1,sn=be.ALLOW_ARIA_ATTR!==!1,Ye=be.ALLOW_DATA_ATTR!==!1,yt=be.ALLOW_UNKNOWN_PROTOCOLS||!1,kt=be.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Kt=be.SAFE_FOR_TEMPLATES||!1,On=be.SAFE_FOR_XML!==!1,Rn=be.WHOLE_DOCUMENT||!1,Tt=be.RETURN_DOM||!1,cn=be.RETURN_DOM_FRAGMENT||!1,nn=be.RETURN_TRUSTED_TYPE||!1,St=be.FORCE_BODY||!1,$r=be.SANITIZE_DOM!==!1,Ta=be.SANITIZE_NAMED_PROPS||!1,vi=be.KEEP_CONTENT!==!1,yn=be.IN_PLACE||!1,Ne=L3(be.ALLOWED_URI_REGEXP)?be.ALLOWED_URI_REGEXP:j1,Ur=typeof be.NAMESPACE=="string"?be.NAMESPACE:Ar,ho=ns(be,"MATHML_TEXT_INTEGRATION_POINTS")&&be.MATHML_TEXT_INTEGRATION_POINTS&&typeof be.MATHML_TEXT_INTEGRATION_POINTS=="object"?Vs(be.MATHML_TEXT_INTEGRATION_POINTS):Sn({},js),Zs=ns(be,"HTML_INTEGRATION_POINTS")&&be.HTML_INTEGRATION_POINTS&&typeof be.HTML_INTEGRATION_POINTS=="object"?Vs(be.HTML_INTEGRATION_POINTS):Sn({},Qs);const Pe=ns(be,"CUSTOM_ELEMENT_HANDLING")&&be.CUSTOM_ELEMENT_HANDLING&&typeof be.CUSTOM_ELEMENT_HANDLING=="object"?Vs(be.CUSTOM_ELEMENT_HANDLING):Ih(null);if(He=Ih(null),ns(Pe,"tagNameCheck")&&fo(Pe.tagNameCheck)&&(He.tagNameCheck=Pe.tagNameCheck),ns(Pe,"attributeNameCheck")&&fo(Pe.attributeNameCheck)&&(He.attributeNameCheck=Pe.attributeNameCheck),ns(Pe,"allowCustomizedBuiltInElements")&&typeof Pe.allowCustomizedBuiltInElements=="boolean"&&(He.allowCustomizedBuiltInElements=Pe.allowCustomizedBuiltInElements),Ss(He),Kt&&(Ye=!1),cn&&(Tt=!0),Fr&&(Je=Sn({},k1),xt=Ih(null),Fr.html===!0&&(Sn(Je,_1),Sn(xt,S1)),Fr.svg===!0&&(Sn(Je,Fv),Sn(xt,Wv),Sn(xt,vx)),Fr.svgFilters===!0&&(Sn(Je,Uv),Sn(xt,Wv),Sn(xt,vx)),Fr.mathMl===!0&&(Sn(Je,Hv),Sn(xt,C1),Sn(xt,vx))),an.tagCheck=null,an.attributeCheck=null,ns(be,"ADD_TAGS")&&(typeof be.ADD_TAGS=="function"?an.tagCheck=be.ADD_TAGS:pc(be.ADD_TAGS)&&(Je===lt&&(Je=Vs(Je)),Sn(Je,be.ADD_TAGS,_n))),ns(be,"ADD_ATTR")&&(typeof be.ADD_ATTR=="function"?an.attributeCheck=be.ADD_ATTR:pc(be.ADD_ATTR)&&(xt===Rt&&(xt=Vs(xt)),Sn(xt,be.ADD_ATTR,_n))),ns(be,"ADD_URI_SAFE_ATTR")&&pc(be.ADD_URI_SAFE_ATTR)&&Sn(Fi,be.ADD_URI_SAFE_ATTR,_n),ns(be,"FORBID_CONTENTS")&&pc(be.FORBID_CONTENTS)&&(Zn===bi&&(Zn=Vs(Zn)),Sn(Zn,be.FORBID_CONTENTS,_n)),ns(be,"ADD_FORBID_CONTENTS")&&pc(be.ADD_FORBID_CONTENTS)&&(Zn===bi&&(Zn=Vs(Zn)),Sn(Zn,be.ADD_FORBID_CONTENTS,_n)),vi&&(Je["#text"]=!0),Rn&&Sn(Je,["html","head","body"]),Je.table&&(Sn(Je,["tbody"]),delete vt.tbody),be.TRUSTED_TYPES_POLICY){if(typeof be.TRUSTED_TYPES_POLICY.createHTML!="function")throw bu('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof be.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw bu('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Qe=R;R=be.TRUSTED_TYPES_POLICY;try{O=Y("")}catch(Et){throw R=Qe,Et}}else be.TRUSTED_TYPES_POLICY===null?(R=void 0,O=""):(R===void 0&&(R=H()),R&&typeof O=="string"&&(O=Y("")));ks&&ks(be),Ct=be},po=Sn({},[...Fv,...Uv,...z3]),mo=Sn({},[...Hv,...B3]),Go=function(be,Pe,Qe){return Pe.namespaceURI===Ar?be==="svg":Pe.namespaceURI===_i?be==="svg"&&(Qe==="annotation-xml"||ho[Qe]):!!po[be]},Sr=function(be,Pe,Qe){return Pe.namespaceURI===Ar?be==="math":Pe.namespaceURI===Is?be==="math"&&Zs[Qe]:!!mo[be]},Aa=function(be,Pe,Qe){return Pe.namespaceURI===Is&&!Zs[Qe]||Pe.namespaceURI===_i&&!ho[Qe]?!1:!mo[be]&&(ei[be]||!po[be])},Ra=function(be){let Pe=b(be);(!Pe||!Pe.tagName)&&(Pe={namespaceURI:Ur,tagName:"template"});const Qe=bm(be.tagName),Et=bm(Pe.tagName);return Rr[be.namespaceURI]?be.namespaceURI===Is?Go(Qe,Pe,Et):be.namespaceURI===_i?Sr(Qe,Pe,Et):be.namespaceURI===Ar?Aa(Qe,Pe,Et):!!(zt==="application/xhtml+xml"&&Rr[be.namespaceURI]):!1},kn=function(be){Eh(n.removed,{element:be});try{b(be).removeChild(be)}catch{if(E(be),!b(be))throw bu("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Mr=function(be){const Pe=y(be);if(Pe){const Et=[];Jp(Pe,en=>{Eh(Et,en)}),Jp(Et,en=>{try{E(en)}catch{}})}const Qe=C(be);if(Qe)for(let Et=Qe.length-1;Et>=0;--Et){const en=Qe[Et],ln=en&&en.name;if(typeof ln=="string")try{be.removeAttribute(ln)}catch{}}},Vn=function(be,Pe){try{Eh(n.removed,{attribute:Pe.getAttributeNode(be),from:Pe})}catch{Eh(n.removed,{attribute:null,from:Pe})}if(Pe.removeAttribute(be),be==="is")if(Tt||cn)try{kn(Pe)}catch{}else try{Pe.setAttribute(be,"")}catch{}},Ir=function(be){const Pe=C(be);if(Pe)for(let Qe=Pe.length-1;Qe>=0;--Qe){const Et=Pe[Qe],en=Et&&Et.name;if(!(typeof en!="string"||xt[_n(en)]))try{be.removeAttribute(en)}catch{}}},ti=function(be){const Pe=[be];for(;Pe.length>0;){const Qe=Pe.pop();(N?N(Qe):Qe.nodeType)===fa.element&&Ir(Qe);const en=y(Qe);if(en)for(let ln=en.length-1;ln>=0;--ln)Pe.push(en[ln])}},Hi=function(be){let Pe=null,Qe=null;if(St)be="<remove></remove>"+be;else{const ln=y1(be,/^[\r\n\t ]+/);Qe=ln&&ln[0]}zt==="application/xhtml+xml"&&Ur===Ar&&(be='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+be+"</body></html>");const Et=R?Y(be):be;if(Ur===Ar)try{Pe=new x().parseFromString(Et,zt)}catch{}if(!Pe||!Pe.documentElement){Pe=ae.createDocument(Ur,"template",null);try{Pe.documentElement.innerHTML=Js?O:Et}catch{}}const en=Pe.body||Pe.documentElement;return be&&Qe&&en.insertBefore(r.createTextNode(Qe),en.childNodes[0]||null),Ur===Ar?X.call(Pe,Rn?"html":"body")[0]:Rn?Pe.documentElement:en},ki=function(be){return oe.call(be.ownerDocument||be,be,h.SHOW_ELEMENT|h.SHOW_COMMENT|h.SHOW_TEXT|h.SHOW_PROCESSING_INSTRUCTION|h.SHOW_CDATA_SECTION,null)},cs=function(be){return be=Qp(be,le," "),be=Qp(be,ce," "),be=Qp(be,pe," "),be},gr=function(be){var Pe;be.normalize();const Qe=oe.call(be.ownerDocument||be,be,h.SHOW_TEXT|h.SHOW_COMMENT|h.SHOW_CDATA_SECTION|h.SHOW_PROCESSING_INSTRUCTION,null);let Et=Qe.nextNode();for(;Et;)Et.data=cs(Et.data),Et=Qe.nextNode();const en=(Pe=be.querySelectorAll)===null||Pe===void 0?void 0:Pe.call(be,"template");en&&Jp(en,ln=>{Gn(ln.content)&&gr(ln.content)})},Bt=function(be){const Pe=$?$(be):null;return typeof Pe!="string"||_n(Pe)!=="form"?!1:typeof be.nodeName!="string"||typeof be.textContent!="string"||typeof be.removeChild!="function"||be.attributes!==C(be)||typeof be.removeAttribute!="function"||typeof be.setAttribute!="function"||typeof be.namespaceURI!="string"||typeof be.insertBefore!="function"||typeof be.hasChildNodes!="function"||be.nodeType!==N(be)||be.childNodes!==y(be)},Gn=function(be){if(!N||typeof be!="object"||be===null)return!1;try{return N(be)===fa.documentFragment}catch{return!1}},Si=function(be){if(!N||typeof be!="object"||be===null)return!1;try{return typeof N(be)=="number"}catch{return!1}};function us(ft,be,Pe){ft.length!==0&&Jp(ft,Qe=>{Qe.call(n,be,Pe,Ct)})}const Ko=function(be,Pe){return!!(On&&be.hasChildNodes()&&!Si(be.firstElementChild)&&_s(E1,be.textContent)&&_s(E1,be.innerHTML)||On&&be.namespaceURI===Ar&&Pe==="style"&&Si(be.firstElementChild)||be.nodeType===fa.processingInstruction||On&&be.nodeType===fa.comment&&_s(Y3,be.data))},Ci=function(be,Pe){if(!vt[Pe]&&on(Pe)&&(He.tagNameCheck instanceof RegExp&&_s(He.tagNameCheck,Pe)||He.tagNameCheck instanceof Function&&He.tagNameCheck(Pe)))return!1;if(vi&&!Zn[Pe]){const Qe=b(be),Et=y(be);if(Et&&Qe){const en=Et.length;for(let ln=en-1;ln>=0;--ln){const $n=yn?Et[ln]:S(Et[ln],!0);Qe.insertBefore($n,j(be))}}}return kn(be),!0},Wr=function(be){if(us(J.beforeSanitizeElements,be,null),Bt(be))return kn(be),!0;const Pe=_n($?$(be):be.nodeName);if(us(J.uponSanitizeElement,be,{tagName:Pe,allowedTags:Je}),Ko(be,Pe))return kn(be),!0;if(vt[Pe]||!(an.tagCheck instanceof Function&&an.tagCheck(Pe))&&!Je[Pe])return Ci(be,Pe);if((N?N(be):be.nodeType)===fa.element&&!Ra(be)||(Pe==="noscript"||Pe==="noembed"||Pe==="noframes")&&_s(J3,be.innerHTML))return kn(be),!0;if(Kt&&be.nodeType===fa.text){const Et=cs(be.textContent);be.textContent!==Et&&(Eh(n.removed,{element:be.cloneNode()}),be.textContent=Et)}return us(J.afterSanitizeElements,be,null),!1},Ps=function(be,Pe,Qe){if(st[Pe]||$r&&(Pe==="id"||Pe==="name")&&(Qe in r||Qe in Ui))return!1;const Et=xt[Pe]||an.attributeCheck instanceof Function&&an.attributeCheck(Pe,be);if(!(Ye&&_s(Ae,Pe))){if(!(sn&&_s(Se,Pe))){if(Et){if(!Fi[Pe]){if(!_s(Ne,Qp(Qe,ne,""))){if(!((Pe==="src"||Pe==="xlink:href"||Pe==="href")&&be!=="script"&&v1(Qe,"data:")===0&&Ms[be])){if(!(yt&&!_s(ye,Qp(Qe,ne,"")))){if(Qe)return!1}}}}}else if(!(on(be)&&(He.tagNameCheck instanceof RegExp&&_s(He.tagNameCheck,be)||He.tagNameCheck instanceof Function&&He.tagNameCheck(be))&&(He.attributeNameCheck instanceof RegExp&&_s(He.attributeNameCheck,Pe)||He.attributeNameCheck instanceof Function&&He.attributeNameCheck(Pe,be))||Pe==="is"&&He.allowCustomizedBuiltInElements&&(He.tagNameCheck instanceof RegExp&&_s(He.tagNameCheck,Qe)||He.tagNameCheck instanceof Function&&He.tagNameCheck(Qe))))return!1}}return!0},ji=Sn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),on=function(be){return!ji[bm(be)]&&_s(we,be)},ds=function(be,Pe,Qe,Et){if(R&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!Qe)switch(g.getAttributeType(be,Pe)){case"TrustedHTML":return Y(Et);case"TrustedScriptURL":return V(Et)}return Et},Wi=function(be,Pe,Qe,Et){try{Qe?be.setAttributeNS(Qe,Pe,Et):be.setAttribute(Pe,Et),Bt(be)?kn(be):x1(n.removed)}catch{Vn(Pe,be)}},Es=function(be){us(J.beforeSanitizeAttributes,be,null);const Pe=be.attributes;if(!Pe||Bt(be))return;const Qe={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:xt,forceKeepAttr:void 0};let Et=Pe.length;const en=_n(be.nodeName);for(;Et--;){const ln=Pe[Et],$n=ln.name,En=ln.namespaceURI,er=ln.value,Ln=_n($n),sr=er;let Nn=$n==="value"?sr:R3(sr);if(Qe.attrName=Ln,Qe.attrValue=Nn,Qe.keepAttr=!0,Qe.forceKeepAttr=void 0,us(J.uponSanitizeAttribute,be,Qe),Nn=Qe.attrValue,Ta&&(Ln==="id"||Ln==="name")&&v1(Nn,Vo)!==0&&(Vn($n,be),Nn=Vo+Nn),On&&_s(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Nn)){Vn($n,be);continue}if(Ln==="attributename"&&y1(Nn,"href")){Vn($n,be);continue}if(!Qe.forceKeepAttr){if(!Qe.keepAttr){Vn($n,be);continue}if(!kt&&_s(Q3,Nn)){Vn($n,be);continue}if(Kt&&(Nn=cs(Nn)),!Ps(en,Ln,Nn)){Vn($n,be);continue}Nn=ds(en,Ln,En,Nn),Nn!==sr&&Wi(be,$n,En,Nn)}}us(J.afterSanitizeAttributes,be,null)},Ke=function(be){let Pe=null;const Qe=ki(be);for(us(J.beforeSanitizeShadowDOM,be,null);Pe=Qe.nextNode();)if(us(J.uponSanitizeShadowNode,Pe,null),Wr(Pe),Es(Pe),Gn(Pe.content)&&Ke(Pe.content),(N?N(Pe):Pe.nodeType)===fa.element){const en=_(Pe);Gn(en)&&(qr(en),Ke(en))}us(J.afterSanitizeShadowDOM,be,null)},qr=function(be){const Pe=[{node:be,shadow:null}];for(;Pe.length>0;){const Qe=Pe.pop();if(Qe.shadow){Ke(Qe.shadow);continue}const Et=Qe.node,ln=(N?N(Et):Et.nodeType)===fa.element,$n=y(Et);if($n)for(let En=$n.length-1;En>=0;--En)Pe.push({node:$n[En],shadow:null});if(ln){const En=$?$(Et):null;if(typeof En=="string"&&_n(En)==="template"){const er=Et.content;Gn(er)&&Pe.push({node:er,shadow:null})}}if(ln){const En=_(Et);Gn(En)&&Pe.push({node:null,shadow:En},{node:En,shadow:null})}}};return n.sanitize=function(ft){let be=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Pe=null,Qe=null,Et=null,en=null;if(Js=!ft,Js&&(ft="<!-->"),typeof ft!="string"&&!Si(ft)&&(ft=O3(ft),typeof ft!="string"))throw bu("dirty is not a string, aborting");if(!n.isSupported)return ft;Br?(Je=Tr,xt=nt):$a(be),(J.uponSanitizeElement.length>0||J.uponSanitizeAttribute.length>0)&&(Je=Vs(Je)),J.uponSanitizeAttribute.length>0&&(xt=Vs(xt)),n.removed=[];const ln=yn&&typeof ft!="string"&&Si(ft);if(ln){const er=$?$(ft):ft.nodeName;if(typeof er=="string"){const Ln=_n(er);if(!Je[Ln]||vt[Ln])throw bu("root node is forbidden and cannot be sanitized in-place")}if(Bt(ft))throw bu("root node is clobbered and cannot be sanitized in-place");try{qr(ft)}catch(Ln){throw Mr(ft),Ln}}else if(Si(ft))Pe=Hi("<!---->"),Qe=Pe.ownerDocument.importNode(ft,!0),Qe.nodeType===fa.element&&Qe.nodeName==="BODY"||Qe.nodeName==="HTML"?Pe=Qe:Pe.appendChild(Qe),qr(Qe);else{if(!Tt&&!Kt&&!Rn&&ft.indexOf("<")===-1)return R&&nn?Y(ft):ft;if(Pe=Hi(ft),!Pe)return Tt?null:nn?O:""}Pe&&St&&kn(Pe.firstChild);const $n=ki(ln?ft:Pe);try{for(;Et=$n.nextNode();)Wr(Et),Es(Et),Gn(Et.content)&&Ke(Et.content)}catch(er){throw ln&&Mr(ft),er}if(ln)return Jp(n.removed,er=>{er.element&&ti(er.element)}),Kt&&gr(ft),ft;if(Tt){if(Kt&&gr(Pe),cn)for(en=ie.call(Pe.ownerDocument);Pe.firstChild;)en.appendChild(Pe.firstChild);else en=Pe;return(xt.shadowroot||xt.shadowrootmode)&&(en=Q.call(i,en,!0)),en}let En=Rn?Pe.outerHTML:Pe.innerHTML;return Rn&&Je["!doctype"]&&Pe.ownerDocument&&Pe.ownerDocument.doctype&&Pe.ownerDocument.doctype.name&&_s(K3,Pe.ownerDocument.doctype.name)&&(En="<!DOCTYPE "+Pe.ownerDocument.doctype.name+`>
|
|
2962
|
-
`+En),Kt&&(En=cs(En)),R&&nn?Y(En):En},n.setConfig=function(){let ft=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};$a(ft),Br=!0,Tr=Je,nt=xt},n.clearConfig=function(){Ct=null,Br=!1,Tr=null,nt=null,R=I,O=""},n.isValidAttribute=function(ft,be,Pe){Ct||$a({});const Qe=_n(ft),Et=_n(be);return Ps(Qe,Et,Pe)},n.addHook=function(ft,be){typeof be=="function"&&ns(J,ft)&&Eh(J[ft],be)},n.removeHook=function(ft,be){if(ns(J,ft)){if(be!==void 0){const Pe=$3(J[ft],be);return Pe===-1?void 0:A3(J[ft],Pe,1)[0]}return x1(J[ft])}},n.removeHooks=function(ft){ns(J,ft)&&(J[ft]=[])},n.removeAllHooks=function(){J=N1()},n}var d0=EC();const by=new wn.Renderer,tA=by.table.bind(by);by.table=e=>`<div class="prose-chat-table-wrap">${tA(e)}</div>`;function nA(e){return d0.sanitize(wn.parse(e,{async:!1,breaks:!0,renderer:by}))}async function NC(e,n=""){if(!e)return;const{absPath:r,line:i,col:o}=P$(e,n),l=await window.api.files.read(r);if(!l.ok&&l.error==="path outside home"){Le.error("That path is outside the project and can't be opened.");return}Tn.getState().openFile(r,{line:i,col:o}),window.dispatchEvent(new CustomEvent("sm:open-editor"))}async function rA(e,n=""){const r=e.target,i=r.closest("a");if(i){const d=i.getAttribute("href")||"";/^https?:\/\//i.test(d)&&(e.preventDefault(),window.api.shell.open({as:"external",url:d}).catch(()=>{}));return}const o=r.closest(`[${Zb}]`);if(!o)return;const l=o.getAttribute(Zb)??"";await NC(l,n)}function sA(e,n){var r;return e.text.trim().length>0?"text":n?"working":(r=e.toolUses)!=null&&r.length?"placeholder":"suppress"}function iA(e){switch(e){case"queued":return"queued";case"running":return"running";case"dispatched-to-prd":return"dispatched";case"done":return"completed";case"failed":return"failed"}}function oA(e,n,r){return[...e,...n?[n]:[],...r]}let rw=null;function aA(e){rw=e,window.dispatchEvent(new CustomEvent("sm:select-prd",{detail:e}))}function lA(){const e=rw;return rw=null,e}const T1=["#6f7d52","#b85c34","#8a7a60","#e4b85a","#5f6f86","#4f7d72","#8a5a6e"];function cA(e){let n=0;for(let r=0;r<e.length;r++)n=n*31+e.charCodeAt(r)>>>0;return n}function bc(e){return T1[cA(e)%T1.length]}function Wo(e){if(!e)return null;const n=e.replace(/\/+$/,"").split("/");return n[n.length-1]||e}function uA(e,n){const r=e?Wo(e)??"":n??"";return bc(r)}const dA={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"},hA={pending:"○",completed:"✓",needs_review:"!",failed:"✕"};function TC({status:e}){const n=hA[e];return s.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 ${dA[e]}`,role:"status","aria-label":`Status: ${e.replace("_"," ")}`,children:[e==="running"?s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-white animate-pulse","aria-hidden":"true"}):n&&s.jsx("span",{"aria-hidden":"true",children:n}),e.replace("_"," ")]})}function h0({cwd:e,name:n}){const r=n??(e?Wo(e)??e:"—"),i=uA(e,n);return s.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono text-xs text-fg-faint",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:i},"aria-hidden":"true"}),r]})}function gc({label:e,children:n}){return s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-bold tracking-[0.7px] uppercase text-fg-faint mb-2",children:e}),s.jsx("div",{className:"grid gap-1.5",children:n})]})}function ss({k:e,v:n,wrap:r}){return s.jsxs("div",{className:"flex gap-2 font-mono text-xs leading-relaxed",children:[s.jsx("span",{className:"text-fg-faint shrink-0 w-14",children:e}),s.jsx("span",{className:`text-fg ${r?"break-all":""}`,children:n})]})}function qv({dotClass:e,n,label:r}){return s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[13px] text-fg-dim",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${e}`,"aria-hidden":"true"}),s.jsx("strong",{className:"text-fg font-mono text-[13.5px]",children:n})," ",r]})}const fA={halt:"verifier halted",deps_unmet:"dependencies unmet",transcript_errors:"transcript had errors",verify_unavailable:"verify unavailable",uncommitted_changes:"uncommitted changes",no_verdict_sentinel:"no commit or verdict sentinel",pass_no_commit:"PASS sentinel but no commit landed"};function wy(e){return fA[e]??e}function Ph(e){const n=e.match(/^(\d+)-/);return n?n[1]:null}function $C({n:e}){return s.jsxs("span",{className:"font-mono text-[12px] font-semibold text-fg-faint shrink-0 tracking-tight select-none","aria-hidden":"true",children:["#",e]})}const pA={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"},completed:{bg:"bg-sage/20",text:"text-sage",border:!1,label:"completed"},failed:{bg:"bg-accent/15",text:"text-accent",border:!1,label:"failed"},needs_review:{bg:"bg-butter/25",text:"text-fg-dim",border:!1,label:"needs review"},dispatched:{bg:"bg-accent/15",text:"text-accent",border:!0,label:"dispatched to PRD"}};function $1(e){return e?e.status==="pending"?"queued":e.status:"ready"}function sw({status:e}){const n=pA[e];return s.jsx("span",{role:"status","aria-label":`Status: ${n.label}`,className:`text-[11.5px] font-semibold px-[9px] py-0.5 rounded-full ${n.bg} ${n.text}${n.border?" ring-1 ring-inset ring-line":""}`,children:n.label})}function AC({path:e,onDismiss:n}){const[r,i]=L.useState(!1);return r?null:s.jsxs("div",{className:"mb-2 inline-flex max-w-[160px] items-start gap-1.5 rounded-md border border-line bg-elev p-1.5",children:[s.jsx("img",{src:Qy(e),alt:"Pasted clipboard image",className:"max-h-[120px] max-w-[120px] rounded object-contain",draggable:!1,onError:()=>i(!0)}),s.jsx("button",{type:"button",onClick:n,title:"Dismiss preview",className:"shrink-0 rounded text-fg-faint hover:bg-hi hover:text-fg",children:"✕"})]})}const mA=/^\s*(?:[-*+]\s+.+|\d+\.\s+.+)/m;function gA(e){return mA.test(e)}function RC(e,n){window.api.clipboard.writeText(e).then(r=>n(!!(r!=null&&r.ok))).catch(()=>n(!1))}function xA({url:e}){const[n,r]=L.useState(!1),i=()=>{RC(e,o=>{o?(r(!0),setTimeout(()=>r(!1),1100)):Le.error("Copy failed")})};return s.jsxs("div",{className:"mt-1.5 flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[s.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"🔗"}),s.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-fg-dim",children:e}),s.jsx("button",{onClick:i,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:n?"Copied":"Copy"})]})}function yA({path:e,cwd:n}){const[r,i]=L.useState(!1),o=()=>{RC(e,d=>{d?(i(!0),setTimeout(()=>i(!1),1100)):Le.error("Copy failed")})},l=()=>{NC(e,n)};return s.jsxs("div",{className:"mt-1.5 flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[s.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"📄"}),s.jsx("button",{onClick:l,title:"Open in Editor",className:"min-w-0 flex-1 truncate text-left font-mono text-fg-dim hover:text-fg hover:underline",children:e}),s.jsx("button",{onClick:o,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:r?"Copied":"Copy"})]})}const MC={skill:"border-sage/60 bg-sage/10 text-sage",mcp:"border-accent/60 bg-accent/10 text-accent",tool:"border-line bg-elev text-fg-dim"},IC={skill:"🧩",mcp:"🔌",tool:"⚙"};function PC(e){const n=[];for(const r of e){const i=n[n.length-1];i&&i.kind===r.kind&&i.label===r.label?(i.count+=1,i.id=r.id):n.push({id:r.id,kind:r.kind,label:r.label,count:1})}return n}function DC(e){return e.count>1?`${e.label} ×${e.count}`:e.label}function iw({items:e,running:n=!1}){if(!(e!=null&&e.length))return null;const r=PC(e),i=r.length-1;return s.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-1",children:[r.map((o,l)=>{const d=n&&l===i;return s.jsxs("span",{className:`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-mono font-medium ${d?"border-accent/40 bg-accent/10 text-accent":MC[o.kind]}`,children:[IC[o.kind]," ",DC(o)]},o.id)}),s.jsxs("span",{className:"text-[10px] font-mono text-fg-dim",children:["· ",e.length," steps"]})]})}const OC="text-[#8a2f28]",vA="border-[#b8443c]/40 bg-[#b8443c]/10",em="text-[#7a5416]",bx="border-[#8e641a]/40 bg-[#8e641a]/10",bA=1180,A1={overview:"Overview",terminal:"Terminal",browser:"Browser","system-prompt":"System Prompt",settings:"Settings",permissions:"Permissions",skills:"Skills",plugins:"Plugins",mcp:"MCP Servers",hooks:"Hooks",subagents:"Subagents",memory:"Memory",projects:"Projects",history:"History",keybindings:"Keybindings",usage:"Usage",scheduler:"Scheduler",editor:"Editor",voice:"Voice",repoviz:"Repo Viz",search:"Search",remote:"Remote"};function wA(){const[e,n]=L.useState(()=>window.innerWidth);return L.useEffect(()=>{const r=()=>n(window.innerWidth);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}function _A({cwd:e,label:n,running:r,queuedPosition:i,stream:o,liveToolUses:l}){const d=PC(l),u=r&&!o?d.length-1:-1;return s.jsxs("div",{className:"w-[280px] shrink-0 overflow-y-auto border-l border-rule px-3 py-4",children:[s.jsxs("div",{className:"rounded-lg border border-line bg-elev px-3 py-2.5",children:[s.jsx("div",{className:"text-xs font-semibold text-fg",children:n}),s.jsx("div",{className:"mt-0.5 truncate font-mono text-[11px] text-fg-dim",title:e,children:e}),s.jsx("div",{className:"mt-2 flex items-center gap-1.5 text-[11px] text-fg-dim",children:r?i>0?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-butter"}),"queued · #",i]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-accent"}),"running"]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-line"}),"idle"]})})]}),s.jsx("div",{className:"mt-3 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"This turn"}),d.length===0?s.jsx("div",{className:"mt-1.5 text-[11px] text-fg-faint",children:"No tool activity yet."}):s.jsx("ul",{className:"mt-1.5 space-y-1",children:d.map((h,m)=>s.jsxs("li",{className:`flex items-center gap-1.5 rounded border px-1.5 py-1 text-[11px] font-mono ${m===u?"border-accent/40 bg-accent/10 text-accent":MC[h.kind]}`,children:[m===u?s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-accent"}):s.jsx("span",{"aria-hidden":!0,className:"shrink-0",children:IC[h.kind]}),s.jsx("span",{className:"truncate",children:DC(h)})]},h.id))})]})}function kA(e){aA(e),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"scheduler"}))}function SA({tickets:e}){return e.length===0?null:s.jsxs("div",{className:"w-[260px] shrink-0 overflow-y-auto border-l border-rule px-3 py-4","data-testid":"chat-queue-panel",children:[s.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"Prompt queue"}),s.jsx("ul",{className:"space-y-2",children:e.map(n=>{var r;return s.jsxs("li",{className:"rounded-lg border border-line bg-elev px-2.5 py-2","data-testid":"chat-queue-ticket",children:[s.jsx(sw,{status:iA(n.status)}),s.jsx("div",{className:"mt-1.5 truncate text-xs text-fg-dim",title:n.text,children:n.text}),n.status==="dispatched-to-prd"&&!!((r=n.prdSlugs)!=null&&r.length)&&s.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:n.prdSlugs.map(i=>s.jsxs("button",{onClick:()=>kA(i),title:`Open PRD "${i}" in Scheduler`,className:"rounded border border-line px-1.5 py-0.5 font-mono text-[10px] text-accent hover:bg-hi",children:["#",i]},i))})]},n.id)})})]})}const CA="needs interactive consent for an MCP server";function jA({turn:e,cwd:n,tabId:r,runActive:i=!1,consentActionDisabled:o=!1}){const l=L.useRef(null),d=e.role==="assistant"?sA(e,i):null;if(L.useEffect(()=>{e.role==="assistant"&&d==="text"&&l.current&&R$(l.current)},[e.role,d,e.text]),e.role==="user")return s.jsx("div",{className:"flex justify-end",children:s.jsx("div",{className:"max-w-[80%] rounded-tl-lg rounded-tr-lg rounded-bl-lg rounded-br-sm bg-accent/15 px-3 py-2 text-sm text-fg whitespace-pre-wrap",children:e.text})});if(e.role==="error")return s.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${vA} ${OC}`,children:e.text});if(e.role==="question")return s.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${bx} ${em}`,children:[s.jsx(iw,{items:e.toolUses}),s.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${em}`,children:[s.jsx("span",{"aria-hidden":!0,children:"❓"}),"Needs your answer"]}),s.jsx("ul",{className:"list-disc space-y-1 pl-5",children:(e.questions??[e.text]).map((x,g)=>s.jsx("li",{children:x},g))}),s.jsx("div",{className:`mt-2 border-t pt-2 text-[11px] opacity-70 ${bx}`,children:"Reply in the composer below to answer."})]});if(e.role==="notice"){const x=e.text.includes(CA),g=()=>{bt.getState().queueRawCommand(r,"/design consent"),bt.getState().wakeTab(r)};return s.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${bx} ${em}`,children:[s.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${em}`,children:[s.jsx("span",{"aria-hidden":!0,children:"ℹ️"}),"Needs your attention"]}),e.text,x&&s.jsx("div",{className:`mt-2 border-t pt-2 ${bx}`,children:s.jsx("button",{onClick:g,disabled:o,title:o?"Cancel or wait for the current run before opening a raw session":"Open a live interactive claude session with /design consent pre-typed",className:`rounded border px-2 py-1 text-xs font-medium hover:bg-white/10 disabled:opacity-40 disabled:hover:bg-transparent ${em} border-current`,children:"Grant consent →"})})]})}if(d==="suppress")return null;const u=L$(e.text),h=I$(e.text),m=gA(e.text);return s.jsxs("div",{className:"flex max-w-[90%] items-start gap-2",children:[s.jsx("div",{className:"flex h-[30px] w-[30px] shrink-0 items-center justify-center rounded-lg border border-line bg-elev text-xs font-semibold text-accent",children:"C"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx(iw,{items:e.toolUses,running:d==="working"}),d==="working"?s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"working…"]})}):d==="placeholder"?s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm italic text-fg-dim",children:"(no textual reply — see tool activity above)"}):s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:l,className:`prose-chat rounded-lg bg-elev px-3 py-2 text-sm leading-relaxed text-fg ${m?"prose-chat--plan":""}`,onClick:x=>{rA(x,n)},dangerouslySetInnerHTML:{__html:nA(e.text)}}),u.map(x=>s.jsx(xA,{url:x},x)),h.map(x=>s.jsx(yA,{path:x,cwd:n},x))]})]})]})}function EA({tabId:e,cwd:n}){const r=bt(oe=>oe.tabs.find(ie=>ie.id===e)),i=(r==null?void 0:r.sessionId)??e,o=gi(oe=>oe.chats[e]),l=gi(oe=>oe.send),d=gi(oe=>oe.hydrate),u=gi(oe=>oe.resetThread),h=gi(oe=>oe.pushNotice),[m,x]=L.useState(""),[g,v]=L.useState(!1),[S,E]=L.useState(null),j=L.useRef(null),y=L.useRef(null),_=wA()>bA,C=(o==null?void 0:o.turns)??[],N=(o==null?void 0:o.running)??!1,$=(o==null?void 0:o.stream)??"",R=(o==null?void 0:o.queuedPosition)??0,O=(o==null?void 0:o.liveToolUses)??[],I=oA((o==null?void 0:o.ticketHistory)??[],o==null?void 0:o.activeTicket,(o==null?void 0:o.queue)??[]);L.useEffect(()=>{d({tabId:e,cwd:n,sessionId:i})},[e]),L.useEffect(()=>{var oe;(oe=j.current)==null||oe.scrollTo({top:j.current.scrollHeight})},[C.length,$,N]);const z=()=>{if(N||!m.trim())return;const oe=F$(m.trim());if(oe.type==="nav"){x(""),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:oe.key}));const ie=`→ opened ${A1[oe.key]} — showing the live list`;h(e,ie),Le.info(`Opened ${A1[oe.key]} — showing the live list`);return}oe.type==="warn-unrouted"&&Le.info('Interactive prompts (consent/approval dialogs) need a real terminal — use "Open raw session" if this command asks you something and nothing appears.'),l({tabId:e,sessionId:i,cwd:n,prompt:m}),x(""),E(null)},U=oe=>{oe.key==="Enter"&&!oe.shiftKey&&(oe.preventDefault(),z())},W=oe=>{const ie=oe.currentTarget,X=ie.selectionStart??m.length,Q=ie.selectionEnd??X;oe.preventDefault(),(async()=>{try{const J=await U$({pasteImage:()=>window.api.clipboard.pasteImage(),readText:()=>window.api.clipboard.pasteText().then(le=>le.ok?le.text:"")},m,X,Q);x(J.value),J.toast&&Le.info(J.toast),J.imagePath&&E(J.imagePath),requestAnimationFrame(()=>{try{ie.setSelectionRange(J.caret,J.caret)}catch{}})}catch(J){Le.error(J instanceof Error?J.message:"Paste failed — clipboard unavailable")}})()};L.useEffect(()=>{if(!g)return;const oe=ie=>{var X;(X=y.current)!=null&&X.contains(ie.target)||v(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[g]);const Y=()=>{bt.getState().wakeTab(e)},V=oe=>{bt.getState().wakeTab(e,oe),v(!1)},[H,te]=L.useState(!1),ae=()=>{if(!N){if(!H){te(!0);return}bt.getState().newSession(e),u(e),te(!1)}};return s.jsxs("div",{className:"flex h-full w-full flex-col bg-bg",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-rule px-4 py-2",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"font-serif text-base text-fg",children:"Chat"}),s.jsx("div",{className:"text-xs text-fg-dim",children:"Chat · headless session — no process runs between commands"}),s.jsx(Zy,{active:"terminal"})]}),s.jsxs("div",{className:"flex items-stretch gap-2",children:[s.jsx("button",{onClick:ae,onBlur:()=>te(!1),disabled:N,title:"Start a brand-new session (clears this conversation's context; shared by both Chat and Raw)",className:`rounded border px-2 py-1 text-xs hover:bg-elev disabled:opacity-40 disabled:hover:bg-transparent ${H?"border-accent/60 text-accent":"border-line text-fg-dim hover:text-fg"}`,children:H?"Confirm new session?":"New session"}),s.jsxs("div",{ref:y,className:"relative flex items-stretch",children:[s.jsx("button",{onClick:Y,disabled:N,className:"rounded-l border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:N?"Cancel or wait for the current run before opening a raw session":"Drop into a live interactive claude session in this directory",children:"Open raw session ⌃"}),s.jsx("button",{onClick:()=>v(oe=>!oe),disabled:N,className:"rounded-r border border-l-0 border-line px-1.5 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:"Choose model for this raw session",children:"▾"}),g&&s.jsx("div",{className:"absolute right-0 top-full z-10 mt-1 w-32 rounded border border-line bg-hi shadow-lg",children:Yw.map(oe=>s.jsx("button",{onClick:()=>V(oe),className:"block w-full px-3 py-1.5 text-left text-xs text-fg-dim hover:bg-elev hover:text-fg",children:oe.charAt(0).toUpperCase()+oe.slice(1)},oe))})]})]})]}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{ref:j,className:"min-w-0 flex-1 space-y-3 overflow-y-auto px-4 py-4",children:[C.length===0&&!N&&s.jsx("div",{className:"flex h-full items-center justify-center text-sm text-fg-faint select-none",children:"Type a command to start a session. It runs, reports back, and asks if it needs you."}),C.map((oe,ie)=>s.jsx(jA,{turn:oe,cwd:n,tabId:e,runActive:N&&oe.role==="assistant"&&ie===C.length-1,consentActionDisabled:N},oe.id)),N&&s.jsxs("div",{className:"max-w-[90%]",children:[s.jsx(iw,{items:O,running:N&&!$}),s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:R>0?s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 rounded-full bg-butter"}),"queued · #",R," — waiting for a free run slot"]}):$?s.jsx("span",{className:"whitespace-pre-wrap",children:$}):s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"running…"]})})]})]}),s.jsx(SA,{tickets:I}),_&&s.jsx(_A,{cwd:n,label:(r==null?void 0:r.label)??n,running:N,queuedPosition:R,stream:$,liveToolUses:O})]}),s.jsxs("div",{className:"border-t border-rule p-3",children:[S&&s.jsx(AC,{path:S,onDismiss:()=>E(null)},S),s.jsxs("div",{className:"flex items-end gap-2",children:[s.jsx("textarea",{value:m,onChange:oe=>x(oe.target.value),onKeyDown:U,onPaste:W,disabled:N,rows:2,placeholder:N?"Running… cancel or wait":"Type a command (Enter to send, Shift+Enter for newline)",className:"flex-1 resize-none rounded-md border border-line bg-bg px-3 py-2 text-sm text-fg placeholder:text-fg-faint focus:border-accent/50 focus:outline-none disabled:opacity-50"}),N?s.jsx("button",{onClick:()=>window.api.chat.cancel(e),className:`rounded-md border px-3 py-2 text-sm hover:bg-[#b8443c]/10 ${OC} border-[#b8443c]/40`,children:"Cancel"}):s.jsx("button",{onClick:z,disabled:!m.trim(),className:"rounded-md bg-accent px-4 py-2 text-sm font-medium text-white hover:bg-accent/90 disabled:opacity-40",children:"Send"})]})]})]})}const ow="\x1B[38;5;240m",aw="\x1B[0m",NA=/\x1b(?:\[[0-9;?]*[a-zA-Z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g;function TA(e){return e.replace(NA,"")}function $A(e){var l;if(!e||typeof e!="object")return null;const n=e,r=n.type==="user"?"You":n.type==="assistant"?"Claude":null;if(!r)return null;const i=(l=n.message)==null?void 0:l.content;if(!Array.isArray(i))return null;const o=i.filter(d=>(d==null?void 0:d.type)==="text"&&typeof d.text=="string").map(d=>TA(d.text).trim()).filter(Boolean).join(`
|
|
2961
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function C3(e,n){return _3(e)||k3(e,n)||j3(e,n)||S3()}function j3(e,n){if(e){if(typeof e=="string")return m1(e,n);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?m1(e,n):void 0}}const CC=Object.entries,g1=Object.setPrototypeOf,E3=Object.isFrozen,N3=Object.getPrototypeOf,T3=Object.getOwnPropertyDescriptor;let ks=Object.freeze,Ss=Object.seal,Ih=Object.create,jC=typeof Reflect<"u"&&Reflect,tw=jC.apply,nw=jC.construct;ks||(ks=function(n){return n});Ss||(Ss=function(n){return n});tw||(tw=function(n,r){for(var i=arguments.length,o=new Array(i>2?i-2:0),l=2;l<i;l++)o[l-2]=arguments[l];return n.apply(r,o)});nw||(nw=function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;o<r;o++)i[o-1]=arguments[o];return new n(...i)});const Jp=Nr(Array.prototype.forEach),$3=Nr(Array.prototype.lastIndexOf),x1=Nr(Array.prototype.pop),Eh=Nr(Array.prototype.push),A3=Nr(Array.prototype.splice),pc=Array.isArray,bm=Nr(String.prototype.toLowerCase),Bv=Nr(String.prototype.toString),y1=Nr(String.prototype.match),Qp=Nr(String.prototype.replace),v1=Nr(String.prototype.indexOf),R3=Nr(String.prototype.trim),M3=Nr(Number.prototype.toString),I3=Nr(Boolean.prototype.toString),b1=typeof BigInt>"u"?null:Nr(BigInt.prototype.toString),w1=typeof Symbol>"u"?null:Nr(Symbol.prototype.toString),ns=Nr(Object.prototype.hasOwnProperty),Zp=Nr(Object.prototype.toString),_s=Nr(RegExp.prototype.test),bu=P3(TypeError);function Nr(e){return function(n){n instanceof RegExp&&(n.lastIndex=0);for(var r=arguments.length,i=new Array(r>1?r-1:0),o=1;o<r;o++)i[o-1]=arguments[o];return tw(e,n,i)}}function P3(e){return function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return nw(e,r)}}function Sn(e,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:bm;if(g1&&g1(e,null),!pc(n))return e;let i=n.length;for(;i--;){let o=n[i];if(typeof o=="string"){const l=r(o);l!==o&&(E3(n)||(n[i]=l),o=l)}e[o]=!0}return e}function D3(e){for(let n=0;n<e.length;n++)ns(e,n)||(e[n]=null);return e}function Vs(e){const n=Ih(null);for(const i of CC(e)){var r=C3(i,2);const o=r[0],l=r[1];ns(e,o)&&(pc(l)?n[o]=D3(l):l&&typeof l=="object"&&l.constructor===Object?n[o]=Vs(l):n[o]=l)}return n}function O3(e){switch(typeof e){case"string":return e;case"number":return M3(e);case"boolean":return I3(e);case"bigint":return b1?b1(e):"0";case"symbol":return w1?w1(e):"Symbol()";case"undefined":return Zp(e);case"function":case"object":{if(e===null)return Zp(e);const n=e,r=pa(n,"toString");if(typeof r=="function"){const i=r(n);return typeof i=="string"?i:Zp(i)}return Zp(e)}default:return Zp(e)}}function pa(e,n){for(;e!==null;){const i=T3(e,n);if(i){if(i.get)return Nr(i.get);if(typeof i.value=="function")return Nr(i.value)}e=N3(e)}function r(){return null}return r}function L3(e){try{return _s(e,""),!0}catch{return!1}}const _1=ks(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Fv=ks(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Uv=ks(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),z3=ks(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Hv=ks(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),B3=ks(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),k1=ks(["#text"]),S1=ks(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","command","commandfor","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns"]),Wv=ks(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","mask-type","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),C1=ks(["accent","accentunder","align","bevelled","close","columnalign","columnlines","columnspacing","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lquote","lspace","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),vx=ks(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),F3=Ss(/{{[\w\W]*|^[\w\W]*}}/g),U3=Ss(/<%[\w\W]*|^[\w\W]*%>/g),H3=Ss(/\${[\w\W]*/g),W3=Ss(/^data-[\-\w.\u00B7-\uFFFF]+$/),q3=Ss(/^aria-[\-\w]+$/),j1=Ss(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),V3=Ss(/^(?:\w+script|data):/i),G3=Ss(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),K3=Ss(/^html$/i),X3=Ss(/^[a-z][.\w]*(-[.\w]+)+$/i),E1=Ss(/<[/\w!]/g),Y3=Ss(/<[/\w]/g),J3=Ss(/<\/no(script|embed|frames)/i),Q3=Ss(/\/>/i),fa={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Z3=function(){return typeof window>"u"?null:window},eA=function(n,r){if(typeof n!="object"||typeof n.createPolicy!="function")return null;let i=null;const o="data-tt-policy-suffix";r&&r.hasAttribute(o)&&(i=r.getAttribute(o));const l="dompurify"+(i?"#"+i:"");try{return n.createPolicy(l,{createHTML(d){return d},createScriptURL(d){return d}})}catch{return console.warn("TrustedTypes policy "+l+" could not be created."),null}},N1=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Zl=function(n,r,i,o){return ns(n,r)&&pc(n[r])?Sn(o.base?Vs(o.base):{},n[r],o.transform):i};function EC(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:Z3();const n=ft=>EC(ft);if(n.version="3.4.11",n.removed=[],!e||!e.document||e.document.nodeType!==fa.document||!e.Element)return n.isSupported=!1,n;let r=e.document;const i=r,o=i.currentScript;e.DocumentFragment;const l=e.HTMLTemplateElement,d=e.Node,u=e.Element,h=e.NodeFilter,m=e.NamedNodeMap;m===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const x=e.DOMParser,g=e.trustedTypes,v=u.prototype,S=pa(v,"cloneNode"),E=pa(v,"remove"),j=pa(v,"nextSibling"),y=pa(v,"childNodes"),b=pa(v,"parentNode"),_=pa(v,"shadowRoot"),C=pa(v,"attributes"),N=d&&d.prototype?pa(d.prototype,"nodeType"):null,$=d&&d.prototype?pa(d.prototype,"nodeName"):null;if(typeof l=="function"){const ft=r.createElement("template");ft.content&&ft.content.ownerDocument&&(r=ft.content.ownerDocument)}let R,O="",I,z=!1,U=0;const W=function(){if(U>0)throw bu('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},Y=function(be){W(),U++;try{return R.createHTML(be)}finally{U--}},V=function(be){W(),U++;try{return R.createScriptURL(be)}finally{U--}},H=function(){return z||(I=eA(g,o),z=!0),I},te=r,ae=te.implementation,oe=te.createNodeIterator,ie=te.createDocumentFragment,X=te.getElementsByTagName,Q=i.importNode;let J=N1();n.isSupported=typeof CC=="function"&&typeof b=="function"&&ae&&ae.createHTMLDocument!==void 0;const le=F3,ce=U3,pe=H3,Ae=W3,Se=q3,ye=V3,ne=G3,we=X3;let Ne=j1,Je=null;const lt=Sn({},[..._1,...Fv,...Uv,...Hv,...k1]);let xt=null;const Rt=Sn({},[...S1,...Wv,...C1,...vx]);let He=Object.seal(Ih(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),vt=null,st=null;const an=Object.seal(Ih(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let sn=!0,Ye=!0,yt=!1,kt=!0,Kt=!1,On=!0,Rn=!1,Br=!1,Tr=null,nt=null,St=!1,Tt=!1,cn=!1,nn=!1,$r=!0,Ta=!1;const Vo="user-content-";let vi=!0,yn=!1,Fr={},Zn=null;const bi=Sn({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Ms=null;const as=Sn({},["audio","video","img","source","image","track"]);let Fi=null;const wi=Sn({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),_i="http://www.w3.org/1998/Math/MathML",Is="http://www.w3.org/2000/svg",Ar="http://www.w3.org/1999/xhtml";let Ur=Ar,Qs=!1,Rr=null;const ls=Sn({},[_i,Is,Ar],Bv),js=ks(["mi","mo","mn","ms","mtext"]);let ho=Sn({},js);const Zs=ks(["annotation-xml"]);let ei=Sn({},Zs);const ti=Sn({},["title","style","font","a","script"]);let zt=null;const Hr=["application/xhtml+xml","text/html"],Hn="text/html";let _n=null,Ct=null;const Ui=r.createElement("form"),fo=function(be){return be instanceof RegExp||be instanceof Function},$a=function(){let be=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(Ct&&Ct===be)return;(!be||typeof be!="object")&&(be={}),be=Vs(be),zt=Hr.indexOf(be.PARSER_MEDIA_TYPE)===-1?Hn:be.PARSER_MEDIA_TYPE,_n=zt==="application/xhtml+xml"?Bv:bm,Je=Zl(be,"ALLOWED_TAGS",lt,{transform:_n}),xt=Zl(be,"ALLOWED_ATTR",Rt,{transform:_n}),Rr=Zl(be,"ALLOWED_NAMESPACES",ls,{transform:Bv}),Fi=Zl(be,"ADD_URI_SAFE_ATTR",wi,{transform:_n,base:wi}),Ms=Zl(be,"ADD_DATA_URI_TAGS",as,{transform:_n,base:as}),Zn=Zl(be,"FORBID_CONTENTS",bi,{transform:_n}),vt=Zl(be,"FORBID_TAGS",Vs({}),{transform:_n}),st=Zl(be,"FORBID_ATTR",Vs({}),{transform:_n}),Fr=ns(be,"USE_PROFILES")?be.USE_PROFILES&&typeof be.USE_PROFILES=="object"?Vs(be.USE_PROFILES):be.USE_PROFILES:!1,sn=be.ALLOW_ARIA_ATTR!==!1,Ye=be.ALLOW_DATA_ATTR!==!1,yt=be.ALLOW_UNKNOWN_PROTOCOLS||!1,kt=be.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Kt=be.SAFE_FOR_TEMPLATES||!1,On=be.SAFE_FOR_XML!==!1,Rn=be.WHOLE_DOCUMENT||!1,Tt=be.RETURN_DOM||!1,cn=be.RETURN_DOM_FRAGMENT||!1,nn=be.RETURN_TRUSTED_TYPE||!1,St=be.FORCE_BODY||!1,$r=be.SANITIZE_DOM!==!1,Ta=be.SANITIZE_NAMED_PROPS||!1,vi=be.KEEP_CONTENT!==!1,yn=be.IN_PLACE||!1,Ne=L3(be.ALLOWED_URI_REGEXP)?be.ALLOWED_URI_REGEXP:j1,Ur=typeof be.NAMESPACE=="string"?be.NAMESPACE:Ar,ho=ns(be,"MATHML_TEXT_INTEGRATION_POINTS")&&be.MATHML_TEXT_INTEGRATION_POINTS&&typeof be.MATHML_TEXT_INTEGRATION_POINTS=="object"?Vs(be.MATHML_TEXT_INTEGRATION_POINTS):Sn({},js),ei=ns(be,"HTML_INTEGRATION_POINTS")&&be.HTML_INTEGRATION_POINTS&&typeof be.HTML_INTEGRATION_POINTS=="object"?Vs(be.HTML_INTEGRATION_POINTS):Sn({},Zs);const Pe=ns(be,"CUSTOM_ELEMENT_HANDLING")&&be.CUSTOM_ELEMENT_HANDLING&&typeof be.CUSTOM_ELEMENT_HANDLING=="object"?Vs(be.CUSTOM_ELEMENT_HANDLING):Ih(null);if(He=Ih(null),ns(Pe,"tagNameCheck")&&fo(Pe.tagNameCheck)&&(He.tagNameCheck=Pe.tagNameCheck),ns(Pe,"attributeNameCheck")&&fo(Pe.attributeNameCheck)&&(He.attributeNameCheck=Pe.attributeNameCheck),ns(Pe,"allowCustomizedBuiltInElements")&&typeof Pe.allowCustomizedBuiltInElements=="boolean"&&(He.allowCustomizedBuiltInElements=Pe.allowCustomizedBuiltInElements),Ss(He),Kt&&(Ye=!1),cn&&(Tt=!0),Fr&&(Je=Sn({},k1),xt=Ih(null),Fr.html===!0&&(Sn(Je,_1),Sn(xt,S1)),Fr.svg===!0&&(Sn(Je,Fv),Sn(xt,Wv),Sn(xt,vx)),Fr.svgFilters===!0&&(Sn(Je,Uv),Sn(xt,Wv),Sn(xt,vx)),Fr.mathMl===!0&&(Sn(Je,Hv),Sn(xt,C1),Sn(xt,vx))),an.tagCheck=null,an.attributeCheck=null,ns(be,"ADD_TAGS")&&(typeof be.ADD_TAGS=="function"?an.tagCheck=be.ADD_TAGS:pc(be.ADD_TAGS)&&(Je===lt&&(Je=Vs(Je)),Sn(Je,be.ADD_TAGS,_n))),ns(be,"ADD_ATTR")&&(typeof be.ADD_ATTR=="function"?an.attributeCheck=be.ADD_ATTR:pc(be.ADD_ATTR)&&(xt===Rt&&(xt=Vs(xt)),Sn(xt,be.ADD_ATTR,_n))),ns(be,"ADD_URI_SAFE_ATTR")&&pc(be.ADD_URI_SAFE_ATTR)&&Sn(Fi,be.ADD_URI_SAFE_ATTR,_n),ns(be,"FORBID_CONTENTS")&&pc(be.FORBID_CONTENTS)&&(Zn===bi&&(Zn=Vs(Zn)),Sn(Zn,be.FORBID_CONTENTS,_n)),ns(be,"ADD_FORBID_CONTENTS")&&pc(be.ADD_FORBID_CONTENTS)&&(Zn===bi&&(Zn=Vs(Zn)),Sn(Zn,be.ADD_FORBID_CONTENTS,_n)),vi&&(Je["#text"]=!0),Rn&&Sn(Je,["html","head","body"]),Je.table&&(Sn(Je,["tbody"]),delete vt.tbody),be.TRUSTED_TYPES_POLICY){if(typeof be.TRUSTED_TYPES_POLICY.createHTML!="function")throw bu('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof be.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw bu('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Qe=R;R=be.TRUSTED_TYPES_POLICY;try{O=Y("")}catch(Et){throw R=Qe,Et}}else be.TRUSTED_TYPES_POLICY===null?(R=void 0,O=""):(R===void 0&&(R=H()),R&&typeof O=="string"&&(O=Y("")));ks&&ks(be),Ct=be},po=Sn({},[...Fv,...Uv,...z3]),mo=Sn({},[...Hv,...B3]),Go=function(be,Pe,Qe){return Pe.namespaceURI===Ar?be==="svg":Pe.namespaceURI===_i?be==="svg"&&(Qe==="annotation-xml"||ho[Qe]):!!po[be]},Sr=function(be,Pe,Qe){return Pe.namespaceURI===Ar?be==="math":Pe.namespaceURI===Is?be==="math"&&ei[Qe]:!!mo[be]},Aa=function(be,Pe,Qe){return Pe.namespaceURI===Is&&!ei[Qe]||Pe.namespaceURI===_i&&!ho[Qe]?!1:!mo[be]&&(ti[be]||!po[be])},Ra=function(be){let Pe=b(be);(!Pe||!Pe.tagName)&&(Pe={namespaceURI:Ur,tagName:"template"});const Qe=bm(be.tagName),Et=bm(Pe.tagName);return Rr[be.namespaceURI]?be.namespaceURI===Is?Go(Qe,Pe,Et):be.namespaceURI===_i?Sr(Qe,Pe,Et):be.namespaceURI===Ar?Aa(Qe,Pe,Et):!!(zt==="application/xhtml+xml"&&Rr[be.namespaceURI]):!1},kn=function(be){Eh(n.removed,{element:be});try{b(be).removeChild(be)}catch{if(E(be),!b(be))throw bu("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},Mr=function(be){const Pe=y(be);if(Pe){const Et=[];Jp(Pe,en=>{Eh(Et,en)}),Jp(Et,en=>{try{E(en)}catch{}})}const Qe=C(be);if(Qe)for(let Et=Qe.length-1;Et>=0;--Et){const en=Qe[Et],ln=en&&en.name;if(typeof ln=="string")try{be.removeAttribute(ln)}catch{}}},Vn=function(be,Pe){try{Eh(n.removed,{attribute:Pe.getAttributeNode(be),from:Pe})}catch{Eh(n.removed,{attribute:null,from:Pe})}if(Pe.removeAttribute(be),be==="is")if(Tt||cn)try{kn(Pe)}catch{}else try{Pe.setAttribute(be,"")}catch{}},Ir=function(be){const Pe=C(be);if(Pe)for(let Qe=Pe.length-1;Qe>=0;--Qe){const Et=Pe[Qe],en=Et&&Et.name;if(!(typeof en!="string"||xt[_n(en)]))try{be.removeAttribute(en)}catch{}}},ni=function(be){const Pe=[be];for(;Pe.length>0;){const Qe=Pe.pop();(N?N(Qe):Qe.nodeType)===fa.element&&Ir(Qe);const en=y(Qe);if(en)for(let ln=en.length-1;ln>=0;--ln)Pe.push(en[ln])}},Hi=function(be){let Pe=null,Qe=null;if(St)be="<remove></remove>"+be;else{const ln=y1(be,/^[\r\n\t ]+/);Qe=ln&&ln[0]}zt==="application/xhtml+xml"&&Ur===Ar&&(be='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+be+"</body></html>");const Et=R?Y(be):be;if(Ur===Ar)try{Pe=new x().parseFromString(Et,zt)}catch{}if(!Pe||!Pe.documentElement){Pe=ae.createDocument(Ur,"template",null);try{Pe.documentElement.innerHTML=Qs?O:Et}catch{}}const en=Pe.body||Pe.documentElement;return be&&Qe&&en.insertBefore(r.createTextNode(Qe),en.childNodes[0]||null),Ur===Ar?X.call(Pe,Rn?"html":"body")[0]:Rn?Pe.documentElement:en},ki=function(be){return oe.call(be.ownerDocument||be,be,h.SHOW_ELEMENT|h.SHOW_COMMENT|h.SHOW_TEXT|h.SHOW_PROCESSING_INSTRUCTION|h.SHOW_CDATA_SECTION,null)},cs=function(be){return be=Qp(be,le," "),be=Qp(be,ce," "),be=Qp(be,pe," "),be},gr=function(be){var Pe;be.normalize();const Qe=oe.call(be.ownerDocument||be,be,h.SHOW_TEXT|h.SHOW_COMMENT|h.SHOW_CDATA_SECTION|h.SHOW_PROCESSING_INSTRUCTION,null);let Et=Qe.nextNode();for(;Et;)Et.data=cs(Et.data),Et=Qe.nextNode();const en=(Pe=be.querySelectorAll)===null||Pe===void 0?void 0:Pe.call(be,"template");en&&Jp(en,ln=>{Gn(ln.content)&&gr(ln.content)})},Bt=function(be){const Pe=$?$(be):null;return typeof Pe!="string"||_n(Pe)!=="form"?!1:typeof be.nodeName!="string"||typeof be.textContent!="string"||typeof be.removeChild!="function"||be.attributes!==C(be)||typeof be.removeAttribute!="function"||typeof be.setAttribute!="function"||typeof be.namespaceURI!="string"||typeof be.insertBefore!="function"||typeof be.hasChildNodes!="function"||be.nodeType!==N(be)||be.childNodes!==y(be)},Gn=function(be){if(!N||typeof be!="object"||be===null)return!1;try{return N(be)===fa.documentFragment}catch{return!1}},Si=function(be){if(!N||typeof be!="object"||be===null)return!1;try{return typeof N(be)=="number"}catch{return!1}};function us(ft,be,Pe){ft.length!==0&&Jp(ft,Qe=>{Qe.call(n,be,Pe,Ct)})}const Ko=function(be,Pe){return!!(On&&be.hasChildNodes()&&!Si(be.firstElementChild)&&_s(E1,be.textContent)&&_s(E1,be.innerHTML)||On&&be.namespaceURI===Ar&&Pe==="style"&&Si(be.firstElementChild)||be.nodeType===fa.processingInstruction||On&&be.nodeType===fa.comment&&_s(Y3,be.data))},Ci=function(be,Pe){if(!vt[Pe]&&on(Pe)&&(He.tagNameCheck instanceof RegExp&&_s(He.tagNameCheck,Pe)||He.tagNameCheck instanceof Function&&He.tagNameCheck(Pe)))return!1;if(vi&&!Zn[Pe]){const Qe=b(be),Et=y(be);if(Et&&Qe){const en=Et.length;for(let ln=en-1;ln>=0;--ln){const $n=yn?Et[ln]:S(Et[ln],!0);Qe.insertBefore($n,j(be))}}}return kn(be),!0},Wr=function(be){if(us(J.beforeSanitizeElements,be,null),Bt(be))return kn(be),!0;const Pe=_n($?$(be):be.nodeName);if(us(J.uponSanitizeElement,be,{tagName:Pe,allowedTags:Je}),Ko(be,Pe))return kn(be),!0;if(vt[Pe]||!(an.tagCheck instanceof Function&&an.tagCheck(Pe))&&!Je[Pe])return Ci(be,Pe);if((N?N(be):be.nodeType)===fa.element&&!Ra(be)||(Pe==="noscript"||Pe==="noembed"||Pe==="noframes")&&_s(J3,be.innerHTML))return kn(be),!0;if(Kt&&be.nodeType===fa.text){const Et=cs(be.textContent);be.textContent!==Et&&(Eh(n.removed,{element:be.cloneNode()}),be.textContent=Et)}return us(J.afterSanitizeElements,be,null),!1},Ps=function(be,Pe,Qe){if(st[Pe]||$r&&(Pe==="id"||Pe==="name")&&(Qe in r||Qe in Ui))return!1;const Et=xt[Pe]||an.attributeCheck instanceof Function&&an.attributeCheck(Pe,be);if(!(Ye&&_s(Ae,Pe))){if(!(sn&&_s(Se,Pe))){if(Et){if(!Fi[Pe]){if(!_s(Ne,Qp(Qe,ne,""))){if(!((Pe==="src"||Pe==="xlink:href"||Pe==="href")&&be!=="script"&&v1(Qe,"data:")===0&&Ms[be])){if(!(yt&&!_s(ye,Qp(Qe,ne,"")))){if(Qe)return!1}}}}}else if(!(on(be)&&(He.tagNameCheck instanceof RegExp&&_s(He.tagNameCheck,be)||He.tagNameCheck instanceof Function&&He.tagNameCheck(be))&&(He.attributeNameCheck instanceof RegExp&&_s(He.attributeNameCheck,Pe)||He.attributeNameCheck instanceof Function&&He.attributeNameCheck(Pe,be))||Pe==="is"&&He.allowCustomizedBuiltInElements&&(He.tagNameCheck instanceof RegExp&&_s(He.tagNameCheck,Qe)||He.tagNameCheck instanceof Function&&He.tagNameCheck(Qe))))return!1}}return!0},ji=Sn({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),on=function(be){return!ji[bm(be)]&&_s(we,be)},ds=function(be,Pe,Qe,Et){if(R&&typeof g=="object"&&typeof g.getAttributeType=="function"&&!Qe)switch(g.getAttributeType(be,Pe)){case"TrustedHTML":return Y(Et);case"TrustedScriptURL":return V(Et)}return Et},Wi=function(be,Pe,Qe,Et){try{Qe?be.setAttributeNS(Qe,Pe,Et):be.setAttribute(Pe,Et),Bt(be)?kn(be):x1(n.removed)}catch{Vn(Pe,be)}},Es=function(be){us(J.beforeSanitizeAttributes,be,null);const Pe=be.attributes;if(!Pe||Bt(be))return;const Qe={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:xt,forceKeepAttr:void 0};let Et=Pe.length;const en=_n(be.nodeName);for(;Et--;){const ln=Pe[Et],$n=ln.name,En=ln.namespaceURI,er=ln.value,Ln=_n($n),sr=er;let Nn=$n==="value"?sr:R3(sr);if(Qe.attrName=Ln,Qe.attrValue=Nn,Qe.keepAttr=!0,Qe.forceKeepAttr=void 0,us(J.uponSanitizeAttribute,be,Qe),Nn=Qe.attrValue,Ta&&(Ln==="id"||Ln==="name")&&v1(Nn,Vo)!==0&&(Vn($n,be),Nn=Vo+Nn),On&&_s(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,Nn)){Vn($n,be);continue}if(Ln==="attributename"&&y1(Nn,"href")){Vn($n,be);continue}if(!Qe.forceKeepAttr){if(!Qe.keepAttr){Vn($n,be);continue}if(!kt&&_s(Q3,Nn)){Vn($n,be);continue}if(Kt&&(Nn=cs(Nn)),!Ps(en,Ln,Nn)){Vn($n,be);continue}Nn=ds(en,Ln,En,Nn),Nn!==sr&&Wi(be,$n,En,Nn)}}us(J.afterSanitizeAttributes,be,null)},Ke=function(be){let Pe=null;const Qe=ki(be);for(us(J.beforeSanitizeShadowDOM,be,null);Pe=Qe.nextNode();)if(us(J.uponSanitizeShadowNode,Pe,null),Wr(Pe),Es(Pe),Gn(Pe.content)&&Ke(Pe.content),(N?N(Pe):Pe.nodeType)===fa.element){const en=_(Pe);Gn(en)&&(qr(en),Ke(en))}us(J.afterSanitizeShadowDOM,be,null)},qr=function(be){const Pe=[{node:be,shadow:null}];for(;Pe.length>0;){const Qe=Pe.pop();if(Qe.shadow){Ke(Qe.shadow);continue}const Et=Qe.node,ln=(N?N(Et):Et.nodeType)===fa.element,$n=y(Et);if($n)for(let En=$n.length-1;En>=0;--En)Pe.push({node:$n[En],shadow:null});if(ln){const En=$?$(Et):null;if(typeof En=="string"&&_n(En)==="template"){const er=Et.content;Gn(er)&&Pe.push({node:er,shadow:null})}}if(ln){const En=_(Et);Gn(En)&&Pe.push({node:null,shadow:En},{node:En,shadow:null})}}};return n.sanitize=function(ft){let be=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},Pe=null,Qe=null,Et=null,en=null;if(Qs=!ft,Qs&&(ft="<!-->"),typeof ft!="string"&&!Si(ft)&&(ft=O3(ft),typeof ft!="string"))throw bu("dirty is not a string, aborting");if(!n.isSupported)return ft;Br?(Je=Tr,xt=nt):$a(be),(J.uponSanitizeElement.length>0||J.uponSanitizeAttribute.length>0)&&(Je=Vs(Je)),J.uponSanitizeAttribute.length>0&&(xt=Vs(xt)),n.removed=[];const ln=yn&&typeof ft!="string"&&Si(ft);if(ln){const er=$?$(ft):ft.nodeName;if(typeof er=="string"){const Ln=_n(er);if(!Je[Ln]||vt[Ln])throw bu("root node is forbidden and cannot be sanitized in-place")}if(Bt(ft))throw bu("root node is clobbered and cannot be sanitized in-place");try{qr(ft)}catch(Ln){throw Mr(ft),Ln}}else if(Si(ft))Pe=Hi("<!---->"),Qe=Pe.ownerDocument.importNode(ft,!0),Qe.nodeType===fa.element&&Qe.nodeName==="BODY"||Qe.nodeName==="HTML"?Pe=Qe:Pe.appendChild(Qe),qr(Qe);else{if(!Tt&&!Kt&&!Rn&&ft.indexOf("<")===-1)return R&&nn?Y(ft):ft;if(Pe=Hi(ft),!Pe)return Tt?null:nn?O:""}Pe&&St&&kn(Pe.firstChild);const $n=ki(ln?ft:Pe);try{for(;Et=$n.nextNode();)Wr(Et),Es(Et),Gn(Et.content)&&Ke(Et.content)}catch(er){throw ln&&Mr(ft),er}if(ln)return Jp(n.removed,er=>{er.element&&ni(er.element)}),Kt&&gr(ft),ft;if(Tt){if(Kt&&gr(Pe),cn)for(en=ie.call(Pe.ownerDocument);Pe.firstChild;)en.appendChild(Pe.firstChild);else en=Pe;return(xt.shadowroot||xt.shadowrootmode)&&(en=Q.call(i,en,!0)),en}let En=Rn?Pe.outerHTML:Pe.innerHTML;return Rn&&Je["!doctype"]&&Pe.ownerDocument&&Pe.ownerDocument.doctype&&Pe.ownerDocument.doctype.name&&_s(K3,Pe.ownerDocument.doctype.name)&&(En="<!DOCTYPE "+Pe.ownerDocument.doctype.name+`>
|
|
2962
|
+
`+En),Kt&&(En=cs(En)),R&&nn?Y(En):En},n.setConfig=function(){let ft=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};$a(ft),Br=!0,Tr=Je,nt=xt},n.clearConfig=function(){Ct=null,Br=!1,Tr=null,nt=null,R=I,O=""},n.isValidAttribute=function(ft,be,Pe){Ct||$a({});const Qe=_n(ft),Et=_n(be);return Ps(Qe,Et,Pe)},n.addHook=function(ft,be){typeof be=="function"&&ns(J,ft)&&Eh(J[ft],be)},n.removeHook=function(ft,be){if(ns(J,ft)){if(be!==void 0){const Pe=$3(J[ft],be);return Pe===-1?void 0:A3(J[ft],Pe,1)[0]}return x1(J[ft])}},n.removeHooks=function(ft){ns(J,ft)&&(J[ft]=[])},n.removeAllHooks=function(){J=N1()},n}var d0=EC();const by=new wn.Renderer,tA=by.table.bind(by);by.table=e=>`<div class="prose-chat-table-wrap">${tA(e)}</div>`;function nA(e){return d0.sanitize(wn.parse(e,{async:!1,breaks:!0,renderer:by}))}async function NC(e,n=""){if(!e)return;const{absPath:r,line:i,col:o}=P$(e,n),l=await window.api.files.read(r);if(!l.ok&&l.error==="path outside home"){Le.error("That path is outside the project and can't be opened.");return}Tn.getState().openFile(r,{line:i,col:o}),window.dispatchEvent(new CustomEvent("sm:open-editor"))}async function rA(e,n=""){const r=e.target,i=r.closest("a");if(i){const d=i.getAttribute("href")||"";/^https?:\/\//i.test(d)&&(e.preventDefault(),window.api.shell.open({as:"external",url:d}).catch(()=>{}));return}const o=r.closest(`[${Zb}]`);if(!o)return;const l=o.getAttribute(Zb)??"";await NC(l,n)}function sA(e,n){var r;return e.text.trim().length>0?"text":n?"working":(r=e.toolUses)!=null&&r.length?"placeholder":"suppress"}function iA(e){switch(e){case"queued":return"queued";case"running":return"running";case"dispatched-to-prd":return"dispatched";case"done":return"completed";case"failed":return"failed"}}function oA(e,n,r){return[...e,...n?[n]:[],...r]}let rw=null;function aA(e){rw=e,window.dispatchEvent(new CustomEvent("sm:select-prd",{detail:e}))}function lA(){const e=rw;return rw=null,e}const T1=["#6f7d52","#b85c34","#8a7a60","#e4b85a","#5f6f86","#4f7d72","#8a5a6e"];function cA(e){let n=0;for(let r=0;r<e.length;r++)n=n*31+e.charCodeAt(r)>>>0;return n}function bc(e){return T1[cA(e)%T1.length]}function Wo(e){if(!e)return null;const n=e.replace(/\/+$/,"").split("/");return n[n.length-1]||e}function uA(e,n){const r=e?Wo(e)??"":n??"";return bc(r)}const dA={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"},hA={pending:"○",completed:"✓",needs_review:"!",failed:"✕"};function TC({status:e}){const n=hA[e];return s.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 ${dA[e]}`,role:"status","aria-label":`Status: ${e.replace("_"," ")}`,children:[e==="running"?s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-white animate-pulse","aria-hidden":"true"}):n&&s.jsx("span",{"aria-hidden":"true",children:n}),e.replace("_"," ")]})}function h0({cwd:e,name:n}){const r=n??(e?Wo(e)??e:"—"),i=uA(e,n);return s.jsxs("span",{className:"inline-flex items-center gap-1.5 font-mono text-xs text-fg-faint",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:i},"aria-hidden":"true"}),r]})}function gc({label:e,children:n}){return s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-bold tracking-[0.7px] uppercase text-fg-faint mb-2",children:e}),s.jsx("div",{className:"grid gap-1.5",children:n})]})}function ss({k:e,v:n,wrap:r}){return s.jsxs("div",{className:"flex gap-2 font-mono text-xs leading-relaxed",children:[s.jsx("span",{className:"text-fg-faint shrink-0 w-14",children:e}),s.jsx("span",{className:`text-fg ${r?"break-all":""}`,children:n})]})}function qv({dotClass:e,n,label:r}){return s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[13px] text-fg-dim",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${e}`,"aria-hidden":"true"}),s.jsx("strong",{className:"text-fg font-mono text-[13.5px]",children:n})," ",r]})}const fA={halt:"verifier halted",deps_unmet:"dependencies unmet",transcript_errors:"transcript had errors",verify_unavailable:"verify unavailable",uncommitted_changes:"uncommitted changes",no_verdict_sentinel:"no commit or verdict sentinel",pass_no_commit:"PASS sentinel but no commit landed"};function wy(e){return fA[e]??e}function Ph(e){const n=e.match(/^(\d+)-/);return n?n[1]:null}function $C({n:e}){return s.jsxs("span",{className:"font-mono text-[12px] font-semibold text-fg-faint shrink-0 tracking-tight select-none","aria-hidden":"true",children:["#",e]})}const pA={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"},completed:{bg:"bg-sage/20",text:"text-sage",border:!1,label:"completed"},failed:{bg:"bg-accent/15",text:"text-accent",border:!1,label:"failed"},needs_review:{bg:"bg-butter/25",text:"text-fg-dim",border:!1,label:"needs review"},dispatched:{bg:"bg-accent/15",text:"text-accent",border:!0,label:"dispatched to PRD"}};function $1(e){return e?e.status==="pending"?"queued":e.status:"ready"}function sw({status:e}){const n=pA[e];return s.jsx("span",{role:"status","aria-label":`Status: ${n.label}`,className:`text-[11.5px] font-semibold px-[9px] py-0.5 rounded-full ${n.bg} ${n.text}${n.border?" ring-1 ring-inset ring-line":""}`,children:n.label})}function AC({path:e,onDismiss:n}){const[r,i]=L.useState(!1);return r?null:s.jsxs("div",{className:"mb-2 inline-flex max-w-[160px] items-start gap-1.5 rounded-md border border-line bg-elev p-1.5",children:[s.jsx("img",{src:Qy(e),alt:"Pasted clipboard image",className:"max-h-[120px] max-w-[120px] rounded object-contain",draggable:!1,onError:()=>i(!0)}),s.jsx("button",{type:"button",onClick:n,title:"Dismiss preview",className:"shrink-0 rounded text-fg-faint hover:bg-hi hover:text-fg",children:"✕"})]})}function Vt({title:e,hint:n}){return s.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:s.jsxs("div",{className:"text-center max-w-md",children:[s.jsx("div",{className:"mb-2 text-fg-dim",children:e}),n&&s.jsx("div",{className:"text-fg-faint",children:n})]})})}const mA=/^\s*(?:[-*+]\s+.+|\d+\.\s+.+)/m;function gA(e){return mA.test(e)}function RC(e,n){window.api.clipboard.writeText(e).then(r=>n(!!(r!=null&&r.ok))).catch(()=>n(!1))}function xA({url:e}){const[n,r]=L.useState(!1),i=()=>{RC(e,o=>{o?(r(!0),setTimeout(()=>r(!1),1100)):Le.error("Copy failed")})};return s.jsxs("div",{className:"mt-1.5 flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[s.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"🔗"}),s.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-fg-dim",children:e}),s.jsx("button",{onClick:i,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:n?"Copied":"Copy"})]})}function yA({path:e,cwd:n}){const[r,i]=L.useState(!1),o=()=>{RC(e,d=>{d?(i(!0),setTimeout(()=>i(!1),1100)):Le.error("Copy failed")})},l=()=>{NC(e,n)};return s.jsxs("div",{className:"mt-1.5 flex items-center gap-2 rounded-lg border border-line bg-elev px-2.5 py-1.5 text-xs",children:[s.jsx("span",{"aria-hidden":!0,className:"text-fg-dim",children:"📄"}),s.jsx("button",{onClick:l,title:"Open in Editor",className:"min-w-0 flex-1 truncate text-left font-mono text-fg-dim hover:text-fg hover:underline",children:e}),s.jsx("button",{onClick:o,className:"shrink-0 rounded border border-line px-2 py-0.5 text-[11px] text-fg-dim hover:bg-hi hover:text-fg",children:r?"Copied":"Copy"})]})}const MC={skill:"border-sage/60 bg-sage/10 text-sage",mcp:"border-accent/60 bg-accent/10 text-accent",tool:"border-line bg-elev text-fg-dim"},IC={skill:"🧩",mcp:"🔌",tool:"⚙"};function PC(e){const n=[];for(const r of e){const i=n[n.length-1];i&&i.kind===r.kind&&i.label===r.label?(i.count+=1,i.id=r.id):n.push({id:r.id,kind:r.kind,label:r.label,count:1})}return n}function DC(e){return e.count>1?`${e.label} ×${e.count}`:e.label}function iw({items:e,running:n=!1}){if(!(e!=null&&e.length))return null;const r=PC(e),i=r.length-1;return s.jsxs("div",{className:"mb-1 flex flex-wrap items-center gap-1",children:[r.map((o,l)=>{const d=n&&l===i;return s.jsxs("span",{className:`inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-mono font-medium ${d?"border-accent/40 bg-accent/10 text-accent":MC[o.kind]}`,children:[IC[o.kind]," ",DC(o)]},o.id)}),s.jsxs("span",{className:"text-[10px] font-mono text-fg-dim",children:["· ",e.length," steps"]})]})}const OC="text-[#8a2f28]",vA="border-[#b8443c]/40 bg-[#b8443c]/10",em="text-[#7a5416]",bx="border-[#8e641a]/40 bg-[#8e641a]/10",bA=1180,A1={overview:"Overview",terminal:"Terminal",browser:"Browser","system-prompt":"System Prompt",settings:"Settings",permissions:"Permissions",skills:"Skills",plugins:"Plugins",mcp:"MCP Servers",hooks:"Hooks",subagents:"Subagents",memory:"Memory",projects:"Projects",history:"History",keybindings:"Keybindings",usage:"Usage",scheduler:"Scheduler",editor:"Editor",voice:"Voice",repoviz:"Repo Viz",search:"Search",remote:"Remote"};function wA(){const[e,n]=L.useState(()=>window.innerWidth);return L.useEffect(()=>{const r=()=>n(window.innerWidth);return window.addEventListener("resize",r),()=>window.removeEventListener("resize",r)},[]),e}function _A({cwd:e,label:n,running:r,queuedPosition:i,stream:o,liveToolUses:l}){const d=PC(l),u=r&&!o?d.length-1:-1;return s.jsxs("div",{className:"w-[280px] shrink-0 overflow-y-auto border-l border-rule px-3 py-4",children:[s.jsxs("div",{className:"rounded-lg border border-line bg-elev px-3 py-2.5",children:[s.jsx("div",{className:"text-xs font-semibold text-fg",children:n}),s.jsx("div",{className:"mt-0.5 truncate font-mono text-[11px] text-fg-dim",title:e,children:e}),s.jsx("div",{className:"mt-2 flex items-center gap-1.5 text-[11px] text-fg-dim",children:r?i>0?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-butter"}),"queued · #",i]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 animate-pulse rounded-full bg-accent"}),"running"]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-line"}),"idle"]})})]}),s.jsx("div",{className:"mt-3 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"This turn"}),d.length===0?s.jsx("div",{className:"mt-1.5 text-[11px] text-fg-faint",children:"No tool activity yet."}):s.jsx("ul",{className:"mt-1.5 space-y-1",children:d.map((h,m)=>s.jsxs("li",{className:`flex items-center gap-1.5 rounded border px-1.5 py-1 text-[11px] font-mono ${m===u?"border-accent/40 bg-accent/10 text-accent":MC[h.kind]}`,children:[m===u?s.jsx("span",{className:"h-1.5 w-1.5 shrink-0 animate-pulse rounded-full bg-accent"}):s.jsx("span",{"aria-hidden":!0,className:"shrink-0",children:IC[h.kind]}),s.jsx("span",{className:"truncate",children:DC(h)})]},h.id))})]})}function kA(e){aA(e),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"scheduler"}))}function SA({tickets:e}){return s.jsxs("div",{className:"w-[260px] shrink-0 overflow-y-auto border-l border-rule px-3 py-4","data-testid":"chat-queue-panel",children:[s.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wide text-fg-faint",children:"Prompt queue"}),e.length===0?s.jsx(Vt,{title:"No prompts queued",hint:"Prompts sent while a turn is running will show up here."}):s.jsx("ul",{className:"space-y-2",children:e.map(n=>{var r;return s.jsxs("li",{className:"rounded-lg border border-line bg-elev px-2.5 py-2","data-testid":"chat-queue-ticket",children:[s.jsx(sw,{status:iA(n.status)}),s.jsx("div",{className:"mt-1.5 truncate text-xs text-fg-dim",title:n.text,children:n.text}),n.status==="dispatched-to-prd"&&!!((r=n.prdSlugs)!=null&&r.length)&&s.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:n.prdSlugs.map(i=>s.jsxs("button",{onClick:()=>kA(i),title:`Open PRD "${i}" in Scheduler`,className:"rounded border border-line px-1.5 py-0.5 font-mono text-[10px] text-accent hover:bg-hi",children:["#",i]},i))})]},n.id)})})]})}const CA="needs interactive consent for an MCP server";function jA({turn:e,cwd:n,tabId:r,runActive:i=!1,consentActionDisabled:o=!1}){const l=L.useRef(null),d=e.role==="assistant"?sA(e,i):null;if(L.useEffect(()=>{e.role==="assistant"&&d==="text"&&l.current&&R$(l.current)},[e.role,d,e.text]),e.role==="user")return s.jsx("div",{className:"flex justify-end",children:s.jsx("div",{className:"max-w-[80%] rounded-tl-lg rounded-tr-lg rounded-bl-lg rounded-br-sm bg-accent/15 px-3 py-2 text-sm text-fg whitespace-pre-wrap",children:e.text})});if(e.role==="error")return s.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${vA} ${OC}`,children:e.text});if(e.role==="question")return s.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${bx} ${em}`,children:[s.jsx(iw,{items:e.toolUses}),s.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${em}`,children:[s.jsx("span",{"aria-hidden":!0,children:"❓"}),"Needs your answer"]}),s.jsx("ul",{className:"list-disc space-y-1 pl-5",children:(e.questions??[e.text]).map((x,g)=>s.jsx("li",{children:x},g))}),s.jsx("div",{className:`mt-2 border-t pt-2 text-[11px] opacity-70 ${bx}`,children:"Reply in the composer below to answer."})]});if(e.role==="notice"){const x=e.text.includes(CA),g=()=>{bt.getState().queueRawCommand(r,"/design consent"),bt.getState().wakeTab(r)};return s.jsxs("div",{className:`rounded-[14px] border px-4 py-3 text-sm ${bx} ${em}`,children:[s.jsxs("div",{className:`mb-2 flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wide ${em}`,children:[s.jsx("span",{"aria-hidden":!0,children:"ℹ️"}),"Needs your attention"]}),e.text,x&&s.jsx("div",{className:`mt-2 border-t pt-2 ${bx}`,children:s.jsx("button",{onClick:g,disabled:o,title:o?"Cancel or wait for the current run before opening a raw session":"Open a live interactive claude session with /design consent pre-typed",className:`rounded border px-2 py-1 text-xs font-medium hover:bg-white/10 disabled:opacity-40 disabled:hover:bg-transparent ${em} border-current`,children:"Grant consent →"})})]})}if(d==="suppress")return null;const u=L$(e.text),h=I$(e.text),m=gA(e.text);return s.jsxs("div",{className:"flex max-w-[90%] items-start gap-2",children:[s.jsx("div",{className:"flex h-[30px] w-[30px] shrink-0 items-center justify-center rounded-lg border border-line bg-elev text-xs font-semibold text-accent",children:"C"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx(iw,{items:e.toolUses,running:d==="working"}),d==="working"?s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"working…"]})}):d==="placeholder"?s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm italic text-fg-dim",children:"(no textual reply — see tool activity above)"}):s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:l,className:`prose-chat rounded-lg bg-elev px-3 py-2 text-sm leading-relaxed text-fg ${m?"prose-chat--plan":""}`,onClick:x=>{rA(x,n)},dangerouslySetInnerHTML:{__html:nA(e.text)}}),u.map(x=>s.jsx(xA,{url:x},x)),h.map(x=>s.jsx(yA,{path:x,cwd:n},x))]})]})]})}function EA({tabId:e,cwd:n}){const r=bt(oe=>oe.tabs.find(ie=>ie.id===e)),i=(r==null?void 0:r.sessionId)??e,o=Gs(oe=>oe.chats[e]),l=Gs(oe=>oe.send),d=Gs(oe=>oe.hydrate),u=Gs(oe=>oe.resetThread),h=Gs(oe=>oe.pushNotice),[m,x]=L.useState(""),[g,v]=L.useState(!1),[S,E]=L.useState(null),j=L.useRef(null),y=L.useRef(null),_=wA()>bA,C=(o==null?void 0:o.turns)??[],N=(o==null?void 0:o.running)??!1,$=(o==null?void 0:o.stream)??"",R=(o==null?void 0:o.queuedPosition)??0,O=(o==null?void 0:o.liveToolUses)??[],I=oA((o==null?void 0:o.ticketHistory)??[],o==null?void 0:o.activeTicket,(o==null?void 0:o.queue)??[]);L.useEffect(()=>{d({tabId:e,cwd:n,sessionId:i})},[e]),L.useEffect(()=>{var oe;(oe=j.current)==null||oe.scrollTo({top:j.current.scrollHeight})},[C.length,$,N]);const z=()=>{if(!m.trim())return;const oe=F$(m.trim());if(oe.type==="nav"){x(""),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:oe.key}));const ie=`→ opened ${A1[oe.key]} — showing the live list`;h(e,ie),Le.info(`Opened ${A1[oe.key]} — showing the live list`);return}oe.type==="warn-unrouted"&&Le.info('Interactive prompts (consent/approval dialogs) need a real terminal — use "Open raw session" if this command asks you something and nothing appears.'),l({tabId:e,sessionId:i,cwd:n,prompt:m}),x(""),E(null)},U=oe=>{oe.key==="Enter"&&!oe.shiftKey&&(oe.preventDefault(),z())},W=oe=>{const ie=oe.currentTarget,X=ie.selectionStart??m.length,Q=ie.selectionEnd??X;oe.preventDefault(),(async()=>{try{const J=await U$({pasteImage:()=>window.api.clipboard.pasteImage(),readText:()=>window.api.clipboard.pasteText().then(le=>le.ok?le.text:"")},m,X,Q);x(J.value),J.toast&&Le.info(J.toast),J.imagePath&&E(J.imagePath),requestAnimationFrame(()=>{try{ie.setSelectionRange(J.caret,J.caret)}catch{}})}catch(J){Le.error(J instanceof Error?J.message:"Paste failed — clipboard unavailable")}})()};L.useEffect(()=>{if(!g)return;const oe=ie=>{var X;(X=y.current)!=null&&X.contains(ie.target)||v(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[g]);const Y=()=>{bt.getState().wakeTab(e)},V=oe=>{bt.getState().wakeTab(e,oe),v(!1)},[H,te]=L.useState(!1),ae=()=>{if(!N){if(!H){te(!0);return}bt.getState().newSession(e),u(e),te(!1)}};return s.jsxs("div",{className:"flex h-full w-full flex-col bg-bg",children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-rule px-4 py-2",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("div",{className:"font-serif text-base text-fg",children:"Chat"}),s.jsx("div",{className:"text-xs text-fg-dim",children:"Chat · headless session — no process runs between commands"}),s.jsx(Zy,{active:"terminal"})]}),s.jsxs("div",{className:"flex items-stretch gap-2",children:[s.jsx("button",{onClick:ae,onBlur:()=>te(!1),disabled:N,title:"Start a brand-new session (clears this conversation's context; shared by both Chat and Raw)",className:`rounded border px-2 py-1 text-xs hover:bg-elev disabled:opacity-40 disabled:hover:bg-transparent ${H?"border-accent/60 text-accent":"border-line text-fg-dim hover:text-fg"}`,children:H?"Confirm new session?":"New session"}),s.jsxs("div",{ref:y,className:"relative flex items-stretch",children:[s.jsx("button",{onClick:Y,disabled:N,className:"rounded-l border border-line px-2 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:N?"Cancel or wait for the current run before opening a raw session":"Drop into a live interactive claude session in this directory",children:"Open raw session ⌃"}),s.jsx("button",{onClick:()=>v(oe=>!oe),disabled:N,className:"rounded-r border border-l-0 border-line px-1.5 py-1 text-xs text-fg-dim hover:bg-elev hover:text-fg disabled:opacity-40 disabled:hover:bg-transparent",title:"Choose model for this raw session",children:"▾"}),g&&s.jsx("div",{className:"absolute right-0 top-full z-10 mt-1 w-32 rounded border border-line bg-hi shadow-lg",children:Yw.map(oe=>s.jsx("button",{onClick:()=>V(oe),className:"block w-full px-3 py-1.5 text-left text-xs text-fg-dim hover:bg-elev hover:text-fg",children:oe.charAt(0).toUpperCase()+oe.slice(1)},oe))})]})]})]}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{ref:j,className:"min-w-0 flex-1 space-y-3 overflow-y-auto px-4 py-4",children:[C.length===0&&!N&&s.jsx("div",{className:"flex h-full items-center justify-center text-sm text-fg-faint select-none",children:"Type a command to start a session. It runs, reports back, and asks if it needs you."}),C.map((oe,ie)=>s.jsx(jA,{turn:oe,cwd:n,tabId:e,runActive:N&&oe.role==="assistant"&&ie===C.length-1,consentActionDisabled:N},oe.id)),N&&s.jsxs("div",{className:"max-w-[90%]",children:[s.jsx(iw,{items:O,running:N&&!$}),s.jsx("div",{className:"rounded-lg bg-elev px-3 py-2 text-sm text-fg-dim",children:R>0?s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 rounded-full bg-butter"}),"queued · #",R," — waiting for a free run slot"]}):$?s.jsx("span",{className:"whitespace-pre-wrap",children:$}):s.jsxs("span",{className:"inline-flex items-center gap-2",children:[s.jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-accent"}),"running…"]})})]})]}),s.jsx(SA,{tickets:I}),_&&s.jsx(_A,{cwd:n,label:(r==null?void 0:r.label)??n,running:N,queuedPosition:R,stream:$,liveToolUses:O})]}),s.jsxs("div",{className:"border-t border-rule p-3",children:[S&&s.jsx(AC,{path:S,onDismiss:()=>E(null)},S),s.jsxs("div",{className:"flex items-end gap-2",children:[s.jsx("textarea",{value:m,onChange:oe=>x(oe.target.value),onKeyDown:U,onPaste:W,rows:2,placeholder:N?"Running… send to queue a follow-up prompt":"Type a command (Enter to send, Shift+Enter for newline)",className:"flex-1 resize-none rounded-md border border-line bg-bg px-3 py-2 text-sm text-fg placeholder:text-fg-faint focus:border-accent/50 focus:outline-none disabled:opacity-50"}),N&&s.jsx("button",{onClick:()=>window.api.chat.cancel(e),className:`rounded-md border px-3 py-2 text-sm hover:bg-[#b8443c]/10 ${OC} border-[#b8443c]/40`,children:"Cancel"}),s.jsx("button",{onClick:z,disabled:!m.trim(),className:"rounded-md bg-accent px-4 py-2 text-sm font-medium text-white hover:bg-accent/90 disabled:opacity-40",children:"Send"})]})]})]})}const ow="\x1B[38;5;240m",aw="\x1B[0m",NA=/\x1b(?:\[[0-9;?]*[a-zA-Z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-Z\\-_])/g;function TA(e){return e.replace(NA,"")}function $A(e){var l;if(!e||typeof e!="object")return null;const n=e,r=n.type==="user"?"You":n.type==="assistant"?"Claude":null;if(!r)return null;const i=(l=n.message)==null?void 0:l.content;if(!Array.isArray(i))return null;const o=i.filter(d=>(d==null?void 0:d.type)==="text"&&typeof d.text=="string").map(d=>TA(d.text).trim()).filter(Boolean).join(`
|
|
2963
2963
|
`);return o?`${ow}[${r}] ${o}${aw}\r
|
|
2964
2964
|
`:null}function AA(e){const n=e.filter(r=>r.kind==="message").map(r=>$A(r.data)).filter(r=>r!==null);return n.length===0?null:`${ow}── prior conversation (from transcript) ──${aw}\r
|
|
2965
2965
|
`+n.join("")+`${ow}── end prior conversation ──${aw}\r
|
|
@@ -2979,7 +2979,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
2979
2979
|
monaco.config({ paths: { vs: '...' } })
|
|
2980
2980
|
|
|
2981
2981
|
For more please check the link https://github.com/suren-atoyan/monaco-loader#config
|
|
2982
|
-
`},z1=jR($R)(UC),AR={config:NR},RR=function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return function(o){return r.reduceRight(function(l,d){return d(l)},o)}};function HC(e,n){return Object.keys(n).forEach(function(r){n[r]instanceof Object&&e[r]&&Object.assign(n[r],HC(e[r],n[r]))}),D1(D1({},e),n)}var MR={type:"cancelation",msg:"operation is manually canceled"};function Vv(e){var n=!1,r=new Promise(function(i,o){e.then(function(l){return n?o(MR):i(l)}),e.catch(o)});return r.cancel=function(){return n=!0},r}var IR=["monaco"],PR=SR.create({config:CR,isInitialized:!1,resolve:null,reject:null,monaco:null}),WC=oR(PR,2),ng=WC[0],nv=WC[1];function DR(e){var n=AR.config(e),r=n.monaco,i=sR(n,IR);nv(function(o){return{config:HC(o.config,i),monaco:r}})}function OR(){var e=ng(function(n){var r=n.monaco,i=n.isInitialized,o=n.resolve;return{monaco:r,isInitialized:i,resolve:o}});if(!e.isInitialized){if(nv({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Vv(Gv);if(window.monaco&&window.monaco.editor)return qC(window.monaco),e.resolve(window.monaco),Vv(Gv);RR(LR,BR)(FR)}return Vv(Gv)}function LR(e){return document.body.appendChild(e)}function zR(e){var n=document.createElement("script");return e&&(n.src=e),n}function BR(e){var n=ng(function(i){var o=i.config,l=i.reject;return{config:o,reject:l}}),r=zR("".concat(n.config.paths.vs,"/loader.js"));return r.onload=function(){return e()},r.onerror=n.reject,r}function FR(){var e=ng(function(r){var i=r.config,o=r.resolve,l=r.reject;return{config:i,resolve:o,reject:l}}),n=window.require;n.config(e.config),n(["vs/editor/editor.main"],function(r){var i=r.m||r;qC(i),e.resolve(i)},function(r){e.reject(r)})}function qC(e){ng().monaco||nv({monaco:e})}function UR(){return ng(function(e){var n=e.monaco;return n})}var Gv=new Promise(function(e,n){return nv({resolve:e,reject:n})}),f0={config:DR,init:OR,__getMonacoInstance:UR},HR={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},Kv=HR,WR={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},qR=WR;function VR({children:e}){return co.createElement("div",{style:qR.container},e)}var GR=VR,KR=GR;function XR({width:e,height:n,isEditorReady:r,loading:i,_ref:o,className:l,wrapperProps:d}){return co.createElement("section",{style:{...Kv.wrapper,width:e,height:n},...d},!r&&co.createElement(KR,null,i),co.createElement("div",{ref:o,style:{...Kv.fullWidth,...!r&&Kv.hide},className:l}))}var YR=XR,VC=L.memo(YR);function JR(e){L.useEffect(e,[])}var GC=JR;function QR(e,n,r=!0){let i=L.useRef(!0);L.useEffect(i.current||!r?()=>{i.current=!1}:e,n)}var Li=QR;function Pm(){}function Dh(e,n,r,i){return ZR(e,i)||eM(e,n,r,i)}function ZR(e,n){return e.editor.getModel(KC(e,n))}function eM(e,n,r,i){return e.editor.createModel(n,r,i?KC(e,i):void 0)}function KC(e,n){return e.Uri.parse(n)}function tM({original:e,modified:n,language:r,originalLanguage:i,modifiedLanguage:o,originalModelPath:l,modifiedModelPath:d,keepCurrentOriginalModel:u=!1,keepCurrentModifiedModel:h=!1,theme:m="light",loading:x="Loading...",options:g={},height:v="100%",width:S="100%",className:E,wrapperProps:j={},beforeMount:y=Pm,onMount:b=Pm}){let[_,C]=L.useState(!1),[N,$]=L.useState(!0),R=L.useRef(null),O=L.useRef(null),I=L.useRef(null),z=L.useRef(b),U=L.useRef(y),W=L.useRef(!1);GC(()=>{let te=f0.init();return te.then(ae=>(O.current=ae)&&$(!1)).catch(ae=>(ae==null?void 0:ae.type)!=="cancelation"&&console.error("Monaco initialization: error:",ae)),()=>R.current?H():te.cancel()}),Li(()=>{if(R.current&&O.current){let te=R.current.getOriginalEditor(),ae=Dh(O.current,e||"",i||r||"text",l||"");ae!==te.getModel()&&te.setModel(ae)}},[l],_),Li(()=>{if(R.current&&O.current){let te=R.current.getModifiedEditor(),ae=Dh(O.current,n||"",o||r||"text",d||"");ae!==te.getModel()&&te.setModel(ae)}},[d],_),Li(()=>{let te=R.current.getModifiedEditor();te.getOption(O.current.editor.EditorOption.readOnly)?te.setValue(n||""):n!==te.getValue()&&(te.executeEdits("",[{range:te.getModel().getFullModelRange(),text:n||"",forceMoveMarkers:!0}]),te.pushUndoStop())},[n],_),Li(()=>{var te,ae;(ae=(te=R.current)==null?void 0:te.getModel())==null||ae.original.setValue(e||"")},[e],_),Li(()=>{let{original:te,modified:ae}=R.current.getModel();O.current.editor.setModelLanguage(te,i||r||"text"),O.current.editor.setModelLanguage(ae,o||r||"text")},[r,i,o],_),Li(()=>{var te;(te=O.current)==null||te.editor.setTheme(m)},[m],_),Li(()=>{var te;(te=R.current)==null||te.updateOptions(g)},[g],_);let Y=L.useCallback(()=>{var oe;if(!O.current)return;U.current(O.current);let te=Dh(O.current,e||"",i||r||"text",l||""),ae=Dh(O.current,n||"",o||r||"text",d||"");(oe=R.current)==null||oe.setModel({original:te,modified:ae})},[r,n,o,e,i,l,d]),V=L.useCallback(()=>{var te;!W.current&&I.current&&(R.current=O.current.editor.createDiffEditor(I.current,{automaticLayout:!0,...g}),Y(),(te=O.current)==null||te.editor.setTheme(m),C(!0),W.current=!0)},[g,m,Y]);L.useEffect(()=>{_&&z.current(R.current,O.current)},[_]),L.useEffect(()=>{!N&&!_&&V()},[N,_,V]);function H(){var ae,oe,ie,X;let te=(ae=R.current)==null?void 0:ae.getModel();u||((oe=te==null?void 0:te.original)==null||oe.dispose()),h||((ie=te==null?void 0:te.modified)==null||ie.dispose()),(X=R.current)==null||X.dispose()}return co.createElement(VC,{width:S,height:v,isEditorReady:_,loading:x,_ref:I,className:E,wrapperProps:j})}var nM=tM;L.memo(nM);function rM(e){let n=L.useRef();return L.useEffect(()=>{n.current=e},[e]),n.current}var sM=rM,kx=new Map;function iM({defaultValue:e,defaultLanguage:n,defaultPath:r,value:i,language:o,path:l,theme:d="light",line:u,loading:h="Loading...",options:m={},overrideServices:x={},saveViewState:g=!0,keepCurrentModel:v=!1,width:S="100%",height:E="100%",className:j,wrapperProps:y={},beforeMount:b=Pm,onMount:_=Pm,onChange:C,onValidate:N=Pm}){let[$,R]=L.useState(!1),[O,I]=L.useState(!0),z=L.useRef(null),U=L.useRef(null),W=L.useRef(null),Y=L.useRef(_),V=L.useRef(b),H=L.useRef(),te=L.useRef(i),ae=sM(l),oe=L.useRef(!1),ie=L.useRef(!1);GC(()=>{let J=f0.init();return J.then(le=>(z.current=le)&&I(!1)).catch(le=>(le==null?void 0:le.type)!=="cancelation"&&console.error("Monaco initialization: error:",le)),()=>U.current?Q():J.cancel()}),Li(()=>{var le,ce,pe,Ae;let J=Dh(z.current,e||i||"",n||o||"",l||r||"");J!==((le=U.current)==null?void 0:le.getModel())&&(g&&kx.set(ae,(ce=U.current)==null?void 0:ce.saveViewState()),(pe=U.current)==null||pe.setModel(J),g&&((Ae=U.current)==null||Ae.restoreViewState(kx.get(l))))},[l],$),Li(()=>{var J;(J=U.current)==null||J.updateOptions(m)},[m],$),Li(()=>{!U.current||i===void 0||(U.current.getOption(z.current.editor.EditorOption.readOnly)?U.current.setValue(i):i!==U.current.getValue()&&(ie.current=!0,U.current.executeEdits("",[{range:U.current.getModel().getFullModelRange(),text:i,forceMoveMarkers:!0}]),U.current.pushUndoStop(),ie.current=!1))},[i],$),Li(()=>{var le,ce;let J=(le=U.current)==null?void 0:le.getModel();J&&o&&((ce=z.current)==null||ce.editor.setModelLanguage(J,o))},[o],$),Li(()=>{var J;u!==void 0&&((J=U.current)==null||J.revealLine(u))},[u],$),Li(()=>{var J;(J=z.current)==null||J.editor.setTheme(d)},[d],$);let X=L.useCallback(()=>{var J;if(!(!W.current||!z.current)&&!oe.current){V.current(z.current);let le=l||r,ce=Dh(z.current,i||e||"",n||o||"",le||"");U.current=(J=z.current)==null?void 0:J.editor.create(W.current,{model:ce,automaticLayout:!0,...m},x),g&&U.current.restoreViewState(kx.get(le)),z.current.editor.setTheme(d),u!==void 0&&U.current.revealLine(u),R(!0),oe.current=!0}},[e,n,r,i,o,l,m,x,g,d,u]);L.useEffect(()=>{$&&Y.current(U.current,z.current)},[$]),L.useEffect(()=>{!O&&!$&&X()},[O,$,X]),te.current=i,L.useEffect(()=>{var J,le;$&&C&&((J=H.current)==null||J.dispose(),H.current=(le=U.current)==null?void 0:le.onDidChangeModelContent(ce=>{ie.current||C(U.current.getValue(),ce)}))},[$,C]),L.useEffect(()=>{if($){let J=z.current.editor.onDidChangeMarkers(le=>{var pe;let ce=(pe=U.current.getModel())==null?void 0:pe.uri;if(ce&&le.find(Ae=>Ae.path===ce.path)){let Ae=z.current.editor.getModelMarkers({resource:ce});N==null||N(Ae)}});return()=>{J==null||J.dispose()}}return()=>{}},[$,N]);function Q(){var J,le;(J=H.current)==null||J.dispose(),v?g&&kx.set(l,U.current.saveViewState()):(le=U.current.getModel())==null||le.dispose(),U.current.dispose()}return co.createElement(VC,{width:S,height:E,isEditorReady:$,loading:h,_ref:W,className:j,wrapperProps:y})}var oM=iM,aM=L.memo(oM),p0=aM;function kc({value:e,onChange:n,path:r,readOnly:i}){return s.jsx(p0,{path:`file://${r}`,defaultLanguage:"markdown",value:e,onChange:o=>n(o??""),theme:"vs-dark",options:{minimap:{enabled:!1},fontSize:13,fontFamily:"JetBrains Mono, ui-monospace, Menlo, monospace",lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,wordWrap:"on",readOnly:i,automaticLayout:!0}})}function ky(e){e<0&&(e=0);const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const r=Math.floor(n/60);return r<60?`${r}m${(n%60).toString().padStart(2,"0")}s`:`${Math.floor(r/60)}h${(r%60).toString().padStart(2,"0")}m`}function Uo(e){e<0&&(e=0);const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const r=Math.floor(n/60);if(r<60)return`${r}m`;const i=Math.floor(r/60);return i<24?`${i}h${r%60?` ${r%60}m`:""}`:`${Math.floor(i/24)}d`}function Wh(e){return new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function Yh(e,n){if(e===null)return"never";const r=n-e;return r<0?"soon":r<5e3?"just now":`${Uo(r)} ago`}function lM(e){if(!e)return"";const n=Math.max(0,Date.now()-e);return n<6e4?`saved ${Math.round(n/1e3)}s ago`:n<36e5?`saved ${Math.round(n/6e4)}m ago`:`saved ${Math.round(n/36e5)}h ago`}function Fm(e){if(!e)return"";const n=Date.now()-e;return n<5e3?"just now":`${Uo(n)} ago`}function XC(e){const n=Math.max(0,Math.floor(e/1e3));return`${Math.floor(n/60)}:${(n%60).toString().padStart(2,"0")}`}function Um(e){e<0&&(e=0);const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const r=Math.floor(n/60);if(r<60)return`${r}m`;const i=Math.floor(r/60),o=r%60;return o>0?`${i}h ${o}m`:`${i}h`}function Uu({dirty:e,busy:n,parseError:r,lastSavedAt:i,onSave:o,onRevert:l,leading:d}){const u=e&&!n&&!r;return s.jsxs("div",{className:"px-3 py-1.5 flex items-center gap-2 text-xs",children:[s.jsx("div",{className:"flex-1 min-w-0 truncate text-fg-faint",children:d}),r&&s.jsx("span",{className:"text-red-400 truncate max-w-xs",title:r,children:r}),!e&&!r&&i&&s.jsx("span",{className:"text-fg-faint",children:lM(i)}),e&&!r&&s.jsx("span",{className:"text-accent",children:"unsaved"}),s.jsx("button",{onClick:l,disabled:!e||n,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed",children:"Revert"}),s.jsx("button",{onClick:o,disabled:!u,className:`px-2.5 py-0.5 rounded border ${u?"border-accent bg-accent/15 text-accent hover:bg-accent/25":"border-line text-fg-faint opacity-50 cursor-not-allowed"}`,children:n?"Saving…":"Save"})]})}function Vt({title:e,hint:n}){return s.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:s.jsxs("div",{className:"text-center max-w-md",children:[s.jsx("div",{className:"mb-2 text-fg-dim",children:e}),n&&s.jsx("div",{className:"text-fg-faint",children:n})]})})}function Mu(...e){return e.filter(Boolean).map((n,r)=>r===0?n.replace(/\/+$/,""):n.replace(/^\/+|\/+$/g,"")).join("/")}const Sy={scopes:["user","project","local"],resolve:(e,n,r)=>e==="user"?Mu(n,".claude","settings.json"):r?e==="project"?Mu(r,".claude","settings.json"):Mu(r,".claude","settings.local.json"):null},Xv={scopes:["user","project","local"],resolve:(e,n,r)=>e==="user"?Mu(n,".claude","CLAUDE.md"):r?e==="project"?Mu(r,"CLAUDE.md"):Mu(r,"CLAUDE.local.md"):null},B1=Sy,cM={scopes:["user"],resolve:(e,n)=>e==="user"?Mu(n,".claude","keybindings.json"):null},os={user:{label:"User",hint:"~/.claude/ — applies to all projects"},project:{label:"Project",hint:"<cwd>/.claude/ — checked into git"},local:{label:"Local",hint:"<cwd>/.claude/…local — gitignored, per-machine"}};function ka({scopes:e,active:n,onChange:r,annotate:i}){return s.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:e.map(o=>{const l=os[o],d=i==null?void 0:i(o),u=o===n;return s.jsxs("button",{title:l.hint,onClick:()=>r(o),className:`px-2.5 py-1 text-xs flex items-center gap-1.5 transition-colors ${u?"bg-bg-hi text-fg":"bg-bg-elev text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:[s.jsx("span",{children:l.label}),(d==null?void 0:d.dirty)&&s.jsx("span",{className:"w-1 h-1 rounded-full bg-accent",title:"unsaved edits"}),d&&d.exists===!1&&!d.dirty&&s.jsx("span",{className:"w-1 h-1 rounded-full bg-fg-faint",title:"not yet created"})]},o)})})}function Cy({checked:e,onChange:n,label:r,disabled:i}){return s.jsxs("label",{className:`inline-flex items-center gap-2 text-xs ${i?"opacity-50 cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:i,onClick:()=>!i&&n(!e),className:`relative w-7 h-4 rounded-full transition-colors ${e?"bg-accent":"bg-bg-hi border border-line"}`,children:s.jsx("span",{className:`absolute top-0.5 w-3 h-3 rounded-full bg-fg transition-transform ${e?"translate-x-3.5":"translate-x-0.5"}`})}),r&&s.jsx("span",{className:"text-fg-dim",children:r})]})}const F1=e=>`${e}/.claude/session-manager/provenance.json`;function uM(e){if(!e||typeof e!="object")return{};const n={};for(const[r,i]of Object.entries(e))(i==="anthropic"||i==="community"||i==="local")&&(n[r]=i);return n}const dM=cr((e,n)=>({overrides:{},loaded:!1,loading:!1,home:null,load:async r=>{const i=n();if(!(i.home===r&&(i.loaded||i.loading))){e({home:r,loading:!0});try{const o=await window.api.config.readJson(F1(r)),l=o.exists?uM(o.data):{};e(d=>({overrides:{...l,...d.overrides},loaded:!0,loading:!1}))}catch{e({loaded:!0,loading:!1})}}},setOverride:async(r,i)=>{const o={...n().overrides};i===null?delete o[r]:o[r]=i,e({overrides:o});const l=n().home;if(l)try{await window.api.config.writeJson(F1(l),o)}catch{}}})),YC={default:"bg-bg-hi text-fg-dim border-line",accent:"bg-accent/15 text-accent-dark border-accent/30",warn:"bg-honey/15 text-honey-dark border-honey/30",dim:"bg-bg-elev text-fg-dim border-line",good:"bg-sage/15 text-sage-dark border-sage/30"};function lr({children:e,tone:n="default",className:r="",title:i}){return s.jsx("span",{title:i,className:`inline-flex items-center gap-1 text-[10px] leading-none px-1.5 py-0.5 rounded border uppercase tracking-wide ${YC[n]} ${r}`,children:e})}const cw=[{id:"filesystem",name:"Filesystem",description:"Secure file operations with configurable access controls",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem",config:{command:"npx",args:["-y","@modelcontextprotocol/server-filesystem","<path>"]},envVars:[]},{id:"fetch",name:"Fetch",description:"Web content fetching and conversion for efficient LLM usage",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/fetch",config:{command:"uvx",args:["mcp-server-fetch"]},envVars:[]},{id:"memory",name:"Memory",description:"Knowledge graph-based persistent memory system",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/memory",config:{command:"npx",args:["-y","@modelcontextprotocol/server-memory"]},envVars:[]},{id:"sequential-thinking",name:"Sequential Thinking",description:"Dynamic and reflective problem-solving through thought sequences",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking",config:{command:"npx",args:["-y","@modelcontextprotocol/server-sequential-thinking"]},envVars:[]},{id:"git",name:"Git",description:"Tools to read, search, and manipulate Git repositories",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/git",config:{command:"uvx",args:["mcp-server-git","--repository","<path>"]},envVars:[]},{id:"time",name:"Time",description:"Time and timezone conversion capabilities",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/time",config:{command:"uvx",args:["mcp-server-time"]},envVars:[]},{id:"everything",name:"Everything",description:"Reference/test server with prompts, resources, and tools",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/everything",config:{command:"npx",args:["-y","@modelcontextprotocol/server-everything"]},envVars:[]},{id:"github",name:"GitHub",description:"Official GitHub repository, issues, and PR management",official:!1,homepage:"https://github.com/github/github-mcp-server",config:{command:"docker",args:["run","-i","--rm","-e","GITHUB_PERSONAL_ACCESS_TOKEN","ghcr.io/github/github-mcp-server"]},envVars:["GITHUB_PERSONAL_ACCESS_TOKEN"]},{id:"gitlab",name:"GitLab",description:"GitLab API integration for projects, issues, and merge requests",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/gitlab",config:{command:"npx",args:["-y","@modelcontextprotocol/server-gitlab"]},envVars:["GITLAB_PERSONAL_ACCESS_TOKEN","GITLAB_API_URL"]},{id:"postgres",name:"PostgreSQL",description:"Read-only database access with schema inspection",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres",config:{command:"npx",args:["-y","@modelcontextprotocol/server-postgres","<connection-string>"]},envVars:[]},{id:"sqlite",name:"SQLite",description:"Database interaction and business intelligence over SQLite",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/sqlite",config:{command:"uvx",args:["mcp-server-sqlite","--db-path","<path>"]},envVars:[]},{id:"slack",name:"Slack",description:"Channel management and messaging for Slack workspaces",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/slack",config:{command:"npx",args:["-y","@modelcontextprotocol/server-slack"]},envVars:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"]},{id:"google-drive",name:"Google Drive",description:"File access and search for Google Drive",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/gdrive",config:{command:"npx",args:["-y","@modelcontextprotocol/server-gdrive"]},envVars:["GDRIVE_CREDENTIALS_PATH"]},{id:"google-maps",name:"Google Maps",description:"Location services, directions, and place details",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/google-maps",config:{command:"npx",args:["-y","@modelcontextprotocol/server-google-maps"]},envVars:["GOOGLE_MAPS_API_KEY"]},{id:"puppeteer",name:"Puppeteer",description:"Browser automation and web scraping via Puppeteer",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/puppeteer",config:{command:"npx",args:["-y","@modelcontextprotocol/server-puppeteer"]},envVars:[]},{id:"playwright",name:"Playwright",description:"Cross-browser automation for navigation, screenshots, and data extraction",official:!1,homepage:"https://github.com/microsoft/playwright-mcp",config:{command:"npx",args:["-y","@playwright/mcp@latest"]},envVars:[]},{id:"brave-search",name:"Brave Search",description:"Web and local search using the Brave Search API",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/brave-search",config:{command:"npx",args:["-y","@modelcontextprotocol/server-brave-search"]},envVars:["BRAVE_API_KEY"]},{id:"redis",name:"Redis",description:"Interact with Redis key-value stores",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/redis",config:{command:"npx",args:["-y","@modelcontextprotocol/server-redis","<redis-url>"]},envVars:[]},{id:"sentry",name:"Sentry",description:"Retrieve and analyze Sentry error tracking issues",official:!1,homepage:"https://github.com/getsentry/sentry-mcp",config:{command:"npx",args:["-y","@sentry/mcp-server@latest"]},envVars:["SENTRY_AUTH_TOKEN"]},{id:"linear",name:"Linear",description:"Issue tracking and project management for Linear",official:!1,homepage:"https://linear.app/docs/mcp",config:{command:"npx",args:["-y","mcp-remote","https://mcp.linear.app/sse"]},envVars:[]},{id:"notion",name:"Notion",description:"Notion workspace page and database management",official:!1,homepage:"https://github.com/makenotion/notion-mcp-server",config:{command:"npx",args:["-y","@notionhq/notion-mcp-server"]},envVars:["NOTION_API_KEY"]},{id:"stripe",name:"Stripe",description:"Payment processing, customers, and invoices via Stripe API",official:!1,homepage:"https://github.com/stripe/agent-toolkit",config:{command:"npx",args:["-y","@stripe/mcp","--tools=all"]},envVars:["STRIPE_SECRET_KEY"]},{id:"cloudflare",name:"Cloudflare",description:"Manage Cloudflare Workers, KV, R2, D1, and Workers AI",official:!1,homepage:"https://github.com/cloudflare/mcp-server-cloudflare",config:{command:"npx",args:["-y","mcp-remote","https://observability.mcp.cloudflare.com/sse"]},envVars:[]},{id:"context7",name:"Context7",description:"Up-to-date version-specific library docs injected into prompts",official:!1,homepage:"https://github.com/upstash/context7",config:{command:"npx",args:["-y","@upstash/context7-mcp@latest"]},envVars:[]},{id:"tavily",name:"Tavily",description:"AI-optimized web search with clean structured results",official:!1,homepage:"https://github.com/tavily-ai/tavily-mcp",config:{command:"npx",args:["-y","tavily-mcp@latest"]},envVars:["TAVILY_API_KEY"]},{id:"perplexity",name:"Perplexity",description:"Answer-engine search with deep research and reasoning",official:!1,homepage:"https://github.com/ppl-ai/modelcontextprotocol",config:{command:"npx",args:["-y","server-perplexity-ask"]},envVars:["PERPLEXITY_API_KEY"]},{id:"figma",name:"Figma Dev Mode",description:"First-party Figma design-to-code bridge exposing node tree",official:!1,homepage:"https://help.figma.com/hc/en-us/articles/32132100833559",config:{url:"http://127.0.0.1:3845/sse"},envVars:[]},{id:"supabase",name:"Supabase",description:"Manage Supabase projects, tables, and SQL queries",official:!1,homepage:"https://github.com/supabase-community/supabase-mcp",config:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest"]},envVars:["SUPABASE_ACCESS_TOKEN"]},{id:"atlassian",name:"Atlassian (Jira/Confluence)",description:"Official Jira and Confluence integration",official:!1,homepage:"https://www.atlassian.com/platform/remote-mcp-server",config:{command:"npx",args:["-y","mcp-remote","https://mcp.atlassian.com/v1/sse"]},envVars:[]},{id:"aws",name:"AWS",description:"AWS services access and best-practice guidance",official:!1,homepage:"https://github.com/awslabs/mcp",config:{command:"uvx",args:["awslabs.core-mcp-server@latest"]},envVars:["AWS_PROFILE","AWS_REGION"]},{id:"obsidian",name:"Obsidian",description:"Read and search notes in an Obsidian vault",official:!1,homepage:"https://github.com/MarkusPfundstein/mcp-obsidian",config:{command:"uvx",args:["mcp-obsidian"]},envVars:["OBSIDIAN_API_KEY"]}],jy=[{id:"pdf",name:"PDF",description:"Create, edit, and extract content from PDF documents",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/pdf"},{id:"docx",name:"DOCX",description:"Create and edit Microsoft Word documents",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/docx"},{id:"xlsx",name:"XLSX",description:"Create and edit Excel spreadsheets with formulas and formatting",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/xlsx"},{id:"pptx",name:"PPTX",description:"Create and edit PowerPoint presentations",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/pptx"},{id:"webapp-testing",name:"Webapp Testing",description:"Test web applications using Playwright-driven browser automation",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/webapp-testing"},{id:"playwright-e2e",name:"Playwright E2E",description:"End-to-end browser tests — navigation, forms, assertions, waiting strategies",official:!1,source:"local"},{id:"playwright-visual-testing",name:"Playwright Visual Testing",description:"Visual regression testing — screenshot comparison, pixel diffs, responsive layouts",official:!1,source:"local"},{id:"playwright-accessibility",name:"Playwright Accessibility",description:"Accessibility testing — WCAG compliance, axe-core scans, keyboard navigation",official:!1,source:"local"},{id:"playwright-api-testing",name:"Playwright API Testing",description:"API testing with Playwright request context — REST endpoints, auth flows, contracts",official:!1,source:"local"},{id:"playwright-debug",name:"Playwright Debug",description:"Debug failing tests — trace viewer, inspector, headed mode, flaky test fixes",official:!1,source:"local"},{id:"web-artifacts-builder",name:"Web Artifacts Builder",description:"Build polished interactive web artifacts and demos",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/web-artifacts-builder"},{id:"frontend-design",name:"Frontend Design",description:"Apply frontend UI/UX design patterns and visual polish",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/frontend-design"},{id:"canvas-design",name:"Canvas Design",description:"Canvas-based graphic design and composition techniques",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/canvas-design"},{id:"algorithmic-art",name:"Algorithmic Art",description:"Create generative and algorithmic art",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/algorithmic-art"},{id:"brand-guidelines",name:"Brand Guidelines",description:"Apply brand identity and style guideline specifications",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/brand-guidelines"},{id:"theme-factory",name:"Theme Factory",description:"Generate and customize visual themes",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/theme-factory"},{id:"slack-gif-creator",name:"Slack GIF Creator",description:"Create animated GIFs suitable for Slack",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/slack-gif-creator"},{id:"doc-coauthoring",name:"Doc Coauthoring",description:"Collaborative document authoring and editing workflows",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/doc-coauthoring"},{id:"internal-comms",name:"Internal Comms",description:"Internal communications templates and drafting",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/internal-comms"},{id:"claude-api",name:"Claude API",description:"Build apps with the Claude API and Anthropic SDKs",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/claude-api"},{id:"mcp-builder",name:"MCP Builder",description:"Scaffold and build new Model Context Protocol servers",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/mcp-builder"},{id:"skill-creator",name:"Skill Creator",description:"Scaffold and create new Claude Code skills",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/skill-creator"}],Ey=[{id:"session-manager-dev",name:"Session Manager Dev",description:"Default end-to-end dev skillset: /develop + /prd (decompose → scheduler PRDs), /process-feedback + /my-feedback (cross-project intake), /project-status + /optimize-kpi + /local-project-health (status & KPI loop), /requesting-code-review + /security-review (review gate), /explain-to-me (HUMAN_LEARN docs).",official:!1,source:"https://github.com/StanislavBG/claude-code-session-manager/tree/main/plugins/session-manager-dev",bundles:["skills"],marketplace:{add:"bundled",name:"session-manager"}},{id:"code-review",name:"Code Review",description:"Comprehensive code review with best practices and improvement suggestions",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/code-review",bundles:["commands","agents"]},{id:"pr-review-toolkit",name:"PR Review Toolkit",description:"Pull request review automation and workflows",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/pr-review-toolkit",bundles:["commands","agents"]},{id:"commit-commands",name:"Commit Commands",description:"Git commit workflow shortcuts with conventional commit formatting",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/commit-commands",bundles:["commands"]},{id:"feature-dev",name:"Feature Dev",description:"Feature development assistance from spec to implementation",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/feature-dev",bundles:["commands","agents"]},{id:"security-guidance",name:"Security Guidance",description:"Security best-practice review and enforcement",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/security-guidance",bundles:["commands","agents"]},{id:"agent-sdk-dev",name:"Agent SDK Dev",description:"Development tools for building with the Claude Agent SDK",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/agent-sdk-dev",bundles:["commands","skills"]},{id:"plugin-dev",name:"Plugin Dev",description:"Scaffolding and tooling for authoring Claude Code plugins",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/plugin-dev",bundles:["commands","skills"]},{id:"mcp-server-dev",name:"MCP Server Dev",description:"Develop and test Model Context Protocol servers",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/mcp-server-dev",bundles:["commands","skills"]},{id:"skill-creator",name:"Skill Creator",description:"Framework for creating and iterating on new skills",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/skill-creator",bundles:["commands","skills"]},{id:"claude-md-management",name:"CLAUDE.md Management",description:"Manage and maintain CLAUDE.md project memory files",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/claude-md-management",bundles:["commands"]},{id:"typescript-lsp",name:"TypeScript LSP",description:"TypeScript/JavaScript language server integration",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/typescript-lsp",bundles:["hooks","commands"]},{id:"pyright-lsp",name:"Pyright LSP",description:"Python language server integration via Pyright",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/pyright-lsp",bundles:["hooks","commands"]},{id:"rust-analyzer-lsp",name:"Rust Analyzer LSP",description:"Rust language server integration via rust-analyzer",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/rust-analyzer-lsp",bundles:["hooks","commands"]},{id:"gopls-lsp",name:"Go LSP (gopls)",description:"Go language server integration via gopls",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/gopls-lsp",bundles:["hooks","commands"]},{id:"code-simplifier",name:"Code Simplifier",description:"Review changed code for reuse, quality, and efficiency then fix issues",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/code-simplifier",bundles:["commands","agents"]},{id:"hookify",name:"Hookify",description:"Utilities and templates for authoring Claude Code hooks",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/hookify",bundles:["commands","skills"]},{id:"frontend-design-plugin",name:"Frontend Design Plugin",description:"Frontend design assistance and visual polish workflows",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/frontend-design",bundles:["commands","skills","agents"]},{id:"clangd-lsp",name:"clangd-lsp",description:"C/C++ diagnostics via clangd. Requires clangd on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/clangd-lsp",bundles:["hooks","commands"]},{id:"csharp-lsp",name:"csharp-lsp",description:"C# diagnostics. Requires OmniSharp or Roslyn LSP on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/csharp-lsp",bundles:["hooks","commands"]},{id:"jdtls-lsp",name:"jdtls-lsp",description:"Java diagnostics via Eclipse JDT LS. Requires jdtls on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/jdtls-lsp",bundles:["hooks","commands"]},{id:"kotlin-lsp",name:"kotlin-lsp",description:"Kotlin diagnostics. Requires kotlin-language-server on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/kotlin-lsp",bundles:["hooks","commands"]},{id:"lua-lsp",name:"lua-lsp",description:"Lua diagnostics. Requires lua-language-server on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/lua-lsp",bundles:["hooks","commands"]},{id:"php-lsp",name:"php-lsp",description:"PHP diagnostics. Requires intelephense or phpactor on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/php-lsp",bundles:["hooks","commands"]},{id:"swift-lsp",name:"swift-lsp",description:"Swift diagnostics via sourcekit-lsp. Requires sourcekit-lsp on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/swift-lsp",bundles:["hooks","commands"]},{id:"github",name:"github",description:"GitHub PRs, issues, gh-style flows.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/github",bundles:["mcp"]},{id:"gitlab",name:"gitlab",description:"GitLab MRs, issues, pipelines.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/gitlab",bundles:["mcp"]},{id:"atlassian",name:"atlassian",description:"Jira / Confluence search and updates.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/atlassian",bundles:["mcp"]},{id:"asana",name:"asana",description:"Asana task and project ops.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/asana",bundles:["mcp"]},{id:"linear",name:"linear",description:"Linear issue tracking — pairs with the Tasks tab.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/linear",bundles:["mcp"]},{id:"notion",name:"notion",description:"Notion document lookup and edits.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/notion",bundles:["mcp"]},{id:"figma",name:"figma",description:"Figma file inspection for UI work.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/figma",bundles:["mcp"]},{id:"vercel",name:"vercel",description:"Vercel deploy diagnostics.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/vercel",bundles:["mcp"]},{id:"firebase",name:"firebase",description:"Firebase project + Firestore ops.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/firebase",bundles:["mcp"]},{id:"supabase",name:"supabase",description:"Supabase database operations.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/supabase",bundles:["mcp"]},{id:"slack",name:"slack",description:"Slack DM / channel posting from agents.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/slack",bundles:["mcp"]},{id:"sentry",name:"sentry",description:"Sentry bug triage and event lookup.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/sentry",bundles:["mcp"]}],Ny=[{id:"prettier-on-write",name:"Prettier on Write",description:"Auto-format JS/TS/JSON/MD files after edit via prettier",event:"PostToolUse",matcher:"Write|Edit",command:"jq -r '.tool_input.file_path // empty' | grep -E '\\.(js|jsx|ts|tsx|json|md|css|html|yaml|yml)$' | xargs -r -I{} npx --no-install prettier --write {} 2>/dev/null || true"},{id:"black-on-write",name:"Black on Write (Python)",description:"Auto-format Python files after edit via black",event:"PostToolUse",matcher:"Write|Edit",command:"jq -r '.tool_input.file_path // empty' | grep -E '\\.py$' | xargs -r black -q 2>/dev/null || true"},{id:"rustfmt-on-write",name:"rustfmt on Write",description:"Auto-format Rust files after edit via rustfmt",event:"PostToolUse",matcher:"Write|Edit",command:"jq -r '.tool_input.file_path // empty' | grep -E '\\.rs$' | xargs -r rustfmt 2>/dev/null || true"},{id:"gofmt-on-write",name:"gofmt on Write",description:"Auto-format Go files after edit via gofmt",event:"PostToolUse",matcher:"Write|Edit",command:"jq -r '.tool_input.file_path // empty' | grep -E '\\.go$' | xargs -r gofmt -w 2>/dev/null || true"},{id:"block-secret-writes",name:"Block Writes to Secrets",description:"Deny edits to .env, credentials, key files",event:"PreToolUse",matcher:"Write|Edit",command:`path=$(jq -r '.tool_input.file_path // empty'); echo "$path" | grep -qE '(^|/)(\\.env|\\.env\\..+|id_rsa|id_ed25519|.*\\.pem|.*\\.key|credentials\\.json|\\.aws/credentials)$' && { echo '{"decision":"block","reason":"refusing to edit secret file"}'; exit 2; } || true`},{id:"notify-on-stop",name:"Desktop Notify on Stop",description:"Send a desktop notification when Claude finishes a turn",event:"Stop",command:`command -v notify-send >/dev/null && notify-send "Claude Code" "Session ready" || (command -v osascript >/dev/null && osascript -e 'display notification "Session ready" with title "Claude Code"') || true`},{id:"bell-on-notification",name:"Terminal Bell on Notification",description:"Ring the terminal bell on permission prompts / idle notifications",event:"Notification",command:"printf '\\a'"},{id:"log-tool-calls",name:"Log Tool Calls (JSONL)",description:"Append every tool call to ~/.claude/logs/tool-calls.jsonl for audit",event:"PreToolUse",command:"mkdir -p ~/.claude/logs && cat >> ~/.claude/logs/tool-calls.jsonl"},{id:"auto-stage-edits",name:"Auto-stage Edited Files",description:"git add each file Claude edits (inside a repo)",event:"PostToolUse",matcher:"Write|Edit",command:`path=$(jq -r '.tool_input.file_path // empty'); [ -n "$path" ] && git -C "$(dirname "$path")" add "$path" 2>/dev/null || true`},{id:"block-dangerous-bash",name:"Block Dangerous Bash",description:"Refuse rm -rf /, fork bombs, curl|sh pipes",event:"PreToolUse",matcher:"Bash",command:`cmd=$(jq -r '.tool_input.command // empty'); echo "$cmd" | grep -qE '(rm -rf /|:\\(\\)\\{.*\\};|curl.*\\|\\s*(bash|sh)|wget.*\\|\\s*(bash|sh)|mkfs\\.|dd if=.*of=/dev/)' && { echo '{"decision":"block","reason":"dangerous command pattern"}'; exit 2; } || true`},{id:"prepend-cwd-to-prompt",name:"Prepend CWD to Prompt",description:"Add cwd context to every user prompt automatically",event:"UserPromptSubmit",command:'echo "{\\"additionalContext\\":\\"cwd: $(pwd)\\"}"'},{id:"archive-transcript",name:"Archive Transcript on SessionEnd",description:"Copy the session jsonl to ~/.claude/archive/ when done",event:"SessionEnd",command:`src=$(jq -r '.transcript_path // empty'); [ -n "$src" ] && mkdir -p ~/.claude/archive && cp "$src" ~/.claude/archive/ 2>/dev/null || true`}],no=(e,n,r,i)=>`---
|
|
2982
|
+
`},z1=jR($R)(UC),AR={config:NR},RR=function(){for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return function(o){return r.reduceRight(function(l,d){return d(l)},o)}};function HC(e,n){return Object.keys(n).forEach(function(r){n[r]instanceof Object&&e[r]&&Object.assign(n[r],HC(e[r],n[r]))}),D1(D1({},e),n)}var MR={type:"cancelation",msg:"operation is manually canceled"};function Vv(e){var n=!1,r=new Promise(function(i,o){e.then(function(l){return n?o(MR):i(l)}),e.catch(o)});return r.cancel=function(){return n=!0},r}var IR=["monaco"],PR=SR.create({config:CR,isInitialized:!1,resolve:null,reject:null,monaco:null}),WC=oR(PR,2),ng=WC[0],nv=WC[1];function DR(e){var n=AR.config(e),r=n.monaco,i=sR(n,IR);nv(function(o){return{config:HC(o.config,i),monaco:r}})}function OR(){var e=ng(function(n){var r=n.monaco,i=n.isInitialized,o=n.resolve;return{monaco:r,isInitialized:i,resolve:o}});if(!e.isInitialized){if(nv({isInitialized:!0}),e.monaco)return e.resolve(e.monaco),Vv(Gv);if(window.monaco&&window.monaco.editor)return qC(window.monaco),e.resolve(window.monaco),Vv(Gv);RR(LR,BR)(FR)}return Vv(Gv)}function LR(e){return document.body.appendChild(e)}function zR(e){var n=document.createElement("script");return e&&(n.src=e),n}function BR(e){var n=ng(function(i){var o=i.config,l=i.reject;return{config:o,reject:l}}),r=zR("".concat(n.config.paths.vs,"/loader.js"));return r.onload=function(){return e()},r.onerror=n.reject,r}function FR(){var e=ng(function(r){var i=r.config,o=r.resolve,l=r.reject;return{config:i,resolve:o,reject:l}}),n=window.require;n.config(e.config),n(["vs/editor/editor.main"],function(r){var i=r.m||r;qC(i),e.resolve(i)},function(r){e.reject(r)})}function qC(e){ng().monaco||nv({monaco:e})}function UR(){return ng(function(e){var n=e.monaco;return n})}var Gv=new Promise(function(e,n){return nv({resolve:e,reject:n})}),f0={config:DR,init:OR,__getMonacoInstance:UR},HR={wrapper:{display:"flex",position:"relative",textAlign:"initial"},fullWidth:{width:"100%"},hide:{display:"none"}},Kv=HR,WR={container:{display:"flex",height:"100%",width:"100%",justifyContent:"center",alignItems:"center"}},qR=WR;function VR({children:e}){return co.createElement("div",{style:qR.container},e)}var GR=VR,KR=GR;function XR({width:e,height:n,isEditorReady:r,loading:i,_ref:o,className:l,wrapperProps:d}){return co.createElement("section",{style:{...Kv.wrapper,width:e,height:n},...d},!r&&co.createElement(KR,null,i),co.createElement("div",{ref:o,style:{...Kv.fullWidth,...!r&&Kv.hide},className:l}))}var YR=XR,VC=L.memo(YR);function JR(e){L.useEffect(e,[])}var GC=JR;function QR(e,n,r=!0){let i=L.useRef(!0);L.useEffect(i.current||!r?()=>{i.current=!1}:e,n)}var Li=QR;function Pm(){}function Dh(e,n,r,i){return ZR(e,i)||eM(e,n,r,i)}function ZR(e,n){return e.editor.getModel(KC(e,n))}function eM(e,n,r,i){return e.editor.createModel(n,r,i?KC(e,i):void 0)}function KC(e,n){return e.Uri.parse(n)}function tM({original:e,modified:n,language:r,originalLanguage:i,modifiedLanguage:o,originalModelPath:l,modifiedModelPath:d,keepCurrentOriginalModel:u=!1,keepCurrentModifiedModel:h=!1,theme:m="light",loading:x="Loading...",options:g={},height:v="100%",width:S="100%",className:E,wrapperProps:j={},beforeMount:y=Pm,onMount:b=Pm}){let[_,C]=L.useState(!1),[N,$]=L.useState(!0),R=L.useRef(null),O=L.useRef(null),I=L.useRef(null),z=L.useRef(b),U=L.useRef(y),W=L.useRef(!1);GC(()=>{let te=f0.init();return te.then(ae=>(O.current=ae)&&$(!1)).catch(ae=>(ae==null?void 0:ae.type)!=="cancelation"&&console.error("Monaco initialization: error:",ae)),()=>R.current?H():te.cancel()}),Li(()=>{if(R.current&&O.current){let te=R.current.getOriginalEditor(),ae=Dh(O.current,e||"",i||r||"text",l||"");ae!==te.getModel()&&te.setModel(ae)}},[l],_),Li(()=>{if(R.current&&O.current){let te=R.current.getModifiedEditor(),ae=Dh(O.current,n||"",o||r||"text",d||"");ae!==te.getModel()&&te.setModel(ae)}},[d],_),Li(()=>{let te=R.current.getModifiedEditor();te.getOption(O.current.editor.EditorOption.readOnly)?te.setValue(n||""):n!==te.getValue()&&(te.executeEdits("",[{range:te.getModel().getFullModelRange(),text:n||"",forceMoveMarkers:!0}]),te.pushUndoStop())},[n],_),Li(()=>{var te,ae;(ae=(te=R.current)==null?void 0:te.getModel())==null||ae.original.setValue(e||"")},[e],_),Li(()=>{let{original:te,modified:ae}=R.current.getModel();O.current.editor.setModelLanguage(te,i||r||"text"),O.current.editor.setModelLanguage(ae,o||r||"text")},[r,i,o],_),Li(()=>{var te;(te=O.current)==null||te.editor.setTheme(m)},[m],_),Li(()=>{var te;(te=R.current)==null||te.updateOptions(g)},[g],_);let Y=L.useCallback(()=>{var oe;if(!O.current)return;U.current(O.current);let te=Dh(O.current,e||"",i||r||"text",l||""),ae=Dh(O.current,n||"",o||r||"text",d||"");(oe=R.current)==null||oe.setModel({original:te,modified:ae})},[r,n,o,e,i,l,d]),V=L.useCallback(()=>{var te;!W.current&&I.current&&(R.current=O.current.editor.createDiffEditor(I.current,{automaticLayout:!0,...g}),Y(),(te=O.current)==null||te.editor.setTheme(m),C(!0),W.current=!0)},[g,m,Y]);L.useEffect(()=>{_&&z.current(R.current,O.current)},[_]),L.useEffect(()=>{!N&&!_&&V()},[N,_,V]);function H(){var ae,oe,ie,X;let te=(ae=R.current)==null?void 0:ae.getModel();u||((oe=te==null?void 0:te.original)==null||oe.dispose()),h||((ie=te==null?void 0:te.modified)==null||ie.dispose()),(X=R.current)==null||X.dispose()}return co.createElement(VC,{width:S,height:v,isEditorReady:_,loading:x,_ref:I,className:E,wrapperProps:j})}var nM=tM;L.memo(nM);function rM(e){let n=L.useRef();return L.useEffect(()=>{n.current=e},[e]),n.current}var sM=rM,kx=new Map;function iM({defaultValue:e,defaultLanguage:n,defaultPath:r,value:i,language:o,path:l,theme:d="light",line:u,loading:h="Loading...",options:m={},overrideServices:x={},saveViewState:g=!0,keepCurrentModel:v=!1,width:S="100%",height:E="100%",className:j,wrapperProps:y={},beforeMount:b=Pm,onMount:_=Pm,onChange:C,onValidate:N=Pm}){let[$,R]=L.useState(!1),[O,I]=L.useState(!0),z=L.useRef(null),U=L.useRef(null),W=L.useRef(null),Y=L.useRef(_),V=L.useRef(b),H=L.useRef(),te=L.useRef(i),ae=sM(l),oe=L.useRef(!1),ie=L.useRef(!1);GC(()=>{let J=f0.init();return J.then(le=>(z.current=le)&&I(!1)).catch(le=>(le==null?void 0:le.type)!=="cancelation"&&console.error("Monaco initialization: error:",le)),()=>U.current?Q():J.cancel()}),Li(()=>{var le,ce,pe,Ae;let J=Dh(z.current,e||i||"",n||o||"",l||r||"");J!==((le=U.current)==null?void 0:le.getModel())&&(g&&kx.set(ae,(ce=U.current)==null?void 0:ce.saveViewState()),(pe=U.current)==null||pe.setModel(J),g&&((Ae=U.current)==null||Ae.restoreViewState(kx.get(l))))},[l],$),Li(()=>{var J;(J=U.current)==null||J.updateOptions(m)},[m],$),Li(()=>{!U.current||i===void 0||(U.current.getOption(z.current.editor.EditorOption.readOnly)?U.current.setValue(i):i!==U.current.getValue()&&(ie.current=!0,U.current.executeEdits("",[{range:U.current.getModel().getFullModelRange(),text:i,forceMoveMarkers:!0}]),U.current.pushUndoStop(),ie.current=!1))},[i],$),Li(()=>{var le,ce;let J=(le=U.current)==null?void 0:le.getModel();J&&o&&((ce=z.current)==null||ce.editor.setModelLanguage(J,o))},[o],$),Li(()=>{var J;u!==void 0&&((J=U.current)==null||J.revealLine(u))},[u],$),Li(()=>{var J;(J=z.current)==null||J.editor.setTheme(d)},[d],$);let X=L.useCallback(()=>{var J;if(!(!W.current||!z.current)&&!oe.current){V.current(z.current);let le=l||r,ce=Dh(z.current,i||e||"",n||o||"",le||"");U.current=(J=z.current)==null?void 0:J.editor.create(W.current,{model:ce,automaticLayout:!0,...m},x),g&&U.current.restoreViewState(kx.get(le)),z.current.editor.setTheme(d),u!==void 0&&U.current.revealLine(u),R(!0),oe.current=!0}},[e,n,r,i,o,l,m,x,g,d,u]);L.useEffect(()=>{$&&Y.current(U.current,z.current)},[$]),L.useEffect(()=>{!O&&!$&&X()},[O,$,X]),te.current=i,L.useEffect(()=>{var J,le;$&&C&&((J=H.current)==null||J.dispose(),H.current=(le=U.current)==null?void 0:le.onDidChangeModelContent(ce=>{ie.current||C(U.current.getValue(),ce)}))},[$,C]),L.useEffect(()=>{if($){let J=z.current.editor.onDidChangeMarkers(le=>{var pe;let ce=(pe=U.current.getModel())==null?void 0:pe.uri;if(ce&&le.find(Ae=>Ae.path===ce.path)){let Ae=z.current.editor.getModelMarkers({resource:ce});N==null||N(Ae)}});return()=>{J==null||J.dispose()}}return()=>{}},[$,N]);function Q(){var J,le;(J=H.current)==null||J.dispose(),v?g&&kx.set(l,U.current.saveViewState()):(le=U.current.getModel())==null||le.dispose(),U.current.dispose()}return co.createElement(VC,{width:S,height:E,isEditorReady:$,loading:h,_ref:W,className:j,wrapperProps:y})}var oM=iM,aM=L.memo(oM),p0=aM;function kc({value:e,onChange:n,path:r,readOnly:i}){return s.jsx(p0,{path:`file://${r}`,defaultLanguage:"markdown",value:e,onChange:o=>n(o??""),theme:"vs-dark",options:{minimap:{enabled:!1},fontSize:13,fontFamily:"JetBrains Mono, ui-monospace, Menlo, monospace",lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,wordWrap:"on",readOnly:i,automaticLayout:!0}})}function ky(e){e<0&&(e=0);const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const r=Math.floor(n/60);return r<60?`${r}m${(n%60).toString().padStart(2,"0")}s`:`${Math.floor(r/60)}h${(r%60).toString().padStart(2,"0")}m`}function Uo(e){e<0&&(e=0);const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const r=Math.floor(n/60);if(r<60)return`${r}m`;const i=Math.floor(r/60);return i<24?`${i}h${r%60?` ${r%60}m`:""}`:`${Math.floor(i/24)}d`}function Wh(e){return new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",timeZoneName:"short"})}function Yh(e,n){if(e===null)return"never";const r=n-e;return r<0?"soon":r<5e3?"just now":`${Uo(r)} ago`}function lM(e){if(!e)return"";const n=Math.max(0,Date.now()-e);return n<6e4?`saved ${Math.round(n/1e3)}s ago`:n<36e5?`saved ${Math.round(n/6e4)}m ago`:`saved ${Math.round(n/36e5)}h ago`}function Fm(e){if(!e)return"";const n=Date.now()-e;return n<5e3?"just now":`${Uo(n)} ago`}function XC(e){const n=Math.max(0,Math.floor(e/1e3));return`${Math.floor(n/60)}:${(n%60).toString().padStart(2,"0")}`}function Um(e){e<0&&(e=0);const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const r=Math.floor(n/60);if(r<60)return`${r}m`;const i=Math.floor(r/60),o=r%60;return o>0?`${i}h ${o}m`:`${i}h`}function Uu({dirty:e,busy:n,parseError:r,lastSavedAt:i,onSave:o,onRevert:l,leading:d}){const u=e&&!n&&!r;return s.jsxs("div",{className:"px-3 py-1.5 flex items-center gap-2 text-xs",children:[s.jsx("div",{className:"flex-1 min-w-0 truncate text-fg-faint",children:d}),r&&s.jsx("span",{className:"text-red-400 truncate max-w-xs",title:r,children:r}),!e&&!r&&i&&s.jsx("span",{className:"text-fg-faint",children:lM(i)}),e&&!r&&s.jsx("span",{className:"text-accent",children:"unsaved"}),s.jsx("button",{onClick:l,disabled:!e||n,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed",children:"Revert"}),s.jsx("button",{onClick:o,disabled:!u,className:`px-2.5 py-0.5 rounded border ${u?"border-accent bg-accent/15 text-accent hover:bg-accent/25":"border-line text-fg-faint opacity-50 cursor-not-allowed"}`,children:n?"Saving…":"Save"})]})}function Mu(...e){return e.filter(Boolean).map((n,r)=>r===0?n.replace(/\/+$/,""):n.replace(/^\/+|\/+$/g,"")).join("/")}const Sy={scopes:["user","project","local"],resolve:(e,n,r)=>e==="user"?Mu(n,".claude","settings.json"):r?e==="project"?Mu(r,".claude","settings.json"):Mu(r,".claude","settings.local.json"):null},Xv={scopes:["user","project","local"],resolve:(e,n,r)=>e==="user"?Mu(n,".claude","CLAUDE.md"):r?e==="project"?Mu(r,"CLAUDE.md"):Mu(r,"CLAUDE.local.md"):null},B1=Sy,cM={scopes:["user"],resolve:(e,n)=>e==="user"?Mu(n,".claude","keybindings.json"):null},os={user:{label:"User",hint:"~/.claude/ — applies to all projects"},project:{label:"Project",hint:"<cwd>/.claude/ — checked into git"},local:{label:"Local",hint:"<cwd>/.claude/…local — gitignored, per-machine"}};function ka({scopes:e,active:n,onChange:r,annotate:i}){return s.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:e.map(o=>{const l=os[o],d=i==null?void 0:i(o),u=o===n;return s.jsxs("button",{title:l.hint,onClick:()=>r(o),className:`px-2.5 py-1 text-xs flex items-center gap-1.5 transition-colors ${u?"bg-bg-hi text-fg":"bg-bg-elev text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:[s.jsx("span",{children:l.label}),(d==null?void 0:d.dirty)&&s.jsx("span",{className:"w-1 h-1 rounded-full bg-accent",title:"unsaved edits"}),d&&d.exists===!1&&!d.dirty&&s.jsx("span",{className:"w-1 h-1 rounded-full bg-fg-faint",title:"not yet created"})]},o)})})}function Cy({checked:e,onChange:n,label:r,disabled:i}){return s.jsxs("label",{className:`inline-flex items-center gap-2 text-xs ${i?"opacity-50 cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("button",{type:"button",role:"switch","aria-checked":e,disabled:i,onClick:()=>!i&&n(!e),className:`relative w-7 h-4 rounded-full transition-colors ${e?"bg-accent":"bg-bg-hi border border-line"}`,children:s.jsx("span",{className:`absolute top-0.5 w-3 h-3 rounded-full bg-fg transition-transform ${e?"translate-x-3.5":"translate-x-0.5"}`})}),r&&s.jsx("span",{className:"text-fg-dim",children:r})]})}const F1=e=>`${e}/.claude/session-manager/provenance.json`;function uM(e){if(!e||typeof e!="object")return{};const n={};for(const[r,i]of Object.entries(e))(i==="anthropic"||i==="community"||i==="local")&&(n[r]=i);return n}const dM=cr((e,n)=>({overrides:{},loaded:!1,loading:!1,home:null,load:async r=>{const i=n();if(!(i.home===r&&(i.loaded||i.loading))){e({home:r,loading:!0});try{const o=await window.api.config.readJson(F1(r)),l=o.exists?uM(o.data):{};e(d=>({overrides:{...l,...d.overrides},loaded:!0,loading:!1}))}catch{e({loaded:!0,loading:!1})}}},setOverride:async(r,i)=>{const o={...n().overrides};i===null?delete o[r]:o[r]=i,e({overrides:o});const l=n().home;if(l)try{await window.api.config.writeJson(F1(l),o)}catch{}}})),YC={default:"bg-bg-hi text-fg-dim border-line",accent:"bg-accent/15 text-accent-dark border-accent/30",warn:"bg-honey/15 text-honey-dark border-honey/30",dim:"bg-bg-elev text-fg-dim border-line",good:"bg-sage/15 text-sage-dark border-sage/30"};function lr({children:e,tone:n="default",className:r="",title:i}){return s.jsx("span",{title:i,className:`inline-flex items-center gap-1 text-[10px] leading-none px-1.5 py-0.5 rounded border uppercase tracking-wide ${YC[n]} ${r}`,children:e})}const cw=[{id:"filesystem",name:"Filesystem",description:"Secure file operations with configurable access controls",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem",config:{command:"npx",args:["-y","@modelcontextprotocol/server-filesystem","<path>"]},envVars:[]},{id:"fetch",name:"Fetch",description:"Web content fetching and conversion for efficient LLM usage",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/fetch",config:{command:"uvx",args:["mcp-server-fetch"]},envVars:[]},{id:"memory",name:"Memory",description:"Knowledge graph-based persistent memory system",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/memory",config:{command:"npx",args:["-y","@modelcontextprotocol/server-memory"]},envVars:[]},{id:"sequential-thinking",name:"Sequential Thinking",description:"Dynamic and reflective problem-solving through thought sequences",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking",config:{command:"npx",args:["-y","@modelcontextprotocol/server-sequential-thinking"]},envVars:[]},{id:"git",name:"Git",description:"Tools to read, search, and manipulate Git repositories",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/git",config:{command:"uvx",args:["mcp-server-git","--repository","<path>"]},envVars:[]},{id:"time",name:"Time",description:"Time and timezone conversion capabilities",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/time",config:{command:"uvx",args:["mcp-server-time"]},envVars:[]},{id:"everything",name:"Everything",description:"Reference/test server with prompts, resources, and tools",official:!0,homepage:"https://github.com/modelcontextprotocol/servers/tree/main/src/everything",config:{command:"npx",args:["-y","@modelcontextprotocol/server-everything"]},envVars:[]},{id:"github",name:"GitHub",description:"Official GitHub repository, issues, and PR management",official:!1,homepage:"https://github.com/github/github-mcp-server",config:{command:"docker",args:["run","-i","--rm","-e","GITHUB_PERSONAL_ACCESS_TOKEN","ghcr.io/github/github-mcp-server"]},envVars:["GITHUB_PERSONAL_ACCESS_TOKEN"]},{id:"gitlab",name:"GitLab",description:"GitLab API integration for projects, issues, and merge requests",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/gitlab",config:{command:"npx",args:["-y","@modelcontextprotocol/server-gitlab"]},envVars:["GITLAB_PERSONAL_ACCESS_TOKEN","GITLAB_API_URL"]},{id:"postgres",name:"PostgreSQL",description:"Read-only database access with schema inspection",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres",config:{command:"npx",args:["-y","@modelcontextprotocol/server-postgres","<connection-string>"]},envVars:[]},{id:"sqlite",name:"SQLite",description:"Database interaction and business intelligence over SQLite",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/sqlite",config:{command:"uvx",args:["mcp-server-sqlite","--db-path","<path>"]},envVars:[]},{id:"slack",name:"Slack",description:"Channel management and messaging for Slack workspaces",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/slack",config:{command:"npx",args:["-y","@modelcontextprotocol/server-slack"]},envVars:["SLACK_BOT_TOKEN","SLACK_TEAM_ID"]},{id:"google-drive",name:"Google Drive",description:"File access and search for Google Drive",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/gdrive",config:{command:"npx",args:["-y","@modelcontextprotocol/server-gdrive"]},envVars:["GDRIVE_CREDENTIALS_PATH"]},{id:"google-maps",name:"Google Maps",description:"Location services, directions, and place details",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/google-maps",config:{command:"npx",args:["-y","@modelcontextprotocol/server-google-maps"]},envVars:["GOOGLE_MAPS_API_KEY"]},{id:"puppeteer",name:"Puppeteer",description:"Browser automation and web scraping via Puppeteer",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/puppeteer",config:{command:"npx",args:["-y","@modelcontextprotocol/server-puppeteer"]},envVars:[]},{id:"playwright",name:"Playwright",description:"Cross-browser automation for navigation, screenshots, and data extraction",official:!1,homepage:"https://github.com/microsoft/playwright-mcp",config:{command:"npx",args:["-y","@playwright/mcp@latest"]},envVars:[]},{id:"brave-search",name:"Brave Search",description:"Web and local search using the Brave Search API",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/brave-search",config:{command:"npx",args:["-y","@modelcontextprotocol/server-brave-search"]},envVars:["BRAVE_API_KEY"]},{id:"redis",name:"Redis",description:"Interact with Redis key-value stores",official:!1,homepage:"https://github.com/modelcontextprotocol/servers-archived/tree/main/src/redis",config:{command:"npx",args:["-y","@modelcontextprotocol/server-redis","<redis-url>"]},envVars:[]},{id:"sentry",name:"Sentry",description:"Retrieve and analyze Sentry error tracking issues",official:!1,homepage:"https://github.com/getsentry/sentry-mcp",config:{command:"npx",args:["-y","@sentry/mcp-server@latest"]},envVars:["SENTRY_AUTH_TOKEN"]},{id:"linear",name:"Linear",description:"Issue tracking and project management for Linear",official:!1,homepage:"https://linear.app/docs/mcp",config:{command:"npx",args:["-y","mcp-remote","https://mcp.linear.app/sse"]},envVars:[]},{id:"notion",name:"Notion",description:"Notion workspace page and database management",official:!1,homepage:"https://github.com/makenotion/notion-mcp-server",config:{command:"npx",args:["-y","@notionhq/notion-mcp-server"]},envVars:["NOTION_API_KEY"]},{id:"stripe",name:"Stripe",description:"Payment processing, customers, and invoices via Stripe API",official:!1,homepage:"https://github.com/stripe/agent-toolkit",config:{command:"npx",args:["-y","@stripe/mcp","--tools=all"]},envVars:["STRIPE_SECRET_KEY"]},{id:"cloudflare",name:"Cloudflare",description:"Manage Cloudflare Workers, KV, R2, D1, and Workers AI",official:!1,homepage:"https://github.com/cloudflare/mcp-server-cloudflare",config:{command:"npx",args:["-y","mcp-remote","https://observability.mcp.cloudflare.com/sse"]},envVars:[]},{id:"context7",name:"Context7",description:"Up-to-date version-specific library docs injected into prompts",official:!1,homepage:"https://github.com/upstash/context7",config:{command:"npx",args:["-y","@upstash/context7-mcp@latest"]},envVars:[]},{id:"tavily",name:"Tavily",description:"AI-optimized web search with clean structured results",official:!1,homepage:"https://github.com/tavily-ai/tavily-mcp",config:{command:"npx",args:["-y","tavily-mcp@latest"]},envVars:["TAVILY_API_KEY"]},{id:"perplexity",name:"Perplexity",description:"Answer-engine search with deep research and reasoning",official:!1,homepage:"https://github.com/ppl-ai/modelcontextprotocol",config:{command:"npx",args:["-y","server-perplexity-ask"]},envVars:["PERPLEXITY_API_KEY"]},{id:"figma",name:"Figma Dev Mode",description:"First-party Figma design-to-code bridge exposing node tree",official:!1,homepage:"https://help.figma.com/hc/en-us/articles/32132100833559",config:{url:"http://127.0.0.1:3845/sse"},envVars:[]},{id:"supabase",name:"Supabase",description:"Manage Supabase projects, tables, and SQL queries",official:!1,homepage:"https://github.com/supabase-community/supabase-mcp",config:{command:"npx",args:["-y","@supabase/mcp-server-supabase@latest"]},envVars:["SUPABASE_ACCESS_TOKEN"]},{id:"atlassian",name:"Atlassian (Jira/Confluence)",description:"Official Jira and Confluence integration",official:!1,homepage:"https://www.atlassian.com/platform/remote-mcp-server",config:{command:"npx",args:["-y","mcp-remote","https://mcp.atlassian.com/v1/sse"]},envVars:[]},{id:"aws",name:"AWS",description:"AWS services access and best-practice guidance",official:!1,homepage:"https://github.com/awslabs/mcp",config:{command:"uvx",args:["awslabs.core-mcp-server@latest"]},envVars:["AWS_PROFILE","AWS_REGION"]},{id:"obsidian",name:"Obsidian",description:"Read and search notes in an Obsidian vault",official:!1,homepage:"https://github.com/MarkusPfundstein/mcp-obsidian",config:{command:"uvx",args:["mcp-obsidian"]},envVars:["OBSIDIAN_API_KEY"]}],jy=[{id:"pdf",name:"PDF",description:"Create, edit, and extract content from PDF documents",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/pdf"},{id:"docx",name:"DOCX",description:"Create and edit Microsoft Word documents",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/docx"},{id:"xlsx",name:"XLSX",description:"Create and edit Excel spreadsheets with formulas and formatting",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/xlsx"},{id:"pptx",name:"PPTX",description:"Create and edit PowerPoint presentations",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/pptx"},{id:"webapp-testing",name:"Webapp Testing",description:"Test web applications using Playwright-driven browser automation",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/webapp-testing"},{id:"playwright-e2e",name:"Playwright E2E",description:"End-to-end browser tests — navigation, forms, assertions, waiting strategies",official:!1,source:"local"},{id:"playwright-visual-testing",name:"Playwright Visual Testing",description:"Visual regression testing — screenshot comparison, pixel diffs, responsive layouts",official:!1,source:"local"},{id:"playwright-accessibility",name:"Playwright Accessibility",description:"Accessibility testing — WCAG compliance, axe-core scans, keyboard navigation",official:!1,source:"local"},{id:"playwright-api-testing",name:"Playwright API Testing",description:"API testing with Playwright request context — REST endpoints, auth flows, contracts",official:!1,source:"local"},{id:"playwright-debug",name:"Playwright Debug",description:"Debug failing tests — trace viewer, inspector, headed mode, flaky test fixes",official:!1,source:"local"},{id:"web-artifacts-builder",name:"Web Artifacts Builder",description:"Build polished interactive web artifacts and demos",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/web-artifacts-builder"},{id:"frontend-design",name:"Frontend Design",description:"Apply frontend UI/UX design patterns and visual polish",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/frontend-design"},{id:"canvas-design",name:"Canvas Design",description:"Canvas-based graphic design and composition techniques",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/canvas-design"},{id:"algorithmic-art",name:"Algorithmic Art",description:"Create generative and algorithmic art",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/algorithmic-art"},{id:"brand-guidelines",name:"Brand Guidelines",description:"Apply brand identity and style guideline specifications",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/brand-guidelines"},{id:"theme-factory",name:"Theme Factory",description:"Generate and customize visual themes",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/theme-factory"},{id:"slack-gif-creator",name:"Slack GIF Creator",description:"Create animated GIFs suitable for Slack",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/slack-gif-creator"},{id:"doc-coauthoring",name:"Doc Coauthoring",description:"Collaborative document authoring and editing workflows",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/doc-coauthoring"},{id:"internal-comms",name:"Internal Comms",description:"Internal communications templates and drafting",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/internal-comms"},{id:"claude-api",name:"Claude API",description:"Build apps with the Claude API and Anthropic SDKs",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/claude-api"},{id:"mcp-builder",name:"MCP Builder",description:"Scaffold and build new Model Context Protocol servers",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/mcp-builder"},{id:"skill-creator",name:"Skill Creator",description:"Scaffold and create new Claude Code skills",official:!0,source:"https://github.com/anthropics/skills/tree/main/skills/skill-creator"}],Ey=[{id:"session-manager-dev",name:"Session Manager Dev",description:"Default end-to-end dev skillset: /develop + /prd (decompose → scheduler PRDs), /process-feedback + /my-feedback (cross-project intake), /project-status + /optimize-kpi + /local-project-health (status & KPI loop), /requesting-code-review + /security-review (review gate), /explain-to-me (HUMAN_LEARN docs).",official:!1,source:"https://github.com/StanislavBG/claude-code-session-manager/tree/main/plugins/session-manager-dev",bundles:["skills"],marketplace:{add:"bundled",name:"session-manager"}},{id:"code-review",name:"Code Review",description:"Comprehensive code review with best practices and improvement suggestions",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/code-review",bundles:["commands","agents"]},{id:"pr-review-toolkit",name:"PR Review Toolkit",description:"Pull request review automation and workflows",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/pr-review-toolkit",bundles:["commands","agents"]},{id:"commit-commands",name:"Commit Commands",description:"Git commit workflow shortcuts with conventional commit formatting",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/commit-commands",bundles:["commands"]},{id:"feature-dev",name:"Feature Dev",description:"Feature development assistance from spec to implementation",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/feature-dev",bundles:["commands","agents"]},{id:"security-guidance",name:"Security Guidance",description:"Security best-practice review and enforcement",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/security-guidance",bundles:["commands","agents"]},{id:"agent-sdk-dev",name:"Agent SDK Dev",description:"Development tools for building with the Claude Agent SDK",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/agent-sdk-dev",bundles:["commands","skills"]},{id:"plugin-dev",name:"Plugin Dev",description:"Scaffolding and tooling for authoring Claude Code plugins",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/plugin-dev",bundles:["commands","skills"]},{id:"mcp-server-dev",name:"MCP Server Dev",description:"Develop and test Model Context Protocol servers",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/mcp-server-dev",bundles:["commands","skills"]},{id:"skill-creator",name:"Skill Creator",description:"Framework for creating and iterating on new skills",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/skill-creator",bundles:["commands","skills"]},{id:"claude-md-management",name:"CLAUDE.md Management",description:"Manage and maintain CLAUDE.md project memory files",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/claude-md-management",bundles:["commands"]},{id:"typescript-lsp",name:"TypeScript LSP",description:"TypeScript/JavaScript language server integration",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/typescript-lsp",bundles:["hooks","commands"]},{id:"pyright-lsp",name:"Pyright LSP",description:"Python language server integration via Pyright",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/pyright-lsp",bundles:["hooks","commands"]},{id:"rust-analyzer-lsp",name:"Rust Analyzer LSP",description:"Rust language server integration via rust-analyzer",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/rust-analyzer-lsp",bundles:["hooks","commands"]},{id:"gopls-lsp",name:"Go LSP (gopls)",description:"Go language server integration via gopls",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/gopls-lsp",bundles:["hooks","commands"]},{id:"code-simplifier",name:"Code Simplifier",description:"Review changed code for reuse, quality, and efficiency then fix issues",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/code-simplifier",bundles:["commands","agents"]},{id:"hookify",name:"Hookify",description:"Utilities and templates for authoring Claude Code hooks",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/hookify",bundles:["commands","skills"]},{id:"frontend-design-plugin",name:"Frontend Design Plugin",description:"Frontend design assistance and visual polish workflows",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/frontend-design",bundles:["commands","skills","agents"]},{id:"clangd-lsp",name:"clangd-lsp",description:"C/C++ diagnostics via clangd. Requires clangd on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/clangd-lsp",bundles:["hooks","commands"]},{id:"csharp-lsp",name:"csharp-lsp",description:"C# diagnostics. Requires OmniSharp or Roslyn LSP on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/csharp-lsp",bundles:["hooks","commands"]},{id:"jdtls-lsp",name:"jdtls-lsp",description:"Java diagnostics via Eclipse JDT LS. Requires jdtls on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/jdtls-lsp",bundles:["hooks","commands"]},{id:"kotlin-lsp",name:"kotlin-lsp",description:"Kotlin diagnostics. Requires kotlin-language-server on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/kotlin-lsp",bundles:["hooks","commands"]},{id:"lua-lsp",name:"lua-lsp",description:"Lua diagnostics. Requires lua-language-server on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/lua-lsp",bundles:["hooks","commands"]},{id:"php-lsp",name:"php-lsp",description:"PHP diagnostics. Requires intelephense or phpactor on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/php-lsp",bundles:["hooks","commands"]},{id:"swift-lsp",name:"swift-lsp",description:"Swift diagnostics via sourcekit-lsp. Requires sourcekit-lsp on $PATH.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/swift-lsp",bundles:["hooks","commands"]},{id:"github",name:"github",description:"GitHub PRs, issues, gh-style flows.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/github",bundles:["mcp"]},{id:"gitlab",name:"gitlab",description:"GitLab MRs, issues, pipelines.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/gitlab",bundles:["mcp"]},{id:"atlassian",name:"atlassian",description:"Jira / Confluence search and updates.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/atlassian",bundles:["mcp"]},{id:"asana",name:"asana",description:"Asana task and project ops.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/asana",bundles:["mcp"]},{id:"linear",name:"linear",description:"Linear issue tracking — pairs with the Tasks tab.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/linear",bundles:["mcp"]},{id:"notion",name:"notion",description:"Notion document lookup and edits.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/notion",bundles:["mcp"]},{id:"figma",name:"figma",description:"Figma file inspection for UI work.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/figma",bundles:["mcp"]},{id:"vercel",name:"vercel",description:"Vercel deploy diagnostics.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/vercel",bundles:["mcp"]},{id:"firebase",name:"firebase",description:"Firebase project + Firestore ops.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/firebase",bundles:["mcp"]},{id:"supabase",name:"supabase",description:"Supabase database operations.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/supabase",bundles:["mcp"]},{id:"slack",name:"slack",description:"Slack DM / channel posting from agents.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/slack",bundles:["mcp"]},{id:"sentry",name:"sentry",description:"Sentry bug triage and event lookup.",official:!0,source:"https://github.com/anthropics/claude-plugins-official/tree/main/plugins/sentry",bundles:["mcp"]}],Ny=[{id:"prettier-on-write",name:"Prettier on Write",description:"Auto-format JS/TS/JSON/MD files after edit via prettier",event:"PostToolUse",matcher:"Write|Edit",command:"jq -r '.tool_input.file_path // empty' | grep -E '\\.(js|jsx|ts|tsx|json|md|css|html|yaml|yml)$' | xargs -r -I{} npx --no-install prettier --write {} 2>/dev/null || true"},{id:"black-on-write",name:"Black on Write (Python)",description:"Auto-format Python files after edit via black",event:"PostToolUse",matcher:"Write|Edit",command:"jq -r '.tool_input.file_path // empty' | grep -E '\\.py$' | xargs -r black -q 2>/dev/null || true"},{id:"rustfmt-on-write",name:"rustfmt on Write",description:"Auto-format Rust files after edit via rustfmt",event:"PostToolUse",matcher:"Write|Edit",command:"jq -r '.tool_input.file_path // empty' | grep -E '\\.rs$' | xargs -r rustfmt 2>/dev/null || true"},{id:"gofmt-on-write",name:"gofmt on Write",description:"Auto-format Go files after edit via gofmt",event:"PostToolUse",matcher:"Write|Edit",command:"jq -r '.tool_input.file_path // empty' | grep -E '\\.go$' | xargs -r gofmt -w 2>/dev/null || true"},{id:"block-secret-writes",name:"Block Writes to Secrets",description:"Deny edits to .env, credentials, key files",event:"PreToolUse",matcher:"Write|Edit",command:`path=$(jq -r '.tool_input.file_path // empty'); echo "$path" | grep -qE '(^|/)(\\.env|\\.env\\..+|id_rsa|id_ed25519|.*\\.pem|.*\\.key|credentials\\.json|\\.aws/credentials)$' && { echo '{"decision":"block","reason":"refusing to edit secret file"}'; exit 2; } || true`},{id:"notify-on-stop",name:"Desktop Notify on Stop",description:"Send a desktop notification when Claude finishes a turn",event:"Stop",command:`command -v notify-send >/dev/null && notify-send "Claude Code" "Session ready" || (command -v osascript >/dev/null && osascript -e 'display notification "Session ready" with title "Claude Code"') || true`},{id:"bell-on-notification",name:"Terminal Bell on Notification",description:"Ring the terminal bell on permission prompts / idle notifications",event:"Notification",command:"printf '\\a'"},{id:"log-tool-calls",name:"Log Tool Calls (JSONL)",description:"Append every tool call to ~/.claude/logs/tool-calls.jsonl for audit",event:"PreToolUse",command:"mkdir -p ~/.claude/logs && cat >> ~/.claude/logs/tool-calls.jsonl"},{id:"auto-stage-edits",name:"Auto-stage Edited Files",description:"git add each file Claude edits (inside a repo)",event:"PostToolUse",matcher:"Write|Edit",command:`path=$(jq -r '.tool_input.file_path // empty'); [ -n "$path" ] && git -C "$(dirname "$path")" add "$path" 2>/dev/null || true`},{id:"block-dangerous-bash",name:"Block Dangerous Bash",description:"Refuse rm -rf /, fork bombs, curl|sh pipes",event:"PreToolUse",matcher:"Bash",command:`cmd=$(jq -r '.tool_input.command // empty'); echo "$cmd" | grep -qE '(rm -rf /|:\\(\\)\\{.*\\};|curl.*\\|\\s*(bash|sh)|wget.*\\|\\s*(bash|sh)|mkfs\\.|dd if=.*of=/dev/)' && { echo '{"decision":"block","reason":"dangerous command pattern"}'; exit 2; } || true`},{id:"prepend-cwd-to-prompt",name:"Prepend CWD to Prompt",description:"Add cwd context to every user prompt automatically",event:"UserPromptSubmit",command:'echo "{\\"additionalContext\\":\\"cwd: $(pwd)\\"}"'},{id:"archive-transcript",name:"Archive Transcript on SessionEnd",description:"Copy the session jsonl to ~/.claude/archive/ when done",event:"SessionEnd",command:`src=$(jq -r '.transcript_path // empty'); [ -n "$src" ] && mkdir -p ~/.claude/archive && cp "$src" ~/.claude/archive/ 2>/dev/null || true`}],no=(e,n,r,i)=>`---
|
|
2983
2983
|
name: ${e}
|
|
2984
2984
|
description: ${n}
|
|
2985
2985
|
tools: ${r}
|
|
@@ -2992,7 +2992,7 @@ ${i}
|
|
|
2992
2992
|
- maintainability issues (naming, duplication, abstractions)
|
|
2993
2993
|
- style / convention deviations vs the rest of the repo
|
|
2994
2994
|
|
|
2995
|
-
Be specific: cite file:line. Distinguish blocking issues from nits. Do not rewrite — just review.`)},{id:"test-runner",name:"Test Runner",description:"Run the project test suite, report failures, suggest fixes",tools:"Bash, Read, Grep",content:no("test-runner","Run the project test suite, report failures, suggest fixes","Bash, Read, Grep","Detect the test framework (jest, vitest, pytest, cargo test, go test, …) from package manifests. Run the suite. For each failure: read the failing test + the code under test, diagnose the cause, and propose a concrete fix. Do not apply fixes yourself.")},{id:"security-auditor",name:"Security Auditor",description:"Scan code for common vulnerabilities and unsafe patterns",tools:"Read, Grep, Glob, Bash",content:no("security-auditor","Scan code for common vulnerabilities and unsafe patterns","Read, Grep, Glob, Bash","Audit the codebase for OWASP top-10 and common CWE patterns: SQL injection, XSS, SSRF, path traversal, hardcoded secrets, weak crypto, insecure deserialization, missing authz. Report findings with severity, file:line, and remediation sketch.")},{id:"docs-writer",name:"Docs Writer",description:"Generate or update docstrings and README sections",tools:"Read, Edit, Grep, Glob",content:no("docs-writer","Generate or update docstrings and README sections","Read, Edit, Grep, Glob","For each public symbol missing documentation, write a concise doc comment in the project's existing style. For README sections, match the existing tone. Never invent APIs — read the code first.")},{id:"refactorer",name:"Refactorer",description:"Propose structural refactors without changing behavior",tools:"Read, Grep, Glob, Edit",content:no("refactorer","Propose structural refactors without changing behavior","Read, Grep, Glob, Edit","Identify extract-method, extract-class, inline, rename, and dead-code opportunities. Prefer small reversible refactors. Always preserve behavior — no feature changes.")},{id:"debugger",name:"Debugger",description:"Diagnose a failing test or runtime error from a stack trace",tools:"Read, Grep, Glob, Bash",content:no("debugger","Diagnose a failing test or runtime error from a stack trace","Read, Grep, Glob, Bash","Given a stack trace or failing test, walk the call chain, read the relevant code, form a hypothesis, and propose a minimal fix. Reproduce the bug before fixing when possible.")},{id:"commit-msg-writer",name:"Commit Message Writer",description:"Write a conventional commit message from staged changes",tools:"Bash, Read",content:no("commit-msg-writer","Write a conventional commit message from staged changes","Bash, Read","Run `git diff --staged`, summarize the change, and produce a conventional-commit message: `<type>(<scope>): <subject>`. Types: feat, fix, refactor, docs, test, chore, perf. Subject ≤72 chars, imperative, lowercase.")},{id:"perf-profiler",name:"Performance Profiler",description:"Identify hot paths and perf regressions in changed code",tools:"Read, Grep, Glob, Bash",content:no("perf-profiler","Identify hot paths and perf regressions in changed code","Read, Grep, Glob, Bash","Look for accidental N+1 loops, quadratic scans, sync IO in hot loops, and unbounded allocations. Rank findings by likely impact; cite file:line. Do not micro-optimize without evidence.")},{id:"sql-reviewer",name:"SQL Reviewer",description:"Review SQL/ORM queries for correctness and performance",tools:"Read, Grep, Glob",content:no("sql-reviewer","Review SQL/ORM queries for correctness and performance","Read, Grep, Glob","Inspect SQL and ORM queries for missing indexes, SELECT *, N+1, cartesian joins, SQL injection risk, and transaction boundaries. Report severity + remediation.")},{id:"api-designer",name:"API Designer",description:"Review REST/GraphQL API design for consistency and correctness",tools:"Read, Grep, Glob",content:no("api-designer","Review REST/GraphQL API design for consistency and correctness","Read, Grep, Glob","Audit route naming, HTTP verb usage, status codes, pagination, auth, error envelopes, and versioning. Flag inconsistencies against the rest of the surface.")},{id:"migration-planner",name:"Migration Planner",description:"Draft a safe DB migration + rollback plan for a schema change",tools:"Read, Grep, Glob, Bash",content:no("migration-planner","Draft a safe DB migration + rollback plan for a schema change","Read, Grep, Glob, Bash","For the requested schema change, produce forward + rollback migrations, a backfill strategy for large tables, and a deploy sequence that keeps the old code running through the transition.")},{id:"dependency-auditor",name:"Dependency Auditor",description:"Audit dependencies for vulnerabilities and stale versions",tools:"Bash, Read",content:no("dependency-auditor","Audit dependencies for vulnerabilities and stale versions","Bash, Read","Run the ecosystem audit (npm audit, pip-audit, cargo audit, etc.) and read the lockfile. Rank CVEs by severity + reachability. Suggest upgrades with known-compatible versions.")}],U1=[{id:"strict",name:"Strict",description:"Deny all network + dangerous bash; ask before edits; no auto-accept",permissions:{deny:["Bash(curl:*)","Bash(wget:*)","Bash(nc:*)","Bash(ssh:*)","Bash(rm -rf:*)","Bash(sudo:*)","WebFetch","WebSearch"],ask:["Edit","Write","Bash"],defaultMode:"default"}},{id:"standard-dev",name:"Standard Dev",description:"Allow common dev commands (git, npm, pnpm, cargo, go, make); deny destructive ops",permissions:{allow:["Bash(git:*)","Bash(npm:*)","Bash(pnpm:*)","Bash(yarn:*)","Bash(cargo:*)","Bash(go:*)","Bash(make:*)","Bash(ls:*)","Bash(pwd)","Bash(cat:*)","Bash(grep:*)","Bash(rg:*)","Bash(find:*)","Read","Glob","Grep"],deny:["Bash(rm -rf /:*)","Bash(sudo:*)","Bash(shutdown:*)","Bash(reboot:*)","Bash(dd:*)"],defaultMode:"acceptEdits"}},{id:"sandboxed",name:"Sandboxed",description:"Block writes outside cwd; allow reads everywhere; deny network and sudo",permissions:{deny:["Bash(sudo:*)","Bash(curl:*)","Bash(wget:*)","WebFetch","WebSearch"],ask:["Write","Edit"],defaultMode:"default",additionalDirectories:[]}},{id:"read-only",name:"Read-only",description:"Research / analysis only — no edits, no bash, no writes",permissions:{allow:["Read","Glob","Grep","WebFetch","WebSearch"],deny:["Write","Edit","Bash","NotebookEdit"],defaultMode:"default"}},{id:"plan-mode",name:"Plan Mode",description:"Force plan-mode by default; ask before any mutation",permissions:{ask:["Write","Edit","Bash","NotebookEdit"],defaultMode:"plan"}}],ju=[{id:"local-time",name:"Local time (Pacific)",description:"Always state times in the user's local timezone (America/Los_Angeles)",category:"communication",section:"Time and timezone",bullets:["When stating any time, date, or deadline, use the user's local timezone: America/Los_Angeles (Pacific Time, PST/PDT depending on DST).","Never use UTC, server time, or your own assumed timezone in user-facing replies. Convert if necessary.",'When showing a time, include the zone abbreviation (e.g., "3:15 PM PDT") so it is unambiguous.',`For relative phrasing ("tomorrow", "in 2 hours"), anchor to the user's local clock, not UTC.`],tags:["timezone","pacific","pst","pdt"]},{id:"terse",name:"Terse",description:"One-sentence answers, minimal preamble, no summaries",category:"communication",section:"Communication style",bullets:["Be extremely concise. Lead with the answer or the diff.","No preamble, no trailing summaries, no recap of what you just did.","If the answer fits in one sentence, use one sentence. Skip pleasantries."],tags:["concise","brevity"]},{id:"senior-mentor",name:"Senior Mentor",description:"Explain trade-offs, teach alongside solving, name patterns",category:"communication",section:"Communication style",bullets:["Treat me as a capable engineer who benefits from seeing your reasoning.","When you make a design choice, name the trade-off explicitly.","When you use a pattern, name it. Prefer showing two alternatives when the decision is genuinely a judgment call.","Teach, don't lecture."],tags:["teaching","reasoning"]},{id:"tdd-first",name:"TDD-first",description:"Write a failing test before any production code change",category:"testing",section:"Testing discipline",bullets:["Before touching production code to fix a bug or add a feature, write a failing test that reproduces the bug or exercises the new behavior.","Run it to confirm it fails. Only then implement. Only then re-run the test.","This discipline is non-negotiable for non-trivial changes."],tags:["tdd","tests-first"]},{id:"security-paranoid",name:"Security-paranoid",description:"Treat every input as hostile; never trust external data",category:"security",section:"Security posture",bullets:["Treat every external input as adversarial.","Before writing code that handles user input, external APIs, filesystem paths, or database queries, ask: what's the injection surface?","Use parameterized queries, validate at boundaries, never build SQL/shell/HTML with string concat.","Secrets never touch logs or git. When in doubt, ask."],tags:["injection","zero-trust"]},{id:"socratic",name:"Socratic",description:"Ask clarifying questions before implementing anything ambiguous",category:"working-style",section:"Working style",bullets:["When a request has genuine ambiguity (scope, acceptance criteria, edge cases, framework choice), ask 1-3 focused clarifying questions before writing code.","Don't ask for confirmation of the obvious — just for decisions that would cost real time to redo."],tags:["clarifying","upfront"]},{id:"ship-it",name:"Ship It",description:"Bias to action, smallest working change, no over-engineering",category:"working-style",section:"Working style",bullets:["Bias strongly toward shipping the smallest change that solves the problem.","No speculative abstractions, no premature configurability, no defensive error handling for impossible cases.","Three similar lines beat a premature abstraction. When the task is done, stop."],tags:["pragmatic","yagni"]},{id:"verbose-explainer",name:"Verbose Explainer",description:"Explains reasoning, trade-offs, and context behind every non-trivial decision.",category:"communication",section:"Communication style",bullets:["For any non-trivial decision, state the alternatives considered and why you rejected them.","After writing code, summarize what changed and why in 2-4 sentences.","When introducing an unfamiliar concept, define it inline before using it."],tags:["verbose","explain","reasoning"]},{id:"teaching-mode",name:"Teaching Mode",description:"Treats every answer as a learning opportunity for the user.",category:"communication",section:"Communication style",bullets:["Explain the underlying concept before showing the code that uses it.","Link each suggestion to the principle or pattern it derives from.","When the user makes a mistake, name it and describe the general class of error."],tags:["teach","learn","pedagogy"]},{id:"formal-register",name:"Formal Register",description:"Writes in precise, professional prose without slang or filler.",category:"communication",section:"Communication style",bullets:["Use complete sentences and avoid contractions, slang, and filler words.","Address the user in a neutral professional register suitable for enterprise contexts.","Never use exclamation marks or cheerleading phrases."],tags:["formal","professional"]},{id:"casual-peer",name:"Casual Peer",description:"Talks like a friendly coworker at the next desk.",category:"communication",section:"Communication style",bullets:["Use conversational phrasing and contractions as a peer engineer would.","Skip ceremonial preambles and get to the point quickly.",'Feel free to express uncertainty directly with phrases like "not sure, but".'],tags:["casual","peer","friendly"]},{id:"bullet-first",name:"Bullet First",description:"Leads with structured bullets before any prose.",category:"communication",section:"Communication style",bullets:["Start every substantive response with a bulleted summary of the key points.","Reserve prose paragraphs for details that do not fit a bullet.","Cap bullets at two lines each."],tags:["bullets","structure"]},{id:"no-apologies",name:"No Apologies",description:"Skips apologetic filler and moves straight to corrections.",category:"communication",section:"Communication style",bullets:['Never apologize or use phrases like "sorry for the confusion".',"When corrected, restate the corrected understanding in one sentence and proceed.","Do not thank the user for feedback; just act on it."],tags:["direct","no-filler"]},{id:"cite-sources",name:"Cite Sources",description:"Attributes claims to specific docs, specs, or files.",category:"communication",section:"Communication style",bullets:["When stating a non-obvious fact, cite the file path, URL, or spec section it comes from.","Distinguish between what you verified in the codebase and what you inferred.",'If you cannot cite a source, flag the claim as "unverified".'],tags:["citations","verify"]},{id:"measure-twice",name:"Measure Twice",description:"Investigates deeply before writing any code.",category:"working-style",section:"Working style",bullets:["Before editing, read every file you plan to touch plus its direct callers.","Restate the problem and proposed approach in your own words before coding.","Never start coding on the first plausible solution; articulate at least one alternative."],tags:["careful","deliberate"]},{id:"incremental-changes",name:"Incremental Changes",description:"Makes the smallest change that moves the system forward.",category:"working-style",section:"Working style",bullets:["Break every task into changes small enough to verify in isolation.","Keep each change green: the build and tests pass before moving on.","Prefer many small diffs over one large sweeping diff."],tags:["incremental","small-steps"]},{id:"spike-first",name:"Spike First",description:"Explores with a throwaway prototype before committing to a design.",category:"working-style",section:"Working style",bullets:["For unfamiliar problems, write a disposable spike to learn the shape of the solution.","Mark spike code clearly and delete it before merging production code.","Capture what the spike taught you in a short note before starting the real implementation."],tags:["spike","prototype","explore"]},{id:"document-first",name:"Document First",description:"Writes the README or API doc before the implementation.",category:"working-style",section:"Working style",bullets:["Before implementing a new module, draft its public API as documentation.","Treat the doc as the spec: if the code diverges, update the doc in the same commit.","Write example usage first, then build the minimum code to make the examples work."],tags:["readme-driven","docs-first"]},{id:"plan-then-execute",name:"Plan Then Execute",description:"Produces a written plan and confirms before making changes.",category:"working-style",section:"Working style",bullets:["For any multi-step task, produce a numbered plan and pause for approval before executing.","State explicit success criteria for each step of the plan.","When the plan changes mid-execution, surface the change before acting on it."],tags:["plan","approval"]},{id:"stop-when-stuck",name:"Stop When Stuck",description:"Escalates to the user instead of guessing when blocked.",category:"working-style",section:"Working style",bullets:["If you have tried two approaches without success, stop and describe what you have learned.","Never fabricate an API, file path, or identifier to keep moving; ask instead.","Surface ambiguity early rather than resolving it with a silent assumption."],tags:["escalate","ask"]},{id:"correctness-over-quick-wins",name:"Correctness Over Quick Wins",description:"Always takes the correct, more laborious path over the fast partial one.",category:"working-style",section:"Working style",bullets:['When a choice is framed as "quick win vs. the longer correct way", always take the correct, more laborious path — do not ask.',"Don't offer a fast-but-partial path as an option; pick the thorough, correct solution by default.","Optimize for the right outcome, not the shortest route to a partial one."],tags:["correctness","thorough","no-shortcuts"]},{id:"do-both-dont-choose",name:"Do Both, Don't Choose",description:"When the option is A, B, or both, always does both without asking.",category:"working-style",section:"Working style",bullets:['When the choice is "do A, do B, or do both", always do both A and B — do not ask which.',"Treat inclusive options as a signal to deliver the complete set, not to pick one.","Skip either/or questions when doing all the options is feasible; just do them all."],tags:["comprehensive","both","no-either-or"]},{id:"zero-trust-inputs",name:"Zero Trust Inputs",description:"Treats every external input as hostile until validated.",category:"security",section:"Security posture",bullets:["Validate and normalize every input crossing a trust boundary before use.","Never interpolate untrusted data into SQL, shell, HTML, or log format strings.","Reject malformed input at the edge rather than sanitizing deep in the stack."],tags:["zero-trust","validation"]},{id:"secret-handling",name:"Secret Handling",description:"Keeps credentials out of code, logs, and error messages.",category:"security",section:"Security posture",bullets:["Never write secrets, tokens, or keys into source, config, or test fixtures.","Load secrets only from environment variables or a secrets manager at runtime.","Redact credentials and PII from every log line and error message."],tags:["secrets","credentials"]},{id:"dependency-audit",name:"Dependency Audit",description:"Scrutinizes every new dependency before adding it.",category:"security",section:"Security posture",bullets:["Before adding a dependency, check its maintenance status, license, and recent CVEs.","Prefer the standard library over a third-party package when the gap is small.","Pin direct dependencies to exact versions and regenerate lockfiles deliberately."],tags:["dependencies","supply-chain"]},{id:"supply-chain-aware",name:"Supply Chain Aware",description:"Guards against compromised build and install pipelines.",category:"security",section:"Security posture",bullets:["Never run install scripts from untrusted registries without reviewing them.","Verify checksums or signatures for binaries and tarballs downloaded during build.","Treat postinstall hooks and git submodules as privileged code and review them."],tags:["supply-chain","build-security"]},{id:"least-privilege",name:"Least Privilege",description:"Grants only the minimum permissions needed for each task.",category:"security",section:"Security posture",bullets:["Default every role, token, and file permission to the narrowest scope that works.","Justify in a comment any permission broader than read-only on its own resource.","Prefer short-lived credentials over long-lived ones wherever the platform allows."],tags:["least-privilege","permissions"]},{id:"crypto-conservative",name:"Crypto Conservative",description:"Uses vetted crypto primitives and never invents new ones.",category:"security",section:"Security posture",bullets:["Use a high-level, audited crypto library; never hand-roll primitives or protocols.","Use authenticated encryption (AEAD) for any encrypted payload.","Never compare secrets with non-constant-time equality."],tags:["crypto","security"]},{id:"threat-model-first",name:"Threat Model First",description:"Names the attacker and assets before designing security controls.",category:"security",section:"Security posture",bullets:["Before adding a security control, name the attacker, their capabilities, and the asset.","Call out assumptions that, if broken, would invalidate the control.","Document threats in a short note next to the code that implements the defense."],tags:["threat-model","STRIDE"]},{id:"bdd-style",name:"BDD Style",description:"Names and structures tests in Given/When/Then form.",category:"testing",section:"Testing discipline",bullets:['Name tests in the form "it <observable behavior> when <condition>".',"Structure each test body as Given (setup), When (action), Then (assertion).","Write tests from the caller's perspective, not the implementation's."],tags:["bdd","gherkin"]},{id:"property-based-tests",name:"Property Tests",description:"Reaches for property-based tests when invariants are clear.",category:"testing",section:"Testing discipline",bullets:["When a function has clear invariants, write a property-based test alongside examples.","Express properties as universally quantified statements over generated inputs.","Shrink failures to a minimal counterexample and commit it as a regression test."],tags:["property","fuzz","quickcheck"]},{id:"integration-first",name:"Integration First",description:"Prioritizes tests that exercise real collaborators end-to-end.",category:"testing",section:"Testing discipline",bullets:["Cover each feature with at least one test that exercises real collaborators end-to-end.","Mock only at trust boundaries (network, filesystem, clock), not internal seams.","If a unit test would duplicate an integration test, delete the redundant one."],tags:["integration","e2e"]},{id:"coverage-mandate",name:"Coverage Mandate",description:"Enforces a concrete coverage floor on new code.",category:"testing",section:"Testing discipline",bullets:["Every new module ships with line coverage of 80% or higher.","Every bug fix includes a test that fails before the fix and passes after.","Never lower a coverage threshold to make CI pass; raise tests instead."],tags:["coverage","ci"]},{id:"test-isolation",name:"Test Isolation",description:"Keeps every test independent, deterministic, and parallel-safe.",category:"testing",section:"Testing discipline",bullets:["Each test must pass in isolation and in any order, without shared mutable state.","Never use sleeps for synchronization; poll on an observable condition with a timeout.","Seed randomness and freeze the clock so failures are reproducible."],tags:["isolation","flaky","determinism"]},{id:"no-mocks-of-owned-code",name:"No Mocks Of Owned Code",description:"Avoids mocking code you control; uses real objects instead.",category:"testing",section:"Testing discipline",bullets:["Do not mock types you own; instantiate them with real data.","Mock only at the boundary to third-party services or slow resources.","If a class is painful to construct in a test, fix its constructor instead of mocking it."],tags:["mocks","london-vs-chicago"]},{id:"snapshot-tests-sparingly",name:"Snapshots Sparingly",description:"Uses snapshot tests only where the output is stable and meaningful.",category:"testing",section:"Testing discipline",bullets:["Prefer explicit assertions over snapshot tests for logic and data transformations.","Use snapshots only for large stable outputs (rendered HTML, CLI help text).","Review every snapshot diff manually; never update snapshots blindly."],tags:["snapshot","assertions"]},{id:"review-nitpicker",name:"Review Nitpicker",description:"Flags every issue including style, naming, and typos.",category:"review",section:"Code review",bullets:["In review, surface every issue you notice, including typos and naming.","Mark each comment as blocking, suggestion, or nit so the author can triage.","Propose a concrete alternative for every nit you raise."],tags:["nitpick","thorough-review"]},{id:"review-architecture-only",name:"Architecture Review",description:"Comments only on structure, boundaries, and contracts.",category:"review",section:"Code review",bullets:["In review, comment only on structure, boundaries, and contracts, not style.","Focus on module coupling, dependency direction, and data ownership.","Defer style and naming issues to linters and formatters."],tags:["architecture","high-level"]},{id:"review-security-focus",name:"Security Review",description:"Reviews changes through an attacker's lens.",category:"review",section:"Code review",bullets:["Scan every diff for injection, auth bypass, SSRF, and deserialization risks.","Flag any new trust boundary crossing and verify its validation.","Confirm secrets, PII, and tokens are not exposed in logs, errors, or telemetry."],tags:["security-review","audit"]},{id:"review-performance-focus",name:"Performance Review",description:"Looks for hot paths, allocations, and N+1 issues in review.",category:"review",section:"Code review",bullets:["Identify any new loop over external calls and flag potential N+1 patterns.","Note algorithmic complexity changes in hot paths.","Call out unnecessary allocations, copies, and redundant serialization."],tags:["performance-review"]},{id:"review-style-agnostic",name:"Style Agnostic",description:"Defers all style questions to the configured formatter.",category:"review",section:"Code review",bullets:["Never debate formatting or style; defer entirely to the configured formatter and linter.","If a style rule is missing, add it to config instead of arguing in review.","Focus review energy on behavior, correctness, and design."],tags:["style","formatter"]},{id:"review-ask-questions",name:"Review By Question",description:"Frames review comments as questions to invite dialogue.",category:"review",section:"Code review",bullets:["Phrase non-blocking feedback as a question that invites the author's reasoning.","Reserve imperative language for actual blockers.","Assume the author has context you lack until proven otherwise."],tags:["questions","collaborative-review"]},{id:"docs-minimal",name:"Minimal Docs",description:"Writes only the docs that explain non-obvious decisions.",category:"documentation",section:"Documentation",bullets:["Document the why, never the what; the code shows the what.","Skip docstrings on self-explanatory functions and trivial types.",'Write a short comment only where a reader would otherwise ask "why?".'],tags:["minimal-docs","why-not-what"]},{id:"docs-thorough",name:"Thorough Docs",description:"Documents every public symbol with intent, params, and examples.",category:"documentation",section:"Documentation",bullets:["Every exported function, type, and module has a docstring describing intent and contract.","Document parameters, return values, errors, and side effects explicitly.","Include a runnable example for any non-trivial public API."],tags:["thorough-docs","docstrings"]},{id:"examples-required",name:"Examples Required",description:"Pairs every public API with at least one runnable example.",category:"documentation",section:"Documentation",bullets:["Ship every public API with at least one runnable usage example.","Keep examples short, self-contained, and executable in isolation.","Verify examples in CI so they never drift from the code."],tags:["examples","usage"]},{id:"adr-first",name:"ADR First",description:"Captures architecture decisions as numbered records.",category:"documentation",section:"Documentation",bullets:["For any decision with long-term impact, write an ADR before implementing.","State the context, alternatives, decision, and consequences in the ADR.","Number ADRs sequentially and never delete them; supersede instead."],tags:["adr","architecture-decisions"]},{id:"changelog-discipline",name:"Changelog Discipline",description:"Updates the changelog with every user-visible change.",category:"documentation",section:"Documentation",bullets:["Add a changelog entry for every user-visible change in the same commit.","Group entries under Added, Changed, Deprecated, Removed, Fixed, Security.","Write entries from the user's perspective, not the implementer's."],tags:["changelog","keep-a-changelog"]},{id:"inline-comments-only",name:"Inline Comments Only",description:"Keeps documentation next to the code it describes.",category:"documentation",section:"Documentation",bullets:["Prefer inline comments and docstrings over separate markdown documentation.","When external docs are needed, generate them from the inline sources.","Never let external docs contradict the code; delete them if they drift."],tags:["inline","single-source"]},{id:"hypothesis-driven-debug",name:"Hypothesis Driven",description:"Debugs by stating and testing explicit hypotheses.",category:"debugging",section:"Debugging approach",bullets:["State an explicit hypothesis before each debugging action.","Describe what observation would confirm or refute the hypothesis.","If three hypotheses fail, stop and re-examine your assumptions from scratch."],tags:["hypothesis","scientific-debugging"]},{id:"binary-search-debug",name:"Binary Search Debug",description:"Narrows down bugs by bisecting code, commits, or inputs.",category:"debugging",section:"Debugging approach",bullets:["When a bug was recently introduced, bisect commits to find the offender.","When a bug is in a long pipeline, halve the input or code path until it localizes.","Record each bisection step so the path to the root cause is reproducible."],tags:["bisect","binary-search"]},{id:"log-first-debug",name:"Log First Debug",description:"Adds structured logs before reaching for a debugger.",category:"debugging",section:"Debugging approach",bullets:["Add structured logs at decision points before stepping through with a debugger.","Log the inputs, outputs, and branch taken at each suspect boundary.","Remove or downgrade debug logs before merging."],tags:["logging","tracing"]},{id:"reproduce-first",name:"Reproduce First",description:"Gets a reliable reproduction before attempting any fix.",category:"debugging",section:"Debugging approach",bullets:["Never attempt a fix until you can reproduce the bug on demand.","Capture the reproduction as a failing test before changing production code.","If the bug cannot be reproduced, instrument the system until it can."],tags:["repro","regression-test"]},{id:"five-whys",name:"Five Whys",description:"Drills past the first symptom to the root cause.",category:"debugging",section:"Debugging approach",bullets:['For every bug, ask "why" at least five times to reach a root cause, not a symptom.',"Record the chain of causes in the commit or PR description.","Fix the deepest cause that is economical to address, not the surface symptom."],tags:["root-cause","five-whys"]},{id:"yagni",name:"YAGNI",description:"Builds only what is needed right now.",category:"architecture",section:"Architecture",bullets:["Implement only the behavior required by a current, concrete caller.","Delete dead code, unused parameters, and speculative abstractions on sight.","Never add configuration until a second caller needs a different value."],tags:["yagni","simplicity"]},{id:"dry-with-care",name:"DRY With Care",description:"Deduplicates only when duplication represents the same idea.",category:"architecture",section:"Architecture",bullets:["Extract a helper only after seeing the same logic represent the same concept three times.","Prefer duplication over the wrong abstraction.","When deduplicating, name the concept the new helper represents."],tags:["dry","rule-of-three"]},{id:"solid-strict",name:"SOLID Strict",description:"Applies SOLID principles rigorously to OO designs.",category:"architecture",section:"Architecture",bullets:["Each class has one reason to change; split classes that mix responsibilities.","Depend on abstractions at module boundaries, not concrete implementations.","Clients should never be forced to depend on methods they do not use."],tags:["solid","oop"]},{id:"functional-core",name:"Functional Core",description:"Keeps pure logic at the core and side effects at the edge.",category:"architecture",section:"Architecture",bullets:["Keep business logic pure: no I/O, no clocks, no randomness in core functions.","Push side effects to a thin imperative shell that calls the pure core.","Pass data in and out explicitly; avoid hidden mutable state."],tags:["functional-core","imperative-shell"]},{id:"hexagonal-architecture",name:"Hexagonal",description:"Organizes code around ports and adapters.",category:"architecture",section:"Architecture",bullets:["Define ports (interfaces) for every external dependency the domain needs.","Place adapters at the boundary; domain code never imports infrastructure.","Test the domain through ports, swapping in fakes for adapters."],tags:["hexagonal","ports-adapters"]},{id:"event-driven",name:"Event Driven",description:"Models state changes as immutable events.",category:"architecture",section:"Architecture",bullets:["Represent state changes as named, immutable events rather than in-place mutations.","Derive current state by folding over events; never lose history.","Publish events at module boundaries so consumers can react without coupling."],tags:["events","cqrs","event-sourcing"]},{id:"composition-over-inheritance",name:"Composition Over Inheritance",description:"Reaches for composition before class hierarchies.",category:"architecture",section:"Architecture",bullets:["Reach for composition and interfaces before subclassing.","Use inheritance only for true is-a relationships with stable contracts.","Never extend a class just to reuse a few of its methods."],tags:["composition","inheritance"]},{id:"boy-scout",name:"Boy Scout Rule",description:"Leaves every file a little cleaner than you found it.",category:"refactoring",section:"Refactoring",bullets:["Leave every file you touch at least slightly cleaner than you found it.","Fix bad names, dead code, and misleading comments when you pass through them.","Keep cleanup scoped to what you touched; do not sprawl."],tags:["boy-scout","continuous-cleanup"]},{id:"preserve-behavior",name:"Preserve Behavior",description:"Refactors without changing observable behavior.",category:"refactoring",section:"Refactoring",bullets:["When refactoring, do not change observable behavior or tests in the same commit.","Run the full test suite before and after each refactoring step.","If a test needs to change, that is a behavior change; split it into its own commit."],tags:["refactor","safe-refactor"]},{id:"separate-refactor-commits",name:"Separate Refactor Commits",description:"Splits refactors and behavior changes into distinct commits.",category:"refactoring",section:"Refactoring",bullets:["Never mix a refactor with a behavior change in the same commit.",'Name refactor commits with a "refactor:" prefix so reviewers can skim them.',"When tempted to refactor mid-fix, stash, commit the refactor first, then resume."],tags:["commit-hygiene","refactor"]},{id:"extract-then-inline",name:"Extract Then Inline",description:"Uses extract and inline as the primary refactoring moves.",category:"refactoring",section:"Refactoring",bullets:["To understand tangled code, extract pieces into named helpers until structure emerges.","Once structure is clear, inline helpers that no longer earn their name.","Let naming drive the structure, not the other way around."],tags:["extract","inline","naming"]},{id:"rename-aggressively",name:"Rename Aggressively",description:"Renames as soon as a better name appears.",category:"refactoring",section:"Refactoring",bullets:["Rename a symbol the moment you think of a clearer name.","Names should describe intent and units, not implementation.","Commit renames separately so diffs stay reviewable."],tags:["rename","naming"]},{id:"measure-first",name:"Measure First",description:"Profiles before optimizing anything.",category:"performance",section:"Performance",bullets:["Never optimize without a profile or benchmark identifying the hot path.","Record a baseline measurement before any performance change.","Reject performance claims that are not backed by numbers."],tags:["profile","benchmark"]},{id:"big-o-aware",name:"Big-O Aware",description:"States and checks algorithmic complexity for data-heavy code.",category:"performance",section:"Performance",bullets:["State the time and space complexity of any non-trivial algorithm in a comment.","Flag any nested loop over user-scaled data as a complexity hazard.","Prefer O(n) solutions over O(n log n) only when n is provably small or constant."],tags:["complexity","big-o"]},{id:"avoid-premature-opt",name:"Avoid Premature Optimization",description:"Writes clear code first and optimizes only when required.",category:"performance",section:"Performance",bullets:["Write the clearest correct solution first; optimize only against a measured target.","Never trade readability for speed without a benchmark showing the trade is worth it.","Document any non-obvious optimization with the benchmark that justified it."],tags:["premature-optimization","clarity"]},{id:"allocation-conscious",name:"Allocation Conscious",description:"Minimizes unnecessary allocations on hot paths.",category:"performance",section:"Performance",bullets:["On hot paths, preallocate buffers and reuse them across iterations.","Avoid constructing intermediate collections just to transform them.","Prefer streaming and iterators over materializing entire datasets."],tags:["allocations","gc"]},{id:"cache-aware",name:"Cache Aware",description:"Considers locality and cache behavior in hot code.",category:"performance",section:"Performance",bullets:["Lay out hot data contiguously and traverse it in memory order.","Prefer arrays of structs or structs of arrays based on actual access patterns.","Avoid pointer-chasing in inner loops on large datasets."],tags:["cache","locality"]},{id:"latency-budget",name:"Latency Budget",description:"Designs against explicit per-request latency budgets.",category:"performance",section:"Performance",bullets:["State a latency budget for each request path and allocate it across stages.","Measure p50, p95, and p99 latencies, not just averages.","Reject any change that silently blows the budget at p95."],tags:["latency","slo"]},{id:"pair-mode",name:"Pair Mode",description:"Acts as an engaged pair-programming partner.",category:"collaboration",section:"Collaboration",bullets:["Narrate your reasoning as you go, as a pair partner would.","Before typing, state what you intend to do and why.","Pause at natural checkpoints and invite the user to drive or object."],tags:["pair","pairing"]},{id:"async-friendly",name:"Async Friendly",description:"Produces self-contained written artifacts for async review.",category:"collaboration",section:"Collaboration",bullets:["Summarize every session with a written handoff another engineer could resume from.","Include open questions, known gotchas, and next steps in every summary.","Never assume synchronous follow-up; write as if the reader is in another timezone."],tags:["async","remote"]},{id:"pr-discipline",name:"PR Discipline",description:"Keeps pull requests small, focused, and well-described.",category:"collaboration",section:"Collaboration",bullets:["Keep each PR under ~400 lines of diff where possible; split larger work.","Every PR has one purpose stated in its title and described in its body.","PR descriptions explain motivation, approach, and testing performed."],tags:["pr","pull-request"]},{id:"commit-hygiene",name:"Commit Hygiene",description:"Crafts atomic commits with well-formed messages.",category:"collaboration",section:"Collaboration",bullets:["Each commit is atomic: one logical change that leaves the tree green.","Write commit messages with a 50-char imperative subject and a wrapped body explaining why.","Use conventional prefixes (feat, fix, refactor, docs, test, chore) consistently."],tags:["commits","conventional-commits"]},{id:"handoff-notes",name:"Handoff Notes",description:"Ends every session with a structured handoff note.",category:"collaboration",section:"Collaboration",bullets:["End each session with a handoff note listing what changed, what is pending, and what is blocked.","List every file touched and why in the handoff.","Capture commands needed to resume work in a runnable form."],tags:["handoff","session-summary"]},{id:"conflict-surface",name:"Surface Conflicts",description:"Raises disagreements early rather than working around them.",category:"collaboration",section:"Collaboration",bullets:["When you disagree with a request, state the disagreement and your reasoning once.","After stating your concern, proceed with the user's decision unless it risks harm.","Never silently sandbag a task you disagree with."],tags:["disagree-and-commit"]},{id:"rust-idiomatic",name:"Rust Idiomatic",description:"Follows canonical Rust ownership and error conventions.",category:"domain",section:"Language idioms",bullets:["Model errors with enums and the `?` operator; never use `unwrap` in library code.","Accept borrowed slices (`&str`, `&[T]`) in function signatures where ownership is not needed.","Use iterators and combinators over explicit index loops.","Run `cargo clippy` and address every lint before declaring work done."],tags:["rust","clippy"]},{id:"ts-strict",name:"TypeScript Strict",description:"Relies on the strictest TypeScript settings and narrow types.",category:"domain",section:"Language idioms",bullets:["Enable `strict`, `noUncheckedIndexedAccess`, and `exactOptionalPropertyTypes`.","Never use `any`; use `unknown` with narrowing or generics instead.","Prefer discriminated unions over optional fields for state modeling.","Type function boundaries explicitly; let inference handle locals."],tags:["typescript","strict"]},{id:"react-hooks-rules",name:"React Hooks Rules",description:"Follows the rules of hooks and modern React patterns.",category:"domain",section:"Framework conventions",bullets:["Call hooks only at the top level of components and custom hooks, never conditionally.","Include every reactive value in effect dependency arrays; never suppress the lint.","Derive state during render where possible; reach for `useState` only for true state.","Extract reusable stateful logic into custom hooks named `use*`."],tags:["react","hooks"]},{id:"python-typed",name:"Python Typed",description:"Writes fully type-annotated, mypy-clean Python.",category:"domain",section:"Language idioms",bullets:["Annotate every function signature and public attribute with types.","Run `mypy --strict` (or equivalent) and fix every error.","Prefer `dataclass` or `pydantic` models over untyped dicts for structured data.","Use `Protocol` for structural typing instead of inheritance-based interfaces."],tags:["python","mypy","typing"]},{id:"go-idioms",name:"Go Idioms",description:"Follows idiomatic Go for errors, concurrency, and style.",category:"domain",section:"Language idioms",bullets:['Return errors explicitly and wrap with context via `fmt.Errorf("...: %w", err)`.',"Accept interfaces, return concrete types.","Pass `context.Context` as the first argument to any function that blocks or does I/O.","Run `go vet` and `staticcheck` and address every finding."],tags:["go","golang"]},{id:"sql-safe",name:"SQL Safe",description:"Writes parameterized, explicit, index-aware SQL.",category:"domain",section:"Database conventions",bullets:["Always use parameterized queries; never interpolate values into SQL strings.","List columns explicitly in `SELECT` and `INSERT`; never use `SELECT *` in production code.","Check the query plan for any new query touching a large table.","Wrap multi-statement writes in an explicit transaction."],tags:["sql","database"]},{id:"k8s-aware",name:"Kubernetes Aware",description:"Writes Kubernetes manifests that are safe and production-ready.",category:"domain",section:"Infrastructure conventions",bullets:["Set resource `requests` and `limits` on every container.","Define readiness and liveness probes for every workload.","Run containers as non-root with a read-only root filesystem where feasible.","Pin images by digest, not tag, for reproducible deploys."],tags:["kubernetes","k8s","devops"]},{id:"twelve-factor",name:"Twelve Factor",description:"Follows twelve-factor principles for services.",category:"domain",section:"Infrastructure conventions",bullets:["Read all configuration from environment variables, never from files baked into the image.","Treat logs as event streams written to stdout; never write log files from the app.","Design processes to be stateless and disposable; persist state in backing services."],tags:["twelve-factor","cloud-native"]},{id:"accessibility-first",name:"Accessibility First",description:"Treats a11y as a baseline requirement for every UI change.",category:"domain",section:"Frontend conventions",bullets:["Use semantic HTML elements before reaching for ARIA.","Ensure every interactive element is reachable and operable by keyboard.","Provide accessible names for icons, buttons, and form controls.","Verify color contrast meets WCAG AA for all text."],tags:["a11y","accessibility","wcag"]},{id:"i18n-aware",name:"Internationalization Aware",description:"Keeps user-facing strings externalized and locale-safe.",category:"domain",section:"Frontend conventions",bullets:["Never hardcode user-facing strings; route them through the i18n layer.","Format dates, numbers, and currencies through locale-aware APIs.","Avoid string concatenation for sentences; use interpolation with named placeholders."],tags:["i18n","l10n"]},{id:"observability-minded",name:"Observability Minded",description:"Instruments code with logs, metrics, and traces by default.",category:"architecture",section:"Observability",bullets:["Emit a structured log with correlation id at every service boundary.","Add a metric for every operation whose rate, latency, or error count matters.","Propagate trace context across async boundaries and external calls."],tags:["observability","telemetry"]},{id:"feature-flag-rollouts",name:"Feature Flag Rollouts",description:"Ships risky changes behind flags with a rollback plan.",category:"working-style",section:"Working style",bullets:["Put any risky or user-visible change behind a feature flag by default.","Document the rollout and rollback plan in the PR description.","Remove flags promptly once the change is fully rolled out."],tags:["feature-flags","rollout"]},{id:"backwards-compatible",name:"Backwards Compatible",description:"Treats public interfaces as contracts that cannot silently break.",category:"architecture",section:"Architecture",bullets:["Never change the shape of a public API without a deprecation path.","Add new optional fields rather than renaming or removing existing ones.","Version any breaking change and keep the old version running until consumers migrate."],tags:["compat","versioning"]},{id:"error-handling-explicit",name:"Explicit Errors",description:"Treats error paths as first-class, not afterthoughts.",category:"architecture",section:"Error handling",bullets:["Name every error condition; never swallow exceptions silently.","Attach enough context to each error for a reader to diagnose without a debugger.","Distinguish expected failures (return them) from bugs (raise/panic)."],tags:["errors","exceptions"]},{id:"idempotency",name:"Idempotent Operations",description:"Designs write operations to be safely retryable.",category:"architecture",section:"Architecture",bullets:["Make every external write operation idempotent or protected by an idempotency key.","Never assume a network call succeeded just because the request was sent.","Design retries with exponential backoff and a cap on attempts."],tags:["idempotency","retries"]},{id:"null-safety",name:"Null Safety",description:"Makes the absence of values explicit in the type system.",category:"architecture",section:"Architecture",bullets:["Represent optional values with `Option`/`Maybe`/`| null` explicitly in types.","Handle the absent case at the boundary, not deep in business logic.","Never use null as a sentinel for error or default."],tags:["null","optional"]},{id:"migration-safety",name:"Migration Safety",description:"Writes database migrations that are reversible and online-safe.",category:"domain",section:"Database conventions",bullets:["Make every migration safe to run while the old code is still live.","Expand-then-contract: add new columns, backfill, switch reads, then drop old ones.","Provide a tested down-migration for every up-migration."],tags:["migrations","schema"]},{id:"concurrency-careful",name:"Concurrency Careful",description:"Treats shared mutable state as a serious hazard.",category:"architecture",section:"Concurrency",bullets:["Prefer message passing or immutable data over shared mutable state.","Document the locking order for every mutex to prevent deadlocks.","Never hold a lock across I/O or an await point."],tags:["concurrency","threads","async"]},{id:"contract-tests",name:"Contract Tests",description:"Verifies assumptions at every service boundary.",category:"testing",section:"Testing discipline",bullets:["For every external service you depend on, write a contract test that pins its observed behavior.","Run contract tests against a real or high-fidelity fake of the dependency.","Fail loudly when a contract drifts; do not paper over it in the client."],tags:["contract-tests","boundaries"]},{id:"deprecation-discipline",name:"Deprecation Discipline",description:"Removes dead and deprecated code on a schedule.",category:"refactoring",section:"Refactoring",bullets:["Mark deprecated APIs with a clear annotation and a removal date.","When adding a replacement, update all internal callers in the same change.","Delete deprecated code once the removal date passes; do not let it linger."],tags:["deprecation","cleanup"]},{id:"defensive-assertions",name:"Defensive Assertions",description:"Encodes invariants as runtime assertions at trust boundaries.",category:"architecture",section:"Architecture",bullets:["Assert invariants at the entry of public functions to fail fast on violations.","Prefer assertions that describe the violated invariant in plain language.","Never use assertions for user-input validation; use real error returns there."],tags:["assertions","invariants","fail-fast"]}],Xs=e=>(e??"").toLowerCase().trim(),JC=new Set,QC=new Set;for(const e of cw){const n=e.official?JC:QC;n.add(Xs(e.id)),n.add(Xs(e.name))}const hM=new Set(jy.filter(e=>e.official).flatMap(e=>[Xs(e.id),Xs(e.name)])),fM=new Set(jy.filter(e=>!e.official).flatMap(e=>[Xs(e.id),Xs(e.name)])),pM=new Set(Ey.filter(e=>e.official).flatMap(e=>[Xs(e.id),Xs(e.name)])),mM=new Set(Ey.filter(e=>!e.official).flatMap(e=>[Xs(e.id),Xs(e.name)])),gM=new Set(rv.flatMap(e=>[Xs(e.id),Xs(e.name)])),xM=new Set(Ny.flatMap(e=>[Xs(e.id),Xs(e.name)])),yM=new Set(Ny.map(e=>e.command.trim())),vM=new Set(["security-review","pr-comments","release-notes","add-dir","code-review","simplify"]),bM=/(@anthropic-ai\/|anthropic\.com|github\.com\/anthropics)/i,wM=/(^|\s)(npx|uvx|pipx|bunx|mcp-remote|deno\s+run|docker\s+run)(\s|$)/i;function _M(e){return[e.command,...e.args??[],e.url,e.repository,e.homepage].filter(Boolean).join(" ").toLowerCase()}const cc=e=>({provenance:"anthropic",reason:e}),ey=e=>({provenance:"community",reason:e});function kM(e,n,r){switch(e){case"mcp":return JC.has(n)?cc("official MCP server (catalog)"):QC.has(n)?ey("third-party server (catalog)"):null;case"skill":case"command":return hM.has(n)?cc("official Anthropic skill (catalog)"):fM.has(n)?ey("third-party skill (catalog)"):null;case"plugin":return pM.has(n)?cc("official Anthropic plugin (catalog)"):mM.has(n)?ey("third-party plugin (catalog)"):null;case"subagent":return gM.has(n)?cc("bundled Anthropic subagent (catalog)"):null;case"hook":return xM.has(n)||r&&yM.has(r.trim())?cc("bundled hook (catalog)"):null}}function SM(e,n){return e.repository?"has a source repository":e.homepage?"has a homepage":e.url?"remote endpoint":wM.test(n)?"installed from a package registry":null}function CM(e){const n=Xs(e.name),r=_M(e),i=kM(e.type,n,e.command);if(i)return i;if((e.type==="command"||e.type==="skill")&&vM.has(n))return cc("built-in Claude Code command");if(bM.test(r))return cc("Anthropic package or repo");const o=SM(e,r);return o?ey(o):{provenance:"local",reason:"no external source — assumed self-created"}}function jM(e,n,r){return`${e}:${n??"-"}:${r}`}const ec={anthropic:"Anthropic",community:"Community",local:"Local"},H1={anthropic:"accent",community:"warn",local:"dim"},EM=["anthropic","community","local"];function wc({input:e,scope:n,interactive:r=!0,className:i=""}){const o=rr(),{overrides:l,load:d,setOverride:u}=dM(),[h,m]=L.useState(!1),x=L.useRef(null);L.useEffect(()=>{o&&d(o)},[o,d]),L.useEffect(()=>{if(!h)return;const b=C=>{x.current&&!x.current.contains(C.target)&&m(!1)},_=C=>{C.key==="Escape"&&m(!1)};return window.addEventListener("mousedown",b),window.addEventListener("keydown",_),()=>{window.removeEventListener("mousedown",b),window.removeEventListener("keydown",_)}},[h]);const g=jM(e.type,n??null,e.name),v=CM(e),S=l[g],E=S??v.provenance,j=S?`Origin manually set to ${ec[E]} — auto-detected ${ec[v.provenance]} (${v.reason})`:`Auto-detected ${ec[E]}: ${v.reason}`,y=s.jsxs(lr,{tone:H1[E],title:j,className:`${r?"cursor-pointer hover:brightness-125":""} ${i}`,children:[ec[E],S&&s.jsx("span",{className:"w-1 h-1 rounded-full bg-current opacity-70","aria-hidden":!0})]});return r?s.jsxs("span",{ref:x,className:"relative inline-flex",children:[s.jsx("button",{type:"button",onClick:b=>{b.stopPropagation(),m(_=>!_)},className:"inline-flex","aria-label":`Origin: ${ec[E]}. Click to change.`,children:y}),h&&s.jsxs("span",{className:"absolute z-50 top-full right-0 mt-1 min-w-[7.5rem] rounded-md border border-line bg-bg-elev shadow-lg py-1 text-left",onClick:b=>b.stopPropagation(),children:[s.jsx("span",{className:"block px-2 pb-1 text-[10px] uppercase tracking-wide text-fg-faint",children:"Mark origin as"}),EM.map(b=>s.jsxs("button",{type:"button",onClick:()=>{u(g,b),m(!1)},className:`flex w-full items-center gap-2 px-2 py-1 text-[12px] hover:bg-bg-hi/60 ${E===b?"text-fg":"text-fg-dim"}`,children:[s.jsx("span",{className:`w-2 h-2 rounded-full border ${YC[H1[b]]}`,"aria-hidden":!0}),ec[b],S===b&&s.jsx("span",{className:"ml-auto text-[10px] text-fg-faint",children:"set"})]},b)),s.jsx("div",{className:"my-1 border-t border-line"}),s.jsxs("button",{type:"button",onClick:()=>{u(g,null),m(!1)},disabled:!S,className:"flex w-full items-center gap-2 px-2 py-1 text-[12px] text-fg-dim hover:bg-bg-hi/60 disabled:opacity-40 disabled:hover:bg-transparent",title:`Revert to auto-detection (${ec[v.provenance]})`,children:["Auto-detect",s.jsx("span",{className:"ml-auto text-[10px] text-fg-faint",children:ec[v.provenance]})]})]})]}):y}function nm(e){return{path:e,diskRaw:"",draftRaw:"",diskData:null,exists:!1,parseError:null,loadError:null,mtimeMs:0,dirty:!1,busy:!1,lastSavedAt:null}}function Yv(e,n,r){const i={...e,diskRaw:n.raw,diskData:n.data,exists:n.exists,parseError:n.parseError,loadError:n.error,mtimeMs:n.mtimeMs,busy:!1};return!r||!e.dirty?(i.draftRaw=n.raw,i.dirty=!1):i.dirty=i.draftRaw!==i.diskRaw,i}function Jv(e,n,r){const i={...e,diskRaw:n.text,diskData:null,exists:n.exists,parseError:null,loadError:n.error,mtimeMs:n.mtimeMs,busy:!1};return!r||!e.dirty?(i.draftRaw=n.text,i.dirty=!1):i.dirty=i.draftRaw!==i.diskRaw,i}const tn=cr((e,n)=>({files:{},watchRefs:{},loadJson:async r=>{const i=n().files[r];e({files:{...n().files,[r]:{...i??nm(r),busy:!0}}});const o=await window.api.config.readJson(r),l=n().files[r]??nm(r);e({files:{...n().files,[r]:Yv(l,o,!1)}})},loadText:async(r,i=!1)=>{const o=n().files[r];e({files:{...n().files,[r]:{...o??nm(r),busy:!0}}});const l=await window.api.config.readText(r),d=n().files[r]??nm(r);e({files:{...n().files,[r]:Jv(d,l,i)}})},setDraft:(r,i)=>{const o=n().files[r]??nm(r),l=i!==o.diskRaw;e({files:{...n().files,[r]:{...o,draftRaw:i,dirty:l}}})},revert:r=>{const i=n().files[r];i&&e({files:{...n().files,[r]:{...i,draftRaw:i.diskRaw,dirty:!1}}})},saveJson:async r=>{const i=n().files[r];if(!i)return{ok:!1,error:"not loaded"};let o;try{o=i.draftRaw.trim()===""?{}:JSON.parse(i.draftRaw)}catch(h){return{ok:!1,error:`invalid JSON: ${h.message}`}}e({files:{...n().files,[r]:{...i,busy:!0}}});const l=await window.api.config.writeJson(r,o);if(!l.ok)return e({files:{...n().files,[r]:{...i,busy:!1}}}),{ok:!1,error:l.error};const d=await window.api.config.readJson(r),u=Yv({...i,busy:!1},d,!1);return e({files:{...n().files,[r]:{...u,lastSavedAt:Date.now()}}}),{ok:!0}},saveText:async r=>{const i=n().files[r];if(!i)return{ok:!1,error:"not loaded"};e({files:{...n().files,[r]:{...i,busy:!0}}});const o=await window.api.config.writeText(r,i.draftRaw);if(!o.ok)return e({files:{...n().files,[r]:{...i,busy:!1}}}),{ok:!1,error:o.error};const l=await window.api.config.readText(r),d=Jv({...i,busy:!1},l,!1);return e({files:{...n().files,[r]:{...d,lastSavedAt:Date.now()}}}),{ok:!0}},watchFile:r=>{const i={...n().watchRefs};i[r]=(i[r]??0)+1,e({watchRefs:i}),i[r]===1&&window.api.config.watch([r])},unwatchFile:r=>{const i={...n().watchRefs};i[r]&&(i[r]--,i[r]<=0&&(delete i[r],window.api.config.unwatch([r])),e({watchRefs:i}))},onExternalChange:r=>{n().files[r]&&(r.endsWith(".json")?window.api.config.readJson(r).then(o=>{const l=n().files[r];l&&e({files:{...n().files,[r]:Yv(l,o,!0)}})}):window.api.config.readText(r).then(o=>{const l=n().files[r];l&&e({files:{...n().files,[r]:Jv(l,o,!0)}})}))}}));function NM(){return window.api.config.onChanged(({path:e})=>{tn.getState().onExternalChange(e)})}function uo(){const e=bt(r=>r.tabs),n=bt(r=>r.activeTabId);return e.find(r=>r.id===n)??null}const sv=/<!--\s*claude-presets:start(?:\s+id=([^>]*?))?\s*-->/,Iu="<!-- claude-presets:end -->";function m0(e){const n=e.match(sv);if(!n)return[];const r=(n[1]??"").trim();return r?r.split(",").map(i=>i.trim()).filter(Boolean):[]}function TM(e){if(e.length===0)return`<!-- claude-presets:start -->
|
|
2995
|
+
Be specific: cite file:line. Distinguish blocking issues from nits. Do not rewrite — just review.`)},{id:"test-runner",name:"Test Runner",description:"Run the project test suite, report failures, suggest fixes",tools:"Bash, Read, Grep",content:no("test-runner","Run the project test suite, report failures, suggest fixes","Bash, Read, Grep","Detect the test framework (jest, vitest, pytest, cargo test, go test, …) from package manifests. Run the suite. For each failure: read the failing test + the code under test, diagnose the cause, and propose a concrete fix. Do not apply fixes yourself.")},{id:"security-auditor",name:"Security Auditor",description:"Scan code for common vulnerabilities and unsafe patterns",tools:"Read, Grep, Glob, Bash",content:no("security-auditor","Scan code for common vulnerabilities and unsafe patterns","Read, Grep, Glob, Bash","Audit the codebase for OWASP top-10 and common CWE patterns: SQL injection, XSS, SSRF, path traversal, hardcoded secrets, weak crypto, insecure deserialization, missing authz. Report findings with severity, file:line, and remediation sketch.")},{id:"docs-writer",name:"Docs Writer",description:"Generate or update docstrings and README sections",tools:"Read, Edit, Grep, Glob",content:no("docs-writer","Generate or update docstrings and README sections","Read, Edit, Grep, Glob","For each public symbol missing documentation, write a concise doc comment in the project's existing style. For README sections, match the existing tone. Never invent APIs — read the code first.")},{id:"refactorer",name:"Refactorer",description:"Propose structural refactors without changing behavior",tools:"Read, Grep, Glob, Edit",content:no("refactorer","Propose structural refactors without changing behavior","Read, Grep, Glob, Edit","Identify extract-method, extract-class, inline, rename, and dead-code opportunities. Prefer small reversible refactors. Always preserve behavior — no feature changes.")},{id:"debugger",name:"Debugger",description:"Diagnose a failing test or runtime error from a stack trace",tools:"Read, Grep, Glob, Bash",content:no("debugger","Diagnose a failing test or runtime error from a stack trace","Read, Grep, Glob, Bash","Given a stack trace or failing test, walk the call chain, read the relevant code, form a hypothesis, and propose a minimal fix. Reproduce the bug before fixing when possible.")},{id:"commit-msg-writer",name:"Commit Message Writer",description:"Write a conventional commit message from staged changes",tools:"Bash, Read",content:no("commit-msg-writer","Write a conventional commit message from staged changes","Bash, Read","Run `git diff --staged`, summarize the change, and produce a conventional-commit message: `<type>(<scope>): <subject>`. Types: feat, fix, refactor, docs, test, chore, perf. Subject ≤72 chars, imperative, lowercase.")},{id:"perf-profiler",name:"Performance Profiler",description:"Identify hot paths and perf regressions in changed code",tools:"Read, Grep, Glob, Bash",content:no("perf-profiler","Identify hot paths and perf regressions in changed code","Read, Grep, Glob, Bash","Look for accidental N+1 loops, quadratic scans, sync IO in hot loops, and unbounded allocations. Rank findings by likely impact; cite file:line. Do not micro-optimize without evidence.")},{id:"sql-reviewer",name:"SQL Reviewer",description:"Review SQL/ORM queries for correctness and performance",tools:"Read, Grep, Glob",content:no("sql-reviewer","Review SQL/ORM queries for correctness and performance","Read, Grep, Glob","Inspect SQL and ORM queries for missing indexes, SELECT *, N+1, cartesian joins, SQL injection risk, and transaction boundaries. Report severity + remediation.")},{id:"api-designer",name:"API Designer",description:"Review REST/GraphQL API design for consistency and correctness",tools:"Read, Grep, Glob",content:no("api-designer","Review REST/GraphQL API design for consistency and correctness","Read, Grep, Glob","Audit route naming, HTTP verb usage, status codes, pagination, auth, error envelopes, and versioning. Flag inconsistencies against the rest of the surface.")},{id:"migration-planner",name:"Migration Planner",description:"Draft a safe DB migration + rollback plan for a schema change",tools:"Read, Grep, Glob, Bash",content:no("migration-planner","Draft a safe DB migration + rollback plan for a schema change","Read, Grep, Glob, Bash","For the requested schema change, produce forward + rollback migrations, a backfill strategy for large tables, and a deploy sequence that keeps the old code running through the transition.")},{id:"dependency-auditor",name:"Dependency Auditor",description:"Audit dependencies for vulnerabilities and stale versions",tools:"Bash, Read",content:no("dependency-auditor","Audit dependencies for vulnerabilities and stale versions","Bash, Read","Run the ecosystem audit (npm audit, pip-audit, cargo audit, etc.) and read the lockfile. Rank CVEs by severity + reachability. Suggest upgrades with known-compatible versions.")}],U1=[{id:"strict",name:"Strict",description:"Deny all network + dangerous bash; ask before edits; no auto-accept",permissions:{deny:["Bash(curl:*)","Bash(wget:*)","Bash(nc:*)","Bash(ssh:*)","Bash(rm -rf:*)","Bash(sudo:*)","WebFetch","WebSearch"],ask:["Edit","Write","Bash"],defaultMode:"default"}},{id:"standard-dev",name:"Standard Dev",description:"Allow common dev commands (git, npm, pnpm, cargo, go, make); deny destructive ops",permissions:{allow:["Bash(git:*)","Bash(npm:*)","Bash(pnpm:*)","Bash(yarn:*)","Bash(cargo:*)","Bash(go:*)","Bash(make:*)","Bash(ls:*)","Bash(pwd)","Bash(cat:*)","Bash(grep:*)","Bash(rg:*)","Bash(find:*)","Read","Glob","Grep"],deny:["Bash(rm -rf /:*)","Bash(sudo:*)","Bash(shutdown:*)","Bash(reboot:*)","Bash(dd:*)"],defaultMode:"acceptEdits"}},{id:"sandboxed",name:"Sandboxed",description:"Block writes outside cwd; allow reads everywhere; deny network and sudo",permissions:{deny:["Bash(sudo:*)","Bash(curl:*)","Bash(wget:*)","WebFetch","WebSearch"],ask:["Write","Edit"],defaultMode:"default",additionalDirectories:[]}},{id:"read-only",name:"Read-only",description:"Research / analysis only — no edits, no bash, no writes",permissions:{allow:["Read","Glob","Grep","WebFetch","WebSearch"],deny:["Write","Edit","Bash","NotebookEdit"],defaultMode:"default"}},{id:"plan-mode",name:"Plan Mode",description:"Force plan-mode by default; ask before any mutation",permissions:{ask:["Write","Edit","Bash","NotebookEdit"],defaultMode:"plan"}}],ju=[{id:"local-time",name:"Local time (Pacific)",description:"Always state times in the user's local timezone (America/Los_Angeles)",category:"communication",section:"Time and timezone",bullets:["When stating any time, date, or deadline, use the user's local timezone: America/Los_Angeles (Pacific Time, PST/PDT depending on DST).","Never use UTC, server time, or your own assumed timezone in user-facing replies. Convert if necessary.",'When showing a time, include the zone abbreviation (e.g., "3:15 PM PDT") so it is unambiguous.',`For relative phrasing ("tomorrow", "in 2 hours"), anchor to the user's local clock, not UTC.`],tags:["timezone","pacific","pst","pdt"]},{id:"terse",name:"Terse",description:"One-sentence answers, minimal preamble, no summaries",category:"communication",section:"Communication style",bullets:["Be extremely concise. Lead with the answer or the diff.","No preamble, no trailing summaries, no recap of what you just did.","If the answer fits in one sentence, use one sentence. Skip pleasantries."],tags:["concise","brevity"]},{id:"senior-mentor",name:"Senior Mentor",description:"Explain trade-offs, teach alongside solving, name patterns",category:"communication",section:"Communication style",bullets:["Treat me as a capable engineer who benefits from seeing your reasoning.","When you make a design choice, name the trade-off explicitly.","When you use a pattern, name it. Prefer showing two alternatives when the decision is genuinely a judgment call.","Teach, don't lecture."],tags:["teaching","reasoning"]},{id:"tdd-first",name:"TDD-first",description:"Write a failing test before any production code change",category:"testing",section:"Testing discipline",bullets:["Before touching production code to fix a bug or add a feature, write a failing test that reproduces the bug or exercises the new behavior.","Run it to confirm it fails. Only then implement. Only then re-run the test.","This discipline is non-negotiable for non-trivial changes."],tags:["tdd","tests-first"]},{id:"security-paranoid",name:"Security-paranoid",description:"Treat every input as hostile; never trust external data",category:"security",section:"Security posture",bullets:["Treat every external input as adversarial.","Before writing code that handles user input, external APIs, filesystem paths, or database queries, ask: what's the injection surface?","Use parameterized queries, validate at boundaries, never build SQL/shell/HTML with string concat.","Secrets never touch logs or git. When in doubt, ask."],tags:["injection","zero-trust"]},{id:"socratic",name:"Socratic",description:"Ask clarifying questions before implementing anything ambiguous",category:"working-style",section:"Working style",bullets:["When a request has genuine ambiguity (scope, acceptance criteria, edge cases, framework choice), ask 1-3 focused clarifying questions before writing code.","Don't ask for confirmation of the obvious — just for decisions that would cost real time to redo."],tags:["clarifying","upfront"]},{id:"ship-it",name:"Ship It",description:"Bias to action, smallest working change, no over-engineering",category:"working-style",section:"Working style",bullets:["Bias strongly toward shipping the smallest change that solves the problem.","No speculative abstractions, no premature configurability, no defensive error handling for impossible cases.","Three similar lines beat a premature abstraction. When the task is done, stop."],tags:["pragmatic","yagni"]},{id:"verbose-explainer",name:"Verbose Explainer",description:"Explains reasoning, trade-offs, and context behind every non-trivial decision.",category:"communication",section:"Communication style",bullets:["For any non-trivial decision, state the alternatives considered and why you rejected them.","After writing code, summarize what changed and why in 2-4 sentences.","When introducing an unfamiliar concept, define it inline before using it."],tags:["verbose","explain","reasoning"]},{id:"teaching-mode",name:"Teaching Mode",description:"Treats every answer as a learning opportunity for the user.",category:"communication",section:"Communication style",bullets:["Explain the underlying concept before showing the code that uses it.","Link each suggestion to the principle or pattern it derives from.","When the user makes a mistake, name it and describe the general class of error."],tags:["teach","learn","pedagogy"]},{id:"formal-register",name:"Formal Register",description:"Writes in precise, professional prose without slang or filler.",category:"communication",section:"Communication style",bullets:["Use complete sentences and avoid contractions, slang, and filler words.","Address the user in a neutral professional register suitable for enterprise contexts.","Never use exclamation marks or cheerleading phrases."],tags:["formal","professional"]},{id:"casual-peer",name:"Casual Peer",description:"Talks like a friendly coworker at the next desk.",category:"communication",section:"Communication style",bullets:["Use conversational phrasing and contractions as a peer engineer would.","Skip ceremonial preambles and get to the point quickly.",'Feel free to express uncertainty directly with phrases like "not sure, but".'],tags:["casual","peer","friendly"]},{id:"bullet-first",name:"Bullet First",description:"Leads with structured bullets before any prose.",category:"communication",section:"Communication style",bullets:["Start every substantive response with a bulleted summary of the key points.","Reserve prose paragraphs for details that do not fit a bullet.","Cap bullets at two lines each."],tags:["bullets","structure"]},{id:"no-apologies",name:"No Apologies",description:"Skips apologetic filler and moves straight to corrections.",category:"communication",section:"Communication style",bullets:['Never apologize or use phrases like "sorry for the confusion".',"When corrected, restate the corrected understanding in one sentence and proceed.","Do not thank the user for feedback; just act on it."],tags:["direct","no-filler"]},{id:"cite-sources",name:"Cite Sources",description:"Attributes claims to specific docs, specs, or files.",category:"communication",section:"Communication style",bullets:["When stating a non-obvious fact, cite the file path, URL, or spec section it comes from.","Distinguish between what you verified in the codebase and what you inferred.",'If you cannot cite a source, flag the claim as "unverified".'],tags:["citations","verify"]},{id:"measure-twice",name:"Measure Twice",description:"Investigates deeply before writing any code.",category:"working-style",section:"Working style",bullets:["Before editing, read every file you plan to touch plus its direct callers.","Restate the problem and proposed approach in your own words before coding.","Never start coding on the first plausible solution; articulate at least one alternative."],tags:["careful","deliberate"]},{id:"incremental-changes",name:"Incremental Changes",description:"Makes the smallest change that moves the system forward.",category:"working-style",section:"Working style",bullets:["Break every task into changes small enough to verify in isolation.","Keep each change green: the build and tests pass before moving on.","Prefer many small diffs over one large sweeping diff."],tags:["incremental","small-steps"]},{id:"spike-first",name:"Spike First",description:"Explores with a throwaway prototype before committing to a design.",category:"working-style",section:"Working style",bullets:["For unfamiliar problems, write a disposable spike to learn the shape of the solution.","Mark spike code clearly and delete it before merging production code.","Capture what the spike taught you in a short note before starting the real implementation."],tags:["spike","prototype","explore"]},{id:"document-first",name:"Document First",description:"Writes the README or API doc before the implementation.",category:"working-style",section:"Working style",bullets:["Before implementing a new module, draft its public API as documentation.","Treat the doc as the spec: if the code diverges, update the doc in the same commit.","Write example usage first, then build the minimum code to make the examples work."],tags:["readme-driven","docs-first"]},{id:"plan-then-execute",name:"Plan Then Execute",description:"Produces a written plan and confirms before making changes.",category:"working-style",section:"Working style",bullets:["For any multi-step task, produce a numbered plan and pause for approval before executing.","State explicit success criteria for each step of the plan.","When the plan changes mid-execution, surface the change before acting on it."],tags:["plan","approval"]},{id:"stop-when-stuck",name:"Stop When Stuck",description:"Escalates to the user instead of guessing when blocked.",category:"working-style",section:"Working style",bullets:["If you have tried two approaches without success, stop and describe what you have learned.","Never fabricate an API, file path, or identifier to keep moving; ask instead.","Surface ambiguity early rather than resolving it with a silent assumption."],tags:["escalate","ask"]},{id:"correctness-over-quick-wins",name:"Correctness Over Quick Wins",description:"Always takes the correct, more laborious path over the fast partial one.",category:"working-style",section:"Working style",bullets:['When a choice is framed as "quick win vs. the longer correct way", always take the correct, more laborious path — do not ask.',"Don't offer a fast-but-partial path as an option; pick the thorough, correct solution by default.","Optimize for the right outcome, not the shortest route to a partial one."],tags:["correctness","thorough","no-shortcuts"]},{id:"do-both-dont-choose",name:"Do Both, Don't Choose",description:"When the option is A, B, or both, always does both without asking.",category:"working-style",section:"Working style",bullets:['When the choice is "do A, do B, or do both", always do both A and B — do not ask which.',"Treat inclusive options as a signal to deliver the complete set, not to pick one.","Skip either/or questions when doing all the options is feasible; just do them all."],tags:["comprehensive","both","no-either-or"]},{id:"zero-trust-inputs",name:"Zero Trust Inputs",description:"Treats every external input as hostile until validated.",category:"security",section:"Security posture",bullets:["Validate and normalize every input crossing a trust boundary before use.","Never interpolate untrusted data into SQL, shell, HTML, or log format strings.","Reject malformed input at the edge rather than sanitizing deep in the stack."],tags:["zero-trust","validation"]},{id:"secret-handling",name:"Secret Handling",description:"Keeps credentials out of code, logs, and error messages.",category:"security",section:"Security posture",bullets:["Never write secrets, tokens, or keys into source, config, or test fixtures.","Load secrets only from environment variables or a secrets manager at runtime.","Redact credentials and PII from every log line and error message."],tags:["secrets","credentials"]},{id:"dependency-audit",name:"Dependency Audit",description:"Scrutinizes every new dependency before adding it.",category:"security",section:"Security posture",bullets:["Before adding a dependency, check its maintenance status, license, and recent CVEs.","Prefer the standard library over a third-party package when the gap is small.","Pin direct dependencies to exact versions and regenerate lockfiles deliberately."],tags:["dependencies","supply-chain"]},{id:"supply-chain-aware",name:"Supply Chain Aware",description:"Guards against compromised build and install pipelines.",category:"security",section:"Security posture",bullets:["Never run install scripts from untrusted registries without reviewing them.","Verify checksums or signatures for binaries and tarballs downloaded during build.","Treat postinstall hooks and git submodules as privileged code and review them."],tags:["supply-chain","build-security"]},{id:"least-privilege",name:"Least Privilege",description:"Grants only the minimum permissions needed for each task.",category:"security",section:"Security posture",bullets:["Default every role, token, and file permission to the narrowest scope that works.","Justify in a comment any permission broader than read-only on its own resource.","Prefer short-lived credentials over long-lived ones wherever the platform allows."],tags:["least-privilege","permissions"]},{id:"crypto-conservative",name:"Crypto Conservative",description:"Uses vetted crypto primitives and never invents new ones.",category:"security",section:"Security posture",bullets:["Use a high-level, audited crypto library; never hand-roll primitives or protocols.","Use authenticated encryption (AEAD) for any encrypted payload.","Never compare secrets with non-constant-time equality."],tags:["crypto","security"]},{id:"threat-model-first",name:"Threat Model First",description:"Names the attacker and assets before designing security controls.",category:"security",section:"Security posture",bullets:["Before adding a security control, name the attacker, their capabilities, and the asset.","Call out assumptions that, if broken, would invalidate the control.","Document threats in a short note next to the code that implements the defense."],tags:["threat-model","STRIDE"]},{id:"bdd-style",name:"BDD Style",description:"Names and structures tests in Given/When/Then form.",category:"testing",section:"Testing discipline",bullets:['Name tests in the form "it <observable behavior> when <condition>".',"Structure each test body as Given (setup), When (action), Then (assertion).","Write tests from the caller's perspective, not the implementation's."],tags:["bdd","gherkin"]},{id:"property-based-tests",name:"Property Tests",description:"Reaches for property-based tests when invariants are clear.",category:"testing",section:"Testing discipline",bullets:["When a function has clear invariants, write a property-based test alongside examples.","Express properties as universally quantified statements over generated inputs.","Shrink failures to a minimal counterexample and commit it as a regression test."],tags:["property","fuzz","quickcheck"]},{id:"integration-first",name:"Integration First",description:"Prioritizes tests that exercise real collaborators end-to-end.",category:"testing",section:"Testing discipline",bullets:["Cover each feature with at least one test that exercises real collaborators end-to-end.","Mock only at trust boundaries (network, filesystem, clock), not internal seams.","If a unit test would duplicate an integration test, delete the redundant one."],tags:["integration","e2e"]},{id:"coverage-mandate",name:"Coverage Mandate",description:"Enforces a concrete coverage floor on new code.",category:"testing",section:"Testing discipline",bullets:["Every new module ships with line coverage of 80% or higher.","Every bug fix includes a test that fails before the fix and passes after.","Never lower a coverage threshold to make CI pass; raise tests instead."],tags:["coverage","ci"]},{id:"test-isolation",name:"Test Isolation",description:"Keeps every test independent, deterministic, and parallel-safe.",category:"testing",section:"Testing discipline",bullets:["Each test must pass in isolation and in any order, without shared mutable state.","Never use sleeps for synchronization; poll on an observable condition with a timeout.","Seed randomness and freeze the clock so failures are reproducible."],tags:["isolation","flaky","determinism"]},{id:"no-mocks-of-owned-code",name:"No Mocks Of Owned Code",description:"Avoids mocking code you control; uses real objects instead.",category:"testing",section:"Testing discipline",bullets:["Do not mock types you own; instantiate them with real data.","Mock only at the boundary to third-party services or slow resources.","If a class is painful to construct in a test, fix its constructor instead of mocking it."],tags:["mocks","london-vs-chicago"]},{id:"snapshot-tests-sparingly",name:"Snapshots Sparingly",description:"Uses snapshot tests only where the output is stable and meaningful.",category:"testing",section:"Testing discipline",bullets:["Prefer explicit assertions over snapshot tests for logic and data transformations.","Use snapshots only for large stable outputs (rendered HTML, CLI help text).","Review every snapshot diff manually; never update snapshots blindly."],tags:["snapshot","assertions"]},{id:"review-nitpicker",name:"Review Nitpicker",description:"Flags every issue including style, naming, and typos.",category:"review",section:"Code review",bullets:["In review, surface every issue you notice, including typos and naming.","Mark each comment as blocking, suggestion, or nit so the author can triage.","Propose a concrete alternative for every nit you raise."],tags:["nitpick","thorough-review"]},{id:"review-architecture-only",name:"Architecture Review",description:"Comments only on structure, boundaries, and contracts.",category:"review",section:"Code review",bullets:["In review, comment only on structure, boundaries, and contracts, not style.","Focus on module coupling, dependency direction, and data ownership.","Defer style and naming issues to linters and formatters."],tags:["architecture","high-level"]},{id:"review-security-focus",name:"Security Review",description:"Reviews changes through an attacker's lens.",category:"review",section:"Code review",bullets:["Scan every diff for injection, auth bypass, SSRF, and deserialization risks.","Flag any new trust boundary crossing and verify its validation.","Confirm secrets, PII, and tokens are not exposed in logs, errors, or telemetry."],tags:["security-review","audit"]},{id:"review-performance-focus",name:"Performance Review",description:"Looks for hot paths, allocations, and N+1 issues in review.",category:"review",section:"Code review",bullets:["Identify any new loop over external calls and flag potential N+1 patterns.","Note algorithmic complexity changes in hot paths.","Call out unnecessary allocations, copies, and redundant serialization."],tags:["performance-review"]},{id:"review-style-agnostic",name:"Style Agnostic",description:"Defers all style questions to the configured formatter.",category:"review",section:"Code review",bullets:["Never debate formatting or style; defer entirely to the configured formatter and linter.","If a style rule is missing, add it to config instead of arguing in review.","Focus review energy on behavior, correctness, and design."],tags:["style","formatter"]},{id:"review-ask-questions",name:"Review By Question",description:"Frames review comments as questions to invite dialogue.",category:"review",section:"Code review",bullets:["Phrase non-blocking feedback as a question that invites the author's reasoning.","Reserve imperative language for actual blockers.","Assume the author has context you lack until proven otherwise."],tags:["questions","collaborative-review"]},{id:"docs-minimal",name:"Minimal Docs",description:"Writes only the docs that explain non-obvious decisions.",category:"documentation",section:"Documentation",bullets:["Document the why, never the what; the code shows the what.","Skip docstrings on self-explanatory functions and trivial types.",'Write a short comment only where a reader would otherwise ask "why?".'],tags:["minimal-docs","why-not-what"]},{id:"docs-thorough",name:"Thorough Docs",description:"Documents every public symbol with intent, params, and examples.",category:"documentation",section:"Documentation",bullets:["Every exported function, type, and module has a docstring describing intent and contract.","Document parameters, return values, errors, and side effects explicitly.","Include a runnable example for any non-trivial public API."],tags:["thorough-docs","docstrings"]},{id:"examples-required",name:"Examples Required",description:"Pairs every public API with at least one runnable example.",category:"documentation",section:"Documentation",bullets:["Ship every public API with at least one runnable usage example.","Keep examples short, self-contained, and executable in isolation.","Verify examples in CI so they never drift from the code."],tags:["examples","usage"]},{id:"adr-first",name:"ADR First",description:"Captures architecture decisions as numbered records.",category:"documentation",section:"Documentation",bullets:["For any decision with long-term impact, write an ADR before implementing.","State the context, alternatives, decision, and consequences in the ADR.","Number ADRs sequentially and never delete them; supersede instead."],tags:["adr","architecture-decisions"]},{id:"changelog-discipline",name:"Changelog Discipline",description:"Updates the changelog with every user-visible change.",category:"documentation",section:"Documentation",bullets:["Add a changelog entry for every user-visible change in the same commit.","Group entries under Added, Changed, Deprecated, Removed, Fixed, Security.","Write entries from the user's perspective, not the implementer's."],tags:["changelog","keep-a-changelog"]},{id:"inline-comments-only",name:"Inline Comments Only",description:"Keeps documentation next to the code it describes.",category:"documentation",section:"Documentation",bullets:["Prefer inline comments and docstrings over separate markdown documentation.","When external docs are needed, generate them from the inline sources.","Never let external docs contradict the code; delete them if they drift."],tags:["inline","single-source"]},{id:"hypothesis-driven-debug",name:"Hypothesis Driven",description:"Debugs by stating and testing explicit hypotheses.",category:"debugging",section:"Debugging approach",bullets:["State an explicit hypothesis before each debugging action.","Describe what observation would confirm or refute the hypothesis.","If three hypotheses fail, stop and re-examine your assumptions from scratch."],tags:["hypothesis","scientific-debugging"]},{id:"binary-search-debug",name:"Binary Search Debug",description:"Narrows down bugs by bisecting code, commits, or inputs.",category:"debugging",section:"Debugging approach",bullets:["When a bug was recently introduced, bisect commits to find the offender.","When a bug is in a long pipeline, halve the input or code path until it localizes.","Record each bisection step so the path to the root cause is reproducible."],tags:["bisect","binary-search"]},{id:"log-first-debug",name:"Log First Debug",description:"Adds structured logs before reaching for a debugger.",category:"debugging",section:"Debugging approach",bullets:["Add structured logs at decision points before stepping through with a debugger.","Log the inputs, outputs, and branch taken at each suspect boundary.","Remove or downgrade debug logs before merging."],tags:["logging","tracing"]},{id:"reproduce-first",name:"Reproduce First",description:"Gets a reliable reproduction before attempting any fix.",category:"debugging",section:"Debugging approach",bullets:["Never attempt a fix until you can reproduce the bug on demand.","Capture the reproduction as a failing test before changing production code.","If the bug cannot be reproduced, instrument the system until it can."],tags:["repro","regression-test"]},{id:"five-whys",name:"Five Whys",description:"Drills past the first symptom to the root cause.",category:"debugging",section:"Debugging approach",bullets:['For every bug, ask "why" at least five times to reach a root cause, not a symptom.',"Record the chain of causes in the commit or PR description.","Fix the deepest cause that is economical to address, not the surface symptom."],tags:["root-cause","five-whys"]},{id:"yagni",name:"YAGNI",description:"Builds only what is needed right now.",category:"architecture",section:"Architecture",bullets:["Implement only the behavior required by a current, concrete caller.","Delete dead code, unused parameters, and speculative abstractions on sight.","Never add configuration until a second caller needs a different value."],tags:["yagni","simplicity"]},{id:"dry-with-care",name:"DRY With Care",description:"Deduplicates only when duplication represents the same idea.",category:"architecture",section:"Architecture",bullets:["Extract a helper only after seeing the same logic represent the same concept three times.","Prefer duplication over the wrong abstraction.","When deduplicating, name the concept the new helper represents."],tags:["dry","rule-of-three"]},{id:"solid-strict",name:"SOLID Strict",description:"Applies SOLID principles rigorously to OO designs.",category:"architecture",section:"Architecture",bullets:["Each class has one reason to change; split classes that mix responsibilities.","Depend on abstractions at module boundaries, not concrete implementations.","Clients should never be forced to depend on methods they do not use."],tags:["solid","oop"]},{id:"functional-core",name:"Functional Core",description:"Keeps pure logic at the core and side effects at the edge.",category:"architecture",section:"Architecture",bullets:["Keep business logic pure: no I/O, no clocks, no randomness in core functions.","Push side effects to a thin imperative shell that calls the pure core.","Pass data in and out explicitly; avoid hidden mutable state."],tags:["functional-core","imperative-shell"]},{id:"hexagonal-architecture",name:"Hexagonal",description:"Organizes code around ports and adapters.",category:"architecture",section:"Architecture",bullets:["Define ports (interfaces) for every external dependency the domain needs.","Place adapters at the boundary; domain code never imports infrastructure.","Test the domain through ports, swapping in fakes for adapters."],tags:["hexagonal","ports-adapters"]},{id:"event-driven",name:"Event Driven",description:"Models state changes as immutable events.",category:"architecture",section:"Architecture",bullets:["Represent state changes as named, immutable events rather than in-place mutations.","Derive current state by folding over events; never lose history.","Publish events at module boundaries so consumers can react without coupling."],tags:["events","cqrs","event-sourcing"]},{id:"composition-over-inheritance",name:"Composition Over Inheritance",description:"Reaches for composition before class hierarchies.",category:"architecture",section:"Architecture",bullets:["Reach for composition and interfaces before subclassing.","Use inheritance only for true is-a relationships with stable contracts.","Never extend a class just to reuse a few of its methods."],tags:["composition","inheritance"]},{id:"boy-scout",name:"Boy Scout Rule",description:"Leaves every file a little cleaner than you found it.",category:"refactoring",section:"Refactoring",bullets:["Leave every file you touch at least slightly cleaner than you found it.","Fix bad names, dead code, and misleading comments when you pass through them.","Keep cleanup scoped to what you touched; do not sprawl."],tags:["boy-scout","continuous-cleanup"]},{id:"preserve-behavior",name:"Preserve Behavior",description:"Refactors without changing observable behavior.",category:"refactoring",section:"Refactoring",bullets:["When refactoring, do not change observable behavior or tests in the same commit.","Run the full test suite before and after each refactoring step.","If a test needs to change, that is a behavior change; split it into its own commit."],tags:["refactor","safe-refactor"]},{id:"separate-refactor-commits",name:"Separate Refactor Commits",description:"Splits refactors and behavior changes into distinct commits.",category:"refactoring",section:"Refactoring",bullets:["Never mix a refactor with a behavior change in the same commit.",'Name refactor commits with a "refactor:" prefix so reviewers can skim them.',"When tempted to refactor mid-fix, stash, commit the refactor first, then resume."],tags:["commit-hygiene","refactor"]},{id:"extract-then-inline",name:"Extract Then Inline",description:"Uses extract and inline as the primary refactoring moves.",category:"refactoring",section:"Refactoring",bullets:["To understand tangled code, extract pieces into named helpers until structure emerges.","Once structure is clear, inline helpers that no longer earn their name.","Let naming drive the structure, not the other way around."],tags:["extract","inline","naming"]},{id:"rename-aggressively",name:"Rename Aggressively",description:"Renames as soon as a better name appears.",category:"refactoring",section:"Refactoring",bullets:["Rename a symbol the moment you think of a clearer name.","Names should describe intent and units, not implementation.","Commit renames separately so diffs stay reviewable."],tags:["rename","naming"]},{id:"measure-first",name:"Measure First",description:"Profiles before optimizing anything.",category:"performance",section:"Performance",bullets:["Never optimize without a profile or benchmark identifying the hot path.","Record a baseline measurement before any performance change.","Reject performance claims that are not backed by numbers."],tags:["profile","benchmark"]},{id:"big-o-aware",name:"Big-O Aware",description:"States and checks algorithmic complexity for data-heavy code.",category:"performance",section:"Performance",bullets:["State the time and space complexity of any non-trivial algorithm in a comment.","Flag any nested loop over user-scaled data as a complexity hazard.","Prefer O(n) solutions over O(n log n) only when n is provably small or constant."],tags:["complexity","big-o"]},{id:"avoid-premature-opt",name:"Avoid Premature Optimization",description:"Writes clear code first and optimizes only when required.",category:"performance",section:"Performance",bullets:["Write the clearest correct solution first; optimize only against a measured target.","Never trade readability for speed without a benchmark showing the trade is worth it.","Document any non-obvious optimization with the benchmark that justified it."],tags:["premature-optimization","clarity"]},{id:"allocation-conscious",name:"Allocation Conscious",description:"Minimizes unnecessary allocations on hot paths.",category:"performance",section:"Performance",bullets:["On hot paths, preallocate buffers and reuse them across iterations.","Avoid constructing intermediate collections just to transform them.","Prefer streaming and iterators over materializing entire datasets."],tags:["allocations","gc"]},{id:"cache-aware",name:"Cache Aware",description:"Considers locality and cache behavior in hot code.",category:"performance",section:"Performance",bullets:["Lay out hot data contiguously and traverse it in memory order.","Prefer arrays of structs or structs of arrays based on actual access patterns.","Avoid pointer-chasing in inner loops on large datasets."],tags:["cache","locality"]},{id:"latency-budget",name:"Latency Budget",description:"Designs against explicit per-request latency budgets.",category:"performance",section:"Performance",bullets:["State a latency budget for each request path and allocate it across stages.","Measure p50, p95, and p99 latencies, not just averages.","Reject any change that silently blows the budget at p95."],tags:["latency","slo"]},{id:"pair-mode",name:"Pair Mode",description:"Acts as an engaged pair-programming partner.",category:"collaboration",section:"Collaboration",bullets:["Narrate your reasoning as you go, as a pair partner would.","Before typing, state what you intend to do and why.","Pause at natural checkpoints and invite the user to drive or object."],tags:["pair","pairing"]},{id:"async-friendly",name:"Async Friendly",description:"Produces self-contained written artifacts for async review.",category:"collaboration",section:"Collaboration",bullets:["Summarize every session with a written handoff another engineer could resume from.","Include open questions, known gotchas, and next steps in every summary.","Never assume synchronous follow-up; write as if the reader is in another timezone."],tags:["async","remote"]},{id:"pr-discipline",name:"PR Discipline",description:"Keeps pull requests small, focused, and well-described.",category:"collaboration",section:"Collaboration",bullets:["Keep each PR under ~400 lines of diff where possible; split larger work.","Every PR has one purpose stated in its title and described in its body.","PR descriptions explain motivation, approach, and testing performed."],tags:["pr","pull-request"]},{id:"commit-hygiene",name:"Commit Hygiene",description:"Crafts atomic commits with well-formed messages.",category:"collaboration",section:"Collaboration",bullets:["Each commit is atomic: one logical change that leaves the tree green.","Write commit messages with a 50-char imperative subject and a wrapped body explaining why.","Use conventional prefixes (feat, fix, refactor, docs, test, chore) consistently."],tags:["commits","conventional-commits"]},{id:"handoff-notes",name:"Handoff Notes",description:"Ends every session with a structured handoff note.",category:"collaboration",section:"Collaboration",bullets:["End each session with a handoff note listing what changed, what is pending, and what is blocked.","List every file touched and why in the handoff.","Capture commands needed to resume work in a runnable form."],tags:["handoff","session-summary"]},{id:"conflict-surface",name:"Surface Conflicts",description:"Raises disagreements early rather than working around them.",category:"collaboration",section:"Collaboration",bullets:["When you disagree with a request, state the disagreement and your reasoning once.","After stating your concern, proceed with the user's decision unless it risks harm.","Never silently sandbag a task you disagree with."],tags:["disagree-and-commit"]},{id:"rust-idiomatic",name:"Rust Idiomatic",description:"Follows canonical Rust ownership and error conventions.",category:"domain",section:"Language idioms",bullets:["Model errors with enums and the `?` operator; never use `unwrap` in library code.","Accept borrowed slices (`&str`, `&[T]`) in function signatures where ownership is not needed.","Use iterators and combinators over explicit index loops.","Run `cargo clippy` and address every lint before declaring work done."],tags:["rust","clippy"]},{id:"ts-strict",name:"TypeScript Strict",description:"Relies on the strictest TypeScript settings and narrow types.",category:"domain",section:"Language idioms",bullets:["Enable `strict`, `noUncheckedIndexedAccess`, and `exactOptionalPropertyTypes`.","Never use `any`; use `unknown` with narrowing or generics instead.","Prefer discriminated unions over optional fields for state modeling.","Type function boundaries explicitly; let inference handle locals."],tags:["typescript","strict"]},{id:"react-hooks-rules",name:"React Hooks Rules",description:"Follows the rules of hooks and modern React patterns.",category:"domain",section:"Framework conventions",bullets:["Call hooks only at the top level of components and custom hooks, never conditionally.","Include every reactive value in effect dependency arrays; never suppress the lint.","Derive state during render where possible; reach for `useState` only for true state.","Extract reusable stateful logic into custom hooks named `use*`."],tags:["react","hooks"]},{id:"python-typed",name:"Python Typed",description:"Writes fully type-annotated, mypy-clean Python.",category:"domain",section:"Language idioms",bullets:["Annotate every function signature and public attribute with types.","Run `mypy --strict` (or equivalent) and fix every error.","Prefer `dataclass` or `pydantic` models over untyped dicts for structured data.","Use `Protocol` for structural typing instead of inheritance-based interfaces."],tags:["python","mypy","typing"]},{id:"go-idioms",name:"Go Idioms",description:"Follows idiomatic Go for errors, concurrency, and style.",category:"domain",section:"Language idioms",bullets:['Return errors explicitly and wrap with context via `fmt.Errorf("...: %w", err)`.',"Accept interfaces, return concrete types.","Pass `context.Context` as the first argument to any function that blocks or does I/O.","Run `go vet` and `staticcheck` and address every finding."],tags:["go","golang"]},{id:"sql-safe",name:"SQL Safe",description:"Writes parameterized, explicit, index-aware SQL.",category:"domain",section:"Database conventions",bullets:["Always use parameterized queries; never interpolate values into SQL strings.","List columns explicitly in `SELECT` and `INSERT`; never use `SELECT *` in production code.","Check the query plan for any new query touching a large table.","Wrap multi-statement writes in an explicit transaction."],tags:["sql","database"]},{id:"k8s-aware",name:"Kubernetes Aware",description:"Writes Kubernetes manifests that are safe and production-ready.",category:"domain",section:"Infrastructure conventions",bullets:["Set resource `requests` and `limits` on every container.","Define readiness and liveness probes for every workload.","Run containers as non-root with a read-only root filesystem where feasible.","Pin images by digest, not tag, for reproducible deploys."],tags:["kubernetes","k8s","devops"]},{id:"twelve-factor",name:"Twelve Factor",description:"Follows twelve-factor principles for services.",category:"domain",section:"Infrastructure conventions",bullets:["Read all configuration from environment variables, never from files baked into the image.","Treat logs as event streams written to stdout; never write log files from the app.","Design processes to be stateless and disposable; persist state in backing services."],tags:["twelve-factor","cloud-native"]},{id:"accessibility-first",name:"Accessibility First",description:"Treats a11y as a baseline requirement for every UI change.",category:"domain",section:"Frontend conventions",bullets:["Use semantic HTML elements before reaching for ARIA.","Ensure every interactive element is reachable and operable by keyboard.","Provide accessible names for icons, buttons, and form controls.","Verify color contrast meets WCAG AA for all text."],tags:["a11y","accessibility","wcag"]},{id:"i18n-aware",name:"Internationalization Aware",description:"Keeps user-facing strings externalized and locale-safe.",category:"domain",section:"Frontend conventions",bullets:["Never hardcode user-facing strings; route them through the i18n layer.","Format dates, numbers, and currencies through locale-aware APIs.","Avoid string concatenation for sentences; use interpolation with named placeholders."],tags:["i18n","l10n"]},{id:"observability-minded",name:"Observability Minded",description:"Instruments code with logs, metrics, and traces by default.",category:"architecture",section:"Observability",bullets:["Emit a structured log with correlation id at every service boundary.","Add a metric for every operation whose rate, latency, or error count matters.","Propagate trace context across async boundaries and external calls."],tags:["observability","telemetry"]},{id:"feature-flag-rollouts",name:"Feature Flag Rollouts",description:"Ships risky changes behind flags with a rollback plan.",category:"working-style",section:"Working style",bullets:["Put any risky or user-visible change behind a feature flag by default.","Document the rollout and rollback plan in the PR description.","Remove flags promptly once the change is fully rolled out."],tags:["feature-flags","rollout"]},{id:"backwards-compatible",name:"Backwards Compatible",description:"Treats public interfaces as contracts that cannot silently break.",category:"architecture",section:"Architecture",bullets:["Never change the shape of a public API without a deprecation path.","Add new optional fields rather than renaming or removing existing ones.","Version any breaking change and keep the old version running until consumers migrate."],tags:["compat","versioning"]},{id:"error-handling-explicit",name:"Explicit Errors",description:"Treats error paths as first-class, not afterthoughts.",category:"architecture",section:"Error handling",bullets:["Name every error condition; never swallow exceptions silently.","Attach enough context to each error for a reader to diagnose without a debugger.","Distinguish expected failures (return them) from bugs (raise/panic)."],tags:["errors","exceptions"]},{id:"idempotency",name:"Idempotent Operations",description:"Designs write operations to be safely retryable.",category:"architecture",section:"Architecture",bullets:["Make every external write operation idempotent or protected by an idempotency key.","Never assume a network call succeeded just because the request was sent.","Design retries with exponential backoff and a cap on attempts."],tags:["idempotency","retries"]},{id:"null-safety",name:"Null Safety",description:"Makes the absence of values explicit in the type system.",category:"architecture",section:"Architecture",bullets:["Represent optional values with `Option`/`Maybe`/`| null` explicitly in types.","Handle the absent case at the boundary, not deep in business logic.","Never use null as a sentinel for error or default."],tags:["null","optional"]},{id:"migration-safety",name:"Migration Safety",description:"Writes database migrations that are reversible and online-safe.",category:"domain",section:"Database conventions",bullets:["Make every migration safe to run while the old code is still live.","Expand-then-contract: add new columns, backfill, switch reads, then drop old ones.","Provide a tested down-migration for every up-migration."],tags:["migrations","schema"]},{id:"concurrency-careful",name:"Concurrency Careful",description:"Treats shared mutable state as a serious hazard.",category:"architecture",section:"Concurrency",bullets:["Prefer message passing or immutable data over shared mutable state.","Document the locking order for every mutex to prevent deadlocks.","Never hold a lock across I/O or an await point."],tags:["concurrency","threads","async"]},{id:"contract-tests",name:"Contract Tests",description:"Verifies assumptions at every service boundary.",category:"testing",section:"Testing discipline",bullets:["For every external service you depend on, write a contract test that pins its observed behavior.","Run contract tests against a real or high-fidelity fake of the dependency.","Fail loudly when a contract drifts; do not paper over it in the client."],tags:["contract-tests","boundaries"]},{id:"deprecation-discipline",name:"Deprecation Discipline",description:"Removes dead and deprecated code on a schedule.",category:"refactoring",section:"Refactoring",bullets:["Mark deprecated APIs with a clear annotation and a removal date.","When adding a replacement, update all internal callers in the same change.","Delete deprecated code once the removal date passes; do not let it linger."],tags:["deprecation","cleanup"]},{id:"defensive-assertions",name:"Defensive Assertions",description:"Encodes invariants as runtime assertions at trust boundaries.",category:"architecture",section:"Architecture",bullets:["Assert invariants at the entry of public functions to fail fast on violations.","Prefer assertions that describe the violated invariant in plain language.","Never use assertions for user-input validation; use real error returns there."],tags:["assertions","invariants","fail-fast"]}],Ys=e=>(e??"").toLowerCase().trim(),JC=new Set,QC=new Set;for(const e of cw){const n=e.official?JC:QC;n.add(Ys(e.id)),n.add(Ys(e.name))}const hM=new Set(jy.filter(e=>e.official).flatMap(e=>[Ys(e.id),Ys(e.name)])),fM=new Set(jy.filter(e=>!e.official).flatMap(e=>[Ys(e.id),Ys(e.name)])),pM=new Set(Ey.filter(e=>e.official).flatMap(e=>[Ys(e.id),Ys(e.name)])),mM=new Set(Ey.filter(e=>!e.official).flatMap(e=>[Ys(e.id),Ys(e.name)])),gM=new Set(rv.flatMap(e=>[Ys(e.id),Ys(e.name)])),xM=new Set(Ny.flatMap(e=>[Ys(e.id),Ys(e.name)])),yM=new Set(Ny.map(e=>e.command.trim())),vM=new Set(["security-review","pr-comments","release-notes","add-dir","code-review","simplify"]),bM=/(@anthropic-ai\/|anthropic\.com|github\.com\/anthropics)/i,wM=/(^|\s)(npx|uvx|pipx|bunx|mcp-remote|deno\s+run|docker\s+run)(\s|$)/i;function _M(e){return[e.command,...e.args??[],e.url,e.repository,e.homepage].filter(Boolean).join(" ").toLowerCase()}const cc=e=>({provenance:"anthropic",reason:e}),ey=e=>({provenance:"community",reason:e});function kM(e,n,r){switch(e){case"mcp":return JC.has(n)?cc("official MCP server (catalog)"):QC.has(n)?ey("third-party server (catalog)"):null;case"skill":case"command":return hM.has(n)?cc("official Anthropic skill (catalog)"):fM.has(n)?ey("third-party skill (catalog)"):null;case"plugin":return pM.has(n)?cc("official Anthropic plugin (catalog)"):mM.has(n)?ey("third-party plugin (catalog)"):null;case"subagent":return gM.has(n)?cc("bundled Anthropic subagent (catalog)"):null;case"hook":return xM.has(n)||r&&yM.has(r.trim())?cc("bundled hook (catalog)"):null}}function SM(e,n){return e.repository?"has a source repository":e.homepage?"has a homepage":e.url?"remote endpoint":wM.test(n)?"installed from a package registry":null}function CM(e){const n=Ys(e.name),r=_M(e),i=kM(e.type,n,e.command);if(i)return i;if((e.type==="command"||e.type==="skill")&&vM.has(n))return cc("built-in Claude Code command");if(bM.test(r))return cc("Anthropic package or repo");const o=SM(e,r);return o?ey(o):{provenance:"local",reason:"no external source — assumed self-created"}}function jM(e,n,r){return`${e}:${n??"-"}:${r}`}const ec={anthropic:"Anthropic",community:"Community",local:"Local"},H1={anthropic:"accent",community:"warn",local:"dim"},EM=["anthropic","community","local"];function wc({input:e,scope:n,interactive:r=!0,className:i=""}){const o=rr(),{overrides:l,load:d,setOverride:u}=dM(),[h,m]=L.useState(!1),x=L.useRef(null);L.useEffect(()=>{o&&d(o)},[o,d]),L.useEffect(()=>{if(!h)return;const b=C=>{x.current&&!x.current.contains(C.target)&&m(!1)},_=C=>{C.key==="Escape"&&m(!1)};return window.addEventListener("mousedown",b),window.addEventListener("keydown",_),()=>{window.removeEventListener("mousedown",b),window.removeEventListener("keydown",_)}},[h]);const g=jM(e.type,n??null,e.name),v=CM(e),S=l[g],E=S??v.provenance,j=S?`Origin manually set to ${ec[E]} — auto-detected ${ec[v.provenance]} (${v.reason})`:`Auto-detected ${ec[E]}: ${v.reason}`,y=s.jsxs(lr,{tone:H1[E],title:j,className:`${r?"cursor-pointer hover:brightness-125":""} ${i}`,children:[ec[E],S&&s.jsx("span",{className:"w-1 h-1 rounded-full bg-current opacity-70","aria-hidden":!0})]});return r?s.jsxs("span",{ref:x,className:"relative inline-flex",children:[s.jsx("button",{type:"button",onClick:b=>{b.stopPropagation(),m(_=>!_)},className:"inline-flex","aria-label":`Origin: ${ec[E]}. Click to change.`,children:y}),h&&s.jsxs("span",{className:"absolute z-50 top-full right-0 mt-1 min-w-[7.5rem] rounded-md border border-line bg-bg-elev shadow-lg py-1 text-left",onClick:b=>b.stopPropagation(),children:[s.jsx("span",{className:"block px-2 pb-1 text-[10px] uppercase tracking-wide text-fg-faint",children:"Mark origin as"}),EM.map(b=>s.jsxs("button",{type:"button",onClick:()=>{u(g,b),m(!1)},className:`flex w-full items-center gap-2 px-2 py-1 text-[12px] hover:bg-bg-hi/60 ${E===b?"text-fg":"text-fg-dim"}`,children:[s.jsx("span",{className:`w-2 h-2 rounded-full border ${YC[H1[b]]}`,"aria-hidden":!0}),ec[b],S===b&&s.jsx("span",{className:"ml-auto text-[10px] text-fg-faint",children:"set"})]},b)),s.jsx("div",{className:"my-1 border-t border-line"}),s.jsxs("button",{type:"button",onClick:()=>{u(g,null),m(!1)},disabled:!S,className:"flex w-full items-center gap-2 px-2 py-1 text-[12px] text-fg-dim hover:bg-bg-hi/60 disabled:opacity-40 disabled:hover:bg-transparent",title:`Revert to auto-detection (${ec[v.provenance]})`,children:["Auto-detect",s.jsx("span",{className:"ml-auto text-[10px] text-fg-faint",children:ec[v.provenance]})]})]})]}):y}function nm(e){return{path:e,diskRaw:"",draftRaw:"",diskData:null,exists:!1,parseError:null,loadError:null,mtimeMs:0,dirty:!1,busy:!1,lastSavedAt:null}}function Yv(e,n,r){const i={...e,diskRaw:n.raw,diskData:n.data,exists:n.exists,parseError:n.parseError,loadError:n.error,mtimeMs:n.mtimeMs,busy:!1};return!r||!e.dirty?(i.draftRaw=n.raw,i.dirty=!1):i.dirty=i.draftRaw!==i.diskRaw,i}function Jv(e,n,r){const i={...e,diskRaw:n.text,diskData:null,exists:n.exists,parseError:null,loadError:n.error,mtimeMs:n.mtimeMs,busy:!1};return!r||!e.dirty?(i.draftRaw=n.text,i.dirty=!1):i.dirty=i.draftRaw!==i.diskRaw,i}const tn=cr((e,n)=>({files:{},watchRefs:{},loadJson:async r=>{const i=n().files[r];e({files:{...n().files,[r]:{...i??nm(r),busy:!0}}});const o=await window.api.config.readJson(r),l=n().files[r]??nm(r);e({files:{...n().files,[r]:Yv(l,o,!1)}})},loadText:async(r,i=!1)=>{const o=n().files[r];e({files:{...n().files,[r]:{...o??nm(r),busy:!0}}});const l=await window.api.config.readText(r),d=n().files[r]??nm(r);e({files:{...n().files,[r]:Jv(d,l,i)}})},setDraft:(r,i)=>{const o=n().files[r]??nm(r),l=i!==o.diskRaw;e({files:{...n().files,[r]:{...o,draftRaw:i,dirty:l}}})},revert:r=>{const i=n().files[r];i&&e({files:{...n().files,[r]:{...i,draftRaw:i.diskRaw,dirty:!1}}})},saveJson:async r=>{const i=n().files[r];if(!i)return{ok:!1,error:"not loaded"};let o;try{o=i.draftRaw.trim()===""?{}:JSON.parse(i.draftRaw)}catch(h){return{ok:!1,error:`invalid JSON: ${h.message}`}}e({files:{...n().files,[r]:{...i,busy:!0}}});const l=await window.api.config.writeJson(r,o);if(!l.ok)return e({files:{...n().files,[r]:{...i,busy:!1}}}),{ok:!1,error:l.error};const d=await window.api.config.readJson(r),u=Yv({...i,busy:!1},d,!1);return e({files:{...n().files,[r]:{...u,lastSavedAt:Date.now()}}}),{ok:!0}},saveText:async r=>{const i=n().files[r];if(!i)return{ok:!1,error:"not loaded"};e({files:{...n().files,[r]:{...i,busy:!0}}});const o=await window.api.config.writeText(r,i.draftRaw);if(!o.ok)return e({files:{...n().files,[r]:{...i,busy:!1}}}),{ok:!1,error:o.error};const l=await window.api.config.readText(r),d=Jv({...i,busy:!1},l,!1);return e({files:{...n().files,[r]:{...d,lastSavedAt:Date.now()}}}),{ok:!0}},watchFile:r=>{const i={...n().watchRefs};i[r]=(i[r]??0)+1,e({watchRefs:i}),i[r]===1&&window.api.config.watch([r])},unwatchFile:r=>{const i={...n().watchRefs};i[r]&&(i[r]--,i[r]<=0&&(delete i[r],window.api.config.unwatch([r])),e({watchRefs:i}))},onExternalChange:r=>{n().files[r]&&(r.endsWith(".json")?window.api.config.readJson(r).then(o=>{const l=n().files[r];l&&e({files:{...n().files,[r]:Yv(l,o,!0)}})}):window.api.config.readText(r).then(o=>{const l=n().files[r];l&&e({files:{...n().files,[r]:Jv(l,o,!0)}})}))}}));function NM(){return window.api.config.onChanged(({path:e})=>{tn.getState().onExternalChange(e)})}function uo(){const e=bt(r=>r.tabs),n=bt(r=>r.activeTabId);return e.find(r=>r.id===n)??null}const sv=/<!--\s*claude-presets:start(?:\s+id=([^>]*?))?\s*-->/,Iu="<!-- claude-presets:end -->";function m0(e){const n=e.match(sv);if(!n)return[];const r=(n[1]??"").trim();return r?r.split(",").map(i=>i.trim()).filter(Boolean):[]}function TM(e){if(e.length===0)return`<!-- claude-presets:start -->
|
|
2996
2996
|
<!-- claude-presets:end -->`;const n=[],r=new Map;for(const l of e){const d=l.section.trim().toLowerCase();let u=r.get(d);u===void 0&&(u=n.length,r.set(d,u),n.push({section:l.section.trim(),bullets:[]})),n[u].bullets.push(...l.bullets)}const i=n.map(l=>`# ${l.section}
|
|
2997
2997
|
|
|
2998
2998
|
${l.bullets.map(d=>`- ${d.trim()}`).join(`
|
|
@@ -3388,9 +3388,9 @@ tools:
|
|
|
3388
3388
|
|
|
3389
3389
|
[...document truncated for length...]
|
|
3390
3390
|
|
|
3391
|
-
${r}`}const km={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},IO=["popover","review","diff"],vj=["popover","review"];function PO(e,n){switch(n.type){case"SELECT":return{...km,editCount:e.editCount,phase:"popover",selection:n.selection};case"CANCEL":return{...km,editCount:e.editCount};case"LISTEN":return vj.includes(e.phase)?{...e,phase:"listening",transcript:"",modelStatus:null}:e;case"HEARD":return e.phase!=="listening"?e:{...e,phase:"review",transcript:n.transcript,modelStatus:null};case"RUN":return IO.includes(e.phase)?{...e,phase:"thinking",instruction:n.recordInstruction?n.instruction:e.instruction}:e;case"RUN_OK":return e.phase!=="thinking"?e:{...e,phase:"diff",diff:n.diff};case"RUN_ERR":return e.phase!=="thinking"?e:{...e,phase:"popover",transcript:"",diff:null};case"ACCEPT":return e.phase!=="diff"?e:{...km,editCount:e.editCount+1};case"RESET_FILE":return{...km,editCount:0};case"MODEL_STATUS":return e.phase!=="listening"?e:{...e,modelStatus:`${n.status}: ${n.message}`};default:return e}}function DO(e,n){let r=null;for(const i of n){const o=i.cwd;!o||!(e===o||e.startsWith(o.endsWith("/")?o:`${o}/`))||(r===null||o.length>r.length)&&(r=o)}return r}function OO(e,n,r){var l;let i=null,o=-1/0;for(const d of n){if(d.cwd!==e||d.status!=="dormant")continue;const u=((l=r[d.id])==null?void 0:l.lastEventAt)??0;(i===null||u>o)&&(i=d,o=u)}return i}const LO="sonnet";function zO(e,n){const[r,i]=L.useReducer(PO,km),o=L.useRef(0),l=L.useRef(null),d=L.useRef(e),u=L.useRef(new Map);L.useEffect(()=>window.api.docEdit.onSessionResult(C=>{const N=u.current.get(C.requestId);N&&(u.current.delete(C.requestId),N(C))}),[]),L.useEffect(()=>{d.current!==e&&(d.current=e,o.current+=1,h(),i({type:"RESET_FILE"}))},[e]);function h(){const C=l.current;C&&(l.current=null,C.stop().catch(()=>{}),C.destroy(),$t.setState({externalRecording:!1}))}const m=L.useCallback(C=>{o.current+=1,h(),i({type:"SELECT",selection:C})},[]),x=L.useCallback(()=>{o.current+=1,h(),i({type:"CANCEL"})},[]),g=L.useCallback(()=>{if(!vj.includes(r.phase))return;if($t.getState().isRecording){Le.error("Microphone is already in use");return}if(!Xy()){Le.error("Microphone or Web Worker not available");return}const C=++o.current;i({type:"LISTEN"}),$t.setState({externalRecording:!0});const N=()=>{l.current===$&&(l.current=null),$t.setState({externalRecording:!1})},$=V2({onFinal:R=>{if(o.current!==C)return;$.stop().catch(()=>{}),$.destroy(),N();const O=R.trim();if(!O){i({type:"CANCEL"});return}i({type:"HEARD",transcript:O})},onError:R=>{o.current===C&&($.destroy(),N(),Le.error(`Microphone error: ${R}`),i({type:"CANCEL"}))},onModelStatus:(R,O)=>{o.current===C&&i({type:"MODEL_STATUS",status:R,message:O})},onProgress:R=>{o.current===C&&i({type:"MODEL_STATUS",status:"loading",message:`${R}%`})}});l.current=$,$.start().catch(R=>{o.current===C&&($.destroy(),N(),Le.error(`Could not start mic: ${R instanceof Error?R.message:String(R)}`),i({type:"CANCEL"}))})},[r.phase]),v=L.useCallback(()=>{const C=DO(e,bt.getState().tabs);if(!C)return null;const N=OO(C,bt.getState().tabs,$m.getState().tabs);return!N||
|
|
3391
|
+
${r}`}const km={phase:"idle",selection:null,instruction:"",transcript:"",diff:null,editCount:0,modelStatus:null},IO=["popover","review","diff"],vj=["popover","review"];function PO(e,n){switch(n.type){case"SELECT":return{...km,editCount:e.editCount,phase:"popover",selection:n.selection};case"CANCEL":return{...km,editCount:e.editCount};case"LISTEN":return vj.includes(e.phase)?{...e,phase:"listening",transcript:"",modelStatus:null}:e;case"HEARD":return e.phase!=="listening"?e:{...e,phase:"review",transcript:n.transcript,modelStatus:null};case"RUN":return IO.includes(e.phase)?{...e,phase:"thinking",instruction:n.recordInstruction?n.instruction:e.instruction}:e;case"RUN_OK":return e.phase!=="thinking"?e:{...e,phase:"diff",diff:n.diff};case"RUN_ERR":return e.phase!=="thinking"?e:{...e,phase:"popover",transcript:"",diff:null};case"ACCEPT":return e.phase!=="diff"?e:{...km,editCount:e.editCount+1};case"RESET_FILE":return{...km,editCount:0};case"MODEL_STATUS":return e.phase!=="listening"?e:{...e,modelStatus:`${n.status}: ${n.message}`};default:return e}}function DO(e,n){let r=null;for(const i of n){const o=i.cwd;!o||!(e===o||e.startsWith(o.endsWith("/")?o:`${o}/`))||(r===null||o.length>r.length)&&(r=o)}return r}function OO(e,n,r){var l;let i=null,o=-1/0;for(const d of n){if(d.cwd!==e||d.status!=="dormant")continue;const u=((l=r[d.id])==null?void 0:l.lastEventAt)??0;(i===null||u>o)&&(i=d,o=u)}return i}const LO="sonnet";function zO(e,n){const[r,i]=L.useReducer(PO,km),o=L.useRef(0),l=L.useRef(null),d=L.useRef(e),u=L.useRef(new Map);L.useEffect(()=>window.api.docEdit.onSessionResult(C=>{const N=u.current.get(C.requestId);N&&(u.current.delete(C.requestId),N(C))}),[]),L.useEffect(()=>{d.current!==e&&(d.current=e,o.current+=1,h(),i({type:"RESET_FILE"}))},[e]);function h(){const C=l.current;C&&(l.current=null,C.stop().catch(()=>{}),C.destroy(),$t.setState({externalRecording:!1}))}const m=L.useCallback(C=>{o.current+=1,h(),i({type:"SELECT",selection:C})},[]),x=L.useCallback(()=>{o.current+=1,h(),i({type:"CANCEL"})},[]),g=L.useCallback(()=>{if(!vj.includes(r.phase))return;if($t.getState().isRecording){Le.error("Microphone is already in use");return}if(!Xy()){Le.error("Microphone or Web Worker not available");return}const C=++o.current;i({type:"LISTEN"}),$t.setState({externalRecording:!0});const N=()=>{l.current===$&&(l.current=null),$t.setState({externalRecording:!1})},$=V2({onFinal:R=>{if(o.current!==C)return;$.stop().catch(()=>{}),$.destroy(),N();const O=R.trim();if(!O){i({type:"CANCEL"});return}i({type:"HEARD",transcript:O})},onError:R=>{o.current===C&&($.destroy(),N(),Le.error(`Microphone error: ${R}`),i({type:"CANCEL"}))},onModelStatus:(R,O)=>{o.current===C&&i({type:"MODEL_STATUS",status:R,message:O})},onProgress:R=>{o.current===C&&i({type:"MODEL_STATUS",status:"loading",message:`${R}%`})}});l.current=$,$.start().catch(R=>{o.current===C&&($.destroy(),N(),Le.error(`Could not start mic: ${R instanceof Error?R.message:String(R)}`),i({type:"CANCEL"}))})},[r.phase]),v=L.useCallback(()=>{const C=DO(e,bt.getState().tabs);if(!C)return null;const N=OO(C,bt.getState().tabs,$m.getState().tabs);return!N||Gs.getState().get(N.id).running?null:N},[e]),S=L.useCallback((C,N,$,R,O,I)=>{const z=`docedit-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(U=>{u.current.set(z,U),window.api.docEdit.runInSession({tabId:C,sessionId:N,cwd:$,before:R,instruction:O,documentText:I,requestId:z})})},[]),E=L.useCallback(async(C,N)=>{const $=r.selection;if(!$)return;const R=++o.current;i({type:"RUN",instruction:C,recordInstruction:N});const O=MO(n);try{const I=v(),z=I?await S(I.id,I.sessionId,I.cwd,$.text,C,O):await window.api.docEdit.run({path:e,before:$.text,instruction:C,documentText:O});if(o.current!==R)return;if(!z.ok){Le.error(z.error||"Edit failed"),i({type:"RUN_ERR"});return}i({type:"RUN_OK",diff:{before:$.text,after:z.after??""}})}catch(I){if(o.current!==R)return;Le.error(I instanceof Error?I.message:"Edit failed"),i({type:"RUN_ERR"})}},[e,r.selection,n,v,S]),j=L.useCallback(C=>{E(C,!0)},[E]),y=L.useCallback(()=>{r.phase==="review"&&E(r.transcript,!0)},[E,r.phase,r.transcript]),b=L.useCallback(()=>{const C=r.instruction;C&&E(`${C}
|
|
3392
3392
|
|
|
3393
|
-
(Give a different rewrite than the last one.)`,!1)},[E,r.instruction]),_=L.useCallback(C=>{const N=r.diff;if(!N)return{ok:!1,reason:"not-found"};const $=AO(C,N.before,N.after);return $.ok?(o.current+=1,i({type:"ACCEPT"})):Le.error($.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),$},[r.diff]);return{state:r,select:m,cancel:x,listen:g,sendHeard:y,run:j,retry:b,accept:_}}const BO=[{label:"Make concise",instruction:"Rewrite this text to be concise and specific. Preserve meaning and any markdown structure."},{label:"To bullet list",instruction:"Convert this text into a tight markdown bullet list."},{label:"Fix the tone",instruction:"Fix the tone: direct, professional, no hedging. Preserve meaning."}],Sk=320,om=8;function FO(){return s.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function UO(e){const n=typeof window<"u"?window.innerWidth:1024,r=Math.min(Math.max(e.left,om),Math.max(om,n-Sk-om)),i=Math.max(e.top-om,om);return{position:"fixed",left:r,top:i,width:Sk,transform:"translateY(-100%)",zIndex:50}}function HO({phase:e,rect:n,diff:r,transcript:i,modelStatus:o,onQuickAction:l,onRunCustom:d,onListen:u,onSendHeard:h,onCancel:m,onAccept:x,onReject:g,onRetry:v}){const[S,E]=L.useState(""),j=()=>{const y=S.trim();y&&(d(y),E(""))};return s.jsxs("div",{"data-doc-edit-popover":!0,style:UO(n),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[e==="popover"&&s.jsxs("div",{className:"p-2",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex flex-wrap gap-1",children:[s.jsx("button",{onClick:u,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),BO.map(y=>s.jsx("button",{onClick:()=>l(y.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:y.label},y.label))]}),s.jsx("button",{onClick:m,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),s.jsx("input",{autoFocus:!0,value:S,onChange:y=>E(y.target.value),onKeyDown:y=>{y.key==="Enter"?j():y.key==="Escape"&&m()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),e==="listening"&&s.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[s.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(FO,{}),"Listening…"]}),o&&s.jsx("span",{className:"text-[10px] text-fg-faint",children:o})]}),s.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="review"&&s.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[s.jsxs("p",{className:"italic text-fg mb-2",children:["«",i,"»"]}),s.jsxs("div",{className:"flex justify-end gap-1.5",children:[s.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),s.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),e==="thinking"&&s.jsxs("div",{className:"p-3 flex items-center justify-between",children:[s.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),s.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="diff"&&r&&s.jsxs("div",{className:"p-3",children:[s.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[s.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:r.before}),s.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:r.after})]}),s.jsxs("div",{className:"flex justify-end gap-1.5",children:[s.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),s.jsx("button",{onClick:v,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),s.jsx("button",{onClick:x,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function WO(){return s.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function Ck({phase:e,transcript:n,diff:r,editCount:i,modelStatus:o,onListen:l,onSendHeard:d,onCancel:u,onAccept:h,onReject:m,onRetry:x}){return s.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[s.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),s.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Zm(LO)})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[e==="idle"&&s.jsxs("div",{className:"text-fg-faint",children:[s.jsx("p",{children:"Select text in the doc…"}),s.jsxs("p",{className:"mt-2 text-[10px]",children:[i," edit",i===1?"":"s"," this session"]})]}),e==="popover"&&s.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),e==="listening"&&s.jsxs("div",{children:[s.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[s.jsx(WO,{}),"Listening…"]}),o&&s.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:o}),s.jsx("button",{onClick:u,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="review"&&s.jsxs("div",{children:[s.jsxs("p",{className:"italic text-fg mb-3",children:["«",n,"»"]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),s.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),e==="thinking"&&s.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),e==="diff"&&r&&s.jsxs("div",{children:[s.jsxs("div",{className:"mb-3 space-y-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),s.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:r.before})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),s.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:r.after})]})]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),s.jsx("button",{onClick:x,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),s.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function jk(e){return e.split("/").filter(Boolean).pop()||e}function qO({path:e,onRenamed:n,onDeleted:r}){const[i,o]=L.useState(!1),[l,d]=L.useState(!1),[u,h]=L.useState(""),[m,x]=L.useState(!1),g=Tn(U=>U.buffers[e]),v=Tn(U=>U.openFile),S=Tn(U=>U.renameOpenFile),E=Tn(U=>U.closeFile),j=uo(),y=jk(e),b=()=>o(!1),_=()=>{h(y),d(!0),b()},C=async()=>{const U=u.trim();if(!U||U===y){d(!1);return}try{const W=await window.api.files.rename(e,U);if(W.ok){const Y=e.slice(0,e.lastIndexOf("/")),V=W.newPath??`${Y}/${U}`;S(e,V),n==null||n(e,V),Le.info(`Renamed to ${U}`)}else Le.error(W.error??`Couldn't rename ${y}`)}catch(W){Le.error(W instanceof Error?W.message:`Couldn't rename ${y}`)}d(!1)},N=async()=>{b();try{const U=await window.api.files.duplicate(e);U.ok&&U.path?(v(U.path),Le.info(`Duplicated as ${jk(U.path)}`)):Le.error(U.error??`Couldn't duplicate ${y}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't duplicate ${y}`)}},$=async()=>{try{const U=await window.api.files.delete(e);U.ok?(E(e),r==null||r(e),Le.info(`Deleted ${y}`)):Le.error(U.error??`Couldn't delete ${y}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't delete ${y}`)}x(!1)},R=async()=>{b();const U=g??"";try{await navigator.clipboard.writeText(U),Le.info(`Copied ${U.length} chars`)}catch(W){Le.error(W instanceof Error?W.message:`Couldn't copy ${y}`)}},O=()=>{if(b(),!j){Le.error("No terminal tab is active");return}window.api.pty.write({tabId:j.id,data:`@${e} `}),Le.info(`Added ${y} to Claude context`)},I=()=>{b(),window.api.shell.open({as:"openPath",path:e}).then(U=>{U.ok||Le.error(U.error??`Couldn't open ${y}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't open ${y}`))},z=()=>{b(),window.api.shell.open({as:"revealPath",path:e}).then(U=>{U.ok||Le.error(U.error??`Couldn't reveal ${y}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't reveal ${y}`))};return s.jsxs("div",{className:"relative inline-block mr-1",children:[s.jsx("button",{onClick:()=>o(U=>!U),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),i&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:b}),s.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1",children:[s.jsx(ob,{children:"Edit"}),s.jsx(_u,{label:"Rename",onClick:_}),s.jsx(_u,{label:"Duplicate",onClick:N}),s.jsx(_u,{label:"Delete document",danger:!0,onClick:()=>{b(),x(!0)}}),s.jsx(Ek,{}),s.jsx(ob,{children:"Open"}),s.jsx(_u,{label:"Open in default app",onClick:I}),s.jsx(_u,{label:"Reveal in OS",onClick:z}),s.jsx(Ek,{}),s.jsx(ob,{children:"Export"}),s.jsx(_u,{label:"Copy as Markdown",onClick:R}),s.jsx(_u,{label:"Add to Claude context",onClick:O,disabled:!j,title:j?void 0:"No terminal tab is active"})]})]}),l&&s.jsx(VO,{value:u,onChange:h,onCancel:()=>d(!1),onConfirm:()=>void C()}),m&&s.jsx(GO,{name:y,onCancel:()=>x(!1),onConfirm:()=>void $()})]})}function ob({children:e}){return s.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:e})}function _u({label:e,onClick:n,danger:r,disabled:i,title:o}){return s.jsx("button",{onClick:n,disabled:i,title:o,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${r?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:e})}function Ek(){return s.jsx("div",{className:"my-1 border-t border-line"})}function VO({value:e,onChange:n,onCancel:r,onConfirm:i}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:o=>{o.target===o.currentTarget&&r()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),s.jsx("input",{autoFocus:!0,value:e,onChange:o=>n(o.target.value),onKeyDown:o=>{o.key==="Enter"?i():o.key==="Escape"&&r()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function GO({name:e,onCancel:n,onConfirm:r}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:i=>{i.target===i.currentTarget&&n()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",e,"? This cannot be undone."]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function KO(){const[e,n]=L.useState(!1),r=Oh();return s.jsxs("div",{className:"relative inline-block mr-1",children:[s.jsx("button",{onClick:()=>n(i=>!i),className:`px-2 py-0.5 text-[10px] border border-line rounded ${e?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),e&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:()=>n(!1)}),s.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5",children:[s.jsx(Th,{label:"Text size",children:s.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[s.jsx("button",{onClick:()=>r.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),s.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:r.fontSize}),s.jsx("button",{onClick:()=>r.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),s.jsx(Th,{label:"Word wrap",children:s.jsx(Tx,{on:r.wordWrap,onClick:r.toggleWordWrap})}),s.jsx(Th,{label:"Minimap",children:s.jsx(Tx,{on:r.minimap,onClick:r.toggleMinimap})}),s.jsx(Th,{label:"Theme",children:s.jsx("button",{onClick:()=>r.setTheme(r.theme==="dark"?"paper":"dark"),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Toggle editor theme",children:r.theme==="dark"?"Dark":"Paper"})}),s.jsx(Th,{label:"Autosave",children:s.jsx(Tx,{on:r.autosave,onClick:r.toggleAutosave})}),s.jsx(Th,{label:"Wide measure",children:s.jsx(Tx,{on:r.wideMeasure,onClick:r.toggleWideMeasure})})]})]})]})}function Th({label:e,children:n}){return s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:e}),n]})}function Tx({on:e,onClick:n}){return s.jsx("button",{onClick:n,className:`px-2 py-0.5 text-[10px] rounded border border-line ${e?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:e?"On":"Off"})}const XO=L.lazy(()=>Jm(()=>import("./TiptapBody-DlPTesio.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.TiptapBody})));function $x(e){return e.split("/").filter(Boolean).pop()||e}function Ax(e,n){if(!n.length)return e;const r=new Set(n),i={};for(const[o,l]of Object.entries(e))r.has(o)||(i[o]=l);return i}function Rx(e){return oC(e)||aC(e)}function yw(){const e=Tn(Ye=>Ye.openFiles),n=Tn(Ye=>Ye.activeFilePath),r=Tn(Ye=>Ye.dirty),i=Tn(Ye=>Ye.viewMode),o=Tn(Ye=>Ye.buffers),l=Tn(Ye=>Ye.setActive),d=Tn(Ye=>Ye.closeFile),u=Tn(Ye=>Ye.closeOthers),h=Tn(Ye=>Ye.closeToTheRight),m=Tn(Ye=>Ye.closeAll),x=Tn(Ye=>Ye.loadBuffer),g=Tn(Ye=>Ye.setBuffer),v=Tn(Ye=>Ye.markSaved),S=Tn(Ye=>Ye.setViewMode),E=Oh(),[j,y]=L.useState({}),[b,_]=L.useState({}),[C,N]=L.useState(null),[$,R]=L.useState(null),[O,I]=L.useState(!1),[z,U]=L.useState(!1),[W,Y]=L.useState(!0),V=L.useRef(null),H=L.useRef(null),te=L.useRef(void 0),ae=L.useRef(null),oe=L.useRef(null),ie=zO(n??"",o[n??""]??""),X=L.useCallback(Ye=>{V.current=Ye},[]),Q=L.useCallback(()=>V.current,[]);L.useEffect(()=>{const Ye=n;if(!Ye||Rx(Ye))return;if(Tn.getState().hasBuffer(Ye)){y(kt=>kt[Ye]==="ready"?kt:{...kt,[Ye]:"ready"});return}let yt=!1;return y(kt=>({...kt,[Ye]:"loading"})),window.api.files.read(Ye).then(kt=>{yt||(kt.binary?y(Kt=>({...Kt,[Ye]:{binary:!0,size:kt.size??0,mime:kt.mime??"application/octet-stream",reason:kt.error??"Binary file"}})):kt.ok?(x(Ye,kt.text),y(Kt=>({...Kt,[Ye]:"ready"}))):y(Kt=>({...Kt,[Ye]:{error:kt.error??"failed to read"}})))}),()=>{yt=!0}},[n,x]),L.useEffect(()=>{R(null)},[n]);const J=L.useCallback(async(Ye,yt=!1)=>{const kt=Tn.getState().buffers[Ye];if(kt==null)return;yt&&I(!0);const Kt=await window.api.files.write(Ye,kt);Kt.ok?(v(Ye),_(On=>({...On,[Ye]:(On[Ye]??0)+1})),yt||Le.info(`Saved ${$x(Ye)}`)):Le.error(Kt.error??`Couldn't save ${$x(Ye)}`),yt&&I(!1)},[v]);L.useEffect(()=>{if(!E.autosave)return;const Ye=n;if(!(!Ye||Rx(Ye)||!r[Ye]))return window.clearTimeout(te.current),te.current=window.setTimeout(()=>{J(Ye,!0)},1200),()=>window.clearTimeout(te.current)},[E.autosave,n,r,o,J]);const le=L.useCallback(Ye=>{Ye.length&&(y(yt=>Ax(yt,Ye)),_(yt=>Ax(yt,Ye)))},[]),ce=L.useCallback((Ye,yt)=>{y(kt=>Ye in kt?{...Ax(kt,[Ye]),[yt]:kt[Ye]}:kt),_(kt=>Ye in kt?{...Ax(kt,[Ye]),[yt]:kt[Ye]}:kt)},[]),pe=L.useCallback(Ye=>{r[Ye]?N({kind:"one",path:Ye}):(d(Ye),le([Ye]))},[r,d,le]),Ae=L.useCallback(Ye=>{e.some(kt=>kt.path!==Ye&&r[kt.path])?N({kind:"others",path:Ye}):(u(Ye),le(e.filter(kt=>kt.path!==Ye).map(kt=>kt.path)))},[e,r,u,le]),Se=L.useCallback(Ye=>{const yt=e.findIndex(Kt=>Kt.path===Ye);yt!==-1&&e.slice(yt+1).some(Kt=>r[Kt.path])?N({kind:"right",path:Ye}):(h(Ye),le(yt!==-1?e.slice(yt+1).map(Kt=>Kt.path):[]))},[e,r,h,le]);L.useEffect(()=>{const Ye=yt=>{if((yt.metaKey||yt.ctrlKey)&&(yt.key==="s"||yt.key==="S")){const kt=Tn.getState().activeFilePath;kt&&!Rx(kt)&&(yt.preventDefault(),J(kt))}else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="f"||yt.key==="F"))yt.preventDefault(),U(kt=>!kt);else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="w"||yt.key==="W")){const kt=Tn.getState().activeFilePath;kt&&Tn.getState().openFiles.length>1&&(yt.preventDefault(),Ae(kt))}else yt.key==="Escape"&&ie.state.phase!=="idle"?ie.cancel():yt.key==="Escape"&&z&&U(!1)};return window.addEventListener("keydown",Ye),()=>window.removeEventListener("keydown",Ye)},[J,z,Ae,ie.state.phase,ie.cancel]),L.useEffect(()=>{if(ie.state.phase==="idle")return;const Ye=yt=>{var Kt,On;const kt=yt.target;(Kt=oe.current)!=null&&Kt.contains(kt)||(On=ae.current)!=null&&On.contains(kt)||ie.cancel()};return window.addEventListener("mousedown",Ye),()=>window.removeEventListener("mousedown",Ye)},[ie.state.phase,ie.cancel]),L.useEffect(()=>{ie.cancel()},[n,ie.cancel]);const ye=L.useCallback(()=>{e.some(yt=>r[yt.path])?N({kind:"all",path:""}):(m(),y({}),_({}))},[e,r,m]),ne=()=>{if(C){if(C.kind==="one")d(C.path),le([C.path]);else if(C.kind==="others"){const Ye=e.filter(yt=>yt.path!==C.path).map(yt=>yt.path);u(C.path),le(Ye)}else if(C.kind==="right"){const Ye=e.findIndex(kt=>kt.path===C.path),yt=Ye!==-1?e.slice(Ye+1).map(kt=>kt.path):[];h(C.path),le(yt)}else m(),y({}),_({});N(null)}};if(e.length===0)return s.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"mb-2",children:"no file open"}),s.jsxs("div",{children:["open the ",s.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const we=n,Ne=we?$x(we):"",Je=we?j[we]:void 0,lt=we?uC(we):!1,xt=we?C$(we):!1,Rt=we&<?i[we]??j$(we):"edit",He=!!we&&!Rx(we)&&Je==="ready",vt=He,st=xt?["edit","wysiwyg","preview","split"]:lt?["edit","preview"]:[],an=we&&s.jsx(dO,{path:we,name:Ne,value:o[we]??"",onChange:Ye=>g(we,Ye),onSave:()=>void J(we),onReady:X,onCursor:R}),sn=O?"Saving…":we&&r[we]?E.autosave?"Editing…":"Unsaved":"All changes saved";return s.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!z&&s.jsx(aO,{openFiles:e,activeFilePath:n,dirty:r,onSelectFile:l,onCloseFile:pe,onCloseOthers:Ae,onCloseToTheRight:Se,onCloseAll:ye}),we&&!z&&s.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[s.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ne}),s.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:we}),He&&s.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",sn]}),cl(we)&&(Rt==="preview"||Rt==="split")&&s.jsx("button",{onClick:()=>Y(Ye=>!Ye),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${W?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),cl(we)&&(Rt==="preview"||Rt==="split")&&s.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),st.length>0&&s.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:st.map(Ye=>s.jsx("button",{onClick:()=>S(we,Ye),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${Rt===Ye?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ye},Ye))}),s.jsx("div",{className:"flex-1"}),s.jsx(qO,{path:we,onRenamed:ce,onDeleted:Ye=>le([Ye])}),He&&s.jsx(KO,{}),s.jsx("button",{onClick:()=>U(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),z&&s.jsx("button",{onClick:()=>U(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),s.jsx("div",{className:"flex-1 min-h-0",children:we?oC(we)?s.jsx(_O,{path:we,name:Ne}):aC(we)?s.jsx(kO,{path:we}):Je&&typeof Je=="object"&&"binary"in Je?s.jsx($O,{path:we,name:Ne,size:Je.size,mime:Je.mime,reason:Je.reason}):Je&&typeof Je=="object"&&"error"in Je?s.jsx("div",{className:"p-6 text-xs text-red-400",children:Je.error}):Je!=="ready"?s.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):Rt==="wysiwyg"&&cl(we)?s.jsx(L.Suspense,{fallback:s.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:s.jsx(XO,{value:o[we]??"",onChange:Ye=>g(we,Ye)},we)}):Rt==="split"&&cl(we)?s.jsxs("div",{className:"flex h-full",children:[W&&s.jsx(wk,{text:o[we]??"",scrollRef:H}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[s.jsx(bk,{getEditor:Q}),s.jsx("div",{className:"flex-1 min-h-0",children:an})]}),s.jsx("div",{ref:ae,className:"flex-1 min-w-0",children:s.jsx(vk,{ref:H,text:o[we]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:ie.select,onDismissSelection:ie.cancel})}),!z&&E.assistantRail&&s.jsx(Ck,{phase:ie.state.phase,transcript:ie.state.transcript,diff:ie.state.diff,editCount:ie.state.editCount,modelStatus:ie.state.modelStatus,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)},onReject:ie.cancel,onRetry:ie.retry})]}):Rt==="preview"&&cl(we)?s.jsxs("div",{className:"flex h-full",children:[W&&s.jsx(wk,{text:o[we]??"",scrollRef:H}),s.jsx("div",{ref:ae,className:"flex-1 min-w-0",children:s.jsx(vk,{ref:H,text:o[we]??"",wideMeasure:E.wideMeasure,onSelect:ie.select,onDismissSelection:ie.cancel})}),!z&&E.assistantRail&&s.jsx(Ck,{phase:ie.state.phase,transcript:ie.state.transcript,diff:ie.state.diff,editCount:ie.state.editCount,modelStatus:ie.state.modelStatus,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)},onReject:ie.cancel,onRetry:ie.retry})]}):Rt==="preview"&&iC(we)?s.jsx(bO,{path:we,dirty:!!r[we],reloadToken:b[we]??0}):Rt==="preview"&&lC(we)?s.jsx(CO,{path:we,text:o[we]??""}):Rt==="preview"&&cC(we)?s.jsx(NO,{path:we,text:o[we]??""}):cl(we)?s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(bk,{getEditor:Q}),s.jsx("div",{className:"flex-1 min-h-0",children:an})]}):an:null}),vt&&s.jsx(vO,{text:o[we]??"",cursor:$,language:zi(we)||void 0}),we&&cl(we)&&(Rt==="preview"||Rt==="split")&&ie.state.phase!=="idle"&&ie.state.selection&&s.jsx("div",{ref:oe,children:s.jsx(HO,{phase:ie.state.phase,rect:ie.state.selection.rect,diff:ie.state.diff,transcript:ie.state.transcript,modelStatus:ie.state.modelStatus,onQuickAction:ie.run,onRunCustom:ie.run,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onReject:ie.cancel,onRetry:ie.retry,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)}})}),C&&s.jsx(YO,{message:C.kind==="one"?`Discard unsaved changes to ${$x(C.path)}?`:C.kind==="others"?"Discard unsaved changes in the other open files?":C.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>N(null),onConfirm:ne})]})}function YO({message:e,onCancel:n,onConfirm:r}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:i=>{i.target===i.currentTarget&&n()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:e}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const Nk={ts:"#3178c6",tsx:"#61dafb",js:"#f7df1e",jsx:"#61dafb",cjs:"#f7df1e",mjs:"#f7df1e",json:"#5d5d5d",css:"#264de4",scss:"#cd6799",less:"#1d365d",html:"#e34c26",md:"#083fa1",mdx:"#083fa1",py:"#3776ab",go:"#00add8",rs:"#dea584",java:"#b07219",kt:"#a97bff",c:"#555555",cpp:"#f34b7d",cc:"#f34b7d",h:"#555555",hpp:"#f34b7d",swift:"#fa7343",rb:"#cc342d",php:"#4f5d95",sql:"#e38c00",sh:"#89e051",bash:"#89e051",zsh:"#89e051",yaml:"#cb171e",yml:"#cb171e",toml:"#9c4221",xml:"#0060ac",svg:"#ff9900",vue:"#41b883",svelte:"#ff3e00",other:"#6b7280"},JO={ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",cjs:"CommonJS",mjs:"ES Module",json:"JSON",css:"CSS",scss:"SCSS",less:"Less",html:"HTML",md:"Markdown",mdx:"MDX",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",c:"C",cpp:"C++",cc:"C++",h:"C/C++ Header",hpp:"C++ Header",swift:"Swift",rb:"Ruby",php:"PHP",sql:"SQL",sh:"Shell",bash:"Shell",zsh:"Shell",yaml:"YAML",yml:"YAML",toml:"TOML",xml:"XML",svg:"SVG",vue:"Vue",svelte:"Svelte",other:"Other"};function ab(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":String(e)}function QO({open:e,onClose:n,variant:r="overlay"}){const i=bt($=>$.tabs.find(R=>R.id===$.activeTabId)??null),o=(i==null?void 0:i.cwd)??null,[l,d]=L.useState(null),[u,h]=L.useState(!1),[m,x]=L.useState(null),g=L.useRef(null),v=L.useCallback(async $=>{h(!0),x(null);try{const R=await window.api.repo.analyze($);R.ok?d(R):(x(R.error||"Analysis failed"),d(null))}catch(R){x(R instanceof Error?R.message:String(R)),d(null)}finally{h(!1)}},[]);L.useEffect(()=>{if(e){if(!o){x("No active session — open a tab in a folder first.");return}v(o)}},[e,o,v]),L.useEffect(()=>{var R;if(!e)return;const $=O=>{O.key==="Escape"&&(O.stopPropagation(),n())};return window.addEventListener("keydown",$),(R=g.current)==null||R.focus(),()=>window.removeEventListener("keydown",$)},[e,n]);const S=L.useCallback(()=>{o&&v(o)},[o,v]),E=L.useMemo(()=>l?Object.entries(l.languageBreakdown).map(([R,O])=>[R,O.files,O.lines]).sort((R,O)=>O[1]-R[1]).slice(0,12):[],[l]),j=L.useMemo(()=>E.length===0?1:E[0][1],[E]),y=L.useMemo(()=>{if(!l)return[];const $=l.topDirectories;if($.length===0)return[];const R=$.map(I=>Math.sqrt(Math.max(1,I.fileCount))),O=R.reduce((I,z)=>I+z,0)||1;return $.map((I,z)=>({path:I.path,fileCount:I.fileCount,totalLines:I.totalLines,basis:R[z]/O*100}))},[l]);if(!e)return null;const b=$=>{$.target===$.currentTarget&&n()},_=o?o.split("/").filter(Boolean).pop()||o:"no folder",C=r==="page",N=s.jsx("div",{className:C?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:C?void 0:b,"data-testid":"repoviz-backdrop",children:s.jsxs("div",{ref:g,role:C?void 0:"dialog","aria-modal":C?void 0:"true","aria-label":"Repository Visualization",tabIndex:-1,className:C?"h-full w-full flex flex-col outline-none bg-bg":"bg-bg-elev border border-line rounded-lg shadow-xl w-[900px] max-w-[95vw] max-h-[85vh] flex flex-col outline-none","data-testid":"repoviz-dialog",children:[s.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-line",children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[s.jsx("span",{className:"text-lg","aria-hidden":!0,children:"🗺"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{className:"text-base font-medium text-fg leading-tight",children:"Repository Visualization"}),s.jsxs("div",{className:"text-xs text-fg-dim truncate",title:o??"",children:[_,(l==null?void 0:l.gitStatus.branch)&&s.jsxs("span",{className:"ml-2 font-mono text-fg-faint",children:["(",l.gitStatus.branch,")"]}),(l==null?void 0:l.truncated)&&s.jsx("span",{className:"ml-2 text-amber-400",children:"truncated"})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[l&&l.gitStatus.uncommitted>0&&s.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 text-[11px] font-mono",title:`${l.gitStatus.uncommitted} uncommitted files`,children:[l.gitStatus.uncommitted," uncommitted"]}),s.jsxs("button",{type:"button",onClick:S,disabled:u||!o,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs disabled:opacity-40 disabled:cursor-not-allowed",title:"Re-run analysis",children:[u?"…":"↻"," Refresh"]}),s.jsx("button",{type:"button",onClick:n,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs","aria-label":"Close",children:"✕"})]})]}),s.jsx("div",{className:"flex-1 overflow-y-auto p-5 space-y-6",children:u&&!l?s.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-fg-dim",children:[s.jsx("div",{className:"text-3xl mb-3 animate-pulse","aria-hidden":!0,children:"⟳"}),s.jsx("div",{className:"text-sm",children:"Analyzing repository…"}),s.jsx("div",{className:"text-xs text-fg-faint mt-1",children:"Walking files, counting lines, reading git status"})]}):m?s.jsxs("div",{className:"py-16 text-center",children:[s.jsx("div",{className:"text-3xl mb-3 text-red-400","aria-hidden":!0,children:"⚠"}),s.jsx("div",{className:"text-sm text-red-400",children:m})]}):l?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[s.jsx(lb,{label:"Files",value:ab(l.totalFiles)}),s.jsx(lb,{label:"Lines of code",value:ab(l.totalLines)}),s.jsx(lb,{label:"Uncommitted",value:String(l.gitStatus.uncommitted),tone:l.gitStatus.uncommitted>0?"warn":"neutral"})]}),s.jsxs("section",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Languages"}),E.length===0?s.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):s.jsx("div",{className:"space-y-1.5",children:E.map(([$,R,O])=>{const I=Nk[$]??Nk.other,z=JO[$]??$,U=R/j*100;return s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsx("span",{className:"w-24 text-fg-dim truncate",title:z,children:z}),s.jsx("div",{className:"flex-1 h-4 bg-bg rounded overflow-hidden",children:s.jsx("div",{className:"h-full rounded",style:{width:`${U}%`,backgroundColor:I}})}),s.jsxs("span",{className:"w-16 text-right text-fg-dim font-mono",children:[R," files"]}),s.jsxs("span",{className:"w-20 text-right text-fg-faint font-mono",children:[ab(O)," L"]})]},$)})})]}),s.jsxs("section",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Top directories"}),y.length===0?s.jsx("div",{className:"text-xs text-fg-dim",children:"No directories."}):s.jsx("div",{className:"flex flex-wrap gap-1 min-h-[140px]",children:y.map($=>s.jsxs("div",{className:"relative rounded bg-bg-hi border border-line hover:border-accent transition-colors cursor-default flex flex-col justify-end p-2 min-w-[80px] min-h-[60px]",style:{flexBasis:`${Math.max($.basis,6)}%`,flexGrow:$.basis>15?1:0},title:`${$.path} — ${$.fileCount} files, ${$.totalLines.toLocaleString()} lines`,children:[s.jsx("div",{className:"text-[11px] font-mono text-fg truncate",children:$.path}),s.jsxs("div",{className:"text-[10px] text-fg-dim font-mono",children:[$.fileCount," files"]})]},$.path))})]}),s.jsxs("div",{className:"text-[10px] text-fg-faint text-right",children:["Analyzed in ",l.durationMs,"ms",l.truncated&&" — stopped early (5000-file cap or 30s timeout)"]})]}):s.jsx("div",{className:"py-16 text-center text-fg-dim text-sm",children:"No analysis yet. Click Refresh."})})]})});return!C&&typeof document<"u"&&document.body?Hu.createPortal(N,document.body):N}function lb({label:e,value:n,tone:r="neutral"}){const i=r==="warn"?"text-amber-400":"text-fg";return s.jsxs("div",{className:"bg-bg-hi/40 border border-line rounded-lg p-3",children:[s.jsx("div",{className:`text-xl font-medium ${i}`,children:n}),s.jsx("div",{className:"text-xs text-fg-dim mt-0.5",children:e})]})}function qu({options:e,active:n,onChange:r}){return s.jsx("div",{className:"flex rounded border border-line overflow-hidden",children:e.map(({key:i,label:o})=>s.jsx("button",{onClick:()=>r(i),className:`px-2 py-0.5 text-xs ${n===i?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:o},i))})}const Tk=e=>/[/\\\-_.\s]/.test(e),$k=e=>e>="A"&&e<="Z";function ZO(e,n,r){if(!e)return{match:!0,score:0,matched:[]};const i=e.toLowerCase(),o=n.toLowerCase(),l=(r||n).toLowerCase(),d=n.split("/").pop()||n,u=d.toLowerCase();if(u===i)return{match:!0,score:1e3,matched:Array.from({length:d.length},(b,_)=>_)};if(u.startsWith(i))return{match:!0,score:900,matched:Array.from({length:e.length},(b,_)=>_)};let h=0;for(const b of l.split("/")){if(b===i)return{match:!0,score:800,matched:[]};b.startsWith(i)&&(h=Math.max(h,700))}const m=u.indexOf(i);if(m!==-1)return{match:!0,score:m===0||Tk(u[m-1])||$k(d[m])?650:600,matched:Array.from({length:e.length},(_,C)=>m+C)};if(l.includes(i))return{match:!0,score:Math.max(500,h),matched:[]};let x=0,g=0,v=0,S=-1,E=0;const j=[];for(let b=0;b<o.length&&x<i.length;b++)o[b]===i[x]&&(j.push(b),g+=10,S===b-1?(v++,g+=v*8):v=0,(b===0||Tk(o[b-1])||$k(n[b]))&&(E++,g+=15,b===0&&(g+=10)),S=b,x++);if(x!==i.length)return{match:!1,score:0,matched:[]};const y=Math.max(0,50-(o.length-i.length));if(g+=y,E>=i.length*.5&&(g+=30),j.length>1){const b=j[j.length-1]-j[0];b>i.length*3&&(g-=Math.min(50,(b-i.length*3)*2))}return{match:!0,score:Math.max(1,g),matched:j}}function cb(e,n){return e.startsWith(n+"/")?e.slice(n.length+1):e===n?"":e}function Ak(e){const n=e.lastIndexOf("/");return n<0?"":e.slice(0,n)}const Rk="session-manager.quickopen.recent",e5=8;function t5({open:e,onClose:n,variant:r="overlay"}){const i=bt(z=>z.tabs.find(U=>U.id===z.activeTabId)??null),o=(i==null?void 0:i.cwd)??"",[l,d]=L.useState(""),[u,h]=L.useState([]),[m,x]=L.useState(!1),[g,v]=L.useState(0),[S,E]=L.useState([]),j=L.useRef(null),y=L.useRef(null);L.useEffect(()=>{if(e)try{const z=localStorage.getItem(Rk);z&&E(JSON.parse(z))}catch{}},[e]),L.useEffect(()=>{if(!e){d(""),v(0);return}const z=setTimeout(()=>{var U;return(U=j.current)==null?void 0:U.focus()},0);return()=>clearTimeout(z)},[e]),L.useEffect(()=>{if(!e||!o)return;let z=!1;return x(!0),window.api.search.files(o,"",{limit:5e3}).then(U=>{if(!z){if(!U.ok){Le.error(`File search failed: ${U.error??"unknown error"}`),h([]);return}h(U.files)}}).catch(U=>{const W=U instanceof Error?U.message:String(U);dt.error("quick-open","search.files threw",{error:W}),Le.error(`File search failed: ${W}`),h([])}).finally(()=>{z||x(!1)}),()=>{z=!0}},[e,o]);const b=L.useMemo(()=>{if(!l.trim())return[...u].sort((Y,V)=>Y.name.localeCompare(V.name)).slice(0,100).map(Y=>({file:Y,score:0,matched:[]}));const z=l.trim(),U=[];for(const W of u){const Y=ZO(z,W.name,W.path);Y.match&&U.push({file:W,score:Y.score,matched:Y.matched})}return U.sort((W,Y)=>Y.score-W.score),U.slice(0,100)},[u,l]),_=L.useMemo(()=>l.trim()?[]:S.map(z=>u.find(U=>U.path===z)||null).filter(z=>z!==null).slice(0,5),[S,u,l]);L.useEffect(()=>{const z=_.length+b.length;g>=z&&v(Math.max(0,z-1))},[_.length,b.length,g]),L.useEffect(()=>{if(!y.current)return;const z=y.current.querySelector(`[data-row="${g}"]`);z&&z.scrollIntoView({block:"nearest"})},[g]);const C=L.useCallback(z=>{try{const V=[z,...S.filter(H=>H!==z)].slice(0,e5);E(V),localStorage.setItem(Rk,JSON.stringify(V))}catch{}const U=i==null?void 0:i.id;if(!U){Le.error("No active tab to receive file path");return}const Y=(o?cb(z,o):z)||z;try{window.api.pty.write({tabId:U,data:Y})}catch(V){const H=V instanceof Error?V.message:String(V);dt.error("quick-open","pty.write failed",{error:H}),Le.error(`Failed to write to terminal: ${H}`);return}n()},[i==null?void 0:i.id,o,S,n]),N=L.useCallback(z=>{const U=_.length+b.length;if(z.key==="Escape"){z.preventDefault(),n();return}if(z.key==="ArrowDown"){if(z.preventDefault(),U===0)return;v(W=>Math.min(U-1,W+1));return}if(z.key==="ArrowUp"){if(z.preventDefault(),U===0)return;v(W=>Math.max(0,W-1));return}if(z.key==="Enter"){if(z.preventDefault(),g<_.length){const V=_[g];V&&C(V.path);return}const W=g-_.length,Y=b[W];Y&&C(Y.file.path)}},[g,b,_,C,n]);if(!e)return null;const $=(z,U)=>{if(U.length===0)return z;const W=new Set(U);return z.split("").map((Y,V)=>s.jsx("span",{className:W.has(V)?"text-accent font-semibold":"",children:Y},V))};let R=-1;const O=r==="page",I=s.jsx("div",{className:O?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[12vh]",onClick:O?void 0:z=>{z.target===z.currentTarget&&n()},"data-testid":"quick-open-backdrop",children:s.jsxs("div",{role:O?void 0:"dialog","aria-modal":O?void 0:"true","aria-label":"Quick Open",className:O?"h-full w-full flex flex-col":"w-[640px] max-w-[90vw] max-h-[70vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"quick-open",onKeyDown:N,children:[s.jsx("div",{className:"border-b border-line p-2",children:s.jsx("input",{ref:j,type:"text",value:l,onChange:z=>{d(z.target.value),v(0)},placeholder:o?"Search files in this project…":"No active tab — open a terminal first",disabled:!o,spellCheck:!1,autoComplete:"off",className:"w-full bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search files"})}),s.jsx("div",{ref:y,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:m?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Loading…"}):o?_.length===0&&b.length===0?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:l?"No files match.":"No files found in this project."}):s.jsxs(s.Fragment,{children:[_.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim",children:"Recent"}),_.map(z=>{R++;const U=R,W=U===g;return s.jsxs("button",{"data-row":U,role:"option","aria-selected":W,onClick:()=>C(z.path),onMouseEnter:()=>v(U),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${W?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"truncate",children:z.name}),s.jsx("span",{className:"text-xs text-fg-dim truncate",children:cb(Ak(z.path),o)})]},`r:${z.path}`)})]}),b.length>0&&s.jsxs("div",{children:[_.length>0&&s.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim border-t border-line",children:"Files"}),b.map(({file:z,matched:U})=>{R++;const W=R,Y=W===g;return s.jsxs("button",{"data-row":W,role:"option","aria-selected":Y,onClick:()=>C(z.path),onMouseEnter:()=>v(W),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${Y?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"truncate",children:$(z.name,U)}),s.jsx("span",{className:"text-xs text-fg-dim truncate",children:cb(Ak(z.path),o)})]},z.path)})]})]}):s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable Quick Open."})}),s.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[s.jsxs("span",{children:[s.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert into terminal"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),s.jsxs("span",{children:[b.length+_.length," ",b.length+_.length===1?"file":"files"]})]})]})});return!O&&typeof document<"u"&&document.body?Hu.createPortal(I,document.body):I}function Mk(e,n){return e.startsWith(n+"/")?e.slice(n.length+1):e===n?"":e}function n5(e,n,r){if(!n)return e;const i=r?e:e.toLowerCase(),o=r?n:n.toLowerCase(),l=i.indexOf(o);return l<0?e:s.jsxs(s.Fragment,{children:[e.slice(0,l),s.jsx("span",{className:"text-accent font-semibold",children:e.slice(l,l+n.length)}),e.slice(l+n.length)]})}function r5({open:e,onClose:n,variant:r="overlay"}){const i=bt(V=>V.tabs.find(H=>H.id===V.activeTabId)??null),o=(i==null?void 0:i.cwd)??"",[l,d]=L.useState(""),[u,h]=L.useState(!1),[m,x]=L.useState([]),[g,v]=L.useState(!1),[S,E]=L.useState(null),[j,y]=L.useState(0),[b,_]=L.useState(null),C=L.useRef(null),N=L.useRef(null),$=L.useRef(0);L.useEffect(()=>{if(!e){d(""),x([]),E(null),y(0);return}const V=setTimeout(()=>{var H;return(H=C.current)==null?void 0:H.focus()},0);return()=>clearTimeout(V)},[e]),L.useEffect(()=>{if(!e||!o)return;const V=l.trim();if(!V){x([]),E(null),v(!1);return}const H=++$.current;v(!0);const te=setTimeout(()=>{window.api.search.text(o,V,{caseSensitive:u,limit:500}).then(ae=>{H===$.current&&(ae.ok?(x(ae.matches),E(null)):(E(ae.error??"unknown error"),x([])),_(ae.usedRipgrep))}).catch(ae=>{if(H!==$.current)return;const oe=ae instanceof Error?ae.message:String(ae);dt.error("global-search","search.text threw",{error:oe}),E(oe),x([])}).finally(()=>{H===$.current&&v(!1)})},250);return()=>clearTimeout(te)},[e,o,l,u]);const R=L.useMemo(()=>{const V=new Map;for(const te of m){const ae=V.get(te.path);ae?ae.push(te):V.set(te.path,[te])}const H=[];for(const[te,ae]of V)H.push({path:te,matches:ae});return H.sort((te,ae)=>ae.matches.length-te.matches.length||te.path.localeCompare(ae.path)),H},[m]),O=L.useMemo(()=>m,[m]);L.useEffect(()=>{j>=O.length&&y(Math.max(0,O.length-1))},[O.length,j]),L.useEffect(()=>{if(!N.current)return;const V=N.current.querySelector(`[data-match="${j}"]`);V&&V.scrollIntoView({block:"nearest"})},[j]);const I=L.useCallback(V=>{const H=i==null?void 0:i.id;if(!H){Le.error("No active tab to receive path");return}const ae=`${(o?Mk(V.path,o):V.path)||V.path}:${V.line}`;try{window.api.pty.write({tabId:H,data:ae})}catch(oe){const ie=oe instanceof Error?oe.message:String(oe);dt.error("global-search","pty.write failed",{error:ie}),Le.error(`Failed to write to terminal: ${ie}`);return}n()},[i==null?void 0:i.id,o,n]),z=L.useCallback(V=>{if(V.key==="Escape"){V.preventDefault(),n();return}if(V.key==="ArrowDown"){if(V.preventDefault(),O.length===0)return;y(H=>Math.min(O.length-1,H+1));return}if(V.key==="ArrowUp"){if(V.preventDefault(),O.length===0)return;y(H=>Math.max(0,H-1));return}if(V.key==="Enter"){V.preventDefault();const H=O[j];H&&I(H)}},[O,j,I,n]);if(!e)return null;const U=r==="page";let W=-1;const Y=s.jsx("div",{className:U?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[8vh]",onClick:U?void 0:V=>{V.target===V.currentTarget&&n()},"data-testid":"global-search-backdrop",children:s.jsxs("div",{role:U?void 0:"dialog","aria-modal":U?void 0:"true","aria-label":"Search in project",className:U?"h-full w-full flex flex-col":"w-[840px] max-w-[95vw] h-[80vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"global-search",onKeyDown:z,children:[s.jsxs("div",{className:"border-b border-line p-2 flex items-center gap-2",children:[s.jsx("input",{ref:C,type:"text",value:l,onChange:V=>{d(V.target.value),y(0)},placeholder:o?"Search in this project…":"No active tab — open a terminal first",disabled:!o,spellCheck:!1,autoComplete:"off",className:"flex-1 bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search query"}),s.jsx("button",{type:"button",onClick:()=>h(V=>!V),className:`px-2 py-1 text-xs rounded border ${u?"bg-accent/20 border-accent text-accent":"bg-bg border-line text-fg-dim hover:text-fg"}`,title:"Match case","aria-pressed":u,children:"Aa"})]}),s.jsx("div",{ref:N,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:o?l.trim()?g?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Searching…"}):S?s.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:S}):O.length===0?s.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["No matches for ",JSON.stringify(l),"."]}):s.jsx("div",{children:R.map(V=>s.jsxs("div",{children:[s.jsxs("div",{className:"sticky top-0 bg-bg-elev border-b border-line px-3 py-1 text-xs text-fg-dim font-mono truncate",children:[Mk(V.path,o)," ",s.jsxs("span",{className:"text-fg-faint",children:["(",V.matches.length,")"]})]}),V.matches.map(H=>{W++;const te=W,ae=te===j;return s.jsxs("button",{"data-match":te,role:"option","aria-selected":ae,onClick:()=>I(H),onMouseEnter:()=>y(te),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${ae?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"text-fg-dim shrink-0 w-12 text-right",children:H.line}),s.jsx("span",{className:"truncate",children:n5(H.text,l,u)})]},`${H.path}:${H.line}:${H.column}:${te}`)})]},V.path))}):s.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["Type to search files in ",s.jsx("span",{className:"font-mono",children:o}),"."]}):s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable project search."})}),s.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[s.jsxs("span",{children:[s.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert path"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),s.jsxs("span",{children:[O.length," ",O.length===1?"match":"matches",b===!1&&" · fs walk (rg missing)"]})]})]})});return!U&&typeof document<"u"&&document.body?Hu.createPortal(Y,document.body):Y}const s5=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function i5({open:e,onClose:n,variant:r="page",initialMode:i="files"}){const[o,l]=L.useState(i);return L.useEffect(()=>{l(i)},[i]),e?s.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[s.jsxs("div",{className:"shrink-0 flex items-center gap-3 px-3 py-2 border-b border-line",children:[s.jsx(qu,{options:s5,active:o,onChange:l}),s.jsx("span",{className:"text-[11px] text-fg-faint",children:o==="files"?"⌘P · fuzzy-find a file in the active project":"⌘⇧F · ripgrep across the active project"})]}),s.jsx("div",{className:"flex-1 min-h-0",children:o==="files"?s.jsx(t5,{open:!0,onClose:n,variant:"page"}):s.jsx(r5,{open:!0,onClose:n,variant:"page"})})]}):null}class bj extends L.Component{constructor(){super(...arguments);Fn(this,"state",{error:null});Fn(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(r){return{error:r}}componentDidCatch(r,i){console.error("[ErrorBoundary]",r,i)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):s.jsxs("div",{className:"p-6 text-xs",children:[s.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),s.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),s.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}function o5({open:e,onClose:n,title:r,children:i,variant:o="overlay"}){return s.jsxs(Wu,{open:e,onClose:n,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:o,children:[o==="overlay"&&s.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[s.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:r}),s.jsx("button",{type:"button",onClick:n,"aria-label":"Close",className:"px-2 py-0.5 text-fg-dim hover:text-fg hover:bg-bg-hi rounded text-base leading-none",children:"✕"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:s.jsx(bj,{children:i})})]})}function a5(e){return/^monitor of /i.test(e.trim())}function Ik(e){return e.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Pk(e,n,r){if(e){const d=r.find(u=>u.deviceId===e);if(d)return d}if(!n)return null;const i=r.filter(d=>d.label===n);if(i.length===1)return i[0];if(i.length>1)return null;const o=Ik(n),l=r.filter(d=>d.label&&Ik(d.label)===o);return l.length===1?l[0]:null}async function Dk(e){var r;return(r=navigator.mediaDevices)!=null&&r.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(i=>!(i.kind!=="audioinput"||i.label&&a5(i.label))):[]}const Ok=!1;function wj(){const e=$t(m=>m.isRecording);$t(m=>m.startRecording),$t(m=>m.stopRecording);const[n,r]=L.useState([]),[i,o]=L.useState(null),[l,d]=L.useState(null);L.useEffect(()=>{let m=!1;return(async()=>{try{const x=await window.api.voice.getDevicePref();if(m)return;const g=await Dk(Ok);if(m)return;r(g),d(x.selectedLabel);const v=Pk(x.selectedDeviceId,x.selectedLabel,g);v?(o(v.deviceId),x.selectedDeviceId&&v.deviceId!==x.selectedDeviceId&&(dt.info("voice","device-picker rebind-by-label",{fromIdPrefix:x.selectedDeviceId.slice(0,8),toIdPrefix:v.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:v.deviceId,selectedLabel:v.label||x.selectedLabel}).catch(()=>{}))):((x.selectedDeviceId||x.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:x.selectedLabel,hadId:!!x.selectedDeviceId}),dt.warn("voice","device-picker selected-unavailable",{hadId:!!x.selectedDeviceId})),o(null))}catch(x){dt.warn("voice","device-picker init failed",{error:x instanceof Error?x.message:String(x)})}})(),()=>{m=!0}},[]);const u=L.useCallback(async()=>{try{const m=await Dk(Ok);if(r(m),i&&!m.some(x=>x.deviceId===i)){const x=Pk(null,l,m);x?(o(x.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:x.deviceId,selectedLabel:x.label||l}).catch(()=>{})):o(null)}}catch(m){dt.warn("voice","device-picker refresh failed",{error:m instanceof Error?m.message:String(m)})}},[i,l]);L.useEffect(()=>{const m=()=>{u()};return window.addEventListener("mic-device-change",m),()=>window.removeEventListener("mic-device-change",m)},[u]);const h=async m=>{var S;const x=m.target.value,g=x===""?null:x,v=g?((S=n.find(E=>E.deviceId===g))==null?void 0:S.label)??null:null;o(g),d(v);try{await window.api.voice.setDevicePref({selectedDeviceId:g,selectedLabel:v}),dt.info("voice","device-picker selected",{deviceIdPrefix:g?g.slice(0,8):null})}catch(E){dt.warn("voice","setDevicePref failed",{error:E instanceof Error?E.message:String(E)})}if(e)try{await $t.getState().restartWithDevice()}catch(E){dt.warn("voice","device-picker restart failed",{error:E instanceof Error?E.message:String(E)})}};return s.jsxs("select",{value:i??"",onChange:h,onFocus:()=>{u()},title:"Microphone input device","data-testid":"mic-device-picker",className:"text-[10px] bg-bg border border-line text-fg-dim hover:text-fg rounded px-1.5 py-1 max-w-[8rem] truncate",children:[s.jsx("option",{value:"",children:"Default"}),n.map(m=>s.jsx("option",{value:m.deviceId,children:m.label||`Mic ${m.deviceId.slice(0,6)}`},m.deviceId))]})}function l5(){const e=$t(S=>S.isRecording),n=$t(S=>S.levelMeterEnabled),[r,i]=L.useState(0),[o,l]=L.useState(0),d=L.useRef(0);d.current=o;const[u,h]=L.useState(0),[m,x]=L.useState(!1),g=L.useRef(null);if(L.useEffect(()=>{if(!e||!n){i(0),l(0);return}let S=0,E=!1,j=null,y=null;const b=()=>{if(E)return;const C=y??X2();if(!C){S=requestAnimationFrame(b);return}y!==C&&(y=C,j=new Uint8Array(new ArrayBuffer(C.fftSize)));const N=j;C.getByteTimeDomainData(N);let $=0;for(let z=0;z<N.length;z++){const U=N[z]-128;$+=U*U}const R=Math.sqrt($/N.length)/128,O=R>0?20*Math.log10(R):-60,I=Math.max(0,Math.min(1,(O+60)/60));l(R),i(I),R>=.95&&(x(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>x(!1),150)),S=requestAnimationFrame(b)};S=requestAnimationFrame(b);const _=setInterval(()=>{E||h(Math.round(d.current*100))},250);return()=>{E=!0,cancelAnimationFrame(S),clearInterval(_),g.current&&(clearTimeout(g.current),g.current=null)}},[e,n]),!e||!n)return null;const v=m?"bg-red-500":o>=.7?"bg-amber-400":"bg-green-500";return s.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":u,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${m?"ring-1 ring-red-500":""}`,children:s.jsx("div",{className:`h-full ${v} transition-[width] duration-75 ease-out`,style:{width:`${r*100}%`}})})}function c5({open:e,onClose:n,variant:r="overlay"}){return s.jsx(o5,{open:e,onClose:n,title:"Voice / Microphone",variant:r,children:s.jsxs("div",{className:"p-4 space-y-4",children:[s.jsx(f5,{}),s.jsx(zC,{}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(J2,{}),s.jsx(wj,{}),s.jsx(QT,{})]}),s.jsx(u5,{}),s.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[s.jsx("button",{type:"button",onClick:()=>$t.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),s.jsx(h5,{})]}),s.jsx(l5,{})]})})}function u5(){const e=$t(l=>l.isRecording),[n,r]=L.useState(null);if(L.useEffect(()=>{let l=!1;window.api.voice.getHotkeyConfig().then(u=>{l||r(u)}).catch(()=>{});const d=window.api.voice.onHotkeyConfigChanged(u=>r(u));return()=>{l=!0,d()}},[]),e||!n)return null;const i=n.mode==="hold"?"Hold":"Press",o=d5(n.accelerator);return s.jsxs("div",{className:"text-[11px] text-fg-faint",children:[s.jsxs("span",{children:[i," "]}),s.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:o}),s.jsx("span",{children:" to record"})]})}function d5(e){const n=typeof navigator<"u"&&/Mac/.test(navigator.platform);return e.replace(/CommandOrControl/g,n?"⌘":"Ctrl").replace(/CmdOrCtrl/g,n?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,n?"⌥":"Alt").replace(/Shift/g,n?"⇧":"Shift")}function h5(){const[e,n]=L.useState(null);if(L.useEffect(()=>{let i=!1;window.api.voice.getHotkeyConfig().then(l=>{i||n(l)}).catch(l=>dt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const o=window.api.voice.onHotkeyConfigChanged(l=>{n(l)});return()=>{i=!0,o()}},[]),!e)return null;const r=async i=>{if(e.mode===i)return;const o={...e,mode:i};n(o);try{await window.api.voice.setHotkeyConfig(o)}catch(l){dt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return s.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-fg-faint select-none",title:"Mic hotkey behavior. Tap on/off: press once to start, again to stop. Hold to talk: record only while held (push-to-talk).",children:[s.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[s.jsx("input",{type:"radio",name:"hotkey-mode",checked:e.mode==="toggle",onChange:()=>r("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),s.jsx("span",{children:"Tap on/off"})]}),s.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[s.jsx("input",{type:"radio",name:"hotkey-mode",checked:e.mode==="hold",onChange:()=>r("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),s.jsx("span",{children:"Hold to talk"})]})]})}function f5(){const e=$t(l=>l.isRecording),n=$t(l=>l.lastTranscript),r=$t(l=>l.error),i=$t(l=>l.modelStatus),o=$t(l=>l.loadingProgress);return r?s.jsxs("div",{className:"text-[11px] text-red-400",title:r,children:["⚠ ",r]}):e?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[s.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),s.jsx("span",{className:"truncate",title:n,children:n||"Listening…"})]}):i==="loading"?s.jsxs("div",{className:"text-[11px] text-fg-faint",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("span",{children:"Loading speech model"}),s.jsxs("span",{className:"font-mono",children:[o,"%"]})]}),s.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:s.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${o}%`}})})]}):null}let ub=null;function p5(){return ub||(ub=Jm(()=>import("./monaco-editor-BW5C4Iv1.js").then(e=>e.b),__vite__mapDeps([1,2]),import.meta.url).then(e=>(f0.config({monaco:e}),e))),ub}function _j({value:e,onChange:n,path:r,readOnly:i}){const o=L.useRef(null),l=d=>{o.current=d};return s.jsx(p0,{path:`file://${r}`,defaultLanguage:"json",value:e,onChange:d=>n(d??""),onMount:l,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:i,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let Lk=!1;async function m5(e){if(Lk)return;const n=await p5(),r=await Promise.all(e.map(async o=>{let l=o.schema;if(!l){const d=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const u=new URL(o.uri).origin;if(!d.includes(u))throw new Error("untrusted origin");const h=await fetch(o.uri);h.ok&&(l=await h.json())}catch{}}return{uri:o.uri,fileMatch:o.fileMatch,schema:l}}));n.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:r.filter(o=>o.schema),enableSchemaRequest:!0}),Lk=!0}function b0({node:e,targetScope:n,onOverride:r,schema:i,rootLabel:o}){const[l,d]=L.useState(""),[u,h]=L.useState(!0),m=[],x=e.kind==="object"&&Object.keys(e.children).length===0,v=((i==null?void 0:i.rootKeys())??[]).length>0;return s.jsxs("div",{className:"h-full flex flex-col",children:[s.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:[s.jsxs("span",{className:"text-fg-faint",children:["merged · overrides → ",s.jsx("span",{className:"text-fg-dim",children:os[n].label})]}),v&&s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:S=>h(S.target.checked),className:"accent-accent"}),"show unset keys"]}),s.jsx("div",{className:"flex-1"}),s.jsx("input",{value:l,onChange:S=>d(S.target.value),placeholder:"filter keys or descriptions…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-56"})]}),s.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 font-mono text-xs",children:x&&!u?s.jsx("div",{className:"text-fg-faint italic px-2 py-4",children:"no settings resolved — all scope files empty or missing"}):s.jsx(kj,{node:e,path:m,label:o??"(root)",targetScope:n,onOverride:r,filter:l,depth:0,schema:i,showGhosts:u,defaultOpen:!0})})]})}function kj(e){return e.node.kind==="object"?s.jsx(g5,{...e,node:e.node}):e.node.kind==="array"?s.jsx(x5,{...e,node:e.node}):s.jsx(y5,{...e,node:e.node})}function zk(e,n){return n.trim()?e.toLowerCase().includes(n.toLowerCase()):!0}function Zh(e,n,r){return!!(!r.trim()||e.some(i=>zk(i,r))||n!=null&&n.description&&zk(n.description,r))}function g5({node:e,path:n,label:r,targetScope:i,onOverride:o,filter:l,depth:d,schema:u,showGhosts:h,defaultOpen:m}){const[x,g]=L.useState(m??d<2),v=(u==null?void 0:u.at(n))??null,S=new Set(Object.keys(e.children)),E=h?(v==null?void 0:v.knownChildren)??[]:[],j=Array.from(new Set([...S,...E])).sort(),y=L.useMemo(()=>l.trim()?j.filter(_=>{const C=(u==null?void 0:u.at([...n,_]))??null;return Zh([...n,_],C,l)?!0:S.has(_)?Sj(e.children[_],[...n,_],l,u):!1}):j,[j.join(","),l,e,n.join("."),u]);if(l.trim()&&y.length===0&&!Zh(n,v,l))return null;if(n.length===0)return s.jsx("div",{children:y.map(_=>b(_))});return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:d*14},onClick:()=>g(!x),children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:x?"▾":"▸"}),s.jsx("span",{className:"text-fg",children:r}),s.jsxs("span",{className:"text-fg-faint",children:[" {",S.size,E.length>S.size?`/${new Set([...S,...E]).size}`:"","}"]}),(v==null?void 0:v.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:v.description,children:["— ",v.description]})]}),x&&y.map(_=>b(_))]});function b(_){if(S.has(_))return s.jsx(kj,{node:e.children[_],path:[...n,_],label:_,targetScope:i,onOverride:o,filter:l,depth:d+1,schema:u,showGhosts:h},_);const C=(u==null?void 0:u.at([...n,_]))??null;return C?s.jsx(v5,{path:[...n,_],label:_,info:C,targetScope:i,onSet:o,depth:d+1,filter:l},_):null}}function Sj(e,n,r,i){const o=(i==null?void 0:i.at(n))??null;if(Zh(n,o,r))return!0;if(e.kind!=="object")return!1;for(const l of Object.keys(e.children))if(Sj(e.children[l],[...n,l],r,i))return!0;return!1}function x5({node:e,path:n,label:r,filter:i,depth:o,schema:l}){const[d,u]=L.useState(!0),h=(l==null?void 0:l.at(n))??null;return Zh(n,h,i)?s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:o*14},onClick:()=>u(!d),children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:d?"▾":"▸"}),s.jsx("span",{className:"text-fg",children:r}),s.jsxs("span",{className:"text-fg-faint",children:[" [",e.items.length,"]"]}),s.jsx(Hm,{tone:"warn",children:"accumulated"}),(h==null?void 0:h.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:h.description,children:["— ",h.description]})]}),d&&e.items.map((m,x)=>s.jsxs("div",{className:"flex items-start gap-2 py-0.5",style:{paddingLeft:(o+1)*14},children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0"}),s.jsxs("span",{className:"text-fg-faint",children:[x,":"]}),s.jsx("span",{className:"text-fg-dim truncate max-w-xl",children:$y(m.value)}),s.jsx(vw,{scope:m.fromScope})]},x))]}):null}function y5({node:e,path:n,label:r,targetScope:i,onOverride:o,filter:l,depth:d,schema:u}){const[h,m]=L.useState(!1),x=(u==null?void 0:u.at(n))??null;if(!Zh(n,x,l))return null;const g=e.winner!==i,v=e.shadowed.length>0;return s.jsxs("div",{children:[s.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded",style:{paddingLeft:d*14},children:[s.jsx("span",{className:`w-3 shrink-0 ${v?"text-fg-faint cursor-pointer":""}`,onClick:()=>v&&m(!h),children:v?h?"▾":"▸":""}),s.jsxs("span",{className:"text-fg",children:[r,":"]}),s.jsx("span",{className:"text-fg-dim truncate max-w-md",children:$y(e.value)}),s.jsx(vw,{scope:e.winner}),(x==null?void 0:x.deprecated)&&s.jsx(Hm,{tone:"warn",children:"deprecated"}),(x==null?void 0:x.default)!==void 0&&b5(e.value,x.default)&&s.jsx(Hm,{tone:"dim",children:"= default"}),e.typeMismatch&&s.jsx("span",{className:"text-yellow-500/80",title:"shadowed scopes have a different value type",children:"⚠"}),(x==null?void 0:x.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:x.description,children:["— ",x.description]}),s.jsx("div",{className:"flex-1"}),(x==null?void 0:x.enum)&&s.jsx(Cj,{values:x.enum}),s.jsx("button",{disabled:!g,onClick:()=>o(n,e.value),className:`opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border rounded transition-opacity ${g?"border-accent/50 text-accent hover:bg-accent hover:text-bg":"border-line text-fg-faint cursor-not-allowed"}`,title:g?`copy into ${os[i].label} draft`:`already winning in ${os[i].label}`,children:"override"})]}),h&&e.shadowed.map((S,E)=>s.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(d+1)*14+12},children:[s.jsx("span",{children:"shadowed:"}),s.jsx("span",{className:"truncate max-w-xl",children:$y(S.value)}),s.jsx(vw,{scope:S.scope,dim:!0})]},E))]})}function v5({path:e,label:n,info:r,targetScope:i,onSet:o,depth:l,filter:d}){if(!Zh(e,r,d))return null;const u=r.default!==void 0?r.default:w5(r.type),h=Array.isArray(r.type)?r.type.join("|"):r.type??"?";return s.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded opacity-60",style:{paddingLeft:l*14},children:[s.jsx("span",{className:"w-3 shrink-0"}),s.jsx("span",{className:"text-fg-dim",children:n}),s.jsx(Hm,{tone:"dim",children:h}),r.required&&s.jsx(Hm,{tone:"warn",children:"required"}),r.default!==void 0&&s.jsxs("span",{className:"text-fg-faint",children:["default: ",$y(r.default)]}),r.description&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:r.description,children:["— ",r.description]}),s.jsx("div",{className:"flex-1"}),r.enum&&s.jsx(Cj,{values:r.enum}),s.jsx("button",{onClick:()=>o(e,u),className:"opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg transition-opacity",title:`write to ${os[i].label} draft`,children:"set"})]})}function b5(e,n){return e===n?!0:typeof e!=typeof n?!1:e&&n&&typeof e=="object"?JSON.stringify(e)===JSON.stringify(n):!1}function w5(e){switch(Array.isArray(e)?e[0]:e){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};case"null":return null;default:return null}}function $y(e){if(typeof e=="string")return JSON.stringify(e);if(e===null)return"null";if(typeof e=="object"){const n=JSON.stringify(e);return n.length>100?n.slice(0,100)+"…":n}return String(e)}function vw({scope:e,dim:n}){const r=e==="user"?"bg-bg-hi text-fg-dim border-line":e==="project"?"bg-blue-950/30 text-blue-400/80 border-blue-900/40":"bg-purple-950/30 text-purple-400/80 border-purple-900/40";return s.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${r} ${n?"opacity-60":""}`,children:os[e].label})}function Hm({children:e,tone:n="default"}){const r={default:"bg-bg-hi text-fg-dim border-line",warn:"bg-yellow-950/30 text-yellow-500/80 border-yellow-900/40",dim:"bg-bg-elev text-fg-faint border-line"}[n];return s.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${r}`,children:e})}function Cj({values:e}){const n=e.map(r=>String(r)).join(" | ");return s.jsxs("span",{className:"text-[10px] text-fg-faint truncate max-w-xs",title:`allowed: ${n}`,children:["∈ ",n.length>30?n.slice(0,30)+"…":n]})}const _5=[{id:"essentials",title:"Essentials",summary:"The knobs you reach for first.",keys:["model","language","outputStyle","permissions"]},{id:"git",title:"Git & Commits",summary:"How Claude writes commits and pull requests on your behalf.",keys:["attribution","includeGitInstructions","includeCoAuthoredBy"]},{id:"memory",title:"Memory & Plans",summary:"Context Claude keeps between sessions and where it files plans.",keys:["autoMemoryEnabled","plansDirectory","claudeMdExcludes","respectGitignore"]},{id:"model",title:"Model & Reasoning",summary:"Which model runs, how hard it thinks, and fast-mode toggles.",keys:["availableModels","modelOverrides","effortLevel","fastMode","fastModePerSessionOptIn","alwaysThinkingEnabled"]},{id:"interface",title:"Interface",summary:"Visual polish — spinners, progress bars, motion.",keys:["spinnerTipsEnabled","spinnerTipsOverride","spinnerVerbs","terminalProgressBarEnabled","showTurnDuration","prefersReducedMotion","companyAnnouncements","statusLine","teammateMode"]},{id:"updates",title:"Updates & Cleanup",summary:"Release channel and how long transcripts stick around.",keys:["autoUpdatesChannel","cleanupPeriodDays"]},{id:"env",title:"Environment & Auth",summary:"Environment variables and auth-helper scripts.",keys:["env","apiKeyHelper","awsCredentialExport","awsAuthRefresh"]},{id:"hooks",title:"Hooks",summary:"Scripts Claude runs before/after tool use.",keys:["hooks","disableAllHooks","allowedHttpHookUrls","httpHookAllowedEnvVars"]},{id:"mcp",title:"MCP Servers",summary:"External tool providers Claude can talk to.",keys:["enableAllProjectMcpServers","enabledMcpjsonServers","disabledMcpjsonServers"]},{id:"plugins",title:"Plugins",summary:"Installed plugins, marketplaces, and per-plugin configuration.",keys:["enabledPlugins","extraKnownMarketplaces","skippedPlugins","skippedMarketplaces","pluginConfigs"]},{id:"filesystem",title:"File Picker & Sandbox",summary:"How Claude browses files and the sandbox it runs in.",keys:["fileSuggestion","sandbox","worktree"]},{id:"login",title:"Login",summary:"Which login method to force on startup.",keys:["forceLoginMethod","forceLoginOrgUUID"]},{id:"feedback",title:"Feedback",summary:"Session-quality surveys.",keys:["feedbackSurveyRate"]},{id:"advanced",title:"Advanced / Enterprise",summary:"Managed-settings-only keys and enterprise allow/denylists.",advanced:!0,keys:["allowedMcpServers","deniedMcpServers","allowManagedHooksOnly","allowManagedPermissionRulesOnly","allowManagedMcpServersOnly","strictKnownMarketplaces","blockedMarketplaces","pluginTrustMessage","otelHeadersHelper","skipWebFetchPreflight"]}],k5={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function jj(e){return e.replace(/^\$/,"").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(Boolean).map((i,o)=>{const l=k5[i];return l||(o===0?i.charAt(0).toUpperCase()+i.slice(1):i)}).join(" ")}function Ej(e){const n=new Set,r=[];for(const o of _5){const l=o.keys.filter(d=>e.has(d));l.forEach(d=>n.add(d)),l.length!==0&&r.push({id:o.id,title:o.title,summary:o.summary,advanced:!!o.advanced,keys:l})}const i=Array.from(e).filter(o=>!n.has(o)&&o!=="$schema").sort();return i.length>0&&r.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:i}),r}function S5(e,n){return Ej(e).map(r=>({id:r.id,title:r.title,advanced:r.advanced,total:r.keys.length,setCount:r.keys.filter(i=>n.has(i)).length}))}const C5={};function Nj(e,n){if(n)return{text:n,authored:!1};const r=C5[e];return r?{text:r,authored:!0}:null}const j5={essentials:"star",git:"link",memory:"memory",model:"sparkle",interface:"eye",updates:"reload",env:"keys",hooks:"hooks",mcp:"mcp",plugins:"plugins",filesystem:"folder",login:"lock",feedback:"send",advanced:"shield",other:"dot"},E5=["user","project","local","default"],N5={user:"user",project:"project",local:"local",default:"default"};function T5({node:e,targetScope:n,onOverride:r,schema:i}){const[o,l]=L.useState(""),[d,u]=L.useState(!1),[h,m]=L.useState(!0),x=e.kind==="object"?e:null,g=x?Object.keys(x.children):[],v=i.rootKeys(),S=new Set([...g,...v]),E=L.useMemo(()=>Ej(S),[Array.from(S).sort().join(",")]),j=L.useMemo(()=>S5(S,new Set(g)),[Array.from(S).sort().join(","),g.join(",")]),[y,b]=L.useState(null),_=N=>{const $=E.find(R=>R.id===N);$!=null&&$.advanced&&!d&&u(!0),b(N)};L.useEffect(()=>{if(!y)return;const N=document.getElementById(`settings-group-${y}`);N&&(N.scrollIntoView({behavior:"smooth",block:"start"}),b(null))});const C=L.useMemo(()=>E.filter(N=>d||!N.advanced).map(N=>({...N,keys:N.keys.filter($=>{const R=(x==null?void 0:x.children[$])!==void 0;if(!h&&!R)return!1;if(!o.trim())return!0;const O=i.at([$]);return[$,jj($),(O==null?void 0:O.description)??""].join(" ").toLowerCase().includes(o.toLowerCase())})})).filter(N=>N.keys.length>0),[E,o,d,h,x,i]);return s.jsxs("div",{className:"h-full flex flex-col",children:[s.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-3 text-xs",children:[s.jsxs("span",{className:"text-fg-faint",children:["writing overrides to"," ",s.jsx("span",{className:"text-fg-dim font-medium",children:os[n].label})]}),s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:h,onChange:N=>m(N.target.checked),className:"accent-accent"}),"show not-yet-configured"]}),s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:d,onChange:N=>u(N.target.checked),className:"accent-accent"}),"show advanced"]}),s.jsx("div",{className:"flex-1"}),s.jsx("input",{value:o,onChange:N=>l(N.target.value),placeholder:"search settings…",className:"bg-bg border border-line rounded px-2 py-1 text-xs text-fg w-64"})]}),s.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[s.jsx($5,{groups:j,onJump:_}),s.jsxs("div",{className:"flex-1 overflow-auto py-3",children:[C.map(N=>s.jsx(A5,{id:N.id,title:N.title,summary:N.summary,advanced:N.advanced,children:N.keys.map($=>{const R=x==null?void 0:x.children[$],O=i.at([$]);return s.jsx(R5,{keyName:$,node:R,info:O,targetScope:n,onOverride:(I,z)=>r([$],I,z)},$)})},N.id)),C.length===0&&s.jsxs("div",{className:"px-6 py-12 text-center text-fg-faint text-sm",children:['no settings match "',o,'"']})]})]})]})}function $5({groups:e,onJump:n}){return s.jsx("nav",{className:"shrink-0 w-48 border-r border-line bg-bg-elev/30 overflow-y-auto py-3",children:e.map(r=>s.jsxs("button",{onClick:()=>n(r.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${r.title}`,children:[s.jsx(dn,{name:j5[r.id]??"dot",size:15,className:"text-fg-faint shrink-0"}),s.jsx("span",{className:"flex-1 min-w-0 truncate text-xs text-fg-dim",children:r.title}),s.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[r.setCount,"/",r.total]})]},r.id))})}function A5({id:e,title:n,summary:r,advanced:i,children:o}){const[l,d]=L.useState(!0);return s.jsxs("section",{id:`settings-group-${e}`,className:"mx-4 mb-4 rounded-lg border border-line shadow-sm bg-bg-elev/50 overflow-hidden",children:[s.jsxs("header",{className:"px-4 py-3 bg-bg-elev cursor-pointer hover:bg-bg-hi flex items-center gap-3 border-b border-line",onClick:()=>d(!l),children:[s.jsx("span",{className:"text-fg-faint w-3",children:l?"▾":"▸"}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h2",{className:"text-fg text-base font-semibold",children:n}),i&&s.jsx("span",{className:"text-[9px] px-1.5 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"advanced"})]}),s.jsx("p",{className:"text-fg-dim text-sm mt-0.5",children:r})]})]}),l&&s.jsx("div",{className:"divide-y divide-line/60",children:o})]})}function R5({keyName:e,node:n,info:r,targetScope:i,onOverride:o}){const[l,d]=L.useState(!1),[u,h]=L.useState(!1),m=jj(e),x=n!==void 0,v=(n==null?void 0:n.kind)==="leaf"?n:null,S=(n==null?void 0:n.kind)==="object"||(n==null?void 0:n.kind)==="array",E=r==null?void 0:r.default,j=v&&E!==void 0&&$j(v.value,E),y=B5({isSet:x,leafNode:v,defaultVal:E,isDefault:!!j,node:n}),b=M5(v,E),_=b.length>=2,C=!!v&&!j,N=Nj(e,r==null?void 0:r.description);return s.jsx("div",{className:"px-4 py-3 hover:bg-bg-elev/20",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("button",{onClick:()=>d(!l),className:"text-fg-faint hover:text-fg w-3 mt-0.5",title:l?"collapse":"expand",children:l?"▾":"▸"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[s.jsx("h3",{className:"text-fg text-sm",children:m}),s.jsx(F5,{kind:y.kind,label:y.label}),_&&s.jsxs("button",{onClick:$=>{$.stopPropagation(),l||d(!0),h(R=>!R)},className:"text-[9px] px-1.5 py-0 rounded border border-blue-900/40 bg-blue-950/30 text-blue-300/90 uppercase tracking-wide hover:bg-blue-900/40",title:"this key is defined in multiple scopes — click to expand",children:["drift · ",b.map($=>N5[$]).join(" · ")]}),C&&v&&s.jsx("button",{onClick:$=>{$.stopPropagation(),o(void 0,v.winner)},className:"text-[9px] px-1.5 py-0 rounded border border-line bg-bg-elev text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`reset · delete from ${os[v.winner].label}`,children:"↺ reset"}),(r==null?void 0:r.deprecated)&&s.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"deprecated"}),(r==null?void 0:r.required)&&!x&&s.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-red-900/40 bg-red-950/30 text-red-400/80 uppercase tracking-wide",children:"required"})]}),N&&s.jsx("p",{className:`text-fg-dim text-xs mt-0.5 leading-relaxed ${N.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:N.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:U5(N.text)}),l&&u&&v&&s.jsx(I5,{leaf:v,defaultVal:E,onReset:$=>o(void 0,$)}),l&&s.jsx(P5,{keyName:e,node:n,info:r,targetScope:i,onOverride:$=>o($)})]}),s.jsx("div",{className:"shrink-0",children:!l&&s.jsx(z5,{node:n,info:r,onSet:$=>{o($)},disabled:S&&x})})]})})}function M5(e,n){if(!e)return[];const r=new Set;r.add(e.winner);for(const i of e.shadowed)r.add(i.scope);return n!==void 0&&r.add("default"),E5.filter(i=>r.has(i))}function I5({leaf:e,defaultVal:n,onReset:r}){const i={};i[e.winner]={value:e.value,winner:!0};for(const o of e.shadowed)i[o.scope]={value:o.value,winner:!1};return s.jsxs("div",{className:"mt-2 border border-line rounded bg-bg-elev/40 text-xs",children:[s.jsx("div",{className:"px-2 py-1 text-fg-faint border-b border-line/60",children:"Values across all scopes (winner highlighted · reset removes that scope's value):"}),s.jsxs("div",{className:"divide-y divide-line/60",children:[["user","project","local"].map(o=>{const l=i[o],d=l!==void 0;return s.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[s.jsx("span",{className:"text-fg-faint",children:os[o].label}),s.jsx("span",{className:`font-mono truncate ${l!=null&&l.winner?"text-accent":"text-fg-dim"}`,children:d?Vh(l.value):s.jsx("span",{className:"text-fg-faint",children:"—"})}),d?s.jsx("button",{onClick:()=>r(o),className:"text-[9px] px-1.5 py-0 rounded border border-line text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`delete this key from ${os[o].label}`,children:"↺"}):s.jsx("span",{})]},o)}),s.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[s.jsx("span",{className:"text-fg-faint",children:"Default"}),s.jsx("span",{className:"font-mono text-fg-dim truncate",children:n!==void 0?Vh(n):s.jsx("span",{className:"text-fg-faint",children:"—"})}),s.jsx("span",{})]})]})]})}function P5({keyName:e,node:n,info:r,targetScope:i,onOverride:o}){const d=(n==null?void 0:n.kind)==="leaf"?n:null,u=Nj(e,r==null?void 0:r.description);return s.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[u&&s.jsx("p",{className:`text-fg-dim leading-relaxed whitespace-pre-wrap ${u.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:u.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:u.text}),s.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-fg-faint",children:[(r==null?void 0:r.type)&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Type"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(r.type)?r.type.join(" | "):r.type})]}),(r==null?void 0:r.default)!==void 0&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Default"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:Vh(r.default)})]}),(r==null?void 0:r.enum)&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Options"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:r.enum.map(h=>String(h)).join(" | ")})]}),d&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Current"}),s.jsxs("dd",{className:"font-mono",children:[s.jsx("span",{className:"text-fg-dim",children:Vh(d.value)}),s.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",os[d.winner].label]})]})]}),d&&d.shadowed.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Shadowed"}),s.jsx("dd",{className:"space-y-0.5",children:d.shadowed.map((h,m)=>s.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[Vh(h.value)," —"," ",s.jsx("span",{className:"no-underline",children:os[h.scope].label})]},m))})]}),(n==null?void 0:n.kind)==="array"&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Accumulated"}),s.jsxs("dd",{className:"text-fg-dim",children:[n.items.length," items across all scopes"]})]})]}),s.jsx("div",{className:"pt-2 flex items-center gap-2 flex-wrap border-t border-line/60",children:s.jsx(D5,{keyName:e,node:n,info:r,onChange:o,targetScope:i})})]})}function D5({node:e,info:n,onChange:r,targetScope:i}){const l=(e==null?void 0:e.kind)==="leaf"?e.value:n==null?void 0:n.default,d=Tj(n==null?void 0:n.type);if(d==="boolean"){const u=l===!0;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:"Set to:"}),s.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:[{v:!0,label:"on"},{v:!1,label:"off"}].map(({v:h,label:m})=>s.jsx("button",{onClick:()=>r(h),className:`px-3 py-0.5 text-xs transition-colors ${u===h?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:m},m))}),s.jsxs("span",{className:"text-fg-faint",children:["→ ",os[i].label]})]})}return n!=null&&n.enum?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-fg-faint",children:"Choose:"}),n.enum.map(u=>{const h=$j(l,u);return s.jsx("button",{onClick:()=>r(u),className:`px-2 py-0.5 text-xs rounded border ${h?"bg-accent text-bg border-accent":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:String(u)},String(u))}),s.jsxs("span",{className:"text-fg-faint",children:["→ ",os[i].label]})]}):d==="integer"||d==="number"?s.jsx(O5,{value:typeof l=="number"?l:void 0,integer:d==="integer",onCommit:r,target:os[i].label}):d==="string"?s.jsx(L5,{value:typeof l=="string"?l:"",onCommit:r,target:os[i].label}):s.jsxs("div",{className:"text-fg-faint",children:["Complex value (",d??"object/array",") — use the"," ",s.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function O5({value:e,integer:n,onCommit:r,target:i}){const[o,l]=L.useState(e!==void 0?String(e):""),d=()=>{const u=n?parseInt(o,10):parseFloat(o);Number.isNaN(u)||r(u)};return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:"Set to:"}),s.jsx("input",{type:"number",value:o,onChange:u=>l(u.target.value),onBlur:d,onKeyDown:u=>{u.key==="Enter"&&u.target.blur()},className:"w-24 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),s.jsxs("button",{onClick:d,className:"px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",i]})]})}function L5({value:e,onCommit:n,target:r}){const[i,o]=L.useState(e);return s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[s.jsx("span",{className:"text-fg-faint shrink-0",children:"Set to:"}),s.jsx("input",{type:"text",value:i,onChange:l=>o(l.target.value),onKeyDown:l=>{l.key==="Enter"&&n(i)},className:"flex-1 min-w-0 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),s.jsxs("button",{onClick:()=>n(i),className:"shrink-0 px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",r]})]})}function z5({node:e,info:n,onSet:r,disabled:i}){const o=(e==null?void 0:e.kind)==="leaf",l=Tj(n==null?void 0:n.type);if(i)return null;if(l==="boolean"){const d=o&&e.value===!0;return s.jsx("button",{onClick:()=>r(!d),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${d?"bg-accent/15 text-accent border-accent/40 hover:bg-accent hover:text-bg":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,title:"toggle",children:d?"on":"off"})}return null}function B5({isSet:e,leafNode:n,defaultVal:r,isDefault:i,node:o}){return e?(o==null?void 0:o.kind)==="array"?{kind:"accumulated",label:`${o.items.length} items`}:(o==null?void 0:o.kind)==="object"?{kind:"set",label:"configured"}:n?i?{kind:"default",label:`= default · ${os[n.winner].label}`}:n.shadowed.length>0?{kind:"override",label:`overriding ${n.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${os[n.winner].label}`}:{kind:"set",label:"configured"}:r!==void 0?{kind:"default",label:`using default: ${Vh(r)}`}:{kind:"unset",label:"not configured"}}function F5({kind:e,label:n}){const r={set:"bg-accent/15 text-accent border-accent/30",default:"bg-bg-hi text-fg-dim border-line",unset:"bg-bg-elev text-fg-faint border-line",override:"bg-purple-950/30 text-purple-400/80 border-purple-900/40",accumulated:"bg-blue-950/30 text-blue-400/80 border-blue-900/40"}[e];return s.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${r}`,children:n})}function Tj(e){if(e)return Array.isArray(e)?e.find(r=>r!=="null")??e[0]:e}function $j(e,n){return e===n?!0:typeof e!=typeof n?!1:e&&n&&typeof e=="object"?JSON.stringify(e)===JSON.stringify(n):!1}function U5(e){const n=e.trim().split(`
|
|
3393
|
+
(Give a different rewrite than the last one.)`,!1)},[E,r.instruction]),_=L.useCallback(C=>{const N=r.diff;if(!N)return{ok:!1,reason:"not-found"};const $=AO(C,N.before,N.after);return $.ok?(o.current+=1,i({type:"ACCEPT"})):Le.error($.reason==="ambiguous"?"That text appears more than once — edit it manually instead.":"That text no longer matches the document — edit it manually instead."),$},[r.diff]);return{state:r,select:m,cancel:x,listen:g,sendHeard:y,run:j,retry:b,accept:_}}const BO=[{label:"Make concise",instruction:"Rewrite this text to be concise and specific. Preserve meaning and any markdown structure."},{label:"To bullet list",instruction:"Convert this text into a tight markdown bullet list."},{label:"Fix the tone",instruction:"Fix the tone: direct, professional, no hedging. Preserve meaning."}],Sk=320,om=8;function FO(){return s.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function UO(e){const n=typeof window<"u"?window.innerWidth:1024,r=Math.min(Math.max(e.left,om),Math.max(om,n-Sk-om)),i=Math.max(e.top-om,om);return{position:"fixed",left:r,top:i,width:Sk,transform:"translateY(-100%)",zIndex:50}}function HO({phase:e,rect:n,diff:r,transcript:i,modelStatus:o,onQuickAction:l,onRunCustom:d,onListen:u,onSendHeard:h,onCancel:m,onAccept:x,onReject:g,onRetry:v}){const[S,E]=L.useState(""),j=()=>{const y=S.trim();y&&(d(y),E(""))};return s.jsxs("div",{"data-doc-edit-popover":!0,style:UO(n),className:"rounded-lg border border-line bg-bg-elev shadow-2xl text-xs text-fg",children:[e==="popover"&&s.jsxs("div",{className:"p-2",children:[s.jsxs("div",{className:"flex items-center justify-between mb-2",children:[s.jsxs("div",{className:"flex flex-wrap gap-1",children:[s.jsx("button",{onClick:u,"data-testid":"doc-edit-voice",className:"px-2 py-1 text-[11px] rounded border border-line bg-bg-hi text-fg hover:border-fg-faint font-medium",title:"Speak your edit instruction",children:"🎤 Voice edit"}),BO.map(y=>s.jsx("button",{onClick:()=>l(y.instruction),className:"px-2 py-1 text-[11px] rounded border border-line text-fg-dim hover:text-fg hover:bg-bg-hi",children:y.label},y.label))]}),s.jsx("button",{onClick:m,className:"ml-2 shrink-0 text-fg-faint hover:text-fg",title:"Dismiss","aria-label":"Dismiss",children:"×"})]}),s.jsx("input",{autoFocus:!0,value:S,onChange:y=>E(y.target.value),onKeyDown:y=>{y.key==="Enter"?j():y.key==="Escape"&&m()},placeholder:"tell Claude what to change…",className:"w-full px-2 py-1 text-[11px] bg-bg border border-line rounded outline-none focus:border-fg-faint text-fg placeholder:text-fg-faint"})]}),e==="listening"&&s.jsxs("div",{className:"p-3 flex items-center justify-between","data-testid":"doc-edit-listening",children:[s.jsxs("span",{className:"flex flex-col gap-0.5 text-fg-dim",children:[s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx(FO,{}),"Listening…"]}),o&&s.jsx("span",{className:"text-[10px] text-fg-faint",children:o})]}),s.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="review"&&s.jsxs("div",{className:"p-3","data-testid":"doc-edit-review",children:[s.jsxs("p",{className:"italic text-fg mb-2",children:["«",i,"»"]}),s.jsxs("div",{className:"flex justify-end gap-1.5",children:[s.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),s.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),e==="thinking"&&s.jsxs("div",{className:"p-3 flex items-center justify-between",children:[s.jsx("span",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),s.jsx("button",{onClick:m,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="diff"&&r&&s.jsxs("div",{className:"p-3",children:[s.jsxs("div",{className:"mb-2 max-h-40 overflow-auto space-y-1",children:[s.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:r.before}),s.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:r.after})]}),s.jsxs("div",{className:"flex justify-end gap-1.5",children:[s.jsx("button",{onClick:g,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),s.jsx("button",{onClick:v,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),s.jsx("button",{onClick:x,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})}function WO(){return s.jsxs("span",{className:"inline-flex items-center gap-0.5","aria-hidden":"true",children:[s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:0ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:150ms]"}),s.jsx("span",{className:"w-1 h-1 rounded-full bg-red-400 animate-pulse [animation-delay:300ms]"})]})}function Ck({phase:e,transcript:n,diff:r,editCount:i,modelStatus:o,onListen:l,onSendHeard:d,onCancel:u,onAccept:h,onReject:m,onRetry:x}){return s.jsxs("div",{"data-testid":"assistant-rail",className:"w-[300px] shrink-0 border-l border-line bg-bg-elev flex flex-col text-xs",children:[s.jsxs("div",{className:"flex items-center justify-between px-3 h-8 border-b border-line shrink-0",children:[s.jsx("span",{className:"font-medium text-fg",children:"Assistant"}),s.jsx("span",{className:"text-[10px] text-fg-faint",title:"Model used for Document Experience edits",children:Zm(LO)})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-3",children:[e==="idle"&&s.jsxs("div",{className:"text-fg-faint",children:[s.jsx("p",{children:"Select text in the doc…"}),s.jsxs("p",{className:"mt-2 text-[10px]",children:[i," edit",i===1?"":"s"," this session"]})]}),e==="popover"&&s.jsx("p",{className:"text-fg-faint",children:"Choose a quick action or speak an instruction from the popover."}),e==="listening"&&s.jsxs("div",{children:[s.jsxs("p",{className:"flex items-center gap-2 text-fg-dim mb-1",children:[s.jsx(WO,{}),"Listening…"]}),o&&s.jsx("p",{className:"text-[10px] text-fg-faint mb-3",children:o}),s.jsx("button",{onClick:u,className:"px-2 py-0.5 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"})]}),e==="review"&&s.jsxs("div",{children:[s.jsxs("p",{className:"italic text-fg mb-3",children:["«",n,"»"]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:l,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Re-record"}),s.jsx("button",{onClick:d,className:"px-2 py-1 text-[11px] text-white rounded bg-accent hover:opacity-90",children:"Send"})]})]}),e==="thinking"&&s.jsx("p",{className:"text-fg-dim animate-pulse",children:"Claude is editing…"}),e==="diff"&&r&&s.jsxs("div",{children:[s.jsxs("div",{className:"mb-3 space-y-2",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"Before"}),s.jsx("div",{className:"text-red-400 line-through whitespace-pre-wrap",children:r.before})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wide text-fg-faint mb-1",children:"After"}),s.jsx("div",{className:"text-green-400 whitespace-pre-wrap",children:r.after})]})]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:m,className:"px-2 py-1 text-[11px] text-fg-faint hover:text-fg border border-line rounded",children:"Reject"}),s.jsx("button",{onClick:x,className:"px-2 py-1 text-[11px] text-fg-dim hover:text-fg border border-line rounded",children:"Retry"}),s.jsx("button",{onClick:h,className:"px-2 py-1 text-[11px] text-white rounded bg-green-600 hover:bg-green-500",children:"Accept"})]})]})]})]})}function jk(e){return e.split("/").filter(Boolean).pop()||e}function qO({path:e,onRenamed:n,onDeleted:r}){const[i,o]=L.useState(!1),[l,d]=L.useState(!1),[u,h]=L.useState(""),[m,x]=L.useState(!1),g=Tn(U=>U.buffers[e]),v=Tn(U=>U.openFile),S=Tn(U=>U.renameOpenFile),E=Tn(U=>U.closeFile),j=uo(),y=jk(e),b=()=>o(!1),_=()=>{h(y),d(!0),b()},C=async()=>{const U=u.trim();if(!U||U===y){d(!1);return}try{const W=await window.api.files.rename(e,U);if(W.ok){const Y=e.slice(0,e.lastIndexOf("/")),V=W.newPath??`${Y}/${U}`;S(e,V),n==null||n(e,V),Le.info(`Renamed to ${U}`)}else Le.error(W.error??`Couldn't rename ${y}`)}catch(W){Le.error(W instanceof Error?W.message:`Couldn't rename ${y}`)}d(!1)},N=async()=>{b();try{const U=await window.api.files.duplicate(e);U.ok&&U.path?(v(U.path),Le.info(`Duplicated as ${jk(U.path)}`)):Le.error(U.error??`Couldn't duplicate ${y}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't duplicate ${y}`)}},$=async()=>{try{const U=await window.api.files.delete(e);U.ok?(E(e),r==null||r(e),Le.info(`Deleted ${y}`)):Le.error(U.error??`Couldn't delete ${y}`)}catch(U){Le.error(U instanceof Error?U.message:`Couldn't delete ${y}`)}x(!1)},R=async()=>{b();const U=g??"";try{await navigator.clipboard.writeText(U),Le.info(`Copied ${U.length} chars`)}catch(W){Le.error(W instanceof Error?W.message:`Couldn't copy ${y}`)}},O=()=>{if(b(),!j){Le.error("No terminal tab is active");return}window.api.pty.write({tabId:j.id,data:`@${e} `}),Le.info(`Added ${y} to Claude context`)},I=()=>{b(),window.api.shell.open({as:"openPath",path:e}).then(U=>{U.ok||Le.error(U.error??`Couldn't open ${y}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't open ${y}`))},z=()=>{b(),window.api.shell.open({as:"revealPath",path:e}).then(U=>{U.ok||Le.error(U.error??`Couldn't reveal ${y}`)}).catch(U=>Le.error(U instanceof Error?U.message:`Couldn't reveal ${y}`))};return s.jsxs("div",{className:"relative inline-block mr-1",children:[s.jsx("button",{onClick:()=>o(U=>!U),className:`px-2 py-0.5 text-[10px] border border-line rounded ${i?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Document actions",children:"Document ▾"}),i&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:b}),s.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-56 rounded-lg border border-line bg-bg-elev shadow-xl text-xs py-1",children:[s.jsx(ob,{children:"Edit"}),s.jsx(_u,{label:"Rename",onClick:_}),s.jsx(_u,{label:"Duplicate",onClick:N}),s.jsx(_u,{label:"Delete document",danger:!0,onClick:()=>{b(),x(!0)}}),s.jsx(Ek,{}),s.jsx(ob,{children:"Open"}),s.jsx(_u,{label:"Open in default app",onClick:I}),s.jsx(_u,{label:"Reveal in OS",onClick:z}),s.jsx(Ek,{}),s.jsx(ob,{children:"Export"}),s.jsx(_u,{label:"Copy as Markdown",onClick:R}),s.jsx(_u,{label:"Add to Claude context",onClick:O,disabled:!j,title:j?void 0:"No terminal tab is active"})]})]}),l&&s.jsx(VO,{value:u,onChange:h,onCancel:()=>d(!1),onConfirm:()=>void C()}),m&&s.jsx(GO,{name:y,onCancel:()=>x(!1),onConfirm:()=>void $()})]})}function ob({children:e}){return s.jsx("div",{className:"px-3 pt-1 pb-0.5 text-[9px] uppercase tracking-wide text-fg-faint",children:e})}function _u({label:e,onClick:n,danger:r,disabled:i,title:o}){return s.jsx("button",{onClick:n,disabled:i,title:o,className:`w-full text-left px-3 py-1.5 transition-colors disabled:opacity-40 disabled:cursor-not-allowed ${r?"text-red-400 hover:bg-bg-hi":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:e})}function Ek(){return s.jsx("div",{className:"my-1 border-t border-line"})}function VO({value:e,onChange:n,onCancel:r,onConfirm:i}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:o=>{o.target===o.currentTarget&&r()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:"Rename"}),s.jsx("input",{autoFocus:!0,value:e,onChange:o=>n(o.target.value),onKeyDown:o=>{o.key==="Enter"?i():o.key==="Escape"&&r()},className:"w-full px-2 py-1 text-xs bg-bg border border-line rounded text-fg mb-3"}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:i,className:"px-3 py-1 text-xs text-white rounded bg-accent hover:bg-accent/90",children:"Rename"})]})]})})}function GO({name:e,onCancel:n,onConfirm:r}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:i=>{i.target===i.currentTarget&&n()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsxs("h3",{className:"text-sm font-medium text-fg mb-3",children:["Delete ",e,"? This cannot be undone."]}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Delete"})]})]})})}function KO(){const[e,n]=L.useState(!1),r=Oh();return s.jsxs("div",{className:"relative inline-block mr-1",children:[s.jsx("button",{onClick:()=>n(i=>!i),className:`px-2 py-0.5 text-[10px] border border-line rounded ${e?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Display preferences",children:"Display"}),e&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[390]",onMouseDown:()=>n(!1)}),s.jsxs("div",{className:"absolute right-0 top-full mt-1 z-[400] w-60 rounded-lg border border-line bg-bg-elev shadow-xl text-xs p-2 space-y-1.5",children:[s.jsx(Th,{label:"Text size",children:s.jsxs("div",{className:"flex items-center rounded border border-line overflow-hidden",children:[s.jsx("button",{onClick:()=>r.bumpFontSize(-1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom out",children:"A−"}),s.jsx("span",{className:"px-2 text-[10px] text-fg-dim",children:r.fontSize}),s.jsx("button",{onClick:()=>r.bumpFontSize(1),className:"px-1.5 py-0.5 text-[11px] text-fg-faint hover:text-fg",title:"Zoom in",children:"A+"})]})}),s.jsx(Th,{label:"Word wrap",children:s.jsx(Tx,{on:r.wordWrap,onClick:r.toggleWordWrap})}),s.jsx(Th,{label:"Minimap",children:s.jsx(Tx,{on:r.minimap,onClick:r.toggleMinimap})}),s.jsx(Th,{label:"Theme",children:s.jsx("button",{onClick:()=>r.setTheme(r.theme==="dark"?"paper":"dark"),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Toggle editor theme",children:r.theme==="dark"?"Dark":"Paper"})}),s.jsx(Th,{label:"Autosave",children:s.jsx(Tx,{on:r.autosave,onClick:r.toggleAutosave})}),s.jsx(Th,{label:"Wide measure",children:s.jsx(Tx,{on:r.wideMeasure,onClick:r.toggleWideMeasure})})]})]})]})}function Th({label:e,children:n}){return s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:e}),n]})}function Tx({on:e,onClick:n}){return s.jsx("button",{onClick:n,className:`px-2 py-0.5 text-[10px] rounded border border-line ${e?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:e?"On":"Off"})}const XO=L.lazy(()=>Jm(()=>import("./TiptapBody-UWL5KIJG.js"),__vite__mapDeps([0,1,2]),import.meta.url).then(e=>({default:e.TiptapBody})));function $x(e){return e.split("/").filter(Boolean).pop()||e}function Ax(e,n){if(!n.length)return e;const r=new Set(n),i={};for(const[o,l]of Object.entries(e))r.has(o)||(i[o]=l);return i}function Rx(e){return oC(e)||aC(e)}function yw(){const e=Tn(Ye=>Ye.openFiles),n=Tn(Ye=>Ye.activeFilePath),r=Tn(Ye=>Ye.dirty),i=Tn(Ye=>Ye.viewMode),o=Tn(Ye=>Ye.buffers),l=Tn(Ye=>Ye.setActive),d=Tn(Ye=>Ye.closeFile),u=Tn(Ye=>Ye.closeOthers),h=Tn(Ye=>Ye.closeToTheRight),m=Tn(Ye=>Ye.closeAll),x=Tn(Ye=>Ye.loadBuffer),g=Tn(Ye=>Ye.setBuffer),v=Tn(Ye=>Ye.markSaved),S=Tn(Ye=>Ye.setViewMode),E=Oh(),[j,y]=L.useState({}),[b,_]=L.useState({}),[C,N]=L.useState(null),[$,R]=L.useState(null),[O,I]=L.useState(!1),[z,U]=L.useState(!1),[W,Y]=L.useState(!0),V=L.useRef(null),H=L.useRef(null),te=L.useRef(void 0),ae=L.useRef(null),oe=L.useRef(null),ie=zO(n??"",o[n??""]??""),X=L.useCallback(Ye=>{V.current=Ye},[]),Q=L.useCallback(()=>V.current,[]);L.useEffect(()=>{const Ye=n;if(!Ye||Rx(Ye))return;if(Tn.getState().hasBuffer(Ye)){y(kt=>kt[Ye]==="ready"?kt:{...kt,[Ye]:"ready"});return}let yt=!1;return y(kt=>({...kt,[Ye]:"loading"})),window.api.files.read(Ye).then(kt=>{yt||(kt.binary?y(Kt=>({...Kt,[Ye]:{binary:!0,size:kt.size??0,mime:kt.mime??"application/octet-stream",reason:kt.error??"Binary file"}})):kt.ok?(x(Ye,kt.text),y(Kt=>({...Kt,[Ye]:"ready"}))):y(Kt=>({...Kt,[Ye]:{error:kt.error??"failed to read"}})))}),()=>{yt=!0}},[n,x]),L.useEffect(()=>{R(null)},[n]);const J=L.useCallback(async(Ye,yt=!1)=>{const kt=Tn.getState().buffers[Ye];if(kt==null)return;yt&&I(!0);const Kt=await window.api.files.write(Ye,kt);Kt.ok?(v(Ye),_(On=>({...On,[Ye]:(On[Ye]??0)+1})),yt||Le.info(`Saved ${$x(Ye)}`)):Le.error(Kt.error??`Couldn't save ${$x(Ye)}`),yt&&I(!1)},[v]);L.useEffect(()=>{if(!E.autosave)return;const Ye=n;if(!(!Ye||Rx(Ye)||!r[Ye]))return window.clearTimeout(te.current),te.current=window.setTimeout(()=>{J(Ye,!0)},1200),()=>window.clearTimeout(te.current)},[E.autosave,n,r,o,J]);const le=L.useCallback(Ye=>{Ye.length&&(y(yt=>Ax(yt,Ye)),_(yt=>Ax(yt,Ye)))},[]),ce=L.useCallback((Ye,yt)=>{y(kt=>Ye in kt?{...Ax(kt,[Ye]),[yt]:kt[Ye]}:kt),_(kt=>Ye in kt?{...Ax(kt,[Ye]),[yt]:kt[Ye]}:kt)},[]),pe=L.useCallback(Ye=>{r[Ye]?N({kind:"one",path:Ye}):(d(Ye),le([Ye]))},[r,d,le]),Ae=L.useCallback(Ye=>{e.some(kt=>kt.path!==Ye&&r[kt.path])?N({kind:"others",path:Ye}):(u(Ye),le(e.filter(kt=>kt.path!==Ye).map(kt=>kt.path)))},[e,r,u,le]),Se=L.useCallback(Ye=>{const yt=e.findIndex(Kt=>Kt.path===Ye);yt!==-1&&e.slice(yt+1).some(Kt=>r[Kt.path])?N({kind:"right",path:Ye}):(h(Ye),le(yt!==-1?e.slice(yt+1).map(Kt=>Kt.path):[]))},[e,r,h,le]);L.useEffect(()=>{const Ye=yt=>{if((yt.metaKey||yt.ctrlKey)&&(yt.key==="s"||yt.key==="S")){const kt=Tn.getState().activeFilePath;kt&&!Rx(kt)&&(yt.preventDefault(),J(kt))}else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="f"||yt.key==="F"))yt.preventDefault(),U(kt=>!kt);else if((yt.metaKey||yt.ctrlKey)&&yt.shiftKey&&(yt.key==="w"||yt.key==="W")){const kt=Tn.getState().activeFilePath;kt&&Tn.getState().openFiles.length>1&&(yt.preventDefault(),Ae(kt))}else yt.key==="Escape"&&ie.state.phase!=="idle"?ie.cancel():yt.key==="Escape"&&z&&U(!1)};return window.addEventListener("keydown",Ye),()=>window.removeEventListener("keydown",Ye)},[J,z,Ae,ie.state.phase,ie.cancel]),L.useEffect(()=>{if(ie.state.phase==="idle")return;const Ye=yt=>{var Kt,On;const kt=yt.target;(Kt=oe.current)!=null&&Kt.contains(kt)||(On=ae.current)!=null&&On.contains(kt)||ie.cancel()};return window.addEventListener("mousedown",Ye),()=>window.removeEventListener("mousedown",Ye)},[ie.state.phase,ie.cancel]),L.useEffect(()=>{ie.cancel()},[n,ie.cancel]);const ye=L.useCallback(()=>{e.some(yt=>r[yt.path])?N({kind:"all",path:""}):(m(),y({}),_({}))},[e,r,m]),ne=()=>{if(C){if(C.kind==="one")d(C.path),le([C.path]);else if(C.kind==="others"){const Ye=e.filter(yt=>yt.path!==C.path).map(yt=>yt.path);u(C.path),le(Ye)}else if(C.kind==="right"){const Ye=e.findIndex(kt=>kt.path===C.path),yt=Ye!==-1?e.slice(Ye+1).map(kt=>kt.path):[];h(C.path),le(yt)}else m(),y({}),_({});N(null)}};if(e.length===0)return s.jsx("div",{className:"h-full flex items-center justify-center text-fg-faint text-xs",children:s.jsxs("div",{className:"text-center",children:[s.jsx("div",{className:"mb-2",children:"no file open"}),s.jsxs("div",{children:["open the ",s.jsx("span",{className:"text-fg-dim",children:"File Explorer"})," tab and click a file to edit it here"]})]})});const we=n,Ne=we?$x(we):"",Je=we?j[we]:void 0,lt=we?uC(we):!1,xt=we?C$(we):!1,Rt=we&<?i[we]??j$(we):"edit",He=!!we&&!Rx(we)&&Je==="ready",vt=He,st=xt?["edit","wysiwyg","preview","split"]:lt?["edit","preview"]:[],an=we&&s.jsx(dO,{path:we,name:Ne,value:o[we]??"",onChange:Ye=>g(we,Ye),onSave:()=>void J(we),onReady:X,onCursor:R}),sn=O?"Saving…":we&&r[we]?E.autosave?"Editing…":"Unsaved":"All changes saved";return s.jsxs("div",{className:"relative flex flex-col h-full bg-bg",children:[!z&&s.jsx(aO,{openFiles:e,activeFilePath:n,dirty:r,onSelectFile:l,onCloseFile:pe,onCloseOthers:Ae,onCloseToTheRight:Se,onCloseAll:ye}),we&&!z&&s.jsxs("div",{className:"flex items-center px-3 h-8 border-b border-line shrink-0 bg-bg-elev",children:[s.jsx("span",{className:"text-xs font-medium text-fg truncate",children:Ne}),s.jsx("span",{className:"ml-3 text-[10px] text-fg-faint truncate",children:we}),He&&s.jsxs("span",{className:"ml-3 text-[10px] text-fg-faint shrink-0",children:["· ",sn]}),cl(we)&&(Rt==="preview"||Rt==="split")&&s.jsx("button",{onClick:()=>Y(Ye=>!Ye),className:`ml-3 px-2 py-0.5 text-[10px] border border-line rounded ${W?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle document outline",children:"Outline"}),cl(we)&&(Rt==="preview"||Rt==="split")&&s.jsx("button",{onClick:E.toggleAssistantRail,className:`ml-1 px-2 py-0.5 text-[10px] border border-line rounded ${E.assistantRail?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,title:"Toggle Assistant rail",children:"Assistant"}),st.length>0&&s.jsx("div",{className:"flex items-center ml-2 rounded border border-line overflow-hidden",children:st.map(Ye=>s.jsx("button",{onClick:()=>S(we,Ye),className:`px-2 py-0.5 text-[10px] capitalize transition-colors ${Rt===Ye?"bg-bg-hi text-fg":"text-fg-faint hover:text-fg"}`,children:Ye},Ye))}),s.jsx("div",{className:"flex-1"}),s.jsx(qO,{path:we,onRenamed:ce,onDeleted:Ye=>le([Ye])}),He&&s.jsx(KO,{}),s.jsx("button",{onClick:()=>U(!0),className:"px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded",title:"Focus mode (Cmd/Ctrl-Shift-F)",children:"Focus"})]}),z&&s.jsx("button",{onClick:()=>U(!1),className:"absolute top-2 right-3 z-10 px-2 py-0.5 text-[10px] text-fg-faint hover:text-fg border border-line rounded bg-bg-elev/80",title:"Exit focus mode (Esc)",children:"Exit focus"}),s.jsx("div",{className:"flex-1 min-h-0",children:we?oC(we)?s.jsx(_O,{path:we,name:Ne}):aC(we)?s.jsx(kO,{path:we}):Je&&typeof Je=="object"&&"binary"in Je?s.jsx($O,{path:we,name:Ne,size:Je.size,mime:Je.mime,reason:Je.reason}):Je&&typeof Je=="object"&&"error"in Je?s.jsx("div",{className:"p-6 text-xs text-red-400",children:Je.error}):Je!=="ready"?s.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"loading…"}):Rt==="wysiwyg"&&cl(we)?s.jsx(L.Suspense,{fallback:s.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading editor…"}),children:s.jsx(XO,{value:o[we]??"",onChange:Ye=>g(we,Ye)},we)}):Rt==="split"&&cl(we)?s.jsxs("div",{className:"flex h-full",children:[W&&s.jsx(wk,{text:o[we]??"",scrollRef:H}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col border-r border-line",children:[s.jsx(bk,{getEditor:Q}),s.jsx("div",{className:"flex-1 min-h-0",children:an})]}),s.jsx("div",{ref:ae,className:"flex-1 min-w-0",children:s.jsx(vk,{ref:H,text:o[we]??"",flush:!0,wideMeasure:E.wideMeasure,onSelect:ie.select,onDismissSelection:ie.cancel})}),!z&&E.assistantRail&&s.jsx(Ck,{phase:ie.state.phase,transcript:ie.state.transcript,diff:ie.state.diff,editCount:ie.state.editCount,modelStatus:ie.state.modelStatus,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)},onReject:ie.cancel,onRetry:ie.retry})]}):Rt==="preview"&&cl(we)?s.jsxs("div",{className:"flex h-full",children:[W&&s.jsx(wk,{text:o[we]??"",scrollRef:H}),s.jsx("div",{ref:ae,className:"flex-1 min-w-0",children:s.jsx(vk,{ref:H,text:o[we]??"",wideMeasure:E.wideMeasure,onSelect:ie.select,onDismissSelection:ie.cancel})}),!z&&E.assistantRail&&s.jsx(Ck,{phase:ie.state.phase,transcript:ie.state.transcript,diff:ie.state.diff,editCount:ie.state.editCount,modelStatus:ie.state.modelStatus,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)},onReject:ie.cancel,onRetry:ie.retry})]}):Rt==="preview"&&iC(we)?s.jsx(bO,{path:we,dirty:!!r[we],reloadToken:b[we]??0}):Rt==="preview"&&lC(we)?s.jsx(CO,{path:we,text:o[we]??""}):Rt==="preview"&&cC(we)?s.jsx(NO,{path:we,text:o[we]??""}):cl(we)?s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(bk,{getEditor:Q}),s.jsx("div",{className:"flex-1 min-h-0",children:an})]}):an:null}),vt&&s.jsx(vO,{text:o[we]??"",cursor:$,language:zi(we)||void 0}),we&&cl(we)&&(Rt==="preview"||Rt==="split")&&ie.state.phase!=="idle"&&ie.state.selection&&s.jsx("div",{ref:oe,children:s.jsx(HO,{phase:ie.state.phase,rect:ie.state.selection.rect,diff:ie.state.diff,transcript:ie.state.transcript,modelStatus:ie.state.modelStatus,onQuickAction:ie.run,onRunCustom:ie.run,onListen:ie.listen,onSendHeard:ie.sendHeard,onCancel:ie.cancel,onReject:ie.cancel,onRetry:ie.retry,onAccept:()=>{const Ye=ie.accept(o[we]??"");Ye.ok&&g(we,Ye.next)}})}),C&&s.jsx(YO,{message:C.kind==="one"?`Discard unsaved changes to ${$x(C.path)}?`:C.kind==="others"?"Discard unsaved changes in the other open files?":C.kind==="right"?"Discard unsaved changes in the files to the right?":"Discard unsaved changes in all open files?",onCancel:()=>N(null),onConfirm:ne})]})}function YO({message:e,onCancel:n,onConfirm:r}){return s.jsx("div",{className:"fixed inset-0 z-[400] flex items-center justify-center bg-black/60",onMouseDown:i=>{i.target===i.currentTarget&&n()},children:s.jsxs("div",{className:"w-96 rounded-lg border border-line bg-bg-elev p-4 shadow-2xl",children:[s.jsx("h3",{className:"text-sm font-medium text-fg mb-3",children:e}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:n,className:"px-3 py-1 text-xs text-fg-dim hover:text-fg border border-line rounded",children:"Cancel"}),s.jsx("button",{onClick:r,className:"px-3 py-1 text-xs text-white rounded bg-red-600 hover:bg-red-500",children:"Discard"})]})]})})}const Nk={ts:"#3178c6",tsx:"#61dafb",js:"#f7df1e",jsx:"#61dafb",cjs:"#f7df1e",mjs:"#f7df1e",json:"#5d5d5d",css:"#264de4",scss:"#cd6799",less:"#1d365d",html:"#e34c26",md:"#083fa1",mdx:"#083fa1",py:"#3776ab",go:"#00add8",rs:"#dea584",java:"#b07219",kt:"#a97bff",c:"#555555",cpp:"#f34b7d",cc:"#f34b7d",h:"#555555",hpp:"#f34b7d",swift:"#fa7343",rb:"#cc342d",php:"#4f5d95",sql:"#e38c00",sh:"#89e051",bash:"#89e051",zsh:"#89e051",yaml:"#cb171e",yml:"#cb171e",toml:"#9c4221",xml:"#0060ac",svg:"#ff9900",vue:"#41b883",svelte:"#ff3e00",other:"#6b7280"},JO={ts:"TypeScript",tsx:"TSX",js:"JavaScript",jsx:"JSX",cjs:"CommonJS",mjs:"ES Module",json:"JSON",css:"CSS",scss:"SCSS",less:"Less",html:"HTML",md:"Markdown",mdx:"MDX",py:"Python",go:"Go",rs:"Rust",java:"Java",kt:"Kotlin",c:"C",cpp:"C++",cc:"C++",h:"C/C++ Header",hpp:"C++ Header",swift:"Swift",rb:"Ruby",php:"PHP",sql:"SQL",sh:"Shell",bash:"Shell",zsh:"Shell",yaml:"YAML",yml:"YAML",toml:"TOML",xml:"XML",svg:"SVG",vue:"Vue",svelte:"Svelte",other:"Other"};function ab(e){return e>=1e6?(e/1e6).toFixed(1)+"M":e>=1e3?(e/1e3).toFixed(1)+"K":String(e)}function QO({open:e,onClose:n,variant:r="overlay"}){const i=bt($=>$.tabs.find(R=>R.id===$.activeTabId)??null),o=(i==null?void 0:i.cwd)??null,[l,d]=L.useState(null),[u,h]=L.useState(!1),[m,x]=L.useState(null),g=L.useRef(null),v=L.useCallback(async $=>{h(!0),x(null);try{const R=await window.api.repo.analyze($);R.ok?d(R):(x(R.error||"Analysis failed"),d(null))}catch(R){x(R instanceof Error?R.message:String(R)),d(null)}finally{h(!1)}},[]);L.useEffect(()=>{if(e){if(!o){x("No active session — open a tab in a folder first.");return}v(o)}},[e,o,v]),L.useEffect(()=>{var R;if(!e)return;const $=O=>{O.key==="Escape"&&(O.stopPropagation(),n())};return window.addEventListener("keydown",$),(R=g.current)==null||R.focus(),()=>window.removeEventListener("keydown",$)},[e,n]);const S=L.useCallback(()=>{o&&v(o)},[o,v]),E=L.useMemo(()=>l?Object.entries(l.languageBreakdown).map(([R,O])=>[R,O.files,O.lines]).sort((R,O)=>O[1]-R[1]).slice(0,12):[],[l]),j=L.useMemo(()=>E.length===0?1:E[0][1],[E]),y=L.useMemo(()=>{if(!l)return[];const $=l.topDirectories;if($.length===0)return[];const R=$.map(I=>Math.sqrt(Math.max(1,I.fileCount))),O=R.reduce((I,z)=>I+z,0)||1;return $.map((I,z)=>({path:I.path,fileCount:I.fileCount,totalLines:I.totalLines,basis:R[z]/O*100}))},[l]);if(!e)return null;const b=$=>{$.target===$.currentTarget&&n()},_=o?o.split("/").filter(Boolean).pop()||o:"no folder",C=r==="page",N=s.jsx("div",{className:C?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:C?void 0:b,"data-testid":"repoviz-backdrop",children:s.jsxs("div",{ref:g,role:C?void 0:"dialog","aria-modal":C?void 0:"true","aria-label":"Repository Visualization",tabIndex:-1,className:C?"h-full w-full flex flex-col outline-none bg-bg":"bg-bg-elev border border-line rounded-lg shadow-xl w-[900px] max-w-[95vw] max-h-[85vh] flex flex-col outline-none","data-testid":"repoviz-dialog",children:[s.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-line",children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[s.jsx("span",{className:"text-lg","aria-hidden":!0,children:"🗺"}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{className:"text-base font-medium text-fg leading-tight",children:"Repository Visualization"}),s.jsxs("div",{className:"text-xs text-fg-dim truncate",title:o??"",children:[_,(l==null?void 0:l.gitStatus.branch)&&s.jsxs("span",{className:"ml-2 font-mono text-fg-faint",children:["(",l.gitStatus.branch,")"]}),(l==null?void 0:l.truncated)&&s.jsx("span",{className:"ml-2 text-amber-400",children:"truncated"})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1",children:[l&&l.gitStatus.uncommitted>0&&s.jsxs("span",{className:"px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 text-[11px] font-mono",title:`${l.gitStatus.uncommitted} uncommitted files`,children:[l.gitStatus.uncommitted," uncommitted"]}),s.jsxs("button",{type:"button",onClick:S,disabled:u||!o,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs disabled:opacity-40 disabled:cursor-not-allowed",title:"Re-run analysis",children:[u?"…":"↻"," Refresh"]}),s.jsx("button",{type:"button",onClick:n,className:"px-2 py-1 rounded text-fg-dim hover:bg-bg-hi hover:text-fg text-xs","aria-label":"Close",children:"✕"})]})]}),s.jsx("div",{className:"flex-1 overflow-y-auto p-5 space-y-6",children:u&&!l?s.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-fg-dim",children:[s.jsx("div",{className:"text-3xl mb-3 animate-pulse","aria-hidden":!0,children:"⟳"}),s.jsx("div",{className:"text-sm",children:"Analyzing repository…"}),s.jsx("div",{className:"text-xs text-fg-faint mt-1",children:"Walking files, counting lines, reading git status"})]}):m?s.jsxs("div",{className:"py-16 text-center",children:[s.jsx("div",{className:"text-3xl mb-3 text-red-400","aria-hidden":!0,children:"⚠"}),s.jsx("div",{className:"text-sm text-red-400",children:m})]}):l?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[s.jsx(lb,{label:"Files",value:ab(l.totalFiles)}),s.jsx(lb,{label:"Lines of code",value:ab(l.totalLines)}),s.jsx(lb,{label:"Uncommitted",value:String(l.gitStatus.uncommitted),tone:l.gitStatus.uncommitted>0?"warn":"neutral"})]}),s.jsxs("section",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Languages"}),E.length===0?s.jsx("div",{className:"text-xs text-fg-dim",children:"No files detected."}):s.jsx("div",{className:"space-y-1.5",children:E.map(([$,R,O])=>{const I=Nk[$]??Nk.other,z=JO[$]??$,U=R/j*100;return s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsx("span",{className:"w-24 text-fg-dim truncate",title:z,children:z}),s.jsx("div",{className:"flex-1 h-4 bg-bg rounded overflow-hidden",children:s.jsx("div",{className:"h-full rounded",style:{width:`${U}%`,backgroundColor:I}})}),s.jsxs("span",{className:"w-16 text-right text-fg-dim font-mono",children:[R," files"]}),s.jsxs("span",{className:"w-20 text-right text-fg-faint font-mono",children:[ab(O)," L"]})]},$)})})]}),s.jsxs("section",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wider text-fg-faint mb-2",children:"Top directories"}),y.length===0?s.jsx("div",{className:"text-xs text-fg-dim",children:"No directories."}):s.jsx("div",{className:"flex flex-wrap gap-1 min-h-[140px]",children:y.map($=>s.jsxs("div",{className:"relative rounded bg-bg-hi border border-line hover:border-accent transition-colors cursor-default flex flex-col justify-end p-2 min-w-[80px] min-h-[60px]",style:{flexBasis:`${Math.max($.basis,6)}%`,flexGrow:$.basis>15?1:0},title:`${$.path} — ${$.fileCount} files, ${$.totalLines.toLocaleString()} lines`,children:[s.jsx("div",{className:"text-[11px] font-mono text-fg truncate",children:$.path}),s.jsxs("div",{className:"text-[10px] text-fg-dim font-mono",children:[$.fileCount," files"]})]},$.path))})]}),s.jsxs("div",{className:"text-[10px] text-fg-faint text-right",children:["Analyzed in ",l.durationMs,"ms",l.truncated&&" — stopped early (5000-file cap or 30s timeout)"]})]}):s.jsx("div",{className:"py-16 text-center text-fg-dim text-sm",children:"No analysis yet. Click Refresh."})})]})});return!C&&typeof document<"u"&&document.body?Hu.createPortal(N,document.body):N}function lb({label:e,value:n,tone:r="neutral"}){const i=r==="warn"?"text-amber-400":"text-fg";return s.jsxs("div",{className:"bg-bg-hi/40 border border-line rounded-lg p-3",children:[s.jsx("div",{className:`text-xl font-medium ${i}`,children:n}),s.jsx("div",{className:"text-xs text-fg-dim mt-0.5",children:e})]})}function qu({options:e,active:n,onChange:r}){return s.jsx("div",{className:"flex rounded border border-line overflow-hidden",children:e.map(({key:i,label:o})=>s.jsx("button",{onClick:()=>r(i),className:`px-2 py-0.5 text-xs ${n===i?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:o},i))})}const Tk=e=>/[/\\\-_.\s]/.test(e),$k=e=>e>="A"&&e<="Z";function ZO(e,n,r){if(!e)return{match:!0,score:0,matched:[]};const i=e.toLowerCase(),o=n.toLowerCase(),l=(r||n).toLowerCase(),d=n.split("/").pop()||n,u=d.toLowerCase();if(u===i)return{match:!0,score:1e3,matched:Array.from({length:d.length},(b,_)=>_)};if(u.startsWith(i))return{match:!0,score:900,matched:Array.from({length:e.length},(b,_)=>_)};let h=0;for(const b of l.split("/")){if(b===i)return{match:!0,score:800,matched:[]};b.startsWith(i)&&(h=Math.max(h,700))}const m=u.indexOf(i);if(m!==-1)return{match:!0,score:m===0||Tk(u[m-1])||$k(d[m])?650:600,matched:Array.from({length:e.length},(_,C)=>m+C)};if(l.includes(i))return{match:!0,score:Math.max(500,h),matched:[]};let x=0,g=0,v=0,S=-1,E=0;const j=[];for(let b=0;b<o.length&&x<i.length;b++)o[b]===i[x]&&(j.push(b),g+=10,S===b-1?(v++,g+=v*8):v=0,(b===0||Tk(o[b-1])||$k(n[b]))&&(E++,g+=15,b===0&&(g+=10)),S=b,x++);if(x!==i.length)return{match:!1,score:0,matched:[]};const y=Math.max(0,50-(o.length-i.length));if(g+=y,E>=i.length*.5&&(g+=30),j.length>1){const b=j[j.length-1]-j[0];b>i.length*3&&(g-=Math.min(50,(b-i.length*3)*2))}return{match:!0,score:Math.max(1,g),matched:j}}function cb(e,n){return e.startsWith(n+"/")?e.slice(n.length+1):e===n?"":e}function Ak(e){const n=e.lastIndexOf("/");return n<0?"":e.slice(0,n)}const Rk="session-manager.quickopen.recent",e5=8;function t5({open:e,onClose:n,variant:r="overlay"}){const i=bt(z=>z.tabs.find(U=>U.id===z.activeTabId)??null),o=(i==null?void 0:i.cwd)??"",[l,d]=L.useState(""),[u,h]=L.useState([]),[m,x]=L.useState(!1),[g,v]=L.useState(0),[S,E]=L.useState([]),j=L.useRef(null),y=L.useRef(null);L.useEffect(()=>{if(e)try{const z=localStorage.getItem(Rk);z&&E(JSON.parse(z))}catch{}},[e]),L.useEffect(()=>{if(!e){d(""),v(0);return}const z=setTimeout(()=>{var U;return(U=j.current)==null?void 0:U.focus()},0);return()=>clearTimeout(z)},[e]),L.useEffect(()=>{if(!e||!o)return;let z=!1;return x(!0),window.api.search.files(o,"",{limit:5e3}).then(U=>{if(!z){if(!U.ok){Le.error(`File search failed: ${U.error??"unknown error"}`),h([]);return}h(U.files)}}).catch(U=>{const W=U instanceof Error?U.message:String(U);dt.error("quick-open","search.files threw",{error:W}),Le.error(`File search failed: ${W}`),h([])}).finally(()=>{z||x(!1)}),()=>{z=!0}},[e,o]);const b=L.useMemo(()=>{if(!l.trim())return[...u].sort((Y,V)=>Y.name.localeCompare(V.name)).slice(0,100).map(Y=>({file:Y,score:0,matched:[]}));const z=l.trim(),U=[];for(const W of u){const Y=ZO(z,W.name,W.path);Y.match&&U.push({file:W,score:Y.score,matched:Y.matched})}return U.sort((W,Y)=>Y.score-W.score),U.slice(0,100)},[u,l]),_=L.useMemo(()=>l.trim()?[]:S.map(z=>u.find(U=>U.path===z)||null).filter(z=>z!==null).slice(0,5),[S,u,l]);L.useEffect(()=>{const z=_.length+b.length;g>=z&&v(Math.max(0,z-1))},[_.length,b.length,g]),L.useEffect(()=>{if(!y.current)return;const z=y.current.querySelector(`[data-row="${g}"]`);z&&z.scrollIntoView({block:"nearest"})},[g]);const C=L.useCallback(z=>{try{const V=[z,...S.filter(H=>H!==z)].slice(0,e5);E(V),localStorage.setItem(Rk,JSON.stringify(V))}catch{}const U=i==null?void 0:i.id;if(!U){Le.error("No active tab to receive file path");return}const Y=(o?cb(z,o):z)||z;try{window.api.pty.write({tabId:U,data:Y})}catch(V){const H=V instanceof Error?V.message:String(V);dt.error("quick-open","pty.write failed",{error:H}),Le.error(`Failed to write to terminal: ${H}`);return}n()},[i==null?void 0:i.id,o,S,n]),N=L.useCallback(z=>{const U=_.length+b.length;if(z.key==="Escape"){z.preventDefault(),n();return}if(z.key==="ArrowDown"){if(z.preventDefault(),U===0)return;v(W=>Math.min(U-1,W+1));return}if(z.key==="ArrowUp"){if(z.preventDefault(),U===0)return;v(W=>Math.max(0,W-1));return}if(z.key==="Enter"){if(z.preventDefault(),g<_.length){const V=_[g];V&&C(V.path);return}const W=g-_.length,Y=b[W];Y&&C(Y.file.path)}},[g,b,_,C,n]);if(!e)return null;const $=(z,U)=>{if(U.length===0)return z;const W=new Set(U);return z.split("").map((Y,V)=>s.jsx("span",{className:W.has(V)?"text-accent font-semibold":"",children:Y},V))};let R=-1;const O=r==="page",I=s.jsx("div",{className:O?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[12vh]",onClick:O?void 0:z=>{z.target===z.currentTarget&&n()},"data-testid":"quick-open-backdrop",children:s.jsxs("div",{role:O?void 0:"dialog","aria-modal":O?void 0:"true","aria-label":"Quick Open",className:O?"h-full w-full flex flex-col":"w-[640px] max-w-[90vw] max-h-[70vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"quick-open",onKeyDown:N,children:[s.jsx("div",{className:"border-b border-line p-2",children:s.jsx("input",{ref:j,type:"text",value:l,onChange:z=>{d(z.target.value),v(0)},placeholder:o?"Search files in this project…":"No active tab — open a terminal first",disabled:!o,spellCheck:!1,autoComplete:"off",className:"w-full bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search files"})}),s.jsx("div",{ref:y,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:m?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Loading…"}):o?_.length===0&&b.length===0?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:l?"No files match.":"No files found in this project."}):s.jsxs(s.Fragment,{children:[_.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim",children:"Recent"}),_.map(z=>{R++;const U=R,W=U===g;return s.jsxs("button",{"data-row":U,role:"option","aria-selected":W,onClick:()=>C(z.path),onMouseEnter:()=>v(U),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${W?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"truncate",children:z.name}),s.jsx("span",{className:"text-xs text-fg-dim truncate",children:cb(Ak(z.path),o)})]},`r:${z.path}`)})]}),b.length>0&&s.jsxs("div",{children:[_.length>0&&s.jsx("div",{className:"px-3 pt-2 pb-1 text-[10px] uppercase tracking-wider text-fg-dim border-t border-line",children:"Files"}),b.map(({file:z,matched:U})=>{R++;const W=R,Y=W===g;return s.jsxs("button",{"data-row":W,role:"option","aria-selected":Y,onClick:()=>C(z.path),onMouseEnter:()=>v(W),className:`w-full text-left px-3 py-1.5 text-sm flex flex-col gap-0.5 ${Y?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"truncate",children:$(z.name,U)}),s.jsx("span",{className:"text-xs text-fg-dim truncate",children:cb(Ak(z.path),o)})]},z.path)})]})]}):s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable Quick Open."})}),s.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[s.jsxs("span",{children:[s.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert into terminal"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),s.jsxs("span",{children:[b.length+_.length," ",b.length+_.length===1?"file":"files"]})]})]})});return!O&&typeof document<"u"&&document.body?Hu.createPortal(I,document.body):I}function Mk(e,n){return e.startsWith(n+"/")?e.slice(n.length+1):e===n?"":e}function n5(e,n,r){if(!n)return e;const i=r?e:e.toLowerCase(),o=r?n:n.toLowerCase(),l=i.indexOf(o);return l<0?e:s.jsxs(s.Fragment,{children:[e.slice(0,l),s.jsx("span",{className:"text-accent font-semibold",children:e.slice(l,l+n.length)}),e.slice(l+n.length)]})}function r5({open:e,onClose:n,variant:r="overlay"}){const i=bt(V=>V.tabs.find(H=>H.id===V.activeTabId)??null),o=(i==null?void 0:i.cwd)??"",[l,d]=L.useState(""),[u,h]=L.useState(!1),[m,x]=L.useState([]),[g,v]=L.useState(!1),[S,E]=L.useState(null),[j,y]=L.useState(0),[b,_]=L.useState(null),C=L.useRef(null),N=L.useRef(null),$=L.useRef(0);L.useEffect(()=>{if(!e){d(""),x([]),E(null),y(0);return}const V=setTimeout(()=>{var H;return(H=C.current)==null?void 0:H.focus()},0);return()=>clearTimeout(V)},[e]),L.useEffect(()=>{if(!e||!o)return;const V=l.trim();if(!V){x([]),E(null),v(!1);return}const H=++$.current;v(!0);const te=setTimeout(()=>{window.api.search.text(o,V,{caseSensitive:u,limit:500}).then(ae=>{H===$.current&&(ae.ok?(x(ae.matches),E(null)):(E(ae.error??"unknown error"),x([])),_(ae.usedRipgrep))}).catch(ae=>{if(H!==$.current)return;const oe=ae instanceof Error?ae.message:String(ae);dt.error("global-search","search.text threw",{error:oe}),E(oe),x([])}).finally(()=>{H===$.current&&v(!1)})},250);return()=>clearTimeout(te)},[e,o,l,u]);const R=L.useMemo(()=>{const V=new Map;for(const te of m){const ae=V.get(te.path);ae?ae.push(te):V.set(te.path,[te])}const H=[];for(const[te,ae]of V)H.push({path:te,matches:ae});return H.sort((te,ae)=>ae.matches.length-te.matches.length||te.path.localeCompare(ae.path)),H},[m]),O=L.useMemo(()=>m,[m]);L.useEffect(()=>{j>=O.length&&y(Math.max(0,O.length-1))},[O.length,j]),L.useEffect(()=>{if(!N.current)return;const V=N.current.querySelector(`[data-match="${j}"]`);V&&V.scrollIntoView({block:"nearest"})},[j]);const I=L.useCallback(V=>{const H=i==null?void 0:i.id;if(!H){Le.error("No active tab to receive path");return}const ae=`${(o?Mk(V.path,o):V.path)||V.path}:${V.line}`;try{window.api.pty.write({tabId:H,data:ae})}catch(oe){const ie=oe instanceof Error?oe.message:String(oe);dt.error("global-search","pty.write failed",{error:ie}),Le.error(`Failed to write to terminal: ${ie}`);return}n()},[i==null?void 0:i.id,o,n]),z=L.useCallback(V=>{if(V.key==="Escape"){V.preventDefault(),n();return}if(V.key==="ArrowDown"){if(V.preventDefault(),O.length===0)return;y(H=>Math.min(O.length-1,H+1));return}if(V.key==="ArrowUp"){if(V.preventDefault(),O.length===0)return;y(H=>Math.max(0,H-1));return}if(V.key==="Enter"){V.preventDefault();const H=O[j];H&&I(H)}},[O,j,I,n]);if(!e)return null;const U=r==="page";let W=-1;const Y=s.jsx("div",{className:U?"h-full w-full flex flex-col bg-bg":"fixed inset-0 z-[55] flex items-start justify-center bg-black/60 pt-[8vh]",onClick:U?void 0:V=>{V.target===V.currentTarget&&n()},"data-testid":"global-search-backdrop",children:s.jsxs("div",{role:U?void 0:"dialog","aria-modal":U?void 0:"true","aria-label":"Search in project",className:U?"h-full w-full flex flex-col":"w-[840px] max-w-[95vw] h-[80vh] bg-bg-elev border border-line rounded shadow-xl flex flex-col","data-testid":"global-search",onKeyDown:z,children:[s.jsxs("div",{className:"border-b border-line p-2 flex items-center gap-2",children:[s.jsx("input",{ref:C,type:"text",value:l,onChange:V=>{d(V.target.value),y(0)},placeholder:o?"Search in this project…":"No active tab — open a terminal first",disabled:!o,spellCheck:!1,autoComplete:"off",className:"flex-1 bg-transparent text-fg placeholder:text-fg-dim outline-none px-2 py-1.5 text-sm","aria-label":"Search query"}),s.jsx("button",{type:"button",onClick:()=>h(V=>!V),className:`px-2 py-1 text-xs rounded border ${u?"bg-accent/20 border-accent text-accent":"bg-bg border-line text-fg-dim hover:text-fg"}`,title:"Match case","aria-pressed":u,children:"Aa"})]}),s.jsx("div",{ref:N,className:"flex-1 min-h-0 overflow-y-auto",role:"listbox",children:o?l.trim()?g?s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Searching…"}):S?s.jsx("div",{className:"px-4 py-6 text-sm text-red-400",children:S}):O.length===0?s.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["No matches for ",JSON.stringify(l),"."]}):s.jsx("div",{children:R.map(V=>s.jsxs("div",{children:[s.jsxs("div",{className:"sticky top-0 bg-bg-elev border-b border-line px-3 py-1 text-xs text-fg-dim font-mono truncate",children:[Mk(V.path,o)," ",s.jsxs("span",{className:"text-fg-faint",children:["(",V.matches.length,")"]})]}),V.matches.map(H=>{W++;const te=W,ae=te===j;return s.jsxs("button",{"data-match":te,role:"option","aria-selected":ae,onClick:()=>I(H),onMouseEnter:()=>y(te),className:`w-full text-left px-3 py-1 text-xs font-mono flex gap-3 ${ae?"bg-bg-hi text-fg":"hover:bg-bg-hi/50 text-fg"}`,children:[s.jsx("span",{className:"text-fg-dim shrink-0 w-12 text-right",children:H.line}),s.jsx("span",{className:"truncate",children:n5(H.text,l,u)})]},`${H.path}:${H.line}:${H.column}:${te}`)})]},V.path))}):s.jsxs("div",{className:"px-4 py-6 text-sm text-fg-dim",children:["Type to search files in ",s.jsx("span",{className:"font-mono",children:o}),"."]}):s.jsx("div",{className:"px-4 py-6 text-sm text-fg-dim",children:"Open a terminal tab to enable project search."})}),s.jsxs("div",{className:"border-t border-line px-3 py-1.5 flex items-center justify-between text-[10px] text-fg-dim",children:[s.jsxs("span",{children:[s.jsx("kbd",{className:"px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↑↓"})," navigate"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"↵"})," insert path"," ",s.jsx("kbd",{className:"ml-2 px-1 py-0.5 rounded bg-bg-hi border border-line",children:"Esc"})," close"]}),s.jsxs("span",{children:[O.length," ",O.length===1?"match":"matches",b===!1&&" · fs walk (rg missing)"]})]})]})});return!U&&typeof document<"u"&&document.body?Hu.createPortal(Y,document.body):Y}const s5=[{key:"files",label:"Files"},{key:"content",label:"Content"}];function i5({open:e,onClose:n,variant:r="page",initialMode:i="files"}){const[o,l]=L.useState(i);return L.useEffect(()=>{l(i)},[i]),e?s.jsxs("div",{className:"h-full w-full flex flex-col bg-bg",children:[s.jsxs("div",{className:"shrink-0 flex items-center gap-3 px-3 py-2 border-b border-line",children:[s.jsx(qu,{options:s5,active:o,onChange:l}),s.jsx("span",{className:"text-[11px] text-fg-faint",children:o==="files"?"⌘P · fuzzy-find a file in the active project":"⌘⇧F · ripgrep across the active project"})]}),s.jsx("div",{className:"flex-1 min-h-0",children:o==="files"?s.jsx(t5,{open:!0,onClose:n,variant:"page"}):s.jsx(r5,{open:!0,onClose:n,variant:"page"})})]}):null}class bj extends L.Component{constructor(){super(...arguments);Fn(this,"state",{error:null});Fn(this,"reset",()=>this.setState({error:null}))}static getDerivedStateFromError(r){return{error:r}}componentDidCatch(r,i){console.error("[ErrorBoundary]",r,i)}render(){return this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):s.jsxs("div",{className:"p-6 text-xs",children:[s.jsx("div",{className:"text-red-400 mb-2",children:"something broke in this panel"}),s.jsx("pre",{className:"text-fg-faint whitespace-pre-wrap mb-3",children:this.state.error.message}),s.jsx("button",{onClick:this.reset,className:"px-2 py-0.5 border border-line rounded text-fg-dim hover:text-fg hover:bg-bg-hi",children:"retry"})]}):this.props.children}}function o5({open:e,onClose:n,title:r,children:i,variant:o="overlay"}){return s.jsxs(Wu,{open:e,onClose:n,size:"xl",fillHeight:!0,noPadding:!0,title:void 0,variant:o,children:[o==="overlay"&&s.jsxs("div",{className:"flex items-center justify-between px-4 py-2 border-b border-line shrink-0",children:[s.jsx("h2",{className:"text-xs uppercase tracking-wider text-fg-dim",children:r}),s.jsx("button",{type:"button",onClick:n,"aria-label":"Close",className:"px-2 py-0.5 text-fg-dim hover:text-fg hover:bg-bg-hi rounded text-base leading-none",children:"✕"})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:s.jsx(bj,{children:i})})]})}function a5(e){return/^monitor of /i.test(e.trim())}function Ik(e){return e.replace(/\s*\([^)]*\)\s*$/,"").replace(/\s*#\d+\s*$/,"").replace(/\s+/g," ").trim().toLowerCase()}function Pk(e,n,r){if(e){const d=r.find(u=>u.deviceId===e);if(d)return d}if(!n)return null;const i=r.filter(d=>d.label===n);if(i.length===1)return i[0];if(i.length>1)return null;const o=Ik(n),l=r.filter(d=>d.label&&Ik(d.label)===o);return l.length===1?l[0]:null}async function Dk(e){var r;return(r=navigator.mediaDevices)!=null&&r.enumerateDevices?(await navigator.mediaDevices.enumerateDevices()).filter(i=>!(i.kind!=="audioinput"||i.label&&a5(i.label))):[]}const Ok=!1;function wj(){const e=$t(m=>m.isRecording);$t(m=>m.startRecording),$t(m=>m.stopRecording);const[n,r]=L.useState([]),[i,o]=L.useState(null),[l,d]=L.useState(null);L.useEffect(()=>{let m=!1;return(async()=>{try{const x=await window.api.voice.getDevicePref();if(m)return;const g=await Dk(Ok);if(m)return;r(g),d(x.selectedLabel);const v=Pk(x.selectedDeviceId,x.selectedLabel,g);v?(o(v.deviceId),x.selectedDeviceId&&v.deviceId!==x.selectedDeviceId&&(dt.info("voice","device-picker rebind-by-label",{fromIdPrefix:x.selectedDeviceId.slice(0,8),toIdPrefix:v.deviceId.slice(0,8)}),await window.api.voice.setDevicePref({selectedDeviceId:v.deviceId,selectedLabel:v.label||x.selectedLabel}).catch(()=>{}))):((x.selectedDeviceId||x.selectedLabel)&&(console.warn("[MicDevicePicker] previously-selected device unavailable; falling back to OS default",{savedLabel:x.selectedLabel,hadId:!!x.selectedDeviceId}),dt.warn("voice","device-picker selected-unavailable",{hadId:!!x.selectedDeviceId})),o(null))}catch(x){dt.warn("voice","device-picker init failed",{error:x instanceof Error?x.message:String(x)})}})(),()=>{m=!0}},[]);const u=L.useCallback(async()=>{try{const m=await Dk(Ok);if(r(m),i&&!m.some(x=>x.deviceId===i)){const x=Pk(null,l,m);x?(o(x.deviceId),await window.api.voice.setDevicePref({selectedDeviceId:x.deviceId,selectedLabel:x.label||l}).catch(()=>{})):o(null)}}catch(m){dt.warn("voice","device-picker refresh failed",{error:m instanceof Error?m.message:String(m)})}},[i,l]);L.useEffect(()=>{const m=()=>{u()};return window.addEventListener("mic-device-change",m),()=>window.removeEventListener("mic-device-change",m)},[u]);const h=async m=>{var S;const x=m.target.value,g=x===""?null:x,v=g?((S=n.find(E=>E.deviceId===g))==null?void 0:S.label)??null:null;o(g),d(v);try{await window.api.voice.setDevicePref({selectedDeviceId:g,selectedLabel:v}),dt.info("voice","device-picker selected",{deviceIdPrefix:g?g.slice(0,8):null})}catch(E){dt.warn("voice","setDevicePref failed",{error:E instanceof Error?E.message:String(E)})}if(e)try{await $t.getState().restartWithDevice()}catch(E){dt.warn("voice","device-picker restart failed",{error:E instanceof Error?E.message:String(E)})}};return s.jsxs("select",{value:i??"",onChange:h,onFocus:()=>{u()},title:"Microphone input device","data-testid":"mic-device-picker",className:"text-[10px] bg-bg border border-line text-fg-dim hover:text-fg rounded px-1.5 py-1 max-w-[8rem] truncate",children:[s.jsx("option",{value:"",children:"Default"}),n.map(m=>s.jsx("option",{value:m.deviceId,children:m.label||`Mic ${m.deviceId.slice(0,6)}`},m.deviceId))]})}function l5(){const e=$t(S=>S.isRecording),n=$t(S=>S.levelMeterEnabled),[r,i]=L.useState(0),[o,l]=L.useState(0),d=L.useRef(0);d.current=o;const[u,h]=L.useState(0),[m,x]=L.useState(!1),g=L.useRef(null);if(L.useEffect(()=>{if(!e||!n){i(0),l(0);return}let S=0,E=!1,j=null,y=null;const b=()=>{if(E)return;const C=y??X2();if(!C){S=requestAnimationFrame(b);return}y!==C&&(y=C,j=new Uint8Array(new ArrayBuffer(C.fftSize)));const N=j;C.getByteTimeDomainData(N);let $=0;for(let z=0;z<N.length;z++){const U=N[z]-128;$+=U*U}const R=Math.sqrt($/N.length)/128,O=R>0?20*Math.log10(R):-60,I=Math.max(0,Math.min(1,(O+60)/60));l(R),i(I),R>=.95&&(x(!0),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>x(!1),150)),S=requestAnimationFrame(b)};S=requestAnimationFrame(b);const _=setInterval(()=>{E||h(Math.round(d.current*100))},250);return()=>{E=!0,cancelAnimationFrame(S),clearInterval(_),g.current&&(clearTimeout(g.current),g.current=null)}},[e,n]),!e||!n)return null;const v=m?"bg-red-500":o>=.7?"bg-amber-400":"bg-green-500";return s.jsx("div",{role:"meter","aria-label":"Microphone input level","aria-valuenow":u,"aria-valuemin":0,"aria-valuemax":100,"data-testid":"mic-level-meter",className:`mx-3 mb-2 h-1 rounded bg-bg overflow-hidden ${m?"ring-1 ring-red-500":""}`,children:s.jsx("div",{className:`h-full ${v} transition-[width] duration-75 ease-out`,style:{width:`${r*100}%`}})})}function c5({open:e,onClose:n,variant:r="overlay"}){return s.jsx(o5,{open:e,onClose:n,title:"Voice / Microphone",variant:r,children:s.jsxs("div",{className:"p-4 space-y-4",children:[s.jsx(f5,{}),s.jsx(zC,{}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsx(J2,{}),s.jsx(wj,{}),s.jsx(QT,{})]}),s.jsx(u5,{}),s.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[s.jsx("button",{type:"button",onClick:()=>$t.getState().openWizard(),className:"text-xs text-fg-faint hover:text-fg-dim underline","data-testid":"run-mic-check",children:"Run mic check"}),s.jsx(h5,{})]}),s.jsx(l5,{})]})})}function u5(){const e=$t(l=>l.isRecording),[n,r]=L.useState(null);if(L.useEffect(()=>{let l=!1;window.api.voice.getHotkeyConfig().then(u=>{l||r(u)}).catch(()=>{});const d=window.api.voice.onHotkeyConfigChanged(u=>r(u));return()=>{l=!0,d()}},[]),e||!n)return null;const i=n.mode==="hold"?"Hold":"Press",o=d5(n.accelerator);return s.jsxs("div",{className:"text-[11px] text-fg-faint",children:[s.jsxs("span",{children:[i," "]}),s.jsx("kbd",{className:"px-1 py-0.5 rounded border border-line bg-bg font-mono text-fg-dim",children:o}),s.jsx("span",{children:" to record"})]})}function d5(e){const n=typeof navigator<"u"&&/Mac/.test(navigator.platform);return e.replace(/CommandOrControl/g,n?"⌘":"Ctrl").replace(/CmdOrCtrl/g,n?"⌘":"Ctrl").replace(/Command/g,"⌘").replace(/Control/g,"Ctrl").replace(/Option/g,n?"⌥":"Alt").replace(/Shift/g,n?"⇧":"Shift")}function h5(){const[e,n]=L.useState(null);if(L.useEffect(()=>{let i=!1;window.api.voice.getHotkeyConfig().then(l=>{i||n(l)}).catch(l=>dt.warn("voice-hotkey","getHotkeyConfig (toggle) failed",{error:String(l)}));const o=window.api.voice.onHotkeyConfigChanged(l=>{n(l)});return()=>{i=!0,o()}},[]),!e)return null;const r=async i=>{if(e.mode===i)return;const o={...e,mode:i};n(o);try{await window.api.voice.setHotkeyConfig(o)}catch(l){dt.warn("voice-hotkey","setHotkeyConfig (toggle) failed",{error:l instanceof Error?l.message:String(l)})}};return s.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-fg-faint select-none",title:"Mic hotkey behavior. Tap on/off: press once to start, again to stop. Hold to talk: record only while held (push-to-talk).",children:[s.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[s.jsx("input",{type:"radio",name:"hotkey-mode",checked:e.mode==="toggle",onChange:()=>r("toggle"),className:"cursor-pointer","data-testid":"hotkey-mode-toggle"}),s.jsx("span",{children:"Tap on/off"})]}),s.jsxs("label",{className:"flex items-center gap-1 cursor-pointer hover:text-fg-dim",children:[s.jsx("input",{type:"radio",name:"hotkey-mode",checked:e.mode==="hold",onChange:()=>r("hold"),className:"cursor-pointer","data-testid":"hotkey-mode-hold"}),s.jsx("span",{children:"Hold to talk"})]})]})}function f5(){const e=$t(l=>l.isRecording),n=$t(l=>l.lastTranscript),r=$t(l=>l.error),i=$t(l=>l.modelStatus),o=$t(l=>l.loadingProgress);return r?s.jsxs("div",{className:"text-[11px] text-red-400",title:r,children:["⚠ ",r]}):e?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-dim border border-line rounded px-2 py-1.5",children:[s.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-red-400 animate-pulse shrink-0"}),s.jsx("span",{className:"truncate",title:n,children:n||"Listening…"})]}):i==="loading"?s.jsxs("div",{className:"text-[11px] text-fg-faint",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("span",{children:"Loading speech model"}),s.jsxs("span",{className:"font-mono",children:[o,"%"]})]}),s.jsx("div",{className:"h-1 rounded bg-bg overflow-hidden",children:s.jsx("div",{className:"h-full bg-accent transition-[width] duration-200",style:{width:`${o}%`}})})]}):null}let ub=null;function p5(){return ub||(ub=Jm(()=>import("./monaco-editor-BW5C4Iv1.js").then(e=>e.b),__vite__mapDeps([1,2]),import.meta.url).then(e=>(f0.config({monaco:e}),e))),ub}function _j({value:e,onChange:n,path:r,readOnly:i}){const o=L.useRef(null),l=d=>{o.current=d};return s.jsx(p0,{path:`file://${r}`,defaultLanguage:"json",value:e,onChange:d=>n(d??""),onMount:l,theme:"vs",options:{minimap:{enabled:!1},fontSize:12,fontFamily:'"IBM Plex Mono", JetBrains Mono, ui-monospace, Menlo, monospace',lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,formatOnPaste:!0,readOnly:i,automaticLayout:!0,bracketPairColorization:{enabled:!0},wordWrap:"on"}})}let Lk=!1;async function m5(e){if(Lk)return;const n=await p5(),r=await Promise.all(e.map(async o=>{let l=o.schema;if(!l){const d=["https://json.schemastore.org","https://www.schemastore.org","https://code.claude.com"];try{const u=new URL(o.uri).origin;if(!d.includes(u))throw new Error("untrusted origin");const h=await fetch(o.uri);h.ok&&(l=await h.json())}catch{}}return{uri:o.uri,fileMatch:o.fileMatch,schema:l}}));n.languages.json.jsonDefaults.setDiagnosticsOptions({validate:!0,allowComments:!1,schemas:r.filter(o=>o.schema),enableSchemaRequest:!0}),Lk=!0}function b0({node:e,targetScope:n,onOverride:r,schema:i,rootLabel:o}){const[l,d]=L.useState(""),[u,h]=L.useState(!0),m=[],x=e.kind==="object"&&Object.keys(e.children).length===0,v=((i==null?void 0:i.rootKeys())??[]).length>0;return s.jsxs("div",{className:"h-full flex flex-col",children:[s.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:[s.jsxs("span",{className:"text-fg-faint",children:["merged · overrides → ",s.jsx("span",{className:"text-fg-dim",children:os[n].label})]}),v&&s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:u,onChange:S=>h(S.target.checked),className:"accent-accent"}),"show unset keys"]}),s.jsx("div",{className:"flex-1"}),s.jsx("input",{value:l,onChange:S=>d(S.target.value),placeholder:"filter keys or descriptions…",className:"bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg w-56"})]}),s.jsx("div",{className:"flex-1 overflow-auto px-3 py-2 font-mono text-xs",children:x&&!u?s.jsx("div",{className:"text-fg-faint italic px-2 py-4",children:"no settings resolved — all scope files empty or missing"}):s.jsx(kj,{node:e,path:m,label:o??"(root)",targetScope:n,onOverride:r,filter:l,depth:0,schema:i,showGhosts:u,defaultOpen:!0})})]})}function kj(e){return e.node.kind==="object"?s.jsx(g5,{...e,node:e.node}):e.node.kind==="array"?s.jsx(x5,{...e,node:e.node}):s.jsx(y5,{...e,node:e.node})}function zk(e,n){return n.trim()?e.toLowerCase().includes(n.toLowerCase()):!0}function Zh(e,n,r){return!!(!r.trim()||e.some(i=>zk(i,r))||n!=null&&n.description&&zk(n.description,r))}function g5({node:e,path:n,label:r,targetScope:i,onOverride:o,filter:l,depth:d,schema:u,showGhosts:h,defaultOpen:m}){const[x,g]=L.useState(m??d<2),v=(u==null?void 0:u.at(n))??null,S=new Set(Object.keys(e.children)),E=h?(v==null?void 0:v.knownChildren)??[]:[],j=Array.from(new Set([...S,...E])).sort(),y=L.useMemo(()=>l.trim()?j.filter(_=>{const C=(u==null?void 0:u.at([...n,_]))??null;return Zh([...n,_],C,l)?!0:S.has(_)?Sj(e.children[_],[...n,_],l,u):!1}):j,[j.join(","),l,e,n.join("."),u]);if(l.trim()&&y.length===0&&!Zh(n,v,l))return null;if(n.length===0)return s.jsx("div",{children:y.map(_=>b(_))});return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:d*14},onClick:()=>g(!x),children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:x?"▾":"▸"}),s.jsx("span",{className:"text-fg",children:r}),s.jsxs("span",{className:"text-fg-faint",children:[" {",S.size,E.length>S.size?`/${new Set([...S,...E]).size}`:"","}"]}),(v==null?void 0:v.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:v.description,children:["— ",v.description]})]}),x&&y.map(_=>b(_))]});function b(_){if(S.has(_))return s.jsx(kj,{node:e.children[_],path:[...n,_],label:_,targetScope:i,onOverride:o,filter:l,depth:d+1,schema:u,showGhosts:h},_);const C=(u==null?void 0:u.at([...n,_]))??null;return C?s.jsx(v5,{path:[...n,_],label:_,info:C,targetScope:i,onSet:o,depth:d+1,filter:l},_):null}}function Sj(e,n,r,i){const o=(i==null?void 0:i.at(n))??null;if(Zh(n,o,r))return!0;if(e.kind!=="object")return!1;for(const l of Object.keys(e.children))if(Sj(e.children[l],[...n,l],r,i))return!0;return!1}function x5({node:e,path:n,label:r,filter:i,depth:o,schema:l}){const[d,u]=L.useState(!0),h=(l==null?void 0:l.at(n))??null;return Zh(n,h,i)?s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-1 py-0.5 hover:bg-bg-elev/50 rounded cursor-pointer",style:{paddingLeft:o*14},onClick:()=>u(!d),children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0",children:d?"▾":"▸"}),s.jsx("span",{className:"text-fg",children:r}),s.jsxs("span",{className:"text-fg-faint",children:[" [",e.items.length,"]"]}),s.jsx(Hm,{tone:"warn",children:"accumulated"}),(h==null?void 0:h.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:h.description,children:["— ",h.description]})]}),d&&e.items.map((m,x)=>s.jsxs("div",{className:"flex items-start gap-2 py-0.5",style:{paddingLeft:(o+1)*14},children:[s.jsx("span",{className:"text-fg-faint w-3 shrink-0"}),s.jsxs("span",{className:"text-fg-faint",children:[x,":"]}),s.jsx("span",{className:"text-fg-dim truncate max-w-xl",children:$y(m.value)}),s.jsx(vw,{scope:m.fromScope})]},x))]}):null}function y5({node:e,path:n,label:r,targetScope:i,onOverride:o,filter:l,depth:d,schema:u}){const[h,m]=L.useState(!1),x=(u==null?void 0:u.at(n))??null;if(!Zh(n,x,l))return null;const g=e.winner!==i,v=e.shadowed.length>0;return s.jsxs("div",{children:[s.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded",style:{paddingLeft:d*14},children:[s.jsx("span",{className:`w-3 shrink-0 ${v?"text-fg-faint cursor-pointer":""}`,onClick:()=>v&&m(!h),children:v?h?"▾":"▸":""}),s.jsxs("span",{className:"text-fg",children:[r,":"]}),s.jsx("span",{className:"text-fg-dim truncate max-w-md",children:$y(e.value)}),s.jsx(vw,{scope:e.winner}),(x==null?void 0:x.deprecated)&&s.jsx(Hm,{tone:"warn",children:"deprecated"}),(x==null?void 0:x.default)!==void 0&&b5(e.value,x.default)&&s.jsx(Hm,{tone:"dim",children:"= default"}),e.typeMismatch&&s.jsx("span",{className:"text-yellow-500/80",title:"shadowed scopes have a different value type",children:"⚠"}),(x==null?void 0:x.description)&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:x.description,children:["— ",x.description]}),s.jsx("div",{className:"flex-1"}),(x==null?void 0:x.enum)&&s.jsx(Cj,{values:x.enum}),s.jsx("button",{disabled:!g,onClick:()=>o(n,e.value),className:`opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border rounded transition-opacity ${g?"border-accent/50 text-accent hover:bg-accent hover:text-bg":"border-line text-fg-faint cursor-not-allowed"}`,title:g?`copy into ${os[i].label} draft`:`already winning in ${os[i].label}`,children:"override"})]}),h&&e.shadowed.map((S,E)=>s.jsxs("div",{className:"flex items-center gap-2 py-0.5 text-fg-faint line-through",style:{paddingLeft:(d+1)*14+12},children:[s.jsx("span",{children:"shadowed:"}),s.jsx("span",{className:"truncate max-w-xl",children:$y(S.value)}),s.jsx(vw,{scope:S.scope,dim:!0})]},E))]})}function v5({path:e,label:n,info:r,targetScope:i,onSet:o,depth:l,filter:d}){if(!Zh(e,r,d))return null;const u=r.default!==void 0?r.default:w5(r.type),h=Array.isArray(r.type)?r.type.join("|"):r.type??"?";return s.jsxs("div",{className:"group flex items-center gap-2 py-0.5 hover:bg-bg-elev/50 rounded opacity-60",style:{paddingLeft:l*14},children:[s.jsx("span",{className:"w-3 shrink-0"}),s.jsx("span",{className:"text-fg-dim",children:n}),s.jsx(Hm,{tone:"dim",children:h}),r.required&&s.jsx(Hm,{tone:"warn",children:"required"}),r.default!==void 0&&s.jsxs("span",{className:"text-fg-faint",children:["default: ",$y(r.default)]}),r.description&&s.jsxs("span",{className:"text-fg-faint truncate max-w-md",title:r.description,children:["— ",r.description]}),s.jsx("div",{className:"flex-1"}),r.enum&&s.jsx(Cj,{values:r.enum}),s.jsx("button",{onClick:()=>o(e,u),className:"opacity-0 group-hover:opacity-100 px-1.5 py-0 text-[10px] border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg transition-opacity",title:`write to ${os[i].label} draft`,children:"set"})]})}function b5(e,n){return e===n?!0:typeof e!=typeof n?!1:e&&n&&typeof e=="object"?JSON.stringify(e)===JSON.stringify(n):!1}function w5(e){switch(Array.isArray(e)?e[0]:e){case"boolean":return!1;case"integer":case"number":return 0;case"string":return"";case"array":return[];case"object":return{};case"null":return null;default:return null}}function $y(e){if(typeof e=="string")return JSON.stringify(e);if(e===null)return"null";if(typeof e=="object"){const n=JSON.stringify(e);return n.length>100?n.slice(0,100)+"…":n}return String(e)}function vw({scope:e,dim:n}){const r=e==="user"?"bg-bg-hi text-fg-dim border-line":e==="project"?"bg-blue-950/30 text-blue-400/80 border-blue-900/40":"bg-purple-950/30 text-purple-400/80 border-purple-900/40";return s.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${r} ${n?"opacity-60":""}`,children:os[e].label})}function Hm({children:e,tone:n="default"}){const r={default:"bg-bg-hi text-fg-dim border-line",warn:"bg-yellow-950/30 text-yellow-500/80 border-yellow-900/40",dim:"bg-bg-elev text-fg-faint border-line"}[n];return s.jsx("span",{className:`text-[10px] px-1 py-0 rounded border uppercase tracking-wide shrink-0 ${r}`,children:e})}function Cj({values:e}){const n=e.map(r=>String(r)).join(" | ");return s.jsxs("span",{className:"text-[10px] text-fg-faint truncate max-w-xs",title:`allowed: ${n}`,children:["∈ ",n.length>30?n.slice(0,30)+"…":n]})}const _5=[{id:"essentials",title:"Essentials",summary:"The knobs you reach for first.",keys:["model","language","outputStyle","permissions"]},{id:"git",title:"Git & Commits",summary:"How Claude writes commits and pull requests on your behalf.",keys:["attribution","includeGitInstructions","includeCoAuthoredBy"]},{id:"memory",title:"Memory & Plans",summary:"Context Claude keeps between sessions and where it files plans.",keys:["autoMemoryEnabled","plansDirectory","claudeMdExcludes","respectGitignore"]},{id:"model",title:"Model & Reasoning",summary:"Which model runs, how hard it thinks, and fast-mode toggles.",keys:["availableModels","modelOverrides","effortLevel","fastMode","fastModePerSessionOptIn","alwaysThinkingEnabled"]},{id:"interface",title:"Interface",summary:"Visual polish — spinners, progress bars, motion.",keys:["spinnerTipsEnabled","spinnerTipsOverride","spinnerVerbs","terminalProgressBarEnabled","showTurnDuration","prefersReducedMotion","companyAnnouncements","statusLine","teammateMode"]},{id:"updates",title:"Updates & Cleanup",summary:"Release channel and how long transcripts stick around.",keys:["autoUpdatesChannel","cleanupPeriodDays"]},{id:"env",title:"Environment & Auth",summary:"Environment variables and auth-helper scripts.",keys:["env","apiKeyHelper","awsCredentialExport","awsAuthRefresh"]},{id:"hooks",title:"Hooks",summary:"Scripts Claude runs before/after tool use.",keys:["hooks","disableAllHooks","allowedHttpHookUrls","httpHookAllowedEnvVars"]},{id:"mcp",title:"MCP Servers",summary:"External tool providers Claude can talk to.",keys:["enableAllProjectMcpServers","enabledMcpjsonServers","disabledMcpjsonServers"]},{id:"plugins",title:"Plugins",summary:"Installed plugins, marketplaces, and per-plugin configuration.",keys:["enabledPlugins","extraKnownMarketplaces","skippedPlugins","skippedMarketplaces","pluginConfigs"]},{id:"filesystem",title:"File Picker & Sandbox",summary:"How Claude browses files and the sandbox it runs in.",keys:["fileSuggestion","sandbox","worktree"]},{id:"login",title:"Login",summary:"Which login method to force on startup.",keys:["forceLoginMethod","forceLoginOrgUUID"]},{id:"feedback",title:"Feedback",summary:"Session-quality surveys.",keys:["feedbackSurveyRate"]},{id:"advanced",title:"Advanced / Enterprise",summary:"Managed-settings-only keys and enterprise allow/denylists.",advanced:!0,keys:["allowedMcpServers","deniedMcpServers","allowManagedHooksOnly","allowManagedPermissionRulesOnly","allowManagedMcpServersOnly","strictKnownMarketplaces","blockedMarketplaces","pluginTrustMessage","otelHeadersHelper","skipWebFetchPreflight"]}],k5={mcp:"MCP",url:"URL",urls:"URLs",http:"HTTP",ui:"UI",id:"ID",uuid:"UUID",api:"API",aws:"AWS",otel:"OTel",json:"JSON"};function jj(e){return e.replace(/^\$/,"").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/\s+/).filter(Boolean).map((i,o)=>{const l=k5[i];return l||(o===0?i.charAt(0).toUpperCase()+i.slice(1):i)}).join(" ")}function Ej(e){const n=new Set,r=[];for(const o of _5){const l=o.keys.filter(d=>e.has(d));l.forEach(d=>n.add(d)),l.length!==0&&r.push({id:o.id,title:o.title,summary:o.summary,advanced:!!o.advanced,keys:l})}const i=Array.from(e).filter(o=>!n.has(o)&&o!=="$schema").sort();return i.length>0&&r.push({id:"other",title:"Other",summary:"Keys not yet grouped.",advanced:!1,keys:i}),r}function S5(e,n){return Ej(e).map(r=>({id:r.id,title:r.title,advanced:r.advanced,total:r.keys.length,setCount:r.keys.filter(i=>n.has(i)).length}))}const C5={};function Nj(e,n){if(n)return{text:n,authored:!1};const r=C5[e];return r?{text:r,authored:!0}:null}const j5={essentials:"star",git:"link",memory:"memory",model:"sparkle",interface:"eye",updates:"reload",env:"keys",hooks:"hooks",mcp:"mcp",plugins:"plugins",filesystem:"folder",login:"lock",feedback:"send",advanced:"shield",other:"dot"},E5=["user","project","local","default"],N5={user:"user",project:"project",local:"local",default:"default"};function T5({node:e,targetScope:n,onOverride:r,schema:i}){const[o,l]=L.useState(""),[d,u]=L.useState(!1),[h,m]=L.useState(!0),x=e.kind==="object"?e:null,g=x?Object.keys(x.children):[],v=i.rootKeys(),S=new Set([...g,...v]),E=L.useMemo(()=>Ej(S),[Array.from(S).sort().join(",")]),j=L.useMemo(()=>S5(S,new Set(g)),[Array.from(S).sort().join(","),g.join(",")]),[y,b]=L.useState(null),_=N=>{const $=E.find(R=>R.id===N);$!=null&&$.advanced&&!d&&u(!0),b(N)};L.useEffect(()=>{if(!y)return;const N=document.getElementById(`settings-group-${y}`);N&&(N.scrollIntoView({behavior:"smooth",block:"start"}),b(null))});const C=L.useMemo(()=>E.filter(N=>d||!N.advanced).map(N=>({...N,keys:N.keys.filter($=>{const R=(x==null?void 0:x.children[$])!==void 0;if(!h&&!R)return!1;if(!o.trim())return!0;const O=i.at([$]);return[$,jj($),(O==null?void 0:O.description)??""].join(" ").toLowerCase().includes(o.toLowerCase())})})).filter(N=>N.keys.length>0),[E,o,d,h,x,i]);return s.jsxs("div",{className:"h-full flex flex-col",children:[s.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-3 text-xs",children:[s.jsxs("span",{className:"text-fg-faint",children:["writing overrides to"," ",s.jsx("span",{className:"text-fg-dim font-medium",children:os[n].label})]}),s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:h,onChange:N=>m(N.target.checked),className:"accent-accent"}),"show not-yet-configured"]}),s.jsxs("label",{className:"flex items-center gap-1 text-fg-faint cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:d,onChange:N=>u(N.target.checked),className:"accent-accent"}),"show advanced"]}),s.jsx("div",{className:"flex-1"}),s.jsx("input",{value:o,onChange:N=>l(N.target.value),placeholder:"search settings…",className:"bg-bg border border-line rounded px-2 py-1 text-xs text-fg w-64"})]}),s.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[s.jsx($5,{groups:j,onJump:_}),s.jsxs("div",{className:"flex-1 overflow-auto py-3",children:[C.map(N=>s.jsx(A5,{id:N.id,title:N.title,summary:N.summary,advanced:N.advanced,children:N.keys.map($=>{const R=x==null?void 0:x.children[$],O=i.at([$]);return s.jsx(R5,{keyName:$,node:R,info:O,targetScope:n,onOverride:(I,z)=>r([$],I,z)},$)})},N.id)),C.length===0&&s.jsxs("div",{className:"px-6 py-12 text-center text-fg-faint text-sm",children:['no settings match "',o,'"']})]})]})]})}function $5({groups:e,onJump:n}){return s.jsx("nav",{className:"shrink-0 w-48 border-r border-line bg-bg-elev/30 overflow-y-auto py-3",children:e.map(r=>s.jsxs("button",{onClick:()=>n(r.id),className:"w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-bg-hi transition-colors",title:`jump to ${r.title}`,children:[s.jsx(dn,{name:j5[r.id]??"dot",size:15,className:"text-fg-faint shrink-0"}),s.jsx("span",{className:"flex-1 min-w-0 truncate text-xs text-fg-dim",children:r.title}),s.jsxs("span",{className:"text-[10px] text-fg-faint font-mono shrink-0",children:[r.setCount,"/",r.total]})]},r.id))})}function A5({id:e,title:n,summary:r,advanced:i,children:o}){const[l,d]=L.useState(!0);return s.jsxs("section",{id:`settings-group-${e}`,className:"mx-4 mb-4 rounded-lg border border-line shadow-sm bg-bg-elev/50 overflow-hidden",children:[s.jsxs("header",{className:"px-4 py-3 bg-bg-elev cursor-pointer hover:bg-bg-hi flex items-center gap-3 border-b border-line",onClick:()=>d(!l),children:[s.jsx("span",{className:"text-fg-faint w-3",children:l?"▾":"▸"}),s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("h2",{className:"text-fg text-base font-semibold",children:n}),i&&s.jsx("span",{className:"text-[9px] px-1.5 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"advanced"})]}),s.jsx("p",{className:"text-fg-dim text-sm mt-0.5",children:r})]})]}),l&&s.jsx("div",{className:"divide-y divide-line/60",children:o})]})}function R5({keyName:e,node:n,info:r,targetScope:i,onOverride:o}){const[l,d]=L.useState(!1),[u,h]=L.useState(!1),m=jj(e),x=n!==void 0,v=(n==null?void 0:n.kind)==="leaf"?n:null,S=(n==null?void 0:n.kind)==="object"||(n==null?void 0:n.kind)==="array",E=r==null?void 0:r.default,j=v&&E!==void 0&&$j(v.value,E),y=B5({isSet:x,leafNode:v,defaultVal:E,isDefault:!!j,node:n}),b=M5(v,E),_=b.length>=2,C=!!v&&!j,N=Nj(e,r==null?void 0:r.description);return s.jsx("div",{className:"px-4 py-3 hover:bg-bg-elev/20",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.jsx("button",{onClick:()=>d(!l),className:"text-fg-faint hover:text-fg w-3 mt-0.5",title:l?"collapse":"expand",children:l?"▾":"▸"}),s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"flex items-baseline gap-2 flex-wrap",children:[s.jsx("h3",{className:"text-fg text-sm",children:m}),s.jsx(F5,{kind:y.kind,label:y.label}),_&&s.jsxs("button",{onClick:$=>{$.stopPropagation(),l||d(!0),h(R=>!R)},className:"text-[9px] px-1.5 py-0 rounded border border-blue-900/40 bg-blue-950/30 text-blue-300/90 uppercase tracking-wide hover:bg-blue-900/40",title:"this key is defined in multiple scopes — click to expand",children:["drift · ",b.map($=>N5[$]).join(" · ")]}),C&&v&&s.jsx("button",{onClick:$=>{$.stopPropagation(),o(void 0,v.winner)},className:"text-[9px] px-1.5 py-0 rounded border border-line bg-bg-elev text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`reset · delete from ${os[v.winner].label}`,children:"↺ reset"}),(r==null?void 0:r.deprecated)&&s.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-yellow-900/40 bg-yellow-950/30 text-yellow-500/80 uppercase tracking-wide",children:"deprecated"}),(r==null?void 0:r.required)&&!x&&s.jsx("span",{className:"text-[9px] px-1 py-0 rounded border border-red-900/40 bg-red-950/30 text-red-400/80 uppercase tracking-wide",children:"required"})]}),N&&s.jsx("p",{className:`text-fg-dim text-xs mt-0.5 leading-relaxed ${N.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:N.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:U5(N.text)}),l&&u&&v&&s.jsx(I5,{leaf:v,defaultVal:E,onReset:$=>o(void 0,$)}),l&&s.jsx(P5,{keyName:e,node:n,info:r,targetScope:i,onOverride:$=>o($)})]}),s.jsx("div",{className:"shrink-0",children:!l&&s.jsx(z5,{node:n,info:r,onSet:$=>{o($)},disabled:S&&x})})]})})}function M5(e,n){if(!e)return[];const r=new Set;r.add(e.winner);for(const i of e.shadowed)r.add(i.scope);return n!==void 0&&r.add("default"),E5.filter(i=>r.has(i))}function I5({leaf:e,defaultVal:n,onReset:r}){const i={};i[e.winner]={value:e.value,winner:!0};for(const o of e.shadowed)i[o.scope]={value:o.value,winner:!1};return s.jsxs("div",{className:"mt-2 border border-line rounded bg-bg-elev/40 text-xs",children:[s.jsx("div",{className:"px-2 py-1 text-fg-faint border-b border-line/60",children:"Values across all scopes (winner highlighted · reset removes that scope's value):"}),s.jsxs("div",{className:"divide-y divide-line/60",children:[["user","project","local"].map(o=>{const l=i[o],d=l!==void 0;return s.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[s.jsx("span",{className:"text-fg-faint",children:os[o].label}),s.jsx("span",{className:`font-mono truncate ${l!=null&&l.winner?"text-accent":"text-fg-dim"}`,children:d?Vh(l.value):s.jsx("span",{className:"text-fg-faint",children:"—"})}),d?s.jsx("button",{onClick:()=>r(o),className:"text-[9px] px-1.5 py-0 rounded border border-line text-fg-faint uppercase tracking-wide hover:text-fg hover:bg-bg-hi",title:`delete this key from ${os[o].label}`,children:"↺"}):s.jsx("span",{})]},o)}),s.jsxs("div",{className:"grid grid-cols-[5rem_1fr_auto] gap-2 px-2 py-1 items-center",children:[s.jsx("span",{className:"text-fg-faint",children:"Default"}),s.jsx("span",{className:"font-mono text-fg-dim truncate",children:n!==void 0?Vh(n):s.jsx("span",{className:"text-fg-faint",children:"—"})}),s.jsx("span",{})]})]})]})}function P5({keyName:e,node:n,info:r,targetScope:i,onOverride:o}){const d=(n==null?void 0:n.kind)==="leaf"?n:null,u=Nj(e,r==null?void 0:r.description);return s.jsxs("div",{className:"mt-3 space-y-2 text-xs",children:[u&&s.jsx("p",{className:`text-fg-dim leading-relaxed whitespace-pre-wrap ${u.authored?"inline-block border-b border-dotted border-fg-faint/70 cursor-help":""}`,title:u.authored?"In-app-authored description — not from the official Claude Code schema":void 0,children:u.text}),s.jsxs("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-fg-faint",children:[(r==null?void 0:r.type)&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Type"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:Array.isArray(r.type)?r.type.join(" | "):r.type})]}),(r==null?void 0:r.default)!==void 0&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Default"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:Vh(r.default)})]}),(r==null?void 0:r.enum)&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Options"}),s.jsx("dd",{className:"text-fg-dim font-mono",children:r.enum.map(h=>String(h)).join(" | ")})]}),d&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Current"}),s.jsxs("dd",{className:"font-mono",children:[s.jsx("span",{className:"text-fg-dim",children:Vh(d.value)}),s.jsxs("span",{className:"ml-2 text-fg-faint",children:["from ",os[d.winner].label]})]})]}),d&&d.shadowed.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Shadowed"}),s.jsx("dd",{className:"space-y-0.5",children:d.shadowed.map((h,m)=>s.jsxs("div",{className:"font-mono text-fg-faint line-through",children:[Vh(h.value)," —"," ",s.jsx("span",{className:"no-underline",children:os[h.scope].label})]},m))})]}),(n==null?void 0:n.kind)==="array"&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Accumulated"}),s.jsxs("dd",{className:"text-fg-dim",children:[n.items.length," items across all scopes"]})]})]}),s.jsx("div",{className:"pt-2 flex items-center gap-2 flex-wrap border-t border-line/60",children:s.jsx(D5,{keyName:e,node:n,info:r,onChange:o,targetScope:i})})]})}function D5({node:e,info:n,onChange:r,targetScope:i}){const l=(e==null?void 0:e.kind)==="leaf"?e.value:n==null?void 0:n.default,d=Tj(n==null?void 0:n.type);if(d==="boolean"){const u=l===!0;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:"Set to:"}),s.jsx("div",{className:"inline-flex rounded border border-line overflow-hidden",children:[{v:!0,label:"on"},{v:!1,label:"off"}].map(({v:h,label:m})=>s.jsx("button",{onClick:()=>r(h),className:`px-3 py-0.5 text-xs transition-colors ${u===h?"bg-accent text-bg":"bg-bg-elev text-fg-dim hover:bg-bg-hi hover:text-fg"}`,children:m},m))}),s.jsxs("span",{className:"text-fg-faint",children:["→ ",os[i].label]})]})}return n!=null&&n.enum?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-fg-faint",children:"Choose:"}),n.enum.map(u=>{const h=$j(l,u);return s.jsx("button",{onClick:()=>r(u),className:`px-2 py-0.5 text-xs rounded border ${h?"bg-accent text-bg border-accent":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,children:String(u)},String(u))}),s.jsxs("span",{className:"text-fg-faint",children:["→ ",os[i].label]})]}):d==="integer"||d==="number"?s.jsx(O5,{value:typeof l=="number"?l:void 0,integer:d==="integer",onCommit:r,target:os[i].label}):d==="string"?s.jsx(L5,{value:typeof l=="string"?l:"",onCommit:r,target:os[i].label}):s.jsxs("div",{className:"text-fg-faint",children:["Complex value (",d??"object/array",") — use the"," ",s.jsx("span",{className:"text-fg-dim",children:"Raw"})," tab to edit."]})}function O5({value:e,integer:n,onCommit:r,target:i}){const[o,l]=L.useState(e!==void 0?String(e):""),d=()=>{const u=n?parseInt(o,10):parseFloat(o);Number.isNaN(u)||r(u)};return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-fg-faint",children:"Set to:"}),s.jsx("input",{type:"number",value:o,onChange:u=>l(u.target.value),onBlur:d,onKeyDown:u=>{u.key==="Enter"&&u.target.blur()},className:"w-24 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),s.jsxs("button",{onClick:d,className:"px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",i]})]})}function L5({value:e,onCommit:n,target:r}){const[i,o]=L.useState(e);return s.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[s.jsx("span",{className:"text-fg-faint shrink-0",children:"Set to:"}),s.jsx("input",{type:"text",value:i,onChange:l=>o(l.target.value),onKeyDown:l=>{l.key==="Enter"&&n(i)},className:"flex-1 min-w-0 bg-bg border border-line rounded px-2 py-0.5 text-xs text-fg"}),s.jsxs("button",{onClick:()=>n(i),className:"shrink-0 px-2 py-0.5 text-xs border border-accent/50 rounded text-accent hover:bg-accent hover:text-bg",children:["save → ",r]})]})}function z5({node:e,info:n,onSet:r,disabled:i}){const o=(e==null?void 0:e.kind)==="leaf",l=Tj(n==null?void 0:n.type);if(i)return null;if(l==="boolean"){const d=o&&e.value===!0;return s.jsx("button",{onClick:()=>r(!d),className:`px-2.5 py-0.5 text-xs rounded border transition-colors ${d?"bg-accent/15 text-accent border-accent/40 hover:bg-accent hover:text-bg":"bg-bg-elev text-fg-dim border-line hover:text-fg hover:bg-bg-hi"}`,title:"toggle",children:d?"on":"off"})}return null}function B5({isSet:e,leafNode:n,defaultVal:r,isDefault:i,node:o}){return e?(o==null?void 0:o.kind)==="array"?{kind:"accumulated",label:`${o.items.length} items`}:(o==null?void 0:o.kind)==="object"?{kind:"set",label:"configured"}:n?i?{kind:"default",label:`= default · ${os[n.winner].label}`}:n.shadowed.length>0?{kind:"override",label:`overriding ${n.shadowed.length} scope(s)`}:{kind:"set",label:`set in ${os[n.winner].label}`}:{kind:"set",label:"configured"}:r!==void 0?{kind:"default",label:`using default: ${Vh(r)}`}:{kind:"unset",label:"not configured"}}function F5({kind:e,label:n}){const r={set:"bg-accent/15 text-accent border-accent/30",default:"bg-bg-hi text-fg-dim border-line",unset:"bg-bg-elev text-fg-faint border-line",override:"bg-purple-950/30 text-purple-400/80 border-purple-900/40",accumulated:"bg-blue-950/30 text-blue-400/80 border-blue-900/40"}[e];return s.jsx("span",{className:`text-[9px] px-1.5 py-0 rounded border uppercase tracking-wide ${r}`,children:n})}function Tj(e){if(e)return Array.isArray(e)?e.find(r=>r!=="null")??e[0]:e}function $j(e,n){return e===n?!0:typeof e!=typeof n?!1:e&&n&&typeof e=="object"?JSON.stringify(e)===JSON.stringify(n):!1}function U5(e){const n=e.trim().split(`
|
|
3394
3394
|
`)[0],r=n.match(/^([^.!?]+[.!?])/);return r?r[1]:n.length>120?n.slice(0,120)+"…":n}function Vh(e){if(typeof e=="string")return e===""?'""':JSON.stringify(e);if(e===null)return"null";if(e===void 0)return"—";if(typeof e=="object"){const n=JSON.stringify(e);return n.length>60?n.slice(0,60)+"…":n}return String(e)}function w0(e,n,r){const i=tn(h=>h.files),o=tn(h=>h.loadJson),l=tn(h=>h.watchFile),d=tn(h=>h.unwatchFile),u=L.useMemo(()=>{const h={};for(const m of e.scopes){const x=e.resolve(m,n??"",r);x&&(h[m]=x)}return h},[e,n,r]);return L.useEffect(()=>{const h=Object.values(u).filter(Boolean);return h.forEach(m=>{i[m]||o(m),l(m)}),()=>{h.forEach(m=>d(m))}},[JSON.stringify(u)]),u}const H5=[];function Mx(e){return Array.isArray(e)?"array":e!==null&&typeof e=="object"?"object":"scalar"}function _0(e){const n=e.filter(r=>r.data!==void 0);return n.length===0?{kind:"object",children:{}}:Aj(n,[])}function Aj(e,n){const r=H5.includes(n.join(".")),i=e.every(x=>Mx(x.data)==="object"),o=e.every(x=>Mx(x.data)==="array");if(i){const x=new Set;for(const v of e)for(const S of Object.keys(v.data))x.add(S);const g={};for(const v of x){const S=e.filter(E=>v in E.data).map(E=>({scope:E.scope,data:E.data[v]}));g[v]=Aj(S,[...n,v])}return{kind:"object",children:g}}if(o&&!r){const x=[];for(const g of[...e].reverse())for(const v of g.data)x.push({value:v,fromScope:g.scope,index:x.length});return{kind:"array",items:x}}const l=[...e].reverse(),d=l[0],u=l.slice(1).map(x=>({scope:x.scope,value:x.data})),h=Mx(d.data),m=u.some(x=>Mx(x.value)!==h);return{kind:"leaf",value:d.data,winner:d.scope,shadowed:u,...m?{typeMismatch:!0}:{}}}function k0(e,n){if(n.length===0)return e;if(e.kind!=="object")return null;const[r,...i]=n,o=e.children[r];return o?k0(o,i):null}function iv(e,n,r){if(n.length===0)return r;const[i,...o]=n,l=e&&typeof e=="object"&&!Array.isArray(e)?{...e}:{};return l[i]=iv(l[i],o,r),l}const W5=["user","project","local"];function S0(e,n){const r=[];for(const i of W5){const o=n[i];if(!o)continue;const l=e[o];if(!l||!l.exists)continue;const d=l.draftRaw??"";if(d.trim())try{r.push({scope:i,data:JSON.parse(d)})}catch{}}return r}const q5="http://json-schema.org/draft-07/schema#",V5="https://json.schemastore.org/claude-code-settings.json",G5={permissionRule:{type:"string",description:`Tool permission rule.
|
|
3395
3395
|
See https://code.claude.com/docs/en/settings#permission-rule-syntax
|
|
3396
3396
|
See https://code.claude.com/docs/en/settings#tools-available-to-claude for full list of tools available to Claude.`,pattern:"^((Agent|Bash|Edit|ExitPlanMode|Glob|Grep|KillShell|LSP|NotebookEdit|Read|Skill|TaskCreate|TaskGet|TaskList|TaskOutput|TaskStop|TaskUpdate|TodoWrite|ToolSearch|WebFetch|WebSearch|Write)(\\((?=.*[^)*?])[^)]+\\))?|mcp__.*)$",examples:["Bash","Bash(npm run build)","Bash(git commit *)","Bash(npm run *)","Bash(ls*)","Bash(git * main)","Edit","Edit(/src/**/*.ts)","Read(./.env)","Read(./secrets/**)","Read(//Users/alice/secrets/**)","Read(~/Documents/*.pdf)","Agent(Explore)","WebFetch","WebFetch(domain:example.com)","mcp__puppeteer","mcp__github__search_repositories"]},hookCommand:{anyOf:[{type:"object",description:"Bash command hook",additionalProperties:!1,required:["type","command"],properties:{type:{type:"string",description:"Hook type",const:"command"},command:{type:"string",description:"Shell command to execute",minLength:1},timeout:{type:"number",description:"Optional timeout in seconds",exclusiveMinimum:0},async:{type:"boolean",description:"Run this hook asynchronously without blocking Claude Code"},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"LLM prompt hook. See https://code.claude.com/docs/en/hooks#prompt-based-hooks",additionalProperties:!1,required:["type","prompt"],properties:{type:{type:"string",description:"Hook type",const:"prompt"},prompt:{type:"string",description:"Prompt to evaluate with LLM. Use $ARGUMENTS placeholder for hook input JSON.",minLength:1},model:{type:"string",description:"Model to use for evaluation. Defaults to a fast model"},timeout:{type:"number",description:"Optional timeout in seconds (default: 30)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"Agent hook with multi-turn tool access for verification. See https://code.claude.com/docs/en/hooks#agent-based-hooks",additionalProperties:!1,required:["type","prompt"],properties:{type:{type:"string",description:"Hook type",const:"agent"},prompt:{type:"string",description:"Prompt describing what to verify. Use $ARGUMENTS placeholder for hook input JSON.",minLength:1},model:{type:"string",description:"Model to use for evaluation. Defaults to a fast model"},timeout:{type:"number",description:"Optional timeout in seconds (default: 60)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}},{type:"object",description:"HTTP webhook hook. POST JSON to a URL and receive JSON response. See https://code.claude.com/docs/en/hooks#http-hooks",additionalProperties:!1,required:["type","url"],properties:{type:{type:"string",description:"Hook type",const:"http"},url:{type:"string",description:"URL to POST hook input JSON to. Endpoint must accept POST requests and return JSON.",minLength:1},headers:{type:"object",additionalProperties:{type:"string"},description:"Custom HTTP headers (e.g., Authorization: Bearer token). Values support $VAR_NAME or ${VAR_NAME} interpolation."},allowedEnvVars:{type:"array",items:{type:"string",minLength:1},description:"List of environment variable names permitted for interpolation in headers. If not set, no env var interpolation is allowed."},timeout:{type:"number",description:"Optional timeout in seconds (default: 30)",exclusiveMinimum:0},statusMessage:{type:"string",description:"Custom spinner message displayed while the hook runs"}}}]},hookMatcher:{type:"object",description:"Hook matcher configuration with multiple hooks",additionalProperties:!1,required:["hooks"],properties:{matcher:{type:"string",description:"Optional pattern to match event contexts, case-sensitive. Behavior depends on event type. See https://code.claude.com/docs/en/hooks#matcher-patterns for event-specific details and examples"},hooks:{type:"array",description:"Array of hooks to execute",items:{$ref:"#/$defs/hookCommand"}}}}},K5="Configuration settings for Claude Code. Learn more: https://code.claude.com/docs/en/settings",X5=!0,Y5=!0,J5="object",Q5=JSON.parse(`{"$schema":{"type":"string","description":"JSON Schema reference for Claude Code settings"},"apiKeyHelper":{"type":"string","description":"Path to a script that outputs authentication values","examples":["/bin/generate_temp_api_key.sh"],"minLength":1},"autoMemoryEnabled":{"type":"boolean","description":"Enable automatic memory saves that capture useful context to .claude/memory/. Also configurable via CLAUDE_CODE_DISABLE_AUTO_MEMORY environment variable (set to 1 to disable, 0 to enable). See https://code.claude.com/docs/en/memory#auto-memory","default":true},"autoUpdatesChannel":{"type":"string","enum":["stable","latest"],"description":"Release channel to follow for updates. Use \\"stable\\" for a version that is typically about one week old and skips versions with major regressions, or \\"latest\\" (default) for the most recent release. Set DISABLE_AUTOUPDATER=1 to disable updates entirely.","default":"latest"},"awsCredentialExport":{"type":"string","description":"Path to a script that exports AWS credentials","examples":["/bin/generate_aws_grant.sh"],"minLength":1},"awsAuthRefresh":{"type":"string","description":"Path to a script that refreshes AWS authentication","examples":["aws sso login --profile myprofile"],"minLength":1},"claudeMdExcludes":{"type":"array","items":{"type":"string","minLength":1},"description":"Glob patterns for CLAUDE.md files to exclude from loading. Useful in monorepos to skip irrelevant instructions from other teams. Patterns match against absolute file paths. Arrays merge across settings layers. Managed policy CLAUDE.md files cannot be excluded. See https://code.claude.com/docs/en/memory#exclude-specific-claudemd-files","examples":[["**/monorepo/CLAUDE.md","/home/user/monorepo/other-team/.claude/rules/**"]]},"cleanupPeriodDays":{"type":"integer","minimum":0,"description":"Number of days to retain chat transcripts (0 to disable cleanup)","examples":[20,30,60],"default":30},"env":{"type":"object","additionalProperties":false,"description":"Environment variables to set for Claude Code sessions. Many environment variables provide settings dimensions not available as dedicated settings.json properties (e.g., thinking tokens, prompt caching, bash timeouts, shell configuration). See https://code.claude.com/docs/en/settings#environment-variables for the full list.\\nUNDOCUMENTED: CLAUDE_CODE_PLUGIN_GIT_TIMEOUT_MS (plugin marketplace git timeout in ms, default 120000, see https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md#2151).\\nUNDOCUMENTED: ENABLE_CLAUDEAI_MCP_SERVERS (set to false to opt out of claude.ai MCP servers, see https://github.com/anthropics/claude-code/blob/main/CHANGELOG.md#2163).","examples":[{"ANTHROPIC_MODEL":"claude-opus-4-1","ANTHROPIC_SMALL_FAST_MODEL":"claude-3-5-haiku-latest"}],"default":{},"patternProperties":{"^[A-Z_][A-Z0-9_]*$":{"type":"string","description":"Environment variable value"}}},"attribution":{"type":"object","description":"Customize attribution for git commits and pull requests. See https://code.claude.com/docs/en/settings#attribution-settings","additionalProperties":false,"properties":{"commit":{"type":"string","description":"Attribution for git commits, including any trailers. Empty string hides commit attribution"},"pr":{"type":"string","description":"Attribution for pull request descriptions. Empty string hides pull request attribution"}}},"includeGitInstructions":{"type":"boolean","description":"Include built-in git commit and PR workflow instructions in Claude's system prompt. Also configurable via CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS environment variable (set to 1 to disable). See https://code.claude.com/docs/en/settings#available-settings","default":true},"includeCoAuthoredBy":{"type":"boolean","description":"DEPRECATED. Use 'attribution' instead. Whether to include the co-authored-by Claude byline in git commits and pull requests (default: true)","default":true},"plansDirectory":{"type":"string","description":"Customize where plan files are stored. Path is relative to project root (default: ~/.claude/plans)","default":"~/.claude/plans","examples":["./plans"]},"respectGitignore":{"type":"boolean","description":"Control whether the @ file picker respects .gitignore patterns. When true (default), files matching .gitignore patterns are excluded from suggestions","default":true},"permissions":{"type":"object","properties":{"allow":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules for allowed operations","uniqueItems":true},"deny":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules for denied operations","uniqueItems":true},"ask":{"type":"array","items":{"$ref":"#/$defs/permissionRule"},"description":"List of permission rules that should always prompt for confirmation","uniqueItems":true},"defaultMode":{"type":"string","enum":["acceptEdits","bypassPermissions","default","delegate","dontAsk","plan"],"description":"Default permission mode.\\n\\"default\\": prompts on first use.\\n\\"acceptEdits\\": auto-accepts file edits.\\n\\"plan\\": read-only, no modifications.\\nUNDOCUMENTED. \\"delegate\\": coordination-only for agent team leads (agent teams are experimental; enable via CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS).\\n\\"dontAsk\\": auto-denies unless pre-approved via permissions.\\n\\"bypassPermissions\\": skips all prompts (use only in isolated environments).\\nSee https://code.claude.com/docs/en/permissions"},"disableBypassPermissionsMode":{"type":"string","enum":["disable"],"description":"Disable the ability to bypass permission prompts"},"additionalDirectories":{"type":"array","items":{"type":"string","minLength":1},"description":"Additional directories to include in the permission scope","examples":[["//Users/alice/Documents","~/projects"]],"uniqueItems":true}},"additionalProperties":false,"description":"Tool usage permissions configuration.\\nSee https://code.claude.com/docs/en/permissions and https://code.claude.com/docs/en/settings#permission-settings\\nSee https://code.claude.com/docs/en/settings#tools-available-to-claude for full list of tools available to Claude.","examples":[{"allow":["Bash(git add:*)"],"ask":["Bash(gh pr create:*)","Bash(git commit:*)"],"deny":["Read(*.env)","Bash(rm:*)","Bash(curl:*)"],"defaultMode":"default"}]},"language":{"type":"string","description":"Preferred language for Claude's responses","examples":["japanese","spanish","french"]},"model":{"type":"string","enum":["opus","sonnet","haiku","default"],"description":"Override the default model used by Claude Code. Accepts a short alias (opus|sonnet|haiku) or a full model ID. For finer control, use environment variables: ANTHROPIC_MODEL (runtime override), ANTHROPIC_DEFAULT_OPUS_MODEL, ANTHROPIC_DEFAULT_SONNET_MODEL, ANTHROPIC_DEFAULT_HAIKU_MODEL (per-class pinning), CLAUDE_CODE_SUBAGENT_MODEL (subagent model). See https://code.claude.com/docs/en/model-config"},"availableModels":{"type":"array","items":{"type":"string"},"description":"Restrict which models users can select. When defined at multiple settings levels (user, project, etc.), arrays are merged and deduplicated. See https://code.claude.com/docs/en/model-config#restrict-model-selection","examples":[["sonnet","haiku"]]},"modelOverrides":{"type":"object","additionalProperties":{"type":"string"},"description":"Map Anthropic model IDs to provider-specific model IDs such as Bedrock inference profile ARNs, Vertex AI version names, or Foundry deployment names. Each model picker entry uses its mapped value when calling the provider API. Unknown keys are ignored. See https://code.claude.com/docs/en/model-config#override-model-ids-per-version","examples":[{"claude-opus-4-6":"arn:aws:bedrock:us-east-2:123456789012:application-inference-profile/opus-prod"}]},"effortLevel":{"type":"string","enum":["low","medium","high"],"description":"Control Opus 4.6 adaptive reasoning effort. Lower effort is faster and cheaper for straightforward tasks, higher effort provides deeper reasoning. Defaults vary by model and plan (Opus 4.6 defaults to medium for Max and Team subscribers). Use /effort auto to reset to model default. Also configurable via CLAUDE_CODE_EFFORT_LEVEL environment variable. See https://code.claude.com/docs/en/model-config#adjust-effort-level"},"fastMode":{"type":"boolean","description":"Enable fast mode for Opus 4.6 (research preview). Fast mode uses the same model with 2.5x faster output at higher per-token cost. Requires extra usage enabled. Alternatively, toggle with /fast command. See https://code.claude.com/docs/en/fast-mode","default":false},"fastModePerSessionOptIn":{"type":"boolean","description":"Require per-session opt-in for fast mode. When true, fast mode does not persist across sessions and users must enable it with /fast each session. Useful for controlling costs. See https://code.claude.com/docs/en/fast-mode","default":false},"feedbackSurveyRate":{"type":"number","minimum":0,"maximum":1,"description":"Probability (0–1) that the session quality survey appears when eligible. A value of 0.05 means 5% of eligible sessions. See https://code.claude.com/docs/en/settings","examples":[0.05]},"editorMode":{"type":"string","enum":["normal","vim"],"default":"normal","description":"Editor input mode for the Claude Code terminal prompt. 'vim' enables modal editing (Esc for normal mode, i for insert). See https://code.claude.com/docs/en/settings"},"skillOverrides":{"type":"object","additionalProperties":{"type":"string","enum":["on","name-only","user-invocable-only","off"]},"description":"Per-skill availability override map. Keys are skill names; values are one of 'on' (default), 'name-only' (skill name listed but not auto-loaded), 'user-invocable-only' (load only when user explicitly invokes), or 'off' (hidden). Requires Claude Code v2.1.129+. See https://code.claude.com/docs/en/settings","examples":[{"playwright-debug":"user-invocable-only","init":"off"}]},"disableAgentView":{"type":"boolean","default":false,"description":"Disable the Agent View feature (read-only inspection of sub-agent activity). Useful when administering managed deployments. Requires Claude Code v2.1.139+. See https://code.claude.com/docs/en/settings"},"disableRemoteControl":{"type":"boolean","default":false,"description":"Block the \`claude remote-control\` channel that allows external clients to drive this Claude Code instance. Recommended default for shared/CI environments. Requires Claude Code v2.1.128+. See https://code.claude.com/docs/en/settings"},"enableAllProjectMcpServers":{"type":"boolean","description":"Whether to automatically approve all MCP servers in the project. See https://code.claude.com/docs/en/mcp","examples":[true]},"enabledMcpjsonServers":{"type":"array","items":{"type":"string","minLength":1},"description":"List of approved MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp","examples":[["memory","github"]]},"disabledMcpjsonServers":{"type":"array","items":{"type":"string","minLength":1},"description":"List of rejected MCP servers from .mcp.json. See https://code.claude.com/docs/en/mcp","examples":[["filesystem"]]},"allowedMcpServers":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"serverName":{"type":"string","pattern":"^[a-zA-Z0-9_-]+$","description":"Name of the MCP server that users are allowed to configure"}},"required":["serverName"],"additionalProperties":false},{"type":"object","properties":{"serverCommand":{"type":"array","items":{"type":"string"},"description":"Exact command and arguments used to start stdio servers"}},"required":["serverCommand"],"additionalProperties":false},{"type":"object","properties":{"serverUrl":{"type":"string","description":"URL pattern for remote servers, supports wildcards (e.g., https://*.example.com/*)"}},"required":["serverUrl"],"additionalProperties":false}]},"description":"Enterprise allowlist of MCP servers that can be used. Applies to all scopes including enterprise servers from managed-mcp.json. If undefined, all servers are allowed. If empty array, no servers are allowed. Denylist takes precedence - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options"},"deniedMcpServers":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"serverName":{"type":"string","pattern":"^[a-zA-Z0-9_-]+$","description":"Name of the MCP server that is explicitly blocked"}},"required":["serverName"],"additionalProperties":false},{"type":"object","properties":{"serverCommand":{"type":"array","items":{"type":"string"},"description":"Exact command and arguments used to start stdio servers"}},"required":["serverCommand"],"additionalProperties":false},{"type":"object","properties":{"serverUrl":{"type":"string","description":"URL pattern for remote servers, supports wildcards (e.g., https://*.example.com/*)"}},"required":["serverUrl"],"additionalProperties":false}]},"description":"Enterprise denylist of MCP servers that are explicitly blocked. If a server is on the denylist, it will be blocked across all scopes including enterprise. Denylist takes precedence over allowlist - if a server is on both lists, it is denied. See https://code.claude.com/docs/en/mcp#restriction-options"},"httpHookAllowedEnvVars":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of environment variable names HTTP hooks may interpolate into headers. When set, each hook's effective allowedEnvVars is the intersection with this list. Undefined = no restriction. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration","examples":[["MY_TOKEN","HOOK_SECRET"]]},"hooks":{"type":"object","additionalProperties":false,"description":"Custom commands to run before/after tool executions. See https://code.claude.com/docs/en/hooks","examples":[{"PostToolUse":[{"matcher":"Edit|Write","hooks":[{"type":"command","command":"prettier --write","timeout":5}]}]}],"properties":{"PreToolUse":{"type":"array","description":"Hooks that run before tool calls","items":{"$ref":"#/$defs/hookMatcher"}},"PostToolUse":{"type":"array","description":"Hooks that run after tool completion","items":{"$ref":"#/$defs/hookMatcher"}},"PostToolUseFailure":{"type":"array","description":"Hooks that run after a tool fails","items":{"$ref":"#/$defs/hookMatcher"}},"PermissionRequest":{"type":"array","description":"Hooks that run when a permission dialog appears","items":{"$ref":"#/$defs/hookMatcher"}},"Notification":{"type":"array","description":"Hooks that trigger on notifications","items":{"$ref":"#/$defs/hookMatcher"}},"UserPromptSubmit":{"type":"array","description":"Hooks that run when a user submits a prompt","items":{"$ref":"#/$defs/hookMatcher"}},"Stop":{"type":"array","description":"Hooks that run when agents finish responding. Does not run on user interrupt","items":{"$ref":"#/$defs/hookMatcher"}},"SubagentStart":{"type":"array","description":"Hooks that run when a subagent is spawned","items":{"$ref":"#/$defs/hookMatcher"}},"SubagentStop":{"type":"array","description":"Hooks that run when subagents finish responding","items":{"$ref":"#/$defs/hookMatcher"}},"PreCompact":{"type":"array","description":"Hooks that run before the context is compacted","items":{"$ref":"#/$defs/hookMatcher"}},"PostCompact":{"type":"array","description":"Hooks that run after the context is compacted. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"Elicitation":{"type":"array","description":"Hooks that run when an MCP server requests user input during a tool call. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"ElicitationResult":{"type":"array","description":"Hooks that run after a user responds to an MCP elicitation, before the response is sent back to the server. See https://code.claude.com/docs/en/hooks","items":{"$ref":"#/$defs/hookMatcher"}},"TeammateIdle":{"type":"array","description":"Hooks that run when an agent team teammate is about to go idle. Exit code 2 sends feedback and keeps the teammate working. Does not support matchers. Agent teams are experimental. See https://code.claude.com/docs/en/hooks#teammateidle","items":{"$ref":"#/$defs/hookMatcher"}},"TaskCompleted":{"type":"array","description":"Hooks that run when a task is being marked as completed. Exit code 2 prevents completion and sends feedback. Does not support matchers. See https://code.claude.com/docs/en/hooks#taskcompleted","items":{"$ref":"#/$defs/hookMatcher"}},"Setup":{"type":"array","description":"UNDOCUMENTED. Hooks that run during repository initialization (--init, --init-only) or maintenance (--maintenance)","items":{"$ref":"#/$defs/hookMatcher"}},"InstructionsLoaded":{"type":"array","description":"Hooks that run when a CLAUDE.md or .claude/rules/*.md file is loaded into context. Fires at session start and when files are lazily loaded (e.g., nested traversal, path glob match). No decision control; used for audit logging and observability. Does not support matchers. See https://code.claude.com/docs/en/hooks#instructionsloaded","items":{"$ref":"#/$defs/hookMatcher"}},"ConfigChange":{"type":"array","description":"Hooks that run when settings, managed settings, or skill files change during a session. Supports matchers: user_settings, project_settings, local_settings, policy_settings, skills. Command handlers only. Exit code 2 blocks the change (except policy_settings which is audit-only). See https://code.claude.com/docs/en/hooks#configchange","items":{"$ref":"#/$defs/hookMatcher"}},"WorktreeCreate":{"type":"array","description":"Hooks that run when a worktree is created via --worktree or isolation: \\"worktree\\" in subagents. Command handlers only, no matchers. Hook must print absolute path to created worktree on stdout; non-zero exit fails creation. See https://code.claude.com/docs/en/hooks#worktreecreate","items":{"$ref":"#/$defs/hookMatcher"}},"WorktreeRemove":{"type":"array","description":"Hooks that run when a worktree is being removed at session exit or when a subagent finishes. Command handlers only, no matchers. Used for cleanup tasks; cannot block removal. See https://code.claude.com/docs/en/hooks#worktreeremove","items":{"$ref":"#/$defs/hookMatcher"}},"SessionStart":{"type":"array","description":"Hooks that run when a new session starts","items":{"$ref":"#/$defs/hookMatcher"}},"SessionEnd":{"type":"array","description":"Hooks that run when a session ends","items":{"$ref":"#/$defs/hookMatcher"}}}},"disableAllHooks":{"type":"boolean","description":"Disable all hooks and statusLine execution. When true in managed settings, user and project-level disableAllHooks cannot override it. See https://code.claude.com/docs/en/hooks#disable-or-remove-hooks"},"allowedHttpHookUrls":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of URL patterns that HTTP hooks may target. Supports * as a wildcard. When set, hooks with non-matching URLs are blocked. Undefined = no restriction, empty array = block all HTTP hooks. Arrays merge across settings sources. See https://code.claude.com/docs/en/settings#hook-configuration","examples":[["https://hooks.example.com/*","http://localhost:*"]]},"allowManagedHooksOnly":{"type":"boolean","description":"(Managed settings only) Prevent loading of user, project, and plugin hooks. Only allows managed hooks and SDK hooks. See https://code.claude.com/docs/en/settings#hook-configuration"},"allowManagedPermissionRulesOnly":{"type":"boolean","description":"(Managed settings only) Prevent user and project settings from defining allow, ask, or deny permission rules. Only rules in managed settings apply. See https://code.claude.com/docs/en/settings#permission-settings"},"statusLine":{"type":"object","properties":{"type":{"type":"string","description":"The type of status line handler; must be set to \\"command\\" to run a custom shell script that receives JSON session data via stdin.","const":"command"},"command":{"type":"string","description":"A shell command or path to a script that displays session information (context usage, costs, git status, etc.) by reading JSON data from stdin and writing output to stdout. See https://code.claude.com/docs/en/statusline"},"padding":{"type":"number","description":"Optional number of extra horizontal spacing characters added to the status line content; defaults to 0."}},"required":["type","command"],"additionalProperties":false,"description":"Custom status line display configuration. See https://code.claude.com/docs/en/statusline","examples":[{"type":"command","command":"~/.claude/statusline.sh"}]},"fileSuggestion":{"type":"object","properties":{"type":{"type":"string","description":"The type of file suggestion handler; must be set to \\"command\\" to execute a custom shell script that generates file suggestions for the @ file picker.","const":"command"},"command":{"type":"string","description":"Shell command to execute for file suggestions"}},"required":["type","command"],"additionalProperties":false,"description":"Configure a custom script for @ file autocomplete. See https://code.claude.com/docs/en/settings#file-suggestion-settings","examples":[{"type":"command","command":"~/.claude/file-suggestion.sh"}]},"enabledPlugins":{"type":"object","additionalProperties":{"anyOf":[{"type":"array","items":{"type":"string"}},{"type":"boolean"},{"not":{}}]},"description":"Enabled plugins using plugin-id@marketplace-id format. Example: { \\"formatter@anthropic-tools\\": true }. See https://code.claude.com/docs/en/plugins"},"extraKnownMarketplaces":{"type":"object","additionalProperties":{"type":"object","properties":{"source":{"anyOf":[{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"url"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json file"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"hostPattern"},"hostPattern":{"type":"string","description":"Git host pattern to trust for repositories in source specifications"}},"required":["source","hostPattern"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"github"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch or tag to use (e.g., \\"main\\", \\"v1.0.0\\"). Defaults to repository default branch."},"path":{"type":"string","description":"Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"}},"required":["source","repo"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"git"},"url":{"type":"string","pattern":"\\\\.git$","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch or tag to use (e.g., \\"main\\", \\"v1.0.0\\"). Defaults to repository default branch."},"path":{"type":"string","description":"Path to marketplace.json within repo (defaults to .claude-plugin/marketplace.json)"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"npm"},"package":{"type":"string","description":"NPM package containing marketplace.json"}},"required":["source","package"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"file"},"path":{"type":"string","description":"Local file path to marketplace.json"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"directory"},"path":{"type":"string","description":"Local directory containing .claude-plugin/marketplace.json"}},"required":["source","path"],"additionalProperties":false}],"description":"Where to fetch the marketplace from"},"installLocation":{"type":"string","description":"Local cache path where marketplace manifest is stored (auto-generated if not provided)"}},"required":["source"],"additionalProperties":false},"description":"Additional marketplaces to make available for this repository. Typically used in repository .claude/settings.json to ensure team members have required plugin sources. See https://code.claude.com/docs/en/plugin-marketplaces"},"strictKnownMarketplaces":{"type":"array","description":"(Managed settings only) Allowlist of plugin marketplaces users can add. Undefined = no restrictions, empty array = lockdown. Uses exact matching for source specifications. See https://code.claude.com/docs/en/settings#strictknownmarketplaces","items":{"anyOf":[{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"hostPattern"},"hostPattern":{"type":"string","description":"Git host pattern to trust for repositories in source specifications"}},"required":["source","hostPattern"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"github"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch, tag, or SHA"},"path":{"type":"string","description":"Subdirectory path"}},"required":["source","repo"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"git"},"url":{"type":"string","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch, tag, or SHA"},"path":{"type":"string","description":"Subdirectory path"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"url"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json"},"headers":{"type":"object","additionalProperties":{"type":"string"},"description":"HTTP headers for authenticated access"}},"required":["source","url"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"npm"},"package":{"type":"string","description":"NPM package name (supports scoped packages)"}},"required":["source","package"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"file"},"path":{"type":"string","description":"Absolute path to marketplace.json file"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"directory"},"path":{"type":"string","description":"Absolute path to directory containing .claude-plugin/marketplace.json"}},"required":["source","path"],"additionalProperties":false},{"type":"object","properties":{"source":{"type":"string","description":"Identifies the marketplace source type","const":"pathPattern"},"pathPattern":{"type":"string","description":"Regex pattern to match file or directory paths for marketplace sources"}},"required":["source","pathPattern"],"additionalProperties":false}]},"examples":[[{"source":"github","repo":"acme-corp/approved-plugins"},{"source":"npm","package":"@acme-corp/compliance-plugins"}]]},"skippedMarketplaces":{"type":"array","items":{"type":"string","minLength":1},"description":"List of marketplace names the user has chosen not to install when prompted"},"skippedPlugins":{"type":"array","items":{"type":"string","minLength":1},"description":"List of plugin IDs (plugin@marketplace format) the user has chosen not to install when prompted"},"forceLoginMethod":{"type":"string","enum":["claudeai","console"],"description":"Force a specific login method: \\"claudeai\\" for Claude Pro/Max, \\"console\\" for Console billing","examples":["claudeai"]},"forceLoginOrgUUID":{"type":"string","description":"Organization UUID to use for OAuth login","examples":["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"],"minLength":1},"otelHeadersHelper":{"type":"string","description":"Path to a script that outputs OpenTelemetry headers","minLength":1},"outputStyle":{"type":"string","description":"Controls the output style for assistant responses. Built-in styles: default, Explanatory, Learning. Custom styles can be added in ~/.claude/output-styles/ or .claude/output-styles/. See https://code.claude.com/docs/en/output-styles","examples":["default","Explanatory","Learning"],"minLength":1},"skipWebFetchPreflight":{"type":"boolean","description":"Skip the WebFetch blocklist check for enterprise environments with restrictive security policies"},"sandbox":{"type":"object","description":"Sandbox execution configuration. See https://code.claude.com/docs/en/sandboxing","properties":{"network":{"type":"object","description":"Configures network isolation settings for the sandboxed bash environment, including domain restrictions, Unix socket access, and custom proxy configuration.","properties":{"allowUnixSockets":{"type":"array","items":{"type":"string"},"description":"Allow Unix domain sockets for local IPC (SSH agent, Docker, etc.). Provide an array of specific paths. Defaults to blocking if not specified"},"allowLocalBinding":{"type":"boolean","description":"Allow binding to local network addresses (e.g., localhost ports). Defaults to false if not specified"},"httpProxyPort":{"type":"integer","minimum":1,"maximum":65535,"description":"HTTP proxy port to use for network filtering. If not specified, a proxy server will be started automatically"},"socksProxyPort":{"type":"integer","minimum":1,"maximum":65535,"description":"SOCKS proxy port to use for network filtering. If not specified, a proxy server will be started automatically"},"allowAllUnixSockets":{"type":"boolean","description":"Allow all Unix domain socket connections. If true, this overrides allowUnixSockets"},"allowedDomains":{"type":"array","items":{"type":"string","minLength":1},"description":"Allowlist of network domains for sandboxed commands. Supports wildcard patterns like *.example.com"},"allowManagedDomainsOnly":{"type":"boolean","description":"(Managed settings only) Only allowedDomains and WebFetch(domain:...) allow rules from managed settings are respected. User, project, local, and flag settings domains are ignored. Denied domains are still respected from all sources. Non-allowed domains are automatically blocked without user prompts."}},"additionalProperties":false},"ignoreViolations":{"type":"object","additionalProperties":{"type":"array","items":{"type":"string"},"description":"List of filesystem paths to ignore sandbox violations for when this command pattern matches"},"description":"Map of command patterns to filesystem paths to ignore violations for. Use \\"*\\" to match all commands"},"excludedCommands":{"type":"array","items":{"type":"string"},"description":"Commands that should never run in the sandbox (e.g., [\\"git\\", \\"docker\\"])"},"autoAllowBashIfSandboxed":{"type":"boolean","description":"Automatically allow bash commands without prompting when they run in the sandbox. Only applies to commands that will run sandboxed.","default":true},"enableWeakerNetworkIsolation":{"type":"boolean","description":"macOS only. Allow access to the system TLS trust service (com.apple.trustd.agent) in the sandbox. Required for Go-based tools like gh, gcloud, and terraform to verify TLS certificates when using httpProxyPort with a MITM proxy and custom CA. Reduces security by opening a potential data exfiltration path. Default: false. See https://code.claude.com/docs/en/settings#sandbox-settings","default":false},"enableWeakerNestedSandbox":{"type":"boolean","description":"Enable weaker sandbox mode for unprivileged docker environments where --proc mounting fails. This significantly reduces the strength of the sandbox and should only be used when this risk is acceptable.Default: false (secure)."},"allowUnsandboxedCommands":{"type":"boolean","description":"Allow commands to run outside the sandbox via the dangerouslyDisableSandbox parameter. When false, the dangerouslyDisableSandbox parameter is completely ignored and all commands must run sandboxed. Default: true."},"enabled":{"type":"boolean","description":"Enable sandboxed bash"},"filesystem":{"type":"object","description":"Filesystem access control for sandboxed commands. See https://code.claude.com/docs/en/sandboxing#filesystem-isolation","properties":{"allowWrite":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are allowed to write. Supports prefixes: // (absolute), ~/ (home directory), / (relative to settings file), ./ or no prefix (relative path)"},"denyWrite":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are explicitly denied write access. Takes precedence over allowWrite"},"denyRead":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths where subprocesses are explicitly denied read access"},"allowRead":{"type":"array","items":{"type":"string","minLength":1},"description":"Paths to re-allow reading within denyRead regions. Takes precedence over denyRead for matching paths"},"allowManagedReadPathsOnly":{"type":"boolean","description":"When true (managed settings only), only allowRead paths from managed settings are used"}},"additionalProperties":false}},"additionalProperties":false},"spinnerVerbs":{"type":"object","description":"Customize the verbs shown in spinner progress messages","properties":{"mode":{"type":"string","enum":["append","replace"],"description":"How to combine custom verbs with default spinner verbs: 'append' adds custom verbs to the default list, 'replace' uses only custom verbs"},"verbs":{"type":"array","items":{"type":"string","minLength":1},"minItems":1,"description":"Custom verbs used in spinner progress text"}},"required":["verbs"],"additionalProperties":false},"spinnerTipsEnabled":{"type":"boolean","description":"Show tips in the spinner while Claude is working. Set to false to disable tips (default: true)","default":true},"spinnerTipsOverride":{"type":"object","description":"Customize the tips displayed in the spinner while Claude is working. See https://code.claude.com/docs/en/settings#available-settings","properties":{"excludeDefault":{"type":"boolean","description":"If true, only show custom tips. If false or absent, custom tips merge with built-in tips","default":false},"tips":{"type":"array","items":{"type":"string","minLength":1},"description":"Custom tip strings to display in the spinner","minItems":1}},"required":["tips"],"additionalProperties":false},"terminalProgressBarEnabled":{"type":"boolean","description":"Enable the terminal progress bar that shows progress in supported terminals like Windows Terminal and iTerm2 (default: true)","default":true},"showTurnDuration":{"type":"boolean","description":"Show turn duration messages after responses (e.g., \\"Cooked for 1m 6s\\"). Set to false to hide these messages (default: true)","default":true},"prefersReducedMotion":{"type":"boolean","description":"Reduce or disable UI animations (spinners, shimmer, flash effects) for accessibility","default":false},"alwaysThinkingEnabled":{"type":"boolean","description":"Enable extended thinking by default for all sessions. Typically configured via the /config command rather than editing directly. See https://code.claude.com/docs/en/common-workflows#use-extended-thinking-thinking-mode"},"companyAnnouncements":{"type":"array","items":{"type":"string","minLength":1},"description":"Company announcements to display at startup (one will be randomly selected if multiple are provided)"},"teammateMode":{"type":"string","enum":["auto","in-process","tmux"],"description":"How agent team teammates display: \\"auto\\" picks split panes in tmux or iTerm2, in-process otherwise. Agent teams are experimental and disabled by default. Enable them by adding CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS to your settings.json or environment. See https://code.claude.com/docs/en/agent-teams","default":"auto"},"worktree":{"type":"object","additionalProperties":false,"description":"Configuration for --worktree sessions. See https://code.claude.com/docs/en/settings","properties":{"sparsePaths":{"type":"array","items":{"type":"string","minLength":1},"description":"Directories to check out in each worktree via git sparse-checkout (cone mode). Only the listed paths are written to disk, which is faster in large monorepos.","examples":[["packages/my-app","shared/utils"]]}}},"pluginTrustMessage":{"type":"string","description":"(Managed settings only) Custom message appended to the plugin trust warning shown before installation. Use to provide organization-specific context about approved plugins. See https://code.claude.com/docs/en/settings#plugin-settings","minLength":1},"pluginConfigs":{"type":"object","additionalProperties":{"type":"object","properties":{"mcpServers":{"type":"object","additionalProperties":{"type":"object","additionalProperties":{"anyOf":[{"type":"string"},{"type":"number"},{"type":"boolean"},{"type":"array","items":{"type":"string"}}]}},"description":"User configuration values for MCP servers keyed by server name"}},"additionalProperties":false},"description":"Per-plugin configuration including MCP server user configs, keyed by plugin ID (plugin@marketplace format). See https://code.claude.com/docs/en/plugins"},"allowManagedMcpServersOnly":{"type":"boolean","description":"(Managed settings only) Only allowedMcpServers from managed settings are respected. deniedMcpServers still merges from all sources. Users can still add their own MCP servers, but only the admin-defined allowlist applies."},"blockedMarketplaces":{"type":"array","description":"(Managed settings only) Blocklist of marketplace sources. These exact sources are blocked from being added as marketplaces. The check happens before downloading, so blocked sources never touch the filesystem.","items":{"anyOf":[{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"url","description":"Block marketplace fetched from direct URL"},"url":{"type":"string","format":"uri","description":"Direct URL to marketplace.json file"},"headers":{"type":"object","additionalProperties":{"type":"string"},"description":"Custom HTTP headers (e.g., for authentication)"}},"required":["source","url"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"github","description":"Block marketplace from GitHub repository"},"repo":{"type":"string","description":"GitHub repository in owner/repo format"},"ref":{"type":"string","description":"Git branch or tag to use"},"path":{"type":"string","description":"Path to marketplace.json within repo"}},"required":["source","repo"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"git","description":"Block marketplace from git repository URL"},"url":{"type":"string","pattern":".*\\\\.git$","description":"Full git repository URL"},"ref":{"type":"string","description":"Git branch or tag to use"},"path":{"type":"string","description":"Path to marketplace.json within repo"}},"required":["source","url"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"npm","description":"Block marketplace from NPM package"},"package":{"type":"string","description":"NPM package containing marketplace.json"}},"required":["source","package"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"file","description":"Block marketplace from local file"},"path":{"type":"string","description":"Local file path to marketplace.json"}},"required":["source","path"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"directory","description":"Block marketplace from local directory"},"path":{"type":"string","description":"Local directory containing .claude-plugin/marketplace.json"}},"required":["source","path"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"hostPattern","description":"Block marketplace by host pattern matching"},"hostPattern":{"type":"string","description":"Regex pattern to match the host/domain extracted from any marketplace source type"}},"required":["source","hostPattern"]},{"type":"object","additionalProperties":false,"properties":{"source":{"type":"string","const":"pathPattern","description":"Block marketplace by file/directory path pattern matching"},"pathPattern":{"type":"string","description":"Regex pattern to match file or directory paths for marketplace sources"}},"required":["source","pathPattern"]}]}}}`),Z5="Claude Code Settings",eL={$schema:q5,$id:V5,$defs:G5,description:K5,allowTrailingCommas:X5,additionalProperties:Y5,type:J5,properties:Q5,title:Z5};function tL(e){const n=e??{},r={...n.$defs??{},...n.definitions??{}},i=S=>{if(!S)return{};if(!S.$ref)return d(S);const E=/^#\/(\$defs|definitions)\/(.+)$/.exec(S.$ref);if(!E)return d(S);const j=r[E[2]];return j?i({...j,...u(S)}):d(S)},o=new Set(["__proto__","constructor","prototype"]),l=S=>{if(!S)return{};const E={};for(const[j,y]of Object.entries(S))o.has(j)||(E[j]=y);return E},d=S=>{if(!S.allOf||S.allOf.length===0)return S;const E={...S};delete E.allOf;for(const j of S.allOf){const y=i(j);Object.assign(E,{properties:{...l(E.properties),...l(y.properties)},required:nL([...E.required??[],...y.required??[]])}),!E.description&&y.description&&(E.description=y.description),E.default===void 0&&y.default!==void 0&&(E.default=y.default),!E.type&&y.type&&(E.type=y.type)}return E},u=S=>{const{$ref:E,...j}=S;return j},h=(S,E)=>{let j=i(S);for(const y of E){if(!j)return null;if(/^\d+$/.test(y)){const C=Array.isArray(j.items)?j.items[Number(y)]:j.items;j=C?i(C):null;continue}const b=j.properties;if(b&&!o.has(y)&&y in b){j=i(b[y]);continue}const _=j.additionalProperties;if(_&&typeof _=="object"){j=i(_);continue}return null}return j},m=(S,E,j)=>{if(!S)return null;const y={};if(S.description&&(y.description=S.description),S.type&&(y.type=S.type),S.default!==void 0&&(y.default=S.default),S.enum&&(y.enum=S.enum),S.const!==void 0&&(y.const=S.const),S.deprecated&&(y.deprecated=!0),S.examples&&(y.examples=S.examples),S.properties&&(y.knownChildren=Object.keys(S.properties)),j&&(E!=null&&E.includes(j))&&(y.required=!0),S.items&&!Array.isArray(S.items)){const b=i(S.items),_=m(b,void 0,null);_&&(y.itemsInfo=_)}return(S.additionalProperties===!0||typeof S.additionalProperties=="object")&&(y.open=!0),y},x=S=>E=>{if(E.length===0)return m(i(S),void 0,null);const j=h(S,E.slice(0,-1));if(!j)return null;const y=E[E.length-1],b=h(j,[y]);return m(b,j.required,y)},g=S=>{const E=i(S);return Object.keys(E.properties??{})},v=S=>({at:x(S),rootKeys:()=>g(S),rootedAt:E=>{const j=h(S,E);return v(j??{})}});return v(n)}function nL(e){return Array.from(new Set(e))}let db=null;function Ay(){return db||(db=tL(eL)),db}function rL(){const[e,n]=L.useState(null),[r,i]=L.useState(null),[o,l]=L.useState(null),[d,u]=L.useState(null),[h,m]=L.useState(!1),[x,g]=L.useState(null),[v,S]=L.useState(null);if(L.useEffect(()=>{let _=!1;return Promise.all([window.api.otel.getConfig(),window.api.otel.status(),window.api.otel.configPath()]).then(([C,N,$])=>{_||(n(C),l(C),i(N),u($))}).catch(C=>{console.warn("[telemetry] load failed:",C==null?void 0:C.message)}),()=>{_=!0}},[]),!o||!e)return s.jsx(Vt,{title:"loading…"});const E=JSON.stringify(o)!==JSON.stringify(e),j=(_,C)=>{g(null),l({...o,[_]:C})},y=async()=>{m(!0),g(null);try{const _=await window.api.otel.setConfig(o);!_.ok&&_.error&&g(_.error),n(_.config),l(_.config),i(_.status),S(Date.now())}catch(_){g(_ instanceof Error?_.message:String(_))}finally{m(!1)}},b=()=>{g(null),l(e)};return s.jsxs("div",{className:"p-4 max-w-3xl space-y-5 text-sm",children:[s.jsxs("header",{className:"space-y-1",children:[s.jsx("h2",{className:"text-fg text-base font-medium",children:"Telemetry — OpenTelemetry export"}),s.jsx("p",{className:"text-fg-dim text-xs leading-relaxed",children:"When enabled, every classified transcript event (tool_use, todo_write, plan, usage, agent_spawn) is mirrored as a 0-duration OTLP/HTTP span. Point this at a local collector (Jaeger, Grafana Tempo, SigNoz, Honeycomb) for cross-session analysis."}),d&&s.jsxs("p",{className:"text-fg-faint text-[11px]",children:["stored at ",s.jsx("span",{className:"font-mono",children:d})]})]}),s.jsxs("section",{className:"border border-line rounded p-3 space-y-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-fg",children:"Export transcripts to OTEL"}),s.jsx("div",{className:"text-fg-faint text-xs",children:"Toggle off to disable all span emission immediately."})]}),s.jsx(Cy,{checked:o.enabled,onChange:_=>j("enabled",_),label:o.enabled?"on":"off"})]}),s.jsxs("label",{className:"block space-y-1",children:[s.jsx("span",{className:"text-fg-dim text-xs",children:"OTLP/HTTP traces endpoint"}),s.jsx("input",{type:"text",value:o.endpoint,onChange:_=>j("endpoint",_.target.value),placeholder:"http://localhost:4318/v1/traces",className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),s.jsxs("label",{className:"block space-y-1",children:[s.jsxs("span",{className:"text-fg-dim text-xs",children:["Headers (newline-separated ",s.jsx("span",{className:"font-mono",children:"Key: Value"}),")"]}),s.jsx("textarea",{value:o.headers,onChange:_=>j("headers",_.target.value),placeholder:"x-honeycomb-team: YOUR_API_KEY",rows:3,className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),s.jsxs("label",{className:"block space-y-1",children:[s.jsx("span",{className:"text-fg-dim text-xs",children:"Service name"}),s.jsx("input",{type:"text",value:o.serviceName,onChange:_=>j("serviceName",_.target.value),placeholder:"session-manager",className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs"})]}),s.jsxs("div",{className:"flex items-start justify-between gap-3 pt-1",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-fg",children:"Include content (PII)"}),s.jsxs("div",{className:"text-fg-faint text-xs leading-relaxed",children:["Adds tool inputs, plan text, and agent prompts to span attributes. Off by default — matches upstream Claude Code's ",s.jsx("span",{className:"font-mono",children:"OTEL_LOG_USER_PROMPTS"})," opt-in."]})]}),s.jsx(Cy,{checked:o.includeContent,onChange:_=>j("includeContent",_),label:o.includeContent?"on":"off"})]})]}),r&&s.jsxs("section",{className:"border border-line rounded p-3 text-xs space-y-1",children:[s.jsx("div",{className:"text-fg-dim",children:"Runtime status"}),s.jsxs("div",{children:[s.jsx("span",{className:"text-fg-faint",children:"enabled:"})," ",s.jsx("span",{className:r.enabled?"text-accent":"text-fg-dim",children:String(r.enabled)})]}),r.error&&s.jsxs("div",{className:"text-red-400 break-words",children:[s.jsx("span",{className:"text-fg-faint",children:"error:"})," ",r.error]}),!r.error&&r.enabled&&s.jsx("div",{className:"text-fg-faint",children:"spans batched and exported in the background. Verify by enabling and pointing at a local Jaeger."})]}),s.jsxs("footer",{className:"flex items-center gap-3 pt-2 border-t border-line",children:[s.jsx("button",{onClick:y,disabled:!E||h,className:"px-3 py-1 text-xs rounded bg-accent text-bg disabled:opacity-50 disabled:cursor-not-allowed",children:h?"saving…":"Save"}),s.jsx("button",{onClick:b,disabled:!E||h,className:"px-3 py-1 text-xs rounded border border-line text-fg-dim hover:text-fg disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert"}),x&&s.jsx("span",{className:"text-red-400 text-xs",children:x}),!x&&v&&!E&&s.jsx("span",{className:"text-fg-faint text-xs",children:"saved"})]})]})}function sL(){const{model:e,setModel:n}=zN();return s.jsxs("div",{className:"p-4 max-w-3xl space-y-5 text-sm",children:[s.jsxs("header",{className:"space-y-1",children:[s.jsx("h2",{className:"text-fg text-base font-medium",children:"Session Manager preferences"}),s.jsx("p",{className:"text-fg-dim text-xs leading-relaxed",children:"Native app preferences, stored locally — not part of Claude Code's own settings."})]}),s.jsx("section",{className:"border border-line rounded p-3 space-y-3",children:s.jsxs("label",{className:"block space-y-1",children:[s.jsx("span",{className:"text-fg-dim text-xs",children:"Default model for raw sessions"}),s.jsx("select",{value:e,onChange:r=>n(r.target.value),className:"w-full bg-bg border border-line rounded px-2 py-1 text-fg font-mono text-xs",children:Yw.map(r=>s.jsx("option",{value:r,children:r.charAt(0).toUpperCase()+r.slice(1)},r))}),s.jsx("span",{className:"text-fg-faint text-[11px]",children:"Used when opening a raw interactive session without an explicit per-launch override."})]})})]})}function iL(){const e=rr(),n=bt($=>$.tabs),r=bt($=>$.activeTabId),i=n.find($=>$.id===r)??null,o=(i==null?void 0:i.cwd)??null,[l,d]=L.useState("user"),[u,h]=L.useState("effective"),m=w0(Sy,e,o),x=m[l]??null,g=tn($=>$.files),v=tn($=>$.setDraft),S=tn($=>$.saveJson),E=tn($=>$.revert),[j,y]=L.useState(null),b=L.useMemo(()=>_0(S0(g,m)),[g,m]),_=($,R,O)=>{var V;const z=m[O??l];if(!z)return;y(null);const U=((V=g[z])==null?void 0:V.draftRaw)??"";let W={};if(U.trim())try{W=JSON.parse(U)}catch{W={}}const Y=iv(W,$,R);v(z,JSON.stringify(Y,null,2)+`
|
|
@@ -3426,7 +3426,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
3426
3426
|
background: rgba(0,0,0,0.6);
|
|
3427
3427
|
pointer-events: none;
|
|
3428
3428
|
}
|
|
3429
|
-
`;I8(P8);var D8=I0({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},init:function(n,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=i.style,l=o===void 0?{}:o,d=!!n&&qy(n)==="object"&&!!n.node&&typeof n.node=="function",u=ao(d?n.node():n);u.style("position")==="static"&&u.style("position","relative"),r.tooltipEl=u.append("div").attr("class","float-tooltip-kap"),Object.entries(l).forEach(function(m){var x=N8(m,2),g=x[0],v=x[1];return r.tooltipEl.style(g,v)}),r.tooltipEl.style("left","-10000px").style("display","none");var h="tooltip-".concat(Math.round(Math.random()*1e12));r.mouseInside=!1,u.on("mousemove.".concat(h),function(m){r.mouseInside=!0;var x=ga(m),g=u.node(),v=g.offsetWidth,S=g.offsetHeight,E=[r.offsetX===null||r.offsetX===void 0?"-".concat(x[0]/v*100,"%"):typeof r.offsetX=="number"?"calc(-50% + ".concat(r.offsetX,"px)"):r.offsetX,r.offsetY===null||r.offsetY===void 0?S>130&&S-x[1]<100?"calc(-100% - 6px)":"21px":typeof r.offsetY=="number"?r.offsetY<0?"calc(-100% - ".concat(Math.abs(r.offsetY),"px)"):"".concat(r.offsetY,"px"):r.offsetY];r.tooltipEl.style("left",x[0]+"px").style("top",x[1]+"px").style("transform","translate(".concat(E.join(","),")")),r.content&&r.tooltipEl.style("display","inline")}),u.on("mouseover.".concat(h),function(){r.mouseInside=!0,r.content&&r.tooltipEl.style("display","inline")}),u.on("mouseout.".concat(h),function(){r.mouseInside=!1,r.tooltipEl.style("display","none")})},update:function(n){n.tooltipEl.style("display",n.content&&n.mouseInside?"inline":"none"),n.content?n.content instanceof HTMLElement?(n.tooltipEl.text(""),n.tooltipEl.append(function(){return n.content})):typeof n.content=="string"?n.tooltipEl.html(n.content):R8(n.content)?(n.tooltipEl.text(""),M8(n.content,n.tooltipEl.node())):(n.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",n.content,n.content.toString())):n.tooltipEl.text("")}});function O8(e,n,r){var i,o=1;e==null&&(e=0),n==null&&(n=0),r==null&&(r=0);function l(){var d,u=i.length,h,m=0,x=0,g=0;for(d=0;d<u;++d)h=i[d],m+=h.x||0,x+=h.y||0,g+=h.z||0;for(m=(m/u-e)*o,x=(x/u-n)*o,g=(g/u-r)*o,d=0;d<u;++d)h=i[d],m&&(h.x-=m),x&&(h.y-=x),g&&(h.z-=g)}return l.initialize=function(d){i=d},l.x=function(d){return arguments.length?(e=+d,l):e},l.y=function(d){return arguments.length?(n=+d,l):n},l.z=function(d){return arguments.length?(r=+d,l):r},l.strength=function(d){return arguments.length?(o=+d,l):o},l}function L8(e){const n=+this._x.call(null,e);return AE(this.cover(n),n,e)}function AE(e,n,r){if(isNaN(n))return e;var i,o=e._root,l={data:r},d=e._x0,u=e._x1,h,m,x,g,v;if(!o)return e._root=l,e;for(;o.length;)if((x=n>=(h=(d+u)/2))?d=h:u=h,i=o,!(o=o[g=+x]))return i[g]=l,e;if(m=+e._x.call(null,o.data),n===m)return l.next=o,i?i[g]=l:e._root=l,e;do i=i?i[g]=new Array(2):e._root=new Array(2),(x=n>=(h=(d+u)/2))?d=h:u=h;while((g=+x)==(v=+(m>=h)));return i[v]=o,i[g]=l,e}function z8(e){Array.isArray(e)||(e=Array.from(e));const n=e.length,r=new Float64Array(n);let i=1/0,o=-1/0;for(let l=0,d;l<n;++l)isNaN(d=+this._x.call(null,e[l]))||(r[l]=d,d<i&&(i=d),d>o&&(o=d));if(i>o)return this;this.cover(i).cover(o);for(let l=0;l<n;++l)AE(this,r[l],e[l]);return this}function B8(e){if(isNaN(e=+e))return this;var n=this._x0,r=this._x1;if(isNaN(n))r=(n=Math.floor(e))+1;else{for(var i=r-n||1,o=this._root,l,d;n>e||e>=r;)switch(d=+(e<n),l=new Array(2),l[d]=o,o=l,i*=2,d){case 0:r=n+i;break;case 1:n=r-i;break}this._root&&this._root.length&&(this._root=o)}return this._x0=n,this._x1=r,this}function F8(){var e=[];return this.visit(function(n){if(!n.length)do e.push(n.data);while(n=n.next)}),e}function U8(e){return arguments.length?this.cover(+e[0][0]).cover(+e[1][0]):isNaN(this._x0)?void 0:[[this._x0],[this._x1]]}function xl(e,n,r){this.node=e,this.x0=n,this.x1=r}function H8(e,n){var r,i=this._x0,o,l,d=this._x1,u=[],h=this._root,m,x;for(h&&u.push(new xl(h,i,d)),n==null?n=1/0:(i=e-n,d=e+n);m=u.pop();)if(!(!(h=m.node)||(o=m.x0)>d||(l=m.x1)<i))if(h.length){var g=(o+l)/2;u.push(new xl(h[1],g,l),new xl(h[0],o,g)),(x=+(e>=g))&&(m=u[u.length-1],u[u.length-1]=u[u.length-1-x],u[u.length-1-x]=m)}else{var v=Math.abs(e-+this._x.call(null,h.data));v<n&&(n=v,i=e-v,d=e+v,r=h.data)}return r}function W8(e){if(isNaN(h=+this._x.call(null,e)))return this;var n,r=this._root,i,o,l,d=this._x0,u=this._x1,h,m,x,g,v;if(!r)return this;if(r.length)for(;;){if((x=h>=(m=(d+u)/2))?d=m:u=m,n=r,!(r=r[g=+x]))return this;if(!r.length)break;n[g+1&1]&&(i=n,v=g)}for(;r.data!==e;)if(o=r,!(r=r.next))return this;return(l=r.next)&&delete r.next,o?(l?o.next=l:delete o.next,this):n?(l?n[g]=l:delete n[g],(r=n[0]||n[1])&&r===(n[1]||n[0])&&!r.length&&(i?i[v]=r:this._root=r),this):(this._root=l,this)}function q8(e){for(var n=0,r=e.length;n<r;++n)this.remove(e[n]);return this}function V8(){return this._root}function G8(){var e=0;return this.visit(function(n){if(!n.length)do++e;while(n=n.next)}),e}function K8(e){var n=[],r,i=this._root,o,l,d;for(i&&n.push(new xl(i,this._x0,this._x1));r=n.pop();)if(!e(i=r.node,l=r.x0,d=r.x1)&&i.length){var u=(l+d)/2;(o=i[1])&&n.push(new xl(o,u,d)),(o=i[0])&&n.push(new xl(o,l,u))}return this}function X8(e){var n=[],r=[],i;for(this._root&&n.push(new xl(this._root,this._x0,this._x1));i=n.pop();){var o=i.node;if(o.length){var l,d=i.x0,u=i.x1,h=(d+u)/2;(l=o[0])&&n.push(new xl(l,d,h)),(l=o[1])&&n.push(new xl(l,h,u))}r.push(i)}for(;i=r.pop();)e(i.node,i.x0,i.x1);return this}function Y8(e){return e[0]}function J8(e){return arguments.length?(this._x=e,this):this._x}function RE(e,n){var r=new z0(n??Y8,NaN,NaN);return e==null?r:r.addAll(e)}function z0(e,n,r){this._x=e,this._x0=n,this._x1=r,this._root=void 0}function LS(e){for(var n={data:e.data},r=n;e=e.next;)r=r.next={data:e.data};return n}var yi=RE.prototype=z0.prototype;yi.copy=function(){var e=new z0(this._x,this._x0,this._x1),n=this._root,r,i;if(!n)return e;if(!n.length)return e._root=LS(n),e;for(r=[{source:n,target:e._root=new Array(2)}];n=r.pop();)for(var o=0;o<2;++o)(i=n.source[o])&&(i.length?r.push({source:i,target:n.target[o]=new Array(2)}):n.target[o]=LS(i));return e};yi.add=L8;yi.addAll=z8;yi.cover=B8;yi.data=F8;yi.extent=U8;yi.find=H8;yi.remove=W8;yi.removeAll=q8;yi.root=V8;yi.size=G8;yi.visit=K8;yi.visitAfter=X8;yi.x=J8;function Q8(e){const n=+this._x.call(null,e),r=+this._y.call(null,e);return ME(this.cover(n,r),n,r,e)}function ME(e,n,r,i){if(isNaN(n)||isNaN(r))return e;var o,l=e._root,d={data:i},u=e._x0,h=e._y0,m=e._x1,x=e._y1,g,v,S,E,j,y,b,_;if(!l)return e._root=d,e;for(;l.length;)if((j=n>=(g=(u+m)/2))?u=g:m=g,(y=r>=(v=(h+x)/2))?h=v:x=v,o=l,!(l=l[b=y<<1|j]))return o[b]=d,e;if(S=+e._x.call(null,l.data),E=+e._y.call(null,l.data),n===S&&r===E)return d.next=l,o?o[b]=d:e._root=d,e;do o=o?o[b]=new Array(4):e._root=new Array(4),(j=n>=(g=(u+m)/2))?u=g:m=g,(y=r>=(v=(h+x)/2))?h=v:x=v;while((b=y<<1|j)===(_=(E>=v)<<1|S>=g));return o[_]=l,o[b]=d,e}function Z8(e){var n,r,i=e.length,o,l,d=new Array(i),u=new Array(i),h=1/0,m=1/0,x=-1/0,g=-1/0;for(r=0;r<i;++r)isNaN(o=+this._x.call(null,n=e[r]))||isNaN(l=+this._y.call(null,n))||(d[r]=o,u[r]=l,o<h&&(h=o),o>x&&(x=o),l<m&&(m=l),l>g&&(g=l));if(h>x||m>g)return this;for(this.cover(h,m).cover(x,g),r=0;r<i;++r)ME(this,d[r],u[r],e[r]);return this}function eU(e,n){if(isNaN(e=+e)||isNaN(n=+n))return this;var r=this._x0,i=this._y0,o=this._x1,l=this._y1;if(isNaN(r))o=(r=Math.floor(e))+1,l=(i=Math.floor(n))+1;else{for(var d=o-r||1,u=this._root,h,m;r>e||e>=o||i>n||n>=l;)switch(m=(n<i)<<1|e<r,h=new Array(4),h[m]=u,u=h,d*=2,m){case 0:o=r+d,l=i+d;break;case 1:r=o-d,l=i+d;break;case 2:o=r+d,i=l-d;break;case 3:r=o-d,i=l-d;break}this._root&&this._root.length&&(this._root=u)}return this._x0=r,this._y0=i,this._x1=o,this._y1=l,this}function tU(){var e=[];return this.visit(function(n){if(!n.length)do e.push(n.data);while(n=n.next)}),e}function nU(e){return arguments.length?this.cover(+e[0][0],+e[0][1]).cover(+e[1][0],+e[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]}function Gs(e,n,r,i,o){this.node=e,this.x0=n,this.y0=r,this.x1=i,this.y1=o}function rU(e,n,r){var i,o=this._x0,l=this._y0,d,u,h,m,x=this._x1,g=this._y1,v=[],S=this._root,E,j;for(S&&v.push(new Gs(S,o,l,x,g)),r==null?r=1/0:(o=e-r,l=n-r,x=e+r,g=n+r,r*=r);E=v.pop();)if(!(!(S=E.node)||(d=E.x0)>x||(u=E.y0)>g||(h=E.x1)<o||(m=E.y1)<l))if(S.length){var y=(d+h)/2,b=(u+m)/2;v.push(new Gs(S[3],y,b,h,m),new Gs(S[2],d,b,y,m),new Gs(S[1],y,u,h,b),new Gs(S[0],d,u,y,b)),(j=(n>=b)<<1|e>=y)&&(E=v[v.length-1],v[v.length-1]=v[v.length-1-j],v[v.length-1-j]=E)}else{var _=e-+this._x.call(null,S.data),C=n-+this._y.call(null,S.data),N=_*_+C*C;if(N<r){var $=Math.sqrt(r=N);o=e-$,l=n-$,x=e+$,g=n+$,i=S.data}}return i}function sU(e){if(isNaN(x=+this._x.call(null,e))||isNaN(g=+this._y.call(null,e)))return this;var n,r=this._root,i,o,l,d=this._x0,u=this._y0,h=this._x1,m=this._y1,x,g,v,S,E,j,y,b;if(!r)return this;if(r.length)for(;;){if((E=x>=(v=(d+h)/2))?d=v:h=v,(j=g>=(S=(u+m)/2))?u=S:m=S,n=r,!(r=r[y=j<<1|E]))return this;if(!r.length)break;(n[y+1&3]||n[y+2&3]||n[y+3&3])&&(i=n,b=y)}for(;r.data!==e;)if(o=r,!(r=r.next))return this;return(l=r.next)&&delete r.next,o?(l?o.next=l:delete o.next,this):n?(l?n[y]=l:delete n[y],(r=n[0]||n[1]||n[2]||n[3])&&r===(n[3]||n[2]||n[1]||n[0])&&!r.length&&(i?i[b]=r:this._root=r),this):(this._root=l,this)}function iU(e){for(var n=0,r=e.length;n<r;++n)this.remove(e[n]);return this}function oU(){return this._root}function aU(){var e=0;return this.visit(function(n){if(!n.length)do++e;while(n=n.next)}),e}function lU(e){var n=[],r,i=this._root,o,l,d,u,h;for(i&&n.push(new Gs(i,this._x0,this._y0,this._x1,this._y1));r=n.pop();)if(!e(i=r.node,l=r.x0,d=r.y0,u=r.x1,h=r.y1)&&i.length){var m=(l+u)/2,x=(d+h)/2;(o=i[3])&&n.push(new Gs(o,m,x,u,h)),(o=i[2])&&n.push(new Gs(o,l,x,m,h)),(o=i[1])&&n.push(new Gs(o,m,d,u,x)),(o=i[0])&&n.push(new Gs(o,l,d,m,x))}return this}function cU(e){var n=[],r=[],i;for(this._root&&n.push(new Gs(this._root,this._x0,this._y0,this._x1,this._y1));i=n.pop();){var o=i.node;if(o.length){var l,d=i.x0,u=i.y0,h=i.x1,m=i.y1,x=(d+h)/2,g=(u+m)/2;(l=o[0])&&n.push(new Gs(l,d,u,x,g)),(l=o[1])&&n.push(new Gs(l,x,u,h,g)),(l=o[2])&&n.push(new Gs(l,d,g,x,m)),(l=o[3])&&n.push(new Gs(l,x,g,h,m))}r.push(i)}for(;i=r.pop();)e(i.node,i.x0,i.y0,i.x1,i.y1);return this}function uU(e){return e[0]}function dU(e){return arguments.length?(this._x=e,this):this._x}function hU(e){return e[1]}function fU(e){return arguments.length?(this._y=e,this):this._y}function IE(e,n,r){var i=new B0(n??uU,r??hU,NaN,NaN,NaN,NaN);return e==null?i:i.addAll(e)}function B0(e,n,r,i,o,l){this._x=e,this._y=n,this._x0=r,this._y0=i,this._x1=o,this._y1=l,this._root=void 0}function zS(e){for(var n={data:e.data},r=n;e=e.next;)r=r.next={data:e.data};return n}var Ys=IE.prototype=B0.prototype;Ys.copy=function(){var e=new B0(this._x,this._y,this._x0,this._y0,this._x1,this._y1),n=this._root,r,i;if(!n)return e;if(!n.length)return e._root=zS(n),e;for(r=[{source:n,target:e._root=new Array(4)}];n=r.pop();)for(var o=0;o<4;++o)(i=n.source[o])&&(i.length?r.push({source:i,target:n.target[o]=new Array(4)}):n.target[o]=zS(i));return e};Ys.add=Q8;Ys.addAll=Z8;Ys.cover=eU;Ys.data=tU;Ys.extent=nU;Ys.find=rU;Ys.remove=sU;Ys.removeAll=iU;Ys.root=oU;Ys.size=aU;Ys.visit=lU;Ys.visitAfter=cU;Ys.x=dU;Ys.y=fU;function pU(e){const n=+this._x.call(null,e),r=+this._y.call(null,e),i=+this._z.call(null,e);return PE(this.cover(n,r,i),n,r,i,e)}function PE(e,n,r,i,o){if(isNaN(n)||isNaN(r)||isNaN(i))return e;var l,d=e._root,u={data:o},h=e._x0,m=e._y0,x=e._z0,g=e._x1,v=e._y1,S=e._z1,E,j,y,b,_,C,N,$,R,O,I;if(!d)return e._root=u,e;for(;d.length;)if((N=n>=(E=(h+g)/2))?h=E:g=E,($=r>=(j=(m+v)/2))?m=j:v=j,(R=i>=(y=(x+S)/2))?x=y:S=y,l=d,!(d=d[O=R<<2|$<<1|N]))return l[O]=u,e;if(b=+e._x.call(null,d.data),_=+e._y.call(null,d.data),C=+e._z.call(null,d.data),n===b&&r===_&&i===C)return u.next=d,l?l[O]=u:e._root=u,e;do l=l?l[O]=new Array(8):e._root=new Array(8),(N=n>=(E=(h+g)/2))?h=E:g=E,($=r>=(j=(m+v)/2))?m=j:v=j,(R=i>=(y=(x+S)/2))?x=y:S=y;while((O=R<<2|$<<1|N)===(I=(C>=y)<<2|(_>=j)<<1|b>=E));return l[I]=d,l[O]=u,e}function mU(e){Array.isArray(e)||(e=Array.from(e));const n=e.length,r=new Float64Array(n),i=new Float64Array(n),o=new Float64Array(n);let l=1/0,d=1/0,u=1/0,h=-1/0,m=-1/0,x=-1/0;for(let g=0,v,S,E,j;g<n;++g)isNaN(S=+this._x.call(null,v=e[g]))||isNaN(E=+this._y.call(null,v))||isNaN(j=+this._z.call(null,v))||(r[g]=S,i[g]=E,o[g]=j,S<l&&(l=S),S>h&&(h=S),E<d&&(d=E),E>m&&(m=E),j<u&&(u=j),j>x&&(x=j));if(l>h||d>m||u>x)return this;this.cover(l,d,u).cover(h,m,x);for(let g=0;g<n;++g)PE(this,r[g],i[g],o[g],e[g]);return this}function gU(e,n,r){if(isNaN(e=+e)||isNaN(n=+n)||isNaN(r=+r))return this;var i=this._x0,o=this._y0,l=this._z0,d=this._x1,u=this._y1,h=this._z1;if(isNaN(i))d=(i=Math.floor(e))+1,u=(o=Math.floor(n))+1,h=(l=Math.floor(r))+1;else{for(var m=d-i||1,x=this._root,g,v;i>e||e>=d||o>n||n>=u||l>r||r>=h;)switch(v=(r<l)<<2|(n<o)<<1|e<i,g=new Array(8),g[v]=x,x=g,m*=2,v){case 0:d=i+m,u=o+m,h=l+m;break;case 1:i=d-m,u=o+m,h=l+m;break;case 2:d=i+m,o=u-m,h=l+m;break;case 3:i=d-m,o=u-m,h=l+m;break;case 4:d=i+m,u=o+m,l=h-m;break;case 5:i=d-m,u=o+m,l=h-m;break;case 6:d=i+m,o=u-m,l=h-m;break;case 7:i=d-m,o=u-m,l=h-m;break}this._root&&this._root.length&&(this._root=x)}return this._x0=i,this._y0=o,this._z0=l,this._x1=d,this._y1=u,this._z1=h,this}function xU(){var e=[];return this.visit(function(n){if(!n.length)do e.push(n.data);while(n=n.next)}),e}function yU(e){return arguments.length?this.cover(+e[0][0],+e[0][1],+e[0][2]).cover(+e[1][0],+e[1][1],+e[1][2]):isNaN(this._x0)?void 0:[[this._x0,this._y0,this._z0],[this._x1,this._y1,this._z1]]}function qn(e,n,r,i,o,l,d){this.node=e,this.x0=n,this.y0=r,this.z0=i,this.x1=o,this.y1=l,this.z1=d}function vU(e,n,r,i){var o,l=this._x0,d=this._y0,u=this._z0,h,m,x,g,v,S,E=this._x1,j=this._y1,y=this._z1,b=[],_=this._root,C,N;for(_&&b.push(new qn(_,l,d,u,E,j,y)),i==null?i=1/0:(l=e-i,d=n-i,u=r-i,E=e+i,j=n+i,y=r+i,i*=i);C=b.pop();)if(!(!(_=C.node)||(h=C.x0)>E||(m=C.y0)>j||(x=C.z0)>y||(g=C.x1)<l||(v=C.y1)<d||(S=C.z1)<u))if(_.length){var $=(h+g)/2,R=(m+v)/2,O=(x+S)/2;b.push(new qn(_[7],$,R,O,g,v,S),new qn(_[6],h,R,O,$,v,S),new qn(_[5],$,m,O,g,R,S),new qn(_[4],h,m,O,$,R,S),new qn(_[3],$,R,x,g,v,O),new qn(_[2],h,R,x,$,v,O),new qn(_[1],$,m,x,g,R,O),new qn(_[0],h,m,x,$,R,O)),(N=(r>=O)<<2|(n>=R)<<1|e>=$)&&(C=b[b.length-1],b[b.length-1]=b[b.length-1-N],b[b.length-1-N]=C)}else{var I=e-+this._x.call(null,_.data),z=n-+this._y.call(null,_.data),U=r-+this._z.call(null,_.data),W=I*I+z*z+U*U;if(W<i){var Y=Math.sqrt(i=W);l=e-Y,d=n-Y,u=r-Y,E=e+Y,j=n+Y,y=r+Y,o=_.data}}return o}const bU=(e,n,r,i,o,l)=>Math.sqrt((e-i)**2+(n-o)**2+(r-l)**2);function wU(e,n,r,i){const o=[],l=e-i,d=n-i,u=r-i,h=e+i,m=n+i,x=r+i;return this.visit((g,v,S,E,j,y,b)=>{if(!g.length)do{const _=g.data;bU(e,n,r,this._x(_),this._y(_),this._z(_))<=i&&o.push(_)}while(g=g.next);return v>h||S>m||E>x||j<l||y<d||b<u}),o}function _U(e){if(isNaN(v=+this._x.call(null,e))||isNaN(S=+this._y.call(null,e))||isNaN(E=+this._z.call(null,e)))return this;var n,r=this._root,i,o,l,d=this._x0,u=this._y0,h=this._z0,m=this._x1,x=this._y1,g=this._z1,v,S,E,j,y,b,_,C,N,$,R;if(!r)return this;if(r.length)for(;;){if((_=v>=(j=(d+m)/2))?d=j:m=j,(C=S>=(y=(u+x)/2))?u=y:x=y,(N=E>=(b=(h+g)/2))?h=b:g=b,n=r,!(r=r[$=N<<2|C<<1|_]))return this;if(!r.length)break;(n[$+1&7]||n[$+2&7]||n[$+3&7]||n[$+4&7]||n[$+5&7]||n[$+6&7]||n[$+7&7])&&(i=n,R=$)}for(;r.data!==e;)if(o=r,!(r=r.next))return this;return(l=r.next)&&delete r.next,o?(l?o.next=l:delete o.next,this):n?(l?n[$]=l:delete n[$],(r=n[0]||n[1]||n[2]||n[3]||n[4]||n[5]||n[6]||n[7])&&r===(n[7]||n[6]||n[5]||n[4]||n[3]||n[2]||n[1]||n[0])&&!r.length&&(i?i[R]=r:this._root=r),this):(this._root=l,this)}function kU(e){for(var n=0,r=e.length;n<r;++n)this.remove(e[n]);return this}function SU(){return this._root}function CU(){var e=0;return this.visit(function(n){if(!n.length)do++e;while(n=n.next)}),e}function jU(e){var n=[],r,i=this._root,o,l,d,u,h,m,x;for(i&&n.push(new qn(i,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));r=n.pop();)if(!e(i=r.node,l=r.x0,d=r.y0,u=r.z0,h=r.x1,m=r.y1,x=r.z1)&&i.length){var g=(l+h)/2,v=(d+m)/2,S=(u+x)/2;(o=i[7])&&n.push(new qn(o,g,v,S,h,m,x)),(o=i[6])&&n.push(new qn(o,l,v,S,g,m,x)),(o=i[5])&&n.push(new qn(o,g,d,S,h,v,x)),(o=i[4])&&n.push(new qn(o,l,d,S,g,v,x)),(o=i[3])&&n.push(new qn(o,g,v,u,h,m,S)),(o=i[2])&&n.push(new qn(o,l,v,u,g,m,S)),(o=i[1])&&n.push(new qn(o,g,d,u,h,v,S)),(o=i[0])&&n.push(new qn(o,l,d,u,g,v,S))}return this}function EU(e){var n=[],r=[],i;for(this._root&&n.push(new qn(this._root,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));i=n.pop();){var o=i.node;if(o.length){var l,d=i.x0,u=i.y0,h=i.z0,m=i.x1,x=i.y1,g=i.z1,v=(d+m)/2,S=(u+x)/2,E=(h+g)/2;(l=o[0])&&n.push(new qn(l,d,u,h,v,S,E)),(l=o[1])&&n.push(new qn(l,v,u,h,m,S,E)),(l=o[2])&&n.push(new qn(l,d,S,h,v,x,E)),(l=o[3])&&n.push(new qn(l,v,S,h,m,x,E)),(l=o[4])&&n.push(new qn(l,d,u,E,v,S,g)),(l=o[5])&&n.push(new qn(l,v,u,E,m,S,g)),(l=o[6])&&n.push(new qn(l,d,S,E,v,x,g)),(l=o[7])&&n.push(new qn(l,v,S,E,m,x,g))}r.push(i)}for(;i=r.pop();)e(i.node,i.x0,i.y0,i.z0,i.x1,i.y1,i.z1);return this}function NU(e){return e[0]}function TU(e){return arguments.length?(this._x=e,this):this._x}function $U(e){return e[1]}function AU(e){return arguments.length?(this._y=e,this):this._y}function RU(e){return e[2]}function MU(e){return arguments.length?(this._z=e,this):this._z}function DE(e,n,r,i){var o=new F0(n??NU,r??$U,i??RU,NaN,NaN,NaN,NaN,NaN,NaN);return e==null?o:o.addAll(e)}function F0(e,n,r,i,o,l,d,u,h){this._x=e,this._y=n,this._z=r,this._x0=i,this._y0=o,this._z0=l,this._x1=d,this._y1=u,this._z1=h,this._root=void 0}function BS(e){for(var n={data:e.data},r=n;e=e.next;)r=r.next={data:e.data};return n}var Cs=DE.prototype=F0.prototype;Cs.copy=function(){var e=new F0(this._x,this._y,this._z,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1),n=this._root,r,i;if(!n)return e;if(!n.length)return e._root=BS(n),e;for(r=[{source:n,target:e._root=new Array(8)}];n=r.pop();)for(var o=0;o<8;++o)(i=n.source[o])&&(i.length?r.push({source:i,target:n.target[o]=new Array(8)}):n.target[o]=BS(i));return e};Cs.add=pU;Cs.addAll=mU;Cs.cover=gU;Cs.data=xU;Cs.extent=yU;Cs.find=vU;Cs.findAllWithinRadius=wU;Cs.remove=_U;Cs.removeAll=kU;Cs.root=SU;Cs.size=CU;Cs.visit=jU;Cs.visitAfter=EU;Cs.x=TU;Cs.y=AU;Cs.z=MU;function ml(e){return function(){return e}}function dl(e){return(e()-.5)*1e-6}function IU(e){return e.index}function FS(e,n){var r=e.get(n);if(!r)throw new Error("node not found: "+n);return r}function PU(e){var n=IU,r=v,i,o=ml(30),l,d,u,h,m,x,g=1;e==null&&(e=[]);function v(b){return 1/Math.min(h[b.source.index],h[b.target.index])}function S(b){for(var _=0,C=e.length;_<g;++_)for(var N=0,$,R,O,I=0,z=0,U=0,W,Y;N<C;++N)$=e[N],R=$.source,O=$.target,I=O.x+O.vx-R.x-R.vx||dl(x),u>1&&(z=O.y+O.vy-R.y-R.vy||dl(x)),u>2&&(U=O.z+O.vz-R.z-R.vz||dl(x)),W=Math.sqrt(I*I+z*z+U*U),W=(W-l[N])/W*b*i[N],I*=W,z*=W,U*=W,O.vx-=I*(Y=m[N]),u>1&&(O.vy-=z*Y),u>2&&(O.vz-=U*Y),R.vx+=I*(Y=1-Y),u>1&&(R.vy+=z*Y),u>2&&(R.vz+=U*Y)}function E(){if(d){var b,_=d.length,C=e.length,N=new Map(d.map((R,O)=>[n(R,O,d),R])),$;for(b=0,h=new Array(_);b<C;++b)$=e[b],$.index=b,typeof $.source!="object"&&($.source=FS(N,$.source)),typeof $.target!="object"&&($.target=FS(N,$.target)),h[$.source.index]=(h[$.source.index]||0)+1,h[$.target.index]=(h[$.target.index]||0)+1;for(b=0,m=new Array(C);b<C;++b)$=e[b],m[b]=h[$.source.index]/(h[$.source.index]+h[$.target.index]);i=new Array(C),j(),l=new Array(C),y()}}function j(){if(d)for(var b=0,_=e.length;b<_;++b)i[b]=+r(e[b],b,e)}function y(){if(d)for(var b=0,_=e.length;b<_;++b)l[b]=+o(e[b],b,e)}return S.initialize=function(b,..._){d=b,x=_.find(C=>typeof C=="function")||Math.random,u=_.find(C=>[1,2,3].includes(C))||2,E()},S.links=function(b){return arguments.length?(e=b,E(),S):e},S.id=function(b){return arguments.length?(n=b,S):n},S.iterations=function(b){return arguments.length?(g=+b,S):g},S.strength=function(b){return arguments.length?(r=typeof b=="function"?b:ml(+b),j(),S):r},S.distance=function(b){return arguments.length?(o=typeof b=="function"?b:ml(+b),y(),S):o},S}const DU=1664525,OU=1013904223,US=4294967296;function LU(){let e=1;return()=>(e=(DU*e+OU)%US)/US}var HS=3;function vb(e){return e.x}function WS(e){return e.y}function zU(e){return e.z}var BU=10,FU=Math.PI*(3-Math.sqrt(5)),UU=Math.PI*20/(9+Math.sqrt(221));function HU(e,n){n=n||2;var r=Math.min(HS,Math.max(1,Math.round(n))),i,o=1,l=.001,d=1-Math.pow(l,1/300),u=0,h=.6,m=new Map,x=$0(S),g=ig("tick","end"),v=LU();e==null&&(e=[]);function S(){E(),g.call("tick",i),o<l&&(x.stop(),g.call("end",i))}function E(b){var _,C=e.length,N;b===void 0&&(b=1);for(var $=0;$<b;++$)for(o+=(u-o)*d,m.forEach(function(R){R(o)}),_=0;_<C;++_)N=e[_],N.fx==null?N.x+=N.vx*=h:(N.x=N.fx,N.vx=0),r>1&&(N.fy==null?N.y+=N.vy*=h:(N.y=N.fy,N.vy=0)),r>2&&(N.fz==null?N.z+=N.vz*=h:(N.z=N.fz,N.vz=0));return i}function j(){for(var b=0,_=e.length,C;b<_;++b){if(C=e[b],C.index=b,C.fx!=null&&(C.x=C.fx),C.fy!=null&&(C.y=C.fy),C.fz!=null&&(C.z=C.fz),isNaN(C.x)||r>1&&isNaN(C.y)||r>2&&isNaN(C.z)){var N=BU*(r>2?Math.cbrt(.5+b):r>1?Math.sqrt(.5+b):b),$=b*FU,R=b*UU;r===1?C.x=N:r===2?(C.x=N*Math.cos($),C.y=N*Math.sin($)):(C.x=N*Math.sin($)*Math.cos(R),C.y=N*Math.cos($),C.z=N*Math.sin($)*Math.sin(R))}(isNaN(C.vx)||r>1&&isNaN(C.vy)||r>2&&isNaN(C.vz))&&(C.vx=0,r>1&&(C.vy=0),r>2&&(C.vz=0))}}function y(b){return b.initialize&&b.initialize(e,v,r),b}return j(),i={tick:E,restart:function(){return x.restart(S),i},stop:function(){return x.stop(),i},numDimensions:function(b){return arguments.length?(r=Math.min(HS,Math.max(1,Math.round(b))),m.forEach(y),i):r},nodes:function(b){return arguments.length?(e=b,j(),m.forEach(y),i):e},alpha:function(b){return arguments.length?(o=+b,i):o},alphaMin:function(b){return arguments.length?(l=+b,i):l},alphaDecay:function(b){return arguments.length?(d=+b,i):+d},alphaTarget:function(b){return arguments.length?(u=+b,i):u},velocityDecay:function(b){return arguments.length?(h=1-b,i):1-h},randomSource:function(b){return arguments.length?(v=b,m.forEach(y),i):v},force:function(b,_){return arguments.length>1?(_==null?m.delete(b):m.set(b,y(_)),i):m.get(b)},find:function(){var b=Array.prototype.slice.call(arguments),_=b.shift()||0,C=(r>1?b.shift():null)||0,N=(r>2?b.shift():null)||0,$=b.shift()||1/0,R=0,O=e.length,I,z,U,W,Y,V;for($*=$,R=0;R<O;++R)Y=e[R],I=_-Y.x,z=C-(Y.y||0),U=N-(Y.z||0),W=I*I+z*z+U*U,W<$&&(V=Y,$=W);return V},on:function(b,_){return arguments.length>1?(g.on(b,_),i):g.on(b)}}}function WU(){var e,n,r,i,o,l=ml(-30),d,u=1,h=1/0,m=.81;function x(E){var j,y=e.length,b=(n===1?RE(e,vb):n===2?IE(e,vb,WS):n===3?DE(e,vb,WS,zU):null).visitAfter(v);for(o=E,j=0;j<y;++j)r=e[j],b.visit(S)}function g(){if(e){var E,j=e.length,y;for(d=new Array(j),E=0;E<j;++E)y=e[E],d[y.index]=+l(y,E,e)}}function v(E){var j=0,y,b,_=0,C,N,$,R,O=E.length;if(O){for(C=N=$=R=0;R<O;++R)(y=E[R])&&(b=Math.abs(y.value))&&(j+=y.value,_+=b,C+=b*(y.x||0),N+=b*(y.y||0),$+=b*(y.z||0));j*=Math.sqrt(4/O),E.x=C/_,n>1&&(E.y=N/_),n>2&&(E.z=$/_)}else{y=E,y.x=y.data.x,n>1&&(y.y=y.data.y),n>2&&(y.z=y.data.z);do j+=d[y.data.index];while(y=y.next)}E.value=j}function S(E,j,y,b,_){if(!E.value)return!0;var C=[y,b,_][n-1],N=E.x-r.x,$=n>1?E.y-r.y:0,R=n>2?E.z-r.z:0,O=C-j,I=N*N+$*$+R*R;if(O*O/m<I)return I<h&&(N===0&&(N=dl(i),I+=N*N),n>1&&$===0&&($=dl(i),I+=$*$),n>2&&R===0&&(R=dl(i),I+=R*R),I<u&&(I=Math.sqrt(u*I)),r.vx+=N*E.value*o/I,n>1&&(r.vy+=$*E.value*o/I),n>2&&(r.vz+=R*E.value*o/I)),!0;if(E.length||I>=h)return;(E.data!==r||E.next)&&(N===0&&(N=dl(i),I+=N*N),n>1&&$===0&&($=dl(i),I+=$*$),n>2&&R===0&&(R=dl(i),I+=R*R),I<u&&(I=Math.sqrt(u*I)));do E.data!==r&&(O=d[E.data.index]*o/I,r.vx+=N*O,n>1&&(r.vy+=$*O),n>2&&(r.vz+=R*O));while(E=E.next)}return x.initialize=function(E,...j){e=E,i=j.find(y=>typeof y=="function")||Math.random,n=j.find(y=>[1,2,3].includes(y))||2,g()},x.strength=function(E){return arguments.length?(l=typeof E=="function"?E:ml(+E),g(),x):l},x.distanceMin=function(E){return arguments.length?(u=E*E,x):Math.sqrt(u)},x.distanceMax=function(E){return arguments.length?(h=E*E,x):Math.sqrt(h)},x.theta=function(E){return arguments.length?(m=E*E,x):Math.sqrt(m)},x}function qU(e,n,r,i){var o,l,d=ml(.1),u,h;typeof e!="function"&&(e=ml(+e)),n==null&&(n=0),r==null&&(r=0),i==null&&(i=0);function m(g){for(var v=0,S=o.length;v<S;++v){var E=o[v],j=E.x-n||1e-6,y=(E.y||0)-r||1e-6,b=(E.z||0)-i||1e-6,_=Math.sqrt(j*j+y*y+b*b),C=(h[v]-_)*u[v]*g/_;E.vx+=j*C,l>1&&(E.vy+=y*C),l>2&&(E.vz+=b*C)}}function x(){if(o){var g,v=o.length;for(u=new Array(v),h=new Array(v),g=0;g<v;++g)h[g]=+e(o[g],g,o),u[g]=isNaN(h[g])?0:+d(o[g],g,o)}}return m.initialize=function(g,...v){o=g,l=v.find(S=>[1,2,3].includes(S))||2,x()},m.strength=function(g){return arguments.length?(d=typeof g=="function"?g:ml(+g),x(),m):d},m.radius=function(g){return arguments.length?(e=typeof g=="function"?g:ml(+g),x(),m):e},m.x=function(g){return arguments.length?(n=+g,m):n},m.y=function(g){return arguments.length?(r=+g,m):r},m.z=function(g){return arguments.length?(i=+g,m):i},m}const{abs:um,cos:ll,sin:$h,acos:VU,atan2:dm,sqrt:tc,pow:so}=Math;function hm(e){return e<0?-so(-e,1/3):so(e,1/3)}const OE=Math.PI,Bx=2*OE,nc=OE/2,GU=1e-6,bb=Number.MAX_SAFE_INTEGER||9007199254740991,wb=Number.MIN_SAFE_INTEGER||-9007199254740991,KU={x:0,y:0,z:0},mt={Tvalues:[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213],Cvalues:[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872],arcfn:function(e,n){const r=n(e);let i=r.x*r.x+r.y*r.y;return typeof r.z<"u"&&(i+=r.z*r.z),tc(i)},compute:function(e,n,r){if(e===0)return n[0].t=0,n[0];const i=n.length-1;if(e===1)return n[i].t=1,n[i];const o=1-e;let l=n;if(i===0)return n[0].t=e,n[0];if(i===1){const u={x:o*l[0].x+e*l[1].x,y:o*l[0].y+e*l[1].y,t:e};return r&&(u.z=o*l[0].z+e*l[1].z),u}if(i<4){let u=o*o,h=e*e,m,x,g,v=0;i===2?(l=[l[0],l[1],l[2],KU],m=u,x=o*e*2,g=h):i===3&&(m=u*o,x=u*e*3,g=o*h*3,v=e*h);const S={x:m*l[0].x+x*l[1].x+g*l[2].x+v*l[3].x,y:m*l[0].y+x*l[1].y+g*l[2].y+v*l[3].y,t:e};return r&&(S.z=m*l[0].z+x*l[1].z+g*l[2].z+v*l[3].z),S}const d=JSON.parse(JSON.stringify(n));for(;d.length>1;){for(let u=0;u<d.length-1;u++)d[u]={x:d[u].x+(d[u+1].x-d[u].x)*e,y:d[u].y+(d[u+1].y-d[u].y)*e},typeof d[u].z<"u"&&(d[u].z=d[u].z+(d[u+1].z-d[u].z)*e);d.splice(d.length-1,1)}return d[0].t=e,d[0]},computeWithRatios:function(e,n,r,i){const o=1-e,l=r,d=n;let u=l[0],h=l[1],m=l[2],x=l[3],g;if(u*=o,h*=e,d.length===2)return g=u+h,{x:(u*d[0].x+h*d[1].x)/g,y:(u*d[0].y+h*d[1].y)/g,z:i?(u*d[0].z+h*d[1].z)/g:!1,t:e};if(u*=o,h*=2*o,m*=e*e,d.length===3)return g=u+h+m,{x:(u*d[0].x+h*d[1].x+m*d[2].x)/g,y:(u*d[0].y+h*d[1].y+m*d[2].y)/g,z:i?(u*d[0].z+h*d[1].z+m*d[2].z)/g:!1,t:e};if(u*=o,h*=1.5*o,m*=3*o,x*=e*e*e,d.length===4)return g=u+h+m+x,{x:(u*d[0].x+h*d[1].x+m*d[2].x+x*d[3].x)/g,y:(u*d[0].y+h*d[1].y+m*d[2].y+x*d[3].y)/g,z:i?(u*d[0].z+h*d[1].z+m*d[2].z+x*d[3].z)/g:!1,t:e}},derive:function(e,n){const r=[];for(let i=e,o=i.length,l=o-1;o>1;o--,l--){const d=[];for(let u=0,h;u<l;u++)h={x:l*(i[u+1].x-i[u].x),y:l*(i[u+1].y-i[u].y)},n&&(h.z=l*(i[u+1].z-i[u].z)),d.push(h);r.push(d),i=d}return r},between:function(e,n,r){return n<=e&&e<=r||mt.approximately(e,n)||mt.approximately(e,r)},approximately:function(e,n,r){return um(e-n)<=(r||GU)},length:function(e){const r=mt.Tvalues.length;let i=0;for(let o=0,l;o<r;o++)l=.5*mt.Tvalues[o]+.5,i+=mt.Cvalues[o]*mt.arcfn(l,e);return .5*i},map:function(e,n,r,i,o){const l=r-n,d=o-i,u=e-n,h=u/l;return i+d*h},lerp:function(e,n,r){const i={x:n.x+e*(r.x-n.x),y:n.y+e*(r.y-n.y)};return n.z!==void 0&&r.z!==void 0&&(i.z=n.z+e*(r.z-n.z)),i},pointToString:function(e){let n=e.x+"/"+e.y;return typeof e.z<"u"&&(n+="/"+e.z),n},pointsToString:function(e){return"["+e.map(mt.pointToString).join(", ")+"]"},copy:function(e){return JSON.parse(JSON.stringify(e))},angle:function(e,n,r){const i=n.x-e.x,o=n.y-e.y,l=r.x-e.x,d=r.y-e.y,u=i*d-o*l,h=i*l+o*d;return dm(u,h)},round:function(e,n){const r=""+e,i=r.indexOf(".");return parseFloat(r.substring(0,i+1+n))},dist:function(e,n){const r=e.x-n.x,i=e.y-n.y;return tc(r*r+i*i)},closest:function(e,n){let r=so(2,63),i,o;return e.forEach(function(l,d){o=mt.dist(n,l),o<r&&(r=o,i=d)}),{mdist:r,mpos:i}},abcratio:function(e,n){if(n!==2&&n!==3)return!1;if(typeof e>"u")e=.5;else if(e===0||e===1)return e;const r=so(e,n)+so(1-e,n),i=r-1;return um(i/r)},projectionratio:function(e,n){if(n!==2&&n!==3)return!1;if(typeof e>"u")e=.5;else if(e===0||e===1)return e;const r=so(1-e,n),i=so(e,n)+r;return r/i},lli8:function(e,n,r,i,o,l,d,u){const h=(e*i-n*r)*(o-d)-(e-r)*(o*u-l*d),m=(e*i-n*r)*(l-u)-(n-i)*(o*u-l*d),x=(e-r)*(l-u)-(n-i)*(o-d);return x==0?!1:{x:h/x,y:m/x}},lli4:function(e,n,r,i){const o=e.x,l=e.y,d=n.x,u=n.y,h=r.x,m=r.y,x=i.x,g=i.y;return mt.lli8(o,l,d,u,h,m,x,g)},lli:function(e,n){return mt.lli4(e,e.c,n,n.c)},makeline:function(e,n){return new Qn(e.x,e.y,(e.x+n.x)/2,(e.y+n.y)/2,n.x,n.y)},findbbox:function(e){let n=bb,r=bb,i=wb,o=wb;return e.forEach(function(l){const d=l.bbox();n>d.x.min&&(n=d.x.min),r>d.y.min&&(r=d.y.min),i<d.x.max&&(i=d.x.max),o<d.y.max&&(o=d.y.max)}),{x:{min:n,mid:(n+i)/2,max:i,size:i-n},y:{min:r,mid:(r+o)/2,max:o,size:o-r}}},shapeintersections:function(e,n,r,i,o){if(!mt.bboxoverlap(n,i))return[];const l=[],d=[e.startcap,e.forward,e.back,e.endcap],u=[r.startcap,r.forward,r.back,r.endcap];return d.forEach(function(h){h.virtual||u.forEach(function(m){if(m.virtual)return;const x=h.intersects(m,o);x.length>0&&(x.c1=h,x.c2=m,x.s1=e,x.s2=r,l.push(x))})}),l},makeshape:function(e,n,r){const i=n.points.length,o=e.points.length,l=mt.makeline(n.points[i-1],e.points[0]),d=mt.makeline(e.points[o-1],n.points[0]),u={startcap:l,forward:e,back:n,endcap:d,bbox:mt.findbbox([l,e,n,d])};return u.intersections=function(h){return mt.shapeintersections(u,u.bbox,h,h.bbox,r)},u},getminmax:function(e,n,r){if(!r)return{min:0,max:0};let i=bb,o=wb,l,d;r.indexOf(0)===-1&&(r=[0].concat(r)),r.indexOf(1)===-1&&r.push(1);for(let u=0,h=r.length;u<h;u++)l=r[u],d=e.get(l),d[n]<i&&(i=d[n]),d[n]>o&&(o=d[n]);return{min:i,mid:(i+o)/2,max:o,size:o-i}},align:function(e,n){const r=n.p1.x,i=n.p1.y,o=-dm(n.p2.y-i,n.p2.x-r),l=function(d){return{x:(d.x-r)*ll(o)-(d.y-i)*$h(o),y:(d.x-r)*$h(o)+(d.y-i)*ll(o)}};return e.map(l)},roots:function(e,n){n=n||{p1:{x:0,y:0},p2:{x:1,y:0}};const r=e.length-1,i=mt.align(e,n),o=function(O){return 0<=O&&O<=1};if(r===2){const O=i[0].y,I=i[1].y,z=i[2].y,U=O-2*I+z;if(U!==0){const W=-tc(I*I-O*z),Y=-O+I,V=-(W+Y)/U,H=-(-W+Y)/U;return[V,H].filter(o)}else if(I!==z&&U===0)return[(2*I-z)/(2*I-2*z)].filter(o);return[]}const l=i[0].y,d=i[1].y,u=i[2].y,h=i[3].y;let m=-l+3*d-3*u+h,x=3*l-6*d+3*u,g=-3*l+3*d,v=l;if(mt.approximately(m,0)){if(mt.approximately(x,0))return mt.approximately(g,0)?[]:[-v/g].filter(o);const O=tc(g*g-4*x*v),I=2*x;return[(O-g)/I,(-g-O)/I].filter(o)}x/=m,g/=m,v/=m;const S=(3*g-x*x)/3,E=S/3,j=(2*x*x*x-9*x*g+27*v)/27,y=j/2,b=y*y+E*E*E;let _,C,N,$,R;if(b<0){const O=-S/3,I=O*O*O,z=tc(I),U=-j/(2*z),W=U<-1?-1:U>1?1:U,Y=VU(W),V=hm(z),H=2*V;return N=H*ll(Y/3)-x/3,$=H*ll((Y+Bx)/3)-x/3,R=H*ll((Y+2*Bx)/3)-x/3,[N,$,R].filter(o)}else{if(b===0)return _=y<0?hm(-y):-hm(y),N=2*_-x/3,$=-_-x/3,[N,$].filter(o);{const O=tc(b);return _=hm(-y+O),C=hm(y+O),[_-C-x/3].filter(o)}}},droots:function(e){if(e.length===3){const n=e[0],r=e[1],i=e[2],o=n-2*r+i;if(o!==0){const l=-tc(r*r-n*i),d=-n+r,u=-(l+d)/o,h=-(-l+d)/o;return[u,h]}else if(r!==i&&o===0)return[(2*r-i)/(2*(r-i))];return[]}if(e.length===2){const n=e[0],r=e[1];return n!==r?[n/(n-r)]:[]}return[]},curvature:function(e,n,r,i,o){let l,d,u,h,m=0,x=0;const g=mt.compute(e,n),v=mt.compute(e,r),S=g.x*g.x+g.y*g.y;if(i?(l=tc(so(g.y*v.z-v.y*g.z,2)+so(g.z*v.x-v.z*g.x,2)+so(g.x*v.y-v.x*g.y,2)),d=so(S+g.z*g.z,3/2)):(l=g.x*v.y-g.y*v.x,d=so(S,3/2)),l===0||d===0)return{k:0,r:0};if(m=l/d,x=d/l,!o){const E=mt.curvature(e-.001,n,r,i,!0).k,j=mt.curvature(e+.001,n,r,i,!0).k;h=(j-m+(m-E))/2,u=(um(j-m)+um(m-E))/2}return{k:m,r:x,dk:h,adk:u}},inflections:function(e){if(e.length<4)return[];const n=mt.align(e,{p1:e[0],p2:e.slice(-1)[0]}),r=n[2].x*n[1].y,i=n[3].x*n[1].y,o=n[1].x*n[2].y,l=n[3].x*n[2].y,d=18*(-3*r+2*i+3*o-l),u=18*(3*r-i-3*o),h=18*(o-r);if(mt.approximately(d,0)){if(!mt.approximately(u,0)){let v=-h/u;if(0<=v&&v<=1)return[v]}return[]}const m=2*d;if(mt.approximately(m,0))return[];const x=u*u-4*d*h;if(x<0)return[];const g=Math.sqrt(x);return[(g-u)/m,-(u+g)/m].filter(function(v){return 0<=v&&v<=1})},bboxoverlap:function(e,n){const r=["x","y"],i=r.length;for(let o=0,l,d,u,h;o<i;o++)if(l=r[o],d=e[l].mid,u=n[l].mid,h=(e[l].size+n[l].size)/2,um(d-u)>=h)return!1;return!0},expandbox:function(e,n){n.x.min<e.x.min&&(e.x.min=n.x.min),n.y.min<e.y.min&&(e.y.min=n.y.min),n.z&&n.z.min<e.z.min&&(e.z.min=n.z.min),n.x.max>e.x.max&&(e.x.max=n.x.max),n.y.max>e.y.max&&(e.y.max=n.y.max),n.z&&n.z.max>e.z.max&&(e.z.max=n.z.max),e.x.mid=(e.x.min+e.x.max)/2,e.y.mid=(e.y.min+e.y.max)/2,e.z&&(e.z.mid=(e.z.min+e.z.max)/2),e.x.size=e.x.max-e.x.min,e.y.size=e.y.max-e.y.min,e.z&&(e.z.size=e.z.max-e.z.min)},pairiteration:function(e,n,r){const i=e.bbox(),o=n.bbox(),l=1e5,d=r||.5;if(i.x.size+i.y.size<d&&o.x.size+o.y.size<d)return[(l*(e._t1+e._t2)/2|0)/l+"/"+(l*(n._t1+n._t2)/2|0)/l];let u=e.split(.5),h=n.split(.5),m=[{left:u.left,right:h.left},{left:u.left,right:h.right},{left:u.right,right:h.right},{left:u.right,right:h.left}];m=m.filter(function(g){return mt.bboxoverlap(g.left.bbox(),g.right.bbox())});let x=[];return m.length===0||(m.forEach(function(g){x=x.concat(mt.pairiteration(g.left,g.right,d))}),x=x.filter(function(g,v){return x.indexOf(g)===v})),x},getccenter:function(e,n,r){const i=n.x-e.x,o=n.y-e.y,l=r.x-n.x,d=r.y-n.y,u=i*ll(nc)-o*$h(nc),h=i*$h(nc)+o*ll(nc),m=l*ll(nc)-d*$h(nc),x=l*$h(nc)+d*ll(nc),g=(e.x+n.x)/2,v=(e.y+n.y)/2,S=(n.x+r.x)/2,E=(n.y+r.y)/2,j=g+u,y=v+h,b=S+m,_=E+x,C=mt.lli8(g,v,j,y,S,E,b,_),N=mt.dist(C,e);let $=dm(e.y-C.y,e.x-C.x),R=dm(n.y-C.y,n.x-C.x),O=dm(r.y-C.y,r.x-C.x),I;return $<O?(($>R||R>O)&&($+=Bx),$>O&&(I=O,O=$,$=I)):O<R&&R<$?(I=O,O=$,$=I):O+=Bx,C.s=$,C.e=O,C.r=N,C},numberSort:function(e,n){return e-n}};class Lm{constructor(n){this.curves=[],this._3d=!1,n&&(this.curves=n,this._3d=this.curves[0]._3d)}valueOf(){return this.toString()}toString(){return"["+this.curves.map(function(n){return mt.pointsToString(n.points)}).join(", ")+"]"}addCurve(n){this.curves.push(n),this._3d=this._3d||n._3d}length(){return this.curves.map(function(n){return n.length()}).reduce(function(n,r){return n+r})}curve(n){return this.curves[n]}bbox(){const n=this.curves;for(var r=n[0].bbox(),i=1;i<n.length;i++)mt.expandbox(r,n[i].bbox());return r}offset(n){const r=[];return this.curves.forEach(function(i){r.push(...i.offset(n))}),new Lm(r)}}const{abs:fm,min:qS,max:VS,cos:XU,sin:YU,acos:JU,sqrt:pm}=Math,QU=Math.PI;class Qn{constructor(n){let r=n&&n.forEach?n:Array.from(arguments).slice(),i=!1;if(typeof r[0]=="object"){i=r.length;const S=[];r.forEach(function(E){["x","y","z"].forEach(function(j){typeof E[j]<"u"&&S.push(E[j])})}),r=S}let o=!1;const l=r.length;if(i){if(i>4){if(arguments.length!==1)throw new Error("Only new Bezier(point[]) is accepted for 4th and higher order curves");o=!0}}else if(l!==6&&l!==8&&l!==9&&l!==12&&arguments.length!==1)throw new Error("Only new Bezier(point[]) is accepted for 4th and higher order curves");const d=this._3d=!o&&(l===9||l===12)||n&&n[0]&&typeof n[0].z<"u",u=this.points=[];for(let S=0,E=d?3:2;S<l;S+=E){var h={x:r[S],y:r[S+1]};d&&(h.z=r[S+2]),u.push(h)}const m=this.order=u.length-1,x=this.dims=["x","y"];d&&x.push("z"),this.dimlen=x.length;const g=mt.align(u,{p1:u[0],p2:u[m]}),v=mt.dist(u[0],u[m]);this._linear=g.reduce((S,E)=>S+fm(E.y),0)<v/50,this._lut=[],this._t1=0,this._t2=1,this.update()}static quadraticFromPoints(n,r,i,o){if(typeof o>"u"&&(o=.5),o===0)return new Qn(r,r,i);if(o===1)return new Qn(n,r,r);const l=Qn.getABC(2,n,r,i,o);return new Qn(n,l.A,i)}static cubicFromPoints(n,r,i,o,l){typeof o>"u"&&(o=.5);const d=Qn.getABC(3,n,r,i,o);typeof l>"u"&&(l=mt.dist(r,d.C));const u=l*(1-o)/o,h=mt.dist(n,i),m=(i.x-n.x)/h,x=(i.y-n.y)/h,g=l*m,v=l*x,S=u*m,E=u*x,j={x:r.x-g,y:r.y-v},y={x:r.x+S,y:r.y+E},b=d.A,_={x:b.x+(j.x-b.x)/(1-o),y:b.y+(j.y-b.y)/(1-o)},C={x:b.x+(y.x-b.x)/o,y:b.y+(y.y-b.y)/o},N={x:n.x+(_.x-n.x)/o,y:n.y+(_.y-n.y)/o},$={x:i.x+(C.x-i.x)/(1-o),y:i.y+(C.y-i.y)/(1-o)};return new Qn(n,N,$,i)}static getUtils(){return mt}getUtils(){return Qn.getUtils()}static get PolyBezier(){return Lm}valueOf(){return this.toString()}toString(){return mt.pointsToString(this.points)}toSVG(){if(this._3d)return!1;const n=this.points,r=n[0].x,i=n[0].y,o=["M",r,i,this.order===2?"Q":"C"];for(let l=1,d=n.length;l<d;l++)o.push(n[l].x),o.push(n[l].y);return o.join(" ")}setRatios(n){if(n.length!==this.points.length)throw new Error("incorrect number of ratio values");this.ratios=n,this._lut=[]}verify(){const n=this.coordDigest();n!==this._print&&(this._print=n,this.update())}coordDigest(){return this.points.map(function(n,r){return""+r+n.x+n.y+(n.z?n.z:0)}).join("")}update(){this._lut=[],this.dpoints=mt.derive(this.points,this._3d),this.computedirection()}computedirection(){const n=this.points,r=mt.angle(n[0],n[this.order],n[1]);this.clockwise=r>0}length(){return mt.length(this.derivative.bind(this))}static getABC(n=2,r,i,o,l=.5){const d=mt.projectionratio(l,n),u=1-d,h={x:d*r.x+u*o.x,y:d*r.y+u*o.y},m=mt.abcratio(l,n);return{A:{x:i.x+(i.x-h.x)/m,y:i.y+(i.y-h.y)/m},B:i,C:h,S:r,E:o}}getABC(n,r){r=r||this.get(n);let i=this.points[0],o=this.points[this.order];return Qn.getABC(this.order,i,r,o,n)}getLUT(n){if(this.verify(),n=n||100,this._lut.length===n+1)return this._lut;this._lut=[],n++,this._lut=[];for(let r=0,i,o;r<n;r++)o=r/(n-1),i=this.compute(o),i.t=o,this._lut.push(i);return this._lut}on(n,r){r=r||5;const i=this.getLUT(),o=[];for(let l=0,d,u=0;l<i.length;l++)d=i[l],mt.dist(d,n)<r&&(o.push(d),u+=l/i.length);return o.length?t/=o.length:!1}project(n){const r=this.getLUT(),i=r.length-1,o=mt.closest(r,n),l=o.mpos,d=(l-1)/i,u=(l+1)/i,h=.1/i;let m=o.mdist,x=d,g=x,v;m+=1;for(let S;x<u+h;x+=h)v=this.compute(x),S=mt.dist(n,v),S<m&&(m=S,g=x);return g=g<0?0:g>1?1:g,v=this.compute(g),v.t=g,v.d=m,v}get(n){return this.compute(n)}point(n){return this.points[n]}compute(n){return this.ratios?mt.computeWithRatios(n,this.points,this.ratios,this._3d):mt.compute(n,this.points,this._3d,this.ratios)}raise(){const n=this.points,r=[n[0]],i=n.length;for(let o=1,l,d;o<i;o++)l=n[o],d=n[o-1],r[o]={x:(i-o)/i*l.x+o/i*d.x,y:(i-o)/i*l.y+o/i*d.y};return r[i]=n[i-1],new Qn(r)}derivative(n){return mt.compute(n,this.dpoints[0],this._3d)}dderivative(n){return mt.compute(n,this.dpoints[1],this._3d)}align(){let n=this.points;return new Qn(mt.align(n,{p1:n[0],p2:n[n.length-1]}))}curvature(n){return mt.curvature(n,this.dpoints[0],this.dpoints[1],this._3d)}inflections(){return mt.inflections(this.points)}normal(n){return this._3d?this.__normal3(n):this.__normal2(n)}__normal2(n){const r=this.derivative(n),i=pm(r.x*r.x+r.y*r.y);return{t:n,x:-r.y/i,y:r.x/i}}__normal3(n){const r=this.derivative(n),i=this.derivative(n+.01),o=pm(r.x*r.x+r.y*r.y+r.z*r.z),l=pm(i.x*i.x+i.y*i.y+i.z*i.z);r.x/=o,r.y/=o,r.z/=o,i.x/=l,i.y/=l,i.z/=l;const d={x:i.y*r.z-i.z*r.y,y:i.z*r.x-i.x*r.z,z:i.x*r.y-i.y*r.x},u=pm(d.x*d.x+d.y*d.y+d.z*d.z);d.x/=u,d.y/=u,d.z/=u;const h=[d.x*d.x,d.x*d.y-d.z,d.x*d.z+d.y,d.x*d.y+d.z,d.y*d.y,d.y*d.z-d.x,d.x*d.z-d.y,d.y*d.z+d.x,d.z*d.z];return{t:n,x:h[0]*r.x+h[1]*r.y+h[2]*r.z,y:h[3]*r.x+h[4]*r.y+h[5]*r.z,z:h[6]*r.x+h[7]*r.y+h[8]*r.z}}hull(n){let r=this.points,i=[],o=[],l=0;for(o[l++]=r[0],o[l++]=r[1],o[l++]=r[2],this.order===3&&(o[l++]=r[3]);r.length>1;){i=[];for(let d=0,u,h=r.length-1;d<h;d++)u=mt.lerp(n,r[d],r[d+1]),o[l++]=u,i.push(u);r=i}return o}split(n,r){if(n===0&&r)return this.split(r).left;if(r===1)return this.split(n).right;const i=this.hull(n),o={left:this.order===2?new Qn([i[0],i[3],i[5]]):new Qn([i[0],i[4],i[7],i[9]]),right:this.order===2?new Qn([i[5],i[4],i[2]]):new Qn([i[9],i[8],i[6],i[3]]),span:i};return o.left._t1=mt.map(0,0,1,this._t1,this._t2),o.left._t2=mt.map(n,0,1,this._t1,this._t2),o.right._t1=mt.map(n,0,1,this._t1,this._t2),o.right._t2=mt.map(1,0,1,this._t1,this._t2),r?(r=mt.map(r,n,1,0,1),o.right.split(r).left):o}extrema(){const n={};let r=[];return this.dims.forEach((function(i){let o=function(d){return d[i]},l=this.dpoints[0].map(o);n[i]=mt.droots(l),this.order===3&&(l=this.dpoints[1].map(o),n[i]=n[i].concat(mt.droots(l))),n[i]=n[i].filter(function(d){return d>=0&&d<=1}),r=r.concat(n[i].sort(mt.numberSort))}).bind(this)),n.values=r.sort(mt.numberSort).filter(function(i,o){return r.indexOf(i)===o}),n}bbox(){const n=this.extrema(),r={};return this.dims.forEach((function(i){r[i]=mt.getminmax(this,i,n[i])}).bind(this)),r}overlaps(n){const r=this.bbox(),i=n.bbox();return mt.bboxoverlap(r,i)}offset(n,r){if(typeof r<"u"){const i=this.get(n),o=this.normal(n),l={c:i,n:o,x:i.x+o.x*r,y:i.y+o.y*r};return this._3d&&(l.z=i.z+o.z*r),l}if(this._linear){const i=this.normal(0),o=this.points.map(function(l){const d={x:l.x+n*i.x,y:l.y+n*i.y};return l.z&&i.z&&(d.z=l.z+n*i.z),d});return[new Qn(o)]}return this.reduce().map(function(i){return i._linear?i.offset(n)[0]:i.scale(n)})}simple(){if(this.order===3){const o=mt.angle(this.points[0],this.points[3],this.points[1]),l=mt.angle(this.points[0],this.points[3],this.points[2]);if(o>0&&l<0||o<0&&l>0)return!1}const n=this.normal(0),r=this.normal(1);let i=n.x*r.x+n.y*r.y;return this._3d&&(i+=n.z*r.z),fm(JU(i))<QU/3}reduce(){let n,r=0,i=0,o=.01,l,d=[],u=[],h=this.extrema().values;for(h.indexOf(0)===-1&&(h=[0].concat(h)),h.indexOf(1)===-1&&h.push(1),r=h[0],n=1;n<h.length;n++)i=h[n],l=this.split(r,i),l._t1=r,l._t2=i,d.push(l),r=i;return d.forEach(function(m){for(r=0,i=0;i<=1;)for(i=r+o;i<=1+o;i+=o)if(l=m.split(r,i),!l.simple()){if(i-=o,fm(r-i)<o)return[];l=m.split(r,i),l._t1=mt.map(r,0,1,m._t1,m._t2),l._t2=mt.map(i,0,1,m._t1,m._t2),u.push(l),r=i;break}r<1&&(l=m.split(r,1),l._t1=mt.map(r,0,1,m._t1,m._t2),l._t2=m._t2,u.push(l))}),u}translate(n,r,i){i=typeof i=="number"?i:r;const o=this.order;let l=this.points.map((d,u)=>(1-u/o)*r+u/o*i);return new Qn(this.points.map((d,u)=>({x:d.x+n.x*l[u],y:d.y+n.y*l[u]})))}scale(n){const r=this.order;let i=!1;if(typeof n=="function"&&(i=n),i&&r===2)return this.raise().scale(i);const o=this.clockwise,l=this.points;if(this._linear)return this.translate(this.normal(0),i?i(0):n,i?i(1):n);const d=i?i(0):n,u=i?i(1):n,h=[this.offset(0,10),this.offset(1,10)],m=[],x=mt.lli4(h[0],h[0].c,h[1],h[1].c);if(!x)throw new Error("cannot scale this curve. Try reducing it first.");return[0,1].forEach(function(g){const v=m[g*r]=mt.copy(l[g*r]);v.x+=(g?u:d)*h[g].n.x,v.y+=(g?u:d)*h[g].n.y}),i?([0,1].forEach(function(g){if(!(r===2&&g)){var v=l[g+1],S={x:v.x-x.x,y:v.y-x.y},E=i?i((g+1)/r):n;i&&!o&&(E=-E);var j=pm(S.x*S.x+S.y*S.y);S.x/=j,S.y/=j,m[g+1]={x:v.x+E*S.x,y:v.y+E*S.y}}}),new Qn(m)):([0,1].forEach(g=>{if(r===2&&g)return;const v=m[g*r],S=this.derivative(g),E={x:v.x+S.x,y:v.y+S.y};m[g+1]=mt.lli4(v,E,x,l[g+1])}),new Qn(m))}outline(n,r,i,o){if(r=r===void 0?n:r,this._linear){const $=this.normal(0),R=this.points[0],O=this.points[this.points.length-1];let I,z,U;i===void 0&&(i=n,o=r),I={x:R.x+$.x*n,y:R.y+$.y*n},U={x:O.x+$.x*i,y:O.y+$.y*i},z={x:(I.x+U.x)/2,y:(I.y+U.y)/2};const W=[I,z,U];I={x:R.x-$.x*r,y:R.y-$.y*r},U={x:O.x-$.x*o,y:O.y-$.y*o},z={x:(I.x+U.x)/2,y:(I.y+U.y)/2};const Y=[U,z,I],V=mt.makeline(Y[2],W[0]),H=mt.makeline(W[2],Y[0]),te=[V,new Qn(W),H,new Qn(Y)];return new Lm(te)}const l=this.reduce(),d=l.length,u=[];let h=[],m,x=0,g=this.length();const v=typeof i<"u"&&typeof o<"u";function S($,R,O,I,z){return function(U){const W=I/O,Y=(I+z)/O,V=R-$;return mt.map(U,0,1,$+W*V,$+Y*V)}}l.forEach(function($){const R=$.length();v?(u.push($.scale(S(n,i,g,x,R))),h.push($.scale(S(-r,-o,g,x,R)))):(u.push($.scale(n)),h.push($.scale(-r))),x+=R}),h=h.map(function($){return m=$.points,m[3]?$.points=[m[3],m[2],m[1],m[0]]:$.points=[m[2],m[1],m[0]],$}).reverse();const E=u[0].points[0],j=u[d-1].points[u[d-1].points.length-1],y=h[d-1].points[h[d-1].points.length-1],b=h[0].points[0],_=mt.makeline(y,E),C=mt.makeline(j,b),N=[_].concat(u).concat([C]).concat(h);return new Lm(N)}outlineshapes(n,r,i){r=r||n;const o=this.outline(n,r).curves,l=[];for(let d=1,u=o.length;d<u/2;d++){const h=mt.makeshape(o[d],o[u-d],i);h.startcap.virtual=d>1,h.endcap.virtual=d<u/2-1,l.push(h)}return l}intersects(n,r){return n?n.p1&&n.p2?this.lineIntersects(n):(n instanceof Qn&&(n=n.reduce()),this.curveintersects(this.reduce(),n,r)):this.selfintersects(r)}lineIntersects(n){const r=qS(n.p1.x,n.p2.x),i=qS(n.p1.y,n.p2.y),o=VS(n.p1.x,n.p2.x),l=VS(n.p1.y,n.p2.y);return mt.roots(this.points,n).filter(d=>{var u=this.get(d);return mt.between(u.x,r,o)&&mt.between(u.y,i,l)})}selfintersects(n){const r=this.reduce(),i=r.length-2,o=[];for(let l=0,d,u,h;l<i;l++)u=r.slice(l,l+1),h=r.slice(l+2),d=this.curveintersects(u,h,n),o.push(...d);return o}curveintersects(n,r,i){const o=[];n.forEach(function(d){r.forEach(function(u){d.overlaps(u)&&o.push({left:d,right:u})})});let l=[];return o.forEach(function(d){const u=mt.pairiteration(d.left,d.right,i);u.length>0&&(l=l.concat(u))}),l}arcs(n){return n=n||.5,this._iterate(n,[])}_error(n,r,i,o){const l=(o-i)/4,d=this.get(i+l),u=this.get(o-l),h=mt.dist(n,r),m=mt.dist(n,d),x=mt.dist(n,u);return fm(m-h)+fm(x-h)}_iterate(n,r){let i=0,o=1,l;do{l=0,o=1;let d=this.get(i),u,h,m,x,g=!1,v=!1,S,E=o,j=1;do if(v=g,x=m,E=(i+o)/2,u=this.get(E),h=this.get(o),m=mt.getccenter(d,u,h),m.interval={start:i,end:o},g=this._error(m,d,i,o)<=n,S=v&&!g,S||(j=o),g){if(o>=1){if(m.interval.end=j=1,x=m,o>1){let b={x:m.x+m.r*XU(m.e),y:m.y+m.r*YU(m.e)};m.e+=mt.angle({x:m.x,y:m.y},b,this.get(1))}break}o=o+(o-i)/2}else o=E;while(!S&&l++<100);if(l>=100)break;x=x||m,r.push(x),i=j}while(o<1);return r}}function Bw(e,n){(n==null||n>e.length)&&(n=e.length);for(var r=0,i=Array(n);r<n;r++)i[r]=e[r];return i}function ZU(e){if(Array.isArray(e))return e}function eH(e){if(Array.isArray(e))return Bw(e)}function tH(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function nH(e,n){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var i,o,l,d,u=[],h=!0,m=!1;try{if(l=(r=r.call(e)).next,n!==0)for(;!(h=(i=l.call(r)).done)&&(u.push(i.value),u.length!==n);h=!0);}catch(x){m=!0,o=x}finally{try{if(!h&&r.return!=null&&(d=r.return(),Object(d)!==d))return}finally{if(m)throw o}}return u}}function rH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
3429
|
+
`;I8(P8);var D8=I0({props:{content:{default:!1},offsetX:{triggerUpdate:!1},offsetY:{triggerUpdate:!1}},init:function(n,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},o=i.style,l=o===void 0?{}:o,d=!!n&&qy(n)==="object"&&!!n.node&&typeof n.node=="function",u=ao(d?n.node():n);u.style("position")==="static"&&u.style("position","relative"),r.tooltipEl=u.append("div").attr("class","float-tooltip-kap"),Object.entries(l).forEach(function(m){var x=N8(m,2),g=x[0],v=x[1];return r.tooltipEl.style(g,v)}),r.tooltipEl.style("left","-10000px").style("display","none");var h="tooltip-".concat(Math.round(Math.random()*1e12));r.mouseInside=!1,u.on("mousemove.".concat(h),function(m){r.mouseInside=!0;var x=ga(m),g=u.node(),v=g.offsetWidth,S=g.offsetHeight,E=[r.offsetX===null||r.offsetX===void 0?"-".concat(x[0]/v*100,"%"):typeof r.offsetX=="number"?"calc(-50% + ".concat(r.offsetX,"px)"):r.offsetX,r.offsetY===null||r.offsetY===void 0?S>130&&S-x[1]<100?"calc(-100% - 6px)":"21px":typeof r.offsetY=="number"?r.offsetY<0?"calc(-100% - ".concat(Math.abs(r.offsetY),"px)"):"".concat(r.offsetY,"px"):r.offsetY];r.tooltipEl.style("left",x[0]+"px").style("top",x[1]+"px").style("transform","translate(".concat(E.join(","),")")),r.content&&r.tooltipEl.style("display","inline")}),u.on("mouseover.".concat(h),function(){r.mouseInside=!0,r.content&&r.tooltipEl.style("display","inline")}),u.on("mouseout.".concat(h),function(){r.mouseInside=!1,r.tooltipEl.style("display","none")})},update:function(n){n.tooltipEl.style("display",n.content&&n.mouseInside?"inline":"none"),n.content?n.content instanceof HTMLElement?(n.tooltipEl.text(""),n.tooltipEl.append(function(){return n.content})):typeof n.content=="string"?n.tooltipEl.html(n.content):R8(n.content)?(n.tooltipEl.text(""),M8(n.content,n.tooltipEl.node())):(n.tooltipEl.style("display","none"),console.warn("Tooltip content is invalid, skipping.",n.content,n.content.toString())):n.tooltipEl.text("")}});function O8(e,n,r){var i,o=1;e==null&&(e=0),n==null&&(n=0),r==null&&(r=0);function l(){var d,u=i.length,h,m=0,x=0,g=0;for(d=0;d<u;++d)h=i[d],m+=h.x||0,x+=h.y||0,g+=h.z||0;for(m=(m/u-e)*o,x=(x/u-n)*o,g=(g/u-r)*o,d=0;d<u;++d)h=i[d],m&&(h.x-=m),x&&(h.y-=x),g&&(h.z-=g)}return l.initialize=function(d){i=d},l.x=function(d){return arguments.length?(e=+d,l):e},l.y=function(d){return arguments.length?(n=+d,l):n},l.z=function(d){return arguments.length?(r=+d,l):r},l.strength=function(d){return arguments.length?(o=+d,l):o},l}function L8(e){const n=+this._x.call(null,e);return AE(this.cover(n),n,e)}function AE(e,n,r){if(isNaN(n))return e;var i,o=e._root,l={data:r},d=e._x0,u=e._x1,h,m,x,g,v;if(!o)return e._root=l,e;for(;o.length;)if((x=n>=(h=(d+u)/2))?d=h:u=h,i=o,!(o=o[g=+x]))return i[g]=l,e;if(m=+e._x.call(null,o.data),n===m)return l.next=o,i?i[g]=l:e._root=l,e;do i=i?i[g]=new Array(2):e._root=new Array(2),(x=n>=(h=(d+u)/2))?d=h:u=h;while((g=+x)==(v=+(m>=h)));return i[v]=o,i[g]=l,e}function z8(e){Array.isArray(e)||(e=Array.from(e));const n=e.length,r=new Float64Array(n);let i=1/0,o=-1/0;for(let l=0,d;l<n;++l)isNaN(d=+this._x.call(null,e[l]))||(r[l]=d,d<i&&(i=d),d>o&&(o=d));if(i>o)return this;this.cover(i).cover(o);for(let l=0;l<n;++l)AE(this,r[l],e[l]);return this}function B8(e){if(isNaN(e=+e))return this;var n=this._x0,r=this._x1;if(isNaN(n))r=(n=Math.floor(e))+1;else{for(var i=r-n||1,o=this._root,l,d;n>e||e>=r;)switch(d=+(e<n),l=new Array(2),l[d]=o,o=l,i*=2,d){case 0:r=n+i;break;case 1:n=r-i;break}this._root&&this._root.length&&(this._root=o)}return this._x0=n,this._x1=r,this}function F8(){var e=[];return this.visit(function(n){if(!n.length)do e.push(n.data);while(n=n.next)}),e}function U8(e){return arguments.length?this.cover(+e[0][0]).cover(+e[1][0]):isNaN(this._x0)?void 0:[[this._x0],[this._x1]]}function xl(e,n,r){this.node=e,this.x0=n,this.x1=r}function H8(e,n){var r,i=this._x0,o,l,d=this._x1,u=[],h=this._root,m,x;for(h&&u.push(new xl(h,i,d)),n==null?n=1/0:(i=e-n,d=e+n);m=u.pop();)if(!(!(h=m.node)||(o=m.x0)>d||(l=m.x1)<i))if(h.length){var g=(o+l)/2;u.push(new xl(h[1],g,l),new xl(h[0],o,g)),(x=+(e>=g))&&(m=u[u.length-1],u[u.length-1]=u[u.length-1-x],u[u.length-1-x]=m)}else{var v=Math.abs(e-+this._x.call(null,h.data));v<n&&(n=v,i=e-v,d=e+v,r=h.data)}return r}function W8(e){if(isNaN(h=+this._x.call(null,e)))return this;var n,r=this._root,i,o,l,d=this._x0,u=this._x1,h,m,x,g,v;if(!r)return this;if(r.length)for(;;){if((x=h>=(m=(d+u)/2))?d=m:u=m,n=r,!(r=r[g=+x]))return this;if(!r.length)break;n[g+1&1]&&(i=n,v=g)}for(;r.data!==e;)if(o=r,!(r=r.next))return this;return(l=r.next)&&delete r.next,o?(l?o.next=l:delete o.next,this):n?(l?n[g]=l:delete n[g],(r=n[0]||n[1])&&r===(n[1]||n[0])&&!r.length&&(i?i[v]=r:this._root=r),this):(this._root=l,this)}function q8(e){for(var n=0,r=e.length;n<r;++n)this.remove(e[n]);return this}function V8(){return this._root}function G8(){var e=0;return this.visit(function(n){if(!n.length)do++e;while(n=n.next)}),e}function K8(e){var n=[],r,i=this._root,o,l,d;for(i&&n.push(new xl(i,this._x0,this._x1));r=n.pop();)if(!e(i=r.node,l=r.x0,d=r.x1)&&i.length){var u=(l+d)/2;(o=i[1])&&n.push(new xl(o,u,d)),(o=i[0])&&n.push(new xl(o,l,u))}return this}function X8(e){var n=[],r=[],i;for(this._root&&n.push(new xl(this._root,this._x0,this._x1));i=n.pop();){var o=i.node;if(o.length){var l,d=i.x0,u=i.x1,h=(d+u)/2;(l=o[0])&&n.push(new xl(l,d,h)),(l=o[1])&&n.push(new xl(l,h,u))}r.push(i)}for(;i=r.pop();)e(i.node,i.x0,i.x1);return this}function Y8(e){return e[0]}function J8(e){return arguments.length?(this._x=e,this):this._x}function RE(e,n){var r=new z0(n??Y8,NaN,NaN);return e==null?r:r.addAll(e)}function z0(e,n,r){this._x=e,this._x0=n,this._x1=r,this._root=void 0}function LS(e){for(var n={data:e.data},r=n;e=e.next;)r=r.next={data:e.data};return n}var yi=RE.prototype=z0.prototype;yi.copy=function(){var e=new z0(this._x,this._x0,this._x1),n=this._root,r,i;if(!n)return e;if(!n.length)return e._root=LS(n),e;for(r=[{source:n,target:e._root=new Array(2)}];n=r.pop();)for(var o=0;o<2;++o)(i=n.source[o])&&(i.length?r.push({source:i,target:n.target[o]=new Array(2)}):n.target[o]=LS(i));return e};yi.add=L8;yi.addAll=z8;yi.cover=B8;yi.data=F8;yi.extent=U8;yi.find=H8;yi.remove=W8;yi.removeAll=q8;yi.root=V8;yi.size=G8;yi.visit=K8;yi.visitAfter=X8;yi.x=J8;function Q8(e){const n=+this._x.call(null,e),r=+this._y.call(null,e);return ME(this.cover(n,r),n,r,e)}function ME(e,n,r,i){if(isNaN(n)||isNaN(r))return e;var o,l=e._root,d={data:i},u=e._x0,h=e._y0,m=e._x1,x=e._y1,g,v,S,E,j,y,b,_;if(!l)return e._root=d,e;for(;l.length;)if((j=n>=(g=(u+m)/2))?u=g:m=g,(y=r>=(v=(h+x)/2))?h=v:x=v,o=l,!(l=l[b=y<<1|j]))return o[b]=d,e;if(S=+e._x.call(null,l.data),E=+e._y.call(null,l.data),n===S&&r===E)return d.next=l,o?o[b]=d:e._root=d,e;do o=o?o[b]=new Array(4):e._root=new Array(4),(j=n>=(g=(u+m)/2))?u=g:m=g,(y=r>=(v=(h+x)/2))?h=v:x=v;while((b=y<<1|j)===(_=(E>=v)<<1|S>=g));return o[_]=l,o[b]=d,e}function Z8(e){var n,r,i=e.length,o,l,d=new Array(i),u=new Array(i),h=1/0,m=1/0,x=-1/0,g=-1/0;for(r=0;r<i;++r)isNaN(o=+this._x.call(null,n=e[r]))||isNaN(l=+this._y.call(null,n))||(d[r]=o,u[r]=l,o<h&&(h=o),o>x&&(x=o),l<m&&(m=l),l>g&&(g=l));if(h>x||m>g)return this;for(this.cover(h,m).cover(x,g),r=0;r<i;++r)ME(this,d[r],u[r],e[r]);return this}function eU(e,n){if(isNaN(e=+e)||isNaN(n=+n))return this;var r=this._x0,i=this._y0,o=this._x1,l=this._y1;if(isNaN(r))o=(r=Math.floor(e))+1,l=(i=Math.floor(n))+1;else{for(var d=o-r||1,u=this._root,h,m;r>e||e>=o||i>n||n>=l;)switch(m=(n<i)<<1|e<r,h=new Array(4),h[m]=u,u=h,d*=2,m){case 0:o=r+d,l=i+d;break;case 1:r=o-d,l=i+d;break;case 2:o=r+d,i=l-d;break;case 3:r=o-d,i=l-d;break}this._root&&this._root.length&&(this._root=u)}return this._x0=r,this._y0=i,this._x1=o,this._y1=l,this}function tU(){var e=[];return this.visit(function(n){if(!n.length)do e.push(n.data);while(n=n.next)}),e}function nU(e){return arguments.length?this.cover(+e[0][0],+e[0][1]).cover(+e[1][0],+e[1][1]):isNaN(this._x0)?void 0:[[this._x0,this._y0],[this._x1,this._y1]]}function Ks(e,n,r,i,o){this.node=e,this.x0=n,this.y0=r,this.x1=i,this.y1=o}function rU(e,n,r){var i,o=this._x0,l=this._y0,d,u,h,m,x=this._x1,g=this._y1,v=[],S=this._root,E,j;for(S&&v.push(new Ks(S,o,l,x,g)),r==null?r=1/0:(o=e-r,l=n-r,x=e+r,g=n+r,r*=r);E=v.pop();)if(!(!(S=E.node)||(d=E.x0)>x||(u=E.y0)>g||(h=E.x1)<o||(m=E.y1)<l))if(S.length){var y=(d+h)/2,b=(u+m)/2;v.push(new Ks(S[3],y,b,h,m),new Ks(S[2],d,b,y,m),new Ks(S[1],y,u,h,b),new Ks(S[0],d,u,y,b)),(j=(n>=b)<<1|e>=y)&&(E=v[v.length-1],v[v.length-1]=v[v.length-1-j],v[v.length-1-j]=E)}else{var _=e-+this._x.call(null,S.data),C=n-+this._y.call(null,S.data),N=_*_+C*C;if(N<r){var $=Math.sqrt(r=N);o=e-$,l=n-$,x=e+$,g=n+$,i=S.data}}return i}function sU(e){if(isNaN(x=+this._x.call(null,e))||isNaN(g=+this._y.call(null,e)))return this;var n,r=this._root,i,o,l,d=this._x0,u=this._y0,h=this._x1,m=this._y1,x,g,v,S,E,j,y,b;if(!r)return this;if(r.length)for(;;){if((E=x>=(v=(d+h)/2))?d=v:h=v,(j=g>=(S=(u+m)/2))?u=S:m=S,n=r,!(r=r[y=j<<1|E]))return this;if(!r.length)break;(n[y+1&3]||n[y+2&3]||n[y+3&3])&&(i=n,b=y)}for(;r.data!==e;)if(o=r,!(r=r.next))return this;return(l=r.next)&&delete r.next,o?(l?o.next=l:delete o.next,this):n?(l?n[y]=l:delete n[y],(r=n[0]||n[1]||n[2]||n[3])&&r===(n[3]||n[2]||n[1]||n[0])&&!r.length&&(i?i[b]=r:this._root=r),this):(this._root=l,this)}function iU(e){for(var n=0,r=e.length;n<r;++n)this.remove(e[n]);return this}function oU(){return this._root}function aU(){var e=0;return this.visit(function(n){if(!n.length)do++e;while(n=n.next)}),e}function lU(e){var n=[],r,i=this._root,o,l,d,u,h;for(i&&n.push(new Ks(i,this._x0,this._y0,this._x1,this._y1));r=n.pop();)if(!e(i=r.node,l=r.x0,d=r.y0,u=r.x1,h=r.y1)&&i.length){var m=(l+u)/2,x=(d+h)/2;(o=i[3])&&n.push(new Ks(o,m,x,u,h)),(o=i[2])&&n.push(new Ks(o,l,x,m,h)),(o=i[1])&&n.push(new Ks(o,m,d,u,x)),(o=i[0])&&n.push(new Ks(o,l,d,m,x))}return this}function cU(e){var n=[],r=[],i;for(this._root&&n.push(new Ks(this._root,this._x0,this._y0,this._x1,this._y1));i=n.pop();){var o=i.node;if(o.length){var l,d=i.x0,u=i.y0,h=i.x1,m=i.y1,x=(d+h)/2,g=(u+m)/2;(l=o[0])&&n.push(new Ks(l,d,u,x,g)),(l=o[1])&&n.push(new Ks(l,x,u,h,g)),(l=o[2])&&n.push(new Ks(l,d,g,x,m)),(l=o[3])&&n.push(new Ks(l,x,g,h,m))}r.push(i)}for(;i=r.pop();)e(i.node,i.x0,i.y0,i.x1,i.y1);return this}function uU(e){return e[0]}function dU(e){return arguments.length?(this._x=e,this):this._x}function hU(e){return e[1]}function fU(e){return arguments.length?(this._y=e,this):this._y}function IE(e,n,r){var i=new B0(n??uU,r??hU,NaN,NaN,NaN,NaN);return e==null?i:i.addAll(e)}function B0(e,n,r,i,o,l){this._x=e,this._y=n,this._x0=r,this._y0=i,this._x1=o,this._y1=l,this._root=void 0}function zS(e){for(var n={data:e.data},r=n;e=e.next;)r=r.next={data:e.data};return n}var Js=IE.prototype=B0.prototype;Js.copy=function(){var e=new B0(this._x,this._y,this._x0,this._y0,this._x1,this._y1),n=this._root,r,i;if(!n)return e;if(!n.length)return e._root=zS(n),e;for(r=[{source:n,target:e._root=new Array(4)}];n=r.pop();)for(var o=0;o<4;++o)(i=n.source[o])&&(i.length?r.push({source:i,target:n.target[o]=new Array(4)}):n.target[o]=zS(i));return e};Js.add=Q8;Js.addAll=Z8;Js.cover=eU;Js.data=tU;Js.extent=nU;Js.find=rU;Js.remove=sU;Js.removeAll=iU;Js.root=oU;Js.size=aU;Js.visit=lU;Js.visitAfter=cU;Js.x=dU;Js.y=fU;function pU(e){const n=+this._x.call(null,e),r=+this._y.call(null,e),i=+this._z.call(null,e);return PE(this.cover(n,r,i),n,r,i,e)}function PE(e,n,r,i,o){if(isNaN(n)||isNaN(r)||isNaN(i))return e;var l,d=e._root,u={data:o},h=e._x0,m=e._y0,x=e._z0,g=e._x1,v=e._y1,S=e._z1,E,j,y,b,_,C,N,$,R,O,I;if(!d)return e._root=u,e;for(;d.length;)if((N=n>=(E=(h+g)/2))?h=E:g=E,($=r>=(j=(m+v)/2))?m=j:v=j,(R=i>=(y=(x+S)/2))?x=y:S=y,l=d,!(d=d[O=R<<2|$<<1|N]))return l[O]=u,e;if(b=+e._x.call(null,d.data),_=+e._y.call(null,d.data),C=+e._z.call(null,d.data),n===b&&r===_&&i===C)return u.next=d,l?l[O]=u:e._root=u,e;do l=l?l[O]=new Array(8):e._root=new Array(8),(N=n>=(E=(h+g)/2))?h=E:g=E,($=r>=(j=(m+v)/2))?m=j:v=j,(R=i>=(y=(x+S)/2))?x=y:S=y;while((O=R<<2|$<<1|N)===(I=(C>=y)<<2|(_>=j)<<1|b>=E));return l[I]=d,l[O]=u,e}function mU(e){Array.isArray(e)||(e=Array.from(e));const n=e.length,r=new Float64Array(n),i=new Float64Array(n),o=new Float64Array(n);let l=1/0,d=1/0,u=1/0,h=-1/0,m=-1/0,x=-1/0;for(let g=0,v,S,E,j;g<n;++g)isNaN(S=+this._x.call(null,v=e[g]))||isNaN(E=+this._y.call(null,v))||isNaN(j=+this._z.call(null,v))||(r[g]=S,i[g]=E,o[g]=j,S<l&&(l=S),S>h&&(h=S),E<d&&(d=E),E>m&&(m=E),j<u&&(u=j),j>x&&(x=j));if(l>h||d>m||u>x)return this;this.cover(l,d,u).cover(h,m,x);for(let g=0;g<n;++g)PE(this,r[g],i[g],o[g],e[g]);return this}function gU(e,n,r){if(isNaN(e=+e)||isNaN(n=+n)||isNaN(r=+r))return this;var i=this._x0,o=this._y0,l=this._z0,d=this._x1,u=this._y1,h=this._z1;if(isNaN(i))d=(i=Math.floor(e))+1,u=(o=Math.floor(n))+1,h=(l=Math.floor(r))+1;else{for(var m=d-i||1,x=this._root,g,v;i>e||e>=d||o>n||n>=u||l>r||r>=h;)switch(v=(r<l)<<2|(n<o)<<1|e<i,g=new Array(8),g[v]=x,x=g,m*=2,v){case 0:d=i+m,u=o+m,h=l+m;break;case 1:i=d-m,u=o+m,h=l+m;break;case 2:d=i+m,o=u-m,h=l+m;break;case 3:i=d-m,o=u-m,h=l+m;break;case 4:d=i+m,u=o+m,l=h-m;break;case 5:i=d-m,u=o+m,l=h-m;break;case 6:d=i+m,o=u-m,l=h-m;break;case 7:i=d-m,o=u-m,l=h-m;break}this._root&&this._root.length&&(this._root=x)}return this._x0=i,this._y0=o,this._z0=l,this._x1=d,this._y1=u,this._z1=h,this}function xU(){var e=[];return this.visit(function(n){if(!n.length)do e.push(n.data);while(n=n.next)}),e}function yU(e){return arguments.length?this.cover(+e[0][0],+e[0][1],+e[0][2]).cover(+e[1][0],+e[1][1],+e[1][2]):isNaN(this._x0)?void 0:[[this._x0,this._y0,this._z0],[this._x1,this._y1,this._z1]]}function qn(e,n,r,i,o,l,d){this.node=e,this.x0=n,this.y0=r,this.z0=i,this.x1=o,this.y1=l,this.z1=d}function vU(e,n,r,i){var o,l=this._x0,d=this._y0,u=this._z0,h,m,x,g,v,S,E=this._x1,j=this._y1,y=this._z1,b=[],_=this._root,C,N;for(_&&b.push(new qn(_,l,d,u,E,j,y)),i==null?i=1/0:(l=e-i,d=n-i,u=r-i,E=e+i,j=n+i,y=r+i,i*=i);C=b.pop();)if(!(!(_=C.node)||(h=C.x0)>E||(m=C.y0)>j||(x=C.z0)>y||(g=C.x1)<l||(v=C.y1)<d||(S=C.z1)<u))if(_.length){var $=(h+g)/2,R=(m+v)/2,O=(x+S)/2;b.push(new qn(_[7],$,R,O,g,v,S),new qn(_[6],h,R,O,$,v,S),new qn(_[5],$,m,O,g,R,S),new qn(_[4],h,m,O,$,R,S),new qn(_[3],$,R,x,g,v,O),new qn(_[2],h,R,x,$,v,O),new qn(_[1],$,m,x,g,R,O),new qn(_[0],h,m,x,$,R,O)),(N=(r>=O)<<2|(n>=R)<<1|e>=$)&&(C=b[b.length-1],b[b.length-1]=b[b.length-1-N],b[b.length-1-N]=C)}else{var I=e-+this._x.call(null,_.data),z=n-+this._y.call(null,_.data),U=r-+this._z.call(null,_.data),W=I*I+z*z+U*U;if(W<i){var Y=Math.sqrt(i=W);l=e-Y,d=n-Y,u=r-Y,E=e+Y,j=n+Y,y=r+Y,o=_.data}}return o}const bU=(e,n,r,i,o,l)=>Math.sqrt((e-i)**2+(n-o)**2+(r-l)**2);function wU(e,n,r,i){const o=[],l=e-i,d=n-i,u=r-i,h=e+i,m=n+i,x=r+i;return this.visit((g,v,S,E,j,y,b)=>{if(!g.length)do{const _=g.data;bU(e,n,r,this._x(_),this._y(_),this._z(_))<=i&&o.push(_)}while(g=g.next);return v>h||S>m||E>x||j<l||y<d||b<u}),o}function _U(e){if(isNaN(v=+this._x.call(null,e))||isNaN(S=+this._y.call(null,e))||isNaN(E=+this._z.call(null,e)))return this;var n,r=this._root,i,o,l,d=this._x0,u=this._y0,h=this._z0,m=this._x1,x=this._y1,g=this._z1,v,S,E,j,y,b,_,C,N,$,R;if(!r)return this;if(r.length)for(;;){if((_=v>=(j=(d+m)/2))?d=j:m=j,(C=S>=(y=(u+x)/2))?u=y:x=y,(N=E>=(b=(h+g)/2))?h=b:g=b,n=r,!(r=r[$=N<<2|C<<1|_]))return this;if(!r.length)break;(n[$+1&7]||n[$+2&7]||n[$+3&7]||n[$+4&7]||n[$+5&7]||n[$+6&7]||n[$+7&7])&&(i=n,R=$)}for(;r.data!==e;)if(o=r,!(r=r.next))return this;return(l=r.next)&&delete r.next,o?(l?o.next=l:delete o.next,this):n?(l?n[$]=l:delete n[$],(r=n[0]||n[1]||n[2]||n[3]||n[4]||n[5]||n[6]||n[7])&&r===(n[7]||n[6]||n[5]||n[4]||n[3]||n[2]||n[1]||n[0])&&!r.length&&(i?i[R]=r:this._root=r),this):(this._root=l,this)}function kU(e){for(var n=0,r=e.length;n<r;++n)this.remove(e[n]);return this}function SU(){return this._root}function CU(){var e=0;return this.visit(function(n){if(!n.length)do++e;while(n=n.next)}),e}function jU(e){var n=[],r,i=this._root,o,l,d,u,h,m,x;for(i&&n.push(new qn(i,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));r=n.pop();)if(!e(i=r.node,l=r.x0,d=r.y0,u=r.z0,h=r.x1,m=r.y1,x=r.z1)&&i.length){var g=(l+h)/2,v=(d+m)/2,S=(u+x)/2;(o=i[7])&&n.push(new qn(o,g,v,S,h,m,x)),(o=i[6])&&n.push(new qn(o,l,v,S,g,m,x)),(o=i[5])&&n.push(new qn(o,g,d,S,h,v,x)),(o=i[4])&&n.push(new qn(o,l,d,S,g,v,x)),(o=i[3])&&n.push(new qn(o,g,v,u,h,m,S)),(o=i[2])&&n.push(new qn(o,l,v,u,g,m,S)),(o=i[1])&&n.push(new qn(o,g,d,u,h,v,S)),(o=i[0])&&n.push(new qn(o,l,d,u,g,v,S))}return this}function EU(e){var n=[],r=[],i;for(this._root&&n.push(new qn(this._root,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1));i=n.pop();){var o=i.node;if(o.length){var l,d=i.x0,u=i.y0,h=i.z0,m=i.x1,x=i.y1,g=i.z1,v=(d+m)/2,S=(u+x)/2,E=(h+g)/2;(l=o[0])&&n.push(new qn(l,d,u,h,v,S,E)),(l=o[1])&&n.push(new qn(l,v,u,h,m,S,E)),(l=o[2])&&n.push(new qn(l,d,S,h,v,x,E)),(l=o[3])&&n.push(new qn(l,v,S,h,m,x,E)),(l=o[4])&&n.push(new qn(l,d,u,E,v,S,g)),(l=o[5])&&n.push(new qn(l,v,u,E,m,S,g)),(l=o[6])&&n.push(new qn(l,d,S,E,v,x,g)),(l=o[7])&&n.push(new qn(l,v,S,E,m,x,g))}r.push(i)}for(;i=r.pop();)e(i.node,i.x0,i.y0,i.z0,i.x1,i.y1,i.z1);return this}function NU(e){return e[0]}function TU(e){return arguments.length?(this._x=e,this):this._x}function $U(e){return e[1]}function AU(e){return arguments.length?(this._y=e,this):this._y}function RU(e){return e[2]}function MU(e){return arguments.length?(this._z=e,this):this._z}function DE(e,n,r,i){var o=new F0(n??NU,r??$U,i??RU,NaN,NaN,NaN,NaN,NaN,NaN);return e==null?o:o.addAll(e)}function F0(e,n,r,i,o,l,d,u,h){this._x=e,this._y=n,this._z=r,this._x0=i,this._y0=o,this._z0=l,this._x1=d,this._y1=u,this._z1=h,this._root=void 0}function BS(e){for(var n={data:e.data},r=n;e=e.next;)r=r.next={data:e.data};return n}var Cs=DE.prototype=F0.prototype;Cs.copy=function(){var e=new F0(this._x,this._y,this._z,this._x0,this._y0,this._z0,this._x1,this._y1,this._z1),n=this._root,r,i;if(!n)return e;if(!n.length)return e._root=BS(n),e;for(r=[{source:n,target:e._root=new Array(8)}];n=r.pop();)for(var o=0;o<8;++o)(i=n.source[o])&&(i.length?r.push({source:i,target:n.target[o]=new Array(8)}):n.target[o]=BS(i));return e};Cs.add=pU;Cs.addAll=mU;Cs.cover=gU;Cs.data=xU;Cs.extent=yU;Cs.find=vU;Cs.findAllWithinRadius=wU;Cs.remove=_U;Cs.removeAll=kU;Cs.root=SU;Cs.size=CU;Cs.visit=jU;Cs.visitAfter=EU;Cs.x=TU;Cs.y=AU;Cs.z=MU;function ml(e){return function(){return e}}function dl(e){return(e()-.5)*1e-6}function IU(e){return e.index}function FS(e,n){var r=e.get(n);if(!r)throw new Error("node not found: "+n);return r}function PU(e){var n=IU,r=v,i,o=ml(30),l,d,u,h,m,x,g=1;e==null&&(e=[]);function v(b){return 1/Math.min(h[b.source.index],h[b.target.index])}function S(b){for(var _=0,C=e.length;_<g;++_)for(var N=0,$,R,O,I=0,z=0,U=0,W,Y;N<C;++N)$=e[N],R=$.source,O=$.target,I=O.x+O.vx-R.x-R.vx||dl(x),u>1&&(z=O.y+O.vy-R.y-R.vy||dl(x)),u>2&&(U=O.z+O.vz-R.z-R.vz||dl(x)),W=Math.sqrt(I*I+z*z+U*U),W=(W-l[N])/W*b*i[N],I*=W,z*=W,U*=W,O.vx-=I*(Y=m[N]),u>1&&(O.vy-=z*Y),u>2&&(O.vz-=U*Y),R.vx+=I*(Y=1-Y),u>1&&(R.vy+=z*Y),u>2&&(R.vz+=U*Y)}function E(){if(d){var b,_=d.length,C=e.length,N=new Map(d.map((R,O)=>[n(R,O,d),R])),$;for(b=0,h=new Array(_);b<C;++b)$=e[b],$.index=b,typeof $.source!="object"&&($.source=FS(N,$.source)),typeof $.target!="object"&&($.target=FS(N,$.target)),h[$.source.index]=(h[$.source.index]||0)+1,h[$.target.index]=(h[$.target.index]||0)+1;for(b=0,m=new Array(C);b<C;++b)$=e[b],m[b]=h[$.source.index]/(h[$.source.index]+h[$.target.index]);i=new Array(C),j(),l=new Array(C),y()}}function j(){if(d)for(var b=0,_=e.length;b<_;++b)i[b]=+r(e[b],b,e)}function y(){if(d)for(var b=0,_=e.length;b<_;++b)l[b]=+o(e[b],b,e)}return S.initialize=function(b,..._){d=b,x=_.find(C=>typeof C=="function")||Math.random,u=_.find(C=>[1,2,3].includes(C))||2,E()},S.links=function(b){return arguments.length?(e=b,E(),S):e},S.id=function(b){return arguments.length?(n=b,S):n},S.iterations=function(b){return arguments.length?(g=+b,S):g},S.strength=function(b){return arguments.length?(r=typeof b=="function"?b:ml(+b),j(),S):r},S.distance=function(b){return arguments.length?(o=typeof b=="function"?b:ml(+b),y(),S):o},S}const DU=1664525,OU=1013904223,US=4294967296;function LU(){let e=1;return()=>(e=(DU*e+OU)%US)/US}var HS=3;function vb(e){return e.x}function WS(e){return e.y}function zU(e){return e.z}var BU=10,FU=Math.PI*(3-Math.sqrt(5)),UU=Math.PI*20/(9+Math.sqrt(221));function HU(e,n){n=n||2;var r=Math.min(HS,Math.max(1,Math.round(n))),i,o=1,l=.001,d=1-Math.pow(l,1/300),u=0,h=.6,m=new Map,x=$0(S),g=ig("tick","end"),v=LU();e==null&&(e=[]);function S(){E(),g.call("tick",i),o<l&&(x.stop(),g.call("end",i))}function E(b){var _,C=e.length,N;b===void 0&&(b=1);for(var $=0;$<b;++$)for(o+=(u-o)*d,m.forEach(function(R){R(o)}),_=0;_<C;++_)N=e[_],N.fx==null?N.x+=N.vx*=h:(N.x=N.fx,N.vx=0),r>1&&(N.fy==null?N.y+=N.vy*=h:(N.y=N.fy,N.vy=0)),r>2&&(N.fz==null?N.z+=N.vz*=h:(N.z=N.fz,N.vz=0));return i}function j(){for(var b=0,_=e.length,C;b<_;++b){if(C=e[b],C.index=b,C.fx!=null&&(C.x=C.fx),C.fy!=null&&(C.y=C.fy),C.fz!=null&&(C.z=C.fz),isNaN(C.x)||r>1&&isNaN(C.y)||r>2&&isNaN(C.z)){var N=BU*(r>2?Math.cbrt(.5+b):r>1?Math.sqrt(.5+b):b),$=b*FU,R=b*UU;r===1?C.x=N:r===2?(C.x=N*Math.cos($),C.y=N*Math.sin($)):(C.x=N*Math.sin($)*Math.cos(R),C.y=N*Math.cos($),C.z=N*Math.sin($)*Math.sin(R))}(isNaN(C.vx)||r>1&&isNaN(C.vy)||r>2&&isNaN(C.vz))&&(C.vx=0,r>1&&(C.vy=0),r>2&&(C.vz=0))}}function y(b){return b.initialize&&b.initialize(e,v,r),b}return j(),i={tick:E,restart:function(){return x.restart(S),i},stop:function(){return x.stop(),i},numDimensions:function(b){return arguments.length?(r=Math.min(HS,Math.max(1,Math.round(b))),m.forEach(y),i):r},nodes:function(b){return arguments.length?(e=b,j(),m.forEach(y),i):e},alpha:function(b){return arguments.length?(o=+b,i):o},alphaMin:function(b){return arguments.length?(l=+b,i):l},alphaDecay:function(b){return arguments.length?(d=+b,i):+d},alphaTarget:function(b){return arguments.length?(u=+b,i):u},velocityDecay:function(b){return arguments.length?(h=1-b,i):1-h},randomSource:function(b){return arguments.length?(v=b,m.forEach(y),i):v},force:function(b,_){return arguments.length>1?(_==null?m.delete(b):m.set(b,y(_)),i):m.get(b)},find:function(){var b=Array.prototype.slice.call(arguments),_=b.shift()||0,C=(r>1?b.shift():null)||0,N=(r>2?b.shift():null)||0,$=b.shift()||1/0,R=0,O=e.length,I,z,U,W,Y,V;for($*=$,R=0;R<O;++R)Y=e[R],I=_-Y.x,z=C-(Y.y||0),U=N-(Y.z||0),W=I*I+z*z+U*U,W<$&&(V=Y,$=W);return V},on:function(b,_){return arguments.length>1?(g.on(b,_),i):g.on(b)}}}function WU(){var e,n,r,i,o,l=ml(-30),d,u=1,h=1/0,m=.81;function x(E){var j,y=e.length,b=(n===1?RE(e,vb):n===2?IE(e,vb,WS):n===3?DE(e,vb,WS,zU):null).visitAfter(v);for(o=E,j=0;j<y;++j)r=e[j],b.visit(S)}function g(){if(e){var E,j=e.length,y;for(d=new Array(j),E=0;E<j;++E)y=e[E],d[y.index]=+l(y,E,e)}}function v(E){var j=0,y,b,_=0,C,N,$,R,O=E.length;if(O){for(C=N=$=R=0;R<O;++R)(y=E[R])&&(b=Math.abs(y.value))&&(j+=y.value,_+=b,C+=b*(y.x||0),N+=b*(y.y||0),$+=b*(y.z||0));j*=Math.sqrt(4/O),E.x=C/_,n>1&&(E.y=N/_),n>2&&(E.z=$/_)}else{y=E,y.x=y.data.x,n>1&&(y.y=y.data.y),n>2&&(y.z=y.data.z);do j+=d[y.data.index];while(y=y.next)}E.value=j}function S(E,j,y,b,_){if(!E.value)return!0;var C=[y,b,_][n-1],N=E.x-r.x,$=n>1?E.y-r.y:0,R=n>2?E.z-r.z:0,O=C-j,I=N*N+$*$+R*R;if(O*O/m<I)return I<h&&(N===0&&(N=dl(i),I+=N*N),n>1&&$===0&&($=dl(i),I+=$*$),n>2&&R===0&&(R=dl(i),I+=R*R),I<u&&(I=Math.sqrt(u*I)),r.vx+=N*E.value*o/I,n>1&&(r.vy+=$*E.value*o/I),n>2&&(r.vz+=R*E.value*o/I)),!0;if(E.length||I>=h)return;(E.data!==r||E.next)&&(N===0&&(N=dl(i),I+=N*N),n>1&&$===0&&($=dl(i),I+=$*$),n>2&&R===0&&(R=dl(i),I+=R*R),I<u&&(I=Math.sqrt(u*I)));do E.data!==r&&(O=d[E.data.index]*o/I,r.vx+=N*O,n>1&&(r.vy+=$*O),n>2&&(r.vz+=R*O));while(E=E.next)}return x.initialize=function(E,...j){e=E,i=j.find(y=>typeof y=="function")||Math.random,n=j.find(y=>[1,2,3].includes(y))||2,g()},x.strength=function(E){return arguments.length?(l=typeof E=="function"?E:ml(+E),g(),x):l},x.distanceMin=function(E){return arguments.length?(u=E*E,x):Math.sqrt(u)},x.distanceMax=function(E){return arguments.length?(h=E*E,x):Math.sqrt(h)},x.theta=function(E){return arguments.length?(m=E*E,x):Math.sqrt(m)},x}function qU(e,n,r,i){var o,l,d=ml(.1),u,h;typeof e!="function"&&(e=ml(+e)),n==null&&(n=0),r==null&&(r=0),i==null&&(i=0);function m(g){for(var v=0,S=o.length;v<S;++v){var E=o[v],j=E.x-n||1e-6,y=(E.y||0)-r||1e-6,b=(E.z||0)-i||1e-6,_=Math.sqrt(j*j+y*y+b*b),C=(h[v]-_)*u[v]*g/_;E.vx+=j*C,l>1&&(E.vy+=y*C),l>2&&(E.vz+=b*C)}}function x(){if(o){var g,v=o.length;for(u=new Array(v),h=new Array(v),g=0;g<v;++g)h[g]=+e(o[g],g,o),u[g]=isNaN(h[g])?0:+d(o[g],g,o)}}return m.initialize=function(g,...v){o=g,l=v.find(S=>[1,2,3].includes(S))||2,x()},m.strength=function(g){return arguments.length?(d=typeof g=="function"?g:ml(+g),x(),m):d},m.radius=function(g){return arguments.length?(e=typeof g=="function"?g:ml(+g),x(),m):e},m.x=function(g){return arguments.length?(n=+g,m):n},m.y=function(g){return arguments.length?(r=+g,m):r},m.z=function(g){return arguments.length?(i=+g,m):i},m}const{abs:um,cos:ll,sin:$h,acos:VU,atan2:dm,sqrt:tc,pow:so}=Math;function hm(e){return e<0?-so(-e,1/3):so(e,1/3)}const OE=Math.PI,Bx=2*OE,nc=OE/2,GU=1e-6,bb=Number.MAX_SAFE_INTEGER||9007199254740991,wb=Number.MIN_SAFE_INTEGER||-9007199254740991,KU={x:0,y:0,z:0},mt={Tvalues:[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213],Cvalues:[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872],arcfn:function(e,n){const r=n(e);let i=r.x*r.x+r.y*r.y;return typeof r.z<"u"&&(i+=r.z*r.z),tc(i)},compute:function(e,n,r){if(e===0)return n[0].t=0,n[0];const i=n.length-1;if(e===1)return n[i].t=1,n[i];const o=1-e;let l=n;if(i===0)return n[0].t=e,n[0];if(i===1){const u={x:o*l[0].x+e*l[1].x,y:o*l[0].y+e*l[1].y,t:e};return r&&(u.z=o*l[0].z+e*l[1].z),u}if(i<4){let u=o*o,h=e*e,m,x,g,v=0;i===2?(l=[l[0],l[1],l[2],KU],m=u,x=o*e*2,g=h):i===3&&(m=u*o,x=u*e*3,g=o*h*3,v=e*h);const S={x:m*l[0].x+x*l[1].x+g*l[2].x+v*l[3].x,y:m*l[0].y+x*l[1].y+g*l[2].y+v*l[3].y,t:e};return r&&(S.z=m*l[0].z+x*l[1].z+g*l[2].z+v*l[3].z),S}const d=JSON.parse(JSON.stringify(n));for(;d.length>1;){for(let u=0;u<d.length-1;u++)d[u]={x:d[u].x+(d[u+1].x-d[u].x)*e,y:d[u].y+(d[u+1].y-d[u].y)*e},typeof d[u].z<"u"&&(d[u].z=d[u].z+(d[u+1].z-d[u].z)*e);d.splice(d.length-1,1)}return d[0].t=e,d[0]},computeWithRatios:function(e,n,r,i){const o=1-e,l=r,d=n;let u=l[0],h=l[1],m=l[2],x=l[3],g;if(u*=o,h*=e,d.length===2)return g=u+h,{x:(u*d[0].x+h*d[1].x)/g,y:(u*d[0].y+h*d[1].y)/g,z:i?(u*d[0].z+h*d[1].z)/g:!1,t:e};if(u*=o,h*=2*o,m*=e*e,d.length===3)return g=u+h+m,{x:(u*d[0].x+h*d[1].x+m*d[2].x)/g,y:(u*d[0].y+h*d[1].y+m*d[2].y)/g,z:i?(u*d[0].z+h*d[1].z+m*d[2].z)/g:!1,t:e};if(u*=o,h*=1.5*o,m*=3*o,x*=e*e*e,d.length===4)return g=u+h+m+x,{x:(u*d[0].x+h*d[1].x+m*d[2].x+x*d[3].x)/g,y:(u*d[0].y+h*d[1].y+m*d[2].y+x*d[3].y)/g,z:i?(u*d[0].z+h*d[1].z+m*d[2].z+x*d[3].z)/g:!1,t:e}},derive:function(e,n){const r=[];for(let i=e,o=i.length,l=o-1;o>1;o--,l--){const d=[];for(let u=0,h;u<l;u++)h={x:l*(i[u+1].x-i[u].x),y:l*(i[u+1].y-i[u].y)},n&&(h.z=l*(i[u+1].z-i[u].z)),d.push(h);r.push(d),i=d}return r},between:function(e,n,r){return n<=e&&e<=r||mt.approximately(e,n)||mt.approximately(e,r)},approximately:function(e,n,r){return um(e-n)<=(r||GU)},length:function(e){const r=mt.Tvalues.length;let i=0;for(let o=0,l;o<r;o++)l=.5*mt.Tvalues[o]+.5,i+=mt.Cvalues[o]*mt.arcfn(l,e);return .5*i},map:function(e,n,r,i,o){const l=r-n,d=o-i,u=e-n,h=u/l;return i+d*h},lerp:function(e,n,r){const i={x:n.x+e*(r.x-n.x),y:n.y+e*(r.y-n.y)};return n.z!==void 0&&r.z!==void 0&&(i.z=n.z+e*(r.z-n.z)),i},pointToString:function(e){let n=e.x+"/"+e.y;return typeof e.z<"u"&&(n+="/"+e.z),n},pointsToString:function(e){return"["+e.map(mt.pointToString).join(", ")+"]"},copy:function(e){return JSON.parse(JSON.stringify(e))},angle:function(e,n,r){const i=n.x-e.x,o=n.y-e.y,l=r.x-e.x,d=r.y-e.y,u=i*d-o*l,h=i*l+o*d;return dm(u,h)},round:function(e,n){const r=""+e,i=r.indexOf(".");return parseFloat(r.substring(0,i+1+n))},dist:function(e,n){const r=e.x-n.x,i=e.y-n.y;return tc(r*r+i*i)},closest:function(e,n){let r=so(2,63),i,o;return e.forEach(function(l,d){o=mt.dist(n,l),o<r&&(r=o,i=d)}),{mdist:r,mpos:i}},abcratio:function(e,n){if(n!==2&&n!==3)return!1;if(typeof e>"u")e=.5;else if(e===0||e===1)return e;const r=so(e,n)+so(1-e,n),i=r-1;return um(i/r)},projectionratio:function(e,n){if(n!==2&&n!==3)return!1;if(typeof e>"u")e=.5;else if(e===0||e===1)return e;const r=so(1-e,n),i=so(e,n)+r;return r/i},lli8:function(e,n,r,i,o,l,d,u){const h=(e*i-n*r)*(o-d)-(e-r)*(o*u-l*d),m=(e*i-n*r)*(l-u)-(n-i)*(o*u-l*d),x=(e-r)*(l-u)-(n-i)*(o-d);return x==0?!1:{x:h/x,y:m/x}},lli4:function(e,n,r,i){const o=e.x,l=e.y,d=n.x,u=n.y,h=r.x,m=r.y,x=i.x,g=i.y;return mt.lli8(o,l,d,u,h,m,x,g)},lli:function(e,n){return mt.lli4(e,e.c,n,n.c)},makeline:function(e,n){return new Qn(e.x,e.y,(e.x+n.x)/2,(e.y+n.y)/2,n.x,n.y)},findbbox:function(e){let n=bb,r=bb,i=wb,o=wb;return e.forEach(function(l){const d=l.bbox();n>d.x.min&&(n=d.x.min),r>d.y.min&&(r=d.y.min),i<d.x.max&&(i=d.x.max),o<d.y.max&&(o=d.y.max)}),{x:{min:n,mid:(n+i)/2,max:i,size:i-n},y:{min:r,mid:(r+o)/2,max:o,size:o-r}}},shapeintersections:function(e,n,r,i,o){if(!mt.bboxoverlap(n,i))return[];const l=[],d=[e.startcap,e.forward,e.back,e.endcap],u=[r.startcap,r.forward,r.back,r.endcap];return d.forEach(function(h){h.virtual||u.forEach(function(m){if(m.virtual)return;const x=h.intersects(m,o);x.length>0&&(x.c1=h,x.c2=m,x.s1=e,x.s2=r,l.push(x))})}),l},makeshape:function(e,n,r){const i=n.points.length,o=e.points.length,l=mt.makeline(n.points[i-1],e.points[0]),d=mt.makeline(e.points[o-1],n.points[0]),u={startcap:l,forward:e,back:n,endcap:d,bbox:mt.findbbox([l,e,n,d])};return u.intersections=function(h){return mt.shapeintersections(u,u.bbox,h,h.bbox,r)},u},getminmax:function(e,n,r){if(!r)return{min:0,max:0};let i=bb,o=wb,l,d;r.indexOf(0)===-1&&(r=[0].concat(r)),r.indexOf(1)===-1&&r.push(1);for(let u=0,h=r.length;u<h;u++)l=r[u],d=e.get(l),d[n]<i&&(i=d[n]),d[n]>o&&(o=d[n]);return{min:i,mid:(i+o)/2,max:o,size:o-i}},align:function(e,n){const r=n.p1.x,i=n.p1.y,o=-dm(n.p2.y-i,n.p2.x-r),l=function(d){return{x:(d.x-r)*ll(o)-(d.y-i)*$h(o),y:(d.x-r)*$h(o)+(d.y-i)*ll(o)}};return e.map(l)},roots:function(e,n){n=n||{p1:{x:0,y:0},p2:{x:1,y:0}};const r=e.length-1,i=mt.align(e,n),o=function(O){return 0<=O&&O<=1};if(r===2){const O=i[0].y,I=i[1].y,z=i[2].y,U=O-2*I+z;if(U!==0){const W=-tc(I*I-O*z),Y=-O+I,V=-(W+Y)/U,H=-(-W+Y)/U;return[V,H].filter(o)}else if(I!==z&&U===0)return[(2*I-z)/(2*I-2*z)].filter(o);return[]}const l=i[0].y,d=i[1].y,u=i[2].y,h=i[3].y;let m=-l+3*d-3*u+h,x=3*l-6*d+3*u,g=-3*l+3*d,v=l;if(mt.approximately(m,0)){if(mt.approximately(x,0))return mt.approximately(g,0)?[]:[-v/g].filter(o);const O=tc(g*g-4*x*v),I=2*x;return[(O-g)/I,(-g-O)/I].filter(o)}x/=m,g/=m,v/=m;const S=(3*g-x*x)/3,E=S/3,j=(2*x*x*x-9*x*g+27*v)/27,y=j/2,b=y*y+E*E*E;let _,C,N,$,R;if(b<0){const O=-S/3,I=O*O*O,z=tc(I),U=-j/(2*z),W=U<-1?-1:U>1?1:U,Y=VU(W),V=hm(z),H=2*V;return N=H*ll(Y/3)-x/3,$=H*ll((Y+Bx)/3)-x/3,R=H*ll((Y+2*Bx)/3)-x/3,[N,$,R].filter(o)}else{if(b===0)return _=y<0?hm(-y):-hm(y),N=2*_-x/3,$=-_-x/3,[N,$].filter(o);{const O=tc(b);return _=hm(-y+O),C=hm(y+O),[_-C-x/3].filter(o)}}},droots:function(e){if(e.length===3){const n=e[0],r=e[1],i=e[2],o=n-2*r+i;if(o!==0){const l=-tc(r*r-n*i),d=-n+r,u=-(l+d)/o,h=-(-l+d)/o;return[u,h]}else if(r!==i&&o===0)return[(2*r-i)/(2*(r-i))];return[]}if(e.length===2){const n=e[0],r=e[1];return n!==r?[n/(n-r)]:[]}return[]},curvature:function(e,n,r,i,o){let l,d,u,h,m=0,x=0;const g=mt.compute(e,n),v=mt.compute(e,r),S=g.x*g.x+g.y*g.y;if(i?(l=tc(so(g.y*v.z-v.y*g.z,2)+so(g.z*v.x-v.z*g.x,2)+so(g.x*v.y-v.x*g.y,2)),d=so(S+g.z*g.z,3/2)):(l=g.x*v.y-g.y*v.x,d=so(S,3/2)),l===0||d===0)return{k:0,r:0};if(m=l/d,x=d/l,!o){const E=mt.curvature(e-.001,n,r,i,!0).k,j=mt.curvature(e+.001,n,r,i,!0).k;h=(j-m+(m-E))/2,u=(um(j-m)+um(m-E))/2}return{k:m,r:x,dk:h,adk:u}},inflections:function(e){if(e.length<4)return[];const n=mt.align(e,{p1:e[0],p2:e.slice(-1)[0]}),r=n[2].x*n[1].y,i=n[3].x*n[1].y,o=n[1].x*n[2].y,l=n[3].x*n[2].y,d=18*(-3*r+2*i+3*o-l),u=18*(3*r-i-3*o),h=18*(o-r);if(mt.approximately(d,0)){if(!mt.approximately(u,0)){let v=-h/u;if(0<=v&&v<=1)return[v]}return[]}const m=2*d;if(mt.approximately(m,0))return[];const x=u*u-4*d*h;if(x<0)return[];const g=Math.sqrt(x);return[(g-u)/m,-(u+g)/m].filter(function(v){return 0<=v&&v<=1})},bboxoverlap:function(e,n){const r=["x","y"],i=r.length;for(let o=0,l,d,u,h;o<i;o++)if(l=r[o],d=e[l].mid,u=n[l].mid,h=(e[l].size+n[l].size)/2,um(d-u)>=h)return!1;return!0},expandbox:function(e,n){n.x.min<e.x.min&&(e.x.min=n.x.min),n.y.min<e.y.min&&(e.y.min=n.y.min),n.z&&n.z.min<e.z.min&&(e.z.min=n.z.min),n.x.max>e.x.max&&(e.x.max=n.x.max),n.y.max>e.y.max&&(e.y.max=n.y.max),n.z&&n.z.max>e.z.max&&(e.z.max=n.z.max),e.x.mid=(e.x.min+e.x.max)/2,e.y.mid=(e.y.min+e.y.max)/2,e.z&&(e.z.mid=(e.z.min+e.z.max)/2),e.x.size=e.x.max-e.x.min,e.y.size=e.y.max-e.y.min,e.z&&(e.z.size=e.z.max-e.z.min)},pairiteration:function(e,n,r){const i=e.bbox(),o=n.bbox(),l=1e5,d=r||.5;if(i.x.size+i.y.size<d&&o.x.size+o.y.size<d)return[(l*(e._t1+e._t2)/2|0)/l+"/"+(l*(n._t1+n._t2)/2|0)/l];let u=e.split(.5),h=n.split(.5),m=[{left:u.left,right:h.left},{left:u.left,right:h.right},{left:u.right,right:h.right},{left:u.right,right:h.left}];m=m.filter(function(g){return mt.bboxoverlap(g.left.bbox(),g.right.bbox())});let x=[];return m.length===0||(m.forEach(function(g){x=x.concat(mt.pairiteration(g.left,g.right,d))}),x=x.filter(function(g,v){return x.indexOf(g)===v})),x},getccenter:function(e,n,r){const i=n.x-e.x,o=n.y-e.y,l=r.x-n.x,d=r.y-n.y,u=i*ll(nc)-o*$h(nc),h=i*$h(nc)+o*ll(nc),m=l*ll(nc)-d*$h(nc),x=l*$h(nc)+d*ll(nc),g=(e.x+n.x)/2,v=(e.y+n.y)/2,S=(n.x+r.x)/2,E=(n.y+r.y)/2,j=g+u,y=v+h,b=S+m,_=E+x,C=mt.lli8(g,v,j,y,S,E,b,_),N=mt.dist(C,e);let $=dm(e.y-C.y,e.x-C.x),R=dm(n.y-C.y,n.x-C.x),O=dm(r.y-C.y,r.x-C.x),I;return $<O?(($>R||R>O)&&($+=Bx),$>O&&(I=O,O=$,$=I)):O<R&&R<$?(I=O,O=$,$=I):O+=Bx,C.s=$,C.e=O,C.r=N,C},numberSort:function(e,n){return e-n}};class Lm{constructor(n){this.curves=[],this._3d=!1,n&&(this.curves=n,this._3d=this.curves[0]._3d)}valueOf(){return this.toString()}toString(){return"["+this.curves.map(function(n){return mt.pointsToString(n.points)}).join(", ")+"]"}addCurve(n){this.curves.push(n),this._3d=this._3d||n._3d}length(){return this.curves.map(function(n){return n.length()}).reduce(function(n,r){return n+r})}curve(n){return this.curves[n]}bbox(){const n=this.curves;for(var r=n[0].bbox(),i=1;i<n.length;i++)mt.expandbox(r,n[i].bbox());return r}offset(n){const r=[];return this.curves.forEach(function(i){r.push(...i.offset(n))}),new Lm(r)}}const{abs:fm,min:qS,max:VS,cos:XU,sin:YU,acos:JU,sqrt:pm}=Math,QU=Math.PI;class Qn{constructor(n){let r=n&&n.forEach?n:Array.from(arguments).slice(),i=!1;if(typeof r[0]=="object"){i=r.length;const S=[];r.forEach(function(E){["x","y","z"].forEach(function(j){typeof E[j]<"u"&&S.push(E[j])})}),r=S}let o=!1;const l=r.length;if(i){if(i>4){if(arguments.length!==1)throw new Error("Only new Bezier(point[]) is accepted for 4th and higher order curves");o=!0}}else if(l!==6&&l!==8&&l!==9&&l!==12&&arguments.length!==1)throw new Error("Only new Bezier(point[]) is accepted for 4th and higher order curves");const d=this._3d=!o&&(l===9||l===12)||n&&n[0]&&typeof n[0].z<"u",u=this.points=[];for(let S=0,E=d?3:2;S<l;S+=E){var h={x:r[S],y:r[S+1]};d&&(h.z=r[S+2]),u.push(h)}const m=this.order=u.length-1,x=this.dims=["x","y"];d&&x.push("z"),this.dimlen=x.length;const g=mt.align(u,{p1:u[0],p2:u[m]}),v=mt.dist(u[0],u[m]);this._linear=g.reduce((S,E)=>S+fm(E.y),0)<v/50,this._lut=[],this._t1=0,this._t2=1,this.update()}static quadraticFromPoints(n,r,i,o){if(typeof o>"u"&&(o=.5),o===0)return new Qn(r,r,i);if(o===1)return new Qn(n,r,r);const l=Qn.getABC(2,n,r,i,o);return new Qn(n,l.A,i)}static cubicFromPoints(n,r,i,o,l){typeof o>"u"&&(o=.5);const d=Qn.getABC(3,n,r,i,o);typeof l>"u"&&(l=mt.dist(r,d.C));const u=l*(1-o)/o,h=mt.dist(n,i),m=(i.x-n.x)/h,x=(i.y-n.y)/h,g=l*m,v=l*x,S=u*m,E=u*x,j={x:r.x-g,y:r.y-v},y={x:r.x+S,y:r.y+E},b=d.A,_={x:b.x+(j.x-b.x)/(1-o),y:b.y+(j.y-b.y)/(1-o)},C={x:b.x+(y.x-b.x)/o,y:b.y+(y.y-b.y)/o},N={x:n.x+(_.x-n.x)/o,y:n.y+(_.y-n.y)/o},$={x:i.x+(C.x-i.x)/(1-o),y:i.y+(C.y-i.y)/(1-o)};return new Qn(n,N,$,i)}static getUtils(){return mt}getUtils(){return Qn.getUtils()}static get PolyBezier(){return Lm}valueOf(){return this.toString()}toString(){return mt.pointsToString(this.points)}toSVG(){if(this._3d)return!1;const n=this.points,r=n[0].x,i=n[0].y,o=["M",r,i,this.order===2?"Q":"C"];for(let l=1,d=n.length;l<d;l++)o.push(n[l].x),o.push(n[l].y);return o.join(" ")}setRatios(n){if(n.length!==this.points.length)throw new Error("incorrect number of ratio values");this.ratios=n,this._lut=[]}verify(){const n=this.coordDigest();n!==this._print&&(this._print=n,this.update())}coordDigest(){return this.points.map(function(n,r){return""+r+n.x+n.y+(n.z?n.z:0)}).join("")}update(){this._lut=[],this.dpoints=mt.derive(this.points,this._3d),this.computedirection()}computedirection(){const n=this.points,r=mt.angle(n[0],n[this.order],n[1]);this.clockwise=r>0}length(){return mt.length(this.derivative.bind(this))}static getABC(n=2,r,i,o,l=.5){const d=mt.projectionratio(l,n),u=1-d,h={x:d*r.x+u*o.x,y:d*r.y+u*o.y},m=mt.abcratio(l,n);return{A:{x:i.x+(i.x-h.x)/m,y:i.y+(i.y-h.y)/m},B:i,C:h,S:r,E:o}}getABC(n,r){r=r||this.get(n);let i=this.points[0],o=this.points[this.order];return Qn.getABC(this.order,i,r,o,n)}getLUT(n){if(this.verify(),n=n||100,this._lut.length===n+1)return this._lut;this._lut=[],n++,this._lut=[];for(let r=0,i,o;r<n;r++)o=r/(n-1),i=this.compute(o),i.t=o,this._lut.push(i);return this._lut}on(n,r){r=r||5;const i=this.getLUT(),o=[];for(let l=0,d,u=0;l<i.length;l++)d=i[l],mt.dist(d,n)<r&&(o.push(d),u+=l/i.length);return o.length?t/=o.length:!1}project(n){const r=this.getLUT(),i=r.length-1,o=mt.closest(r,n),l=o.mpos,d=(l-1)/i,u=(l+1)/i,h=.1/i;let m=o.mdist,x=d,g=x,v;m+=1;for(let S;x<u+h;x+=h)v=this.compute(x),S=mt.dist(n,v),S<m&&(m=S,g=x);return g=g<0?0:g>1?1:g,v=this.compute(g),v.t=g,v.d=m,v}get(n){return this.compute(n)}point(n){return this.points[n]}compute(n){return this.ratios?mt.computeWithRatios(n,this.points,this.ratios,this._3d):mt.compute(n,this.points,this._3d,this.ratios)}raise(){const n=this.points,r=[n[0]],i=n.length;for(let o=1,l,d;o<i;o++)l=n[o],d=n[o-1],r[o]={x:(i-o)/i*l.x+o/i*d.x,y:(i-o)/i*l.y+o/i*d.y};return r[i]=n[i-1],new Qn(r)}derivative(n){return mt.compute(n,this.dpoints[0],this._3d)}dderivative(n){return mt.compute(n,this.dpoints[1],this._3d)}align(){let n=this.points;return new Qn(mt.align(n,{p1:n[0],p2:n[n.length-1]}))}curvature(n){return mt.curvature(n,this.dpoints[0],this.dpoints[1],this._3d)}inflections(){return mt.inflections(this.points)}normal(n){return this._3d?this.__normal3(n):this.__normal2(n)}__normal2(n){const r=this.derivative(n),i=pm(r.x*r.x+r.y*r.y);return{t:n,x:-r.y/i,y:r.x/i}}__normal3(n){const r=this.derivative(n),i=this.derivative(n+.01),o=pm(r.x*r.x+r.y*r.y+r.z*r.z),l=pm(i.x*i.x+i.y*i.y+i.z*i.z);r.x/=o,r.y/=o,r.z/=o,i.x/=l,i.y/=l,i.z/=l;const d={x:i.y*r.z-i.z*r.y,y:i.z*r.x-i.x*r.z,z:i.x*r.y-i.y*r.x},u=pm(d.x*d.x+d.y*d.y+d.z*d.z);d.x/=u,d.y/=u,d.z/=u;const h=[d.x*d.x,d.x*d.y-d.z,d.x*d.z+d.y,d.x*d.y+d.z,d.y*d.y,d.y*d.z-d.x,d.x*d.z-d.y,d.y*d.z+d.x,d.z*d.z];return{t:n,x:h[0]*r.x+h[1]*r.y+h[2]*r.z,y:h[3]*r.x+h[4]*r.y+h[5]*r.z,z:h[6]*r.x+h[7]*r.y+h[8]*r.z}}hull(n){let r=this.points,i=[],o=[],l=0;for(o[l++]=r[0],o[l++]=r[1],o[l++]=r[2],this.order===3&&(o[l++]=r[3]);r.length>1;){i=[];for(let d=0,u,h=r.length-1;d<h;d++)u=mt.lerp(n,r[d],r[d+1]),o[l++]=u,i.push(u);r=i}return o}split(n,r){if(n===0&&r)return this.split(r).left;if(r===1)return this.split(n).right;const i=this.hull(n),o={left:this.order===2?new Qn([i[0],i[3],i[5]]):new Qn([i[0],i[4],i[7],i[9]]),right:this.order===2?new Qn([i[5],i[4],i[2]]):new Qn([i[9],i[8],i[6],i[3]]),span:i};return o.left._t1=mt.map(0,0,1,this._t1,this._t2),o.left._t2=mt.map(n,0,1,this._t1,this._t2),o.right._t1=mt.map(n,0,1,this._t1,this._t2),o.right._t2=mt.map(1,0,1,this._t1,this._t2),r?(r=mt.map(r,n,1,0,1),o.right.split(r).left):o}extrema(){const n={};let r=[];return this.dims.forEach((function(i){let o=function(d){return d[i]},l=this.dpoints[0].map(o);n[i]=mt.droots(l),this.order===3&&(l=this.dpoints[1].map(o),n[i]=n[i].concat(mt.droots(l))),n[i]=n[i].filter(function(d){return d>=0&&d<=1}),r=r.concat(n[i].sort(mt.numberSort))}).bind(this)),n.values=r.sort(mt.numberSort).filter(function(i,o){return r.indexOf(i)===o}),n}bbox(){const n=this.extrema(),r={};return this.dims.forEach((function(i){r[i]=mt.getminmax(this,i,n[i])}).bind(this)),r}overlaps(n){const r=this.bbox(),i=n.bbox();return mt.bboxoverlap(r,i)}offset(n,r){if(typeof r<"u"){const i=this.get(n),o=this.normal(n),l={c:i,n:o,x:i.x+o.x*r,y:i.y+o.y*r};return this._3d&&(l.z=i.z+o.z*r),l}if(this._linear){const i=this.normal(0),o=this.points.map(function(l){const d={x:l.x+n*i.x,y:l.y+n*i.y};return l.z&&i.z&&(d.z=l.z+n*i.z),d});return[new Qn(o)]}return this.reduce().map(function(i){return i._linear?i.offset(n)[0]:i.scale(n)})}simple(){if(this.order===3){const o=mt.angle(this.points[0],this.points[3],this.points[1]),l=mt.angle(this.points[0],this.points[3],this.points[2]);if(o>0&&l<0||o<0&&l>0)return!1}const n=this.normal(0),r=this.normal(1);let i=n.x*r.x+n.y*r.y;return this._3d&&(i+=n.z*r.z),fm(JU(i))<QU/3}reduce(){let n,r=0,i=0,o=.01,l,d=[],u=[],h=this.extrema().values;for(h.indexOf(0)===-1&&(h=[0].concat(h)),h.indexOf(1)===-1&&h.push(1),r=h[0],n=1;n<h.length;n++)i=h[n],l=this.split(r,i),l._t1=r,l._t2=i,d.push(l),r=i;return d.forEach(function(m){for(r=0,i=0;i<=1;)for(i=r+o;i<=1+o;i+=o)if(l=m.split(r,i),!l.simple()){if(i-=o,fm(r-i)<o)return[];l=m.split(r,i),l._t1=mt.map(r,0,1,m._t1,m._t2),l._t2=mt.map(i,0,1,m._t1,m._t2),u.push(l),r=i;break}r<1&&(l=m.split(r,1),l._t1=mt.map(r,0,1,m._t1,m._t2),l._t2=m._t2,u.push(l))}),u}translate(n,r,i){i=typeof i=="number"?i:r;const o=this.order;let l=this.points.map((d,u)=>(1-u/o)*r+u/o*i);return new Qn(this.points.map((d,u)=>({x:d.x+n.x*l[u],y:d.y+n.y*l[u]})))}scale(n){const r=this.order;let i=!1;if(typeof n=="function"&&(i=n),i&&r===2)return this.raise().scale(i);const o=this.clockwise,l=this.points;if(this._linear)return this.translate(this.normal(0),i?i(0):n,i?i(1):n);const d=i?i(0):n,u=i?i(1):n,h=[this.offset(0,10),this.offset(1,10)],m=[],x=mt.lli4(h[0],h[0].c,h[1],h[1].c);if(!x)throw new Error("cannot scale this curve. Try reducing it first.");return[0,1].forEach(function(g){const v=m[g*r]=mt.copy(l[g*r]);v.x+=(g?u:d)*h[g].n.x,v.y+=(g?u:d)*h[g].n.y}),i?([0,1].forEach(function(g){if(!(r===2&&g)){var v=l[g+1],S={x:v.x-x.x,y:v.y-x.y},E=i?i((g+1)/r):n;i&&!o&&(E=-E);var j=pm(S.x*S.x+S.y*S.y);S.x/=j,S.y/=j,m[g+1]={x:v.x+E*S.x,y:v.y+E*S.y}}}),new Qn(m)):([0,1].forEach(g=>{if(r===2&&g)return;const v=m[g*r],S=this.derivative(g),E={x:v.x+S.x,y:v.y+S.y};m[g+1]=mt.lli4(v,E,x,l[g+1])}),new Qn(m))}outline(n,r,i,o){if(r=r===void 0?n:r,this._linear){const $=this.normal(0),R=this.points[0],O=this.points[this.points.length-1];let I,z,U;i===void 0&&(i=n,o=r),I={x:R.x+$.x*n,y:R.y+$.y*n},U={x:O.x+$.x*i,y:O.y+$.y*i},z={x:(I.x+U.x)/2,y:(I.y+U.y)/2};const W=[I,z,U];I={x:R.x-$.x*r,y:R.y-$.y*r},U={x:O.x-$.x*o,y:O.y-$.y*o},z={x:(I.x+U.x)/2,y:(I.y+U.y)/2};const Y=[U,z,I],V=mt.makeline(Y[2],W[0]),H=mt.makeline(W[2],Y[0]),te=[V,new Qn(W),H,new Qn(Y)];return new Lm(te)}const l=this.reduce(),d=l.length,u=[];let h=[],m,x=0,g=this.length();const v=typeof i<"u"&&typeof o<"u";function S($,R,O,I,z){return function(U){const W=I/O,Y=(I+z)/O,V=R-$;return mt.map(U,0,1,$+W*V,$+Y*V)}}l.forEach(function($){const R=$.length();v?(u.push($.scale(S(n,i,g,x,R))),h.push($.scale(S(-r,-o,g,x,R)))):(u.push($.scale(n)),h.push($.scale(-r))),x+=R}),h=h.map(function($){return m=$.points,m[3]?$.points=[m[3],m[2],m[1],m[0]]:$.points=[m[2],m[1],m[0]],$}).reverse();const E=u[0].points[0],j=u[d-1].points[u[d-1].points.length-1],y=h[d-1].points[h[d-1].points.length-1],b=h[0].points[0],_=mt.makeline(y,E),C=mt.makeline(j,b),N=[_].concat(u).concat([C]).concat(h);return new Lm(N)}outlineshapes(n,r,i){r=r||n;const o=this.outline(n,r).curves,l=[];for(let d=1,u=o.length;d<u/2;d++){const h=mt.makeshape(o[d],o[u-d],i);h.startcap.virtual=d>1,h.endcap.virtual=d<u/2-1,l.push(h)}return l}intersects(n,r){return n?n.p1&&n.p2?this.lineIntersects(n):(n instanceof Qn&&(n=n.reduce()),this.curveintersects(this.reduce(),n,r)):this.selfintersects(r)}lineIntersects(n){const r=qS(n.p1.x,n.p2.x),i=qS(n.p1.y,n.p2.y),o=VS(n.p1.x,n.p2.x),l=VS(n.p1.y,n.p2.y);return mt.roots(this.points,n).filter(d=>{var u=this.get(d);return mt.between(u.x,r,o)&&mt.between(u.y,i,l)})}selfintersects(n){const r=this.reduce(),i=r.length-2,o=[];for(let l=0,d,u,h;l<i;l++)u=r.slice(l,l+1),h=r.slice(l+2),d=this.curveintersects(u,h,n),o.push(...d);return o}curveintersects(n,r,i){const o=[];n.forEach(function(d){r.forEach(function(u){d.overlaps(u)&&o.push({left:d,right:u})})});let l=[];return o.forEach(function(d){const u=mt.pairiteration(d.left,d.right,i);u.length>0&&(l=l.concat(u))}),l}arcs(n){return n=n||.5,this._iterate(n,[])}_error(n,r,i,o){const l=(o-i)/4,d=this.get(i+l),u=this.get(o-l),h=mt.dist(n,r),m=mt.dist(n,d),x=mt.dist(n,u);return fm(m-h)+fm(x-h)}_iterate(n,r){let i=0,o=1,l;do{l=0,o=1;let d=this.get(i),u,h,m,x,g=!1,v=!1,S,E=o,j=1;do if(v=g,x=m,E=(i+o)/2,u=this.get(E),h=this.get(o),m=mt.getccenter(d,u,h),m.interval={start:i,end:o},g=this._error(m,d,i,o)<=n,S=v&&!g,S||(j=o),g){if(o>=1){if(m.interval.end=j=1,x=m,o>1){let b={x:m.x+m.r*XU(m.e),y:m.y+m.r*YU(m.e)};m.e+=mt.angle({x:m.x,y:m.y},b,this.get(1))}break}o=o+(o-i)/2}else o=E;while(!S&&l++<100);if(l>=100)break;x=x||m,r.push(x),i=j}while(o<1);return r}}function Bw(e,n){(n==null||n>e.length)&&(n=e.length);for(var r=0,i=Array(n);r<n;r++)i[r]=e[r];return i}function ZU(e){if(Array.isArray(e))return e}function eH(e){if(Array.isArray(e))return Bw(e)}function tH(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function nH(e,n){var r=e==null?null:typeof Symbol<"u"&&e[Symbol.iterator]||e["@@iterator"];if(r!=null){var i,o,l,d,u=[],h=!0,m=!1;try{if(l=(r=r.call(e)).next,n!==0)for(;!(h=(i=l.call(r)).done)&&(u.push(i.value),u.length!==n);h=!0);}catch(x){m=!0,o=x}finally{try{if(!h&&r.return!=null&&(d=r.return(),Object(d)!==d))return}finally{if(m)throw o}}return u}}function rH(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
3430
3430
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function sH(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
3431
3431
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function iH(e,n){if(e==null)return{};var r,i,o=oH(e,n);if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(e);for(i=0;i<l.length;i++)r=l[i],n.includes(r)||{}.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}function oH(e,n){if(e==null)return{};var r={};for(var i in e)if({}.hasOwnProperty.call(e,i)){if(n.includes(i))continue;r[i]=e[i]}return r}function aH(e,n){return ZU(e)||nH(e,n)||LE(e,n)||rH()}function lH(e){return eH(e)||tH(e)||LE(e)||sH()}function cH(e,n){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var i=r.call(e,n);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}function uH(e){var n=cH(e,"string");return typeof n=="symbol"?n:n+""}function LE(e,n){if(e){if(typeof e=="string")return Bw(e,n);var r={}.toString.call(e).slice(8,-1);return r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set"?Array.from(e):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?Bw(e,n):void 0}}var dH=(function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1,o=(n instanceof Array?n.length?n:[void 0]:[n]).map(function(u){return{keyAccessor:u,isProp:!(u instanceof Function)}}),l=e.reduce(function(u,h){var m=u,x=h;return o.forEach(function(g,v){var S=g.keyAccessor,E=g.isProp,j;if(E){var y=x,b=y[S],_=iH(y,[S].map(uH));j=b,x=_}else j=S(x,v);v+1<o.length?(m.hasOwnProperty(j)||(m[j]={}),m=m[j]):r?(m.hasOwnProperty(j)||(m[j]=[]),m[j].push(x)):m[j]=x}),u},{});r instanceof Function&&(function u(h){var m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1;m===o.length?Object.keys(h).forEach(function(x){return h[x]=r(h[x])}):Object.values(h).forEach(function(x){return u(x,m+1)})})(l);var d=l;return i&&(d=[],(function u(h){var m=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];m.length===o.length?d.push({keys:m,vals:h}):Object.entries(h).forEach(function(x){var g=aH(x,2),v=g[0],S=g[1];return u(S,[].concat(lH(m),[v]))})})(l),n instanceof Array&&n.length===0&&d.length===1&&(d[0].keys=[])),d});function hH(e,n){switch(arguments.length){case 0:break;case 1:this.range(e);break;default:this.range(n).domain(e);break}return this}const GS=Symbol("implicit");function zE(){var e=new pS,n=[],r=[],i=GS;function o(l){let d=e.get(l);if(d===void 0){if(i!==GS)return i;e.set(l,d=n.push(l)-1)}return r[d%r.length]}return o.domain=function(l){if(!arguments.length)return n.slice();n=[],e=new pS;for(const d of l)e.has(d)||e.set(d,n.push(d)-1);return o},o.range=function(l){return arguments.length?(r=Array.from(l),o):r.slice()},o.unknown=function(l){return arguments.length?(i=l,o):i},o.copy=function(){return zE(n,r).unknown(i)},hH.apply(o,arguments),o}function fH(e){for(var n=e.length/6|0,r=new Array(n),i=0;i<n;)r[i]="#"+e.slice(i*6,++i*6);return r}const pH=fH("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928");function mH(e,n){n===void 0&&(n={});var r=n.insertAt;if(!(typeof document>"u")){var i=document.head||document.getElementsByTagName("head")[0],o=document.createElement("style");o.type="text/css",r==="top"&&i.firstChild?i.insertBefore(o,i.firstChild):i.appendChild(o),o.styleSheet?o.styleSheet.cssText=e:o.appendChild(document.createTextNode(e))}}var gH=`.force-graph-container canvas {
|
|
3432
3432
|
display: block;
|
|
@@ -3488,7 +3488,7 @@ ${Ab(l)}`;if(W.length>a9){const Y=await window.api.clipboard.writeText(W);if(!Y.
|
|
|
3488
3488
|
|
|
3489
3489
|
Files are moved to prds-archived/<timestamp>/ and can be restored from disk. Running jobs are kept.`;if(!window.confirm(ye))return;const ne=await window.api.schedule.clearQueue();ne.ok||Le.error(`Clear queue failed: ${ne.error??"unknown error"}`)},pe=()=>{h(new Set),u2(new Set),x(!1)},Ae=Q.some(Se=>Se.status==="completed");return s.jsxs("div",{className:"overflow-y-auto h-full",children:[s.jsx("div",{"aria-live":"polite","aria-atomic":"true",className:"sr-only",children:N}),s.jsxs("div",{className:"px-9 py-6 max-w-[1100px] mx-auto space-y-4",children:[s.jsxs("div",{className:`flex flex-wrap items-center gap-3 px-4 py-3 rounded-xl border ${I9(oe.kind)}`,title:oe.tooltip,children:[s.jsxs("div",{className:"flex items-center gap-3 min-w-0 flex-1",children:[s.jsx("div",{className:`w-[38px] h-[38px] rounded-[10px] bg-bg border border-line flex items-center justify-center shrink-0 ${P9(oe.kind)}`,children:s.jsx(dn,{name:"clock",size:19})}),s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[14px] text-fg truncate",children:O9(L9(oe.line1,e.utilization))}),oe.line2&&s.jsx("div",{className:"text-[12px] text-fg-faint font-mono mt-0.5 truncate",children:oe.line2})]})]}),s.jsxs("span",{className:"ml-auto font-mono text-[11.5px] text-fg-faint whitespace-nowrap",children:[z.concurrencyCap??4," slot",(z.concurrencyCap??4)!==1?"s":""," · last batch ",Yh(Y?Date.parse(Y):null,l)]}),oe.action&&s.jsx("button",{type:"button",onClick:oe.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:oe.action.title,children:oe.action.label})]}),n&&n.consecutiveFailures>5&&n.lastFailureKind==="meter_rate_limited"&&!W&&!S&&s.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:[s.jsx("span",{className:"text-[12.5px] text-amber-400 font-medium",children:"Meter rate-limited — firing on heuristic"}),s.jsx("button",{type:"button",onClick:()=>E(!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"})]}),s.jsxs("div",{className:"flex items-center gap-[18px] flex-wrap bg-bg-elev border border-line rounded-xl px-4 py-3",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[13px] text-fg-dim",children:"Start jobs"}),s.jsxs("select",{value:z.firePolicy??"when-available",onChange:Se=>window.api.schedule.setConfig({firePolicy:Se.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:[s.jsx("option",{value:"when-available",children:"when available"}),s.jsx("option",{value:"on-reset",children:"only on reset"}),s.jsx("option",{value:"manual",children:"manually"})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[13px] text-fg-dim",children:"Up to"}),(H==null?void 0:H.source)==="env"&&s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-amber-400/90 bg-amber-400/10 border border-amber-400/30 rounded px-1.5 py-0.5",title:"Pinned by SM_SCHEDULER_MAX_CONCURRENCY — unset the env var to edit",children:"env"}),s.jsx("input",{type:"number",min:1,max:20,value:(H==null?void 0:H.source)==="env"?H.cap:z.concurrencyCap,disabled:(H==null?void 0:H.source)==="env",onChange:Se=>window.api.schedule.setConfig({concurrencyCap:Number(Se.target.value)}),className:"w-11 text-center border border-line bg-bg-hi rounded-lg py-1.5 font-mono text-[13px] text-fg disabled:opacity-50 disabled:cursor-not-allowed",title:(H==null?void 0:H.source)==="env"?"pinned by SM_SCHEDULER_MAX_CONCURRENCY — unset the env var to edit":"Max simultaneous jobs within a parallel group"}),s.jsx("span",{className:"text-[13px] text-fg-dim",children:"at once"})]}),(z.firePolicy??"when-available")==="when-available"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[13px] text-fg-dim",children:"Pause above"}),s.jsx("input",{type:"number",min:0,max:100,value:z.utilizationThreshold??90,onChange:Se=>window.api.schedule.setConfig({utilizationThreshold:Number(Se.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"}),s.jsx("span",{className:"text-[13px] text-fg-dim",children:"% of window"})]}),s.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:()=>window.api.schedule.forceTick().then(Le.fromOutcome).catch(()=>Le.error("Failed to fire batch")),disabled:te.pending===0&&te.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"}),s.jsx("button",{type:"button",onClick:()=>window.api.schedule.rescan().then(Le.fromOutcome).catch(()=>Le.error("Failed to 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"})]})]}),ae.length>0&&(()=>{var we;const Se=z.concurrencyCap??4,ye=(we=ae[0])==null?void 0:we.parallelGroup,ne=U.filter(Ne=>Ne.status==="pending"&&Ne.parallelGroup===ye).length;return s.jsxs("div",{className:"flex items-center gap-2 text-[12px] font-mono",children:[s.jsxs("span",{className:"px-2 py-0.5 rounded bg-amber-400/20 text-amber-400 shrink-0",children:[ae.length,"/",Se," running"]}),ne>0&&s.jsxs("span",{className:"text-fg-faint",children:["+",ne," ready in this group"]})]})})(),U.length>0&&s.jsx(F9,{filter:g,onChange:Se=>{v(Se),E9(Se)}}),s.jsxs("div",{className:"bg-bg-hi border border-line rounded-2xl overflow-hidden",children:[s.jsxs("div",{className:"flex items-center justify-between px-[18px] py-3 bg-bg-elev",children:[s.jsxs("span",{className:"font-serif text-base font-semibold text-fg",children:[ie.length," job",ie.length!==1?"s":""]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsxs("span",{className:"font-mono text-[12px] text-fg-faint",children:[te.pending,"p · ",te.running,"r · ",te.completed,"d",te.failed>0&&s.jsxs("span",{className:"text-accent",children:[" · ",te.failed,"f"]})]}),Ae&&s.jsx("button",{type:"button",onClick:le,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"}),s.jsx("button",{type:"button",onClick:ce,disabled:U.every(Se=>Se.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"})]})]}),U.length===0&&s.jsxs("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint italic",children:["No PRDs queued. Drop .md files in:",s.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/"})]}),U.length>0&&Q.length===0&&J===0&&s.jsx("div",{className:"px-[18px] py-6 text-[13px] text-fg-faint italic",children:"no matching jobs"}),s.jsx("div",{ref:b,role:"list","aria-label":"Job queue",onKeyDown:I,children:Q.map((Se,ye)=>s.jsx(B9,{job:Se,eta:z9(Se,U,X.get(Se.slug)??0,R,oe.kind,l),now:l,avgDurationMs:R,listIndex:ye,onFocused:ne=>{C(ne);try{localStorage.setItem(Wx,String(ne))}catch{}}},Se.slug))}),J>0&&s.jsxs("button",{type:"button",onClick:()=>x(Se=>!Se),className:"w-full text-left text-[12px] text-fg-faint hover:text-fg-dim px-[18px] py-3 border-t border-line",title:m?"Re-collapse old/cleared completed":"Show all completed (incl. cleared and >24h)",children:[m?"▾":"▸"," ",J," more completed",s.jsx("span",{className:"ml-1.5 font-mono text-[11.5px] text-fg-faint",children:"· fresh & capped at 5 shown inline"}),u.size>0&&s.jsx("span",{className:"ml-2 underline",onClick:Se=>{Se.stopPropagation(),pe()},children:"un-hide"})]})]}),s.jsx(q9,{snap:e}),s.jsx(W9,{health:n,now:l,showHealth:i,setShowHealth:o}),s.jsxs("div",{className:"flex items-center justify-between text-[12px] text-fg-faint pt-1 border-t border-line",children:[s.jsxs("span",{children:[V&&s.jsxs("span",{title:`next 5h reset: ${V}`,children:["reset ",Uo(Date.parse(V)-l)]}),Y&&s.jsxs("span",{className:"ml-2",title:Y,children:["last run ",Uo(l-Date.parse(Y))," ago"]})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",onClick:()=>y("supervisor"),className:"hover:text-fg-dim underline",title:"Open supervisor log and settings",children:"supervisor"}),s.jsx("button",{type:"button",onClick:()=>window.api.schedule.openFolder(),className:"hover:text-fg-dim underline",children:"folder"})]})]})]})]})}function A9({snap:e,now:n,avgDurationMs:r,runningJobs:i}){const{config:o,jobs:l,paused:d,nextReset:u,utilization:h}=e;let m=0,x=0;for(const y of l)y.status==="pending"?m++:y.status==="completed"&&x++;const g=i.length,v=m+g,S=o.concurrencyCap??4;if(g>0){const y=i.reduce(($,R)=>($.startedAt??"")<(R.startedAt??"")?$:R),b=y.startedAt?n-Date.parse(y.startedAt):0,_=x+g,C=x+v,N=g>1?` · ${g}/${S} parallel`:"";return{kind:"running",line1:`Running ${_}/${C}${N} · ${Um(b)}`,line2:g===1?y.title:i.map($=>$.title).join(", "),tooltip:i.map($=>`${$.slug} (g${$.parallelGroup})`).join("; ")}}if(d){const y=d.resumeAt?Date.parse(d.resumeAt)-n: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"}[d.reason]??`Paused — ${d.reason}`,line2:d.reason==="auth"?"Run `claude` in any terminal to refresh credentials, then Resume":y!==null&&y>0?`auto-resume ${Wh(Date.parse(d.resumeAt))} (in ${Uo(y)})`:d.resumeAt?"resuming…":"no auto-resume scheduled",tooltip:d.resumeAt??"",action:{label:"Resume",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately"}}}if(v===0)return{kind:"idle",line1:"No work queued",line2:null};const E=o.firePolicy??"when-available";if(E==="manual")return{kind:"manual",line1:`Manual · ${m} pending`,line2:"click Fire next batch now to fire",action:{label:"Fire next batch now",onClick:()=>window.api.schedule.forceTick().then(Le.fromOutcome).catch(()=>Le.error("Failed to fire batch")),title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress."}};if(E==="on-reset"){if(!u)return{kind:"on-reset",line1:"On-reset · waiting for billing data",line2:null};const y=Date.parse(u)+o.offsetMinutes*6e4,b=y-n;return{kind:"on-reset",line1:`On-reset · ${m} pending`,line2:b>0?`fires ${Wh(y)} (in ${Uo(b)})`:"firing now…"}}const j=o.utilizationThreshold??90;if(h==null)return{kind:"auto-soon",line1:`Auto · ${m} pending`,line2:"checking token availability…"};if(h>=j){const y=u?Date.parse(u)-n:null;return{kind:"auto-throttled",line1:`Auto · throttled (util ${h.toFixed(0)}% ≥ ${j}%)`,line2:y&&y>0?`next reset ${Wh(Date.parse(u))} (in ${Uo(y)})`:"will fire when usage drops"}}return{kind:"auto-soon",line1:`Auto · ${m} pending · util ${h.toFixed(0)}%`,line2:"fires within 2 min (poll cycle)"}}function R9(e){const n=e.filter(i=>i.status==="running"||i.status==="pending").sort((i,o)=>i.parallelGroup-o.parallelGroup||i.slug.localeCompare(o.slug)),r=new Map;return n.forEach((i,o)=>r.set(i.slug,o)),r}function M9(e,n,r,i){if(i)return{inline:e,collapsedCount:0};const o=e.filter(m=>m.status==="completed").sort((m,x)=>{const g=m.finishedAt?Date.parse(m.finishedAt):0;return(x.finishedAt?Date.parse(x.finishedAt):0)-g}),l=new Set;let d=0;for(const m of o){if(d>=k9)break;n.has(m.slug)||m.finishedAt&&r-Date.parse(m.finishedAt)>S9||(l.add(m.slug),d++)}const u=[];let h=0;for(const m of e){if(m.status==="failed"&&n.has(m.slug)){h++;continue}if(m.status!=="completed"){u.push(m);continue}l.has(m.slug)?u.push(m):h++}return{inline:u,collapsedCount:h}}function I9(e){return e==="running"?"bg-amber-400/10 border-amber-400/25":e==="paused"?"bg-amber-500/10 border-amber-500/25":e==="auto-throttled"?"bg-amber-500/5 border-amber-500/15":"bg-bg-elev border-line"}function P9(e){return e==="running"||e==="auto-soon"?"text-accent":e==="idle"?"text-sage":e==="paused"||e==="auto-throttled"?"text-butter":"text-fg-faint"}const D9=["Running","Paused","Manual","On-reset","Auto"];function O9(e){for(const n of D9)if(e.startsWith(n))return s.jsxs(s.Fragment,{children:[s.jsx("strong",{className:"font-bold",children:n}),e.slice(n.length)]});return e}function L9(e,n){return n==null||e.includes("util")?e:`${e} · util ${Math.round(n)}%`}function z9(e,n,r,i,o,l){if(e.status!=="pending"||o==="paused"||o==="manual"||o==="auto-throttled")return null;let d=r*i;if(r>0){const u=n.find(h=>h.status==="running"&&h.startedAt);u&&u.startedAt&&(d-=Math.min(i,l-Date.parse(u.startedAt)))}return d<=5e3?"~now":`~${Um(d)}`}function B9({job:e,eta:n,now:r,avgDurationMs:i,listIndex:o,onFocused:l}){const[d,u]=L.useState(!1),[h,m]=L.useState(!1),x=e.status==="running",g=e.status==="failed";let v=null;x&&e.startedAt?v=`${ky(r-Date.parse(e.startedAt))} elapsed`:e.status==="completed"&&e.startedAt&&e.finishedAt?v=`took ${Um(Date.parse(e.finishedAt)-Date.parse(e.startedAt))}`:n&&(v=n);const S=e.error??null,E=g&&S?S.split(`
|
|
3490
3490
|
`)[0]:e.status==="needs_review"&&e.verifierVerdict?wy(e.verifierVerdict):null,j=x&&e.startedAt?Math.min(.99,(r-Date.parse(e.startedAt))/i):0;return s.jsxs("div",{role:"listitem",className:"border-t border-line",children:[s.jsxs("button",{type:"button","data-job-row":!0,"data-job-index":o,onClick:()=>u(y=>!y),onFocus:()=>l(o),className:`w-full text-left grid grid-cols-[116px_1fr_auto_auto] items-center gap-4 px-[18px] py-3.5 hover:bg-bg/40 focus:outline-none focus:ring-1 focus:ring-accent focus:ring-inset ${d?"bg-bg-elev/40":""}`,"aria-expanded":d,"aria-label":`${Ph(e.slug)?`PRD ${Ph(e.slug)}, `:""}${e.title}, ${e.status}${v?`, ${v}`:""}`,title:e.title,children:[s.jsx(TC,{status:e.status}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-baseline gap-2 text-[14.5px] font-medium text-fg leading-snug",children:[Ph(e.slug)&&s.jsx($C,{n:Ph(e.slug)}),e.title]}),E&&s.jsx("div",{className:`text-[12.5px] mt-0.5 ${g?"text-accent/80":"text-fg-faint"}`,children:E})]}),s.jsx(h0,{cwd:e.cwd}),s.jsxs("span",{className:"inline-flex items-center gap-2.5 font-mono text-xs text-fg-faint shrink-0",children:[v,s.jsx("span",{className:`text-fg-faint inline-flex transition-transform duration-150 ${d?"rotate-90":""}`,"aria-hidden":"true",children:s.jsx(dn,{name:"chevron",size:14})})]})]}),x&&!d&&s.jsx("div",{className:"h-1 bg-line mx-[18px] mb-3 rounded-full overflow-hidden",children:s.jsx("div",{className:"h-full bg-accent transition-all duration-1000",style:{width:`${Math.max(4,j*100)}%`}})}),d&&s.jsxs("div",{className:"px-[18px] py-5 grid grid-cols-[repeat(auto-fit,minmax(160px,1fr))] gap-5 bg-bg-elev/50 border-t border-line",children:[s.jsxs(gc,{label:"Status",children:[s.jsx(ss,{k:"result",v:e.exitCode!==null?`exit ${e.exitCode}`:"—"}),s.jsx(ss,{k:"state",v:e.status.replace(/_/g," ")}),e.verifierVerdict&&s.jsx(ss,{k:"verdict",v:wy(e.verifierVerdict)}),S&&s.jsx(ss,{k:"error",v:S.split(`
|
|
3491
|
-
`)[0],wrap:!0})]}),s.jsxs(gc,{label:"Timing",children:[s.jsx(ss,{k:"started",v:e.startedAt?Wh(Date.parse(e.startedAt)):"—"}),s.jsx(ss,{k:"finished",v:e.finishedAt?Wh(Date.parse(e.finishedAt)):"—"}),s.jsx(ss,{k:"duration",v:e.startedAt&&e.finishedAt?Um(Date.parse(e.finishedAt)-Date.parse(e.startedAt)):x&&e.startedAt?ky(r-Date.parse(e.startedAt)):"—"})]}),s.jsxs(gc,{label:"Location",children:[s.jsx(ss,{k:"group",v:`${e.parallelGroup} · ${e.slug}`}),s.jsx(ss,{k:"cwd",v:e.cwd??"—",wrap:!0})]}),s.jsx(gc,{label:"Actions",children:s.jsxs("div",{className:"flex flex-col gap-1.5 items-start",children:[e.runId&&s.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"view log →"}),e.status!=="pending"&&e.status!=="running"&&s.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(e.slug),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"reset to pending →"})]})})]}),h&&e.runId&&s.jsx(sN,{runId:e.runId,slug:e.slug,title:e.title||e.slug,onClose:()=>m(!1)})]})}function F9({filter:e,onChange:n}){const r=[{label:"All",value:"all"},{label:"Running",value:"running"},{label:"Pending",value:"pending"},{label:"Completed",value:"completed"},{label:"Needs review",value:"needs_review"},{label:"Failed",value:"failed"}];return s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-[320px]",children:[s.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-faint inline-flex","aria-hidden":"true",children:s.jsx(dn,{name:"search",size:15})}),s.jsx("input",{type:"text",value:e.text,onChange:i=>n({...e,text:i.target.value}),placeholder:"filter jobs…",className:"w-full bg-bg-hi border border-line rounded-xl py-2 pl-9 pr-3 text-[13.5px] text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint","aria-label":"Filter jobs by title, slug, or project"})]}),s.jsx(iN,{options:r,value:e.status,onChange:i=>n({...e,status:i})})]})}function U9({supervisorConfig:e,onSetConfig:n,onBack:r}){const[i,o]=L.useState([]),[l,d]=L.useState(()=>Date.now());L.useEffect(()=>{window.api.supervisor.getLog().then(o).catch(()=>{});const h=setInterval(()=>d(Date.now()),5e3);return()=>clearInterval(h)},[]);const u={enabled:(e==null?void 0:e.enabled)??!0,intervalMinutes:(e==null?void 0:e.intervalMinutes)??15,maxConcurrentProbes:(e==null?void 0:e.maxConcurrentProbes)??2,probeStaleThresholdMinutes:(e==null?void 0:e.probeStaleThresholdMinutes)??10};return s.jsxs("div",{className:"bg-bg-elev/60",children:[s.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 border-b border-line",children:[s.jsx("button",{type:"button",onClick:r,className:"text-[10px] text-fg-faint hover:text-fg-dim",title:"Back to queue",children:"← queue"}),s.jsx("span",{className:"text-[11px] font-medium text-fg-dim",children:"Supervisor"}),s.jsx("button",{type:"button",onClick:()=>window.api.supervisor.getLog().then(o).catch(()=>{}),className:"ml-auto text-[10px] text-fg-faint hover:text-fg-dim underline",title:"Refresh log",children:"refresh"})]}),s.jsxs("div",{className:"px-3 py-2 space-y-1.5 border-b border-line",children:[s.jsx("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider",children:"Config"}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap text-[10px] text-fg-faint",children:[s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:u.enabled,onChange:h=>n({enabled:h.target.checked}),className:"cursor-pointer"}),s.jsx("span",{children:"enabled"})]}),s.jsxs("label",{className:"flex items-center gap-1",title:"How often to check for wedged jobs (minutes)",children:[s.jsx("span",{children:"interval"}),s.jsx("input",{type:"number",min:5,max:60,value:u.intervalMinutes,onChange:h=>n({intervalMinutes:Number(h.target.value)}),className:"w-10 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),s.jsx("span",{children:"min"})]}),s.jsxs("label",{className:"flex items-center gap-1",title:"Max concurrent Opus probes per tick",children:[s.jsx("span",{children:"probes"}),s.jsx("input",{type:"number",min:1,max:5,value:u.maxConcurrentProbes,onChange:h=>n({maxConcurrentProbes:Number(h.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"})]}),s.jsxs("label",{className:"flex items-center gap-1",title:"Probe a job only if no JSONL event in this many minutes",children:[s.jsx("span",{children:"stale"}),s.jsx("input",{type:"number",min:5,max:30,value:u.probeStaleThresholdMinutes,onChange:h=>n({probeStaleThresholdMinutes:Number(h.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),s.jsx("span",{children:"min"})]})]})]}),s.jsxs("div",{className:"px-3 py-2",children:[s.jsxs("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider mb-1",children:["Recent probes (last ",i.length,")"]}),i.length===0?s.jsx("div",{className:"text-[10px] text-fg-faint italic",children:"No probes yet."}):s.jsx("div",{className:"space-y-0.5 max-h-64 overflow-y-auto",children:i.map((h,m)=>s.jsx(H9,{entry:h,now:l},`${h.ts}-${m}`))})]})]})}function H9({entry:e,now:n}){const r=e.action!=="none",i=Uo(n-e.ts);return s.jsxs("div",{className:`text-[10px] px-1.5 py-1 rounded font-mono ${r?"bg-red-500/10 border border-red-500/20":"bg-bg/40"}`,title:e.reason,children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsxs("span",{className:"text-fg-faint shrink-0",children:[i," ago"]}),s.jsx("span",{className:`shrink-0 px-1 rounded ${e.verdict==="stuck"?"text-red-400 bg-red-500/10":"text-green-500/70"}`,children:e.verdict}),s.jsx("span",{className:"truncate text-fg-dim",children:e.jobSlug}),r&&s.jsxs("span",{className:"shrink-0 text-red-400",children:[e.action,e.targetPid?` pid=${e.targetPid}`:""]}),e.costUsd!==null&&s.jsxs("span",{className:"shrink-0 text-fg-faint",children:["$",e.costUsd.toFixed(3)]})]}),s.jsx("div",{className:"text-fg-faint truncate mt-0.5",children:e.reason})]})}function W9({health:e,now:n,showHealth:r,setShowHealth:i}){if(!e)return null;const o=e.consecutiveFailures>0||e.pauseReason!==null;return s.jsxs("div",{className:"text-[9px] text-fg-faint border-t border-line pt-1",children:[s.jsxs("button",{type:"button",onClick:()=>i(!r),className:`flex items-center gap-1 hover:text-fg-dim w-full text-left ${o?"text-amber-400":""}`,title:"Scheduler diagnostic info",children:[s.jsx("span",{children:r?"▾":"▸"}),s.jsx("span",{children:o?e.consecutiveFailures>0?`scheduler health · ${e.consecutiveFailures} failure${e.consecutiveFailures!==1?"s":""}`:"scheduler health · paused":"scheduler health"})]}),r&&s.jsxs("div",{className:"mt-1 space-y-0.5 font-mono pl-2",children:[s.jsxs("div",{children:["booted: ",Yh(e.bootedAt,n)]}),s.jsxs("div",{children:["last poll: ",Yh(e.lastPollAt,n)," · ",e.lastPollOk?"ok":"failed"]}),e.consecutiveFailures>0&&s.jsxs("div",{className:"text-amber-400",children:["failures: ",e.consecutiveFailures]}),e.backoffNextAt!==null&&e.backoffNextAt>n&&s.jsxs("div",{children:["retry in: ",Uo(e.backoffNextAt-n)]}),e.nextResetCached&&s.jsxs("div",{children:["cached reset: ",Wh(Date.parse(e.nextResetCached))]}),e.runningJobs.length>0&&s.jsxs("div",{children:["running: ",e.runningJobs.map(l=>`${l.slug}(pid ${l.pid})`).join(", ")]})]})]})}function q9({snap:e}){const[n,r]=L.useState(null),[i,o]=L.useState(!1),[l,d]=L.useState(!1),u=`${e.jobs.length}:${e.lastRunAt??""}`;if(L.useEffect(()=>{let S=!0;return o(!0),qw().then(E=>{if(!S)return;r(E),E.reports.some(y=>y.findings.some(b=>b.severity==="error"))&&d(!0)}).catch(()=>{}).finally(()=>{S&&o(!1)}),()=>{S=!1}},[u]),!n)return s.jsx("div",{className:"text-[9px] text-fg-faint border-t border-line pt-1",children:i?"queue health · scanning…":"queue health · idle"});let h=0,m=0;const x=n.reports.filter(S=>S.findings.length>0);for(const S of x)for(const E of S.findings)E.severity==="error"?h++:m++;const g=h===0&&m===0,v=h>0?"text-red-400":m>0?"text-amber-400":"";return s.jsxs("div",{className:"text-[9px] text-fg-faint border-t border-line pt-1",children:[s.jsxs("div",{className:`flex items-center gap-1 w-full ${v}`,children:[s.jsxs("button",{type:"button",onClick:()=>d(S=>!S),className:"flex items-center gap-1 hover:text-fg-dim flex-1 text-left",title:"Static lint of queued PRDs for unbounded loops, missing frontmatter, etc.","aria-expanded":l,children:[s.jsx("span",{children:l?"▾":"▸"}),s.jsx("span",{children:g?`queue health · all clear (${n.reports.length} scanned)`:`queue health · ${h} error${h===1?"":"s"}${m>0?`, ${m} warn${m===1?"":"s"}`:""}`})]}),s.jsx("button",{type:"button",onClick:()=>{o(!0),qw({fresh:!0}).then(r).catch(()=>{}).finally(()=>o(!1))},className:"ml-auto text-fg-faint hover:text-fg-dim underline",title:"Re-run the lint now",children:i?"…":"rerun"})]}),l&&!g&&s.jsx("div",{className:"mt-1 space-y-1 max-h-48 overflow-y-auto pl-2",children:x.map(S=>s.jsxs("div",{className:"font-mono",children:[s.jsx("div",{className:"text-fg-dim truncate",title:S.slug,children:S.slug}),S.findings.map((E,j)=>s.jsxs("div",{className:`pl-3 truncate ${E.severity==="error"?"text-red-400/80":"text-amber-400/70"}`,title:E.snippet,children:[E.severity==="error"?"✗":"⚠"," L",E.line,": ",E.snippet]},`${S.slug}-${j}`))]},S.slug))}),l&&g&&s.jsxs("div",{className:"mt-1 pl-2 text-green-400/70 font-mono",children:["✓ no issues in ",n.reports.length," PRD",n.reports.length!==1?"s":""]})]})}const V9=new Set(["title","cwd","estimateMinutes","parallelGroup","sourcePromptId"]),G9=["title","cwd","estimateMinutes","parallelGroup","sourcePromptId"],K9=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function d2(e){let n=0;for(const r of e)if(r===" ")n++;else if(r===" ")n+=2;else break;return n}function lN(e){const n=e.trim();return n===""||n==="~"||n==="null"?null:n==="true"?!0:n==="false"?!1:/^-?\d+$/.test(n)||/^-?\d+\.\d+$/.test(n)?Number(n):n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n}function Lh(e){const n=e.match(K9);if(!n)return{frontmatter:{},body:e};const r=n[1],i=n[2]??"",o=r.split(/\r?\n/),l={},d={};for(let u=0;u<o.length;){const h=o[u];if(!h.trim()||h.trimStart().startsWith("#")){u++;continue}if(d2(h)!==0){u++;continue}const x=h.indexOf(":");if(x<0){u++;continue}const g=h.slice(0,x).trim(),v=h.slice(x+1);let S=u+1;const E=[h];for(;S<o.length;){const j=o[S];if(j.trim()===""||j.trimStart().startsWith("#")){E.push(j),S++;continue}if(d2(j)===0&&j.indexOf(":")>=0)break;E.push(j),S++}if(V9.has(g)){X9(l,g,v);const j=lN(v);j!==null&&(typeof j=="string"||typeof j=="number")&&(l._raw||(l._raw={}),l._raw[g]={line:h,parsed:j})}else d[g]={lines:E};u=S}return Object.keys(d).length&&(l.extras=d),{frontmatter:l,body:i}}function X9(e,n,r){const i=lN(r);if(i!==null)switch(n){case"estimateMinutes":e.estimateMinutes=typeof i=="number"?i:Number(i);return;case"parallelGroup":e.parallelGroup=typeof i=="number"?i:Number(i);return;case"title":e.title=String(i);return;case"cwd":e.cwd=String(i);return;case"sourcePromptId":e.sourcePromptId=String(i);return}}function Y9(e){if(e==null)return"";if(typeof e=="boolean"||typeof e=="number")return String(e);const n=String(e);return n===""||/^(true|false|null|~)$/.test(n)||/^-?\d+(\.\d+)?$/.test(n)||/^\s|\s$/.test(n)||n.startsWith("'")||n.startsWith('"')||n.includes(`
|
|
3491
|
+
`)[0],wrap:!0})]}),s.jsxs(gc,{label:"Timing",children:[s.jsx(ss,{k:"started",v:e.startedAt?Wh(Date.parse(e.startedAt)):"—"}),s.jsx(ss,{k:"finished",v:e.finishedAt?Wh(Date.parse(e.finishedAt)):"—"}),s.jsx(ss,{k:"duration",v:e.startedAt&&e.finishedAt?Um(Date.parse(e.finishedAt)-Date.parse(e.startedAt)):x&&e.startedAt?ky(r-Date.parse(e.startedAt)):"—"})]}),s.jsxs(gc,{label:"Location",children:[s.jsx(ss,{k:"group",v:`${e.parallelGroup} · ${e.slug}`}),s.jsx(ss,{k:"cwd",v:e.cwd??"—",wrap:!0})]}),s.jsx(gc,{label:"Actions",children:s.jsxs("div",{className:"flex flex-col gap-1.5 items-start",children:[e.runId&&s.jsx("button",{type:"button",onClick:()=>m(!0),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"view log →"}),e.status!=="pending"&&e.status!=="running"&&s.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(e.slug),className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:"reset to pending →"})]})})]}),h&&e.runId&&s.jsx(sN,{runId:e.runId,slug:e.slug,title:e.title||e.slug,onClose:()=>m(!1)})]})}function F9({filter:e,onChange:n}){const r=[{label:"All",value:"all"},{label:"Running",value:"running"},{label:"Pending",value:"pending"},{label:"Completed",value:"completed"},{label:"Needs review",value:"needs_review"},{label:"Failed",value:"failed"}];return s.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[s.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-[320px]",children:[s.jsx("span",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 text-fg-faint inline-flex","aria-hidden":"true",children:s.jsx(dn,{name:"search",size:15})}),s.jsx("input",{type:"text",value:e.text,onChange:i=>n({...e,text:i.target.value}),placeholder:"filter jobs…",className:"w-full bg-bg-hi border border-line rounded-xl py-2 pl-9 pr-3 text-[13.5px] text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint","aria-label":"Filter jobs by title, slug, or project"})]}),s.jsx(iN,{options:r,value:e.status,onChange:i=>n({...e,status:i})})]})}function U9({supervisorConfig:e,onSetConfig:n,onBack:r}){const[i,o]=L.useState([]),[l,d]=L.useState(()=>Date.now());L.useEffect(()=>{window.api.supervisor.getLog().then(o).catch(()=>{});const h=setInterval(()=>d(Date.now()),5e3);return()=>clearInterval(h)},[]);const u={enabled:(e==null?void 0:e.enabled)??!0,intervalMinutes:(e==null?void 0:e.intervalMinutes)??15,maxConcurrentProbes:(e==null?void 0:e.maxConcurrentProbes)??2,probeStaleThresholdMinutes:(e==null?void 0:e.probeStaleThresholdMinutes)??10};return s.jsxs("div",{className:"bg-bg-elev/60",children:[s.jsxs("div",{className:"px-3 py-2 flex items-center gap-2 border-b border-line",children:[s.jsx("button",{type:"button",onClick:r,className:"text-[10px] text-fg-faint hover:text-fg-dim",title:"Back to queue",children:"← queue"}),s.jsx("span",{className:"text-[11px] font-medium text-fg-dim",children:"Supervisor"}),s.jsx("button",{type:"button",onClick:()=>window.api.supervisor.getLog().then(o).catch(()=>{}),className:"ml-auto text-[10px] text-fg-faint hover:text-fg-dim underline",title:"Refresh log",children:"refresh"})]}),s.jsxs("div",{className:"px-3 py-2 space-y-1.5 border-b border-line",children:[s.jsx("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider",children:"Config"}),s.jsxs("div",{className:"flex items-center gap-3 flex-wrap text-[10px] text-fg-faint",children:[s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:u.enabled,onChange:h=>n({enabled:h.target.checked}),className:"cursor-pointer"}),s.jsx("span",{children:"enabled"})]}),s.jsxs("label",{className:"flex items-center gap-1",title:"How often to check for wedged jobs (minutes)",children:[s.jsx("span",{children:"interval"}),s.jsx("input",{type:"number",min:5,max:60,value:u.intervalMinutes,onChange:h=>n({intervalMinutes:Number(h.target.value)}),className:"w-10 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),s.jsx("span",{children:"min"})]}),s.jsxs("label",{className:"flex items-center gap-1",title:"Max concurrent Opus probes per tick",children:[s.jsx("span",{children:"probes"}),s.jsx("input",{type:"number",min:1,max:5,value:u.maxConcurrentProbes,onChange:h=>n({maxConcurrentProbes:Number(h.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"})]}),s.jsxs("label",{className:"flex items-center gap-1",title:"Probe a job only if no JSONL event in this many minutes",children:[s.jsx("span",{children:"stale"}),s.jsx("input",{type:"number",min:5,max:30,value:u.probeStaleThresholdMinutes,onChange:h=>n({probeStaleThresholdMinutes:Number(h.target.value)}),className:"w-8 bg-bg border border-line rounded px-1 py-0.5 font-mono"}),s.jsx("span",{children:"min"})]})]})]}),s.jsxs("div",{className:"px-3 py-2",children:[s.jsxs("div",{className:"text-[9px] text-fg-faint uppercase tracking-wider mb-1",children:["Recent probes (last ",i.length,")"]}),i.length===0?s.jsx("div",{className:"text-[10px] text-fg-faint italic",children:"No probes yet."}):s.jsx("div",{className:"space-y-0.5 max-h-64 overflow-y-auto",children:i.map((h,m)=>s.jsx(H9,{entry:h,now:l},`${h.ts}-${m}`))})]})]})}function H9({entry:e,now:n}){const r=e.action!=="none",i=Uo(n-e.ts);return s.jsxs("div",{className:`text-[10px] px-1.5 py-1 rounded font-mono ${r?"bg-red-500/10 border border-red-500/20":"bg-bg/40"}`,title:e.reason,children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsxs("span",{className:"text-fg-faint shrink-0",children:[i," ago"]}),s.jsx("span",{className:`shrink-0 px-1 rounded ${e.verdict==="stuck"?"text-red-400 bg-red-500/10":"text-green-500/70"}`,children:e.verdict}),s.jsx("span",{className:"truncate text-fg-dim",children:e.jobSlug}),r&&s.jsxs("span",{className:"shrink-0 text-red-400",children:[e.action,e.targetPid?` pid=${e.targetPid}`:""]}),e.costUsd!==null&&s.jsxs("span",{className:"shrink-0 text-fg-faint",children:["$",e.costUsd.toFixed(3)]})]}),s.jsx("div",{className:"text-fg-faint truncate mt-0.5",children:e.reason})]})}function W9({health:e,now:n,showHealth:r,setShowHealth:i}){if(!e)return null;const o=e.consecutiveFailures>0||e.pauseReason!==null;return s.jsxs("div",{className:"text-[9px] text-fg-faint border-t border-line pt-1",children:[s.jsxs("button",{type:"button",onClick:()=>i(!r),className:`flex items-center gap-1 hover:text-fg-dim w-full text-left ${o?"text-amber-400":""}`,title:"Scheduler diagnostic info",children:[s.jsx("span",{children:r?"▾":"▸"}),s.jsx("span",{children:o?e.consecutiveFailures>0?`scheduler health · ${e.consecutiveFailures} failure${e.consecutiveFailures!==1?"s":""}`:"scheduler health · paused":"scheduler health"})]}),r&&s.jsxs("div",{className:"mt-1 space-y-0.5 font-mono pl-2",children:[s.jsxs("div",{children:["booted: ",Yh(e.bootedAt,n)]}),s.jsxs("div",{children:["last poll: ",Yh(e.lastPollAt,n)," · ",e.lastPollOk?"ok":"failed"]}),e.consecutiveFailures>0&&s.jsxs("div",{className:"text-amber-400",children:["failures: ",e.consecutiveFailures]}),e.backoffNextAt!==null&&e.backoffNextAt>n&&s.jsxs("div",{children:["retry in: ",Uo(e.backoffNextAt-n)]}),e.nextResetCached&&s.jsxs("div",{children:["cached reset: ",Wh(Date.parse(e.nextResetCached))]}),e.runningJobs.length>0&&s.jsxs("div",{children:["running: ",e.runningJobs.map(l=>`${l.slug}(pid ${l.pid})`).join(", ")]})]})]})}function q9({snap:e}){const[n,r]=L.useState(null),[i,o]=L.useState(!1),[l,d]=L.useState(!1),u=`${e.jobs.length}:${e.lastRunAt??""}`;if(L.useEffect(()=>{let S=!0;return o(!0),qw().then(E=>{if(!S)return;r(E),E.reports.some(y=>y.findings.some(b=>b.severity==="error"))&&d(!0)}).catch(()=>{}).finally(()=>{S&&o(!1)}),()=>{S=!1}},[u]),!n)return s.jsx("div",{className:"text-[9px] text-fg-faint border-t border-line pt-1",children:i?"queue health · scanning…":"queue health · idle"});let h=0,m=0;const x=n.reports.filter(S=>S.findings.length>0);for(const S of x)for(const E of S.findings)E.severity==="error"?h++:m++;const g=h===0&&m===0,v=h>0?"text-red-400":m>0?"text-amber-400":"";return s.jsxs("div",{className:"text-[9px] text-fg-faint border-t border-line pt-1",children:[s.jsxs("div",{className:`flex items-center gap-1 w-full ${v}`,children:[s.jsxs("button",{type:"button",onClick:()=>d(S=>!S),className:"flex items-center gap-1 hover:text-fg-dim flex-1 text-left",title:"Static lint of queued PRDs for unbounded loops, missing frontmatter, etc.","aria-expanded":l,children:[s.jsx("span",{children:l?"▾":"▸"}),s.jsx("span",{children:g?`queue health · all clear (${n.reports.length} scanned)`:`queue health · ${h} error${h===1?"":"s"}${m>0?`, ${m} warn${m===1?"":"s"}`:""}`})]}),s.jsx("button",{type:"button",onClick:()=>{o(!0),qw({fresh:!0}).then(r).catch(()=>{}).finally(()=>o(!1))},className:"ml-auto text-fg-faint hover:text-fg-dim underline",title:"Re-run the lint now",children:i?"…":"rerun"})]}),l&&!g&&s.jsx("div",{className:"mt-1 space-y-1 max-h-48 overflow-y-auto pl-2",children:x.map(S=>s.jsxs("div",{className:"font-mono",children:[s.jsx("div",{className:"text-fg-dim truncate",title:S.slug,children:S.slug}),S.findings.map((E,j)=>s.jsxs("div",{className:`pl-3 truncate ${E.severity==="error"?"text-red-400/80":"text-amber-400/70"}`,title:E.snippet,children:[E.severity==="error"?"✗":"⚠"," L",E.line,": ",E.snippet]},`${S.slug}-${j}`))]},S.slug))}),l&&g&&s.jsxs("div",{className:"mt-1 pl-2 text-green-400/70 font-mono",children:["✓ no issues in ",n.reports.length," PRD",n.reports.length!==1?"s":""]})]})}const V9=new Set(["title","cwd","estimateMinutes","parallelGroup","sourcePromptId","sourceTabId"]),G9=["title","cwd","estimateMinutes","parallelGroup","sourcePromptId","sourceTabId"],K9=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function d2(e){let n=0;for(const r of e)if(r===" ")n++;else if(r===" ")n+=2;else break;return n}function lN(e){const n=e.trim();return n===""||n==="~"||n==="null"?null:n==="true"?!0:n==="false"?!1:/^-?\d+$/.test(n)||/^-?\d+\.\d+$/.test(n)?Number(n):n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n}function Lh(e){const n=e.match(K9);if(!n)return{frontmatter:{},body:e};const r=n[1],i=n[2]??"",o=r.split(/\r?\n/),l={},d={};for(let u=0;u<o.length;){const h=o[u];if(!h.trim()||h.trimStart().startsWith("#")){u++;continue}if(d2(h)!==0){u++;continue}const x=h.indexOf(":");if(x<0){u++;continue}const g=h.slice(0,x).trim(),v=h.slice(x+1);let S=u+1;const E=[h];for(;S<o.length;){const j=o[S];if(j.trim()===""||j.trimStart().startsWith("#")){E.push(j),S++;continue}if(d2(j)===0&&j.indexOf(":")>=0)break;E.push(j),S++}if(V9.has(g)){X9(l,g,v);const j=lN(v);j!==null&&(typeof j=="string"||typeof j=="number")&&(l._raw||(l._raw={}),l._raw[g]={line:h,parsed:j})}else d[g]={lines:E};u=S}return Object.keys(d).length&&(l.extras=d),{frontmatter:l,body:i}}function X9(e,n,r){const i=lN(r);if(i!==null)switch(n){case"estimateMinutes":e.estimateMinutes=typeof i=="number"?i:Number(i);return;case"parallelGroup":e.parallelGroup=typeof i=="number"?i:Number(i);return;case"title":e.title=String(i);return;case"cwd":e.cwd=String(i);return;case"sourcePromptId":e.sourcePromptId=String(i);return;case"sourceTabId":e.sourceTabId=String(i);return}}function Y9(e){if(e==null)return"";if(typeof e=="boolean"||typeof e=="number")return String(e);const n=String(e);return n===""||/^(true|false|null|~)$/.test(n)||/^-?\d+(\.\d+)?$/.test(n)||/^\s|\s$/.test(n)||n.startsWith("'")||n.startsWith('"')||n.includes(`
|
|
3492
3492
|
`)?n.includes("'")?`"${n.replace(/"/g,'\\"')}"`:`'${n}'`:n}function qx(e,n){var o;const r=[];for(const l of G9){const d=e[l];if(d==null||d==="")continue;const u=(o=e._raw)==null?void 0:o[l];if(u&&u.parsed===d){r.push(u.line);continue}if(typeof d=="number"){r.push(`${l}: ${d}`);continue}r.push(`${l}: ${Y9(d)}`)}if(e.extras)for(const l of Object.keys(e.extras)){const d=e.extras[l];!d||!d.lines.length||r.push(d.lines.join(`
|
|
3493
3493
|
`))}return`---
|
|
3494
3494
|
${r.join(`
|