1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/hooks-mpVIaQOb.js","assets/rolldown-runtime-CMxvf4Kt.js","vendor/vendor-ui-runtime-CtdfFhWo.js","assets/app-const-BzFqCjOv.js","vendor/vendor-react-Bwss5s6Y.js","vendor/vendor-ai-runtime-DrDK77gy.js","vendor/vendor-data-runtime-nLFaCKB0.js","assets/swr-C_leGIiU.js","assets/keys-BAizXMAH.js","assets/swrKeys-D98yQcag.js","assets/resource-D1c_4mou.js","assets/client-DUGXaJW2.js","assets/document-B0YnY6Mv.js","assets/abortableRequest-C6SDiPFy.js"])))=>i.map(i=>d[i]); 2import{n as e,o as t}from"./rolldown-runtime-CMxvf4Kt.js";import{G as n,O as r,S as i,U as a,w as o,x as s}from"../vendor/vendor-data-runtime-nLFaCKB0.js";import{B as c,Gt as l,Ht as u,Ki as d,O as f,Wt as p,br as m,cr as h,k as g,ln as _,lr as v,na as y,pn as ee,ta as te,un as ne,yr as b,z as re}from"../vendor/vendor-ai-runtime-DrDK77gy.js";import{C as x,S,a as C,b as ie,c as ae,g as w,i as oe,l as T,o as E,r as se,s as D,u as ce}from"./agent-Doq2Q6Wt.js";import{$i as le,Ri as ue,Si as O,To as de,Ut as k,Vt as A,bi as j,g as fe,xi as pe}from"./app-const-BzFqCjOv.js";import{D as me}from"./ScrollArea-CdDxdn_v.js";import{a as he}from"../vendor/vendor-ui-runtime-CtdfFhWo.js";import{n as ge}from"./base-ui-Bi3Dz7GG.js";import{Xn as _e,Zn as ve,ar as ye,ir as be,n as xe,o as Se,pt as Ce,r as we,rr as Te}from"./agent-Dh3-_0ai.js";import{n as Ee,t as De}from"./p-map-D5Ha-P-7.js";import{r as Oe,s as ke,t as Ae,u as je}from"./swr-C_leGIiU.js";import{b as M,j as Me}from"./keys-BAizXMAH.js";import{i as Ne,n as Pe}from"./global-DfKpeTkj.js";import{n as Fe,t as N}from"./document-B0YnY6Mv.js";import{n as Ie,t as Le}from"./knowledgeBase-o6SNuybf.js";import{a as P,i as Re,n as F,o as ze,t as Be}from"./resource-D1c_4mou.js";import{i as Ve,n as He,r as Ue}from"./upload-DXx2CvIy.js";import{n as We,t as Ge}from"./isChunkingUnsupported-DzBdjh0S.js";async function Ke(e){let t=e.topK??5,n=[];if(n=e.knowledgeIds?.length?e.knowledgeIds.map(e=>({id:e})):await Ie.getKnowledgeBaseList(),!n.length)return[];let r=[];return await Promise.all(n.map(async n=>{try{let i=await Ie.search(n.id,e.query,t);for(let e of i||[])r.push({id:e.chunkId,text:e.content,similarity:Number(e.score)||0,fileId:e.docId??null,fileName:e.docName??null})}catch(e){console.warn(`[rag] search base failed:`,n.id,e)}})),r.sort((e,t)=>t.similarity-e.similarity),r.slice(0,t)}var qe,I,Je=e((()=>{Le(),qe=class{parseFileContent=async(e,t)=>({taskId:`done-${e}`,status:`success`});createParseFileTask=async(e,t)=>({taskId:`done-${e}`,status:`success`});retryParseFile=async e=>({taskId:`done-${e}`,status:`success`});createEmbeddingChunksTask=async e=>({taskId:`done-${e}`,status:`success`});semanticSearch=async(e,t)=>Ke({query:e,fileIds:t,topK:5});semanticSearchForChat=async(e,t)=>Ke(e);getFileContents=async(e,t)=>[];deleteMessageRagQuery=async e=>({success:!0,id:e})},I=new qe}));function Ye(e){return e}function Xe(e){let t=tt.get(e);return t||(t=`optimistic-store-${++nt}`,tt.set(e,t)),t}function Ze(e){let t=new Set;for(let n of e){let e=n.path.slice(0,Math.min(n.path.length,2)).join(`.`);t.add(e)}return Array.from(t)}function Qe(e,t){let n=Xe(e);return Ze(t).map(e=>`${n}:${e}`)}function $e(e,t){for(let n of e)for(let e of t)if(n===e||n.startsWith(`${e}.`)||e.startsWith(`${n}.`))return!0;return!1}function et(e){return{actionName:e.actionName,affectedPaths:e.affectedPaths,id:e.id,maxRetries:e.maxRetries,retryCount:e.retryCount,status:e.status,timestamp:new Date(e.timestamp)}}var tt,nt,rt,it,at,ot,st=e((()=>{ie(),tt=new WeakMap,nt=0,rt=0,it=class{history=[];idleResolvers=new Set;inflightIds=new Set;maxHistory;options;queue=[];constructor(e={}){this.maxHistory=e.maxHistory??20,this.options={maxHistory:this.maxHistory,maxRetries:e.maxRetries??0,onMutationError:e.onMutationError??(()=>{}),onMutationSuccess:e.onMutationSuccess??(()=>{}),onQueueChange:e.onQueueChange??(()=>{})}}addToHistory(e){this.history.unshift(e),this.history.length>this.maxHistory&&(this.history=this.history.slice(0,this.maxHistory))}getInflightMutations(){return this.queue.filter(e=>this.inflightIds.has(e.id))}hasPendingMutations(){return this.queue.some(e=>
2e.status===`pending`||e.status===`inflight`)}hasInflightConflict(e){for(let t of this.getInflightMutations())if($e(e.affectedPaths,t.affectedPaths))return!0;return!1}notify(){if(this.options.onQueueChange([...this.queue.map(et),...this.history]),!this.hasPendingMutations()){for(let e of this.idleResolvers)e();this.idleResolvers.clear()}}processNext(){let e=this.queue.filter(e=>e.status===`pending`&&!this.inflightIds.has(e.id)).sort((e,t)=>e.timestamp-t.timestamp);for(let t of e)this.hasInflightConflict(t)||this.executeMutation(t)}async settleFailure(e,t){e.status=`failed`,this.inflightIds.delete(e.id),this.rollback(e),await e.onError?.(t);let n={...et(e),status:`rolled-back`};this.addToHistory(n),this.queue=this.queue.filter(t=>t.id!==e.id),this.notify(),this.options.onMutationError(n,t),e.reject?.(t),this.processNext()}enqueue(e){let{onSuccess:t,remoteFn:n,resolve:r,...i}=e,a={...i,onSuccess:t?async e=>{await t(e)}:void 0,remoteFn:async()=>n()};return new Promise((e,t)=>{a.resolve=t=>e(t),a.reject=t,this.queue.push(a),this.notify(),this.processNext()})}async flush(){this.processNext(),this.hasPendingMutations()&&await new Promise(e=>{this.idleResolvers.add(e)})}async executeMutation(e){this.inflightIds.add(e.id),e.status=`inflight`,this.notify();try{let t=await e.remoteFn();await e.onSuccess?.(t),e.status=`success`,this.inflightIds.delete(e.id),this.addToHistory(et(e)),this.queue=this.queue.filter(t=>t.id!==e.id),this.notify(),this.options.onMutationSuccess(et(e)),e.resolve?.(t),this.processNext()}catch(t){if(e.retryCount+=1,e.retryCount<=e.maxRetries){e.status=`pending`,this.inflightIds.delete(e.id),this.notify(),this.processNext();return}await this.settleFailure(e,t)}}rollback(e){let t=new Set;for(let n of e.storePatches.keys())t.add(n);let n=this.queue.filter(t=>t.id!==e.id&&t.status!==`failed`).sort((e,t)=>t.timestamp-e.timestamp);for(let e of n)for(let n of e.storePatches.keys())t.add(n);for(let r of t){let t=r.getState();for(let e of n){let n=e.storePatches.get(r);n&&(t=w(t,n.inversePatches))}let i=e.storePatches.get(r);i&&(t=w(t,i.inversePatches));for(let e of[...n].reverse()){let n=e.storePatches.get(r);n&&(t=w(t,n.patches))}r.setState(t)}}},at=class{committed=!1;defaultStore;mutationFn=null;mutationErrorHandler;mutationSuccessHandler;name;enqueueFn;maxRetries;records=[];workingStates=new Map;constructor(e,t,n,r){this.defaultStore=r?Ye(r):null,this.enqueueFn=t,this.maxRetries=n,this.name=e}set(e,t,n){let r,i,a;if(typeof e==`function`){if(!this.defaultStore)throw Error(`[OptimisticEngine] "${this.name}": no default store set`);r=this.defaultStore,i=e,a={}}else r=Ye(e),i=t,a=n??{};if(this.committed)throw Error(`[OptimisticEngine] "${this.name}": cannot call set() after commit()`);let o=a.flush??!0,[s,c,l]=x(this.workingStates.get(r)??r.getState(),i);c.length!==0&&(o?(r.setState(s),this.workingStates.delete(r)):this.workingStates.set(r,s),this.records.push({flushed:o,inversePatches:l,patches:c,store:r}))}set mutation(e){this.mutationFn=e}set onError(e){this.mutationErrorHandler=e}set onSuccess(e){this.mutationSuccessHandler=e}commit(){if(this.committed)throw Error(`[OptimisticEngine] "${this.name}": transaction already committed`);if(!this.mutationFn)throw Error(`[OptimisticEngine] "${this.name}": missing remote mutation`);this.committed=!0;for(let e of this.records){if(e.flushed)continue;let t=w(e.store.getState(),e.patches);e.store.setState(t),e.flushed=!0}this.workingStates.clear();let e=new Map;for(let t of this.records){let n=e.get(t.store);n?(n.patches.push(...t.patches),n.inversePatches=[...t.inversePatches,...n.inversePatches]):e.set(t.store,{inversePatches:[...t.inversePatches],patches:[...t.patches]})}let t=Array.from(e.entries()).flatMap(([e,t])=>Qe(e,t.patches));return this.enqueueFn({actionName:this.name,affectedPaths:t,id:`optimistic-mutation-${++rt}-${Date.now()}`,maxRetries:this.maxRetries,onError:this.mutationErrorHandler,onSuccess:this.mutationSuccessHandler,remoteFn:this.mutationFn,retryCount:0,status:`pending`,storePatches:e,timestamp:Date.now()})}},ot=class{defaultStore;maxRetries;queue;constructor(e,t){this.defaultStore=e,this.maxRetries=t?.maxRetries??0,this.queue=new it(t)}createTransaction(e){return new at(e,e=>this.queue.enqueue(e),this.maxRetries,this.defaultStore)}async flush(){await this.queue.flush()}}})),ct,lt,ut,dt,ft,pt,mt,ht=e((()=>{ne(),ct=1920,lt=new Set([`image/jpeg`,`image/png`,`image/webp`]),ut=.85,dt=({img:e,type:t,maxSize:n=ct})=>
2{let r=e.width,i=e.height;(r>n||i>n)&&(r>=i?(i=Math.round(n/r*i),r=n):(r=Math.round(n/i*r),i=n));let a=document.createElement(`canvas`),o=a.getContext(`2d`);return a.width=r,a.height=i,o.drawImage(e,0,0,e.width,e.height,0,0,r,i),t===`image/jpeg`?a.toDataURL(`image/jpeg`,ut):a.toDataURL(`image/png`)},ft=(e,t)=>{let n=e.split(`,`)[0].split(`:`)[1].split(`;`)[0],r=atob(e.split(`,`)[1]),i=new Uint8Array(r.length);for(let e=0;e<r.length;e++)i[e]=r.charCodeAt(e);return new File([i],t,{type:n})},pt=async e=>{let t=await _(await e.arrayBuffer());return!t||t===e.type?e:new File([e],e.name,{lastModified:e.lastModified,type:t})},mt=e=>new Promise(t=>{let n=new Image,r=URL.createObjectURL(e);n.addEventListener(`load`,async()=>{URL.revokeObjectURL(r);try{let r=await pt(e),i=r.type;if(n.width<=1920&&n.height<=1920&&r.size<=3145728){t(r);return}let a=ct,o;do o=ft(dt({img:n,maxSize:a,type:i}),r.name),a=Math.round(a*.8);while(o.size>3145728&&a>100);t(o)}catch{t(e)}}),n.addEventListener(`error`,()=>{URL.revokeObjectURL(r),t(e)}),n.src=r})})),gt,_t=e((()=>{ie(),gt=(e,t)=>{switch(t.type){case`addFile`:return S(e,e=>{let{atStart:n,file:r}=t;n?e.unshift(r):e.push(r)});case`addFiles`:return S(e,e=>{let{atStart:n,files:r}=t;for(let t of r)n?e.unshift(t):e.push(t)});case`updateFile`:return S(e,e=>{let n=e.find(e=>e.id===t.id);n&&Object.assign(n,t.value)});case`updateFileStatus`:return S(e,e=>{let n=e.find(e=>e.id===t.id);n&&(n.status=t.status)});case`updateFileStatuses`:return S(e,e=>{let n=new Set(t.ids);for(let r of e)n.has(r.id)&&(r.status=t.status)});case`updateFileUploadState`:return S(e,e=>{let n=e.find(e=>e.id===t.id);n&&(n.uploadState=t.uploadState)});case`removeFile`:return S(e,e=>{let n=e.findIndex(e=>e.id===t.id);n!==-1&&e.splice(n,1)});case`removeFiles`:return S(e,e=>{for(let n of t.ids){let t=e.findIndex(e=>e.id===n);t!==-1&&e.splice(t,1)}});default:throw Error(`Unhandled action type`)}}})),vt,yt,bt,xt,St,Ct,wt,Tt,Et,Dt,Ot=e((()=>{vt=new Set([`image/gif`,`image/jpeg`,`image/jpg`,`image/png`,`image/webp`]),yt=new Set([`gif`,`jpeg`,`jpg`,`png`,`webp`]),bt=new Set([`aac`,`flac`,`m4a`,`mp3`,`oga`,`ogg`,`opus`,`wav`,`weba`]),xt=new Set(`bat.bash.c.cfg.conf.cpp.cs.csv.cts.dart.db.diff.doc.docx.env.go.gradle.groovy.h.hpp.htm.html.ini.java.js.json.json5.jsonc.jsx.kt.less.log.lua.markdown.md.mdx.mjs.mts.patch.pdf.php.properties.pptx.ps1.py.rb.rs.scala.scss.sh.sql.svelte.svg.swift.toml.ts.tsx.txt.vue.xls.xlsx.xml.yaml.yml`.split(`.`)),St=new Set([`application/json`,`application/pdf`,`application/vnd.ms-excel`,`application/vnd.ms-powerpoint`,`application/vnd.openxmlformats-officedocument.presentationml.presentation`,`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,`application/msword`,`text/csv`,`text/markdown`,`text/plain`]),Ct=e=>e.split(`.`).pop()?.toLowerCase()||``,wt={aac:`audio/aac`,flac:`audio/flac`,m4a:`audio/mp4`,m4b:`audio/mp4`,mp3:`audio/mpeg`,oga:`audio/ogg`,ogg:`audio/ogg`,opus:`audio/opus`,wav:`audio/wav`,weba:`audio/webm`},Tt=e=>wt[Ct(e)],Et=e=>{let t=e.type.toLowerCase(),n=Ct(e.name);return t.startsWith(`image/`)?vt.has(t):!t&&yt.has(n)||t.startsWith(`video/`)||t.startsWith(`audio/`)||bt.has(n)?!0:n?xt.has(n):t.startsWith(`text/`)?!0:St.has(t)},Dt=e=>{let t=[],n=[];for(let r of e)Et(r)?t.push(r):n.push(r);return{supportedFiles:t,unsupportedFiles:n}}})),kt,At,jt,Mt,Nt,Pt,Ft,It=e((()=>{ht(),ge(),kt=ee(),a(),Te(),k(),ze(),Je(),He(),xe(),Se(),_t(),Ge(),re(),_e(),Ot(),At=ve(`chat`),jt=(e,t,n)=>new Ft(e,t,n),Mt=e=>{if(typeof e!=`object`||!e||!(`data`in e))return;let t=e.data;return typeof t?.code==`string`?t.code:void 0},Nt=e=>{if(e instanceof Error)return e.message;if(typeof e==`string`)return e;if(typeof e==`object`&&e&&`message`in e){let t=e.message;if(typeof t==`string`)return t}return String(e)},Pt=e=>e===`NetWorkError`?n(`upload.networkError`,{ns:`error`}):Mt(e)===`FORBIDDEN`?n(`upload.permissionDenied`,{ns:`error`}):typeof e==`string`?e:n(`upload.unknownError`,{ns:`error`,reason:Nt(e)}),Ft=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}addChatContextSelection=e=>{let t=[e,...this.#e().chatContextSelections.filter(t=>t.id!==e.id)];this.#t({chatContextSelections:t},!1,At(`addChatContextSelection`))};clearChatContextSelections=()=>{this.#t({chatContextSelections:[]},!1,At(`clearChatContextSelections`))};clearChatUploadFileList=()=>{this.#t({chatUploadFileList:[]},!1,At(`clearChatUploadFileList`))};dispatchChatUploadFileList=e=>{let t=gt(this.#e().chatUploadFileList,e);t!==this.#e().chatUploadFileList&&this.#t({chatUploadFileList:t},!1,`dispatchChatFileList/${e.type}`)};removeChatContextSelection=e=>{let t=this.#e().chatContextSelections.filter(t=>t.id!==e);this.#t({chatContextSelections:t},!1,At(`removeChatContextSelection`))};removeChatUploadFile=async e=>{let{chatUploadFileList:t,dispatchChatUploadFileList:n}=this.#e(),r=t.find(t=>
2t.id===e)?.skipRemoveFile;n({id:e,type:`removeFile`}),!r&&await P.removeFile(e)};startAsyncTask=async(e,t,n)=>{await t(e);let r=!1;for(;!r;){await c(2e3);let t;try{t=await P.getKnowledgeItem(e)??void 0}catch(e){console.error(`getFileItem Error:`,e);continue}if(!t)return;n(t),(t.finishEmbedding||t.chunkingStatus===`error`||t.embeddingStatus===`error`)&&(r=!0)}};uploadChatFiles=async(e,t)=>{let{dispatchChatUploadFileList:r}=this.#e(),i=e.filter(e=>!A.includes(e.name)),a=we(),{supportedFiles:o,unsupportedFiles:s}=!Ce.getAgentEnableModeById(t)(a)&&!Ce.isAgentHeterogeneousById(t)(a)?Dt(i):{supportedFiles:i,unsupportedFiles:[]};if(s.length>0&&me.error(n(`upload.validation.unsupportedFileType`,{files:s.map(e=>e.name).join(`, `),ns:`chat`})),o.length===0)return;let c=await Promise.all(o.map(e=>lt.has(e.type)?mt(e):e));r({files:await Promise.all(c.map(async e=>{let t,n;if(e.type.startsWith(`image`)||e.type.startsWith(`video`)){let r=await e.arrayBuffer();t=URL.createObjectURL(new Blob([r],{type:e.type}));let i=kt.Buffer.from(r).toString(`base64`);n=`data:${e.type};base64,${i}`}return{base64Url:n,file:e,id:e.name,previewUrl:t,status:`pending`}})),type:`addFiles`});let l=c.map(async e=>{let t;try{t=await this.#e().uploadWithProgress({file:e,onStatusUpdate:r})}catch(t){Nt(t)!==`UNAUTHORIZED`&&ye.error({description:Pt(t),message:n(`upload.uploadFailed`,{ns:`error`})}),r({id:e.name,type:`removeFile`})}t&&(We(e.type)||await I.parseFileContent(t.id))});await Promise.all(l)}}})),Lt,Rt=e((()=>{Lt={chatContextSelections:[],chatUploadFileList:[],uploadingIds:[]}})),zt,Bt,Vt,Ht,Ut,Wt,Gt,Kt,qt,Jt=e((()=>{v(),zt=e=>e.chatUploadFileList,Bt=e=>e.chatContextSelections,Vt=e=>e.uploadingIds.length>0,Ht=e=>e.chatUploadFileList.map(e=>e.file),Ut=e=>e.chatUploadFileList.length>0,Wt=e=>e.chatContextSelections.length>0,Gt=e=>e.chatUploadFileList.some(e=>h.has(e.status)||e.tasks&&!e.tasks?.finishEmbedding),Kt={chatUploadFileList:zt,isImageUploading:Vt},qt={chatContextSelectionHasItem:Wt,chatContextSelections:Bt,chatRawFileList:Ht,chatUploadFileList:zt,chatUploadFileListHasItem:Ut,isUploadingFiles:Gt}})),Yt=e((()=>{It(),Rt(),Jt()})),Xt,Zt,Qt=e((()=>{Je(),Xt=(e,t,n)=>new Zt(e,t,n),Zt=class{#e;constructor(e,t,n){this.#e=e}closeChunkDrawer=()=>{this.#e({chunkDetailId:null,isSimilaritySearch:!1,similaritySearchChunks:[]})};highlightChunks=e=>{this.#e({highlightChunkIds:e})};openChunkDrawer=e=>{this.#e({chunkDetailId:e})};semanticSearch=async(e,t)=>{this.#e({isSimilaritySearching:!0});let n=await I.semanticSearch(e,[t]);this.#e({isSimilaritySearching:!1,similaritySearchChunks:n})}}})),$t,en=e((()=>{$t={chunkDetailId:null,highlightChunkIds:[],similaritySearchChunks:[]}})),tn,nn,rn,an=e((()=>{tn=e=>e.isSimilaritySearch,nn=e=>e.chunkDetailId,rn={enabledChunkFileId:nn,showSimilaritySearchResult:tn}})),on=e((()=>{Qt(),en(),an()})),L,sn,cn=e((()=>{he(),L=e=>e?JSON.stringify({category:e.category??null,libraryId:e.libraryId??null,parentId:e.parentId??null,q:e.q??null,showFilesInKnowledgeBase:e.showFilesInKnowledgeBase??null,sorter:e.sorter??null,sortType:e.sortType??null}):`resource-query:default`,sn=(e,t,n)=>{let r=L(n),i=new Map(e.map(e=>[e.id,e])),a=Array.from(t.values()).filter(e=>e._optimistic?.queryKey===r),o=new Map,s=[];for(let e of a){if(i.has(e.id)){o.set(e.id,e);continue}s.push(e)}let c=[...s,...e.map(e=>o.get(e.id)??e)],l=new Map(t);for(let e of c)l.set(e.id,e);return{changed:!de(c,e)||s.length>0||o.size>0,resourceList:c,resourceMap:l}}})),R,ln,un,dn,fn,pn,mn,hn=e((()=>{fe(),f(),Ae(),Fe(),Pe(),m(),_e(),cn(),R=ve(`document`),ln=new Set([`editor`,`file`,`api`]),un=new Set([j,`application/pdf`]),dn=j,fn=e=>ln.has(e.sourceType)&&un.has(e.fileType),pn=(e,t,n)=>new mn(e,t,n),mn=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}#n=e=>{let{documents:t,localDocumentMap:n}=this.#e();return n.get(e)??t.find(t=>t.id===e)};#r=(e,t)=>e?new Date(e):t;#i=(e,t)=>e===void 0?t:e===null?null:typeof e==`string`?JSON.parse(e):e;#a=(e,t)=>{let n=t.metadata===void 0?e.metadata:{...e.metadata,...t.metadata},r=n?Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0)):{};return{...e,...t,metadata:r,title:t.title||e.title,updatedAt:new Date}};#o=(e,t,n)=>{let{localDocumentMap:r}=this.#e(),i=new Map(r);i.set(e,t),this.#t({localDocumentMap:i},!1,n)};#s=e=>{let{queryParams:t,resourceMap:n}=this.#e();if(!t||t.libraryId!==void 0&&(e.knowledgeBaseId??void 0)!==t.libraryId)return!1;let r=t.q?.trim().toLowerCase();return r&&!`${e.name} ${e.title??``}`.trim().toLowerCase().includes(r)?!1:t.parentId==null?(e.parentId??null)===null:e.parentId?e.parentId===t.parentId?!0:n.get(e.parentId)?.slug===t.parentId:!1};#c=(e,t,n)=>{let r=n?.optimistic??!1,i=new Date;return{...t,_optimistic:r?{error:t?._optimistic?.error,isPending:!0,lastSyncAttempt:t?._optimistic?.lastSyncAttempt,queryKey:L(this.#e().queryParams),retryCount:t?._optimistic?.retryCount??0}:void 0,content:e.content===void 0?t?.content??null:e.content,createdAt:this.#r(e.createdAt,t?.createdAt??i),editorData:this.#i(e.editorData,t?.editorData),fileType:e.fileType??t?.fileType??dn,id:e.id,knowledgeBaseId:e.knowledgeBaseId??t?.knowledgeBaseId,metadata:e.metadata??t?.metadata,name:e.title===void 0?t?.name??t?.title??`Untitled`:e.title??`Untitled`,parentId:e.parentId===void 0?t?.parentId??null:e.parentId,size:e.totalCharCount??t?.size??e.content?.length??0,slug:e.slug===void 0?t?.slug:e.slug,sourceType:O,title:e.title===void 0?t?.title??void 0:e.title??void 0,updatedAt:this.#r(e.updatedAt,t?.updatedAt??i),url:e.source===void 0?t?.url??``:e.source??``}};#l=(e,t)=>
2{let{queryParams:n,removeLocalResource:r,replaceLocalResource:i,resourceList:a,resourceMap:o}=this.#e();if(o.has(e.id)||a.some(t=>t.id===e.id)){!n||this.#s(e)?i(e.id,e):r(e.id);return}t?.allowInsert===!1||!n||this.#s(e)&&i(e.id,e)};createDocument=async({title:e,content:t,knowledgeBaseId:n,parentId:r})=>{let i=Date.now(),a=await N.createDocument({content:t,editorData:`{}`,fileType:dn,knowledgeBaseId:n,metadata:{createdAt:i},parentId:r,title:e});return this.#l(this.#c({content:a.content,createdAt:a.createdAt,editorData:a.editorData,fileType:a.fileType,id:a.id,knowledgeBaseId:n,metadata:a.metadata,parentId:a.parentId,source:a.source,title:a.title,totalCharCount:a.totalCharCount,updatedAt:a.updatedAt},void 0)),a};createFolder=async(e,t,n)=>{let r=Date.now(),i=g(8)(),a=await N.createDocument({content:``,editorData:`{}`,fileType:pe,knowledgeBaseId:n,metadata:{createdAt:r},parentId:t,slug:i,title:e});return this.#l(this.#c({content:a.content,createdAt:a.createdAt,editorData:a.editorData,fileType:a.fileType,id:a.id,knowledgeBaseId:n,metadata:a.metadata,parentId:a.parentId,slug:a.slug,source:a.source,title:a.title,totalCharCount:a.totalCharCount,updatedAt:a.updatedAt},void 0)),a.id};createOptimisticDocument=(e=`Untitled`)=>{let{localDocumentMap:t}=this.#e(),n=`temp-document-${Date.now()}-${Math.random().toString(36).slice(2,9)}`,r=new Date,i={content:null,createdAt:r,editorData:null,fileType:dn,filename:e,id:n,metadata:{},source:`document`,sourceType:b.EDITOR,title:e,totalCharCount:0,totalLineCount:0,updatedAt:r},a=new Map(t);return a.set(n,i),this.#t({localDocumentMap:a},!1,R(`createOptimisticDocument`)),n};duplicateDocument=async e=>{let t=await N.getDocumentById(e);if(!t)throw Error(`Page with ID ${e} not found`);let n=await N.createDocument({content:t.content||``,editorData:t.editorData?typeof t.editorData==`string`?t.editorData:JSON.stringify(t.editorData):`{}`,fileType:t.fileType,metadata:{...t.metadata,createdAt:Date.now(),duplicatedFrom:e},title:`${t.title} (Copy)`}),{localDocumentMap:r}=this.#e(),i=new Map(r),a={content:n.content||null,createdAt:n.createdAt?new Date(n.createdAt):new Date,editorData:typeof n.editorData==`string`?JSON.parse(n.editorData):n.editorData||null,fileType:n.fileType,filename:n.title||n.filename||``,id:n.id,metadata:n.metadata||{},source:`document`,sourceType:b.EDITOR,title:n.title||``,totalCharCount:n.content?.length||0,totalLineCount:0,updatedAt:n.updatedAt?new Date(n.updatedAt):new Date};return i.set(n.id,a),this.#t({localDocumentMap:i},!1,R(`duplicateDocument`)),n};fetchDocumentDetail=async e=>{try{let t=await N.getDocumentById(e);if(!t){console.warn(`[fetchDocumentDetail] Document not found: ${e}`);return}let{localDocumentMap:n}=this.#e(),r=new Map(n),i={content:t.content||null,createdAt:t.createdAt?new Date(t.createdAt):new Date,editorData:typeof t.editorData==`string`?JSON.parse(t.editorData):t.editorData||null,fileType:t.fileType,filename:t.title||t.filename||`Untitled`,id:t.id,metadata:t.metadata||{},source:`document`,sourceType:b.EDITOR,title:t.title||``,totalCharCount:t.content?.length||0,totalLineCount:0,updatedAt:t.updatedAt?new Date(t.updatedAt):new Date};r.set(e,i),this.#t({localDocumentMap:r},!1,R(`fetchDocumentDetail`))}catch(e){console.error(`[fetchDocumentDetail] Failed to fetch document:`,e)}};fetchDocuments=async({pageOnly:e=!1})=>{this.#t({isDocumentListLoading:!0},!1,R(`fetchDocuments/start`));try{let t=Ne.getState().status.pagePageSize||20,n=e?{fileTypes:Array.from(un),sourceTypes:Array.from(ln)}:void 0,r=n?{current:0,pageSize:t,...n}:{current:0,pageSize:t},i=await N.queryDocuments(r),a=i.items.filter(fn).map(e=>({...e,filename:e.filename??e.title??`Untitled`})),o=i.items.length>=t;this.#t({currentPage:0,documentQueryFilter:n,documents:a,documentsTotal:i.total,hasMoreDocuments:o,isDocumentListLoading:!1},!1,R(`fetchDocuments/success`));let{localDocumentMap:s}=this.#e(),c=new Map(s);for(let[e]of s.entries())e.startsWith(`temp-document-`)&&c.delete(e);this.#t({localDocumentMap:c},!1,R(`fetchDocuments/syncLocalMap`))}catch(e){throw console.error(`Failed to fetch pages:`,e),this.#t({isDocumentListLoading:!1},!1,R(`fetchDocuments/error`)),e}};getOptimisticDocuments=()=>{let{localDocumentMap:e,documents:t}=this.#e(),n=new Set,r=t.map(t=>{n.add(t.id);let r=e.get(t.id);return r&&new Date(r.updatedAt)>=new Date(t.updatedAt)?r:t});for(let[t,i]of e.entries())n.has(t)||r.unshift(i);return r};loadMoreDocuments=async()=>{let{currentPage:e,isLoadingMoreDocuments:t,hasMoreDocuments:n,documentQueryFilter:r}=this.#e();if(t||!n)return;let i=e+1;this.#t({isLoadingMoreDocuments:!0},!1,R(`loadMoreDocuments/start`));try{let e=Ne.getState().status.pagePageSize||20,t=r?{current:i,pageSize:e,...r}:{current:i,pageSize:e},n=await N.queryDocuments(t),a=n.items.filter(fn).map(e=>({...e,filename:e.filename??e.title??`Untitled`})),o=n.items.length>=e;this.#t({currentPage:i,documents:[...this.#e().documents,...a],documentsTotal:n.total,hasMoreDocuments:o,isLoadingMoreDocuments:!1},!1,R(`loadMoreDocuments/success`))}catch(e){console.error(`Failed to load more pages:`,e),this.#t({isLoadingMoreDocuments:!1},!1,R(`loadMoreDocuments/error`))}};removeDocument=async e=>{let{localDocumentMap:t,documents:n}=this.#e(),r=new Map(t);r.delete(e);let i=n.filter(t=>t.id!==e);this.#t({documents:i,localDocumentMap:r},!1,R(`removeDocument/optimistic`));try{await N.deleteDocument(e)}catch(e){console.error(`Failed to delete document:`,e);let r=new Map(t);throw this.#t({documents:n,localDocumentMap:r},!1,R(`removeDocument/restore`)),e}};removeTempDocument=e=>{let{localDocumentMap:t}=this.#e(),n=new Map(t);n.delete(e),this.#t({localDocumentMap:n},!1,R(`removeTempDocument`))};replaceTempDocumentWithReal=(e,t)=>{let{localDocumentMap:n}=this.#e(),r=new Map(n);
2r.delete(e),r.set(t.id,t),this.#t({localDocumentMap:r},!1,R(`replaceTempDocumentWithReal`))};updateDocument=async(e,t)=>{await N.updateDocument({content:t.content??void 0,editorData:t.editorData?typeof t.editorData==`string`?t.editorData:JSON.stringify(t.editorData):void 0,id:e,metadata:t.metadata,parentId:t.parentId===void 0?void 0:t.parentId,title:t.title});let n=this.#n(e);if(n){let r=this.#a(n,t);this.#o(e,r,R(`updateDocument`)),this.#l(this.#c(r,this.#e().resourceMap.get(e)));return}let r=this.#e().resourceMap.get(e);r&&this.#l(this.#c({content:t.content,editorData:t.editorData,fileType:r.fileType,id:e,metadata:t.metadata,parentId:t.parentId,title:t.title,updatedAt:new Date},r))};updateDocumentOptimistically=async(e,t)=>{let{localDocumentMap:n,documents:r}=this.#e(),i=n.get(e);if(i||=r.find(t=>t.id===e),!i){console.warn(`[updateDocumentOptimistically] Page not found:`,e);return}let a=this.#e().resourceMap.get(e),o=this.#a(i,t);this.#o(e,o,R(`updateDocumentOptimistically`)),a&&this.#l(this.#c(o,a,{optimistic:!0}));try{await N.updateDocument({id:e,metadata:o.metadata||{},parentId:o.parentId===void 0?void 0:o.parentId,title:o.title||o.filename,...t.content===void 0?{}:{content:o.content??``},...t.editorData===void 0?{}:{editorData:typeof o.editorData==`string`?o.editorData:JSON.stringify(o.editorData||{})}}),a&&this.#l(this.#c(o,a))}catch(t){console.error(`[updateDocumentOptimistically] Failed to sync to DB:`,t);let r=new Map(n);i?r.set(e,i):r.delete(e),this.#t({localDocumentMap:r},!1,R(`revertOptimisticUpdate`)),a&&this.#l(a)}};useFetchDocumentDetail=e=>je(e?[`documentDetail`,e]:null,async()=>{if(!e)return null;let t=await N.getDocumentById(e);return t?{content:t.content||null,createdAt:t.createdAt?new Date(t.createdAt):new Date,editorData:typeof t.editorData==`string`?JSON.parse(t.editorData):t.editorData||null,fileType:t.fileType,filename:t.title||t.filename||`Untitled`,id:t.id,metadata:t.metadata||{},source:`document`,sourceType:b.EDITOR,title:t.title||``,totalCharCount:t.content?.length||0,totalLineCount:0,updatedAt:t.updatedAt?new Date(t.updatedAt):new Date}:(console.warn(`[useFetchDocumentDetail] Document not found: ${e}`),null)},{focusThrottleInterval:5e3,onData:t=>{if(!t)return;let{localDocumentMap:n}=this.#e(),r=new Map(n);r.set(e,t),this.#t({localDocumentMap:r},!1,R(`useFetchDocumentDetail/onData`))},revalidateOnFocus:!0})}})),gn,_n=e((()=>{gn={currentPage:0,documentQueryFilter:void 0,documents:[],documentsTotal:0,hasMoreDocuments:!1,isDocumentListLoading:!1,isLoadingMoreDocuments:!1,localDocumentMap:new Map}})),vn,yn,bn,xn,Sn,Cn,wn=e((()=>{vn=e=>t=>{if(!e)return;let n=t.localDocumentMap.get(e),r=t.documents.find(t=>t.id===e);return n&&r?new Date(n.updatedAt)>=new Date(r.updatedAt)?n:r:n||r},yn=e=>{let t=new Set,n=e.documents.map(n=>{t.add(n.id);let r=e.localDocumentMap.get(n.id);return r&&new Date(r.updatedAt)>=new Date(n.updatedAt)?r:n});for(let[r,i]of e.localDocumentMap.entries())t.has(r)||n.unshift(i);return n},bn=e=>e.hasMoreDocuments,xn=e=>e.isLoadingMoreDocuments,Sn=e=>e.documentsTotal,Cn={documentsTotal:Sn,getDocumentById:vn,getOptimisticDocuments:yn,hasMoreDocuments:bn,isLoadingMoreDocuments:xn}})),Tn=e((()=>{hn(),_n(),wn()}));function En(e,t,n){return n||(n=t,t={}),typeof n!=`function`&&Y(7),rr(e,t,[er],function(e){return tr(Dn(e.data[0],nr(e.data[1])))},1,n)}function Dn(e,t){return Jn(e,{i:2},t&&t.out,t&&t.dictionary)}function On(e,t){if(t){for(var n=``,r=0;r<e.length;r+=16384)n+=String.fromCharCode.apply(null,e.subarray(r,r+16384));return n}else if(ar)return ar.decode(e);else{var i=or(e),a=i.s,n=i.r;return n.length&&Y(8),a}}function kn(e,t,n){n||(n=t,t={}),typeof n!=`function`&&Y(7);var r=[],i=function(){for(var e=0;e<r.length;++e)r[e]()},a={},o=function(e,t){ur(function(){n(e,t)})};ur(function(){o=n});for(var s=e.length-22;Q(e,s)!=101010256;--s)if(!s||e.length-s>65558)return o(Y(13,0,1),null),i;var c=Z(e,s+8);if(c){var l=c,u=Q(e,s+16),d=Q(e,s-20)==117853008;if(d){var f=Q(e,s-12);d=Q(e,f)==101075792,d&&(l=c=Q(e,f+32),u=Q(e,f+48))}for(var p=t&&t.filter,m=function(t){var n=cr(e,u,d),s=n[0],l=n[1],f=n[2],m=n[3],h=n[4],g=n[5],_=sr(e,g);u=h;var v=function(e,t){e?(i(),o(e,null)):(t&&(a[m]=t),--c||o(null,a))};if(!p||p({name:m,size:l,originalSize:f,compression:s}))if(!s)v(null,Kn(e,_,_+l));else if(s==8){var y=e.subarray(_,_+l);if(f<524288||l>.8*f)try{v(null,Dn(y,{out:new z(f)}))}catch(e){v(e,null)}else r.push(En(y,{size:f},v))}else v(Y(14,`unknown compression type `+s,1),null);else v(null,null)},h=0;h<l;++h)m(h)}else o(null,{});return i}var An,jn,z,B,Mn,Nn,Pn,Fn,In,Ln,Rn,zn,Bn,Vn,V,H,U,W,G,Hn,Un,Wn,K,q,J,Gn,Kn,qn,Y,Jn,Yn,Xn,Zn,X,Qn,$n,er,tr,nr,rr,Z,Q,ir,ar,or,sr,cr,lr,ur,dr=e((()=>{for(An={},jn=(function(e,t,n,r,i){var a=new Worker(An[t]||(An[t]=URL.createObjectURL(new Blob([e+`;addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})`],{type:`text/javascript`}))));return a.onmessage=function(e){var t=e.data,n=t.$e$;if(n){var r=Error(n[0]);r.code=n[1],r.stack=n[2],i(r,null)}else i(null,t)},a.postMessage(n,r),a}),z=Uint8Array,B=Uint16Array,Mn=Int32Array,Nn=new z([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Pn=new z([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Fn=new z([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),In=function(e,t){for(var n=new B(31),r=0;r<31;++r)n[r]=t+=1<<e[r-1];for(var i=new Mn(n[30]),r=1;r<30;++r)for(var a=n[r];a<n[r+1];++a)i[a]=a-n[r]<<5|r;return{b:n,r:i}},Ln=In(Nn,2),Rn=Ln.b,zn=Ln.r,Rn[28]=258,zn[258]=28,Bn=In(Pn,0),Vn=Bn.b,Bn.r,V=new B(32768),H=0;H<32768;++H)U=(H&43690)>>1|(H&21845)<<1,U=(U&52428)>>2|(U&13107)<<2,U=(U&61680)>>4|(U&3855)<<4,V[H]=((U&65280)>>8|(U&255)<<8)>>1;for(W=(function(e,t,n){for(var r=e.length,i=0,a=new B(t);i<r;++i)e[i]&&++a[e[i]-1];var o=new B(t);for(i=1;i<t;++i)o[i]=o[i-1]+a[i-1]<<1;var s;if(n){s=new B(1<<t);var c=15-t;for(i=0;i<r;++i)if(e[i])for(var l=i<<4|e[i],u=t-e[i],d=o[e[i]-1]++<<u,f=d|(1<<u)-1;d<=f;++d)s[V[d]>>c]=l}else for(s=new B(r),i=0;i<r;++i)e[i]&&(s[i]=V[o[e[i]-1]++]>>15-e[i]);return s}),G=new z(288),H=0;H<144;++H)G[H]=8;for(H=144;H<256;++H)G[H]=9;for(H=256;H<280;++H)G[H]=7;for(H=280;H<288;++H)G[H]=8;for(Hn=new z(32),H=0;H<32;++H)Hn[H]=5;Un=W(G,9,1),Wn=W(Hn,5,1),K=function(e){for(var t=e[0],n=1;n<e.length;++n)e[n]>t&&(t=e[n]);return t},q=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},J=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Gn=function(e){return(e+7)/8|0},Kn=function(e,t,n){return(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length),new z(e.subarray(t,n))},qn=[`unexpected EOF`,`invalid block type`,`invalid length/literal`,`invalid distance`,`stream finished`,`no stream handler`,,`no callback`,`invalid UTF-8 data`,`extra field too long`,`date not in range 1980-2099`,`filename too long`,`stream finishing`,`invalid zip data`],Y=function(e,t,n){var r=Error(t||qn[e]);if(r.code=e,Error.captureStackTrace&&Error.captureStackTrace(r,Y),!n)throw r;return r},Jn=function(e,t,n,r){var i=e.length,a=r?r.length:0;if(!i||t.f&&!t.l)return n||new z(0);var o=!n,s=o||t.i!=2,c=t.i;o&&(n=new z(i*3));var l=function(e){var t=n.length;if(e>t){var r=new z(Math.max(t*2,e));r.set(n),n=r}},u=t.f||0,d=t.p||0,f=t.b||0,p=t.l,m=t.d,h=t.m,g=t.n,_=i*8;do{if(!p){u=q(e,d,1);var v=q(e,d+1,3);if(d+=3,!v){var y=Gn(d)+4,ee=e[y-4]|e[y-3]<<8,te=y+ee;if(te>i){c&&Y(0);break}s&&l(f+ee),n.set(e.subarray(y,te),f),t.b=f+=ee,t.p=d=te*8,t.f=u;continue}else if(v==1)p=Un,m=Wn,h=9,g=5;else if(v==2){var ne=q(e,d,31)+257,b=q(e,d+10,15)+4,re=ne+q(e,d+5,31)+1;d+=14;for(var x=new z(re),S=new z(19),C=0;C<b;++C)S[Fn[C]]=q(e,d+C*3,7);d+=b*3;for(var ie=K(S),ae=(1<<ie)-1,w=W(S,ie,1),C=0;C<re;){var oe=w[q(e,d,ae)];d+=oe&15;var y=oe>>4;if(y<16)x[C++]=y;else{var T=0,E=0;for(y==16?(E=3+q(e,d,3),d+=2,T=x[C-1]):y==17?(E=3+q(e,d,7),d+=3):y==18&&(E=11+q(e,d,127),d+=7);E--;)x[C++]=T}}var se=x.subarray(0,ne),D=x.subarray(ne);h=K(se),g=K(D),p=W(se,h,1),m=W(D,g,1)}else Y(1);if(d>_){c&&Y(0);break}}s&&l(f+131072);for(var ce=(1<<h)-1,le=(1<<g)-1,ue=d;;ue=d){var T=p[J(e,d)&ce],O=T>>4;if(d+=T&15,d>_){c&&Y(0);break}if(T||Y(2),O<256)n[f++]=O;else if(O==256){ue=d,p=null;break}else{var de=O-254;if(O>264){var C=O-257,k=Nn[C];de=q(e,d,(1<<k)-1)+Rn[C],d+=k}var A=m[J(e,d)&le],j=A>>4;A||Y(3),d+=A&15;var D=Vn[j];if(j>3){var k=Pn[j];D+=J(e,d)&(1<<k)-1,d+=k}if(d>_){c&&Y(0);break}s&&l(f+131072);var fe=f+de;if(f<D){var pe=a-D,me=Math.min(D,fe);for(pe+f<0&&Y(3);f<me;++f)n[f]=r[pe+f]}for(;f<fe;++f)n[f]=n[f-D]}}t.l=p,t.p=ue,t.b=f,t.f=u,p&&(u=1,t.m=h,t.d=m,t.n=g)}while(!u);return f!=n.length&&o?Kn(n,0,f):n.subarray(0,f)},Yn=new z(0),Xn=function(e,t){var n={};for(var r in e)n[r]=e[r];for(var r in t)n[r]=t[r];return n},Zn=function(e,t,n){for(var r=e(),i=e.toString(),a=i.slice(i.indexOf(`[`)+1,i.lastIndexOf(`]`)).replace(/\s+/g,``).split(`,`),o=0;o<r.length;++o){var s=r[o],c=a[o];if(typeof s==`function`){t+=`;`+c+`=`;var l=s.toString();if(s.prototype)if(l.indexOf(`[native code]`)!=-1){var u=l.indexOf(` `,8)+1;t+=l.slice(u,l.indexOf(`(`,u))}else for(var d in t+=l,s.prototype)t+=`;`+c+`.prototype.`+d+`=`+s.prototype[d].toString();else t+=l}else n[c]=s}return t},X=[],Qn=function(e){var t=[];for(var n in e)e[n].buffer&&t.push((e[n]=new e[n].constructor(e[n])).buffer);return t},$n=function(e,t,n,r){if(!X[n]){for(var i=``,a={},o=e.length-1,s=0;s<o;++s)i=Zn(e[s],i,a);X[n]={c:Zn(e[o],i,a),e:a}}var c=Xn({},X[n].e);return jn(X[n].c+`;onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=`+t.toString()+`}`,n,c,Qn(c),r)},er=function(){return[z,B,Mn,Nn,Pn,Fn,Rn,Vn,Un,Wn,V,qn,W,K,q,J,Gn,Kn,Y,Jn,Dn,tr,nr]},tr=function(e){return postMessage(e,[e.buffer])},nr=function(e){return e&&{out:e.size&&new z(e.size),dictionary:e.dictionary}},rr=function(e,t,n,r,i,a){var o=$n(n,r,i,function(e,t){o.terminate(),a(e,t)});return o.postMessage([e,t],t.consume?[e.buffer]:[]),function(){o.terminate()}},Z=function(e,t){return e[t]|e[t+1]<<8},Q=function(e,t){return(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0},ir=function(e,t){return Q(e,t)+Q(e,t+4)*4294967296},ar=typeof TextDecoder<`u`&&new TextDecoder;try{ar.decode(Yn,{stream:!0})}catch{}or=function(e){for(var t=``,n=0;;){var r=e[n++],i=(r>127)+(r>223)+(r>239);if(n+i>e.length)return{s:t,r:Kn(e,n-1)};i?i==3?(r=((r&15)<<18|(e[n++]&63)<<12|(e[n++]&63)<<6|e[n++]&63)-65536,t+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?t+=String.fromCharCode((r&31)<<6|e[n++]&63):t+=String.fromCharCode((r&15)<<12|(e[n++]&63)<<6|e[n++]&63):t+=String.fromCharCode(r)}},sr=function(e,t){return t+30+Z(e,t+26)+Z(e,t+28)},cr=function(e,t,n){var r=Z(e,t+28),i=Z(e,t+30),a=On(e.subarray(t+46,t+46+r),!(Z(e,t+8)&2048)),o=t+46+r,s=lr(e,o,i,n,Q(e,t+20),Q(e,t+24),Q(e,t+42)),c=s[0],l=s[1],u=s[2];return[Z(e,t+10),c,l,a,o+i+Z(e,t+32),u]},lr=function(e,t,n,r,i,a,o){var s=i==4294967295,c=a==4294967295,l=o==4294967295,u=t+n,d=s+c+l;if(r&&d){for(;t+4<u;t+=4+Z(e,t+2))if(Z(e,t)==1)return[s?ir(e,t+4+8*c):i,c?ir(e,t+4):a,l?ir(e,t+4+8*(c+s)):o,1];r<2&&Y(13)}return[i,a,o,0]},ur=typeof queueMicrotask==`function`?queueMicrotask:typeof setTimeout==`function`?setTimeout:function(e){e()}})),fr,pr,mr=e((()=>{dr(),fr=e=>({bmp:`image/bmp`,c:`text/x-c`,cpp:`text/x-c++`,cs:`text/x-csharp`,css:`text/css`,csv:`text/csv`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,gif:`image/gif`,go:`text/x-go`,html:`text/html`,java:`text/x-java`,jpeg:`image/jpeg`,jpg:`image/jpeg`,js:`text/javascript`,json:`application/json`,jsx:`text/javascript`,md:`text/markdown`,pdf:`application/pdf`,php:`application/x-httpd-php`,png:`image/png`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`,py:`text/x-python`,rb:`text/x-ruby`,rs:`text/x-rust`,rtf:`application/rtf`,sh:`a
2pplication/x-sh`,svg:`image/svg+xml`,ts:`text/typescript`,tsx:`text/typescript`,txt:`text/plain`,webp:`image/webp`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,xml:`application/xml`})[e.split(`.`).pop()?.toLowerCase()||``]||`application/octet-stream`,pr=async e=>new Promise((t,n)=>{e.arrayBuffer().then(e=>{kn(new Uint8Array(e),(e,r)=>{if(e){n(e);return}let i=[];for(let[e,t]of Object.entries(r)){if(e.endsWith(`/`)||e.includes(`__MACOSX`)||e.startsWith(`.`))continue;let n=e.split(`/`).pop()||e,r=new Blob([new Uint8Array(t)],{type:fr(n)}),a=new File([r],n,{type:fr(n)});i.push(a)}t(i)})}).catch(()=>{n(Error(`Failed to read ZIP file`))})})})),hr,gr,_r,vr,yr,br,xr,Sr,Cr,wr,Tr,Er,Dr,Or=e((()=>{hr=new Set([`uploading`,`pending`,`processing`]),gr=e=>e.dockUploadFileList,_r=e=>e.dockUploadFileList.map(e=>e.file),vr=e=>t=>{if(e)return t.fileList.find(t=>t.id===e)},yr=e=>t=>{if(e)return vr(e)(t)??t.resourceMap.get(e)??[...t.resourceMap.values()].find(t=>t.fileId===e)??t.resourceList.find(t=>t.id===e||t.fileId===e)},br=e=>e.fileId??e.id,xr=e=>e.dockUploadFileList.some(e=>hr.has(e.status)),Sr=e=>e.dockUploadFileList.length===0?`pending`:e.dockUploadFileList.some(e=>hr.has(e.status))?`uploading`:`success`,Cr=e=>{let t=e.dockUploadFileList.filter(e=>e.status===`uploading`||e.status===`pending`);if(t.length===0)return 100;let n=t.length*100;return t.reduce((e,t)=>e+(t.uploadState?.progress||0),0)/n*100},wr=e=>t=>t.creatingChunkingTaskIds.includes(e),Tr=e=>t=>t.creatingEmbeddingTaskIds.includes(e),Er=e=>e.fileListHasMore,Dr={dockFileList:gr,dockRawFileList:_r,fileListHasMore:Er,getFileByChunkTargetId:yr,getFileById:vr,isCreatingChunkEmbeddingTask:Tr,isCreatingFileParseTask:wr,isUploadingFiles:xr,overviewUploadingProgress:Cr,overviewUploadingStatus:Sr}})),$,kr,Ar,jr=e((()=>{f(),a(),De(),Te(),k(),Ae(),Me(),Fe(),ze(),Je(),_t(),Ge(),mr(),Or(),y(),$=new Re,kr=(e,t,n)=>new Ar(e,t,n),Ar=class{#e;#t;constructor(e,t,n){this.#t=e,this.#e=t}#n=async e=>{let t=Dr.getFileByChunkTargetId(e)(this.#e());if(t?.fileId)return t.fileId;if(!e.startsWith(`docs_`))return e;try{return(await P.getKnowledgeItem(e))?.fileId??e}catch{return e}};#r=async e=>Promise.all(e.map(e=>this.#n(e)));#i=(e,t,n,r,i)=>({...this.#e().resourceMap.get(t.id)||{createdAt:new Date,fileType:e.type||`application/octet-stream`,name:e.name,size:e.size,sourceType:`file`},_optimistic:void 0,id:t.id,knowledgeBaseId:n,name:e.name,parentId:r,size:e.size,updatedAt:new Date,url:t.url,...i===void 0?{}:{visibility:i}});#a=(e,t,n,r,i)=>{this.#e().insertLocalResource({fileType:t.type||`application/octet-stream`,knowledgeBaseId:n,name:t.name,parentId:r,size:t.size,sourceType:`file`,url:``,...i===void 0?{}:{visibility:i}},e)};cancelUpload=e=>{let{dockUploadFileList:t,dispatchDockFileList:n}=this.#e(),r=t.find(t=>t.id===e);r?.abortController&&r.abortController.abort(),n({id:e,status:`cancelled`,type:`updateFileStatus`})};cancelUploads=e=>{if(e.length===0)return;let{dockUploadFileList:t,dispatchDockFileList:n}=this.#e(),r=new Set(e),i=[];for(let e of t)r.has(e.id)&&(e.abortController?.abort(),i.push(e.id));i.length!==0&&n({ids:i,status:`cancelled`,type:`updateFileStatuses`})};dispatchDockFileList=e=>{let t=gt(this.#e().dockUploadFileList,e);t!==this.#e().dockUploadFileList&&this.#t({dockUploadFileList:t},!1,`dispatchDockFileList/${e.type}`)};embeddingChunks=async e=>{let t=await this.#r(e);this.#e().toggleEmbeddingIds(t);let n=t.map(async e=>{try{await I.createEmbeddingChunksTask(e)}catch(e){console.error(e)}});await Promise.all(n),await this.#e().refreshFileList(),this.#e().toggleEmbeddingIds(t,!1)};loadMoreKnowledgeItems=async()=>{let{queryListParams:e,fileList:t,fileListOffset:n,fileListHasMore:r}=this.#e();if(!(!r||!e))try{let r=await $.getKnowledgeItems({...e,limit:e.limit??50,offset:n}),i=new Set(t.map(e=>e.id)),a=r.items.filter(e=>!i.has(e.id)),o=[...t,...a];this.#t({fileList:o,fileListHasMore:r.hasMore,fileListOffset:n+a.length}),await ke(M.knowledgeItems(e),o,{revalidate:!1})}catch(e){console.error(`Failed to load more knowledge items:`,e)}};moveFileToFolder=async(e,t)=>{await ke(e=>Array.isArray(e)&&e[0]===M.knowledgeItems.root,async n=>n&&n.map(n=>n.id===e?{...n,parentId:t}:n),{revalidate:!1}),await P.updateFile(e,{parentId:t}),await this.#e().refreshFileList()};parseFilesToChunks=async(e,t)=>{let n=await this.#r(e);this.#e().toggleParsingIds(n);let r=n.map(async e=>{try{await I.createParseFileTask(e,t?.skipExist)}catch(e){console.error(e)}});await Promise.all(r),await this.#e().refreshFileList(),this.#e().toggleParsingIds(n,!1)};pushDockFileList=async(e,t,n,r)=>{let{dispatchDockFileList:i}=this.#e(),a=g(12),o=[];for(let t of e)if(t.type===`application/zip`||t.name.endsWith(`.zip`))try{let e=await pr(t);o.push(...e)}catch(e){console.error(`Failed to extract ZIP file:`,e),o.push(t)}else o.push(t);let s=o.filter(e=>!A.includes(e.name)).map(e=>({abortController:new AbortController,file:e,id:`upload_${a()}`,status:`pending`}));for(let e of s)this.#a(e.id,e.file,t,n,r);i({atStart:!0,files:s,type:`addFiles`});let c=(await Ee(s,async e=>{let a=await this.#e().uploadWithProgress({abortController:e.abortController,file:e.file,knowledgeBaseId:t,onStatusUpdate:i,parentId:n,uploadId:e.id,visibility:r});return a?this.#e().replaceLocalResource(e.id,this.#i(e.file,a,t,n,r)):this.#e().removeLocalResource(e.id),{file:e.file,fileId:a?.id,fileType:e.file.type}},{concurrency:10}).catch(e=>{for(let e of s)this.#e().removeLocalResource(e.id);throw e})).filter(({fileType:e,fileId:t})=>t&&!We(e)).map(({fileId:e})=>e);c.length>0&&await this.#e().parseFilesToChunks(c,{skipExist:!1})};reEmbeddingChunks=async e=>{let t=await this.#n(e);Dr.isCreatingChunkEmbeddingTask(t)(this.#e())||(this.#e().toggleEmbeddingIds([t]),await $.removeFileAsyncTask(t,`embedding`),await this.#e().refreshFileList(),await I.createEmbeddingChunksTask(t),await this.#e().refreshFileList(),this.#e().toggleEmbeddingIds([t],!1))};reParseFile=async e=>{let t=await this.#n(e);this.#e().toggleParsingIds([t]),await I.retryParseFile(t),await this.#e().refreshFileList(),this.#e().toggleParsingIds([t],!1)};#o=async()=>{await ke(e=>Array.isArray(e)&&e[0]===M.knowledgeItems.root,async e=>e,{revalidate:!0})};refreshFileList=async e=>{if(await this.#o(),e?.revalidateResources===!1)return;let{revalidateResources:t}=await te(async()=>{let{revalidateResources:e}=await import(`./hooks-mpVIaQOb.js`).then(e=>(e.n(),e.t));return{revalidateResources:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]));await t()};publishFileToWorkspace=async e=>{await P.publishFileToWorkspace(e),await this.#e().refreshFileList()};setFileVisibility=async(e,t)=>{await P.setFileVisibility(e,t),await this.#e().refreshFileList()};removeFileItem=async e=>{await P.removeFile(e),await this.#e().refreshFileList()};removeFiles=async e=>{await P.removeFiles(e),await this.#e().refreshFileList()};
2renameFolder=async(e,t)=>{await ke(e=>Array.isArray(e)&&e[0]===M.knowledgeItems.root,async n=>n&&n.map(n=>n.id===e?{...n,name:t}:n),{revalidate:!1}),await N.updateDocument({id:e,title:t}),await this.#e().refreshFileList()};setCurrentFolderId=e=>{this.#t({currentFolderId:e},!1,`setCurrentFolderId`)};setPendingRenameItemId=e=>{this.#t({pendingRenameItemId:e},!1,`setPendingRenameItemId`)};setUploadDockExpanded=e=>{this.#t({uploadDockExpanded:e},!1,`setUploadDockExpanded`)};toggleEmbeddingIds=(e,t)=>{this.#t(n=>{let r=new Set(n.creatingEmbeddingTaskIds);return e.forEach(e=>{t===void 0?r.has(e)?r.delete(e):r.add(e):t?r.add(e):r.delete(e)}),{creatingEmbeddingTaskIds:Array.from(r.values())}})};toggleParsingIds=(e,t)=>{this.#t(n=>{let r=new Set(n.creatingChunkingTaskIds);return e.forEach(e=>{t===void 0?r.has(e)?r.delete(e):r.add(e):t?r.add(e):r.delete(e)}),{creatingChunkingTaskIds:Array.from(r.values())}})};uploadFolderWithStructure=async(e,t,r)=>{let{dispatchDockFileList:i}=this.#e(),a=g(12),{filesByFolder:o,folders:s}=u(e),c=l(s),d=`uploadFolder.creatingFolders`;c.length>0&&be.loading({content:n(`header.actions.uploadFolder.creatingFolders`,{ns:`file`}),duration:0,key:d});try{let e=new Map,n=new Map;for(let e of c){let t=(e.match(/\//g)||[]).length;n.has(t)||n.set(t,[]),n.get(t).push(e)}let l=g(8),u=Array.from(n.keys()).sort((e,t)=>e-t);for(let i of u){let a=n.get(i),o=a.map(n=>{let i=s[n],a=i.parent?e.get(i.parent):r,o=p(i.name),c=l();return{content:``,editorData:`{}`,fileType:`custom/folder`,knowledgeBaseId:t,metadata:{createdAt:Date.now()},parentId:a,slug:c,title:o}}),c=await N.createDocuments(o);for(let[t,n]of a.entries())e.set(n,c[t].id)}c.length>0&&be.destroy(d),await this.#e().refreshFileList();let f=[];for(let[t,n]of Object.entries(o)){let i=t?e.get(t):r;f.push(...n.map(e=>({file:e,parentId:i})))}let m=f.filter(({file:e})=>!A.includes(e.name)).map(({file:e,parentId:t})=>({abortController:new AbortController,file:e,id:`upload_${a()}`,parentId:t,shouldShowInCurrentList:(t??void 0)===r}));i({atStart:!0,files:m.map(({abortController:e,file:t,id:n})=>({abortController:e,file:t,id:n,status:`pending`})),type:`addFiles`});for(let e of m)e.shouldShowInCurrentList&&this.#a(e.id,e.file,t,e.parentId);let h=(await Ee(m,async({abortController:e,file:n,id:r,parentId:a,shouldShowInCurrentList:o})=>{let s=await this.#e().uploadWithProgress({abortController:e,file:n,knowledgeBaseId:t,onStatusUpdate:i,parentId:a,uploadId:r});return o&&(s?this.#e().replaceLocalResource(r,this.#i(n,s,t,a)):this.#e().removeLocalResource(r)),{file:n,fileId:s?.id,fileType:n.type}},{concurrency:10}).catch(e=>{for(let e of m)e.shouldShowInCurrentList&&this.#e().removeLocalResource(e.id);throw e})).filter(({fileType:e,fileId:t})=>t&&!We(e)).map(({fileId:e})=>e);h.length>0&&await this.#e().parseFilesToChunks(h,{skipExist:!1})}catch(e){throw c.length>0&&be.destroy(d),e}};useFetchFolderBreadcrumb=e=>Oe(e?[`useFetchFolderBreadcrumb`,e]:null,async()=>await $.getFolderBreadcrumb(e));useFetchKnowledgeItem=e=>Oe(e?[`useFetchKnowledgeItem`,e]:null,async()=>await $.getKnowledgeItem(e)??void 0);useFetchKnowledgeItems=e=>Oe(M.knowledgeItems(e),async()=>{let t=await $.getKnowledgeItems({...e,limit:e.limit??50,offset:0});return this.#t({fileList:t.items,fileListHasMore:t.hasMore,fileListOffset:t.items.length,queryListParams:e}),t.items})}})),Mr,Nr=e((()=>{Mr={creatingChunkingTaskIds:[],creatingEmbeddingTaskIds:[],currentFolderId:void 0,dockUploadFileList:[],fileList:[],fileListHasMore:!1,fileListOffset:0,pendingRenameItemId:null,uploadDockExpanded:!0}})),Pr=e((()=>{jr(),Nr(),Or()})),Fr,Ir=e((()=>{Fr={hasMore:!1,isLoadingMore:!1,isSyncing:!1,offset:0,resourceList:[],resourceMap:new Map,syncQueue:[],syncingIds:new Set,total:0}})),Lr,Rr=e((()=>{Yt(),on(),Tn(),Pr(),Ir(),Lr={...Lt,...gn,...Mr,...$t,...Fr}})),zr,Br,Vr,Hr,Ur=e((()=>{zr=t(d()),Le(),Be(),st(),Ir(),cn(),Br=(0,zr.default)(`resource-manager:action`),Vr=e=>e instanceof Error?e:Error(String(e)),Hr=class{#e;#t;#n;#r;constructor(e,t,n){this.#e=t,this.#n=e,this.#t={getState:()=>{let e=this.#e();return{hasMore:e.hasMore,isLoadingMore:e.isLoadingMore,isSyncing:e.isSyncing,lastSyncTime:e.lastSyncTime,offset:e.offset,queryParams:e.queryParams,resourceList:e.resourceList,resourceMap:e.resourceMap,syncError:e.syncError,syncQueue:e.syncQueue,syncingIds:e.syncingIds,total:e.total}},setState:e=>{this.#n(e,!1,`resourceSyncEngine/setState`)}}}#i=e=>{this.#n(t=>{if(!t.syncingIds.has(e))return{};let n=new Set(t.syncingIds);return n.delete(e),{syncingIds:n}},!1,`resource/clearSyncingId`)};#a=e=>{let{_optimistic:t,...n}=e;return n};#o=(e,t)=>({_optimistic:{isPending:!0,queryKey:L(this.#e().queryParams),retryCount:0},createdAt:new Date,fileType:e.fileType,id:t||`temp-resource-${Date.now()}-${Math.random().toString(36).slice(2,11)}`,knowledgeBaseId:e.knowledgeBaseId,metadata:e.metadata,name:`title`in e?e.title:e.name,parentId:e.parentId,size:`size`in e?e.size:0,sourceType:e.sourceType,updatedAt:new Date,...e.sourceType===`file`?{url:e.url,...e.visibility===void 0?{}:{visibility:e.visibility}}:{content:e.content,editorData:e.editorData??{},slug:e.slug,title:e.title}}
2);#s=()=>(this.#r||=new ot(this.#t,{maxRetries:1,onMutationError:(e,t)=>{this.#n({syncError:Vr(t)},!1,`resourceSyncEngine/error`)},onMutationSuccess:()=>{this.#n({lastSyncTime:new Date,syncError:void 0},!1,`resourceSyncEngine/success`)},onQueueChange:e=>{this.#n({isSyncing:e.some(e=>e.status===`pending`||e.status===`inflight`),syncQueue:e},!1,`resourceSyncEngine/queueChange`)}}),this.#r);#c=(e,t)=>{let{resourceList:n,resourceMap:r}=this.#e(),i=new Map(r);i.delete(e),i.set(t.id,t);let a=n.findIndex(t=>t.id===e),o=n.filter(n=>n.id!==e&&n.id!==t.id);if(a!==-1||this.#l(t)){let e=a===-1?0:Math.min(a,o.length);o.splice(e,0,t)}this.#n({resourceList:o,resourceMap:i},!1,`resource/replaceLocalResource`)};#l=e=>{let{queryParams:t,resourceMap:n}=this.#e();if(!t||t.libraryId!==void 0&&(e.knowledgeBaseId??void 0)!==t.libraryId)return!1;let r=t.q?.trim().toLowerCase();return r&&!`${e.name} ${e.title??``}`.trim().toLowerCase().includes(r)?!1:t.parentId==null?(e.parentId??null)===null:e.parentId?e.parentId===t.parentId?!0:n.get(e.parentId)?.slug===t.parentId:!1};#u=(e,t,n,r)=>{this.#n(n=>{if(e.size===0)return{};let i=new Map(n.resourceMap),a=!1,o=0,s=n.resourceList.flatMap(n=>{if(!e.has(n.id))return[n];let r=t(i.get(n.id)??n);return o+=1,a=!0,r?(i.set(r.id,r),[r]):(i.delete(n.id),[])});for(let r of e){if(n.resourceList.some(e=>e.id===r))continue;let e=i.get(r);if(!e)continue;let o=t(e);if(a=!0,!o){i.delete(r);continue}i.set(o.id,o)}if(!a)return{};let c={...n,resourceList:s,resourceMap:i};return r?.(c,{visibleChangedCount:o}),c},!1,n)};#d=(e,t)=>({...e,...t,_optimistic:{...e._optimistic||{queryKey:L(this.#e().queryParams),retryCount:0},isPending:!0},updatedAt:t?.updatedAt??new Date});clearResources=()=>{this.#n({...Fr},!1,`resource/clearResources`)};clearCurrentQueryResources=()=>{this.#n(e=>{let t=new Set(e.resourceList.map(e=>e.id)),n=new Set(Array.from(e.syncingIds).filter(e=>!t.has(e))),r=new Map;for(let[n,i]of e.resourceMap)!t.has(n)&&i._optimistic&&r.set(n,i);return{hasMore:!1,offset:0,resourceList:[],resourceMap:r,syncingIds:n,total:0}},!1,`resource/clearCurrentQueryResources`)};createResource=async e=>{let t=this.#o(e),n=this.#s().createTransaction(`createResource(${t.id})`);return n.set(e=>{e.resourceList.unshift(t),e.resourceMap.set(t.id,t),e.syncingIds.add(t.id)}),n.mutation=()=>F.createResource(e),n.onSuccess=async e=>{this.#c(t.id,e),this.#i(t.id)},n.onError=async e=>{this.#i(t.id),this.markLocalResourceError(t.id,Vr(e))},n.commit().catch(e=>{console.error(`Failed to create resource:`,e)}),t.id};createResourceAndSync=async e=>{let t=this.#o(e),n=this.#s().createTransaction(`createResourceAndSync(${t.id})`);return n.set(e=>{e.resourceList.unshift(t),e.resourceMap.set(t.id,t),e.syncingIds.add(t.id)}),n.mutation=()=>F.createResource(e),n.onSuccess=async e=>{this.#c(t.id,e),this.#i(t.id)},n.onError=async e=>{this.#i(t.id),this.markLocalResourceError(t.id,Vr(e))},(await n.commit()).id};deleteResource=async e=>{let t=this.#s().createTransaction(`deleteResource(${e})`);t.set(t=>{t.resourceList=t.resourceList.filter(t=>t.id!==e),t.resourceMap.delete(e)}),t.mutation=()=>F.deleteResource(e),await t.commit()};deleteResources=async e=>{if(e.length===0)return;let t=new Set(e),n=this.#s().createTransaction(`deleteResources(${e.join(`,`)})`);n.set(e=>{e.resourceList=e.resourceList.filter(e=>!t.has(e.id));for(let n of t)e.resourceMap.delete(n)}),n.mutation=()=>F.deleteResources(e),await n.commit()};flushSync=async()=>{await this.#s().flush()};insertLocalResource=(e,t)=>{let n=this.#o(e,t);return this.#n(e=>{let t=new Map(e.resourceMap);return t.set(n.id,n),{resourceList:[n,...e.resourceList],resourceMap:t}},!1,`resource/insertLocalResource`),n.id};patchLocalResource=(e,t,n=`resource/patchLocalResource`)=>{this.#u(new Set([e]),e=>({...e,...t}),n)};patchLocalResourceStatuses=e=>{if(e.length===0)return;let t=new Map(e.map(e=>[e.id,e])),n=new Map;for(let e of this.#e().resourceList){let r=t.get(e.id)??(e.fileId&&t.get(e.fileId));r&&n.set(e.id,r)}this.#u(new Set(n.keys()),e=>{let t=n.get(e.id);return t?{...e,chunkCount:t.chunkCount===void 0?e.chunkCount:t.chunkCount,chunkingError:t.chunkingError===void 0?e.chunkingError:t.chunkingError,chunkingStatus:t.chunkingStatus===void 0?e.chunkingStatus:t.chunkingStatus,embeddingError:t.embeddingError===void 0?e.embeddingError:t.embeddingError,embeddingStatus:t.embeddingStatus===void 0?e.embeddingStatus:t.embeddingStatus,finishEmbedding:t.finishEmbedding===void 0?e.finishEmbedding:t.finishEmbedding}:e},`resource/patchLocalResourceStatuses`)};loadMoreResources=async()=>{let{hasMore:e,offset:t,queryParams:n}=this.#e();if(!(!e||!n)){this.#n({isLoadingMore:!0},!1,`resource/loadMoreResources/start`);try{let{items:e}=await F.queryResources({...n,limit:50,offset:t});this.#n(n=>{let r=new Set(n.resourceList.map(e=>e.id)),i=new Map(n.resourceMap);for(let t of e)i.set(t.id,t);return{hasMore:e.length===50,isLoadingMore:!1,offset:t+e.length,resourceList:[...n.resourceList,...e.filter(e=>!r.has(e.id))],resourceMap:i}},!1,`resource/loadMoreResources/success`)}catch(e){throw this.#n({isLoadingMore:!1},!1,`resource/loadMoreResources/error`),e}}};markLocalResourceError=(e,t)=>
2{let{resourceMap:n}=this.#e(),r=n.get(e);if(!r)return;let i={...r,_optimistic:{...r._optimistic||{isPending:!1,queryKey:L(this.#e().queryParams),retryCount:0},error:t,isPending:!1,lastSyncAttempt:new Date}};this.#n(t=>{let n=new Map(t.resourceMap);return n.set(e,i),{resourceList:t.resourceList.map(t=>t.id===e?i:t),resourceMap:n}},!1,`resource/markLocalResourceError`)};moveResource=async(e,t)=>{let{queryParams:n,resourceMap:r}=this.#e(),i=r.get(e);if(!i){console.warn(`Resource ${e} not found for move`);return}if((i.parentId??null)===t)return;let a=this.#s().createTransaction(`moveResource(${e})`),o={...i,_optimistic:{...i._optimistic||{queryKey:L(this.#e().queryParams),retryCount:0},isPending:!0},parentId:t,updatedAt:new Date},s=!n||this.#l(o);a.set(t=>{if(s){t.resourceMap.set(e,o),t.resourceList=t.resourceList.map(t=>t.id===e?o:t);return}t.resourceList=t.resourceList.filter(t=>t.id!==e),t.resourceMap.delete(e)}),a.mutation=()=>F.moveResource(e,t),a.onSuccess=async t=>{s&&this.#c(e,t)},await a.commit()};removeLocalResource=e=>{this.#n(t=>{let n=new Map(t.resourceMap);return n.delete(e),{resourceList:t.resourceList.filter(t=>t.id!==e),resourceMap:n}},!1,`resource/removeLocalResource`)};replaceLocalResource=(e,t)=>{this.#c(e,t)};retrySync=async()=>{await this.flushSync()};addResourcesToKnowledgeBase=async(e,t)=>{if(t.length===0)return;let n=new Set(t),r=this.#s().createTransaction(`addResourcesToKnowledgeBase(${e})`);r.set(t=>{for(let r of t.resourceList){if(!n.has(r.id))continue;let i=this.#d(r,{knowledgeBaseId:e});t.resourceMap.set(r.id,i)}t.resourceList=t.resourceList.map(e=>n.has(e.id)?t.resourceMap.get(e.id)??e:e)}),r.mutation=()=>Ie.addFilesToKnowledgeBase(e,t),r.onSuccess=async()=>{this.#u(n,t=>this.#a({...t,knowledgeBaseId:e}),`resource/addResourcesToKnowledgeBase/success`)},await r.commit()};removeResourcesFromKnowledgeBase=async(e,t)=>{if(t.length===0)return;let n=new Set(t),r=this.#e().queryParams?.libraryId===e,i=this.#s().createTransaction(`removeResourcesFromKnowledgeBase(${e})`);i.set(e=>{if(r){let r=0;e.resourceList=e.resourceList.filter(t=>n.has(t.id)?(e.resourceMap.delete(t.id),r+=1,!1):!0),typeof e.total==`number`&&(e.total=Math.max(0,e.total-t.length),e.hasMore=e.total>e.resourceList.length),e.offset=Math.max(0,e.offset-r);return}for(let t of e.resourceList){if(!n.has(t.id))continue;let r=this.#d(t,{knowledgeBaseId:void 0});e.resourceMap.set(t.id,r)}e.resourceList=e.resourceList.map(t=>n.has(t.id)?e.resourceMap.get(t.id)??t:t)}),i.mutation=()=>Ie.removeFilesFromKnowledgeBase(e,t),i.onSuccess=async()=>{r||this.#u(n,e=>this.#a({...e,knowledgeBaseId:void 0}),`resource/removeResourcesFromKnowledgeBase/success`)},await i.commit()};updateResource=async(e,t)=>{let{resourceMap:n}=this.#e(),r=n.get(e);if(!r){console.warn(`Resource ${e} not found for update`);return}let i={...r,...t,_optimistic:{...r._optimistic||{queryKey:L(this.#e().queryParams),retryCount:0},isPending:!0},name:t.name||t.title||r.name,updatedAt:new Date};Br(`updateResource`,e,r,t);let a=this.#s().createTransaction(`updateResource(${e})`);a.set(t=>{t.resourceMap.set(e,i),t.resourceList=t.resourceList.map(t=>t.id===e?i:t)}),a.mutation=()=>F.updateResource(e,t),a.onSuccess=async t=>{this.#c(e,t)},await a.commit()}}})),Wr,Gr,Kr=e((()=>{Ae(),Me(),ze(),Wr=(e,t,n)=>new Gr(e,t,n),Gr=class{#e;constructor(e,t,n){this.#e=t}removeTTSFile=async e=>{await P.removeFile(e)};uploadTTSByArrayBuffers=async(e,t)=>{let n=`audio/mp3`,r=new Blob(t,{type:n}),i=`${e}.mp3`,a=new File([r],i,{lastModified:Date.now(),type:n});return(await this.#e().uploadWithProgress({file:a,skipCheckFileType:!0}))?.id};useFetchTTSFile=e=>Oe(e?M.ttsFile(e):null,()=>P.getFile(e))}})),qr,Jr=e((()=>{qr={}})),Yr=e((()=>{Kr(),Jr()})),Xr,Zr=e((()=>{Xr=(e,t)=>
2!1})),Qr,$r=e((()=>{Qr=async e=>{if(typeof e==`string`){if(!e.startsWith(`data:image/`))return}else if(!e.type.startsWith(`image/`))return;return new Promise(t=>{let n=new Image,r=null;n.addEventListener(`load`,()=>{let e=n.naturalHeight,i=n.naturalWidth;t({height:e,ratio:e>0?Math.round(i/e*1e4)/1e4:0,width:i}),r&&URL.revokeObjectURL(r)}),n.addEventListener(`error`,()=>{r&&URL.revokeObjectURL(r),t(void 0)}),typeof e==`string`?n.src=e:(r=URL.createObjectURL(e),n.src=r)})}})),ei,ti,ni,ri,ii,ai=e((()=>{ue(),f(),a(),ei=Ve(),Zr(),Te(),ze(),He(),$r(),Ot(),y(),ti=async(e,t)=>{let n=await _(t);return!n||n===e.type?e:new File([e],e.name,{lastModified:e.lastModified,type:n})},ni=e=>!e||typeof e!=`object`||Array.isArray(e)?{}:e,ri=(e,t,n)=>new ii(e,t,n),ii=class{constructor(e,t,n){}uploadBase64FileWithProgress=async e=>{try{let t=await Qr(e),{metadata:n,fileType:r,size:i,hash:a}=await Ue.uploadBase64ToS3(e);return{...await P.createFile({fileType:r,hash:a,metadata:{...n,...t},name:n.filename,size:i,url:n.path}),dimensions:t,filename:n.filename}}catch(e){if(Xr(e))return;throw e}};uploadWithProgress=async({file:e,onStatusUpdate:t,knowledgeBaseId:r,skipCheckFileType:i,parentId:a,source:o,uploadId:s,abortController:c,visibility:l})=>{let u=s??e.name;try{let s=await e.arrayBuffer(),d=await ti(e,s),f=await Qr(d),p=(0,ei.sha256)(s),m=await P.checkFileHash(p),h;if(m.isExist)h=ni(m.metadata),t?.({id:u,type:`updateFile`,value:{status:`processing`,uploadState:{progress:100,restTime:0,speed:0}}});else{let{data:e,success:r}=await Ue.uploadFileToS3(d,{abortController:c,onNotSupported:()=>{t?.({id:u,type:`removeFile`}),be.info({content:n(`upload.fileOnlySupportInServerMode`,{cloud:le,ext:d.name.split(`.`).pop(),ns:`error`}),duration:5})},onProgress:(e,n)=>{t?.({id:u,type:`updateFile`,value:{status:e===`success`?`processing`:e,uploadState:n}})},skipCheckFileType:i});if(!r)return;h={...e}}let g=d.type;if(!d.type){let{fileTypeFromBuffer:e}=await te(async()=>{let{fileTypeFromBuffer:e}=await import(`../vendor/vendor-ai-runtime-DrDK77gy.js`).then(e=>(e.fn(),e.dn));return{fileTypeFromBuffer:e}},__vite__mapDeps([5,1,3]));g=(await e(s))?.mime||`text/plain`}let _=Tt(d.name);_&&!g.startsWith(`audio/`)&&(g=_);let v=h.path||m.url;if(!v)throw Error(`File upload failed: missing file url`);let y=await P.createFile({fileType:g,hash:p,metadata:{...h,...f},name:d.name,parentId:a,size:d.size,source:o,url:v,visibility:l},r);return t?.({id:u,type:`updateFile`,value:{fileUrl:y.url,id:y.id,status:`success`,uploadState:{progress:100,restTime:0,speed:0}}}),{...y,dimensions:f,filename:d.name}}catch(e){if(Xr(e,{onUploadBlocked:()=>t?.({id:u,type:`removeFile`})}))return;throw e}}}})),oi,si,ci,li,ui,di=e((()=>{o(),i(),ce(),ae(),E(),oe(),Rr(),Yt(),on(),Tn(),Pr(),Ur(),Yr(),ai(),oi=class extends se{resetActionName=`resetFileStore`},si=(...e)=>({...Lr,...C([jt(...e),pn(...e),kr(...e),Wr(...e),Xt(...e),ri(...e),new Hr(...e),new oi(...e)])}),ci=T(`file`),li=s()(ci(si),r),D(`file`,li),ui=()=>li.getState()}));export{st as A,qt as C,mt as D,lt as E,I as M,ht as O,Yt as S,Jt as T,cn as _,Jr as a,rn as b,br as c,pr as d,dr as f,wn as g,Cn as h,Yr as i,Je as j,ot as k,Or as l,Tn as m,di as n,qr as o,kn as p,li as r,Dr as s,ui as t,mr as u,sn as v,Kt as w,an as x,on as y};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.