@redocly/replay 0.28.0-next.9 → 0.29.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/replay-AiChatProvider-DUQ2hsZo.js +6 -0
  2. package/dist/{replay-AiChatProvider-DuTK5g1N.js → replay-AiChatProvider-DWj4kzZG.js} +182 -180
  3. package/dist/{replay-AiChatSqliteDBStorage-CHfMo6M6.js → replay-AiChatSqliteDBStorage-AwkpaRF3.js} +1 -1
  4. package/dist/{replay-AiChatSqliteDBStorage-cXsRIQfJ.js → replay-AiChatSqliteDBStorage-C-QR82Oo.js} +1 -1
  5. package/dist/{replay-AiPanel-CGbGwIMX.js → replay-AiPanel-DkUjsiBN.js} +50 -50
  6. package/dist/{replay-AiPanel-C_C52r20.js → replay-AiPanel-jffKz76q.js} +2 -2
  7. package/dist/replay-FileWatcher-BuLGLLQr.js +1 -0
  8. package/dist/replay-FileWatcher-DUvCC-PY.js +365 -0
  9. package/dist/{replay-SemanticSearchService-BLF1oOOu.js → replay-SemanticSearchService-CHkdWIcG.js} +15 -15
  10. package/dist/{replay-SemanticSearchService-DTc0oxN4.js → replay-SemanticSearchService-VF6AneJg.js} +1 -1
  11. package/dist/{replay-SqliteDBStorage-B_kyJ0a3.js → replay-SqliteDBStorage-CSYBSOEO.js} +1 -1
  12. package/dist/{replay-SqliteDBStorage-DF9kKplR.js → replay-SqliteDBStorage-EbVgsvZY.js} +1 -1
  13. package/dist/replay-TauriFileSystemAdapter-C2Vhu3Ay.js +108 -0
  14. package/dist/replay-TauriFileSystemAdapter-ZLQv2Jpa.js +1 -0
  15. package/dist/{replay-TauriRootStorage-Den8gI4S.js → replay-TauriRootStorage-Bqoz3cld.js} +192 -188
  16. package/dist/replay-TauriRootStorage-D8DYLi8t.js +1 -0
  17. package/dist/{replay-agent-loop-Z_nrrmg_.js → replay-agent-loop-Bm9BCm02.js} +1 -1
  18. package/dist/{replay-agent-loop-B8Mjb8DU.js → replay-agent-loop-De5Qyhy9.js} +3 -3
  19. package/dist/{replay-ai-chat-mappers-D7e8buTk.js → replay-ai-chat-mappers-lYbHE7LU.js} +1 -1
  20. package/dist/{replay-ai-chat-mappers-aJ_VMb6Z.js → replay-ai-chat-mappers-y3wFVHQe.js} +1 -1
  21. package/dist/{replay-create-model-Be3vPVDb.js → replay-create-model-BR_hDMYz.js} +4 -4
  22. package/dist/{replay-create-model-Bw20x80b.js → replay-create-model-DeyX2a2A.js} +3 -3
  23. package/dist/{replay-db-BQXljNM0.js → replay-db-8Yfdu1EO.js} +1 -1
  24. package/dist/{replay-db-BmZNrdZM.js → replay-db-CmLId87t.js} +1 -1
  25. package/dist/{replay-external-resolver-BQvSDNfH.js → replay-external-resolver-BL-garqK.js} +2 -2
  26. package/dist/{replay-external-resolver-BLzbbtnT.js → replay-external-resolver-CkqL8AKf.js} +1 -1
  27. package/dist/replay-index-49ub7kjO.js +4 -0
  28. package/dist/{replay-index-C7y4K4Cr.js → replay-index-B2_OwIzz.js} +1 -1
  29. package/dist/{replay-index-C0kvTxxm.js → replay-index-BAD7NmvH.js} +41 -41
  30. package/dist/{replay-index-BCz452N6.js → replay-index-BDcjQnps.js} +22286 -21701
  31. package/dist/{replay-index-DAIwC3ls.js → replay-index-BfiTbks9.js} +1 -1
  32. package/dist/{replay-index-B-uZhXHj.js → replay-index-CDhdpEsv.js} +1 -1
  33. package/dist/{replay-index-DYtXcqDk.js → replay-index-DTg-X2sJ.js} +1150 -1149
  34. package/dist/{replay-index-wBHsAQEV.js → replay-index-DorMJxDL.js} +1 -1
  35. package/dist/{replay-lint-CqDMOMQt.js → replay-lint-BTpTdc1d.js} +6100 -6063
  36. package/dist/{replay-lint-BzkTeXqI.js → replay-lint-DvPtwqB_.js} +97 -97
  37. package/dist/{replay-lint-graphql-BDBGJSir.js → replay-lint-graphql-B9_N8uLm.js} +1 -1
  38. package/dist/{replay-lint-graphql-BZF2eLiZ.js → replay-lint-graphql-BE8DlHWF.js} +1 -1
  39. package/dist/{replay-periodic-revalidation-C7SkB1vs.js → replay-periodic-revalidation-Dk5I6zpL.js} +1 -1
  40. package/dist/{replay-periodic-revalidation-orCv_JoF.js → replay-periodic-revalidation-QN1Nzs5P.js} +1 -1
  41. package/dist/{replay-resolve-0e5f8I7b.js → replay-resolve-Bu8MUbb4.js} +1 -1
  42. package/dist/{replay-resolve-DZMWoig2.js → replay-resolve-CiT66v_T.js} +1 -1
  43. package/dist/{replay-respect-run-ChP63WzG.js → replay-respect-run-_H2BVClG.js} +1 -1
  44. package/dist/{replay-respect-run-CLW3wGhx.js → replay-respect-run-vyQ9167I.js} +3 -3
  45. package/dist/{replay-tauri-path-DBt1dqkG.js → replay-tauri-path-C2_c3UUW.js} +1 -1
  46. package/dist/{replay-tauri-path-DvLF4Z8f.js → replay-tauri-path-nSR1IXTa.js} +2 -2
  47. package/dist/{replay-useAiChatQueries-S6v5duiJ.js → replay-useAiChatQueries-Di7srepQ.js} +994 -945
  48. package/dist/replay-useAiChatQueries-Z3RHPc9x.js +215 -0
  49. package/dist/{replay-validate-key-CMJODIH6.js → replay-validate-key-DCjaZPTw.js} +2 -2
  50. package/dist/{replay-validate-key-CNl7BV_v.js → replay-validate-key-DTrKCzzp.js} +1 -1
  51. package/dist/replay.cjs +1 -1
  52. package/dist/replay.d.ts +5 -0
  53. package/dist/replay.js +8 -8
  54. package/package.json +5 -5
  55. package/dist/replay-AiChatProvider-B_f9Wn8a.js +0 -6
  56. package/dist/replay-FileWatcher-DEOB0_DG.js +0 -1
  57. package/dist/replay-FileWatcher-Z6eygcBI.js +0 -359
  58. package/dist/replay-TauriFileSystemAdapter-CwSMakdJ.js +0 -1
  59. package/dist/replay-TauriFileSystemAdapter-DcFBYSUW.js +0 -99
  60. package/dist/replay-TauriRootStorage-DEGEIJrz.js +0 -1
  61. package/dist/replay-index-gM6vL6iT.js +0 -4
  62. package/dist/replay-useAiChatQueries-Bypgnkwa.js +0 -215
@@ -1,6 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const X=require("react/jsx-runtime"),i=require("react"),o=require("./replay-index-DYtXcqDk.js"),te=require("./replay-create-model-Bw20x80b.js"),fe=require("./replay-agent-loop-Z_nrrmg_.js"),pe=require("./replay-db-BQXljNM0.js"),v=require("./replay-useAiChatQueries-Bypgnkwa.js"),B=require("@tanstack/react-query"),Z=require("./replay-ai-chat-mappers-aJ_VMb6Z.js");class ge{handlers=new Map;middlewares;constructor(t){this.middlewares=t?.middlewares??[]}register(t){this.handlers.set(t.name,t)}getToolSet(){const t={};for(const[n,s]of this.handlers)t[n]=this.buildTool(s);return t}buildTool(t){return{...t.definition,execute:this.wrapExecutor(t)}}wrapExecutor(t){const n=(a,r)=>({isError:!0,error:{message:a,details:r}}),s=this.applyMiddlewares(t.name,t.execute);return(a,r)=>{if(r.abortSignal?.aborted)return n("Tool execution was aborted.");try{const l=s(a,r);return typeof l=="object"&&l!==null&&"then"in l?l.then(c=>c,c=>n(c instanceof Error?c.message:"Unknown tool execution error")):l}catch(l){return n(l instanceof Error?l.message:"Unknown tool execution error")}}}applyMiddlewares(t,n){return this.middlewares.length===0?n:this.middlewares.reduceRight((s,a)=>a(t,s),n)}}function ce(){const e=B.useQueryClient();return B.useMutation({async mutationFn(t){const n=Z.buildPersistableUiChat(t);await o.AiChatServiceFactory.getInstance().upsert(n)},onSuccess(){e.invalidateQueries({queryKey:o.aiChatKeys.all()})},onError(t){console.error("Failed to upsert ai chat item:",t)}})}function Ce(e){const t=B.useQueryClient(),n=o.aiChatKeys.detailTitle(e??"");return B.useMutation({mutationKey:n,async mutationFn(s){if(t.isMutating({mutationKey:n,exact:!0})>1)return;const a=Z.buildPersistableUiChat(s);await o.AiChatServiceFactory.getInstance().upsert(a)},onSuccess(){t.invalidateQueries({queryKey:o.aiChatKeys.all()})},onError(s){console.error("Failed to upsert ai chat item:",s)}})}function me(){const e=B.useQueryClient();return B.useMutation({async mutationFn(t){await o.AiChatServiceFactory.getInstance().remove(t)},onMutate:async t=>{await e.cancelQueries({queryKey:o.aiChatKeys.all()});const n=e.getQueryData(o.aiChatKeys.all());n&&e.setQueryData(o.aiChatKeys.all(),n.filter(s=>s.id!==t)),e.setQueryData(o.aiChatKeys.detail(t),null),e.setQueriesData({queryKey:o.aiChatKeys.infiniteHistories()},s=>s&&{...s,pages:s.pages.map(a=>({...a,items:a.items.filter(r=>r.id!==t)}))})},onError(t){console.error("Failed to remove ai chat:",t)},onSettled(){e.invalidateQueries({queryKey:o.aiChatKeys.all()})}})}var ee,oe;function ve(){if(oe)return ee;oe=1;function e(t,n){if(typeof t!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let s,a=0;return function(...l){clearTimeout(s);const c=Date.now(),d=c-a,p=n-d;p<=0?(a=c,t.apply(this,l)):s=setTimeout(()=>{a=Date.now(),t.apply(this,l)},p)}}return ee=e,ee}var we=ve();const Ie=o.getDefaultExportFromCjs(we);var ue=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},h=(e,t,n)=>(ue(e,t,"read from private field"),n?n.call(e):t.get(e)),A=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},R=(e,t,n,s)=>(ue(e,t,"write to private field"),t.set(e,n),n);function Te(e,t){return t!=null?Ie(e,t):e}var w,Y,J,j,Q,V,W,ne,se,ye=class{constructor(e=[]){A(this,w,void 0),A(this,Y,"ready"),A(this,J,void 0),A(this,j,new Set),A(this,Q,new Set),A(this,V,new Set),this.pushMessage=t=>{R(this,w,h(this,w).concat(t)),h(this,W).call(this)},this.popMessage=()=>{R(this,w,h(this,w).slice(0,-1)),h(this,W).call(this)},this.replaceMessage=(t,n)=>{R(this,w,[...h(this,w).slice(0,t),this.snapshot(n),...h(this,w).slice(t+1)]),h(this,W).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const s=n?Te(t,n):t;return h(this,j).add(s),()=>{h(this,j).delete(s)}},this["~registerStatusCallback"]=t=>(h(this,Q).add(t),()=>{h(this,Q).delete(t)}),this["~registerErrorCallback"]=t=>(h(this,V).add(t),()=>{h(this,V).delete(t)}),A(this,W,()=>{h(this,j).forEach(t=>t())}),A(this,ne,()=>{h(this,Q).forEach(t=>t())}),A(this,se,()=>{h(this,V).forEach(t=>t())}),R(this,w,e)}get status(){return h(this,Y)}set status(e){R(this,Y,e),h(this,ne).call(this)}get error(){return h(this,J)}set error(e){R(this,J,e),h(this,se).call(this)}get messages(){return h(this,w)}set messages(e){R(this,w,[...e]),h(this,W).call(this)}};w=new WeakMap;Y=new WeakMap;J=new WeakMap;j=new WeakMap;Q=new WeakMap;V=new WeakMap;W=new WeakMap;ne=new WeakMap;se=new WeakMap;var U,ae=class extends te.AbstractChat{constructor({messages:e,...t}){const n=new ye(e);super({...t,state:n}),A(this,U,void 0),this["~registerMessagesCallback"]=(s,a)=>h(this,U)["~registerMessagesCallback"](s,a),this["~registerStatusCallback"]=s=>h(this,U)["~registerStatusCallback"](s),this["~registerErrorCallback"]=s=>h(this,U)["~registerErrorCallback"](s),R(this,U,n)}};U=new WeakMap;function Ae({experimental_throttle:e,resume:t=!1,...n}={}){const s=i.useRef("chat"in n?{}:{onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});"chat"in n||(s.current={onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});const a={...n,onToolCall:u=>{var g,f;return(f=(g=s.current).onToolCall)==null?void 0:f.call(g,u)},onData:u=>{var g,f;return(f=(g=s.current).onData)==null?void 0:f.call(g,u)},onFinish:u=>{var g,f;return(f=(g=s.current).onFinish)==null?void 0:f.call(g,u)},onError:u=>{var g,f;return(f=(g=s.current).onError)==null?void 0:f.call(g,u)},sendAutomaticallyWhen:u=>{var g,f,_;return(_=(f=(g=s.current).sendAutomaticallyWhen)==null?void 0:f.call(g,u))!=null?_:!1}},r=i.useRef("chat"in n?n.chat:new ae(a));("chat"in n&&n.chat!==r.current||"id"in n&&n.id!=null&&r.current.id!==n.id)&&(r.current="chat"in n?n.chat:new ae(a));const c=i.useCallback(u=>r.current["~registerMessagesCallback"](u,e),[e,r.current.id]),d=i.useSyncExternalStore(c,()=>r.current.messages,()=>r.current.messages),p=i.useSyncExternalStore(r.current["~registerStatusCallback"],()=>r.current.status,()=>r.current.status),I=i.useSyncExternalStore(r.current["~registerErrorCallback"],()=>r.current.error,()=>r.current.error),T=i.useCallback(u=>{typeof u=="function"&&(u=u(r.current.messages)),r.current.messages=u},[r]);return i.useEffect(()=>{t&&r.current.resumeStream()},[t,r]),{id:r.current.id,messages:d,setMessages:T,sendMessage:r.current.sendMessage,regenerate:r.current.regenerate,clearError:r.current.clearError,stop:r.current.stop,error:I,resumeStream:r.current.resumeStream,status:p,addToolResult:r.current.addToolOutput,addToolOutput:r.current.addToolOutput,addToolApprovalResponse:r.current.addToolApprovalResponse}}const be=20;function Se(e){if(e.length===0)return"No OpenAPI specs loaded.";const t=e.slice(0,be),n=t.map(ke),s=e.length-t.length;return s>0&&n.push(` …and ${s} more API(s) not shown.`),[`Loaded APIs (${e.length}):`,...n].join(`
2
- `)}function ke(e){return[` apiId="${e.apiId}"`,`title="${e.title}"`,e.version?`version="${e.version}"`:null,e.primaryServer?`server="${e.primaryServer}"`:null].filter(Boolean).join(" ")}const Ee=30;function Me(e){if(e.length===0)return"No Arazzo collections loaded.";const t=[`Arazzo collections (${e.length}):`];let n=Ee,s=0,a=0;for(const l of e){if(n<=0){s+=l.workflows.length,a++;continue}if(t.push(Re(l)),n--,l.workflows.length===0)t.push(" (no workflows)");else if(n>=2){t.push(` workflows (${l.workflows.length}):`),n--;for(const c of l.workflows)n>0?(t.push(` ${_e(c)}`),n--):s++}else s+=l.workflows.length}const r=[s>0?`${s} more workflow(s)`:null,a>0?`${a} more collection(s)`:null].filter(Boolean);return r.length>0&&t.push(` …and ${r.join(", plus ")} not shown.`),t.join(`
3
- `)}function Re(e){const t=e.sourceApiIds.length>0?` apis=[${e.sourceApiIds.join(", ")}]`:"";return` collectionId="${e.collectionId}" title="${e.title}"${t}`}function _e(e){const t=`id="${e.workflowId}"`,n=e.summary?`label="${e.summary}"`:null,s=`[${e.stepCount} step${e.stepCount!==1?"s":""}]`;return[t,n,s].filter(Boolean).join(" ")}const Pe=20;function De(e){if(e.length===0)return"No environments configured.";const t=e.slice(0,Pe),n=t.map(xe),s=e.length-t.length;return s>0&&n.push(` …and ${s} more environment(s) not shown.`),[`Environments (${e.length}); * marks the active environment:`,...n].join(`
4
- `)}function xe(e){return[`${e.isActive?"*":" "} name="${e.name}"`,`inputs=${e.inputCount}`,`servers=${e.serverCount}`].join(" ")}const $e=30;function Oe(e){if(e.length===0)return"No tabs are open.";const t=e.slice(0,$e),n=t.map(We),s=e.length-t.length;return s>0&&n.push(` …and ${s} more tab(s) not shown.`),[`Open tabs (${e.length}), listed by tabIndex; * marks the active (focused) tab:`,...n].join(`
5
- `)}function We(e){const t=[e.collectionId?`collectionId="${e.collectionId}"`:null,e.workflowId?`workflowId="${e.workflowId}"`:null,e.stepId?`stepId="${e.stepId}"`:null,e.operationId?`operationId="${e.operationId}"`:null].filter(Boolean),n=[e.isPreview?"preview":null,e.isDraft?"draft":null,e.isHistory?"history":null].filter(Boolean);return[`${e.isActive?"*":" "} ${e.tabIndex}.`,`type="${e.type}"`,`label="${e.label}"`,...t,n.length>0?`(${n.join(", ")})`:null].filter(Boolean).join(" ")}const Ue="Auto-attached snapshot of the user's current Replay UI state. Generated by Replay before each step; not written by the user. It is a shallow summary — use tools to read detailed tab contents when needed.";function Be(e){const t=`
6
- `.repeat(2),n=[Ue,t,Oe(e.tabs),t,Se(e.apis),t,Me(e.collections),t,De(e.environments)].join("");return pe.section("active_state",n)}function Le(e){return e.map(Fe)}function Fe(e){return{apiId:e.id,title:e.info?.title??"Untitled API",version:e.info?.version,primaryServer:e.servers?.[0]?.url}}function Ne(e){return e.map(qe)}function qe(e){const t=(e.workflows??[]).map(s=>({workflowId:s.workflowId,summary:s.summary,stepCount:s.steps?.length??0})),n=(e.sourceDescriptions??[]).map(s=>s.apiId).filter(Boolean);return{collectionId:e.id,title:e.info?.title??"Untitled Collection",workflows:t,sourceApiIds:n}}function Ke(e,t){return e.filter(n=>n.state!==o.ItemState.Draft).map(n=>({name:n.name,isActive:n.name===t,inputCount:n.inputs.length,serverCount:n.servers.length}))}function je(e,t,n){return e.map((s,a)=>Qe(n,s,a,a===t))}function Qe(e,t,n,s){const a={tabIndex:n,type:t.data.type,isActive:s,isPreview:t.state===o.TabState.Preview};switch(t.data.type){case o.TabDataType.Collection:{const{collectionId:r}=t.data;return{...a,label:Ve(e,r)??r,collectionId:r}}case o.TabDataType.Workflow:{const{collectionId:r,workflowId:l}=t.data;return{...a,label:l,collectionId:r,workflowId:l}}case o.TabDataType.WorkflowRun:{const{collectionId:r,workflowId:l,historyId:c,label:d}=t.data;return{...a,label:d??`${l} run`,collectionId:r,workflowId:l,isHistory:c!=null}}case o.TabDataType.Step:{const r=t.data;return{...a,label:He(r),collectionId:r.collectionId,workflowId:r.workflowId,stepId:r.stepId,operationId:r.draftStep?.operation?.operationId??null,isDraft:!r.collectionId&&!r.workflowId,isHistory:r.historyId!=null}}}}function Ve(e,t){return e.find(n=>n.id===t)?.info.title}function He(e){if(e.stepId)return e.stepId;if(e.draftStep){const t=[o.getStepMethod(e.draftStep),o.getStepUrl(e.draftStep)].filter(Boolean).join(" ");if(t)return t}return"New Request"}function Ge(e){const t=e.get(o.collectionsAtom);return{tabs:je(e.get(o.tabsAtom),e.get(o.activeTabIdxAtom),t),apis:Le(e.get(o.apisAtom)),collections:Ne(t),environments:Ke(e.get(o.environmentsAtom),e.get(o.activeEnvironmentIdAtom))}}function ze(){const e=o.useCollections(),{tab:t}=o.useActiveTab(),n=t?.data??null;return i.useMemo(()=>{if(!n)return null;switch(n.type){case o.TabDataType.Collection:const a=o.findCollection(e,n.collectionId);return{...n,collection:a};case o.TabDataType.Workflow:const r=o.findWorkflow(e,{collectionId:n.collectionId,workflowId:n.workflowId});return{...n,workflow:r};case o.TabDataType.Step:const l=o.findStep(e,{collectionId:n.collectionId,workflowId:n.workflowId,stepId:n.stepId});return{...n,step:l};case o.TabDataType.WorkflowRun:const c=o.findWorkflow(e,{collectionId:n.collectionId,workflowId:n.workflowId});return{...n,workflow:c}}},[n,e])}function Ye(e){if(!e||typeof e!="object"||!("changes"in e)||!Array.isArray(e.changes))return e;const t=e.changes.filter(s=>s&&typeof s=="object"&&"approved"in s&&s.approved===!0),n="meta"in e&&typeof e.meta=="object"?e.meta:{};return{...e,changes:t,meta:{...n,totalChanges:e.changes.length,approvedChanges:t.length}}}function Je(){return(e,t)=>(n,s)=>t(Ye(n),s)}function Xe(){const{getApiOperation:e}=o.useApiOperationGetter(),t=o.useTabHandlers();return i.useMemo(()=>({getApiOperation:e,...t}),[e,t])}function Ze(e){const{convertOperationToReplayValue:t}=o.useSettingsContext(),n=ze(),s=Xe(),a=o.useSettings(),r=o.useStore(),{attachApiToCollection:l}=o.useCollectionActions(),{handleCloseByDataId:c}=o.useTabHandlers(),d=o.useRunWorkflow(),p=i.useRef(n);return p.current=n,{tools:i.useMemo(()=>{const T=new ge({middlewares:[Je()]});return v.registerBuiltInTools(T,{[v.reportStatusBlueprint.name]:void 0,[v.runRequestBlueprint.name]:{settings:a,store:r},[v.runWorkflowBlueprint.name]:{store:r,runWorkflow:d},[v.updateSecurityBlueprint.name]:{store:r},[v.updateStepBlueprint.name]:{store:r},[v.manageCollectionBlueprint.name]:{store:r,attachApiToCollection:l,handleCloseByDataId:c,convertOperationToReplayValue:t},[v.manageEnvironmentBlueprint.name]:{store:r},[v.webSearchBlueprint.name]:{model:e},[v.searchBlueprint.name]:{store:r},[v.openTabBlueprint.name]:{store:r,context:s},[v.getCurrentTabBlueprint.name]:{getActiveTabDetailedData:()=>p.current},[v.getApiMetadataBlueprint.name]:{store:r}}),T.getToolSet()},[l,t,c,e,s,d,a,r])}}function et(e){const{children:t,chatId:n,model:s,initialMessages:a,onChatFinish:r,onChatMessagesUpdated:l}=e,c=o.useSettings(),{getReuniteAuth:d}=o.useSettingsContext(),{tools:p}=Ze(s),{sendEvent:I}=o.useTelemetry(),T=i.useRef(p),u=i.useRef(s),{isOpen:g,openPanel:f,closePanel:_}=o.useAiPanel(),P=i.useRef(void 0),L=o.useStore();T.current=p,u.current=s;const C=i.useMemo(()=>{P.current?.end();const E=o.trace.getTracer("replay-ai-chat").startSpan("ai.chat.session",{attributes:{conversation_id:n}});P.current=E;const M=o.trace.setSpan(o.context.active(),E);return new fe.AgentLoop({activeConversationId:n,model:u.current,tools:T.current,sendEvent:I,parentCtx:M,getActiveStateMessage:()=>Be(Ge(L))})},[n,I,L]);i.useEffect(()=>()=>P.current?.end(),[]);const x=i.useMemo(()=>{if(C)return new te.DirectChatTransport({agent:C.getAgent()})},[C]);i.useEffect(()=>{C.setModel(s)},[C,s]),i.useEffect(()=>{C.registerTools(p)},[C,p]);const{messages:S,setMessages:D,sendMessage:F,status:k,error:H,stop:$,addToolApprovalResponse:N}=Ae({id:n,messages:a,transport:x,sendAutomaticallyWhen:te.lastAssistantMessageIsCompleteWithApprovalResponses,onFinish(E){if(!r||!C)return;r({agentLoop:C,chat:this},E)}}),b=i.useMemo(()=>k==="streaming"||k==="submitted",[k]),q=i.useCallback(()=>{c.aiEnabled===!0&&f()},[f,c.aiEnabled]),K=i.useCallback(()=>{_()},[_]),G=i.useCallback(async E=>{const M=E.trim();if(!(!M||!x)){if(s.provider===o.REUNITE_AI_PROVIDER){const y=await d?.();y?.baseUrl&&y?.accessToken&&C.setModel({provider:o.REUNITE_AI_PROVIDER,baseUrl:y.baseUrl,accessToken:y.accessToken})}D(y=>v.hasPendingApprovalMessage(y)?v.denyPendingApprovals(y):y),F({text:M})}},[C,d,s.provider,F,D,x]),m=i.useCallback(()=>{b&&$()},[b,$]);i.useEffect(()=>()=>{$()},[n,$]);const O=i.useCallback(E=>{const M=E(S),y=M.map(z=>z.message),re=[...S];for(const z of M)re[z.index]=z.message;D(re),l?.(y)},[S,l,D]),de=i.useMemo(()=>({messages:S,isStreaming:b,chatStatus:k,chatError:H,sendMessage:G,updateMessages:O,stopGeneration:m,addToolApprovalResponse:N}),[N,H,b,S,G,k,m,O]),he=i.useMemo(()=>({isOpen:g,openPanel:q,closePanel:K}),[g,q,K]);return X.jsx(v.AiConversationContext.Provider,{value:de,children:X.jsx(o.AiPanelContext.Provider,{value:he,children:t})})}function tt(e){return e.slice(-2)}function nt(e,t){return!!(e||t<1)}function st(e){return i.useCallback(async(t,n)=>{if(nt(e,n.messages.length))return null;const s=n.messages[0],a=v.getMessageTextContent(s.parts);try{return(await t.agentLoop.generateTitle(a)).trim()}catch(r){return console.error("Unable to generate chat title",r),null}},[e])}function rt({chatId:e,model:t,existingTitle:n}){const{mutate:s}=Ce(e),a=st(n);return i.useCallback(async(...r)=>{const l=await a(...r);l!==null&&l.length!==0&&s({id:e,model:t,messages:[],title:l})},[a,t,e,s])}function ot({chatId:e,model:t}){const{mutate:n}=ce();return i.useCallback((s,a)=>{const r=tt(a.messages);n({id:e,model:t,messages:r})},[t,e,n])}function at({chatId:e,model:t}){const{mutate:n}=ce();return i.useCallback(s=>{s.length!==0&&n({id:e,model:t,messages:s})},[t,e,n])}function it(e){return i.useMemo(()=>{const t=[o.REUNITE_MODEL_OPTION];if(e){for(const[n,s]of Object.entries(e))if(s.enabled&&s.apiKey){const a=s.models.map(r=>({...r,provider:n}));t.push(...a)}}return t},[e])}function ie(e){return typeof e=="function"?e():e}function le(e,t){try{const n=globalThis.localStorage.getItem(e);return n===null?ie(t):n}catch{return ie(t)}}function lt(e,t){try{globalThis.localStorage.setItem(e,t)}catch{console.error("Failed to write to localStorage",{key:e,value:t})}}function ct(e,t){const[n,s]=i.useState(()=>le(e,t)),a=i.useRef(t);a.current=t,i.useEffect(()=>{s(le(e,a.current))},[e]);const r=i.useCallback(l=>{s(c=>{const d=l instanceof Function?l(c):l;return lt(e,d),d})},[e]);return[n,r]}const ut="replay:ai:selectedModelId";function dt(e){const{availableModels:t,aiProviders:n,reuniteAuth:s}=e,[a,r]=ct(ut,o.REUNITE_MODEL_OPTION.id);return i.useEffect(()=>{t.find(d=>d.id===a)||r(o.REUNITE_MODEL_OPTION.id)},[t,a,r]),{model:i.useMemo(()=>{const c={provider:o.REUNITE_AI_PROVIDER,baseUrl:s.baseUrl,accessToken:s.accessToken},d=t.find(I=>I.id===a);if(!d||d.provider===o.REUNITE_AI_PROVIDER)return c;const p=n?.[d.provider];return!p||!p.apiKey||!p.enabled?c:{provider:d.provider,modelId:d.id,apiKey:p.apiKey}},[a,t,n,s]),selectedModelId:a,selectModel:r}}function ht(){const[e,t]=i.useState({baseUrl:"",accessToken:""}),{getReuniteAuth:n}=o.useSettingsContext();return i.useEffect(()=>{let s=!1;async function a(){const r=await n?.();s||t({baseUrl:r?.baseUrl??"",accessToken:r?.accessToken??""})}return a().catch(()=>{s||t({baseUrl:"",accessToken:""})}),()=>{s=!0}},[n]),e}function ft(e){const{children:t}=e,[n,s]=i.useState(Z.generateAiChatId),[a,r]=i.useState(n),[l,c]=i.useState(null),d=o.useSettings(),p=o.useSettingsContext(),{openPanel:I}=o.useAiPanel(),T=a!==n,u=i.useCallback(()=>{const m=Z.generateAiChatId();r(m),s(m)},[]),g=i.useCallback(m=>{r(m)},[]),{data:f}=v.useAiChat(a),_=ht(),P=it(p.aiProviders),{selectedModelId:L,model:C,selectModel:x}=dt({availableModels:P,aiProviders:p.aiProviders,reuniteAuth:_}),S=me(),D=ot({chatId:n,model:C}),F=at({chatId:n,model:C}),k=rt({chatId:n,model:C,existingTitle:f?.title}),H=i.useCallback((m,O)=>{O.isAbort||(D(m,O),k(m,O))},[D,k]),$=i.useCallback((...m)=>{F(...m)},[F]),N=i.useCallback(m=>{(a===m||n===m)&&u(),S.mutate(m)},[u,n,S,a]),b=f?.id;i.useEffect(()=>{b&&b!==n&&s(b)},[b,a,n]);const q=i.useCallback(()=>{c(null)},[]),K=i.useCallback(m=>{d.aiEnabled&&(u(),c(m),I())},[I,u,d.aiEnabled]),G=i.useMemo(()=>({chatId:n,model:C,availableModels:P,selectedModelId:L,selectModel:x,onSettingsOpen:p.onSettingsOpen,title:f?.title??o.defaultAiChatContextValue.title,isLoading:T,selectChat:g,removeChat:N,createNewChat:u,openAiChatWithPresetInput:K,pendingComposerPreset:l,clearPendingComposerPreset:q}),[n,P,f?.title,C,T,g,N,u,K,l,q,L,x,p.onSettingsOpen]);return X.jsx(o.AiChatContext.Provider,{value:G,children:X.jsx(et,{chatId:n,model:C,initialMessages:f?.messages,onChatFinish:H,onChatMessagesUpdated:$,children:t})})}exports.AiChatProvider=ft;
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const d=require("./replay-index-DYtXcqDk.js"),m=require("./replay-SemanticSearchService-DTc0oxN4.js");var v;(function(l){l.WINDOW_RESIZED="tauri://resize",l.WINDOW_MOVED="tauri://move",l.WINDOW_CLOSE_REQUESTED="tauri://close-requested",l.WINDOW_DESTROYED="tauri://destroyed",l.WINDOW_FOCUS="tauri://focus",l.WINDOW_BLUR="tauri://blur",l.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",l.WINDOW_THEME_CHANGED="tauri://theme-changed",l.WINDOW_CREATED="tauri://window-created",l.WEBVIEW_CREATED="tauri://webview-created",l.DRAG_ENTER="tauri://drag-enter",l.DRAG_OVER="tauri://drag-over",l.DRAG_DROP="tauri://drag-drop",l.DRAG_LEAVE="tauri://drag-leave"})(v||(v={}));async function E(l,e){await d.invoke("plugin:event|unlisten",{event:l,eventId:e})}async function w(l,e,a){var t;const i=(t=void 0)!==null&&t!==void 0?t:{kind:"Any"};return d.invoke("plugin:event|listen",{event:l,target:i,handler:d.transformCallback(e)}).then(s=>async()=>E(l,s))}const p="replay-environments.yaml";class F{constructor(e,a,t,i,s,o){this.storage=e,this.projectDir=a,this.aiEnabled=t,this.setEnvironments=i,this.apis=s,this.collections=o}storage;projectDir;aiEnabled;setEnvironments;apis;collections;watchPath=null;unlistenEvent=null;get tauriStorage(){return this.storage}indexApis(e){!this.aiEnabled||e.length===0||m.getSemanticSearchService().indexApis(e).catch(a=>console.error("Semantic index (apis):",a))}indexCollections(e){!this.aiEnabled||e.length===0||m.getSemanticSearchService().indexCollections(e).catch(a=>console.error("Semantic index (collections):",a))}removeApis(e){if(!this.aiEnabled||e.length===0)return;const a=m.getSemanticSearchService();Promise.all(e.map(t=>a.removeApi(t))).catch(t=>console.error("Semantic remove (apis):",t))}removeCollections(e){if(!this.aiEnabled||e.length===0)return;const a=m.getSemanticSearchService();Promise.all(e.map(t=>a.removeCollection(t))).catch(t=>console.error("Semantic remove (collections):",t))}async start(){if(this.watchPath){console.warn("Watcher already started for:",this.watchPath);return}try{this.unlistenEvent=await w("fs-watch-event",async e=>{const a=e.payload;try{await this.handleEvent(a)}catch(t){console.error("Error handling file change:",t)}}),await d.invoke("fs_watch",{path:this.projectDir,options:{recursive:!0,delayMs:500}}),this.watchPath=this.projectDir}catch(e){throw console.error("Failed to start file watcher:",e),this.unlistenEvent&&(this.unlistenEvent(),this.unlistenEvent=null),e}}async stop(){if(this.watchPath)try{await d.invoke("fs_unwatch",{path:this.watchPath})}catch(e){console.error("Error stopping file watcher:",e)}finally{this.unlistenEvent&&(this.unlistenEvent(),this.unlistenEvent=null),this.watchPath=null}}async handleEvent(e){const{changeType:a,paths:t,pathTypes:i,type:s}=e;if(await this.isProjectFolderRemoved(t,a)){await this.handleProjectFolderRemoval();return}const o=this.filterSpecFiles(t,i);if(o.paths.length===0)return;const n=await this.toFileEntries(o.paths,o.pathTypes);switch(a){case"changed":(s.includes("Data")||s.includes("Name"))&&await this.handleModify(n);break;case"added":await this.handleCreate(n);break;case"deleted":await this.handleDelete(n);break;case"renamed":await this.handleRename(n);break;default:console.log("Unhandled change type:",a)}}filterSpecFiles(e,a){const t=[],i=[];for(let s=0;s<e.length;s++){const o=e[s],n=o.split(".").pop()?.toLowerCase();n&&["yaml","yml","json"].includes(n)&&(t.push(o),i.push(a[s]||"unknown"))}return{paths:t,pathTypes:i}}async toFileEntries(e,a){return Promise.all(e.map(async(t,i)=>({relative_path:await d.PathUtils.relative(this.projectDir,t),absolute_path:t,type:a[i]||"unknown"})))}hasEnvironmentsFileChange(e){return!this.storage.isWatchExcluded(p)&&e.some(a=>a.relative_path===p)}withoutEnvironmentsFile(e){return e.filter(a=>a.relative_path!==p)}consolidateFileEntries(e){const a=[],t=new Set;for(const i of e)t.has(i.relative_path)||(t.add(i.relative_path),this.storage.isWatchExcluded(i.relative_path)||a.push(i));return a}async handleModify(e){const a=this.hasEnvironmentsFileChange(e),t=this.withoutEnvironmentsFile(e),{newApiFiles:i,existingApiFiles:s}=this.categorizeApisFromFiles(t),{newCollectionFiles:o,existingCollectionFiles:n}=this.categorizeCollectionsFromFiles(t),r=await this.findApisToReload(e),c=await this.findCollectionsToReload(e),u=[...i,...o];u.length>0&&await this.handleCreate(u),a&&await this.reloadEnvironments();const g=this.consolidateFileEntries([...s,...r]),f=this.consolidateFileEntries([...n,...c]);await this.reloadApis(g),await this.reloadCollections(f)}async handleCreate(e){this.hasEnvironmentsFileChange(e)&&await this.reloadEnvironments();const a=this.withoutEnvironmentsFile(e),t=a.filter(c=>c.type==="api"),i=a.filter(c=>c.type==="collection"),{newApiFiles:s,existingApiFiles:o}=this.categorizeApisFromFiles(t),{newCollectionFiles:n,existingCollectionFiles:r}=this.categorizeCollectionsFromFiles(i);if(s.length>0||n.length>0){s.forEach(h=>this.storage.addPersistExcludedId(h.relative_path)),n.forEach(h=>this.storage.addPersistExcludedId(h.relative_path));const c=s.length>0?await this.tauriStorage.loadAndParseApis(s,void 0,!0):[],u=n.length>0?await this.tauriStorage.loadAndParseCollections(n,void 0):[],g=c.filter(h=>h!==null),f=u.filter(h=>h!==null);this.apis.set([...this.apis.get(),...g]),this.collections.set([...this.collections.get(),...f]),this.indexApis(g),this.indexCollections(f),setTimeout(()=>{s.forEach(h=>this.storage.removePersistExcludedId(h.relative_path)),n.forEach(h=>this.storage.removePersistExcludedId(h.relative_path))},500)}o.length>0&&await this.reloadApis(o),r.length>0&&await this.reloadCollections(r)}categorizeApisFromFiles(e){const a=new Set,t=[],i=[];for(const s of e){if(a.has(s.relative_path))continue;a.add(s.relative_path),this.apis.get().some(n=>n.id===s.relative_path)?i.push(s):s.type==="api"&&t.push(s)}return{newApiFiles:t,existingApiFiles:i}}categorizeCollectionsFromFiles(e){const a=new Set,t=[],i=[];for(const s of e){if(a.has(s.relative_path))continue;a.add(s.relative_path),this.collections.get().some(n=>n.id===s.relative_path)?i.push(s):s.type==="collection"&&t.push(s)}return{newCollectionFiles:t,existingCollectionFiles:i}}async handleDelete(e){this.hasEnvironmentsFileChange(e)&&await this.reloadEnvironments();const a=[],t=[];for(const i of this.withoutEnvironmentsFile(e)){this.storage.addPersistExcludedId(i.relative_path);const s=this.apis.get();s.some(r=>r.id===i.relative_path)&&(this.apis.set(s.filter(r=>r.id!==i.relative_path)),this.tauriStorage.deleteApiFromCache(i.relative_path),a.push(i.relative_path));const o=this.collections.get(),n=o.findIndex(r=>r.id===i.relative_path);n>=0&&(this.collections.set(o.filter((r,c)=>c!==n)),t.push(i.relative_path)),setTimeout(()=>{this.storage.removePersistExcludedId(i.relative_path)},500)}this.removeApis(a),this.removeCollections(t)}async handleRename(e){if(e.length>=2){const[a,t]=e;await this.handleDelete([a]),await this.handleCreate([t])}else await this.handleCreate(e)}async isProjectFolderRemoved(e,a){if(e.length===0)return!1;if(a==="deleted"||a==="renamed"){for(const i of e)if(i===this.projectDir)return!0}return e.filter(i=>!i.startsWith(this.projectDir+"/")&&i!==this.projectDir).length>0&&a==="renamed"}async handleProjectFolderRemoval(){const e=this.apis.get(),a=e.map(s=>s.id);e.forEach(s=>{this.storage.addPersistExcludedId(s.id),this.tauriStorage.deleteApiFromCache(s.id)}),this.apis.set([]);const t=this.collections.get(),i=t.map(s=>s.id);t.forEach(s=>{this.storage.addPersistExcludedId(s.id)}),this.collections.set([]),setTimeout(()=>{e.forEach(s=>this.storage.removePersistExcludedId(s.id)),t.forEach(s=>this.storage.removePersistExcludedId(s.id))},500),this.removeApis(a),this.removeCollections(i),await this.stop()}async findApisToReload(e){const a=[];return await Promise.all(this.apis.get().map(async t=>{const i=t.fileDependencies??new Set,s=t.id,o=e.find(n=>i.has(n.absolute_path));if(!this.storage.isWatchExcluded(s)&&o){const n=await d.PathUtils.join(this.projectDir,s);a.push({relative_path:s,absolute_path:n,type:"api"})}})),a}async findCollectionsToReload(e){const a=[];return await Promise.all(this.collections.get().map(async t=>{const i=t.fileDependencies??new Set,s=t.id,o=e.find(n=>i.has(n.absolute_path));if(!this.storage.isWatchExcluded(s)&&o){const n=await d.PathUtils.join(this.projectDir,s);a.push({relative_path:s,absolute_path:n,type:"collection"})}})),a}async reloadEnvironments(){const e=await this.tauriStorage.readEnviroments();this.storage.addPersistExcludedId(p),this.setEnvironments(e.length>0?e:d.cloneObject(d.DEFAULT_ENVIRONMENTS)),this.storage.publishEnvironmentsConfigError(),setTimeout(()=>{this.storage.removePersistExcludedId(p)},500)}async reloadApis(e){if(e.length===0)return;const a=await this.tauriStorage.loadAndParseApis(e,void 0,!0),t=[];await Promise.all(a.map(async(i,s)=>{if(!i){await this.handleDelete([e[s]]);return}const o=this.apis.get();o.some(n=>n.id===i.id)?(this.storage.addPersistExcludedId(i.id),this.apis.set(o.map(n=>n.id===i.id?i:n)),t.push(i),setTimeout(()=>this.storage.removePersistExcludedId(i.id),500)):console.warn("API not found in state after reload:",i.id)})),t.length>0&&this.indexApis(t)}async reloadCollections(e){if(e.length===0)return;const a=await this.tauriStorage.loadAndParseCollections(e,void 0),t=[];await Promise.all(a.map(async(i,s)=>{if(!i){await this.handleDelete([e[s]]);return}const o=this.collections.get(),n=o.findIndex(r=>r.id===i.id);n>=0?(this.storage.addPersistExcludedId(i.id),this.collections.set(o.map((r,c)=>c===n?i:r)),t.push(i),setTimeout(()=>this.storage.removePersistExcludedId(i.id),500)):console.warn("Collection not found in state after reload:",i.id)})),t.length>0&&this.indexCollections(t)}}exports.FileWatcher=F;
@@ -1,359 +0,0 @@
1
- import { i as m, t as w, P as E, q as F, D as C } from "./replay-index-BCz452N6.js";
2
- import { g } from "./replay-SemanticSearchService-BLF1oOOu.js";
3
- var v;
4
- (function(l) {
5
- l.WINDOW_RESIZED = "tauri://resize", l.WINDOW_MOVED = "tauri://move", l.WINDOW_CLOSE_REQUESTED = "tauri://close-requested", l.WINDOW_DESTROYED = "tauri://destroyed", l.WINDOW_FOCUS = "tauri://focus", l.WINDOW_BLUR = "tauri://blur", l.WINDOW_SCALE_FACTOR_CHANGED = "tauri://scale-change", l.WINDOW_THEME_CHANGED = "tauri://theme-changed", l.WINDOW_CREATED = "tauri://window-created", l.WEBVIEW_CREATED = "tauri://webview-created", l.DRAG_ENTER = "tauri://drag-enter", l.DRAG_OVER = "tauri://drag-over", l.DRAG_DROP = "tauri://drag-drop", l.DRAG_LEAVE = "tauri://drag-leave";
6
- })(v || (v = {}));
7
- async function _(l, e) {
8
- await m("plugin:event|unlisten", {
9
- event: l,
10
- eventId: e
11
- });
12
- }
13
- async function y(l, e, a) {
14
- var t;
15
- const i = (t = void 0) !== null && t !== void 0 ? t : { kind: "Any" };
16
- return m("plugin:event|listen", {
17
- event: l,
18
- target: i,
19
- handler: w(e)
20
- }).then((s) => async () => _(l, s));
21
- }
22
- const d = "replay-environments.yaml";
23
- class P {
24
- constructor(e, a, t, i, s, o) {
25
- this.storage = e, this.projectDir = a, this.aiEnabled = t, this.setEnvironments = i, this.apis = s, this.collections = o;
26
- }
27
- storage;
28
- projectDir;
29
- aiEnabled;
30
- setEnvironments;
31
- apis;
32
- collections;
33
- watchPath = null;
34
- unlistenEvent = null;
35
- get tauriStorage() {
36
- return this.storage;
37
- }
38
- indexApis(e) {
39
- !this.aiEnabled || e.length === 0 || g().indexApis(e).catch((a) => console.error("Semantic index (apis):", a));
40
- }
41
- indexCollections(e) {
42
- !this.aiEnabled || e.length === 0 || g().indexCollections(e).catch((a) => console.error("Semantic index (collections):", a));
43
- }
44
- removeApis(e) {
45
- if (!this.aiEnabled || e.length === 0) return;
46
- const a = g();
47
- Promise.all(e.map((t) => a.removeApi(t))).catch(
48
- (t) => console.error("Semantic remove (apis):", t)
49
- );
50
- }
51
- removeCollections(e) {
52
- if (!this.aiEnabled || e.length === 0) return;
53
- const a = g();
54
- Promise.all(e.map((t) => a.removeCollection(t))).catch(
55
- (t) => console.error("Semantic remove (collections):", t)
56
- );
57
- }
58
- /**
59
- * Starts watching the directory for changes.
60
- */
61
- async start() {
62
- if (this.watchPath) {
63
- console.warn("Watcher already started for:", this.watchPath);
64
- return;
65
- }
66
- try {
67
- this.unlistenEvent = await y("fs-watch-event", async (e) => {
68
- const a = e.payload;
69
- try {
70
- await this.handleEvent(a);
71
- } catch (t) {
72
- console.error("Error handling file change:", t);
73
- }
74
- }), await m("fs_watch", {
75
- path: this.projectDir,
76
- options: {
77
- recursive: !0,
78
- delayMs: 500
79
- }
80
- }), this.watchPath = this.projectDir;
81
- } catch (e) {
82
- throw console.error("Failed to start file watcher:", e), this.unlistenEvent && (this.unlistenEvent(), this.unlistenEvent = null), e;
83
- }
84
- }
85
- /**
86
- * Stops watching and cleans up resources.
87
- */
88
- async stop() {
89
- if (this.watchPath)
90
- try {
91
- await m("fs_unwatch", { path: this.watchPath });
92
- } catch (e) {
93
- console.error("Error stopping file watcher:", e);
94
- } finally {
95
- this.unlistenEvent && (this.unlistenEvent(), this.unlistenEvent = null), this.watchPath = null;
96
- }
97
- }
98
- /**
99
- * Main event handler - dispatches to specific handlers based on event type.
100
- */
101
- async handleEvent(e) {
102
- const { changeType: a, paths: t, pathTypes: i, type: s } = e;
103
- if (await this.isProjectFolderRemoved(t, a)) {
104
- await this.handleProjectFolderRemoval();
105
- return;
106
- }
107
- const o = this.filterSpecFiles(t, i);
108
- if (o.paths.length === 0)
109
- return;
110
- const n = await this.toFileEntries(o.paths, o.pathTypes);
111
- switch (a) {
112
- case "changed":
113
- (s.includes("Data") || s.includes("Name")) && await this.handleModify(n);
114
- break;
115
- case "added":
116
- await this.handleCreate(n);
117
- break;
118
- case "deleted":
119
- await this.handleDelete(n);
120
- break;
121
- case "renamed":
122
- await this.handleRename(n);
123
- break;
124
- default:
125
- console.log("Unhandled change type:", a);
126
- }
127
- }
128
- /**
129
- * Filter paths to only include yaml/json files.
130
- * Returns filtered paths and their corresponding pathTypes.
131
- */
132
- filterSpecFiles(e, a) {
133
- const t = [], i = [];
134
- for (let s = 0; s < e.length; s++) {
135
- const o = e[s], n = o.split(".").pop()?.toLowerCase();
136
- n && ["yaml", "yml", "json"].includes(n) && (t.push(o), i.push(a[s] || "unknown"));
137
- }
138
- return { paths: t, pathTypes: i };
139
- }
140
- /**
141
- * Convert absolute paths to file entry format with relative paths and types.
142
- */
143
- async toFileEntries(e, a) {
144
- return Promise.all(
145
- e.map(async (t, i) => ({
146
- relative_path: await E.relative(this.projectDir, t),
147
- absolute_path: t,
148
- type: a[i] || "unknown"
149
- }))
150
- );
151
- }
152
- hasEnvironmentsFileChange(e) {
153
- return !this.storage.isWatchExcluded(d) && e.some((a) => a.relative_path === d);
154
- }
155
- withoutEnvironmentsFile(e) {
156
- return e.filter((a) => a.relative_path !== d);
157
- }
158
- consolidateFileEntries(e) {
159
- const a = [], t = /* @__PURE__ */ new Set();
160
- for (const i of e)
161
- t.has(i.relative_path) || (t.add(i.relative_path), this.storage.isWatchExcluded(i.relative_path) || a.push(i));
162
- return a;
163
- }
164
- /**
165
- * Handles file content modification events.
166
- * If file doesn't exist in state yet, treat as creation.
167
- */
168
- async handleModify(e) {
169
- const a = this.hasEnvironmentsFileChange(e), t = this.withoutEnvironmentsFile(e), { newApiFiles: i, existingApiFiles: s } = this.categorizeApisFromFiles(t), { newCollectionFiles: o, existingCollectionFiles: n } = this.categorizeCollectionsFromFiles(t), r = await this.findApisToReload(e), c = await this.findCollectionsToReload(e), p = [...i, ...o];
170
- p.length > 0 && await this.handleCreate(p), a && await this.reloadEnvironments();
171
- const u = this.consolidateFileEntries([...s, ...r]), f = this.consolidateFileEntries([
172
- ...n,
173
- ...c
174
- ]);
175
- await this.reloadApis(u), await this.reloadCollections(f);
176
- }
177
- /**
178
- * Handles file creation events.
179
- * If file already exists in state, update it instead of creating duplicate.
180
- */
181
- async handleCreate(e) {
182
- this.hasEnvironmentsFileChange(e) && await this.reloadEnvironments();
183
- const a = this.withoutEnvironmentsFile(e), t = a.filter((c) => c.type === "api"), i = a.filter((c) => c.type === "collection"), { newApiFiles: s, existingApiFiles: o } = this.categorizeApisFromFiles(t), { newCollectionFiles: n, existingCollectionFiles: r } = this.categorizeCollectionsFromFiles(i);
184
- if (s.length > 0 || n.length > 0) {
185
- s.forEach((h) => this.storage.addPersistExcludedId(h.relative_path)), n.forEach((h) => this.storage.addPersistExcludedId(h.relative_path));
186
- const c = s.length > 0 ? await this.tauriStorage.loadAndParseApis(s, void 0, !0) : [], p = n.length > 0 ? await this.tauriStorage.loadAndParseCollections(n, void 0) : [], u = c.filter((h) => h !== null), f = p.filter((h) => h !== null);
187
- this.apis.set([...this.apis.get(), ...u]), this.collections.set([...this.collections.get(), ...f]), this.indexApis(u), this.indexCollections(f), setTimeout(() => {
188
- s.forEach((h) => this.storage.removePersistExcludedId(h.relative_path)), n.forEach(
189
- (h) => this.storage.removePersistExcludedId(h.relative_path)
190
- );
191
- }, 500);
192
- }
193
- o.length > 0 && await this.reloadApis(o), r.length > 0 && await this.reloadCollections(r);
194
- }
195
- /**
196
- * Categorize API paths into new vs existing
197
- */
198
- /**
199
- * Categorize API files into new vs existing
200
- */
201
- categorizeApisFromFiles(e) {
202
- const a = /* @__PURE__ */ new Set(), t = [], i = [];
203
- for (const s of e) {
204
- if (a.has(s.relative_path))
205
- continue;
206
- a.add(s.relative_path), this.apis.get().some((n) => n.id === s.relative_path) ? i.push(s) : s.type === "api" && t.push(s);
207
- }
208
- return { newApiFiles: t, existingApiFiles: i };
209
- }
210
- /**
211
- * Categorize collection files into new vs existing
212
- */
213
- categorizeCollectionsFromFiles(e) {
214
- const a = /* @__PURE__ */ new Set(), t = [], i = [];
215
- for (const s of e) {
216
- if (a.has(s.relative_path))
217
- continue;
218
- a.add(s.relative_path), this.collections.get().some((n) => n.id === s.relative_path) ? i.push(s) : s.type === "collection" && t.push(s);
219
- }
220
- return { newCollectionFiles: t, existingCollectionFiles: i };
221
- }
222
- /**
223
- * Handles file deletion events.
224
- */
225
- async handleDelete(e) {
226
- this.hasEnvironmentsFileChange(e) && await this.reloadEnvironments();
227
- const a = [], t = [];
228
- for (const i of this.withoutEnvironmentsFile(e)) {
229
- this.storage.addPersistExcludedId(i.relative_path);
230
- const s = this.apis.get();
231
- s.some((r) => r.id === i.relative_path) && (this.apis.set(s.filter((r) => r.id !== i.relative_path)), this.tauriStorage.deleteApiFromCache(i.relative_path), a.push(i.relative_path));
232
- const o = this.collections.get(), n = o.findIndex(
233
- (r) => r.id === i.relative_path
234
- );
235
- n >= 0 && (this.collections.set(o.filter((r, c) => c !== n)), t.push(i.relative_path)), setTimeout(() => {
236
- this.storage.removePersistExcludedId(i.relative_path);
237
- }, 500);
238
- }
239
- this.removeApis(a), this.removeCollections(t);
240
- }
241
- /**
242
- * Handles file rename/move events.
243
- * For rename events, files typically contains [oldFile, newFile]
244
- */
245
- async handleRename(e) {
246
- if (e.length >= 2) {
247
- const [a, t] = e;
248
- await this.handleDelete([a]), await this.handleCreate([t]);
249
- } else
250
- await this.handleCreate(e);
251
- }
252
- /**
253
- * Checks if the project folder itself was renamed/moved/deleted.
254
- * This happens when:
255
- * - We get a rename/delete event for the project directory itself
256
- * - Or when paths no longer match the watched directory structure
257
- */
258
- async isProjectFolderRemoved(e, a) {
259
- if (e.length === 0)
260
- return !1;
261
- if (a === "deleted" || a === "renamed") {
262
- for (const i of e)
263
- if (i === this.projectDir)
264
- return !0;
265
- }
266
- return e.filter(
267
- (i) => !i.startsWith(this.projectDir + "/") && i !== this.projectDir
268
- ).length > 0 && a === "renamed";
269
- }
270
- /**
271
- * Handles the case when the entire project folder is renamed or deleted.
272
- * Clears all APIs and collections from state.
273
- */
274
- async handleProjectFolderRemoval() {
275
- const e = this.apis.get(), a = e.map((s) => s.id);
276
- e.forEach((s) => {
277
- this.storage.addPersistExcludedId(s.id), this.tauriStorage.deleteApiFromCache(s.id);
278
- }), this.apis.set([]);
279
- const t = this.collections.get(), i = t.map((s) => s.id);
280
- t.forEach((s) => {
281
- this.storage.addPersistExcludedId(s.id);
282
- }), this.collections.set([]), setTimeout(() => {
283
- e.forEach((s) => this.storage.removePersistExcludedId(s.id)), t.forEach((s) => this.storage.removePersistExcludedId(s.id));
284
- }, 500), this.removeApis(a), this.removeCollections(i), await this.stop();
285
- }
286
- async findApisToReload(e) {
287
- const a = [];
288
- return await Promise.all(
289
- this.apis.get().map(async (t) => {
290
- const i = t.fileDependencies ?? /* @__PURE__ */ new Set(), s = t.id, o = e.find((n) => i.has(n.absolute_path));
291
- if (!this.storage.isWatchExcluded(s) && o) {
292
- const n = await E.join(this.projectDir, s);
293
- a.push({
294
- relative_path: s,
295
- absolute_path: n,
296
- type: "api"
297
- });
298
- }
299
- })
300
- ), a;
301
- }
302
- async findCollectionsToReload(e) {
303
- const a = [];
304
- return await Promise.all(
305
- this.collections.get().map(async (t) => {
306
- const i = t.fileDependencies ?? /* @__PURE__ */ new Set(), s = t.id, o = e.find((n) => i.has(n.absolute_path));
307
- if (!this.storage.isWatchExcluded(s) && o) {
308
- const n = await E.join(this.projectDir, s);
309
- a.push({
310
- relative_path: s,
311
- absolute_path: n,
312
- type: "collection"
313
- });
314
- }
315
- })
316
- ), a;
317
- }
318
- async reloadEnvironments() {
319
- const e = await this.tauriStorage.readEnviroments();
320
- this.storage.addPersistExcludedId(d), this.setEnvironments(e.length > 0 ? e : F(C)), this.storage.publishEnvironmentsConfigError(), setTimeout(() => {
321
- this.storage.removePersistExcludedId(d);
322
- }, 500);
323
- }
324
- async reloadApis(e) {
325
- if (e.length === 0) return;
326
- const a = await this.tauriStorage.loadAndParseApis(e, void 0, !0), t = [];
327
- await Promise.all(
328
- a.map(async (i, s) => {
329
- if (!i) {
330
- await this.handleDelete([e[s]]);
331
- return;
332
- }
333
- const o = this.apis.get();
334
- o.some((n) => n.id === i.id) ? (this.storage.addPersistExcludedId(i.id), this.apis.set(o.map((n) => n.id === i.id ? i : n)), t.push(i), setTimeout(() => this.storage.removePersistExcludedId(i.id), 500)) : console.warn("API not found in state after reload:", i.id);
335
- })
336
- ), t.length > 0 && this.indexApis(t);
337
- }
338
- async reloadCollections(e) {
339
- if (e.length === 0) return;
340
- const a = await this.tauriStorage.loadAndParseCollections(e, void 0), t = [];
341
- await Promise.all(
342
- a.map(async (i, s) => {
343
- if (!i) {
344
- await this.handleDelete([e[s]]);
345
- return;
346
- }
347
- const o = this.collections.get(), n = o.findIndex((r) => r.id === i.id);
348
- n >= 0 ? (this.storage.addPersistExcludedId(i.id), this.collections.set(
349
- o.map(
350
- (r, c) => c === n ? i : r
351
- )
352
- ), t.push(i), setTimeout(() => this.storage.removePersistExcludedId(i.id), 500)) : console.warn("Collection not found in state after reload:", i.id);
353
- })
354
- ), t.length > 0 && this.indexCollections(t);
355
- }
356
- }
357
- export {
358
- P as FileWatcher
359
- };
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./replay-index-DYtXcqDk.js"),c=require("./replay-Observable-bjJ6wkRB.js"),o=new Set(["node_modules"]);class l extends c.Observable{constructor(e){super(),this.baseDir=e,this.initializeDirectory(e)}baseDir;writeExcludedKeys=new Set;writeEndTimers=new Map;async initializeDirectory(e){await s.mkdir(e,{recursive:!0})}setWriteExcludedKeys(e){this.writeExcludedKeys=e}async ls(e){const t=await this.getFullPath(e);return this.getDirEntryFilesRecursively(t)}async getDirEntryFilesRecursively(e){try{const t=[],i=await s.readDir(e);for(const r of i)if(r.isDirectory){if(o.has(r.name))continue;const n=await s.join(e,r.name),a=await this.getDirEntryFilesRecursively(n);t.push(...a)}else{const n=await s.join(e,r.name),a=await s.PathUtils.relative(this.baseDir,n);t.push(a)}return t}catch(t){return t.includes("forbidden path")||console.error(t),[]}}async get(e){const t=await this.getFullPath(e);try{return await s.readTextFile(t)}catch(i){return!i.includes("No such file or directory")&&!i.includes("forbidden path")&&console.error(i),null}}async has(e){const t=await this.getFullPath(e);return await s.exists(t)}async set(e,t){if(!this.writeExcludedKeys.has(e)){this.emit("write-start",e);try{const i=await this.getFullPath(e),r=s.sep(),n=i.split(r).slice(0,-1).join(r);await s.mkdir(n,{recursive:!0}),await s.writeTextFile(i,t)}finally{const i=this.writeEndTimers.get(e);i&&clearTimeout(i);const r=setTimeout(()=>{this.emit("write-end",e),this.writeEndTimers.delete(e)},1e3);this.writeEndTimers.set(e,r)}}}async remove(e){if(!this.writeExcludedKeys.has(e)){this.emit("write-start",e);try{const t=await this.getFullPath(e);await s.remove(t)}catch(t){!t.includes("No such file or directory")&&!t.includes("forbidden path")&&console.error(t)}finally{const t=this.writeEndTimers.get(e);t&&clearTimeout(t);const i=setTimeout(()=>{this.emit("write-end",e),this.writeEndTimers.delete(e)},1e3);this.writeEndTimers.set(e,i)}}}async rename(e,t){const i=await this.getFullPath(e),r=await this.getFullPath(t);await s.rename(i,r)}async getFullPath(e){return await s.join(this.baseDir,e??"")}}exports.TauriFileSystemAdapter=l;
@@ -1,99 +0,0 @@
1
- import { m as c, r as o, j as a, P as l, b as u, e as d, s as h, w, d as m, f as y } from "./replay-index-BCz452N6.js";
2
- import { O as f } from "./replay-Observable-D6wKbFwB.js";
3
- const E = /* @__PURE__ */ new Set(["node_modules"]);
4
- class p extends f {
5
- constructor(t) {
6
- super(), this.baseDir = t, this.initializeDirectory(t);
7
- }
8
- baseDir;
9
- writeExcludedKeys = /* @__PURE__ */ new Set();
10
- writeEndTimers = /* @__PURE__ */ new Map();
11
- async initializeDirectory(t) {
12
- await c(t, {
13
- recursive: !0
14
- });
15
- }
16
- setWriteExcludedKeys(t) {
17
- this.writeExcludedKeys = t;
18
- }
19
- async ls(t) {
20
- const e = await this.getFullPath(t);
21
- return this.getDirEntryFilesRecursively(e);
22
- }
23
- async getDirEntryFilesRecursively(t) {
24
- try {
25
- const e = [], i = await o(t);
26
- for (const s of i)
27
- if (s.isDirectory) {
28
- if (E.has(s.name))
29
- continue;
30
- const r = await a(t, s.name), n = await this.getDirEntryFilesRecursively(r);
31
- e.push(...n);
32
- } else {
33
- const r = await a(t, s.name), n = await l.relative(this.baseDir, r);
34
- e.push(n);
35
- }
36
- return e;
37
- } catch (e) {
38
- return e.includes("forbidden path") || console.error(e), [];
39
- }
40
- }
41
- async get(t) {
42
- const e = await this.getFullPath(t);
43
- try {
44
- return await u(e);
45
- } catch (i) {
46
- return !i.includes("No such file or directory") && !i.includes("forbidden path") && console.error(i), null;
47
- }
48
- }
49
- async has(t) {
50
- const e = await this.getFullPath(t);
51
- return await d(e);
52
- }
53
- async set(t, e) {
54
- if (!this.writeExcludedKeys.has(t)) {
55
- this.emit("write-start", t);
56
- try {
57
- const i = await this.getFullPath(t), s = h(), r = i.split(s).slice(0, -1).join(s);
58
- await c(r, {
59
- recursive: !0
60
- }), await w(i, e);
61
- } finally {
62
- const i = this.writeEndTimers.get(t);
63
- i && clearTimeout(i);
64
- const s = setTimeout(() => {
65
- this.emit("write-end", t), this.writeEndTimers.delete(t);
66
- }, 1e3);
67
- this.writeEndTimers.set(t, s);
68
- }
69
- }
70
- }
71
- async remove(t) {
72
- if (!this.writeExcludedKeys.has(t)) {
73
- this.emit("write-start", t);
74
- try {
75
- const e = await this.getFullPath(t);
76
- await m(e);
77
- } catch (e) {
78
- !e.includes("No such file or directory") && !e.includes("forbidden path") && console.error(e);
79
- } finally {
80
- const e = this.writeEndTimers.get(t);
81
- e && clearTimeout(e);
82
- const i = setTimeout(() => {
83
- this.emit("write-end", t), this.writeEndTimers.delete(t);
84
- }, 1e3);
85
- this.writeEndTimers.set(t, i);
86
- }
87
- }
88
- }
89
- async rename(t, e) {
90
- const i = await this.getFullPath(t), s = await this.getFullPath(e);
91
- await y(i, s);
92
- }
93
- async getFullPath(t) {
94
- return await a(this.baseDir, t ?? "");
95
- }
96
- }
97
- export {
98
- p as TauriFileSystemAdapter
99
- };
@@ -1 +0,0 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const p=require("./replay-index-DYtXcqDk.js"),Y=require("./replay-promise-map-limit-DRDkHc-b.js"),G=require("./replay-TauriFileSystemAdapter-CwSMakdJ.js");var U={exports:{}},V;function oe(){return V||(V=1,(function(s){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function n(a,u,h){this.fn=a,this.context=u,this.once=h||!1}function o(a,u,h,f,g){if(typeof h!="function")throw new TypeError("The listener must be a function");var y=new n(h,f||a,g),v=t?t+u:u;return a._events[v]?a._events[v].fn?a._events[v]=[a._events[v],y]:a._events[v].push(y):(a._events[v]=y,a._eventsCount++),a}function d(a,u){--a._eventsCount===0?a._events=new r:delete a._events[u]}function c(){this._events=new r,this._eventsCount=0}c.prototype.eventNames=function(){var u=[],h,f;if(this._eventsCount===0)return u;for(f in h=this._events)e.call(h,f)&&u.push(t?f.slice(1):f);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(h)):u},c.prototype.listeners=function(u){var h=t?t+u:u,f=this._events[h];if(!f)return[];if(f.fn)return[f.fn];for(var g=0,y=f.length,v=new Array(y);g<y;g++)v[g]=f[g].fn;return v},c.prototype.listenerCount=function(u){var h=t?t+u:u,f=this._events[h];return f?f.fn?1:f.length:0},c.prototype.emit=function(u,h,f,g,y,v){var b=t?t+u:u;if(!this._events[b])return!1;var l=this._events[b],T=arguments.length,Q,w;if(l.fn){switch(l.once&&this.removeListener(u,l.fn,void 0,!0),T){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,h),!0;case 3:return l.fn.call(l.context,h,f),!0;case 4:return l.fn.call(l.context,h,f,g),!0;case 5:return l.fn.call(l.context,h,f,g,y),!0;case 6:return l.fn.call(l.context,h,f,g,y,v),!0}for(w=1,Q=new Array(T-1);w<T;w++)Q[w-1]=arguments[w];l.fn.apply(l.context,Q)}else{var ae=l.length,x;for(w=0;w<ae;w++)switch(l[w].once&&this.removeListener(u,l[w].fn,void 0,!0),T){case 1:l[w].fn.call(l[w].context);break;case 2:l[w].fn.call(l[w].context,h);break;case 3:l[w].fn.call(l[w].context,h,f);break;case 4:l[w].fn.call(l[w].context,h,f,g);break;default:if(!Q)for(x=1,Q=new Array(T-1);x<T;x++)Q[x-1]=arguments[x];l[w].fn.apply(l[w].context,Q)}}return!0},c.prototype.on=function(u,h,f){return o(this,u,h,f,!1)},c.prototype.once=function(u,h,f){return o(this,u,h,f,!0)},c.prototype.removeListener=function(u,h,f,g){var y=t?t+u:u;if(!this._events[y])return this;if(!h)return d(this,y),this;var v=this._events[y];if(v.fn)v.fn===h&&(!g||v.once)&&(!f||v.context===f)&&d(this,y);else{for(var b=0,l=[],T=v.length;b<T;b++)(v[b].fn!==h||g&&!v[b].once||f&&v[b].context!==f)&&l.push(v[b]);l.length?this._events[y]=l.length===1?l[0]:l:d(this,y)}return this},c.prototype.removeAllListeners=function(u){var h;return u?(h=t?t+u:u,this._events[h]&&d(this,h)):(this._events=new r,this._eventsCount=0),this},c.prototype.off=c.prototype.removeListener,c.prototype.addListener=c.prototype.on,c.prefixed=t,c.EventEmitter=c,s.exports=c})(U)),U.exports}var ue=oe();const le=p.getDefaultExportFromCjs(ue);class re extends Error{constructor(e){super(e),this.name="TimeoutError"}}let ce=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};const J=s=>globalThis.DOMException===void 0?new ce(s):new DOMException(s),H=s=>{const e=s.reason===void 0?J("This operation was aborted."):s.reason;return e instanceof Error?e:J(e)};function he(s,e,t,r){let n;const o=new Promise((d,c)=>{if(typeof e!="number"||Math.sign(e)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${e}\``);if(e===Number.POSITIVE_INFINITY){d(s);return}if(r={customTimers:{setTimeout,clearTimeout},...r},r.signal){const{signal:a}=r;a.aborted&&c(H(a)),a.addEventListener("abort",()=>{c(H(a))})}n=r.customTimers.setTimeout.call(void 0,()=>{const a=`Promise timed out after ${e} milliseconds`,u=t instanceof Error?t:new re(a);typeof s.cancel=="function"&&s.cancel(),c(u)},e),(async()=>{try{d(await s)}catch(a){c(a)}finally{r.customTimers.clearTimeout.call(void 0,n)}})()});return o.clear=()=>{clearTimeout(n),n=void 0},o}function fe(s,e,t){let r=0,n=s.length;for(;n>0;){const o=Math.trunc(n/2);let d=r+o;t(s[d],e)<=0?(r=++d,n-=o+1):n=o}return r}var F=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},A;class de{constructor(){A.set(this,[])}enqueue(e,t){t={priority:0,...t};const r={priority:t.priority,run:e};if(this.size&&F(this,A,"f")[this.size-1].priority>=t.priority){F(this,A,"f").push(r);return}const n=fe(F(this,A,"f"),r,(o,d)=>d.priority-o.priority);F(this,A,"f").splice(n,0,r)}dequeue(){const e=F(this,A,"f").shift();return e?.run}filter(e){return F(this,A,"f").filter(t=>t.priority===e.priority).map(t=>t.run)}get size(){return F(this,A,"f").length}}A=new WeakMap;var m=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},i=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},_,L,M,I,R,N,z,E,O,P,k,S,W,C,q,X,Z,ie,ee,te,D,B,K,$,se,j;class ne extends Error{}class pe extends le{constructor(e){var t,r,n,o;if(super(),_.add(this),L.set(this,void 0),M.set(this,void 0),I.set(this,0),R.set(this,void 0),N.set(this,void 0),z.set(this,0),E.set(this,void 0),O.set(this,void 0),P.set(this,void 0),k.set(this,void 0),S.set(this,0),W.set(this,void 0),C.set(this,void 0),q.set(this,void 0),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e={carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:de,...e},!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(t=e.intervalCap)===null||t===void 0?void 0:t.toString())!==null&&r!==void 0?r:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(o=(n=e.interval)===null||n===void 0?void 0:n.toString())!==null&&o!==void 0?o:""}\` (${typeof e.interval})`);m(this,L,e.carryoverConcurrencyCount,"f"),m(this,M,e.intervalCap===Number.POSITIVE_INFINITY||e.interval===0,"f"),m(this,R,e.intervalCap,"f"),m(this,N,e.interval,"f"),m(this,P,new e.queueClass,"f"),m(this,k,e.queueClass,"f"),this.concurrency=e.concurrency,this.timeout=e.timeout,m(this,q,e.throwOnTimeout===!0,"f"),m(this,C,e.autoStart===!1,"f")}get concurrency(){return i(this,W,"f")}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);m(this,W,e,"f"),i(this,_,"m",$).call(this)}async add(e,t={}){return t={timeout:this.timeout,throwOnTimeout:i(this,q,"f"),...t},new Promise((r,n)=>{i(this,P,"f").enqueue(async()=>{var o,d,c;m(this,S,(d=i(this,S,"f"),d++,d),"f"),m(this,I,(c=i(this,I,"f"),c++,c),"f");try{if(!((o=t.signal)===null||o===void 0)&&o.aborted)throw new ne("The task was aborted.");let a=e({signal:t.signal});t.timeout&&(a=he(Promise.resolve(a),t.timeout)),t.signal&&(a=Promise.race([a,i(this,_,"m",se).call(this,t.signal)]));const u=await a;r(u),this.emit("completed",u)}catch(a){if(a instanceof re&&!t.throwOnTimeout){r();return}n(a),this.emit("error",a)}finally{i(this,_,"m",ie).call(this)}},t),this.emit("add"),i(this,_,"m",D).call(this)})}async addAll(e,t){return Promise.all(e.map(async r=>this.add(r,t)))}start(){return i(this,C,"f")?(m(this,C,!1,"f"),i(this,_,"m",$).call(this),this):this}pause(){m(this,C,!0,"f")}clear(){m(this,P,new(i(this,k,"f")),"f")}async onEmpty(){i(this,P,"f").size!==0&&await i(this,_,"m",j).call(this,"empty")}async onSizeLessThan(e){i(this,P,"f").size<e||await i(this,_,"m",j).call(this,"next",()=>i(this,P,"f").size<e)}async onIdle(){i(this,S,"f")===0&&i(this,P,"f").size===0||await i(this,_,"m",j).call(this,"idle")}get size(){return i(this,P,"f").size}sizeBy(e){return i(this,P,"f").filter(e).length}get pending(){return i(this,S,"f")}get isPaused(){return i(this,C,"f")}}L=new WeakMap,M=new WeakMap,I=new WeakMap,R=new WeakMap,N=new WeakMap,z=new WeakMap,E=new WeakMap,O=new WeakMap,P=new WeakMap,k=new WeakMap,S=new WeakMap,W=new WeakMap,C=new WeakMap,q=new WeakMap,_=new WeakSet,X=function(){return i(this,M,"f")||i(this,I,"f")<i(this,R,"f")},Z=function(){return i(this,S,"f")<i(this,W,"f")},ie=function(){var e;m(this,S,(e=i(this,S,"f"),e--,e),"f"),i(this,_,"m",D).call(this),this.emit("next")},ee=function(){i(this,_,"m",K).call(this),i(this,_,"m",B).call(this),m(this,O,void 0,"f")},te=function(){const e=Date.now();if(i(this,E,"f")===void 0){const t=i(this,z,"f")-e;if(t<0)m(this,I,i(this,L,"f")?i(this,S,"f"):0,"f");else return i(this,O,"f")===void 0&&m(this,O,setTimeout(()=>{i(this,_,"m",ee).call(this)},t),"f"),!0}return!1},D=function(){if(i(this,P,"f").size===0)return i(this,E,"f")&&clearInterval(i(this,E,"f")),m(this,E,void 0,"f"),this.emit("empty"),i(this,S,"f")===0&&this.emit("idle"),!1;if(!i(this,C,"f")){const e=!i(this,_,"a",te);if(i(this,_,"a",X)&&i(this,_,"a",Z)){const t=i(this,P,"f").dequeue();return t?(this.emit("active"),t(),e&&i(this,_,"m",B).call(this),!0):!1}}return!1},B=function(){i(this,M,"f")||i(this,E,"f")!==void 0||(m(this,E,setInterval(()=>{i(this,_,"m",K).call(this)},i(this,N,"f")),"f"),m(this,z,Date.now()+i(this,N,"f"),"f"))},K=function(){i(this,I,"f")===0&&i(this,S,"f")===0&&i(this,E,"f")&&(clearInterval(i(this,E,"f")),m(this,E,void 0,"f")),m(this,I,i(this,L,"f")?i(this,S,"f"):0,"f"),i(this,_,"m",$).call(this)},$=function(){for(;i(this,_,"m",D).call(this););},se=async function(e){return new Promise((t,r)=>{e.addEventListener("abort",()=>{r(new ne("The task was aborted."))},{once:!0})})},j=async function(e,t){return new Promise(r=>{const n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)})};class ve{constructor(e){this.apisStorage=e}apisStorage;data=new Map;loading=new Set;pQueue=new pe({concurrency:20});async get(e){return this.data.has(e)?this.data.get(e)??null:(await this.loadAndParse(e),this.data.get(e)??null)}async load(e,t=!1){this.data.has(e)&&!t||await this.loadAndParse(e,t)}async loadAndParse(e,t=!1){if(this.loading.has(e)){await this.pQueue.add(()=>this.get(e));return}t&&this.data.delete(e),this.loading.add(e),await this.pQueue.add(async()=>{const r=p.isWebUrl(e)?p.SourceType.WEB:p.SourceType.FS,n=r===p.SourceType.WEB?e:await this.apisStorage.getAbsolutePath(e);try{const{definition:o,fileDependencies:d}=await p.loadAndBundleDefinition(n);if(!o){this.data.set(e,null),await p.clearNotificationsForSource(e);return}const c=this.apisStorage.parse({uri:e,type:r,content:o});this.data.set(e,{...c,fileDependencies:d}),await p.clearNotificationsForSource(e)}catch(o){if(this.data.set(e,null),o instanceof Error&&(o.message.includes("Unsupported specification")||o.message.includes("File not found"))){await p.clearNotificationsForSource(e);return}console.info("Error loading api "+e,o),await p.reportParseError(e,o);return}}),this.loading.delete(e)}get size(){return this.data.size}delete(e){this.data.delete(e)}getAll(){return Array.from(this.data.values()).filter(e=>e!==null)}clear(){this.data.clear(),this.loading.clear()}}class me extends p.RootStorage{apiLoader;constructor(e,t,r){const n=new G.TauriFileSystemAdapter(e.systemFilesDir),o=new G.TauriFileSystemAdapter(e.userFilesDir);super(n,o,e,!0,!1,t,r),this.apiLoader=new ve(this.apisStorage),this.setupWriteListeners(o)}setupWriteListeners(e){e.on("write-start",t=>{this.addWatchExcludedId(t)}),e.on("write-end",t=>{this.removeWatchExcludedId(t)})}async read(){const e=this.telemetry?.startSpan("com.redocly.storage.read",[p.createResource("storageOperation","read","storage")],void 0),t=this.telemetry?.startSpan("com.redocly.storage.loadUserState",[p.createResource("storageOperation","loadUserState","storage")],e?.parentCtx),[r,n,o]=await Promise.all([this.activeEnvironmentIdStorage.read(),this.tabsStateStorage.read(),this.environmentsStorage.read()]);t?.setAttribute("status","completed"),t?.setAttribute("environmentCount",o.length),t?.setStatus(p.SpanStatusCode.OK),t?.end();const{apiFiles:d,collectionFiles:c}=await this.detectProjectFiles(e);await this.loadAndParseApis(d,e);const u=(await this.loadAndParseCollections(c,e)).filter(f=>f!==null),h=this.apiLoader.getAll();return e?.setAttribute("status","completed"),e?.setStatus(p.SpanStatusCode.OK),e?.end(),{project:this.project,activeEnvironmentId:r,tabsState:n,environments:o,apis:h,collections:u}}async detectProjectFiles(e){const t=this.telemetry?.startSpan("com.redocly.storage.detectFiles",[p.createResource("storageOperation","detectFiles","storage")],e?.parentCtx),{api_files:r,collection_files:n}=await p.invoke("fs_scan",{dir:this.project.userFilesDir});return t?.setAttribute("status","completed"),t?.setAttribute("filesCount",r.length+n.length),t?.setAttribute("apiFilesCount",r.length),t?.setAttribute("collectionFilesCount",n.length),t?.setStatus(p.SpanStatusCode.OK),t?.end(),{apiFiles:r,collectionFiles:n}}readEnviroments(){return this.environmentsStorage.read()}deleteApiFromCache(e){this.apiLoader.delete(e)}async loadAndParseApis(e,t,r=!1){const n=this.telemetry?.startSpan("com.redocly.storage.parseApis",[{...p.createResource("storageOperation","parseApis","storage"),apisCount:e.length}],t?.parentCtx),o=await Y.promiseMapLimit(e,20,async d=>{try{return await this.apiLoader.load(d.relative_path,r),this.apiLoader.get(d.relative_path)}catch(c){return console.info(`Error parsing YAML/JSON file ${d.absolute_path}:`,c),await p.reportParseError(d.relative_path,c),null}});return n?.setAttribute("status","completed"),n?.setAttribute("parsedApisCount",this.apiLoader.size),n?.setStatus(p.SpanStatusCode.OK),n?.end(),o}async loadAndParseCollections(e,t){const r=this.telemetry?.startSpan("com.redocly.storage.parseCollections",[{...p.createResource("storageOperation","parseCollections","storage"),collectionsCount:e.length}],t?.parentCtx),n=await Y.promiseMapLimit(e,20,async o=>{try{const d=await this.userFilesStorage.get(o.relative_path);if(!d)return null;const c=p.yaml.load(d);if(typeof c!="object"||c===null||typeof c.arazzo!="string")return await p.clearNotificationsForSource(o.relative_path),null;const a=[];await Promise.all(c.sourceDescriptions?.map(async f=>{const g=f.type,y=f.url,v=!g||g==="openapi",b=await p.apiUrlToApiId({projectPath:this.project.userFilesDir,apiUrl:y,collectionId:o.relative_path});if(v){const l=await this.apiLoader.get(b);l&&a.push(l)}}));const u=await p.PathUtils.join(this.project.userFilesDir,o.relative_path),h=await this.collectionsStorage.parse({uri:o.relative_path,type:p.SourceType.FS,content:c,fileDependencies:new Set([u])},a);return await p.clearNotificationsForSource(o.relative_path),h}catch(d){return console.info(`Error parsing Arazzo file ${o.relative_path}:`,d),await p.reportParseError(o.relative_path,d),null}});return r?.setAttribute("status","completed"),r?.setAttribute("parsedCollectionsCount",n.length),r?.setStatus(p.SpanStatusCode.OK),r?.end(),n}}exports.TauriRootStorage=me;
@@ -1,4 +0,0 @@
1
- import { g as r } from "./replay-SemanticSearchService-BLF1oOOu.js";
2
- export {
3
- r as getSemanticSearchService
4
- };