livedesk 0.1.488 → 0.1.490
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/client/bin/livedesk-client.js +119 -44
- package/client/package.json +1 -1
- package/client/src/runtime/fast-runtime-repair.js +300 -0
- package/hub/package.json +32 -32
- package/hub/src/remote-hub.js +728 -722
- package/hub/src/settings/settings-schema.js +251 -239
- package/hub/src/settings/settings-store.js +82 -77
- package/hub/src/transport/secure-direct-acceptor.js +1 -1
- package/package.json +2 -2
- package/web/dist/assets/{index-KNTHLeo-.js → index-BRPz6Wux.js} +1 -1
- package/web/dist/index.html +1 -1
- package/web/dist/livedesk-build-evidence.json +7 -7
|
@@ -170,7 +170,7 @@ registerProcessor(
|
|
|
170
170
|
LiveDeskRemoteAudioProcessor
|
|
171
171
|
);
|
|
172
172
|
`,Zb="livedesk_remote_host_targets",m1="livedesk_entitlements",Jb=4e3,p1=2500,Lv=new TextDecoder,ov=new Set;function h1(){const t=[...ov].map(r=>r()),n=r=>t.reduce((i,l)=>i+Number(l[r]||0),0);return{ownerCount:t.length,activeOwnerCount:t.filter(r=>r.active).length,socketCount:n("socketCount"),openSocketCount:n("openSocketCount"),connectingSocketCount:n("connectingSocketCount"),closingSocketCount:n("closingSocketCount"),closingSocketTimerCount:n("closingSocketTimerCount"),closingSocketTimeoutCount:n("closingSocketTimeoutCount"),expectedBindingCount:n("expectedBindingCount"),reconnectTimerCount:n("reconnectTimerCount"),statsTimerCount:n("statsTimerCount"),configurationRefreshTimerCount:n("configurationRefreshTimerCount"),restartTokenCount:n("restartTokenCount"),retainedFrameCount:n("retainedFrameCount"),retainedPayloadBytes:n("retainedPayloadBytes"),owners:t}}function g1(){return ha.snapshot()}function v1(t){const r=(Array.isArray(t)?t:[t||Dn]).map(i=>ho(i||Dn));return[...new Set(r.filter(Boolean))]}function y1(){const[t,n]=d.useState(null),[r,i]=d.useState(!0);return d.useEffect(()=>{let l=!0;const u=window.liveDesk?.auth?.onComplete?.(h=>{h.ok&&h.session&&Pt.auth.setSession(h.session)});(window.liveDesk?.auth?.getSession?.()||Pt.auth.getSession()).then(h=>{l&&(n(qx(h)),i(!1))});const{data:{subscription:f}}=Pt.auth.onAuthStateChange((h,g)=>{n(g),i(!1),window.liveDesk?.auth?.persistSession?.(g)});return()=>{l=!1,u?.(),f.unsubscribe()}},[]),{session:t,loading:r}}function b1(t,n=!0){const[r,i]=d.useState(null),[l,u]=d.useState([]),[f,h]=d.useState(""),[g,y]=d.useState(""),w=d.useRef(new Map),b=d.useRef(null),x=Array.isArray(t)?t.join(`
|
|
173
|
-
`):String(t||""),M=d.useMemo(()=>v1(t),[x]),k=d.useMemo(()=>M.find(I=>hd(I)==="loopback")||M[0]||Dn,[M]),N=d.useCallback(async I=>{if(!n){i(null),u([]),y(""),h("");return}let T=null;const P=Date.now(),U=M.filter(F=>(w.current.get(F)||0)<=P);if(U.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const F of U)try{const[Y,D]=await Promise.all([tt("/api/remote/status",{signal:I,timeoutMs:Jb},F),tt("/api/remote/devices",{signal:I,timeoutMs:Jb},F)]);if(I?.aborted)throw I.reason||new Error("LiveDesk Hub snapshot cancelled.");if(!Array.isArray(D.devices))throw new Error("Invalid Hub devices response.");w.current.delete(F),i(Y),u(D.devices),y(F),h("");return}catch(Y){if(I?.aborted)throw Y;T=Y,w.current.set(F,Date.now()+1e4)}throw y(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[n,M]),E=d.useCallback(()=>{w.current.clear(),Op(b,()=>N()).catch(I=>{h(I instanceof Error?I.message:String(I))})},[N]);return d.useEffect(()=>{if(!n){i(null),u([]),y(""),h("");return}let I=!0,T=null;const P=new AbortController,U=()=>{Op(b,()=>N(P.signal)).catch(Y=>{I&&!P.signal.aborted&&h(Y instanceof Error?Y.message:String(Y))}).finally(()=>{I&&!P.signal.aborted&&(T=window.setTimeout(U,p1))})};return U(),()=>{I=!1,P.abort(new Error("LiveDesk Hub snapshot polling stopped.")),T!==null&&window.clearTimeout(T)}},[n,N]),{status:r,devices:l,error:f,refresh:E,hubBaseUrl:g||k,hubCandidates:M}}function w1(t){const[n,r]=d.useState(null),[i,l]=d.useState(""),u=t?.user?.id||"",f=d.useCallback(async()=>{if(!u){r(null);return}const{data:h,error:g}=await Pt.from(Zb).select("*").eq("user_id",u).maybeSingle();if(g){l(g.message);return}r(h),l("")},[u]);return d.useEffect(()=>{f()},[f]),d.useEffect(()=>{if(!u)return;const h=Pt.channel(`livedesk-remote-host-targets-${u.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:Zb,filter:`user_id=eq.${u}`},g=>r(g.new)).subscribe();return()=>{Pt.removeChannel(h)}},[u]),{target:n,error:i,refresh:f}}function x1(t){const[n,r]=d.useState(null),[i,l]=d.useState(!1),[u,f]=d.useState(""),h=t?.user?.id||"",g=d.useCallback(async()=>{if(!h){r(null),f(""),l(!1);return}l(!0);const{data:w,error:b}=await Pt.from(m1).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){f(b.message),l(!1);return}r(w),f(""),l(!1)},[h]);d.useEffect(()=>{g()},[g]);const y=d.useMemo(()=>!n||n.status!=="active"?!1:n.expires_at?new Date(n.expires_at).getTime()>Date.now():!0,[n]);return{entitlement:n,licensed:y,loading:i,error:u,refresh:g}}const Vf={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},S1=2500,C1=3e4,k1=64*1024,M1=64*1024,A1=64,gg=1500,N1=150,T1=1e3,R1=6,j1=R1,CS=new Map;function E1(t){return CS.get(t)}const ew={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function D1(t,n,r){const i=Number(n);if(!Number.isFinite(i)||i<=0)return 0;const l=r-i,u=t.minimumHubClockOffsetMs;if(!Number.isFinite(u)||l<Number(u))return t.minimumHubClockOffsetMs=l,0;const f=Math.max(0,l-Number(u));return f>C1?(t.minimumHubClockOffsetMs=l,0):f}function ht(t){if(t==null||t==="")return;const n=Number(t);return Number.isFinite(n)?n:void 0}const I1=["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"];function L1(t){return Number(t.nativeCaptureTelemetryVersion)>=5&&I1.every(n=>ht(t[n])!==void 0)&&typeof t.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t.nativeCopyTelemetryAvailable===!0}function _1(t,n,r){if(!t||typeof t!="object")return null;const i=t,l=String(i.deviceId||n||"").trim(),u=String(i.sessionId||"").trim(),f=String(i.streamId||"").trim(),h=i.streamPurpose==="control"?"control":i.streamPurpose==="wall"?"wall":null,g=String(i.commandId||"").trim(),y=Number(i.captureGeneration||0),w=Number(i.monitorIndex??-1);return!l||l!==n||!h||h!==r||!u||!f||!g||!Number.isSafeInteger(y)||y<=0||!Number.isSafeInteger(w)||w<0?null:{deviceId:l,sessionId:u,streamId:f,streamPurpose:h,commandId:g,captureGeneration:y,monitorIndex:w}}function tw(t,n,r=Dn,i={}){const[l,u]=d.useState(new Map),[f,h]=d.useState("idle"),[g,y]=d.useState(""),[w,b]=d.useState(Vf),x=d.useRef(new Map),M=d.useRef(new Map),k=d.useRef(new Map),N=d.useRef(null);N.current===null&&(N.current=HA());const E=d.useRef(0),I=d.useRef(new Map),T=d.useRef({enabled:!1,token:"",reason:""}),P=d.useRef(new Map),U=d.useRef(null),F=d.useRef(null),[Y,D]=d.useState(0),K=d.useRef(i.onFrame),ne=d.useRef(i.onStreamReady),q=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),O=d.useMemo(()=>[...t].sort().join(","),[t]),W=n&&O.length>0,ce=d.useRef(!1);d.useLayoutEffect(()=>(ce.current=W,()=>{ce.current=!1}),[W]);const $=Number.isFinite(i.fps)?Number(i.fps):2,ee=Number.isFinite(i.maxWidth)?Number(i.maxWidth):640,B=Number.isFinite(i.maxHeight)?Number(i.maxHeight):360,L=Number.isFinite(i.quality)?Number(i.quality):45,oe=Number.isFinite(i.configurationRefreshMs)?Math.max(0,Math.round(Number(i.configurationRefreshMs))):0,be=String(i.frameMode||i.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",H=i.streamPurpose==="control"?"control":"wall",me=i.forceRestart===!0,ue=String(i.forceRestartToken||"").trim(),Ce=String(i.restartReason||"").trim();T.current={enabled:me,token:ue,reason:Ce};const Me=d.useMemo(()=>{const he=Object.entries(i.monitorSelections||{}).filter(([pe])=>!!pe).sort(([pe],[Ae])=>pe.localeCompare(Ae));return JSON.stringify(Object.fromEntries(he))},[i.monitorSelections]),Ne=d.useMemo(()=>{const he=Object.entries(i.connectionSessionIds||{}).filter(([pe])=>!!pe).map(([pe,Ae])=>[pe,String(Ae||"").trim()]).sort(([pe],[Ae])=>pe.localeCompare(Ae));return JSON.stringify(Object.fromEntries(he))},[i.connectionSessionIds]);d.useEffect(()=>{K.current=i.onFrame},[i.onFrame]),d.useEffect(()=>{ne.current=i.onStreamReady},[i.onStreamReady]);const He=d.useCallback((he,pe="livedesk-frame-socket-release")=>{BA(he,pe,N.current)},[]),Ve=d.useCallback(he=>{const pe=P.current.get(he);pe!==void 0&&(window.clearTimeout(pe),P.current.delete(he))},[]),ie=d.useCallback((he,pe=!0)=>{for(const Ae of P.current.values())window.clearTimeout(Ae);P.current.clear();for(const Ae of k.current.values())Ae.expectedBinding=void 0,He(Ae,he);k.current.clear(),I.current.clear(),x.current=new Map,M.current.clear(),q.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},pe&&(u(new Map),y(""),b(Vf),h("idle"))},[He]),Oe=d.useCallback(()=>{const he=[...k.current.values()].map(pe=>pe.socket);if(he.length===0){h("idle");return}if(he.some(pe=>pe.readyState===WebSocket.OPEN)){h("open");return}if(he.some(pe=>pe.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),$e=d.useCallback((he,pe,Ae,Se)=>{if(pe.disposed||pe.socket.readyState!==WebSocket.OPEN)return!1;try{return pe.socket.send(JSON.stringify({...pe.payload,type:"restart-live",deviceIds:[he],forceRestart:!0,restartReason:Ae,restartToken:Se})),pe.expectedBinding=void 0,Qb(pe.sparseTelemetry),!0}catch{return!1}},[]),qe=d.useCallback((he,pe)=>{if(!ce.current||pe.disposed||!he||he.byteLength<5)return;const Ae=Date.now(),Pe=new DataView(he).getUint32(0,!1);if(Pe<=0||Pe+4>he.byteLength)return;const Qe=new Uint8Array(he,4,Pe),Z=JSON.parse(Lv.decode(Qe));WA(Z,pe.sparseTelemetry,pe.expectedBinding);const $t=ht(Z.hubPacketEpochMs),Ee=$t!==void 0&&$t>0?$t:void 0,Ge=D1(pe,Ee,Ae);if(Ge>S1)return;const ze=new Uint8Array(he,4+Pe),Ft=ht(Z.nativeCaptureTelemetryVersion),Ze=ht(Z.nativeCaptureTelemetryAgeMs),nt=ht(Z.hubClientDropped),lt=ht(Z.hubClientQueueDepth),Tt=ht(Z.hubClientQueueLimit),Mt=ht(Z.hubClientBufferedBytes),rt=nt!==void 0&<!==void 0&&Tt!==void 0&&Mt!==void 0,dt={deviceId:String(Z.deviceId||""),kind:Z.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(Z.frameSeq||0),streamFrameSeq:Number(Z.streamFrameSeq||0)||void 0,streamId:String(Z.streamId||""),commandId:Z.commandId?String(Z.commandId):void 0,sessionId:Z.sessionId?String(Z.sessionId):void 0,captureGeneration:Number(Z.captureGeneration||0)||void 0,currentGenerationVerified:!1,streamPurpose:Z.streamPurpose?String(Z.streamPurpose):void 0,width:Number(Z.width||0),height:Number(Z.height||0),sourceWidth:Number(Z.sourceWidth||0)||void 0,sourceHeight:Number(Z.sourceHeight||0)||void 0,mimeType:String(Z.mimeType||"image/jpeg"),mode:Z.mode?String(Z.mode):void 0,frameMode:Z.frameMode?String(Z.frameMode):void 0,frameProfile:Z.frameProfile?String(Z.frameProfile):void 0,encoding:Z.encoding?String(Z.encoding):void 0,codec:Z.codec?String(Z.codec):void 0,compression:Z.compression?String(Z.compression):void 0,pixelFormat:Z.pixelFormat?String(Z.pixelFormat):void 0,bytesPerPixel:Number(Z.bytesPerPixel||0)||0,uncompressedByteLength:Number(Z.uncompressedByteLength||0)||0,h264Format:Z.h264Format?String(Z.h264Format):void 0,isKeyFrame:Z.isKeyFrame===!0,chunkType:Z.chunkType?String(Z.chunkType):void 0,timestampUs:Number(Z.timestampUs||0)||0,durationUs:Number(Z.durationUs||0)||0,sourceGapMs:Number(Z.sourceGapMs||0)||0,agentSendGapMs:Number(Z.agentSendGapMs||0)||0,agentSendDurationMs:Number(Z.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(Z.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(Z.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(Z.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(Z.agentFrameAgeMs||0)||0,inputFeedbackEventId:Z.inputFeedbackEventId?String(Z.inputFeedbackEventId):void 0,inputFeedbackInputSeq:ht(Z.inputFeedbackInputSeq),inputFeedbackInputType:Z.inputFeedbackInputType?String(Z.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:ht(Z.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:ht(Z.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:ht(Z.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:ht(Z.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:ht(Z.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:ht(Z.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:ht(Z.inputFeedbackApplyToCaptureMs),inputFeedbackCaptureTimestampAvailable:typeof Z.inputFeedbackCaptureTimestampAvailable=="boolean"?Z.inputFeedbackCaptureTimestampAvailable:void 0,nativeCaptureTelemetryAvailable:typeof Z.nativeCaptureTelemetryAvailable=="boolean"?Z.nativeCaptureTelemetryAvailable:void 0,nativeCaptureTelemetryVersion:Ft===void 0?void 0:Math.max(0,Ft),nativeCaptureTelemetryAgeMs:Ze===void 0?void 0:Math.max(0,Ze),nativeEncoderHardwareAccelerationKnown:typeof Z.nativeEncoderHardwareAccelerationKnown=="boolean"?Z.nativeEncoderHardwareAccelerationKnown:void 0,nativeEncoderHardwareAccelerated:typeof Z.nativeEncoderHardwareAccelerated=="boolean"?Z.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:Z.nativeEncoderHardwareQueryStatus?String(Z.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureDisplayId:ht(Z.nativeCaptureDisplayId),nativeCaptureFps:ht(Z.nativeCaptureFps),nativeCompressionFps:ht(Z.nativeCompressionFps),nativeEncodedFps:ht(Z.nativeEncodedFps),nativeCaptureSampleCount:ht(Z.nativeCaptureSampleCount),nativeEncodableFrameCount:ht(Z.nativeEncodableFrameCount),nativeSkippedFrameCount:ht(Z.nativeSkippedFrameCount),nativeCompressionOutputCount:ht(Z.nativeCompressionOutputCount),nativeEncodedFrameCount:ht(Z.nativeEncodedFrameCount),nativeEncodeFramesInFlight:ht(Z.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:ht(Z.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:ht(Z.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:ht(Z.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:ht(Z.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:ht(Z.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:ht(Z.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:ht(Z.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:ht(Z.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:ht(Z.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:ht(Z.nativeOutputQueueDepth),nativeOutputQueueBytes:ht(Z.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:ht(Z.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:ht(Z.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:ht(Z.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof Z.nativeOutputQueueAwaitingKeyFrame=="boolean"?Z.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof Z.nativeCopyTelemetryAvailable=="boolean"?Z.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:ht(Z.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:ht(Z.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:ht(Z.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:ht(Z.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:ht(Z.pipePayloadAllocationCount),pipePayloadCopyCount:ht(Z.pipePayloadCopyCount),pipePayloadCopiedBytes:ht(Z.pipePayloadCopiedBytes),handoffDroppedFrameCount:ht(Z.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:ht(Z.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:ht(Z.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:Z.nativeCaptureResourceTelemetryAvailable===!0?L1(Z):Z.nativeCaptureResourceTelemetryAvailable===!1?!1:void 0,nativeCaptureTelemetryAt:Z.nativeCaptureTelemetryAt?String(Z.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(Z.droppedByAgent||0)||0,hubIngressDropped:Number(Z.hubIngressDropped||0)||0,hubClientDropped:nt,transport:Z.transport?String(Z.transport):void 0,videoTransport:Z.videoTransport?String(Z.videoTransport):void 0,frameTransportActive:Z.frameTransportActive?String(Z.frameTransportActive):void 0,frameTransportProtocol:Z.frameTransportProtocol?String(Z.frameTransportProtocol):void 0,frameTransportState:Z.frameTransportState?String(Z.frameTransportState):void 0,frameTransportReason:Z.frameTransportReason?String(Z.frameTransportReason):void 0,frameTransportChangedAt:Z.frameTransportChangedAt?String(Z.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(Z.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(Z.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:Z.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:rt,hubClientQueueDepth:lt,hubClientQueueLimit:Tt,hubClientBufferedBytes:Mt,udpIncompleteFrames:Number(Z.udpIncompleteFrames||0)||0,hardwareEncoder:Z.hardwareEncoder?String(Z.hardwareEncoder):void 0,platformProfile:Z.platformProfile?String(Z.platformProfile):void 0,monitorIndex:Number.isFinite(Number(Z.monitorIndex))?Number(Z.monitorIndex):void 0,monitorCount:Number.isFinite(Number(Z.monitorCount))?Number(Z.monitorCount):void 0,requestedFps:Number(Z.requestedFps||0)||0,effectiveFps:Number(Z.effectiveFps||0)||0,captureTimingAvailable:Z.captureTimingAvailable===!0,captureAverageMs:ht(Z.captureAverageMs),captureP95Ms:ht(Z.captureP95Ms),slowFrameCount:Number(Z.slowFrameCount||0)||0,captureHelperRestarts:Number(Z.captureHelperRestarts||0)||0,capturedAt:String(Z.capturedAt||""),receivedAt:String(Z.receivedAt||""),hubPacketAt:Z.hubPacketAt?String(Z.hubPacketAt):void 0,hubPacketEpochMs:Ee,browserReceivedEpochMs:Ae,hubPacketTransitAgeMs:Ee!==void 0?Ge:void 0,byteLength:Number(Z.byteLength||ze.byteLength),contentHash:Z.contentHash?String(Z.contentHash):void 0,captureMs:ht(Z.captureMs),captureStageMs:ht(Z.captureStageMs),convertMs:Number(Z.convertMs||0)||0,compressMs:Number(Z.compressMs||0)||0,captureSourceSerial:Number(Z.captureSourceSerial||0)||0,captureSourceSkipped:Number(Z.captureSourceSkipped||0)||0,deltaTileSize:Number(Z.deltaTileSize||0)||0,deltaTileCount:Number(Z.deltaTileCount||0)||0,deltaVisualTileCount:Number(Z.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(Z.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(Z.deltaTotalTiles||0)||0,payload:ze};if(!dt.deviceId)return;const G=pe.expectedBinding;if(!G)return;const ge=dt.deviceId===G.deviceId&&String(dt.sessionId||"")===G.sessionId&&dt.streamId===G.streamId&&String(dt.commandId||"")===G.commandId&&Number(dt.captureGeneration||0)===G.captureGeneration&&Number(dt.monitorIndex??-1)===G.monitorIndex&&String(dt.streamPurpose||"")===G.streamPurpose;if(!ge)return;dt.currentGenerationVerified=ge;const De=Number(pe.payload.monitorSelections?.[dt.deviceId]);if(Number.isFinite(De)&&Number.isFinite(Number(dt.monitorIndex))&&Number(dt.monitorIndex)!==De)return;const z={streamId:pe.lastFrameStreamId,commandId:pe.lastFrameCommandId,order:pe.lastFrameOrder},ae=Number(dt.streamFrameSeq||dt.frameSeq||0),Te=!!z.commandId&&!!dt.commandId,Ue=z.streamId===dt.streamId&&(!Te||z.commandId===dt.commandId),Xe=z.order;if(Ue&&Xe>=ae&&(Xe===ae||Te))return;pe.lastFrameStreamId=dt.streamId,pe.lastFrameCommandId=dt.commandId||"",pe.lastFrameOrder=ae;const at=q.current;at.totalFrames+=1,at.totalBytes+=ze.byteLength,at.sampleFrames+=1,at.sampleBytes+=ze.byteLength;const kt=!x.current.has(dt.deviceId)&&!M.current.has(dt.deviceId),At=PA(M.current,dt);kt&&(x.current.set(dt.deviceId,At),M.current.delete(dt.deviceId),u(new Map(x.current))),K.current?.(dt)},[]);d.useEffect(()=>{if(!n||!O)return;q.current.sampleStartedAt=performance.now();const he=window.setInterval(()=>{if(!ce.current)return;const pe=performance.now(),Ae=q.current,Se=Math.max(1,pe-Ae.sampleStartedAt);b({totalFrames:Ae.totalFrames,totalBytes:Ae.totalBytes,framesPerSecond:Ae.sampleFrames*1e3/Se,bytesPerSecond:Ae.sampleBytes*1e3/Se,sampleMs:Se,lastUpdatedAt:Date.now()}),u(FA(x.current,M.current)),Ae.sampleFrames=0,Ae.sampleBytes=0,Ae.sampleStartedAt=pe},2e3);return U.current=he,()=>{window.clearInterval(he),U.current===he&&(U.current=null)}},[n,O]),d.useEffect(()=>{const he=()=>{const pe=new Set,Ae=[...k.current.values()];for(;Ae.length>0;){const Z=Ae.pop();!Z||pe.has(Z)||(pe.add(Z),Z.handoffFrom&&Ae.push(Z.handoffFrom))}const Se=[...x.current.values(),...M.current.values()],Pe=[...pe],Qe=N.current?.snapshot()||{closingSocketCount:0,closingSocketTimerCount:0,closingSocketTimeoutCount:0};return{deviceKey:O,active:ce.current,socketCount:Pe.length+Qe.closingSocketCount,openSocketCount:Pe.filter(Z=>Z.socket.readyState===WebSocket.OPEN).length,connectingSocketCount:Pe.filter(Z=>Z.socket.readyState===WebSocket.CONNECTING).length,closingSocketCount:Qe.closingSocketCount,closingSocketTimerCount:Qe.closingSocketTimerCount,closingSocketTimeoutCount:Qe.closingSocketTimeoutCount,expectedBindingCount:Pe.filter(Z=>!!Z.expectedBinding).length,reconnectTimerCount:P.current.size,statsTimerCount:U.current===null?0:1,configurationRefreshTimerCount:F.current===null?0:1,restartTokenCount:I.current.size,retainedFrameCount:Se.length,retainedPayloadBytes:Se.reduce((Z,$t)=>Z+Math.max(0,Number($t.payload?.byteLength||0)),0)}};return ov.add(he),()=>{ov.delete(he)}},[O]),d.useEffect(()=>{const he=O?O.split(",").filter(Boolean):[];if(!W){ie(n?"livedesk-no-devices":"livedesk-stream-inactive");return}const pe=new Set(he),Ae=performance.now();for(const Se of P.current.keys())pe.has(Se)||Ve(Se);for(const[Se,Pe]of k.current.entries())pe.has(Se)||(Ve(Se),He(Pe,"livedesk-device-unsubscribed"),k.current.delete(Se),I.current.delete(Se),x.current.delete(Se),M.current.delete(Se));q.current.sampleStartedAt<=0&&(q.current.sampleStartedAt=Ae,b({...Vf,lastUpdatedAt:Date.now()}));for(const Se of he){Ve(Se);const Pe=Number(i.monitorSelections?.[Se]),Qe=Number.isInteger(Pe)&&Pe>=0?Pe:0,Z={[Se]:Qe},$t={type:"subscribe",deviceIds:[Se],autoStartLive:n,fps:$,maxWidth:ee,maxHeight:B,quality:L,mode:be,frameMode:be,streamPurpose:H,monitorSelections:Z},Ee=String(i.connectionSessionIds?.[Se]||"").trim(),Ge=JSON.stringify({subscribePayload:$t,connectionSessionId:Ee}),ze=k.current.get(Se),Ft=Number(ze?.payload.monitorSelections?.[Se]),Ze=Number(Z[Se]),nt=!!ze&&Number.isFinite(Ft)&&Number.isFinite(Ze)&&Ft!==Ze,lt=!!ze&&ze?.connectionSessionId!==Ee;if(ze){const Te=ze.socket.readyState===WebSocket.CONNECTING||ze.socket.readyState===WebSocket.OPEN;if(ze.payloadKey===Ge&&Te&&!ze.disposed)continue}const Tt=ze&&(ze.socket.readyState===WebSocket.CONNECTING||ze.socket.readyState===WebSocket.OPEN)&&!ze.disposed?ze.handoffFrom&&!ze.handoffCompleted?ze.handoffFrom:ze:void 0,Mt=ze&&ze!==Tt?ze:void 0,rt=new WebSocket(Yp(`/api/remote/frames/ws?devices=${encodeURIComponent(Se)}`,r),Xp(r));rt.binaryType="arraybuffer";const dt=qA(),G={socket:rt,payload:$t,payloadKey:Ge,connectionSessionId:Ee,generation:E.current+1,monitorRestartToken:nt?`monitor-${Se}-${Ze}-${E.current+1}`:"",disposed:!1,handoffFrom:Tt,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:dt,releaseOwnedState:()=>Qb(dt)};E.current=G.generation,(nt||lt)&&(x.current.delete(Se),M.current.delete(Se),u(new Map(x.current))),k.current.set(Se,G),Mt&&(Mt.handoffFrom=void 0,He(Mt,"livedesk-subscription-superseded"));const ge=()=>{if(!ce.current||G.disposed||k.current.get(Se)!==G){He(G,"livedesk-stale-frame-socket");return}Ve(Se),y("");const Te=T.current,Ue=Te.enabled&&(!Te.token||I.current.get(Se)!==Te.token),Xe=Ue||G.monitorRestartToken!=="",at=Ue?Te.token:G.monitorRestartToken,kt=Ue?Te.reason:G.monitorRestartToken?"monitor-selection-change":"";rt.send(JSON.stringify({...G.payload,forceRestart:Xe,restartReason:Xe?kt:"",restartToken:Xe?at:""})),Ue&&Te.token&&I.current.set(Se,Te.token);const At=G.handoffFrom;G.handoffFrom=void 0,G.handoffCompleted=!0,At&&!At.disposed&&He(At,"livedesk-subscription-replaced"),Oe()},De=Te=>{if(!ce.current||G.disposed||k.current.get(Se)!==G)return;if(typeof Te.data=="string"){try{const Xe=JSON.parse(Te.data),at=(kt,At=!0)=>{const Ut=_1(kt,Se,H);return Ut?(G.expectedBinding=Ut,At&&ne.current?.(Ut),!0):!1};if(Xe?.type==="RemoteFrameSubscriptionError")y(String(Xe.error||"control-stream-start-failed"));else if(Xe?.type==="RemoteFrameLiveAutoStart"){const At=(Array.isArray(Xe.skipped)?Xe.skipped:[]).find(Ut=>Ut?.deviceId===Se);if(At)At.reason==="CAPTURE_TRANSITION_IN_PROGRESS"&&At.retryScheduled===!0?y(""):y(String(At.reason||"control-stream-start-failed"));else if(Array.isArray(Xe.started)){const Ut=Xe.started.find(Qt=>Qt?.deviceId===Se);Ut&&(y(""),at(Ut,Ut.ready===!0))}}else Xe?.type==="RemoteFrameStreamReady"&&Xe.deviceId===Se&&at(Xe)&&y("")}catch{}return}const Ue=Te.data instanceof ArrayBuffer?Te.data:null;Ue&&(y(""),qe(Ue,G))},z=()=>{!ce.current||G.disposed||k.current.get(Se)!==G||h("connecting")},ae=()=>{const Te=!G.disposed;G.disposed=!0,G.handoffCompleted=!0;const Ue=G.detachListeners;G.detachListeners=void 0,Ue?.();const Xe=k.current.get(Se);let at=!1;if(Xe===G){const kt=G.handoffFrom;G.handoffFrom=void 0,kt&&!kt.disposed&&(kt.socket.readyState===WebSocket.CONNECTING||kt.socket.readyState===WebSocket.OPEN)?(k.current.set(Se,kt),at=!0):k.current.delete(Se)}if(Oe(),Te&&ce.current&&Xe===G&&!at){const kt=window.setTimeout(()=>{P.current.get(Se)===kt&&P.current.delete(Se),ce.current&&D(At=>At+1)},750);Ve(Se),P.current.set(Se,kt)}};G.detachListeners=()=>{rt.removeEventListener("open",ge),rt.removeEventListener("message",De),rt.removeEventListener("error",z),rt.removeEventListener("close",ae)},rt.addEventListener("open",ge),rt.addEventListener("message",De),rt.addEventListener("error",z),rt.addEventListener("close",ae)}Oe()},[n,Ve,He,Ne,O,$,be,qe,r,B,ee,Me,i.monitorSelections,L,Y,ie,H,W,Oe]),d.useEffect(()=>{if(!W||oe<=0){F.current!==null&&(window.clearInterval(F.current),F.current=null);return}const he=Math.max(1e3,oe),pe=window.setInterval(()=>{for(const[Ae,Se]of k.current.entries())if(!(Se.disposed||Se.socket.readyState!==WebSocket.OPEN))try{Se.socket.send(JSON.stringify({...Se.payload,type:"refresh-live",deviceIds:[Ae],reason:"periodic-configuration"}))}catch{try{Se.socket.close(4003,"configuration-refresh-failed")}catch{}}},he);return F.current=pe,()=>{window.clearInterval(pe),F.current===pe&&(F.current=null)}},[oe,W]),d.useEffect(()=>{if(!W||!me||!ue)return;const he=O?O.split(",").filter(Boolean):[];for(const pe of he){if(I.current.get(pe)===ue)continue;const Ae=k.current.get(pe);!Ae||!$e(pe,Ae,Ce,ue)||I.current.set(pe,ue)}},[O,me,ue,Ce,$e,W]),d.useEffect(()=>()=>{ie("livedesk-hook-unmount",!1)},[ie]);const vt=d.useCallback((he,pe="browser-stale")=>{if(!W)return!1;const Ae=Array.isArray(he)&&he.length>0?he:O.split(",").filter(Boolean);if(Ae.length===0)return!1;let Se=!1;for(const Pe of Ae){const Qe=k.current.get(Pe);!Qe||Qe.socket.readyState!==WebSocket.OPEN||(Se=$e(Pe,Qe,pe,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Se)}return Se},[O,$e,W]),xe=d.useCallback((he,pe="browser-reconnect")=>{if(!W)return!1;const Ae=Array.isArray(he)&&he.length>0?he:O.split(",").filter(Boolean);if(Ae.length===0)return!1;let Se=!1;for(const Pe of Ae){const Qe=k.current.get(Pe);Qe&&(Ve(Pe),He(Qe,`livedesk-${pe}`),k.current.delete(Pe),I.current.delete(Pe),x.current.delete(Pe),M.current.delete(Pe),Se=!0)}return Se&&u(new Map(x.current)),D(Pe=>Pe+1),Oe(),!0},[Ve,He,O,W,Oe]);return{frames:l,state:f,error:g,stats:w,restartLive:vt,reconnectLive:xe}}function P1(t,n,r=Dn,i={}){const[l,u]=d.useState(null),[f,h]=d.useState(null),[g,y]=d.useState("idle"),[w,b]=d.useState(Vf),x=d.useRef(null),M=d.useRef(i.onFrame),k=d.useRef(null),N=d.useRef(0),E=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),I=d.useMemo(()=>[...new Set(t.filter(Boolean))].join(","),[t]),T=d.useMemo(()=>[...new Set((i.captureDeviceIds||t).filter(Boolean))].join(","),[t,i.captureDeviceIds]),P=d.useMemo(()=>JSON.stringify(i.monitorSelections||{}),[i.monitorSelections]),U=d.useMemo(()=>{const O=Object.entries(i.connectionSessionIds||{}).filter(([W])=>!!W).map(([W,ce])=>[W,String(ce||"").trim()]).sort(([W],[ce])=>W.localeCompare(ce));return JSON.stringify(Object.fromEntries(O))},[i.connectionSessionIds]),F=d.useMemo(()=>({deviceIds:I.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(i.fps||20),inputFps:Number(i.inputFps||8),width:Number(i.width||1920),height:Number(i.height||1080),tileWidth:Number(i.tileWidth||320),tileHeight:Number(i.tileHeight||180),monitorSelections:i.monitorSelections||{}}),[T,I,P,i.fps,i.height,i.inputFps,i.monitorSelections,i.tileHeight,i.tileWidth,i.width]),Y=d.useMemo(()=>JSON.stringify({atlasConfiguration:F,connectionSessionKey:U}),[F,U]),D=d.useRef(F);D.current=F;const K=n&&F.deviceIds.length>0,ne=d.useCallback(O=>O.readyState!==WebSocket.OPEN?!1:(O.send(JSON.stringify({type:"configure",...D.current})),!0),[]);d.useEffect(()=>{M.current=i.onFrame},[i.onFrame]),d.useEffect(()=>{if(!K)return;E.current.sampleStartedAt=performance.now();const O=window.setInterval(()=>{const W=E.current,ce=performance.now(),$=Math.max(1,ce-W.sampleStartedAt);b({totalFrames:W.totalFrames,totalBytes:W.totalBytes,framesPerSecond:W.sampleFrames*1e3/$,bytesPerSecond:W.sampleBytes*1e3/$,sampleMs:$,lastUpdatedAt:Date.now()});const ee=k.current;ee&&ee.frameSeq!==N.current&&(N.current=ee.frameSeq,u(ee)),W.sampleFrames=0,W.sampleBytes=0,W.sampleStartedAt=ce},1e3);return()=>window.clearInterval(O)},[K]),d.useEffect(()=>{if(!K){x.current?.close(),x.current=null,u(null),k.current=null,N.current=0,h(null),y("idle"),b(Vf);return}let O=!1,W=0;const ce=()=>{if(O)return;const $=new WebSocket(Yp("/api/remote/atlas/ws",r),Xp(r));$.binaryType="arraybuffer",x.current=$,y("connecting"),$.addEventListener("open",()=>{E.current.sampleStartedAt=performance.now(),y("open"),ne($)}),$.addEventListener("message",ee=>{if(typeof ee.data=="string"){try{const L=JSON.parse(ee.data);L?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(L.layoutVersion||0),width:Number(L.width||1920),height:Number(L.height||1080),columns:Number(L.columns||1),rows:Number(L.rows||1),tiles:Array.isArray(L.tiles)?L.tiles:[]})}catch{}return}const B=ee.data instanceof ArrayBuffer?ee.data:null;if(!(!B||B.byteLength<5))try{const L=Date.now(),be=new DataView(B).getUint32(0,!1);if(be<=0||be+4>B.byteLength)return;const H=JSON.parse(Lv.decode(new Uint8Array(B,4,be))),me=new Uint8Array(B,4+be),ue=ht(H.hubClientDropped),Ce=ht(H.hubClientQueueDepth),Me=ht(H.hubClientQueueLimit),Ne=ht(H.hubClientBufferedBytes),He={deviceId:String(H.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(H.frameSeq||0),streamFrameSeq:Number(H.streamFrameSeq||0)||void 0,streamId:String(H.streamId||"mode4-atlas"),commandId:H.commandId?String(H.commandId):void 0,width:Number(H.width||1920),height:Number(H.height||1080),sourceWidth:Number(H.sourceWidth||H.width||1920),sourceHeight:Number(H.sourceHeight||H.height||1080),mimeType:String(H.mimeType||"video/h264"),mode:String(H.mode||"mode4-h264-atlas"),frameMode:String(H.frameMode||"mode4-h264-atlas"),frameProfile:String(H.frameProfile||"mode4-h264-atlas-v1"),encoding:String(H.encoding||"video-atlas"),codec:String(H.codec||"h264"),compression:String(H.compression||"video/h264"),h264Format:String(H.h264Format||"annexb"),isKeyFrame:H.isKeyFrame===!0,chunkType:String(H.chunkType||""),timestampUs:Number(H.timestampUs||0),durationUs:Number(H.durationUs||0),transport:H.transport?String(H.transport):void 0,videoTransport:H.videoTransport?String(H.videoTransport):void 0,frameTransportActive:H.frameTransportActive?String(H.frameTransportActive):void 0,frameTransportProtocol:H.frameTransportProtocol?String(H.frameTransportProtocol):void 0,frameTransportState:H.frameTransportState?String(H.frameTransportState):void 0,frameTransportReason:H.frameTransportReason?String(H.frameTransportReason):void 0,frameTransportChangedAt:H.frameTransportChangedAt?String(H.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(H.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(H.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:H.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:ue!==void 0&&Ce!==void 0&&Me!==void 0&&Ne!==void 0,hubClientDropped:ue,hubClientQueueDepth:Ce,hubClientQueueLimit:Me,hubClientBufferedBytes:Ne,udpIncompleteFrames:Number(H.udpIncompleteFrames||0)||0,hardwareEncoder:H.hardwareEncoder?String(H.hardwareEncoder):void 0,platformProfile:H.platformProfile?String(H.platformProfile):void 0,capturedAt:String(H.capturedAt||""),receivedAt:String(H.receivedAt||""),hubPacketAt:H.hubPacketAt?String(H.hubPacketAt):void 0,hubPacketEpochMs:Number(H.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:L,byteLength:me.byteLength,layoutVersion:Number(H.layoutVersion||0),atlasComposeMs:Number(H.atlasComposeMs||0),atlasPoolStarved:Number(H.atlasPoolStarved||0),atlasReadyTiles:Number(H.atlasReadyTiles||0),atlasTileCount:Number(H.atlasTileCount||0),atlasInputRevision:Number(H.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(H.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(H.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(H.atlasSourceMaxAgeMs||0),payload:me},Ve=E.current;Ve.totalFrames+=1,Ve.totalBytes+=me.byteLength,Ve.sampleFrames+=1,Ve.sampleBytes+=me.byteLength,k.current=He,N.current===0&&(N.current=He.frameSeq,u(He)),M.current?.(He)}catch{}}),$.addEventListener("error",()=>y("error")),$.addEventListener("close",()=>{x.current===$&&(x.current=null),!O&&(y("closed"),W=window.setTimeout(ce,1200))})};return ce(),()=>{O=!0,window.clearTimeout(W),x.current?.close(),x.current=null}},[K,r,ne]),d.useEffect(()=>{if(!K)return;const O=x.current;O&&ne(O)},[Y,K,ne]);const q=d.useCallback(()=>{const O=x.current;return O?ne(O):!1},[ne]);return{frame:l,layout:f,state:g,stats:w,refreshInputs:q}}function F1(t,n=Dn,r=""){const i=d.useRef(null),l=d.useRef(0),u=d.useRef(0),f=d.useRef(new Map),h=d.useRef(""),g=d.useRef(r);g.current=r;const y=d.useRef(r),w=d.useRef(0),b=d.useRef([]),[x,M]=d.useState("idle"),[k,N]=d.useState(""),[E,I]=d.useState(ew),T=d.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0}),P=d.useCallback((K=performance.now())=>{const ne=g.current;b.current=b.current.filter(q=>!!ne&&q.ownerKey===ne&&K-q.queuedAt<=gg)},[]),U=d.useCallback((K,ne)=>{const q=g.current,O=String(ne.type||"input").toLowerCase();return!q||!K?(T.current.totalDropped+=1,T.current.sampleDropped+=1,T.current.lastInputType=O+"-owner-unavailable",!1):(P(),b.current.length>=A1?(b.current=[],T.current.totalDropped+=1,T.current.sampleDropped+=1,T.current.lastInputType=O+"-queue-overflow",N("Remote input queue was reset because ordered input could not drain."),!1):(b.current.push({ownerKey:q,deviceId:K,input:{...ne},queuedAt:performance.now()}),T.current.lastInputType=O+"-queued",!0))},[P]),F=d.useCallback((K,ne,q)=>{if(K.readyState!==WebSocket.OPEN||!ne)return!1;const O=String(q.type||"").toLowerCase(),W=O==="pointermove",$=W||O==="wheel",ee=T.current;if($&&K.bufferedAmount>k1)return ee.totalDropped+=1,ee.sampleDropped+=1,ee.lastInputType=O+"-coalescible-drop",!1;const B=l.current+1;l.current=B;const L=B+"-"+crypto.randomUUID(),oe=Date.now(),be=!$||B-u.current>=j1;for(be&&(f.current.set(B,{sentAt:performance.now(),deviceId:ne,inputEventId:L}),$&&(u.current=B)),h.current=ne,W||CS.set(ne,{inputSeq:B,inputType:O||"input",sentAt:performance.now()});f.current.size>256;){const H=f.current.keys().next().value;if(H===void 0)break;f.current.delete(H)}try{K.send(JSON.stringify({type:"input",requestId:$?"":crypto.randomUUID(),fireAndForget:$,deviceId:ne,input:{...q,inputEventId:L,inputSeq:B,requestAck:be,issuedAtEpochMs:oe,issuedAt:new Date(oe).toISOString()}}))}catch{return f.current.delete(B),!1}return ee.totalSent+=1,ee.sampleSent+=1,ee.lastInputType=O||"input",!0},[]),Y=d.useCallback(K=>{P();const ne=g.current;if(!ne||K.readyState!==WebSocket.OPEN)return;const q=b.current;b.current=[];for(let O=0;O<q.length;O+=1){const W=q[O];if(!(W.ownerKey!==ne||performance.now()-W.queuedAt>gg)&&(K.readyState!==WebSocket.OPEN||!F(K,W.deviceId,W.input))){b.current=q.slice(O).filter(ce=>ce.ownerKey===ne&&performance.now()-ce.queuedAt<=gg);return}}},[F,P]);d.useLayoutEffect(()=>{y.current!==r&&(y.current=r,b.current=[],f.current.clear(),u.current=0,h.current="")},[r]),d.useEffect(()=>{if(!t){i.current?.close(),i.current=null,w.current=0,b.current=[],u.current=0,h.current="",f.current.clear(),M("idle"),N(""),I(ew);return}let K=!1,ne=0;const q=()=>{if(K)return;const O=new WebSocket(Yp("/api/remote/input/ws",n),Xp(n));i.current=O,T.current.sampleStartedAt=performance.now(),M("connecting"),N(""),O.addEventListener("open",()=>{K||i.current!==O||(w.current=0,N(""),M("open"),Y(O))}),O.addEventListener("message",W=>{if(!(K||i.current!==O||typeof W.data!="string"))try{const ce=JSON.parse(W.data),$=Number(ce.inputSeq||ce.result?.inputSeq||0),ee=String(ce.deviceId||ce.result?.deviceId||""),B=String(ce.inputEventId||ce.result?.inputEventId||""),L=f.current.get($);if(ee&&(L&&L.deviceId!==ee||!L&&h.current&&h.current!==ee)||L?.inputEventId&&B&&L.inputEventId!==B)return;if(ce?.type==="RemoteInputError"){$>0&&f.current.delete($),N(String(ce.error||ce.result?.error||"Remote input failed.")),O.readyState===WebSocket.OPEN&&M("open");return}if(ce?.type!=="RemoteInputApplied")return;L&&(T.current.lastRoundTripMs=Math.max(0,performance.now()-L.sentAt),f.current.delete($)),T.current.lastInputSeq=$,T.current.lastAgentApplyMs=Math.max(0,Number(ce.agentApplyMs||0)),N(""),M("open")}catch{}}),O.addEventListener("close",()=>{if(K||i.current!==O)return;i.current=null,f.current.clear(),M("closed");const W=w.current;w.current=W+1;const ce=Math.min(T1,N1*2**Math.min(W,3));ne=window.setTimeout(q,ce)}),O.addEventListener("error",()=>{!K&&i.current===O&&M("error")})};return q(),()=>{K=!0,window.clearTimeout(ne);const O=i.current;i.current=null,O?.close(),f.current.clear()}},[t,Y,n]),d.useEffect(()=>{if(!t)return;const K=window.setInterval(()=>{const ne=performance.now();P(ne);const q=T.current,O=Math.max(1,ne-q.sampleStartedAt);I({totalSent:q.totalSent,totalDropped:q.totalDropped,sentPerSecond:q.sampleSent*1e3/O,droppedPerSecond:q.sampleDropped*1e3/O,bufferedAmount:i.current?.bufferedAmount||0,lastInputType:q.lastInputType,lastInputSeq:q.lastInputSeq,lastRoundTripMs:q.lastRoundTripMs,lastAgentApplyMs:q.lastAgentApplyMs,lastUpdatedAt:Date.now()}),q.sampleSent=0,q.sampleDropped=0,q.sampleStartedAt=ne},1e3);return()=>window.clearInterval(K)},[t,P]);const D=d.useCallback((K,ne)=>{const q=String(ne.type||"").toLowerCase(),O=q==="pointermove"||q==="wheel",W=i.current;if(!W||W.readyState!==WebSocket.OPEN)return O?(T.current.totalDropped+=1,T.current.sampleDropped+=1,T.current.lastInputType=(q||"input")+"-transport-unavailable",!1):U(K,ne);if(!O&&W.bufferedAmount>M1){const ee=U(K,ne);N("Remote input is reconnecting because ordered input could not drain immediately.");try{W.close(4001,"ordered-input-backpressure")}catch{}return ee}const ce=F(W,K,ne);if(ce||O)return ce;const $=U(K,ne);N("Remote input is reconnecting after a send failure.");try{W.close(4002,"input-send-failed")}catch{}return $},[F,U]);return{state:x,sendInput:D,stats:E,error:k}}const ld={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureAwaitingCurrentPcm:!1,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0,lastUpdatedAt:0},O1=.25,nw=300,aw=2,lp=1500,vg=5e3,H1=2e3,rw=1e4,Lf=[0,1e3,3e3];function sw(t){const n=Date.parse(String(t||""));return Number.isFinite(n)?Math.max(0,Date.now()-n):0}function B1(t,n,r=Dn,i=0,l=!1,u="",f,h){const g=d.useRef(null),[y,w]=d.useState("idle"),[b,x]=d.useState(null),[M,k]=d.useState(ld),[N,E]=d.useState(""),I=d.useRef(l);return I.current=l,d.useEffect(()=>{l||(x(T=>T===null?T:null),k(T=>T===ld?T:ld))},[l]),d.useEffect(()=>{if(!n||!t){w("idle"),x(null),k(ld),E("");return}w("connecting"),x(null),k(ld),E("");const T=window.AudioContext||window.webkitAudioContext;if(!T){w("unsupported"),k(ld),E("Audio playback is not supported in this browser.");return}let P=!1,U=null;const F=JA.acquire(({release:Y})=>{if(P){Y();return}const D=new T({latencyHint:"interactive"});g.current=D;let K=String(u||"").trim();const ne="/api/remote/audio/ws?devices="+encodeURIComponent(t)+(K?"&streamId="+encodeURIComponent(K):""),q=new WebSocket(Yp(ne,r),Xp(r));q.binaryType="arraybuffer";const O=ha.createOwner({deviceId:t,socket:q,audioContext:D,statsTimer:null});let W=!1;const ce=()=>{const G=ha.releaseIfDrained(O);return(G||!ha.hasOwner(O))&&!W&&(W=!0,Y()),G},$=Iv({sampleRate:192e3,channels:8}).capacityBytes,ee=o1({maxPendingPackets:sv,maxPendingBytes:$}),B=KA(),L={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureStatusFailed:!1,captureAwaitingCurrentPcm:!1,captureAwaitingSinceAt:0,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(D.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:K,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let oe=!1,be=!1,H=null,me=0,ue=0,Ce="",Me=!1,Ne=()=>{},He="connecting",Ve="";const ie=G=>{oe||G===He||(He=G,w(G))},Oe=G=>{oe||G===Ve||(Ve=G,E(G))};let $e=0,qe=!1,vt=0,xe=0,he=0,pe=!1;const Ae=()=>{ha.setPendingWorkletPackets(O,ee.getPendingPacketCount(),ee.getPendingPacketBytes(),ee.getPendingPacketHighWater(),ee.getPendingByteHighWater())},Se=G=>{L.workletRingCapacityBytes=Math.max(0,Math.min($,Number(G.ringCapacityBytes||0)||0)),L.workletRingBufferedBytes=Math.max(0,Math.min(L.workletRingCapacityBytes,Number(G.ringBufferedBytes||0)||0)),L.workletRingBufferedMs=Math.max(0,Math.min(O1*1e3,Number(G.ringBufferedMs||0)||0)),L.workletRingDroppedFrames=Math.max(L.workletRingDroppedFrames,Number(G.ringDroppedFrames||0)||0),L.workletRingUnderflowCount=Math.max(L.workletRingUnderflowCount,Number(G.ringUnderflowCount||0)||0),ha.setPcmRing(O,L.workletRingCapacityBytes,L.workletRingBufferedBytes)},Pe=()=>{const G=H;if(H=null,Me=!1,G){G.onprocessorerror=null,G.port.onmessage=null;try{G.disconnect()}catch{}try{G.port.close()}catch{}}ee.terminate(),Ae(),L.workletRingCapacityBytes=0,L.workletRingBufferedBytes=0,L.workletRingBufferedMs=0,ha.setPcmRing(O,0,0),ha.setWorkletNode(O,0,0,me),ce()},Qe=G=>{const ge=G.data||{},De=String(ge.type||"");if((De==="packet-terminal"||De==="processor-error")&&(ee.acknowledge(typeof ge.packetId=="number"?ge.packetId:String(ge.packetId||"")),Ae()),De==="packet-terminal"){const z=Math.max(0,Number(ge.droppedFrames||0)||0);z>0&&(L.workletRingDroppedFrames+=z,L.resyncs+=1)}if(De==="ring-configured"||De==="ring-state"||De==="disposed"){const z=L.workletRingDroppedFrames;Se(ge),L.workletRingDroppedFrames>z&&(L.resyncs+=1)}De==="disposed"?Pe():De==="processor-error"&&Ne(String(ge.error||"Remote audio worklet processing failed."))},Z=()=>{if(!(!H||!Me))try{H.port.postMessage({type:"flush"})}catch{Ne("Remote audio worklet could not be flushed.")}},$t=()=>{q.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"subscribe",deviceIds:[t],streamIdsByDeviceId:K?{[t]:K}:{}}))},Ee=()=>{L.audioContextState=String(D.state),!oe&&(L.audioContextState==="suspended"||L.audioContextState==="interrupted"?ie("suspended"):L.audioContextState==="closed"&&(ie("error"),Oe("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},Ge=async()=>{if(oe||String(D.state)==="closed")return!1;try{if(String(D.state)!=="running"&&await D.resume(),L.audioContextState=String(D.state),!oe&&!qe&&L.audioContextState==="running"){const G=L.lastAcceptedAt>0&&performance.now()-L.lastAcceptedAt<=lp,ge=L.lastCaptureStatusAt>0&&performance.now()-L.lastCaptureStatusAt<=vg&&L.captureHealthy;ie(G?"playing":ge?"silent":"open")}return L.audioContextState==="running"}catch(G){return oe||(ie("suspended"),Oe(G instanceof Error?"Audio playback is suspended: "+G.message:"Audio playback is suspended.")),!1}},ze=async()=>{if(!D.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const G=new Blob([f1],{type:"text/javascript"});Ce=URL.createObjectURL(G);try{await D.audioWorklet.addModule(Ce)}finally{URL.revokeObjectURL(Ce),Ce=""}if(oe||String(D.state)==="closed")return;const ge=new AudioWorkletNode(D,SS,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[aw],channelCount:aw,channelCountMode:"explicit"});me+=1,H=ge,ge.port.onmessage=Qe,ge.onprocessorerror=()=>{Ne("Remote audio worklet stopped unexpectedly.")},ge.connect(D.destination),Me=!0,ha.setWorkletNode(O,1,1,me)},Ft=(G,ge,De,z)=>{const ae=H;if(oe||!Me||!ae||ge.byteLength<=0)return!1;const Te=Dv({sampleRate:G.sampleRate,channels:G.channels,mimeType:G.mimeType}),Ue=++ue;if(!ee.claim(Ue,ge.byteLength))return Ae(),!1;Ae();try{return ae.port.postMessage({type:"pcm",packetId:Ue,buffer:ge,byteOffset:De,byteLength:z,sampleRate:Te.sampleRate,channels:Te.channels,mimeType:G.mimeType,sampleFormat:Te.sampleFormat},[ge]),!0}catch{return ee.acknowledge(Ue),Ae(),!1}},Ze=async()=>{if(oe||qe||q.readyState!==WebSocket.OPEN)return;if(vt>=Lf.length){ie("error"),Oe("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const G=vt;vt+=1,qe=!0,L.stalledCount+=1,L.automaticRestarts+=1,ie("reconnecting");try{if(!f)throw new Error("Remote audio restart owner is unavailable.");const ge=await f(t);if(oe||!ge)return;K=ge,$t();const De=performance.now();$e=De,L.lastPacketAt=De,L.lastAcceptedAt=0,L.lastCaptureStatusAt=0,L.lastPcmAtEpochMs=0,L.captureAlive=null,L.helperAlive=null,L.helperReady=!1,L.captureHealthy=!1,L.captureStatusFailed=!1,L.captureAwaitingCurrentPcm=!1,L.captureAwaitingSinceAt=0,L.capturePhase="",L.backendKind="",L.helperRequired=!1,L.helperPid=0,L.nativeCallbackDiagnosticsAvailable=!1,L.nativeRejectedCallbackCount=0,L.nativeCurrentnessDropCount=0,L.nativeLastDropReason="",L.silentForMs=0,L.activeStreamId=K,L.lastFrameSeq=0,L.maximumAcceptedGapMs=0,Z(),xe=De+(Lf[G+1]??3e3),Oe(""),oe||ie("open")}catch(ge){oe||(xe=performance.now()+(Lf[G+1]??3e3),ie("error"),Oe(ge instanceof Error?"Remote audio restart failed: "+ge.message:"Remote audio restart failed."))}finally{qe=!1}},nt=()=>{L.drops+=1},lt=window.setInterval(()=>{if(oe)return;const G=performance.now(),ge=L.lastPacketAt>0?Math.max(0,G-L.lastPacketAt):$e>0?Math.max(0,G-$e):0,De=L.lastAcceptedAt>0?Math.max(0,G-L.lastAcceptedAt):0,z=L.lastCaptureStatusAt>0?Math.max(0,G-L.lastCaptureStatusAt):0,ae=q.readyState===WebSocket.OPEN,Te=L.lastCaptureStatusAt>0,Ue=Te&&z<=vg&&L.captureHealthy,Xe=Te&&L.captureStatusFailed&&z>H1,at=Te&&z>vg,kt=!Te&&$e>0&&G-$e>rw,At=L.captureAwaitingCurrentPcm&&L.captureAwaitingSinceAt>0&&G-L.captureAwaitingSinceAt>rw,Ut=$e>0&&(L.lastAcceptedAt<=0?G-$e>lp:De>lp);if(ae&&$e>0&&(Xe||at||kt||At)?vt>=Lf.length&&!qe?(ie("error"),Oe("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!qe&&G>=xe?Ze():qe||ie("stalled"):ae&&Ut&&!qe&&L.audioContextState!=="suspended"&&L.audioContextState!=="interrupted"&&ie(Ue?"silent":"open"),e1({enabled:I.current,now:G,lastPublishedAt:he})){he=G,k({queuedMs:L.workletRingBufferedMs,browserAgeMs:L.browserAgeMs,captureAgeMs:L.captureAgeMs,captureStatusAgeMs:z,silentForMs:L.silentForMs,captureAlive:L.captureAlive,helperAlive:L.helperAlive,helperReady:L.helperReady,captureHealthy:L.captureHealthy,captureAwaitingCurrentPcm:L.captureAwaitingCurrentPcm,capturePhase:L.capturePhase,backendKind:L.backendKind,helperRequired:L.helperRequired,helperPid:L.helperPid,captureRestartCount:L.captureRestartCount,nativeCallbackDiagnosticsAvailable:L.nativeCallbackDiagnosticsAvailable,nativeRejectedCallbackCount:L.nativeRejectedCallbackCount,nativeCurrentnessDropCount:L.nativeCurrentnessDropCount,nativeLastDropReason:L.nativeLastDropReason,localProcessingAgeMs:L.localProcessingAgeMs,lastPacketAgeMs:ge,lastAcceptedAgeMs:De,framesReceived:L.framesReceived,drops:L.drops,resyncs:L.resyncs,pendingDecodes:L.pendingDecodes,lastFrameSeq:L.lastFrameSeq,audioContextState:L.audioContextState,stalledCount:L.stalledCount,automaticRestarts:L.automaticRestarts,maximumAcceptedGapMs:L.maximumAcceptedGapMs,workletRingCapacityBytes:L.workletRingCapacityBytes,workletRingBufferedBytes:L.workletRingBufferedBytes,workletRingDroppedFrames:L.workletRingDroppedFrames,workletRingUnderflowCount:L.workletRingUnderflowCount,lastUpdatedAt:Date.now()});const Qt=B.publish();Qt&&(pe=!0,ha.setRetainedFrame(O,1,Qt.payload.byteLength),x(Qt))}else!I.current&&pe&&(pe=!1,B.clear(),ha.setRetainedFrame(O,0,0))},250);ha.setStatsTimer(O,lt);const Tt=()=>{Ee(),(String(D.state)==="suspended"||String(D.state)==="interrupted")&&Ge()},Mt=()=>{document.visibilityState==="visible"&&Ge()},rt=()=>{Ge()};D.addEventListener("statechange",Tt),document.addEventListener("visibilitychange",Mt),window.addEventListener("pageshow",rt),window.addEventListener("pointerdown",rt),window.addEventListener("keydown",rt),ie("connecting"),Oe(""),Ee();const dt=(G,ge,De,z,ae)=>{if(L.localProcessingAgeMs=Math.max(0,performance.now()-ae),oe||L.localProcessingAgeMs>nw||!iv(G,{deviceId:t,streamId:K}))return nt(),!1;L.activeStreamId!==K&&(L.activeStreamId=K,L.lastFrameSeq=0,L.maximumAcceptedGapMs=0,Z());const Te=r1(G,{deviceId:t,streamId:K,lastFrameSeq:L.lastFrameSeq});if(!Te.accepted||!Ft(G,ge,De,z))return nt(),!1;L.browserAgeMs=sw(G.receivedAt),L.captureAgeMs=sw(G.capturedAt);const Ue=performance.now();L.lastAcceptedAt>0&&(L.maximumAcceptedGapMs=Math.max(L.maximumAcceptedGapMs,Ue-L.lastAcceptedAt)),L.lastAcceptedAt=Ue,L.framesReceived+=1,L.lastFrameSeq=Te.nextFrameSeq,vt=0,xe=0,I.current&&(B.accept(G),pe=!0,ha.setRetainedFrame(O,1,0)),String(D.state)!=="running"&&Ge();const Xe=String(D.state)==="running";return Xe&&Oe(""),ie(Xe?"playing":"suspended"),!0};Ne=(G="")=>{if(!be){if(be=!0,G&&(ha.recordTerminalFailure(O,G,G.includes("setup failed")?"setup":"processor"),ie(G.includes("AudioWorklet is unavailable")?"unsupported":"error"),Oe(G),h?.(t,K,"browser-audio-playback-failed").catch(()=>{})),oe=!0,ha.deactivate(O),window.clearInterval(lt),ha.setStatsTimer(O,null),D.removeEventListener("statechange",Tt),document.removeEventListener("visibilitychange",Mt),window.removeEventListener("pageshow",rt),window.removeEventListener("pointerdown",rt),window.removeEventListener("keydown",rt),B.clear(),ha.setRetainedFrame(O,0,0),H)try{H.port.postMessage({type:"dispose"})}catch{}try{q.close()}catch{}q.readyState===WebSocket.CLOSED&&ha.setSocket(O,null),D.close().catch(()=>{}).finally(()=>{Pe(),String(D.state)==="closed"&&ha.setAudioContext(O,null),ce()}),g.current===D&&(g.current=null),ce()}},ze().catch(G=>{Ne(G instanceof Error?`Remote audio worklet setup failed: ${G.message}`:"Remote audio worklet setup failed.")}),q.addEventListener("open",()=>{oe||($e=performance.now(),L.lastPacketAt=$e,L.lastAcceptedAt=0,L.lastCaptureStatusAt=0,L.lastPcmAtEpochMs=0,L.captureAlive=null,L.helperAlive=null,L.helperReady=!1,L.captureHealthy=!1,L.captureStatusFailed=!1,L.captureAwaitingCurrentPcm=!1,L.captureAwaitingSinceAt=0,L.capturePhase="",L.backendKind="",L.helperRequired=!1,L.helperPid=0,L.maximumAcceptedGapMs=0,L.silentForMs=0,ie("open"),$t(),Ge())}),q.addEventListener("message",G=>{if(typeof G.data=="string")return;const ge=G.data instanceof ArrayBuffer?G.data:null;if(!ge||ge.byteLength<5)return;const De=performance.now();L.lastPacketAt=De;try{const ae=new DataView(ge).getUint32(0,!1);if(ae<=0||ae+4>ge.byteLength){nt();return}const Te=new Uint8Array(ge,4,ae),Ue=JSON.parse(Lv.decode(Te)),Xe=new Uint8Array(ge,4+ae),at=String(Ue.deviceId||""),kt=String(Ue.streamId||"");if(!iv({deviceId:at,streamId:kt},{deviceId:t,streamId:K})){nt();return}const At=String(Ue.frameKind||Ue.kind||"").toLowerCase();if(Ue.type==="remote.audio.status"||At==="audio-status"){L.lastCaptureStatusAt=De;const Qt=s1(Ue);if(L.captureAlive=Qt.captureAlive,L.helperAlive=Qt.helperAlive,L.helperReady=Qt.helperReady,L.captureHealthy=Qt.healthy,L.captureStatusFailed=Qt.failed,L.captureAwaitingCurrentPcm=Qt.awaitingCurrentPcm,Qt.awaitingCurrentPcm?L.captureAwaitingSinceAt||=De:L.captureAwaitingSinceAt=0,L.capturePhase=Qt.capturePhase,L.backendKind=Qt.backendKind,L.helperRequired=Qt.helperRequired===!0,L.helperPid=Qt.helperPid,L.captureRestartCount=Math.max(0,Number(Ue.restartCount||0)||0),L.nativeCallbackDiagnosticsAvailable=Ue.callbackDiagnosticsAvailable===!0,L.nativeRejectedCallbackCount=L.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ue.rejectedCallbackCount||0)||0):0,L.nativeCurrentnessDropCount=L.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ue.currentnessDropCount||0)||0):0,L.nativeLastDropReason=L.nativeCallbackDiagnosticsAvailable?String(Ue.lastDropReason||""):"",L.lastPcmAtEpochMs=Math.max(0,Number(Ue.lastPcmAtEpochMs||0)||0),L.silentForMs=Math.max(0,Number(Ue.silentForMs||0)||0),L.captureAgeMs=L.lastPcmAtEpochMs>0?Math.max(0,Date.now()-L.lastPcmAtEpochMs):L.silentForMs,L.captureHealthy){if(vt=0,xe=0,!qe){Oe("");const sa=String(D.state)==="running",Ra=L.lastAcceptedAt>0&&performance.now()-L.lastAcceptedAt<=lp;ie(sa?Ra?"playing":"silent":"suspended")}}else L.captureAwaitingCurrentPcm&&!qe?ie("open"):L.captureStatusFailed&&!qe&&ie("stalled");return}const Ut={deviceId:at,frameSeq:Number(Ue.frameSeq||0),streamId:kt,mimeType:String(Ue.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Ue.sampleRate||48e3),channels:Number(Ue.channels||2),capturedAt:String(Ue.capturedAt||""),receivedAt:String(Ue.receivedAt||""),byteLength:Number(Ue.byteLength||Xe.byteLength),payload:xS};if(!Ut.deviceId||oe)return;if(performance.now()-De>nw){nt();return}if(a1(Ut.mimeType)){dt(Ut,ge,Xe.byteOffset,Xe.byteLength,De);return}nt(),ie("error"),Oe(`Unsupported remote audio format "${Ut.mimeType}". Requesting a bounded PCM restart.`),!qe&&vt<Lf.length&&(xe=0,Ze());return}catch(z){oe||(ie("error"),Oe(z instanceof Error?z.message:String(z)))}}),q.addEventListener("error",()=>{oe||(ie("error"),Oe("Remote audio WebSocket error."))}),q.addEventListener("close",()=>{ha.setSocket(O,null),ce(),oe||ie("closed")}),U=()=>{Ne()}});return F.ready.catch(Y=>{P||(w("error"),E(Y instanceof Error?`Remote audio owner setup failed: ${Y.message}`:"Remote audio owner setup failed."))}),()=>{P=!0,U?U():F.cancel()}},[t,n,r,i,f,h]),{state:y,lastFrame:b,stats:M,error:N}}const z1=3;function iw(t,n,r){const i=Math.max(1,Number(r)||1),l=Math.max(0,Math.min(i,Number(t)-Number(n))),u=Math.min(i/2,z1);return l<=u?0:l>=i-u?1:l/i}function $1(t,n,r){return{normalizedX:iw(t,r.left,r.width),normalizedY:iw(n,r.top,r.height)}}const Up=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),U1=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),ow=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),lv=64;function ah(t,n=80){return String(t||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,n)}function cv(t){const n=ah(t);return Object.prototype.hasOwnProperty.call(ow,n)?ow[n]:n}function lw(t={}){const n=ah(t.key),r=Number.isFinite(Number(t.location))?Math.max(0,Math.min(3,Math.trunc(Number(t.location)))):0,i=r===2?"Right":"Left";return n==="Shift"?`Shift${i}`:n==="Control"?`Control${i}`:n==="Alt"||n==="AltGraph"?`Alt${i}`:n==="Meta"||n==="OS"?`Meta${i}`:n?`Key:${r}:${n}`.slice(0,80):""}function uv(t={}){const n=cv(t.code);return["Shift","Control","Alt","AltGraph","Meta","OS"].includes(n)?lw({...t,key:n}):n||lw(t)}function Ep(t){for(const[n,r]of Object.entries(Up))if(r.includes(t))return n;return""}function Jl(t,n){return Up[n].some(r=>t.has(r))}function cp(t,n,r={},i="",l=""){for(const u of Object.keys(Up)){const f=r[u]===!0,h=Up[u];if(u===i){if(l==="keyup"&&!f)for(const g of h)n.has(g)||t.delete(g);continue}if(f){!Jl(t,u)&&t.size<lv&&t.add(U1[u]);continue}for(const g of h)n.has(g)||t.delete(g)}}function q1(t,n){if(t.length!==n.size)return!1;let r=0;for(const i of n){if(t[r]!==i)return!1;r+=1}return!0}function cw(t){for(const n of[...t])Ep(n)||t.delete(n)}function dv(t){return{shiftKey:Jl(t,"shiftKey"),ctrlKey:Jl(t,"ctrlKey"),altKey:Jl(t,"altKey"),metaKey:Jl(t,"metaKey")}}function W1(t={},n={}){return{shiftKey:t.shiftKey===!0||n.shiftKey===!0,ctrlKey:t.ctrlKey===!0||n.ctrlKey===!0,altKey:t.altKey===!0||n.altKey===!0,metaKey:t.metaKey===!0||n.metaKey===!0}}function G1(t,n,r){const i=uv(t),l=ah(t.key),u=Number(t.keyCode??t.which),f=Number(t.location);return{type:n,key:l,code:i,keyCode:Number.isFinite(u)?Math.max(0,Math.min(65535,Math.trunc(u))):0,location:Number.isFinite(f)?Math.max(0,Math.min(255,Math.trunc(f))):0,text:l.length===1?l:"",repeat:n==="keydown"&&t.repeat===!0,pressedCodes:[...r],...dv(r)}}function V1(){const t=new Set,n=new Set,r=()=>({pressedCodes:[...t]});return{event(i={},l=""){if(l!=="keydown"&&l!=="keyup")return null;const u=uv(i);if(!u)return null;const f=Ep(u),h=t.has(u),g=[...t];return f?l==="keydown"?(cp(t,n,i,f,l),t.size<lv&&t.add(u)):(n.has(u)||t.delete(u),cp(t,n,i,f,l)):(cp(t,n,i),l==="keydown"?t.size<lv&&t.add(u):t.delete(u)),l==="keyup"&&f==="metaKey"&&!Jl(t,"metaKey")&&cw(t),l==="keydown"&&h&&i.repeat!==!0&&q1(g,t)?null:G1(i,l,t)},modifier(i,l){const u=cv(i),f=Ep(u);if(!f)return null;const h=n.has(u);return l===h?null:(l?(n.add(u),t.add(u)):(n.delete(u),t.delete(u),f==="metaKey"&&!Jl(t,"metaKey")&&cw(t)),{type:l?"keydown":"keyup",key:f==="metaKey"?"Meta":f==="ctrlKey"?"Control":f==="altKey"?"Alt":"Shift",code:u,keyCode:0,location:u.endsWith("Right")?2:1,text:"",repeat:!1,...r(),...dv(t)})},reset(i="keyboard-owner-reset",l=!1){const u=t.size>0;return t.clear(),n.clear(),!u&&!l?null:{type:"keyboard.reset",reason:ah(i,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(i={}){const l=typeof i=="string"?cv(i):uv(i);if(t.has(l))return!0;const u=Ep(l);return!!u&&Jl(t,u)},snapshot(){return{...r(),latchedCodes:[...n],...dv(t)}}}}const kS=64,K1=2;function MS(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(1,Math.min(kS,n)):1}function _v(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(0,Math.min(kS-1,n)):0}function AS(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"||n==="linux"||n.startsWith("linux ")}function Q1(t,n,r){const i=String(n||"").trim();if(!i)return t||null;const l=String(r||"").trim();return t&&t.fingerprint===i&&(l?t.sampleId===l:t.sampleId==="")?t:{fingerprint:i,sampleId:l,consecutiveSamples:t?.fingerprint===i?t.consecutiveSamples+1:1}}function NS({platform:t,topologyFingerprint:n,consecutiveTopologySamples:r}){return AS(t)?!!String(n||"").trim()&&Number(r)>=K1:!0}function Y1({requestedIndex:t,monitorCount:n,platform:r,topologyFingerprint:i,consecutiveTopologySamples:l}){const u=_v(t),f=MS(n);return u<f||!NS({platform:r,topologyFingerprint:i,consecutiveTopologySamples:l})?u:f-1}function X1(t,n,r){const i=_v(t),l=MS(n);return i<l||AS(r)?i:l-1}function ic(t){const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:0}function ga(t){return String(t||"").trim()}function up(t,n,r={}){return{deviceId:ga(t),transitionGeneration:ic(n),sessionId:ga(r.sessionId),streamId:ga(r.streamId),commandId:ga(r.commandId),captureGeneration:ic(r.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(r.monitorIndex)||0))}}function Bn(t,n){return!!t&&!!n&&ga(t.deviceId)===ga(n.deviceId)&&ic(t.transitionGeneration)===ic(n.transitionGeneration)}function uw({deviceId:t,requestTransitionGeneration:n,currentTransitionGeneration:r,actualControlOwner:i}){const l=ga(t),u=ic(n),f=ic(r);return!!l&&u>0&&u===f&&(!i||ga(i.deviceId)===l)}function dw(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function dp(t,n,r){const i=ga(t);return!i||!n||ga(n.deviceId)!==i?!1:!r||ga(r.deviceId)!==i}function yg(t,n){if(!t||!n)return!1;const r=ic(n.captureGeneration),i=ga(n.commandId),l=ga(n.sessionId),u=ga(n.streamId),f=Number(t.monitorIndex);return!r||!i||!l||!u||!Number.isInteger(f)||f<0?!1:ga(t.deviceId)===ga(n.deviceId)&&ga(t.sessionId)===l&&ga(t.streamId)===u&&ga(t.commandId)===i&&ic(t.captureGeneration)===r&&ga(t.streamPurpose).toLowerCase()==="control"&&f===n.monitorIndex}function Z1(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function J1(){let t=Promise.resolve(),n=Promise.resolve();const r=i=>{const l=Z1(t,i);return t=l.tail,l.result};return{enqueue:r,enqueueStop(i){const l=r(i);return n=l.then(()=>{}),n.catch(()=>{}),l},enqueueStart(i){const l=n;return r(async()=>(await l,i()))}}}function eN(t={}){return Number(t.generation)===Number(t.currentGeneration)&&t.enabled===!0&&String(t.deviceId||"")!==""&&String(t.deviceId||"")===String(t.currentDeviceId||"")&&t.documentVisible===!0&&t.presentationVisible===!0&&String(t.streamId||"")!==""&&String(t.streamId||"")===String(t.currentStreamId||"")}function tN(t={}){const n=t.ok!==!1,r=n&&t.staleOwner===!0;return{confirmed:n&&(r||t.captureStopConfirmed===!0||t.alreadyStopped===!0),staleOwner:r,preserveNewerOwner:r&&(t.retainedNewerOwner===!0||String(t.activeStreamId||"")!=="")}}const Jn=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:30,slowWallFps:5,fastWallFps:30,directPopulationThrottle:!1,adaptiveMinimumCurrentSampleMs:750,adaptiveDownshiftStableMs:6e3,adaptiveDownshiftConsecutiveSamples:3,missingDeliveryRatio:.72,recoveryDeliveryRatio:.88,recoveryByteRatio:.52,recoveryGapRatio:.7,controlWallReuseMaxFps:30,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function fv(t){return t==="slow"?Jn.slowWallFps:Jn.fastWallFps}function nN({nowMs:t,nextPaintAtMs:n,targetFps:r,sourceFps:i,force:l=!1}){const u=Number.isFinite(Number(t))?Number(t):0,f=Number.isFinite(Number(n))?Math.max(0,Number(n)):0,h=Math.max(1,Number(r)||1),g=Math.max(1,Number(i)||1);if(h>=g)return{shouldPaint:!0,nextPaintAtMs:0,sourceCadencePassthrough:!0};const y=2;if(!l&&f>0&&u+y<f)return{shouldPaint:!1,nextPaintAtMs:f,sourceCadencePassthrough:!1};const w=1e3/h;let b=(l||f<=0?u:f)+w;for(;b<=u+y;)b+=w;return{shouldPaint:!0,nextPaintAtMs:b,sourceCadencePassthrough:!1}}function aN(t,n){const r=Number.isFinite(Number(n))?Math.max(0,Math.floor(Number(n))):Number.POSITIVE_INFINITY;if(r<=0)return[];const i=(Array.isArray(t)?t:[]).filter(f=>f&&String(f.deviceId||"").trim()).slice().sort((f,h)=>{const g=Number.isFinite(Number(f.slotNumber))?Number(f.slotNumber):Number.MAX_SAFE_INTEGER,y=Number.isFinite(Number(h.slotNumber))?Number(h.slotNumber):Number.MAX_SAFE_INTEGER;return g!==y?g-y:String(f.deviceId).localeCompare(String(h.deviceId))}),l=[],u=new Set;for(const f of i){const h=String(f.deviceId).trim();if(!u.has(h)&&(u.add(h),l.push(h),l.length>=r))break}return l}function rN(t,n){const r=Math.max(0,Math.floor(Number(n)||0));return t===!0&&r>0}function _f({mode4Enabled:t,directMode4WallEnabled:n,isMac:r}){return"direct"}function sN({mode4Enabled:t,directMode4WallEnabled:n,adaptiveFps:r,directDeviceCount:i,adaptive:l=!0}){return Math.max(1,Math.floor(Number(r)||1))}function iN({directDeviceCount:t,requestedFps:n,measuredFramesPerSecond:r,measuredPaintFramesPerSecond:i,measuredBytesPerSecond:l,maxBytesPerSecond:u,worstReceiveGapMs:f,worstPaintP95Ms:h,maxFrameGapMs:g}){const y=Math.max(1,Math.floor(Number(t)||1)),w=Math.max(1,Number(n)||1),b=Math.max(0,Number(r)||0),x=Math.max(0,Number(i)||0),M=Math.max(0,Number(l)||0),k=Math.max(1,Number(u)||1),N=Math.max(0,Number(f)||0),E=Math.max(0,Number(h)||0),I=Math.max(1,Number(g)||1),T=y*w,P=T>8&&b<T*Jn.missingDeliveryRatio,U=T>8&&x<T*Jn.missingDeliveryRatio,F=M>k||N>I||P||U,Y=b>=T*Jn.recoveryDeliveryRatio&&x>=T*Jn.recoveryDeliveryRatio&&M<k*Jn.recoveryByteRatio&&N<I*Jn.recoveryGapRatio&&E<I*Jn.recoveryGapRatio;return{expectedFramesPerSecond:T,estimatedMissingFrames:P,estimatedMissingPaints:U,overloaded:F,healthyForRecovery:Y}}function oN({receiveSampleMs:t,paintSampleMs:n,currentGenerationVerified:r,frameRequestedFps:i,adaptiveFps:l}){const u=Number(t),f=Number(n),h=Number(i),g=Number(l);return r===!0&&Number.isFinite(u)&&u>=Jn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(f)&&f>=Jn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(h)&&h>0&&h===g}function lN({deviceCount:t,targetFps:n,adaptive:r=!0}){const i=Math.max(1,Math.floor(Number(t)||1)),l=Math.max(1,Math.min(Jn.scalableAtlasMaxInputFps,Math.floor(Number(n)||Jn.scalableAtlasMaxInputFps)));if(!r)return l;const u=Math.max(Jn.scalableAtlasMinInputFps,Math.min(Jn.scalableAtlasMaxInputFps,Math.floor(Jn.scalableAtlasAggregateInputFps/i)));return Math.min(l,u)}function cN(t,n){return{acceleration:Jn.directDecodeAcceleration,latencyMode:Jn.directLatencyMode}}const md=999;function Jf(t){const n=Number(t);if(!Number.isFinite(n))return 0;const r=Math.floor(n);return r>=1&&r<=md?r:0}function uN(t){return String(t?.deviceName||t?.hostname||t?.deviceId||"Unknown Client").trim()||"Unknown Client"}function TS(t,n){return{deviceId:String(t?.deviceId||"").trim(),label:uN(t),platform:String(t?.platform||"").trim(),slotNumber:Jf(n)}}function ou(t){const n=Array.isArray(t)?t:[],r=new Map,i=new Set;for(const l of n){const u=String(l?.deviceId||"").trim(),f=Jf(l?.slotNumber);if(!u||!f||r.has(u)||i.has(f))continue;const h={deviceId:u,label:String(l?.label||u).trim()||u,platform:String(l?.platform||"").trim(),slotNumber:f};r.set(u,h),i.add(f)}return[...r.values()].sort((l,u)=>l.slotNumber-u.slotNumber||l.deviceId.localeCompare(u.deviceId))}function dN({connectedDevices:t,entries:n,minimumSlotCount:r=0}){const i=ou(n),l=(Array.isArray(t)?t:[]).filter(w=>w?.deviceId).slice().sort((w,b)=>{const x=Jf(w.slotNumber)||md+1,M=Jf(b.slotNumber)||md+1;return x-M||String(w.deviceId).localeCompare(String(b.deviceId))}),u=i.reduce((w,b)=>Math.max(w,b.slotNumber),0),f=Math.min(md,Math.max(0,Math.floor(Number(r)||0),u,l.length)),h=Array.from({length:f},(w,b)=>({slotNumber:b+1,device:null,saved:null,offline:!1,persisted:!1})),g=new Map(l.map(w=>[String(w.deviceId),w])),y=new Set;for(const w of i){for(;h.length<w.slotNumber&&h.length<md;)h.push({slotNumber:h.length+1,device:null,saved:null,offline:!1,persisted:!1});const b=h[w.slotNumber-1];if(!b)continue;const x=g.get(w.deviceId)||null;b.device=x,b.saved=w,b.offline=!x,b.persisted=!0,y.add(w.deviceId)}for(const w of l){const b=String(w.deviceId);if(y.has(b))continue;let x=h.find(M=>!M.device&&!M.saved);if(!x&&h.length<md&&(x={slotNumber:h.length+1,device:null,saved:null,offline:!1,persisted:!1},h.push(x)),!x)break;x.device=w,x.saved=TS(w,x.slotNumber),x.offline=!1,x.persisted=!1,y.add(b)}return h}function RS(t){return ou((Array.isArray(t)?t:[]).flatMap(n=>String(n?.saved?.deviceId||n?.device?.deviceId||"").trim()?[n.device?TS(n.device,n.slotNumber):{...n.saved,slotNumber:n.slotNumber}]:[]))}function fN(t,n,r){const i=String(n||"").trim(),l=Jf(r),u=RS(t);if(!i||!l)return u;const f=u.find(y=>y.deviceId===i);if(!f||f.slotNumber===l)return u;const h=u.find(y=>y.slotNumber===l),g=f.slotNumber;return f.slotNumber=l,h&&(h.slotNumber=g),ou(u)}const nu={revision:0,settings:{security:{accessMode:"trusted-only",allowLanConnections:!0,allowInternetConnections:!1,lockOnControlEnd:!0,idleControlMinutes:30},control:{allowKeyboardMouse:!0,allowRemoteRestart:!1},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},mN=[{id:"connection",label:"Connection",icon:wd},{id:"remote-access",label:"Remote Access",icon:Na},{id:"capture-audio",label:"Capture & Audio",icon:zg},{id:"display",label:"Display",icon:Fp},{id:"agent",label:"Agent",icon:nc}];function Dp(t,n){return t?.settings?.[n]||nu.settings[n]||{}}function fw(t,n){return{...t,settings:{...t.settings,[n.section]:{...Dp(t,n.section),[n.key]:n.value}}}}function bg(t){return{revision:Number(t.revision||0),updatedAt:t.updatedAt,settings:t.settings}}function qs({icon:t,title:n,description:r,children:i,recommended:l=!1}){return o.jsxs("div",{className:"product-setting-row",children:[o.jsx("div",{className:"product-setting-control",children:i}),t&&o.jsx("span",{className:"product-setting-icon",children:o.jsx(t,{size:17})}),o.jsxs("div",{className:"product-setting-copy",children:[o.jsx("strong",{children:n}),l&&o.jsx("em",{children:"Recommended"}),o.jsx("small",{children:r})]})]})}function el({checked:t,onChange:n,label:r}){return o.jsxs("label",{className:"product-switch",children:[o.jsx("input",{"aria-label":r,type:"checkbox",checked:t,onChange:i=>n(i.target.checked)}),o.jsx("span",{})]})}function wg({value:t,onChange:n,options:r,label:i}){return o.jsx("select",{"aria-label":i,value:String(t),onChange:l=>n(l.target.value),children:r.map(([l,u])=>o.jsx("option",{value:l,children:u},l))})}function pN({hubUrl:t="",runtimeRole:n="hub",runtimeDeviceId:r="",sessionAccessToken:i="",initialTab:l="connection",pin:u,agent:f,captureGallery:h,advertisementsHidden:g=!1,onAdvertisementsHiddenChange:y=()=>{}}){const[w,b]=d.useState(l),[x,M]=d.useState(null),[k,N]=d.useState("loading"),[E,I]=d.useState(""),[T,P]=d.useState("idle"),[U,F]=d.useState(""),Y=d.useRef(null),D=d.useRef(null),K=d.useRef([]),ne=d.useRef(Promise.resolve()),q=d.useRef(0),O=d.useRef(0);d.useEffect(()=>{const Me=++O.current;let Ne=!0;return K.current=[],D.current=null,Y.current=null,ne.current=Promise.resolve(),N("loading"),tt("/api/settings",void 0,t).then(He=>{if(!Ne||Me!==O.current)return;const Ve=bg(He);D.current=Ve,Y.current=Ve,M(Ve),N("saved")}).catch(He=>{!Ne||Me!==O.current||(I(He instanceof Error?He.message:String(He)),D.current=nu,Y.current=nu,M(nu),N("failed"))}),()=>{Ne=!1}},[t]);const W=async(Me,Ne,He)=>{const Ve={id:++q.current,section:Me,key:Ne,value:He},ie=O.current;K.current.push(Ve);const Oe=fw(Y.current||D.current||nu,Ve);Y.current=Oe,M(Oe),N("saving"),I(""),ne.current=ne.current.then(async()=>{if(ie!==O.current)return;let $e=null,qe=null;for(let he=0;he<2&&!$e;he+=1){const pe=D.current||nu;try{const Ae=await tt("/api/settings",{method:"PATCH",body:JSON.stringify({revision:pe.revision,[Ve.section]:{[Ve.key]:Ve.value}})},t);$e=bg(Ae)}catch(Ae){if(qe=Ae,he!==0||!String(Ae instanceof Error?Ae.message:Ae).startsWith("409 "))break;try{const Se=await tt("/api/settings",void 0,t);if(ie!==O.current)return;D.current=bg(Se)}catch(Se){qe=Se;break}}}if(ie!==O.current)return;K.current=K.current.filter(he=>he.id!==Ve.id),$e&&(D.current=$e);const vt=D.current||nu,xe=K.current.reduce(fw,vt);Y.current=xe,M(xe),$e?(I(""),N(K.current.length>0?"saving":"saved")):(N(K.current.length>0?"saving":"failed"),I(qe instanceof Error?qe.message:String(qe||"Settings could not be saved.")))}),await ne.current},ce=(Me,Ne)=>He=>{W(Me,Ne,He)},$=async()=>{if(n!=="hub"||!r||!i){P("failed"),F("Sign in to this Hub before changing its runtime role.");return}P("changing"),F("");try{const Me=await tt("/api/runtime/status",void 0,t);await tt("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${i}`},body:JSON.stringify({role:"client"})},t),P("accepted"),await Wx({baseUrl:t,targetRole:"client",previousRuntimePid:Number(Me.runtimePid||0),allowedStates:["running","waiting-auth"]}),hM(5179)}catch(Me){P("failed"),F(Me instanceof Error?Me.message:String(Me))}},ee=Dp(x,"security"),B=Dp(x,"control"),L=Dp(x,"filesAudio"),oe=`settings-panel-${w}`,be=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[u,o.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Runtime role"}),o.jsx("h3",{children:"Use this computer as a Client"})]}),o.jsx(Fp,{size:20})]}),o.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),T==="accepted"?o.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):U?o.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:U}):null,o.jsx("button",{className:"settings-reset",onClick:()=>{$()},disabled:T==="changing"||n!=="hub",type:"button",children:T==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),H=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Remote access"}),o.jsx("h3",{children:"Who may connect?"})]}),o.jsx(Ci,{size:20})]}),o.jsx(qs,{icon:Na,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:o.jsx(wg,{value:String(ee.accessMode),onChange:ce("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})}),o.jsx(qs,{icon:wd,title:"Allow LAN connections",description:"Permit authenticated, encrypted Clients on private network addresses.",recommended:!0,children:o.jsx(el,{checked:!!ee.allowLanConnections,onChange:ce("security","allowLanConnections"),label:"Allow LAN connections"})}),o.jsx(qs,{icon:wd,title:"Allow internet connections",description:"Permit authenticated, end-to-end encrypted Direct or Relay connections from public networks.",children:o.jsx(el,{checked:!!ee.allowInternetConnections,onChange:ce("security","allowInternetConnections"),label:"Allow internet connections"})})]}),o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Session permissions"}),o.jsx("h3",{children:"What may remote users do?"})]}),o.jsx(Ta,{size:20})]}),o.jsx(qs,{icon:Ta,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:o.jsx(el,{checked:!!B.allowKeyboardMouse,onChange:ce("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),o.jsx(qs,{icon:_x,title:"Power actions",description:"Allow confirmed sleep, restart, and shut down commands from the Hub.",children:o.jsx(el,{checked:!!B.allowRemoteRestart,onChange:ce("control","allowRemoteRestart"),label:"Power actions"})}),o.jsx(qs,{icon:zg,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:o.jsx(el,{checked:!!L.allowFileTransfer,onChange:ce("filesAudio","allowFileTransfer"),label:"File transfer"})}),o.jsx(qs,{icon:Zl,title:"Remote audio",description:"Allow sound capture from connected computers.",children:o.jsx(el,{checked:!!L.allowRemoteAudio,onChange:ce("filesAudio","allowRemoteAudio"),label:"Remote audio"})}),o.jsx(qs,{icon:Ci,title:"Lock after Control ends",description:"Release every remote key and button, then lock the controlled computer when the Control owner disconnects.",children:o.jsx(el,{checked:!!ee.lockOnControlEnd,onChange:ce("security","lockOnControlEnd"),label:"Lock after Control ends"})}),o.jsx(qs,{icon:Zl,title:"Control idle timeout",description:"End inactive Control ownership automatically. The visible local stop control is always enabled.",recommended:!0,children:o.jsx(wg,{value:Number(ee.idleControlMinutes),onChange:Me=>ce("security","idleControlMinutes")(Number(Me)),label:"Control idle timeout",options:[["5","5 minutes"],["15","15 minutes"],["30","30 minutes"],["60","1 hour"]]})})]})]}),me=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Capture"}),o.jsx("h3",{children:"Recording defaults"})]}),o.jsx(zg,{size:20})]}),o.jsx(qs,{icon:Zl,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:o.jsx(el,{checked:!!L.rollingBufferEnabled,onChange:ce("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),o.jsx(qs,{icon:Zl,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:o.jsx(wg,{value:Number(L.timelapseIntervalSeconds),onChange:Me=>ce("filesAudio","timelapseIntervalSeconds")(Number(Me)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),Ce=w==="connection"?be:w==="remote-access"?H:w==="capture-audio"?me:w==="display"?o.jsx("div",{className:"settings-tab-content product-settings-content",children:o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Display"}),o.jsx("h3",{children:"Wall appearance"})]}),o.jsx(Fp,{size:20})]}),o.jsx(qs,{icon:Ta,title:"Hide advertisements",description:"Remove the optional advertisement banner from the Wall on this computer.",children:o.jsx(el,{checked:g,onChange:y,label:"Hide advertisements"})})]})}):f;return o.jsxs("section",{className:"settings-page",children:[o.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:mN.map(({id:Me,label:Ne,icon:He})=>o.jsxs("button",{className:w===Me?"active":"",id:`settings-tab-${Me}`,role:"tab","aria-selected":w===Me,"aria-controls":`settings-panel-${Me}`,tabIndex:w===Me?0:-1,onClick:()=>b(Me),type:"button",children:[o.jsx(He,{size:16}),Ne]},Me))}),k==="saving"&&o.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),E&&o.jsx("div",{className:"agent-settings-alert error",role:"alert",children:E}),o.jsx("section",{className:"settings-page-panel",id:oe,role:"tabpanel","aria-labelledby":`settings-tab-${w}`,tabIndex:0,children:Ce})]})}function hN({children:t}){return o.jsx("div",{className:"settings-tab-content",children:t})}const mw={enabled:!1};function pw(t){return{enabled:t?.enabled===!0}}async function gN(t,n,r){let i=null;for(let l=0;l<2;l+=1){const u=await tt("/api/settings",{signal:r},n);if(u.settings.agent?.enabled===t)return;try{await tt("/api/settings",{method:"PATCH",signal:r,body:JSON.stringify({revision:u.revision,agent:{enabled:t}})},n);return}catch(f){if(i=f,l!==0||!String(f instanceof Error?f.message:f).startsWith("409 "))throw f}}throw i}function vN({hubUrl:t}){const[n,r]=d.useState(mw),[i,l]=d.useState(null),[u,f]=d.useState(""),[h,g]=d.useState(""),[y,w]=d.useState(""),b=d.useRef(0),x=d.useRef(null);d.useEffect(()=>{let F=!0;x.current?.abort();const Y=new AbortController;x.current=Y;const D=++b.current;return l(null),r(mw),f(""),w(""),g(""),tt("/api/settings/agent",{signal:Y.signal},t).then(K=>{!F||Y.signal.aborted||D!==b.current||(l(K.settings),r(pw(K.settings)))}).catch(K=>{F&&!Y.signal.aborted&&D===b.current&&w(K instanceof Error?K.message:String(K))}),()=>{F=!1,Y.abort(),x.current===Y&&(x.current=null)}},[t]);const M=(F,Y)=>r(D=>({...D,[F]:Y})),k=F=>{l(F),r(pw(F))},N=()=>({generation:b.current,controller:x.current}),E=F=>F.generation===b.current&&F.controller!==null&&F.controller===x.current&&!F.controller.signal.aborted,I=async()=>{if(!i){w("Agent settings are not available yet.");return}const F=N();if(E(F)){f("save"),w(""),g("");try{if(await gN(n.enabled,t,F.controller.signal),!E(F))return;const Y=await tt("/api/settings/agent",{signal:F.controller.signal},t);if(!E(F))return;k(Y.settings),g("Codex Agent settings saved.")}catch(Y){E(F)&&w(Y instanceof Error?Y.message:String(Y))}finally{E(F)&&f("")}}},T=async()=>{const F=N();if(E(F)){f("test"),w(""),g("");try{const Y=await tt("/api/settings/agent/test",{method:"POST",signal:F.controller.signal,body:JSON.stringify({})},t);if(!E(F))return;const D=await tt("/api/settings/agent",{signal:F.controller.signal},t);if(!E(F))return;k(D.settings);const K=Number.isFinite(Y.connection?.latencyMs)?Math.max(0,Math.round(Y.connection.latencyMs)):null;g(`Codex Agent connection verified${K!==null?` in ${K} ms.`:"."}`)}catch(Y){E(F)&&w(Y instanceof Error?Y.message:String(Y))}finally{E(F)&&f("")}}},P=i?.codexInstallation==="installed"&&i.codexAuth==="signed-in",U=i!==null;return o.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[o.jsx("section",{className:"settings-section-card agent-enable-card",children:o.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[o.jsx("input",{type:"checkbox",checked:n.enabled,onChange:F=>M("enabled",F.target.checked),disabled:!U||u!==""}),o.jsx("span",{children:"Enable Codex Agent"})]})}),y&&o.jsx("div",{className:"agent-settings-alert error",role:"alert",children:y}),h&&o.jsx("div",{className:"agent-settings-alert success",role:"status",children:h}),o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Connection"}),o.jsx("h3",{children:"Codex SDK / CLI"})]}),o.jsx(Na,{size:20})]}),o.jsxs("div",{className:"agent-connection-row",children:[o.jsx("span",{className:`agent-connection-dot ${P?"connected":i?.codexAuth==="not-signed-in"?"unavailable":""}`}),o.jsx("span",{children:i?.codexInstallation==="not-installed"?"Codex SDK not installed":i?.codexAuth==="signed-in"?"Codex CLI signed in":i?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),o.jsxs("button",{className:"settings-reset",onClick:()=>{T()},disabled:u!=="",type:"button",children:[o.jsx(YC,{size:15})," ",u==="test"?"Testing":"Test connection"]})]}),o.jsxs("p",{className:"settings-help",children:[o.jsx(XC,{size:12})," The Hub uses the installed Codex SDK / CLI to plan approved commands and run them through LiveDesk Agent tools on selected computers."]})]}),o.jsx("div",{className:"settings-action-row agent-settings-actions",children:o.jsxs("button",{className:"text-button primary",onClick:()=>{I()},disabled:!U||u!=="",type:"button",children:[o.jsx(ZC,{size:15})," ",u==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function po(t){const[n,r]=d.useState(t),i=d.useRef(t);return d.useEffect(()=>{if(i.current!==t){if(Array.isArray(i.current)&&Array.isArray(t)&&i.current.length===0&&t.length===0)return;i.current=t,r(t)}},[t]),[n,r]}function Pv(t,n){return typeof t=="function"?typeof n=="object"?t(n):t():t}function Sd(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function yN(t,n="data-id"){const r=Sd(t,n);return r?r.getAttribute(n):null}function em(t,n="data-id"){const r=Sd(t,n);return r?rh(r,n):null}function rh(t,n="data-id"){const r=t.getAttribute(n);return r?bN(r):null}function za(t){return typeof t=="string"?":"+t:t}function bN(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function wN(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var Yr=wN();function Fv(t){Object.assign(Yr,t)}function hw(t,n,r){function i(l){const u=Sd(l);if(!u)return;const f=rh(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}Yr.addEvent(t,r,i)}function Cd(t,n){hw(t,n,"click"),n.dblclick&&hw(t,n.dblclick,"dblclick")}function xN(t,n){for(let r=t.length-1;r>=0;r--)if(t[r]===n){t.splice(r,1);break}}function SN(t,n,r){for(let i=0;i<al.length;i++){if(i===r)continue;const l=al[i],u=l.props.parent?.();if(u&&t.contains(u)&&l.node.contains(n))return!0}return!1}var jS=new Date,qp=!1,fp=[],al=[],gw=t=>{const n=t.target;if(qp||!n.isConnected){qp=!1;return}for(let r=al.length-1;r>=0;r--){const{node:i,date:l,props:u}=al[r];if(!(l>jS)&&!i.contains(n)&&i!==n&&(SN(i,n,r)||(u.callback&&u.callback(t),u.modal||t.defaultPrevented)))break}},CN=t=>{jS=new Date,qp=!0;for(let n=al.length-1;n>=0;n--){const{node:r}=al[n];if(!r.contains(t.target)&&r!==t.target){qp=!1;break}}};function go(t,n){fp.length||(fp=[Yr.addGlobalEvent("click",gw,t),Yr.addGlobalEvent("contextmenu",gw,t),Yr.addGlobalEvent("mousedown",CN,t)]),typeof n!="object"&&(n={callback:n});const r={node:t,date:new Date,props:n};return al.push(r),{destroy(){xN(al,r),al.length||(fp.forEach(i=>i()),fp=[])}}}var mp=t=>t.indexOf("bottom")!==-1,pp=t=>t.indexOf("left")!==-1,hp=t=>t.indexOf("right")!==-1,xg=t=>t.indexOf("top")!==-1,vw=t=>t.indexOf("fit")!==-1,Pf=t=>t.indexOf("overlap")!==-1,kN=t=>t.split("-").every(n=>["center","fit"].indexOf(n)>-1),MN=t=>{const n=t.match(/(start|center|end)/);return n?n[0]:null};function AN(t,n){let r=0;const i=Yr.getTopNode(t);for(;t&&t!==i;){const l=getComputedStyle(t).position;if((l==="absolute"||l==="relative"||l==="fixed")&&(r=parseInt(getComputedStyle(t).zIndex)||0),t=t.parentNode,t===n)break}return r}var ma,fr,Ff,Za;function ES(t,n,r="bottom",i=0,l=0){if(!t)return null;ma=i,fr=l,Ff="auto";let u=0,f=0,h=r;const g=DS(t),y=Pf(r)?Yr.getTopNode(t):g;if(!g)return null;const w=g.getBoundingClientRect(),b=t.getBoundingClientRect(),x=y.getBoundingClientRect(),M=window.getComputedStyle(y),k={left:0,top:0,bottom:0,right:0};for(const U in k){const F=`border-${U}-width`;k[U]=parseFloat(M.getPropertyValue(F))}if(n){const U=AN(n,g);u=Math.max(U+1,20)}if(n){if(Za=n.getBoundingClientRect(),vw(r)&&(Ff=Za.width+"px"),r!=="point")if(kN(r))vw(r)?ma=0:(ma=x.width/2,f=1),fr=(x.height-b.height)/2;else{const U=Pf(r)?0:1;ma=hp(r)?Za.right+U:Za.left-U,fr=mp(r)?Za.bottom+1:Za.top;const F=MN(r);F&&(hp(r)||pp(r)?F==="center"?fr-=(b.height-Za.height)/2:F==="end"&&(fr-=b.height-Za.height):(mp(r)||xg(r))&&(F==="center"?ma-=(b.width-Za.width)/2:F==="end"&&(ma-=b.width-Za.width),Pf(r)||(ma+=1)))}}else Za={left:i,right:i,top:l,bottom:l};const N=(pp(r)||hp(r))&&(mp(r)||xg(r));pp(r)&&(f=2);const E=ma-b.width-x.left;n&&pp(r)&&!N&&E<0&&(ma=Za.right,f=0,h=h.replace("left","right"));const I=ma+b.width*(1-f/2)-x.right;if(I>0)if(!hp(r))ma=x.right-k.right-b.width;else{const U=Za.left-x.x-b.width;n&&!N&&U>=0?(ma=Za.left-b.width,h=h.replace("right","left")):ma-=I+k.right}f&&(ma=Math.round(ma-b.width*f/2));const T=E<0||I>0||!N;xg(r)&&(fr=Za.top-b.height,n&&fr<x.y&&T&&(fr=Za.bottom,h=h.replace("top","bottom")));const P=fr+b.height-x.bottom;return P>0&&(n&&mp(r)&&T?(fr-=b.height+Za.height+1,h=h.replace("bottom","top")):fr-=P+k.bottom),ma-=w.left+k.left,fr-=w.top+k.top,ma=(Pf(r)?ma:Math.max(ma,0))+y.scrollLeft,fr=(Pf(r)?fr:Math.max(fr,0))+y.scrollTop,Ff=Ff||"auto",{at:h,x:ma,y:fr,z:u,width:Ff}}function DS(t){const n=Yr.getTopNode(t);for(t&&(t=t.parentElement);t;){const r=getComputedStyle(t).position;if(t===n||r==="relative"||r==="absolute"||r==="fixed")return t;t=t.parentNode}return null}function NN(t){const n=[];let r=t;const i=Yr.getTopNode(t);for(;r&&r!==i&&!r.getAttribute("data-wx-portal-root");)getComputedStyle(r).position==="absolute"&&n.push(r),r=r.parentNode;return n}var yw=new Date().valueOf();function Ov(){return yw+=1,yw}function pr(t){return t<10?"0"+t:t.toString()}function TN(t){const n=pr(t);return n.length==2?"0"+n:n}function IS(t){const n=Math.floor(t/11)*11;return{start:n,end:n+11}}function Sg(t){const n=(t.getDay()+6)%7,r=new Date(t.valueOf());r.setDate(t.getDate()+(3-n)),r.setHours(0,0,0,0);const i=new Date(r.getFullYear(),0,1),l=Math.round((r.getTime()-i.getTime())/864e5);return 1+Math.floor(l/7)}var bw=["",""];function RN(t,n,r){switch(t){case"%d":return pr(n.getDate());case"%m":return pr(n.getMonth()+1);case"%j":return n.getDate();case"%n":return n.getMonth()+1;case"%y":return pr(n.getFullYear()%100);case"%Y":return n.getFullYear();case"%D":return r.dayShort[n.getDay()];case"%l":return r.dayFull[n.getDay()];case"%M":return r.monthShort[n.getMonth()];case"%F":return r.monthFull[n.getMonth()];case"%h":return pr((n.getHours()+11)%12+1);case"%g":return(n.getHours()+11)%12+1;case"%G":return n.getHours();case"%H":return pr(n.getHours());case"%i":return pr(n.getMinutes());case"%a":return((n.getHours()>11?r.pm:r.am)||bw)[0];case"%A":return((n.getHours()>11?r.pm:r.am)||bw)[1];case"%s":return pr(n.getSeconds());case"%S":return TN(n.getMilliseconds());case"%W":return pr(Sg(n));case"%w":{const i=r.weekStart??1;if(i===1)return pr(Sg(n));const l=(n.getDay()-i+7)%7,u=(1-i+7)%7,f=new Date(n.valueOf());return f.setDate(n.getDate()+(u-l)),pr(Sg(f))}case"%c":{let i=n.getFullYear()+"";return i+="-"+pr(n.getMonth()+1),i+="-"+pr(n.getDate()),i+="T",i+=pr(n.getHours()),i+=":"+pr(n.getMinutes()),i+=":"+pr(n.getSeconds()),i}case"%Q":return Math.floor(n.getMonth()/3)+1;default:return t}}var jN=/%[a-zA-Z]/g;function gd(t,n){return typeof t=="function"?t:function(r){return r?(r.getMonth||(r=new Date(r)),t.replace(jN,i=>RN(i,r,n))):""}}function ww(t){return t&&typeof t=="object"&&!Array.isArray(t)}function mv(t,n){for(const r in n){const i=n[r];ww(t[r])&&ww(i)?t[r]=mv({...t[r]},n[r]):t[r]=n[r]}return t}function rm(t){return{getGroup(n){const r=t[n];return i=>r&&r[i]||i},getRaw(){return t},extend(n,r){if(!n)return this;let i;return r?i=mv({...n},t):i=mv({...t},n),rm(i)}}}var EN=$x();const DN="en-US",IN={monthFull:["January","February","March","April","May","June","July","August","September","October","November","December"],monthShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayFull:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],hours:"Hours",minutes:"Minutes",done:"Done",clear:"Clear",today:"Today",am:["am","AM"],pm:["pm","PM"],weekStart:0,clockFormat:24},LN={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},_N={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},LS={core:LN,calendar:IN,formats:_N,lang:DN},Hv=d.createContext(""),_S=d.createContext({}),Ai=d.createContext(null),PS=d.createContext(null),Ua=Object.freeze(Object.defineProperty({__proto__:null,fieldId:PS,helpers:_S,i18n:Ai,theme:Hv},Symbol.toStringTag,{value:"Module"}));function FS(t){const n=d.useContext(PS),[r]=d.useState(()=>t||n||Ov());return r}function Kf({type:t="",css:n="",icon:r="",disabled:i=!1,title:l="",tooltip:u,text:f="",children:h,onClick:g}){const y=d.useMemo(()=>{let b=t?t.split(" ").filter(x=>x!=="").map(x=>"wx-"+x).join(" "):"";return n+(n?" ":"")+b},[t,n]),w=b=>{g&&g(b)};return o.jsxs("button",{title:l,className:`wx-2ZWgb4 wx-button ${y} ${r&&!h?"wx-icon":""}`,disabled:i,onClick:w,"data-tooltip-text":u,children:[r&&o.jsx("i",{className:"wx-2ZWgb4 "+r}),h||f||" "]})}function PN({id:t,label:n="",inputValue:r="",value:i=!1,onChange:l,disabled:u=!1,css:f=""}){const h=FS(t),[g,y]=po(i),w=({target:b})=>{const x=b.checked;y(x),l&&l({value:x,inputValue:r})};return o.jsxs("div",{className:`wx-2IvefP wx-checkbox ${f}`,children:[o.jsx("input",{type:"checkbox",id:h,disabled:u,className:"wx-2IvefP wx-check",checked:g,value:r,onChange:w}),o.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[o.jsx("span",{className:"wx-2IvefP wx-before"}),n&&o.jsx("span",{className:"wx-2IvefP wx-after",children:n})]})]})}function Bv({theme:t="",target:n,children:r}){const i=d.useRef(null),l=d.useRef(null),[u,f]=d.useState(null);i.current||(i.current=document.createElement("div"));const h=d.useContext(Hv);return d.useEffect(()=>{f(n||FN(l.current)||Yr.getTopNode(l.current))},[l.current]),o.jsxs(o.Fragment,{children:[o.jsx("span",{ref:l,style:{display:"none"}}),l.current&&u?EN.createPortal(o.jsx("div",{className:`wx-3ZWsT0 wx-${t||h}-theme`,children:r}),u):null]})}function FN(t){const n=Yr.getTopNode(t);for(;t&&t!==n&&!t.getAttribute("data-wx-portal-root");)t=t.parentNode;return t}function ON({left:t=0,top:n=0,at:r="bottom",parent:i=null,width:l="auto",css:u="",onCancel:f,children:h,trackScroll:g=!1}){const[y,w]=d.useState(0),[b,x]=d.useState(0),[M,k]=d.useState("auto"),[N,E]=d.useState(!1),I=d.useRef(null),T=d.useRef(null),P=d.useRef(f);d.useEffect(()=>{P.current=f},[f]);function U(Y){return i&&(l+"").indexOf("%")>-1?l.replace(/(\d+)%/,(D,K)=>(K=K*i.offsetWidth/100+"px",l.replace(D,K))):l&&l!=="auto"?l:Y}const F=d.useCallback(()=>{if(!I.current)return;const Y=ES(I.current,i,r,t,n);Y&&(w(Y.x),x(Y.y),k(U(Y.width)))},[I,i,r,t,n,l]);return d.useLayoutEffect(()=>{const Y=K=>{P.current&&K.target!==T.current&&I.current&&!I.current.contains(K.target)&&P.current(K)};let D;return requestAnimationFrame(()=>{F(),E(!0),g&&I.current&&(T.current=DS(I.current),T.current&&T.current.addEventListener("scroll",Y,!0)),i&&(D=new ResizeObserver(F),D.observe(i))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",Y,!0),D?.disconnect()}},[]),d.useLayoutEffect(()=>{F()},[i,r,t,n]),d.useEffect(()=>{const Y=D=>{P.current&&P.current(D)};if(I.current)return go(I.current,{callback:Y,parent:()=>i}).destroy},[i]),o.jsx("div",{ref:I,className:["wx-37M6Fj","wx-popup",u].filter(Boolean).join(" "),style:{position:"absolute",visibility:N?"visible":"hidden",top:b+"px",left:y+"px",width:M},children:h})}function HN({position:t="bottom",align:n="start",autoFit:r=!0,onCancel:i=null,width:l="100%",css:u="",children:f}){const h=d.useRef(null),[g,y]=d.useState(t),[w,b]=d.useState(n),x=d.useRef(i);return d.useEffect(()=>{x.current=i},[i]),d.useEffect(()=>{if(r){const M=h.current;if(M){const k=M.getBoundingClientRect(),N=document.body.getBoundingClientRect();k.right>=N.right&&b("end"),k.bottom>=N.bottom&&y("top")}}},[]),d.useEffect(()=>{if(h.current){const M=k=>{x.current&&x.current(k)};return go(h.current,M).destroy}},[]),o.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${w}`,u||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:l},children:f})}function zv({position:t="bottom",align:n="start",autoFit:r=!0,inline:i=!1,onCancel:l,width:u="100%",children:f,...h}){const[g,y]=d.useState(void 0),w=d.useRef(null),b=d.useMemo(()=>`${t}-${n}`,[t,n]);return d.useLayoutEffect(()=>{w.current&&y(w.current.parentNode)},[]),o.jsxs(o.Fragment,{children:[g&&(i?o.jsx(HN,{onCancel:l,position:t,align:n,autoFit:r,width:u,...h,children:f}):o.jsx(Bv,{children:o.jsx(ON,{parent:g,at:b,onCancel:l,width:u,...h,children:f})})),o.jsx("span",{ref:w,className:"wx-portal-node wx-32GZ52"})]})}function sh(){return rm(LS)}function BN(){let t=null,n=!1,r=!1,i,l,u,f;const h=(b,x,M,k,N)=>{i=b,l=x,u=M,f=k,r=N},g=b=>{t=b,n=t!==null,u(t)},y=(b,x)=>{if(!r&&b!==null&&i){const M=i.querySelectorAll(".wx-list > .wx-item")[b];M&&(M.scrollIntoView({block:"nearest"}),x&&x.preventDefault())}},w=(b,x)=>{const M=b===null?null:Math.max(0,Math.min(t+b,l.length-1));M!==t&&(g(M),i?y(M,x):requestAnimationFrame(()=>y(M,x)))};return{move:b=>{const x=em(b),M=l.findIndex(k=>k.id===x);M!==t&&g(M)},keydown:(b,x)=>{switch(b.code){case"Enter":n?f():g(0);break;case"Space":n||g(0);break;case"Escape":u(t=null);break;case"Tab":u(t=null);break;case"ArrowDown":w(n?1:x||0,b);break;case"ArrowUp":w(n?-1:x||0,b);break}},init:h,navigate:w}}const xw=10,zN=d.memo(function({data:t,checkboxes:n,itemTemplate:r,value:i}){return o.jsxs(o.Fragment,{children:[n&&o.jsx(PN,{id:t.id,css:"wx-list-checkbox",value:i&&i.includes(t.id)}),r?Pv(r,{option:t}):t.label]})});function Sw({visibleItems:t,visibleRange:n,navIndex:r,checkboxes:i,itemTemplate:l,value:u,measureRefCallback:f}){return t.map((h,g)=>{const y=n.start+g;return o.jsx("div",{ref:g===0?f:void 0,className:`wx-233fr7 wx-item ${y===r?"wx-focus":""}`,"data-id":h.id,children:o.jsx(zN,{data:h,checkboxes:i,itemTemplate:l,value:u})},h.id)})}function ih({items:t=[],children:n,onSelect:r,onReady:i,virtualized:l=!1,checkboxes:u,multiselect:f,value:h,...g}){const y=d.useRef(),w=d.useRef(!1),b=d.useRef(BN()),[x,M]=d.useState(null),k=d.useRef(x),[N,E]=d.useState(0),[I,T]=d.useState(24),P=d.useRef(!1),U=(d.useContext(Ai)||sh()).getGroup("core"),F=d.useRef(t);d.useEffect(()=>{F.current=t},[t]);const Y=d.useRef(h);d.useEffect(()=>{Y.current=h},[h]);const D=d.useRef(0);d.useEffect(()=>{D.current=I},[I]);const K=d.useCallback(ue=>{ue&&ue.stopPropagation();const Ce=F.current,Me=Y.current,Ne=k.current;let He;const Ve=Ce[Ne]?.id;f?Me&&Me.includes(Ve)?He=Me.filter(ie=>ie!==Ve):He=[...Me||[],Ve]:He=Ve,r&&r({id:He})},[f,r]),ne=d.useRef(K);d.useEffect(()=>{ne.current=K},[K]);const q=d.useCallback(ue=>{if(y.current){let Ce=ue*D.current-y.current.clientHeight+D.current;E(Ce),y.current.scrollTop=Ce}},[D.current]),O=d.useCallback(ue=>{y.current=ue,l&&(ue&&!w.current&&k.current!==null&&requestAnimationFrame(()=>{y.current&&(q(k.current),w.current=!0)}),ue||(w.current=!1))},[q]),W=d.useCallback(ue=>{if(!ue||P.current)return;const Ce=ue.getBoundingClientRect().height;Ce&&(T(Ce),D.current=Ce,P.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,t,ue=>{M(ue),k.current=ue},ue=>ne.current(ue),l)},[t,y.current,l]),d.useEffect(()=>{const ue=(Me,Ne)=>{b.current.navigate(Me,Ne),q(k.current)},Ce=(Me,Ne)=>{const He=k.current,Ve=F.current;if(He!==0&&He!==Ve.length-1&&(Me.key==="ArrowDown"||Me.key==="ArrowUp")&&Me.preventDefault(),b.current.keydown(Me,Ne),y.current){const ie=y.current.scrollTop<=k.current*D.current,Oe=y.current.scrollTop+y.current.clientHeight>=k.current*D.current+D.current;ie?Oe||q(k.current):(y.current.scrollTop=k.current*D.current,E(y.current.scrollTop))}};i&&i({navigate:l?ue:b.current.navigate,keydown:l?Ce:b.current.keydown,move:b.current.move})},[]);const ce=d.useRef(0),$=d.useRef(t);$.current!==t&&($.current=t,ce.current+=1);const ee=d.useCallback(()=>{b.current.navigate(null)},[b]),B=d.useCallback(ue=>{l&&E(ue.target.scrollTop)},[l]),L=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/I),[I,N]),oe=d.useMemo(()=>{if(!l)return{start:0,end:t.length};if(!t.length)return{start:0,end:0};const ue=Math.floor(N/I),Ce=ue+L;return{start:Math.max(0,ue-xw),end:Math.min(t.length,Ce+xw)}},[l,t,N,I,L]),be=d.useMemo(()=>{if(!l)return t;const{start:ue,end:Ce}=oe;return t.slice(ue,Ce).map(Me=>({...Me}))},[l,t,oe]),H=oe.start*I,me=t.length*I;return d.useEffect(()=>{l&&E(0)},[t,l]),d.useEffect(()=>{x===null&&(w.current=!1)},[x]),x===null?null:o.jsx(zv,{onCancel:ee,...g,children:o.jsx("div",{className:"wx-233fr7 wx-list",ref:O,onClick:K,onMouseMove:b.current.move,onScroll:B,children:t.length?l?o.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${me}px`},children:o.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${H}px)`},children:o.jsx(Sw,{visibleRange:oe,visibleItems:be,navIndex:x,measureRefCallback:W,checkboxes:u,itemTemplate:n,value:h})})}):o.jsx(Sw,{visibleRange:oe,visibleItems:be,navIndex:x,measureRefCallback:W,checkboxes:u,itemTemplate:n,value:h}):o.jsx("div",{className:"wx-233fr7 wx-no-data",children:U("No data")})})},ce.current)}function $v({value:t="",id:n,readonly:r=!1,focus:i=!1,select:l=!1,type:u="text",placeholder:f="",disabled:h=!1,error:g=!1,title:y="",tooltip:w,css:b="",icon:x="",clear:M=!1,onChange:k}){const N=FS(n),[E,I]=po(t),T=d.useRef(null),P=d.useMemo(()=>x&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[x,b]),U=d.useMemo(()=>x&&b.indexOf("wx-icon-left")!==-1,[x,b]);d.useEffect(()=>{const ne=setTimeout(()=>{i&&T.current&&T.current.focus(),l&&T.current&&T.current.select()},1);return()=>clearTimeout(ne)},[i,l]);const F=d.useCallback(ne=>{const q=ne.target.value;I(q),k&&k({value:q,input:!0})},[k]),Y=d.useCallback(ne=>k&&k({value:ne.target.value}),[k]);function D(ne){ne.stopPropagation(),I(""),k&&k({value:""})}let K=u;return u!=="password"&&u!=="number"&&(K="text"),d.useEffect(()=>{const ne=Y,q=T.current;return q.addEventListener("change",ne),()=>{q&&q.removeEventListener("change",ne)}},[Y]),o.jsxs("div",{className:`wx-hQ64J4 wx-text ${P} ${g?"wx-error":""} ${h?"wx-disabled":""} ${M?"wx-clear":""}`,"data-tooltip-text":w,children:[o.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:N,readOnly:r,disabled:h,placeholder:f,type:K,title:y,value:E,onInput:F}),M&&!h&&E?o.jsxs(o.Fragment,{children:[o.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:D}),U&&o.jsx("i",{className:`wx-hQ64J4 wx-icon ${x}`})]}):x?o.jsx("i",{className:`wx-hQ64J4 wx-icon ${x}`}):null]})}function $N({date:t,type:n,part:r,onShift:i}){const{calendar:l,formats:u}=d.useContext(Ai).getRaw(),f=t.getFullYear(),h=d.useMemo(()=>{switch(n){case"month":return gd(u.monthYearFormat,l)(t);case"year":return gd(u.yearFormat,l)(t);case"duodecade":{const{start:y,end:w}=IS(f),b=gd(u.yearFormat,l);return`${b(new Date(y,0,1))} - ${b(new Date(w,11,31))}`}default:return""}},[t,n,f,l,u]);function g(){i&&i({diff:0,type:n})}return o.jsxs("div",{className:"wx-8HQVQV wx-header",children:[r!=="right"?o.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>i&&i({diff:-1,type:n})}):o.jsx("span",{className:"wx-8HQVQV wx-spacer"}),o.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),r!=="left"?o.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>i&&i({diff:1,type:n})}):o.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function Uv({onClick:t,children:n}){return o.jsx("button",{className:"wx-3s8W4d wx-button",onClick:t,children:n})}function UN({value:t,current:n,part:r="",markers:i=null,css:l="",onCancel:u,onChange:f}){const h=(d.useContext(Ai)||sh()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),w=(F,Y,D)=>new Date(F.getFullYear(),F.getMonth()+(Y||0),F.getDate()+(D||0));let b=r!=="normal";function x(F){const Y=F.getDay();return Y===0||Y===6}function M(){const F=w(n,0,1-n.getDate());return F.setDate(F.getDate()-(F.getDay()-(g-7))%7),F}function k(){const F=w(n,1,-n.getDate());return F.setDate(F.getDate()+(6-F.getDay()+g)%7),F}const N=d.useRef(0);function E(F,Y){Y.timeStamp!==N.current&&(N.current=Y.timeStamp,Y.stopPropagation(),f&&f(new Date(F)),u&&u())}const I=d.useMemo(()=>r=="normal"?[t?w(t).valueOf():0]:t?[t.start?w(t.start).valueOf():0,t.end?w(t.end).valueOf():0]:[0,0],[r,t]),T=d.useMemo(()=>{const F=M(),Y=k(),D=n.getMonth();let K=[];for(let ne=F;ne<=Y;ne.setDate(ne.getDate()+1)){const q={day:ne.getDate(),in:ne.getMonth()===D,date:ne.valueOf()};let O="";if(O+=q.in?"":" wx-inactive",O+=I.indexOf(q.date)>-1?" wx-selected":"",b){const W=q.date==I[0],ce=q.date==I[1];W&&!ce?O+=" wx-left":ce&&!W&&(O+=" wx-right"),q.date>I[0]&&q.date<I[1]&&(O+=" wx-inrange")}if(O+=x(ne)?" wx-weekend":"",i){const W=i(ne);W&&(O+=" "+W)}K.push({...q,css:O})}return K},[n,I,b,i]),P=d.useRef(null);let U=d.useRef({});return U.current.click=E,d.useEffect(()=>{Cd(P.current,U.current)},[]),o.jsxs("div",{className:`wx-398RBS wx-month ${l}`,children:[o.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map(F=>o.jsx("div",{className:"wx-398RBS wx-weekday",children:F},F))}),o.jsx("div",{className:"wx-398RBS wx-days",ref:P,children:T.map(F=>o.jsx("div",{className:`wx-398RBS wx-day ${F.css} ${F.in?"":"wx-out"}`,"data-id":F.date,children:F.day},F.date))})]})}function qN({value:t,current:n,part:r,onCancel:i,onChange:l,onShift:u}){const f=d.useRef(new Date),[h,g]=po(t||f.current),[y,w]=po(n||f.current),b=d.useContext(Ai).getRaw().calendar,x=b.monthShort||[],M=d.useMemo(()=>y.getMonth(),[y]),k=d.useCallback((I,T)=>{if(I!=null){T.stopPropagation();const P=new Date(y);P.setMonth(I),w(P),u&&u({current:P})}r==="normal"&&g(new Date(y)),i&&i()},[y,r,u,i]),N=d.useCallback(()=>{const I=new Date(OS(h,r)||y);I.setMonth(y.getMonth()),I.setFullYear(y.getFullYear()),l&&l(I)},[h,y,r,l]),E=d.useCallback(I=>{const T=I.target.closest("[data-id]");if(T){const P=parseInt(T.getAttribute("data-id"),10);k(P,I)}},[k]);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-34U8T8 wx-months",onClick:E,children:x.map((I,T)=>o.jsx("div",{className:"wx-34U8T8 wx-month"+(M===T?" wx-current":""),"data-id":T,children:I},T))}),o.jsx("div",{className:"wx-34U8T8 wx-buttons",children:o.jsx(Uv,{onClick:N,children:b.done})})]})}const Cg="wx-1XEF33",WN=({value:t,current:n,onCancel:r,onChange:i,onShift:l,part:u})=>{const f=d.useContext(Ai).getRaw().calendar,[h,g]=po(n),[y,w]=po(t),b=d.useMemo(()=>h.getFullYear(),[h]),x=d.useMemo(()=>{const{start:I,end:T}=IS(b),P=[];for(let U=I;U<=T;++U)P.push(U);return P},[b]),M={click:k};function k(I,T){if(I){T.stopPropagation();const P=new Date(h);P.setFullYear(I),g(P),l&&l({current:P})}u==="normal"&&w(new Date(h)),r&&r()}function N(){const I=new Date(OS(y,u)||h);I.setFullYear(h.getFullYear()),i&&i(I)}const E=d.useRef(null);return d.useEffect(()=>{E.current&&Cd(E.current,M)},[]),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:Cg+" wx-years",ref:E,children:x.map((I,T)=>o.jsx("div",{className:Cg+` wx-year ${b==I?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":I,children:I},T))}),o.jsx("div",{className:Cg+" wx-buttons",children:o.jsx(Uv,{onClick:N,children:f.done})})]})},Cw={month:{component:UN,next:VN,prev:GN},year:{component:qN,next:QN,prev:KN},duodecade:{component:WN,next:XN,prev:YN}};function GN(t){return t=new Date(t),t.setMonth(t.getMonth()-1),t}function VN(t){return t=new Date(t),t.setMonth(t.getMonth()+1),t}function KN(t){return t=new Date(t),t.setFullYear(t.getFullYear()-1),t}function QN(t){return t=new Date(t),t.setFullYear(t.getFullYear()+1),t}function YN(t){return t=new Date(t),t.setFullYear(t.getFullYear()-10),t}function XN(t){return t=new Date(t),t.setFullYear(t.getFullYear()+10),t}function OS(t,n){let r;if(n==="normal")r=t;else{const{start:i,end:l}=t;n==="left"?r=i:n=="right"?r=l:r=i&&l}return r}const ZN=["clear","today"];function JN(t){if(t==="done")return-1;if(t==="clear")return null;if(t==="today")return new Date}function eT({value:t,current:n,onCurrentChange:r,part:i="normal",markers:l=null,buttons:u,css:f="",onShift:h,onChange:g}){const y=d.useContext(Ai).getGroup("calendar"),[w,b]=d.useState("month"),x=Array.isArray(u)?u:u?ZN:[],M=(T,P)=>{T.preventDefault(),g&&g({value:P})},k=()=>{w==="duodecade"?b("year"):w==="year"&&b("month")},N=T=>{const{diff:P,current:U}=T;if(P===0){w==="month"?b("year"):w==="year"&&b("duodecade");return}if(P){const F=Cw[w];r(P>0?F.next(n):F.prev(n))}else U&&r(U);h&&h()},E=T=>{b("month"),g&&g({select:!0,value:T})},I=d.useMemo(()=>Cw[w].component,[w]);return o.jsx("div",{className:`wx-2Gr4AS wx-calendar ${i!=="normal"&&i!=="both"?"wx-part":""} ${f}`,children:o.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[o.jsx($N,{date:n,part:i,type:w,onShift:N}),o.jsxs("div",{children:[o.jsx(I,{value:t,current:n,onCurrentChange:r,part:i,markers:l,onCancel:k,onChange:E,onShift:N}),w==="month"&&x.length>0&&o.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:x.map(T=>o.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:o.jsx(Uv,{onClick:P=>M(P,JN(T)),children:y(T)})},T))})]})]})})}function qv(t){let{words:n=null,optional:r=!1,children:i}=t,l=d.useContext(Ai);const u=d.useMemo(()=>{let f=l;return(!f||!f.extend)&&(f=rm(LS)),n!==null&&(f=f.extend(n,r)),f},[n,r,l]);return o.jsx(Ai.Provider,{value:u,children:i})}function kw(t,n,r,i){if(!t||i){const l=n?new Date(n):new Date;l.setDate(1),r(l)}else if(t.getDate()!==1){const l=new Date(t);l.setDate(1),r(l)}}const tT=["clear","today"];function HS({value:t,current:n,markers:r=null,buttons:i=tT,css:l="",onChange:u}){const[f,h]=po(t),[g,y]=po(n);d.useEffect(()=>{kw(g,f,y,!1)},[f,g]);const w=d.useCallback(x=>{const M=x.value;M?(h(new Date(M)),kw(g,new Date(M),y,!0)):h(null),u&&u({value:M?new Date(M):null})},[u,g]),b=d.useCallback(x=>{y(x)},[y]);return g?o.jsx(qv,{children:o.jsx(eT,{value:f,current:g,markers:r,buttons:i,css:l,onChange:w,onCurrentChange:b})}):null}function nT(t){return t||(t={}),t.width||(t.width="unset"),t}const aT=["clear","today"];function rT({value:t,id:n,disabled:r=!1,error:i=!1,placeholder:l="",format:u="",buttons:f=aT,css:h="",title:g="",tooltip:y,editable:w=!1,clear:b=!1,onChange:x,dropdown:M={}}){const{calendar:k,formats:N}=(d.useContext(Ai)||sh()).getRaw(),E=u||N?.dateFormat;let I=typeof E=="function"?E:gd(E,k);const[T,P]=d.useState(t),[U,F]=d.useState(!1);d.useEffect(()=>{P(t)},[t]);function Y(){F(!1)}function D(q){const O=q===T||q&&T&&q.valueOf()===T.valueOf()||!q&&!T;P(q),O||x&&x({value:q}),setTimeout(Y,1)}const K=d.useMemo(()=>T?I(T):"",[T,I]);function ne({value:q,input:O}){if(!w&&!b||O)return;let W=typeof w=="function"?w(q):q?new Date(q):null;W=isNaN(W)?T||null:W||null,D(W)}return d.useEffect(()=>{const q=Y;return window.addEventListener("scroll",q),()=>window.removeEventListener("scroll",q)},[]),o.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>F(!0),children:[o.jsx($v,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:K,id:n,readonly:!w,disabled:r,error:i,placeholder:l,onInput:Y,onChange:ne,icon:"wxi-calendar",clear:b}),U&&!r&&o.jsx(zv,{onCancel:Y,...nT(M),children:o.jsx(HS,{buttons:f,value:T,onChange:q=>D(q.value)})})]})}function sT({value:t="",options:n=[],textOptions:r=null,placeholder:i="",disabled:l=!1,error:u=!1,title:f="",tooltip:h,textField:g="label",clear:y=!1,css:w="",children:b,onChange:x,dropdown:M={}}){const k=d.useRef(null),N=d.useRef(null);let[E,I]=po(t);function T(D){k.current=D.navigate,N.current=D.keydown}const P=d.useMemo(()=>E||E===0?(r||n).find(D=>D.id===E):null,[E,r,n]),U=d.useCallback(({id:D})=>{(D||D===0)&&(I(D),k.current(null),x&&x({value:D}))},[I,x]),F=d.useCallback(D=>{D.stopPropagation(),I(""),x&&x({value:""})},[I,x]),Y=d.useCallback(()=>n.findIndex(D=>D.id===E),[n,E]);return o.jsxs("div",{className:`wx-2YgblL wx-richselect ${w} ${u?"wx-2YgblL wx-error":""} ${l?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:f,onClick:()=>k.current(Y()),onKeyDown:D=>N.current(D,Y()),tabIndex:0,"data-tooltip-text":h,children:[o.jsx("div",{className:"wx-2YgblL wx-label",children:P?b?b(P):P[g]:i?o.jsx("span",{className:"wx-2YgblL wx-placeholder",children:i}):" "}),y&&!l&&E?o.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:F}):o.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!l&&o.jsx(ih,{items:n,onReady:T,onSelect:U,...M,children:({option:D})=>b?b(D):D[g]})]})}const iT=({options:t=[],value:n="",css:r="",children:i,onChange:l})=>{const[u,f]=d.useState(n),h=g=>{f(g),l&&l({value:g})};return d.useEffect(()=>{f(n)},[n]),o.jsx("div",{className:`wx-0hMO7P wx-segmented ${r}`,children:t.map(g=>o.jsx("button",{className:`wx-0hMO7P wx-segment ${g.css} ${g.id===u?"wx-selected":""}`,title:g.title,onClick:()=>h(g.id),"data-tooltip-text":g.tooltip,children:i?Pv(i,{option:g}):o.jsxs(o.Fragment,{children:[g.icon&&o.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&o.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function oT({notice:t={}}){function n(){t.remove&&t.remove()}return o.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${t.type?t.type:""}`,role:"status","aria-live":"polite",children:[o.jsx("div",{className:"wx-11sNg5 wx-text",children:t.text}),o.jsx("div",{className:"wx-11sNg5 wx-button",children:o.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:n})})]})}function lT({data:t=[]}){return o.jsx("div",{className:"wx-3nwoO9 wx-notices",children:t.map(n=>o.jsx(oT,{notice:n},n.id))})}function pv({title:t="",buttons:n=["cancel","ok"],header:r,children:i,footer:l,css:u="",onConfirm:f,onCancel:h}){const g=(d.useContext(Ai)||sh()).getGroup("core"),y=d.useRef(null);d.useEffect(()=>{y.current?.focus()},[]);function w(x){switch(x.code){case"Enter":{const M=x.target.tagName;if(M==="TEXTAREA"||M==="BUTTON")return;f&&f({event:x});break}case"Escape":h&&h({event:x});break}}function b(x,M){const k={event:x,button:M};M==="cancel"?h&&h(k):f&&f(k)}return o.jsx("div",{className:`wx-1FxkZa wx-modal ${u}`,ref:y,tabIndex:0,onKeyDown:w,children:o.jsxs("div",{className:"wx-1FxkZa wx-window",children:[r||(t?o.jsx("div",{className:"wx-1FxkZa wx-header",children:t}):null),o.jsx("div",{children:i}),l||n&&o.jsx("div",{className:"wx-1FxkZa wx-buttons",children:n.map(x=>o.jsx("div",{className:"wx-1FxkZa wx-button",children:o.jsx(Kf,{type:`block ${x==="ok"?"primary":"secondary"}`,onClick:M=>b(M,x),children:g(x)})},x))})]})})}function cT({children:t},n){const[r,i]=d.useState(null),[l,u]=d.useState([]);return d.useImperativeHandle(n,()=>({showModal:f=>{const h={...f};return i(h),new Promise((g,y)=>{h.resolve=w=>{i(null),g(w)},h.reject=w=>{i(null),y(w)}})},showNotice:f=>{f={...f},f.id=f.id||Ov(),f.remove=()=>u(h=>h.filter(g=>g.id!==f.id)),f.expire!=-1&&setTimeout(f.remove,f.expire||5100),u(h=>[...h,f])}}),[]),o.jsxs(o.Fragment,{children:[t,r&&o.jsx(pv,{title:r.title,buttons:r.buttons,onConfirm:r.resolve,onCancel:r.reject,children:r.message}),o.jsx(lT,{data:l})]})}const uT=d.forwardRef(cT);function dT(t){let{children:n}=t,r=d.useRef();const i=d.useMemo(()=>({showNotice:l=>r.current.showNotice(l),showModal:l=>r.current.showModal(l)}),[]);return o.jsx(_S.Provider,{value:i,children:o.jsx(uT,{ref:r,children:n})})}const fT=({value:t=!1,type:n="",icon:r="",disabled:i=!1,iconActive:l="",onClick:u,title:f="",tooltip:h,css:g="",text:y="",textActive:w="",children:b,active:x,onChange:M})=>{const[k,N]=po(t),E=d.useMemo(()=>(k?"pressed":"")+(n?" "+n:""),[k,n]),I=d.useCallback(T=>{let P=!k;u&&u(T),T.defaultPrevented||(N(P),M&&M({value:P}))},[k,u,M]);return k&&x?o.jsx(Kf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&l||r,onClick:I,disabled:i,children:Pv(x,{value:k})}):b?o.jsx(Kf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&l||r,onClick:I,disabled:i,children:b}):o.jsx(Kf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&l||r,onClick:I,disabled:i})};function mT(){return o.jsx(o.Fragment,{})}function Mw(t){const{fonts:n=!0,children:r}=t;return o.jsx(Hv.Provider,{value:"willow",children:o.jsxs(o.Fragment,{children:[r&&r&&o.jsx("div",{className:"wx-theme wx-willow-theme",children:r}),n&&o.jsxs(o.Fragment,{children:[o.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),o.jsx(mT,{}),o.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Fv(Yr);const Wv={grid:{"Add before":"Add before","Add after":"Add after",Copy:"Copy",Cut:"Cut",Paste:"Paste",Delete:"Delete","New row":"New row","Move up":"Move up","Move down":"Move down",Undo:"Undo",Redo:"Redo",selected:"selected"}};new Date().valueOf();var BS=class{constructor(t){this._nextHandler=null,this._dispatch=t,this.exec=this.exec.bind(this)}async exec(t,n){return this._dispatch(t,n),this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};new Date().valueOf();var pT=class{constructor(t){const n={id:0,$level:0,data:[],parent:null},r=new Map;r.set(0,n),this._pool=r,t&&t.length&&this.parse(t,0)}parse(t,n){const r=this._pool;for(let l=0;l<t.length;l++){const u=t[l];u.parent=u.parent||n,u.data=null,r.set(u.id,u)}for(let l=0;l<t.length;l++){const u=t[l],f=r.get(u.parent);f&&(f.data||(f.data=[]),f.data.push(u))}const i=r.get(n);this.setLevel(i,i.$level+1,!1)}add(t,n){const r=this._pool.get(t.parent||0);t.$level=r.$level+1,this._pool.set(t.id,t),r.data?n===-1?r.data=[...r.data,t]:Aw(r,n,t):r.data=[t]}addAfter(t,n){if(!n)return this.add(t,-1);const r=this.byId(n),i=this.byId(r.parent),l=gp(i,r.id)+1;t.parent=i.id,t.$level=i.$level+1,this.add(t,l)}remove(t){const n=this._pool.get(t);this._remove(n);const r=this._pool.get(n.parent);r.data=r.data.filter(i=>i.id!=t),this._clearBranch(r)}_remove(t){t.data&&t.data.forEach(n=>this._remove(n)),this._pool.delete(t.id)}update(t,n){let r=this._pool.get(t);const i=this._pool.get(r.parent),l=gp(i,r.id);r={...r,...n},i&&l>=0&&(i.data[l]=r,i.data=[...i.data]),this._pool.set(r.id,r)}move(t,n,r){const i=this._pool.get(t),l=n==="child",u=this._pool.get(r),f=u.$level+(l?1:0);if(!i||!u)return;const h=this._pool.get(i.parent),g=l?u:this._pool.get(u.parent);g.data||(g.data=[]);const y=gp(h,i.id);hT(h,y);const w=l?g.data.length:gp(g,u.id)+(n==="after"?1:0);if(Aw(g,w,i),h.id===g.id&&y===w)return null;i.parent=g.id,i.$level!==f&&(i.$level=f,this.setLevel(i,f+1,!0)),this.update(i.id,i),this._clearBranch(h)}_clearBranch(t){t.data&&!t.data.length&&(t.open&&delete t.open,this.update(t.id,{data:null}))}toArray(){const t=[],n=this._pool.get(0).data;return n&&zS(n,t),t}byId(t){return this._pool.get(t)}getBranch(t){return this._pool.get(t).data}forEach(t){this._pool.forEach((n,r)=>{r!==0&&t(n)})}eachChild(t,n){const r=this.byId(n);!r||!r.data||r.data.forEach((i,l)=>{t(this.byId(i.id),l),this.eachChild(t,i.id)})}setLevel(t,n,r){t.data&&(t.data=t.data.map(i=>(r&&(i={...i},this._pool.set(i.id,i)),i.$level=n,i.data&&this.setLevel(i,n+1,r),i)))}};function zS(t,n){t.forEach(r=>{n.push(r),r.open===!0&&zS(r.data,n)})}function hT(t,n){const r=[...t.data];r.splice(n,1),t.data=r}function Aw(t,n,r){const i=[...t.data];i.splice(n,0,r),t.data=i}function gp(t,n){return t?.data.findIndex(r=>r.id===n)}var $S=2,gT=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,r=0){const i={};return this._wrapProperties(n,this._state,this._values,"",i,r),i}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,r,i,l,u,f){for(const h in n){const g=r[h],y=i[h],w=n[h];if(g&&(y===w&&typeof w!="object"||w instanceof Date&&y instanceof Date&&y.getTime()===w.getTime()))continue;const b=l+(l?".":"")+h;g?(g.__parse(w,b,u,f)&&(i[h]=w),f&$S?u[b]=g.__trigger:g.__trigger()):(w&&w.__reactive?r[h]=this._wrapNested(w,w,b,u):r[h]=this._wrapWritable(w),i[h]=w),u[b]=u[b]||null}}_wrapNested(n,r,i,l){const u=this._wrapWritable(n);return this._wrapProperties(n,u,r,i,l,0),u.__parse=(f,h,g,y)=>(this._wrapProperties(f,u,r,h,g,y),!1),u}_wrapWritable(n){const r=[],i=function(){for(let l=0;l<r.length;l++)r[l](n)};return{subscribe:l=>(r.push(l),this._async?setTimeout(l,1,n):l(n),()=>{const u=r.indexOf(l);u>=0&&r.splice(u,1)}),__trigger:()=>{r.length&&(this._async?setTimeout(i,1):i())},__parse:function(l){return n=l,!0}}}};function Nw(t,n){return Object.defineProperty(t,"__reactive",{value:!0,enumerable:!1,writable:!1}),t}var vT=class{constructor(n,r,i,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=r,this._parsers=i,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(u=>{u.in.forEach(f=>{const h=this._triggers.get(f)||[];h.push(u),this._triggers.set(f,h)}),u.out.forEach(f=>{const h=this._sources.get(f)||{};u.in.forEach(g=>h[g]=!0),this._sources.set(f,h)})}),this._routes.forEach(u=>{u.length=Math.max(...u.in.map(f=>US(f,this._sources,1)))}),this._bus=l}init(n){const r={};for(const i in n)if(this._prev[i]!==n[i]){const l=this._parsers[i];r[i]=l?l(n[i]):n[i]}this._prev=this._prev?{...this._prev,...n}:{...n},this.setState(r),this._bus&&this._bus.exec("init-state",r)}setStateAsync(n){const r=this._setter(n,$S);return this._async?Object.assign(this._async.signals,r):this._async={signals:r,timer:setTimeout(this._applyState.bind(this),1)},r}_applyState(){const n=this._async;if(n){this._async=null,this._triggerUpdates(n.signals,[]);for(const r in n.signals){const i=n.signals[r];i&&i()}}}setState(n,r=[]){const i=this._setter(n);return this._triggerUpdates(i,r),i}_triggerUpdates(n,r){const i=Object.keys(n),l=!r.length;r=r||[];for(let u=0;u<i.length;u++){const f=i[u],h=this._triggers.get(f);h&&h.forEach(g=>{r.indexOf(g)==-1&&r.push(g)})}l&&this._execNext(r)}_execNext(n){for(;n.length;){n.sort((i,l)=>i.length<l.length?1:-1);const r=n[n.length-1];n.splice(n.length-1),r.exec(n)}}};function US(t,n,r){const i=n.get(t);if(!i)return r;const l=Object.keys(i).map(u=>US(u,n,r+1));return Math.max(...l)}var yT=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,r,i){let l=this._handlers[n];l?i&&i.intercept?l.unshift(r):l.push(r):l=this._handlers[n]=[r],i&&i.tag&&this._tag.set(r,i.tag)}intercept(n,r,i){this.on(n,r,{...i,intercept:!0})}detach(n){for(const r in this._handlers){const i=this._handlers[r];for(let l=i.length-1;l>=0;l--)this._tag.get(i[l])===n&&i.splice(l,1)}}async exec(n,r){const i=this._handlers[n];if(i)for(let l=0;l<i.length;l++){const u=i[l](r);if(u===!1||u&&u.then&&await u===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,r),r}setNext(n){return this._nextHandler=n}};const cd=1024;function tm(t){return t<cd?`${t} B`:t<cd**2?`${(t/cd).toFixed(1)} KB`:t<cd**3?`${(t/cd**2).toFixed(1)} MB`:`${(t/cd**3).toFixed(1)} GB`}function Tw(t,n){n||(n={key:"name",order:"asc"});const r=t.filter(f=>f.type==="folder"),i=t.filter(f=>f.type!=="folder"),l=r.sort(Rw(n)),u=i.sort(Rw(n));return[...l,...u]}function bT(t,n){return typeof t=="string"?t.localeCompare(n,void 0,{numeric:!0}):typeof t=="object"?t.getTime()-n.getTime():(t??0)-(n??0)}function wT(t,n){return typeof t=="string"?-t.localeCompare(n,void 0,{numeric:!0}):typeof n=="object"?n.getTime()-t.getTime():(n??0)-(t??0)}function Rw({key:t,order:n}){const r=n==="asc"?bT:wT;return(i,l)=>r(i[t],l[t])}function Gv(t,n){const r=t==="/"?1:t.split("/").length;return r>=n.length?null:n[r].id}function xT(t){return t.length>1?t[t.length-2].id:null}let ST=class extends pT{constructor(n){const r={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([r]),this.parse(n,"/")}parse(n,r,i){!n||!n.length||(n.forEach(l=>this.parseId(l,i?r:void 0)),super.parse(n,r))}parseId(n,r){if(n.parent===0)return;const i=n.id,l=i.lastIndexOf("/");if(n.parent=r??(l===0?"/":i.slice(0,l)),n.name=i.slice(l+1),n.type=n.type||"file",n.type!=="folder"){const u=n.name.lastIndexOf("."),f=u!==-1?n.name.slice(u+1):"";n.ext=f!=="new"?f?.toLocaleLowerCase():""}}getParents(n){const r=[];let i=this.byId(n);if(!i)return r;for(;i.id!==0;)r.push(i),i=this.byId(i.parent);return r.reverse()}findFiles(n,r="/"){const i=[],l=n.toLocaleLowerCase();return this.eachChild(u=>{u.name.toLowerCase().indexOf(l)!==-1&&i.push(u)},r),i}add(n,r){const i=this.byId(n.parent||"/"),l=n.data?[...n.data]:null;n.data=null,super.add(n,r??i.data?i.data.length:0),l&&l.forEach(u=>this.add(u))}renameFiles(n,r,i){const l=this.byId(n),u=this.normalizeFile(l,r),f=[];return u.data?.forEach(h=>f.push(this.renameFiles(h.id,u.id,i))),f.length&&(u.data=f),i[n]=u.id,u}copyFiles(n,r,i){const l={};return n.forEach(u=>{const f=this.renameFiles(u,r,l);this.add(f),i&&this.remove(u),l[u]=f.id}),l}moveFiles(n,r){if(this.byId(n[0]).parent!==r)return this.copyFiles(n,r,!0)}serialize(n="/"){const r=[],i=this.byId(n);return i?(i.data?.forEach(l=>{const{id:u,date:f,type:h,size:g,lazy:y}=l,w={id:u,date:f,type:h??"file"};y&&(w.lazy=y),g&&(w.size=g),r.push(w);const b=this.serialize(u);b.length&&r.push(...b)}),r):null}normalizeFile(n,r){const i=n.name,l=i.lastIndexOf("."),u=l!==-1?i.slice(l+1):"",f=u?`.${u}`:"";let h=l!==-1?i.slice(0,l):i,g=r+(r==="/"?"":"/")+h;for(;this.byId(g+f);){const y=".new";g+=y,h+=y}return{...n,id:g+f,name:h+f,parent:r,ext:u.toLocaleLowerCase()}}},CT=class extends gT{in;_router;constructor(n){super({writable:n,async:!1});const r=[];for(let u=0;u<2;u++)r.push({in:["data",`panels.${u}.path`],out:[`panels.${u}._crumbs`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];y[u]={_crumbs:h.getParents(g[u].path)},this.setState({panels:y},f)}}),r.push({in:["data",`panels.${u}.path`,`panels.${u}._sorts`,"search"],out:[`panels.${u}._files`],exec:f=>{const{data:h,panels:g,search:y}=this.getState();let w;y?w=h.findFiles(y,g[u].path):w=h.byId(g[u].path)?.data||[];const{path:b,_sorts:x}=g[u];w=Tw(w,x[b]);const M=[];M[u]={_files:w},this.setState({panels:M},f)}}),r.push({in:["data",`panels.${u}.selected`,`panels.${u}._sorts`],out:[`panels.${u}._selected`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];g[u].selected.forEach(k=>{const N=h.byId(k);N&&y.push(N)});const{path:w,_sorts:b}=g[u],x=Tw(y,b[w]),M=[];M[u]={_selected:x},this.setState({panels:M},f)}});this._router=new vT(super.setState.bind(this),r,{data:u=>new ST(u)});const i=this.in=new yT;i.on("select-file",({id:u,toggle:f,range:h,panel:g,type:y})=>{const{panels:w,activePanel:b}=this.getState();typeof g>"u"&&(g=b),u||(f=h=!1);let x=[...w[g].selected];if(f){const k=x.indexOf(u);k===-1?x.push(u):x.splice(k,1)}else if(h&&w[g]._lastSelected){const k=w[g]._files;let N=k.findIndex(T=>T.id==w[g]._lastSelected),E=k.findIndex(T=>T.id==u);E<N&&([N,E]=[E,N]);const I=k.slice(N,E+1).map(T=>T.id);x=[...new Set([...x,...I])]}else x=u?[u]:[];const M=[];M[g]={selected:x,_lastSelected:u,_selectNavigation:y==="navigation"},this.setState({panels:M})}),i.on("set-path",({id:u,panel:f,selected:h})=>{const{data:g,activePanel:y}=this.getState(),w=g.byId(u);if(w){const b=[];typeof f>"u"&&(f=y),b[f]={path:u},this.setState({panels:b}),i.exec("select-file",{panel:f}),h&&h.forEach(x=>i.exec("select-file",{id:x,panel:f,toggle:!0})),w.lazy&&i.exec("request-data",{id:u})}}),i.on("provide-data",({id:u,data:f})=>{const{mode:h,data:g}=this.getState(),y=g.byId(u);y&&(y.lazy||(y.data=[]),y.lazy=!1,g.parse(f,u,h==="search"),this.setState({data:g}))}),i.on("open-tree-folder",({id:u,mode:f})=>{const{data:h}=this.getState();h.update(u,{open:f}),this.setState({data:h})}),i.on("show-preview",({mode:u})=>{this.setState({preview:u})}),i.on("rename-file",u=>{const{id:f,name:h}=u,{data:g,panels:y}=this.getState(),w=g.byId(f);if(w.name!==h){w.name=h;const b=g.normalizeFile(w,w.parent);u.newId=b.id,b.data=null,g.add(b);let x={[f]:b.id};w.data?.forEach(k=>x={...g.moveFiles([k.id],b.id),...x});const M=y.map(k=>({selected:k.selected,_crumbs:k._crumbs,_lastSelected:k._lastSelected,_sorts:k._sorts}));g.remove(f),this._updatePanels(M,x),this.setState({data:g,panels:M})}}),i.on("create-file",u=>{const{file:f,parent:h}=u,{data:g}=this.getState(),y=g.normalizeFile(f,h);y.type=f.type||"file",u.newId=y.id,g.add(y),this.setState({data:g}),i.exec("select-file",{id:y.id})}),i.on("delete-files",({ids:u})=>{const{data:f,panels:h}=this.getState(),g=h.map(y=>({selected:y.selected,_crumbs:y._crumbs,_lastSelected:y._lastSelected,_sorts:y._sorts}));u.forEach(y=>f.remove(y)),this._updatePanels(g,{}),this.setState({data:f,panels:g})}),i.on("copy-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot copy a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.copyFiles(f,h);u.newIds=f.map(x=>b[x]),this.setState({data:g}),y[w].path==h&&(i.exec("select-file",{}),f.forEach(x=>{i.exec("select-file",{id:b[x],toggle:!0})}))}),i.on("move-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot move a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.moveFiles(f,h);if(b){u.newIds=f.map(M=>b[M]);const x=y.map(M=>({selected:M.selected,_crumbs:M._crumbs,_lastSelected:M._lastSelected,_sorts:M._sorts}));this._updatePanels(x,b,!0),this.setState({data:g,panels:x}),y[w].path==h&&(i.exec("select-file",{}),f.forEach(M=>{i.exec("select-file",{id:b[M],toggle:!0})}))}});let l=null;i.on("filter-files",({text:u})=>{if(!u){l&&this.setState({...l});return}i.exec("select-file",{});const{panels:f,mode:h}=this.getState();l||(l={panels:f,mode:h,search:""}),this.setState({mode:"search",search:u})}),i.on("set-mode",({mode:u})=>{const{activePanel:f}=this.getState(),h=[];h[f]={_selectNavigation:!1};const g={mode:u,search:"",panels:h};l=null,this.setState(g)}),i.on("set-active-panel",({panel:u})=>{this.setState({activePanel:u})}),i.on("sort-files",({key:u,order:f,panel:h,path:g})=>{const{activePanel:y,panels:w}=this.getState();h=h??y,g=g??w[h].path;const b=[];b[h]={_sorts:{...w[h]._sorts,[g]:{key:u,order:f}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const n=[];for(let i=0;i<2;i++)n[i]=Nw({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...n[i]});const r={panels:Nw(n),data:[],search:""};this._router.init(r)}init(n){const r={...n};this._router.init(r)}setState(n,r){return this._router.setState(n,r)}getFile(n){const{data:r}=this.getState();return r.byId(n)||null}serialize(n){const{data:r}=this.getState();return r.serialize(n)}_updatePanels(n,r,i){const{data:l}=this.getState();n.forEach(u=>{const f=[];u.selected.forEach(y=>{l.byId(y)?f.push(y):!i&&r[y]&&f.push(r[y])}),u.selected=f,l.byId(u._lastSelected)||(u._lastSelected=i?null:r[u._lastSelected]||null);const h={};Object.keys(u._sorts).forEach(y=>{l.byId(y)?h[y]=u._sorts[y]:r[y]&&!i&&(h[r[y]]=u._sorts[y])}),u._sorts=h;const g=u._crumbs[u._crumbs.length-1];g?.id!=="/"&&(r[g.id]?u.path=r[g.id]:l.byId(g.id)||(u.path="/"))})}_isPlacedIntoSelf(n,r){return n.some(i=>i===r||this.getState().data.getParents(r).some(l=>l.id===i))}};function kT(t){switch(t){case"body":return[{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"}];case"add":return[{icon:"mdi mdi-folder-plus-outline",text:"Add new file",id:"add-file"},{icon:"mdi mdi-file-plus-outline",text:"Add new folder",id:"add-folder"},{icon:"mdi mdi-file-upload-outline",text:"Upload file",id:"upload",comp:"upload"}];case"multiselect":return[{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{comp:"separator"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}];default:return[t==="folder"?null:{icon:"wxi-download",text:"Download",hotkey:"Ctrl+D",id:"download"},{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"},{comp:"separator"},{icon:"wxi-edit",text:"Rename",hotkey:"Ctrl+R",id:"rename"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}].filter(n=>n!==null)}}function MT(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function AT(t,n="data-id"){const r=MT(t,n);return r?r.getAttribute(n):null}new Date().valueOf();function NT(t,n){const{api:r}=n;function i(u,f){const h=n.getPanel(),g=h.selected,y=f.ctrlKey||f.metaKey,w=f.shiftKey;let b;const x=g?.[0]?r.getFile(g[0]):null;g?.length?g.length>1?b=n.menuOptions("multiselect"):b=n.menuOptions(x.type,x):b=n.menuOptions("body");const M=`${y?"ctrl+":""}${w?"shift+":""}${u}`,k=b?b.find(E=>E.hotkey?.toLowerCase()===M):!1,N=n.performAction;if(k)switch(M){case"ctrl+c":N("copy");break;case"ctrl+x":N("move");break;case"ctrl+v":N("paste",x);break;case"delete":N("delete");break;case"ctrl+r":f.preventDefault(),N("rename",x);break;case"ctrl+d":f.preventDefault(),N("download",x);break;default:k.handler?.({context:x})}switch(u){case"enter":{if(y||w)break;const{_crumbs:E,_selectNavigation:I}=h;if(I){const T=xT(E);if(T){const P=Gv(T,E);r.exec("set-path",{id:T,selected:[P]})}}else if(g.length===1){const T=r.getFile(g[0]);T&&r.exec(T.type==="folder"?"set-path":"open-file",{id:T.id})}break}case"arrowup":case"arrowleft":{const{_files:E,_selected:I,path:T,_selectNavigation:P}=h;let U;if(I.length){const F=I.at(0).id,Y=E.findIndex(D=>D.id===F);if(Y!==-1){const D=Y-1;E[D]?U=E[D].id:T!=="/"&&!(y||w)&&r.exec("select-file",{type:"navigation"})}}else{if(P)break;if(T!=="/"){r.exec("select-file",{type:"navigation"});break}U=E.at(0)?.id}U&&r.exec("select-file",{id:U,toggle:y,range:w});break}case"arrowdown":case"arrowright":{const{_files:E,_selected:I,path:T,_selectNavigation:P}=h;let U;if(I.length){const F=I.at(-1).id,Y=E.findIndex(D=>D.id===F);if(Y!==-1){const D=Y+1;E[D]&&(U=E[D].id)}}else{if(T!=="/"&&!P){r.exec("select-file",{type:"navigation"});break}U=E.at(0)?.id}U&&r.exec("select-file",{id:U,toggle:y,range:w});break}}}function l(u){const f=u.code.replace("Key","").toLowerCase();i(f,u),f=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&r.exec("set-active-panel",{panel:+AT(h,"data-panel")})})}return t.addEventListener("keydown",l),{destroy:()=>{t.removeEventListener("keydown",l)}}}function TT(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function RT(t,n="data-id"){const r=t.getAttribute(n);return r?jT(r):null}function jT(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function ET(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var DT=ET();new Date().valueOf();function qS(t){const[n,r]=d.useState(t),i=d.useRef(t);return d.useEffect(()=>{if(i.current!==t){if(Array.isArray(i.current)&&Array.isArray(t)&&i.current.length===0&&t.length===0)return;i.current=t,r(t)}},[t]),[n,r]}function IT(t,n,r){const[i,l]=d.useState(()=>n);return t||console.warn(`Writable ${r} is not defined`),d.useEffect(()=>t?t.subscribe(f=>{l(()=>f)}):void 0,[t]),i}function Lt(t,n){const r=t.getState(),i=t.getReactiveState();return IT(i[n],r[n],n)}function LT(t,n){const r=d.useRef(n);r.current=n;const[i,l]=d.useState(1);return d.useEffect(()=>t.subscribe(f=>{r.current=f,l(h=>h+1)}),[t]),[r.current,i]}function Vs(t,n){const r=t.getState(),i=t.getReactiveState();return LT(i[n],r[n])}function WS(t){const n={};return t.split(";").forEach(r=>{const[i,l]=r.split(":");if(l){let u=i.trim();u.indexOf("-")&&(u=u.replace(/-([a-z])/g,(f,h)=>h.toUpperCase())),n[u]=l.trim()}}),n}function GS(t){let n=t,r=[];return{subscribe:h=>{r.push(h),h(n)},unsubscribe:h=>{r=r.filter(g=>g!==h)},set:h=>{n=h,r.forEach(g=>g(n))},update:h=>{n=h(n),r.forEach(g=>g(n))}}}function jw(t,n,r){function i(l){const u=TT(l);if(!u)return;const f=RT(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}return DT.addEvent(t,r,i)}function _T(t,n){const r=[jw(t,n,"click")];return n.dblclick&&r.push(jw(t,n.dblclick,"dblclick")),()=>{r.forEach(i=>i())}}function VS(t,n){return t.map((r,i)=>{const l=n(r,i);return r.data&&r.data.length&&(l.data=VS(r.data,n)),l}).filter(Boolean)}function KS(t,n){const r=[];return t.forEach(i=>{if(i.data){const l=KS(i.data,n);l.length&&r.push({...i,data:l})}else n(i)&&r.push(i)}),r}function PT(t){return VS(t,(n,r)=>{const i={...n,id:n.id||Ov()};return i.type&&(i.comp=i.type),i.comp==="separator"&&t[r-1]?.comp==="separator"?null:i})}const QS={};function FT(t){return QS[t]||t}function OT(t,n){QS[t]=n}function HT({onClick:t,onShow:n,option:r}){const i=d.useRef(null),l=d.useCallback(()=>{n(r.data?r.id:!1,i.current)},[n,r]),u=d.useCallback(h=>{if(r.data){h.stopPropagation(),n(r.id,i.current);return}t(h)},[t,n,r]),f=d.useMemo(()=>r&&r.comp?FT(r.comp):null,[r]);return o.jsxs("div",{ref:i,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":za(r.id),onMouseEnter:l,onClick:u,children:[r.icon?o.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${r.icon}`}):null,r.comp?f?o.jsx(f,{item:r,option:r}):null:o.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",r.text," "]}),r.subtext?o.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:r.subtext}):null,r.data?o.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function Vv({options:t,left:n=0,top:r=0,at:i="bottom",parent:l=null,mount:u=null,context:f=null,css:h="",onClick:g,onCancel:y}){const[w,b]=d.useState(-1e4),[x,M]=d.useState(-1e4),[k,N]=d.useState(20),[E,I]=d.useState(),T=d.useRef(null),[P,U]=d.useState(!1),[F,Y]=d.useState(null),D=d.useCallback(()=>{const $=ES(T.current,l,i,n,r);$&&(b($.x),M($.y),I($.width));let ee=$?.z??20;const B=l?NN(l):[];let L=0;for(const oe of B){const be=parseInt(getComputedStyle(oe).zIndex,10);be>L&&(L=be)}L>=ee&&(ee=L+1),N(ee)},[l,i,n,r]);d.useEffect(()=>{u&&u(D)},[]);const K=d.useCallback(()=>{U(!1)},[]),ne=d.useCallback(($,ee)=>{U($),Y(ee)},[]),q=d.useMemo(()=>PT(t),[t]);d.useEffect(()=>{D()},[l,D]);const O=d.useRef(g),W=d.useRef(y),ce=d.useRef(l);return d.useEffect(()=>{O.current=g},[g]),d.useEffect(()=>{W.current=y},[y]),d.useEffect(()=>{ce.current=l},[l]),d.useEffect(()=>{if(!T.current)return;function $(ee){W.current?W.current(ee):O.current&&O.current({action:null,option:null})}return go(T.current,{callback:$,modal:!0,parent:()=>ce.current}).destroy},[]),o.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:x+"px",left:w+"px",width:E,zIndex:k},onMouseLeave:K,children:q.map($=>o.jsxs(d.Fragment,{children:[$.comp==="separator"?o.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):o.jsx(HT,{option:$,onShow:ne,onClick:ee=>{if(!$.data&&!ee.defaultPrevented){const B={context:f,action:$,option:$,event:ee};$.handler&&$.handler(B),g&&g(B),ee.stopPropagation()}}}),$.data&&P===$.id?o.jsx(Vv,{css:h,options:$.data,at:"right-overlap",parent:F,context:f,onClick:g,onCancel:y}):null]},$.id))})}const YS=d.forwardRef(function(t,n){const{options:r,at:i="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,[w,b]=d.useState(null),[x,M]=d.useState(null),[k,N]=d.useState(0),[E,I]=d.useState(0),T=d.useRef(null),P=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),U=d.useMemo(()=>w!==null&&f?KS(r,K=>f(K,w)):r,[w,f,r]);function F(K){M(null),y&&y(K)}function Y(K){if(T.current===K){T.current=null;return}M(null),y&&y({action:null,option:null})}const D=d.useCallback((K,ne)=>{if(!K){M(null);return}if(K.defaultPrevented)return;const q=K.target;if(q&&q.dataset&&q.dataset.menuIgnore)return;if(x&&x===q){M(null),K.preventDefault();return}N(K.clientX+1),I(K.clientY+1);let O=typeof ne<"u"?ne:em(q,P);l&&(O=l(O,K),!O)||(b(O),M(q),T.current=K.nativeEvent||K,K.preventDefault())},[x,P,l]);return d.useImperativeHandle(n,()=>({show:D}),[D]),o.jsxs(o.Fragment,{children:[g?o.jsx("span",{onClick:D,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,x?o.jsx(Bv,{children:o.jsx(Vv,{css:h,at:i,top:E,left:k,parent:x,context:w,onClick:F,onCancel:Y,options:U},x)}):null]})}),BT=d.forwardRef(function(t,n){const{options:r,at:i="bottom",css:l="",children:u,onClick:f}=t,[h,g]=d.useState(null),y=d.useRef(null);function w(k){g(null),f&&f(k)}function b(k){if(y.current===k){y.current=null;return}g(null),f&&f({action:null,option:null})}const x=d.useCallback(k=>{g(k.target),y.current=k.nativeEvent||k,k.preventDefault()},[]);d.useImperativeHandle(n,()=>({show:x}),[x]);function M(k){let N=k.target;for(;!N.dataset.menuIgnore;)g(N),N=N.parentNode}return o.jsxs(o.Fragment,{children:[o.jsx("span",{onClick:M,"data-menu-ignore":"true",children:u}),h?o.jsx(Bv,{children:o.jsx(Vv,{css:l,at:i,parent:h,options:r,onClick:w,onCancel:b})}):null]})}),zT=d.forwardRef(function(t,n){const{options:r,at:i="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,w=d.useRef(null),b=d.useCallback((x,M)=>{w.current.show(x,M)},[]);return d.useImperativeHandle(n,()=>({show:b}),[b]),o.jsxs(o.Fragment,{children:[g?o.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,o.jsx(YS,{css:h,at:i,options:r,resolver:l,dataKey:u,filter:f,ref:w,onClick:y})]})}),$T={uploader:{B:"B",KB:"KB",MB:"MB",GB:"GB",TB:"TB",PB:"PB",EB:"EB","Drop files here or":"Drop files here or","select files":"select files"}};let UT=class{constructor(n,r,i,l,u){this.setFiles=n,this.setReady=r,this.setSignal=i,this.setDrag=l,u&&u.length&&this.setFiles(u)}open(n){this.setSignal(["click",n||{}])}getState(){let n="server";const r=this.files;for(let i=0;i<r.length;i++){if(r[i].status==="client")return"client";r[i].status==="error"&&(n="error")}return n}droparea(n,r){r=r||{};const i=()=>{r.dragEnter&&r.dragEnter(),this.setDrag(!0)},l=()=>{r.dragLeave&&r.dragLeave(),this.setDrag(!1)},u=h=>{h.preventDefault()},f=h=>{h.preventDefault(),this.setDrag(!1),this.setSignal(["drop",r,h]),r.dragLeave&&r.dragLeave(),r.drop&&r.drop()};return n.addEventListener("dragenter",i),n.addEventListener("dragleave",l),n.addEventListener("dragover",u,!0),n.addEventListener("drop",f,!0),()=>{n.removeEventListener("dragenter",i),n.removeEventListener("dragleave",l),n.removeEventListener("dragover",u,!0),n.removeEventListener("drop",f,!0)}}updateFile(n,r){const i=this.files.findIndex(u=>u.id===n);if(i===-1)return;const l=[...this.files];return l[i]={...l[i],...r},this.files=l,this.setFiles(this.files),this.files[i]}deleteFile(n){this.files=this.files.filter(r=>r.id!==n),this.setFiles(this.files)}addFile(n,r){r?this.files=[...this.files,n]:this.files=[n],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function XS(t){const[n,r]=d.useState([]),[i,l]=d.useState(Promise.resolve(null)),[u,f]=d.useState(null),[h,g]=d.useState(!1),y=d.useRef();return y.current||(y.current=new UT(r,l,f,g,t)),y.current.files=n,y.current.ready=i,y.current.signal=u,y.current.drag=h,y.current}function qT(t,n){{if(t){const r=t.getGroup(n);if(r)return r}return rm($T).getGroup(n)}}const WT=()=>Math.random().toString(36).substr(2,9),GT=({data:t,accept:n="",multiple:r=!0,folder:i=!1,uploadURL:l="",apiOnly:u=!1,disabled:f=!1,children:h,onChange:g,onUpload:y})=>{const w=d.useRef(null),b=d.useRef(null),[x,M]=d.useState({}),k=XS(),N=t||k,E=d.useContext(Ua.i18n),I=qT(E,"uploader");d.useEffect(()=>{w.current&&i&&(w.current.webkitdirectory=!0)},[i]),d.useEffect(()=>{if(!u&&b.current&&!f)return N.droparea(b.current)},[u,f,b]);const T=q=>{const O=new FormData;return O.append("upload",q.file),fetch(l,{method:"POST",body:O}).then(W=>W.json()).then(W=>({id:q.id,...W}),()=>({id:q.id,status:"error"})).catch(W=>(console.log(W),{id:q.id,status:"error"}))},P=(q,O)=>{const W=N.updateFile(q,O),ce={...W,status:N.getState()};W&&W.uploaded&&W.uploaded(ce),y&&y(ce),W.temp&&N.deleteFile(W.id)},U=q=>{if(!q)return;const O=typeof l=="function"?l(q):T(q);N.setReady(O.then(W=>{W.status=W.status||"server",P(q.id,W)}).catch(W=>{P(q.id,{status:"error",error:W})}))},F=(q,O)=>{const W={...O||x,id:WT(),status:"client",name:q.name,file:q};W.selected&&W.selected(W),g&&g(W),N.addFile(W,r),U(W),w.current&&(w.current.value="")},Y=(q,O,W)=>{q.isFile?q.file(ce=>{F(ce,W)}):q.isDirectory&&q.createReader().readEntries(ce=>{ce.forEach($=>{Y($,O+$.name+"/",W)})})},D=q=>{Array.from(q.target.files).forEach(O=>F(O))},K=(q,O)=>{Array.from(q.dataTransfer.items).forEach(W=>{const ce=W.webkitGetAsEntry();ce&&Y(ce,"",O)})},ne=()=>{w.current&&w.current.click()};return d.useEffect(()=>{if(N.signal){const[q,O,W]=N.signal;M(O),q==="click"?ne():q==="drop"&&K(W,O),N.setSignal(null)}},[N.signal]),u?o.jsxs(o.Fragment,{children:[o.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h]}):o.jsxs("div",{className:`wx-at1A8tb8 wx-label ${N.drag?"wx-active":""} ${f?"wx-disabled":""}`,ref:b,children:[o.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h||o.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:o.jsxs("span",{children:[I("Drop files here or")," ",o.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:ne,children:I("select files")})]})})]})};new Date().valueOf();function VT(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in n){const i=t[r],l=n[r];if(!oh(i,l))return!1}return!0}function oh(t,n){if(typeof t=="number"||typeof t=="string"||typeof t=="boolean"||t===null)return t===n;if(typeof t!=typeof n||(t===null||n===null)&&t!==n||t instanceof Date&&n instanceof Date&&t.getTime()!==n.getTime())return!1;if(typeof t=="object")if(Array.isArray(t)&&Array.isArray(n)){if(t.length!==n.length)return!1;for(let r=t.length-1;r>=0;r--)if(!oh(t[r],n[r]))return!1;return!0}else return VT(t,n);return t===n}function hv(t){if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t);if(t instanceof Array)return t.map(hv);const n={};for(const r in t)n[r]=hv(t[r]);return n}var ZS=2,KT=class{constructor(t){t&&(this._writable=t.writable,this._async=t.async),this._values={},this._state={}}setState(t,n=0){const r={};return this._wrapProperties(t,this._state,this._values,"",r,n),r}getState(){return this._values}getReactive(){return this._state}_wrapProperties(t,n,r,i,l,u){for(const f in t){const h=n[f],g=r[f],y=t[f];if(h&&(g===y&&typeof y!="object"||y instanceof Date&&g instanceof Date&&g.getTime()===y.getTime()))continue;const w=i+(i?".":"")+f;h?(h.__parse(y,w,l,u)&&(r[f]=y),u&ZS?l[w]=h.__trigger:h.__trigger()):(y&&y.__reactive?n[f]=this._wrapNested(y,y,w,l):n[f]=this._wrapWritable(y),r[f]=y),l[w]=l[w]||null}}_wrapNested(t,n,r,i){const l=this._wrapWritable(t);return this._wrapProperties(t,l,n,r,i,0),l.__parse=(u,f,h,g)=>(this._wrapProperties(u,l,n,f,h,g),!1),l}_wrapWritable(t){const n=[],r=function(){for(let i=0;i<n.length;i++)n[i](t)};return{subscribe:i=>(n.push(i),this._async?setTimeout(i,1,t):i(t),()=>{const l=n.indexOf(i);l>=0&&n.splice(l,1)}),__trigger:()=>{n.length&&(this._async?setTimeout(r,1):r())},__parse:function(i){return t=i,!0}}}},QT=class{constructor(t,n,r,i){typeof t=="function"?this._setter=t:this._setter=t.setState.bind(t),this._routes=n,this._parsers=r,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(l=>{l.in.forEach(u=>{const f=this._triggers.get(u)||[];f.push(l),this._triggers.set(u,f)}),l.out.forEach(u=>{const f=this._sources.get(u)||{};l.in.forEach(h=>f[h]=!0),this._sources.set(u,f)})}),this._routes.forEach(l=>{l.length=Math.max(...l.in.map(u=>JS(u,this._sources,1)))}),this._bus=i}init(t){const n={};for(const r in t)if(this._prev[r]!==t[r]){const i=this._parsers[r];n[r]=i?i(t[r]):t[r]}this._prev=this._prev?{...this._prev,...t}:{...t},this.setState(n),this._bus&&this._bus.exec("init-state",n)}setStateAsync(t){const n=this._setter(t,ZS);return this._async?Object.assign(this._async.signals,n):this._async={signals:n,timer:setTimeout(this._applyState.bind(this),1)},n}_applyState(){const t=this._async;if(t){this._async=null,this._triggerUpdates(t.signals,[]);for(const n in t.signals){const r=t.signals[n];r&&r()}}}setState(t,n=[]){const r=this._setter(t);return this._triggerUpdates(r,n),r}_triggerUpdates(t,n){const r=Object.keys(t),i=!n.length;n=n||[];for(let l=0;l<r.length;l++){const u=r[l],f=this._triggers.get(u);f&&f.forEach(h=>{n.indexOf(h)==-1&&n.push(h)})}i&&this._execNext(n)}_execNext(t){for(;t.length;){t.sort((r,i)=>r.length<i.length?1:-1);const n=t[t.length-1];t.splice(t.length-1),n.exec(t)}}};function JS(t,n,r){const i=n.get(t);if(!i)return r;const l=Object.keys(i).map(u=>JS(u,n,r+1));return Math.max(...l)}var YT=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(t,n,r){let i=this._handlers[t];i?r&&r.intercept?i.unshift(n):i.push(n):i=this._handlers[t]=[n],r&&r.tag&&this._tag.set(n,r.tag)}intercept(t,n,r){this.on(t,n,{...r,intercept:!0})}detach(t){for(const n in this._handlers){const r=this._handlers[n];for(let i=r.length-1;i>=0;i--)this._tag.get(r[i])===t&&r.splice(i,1)}}async exec(t,n){const r=this._handlers[t];if(r)for(let i=0;i<r.length;i++){const l=r[i](n);if(l===!1||l&&l.then&&await l===!1)return}return this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};function XT(t){return n=>n[t]}function ZT(t){return(n,r)=>n[t]=r}function oc(t,n){return(n.getter||XT(n.id))(t)}function kg(t,n,r){return(n.setter||ZT(n.id))(t,r)}function JT(t,n){const r=document.createElement("a");r.href=URL.createObjectURL(t),r.download=n,document.body.appendChild(r),r.click(),document.body.removeChild(r)}function ac(t,n){let r=oc(t,n)??"";return n.template?r=n.template(r,t,n):n.optionsMap&&(Array.isArray(r)?r=r.map(i=>n.optionsMap.get(i)).join(", "):r=n.optionsMap.get(r)),typeof r>"u"?"":r+""}function eR(t,n){const r=/\n|"|;|,/;let i="";const l=n.rows||`
|
|
173
|
+
`):String(t||""),M=d.useMemo(()=>v1(t),[x]),k=d.useMemo(()=>M.find(I=>hd(I)==="loopback")||M[0]||Dn,[M]),N=d.useCallback(async I=>{if(!n){i(null),u([]),y(""),h("");return}let T=null;const P=Date.now(),U=M.filter(F=>(w.current.get(F)||0)<=P);if(U.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const F of U)try{const[Y,D]=await Promise.all([tt("/api/remote/status",{signal:I,timeoutMs:Jb},F),tt("/api/remote/devices",{signal:I,timeoutMs:Jb},F)]);if(I?.aborted)throw I.reason||new Error("LiveDesk Hub snapshot cancelled.");if(!Array.isArray(D.devices))throw new Error("Invalid Hub devices response.");w.current.delete(F),i(Y),u(D.devices),y(F),h("");return}catch(Y){if(I?.aborted)throw Y;T=Y,w.current.set(F,Date.now()+1e4)}throw y(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[n,M]),E=d.useCallback(()=>{w.current.clear(),Op(b,()=>N()).catch(I=>{h(I instanceof Error?I.message:String(I))})},[N]);return d.useEffect(()=>{if(!n){i(null),u([]),y(""),h("");return}let I=!0,T=null;const P=new AbortController,U=()=>{Op(b,()=>N(P.signal)).catch(Y=>{I&&!P.signal.aborted&&h(Y instanceof Error?Y.message:String(Y))}).finally(()=>{I&&!P.signal.aborted&&(T=window.setTimeout(U,p1))})};return U(),()=>{I=!1,P.abort(new Error("LiveDesk Hub snapshot polling stopped.")),T!==null&&window.clearTimeout(T)}},[n,N]),{status:r,devices:l,error:f,refresh:E,hubBaseUrl:g||k,hubCandidates:M}}function w1(t){const[n,r]=d.useState(null),[i,l]=d.useState(""),u=t?.user?.id||"",f=d.useCallback(async()=>{if(!u){r(null);return}const{data:h,error:g}=await Pt.from(Zb).select("*").eq("user_id",u).maybeSingle();if(g){l(g.message);return}r(h),l("")},[u]);return d.useEffect(()=>{f()},[f]),d.useEffect(()=>{if(!u)return;const h=Pt.channel(`livedesk-remote-host-targets-${u.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:Zb,filter:`user_id=eq.${u}`},g=>r(g.new)).subscribe();return()=>{Pt.removeChannel(h)}},[u]),{target:n,error:i,refresh:f}}function x1(t){const[n,r]=d.useState(null),[i,l]=d.useState(!1),[u,f]=d.useState(""),h=t?.user?.id||"",g=d.useCallback(async()=>{if(!h){r(null),f(""),l(!1);return}l(!0);const{data:w,error:b}=await Pt.from(m1).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){f(b.message),l(!1);return}r(w),f(""),l(!1)},[h]);d.useEffect(()=>{g()},[g]);const y=d.useMemo(()=>!n||n.status!=="active"?!1:n.expires_at?new Date(n.expires_at).getTime()>Date.now():!0,[n]);return{entitlement:n,licensed:y,loading:i,error:u,refresh:g}}const Vf={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},S1=2500,C1=3e4,k1=64*1024,M1=64*1024,A1=64,gg=1500,N1=150,T1=1e3,R1=6,j1=R1,CS=new Map;function E1(t){return CS.get(t)}const ew={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function D1(t,n,r){const i=Number(n);if(!Number.isFinite(i)||i<=0)return 0;const l=r-i,u=t.minimumHubClockOffsetMs;if(!Number.isFinite(u)||l<Number(u))return t.minimumHubClockOffsetMs=l,0;const f=Math.max(0,l-Number(u));return f>C1?(t.minimumHubClockOffsetMs=l,0):f}function ht(t){if(t==null||t==="")return;const n=Number(t);return Number.isFinite(n)?n:void 0}const I1=["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"];function L1(t){return Number(t.nativeCaptureTelemetryVersion)>=5&&I1.every(n=>ht(t[n])!==void 0)&&typeof t.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t.nativeCopyTelemetryAvailable===!0}function _1(t,n,r){if(!t||typeof t!="object")return null;const i=t,l=String(i.deviceId||n||"").trim(),u=String(i.sessionId||"").trim(),f=String(i.streamId||"").trim(),h=i.streamPurpose==="control"?"control":i.streamPurpose==="wall"?"wall":null,g=String(i.commandId||"").trim(),y=Number(i.captureGeneration||0),w=Number(i.monitorIndex??-1);return!l||l!==n||!h||h!==r||!u||!f||!g||!Number.isSafeInteger(y)||y<=0||!Number.isSafeInteger(w)||w<0?null:{deviceId:l,sessionId:u,streamId:f,streamPurpose:h,commandId:g,captureGeneration:y,monitorIndex:w}}function tw(t,n,r=Dn,i={}){const[l,u]=d.useState(new Map),[f,h]=d.useState("idle"),[g,y]=d.useState(""),[w,b]=d.useState(Vf),x=d.useRef(new Map),M=d.useRef(new Map),k=d.useRef(new Map),N=d.useRef(null);N.current===null&&(N.current=HA());const E=d.useRef(0),I=d.useRef(new Map),T=d.useRef({enabled:!1,token:"",reason:""}),P=d.useRef(new Map),U=d.useRef(null),F=d.useRef(null),[Y,D]=d.useState(0),K=d.useRef(i.onFrame),ne=d.useRef(i.onStreamReady),q=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),O=d.useMemo(()=>[...t].sort().join(","),[t]),W=n&&O.length>0,ce=d.useRef(!1);d.useLayoutEffect(()=>(ce.current=W,()=>{ce.current=!1}),[W]);const $=Number.isFinite(i.fps)?Number(i.fps):2,ee=Number.isFinite(i.maxWidth)?Number(i.maxWidth):640,B=Number.isFinite(i.maxHeight)?Number(i.maxHeight):360,L=Number.isFinite(i.quality)?Number(i.quality):45,oe=Number.isFinite(i.configurationRefreshMs)?Math.max(0,Math.round(Number(i.configurationRefreshMs))):0,be=String(i.frameMode||i.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",H=i.streamPurpose==="control"?"control":"wall",me=i.forceRestart===!0,ue=String(i.forceRestartToken||"").trim(),Ce=String(i.restartReason||"").trim();T.current={enabled:me,token:ue,reason:Ce};const Me=d.useMemo(()=>{const he=Object.entries(i.monitorSelections||{}).filter(([pe])=>!!pe).sort(([pe],[Ae])=>pe.localeCompare(Ae));return JSON.stringify(Object.fromEntries(he))},[i.monitorSelections]),Ne=d.useMemo(()=>{const he=Object.entries(i.connectionSessionIds||{}).filter(([pe])=>!!pe).map(([pe,Ae])=>[pe,String(Ae||"").trim()]).sort(([pe],[Ae])=>pe.localeCompare(Ae));return JSON.stringify(Object.fromEntries(he))},[i.connectionSessionIds]);d.useEffect(()=>{K.current=i.onFrame},[i.onFrame]),d.useEffect(()=>{ne.current=i.onStreamReady},[i.onStreamReady]);const He=d.useCallback((he,pe="livedesk-frame-socket-release")=>{BA(he,pe,N.current)},[]),Ve=d.useCallback(he=>{const pe=P.current.get(he);pe!==void 0&&(window.clearTimeout(pe),P.current.delete(he))},[]),ie=d.useCallback((he,pe=!0)=>{for(const Ae of P.current.values())window.clearTimeout(Ae);P.current.clear();for(const Ae of k.current.values())Ae.expectedBinding=void 0,He(Ae,he);k.current.clear(),I.current.clear(),x.current=new Map,M.current.clear(),q.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},pe&&(u(new Map),y(""),b(Vf),h("idle"))},[He]),Oe=d.useCallback(()=>{const he=[...k.current.values()].map(pe=>pe.socket);if(he.length===0){h("idle");return}if(he.some(pe=>pe.readyState===WebSocket.OPEN)){h("open");return}if(he.some(pe=>pe.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),$e=d.useCallback((he,pe,Ae,Se)=>{if(pe.disposed||pe.socket.readyState!==WebSocket.OPEN)return!1;try{return pe.socket.send(JSON.stringify({...pe.payload,type:"restart-live",deviceIds:[he],forceRestart:!0,restartReason:Ae,restartToken:Se})),pe.expectedBinding=void 0,Qb(pe.sparseTelemetry),!0}catch{return!1}},[]),qe=d.useCallback((he,pe)=>{if(!ce.current||pe.disposed||!he||he.byteLength<5)return;const Ae=Date.now(),Pe=new DataView(he).getUint32(0,!1);if(Pe<=0||Pe+4>he.byteLength)return;const Qe=new Uint8Array(he,4,Pe),Z=JSON.parse(Lv.decode(Qe));WA(Z,pe.sparseTelemetry,pe.expectedBinding);const $t=ht(Z.hubPacketEpochMs),Ee=$t!==void 0&&$t>0?$t:void 0,Ge=D1(pe,Ee,Ae);if(Ge>S1)return;const ze=new Uint8Array(he,4+Pe),Ft=ht(Z.nativeCaptureTelemetryVersion),Ze=ht(Z.nativeCaptureTelemetryAgeMs),nt=ht(Z.hubClientDropped),lt=ht(Z.hubClientQueueDepth),Tt=ht(Z.hubClientQueueLimit),Mt=ht(Z.hubClientBufferedBytes),rt=nt!==void 0&<!==void 0&&Tt!==void 0&&Mt!==void 0,dt={deviceId:String(Z.deviceId||""),kind:Z.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(Z.frameSeq||0),streamFrameSeq:Number(Z.streamFrameSeq||0)||void 0,streamId:String(Z.streamId||""),commandId:Z.commandId?String(Z.commandId):void 0,sessionId:Z.sessionId?String(Z.sessionId):void 0,captureGeneration:Number(Z.captureGeneration||0)||void 0,currentGenerationVerified:!1,streamPurpose:Z.streamPurpose?String(Z.streamPurpose):void 0,width:Number(Z.width||0),height:Number(Z.height||0),sourceWidth:Number(Z.sourceWidth||0)||void 0,sourceHeight:Number(Z.sourceHeight||0)||void 0,mimeType:String(Z.mimeType||"image/jpeg"),mode:Z.mode?String(Z.mode):void 0,frameMode:Z.frameMode?String(Z.frameMode):void 0,frameProfile:Z.frameProfile?String(Z.frameProfile):void 0,encoding:Z.encoding?String(Z.encoding):void 0,codec:Z.codec?String(Z.codec):void 0,compression:Z.compression?String(Z.compression):void 0,pixelFormat:Z.pixelFormat?String(Z.pixelFormat):void 0,bytesPerPixel:Number(Z.bytesPerPixel||0)||0,uncompressedByteLength:Number(Z.uncompressedByteLength||0)||0,h264Format:Z.h264Format?String(Z.h264Format):void 0,isKeyFrame:Z.isKeyFrame===!0,chunkType:Z.chunkType?String(Z.chunkType):void 0,timestampUs:Number(Z.timestampUs||0)||0,durationUs:Number(Z.durationUs||0)||0,sourceGapMs:Number(Z.sourceGapMs||0)||0,agentSendGapMs:Number(Z.agentSendGapMs||0)||0,agentSendDurationMs:Number(Z.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(Z.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(Z.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(Z.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(Z.agentFrameAgeMs||0)||0,inputFeedbackEventId:Z.inputFeedbackEventId?String(Z.inputFeedbackEventId):void 0,inputFeedbackInputSeq:ht(Z.inputFeedbackInputSeq),inputFeedbackInputType:Z.inputFeedbackInputType?String(Z.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:ht(Z.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:ht(Z.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:ht(Z.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:ht(Z.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:ht(Z.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:ht(Z.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:ht(Z.inputFeedbackApplyToCaptureMs),inputFeedbackCaptureTimestampAvailable:typeof Z.inputFeedbackCaptureTimestampAvailable=="boolean"?Z.inputFeedbackCaptureTimestampAvailable:void 0,nativeCaptureTelemetryAvailable:typeof Z.nativeCaptureTelemetryAvailable=="boolean"?Z.nativeCaptureTelemetryAvailable:void 0,nativeCaptureTelemetryVersion:Ft===void 0?void 0:Math.max(0,Ft),nativeCaptureTelemetryAgeMs:Ze===void 0?void 0:Math.max(0,Ze),nativeEncoderHardwareAccelerationKnown:typeof Z.nativeEncoderHardwareAccelerationKnown=="boolean"?Z.nativeEncoderHardwareAccelerationKnown:void 0,nativeEncoderHardwareAccelerated:typeof Z.nativeEncoderHardwareAccelerated=="boolean"?Z.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:Z.nativeEncoderHardwareQueryStatus?String(Z.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureDisplayId:ht(Z.nativeCaptureDisplayId),nativeCaptureFps:ht(Z.nativeCaptureFps),nativeCompressionFps:ht(Z.nativeCompressionFps),nativeEncodedFps:ht(Z.nativeEncodedFps),nativeCaptureSampleCount:ht(Z.nativeCaptureSampleCount),nativeEncodableFrameCount:ht(Z.nativeEncodableFrameCount),nativeSkippedFrameCount:ht(Z.nativeSkippedFrameCount),nativeCompressionOutputCount:ht(Z.nativeCompressionOutputCount),nativeEncodedFrameCount:ht(Z.nativeEncodedFrameCount),nativeEncodeFramesInFlight:ht(Z.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:ht(Z.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:ht(Z.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:ht(Z.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:ht(Z.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:ht(Z.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:ht(Z.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:ht(Z.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:ht(Z.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:ht(Z.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:ht(Z.nativeOutputQueueDepth),nativeOutputQueueBytes:ht(Z.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:ht(Z.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:ht(Z.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:ht(Z.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof Z.nativeOutputQueueAwaitingKeyFrame=="boolean"?Z.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof Z.nativeCopyTelemetryAvailable=="boolean"?Z.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:ht(Z.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:ht(Z.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:ht(Z.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:ht(Z.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:ht(Z.pipePayloadAllocationCount),pipePayloadCopyCount:ht(Z.pipePayloadCopyCount),pipePayloadCopiedBytes:ht(Z.pipePayloadCopiedBytes),handoffDroppedFrameCount:ht(Z.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:ht(Z.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:ht(Z.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:Z.nativeCaptureResourceTelemetryAvailable===!0?L1(Z):Z.nativeCaptureResourceTelemetryAvailable===!1?!1:void 0,nativeCaptureTelemetryAt:Z.nativeCaptureTelemetryAt?String(Z.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(Z.droppedByAgent||0)||0,hubIngressDropped:Number(Z.hubIngressDropped||0)||0,hubClientDropped:nt,transport:Z.transport?String(Z.transport):void 0,videoTransport:Z.videoTransport?String(Z.videoTransport):void 0,frameTransportActive:Z.frameTransportActive?String(Z.frameTransportActive):void 0,frameTransportProtocol:Z.frameTransportProtocol?String(Z.frameTransportProtocol):void 0,frameTransportState:Z.frameTransportState?String(Z.frameTransportState):void 0,frameTransportReason:Z.frameTransportReason?String(Z.frameTransportReason):void 0,frameTransportChangedAt:Z.frameTransportChangedAt?String(Z.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(Z.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(Z.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:Z.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:rt,hubClientQueueDepth:lt,hubClientQueueLimit:Tt,hubClientBufferedBytes:Mt,udpIncompleteFrames:Number(Z.udpIncompleteFrames||0)||0,hardwareEncoder:Z.hardwareEncoder?String(Z.hardwareEncoder):void 0,platformProfile:Z.platformProfile?String(Z.platformProfile):void 0,monitorIndex:Number.isFinite(Number(Z.monitorIndex))?Number(Z.monitorIndex):void 0,monitorCount:Number.isFinite(Number(Z.monitorCount))?Number(Z.monitorCount):void 0,requestedFps:Number(Z.requestedFps||0)||0,effectiveFps:Number(Z.effectiveFps||0)||0,captureTimingAvailable:Z.captureTimingAvailable===!0,captureAverageMs:ht(Z.captureAverageMs),captureP95Ms:ht(Z.captureP95Ms),slowFrameCount:Number(Z.slowFrameCount||0)||0,captureHelperRestarts:Number(Z.captureHelperRestarts||0)||0,capturedAt:String(Z.capturedAt||""),receivedAt:String(Z.receivedAt||""),hubPacketAt:Z.hubPacketAt?String(Z.hubPacketAt):void 0,hubPacketEpochMs:Ee,browserReceivedEpochMs:Ae,hubPacketTransitAgeMs:Ee!==void 0?Ge:void 0,byteLength:Number(Z.byteLength||ze.byteLength),contentHash:Z.contentHash?String(Z.contentHash):void 0,captureMs:ht(Z.captureMs),captureStageMs:ht(Z.captureStageMs),convertMs:Number(Z.convertMs||0)||0,compressMs:Number(Z.compressMs||0)||0,captureSourceSerial:Number(Z.captureSourceSerial||0)||0,captureSourceSkipped:Number(Z.captureSourceSkipped||0)||0,deltaTileSize:Number(Z.deltaTileSize||0)||0,deltaTileCount:Number(Z.deltaTileCount||0)||0,deltaVisualTileCount:Number(Z.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(Z.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(Z.deltaTotalTiles||0)||0,payload:ze};if(!dt.deviceId)return;const G=pe.expectedBinding;if(!G)return;const ge=dt.deviceId===G.deviceId&&String(dt.sessionId||"")===G.sessionId&&dt.streamId===G.streamId&&String(dt.commandId||"")===G.commandId&&Number(dt.captureGeneration||0)===G.captureGeneration&&Number(dt.monitorIndex??-1)===G.monitorIndex&&String(dt.streamPurpose||"")===G.streamPurpose;if(!ge)return;dt.currentGenerationVerified=ge;const De=Number(pe.payload.monitorSelections?.[dt.deviceId]);if(Number.isFinite(De)&&Number.isFinite(Number(dt.monitorIndex))&&Number(dt.monitorIndex)!==De)return;const z={streamId:pe.lastFrameStreamId,commandId:pe.lastFrameCommandId,order:pe.lastFrameOrder},ae=Number(dt.streamFrameSeq||dt.frameSeq||0),Te=!!z.commandId&&!!dt.commandId,Ue=z.streamId===dt.streamId&&(!Te||z.commandId===dt.commandId),Xe=z.order;if(Ue&&Xe>=ae&&(Xe===ae||Te))return;pe.lastFrameStreamId=dt.streamId,pe.lastFrameCommandId=dt.commandId||"",pe.lastFrameOrder=ae;const at=q.current;at.totalFrames+=1,at.totalBytes+=ze.byteLength,at.sampleFrames+=1,at.sampleBytes+=ze.byteLength;const kt=!x.current.has(dt.deviceId)&&!M.current.has(dt.deviceId),At=PA(M.current,dt);kt&&(x.current.set(dt.deviceId,At),M.current.delete(dt.deviceId),u(new Map(x.current))),K.current?.(dt)},[]);d.useEffect(()=>{if(!n||!O)return;q.current.sampleStartedAt=performance.now();const he=window.setInterval(()=>{if(!ce.current)return;const pe=performance.now(),Ae=q.current,Se=Math.max(1,pe-Ae.sampleStartedAt);b({totalFrames:Ae.totalFrames,totalBytes:Ae.totalBytes,framesPerSecond:Ae.sampleFrames*1e3/Se,bytesPerSecond:Ae.sampleBytes*1e3/Se,sampleMs:Se,lastUpdatedAt:Date.now()}),u(FA(x.current,M.current)),Ae.sampleFrames=0,Ae.sampleBytes=0,Ae.sampleStartedAt=pe},2e3);return U.current=he,()=>{window.clearInterval(he),U.current===he&&(U.current=null)}},[n,O]),d.useEffect(()=>{const he=()=>{const pe=new Set,Ae=[...k.current.values()];for(;Ae.length>0;){const Z=Ae.pop();!Z||pe.has(Z)||(pe.add(Z),Z.handoffFrom&&Ae.push(Z.handoffFrom))}const Se=[...x.current.values(),...M.current.values()],Pe=[...pe],Qe=N.current?.snapshot()||{closingSocketCount:0,closingSocketTimerCount:0,closingSocketTimeoutCount:0};return{deviceKey:O,active:ce.current,socketCount:Pe.length+Qe.closingSocketCount,openSocketCount:Pe.filter(Z=>Z.socket.readyState===WebSocket.OPEN).length,connectingSocketCount:Pe.filter(Z=>Z.socket.readyState===WebSocket.CONNECTING).length,closingSocketCount:Qe.closingSocketCount,closingSocketTimerCount:Qe.closingSocketTimerCount,closingSocketTimeoutCount:Qe.closingSocketTimeoutCount,expectedBindingCount:Pe.filter(Z=>!!Z.expectedBinding).length,reconnectTimerCount:P.current.size,statsTimerCount:U.current===null?0:1,configurationRefreshTimerCount:F.current===null?0:1,restartTokenCount:I.current.size,retainedFrameCount:Se.length,retainedPayloadBytes:Se.reduce((Z,$t)=>Z+Math.max(0,Number($t.payload?.byteLength||0)),0)}};return ov.add(he),()=>{ov.delete(he)}},[O]),d.useEffect(()=>{const he=O?O.split(",").filter(Boolean):[];if(!W){ie(n?"livedesk-no-devices":"livedesk-stream-inactive");return}const pe=new Set(he),Ae=performance.now();for(const Se of P.current.keys())pe.has(Se)||Ve(Se);for(const[Se,Pe]of k.current.entries())pe.has(Se)||(Ve(Se),He(Pe,"livedesk-device-unsubscribed"),k.current.delete(Se),I.current.delete(Se),x.current.delete(Se),M.current.delete(Se));q.current.sampleStartedAt<=0&&(q.current.sampleStartedAt=Ae,b({...Vf,lastUpdatedAt:Date.now()}));for(const Se of he){Ve(Se);const Pe=Number(i.monitorSelections?.[Se]),Qe=Number.isInteger(Pe)&&Pe>=0?Pe:0,Z={[Se]:Qe},$t={type:"subscribe",deviceIds:[Se],autoStartLive:n,fps:$,maxWidth:ee,maxHeight:B,quality:L,mode:be,frameMode:be,streamPurpose:H,monitorSelections:Z},Ee=String(i.connectionSessionIds?.[Se]||"").trim(),Ge=JSON.stringify({subscribePayload:$t,connectionSessionId:Ee}),ze=k.current.get(Se),Ft=Number(ze?.payload.monitorSelections?.[Se]),Ze=Number(Z[Se]),nt=!!ze&&Number.isFinite(Ft)&&Number.isFinite(Ze)&&Ft!==Ze,lt=!!ze&&ze?.connectionSessionId!==Ee;if(ze){const Te=ze.socket.readyState===WebSocket.CONNECTING||ze.socket.readyState===WebSocket.OPEN;if(ze.payloadKey===Ge&&Te&&!ze.disposed)continue}const Tt=ze&&(ze.socket.readyState===WebSocket.CONNECTING||ze.socket.readyState===WebSocket.OPEN)&&!ze.disposed?ze.handoffFrom&&!ze.handoffCompleted?ze.handoffFrom:ze:void 0,Mt=ze&&ze!==Tt?ze:void 0,rt=new WebSocket(Yp(`/api/remote/frames/ws?devices=${encodeURIComponent(Se)}`,r),Xp(r));rt.binaryType="arraybuffer";const dt=qA(),G={socket:rt,payload:$t,payloadKey:Ge,connectionSessionId:Ee,generation:E.current+1,monitorRestartToken:nt?`monitor-${Se}-${Ze}-${E.current+1}`:"",disposed:!1,handoffFrom:Tt,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:dt,releaseOwnedState:()=>Qb(dt)};E.current=G.generation,(nt||lt)&&(x.current.delete(Se),M.current.delete(Se),u(new Map(x.current))),k.current.set(Se,G),Mt&&(Mt.handoffFrom=void 0,He(Mt,"livedesk-subscription-superseded"));const ge=()=>{if(!ce.current||G.disposed||k.current.get(Se)!==G){He(G,"livedesk-stale-frame-socket");return}Ve(Se),y("");const Te=T.current,Ue=Te.enabled&&(!Te.token||I.current.get(Se)!==Te.token),Xe=Ue||G.monitorRestartToken!=="",at=Ue?Te.token:G.monitorRestartToken,kt=Ue?Te.reason:G.monitorRestartToken?"monitor-selection-change":"";rt.send(JSON.stringify({...G.payload,forceRestart:Xe,restartReason:Xe?kt:"",restartToken:Xe?at:""})),Ue&&Te.token&&I.current.set(Se,Te.token);const At=G.handoffFrom;G.handoffFrom=void 0,G.handoffCompleted=!0,At&&!At.disposed&&He(At,"livedesk-subscription-replaced"),Oe()},De=Te=>{if(!ce.current||G.disposed||k.current.get(Se)!==G)return;if(typeof Te.data=="string"){try{const Xe=JSON.parse(Te.data),at=(kt,At=!0)=>{const Ut=_1(kt,Se,H);return Ut?(G.expectedBinding=Ut,At&&ne.current?.(Ut),!0):!1};if(Xe?.type==="RemoteFrameSubscriptionError")y(String(Xe.error||"control-stream-start-failed"));else if(Xe?.type==="RemoteFrameLiveAutoStart"){const At=(Array.isArray(Xe.skipped)?Xe.skipped:[]).find(Ut=>Ut?.deviceId===Se);if(At)At.reason==="CAPTURE_TRANSITION_IN_PROGRESS"&&At.retryScheduled===!0?y(""):y(String(At.reason||"control-stream-start-failed"));else if(Array.isArray(Xe.started)){const Ut=Xe.started.find(Qt=>Qt?.deviceId===Se);Ut&&(y(""),at(Ut,Ut.ready===!0))}}else Xe?.type==="RemoteFrameStreamReady"&&Xe.deviceId===Se&&at(Xe)&&y("")}catch{}return}const Ue=Te.data instanceof ArrayBuffer?Te.data:null;Ue&&(y(""),qe(Ue,G))},z=()=>{!ce.current||G.disposed||k.current.get(Se)!==G||h("connecting")},ae=()=>{const Te=!G.disposed;G.disposed=!0,G.handoffCompleted=!0;const Ue=G.detachListeners;G.detachListeners=void 0,Ue?.();const Xe=k.current.get(Se);let at=!1;if(Xe===G){const kt=G.handoffFrom;G.handoffFrom=void 0,kt&&!kt.disposed&&(kt.socket.readyState===WebSocket.CONNECTING||kt.socket.readyState===WebSocket.OPEN)?(k.current.set(Se,kt),at=!0):k.current.delete(Se)}if(Oe(),Te&&ce.current&&Xe===G&&!at){const kt=window.setTimeout(()=>{P.current.get(Se)===kt&&P.current.delete(Se),ce.current&&D(At=>At+1)},750);Ve(Se),P.current.set(Se,kt)}};G.detachListeners=()=>{rt.removeEventListener("open",ge),rt.removeEventListener("message",De),rt.removeEventListener("error",z),rt.removeEventListener("close",ae)},rt.addEventListener("open",ge),rt.addEventListener("message",De),rt.addEventListener("error",z),rt.addEventListener("close",ae)}Oe()},[n,Ve,He,Ne,O,$,be,qe,r,B,ee,Me,i.monitorSelections,L,Y,ie,H,W,Oe]),d.useEffect(()=>{if(!W||oe<=0){F.current!==null&&(window.clearInterval(F.current),F.current=null);return}const he=Math.max(1e3,oe),pe=window.setInterval(()=>{for(const[Ae,Se]of k.current.entries())if(!(Se.disposed||Se.socket.readyState!==WebSocket.OPEN))try{Se.socket.send(JSON.stringify({...Se.payload,type:"refresh-live",deviceIds:[Ae],reason:"periodic-configuration"}))}catch{try{Se.socket.close(4003,"configuration-refresh-failed")}catch{}}},he);return F.current=pe,()=>{window.clearInterval(pe),F.current===pe&&(F.current=null)}},[oe,W]),d.useEffect(()=>{if(!W||!me||!ue)return;const he=O?O.split(",").filter(Boolean):[];for(const pe of he){if(I.current.get(pe)===ue)continue;const Ae=k.current.get(pe);!Ae||!$e(pe,Ae,Ce,ue)||I.current.set(pe,ue)}},[O,me,ue,Ce,$e,W]),d.useEffect(()=>()=>{ie("livedesk-hook-unmount",!1)},[ie]);const vt=d.useCallback((he,pe="browser-stale")=>{if(!W)return!1;const Ae=Array.isArray(he)&&he.length>0?he:O.split(",").filter(Boolean);if(Ae.length===0)return!1;let Se=!1;for(const Pe of Ae){const Qe=k.current.get(Pe);!Qe||Qe.socket.readyState!==WebSocket.OPEN||(Se=$e(Pe,Qe,pe,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Se)}return Se},[O,$e,W]),xe=d.useCallback((he,pe="browser-reconnect")=>{if(!W)return!1;const Ae=Array.isArray(he)&&he.length>0?he:O.split(",").filter(Boolean);if(Ae.length===0)return!1;let Se=!1;for(const Pe of Ae){const Qe=k.current.get(Pe);Qe&&(Ve(Pe),He(Qe,`livedesk-${pe}`),k.current.delete(Pe),I.current.delete(Pe),x.current.delete(Pe),M.current.delete(Pe),Se=!0)}return Se&&u(new Map(x.current)),D(Pe=>Pe+1),Oe(),!0},[Ve,He,O,W,Oe]);return{frames:l,state:f,error:g,stats:w,restartLive:vt,reconnectLive:xe}}function P1(t,n,r=Dn,i={}){const[l,u]=d.useState(null),[f,h]=d.useState(null),[g,y]=d.useState("idle"),[w,b]=d.useState(Vf),x=d.useRef(null),M=d.useRef(i.onFrame),k=d.useRef(null),N=d.useRef(0),E=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),I=d.useMemo(()=>[...new Set(t.filter(Boolean))].join(","),[t]),T=d.useMemo(()=>[...new Set((i.captureDeviceIds||t).filter(Boolean))].join(","),[t,i.captureDeviceIds]),P=d.useMemo(()=>JSON.stringify(i.monitorSelections||{}),[i.monitorSelections]),U=d.useMemo(()=>{const O=Object.entries(i.connectionSessionIds||{}).filter(([W])=>!!W).map(([W,ce])=>[W,String(ce||"").trim()]).sort(([W],[ce])=>W.localeCompare(ce));return JSON.stringify(Object.fromEntries(O))},[i.connectionSessionIds]),F=d.useMemo(()=>({deviceIds:I.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(i.fps||20),inputFps:Number(i.inputFps||8),width:Number(i.width||1920),height:Number(i.height||1080),tileWidth:Number(i.tileWidth||320),tileHeight:Number(i.tileHeight||180),monitorSelections:i.monitorSelections||{}}),[T,I,P,i.fps,i.height,i.inputFps,i.monitorSelections,i.tileHeight,i.tileWidth,i.width]),Y=d.useMemo(()=>JSON.stringify({atlasConfiguration:F,connectionSessionKey:U}),[F,U]),D=d.useRef(F);D.current=F;const K=n&&F.deviceIds.length>0,ne=d.useCallback(O=>O.readyState!==WebSocket.OPEN?!1:(O.send(JSON.stringify({type:"configure",...D.current})),!0),[]);d.useEffect(()=>{M.current=i.onFrame},[i.onFrame]),d.useEffect(()=>{if(!K)return;E.current.sampleStartedAt=performance.now();const O=window.setInterval(()=>{const W=E.current,ce=performance.now(),$=Math.max(1,ce-W.sampleStartedAt);b({totalFrames:W.totalFrames,totalBytes:W.totalBytes,framesPerSecond:W.sampleFrames*1e3/$,bytesPerSecond:W.sampleBytes*1e3/$,sampleMs:$,lastUpdatedAt:Date.now()});const ee=k.current;ee&&ee.frameSeq!==N.current&&(N.current=ee.frameSeq,u(ee)),W.sampleFrames=0,W.sampleBytes=0,W.sampleStartedAt=ce},1e3);return()=>window.clearInterval(O)},[K]),d.useEffect(()=>{if(!K){x.current?.close(),x.current=null,u(null),k.current=null,N.current=0,h(null),y("idle"),b(Vf);return}let O=!1,W=0;const ce=()=>{if(O)return;const $=new WebSocket(Yp("/api/remote/atlas/ws",r),Xp(r));$.binaryType="arraybuffer",x.current=$,y("connecting"),$.addEventListener("open",()=>{E.current.sampleStartedAt=performance.now(),y("open"),ne($)}),$.addEventListener("message",ee=>{if(typeof ee.data=="string"){try{const L=JSON.parse(ee.data);L?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(L.layoutVersion||0),width:Number(L.width||1920),height:Number(L.height||1080),columns:Number(L.columns||1),rows:Number(L.rows||1),tiles:Array.isArray(L.tiles)?L.tiles:[]})}catch{}return}const B=ee.data instanceof ArrayBuffer?ee.data:null;if(!(!B||B.byteLength<5))try{const L=Date.now(),be=new DataView(B).getUint32(0,!1);if(be<=0||be+4>B.byteLength)return;const H=JSON.parse(Lv.decode(new Uint8Array(B,4,be))),me=new Uint8Array(B,4+be),ue=ht(H.hubClientDropped),Ce=ht(H.hubClientQueueDepth),Me=ht(H.hubClientQueueLimit),Ne=ht(H.hubClientBufferedBytes),He={deviceId:String(H.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(H.frameSeq||0),streamFrameSeq:Number(H.streamFrameSeq||0)||void 0,streamId:String(H.streamId||"mode4-atlas"),commandId:H.commandId?String(H.commandId):void 0,width:Number(H.width||1920),height:Number(H.height||1080),sourceWidth:Number(H.sourceWidth||H.width||1920),sourceHeight:Number(H.sourceHeight||H.height||1080),mimeType:String(H.mimeType||"video/h264"),mode:String(H.mode||"mode4-h264-atlas"),frameMode:String(H.frameMode||"mode4-h264-atlas"),frameProfile:String(H.frameProfile||"mode4-h264-atlas-v1"),encoding:String(H.encoding||"video-atlas"),codec:String(H.codec||"h264"),compression:String(H.compression||"video/h264"),h264Format:String(H.h264Format||"annexb"),isKeyFrame:H.isKeyFrame===!0,chunkType:String(H.chunkType||""),timestampUs:Number(H.timestampUs||0),durationUs:Number(H.durationUs||0),transport:H.transport?String(H.transport):void 0,videoTransport:H.videoTransport?String(H.videoTransport):void 0,frameTransportActive:H.frameTransportActive?String(H.frameTransportActive):void 0,frameTransportProtocol:H.frameTransportProtocol?String(H.frameTransportProtocol):void 0,frameTransportState:H.frameTransportState?String(H.frameTransportState):void 0,frameTransportReason:H.frameTransportReason?String(H.frameTransportReason):void 0,frameTransportChangedAt:H.frameTransportChangedAt?String(H.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(H.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(H.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:H.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:ue!==void 0&&Ce!==void 0&&Me!==void 0&&Ne!==void 0,hubClientDropped:ue,hubClientQueueDepth:Ce,hubClientQueueLimit:Me,hubClientBufferedBytes:Ne,udpIncompleteFrames:Number(H.udpIncompleteFrames||0)||0,hardwareEncoder:H.hardwareEncoder?String(H.hardwareEncoder):void 0,platformProfile:H.platformProfile?String(H.platformProfile):void 0,capturedAt:String(H.capturedAt||""),receivedAt:String(H.receivedAt||""),hubPacketAt:H.hubPacketAt?String(H.hubPacketAt):void 0,hubPacketEpochMs:Number(H.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:L,byteLength:me.byteLength,layoutVersion:Number(H.layoutVersion||0),atlasComposeMs:Number(H.atlasComposeMs||0),atlasPoolStarved:Number(H.atlasPoolStarved||0),atlasReadyTiles:Number(H.atlasReadyTiles||0),atlasTileCount:Number(H.atlasTileCount||0),atlasInputRevision:Number(H.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(H.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(H.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(H.atlasSourceMaxAgeMs||0),payload:me},Ve=E.current;Ve.totalFrames+=1,Ve.totalBytes+=me.byteLength,Ve.sampleFrames+=1,Ve.sampleBytes+=me.byteLength,k.current=He,N.current===0&&(N.current=He.frameSeq,u(He)),M.current?.(He)}catch{}}),$.addEventListener("error",()=>y("error")),$.addEventListener("close",()=>{x.current===$&&(x.current=null),!O&&(y("closed"),W=window.setTimeout(ce,1200))})};return ce(),()=>{O=!0,window.clearTimeout(W),x.current?.close(),x.current=null}},[K,r,ne]),d.useEffect(()=>{if(!K)return;const O=x.current;O&&ne(O)},[Y,K,ne]);const q=d.useCallback(()=>{const O=x.current;return O?ne(O):!1},[ne]);return{frame:l,layout:f,state:g,stats:w,refreshInputs:q}}function F1(t,n=Dn,r=""){const i=d.useRef(null),l=d.useRef(0),u=d.useRef(0),f=d.useRef(new Map),h=d.useRef(""),g=d.useRef(r);g.current=r;const y=d.useRef(r),w=d.useRef(0),b=d.useRef([]),[x,M]=d.useState("idle"),[k,N]=d.useState(""),[E,I]=d.useState(ew),T=d.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0}),P=d.useCallback((K=performance.now())=>{const ne=g.current;b.current=b.current.filter(q=>!!ne&&q.ownerKey===ne&&K-q.queuedAt<=gg)},[]),U=d.useCallback((K,ne)=>{const q=g.current,O=String(ne.type||"input").toLowerCase();return!q||!K?(T.current.totalDropped+=1,T.current.sampleDropped+=1,T.current.lastInputType=O+"-owner-unavailable",!1):(P(),b.current.length>=A1?(b.current=[],T.current.totalDropped+=1,T.current.sampleDropped+=1,T.current.lastInputType=O+"-queue-overflow",N("Remote input queue was reset because ordered input could not drain."),!1):(b.current.push({ownerKey:q,deviceId:K,input:{...ne},queuedAt:performance.now()}),T.current.lastInputType=O+"-queued",!0))},[P]),F=d.useCallback((K,ne,q)=>{if(K.readyState!==WebSocket.OPEN||!ne)return!1;const O=String(q.type||"").toLowerCase(),W=O==="pointermove",$=W||O==="wheel",ee=T.current;if($&&K.bufferedAmount>k1)return ee.totalDropped+=1,ee.sampleDropped+=1,ee.lastInputType=O+"-coalescible-drop",!1;const B=l.current+1;l.current=B;const L=B+"-"+crypto.randomUUID(),oe=Date.now(),be=!$||B-u.current>=j1;for(be&&(f.current.set(B,{sentAt:performance.now(),deviceId:ne,inputEventId:L}),$&&(u.current=B)),h.current=ne,W||CS.set(ne,{inputSeq:B,inputType:O||"input",sentAt:performance.now()});f.current.size>256;){const H=f.current.keys().next().value;if(H===void 0)break;f.current.delete(H)}try{K.send(JSON.stringify({type:"input",requestId:$?"":crypto.randomUUID(),fireAndForget:$,deviceId:ne,input:{...q,inputEventId:L,inputSeq:B,requestAck:be,issuedAtEpochMs:oe,issuedAt:new Date(oe).toISOString()}}))}catch{return f.current.delete(B),!1}return ee.totalSent+=1,ee.sampleSent+=1,ee.lastInputType=O||"input",!0},[]),Y=d.useCallback(K=>{P();const ne=g.current;if(!ne||K.readyState!==WebSocket.OPEN)return;const q=b.current;b.current=[];for(let O=0;O<q.length;O+=1){const W=q[O];if(!(W.ownerKey!==ne||performance.now()-W.queuedAt>gg)&&(K.readyState!==WebSocket.OPEN||!F(K,W.deviceId,W.input))){b.current=q.slice(O).filter(ce=>ce.ownerKey===ne&&performance.now()-ce.queuedAt<=gg);return}}},[F,P]);d.useLayoutEffect(()=>{y.current!==r&&(y.current=r,b.current=[],f.current.clear(),u.current=0,h.current="")},[r]),d.useEffect(()=>{if(!t){i.current?.close(),i.current=null,w.current=0,b.current=[],u.current=0,h.current="",f.current.clear(),M("idle"),N(""),I(ew);return}let K=!1,ne=0;const q=()=>{if(K)return;const O=new WebSocket(Yp("/api/remote/input/ws",n),Xp(n));i.current=O,T.current.sampleStartedAt=performance.now(),M("connecting"),N(""),O.addEventListener("open",()=>{K||i.current!==O||(w.current=0,N(""),M("open"),Y(O))}),O.addEventListener("message",W=>{if(!(K||i.current!==O||typeof W.data!="string"))try{const ce=JSON.parse(W.data),$=Number(ce.inputSeq||ce.result?.inputSeq||0),ee=String(ce.deviceId||ce.result?.deviceId||""),B=String(ce.inputEventId||ce.result?.inputEventId||""),L=f.current.get($);if(ee&&(L&&L.deviceId!==ee||!L&&h.current&&h.current!==ee)||L?.inputEventId&&B&&L.inputEventId!==B)return;if(ce?.type==="RemoteInputError"){$>0&&f.current.delete($),N(String(ce.error||ce.result?.error||"Remote input failed.")),O.readyState===WebSocket.OPEN&&M("open");return}if(ce?.type!=="RemoteInputApplied")return;L&&(T.current.lastRoundTripMs=Math.max(0,performance.now()-L.sentAt),f.current.delete($)),T.current.lastInputSeq=$,T.current.lastAgentApplyMs=Math.max(0,Number(ce.agentApplyMs||0)),N(""),M("open")}catch{}}),O.addEventListener("close",()=>{if(K||i.current!==O)return;i.current=null,f.current.clear(),M("closed");const W=w.current;w.current=W+1;const ce=Math.min(T1,N1*2**Math.min(W,3));ne=window.setTimeout(q,ce)}),O.addEventListener("error",()=>{!K&&i.current===O&&M("error")})};return q(),()=>{K=!0,window.clearTimeout(ne);const O=i.current;i.current=null,O?.close(),f.current.clear()}},[t,Y,n]),d.useEffect(()=>{if(!t)return;const K=window.setInterval(()=>{const ne=performance.now();P(ne);const q=T.current,O=Math.max(1,ne-q.sampleStartedAt);I({totalSent:q.totalSent,totalDropped:q.totalDropped,sentPerSecond:q.sampleSent*1e3/O,droppedPerSecond:q.sampleDropped*1e3/O,bufferedAmount:i.current?.bufferedAmount||0,lastInputType:q.lastInputType,lastInputSeq:q.lastInputSeq,lastRoundTripMs:q.lastRoundTripMs,lastAgentApplyMs:q.lastAgentApplyMs,lastUpdatedAt:Date.now()}),q.sampleSent=0,q.sampleDropped=0,q.sampleStartedAt=ne},1e3);return()=>window.clearInterval(K)},[t,P]);const D=d.useCallback((K,ne)=>{const q=String(ne.type||"").toLowerCase(),O=q==="pointermove"||q==="wheel",W=i.current;if(!W||W.readyState!==WebSocket.OPEN)return O?(T.current.totalDropped+=1,T.current.sampleDropped+=1,T.current.lastInputType=(q||"input")+"-transport-unavailable",!1):U(K,ne);if(!O&&W.bufferedAmount>M1){const ee=U(K,ne);N("Remote input is reconnecting because ordered input could not drain immediately.");try{W.close(4001,"ordered-input-backpressure")}catch{}return ee}const ce=F(W,K,ne);if(ce||O)return ce;const $=U(K,ne);N("Remote input is reconnecting after a send failure.");try{W.close(4002,"input-send-failed")}catch{}return $},[F,U]);return{state:x,sendInput:D,stats:E,error:k}}const ld={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureAwaitingCurrentPcm:!1,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0,lastUpdatedAt:0},O1=.25,nw=300,aw=2,lp=1500,vg=5e3,H1=2e3,rw=1e4,Lf=[0,1e3,3e3];function sw(t){const n=Date.parse(String(t||""));return Number.isFinite(n)?Math.max(0,Date.now()-n):0}function B1(t,n,r=Dn,i=0,l=!1,u="",f,h){const g=d.useRef(null),[y,w]=d.useState("idle"),[b,x]=d.useState(null),[M,k]=d.useState(ld),[N,E]=d.useState(""),I=d.useRef(l);return I.current=l,d.useEffect(()=>{l||(x(T=>T===null?T:null),k(T=>T===ld?T:ld))},[l]),d.useEffect(()=>{if(!n||!t){w("idle"),x(null),k(ld),E("");return}w("connecting"),x(null),k(ld),E("");const T=window.AudioContext||window.webkitAudioContext;if(!T){w("unsupported"),k(ld),E("Audio playback is not supported in this browser.");return}let P=!1,U=null;const F=JA.acquire(({release:Y})=>{if(P){Y();return}const D=new T({latencyHint:"interactive"});g.current=D;let K=String(u||"").trim();const ne="/api/remote/audio/ws?devices="+encodeURIComponent(t)+(K?"&streamId="+encodeURIComponent(K):""),q=new WebSocket(Yp(ne,r),Xp(r));q.binaryType="arraybuffer";const O=ha.createOwner({deviceId:t,socket:q,audioContext:D,statsTimer:null});let W=!1;const ce=()=>{const G=ha.releaseIfDrained(O);return(G||!ha.hasOwner(O))&&!W&&(W=!0,Y()),G},$=Iv({sampleRate:192e3,channels:8}).capacityBytes,ee=o1({maxPendingPackets:sv,maxPendingBytes:$}),B=KA(),L={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureStatusFailed:!1,captureAwaitingCurrentPcm:!1,captureAwaitingSinceAt:0,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(D.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:K,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let oe=!1,be=!1,H=null,me=0,ue=0,Ce="",Me=!1,Ne=()=>{},He="connecting",Ve="";const ie=G=>{oe||G===He||(He=G,w(G))},Oe=G=>{oe||G===Ve||(Ve=G,E(G))};let $e=0,qe=!1,vt=0,xe=0,he=0,pe=!1;const Ae=()=>{ha.setPendingWorkletPackets(O,ee.getPendingPacketCount(),ee.getPendingPacketBytes(),ee.getPendingPacketHighWater(),ee.getPendingByteHighWater())},Se=G=>{L.workletRingCapacityBytes=Math.max(0,Math.min($,Number(G.ringCapacityBytes||0)||0)),L.workletRingBufferedBytes=Math.max(0,Math.min(L.workletRingCapacityBytes,Number(G.ringBufferedBytes||0)||0)),L.workletRingBufferedMs=Math.max(0,Math.min(O1*1e3,Number(G.ringBufferedMs||0)||0)),L.workletRingDroppedFrames=Math.max(L.workletRingDroppedFrames,Number(G.ringDroppedFrames||0)||0),L.workletRingUnderflowCount=Math.max(L.workletRingUnderflowCount,Number(G.ringUnderflowCount||0)||0),ha.setPcmRing(O,L.workletRingCapacityBytes,L.workletRingBufferedBytes)},Pe=()=>{const G=H;if(H=null,Me=!1,G){G.onprocessorerror=null,G.port.onmessage=null;try{G.disconnect()}catch{}try{G.port.close()}catch{}}ee.terminate(),Ae(),L.workletRingCapacityBytes=0,L.workletRingBufferedBytes=0,L.workletRingBufferedMs=0,ha.setPcmRing(O,0,0),ha.setWorkletNode(O,0,0,me),ce()},Qe=G=>{const ge=G.data||{},De=String(ge.type||"");if((De==="packet-terminal"||De==="processor-error")&&(ee.acknowledge(typeof ge.packetId=="number"?ge.packetId:String(ge.packetId||"")),Ae()),De==="packet-terminal"){const z=Math.max(0,Number(ge.droppedFrames||0)||0);z>0&&(L.workletRingDroppedFrames+=z,L.resyncs+=1)}if(De==="ring-configured"||De==="ring-state"||De==="disposed"){const z=L.workletRingDroppedFrames;Se(ge),L.workletRingDroppedFrames>z&&(L.resyncs+=1)}De==="disposed"?Pe():De==="processor-error"&&Ne(String(ge.error||"Remote audio worklet processing failed."))},Z=()=>{if(!(!H||!Me))try{H.port.postMessage({type:"flush"})}catch{Ne("Remote audio worklet could not be flushed.")}},$t=()=>{q.readyState===WebSocket.OPEN&&q.send(JSON.stringify({type:"subscribe",deviceIds:[t],streamIdsByDeviceId:K?{[t]:K}:{}}))},Ee=()=>{L.audioContextState=String(D.state),!oe&&(L.audioContextState==="suspended"||L.audioContextState==="interrupted"?ie("suspended"):L.audioContextState==="closed"&&(ie("error"),Oe("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},Ge=async()=>{if(oe||String(D.state)==="closed")return!1;try{if(String(D.state)!=="running"&&await D.resume(),L.audioContextState=String(D.state),!oe&&!qe&&L.audioContextState==="running"){const G=L.lastAcceptedAt>0&&performance.now()-L.lastAcceptedAt<=lp,ge=L.lastCaptureStatusAt>0&&performance.now()-L.lastCaptureStatusAt<=vg&&L.captureHealthy;ie(G?"playing":ge?"silent":"open")}return L.audioContextState==="running"}catch(G){return oe||(ie("suspended"),Oe(G instanceof Error?"Audio playback is suspended: "+G.message:"Audio playback is suspended.")),!1}},ze=async()=>{if(!D.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const G=new Blob([f1],{type:"text/javascript"});Ce=URL.createObjectURL(G);try{await D.audioWorklet.addModule(Ce)}finally{URL.revokeObjectURL(Ce),Ce=""}if(oe||String(D.state)==="closed")return;const ge=new AudioWorkletNode(D,SS,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[aw],channelCount:aw,channelCountMode:"explicit"});me+=1,H=ge,ge.port.onmessage=Qe,ge.onprocessorerror=()=>{Ne("Remote audio worklet stopped unexpectedly.")},ge.connect(D.destination),Me=!0,ha.setWorkletNode(O,1,1,me)},Ft=(G,ge,De,z)=>{const ae=H;if(oe||!Me||!ae||ge.byteLength<=0)return!1;const Te=Dv({sampleRate:G.sampleRate,channels:G.channels,mimeType:G.mimeType}),Ue=++ue;if(!ee.claim(Ue,ge.byteLength))return Ae(),!1;Ae();try{return ae.port.postMessage({type:"pcm",packetId:Ue,buffer:ge,byteOffset:De,byteLength:z,sampleRate:Te.sampleRate,channels:Te.channels,mimeType:G.mimeType,sampleFormat:Te.sampleFormat},[ge]),!0}catch{return ee.acknowledge(Ue),Ae(),!1}},Ze=async()=>{if(oe||qe||q.readyState!==WebSocket.OPEN)return;if(vt>=Lf.length){ie("error"),Oe("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const G=vt;vt+=1,qe=!0,L.stalledCount+=1,L.automaticRestarts+=1,ie("reconnecting");try{if(!f)throw new Error("Remote audio restart owner is unavailable.");const ge=await f(t);if(oe||!ge)return;K=ge,$t();const De=performance.now();$e=De,L.lastPacketAt=De,L.lastAcceptedAt=0,L.lastCaptureStatusAt=0,L.lastPcmAtEpochMs=0,L.captureAlive=null,L.helperAlive=null,L.helperReady=!1,L.captureHealthy=!1,L.captureStatusFailed=!1,L.captureAwaitingCurrentPcm=!1,L.captureAwaitingSinceAt=0,L.capturePhase="",L.backendKind="",L.helperRequired=!1,L.helperPid=0,L.nativeCallbackDiagnosticsAvailable=!1,L.nativeRejectedCallbackCount=0,L.nativeCurrentnessDropCount=0,L.nativeLastDropReason="",L.silentForMs=0,L.activeStreamId=K,L.lastFrameSeq=0,L.maximumAcceptedGapMs=0,Z(),xe=De+(Lf[G+1]??3e3),Oe(""),oe||ie("open")}catch(ge){oe||(xe=performance.now()+(Lf[G+1]??3e3),ie("error"),Oe(ge instanceof Error?"Remote audio restart failed: "+ge.message:"Remote audio restart failed."))}finally{qe=!1}},nt=()=>{L.drops+=1},lt=window.setInterval(()=>{if(oe)return;const G=performance.now(),ge=L.lastPacketAt>0?Math.max(0,G-L.lastPacketAt):$e>0?Math.max(0,G-$e):0,De=L.lastAcceptedAt>0?Math.max(0,G-L.lastAcceptedAt):0,z=L.lastCaptureStatusAt>0?Math.max(0,G-L.lastCaptureStatusAt):0,ae=q.readyState===WebSocket.OPEN,Te=L.lastCaptureStatusAt>0,Ue=Te&&z<=vg&&L.captureHealthy,Xe=Te&&L.captureStatusFailed&&z>H1,at=Te&&z>vg,kt=!Te&&$e>0&&G-$e>rw,At=L.captureAwaitingCurrentPcm&&L.captureAwaitingSinceAt>0&&G-L.captureAwaitingSinceAt>rw,Ut=$e>0&&(L.lastAcceptedAt<=0?G-$e>lp:De>lp);if(ae&&$e>0&&(Xe||at||kt||At)?vt>=Lf.length&&!qe?(ie("error"),Oe("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!qe&&G>=xe?Ze():qe||ie("stalled"):ae&&Ut&&!qe&&L.audioContextState!=="suspended"&&L.audioContextState!=="interrupted"&&ie(Ue?"silent":"open"),e1({enabled:I.current,now:G,lastPublishedAt:he})){he=G,k({queuedMs:L.workletRingBufferedMs,browserAgeMs:L.browserAgeMs,captureAgeMs:L.captureAgeMs,captureStatusAgeMs:z,silentForMs:L.silentForMs,captureAlive:L.captureAlive,helperAlive:L.helperAlive,helperReady:L.helperReady,captureHealthy:L.captureHealthy,captureAwaitingCurrentPcm:L.captureAwaitingCurrentPcm,capturePhase:L.capturePhase,backendKind:L.backendKind,helperRequired:L.helperRequired,helperPid:L.helperPid,captureRestartCount:L.captureRestartCount,nativeCallbackDiagnosticsAvailable:L.nativeCallbackDiagnosticsAvailable,nativeRejectedCallbackCount:L.nativeRejectedCallbackCount,nativeCurrentnessDropCount:L.nativeCurrentnessDropCount,nativeLastDropReason:L.nativeLastDropReason,localProcessingAgeMs:L.localProcessingAgeMs,lastPacketAgeMs:ge,lastAcceptedAgeMs:De,framesReceived:L.framesReceived,drops:L.drops,resyncs:L.resyncs,pendingDecodes:L.pendingDecodes,lastFrameSeq:L.lastFrameSeq,audioContextState:L.audioContextState,stalledCount:L.stalledCount,automaticRestarts:L.automaticRestarts,maximumAcceptedGapMs:L.maximumAcceptedGapMs,workletRingCapacityBytes:L.workletRingCapacityBytes,workletRingBufferedBytes:L.workletRingBufferedBytes,workletRingDroppedFrames:L.workletRingDroppedFrames,workletRingUnderflowCount:L.workletRingUnderflowCount,lastUpdatedAt:Date.now()});const Qt=B.publish();Qt&&(pe=!0,ha.setRetainedFrame(O,1,Qt.payload.byteLength),x(Qt))}else!I.current&&pe&&(pe=!1,B.clear(),ha.setRetainedFrame(O,0,0))},250);ha.setStatsTimer(O,lt);const Tt=()=>{Ee(),(String(D.state)==="suspended"||String(D.state)==="interrupted")&&Ge()},Mt=()=>{document.visibilityState==="visible"&&Ge()},rt=()=>{Ge()};D.addEventListener("statechange",Tt),document.addEventListener("visibilitychange",Mt),window.addEventListener("pageshow",rt),window.addEventListener("pointerdown",rt),window.addEventListener("keydown",rt),ie("connecting"),Oe(""),Ee();const dt=(G,ge,De,z,ae)=>{if(L.localProcessingAgeMs=Math.max(0,performance.now()-ae),oe||L.localProcessingAgeMs>nw||!iv(G,{deviceId:t,streamId:K}))return nt(),!1;L.activeStreamId!==K&&(L.activeStreamId=K,L.lastFrameSeq=0,L.maximumAcceptedGapMs=0,Z());const Te=r1(G,{deviceId:t,streamId:K,lastFrameSeq:L.lastFrameSeq});if(!Te.accepted||!Ft(G,ge,De,z))return nt(),!1;L.browserAgeMs=sw(G.receivedAt),L.captureAgeMs=sw(G.capturedAt);const Ue=performance.now();L.lastAcceptedAt>0&&(L.maximumAcceptedGapMs=Math.max(L.maximumAcceptedGapMs,Ue-L.lastAcceptedAt)),L.lastAcceptedAt=Ue,L.framesReceived+=1,L.lastFrameSeq=Te.nextFrameSeq,vt=0,xe=0,I.current&&(B.accept(G),pe=!0,ha.setRetainedFrame(O,1,0)),String(D.state)!=="running"&&Ge();const Xe=String(D.state)==="running";return Xe&&Oe(""),ie(Xe?"playing":"suspended"),!0};Ne=(G="")=>{if(!be){if(be=!0,G&&(ha.recordTerminalFailure(O,G,G.includes("setup failed")?"setup":"processor"),ie(G.includes("AudioWorklet is unavailable")?"unsupported":"error"),Oe(G),h?.(t,K,"browser-audio-playback-failed").catch(()=>{})),oe=!0,ha.deactivate(O),window.clearInterval(lt),ha.setStatsTimer(O,null),D.removeEventListener("statechange",Tt),document.removeEventListener("visibilitychange",Mt),window.removeEventListener("pageshow",rt),window.removeEventListener("pointerdown",rt),window.removeEventListener("keydown",rt),B.clear(),ha.setRetainedFrame(O,0,0),H)try{H.port.postMessage({type:"dispose"})}catch{}try{q.close()}catch{}q.readyState===WebSocket.CLOSED&&ha.setSocket(O,null),D.close().catch(()=>{}).finally(()=>{Pe(),String(D.state)==="closed"&&ha.setAudioContext(O,null),ce()}),g.current===D&&(g.current=null),ce()}},ze().catch(G=>{Ne(G instanceof Error?`Remote audio worklet setup failed: ${G.message}`:"Remote audio worklet setup failed.")}),q.addEventListener("open",()=>{oe||($e=performance.now(),L.lastPacketAt=$e,L.lastAcceptedAt=0,L.lastCaptureStatusAt=0,L.lastPcmAtEpochMs=0,L.captureAlive=null,L.helperAlive=null,L.helperReady=!1,L.captureHealthy=!1,L.captureStatusFailed=!1,L.captureAwaitingCurrentPcm=!1,L.captureAwaitingSinceAt=0,L.capturePhase="",L.backendKind="",L.helperRequired=!1,L.helperPid=0,L.maximumAcceptedGapMs=0,L.silentForMs=0,ie("open"),$t(),Ge())}),q.addEventListener("message",G=>{if(typeof G.data=="string")return;const ge=G.data instanceof ArrayBuffer?G.data:null;if(!ge||ge.byteLength<5)return;const De=performance.now();L.lastPacketAt=De;try{const ae=new DataView(ge).getUint32(0,!1);if(ae<=0||ae+4>ge.byteLength){nt();return}const Te=new Uint8Array(ge,4,ae),Ue=JSON.parse(Lv.decode(Te)),Xe=new Uint8Array(ge,4+ae),at=String(Ue.deviceId||""),kt=String(Ue.streamId||"");if(!iv({deviceId:at,streamId:kt},{deviceId:t,streamId:K})){nt();return}const At=String(Ue.frameKind||Ue.kind||"").toLowerCase();if(Ue.type==="remote.audio.status"||At==="audio-status"){L.lastCaptureStatusAt=De;const Qt=s1(Ue);if(L.captureAlive=Qt.captureAlive,L.helperAlive=Qt.helperAlive,L.helperReady=Qt.helperReady,L.captureHealthy=Qt.healthy,L.captureStatusFailed=Qt.failed,L.captureAwaitingCurrentPcm=Qt.awaitingCurrentPcm,Qt.awaitingCurrentPcm?L.captureAwaitingSinceAt||=De:L.captureAwaitingSinceAt=0,L.capturePhase=Qt.capturePhase,L.backendKind=Qt.backendKind,L.helperRequired=Qt.helperRequired===!0,L.helperPid=Qt.helperPid,L.captureRestartCount=Math.max(0,Number(Ue.restartCount||0)||0),L.nativeCallbackDiagnosticsAvailable=Ue.callbackDiagnosticsAvailable===!0,L.nativeRejectedCallbackCount=L.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ue.rejectedCallbackCount||0)||0):0,L.nativeCurrentnessDropCount=L.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ue.currentnessDropCount||0)||0):0,L.nativeLastDropReason=L.nativeCallbackDiagnosticsAvailable?String(Ue.lastDropReason||""):"",L.lastPcmAtEpochMs=Math.max(0,Number(Ue.lastPcmAtEpochMs||0)||0),L.silentForMs=Math.max(0,Number(Ue.silentForMs||0)||0),L.captureAgeMs=L.lastPcmAtEpochMs>0?Math.max(0,Date.now()-L.lastPcmAtEpochMs):L.silentForMs,L.captureHealthy){if(vt=0,xe=0,!qe){Oe("");const sa=String(D.state)==="running",Ra=L.lastAcceptedAt>0&&performance.now()-L.lastAcceptedAt<=lp;ie(sa?Ra?"playing":"silent":"suspended")}}else L.captureAwaitingCurrentPcm&&!qe?ie("open"):L.captureStatusFailed&&!qe&&ie("stalled");return}const Ut={deviceId:at,frameSeq:Number(Ue.frameSeq||0),streamId:kt,mimeType:String(Ue.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Ue.sampleRate||48e3),channels:Number(Ue.channels||2),capturedAt:String(Ue.capturedAt||""),receivedAt:String(Ue.receivedAt||""),byteLength:Number(Ue.byteLength||Xe.byteLength),payload:xS};if(!Ut.deviceId||oe)return;if(performance.now()-De>nw){nt();return}if(a1(Ut.mimeType)){dt(Ut,ge,Xe.byteOffset,Xe.byteLength,De);return}nt(),ie("error"),Oe(`Unsupported remote audio format "${Ut.mimeType}". Requesting a bounded PCM restart.`),!qe&&vt<Lf.length&&(xe=0,Ze());return}catch(z){oe||(ie("error"),Oe(z instanceof Error?z.message:String(z)))}}),q.addEventListener("error",()=>{oe||(ie("error"),Oe("Remote audio WebSocket error."))}),q.addEventListener("close",()=>{ha.setSocket(O,null),ce(),oe||ie("closed")}),U=()=>{Ne()}});return F.ready.catch(Y=>{P||(w("error"),E(Y instanceof Error?`Remote audio owner setup failed: ${Y.message}`:"Remote audio owner setup failed."))}),()=>{P=!0,U?U():F.cancel()}},[t,n,r,i,f,h]),{state:y,lastFrame:b,stats:M,error:N}}const z1=3;function iw(t,n,r){const i=Math.max(1,Number(r)||1),l=Math.max(0,Math.min(i,Number(t)-Number(n))),u=Math.min(i/2,z1);return l<=u?0:l>=i-u?1:l/i}function $1(t,n,r){return{normalizedX:iw(t,r.left,r.width),normalizedY:iw(n,r.top,r.height)}}const Up=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),U1=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),ow=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),lv=64;function ah(t,n=80){return String(t||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,n)}function cv(t){const n=ah(t);return Object.prototype.hasOwnProperty.call(ow,n)?ow[n]:n}function lw(t={}){const n=ah(t.key),r=Number.isFinite(Number(t.location))?Math.max(0,Math.min(3,Math.trunc(Number(t.location)))):0,i=r===2?"Right":"Left";return n==="Shift"?`Shift${i}`:n==="Control"?`Control${i}`:n==="Alt"||n==="AltGraph"?`Alt${i}`:n==="Meta"||n==="OS"?`Meta${i}`:n?`Key:${r}:${n}`.slice(0,80):""}function uv(t={}){const n=cv(t.code);return["Shift","Control","Alt","AltGraph","Meta","OS"].includes(n)?lw({...t,key:n}):n||lw(t)}function Ep(t){for(const[n,r]of Object.entries(Up))if(r.includes(t))return n;return""}function Jl(t,n){return Up[n].some(r=>t.has(r))}function cp(t,n,r={},i="",l=""){for(const u of Object.keys(Up)){const f=r[u]===!0,h=Up[u];if(u===i){if(l==="keyup"&&!f)for(const g of h)n.has(g)||t.delete(g);continue}if(f){!Jl(t,u)&&t.size<lv&&t.add(U1[u]);continue}for(const g of h)n.has(g)||t.delete(g)}}function q1(t,n){if(t.length!==n.size)return!1;let r=0;for(const i of n){if(t[r]!==i)return!1;r+=1}return!0}function cw(t){for(const n of[...t])Ep(n)||t.delete(n)}function dv(t){return{shiftKey:Jl(t,"shiftKey"),ctrlKey:Jl(t,"ctrlKey"),altKey:Jl(t,"altKey"),metaKey:Jl(t,"metaKey")}}function W1(t={},n={}){return{shiftKey:t.shiftKey===!0||n.shiftKey===!0,ctrlKey:t.ctrlKey===!0||n.ctrlKey===!0,altKey:t.altKey===!0||n.altKey===!0,metaKey:t.metaKey===!0||n.metaKey===!0}}function G1(t,n,r){const i=uv(t),l=ah(t.key),u=Number(t.keyCode??t.which),f=Number(t.location);return{type:n,key:l,code:i,keyCode:Number.isFinite(u)?Math.max(0,Math.min(65535,Math.trunc(u))):0,location:Number.isFinite(f)?Math.max(0,Math.min(255,Math.trunc(f))):0,text:l.length===1?l:"",repeat:n==="keydown"&&t.repeat===!0,pressedCodes:[...r],...dv(r)}}function V1(){const t=new Set,n=new Set,r=()=>({pressedCodes:[...t]});return{event(i={},l=""){if(l!=="keydown"&&l!=="keyup")return null;const u=uv(i);if(!u)return null;const f=Ep(u),h=t.has(u),g=[...t];return f?l==="keydown"?(cp(t,n,i,f,l),t.size<lv&&t.add(u)):(n.has(u)||t.delete(u),cp(t,n,i,f,l)):(cp(t,n,i),l==="keydown"?t.size<lv&&t.add(u):t.delete(u)),l==="keyup"&&f==="metaKey"&&!Jl(t,"metaKey")&&cw(t),l==="keydown"&&h&&i.repeat!==!0&&q1(g,t)?null:G1(i,l,t)},modifier(i,l){const u=cv(i),f=Ep(u);if(!f)return null;const h=n.has(u);return l===h?null:(l?(n.add(u),t.add(u)):(n.delete(u),t.delete(u),f==="metaKey"&&!Jl(t,"metaKey")&&cw(t)),{type:l?"keydown":"keyup",key:f==="metaKey"?"Meta":f==="ctrlKey"?"Control":f==="altKey"?"Alt":"Shift",code:u,keyCode:0,location:u.endsWith("Right")?2:1,text:"",repeat:!1,...r(),...dv(t)})},reset(i="keyboard-owner-reset",l=!1){const u=t.size>0;return t.clear(),n.clear(),!u&&!l?null:{type:"keyboard.reset",reason:ah(i,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(i={}){const l=typeof i=="string"?cv(i):uv(i);if(t.has(l))return!0;const u=Ep(l);return!!u&&Jl(t,u)},snapshot(){return{...r(),latchedCodes:[...n],...dv(t)}}}}const kS=64,K1=2;function MS(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(1,Math.min(kS,n)):1}function _v(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(0,Math.min(kS-1,n)):0}function AS(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"||n==="linux"||n.startsWith("linux ")}function Q1(t,n,r){const i=String(n||"").trim();if(!i)return t||null;const l=String(r||"").trim();return t&&t.fingerprint===i&&(l?t.sampleId===l:t.sampleId==="")?t:{fingerprint:i,sampleId:l,consecutiveSamples:t?.fingerprint===i?t.consecutiveSamples+1:1}}function NS({platform:t,topologyFingerprint:n,consecutiveTopologySamples:r}){return AS(t)?!!String(n||"").trim()&&Number(r)>=K1:!0}function Y1({requestedIndex:t,monitorCount:n,platform:r,topologyFingerprint:i,consecutiveTopologySamples:l}){const u=_v(t),f=MS(n);return u<f||!NS({platform:r,topologyFingerprint:i,consecutiveTopologySamples:l})?u:f-1}function X1(t,n,r){const i=_v(t),l=MS(n);return i<l||AS(r)?i:l-1}function ic(t){const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:0}function ga(t){return String(t||"").trim()}function up(t,n,r={}){return{deviceId:ga(t),transitionGeneration:ic(n),sessionId:ga(r.sessionId),streamId:ga(r.streamId),commandId:ga(r.commandId),captureGeneration:ic(r.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(r.monitorIndex)||0))}}function Bn(t,n){return!!t&&!!n&&ga(t.deviceId)===ga(n.deviceId)&&ic(t.transitionGeneration)===ic(n.transitionGeneration)}function uw({deviceId:t,requestTransitionGeneration:n,currentTransitionGeneration:r,actualControlOwner:i}){const l=ga(t),u=ic(n),f=ic(r);return!!l&&u>0&&u===f&&(!i||ga(i.deviceId)===l)}function dw(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function dp(t,n,r){const i=ga(t);return!i||!n||ga(n.deviceId)!==i?!1:!r||ga(r.deviceId)!==i}function yg(t,n){if(!t||!n)return!1;const r=ic(n.captureGeneration),i=ga(n.commandId),l=ga(n.sessionId),u=ga(n.streamId),f=Number(t.monitorIndex);return!r||!i||!l||!u||!Number.isInteger(f)||f<0?!1:ga(t.deviceId)===ga(n.deviceId)&&ga(t.sessionId)===l&&ga(t.streamId)===u&&ga(t.commandId)===i&&ic(t.captureGeneration)===r&&ga(t.streamPurpose).toLowerCase()==="control"&&f===n.monitorIndex}function Z1(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function J1(){let t=Promise.resolve(),n=Promise.resolve();const r=i=>{const l=Z1(t,i);return t=l.tail,l.result};return{enqueue:r,enqueueStop(i){const l=r(i);return n=l.then(()=>{}),n.catch(()=>{}),l},enqueueStart(i){const l=n;return r(async()=>(await l,i()))}}}function eN(t={}){return Number(t.generation)===Number(t.currentGeneration)&&t.enabled===!0&&String(t.deviceId||"")!==""&&String(t.deviceId||"")===String(t.currentDeviceId||"")&&t.documentVisible===!0&&t.presentationVisible===!0&&String(t.streamId||"")!==""&&String(t.streamId||"")===String(t.currentStreamId||"")}function tN(t={}){const n=t.ok!==!1,r=n&&t.staleOwner===!0;return{confirmed:n&&(r||t.captureStopConfirmed===!0||t.alreadyStopped===!0),staleOwner:r,preserveNewerOwner:r&&(t.retainedNewerOwner===!0||String(t.activeStreamId||"")!=="")}}const Jn=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:30,slowWallFps:5,fastWallFps:30,directPopulationThrottle:!1,adaptiveMinimumCurrentSampleMs:750,adaptiveDownshiftStableMs:6e3,adaptiveDownshiftConsecutiveSamples:3,missingDeliveryRatio:.72,recoveryDeliveryRatio:.88,recoveryByteRatio:.52,recoveryGapRatio:.7,controlWallReuseMaxFps:30,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function fv(t){return t==="slow"?Jn.slowWallFps:Jn.fastWallFps}function nN({nowMs:t,nextPaintAtMs:n,targetFps:r,sourceFps:i,force:l=!1}){const u=Number.isFinite(Number(t))?Number(t):0,f=Number.isFinite(Number(n))?Math.max(0,Number(n)):0,h=Math.max(1,Number(r)||1),g=Math.max(1,Number(i)||1);if(h>=g)return{shouldPaint:!0,nextPaintAtMs:0,sourceCadencePassthrough:!0};const y=2;if(!l&&f>0&&u+y<f)return{shouldPaint:!1,nextPaintAtMs:f,sourceCadencePassthrough:!1};const w=1e3/h;let b=(l||f<=0?u:f)+w;for(;b<=u+y;)b+=w;return{shouldPaint:!0,nextPaintAtMs:b,sourceCadencePassthrough:!1}}function aN(t,n){const r=Number.isFinite(Number(n))?Math.max(0,Math.floor(Number(n))):Number.POSITIVE_INFINITY;if(r<=0)return[];const i=(Array.isArray(t)?t:[]).filter(f=>f&&String(f.deviceId||"").trim()).slice().sort((f,h)=>{const g=Number.isFinite(Number(f.slotNumber))?Number(f.slotNumber):Number.MAX_SAFE_INTEGER,y=Number.isFinite(Number(h.slotNumber))?Number(h.slotNumber):Number.MAX_SAFE_INTEGER;return g!==y?g-y:String(f.deviceId).localeCompare(String(h.deviceId))}),l=[],u=new Set;for(const f of i){const h=String(f.deviceId).trim();if(!u.has(h)&&(u.add(h),l.push(h),l.length>=r))break}return l}function rN(t,n){const r=Math.max(0,Math.floor(Number(n)||0));return t===!0&&r>0}function _f({mode4Enabled:t,directMode4WallEnabled:n,isMac:r}){return"direct"}function sN({mode4Enabled:t,directMode4WallEnabled:n,adaptiveFps:r,directDeviceCount:i,adaptive:l=!0}){return Math.max(1,Math.floor(Number(r)||1))}function iN({directDeviceCount:t,requestedFps:n,measuredFramesPerSecond:r,measuredPaintFramesPerSecond:i,measuredBytesPerSecond:l,maxBytesPerSecond:u,worstReceiveGapMs:f,worstPaintP95Ms:h,maxFrameGapMs:g}){const y=Math.max(1,Math.floor(Number(t)||1)),w=Math.max(1,Number(n)||1),b=Math.max(0,Number(r)||0),x=Math.max(0,Number(i)||0),M=Math.max(0,Number(l)||0),k=Math.max(1,Number(u)||1),N=Math.max(0,Number(f)||0),E=Math.max(0,Number(h)||0),I=Math.max(1,Number(g)||1),T=y*w,P=T>8&&b<T*Jn.missingDeliveryRatio,U=T>8&&x<T*Jn.missingDeliveryRatio,F=M>k||N>I||P||U,Y=b>=T*Jn.recoveryDeliveryRatio&&x>=T*Jn.recoveryDeliveryRatio&&M<k*Jn.recoveryByteRatio&&N<I*Jn.recoveryGapRatio&&E<I*Jn.recoveryGapRatio;return{expectedFramesPerSecond:T,estimatedMissingFrames:P,estimatedMissingPaints:U,overloaded:F,healthyForRecovery:Y}}function oN({receiveSampleMs:t,paintSampleMs:n,currentGenerationVerified:r,frameRequestedFps:i,adaptiveFps:l}){const u=Number(t),f=Number(n),h=Number(i),g=Number(l);return r===!0&&Number.isFinite(u)&&u>=Jn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(f)&&f>=Jn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(h)&&h>0&&h===g}function lN({deviceCount:t,targetFps:n,adaptive:r=!0}){const i=Math.max(1,Math.floor(Number(t)||1)),l=Math.max(1,Math.min(Jn.scalableAtlasMaxInputFps,Math.floor(Number(n)||Jn.scalableAtlasMaxInputFps)));if(!r)return l;const u=Math.max(Jn.scalableAtlasMinInputFps,Math.min(Jn.scalableAtlasMaxInputFps,Math.floor(Jn.scalableAtlasAggregateInputFps/i)));return Math.min(l,u)}function cN(t,n){return{acceleration:Jn.directDecodeAcceleration,latencyMode:Jn.directLatencyMode}}const md=999;function Jf(t){const n=Number(t);if(!Number.isFinite(n))return 0;const r=Math.floor(n);return r>=1&&r<=md?r:0}function uN(t){return String(t?.deviceName||t?.hostname||t?.deviceId||"Unknown Client").trim()||"Unknown Client"}function TS(t,n){return{deviceId:String(t?.deviceId||"").trim(),label:uN(t),platform:String(t?.platform||"").trim(),slotNumber:Jf(n)}}function ou(t){const n=Array.isArray(t)?t:[],r=new Map,i=new Set;for(const l of n){const u=String(l?.deviceId||"").trim(),f=Jf(l?.slotNumber);if(!u||!f||r.has(u)||i.has(f))continue;const h={deviceId:u,label:String(l?.label||u).trim()||u,platform:String(l?.platform||"").trim(),slotNumber:f};r.set(u,h),i.add(f)}return[...r.values()].sort((l,u)=>l.slotNumber-u.slotNumber||l.deviceId.localeCompare(u.deviceId))}function dN({connectedDevices:t,entries:n,minimumSlotCount:r=0}){const i=ou(n),l=(Array.isArray(t)?t:[]).filter(w=>w?.deviceId).slice().sort((w,b)=>{const x=Jf(w.slotNumber)||md+1,M=Jf(b.slotNumber)||md+1;return x-M||String(w.deviceId).localeCompare(String(b.deviceId))}),u=i.reduce((w,b)=>Math.max(w,b.slotNumber),0),f=Math.min(md,Math.max(0,Math.floor(Number(r)||0),u,l.length)),h=Array.from({length:f},(w,b)=>({slotNumber:b+1,device:null,saved:null,offline:!1,persisted:!1})),g=new Map(l.map(w=>[String(w.deviceId),w])),y=new Set;for(const w of i){for(;h.length<w.slotNumber&&h.length<md;)h.push({slotNumber:h.length+1,device:null,saved:null,offline:!1,persisted:!1});const b=h[w.slotNumber-1];if(!b)continue;const x=g.get(w.deviceId)||null;b.device=x,b.saved=w,b.offline=!x,b.persisted=!0,y.add(w.deviceId)}for(const w of l){const b=String(w.deviceId);if(y.has(b))continue;let x=h.find(M=>!M.device&&!M.saved);if(!x&&h.length<md&&(x={slotNumber:h.length+1,device:null,saved:null,offline:!1,persisted:!1},h.push(x)),!x)break;x.device=w,x.saved=TS(w,x.slotNumber),x.offline=!1,x.persisted=!1,y.add(b)}return h}function RS(t){return ou((Array.isArray(t)?t:[]).flatMap(n=>String(n?.saved?.deviceId||n?.device?.deviceId||"").trim()?[n.device?TS(n.device,n.slotNumber):{...n.saved,slotNumber:n.slotNumber}]:[]))}function fN(t,n,r){const i=String(n||"").trim(),l=Jf(r),u=RS(t);if(!i||!l)return u;const f=u.find(y=>y.deviceId===i);if(!f||f.slotNumber===l)return u;const h=u.find(y=>y.slotNumber===l),g=f.slotNumber;return f.slotNumber=l,h&&(h.slotNumber=g),ou(u)}const nu={revision:0,settings:{security:{accessMode:"trusted-only",allowLanConnections:!0,allowInternetConnections:!0,lockOnControlEnd:!0,idleControlMinutes:30},control:{allowKeyboardMouse:!0,allowRemoteRestart:!1},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},mN=[{id:"connection",label:"Connection",icon:wd},{id:"remote-access",label:"Remote Access",icon:Na},{id:"capture-audio",label:"Capture & Audio",icon:zg},{id:"display",label:"Display",icon:Fp},{id:"agent",label:"Agent",icon:nc}];function Dp(t,n){return t?.settings?.[n]||nu.settings[n]||{}}function fw(t,n){return{...t,settings:{...t.settings,[n.section]:{...Dp(t,n.section),[n.key]:n.value}}}}function bg(t){return{revision:Number(t.revision||0),updatedAt:t.updatedAt,settings:t.settings}}function qs({icon:t,title:n,description:r,children:i,recommended:l=!1}){return o.jsxs("div",{className:"product-setting-row",children:[o.jsx("div",{className:"product-setting-control",children:i}),t&&o.jsx("span",{className:"product-setting-icon",children:o.jsx(t,{size:17})}),o.jsxs("div",{className:"product-setting-copy",children:[o.jsx("strong",{children:n}),l&&o.jsx("em",{children:"Recommended"}),o.jsx("small",{children:r})]})]})}function el({checked:t,onChange:n,label:r}){return o.jsxs("label",{className:"product-switch",children:[o.jsx("input",{"aria-label":r,type:"checkbox",checked:t,onChange:i=>n(i.target.checked)}),o.jsx("span",{})]})}function wg({value:t,onChange:n,options:r,label:i}){return o.jsx("select",{"aria-label":i,value:String(t),onChange:l=>n(l.target.value),children:r.map(([l,u])=>o.jsx("option",{value:l,children:u},l))})}function pN({hubUrl:t="",runtimeRole:n="hub",runtimeDeviceId:r="",sessionAccessToken:i="",initialTab:l="connection",pin:u,agent:f,captureGallery:h,advertisementsHidden:g=!1,onAdvertisementsHiddenChange:y=()=>{}}){const[w,b]=d.useState(l),[x,M]=d.useState(null),[k,N]=d.useState("loading"),[E,I]=d.useState(""),[T,P]=d.useState("idle"),[U,F]=d.useState(""),Y=d.useRef(null),D=d.useRef(null),K=d.useRef([]),ne=d.useRef(Promise.resolve()),q=d.useRef(0),O=d.useRef(0);d.useEffect(()=>{const Me=++O.current;let Ne=!0;return K.current=[],D.current=null,Y.current=null,ne.current=Promise.resolve(),N("loading"),tt("/api/settings",void 0,t).then(He=>{if(!Ne||Me!==O.current)return;const Ve=bg(He);D.current=Ve,Y.current=Ve,M(Ve),N("saved")}).catch(He=>{!Ne||Me!==O.current||(I(He instanceof Error?He.message:String(He)),D.current=nu,Y.current=nu,M(nu),N("failed"))}),()=>{Ne=!1}},[t]);const W=async(Me,Ne,He)=>{const Ve={id:++q.current,section:Me,key:Ne,value:He},ie=O.current;K.current.push(Ve);const Oe=fw(Y.current||D.current||nu,Ve);Y.current=Oe,M(Oe),N("saving"),I(""),ne.current=ne.current.then(async()=>{if(ie!==O.current)return;let $e=null,qe=null;for(let he=0;he<2&&!$e;he+=1){const pe=D.current||nu;try{const Ae=await tt("/api/settings",{method:"PATCH",body:JSON.stringify({revision:pe.revision,[Ve.section]:{[Ve.key]:Ve.value}})},t);$e=bg(Ae)}catch(Ae){if(qe=Ae,he!==0||!String(Ae instanceof Error?Ae.message:Ae).startsWith("409 "))break;try{const Se=await tt("/api/settings",void 0,t);if(ie!==O.current)return;D.current=bg(Se)}catch(Se){qe=Se;break}}}if(ie!==O.current)return;K.current=K.current.filter(he=>he.id!==Ve.id),$e&&(D.current=$e);const vt=D.current||nu,xe=K.current.reduce(fw,vt);Y.current=xe,M(xe),$e?(I(""),N(K.current.length>0?"saving":"saved")):(N(K.current.length>0?"saving":"failed"),I(qe instanceof Error?qe.message:String(qe||"Settings could not be saved.")))}),await ne.current},ce=(Me,Ne)=>He=>{W(Me,Ne,He)},$=async()=>{if(n!=="hub"||!r||!i){P("failed"),F("Sign in to this Hub before changing its runtime role.");return}P("changing"),F("");try{const Me=await tt("/api/runtime/status",void 0,t);await tt("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${i}`},body:JSON.stringify({role:"client"})},t),P("accepted"),await Wx({baseUrl:t,targetRole:"client",previousRuntimePid:Number(Me.runtimePid||0),allowedStates:["running","waiting-auth"]}),hM(5179)}catch(Me){P("failed"),F(Me instanceof Error?Me.message:String(Me))}},ee=Dp(x,"security"),B=Dp(x,"control"),L=Dp(x,"filesAudio"),oe=`settings-panel-${w}`,be=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[u,o.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Runtime role"}),o.jsx("h3",{children:"Use this computer as a Client"})]}),o.jsx(Fp,{size:20})]}),o.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),T==="accepted"?o.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):U?o.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:U}):null,o.jsx("button",{className:"settings-reset",onClick:()=>{$()},disabled:T==="changing"||n!=="hub",type:"button",children:T==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),H=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Remote access"}),o.jsx("h3",{children:"Who may connect?"})]}),o.jsx(Ci,{size:20})]}),o.jsx(qs,{icon:Na,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:o.jsx(wg,{value:String(ee.accessMode),onChange:ce("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})}),o.jsx(qs,{icon:wd,title:"Allow LAN connections",description:"Permit authenticated, encrypted Clients on private network addresses.",recommended:!0,children:o.jsx(el,{checked:!!ee.allowLanConnections,onChange:ce("security","allowLanConnections"),label:"Allow LAN connections"})}),o.jsx(qs,{icon:wd,title:"Allow internet connections",description:"Permit authenticated, end-to-end encrypted Direct or Relay connections from public networks.",children:o.jsx(el,{checked:!!ee.allowInternetConnections,onChange:ce("security","allowInternetConnections"),label:"Allow internet connections"})})]}),o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Session permissions"}),o.jsx("h3",{children:"What may remote users do?"})]}),o.jsx(Ta,{size:20})]}),o.jsx(qs,{icon:Ta,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:o.jsx(el,{checked:!!B.allowKeyboardMouse,onChange:ce("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),o.jsx(qs,{icon:_x,title:"Power actions",description:"Allow confirmed sleep, restart, and shut down commands from the Hub.",children:o.jsx(el,{checked:!!B.allowRemoteRestart,onChange:ce("control","allowRemoteRestart"),label:"Power actions"})}),o.jsx(qs,{icon:zg,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:o.jsx(el,{checked:!!L.allowFileTransfer,onChange:ce("filesAudio","allowFileTransfer"),label:"File transfer"})}),o.jsx(qs,{icon:Zl,title:"Remote audio",description:"Allow sound capture from connected computers.",children:o.jsx(el,{checked:!!L.allowRemoteAudio,onChange:ce("filesAudio","allowRemoteAudio"),label:"Remote audio"})}),o.jsx(qs,{icon:Ci,title:"Lock after Control ends",description:"Release every remote key and button, then lock the controlled computer when the Control owner disconnects.",children:o.jsx(el,{checked:!!ee.lockOnControlEnd,onChange:ce("security","lockOnControlEnd"),label:"Lock after Control ends"})}),o.jsx(qs,{icon:Zl,title:"Control idle timeout",description:"End inactive Control ownership automatically. The visible local stop control is always enabled.",recommended:!0,children:o.jsx(wg,{value:Number(ee.idleControlMinutes),onChange:Me=>ce("security","idleControlMinutes")(Number(Me)),label:"Control idle timeout",options:[["5","5 minutes"],["15","15 minutes"],["30","30 minutes"],["60","1 hour"]]})})]})]}),me=o.jsxs("div",{className:"settings-tab-content product-settings-content",children:[o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Capture"}),o.jsx("h3",{children:"Recording defaults"})]}),o.jsx(zg,{size:20})]}),o.jsx(qs,{icon:Zl,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:o.jsx(el,{checked:!!L.rollingBufferEnabled,onChange:ce("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),o.jsx(qs,{icon:Zl,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:o.jsx(wg,{value:Number(L.timelapseIntervalSeconds),onChange:Me=>ce("filesAudio","timelapseIntervalSeconds")(Number(Me)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),Ce=w==="connection"?be:w==="remote-access"?H:w==="capture-audio"?me:w==="display"?o.jsx("div",{className:"settings-tab-content product-settings-content",children:o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Display"}),o.jsx("h3",{children:"Wall appearance"})]}),o.jsx(Fp,{size:20})]}),o.jsx(qs,{icon:Ta,title:"Hide advertisements",description:"Remove the optional advertisement banner from the Wall on this computer.",children:o.jsx(el,{checked:g,onChange:y,label:"Hide advertisements"})})]})}):f;return o.jsxs("section",{className:"settings-page",children:[o.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:mN.map(({id:Me,label:Ne,icon:He})=>o.jsxs("button",{className:w===Me?"active":"",id:`settings-tab-${Me}`,role:"tab","aria-selected":w===Me,"aria-controls":`settings-panel-${Me}`,tabIndex:w===Me?0:-1,onClick:()=>b(Me),type:"button",children:[o.jsx(He,{size:16}),Ne]},Me))}),k==="saving"&&o.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),E&&o.jsx("div",{className:"agent-settings-alert error",role:"alert",children:E}),o.jsx("section",{className:"settings-page-panel",id:oe,role:"tabpanel","aria-labelledby":`settings-tab-${w}`,tabIndex:0,children:Ce})]})}function hN({children:t}){return o.jsx("div",{className:"settings-tab-content",children:t})}const mw={enabled:!1};function pw(t){return{enabled:t?.enabled===!0}}async function gN(t,n,r){let i=null;for(let l=0;l<2;l+=1){const u=await tt("/api/settings",{signal:r},n);if(u.settings.agent?.enabled===t)return;try{await tt("/api/settings",{method:"PATCH",signal:r,body:JSON.stringify({revision:u.revision,agent:{enabled:t}})},n);return}catch(f){if(i=f,l!==0||!String(f instanceof Error?f.message:f).startsWith("409 "))throw f}}throw i}function vN({hubUrl:t}){const[n,r]=d.useState(mw),[i,l]=d.useState(null),[u,f]=d.useState(""),[h,g]=d.useState(""),[y,w]=d.useState(""),b=d.useRef(0),x=d.useRef(null);d.useEffect(()=>{let F=!0;x.current?.abort();const Y=new AbortController;x.current=Y;const D=++b.current;return l(null),r(mw),f(""),w(""),g(""),tt("/api/settings/agent",{signal:Y.signal},t).then(K=>{!F||Y.signal.aborted||D!==b.current||(l(K.settings),r(pw(K.settings)))}).catch(K=>{F&&!Y.signal.aborted&&D===b.current&&w(K instanceof Error?K.message:String(K))}),()=>{F=!1,Y.abort(),x.current===Y&&(x.current=null)}},[t]);const M=(F,Y)=>r(D=>({...D,[F]:Y})),k=F=>{l(F),r(pw(F))},N=()=>({generation:b.current,controller:x.current}),E=F=>F.generation===b.current&&F.controller!==null&&F.controller===x.current&&!F.controller.signal.aborted,I=async()=>{if(!i){w("Agent settings are not available yet.");return}const F=N();if(E(F)){f("save"),w(""),g("");try{if(await gN(n.enabled,t,F.controller.signal),!E(F))return;const Y=await tt("/api/settings/agent",{signal:F.controller.signal},t);if(!E(F))return;k(Y.settings),g("Codex Agent settings saved.")}catch(Y){E(F)&&w(Y instanceof Error?Y.message:String(Y))}finally{E(F)&&f("")}}},T=async()=>{const F=N();if(E(F)){f("test"),w(""),g("");try{const Y=await tt("/api/settings/agent/test",{method:"POST",signal:F.controller.signal,body:JSON.stringify({})},t);if(!E(F))return;const D=await tt("/api/settings/agent",{signal:F.controller.signal},t);if(!E(F))return;k(D.settings);const K=Number.isFinite(Y.connection?.latencyMs)?Math.max(0,Math.round(Y.connection.latencyMs)):null;g(`Codex Agent connection verified${K!==null?` in ${K} ms.`:"."}`)}catch(Y){E(F)&&w(Y instanceof Error?Y.message:String(Y))}finally{E(F)&&f("")}}},P=i?.codexInstallation==="installed"&&i.codexAuth==="signed-in",U=i!==null;return o.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[o.jsx("section",{className:"settings-section-card agent-enable-card",children:o.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[o.jsx("input",{type:"checkbox",checked:n.enabled,onChange:F=>M("enabled",F.target.checked),disabled:!U||u!==""}),o.jsx("span",{children:"Enable Codex Agent"})]})}),y&&o.jsx("div",{className:"agent-settings-alert error",role:"alert",children:y}),h&&o.jsx("div",{className:"agent-settings-alert success",role:"status",children:h}),o.jsxs("section",{className:"settings-section-card",children:[o.jsxs("div",{className:"settings-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Connection"}),o.jsx("h3",{children:"Codex SDK / CLI"})]}),o.jsx(Na,{size:20})]}),o.jsxs("div",{className:"agent-connection-row",children:[o.jsx("span",{className:`agent-connection-dot ${P?"connected":i?.codexAuth==="not-signed-in"?"unavailable":""}`}),o.jsx("span",{children:i?.codexInstallation==="not-installed"?"Codex SDK not installed":i?.codexAuth==="signed-in"?"Codex CLI signed in":i?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),o.jsxs("button",{className:"settings-reset",onClick:()=>{T()},disabled:u!=="",type:"button",children:[o.jsx(YC,{size:15})," ",u==="test"?"Testing":"Test connection"]})]}),o.jsxs("p",{className:"settings-help",children:[o.jsx(XC,{size:12})," The Hub uses the installed Codex SDK / CLI to plan approved commands and run them through LiveDesk Agent tools on selected computers."]})]}),o.jsx("div",{className:"settings-action-row agent-settings-actions",children:o.jsxs("button",{className:"text-button primary",onClick:()=>{I()},disabled:!U||u!=="",type:"button",children:[o.jsx(ZC,{size:15})," ",u==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function po(t){const[n,r]=d.useState(t),i=d.useRef(t);return d.useEffect(()=>{if(i.current!==t){if(Array.isArray(i.current)&&Array.isArray(t)&&i.current.length===0&&t.length===0)return;i.current=t,r(t)}},[t]),[n,r]}function Pv(t,n){return typeof t=="function"?typeof n=="object"?t(n):t():t}function Sd(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function yN(t,n="data-id"){const r=Sd(t,n);return r?r.getAttribute(n):null}function em(t,n="data-id"){const r=Sd(t,n);return r?rh(r,n):null}function rh(t,n="data-id"){const r=t.getAttribute(n);return r?bN(r):null}function za(t){return typeof t=="string"?":"+t:t}function bN(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function wN(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var Yr=wN();function Fv(t){Object.assign(Yr,t)}function hw(t,n,r){function i(l){const u=Sd(l);if(!u)return;const f=rh(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}Yr.addEvent(t,r,i)}function Cd(t,n){hw(t,n,"click"),n.dblclick&&hw(t,n.dblclick,"dblclick")}function xN(t,n){for(let r=t.length-1;r>=0;r--)if(t[r]===n){t.splice(r,1);break}}function SN(t,n,r){for(let i=0;i<al.length;i++){if(i===r)continue;const l=al[i],u=l.props.parent?.();if(u&&t.contains(u)&&l.node.contains(n))return!0}return!1}var jS=new Date,qp=!1,fp=[],al=[],gw=t=>{const n=t.target;if(qp||!n.isConnected){qp=!1;return}for(let r=al.length-1;r>=0;r--){const{node:i,date:l,props:u}=al[r];if(!(l>jS)&&!i.contains(n)&&i!==n&&(SN(i,n,r)||(u.callback&&u.callback(t),u.modal||t.defaultPrevented)))break}},CN=t=>{jS=new Date,qp=!0;for(let n=al.length-1;n>=0;n--){const{node:r}=al[n];if(!r.contains(t.target)&&r!==t.target){qp=!1;break}}};function go(t,n){fp.length||(fp=[Yr.addGlobalEvent("click",gw,t),Yr.addGlobalEvent("contextmenu",gw,t),Yr.addGlobalEvent("mousedown",CN,t)]),typeof n!="object"&&(n={callback:n});const r={node:t,date:new Date,props:n};return al.push(r),{destroy(){xN(al,r),al.length||(fp.forEach(i=>i()),fp=[])}}}var mp=t=>t.indexOf("bottom")!==-1,pp=t=>t.indexOf("left")!==-1,hp=t=>t.indexOf("right")!==-1,xg=t=>t.indexOf("top")!==-1,vw=t=>t.indexOf("fit")!==-1,Pf=t=>t.indexOf("overlap")!==-1,kN=t=>t.split("-").every(n=>["center","fit"].indexOf(n)>-1),MN=t=>{const n=t.match(/(start|center|end)/);return n?n[0]:null};function AN(t,n){let r=0;const i=Yr.getTopNode(t);for(;t&&t!==i;){const l=getComputedStyle(t).position;if((l==="absolute"||l==="relative"||l==="fixed")&&(r=parseInt(getComputedStyle(t).zIndex)||0),t=t.parentNode,t===n)break}return r}var ma,fr,Ff,Za;function ES(t,n,r="bottom",i=0,l=0){if(!t)return null;ma=i,fr=l,Ff="auto";let u=0,f=0,h=r;const g=DS(t),y=Pf(r)?Yr.getTopNode(t):g;if(!g)return null;const w=g.getBoundingClientRect(),b=t.getBoundingClientRect(),x=y.getBoundingClientRect(),M=window.getComputedStyle(y),k={left:0,top:0,bottom:0,right:0};for(const U in k){const F=`border-${U}-width`;k[U]=parseFloat(M.getPropertyValue(F))}if(n){const U=AN(n,g);u=Math.max(U+1,20)}if(n){if(Za=n.getBoundingClientRect(),vw(r)&&(Ff=Za.width+"px"),r!=="point")if(kN(r))vw(r)?ma=0:(ma=x.width/2,f=1),fr=(x.height-b.height)/2;else{const U=Pf(r)?0:1;ma=hp(r)?Za.right+U:Za.left-U,fr=mp(r)?Za.bottom+1:Za.top;const F=MN(r);F&&(hp(r)||pp(r)?F==="center"?fr-=(b.height-Za.height)/2:F==="end"&&(fr-=b.height-Za.height):(mp(r)||xg(r))&&(F==="center"?ma-=(b.width-Za.width)/2:F==="end"&&(ma-=b.width-Za.width),Pf(r)||(ma+=1)))}}else Za={left:i,right:i,top:l,bottom:l};const N=(pp(r)||hp(r))&&(mp(r)||xg(r));pp(r)&&(f=2);const E=ma-b.width-x.left;n&&pp(r)&&!N&&E<0&&(ma=Za.right,f=0,h=h.replace("left","right"));const I=ma+b.width*(1-f/2)-x.right;if(I>0)if(!hp(r))ma=x.right-k.right-b.width;else{const U=Za.left-x.x-b.width;n&&!N&&U>=0?(ma=Za.left-b.width,h=h.replace("right","left")):ma-=I+k.right}f&&(ma=Math.round(ma-b.width*f/2));const T=E<0||I>0||!N;xg(r)&&(fr=Za.top-b.height,n&&fr<x.y&&T&&(fr=Za.bottom,h=h.replace("top","bottom")));const P=fr+b.height-x.bottom;return P>0&&(n&&mp(r)&&T?(fr-=b.height+Za.height+1,h=h.replace("bottom","top")):fr-=P+k.bottom),ma-=w.left+k.left,fr-=w.top+k.top,ma=(Pf(r)?ma:Math.max(ma,0))+y.scrollLeft,fr=(Pf(r)?fr:Math.max(fr,0))+y.scrollTop,Ff=Ff||"auto",{at:h,x:ma,y:fr,z:u,width:Ff}}function DS(t){const n=Yr.getTopNode(t);for(t&&(t=t.parentElement);t;){const r=getComputedStyle(t).position;if(t===n||r==="relative"||r==="absolute"||r==="fixed")return t;t=t.parentNode}return null}function NN(t){const n=[];let r=t;const i=Yr.getTopNode(t);for(;r&&r!==i&&!r.getAttribute("data-wx-portal-root");)getComputedStyle(r).position==="absolute"&&n.push(r),r=r.parentNode;return n}var yw=new Date().valueOf();function Ov(){return yw+=1,yw}function pr(t){return t<10?"0"+t:t.toString()}function TN(t){const n=pr(t);return n.length==2?"0"+n:n}function IS(t){const n=Math.floor(t/11)*11;return{start:n,end:n+11}}function Sg(t){const n=(t.getDay()+6)%7,r=new Date(t.valueOf());r.setDate(t.getDate()+(3-n)),r.setHours(0,0,0,0);const i=new Date(r.getFullYear(),0,1),l=Math.round((r.getTime()-i.getTime())/864e5);return 1+Math.floor(l/7)}var bw=["",""];function RN(t,n,r){switch(t){case"%d":return pr(n.getDate());case"%m":return pr(n.getMonth()+1);case"%j":return n.getDate();case"%n":return n.getMonth()+1;case"%y":return pr(n.getFullYear()%100);case"%Y":return n.getFullYear();case"%D":return r.dayShort[n.getDay()];case"%l":return r.dayFull[n.getDay()];case"%M":return r.monthShort[n.getMonth()];case"%F":return r.monthFull[n.getMonth()];case"%h":return pr((n.getHours()+11)%12+1);case"%g":return(n.getHours()+11)%12+1;case"%G":return n.getHours();case"%H":return pr(n.getHours());case"%i":return pr(n.getMinutes());case"%a":return((n.getHours()>11?r.pm:r.am)||bw)[0];case"%A":return((n.getHours()>11?r.pm:r.am)||bw)[1];case"%s":return pr(n.getSeconds());case"%S":return TN(n.getMilliseconds());case"%W":return pr(Sg(n));case"%w":{const i=r.weekStart??1;if(i===1)return pr(Sg(n));const l=(n.getDay()-i+7)%7,u=(1-i+7)%7,f=new Date(n.valueOf());return f.setDate(n.getDate()+(u-l)),pr(Sg(f))}case"%c":{let i=n.getFullYear()+"";return i+="-"+pr(n.getMonth()+1),i+="-"+pr(n.getDate()),i+="T",i+=pr(n.getHours()),i+=":"+pr(n.getMinutes()),i+=":"+pr(n.getSeconds()),i}case"%Q":return Math.floor(n.getMonth()/3)+1;default:return t}}var jN=/%[a-zA-Z]/g;function gd(t,n){return typeof t=="function"?t:function(r){return r?(r.getMonth||(r=new Date(r)),t.replace(jN,i=>RN(i,r,n))):""}}function ww(t){return t&&typeof t=="object"&&!Array.isArray(t)}function mv(t,n){for(const r in n){const i=n[r];ww(t[r])&&ww(i)?t[r]=mv({...t[r]},n[r]):t[r]=n[r]}return t}function rm(t){return{getGroup(n){const r=t[n];return i=>r&&r[i]||i},getRaw(){return t},extend(n,r){if(!n)return this;let i;return r?i=mv({...n},t):i=mv({...t},n),rm(i)}}}var EN=$x();const DN="en-US",IN={monthFull:["January","February","March","April","May","June","July","August","September","October","November","December"],monthShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayFull:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],hours:"Hours",minutes:"Minutes",done:"Done",clear:"Clear",today:"Today",am:["am","AM"],pm:["pm","PM"],weekStart:0,clockFormat:24},LN={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},_N={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},LS={core:LN,calendar:IN,formats:_N,lang:DN},Hv=d.createContext(""),_S=d.createContext({}),Ai=d.createContext(null),PS=d.createContext(null),Ua=Object.freeze(Object.defineProperty({__proto__:null,fieldId:PS,helpers:_S,i18n:Ai,theme:Hv},Symbol.toStringTag,{value:"Module"}));function FS(t){const n=d.useContext(PS),[r]=d.useState(()=>t||n||Ov());return r}function Kf({type:t="",css:n="",icon:r="",disabled:i=!1,title:l="",tooltip:u,text:f="",children:h,onClick:g}){const y=d.useMemo(()=>{let b=t?t.split(" ").filter(x=>x!=="").map(x=>"wx-"+x).join(" "):"";return n+(n?" ":"")+b},[t,n]),w=b=>{g&&g(b)};return o.jsxs("button",{title:l,className:`wx-2ZWgb4 wx-button ${y} ${r&&!h?"wx-icon":""}`,disabled:i,onClick:w,"data-tooltip-text":u,children:[r&&o.jsx("i",{className:"wx-2ZWgb4 "+r}),h||f||" "]})}function PN({id:t,label:n="",inputValue:r="",value:i=!1,onChange:l,disabled:u=!1,css:f=""}){const h=FS(t),[g,y]=po(i),w=({target:b})=>{const x=b.checked;y(x),l&&l({value:x,inputValue:r})};return o.jsxs("div",{className:`wx-2IvefP wx-checkbox ${f}`,children:[o.jsx("input",{type:"checkbox",id:h,disabled:u,className:"wx-2IvefP wx-check",checked:g,value:r,onChange:w}),o.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[o.jsx("span",{className:"wx-2IvefP wx-before"}),n&&o.jsx("span",{className:"wx-2IvefP wx-after",children:n})]})]})}function Bv({theme:t="",target:n,children:r}){const i=d.useRef(null),l=d.useRef(null),[u,f]=d.useState(null);i.current||(i.current=document.createElement("div"));const h=d.useContext(Hv);return d.useEffect(()=>{f(n||FN(l.current)||Yr.getTopNode(l.current))},[l.current]),o.jsxs(o.Fragment,{children:[o.jsx("span",{ref:l,style:{display:"none"}}),l.current&&u?EN.createPortal(o.jsx("div",{className:`wx-3ZWsT0 wx-${t||h}-theme`,children:r}),u):null]})}function FN(t){const n=Yr.getTopNode(t);for(;t&&t!==n&&!t.getAttribute("data-wx-portal-root");)t=t.parentNode;return t}function ON({left:t=0,top:n=0,at:r="bottom",parent:i=null,width:l="auto",css:u="",onCancel:f,children:h,trackScroll:g=!1}){const[y,w]=d.useState(0),[b,x]=d.useState(0),[M,k]=d.useState("auto"),[N,E]=d.useState(!1),I=d.useRef(null),T=d.useRef(null),P=d.useRef(f);d.useEffect(()=>{P.current=f},[f]);function U(Y){return i&&(l+"").indexOf("%")>-1?l.replace(/(\d+)%/,(D,K)=>(K=K*i.offsetWidth/100+"px",l.replace(D,K))):l&&l!=="auto"?l:Y}const F=d.useCallback(()=>{if(!I.current)return;const Y=ES(I.current,i,r,t,n);Y&&(w(Y.x),x(Y.y),k(U(Y.width)))},[I,i,r,t,n,l]);return d.useLayoutEffect(()=>{const Y=K=>{P.current&&K.target!==T.current&&I.current&&!I.current.contains(K.target)&&P.current(K)};let D;return requestAnimationFrame(()=>{F(),E(!0),g&&I.current&&(T.current=DS(I.current),T.current&&T.current.addEventListener("scroll",Y,!0)),i&&(D=new ResizeObserver(F),D.observe(i))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",Y,!0),D?.disconnect()}},[]),d.useLayoutEffect(()=>{F()},[i,r,t,n]),d.useEffect(()=>{const Y=D=>{P.current&&P.current(D)};if(I.current)return go(I.current,{callback:Y,parent:()=>i}).destroy},[i]),o.jsx("div",{ref:I,className:["wx-37M6Fj","wx-popup",u].filter(Boolean).join(" "),style:{position:"absolute",visibility:N?"visible":"hidden",top:b+"px",left:y+"px",width:M},children:h})}function HN({position:t="bottom",align:n="start",autoFit:r=!0,onCancel:i=null,width:l="100%",css:u="",children:f}){const h=d.useRef(null),[g,y]=d.useState(t),[w,b]=d.useState(n),x=d.useRef(i);return d.useEffect(()=>{x.current=i},[i]),d.useEffect(()=>{if(r){const M=h.current;if(M){const k=M.getBoundingClientRect(),N=document.body.getBoundingClientRect();k.right>=N.right&&b("end"),k.bottom>=N.bottom&&y("top")}}},[]),d.useEffect(()=>{if(h.current){const M=k=>{x.current&&x.current(k)};return go(h.current,M).destroy}},[]),o.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${w}`,u||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:l},children:f})}function zv({position:t="bottom",align:n="start",autoFit:r=!0,inline:i=!1,onCancel:l,width:u="100%",children:f,...h}){const[g,y]=d.useState(void 0),w=d.useRef(null),b=d.useMemo(()=>`${t}-${n}`,[t,n]);return d.useLayoutEffect(()=>{w.current&&y(w.current.parentNode)},[]),o.jsxs(o.Fragment,{children:[g&&(i?o.jsx(HN,{onCancel:l,position:t,align:n,autoFit:r,width:u,...h,children:f}):o.jsx(Bv,{children:o.jsx(ON,{parent:g,at:b,onCancel:l,width:u,...h,children:f})})),o.jsx("span",{ref:w,className:"wx-portal-node wx-32GZ52"})]})}function sh(){return rm(LS)}function BN(){let t=null,n=!1,r=!1,i,l,u,f;const h=(b,x,M,k,N)=>{i=b,l=x,u=M,f=k,r=N},g=b=>{t=b,n=t!==null,u(t)},y=(b,x)=>{if(!r&&b!==null&&i){const M=i.querySelectorAll(".wx-list > .wx-item")[b];M&&(M.scrollIntoView({block:"nearest"}),x&&x.preventDefault())}},w=(b,x)=>{const M=b===null?null:Math.max(0,Math.min(t+b,l.length-1));M!==t&&(g(M),i?y(M,x):requestAnimationFrame(()=>y(M,x)))};return{move:b=>{const x=em(b),M=l.findIndex(k=>k.id===x);M!==t&&g(M)},keydown:(b,x)=>{switch(b.code){case"Enter":n?f():g(0);break;case"Space":n||g(0);break;case"Escape":u(t=null);break;case"Tab":u(t=null);break;case"ArrowDown":w(n?1:x||0,b);break;case"ArrowUp":w(n?-1:x||0,b);break}},init:h,navigate:w}}const xw=10,zN=d.memo(function({data:t,checkboxes:n,itemTemplate:r,value:i}){return o.jsxs(o.Fragment,{children:[n&&o.jsx(PN,{id:t.id,css:"wx-list-checkbox",value:i&&i.includes(t.id)}),r?Pv(r,{option:t}):t.label]})});function Sw({visibleItems:t,visibleRange:n,navIndex:r,checkboxes:i,itemTemplate:l,value:u,measureRefCallback:f}){return t.map((h,g)=>{const y=n.start+g;return o.jsx("div",{ref:g===0?f:void 0,className:`wx-233fr7 wx-item ${y===r?"wx-focus":""}`,"data-id":h.id,children:o.jsx(zN,{data:h,checkboxes:i,itemTemplate:l,value:u})},h.id)})}function ih({items:t=[],children:n,onSelect:r,onReady:i,virtualized:l=!1,checkboxes:u,multiselect:f,value:h,...g}){const y=d.useRef(),w=d.useRef(!1),b=d.useRef(BN()),[x,M]=d.useState(null),k=d.useRef(x),[N,E]=d.useState(0),[I,T]=d.useState(24),P=d.useRef(!1),U=(d.useContext(Ai)||sh()).getGroup("core"),F=d.useRef(t);d.useEffect(()=>{F.current=t},[t]);const Y=d.useRef(h);d.useEffect(()=>{Y.current=h},[h]);const D=d.useRef(0);d.useEffect(()=>{D.current=I},[I]);const K=d.useCallback(ue=>{ue&&ue.stopPropagation();const Ce=F.current,Me=Y.current,Ne=k.current;let He;const Ve=Ce[Ne]?.id;f?Me&&Me.includes(Ve)?He=Me.filter(ie=>ie!==Ve):He=[...Me||[],Ve]:He=Ve,r&&r({id:He})},[f,r]),ne=d.useRef(K);d.useEffect(()=>{ne.current=K},[K]);const q=d.useCallback(ue=>{if(y.current){let Ce=ue*D.current-y.current.clientHeight+D.current;E(Ce),y.current.scrollTop=Ce}},[D.current]),O=d.useCallback(ue=>{y.current=ue,l&&(ue&&!w.current&&k.current!==null&&requestAnimationFrame(()=>{y.current&&(q(k.current),w.current=!0)}),ue||(w.current=!1))},[q]),W=d.useCallback(ue=>{if(!ue||P.current)return;const Ce=ue.getBoundingClientRect().height;Ce&&(T(Ce),D.current=Ce,P.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,t,ue=>{M(ue),k.current=ue},ue=>ne.current(ue),l)},[t,y.current,l]),d.useEffect(()=>{const ue=(Me,Ne)=>{b.current.navigate(Me,Ne),q(k.current)},Ce=(Me,Ne)=>{const He=k.current,Ve=F.current;if(He!==0&&He!==Ve.length-1&&(Me.key==="ArrowDown"||Me.key==="ArrowUp")&&Me.preventDefault(),b.current.keydown(Me,Ne),y.current){const ie=y.current.scrollTop<=k.current*D.current,Oe=y.current.scrollTop+y.current.clientHeight>=k.current*D.current+D.current;ie?Oe||q(k.current):(y.current.scrollTop=k.current*D.current,E(y.current.scrollTop))}};i&&i({navigate:l?ue:b.current.navigate,keydown:l?Ce:b.current.keydown,move:b.current.move})},[]);const ce=d.useRef(0),$=d.useRef(t);$.current!==t&&($.current=t,ce.current+=1);const ee=d.useCallback(()=>{b.current.navigate(null)},[b]),B=d.useCallback(ue=>{l&&E(ue.target.scrollTop)},[l]),L=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/I),[I,N]),oe=d.useMemo(()=>{if(!l)return{start:0,end:t.length};if(!t.length)return{start:0,end:0};const ue=Math.floor(N/I),Ce=ue+L;return{start:Math.max(0,ue-xw),end:Math.min(t.length,Ce+xw)}},[l,t,N,I,L]),be=d.useMemo(()=>{if(!l)return t;const{start:ue,end:Ce}=oe;return t.slice(ue,Ce).map(Me=>({...Me}))},[l,t,oe]),H=oe.start*I,me=t.length*I;return d.useEffect(()=>{l&&E(0)},[t,l]),d.useEffect(()=>{x===null&&(w.current=!1)},[x]),x===null?null:o.jsx(zv,{onCancel:ee,...g,children:o.jsx("div",{className:"wx-233fr7 wx-list",ref:O,onClick:K,onMouseMove:b.current.move,onScroll:B,children:t.length?l?o.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${me}px`},children:o.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${H}px)`},children:o.jsx(Sw,{visibleRange:oe,visibleItems:be,navIndex:x,measureRefCallback:W,checkboxes:u,itemTemplate:n,value:h})})}):o.jsx(Sw,{visibleRange:oe,visibleItems:be,navIndex:x,measureRefCallback:W,checkboxes:u,itemTemplate:n,value:h}):o.jsx("div",{className:"wx-233fr7 wx-no-data",children:U("No data")})})},ce.current)}function $v({value:t="",id:n,readonly:r=!1,focus:i=!1,select:l=!1,type:u="text",placeholder:f="",disabled:h=!1,error:g=!1,title:y="",tooltip:w,css:b="",icon:x="",clear:M=!1,onChange:k}){const N=FS(n),[E,I]=po(t),T=d.useRef(null),P=d.useMemo(()=>x&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[x,b]),U=d.useMemo(()=>x&&b.indexOf("wx-icon-left")!==-1,[x,b]);d.useEffect(()=>{const ne=setTimeout(()=>{i&&T.current&&T.current.focus(),l&&T.current&&T.current.select()},1);return()=>clearTimeout(ne)},[i,l]);const F=d.useCallback(ne=>{const q=ne.target.value;I(q),k&&k({value:q,input:!0})},[k]),Y=d.useCallback(ne=>k&&k({value:ne.target.value}),[k]);function D(ne){ne.stopPropagation(),I(""),k&&k({value:""})}let K=u;return u!=="password"&&u!=="number"&&(K="text"),d.useEffect(()=>{const ne=Y,q=T.current;return q.addEventListener("change",ne),()=>{q&&q.removeEventListener("change",ne)}},[Y]),o.jsxs("div",{className:`wx-hQ64J4 wx-text ${P} ${g?"wx-error":""} ${h?"wx-disabled":""} ${M?"wx-clear":""}`,"data-tooltip-text":w,children:[o.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:N,readOnly:r,disabled:h,placeholder:f,type:K,title:y,value:E,onInput:F}),M&&!h&&E?o.jsxs(o.Fragment,{children:[o.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:D}),U&&o.jsx("i",{className:`wx-hQ64J4 wx-icon ${x}`})]}):x?o.jsx("i",{className:`wx-hQ64J4 wx-icon ${x}`}):null]})}function $N({date:t,type:n,part:r,onShift:i}){const{calendar:l,formats:u}=d.useContext(Ai).getRaw(),f=t.getFullYear(),h=d.useMemo(()=>{switch(n){case"month":return gd(u.monthYearFormat,l)(t);case"year":return gd(u.yearFormat,l)(t);case"duodecade":{const{start:y,end:w}=IS(f),b=gd(u.yearFormat,l);return`${b(new Date(y,0,1))} - ${b(new Date(w,11,31))}`}default:return""}},[t,n,f,l,u]);function g(){i&&i({diff:0,type:n})}return o.jsxs("div",{className:"wx-8HQVQV wx-header",children:[r!=="right"?o.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>i&&i({diff:-1,type:n})}):o.jsx("span",{className:"wx-8HQVQV wx-spacer"}),o.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),r!=="left"?o.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>i&&i({diff:1,type:n})}):o.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function Uv({onClick:t,children:n}){return o.jsx("button",{className:"wx-3s8W4d wx-button",onClick:t,children:n})}function UN({value:t,current:n,part:r="",markers:i=null,css:l="",onCancel:u,onChange:f}){const h=(d.useContext(Ai)||sh()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),w=(F,Y,D)=>new Date(F.getFullYear(),F.getMonth()+(Y||0),F.getDate()+(D||0));let b=r!=="normal";function x(F){const Y=F.getDay();return Y===0||Y===6}function M(){const F=w(n,0,1-n.getDate());return F.setDate(F.getDate()-(F.getDay()-(g-7))%7),F}function k(){const F=w(n,1,-n.getDate());return F.setDate(F.getDate()+(6-F.getDay()+g)%7),F}const N=d.useRef(0);function E(F,Y){Y.timeStamp!==N.current&&(N.current=Y.timeStamp,Y.stopPropagation(),f&&f(new Date(F)),u&&u())}const I=d.useMemo(()=>r=="normal"?[t?w(t).valueOf():0]:t?[t.start?w(t.start).valueOf():0,t.end?w(t.end).valueOf():0]:[0,0],[r,t]),T=d.useMemo(()=>{const F=M(),Y=k(),D=n.getMonth();let K=[];for(let ne=F;ne<=Y;ne.setDate(ne.getDate()+1)){const q={day:ne.getDate(),in:ne.getMonth()===D,date:ne.valueOf()};let O="";if(O+=q.in?"":" wx-inactive",O+=I.indexOf(q.date)>-1?" wx-selected":"",b){const W=q.date==I[0],ce=q.date==I[1];W&&!ce?O+=" wx-left":ce&&!W&&(O+=" wx-right"),q.date>I[0]&&q.date<I[1]&&(O+=" wx-inrange")}if(O+=x(ne)?" wx-weekend":"",i){const W=i(ne);W&&(O+=" "+W)}K.push({...q,css:O})}return K},[n,I,b,i]),P=d.useRef(null);let U=d.useRef({});return U.current.click=E,d.useEffect(()=>{Cd(P.current,U.current)},[]),o.jsxs("div",{className:`wx-398RBS wx-month ${l}`,children:[o.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map(F=>o.jsx("div",{className:"wx-398RBS wx-weekday",children:F},F))}),o.jsx("div",{className:"wx-398RBS wx-days",ref:P,children:T.map(F=>o.jsx("div",{className:`wx-398RBS wx-day ${F.css} ${F.in?"":"wx-out"}`,"data-id":F.date,children:F.day},F.date))})]})}function qN({value:t,current:n,part:r,onCancel:i,onChange:l,onShift:u}){const f=d.useRef(new Date),[h,g]=po(t||f.current),[y,w]=po(n||f.current),b=d.useContext(Ai).getRaw().calendar,x=b.monthShort||[],M=d.useMemo(()=>y.getMonth(),[y]),k=d.useCallback((I,T)=>{if(I!=null){T.stopPropagation();const P=new Date(y);P.setMonth(I),w(P),u&&u({current:P})}r==="normal"&&g(new Date(y)),i&&i()},[y,r,u,i]),N=d.useCallback(()=>{const I=new Date(OS(h,r)||y);I.setMonth(y.getMonth()),I.setFullYear(y.getFullYear()),l&&l(I)},[h,y,r,l]),E=d.useCallback(I=>{const T=I.target.closest("[data-id]");if(T){const P=parseInt(T.getAttribute("data-id"),10);k(P,I)}},[k]);return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-34U8T8 wx-months",onClick:E,children:x.map((I,T)=>o.jsx("div",{className:"wx-34U8T8 wx-month"+(M===T?" wx-current":""),"data-id":T,children:I},T))}),o.jsx("div",{className:"wx-34U8T8 wx-buttons",children:o.jsx(Uv,{onClick:N,children:b.done})})]})}const Cg="wx-1XEF33",WN=({value:t,current:n,onCancel:r,onChange:i,onShift:l,part:u})=>{const f=d.useContext(Ai).getRaw().calendar,[h,g]=po(n),[y,w]=po(t),b=d.useMemo(()=>h.getFullYear(),[h]),x=d.useMemo(()=>{const{start:I,end:T}=IS(b),P=[];for(let U=I;U<=T;++U)P.push(U);return P},[b]),M={click:k};function k(I,T){if(I){T.stopPropagation();const P=new Date(h);P.setFullYear(I),g(P),l&&l({current:P})}u==="normal"&&w(new Date(h)),r&&r()}function N(){const I=new Date(OS(y,u)||h);I.setFullYear(h.getFullYear()),i&&i(I)}const E=d.useRef(null);return d.useEffect(()=>{E.current&&Cd(E.current,M)},[]),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:Cg+" wx-years",ref:E,children:x.map((I,T)=>o.jsx("div",{className:Cg+` wx-year ${b==I?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":I,children:I},T))}),o.jsx("div",{className:Cg+" wx-buttons",children:o.jsx(Uv,{onClick:N,children:f.done})})]})},Cw={month:{component:UN,next:VN,prev:GN},year:{component:qN,next:QN,prev:KN},duodecade:{component:WN,next:XN,prev:YN}};function GN(t){return t=new Date(t),t.setMonth(t.getMonth()-1),t}function VN(t){return t=new Date(t),t.setMonth(t.getMonth()+1),t}function KN(t){return t=new Date(t),t.setFullYear(t.getFullYear()-1),t}function QN(t){return t=new Date(t),t.setFullYear(t.getFullYear()+1),t}function YN(t){return t=new Date(t),t.setFullYear(t.getFullYear()-10),t}function XN(t){return t=new Date(t),t.setFullYear(t.getFullYear()+10),t}function OS(t,n){let r;if(n==="normal")r=t;else{const{start:i,end:l}=t;n==="left"?r=i:n=="right"?r=l:r=i&&l}return r}const ZN=["clear","today"];function JN(t){if(t==="done")return-1;if(t==="clear")return null;if(t==="today")return new Date}function eT({value:t,current:n,onCurrentChange:r,part:i="normal",markers:l=null,buttons:u,css:f="",onShift:h,onChange:g}){const y=d.useContext(Ai).getGroup("calendar"),[w,b]=d.useState("month"),x=Array.isArray(u)?u:u?ZN:[],M=(T,P)=>{T.preventDefault(),g&&g({value:P})},k=()=>{w==="duodecade"?b("year"):w==="year"&&b("month")},N=T=>{const{diff:P,current:U}=T;if(P===0){w==="month"?b("year"):w==="year"&&b("duodecade");return}if(P){const F=Cw[w];r(P>0?F.next(n):F.prev(n))}else U&&r(U);h&&h()},E=T=>{b("month"),g&&g({select:!0,value:T})},I=d.useMemo(()=>Cw[w].component,[w]);return o.jsx("div",{className:`wx-2Gr4AS wx-calendar ${i!=="normal"&&i!=="both"?"wx-part":""} ${f}`,children:o.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[o.jsx($N,{date:n,part:i,type:w,onShift:N}),o.jsxs("div",{children:[o.jsx(I,{value:t,current:n,onCurrentChange:r,part:i,markers:l,onCancel:k,onChange:E,onShift:N}),w==="month"&&x.length>0&&o.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:x.map(T=>o.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:o.jsx(Uv,{onClick:P=>M(P,JN(T)),children:y(T)})},T))})]})]})})}function qv(t){let{words:n=null,optional:r=!1,children:i}=t,l=d.useContext(Ai);const u=d.useMemo(()=>{let f=l;return(!f||!f.extend)&&(f=rm(LS)),n!==null&&(f=f.extend(n,r)),f},[n,r,l]);return o.jsx(Ai.Provider,{value:u,children:i})}function kw(t,n,r,i){if(!t||i){const l=n?new Date(n):new Date;l.setDate(1),r(l)}else if(t.getDate()!==1){const l=new Date(t);l.setDate(1),r(l)}}const tT=["clear","today"];function HS({value:t,current:n,markers:r=null,buttons:i=tT,css:l="",onChange:u}){const[f,h]=po(t),[g,y]=po(n);d.useEffect(()=>{kw(g,f,y,!1)},[f,g]);const w=d.useCallback(x=>{const M=x.value;M?(h(new Date(M)),kw(g,new Date(M),y,!0)):h(null),u&&u({value:M?new Date(M):null})},[u,g]),b=d.useCallback(x=>{y(x)},[y]);return g?o.jsx(qv,{children:o.jsx(eT,{value:f,current:g,markers:r,buttons:i,css:l,onChange:w,onCurrentChange:b})}):null}function nT(t){return t||(t={}),t.width||(t.width="unset"),t}const aT=["clear","today"];function rT({value:t,id:n,disabled:r=!1,error:i=!1,placeholder:l="",format:u="",buttons:f=aT,css:h="",title:g="",tooltip:y,editable:w=!1,clear:b=!1,onChange:x,dropdown:M={}}){const{calendar:k,formats:N}=(d.useContext(Ai)||sh()).getRaw(),E=u||N?.dateFormat;let I=typeof E=="function"?E:gd(E,k);const[T,P]=d.useState(t),[U,F]=d.useState(!1);d.useEffect(()=>{P(t)},[t]);function Y(){F(!1)}function D(q){const O=q===T||q&&T&&q.valueOf()===T.valueOf()||!q&&!T;P(q),O||x&&x({value:q}),setTimeout(Y,1)}const K=d.useMemo(()=>T?I(T):"",[T,I]);function ne({value:q,input:O}){if(!w&&!b||O)return;let W=typeof w=="function"?w(q):q?new Date(q):null;W=isNaN(W)?T||null:W||null,D(W)}return d.useEffect(()=>{const q=Y;return window.addEventListener("scroll",q),()=>window.removeEventListener("scroll",q)},[]),o.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>F(!0),children:[o.jsx($v,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:K,id:n,readonly:!w,disabled:r,error:i,placeholder:l,onInput:Y,onChange:ne,icon:"wxi-calendar",clear:b}),U&&!r&&o.jsx(zv,{onCancel:Y,...nT(M),children:o.jsx(HS,{buttons:f,value:T,onChange:q=>D(q.value)})})]})}function sT({value:t="",options:n=[],textOptions:r=null,placeholder:i="",disabled:l=!1,error:u=!1,title:f="",tooltip:h,textField:g="label",clear:y=!1,css:w="",children:b,onChange:x,dropdown:M={}}){const k=d.useRef(null),N=d.useRef(null);let[E,I]=po(t);function T(D){k.current=D.navigate,N.current=D.keydown}const P=d.useMemo(()=>E||E===0?(r||n).find(D=>D.id===E):null,[E,r,n]),U=d.useCallback(({id:D})=>{(D||D===0)&&(I(D),k.current(null),x&&x({value:D}))},[I,x]),F=d.useCallback(D=>{D.stopPropagation(),I(""),x&&x({value:""})},[I,x]),Y=d.useCallback(()=>n.findIndex(D=>D.id===E),[n,E]);return o.jsxs("div",{className:`wx-2YgblL wx-richselect ${w} ${u?"wx-2YgblL wx-error":""} ${l?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:f,onClick:()=>k.current(Y()),onKeyDown:D=>N.current(D,Y()),tabIndex:0,"data-tooltip-text":h,children:[o.jsx("div",{className:"wx-2YgblL wx-label",children:P?b?b(P):P[g]:i?o.jsx("span",{className:"wx-2YgblL wx-placeholder",children:i}):" "}),y&&!l&&E?o.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:F}):o.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!l&&o.jsx(ih,{items:n,onReady:T,onSelect:U,...M,children:({option:D})=>b?b(D):D[g]})]})}const iT=({options:t=[],value:n="",css:r="",children:i,onChange:l})=>{const[u,f]=d.useState(n),h=g=>{f(g),l&&l({value:g})};return d.useEffect(()=>{f(n)},[n]),o.jsx("div",{className:`wx-0hMO7P wx-segmented ${r}`,children:t.map(g=>o.jsx("button",{className:`wx-0hMO7P wx-segment ${g.css} ${g.id===u?"wx-selected":""}`,title:g.title,onClick:()=>h(g.id),"data-tooltip-text":g.tooltip,children:i?Pv(i,{option:g}):o.jsxs(o.Fragment,{children:[g.icon&&o.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&o.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function oT({notice:t={}}){function n(){t.remove&&t.remove()}return o.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${t.type?t.type:""}`,role:"status","aria-live":"polite",children:[o.jsx("div",{className:"wx-11sNg5 wx-text",children:t.text}),o.jsx("div",{className:"wx-11sNg5 wx-button",children:o.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:n})})]})}function lT({data:t=[]}){return o.jsx("div",{className:"wx-3nwoO9 wx-notices",children:t.map(n=>o.jsx(oT,{notice:n},n.id))})}function pv({title:t="",buttons:n=["cancel","ok"],header:r,children:i,footer:l,css:u="",onConfirm:f,onCancel:h}){const g=(d.useContext(Ai)||sh()).getGroup("core"),y=d.useRef(null);d.useEffect(()=>{y.current?.focus()},[]);function w(x){switch(x.code){case"Enter":{const M=x.target.tagName;if(M==="TEXTAREA"||M==="BUTTON")return;f&&f({event:x});break}case"Escape":h&&h({event:x});break}}function b(x,M){const k={event:x,button:M};M==="cancel"?h&&h(k):f&&f(k)}return o.jsx("div",{className:`wx-1FxkZa wx-modal ${u}`,ref:y,tabIndex:0,onKeyDown:w,children:o.jsxs("div",{className:"wx-1FxkZa wx-window",children:[r||(t?o.jsx("div",{className:"wx-1FxkZa wx-header",children:t}):null),o.jsx("div",{children:i}),l||n&&o.jsx("div",{className:"wx-1FxkZa wx-buttons",children:n.map(x=>o.jsx("div",{className:"wx-1FxkZa wx-button",children:o.jsx(Kf,{type:`block ${x==="ok"?"primary":"secondary"}`,onClick:M=>b(M,x),children:g(x)})},x))})]})})}function cT({children:t},n){const[r,i]=d.useState(null),[l,u]=d.useState([]);return d.useImperativeHandle(n,()=>({showModal:f=>{const h={...f};return i(h),new Promise((g,y)=>{h.resolve=w=>{i(null),g(w)},h.reject=w=>{i(null),y(w)}})},showNotice:f=>{f={...f},f.id=f.id||Ov(),f.remove=()=>u(h=>h.filter(g=>g.id!==f.id)),f.expire!=-1&&setTimeout(f.remove,f.expire||5100),u(h=>[...h,f])}}),[]),o.jsxs(o.Fragment,{children:[t,r&&o.jsx(pv,{title:r.title,buttons:r.buttons,onConfirm:r.resolve,onCancel:r.reject,children:r.message}),o.jsx(lT,{data:l})]})}const uT=d.forwardRef(cT);function dT(t){let{children:n}=t,r=d.useRef();const i=d.useMemo(()=>({showNotice:l=>r.current.showNotice(l),showModal:l=>r.current.showModal(l)}),[]);return o.jsx(_S.Provider,{value:i,children:o.jsx(uT,{ref:r,children:n})})}const fT=({value:t=!1,type:n="",icon:r="",disabled:i=!1,iconActive:l="",onClick:u,title:f="",tooltip:h,css:g="",text:y="",textActive:w="",children:b,active:x,onChange:M})=>{const[k,N]=po(t),E=d.useMemo(()=>(k?"pressed":"")+(n?" "+n:""),[k,n]),I=d.useCallback(T=>{let P=!k;u&&u(T),T.defaultPrevented||(N(P),M&&M({value:P}))},[k,u,M]);return k&&x?o.jsx(Kf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&l||r,onClick:I,disabled:i,children:Pv(x,{value:k})}):b?o.jsx(Kf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&l||r,onClick:I,disabled:i,children:b}):o.jsx(Kf,{title:f,tooltip:h,text:k&&w||y,css:g,type:E,icon:k&&l||r,onClick:I,disabled:i})};function mT(){return o.jsx(o.Fragment,{})}function Mw(t){const{fonts:n=!0,children:r}=t;return o.jsx(Hv.Provider,{value:"willow",children:o.jsxs(o.Fragment,{children:[r&&r&&o.jsx("div",{className:"wx-theme wx-willow-theme",children:r}),n&&o.jsxs(o.Fragment,{children:[o.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),o.jsx(mT,{}),o.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Fv(Yr);const Wv={grid:{"Add before":"Add before","Add after":"Add after",Copy:"Copy",Cut:"Cut",Paste:"Paste",Delete:"Delete","New row":"New row","Move up":"Move up","Move down":"Move down",Undo:"Undo",Redo:"Redo",selected:"selected"}};new Date().valueOf();var BS=class{constructor(t){this._nextHandler=null,this._dispatch=t,this.exec=this.exec.bind(this)}async exec(t,n){return this._dispatch(t,n),this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};new Date().valueOf();var pT=class{constructor(t){const n={id:0,$level:0,data:[],parent:null},r=new Map;r.set(0,n),this._pool=r,t&&t.length&&this.parse(t,0)}parse(t,n){const r=this._pool;for(let l=0;l<t.length;l++){const u=t[l];u.parent=u.parent||n,u.data=null,r.set(u.id,u)}for(let l=0;l<t.length;l++){const u=t[l],f=r.get(u.parent);f&&(f.data||(f.data=[]),f.data.push(u))}const i=r.get(n);this.setLevel(i,i.$level+1,!1)}add(t,n){const r=this._pool.get(t.parent||0);t.$level=r.$level+1,this._pool.set(t.id,t),r.data?n===-1?r.data=[...r.data,t]:Aw(r,n,t):r.data=[t]}addAfter(t,n){if(!n)return this.add(t,-1);const r=this.byId(n),i=this.byId(r.parent),l=gp(i,r.id)+1;t.parent=i.id,t.$level=i.$level+1,this.add(t,l)}remove(t){const n=this._pool.get(t);this._remove(n);const r=this._pool.get(n.parent);r.data=r.data.filter(i=>i.id!=t),this._clearBranch(r)}_remove(t){t.data&&t.data.forEach(n=>this._remove(n)),this._pool.delete(t.id)}update(t,n){let r=this._pool.get(t);const i=this._pool.get(r.parent),l=gp(i,r.id);r={...r,...n},i&&l>=0&&(i.data[l]=r,i.data=[...i.data]),this._pool.set(r.id,r)}move(t,n,r){const i=this._pool.get(t),l=n==="child",u=this._pool.get(r),f=u.$level+(l?1:0);if(!i||!u)return;const h=this._pool.get(i.parent),g=l?u:this._pool.get(u.parent);g.data||(g.data=[]);const y=gp(h,i.id);hT(h,y);const w=l?g.data.length:gp(g,u.id)+(n==="after"?1:0);if(Aw(g,w,i),h.id===g.id&&y===w)return null;i.parent=g.id,i.$level!==f&&(i.$level=f,this.setLevel(i,f+1,!0)),this.update(i.id,i),this._clearBranch(h)}_clearBranch(t){t.data&&!t.data.length&&(t.open&&delete t.open,this.update(t.id,{data:null}))}toArray(){const t=[],n=this._pool.get(0).data;return n&&zS(n,t),t}byId(t){return this._pool.get(t)}getBranch(t){return this._pool.get(t).data}forEach(t){this._pool.forEach((n,r)=>{r!==0&&t(n)})}eachChild(t,n){const r=this.byId(n);!r||!r.data||r.data.forEach((i,l)=>{t(this.byId(i.id),l),this.eachChild(t,i.id)})}setLevel(t,n,r){t.data&&(t.data=t.data.map(i=>(r&&(i={...i},this._pool.set(i.id,i)),i.$level=n,i.data&&this.setLevel(i,n+1,r),i)))}};function zS(t,n){t.forEach(r=>{n.push(r),r.open===!0&&zS(r.data,n)})}function hT(t,n){const r=[...t.data];r.splice(n,1),t.data=r}function Aw(t,n,r){const i=[...t.data];i.splice(n,0,r),t.data=i}function gp(t,n){return t?.data.findIndex(r=>r.id===n)}var $S=2,gT=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,r=0){const i={};return this._wrapProperties(n,this._state,this._values,"",i,r),i}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,r,i,l,u,f){for(const h in n){const g=r[h],y=i[h],w=n[h];if(g&&(y===w&&typeof w!="object"||w instanceof Date&&y instanceof Date&&y.getTime()===w.getTime()))continue;const b=l+(l?".":"")+h;g?(g.__parse(w,b,u,f)&&(i[h]=w),f&$S?u[b]=g.__trigger:g.__trigger()):(w&&w.__reactive?r[h]=this._wrapNested(w,w,b,u):r[h]=this._wrapWritable(w),i[h]=w),u[b]=u[b]||null}}_wrapNested(n,r,i,l){const u=this._wrapWritable(n);return this._wrapProperties(n,u,r,i,l,0),u.__parse=(f,h,g,y)=>(this._wrapProperties(f,u,r,h,g,y),!1),u}_wrapWritable(n){const r=[],i=function(){for(let l=0;l<r.length;l++)r[l](n)};return{subscribe:l=>(r.push(l),this._async?setTimeout(l,1,n):l(n),()=>{const u=r.indexOf(l);u>=0&&r.splice(u,1)}),__trigger:()=>{r.length&&(this._async?setTimeout(i,1):i())},__parse:function(l){return n=l,!0}}}};function Nw(t,n){return Object.defineProperty(t,"__reactive",{value:!0,enumerable:!1,writable:!1}),t}var vT=class{constructor(n,r,i,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=r,this._parsers=i,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(u=>{u.in.forEach(f=>{const h=this._triggers.get(f)||[];h.push(u),this._triggers.set(f,h)}),u.out.forEach(f=>{const h=this._sources.get(f)||{};u.in.forEach(g=>h[g]=!0),this._sources.set(f,h)})}),this._routes.forEach(u=>{u.length=Math.max(...u.in.map(f=>US(f,this._sources,1)))}),this._bus=l}init(n){const r={};for(const i in n)if(this._prev[i]!==n[i]){const l=this._parsers[i];r[i]=l?l(n[i]):n[i]}this._prev=this._prev?{...this._prev,...n}:{...n},this.setState(r),this._bus&&this._bus.exec("init-state",r)}setStateAsync(n){const r=this._setter(n,$S);return this._async?Object.assign(this._async.signals,r):this._async={signals:r,timer:setTimeout(this._applyState.bind(this),1)},r}_applyState(){const n=this._async;if(n){this._async=null,this._triggerUpdates(n.signals,[]);for(const r in n.signals){const i=n.signals[r];i&&i()}}}setState(n,r=[]){const i=this._setter(n);return this._triggerUpdates(i,r),i}_triggerUpdates(n,r){const i=Object.keys(n),l=!r.length;r=r||[];for(let u=0;u<i.length;u++){const f=i[u],h=this._triggers.get(f);h&&h.forEach(g=>{r.indexOf(g)==-1&&r.push(g)})}l&&this._execNext(r)}_execNext(n){for(;n.length;){n.sort((i,l)=>i.length<l.length?1:-1);const r=n[n.length-1];n.splice(n.length-1),r.exec(n)}}};function US(t,n,r){const i=n.get(t);if(!i)return r;const l=Object.keys(i).map(u=>US(u,n,r+1));return Math.max(...l)}var yT=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,r,i){let l=this._handlers[n];l?i&&i.intercept?l.unshift(r):l.push(r):l=this._handlers[n]=[r],i&&i.tag&&this._tag.set(r,i.tag)}intercept(n,r,i){this.on(n,r,{...i,intercept:!0})}detach(n){for(const r in this._handlers){const i=this._handlers[r];for(let l=i.length-1;l>=0;l--)this._tag.get(i[l])===n&&i.splice(l,1)}}async exec(n,r){const i=this._handlers[n];if(i)for(let l=0;l<i.length;l++){const u=i[l](r);if(u===!1||u&&u.then&&await u===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,r),r}setNext(n){return this._nextHandler=n}};const cd=1024;function tm(t){return t<cd?`${t} B`:t<cd**2?`${(t/cd).toFixed(1)} KB`:t<cd**3?`${(t/cd**2).toFixed(1)} MB`:`${(t/cd**3).toFixed(1)} GB`}function Tw(t,n){n||(n={key:"name",order:"asc"});const r=t.filter(f=>f.type==="folder"),i=t.filter(f=>f.type!=="folder"),l=r.sort(Rw(n)),u=i.sort(Rw(n));return[...l,...u]}function bT(t,n){return typeof t=="string"?t.localeCompare(n,void 0,{numeric:!0}):typeof t=="object"?t.getTime()-n.getTime():(t??0)-(n??0)}function wT(t,n){return typeof t=="string"?-t.localeCompare(n,void 0,{numeric:!0}):typeof n=="object"?n.getTime()-t.getTime():(n??0)-(t??0)}function Rw({key:t,order:n}){const r=n==="asc"?bT:wT;return(i,l)=>r(i[t],l[t])}function Gv(t,n){const r=t==="/"?1:t.split("/").length;return r>=n.length?null:n[r].id}function xT(t){return t.length>1?t[t.length-2].id:null}let ST=class extends pT{constructor(n){const r={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([r]),this.parse(n,"/")}parse(n,r,i){!n||!n.length||(n.forEach(l=>this.parseId(l,i?r:void 0)),super.parse(n,r))}parseId(n,r){if(n.parent===0)return;const i=n.id,l=i.lastIndexOf("/");if(n.parent=r??(l===0?"/":i.slice(0,l)),n.name=i.slice(l+1),n.type=n.type||"file",n.type!=="folder"){const u=n.name.lastIndexOf("."),f=u!==-1?n.name.slice(u+1):"";n.ext=f!=="new"?f?.toLocaleLowerCase():""}}getParents(n){const r=[];let i=this.byId(n);if(!i)return r;for(;i.id!==0;)r.push(i),i=this.byId(i.parent);return r.reverse()}findFiles(n,r="/"){const i=[],l=n.toLocaleLowerCase();return this.eachChild(u=>{u.name.toLowerCase().indexOf(l)!==-1&&i.push(u)},r),i}add(n,r){const i=this.byId(n.parent||"/"),l=n.data?[...n.data]:null;n.data=null,super.add(n,r??i.data?i.data.length:0),l&&l.forEach(u=>this.add(u))}renameFiles(n,r,i){const l=this.byId(n),u=this.normalizeFile(l,r),f=[];return u.data?.forEach(h=>f.push(this.renameFiles(h.id,u.id,i))),f.length&&(u.data=f),i[n]=u.id,u}copyFiles(n,r,i){const l={};return n.forEach(u=>{const f=this.renameFiles(u,r,l);this.add(f),i&&this.remove(u),l[u]=f.id}),l}moveFiles(n,r){if(this.byId(n[0]).parent!==r)return this.copyFiles(n,r,!0)}serialize(n="/"){const r=[],i=this.byId(n);return i?(i.data?.forEach(l=>{const{id:u,date:f,type:h,size:g,lazy:y}=l,w={id:u,date:f,type:h??"file"};y&&(w.lazy=y),g&&(w.size=g),r.push(w);const b=this.serialize(u);b.length&&r.push(...b)}),r):null}normalizeFile(n,r){const i=n.name,l=i.lastIndexOf("."),u=l!==-1?i.slice(l+1):"",f=u?`.${u}`:"";let h=l!==-1?i.slice(0,l):i,g=r+(r==="/"?"":"/")+h;for(;this.byId(g+f);){const y=".new";g+=y,h+=y}return{...n,id:g+f,name:h+f,parent:r,ext:u.toLocaleLowerCase()}}},CT=class extends gT{in;_router;constructor(n){super({writable:n,async:!1});const r=[];for(let u=0;u<2;u++)r.push({in:["data",`panels.${u}.path`],out:[`panels.${u}._crumbs`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];y[u]={_crumbs:h.getParents(g[u].path)},this.setState({panels:y},f)}}),r.push({in:["data",`panels.${u}.path`,`panels.${u}._sorts`,"search"],out:[`panels.${u}._files`],exec:f=>{const{data:h,panels:g,search:y}=this.getState();let w;y?w=h.findFiles(y,g[u].path):w=h.byId(g[u].path)?.data||[];const{path:b,_sorts:x}=g[u];w=Tw(w,x[b]);const M=[];M[u]={_files:w},this.setState({panels:M},f)}}),r.push({in:["data",`panels.${u}.selected`,`panels.${u}._sorts`],out:[`panels.${u}._selected`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];g[u].selected.forEach(k=>{const N=h.byId(k);N&&y.push(N)});const{path:w,_sorts:b}=g[u],x=Tw(y,b[w]),M=[];M[u]={_selected:x},this.setState({panels:M},f)}});this._router=new vT(super.setState.bind(this),r,{data:u=>new ST(u)});const i=this.in=new yT;i.on("select-file",({id:u,toggle:f,range:h,panel:g,type:y})=>{const{panels:w,activePanel:b}=this.getState();typeof g>"u"&&(g=b),u||(f=h=!1);let x=[...w[g].selected];if(f){const k=x.indexOf(u);k===-1?x.push(u):x.splice(k,1)}else if(h&&w[g]._lastSelected){const k=w[g]._files;let N=k.findIndex(T=>T.id==w[g]._lastSelected),E=k.findIndex(T=>T.id==u);E<N&&([N,E]=[E,N]);const I=k.slice(N,E+1).map(T=>T.id);x=[...new Set([...x,...I])]}else x=u?[u]:[];const M=[];M[g]={selected:x,_lastSelected:u,_selectNavigation:y==="navigation"},this.setState({panels:M})}),i.on("set-path",({id:u,panel:f,selected:h})=>{const{data:g,activePanel:y}=this.getState(),w=g.byId(u);if(w){const b=[];typeof f>"u"&&(f=y),b[f]={path:u},this.setState({panels:b}),i.exec("select-file",{panel:f}),h&&h.forEach(x=>i.exec("select-file",{id:x,panel:f,toggle:!0})),w.lazy&&i.exec("request-data",{id:u})}}),i.on("provide-data",({id:u,data:f})=>{const{mode:h,data:g}=this.getState(),y=g.byId(u);y&&(y.lazy||(y.data=[]),y.lazy=!1,g.parse(f,u,h==="search"),this.setState({data:g}))}),i.on("open-tree-folder",({id:u,mode:f})=>{const{data:h}=this.getState();h.update(u,{open:f}),this.setState({data:h})}),i.on("show-preview",({mode:u})=>{this.setState({preview:u})}),i.on("rename-file",u=>{const{id:f,name:h}=u,{data:g,panels:y}=this.getState(),w=g.byId(f);if(w.name!==h){w.name=h;const b=g.normalizeFile(w,w.parent);u.newId=b.id,b.data=null,g.add(b);let x={[f]:b.id};w.data?.forEach(k=>x={...g.moveFiles([k.id],b.id),...x});const M=y.map(k=>({selected:k.selected,_crumbs:k._crumbs,_lastSelected:k._lastSelected,_sorts:k._sorts}));g.remove(f),this._updatePanels(M,x),this.setState({data:g,panels:M})}}),i.on("create-file",u=>{const{file:f,parent:h}=u,{data:g}=this.getState(),y=g.normalizeFile(f,h);y.type=f.type||"file",u.newId=y.id,g.add(y),this.setState({data:g}),i.exec("select-file",{id:y.id})}),i.on("delete-files",({ids:u})=>{const{data:f,panels:h}=this.getState(),g=h.map(y=>({selected:y.selected,_crumbs:y._crumbs,_lastSelected:y._lastSelected,_sorts:y._sorts}));u.forEach(y=>f.remove(y)),this._updatePanels(g,{}),this.setState({data:f,panels:g})}),i.on("copy-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot copy a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.copyFiles(f,h);u.newIds=f.map(x=>b[x]),this.setState({data:g}),y[w].path==h&&(i.exec("select-file",{}),f.forEach(x=>{i.exec("select-file",{id:b[x],toggle:!0})}))}),i.on("move-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot move a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.moveFiles(f,h);if(b){u.newIds=f.map(M=>b[M]);const x=y.map(M=>({selected:M.selected,_crumbs:M._crumbs,_lastSelected:M._lastSelected,_sorts:M._sorts}));this._updatePanels(x,b,!0),this.setState({data:g,panels:x}),y[w].path==h&&(i.exec("select-file",{}),f.forEach(M=>{i.exec("select-file",{id:b[M],toggle:!0})}))}});let l=null;i.on("filter-files",({text:u})=>{if(!u){l&&this.setState({...l});return}i.exec("select-file",{});const{panels:f,mode:h}=this.getState();l||(l={panels:f,mode:h,search:""}),this.setState({mode:"search",search:u})}),i.on("set-mode",({mode:u})=>{const{activePanel:f}=this.getState(),h=[];h[f]={_selectNavigation:!1};const g={mode:u,search:"",panels:h};l=null,this.setState(g)}),i.on("set-active-panel",({panel:u})=>{this.setState({activePanel:u})}),i.on("sort-files",({key:u,order:f,panel:h,path:g})=>{const{activePanel:y,panels:w}=this.getState();h=h??y,g=g??w[h].path;const b=[];b[h]={_sorts:{...w[h]._sorts,[g]:{key:u,order:f}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const n=[];for(let i=0;i<2;i++)n[i]=Nw({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...n[i]});const r={panels:Nw(n),data:[],search:""};this._router.init(r)}init(n){const r={...n};this._router.init(r)}setState(n,r){return this._router.setState(n,r)}getFile(n){const{data:r}=this.getState();return r.byId(n)||null}serialize(n){const{data:r}=this.getState();return r.serialize(n)}_updatePanels(n,r,i){const{data:l}=this.getState();n.forEach(u=>{const f=[];u.selected.forEach(y=>{l.byId(y)?f.push(y):!i&&r[y]&&f.push(r[y])}),u.selected=f,l.byId(u._lastSelected)||(u._lastSelected=i?null:r[u._lastSelected]||null);const h={};Object.keys(u._sorts).forEach(y=>{l.byId(y)?h[y]=u._sorts[y]:r[y]&&!i&&(h[r[y]]=u._sorts[y])}),u._sorts=h;const g=u._crumbs[u._crumbs.length-1];g?.id!=="/"&&(r[g.id]?u.path=r[g.id]:l.byId(g.id)||(u.path="/"))})}_isPlacedIntoSelf(n,r){return n.some(i=>i===r||this.getState().data.getParents(r).some(l=>l.id===i))}};function kT(t){switch(t){case"body":return[{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"}];case"add":return[{icon:"mdi mdi-folder-plus-outline",text:"Add new file",id:"add-file"},{icon:"mdi mdi-file-plus-outline",text:"Add new folder",id:"add-folder"},{icon:"mdi mdi-file-upload-outline",text:"Upload file",id:"upload",comp:"upload"}];case"multiselect":return[{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{comp:"separator"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}];default:return[t==="folder"?null:{icon:"wxi-download",text:"Download",hotkey:"Ctrl+D",id:"download"},{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"},{comp:"separator"},{icon:"wxi-edit",text:"Rename",hotkey:"Ctrl+R",id:"rename"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}].filter(n=>n!==null)}}function MT(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function AT(t,n="data-id"){const r=MT(t,n);return r?r.getAttribute(n):null}new Date().valueOf();function NT(t,n){const{api:r}=n;function i(u,f){const h=n.getPanel(),g=h.selected,y=f.ctrlKey||f.metaKey,w=f.shiftKey;let b;const x=g?.[0]?r.getFile(g[0]):null;g?.length?g.length>1?b=n.menuOptions("multiselect"):b=n.menuOptions(x.type,x):b=n.menuOptions("body");const M=`${y?"ctrl+":""}${w?"shift+":""}${u}`,k=b?b.find(E=>E.hotkey?.toLowerCase()===M):!1,N=n.performAction;if(k)switch(M){case"ctrl+c":N("copy");break;case"ctrl+x":N("move");break;case"ctrl+v":N("paste",x);break;case"delete":N("delete");break;case"ctrl+r":f.preventDefault(),N("rename",x);break;case"ctrl+d":f.preventDefault(),N("download",x);break;default:k.handler?.({context:x})}switch(u){case"enter":{if(y||w)break;const{_crumbs:E,_selectNavigation:I}=h;if(I){const T=xT(E);if(T){const P=Gv(T,E);r.exec("set-path",{id:T,selected:[P]})}}else if(g.length===1){const T=r.getFile(g[0]);T&&r.exec(T.type==="folder"?"set-path":"open-file",{id:T.id})}break}case"arrowup":case"arrowleft":{const{_files:E,_selected:I,path:T,_selectNavigation:P}=h;let U;if(I.length){const F=I.at(0).id,Y=E.findIndex(D=>D.id===F);if(Y!==-1){const D=Y-1;E[D]?U=E[D].id:T!=="/"&&!(y||w)&&r.exec("select-file",{type:"navigation"})}}else{if(P)break;if(T!=="/"){r.exec("select-file",{type:"navigation"});break}U=E.at(0)?.id}U&&r.exec("select-file",{id:U,toggle:y,range:w});break}case"arrowdown":case"arrowright":{const{_files:E,_selected:I,path:T,_selectNavigation:P}=h;let U;if(I.length){const F=I.at(-1).id,Y=E.findIndex(D=>D.id===F);if(Y!==-1){const D=Y+1;E[D]&&(U=E[D].id)}}else{if(T!=="/"&&!P){r.exec("select-file",{type:"navigation"});break}U=E.at(0)?.id}U&&r.exec("select-file",{id:U,toggle:y,range:w});break}}}function l(u){const f=u.code.replace("Key","").toLowerCase();i(f,u),f=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&r.exec("set-active-panel",{panel:+AT(h,"data-panel")})})}return t.addEventListener("keydown",l),{destroy:()=>{t.removeEventListener("keydown",l)}}}function TT(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function RT(t,n="data-id"){const r=t.getAttribute(n);return r?jT(r):null}function jT(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function ET(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var DT=ET();new Date().valueOf();function qS(t){const[n,r]=d.useState(t),i=d.useRef(t);return d.useEffect(()=>{if(i.current!==t){if(Array.isArray(i.current)&&Array.isArray(t)&&i.current.length===0&&t.length===0)return;i.current=t,r(t)}},[t]),[n,r]}function IT(t,n,r){const[i,l]=d.useState(()=>n);return t||console.warn(`Writable ${r} is not defined`),d.useEffect(()=>t?t.subscribe(f=>{l(()=>f)}):void 0,[t]),i}function Lt(t,n){const r=t.getState(),i=t.getReactiveState();return IT(i[n],r[n],n)}function LT(t,n){const r=d.useRef(n);r.current=n;const[i,l]=d.useState(1);return d.useEffect(()=>t.subscribe(f=>{r.current=f,l(h=>h+1)}),[t]),[r.current,i]}function Vs(t,n){const r=t.getState(),i=t.getReactiveState();return LT(i[n],r[n])}function WS(t){const n={};return t.split(";").forEach(r=>{const[i,l]=r.split(":");if(l){let u=i.trim();u.indexOf("-")&&(u=u.replace(/-([a-z])/g,(f,h)=>h.toUpperCase())),n[u]=l.trim()}}),n}function GS(t){let n=t,r=[];return{subscribe:h=>{r.push(h),h(n)},unsubscribe:h=>{r=r.filter(g=>g!==h)},set:h=>{n=h,r.forEach(g=>g(n))},update:h=>{n=h(n),r.forEach(g=>g(n))}}}function jw(t,n,r){function i(l){const u=TT(l);if(!u)return;const f=RT(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}return DT.addEvent(t,r,i)}function _T(t,n){const r=[jw(t,n,"click")];return n.dblclick&&r.push(jw(t,n.dblclick,"dblclick")),()=>{r.forEach(i=>i())}}function VS(t,n){return t.map((r,i)=>{const l=n(r,i);return r.data&&r.data.length&&(l.data=VS(r.data,n)),l}).filter(Boolean)}function KS(t,n){const r=[];return t.forEach(i=>{if(i.data){const l=KS(i.data,n);l.length&&r.push({...i,data:l})}else n(i)&&r.push(i)}),r}function PT(t){return VS(t,(n,r)=>{const i={...n,id:n.id||Ov()};return i.type&&(i.comp=i.type),i.comp==="separator"&&t[r-1]?.comp==="separator"?null:i})}const QS={};function FT(t){return QS[t]||t}function OT(t,n){QS[t]=n}function HT({onClick:t,onShow:n,option:r}){const i=d.useRef(null),l=d.useCallback(()=>{n(r.data?r.id:!1,i.current)},[n,r]),u=d.useCallback(h=>{if(r.data){h.stopPropagation(),n(r.id,i.current);return}t(h)},[t,n,r]),f=d.useMemo(()=>r&&r.comp?FT(r.comp):null,[r]);return o.jsxs("div",{ref:i,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":za(r.id),onMouseEnter:l,onClick:u,children:[r.icon?o.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${r.icon}`}):null,r.comp?f?o.jsx(f,{item:r,option:r}):null:o.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",r.text," "]}),r.subtext?o.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:r.subtext}):null,r.data?o.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function Vv({options:t,left:n=0,top:r=0,at:i="bottom",parent:l=null,mount:u=null,context:f=null,css:h="",onClick:g,onCancel:y}){const[w,b]=d.useState(-1e4),[x,M]=d.useState(-1e4),[k,N]=d.useState(20),[E,I]=d.useState(),T=d.useRef(null),[P,U]=d.useState(!1),[F,Y]=d.useState(null),D=d.useCallback(()=>{const $=ES(T.current,l,i,n,r);$&&(b($.x),M($.y),I($.width));let ee=$?.z??20;const B=l?NN(l):[];let L=0;for(const oe of B){const be=parseInt(getComputedStyle(oe).zIndex,10);be>L&&(L=be)}L>=ee&&(ee=L+1),N(ee)},[l,i,n,r]);d.useEffect(()=>{u&&u(D)},[]);const K=d.useCallback(()=>{U(!1)},[]),ne=d.useCallback(($,ee)=>{U($),Y(ee)},[]),q=d.useMemo(()=>PT(t),[t]);d.useEffect(()=>{D()},[l,D]);const O=d.useRef(g),W=d.useRef(y),ce=d.useRef(l);return d.useEffect(()=>{O.current=g},[g]),d.useEffect(()=>{W.current=y},[y]),d.useEffect(()=>{ce.current=l},[l]),d.useEffect(()=>{if(!T.current)return;function $(ee){W.current?W.current(ee):O.current&&O.current({action:null,option:null})}return go(T.current,{callback:$,modal:!0,parent:()=>ce.current}).destroy},[]),o.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:x+"px",left:w+"px",width:E,zIndex:k},onMouseLeave:K,children:q.map($=>o.jsxs(d.Fragment,{children:[$.comp==="separator"?o.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):o.jsx(HT,{option:$,onShow:ne,onClick:ee=>{if(!$.data&&!ee.defaultPrevented){const B={context:f,action:$,option:$,event:ee};$.handler&&$.handler(B),g&&g(B),ee.stopPropagation()}}}),$.data&&P===$.id?o.jsx(Vv,{css:h,options:$.data,at:"right-overlap",parent:F,context:f,onClick:g,onCancel:y}):null]},$.id))})}const YS=d.forwardRef(function(t,n){const{options:r,at:i="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,[w,b]=d.useState(null),[x,M]=d.useState(null),[k,N]=d.useState(0),[E,I]=d.useState(0),T=d.useRef(null),P=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),U=d.useMemo(()=>w!==null&&f?KS(r,K=>f(K,w)):r,[w,f,r]);function F(K){M(null),y&&y(K)}function Y(K){if(T.current===K){T.current=null;return}M(null),y&&y({action:null,option:null})}const D=d.useCallback((K,ne)=>{if(!K){M(null);return}if(K.defaultPrevented)return;const q=K.target;if(q&&q.dataset&&q.dataset.menuIgnore)return;if(x&&x===q){M(null),K.preventDefault();return}N(K.clientX+1),I(K.clientY+1);let O=typeof ne<"u"?ne:em(q,P);l&&(O=l(O,K),!O)||(b(O),M(q),T.current=K.nativeEvent||K,K.preventDefault())},[x,P,l]);return d.useImperativeHandle(n,()=>({show:D}),[D]),o.jsxs(o.Fragment,{children:[g?o.jsx("span",{onClick:D,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,x?o.jsx(Bv,{children:o.jsx(Vv,{css:h,at:i,top:E,left:k,parent:x,context:w,onClick:F,onCancel:Y,options:U},x)}):null]})}),BT=d.forwardRef(function(t,n){const{options:r,at:i="bottom",css:l="",children:u,onClick:f}=t,[h,g]=d.useState(null),y=d.useRef(null);function w(k){g(null),f&&f(k)}function b(k){if(y.current===k){y.current=null;return}g(null),f&&f({action:null,option:null})}const x=d.useCallback(k=>{g(k.target),y.current=k.nativeEvent||k,k.preventDefault()},[]);d.useImperativeHandle(n,()=>({show:x}),[x]);function M(k){let N=k.target;for(;!N.dataset.menuIgnore;)g(N),N=N.parentNode}return o.jsxs(o.Fragment,{children:[o.jsx("span",{onClick:M,"data-menu-ignore":"true",children:u}),h?o.jsx(Bv,{children:o.jsx(Vv,{css:l,at:i,parent:h,options:r,onClick:w,onCancel:b})}):null]})}),zT=d.forwardRef(function(t,n){const{options:r,at:i="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,w=d.useRef(null),b=d.useCallback((x,M)=>{w.current.show(x,M)},[]);return d.useImperativeHandle(n,()=>({show:b}),[b]),o.jsxs(o.Fragment,{children:[g?o.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,o.jsx(YS,{css:h,at:i,options:r,resolver:l,dataKey:u,filter:f,ref:w,onClick:y})]})}),$T={uploader:{B:"B",KB:"KB",MB:"MB",GB:"GB",TB:"TB",PB:"PB",EB:"EB","Drop files here or":"Drop files here or","select files":"select files"}};let UT=class{constructor(n,r,i,l,u){this.setFiles=n,this.setReady=r,this.setSignal=i,this.setDrag=l,u&&u.length&&this.setFiles(u)}open(n){this.setSignal(["click",n||{}])}getState(){let n="server";const r=this.files;for(let i=0;i<r.length;i++){if(r[i].status==="client")return"client";r[i].status==="error"&&(n="error")}return n}droparea(n,r){r=r||{};const i=()=>{r.dragEnter&&r.dragEnter(),this.setDrag(!0)},l=()=>{r.dragLeave&&r.dragLeave(),this.setDrag(!1)},u=h=>{h.preventDefault()},f=h=>{h.preventDefault(),this.setDrag(!1),this.setSignal(["drop",r,h]),r.dragLeave&&r.dragLeave(),r.drop&&r.drop()};return n.addEventListener("dragenter",i),n.addEventListener("dragleave",l),n.addEventListener("dragover",u,!0),n.addEventListener("drop",f,!0),()=>{n.removeEventListener("dragenter",i),n.removeEventListener("dragleave",l),n.removeEventListener("dragover",u,!0),n.removeEventListener("drop",f,!0)}}updateFile(n,r){const i=this.files.findIndex(u=>u.id===n);if(i===-1)return;const l=[...this.files];return l[i]={...l[i],...r},this.files=l,this.setFiles(this.files),this.files[i]}deleteFile(n){this.files=this.files.filter(r=>r.id!==n),this.setFiles(this.files)}addFile(n,r){r?this.files=[...this.files,n]:this.files=[n],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function XS(t){const[n,r]=d.useState([]),[i,l]=d.useState(Promise.resolve(null)),[u,f]=d.useState(null),[h,g]=d.useState(!1),y=d.useRef();return y.current||(y.current=new UT(r,l,f,g,t)),y.current.files=n,y.current.ready=i,y.current.signal=u,y.current.drag=h,y.current}function qT(t,n){{if(t){const r=t.getGroup(n);if(r)return r}return rm($T).getGroup(n)}}const WT=()=>Math.random().toString(36).substr(2,9),GT=({data:t,accept:n="",multiple:r=!0,folder:i=!1,uploadURL:l="",apiOnly:u=!1,disabled:f=!1,children:h,onChange:g,onUpload:y})=>{const w=d.useRef(null),b=d.useRef(null),[x,M]=d.useState({}),k=XS(),N=t||k,E=d.useContext(Ua.i18n),I=qT(E,"uploader");d.useEffect(()=>{w.current&&i&&(w.current.webkitdirectory=!0)},[i]),d.useEffect(()=>{if(!u&&b.current&&!f)return N.droparea(b.current)},[u,f,b]);const T=q=>{const O=new FormData;return O.append("upload",q.file),fetch(l,{method:"POST",body:O}).then(W=>W.json()).then(W=>({id:q.id,...W}),()=>({id:q.id,status:"error"})).catch(W=>(console.log(W),{id:q.id,status:"error"}))},P=(q,O)=>{const W=N.updateFile(q,O),ce={...W,status:N.getState()};W&&W.uploaded&&W.uploaded(ce),y&&y(ce),W.temp&&N.deleteFile(W.id)},U=q=>{if(!q)return;const O=typeof l=="function"?l(q):T(q);N.setReady(O.then(W=>{W.status=W.status||"server",P(q.id,W)}).catch(W=>{P(q.id,{status:"error",error:W})}))},F=(q,O)=>{const W={...O||x,id:WT(),status:"client",name:q.name,file:q};W.selected&&W.selected(W),g&&g(W),N.addFile(W,r),U(W),w.current&&(w.current.value="")},Y=(q,O,W)=>{q.isFile?q.file(ce=>{F(ce,W)}):q.isDirectory&&q.createReader().readEntries(ce=>{ce.forEach($=>{Y($,O+$.name+"/",W)})})},D=q=>{Array.from(q.target.files).forEach(O=>F(O))},K=(q,O)=>{Array.from(q.dataTransfer.items).forEach(W=>{const ce=W.webkitGetAsEntry();ce&&Y(ce,"",O)})},ne=()=>{w.current&&w.current.click()};return d.useEffect(()=>{if(N.signal){const[q,O,W]=N.signal;M(O),q==="click"?ne():q==="drop"&&K(W,O),N.setSignal(null)}},[N.signal]),u?o.jsxs(o.Fragment,{children:[o.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h]}):o.jsxs("div",{className:`wx-at1A8tb8 wx-label ${N.drag?"wx-active":""} ${f?"wx-disabled":""}`,ref:b,children:[o.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h||o.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:o.jsxs("span",{children:[I("Drop files here or")," ",o.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:ne,children:I("select files")})]})})]})};new Date().valueOf();function VT(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in n){const i=t[r],l=n[r];if(!oh(i,l))return!1}return!0}function oh(t,n){if(typeof t=="number"||typeof t=="string"||typeof t=="boolean"||t===null)return t===n;if(typeof t!=typeof n||(t===null||n===null)&&t!==n||t instanceof Date&&n instanceof Date&&t.getTime()!==n.getTime())return!1;if(typeof t=="object")if(Array.isArray(t)&&Array.isArray(n)){if(t.length!==n.length)return!1;for(let r=t.length-1;r>=0;r--)if(!oh(t[r],n[r]))return!1;return!0}else return VT(t,n);return t===n}function hv(t){if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t);if(t instanceof Array)return t.map(hv);const n={};for(const r in t)n[r]=hv(t[r]);return n}var ZS=2,KT=class{constructor(t){t&&(this._writable=t.writable,this._async=t.async),this._values={},this._state={}}setState(t,n=0){const r={};return this._wrapProperties(t,this._state,this._values,"",r,n),r}getState(){return this._values}getReactive(){return this._state}_wrapProperties(t,n,r,i,l,u){for(const f in t){const h=n[f],g=r[f],y=t[f];if(h&&(g===y&&typeof y!="object"||y instanceof Date&&g instanceof Date&&g.getTime()===y.getTime()))continue;const w=i+(i?".":"")+f;h?(h.__parse(y,w,l,u)&&(r[f]=y),u&ZS?l[w]=h.__trigger:h.__trigger()):(y&&y.__reactive?n[f]=this._wrapNested(y,y,w,l):n[f]=this._wrapWritable(y),r[f]=y),l[w]=l[w]||null}}_wrapNested(t,n,r,i){const l=this._wrapWritable(t);return this._wrapProperties(t,l,n,r,i,0),l.__parse=(u,f,h,g)=>(this._wrapProperties(u,l,n,f,h,g),!1),l}_wrapWritable(t){const n=[],r=function(){for(let i=0;i<n.length;i++)n[i](t)};return{subscribe:i=>(n.push(i),this._async?setTimeout(i,1,t):i(t),()=>{const l=n.indexOf(i);l>=0&&n.splice(l,1)}),__trigger:()=>{n.length&&(this._async?setTimeout(r,1):r())},__parse:function(i){return t=i,!0}}}},QT=class{constructor(t,n,r,i){typeof t=="function"?this._setter=t:this._setter=t.setState.bind(t),this._routes=n,this._parsers=r,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(l=>{l.in.forEach(u=>{const f=this._triggers.get(u)||[];f.push(l),this._triggers.set(u,f)}),l.out.forEach(u=>{const f=this._sources.get(u)||{};l.in.forEach(h=>f[h]=!0),this._sources.set(u,f)})}),this._routes.forEach(l=>{l.length=Math.max(...l.in.map(u=>JS(u,this._sources,1)))}),this._bus=i}init(t){const n={};for(const r in t)if(this._prev[r]!==t[r]){const i=this._parsers[r];n[r]=i?i(t[r]):t[r]}this._prev=this._prev?{...this._prev,...t}:{...t},this.setState(n),this._bus&&this._bus.exec("init-state",n)}setStateAsync(t){const n=this._setter(t,ZS);return this._async?Object.assign(this._async.signals,n):this._async={signals:n,timer:setTimeout(this._applyState.bind(this),1)},n}_applyState(){const t=this._async;if(t){this._async=null,this._triggerUpdates(t.signals,[]);for(const n in t.signals){const r=t.signals[n];r&&r()}}}setState(t,n=[]){const r=this._setter(t);return this._triggerUpdates(r,n),r}_triggerUpdates(t,n){const r=Object.keys(t),i=!n.length;n=n||[];for(let l=0;l<r.length;l++){const u=r[l],f=this._triggers.get(u);f&&f.forEach(h=>{n.indexOf(h)==-1&&n.push(h)})}i&&this._execNext(n)}_execNext(t){for(;t.length;){t.sort((r,i)=>r.length<i.length?1:-1);const n=t[t.length-1];t.splice(t.length-1),n.exec(t)}}};function JS(t,n,r){const i=n.get(t);if(!i)return r;const l=Object.keys(i).map(u=>JS(u,n,r+1));return Math.max(...l)}var YT=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(t,n,r){let i=this._handlers[t];i?r&&r.intercept?i.unshift(n):i.push(n):i=this._handlers[t]=[n],r&&r.tag&&this._tag.set(n,r.tag)}intercept(t,n,r){this.on(t,n,{...r,intercept:!0})}detach(t){for(const n in this._handlers){const r=this._handlers[n];for(let i=r.length-1;i>=0;i--)this._tag.get(r[i])===t&&r.splice(i,1)}}async exec(t,n){const r=this._handlers[t];if(r)for(let i=0;i<r.length;i++){const l=r[i](n);if(l===!1||l&&l.then&&await l===!1)return}return this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};function XT(t){return n=>n[t]}function ZT(t){return(n,r)=>n[t]=r}function oc(t,n){return(n.getter||XT(n.id))(t)}function kg(t,n,r){return(n.setter||ZT(n.id))(t,r)}function JT(t,n){const r=document.createElement("a");r.href=URL.createObjectURL(t),r.download=n,document.body.appendChild(r),r.click(),document.body.removeChild(r)}function ac(t,n){let r=oc(t,n)??"";return n.template?r=n.template(r,t,n):n.optionsMap&&(Array.isArray(r)?r=r.map(i=>n.optionsMap.get(i)).join(", "):r=n.optionsMap.get(r)),typeof r>"u"?"":r+""}function eR(t,n){const r=/\n|"|;|,/;let i="";const l=n.rows||`
|
|
174
174
|
`,u=n.cols||" ",f=t._columns,h=t.flatData;n.header!==!1&&f[0].header&&(i=Ew("header",f,i,u,l));for(let g=0;g<h.length;g++){const y=[];for(let w=0;w<f.length;w++){let b=ac(h[g],f[w]);r.test(b)&&(b='"'+b.replace(/"/g,'""')+'"'),y.push(b)}i+=(i?l:"")+y.join(u)}return n.footer!==!1&&f[0].footer&&(i=Ew("footer",f,i,u,l)),i}function Ew(t,n,r,i,l){const u=/\n|"|;|,/;for(let f=0;f<n[0][t].length;f++){const h=[];for(let g=0;g<n.length;g++){let y=(n[g][t][f].text||"")+"";u.test(y)&&(y='"'+y.replace(/"/g,'""')+'"'),h.push(y)}r+=(r?l:"")+h.join(i)}return r}const tR="portrait",nR=100,aR="a4",rR={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function sR(t,n){const r=[];let i=[],l=0;const u=t.filter(h=>!h.hidden),f=iR(n);return u.forEach((h,g)=>{l+h.width<=f?(l+=h.width,i.push(h)):(i.length&&r.push(i),i=[h],l=h.width),g===u.length-1&&i.length&&r.push(i)}),r}function Dw(t,n,r){const i=[];return t.forEach((l,u)=>{const f=l[n];for(let h=0;h<r.length;h++){i[h]||(i[h]=[]);const g={...f[h]};if(i[h][u]!==null){if(!u&&!g.rowspan&&!g.colspan){let y=1,w=t[u+y][n][h],b=g.width;for(;!w.rowspan&&!w.colspan;)y++,w=t[u+y][n][h],b+=w.width;g.colspan=y,g.width=b,g.height=r[h]}if(i[h].push(g),!g.collapsed&&g.colspan>1){let y=g.colspan-1;if(g.colspan+u>t.length){const w=g.colspan-(g.colspan+u-t.length);g.colspan=w,g.width=t.slice(u,u+y+1).reduce((b,x)=>b+x.width,0),w>1&&(y=w-1)}for(let w=0;w<y;w++)i[h].push(null)}if(g.rowspan>1){const y=g.rowspan;for(let w=1;w<y;w++)i[h+w]||(i[h+w]=[]),i[h+w].push(null)}}}if(l.collapsed)for(let h=0;h<i.length;h++){const g=i[h],y=g[u];if(y&&y.collapsed){if(g[u]=null,!h)break}else{const w=y||g.findLast(b=>b?.colspan>=1);w&&(w.colspan=w.colspan-1,w.width=w.width-l.width)}}}),i.map(l=>l.filter(u=>u&&u.colspan!==0))}function iR(t){const{mode:n,ppi:r,paper:i}=t,{width:l,height:u}=rR[i];return oR(n==="portrait"?l:u,r)}function oR(t,n){return t*n}function lR(t={}){const{mode:n,ppi:r,paper:i}=t;return{mode:n||tR,ppi:r||nR,paper:i||aR}}function e0(t,n){return t.flexgrow?`min-width:${n}px;width:auto`:`width:${t.width}px; max-width:${t.width}px; height:${t.height}px`}function cR(t,n,r){let i=t[r.id];if(r.filter.type==="richselect"&&i){const l=r.filter.config?.options||n.find(({id:u})=>u==r.id).options;l&&(i=l.find(({id:u})=>u==i).label)}return i??""}const Iw=["resize-column","hide-column","update-cell"],uR=["delete-row","update-row","update-cell"],dR=["move-item"],fR=["resize-column","move-item"];class mR{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(n,r,i){this.in=n,this.getState=r,this.setState=i,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:n=>({action:"delete-row",data:{id:n.id},source:{action:"add-row",data:n}})},"delete-row":{handler:n=>{const{id:r}=n,{data:i}=this.getPrev(),l=i.findIndex(u=>u.id===r);return{action:"add-row",data:{id:r,row:i[l],before:l<i.length-1?i[l+1].id:void 0},source:{action:"delete-row",data:n}}}},"update-cell":{handler:n=>{const{id:r,column:i}=n,l=this.getRow(r),u=this.getColumn(i),f=oc(l,u);return oh(f,n.value)?null:{action:"update-cell",data:{id:r,column:i,value:f},source:{action:"update-cell",data:n}}}},"update-row":{handler:n=>{const{id:r,row:i}=n,l=this.getRow(r);for(const u in i)Object.keys(l).includes(u)||(l[u]=void 0);return{action:"update-row",data:{id:r,row:l},source:{action:"update-row",data:n}}}},"copy-row":{handler:n=>{const{id:r}=n,{data:i}=this.getState(),l=i.findIndex(f=>f.id===r),u=i[l];return{action:"delete-row",data:{id:r},source:{action:"add-row",data:{id:r,row:u,before:l<i.length-1?i[l+1].id:void 0}}}}},"resize-column":{handler:n=>{const{id:r,width:i}=n,l=this.getColumn(r),{_sizes:u}=this.getState();return{action:"resize-column",data:{id:r,width:l.width??u.columnWidth},source:{action:"resize-column",data:{id:r,width:i}}}}},"hide-column":{handler:n=>{const{id:r}=n,i=this.getColumn(r);return{action:"hide-column",data:{id:r,mode:i.hidden},source:{action:"hide-column",data:n}}}},"collapse-column":{handler:n=>{const{id:r,row:i,mode:l}=n;return{action:"collapse-column",data:{id:r,row:i,mode:typeof l=="boolean"?!l:l},source:{action:"collapse-column",data:n}}}},"move-item":{handler:n=>{const{id:r,target:i,mode:l}=n,{flatData:u}=this.getPrev(),f=u.findIndex(h=>h.id===r);return{action:"move-item",data:{id:r,target:u[f+(f?-1:1)].id,mode:f?"after":"before"},source:{action:"move-item",data:{id:r,target:i,mode:l}}}}},"open-row":{handler:n=>{const{id:r,nested:i}=n;return{action:"close-row",data:{id:r,nested:i},source:{action:"open-row",data:n}}}},"close-row":{handler:n=>{const{id:r,nested:i}=n;return{action:"open-row",data:{id:r,nested:i},source:{action:"close-row",data:n}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const n=this.getHandlers();for(const r in n)this.in.intercept(r,i=>{if(!(i.eventSource==="undo"||i.eventSource==="redo"||i.skipUndo)){if(fR.includes(r)){(i.inProgress&&!this.progress[r]||typeof i.inProgress!="boolean")&&(dR.includes(r)&&this.setPrev("flatData"),Iw.includes(r)&&this.setPrev("columns")),this.progress[r]=i.inProgress;return}uR.includes(r)&&this.setPrev("data"),Iw.includes(r)&&this.setPrev("columns")}}),this.in.on(r,i=>{if(i.eventSource==="undo"||i.eventSource==="redo"||i.skipUndo||i.inProgress)return;const l=n[r].handler(i);l&&this.addToHistory(l)})}setPrev(n){this._previousValues[n]=hv(this.getState()[n])}addToHistory(n){this.undo.push(n),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const n=this.undo.pop();this.redo.push({...n.source,source:n}),this.in.exec(n.action,{...n.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const n=this.redo.pop();this.undo.push({...n.source,source:n}),this.in.exec(n.action,{...n.data,eventSource:"redo"}),this.setStateHistory()}resetStateHistory(){this.setState({history:{undo:0,redo:0}})}setStateHistory(){this.setState({history:{undo:this.undo.length,redo:this.redo.length}})}getRow(n){const{data:r}=this.getPrev();return this.getState().tree?this.getTreeRow(r,n):r.find(i=>i.id===n)}getTreeRow(n,r){for(let i=0;i<n.length;i++){if(n[i].id===r)return n[i];if(n[i].data){const l=this.getTreeRow(n[i].data,r);if(l)return l}}return null}getColumn(n){const{columns:r}=this.getPrev();return r.find(i=>i.id===n)}}function t0(t,n){return typeof t>"u"||t===null?-1:typeof n>"u"||n===null?1:t===n?0:t>n?1:-1}function pR(t,n){return-t0(t,n)}function hR(t,n){if(typeof n.sort=="function")return function(i,l){const u=n.sort(i,l);return t==="asc"?u:-u};const r=t==="asc"?t0:pR;return function(i,l){return r(oc(i,n),oc(l,n))}}function gR(t,n){if(!t||!t.length)return;const r=t.map(i=>{const l=n.find(u=>u.id==i.key);return hR(i.order,l)});return t.length===1?r[0]:function(i,l){for(let u=0;u<r.length;u++){const f=r[u](i,l);if(f!==0)return f}return 0}}const vp=28,vR=20;function yR(){if(typeof document>"u")return"willow";const t=document.querySelector('[class^="wx"][class$="theme"]');return t?t.className.substring(3,t.className.length-6):"willow"}function Wp(t,n,r,i,l){const u=document.createElement("div"),f=document.createElement("div"),h=document.body;l=l?`${l}px`:"auto";let g,y;f.className=n,u.classList.add(`wx-${r}-theme`),u.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${l};white-space:nowrap;`,u.appendChild(f),h.appendChild(u),typeof t!="object"&&(t=[t]);for(let w=0;w<t.length;w++){f.innerText=t[w]+"";const b=u.getBoundingClientRect(),x=Math.ceil(b.width)+(i&&i.length?i[w]:0),M=Math.ceil(b.height);g=Math.max(g||0,x),y=Math.max(y||0,M)}return u.remove(),{width:g,height:y}}function Lw(t,n,r,i,l){const u=[];for(let f=0;f<t.length;f++){const h=t[f][n],g=h.length;for(let y=0;y<g;y++){const{text:w,vertical:b,collapsed:x,rowspan:M,css:k}=h[y];if(!w){u[y]=Math.max(u[y]||0,i);continue}let N=0;if(b&&!x){let E=`wx-measure-cell-${n}`;if(E+=k?` ${k}`:"",N=Wp(w,E,l).width,(M>1||!h[y+1])&&r>y+1){const I=M||r-y,T=u.slice(y,y+I).reduce((P,U)=>P+U,0);if(T<N){const P=Math.ceil((N-T)/I);for(let U=y;U<y+I;U++)u[U]=(u[U]||i)+P}continue}}u[y]=Math.max(u[y]||i,N)}}return u}function bR(t,n,r){const i=[],l=[];let u="wx-measure-cell-body";u+=t.css?` ${t.css}`:"";for(let f=0;f<n.length;f++){const h=n[f],g=ac(h,t);g&&(i.push(g),t.treetoggle?l.push(n[f].$level*vp+(n[f].$count?vp:0)+(t.draggable?vp:0)):t.draggable&&l.push(vp))}return Wp(i,u,r,l).width}function wR(t,n){const r="wx-measure-cell-header",i=t.sort?vR:0;let l=t.header;if(typeof l=="string")return Wp(l,r,n).width+i;let u;Array.isArray(l)||(l=[l]);for(let f=0;f<l.length;f++){const h=l[f],g=typeof h=="string"?h:h.text,y=r+(typeof h=="string"?"":` ${h.css}`);let w=Wp(g,y,n).width;f===l.length-1&&(w+=i),u=Math.max(u||0,w)}return u}const xR={text:(t,n)=>t?t.toString().toLowerCase().indexOf(n.toLowerCase())!==-1:!n,richselect:(t,n)=>typeof n!="number"&&!n?!0:t==n,datepicker:(t,n)=>n?t&&CR(t,n):!0,multiselect:(t,n)=>!n||n?.length===0?!0:Array.isArray(t)?t?.some(r=>n.includes(r)):t&&n.includes(t)};function n0(t){return xR[t]}function SR(t,n){const r=[];for(const i in t){const l=n.find(g=>g.id==i),{config:u,type:f}=l.header.find(g=>g.filter).filter,h=t[i];r.push(g=>{const y=oc(g,l);return u?.handler?u.handler(y,h):n0(f)(y,h)})}return i=>{for(let l=0;l<r.length;l++)if(!r[l](i))return!1;return!0}}function CR(t,n){return t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate()}let kR=class extends KT{in;_router;_branches;_xlsxWorker;_historyManager;constructor(n){super({writable:n,async:!1});const r={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new QT(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:l=>{const{columns:u,sizes:f,_skin:h}=this.getState(),g=this.copyColumns(u),y=g.reduce((x,M)=>Math.max(M.header.length,x),0),w=g.reduce((x,M)=>Math.max(M.footer.length,x),0);g.forEach(this.setCollapsibleColumns);const b=this.normalizeSizes(g,f,y,w,h);for(let x=0;x<g.length;x++)this.normalizeColumns(g,x,"header",y,b),this.normalizeColumns(g,x,"footer",w,b);this.setState({_columns:g,_sizes:b},l)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:l=>{const{data:u,tree:f,dynamic:h,_filterIds:g}=this.getState(),y=g&&new Set(g),w=f?this.flattenRows(u,[],g):y?u.filter(x=>y.has(x.id)):u,b=!h&&w.some(x=>x.rowHeight);this.setState({flatData:w,_rowHeightFromData:b},l)}}],{sizes:l=>({...r,...l})});const i=this.in=new YT;i.on("close-editor",({ignore:l})=>{const{editor:u}=this.getState();u&&(l||i.exec("update-cell",u),this.setState({editor:null}))}),i.on("open-editor",({id:l,column:u})=>{let f=this.getState().editor;f&&i.exec("close-editor",{});const h=this.getRow(l),g=u?this.getColumn(u):this.getNextEditor(h);if(g?.editor){let y=g.editor;if(typeof y=="function"&&(y=y(h,g)),!y)return;f={column:g.id,id:l,value:oc(h,g)??"",renderedValue:ac(h,g),type:y.type||y},typeof y=="object"&&y.config&&(f.config=y.config,y.config.options&&(f.options=y.config.options)),g.options&&!f.options&&(f.options=g.options),this.setState({editor:f})}}),i.on("editor",({value:l})=>{let u=this.getState().editor;if(u){u={...u},u.value=l;const f=this.getColumn(u.column),h={...this.getRow(u.id)};kg(h,f,l),u.renderedValue=ac(h,f),this.setState({editor:u})}}),i.on("add-row",l=>{const u=this.getState();let{data:f}=u;const{select:h,_filterIds:g}=u,{row:y,before:w,after:b,select:x}=l;if(l.id=y.id=l.id||y.id||yp(),w||b){const k=w||b,N=f.findIndex(E=>E.id===k);f=[...f],f.splice(N+(b?1:0),0,l.row)}else f=[...f,l.row];const M={data:f};g&&(M._filterIds=[...g,l.id]),this.setState(M),!(typeof x=="boolean"&&!x)&&(x||h)&&i.exec("select-row",{id:y.id,show:!0})}),i.on("delete-row",l=>{const{data:u,selectedRows:f,focusCell:h,editor:g}=this.getState(),{id:y}=l,w={data:u.filter(b=>b.id!==y)};this.isSelected(y)&&(w.selectedRows=f.filter(b=>b!==y)),g?.id===y&&(w.editor=null),this.setState(w),h?.row===y&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),i.on("update-cell",l=>{const u=this.getState();let{data:f}=u;f=[...f];const{tree:h}=u,{id:g,column:y,value:w}=l,b=this.getColumn(y);if(h){const x={...this._branches[g]};kg(x,b,w);const M=this.updateTreeRow(x);x.$parent===0&&(f=M)}else{const x=f.findIndex(k=>k.id===g),M={...f[x]};kg(M,b,w),f[x]=M}this.setState({data:f})}),i.on("update-row",l=>{let{data:u}=this.getState();const{id:f,row:h}=l,g=u.findIndex(y=>y.id===f);u=[...u],u[g]={...u[g],...h},this.setState({data:u})}),i.on("select-row",({id:l,toggle:u,range:f,mode:h,show:g,column:y})=>{const w=this.getState(),{focusCell:b}=w;let{selectedRows:x}=w;if(x.length||(f=u=!1),f){const{data:M}=this.getState();let k=M.findIndex(E=>E.id===x[x.length-1]),N=M.findIndex(E=>E.id===l);k>N&&([k,N]=[N,k]),M.slice(k,N+1).forEach(E=>{this.isSelected(E.id)||x.push(E.id)})}else if(u&&this.isSelected(l)){if(h===!0)return;x=x.filter(M=>M!==l)}else if(u){if(h===!1)return;x.push(l)}else x=[l];this.setState({selectedRows:[...x]}),b?.row!==l&&this.in.exec("focus-cell",{eventSource:"select-row"}),g&&this.in.exec("scroll",{row:l,column:y})}),this.in.on("focus-cell",l=>{const{row:u,column:f,eventSource:h}=l,{_columns:g,split:y}=this.getState();u&&f?(this.setState({focusCell:{row:u,column:f}}),h!=="click"&&((!y.left||g.findIndex(w=>w.id===l.column)>=y.left)&&(!y.right||g.findIndex(w=>w.id===l.column)<g.length-y.right)?this.in.exec("scroll",{row:u,column:f}):this.in.exec("scroll",{row:u}))):this.setState({focusCell:null})}),i.on("resize-column",l=>{const{id:u,auto:f,maxRows:h,inProgress:g}=l;if(g===!1)return;let y=l.width||0;const w=[...this.getState().columns],b=this.getColumn(u);if(f){if(f==="data"||f===!0){const{flatData:x,_skin:M}=this.getState();let k=x.length;h&&(k=Math.min(h,k));const N=x.slice(0,k);y=bR(b,N,M)}if(f==="header"||f===!0){const{_skin:x}=this.getState();y=Math.max(wR(b,x),y)}}b.width=Math.max(17,y),delete b.flexgrow,this.setState({columns:w})}),i.on("hide-column",l=>{const{id:u,mode:f}=l,h=[...this.getState().columns],g=this.getColumn(u),y=h.reduce((w,b)=>w+(b.hidden?0:1),0);!f||y>1?(g.hidden=!g.hidden,this.setState({columns:h})):l.skipUndo=!0}),i.on("sort-rows",l=>{const{key:u,add:f,sort:h}=l,g=this.getState(),{columns:y,data:w,tree:b}=g;if(h){const T=[...w];T.sort(h),this.setState({data:T});return}const{order:x="asc"}=l;let M=g.sortMarks;const k=Object.keys(M),N=k.length;!f||!N||N===1&&M[u]?M={[u]:{order:x}}:(N===1&&(M[k[0]]={...M[k[0]],index:0}),M={...M,[u]:{order:x,index:typeof f=="number"?f:M[u]?.index??N}});const E=Object.keys(M).sort((T,P)=>M[T].index-M[P].index).map(T=>({key:T,order:M[T].order}));this.setState({sortMarks:M});const I=gR(E,y);if(I){const T=[...w];b?this.sortTree(T,I):T.sort(I),this.setState({data:T})}}),i.on("filter-rows",l=>{const{value:u,key:f,filter:h}=l;if(!Object.keys(l).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:y,tree:w,_columns:b}=g;let x=g.filterValues;const M={};f&&(x={...x,[f]:u},M.filterValues=x);const k=h??SR(x,b);let N=[];w?N=this.filterTree(y,k,N):y.forEach(E=>{k(E)&&N.push(E.id)}),M._filterIds=N,this.setState(M)}),i.on("collapse-column",l=>{const{id:u,row:f,mode:h}=l,g=[...this.getState().columns],y=this.getColumn(u).header,w=Array.isArray(y)?y[f]:y;typeof w=="object"&&(w.collapsed=h??!w.collapsed,this.setState({columns:g}))}),i.on("move-item",l=>{const{id:u,inProgress:f}=l;let{target:h,mode:g="after"}=l;const{data:y,flatData:w,tree:b}=this.getState(),x=w.findIndex(N=>N.id===u);let M;if(g==="up"||g==="down"){if(g==="up"){if(x===0)return;M=x-1,g="before"}else if(g==="down"){if(x===w.length-1)return;M=x+1,g="after"}h=w[M]&&w[M].id}else M=w.findIndex(N=>N.id===h);if(x===-1||M===-1||f===!1)return;let k;b||(k=this.moveItem(u,h,y,g)),this.setState({data:b?this.normalizeTreeRows(k):k})}),i.on("copy-row",l=>{const{id:u,target:f,mode:h="after"}=l,g=this.getState(),{flatData:y,_filterIds:w}=g;let{data:b}=g;const x=this.getRow(u);if(!x)return;const M={...x,id:yp()};l.id=M.id;const k=y.findIndex(E=>E.id===f);if(k===-1)return;b.splice(k+(h==="after"?1:0),0,M),b=[...b];const N={data:b};w&&(N._filterIds=[...w,M.id]),this.setState(N)}),i.on("open-row",l=>{const{id:u,nested:f}=l;this.toggleBranch(u,!0,f)}),i.on("close-row",l=>{const{id:u,nested:f}=l;this.toggleBranch(u,!1,f)}),i.on("export-data",l=>new Promise((u,f)=>{const h=l.format||"csv",g=`${l.fileName||"data"}.${h}`;if(h==="csv"){const y=eR(this.getState(),l.csv||{});l.download!==!1?JT(new Blob(["\uFEFF"+y],{type:"text/csv"}),g):l.result=y,u(!0)}else f()})),i.on("hotkey",({key:l,event:u,isInput:f})=>{switch(l){case"arrowup":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),f)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getPrevRow(g.row)?.id:h[h.length-1]?.id;w&&b&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowdown":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),f)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getNextRow(g.row)?.id:h[0]?.id;w&&b&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowright":{const{focusCell:h}=this.getState();if(f)return;if(u.preventDefault(),h){const g=this.getNextColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"arrowleft":{const{focusCell:h}=this.getState();if(f)return;if(u.preventDefault(),h){const g=this.getPrevColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const w=h.column;let b=h.id,x=this.getNextEditor(this.getRow(b),this.getColumn(w));if(!x){const M=this.getNextRow(b);M&&(b=M.id,x=this.getNextEditor(M))}x&&(this.in.exec("open-editor",{id:b,column:x.id}),this.in.exec("focus-cell",{row:b,column:x.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const w=h.column;let b=h.id,x=this.getPrevEditor(this.getRow(b),this.getColumn(w));if(!x){const M=this.getPrevRow(b);M&&(b=M.id,x=this.getPrevEditor(M))}x&&(this.in.exec("open-editor",{id:b,column:x.id}),this.in.exec("focus-cell",{row:b,column:x.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:h}=this.getState();h&&(this.in.exec("close-editor",{ignore:h.type!="multiselect"}),this.in.exec("focus-cell",{row:h.id,column:h.column,eventSource:"key"}));break}case"f2":{const{editor:h,focusCell:g}=this.getState();!h&&g&&this.in.exec("open-editor",{id:g.row,column:g.column});break}case"enter":{const{focusCell:h,tree:g}=this.getState();if(!f&&g&&h&&this.getColumn(h.column).treetoggle){const y=this.getRow(h.row);if(!y.data)return;this.in.exec(y.open?"close-row":"open-row",{id:h.row,nested:!0})}break}case"home":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:g.row,column:y,eventSource:"key"})}break}case"ctrl+home":{const{editor:h,focusCell:g,flatData:y,select:w}=this.getState();if(!h&&g){u.preventDefault();const b=y[0]?.id,x=this._getFirstVisibleColumn()?.id;b&&x&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),w&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"end":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getLastVisibleColumn()?.id,w=g.row;this.in.exec("focus-cell",{row:w,column:y,eventSource:"key"})}break}case"ctrl+end":{const{editor:h,focusCell:g,flatData:y,select:w}=this.getState();if(!h&&g){u.preventDefault();const b=y.at(-1).id,x=this._getLastVisibleColumn()?.id;b&&x&&(this.in.exec("focus-cell",{row:b,column:x,eventSource:"key"}),w&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),i.on("scroll",l=>{const{_columns:u,split:f,_sizes:h,flatData:g,dynamic:y,_rowHeightFromData:w}=this.getState();let b=-1,x=-1,M=0,k=0;if(l.column){b=0;const N=u.findIndex(E=>E.id===l.column);M=u[N].width;for(let E=f.left??0;E<N;E++){const I=u[E];I.hidden||(b+=I.width)}}if(l.row&&!y){const N=g.findIndex(E=>E.id===l.row);N>=0&&(w?(x=g.slice(0,N).reduce((E,I)=>E+(I.rowHeight||h.rowHeight),0),k=g[N].rowHeight):x=h.rowHeight*N)}this.setState({scroll:{top:x,left:b,width:M,height:k||h.rowHeight}})}),i.on("scroll-to",l=>{const u={};l.top!==void 0&&(u.scrollTop=l.top),l.left!==void 0&&(u.scrollLeft=l.left),Object.keys(u).length&&this.setState(u)}),i.on("print",l=>{const u=lR(l);this.setState({_print:u}),this.setStateAsync({_print:null})}),i.on("undo",()=>{this._historyManager?.handleUndo()}),i.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(n){if(!this._xlsxWorker){const r=window.URL.createObjectURL(new Blob([`importScripts('${n}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(i=>{const l=new Worker(r);l.addEventListener("message",u=>{u.data.type==="init"&&i(l)})})}return this._xlsxWorker}initOnce(){const n={sortMarks:{},_filterIds:null,data:[],filterValues:{},scroll:null,scrollLeft:0,scrollTop:0,editor:null,focusCell:null,_print:null,history:{undo:0,redo:0},search:null};this._router.init(n)}init(n){n.hasOwnProperty("_skin")&&!n._skin&&(n._skin=yR()),n.columns&&n.columns.forEach(r=>{r.options&&(r.optionsMap=new Map(r.options.map(i=>[i.id,i.label])))}),oh(this.getState().data,n.data)||(n.tree?n.data=this.normalizeTreeRows(n.data):n.data=this.normalizeRows(n.data),this.setState({_filterIds:null,filterValues:{},sortMarks:{},search:null}),this._historyManager&&this._historyManager.resetHistory()),n.tree&&(n.undo=!1,n.reorder=!1),n.split?.right&&(n.split.right=0),n.undo&&!this._historyManager&&(this._historyManager=new mR(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...n})}setState(n,r){return this._router.setState(n,r)}setStateAsync(n){this._router.setStateAsync(n)}getRow(n){const{tree:r}=this.getState();return r?this._branches[n]:this.getState().data.find(i=>i.id===n)}getRowIndex(n,r){return r||(r=this.getState().flatData),r.findIndex(i=>i.id===n)}getNextRow(n){const r=this.getState().flatData,i=this.getRowIndex(n,r);return r[i+1]}getPrevRow(n){const r=this.getState().flatData,i=this.getRowIndex(n,r);return r[i-1]}getColumn(n){return this.getState().columns.find(r=>r.id===n)}getNextColumn(n,r){const i=this.getState()._columns,l=i.findIndex(u=>u.id===n);return r?this._getFirstVisibleColumn(l+1):i[l+1]}getPrevColumn(n,r){const i=this.getState()._columns,l=i.findIndex(u=>u.id===n);return r?this._getLastVisibleColumn(l-1):i[l-1]}_getFirstVisibleColumn(n){const r=this.getState()._columns;let i=n??0;for(;i<r.length&&(r[i]?.hidden||r[i]?.collapsed);)i++;return r[i]}_getLastVisibleColumn(n){const r=this.getState()._columns;let i=n??r.length-1;for(;i<r.length&&(r[i]?.hidden||r[i]?.collapsed);)i--;return r[i]}isCellEditable(n,r){const{editor:i,hidden:l}=r;return!i||l?!1:typeof i=="function"?i(n,r):!0}getNextEditor(n,r){let i=this.getState().columns;if(r){const l=i.findIndex(u=>u.id===r.id);i=i.slice(l+1)}return i.find(l=>this.isCellEditable(n,l))}getPrevEditor(n,r){let i=this.getState().columns;if(r){const l=i.findLastIndex(u=>u.id===r.id);i=i.slice(0,l)}return i.findLast(l=>this.isCellEditable(n,l))}toggleBranch(n,r,i){let l=this._branches[n],{data:u}=this.getState();if(u=[...u],n!==0){l={...l,open:r};const f=this.updateTreeRow(l);l.$parent===0&&(u=f)}i&&l.data?.length&&l.data.forEach(f=>{const h=this.toggleKids(f,r,i);n===0&&(u=h)}),this.setState({data:u})}toggleKids(n,r,i){n={...n,open:r};const l=this.updateTreeRow(n);return i&&n.data?.length&&n.data.forEach(u=>{this.toggleKids(u,r,i)}),l}updateTreeRow(n){const r=n.id;this._branches[r]=n;const i=this._branches[n.$parent],l=i.data.findIndex(u=>u.id===r);return i.data=[...i.data],i.data[l]=n,i.data}isSelected(n){return this.getState().selectedRows.indexOf(n)!==-1}findAndRemove(n,r){for(let i=0;i<n.length;i++){if(n[i].id===r)return n.splice(i,1)[0];if(n[i].data){const l=[...n[i].data],u=this.findAndRemove(l,r);if(u)return n[i]={...n[i],data:l},u}}return null}insertItem(n,r,i,l){for(let u=0;u<n.length;u++){if(n[u].id===r){const f=n[u],h=l==="before"?u:u+1;if(f.data){if(l==="before"){const g=u>0?n[u-1]:null;return g?.data&&g.open?n[u-1]={...g,data:[...g.data,i]}:n.splice(h,0,i),!0}else if(f.open)return n[u]={...f,data:[i,...f.data]},!0}return n.splice(h,0,i),!0}if(n[u].data&&(n[u]={...n[u],data:[...n[u].data]},this.insertItem(n[u].data,r,i,l)))return!0}return!1}moveItem(n,r,i,l){const u=[...i],f=this.findAndRemove(u,n);return this.insertItem(u,r,f,l),u}copyColumns(n){const r=[];for(let i=0;i<n.length;i++){const l={...n[i]};this.copyHeaderFooter(l,"header"),this.copyHeaderFooter(l,"footer"),r[i]=l}return r}copyHeaderFooter(n,r){let i=n[r];i=Array.isArray(i)?[...i]:[i],i.forEach((l,u)=>{i[u]=typeof l=="string"?{text:l}:{...l}}),n[r]=i}setCollapsibleColumns(n,r,i){let l=n.header;for(let u=0;u<l.length;u++){const f=l[u];if(f.collapsible&&f.collapsed){if(f.collapsible!=="first"){n.collapsed=!0,n.width=36,f.vertical=!0;const g=l.length-u;l=l.slice(0,u+1),l[u].rowspan=g}const h=f.colspan;if(h){const g=l[u+1];let y=1;g&&g.colspan&&!g.collapsed&&(y=g.colspan);for(let w=y;w<h;w++){const b=i[r+w];b&&(b.hidden=!0)}}}}}normalizeColumns(n,r,i,l,u){const f=n[r];f.width||(f.width=f.flexgrow?17:u.columnWidth),f._colindex=r+1;const h=f[i],g=u[`${i}RowHeights`];for(let y=0;y<l;y++){const w=h[y];w.id=f.id,y===h.length-1&&(w.rowspan=w.rowspan?Math.min(w.rowspan,l-y):l-y);for(let b=1;b<w.rowspan;b++){h.splice(y+b,0,{_hidden:!0});for(let x=1;x<w.colspan;x++)n[r+x][i].splice(y+b,0,{})}if(w.rowspan){const b=(w.rowspan===l?g:g.slice(y,w.rowspan+y)).reduce((x,M)=>x+M,0);w.height=b,y+w.rowspan!=l&&w.height--}if(w.colspan){let b=f.width,x=f.flexgrow||0;const M=w.colspan;for(let k=1;k<M;k++){const N=n[r+k];N&&(N.hidden?w.colspan-=1:N.flexgrow?x+=N.flexgrow:b+=N.width||u.columnWidth),x?w.flexgrow=x:w.width=b}}else w.width=f.width,w.flexgrow=f.flexgrow;i==="header"&&w.filter&&typeof w.filter=="string"&&(w.filter={type:w.filter})}h.length>l&&(h.length=l),f[i]=h}normalizeRows(n){for(let r=0;r<n.length;r++)n[r].id||(n[r].id=yp());return n}normalizeTreeRows(n,r,i){return!r&&!i&&(this._branches={0:{data:n}}),n.forEach(l=>{l.id||(l.id=yp()),l.$level=r||0,l.$parent=i||0,this._branches[l.id]=l,l.data&&(l.data.length?(l.$count=l.data.length,this.normalizeTreeRows(l.data,l.$level+1,l.id)):(delete l.data,delete l.$count,delete l.open))}),n}sortTree(n,r){n.sort(r),n.forEach(i=>{i.data&&this.sortTree(i.data,r)})}filterTree(n,r,i){return n.forEach(l=>{r(l)&&i.push(l.id),l.data&&this.filterTree(l.data,r,i)}),i}flattenRows(n,r,i){const l=r;return n.forEach(u=>{(!i||i.includes(u.id))&&l.push(u),u.data?.length&&u.open!==!1&&this.flattenRows(u.data,l,i)}),l}createFilter(n){const{_columns:r}=this.getState(),i=[];for(const l in n){const u=r.find(y=>y.id==l),{config:f,type:h}=u.header.find(y=>y.filter).filter,g=n[l];i.push(y=>{const w=oc(y,u);return f?.handler?f.handler(w,g):n0(h)(w,g)})}return l=>{for(let u=0;u<i.length;u++)if(!i[u](l))return!1;return!0}}searchRows(n,r){n=n.trim().toLowerCase();const i={};if(!n)return i;const{flatData:l,columns:u}=this.getState(),f=r?u.filter(h=>r[h.id]):u;return l.forEach(h=>{const g={};f.forEach(y=>{const w=ac(h,y);String(w).toLowerCase().includes(n)&&(g[y.id]=!0)}),Object.keys(g).length&&(i[h.id]=g)}),i}normalizeSizes(n,r,i,l,u){const f=Lw(n,"header",i,r.headerHeight,u),h=Lw(n,"footer",l,r.footerHeight,u),g=f.reduce((w,b)=>w+b,0),y=h.reduce((w,b)=>w+b,0);return{...r,headerRowHeights:f,footerRowHeights:h,headerHeight:g,footerHeight:y}}},MR=new Date().valueOf();function yp(){return"temp://"+MR++}function AR(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}new Date().valueOf();var NR=class{constructor(){this.store=new Map}configure(t,n){this.node=n;for(const r in t)if(t[r]){const i=r.toLowerCase().replace(/[ ]/g,""),l=t[r];this.store.set(i,l)}}},vd=[],TR={subscribe:t=>{RR();const n=new NR;return vd.push(n),t(n),()=>{const r=vd.findIndex(i=>i===n);r>=0&&vd.splice(r,1)}}},_w=!1;function RR(){_w||(_w=!0,document.addEventListener("keydown",t=>{if(vd.length&&(t.ctrlKey||t.altKey||t.metaKey||t.shiftKey||t.key.length>1||t.key===" ")){const n=[];t.ctrlKey&&n.push("ctrl"),t.altKey&&n.push("alt"),t.metaKey&&n.push("meta"),t.shiftKey&&n.push("shift");let r=t.code.replace("Key","").toLocaleLowerCase();t.key===" "&&(r="space"),n.push(r);const i=n.join("+");for(let l=vd.length-1;l>=0;l--){const u=vd[l],f=u.store.get(i)||u.store.get(r);f&&u.node.contains(t.target)&&f(t,{key:i,evKey:r})}}}))}const jR={tab:!0,"shift+tab":!0,arrowup:!0,arrowdown:!0,arrowright:!0,arrowleft:!0,enter:!0,escape:!0,f2:!0,home:!0,end:!0,"ctrl+home":!0,"ctrl+end":!0,"ctrl+z":!0,"ctrl+y":!0};function ER(t,{keys:n,exec:r}){if(!n)return;function i(f){const h=f.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||AR(h,"data-header-id")?.classList.contains("wx-filter")||!!h.closest(".wx-cell.wx-editor")}const l={};for(const f in n){const h=n[f];typeof h<"u"&&(typeof h=="function"?l[f]=h:h&&(l[f]=g=>{const y=i(g);r({key:f,event:g,isInput:y})}))}const u=TR.subscribe(f=>{f.configure(l,t)});return{destroy:()=>{u()}}}function DR(t,n){let r=null;n.scroll.subscribe(i=>{if(!i||i===r)return;r=i;const{left:l,top:u,height:f,width:h}=i,g=n.getHeight(),y=n.getWidth(),w=n.getScrollMargin();if(u>=0){const b=t.scrollTop;u<b?t.scrollTop=u:u+f>b+g&&(t.scrollTop=u-g+f)}if(l>=0){const b=t.scrollLeft;l<b?t.scrollLeft=l:l+h>b+y-w&&(t.scrollLeft=l-y+h+w)}}),n.scrollLeft?.subscribe?.(i=>{requestAnimationFrame(()=>{Math.abs(t.scrollLeft-i)>1&&(t.scrollLeft=i)})}),n.scrollTop?.subscribe?.(i=>{requestAnimationFrame(()=>{Math.abs(t.scrollTop-i)>1&&(t.scrollTop=i)})})}const ks=d.createContext(null);function IR(t,n){const r=new ResizeObserver(i=>{requestAnimationFrame(()=>n(i[0].contentRect))});return r.observe(t.parentNode),{destroy(){r.disconnect()}}}const Pw=5,LR=700;function Ip(t){const n=t.getBoundingClientRect(),r=document.body,i=n.top+r.scrollTop-r.clientTop||0,l=n.left+r.scrollLeft-r.clientLeft||0;return{y:Math.round(i),x:Math.round(l),width:t.offsetWidth,height:t.offsetHeight}}function gv(t,n){const r=Ip(n);return{x:t.clientX-r.x,y:t.clientY-r.y}}function _R(t,n){const r=n.current;let i=null,l,u,f=!1,h=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function y(){clearTimeout(l),l=null}function w(D){const K=Sd(D);K&&(i={container:g,sourceNode:D.target,from:rh(K),pos:gv(D,t)},u=i.pos,b(D))}function b(D){if(!i)return;const K=i.pos=gv(D,t);if(!f){if(!h&&!D?.target?.getAttribute("draggable-data")&&Math.abs(u.x-K.x)<Pw&&Math.abs(u.y-K.y)<Pw)return;if(F(D)===!1)return Y()}if(h){const ne=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,q=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;i.targetNode=document.elementFromPoint(D.pageX-ne,D.pageY-q)}else i.targetNode=D.target;r.move&&r.move(D,i),g.style.left=-(i.offset?i.offset.x:0)+"px",g.style.top=i.pos.y+(i.offset?i.offset.y:0)+"px"}function x(D){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",f&&r.end&&r.end(D,i),i=u=null,Y()}function M(D){r.getReorder&&!r.getReorder()||D.button===0&&(U(D),window.addEventListener("mousemove",k),window.addEventListener("mouseup",N),w(D))}function k(D){b(D)}function N(D){x(D)}function E(D){if(r.getReorder&&!r.getReorder())return;l=setTimeout(()=>{h=!0,w(D.touches[0])},LR),U(D);function K(){l&&y(),D.target.removeEventListener("touchmove",I),D.target.removeEventListener("touchend",K),x(D)}D.target.addEventListener("touchmove",I),D.target.addEventListener("touchend",K),t.addEventListener("contextmenu",T)}function I(D){f?(D.preventDefault(),b(D.touches[0])):l&&y()}function T(D){if(f||l)return D.preventDefault(),!1}function P(D){D.preventDefault()}function U(D){if(!r.getDraggableInfo)return;const{hasDraggable:K}=r.getDraggableInfo();(!K||D.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function F(D){if(f=!0,r.start){if(r.start(D,i)===!1)return!1;t.appendChild(g),document.body.style.cursor="move"}}function Y(D){f=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",k),window.removeEventListener("mouseup",N),D&&(t.removeEventListener("mousedown",M),t.removeEventListener("touchstart",E),t.removeEventListener("dragstart",P))}return t.addEventListener("mousedown",M),t.addEventListener("touchstart",E),t.addEventListener("dragstart",P),{destroy(){Y(!0)}}}const PR=.004;function FR(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function OR(t,n,r,i){const{node:l,left:u,top:f,bottom:h,sense:g,xScroll:y,yScroll:w}=i,b=gv(t,l);r.scrollState||(r.scrollState=FR());let x=0,M=0;b.x<u+g?x=-1:b.x>n.width-g&&(x=1),b.y<f+Math.round(g/2)?M=-1:b.y>n.height-h-Math.round(g/2)&&(M=1),(r.scrollState.dirX!==x||r.scrollState.dirY!==M)&&(a0(r),r.scrollState.dirX=x,r.scrollState.dirY=M),(y&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&HR(r,i,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function HR(t,n,r){t.autoScrollTimer||(t.autoScrollTimer=setTimeout(()=>{t.activeAutoScroll=setInterval(BR,15,t,n,r)},250))}function a0(t){t.scrollSpeedFactor=1,t.autoScrollTimer&&(t.autoScrollTimer=clearTimeout(t.autoScrollTimer),t.activeAutoScroll=clearInterval(t.activeAutoScroll))}function BR(t,n,r){const{x:i,y:l}=r;t.scrollSpeedFactor+=PR,i!==0&&$R(t,n,i),l!==0&&zR(t,n,l)}function zR(t,n,r){const i=n.node.scrollTop;r0(i+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollTop",n)}function $R(t,n,r){const i=n.node.scrollLeft;r0(i+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollLeft",n)}function r0(t,n,r){r.node[n]=t}function lh(t,n,r,i,l,u){const f={};return t&&(f.width=`${t}px`,f.minWidth=`${t}px`),n&&(f.flexGrow=n),u&&(f.height=`${u}px`),r&&(f.position="sticky",r.left&&(f.left=`${i}px`),r.right&&(f.right=`${l}px`)),f}function s0(t,n,r){let i="";if(t.fixed)for(const l in t.fixed){let u=t.fixed[l]===-1;!u&&t.fixed.leftSize&&n.colspan&&(u=n.colspan+t._colindex-1===t.fixed.leftSize),i+=u?"wx-shadow ":"wx-fixed "}return i+=n.rowspan>1?"wx-rowspan ":"",i+=n.colspan>1?"wx-colspan ":"",i+=n.vertical?"wx-vertical ":"",i+=r?r(t)+" ":"",i}function UR(t){const{row:n,column:r,cellStyle:i=null,columnStyle:l=null,children:u,focusable:f}=t,h=d.useContext(ks),g=Lt(h,"focusCell"),y=Lt(h,"search"),w=Lt(h,"reorder"),b=d.useMemo(()=>y?.rows[n.id]&&y.rows[n.id][r.id],[y,n.id,r.id]),x=d.useMemo(()=>lh(r.width,r.flexgrow,r.fixed,r.left,r.right),[r.width,r.flexgrow,r.fixed,r.left,r.right]);function M(F,Y){let D="wx-cell";return D+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",D+=F?" "+F(r):"",D+=Y?" "+Y(n,r):"",D+=r.treetoggle?" wx-tree-cell":"",D}const k=d.useMemo(()=>M(l,i),[l,i,r,n]),N=d.useMemo(()=>typeof r.draggable=="function"?r.draggable(n,r)!==!1:r.draggable,[r,n]),E=d.useRef(null);d.useEffect(()=>{E.current&&f&&g?.row===n.id&&g?.column===r.id&&E.current.focus()},[g,f,n.id,r.id]);const I=d.useCallback(()=>{f&&!g&&h.exec("focus-cell",{row:n.id,column:r.id,eventSource:"focus"})},[h,f,g,n.id,r.id]);function T(F){const Y=new RegExp(`(${y.value.trim()})`,"gi");return String(F).split(Y).map(D=>({text:D,highlight:Y.test(D)}))}const P=d.useMemo(()=>{const F=r.fixed&&r.fixed.left===-1||r.fixed.right===-1,Y=r.fixed&&r.fixed.right;return[k,F?"wx-shadow":"",Y?"wx-fixed-right":""].filter(Boolean).join(" ")},[k,r]),U=r.cell;return o.jsxs("div",{className:"wx-TSCaXsGV "+P,ref:E,onFocus:I,style:x,"data-row-id":za(n.id),"data-col-id":za(r.id),tabIndex:f?"0":"-1",role:"gridcell","aria-colindex":r._colindex,"aria-readonly":r.editor?void 0:!0,children:[w&&r.draggable?N?o.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):o.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,r.treetoggle?o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{marginLeft:`${n.$level*28}px`}}),n.$count?o.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${n.open!==!1?"down":"right"}`}):null]}):null,U?o.jsx(U,{api:h,row:n,column:r,onAction:({action:F,data:Y})=>h.exec(F,Y)}):u?u():b?o.jsx("span",{children:T(ac(n,r)).map(({highlight:F,text:Y},D)=>F?o.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:Y},D):o.jsx("span",{children:Y},D))}):ac(n,r)]})}function Fw(t,n){let r,i;function l(h){r=h.clientX,t.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",u),window.addEventListener("mouseup",f),n&&n.down&&n.down(t)}function u(h){i=h.clientX-r,n&&n.move&&n.move(i)}function f(){t.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",n&&n.up&&n.up(i),window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",f)}return t.addEventListener("mousedown",l),{destroy(){t.removeEventListener("mousedown",l)}}}function qR({filter:t,column:n,action:r,filterValue:i}){function l({value:u}){r({value:u,key:n.id})}return o.jsx($v,{...t.config??{},value:i,onChange:l})}function WR({filter:t,column:n,action:r,filterValue:i}){const l=d.useContext(ks),u=Lt(l,"flatData"),f=d.useMemo(()=>t?.config?.options||n?.options||g(),[t,n,u]),h=d.useMemo(()=>t?.config?.template,[t]);function g(){const b=[];return u.forEach(x=>{const M=oc(x,n);b.includes(M)||b.push(M)}),b.map(x=>({id:x,label:x}))}function y({value:b}){r({value:b,key:n.id})}function w(b){b.key!=="Tab"&&b.preventDefault()}return o.jsx("div",{style:{width:"100%"},onKeyDown:w,children:o.jsx(sT,{placeholder:"",clear:!0,...t?.config??{},options:f,value:i,onChange:y,children:b=>h?h(b):b.label})})}function GR({filter:t,column:n,action:r,filterValue:i}){function l({value:u}){r({value:u,key:n.id})}return o.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:o.jsx(rT,{placeholder:"",clear:!0,...t?.config??{},value:i,onChange:l})})}function i0(t){const{value:n,options:r=[],placeholder:i="",clear:l=!1,text:u=null,template:f=null,cell:h=null,dropdown:g={},autoOpen:y=!1,onChange:w,onAction:b}=t,[x,M]=qS(n||[]),k=d.useMemo(()=>(x||[]).map(q=>r.find(O=>O.id===q)).filter(Boolean),[x,r]),N=d.useRef(null),E=d.useRef(null),[I,T]=d.useState(null),P=()=>{const q=x||[];if(!q.length)return 0;const O=r.find(W=>q.includes(W.id));return O?r.indexOf(O):0};function U(q){E.current=q.navigate,T(()=>q.keydown),y&&q.navigate(P())}d.useEffect(()=>{y&&(N.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function F({id:q}){M(q),w&&w({value:q})}function Y(q){q.stopPropagation(),M([]),w&&w({value:[]})}function D(){E.current?.(P())}function K(){E.current?.(null)}function ne(q){I?.(q,P())}return o.jsxs("div",{ref:N,className:"wx-multiselect wx-aadNNOwy",onClick:D,onKeyDown:ne,tabIndex:0,children:[o.jsx("div",{className:"wx-label wx-aadNNOwy",children:f?f(k):h?o.jsx(h,{data:k,onAction:b}):u?o.jsx("span",{className:"wx-text wx-aadNNOwy",children:u}):k.length?o.jsx("span",{className:"wx-text wx-aadNNOwy",children:k.map(q=>q.label).join(", ")}):i?o.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:i}):" "}),l&&x?.length?o.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:Y}):o.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),o.jsx(ih,{items:r,onReady:U,onSelect:F,multiselect:!0,checkboxes:!0,value:x||[],onCancel:K,...g,children:({option:q})=>o.jsx("div",{className:"wx-option wx-aadNNOwy",children:f?f(q):h?o.jsx(h,{data:q,onAction:b}):q.label})})]})}function VR({filter:t,column:n,action:r,filterValue:i}){const l=d.useContext(Ua.i18n)?.getGroup("grid")||rm(Wv).getGroup("grid"),u=d.useMemo(()=>({clear:!0,...t?.config||{}}),[t]),f=d.useMemo(()=>u.options||n.options,[u,n]),h=d.useMemo(()=>{const w=i?.length;return w?w<3?i.map(b=>n.optionsMap.get(b)).join(", "):w+" "+l("selected"):""},[i,n,l]);function g({value:w}){r({value:w,key:n.id})}function y(w){w.key!=="Tab"&&w.preventDefault()}return o.jsx("div",{style:{width:"100%"},onKeyDown:y,children:o.jsx(i0,{placeholder:"",...u,options:f,value:i||[],text:h,onChange:g})})}const KR={text:qR,richselect:WR,datepicker:GR,multiselect:VR};function QR({filter:t,column:n}){const r=d.useContext(ks),i=Lt(r,"filterValues");function l(f){r.exec("filter-rows",f)}const u=d.useMemo(()=>KR[t.type],[t.type]);return o.jsx(u,{filter:t,column:n,action:l,filterValue:i[n.id]})}function YR(t){const{cell:n,column:r,row:i,lastRow:l,sortRow:u,columnStyle:f,bodyHeight:h,hasSplit:g}=t,y=d.useContext(ks),w=Lt(y,"sortMarks"),b=d.useMemo(()=>w?w[r.id]:void 0,[w,r.id]),x=d.useRef(),M=d.useCallback($=>{x.current=n.flexgrow?$.parentNode.clientWidth:n.width},[n.flexgrow,n.width]),k=d.useCallback(($,ee)=>{y.exec("resize-column",{id:n.id,width:Math.max(1,(x.current||0)+$),inProgress:ee})},[y,n.id]),N=d.useCallback($=>k($,!0),[k]),E=d.useCallback($=>k($,!1),[k]),I=d.useCallback($=>{if(!r.sort||n.filter)return;let ee=b?.order;ee&&(ee=ee==="asc"?"desc":"asc"),y.exec("sort-rows",{key:n.id,add:$.ctrlKey||$.metaKey,order:ee})},[y,n.id,n.filter,r.sort,b?.order]),T=d.useCallback($=>{$&&$.stopPropagation(),y.exec("collapse-column",{id:n.id,row:i})},[y,n.id,i]),P=d.useCallback($=>{$.key==="Enter"&&T()},[T]),U=d.useCallback($=>{$.key==="Enter"&&!n.filter&&I($)},[I,n.filter]),F=d.useMemo(()=>n.collapsed&&r.collapsed,[n.collapsed,r.collapsed]),Y=d.useMemo(()=>F&&!g&&n.collapsible!=="header",[F,g,n.collapsible]),D=d.useMemo(()=>Y?{top:-h/2,position:"absolute"}:{},[Y,h]),K=d.useMemo(()=>lh(n.width,n.flexgrow,r.fixed,r.left,n.right??r.right,n.height+(F&&Y?h:0)),[n.width,n.flexgrow,r.fixed,r.left,n.right,r.right,n.height,F,Y,h]),ne=d.useMemo(()=>s0(r,n,f),[r,n,f]),q=d.useCallback(()=>Object.fromEntries(Object.entries(n).filter(([$])=>$!=="cell")),[n]),O=`wx-cell ${ne} ${n.css||""} wx-collapsed`,W=["wx-cell",ne,n.css||"",n.filter?"wx-filter":"",r.fixed&&r.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),ce=d.useRef(null);return d.useEffect(()=>{const $=ce.current;if(!$)return;const ee=Fw($,{down:M,move:N,up:E});return()=>{typeof ee=="function"&&ee()}},[M,N,E,Fw]),F?o.jsx("div",{className:"wx-RsQD74qC "+O,style:K,role:"button","aria-label":`Expand column ${n.text||""}`,"aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:P,onClick:T,"data-header-id":za(r.id),children:o.jsx("div",{className:"wx-RsQD74qC wx-text",style:D,children:n.text||""})}):o.jsxs("div",{className:"wx-RsQD74qC "+W,style:K,onClick:I,"data-header-id":za(r.id),tabIndex:!n._hidden&&r.sort&&!n.filter?0:void 0,role:"columnheader","aria-colindex":r._colindex,"aria-colspan":n.colspan>1?n.colspan:void 0,"aria-rowspan":n.rowspan>1?n.rowspan:void 0,"aria-sort":!b?.order||n.filter?"none":b?.order==="asc"?"ascending":"descending",onKeyDown:U,children:[n.collapsible?o.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":n.collapsed?"Expand column":"Collapse column","aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:P,onClick:T,children:o.jsx("i",{className:`wx-RsQD74qC wxi-angle-${n.collapsed?"down":"right"}`})}):null,n.cell?(()=>{const $=n.cell;return o.jsx($,{api:y,cell:q(),column:r,row:i,onAction:({action:ee,data:B})=>y.exec(ee,B)})})():n.filter?o.jsx(QR,{filter:n.filter,column:r}):o.jsx("div",{className:"wx-RsQD74qC wx-text",children:n.text||""}),r.resize&&l&&!n._hidden?o.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:ce,onClick:$=>$.stopPropagation(),children:o.jsx("div",{})}):null,u?o.jsx("div",{className:"wx-RsQD74qC wx-sort",children:b?o.jsxs(o.Fragment,{children:[typeof b.index<"u"?o.jsx("div",{className:"wx-RsQD74qC wx-order",children:b.index+1}):null,o.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${b.order==="asc"?"up":"down"}`})]}):null}):null]})}function XR({cell:t,column:n,row:r,columnStyle:i}){const l=d.useContext(ks),u=d.useMemo(()=>lh(t?.width,t?.flexgrow,n?.fixed,n?.left,t?.right??n?.right,t?.height),[t?.width,t?.flexgrow,n?.fixed,n?.left,t?.right,n?.right,t?.height]),f=d.useMemo(()=>s0(n,t,i),[n,t,i]),h=d.useCallback(()=>Object.fromEntries(Object.entries(t||{}).filter(([y])=>y!=="cell")),[t]),g=`wx-6Sdi3Dfd wx-cell ${f||""} ${t?.css||""}`+(n?.fixed&&n?.fixed.right?" wx-fixed-right":"");return o.jsx("div",{className:g,style:u,children:!n?.collapsed&&!t?.collapsed?t?.cell?kv.createElement(t.cell,{api:l,cell:h(),column:n,row:r,onAction:({action:y,data:w})=>l.exec(y,w)}):o.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:t?.text||""}):null})}function Ow({deltaLeft:t,contentWidth:n,columns:r,type:i="header",columnStyle:l,bodyHeight:u}){const f=d.useContext(ks),h=Lt(f,"_sizes"),g=Lt(f,"split"),y=d.useMemo(()=>h?.[`${i}RowHeights`],[h,i]),w=d.useMemo(()=>{let N=[];if(r&&r.length){const E=r[0][i].length;for(let I=0;I<E;I++){let T=0;N.push([]),r.forEach((P,U)=>{const F={...P[i][I]};T||N[I].push(F),F.colspan>1?T=F.colspan-1:T&&T--})}}return N},[r,i]),b=d.useMemo(()=>g?.left||g?.right,[g]);function x(N){return r.find(E=>E.id===N)}function M(N,E){let I=E;return N.rowspan&&(I+=N.rowspan-1),I===w.length-1}function k(N,E,I){if(!I.sort)return!1;for(let T=w.length-1;T>=0;T--){const P=I.header[T];if(!P.filter&&!P._hidden)return E===T}return M(N,E)}return o.jsx("div",{className:`wx-sAsPVaUK wx-${i}`,style:{paddingLeft:`${t}px`,width:`${n}px`},role:"rowgroup",children:w.map((N,E)=>o.jsx("div",{className:i==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[E]}px`,display:"flex"},role:"row",children:N.map(I=>{const T=x(I.id);return i==="header"?o.jsx(YR,{cell:I,columnStyle:l,column:T,row:E,lastRow:M(I,E),bodyHeight:u,sortRow:k(I,E,T),hasSplit:b},I.id):o.jsx(XR,{cell:I,columnStyle:l,column:x(I.id),row:E},I.id)})},E))})}function ZR({overlay:t}){const n=d.useContext(ks);function r(l){return typeof l=="function"}const i=t;return o.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:r(t)?o.jsx(i,{onAction:({action:l,data:u})=>n.exec(l,u)}):t})}function JR(t){const{editor:n,onSave:r,onApply:i}=t,[l,u]=d.useState(n?.value||""),{type:f="text"}=d.useMemo(()=>n?.config||{},[n]),h=d.useRef(null);d.useEffect(()=>{h.current&&h.current.focus()},[]),d.useEffect(()=>{if(!h.current)return;const w=go(h.current,()=>r(!0));return()=>w.destroy()},[r]);function g(){h.current&&(u(h.current.value),i(h.current.value))}function y({key:w}){w==="Enter"&&r()}return o.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:y,ref:h,type:f,value:l})}function ej({editor:t,onAction:n,onSave:r,onApply:i,onCancel:l}){const[u,f]=d.useState(t?.value),[h,g]=d.useState(t?.renderedValue),[y,w]=d.useState(t?.options||[]),b=d.useMemo(()=>t?.config?.template,[t]),x=d.useMemo(()=>t?.config?.cell,[t]),M=d.useMemo(()=>t?.config?.dropdown||{},[t]),k=d.useMemo(()=>({trackScroll:!0,...M}),[M]),N=d.useMemo(()=>(y||[]).findIndex(D=>D.id===u),[y,u]),E=d.useRef(null),I=d.useRef(null),T=d.useCallback(D=>{E.current=D.navigate,I.current=D.keydown,E.current(N)},[N,E]),P=d.useCallback(D=>{const K=D?.target?.value??"";g(K);const ne=K?(t?.options||[]).filter(q=>(q.label||"").toLowerCase().includes(K.toLowerCase())):t?.options||[];w(ne),ne.length?E.current(-1/0):E.current(null)},[t]),U=d.useRef(null);d.useEffect(()=>{U.current&&U.current.focus()},[]);const F=d.useRef(r);d.useEffect(()=>{F.current=r},[r]),d.useEffect(()=>{if(!U.current)return;const D=go(U.current,()=>F.current(!0));return()=>D.destroy()},[]),d.useEffect(()=>{f(t?.value),g(t?.renderedValue),w(t?.options||[])},[t]);const Y=d.useCallback(({id:D})=>{i(D),r()},[i,r]);return o.jsxs(o.Fragment,{children:[o.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:U,value:h??"",onChange:P,onKeyDown:D=>I.current?I.current(D,N):void 0}),o.jsx(ih,{items:y,onReady:T,onSelect:Y,...k,onCancel:l,children:({option:D})=>b?b(D):x?o.jsx(x,{data:D,onAction:n}):D.label})]})}function tj({editor:t,onAction:n,onSave:r,onApply:i,onCancel:l}){const[u]=d.useState(()=>t.value||new Date),{template:f,cell:h,dropdown:g={}}=t?.config||{},y=d.useMemo(()=>({trackScroll:!0,width:"auto",...g}),[g]);function w({value:k}){i(k),r()}const b=d.useRef(null),[x,M]=d.useState(null);return d.useEffect(()=>{b.current&&b.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!x)return;const k=go(x,()=>r(!0));return()=>k.destroy()},[x,r]),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:b,tabIndex:0,onClick:l,onKeyDown:k=>k.preventDefault(),children:f?f(u):h?o.jsx(h,{data:t.value,onAction:n}):o.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:t.renderedValue})}),o.jsx(zv,{...y,onCancel:l,children:o.jsx("div",{ref:M,className:"wx-lNWNYUb6",children:o.jsx(HS,{value:u,onChange:w,buttons:t.config?.buttons})})})]})}function nj(t){const{editor:n}=t,r=t.onAction??t.onaction,i=t.onSave??t.onsave,l=t.onApply??t.onapply,u=t.onCancel??t.oncancel,f=n.config||{},{dropdown:h={}}=f,g=d.useMemo(()=>({trackScroll:!0,...h}),[h]),[y]=d.useState(n.options.find(P=>P.id===n.value)),[w]=d.useState(n.value),[b]=d.useState(n.options),x=d.useMemo(()=>b.findIndex(P=>P.id===w),[b,w]);function M({id:P}){l(P),i()}let k;const[N,E]=d.useState();function I(P){k=P.navigate,E(()=>P.keydown),k(x)}const T=d.useRef(null);return d.useEffect(()=>{T.current&&T.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!T.current)return;const P=go(T.current,()=>i(!0));return()=>P.destroy()},[i]),o.jsxs(o.Fragment,{children:[o.jsx("div",{ref:T,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:u,onKeyDown:P=>{N(P,x),P.preventDefault()},children:f.template?f.template(y):f.cell?(()=>{const P=f.cell;return o.jsx(P,{data:y,onAction:r})})():o.jsx("span",{className:"wx-ywGRk611 wx-text",children:n.renderedValue})}),o.jsx(ih,{items:b,onReady:I,onSelect:M,...g,onCancel:u,children:({option:P})=>f.template?f.template(P):f.cell?(()=>{const U=f.cell;return o.jsx(U,{data:P,onAction:r})})():P.label})]})}function aj(t){const{editor:n,onAction:r,onSave:i,onApply:l}=t,u=n?.config||{},f=n?.options??[],h=n?.value||[],g=n?.renderedValue,y=d.useMemo(()=>({trackScroll:!0,...u.dropdown||{}}),[u]);function w({value:x}){l(x)}const b=d.useRef(null);return d.useEffect(()=>{if(!b.current)return;const x=go(b.current,()=>i(!0));return()=>x.destroy()},[i]),o.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>i(!0),children:o.jsx(i0,{value:h,options:f,text:g,template:u.template,cell:u.cell,clear:u.clear,dropdown:y,autoOpen:!0,onChange:w,onAction:r})})}const rj={text:JR,combo:ej,datepicker:tj,richselect:nj,multiselect:aj};function sj({column:t,row:n}){const r=d.useContext(ks),i=Lt(r,"editor"),l=d.useCallback((k,N)=>{r.exec("close-editor",{ignore:k}),N&&r.exec("focus-cell",{...N,eventSource:"click"})},[r]),u=d.useCallback(k=>{const N=k?null:{row:i?.id,column:i?.column};l(!1,N)},[i,l]),f=d.useCallback(()=>{l(!0,{row:i?.id,column:i?.column})},[i,l]),h=d.useCallback(k=>{r.exec("editor",{value:k})},[r]),g=d.useCallback(k=>{k.key==="Enter"&&i&&(t.editor.type==="multiselect"?h(i.value):f())},[i,t.editor,f,h]),y=d.useMemo(()=>lh(t.width,t.flexgrow,t.fixed,t.left,t.right),[t.width,t.flexgrow,t.fixed,t.left,t.right]),w=d.useMemo(()=>{let k=t.editor;if(typeof k=="function"&&(k=k(n,t)),!k)return null;let N=typeof k=="string"?k:k.type;return rj[N]},[t,n]),b=d.useRef(null);d.useEffect(()=>{b.current&&typeof y=="string"&&b.current.setAttribute("style",y)},[y]);const x=typeof n.$parent<"u"?"gridcell":"cell",M=typeof n.$parent<"u"?!t.editor:void 0;return o.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:b,style:typeof y=="object"&&y!==null?y:void 0,role:x,"aria-readonly":M,tabIndex:-1,onClick:k=>k.stopPropagation(),onDoubleClick:k=>k.stopPropagation(),onKeyDown:g,children:w?o.jsx(w,{editor:i,onSave:u,onApply:h,onCancel:f,onAction:({action:k,data:N})=>r.exec(k,N)}):null})}function Hw(t){const{columns:n,type:r,columnStyle:i}=t,l=d.useContext(ks),{filterValues:u,_columns:f,_sizes:h}=l.getState();function g(y){return i?" "+i(y):""}return o.jsx(o.Fragment,{children:n.map((y,w)=>o.jsx("tr",{children:y.map(b=>{const x=f.find(N=>N.id===b.id),M=`wx-print-cell-${r}${g(x)}${b.filter?" wx-print-cell-filter":""}${b.vertical?" wx-vertical":""}`,k=b.cell;return o.jsx("th",{style:WS(e0(b,h.columnWidth)),className:"wx-Gy81xq2u "+M,rowSpan:b.rowspan,colSpan:b.colspan,children:k?o.jsx(k,{api:l,cell:Object.fromEntries(Object.entries(b).filter(([N])=>N!=="cell")),column:x,row:w}):b.filter?o.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:cR(u,f,b)}):o.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},w))})}function ij(t){const{columns:n,rowStyle:r,columnStyle:i,cellStyle:l,header:u,footer:f,reorder:h}=t,g=d.useContext(ks),{flatData:y,_sizes:w}=g.getState(),b=u&&Dw(n,"header",w.headerRowHeights),x=f&&Dw(n,"footer",w.footerRowHeights);function M(N,E){let I="";return I+=i?" "+i(E):"",I+=l?" "+l(N,E):"",I}function k(N,E){return typeof E.draggable=="function"?E.draggable(N,E)!==!1:E.draggable}return o.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${n.some(N=>N.flexgrow)?"wx-flex-columns":""}`,children:[u?o.jsx("thead",{children:o.jsx(Hw,{columns:b,type:"header",columnStyle:i})}):null,o.jsx("tbody",{children:y.map((N,E)=>o.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(r?" "+r(N):""),style:{height:`${N.rowHeight||w.rowHeight}px`},children:n.map(I=>I.collapsed?null:o.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${M(N,I)}`,style:WS(e0(I,w.columnWidth)),children:[h&&I.draggable?o.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:k(N,I)?o.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,I.treetoggle?o.jsxs(o.Fragment,{children:[o.jsx("span",{style:{marginLeft:N.$level*28+"px"}}),N.$count?o.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${N.open!==!1?"down":"right"}`}):null]}):null,I.cell?(()=>{const T=I.cell;return o.jsx(T,{api:g,row:N,column:I})})():o.jsx("span",{children:ac(N,I)})]},I.id))},E))}),f?o.jsx("tfoot",{children:o.jsx(Hw,{columns:x,type:"footer",columnStyle:i})}):null]})}function oj(t){const{config:n,...r}=t,i=d.useContext(ks),{_skin:l,_columns:u}=i.getState(),f=d.useMemo(()=>sR(u,n),[]),h=d.useRef(null);return d.useEffect(()=>{const g=document.body;g.classList.add("wx-print");const y=h.current;if(!y)return;const w=y.cloneNode(!0);g.appendChild(w);const b=`@media print { @page { size: ${n.paper} ${n.mode}; }`,x=document.createElement("style");x.setAttribute("type","text/css"),x.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(x),x.appendChild(document.createTextNode(b)),window.print(),x.remove(),g.classList.remove("wx-print"),w.remove()},[]),o.jsx("div",{className:`wx-4zwCKA7C wx-${l}-theme wx-print-container`,ref:h,children:f.map((g,y)=>o.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:o.jsx(ij,{columns:g,...r})},y))})}function lj(t){const{header:n,footer:r,overlay:i,multiselect:l,onreorder:u,rowStyle:f,columnStyle:h,cellStyle:g,autoRowHeight:y,resize:w,clientWidth:b,clientHeight:x,responsiveLevel:M,hotkeys:k}=t,N=d.useContext(ks),E=Lt(N,"dynamic"),I=Lt(N,"_columns"),T=Lt(N,"flatData"),P=Lt(N,"split"),U=Lt(N,"_sizes"),[F,Y]=Vs(N,"selectedRows"),D=Lt(N,"select"),K=Lt(N,"editor"),ne=Lt(N,"scrollLeft"),q=Lt(N,"scrollTop"),O=Lt(N,"tree"),W=Lt(N,"focusCell"),ce=Lt(N,"_print"),$=Lt(N,"undo"),ee=Lt(N,"reorder"),B=Lt(N,"_rowHeightFromData"),[L,oe]=d.useState(0);d.useEffect(()=>{oe(Pn())},[]);const[be,H]=d.useState(0),me=d.useMemo(()=>(I||[]).some(fe=>!fe.hidden&&fe.flexgrow),[I]),ue=d.useMemo(()=>U?.rowHeight||0,[U]),Ce=d.useRef(null),[Me,Ne]=d.useState(null),[He,Ve]=d.useState(null),ie=d.useMemo(()=>{let fe=[],_e=0;return P&&P.left&&(fe=(I||[]).slice(0,P.left).filter(et=>!et.hidden).map(et=>({...et})),fe.forEach(et=>{et.fixed={left:1,leftSize:P.left},et.left=_e,_e+=et.width}),fe.length&&(fe[fe.length-1].fixed.left=-1)),{columns:fe,width:_e}},[P,I]),Oe=d.useMemo(()=>{let fe=[],_e=0;if(P&&P.right){fe=(I||[]).slice(P.right*-1).filter(et=>!et.hidden).map(et=>({...et}));for(let et=fe.length-1;et>=0;et--){const Rt=fe[et];Rt.fixed={right:1},Rt.right=_e,_e+=Rt.width}fe.length&&(fe[0].fixed={right:-1})}return{columns:fe,width:_e}},[P,I]),$e=d.useMemo(()=>{const fe=(I||[]).slice(P?.left||0,(I||[]).length-(P?.right??0)).filter(_e=>!_e.hidden);return fe.forEach(_e=>{_e.fixed=0}),fe},[I,P]),qe=d.useMemo(()=>(I||[]).reduce((fe,_e)=>(_e.hidden||(fe+=_e.width),fe),0),[I]),vt=1;function xe(fe,_e,et){let Rt=_e,An=fe;if($e.length){let Et=$e.length;for(let ct=fe;ct>=0;ct--)$e[ct][et].forEach(jt=>{jt.colspan>1&&ct>fe-jt.colspan&&ct<Et&&(Et=ct)});if(Et!==$e.length&&Et<fe){for(let ct=Et;ct<fe;ct++)Rt-=$e[ct].width;An=Et}}return{index:An,delta:Rt}}const he=d.useMemo(()=>{let fe,_e,et;const Rt=ne||0,An=(ne||0)+(b||0);let Et=0,ct=0,jt=0,mt=0;$e.forEach((Nn,Un)=>{Rt>jt&&(Et=Un,mt=jt),jt=jt+Nn.width,An>jt&&(ct=Un+vt)});const Yt={header:0,footer:0};for(let Nn=ct;Nn>=Et;Nn--)["header","footer"].forEach(Un=>{$e[Nn]&&$e[Nn][Un].forEach(Ni=>{const Ja=Ni.colspan;if(Ja&&Ja>1){const Er=Ja-(ct-Nn+1);Er>0&&(Yt[Un]=Math.max(Yt[Un],Er))}})});const fn=xe(Et,mt,"header"),Xt=xe(Et,mt,"footer"),Rn=fn.delta,Wt=fn.index,jr=Xt.delta,Ks=Xt.index;return me&&qe>(b||0)?fe=_e=et=[...ie.columns,...$e,...Oe.columns]:(fe=[...ie.columns,...$e.slice(Et,ct+1),...Oe.columns],_e=[...ie.columns,...$e.slice(Wt,ct+Yt.header+1),...Oe.columns],et=[...ie.columns,...$e.slice(Ks,ct+Yt.footer+1),...Oe.columns]),{data:fe||[],header:_e||[],footer:et||[],d:mt,df:jr,dh:Rn}},[$e,ie,Oe,ne,b,me,qe]),pe=d.useMemo(()=>n&&U?.headerHeight||0,[n,U]),Ae=d.useMemo(()=>r&&U?.footerHeight||0,[r,U]),Se=d.useMemo(()=>b&&x?qe>=b:!1,[b,x,qe]),[Pe,Qe]=d.useState(!1),Z=d.useMemo(()=>(x||0)-pe-Ae-(Se?L:0),[x,pe,Ae,Se,L]),$t=d.useMemo(()=>Math.ceil((Z||0)/(ue||1))+1,[Z,ue]),Ee=d.useRef([]),[Ge,ze]=d.useState(0),[Ft,Ze]=d.useState(void 0),nt=d.useMemo(()=>{let fe=0,_e=0;const et=2,Rt=q||0;if(y){let ct=Rt;for(;ct>0;)ct-=Ee.current[fe]||ue,fe++;_e=Rt-ct;for(let jt=Math.max(0,fe-et-1);jt<fe;jt++)_e-=Ee.current[fe-jt]||ue;fe=Math.max(0,fe-et)}else{if(B){let ct=0,jt=0;for(let Xt=0;Xt<(T||[]).length;Xt++){const Rn=T[Xt].rowHeight||ue;if(jt+Rn>Rt){ct=Xt;break}jt+=Rn}fe=Math.max(0,ct-et);for(let Xt=0;Xt<fe;Xt++)_e+=T[Xt].rowHeight||ue;let mt=0,Yt=0;for(let Xt=ct+1;Xt<(T||[]).length;Xt++){const Rn=T[Xt].rowHeight||ue;if(mt++,Yt+Rn>Z)break;Yt+=Rn}const fn=Math.min(E?E.rowCount:(T||[]).length,ct+mt+et);return{d:_e,start:fe,end:fn}}fe=Math.floor(Rt/(ue||1)),fe=Math.max(0,fe-et),_e=fe*(ue||0)}const An=E?E.rowCount:(T||[]).length,Et=Math.min(An,fe+($t||0)+et);return{d:_e,start:fe,end:Et}},[y,B,q,ue,E,T,$t,Z]),lt=d.useMemo(()=>{const fe=E?E.rowCount:(T||[]).length;if(y)return Ge+nt.d+(fe-(Ft||0))*(ue||0);if(!B)return fe*(ue||0);let _e=0;for(let et=0;et<fe;et++)_e+=T[et]?.rowHeight||ue;return _e},[E,T,ue,y,B,Ge,nt.d,Ft]),Tt=d.useRef({});Tt.current={clientWidth:b,clientHeight:x,fullHeight:lt,headerHeight:pe,footerHeight:Ae,fullWidth:qe,SCROLLSIZE:L};const Mt=d.useCallback(()=>{const fe=Tt.current;Qe(fe.clientWidth&&fe.clientHeight?fe.fullHeight+fe.headerHeight+fe.footerHeight>=fe.clientHeight-(fe.fullWidth>=fe.clientWidth?fe.SCROLLSIZE:0):!1)},[]);d.useEffect(()=>{const fe=requestAnimationFrame(Mt);return()=>window.cancelAnimationFrame(fe)},[be,Mt]),d.useEffect(()=>{Mt()},[x,Mt]);const rt=d.useMemo(()=>me&&qe<=(b||0)?(b||0)-0-(Pe?L:0):qe,[me,qe,b,Pe,L,Se]),dt=d.useMemo(()=>me&&qe<=(b||0)?b||0:rt<(b||0)?qe+(Pe?L:0):-1,[me,qe,b,rt,Pe,L]),G=d.useRef({});d.useEffect(()=>{if(E&&(G.current.start!==nt.start||G.current.end!==nt.end)){const{start:fe,end:_e}=nt;G.current={start:fe,end:_e},N&&N.exec&&N.exec("request-data",{row:{start:fe,end:_e}})}},[E,nt,N]);const ge=d.useMemo(()=>E?T||[]:(T||[]).slice(nt.start,nt.end),[E,T,nt]),De=d.useMemo(()=>(F||[]).filter(fe=>(ge||[]).some(_e=>_e.id===fe)),[Y,ge]),z=d.useMemo(()=>nt.start,[nt.start]),ae=d.useRef({top:q,left:ne});ae.current={top:q,left:ne};const Te=d.useCallback(fe=>{const _e=fe.target.scrollTop,et=fe.target.scrollLeft,Rt=ae.current;(_e!==Rt.top||et!==Rt.left)&&N.exec("scroll-to",{top:_e,left:et})},[N]),Ue=d.useCallback(fe=>{fe.shiftKey&&fe.preventDefault(),Ce.current&&Ce.current.focus&&Ce.current.focus()},[]),Xe=d.useCallback(()=>!!(I||[]).find(fe=>!!fe.draggable),[I]),at=d.useRef(null),kt=d.useRef(null),At=d.useRef({dblclick:(fe,_e)=>{const et={id:fe,column:em(_e,"data-col-id")};N.exec("open-editor",et)},click:(fe,_e)=>{if(_e.target.closest("input")||at.current)return;const et=em(_e,"data-col-id");if(W?.id!==fe&&N.exec("focus-cell",{row:fe,column:et,eventSource:"click"}),D===!1)return;const Rt=l&&(_e.ctrlKey||_e.metaKey),An=l&&_e.shiftKey;(Rt||F.length>1||!F.includes(fe))&&N.exec("select-row",{id:fe,toggle:Rt,range:An})},"toggle-row":fe=>{const _e=N.getRow(fe);N.exec(_e.open!==!1?"close-row":"open-row",{id:fe})},"ignore-click":()=>!1}),Ut=d.useMemo(()=>({top:pe,bottom:Ae,left:ie.width,xScroll:Se,yScroll:Pe,sense:y&&He?He.offsetHeight:Math.max(U?.rowHeight||0,40),node:Ce.current&&Ce.current.firstElementChild}),[pe,Ae,ie.width,Se,Pe,y,He,U]);function Qt(fe,_e){const{container:et,sourceNode:Rt,from:An}=_e;if(Xe()&&!Rt.getAttribute("draggable-data"))return!1;Ne(An),O&&N.getRow(An).open&&N.exec("close-row",{id:An,nested:!0});const Et=Sd(Rt),ct=Et.cloneNode(!0);ct.classList.remove("wx-selected"),ct.querySelectorAll("[tabindex]").forEach(fn=>fn.setAttribute("tabindex","-1")),et.appendChild(ct),Ve(ct);const jt=(ne||0)-he.d,mt=Pe?L:0;et.style.width=Math.min((b||0)-mt,me&&qe<=(b||0)?rt:rt-mt)+jt+"px";const Yt=Ip(Et);_e.offset={x:jt,y:-Math.round(Yt.height/2)},kt.current||(kt.current=fe.clientY)}function sa(fe,_e){const{from:et}=_e,Rt=_e.pos,An=Ip(Ce.current);Rt.x=An.x;const Et=Ut.top;if(Rt.y<Et)Rt.y=Et;else{const ct=An.height-(Se&&L>0?L:Math.round(Ut.sense/2))-Ut.bottom;Rt.y>ct&&(Rt.y=ct)}if(Ce.current.contains(_e.targetNode)){const ct=Sd(_e.targetNode),jt=ct&&rh(ct);if(jt&&jt!==et){_e.to=jt;const mt=y?He?.offsetHeight:U?.rowHeight;if(He&&((q||0)===0||Rt.y>Et+mt-1)){const Yt=ct.getBoundingClientRect(),fn=Ip(He).y,Xt=Yt.y,Rn=fn>Xt?-1:1,Wt=Rn===1?"after":"before",jr=N.getState().flatData,Ks=Math.abs(jr.findIndex(Un=>Un.id===et)-jr.findIndex(Un=>Un.id===jt)),Nn=Ks!==1?Wt==="before"?"after":"before":Wt;if(Ks===1&&(Rn===-1&&fe.clientY>kt.current||Rn===1&&fe.clientY<kt.current))return;kt.current=fe.clientY,N.exec("move-item",{id:et,target:jt,mode:Nn,inProgress:!0})}}u&&u({event:fe,context:_e})}OR(fe,An,_e,Ut)}function Ra(fe,_e){const{from:et,to:Rt}=_e;N.exec("move-item",{id:et,target:Rt,inProgress:!1}),at.current=setTimeout(()=>{at.current=0},1),Ne(null),Ve(null),kt.current=null,a0(_e)}function Pn(){const fe=document.createElement("div");fe.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(fe);const _e=fe.offsetWidth-fe.clientWidth;return document.body.removeChild(fe),_e}const $n=d.useMemo(()=>dt>0?{width:`${dt}px`}:void 0,[dt]),ia=d.useRef(null);function Fe(){Promise.resolve().then(()=>{let fe=0,_e=z;const et=ia.current;et&&(Array.from(et.children).forEach((Rt,An)=>{Ee.current[z+An]=Rt.offsetHeight,fe+=Rt.offsetHeight,_e++}),ze(fe),Ze(_e))})}d.useEffect(()=>{ge&&y&&Fe()},[ge,y,z]);let[V,Je]=d.useState();d.useEffect(()=>{if(W&&(!D||!De.length||De.includes(W.row)))Je({...W});else if(ge.length&&he.data.length){if(!V||De.length&&!De.includes(V.row)||ge.findIndex(fe=>fe.id===V.row)===-1||he.data.findIndex(fe=>fe.id===V.column&&!fe.collapsed)===-1){const fe=De[0]||ge[0].id,_e=he.data.findIndex(et=>!et.collapsed);Je(_e!==-1?{row:fe,column:he.data[_e].id}:null)}}else Je(null)},[W]);const gt=d.useRef(null);d.useEffect(()=>{const fe=Ce.current;if(!fe)return;const _e=IR(fe,w);return()=>{typeof _e=="function"&&_e()}},[w]);const nn=d.useRef({});Object.assign(nn.current,{start:Qt,move:sa,end:Ra,getReorder:()=>ee,getDraggableInfo:()=>({hasDraggable:Xe()})}),d.useEffect(()=>{const fe=Ce.current;return fe?_R(fe,nn).destroy:void 0},[ee,Ce.current]),d.useEffect(()=>{const fe=Ce.current;return fe?ER(fe,{keys:k!==!1&&{...jR,"ctrl+z":$,"ctrl+y":$,...k},exec:_e=>N.exec("hotkey",_e)}).destroy:void 0},[N,$,k]);const Sn=d.useRef({scroll:N.getReactiveState().scroll,scrollLeft:N.getReactiveState().scrollLeft,scrollTop:N.getReactiveState().scrollTop});Sn.current.getWidth=()=>(b||0)-(Pe?L:0),Sn.current.getHeight=()=>Z,Sn.current.getScrollMargin=()=>ie.width+Oe.width,d.useEffect(()=>{DR(gt.current,Sn.current)},[]);const Ms=d.useRef(null);d.useEffect(()=>{const fe=Ms.current;if(!fe)return;const _e=[];_e.push(go(fe,()=>W&&N.exec("focus-cell",{eventSource:"click"})).destroy),_e.push(_T(fe,At.current)),H(fe.clientHeight);const et=new ResizeObserver(()=>{H(fe.clientHeight)});return et.observe(fe),_e.push(()=>et.disconnect()),()=>_e.forEach(Rt=>Rt())},[]);const qa=`wx-grid ${M?`wx-responsive-${M}`:""}`;return d.useEffect(()=>{W&&(ge.some(fe=>fe.id===W.row)&&he.data.some(fe=>fe.id===W.column&&!fe.collapsed)||N.exec("focus-cell",{eventSource:"destroy"}))},[W,ge,he.data,N]),o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-4VuBwK2D "+qa,style:{"--header-height":`${pe}px`,"--footer-height":`${Ae}px`,"--split-left-width":`${ie.width}px`,"--split-right-width":`${Oe.width}px`},children:o.jsx("div",{ref:Ce,className:"wx-4VuBwK2D wx-table-box",style:$n,role:O?"treegrid":"grid","aria-colcount":he.data.length,"aria-rowcount":ge.length,"aria-multiselectable":O&&l?!0:void 0,tabIndex:-1,children:o.jsxs("div",{ref:gt,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:Se?"scroll":"hidden",overflowY:Pe?"scroll":"hidden"},onScroll:Te,children:[n?o.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:o.jsx(Ow,{contentWidth:rt,deltaLeft:he.dh,columns:he.header,columnStyle:h,bodyHeight:Z-+r})}):null,o.jsxs("div",{ref:Ms,className:"wx-4VuBwK2D wx-body",style:{width:`${rt}px`,height:`${lt}px`},onMouseDown:fe=>Ue(fe),children:[i?o.jsx(ZR,{overlay:i}):null,o.jsx("div",{ref:ia,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${nt.d}px`,paddingLeft:`${he.d}px`},children:ge.map((fe,_e)=>{const et=F.indexOf(fe.id)!==-1,Rt=Me===fe.id,An="wx-row"+(y?" wx-autoheight":"")+(f?" "+f(fe):"")+(et?" wx-selected":"")+(Rt?" wx-inactive":""),Et=y?{minHeight:`${fe.rowHeight||ue}px`}:{height:`${fe.rowHeight||ue}px`};return o.jsx("div",{className:"wx-4VuBwK2D "+An,"data-id":za(fe.id),"data-context-id":za(fe.id),style:Et,role:"row","aria-rowindex":_e,"aria-expanded":fe.open,"aria-level":O?fe.$level+1:void 0,"aria-selected":O?et:void 0,tabIndex:-1,children:he.data.map(ct=>ct.collapsed?o.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},ct.id):K?.id===fe.id&&K.column===ct.id?o.jsx(sj,{row:fe,column:ct},ct.id):o.jsx(UR,{row:fe,column:ct,columnStyle:h,cellStyle:g,reorder:ee,focusable:V?.row===fe.id&&V?.column===ct.id},ct.id))},fe.id)})})]}),r&&(T||[]).length?o.jsx(Ow,{type:"footer",contentWidth:rt,deltaLeft:he.df,columns:he.footer,columnStyle:h}):null]})})}),ce?o.jsx(oj,{config:ce,rowStyle:f,columnStyle:h,cellStyle:g,header:n,footer:r,reorder:ee}):null]})}const cj=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join(""),uj=d.forwardRef(function({data:t=[],columns:n=[],rowStyle:r=null,columnStyle:i=null,cellStyle:l=null,selectedRows:u,select:f=!0,multiselect:h=!1,header:g=!0,footer:y=!1,dynamic:w=null,overlay:b=null,reorder:x=!1,onReorder:M=null,autoRowHeight:k=!1,sizes:N,split:E,tree:I=!1,autoConfig:T=!1,init:P=null,responsive:U=null,sortMarks:F,undo:Y=!1,hotkeys:D=null,filterValues:K,...ne},q){const O=d.useRef();O.current=ne;const W=d.useMemo(()=>new kR(GS),[]),ce=d.useMemo(()=>W.in,[W]),$=d.useRef(null);$.current===null&&($.current=new BS((Oe,$e)=>{const qe="on"+cj(Oe);O.current&&O.current[qe]&&O.current[qe]($e)}),ce.setNext($.current));const ee=d.useMemo(()=>({getState:W.getState.bind(W),getReactiveState:W.getReactive.bind(W),getStores:()=>({data:W}),exec:ce.exec,setNext:Oe=>($.current=$.current.setNext(Oe),$.current),intercept:ce.intercept.bind(ce),on:ce.on.bind(ce),detach:ce.detach.bind(ce),getRow:W.getRow.bind(W),getColumn:W.getColumn.bind(W)}),[W,ce]),[B,L]=d.useState(0),[oe,be]=d.useState(0),[H,me]=d.useState(null),[ue,Ce]=d.useState(null),Me=d.useMemo(()=>{if(T&&!n.length&&t.length){const Oe=t[0],$e=[];for(let qe in Oe)if(qe!=="id"&&qe[0]!=="$"){let vt={id:qe,header:qe[0].toUpperCase()+qe.slice(1)};typeof T=="object"&&(vt={...vt,...T}),$e.push(vt)}return $e}return(ue&&ue.columns)??n},[T,n,t,ue]),Ne=d.useMemo(()=>(ue&&ue.sizes)??N,[ue,N]),He=d.useCallback(Oe=>{if(L(Oe.width),be(Oe.height),U){const $e=Object.keys(U).map(Number).sort((qe,vt)=>qe-vt).find(qe=>Oe.width<=qe)??null;$e!==H&&(Ce(U[$e]),me($e))}},[U,H]),Ve=d.useContext(Ua.theme),ie=d.useRef(0);return d.useEffect(()=>{if(!ie.current)P&&P(ee);else{const Oe=W.getState();W.init({data:t,columns:Me,split:E||Oe.split,sizes:Ne||Oe.sizes,selectedRows:u||Oe.selectedRows,dynamic:w,tree:I,sortMarks:F||Oe.sortMarks,filterValues:K||Oe.filterValues,undo:Y,reorder:x,_skin:Ve,_select:f})}ie.current++},[W,t,Me,E,Ne,u,w,I,F,K,Y,x,Ve,f,P,ee]),ie.current===0&&W.init({data:t,columns:Me,split:E||{left:0},sizes:Ne||{},selectedRows:u||[],dynamic:w,tree:I,sortMarks:F||{},filterValues:K||{},undo:Y,reorder:x,_skin:Ve,select:f}),d.useImperativeHandle(q,()=>({...ee}),[ee]),o.jsx(ks.Provider,{value:ee,children:o.jsx(qv,{words:Wv,optional:!0,children:o.jsx(lj,{header:g,footer:y,overlay:b,rowStyle:r,columnStyle:i,cellStyle:l,onReorder:M,multiselect:h,autoRowHeight:k,clientWidth:B,clientHeight:oe,responsiveLevel:H,resize:He,hotkeys:D})})})});Fv(Yr);const $a=d.createContext(null),Kv=d.createContext(null),Qv=d.createContext(null);function dj({children:t}){const n=d.useContext(Ua.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),i=d.useContext($a),[l]=Vs(i,"panels"),u=Lt(i,"activePanel"),f=l[u].path,[h,g]=d.useState(null),[y,w]=d.useState(null),[b,x]=d.useState(""),[M,k]=d.useState(""),[N,E]=d.useState(!1);function I(){const F=b.trim();if(!F){E(!0);return}h.add?i.exec("create-file",{file:{...h.item,name:F},parent:f}):M!==F&&i.exec("rename-file",{id:h.item.id,name:F}),T()}function T(){g(null),E(null),k(""),x("")}function P(){i.exec("delete-files",{ids:y.selected}),w(null)}const U=d.useMemo(()=>({showPrompt(F){const Y=F.item.name||(F.item.type==="folder"?r("New folder"):`${r("New file")}.txt`);k(Y),x(Y),g({...F})},showConfirm(F){w({...F})}}),[r]);return o.jsxs(Kv.Provider,{value:U,children:[o.jsx(dT,{children:t}),h?o.jsx(pv,{title:r(`Enter ${h.item.type} name`),onConfirm:I,onCancel:T,children:o.jsx($v,{error:N,select:!0,focus:!0,value:b,onChange:({value:F})=>x(F)})}):null,y?o.jsx(pv,{title:r("Are you sure you want to delete these items:"),onConfirm:P,onCancel:()=>w(null),children:y.selected?o.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:y.selected.map((F,Y)=>o.jsx("li",{children:F},Y))}):null}):null]})}let Bw={"7z":!0,rar:!0,zip:!0,css:!0,html:!0,js:!0,php:!0,md:!0,xml:!0,sql:!0,aif:!0,mid:!0,mp3:!0,waw:!0,wma:!0,doc:!0,docx:!0,txt:!0,avi:!0,mov:!0,mp4:!0,mpeg:!0,mpg:!0,pdf:!0,xls:!0,xlsx:!0,gif:!0,jpg:!0,jpeg:!0,png:!0,psd:!0,tiff:!0,svg:!0,folder:!0,file:!0,multiple:!0,search:!0,none:!0};function fj(t){const n=t.lastIndexOf("."),r=n>0&&n<t.length-1?Math.min(10,t.length-n):Math.min(5,t.length),i=t.slice(0,-r),l=t.slice(-r);return[i,l]}function mj({item:t}){const n=d.useContext($a),r=d.useContext(Ua.i18n).getGroup("filemanager"),i=d.useContext($a).templates,[l]=Vs(n,"panels"),u=Lt(n,"activePanel"),f=Lt(n,"mode"),h=l[u].selected,g=d.useMemo(()=>i.preview(t,214,163),[i,t]),y=d.useMemo(()=>i.icon(t,"big"),[i,t]),[w,b]=d.useMemo(()=>fj(t.name),[t.name]);return o.jsx(o.Fragment,{children:t.id==="/wx-filemanager-parent-link"?f!=="search"?o.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:o.jsxs("div",{className:`wx-GAOa4kDV wx-back ${t.navigation?"wx-selected":""}`,"data-id":za("/wx-filemanager-parent-link"),children:[o.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),o.jsx("span",{children:r("Back to parent folder")})]})}):null:o.jsxs("div",{className:`wx-GAOa4kDV wx-item ${h?.length&&h.indexOf(t.id)>=0?"wx-selected":""}`,"data-id":za(t.id),children:[g?o.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:o.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:r("A miniature file preview"),src:g})}):y?o.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:o.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:y})}):o.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:o.jsx("i",{className:`wx-GAOa4kDV wxi-${t.type}`})}),t.type==="folder"?o.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[o.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[o.jsx("span",{className:"wx-GAOa4kDV wx-type",children:r("Folder")}),o.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[o.jsx("span",{children:w}),o.jsx("span",{children:b})]})]}),o.jsx("div",{"data-action-id":za(t.id),className:"wx-GAOa4kDV wx-more",children:o.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):o.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[o.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:o.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[o.jsx("span",{children:w}),o.jsx("span",{children:b})]})}),o.jsx("div",{"data-action-id":za(t.id),className:"wx-GAOa4kDV wx-more",children:o.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function o0(){const t=d.useContext($a),n=d.useContext(Ua.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),[i]=Vs(t,"panels"),l=Lt(t,"activePanel"),u=Lt(t,"mode"),f=i[l]._files,h=i[l].selected,g=i[l].path,y=i[l]._crumbs,w=i[l]._selectNavigation,b=d.useCallback((T,P)=>{const U=P&&(P.ctrlKey||P.metaKey),F=P&&P.shiftKey;if(T==="/wx-filemanager-parent-link"){if(h.length&&(U||F))return;t.exec("select-file",{type:"navigation"});return}let Y=T==="body"&&P?null:T;const D=P.target.className.indexOf("wx-more")!==-1||P.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{t.exec("select-file",{id:Y,toggle:U&&!D,range:F&&!D,panel:l})},1)},[t,h,l]),x=d.useCallback(()=>{y.length>1&&t.exec("set-path",{id:y[y.length-2].id,panel:l,selected:[y[y.length-1].id]})},[t,y,l]),M=d.useCallback(T=>{if(T==="/wx-filemanager-parent-link")return x();u==="search"&&t.exec("filter-files",{text:""});const P=f.find(U=>U.id===T);P&&(P.type=="folder"?t.exec("set-path",{id:P.id,panel:l}):t.exec("open-file",{id:P.id}))},[t,x,u,f,l]),k=d.useCallback((T,P)=>{(!h?.length||!h.filter(U=>U?.id===T).length>0)&&b(T,P)},[h,b]),N=d.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:r("Back to parent folder"),navigation:w},...f]:f,[g,r,w,f]),E=d.useRef(null),I=d.useRef();return d.useEffect(()=>{E.current&&(I.current?(I.current.click=b,I.current._dblclick=M,I.current.context=k):(I.current={click:b,dblclick:T=>I.current._dblclick(T),_dblclick:M,context:k},Cd(E.current,I.current)))},[b,M,k]),u=="search"&&!N.length?o.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:o.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:r("Looks like nothing is here")})}):o.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(g!=="/"&&u!=="search"?" wx-has-back-link":"")),"data-id":za("body"),ref:E,children:N.map(T=>o.jsx(mj,{item:T},T.id))})}function du({name:t="",spin:n=!1,onClick:r}){return o.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${t} ${n?"wx-spin":""} ${r?"wx-clickable":""}`,onClick:()=>{r&&r()}})}function pj(){const t=d.useContext(Ua.i18n).getGroup("filemanager"),n=d.useContext($a),r=Lt(n,"activePanel"),[i]=Vs(n,"panels"),l=d.useMemo(()=>i[r]._crumbs,[i,r]);function u(){n.exec("filter-files",{text:""})}return o.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[o.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[o.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:o.jsx(du,{name:"angle-left",onClick:u})}),o.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[t("Search results in")," ",Array.isArray(l)&&l.map((f,h)=>o.jsxs(d.Fragment,{children:[h?"/":null,f.id=="/"?t(f.name):f.name]},h))]})]}),o.jsx(o0,{})]})}function Mg({narrowMode:t,extraInfo:n}){const r=d.useContext($a),{preview:i,icon:l}=r.templates,u=d.useContext(Ua.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>gd("%D, %d %F %Y, %H:%i",u.getRaw().calendar),[u]),[g,y]=Vs(r,"panels"),w=Lt(r,"activePanel"),b=Lt(r,"preview"),x=Lt(r,"search"),M=d.useMemo(()=>{const D=g&&w!=null&&g[w]?._selected?.length||0;return x&&!D},[x,y,w]),k=d.useMemo(()=>{const D=g&&w!=null?g[w]:null;return D?M?D._files:D._selected:[]},[M,y,w]),N=d.useCallback((D,K)=>(D?`${D} ${f(D>1?"folders":"folder")} `:"")+(K?`${K} ${f(K>1?"files":"file")}`:""),[f]),E=d.useCallback(()=>{r.exec("show-preview",{mode:!b})},[r,b]),I=d.useCallback(D=>D.type==="folder"?f("Folder"):D.ext||f("Unknown file"),[f]),T=d.useMemo(()=>{let D,K,ne,q,O,W,ce,$;if(k.length===1&&!M){K=k[0],D=K.name;const ee=i(K,400,500);ee?(ne=ee,q=""):(q=l(K,"big"),ne=""),O=K.type!=="folder"}else{if(K=O=null,D="",k.length){let ee=0,B=0,L=0,oe=[],be;k.forEach(me=>{typeof me.size>"u"&&(be=!0,ee=void 0),be||(ee+=me.size),oe.push(I(me)),me.type==="folder"?B++:L++});const H=new Set(oe);W=H.size>1?f("multiple"):[...H][0],ce=N(B,L),$=ee,M||(D=f("Multiple files"))}q=l({type:M?"search":k.length?"multiple":"none"},"big"),ne=""}return{name:D,item:K,previewSrc:ne,iconSrc:q,showDownloadIcon:O,type:W,totalCount:ce,totalSize:$}},[k,M,i,l,f,I,N]),P=d.useCallback(()=>{r.exec("download-file",{id:k[0].id})},[r,k]),U=d.useCallback(async D=>{if(!n||!D)return null;try{return await n(D)}catch(K){return console.log(K),null}},[n]),[F,Y]=d.useState(null);return d.useEffect(()=>{let D=!1;return Y(null),Promise.resolve(U(T.item)).then(K=>{D||Y(K)}).catch(()=>{D||Y(null)}),()=>{D=!0}},[U,T.item]),o.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:k&&k.length?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[o.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[o.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),o.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[T.showDownloadIcon?o.jsx(du,{name:"download",onClick:P}):null,t?o.jsx(du,{name:"close",onClick:E}):null]})]}),T.previewSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:o.jsx("img",{src:T.previewSrc,alt:f("A miniature file preview")})}):T.iconSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:o.jsx("img",{src:T.iconSrc,alt:f("A miniature file preview")})}):o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:T.item?o.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${T.item.type}`}):o.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${M?"search":"file-multiple-outline"}`})})]}),o.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[o.jsx("div",{className:"wx-O0BTtRrH wx-title",children:f(M?"Found":"Information")}),o.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[T.item?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:I(T.item)}),typeof T.item.size<"u"?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:tm(T.item.size)})]}):null,o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Date")}),o.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(T.item.date)," "]})]}):o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Count")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.totalCount}),o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.type}),typeof T.totalSize<"u"?o.jsxs(o.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:tm(T.totalSize)})]}):null]}),F?Object.entries(F).map(([D,K])=>o.jsxs(kv.Fragment,{children:[o.jsx("span",{className:"wx-O0BTtRrH wx-name",children:D}),o.jsx("span",{className:"wx-O0BTtRrH wx-value",children:K})]},D)):null]})]})]}):o.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[o.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[o.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),o.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:t?o.jsx(du,{name:"close",onClick:E}):null})]}),o.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:o.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[T.previewSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:o.jsx("img",{src:T.previewSrc,alt:f("A miniature file preview")})}):T.iconSrc?o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:o.jsx("img",{src:T.iconSrc,alt:f("A miniature file preview")})}):o.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:o.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${M?"search":"message-question-outline"}`})}),o.jsx("span",{className:"wx-O0BTtRrH wx-text",children:M?"":f("Select file or folder to view details")})]})})]})})}function l0({panel:t}){const n=d.useContext($a),r=d.useContext(Ua.i18n),i=d.useMemo(()=>r.getGroup("filemanager"),[r]),[l,u]=Vs(n,"panels"),f=d.useMemo(()=>l[t]._files,[u,t]),h=d.useMemo(()=>l[t]._crumbs||[],[u,t]);function g(k){const N=Gv(k,h);n.exec("set-path",{id:k,panel:t,...N&&{selected:[N]}})}const[y,w]=d.useState(null);d.useEffect(()=>{f&&w(null)},[f]);function b(){w(!0),n.exec("request-data",{id:h[h.length-1].id}),setTimeout(()=>{w(null)},5e3)}const x=d.useRef(null),M=d.useRef();return d.useEffect(()=>{M.current?M.current.click=g:(M.current={click:g},Cd(x.current,M.current))},[g]),o.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:x,children:[o.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:o.jsx(du,{name:"refresh",spin:!!y,onClick:b})}),h.map((k,N)=>o.jsxs(kv.Fragment,{children:[N?o.jsx(du,{name:"angle-right"}):null,o.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":za(k.id),"data-menu-ignore":"true",children:k.id=="/"?i(k.name):k.name})]},N))]})}function hj({row:t}){const n=d.useContext(Ua.i18n),[r]=d.useState(()=>n.getGroup("filemanager")),i=d.useContext($a).templates,[l]=d.useState(()=>i.icon(t,"small"));return o.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:t.id==="/wx-filemanager-parent-link"?o.jsxs(o.Fragment,{children:[o.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),o.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",r("Back to parent folder")]})]}):o.jsxs(o.Fragment,{children:[l?o.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:l,height:"24px",width:"24px"}):o.jsx("i",{className:`wx-qgAqG6sL wxi-${t.type}`}),o.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",t.name," "]})]})})}function c0({children:t}){const n=d.useContext($a),r=Lt(n,"activePanel"),i=d.useContext(Qv),l=d.useRef(null);let u=d.useRef({});return u.current.drop=()=>{const f=l.current,h=yN(f,"data-panel");h&&h!=r&&n.exec("set-active-panel",{panel:h*1})},u.current.dragEnter=()=>{const f=l.current;f&&f.classList.toggle("wx-active")},u.current.dragLeave=()=>{const f=l.current;f&&f.classList.toggle("wx-active")},d.useEffect(()=>{const f=l.current;return i.droparea(f,u.current)},[]),o.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:l,children:t})}function vv({panel:t,active:n=!1,onClick:r,onContextMenu:i}){const l=d.useContext($a),u=d.useContext(Ua.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>gd("%d %M %Y",u.getRaw().calendar),[u]),[g]=Vs(l,"panels"),y=g[t].selected,w=g[t].path,b=g[t]._crumbs,x=g[t]._sorts,M=g[t]._selectNavigation,k=g[t]._files,N=d.useMemo(()=>[{id:"name",header:f("Name"),flexgrow:3,sort:!0,resize:!0,cell:hj},{id:"size",header:f("Size"),width:100,sort:!0,resize:!0,template:W=>typeof W=="number"?tm(W):""},{id:"date",header:f("Date"),width:120,sort:!0,resize:!0,template:W=>W?h(W):""}],[f,h]),E=d.useRef(null),I=d.useRef(null),T=d.useMemo(()=>M?["/wx-filemanager-parent-link"]:[...y],[M,y]);function P(W,ce){if(ce&&ce.target&&ce.target.className&&ce.target.className.indexOf("wx-grip")!==-1)return;const $=ce&&(ce.ctrlKey||ce.metaKey),ee=ce&&ce.shiftKey;if(W==="/wx-filemanager-parent-link"){if(y.length&&($||ee))return;l.exec("select-file",{type:"navigation"});return}let B=W==="body"&&ce?null:W;!E.current&&!I.current?l.exec("select-file",{id:B,toggle:$,range:ee,panel:t}):(E.current=null,I.current=null)}function U(){b.length>1&&l.exec("set-path",{id:b[b.length-2].id,panel:t,selected:[b[b.length-1].id]})}function F(W){if(W==="/wx-filemanager-parent-link")return U();const ce=k.find($=>$.id===W);ce&&(ce.type==="folder"?l.exec("set-path",{id:ce.id,panel:t}):l.exec("open-file",{id:ce.id}))}function Y(W){const ce=W.key,$=x[w];let ee=$?"asc":"desc";$&&$.key===ce&&(ee=$.order==="asc"?"desc":"asc"),l.exec("sort-files",{key:ce,order:ee,panel:t,path:w})}function D(W){W.intercept("sort-rows",ce=>(E.current=!0,Y(ce),!1)),W.intercept("select-row",()=>!1),W.on("resize-column",()=>I.current=!0),W.intercept("hotkey",()=>!1)}const K=d.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:f("Back to parent folder")},...k]:k,[w,k,f]),ne=d.useMemo(()=>{if(K&&x&&x[w]){const{key:W,order:ce}=x[w];return{[W]:{order:ce}}}},[K,x,w]),q=d.useRef(null),O=d.useRef();return d.useEffect(()=>{O.current?(O.current.click=P,O.current._dblclick=F):(O.current={click:P,dblclick:W=>O.current._dblclick(W),_dblclick:F},Cd(q.current,O.current))},[P,F]),o.jsxs("div",{onClick:r,onContextMenu:i,className:"wx-SSaVhET7 wx-wrapper",children:[o.jsx(l0,{panel:t}),o.jsx("div",{"data-id":za("body"),className:`wx-SSaVhET7 wx-list ${n?"wx-active":""}`,ref:q,children:o.jsx(c0,{children:o.jsx(uj,{init:D,data:K,columns:N,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:ne})})})]})}function gj(){const t=d.useContext($a),n=Lt(t,"activePanel");function r(i){t.exec("set-active-panel",{panel:i})}return o.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":za("body"),children:[o.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:o.jsx(vv,{panel:0,active:n==0,onClick:()=>r(0),onContextMenu:()=>r(0)})}),o.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:o.jsx(vv,{panel:1,active:n==1,onClick:()=>r(1),onContextMenu:()=>r(1)})})]})}function u0({folderIcon:t=!1,folder:n={}}){const r=d.useContext($a),[i,l]=Vs(r,"panels"),u=Lt(r,"activePanel"),f=d.useMemo(()=>i[u].path,[l,u]),h=d.useContext(Ua.i18n),g=d.useMemo(()=>h.getGroup("filemanager"),[h]),y=d.useMemo(()=>!!n.data?.find(M=>M.type==="folder"),[n]),w=d.useMemo(()=>n.id=="/"?g(n.name):n.name,[n,g]),b=d.useMemo(()=>n.$level>1?(n.$level-1)*20:0,[n]),x=n.open;return o.jsxs(o.Fragment,{children:[o.jsxs("li",{"data-id":za(n.id),className:`wx-NYfhvGIt wx-folder${f===n.id?" wx-selected":""}`,style:{paddingLeft:`${b}px`},children:[y?o.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${x?"angle-down":"angle-right"}`,"data-action":"toggle"}):o.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),o.jsx("i",{className:"wx-NYfhvGIt "+(t||"wxi-folder")}),o.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",w," "]})]}),x&&n.data&&n.data.length&&y?o.jsx(o.Fragment,{children:n.data.map(M=>M.type==="folder"?o.jsx(u0,{folder:M},M.id):null)}):null]})}function vj(){const t=d.useContext($a),[n,r]=Vs(t,"data"),[i,l]=Vs(t,"panels"),u=Lt(t,"activePanel"),f=d.useMemo(()=>i[u]._crumbs,[l,u]),h=d.useCallback(M=>{t.exec("open-tree-folder",{id:M,mode:!n.byId(M).open})},[t,r]),g=d.useCallback(M=>{const k=Gv(M,f);t.exec("set-path",{id:M,panel:u,...k&&{selected:[k]}})},[t,f,u]),[y,w]=d.useState([]);d.useEffect(()=>{w(n.byId(0).data)},[r]);const b=d.useRef(null),x=d.useRef();return d.useEffect(()=>{x.current?(x.current.click=g,x.current.toggle=h):(x.current={click:g,toggle:h},Cd(b.current,x.current))},[g,h]),o.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(M=>M.type==="folder"?o.jsx(u0,{folder:M},M.id):null)})}function yj(){const t=d.useContext($a),n=d.useContext(Ua.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),i=Lt(t,"drive"),l=i?i.used:"",u=i?i.total:"";return l&&u?o.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[o.jsx("progress",{value:l,max:u,className:"wx-DetSyKGG wx-progress"}),o.jsxs("p",{children:[tm(l)," ",r("of")," ",tm(u)," ",r("used")]})]}):null}function bj({option:t}){const n=d.useContext(Ua.i18n).getGroup("filemanager"),r=d.useContext(Qv),i=d.useCallback(()=>{r.open({})},[r]);return o.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:i,children:o.jsx("span",{children:n(t.text)})})}function wj({readonly:t,menuOptions:n}){const r=d.useContext(Ua.i18n).getGroup("filemanager"),{showPrompt:i}=d.useContext(Kv);d.useEffect(()=>{OT("upload",bj)},[]);function l({action:f}){f&&(f.id==="add-file"?i({item:{type:"file",size:0,date:new Date},add:!0}):f.id==="add-folder"&&i({item:{type:"folder",date:new Date},add:!0}))}const u=d.useMemo(()=>n("add").map(f=>(f.text=r(f.text),f)),[n,r]);return o.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!t&&o.jsx("div",{className:"wx-FlucfALM wx-button",children:o.jsx(BT,{options:u,at:"bottom-fit",onClick:l,children:o.jsx(Kf,{type:"primary block",children:r("Add New")})})}),o.jsx("div",{className:"wx-FlucfALM wx-tree",children:o.jsx(vj,{})}),o.jsx(yj,{})]})}function xj({value:t="",onSearch:n}){const[r,i]=qS(t),l=d.useContext(Ua.i18n).getGroup("filemanager"),u=d.useRef(null),f=d.useMemo(()=>r!==""?"wxi-close":"wxi-search",[r]);function h(y){const w=y.target.value;i(w),n&&n({value:w})}function g(){i(""),u.current&&u.current.focus(),n&&n({value:""})}return o.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[o.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${f}`,onClick:g}),o.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:u,value:r,onInput:h,placeholder:l("Search")})]})}function Sj({narrowMode:t=!1,onShowTree:n}){const r=d.useContext($a),i=d.useContext(Ua.i18n).getGroup("filemanager"),l=Lt(r,"mode"),u=Lt(r,"preview"),f=Lt(r,"search"),h=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function g({value:b}){r.exec("set-mode",{mode:b})}function y(b){b.preventDefault(),r.exec("show-preview",{mode:!u})}function w(b){r.exec("filter-files",{text:b.value})}return o.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[o.jsxs("div",{className:"wx-5PZQQztG wx-left "+(t?"wx-left-narrow":""),children:[t?l==="panels"||l==="search"?null:o.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":za("toggle-tree"),children:o.jsx(du,{onClick:()=>n&&n(),name:"subtask"})}):o.jsx("div",{className:"wx-5PZQQztG wx-name",children:i("Files")}),o.jsx(xj,{onSearch:w,value:f})]}),o.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[t?null:o.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:o.jsx(fT,{onClick:y,value:u,children:o.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),o.jsx("div",{className:"wx-5PZQQztG wx-modes",children:o.jsx(iT,{value:l,options:h,onChange:g})})]})]})}function Cj(){const t=d.useContext($a),n=Lt(t,"activePanel");return o.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[o.jsx(l0,{panel:n}),o.jsx(c0,{children:o.jsx(o0,{})})]})}function kj({readonly:t=!1,menuOptions:n,extraInfo:r}){const i=d.useRef(null),l=d.useRef(null),[u,f]=d.useState(void 0),[h,g]=d.useState(void 0),[y,w]=d.useState(!1),b=XS(),x=d.useContext($a),{showPrompt:M,showConfirm:k}=d.useContext(Kv),N=d.useContext(Ua.i18n),E=d.useMemo(()=>N.getGroup("filemanager"),[N]),I=Lt(x,"mode"),T=Lt(x,"preview"),P=Lt(x,"activePanel"),[U,F]=Vs(x,"panels"),Y=d.useMemo(()=>(U&&P!=null?U[P]:null)?.selected??[],[F,P]),D=d.useMemo(()=>(U&&P!=null?U[P]:null)?.path,[F,P]),[K,ne]=d.useState([]);d.useEffect(()=>{const H=i.current;if(!H)return;const me=new ResizeObserver(ue=>{const Ce=ue[0]?.borderBoxSize?.[0]?.inlineSize;typeof Ce=="number"&&g(Ce<768)});return me.observe(H),()=>{me.disconnect()}},[]);const q=d.useCallback(()=>{w(H=>!H)},[]),O=d.useCallback(H=>{h&&em(H)!=="toggle-tree"&&w(!1)},[h]);d.useEffect(()=>{const H=l.current;if(H)return go(H,O).destroy},[O]),d.useEffect(()=>{const H=l.current;if(!H)return;const me=new ResizeObserver(()=>{H&&f(H.clientWidth)});return me.observe(H),H&&f(H.clientWidth),()=>{me.disconnect()}},[]);const W=d.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),ce=d.useCallback(H=>{let me=h?[W]:[];return H==="file"&&(me=[...me,...n().filter(ue=>ue.id==="download")]),me},[h,W,n]),$=d.useRef(null),ee=d.useCallback((H,me,ue)=>{const Ce=ue?[me.id]:Y;switch(H){case"download":x.exec("download-file",{id:me.id});break;case"copy":case"move":$.current={action:H,ids:Ce};break;case"paste":$.current&&x.exec($.current.action==="copy"?"copy-files":"move-files",{ids:$.current.ids,target:me?.type==="folder"?me.id:D});break;case"rename":M({item:me});break;case"delete":k({selected:Ce});break;case"preview":x.exec("show-preview",{mode:!T});break}},[x,Y,D,M,k,T]),B=d.useCallback(()=>U?.[P],[U,P]);d.useEffect(()=>{const H=i.current;if(!H)return;const me=NT(H,{api:x,menuOptions:t?ce:n,performAction:ee,getPanel:B});return()=>{typeof me=="function"?me():me&&typeof me.destroy=="function"&&me.destroy()}},[x,t,ce,n,ee,B]);const L=d.useCallback((H,me)=>{const ue=H?x.getFile(H):null,Ce=me.target.closest(".tree-item.folder");let Me;if(t)Me=ce(ue?.type);else{switch(H){case"body":Me=n(H);break;default:if(ue)if(!Ce&&Y.length>1)Me=h?[W,...n("multiselect")]:n("multiselect");else if(H==="/")Me=n("folder",ue).filter(Ne=>Ne.id==="paste");else{const Ne=n(ue.type,ue);Ne&&(Me=h?[W,...Ne]:Ne)}}I==="search"&&(Me=Me?.filter(Ne=>Ne.id!=="paste"))}if(ue?.id&&(!Y.length||!Y.some(Ne=>Ne===ue.id))&&!Ce&&x.exec("select-file",{id:ue.id}),Me?.length)return Me.forEach(Ne=>{Ce&&(Ne.hotkey=""),Ne.text&&(Ne.text=E(Ne.text)),Ne.hotkey&&(Ne.subtext=Ne.hotkey)}),ne(Me),ue||{}},[x,t,ce,n,Y,h,W,I,E]),oe=d.useCallback(H=>{const{action:me,context:ue}=H;me&&ee(me.id,ue,!me.hotkey)},[ee]);async function be(H){await Promise.resolve();const{name:me,size:ue}=H.file;x.exec("create-file",{file:{name:me,size:ue,date:new Date,file:H.file},parent:D})}return o.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:i,"data-menu-ignore":"false",children:h&&T?o.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:o.jsx(Mg,{narrowMode:h,extraInfo:r})}):o.jsxs(o.Fragment,{children:[o.jsx(Sj,{narrowMode:h,onShowTree:q}),o.jsx(zT,{dataKey:"id",at:"point",options:K,resolver:L,onClick:oe,children:o.jsxs(YS,{dataKey:"actionId",options:K,resolver:L,onClick:oe,children:[o.jsx(GT,{data:b,apiOnly:!0,uploadURL:be}),o.jsx(Qv.Provider,{value:b,children:o.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:I!=="panels"&&I!=="search"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",h?"wx-sidebar-narrow":"",y?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:l,children:o.jsx(wj,{readonly:t,menuOptions:n})}),o.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${u||0}px - 10px)`},children:[o.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,"data-id":za("body"),children:I==="table"?o.jsx(vv,{panel:P}):o.jsx(Cj,{})}),T?o.jsx("div",{className:"wx-RJbNonjJ wx-info",children:o.jsx(Mg,{extraInfo:r})}):null]})]}):o.jsxs(o.Fragment,{children:[o.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:I==="panels"?o.jsx(gj,{}):o.jsx(pj,{})}),T?o.jsx("div",{className:"wx-RJbNonjJ wx-info",children:o.jsx(Mg,{extraInfo:r})}):null]})})})]})})]})})}const Mj=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join("");function Aj(t,n){const{type:r,ext:i}=t;if(r==="folder")return!1;let l;return r&&r!=="file"&&Bw[r]?l=r:i?l=Bw[i]?i:"file":l="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${n}/${l}.svg`}const Nj=d.forwardRef(function(t,n){const{data:r=[],mode:i="cards",drive:l=null,preview:u=!1,panels:f=null,activePanel:h=0,readonly:g=!1,menuOptions:y=kT,extraInfo:w=null,init:b=null,icons:x=Aj,previews:M=null,...k}=t,N=d.useRef();N.current=k;const E=d.useMemo(()=>new CT(GS),[]),I=d.useMemo(()=>E.in,[E]),T=d.useRef(null);T.current===null&&(T.current=new BS((F,Y)=>{const D="on"+Mj(F);N.current&&N.current[D]&&N.current[D](Y)}),I.setNext(T.current));const P=d.useMemo(()=>({getState:E.getState.bind(E),getReactiveState:E.getReactive.bind(E),getStores:()=>({data:E}),exec:I.exec,setNext:F=>(T.current=T.current.setNext(F),T.current),intercept:I.intercept.bind(I),on:I.on.bind(I),detach:I.detach.bind(I),getFile:E.getFile.bind(E),serialize:E.serialize.bind(E),templates:{preview:M||(()=>null),icon:x==="simple"?(()=>null):x}}),[E,I]),U=d.useRef(0);return d.useEffect(()=>{if(!U.current)b&&b(P);else{const F=E.getState();E.init({data:r,mode:i,drive:l,preview:u,panels:f||F.panels||[],activePanel:h})}U.current++},[E,r,i,l,u,f,h,b,P]),U.current===0&&E.init({data:r,mode:i,drive:l,preview:u,panels:f||[],activePanel:h}),d.useImperativeHandle(n,()=>({...P}),[P]),o.jsx($a.Provider,{value:P,children:o.jsx(qv,{words:Wv,optional:!0,children:o.jsx(dj,{children:o.jsx(kj,{readonly:g,menuOptions:y,extraInfo:w})})})})});function Tj({fonts:t=!0,children:n}){return n?o.jsx(Mw,{fonts:t,children:n}):o.jsx(Mw,{fonts:t})}Fv(Yr);function Yv(t,n){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Hub ${n} response.`);return t}function sm(t,n,r){const i=Yv(t,r);if(!Array.isArray(i[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an array.`);return i[n]}function Rj(t,n,r){const i=Yv(t,r);if(!i[n]||typeof i[n]!="object"||Array.isArray(i[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an object.`);return i[n]}async function jj(t,n=!1){return sm(await tt(`/api/remote/filesystem/roots${n?"?refresh=1":""}`,void 0,t),"roots","filesystem roots")}async function Ag(t,n){const r=await tt(`/api/remote/filesystem/entries?id=${encodeURIComponent(t)}`,void 0,n);return{folder:Rj(r,"folder","filesystem entries"),entries:sm(r,"entries","filesystem entries")}}async function Ej(t,n){return tt("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:t})},n)}async function Dj(t,n,r,i){return tt("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:t,deviceIds:n,remoteDirectory:r})},i)}async function Ij(t,n=!1){const r=await tt(`/api/remote/files/jobs?active=${n?"1":"0"}`,void 0,t);return{jobs:sm(r,"jobs","file transfer jobs")}}async function Lj(t,n){return tt(`/api/remote/files/jobs/${encodeURIComponent(t)}`,void 0,n)}async function _j(t,n){return tt(`/api/remote/files/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"},n)}async function zw(t){return sm(await tt("/api/remote/filesystem/shared-folders",void 0,t),"folders","shared folders")}async function Pj(t,n){return tt("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:t})},n)}async function Fj(t,n,r){return tt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)},r)}async function Oj(t,n){return tt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function Hj(t,n,r,i){const l=await tt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:n,remoteDirectory:r})},i),u=Yv(l,"shared folder sync");return{ok:u.ok===!0,jobs:sm(l,"jobs","shared folder sync"),files:Number(u.files||0),totalBytes:Number(u.totalBytes||0)}}function Bj(t){return{id:String(t.id),parentId:t.parent,name:t.name,type:t.type==="file"?"file":"folder",size:Number(t.size||0),modifiedAt:t.date?.toISOString()||null,displayPath:String(t.displayPath||t.name),hasChildren:t.lazy===!0||!!t.data?.length,locked:t.locked===!0}}function $w(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,i=0;for(;r>=1024&&i<n.length-1;)r/=1024,i+=1;return`${r.toFixed(i===0||r>=100?0:1)} ${n[i]}`}function Lp(t){return t.driveType==="network"?"network":t.driveType==="removable"?"removable":"local"}function zj(t){const n=t.filter(r=>Lp(r)==="local");return n.find(r=>/\bC:/i.test(`${r.name} ${r.displayPath||""}`))||n[0]||t[0]||null}function $j({hubUrl:t,roots:n,loading:r,error:i,onRefreshRoots:l,onImportFiles:u,onImportFolder:f,onSelectionChange:h,onShareItem:g,onAddSyncFolder:y,onNotice:w}){const b=d.useRef(null),x=d.useRef("/"),M=d.useRef(0),k=d.useRef([]),N=d.useRef(new Map),[E,I]=d.useState(null),[T,P]=d.useState([]),[U,F]=d.useState([]),[Y,D]=d.useState(0),[K,ne]=d.useState(null),[q,O]=d.useState(!1),[W,ce]=d.useState(""),[$,ee]=d.useState(new Set),B=n.find(xe=>xe.id===E)||null,L=T[T.length-1]||null,oe=B?L?.svarPath||`/${B.name}`:null,be=oe;d.useEffect(()=>{k.current=T,x.current=be||"/"},[be,T]);const H=d.useMemo(()=>(N.current.clear(),!B||!be||T.length===0?[]:(T.forEach(xe=>N.current.set(xe.svarPath,xe.hubId)),[...T.map((xe,he)=>({id:xe.svarPath,parent:he===0?"/":T[he-1].svarPath,type:"folder",name:xe.name,date:xe.modifiedAt?new Date(xe.modifiedAt):void 0,lazy:!1})),...U.map(xe=>{const he=`${be}/${xe.name}`;return N.current.set(he,xe.id),{id:he,parent:be,name:xe.name,type:xe.type==="file"?"file":"folder",...xe.type==="file"?{size:xe.size}:{},date:xe.modifiedAt?new Date(xe.modifiedAt):void 0,lazy:xe.type!=="file"&&xe.hasChildren===!0,displayPath:xe.displayPath,locked:xe.locked,driveType:xe.driveType,totalBytes:xe.totalBytes,freeBytes:xe.freeBytes}})])),[B,U,be,T]),me=xe=>N.current.get(String(xe))||String(xe),ue=xe=>Bj({...xe,id:me(String(xe.id)),parent:me(String(xe.parent))}),Ce=async(xe,he)=>{const pe=xe[xe.length-1];if(!pe)return;const Ae=++M.current;O(!0),ce("");try{const Se=await Ag(pe.hubId,t);if(Ae!==M.current)return;if(!Array.isArray(Se.entries))throw new Error("Invalid Hub filesystem entries response.");const Pe={...pe,displayPath:Se.folder.displayPath||pe.displayPath,modifiedAt:Se.folder.modifiedAt||pe.modifiedAt},Qe=[...xe.slice(0,-1),Pe];k.current=Qe,P(Qe),F(Se.entries),D(Z=>Z+1)}catch(Se){if(Ae!==M.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:pe.hubId,error:Se}),ce(Se instanceof Error?`${he}: ${Se.message}`:`${he}: Unable to read this folder.`)}finally{Ae===M.current&&O(!1)}},Me=async xe=>{const he={svarPath:`/${xe.name}`,hubId:xe.id,name:xe.name,displayPath:xe.displayPath,modifiedAt:xe.modifiedAt},pe=++M.current;I(xe.id),k.current=[he],P([he]),x.current=he.svarPath,F([]),ce(""),O(!0),ne(xe.id),ee(Ae=>{const Se=new Set(Ae);return Se.delete(xe.id),Se});try{const Ae=await Ag(xe.id,t);if(pe!==M.current)return;if(!Array.isArray(Ae.entries))throw new Error("Invalid Hub filesystem entries response.");const Se={...he,displayPath:Ae.folder.displayPath||he.displayPath,modifiedAt:Ae.folder.modifiedAt||he.modifiedAt};k.current=[Se],P([Se]),F(Ae.entries),D(Pe=>Pe+1)}catch(Ae){if(pe!==M.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:xe.id,error:Ae}),ee(Se=>new Set(Se).add(xe.id)),ce(Ae instanceof Error?`${xe.name}: ${Ae.message}`:`${xe.name}: Unable to read this drive.`),w(Ae instanceof Error?`${xe.name}: ${Ae.message}`:`${xe.name}: Unable to read this drive.`)}finally{pe===M.current&&(ne(null),O(!1))}},Ne=xe=>{const he=k.current;xe<0||xe>=he.length||xe===he.length-1||Ce(he.slice(0,xe+1),he[xe].name)},He=(xe,he)=>{if(xe.type!=="folder")return;const pe=k.current,Ae=pe.findIndex(Pe=>Pe.svarPath===he);if(Ae<0)return;const Se={svarPath:`${he}/${xe.name}`,hubId:xe.id,name:xe.name,displayPath:xe.displayPath,modifiedAt:xe.modifiedAt};Ce([...pe.slice(0,Ae+1),Se],xe.name)},Ve=()=>Ne(k.current.length-2),ie=xe=>{if(xe.key!=="Enter"&&xe.code!=="Enter"&&xe.code!=="NumpadEnter"||xe.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const pe=b.current;if(!pe)return;const Ae=pe.getState().panels?.flatMap(Pe=>Pe.selected||[])||[];if(Ae.length!==1)return;const Se=pe.getFile(String(Ae[0]));Se?.type==="folder"&&(xe.preventDefault(),xe.stopPropagation(),He(ue(Se),String(Se.parent||x.current)))};d.useEffect(()=>{const xe=n.find(he=>he.id===E)||zj(n);if(ee(he=>new Set([...he].filter(pe=>n.some(Ae=>Ae.id===pe)))),!xe){I(null),k.current=[],P([]),F([]);return}Me(xe)},[n]);const Oe=xe=>{b.current=xe,xe.on("request-data",async({id:he})=>{const pe=String(he),Ae=me(pe);try{const Se=await Ag(Ae,t);if(!Array.isArray(Se.entries))throw new Error("Invalid Hub filesystem entries response.");const Pe=Se.entries.map(Qe=>{const Z=`${pe}/${Qe.name}`;return N.current.set(Z,Qe.id),{id:Z,parent:pe,name:Qe.name,type:Qe.type==="file"?"file":"folder",...Qe.type==="file"?{size:Qe.size}:{},date:Qe.modifiedAt?new Date(Qe.modifiedAt):void 0,lazy:Qe.type!=="file"&&Qe.hasChildren===!0,displayPath:Qe.displayPath,locked:Qe.locked,driveType:Qe.driveType,totalBytes:Qe.totalBytes,freeBytes:Qe.freeBytes}});await xe.exec("provide-data",{id:pe,data:Pe})}catch(Se){console.error("[LiveDesk FS] nested getEntries failed",{id:Ae,error:Se}),w(Se instanceof Error?Se.message:"Unable to read this folder.")}}),xe.intercept("set-path",({id:he})=>{const pe=String(he),Ae=k.current.findIndex(Pe=>Pe.svarPath===pe);if(Ae>=0)return Ne(Ae),!1;const Se=xe.getFile(pe);if(Se?.type==="folder")return He(ue(Se),String(Se.parent||x.current)),!1}),xe.intercept("open-file",()=>!1),xe.on("select-file",()=>{window.setTimeout(()=>{const Ae=(xe.getState().panels?.flatMap(Se=>Se.selected||[])||[]).map(Se=>xe.getFile(Se)).filter(Boolean).map(Se=>ue(Se));h(Ae.map(Se=>Se.id),Ae)},0)})},$e=(xe,he)=>{const pe=he?ue(he):null,Ae=()=>{const Se=pe?.type==="file"?String(he?.parent||x.current):String(he?.id||x.current);b.current?.exec("request-data",{id:Se})};return xe==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ae},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w("Select a file or folder to view its properties.")}]:xe==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(b.current?.getState().panels?.flatMap(Pe=>Pe.selected||[])||[]).forEach(Pe=>{const Qe=b.current?.getFile(Pe);Qe&&g(ue(Qe))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ae}]:pe?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(pe)},...pe.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(pe)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Rp(pe.displayPath||pe.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Ae},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${pe.name}
|
|
175
175
|
${pe.displayPath||""}`)}]:[]},qe=async()=>{try{await l()}catch(xe){w(xe instanceof Error?xe.message:"Unable to refresh Hub drives.")}},vt=[{id:"local",label:"Local drives",icon:su,roots:n.filter(xe=>Lp(xe)==="local")},{id:"removable",label:"Removable drives",icon:JC,roots:n.filter(xe=>Lp(xe)==="removable")},{id:"network",label:"Network drives",icon:Mv,roots:n.filter(xe=>Lp(xe)==="network")}];return o.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[o.jsxs("div",{className:"hub-file-explorer-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Hub file explorer"}),o.jsxs("strong",{children:[o.jsx(su,{size:16})," Browse files on this Hub"]})]}),o.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[o.jsx("button",{className:"icon-button",onClick:u,title:"Import files from this browser",type:"button",children:o.jsx(Px,{size:16})}),o.jsx("button",{className:"icon-button",onClick:f,title:"Import folder from this browser",type:"button",children:o.jsx(ek,{size:16})}),o.jsx("button",{className:"icon-button",onClick:()=>{qe()},title:"Refresh drives",type:"button",children:o.jsx(bd,{size:16})})]})]}),r?o.jsxs("div",{className:"hub-file-explorer-state",children:[o.jsx(su,{size:24}),o.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):i?o.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[o.jsx(Ci,{size:24}),o.jsx("strong",{children:i})]}):o.jsxs("div",{className:"hub-file-explorer-content",children:[o.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[o.jsxs("div",{className:"hub-drive-sidebar-title",children:[o.jsx(su,{size:15}),o.jsx("strong",{children:"This PC"})]}),vt.map(xe=>xe.roots.length>0&&o.jsxs("section",{className:"hub-drive-group",children:[o.jsxs("h3",{children:[o.jsx(xe.icon,{size:13}),xe.label]}),o.jsx("div",{className:"hub-drive-list",children:xe.roots.map(he=>{const pe=xe.icon,Ae=$.has(he.id)||he.locked===!0;return o.jsxs("button",{className:`hub-drive-item ${E===he.id?"active":""} ${Ae?"unavailable":""}`,onClick:()=>{Me(he)},"aria-pressed":E===he.id,type:"button",children:[o.jsx("span",{className:"hub-drive-item-icon",children:o.jsx(pe,{size:16})}),o.jsxs("span",{className:"hub-drive-item-copy",children:[o.jsx("strong",{children:he.name}),o.jsx("small",{children:he.displayPath||he.name}),o.jsxs("em",{children:[$w(he.freeBytes||0)," free / ",$w(he.totalBytes||0)]})]}),K===he.id?o.jsx(Si,{className:"hub-drive-item-status spin",size:15}):Ae?o.jsx(vb,{className:"hub-drive-item-status",size:15}):null]},he.id)})})]},xe.id)),n.length===0&&o.jsxs("div",{className:"hub-drive-sidebar-empty",children:[o.jsx(Ci,{size:17}),o.jsx("span",{children:"No drives available."})]})]}),o.jsxs("div",{className:"hub-file-explorer-browser",children:[o.jsxs("div",{className:"hub-file-explorer-navigation",children:[o.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:T.map((xe,he)=>o.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[he>0&&o.jsx(Av,{size:13,"aria-hidden":"true"}),o.jsx("button",{className:`hub-file-explorer-breadcrumb ${he===T.length-1?"current":""}`,onClick:()=>Ne(he),"aria-current":he===T.length-1?"location":void 0,type:"button",children:xe.name})]},xe.svarPath))}),o.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[q&&o.jsx(Si,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),o.jsx("button",{className:"icon-button",onClick:Ve,disabled:T.length<=1||q,title:"Back to parent folder",type:"button",children:o.jsx(jx,{size:16})})]})]}),W&&o.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[o.jsx(vb,{size:15}),o.jsx("span",{children:W})]}),o.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:ie,children:o.jsx(Tj,{fonts:!1,children:o.jsx(Nj,{data:H,panels:oe?[{path:oe,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Oe,icons:"simple",menuOptions:$e},`${B?.id||"no-root"}:${Y}`)})})]})]})]})}class Uj extends d.Component{state={error:null};static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,r){console.error("[LiveDesk] Share Files runtime error",n,r.componentStack)}render(){return this.state.error?o.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[o.jsx(Qp,{size:24}),o.jsx("strong",{children:"Share Files could not be opened."}),o.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),o.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[o.jsx(bd,{size:15})," Retry"]})]}):this.props.children}}function qj(t){return t.deviceName||t.hostname||t.deviceId}function Wj({devices:t,mode:n,selectedIds:r,onModeChange:i,onToggle:l}){const u=new Set(r);return o.jsxs("section",{className:"distribution-targets",children:[o.jsxs("div",{className:"file-share-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Target"}),o.jsx("strong",{children:n==="all"?`${t.length} connected`:`${r.length} selected`})]}),o.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[o.jsxs("button",{className:n==="all"?"active":"",onClick:()=>i("all"),type:"button",children:[o.jsx(Xf,{size:14})," All connected"]}),o.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>i("selected"),type:"button",children:[o.jsx(Ta,{size:14})," Selected"]})]})]}),o.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:t.length===0?o.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):t.map(f=>{const h=n==="all"||u.has(f.deviceId);return o.jsxs("label",{className:`file-share-device-option ${h?"selected":""}`,children:[o.jsx("input",{type:"checkbox",checked:h,disabled:n==="all",onChange:()=>l(f.deviceId)}),o.jsx(Ta,{size:20,"aria-hidden":"true"}),o.jsxs("span",{children:[o.jsx("strong",{children:qj(f)}),o.jsxs("small",{children:["Slot ",f.slotNumber?String(f.slotNumber).padStart(3,"0"):"-"," / ",f.platform||"unknown OS"]})]}),o.jsx(Ba,{size:17,"aria-hidden":"true"})]},f.deviceId)})})]})}function Gj(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,i=0;for(;r>=1024&&i<n.length-1;)r/=1024,i+=1;return`${r.toFixed(i===0||r>=100?0:1)} ${n[i]}`}function Vj({folders:t,loading:n,busy:r,canSync:i,onSyncAll:l,onSync:u,onToggleAuto:f,onRemove:h,onAdd:g}){return o.jsxs("section",{className:"file-share-sync-panel",children:[o.jsxs("div",{className:"file-share-section-heading",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Hub folders"}),o.jsx("strong",{children:"Continuous sync"})]}),o.jsxs("button",{className:"text-button compact",onClick:l,disabled:r||!i||t.length===0,type:"button",children:[o.jsx(Np,{size:15})," ",r?"Syncing":"Sync all"]})]}),n?o.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):t.length===0?o.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[o.jsx(Np,{size:28}),o.jsx("strong",{children:"Add a selected Hub folder"}),o.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):o.jsx("div",{className:"file-share-sync-list",children:t.map(y=>o.jsxs("article",{className:`file-share-sync-row state-${y.status}`,children:[o.jsx("div",{className:"file-share-sync-icon",children:o.jsx(Np,{size:19})}),o.jsxs("div",{className:"file-share-sync-info",children:[o.jsx("strong",{children:y.name}),o.jsx("span",{children:y.displayPath}),o.jsxs("small",{children:[y.fileCount," files / ",Gj(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${Gx(y.lastSyncedAt)} ago`:y.message||"Not synced yet"]})]}),o.jsxs("label",{className:"file-share-auto-sync",children:[o.jsx("input",{type:"checkbox",checked:y.autoSync,onChange:()=>f(y)}),o.jsx("span",{children:"Auto"})]}),o.jsxs("button",{className:"text-button compact",onClick:()=>u(y),disabled:r||!i||y.status==="syncing",type:"button",children:[o.jsx(bd,{size:14})," Sync now"]}),o.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:o.jsx(Fx,{size:15})})]},y.id))})]})}function Kj(t){const r=(t.targetMode==="all"?t.devices.map(i=>i.deviceId):t.selectedTargetIds).length>0;return o.jsxs("aside",{className:"file-share-distribution-panel",children:[o.jsxs("div",{className:"file-share-distribution-head",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Distribution"}),o.jsx("strong",{children:"Hub → Clients"})]}),o.jsx(Yf,{size:18})]}),o.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[o.jsx("button",{className:t.tab==="send"?"active":"",onClick:()=>t.onTabChange("send"),role:"tab","aria-selected":t.tab==="send",type:"button",children:"Send"}),o.jsx("button",{className:t.tab==="sync"?"active":"",onClick:()=>t.onTabChange("sync"),role:"tab","aria-selected":t.tab==="sync",type:"button",children:"Sync"})]}),t.tab==="send"?o.jsxs(o.Fragment,{children:[o.jsx(Wj,{devices:t.devices,mode:t.targetMode,selectedIds:t.selectedTargetIds,onModeChange:t.onTargetModeChange,onToggle:t.onTargetToggle}),o.jsxs("label",{className:"file-share-destination",children:[o.jsx("span",{children:"Destination folder"}),o.jsxs("div",{children:[o.jsx(pd,{size:15}),o.jsx("input",{value:t.remoteDirectory,onChange:i=>t.onRemoteDirectoryChange(i.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),o.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),o.jsxs("div",{className:"file-share-selection-summary",children:[o.jsx("span",{children:"Selected"}),o.jsx("strong",{children:t.selectedSummary})]}),o.jsxs("button",{className:"file-share-share-button",onClick:t.onShare,disabled:!t.canShare,type:"button",children:[o.jsx(Yf,{size:17})," Share selected"]}),o.jsxs("button",{className:"file-share-secondary-button",onClick:t.onAddSync,disabled:!t.canAddSync,type:"button",children:[o.jsx(pd,{size:16})," Add selected folder to Sync"]})]}):o.jsx(Vj,{folders:t.folders,loading:t.foldersLoading,busy:t.syncBusy,canSync:r,onSyncAll:t.onSyncAll,onSync:t.onSync,onToggleAuto:t.onToggleAuto,onRemove:t.onRemove,onAdd:t.onAddFolder})]})}function Qj(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,i=0;for(;r>=1024&&i<n.length-1;)r/=1024,i+=1;return`${r.toFixed(i===0||r>=100?0:1)} ${n[i]}`}function Uw(t){if(t.state==="completed")return 100;const n=t.totalBytes>0?Math.round(t.sentBytes/t.totalBytes*100):t.totalFiles>0?Math.round(t.completedFiles/t.totalFiles*100):0;return Math.max(0,Math.min(yv(t.state)?100:99,n))}function qw(t){return t.state==="scanning"?"Scanning selected Hub items":t.state==="queued"?"Preparing transfer":t.state==="sending"?`${t.completedFiles}/${t.totalFiles} · ${t.currentPath||"sending"}`:t.state==="completed"?`Sent ${t.totalFiles} file${t.totalFiles===1?"":"s"} to ${t.targetCount} Client${t.targetCount===1?"":"s"}`:t.state==="partially-failed"?`${t.failedTargets.length} Client${t.failedTargets.length===1?"":"s"} failed`:t.state==="cancelled"?"Transfer cancelled":t.error||"Transfer failed"}function yv(t){return["completed","partially-failed","failed","cancelled"].includes(t)}function Yj({hubUrl:t,devices:n,localFeatureAccess:r,upgradeNotice:i,remoteDirectory:l,onRemoteDirectoryChange:u,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,filePickerRef:w,folderPickerRef:b,onBrowserFileImport:x,onBrowserFolderImport:M,onNotice:k,onTransferChange:N}){const E=Array.isArray(n)?n:[],[I,T]=d.useState([]),[P,U]=d.useState(!0),[F,Y]=d.useState(""),[D,K]=d.useState([]),[ne,q]=d.useState([]),[O,W]=d.useState(null),[ce,$]=d.useState(!1),[ee,B]=d.useState([]),[L,oe]=d.useState(!0),[be,H]=d.useState(!1),[me,ue]=d.useState("send"),[Ce,Me]=d.useState([]),Ne=d.useRef(new Set),He=d.useRef(!1),Ve=d.useMemo(()=>f==="all"?E.map(Ee=>Ee.deviceId):h.filter(Ee=>E.some(Ge=>Ge.deviceId===Ee)),[E,h,f]),ie=Ce.find(Ee=>!yv(Ee.state)),Oe=ne.length===1&&ne[0].type==="folder"?ne[0]:null,$e=ne.length===0?"Select files or folders from the Hub explorer.":ce?"Calculating selection size...":O?`${O.files} files, ${O.folders} folders · ${Qj(O.totalBytes)}`:`${ne.length} item${ne.length===1?"":"s"} selected`,qe=Ee=>{N({id:Ee.jobId,state:Ee.state,progress:Uw(Ee),message:qw(Ee)})},vt=d.useCallback(async()=>{const Ee=await jj(t,!0);return T(Ee),Y(""),Ee},[t]),xe=async()=>{if(!He.current){He.current=!0;try{const Ge=(await Ij(t,!0)).jobs||[],ze=await Promise.all([...Ne.current].map(async nt=>{try{return await Lj(nt,t)}catch{return null}})),Ft=[...Ge,...ze.filter(Boolean)],Ze=[...new Map(Ft.map(nt=>[nt.jobId,nt])).values()];Me(Ze),Ze.forEach(qe),Ze.filter(nt=>yv(nt.state)).forEach(nt=>Ne.current.delete(nt.jobId))}catch{}finally{He.current=!1}}};d.useEffect(()=>{let Ee=!0;U(!0),Y(""),Promise.all([vt(),zw(t).then(ze=>{Ee&&B(ze)})]).catch(ze=>{Ee&&(Y(ze instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),k(ze instanceof Error?ze.message:"Hub file system is unavailable."))}).finally(()=>{Ee&&(U(!1),oe(!1))}),xe();const Ge=window.setInterval(()=>{xe()},800);return()=>{Ee=!1,window.clearInterval(Ge)}},[t,vt]),d.useEffect(()=>{if(D.length===0){W(null);return}let Ee=!1;return $(!0),Ej(D,t).then(Ge=>{Ee||W(Ge)}).catch(Ge=>{Ee||k(Ge instanceof Error?Ge.message:"Unable to calculate selected size.")}).finally(()=>{Ee||$(!1)}),()=>{Ee=!0}},[t,D.join("|")]);const he=(Ee,Ge)=>{K(Ee),q(Ge)},pe=Ee=>{Ee.forEach(Ge=>Ne.current.add(Ge.jobId)),Me(Ge=>[...new Map([...Ge,...Ee].map(ze=>[ze.jobId,ze])).values()]),Ee.forEach(qe)},Ae=async()=>{if(!r){k(i);return}if(D.length===0){k("Select files or folders from the Hub explorer.");return}if(Ve.length===0){k("Choose at least one connected Client.");return}if(ie){k("A Hub transfer is already running.");return}try{const Ee=await Dj(D,Ve,l.trim(),t);Ne.current.add(Ee.jobId),k("Hub transfer queued."),await xe()}catch(Ee){k(Ee instanceof Error?Ee.message:"Unable to start Hub transfer.")}},Se=async Ee=>{const Ge=Ee||Oe;if(!Ge||Ge.type!=="folder"){k("Select one folder to add it to Sync.");return}try{const ze=await Pj(Ge.id,t);B(Ft=>[...Ft.filter(Ze=>Ze.id!==ze.folder.id),ze.folder]),ue("sync"),k(`${Ge.name} is ready for Hub sync.`)}catch(ze){k(ze instanceof Error?ze.message:"Unable to add the Hub folder to Sync.")}},Pe=async Ee=>{if(Ve.length===0){k("Choose at least one connected Client.");return}H(!0),B(Ge=>Ge.map(ze=>ze.id===Ee.id?{...ze,status:"syncing"}:ze));try{const Ge=await Hj(Ee.id,Ve,l.trim(),t);pe(Ge.jobs||[]),k(Ge.jobs?.length?"Hub sync queued.":"No changed files to sync.");const ze=await zw(t);B(ze)}catch(Ge){k(Ge instanceof Error?Ge.message:"Unable to sync the Hub folder."),B(ze=>ze.map(Ft=>Ft.id===Ee.id?{...Ft,status:"error",message:"Sync failed"}:Ft))}finally{H(!1)}},Qe=async()=>{H(!0);try{for(const Ee of ee)await Pe(Ee)}finally{H(!1)}},Z=async Ee=>{try{const Ge=await Fj(Ee.id,{autoSync:!Ee.autoSync},t);B(ze=>ze.map(Ft=>Ft.id===Ee.id?Ge.folder:Ft))}catch(Ge){k(Ge instanceof Error?Ge.message:"Unable to update auto sync.")}},$t=async Ee=>{try{await Oj(Ee.id,t),B(Ge=>Ge.filter(ze=>ze.id!==Ee.id))}catch(Ge){k(Ge instanceof Error?Ge.message:"Unable to remove the sync folder.")}};return o.jsxs("section",{className:"livedesk-file-explorer",children:[o.jsx("input",{ref:w,className:"hidden-file-input",type:"file",multiple:!0,onChange:Ee=>{Ee.currentTarget.files&&x(Ee.currentTarget.files),Ee.currentTarget.value=""}}),o.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:Ee=>{Ee.currentTarget.files&&M(Ee.currentTarget.files),Ee.currentTarget.value=""}}),o.jsx("div",{className:"file-share-workspace",children:o.jsxs(Uj,{onRetry:()=>window.location.reload(),children:[o.jsx($j,{hubUrl:t,roots:I,loading:P,error:F,onRefreshRoots:vt,onImportFiles:()=>w.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:he,onShareItem:Ee=>{K([Ee.id]),q([Ee]),ue("send")},onAddSyncFolder:Ee=>{K([Ee.id]),q([Ee]),Se(Ee)},onNotice:k}),o.jsx(Kj,{devices:E,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:l,onRemoteDirectoryChange:u,selectedEntries:ne,selectedSummary:$e,canShare:r&&!ie&&D.length>0&&Ve.length>0&&!ce,onShare:()=>{Ae()},canAddSync:!!Oe,onAddSync:()=>{Se()},tab:me,onTabChange:ue,folders:ee,foldersLoading:L,syncBusy:be,onSyncAll:()=>{Qe()},onSync:Ee=>{Pe(Ee)},onToggleAuto:Ee=>{Z(Ee)},onRemove:Ee=>{$t(Ee)},onAddFolder:()=>{Se()}})]})}),ie&&o.jsx("footer",{className:"file-share-workspace-footer",children:o.jsxs("span",{children:[qw(ie)," · ",Uw(ie),"% ",o.jsx("button",{className:"icon-button",onClick:()=>{_j(ie.jobId,t).then(Ee=>{Me(Ge=>Ge.map(ze=>ze.jobId===Ee.jobId?Ee:ze)),qe(Ee)})},title:"Cancel transfer",type:"button",children:o.jsx(hr,{size:14})})]})})]})}const Xj=d.forwardRef(function({value:n,onChange:r,onSubmit:i,onOpenSuggestedTasks:l,suggestedOpen:u=!1,suggestedTaskCount:f,disabled:h=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:y=!1},w){return o.jsxs("form",{className:"agents-composer",onSubmit:b=>{b.preventDefault(),i()},children:[o.jsx("button",{className:`agents-suggested-trigger ${u?"active":""}`,type:"button","aria-label":f===void 0?"Open Suggested tasks":`Open Suggested tasks (${f} available)`,"aria-expanded":u,onClick:l,disabled:h,children:o.jsx(tk,{size:17})}),o.jsx("textarea",{ref:w,value:n,onChange:b=>r(b.target.value.slice(0,4e3)),placeholder:g,"aria-label":"Ask LiveDesk",rows:y?1:2,disabled:h}),o.jsxs("button",{className:"agents-run-button",type:"submit",disabled:h||!n.trim(),children:[h?o.jsx(Si,{className:"spin",size:16}):o.jsx(Yf,{size:16}),h?"Running":"Run"]})]})}),Zj=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Gp(t){return t.deviceName?.trim()||t.hostname?.trim()||t.deviceId}function Vp(t){return t.connected!==!0?!1:t.synthetic===!0?!0:!t.channels||t.channels.control===!0}function Jj(t){return t==="running"||t==="completed"||t==="failed"||t==="cancelled"?t:"queued"}function eE(t){switch(t){case"process.list":return"Process list";case"system.health":return"System health";case"gpu.status":return"GPU status";case"disk.status":return"Disk status";case"service.status":return"Service status";case"diagnostics.collect":return"Diagnostics";case"process.control":return"Process control";case"service.control":return"Service control";case"application.launch":return"Launch application";case"application.close":return"Close application";case"file.read":return"Read file";case"file.write":return"Write file";case"file.delete":return"Delete file";case"file.list":return"List directory";case"command.run":return"Run command";case"script.run":return"Run script";case"software.install":return"Install software";case"network.status":return"Network status";case"system.power":return"Power action";case"system.configure":return"System configuration";case"logs.collect":return"Collect logs"}}function tE(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Cs(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function bp(t){const n=Cs(t);return n===null?"":n<1024**2?`${Math.round(n/1024)}K`:n<1024**3?`${(n/1024**2).toFixed(0)}M`:`${(n/1024**3).toFixed(1)}G`}function nE(t){const n=Cs(t);return n===null?"":`${Math.round((n<=1?n:n/100)*100)}%`}function aE(t){return!t||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(t.trim())?"":t.trim()}function Kp(t,n){if(n.error)return n.error;const r=tE(n.data),i=aE(n.result||"");if(!r)return i||n.stage||n.status;if(t==="system.health"){const l=typeof r.machine=="string"?r.machine:"",u=bp(r.freeMemoryBytes),f=bp(r.totalMemoryBytes),h=Cs(r.totalMemoryBytes)&&Cs(r.freeMemoryBytes)!==null?`${Math.round(Cs(r.freeMemoryBytes)/Cs(r.totalMemoryBytes)*100)}% RAM free`:"";return[l,u&&f?`RAM ${u}/${f}`:"",h,typeof r.platform=="string"?r.platform:""].filter(Boolean).join(" · ")||i||n.status}if(t==="disk.status"){const l=typeof r.root=="string"?r.root:"",u=bp(r.freeBytes),f=Cs(r.totalBytes)&&Cs(r.freeBytes)!==null?`${Math.round(Cs(r.freeBytes)/Cs(r.totalBytes)*100)}% free`:"";return[l,u&&`${u} free`,f].filter(Boolean).join(" · ")||i||n.status}if(t==="gpu.status"){const l=typeof r.name=="string"&&r.name?r.name:"No GPU detected",u=nE(r.usageRatio),f=Cs(r.temperatureC)!==null?`${Math.round(Cs(r.temperatureC))}°C`:"",h=bp(r.freeMemoryBytes);return[l,u&&`GPU ${u}`,f,h&&`${h} free`].filter(Boolean).join(" · ")||i||n.status}if(t==="process.list"){const l=Cs(r.count);return l!==null?`${l} matching process${l===1?"":"es"}`:i||n.status}if(t==="network.status"){const l=Array.isArray(r.adapters)?r.adapters.length:null;return l!==null?`${l} active adapter${l===1?"":"s"}`:i||n.status}return i||n.stage||n.status}function Ww(t,n){const r=Kp(t,n);return n.status==="failed"||n.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${n.result||""} ${r}`)}function rE({state:t,operation:n}){const r=t.status==="completed"?fo:t.status==="failed"||t.status==="cancelled"?hr:t.status==="running"?Si:Ox,i=t.status==="running"?t.stage||"Working":t.status==="completed"?n?Kp(n,t):t.result||"Completed":t.status==="failed"?t.error||"Failed":t.status==="cancelled"?"Cancelled":"Queued";return o.jsxs("div",{className:`agent-target-row status-${t.status}`,"data-agent-target-id":t.deviceId,children:[o.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:o.jsx(r,{size:15})}),o.jsx("strong",{children:t.deviceName}),o.jsx("span",{className:"agent-target-state",children:t.status[0].toUpperCase()+t.status.slice(1)}),o.jsx("small",{children:i})]})}function sE({operation:t,states:n,status:r,onCancel:i,onRetry:l,busy:u=!1}){const f=["running","queued"].includes(r),[h,g]=d.useState(!1),[y,w]=d.useState("all"),b=d.useMemo(()=>({total:n.length,completed:n.filter(P=>P.status==="completed").length,failed:n.filter(P=>P.status==="failed").length,running:n.filter(P=>P.status==="running").length,queued:n.filter(P=>P.status==="queued").length,cancelled:n.filter(P=>P.status==="cancelled").length}),[n]),x=n.filter(P=>Ww(t,P)),M=x.filter(P=>P.status==="completed").length,k=b.failed>0,N=x.length>0,E=n.filter(P=>y==="issues"?Ww(t,P):y==="running"?P.status==="running"||P.status==="queued":y==="completed"?P.status==="completed":y==="failed"?P.status==="failed":!0),I=N&&!f||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),T=n.filter(P=>P.status==="completed").map(P=>Kp(t,P)).filter(Boolean).filter((P,U,F)=>F.indexOf(P)===U).slice(0,2);return o.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[o.jsxs("div",{className:"agent-task-head",children:[o.jsxs("div",{children:[o.jsx("span",{children:"LiveDesk Agent"}),o.jsx("strong",{children:eE(t)})]}),o.jsx("span",{className:`agent-task-status status-${N?"completed-with-failures":r}`,children:I})]}),o.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[o.jsxs("strong",{children:[b.total," targets"]}),o.jsxs("span",{className:"summary-completed",children:[b.completed," completed"]}),b.running>0&&o.jsxs("span",{className:"summary-running",children:[b.running," running"]}),b.queued>0&&o.jsxs("span",{children:[b.queued," queued"]}),k&&o.jsxs("span",{className:"summary-failed",children:[b.failed," failed"]}),M>0&&o.jsxs("span",{className:"summary-cancelled",children:[M," warning"]}),b.cancelled>0&&o.jsxs("span",{className:"summary-cancelled",children:[b.cancelled," cancelled"]})]}),T.length>0&&o.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[o.jsx("span",{children:"Result"}),T.join(" · ")]}),o.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:n.map((P,U)=>{const F=P.status==="completed"?"✓":P.status==="failed"?"×":P.status==="cancelled"?"!":P.status==="running"?"…":"·";return o.jsxs("span",{className:`agent-target-chip status-${P.status}`,title:`${P.deviceName}: ${Kp(t,P)}`,"aria-label":`${U+1}. ${P.deviceName}: ${P.status}`,children:[o.jsx("b",{children:String(U+1).padStart(2,"0")}),o.jsx("span",{children:F})]},P.deviceId)})}),n.length>0&&o.jsx("div",{className:"agent-task-details-toggle",children:o.jsxs("button",{type:"button",onClick:()=>g(P=>!P),"aria-expanded":h,children:[h?o.jsx(nk,{size:14}):o.jsx(Hx,{size:14}),h?"Hide details":"Show details"]})}),h&&o.jsxs("div",{className:"agent-task-details",children:[o.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(P=>o.jsx("button",{className:y===P?"active":"",onClick:()=>w(P),role:"tab","aria-selected":y===P,type:"button",children:P==="all"?"All":P==="issues"?"Issues only":P[0].toUpperCase()+P.slice(1)},P))}),o.jsx("div",{className:"agent-task-rows",children:E.length>0?E.map(P=>o.jsx(rE,{operation:t,state:P},P.deviceId)):o.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(f||k)&&o.jsxs("div",{className:"agent-task-actions",children:[f&&i&&o.jsxs("button",{onClick:i,disabled:u,type:"button",children:[o.jsx(ak,{size:14})," Cancel"]}),!f&&k&&l&&o.jsxs("button",{onClick:l,disabled:u,type:"button",children:[o.jsx($g,{size:14})," Retry failed"]})]})]})}function iE(t){try{return JSON.stringify(t,null,2).slice(0,6e3)}catch{return"{}"}}function oE({approval:t,busy:n=!1,onApprove:r,onReject:i}){return o.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[o.jsxs("div",{className:"agent-approval-head",children:[o.jsxs("div",{children:[o.jsx("span",{children:"Approval required"}),o.jsx("strong",{children:t.toolName})]}),o.jsx("span",{className:`agent-approval-risk risk-${t.risk}`,children:t.risk})]}),o.jsx("p",{children:t.description}),o.jsx("pre",{children:iE(t.arguments)}),o.jsxs("small",{children:["Permission: ",t.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),o.jsxs("div",{className:"agent-approval-actions",children:[o.jsxs("button",{className:"reject",disabled:n,onClick:i,type:"button",children:[o.jsx(hr,{size:14})," Reject"]}),o.jsxs("button",{disabled:n,onClick:()=>r("once"),type:"button",children:[o.jsx(fo,{size:14})," Once"]}),o.jsx("button",{disabled:n,onClick:()=>r("same-action-this-run"),type:"button",children:"Allow same action"}),o.jsx("button",{disabled:n,onClick:()=>r("category-this-run"),type:"button",children:"Allow category"})]}),o.jsxs("div",{className:"agent-approval-scope",children:[o.jsx(Qp,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function lE(t){return t==="queued"?"Request queued":t==="checking-codex"?"Checking Codex":t==="preparing-tools"?"Preparing tools":t==="thinking"?"Preparing answer":t==="tool-running"?"Working on computers":t==="recovering"?"Retrying safely":t==="waiting-approval"?"Waiting for approval":"Working"}function cE({items:t,onCancel:n,onRetry:r,busyBatchId:i,approvals:l,onApprove:u,onReject:f,busyApprovalId:h,progress:g,emptyTitle:y="Ask LiveDesk to work across your machines.",emptyBody:w="Start with a read-only request such as “현재 대상에서 CPU와 메모리 상태를 확인해줘”."}){const b=d.useRef(null),x=d.useRef(!0),M=d.useRef(""),k=t[t.length-1];return d.useLayoutEffect(()=>{const N=b.current;N&&(k?.type==="user"&&k.id!==M.current&&(x.current=!0),M.current=k?.id||"",x.current&&(N.scrollTop=N.scrollHeight))},[l,t,k?.id,k?.type,g?.message,g?.stage]),o.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:b,onScroll:N=>{const E=N.currentTarget;x.current=E.scrollHeight-E.scrollTop-E.clientHeight<72},children:[l.filter(N=>N.status==="pending").map(N=>o.jsx(oE,{approval:N,busy:h===N.approvalId,onApprove:E=>u(N,E),onReject:()=>f(N)},N.approvalId)),t.length===0&&o.jsxs("div",{className:"agents-empty-conversation",children:[o.jsx("strong",{children:y}),o.jsx("span",{children:w})]}),t.map(N=>{if(N.type==="task"){const E=N;return o.jsx(sE,{operation:E.operation,states:E.states,status:E.status,onCancel:()=>n(E.batchId,E.agentRunId),onRetry:()=>r(E.batchId),busy:i===E.batchId},E.id)}return o.jsxs("article",{className:`agents-message ${N.type}`,children:[o.jsx("span",{children:N.type==="user"?"You":"LiveDesk Agent"}),o.jsx("p",{children:N.text})]},N.id)}),g&&o.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[o.jsxs("span",{children:[o.jsx(Si,{"aria-hidden":"true",size:15}),lE(g.stage)]}),o.jsx("p",{children:g.message})]})]})}const Gw=["Recommended","Health & capacity","Processes & services","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],ra=["windows","macos","linux"],ec={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:ra},"service.control":{label:"service control",permissionCategory:"serviceControl",readOnly:!1,risk:"high",supportedPlatforms:["windows","linux"]},"application.launch":{label:"application launch",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:ra},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:ra},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:ra},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:ra},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:ra},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:ra},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:ra},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:ra},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:ra},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:ra},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:ra},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:ra},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ra}};new Set(Object.keys(ec));const uE={Recommended:["recommended","overview","fleet","요약","추천"],"Health & capacity":["health","capacity","performance","상태","성능","용량"],"Processes & services":["process","service","application","프로세스","서비스","앱"],"Files & configuration":["file","config","directory","파일","설정","폴더"],"Software & automation":["software","install","automation","프로그램","설치","자동화"],"Network & connectivity":["network","connection","adapter","네트워크","연결","어댑터"],"Power & maintenance":["power","maintenance","restart","전원","유지보수","재시작"],"Troubleshooting & recovery":["troubleshooting","recovery","incident","문제해결","복구","장애"]},Vw=["low","medium","high","critical"];function dE(t){return t.reduce((n,r)=>{const i=ec[r].risk;return Vw.indexOf(i)>Vw.indexOf(n)?i:n},"low")}function fE(t){return ra.filter(n=>t.every(r=>ec[r].supportedPlatforms.includes(n)))}function ot(t,n,r,i,l,u,f={}){const h=f.description||i,g=l.flatMap(w=>w.split(".")),y=[...new Set([...uE[n],...u,...g])];return{id:t,category:n,title:r,prompt:i,description:h,requiredOperations:l,risk:f.risk||dE(l),targetSupport:f.targetSupport||"single-or-multiple",supportedPlatforms:f.supportedPlatforms||fE(l),keywords:y,recommended:f.recommended??!1,enabled:!0}}const d0=[ot("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target Clients.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),ot("recommended-attention","Recommended","Find targets needing attention","Identify current targets with high resource use, low disk space, or service warnings.",["system.health","disk.status","service.status"],["attention","warning","monitor"],{recommended:!0}),ot("recommended-performance-compare","Recommended","Compare selected performance","Compare CPU, memory, disk, and GPU capacity across the current targets.",["system.health","disk.status","gpu.status"],["compare","benchmark"],{recommended:!0}),ot("recommended-gpu-vram","Recommended","Review GPU and VRAM availability","Show GPU temperature, utilization, and VRAM availability for the current targets.",["gpu.status"],["graphics","temperature","utilization"],{recommended:!0}),ot("recommended-low-disk","Recommended","Locate low disk capacity","Find current targets with low free disk capacity and report the affected volumes.",["disk.status"],["storage","free space","capacity"],{recommended:!0}),ot("recommended-process-services","Recommended","Review processes and services","Review running processes and service state for warnings on the current targets.",["process.list","service.status"],["process","service","warning"],{recommended:!0}),ot("recommended-recover-application","Recommended","Recover a stopped application","Check a named application or service, relaunch its registered entry when stopped, and verify the result.",["process.list","application.launch","service.status"],["recover","start","application"],{targetSupport:"single",recommended:!0}),ot("recommended-incident-diagnostics","Recommended","Collect an incident diagnostic bundle","Collect health, service, network, and recent log diagnostics for the current targets.",["diagnostics.collect","logs.collect","system.health","network.status"],["incident","report","evidence"],{recommended:!0}),ot("health-cpu-memory","Health & capacity","Check high CPU and memory use","Find current targets with unusually high CPU or memory usage.",["system.health"],["cpu","memory","load","높은 사용량"]),ot("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),ot("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),ot("health-vram-usage","Health & capacity","Check VRAM usage","Report GPU memory usage and remaining VRAM on the current targets.",["gpu.status"],["vram","gpu memory","video memory"]),ot("health-low-disk","Health & capacity","Find low disk space","Find volumes below a safe free-space threshold on the current targets.",["disk.status"],["disk","storage","free space","디스크"]),ot("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),ot("health-system-warnings","Health & capacity","Collect system warnings","Review health, disk, and network status for warnings that need attention.",["system.health","disk.status","network.status"],["warnings","alerts","경고"]),ot("health-capacity-report","Health & capacity","Build a capacity report","Create a concise capacity report covering CPU, memory, GPU, disk, and network status.",["system.health","gpu.status","disk.status","network.status"],["report","capacity","inventory"]),ot("process-find-name","Processes & services","Find a running process by name","Find process named [process name] on the current targets.",["process.list"],["find","running","name","실행 중"]),ot("process-resource-heavy","Processes & services","Find resource-heavy processes","List the processes using the most CPU or memory on the current targets.",["process.list","system.health"],["top","cpu","memory","resource"]),ot("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target Client after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),ot("process-restart-named","Processes & services","Restart a named process","Check process named [process name] and restart it with its registered launch details when available.",["process.list","process.control"],["restart","relaunch","재시작"],{targetSupport:"single"}),ot("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target Client with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),ot("process-close-app","Processes & services","Close an application","Close application [application] on the target Client and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),ot("service-status-name","Processes & services","Check a service status","Check service [service name] and report its state on the current targets.",["service.status"],["service","status","서비스 상태"]),ot("service-restart-name","Processes & services","Restart a service safely","Check service [service name], stop it, wait for it to stop, then start it and verify the result.",["service.status","service.control"],["restart","start","stop","서비스 재시작"],{targetSupport:"single"}),ot("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target Client.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),ot("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target Client.",["file.read"],["config","settings","read","구성"]),ot("files-recent-logs","Files & configuration","Find recent log files","List recent log files under [path] and summarize the latest entries.",["file.list","file.read"],["logs","recent","tail"]),ot("files-update-config","Files & configuration","Update a configuration value","Read configuration file [path], update [change], and report the exact change made.",["file.read","file.write"],["edit","update","설정 변경"],{targetSupport:"single"}),ot("files-delete-temp","Files & configuration","Delete temporary files","Find temporary files under [path], delete only the requested matches, and report the freed space.",["file.list","file.delete","disk.status"],["cleanup","temp","delete","정리"],{targetSupport:"single"}),ot("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target Client and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),ot("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target Client and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),ot("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target Client.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),ot("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target Client, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),ot("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target Client, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),ot("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target Client, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),ot("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target Client and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),ot("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target Client and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),ot("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target Client and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),ot("software-verify-install","Software & automation","Verify an installed tool","Check whether [application] is installed, running, and available on the PATH of the current targets.",["process.list","system.health"],["verify","installed","path"]),ot("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target Client.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),ot("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),ot("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),ot("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),ot("network-warnings","Network & connectivity","Review network warnings","Review network status and recent logs for connectivity warnings on the current targets.",["network.status","logs.collect"],["warning","latency","packet loss"]),ot("network-diagnostics","Network & connectivity","Collect network diagnostics","Collect network status, system diagnostics, and relevant logs for the current targets.",["network.status","diagnostics.collect","logs.collect"],["diagnostics","incident","connectivity"]),ot("network-service-failures","Network & connectivity","Find network service failures","Check network status and relevant service states on the current targets.",["network.status","service.status"],["service","failure","dns"]),ot("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),ot("network-intermittent","Network & connectivity","Investigate intermittent connectivity","Investigate intermittent connectivity using network status, service state, and diagnostics evidence.",["network.status","service.status","diagnostics.collect"],["intermittent","unstable","recovery"]),ot("power-lock","Power & maintenance","Lock the Client","Lock the target Client and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),ot("power-logoff","Power & maintenance","Log off the Client","Log off the target Client after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),ot("power-sleep","Power & maintenance","Put the Client to sleep","Put the target Client to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),ot("power-restart","Power & maintenance","Restart the Client","Restart the target Client after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),ot("power-shutdown","Power & maintenance","Shut down the Client","Shut down the target Client after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),ot("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target Client, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),ot("power-timezone","Power & maintenance","Set the Client timezone","Set the target Client timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),ot("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target Client and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),ot("recovery-app-wont-start","Troubleshooting & recovery","Investigate an app that will not start","Inspect [application], review its logs, launch the registered application, and verify the process.",["process.list","application.launch","logs.collect"],["app failure","start","실행 오류"],{targetSupport:"single"}),ot("recovery-failed-service","Troubleshooting & recovery","Recover a failed service","Inspect service [service name], collect logs, restart it safely, and verify its running state.",["service.status","logs.collect","service.control"],["service failure","recover","서비스 복구"],{targetSupport:"single"}),ot("recovery-repeated-process","Troubleshooting & recovery","Investigate a repeatedly stopping process","Inspect process [process name], collect diagnostics, stop stale instances, and relaunch the registered process.",["process.list","diagnostics.collect","process.control","application.launch"],["crash loop","process","반복 종료"],{targetSupport:"single"}),ot("recovery-low-disk","Troubleshooting & recovery","Recover from low disk space","Inspect disk capacity, find temporary files, remove only the requested files, and verify free space.",["disk.status","file.list","file.delete"],["disk full","cleanup","저장공간 부족"],{targetSupport:"single"}),ot("recovery-gpu-overheating","Troubleshooting & recovery","Investigate GPU overheating","Inspect GPU temperature and processes, then close the specified workload if it is causing the thermal warning.",["gpu.status","process.list","application.close"],["overheating","thermal","GPU 발열"],{targetSupport:"single"}),ot("recovery-high-vram","Troubleshooting & recovery","Recover high VRAM usage","Inspect VRAM usage and GPU processes, then stop the specified stale workload if necessary.",["gpu.status","process.list","process.control"],["vram","memory pressure","VRAM 부족"],{targetSupport:"single"}),ot("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target Client.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),ot("recovery-incident-report","Troubleshooting & recovery","Create a full incident report","Create a full incident report from health, process, service, network, and log evidence for the current targets.",["system.health","process.list","service.status","network.status","logs.collect"],["incident","report","장애 보고서"])],Ng={read:"allow",processControl:"allow",serviceControl:"allow",applicationControl:"ask",fileRead:"allow",fileWrite:"allow",fileDelete:"ask",shell:"ask",script:"ask",softwareInstall:"ask",network:"allow",systemPower:"ask",systemConfiguration:"ask",userAccount:"deny"};function mE(t,n){return t==="safe-auto"?Ng:t==="full-access"?{...Ng,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:t==="custom"&&n?n:{...Ng,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function pE(t,n,r){const i=mE(n,r),l=t.requiredOperations.map(u=>i[ec[u].permissionCategory]);if(l.includes("deny")){const u=t.requiredOperations.find(f=>i[ec[f].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${ec[u].label}, which is blocked by the current permission policy.`}}return l.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a Client."}:t.requiredOperations.every(u=>ec[u].readOnly)?{state:"read-only",label:"Read only"}:n==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function hE(t){const n=String(t||"").trim().toLowerCase();return n==="windows"||n==="win32"||n==="win32nt"?"windows":n==="macos"||n==="macosx"||n==="darwin"||n==="osx"?"macos":n==="linux"?"linux":null}function gE(t,n,r){const i=new Set(r);return t.filter(l=>l.connected&&(n==="all"||n==="auto"||i.has(l.deviceId)))}function vE(t,n){const r=hE(t.platform);if(!r||!n.supportedPlatforms.includes(r))return!1;const i=t.capabilities?.agentTools;return!Array.isArray(i)||i.length===0?n.requiredOperations.every(l=>ec[l].readOnly):n.requiredOperations.every(l=>i.includes(l))}function f0(t,n,r,i,l,u){const f=pE(t,l,u),h=gE(n,r,i),g=h.map(M=>M.deviceId),y={...f,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:t.risk,supportedPlatforms:t.supportedPlatforms};if(h.length===0)return{...y,reason:"Select at least one connected Client."};if(t.targetSupport==="single"&&h.length!==1)return{...y,reason:"This task supports one Client at a time."};if(f.state==="blocked")return y;const w=h.filter(M=>vE(M,t)),b=w.map(M=>M.deviceId),x=g.filter(M=>!b.includes(M));return w.length===0?{...y,unsupportedDeviceIds:x,reason:"No current target supports the required platform and client capabilities."}:{...y,available:!0,availableDeviceIds:b,unsupportedDeviceIds:x}}function yE(t,n,r,i,l,u){return t.filter(f=>f.enabled&&f0(f,n,r,i,l,u).available).length}const Tg="livedesk.agentPromptRecent",Rg="livedesk.agentPromptFavorites",bE={Recommended:nc,"Health & capacity":Zl,"Processes & services":ok,"Files & configuration":ik,"Software & automation":Fp,"Network & connectivity":Mv,"Power & maintenance":Na,"Troubleshooting & recovery":sk};function Kw(t){if(typeof window>"u")return[];try{const n=JSON.parse(window.localStorage.getItem(t)||"[]");return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{return[]}}function wp(t,n){try{window.localStorage.setItem(t,JSON.stringify(n))}catch{}}function jg(t){return t==="all"?"All tasks":t==="recent"?"Recent":t==="favorites"?"Favorites":t==="read-only"?"Read only":t==="auto"?"Auto allowed":t==="approval"?"Approval required":t==="full-access"?"Full Access":t==="available"?"Available":t==="unavailable"?"Unavailable":t}function wE(t){return t==="all"?"All":t==="recent"?"Recent":t==="favorites"?"Favorites":t==="read-only"?"Read only":t==="auto"?"Auto":t==="approval"?"Approval":t==="full-access"?"Full access":t==="available"?"Available":t==="unavailable"?"Unavailable":{Recommended:"Recommended","Health & capacity":"Health","Processes & services":"Processes","Files & configuration":"Files","Software & automation":"Software","Network & connectivity":"Network","Power & maintenance":"Power","Troubleshooting & recovery":"Recovery"}[t]}function xE(t,n,r){if(!r.trim())return!0;const i=r.trim().toLowerCase();return[t.title,t.prompt,t.description,t.category,t.risk,n.label,...t.keywords,...t.requiredOperations,...t.supportedPlatforms].join(" ").toLowerCase().includes(i)}function SE(t){return`permission-${t}`}function CE(t){return t==="low"?"Low risk":t==="medium"?"Medium risk":t==="high"?"High risk":"Critical risk"}function kE(t){return t==="windows"?"Windows":t==="macos"?"macOS":"Linux"}function ME({devices:t,targetMode:n,selectedIds:r,permissionMode:i,customCategories:l,onSelectPrompt:u,onClose:f}){const[h,g]=d.useState(""),[y,w]=d.useState("all"),[b,x]=d.useState(()=>Kw(Tg)),[M,k]=d.useState(()=>Kw(Rg)),[N,E]=d.useState(0),[I,T]=d.useState(""),P=d.useRef(null),U=d.useRef(null),F=d.useMemo(()=>d0.filter(ee=>ee.enabled),[]),Y=d.useMemo(()=>new Map(F.map(ee=>[ee.id,f0(ee,t,n,r,i,l)])),[l,t,i,r,n,F]),D=d.useMemo(()=>[...Y.values()].filter(ee=>ee.available).length,[Y]),K=d.useMemo(()=>t.filter(ee=>ee.connected&&(n==="all"||n==="auto"||r.includes(ee.deviceId))).length,[t,r,n]),ne=d.useMemo(()=>{const ee=F.filter(B=>xE(B,Y.get(B.id),h));return y==="recent"?b.map(B=>ee.find(L=>L.id===B)).filter(B=>!!B):y==="favorites"?M.map(B=>ee.find(L=>L.id===B)).filter(B=>!!B):y==="all"?ee:ee.filter(B=>{const L=Y.get(B.id);return y==="read-only"?L.state==="read-only":y==="auto"?L.state==="auto":y==="approval"?L.state==="approval":y==="full-access"?L.state==="full-access":y==="available"?L.available:y==="unavailable"?!L.available:B.category===y})},[Y,M,y,b,h,F]),q=d.useMemo(()=>y!=="all"?[{category:jg(y),templates:ne}]:Gw.map(ee=>({category:ee,templates:ne.filter(B=>B.category===ee)})).filter(ee=>ee.templates.length>0),[y,ne]);d.useEffect(()=>{E(ee=>Math.min(ee,Math.max(0,ne.length-1)))},[ne.length]),d.useEffect(()=>{wp(Tg,b)},[b]),d.useEffect(()=>{wp(Rg,M)},[M]),d.useEffect(()=>{U.current?.focus();const ee=L=>{L.target instanceof Node&&!P.current?.contains(L.target)&&f()},B=L=>{L.key==="Escape"&&(L.preventDefault(),f())};return document.addEventListener("pointerdown",ee),document.addEventListener("keydown",B),()=>{document.removeEventListener("pointerdown",ee),document.removeEventListener("keydown",B)}},[f]);const O=ee=>{const B=Y.get(ee.id);if(!B.available){T(B.reason||"This task is not available for the current targets and permission policy.");return}const L=[ee.id,...b.filter(oe=>oe!==ee.id)].slice(0,10);x(L),wp(Tg,L),u(ee.prompt),f()},W=ee=>{k(B=>{const L=B.includes(ee)?B.filter(oe=>oe!==ee):[ee,...B];return wp(Rg,L),L})},ce=ee=>{ee.key==="ArrowDown"?(ee.preventDefault(),E(B=>Math.min(B+1,Math.max(0,ne.length-1)))):ee.key==="ArrowUp"?(ee.preventDefault(),E(B=>Math.max(B-1,0))):ee.key==="Enter"&&ne[N]&&(ee.preventDefault(),O(ne[N]))};let $=-1;return o.jsxs("section",{className:"agents-suggested-tasks",ref:P,"aria-label":"Suggested tasks",children:[o.jsxs("header",{className:"agents-suggested-header",children:[o.jsxs("div",{children:[o.jsxs("span",{className:"agents-suggested-title",children:[o.jsx(nc,{size:15})," Suggested tasks"]}),o.jsxs("small",{children:[D," available · ",F.length," total. Choose a task, edit it, then run it."]})]}),o.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:f,children:o.jsx(hr,{size:16})})]}),o.jsxs("label",{className:"agents-suggested-search",children:[o.jsx(rk,{size:15,"aria-hidden":"true"}),o.jsx("input",{ref:U,value:h,onChange:ee=>g(ee.target.value),onKeyDown:ce,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),o.jsx("div",{className:"agents-suggested-filters","aria-label":"Task categories and availability filters",children:["all","recent","favorites","read-only","auto","approval","full-access","available","unavailable",...Gw].map(ee=>{const B=ee==="recent"?Lx:ee==="favorites"?Ug:ee==="all"?nc:ee==="available"?Ba:ee==="unavailable"?Bx:ee==="read-only"||ee==="auto"||ee==="approval"||ee==="full-access"?Na:bE[ee];return o.jsxs("button",{className:y===ee?"active":"",type:"button",title:jg(ee),"aria-label":jg(ee),"aria-pressed":y===ee,onClick:()=>{w(ee),E(0),T("")},children:[o.jsx(B,{size:12})," ",wE(ee)]},ee)})}),I&&o.jsx("div",{className:"agents-suggested-notice",role:"status",children:I}),o.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[q.map(ee=>o.jsxs("div",{className:"agents-suggested-group",children:[o.jsx("strong",{children:ee.category}),ee.templates.map(B=>{$+=1;const L=$===N,oe=M.includes(B.id),be=Y.get(B.id),H=be.availableDeviceIds.length+be.unsupportedDeviceIds.length||K,me=be.available?`Available on ${be.availableDeviceIds.length} of ${H} target${H===1?"":"s"}`:`Unavailable: ${be.reason||"not supported by the current targets"}`;return o.jsxs("div",{className:`agents-suggested-item ${L?"active":""} ${be.available?"":"unavailable"}`,children:[o.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":L,"aria-disabled":!be.available,onClick:()=>O(B),children:[o.jsx("span",{children:B.title}),o.jsx("small",{className:"agents-suggested-description",children:B.description}),o.jsxs("span",{className:"agents-suggested-meta",children:[o.jsx("em",{children:B.category}),o.jsx("em",{className:SE(be.state),children:be.label}),o.jsx("em",{className:`risk-${B.risk}`,children:CE(B.risk)}),o.jsx("em",{children:B.supportedPlatforms.map(kE).join(" · ")}),o.jsx("em",{className:be.available?"availability-ok":"availability-unavailable",children:me}),be.available&&be.unsupportedDeviceIds.length>0&&o.jsxs("em",{className:"availability-warning",children:["Unsupported on ",be.unsupportedDeviceIds.length]})]})]}),o.jsx("button",{className:`agents-suggested-favorite ${oe?"favorite":""}`,type:"button","aria-label":oe?`Remove ${B.title} from favorites`:`Add ${B.title} to favorites`,"aria-pressed":oe,onClick:()=>W(B.id),children:o.jsx(Ug,{size:14,fill:oe?"currentColor":"none"})})]},B.id)})]},ee.category)),ne.length===0&&o.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function AE({devices:t,mode:n,selectedIds:r,onModeChange:i,onToggle:l,permissionMode:u,onPermissionModeChange:f}){const h=t.filter(Vp),g=r.filter(y=>h.some(w=>w.deviceId===y)).length;return o.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[o.jsxs("div",{className:"agents-target-toolbar",children:[o.jsx("span",{className:"agents-section-label",children:"Targets"}),o.jsxs("div",{className:"agents-target-modes",children:[o.jsxs("button",{className:n==="all"?"active":"",onClick:()=>i("all"),type:"button",children:[o.jsx(Xf,{size:14})," All connected ",o.jsx("small",{children:h.length})]}),o.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>i("selected"),type:"button",children:[o.jsx(fo,{size:14})," Selected ",g]}),o.jsxs("button",{className:n==="auto"?"active":"",onClick:()=>i("auto"),type:"button",children:[o.jsx(nc,{size:14})," Auto"]}),o.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[o.jsx(Xf,{size:14})," Group ",o.jsx("small",{children:"Soon"})]})]}),o.jsxs("label",{className:`agents-permission-picker permission-${u}`,children:[o.jsx(Qp,{size:14}),o.jsx("span",{children:"Permission"}),o.jsxs("select",{value:u,onChange:y=>f(y.target.value),"aria-label":"Agent permission mode",children:[o.jsx("option",{value:"ask",children:"Ask"}),o.jsx("option",{value:"safe-auto",children:"Safe Auto"}),o.jsx("option",{value:"full-access",children:"Full Access"}),o.jsx("option",{value:"custom",children:"Custom"})]}),o.jsx(Hx,{size:13,"aria-hidden":"true"})]})]}),o.jsx("div",{className:"agents-target-list",children:t.length===0?o.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):t.map(y=>{const w=Vp(y),b=n==="all"||n==="auto"?w:r.includes(y.deviceId);return o.jsxs("label",{className:`agents-target-option ${b?"selected":""} ${w?"":"offline"}`,children:[o.jsx("input",{type:"checkbox",checked:b,disabled:!w||n!=="selected",onChange:()=>l(y.deviceId)}),o.jsx("span",{className:"agents-target-icon",children:o.jsx(Ta,{size:15})}),o.jsxs("span",{children:[o.jsx("strong",{children:Gp(y)}),o.jsx("small",{children:w?"Ready":y.connected?"Agent reconnecting":"Offline"})]}),b&&o.jsx(fo,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},y.deviceId)})})]})}const NE=800,Qw=5e3;function TE(){return typeof document>"u"||document.visibilityState==="visible"}function RE(t){return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t))}function Yw({poll:t,onResult:n,onError:r,intervalMs:i=NE,isVisible:l=TE,subscribeVisibility:u=RE,setTimeoutImpl:f=globalThis.setTimeout.bind(globalThis),clearTimeoutImpl:h=globalThis.clearTimeout.bind(globalThis),createAbortController:g=()=>new AbortController}){if(typeof t!="function")throw new TypeError("Agent polling requires a poll function.");const y={current:null};let w=!0,b=0,x=null,M=null;const k=()=>{x!==null&&(h(x),x=null)},N=()=>{!w||!l()||x!==null||y.current||(x=f(()=>{x=null,E()},i))},E=()=>{if(!w||!l()||y.current)return y.current;const U=++b,F=g();M=F;const Y=Op(y,()=>t(F.signal));return Y.then(D=>{w&&U===b&&!F.signal.aborted&&n?.(D)},D=>{w&&U===b&&!F.signal.aborted&&r?.(D)}).finally(()=>{M===F&&(M=null),w&&l()&&N()}).catch(()=>{}),Y},I=async()=>{if(!w)throw new Error("LiveDesk Agent polling owner is closed.");k(),b+=1;const U=y.current;if(M&&!M.signal.aborted&&M.abort(new Error("LiveDesk Agent polling was superseded by an explicit refresh.")),U)try{await U}catch{}if(!(!w||!l()))return k(),E()},P=u(()=>{if(k(),!l()){b+=1,M&&!M.signal.aborted&&M.abort(new Error("LiveDesk Agent polling paused while hidden."));return}E()});return E(),{refresh:I,stop(){w&&(w=!1,b+=1,k(),P?.(),M&&!M.signal.aborted&&M.abort(new Error("LiveDesk Agent polling owner closed.")))}}}async function jE(t,n){return tt("/api/settings/agent/run",{method:"POST",body:JSON.stringify(n)},t)}async function EE(t,n,r={}){return tt(`/api/settings/agent/runs/${encodeURIComponent(n)}`,r,t)}async function DE(t,n){return tt(`/api/settings/agent/runs/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function IE(t){return tt("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},t)}async function LE(t,n,r,i){return tt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:i})},t)}async function _E(t,n,r,i="User rejected this action."){return tt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:i})},t)}async function PE(t,n,r){return tt(`/api/settings/agent/policies/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({categories:r})},t)}async function FE(t,n){return tt("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(n)},t)}async function OE(t,n,r={}){return tt(`/api/remote/tasks/${encodeURIComponent(n)}`,r,t)}async function HE(t,n){return tt(`/api/remote/tasks/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function BE(t,n){return tt(`/api/remote/tasks/${encodeURIComponent(n)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},t)}function ud(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Eg(t,n){const r=new Map(n.map(i=>[i.deviceId,Gp(i)]));return t.results.map(i=>({deviceId:i.deviceId,deviceName:i.deviceName||r.get(i.deviceId)||i.deviceId,status:Jj(i.status),stage:i.stage||(i.status==="running"?"Checking processes":void 0),result:i.result,data:i.data,error:i.error,sequence:Number.isSafeInteger(i.sequence)?i.sequence:0}))}function zE(t,n){const r=new Map(n.map(i=>[i.deviceId,i]));return t.map(i=>{const l=r.get(i.deviceId);return!l||l.sequence<=i.sequence?i:l})}function $E(t,n){const r=n.filter(u=>u.status==="completed"),i=n.filter(u=>u.status==="failed");if(t.operation==="process.list"){const f=`${r.filter(h=>{const g=h.result||"";return!/not running|no process/i.test(g)&&/running|online|found/i.test(g)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return i.length>0?`${f}
|
|
176
176
|
${i.map(h=>`${h.deviceName}는 ${h.error||"응답하지 않았습니다."}`).join(`
|