sliccy 6.141.2 → 6.141.3

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 (130) hide show
  1. package/dist/ui/.vite/manifest.json +165 -165
  2. package/dist/ui/assets/__vite-browser-external-oXcxoO19.js +1 -0
  3. package/dist/ui/assets/{account-store-CEOiQheZ.js → account-store-CDR1C1oH.js} +1 -1
  4. package/dist/ui/assets/{account-store-1giUExSS.js → account-store-OqSCLUiN.js} +1 -1
  5. package/dist/ui/assets/{adobe-CuKX_Gw4.js → adobe-DOKmLQCK.js} +1 -1
  6. package/dist/ui/assets/{adobe-CAJTksuy.js → adobe-VmM9LuAK.js} +1 -1
  7. package/dist/ui/assets/{agent-bridge-UBo80Ndw.js → agent-bridge-CcjfBcbz.js} +1 -1
  8. package/dist/ui/assets/{agent-panels-DyOEhG6c.js → agent-panels-C0onsdTK.js} +1 -1
  9. package/dist/ui/assets/{apply-layout-VtuQ2xkc.js → apply-layout-Bn1R7u85.js} +1 -1
  10. package/dist/ui/assets/{apps-U1kwfX_v.js → apps-ZExW_fDs.js} +1 -1
  11. package/dist/ui/assets/{azure-openai-Ddl-lvTg.js → azure-openai-Bq1gxkhj.js} +1 -1
  12. package/dist/ui/assets/{azure-openai-Cqv8rGOp.js → azure-openai-VEnHlRuV.js} +1 -1
  13. package/dist/ui/assets/{bsh-watchdog-ClwrdzEH.js → bsh-watchdog-DqSIi75u.js} +1 -1
  14. package/dist/ui/assets/{budget-usage-source-D542v3BA.js → budget-usage-source-BBh4_xMQ.js} +1 -1
  15. package/dist/ui/assets/{cdp-CLhbRC4S.js → cdp-D4w-FTbd.js} +1 -1
  16. package/dist/ui/assets/{cerebras-_Db4_aiE.js → cerebras-BIJOby0i.js} +1 -1
  17. package/dist/ui/assets/{cerebras-CjIkFcWP.js → cerebras-BewEdNd6.js} +1 -1
  18. package/dist/ui/assets/{composer-speech-DaflYjI9.js → composer-speech-BMDdMTKQ.js} +1 -1
  19. package/dist/ui/assets/{connect-surface-XZmKRFD-.js → connect-surface-79MIyGAY.js} +1 -1
  20. package/dist/ui/assets/{core-CbzVRzJt.js → core-BkHMrXyn.js} +1 -1
  21. package/dist/ui/assets/{directed-approval-BN6dULqi.js → directed-approval-BcPMLVWo.js} +1 -1
  22. package/dist/ui/assets/{ensure-speech-assets-Czc4X1XD.js → ensure-speech-assets-B14FEqf-.js} +1 -1
  23. package/dist/ui/assets/{esbuild-wasm-L2Rk3D-4.js → esbuild-wasm-CY2jFm-D.js} +1 -1
  24. package/dist/ui/assets/{extension-media-capture-I_fwSF5G.js → extension-media-capture-BwxRQ-WA.js} +1 -1
  25. package/dist/ui/assets/{fs-CGTZ8FRd.js → fs-BFK8H_mF.js} +1 -1
  26. package/dist/ui/assets/{fs-BA09m1QZ.js → fs-DsEo-CTs.js} +2 -2
  27. package/dist/ui/assets/{github-PSX9aEBn.js → github-BhmFLTRs.js} +2 -2
  28. package/dist/ui/assets/{github-Cq2ILMY9.js → github-DZ4if-qZ.js} +1 -1
  29. package/dist/ui/assets/{github-copilot-D-4VMd3T.js → github-copilot-DnRaZK_M.js} +1 -1
  30. package/dist/ui/assets/{github-copilot-DG4ZIs2I.js → github-copilot-U9KFOJEm.js} +1 -1
  31. package/dist/ui/assets/{github-install-ldpkPFFj.js → github-install-2Ug7GRRI.js} +1 -1
  32. package/dist/ui/assets/{github-zip-CNnBN_eK.js → github-zip-BgbkZRd2.js} +1 -1
  33. package/dist/ui/assets/{guest-tool-gate-g70kqGoB.js → guest-tool-gate-CwWcQt6s.js} +1 -1
  34. package/dist/ui/assets/{hear-D1MeyTuZ.js → hear-CdVBwJxW.js} +1 -1
  35. package/dist/ui/assets/{help-CtvHLjUb.js → help-02vmB0PN.js} +1 -1
  36. package/dist/ui/assets/{installer-DK4dNFOa.js → installer-CTX50_zb.js} +1 -1
  37. package/dist/ui/assets/js-realm-worker-DntrRTxU.js +50 -0
  38. package/dist/ui/assets/{kernel-worker-gHxPjWqC.js → kernel-worker-cOT-nF92.js} +584 -584
  39. package/dist/ui/assets/{local-llm-795gKzFO.js → local-llm-Ct2zoONz.js} +1 -1
  40. package/dist/ui/assets/{local-llm-D9n5Pv4v.js → local-llm-DO05qCpu.js} +1 -1
  41. package/dist/ui/assets/{magick-wasm-IdXcHdTy.js → magick-wasm-DrHkiveP.js} +1 -1
  42. package/dist/ui/assets/{main-CmEbg5ii.js → main-Kp4I5rQC.js} +3 -3
  43. package/dist/ui/assets/{main-cherry--4qAV7sk.js → main-cherry-CZYiEfWz.js} +1 -1
  44. package/dist/ui/assets/{mount-WtleT3fD.js → mount-BlGkBXLX.js} +1 -1
  45. package/dist/ui/assets/{mount-recovery-BaCu7G48.js → mount-recovery-BkELRMZC.js} +1 -1
  46. package/dist/ui/assets/{mount-Cb23pYLO.js → mount-tnzaYGv8.js} +3 -3
  47. package/dist/ui/assets/{new-session-64SepVcs.js → new-session-CK-dv8Uj.js} +2 -2
  48. package/dist/ui/assets/{oauth-bootstrap-D-BY9eAI.js → oauth-bootstrap-DvfcDL78.js} +2 -2
  49. package/dist/ui/assets/{onboarding-orchestrator-bfS34kjc.js → onboarding-orchestrator-B5mIIefF.js} +1 -1
  50. package/dist/ui/assets/{openai-codex-D-x53dS9.js → openai-codex-DCX9X0rw.js} +1 -1
  51. package/dist/ui/assets/{openai-codex-zU3F7KlY.js → openai-codex-DendXsAj.js} +1 -1
  52. package/dist/ui/assets/{openrouter-Ba1JpnSb.js → openrouter-8be8gr7i.js} +1 -1
  53. package/dist/ui/assets/{openrouter-free-DQcwC3UT.js → openrouter-free-BfMTb2W7.js} +1 -1
  54. package/dist/ui/assets/{openrouter-free-BqJ3pQB2.js → openrouter-free-DD6Qaosl.js} +1 -1
  55. package/dist/ui/assets/{openrouter-CmS2rYhd.js → openrouter-nXMshaNH.js} +1 -1
  56. package/dist/ui/assets/{openrouter-oauth-DHUr88fi.js → openrouter-oauth-CmQPsN12.js} +1 -1
  57. package/dist/ui/assets/{openrouter-oauth-C-erOniu.js → openrouter-oauth-vKJGFRVJ.js} +1 -1
  58. package/dist/ui/assets/{panel-rpc-handlers-98Ajkixu.js → panel-rpc-handlers-BENTXBlL.js} +2 -2
  59. package/dist/ui/assets/{panelize-shell-BMyKc1pp.js → panelize-shell-toaG2G-p.js} +1 -1
  60. package/dist/ui/assets/{provider-C5Z0FLhi.js → provider-7ZZ5IAaH.js} +1 -1
  61. package/dist/ui/assets/{provider-D9l25_oW.js → provider-Cc9fYW0-.js} +2 -2
  62. package/dist/ui/assets/provider-settings-DJ5mCQCp.js +1 -0
  63. package/dist/ui/assets/provider-store-access-DExU-wl1.js +1 -0
  64. package/dist/ui/assets/provider-store-access-jrpXOE2e.js +1 -0
  65. package/dist/ui/assets/{providers-CDNZj56F.js → providers-CccaVwQm.js} +2 -2
  66. package/dist/ui/assets/{providers-DU6K5lm4.js → providers-DHrNt71c.js} +1 -1
  67. package/dist/ui/assets/py-realm-worker-CMUAG309.js +244 -0
  68. package/dist/ui/assets/{pyodide-BwD0AtZB.js → pyodide-BIBsaAI1.js} +2 -2
  69. package/dist/ui/assets/{quick-llm-CGmdkAbo.js → quick-llm-K9vKc8Ud.js} +1 -1
  70. package/dist/ui/assets/{recovery-screen-DbUQYiGt.js → recovery-screen-BYRgSmRA.js} +1 -1
  71. package/dist/ui/assets/{run-D5XnzhFr.js → run-CR5q-DCz.js} +2 -2
  72. package/dist/ui/assets/{run-BdNihxEm.js → run-DJMGsrtb.js} +1 -1
  73. package/dist/ui/assets/{run-CEO6EbaH.js → run-DJPYQDHB.js} +1 -1
  74. package/dist/ui/assets/{run-Brj7DLeJ.js → run-DcJO0Q_l.js} +1 -1
  75. package/dist/ui/assets/{run-C52p_9Qk.js → run-dSobJ2Jl.js} +1 -1
  76. package/dist/ui/assets/{setup-feature-flags-remote-Cvdn6hdM.js → setup-feature-flags-remote-C1qq4ZTv.js} +1 -1
  77. package/dist/ui/assets/shared-f0tP2HLX.js +1 -0
  78. package/dist/ui/assets/shared-pVZLJOGO.js +4 -0
  79. package/dist/ui/assets/sidecar-repair-C8zxoZAq.js +1 -0
  80. package/dist/ui/assets/{silent-renew-backoff-CtePV08H.js → silent-renew-backoff-Ccx1cluB.js} +1 -1
  81. package/dist/ui/assets/{skills-B-6EX8_-.js → skills-DlpDPS0V.js} +1 -1
  82. package/dist/ui/assets/slicc-version-Cjlsyldl.js +1 -0
  83. package/dist/ui/assets/{snapshot-WlEbVfgz.js → snapshot-CTWR15MP.js} +1 -1
  84. package/dist/ui/assets/{snapshot-features-ChRer_go.js → snapshot-features-BIZ6PQ0S.js} +1 -1
  85. package/dist/ui/assets/{soundscape-BVUWKD0V.js → soundscape-CkW-Gcfy.js} +1 -1
  86. package/dist/ui/assets/{speak-CgSo0rXK.js → speak-BrovnTsm.js} +1 -1
  87. package/dist/ui/assets/{sprinkle-manager-LMSdR63e.js → sprinkle-manager-B5nR8afu.js} +1 -1
  88. package/dist/ui/assets/{sprinkle-renderer-BGx8hJZ_.js → sprinkle-renderer-D4iP6_5Z.js} +1 -1
  89. package/dist/ui/assets/{state-97_6_0AF.js → state-XgRu82mi.js} +1 -1
  90. package/dist/ui/assets/{store-Czh0k7Ej.js → store-C-UwOtjF.js} +1 -1
  91. package/dist/ui/assets/{store-BsYziZmA.js → store-CYMOamMP.js} +1 -1
  92. package/dist/ui/assets/{sudo-BLu3k0lA.js → sudo-ocACPtd7.js} +1 -1
  93. package/dist/ui/assets/{sync-dialog-C2VQi8rS.js → sync-dialog-CwJUqcs0.js} +1 -1
  94. package/dist/ui/assets/{transformers-env-Dtjt9IFM.js → transformers-env--mgWdw0R.js} +1 -1
  95. package/dist/ui/assets/{tray-sidecar-CyZO4AI3.js → tray-sidecar-l3_U61FU.js} +1 -1
  96. package/dist/ui/assets/{upgrade-detection-BtelIV1o.js → upgrade-detection-DlCzP4lD.js} +1 -1
  97. package/dist/ui/assets/{voice-reply-DP6xzedi.js → voice-reply-ChfXGGOt.js} +1 -1
  98. package/dist/ui/assets/{wc-attach-CzsJrwZF.js → wc-attach-CnFlhppo.js} +2 -2
  99. package/dist/ui/assets/{wc-extension-wMcey-Cc.js → wc-extension-DeX-TlqV.js} +2 -2
  100. package/dist/ui/assets/{wc-follower-ByN9dVQ1.js → wc-follower-CC8jLdo7.js} +3 -3
  101. package/dist/ui/assets/{wc-follower-oauth-9hxhD2eL.js → wc-follower-oauth-BUNweTOx.js} +1 -1
  102. package/dist/ui/assets/{wc-live-TppgvY0W.js → wc-live-PsUc0Bl_.js} +6 -6
  103. package/dist/ui/assets/{wc-nav-CgkpNqYH.js → wc-nav-BANvh-0o.js} +2 -2
  104. package/dist/ui/assets/{wc-onboarding-D4pn4la8.js → wc-onboarding-DPixxui2.js} +2 -2
  105. package/dist/ui/assets/{wc-placeholder-BWlJ100a.js → wc-placeholder-DD_FPDH3.js} +3 -3
  106. package/dist/ui/assets/{wc-settings-nW_MRain.js → wc-settings-Cp5TJPHd.js} +3 -3
  107. package/dist/ui/assets/{wc-shell-BFq7cCkV.js → wc-shell-ngaz1xGJ.js} +3 -3
  108. package/dist/ui/assets/{wc-shortcut-config-DX1ZeRvp.js → wc-shortcut-config-DArDfV9f.js} +1 -1
  109. package/dist/ui/assets/{wc-shortcuts-Cofh5Gbv.js → wc-shortcuts-CLBUOdsH.js} +1 -1
  110. package/dist/ui/assets/{wc-sprinkles-f2qsZXFn.js → wc-sprinkles-B8KJmUa3.js} +2 -2
  111. package/dist/ui/assets/{wc-transcript-export-DaV1rNpE.js → wc-transcript-export-Dn0bSMDk.js} +2 -2
  112. package/dist/ui/assets/{wc-tray-ijuKOV8w.js → wc-tray-BkFcSYHj.js} +4 -4
  113. package/dist/ui/assets/welcome-detection-CM-e1SiO.js +1 -0
  114. package/dist/ui/assets/{whisper-session-CargUQnZ.js → whisper-session-C_0wh0Zg.js} +2 -2
  115. package/dist/ui/assets/{xai-grok-Bk0i1-e4.js → xai-grok-DMHiFuln.js} +1 -1
  116. package/dist/ui/assets/{xai-grok-DXFRDUbJ.js → xai-grok-jQN78mEE.js} +1 -1
  117. package/dist/ui/index.html +3 -3
  118. package/dist/ui/packages/webapp/index.html +3 -3
  119. package/package.json +4 -3
  120. package/dist/ui/assets/__vite-browser-external-B6A3FtA_.js +0 -1
  121. package/dist/ui/assets/js-realm-worker-CWWdnszr.js +0 -50
  122. package/dist/ui/assets/provider-settings-CqIZoy7n.js +0 -1
  123. package/dist/ui/assets/provider-store-access-B7Zu_WTv.js +0 -1
  124. package/dist/ui/assets/provider-store-access-CzfqGk9d.js +0 -1
  125. package/dist/ui/assets/py-realm-worker-BYQkpReo.js +0 -244
  126. package/dist/ui/assets/shared-Djytys1b.js +0 -1
  127. package/dist/ui/assets/shared-vu5AooI5.js +0 -4
  128. package/dist/ui/assets/sidecar-repair-Codn4wCd.js +0 -1
  129. package/dist/ui/assets/slicc-version-C4ygb52b.js +0 -1
  130. package/dist/ui/assets/welcome-detection-BPEhaGvB.js +0 -1
@@ -1,4 +1,4 @@
1
- import{t as e}from"./logger-DDBAeTLF.js";import"./navigation-watcher-BpA1OwJw.js";import"./wc-follower-oauth-9hxhD2eL.js";import{n as t,t as n}from"./pending-request-table-k-D7ZZsL.js";var r=e(`cdp`);function i(e){return e===4001?`CDP connection superseded by another SLICC tab/window on this instance`:e===4002?`CDP connection reset by proxy (upstream Chrome connection was re-established)`:`CDP connection closed`}var a=class{ws=null;nextId=1;_superseded=!1;pending=new n;listeners=new Map;_state=`disconnected`;stateListeners=new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:i}=e;return this._state=`connecting`,new Promise((e,a)=>{let o=setTimeout(()=>{this.cleanup(),a(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=i===void 0?new WebSocket(t):new WebSocket(t,i)}catch(e){clearTimeout(o),this._state=`disconnected`,a(e);return}this.ws.onopen=()=>{clearTimeout(o),this._state=`connected`,this._superseded=!1,r.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(o),this._state===`connecting`&&(r.error(`Connection failed`,{url:t}),this.cleanup(),a(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),r.info(`Disconnected`)}async send(e,t,n,i=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let a=this.nextId++,o={id:a,method:e};t&&(o.params=t),n&&(o.sessionId=n),r.debug(`Send`,{method:e,id:a,sessionId:n});let s=this.pending.issue(a,i,`CDP command timed out after ${i}ms: ${e}`);return this.ws.send(JSON.stringify(o)),s}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,n=3e4){return t(t=>(this.on(e,t),()=>this.off(e,t)),n,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;r.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(r.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;r.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){e===4001?(this._superseded=!0,r.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?r.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):r.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(i(e))}cleanup(e=`CDP client disconnected`){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(e),this.notifyState(`disconnected`,e)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}},o=class extends Error{step;name=`CommandAbortedError`;constructor(e){super(`Browser command aborted while ${e}. A CDP round trip already in flight cannot be cancelled, so it may still have been applied to the page; nothing after it was started.`),this.step=e}};function s(e,t){if(e?.aborted)throw new o(t)}function c(e,t){return e?{signal:e,error:()=>new o(t)}:void 0}function l(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new o(n));return}let a=()=>{clearTimeout(s),i(new o(n))},s=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function u(e,t,n){return t?t.aborted?Promise.reject(new o(n)):new Promise((r,i)=>{let a=()=>i(new o(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}var d=e(`har-recorder`),f=class{recordings=new Map;client;fs;eventCleanup=new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n,r){let i=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;s(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),s(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),s(r,`about to read the URL of tab ${e}`);let a=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,o={id:i,targetId:e,sessionId:t,filterCode:n,pendingRequests:new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),d.debug(`Started recording`,{recordingId:i,targetId:e,currentUrl:a}),i}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{let r=n;r.sessionId===t&&this.handleRequestWillBeSent(e,r)},i=n=>{let r=n;r.sessionId===t&&this.handleResponseReceived(e,r)},a=r=>{let i=r;i.sessionId===t&&this.handleLoadingFinished(e,i).catch(e=>{d.error(`Failed to process loadingFinished event`,{recordingId:n,requestId:i.requestId,error:e instanceof Error?e.message:String(e)})})},o=n=>{let r=n;r.sessionId===t&&this.handleLoadingFailed(e,r)},s=r=>{let i=r;if(i.sessionId!==t)return;let a=i.frame;if(!a?.parentId&&a?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=a.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{d.error(`Failed to save navigation snapshot`,{recordingId:n,error:e instanceof Error?e.message:String(e)})})}};this.client.on(`Network.requestWillBeSent`,r),this.client.on(`Network.responseReceived`,i),this.client.on(`Network.loadingFinished`,a),this.client.on(`Network.loadingFailed`,o),this.client.on(`Page.frameNavigated`,s),this.eventCleanup.set(n,()=>{this.client.off(`Network.requestWillBeSent`,r),this.client.off(`Network.responseReceived`,i),this.client.off(`Network.loadingFinished`,a),this.client.off(`Network.loadingFailed`,o),this.client.off(`Page.frameNavigated`,s)})}handleRequestWillBeSent(e,t){let{requestId:n,request:r,timestamp:i}=t;!n||!r||i==null||e.pendingRequests.set(n,{requestId:n,startTime:i*1e3,request:{method:r.method,url:r.url,headers:r.headers,postData:r.postData}})}handleResponseReceived(e,t){let{requestId:n,response:r}=t;if(!n||!r)return;let i=e.pendingRequests.get(n);i&&(i.response={status:r.status,statusText:r.statusText,headers:r.headers,mimeType:r.mimeType},i.timing=r.timing)}async handleLoadingFinished(e,t){let{requestId:n,timestamp:r}=t;if(!n||r==null)return;let i=e.pendingRequests.get(n);if(!i)return;i.endTime=r*1e3;try{let t=await this.client.send(`Network.getResponseBody`,{requestId:n},e.sessionId);i.responseBody=t.body,i.responseBodyBase64=t.base64Encoded===!0}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let{requestId:n}=t;n&&e.pendingRequests.delete(n)}buildHarEntry(e){if(!e.response)return null;let{request:t,response:n,timing:r,startTime:i,endTime:a,responseBody:o,responseBodyBase64:s}=e,c=a?a-i:0,l=[];try{let e=new URL(t.url);l=Array.from(e.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{}let u=r?(()=>{let e=(e,t)=>{if(e==null||t==null||e<0||t<0)return-1;let n=t-e;return n>=0?n:-1},t=r.dnsStart>=0?r.dnsStart:r.connectStart>=0?r.connectStart:0;return{blocked:t>0?t:-1,dns:e(r.dnsStart,r.dnsEnd),connect:e(r.connectStart,r.connectEnd),ssl:e(r.sslStart,r.sslEnd),send:e(r.sendStart,r.sendEnd),wait:e(r.sendEnd,r.receiveHeadersStart),receive:e(r.receiveHeadersStart,r.receiveHeadersEnd)}})():{blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:c,receive:0},d={size:o?.length??0,mimeType:n.mimeType??`application/octet-stream`};o&&(d.text=o,s&&(d.encoding=`base64`));let f;return t.postData&&(f={mimeType:t.headers[`content-type`]??t.headers[`Content-Type`]??`text/plain`,text:t.postData}),{startedDateTime:new Date(i).toISOString(),time:c,request:{method:t.method,url:t.url,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(t.headers).map(([e,t])=>({name:e,value:t})),queryString:l,postData:f,headersSize:-1,bodySize:t.postData?.length??0},response:{status:n.status,statusText:n.statusText,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(n.headers).map(([e,t])=>({name:e,value:t})),content:d,redirectURL:n.headers.location??n.headers.Location??``,headersSize:-1,bodySize:d.size},cache:{},timings:u}}async saveSnapshot(e,t){return this.saveSnapshotWithEntries(e,t,e.entries,e.currentUrl)}async applyFilter(e,t){return p(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return d.debug(`No entries to save`,{recordingId:e.id,trigger:t}),null;let i=e.filterCode?await this.applyFilter(n,e.filterCode):n;if(i.length===0)return d.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=new Date().toISOString().replace(/[:.]/g,`-`),o=this.urlToSlug(r),s=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${o}.har`,c=`/recordings/${e.id}/${s}`,l={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(c,JSON.stringify(l,null,2)),d.debug(`Saved HAR snapshot`,{recordingId:e.id,path:c,entryCount:i.length}),c}urlToSlug(e){try{let t=new URL(e);return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,50)||`page`}catch{return`page`}}async stopRecording(e){let t=this.recordings.get(e);if(!t)throw Error(`Recording not found: ${e}`);await this.saveSnapshot(t,`close`);let n=this.eventCleanup.get(e);n&&(n(),this.eventCleanup.delete(e));try{await this.client.send(`Network.disable`,{},t.sessionId)}catch{}this.recordings.delete(e);let r=`/recordings/${e}`;return d.debug(`Stopped recording`,{recordingId:e,snapshotCount:t.snapshotCount}),r}getRecording(e){return this.recordings.get(e)}getRecordingByTarget(e){for(let[t,n]of this.recordings)if(n.targetId===e)return t}async ensureDir(e){await this.fs.mkdir(e,{recursive:!0})}};function p(e,t){try{let n=Function(`entry`,`return (${t})(entry);`),r=[];for(let t of e)try{let e=n(t);if(e===!1)continue;typeof e==`object`&&e?r.push(e):r.push(t)}catch(e){d.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return d.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var m=`(function() {
1
+ import{t as e}from"./logger-DDBAeTLF.js";import"./navigation-watcher-BpA1OwJw.js";import"./wc-follower-oauth-BUNweTOx.js";import{n as t,t as n}from"./pending-request-table-k-D7ZZsL.js";var r=e(`cdp`);function i(e){return e===4001?`CDP connection superseded by another SLICC tab/window on this instance`:e===4002?`CDP connection reset by proxy (upstream Chrome connection was re-established)`:`CDP connection closed`}var a=class{ws=null;nextId=1;_superseded=!1;pending=new n;listeners=new Map;_state=`disconnected`;stateListeners=new Set;lastNotifiedState=`disconnected`;lastNotifiedReason;get state(){return this._state}onStateChange(e){return this.stateListeners.add(e),()=>{this.stateListeners.delete(e)}}get superseded(){return this._superseded}async connect(e){if(this._state!==`disconnected`)throw Error(`Cannot connect: state is ${this._state}`);if(!e?.url)throw Error(`CDPClient.connect() requires a WebSocket URL`);let{url:t,timeout:n=5e3,protocols:i}=e;return this._state=`connecting`,new Promise((e,a)=>{let o=setTimeout(()=>{this.cleanup(),a(Error(`CDP connection timed out after ${n}ms`))},n);try{this.ws=i===void 0?new WebSocket(t):new WebSocket(t,i)}catch(e){clearTimeout(o),this._state=`disconnected`,a(e);return}this.ws.onopen=()=>{clearTimeout(o),this._state=`connected`,this._superseded=!1,r.info(`Connected`,{url:t}),this.notifyState(`connected`),e()},this.ws.onerror=e=>{clearTimeout(o),this._state===`connecting`&&(r.error(`Connection failed`,{url:t}),this.cleanup(),a(Error(`CDP WebSocket connection failed`)))},this.ws.onmessage=e=>{this.handleMessage(e.data)},this.ws.onclose=e=>{this.handleClose(e?.code)}})}disconnect(){this.ws&&(this.ws.onclose=null,this.ws.close()),this._superseded=!1,this.cleanup(),r.info(`Disconnected`)}async send(e,t,n,i=3e4){if(this._state!==`connected`||!this.ws)throw Error(`CDP client is not connected`);let a=this.nextId++,o={id:a,method:e};t&&(o.params=t),n&&(o.sessionId=n),r.debug(`Send`,{method:e,id:a,sessionId:n});let s=this.pending.issue(a,i,`CDP command timed out after ${i}ms: ${e}`);return this.ws.send(JSON.stringify(o)),s}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){let n=this.listeners.get(e);n&&(n.delete(t),n.size===0&&this.listeners.delete(e))}once(e,n=3e4){return t(t=>(this.on(e,t),()=>this.off(e,t)),n,`Timed out waiting for event: ${e}`)}handleMessage(e){let t;try{t=JSON.parse(e)}catch{return}if(`id`in t&&typeof t.id==`number`){let e=t;r.debug(`Response`,{id:e.id,hasError:!!e.error}),e.error?(r.error(`Command error`,{id:e.id,code:e.error.code,message:e.error.message}),this.pending.reject(e.id,Error(`CDP error: ${e.error.message} (${e.error.code})`))):this.pending.resolve(e.id,e.result??{});return}if(`method`in t){let e=t;r.debug(`Event`,{method:e.method,sessionId:e.sessionId});let n=this.listeners.get(e.method);if(n){let t=e.sessionId?{...e.params,sessionId:e.sessionId}:e.params??{};for(let e of n)try{e(t)}catch{}}}}handleClose(e){e===4001?(this._superseded=!0,r.warn(`CDP slot superseded by another SLICC tab/window on this instance`,{code:e})):e===4002?r.warn(`CDP proxy reset its upstream Chrome connection — sessions dropped`,{code:e,pendingCommands:this.pending.size}):r.error(`Connection closed unexpectedly`,{pendingCommands:this.pending.size}),this.cleanup(i(e))}cleanup(e=`CDP client disconnected`){this.ws=null,this._state=`disconnected`,this.pending.rejectAll(e),this.notifyState(`disconnected`,e)}notifyState(e,t){if(e!==this.lastNotifiedState||t!==this.lastNotifiedReason){this.lastNotifiedState=e,this.lastNotifiedReason=t;for(let n of this.stateListeners)try{n(e,t)}catch{}}}},o=class extends Error{step;name=`CommandAbortedError`;constructor(e){super(`Browser command aborted while ${e}. A CDP round trip already in flight cannot be cancelled, so it may still have been applied to the page; nothing after it was started.`),this.step=e}};function s(e,t){if(e?.aborted)throw new o(t)}function c(e,t){return e?{signal:e,error:()=>new o(t)}:void 0}function l(e,t,n){return new Promise((r,i)=>{if(t?.aborted){i(new o(n));return}let a=()=>{clearTimeout(s),i(new o(n))},s=setTimeout(()=>{t?.removeEventListener(`abort`,a),r()},e);t?.addEventListener(`abort`,a,{once:!0})})}function u(e,t,n){return t?t.aborted?Promise.reject(new o(n)):new Promise((r,i)=>{let a=()=>i(new o(n));t.addEventListener(`abort`,a,{once:!0}),e.then(()=>{t.removeEventListener(`abort`,a),r()},e=>{t.removeEventListener(`abort`,a),i(e instanceof Error?e:Error(String(e)))})}):e}var d=e(`har-recorder`),f=class{recordings=new Map;client;fs;eventCleanup=new Map;constructor(e,t){this.client=e,this.fs=t}async startRecording(e,t,n,r){let i=`rec-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;s(r,`about to enable Network on tab ${e}`),await this.client.send(`Network.enable`,{},t),s(r,`about to enable Page on tab ${e}`),await this.client.send(`Page.enable`,{},t),s(r,`about to read the URL of tab ${e}`);let a=(await this.client.send(`Runtime.evaluate`,{expression:`location.href`,returnByValue:!0},t)).result?.value??`about:blank`,o={id:i,targetId:e,sessionId:t,filterCode:n,pendingRequests:new Map,entries:[],startTime:Date.now(),currentUrl:a,snapshotCount:0};return this.recordings.set(i,o),this.setupEventListeners(o),await this.ensureDir(`/recordings/${i}`),d.debug(`Started recording`,{recordingId:i,targetId:e,currentUrl:a}),i}setupEventListeners(e){let{sessionId:t,id:n}=e,r=n=>{let r=n;r.sessionId===t&&this.handleRequestWillBeSent(e,r)},i=n=>{let r=n;r.sessionId===t&&this.handleResponseReceived(e,r)},a=r=>{let i=r;i.sessionId===t&&this.handleLoadingFinished(e,i).catch(e=>{d.error(`Failed to process loadingFinished event`,{recordingId:n,requestId:i.requestId,error:e instanceof Error?e.message:String(e)})})},o=n=>{let r=n;r.sessionId===t&&this.handleLoadingFailed(e,r)},s=r=>{let i=r;if(i.sessionId!==t)return;let a=i.frame;if(!a?.parentId&&a?.url){let t=[...e.entries],r=e.currentUrl;e.currentUrl=a.url,e.entries=[],e.pendingRequests.clear(),this.saveSnapshotWithEntries(e,`navigation`,t,r).catch(e=>{d.error(`Failed to save navigation snapshot`,{recordingId:n,error:e instanceof Error?e.message:String(e)})})}};this.client.on(`Network.requestWillBeSent`,r),this.client.on(`Network.responseReceived`,i),this.client.on(`Network.loadingFinished`,a),this.client.on(`Network.loadingFailed`,o),this.client.on(`Page.frameNavigated`,s),this.eventCleanup.set(n,()=>{this.client.off(`Network.requestWillBeSent`,r),this.client.off(`Network.responseReceived`,i),this.client.off(`Network.loadingFinished`,a),this.client.off(`Network.loadingFailed`,o),this.client.off(`Page.frameNavigated`,s)})}handleRequestWillBeSent(e,t){let{requestId:n,request:r,timestamp:i}=t;!n||!r||i==null||e.pendingRequests.set(n,{requestId:n,startTime:i*1e3,request:{method:r.method,url:r.url,headers:r.headers,postData:r.postData}})}handleResponseReceived(e,t){let{requestId:n,response:r}=t;if(!n||!r)return;let i=e.pendingRequests.get(n);i&&(i.response={status:r.status,statusText:r.statusText,headers:r.headers,mimeType:r.mimeType},i.timing=r.timing)}async handleLoadingFinished(e,t){let{requestId:n,timestamp:r}=t;if(!n||r==null)return;let i=e.pendingRequests.get(n);if(!i)return;i.endTime=r*1e3;try{let t=await this.client.send(`Network.getResponseBody`,{requestId:n},e.sessionId);i.responseBody=t.body,i.responseBodyBase64=t.base64Encoded===!0}catch{}let a=this.buildHarEntry(i);a&&e.entries.push(a),e.pendingRequests.delete(n)}handleLoadingFailed(e,t){let{requestId:n}=t;n&&e.pendingRequests.delete(n)}buildHarEntry(e){if(!e.response)return null;let{request:t,response:n,timing:r,startTime:i,endTime:a,responseBody:o,responseBodyBase64:s}=e,c=a?a-i:0,l=[];try{let e=new URL(t.url);l=Array.from(e.searchParams.entries()).map(([e,t])=>({name:e,value:t}))}catch{}let u=r?(()=>{let e=(e,t)=>{if(e==null||t==null||e<0||t<0)return-1;let n=t-e;return n>=0?n:-1},t=r.dnsStart>=0?r.dnsStart:r.connectStart>=0?r.connectStart:0;return{blocked:t>0?t:-1,dns:e(r.dnsStart,r.dnsEnd),connect:e(r.connectStart,r.connectEnd),ssl:e(r.sslStart,r.sslEnd),send:e(r.sendStart,r.sendEnd),wait:e(r.sendEnd,r.receiveHeadersStart),receive:e(r.receiveHeadersStart,r.receiveHeadersEnd)}})():{blocked:-1,dns:-1,connect:-1,ssl:-1,send:0,wait:c,receive:0},d={size:o?.length??0,mimeType:n.mimeType??`application/octet-stream`};o&&(d.text=o,s&&(d.encoding=`base64`));let f;return t.postData&&(f={mimeType:t.headers[`content-type`]??t.headers[`Content-Type`]??`text/plain`,text:t.postData}),{startedDateTime:new Date(i).toISOString(),time:c,request:{method:t.method,url:t.url,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(t.headers).map(([e,t])=>({name:e,value:t})),queryString:l,postData:f,headersSize:-1,bodySize:t.postData?.length??0},response:{status:n.status,statusText:n.statusText,httpVersion:`HTTP/1.1`,cookies:[],headers:Object.entries(n.headers).map(([e,t])=>({name:e,value:t})),content:d,redirectURL:n.headers.location??n.headers.Location??``,headersSize:-1,bodySize:d.size},cache:{},timings:u}}async saveSnapshot(e,t){return this.saveSnapshotWithEntries(e,t,e.entries,e.currentUrl)}async applyFilter(e,t){return p(e,t)}async saveSnapshotWithEntries(e,t,n,r){if(n.length===0)return d.debug(`No entries to save`,{recordingId:e.id,trigger:t}),null;let i=e.filterCode?await this.applyFilter(n,e.filterCode):n;if(i.length===0)return d.debug(`All entries filtered out`,{recordingId:e.id,trigger:t}),null;e.snapshotCount++;let a=new Date().toISOString().replace(/[:.]/g,`-`),o=this.urlToSlug(r),s=`${e.snapshotCount.toString().padStart(3,`0`)}-${a}-${t}-${o}.har`,c=`/recordings/${e.id}/${s}`,l={log:{version:`1.2`,creator:{name:`SLICC HAR Recorder`,version:`1.0.0`},entries:i}};return await this.fs.writeFile(c,JSON.stringify(l,null,2)),d.debug(`Saved HAR snapshot`,{recordingId:e.id,path:c,entryCount:i.length}),c}urlToSlug(e){try{let t=new URL(e);return`${t.hostname}${t.pathname}`.replace(/[^a-zA-Z0-9]/g,`-`).replace(/-+/g,`-`).replace(/^-|-$/g,``).slice(0,50)||`page`}catch{return`page`}}async stopRecording(e){let t=this.recordings.get(e);if(!t)throw Error(`Recording not found: ${e}`);await this.saveSnapshot(t,`close`);let n=this.eventCleanup.get(e);n&&(n(),this.eventCleanup.delete(e));try{await this.client.send(`Network.disable`,{},t.sessionId)}catch{}this.recordings.delete(e);let r=`/recordings/${e}`;return d.debug(`Stopped recording`,{recordingId:e,snapshotCount:t.snapshotCount}),r}getRecording(e){return this.recordings.get(e)}getRecordingByTarget(e){for(let[t,n]of this.recordings)if(n.targetId===e)return t}async ensureDir(e){await this.fs.mkdir(e,{recursive:!0})}};function p(e,t){try{let n=Function(`entry`,`return (${t})(entry);`),r=[];for(let t of e)try{let e=n(t);if(e===!1)continue;typeof e==`object`&&e?r.push(e):r.push(t)}catch(e){d.error(`Filter function error on entry, keeping it`,{error:e instanceof Error?e.message:String(e)}),r.push(t)}return r}catch(t){return d.error(`Failed to compile filter, returning unfiltered`,{error:t instanceof Error?t.message:String(t)}),e}}var m=`(function() {
2
2
  'use strict';
3
3
 
4
4
  // ===== DOM Utilities =====
@@ -1 +1 @@
1
- import{_ as e}from"./account-store-CEOiQheZ.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{d as n}from"./claude-model-version-CSATLzrT.js";import{r,s as i}from"./legacy-api-aliases-bAJ0Klzq.js";var a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`,u=[],d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}var v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var S={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
1
+ import{_ as e}from"./account-store-CDR1C1oH.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{d as n}from"./claude-model-version-CSATLzrT.js";import{r,s as i}from"./legacy-api-aliases-bAJ0Klzq.js";var a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`,u=[],d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}var v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}var S={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
@@ -1 +1 @@
1
- import{a as e}from"./account-store-1giUExSS.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{a as n}from"./compat-uEPf6-XW.js";import{r,s as i}from"./legacy-api-aliases-jKEvBgOL.js";const a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`;let u=[];const d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}const v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const S={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
1
+ import{a as e}from"./account-store-OqSCLUiN.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{a as n}from"./compat-uEPf6-XW.js";import{r,s as i}from"./legacy-api-aliases-jKEvBgOL.js";const a=`cerebras`,o=`https://api.cerebras.ai/v1`,s=`openai-completions`,c=`${a}-openai`,l=`slicc-cerebras-models`;let u=[];const d=[{id:`gpt-oss-120b`,name:`GPT OSS 120B`,api:`openai`,reasoning:!0,input:[`text`],context_window:131072,max_tokens:40960},{id:`gemma-4-31b`,name:`Gemma 4 31B`,api:`openai`,reasoning:!1,input:[`text`,`image`],context_window:131072,max_tokens:40960},{id:`zai-glm-4.7`,name:`Z.AI GLM-4.7`,api:`openai`,reasoning:!1,input:[`text`],context_window:131072,max_tokens:40960}];function f(e){try{localStorage.setItem(l,JSON.stringify(e))}catch{}}function p(){try{let e=localStorage.getItem(l);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)&&t.length>0?t:[]}catch{return[]}}function m(e){let t=e.id??``,n=d.find(e=>e.id===t);return{id:t,name:e.name??n?.name??t,api:`openai`,reasoning:e.capabilities?.reasoning??n?.reasoning??!1,input:e.capabilities?.vision?[`text`,`image`]:n?.input??[`text`],context_window:e.limits?.max_context_length??n?.context_window??8192,max_tokens:e.limits?.max_completion_tokens??n?.max_tokens??4096}}async function h(e){let t=await fetch(`${o}/models`,{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw Error(`GET /v1/models → ${t.status} ${t.statusText}`);let n=((await t.json()).data??[]).map(m).filter(e=>e.id.length>0);n.length>0&&(u=n,f(n))}function g(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:c,provider:a,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}function _(e){console.error(`[cerebras] Stream error:`,e instanceof Error?e.message:String(e))}const v=(e,n,r={})=>{let i=t();return y(i,e,n,r).catch(_),i};async function y(e,t,n,i){try{let a={...t,baseUrl:o,api:s},c=r(a,n,i);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const b=(e,n,r)=>{let i=t();return x(i,e,n,r).catch(_),i};async function x(e,t,n,r){try{let a={...t,baseUrl:o,api:s},c=i(a,n,r);for await(let t of c)e.push(t);e.end()}catch(n){_(n),e.push(g(t,n)),e.end()}}const S={id:a,name:`Cerebras`,description:`Ultra-fast inference on Cerebras hardware. Get an API key at cloud.cerebras.ai.`,requiresApiKey:!0,requiresBaseUrl:!1,getModelIds:()=>{if(u.length>0)return u;let e=p();return e.length>0?e:d},refreshModels:async t=>{let n=t??e(a)??``;if(n)try{await h(n)}catch(e){console.warn(`[cerebras] Failed to refresh model list:`,e instanceof Error?e.message:String(e))}}};function C(){n({api:c,stream:v,streamSimple:b})}export{S as config,C as register};
@@ -1 +1 @@
1
- import{t as e}from"./logger-DDBAeTLF.js";import{K as t}from"./wc-shortcuts-Cofh5Gbv.js";import{n}from"./runtime-env-Dlaokqg1.js";import{t as r}from"./permissions-surface-registry-CilCRwhh.js";import{t as i}from"./speech-assets-bridge-CFYafE89.js";import{o as a}from"./transformers-env-Dtjt9IFM.js";import{i as o,t as s}from"./whisper-session-CargUQnZ.js";var c=e(`speech:composer`),l=5e3,u=(e,t,n)=>new Promise((r,i)=>{let a=setTimeout(()=>i(Error(`${n} timed out after ${t}ms`)),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})}),d=class{#e;#t;#n;#r;#i;#a=null;#o=!1;#s={engine:`builtin`,state:`idle`};#c=a();#l=new Set;#u=null;constructor(e={}){this.#e=e.builtin??t(),this.#t=e.loadWhisper??o,this.#n=e.startSession??s,this.#r=e.getPermissionSurface??f,this.#i=e.ensureAssets??v}permission(){return this.#e.permission()}async requestPermission(){let e=this.#r();if(e)try{let t=await e.request(`microphone`);return t?(this.#p(t.stream),!0):!1}catch(e){return c.warn(`permission surface microphone request failed`,e),!1}return this.#e.requestPermission()}microphones(){return this.#e.microphones()}status(){return this.#s}onStatus(e){return this.#l.add(e),e(this.#s),()=>this.#l.delete(e)}warmup(){this.#o||(this.#o=!0,this.#c=a(),this.#_({engine:`builtin`,state:`downloading`}),this.#d().then(e=>{this.#a=e,this.#_({engine:`enhanced`,state:`ready`})},e=>{this.#o=!1,this.#_({engine:`builtin`,state:`unavailable`,message:m(e)}),c.warn(`enhanced speech engine unavailable`,e)}))}async#d(){let e=null;try{await this.#i(e=>this.#h(e))}catch(t){e=t,c.warn(`speech asset staging failed; trying already-present assets`,t)}try{return await this.#t(e=>this.#g(e))}catch(t){throw e??t}}async start(e){let t=this.#a;if(t){let n=null;try{return n=await this.#f(e.deviceId),await this.#n(t,{deviceId:e.deviceId,lang:e.lang,onPartial:e.onPartial,onError:e.onError,stream:n??void 0})}catch(e){if(n)for(let e of n.getTracks())e.stop();c.warn(`whisper session failed to start; falling back to builtin`,e)}}return this.#e.start(e)}async#f(e){let t=e&&e!=="default"?e:void 0,n=this.#m();if(n){if(!t&&p(n))return n;for(let e of n.getTracks())e.stop()}let r=this.#r();if(!r)return null;let i={audio:!t||{deviceId:{exact:t}}},a=await u(r.request(`microphone`,{constraints:i}),l,`microphone capture`);if(!a)throw Error(`microphone permission denied`);return a.stream}#p(e){if(this.#u&&this.#u!==e)for(let e of this.#u.getTracks())e.stop();this.#u=e}#m(){let e=this.#u;return this.#u=null,e}get enhancedReady(){return this.#a!==null}#h(e){if(this.#s.state!==`downloading`)return;(e.bytesTotal!=null||e.bytesLoaded!=null)&&this.#c.update(e.asset,e.bytesLoaded??0,e.bytesTotal??0);let t=this.#c.snapshot();t.total<=0||this.#_({engine:`builtin`,state:`downloading`,download:{loaded:t.loaded,total:t.total,etaSeconds:t.etaSeconds}})}#g(e){this.#s.state===`downloading`&&this.#_({engine:`builtin`,state:`downloading`,download:{loaded:e.loaded,total:e.total,etaSeconds:e.etaSeconds}})}#_(e){this.#s=e;for(let t of this.#l)t(e)}};function f(){let e=r();return e?{async request(t,n){let r=await e.request(t,n);return r?.kind===`microphone`?{kind:`microphone`,stream:r.stream}:null}}:null}function p(e){let t=e.getTracks();return t.length>0&&t.some(e=>e.readyState!==`ended`)}function m(e){return`Enhanced speech unavailable: ${e instanceof Error?e.message:String(e)}`}var h=n,g;function _(e){g=e}function v(e){return h()?Promise.resolve():i({instanceId:g,onProgress:e})}var y=null;function b(){return y??=new d,y}export{b as getComposerSpeech,_ as setComposerSpeechInstanceId};
1
+ import{t as e}from"./logger-DDBAeTLF.js";import{K as t}from"./wc-shortcuts-CLBUOdsH.js";import{n}from"./runtime-env-Dlaokqg1.js";import{t as r}from"./permissions-surface-registry-CilCRwhh.js";import{t as i}from"./speech-assets-bridge-CFYafE89.js";import{o as a}from"./transformers-env--mgWdw0R.js";import{i as o,t as s}from"./whisper-session-C_0wh0Zg.js";var c=e(`speech:composer`),l=5e3,u=(e,t,n)=>new Promise((r,i)=>{let a=setTimeout(()=>i(Error(`${n} timed out after ${t}ms`)),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})}),d=class{#e;#t;#n;#r;#i;#a=null;#o=!1;#s={engine:`builtin`,state:`idle`};#c=a();#l=new Set;#u=null;constructor(e={}){this.#e=e.builtin??t(),this.#t=e.loadWhisper??o,this.#n=e.startSession??s,this.#r=e.getPermissionSurface??f,this.#i=e.ensureAssets??v}permission(){return this.#e.permission()}async requestPermission(){let e=this.#r();if(e)try{let t=await e.request(`microphone`);return t?(this.#p(t.stream),!0):!1}catch(e){return c.warn(`permission surface microphone request failed`,e),!1}return this.#e.requestPermission()}microphones(){return this.#e.microphones()}status(){return this.#s}onStatus(e){return this.#l.add(e),e(this.#s),()=>this.#l.delete(e)}warmup(){this.#o||(this.#o=!0,this.#c=a(),this.#_({engine:`builtin`,state:`downloading`}),this.#d().then(e=>{this.#a=e,this.#_({engine:`enhanced`,state:`ready`})},e=>{this.#o=!1,this.#_({engine:`builtin`,state:`unavailable`,message:m(e)}),c.warn(`enhanced speech engine unavailable`,e)}))}async#d(){let e=null;try{await this.#i(e=>this.#h(e))}catch(t){e=t,c.warn(`speech asset staging failed; trying already-present assets`,t)}try{return await this.#t(e=>this.#g(e))}catch(t){throw e??t}}async start(e){let t=this.#a;if(t){let n=null;try{return n=await this.#f(e.deviceId),await this.#n(t,{deviceId:e.deviceId,lang:e.lang,onPartial:e.onPartial,onError:e.onError,stream:n??void 0})}catch(e){if(n)for(let e of n.getTracks())e.stop();c.warn(`whisper session failed to start; falling back to builtin`,e)}}return this.#e.start(e)}async#f(e){let t=e&&e!=="default"?e:void 0,n=this.#m();if(n){if(!t&&p(n))return n;for(let e of n.getTracks())e.stop()}let r=this.#r();if(!r)return null;let i={audio:!t||{deviceId:{exact:t}}},a=await u(r.request(`microphone`,{constraints:i}),l,`microphone capture`);if(!a)throw Error(`microphone permission denied`);return a.stream}#p(e){if(this.#u&&this.#u!==e)for(let e of this.#u.getTracks())e.stop();this.#u=e}#m(){let e=this.#u;return this.#u=null,e}get enhancedReady(){return this.#a!==null}#h(e){if(this.#s.state!==`downloading`)return;(e.bytesTotal!=null||e.bytesLoaded!=null)&&this.#c.update(e.asset,e.bytesLoaded??0,e.bytesTotal??0);let t=this.#c.snapshot();t.total<=0||this.#_({engine:`builtin`,state:`downloading`,download:{loaded:t.loaded,total:t.total,etaSeconds:t.etaSeconds}})}#g(e){this.#s.state===`downloading`&&this.#_({engine:`builtin`,state:`downloading`,download:{loaded:e.loaded,total:e.total,etaSeconds:e.etaSeconds}})}#_(e){this.#s=e;for(let t of this.#l)t(e)}};function f(){let e=r();return e?{async request(t,n){let r=await e.request(t,n);return r?.kind===`microphone`?{kind:`microphone`,stream:r.stream}:null}}:null}function p(e){let t=e.getTracks();return t.length>0&&t.some(e=>e.readyState!==`ended`)}function m(e){return`Enhanced speech unavailable: ${e instanceof Error?e.message:String(e)}`}var h=n,g;function _(e){g=e}function v(e){return h()?Promise.resolve():i({instanceId:g,onProgress:e})}var y=null;function b(){return y??=new d,y}export{b as getComposerSpeech,_ as setComposerSpeechInstanceId};
@@ -1,4 +1,4 @@
1
- import{T as e,f as t,p as n,z as r}from"./account-store-CEOiQheZ.js";import{n as i}from"./main-CmEbg5ii.js";var a=`slicc_cloud_model_catalog`,o=`adobe`;function s(t){if(t===o)return!1;let n=e(t);return!(n.hidden||n.onOAuthLoginIntercepted)}function c(){try{let e=n().map(e=>({providerId:e.providerId,providerName:e.providerName,models:e.models.map(e=>({id:e.id,name:e.name}))}));localStorage.setItem(a,JSON.stringify(e))}catch{}}async function l(n){for(;n.firstChild;)n.removeChild(n.firstChild);n.className=`connect-surface`;let a=document.createElement(`h1`);a.className=`connect-surface__title`,a.textContent=`Connect providers`,n.appendChild(a);let l=document.createElement(`p`);l.className=`connect-surface__desc`,l.textContent=`Log in or add API keys for the providers your cone should use, then click Done to return to the dashboard.`,n.appendChild(l);let u=document.createElement(`div`);u.className=`connect-surface__accounts`,n.appendChild(u);function d(){for(;u.firstChild;)u.removeChild(u.firstChild);let n=t().filter(e=>e.providerId!==o);if(n.length===0){let e=document.createElement(`div`);e.className=`connect-surface__empty`,e.textContent=`No providers connected yet.`,u.appendChild(e)}else{let t=document.createElement(`div`);t.className=`connect-surface__accounts-list`;for(let i of n){let n=e(i.providerId),a=document.createElement(`div`);a.className=`connect-surface__account-row`;let o=document.createElement(`div`);o.className=`connect-surface__account-info`;let s=document.createElement(`div`);s.className=`connect-surface__account-name`,s.textContent=n.name,o.appendChild(s);let l=document.createElement(`div`);l.className=`connect-surface__account-detail`,l.textContent=i.userName?i.userName:i.accessToken?`Logged in`:i.apiKey?`API key set`:`No credentials`,o.appendChild(l),a.appendChild(o);let u=document.createElement(`button`);u.className=`connect-surface__remove-btn`,u.textContent=`Remove`,u.onclick=async()=>{await r(i.providerId),c(),d()},a.appendChild(u),t.appendChild(a)}u.appendChild(t)}let a=document.createElement(`button`);a.className=`connect-surface__add-btn`,a.textContent=n.length===0?`Add provider`:`Manage providers`,a.onclick=async()=>{await i({startInAddAccount:!0,providerFilter:s})&&(c(),d())},u.appendChild(a)}d(),c();let f=document.createElement(`div`);f.className=`connect-surface__footer`;let p=document.createElement(`button`);if(p.className=`connect-surface__done-btn`,p.textContent=`Done — return to dashboard`,p.onclick=()=>{c(),window.close()},f.appendChild(p),n.appendChild(f),!document.getElementById(`connect-surface-style`)){let e=document.createElement(`style`);e.id=`connect-surface-style`,e.textContent=`
1
+ import{T as e,f as t,p as n,z as r}from"./account-store-CDR1C1oH.js";import{n as i}from"./main-Kp4I5rQC.js";var a=`slicc_cloud_model_catalog`,o=`adobe`;function s(t){if(t===o)return!1;let n=e(t);return!(n.hidden||n.onOAuthLoginIntercepted)}function c(){try{let e=n().map(e=>({providerId:e.providerId,providerName:e.providerName,models:e.models.map(e=>({id:e.id,name:e.name}))}));localStorage.setItem(a,JSON.stringify(e))}catch{}}async function l(n){for(;n.firstChild;)n.removeChild(n.firstChild);n.className=`connect-surface`;let a=document.createElement(`h1`);a.className=`connect-surface__title`,a.textContent=`Connect providers`,n.appendChild(a);let l=document.createElement(`p`);l.className=`connect-surface__desc`,l.textContent=`Log in or add API keys for the providers your cone should use, then click Done to return to the dashboard.`,n.appendChild(l);let u=document.createElement(`div`);u.className=`connect-surface__accounts`,n.appendChild(u);function d(){for(;u.firstChild;)u.removeChild(u.firstChild);let n=t().filter(e=>e.providerId!==o);if(n.length===0){let e=document.createElement(`div`);e.className=`connect-surface__empty`,e.textContent=`No providers connected yet.`,u.appendChild(e)}else{let t=document.createElement(`div`);t.className=`connect-surface__accounts-list`;for(let i of n){let n=e(i.providerId),a=document.createElement(`div`);a.className=`connect-surface__account-row`;let o=document.createElement(`div`);o.className=`connect-surface__account-info`;let s=document.createElement(`div`);s.className=`connect-surface__account-name`,s.textContent=n.name,o.appendChild(s);let l=document.createElement(`div`);l.className=`connect-surface__account-detail`,l.textContent=i.userName?i.userName:i.accessToken?`Logged in`:i.apiKey?`API key set`:`No credentials`,o.appendChild(l),a.appendChild(o);let u=document.createElement(`button`);u.className=`connect-surface__remove-btn`,u.textContent=`Remove`,u.onclick=async()=>{await r(i.providerId),c(),d()},a.appendChild(u),t.appendChild(a)}u.appendChild(t)}let a=document.createElement(`button`);a.className=`connect-surface__add-btn`,a.textContent=n.length===0?`Add provider`:`Manage providers`,a.onclick=async()=>{await i({startInAddAccount:!0,providerFilter:s})&&(c(),d())},u.appendChild(a)}d(),c();let f=document.createElement(`div`);f.className=`connect-surface__footer`;let p=document.createElement(`button`);if(p.className=`connect-surface__done-btn`,p.textContent=`Done — return to dashboard`,p.onclick=()=>{c(),window.close()},f.appendChild(p),n.appendChild(f),!document.getElementById(`connect-surface-style`)){let e=document.createElement(`style`);e.id=`connect-surface-style`,e.textContent=`
2
2
  .connect-surface {
3
3
  padding: 2rem;
4
4
  max-width: 560px;
@@ -35,4 +35,4 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
35
35
  `}}return e?(p+=`
36
36
  `+qf(l(e),c),s&&s()):d&&o&&o(),p}function Tp({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(Q(i))i.spaceBefore&&d.push(``),Ep(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(X(i)){let e=Q(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),Ep(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=Q(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=dp(i,c,()=>a=null);l||=d.length>u||o.includes(`
37
37
  `),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=Jf(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
38
- `;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function Ep({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=qf(t(r),e);n.push(i.trimStart())}}function Dp(e,t){let n=Z(t)?t.value:t;for(let r of e)if(X(r)&&(r.key===t||r.key===n||Z(r.key)&&r.key.value===n))return r}var Op=class extends Gf{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(hf,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(xp(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=X(e)?e:!e||typeof e!=`object`||!(`key`in e)?new Sp(e,e?.value):new Sp(e.key,e.value);let r=Dp(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);Z(r.value)&&Bf(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=Dp(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=Dp(this.items,e)?.value;return(!t&&Z(n)?n.value:n)??void 0}has(e){return!!Dp(this.items,e)}set(e,t){this.add(new Sp(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)yp(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!X(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Cp(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}};const kp={collection:`map`,default:!0,nodeClass:Op,tag:`tag:yaml.org,2002:map`,resolve(e,t){return Sf(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>Op.from(e,t,n)};var Ap=class extends Gf{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(vf,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=jp(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=jp(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&Z(r)?r.value:r}has(e){let t=jp(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=jp(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];Z(r)&&Bf(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(If(e,String(r++),t));return n}toString(e,t,n){return e?Cp(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(Hf(a,void 0,n))}}return i}};function jp(e){let t=Z(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}const Mp={collection:`seq`,default:!0,nodeClass:Ap,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return Cf(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>Ap.from(e,t,n)};function Np(e){return typeof e==`bigint`||Number.isInteger(e)}const Pp=({value:e})=>JSON.stringify(e),Fp=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:Pp},{identify:e=>e==null,createNode:()=>new $(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:Pp},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:Pp},{identify:Np,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>Np(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Pp}];[kp,Mp].concat(Fp,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}});function Ip(e,t,n){let{replacer:r}=n,i=new Ap(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(xp(o,s,n))}return i}var Lp=class e extends Ap{constructor(){super(),this.add=Op.prototype.add.bind(this),this.delete=Op.prototype.delete.bind(this),this.get=Op.prototype.get.bind(this),this.has=Op.prototype.has.bind(this),this.set=Op.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(X(e)?(r=If(e.key,``,t),i=If(e.value,r,t)):r=If(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=Ip(e,t,n),i=new this;return i.items=r.items,i}};Lp.tag=`tag:yaml.org,2002:omap`;var Rp=class e extends Op{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=X(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new Sp(e.key,null):new Sp(e,null),Dp(this.items,t.key)||this.items.push(t)}get(e,t){let n=Dp(this.items,e);return!t&&X(n)?Z(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Dp(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Sp(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(xp(e,null,n));return i}};Rp.tag=`tag:yaml.org,2002:set`;const zp=Symbol(`break visit`),Bp=Symbol(`skip children`),Vp=Symbol(`remove item`);function Hp(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),Up(Object.freeze([]),e,t)}Hp.BREAK=zp,Hp.SKIP=Bp,Hp.REMOVE=Vp,Hp.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},Hp.parentCollection=(e,t)=>{let n=Hp.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function Up(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=Up(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===zp)return zp;else r===Vp&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}t(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}let r=/^\s+$/,i=/(?:[^\\]|^)\\$/,a=/^\\!/,o=/^\\#/,s=/\r?\n/g,c=/^\.{0,2}\/|^\.{1,2}$/,l=/\/$/,u=`node-ignore`;typeof Symbol<`u`&&(u=Symbol.for(`node-ignore`));let d=u,f=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),p=/([0-z])-([0-z])/g,m=()=>!1,h=e=>e.replace(p,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:``),g=e=>{let{length:t}=e;return e.slice(0,t-t%2)},ee=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===`\\`?`\\[${n}${g(r)}${i}`:i===`]`&&r.length%2==0?`[${h(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],_=/(^|\\\/)?\\\*$/,v=`regex`,te=`checkRegex`,ne={[v](e,t){return`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`},[te](e,t){return`${t?`${t}[^/]*`:`[^/]*`}(?=$|\\/$)`}},re=e=>ee.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),ie=e=>typeof e==`string`,ae=e=>e&&ie(e)&&!r.test(e)&&!i.test(e)&&e.indexOf(`#`)!==0,oe=e=>e.split(s).filter(Boolean);var se=class{constructor(e,t,n,r,i,a){this.pattern=e,this.mark=t,this.negative=i,f(this,`body`,n),f(this,`ignoreCase`,r),f(this,`regexPrefix`,a)}get regex(){let e=`_regex`;return this[e]?this[e]:this._make(v,e)}get checkRegex(){let e=`_checkRegex`;return this[e]?this[e]:this._make(te,e)}_make(e,t){let n=this.regexPrefix.replace(_,ne[e]),r=this.ignoreCase?new RegExp(n,`i`):new RegExp(n);return f(this,t,r)}};let ce=({pattern:e,mark:t},n)=>{let r=!1,i=e;i.indexOf(`!`)===0&&(r=!0,i=i.substr(1)),i=i.replace(a,`!`).replace(o,`#`);let s=re(i);return new se(e,t,i,n,r,s)};var le=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[d]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(ie(e)&&(e={pattern:e}),ae(e.pattern)){let t=ce(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(ie(e)?oe(e):e).forEach(this._add,this),this._added}test(e,t,n){let r=!1,i=!1,a;this._rules.forEach(o=>{let{negative:s}=o;i===s&&r!==i||s&&!r&&!i&&!t||o[n].test(e)&&(r=!s,i=s,a=s?void 0:o)});let o={ignored:r,unignored:i};return a&&(o.rule=a),o}};let ue=(e,t)=>{throw new t(e)},y=(e,t,n)=>ie(e)?e?!y.isNotRelative(e)||n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),de=e=>c.test(e);y.isNotRelative=de,y.convert=e=>e;var fe=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){f(this,d,!0),this._rules=new le(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,r){let i=e&&y.convert(e);return y(i,e,this._strictPathCheck?ue:m),this._t(i,t,n,r)}checkIgnore(e){if(!l.test(e))return this.test(e);let t=e.split(`/`).filter(Boolean);if(t.pop(),t.length){let e=this._t(t.join(`/`)+`/`,this._testCache,!0,t);if(e.ignored)return e}return this._rules.test(e,!1,te)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(`/`).filter(Boolean),r.pop(),!r.length)return t[e]=this._rules.test(e,n,v);let i=this._t(r.join(`/`)+`/`,t,n,r);return t[e]=i.ignored?i:this._rules.test(e,n,v)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let pe=e=>new fe(e),me=e=>y(e&&y.convert(e),e,m),he=()=>{y.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;y.isNotRelative=t=>e.test(t)||de(t)};typeof process<`u`&&process.platform===`win32`&&he(),t.exports=pe,pe.default=pe,t.exports.isPathValid=me,f(t.exports,Symbol.for(`setupWindows`),he)}))();const Wp={"pi.session.id":{type:`string`,required:!0,cardinality:`high`,description:`Session id`},"pi.lane.name":{type:`string`,required:!0,cardinality:`high`,description:`Lane name`},"pi.operation.id":{type:`string`,required:!0,cardinality:`high`,description:`Durable operation id`},"pi.operation.recovery":{type:`boolean`,required:!0,description:`Whether this invocation resumes durable work`}},Gp={"pi.error.code":{type:`string`,cardinality:`low`,description:`Stable operation error code`},"pi.error.type":{type:`string`,cardinality:`low`,description:`Low-cardinality operation error class`}};({...Wp}),{...Gp},{...Wp},{...Gp},{...Wp},{...Gp},globalThis.Buffer,j({command:R({description:`Bash command to execute`}),timeout:Lt(Zn({description:`Timeout in seconds (optional, no default timeout)`}))});const Kp=j({oldText:R({description:`Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.`}),newText:R({description:`Replacement text for this targeted edit.`})},{});j({path:R({description:`Path to the file to edit (relative or absolute)`}),edits:xt(Kp,{description:`One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.`})},{}),j({path:R({description:`Path to the file to read (relative or absolute)`}),offset:Lt(Zn({description:`Line number to start reading from (1-indexed)`})),limit:Lt(Zn({description:`Maximum number of lines to read`}))}),j({path:R({description:`Path to the file to write (relative or absolute)`}),content:R({description:`Content to write to the file`})});function qp(){return a()?`extension-direct`:s()?`extension-delegate`:globalThis.__slicc_connect_mode?`connect`:`node-rest`}function Jp(){return qp()===`node-rest`}const Yp=n(`secret-scrub`),Xp=`[tool output withheld: secret scrub unavailable]`,Zp=async e=>e;function Qp(){let e=qp();return e===`extension-direct`?async e=>{if(!e)return e;try{let t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.scrub-tool-result`,text:e},e=>t(e??{}))});return t.error?(Yp.debug(`SW scrub-tool-result returned error`),Xp):typeof t.text==`string`?t.text:Xp}catch{return Yp.debug(`SW scrub-tool-result failed`),Xp}}:e===`extension-delegate`?async e=>{if(!e)return e;try{let t=await l(`secrets.scrub-tool-result`,{text:e});return t?.error?(Yp.debug(`Bridge scrub-tool-result returned error`),Xp):typeof t?.text==`string`?t.text:Xp}catch{return Yp.debug(`Bridge scrub-tool-result failed`),Xp}}:e===`connect`?Zp:async e=>{if(!e)return e;try{let t=await fetch(o(`/api/secrets/scrub`),{method:`POST`,headers:c({"content-type":`application/json`}),body:JSON.stringify({text:e})});if(!t.ok)return Yp.debug(`Server scrub-tool-result returned non-ok`,{status:t.status}),e;let n=await t.json();return typeof n.text==`string`?n.text:e}catch(t){return Yp.debug(`Server scrub-tool-result failed`,{error:t instanceof Error?t.message:String(t)}),e}}}const $p=[];function em(e){return $p.push(e),e}function tm(e){let t=$p.lastIndexOf(e);t!==-1&&$p.splice(t,1)}function nm(){return $p.length>0?$p[$p.length-1]:null}const rm=n(`tool-ui`),im=`__mounted`,am=new class{pending=new Map;idCounter=0;mounted=new Set;mountWaiters=new Map;generateId(){return`tool-ui-${++this.idCounter}-${Date.now().toString(36)}`}register(e,t,n,r){this.mounted.delete(e),this.pending.set(e,{request:t,resolve:n,reject:r}),rm.info(`Tool UI registered`,{id:e})}async handleAction(e,t){let n=this.pending.get(e);if(!n){rm.warn(`Action for unknown tool UI`,{id:e,action:t.action});return}rm.info(`Tool UI action`,{id:e,action:t.action});try{let e;e=n.request.onAction?await n.request.onAction(t.action,t.data):t,n.resolve(e)}catch(e){n.reject(e instanceof Error?e:Error(String(e)))}finally{this.pending.delete(e),this.clearMountWaiter(e,`tool ui completed`)}}cancel(e,t=`cancelled`){let n=this.pending.get(e);n&&(n.reject(Error(t)),this.pending.delete(e),rm.info(`Tool UI cancelled`,{id:e,reason:t})),this.clearMountWaiter(e,t),this.mounted.delete(e)}cancelAll(e=`cancelled`){let t=this.pending.size;for(let[t,n]of this.pending)n.reject(Error(e));this.pending.clear();for(let t of[...this.mountWaiters.keys()])this.clearMountWaiter(t,e);this.mounted.clear(),t>0&&rm.info(`All tool UIs cancelled`,{reason:e,count:t})}isPending(e){return this.pending.has(e)}getPendingIds(){return[...this.pending.keys()]}markMounted(e){this.mounted.add(e);let t=this.mountWaiters.get(e);t&&(clearTimeout(t.timeoutHandle),this.mountWaiters.delete(e),t.resolve())}waitForMount(e,t){return this.mounted.has(e)?Promise.resolve():new Promise((n,r)=>{let i=setTimeout(()=>{this.mountWaiters.delete(e),r(Error(`tool UI ${e} was not mounted by any panel within ${t}ms — check the chat panel`))},t);this.mountWaiters.set(e,{resolve:n,reject:r,timeoutHandle:i})})}clearMountWaiter(e,t){let n=this.mountWaiters.get(e);n&&(clearTimeout(n.timeoutHandle),this.mountWaiters.delete(e),n.reject(Error(t)))}};async function om(e,t){let n=e.id??am.generateId(),r,i,a=new Promise((e,t)=>{r=e,i=t});return am.register(n,e,r,i),t?t({content:[{type:`tool_ui`,requestId:n,html:e.html}]}):rm.warn(`showToolUI called without onUpdate callback — UI may not render`),a.finally(()=>{t&&t({content:[{type:`tool_ui_done`,requestId:n}]})})}async function sm(e){let t=nm();return t?om(e,t.onUpdate):(rm.warn(`showToolUIFromContext called without execution context`),null)}const cm=n(`image-processor`),lm=3932160;function um(e){let t=e.replace(/[\t\n\f\r ]/g,``),n=t.length%4;return n===2?`${t}==`:n===3?`${t}=`:t}function dm(e,t){let n=i(um(e.slice(0,t)));return new DataView(n.buffer,n.byteOffset,n.byteLength)}function fm(e,t){return e>0&&t>0?{width:e,height:t}:null}function pm(e){if(e.length<32)return null;let t=dm(e,32);return fm(t.getUint32(16,!1),t.getUint32(20,!1))}function mm(e){if(e.length<16)return null;let t=dm(e,16);return fm(t.getUint16(6,!0),t.getUint16(8,!0))}function hm(e){let t=dm(e,Math.min(87384,e.length));for(let e=0;e<t.byteLength-8;e++){if(t.getUint8(e)!==255)continue;let n=t.getUint8(e+1);if(n===192||n===194)return fm(t.getUint16(e+7,!1),t.getUint16(e+5,!1))}return null}function gm(e,t){try{let n=um(e);if(t===`image/png`)return pm(n);if(t===`image/gif`)return mm(n);if(t===`image/jpeg`)return hm(n)}catch{}return null}async function _m(e){if(!u(e.mimeType))return cm.warn(`Unsupported image format`,{mimeType:e.mimeType}),{type:`text`,text:`[Image removed: unsupported format "${e.mimeType}". Supported: JPEG, PNG, GIF, WebP]`};let t=e.data.length,n=gm(e.data,e.mimeType);if(!(t>5242880||n!==null&&(n.width>8e3||n.height>8e3)||n!==null&&Math.max(n.width,n.height)>1568))return e;cm.info(`Image needs processing`,{base64Size:t,dimensions:n?`${n.width}x${n.height}`:`unknown`,reason:t>5242880?`size`:`dimensions`});let a,o;try{let e=await import(`./magick-wasm-IdXcHdTy.js`).then(e=>e.r);a=e.getMagick,o=e.MIME_TO_MAGICK_FORMAT}catch(e){return cm.error(`ImageMagick WASM module unavailable`,{error:e instanceof Error?e.message:String(e)}),{type:`text`,text:`[Image removed: resize service unavailable (ImageMagick WASM could not be loaded)]`}}let s;try{s=await a()}catch(e){return cm.error(`ImageMagick WASM initialization failed`,{error:e instanceof Error?e.message:String(e)}),{type:`text`,text:`[Image removed: resize service unavailable (WASM init failed)]`}}try{let n=i(um(e.data)),a={data:null,mime:e.mimeType};if(await s.ImageMagick.read(n,async t=>{let n=t.width,r=t.height,i=Math.max(n,r);if(i>1568){let e=1568/i,a=Math.round(n*e),o=Math.round(r*e);t.resize(a,o),cm.info(`Resized image`,{from:`${n}x${r}`,to:`${a}x${o}`})}let s=o[e.mimeType]||`JPEG`;t.write(s,e=>{a.data=new Uint8Array(e)}),a.data&&a.data.length>lm&&s!==`JPEG`?(cm.info(`Still over 5MB, compressing to JPEG q80`),t.quality=80,t.write(`JPEG`,e=>{a.data=new Uint8Array(e)}),a.mime=`image/jpeg`):a.data&&a.data.length>lm&&(cm.info(`Still over 5MB as JPEG, reducing quality to 60`),t.quality=60,t.write(`JPEG`,e=>{a.data=new Uint8Array(e)}))}),!a.data)return cm.warn(`ImageMagick produced no output`),{type:`text`,text:`[Image removed: could not be processed (empty output from resize)]`};if(a.data.length>lm)return cm.warn(`Image still over 5MB after resize+compress`,{size:a.data.length}),{type:`text`,text:`[Image removed: still ${Math.round(a.data.length/1024/1024*10)/10}MB after resize and compression, exceeds 5MB API limit]`};let c=r(a.data);return cm.info(`Image processed successfully`,{originalBase64:t,newBase64:c.length,mimeType:a.mime}),{type:`image`,data:c,mimeType:a.mime}}catch(n){return cm.error(`Image data processing failed (corrupt or unreadable)`,{mimeType:e.mimeType,estimatedBytes:t,error:n instanceof Error?n.message:String(n)}),{type:`text`,text:`[Image removed: image data could not be processed (${n instanceof Error?n.message:`corrupt or unreadable`})]`}}}const vm=n(`tool-adapter`);function ym(e){let t=[],n=0;for(let r of d(e)){if(r.kind===`inert`||!r.parsed)continue;let i=e.slice(n,r.index);i.trim()&&t.push({type:`text`,text:i.trimEnd()}),t.push({type:`image`,mimeType:r.parsed.mimeType,data:r.parsed.data}),n=r.index+r.marker.length}let r=e.slice(n);return(r.trim()||t.length===0)&&t.push({type:`text`,text:r||e}),t}async function bm(e){let t=ym(e),n=[];for(let e of t)e.type===`image`?n.push(await _m(e)):n.push(e);return n}function xm(e,t,n,r){if(!r)return{tracked:null,effectiveSignal:n};let i=r.processManager.spawn({kind:`tool`,argv:[e.name,...Om(t)],owner:r.owner,ppid:r.getParentPid?.()});n?.aborted?r.processManager.signal(i.pid,`SIGINT`):n&&n.addEventListener(`abort`,()=>r.processManager.signal(i.pid,`SIGINT`),{once:!0});let a=r.processManager.onSignal((e,t)=>{e.pid===i.pid&&t===`SIGKILL`&&r.processManager.exit(i.pid,null)});return{tracked:{record:i,manager:r.processManager,unsubscribeKill:a},effectiveSignal:i.abort.signal}}function Sm(e,t){e&&e.manager.exit(e.record.pid,t)}async function Cm(e,t,n){if(!n||typeof e!=`string`||e.length===0)return e;try{return await n.scrubToolResult(e)}catch(n){return vm.warn(`Tool-result scrub failed, falling back to unscrubbed content`,{tool:t,error:n instanceof Error?n.message:String(n)}),e}}async function wm(e,t){try{return await bm(e)}catch(n){return vm.warn(`Image processing failed, falling back to raw content`,{tool:t,error:n instanceof Error?n.message:String(n)}),ym(e)}}async function Tm(e,t,n,r){let i=n?.currentGate();if(!i)return!0;if(r?.aborted)return!1;try{return await i.approve(e.name,t)&&r?.aborted!==!0}catch(t){return vm.warn(`Tool-call gate threw — refusing the call`,{tool:e.name,error:t instanceof Error?t.message:String(t)}),!1}}function Em(e,t,n,r){return{name:e.name,label:e.name,description:e.description,parameters:e.inputSchema,async execute(i,a,o,s){let c;if(s&&(c=em({onUpdate:s,toolName:e.name,toolCallId:i})),!await Tm(e,a,r,o))return c&&tm(c),{content:[{type:`text`,text:`${e.name}: not approved (guest-caused turn).`}],details:{isError:!0}};let l=xm(e,a,o,t);try{let t=await e.execute(a??{},l.effectiveSignal),r=await wm(await Cm(t.content,e.name,n),e.name);return Sm(l.tracked,+!!t.isError),{content:r,details:{isError:t.isError}}}catch(e){throw Sm(l.tracked,l.tracked?.record.abort.signal.aborted?null:1),e}finally{c&&tm(c),l.tracked?.unsubscribeKill()}}}}function Dm(e,t,n,r){return e.map(e=>Em(e,t,n,r))}function Om(e){if(typeof e!=`object`||!e)return[];let t=e;for(let e of[`command`,`file_path`,`path`,`pattern`,`url`,`key`,`name`,`query`,`message`]){let n=t[e];if(typeof n==`string`&&n.length>0)return[n]}for(let e of Object.values(t))if(typeof e==`string`&&e.length>0)return[e];return[]}export{Rt as $,er as A,Ee as At,Ln as B,w as Bt,V as C,Te as Ct,z as D,Ce as Dt,B as E,we as Et,Gn as F,ye as Ft,tn as G,jn as H,Kn as I,be as It,Qt as J,$t as K,qn as L,xe as Lt,Yn as M,_e as Mt,L as N,b as Nt,tr as O,Ae as Ot,Wn as P,ve as Pt,j as Q,I as R,Pe as Rt,ji as S,me as St,yr as T,he as Tt,An as U,In as V,ue as Vt,nn as W,Ut as X,Kt as Y,M as Z,Li as _,de as _t,sm as a,St as at,Ai as b,Ve as bt,Qp as c,pt as ct,uf as d,Ie as dt,Ft as et,of as f,Fe as ft,Ri as g,y as gt,qa as h,C as ht,om as i,wt as it,Qn as j,ge as jt,R as k,je as kt,Jp as l,lt,Hd as m,Ne as mt,Om as n,kt as nt,am as o,k as ot,ef as p,Me as pt,N as q,im as r,Dt as rt,nm as s,xt as st,Dm as t,At as tt,qp as u,st as ut,Mi as v,fe as vt,Cr as w,Se as wt,ki as x,x as xt,Ei as y,pe as yt,Bn as z,Oe as zt};
38
+ `;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function Ep({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=qf(t(r),e);n.push(i.trimStart())}}function Dp(e,t){let n=Z(t)?t.value:t;for(let r of e)if(X(r)&&(r.key===t||r.key===n||Z(r.key)&&r.key.value===n))return r}var Op=class extends Gf{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(hf,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(xp(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=X(e)?e:!e||typeof e!=`object`||!(`key`in e)?new Sp(e,e?.value):new Sp(e.key,e.value);let r=Dp(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);Z(r.value)&&Bf(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=Dp(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=Dp(this.items,e)?.value;return(!t&&Z(n)?n.value:n)??void 0}has(e){return!!Dp(this.items,e)}set(e,t){this.add(new Sp(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)yp(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!X(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Cp(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}};const kp={collection:`map`,default:!0,nodeClass:Op,tag:`tag:yaml.org,2002:map`,resolve(e,t){return Sf(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>Op.from(e,t,n)};var Ap=class extends Gf{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(vf,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=jp(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=jp(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&Z(r)?r.value:r}has(e){let t=jp(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=jp(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];Z(r)&&Bf(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(If(e,String(r++),t));return n}toString(e,t,n){return e?Cp(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(Hf(a,void 0,n))}}return i}};function jp(e){let t=Z(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}const Mp={collection:`seq`,default:!0,nodeClass:Ap,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return Cf(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>Ap.from(e,t,n)};function Np(e){return typeof e==`bigint`||Number.isInteger(e)}const Pp=({value:e})=>JSON.stringify(e),Fp=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:Pp},{identify:e=>e==null,createNode:()=>new $(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:Pp},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:Pp},{identify:Np,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>Np(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:Pp}];[kp,Mp].concat(Fp,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}});function Ip(e,t,n){let{replacer:r}=n,i=new Ap(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(xp(o,s,n))}return i}var Lp=class e extends Ap{constructor(){super(),this.add=Op.prototype.add.bind(this),this.delete=Op.prototype.delete.bind(this),this.get=Op.prototype.get.bind(this),this.has=Op.prototype.has.bind(this),this.set=Op.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(X(e)?(r=If(e.key,``,t),i=If(e.value,r,t)):r=If(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=Ip(e,t,n),i=new this;return i.items=r.items,i}};Lp.tag=`tag:yaml.org,2002:omap`;var Rp=class e extends Op{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=X(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new Sp(e.key,null):new Sp(e,null),Dp(this.items,t.key)||this.items.push(t)}get(e,t){let n=Dp(this.items,e);return!t&&X(n)?Z(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Dp(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Sp(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(xp(e,null,n));return i}};Rp.tag=`tag:yaml.org,2002:set`;const zp=Symbol(`break visit`),Bp=Symbol(`skip children`),Vp=Symbol(`remove item`);function Hp(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),Up(Object.freeze([]),e,t)}Hp.BREAK=zp,Hp.SKIP=Bp,Hp.REMOVE=Vp,Hp.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},Hp.parentCollection=(e,t)=>{let n=Hp.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)};function Up(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=Up(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===zp)return zp;else r===Vp&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}t(((e,t)=>{function n(e){return Array.isArray(e)?e:[e]}let r=/^\s+$/,i=/(?:[^\\]|^)\\$/,a=/^\\!/,o=/^\\#/,s=/\r?\n/g,c=/^\.{0,2}\/|^\.{1,2}$/,l=/\/$/,u=`node-ignore`;typeof Symbol<`u`&&(u=Symbol.for(`node-ignore`));let d=u,f=(e,t,n)=>(Object.defineProperty(e,t,{value:n}),n),p=/([0-z])-([0-z])/g,m=()=>!1,h=e=>e.replace(p,(e,t,n)=>t.charCodeAt(0)<=n.charCodeAt(0)?e:``),g=e=>{let{length:t}=e;return e.slice(0,t-t%2)},ee=[[/^\uFEFF/,()=>``],[/((?:\\\\)*?)(\\?\s+)$/,(e,t,n)=>t+(n.indexOf(`\\`)===0?` `:``)],[/(\\+?)\s/g,(e,t)=>{let{length:n}=t;return t.slice(0,n-n%2)+` `}],[/[\\$.|*+(){^]/g,e=>`\\${e}`],[/(?!\\)\?/g,()=>`[^/]`],[/^\//,()=>`^`],[/\//g,()=>`\\/`],[/^\^*\\\*\\\*\\\//,()=>`^(?:.*\\/)?`],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?`^`:`(?:^|\\/)`}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(e,t,n)=>t+6<n.length?`(?:\\/[^\\/]+)*`:`\\/.+`],[/(^|[^\\]+)(\\\*)+(?=.+)/g,(e,t,n)=>t+n.replace(/\\\*/g,`[^\\/]*`)],[/\\\\\\(?=[$.|*+(){^])/g,()=>`\\`],[/\\\\/g,()=>`\\`],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(e,t,n,r,i)=>t===`\\`?`\\[${n}${g(r)}${i}`:i===`]`&&r.length%2==0?`[${h(n)}${r}]`:`[]`],[/(?:[^*])$/,e=>/\/$/.test(e)?`${e}$`:`${e}(?=$|\\/$)`]],_=/(^|\\\/)?\\\*$/,v=`regex`,te=`checkRegex`,ne={[v](e,t){return`${t?`${t}[^/]+`:`[^/]*`}(?=$|\\/$)`},[te](e,t){return`${t?`${t}[^/]*`:`[^/]*`}(?=$|\\/$)`}},re=e=>ee.reduce((t,[n,r])=>t.replace(n,r.bind(e)),e),ie=e=>typeof e==`string`,ae=e=>e&&ie(e)&&!r.test(e)&&!i.test(e)&&e.indexOf(`#`)!==0,oe=e=>e.split(s).filter(Boolean);var se=class{constructor(e,t,n,r,i,a){this.pattern=e,this.mark=t,this.negative=i,f(this,`body`,n),f(this,`ignoreCase`,r),f(this,`regexPrefix`,a)}get regex(){let e=`_regex`;return this[e]?this[e]:this._make(v,e)}get checkRegex(){let e=`_checkRegex`;return this[e]?this[e]:this._make(te,e)}_make(e,t){let n=this.regexPrefix.replace(_,ne[e]),r=this.ignoreCase?new RegExp(n,`i`):new RegExp(n);return f(this,t,r)}};let ce=({pattern:e,mark:t},n)=>{let r=!1,i=e;i.indexOf(`!`)===0&&(r=!0,i=i.substr(1)),i=i.replace(a,`!`).replace(o,`#`);let s=re(i);return new se(e,t,i,n,r,s)};var le=class{constructor(e){this._ignoreCase=e,this._rules=[]}_add(e){if(e&&e[d]){this._rules=this._rules.concat(e._rules._rules),this._added=!0;return}if(ie(e)&&(e={pattern:e}),ae(e.pattern)){let t=ce(e,this._ignoreCase);this._added=!0,this._rules.push(t)}}add(e){return this._added=!1,n(ie(e)?oe(e):e).forEach(this._add,this),this._added}test(e,t,n){let r=!1,i=!1,a;this._rules.forEach(o=>{let{negative:s}=o;i===s&&r!==i||s&&!r&&!i&&!t||o[n].test(e)&&(r=!s,i=s,a=s?void 0:o)});let o={ignored:r,unignored:i};return a&&(o.rule=a),o}};let ue=(e,t)=>{throw new t(e)},y=(e,t,n)=>ie(e)?e?!y.isNotRelative(e)||n(`path should be a \`path.relative()\`d string, but got "${t}"`,RangeError):n(`path must not be empty`,TypeError):n(`path must be a string, but got \`${t}\``,TypeError),de=e=>c.test(e);y.isNotRelative=de,y.convert=e=>e;var fe=class{constructor({ignorecase:e=!0,ignoreCase:t=e,allowRelativePaths:n=!1}={}){f(this,d,!0),this._rules=new le(t),this._strictPathCheck=!n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}add(e){return this._rules.add(e)&&this._initCache(),this}addPattern(e){return this.add(e)}_test(e,t,n,r){let i=e&&y.convert(e);return y(i,e,this._strictPathCheck?ue:m),this._t(i,t,n,r)}checkIgnore(e){if(!l.test(e))return this.test(e);let t=e.split(`/`).filter(Boolean);if(t.pop(),t.length){let e=this._t(t.join(`/`)+`/`,this._testCache,!0,t);if(e.ignored)return e}return this._rules.test(e,!1,te)}_t(e,t,n,r){if(e in t)return t[e];if(r||=e.split(`/`).filter(Boolean),r.pop(),!r.length)return t[e]=this._rules.test(e,n,v);let i=this._t(r.join(`/`)+`/`,t,n,r);return t[e]=i.ignored?i:this._rules.test(e,n,v)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return n(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}};let pe=e=>new fe(e),me=e=>y(e&&y.convert(e),e,m),he=()=>{y.convert=e=>/^\\\\\?\\/.test(e)||/["<>|\u0000-\u001F]+/u.test(e)?e:e.replace(/\\/g,`/`);let e=/^[a-z]:\//i;y.isNotRelative=t=>e.test(t)||de(t)};typeof process<`u`&&process.platform===`win32`&&he(),t.exports=pe,pe.default=pe,t.exports.isPathValid=me,f(t.exports,Symbol.for(`setupWindows`),he)}))();const Wp={"pi.session.id":{type:`string`,required:!0,cardinality:`high`,description:`Session id`},"pi.lane.name":{type:`string`,required:!0,cardinality:`high`,description:`Lane name`},"pi.operation.id":{type:`string`,required:!0,cardinality:`high`,description:`Durable operation id`},"pi.operation.recovery":{type:`boolean`,required:!0,description:`Whether this invocation resumes durable work`}},Gp={"pi.error.code":{type:`string`,cardinality:`low`,description:`Stable operation error code`},"pi.error.type":{type:`string`,cardinality:`low`,description:`Low-cardinality operation error class`}};({...Wp}),{...Gp},{...Wp},{...Gp},{...Wp},{...Gp},globalThis.Buffer,j({command:R({description:`Bash command to execute`}),timeout:Lt(Zn({description:`Timeout in seconds (optional, no default timeout)`}))});const Kp=j({oldText:R({description:`Exact text for one targeted replacement. It must be unique in the original file and must not overlap with any other edits[].oldText in the same call.`}),newText:R({description:`Replacement text for this targeted edit.`})},{});j({path:R({description:`Path to the file to edit (relative or absolute)`}),edits:xt(Kp,{description:`One or more targeted replacements. Each edit is matched against the original file, not incrementally. Do not include overlapping or nested edits. If two changes touch the same block or nearby lines, merge them into one edit instead.`})},{}),j({path:R({description:`Path to the file to read (relative or absolute)`}),offset:Lt(Zn({description:`Line number to start reading from (1-indexed)`})),limit:Lt(Zn({description:`Maximum number of lines to read`}))}),j({path:R({description:`Path to the file to write (relative or absolute)`}),content:R({description:`Content to write to the file`})});function qp(){return a()?`extension-direct`:s()?`extension-delegate`:globalThis.__slicc_connect_mode?`connect`:`node-rest`}function Jp(){return qp()===`node-rest`}const Yp=n(`secret-scrub`),Xp=`[tool output withheld: secret scrub unavailable]`,Zp=async e=>e;function Qp(){let e=qp();return e===`extension-direct`?async e=>{if(!e)return e;try{let t=await new Promise(t=>{chrome.runtime.sendMessage({type:`secrets.scrub-tool-result`,text:e},e=>t(e??{}))});return t.error?(Yp.debug(`SW scrub-tool-result returned error`),Xp):typeof t.text==`string`?t.text:Xp}catch{return Yp.debug(`SW scrub-tool-result failed`),Xp}}:e===`extension-delegate`?async e=>{if(!e)return e;try{let t=await l(`secrets.scrub-tool-result`,{text:e});return t?.error?(Yp.debug(`Bridge scrub-tool-result returned error`),Xp):typeof t?.text==`string`?t.text:Xp}catch{return Yp.debug(`Bridge scrub-tool-result failed`),Xp}}:e===`connect`?Zp:async e=>{if(!e)return e;try{let t=await fetch(o(`/api/secrets/scrub`),{method:`POST`,headers:c({"content-type":`application/json`}),body:JSON.stringify({text:e})});if(!t.ok)return Yp.debug(`Server scrub-tool-result returned non-ok`,{status:t.status}),e;let n=await t.json();return typeof n.text==`string`?n.text:e}catch(t){return Yp.debug(`Server scrub-tool-result failed`,{error:t instanceof Error?t.message:String(t)}),e}}}const $p=[];function em(e){return $p.push(e),e}function tm(e){let t=$p.lastIndexOf(e);t!==-1&&$p.splice(t,1)}function nm(){return $p.length>0?$p[$p.length-1]:null}const rm=n(`tool-ui`),im=`__mounted`,am=new class{pending=new Map;idCounter=0;mounted=new Set;mountWaiters=new Map;generateId(){return`tool-ui-${++this.idCounter}-${Date.now().toString(36)}`}register(e,t,n,r){this.mounted.delete(e),this.pending.set(e,{request:t,resolve:n,reject:r}),rm.info(`Tool UI registered`,{id:e})}async handleAction(e,t){let n=this.pending.get(e);if(!n){rm.warn(`Action for unknown tool UI`,{id:e,action:t.action});return}rm.info(`Tool UI action`,{id:e,action:t.action});try{let e;e=n.request.onAction?await n.request.onAction(t.action,t.data):t,n.resolve(e)}catch(e){n.reject(e instanceof Error?e:Error(String(e)))}finally{this.pending.delete(e),this.clearMountWaiter(e,`tool ui completed`)}}cancel(e,t=`cancelled`){let n=this.pending.get(e);n&&(n.reject(Error(t)),this.pending.delete(e),rm.info(`Tool UI cancelled`,{id:e,reason:t})),this.clearMountWaiter(e,t),this.mounted.delete(e)}cancelAll(e=`cancelled`){let t=this.pending.size;for(let[t,n]of this.pending)n.reject(Error(e));this.pending.clear();for(let t of[...this.mountWaiters.keys()])this.clearMountWaiter(t,e);this.mounted.clear(),t>0&&rm.info(`All tool UIs cancelled`,{reason:e,count:t})}isPending(e){return this.pending.has(e)}getPendingIds(){return[...this.pending.keys()]}markMounted(e){this.mounted.add(e);let t=this.mountWaiters.get(e);t&&(clearTimeout(t.timeoutHandle),this.mountWaiters.delete(e),t.resolve())}waitForMount(e,t){return this.mounted.has(e)?Promise.resolve():new Promise((n,r)=>{let i=setTimeout(()=>{this.mountWaiters.delete(e),r(Error(`tool UI ${e} was not mounted by any panel within ${t}ms — check the chat panel`))},t);this.mountWaiters.set(e,{resolve:n,reject:r,timeoutHandle:i})})}clearMountWaiter(e,t){let n=this.mountWaiters.get(e);n&&(clearTimeout(n.timeoutHandle),this.mountWaiters.delete(e),n.reject(Error(t)))}};async function om(e,t){let n=e.id??am.generateId(),r,i,a=new Promise((e,t)=>{r=e,i=t});return am.register(n,e,r,i),t?t({content:[{type:`tool_ui`,requestId:n,html:e.html}]}):rm.warn(`showToolUI called without onUpdate callback — UI may not render`),a.finally(()=>{t&&t({content:[{type:`tool_ui_done`,requestId:n}]})})}async function sm(e){let t=nm();return t?om(e,t.onUpdate):(rm.warn(`showToolUIFromContext called without execution context`),null)}const cm=n(`image-processor`),lm=3932160;function um(e){let t=e.replace(/[\t\n\f\r ]/g,``),n=t.length%4;return n===2?`${t}==`:n===3?`${t}=`:t}function dm(e,t){let n=i(um(e.slice(0,t)));return new DataView(n.buffer,n.byteOffset,n.byteLength)}function fm(e,t){return e>0&&t>0?{width:e,height:t}:null}function pm(e){if(e.length<32)return null;let t=dm(e,32);return fm(t.getUint32(16,!1),t.getUint32(20,!1))}function mm(e){if(e.length<16)return null;let t=dm(e,16);return fm(t.getUint16(6,!0),t.getUint16(8,!0))}function hm(e){let t=dm(e,Math.min(87384,e.length));for(let e=0;e<t.byteLength-8;e++){if(t.getUint8(e)!==255)continue;let n=t.getUint8(e+1);if(n===192||n===194)return fm(t.getUint16(e+7,!1),t.getUint16(e+5,!1))}return null}function gm(e,t){try{let n=um(e);if(t===`image/png`)return pm(n);if(t===`image/gif`)return mm(n);if(t===`image/jpeg`)return hm(n)}catch{}return null}async function _m(e){if(!u(e.mimeType))return cm.warn(`Unsupported image format`,{mimeType:e.mimeType}),{type:`text`,text:`[Image removed: unsupported format "${e.mimeType}". Supported: JPEG, PNG, GIF, WebP]`};let t=e.data.length,n=gm(e.data,e.mimeType);if(!(t>5242880||n!==null&&(n.width>8e3||n.height>8e3)||n!==null&&Math.max(n.width,n.height)>1568))return e;cm.info(`Image needs processing`,{base64Size:t,dimensions:n?`${n.width}x${n.height}`:`unknown`,reason:t>5242880?`size`:`dimensions`});let a,o;try{let e=await import(`./magick-wasm-DrHkiveP.js`).then(e=>e.r);a=e.getMagick,o=e.MIME_TO_MAGICK_FORMAT}catch(e){return cm.error(`ImageMagick WASM module unavailable`,{error:e instanceof Error?e.message:String(e)}),{type:`text`,text:`[Image removed: resize service unavailable (ImageMagick WASM could not be loaded)]`}}let s;try{s=await a()}catch(e){return cm.error(`ImageMagick WASM initialization failed`,{error:e instanceof Error?e.message:String(e)}),{type:`text`,text:`[Image removed: resize service unavailable (WASM init failed)]`}}try{let n=i(um(e.data)),a={data:null,mime:e.mimeType};if(await s.ImageMagick.read(n,async t=>{let n=t.width,r=t.height,i=Math.max(n,r);if(i>1568){let e=1568/i,a=Math.round(n*e),o=Math.round(r*e);t.resize(a,o),cm.info(`Resized image`,{from:`${n}x${r}`,to:`${a}x${o}`})}let s=o[e.mimeType]||`JPEG`;t.write(s,e=>{a.data=new Uint8Array(e)}),a.data&&a.data.length>lm&&s!==`JPEG`?(cm.info(`Still over 5MB, compressing to JPEG q80`),t.quality=80,t.write(`JPEG`,e=>{a.data=new Uint8Array(e)}),a.mime=`image/jpeg`):a.data&&a.data.length>lm&&(cm.info(`Still over 5MB as JPEG, reducing quality to 60`),t.quality=60,t.write(`JPEG`,e=>{a.data=new Uint8Array(e)}))}),!a.data)return cm.warn(`ImageMagick produced no output`),{type:`text`,text:`[Image removed: could not be processed (empty output from resize)]`};if(a.data.length>lm)return cm.warn(`Image still over 5MB after resize+compress`,{size:a.data.length}),{type:`text`,text:`[Image removed: still ${Math.round(a.data.length/1024/1024*10)/10}MB after resize and compression, exceeds 5MB API limit]`};let c=r(a.data);return cm.info(`Image processed successfully`,{originalBase64:t,newBase64:c.length,mimeType:a.mime}),{type:`image`,data:c,mimeType:a.mime}}catch(n){return cm.error(`Image data processing failed (corrupt or unreadable)`,{mimeType:e.mimeType,estimatedBytes:t,error:n instanceof Error?n.message:String(n)}),{type:`text`,text:`[Image removed: image data could not be processed (${n instanceof Error?n.message:`corrupt or unreadable`})]`}}}const vm=n(`tool-adapter`);function ym(e){let t=[],n=0;for(let r of d(e)){if(r.kind===`inert`||!r.parsed)continue;let i=e.slice(n,r.index);i.trim()&&t.push({type:`text`,text:i.trimEnd()}),t.push({type:`image`,mimeType:r.parsed.mimeType,data:r.parsed.data}),n=r.index+r.marker.length}let r=e.slice(n);return(r.trim()||t.length===0)&&t.push({type:`text`,text:r||e}),t}async function bm(e){let t=ym(e),n=[];for(let e of t)e.type===`image`?n.push(await _m(e)):n.push(e);return n}function xm(e,t,n,r){if(!r)return{tracked:null,effectiveSignal:n};let i=r.processManager.spawn({kind:`tool`,argv:[e.name,...Om(t)],owner:r.owner,ppid:r.getParentPid?.()});n?.aborted?r.processManager.signal(i.pid,`SIGINT`):n&&n.addEventListener(`abort`,()=>r.processManager.signal(i.pid,`SIGINT`),{once:!0});let a=r.processManager.onSignal((e,t)=>{e.pid===i.pid&&t===`SIGKILL`&&r.processManager.exit(i.pid,null)});return{tracked:{record:i,manager:r.processManager,unsubscribeKill:a},effectiveSignal:i.abort.signal}}function Sm(e,t){e&&e.manager.exit(e.record.pid,t)}async function Cm(e,t,n){if(!n||typeof e!=`string`||e.length===0)return e;try{return await n.scrubToolResult(e)}catch(n){return vm.warn(`Tool-result scrub failed, falling back to unscrubbed content`,{tool:t,error:n instanceof Error?n.message:String(n)}),e}}async function wm(e,t){try{return await bm(e)}catch(n){return vm.warn(`Image processing failed, falling back to raw content`,{tool:t,error:n instanceof Error?n.message:String(n)}),ym(e)}}async function Tm(e,t,n,r){let i=n?.currentGate();if(!i)return!0;if(r?.aborted)return!1;try{return await i.approve(e.name,t)&&r?.aborted!==!0}catch(t){return vm.warn(`Tool-call gate threw — refusing the call`,{tool:e.name,error:t instanceof Error?t.message:String(t)}),!1}}function Em(e,t,n,r){return{name:e.name,label:e.name,description:e.description,parameters:e.inputSchema,async execute(i,a,o,s){let c;if(s&&(c=em({onUpdate:s,toolName:e.name,toolCallId:i})),!await Tm(e,a,r,o))return c&&tm(c),{content:[{type:`text`,text:`${e.name}: not approved (guest-caused turn).`}],details:{isError:!0}};let l=xm(e,a,o,t);try{let t=await e.execute(a??{},l.effectiveSignal),r=await wm(await Cm(t.content,e.name,n),e.name);return Sm(l.tracked,+!!t.isError),{content:r,details:{isError:t.isError}}}catch(e){throw Sm(l.tracked,l.tracked?.record.abort.signal.aborted?null:1),e}finally{c&&tm(c),l.tracked?.unsubscribeKill()}}}}function Dm(e,t,n,r){return e.map(e=>Em(e,t,n,r))}function Om(e){if(typeof e!=`object`||!e)return[];let t=e;for(let e of[`command`,`file_path`,`path`,`pattern`,`url`,`key`,`name`,`query`,`message`]){let n=t[e];if(typeof n==`string`&&n.length>0)return[n]}for(let e of Object.values(t))if(typeof e==`string`&&e.length>0)return[e];return[]}export{Rt as $,er as A,Ee as At,Ln as B,w as Bt,V as C,Te as Ct,z as D,Ce as Dt,B as E,we as Et,Gn as F,ye as Ft,tn as G,jn as H,Kn as I,be as It,Qt as J,$t as K,qn as L,xe as Lt,Yn as M,_e as Mt,L as N,b as Nt,tr as O,Ae as Ot,Wn as P,ve as Pt,j as Q,I as R,Pe as Rt,ji as S,me as St,yr as T,he as Tt,An as U,In as V,ue as Vt,nn as W,Ut as X,Kt as Y,M as Z,Li as _,de as _t,sm as a,St as at,Ai as b,Ve as bt,Qp as c,pt as ct,uf as d,Ie as dt,Ft as et,of as f,Fe as ft,Ri as g,y as gt,qa as h,C as ht,om as i,wt as it,Qn as j,ge as jt,R as k,je as kt,Jp as l,lt,Hd as m,Ne as mt,Om as n,kt as nt,am as o,k as ot,ef as p,Me as pt,N as q,im as r,Dt as rt,nm as s,xt as st,Dm as t,At as tt,qp as u,st as ut,Mi as v,fe as vt,Cr as w,Se as wt,ki as x,x as xt,Ei as y,pe as yt,Bn as z,Oe as zt};
@@ -1 +1 @@
1
- import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./agent-bridge-UBo80Ndw.js";import{x as n}from"./record-CUBwpX6h.js";const r=e(`directed-approval`);function i(e,t){if(e.kind===`user`)return a(`the user tier is not a directed approval`);if(e.kind===`agent`)return a(`agent approvals are not enqueued to a unit`);let r=e.unitJid;if(!t.scoops.has(r))return a(`the requesting unit is not registered`);let i=t.ownerRootOf(r);if(!i)return a(`no owning cone for the requesting unit`);let o=e.kind===`cone`?i:[...t.scoops.values()].find(t=>t.parentJid===i.jid&&(t.name===e.scoopName||t.folder===e.scoopName));return o?n(o).canResolveApprovals?{ok:!0,requesterJid:r,approver:o}:a(`the named approver cannot resolve approvals`):a(`delegated approver not found under this cone`)}function a(e){return r.warn(`Directed approval failing closed`,{reason:e}),{ok:!1,reason:e}}const o={decision:`deny`};async function s(e,n){let a=e.approver;if(a?.kind===`agent`){let i=globalThis[t];if(!i)return r.warn(`No agent bridge available for an approver agent — denying`),o;let{approverRunnerFor:s}=await import(`./approver-agent-CDzqjgJM.js`),c=n.getSharedFs(),l=await s({spawn:e=>i.spawn(e),readSharedFile:async e=>{if(!c)return null;try{let t=await c.readFile(e,{encoding:`utf-8`});return typeof t==`string`?t:null}catch{return null}},findUnit:e=>{let t=n.scoops.get(e);return t?{workspace:n.workspaceFor(t),folder:t.folder}:void 0}})({kind:e.kind===`guest-tool`?`guest-tool`:`guest-message`,requester:e.requester??`an unidentified requester`,detail:e.detail},a.unitJid);return r.info(`Approver agent verdict`,{decision:l.decision,reason:l.reason}),l.decision===`allow`?{decision:`allow`}:o}if(a&&a.kind!==`user`){let t=i(a,n);return t.ok?n.enqueue(t.requesterJid,e,{approver:t.approver}):o}return n.approveAsUser(e)}export{s as runDirectedApproval};
1
+ import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./agent-bridge-CcjfBcbz.js";import{x as n}from"./record-CUBwpX6h.js";const r=e(`directed-approval`);function i(e,t){if(e.kind===`user`)return a(`the user tier is not a directed approval`);if(e.kind===`agent`)return a(`agent approvals are not enqueued to a unit`);let r=e.unitJid;if(!t.scoops.has(r))return a(`the requesting unit is not registered`);let i=t.ownerRootOf(r);if(!i)return a(`no owning cone for the requesting unit`);let o=e.kind===`cone`?i:[...t.scoops.values()].find(t=>t.parentJid===i.jid&&(t.name===e.scoopName||t.folder===e.scoopName));return o?n(o).canResolveApprovals?{ok:!0,requesterJid:r,approver:o}:a(`the named approver cannot resolve approvals`):a(`delegated approver not found under this cone`)}function a(e){return r.warn(`Directed approval failing closed`,{reason:e}),{ok:!1,reason:e}}const o={decision:`deny`};async function s(e,n){let a=e.approver;if(a?.kind===`agent`){let i=globalThis[t];if(!i)return r.warn(`No agent bridge available for an approver agent — denying`),o;let{approverRunnerFor:s}=await import(`./approver-agent-CDzqjgJM.js`),c=n.getSharedFs(),l=await s({spawn:e=>i.spawn(e),readSharedFile:async e=>{if(!c)return null;try{let t=await c.readFile(e,{encoding:`utf-8`});return typeof t==`string`?t:null}catch{return null}},findUnit:e=>{let t=n.scoops.get(e);return t?{workspace:n.workspaceFor(t),folder:t.folder}:void 0}})({kind:e.kind===`guest-tool`?`guest-tool`:`guest-message`,requester:e.requester??`an unidentified requester`,detail:e.detail},a.unitJid);return r.info(`Approver agent verdict`,{decision:l.decision,reason:l.reason}),l.decision===`allow`?{decision:`allow`}:o}if(a&&a.kind!==`user`){let t=i(a,n);return t.ok?n.enqueue(t.requesterJid,e,{approver:t.approver}):o}return n.approveAsUser(e)}export{s as runDirectedApproval};
@@ -1 +1 @@
1
- import{t as e}from"./logger-LESFN7Hj.js";import"./proxied-fetch-DUC7X0GS.js";import{t}from"./runtime-env-DadgceZk.js";import"./shared-vu5AooI5.js";import{f as n,p as r,r as i}from"./installer-DK4dNFOa.js";e(`speech:espeak`);const a=[`ort-wasm-simd-threaded.jsep.mjs`,`https://${["cdn","jsdelivr","net"].join(".")}/npm/onnxruntime-web@1.26.0-dev.20260416-b7804b056c/dist/ort-wasm-simd-threaded.jsep.wasm`,`ort-wasm-simd-threaded.mjs`,`https://${["cdn","jsdelivr","net"].join(".")}/npm/onnxruntime-web@1.26.0-dev.20260416-b7804b056c/dist/ort.wasm`,`ort-wasm-simd-threaded.asyncify.mjs`,`https://${["cdn","jsdelivr","net"].join(".")}/npm/onnxruntime-web@1.26.0-dev.20260416-b7804b056c/dist/ort-wasm-simd-threaded.asyncify.wasm`],o=e(`speech:ensure-assets`),s=`onnxruntime-web`,c=`espeak-ng`,l=[`espeak-ng.js`,`espeak-ng.wasm`],u=`/workspace`,d=t,f=a.filter(e=>!/\.(asyncify|jspi)\./.test(e));async function p(e,t){if((await Promise.all(f.map(t=>e.fs.exists(`/workspace/node_modules/onnxruntime-web/dist/${t}`)))).every(Boolean))return t?.({asset:s,phase:`present`}),!1;t?.({asset:s,phase:`staging`});let{errors:n}=await i([s],{fs:e.fs,fetch:e.fetch,cwd:u});if(n.length>0)throw Error(`failed to stage ${s} wasm runtime: ${n[0].error.message}`);return t?.({asset:s,phase:`done`}),!0}async function m(e,t){if((await Promise.all(l.map(t=>e.fs.exists(`/workspace/node_modules/espeak-ng/dist/${t}`)))).every(Boolean))return t?.({asset:c,phase:`present`}),!1;t?.({asset:c,phase:`staging`});let{errors:n}=await i([c],{fs:e.fs,fetch:e.fetch,cwd:u});if(n.length>0)throw Error(`failed to stage ${c} wasm: ${n[0].error.message}`);return t?.({asset:c,phase:`done`}),!0}async function h(e,t){try{return await m(e,t)}catch(e){return o.warn(`optional espeak-ng staging failed; non-English Kokoro voices may fall back`,e),!1}}async function g(e,t,i){let a=r(t,null,u),o=0,s=await n({fetch:e.fetch,fs:e.fs,repo:t,targetDir:a,progress:{onListed:({files:e,totalBytes:n})=>i?.({asset:t,phase:`listing`,filesLoaded:0,filesTotal:e.length,bytesLoaded:0,bytesTotal:n}),onFile:e=>{o+=e.bytes,i?.({asset:t,phase:e.status,file:e.file,filesLoaded:e.index,filesTotal:e.total,bytesLoaded:o})}}});return i?.({asset:t,phase:`done`,filesLoaded:s.files.length,filesTotal:s.files.length,bytesLoaded:o,bytesTotal:o}),{repo:t,downloaded:s.downloaded,skipped:s.skipped}}async function _(e,t){if(d())return{skipped:!0,ortStaged:!1,espeakStaged:!1,repos:[]};let n=await p(e,t),r=e.repos??[`onnx-community/whisper-tiny`,`onnx-community/Kokoro-82M-v1.0-ONNX`],i=[];for(let n of r)i.push(await g(e,n,t));let a=await h(e,t);return o.info(`speech assets staged`,{ortStaged:n,espeakStaged:a,repos:i.length}),{skipped:!1,ortStaged:n,espeakStaged:a,repos:i}}export{_ as ensureSpeechAssetsStaged};
1
+ import{t as e}from"./logger-LESFN7Hj.js";import"./proxied-fetch-DUC7X0GS.js";import{t}from"./runtime-env-DadgceZk.js";import"./shared-pVZLJOGO.js";import{f as n,p as r,r as i}from"./installer-CTX50_zb.js";e(`speech:espeak`);const a=[`ort-wasm-simd-threaded.jsep.mjs`,`https://${["cdn","jsdelivr","net"].join(".")}/npm/onnxruntime-web@1.26.0-dev.20260416-b7804b056c/dist/ort-wasm-simd-threaded.jsep.wasm`,`ort-wasm-simd-threaded.mjs`,`https://${["cdn","jsdelivr","net"].join(".")}/npm/onnxruntime-web@1.26.0-dev.20260416-b7804b056c/dist/ort.wasm`,`ort-wasm-simd-threaded.asyncify.mjs`,`https://${["cdn","jsdelivr","net"].join(".")}/npm/onnxruntime-web@1.26.0-dev.20260416-b7804b056c/dist/ort-wasm-simd-threaded.asyncify.wasm`],o=e(`speech:ensure-assets`),s=`onnxruntime-web`,c=`espeak-ng`,l=[`espeak-ng.js`,`espeak-ng.wasm`],u=`/workspace`,d=t,f=a.filter(e=>!/\.(asyncify|jspi)\./.test(e));async function p(e,t){if((await Promise.all(f.map(t=>e.fs.exists(`/workspace/node_modules/onnxruntime-web/dist/${t}`)))).every(Boolean))return t?.({asset:s,phase:`present`}),!1;t?.({asset:s,phase:`staging`});let{errors:n}=await i([s],{fs:e.fs,fetch:e.fetch,cwd:u});if(n.length>0)throw Error(`failed to stage ${s} wasm runtime: ${n[0].error.message}`);return t?.({asset:s,phase:`done`}),!0}async function m(e,t){if((await Promise.all(l.map(t=>e.fs.exists(`/workspace/node_modules/espeak-ng/dist/${t}`)))).every(Boolean))return t?.({asset:c,phase:`present`}),!1;t?.({asset:c,phase:`staging`});let{errors:n}=await i([c],{fs:e.fs,fetch:e.fetch,cwd:u});if(n.length>0)throw Error(`failed to stage ${c} wasm: ${n[0].error.message}`);return t?.({asset:c,phase:`done`}),!0}async function h(e,t){try{return await m(e,t)}catch(e){return o.warn(`optional espeak-ng staging failed; non-English Kokoro voices may fall back`,e),!1}}async function g(e,t,i){let a=r(t,null,u),o=0,s=await n({fetch:e.fetch,fs:e.fs,repo:t,targetDir:a,progress:{onListed:({files:e,totalBytes:n})=>i?.({asset:t,phase:`listing`,filesLoaded:0,filesTotal:e.length,bytesLoaded:0,bytesTotal:n}),onFile:e=>{o+=e.bytes,i?.({asset:t,phase:e.status,file:e.file,filesLoaded:e.index,filesTotal:e.total,bytesLoaded:o})}}});return i?.({asset:t,phase:`done`,filesLoaded:s.files.length,filesTotal:s.files.length,bytesLoaded:o,bytesTotal:o}),{repo:t,downloaded:s.downloaded,skipped:s.skipped}}async function _(e,t){if(d())return{skipped:!0,ortStaged:!1,espeakStaged:!1,repos:[]};let n=await p(e,t),r=e.repos??[`onnx-community/whisper-tiny`,`onnx-community/Kokoro-82M-v1.0-ONNX`],i=[];for(let n of r)i.push(await g(e,n,t));let a=await h(e,t);return o.info(`speech assets staged`,{ortStaged:n,espeakStaged:a,repos:i.length}),{skipped:!1,ortStaged:n,espeakStaged:a,repos:i}}export{_ as ensureSpeechAssetsStaged};
@@ -1,4 +1,4 @@
1
- import{i as e,t}from"./rolldown-runtime-Dd_uD5pT.js";import{a as n}from"./path-utils-DNJG-zQf.js";import{C as r,S as i,p as a,t as o}from"./shared-vu5AooI5.js";import{n as s}from"./wasm-compiler-Ct7QZURL.js";var c=e(t(((e,t)=>{(e=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},o=(e,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of r(a))!i.call(e,c)&&c!==o&&t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e},s=e=>o(t({},`__esModule`,{value:!0}),e),c=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),l={};a(l,{analyzeMetafile:()=>xe,analyzeMetafileSync:()=>Te,build:()=>_e,buildSync:()=>Se,context:()=>ve,default:()=>je,formatMessages:()=>be,formatMessagesSync:()=>we,initialize:()=>ke,stop:()=>Ee,transform:()=>ye,transformSync:()=>Ce,version:()=>ge}),e.exports=s(l);function u(e){let t=e=>{if(e===null)n.write8(0);else if(typeof e==`boolean`)n.write8(1),n.write8(+e);else if(typeof e==`number`)n.write8(2),n.write32(e|0);else if(typeof e==`string`)n.write8(3),n.write(p(e));else if(e instanceof Uint8Array)n.write8(4),n.write(e);else if(e instanceof Array){n.write8(5),n.write32(e.length);for(let n of e)t(n)}else{let r=Object.keys(e);n.write8(6),n.write32(r.length);for(let i of r)n.write(p(i)),t(e[i])}},n=new f;return n.write32(0),n.write32(e.id<<1|!e.isRequest),t(e.value),_(n.buf,n.len-4,0),n.buf.subarray(0,n.len)}function d(e){let t=()=>{switch(n.read8()){case 0:return null;case 1:return!!n.read8();case 2:return n.read32();case 3:return m(n.read());case 4:return n.read();case 5:{let e=n.read32(),r=[];for(let n=0;n<e;n++)r.push(t());return r}case 6:{let e=n.read32(),r={};for(let i=0;i<e;i++)r[m(n.read())]=t();return r}default:throw Error(`Invalid packet`)}},n=new f(e),r=n.read32(),i=!(r&1);r>>>=1;let a=t();if(n.ptr!==e.length)throw Error(`Invalid packet`);return{id:r,isRequest:i,value:a}}var f=class{constructor(e=new Uint8Array(1024)){this.buf=e,this.len=0,this.ptr=0}_write(e){if(this.len+e>this.buf.length){let t=new Uint8Array((this.len+e)*2);t.set(this.buf),this.buf=t}return this.len+=e,this.len-e}write8(e){let t=this._write(1);this.buf[t]=e}write32(e){let t=this._write(4);_(this.buf,e,t)}write(e){let t=this._write(4+e.length);_(this.buf,e.length,t),this.buf.set(e,t+4)}_read(e){if(this.ptr+e>this.buf.length)throw Error(`Invalid packet`);return this.ptr+=e,this.ptr-e}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let e=this.read32(),t=new Uint8Array(e),n=this._read(t.length);return t.set(this.buf.subarray(n,n+e)),t}},p,m,h;if(typeof TextEncoder<`u`&&typeof TextDecoder<`u`){let e=new TextEncoder,t=new TextDecoder;p=t=>e.encode(t),m=e=>t.decode(e),h=`new TextEncoder().encode("")`}else if(typeof Buffer<`u`)p=e=>Buffer.from(e),m=e=>{let{buffer:t,byteOffset:n,byteLength:r}=e;return Buffer.from(t,n,r).toString()},h=`Buffer.from("")`;else throw Error(`No UTF-8 codec found`);if(!(p(``)instanceof Uint8Array))throw Error(`Invariant violation: "${h} instanceof Uint8Array" is incorrectly false
1
+ import{i as e,t}from"./rolldown-runtime-Dd_uD5pT.js";import{a as n}from"./path-utils-DNJG-zQf.js";import{C as r,S as i,p as a,t as o}from"./shared-pVZLJOGO.js";import{n as s}from"./wasm-compiler-Ct7QZURL.js";var c=e(t(((e,t)=>{(e=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},o=(e,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of r(a))!i.call(e,c)&&c!==o&&t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e},s=e=>o(t({},`__esModule`,{value:!0}),e),c=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),l={};a(l,{analyzeMetafile:()=>xe,analyzeMetafileSync:()=>Te,build:()=>_e,buildSync:()=>Se,context:()=>ve,default:()=>je,formatMessages:()=>be,formatMessagesSync:()=>we,initialize:()=>ke,stop:()=>Ee,transform:()=>ye,transformSync:()=>Ce,version:()=>ge}),e.exports=s(l);function u(e){let t=e=>{if(e===null)n.write8(0);else if(typeof e==`boolean`)n.write8(1),n.write8(+e);else if(typeof e==`number`)n.write8(2),n.write32(e|0);else if(typeof e==`string`)n.write8(3),n.write(p(e));else if(e instanceof Uint8Array)n.write8(4),n.write(e);else if(e instanceof Array){n.write8(5),n.write32(e.length);for(let n of e)t(n)}else{let r=Object.keys(e);n.write8(6),n.write32(r.length);for(let i of r)n.write(p(i)),t(e[i])}},n=new f;return n.write32(0),n.write32(e.id<<1|!e.isRequest),t(e.value),_(n.buf,n.len-4,0),n.buf.subarray(0,n.len)}function d(e){let t=()=>{switch(n.read8()){case 0:return null;case 1:return!!n.read8();case 2:return n.read32();case 3:return m(n.read());case 4:return n.read();case 5:{let e=n.read32(),r=[];for(let n=0;n<e;n++)r.push(t());return r}case 6:{let e=n.read32(),r={};for(let i=0;i<e;i++)r[m(n.read())]=t();return r}default:throw Error(`Invalid packet`)}},n=new f(e),r=n.read32(),i=!(r&1);r>>>=1;let a=t();if(n.ptr!==e.length)throw Error(`Invalid packet`);return{id:r,isRequest:i,value:a}}var f=class{constructor(e=new Uint8Array(1024)){this.buf=e,this.len=0,this.ptr=0}_write(e){if(this.len+e>this.buf.length){let t=new Uint8Array((this.len+e)*2);t.set(this.buf),this.buf=t}return this.len+=e,this.len-e}write8(e){let t=this._write(1);this.buf[t]=e}write32(e){let t=this._write(4);_(this.buf,e,t)}write(e){let t=this._write(4+e.length);_(this.buf,e.length,t),this.buf.set(e,t+4)}_read(e){if(this.ptr+e>this.buf.length)throw Error(`Invalid packet`);return this.ptr+=e,this.ptr-e}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let e=this.read32(),t=new Uint8Array(e),n=this._read(t.length);return t.set(this.buf.subarray(n,n+e)),t}},p,m,h;if(typeof TextEncoder<`u`&&typeof TextDecoder<`u`){let e=new TextEncoder,t=new TextDecoder;p=t=>e.encode(t),m=e=>t.decode(e),h=`new TextEncoder().encode("")`}else if(typeof Buffer<`u`)p=e=>Buffer.from(e),m=e=>{let{buffer:t,byteOffset:n,byteLength:r}=e;return Buffer.from(t,n,r).toString()},h=`Buffer.from("")`;else throw Error(`No UTF-8 codec found`);if(!(p(``)instanceof Uint8Array))throw Error(`Invariant violation: "${h} instanceof Uint8Array" is incorrectly false
2
2
 
3
3
  This indicates that your JavaScript environment is broken. You cannot use
4
4
  esbuild in this environment because esbuild relies on this invariant. This
@@ -1 +1 @@
1
- import{t as e}from"./runtime-env-DadgceZk.js";import{a as t}from"./path-utils-DNJG-zQf.js";import{C as n,p as r,t as i}from"./shared-vu5AooI5.js";var a;(function(e){e.LOAD=`LOAD`,e.EXEC=`EXEC`,e.FFPROBE=`FFPROBE`,e.WRITE_FILE=`WRITE_FILE`,e.READ_FILE=`READ_FILE`,e.DELETE_FILE=`DELETE_FILE`,e.RENAME=`RENAME`,e.CREATE_DIR=`CREATE_DIR`,e.LIST_DIR=`LIST_DIR`,e.DELETE_DIR=`DELETE_DIR`,e.ERROR=`ERROR`,e.DOWNLOAD=`DOWNLOAD`,e.PROGRESS=`PROGRESS`,e.LOG=`LOG`,e.MOUNT=`MOUNT`,e.UNMOUNT=`UNMOUNT`})(a||={});const o=(()=>{let e=0;return()=>e++})(),s=Error("ffmpeg is not loaded, call `await ffmpeg.load()` first"),c=Error(`called FFmpeg.terminate()`);var l=class{#e=null;#t={};#n={};#r=[];#i=[];loaded=!1;#a=()=>{this.#e&&(this.#e.onmessage=({data:{id:e,type:t,data:n}})=>{switch(t){case a.LOAD:this.loaded=!0,this.#t[e](n);break;case a.MOUNT:case a.UNMOUNT:case a.EXEC:case a.FFPROBE:case a.WRITE_FILE:case a.READ_FILE:case a.DELETE_FILE:case a.RENAME:case a.CREATE_DIR:case a.LIST_DIR:case a.DELETE_DIR:this.#t[e](n);break;case a.LOG:this.#r.forEach(e=>e(n));break;case a.PROGRESS:this.#i.forEach(e=>e(n));break;case a.ERROR:this.#n[e](n)}delete this.#t[e],delete this.#n[e]})};#o=({type:e,data:t},n=[],r)=>this.#e?new Promise((i,a)=>{let s=o();this.#e&&this.#e.postMessage({id:s,type:e,data:t},n),this.#t[s]=i,this.#n[s]=a,r?.addEventListener(`abort`,()=>{a(new DOMException(`Message # ${s} was aborted`,`AbortError`))},{once:!0})}):Promise.reject(s);on(e,t){e===`log`?this.#r.push(t):e===`progress`&&this.#i.push(t)}off(e,t){e===`log`?this.#r=this.#r.filter(e=>e!==t):e===`progress`&&(this.#i=this.#i.filter(e=>e!==t))}load=({classWorkerURL:e,...t}={},{signal:n}={})=>(this.#e||(this.#e=e?new Worker(new URL(e,import.meta.url),{type:`module`}):new Worker(new URL(`/assets/worker-D1KsWRGg.js`,``+import.meta.url),{type:`module`}),this.#a()),this.#o({type:a.LOAD,data:t},void 0,n));exec=(e,t=-1,{signal:n}={})=>this.#o({type:a.EXEC,data:{args:e,timeout:t}},void 0,n);ffprobe=(e,t=-1,{signal:n}={})=>this.#o({type:a.FFPROBE,data:{args:e,timeout:t}},void 0,n);terminate=()=>{let e=Object.keys(this.#n);for(let t of e)this.#n[t](c),delete this.#n[t],delete this.#t[t];this.#e&&(this.#e.terminate(),this.#e=null,this.loaded=!1)};writeFile=(e,t,{signal:n}={})=>{let r=[];return t instanceof Uint8Array&&r.push(t.buffer),this.#o({type:a.WRITE_FILE,data:{path:e,data:t}},r,n)};mount=(e,t,n)=>this.#o({type:a.MOUNT,data:{fsType:e,options:t,mountPoint:n}},[]);unmount=e=>this.#o({type:a.UNMOUNT,data:{mountPoint:e}},[]);readFile=(e,t=`binary`,{signal:n}={})=>this.#o({type:a.READ_FILE,data:{path:e,encoding:t}},void 0,n);deleteFile=(e,{signal:t}={})=>this.#o({type:a.DELETE_FILE,data:{path:e}},void 0,t);rename=(e,t,{signal:n}={})=>this.#o({type:a.RENAME,data:{oldPath:e,newPath:t}},void 0,n);createDir=(e,{signal:t}={})=>this.#o({type:a.CREATE_DIR,data:{path:e}},void 0,t);listDir=(e,{signal:t}={})=>this.#o({type:a.LIST_DIR,data:{path:e}},void 0,t);deleteDir=(e,{signal:t}={})=>this.#o({type:a.DELETE_DIR,data:{path:e}},void 0,t)},u;(function(e){e.MEMFS=`MEMFS`,e.NODEFS=`NODEFS`,e.NODERAWFS=`NODERAWFS`,e.IDBFS=`IDBFS`,e.WORKERFS=`WORKERFS`,e.PROXYFS=`PROXYFS`})(u||={});const d=`0.12.10`,f=`@ffmpeg/core is not installed in node_modules: run \`${i} @ffmpeg/core@${d}\` (no network fallback)`,p=`@ffmpeg/core-mt`,m=`@ffmpeg/core-mt is not installed in node_modules (FFMPEG_CORE=mt asked for the multi-threaded core): run \`${i} ${p}@${d}\`, or unset FFMPEG_CORE and run \`${i} @ffmpeg/core@${d}\` (no network fallback)`;function h(){return globalThis.crossOriginIsolated===!0}function g(e=!1){return e&&h()?m:f}function _(e,t=h(),n=typeof navigator<`u`?navigator.hardwareConcurrency:void 0){let r=`${e.pkg} ${d}`;return e.pkg===`@ffmpeg/core-mt`?`${r} (multi-threaded${typeof n==`number`&&n>0?`, ${n} threads`:``}; single-input jobs only)`:t?`${r} (single-threaded; the multi-threaded core is opt-in on this isolated runtime: \`${i} ${p}@${d}\` then FFMPEG_CORE=mt, single-input jobs only)`:`${r} (single-threaded; runtime is not cross-origin isolated)`}const v=[`dist/esm`];async function y(e,t,n){for(let r of v){let i=`${e}/${r}`,a={core:`${i}/ffmpeg-core.js`,wasm:`${i}/ffmpeg-core.wasm`,worker:t===`@ffmpeg/core-mt`?`${i}/ffmpeg-core.worker.js`:null};if(await n.exists(a.core)&&await n.exists(a.wasm)&&!(a.worker&&!await n.exists(a.worker)))return a}return null}let b=null,x=null,S=[],C=null;function w(){return C}function T(e){for(let t of e)try{URL.revokeObjectURL(t)}catch{}}async function E(e={}){return b||=D(e.onProgress,e.ipk,e.preferMt===!0).catch(e=>{throw b=null,e}),b}async function D(e,t,n){let r=e??(()=>{}),i=new l,a=await A(t,r,n),o=[a.coreURL,a.wasmURL,a.workerURL,a.classWorkerURL].filter(e=>typeof e==`string`);r(`initializing ffmpeg-core...`);try{await i.load({coreURL:a.coreURL,wasmURL:a.wasmURL,...a.workerURL?{workerURL:a.workerURL}:{},...a.classWorkerURL?{classWorkerURL:a.classWorkerURL}:{}})}catch(e){throw T(o),e}return r(`ffmpeg ready`),x=i,S=o,C=a.pkg,i}async function O(e,r,i=!1){if(r===void 0)return k(e,i&&h());let a;try{a=await n(`${r}/package.json`,e.fromDir,e.reader)}catch{return null}if(a.type!==`file`)return null;let o=await y(t(a.path).dir,r,e.reader);if(!o)return null;try{let t=await e.reader.readFile(o.core),n=await e.readBytes(o.wasm),i=o.worker?await e.reader.readFile(o.worker):void 0;return{pkg:r,coreSource:t,wasmBytes:n,...i===void 0?{}:{workerSource:i}}}catch{return null}}async function k(e,t){if(t){let t=await O(e,p);if(t)return t}return O(e,`@ffmpeg/core`)}async function A(e,t,n){if(r())throw Error(`ffmpeg-wasm is not available in Node runtime`);let i=n&&h();if(!e)throw Error(g(i));let a=await k(e,i);if(!a)throw Error(g(i));t(`${a.pkg} loaded from ipk node_modules (js: ${a.coreSource.length} chars, wasm: ${a.wasmBytes.byteLength} bytes${a.workerSource?`, multi-threaded`:``})`);let o=j(a.wasmBytes,`application/wasm`);return{pkg:a.pkg,coreURL:M(a.coreSource,`text/javascript`),wasmURL:o,...a.workerSource===void 0?{}:{workerURL:M(a.workerSource,`text/javascript`)}}}function j(e,t){let n=new ArrayBuffer(e.byteLength);return new Uint8Array(n).set(e),URL.createObjectURL(new Blob([n],{type:t}))}function M(e,t){return URL.createObjectURL(new Blob([e],{type:t}))}function N(e){if(typeof WebAssembly<`u`&&e instanceof WebAssembly.RuntimeError||e instanceof RangeError)return!0;let t=e instanceof Error?e.message:String(e);return/RuntimeError|memory access out of bounds|unreachable|Aborted|out of memory|allocation failed|table index is out of bounds|function signature mismatch/i.test(t)}function P(e){if(e!==void 0&&x!==e)return;let t=x,n=S;if(b=null,x=null,S=[],C=null,t)try{t.terminate()}catch{}T(n)}function F(){return e()}function I(e){return{bytes:B(e.bytesBase64),mimeType:e.mimeType??`application/octet-stream`,width:e.width??0,height:e.height??0,...typeof e.durationMs==`number`?{durationMs:e.durationMs}:{}}}async function L(t,n={}){if(!e())throw Error(`media capture popup requires the extension runtime`);let r=n.timeoutMs??3e5,i=R(),a=z(JSON.stringify({...t,requestId:i})),o=chrome.runtime.getURL(`capture-popup.html?req=${a}`);return await new Promise((e,t)=>{let n=!1,a=()=>{if(!n){n=!0,clearTimeout(c);try{chrome.runtime.onMessage.removeListener(s)}catch{}}},s=n=>{let r=n;if(r?.source===`capture-popup`&&r.requestId===i){if(a(),r.ok&&r.bytesBase64!==void 0)try{e(I(r))}catch(e){t(e instanceof Error?e:Error(String(e)))}else t(Error(r.error||`media capture failed`))}},c=setTimeout(()=>{try{chrome.runtime.sendMessage({target:`capture-popup`,type:`capture-abort`,requestId:i})}catch{}a(),t(Error(`media capture timed out waiting for the capture window`))},r);chrome.runtime.onMessage.addListener(s);try{chrome.runtime.sendMessage({type:`capture-open-window`,url:o,requestId:i})}catch(e){a(),t(e instanceof Error?e:Error(String(e)))}})}function R(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`cap-${crypto.randomUUID()}`:`cap-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function z(e){let t=new TextEncoder().encode(e),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,e+r));return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function B(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}export{_ as a,N as c,O as d,p as i,w as l,F as n,g as o,d as r,E as s,L as t,P as u};
1
+ import{t as e}from"./runtime-env-DadgceZk.js";import{a as t}from"./path-utils-DNJG-zQf.js";import{C as n,p as r,t as i}from"./shared-pVZLJOGO.js";var a;(function(e){e.LOAD=`LOAD`,e.EXEC=`EXEC`,e.FFPROBE=`FFPROBE`,e.WRITE_FILE=`WRITE_FILE`,e.READ_FILE=`READ_FILE`,e.DELETE_FILE=`DELETE_FILE`,e.RENAME=`RENAME`,e.CREATE_DIR=`CREATE_DIR`,e.LIST_DIR=`LIST_DIR`,e.DELETE_DIR=`DELETE_DIR`,e.ERROR=`ERROR`,e.DOWNLOAD=`DOWNLOAD`,e.PROGRESS=`PROGRESS`,e.LOG=`LOG`,e.MOUNT=`MOUNT`,e.UNMOUNT=`UNMOUNT`})(a||={});const o=(()=>{let e=0;return()=>e++})(),s=Error("ffmpeg is not loaded, call `await ffmpeg.load()` first"),c=Error(`called FFmpeg.terminate()`);var l=class{#e=null;#t={};#n={};#r=[];#i=[];loaded=!1;#a=()=>{this.#e&&(this.#e.onmessage=({data:{id:e,type:t,data:n}})=>{switch(t){case a.LOAD:this.loaded=!0,this.#t[e](n);break;case a.MOUNT:case a.UNMOUNT:case a.EXEC:case a.FFPROBE:case a.WRITE_FILE:case a.READ_FILE:case a.DELETE_FILE:case a.RENAME:case a.CREATE_DIR:case a.LIST_DIR:case a.DELETE_DIR:this.#t[e](n);break;case a.LOG:this.#r.forEach(e=>e(n));break;case a.PROGRESS:this.#i.forEach(e=>e(n));break;case a.ERROR:this.#n[e](n)}delete this.#t[e],delete this.#n[e]})};#o=({type:e,data:t},n=[],r)=>this.#e?new Promise((i,a)=>{let s=o();this.#e&&this.#e.postMessage({id:s,type:e,data:t},n),this.#t[s]=i,this.#n[s]=a,r?.addEventListener(`abort`,()=>{a(new DOMException(`Message # ${s} was aborted`,`AbortError`))},{once:!0})}):Promise.reject(s);on(e,t){e===`log`?this.#r.push(t):e===`progress`&&this.#i.push(t)}off(e,t){e===`log`?this.#r=this.#r.filter(e=>e!==t):e===`progress`&&(this.#i=this.#i.filter(e=>e!==t))}load=({classWorkerURL:e,...t}={},{signal:n}={})=>(this.#e||(this.#e=e?new Worker(new URL(e,import.meta.url),{type:`module`}):new Worker(new URL(`/assets/worker-D1KsWRGg.js`,``+import.meta.url),{type:`module`}),this.#a()),this.#o({type:a.LOAD,data:t},void 0,n));exec=(e,t=-1,{signal:n}={})=>this.#o({type:a.EXEC,data:{args:e,timeout:t}},void 0,n);ffprobe=(e,t=-1,{signal:n}={})=>this.#o({type:a.FFPROBE,data:{args:e,timeout:t}},void 0,n);terminate=()=>{let e=Object.keys(this.#n);for(let t of e)this.#n[t](c),delete this.#n[t],delete this.#t[t];this.#e&&(this.#e.terminate(),this.#e=null,this.loaded=!1)};writeFile=(e,t,{signal:n}={})=>{let r=[];return t instanceof Uint8Array&&r.push(t.buffer),this.#o({type:a.WRITE_FILE,data:{path:e,data:t}},r,n)};mount=(e,t,n)=>this.#o({type:a.MOUNT,data:{fsType:e,options:t,mountPoint:n}},[]);unmount=e=>this.#o({type:a.UNMOUNT,data:{mountPoint:e}},[]);readFile=(e,t=`binary`,{signal:n}={})=>this.#o({type:a.READ_FILE,data:{path:e,encoding:t}},void 0,n);deleteFile=(e,{signal:t}={})=>this.#o({type:a.DELETE_FILE,data:{path:e}},void 0,t);rename=(e,t,{signal:n}={})=>this.#o({type:a.RENAME,data:{oldPath:e,newPath:t}},void 0,n);createDir=(e,{signal:t}={})=>this.#o({type:a.CREATE_DIR,data:{path:e}},void 0,t);listDir=(e,{signal:t}={})=>this.#o({type:a.LIST_DIR,data:{path:e}},void 0,t);deleteDir=(e,{signal:t}={})=>this.#o({type:a.DELETE_DIR,data:{path:e}},void 0,t)},u;(function(e){e.MEMFS=`MEMFS`,e.NODEFS=`NODEFS`,e.NODERAWFS=`NODERAWFS`,e.IDBFS=`IDBFS`,e.WORKERFS=`WORKERFS`,e.PROXYFS=`PROXYFS`})(u||={});const d=`0.12.10`,f=`@ffmpeg/core is not installed in node_modules: run \`${i} @ffmpeg/core@${d}\` (no network fallback)`,p=`@ffmpeg/core-mt`,m=`@ffmpeg/core-mt is not installed in node_modules (FFMPEG_CORE=mt asked for the multi-threaded core): run \`${i} ${p}@${d}\`, or unset FFMPEG_CORE and run \`${i} @ffmpeg/core@${d}\` (no network fallback)`;function h(){return globalThis.crossOriginIsolated===!0}function g(e=!1){return e&&h()?m:f}function _(e,t=h(),n=typeof navigator<`u`?navigator.hardwareConcurrency:void 0){let r=`${e.pkg} ${d}`;return e.pkg===`@ffmpeg/core-mt`?`${r} (multi-threaded${typeof n==`number`&&n>0?`, ${n} threads`:``}; single-input jobs only)`:t?`${r} (single-threaded; the multi-threaded core is opt-in on this isolated runtime: \`${i} ${p}@${d}\` then FFMPEG_CORE=mt, single-input jobs only)`:`${r} (single-threaded; runtime is not cross-origin isolated)`}const v=[`dist/esm`];async function y(e,t,n){for(let r of v){let i=`${e}/${r}`,a={core:`${i}/ffmpeg-core.js`,wasm:`${i}/ffmpeg-core.wasm`,worker:t===`@ffmpeg/core-mt`?`${i}/ffmpeg-core.worker.js`:null};if(await n.exists(a.core)&&await n.exists(a.wasm)&&!(a.worker&&!await n.exists(a.worker)))return a}return null}let b=null,x=null,S=[],C=null;function w(){return C}function T(e){for(let t of e)try{URL.revokeObjectURL(t)}catch{}}async function E(e={}){return b||=D(e.onProgress,e.ipk,e.preferMt===!0).catch(e=>{throw b=null,e}),b}async function D(e,t,n){let r=e??(()=>{}),i=new l,a=await A(t,r,n),o=[a.coreURL,a.wasmURL,a.workerURL,a.classWorkerURL].filter(e=>typeof e==`string`);r(`initializing ffmpeg-core...`);try{await i.load({coreURL:a.coreURL,wasmURL:a.wasmURL,...a.workerURL?{workerURL:a.workerURL}:{},...a.classWorkerURL?{classWorkerURL:a.classWorkerURL}:{}})}catch(e){throw T(o),e}return r(`ffmpeg ready`),x=i,S=o,C=a.pkg,i}async function O(e,r,i=!1){if(r===void 0)return k(e,i&&h());let a;try{a=await n(`${r}/package.json`,e.fromDir,e.reader)}catch{return null}if(a.type!==`file`)return null;let o=await y(t(a.path).dir,r,e.reader);if(!o)return null;try{let t=await e.reader.readFile(o.core),n=await e.readBytes(o.wasm),i=o.worker?await e.reader.readFile(o.worker):void 0;return{pkg:r,coreSource:t,wasmBytes:n,...i===void 0?{}:{workerSource:i}}}catch{return null}}async function k(e,t){if(t){let t=await O(e,p);if(t)return t}return O(e,`@ffmpeg/core`)}async function A(e,t,n){if(r())throw Error(`ffmpeg-wasm is not available in Node runtime`);let i=n&&h();if(!e)throw Error(g(i));let a=await k(e,i);if(!a)throw Error(g(i));t(`${a.pkg} loaded from ipk node_modules (js: ${a.coreSource.length} chars, wasm: ${a.wasmBytes.byteLength} bytes${a.workerSource?`, multi-threaded`:``})`);let o=j(a.wasmBytes,`application/wasm`);return{pkg:a.pkg,coreURL:M(a.coreSource,`text/javascript`),wasmURL:o,...a.workerSource===void 0?{}:{workerURL:M(a.workerSource,`text/javascript`)}}}function j(e,t){let n=new ArrayBuffer(e.byteLength);return new Uint8Array(n).set(e),URL.createObjectURL(new Blob([n],{type:t}))}function M(e,t){return URL.createObjectURL(new Blob([e],{type:t}))}function N(e){if(typeof WebAssembly<`u`&&e instanceof WebAssembly.RuntimeError||e instanceof RangeError)return!0;let t=e instanceof Error?e.message:String(e);return/RuntimeError|memory access out of bounds|unreachable|Aborted|out of memory|allocation failed|table index is out of bounds|function signature mismatch/i.test(t)}function P(e){if(e!==void 0&&x!==e)return;let t=x,n=S;if(b=null,x=null,S=[],C=null,t)try{t.terminate()}catch{}T(n)}function F(){return e()}function I(e){return{bytes:B(e.bytesBase64),mimeType:e.mimeType??`application/octet-stream`,width:e.width??0,height:e.height??0,...typeof e.durationMs==`number`?{durationMs:e.durationMs}:{}}}async function L(t,n={}){if(!e())throw Error(`media capture popup requires the extension runtime`);let r=n.timeoutMs??3e5,i=R(),a=z(JSON.stringify({...t,requestId:i})),o=chrome.runtime.getURL(`capture-popup.html?req=${a}`);return await new Promise((e,t)=>{let n=!1,a=()=>{if(!n){n=!0,clearTimeout(c);try{chrome.runtime.onMessage.removeListener(s)}catch{}}},s=n=>{let r=n;if(r?.source===`capture-popup`&&r.requestId===i){if(a(),r.ok&&r.bytesBase64!==void 0)try{e(I(r))}catch(e){t(e instanceof Error?e:Error(String(e)))}else t(Error(r.error||`media capture failed`))}},c=setTimeout(()=>{try{chrome.runtime.sendMessage({target:`capture-popup`,type:`capture-abort`,requestId:i})}catch{}a(),t(Error(`media capture timed out waiting for the capture window`))},r);chrome.runtime.onMessage.addListener(s);try{chrome.runtime.sendMessage({type:`capture-open-window`,url:o,requestId:i})}catch(e){a(),t(e instanceof Error?e:Error(String(e)))}})}function R(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`cap-${crypto.randomUUID()}`:`cap-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function z(e){let t=new TextEncoder().encode(e),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,e+r));return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function B(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}export{_ as a,N as c,O as d,p as i,w as l,F as n,g as o,d as r,E as s,L as t,P as u};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{n as s,t as c}from"./types-Dgm4REV3.js";import{i as l,r as u,t as d}from"./mount-index-D9w_zMSm.js";import{a as f,i as p,n as m,t as h}from"./mount-table-store-DrF_Ifaz.js";import{n as g,t as _}from"./virtual-device-paths-CS5o4QVz.js";import{i as v,r as y,t as b}from"./sidecar-repair-CIHuOk7H.js";function x(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function S(e,t){try{return await e(t)}catch{return t}}async function*C(e,t,n,r=0){let a=i(t);if(x(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(r>64||o.size>=1e5)return;let s=await S(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*w(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*w(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*T(e,n,r,i);return}yield*C(e,n,r,i)}async function*T(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*C(e,t,n,r))}catch{}}const E=t(`fs-watcher`);let D=0;function O(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var k=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++D}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),E.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),E.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>O(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){E.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),E.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const A=new TextEncoder,j=new TextDecoder(`utf-8`,{fatal:!1});var M=class{entries=new Map;static handles(e){return g(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?A.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?j.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return j.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new c(`ENOENT`,`no such file or directory`,t);return n}};const N={[_]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},P=[`/tmp/`];var F=class{ephemeralFds=new M;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;includeMounts;constructor(e,t,n=[],r=`hard`,a={}){this.vfs=e;let o=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(o),this.readOnlyPrefixes=n.map(o),this.writeEnforcement=r,this.includeMounts=a.includeMounts!==!1}getAllPrefixes(){let e=this.includeMounts?this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`):[];return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...P]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return[...this.allowedPrefixes,...P].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return M.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new c(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new c(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof c?t:new c(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new c(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=N[i(e)];if(n)return n.read(t);if(M.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readFileRange(e,t,n){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFileRange(r,t,n)}async getNativeFile(e){if(N[i(e)]||M.handles(e)||!this.isAllowedStrict(e))return null;try{let t=await this.resolveAndCheckRead(e);return await this.vfs.getNativeFile(t)}catch{return null}}async readDir(e,t){if(!this.isAllowed(e))return[];let n=e;if(this.isAllowedStrict(e))try{n=await this.resolveAndCheckRead(e)}catch{return[]}let r=await this.vfs.readDir(n,t);if(!this.isAllowedStrict(e)){let t=i(e);return r.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return r}async stat(e){let t=N[i(e)];if(t)return t.stat();if(M.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=N[i(e)];return t?t.stat():M.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=N[i(e)];return t?t.stat():M.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=i(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){if(M.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new c(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(N[i(e)])return!0;if(M.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=N[i(e)];if(t)return t.readText();if(M.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=N[i(e)];if(r){r.write(t);return}if(M.handles(e)){this.ephemeralFds.write(e,t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(M.handles(e))throw new c(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(M.handles(e)){if(!this.ephemeralFds.remove(e))throw new c(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(M.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(M.handles(t)){if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=N[i(e)];if(t)return t.stat();if(M.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new c(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new c(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new c(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new c(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){let e=this.vfs.listMounts();return this.includeMounts?e:e.filter(e=>this.isAllowedStrict(e))}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function I(e,t){if(e instanceof c){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new c(e.code,r,t)}throw e}const L=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function R(e,t){if(e instanceof c)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new c(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(L.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new c(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new c(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new c(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new c(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new c(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new c(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new c(`ELOOP`,`too many levels of symbolic links`,t):new c(`EINVAL`,r,t)}function z(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function B(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function V(e){let t=e?.mode;return typeof t==`number`?t:void 0}function H(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=z(V(r));o!==z(V(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function U(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(r===void 0)return null;try{let t=e;for(let e of n)t=await t.getDirectoryHandle(e);return await(await t.getFileHandle(r)).getFile()}catch{return null}}async function W(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=R(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function G(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw R(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function K(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await W(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new c(`ELOOP`,`too many symbolic links encountered`,i);o=await G(e,o,i)}}async function q(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await K(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function J(e,t,n){return t(n)?n:q(e,t,n)}function Y(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function X(e,t){let n=e.kind===`directory`?`directory`:`file`;return t?{name:e.name,type:n,...e.size===void 0?{}:{size:e.size},...e.lastModified===void 0?{}:{mtime:e.lastModified},...e.ctime===void 0?{}:{ctime:e.ctime},...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}:{name:e.name,type:n}}function Z(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var Q=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new d;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(t,n,r){let i=n??await e.acquireOpfsHandle(t.dbName,r);await t.withWriteLock(()=>e.seedOpfsMetadataSidecarIfMissing(i));let[a,{WebAccess:o}]=await Promise.all([import(`./dist-v35W6TZp.js`).then(e=>e.t),import(`./dist-B9-e6K9J.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=()=>a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:r,repairOpfsMetadataSidecar:l}=await import(`./sidecar-repair-CIHuOk7H.js`).then(e=>e.n);try{let e=await t.withWriteLock(()=>l(i,t.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let u=await r(n,()=>t.withWriteLock(()=>l(i,t.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{a.mount(s,u)}catch{}c={backendFs:u,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-v35W6TZp.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(t){let n=`.metadata.json`;try{let r=await t.getFileHandle(n);if(e.isUsableMetadataDocument(await e.readSidecarText(r)))return;console.warn(`[virtual-fs] metadata sidecar is unparseable (torn write?); reseeding an empty index`)}catch(e){if(e?.name!==`NotFoundError`)throw e}let r=await(await t.getFileHandle(n,{create:!0})).createWritable(),i=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await r.write(i),await r.close()}static async readSidecarText(e){let t;for(let n=0;n<3;n++)try{return await(await e.getFile()).text()}catch(e){if(e?.name!==`NotReadableError`)throw e;t=e}throw t}static isUsableMetadataDocument(e){let t;try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!=`object`)return!1;let n=t.entries;return!!n&&typeof n==`object`}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new c(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??Y(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,r&&await h().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=y(e,r,i))}let o=JSON.stringify(v(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=H(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=b(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,r=`path`){if(this.backend!==`opfs`)return;let a=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(t);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await b(n)(a),s=z(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=B(o,s),d=B(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new c(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-v35W6TZp.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push(a===`symlink`?{name:i,type:a}:{name:i,type:a,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},mode:t.mode})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;if(t===`/`)try{let e=r.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new c(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new c(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new c(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??u(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=Z(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:s,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await f(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await p(t)}catch{}}async reconstructBackendFromDescriptor(e,t){switch(e.kind){case`local`:{let t=await m(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return l.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:n}=await import(`./backend-hostfs-BxfjZHzO.js`);return new n({targetPath:t,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-WtleT3fD.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r(e.profile)})}case`da`:{let{DaMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-WtleT3fD.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}case`aem`:{let{AemMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-WtleT3fD.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}getMountBackend(e){let t=i(e);return this.mountPoints.get(t)??null}async mountInternal(e,t){let r=i(e);if(this.mountPoints.has(r))throw new c(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new c(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=i(e),r=this.mountPoints.get(n);if(!r)throw new c(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,u(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){I(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw R(e,n)}}async readFileRange(e,t,n){let r=i(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<t)throw new c(`EINVAL`,`invalid byte range ${t}-${n}`,r);if(t===n)return new Uint8Array;let a=this.findMount(r),o=a?.backend.readFileRange;if(a&&o){if(a.relParts.length===0)throw new c(`EISDIR`,`is a directory`,r);try{return await o.call(a.backend,a.relParts.join(`/`),t,n)}catch(e){I(e,r)}}let s=await this.readFile(r,{encoding:`binary`});return new Uint8Array(s.subarray(t,Math.min(n,s.byteLength)))}async getNativeFile(e){let t=i(e),n=this.findMount(t);if(n){let e=n.backend.getNativeFile;if(!e||n.relParts.length===0)return null;try{return await e.call(n.backend,n.relParts.join(`/`))}catch{return null}}let r=this.opfsHandle;if(!r)return null;try{return await U(r,await this.resolveSymlinks(t))}catch{return null}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new c(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){I(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let l=!1;try{await this.lfs.stat(s),l=!0}catch{}let{dir:u}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(s,t)}catch(e){throw R(e,a)}}else throw R(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw R(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e,t){let n=i(e),r=this.findMount(n);return r?this.readDirMounted(n,r,t):this.readDirLocal(n)}async readDirMounted(e,t,n){let r=n?.includeStats===!0?void 0:this.mountIndex.getDirectoryEntries(t.path,e);if(r!==void 0){let t=new Map;for(let e of r)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let i=t.relParts.join(`/`)||`/`,a;try{a=await t.backend.readDir(i,n)}catch(t){I(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,X(e,s));return this.addNestedMountEntries(o,e),[...o.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw R(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},mode:e.mode}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw R(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new c(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof c&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){I(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw R(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.ctime??t.mtime,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},...t.mode===void 0?{}:{mode:t.mode}}}catch(e){I(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*C({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new c(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw R(e,r)}}else throw R(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw R(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async realpath(e){return q(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return J(this.lfs,e=>this.findMount(e)!==null,e)}},$=e({FsError:()=>c,FsWatcher:()=>k,MountIndex:()=>d,RestrictedFS:()=>F,VirtualFS:()=>Q,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>Y,splitPath:()=>n,statsFromDirEntry:()=>s});export{k as i,Q as n,F as r,$ as t};
1
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{n as s,t as c}from"./types-Dgm4REV3.js";import{i as l,r as u,t as d}from"./mount-index-D9w_zMSm.js";import{a as f,i as p,n as m,t as h}from"./mount-table-store-DrF_Ifaz.js";import{n as g,t as _}from"./virtual-device-paths-CS5o4QVz.js";import{i as v,r as y,t as b}from"./sidecar-repair-CIHuOk7H.js";function x(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function S(e,t){try{return await e(t)}catch{return t}}async function*C(e,t,n,r=0){let a=i(t);if(x(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(r>64||o.size>=1e5)return;let s=await S(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*w(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*w(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*T(e,n,r,i);return}yield*C(e,n,r,i)}async function*T(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*C(e,t,n,r))}catch{}}const E=t(`fs-watcher`);let D=0;function O(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var k=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++D}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),E.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),E.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>O(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){E.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),E.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const A=new TextEncoder,j=new TextDecoder(`utf-8`,{fatal:!1});var M=class{entries=new Map;static handles(e){return g(i(e))}has(e){return this.entries.has(i(e))}write(e,t){let n=i(e),r=typeof t==`string`?A.encode(t):new Uint8Array(t),a=Date.now(),o=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:a,ctime:o?.ctime??a})}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?j.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return j.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(i(e))}require(e){let t=i(e),n=this.entries.get(t);if(!n)throw new c(`ENOENT`,`no such file or directory`,t);return n}};const N={[_]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},P=[`/tmp/`];var F=class{ephemeralFds=new M;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;includeMounts;constructor(e,t,n=[],r=`hard`,a={}){this.vfs=e;let o=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(o),this.readOnlyPrefixes=n.map(o),this.writeEnforcement=r,this.includeMounts=a.includeMounts!==!1}getAllPrefixes(){let e=this.includeMounts?this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`):[];return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...P]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return[...this.allowedPrefixes,...P].some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return M.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new c(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new c(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof c?t:new c(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new c(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=N[i(e)];if(n)return n.read(t);if(M.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readFileRange(e,t,n){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFileRange(r,t,n)}async getNativeFile(e){if(N[i(e)]||M.handles(e)||!this.isAllowedStrict(e))return null;try{let t=await this.resolveAndCheckRead(e);return await this.vfs.getNativeFile(t)}catch{return null}}async readDir(e,t){if(!this.isAllowed(e))return[];let n=e;if(this.isAllowedStrict(e))try{n=await this.resolveAndCheckRead(e)}catch{return[]}let r=await this.vfs.readDir(n,t);if(!this.isAllowedStrict(e)){let t=i(e);return r.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return r}async stat(e){let t=N[i(e)];if(t)return t.stat();if(M.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=N[i(e)];return t?t.stat():M.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=N[i(e)];return t?t.stat():M.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=i(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){if(M.handles(e)){let t=i(e);if(!this.ephemeralFds.has(t))throw new c(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(N[i(e)])return!0;if(M.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=N[i(e)];if(t)return t.readText();if(M.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=N[i(e)];if(r){r.write(t);return}if(M.handles(e)){this.ephemeralFds.write(e,t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}refuseDescriptorTreeOp(e){if(M.handles(e))throw new c(`EACCES`,`permission denied`,i(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(M.handles(e)){if(!this.ephemeralFds.remove(e))throw new c(`ENOENT`,`no such file or directory`,i(e));return}this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(M.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(M.handles(t)){if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.refuseDescriptorTreeOp(t),this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=N[i(e)];if(t)return t.stat();if(M.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new c(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new c(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new c(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new c(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){let e=this.vfs.listMounts();return this.includeMounts?e:e.filter(e=>this.isAllowedStrict(e))}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function I(e,t){if(e instanceof c){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new c(e.code,r,t)}throw e}const L=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EIO`];function R(e,t){if(e instanceof c)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new c(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(L.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new c(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new c(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new c(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new c(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new c(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new c(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new c(`ELOOP`,`too many levels of symbolic links`,t):new c(`EINVAL`,r,t)}function z(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function B(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function V(e){let t=e?.mode;return typeof t==`number`?t:void 0}function H(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=z(V(r));o!==z(V(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function U(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(r===void 0)return null;try{let t=e;for(let e of n)t=await t.getDirectoryHandle(e);return await(await t.getFileHandle(r)).getFile()}catch{return null}}async function W(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=R(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function G(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw R(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function K(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await W(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new c(`ELOOP`,`too many symbolic links encountered`,i);o=await G(e,o,i)}}async function q(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await K(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function J(e,t,n){return t(n)?n:q(e,t,n)}function Y(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}function X(e,t){let n=e.kind===`directory`?`directory`:`file`;return t?{name:e.name,type:n,...e.size===void 0?{}:{size:e.size},...e.lastModified===void 0?{}:{mtime:e.lastModified},...e.ctime===void 0?{}:{ctime:e.ctime},...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}:{name:e.name,type:n}}function Z(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}var Q=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new d;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a){if(this.dbName=t,this.onRepairProgress=a,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?e.initOpfsBackend(this,i,n===!0):e.initMemoryBackend(this,t,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${t}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r,n).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(t,n,r){let i=n??await e.acquireOpfsHandle(t.dbName,r);await t.withWriteLock(()=>e.seedOpfsMetadataSidecarIfMissing(i));let[a,{WebAccess:o}]=await Promise.all([import(`./dist-v35W6TZp.js`).then(e=>e.t),import(`./dist-B9-e6K9J.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=()=>a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:r,repairOpfsMetadataSidecar:l}=await import(`./sidecar-repair-CIHuOk7H.js`).then(e=>e.n);try{let e=await t.withWriteLock(()=>l(i,t.onRepairProgress));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped})}catch{}let u=await r(n,()=>t.withWriteLock(()=>l(i,t.onRepairProgress)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,nlinksFixed:e.nlinksFixed,selfEntryDropped:e.selfEntryDropped}));try{a.mount(s,u)}catch{}c={backendFs:u,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-v35W6TZp.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(t){let n=`.metadata.json`;try{let r=await t.getFileHandle(n);if(e.isUsableMetadataDocument(await e.readSidecarText(r)))return;console.warn(`[virtual-fs] metadata sidecar is unparseable (torn write?); reseeding an empty index`)}catch(e){if(e?.name!==`NotFoundError`)throw e}let r=await(await t.getFileHandle(n,{create:!0})).createWritable(),i=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await r.write(i),await r.close()}static async readSidecarText(e){let t;for(let n=0;n<3;n++)try{return await(await e.getFile()).text()}catch(e){if(e?.name!==`NotReadableError`)throw e;t=e}throw t}static isUsableMetadataDocument(e){let t;try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!=`object`)return!1;let n=t.entries;return!!n&&typeof n==`object`}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new c(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??Y(),a=new e(n,r,i,void 0,t?.onRepairProgress);return await a._ready,r&&await h().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=y(e,r,i))}let o=JSON.stringify(v(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=H(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=b(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,r=`path`){if(this.backend!==`opfs`)return;let a=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(t);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await b(n)(a),s=z(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=B(o,s),d=B(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new c(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-v35W6TZp.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push(a===`symlink`?{name:i,type:a}:{name:i,type:a,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},mode:t.mode})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;if(t===`/`)try{let e=r.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;if(t===`/`)return this.statSync(t);try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r,ino:e.ino}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new c(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new c(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new c(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=r?.limits??u(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=Z(t,a);try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}if(this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:a,descriptor:s,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await f(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await p(t)}catch{}}async reconstructBackendFromDescriptor(e,t){switch(e.kind){case`local`:{let t=await m(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return l.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:n}=await import(`./backend-hostfs-BxfjZHzO.js`);return new n({targetPath:t,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-BlGkBXLX.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r(e.profile)})}case`da`:{let{DaMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-BlGkBXLX.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}case`aem`:{let{AemMountBackend:t,RemoteMountCache:n,makeSignedFetchDa:r}=await import(`./mount-BlGkBXLX.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}getMountBackend(e){let t=i(e);return this.mountPoints.get(t)??null}async mountInternal(e,t){let r=i(e);if(this.mountPoints.has(r))throw new c(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new c(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=i(e),r=this.mountPoints.get(n);if(!r)throw new c(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,u(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){I(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw R(e,n)}}async readFileRange(e,t,n){let r=i(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<t)throw new c(`EINVAL`,`invalid byte range ${t}-${n}`,r);if(t===n)return new Uint8Array;let a=this.findMount(r),o=a?.backend.readFileRange;if(a&&o){if(a.relParts.length===0)throw new c(`EISDIR`,`is a directory`,r);try{return await o.call(a.backend,a.relParts.join(`/`),t,n)}catch(e){I(e,r)}}let s=await this.readFile(r,{encoding:`binary`});return new Uint8Array(s.subarray(t,Math.min(n,s.byteLength)))}async getNativeFile(e){let t=i(e),n=this.findMount(t);if(n){let e=n.backend.getNativeFile;if(!e||n.relParts.length===0)return null;try{return await e.call(n.backend,n.relParts.join(`/`))}catch{return null}}let r=this.opfsHandle;if(!r)return null;try{return await U(r,await this.resolveSymlinks(t))}catch{return null}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new c(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){I(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let l=!1;try{await this.lfs.stat(s),l=!0}catch{}let{dir:u}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(s,t)}catch(e){throw R(e,a)}}else throw R(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw R(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e,t){let n=i(e),r=this.findMount(n);return r?this.readDirMounted(n,r,t):this.readDirLocal(n)}async readDirMounted(e,t,n){let r=n?.includeStats===!0?void 0:this.mountIndex.getDirectoryEntries(t.path,e);if(r!==void 0){let t=new Map;for(let e of r)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let i=t.relParts.join(`/`)||`/`,a;try{a=await t.backend.readDir(i,n)}catch(t){I(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,X(e,s));return this.addNestedMountEntries(o,e),[...o.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw R(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,...e.ino===void 0?{}:{ino:e.ino},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},mode:e.mode}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);!i||i.includes(`/`)||e.has(i)||e.set(i,{name:i,type:`directory`})}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw R(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new c(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof c&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){I(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw R(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.ctime??t.mtime,...t.ino===void 0?{}:{ino:t.ino},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},...t.mode===void 0?{}:{mode:t.mode}}}catch(e){I(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}let o=this.findMount(n);if(o?.backend.rename){let e=this.findMount(r);if(e&&e.backend===o.backend){try{await o.backend.rename(o.relParts.join(`/`),e.relParts.join(`/`))}catch(e){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r);return}}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*C({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new c(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw R(e,r)}}else throw R(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw R(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t)||t===`/`)return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw R(e,t)}}async realpath(e){return q(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return J(this.lfs,e=>this.findMount(e)!==null,e)}},$=e({FsError:()=>c,FsWatcher:()=>k,MountIndex:()=>d,RestrictedFS:()=>F,VirtualFS:()=>Q,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>Y,splitPath:()=>n,statsFromDirEntry:()=>s});export{k as i,Q as n,F as r,$ as t};