sliccy 5.84.0 → 5.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/dist/ui/assets/{account-store-DqOwEqPJ.js → account-store-Cl38jIN3.js} +1 -1
  2. package/dist/ui/assets/account-store-uZBiyCfC.js +101 -0
  3. package/dist/ui/assets/{adobe-DpUgMhMf.js → adobe-BRZiyGHt.js} +1 -1
  4. package/dist/ui/assets/{adobe-DGx3DYwC.js → adobe-CT-UsXZV.js} +1 -1
  5. package/dist/ui/assets/{apps-DVTVcvIV.js → apps-D0rkU7aR.js} +1 -1
  6. package/dist/ui/assets/{azure-openai-VvV3bfKn.js → azure-openai-CCPcd0Zz.js} +1 -1
  7. package/dist/ui/assets/{azure-openai-CvlKI0gI.js → azure-openai-Dz5p5R6j.js} +1 -1
  8. package/dist/ui/assets/{cdp-BvZO3XX0.js → cdp-BEmpfM7z.js} +3 -3
  9. package/dist/ui/assets/{cerebras-CJvtnPux.js → cerebras-B4jWV7B2.js} +1 -1
  10. package/dist/ui/assets/{cerebras-yb140WKQ.js → cerebras-b62QozG2.js} +1 -1
  11. package/dist/ui/assets/{connect-surface-DCr_sst4.js → connect-surface-BxEHN4gI.js} +1 -1
  12. package/dist/ui/assets/{fs-DHqCcha5.js → fs-C7Mt0maU.js} +2 -2
  13. package/dist/ui/assets/{fs-C3EYD3qT.js → fs-CQ25L4dA.js} +1 -1
  14. package/dist/ui/assets/{github-D03OPP_K.js → github-BYlDqXpn.js} +2 -2
  15. package/dist/ui/assets/{github-C1llen91.js → github-DahxKpAX.js} +1 -1
  16. package/dist/ui/assets/{github-copilot-5U2E9Vz_.js → github-copilot-DPE6uejC.js} +1 -1
  17. package/dist/ui/assets/{github-copilot-BOslP0sZ.js → github-copilot-kmzW6ouH.js} +1 -1
  18. package/dist/ui/assets/{kernel-worker-BNnqnIh-.js → kernel-worker-uFfrR9ir.js} +437 -434
  19. package/dist/ui/assets/{local-llm-DF_UaKBw.js → local-llm-DN1xgkKk.js} +1 -1
  20. package/dist/ui/assets/{local-llm-Dmd1MYay.js → local-llm-MsccM8G4.js} +1 -1
  21. package/dist/ui/assets/{main-OC7WLZIp.js → main-B10kZ_Ob.js} +3 -3
  22. package/dist/ui/assets/{main-cherry-CQ53lnqT.js → main-cherry-DCIO_2RP.js} +1 -1
  23. package/dist/ui/assets/{mount-BGLX5HYy.js → mount-DMj9lhpQ.js} +2 -2
  24. package/dist/ui/assets/{mount-DqW1EKLo.js → mount-DnOOuthV.js} +1 -1
  25. package/dist/ui/assets/{mount-recovery-EGuo4xHy.js → mount-recovery-C-ZLNXnx.js} +1 -1
  26. package/dist/ui/assets/{new-session-DeRaLfZJ.js → new-session-Bs_C1R2_.js} +2 -2
  27. package/dist/ui/assets/{oauth-bootstrap-BTv4hjuO.js → oauth-bootstrap-sCoftFUR.js} +2 -2
  28. package/dist/ui/assets/{openai-codex-DeSSYpyV.js → openai-codex-BatsqjVw.js} +1 -1
  29. package/dist/ui/assets/{openai-codex-0z7ugfds.js → openai-codex-DC9sfUHh.js} +1 -1
  30. package/dist/ui/assets/{openrouter-DmXu0orK.js → openrouter-D0j2IDaO.js} +1 -1
  31. package/dist/ui/assets/{openrouter-B684-YNV.js → openrouter-LemIswHz.js} +1 -1
  32. package/dist/ui/assets/{openrouter-oauth-4TQRhnJc.js → openrouter-oauth-B3f2WK2Z.js} +1 -1
  33. package/dist/ui/assets/{openrouter-oauth-B50WslGj.js → openrouter-oauth-BTRApFnw.js} +1 -1
  34. package/dist/ui/assets/{panel-rpc-handlers-89YhWuM8.js → panel-rpc-handlers-6LpO_FVl.js} +2 -2
  35. package/dist/ui/assets/{provider-Bi-hjlEX.js → provider-0VWOzm_p.js} +1 -1
  36. package/dist/ui/assets/{provider-oUC8vFQ5.js → provider-g6b9Kka8.js} +2 -2
  37. package/dist/ui/assets/{provider-settings-CzdPoa2L.js → provider-settings-5ZSUhS4X.js} +1 -1
  38. package/dist/ui/assets/{provider-settings-_PFHVGxB.js → provider-settings-CfhqyIyK.js} +1 -1
  39. package/dist/ui/assets/provider-store-access-1f-jNcnn.js +1 -0
  40. package/dist/ui/assets/{provider-store-access-BbYdUswr.js → provider-store-access-Bf-m4VVO.js} +2 -2
  41. package/dist/ui/assets/{providers-K_nrbRE6.js → providers-B4d7o0sL.js} +1 -1
  42. package/dist/ui/assets/{providers-Bq7zW4Gk.js → providers-C3QccIn1.js} +2 -2
  43. package/dist/ui/assets/{quick-llm-Dl7XIpey.js → quick-llm-BdPuR9YE.js} +1 -1
  44. package/dist/ui/assets/{session-freezer-BlEQaK0W.js → session-freezer-xprWWf7C.js} +2 -2
  45. package/dist/ui/assets/{setup-standalone-prelude-KH8G_LfB.js → setup-standalone-prelude-C8f1oX0w.js} +2 -2
  46. package/dist/ui/assets/{setup-sudo-krlb-y3i.js → setup-sudo-B9Ylt90j.js} +2 -2
  47. package/dist/ui/assets/{skills-CTb4NuXP.js → skills-BViuGAGa.js} +1 -1
  48. package/dist/ui/assets/{store--D7lWwZR.js → store-BHybUTO2.js} +1 -1
  49. package/dist/ui/assets/{sudo-QRrN7GP8.js → sudo-B_AcSXZk.js} +1 -1
  50. package/dist/ui/assets/synthetic-cdp-transport-CtfKyiws.js +1 -0
  51. package/dist/ui/assets/{upgrade-detection-e_modEZG.js → upgrade-detection-DBzqUQvq.js} +1 -1
  52. package/dist/ui/assets/{wc-extension-x68wh_S1.js → wc-extension-xlXuU7Ah.js} +2 -2
  53. package/dist/ui/assets/wc-floatbar-online-B6M0vf6K.js +5 -0
  54. package/dist/ui/assets/{wc-follower-DP6y1rn1.js → wc-follower-22gyIeMl.js} +3 -3
  55. package/dist/ui/assets/{wc-live-Ca_Pupdm.js → wc-live-Bzt-INQF.js} +3 -3
  56. package/dist/ui/assets/{wc-nav-BgXT_vJ8.js → wc-nav-B1Y-W-TA.js} +2 -2
  57. package/dist/ui/assets/{wc-onboarding-CMTrRNAb.js → wc-onboarding-C2m3Ngqf.js} +2 -2
  58. package/dist/ui/assets/{wc-placeholder-D0-hD2IZ.js → wc-placeholder-Coq_jyXk.js} +2 -2
  59. package/dist/ui/assets/{wc-settings-DUy4cLvW.js → wc-settings-fUJr1K7Q.js} +2 -2
  60. package/dist/ui/assets/{wc-shell-Fq-OIqlc.js → wc-shell-BKqeBMFY.js} +2 -2
  61. package/dist/ui/assets/{wc-sprinkles-1kb8khRN.js → wc-sprinkles-XFBEV_K6.js} +2 -2
  62. package/dist/ui/assets/wc-tray-CbpLz35a.js +2 -0
  63. package/dist/ui/assets/{xai-grok-BRS79NT7.js → xai-grok-DMMAcuyp.js} +1 -1
  64. package/dist/ui/assets/{xai-grok-CmlbtRNX.js → xai-grok-DVGV8-BT.js} +1 -1
  65. package/dist/ui/index.html +6 -6
  66. package/dist/ui/packages/webapp/index.html +6 -6
  67. package/package.json +1 -1
  68. package/dist/ui/assets/account-store-CJ9KAeuF.js +0 -101
  69. package/dist/ui/assets/provider-store-access-Dcw79llI.js +0 -1
  70. package/dist/ui/assets/synthetic-cdp-transport-DLIt5SkY.js +0 -1
  71. package/dist/ui/assets/wc-floatbar-online-0Dg_sFmu.js +0 -5
  72. package/dist/ui/assets/wc-tray-BhkmdnRe.js +0 -2
@@ -1,4 +1,4 @@
1
- import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./types-idfTVsM8.js";import{t as n}from"./global-db-DvmmimLY.js";const r=e(`mcp-apps`),i=`/workspace/.mcp/sprinkles`;async function a(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-C3EYD3qT.js`).then(e=>e.t);return await t.create({dbName:n})}function o(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64)||`app`}function s(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function c(e,t){let n=s(t.title??t.name),r=t.description?s(t.description):``,i=s(t.templateUri??`about:blank`),a=JSON.stringify(e),o=JSON.stringify(t.name);return`<div class="mcp-app" data-sprinkle-title="${n}" style="display:flex;flex-direction:column;height:100%;min-height:0;">
1
+ import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./types-idfTVsM8.js";import{t as n}from"./global-db-DvmmimLY.js";const r=e(`mcp-apps`),i=`/workspace/.mcp/sprinkles`;async function a(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-CQ25L4dA.js`).then(e=>e.t);return await t.create({dbName:n})}function o(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,64)||`app`}function s(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function c(e,t){let n=s(t.title??t.name),r=t.description?s(t.description):``,i=s(t.templateUri??`about:blank`),a=JSON.stringify(e),o=JSON.stringify(t.name);return`<div class="mcp-app" data-sprinkle-title="${n}" style="display:flex;flex-direction:column;height:100%;min-height:0;">
2
2
  <header class="mcp-app__header" style="padding:8px 12px;border-bottom:1px solid var(--s2-border-subtle,#3a3a3a);">
3
3
  <h2 style="font-size:14px;font-weight:600;margin:0;">${n}</h2>${r?`\n <p style="font-size:12px;margin:4px 0 0;color:var(--s2-content-secondary,#a0a0a0);">${r}</p>`:``}
4
4
  </header>
@@ -1 +1 @@
1
- import{b as e,g as t}from"./account-store-CJ9KAeuF.js";import{n}from"./event-stream-qbAZIAKV.js";import{o as r,r as i,t as a}from"./transform-messages-Bp94o3FD.js";import{p as o}from"./bedrock-camp-BO4bvAKs.js";import{t as s}from"./openai-CmTnPr9N.js";const c=`azure-openai`,l=`2024-12-01-preview`,u={id:c,name:`Azure OpenAI`,description:`GPT models via Azure AI Foundry`,requiresApiKey:!0,apiKeyPlaceholder:`Azure API key`,apiKeyEnvVar:`AZURE_OPENAI_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`https://your-resource.cognitiveservices.azure.com/`,baseUrlDescription:`Azure resource endpoint`,requiresDeployment:!0,deploymentPlaceholder:`gpt-4.1-mini, gpt-4o, o4-mini`,deploymentDescription:`Comma-separated deployment names (from Azure Portal → Deployments)`,requiresApiVersion:!0,apiVersionDefault:l,apiVersionDescription:`Azure OpenAI API version`,getModelIds:()=>{let t=e(c);if(!t)return[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}];let n=t.split(`,`).map(e=>e.trim()).filter(Boolean);return n.length===0?[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}]:n.map(e=>{let t=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`);return{id:e,name:`${e} (Azure)`,reasoning:t,input:[`text`,`image`]}})}};function d(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function f(e,t){let n=a(e.messages,t,d),r=[];for(let e of n)if(e.role===`user`)if(typeof e.content==`string`)r.push({role:`user`,content:e.content});else{let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text??``}:e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`text`,text:JSON.stringify(e)});r.push({role:`user`,content:t})}else if(e.role===`assistant`){let t=e.content,n=t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i=t.filter(e=>e.type===`toolCall`).map(e=>({id:e.id??``,type:`function`,function:{name:e.name??``,arguments:JSON.stringify(e.arguments??{})}}));i.length?r.push({role:`assistant`,content:n||null,tool_calls:i}):r.push({role:`assistant`,content:n})}else if(e.role===`toolResult`){let t=e.content;r.push({role:`tool`,tool_call_id:e.toolCallId??``,content:t?.map(e=>e.type===`text`?e.text??``:JSON.stringify(e)).join(``)||``})}return r}function p(e){if(e?.length)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function m(e){let t=e.content.find(e=>e.type===`text`);if(t)return{block:t,index:e.content.indexOf(t)};let n={type:`text`,text:``};return e.content.push(n),{block:n,index:e.content.length-1}}function h(e,t){return e.content.find(e=>e.type===`toolCall`&&e.id===t)}function g(e){return{role:`assistant`,content:[],api:`azure-openai-anthropic`,provider:c,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:`stop`,timestamp:Date.now()}}function _(e,n){let r=n.apiKey;if(!r)throw Error(`Azure API key is required`);let i=e.baseUrl;if(!i)throw Error(`Azure endpoint is required`);let a={};e.headers&&Object.assign(a,e.headers),n.headers&&Object.assign(a,n.headers);let o=t(c)||l,u=e.id;return{client:new s({endpoint:i.replace(/\/+$/,``),apiKey:r,deployment:u,apiVersion:o,dangerouslyAllowBrowser:!0,defaultHeaders:a}),deployment:u}}function v(e,t){return[...e.systemPrompt?[{role:`system`,content:e.systemPrompt}]:[],...f(e,t)]}function y(e,t,n){n&&(e.usage.input=n.prompt_tokens??0,e.usage.output=n.completion_tokens??0,e.usage.totalTokens=n.total_tokens??0,r(t,e.usage))}function b(e){return e===`tool_calls`?`toolUse`:e===`length`?`length`:`stop`}function x(e,t,n){let{block:r,index:i}=m(t);r.text===``&&e.push({type:`text_start`,contentIndex:i,partial:t}),r.text+=n,e.push({type:`text_delta`,contentIndex:i,delta:n,partial:t})}function S(e,t,n){let r=n.id?h(t,n.id):void 0;if(r||!n.id)return r;let i={type:`toolCall`,id:n.id,name:n.function?.name??``,arguments:{},_partialJson:``};return t.content.push(i),e.push({type:`toolcall_start`,contentIndex:t.content.length-1,partial:t}),i}function C(e,t,n,r){n._partialJson+=r;try{n.arguments=JSON.parse(n._partialJson)}catch{}e.push({type:`toolcall_delta`,contentIndex:t.content.indexOf(n),delta:r,partial:t})}function w(e,t,n){for(let r of n){let n=S(e,t,r);n&&r.function?.arguments&&C(e,t,n,r.function.arguments)}}function T(e,t,n){let r=n.delta;r&&(r.content&&x(e,t,r.content),r.tool_calls&&w(e,t,r.tool_calls),n.finish_reason&&(t.stopReason=b(n.finish_reason)))}function E(e,t,n,r){try{n.arguments=JSON.parse(n._partialJson||`{}`)}catch{}delete n._partialJson,e.push({type:`toolcall_end`,contentIndex:r,toolCall:n,partial:t})}function D(e,t){for(let n=0;n<t.content.length;n+=1){let r=t.content[n];r.type===`toolCall`?E(e,t,r,n):r.type===`text`&&e.push({type:`text_end`,contentIndex:n,content:r.text,partial:t})}}async function O(e,t,n,r,i){let{client:a,deployment:o}=_(n,i),s=p(r.tools),c=await a.chat.completions.create({model:o,messages:v(r,n),stream:!0,stream_options:{include_usage:!0},...i.maxTokens?{max_completion_tokens:i.maxTokens}:{},...i.temperature===void 0?{}:{temperature:i.temperature},...s?{tools:s}:{}});e.push({type:`start`,partial:t});for await(let r of c){y(t,n,r.usage);for(let n of r.choices??[])T(e,t,n)}D(e,t),e.push({type:`done`,reason:t.stopReason,message:t}),e.end()}function k(e,t,n,r){t.stopReason=r?`aborted`:`error`,t.errorMessage=n instanceof Error?n.message:JSON.stringify(n),e.push({type:`error`,reason:t.stopReason,error:t}),e.end()}const A=(e,t,r={})=>{let i=n(),a=g(e);return O(i,a,e,t,r).catch(e=>{k(i,a,e,!!r.signal?.aborted)}),i},j=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`Azure API key is required`);let a=i(e,n,r);return A(e,t,{...a})};function M(){o({api:`azure-openai-anthropic`,stream:A,streamSimple:j})}export{u as config,M as register};
1
+ import{b as e,g as t}from"./account-store-uZBiyCfC.js";import{n}from"./event-stream-qbAZIAKV.js";import{o as r,r as i,t as a}from"./transform-messages-Bp94o3FD.js";import{p as o}from"./bedrock-camp-BO4bvAKs.js";import{t as s}from"./openai-CmTnPr9N.js";const c=`azure-openai`,l=`2024-12-01-preview`,u={id:c,name:`Azure OpenAI`,description:`GPT models via Azure AI Foundry`,requiresApiKey:!0,apiKeyPlaceholder:`Azure API key`,apiKeyEnvVar:`AZURE_OPENAI_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`https://your-resource.cognitiveservices.azure.com/`,baseUrlDescription:`Azure resource endpoint`,requiresDeployment:!0,deploymentPlaceholder:`gpt-4.1-mini, gpt-4o, o4-mini`,deploymentDescription:`Comma-separated deployment names (from Azure Portal → Deployments)`,requiresApiVersion:!0,apiVersionDefault:l,apiVersionDescription:`Azure OpenAI API version`,getModelIds:()=>{let t=e(c);if(!t)return[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}];let n=t.split(`,`).map(e=>e.trim()).filter(Boolean);return n.length===0?[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}]:n.map(e=>{let t=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`);return{id:e,name:`${e} (Azure)`,reasoning:t,input:[`text`,`image`]}})}};function d(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function f(e,t){let n=a(e.messages,t,d),r=[];for(let e of n)if(e.role===`user`)if(typeof e.content==`string`)r.push({role:`user`,content:e.content});else{let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text??``}:e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`text`,text:JSON.stringify(e)});r.push({role:`user`,content:t})}else if(e.role===`assistant`){let t=e.content,n=t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i=t.filter(e=>e.type===`toolCall`).map(e=>({id:e.id??``,type:`function`,function:{name:e.name??``,arguments:JSON.stringify(e.arguments??{})}}));i.length?r.push({role:`assistant`,content:n||null,tool_calls:i}):r.push({role:`assistant`,content:n})}else if(e.role===`toolResult`){let t=e.content;r.push({role:`tool`,tool_call_id:e.toolCallId??``,content:t?.map(e=>e.type===`text`?e.text??``:JSON.stringify(e)).join(``)||``})}return r}function p(e){if(e?.length)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function m(e){let t=e.content.find(e=>e.type===`text`);if(t)return{block:t,index:e.content.indexOf(t)};let n={type:`text`,text:``};return e.content.push(n),{block:n,index:e.content.length-1}}function h(e,t){return e.content.find(e=>e.type===`toolCall`&&e.id===t)}function g(e){return{role:`assistant`,content:[],api:`azure-openai-anthropic`,provider:c,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:`stop`,timestamp:Date.now()}}function _(e,n){let r=n.apiKey;if(!r)throw Error(`Azure API key is required`);let i=e.baseUrl;if(!i)throw Error(`Azure endpoint is required`);let a={};e.headers&&Object.assign(a,e.headers),n.headers&&Object.assign(a,n.headers);let o=t(c)||l,u=e.id;return{client:new s({endpoint:i.replace(/\/+$/,``),apiKey:r,deployment:u,apiVersion:o,dangerouslyAllowBrowser:!0,defaultHeaders:a}),deployment:u}}function v(e,t){return[...e.systemPrompt?[{role:`system`,content:e.systemPrompt}]:[],...f(e,t)]}function y(e,t,n){n&&(e.usage.input=n.prompt_tokens??0,e.usage.output=n.completion_tokens??0,e.usage.totalTokens=n.total_tokens??0,r(t,e.usage))}function b(e){return e===`tool_calls`?`toolUse`:e===`length`?`length`:`stop`}function x(e,t,n){let{block:r,index:i}=m(t);r.text===``&&e.push({type:`text_start`,contentIndex:i,partial:t}),r.text+=n,e.push({type:`text_delta`,contentIndex:i,delta:n,partial:t})}function S(e,t,n){let r=n.id?h(t,n.id):void 0;if(r||!n.id)return r;let i={type:`toolCall`,id:n.id,name:n.function?.name??``,arguments:{},_partialJson:``};return t.content.push(i),e.push({type:`toolcall_start`,contentIndex:t.content.length-1,partial:t}),i}function C(e,t,n,r){n._partialJson+=r;try{n.arguments=JSON.parse(n._partialJson)}catch{}e.push({type:`toolcall_delta`,contentIndex:t.content.indexOf(n),delta:r,partial:t})}function w(e,t,n){for(let r of n){let n=S(e,t,r);n&&r.function?.arguments&&C(e,t,n,r.function.arguments)}}function T(e,t,n){let r=n.delta;r&&(r.content&&x(e,t,r.content),r.tool_calls&&w(e,t,r.tool_calls),n.finish_reason&&(t.stopReason=b(n.finish_reason)))}function E(e,t,n,r){try{n.arguments=JSON.parse(n._partialJson||`{}`)}catch{}delete n._partialJson,e.push({type:`toolcall_end`,contentIndex:r,toolCall:n,partial:t})}function D(e,t){for(let n=0;n<t.content.length;n+=1){let r=t.content[n];r.type===`toolCall`?E(e,t,r,n):r.type===`text`&&e.push({type:`text_end`,contentIndex:n,content:r.text,partial:t})}}async function O(e,t,n,r,i){let{client:a,deployment:o}=_(n,i),s=p(r.tools),c=await a.chat.completions.create({model:o,messages:v(r,n),stream:!0,stream_options:{include_usage:!0},...i.maxTokens?{max_completion_tokens:i.maxTokens}:{},...i.temperature===void 0?{}:{temperature:i.temperature},...s?{tools:s}:{}});e.push({type:`start`,partial:t});for await(let r of c){y(t,n,r.usage);for(let n of r.choices??[])T(e,t,n)}D(e,t),e.push({type:`done`,reason:t.stopReason,message:t}),e.end()}function k(e,t,n,r){t.stopReason=r?`aborted`:`error`,t.errorMessage=n instanceof Error?n.message:JSON.stringify(n),e.push({type:`error`,reason:t.stopReason,error:t}),e.end()}const A=(e,t,r={})=>{let i=n(),a=g(e);return O(i,a,e,t,r).catch(e=>{k(i,a,e,!!r.signal?.aborted)}),i},j=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`Azure API key is required`);let a=i(e,n,r);return A(e,t,{...a})};function M(){o({api:`azure-openai-anthropic`,stream:A,streamSimple:j})}export{u as config,M as register};
@@ -1 +1 @@
1
- import{b as e,g as t}from"./account-store-DqOwEqPJ.js";import{n}from"./event-stream-qbAZIAKV.js";import{t as r}from"./models-Bnh9VDA1.js";import{a as i}from"./compat-aVSWLlYQ.js";import{r as a,t as o}from"./transform-messages-wECJwtH0.js";import{t as s}from"./openai-BxFF4GUL.js";var c=`azure-openai`,l=`2024-12-01-preview`,u={id:c,name:`Azure OpenAI`,description:`GPT models via Azure AI Foundry`,requiresApiKey:!0,apiKeyPlaceholder:`Azure API key`,apiKeyEnvVar:`AZURE_OPENAI_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`https://your-resource.cognitiveservices.azure.com/`,baseUrlDescription:`Azure resource endpoint`,requiresDeployment:!0,deploymentPlaceholder:`gpt-4.1-mini, gpt-4o, o4-mini`,deploymentDescription:`Comma-separated deployment names (from Azure Portal → Deployments)`,requiresApiVersion:!0,apiVersionDefault:l,apiVersionDescription:`Azure OpenAI API version`,getModelIds:()=>{let t=e(c);if(!t)return[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}];let n=t.split(`,`).map(e=>e.trim()).filter(Boolean);return n.length===0?[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}]:n.map(e=>{let t=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`);return{id:e,name:`${e} (Azure)`,reasoning:t,input:[`text`,`image`]}})}};function d(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function f(e,t){let n=o(e.messages,t,d),r=[];for(let e of n)if(e.role===`user`)if(typeof e.content==`string`)r.push({role:`user`,content:e.content});else{let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text??``}:e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`text`,text:JSON.stringify(e)});r.push({role:`user`,content:t})}else if(e.role===`assistant`){let t=e.content,n=t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i=t.filter(e=>e.type===`toolCall`).map(e=>({id:e.id??``,type:`function`,function:{name:e.name??``,arguments:JSON.stringify(e.arguments??{})}}));i.length?r.push({role:`assistant`,content:n||null,tool_calls:i}):r.push({role:`assistant`,content:n})}else if(e.role===`toolResult`){let t=e.content;r.push({role:`tool`,tool_call_id:e.toolCallId??``,content:t?.map(e=>e.type===`text`?e.text??``:JSON.stringify(e)).join(``)||``})}return r}function p(e){if(e?.length)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function m(e){let t=e.content.find(e=>e.type===`text`);if(t)return{block:t,index:e.content.indexOf(t)};let n={type:`text`,text:``};return e.content.push(n),{block:n,index:e.content.length-1}}function h(e,t){return e.content.find(e=>e.type===`toolCall`&&e.id===t)}function g(e){return{role:`assistant`,content:[],api:`azure-openai-anthropic`,provider:c,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:`stop`,timestamp:Date.now()}}function _(e,n){let r=n.apiKey;if(!r)throw Error(`Azure API key is required`);let i=e.baseUrl;if(!i)throw Error(`Azure endpoint is required`);let a={};e.headers&&Object.assign(a,e.headers),n.headers&&Object.assign(a,n.headers);let o=t(c)||l,u=e.id;return{client:new s({endpoint:i.replace(/\/+$/,``),apiKey:r,deployment:u,apiVersion:o,dangerouslyAllowBrowser:!0,defaultHeaders:a}),deployment:u}}function v(e,t){return[...e.systemPrompt?[{role:`system`,content:e.systemPrompt}]:[],...f(e,t)]}function y(e,t,n){n&&(e.usage.input=n.prompt_tokens??0,e.usage.output=n.completion_tokens??0,e.usage.totalTokens=n.total_tokens??0,r(t,e.usage))}function b(e){return e===`tool_calls`?`toolUse`:e===`length`?`length`:`stop`}function x(e,t,n){let{block:r,index:i}=m(t);r.text===``&&e.push({type:`text_start`,contentIndex:i,partial:t}),r.text+=n,e.push({type:`text_delta`,contentIndex:i,delta:n,partial:t})}function S(e,t,n){let r=n.id?h(t,n.id):void 0;if(r||!n.id)return r;let i={type:`toolCall`,id:n.id,name:n.function?.name??``,arguments:{},_partialJson:``};return t.content.push(i),e.push({type:`toolcall_start`,contentIndex:t.content.length-1,partial:t}),i}function C(e,t,n,r){n._partialJson+=r;try{n.arguments=JSON.parse(n._partialJson)}catch{}e.push({type:`toolcall_delta`,contentIndex:t.content.indexOf(n),delta:r,partial:t})}function w(e,t,n){for(let r of n){let n=S(e,t,r);n&&r.function?.arguments&&C(e,t,n,r.function.arguments)}}function T(e,t,n){let r=n.delta;r&&(r.content&&x(e,t,r.content),r.tool_calls&&w(e,t,r.tool_calls),n.finish_reason&&(t.stopReason=b(n.finish_reason)))}function E(e,t,n,r){try{n.arguments=JSON.parse(n._partialJson||`{}`)}catch{}delete n._partialJson,e.push({type:`toolcall_end`,contentIndex:r,toolCall:n,partial:t})}function D(e,t){for(let n=0;n<t.content.length;n+=1){let r=t.content[n];r.type===`toolCall`?E(e,t,r,n):r.type===`text`&&e.push({type:`text_end`,contentIndex:n,content:r.text,partial:t})}}async function O(e,t,n,r,i){let{client:a,deployment:o}=_(n,i),s=p(r.tools),c=await a.chat.completions.create({model:o,messages:v(r,n),stream:!0,stream_options:{include_usage:!0},...i.maxTokens?{max_completion_tokens:i.maxTokens}:{},...i.temperature===void 0?{}:{temperature:i.temperature},...s?{tools:s}:{}});e.push({type:`start`,partial:t});for await(let r of c){y(t,n,r.usage);for(let n of r.choices??[])T(e,t,n)}D(e,t),e.push({type:`done`,reason:t.stopReason,message:t}),e.end()}function k(e,t,n,r){t.stopReason=r?`aborted`:`error`,t.errorMessage=n instanceof Error?n.message:JSON.stringify(n),e.push({type:`error`,reason:t.stopReason,error:t}),e.end()}var A=(e,t,r={})=>{let i=n(),a=g(e);return O(i,a,e,t,r).catch(e=>{k(i,a,e,!!r.signal?.aborted)}),i},j=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`Azure API key is required`);return A(e,t,{...a(e,n,r)})};function M(){i({api:`azure-openai-anthropic`,stream:A,streamSimple:j})}export{u as config,M as register};
1
+ import{b as e,g as t}from"./account-store-Cl38jIN3.js";import{n}from"./event-stream-qbAZIAKV.js";import{t as r}from"./models-Bnh9VDA1.js";import{a as i}from"./compat-aVSWLlYQ.js";import{r as a,t as o}from"./transform-messages-wECJwtH0.js";import{t as s}from"./openai-BxFF4GUL.js";var c=`azure-openai`,l=`2024-12-01-preview`,u={id:c,name:`Azure OpenAI`,description:`GPT models via Azure AI Foundry`,requiresApiKey:!0,apiKeyPlaceholder:`Azure API key`,apiKeyEnvVar:`AZURE_OPENAI_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`https://your-resource.cognitiveservices.azure.com/`,baseUrlDescription:`Azure resource endpoint`,requiresDeployment:!0,deploymentPlaceholder:`gpt-4.1-mini, gpt-4o, o4-mini`,deploymentDescription:`Comma-separated deployment names (from Azure Portal → Deployments)`,requiresApiVersion:!0,apiVersionDefault:l,apiVersionDescription:`Azure OpenAI API version`,getModelIds:()=>{let t=e(c);if(!t)return[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}];let n=t.split(`,`).map(e=>e.trim()).filter(Boolean);return n.length===0?[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}]:n.map(e=>{let t=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`);return{id:e,name:`${e} (Azure)`,reasoning:t,input:[`text`,`image`]}})}};function d(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function f(e,t){let n=o(e.messages,t,d),r=[];for(let e of n)if(e.role===`user`)if(typeof e.content==`string`)r.push({role:`user`,content:e.content});else{let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text??``}:e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`text`,text:JSON.stringify(e)});r.push({role:`user`,content:t})}else if(e.role===`assistant`){let t=e.content,n=t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i=t.filter(e=>e.type===`toolCall`).map(e=>({id:e.id??``,type:`function`,function:{name:e.name??``,arguments:JSON.stringify(e.arguments??{})}}));i.length?r.push({role:`assistant`,content:n||null,tool_calls:i}):r.push({role:`assistant`,content:n})}else if(e.role===`toolResult`){let t=e.content;r.push({role:`tool`,tool_call_id:e.toolCallId??``,content:t?.map(e=>e.type===`text`?e.text??``:JSON.stringify(e)).join(``)||``})}return r}function p(e){if(e?.length)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function m(e){let t=e.content.find(e=>e.type===`text`);if(t)return{block:t,index:e.content.indexOf(t)};let n={type:`text`,text:``};return e.content.push(n),{block:n,index:e.content.length-1}}function h(e,t){return e.content.find(e=>e.type===`toolCall`&&e.id===t)}function g(e){return{role:`assistant`,content:[],api:`azure-openai-anthropic`,provider:c,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:`stop`,timestamp:Date.now()}}function _(e,n){let r=n.apiKey;if(!r)throw Error(`Azure API key is required`);let i=e.baseUrl;if(!i)throw Error(`Azure endpoint is required`);let a={};e.headers&&Object.assign(a,e.headers),n.headers&&Object.assign(a,n.headers);let o=t(c)||l,u=e.id;return{client:new s({endpoint:i.replace(/\/+$/,``),apiKey:r,deployment:u,apiVersion:o,dangerouslyAllowBrowser:!0,defaultHeaders:a}),deployment:u}}function v(e,t){return[...e.systemPrompt?[{role:`system`,content:e.systemPrompt}]:[],...f(e,t)]}function y(e,t,n){n&&(e.usage.input=n.prompt_tokens??0,e.usage.output=n.completion_tokens??0,e.usage.totalTokens=n.total_tokens??0,r(t,e.usage))}function b(e){return e===`tool_calls`?`toolUse`:e===`length`?`length`:`stop`}function x(e,t,n){let{block:r,index:i}=m(t);r.text===``&&e.push({type:`text_start`,contentIndex:i,partial:t}),r.text+=n,e.push({type:`text_delta`,contentIndex:i,delta:n,partial:t})}function S(e,t,n){let r=n.id?h(t,n.id):void 0;if(r||!n.id)return r;let i={type:`toolCall`,id:n.id,name:n.function?.name??``,arguments:{},_partialJson:``};return t.content.push(i),e.push({type:`toolcall_start`,contentIndex:t.content.length-1,partial:t}),i}function C(e,t,n,r){n._partialJson+=r;try{n.arguments=JSON.parse(n._partialJson)}catch{}e.push({type:`toolcall_delta`,contentIndex:t.content.indexOf(n),delta:r,partial:t})}function w(e,t,n){for(let r of n){let n=S(e,t,r);n&&r.function?.arguments&&C(e,t,n,r.function.arguments)}}function T(e,t,n){let r=n.delta;r&&(r.content&&x(e,t,r.content),r.tool_calls&&w(e,t,r.tool_calls),n.finish_reason&&(t.stopReason=b(n.finish_reason)))}function E(e,t,n,r){try{n.arguments=JSON.parse(n._partialJson||`{}`)}catch{}delete n._partialJson,e.push({type:`toolcall_end`,contentIndex:r,toolCall:n,partial:t})}function D(e,t){for(let n=0;n<t.content.length;n+=1){let r=t.content[n];r.type===`toolCall`?E(e,t,r,n):r.type===`text`&&e.push({type:`text_end`,contentIndex:n,content:r.text,partial:t})}}async function O(e,t,n,r,i){let{client:a,deployment:o}=_(n,i),s=p(r.tools),c=await a.chat.completions.create({model:o,messages:v(r,n),stream:!0,stream_options:{include_usage:!0},...i.maxTokens?{max_completion_tokens:i.maxTokens}:{},...i.temperature===void 0?{}:{temperature:i.temperature},...s?{tools:s}:{}});e.push({type:`start`,partial:t});for await(let r of c){y(t,n,r.usage);for(let n of r.choices??[])T(e,t,n)}D(e,t),e.push({type:`done`,reason:t.stopReason,message:t}),e.end()}function k(e,t,n,r){t.stopReason=r?`aborted`:`error`,t.errorMessage=n instanceof Error?n.message:JSON.stringify(n),e.push({type:`error`,reason:t.stopReason,error:t}),e.end()}var A=(e,t,r={})=>{let i=n(),a=g(e);return O(i,a,e,t,r).catch(e=>{k(i,a,e,!!r.signal?.aborted)}),i},j=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`Azure API key is required`);return A(e,t,{...a(e,n,r)})};function M(){i({api:`azure-openai-anthropic`,stream:A,streamSimple:j})}export{u as config,M as register};
@@ -868,12 +868,12 @@ import{t as e}from"./logger-DDBAeTLF.js";import"./navigation-watcher-DkN9hU8i.js
868
868
  } catch(e) {
869
869
  return { role: 'RootWebArea', name: '', description: 'Error: ' + (e.message || String(e)) };
870
870
  }
871
- })()`;function a(e,t=``){if(e==null)return t;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);try{return JSON.stringify(e)??t}catch{return String(e)}}function o(e){try{let t=atob(e.slice(0,48));return(t.charCodeAt(16)<<24|t.charCodeAt(17)<<16|t.charCodeAt(18)<<8|t.charCodeAt(19))>>>0}catch{return 0}}var s=`ws://localhost:5710/cdp`,c=e(`browser-api`);function l(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:s}var u=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;_frameContextCache=new Map;_tabLock=Promise.resolve();_onSessionChange;_lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;handleJavaScriptDialogOpening=async e=>{let t=typeof e.sessionId==`string`?e.sessionId:this.sessionId;if(t)try{await this.client.send(`Page.handleJavaScriptDialog`,{accept:!1},t,5e3),c.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){c.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}};constructor(e){this.client=e??new r,this.localClient=this.client,this.addDialogListener(this.client)}getTransport(){return this.client}setSessionChangeCallback(e){this._onSessionChange=e}getSessionId(){return this.sessionId}getAttachedTargetId(){return this.attachedTargetId}async withTab(e,t){let n,r=new Promise(e=>{n=e}),i=this._tabLock;this._tabLock=r,await i;try{return await t(await this.attachToPage(e))}finally{n()}}setTrayTargetProvider(e){this.trayTargetProvider=e}async listAllTargets(){let e=await this.listPages();if(!this.trayTargetProvider)return e;let t=!this.remoteTargetInfo,n=new Set(e.map(e=>e.targetId)),r=this.trayTargetProvider.getTargets().filter(e=>!t||!(e.runtimeId===`leader`&&n.has(e.localTargetId))).map(e=>({targetId:e.targetId,title:e.title,url:e.url,kind:e.kind,capabilities:e.capabilities}));return[...e,...r]}async connect(e){this._lastConnectOptions=e?{...e}:{},await this.client.connect({url:e?.url??l(),timeout:e?.timeout,...e?.protocols===void 0?{}:{protocols:e.protocols}}),this.supersededNotified=!1}primeConnectOptions(e){this._lastConnectOptions=e?{...e}:{}}setCdpSupersededHandler(e){this.supersededHandler=e}notifySuperseded(){if(!this.supersededNotified){this.supersededNotified=!0;try{this.supersededHandler?.()}catch{}}}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}async createRemotePage(e,t){if(!this.trayTargetProvider?.openRemoteTab)throw Error(`Remote tab opening not available (no tray target provider)`);return this.trayTargetProvider.openRemoteTab(e,t??`about:blank`)}async closePage(e){if(await this.ensureConnected(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);try{await t.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}this.attachedTargetId===e&&(this.remoteTargetInfo&&=(this.setClient(this.localClient),null),this.sessionId=null,this.attachedTargetId=null);return}}await this.localClient.send(`Target.closeTarget`,{targetId:e}),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disconnect(){this.sessionId=null,this.attachedTargetId=null,this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){if(await this.ensureConnected(),this.sessionId&&this.attachedTargetId===e)return this.sessionId;if(this._frameContextCache.clear(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);this.setClient(t),this.remoteTargetInfo={runtimeId:n,localTargetId:r};let i=await this.client.send(`Target.attachToTarget`,{targetId:r,flatten:!0});return this.sessionId=i.sessionId,this.attachedTargetId=e,await this.client.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.client),this.sessionId}}this.remoteTargetInfo&&=(this.trayTargetProvider?.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),null),await this.ensureLocalConnected();let t=await this.localClient.send(`Target.attachToTarget`,{targetId:e,flatten:!0});return this.sessionId=t.sessionId,this.attachedTargetId=e,await this.localClient.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.localClient),this.sessionId}async detach(){if(this.sessionId){try{await this.client.send(`Target.detachFromTarget`,{sessionId:this.sessionId})}catch{}this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null}}async navigate(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.enable`,{},this.sessionId);let t=this.client.once(`Page.loadEventFired`);await this.client.send(`Page.navigate`,{url:e},this.sessionId),await t}async bringToFront(){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.bringToFront`,{},this.sessionId??void 0)}async screenshot(e){await this.ensureConnected(),this.ensureAttached();try{let t={format:e?.format??`png`,captureBeyondViewport:!!(e?.clip||e?.fullPage)};if(e?.quality!==void 0&&(t.quality=e.quality),e?.clip||e?.fullPage){let n=0,r=0;try{await this.client.send(`Runtime.enable`,{},this.sessionId);let e=await this.client.send(`Runtime.evaluate`,{expression:`JSON.stringify({ w: window.innerWidth, h: document.documentElement.scrollHeight })`,returnByValue:!0},this.sessionId),t=JSON.parse(e.result?.value??`{}`);n=t.w??0,r=t.h??0}catch(e){c.warn(`fullPage: failed to evaluate scroll dimensions, falling back to viewport`,e)}e?.clip?t.clip={...e.clip,scale:e.clip.scale??1}:t.clip={x:0,y:0,width:n||1280,height:r||800,scale:1}}let n;try{n=await this.client.send(`Page.captureScreenshot`,t,this.sessionId)}catch(r){if(e?.foregroundFallback===!1)throw r;await this.client.send(`Page.bringToFront`,{},this.sessionId),n=await this.client.send(`Page.captureScreenshot`,t,this.sessionId)}let r=n.data;return e?.maxWidth&&(r=await this._applyMaxWidth(r,e.maxWidth,t)),r}finally{}}async _applyMaxWidth(e,t,n){let r=o(e);if(!r||r<=t)return e;let i=t/r,a=n.clip;if(a)a.scale=i;else{let e=1280,t=800;try{await this.client.send(`Runtime.enable`,{},this.sessionId);let n=await this.client.send(`Runtime.evaluate`,{expression:`JSON.stringify({w:window.innerWidth,h:window.innerHeight})`,returnByValue:!0},this.sessionId),r=JSON.parse(n.result?.value??`{}`);e=r.w||1280,t=r.h||800}catch{}n.clip={x:0,y:0,width:e,height:t,scale:i}}n.captureBeyondViewport=!0;try{return(await this.client.send(`Page.captureScreenshot`,n,this.sessionId)).data}catch(t){return c.warn(`maxWidth re-capture failed, returning original`,t),e}}async evaluate(e,t){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Runtime.enable`,{},this.sessionId);let n=await this.client.send(`Runtime.evaluate`,{expression:e,awaitPromise:t?.awaitPromise??!0,returnByValue:t?.returnByValue??!0},this.sessionId),r=n.exceptionDetails;if(r){let e=r.exception?.description??r.text;throw Error(`Evaluation failed: ${e}`)}return n.result.value}async click(e,t=0){await this.ensureConnected(),this.ensureAttached();let n=await this.boundingBox(e);if(!n)throw Error(`Element not found: ${e}`);let r=n.x+n.width/2,i=n.y+n.height/2;await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:`left`,clickCount:1,modifiers:t},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:`left`,clickCount:1,modifiers:t},this.sessionId)}async type(e){await this.ensureConnected(),this.ensureAttached();for(let t of e)await this.client.send(`Input.dispatchKeyEvent`,{type:`keyDown`,text:t},this.sessionId),await this.client.send(`Input.dispatchKeyEvent`,{type:`keyUp`,text:t},this.sessionId)}async insertText(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Input.insertText`,{text:e},this.sessionId)}async waitForSelector(e,t){await this.ensureConnected(),this.ensureAttached();let n=t?.timeout??3e4,r=t?.interval??100,i=Date.now();for(;Date.now()-i<n;){if(await this.evaluate(`!!document.querySelector(${JSON.stringify(e)})`))return;await new Promise(e=>setTimeout(e,r))}throw Error(`waitForSelector timed out after ${n}ms: ${e}`)}async getAccessibilityTree(){await this.ensureConnected(),this.ensureAttached();let e=await this.evaluate(i,{awaitPromise:!1,returnByValue:!0});if(!e||typeof e!=`object`)return{role:`RootWebArea`,name:``};let t=p(e);try{let e=(await this.client.send(`Accessibility.getFullAXTree`,{},this.sessionId)).nodes;Array.isArray(e)&&f(t,d(e))}catch{}return t}async clickByBackendNodeId(e,t=0){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`DOM.enable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId);let n=(await this.client.send(`DOM.resolveNode`,{backendNodeId:e},this.sessionId)).object;if(!n?.objectId)throw Error(`Could not resolve backend node ${e} to a DOM element`);let r=(await this.client.send(`Runtime.callFunctionOn`,{objectId:n.objectId,functionDeclaration:`function() {
871
+ })()`;function a(e,t=``){if(e==null)return t;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`)return String(e);try{return JSON.stringify(e)??t}catch{return String(e)}}function o(e){try{let t=atob(e.slice(0,48));return(t.charCodeAt(16)<<24|t.charCodeAt(17)<<16|t.charCodeAt(18)<<8|t.charCodeAt(19))>>>0}catch{return 0}}var s=`ws://localhost:5710/cdp`,c=e(`browser-api`);function l(e=typeof window<`u`?window.location:null){return e?.host?`${e.protocol===`https:`?`wss:`:`ws:`}//${e.host}/cdp`:s}var u=class{client;localClient;sessionId=null;attachedTargetId=null;trayTargetProvider=null;remoteTargetInfo=null;_frameContextCache=new Map;_mainWorldContextCache=new Map;_tabLock=Promise.resolve();_onSessionChange;_lastConnectOptions=null;supersededHandler=null;supersededNotified=!1;handleJavaScriptDialogOpening=async e=>{let t=typeof e.sessionId==`string`?e.sessionId:this.sessionId;if(t)try{await this.client.send(`Page.handleJavaScriptDialog`,{accept:!1},t,5e3),c.warn(`Auto-dismissed unexpected JavaScript dialog`,{sessionId:t,type:e.type,message:e.message,url:e.url})}catch(e){c.warn(`Failed to auto-dismiss JavaScript dialog`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}};handleExecutionContextCreated=e=>{let t=e.sessionId;if(typeof t==`string`&&t!==this.sessionId)return;let n=e.context,r=n?.auxData?.frameId;n?.auxData?.isDefault===!0&&r&&typeof n.id==`number`&&this._mainWorldContextCache.set(r,n.id)};handleExecutionContextDestroyed=e=>{let t=e.sessionId;if(typeof t==`string`&&t!==this.sessionId)return;let n=e.executionContextId;if(typeof n==`number`)for(let[e,t]of this._mainWorldContextCache)t===n&&this._mainWorldContextCache.delete(e)};handleExecutionContextsCleared=e=>{let t=e.sessionId;typeof t==`string`&&t!==this.sessionId||this._mainWorldContextCache.clear()};constructor(e){this.client=e??new r,this.localClient=this.client,this.addDialogListener(this.client),this.addExecutionContextListeners(this.client)}getTransport(){return this.client}setSessionChangeCallback(e){this._onSessionChange=e}getSessionId(){return this.sessionId}getAttachedTargetId(){return this.attachedTargetId}async withTab(e,t){let n,r=new Promise(e=>{n=e}),i=this._tabLock;this._tabLock=r,await i;try{return await t(await this.attachToPage(e))}finally{n()}}setTrayTargetProvider(e){this.trayTargetProvider=e}async listAllTargets(){let e=await this.listPages();if(!this.trayTargetProvider)return e;let t=!this.remoteTargetInfo,n=new Set(e.map(e=>e.targetId)),r=this.trayTargetProvider.getTargets().filter(e=>!t||!(e.runtimeId===`leader`&&n.has(e.localTargetId))).map(e=>({targetId:e.targetId,title:e.title,url:e.url,kind:e.kind,capabilities:e.capabilities}));return[...e,...r]}async connect(e){this._lastConnectOptions=e?{...e}:{},await this.client.connect({url:e?.url??l(),timeout:e?.timeout,...e?.protocols===void 0?{}:{protocols:e.protocols}}),this.supersededNotified=!1}primeConnectOptions(e){this._lastConnectOptions=e?{...e}:{}}setCdpSupersededHandler(e){this.supersededHandler=e}notifySuperseded(){if(!this.supersededNotified){this.supersededNotified=!0;try{this.supersededHandler?.()}catch{}}}async createPage(e){return await this.ensureConnected(),await this.ensureLocalConnected(),(await this.localClient.send(`Target.createTarget`,{url:e??`about:blank`,background:!0})).targetId}async createRemotePage(e,t){if(!this.trayTargetProvider?.openRemoteTab)throw Error(`Remote tab opening not available (no tray target provider)`);return this.trayTargetProvider.openRemoteTab(e,t??`about:blank`)}async closePage(e){if(await this.ensureConnected(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);try{await t.send(`Target.closeTarget`,{targetId:r})}finally{this.trayTargetProvider.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(n,r)}this.attachedTargetId===e&&(this.remoteTargetInfo&&=(this.setClient(this.localClient),null),this.sessionId=null,this.attachedTargetId=null);return}}await this.localClient.send(`Target.closeTarget`,{targetId:e}),this.attachedTargetId===e&&(this.sessionId=null,this.attachedTargetId=null)}disconnect(){this.sessionId=null,this.attachedTargetId=null,this.client.disconnect()}async listPages(){return await this.ensureConnected(),await this.ensureLocalConnected(),((await this.localClient.send(`Target.getTargets`)).targetInfos??[]).filter(e=>e.type===`page`).map(e=>({targetId:e.targetId,title:e.title,url:e.url,...e.active?{active:!0}:{}}))}async attachToPage(e){if(await this.ensureConnected(),this.sessionId&&this.attachedTargetId===e)return this.sessionId;if(this._frameContextCache.clear(),this._mainWorldContextCache.clear(),this.trayTargetProvider?.createRemoteTransport&&e.includes(`:`)){let t=e.indexOf(`:`),n=e.substring(0,t),r=e.substring(t+1);{let t=this.trayTargetProvider.createRemoteTransport(n,r);this.setClient(t),this.remoteTargetInfo={runtimeId:n,localTargetId:r};let i=await this.client.send(`Target.attachToTarget`,{targetId:r,flatten:!0});return this.sessionId=i.sessionId,this.attachedTargetId=e,await this.client.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.client),this.sessionId}}this.remoteTargetInfo&&=(this.trayTargetProvider?.removeRemoteTransport&&this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),null),await this.ensureLocalConnected();let t=await this.localClient.send(`Target.attachToTarget`,{targetId:e,flatten:!0});return this.sessionId=t.sessionId,this.attachedTargetId=e,await this.localClient.send(`Page.enable`,{},this.sessionId),this._onSessionChange?.(this.sessionId,this.localClient),this.sessionId}async detach(){if(this.sessionId){try{await this.client.send(`Target.detachFromTarget`,{sessionId:this.sessionId})}catch{}this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null}}async navigate(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.enable`,{},this.sessionId);let t=this.client.once(`Page.loadEventFired`);await this.client.send(`Page.navigate`,{url:e},this.sessionId),await t}async bringToFront(){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.bringToFront`,{},this.sessionId??void 0)}async screenshot(e){await this.ensureConnected(),this.ensureAttached();try{let t={format:e?.format??`png`,captureBeyondViewport:!!(e?.clip||e?.fullPage)};if(e?.quality!==void 0&&(t.quality=e.quality),e?.clip||e?.fullPage){let n=0,r=0;try{await this.client.send(`Runtime.enable`,{},this.sessionId);let e=await this.client.send(`Runtime.evaluate`,{expression:`JSON.stringify({ w: window.innerWidth, h: document.documentElement.scrollHeight })`,returnByValue:!0},this.sessionId),t=JSON.parse(e.result?.value??`{}`);n=t.w??0,r=t.h??0}catch(e){c.warn(`fullPage: failed to evaluate scroll dimensions, falling back to viewport`,e)}e?.clip?t.clip={...e.clip,scale:e.clip.scale??1}:t.clip={x:0,y:0,width:n||1280,height:r||800,scale:1}}let n;try{n=await this.client.send(`Page.captureScreenshot`,t,this.sessionId)}catch(r){if(e?.foregroundFallback===!1)throw r;await this.client.send(`Page.bringToFront`,{},this.sessionId),n=await this.client.send(`Page.captureScreenshot`,t,this.sessionId)}let r=n.data;return e?.maxWidth&&(r=await this._applyMaxWidth(r,e.maxWidth,t)),r}finally{}}async _applyMaxWidth(e,t,n){let r=o(e);if(!r||r<=t)return e;let i=t/r,a=n.clip;if(a)a.scale=i;else{let e=1280,t=800;try{await this.client.send(`Runtime.enable`,{},this.sessionId);let n=await this.client.send(`Runtime.evaluate`,{expression:`JSON.stringify({w:window.innerWidth,h:window.innerHeight})`,returnByValue:!0},this.sessionId),r=JSON.parse(n.result?.value??`{}`);e=r.w||1280,t=r.h||800}catch{}n.clip={x:0,y:0,width:e,height:t,scale:i}}n.captureBeyondViewport=!0;try{return(await this.client.send(`Page.captureScreenshot`,n,this.sessionId)).data}catch(t){return c.warn(`maxWidth re-capture failed, returning original`,t),e}}async evaluate(e,t){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Runtime.enable`,{},this.sessionId);let n=await this.client.send(`Runtime.evaluate`,{expression:e,awaitPromise:t?.awaitPromise??!0,returnByValue:t?.returnByValue??!0},this.sessionId),r=n.exceptionDetails;if(r){let e=r.exception?.description??r.text;throw Error(`Evaluation failed: ${e}`)}return n.result.value}async click(e,t=0){await this.ensureConnected(),this.ensureAttached();let n=await this.boundingBox(e);if(!n)throw Error(`Element not found: ${e}`);let r=n.x+n.width/2,i=n.y+n.height/2;await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:`left`,clickCount:1,modifiers:t},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:`left`,clickCount:1,modifiers:t},this.sessionId)}async type(e){await this.ensureConnected(),this.ensureAttached();for(let t of e)await this.client.send(`Input.dispatchKeyEvent`,{type:`keyDown`,text:t},this.sessionId),await this.client.send(`Input.dispatchKeyEvent`,{type:`keyUp`,text:t},this.sessionId)}async insertText(e){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Input.insertText`,{text:e},this.sessionId)}async waitForSelector(e,t){await this.ensureConnected(),this.ensureAttached();let n=t?.timeout??3e4,r=t?.interval??100,i=Date.now();for(;Date.now()-i<n;){if(await this.evaluate(`!!document.querySelector(${JSON.stringify(e)})`))return;await new Promise(e=>setTimeout(e,r))}throw Error(`waitForSelector timed out after ${n}ms: ${e}`)}async getAccessibilityTree(){await this.ensureConnected(),this.ensureAttached();let e=await this.evaluate(i,{awaitPromise:!1,returnByValue:!0});if(!e||typeof e!=`object`)return{role:`RootWebArea`,name:``};let t=p(e);try{let e=(await this.client.send(`Accessibility.getFullAXTree`,{},this.sessionId)).nodes;Array.isArray(e)&&f(t,d(e))}catch{}return t}async clickByBackendNodeId(e,t=0){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`DOM.enable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId);let n=(await this.client.send(`DOM.resolveNode`,{backendNodeId:e},this.sessionId)).object;if(!n?.objectId)throw Error(`Could not resolve backend node ${e} to a DOM element`);let r=(await this.client.send(`Runtime.callFunctionOn`,{objectId:n.objectId,functionDeclaration:`function() {
872
872
  this.scrollIntoView({ block: 'center', inline: 'center' });
873
873
  const r = this.getBoundingClientRect();
874
874
  return { x: r.x, y: r.y, width: r.width, height: r.height };
875
- }`,returnByValue:!0},this.sessionId)).result?.value;if(!r||r.width===0||r.height===0){await this.client.send(`Runtime.callFunctionOn`,{objectId:n.objectId,functionDeclaration:`function() { this.click(); }`},this.sessionId);return}let i=r.x+r.width/2,a=r.y+r.height/2;await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:i,y:a,button:`left`,clickCount:1,modifiers:t},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:i,y:a,button:`left`,clickCount:1,modifiers:t},this.sessionId)}async dblclickByBackendNodeId(e,t=`left`,n=0){await this.ensureConnected(),this.ensureAttached();let{x:r,y:i}=await this.resolveNodeCenter(e);await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:t,clickCount:1,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:t,clickCount:1,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:t,clickCount:2,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:t,clickCount:2,modifiers:n},this.sessionId)}async hoverByBackendNodeId(e){await this.ensureConnected(),this.ensureAttached();let{x:t,y:n}=await this.resolveNodeCenter(e);await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:t,y:n},this.sessionId)}async selectByBackendNodeId(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeObjectId(e);await this.client.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function(val) { this.value = val; this.dispatchEvent(new Event('change', { bubbles: true })); }`,arguments:[{value:t}],returnByValue:!0},this.sessionId)}async setCheckedByBackendNodeId(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeObjectId(e);return(await this.client.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function() { return this.checked; }`,returnByValue:!0},this.sessionId)).result?.value===t?`already`:(await this.clickByBackendNodeId(e),`toggled`)}async dragByBackendNodeIds(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeCenter(e),r=await this.resolveNodeCenter(t);await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:n.x,y:n.y,button:`left`,clickCount:1},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:r.x,y:r.y},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r.x,y:r.y,button:`left`,clickCount:1},this.sessionId)}async getFrameTree(){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.enable`,{},this.sessionId);let e=(await this.client.send(`Page.getFrameTree`,{},this.sessionId)).frameTree,t=[],n=e=>{if(t.push({frameId:e.frame.id,parentFrameId:e.frame.parentId,url:e.frame.url,name:e.frame.name??``,securityOrigin:e.frame.securityOrigin}),Array.isArray(e.childFrames))for(let t of e.childFrames)n(t)};return n(e),t}async evaluateInFrame(e,t,n){await this.ensureConnected(),this.ensureAttached();let r=e=>{let t=e instanceof Error?e.message:String(e);return t.includes(`Cannot find context with specified id`)||t.includes(`Execution context was destroyed`)},i=async()=>{let t=(await this.client.send(`Page.createIsolatedWorld`,{frameId:e,worldName:`__slicc_iframe`},this.sessionId)).executionContextId;return this._frameContextCache.set(e,t),t},a=this._frameContextCache.get(e);if(a===void 0)try{a=await i()}catch(t){throw Error(`Failed to create isolated world for frame ${e}: ${t instanceof Error?t.message:String(t)}`)}await this.client.send(`Runtime.enable`,{},this.sessionId);let o={expression:t,contextId:a,awaitPromise:n?.awaitPromise??!0,returnByValue:n?.returnByValue??!0},s;try{s=await this.client.send(`Runtime.evaluate`,o,this.sessionId)}catch(t){if(r(t))this._frameContextCache.delete(e),a=await i(),s=await this.client.send(`Runtime.evaluate`,{...o,contextId:a},this.sessionId);else throw t}let c=s.exceptionDetails;if(c){let t=c.exception?.description??c.text;if(r(Error(t))){this._frameContextCache.delete(e),a=await i();let t=await this.client.send(`Runtime.evaluate`,{...o,contextId:a},this.sessionId),n=t.exceptionDetails;if(n){let t=n.exception?.description??n.text;throw Error(`Evaluation in frame ${e} failed: ${t}`)}return t.result.value}throw this._frameContextCache.delete(e),Error(`Evaluation in frame ${e} failed: ${t}`)}return s.result.value}async getAccessibilityTreeForFrame(e){if(!e)return this.getAccessibilityTree();await this.ensureConnected(),this.ensureAttached();let t=await this.evaluateInFrame(e,i,{awaitPromise:!1,returnByValue:!0});return!t||typeof t!=`object`?{role:`RootWebArea`,name:``}:p(t)}async sendCDP(e,t={}){return await this.ensureConnected(),this.ensureAttached(),await this.client.send(e,t,this.sessionId)}async resolveNodeObjectId(e){await this.client.send(`DOM.enable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.resolveNode`,{backendNodeId:e},this.sessionId)).object;if(!t?.objectId)throw Error(`Could not resolve backend node ${e} to a DOM element`);return t.objectId}async resolveNodeCenter(e){let t=await this.resolveNodeObjectId(e),n=(await this.client.send(`Runtime.callFunctionOn`,{objectId:t,functionDeclaration:`function() {
875
+ }`,returnByValue:!0},this.sessionId)).result?.value;if(!r||r.width===0||r.height===0){await this.client.send(`Runtime.callFunctionOn`,{objectId:n.objectId,functionDeclaration:`function() { this.click(); }`},this.sessionId);return}let i=r.x+r.width/2,a=r.y+r.height/2;await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:i,y:a,button:`left`,clickCount:1,modifiers:t},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:i,y:a,button:`left`,clickCount:1,modifiers:t},this.sessionId)}async dblclickByBackendNodeId(e,t=`left`,n=0){await this.ensureConnected(),this.ensureAttached();let{x:r,y:i}=await this.resolveNodeCenter(e);await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:t,clickCount:1,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:t,clickCount:1,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:r,y:i,button:t,clickCount:2,modifiers:n},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r,y:i,button:t,clickCount:2,modifiers:n},this.sessionId)}async hoverByBackendNodeId(e){await this.ensureConnected(),this.ensureAttached();let{x:t,y:n}=await this.resolveNodeCenter(e);await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:t,y:n},this.sessionId)}async selectByBackendNodeId(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeObjectId(e);await this.client.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function(val) { this.value = val; this.dispatchEvent(new Event('change', { bubbles: true })); }`,arguments:[{value:t}],returnByValue:!0},this.sessionId)}async setCheckedByBackendNodeId(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeObjectId(e);return(await this.client.send(`Runtime.callFunctionOn`,{objectId:n,functionDeclaration:`function() { return this.checked; }`,returnByValue:!0},this.sessionId)).result?.value===t?`already`:(await this.clickByBackendNodeId(e),`toggled`)}async dragByBackendNodeIds(e,t){await this.ensureConnected(),this.ensureAttached();let n=await this.resolveNodeCenter(e),r=await this.resolveNodeCenter(t);await this.client.send(`Input.dispatchMouseEvent`,{type:`mousePressed`,x:n.x,y:n.y,button:`left`,clickCount:1},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseMoved`,x:r.x,y:r.y},this.sessionId),await this.client.send(`Input.dispatchMouseEvent`,{type:`mouseReleased`,x:r.x,y:r.y,button:`left`,clickCount:1},this.sessionId)}async getFrameTree(){await this.ensureConnected(),this.ensureAttached(),await this.client.send(`Page.enable`,{},this.sessionId);let e=(await this.client.send(`Page.getFrameTree`,{},this.sessionId)).frameTree,t=[],n=e=>{if(t.push({frameId:e.frame.id,parentFrameId:e.frame.parentId,url:e.frame.url,name:e.frame.name??``,securityOrigin:e.frame.securityOrigin}),Array.isArray(e.childFrames))for(let t of e.childFrames)n(t)};return n(e),t}async evaluateInFrame(e,t,n){await this.ensureConnected(),this.ensureAttached();let r=e=>{let t=e instanceof Error?e.message:String(e);return t.includes(`Cannot find context with specified id`)||t.includes(`Execution context was destroyed`)},i=async()=>{let t=(await this.client.send(`Page.createIsolatedWorld`,{frameId:e,worldName:`__slicc_iframe`},this.sessionId)).executionContextId;return this._frameContextCache.set(e,t),t},a=async()=>{if(n?.world!==`main`)return this._frameContextCache.get(e)??i();await this.client.send(`Runtime.enable`,{},this.sessionId);let t=this._mainWorldContextCache.get(e);if(t===void 0&&(await this.client.send(`Runtime.disable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId),t=this._mainWorldContextCache.get(e)),t===void 0)throw Error(`Failed to find main world execution context for frame ${e}`);return t},o=()=>{n?.world===`main`?this._mainWorldContextCache.delete(e):this._frameContextCache.delete(e)},s;try{s=await a()}catch(t){let r=n?.world===`main`?`main world`:`isolated world`;throw Error(`Failed to resolve ${r} for frame ${e}: ${t instanceof Error?t.message:String(t)}`)}n?.world!==`main`&&await this.client.send(`Runtime.enable`,{},this.sessionId);let c={expression:t,contextId:s,awaitPromise:n?.awaitPromise??!0,returnByValue:n?.returnByValue??!0},l;try{l=await this.client.send(`Runtime.evaluate`,c,this.sessionId)}catch(e){if(r(e))o(),s=await a(),l=await this.client.send(`Runtime.evaluate`,{...c,contextId:s},this.sessionId);else throw e}let u=l.exceptionDetails;if(u){let t=u.exception?.description??u.text;if(r(Error(t))){o(),s=await a();let t=await this.client.send(`Runtime.evaluate`,{...c,contextId:s},this.sessionId),n=t.exceptionDetails;if(n){let t=n.exception?.description??n.text;throw Error(`Evaluation in frame ${e} failed: ${t}`)}return t.result.value}throw o(),Error(`Evaluation in frame ${e} failed: ${t}`)}return l.result.value}async getAccessibilityTreeForFrame(e){if(!e)return this.getAccessibilityTree();await this.ensureConnected(),this.ensureAttached();let t=await this.evaluateInFrame(e,i,{awaitPromise:!1,returnByValue:!0});return!t||typeof t!=`object`?{role:`RootWebArea`,name:``}:p(t)}async sendCDP(e,t={}){return await this.ensureConnected(),this.ensureAttached(),await this.client.send(e,t,this.sessionId)}async resolveNodeObjectId(e){await this.client.send(`DOM.enable`,{},this.sessionId),await this.client.send(`Runtime.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.resolveNode`,{backendNodeId:e},this.sessionId)).object;if(!t?.objectId)throw Error(`Could not resolve backend node ${e} to a DOM element`);return t.objectId}async resolveNodeCenter(e){let t=await this.resolveNodeObjectId(e),n=(await this.client.send(`Runtime.callFunctionOn`,{objectId:t,functionDeclaration:`function() {
876
876
  this.scrollIntoView({ block: 'center', inline: 'center' });
877
877
  const r = this.getBoundingClientRect();
878
878
  return { x: r.x, y: r.y, width: r.width, height: r.height };
879
- }`,returnByValue:!0},this.sessionId)).result?.value;if(!n||n.width===0||n.height===0)throw Error(`Element with backend node ${e} has no dimensions`);return{x:n.x+n.width/2,y:n.y+n.height/2}}async ensureLocalConnected(){if(this.localClient.superseded===!0){this.notifySuperseded();return}if(this.localClient.state===`disconnected`){let e=this._lastConnectOptions;await this.localClient.connect({url:e?.url??l(),...e?.timeout===void 0?{}:{timeout:e.timeout},...e?.protocols===void 0?{}:{protocols:e.protocols}})}}async ensureConnected(){if(this.client.superseded===!0){this.notifySuperseded();return}this.client.state===`disconnected`&&(this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null,this.client.state===`disconnected`&&await this.connect(this._lastConnectOptions??void 0))}ensureAttached(){if(!this.sessionId)throw Error(`Not attached to a page. Call attachToPage(targetId) first.`)}addDialogListener(e){e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}removeDialogListener(e){e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}setClient(e){this.client!==e&&(this.removeDialogListener(this.client),this.client=e,this.addDialogListener(this.client))}async boundingBox(e){await this.client.send(`DOM.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.getDocument`,{depth:0},this.sessionId)).root.nodeId,n;try{n=(await this.client.send(`DOM.querySelector`,{nodeId:t,selector:e},this.sessionId)).nodeId}catch{return null}if(!n)return null;let r=(await this.client.send(`DOM.getBoxModel`,{nodeId:n},this.sessionId)).model;if(!r)return null;let i=r.content;return{x:i[0],y:i[1],width:r.width,height:r.height}}};function d(e){let t=new Map;for(let n of e){let e=typeof n.backendDOMNodeId==`number`?n.backendDOMNodeId:null;if(e===null)continue;let r=n.role,i=n.name,a=typeof r?.value==`string`?r.value.toLowerCase():``,o=typeof i?.value==`string`?i.value:``;if(!a)continue;let s=`${a}|${o}`;t.has(s)||t.set(s,e)}return t}function f(e,t){let n=`${e.role.toLowerCase()}|${e.name}`,r=t.get(n);if(r!==void 0&&(e.backendNodeId=r),e.children)for(let n of e.children)f(n,t)}function p(e){let t={role:a(e.role,`unknown`),name:a(e.name)},n=a(e.value);n!==``&&(t.value=n);let r=a(e.description);return r!==``&&(t.description=r),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>p(e)).filter(e=>e.role!==`unknown`)),t}e(`har-recorder`);export{u as BrowserAPI};
879
+ }`,returnByValue:!0},this.sessionId)).result?.value;if(!n||n.width===0||n.height===0)throw Error(`Element with backend node ${e} has no dimensions`);return{x:n.x+n.width/2,y:n.y+n.height/2}}async ensureLocalConnected(){if(this.localClient.superseded===!0){this.notifySuperseded();return}if(this.localClient.state===`disconnected`){let e=this._lastConnectOptions;await this.localClient.connect({url:e?.url??l(),...e?.timeout===void 0?{}:{timeout:e.timeout},...e?.protocols===void 0?{}:{protocols:e.protocols}})}}async ensureConnected(){if(this.client.superseded===!0){this.notifySuperseded();return}this.client.state===`disconnected`&&(this.remoteTargetInfo&&this.trayTargetProvider?.removeRemoteTransport&&(this.trayTargetProvider.removeRemoteTransport(this.remoteTargetInfo.runtimeId,this.remoteTargetInfo.localTargetId),this.setClient(this.localClient),this.remoteTargetInfo=null),this.sessionId=null,this.attachedTargetId=null,this.client.state===`disconnected`&&await this.connect(this._lastConnectOptions??void 0))}ensureAttached(){if(!this.sessionId)throw Error(`Not attached to a page. Call attachToPage(targetId) first.`)}addDialogListener(e){e.on(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}addExecutionContextListeners(e){e.on(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.on(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.on(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared)}removeDialogListener(e){e.off(`Page.javascriptDialogOpening`,this.handleJavaScriptDialogOpening)}removeExecutionContextListeners(e){e.off(`Runtime.executionContextCreated`,this.handleExecutionContextCreated),e.off(`Runtime.executionContextDestroyed`,this.handleExecutionContextDestroyed),e.off(`Runtime.executionContextsCleared`,this.handleExecutionContextsCleared)}setClient(e){this.client!==e&&(this.removeDialogListener(this.client),this.removeExecutionContextListeners(this.client),this.client=e,this.addDialogListener(this.client),this.addExecutionContextListeners(this.client))}async boundingBox(e){await this.client.send(`DOM.enable`,{},this.sessionId);let t=(await this.client.send(`DOM.getDocument`,{depth:0},this.sessionId)).root.nodeId,n;try{n=(await this.client.send(`DOM.querySelector`,{nodeId:t,selector:e},this.sessionId)).nodeId}catch{return null}if(!n)return null;let r=(await this.client.send(`DOM.getBoxModel`,{nodeId:n},this.sessionId)).model;if(!r)return null;let i=r.content;return{x:i[0],y:i[1],width:r.width,height:r.height}}};function d(e){let t=new Map;for(let n of e){let e=typeof n.backendDOMNodeId==`number`?n.backendDOMNodeId:null;if(e===null)continue;let r=n.role,i=n.name,a=typeof r?.value==`string`?r.value.toLowerCase():``,o=typeof i?.value==`string`?i.value:``;if(!a)continue;let s=`${a}|${o}`;t.has(s)||t.set(s,e)}return t}function f(e,t){let n=`${e.role.toLowerCase()}|${e.name}`,r=t.get(n);if(r!==void 0&&(e.backendNodeId=r),e.children)for(let n of e.children)f(n,t)}function p(e){let t={role:a(e.role,`unknown`),name:a(e.name)},n=a(e.value);n!==``&&(t.value=n);let r=a(e.description);return r!==``&&(t.description=r),Array.isArray(e.children)&&e.children.length>0&&(t.children=e.children.map(e=>p(e)).filter(e=>e.role!==`unknown`)),t}e(`har-recorder`);export{u as BrowserAPI};
@@ -1 +1 @@
1
- import{h as e}from"./account-store-DqOwEqPJ.js";import{n as t}from"./event-stream-qbAZIAKV.js";import{a as n}from"./compat-aVSWLlYQ.js";import{r,s as i}from"./legacy-api-aliases-IllWZ-uu.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()}}}var _=(e,n,i={})=>{let a=t();return(async()=>{try{let t=r({...e,baseUrl:o,api:s},n,i);for await(let e of t)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},v=(e,n,r)=>{let a=t();return(async()=>{try{let t=i({...e,baseUrl:o,api:s},n,r);for await(let e of t)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},y={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 b(){n({api:c,stream:_,streamSimple:v})}export{y as config,b as register};
1
+ import{h as e}from"./account-store-Cl38jIN3.js";import{n as t}from"./event-stream-qbAZIAKV.js";import{a as n}from"./compat-aVSWLlYQ.js";import{r,s as i}from"./legacy-api-aliases-IllWZ-uu.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()}}}var _=(e,n,i={})=>{let a=t();return(async()=>{try{let t=r({...e,baseUrl:o,api:s},n,i);for await(let e of t)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},v=(e,n,r)=>{let a=t();return(async()=>{try{let t=i({...e,baseUrl:o,api:s},n,r);for await(let e of t)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},y={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 b(){n({api:c,stream:_,streamSimple:v})}export{y as config,b as register};
@@ -1 +1 @@
1
- import{h as e}from"./account-store-CJ9KAeuF.js";import{n as t}from"./event-stream-qbAZIAKV.js";import{p as n}from"./bedrock-camp-BO4bvAKs.js";import{r,s as i}from"./legacy-api-aliases-sqlB2uHc.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()}}}const _=(e,n,i={})=>{let a=t();return(async()=>{try{let t=r({...e,baseUrl:o,api:s},n,i);for await(let e of t)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},v=(e,n,r)=>{let a=t();return(async()=>{try{let t=i({...e,baseUrl:o,api:s},n,r);for await(let e of t)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},y={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 b(){n({api:c,stream:_,streamSimple:v})}export{y as config,b as register};
1
+ import{h as e}from"./account-store-uZBiyCfC.js";import{n as t}from"./event-stream-qbAZIAKV.js";import{p as n}from"./bedrock-camp-BO4bvAKs.js";import{r,s as i}from"./legacy-api-aliases-sqlB2uHc.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()}}}const _=(e,n,i={})=>{let a=t();return(async()=>{try{let t=r({...e,baseUrl:o,api:s},n,i);for await(let e of t)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},v=(e,n,r)=>{let a=t();return(async()=>{try{let t=i({...e,baseUrl:o,api:s},n,r);for await(let e of t)a.push(e);a.end()}catch(t){console.error(`[cerebras] Stream error:`,t instanceof Error?t.message:String(t)),a.push(g(e,t)),a.end()}})(),a},y={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 b(){n({api:c,stream:_,streamSimple:v})}export{y as config,b as register};
@@ -1,4 +1,4 @@
1
- import{C as e,P as t,d as n,f as r}from"./account-store-DqOwEqPJ.js";import{n as i}from"./provider-settings-CzdPoa2L.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=r().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(r){for(;r.firstChild;)r.removeChild(r.firstChild);r.className=`connect-surface`;let a=document.createElement(`h1`);a.className=`connect-surface__title`,a.textContent=`Connect providers`,r.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.`,r.appendChild(l);let u=document.createElement(`div`);u.className=`connect-surface__accounts`,r.appendChild(u);function d(){for(;u.firstChild;)u.removeChild(u.firstChild);let r=n().filter(e=>e.providerId!==o);if(r.length===0){let e=document.createElement(`div`);e.className=`connect-surface__empty`,e.textContent=`No providers connected yet.`,u.appendChild(e)}else{let n=document.createElement(`div`);n.className=`connect-surface__accounts-list`;for(let i of r){let r=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=r.name,o.appendChild(s);let l=document.createElement(`div`);l.className=`connect-surface__account-detail`,i.userName?l.textContent=i.userName:i.accessToken?l.textContent=`Logged in`:l.textContent=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 t(i.providerId),c(),d()},a.appendChild(u),n.appendChild(a)}u.appendChild(n)}let a=document.createElement(`button`);a.className=`connect-surface__add-btn`,a.textContent=r.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),r.appendChild(f),!document.getElementById(`connect-surface-style`)){let e=document.createElement(`style`);e.id=`connect-surface-style`,e.textContent=`
1
+ import{C as e,P as t,d as n,f as r}from"./account-store-Cl38jIN3.js";import{n as i}from"./provider-settings-5ZSUhS4X.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=r().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(r){for(;r.firstChild;)r.removeChild(r.firstChild);r.className=`connect-surface`;let a=document.createElement(`h1`);a.className=`connect-surface__title`,a.textContent=`Connect providers`,r.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.`,r.appendChild(l);let u=document.createElement(`div`);u.className=`connect-surface__accounts`,r.appendChild(u);function d(){for(;u.firstChild;)u.removeChild(u.firstChild);let r=n().filter(e=>e.providerId!==o);if(r.length===0){let e=document.createElement(`div`);e.className=`connect-surface__empty`,e.textContent=`No providers connected yet.`,u.appendChild(e)}else{let n=document.createElement(`div`);n.className=`connect-surface__accounts-list`;for(let i of r){let r=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=r.name,o.appendChild(s);let l=document.createElement(`div`);l.className=`connect-surface__account-detail`,i.userName?l.textContent=i.userName:i.accessToken?l.textContent=`Logged in`:l.textContent=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 t(i.providerId),c(),d()},a.appendChild(u),n.appendChild(a)}u.appendChild(n)}let a=document.createElement(`button`);a.className=`connect-surface__add-btn`,a.textContent=r.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),r.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;
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-0FRaZO2z.js","assets/rolldown-runtime-aKtaBQYM.js","assets/dist-Bj10RLrf.js","assets/mount-BGLX5HYy.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-ugOWOUZ9.js","assets/base64-DpPqYZJF.js","assets/src-DoFhVmQT.js","assets/proxied-fetch-CfcFb0B0.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/types-idfTVsM8.js","assets/backend-local-smcj-_Ox.js","assets/tool-ui-DfXu6quJ.js","assets/logger-DDBAeTLF.js","assets/picker-approval-CdWaB1mR.js","assets/mount-picker-popup-Bs1o43Z5.js","assets/picker-popup-BvzmBsGL.js","assets/mount-table-store-CfQUN_2R.js","assets/mount-bridge-client-BWPRzAQ5.js","assets/port-bridge-client-DdolH4cw.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.js";import{t as n}from"./types-idfTVsM8.js";import{t as r}from"./backend-local-smcj-_Ox.js";import{a as i,i as a,n as o,t as s}from"./mount-table-store-CfQUN_2R.js";var c=t(`fs-watcher`),l=0;function u(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var d=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++l}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),c.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),c.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>u(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){c.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),c.debug(`All watchers disposed`)}get size(){return this.registrations.size}},f=t(`mount-index`),p=400,m=2e6,h=`SLICC_MOUNT_INDEX_MAX_DEPTH`,g=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,_=256,v=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function y(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>_?t.slice(0,_):t;return`${t.length}\u0001${n.join(``)}`}async function b(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function x(e,t){return e instanceof Map?e.get(t):e[t]}function S(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function C(e,t,n){let r=x(e,t);if(r===void 0||r.trim()===``)return n;let i=S(r);return i===void 0?(f.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function w(e){return{maxDepth:C(e,h,p),maxEntries:C(e,g,m)}}var T=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=w({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,f.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof v?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},f.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new v(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new v(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new v(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=y(n),a=r.get(i);if(a){for(let n of a)if(await b(n.handle,t))throw new v(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}};function E(e){if(!e||e===`/`)return`/`;e.startsWith(`/`)||(e=`/`+e);let t=e.split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return`/`+n.join(`/`)}function D(e){let t=E(e);if(t===`/`)return{dir:`/`,base:``};let n=t.lastIndexOf(`/`);return{dir:n===0?`/`:t.slice(0,n),base:t.slice(n+1)}}function O(e){let t=E(e);return t===`/`?[]:t.slice(1).split(`/`)}function k(...e){return E(e.join(`/`))}var A={"/dev/null":{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},j=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let i=e=>{let t=E(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(i),this.readOnlyPrefixes=n.map(i),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=E(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=E(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=E(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new n(`EACCES`,`permission denied`,E(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new n(`ENOENT`,`no such file or directory`,E(e));return t}catch(t){throw t instanceof n?t:new n(`ENOENT`,`no such file or directory`,E(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new n(`EACCES`,`permission denied`,E(e));return t}catch(t){throw t instanceof n?t:new n(`EACCES`,`permission denied`,E(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),r=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof n&&e.code===`EACCES`)throw e;return}let a=i+`/`+r;if(this.isWritable(a))return;let o=E(i)!==E(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new n(`EACCES`,`permission denied`,E(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let r=A[E(e)];if(r)return r.read(t);if(!this.isAllowedStrict(e))throw new n(`ENOENT`,`no such file or directory`,E(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=E(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=A[E(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new n(`ENOENT`,`no such file or directory`,E(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=E(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),i=t?r.length:r.length-1,a=``;for(let e=0;e<i;e++){a=a+`/`+r[e];let t=this.vfs.lstatSync(a);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=A[E(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=A[E(e)];return t?t.stat():!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=E(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof n?t:new n(`ENOENT`,`no such file or directory`,E(e))}if(!this.isAllowedStrict(t))throw new n(`ENOENT`,`no such file or directory`,E(e));return t}async exists(e){if(A[E(e)])return!0;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=A[E(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new n(`ENOENT`,`no such file or directory`,E(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(r)}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,r){let i=A[E(e)];if(i){i.write(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 n&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,r)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof n&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new n(`ENOENT`,`no such file or directory`,E(e));this.checkWrite(t);let r=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 n&&e.code===`EACCES`)throw e}return this.vfs.copyFile(r,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new n(`ENOENT`,`no such file or directory`,E(e));let t=await this.vfs.readlink(e),r;if(r=t.startsWith(`/`)?E(t):E(this.vfs.dirname(e)+`/`+t),!this.isAllowedStrict(r))throw new n(`ENOENT`,`no such file or directory`,E(e));return t}async lstat(e){let t=A[E(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new n(`ENOENT`,`no such file or directory`,E(e));let r=E(e),i=this.vfs.dirname(r),a=this.vfs.basename(r),o;if(i===r)o=i;else try{o=await this.vfs.realpath(i)}catch{throw new n(`ENOENT`,`no such file or directory`,r)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new n(`ENOENT`,`no such file or directory`,r);return this.vfs.lstat(s)}watch(e,t,r){if(!this.isAllowed(e))throw new n(`EACCES`,`permission denied`,E(e));let i=this.vfs.getWatcher();if(!i)throw new n(`EINVAL`,`no watcher configured`);return i.watch(E(e),t,r)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function M(e,t){if(e instanceof n){let r=`${e.code}: `,i=e.message;throw i.startsWith(r)&&(i=i.slice(r.length)),e.path&&i.endsWith(` '${e.path}'`)&&(i=i.slice(0,i.length-` '${e.path}'`.length)),new n(e.code,i,t)}throw e}var N=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`];function P(e,t){if(e instanceof n)return e;let r=e?.code;if(typeof r==`string`){let i=r;if(N.includes(i))return new n(i,(e instanceof Error?e.message:String(e))||i,t)}let i=e instanceof Error?e.message:String(e);return i.includes(`ENOENT`)?new n(`ENOENT`,`no such file or directory`,t):i.includes(`EEXIST`)?new n(`EEXIST`,`file already exists`,t):i.includes(`ENOTDIR`)?new n(`ENOTDIR`,`not a directory`,t):i.includes(`EISDIR`)?new n(`EISDIR`,`is a directory`,t):i.includes(`ENOTEMPTY`)?new n(`ENOTEMPTY`,`directory not empty`,t):i.includes(`ELOOP`)?new n(`ELOOP`,`too many levels of symbolic links`,t):new n(`EINVAL`,i,t)}async function F(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=P(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function I(e,t,n){let r;try{r=await e.readlink(t)}catch(e){throw P(e,n)}return r.startsWith(`/`)?E(r):E(k(D(t).dir,r))}async function L(e,t,r,i,a,o){let s=t===`/`?`/${r}`:`${t}/${r}`;for(;;){let t=await F(e,s,i,a);if(t===null||!t.isSymbolicLink())return{resolved:s,hops:o};if(++o>10)throw new n(`ELOOP`,`too many symbolic links encountered`,a);s=await I(e,s,a)}}async function R(e,t,n){let r=E(n);if(t(r))return r;let i=r.split(`/`).filter(Boolean),a=`/`,o=0;for(let t=0;t<i.length;t++){let n=await L(e,a,i[t],t===i.length-1,r,o);a=n.resolved,o=n.hops}return a}async function z(e,t,n){return t(n)?n:R(e,t,n)}function B(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 V(e,t){try{return await e(t)}catch{return t}}async function*H(e,t,n,r=0){let i=E(t);if(B(e.mountPoints,e.mountIndex,i)){let t=e.mountIndex.getFiles(i);if(t){for(let e of t)yield e;return}}let a=n??new Set;if(r>64||a.size>=1e5)return;let o=await V(t=>e.realpath(t),i);if(a.has(o))return;a.add(o);let s=await e.readDir(i);for(let t of s)yield*U(e,t,i===`/`?`/${t.name}`:`${i}/${t.name}`,a,r+1)}async function*U(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*W(e,n,r,i);return}yield*H(e,n,r,i)}async function*W(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*H(e,t,n,r))}catch{}}function G(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var K=class t{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 T;_writeLock=Promise.resolve();constructor(e,n,r,i){if(this.dbName=e,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?t.initOpfsBackend(this,i,n===!0):t.initMemoryBackend(this,e,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${e}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r).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(n,r,i){let a=r??await t.acquireOpfsHandle(n.dbName,i);await t.seedOpfsMetadataSidecarIfMissing(a);let[o,{WebAccess:s}]=await Promise.all([e(()=>import(`./dist-0FRaZO2z.js`).then(e=>e.t),__vite__mapDeps([0,1])),e(()=>import(`./dist-Bj10RLrf.js`),__vite__mapDeps([2,0,1]))]);await t.ensureRootMount(o);let c=`/__opfs__/${n.dbName}`,l=t.opfsBackends.get(n.dbName);if(l&&i){try{o.umount(c)}catch{}t.opfsBackends.delete(n.dbName),l=void 0}if(!l){let e=await o.resolveMountConfig({backend:s,handle:a,metadata:`/.metadata.json`});try{o.mount(c,e)}catch{}l={backendFs:e,refs:0},t.opfsBackends.set(n.dbName,l)}l.refs+=1,n.opfsBackendFs=l.backendFs.index?l.backendFs:null,n.opfsHandle=a,n.mountRoot=c,n.rawLfs=o.promises,n.rawLfsSync=o}static async initMemoryBackend(n,r,i){let a=await e(()=>import(`./dist-0FRaZO2z.js`).then(e=>e.t),__vite__mapDeps([0,1]));await t.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=t.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}t.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},t.memoryBackends.set(r,s)),s.refs+=1;try{a.mount(o,s.store)}catch{}n.mountRoot=o,n.rawLfs=a.promises,n.rawLfsSync=a,n.opfsBackendFs=null,n.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(e){return t.rootMountReady||=(async()=>{await e.configureSingle({backend:e.InMemory,label:`__vfs_root__`})})(),t.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(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let r=navigator.storage;if(!r?.getDirectory)throw new n(`EINVAL`,`OPFS is not available in this environment`);let i=await r.getDirectory();if(t)try{await i.removeEntry(e,{recursive:!0})}catch{}return i.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(e){return new t(e)}static async create(e){let n=e?.dbName??`browser-fs`,r=e?.wipe===!0,i=e?.backend??G(),a=new t(n,r,i);return await a._ready,r&&await s().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){if(this.backend!==`opfs`)return;let e=this.opfsBackendFs,t=this.opfsHandle;if(!e||!t)return;let n=JSON.stringify(e.index.toJSON()),r=await(await t.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await r.write(n),await r.close()}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=E(n);t.index.delete(e),t._handles?.delete(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let n=this.backend===`opfs`?t.opfsBackends:t.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await e(()=>import(`./dist-0FRaZO2z.js`).then(e=>e.t),__vite__mapDeps([0,1]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=E(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({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=E(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.statSync!=`function`||typeof n.lstatSync!=`function`||typeof n.readlinkSync!=`function`)return null;let r=t;for(let e=0;e<=10;e++){let e;try{e=n.lstatSync(r)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=n.readlinkSync(r)}catch{return null}r=t.startsWith(`/`)?E(t):E(k(D(r).dir,t))}return null}lstatSync(e){let t=E(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;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}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,r){let a=E(e);if(this.mountPoints.has(a))throw new n(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new n(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new n(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof n)||e.code!==`ENOENT`)throw e}let{dir:o}=D(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=w(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{await i({targetPath:a,descriptor:s,createdAt:Date.now()},t.kind===`local`?t.getHandle():void 0)}catch{}}async unmount(e){let t=E(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 a(t)}catch{}}async reconstructBackendFromDescriptor(t){switch(t.kind){case`local`:{let e=await o(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return r.fromHandle(e,{mountId:t.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await e(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-BGLX5HYy.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([3,4,5,6,7,8,1,9,10,11,12,13,14,15,16,17,18,19,20])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i(t.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-BGLX5HYy.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([3,4,5,6,7,8,1,9,10,11,12,13,14,15,16,17,18,19,20])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i()})}}}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}async mountInternal(e,t){let r=E(e);if(this.mountPoints.has(r))throw new n(`EEXIST`,`mount point is already mounted`,r);let{dir:i}=D(r);i!==`/`&&await this.mkdir(i,{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=E(e);if(!this.internalMounts.has(t))throw new n(`ENOENT`,`not an internal mount point`,t);let r=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await r?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let r=E(e),i=this.mountPoints.get(r);if(!i)throw new n(`ENOENT`,`not a mount point`,r);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(r,w(t?.env??{})),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){let r=E(e),i=this.findMount(r);if(i){if(i.relParts.length===0)throw new n(`EISDIR`,`is a directory`,r);let e=i.relParts.join(`/`);try{let n=await i.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){M(e,r)}}let a=await this.resolveSymlinks(r);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw P(e,r)}}async writeFile(e,t,r){let i=E(e),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new n(`EISDIR`,`is a directory`,i);let e=a.relParts.join(`/`),r=!1;try{await this.stat(i),r=!0}catch{}let o=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await a.backend.writeFile(e,o)}catch(e){M(e,i)}this.watcher?.notify([{type:r?`modify`:`create`,path:i,entryType:`file`}]),this.mountIndex.notifyWrite(i);return}let o;try{o=await this.resolveSymlinks(i)}catch{o=i}let s=!1;try{await this.lfs.stat(o),s=!0}catch{}let{dir:c}=D(o);await this.withWriteLock(async()=>{c!==`/`&&await this.mkdirRecursiveUnlocked(c);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(o,t)}catch(e){if(c!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(c);try{await this.lfs.writeFile(o,t)}catch(e){throw P(e,i)}}else throw P(e,i)}try{await this.lfs.truncate?.(o,e)}catch(e){throw P(e,i)}}),this.watcher?.notify([{type:s?`modify`:`create`,path:o,entryType:`file`}])}async readDir(e){let t=E(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,t){let n=this.mountIndex.getDirectoryEntries(t.path,e);if(n!==void 0){let t=new Map;for(let e of n)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let r=t.relParts.join(`/`)||`/`,i;try{i=await t.backend.readDir(r)}catch(t){M(t,e)}let a=new Map;for(let e of i)a.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(a,e),[...a.values()]}async readDirLocal(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 P(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`}}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(e){let t,n=new Promise(e=>{t=e}),r=this._writeLock;this._writeLock=n,await r;try{return await e()}finally{t()}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=``;for(let e of t){n+=`/`+e;try{await this.lfs.mkdir(n)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw P(e,n)}}}async mkdir(e,t){let n=E(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){M(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}t?.recursive?await this.withWriteLock(()=>this.mkdirRecursiveUnlocked(n)):(await this.withWriteLock(async()=>{try{await this.lfs.mkdir(n)}catch(e){throw P(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]))}async rm(e,t){let r=E(e),i=this.findMount(r);if(i){if(i.relParts.length===0)throw new n(`EINVAL`,`cannot remove a mount point — use unmount`,r);let e;try{e=(await this.stat(r)).type}catch{}let a=i.relParts.join(`/`);try{await i.backend.remove(a,{recursive:t?.recursive})}catch(e){M(e,r)}this.watcher?.notify([{type:`delete`,path:r,entryType:e}]),this.mountIndex.notifyDelete(r);return}try{let e=await this.lfs.lstat(r);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(r):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(r):await this.lfs.rmdir(r):await this.lfs.unlink(r),await this.writeOpfsMetadataSidecar()})}catch(e){throw P(e,r)}this.watcher?.notify([{type:`delete`,path:r}])}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){let t=E(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.mtime}}catch(e){M(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}}catch(e){throw P(e,t)}}async exists(e){let t=E(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){let n=E(e),r=E(t),i;try{i=(await this.lstat(n)).type}catch{}try{await this.lfs.rename(n,r)}catch(e){throw P(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*H({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 n(`EISDIR`,`is a directory`,e);let r=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,r)}dirname(e){return D(E(e)).dir}basename(e){return D(E(e)).base}async symlink(e,t){let r=E(t);if(this.findMount(r))throw new n(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:i}=D(r);await this.withWriteLock(async()=>{i!==`/`&&await this.mkdirRecursiveUnlocked(i);try{await this.lfs.symlink(e,r)}catch(t){if(i!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(i);try{await this.lfs.symlink(e,r)}catch(e){throw P(e,r)}}else throw P(t,r)}await this.writeOpfsMetadataSidecar()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=E(e);try{return await this.lfs.readlink(t)}catch(e){throw P(e,t)}}async lstat(e){let t=E(e);if(this.findMount(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}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw P(e,t)}}async realpath(e){return R(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return z(this.lfs,e=>this.findMount(e)!==null,e)}};export{n as FsError,d as FsWatcher,T as MountIndex,j as RestrictedFS,K as VirtualFS,k as joinPath,E as normalizePath,O as pathSegments,G as resolveVfsBackendFromEnv,D as splitPath};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-0FRaZO2z.js","assets/rolldown-runtime-aKtaBQYM.js","assets/dist-Bj10RLrf.js","assets/mount-DMj9lhpQ.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-ugOWOUZ9.js","assets/base64-DpPqYZJF.js","assets/src-DoFhVmQT.js","assets/proxied-fetch-CfcFb0B0.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/types-idfTVsM8.js","assets/backend-local-smcj-_Ox.js","assets/tool-ui-DfXu6quJ.js","assets/logger-DDBAeTLF.js","assets/picker-approval-CdWaB1mR.js","assets/mount-picker-popup-Bs1o43Z5.js","assets/picker-popup-BvzmBsGL.js","assets/mount-table-store-CfQUN_2R.js","assets/mount-bridge-client-BWPRzAQ5.js","assets/port-bridge-client-DdolH4cw.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.js";import{t as n}from"./types-idfTVsM8.js";import{t as r}from"./backend-local-smcj-_Ox.js";import{a as i,i as a,n as o,t as s}from"./mount-table-store-CfQUN_2R.js";var c=t(`fs-watcher`),l=0;function u(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var d=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++l}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),c.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),c.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>u(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){c.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),c.debug(`All watchers disposed`)}get size(){return this.registrations.size}},f=t(`mount-index`),p=400,m=2e6,h=`SLICC_MOUNT_INDEX_MAX_DEPTH`,g=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,_=256,v=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function y(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>_?t.slice(0,_):t;return`${t.length}\u0001${n.join(``)}`}async function b(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function x(e,t){return e instanceof Map?e.get(t):e[t]}function S(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function C(e,t,n){let r=x(e,t);if(r===void 0||r.trim()===``)return n;let i=S(r);return i===void 0?(f.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function w(e){return{maxDepth:C(e,h,p),maxEntries:C(e,g,m)}}var T=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=w({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,f.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof v?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},f.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new v(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new v(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new v(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=y(n),a=r.get(i);if(a){for(let n of a)if(await b(n.handle,t))throw new v(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}};function E(e){if(!e||e===`/`)return`/`;e.startsWith(`/`)||(e=`/`+e);let t=e.split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return`/`+n.join(`/`)}function D(e){let t=E(e);if(t===`/`)return{dir:`/`,base:``};let n=t.lastIndexOf(`/`);return{dir:n===0?`/`:t.slice(0,n),base:t.slice(n+1)}}function O(e){let t=E(e);return t===`/`?[]:t.slice(1).split(`/`)}function k(...e){return E(e.join(`/`))}var A={"/dev/null":{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},j=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let i=e=>{let t=E(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(i),this.readOnlyPrefixes=n.map(i),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=E(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=E(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=E(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new n(`EACCES`,`permission denied`,E(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new n(`ENOENT`,`no such file or directory`,E(e));return t}catch(t){throw t instanceof n?t:new n(`ENOENT`,`no such file or directory`,E(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new n(`EACCES`,`permission denied`,E(e));return t}catch(t){throw t instanceof n?t:new n(`EACCES`,`permission denied`,E(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),r=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof n&&e.code===`EACCES`)throw e;return}let a=i+`/`+r;if(this.isWritable(a))return;let o=E(i)!==E(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new n(`EACCES`,`permission denied`,E(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let r=A[E(e)];if(r)return r.read(t);if(!this.isAllowedStrict(e))throw new n(`ENOENT`,`no such file or directory`,E(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=E(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=A[E(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new n(`ENOENT`,`no such file or directory`,E(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=E(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),i=t?r.length:r.length-1,a=``;for(let e=0;e<i;e++){a=a+`/`+r[e];let t=this.vfs.lstatSync(a);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=A[E(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=A[E(e)];return t?t.stat():!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=E(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof n?t:new n(`ENOENT`,`no such file or directory`,E(e))}if(!this.isAllowedStrict(t))throw new n(`ENOENT`,`no such file or directory`,E(e));return t}async exists(e){if(A[E(e)])return!0;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=A[E(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new n(`ENOENT`,`no such file or directory`,E(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(r)}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,r){let i=A[E(e)];if(i){i.write(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 n&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,r)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof n&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new n(`ENOENT`,`no such file or directory`,E(e));this.checkWrite(t);let r=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 n&&e.code===`EACCES`)throw e}return this.vfs.copyFile(r,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new n(`ENOENT`,`no such file or directory`,E(e));let t=await this.vfs.readlink(e),r;if(r=t.startsWith(`/`)?E(t):E(this.vfs.dirname(e)+`/`+t),!this.isAllowedStrict(r))throw new n(`ENOENT`,`no such file or directory`,E(e));return t}async lstat(e){let t=A[E(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new n(`ENOENT`,`no such file or directory`,E(e));let r=E(e),i=this.vfs.dirname(r),a=this.vfs.basename(r),o;if(i===r)o=i;else try{o=await this.vfs.realpath(i)}catch{throw new n(`ENOENT`,`no such file or directory`,r)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new n(`ENOENT`,`no such file or directory`,r);return this.vfs.lstat(s)}watch(e,t,r){if(!this.isAllowed(e))throw new n(`EACCES`,`permission denied`,E(e));let i=this.vfs.getWatcher();if(!i)throw new n(`EINVAL`,`no watcher configured`);return i.watch(E(e),t,r)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function M(e,t){if(e instanceof n){let r=`${e.code}: `,i=e.message;throw i.startsWith(r)&&(i=i.slice(r.length)),e.path&&i.endsWith(` '${e.path}'`)&&(i=i.slice(0,i.length-` '${e.path}'`.length)),new n(e.code,i,t)}throw e}var N=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`];function P(e,t){if(e instanceof n)return e;let r=e?.code;if(typeof r==`string`){let i=r;if(N.includes(i))return new n(i,(e instanceof Error?e.message:String(e))||i,t)}let i=e instanceof Error?e.message:String(e);return i.includes(`ENOENT`)?new n(`ENOENT`,`no such file or directory`,t):i.includes(`EEXIST`)?new n(`EEXIST`,`file already exists`,t):i.includes(`ENOTDIR`)?new n(`ENOTDIR`,`not a directory`,t):i.includes(`EISDIR`)?new n(`EISDIR`,`is a directory`,t):i.includes(`ENOTEMPTY`)?new n(`ENOTEMPTY`,`directory not empty`,t):i.includes(`ELOOP`)?new n(`ELOOP`,`too many levels of symbolic links`,t):new n(`EINVAL`,i,t)}async function F(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=P(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function I(e,t,n){let r;try{r=await e.readlink(t)}catch(e){throw P(e,n)}return r.startsWith(`/`)?E(r):E(k(D(t).dir,r))}async function L(e,t,r,i,a,o){let s=t===`/`?`/${r}`:`${t}/${r}`;for(;;){let t=await F(e,s,i,a);if(t===null||!t.isSymbolicLink())return{resolved:s,hops:o};if(++o>10)throw new n(`ELOOP`,`too many symbolic links encountered`,a);s=await I(e,s,a)}}async function R(e,t,n){let r=E(n);if(t(r))return r;let i=r.split(`/`).filter(Boolean),a=`/`,o=0;for(let t=0;t<i.length;t++){let n=await L(e,a,i[t],t===i.length-1,r,o);a=n.resolved,o=n.hops}return a}async function z(e,t,n){return t(n)?n:R(e,t,n)}function B(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 V(e,t){try{return await e(t)}catch{return t}}async function*H(e,t,n,r=0){let i=E(t);if(B(e.mountPoints,e.mountIndex,i)){let t=e.mountIndex.getFiles(i);if(t){for(let e of t)yield e;return}}let a=n??new Set;if(r>64||a.size>=1e5)return;let o=await V(t=>e.realpath(t),i);if(a.has(o))return;a.add(o);let s=await e.readDir(i);for(let t of s)yield*U(e,t,i===`/`?`/${t.name}`:`${i}/${t.name}`,a,r+1)}async function*U(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*W(e,n,r,i);return}yield*H(e,n,r,i)}async function*W(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*H(e,t,n,r))}catch{}}function G(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var K=class t{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 T;_writeLock=Promise.resolve();constructor(e,n,r,i){if(this.dbName=e,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?t.initOpfsBackend(this,i,n===!0):t.initMemoryBackend(this,e,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${e}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r).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(n,r,i){let a=r??await t.acquireOpfsHandle(n.dbName,i);await t.seedOpfsMetadataSidecarIfMissing(a);let[o,{WebAccess:s}]=await Promise.all([e(()=>import(`./dist-0FRaZO2z.js`).then(e=>e.t),__vite__mapDeps([0,1])),e(()=>import(`./dist-Bj10RLrf.js`),__vite__mapDeps([2,0,1]))]);await t.ensureRootMount(o);let c=`/__opfs__/${n.dbName}`,l=t.opfsBackends.get(n.dbName);if(l&&i){try{o.umount(c)}catch{}t.opfsBackends.delete(n.dbName),l=void 0}if(!l){let e=await o.resolveMountConfig({backend:s,handle:a,metadata:`/.metadata.json`});try{o.mount(c,e)}catch{}l={backendFs:e,refs:0},t.opfsBackends.set(n.dbName,l)}l.refs+=1,n.opfsBackendFs=l.backendFs.index?l.backendFs:null,n.opfsHandle=a,n.mountRoot=c,n.rawLfs=o.promises,n.rawLfsSync=o}static async initMemoryBackend(n,r,i){let a=await e(()=>import(`./dist-0FRaZO2z.js`).then(e=>e.t),__vite__mapDeps([0,1]));await t.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=t.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}t.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},t.memoryBackends.set(r,s)),s.refs+=1;try{a.mount(o,s.store)}catch{}n.mountRoot=o,n.rawLfs=a.promises,n.rawLfsSync=a,n.opfsBackendFs=null,n.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(e){return t.rootMountReady||=(async()=>{await e.configureSingle({backend:e.InMemory,label:`__vfs_root__`})})(),t.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(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let r=navigator.storage;if(!r?.getDirectory)throw new n(`EINVAL`,`OPFS is not available in this environment`);let i=await r.getDirectory();if(t)try{await i.removeEntry(e,{recursive:!0})}catch{}return i.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(e){return new t(e)}static async create(e){let n=e?.dbName??`browser-fs`,r=e?.wipe===!0,i=e?.backend??G(),a=new t(n,r,i);return await a._ready,r&&await s().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){if(this.backend!==`opfs`)return;let e=this.opfsBackendFs,t=this.opfsHandle;if(!e||!t)return;let n=JSON.stringify(e.index.toJSON()),r=await(await t.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await r.write(n),await r.close()}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=E(n);t.index.delete(e),t._handles?.delete(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let n=this.backend===`opfs`?t.opfsBackends:t.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await e(()=>import(`./dist-0FRaZO2z.js`).then(e=>e.t),__vite__mapDeps([0,1]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=E(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({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=E(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.statSync!=`function`||typeof n.lstatSync!=`function`||typeof n.readlinkSync!=`function`)return null;let r=t;for(let e=0;e<=10;e++){let e;try{e=n.lstatSync(r)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=n.readlinkSync(r)}catch{return null}r=t.startsWith(`/`)?E(t):E(k(D(r).dir,t))}return null}lstatSync(e){let t=E(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;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}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,r){let a=E(e);if(this.mountPoints.has(a))throw new n(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new n(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new n(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof n)||e.code!==`ENOENT`)throw e}let{dir:o}=D(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=w(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{await i({targetPath:a,descriptor:s,createdAt:Date.now()},t.kind===`local`?t.getHandle():void 0)}catch{}}async unmount(e){let t=E(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 a(t)}catch{}}async reconstructBackendFromDescriptor(t){switch(t.kind){case`local`:{let e=await o(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return r.fromHandle(e,{mountId:t.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await e(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-DMj9lhpQ.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([3,4,5,6,7,8,1,9,10,11,12,13,14,15,16,17,18,19,20])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i(t.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-DMj9lhpQ.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([3,4,5,6,7,8,1,9,10,11,12,13,14,15,16,17,18,19,20])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i()})}}}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}async mountInternal(e,t){let r=E(e);if(this.mountPoints.has(r))throw new n(`EEXIST`,`mount point is already mounted`,r);let{dir:i}=D(r);i!==`/`&&await this.mkdir(i,{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=E(e);if(!this.internalMounts.has(t))throw new n(`ENOENT`,`not an internal mount point`,t);let r=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await r?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let r=E(e),i=this.mountPoints.get(r);if(!i)throw new n(`ENOENT`,`not a mount point`,r);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(r,w(t?.env??{})),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){let r=E(e),i=this.findMount(r);if(i){if(i.relParts.length===0)throw new n(`EISDIR`,`is a directory`,r);let e=i.relParts.join(`/`);try{let n=await i.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){M(e,r)}}let a=await this.resolveSymlinks(r);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw P(e,r)}}async writeFile(e,t,r){let i=E(e),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new n(`EISDIR`,`is a directory`,i);let e=a.relParts.join(`/`),r=!1;try{await this.stat(i),r=!0}catch{}let o=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await a.backend.writeFile(e,o)}catch(e){M(e,i)}this.watcher?.notify([{type:r?`modify`:`create`,path:i,entryType:`file`}]),this.mountIndex.notifyWrite(i);return}let o;try{o=await this.resolveSymlinks(i)}catch{o=i}let s=!1;try{await this.lfs.stat(o),s=!0}catch{}let{dir:c}=D(o);await this.withWriteLock(async()=>{c!==`/`&&await this.mkdirRecursiveUnlocked(c);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(o,t)}catch(e){if(c!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(c);try{await this.lfs.writeFile(o,t)}catch(e){throw P(e,i)}}else throw P(e,i)}try{await this.lfs.truncate?.(o,e)}catch(e){throw P(e,i)}}),this.watcher?.notify([{type:s?`modify`:`create`,path:o,entryType:`file`}])}async readDir(e){let t=E(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,t){let n=this.mountIndex.getDirectoryEntries(t.path,e);if(n!==void 0){let t=new Map;for(let e of n)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let r=t.relParts.join(`/`)||`/`,i;try{i=await t.backend.readDir(r)}catch(t){M(t,e)}let a=new Map;for(let e of i)a.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(a,e),[...a.values()]}async readDirLocal(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 P(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`}}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(e){let t,n=new Promise(e=>{t=e}),r=this._writeLock;this._writeLock=n,await r;try{return await e()}finally{t()}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=``;for(let e of t){n+=`/`+e;try{await this.lfs.mkdir(n)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw P(e,n)}}}async mkdir(e,t){let n=E(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){M(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}t?.recursive?await this.withWriteLock(()=>this.mkdirRecursiveUnlocked(n)):(await this.withWriteLock(async()=>{try{await this.lfs.mkdir(n)}catch(e){throw P(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]))}async rm(e,t){let r=E(e),i=this.findMount(r);if(i){if(i.relParts.length===0)throw new n(`EINVAL`,`cannot remove a mount point — use unmount`,r);let e;try{e=(await this.stat(r)).type}catch{}let a=i.relParts.join(`/`);try{await i.backend.remove(a,{recursive:t?.recursive})}catch(e){M(e,r)}this.watcher?.notify([{type:`delete`,path:r,entryType:e}]),this.mountIndex.notifyDelete(r);return}try{let e=await this.lfs.lstat(r);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(r):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(r):await this.lfs.rmdir(r):await this.lfs.unlink(r),await this.writeOpfsMetadataSidecar()})}catch(e){throw P(e,r)}this.watcher?.notify([{type:`delete`,path:r}])}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){let t=E(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.mtime}}catch(e){M(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}}catch(e){throw P(e,t)}}async exists(e){let t=E(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){let n=E(e),r=E(t),i;try{i=(await this.lstat(n)).type}catch{}try{await this.lfs.rename(n,r)}catch(e){throw P(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*H({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 n(`EISDIR`,`is a directory`,e);let r=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,r)}dirname(e){return D(E(e)).dir}basename(e){return D(E(e)).base}async symlink(e,t){let r=E(t);if(this.findMount(r))throw new n(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:i}=D(r);await this.withWriteLock(async()=>{i!==`/`&&await this.mkdirRecursiveUnlocked(i);try{await this.lfs.symlink(e,r)}catch(t){if(i!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(i);try{await this.lfs.symlink(e,r)}catch(e){throw P(e,r)}}else throw P(t,r)}await this.writeOpfsMetadataSidecar()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=E(e);try{return await this.lfs.readlink(t)}catch(e){throw P(e,t)}}async lstat(e){let t=E(e);if(this.findMount(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}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw P(e,t)}}async realpath(e){return R(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return z(this.lfs,e=>this.findMount(e)!==null,e)}};export{n as FsError,d as FsWatcher,T as MountIndex,j as RestrictedFS,K as VirtualFS,k as joinPath,E as normalizePath,O as pathSegments,G as resolveVfsBackendFromEnv,D as splitPath};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./logger-LESFN7Hj.js";import{t as n}from"./backend-local-D4WZgy4J.js";import{t as r}from"./types-idfTVsM8.js";import{a as i,i as a,n as o,t as s}from"./mount-table-store-CTrzlrNn.js";import{i as c,n as l,r as u,t as d}from"./path-utils-DU6QhF_k.js";const f=t(`fs-watcher`);let p=0;function m(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var h=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++p}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),f.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),f.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>m(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){f.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),f.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const g=t(`mount-index`);var _=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function v(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>256?t.slice(0,256):t;return`${t.length}\u0001${n.join(``)}`}async function y(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function b(e,t){return e instanceof Map?e.get(t):e[t]}function x(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function S(e,t,n){let r=b(e,t);if(r===void 0||r.trim()===``)return n;let i=x(r);return i===void 0?(g.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function C(e){return{maxDepth:S(e,`SLICC_MOUNT_INDEX_MAX_DEPTH`,400),maxEntries:S(e,`SLICC_MOUNT_INDEX_MAX_ENTRIES`,2e6)}}var w=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=C({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,g.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof _?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},g.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new _(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new _(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new _(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=v(n),a=r.get(i);if(a){for(let n of a)if(await y(n.handle,t))throw new _(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}};const T=`/dev/null`,E=new Set([T]);function D(e){return E.has(e)}const O={[T]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}};var k=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let i=e=>{let t=l(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(i),this.readOnlyPrefixes=n.map(i),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=l(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new r(`EACCES`,`permission denied`,l(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new r(`EACCES`,`permission denied`,l(e));return t}catch(t){throw t instanceof r?t:new r(`EACCES`,`permission denied`,l(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let o=l(i)!==l(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new r(`EACCES`,`permission denied`,l(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=O[l(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=l(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=O[l(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(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=l(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),i=t?r.length:r.length-1,a=``;for(let e=0;e<i;e++){a=a+`/`+r[e];let t=this.vfs.lstatSync(a);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=O[l(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=O[l(e)];return t?t.stat():!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=l(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async exists(e){if(O[l(e)])return!0;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=O[l(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(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 i=O[l(e)];if(i){i.write(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 r&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(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 r&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let t=await this.vfs.readlink(e),n;if(n=t.startsWith(`/`)?l(t):l(this.vfs.dirname(e)+`/`+t),!this.isAllowedStrict(n))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async lstat(e){let t=O[l(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let n=l(e),i=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(i===n)o=i;else try{o=await this.vfs.realpath(i)}catch{throw new r(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new r(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new r(`EACCES`,`permission denied`,l(e));let i=this.vfs.getWatcher();if(!i)throw new r(`EINVAL`,`no watcher configured`);return i.watch(l(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function A(e,t){if(e instanceof r){let n=`${e.code}: `,i=e.message;throw i.startsWith(n)&&(i=i.slice(n.length)),e.path&&i.endsWith(` '${e.path}'`)&&(i=i.slice(0,i.length-` '${e.path}'`.length)),new r(e.code,i,t)}throw e}const j=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`];function M(e,t){if(e instanceof r)return e;let n=e?.code;if(typeof n==`string`){let i=n;if(j.includes(i))return new r(i,(e instanceof Error?e.message:String(e))||i,t)}let i=e instanceof Error?e.message:String(e);return i.includes(`ENOENT`)?new r(`ENOENT`,`no such file or directory`,t):i.includes(`EEXIST`)?new r(`EEXIST`,`file already exists`,t):i.includes(`ENOTDIR`)?new r(`ENOTDIR`,`not a directory`,t):i.includes(`EISDIR`)?new r(`EISDIR`,`is a directory`,t):i.includes(`ENOTEMPTY`)?new r(`ENOTEMPTY`,`directory not empty`,t):i.includes(`ELOOP`)?new r(`ELOOP`,`too many levels of symbolic links`,t):new r(`EINVAL`,i,t)}async function N(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=M(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function P(e,t,n){let r;try{r=await e.readlink(t)}catch(e){throw M(e,n)}return r.startsWith(`/`)?l(r):l(d(c(t).dir,r))}async function F(e,t,n,i,a,o){let s=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await N(e,s,i,a);if(t===null||!t.isSymbolicLink())return{resolved:s,hops:o};if(++o>10)throw new r(`ELOOP`,`too many symbolic links encountered`,a);s=await P(e,s,a)}}async function I(e,t,n){let r=l(n);if(t(r))return r;let i=r.split(`/`).filter(Boolean),a=`/`,o=0;for(let t=0;t<i.length;t++){let n=await F(e,a,i[t],t===i.length-1,r,o);a=n.resolved,o=n.hops}return a}async function L(e,t,n){return t(n)?n:I(e,t,n)}function R(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 z(e,t){try{return await e(t)}catch{return t}}async function*B(e,t,n,r=0){let i=l(t);if(R(e.mountPoints,e.mountIndex,i)){let t=e.mountIndex.getFiles(i);if(t){for(let e of t)yield e;return}}let a=n??new Set;if(r>64||a.size>=1e5)return;let o=await z(t=>e.realpath(t),i);if(a.has(o))return;a.add(o);let s=await e.readDir(i);for(let t of s)yield*V(e,t,i===`/`?`/${t.name}`:`${i}/${t.name}`,a,r+1)}async function*V(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*H(e,n,r,i);return}yield*B(e,n,r,i)}async function*H(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*B(e,t,n,r))}catch{}}function U(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var W=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 w;_writeLock=Promise.resolve();constructor(t,n,r,i){if(this.dbName=t,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).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 e.seedOpfsMetadataSidecarIfMissing(i);let[a,{WebAccess:o}]=await Promise.all([import(`./dist-CJ6ilPeJ.js`).then(e=>e.t),import(`./dist-BhEJb2Dl.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=await a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`});try{a.mount(s,n)}catch{}c={backendFs:n,refs:0},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-CJ6ilPeJ.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||=(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(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new r(`EINVAL`,`OPFS is not available in this environment`);let i=await n.getDirectory();if(t)try{await i.removeEntry(e,{recursive:!0})}catch{}return i.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??U(),a=new e(n,r,i);return await a._ready,r&&await s().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){if(this.backend!==`opfs`)return;let e=this.opfsBackendFs,t=this.opfsHandle;if(!e||!t)return;let n=JSON.stringify(e.index.toJSON()),r=await(await t.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await r.write(n),await r.close()}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=l(n);t.index.delete(e),t._handles?.delete(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}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-CJ6ilPeJ.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=l(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({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.statSync!=`function`||typeof n.lstatSync!=`function`||typeof n.readlinkSync!=`function`)return null;let r=t;for(let e=0;e<=10;e++){let e;try{e=n.lstatSync(r)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=n.readlinkSync(r)}catch{return null}r=t.startsWith(`/`)?l(t):l(d(c(r).dir,t))}return null}lstatSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;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}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,n){let a=l(e);if(this.mountPoints.has(a))throw new r(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new r(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new r(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof r)||e.code!==`ENOENT`)throw e}let{dir:o}=c(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=C(n?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{await i({targetPath:a,descriptor:s,createdAt:Date.now()},t.kind===`local`?t.getHandle():void 0)}catch{}}async unmount(e){let t=l(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 a(t)}catch{}}async reconstructBackendFromDescriptor(e){switch(e.kind){case`local`:{let t=await o(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return n.fromHandle(t,{mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-DqW1EKLo.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-DqW1EKLo.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}async mountInternal(e,t){let n=l(e);if(this.mountPoints.has(n))throw new r(`EEXIST`,`mount point is already mounted`,n);let{dir:i}=c(n);i!==`/`&&await this.mkdir(i,{recursive:!0});try{await this.lfs.mkdir(n)}catch{}this.mountPoints.set(n,t),this.internalMounts.add(n),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}async unmountInternal(e){let t=l(e);if(!this.internalMounts.has(t))throw new r(`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=l(e),i=this.mountPoints.get(n);if(!i)throw new r(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n,C(t?.env??{})),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){let n=l(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new r(`EISDIR`,`is a directory`,n);let e=i.relParts.join(`/`);try{let n=await i.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){A(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 M(e,n)}}async writeFile(e,t,n){let i=l(e),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new r(`EISDIR`,`is a directory`,i);let e=a.relParts.join(`/`),n=!1;try{await this.stat(i),n=!0}catch{}let o=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await a.backend.writeFile(e,o)}catch(e){A(e,i)}this.watcher?.notify([{type:n?`modify`:`create`,path:i,entryType:`file`}]),this.mountIndex.notifyWrite(i);return}let o;try{o=await this.resolveSymlinks(i)}catch{o=i}let s=!1;try{await this.lfs.stat(o),s=!0}catch{}let{dir:u}=c(o);await this.withWriteLock(async()=>{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(o,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(o,t)}catch(e){throw M(e,i)}}else throw M(e,i)}try{await this.lfs.truncate?.(o,e)}catch(e){throw M(e,i)}}),this.watcher?.notify([{type:s?`modify`:`create`,path:o,entryType:`file`}])}async readDir(e){let t=l(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,t){let n=this.mountIndex.getDirectoryEntries(t.path,e);if(n!==void 0){let t=new Map;for(let e of n)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let r=t.relParts.join(`/`)||`/`,i;try{i=await t.backend.readDir(r)}catch(t){A(t,e)}let a=new Map;for(let e of i)a.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(a,e),[...a.values()]}async readDirLocal(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 M(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`}}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(e){let t,n=new Promise(e=>{t=e}),r=this._writeLock;this._writeLock=n,await r;try{return await e()}finally{t()}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=``;for(let e of t){n+=`/`+e;try{await this.lfs.mkdir(n)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw M(e,n)}}}async mkdir(e,t){let n=l(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){A(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}t?.recursive?await this.withWriteLock(()=>this.mkdirRecursiveUnlocked(n)):(await this.withWriteLock(async()=>{try{await this.lfs.mkdir(n)}catch(e){throw M(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]))}async rm(e,t){let n=l(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new r(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let a=i.relParts.join(`/`);try{await i.backend.remove(a,{recursive:t?.recursive})}catch(e){A(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),await this.writeOpfsMetadataSidecar()})}catch(e){throw M(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){let t=l(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.mtime}}catch(e){A(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}}catch(e){throw M(e,t)}}async exists(e){let t=l(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){let n=l(e),r=l(t),i;try{i=(await this.lstat(n)).type}catch{}try{await this.lfs.rename(n,r)}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*B({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 r(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return c(l(e)).dir}basename(e){return c(l(e)).base}async symlink(e,t){let n=l(t);if(this.findMount(n))throw new r(`EINVAL`,`symlinks not supported on mounted filesystems`,n);let{dir:i}=c(n);await this.withWriteLock(async()=>{i!==`/`&&await this.mkdirRecursiveUnlocked(i);try{await this.lfs.symlink(e,n)}catch(t){if(i!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(i);try{await this.lfs.symlink(e,n)}catch(e){throw M(e,n)}}else throw M(t,n)}await this.writeOpfsMetadataSidecar()}),this.watcher?.notify([{type:`create`,path:n,entryType:`symlink`}])}async readlink(e){let t=l(e);try{return await this.lfs.readlink(t)}catch(e){throw M(e,t)}}async lstat(e){let t=l(e);if(this.findMount(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}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw M(e,t)}}async realpath(e){return I(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return L(this.lfs,e=>this.findMount(e)!==null,e)}},G=e({FsError:()=>r,FsWatcher:()=>h,MountIndex:()=>w,RestrictedFS:()=>k,VirtualFS:()=>W,joinPath:()=>d,normalizePath:()=>l,pathSegments:()=>u,resolveVfsBackendFromEnv:()=>U,splitPath:()=>c});export{h as a,D as i,W as n,k as r,G as t};
1
+ import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./logger-LESFN7Hj.js";import{t as n}from"./backend-local-D4WZgy4J.js";import{t as r}from"./types-idfTVsM8.js";import{a as i,i as a,n as o,t as s}from"./mount-table-store-CTrzlrNn.js";import{i as c,n as l,r as u,t as d}from"./path-utils-DU6QhF_k.js";const f=t(`fs-watcher`);let p=0;function m(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var h=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++p}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),f.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),f.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>m(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){f.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),f.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const g=t(`mount-index`);var _=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function v(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>256?t.slice(0,256):t;return`${t.length}\u0001${n.join(``)}`}async function y(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function b(e,t){return e instanceof Map?e.get(t):e[t]}function x(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function S(e,t,n){let r=b(e,t);if(r===void 0||r.trim()===``)return n;let i=x(r);return i===void 0?(g.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function C(e){return{maxDepth:S(e,`SLICC_MOUNT_INDEX_MAX_DEPTH`,400),maxEntries:S(e,`SLICC_MOUNT_INDEX_MAX_ENTRIES`,2e6)}}var w=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=C({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,g.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof _?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},g.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new _(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new _(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new _(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=v(n),a=r.get(i);if(a){for(let n of a)if(await y(n.handle,t))throw new _(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}};const T=`/dev/null`,E=new Set([T]);function D(e){return E.has(e)}const O={[T]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}};var k=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let i=e=>{let t=l(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(i),this.readOnlyPrefixes=n.map(i),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=l(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new r(`EACCES`,`permission denied`,l(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new r(`EACCES`,`permission denied`,l(e));return t}catch(t){throw t instanceof r?t:new r(`EACCES`,`permission denied`,l(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let o=l(i)!==l(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new r(`EACCES`,`permission denied`,l(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=O[l(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=l(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=O[l(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(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=l(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),i=t?r.length:r.length-1,a=``;for(let e=0;e<i;e++){a=a+`/`+r[e];let t=this.vfs.lstatSync(a);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=O[l(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=O[l(e)];return t?t.stat():!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=l(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async exists(e){if(O[l(e)])return!0;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=O[l(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(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 i=O[l(e)];if(i){i.write(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 r&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(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 r&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let t=await this.vfs.readlink(e),n;if(n=t.startsWith(`/`)?l(t):l(this.vfs.dirname(e)+`/`+t),!this.isAllowedStrict(n))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async lstat(e){let t=O[l(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let n=l(e),i=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(i===n)o=i;else try{o=await this.vfs.realpath(i)}catch{throw new r(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new r(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new r(`EACCES`,`permission denied`,l(e));let i=this.vfs.getWatcher();if(!i)throw new r(`EINVAL`,`no watcher configured`);return i.watch(l(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){return this.vfs.listMounts()}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function A(e,t){if(e instanceof r){let n=`${e.code}: `,i=e.message;throw i.startsWith(n)&&(i=i.slice(n.length)),e.path&&i.endsWith(` '${e.path}'`)&&(i=i.slice(0,i.length-` '${e.path}'`.length)),new r(e.code,i,t)}throw e}const j=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`];function M(e,t){if(e instanceof r)return e;let n=e?.code;if(typeof n==`string`){let i=n;if(j.includes(i))return new r(i,(e instanceof Error?e.message:String(e))||i,t)}let i=e instanceof Error?e.message:String(e);return i.includes(`ENOENT`)?new r(`ENOENT`,`no such file or directory`,t):i.includes(`EEXIST`)?new r(`EEXIST`,`file already exists`,t):i.includes(`ENOTDIR`)?new r(`ENOTDIR`,`not a directory`,t):i.includes(`EISDIR`)?new r(`EISDIR`,`is a directory`,t):i.includes(`ENOTEMPTY`)?new r(`ENOTEMPTY`,`directory not empty`,t):i.includes(`ELOOP`)?new r(`ELOOP`,`too many levels of symbolic links`,t):new r(`EINVAL`,i,t)}async function N(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=M(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function P(e,t,n){let r;try{r=await e.readlink(t)}catch(e){throw M(e,n)}return r.startsWith(`/`)?l(r):l(d(c(t).dir,r))}async function F(e,t,n,i,a,o){let s=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await N(e,s,i,a);if(t===null||!t.isSymbolicLink())return{resolved:s,hops:o};if(++o>10)throw new r(`ELOOP`,`too many symbolic links encountered`,a);s=await P(e,s,a)}}async function I(e,t,n){let r=l(n);if(t(r))return r;let i=r.split(`/`).filter(Boolean),a=`/`,o=0;for(let t=0;t<i.length;t++){let n=await F(e,a,i[t],t===i.length-1,r,o);a=n.resolved,o=n.hops}return a}async function L(e,t,n){return t(n)?n:I(e,t,n)}function R(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 z(e,t){try{return await e(t)}catch{return t}}async function*B(e,t,n,r=0){let i=l(t);if(R(e.mountPoints,e.mountIndex,i)){let t=e.mountIndex.getFiles(i);if(t){for(let e of t)yield e;return}}let a=n??new Set;if(r>64||a.size>=1e5)return;let o=await z(t=>e.realpath(t),i);if(a.has(o))return;a.add(o);let s=await e.readDir(i);for(let t of s)yield*V(e,t,i===`/`?`/${t.name}`:`${i}/${t.name}`,a,r+1)}async function*V(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*H(e,n,r,i);return}yield*B(e,n,r,i)}async function*H(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*B(e,t,n,r))}catch{}}function U(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var W=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 w;_writeLock=Promise.resolve();constructor(t,n,r,i){if(this.dbName=t,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).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 e.seedOpfsMetadataSidecarIfMissing(i);let[a,{WebAccess:o}]=await Promise.all([import(`./dist-CJ6ilPeJ.js`).then(e=>e.t),import(`./dist-BhEJb2Dl.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=await a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`});try{a.mount(s,n)}catch{}c={backendFs:n,refs:0},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-CJ6ilPeJ.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||=(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(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new r(`EINVAL`,`OPFS is not available in this environment`);let i=await n.getDirectory();if(t)try{await i.removeEntry(e,{recursive:!0})}catch{}return i.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??U(),a=new e(n,r,i);return await a._ready,r&&await s().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){if(this.backend!==`opfs`)return;let e=this.opfsBackendFs,t=this.opfsHandle;if(!e||!t)return;let n=JSON.stringify(e.index.toJSON()),r=await(await t.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await r.write(n),await r.close()}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=l(n);t.index.delete(e),t._handles?.delete(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}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-CJ6ilPeJ.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=l(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({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.statSync!=`function`||typeof n.lstatSync!=`function`||typeof n.readlinkSync!=`function`)return null;let r=t;for(let e=0;e<=10;e++){let e;try{e=n.lstatSync(r)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=n.readlinkSync(r)}catch{return null}r=t.startsWith(`/`)?l(t):l(d(c(r).dir,t))}return null}lstatSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;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}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,n){let a=l(e);if(this.mountPoints.has(a))throw new r(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new r(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new r(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof r)||e.code!==`ENOENT`)throw e}let{dir:o}=c(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=C(n?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{await i({targetPath:a,descriptor:s,createdAt:Date.now()},t.kind===`local`?t.getHandle():void 0)}catch{}}async unmount(e){let t=l(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 a(t)}catch{}}async reconstructBackendFromDescriptor(e){switch(e.kind){case`local`:{let t=await o(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return n.fromHandle(t,{mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-DnOOuthV.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-DnOOuthV.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}async mountInternal(e,t){let n=l(e);if(this.mountPoints.has(n))throw new r(`EEXIST`,`mount point is already mounted`,n);let{dir:i}=c(n);i!==`/`&&await this.mkdir(i,{recursive:!0});try{await this.lfs.mkdir(n)}catch{}this.mountPoints.set(n,t),this.internalMounts.add(n),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}async unmountInternal(e){let t=l(e);if(!this.internalMounts.has(t))throw new r(`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=l(e),i=this.mountPoints.get(n);if(!i)throw new r(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n,C(t?.env??{})),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){let n=l(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new r(`EISDIR`,`is a directory`,n);let e=i.relParts.join(`/`);try{let n=await i.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){A(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 M(e,n)}}async writeFile(e,t,n){let i=l(e),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new r(`EISDIR`,`is a directory`,i);let e=a.relParts.join(`/`),n=!1;try{await this.stat(i),n=!0}catch{}let o=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await a.backend.writeFile(e,o)}catch(e){A(e,i)}this.watcher?.notify([{type:n?`modify`:`create`,path:i,entryType:`file`}]),this.mountIndex.notifyWrite(i);return}let o;try{o=await this.resolveSymlinks(i)}catch{o=i}let s=!1;try{await this.lfs.stat(o),s=!0}catch{}let{dir:u}=c(o);await this.withWriteLock(async()=>{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(o,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(o,t)}catch(e){throw M(e,i)}}else throw M(e,i)}try{await this.lfs.truncate?.(o,e)}catch(e){throw M(e,i)}}),this.watcher?.notify([{type:s?`modify`:`create`,path:o,entryType:`file`}])}async readDir(e){let t=l(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,t){let n=this.mountIndex.getDirectoryEntries(t.path,e);if(n!==void 0){let t=new Map;for(let e of n)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let r=t.relParts.join(`/`)||`/`,i;try{i=await t.backend.readDir(r)}catch(t){A(t,e)}let a=new Map;for(let e of i)a.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(a,e),[...a.values()]}async readDirLocal(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 M(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`}}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(e){let t,n=new Promise(e=>{t=e}),r=this._writeLock;this._writeLock=n,await r;try{return await e()}finally{t()}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=``;for(let e of t){n+=`/`+e;try{await this.lfs.mkdir(n)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw M(e,n)}}}async mkdir(e,t){let n=l(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){A(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}t?.recursive?await this.withWriteLock(()=>this.mkdirRecursiveUnlocked(n)):(await this.withWriteLock(async()=>{try{await this.lfs.mkdir(n)}catch(e){throw M(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]))}async rm(e,t){let n=l(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new r(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let a=i.relParts.join(`/`);try{await i.backend.remove(a,{recursive:t?.recursive})}catch(e){A(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),await this.writeOpfsMetadataSidecar()})}catch(e){throw M(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){let t=l(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.mtime}}catch(e){A(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}}catch(e){throw M(e,t)}}async exists(e){let t=l(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){let n=l(e),r=l(t),i;try{i=(await this.lstat(n)).type}catch{}try{await this.lfs.rename(n,r)}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*B({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 r(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return c(l(e)).dir}basename(e){return c(l(e)).base}async symlink(e,t){let n=l(t);if(this.findMount(n))throw new r(`EINVAL`,`symlinks not supported on mounted filesystems`,n);let{dir:i}=c(n);await this.withWriteLock(async()=>{i!==`/`&&await this.mkdirRecursiveUnlocked(i);try{await this.lfs.symlink(e,n)}catch(t){if(i!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(i);try{await this.lfs.symlink(e,n)}catch(e){throw M(e,n)}}else throw M(t,n)}await this.writeOpfsMetadataSidecar()}),this.watcher?.notify([{type:`create`,path:n,entryType:`symlink`}])}async readlink(e){let t=l(e);try{return await this.lfs.readlink(t)}catch(e){throw M(e,t)}}async lstat(e){let t=l(e);if(this.findMount(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}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw M(e,t)}}async realpath(e){return I(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return L(this.lfs,e=>this.findMount(e)!==null,e)}},G=e({FsError:()=>r,FsWatcher:()=>h,MountIndex:()=>w,RestrictedFS:()=>k,VirtualFS:()=>W,joinPath:()=>d,normalizePath:()=>l,pathSegments:()=>u,resolveVfsBackendFromEnv:()=>U,splitPath:()=>c});export{h as a,D as i,W as n,k as r,G as t};