sliccy 6.34.0 → 6.35.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/node-server/_shared/index.d.ts +1 -0
- package/dist/node-server/_shared/index.d.ts.map +1 -1
- package/dist/node-server/_shared/index.js +1 -0
- package/dist/node-server/_shared/index.js.map +1 -1
- package/dist/node-server/_shared/slicc-app-url.d.ts +30 -0
- package/dist/node-server/_shared/slicc-app-url.d.ts.map +1 -0
- package/dist/node-server/_shared/slicc-app-url.js +76 -0
- package/dist/node-server/_shared/slicc-app-url.js.map +1 -0
- package/dist/node-server/_shared/tray-sync-protocol.d.ts +58 -3
- package/dist/node-server/_shared/tray-sync-protocol.d.ts.map +1 -1
- package/dist/node-server/_shared/tray-sync-protocol.js +5 -3
- package/dist/node-server/_shared/tray-sync-protocol.js.map +1 -1
- package/dist/ui/assets/{account-store-C5MkHEZ9.js → account-store-DWX-EZHx.js} +2 -2
- package/dist/ui/assets/{account-store-RKZ1rsSS.js → account-store-fsZiMtXd.js} +3 -3
- package/dist/ui/assets/{adobe-BbmLhdeR.js → adobe-CMYfdTV_.js} +2 -2
- package/dist/ui/assets/{adobe-WsyqF5WB.js → adobe-LRe2nlQ-.js} +1 -1
- package/dist/ui/assets/{apply-layout-C4EHp4lG.js → apply-layout-LlDO9Nk8.js} +1 -1
- package/dist/ui/assets/{apps-BONd6Adw.js → apps-XUz4UHJy.js} +1 -1
- package/dist/ui/assets/{azure-openai-CbCyIfSb.js → azure-openai-B7qn6krc.js} +1 -1
- package/dist/ui/assets/{azure-openai-9zlWs9VO.js → azure-openai-vSDrXKCz.js} +1 -1
- package/dist/ui/assets/{cerebras-vU4kGSDM.js → cerebras-DgXSeCJt.js} +1 -1
- package/dist/ui/assets/{cerebras-DmvjfElk.js → cerebras-u8ZWzxTB.js} +1 -1
- package/dist/ui/assets/composer-speech-CNhvMpkj.js +1 -0
- package/dist/ui/assets/{connect-surface-GR1v14Hc.js → connect-surface-CKjmFE_I.js} +1 -1
- package/dist/ui/assets/{dip-rdFXauwM.js → dip-DReIJmS8.js} +1 -1
- package/dist/ui/assets/dist-Ca06zVsb.js +2 -0
- package/dist/ui/assets/dist-sUBuiXIF.js +2 -0
- package/dist/ui/assets/fs-CqrpSNTX.js +1 -0
- package/dist/ui/assets/fs-VCwbgYvh.js +2 -0
- package/dist/ui/assets/github-B5DdlAQU.js +2 -0
- package/dist/ui/assets/github-CBhxlF7p.js +1 -0
- package/dist/ui/assets/{github-copilot-X15xvS2M.js → github-copilot-Bk_IBZCm.js} +1 -1
- package/dist/ui/assets/{github-copilot-C4eRlMBG.js → github-copilot-CBNhncDi.js} +1 -1
- package/dist/ui/assets/{github-install-CkAgg36g.js → github-install-B3ZM7IrG.js} +1 -1
- package/dist/ui/assets/{github-zip-DbDHaWND.js → github-zip-DaPqIt4B.js} +1 -1
- package/dist/ui/assets/hear-C4KEOBVf.js +1 -0
- package/dist/ui/assets/hear-krvcqhL7.js +1 -0
- package/dist/ui/assets/{kernel-worker-I0OXrVF9.js → kernel-worker-DQl7D0WI.js} +448 -448
- package/dist/ui/assets/{local-llm-Szt9yM5f.js → local-llm-B1ibS4CJ.js} +1 -1
- package/dist/ui/assets/{local-llm-DJ3sMcsp.js → local-llm-BlWvSasC.js} +1 -1
- package/dist/ui/assets/{main-CGZ6fL1-.js → main-C1z-umpk.js} +3 -3
- package/dist/ui/assets/{mount-BKO4sT5Q.js → mount-8csnltQ9.js} +1 -1
- package/dist/ui/assets/{mount-CWKoVdHH.js → mount-CxmnNZsY.js} +2 -2
- package/dist/ui/assets/{mount-recovery-BDG3OFSI.js → mount-recovery-BK3xkz-a.js} +1 -1
- package/dist/ui/assets/{new-session-BezQ3TUX.js → new-session-C1dKxso_.js} +2 -2
- package/dist/ui/assets/{oauth-bootstrap-CRIyd41E.js → oauth-bootstrap-BioadW_t.js} +2 -2
- package/dist/ui/assets/oauth-service-Dmnx-pbE.js +1 -0
- package/dist/ui/assets/oauth-service-a6YE6xTR.js +1 -0
- package/dist/ui/assets/{openai-codex-DWjPFtj6.js → openai-codex-BZ1L8fpb.js} +1 -1
- package/dist/ui/assets/{openai-codex-DocXqzaV.js → openai-codex-DKlx0_yo.js} +1 -1
- package/dist/ui/assets/{openrouter-7EU5njOl.js → openrouter-CV3xKx85.js} +1 -1
- package/dist/ui/assets/{openrouter-DPxRUZWd.js → openrouter-IauFwJCr.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-BYS83wR9.js → openrouter-oauth-BiKNscbx.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-DmWe19ka.js → openrouter-oauth-C8WqNElY.js} +1 -1
- package/dist/ui/assets/panel-rpc-handlers-B7-5MvpQ.js +2 -0
- package/dist/ui/assets/{panelize-shell-CgDNoGLr.js → panelize-shell-Bo3jE0rP.js} +1 -1
- package/dist/ui/assets/permissions-surface-registry-BqPdUk9w.js +1 -0
- package/dist/ui/assets/permissions-surface-registry-CilCRwhh.js +1 -0
- package/dist/ui/assets/{provider-ClOlQuX4.js → provider-Bss6JSnT.js} +2 -2
- package/dist/ui/assets/{provider-B7BFsjld.js → provider-hQNT4vZC.js} +1 -1
- package/dist/ui/assets/{provider-settings-D7mEx6UA.js → provider-settings-DRzBx_K-.js} +2 -2
- package/dist/ui/assets/{provider-settings-XsnsrFeJ.js → provider-settings-LcSPuWPj.js} +1 -1
- package/dist/ui/assets/provider-store-access-BZp12OD3.js +1 -0
- package/dist/ui/assets/{provider-store-access-vfCs86Yg.js → provider-store-access-Ci97F5qf.js} +2 -2
- package/dist/ui/assets/{providers-CCMuUgF2.js → providers-CC3HjAlh.js} +1 -1
- package/dist/ui/assets/{providers-DK4B7dOl.js → providers-CvRdyDpX.js} +2 -2
- package/dist/ui/assets/{quick-llm-M4yYAaET.js → quick-llm-BsKuuErB.js} +1 -1
- package/dist/ui/assets/{redirect-uri-BFmzKMz6.js → redirect-uri-D02-fMO2.js} +1 -1
- package/dist/ui/assets/{remote-terminal-view-DqYuVTcF.js → remote-terminal-view-2Wk02uVb.js} +1 -1
- package/dist/ui/assets/{session-freezer-pW1DX6xd.js → session-freezer-AVMhPlXu.js} +2 -2
- package/dist/ui/assets/{setup-feature-flags-remote-Cv2rKxim.js → setup-feature-flags-remote-B1tLs0mW.js} +1 -1
- package/dist/ui/assets/{setup-standalone-prelude-jrjkDz5j.js → setup-standalone-prelude-DYYcXOyR.js} +1 -1
- package/dist/ui/assets/{setup-sudo-vVO0OdGl.js → setup-sudo-CCOhbwTK.js} +2 -2
- package/dist/ui/assets/{skills-Br_jQZJ0.js → skills-C9XJE6Cb.js} +1 -1
- package/dist/ui/assets/slicc-app-url-BsBryEhn.js +1 -0
- package/dist/ui/assets/{store-CgGJaImt.js → store-DLosooX2.js} +1 -1
- package/dist/ui/assets/{store-B7QzRU72.js → store-RBIStgRQ.js} +1 -1
- package/dist/ui/assets/{sudo-BUOdLgcY.js → sudo-CX6L-imR.js} +1 -1
- package/dist/ui/assets/tab-teleport-CLc1Tuqi.js +1 -0
- package/dist/ui/assets/teleport-storage-Beud1T6_.js +31 -0
- package/dist/ui/assets/{tray-sync-protocol-BoMM1sx5.js → tray-sync-protocol-y3ZAs0Go.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-LdVdChpr.js → upgrade-detection-CUghvK-5.js} +1 -1
- package/dist/ui/assets/{wc-attach-GJkf0zy_.js → wc-attach-CQ73n67L.js} +1 -1
- package/dist/ui/assets/wc-browser-BTGpaihO.js +1 -0
- package/dist/ui/assets/{wc-extension-CNo8AtRj.js → wc-extension-CPus6AG_.js} +2 -2
- package/dist/ui/assets/wc-follower-CJ0D6nJ6.js +17 -0
- package/dist/ui/assets/{wc-live-B_RZbCUg.js → wc-live-CPgy6Rt3.js} +3 -3
- package/dist/ui/assets/{wc-nav-DhQ2oW5i.js → wc-nav-CTdoUJsb.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-Bv2xKDs3.js → wc-onboarding-CgiUSi7F.js} +2 -2
- package/dist/ui/assets/{wc-permissions-8LUp20Jr.js → wc-permissions-iqdYkwde.js} +3 -3
- package/dist/ui/assets/wc-permissions-registry-BVc_OAkS.js +1 -0
- package/dist/ui/assets/wc-permissions-registry-DfoogAy3.js +1 -0
- package/dist/ui/assets/{wc-placeholder-2UVmNZT9.js → wc-placeholder-BMh4Tisi.js} +2 -2
- package/dist/ui/assets/{wc-settings-D9pDxr9U.js → wc-settings-F06K4Jl2.js} +2 -2
- package/dist/ui/assets/{wc-shell-DOdo4DpA.js → wc-shell-CdxYnLU8.js} +2 -2
- package/dist/ui/assets/{wc-sprinkles-BvKDzsSE.js → wc-sprinkles-TY8z4iwr.js} +2 -2
- package/dist/ui/assets/wc-tray-ClWTrIkP.js +2 -0
- package/dist/ui/assets/wc-tray-scoops-Bpcyy0qK.js +5 -0
- package/dist/ui/assets/{xai-grok-BaM7bzLG.js → xai-grok-B-YVuGaO.js} +1 -1
- package/dist/ui/assets/{xai-grok-CMubzNz2.js → xai-grok-DX8mvf4y.js} +1 -1
- package/dist/ui/index.html +6 -6
- package/dist/ui/llm-proxy-sw.js +1 -1
- package/dist/ui/packages/webapp/index.html +6 -6
- package/package.json +1 -1
- package/dist/ui/assets/composer-speech-Cn93D0hw.js +0 -1
- package/dist/ui/assets/dist-B3IaYEkN.js +0 -2
- package/dist/ui/assets/dist-Dc9ToRIQ.js +0 -2
- package/dist/ui/assets/fs-D8OsPNXu.js +0 -1
- package/dist/ui/assets/fs-DSaaO4iU.js +0 -2
- package/dist/ui/assets/github-2XuRvnna.js +0 -1
- package/dist/ui/assets/github-HVBSJFUW.js +0 -2
- package/dist/ui/assets/hear-B68rghJ6.js +0 -1
- package/dist/ui/assets/hear-BGjelK9s.js +0 -1
- package/dist/ui/assets/oauth-service-BVNxhxJP.js +0 -1
- package/dist/ui/assets/oauth-service-CeFviz7O.js +0 -1
- package/dist/ui/assets/panel-rpc-handlers-CLCrw7o4.js +0 -2
- package/dist/ui/assets/provider-store-access-DyhfYYSN.js +0 -1
- package/dist/ui/assets/wc-browser-BQYjgdk8.js +0 -1
- package/dist/ui/assets/wc-follower-CBJpceTk.js +0 -17
- package/dist/ui/assets/wc-permissions-registry-DHel9S61.js +0 -1
- package/dist/ui/assets/wc-permissions-registry-Dcdmzs0U.js +0 -1
- package/dist/ui/assets/wc-tray-CMIZkjOE.js +0 -2
- package/dist/ui/assets/wc-tray-scoops-CwSRVd7s.js +0 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./panel-rpc-BPwAqRch.js";import{K as t,d as n,y as r,z as i}from"./account-store-C5MkHEZ9.js";import{a}from"./diagnostics-DN_idNHx.js";import{a as o,d as s,f as c,i as l,o as u,p as d,s as f}from"./bedrock-camp-CFmElpzZ.js";import{a as p,r as m,s as h,t as g}from"./legacy-api-aliases-BVP0Ho8x.js";import{n as _}from"./llm-session-id-ZObKEXzb.js";import{n as v,t as ee}from"./silent-renew-backoff-BrAZcbzt.js";import{getOAuthPageOrigin as te}from"./oauth-service-BVNxhxJP.js";import"./provider-settings-XsnsrFeJ.js";var ne={proxyEndpoint:`https://adobe-llm-proxy.paolo-moz.workers.dev`,redirectUri:`https://www.sliccy.ai/auth/callback`,extensionRedirectUri:`https://akjjllgokmbgpbdbmafpiefnhidlmbgf.chromiumapp.org/adobe`};function re(e,t){return o(e,t)}function y(e,t,n){return e!==`xhigh`||!t?e:f(t,n)?`xhigh`:u(t,n)?`max`:`high`}function ie(e,t){let n=e?t?.thinkingLevelMap?.[e]:void 0;return y((()=>{if(typeof n==`string`)return n;switch(e){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`xhigh`:return`xhigh`;default:return`high`}})(),t?.id,t?.name)}function ae(e,t){return async(n,r)=>{let i=t?await t(n,r)??n:n,a=i.thinking;return a&&a.type===`enabled`&&(i.thinking={type:`adaptive`,...a.display===void 0?{}:{display:a.display}},i.output_config={...i.output_config??{},effort:e}),i}}function b(e,t){if(!re(e.id,e.name))return t;let n=t,r=y(n.effort??ie(n.reasoning,e),e.id,e.name);return{...t,onPayload:ae(r,n.onPayload)}}function oe(e,t){let n={id:e.id,name:e.name??e.id},r=t?.api??e.api,i=t?.context_window??e.context_window,a=t?.max_tokens??e.max_tokens,o=t?.reasoning??e.reasoning,s=t?.input??e.input;r&&(n.api=r),i!==void 0&&(n.context_window=i),a!==void 0&&(n.max_tokens=a),o!==void 0&&(n.reasoning=o),s&&(n.input=s);let c=t?.cost??e.cost;return c&&(n.cost=c),/haiku/i.test(e.id)&&(n.compat={supportsEagerToolInputStreaming:!1}),/sonnet-5\b/i.test(e.id)&&!n.thinkingLevelMap&&(n.thinkingLevelMap={xhigh:`xhigh`}),n}const x=Object.assign({"/packages/webapp/providers/adobe-config.json":ne})[`/packages/webapp/providers/adobe-config.json`]??{clientId:``,proxyEndpoint:``,scopes:`openid,profile,email`};function S(){let e=r(`adobe`);if(e)return e.replace(/\/$/,``);if(x.proxyEndpoint)return x.proxyEndpoint.replace(/\/$/,``);throw Error(`Adobe proxy endpoint not configured — set it in Settings or adobe-config.json`)}const C=new Map,w=new Map,T=`slicc-adobe-models`;function E(e){try{localStorage.setItem(T,JSON.stringify(e))}catch{}}async function D(e){let t=C.get(e);if(t)return t;try{let t=await fetch(`${e}/v1/config`,{headers:{[W]:`6.34.0`}});if(t.ok){let n=await t.json();return C.set(e,n),n}console.warn(`[adobe] Proxy /v1/config returned ${t.status}, falling back to build-time config`)}catch(e){console.warn(`[adobe] Failed to fetch proxy config:`,e instanceof Error?e.message:String(e))}return{}}function O(e){let t=e.clientId||x.clientId;if(!t)throw Error(`Could not determine IMS client ID — proxy /v1/config did not return one and adobe-config.json is empty`);return t}function k(e){return e.scopes||x.scopes}function A(e){return e.imsEnvironment||x.imsEnvironment||`prod`}const j={prod:`https://ims-na1.adobelogin.com`,stg1:`https://ims-na1-stg1.adobelogin.com`};function M(e){return j[e??x.imsEnvironment??`prod`]??j.prod}const N=typeof chrome<`u`&&!!chrome?.runtime?.id;function P(){return n().find(e=>e.providerId===`adobe`)}async function se(e,t){try{let n=await fetch(`${M(t)}/ims/userinfo/v2`,{headers:{Authorization:`Bearer ${e}`}});if(n.ok){let e=await n.json();return{name:e.displayName||e.name||e.email,avatar:e.picture||e.avatar_url}}console.warn(`[adobe] User profile fetch returned ${n.status}, account will have no display name`)}catch(e){console.warn(`[adobe] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function F(e){let t=e.indexOf(`#`);if(t<0)return null;let n=new URLSearchParams(e.slice(t+1)),r=n.get(`access_token`);return r?{accessToken:r,expiresIn:parseInt(n.get(`expires_in`)??`86400`,10),scope:n.get(`scope`)??void 0}:null}const I={id:`adobe`,name:`Adobe`,description:`Claude via Adobe — login with your Adobe ID`,requiresApiKey:!1,requiresBaseUrl:!x.proxyEndpoint,baseUrlPlaceholder:`https://your-proxy.example.com`,baseUrlDescription:`Anthropic-compatible proxy endpoint`,isOAuth:!0,defaultModelId:`sonnet`,oauthTokenDomains:[`ims-na1.adobelogin.com`,`ims-na1-stg1.adobelogin.com`,`*.adobelogin.com`,`*.adobe.io`,`firefall.adobe.io`,`admin.hlx.page`,`admin.hlx.live`,`admin.aem.page`,`admin.aem.live`],getModelIds:()=>{let e=e=>oe(e,w.get(e.id));for(let t of Q.values())if(t.length){let n=t.map(t=>e({id:t.id,name:t.name??t.id,reasoning:t.reasoning,input:t.input,cost:t.cost}));return E(n),n}for(let t of C.values())if(t.models?.length)return t.models.map(t=>e(t));try{let e=localStorage.getItem(T);if(e){let t=JSON.parse(e);if(t.length)return t}}catch{}return[{id:`claude-sonnet-4-6`,name:`Claude Sonnet 4.6`}]},onOAuthLogin:async(e,t,n)=>{let r=S(),a=await D(r),o=O(a),s=k(a),c=A(a),l=N?null:await te(),u=N?null:v({pageHref:l.href,pageOrigin:l.origin,configuredRedirectUri:x.redirectUri},()=>crypto.randomUUID()),d=N?x.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:u.redirectUri,f=u?.oauthState,p=u?.expectedNonce??null,m=new URLSearchParams({client_id:o,scope:s,response_type:`token`,redirect_uri:d});f&&m.set(`state`,f),n?.forceReauth&&m.set(`prompt`,`login`);let h=await e(`${M(c)}/ims/authorize/v2?${m}`);if(!h)return;if(p&&h)try{if(new URL(h).searchParams.get(`nonce`)!==p){console.error(`[adobe] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let g=F(h);if(!g){console.error(`[adobe] Could not extract token from redirect URL`);return}let _=await se(g.accessToken,c);await i({providerId:`adobe`,accessToken:g.accessToken,tokenExpiresAt:Date.now()+g.expiresIn*1e3,userName:_.name,userAvatar:_.avatar,scopes:g.scope,baseUrl:x.proxyEndpoint?void 0:r}),await $().catch(e=>console.warn(`[adobe] Failed to fetch models after login:`,e instanceof Error?e.message:String(e))),t()},onOAuthLogout:async()=>{let e=P();if(e?.accessToken)try{let t=C.values().next().value??{},n=t.clientId||x.clientId,r=A(t);if(n){let t=await fetch(`${M(r)}/ims/revoke`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({token:e.accessToken,token_type_hint:`access_token`,client_id:n})});t.ok||console.warn(`[adobe] Token revocation returned ${t.status}, token may still be valid server-side`)}}catch(e){console.warn(`[adobe] Failed to revoke token:`,e instanceof Error?e.message:String(e))}await i({providerId:`adobe`,accessToken:``})},onSilentRenew:async()=>P()?.accessToken?z():null,refreshModels:async e=>{await $(e);let t=I.getModelIds?.();t?.length&&E(t)}};let L=null;const ce=ee();async function R(){let e=P();if(!e?.accessToken)throw Error(`Not logged in to Adobe — please log in first`);if((e.tokenExpiresAt??0)-Date.now()>6e4)return e.accessToken;console.log(`[adobe] Token expired or expiring soon, attempting silent renewal...`);let t=await ce.run(()=>z());if(t)return t;let n=P();if((n?.tokenExpiresAt??0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`Adobe session expired — please log in again`)}function le(){let e=P();return!e?.tokenExpiresAt||Date.now()>e.tokenExpiresAt-6e4}async function z(){if(typeof window>`u`){let t=e();if(!t)return null;try{let{accessToken:e}=await t.call(`silent-renew`,{providerId:`adobe`},{timeoutMs:13e4});return e}catch(e){return console.warn(`[adobe] worker→page silent-renew bridge failed:`,e instanceof Error?e.message:String(e)),null}}return L||(L=U().finally(()=>{L=null}),L)}function B(e,t){let n=O(t),r=k(t),i=A(t),a=N?null:v({pageHref:window.location.href,pageOrigin:window.location.origin,configuredRedirectUri:x.redirectUri},()=>crypto.randomUUID()),o=N?x.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:a.redirectUri,s=a?.oauthState,c=a?.expectedNonce??null,l=new URLSearchParams({client_id:n,scope:r,response_type:`token`,redirect_uri:o,prompt:`none`});return s&&l.set(`state`,s),{authorizeUrl:`${M(i)}/ims/authorize/v2?${l}`,expectedNonce:c,proxyEndpoint:e}}function V(e,t){if(!t)return!0;try{if(new URL(e).searchParams.get(`nonce`)!==t)return console.error(`[adobe] OAuth nonce mismatch — possible CSRF`),!1}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}return!0}async function H(e,t){let n=P();await i({providerId:`adobe`,accessToken:e.accessToken,tokenExpiresAt:Date.now()+e.expiresIn*1e3,userName:n?.userName,userAvatar:n?.userAvatar,scopes:e.scope,baseUrl:x.proxyEndpoint?void 0:t})}async function U(){try{let e=S(),{authorizeUrl:t,expectedNonce:n}=B(e,await D(e)),{createOAuthLauncher:r}=await import(`./oauth-service-BVNxhxJP.js`),i=await r()(t,{interactive:!1});if(!i||!V(i,n))return null;let a=F(i);return a?(await H(a,e),console.log(`[adobe] Token renewed silently`),await $().catch(e=>console.warn(`[adobe] Failed to refresh models after silent renewal:`,e instanceof Error?e.message:String(e))),a.accessToken):null}catch(e){return console.warn(`[adobe] Silent renewal error:`,e instanceof Error?e.message:String(e)),null}}const W=`X-Slicc-Version`;function G(e){let t={};if(e.headers)for(let[n,r]of Object.entries(e.headers))n.toLowerCase()!==`x-slicc-version`&&(t[n]=r);return t[W]=`6.34.0`,{...e,headers:t}}const K=new Set;function q(e,t){if(e.headers){for(let[t,n]of Object.entries(e.headers))if(t.toLowerCase()===`x-session-id`&&n!=null)return e}return K.has(t)||(K.add(t),console.warn(`[adobe] Missing X-Session-Id from ${t} — using daily fallback. Attach an X-Session-Id header at the call site (see scoop-context.ts streamWithSessionId or docs/pitfalls.md).`)),{...e,headers:{...e.headers??{},"X-Session-Id":_(`adobe-provider-fallback`)}}}function ue(){K.clear()}function J(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:`adobe-anthropic`,provider:`adobe`,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 Y=(e,t,n={})=>{let r=a();return(async()=>{try{let i=await R();if(String(e.api).includes(`openai`)){let a={...e,baseUrl:`${S()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},o=m(a,t,G(q({...n,apiKey:i},`streamAdobe[openai]`)));for await(let e of o)r.push(e)}else{let a={...e,baseUrl:S(),api:`anthropic-messages`},o=g(a,t,G(q(b(e,l(e.id,e.name,{...n,apiKey:i})),`streamAdobe[anthropic]`)));for await(let e of o)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(J(e,t)),r.end()}})(),r},X=(e,t,n)=>{let r=a();return(async()=>{try{let i=await R();if(String(e.api).includes(`openai`)){let a={...e,baseUrl:`${S()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},o=h(a,t,G(q({...n,apiKey:i},`streamSimpleAdobe[openai]`)));for await(let e of o)r.push(e)}else{let a={...e,baseUrl:S(),api:`anthropic-messages`},o=p(a,t,G(q(b(e,l(e.id,e.name,{...n,apiKey:i})),`streamSimpleAdobe[anthropic]`)));for await(let e of o)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(J(e,t)),r.end()}})(),r};function de(e){let t={id:e.id,name:e.name};return e.api!==void 0&&(t.api=e.api),e.context_window!==void 0&&(t.context_window=e.context_window),e.max_tokens!==void 0&&(t.max_tokens=e.max_tokens),e.reasoning!==void 0&&(t.reasoning=e.reasoning),e.input!==void 0&&(t.input=e.input),t}function Z(){let e=new Map;for(let t of c())try{for(let n of s(t))e.set(n.id,n)}catch{}return e}function fe(e,n,r){let i=`adobe-${e.api===`openai`?`openai`:`anthropic`}`,a=r.get(e.id);if(a)return{...a,provider:`adobe`,api:i};let o=t(e.id,r);return{id:e.id,name:e.name??e.id,provider:`adobe`,api:i,baseUrl:n,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:o,inputCost:o.input,outputCost:o.output,cacheReadCost:o.cacheRead,cacheWriteCost:o.cacheWrite,reasoning:!0}}function pe(e,t){for(let t of e)w.set(t.id,de(t));let n=Z();return e.map(e=>fe(e,t,n))}async function me(e){try{let t=e??await R(),n=S(),r=await fetch(`${n}/v1/models`,{headers:{Authorization:`Bearer ${t}`,[W]:`6.34.0`}});if(!r.ok)console.warn(`[adobe] Proxy /v1/models returned ${r.status}, falling back to Anthropic models`);else{let e=await r.json();if(e.data?.length)return pe(e.data,n)}}catch(e){console.warn(`[adobe] Failed to fetch proxy models:`,e instanceof Error?e.message:String(e))}return null}const Q=new Map;function he(){return s(`anthropic`).map(e=>({...e,provider:`adobe`,api:`adobe-anthropic`}))}async function $(e){let t=S(),n=Q.get(t);if(n)return n;let r=await me(e);return r?(Q.set(t,r),r):he()}function ge(){d({api:`adobe-anthropic`,stream:Y,streamSimple:X}),d({api:`adobe-openai`,stream:Y,streamSimple:X})}export{ue as __resetAdobeSessionIdWarningCacheForTests,I as config,F as extractTokenFromUrl,$ as getAdobeModels,R as getValidAccessToken,le as isTokenExpired,ge as register};
|
|
1
|
+
import{n as e}from"./panel-rpc-BPwAqRch.js";import{K as t,d as n,y as r,z as i}from"./account-store-DWX-EZHx.js";import{a}from"./diagnostics-DN_idNHx.js";import{a as o,d as s,f as c,i as l,o as u,p as d,s as f}from"./bedrock-camp-CFmElpzZ.js";import{a as p,r as m,s as h,t as g}from"./legacy-api-aliases-BVP0Ho8x.js";import{n as _}from"./llm-session-id-ZObKEXzb.js";import{n as v,t as ee}from"./silent-renew-backoff-BrAZcbzt.js";import{getOAuthPageOrigin as te}from"./oauth-service-a6YE6xTR.js";import"./provider-settings-LcSPuWPj.js";var ne={proxyEndpoint:`https://adobe-llm-proxy.paolo-moz.workers.dev`,redirectUri:`https://www.sliccy.ai/auth/callback`,extensionRedirectUri:`https://akjjllgokmbgpbdbmafpiefnhidlmbgf.chromiumapp.org/adobe`};function re(e,t){return o(e,t)}function y(e,t,n){return e!==`xhigh`||!t?e:f(t,n)?`xhigh`:u(t,n)?`max`:`high`}function ie(e,t){let n=e?t?.thinkingLevelMap?.[e]:void 0;return y((()=>{if(typeof n==`string`)return n;switch(e){case`minimal`:case`low`:return`low`;case`medium`:return`medium`;case`xhigh`:return`xhigh`;default:return`high`}})(),t?.id,t?.name)}function ae(e,t){return async(n,r)=>{let i=t?await t(n,r)??n:n,a=i.thinking;return a&&a.type===`enabled`&&(i.thinking={type:`adaptive`,...a.display===void 0?{}:{display:a.display}},i.output_config={...i.output_config??{},effort:e}),i}}function b(e,t){if(!re(e.id,e.name))return t;let n=t,r=y(n.effort??ie(n.reasoning,e),e.id,e.name);return{...t,onPayload:ae(r,n.onPayload)}}function oe(e,t){let n={id:e.id,name:e.name??e.id},r=t?.api??e.api,i=t?.context_window??e.context_window,a=t?.max_tokens??e.max_tokens,o=t?.reasoning??e.reasoning,s=t?.input??e.input;r&&(n.api=r),i!==void 0&&(n.context_window=i),a!==void 0&&(n.max_tokens=a),o!==void 0&&(n.reasoning=o),s&&(n.input=s);let c=t?.cost??e.cost;return c&&(n.cost=c),/haiku/i.test(e.id)&&(n.compat={supportsEagerToolInputStreaming:!1}),/sonnet-5\b/i.test(e.id)&&!n.thinkingLevelMap&&(n.thinkingLevelMap={xhigh:`xhigh`}),n}const x=Object.assign({"/packages/webapp/providers/adobe-config.json":ne})[`/packages/webapp/providers/adobe-config.json`]??{clientId:``,proxyEndpoint:``,scopes:`openid,profile,email`};function S(){let e=r(`adobe`);if(e)return e.replace(/\/$/,``);if(x.proxyEndpoint)return x.proxyEndpoint.replace(/\/$/,``);throw Error(`Adobe proxy endpoint not configured — set it in Settings or adobe-config.json`)}const C=new Map,w=new Map,T=`slicc-adobe-models`;function E(e){try{localStorage.setItem(T,JSON.stringify(e))}catch{}}async function D(e){let t=C.get(e);if(t)return t;try{let t=await fetch(`${e}/v1/config`,{headers:{[W]:`6.35.1`}});if(t.ok){let n=await t.json();return C.set(e,n),n}console.warn(`[adobe] Proxy /v1/config returned ${t.status}, falling back to build-time config`)}catch(e){console.warn(`[adobe] Failed to fetch proxy config:`,e instanceof Error?e.message:String(e))}return{}}function O(e){let t=e.clientId||x.clientId;if(!t)throw Error(`Could not determine IMS client ID — proxy /v1/config did not return one and adobe-config.json is empty`);return t}function k(e){return e.scopes||x.scopes}function A(e){return e.imsEnvironment||x.imsEnvironment||`prod`}const j={prod:`https://ims-na1.adobelogin.com`,stg1:`https://ims-na1-stg1.adobelogin.com`};function M(e){return j[e??x.imsEnvironment??`prod`]??j.prod}const N=typeof chrome<`u`&&!!chrome?.runtime?.id;function P(){return n().find(e=>e.providerId===`adobe`)}async function se(e,t){try{let n=await fetch(`${M(t)}/ims/userinfo/v2`,{headers:{Authorization:`Bearer ${e}`}});if(n.ok){let e=await n.json();return{name:e.displayName||e.name||e.email,avatar:e.picture||e.avatar_url}}console.warn(`[adobe] User profile fetch returned ${n.status}, account will have no display name`)}catch(e){console.warn(`[adobe] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function F(e){let t=e.indexOf(`#`);if(t<0)return null;let n=new URLSearchParams(e.slice(t+1)),r=n.get(`access_token`);return r?{accessToken:r,expiresIn:parseInt(n.get(`expires_in`)??`86400`,10),scope:n.get(`scope`)??void 0}:null}const I={id:`adobe`,name:`Adobe`,description:`Claude via Adobe — login with your Adobe ID`,requiresApiKey:!1,requiresBaseUrl:!x.proxyEndpoint,baseUrlPlaceholder:`https://your-proxy.example.com`,baseUrlDescription:`Anthropic-compatible proxy endpoint`,isOAuth:!0,defaultModelId:`sonnet`,oauthTokenDomains:[`ims-na1.adobelogin.com`,`ims-na1-stg1.adobelogin.com`,`*.adobelogin.com`,`*.adobe.io`,`firefall.adobe.io`,`admin.hlx.page`,`admin.hlx.live`,`admin.aem.page`,`admin.aem.live`],getModelIds:()=>{let e=e=>oe(e,w.get(e.id));for(let t of Q.values())if(t.length){let n=t.map(t=>e({id:t.id,name:t.name??t.id,reasoning:t.reasoning,input:t.input,cost:t.cost}));return E(n),n}for(let t of C.values())if(t.models?.length)return t.models.map(t=>e(t));try{let e=localStorage.getItem(T);if(e){let t=JSON.parse(e);if(t.length)return t}}catch{}return[{id:`claude-sonnet-4-6`,name:`Claude Sonnet 4.6`}]},onOAuthLogin:async(e,t,n)=>{let r=S(),a=await D(r),o=O(a),s=k(a),c=A(a),l=N?null:await te(),u=N?null:v({pageHref:l.href,pageOrigin:l.origin,configuredRedirectUri:x.redirectUri},()=>crypto.randomUUID()),d=N?x.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:u.redirectUri,f=u?.oauthState,p=u?.expectedNonce??null,m=new URLSearchParams({client_id:o,scope:s,response_type:`token`,redirect_uri:d});f&&m.set(`state`,f),n?.forceReauth&&m.set(`prompt`,`login`);let h=await e(`${M(c)}/ims/authorize/v2?${m}`);if(!h)return;if(p&&h)try{if(new URL(h).searchParams.get(`nonce`)!==p){console.error(`[adobe] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let g=F(h);if(!g){console.error(`[adobe] Could not extract token from redirect URL`);return}let _=await se(g.accessToken,c);await i({providerId:`adobe`,accessToken:g.accessToken,tokenExpiresAt:Date.now()+g.expiresIn*1e3,userName:_.name,userAvatar:_.avatar,scopes:g.scope,baseUrl:x.proxyEndpoint?void 0:r}),await $().catch(e=>console.warn(`[adobe] Failed to fetch models after login:`,e instanceof Error?e.message:String(e))),t()},onOAuthLogout:async()=>{let e=P();if(e?.accessToken)try{let t=C.values().next().value??{},n=t.clientId||x.clientId,r=A(t);if(n){let t=await fetch(`${M(r)}/ims/revoke`,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({token:e.accessToken,token_type_hint:`access_token`,client_id:n})});t.ok||console.warn(`[adobe] Token revocation returned ${t.status}, token may still be valid server-side`)}}catch(e){console.warn(`[adobe] Failed to revoke token:`,e instanceof Error?e.message:String(e))}await i({providerId:`adobe`,accessToken:``})},onSilentRenew:async()=>P()?.accessToken?z():null,refreshModels:async e=>{await $(e);let t=I.getModelIds?.();t?.length&&E(t)}};let L=null;const ce=ee();async function R(){let e=P();if(!e?.accessToken)throw Error(`Not logged in to Adobe — please log in first`);if((e.tokenExpiresAt??0)-Date.now()>6e4)return e.accessToken;console.log(`[adobe] Token expired or expiring soon, attempting silent renewal...`);let t=await ce.run(()=>z());if(t)return t;let n=P();if((n?.tokenExpiresAt??0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`Adobe session expired — please log in again`)}function le(){let e=P();return!e?.tokenExpiresAt||Date.now()>e.tokenExpiresAt-6e4}async function z(){if(typeof window>`u`){let t=e();if(!t)return null;try{let{accessToken:e}=await t.call(`silent-renew`,{providerId:`adobe`},{timeoutMs:13e4});return e}catch(e){return console.warn(`[adobe] worker→page silent-renew bridge failed:`,e instanceof Error?e.message:String(e)),null}}return L||(L=U().finally(()=>{L=null}),L)}function B(e,t){let n=O(t),r=k(t),i=A(t),a=N?null:v({pageHref:window.location.href,pageOrigin:window.location.origin,configuredRedirectUri:x.redirectUri},()=>crypto.randomUUID()),o=N?x.extensionRedirectUri??`https://${chrome.runtime.id}.chromiumapp.org/`:a.redirectUri,s=a?.oauthState,c=a?.expectedNonce??null,l=new URLSearchParams({client_id:n,scope:r,response_type:`token`,redirect_uri:o,prompt:`none`});return s&&l.set(`state`,s),{authorizeUrl:`${M(i)}/ims/authorize/v2?${l}`,expectedNonce:c,proxyEndpoint:e}}function V(e,t){if(!t)return!0;try{if(new URL(e).searchParams.get(`nonce`)!==t)return console.error(`[adobe] OAuth nonce mismatch — possible CSRF`),!1}catch(e){console.warn(`[adobe] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}return!0}async function H(e,t){let n=P();await i({providerId:`adobe`,accessToken:e.accessToken,tokenExpiresAt:Date.now()+e.expiresIn*1e3,userName:n?.userName,userAvatar:n?.userAvatar,scopes:e.scope,baseUrl:x.proxyEndpoint?void 0:t})}async function U(){try{let e=S(),{authorizeUrl:t,expectedNonce:n}=B(e,await D(e)),{createOAuthLauncher:r}=await import(`./oauth-service-a6YE6xTR.js`),i=await r()(t,{interactive:!1});if(!i||!V(i,n))return null;let a=F(i);return a?(await H(a,e),console.log(`[adobe] Token renewed silently`),await $().catch(e=>console.warn(`[adobe] Failed to refresh models after silent renewal:`,e instanceof Error?e.message:String(e))),a.accessToken):null}catch(e){return console.warn(`[adobe] Silent renewal error:`,e instanceof Error?e.message:String(e)),null}}const W=`X-Slicc-Version`;function G(e){let t={};if(e.headers)for(let[n,r]of Object.entries(e.headers))n.toLowerCase()!==`x-slicc-version`&&(t[n]=r);return t[W]=`6.35.1`,{...e,headers:t}}const K=new Set;function q(e,t){if(e.headers){for(let[t,n]of Object.entries(e.headers))if(t.toLowerCase()===`x-session-id`&&n!=null)return e}return K.has(t)||(K.add(t),console.warn(`[adobe] Missing X-Session-Id from ${t} — using daily fallback. Attach an X-Session-Id header at the call site (see scoop-context.ts streamWithSessionId or docs/pitfalls.md).`)),{...e,headers:{...e.headers??{},"X-Session-Id":_(`adobe-provider-fallback`)}}}function ue(){K.clear()}function J(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:`adobe-anthropic`,provider:`adobe`,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 Y=(e,t,n={})=>{let r=a();return(async()=>{try{let i=await R();if(String(e.api).includes(`openai`)){let a={...e,baseUrl:`${S()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},o=m(a,t,G(q({...n,apiKey:i},`streamAdobe[openai]`)));for await(let e of o)r.push(e)}else{let a={...e,baseUrl:S(),api:`anthropic-messages`},o=g(a,t,G(q(b(e,l(e.id,e.name,{...n,apiKey:i})),`streamAdobe[anthropic]`)));for await(let e of o)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(J(e,t)),r.end()}})(),r},X=(e,t,n)=>{let r=a();return(async()=>{try{let i=await R();if(String(e.api).includes(`openai`)){let a={...e,baseUrl:`${S()}/v1`,api:`openai-completions`,compat:{...e.compat,supportsStore:!1,supportsDeveloperRole:!1}},o=h(a,t,G(q({...n,apiKey:i},`streamSimpleAdobe[openai]`)));for await(let e of o)r.push(e)}else{let a={...e,baseUrl:S(),api:`anthropic-messages`},o=p(a,t,G(q(b(e,l(e.id,e.name,{...n,apiKey:i})),`streamSimpleAdobe[anthropic]`)));for await(let e of o)r.push(e)}r.end()}catch(t){console.error(`[adobe] Stream error:`,t instanceof Error?t.message:String(t)),r.push(J(e,t)),r.end()}})(),r};function de(e){let t={id:e.id,name:e.name};return e.api!==void 0&&(t.api=e.api),e.context_window!==void 0&&(t.context_window=e.context_window),e.max_tokens!==void 0&&(t.max_tokens=e.max_tokens),e.reasoning!==void 0&&(t.reasoning=e.reasoning),e.input!==void 0&&(t.input=e.input),t}function Z(){let e=new Map;for(let t of c())try{for(let n of s(t))e.set(n.id,n)}catch{}return e}function fe(e,n,r){let i=`adobe-${e.api===`openai`?`openai`:`anthropic`}`,a=r.get(e.id);if(a)return{...a,provider:`adobe`,api:i};let o=t(e.id,r);return{id:e.id,name:e.name??e.id,provider:`adobe`,api:i,baseUrl:n,contextWindow:2e5,maxTokens:16384,input:[`text`,`image`],cost:o,inputCost:o.input,outputCost:o.output,cacheReadCost:o.cacheRead,cacheWriteCost:o.cacheWrite,reasoning:!0}}function pe(e,t){for(let t of e)w.set(t.id,de(t));let n=Z();return e.map(e=>fe(e,t,n))}async function me(e){try{let t=e??await R(),n=S(),r=await fetch(`${n}/v1/models`,{headers:{Authorization:`Bearer ${t}`,[W]:`6.35.1`}});if(!r.ok)console.warn(`[adobe] Proxy /v1/models returned ${r.status}, falling back to Anthropic models`);else{let e=await r.json();if(e.data?.length)return pe(e.data,n)}}catch(e){console.warn(`[adobe] Failed to fetch proxy models:`,e instanceof Error?e.message:String(e))}return null}const Q=new Map;function he(){return s(`anthropic`).map(e=>({...e,provider:`adobe`,api:`adobe-anthropic`}))}async function $(e){let t=S(),n=Q.get(t);if(n)return n;let r=await me(e);return r?(Q.set(t,r),r):he()}function ge(){d({api:`adobe-anthropic`,stream:Y,streamSimple:X}),d({api:`adobe-openai`,stream:Y,streamSimple:X})}export{ue as __resetAdobeSessionIdWarningCacheForTests,I as config,F as extractTokenFromUrl,$ as getAdobeModels,R as getValidAccessToken,le as isTokenExpired,ge as register};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{CHAT_SURFACE_ID as e}from"./wc-sprinkles-
|
|
1
|
+
import{CHAT_SURFACE_ID as e}from"./wc-sprinkles-TY8z4iwr.js";var t=`focus`,n={type:`leaf`,surfaceId:`chat`};function r(e,t={},n={}){return{zones:{top:null,left:null,middle:null,right:null,bottom:null,...e},rowFr:{top:1,center:1,bottom:1,...n},colFr:{left:1,middle:1,right:1,...t}}}var i={focus:{name:`focus`,tree:r({left:n},{left:3,middle:1})}};function a(e){return i[e]??null}function o(n,r){switch(r.kind){case`set`:n.applyLayout(r.tree);break;case`reset`:{let e=a(t);e&&n.applyLayout(e.tree);break}case`chat`:n.moveSurfaceToZone(e,r.zone);break;case`open`:n.placeSurface(r.zone,r.surfaceId);break;case`close`:n.removeSurface(r.surfaceId);break;case`move`:n.moveSurfaceToZone(r.surfaceId,r.zone);break;case`size`:n.setSurfaceSize(r.surfaceId,r.size)}}export{o as applyLayout};
|
|
@@ -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-DJXlpNui.js";const r=e(`mcp-apps`),i=`/workspace/.mcp/sprinkles`;async function a(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-
|
|
1
|
+
import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./types-idfTVsM8.js";import{t as n}from"./global-db-DJXlpNui.js";const r=e(`mcp-apps`),i=`/workspace/.mcp/sprinkles`;async function a(e){if(e)return e;let{VirtualFS:t}=await import(`./fs-CqrpSNTX.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,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}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-
|
|
1
|
+
import{b as e,g as t}from"./account-store-fsZiMtXd.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{t as r}from"./models-DgdVqaw5.js";import{a as i}from"./compat-Bn8HnC3L.js";import{r as a,t as o}from"./transform-messages-DgR3h-Ck.js";import{t as s}from"./openai-DQxsE__c.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 +1 @@
|
|
|
1
|
-
import{b as e,g as t}from"./account-store-
|
|
1
|
+
import{b as e,g as t}from"./account-store-DWX-EZHx.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{o as r,r as i,t as a}from"./transform-messages-D27pVLZ-.js";import{p as o}from"./bedrock-camp-CFmElpzZ.js";import{t as s}from"./openai-DehfWK3N.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{h as e}from"./account-store-
|
|
1
|
+
import{h as e}from"./account-store-fsZiMtXd.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{a as n}from"./compat-Bn8HnC3L.js";import{r,s as i}from"./legacy-api-aliases-DAkrHYf9.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={...e,baseUrl:o,api:s},c=r(t,n,i);for await(let e of c)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={...e,baseUrl:o,api:s},c=i(t,n,r);for await(let e of c)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-
|
|
1
|
+
import{h as e}from"./account-store-DWX-EZHx.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{p as n}from"./bedrock-camp-CFmElpzZ.js";import{r,s as i}from"./legacy-api-aliases-BVP0Ho8x.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={...e,baseUrl:o,api:s},c=r(t,n,i);for await(let e of c)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={...e,baseUrl:o,api:s},c=i(t,n,r);for await(let e of c)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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./logger-DDBAeTLF.js";import{n as t}from"./runtime-env-DH4NDw4t.js";import{t as n}from"./permissions-surface-registry-CilCRwhh.js";import{t as r}from"./speech-C5U8h4In.js";import{t as i}from"./speech-assets-bridge-CFYafE89.js";import{i as a}from"./transformers-env-CflaNVb-.js";import{i as o,t as s}from"./whisper-session-hMgosjVG.js";var c=e(`speech:composer`),l=5e3,u=(e,t,n)=>new Promise((r,i)=>{let a=setTimeout(()=>i(Error(`${n} timed out after ${t}ms`)),t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})}),d=class{#e;#t;#n;#r;#i;#a=null;#o=!1;#s={engine:`builtin`,state:`idle`};#c=a();#l=new Set;#u=null;constructor(e={}){this.#e=e.builtin??r(),this.#t=e.loadWhisper??o,this.#n=e.startSession??s,this.#r=e.getPermissionSurface??f,this.#i=e.ensureAssets??v}permission(){return this.#e.permission()}async requestPermission(){let e=this.#r();if(e)try{let t=await e.request(`microphone`);return t?(this.#p(t.stream),!0):!1}catch(e){return c.warn(`permission surface microphone request failed`,e),!1}return this.#e.requestPermission()}microphones(){return this.#e.microphones()}status(){return this.#s}onStatus(e){return this.#l.add(e),e(this.#s),()=>this.#l.delete(e)}warmup(){this.#o||(this.#o=!0,this.#c=a(),this.#_({engine:`builtin`,state:`downloading`}),this.#d().then(e=>{this.#a=e,this.#_({engine:`enhanced`,state:`ready`})},e=>{this.#o=!1,this.#_({engine:`builtin`,state:`unavailable`,message:m(e)}),c.warn(`enhanced speech engine unavailable`,e)}))}async#d(){let e=null;try{await this.#i(e=>this.#h(e))}catch(t){e=t,c.warn(`speech asset staging failed; trying already-present assets`,t)}try{return await this.#t(e=>this.#g(e))}catch(t){throw e??t}}async start(e){let t=this.#a;if(t){let n=null;try{return n=await this.#f(e.deviceId),await this.#n(t,{deviceId:e.deviceId,lang:e.lang,onPartial:e.onPartial,onError:e.onError,stream:n??void 0})}catch(e){if(n)for(let e of n.getTracks())e.stop();c.warn(`whisper session failed to start; falling back to builtin`,e)}}return this.#e.start(e)}async#f(e){let t=e&&e!=="default"?e:void 0,n=this.#m();if(n){if(!t&&p(n))return n;for(let e of n.getTracks())e.stop()}let r=this.#r();if(!r)return null;let i={audio:!t||{deviceId:{exact:t}}},a=await u(r.request(`microphone`,{constraints:i}),l,`microphone capture`);if(!a)throw Error(`microphone permission denied`);return a.stream}#p(e){if(this.#u&&this.#u!==e)for(let e of this.#u.getTracks())e.stop();this.#u=e}#m(){let e=this.#u;return this.#u=null,e}get enhancedReady(){return this.#a!==null}#h(e){if(this.#s.state!==`downloading`)return;(e.bytesTotal!=null||e.bytesLoaded!=null)&&this.#c.update(e.asset,e.bytesLoaded??0,e.bytesTotal??0);let t=this.#c.snapshot();t.total<=0||this.#_({engine:`builtin`,state:`downloading`,download:{loaded:t.loaded,total:t.total,etaSeconds:t.etaSeconds}})}#g(e){this.#s.state===`downloading`&&this.#_({engine:`builtin`,state:`downloading`,download:{loaded:e.loaded,total:e.total,etaSeconds:e.etaSeconds}})}#_(e){this.#s=e;for(let t of this.#l)t(e)}};function f(){let e=n();return e?{async request(t,n){let r=await e.request(t,n);return r?.kind===`microphone`?{kind:`microphone`,stream:r.stream}:null}}:null}function p(e){let t=e.getTracks();return t.length>0&&t.some(e=>e.readyState!==`ended`)}function m(e){return`Enhanced speech unavailable: ${e instanceof Error?e.message:String(e)}`}var h=t,g;function _(e){g=e}function v(e){return h()?Promise.resolve():i({instanceId:g,onProgress:e})}var y=null;function b(){return y??=new d,y}export{b as getComposerSpeech,_ as setComposerSpeechInstanceId};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{C as e,P as t,d as n,f as r}from"./account-store-
|
|
1
|
+
import{C as e,P as t,d as n,f as r}from"./account-store-fsZiMtXd.js";import{n as i}from"./provider-settings-DRzBx_K-.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`,l.textContent=i.userName?i.userName:i.accessToken?`Logged in`:i.apiKey?`API key set`:`No credentials`,o.appendChild(l),a.appendChild(o);let u=document.createElement(`button`);u.className=`connect-surface__remove-btn`,u.textContent=`Remove`,u.onclick=async()=>{await 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,5 +1,5 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mount-picker-popup-CSSC05JS.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/logger-DDBAeTLF.js","assets/picker-popup-BvzmBsGL.js","assets/runtime-env-DH4NDw4t.js","assets/usb-picker-Cl6Cwuv9.js","assets/serial-picker-CUd91lje.js","assets/hid-picker-Bhoh8hxy.js","assets/usb-device-registry-CRsCisej.js","assets/serial-port-registry-B3LG5UIy.js","assets/hid-device-registry-B2R-0rNt.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./preload-helper-Czpn1I53.js";import{n}from"./runtime-env-DH4NDw4t.js";import{t as r}from"./
|
|
2
|
+
import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./preload-helper-Czpn1I53.js";import{n}from"./runtime-env-DH4NDw4t.js";import{t as r}from"./permissions-surface-registry-CilCRwhh.js";import{n as i,r as a}from"./hid-device-registry-B2R-0rNt.js";import{a as o,i as s}from"./serial-port-registry-B3LG5UIy.js";import{C as c,D as l,E as u,S as d,_ as f,a as ee,g as te,h as p,k as m,l as h,m as ne,n as re,o as g,s as ie,w as ae,x as oe,y as se}from"./usb-operations-Cgk-otz-.js";import{i as ce,r as _}from"./usb-device-registry-CRsCisej.js";import{i as v,n as le,r as y}from"./sprinkle-renderer-CMk2ghMi.js";import{n as ue}from"./sprinkle-bridge-RIIOK3yH.js";import{a as b,n as x,r as S}from"./theme-CXRqxpw6.js";var C=e({broadcastToDips:()=>R,disposeDips:()=>X,handleDipPickerAction:()=>Z,hydrateDips:()=>Y,mountDip:()=>K,setDipExecHandler:()=>he}),w=n();async function T(e,t){if(t?.aborted)throw new DOMException(`aborted`,`AbortError`);let n=await D(e,!0,t);if(t?.aborted)throw new DOMException(`aborted`,`AbortError`);if(n===null)throw Error(`VFS read failed: ${e}`);return typeof n==`string`?n:new TextDecoder().decode(n)}var E=null;function de(){if(E)return E;if(typeof BroadcastChannel>`u`)return null;try{E=new BroadcastChannel(`preview-vfs`)}catch{return null}return E}async function D(e,t,n){let r=de();if(!r)return null;let i=`dip-${Date.now()}-${Math.random().toString(36).slice(2)}`;return new Promise(a=>{let o=!1,s=()=>{r.removeEventListener(`message`,c),n?.removeEventListener(`abort`,l)},c=e=>{if(!o&&e.data?.type===`preview-vfs-response`&&e.data.id===i){if(o=!0,s(),e.data.error){a(null);return}a(e.data.content??null)}},l=()=>{o||(o=!0,s(),a(null))};r.addEventListener(`message`,c),n?.addEventListener(`abort`,l),setTimeout(()=>{o||(o=!0,s(),a(null))},5e3),r.postMessage({type:`preview-vfs-read`,id:i,path:e,asText:t})})}var fe=[`/shared/sprinkles/`,`/workspace/skills/sprinkles/`,`/workspace/sprinkles/`],pe=[`/shared/`,`/workspace/skills/sprinkles/`,`/workspace/sprinkles/`];function me(e){return fe.some(t=>e.startsWith(t))}function O(e){return typeof e!=`string`||!e.startsWith(`/`)||e.includes(`..`)?!1:pe.some(t=>e.startsWith(t))}var k=new WeakSet,A=`,
|
|
3
3
|
exec: Object.assign(function(cmd) {
|
|
4
4
|
return _vfsCall('dip-exec', { cmd: cmd }, function(m) { return m.result; });
|
|
5
5
|
}, { spawn: function(argv) {
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{C as e,D as t,E as n,O as r,S as i,T as a,_ as o,a as s,b as c,c as l,d as u,f as d,g as f,h as p,i as m,k as h,l as g,m as _,n as v,o as y,p as b,r as x,s as S,u as C,w,x as T}from"./dist-CoWnU-QN.js";function E(e){switch(e.name){case`TypeMismatchError`:return`EPERM`;case`IndexSizeError`:case`HierarchyRequestError`:case`InvalidCharacterError`:case`InvalidStateError`:case`SyntaxError`:case`NamespaceError`:case`ConstraintError`:case`VersionError`:case`URLMismatchError`:case`InvalidNodeTypeError`:return`EINVAL`;case`WrongDocumentError`:return`EXDEV`;case`NoModificationAllowedError`:case`InvalidModificationError`:case`InvalidAccessError`:case`SecurityError`:case`NotAllowedError`:return`EACCES`;case`NotFoundError`:return`ENOENT`;case`NotSupportedError`:return`ENOTSUP`;case`InUseAttributeError`:return`EBUSY`;case`NetworkError`:return`ENETDOWN`;case`AbortError`:return`EINTR`;case`QuotaExceededError`:return`ENOSPC`;case`TimeoutError`:return`ETIMEDOUT`;case`ReadOnlyError`:return`EROFS`;default:return`EIO`}}function D(e,t){if(e instanceof a)return e;let n=e instanceof DOMException?w[E(e)]:w.EIO,r=new a(n,e.message);return r.stack=e.stack,Error.captureStackTrace?.(r,D),r.cause=e.cause,r}function O(e){return typeof e==`object`&&!!e&&e.constructor.name==`SharedArrayBuffer`}function k(e){return e instanceof ArrayBuffer?e.resizable:O(e)?e.growable:!1}function A(e,t){return e.kind==t}var j=class extends x(m){async _loadHandles(e,t){for await(let[n,r]of t.entries()){let t=_(e,n);this._handles.set(t,r),A(r,`directory`)&&await this._loadHandles(t,r)}}async _loadMetadata(e){if(this._handles.set(`/`,this.root),await this._loadHandles(`/`,this.root),e){let t=await(await(await this.get(`file`,e)).getFile()).text(),n=JSON.parse(t);this.index.fromJSON(n);return}for(let[e,t]of this._handles){if(A(t,`file`)){let{lastModified:n,size:r}=await t.getFile();this.index.set(e,new C({mode:420|o,size:r,mtimeMs:n}));continue}if(!A(t,`directory`))throw n(`EIO`,`Invalid handle`);this.index.set(e,new C({mode:511|p,size:0}))}}constructor(e,t=!1){super(2003133025,`webaccessfs`),this.root=e,this.disableHandleCache=t,this._handles=new Map,this._sync=s.create({label:`accessfs-cache`}),this.attributes.set(`no_buffer_resize`,!0),t&&this.attributes.set(`no_handle_cache`,!0)}async stat(e){try{return await super.stat(e)}catch(t){if(t.code!=`ENOENT`)throw t;let n=await this.get(null,e),r=new C;if(A(n,`file`)){let e=await n.getFile();r.update({mode:420|o,size:e.size,mtimeMs:e.lastModified})}else r.update({mode:p|511,size:0});return this.index.set(e,r),r}}async readdir(e){let t=await this.get(`directory`,e);return await Array.fromAsync(t.keys())}async remove(e){let t=await this.get(`directory`,b(e));for(let t of this._handles.keys())b(t)==e&&this._handles.delete(t);this._handles.delete(e),await t.removeEntry(d(e),{recursive:!0}).catch(t=>h(D(t,e)))}removeSync(){throw T(n(`ENOSYS`))}async read(e,t,r,i){if(i<=r)return;let a=await(await(await this.get(`file`,e)).getFile()).arrayBuffer();if(a.byteLength<i-r)throw c(n(`EIO`,[`Unexpected mismatch in file data size. This should not happen.`,`tried to read ${i-r} bytes but the file is ${a.byteLength} bytes.`,`path: ${e}`].join(`
|
|
2
|
+
`+` `.repeat(24))));t.set(new Uint8Array(a,r,i-r))}async write(e,t,r){if(k(t.buffer)||O(t.buffer)){let e=new Uint8Array(new ArrayBuffer(t.byteLength),t.byteOffset,t.byteLength);e.set(t),t=e}let i=this.index.get(e);if(!i)throw n(`ENOENT`);let a=(i.mode&f)==p,o;try{o=await this.get(a?`directory`:`file`,e)}catch{o=await(await this.get(`directory`,b(e)))[a?`getDirectoryHandle`:`getFileHandle`](d(e),{create:!0}).catch(t=>h(D(t,e))),this.disableHandleCache||this._handles.set(e,o)}if(a)return;if(A(o,`directory`)){T(n(`EIO`,`Mismatch in entry kind on write`));return}let s=!r&&t.byteLength>=i.size,c=await o.createWritable({keepExistingData:!s});if(r)try{await c.seek(r)}catch{await c.write({type:`seek`,position:r})}await c.write(t),await c.close();let{size:l,lastModified:u}=await o.getFile();i.update({size:l,mtimeMs:u}),this.index.set(e,i)}async writeFile(e,t){return this.write(e,t,0)}async _mkdir(e){let t=await(await this.get(`directory`,b(e))).getDirectoryHandle(d(e),{create:!0}).catch(t=>h(D(t,e)));this.disableHandleCache||this._handles.set(e,t)}async get(e=null,t){let r=this._handles.get(t);if(!this.disableHandleCache&&r){if(e&&!A(r,e))throw n(e==`directory`?`ENOTDIR`:`EISDIR`);return r}if(t==`/`)return this.root;let i=t.slice(1).split(`/`),a=this.root;for(let e=0;e<i.length-1;++e)a=await a.getDirectoryHandle(i[e]).catch(e=>h(D(e,t)));try{let n=await a[e==`file`?`getFileHandle`:`getDirectoryHandle`](i.at(-1));return this.disableHandleCache||this._handles.set(t,n),n}catch(r){if(r.name!=`TypeMismatchError`)throw D(r,t);if(e===null){let e=await a.getFileHandle(i.at(-1)).catch(e=>h(D(e,t)));return this.disableHandleCache||this._handles.set(t,e),e}throw n(e==`file`?`EISDIR`:`ENOTDIR`)}}},M={name:`WebAccess`,options:{handle:{type:`object`,required:!0},metadata:{type:`string`,required:!1},disableHandleCache:{type:`boolean`,required:!1}},async create(e){let t=new j(e.handle,e.disableHandleCache);return await t._loadMetadata(e.metadata),t}};function N(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=t=>{t.preventDefault(),n(D(e.error))}})}var P=class extends l{async(e){this.asyncDone=this.asyncDone.then(()=>e)}constructor(e,t){super(t),this.tx=e,this.store=t,this.asyncDone=Promise.resolve(),this._idb=e.objectStore(t.name)}async keys(){return(await N(this._idb.getAllKeys())).map(Number)}async get(e){let t=await N(this._idb.get(e));return t&&this.store.cache.set(e,new Uint8Array(t)),t}getSync(e,t,n){if(!this.store.cache.has(e))return;let r=new Uint8Array(this.store.cache.get(e));return n??=r.byteLength,r.subarray(t,n)}async set(e,t){this.store.cache.set(e,new Uint8Array(t)),await N(this._idb.put(t,e))}setSync(e,t){this.async(this.set(e,t))}remove(e){return this.store.cache.delete(e),N(this._idb.delete(e))}removeSync(e){this.store.cache.delete(e),this.async(this.remove(e))}async commit(){await this.asyncDone;let{promise:e,resolve:t,reject:n}=Promise.withResolvers();return this.tx.oncomplete=()=>t(),this.tx.onerror=()=>n(D(this.tx.error)),this.tx.commit(),e}async abort(){await this.asyncDone;let{promise:e,resolve:t,reject:n}=Promise.withResolvers();return this.tx.onabort=()=>t(),this.tx.onerror=()=>n(D(this.tx.error)),this.tx.abort(),e}};async function F(t,n=globalThis.indexedDB){let r=n.open(t);return r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(t)&&(e(`Found unexpected object store: `+t),n.deleteObjectStore(t)),n.createObjectStore(t)},await N(r)}var I=class{constructor(e){this.db=e,this.cache=new Map}sync(){return Promise.resolve()}get name(){return this.db.name}transaction(){return new P(this.db.transaction(this.name,`readwrite`),this)}},L=new WeakMap;async function R(e){if(!(e instanceof IDBFactory))return!1;try{return(await N(e.open(`__zenfs_test`))).close(),!0}catch{return!1}finally{e?.deleteDatabase(`__zenfs_test`)}}var z={name:`IndexedDB`,options:{storeName:{type:`string`,required:!1},idbFactory:{type:`object`,required:!1}},async isAvailable({idbFactory:e=globalThis.indexedDB}){if(L.has(e))return L.get(e);let t=R(e);return L.set(e,t),t},async create(e){let t=new I(await F(e.storeName||`zenfs`,e.idbFactory)),n=new S(t);if(e?.disableAsyncCache)return i(`Async preloading disabled for IndexedDB`),n;let r=t.transaction();for(let e of await r.keys())await r.get(e);return n}},B=class{get name(){return V.name}constructor(e){this.storage=e}clear(){this.storage.clear()}clearSync(){this.storage.clear()}async sync(){}transaction(){return new y(this)}keys(){return Object.keys(this.storage).map(e=>Number(e))}get(e){let t=this.storage.getItem(e.toString());if(typeof t==`string`)return r(t)}set(e,r){try{this.storage.setItem(e.toString(),t(r))}catch{throw n(`ENOSPC`)}}delete(e){try{this.storage.removeItem(e.toString())}catch(t){throw n(`EIO`,`Unable to delete '${e}': ${t}`)}}},V={name:`WebStorage`,options:{storage:{type:`object`,required:!1}},isAvailable(e){return(e?.storage??globalThis.localStorage)instanceof globalThis.Storage},create({storage:e=globalThis.localStorage}){return new S(new B(e))}};function H(e){let t={};for(let n of u){let r=e.getAttribute(n);r!=null&&(t[n]=parseInt(r,16))}return new C(t)}function U(e,t){for(let n of Object.keys(t))!(n in u)||t[n]===void 0||e.setAttribute(n,t[n].toString(16))}function W(e,t=!1){let n;try{let r=t?e.textContent:e.getAttribute(`paths`);n=JSON.parse(r||`[]`)}catch{n=[]}return n}var G=class extends v(g){constructor(e=new DOMParser().parseFromString(`<fs></fs>`,`application/xml`).documentElement){super(544763244,`xmltmpfs`),this.root=e;try{this.mkdirSync(`/`,{uid:0,gid:0,mode:511})}catch(e){let t=e;if(t.code!=`EEXIST`)throw t}}renameSync(e,t){let n=this.get(`rename`,e);this.remove(`rename`,n,e),this.add(`rename`,n,t)}statSync(e){return H(this.get(`stat`,e))}createFileSync(e,t){let n=this.statSync(b(e)),r=new C({mode:t.mode|o,uid:n.mode&2048?n.uid:t.uid,gid:n.mode&1024?n.gid:t.gid});return this.create(`createFile`,e,r),r}unlinkSync(e){let t=this.get(`unlink`,e);if(H(t).mode&16384)throw n(`EISDIR`);this.remove(`unlink`,t,e)}rmdirSync(e){let t=this.get(`rmdir`,e);if(t.textContent?.length)throw n(`ENOTEMPTY`);if(!(H(t).mode&16384))throw n(`ENOTDIR`);this.remove(`rmdir`,t,e)}mkdirSync(e,t){let n=this.statSync(b(e)),r=new C({mode:t.mode|p,uid:n.mode&2048?n.uid:t.uid,gid:n.mode&1024?n.gid:t.gid});return this.create(`mkdir`,e,r).textContent=`[]`,r}readdirSync(e){let t=this.get(`readdir`,e);if(!(H(t).mode&16384))throw n(`ENOTDIR`);try{return JSON.parse(t.textContent)}catch(e){throw n(`EIO`,`Invalid directory listing: `+e)}}linkSync(e,t){let n=this.get(`link`,e);this.add(`link`,n,t)}touchSync(e,t){U(this.get(`touch`,e),t)}syncSync(){}readSync(e,t,n,i){let a=this.get(`read`,e),o=r(a.textContent.slice(n,i));t.set(o)}writeSync(e,n,r){let i=this.get(`write`,e),a=t(n),o=i.textContent.slice(r+a.length);i.textContent=i.textContent.slice(0,r)+a+o}toString(){return new XMLSerializer().serializeToString(this.root)}get(e,t){let r=this.root.children;if(!r)throw n(`EIO`);for(let e=0;e<r.length;e++)if(W(r[e]).includes(t))return r[e];throw n(`ENOENT`)}create(e,t,r){if(this.existsSync(t))throw n(`EEXIST`);let i=document.createElement(`file`);return this.add(e,i,t),U(i,new C({...r,uid:r.mode})),this.root.append(i),i}add(e,t,n,r=!1){let i=W(t,r);if(i.push(n),r){t.textContent=JSON.stringify(i);return}if(t.setAttribute(`paths`,JSON.stringify(i)),t.setAttribute(`nlink`,i.length.toString(16)),n!=`/`){let t=this.get(e,b(n));this.add(e,t,d(n),!0)}}remove(e,t,n,r=!1){let i=W(t,r),a=i.indexOf(n);if(a!=-1){if(i.splice(a,1),r){t.textContent=JSON.stringify(i);return}if(i.length?(t.setAttribute(`paths`,JSON.stringify(i)),t.setAttribute(`nlink`,i.length.toString(16))):t.remove(),n!=`/`){let t=this.get(e,b(n));this.remove(e,t,d(n),!0)}}}},K={name:`XML`,options:{root:{type:`object`,required:!1}},isAvailable(){return!0},create(e){return new G(e.root)}};export{z as IndexedDB,I as IndexedDBStore,P as IndexedDBTransaction,M as WebAccess,j as WebAccessFS,V as WebStorage,B as WebStorageStore,K as XML,G as XMLFS};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{C as e,D as t,E as n,O as r,S as i,T as a,_ as o,a as s,b as c,c as l,d as u,f as d,g as f,h as p,i as m,k as h,l as g,m as _,n as v,o as y,p as b,r as x,s as S,u as C,w,x as T}from"./dist-4adALD4z.js";function E(e){switch(e.name){case`TypeMismatchError`:return`EPERM`;case`IndexSizeError`:case`HierarchyRequestError`:case`InvalidCharacterError`:case`InvalidStateError`:case`SyntaxError`:case`NamespaceError`:case`ConstraintError`:case`VersionError`:case`URLMismatchError`:case`InvalidNodeTypeError`:return`EINVAL`;case`WrongDocumentError`:return`EXDEV`;case`NoModificationAllowedError`:case`InvalidModificationError`:case`InvalidAccessError`:case`SecurityError`:case`NotAllowedError`:return`EACCES`;case`NotFoundError`:return`ENOENT`;case`NotSupportedError`:return`ENOTSUP`;case`InUseAttributeError`:return`EBUSY`;case`NetworkError`:return`ENETDOWN`;case`AbortError`:return`EINTR`;case`QuotaExceededError`:return`ENOSPC`;case`TimeoutError`:return`ETIMEDOUT`;case`ReadOnlyError`:return`EROFS`;default:return`EIO`}}function D(e,t){if(e instanceof a)return e;let n=e instanceof DOMException?w[E(e)]:w.EIO,r=new a(n,e.message);return r.stack=e.stack,Error.captureStackTrace?.(r,D),r.cause=e.cause,r}function O(e){return typeof e==`object`&&!!e&&e.constructor.name==`SharedArrayBuffer`}function k(e){return e instanceof ArrayBuffer?e.resizable:O(e)?e.growable:!1}function A(e,t){return e.kind==t}var j=class extends x(m){async _loadHandles(e,t){for await(let[n,r]of t.entries()){let t=_(e,n);this._handles.set(t,r),A(r,`directory`)&&await this._loadHandles(t,r)}}async _loadMetadata(e){if(this._handles.set(`/`,this.root),await this._loadHandles(`/`,this.root),e){let t=await(await(await this.get(`file`,e)).getFile()).text(),n=JSON.parse(t);this.index.fromJSON(n);return}for(let[e,t]of this._handles){if(A(t,`file`)){let{lastModified:n,size:r}=await t.getFile();this.index.set(e,new C({mode:420|o,size:r,mtimeMs:n}));continue}if(!A(t,`directory`))throw n(`EIO`,`Invalid handle`);this.index.set(e,new C({mode:511|p,size:0}))}}constructor(e,t=!1){super(2003133025,`webaccessfs`),this.root=e,this.disableHandleCache=t,this._handles=new Map,this._sync=s.create({label:`accessfs-cache`}),this.attributes.set(`no_buffer_resize`,!0),t&&this.attributes.set(`no_handle_cache`,!0)}async stat(e){try{return await super.stat(e)}catch(t){if(t.code!=`ENOENT`)throw t;let n=await this.get(null,e),r=new C;if(A(n,`file`)){let e=await n.getFile();r.update({mode:420|o,size:e.size,mtimeMs:e.lastModified})}else r.update({mode:p|511,size:0});return this.index.set(e,r),r}}async readdir(e){let t=await this.get(`directory`,e);return await Array.fromAsync(t.keys())}async remove(e){let t=await this.get(`directory`,b(e));for(let t of this._handles.keys())b(t)==e&&this._handles.delete(t);this._handles.delete(e),await t.removeEntry(d(e),{recursive:!0}).catch(t=>h(D(t,e)))}removeSync(){throw T(n(`ENOSYS`))}async read(e,t,r,i){if(i<=r)return;let a=await(await(await this.get(`file`,e)).getFile()).arrayBuffer();if(a.byteLength<i-r)throw c(n(`EIO`,[`Unexpected mismatch in file data size. This should not happen.`,`tried to read ${i-r} bytes but the file is ${a.byteLength} bytes.`,`path: ${e}`].join(`
|
|
2
|
+
`+` `.repeat(24))));t.set(new Uint8Array(a,r,i-r))}async write(e,t,r){if(k(t.buffer)||O(t.buffer)){let e=new Uint8Array(new ArrayBuffer(t.byteLength),t.byteOffset,t.byteLength);e.set(t),t=e}let i=this.index.get(e);if(!i)throw n(`ENOENT`);let a=(i.mode&f)==p,o;try{o=await this.get(a?`directory`:`file`,e)}catch{o=await(await this.get(`directory`,b(e)))[a?`getDirectoryHandle`:`getFileHandle`](d(e),{create:!0}).catch(t=>h(D(t,e))),this.disableHandleCache||this._handles.set(e,o)}if(a)return;if(A(o,`directory`)){T(n(`EIO`,`Mismatch in entry kind on write`));return}let s=!r&&t.byteLength>=i.size,c=await o.createWritable({keepExistingData:!s});if(r)try{await c.seek(r)}catch{await c.write({type:`seek`,position:r})}await c.write(t),await c.close();let{size:l,lastModified:u}=await o.getFile();i.update({size:l,mtimeMs:u}),this.index.set(e,i)}async writeFile(e,t){return this.write(e,t,0)}async _mkdir(e){let t=await(await this.get(`directory`,b(e))).getDirectoryHandle(d(e),{create:!0}).catch(t=>h(D(t,e)));this.disableHandleCache||this._handles.set(e,t)}async get(e=null,t){let r=this._handles.get(t);if(!this.disableHandleCache&&r){if(e&&!A(r,e))throw n(e==`directory`?`ENOTDIR`:`EISDIR`);return r}if(t==`/`)return this.root;let i=t.slice(1).split(`/`),a=this.root;for(let e=0;e<i.length-1;++e)a=await a.getDirectoryHandle(i[e]).catch(e=>h(D(e,t)));try{let n=await a[e==`file`?`getFileHandle`:`getDirectoryHandle`](i.at(-1));return this.disableHandleCache||this._handles.set(t,n),n}catch(r){if(r.name!=`TypeMismatchError`)throw D(r,t);if(e===null){let e=await a.getFileHandle(i.at(-1)).catch(e=>h(D(e,t)));return this.disableHandleCache||this._handles.set(t,e),e}throw n(e==`file`?`EISDIR`:`ENOTDIR`)}}};const M={name:`WebAccess`,options:{handle:{type:`object`,required:!0},metadata:{type:`string`,required:!1},disableHandleCache:{type:`boolean`,required:!1}},async create(e){let t=new j(e.handle,e.disableHandleCache);return await t._loadMetadata(e.metadata),t}};function N(e){return new Promise((t,n)=>{e.onsuccess=()=>t(e.result),e.onerror=t=>{t.preventDefault(),n(D(e.error))}})}var P=class extends l{async(e){this.asyncDone=this.asyncDone.then(()=>e)}constructor(e,t){super(t),this.tx=e,this.store=t,this.asyncDone=Promise.resolve(),this._idb=e.objectStore(t.name)}async keys(){return(await N(this._idb.getAllKeys())).map(Number)}async get(e){let t=await N(this._idb.get(e));return t&&this.store.cache.set(e,new Uint8Array(t)),t}getSync(e,t,n){if(!this.store.cache.has(e))return;let r=new Uint8Array(this.store.cache.get(e));return n??=r.byteLength,r.subarray(t,n)}async set(e,t){this.store.cache.set(e,new Uint8Array(t)),await N(this._idb.put(t,e))}setSync(e,t){this.async(this.set(e,t))}remove(e){return this.store.cache.delete(e),N(this._idb.delete(e))}removeSync(e){this.store.cache.delete(e),this.async(this.remove(e))}async commit(){await this.asyncDone;let{promise:e,resolve:t,reject:n}=Promise.withResolvers();return this.tx.oncomplete=()=>t(),this.tx.onerror=()=>n(D(this.tx.error)),this.tx.commit(),e}async abort(){await this.asyncDone;let{promise:e,resolve:t,reject:n}=Promise.withResolvers();return this.tx.onabort=()=>t(),this.tx.onerror=()=>n(D(this.tx.error)),this.tx.abort(),e}};async function F(t,n=globalThis.indexedDB){let r=n.open(t);return r.onupgradeneeded=()=>{let n=r.result;n.objectStoreNames.contains(t)&&(e(`Found unexpected object store: `+t),n.deleteObjectStore(t)),n.createObjectStore(t)},await N(r)}var I=class{constructor(e){this.db=e,this.cache=new Map}sync(){return Promise.resolve()}get name(){return this.db.name}transaction(){return new P(this.db.transaction(this.name,`readwrite`),this)}};const L=new WeakMap;async function R(e){if(!(e instanceof IDBFactory))return!1;try{return(await N(e.open(`__zenfs_test`))).close(),!0}catch{return!1}finally{e?.deleteDatabase(`__zenfs_test`)}}const z={name:`IndexedDB`,options:{storeName:{type:`string`,required:!1},idbFactory:{type:`object`,required:!1}},async isAvailable({idbFactory:e=globalThis.indexedDB}){if(L.has(e))return L.get(e);let t=R(e);return L.set(e,t),t},async create(e){let t=new I(await F(e.storeName||`zenfs`,e.idbFactory)),n=new S(t);if(e?.disableAsyncCache)return i(`Async preloading disabled for IndexedDB`),n;let r=t.transaction();for(let e of await r.keys())await r.get(e);return n}};var B=class{get name(){return V.name}constructor(e){this.storage=e}clear(){this.storage.clear()}clearSync(){this.storage.clear()}async sync(){}transaction(){return new y(this)}keys(){return Object.keys(this.storage).map(e=>Number(e))}get(e){let t=this.storage.getItem(e.toString());if(typeof t==`string`)return r(t)}set(e,r){try{this.storage.setItem(e.toString(),t(r))}catch{throw n(`ENOSPC`)}}delete(e){try{this.storage.removeItem(e.toString())}catch(t){throw n(`EIO`,`Unable to delete '${e}': ${t}`)}}};const V={name:`WebStorage`,options:{storage:{type:`object`,required:!1}},isAvailable(e){return(e?.storage??globalThis.localStorage)instanceof globalThis.Storage},create({storage:e=globalThis.localStorage}){return new S(new B(e))}};function H(e){let t={};for(let n of u){let r=e.getAttribute(n);r!=null&&(t[n]=parseInt(r,16))}return new C(t)}function U(e,t){for(let n of Object.keys(t))!(n in u)||t[n]===void 0||e.setAttribute(n,t[n].toString(16))}function W(e,t=!1){let n;try{let r=t?e.textContent:e.getAttribute(`paths`);n=JSON.parse(r||`[]`)}catch{n=[]}return n}var G=class extends v(g){constructor(e=new DOMParser().parseFromString(`<fs></fs>`,`application/xml`).documentElement){super(544763244,`xmltmpfs`),this.root=e;try{this.mkdirSync(`/`,{uid:0,gid:0,mode:511})}catch(e){let t=e;if(t.code!=`EEXIST`)throw t}}renameSync(e,t){let n=this.get(`rename`,e);this.remove(`rename`,n,e),this.add(`rename`,n,t)}statSync(e){return H(this.get(`stat`,e))}createFileSync(e,t){let n=this.statSync(b(e)),r=new C({mode:t.mode|o,uid:n.mode&2048?n.uid:t.uid,gid:n.mode&1024?n.gid:t.gid});return this.create(`createFile`,e,r),r}unlinkSync(e){let t=this.get(`unlink`,e);if(H(t).mode&16384)throw n(`EISDIR`);this.remove(`unlink`,t,e)}rmdirSync(e){let t=this.get(`rmdir`,e);if(t.textContent?.length)throw n(`ENOTEMPTY`);if(!(H(t).mode&16384))throw n(`ENOTDIR`);this.remove(`rmdir`,t,e)}mkdirSync(e,t){let n=this.statSync(b(e)),r=new C({mode:t.mode|p,uid:n.mode&2048?n.uid:t.uid,gid:n.mode&1024?n.gid:t.gid});return this.create(`mkdir`,e,r).textContent=`[]`,r}readdirSync(e){let t=this.get(`readdir`,e);if(!(H(t).mode&16384))throw n(`ENOTDIR`);try{return JSON.parse(t.textContent)}catch(e){throw n(`EIO`,`Invalid directory listing: `+e)}}linkSync(e,t){let n=this.get(`link`,e);this.add(`link`,n,t)}touchSync(e,t){U(this.get(`touch`,e),t)}syncSync(){}readSync(e,t,n,i){let a=this.get(`read`,e),o=r(a.textContent.slice(n,i));t.set(o)}writeSync(e,n,r){let i=this.get(`write`,e),a=t(n),o=i.textContent.slice(r+a.length);i.textContent=i.textContent.slice(0,r)+a+o}toString(){return new XMLSerializer().serializeToString(this.root)}get(e,t){let r=this.root.children;if(!r)throw n(`EIO`);for(let e=0;e<r.length;e++)if(W(r[e]).includes(t))return r[e];throw n(`ENOENT`)}create(e,t,r){if(this.existsSync(t))throw n(`EEXIST`);let i=document.createElement(`file`);return this.add(e,i,t),U(i,new C({...r,uid:r.mode})),this.root.append(i),i}add(e,t,n,r=!1){let i=W(t,r);if(i.push(n),r){t.textContent=JSON.stringify(i);return}if(t.setAttribute(`paths`,JSON.stringify(i)),t.setAttribute(`nlink`,i.length.toString(16)),n!=`/`){let t=this.get(e,b(n));this.add(e,t,d(n),!0)}}remove(e,t,n,r=!1){let i=W(t,r),a=i.indexOf(n);if(a!=-1){if(i.splice(a,1),r){t.textContent=JSON.stringify(i);return}if(i.length?(t.setAttribute(`paths`,JSON.stringify(i)),t.setAttribute(`nlink`,i.length.toString(16))):t.remove(),n!=`/`){let t=this.get(e,b(n));this.remove(e,t,d(n),!0)}}}};const K={name:`XML`,options:{root:{type:`object`,required:!1}},isAvailable(){return!0},create(e){return new G(e.root)}};export{z as IndexedDB,I as IndexedDBStore,P as IndexedDBTransaction,M as WebAccess,j as WebAccessFS,V as WebStorage,B as WebStorageStore,K as XML,G as XMLFS};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{i as n,n as r,r as i,t as a}from"./path-utils-Rm3AltuN.js";import{t as o}from"./backend-local-D4WZgy4J.js";import{t as s}from"./types-idfTVsM8.js";import{a as c,i as l,n as u,t as d}from"./mount-table-store-DrF_Ifaz.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=[],i=`hard`){this.vfs=e;let a=e=>{let t=r(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=i}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=r(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 s(`EACCES`,`permission denied`,r(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,r(e));return t}catch(t){throw t instanceof s?t:new s(`ENOENT`,`no such file or directory`,r(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new s(`EACCES`,`permission denied`,r(e));return t}catch(t){throw t instanceof s?t:new s(`EACCES`,`permission denied`,r(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 s&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let o=r(i)!==r(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new s(`EACCES`,`permission denied`,r(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[r(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new s(`ENOENT`,`no such file or directory`,r(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=r(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[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,r(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=r(e);if(n===`/`)return!1;let i=n.slice(1).split(`/`),a=t?i.length:i.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+i[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=O[r(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=O[r(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=r(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 s?t:new s(`ENOENT`,`no such file or directory`,r(e))}if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,r(e));return t}async exists(e){if(O[r(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[r(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new s(`ENOENT`,`no such file or directory`,r(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[r(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 s&&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 s&&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 s(`ENOENT`,`no such file or directory`,r(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 s&&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 s(`ENOENT`,`no such file or directory`,r(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=r(t);else{let i=this.vfs.dirname(e);n=r(i+`/`+t)}if(!this.isAllowedStrict(n))throw new s(`ENOENT`,`no such file or directory`,r(e));return t}async lstat(e){let t=O[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,r(e));let n=r(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 s(`ENOENT`,`no such file or directory`,n)}let c=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(c))throw new s(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(c)}watch(e,t,n){if(!this.isAllowed(e))throw new s(`EACCES`,`permission denied`,r(e));let i=this.vfs.getWatcher();if(!i)throw new s(`EINVAL`,`no watcher configured`);return i.watch(r(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 s){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new s(e.code,r,t)}throw e}const j=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`];function M(e,t){if(e instanceof s)return e;let n=e?.code;if(typeof n==`string`){let r=n;if(j.includes(r)){let n=e instanceof Error?e.message:String(e);return new s(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new s(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new s(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new s(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new s(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new s(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new s(`ELOOP`,`too many levels of symbolic links`,t):new s(`EINVAL`,r,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,i){let o;try{o=await e.readlink(t)}catch(e){throw M(e,i)}return o.startsWith(`/`)?r(o):r(a(n(t).dir,o))}async function F(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await N(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new s(`ELOOP`,`too many symbolic links encountered`,i);o=await P(e,o,i)}}async function I(e,t,n){let i=r(n);if(t(i))return i;let a=i.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await F(e,o,a[t],t===a.length-1,i,s);o=n.resolved,s=n.hops}return o}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,i=0){let a=r(t);if(R(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(i>64||o.size>=1e5)return;let s=await z(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*V(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,i+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;static writeChains=new Map;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-4adALD4z.js`).then(e=>e.t),import(`./dist-sUBuiXIF.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-4adALD4z.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(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 s(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??U(),a=new e(n,r,i);return await a._ready,r&&await d().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=r(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-4adALD4z.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=r(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=r(e);if(this.findMount(t))return null;let i=this.lfsSync;if(typeof i.statSync!=`function`||typeof i.lstatSync!=`function`||typeof i.readlinkSync!=`function`)return null;let o=t;for(let e=0;e<=10;e++){let e;try{e=i.lstatSync(o)}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=i.readlinkSync(o)}catch{return null}o=t.startsWith(`/`)?r(t):r(a(n(o).dir,t))}return null}lstatSync(e){let t=r(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,i){let a=r(e);if(this.mountPoints.has(a))throw new s(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new s(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new s(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof s)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=C(i?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let l=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:l})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{let e={targetPath:a,descriptor:l,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await c(e,n)}catch{}}async unmount(e){let t=r(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 l(t)}catch{}}async reconstructBackendFromDescriptor(e){switch(e.kind){case`local`:{let t=await u(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return o.fromHandle(t,{mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-8csnltQ9.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-8csnltQ9.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 i=r(e);if(this.mountPoints.has(i))throw new s(`EEXIST`,`mount point is already mounted`,i);let{dir:a}=n(i);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(i)}catch{}this.mountPoints.set(i,t),this.internalMounts.add(i),this.watcher?.notify([{type:`modify`,path:i,entryType:`directory`}])}async unmountInternal(e){let t=r(e);if(!this.internalMounts.has(t))throw new s(`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=r(e),i=this.mountPoints.get(n);if(!i)throw new s(`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=r(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new s(`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,i){let a=r(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new s(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){A(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let c;try{c=await this.resolveSymlinks(a)}catch{c=a}let l=!1;try{await this.lfs.stat(c),l=!0}catch{}let{dir:u}=n(c);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(c,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(c,t)}catch(e){throw M(e,a)}}else throw M(e,a)}try{await this.lfs.truncate?.(c,e)}catch(e){throw M(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:c,entryType:`file`}])}async readDir(e){let t=r(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(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=``;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=r(e);if(n===`/`)return;let i=this.findMount(n);if(i){if(i.relParts.length===0)return;let e=i.relParts.join(`/`),t=await this.exists(n);try{await i.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=r(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new s(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let r=i.relParts.join(`/`);try{await i.backend.remove(r,{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=r(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 i=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(i);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=r(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=r(e),i=r(t),a;try{a=(await this.lstat(n)).type}catch{}try{await this.lfs.rename(n,i)}catch(e){throw M(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:i,entryType:a}]),this.mountIndex.notifyRename(n,i)}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 s(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(r(e)).dir}basename(e){return n(r(e)).base}async symlink(e,t){let i=r(t);if(this.findMount(i))throw new s(`EINVAL`,`symlinks not supported on mounted filesystems`,i);let{dir:a}=n(i);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(e){throw M(e,i)}}else throw M(t,i)}await this.writeOpfsMetadataSidecar()}),this.watcher?.notify([{type:`create`,path:i,entryType:`symlink`}])}async readlink(e){let t=r(e);try{return await this.lfs.readlink(t)}catch(e){throw M(e,t)}}async lstat(e){let t=r(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:()=>s,FsWatcher:()=>h,MountIndex:()=>w,RestrictedFS:()=>k,VirtualFS:()=>W,joinPath:()=>a,normalizePath:()=>r,pathSegments:()=>i,resolveVfsBackendFromEnv:()=>U,splitPath:()=>n});export{h as a,D as i,W as n,k as r,G as t};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-CoWnU-QN.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/dist-Ca06zVsb.js","assets/mount-CxmnNZsY.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-ugOWOUZ9.js","assets/base64-DpPqYZJF.js","assets/src-CAWTvdAa.js","assets/proxied-fetch-ULPrH97b.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/types-idfTVsM8.js","assets/backend-local-Btkv66jT.js","assets/tool-ui-DfXu6quJ.js","assets/logger-DDBAeTLF.js","assets/picker-approval-CdWaB1mR.js","assets/mount-picker-popup-CSSC05JS.js","assets/picker-popup-BvzmBsGL.js","assets/mount-table-store-dY2IfQ5S.js","assets/mount-bridge-client-DkyfUm3y.js","assets/port-bridge-client-Bg6_jjLD.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.js";import{i as n,n as r,r as i,t as a}from"./path-utils-Rm3AltuN.js";import{t as o}from"./types-idfTVsM8.js";import{t as s}from"./virtual-device-paths-9EXC9iPp.js";import{t as c}from"./backend-local-Btkv66jT.js";import{a as l,i as u,n as d,t as f}from"./mount-table-store-dY2IfQ5S.js";var p=t(`fs-watcher`),m=0;function h(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var g=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++m}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),p.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),p.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>h(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){p.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),p.debug(`All watchers disposed`)}get size(){return this.registrations.size}},_=t(`mount-index`),v=400,y=2e6,b=`SLICC_MOUNT_INDEX_MAX_DEPTH`,x=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,S=256,C=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function w(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>S?t.slice(0,S):t;return`${t.length}\u0001${n.join(``)}`}async function T(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function E(e,t){return e instanceof Map?e.get(t):e[t]}function D(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function O(e,t,n){let r=E(e,t);if(r===void 0||r.trim()===``)return n;let i=D(r);return i===void 0?(_.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function k(e){return{maxDepth:O(e,b,v),maxEntries:O(e,x,y)}}var A=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=k({})){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,_.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 C?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},_.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 C(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new C(`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 C(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=w(n),a=r.get(i);if(a){for(let n of a)if(await T(n.handle,t))throw new C(`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)))}}},j={[s]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},M=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],i=`hard`){this.vfs=e;let a=e=>{let t=r(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=i}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=r(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 o(`EACCES`,`permission denied`,r(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}catch(t){throw t instanceof o?t:new o(`ENOENT`,`no such file or directory`,r(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new o(`EACCES`,`permission denied`,r(e));return t}catch(t){throw t instanceof o?t:new o(`EACCES`,`permission denied`,r(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 o&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let s=r(i)!==r(t);if(!(this.writeEnforcement===`sudo-delegated`&&!s))throw new o(`EACCES`,`permission denied`,r(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=j[r(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(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=r(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=j[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(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=r(e);if(n===`/`)return!1;let i=n.slice(1).split(`/`),a=t?i.length:i.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+i[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=j[r(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=j[r(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=r(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 o?t:new o(`ENOENT`,`no such file or directory`,r(e))}if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}async exists(e){if(j[r(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=j[r(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(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=j[r(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 o&&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 o&&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 o(`ENOENT`,`no such file or directory`,r(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 o&&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 o(`ENOENT`,`no such file or directory`,r(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=r(t);else{let i=this.vfs.dirname(e);n=r(i+`/`+t)}if(!this.isAllowedStrict(n))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}async lstat(e){let t=j[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let n=r(e),i=this.vfs.dirname(n),a=this.vfs.basename(n),s;if(i===n)s=i;else try{s=await this.vfs.realpath(i)}catch{throw new o(`ENOENT`,`no such file or directory`,n)}let c=s===`/`?`/${a}`:`${s}/${a}`;if(!this.isAllowed(c))throw new o(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(c)}watch(e,t,n){if(!this.isAllowed(e))throw new o(`EACCES`,`permission denied`,r(e));let i=this.vfs.getWatcher();if(!i)throw new o(`EINVAL`,`no watcher configured`);return i.watch(r(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 N(e,t){if(e instanceof o){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new o(e.code,r,t)}throw e}var P=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`];function F(e,t){if(e instanceof o)return e;let n=e?.code;if(typeof n==`string`){let r=n;if(P.includes(r)){let n=e instanceof Error?e.message:String(e);return new o(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new o(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new o(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new o(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new o(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new o(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new o(`ELOOP`,`too many levels of symbolic links`,t):new o(`EINVAL`,r,t)}async function I(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=F(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function L(e,t,i){let o;try{o=await e.readlink(t)}catch(e){throw F(e,i)}return o.startsWith(`/`)?r(o):r(a(n(t).dir,o))}async function R(e,t,n,r,i,a){let s=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await I(e,s,r,i);if(t===null||!t.isSymbolicLink())return{resolved:s,hops:a};if(++a>10)throw new o(`ELOOP`,`too many symbolic links encountered`,i);s=await L(e,s,i)}}async function z(e,t,n){let i=r(n);if(t(i))return i;let a=i.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await R(e,o,a[t],t===a.length-1,i,s);o=n.resolved,s=n.hops}return o}async function B(e,t,n){return t(n)?n:z(e,t,n)}function V(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 H(e,t){try{return await e(t)}catch{return t}}async function*U(e,t,n,i=0){let a=r(t);if(V(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(i>64||o.size>=1e5)return;let s=await H(t=>e.realpath(t),a);if(o.has(s))return;o.add(s);let c=await e.readDir(a);for(let t of c)yield*W(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,i+1)}async function*W(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*G(e,n,r,i);return}yield*U(e,n,r,i)}async function*G(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*U(e,t,n,r))}catch{}}function K(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var q=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 A;static writeChains=new Map;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-CoWnU-QN.js`).then(e=>e.t),__vite__mapDeps([0,1])),e(()=>import(`./dist-Ca06zVsb.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-CoWnU-QN.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===null&&(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 n=navigator.storage;if(!n?.getDirectory)throw new o(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(e){return new t(e)}static async create(e){let n=e?.dbName??`browser-fs`,r=e?.wipe===!0,i=e?.backend??K(),a=new t(n,r,i);return await a._ready,r&&await f().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=r(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-CoWnU-QN.js`).then(e=>e.t),__vite__mapDeps([0,1]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=r(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=r(e);if(this.findMount(t))return null;let i=this.lfsSync;if(typeof i.statSync!=`function`||typeof i.lstatSync!=`function`||typeof i.readlinkSync!=`function`)return null;let o=t;for(let e=0;e<=10;e++){let e;try{e=i.lstatSync(o)}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=i.readlinkSync(o)}catch{return null}o=t.startsWith(`/`)?r(t):r(a(n(o).dir,t))}return null}lstatSync(e){let t=r(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,i){let a=r(e);if(this.mountPoints.has(a))throw new o(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new o(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new o(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof o)||e.code!==`ENOENT`)throw e}let{dir:s}=n(a);s!==`/`&&await this.mkdir(s,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=k(i?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let c=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:c})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{let e={targetPath:a,descriptor:c,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await l(e,n)}catch{}}async unmount(e){let t=r(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 u(t)}catch{}}async reconstructBackendFromDescriptor(t){switch(t.kind){case`local`:{let e=await d(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return c.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-CxmnNZsY.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-CxmnNZsY.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 i=r(e);if(this.mountPoints.has(i))throw new o(`EEXIST`,`mount point is already mounted`,i);let{dir:a}=n(i);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(i)}catch{}this.mountPoints.set(i,t),this.internalMounts.add(i),this.watcher?.notify([{type:`modify`,path:i,entryType:`directory`}])}async unmountInternal(e){let t=r(e);if(!this.internalMounts.has(t))throw new o(`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=r(e),i=this.mountPoints.get(n);if(!i)throw new o(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n,k(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=r(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new o(`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){N(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 F(e,n)}}async writeFile(e,t,i){let a=r(e),s=this.findMount(a);if(s){if(s.relParts.length===0)throw new o(`EISDIR`,`is a directory`,a);let e=s.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await s.backend.writeFile(e,r)}catch(e){N(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let c;try{c=await this.resolveSymlinks(a)}catch{c=a}let l=!1;try{await this.lfs.stat(c),l=!0}catch{}let{dir:u}=n(c);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(c,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(c,t)}catch(e){throw F(e,a)}}else throw F(e,a)}try{await this.lfs.truncate?.(c,e)}catch(e){throw F(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:c,entryType:`file`}])}async readDir(e){let t=r(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){N(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 F(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 n=this.dbName,r,i=new Promise(e=>{r=e}),a=t.writeChains.get(n)??Promise.resolve();t.writeChains.set(n,i),await a;try{let t=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof t?.request!=`function`?await e():await t.request(`slicc-vfs:${n}`,()=>e())}finally{r(),t.writeChains.get(n)===i&&t.writeChains.delete(n)}}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 F(e,n)}}}async mkdir(e,t){let n=r(e);if(n===`/`)return;let i=this.findMount(n);if(i){if(i.relParts.length===0)return;let e=i.relParts.join(`/`),t=await this.exists(n);try{await i.backend.mkdir(e)}catch(e){N(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 F(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]))}async rm(e,t){let n=r(e),i=this.findMount(n);if(i){if(i.relParts.length===0)throw new o(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let r=i.relParts.join(`/`);try{await i.backend.remove(r,{recursive:t?.recursive})}catch(e){N(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 F(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=r(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){N(e,t)}}let i=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(i);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw F(e,t)}}async exists(e){let t=r(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=r(e),i=r(t),a;try{a=(await this.lstat(n)).type}catch{}try{await this.lfs.rename(n,i)}catch(e){throw F(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:i,entryType:a}]),this.mountIndex.notifyRename(n,i)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*U({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 o(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(r(e)).dir}basename(e){return n(r(e)).base}async symlink(e,t){let i=r(t);if(this.findMount(i))throw new o(`EINVAL`,`symlinks not supported on mounted filesystems`,i);let{dir:a}=n(i);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,i)}catch(e){throw F(e,i)}}else throw F(t,i)}await this.writeOpfsMetadataSidecar()}),this.watcher?.notify([{type:`create`,path:i,entryType:`symlink`}])}async readlink(e){let t=r(e);try{return await this.lfs.readlink(t)}catch(e){throw F(e,t)}}async lstat(e){let t=r(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 F(e,t)}}async realpath(e){return z(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return B(this.lfs,e=>this.findMount(e)!==null,e)}};export{o as FsError,g as FsWatcher,A as MountIndex,M as RestrictedFS,q as VirtualFS,a as joinPath,r as normalizePath,i as pathSegments,K as resolveVfsBackendFromEnv,n as splitPath};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/fs-VCwbgYvh.js","assets/preload-helper-Czpn1I53.js","assets/logger-DDBAeTLF.js","assets/path-utils-Rm3AltuN.js","assets/types-idfTVsM8.js","assets/virtual-device-paths-9EXC9iPp.js","assets/backend-local-Btkv66jT.js","assets/tool-ui-DfXu6quJ.js","assets/picker-approval-CdWaB1mR.js","assets/mount-picker-popup-CSSC05JS.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/picker-popup-BvzmBsGL.js","assets/runtime-env-DH4NDw4t.js","assets/mount-table-store-dY2IfQ5S.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{S as e,d as t,z as n}from"./account-store-fsZiMtXd.js";import{t as r}from"./preload-helper-Czpn1I53.js";import{i}from"./proxied-fetch-ULPrH97b.js";import{i as a,t as o}from"./tray-runtime-config-C82czC62.js";import"./provider-settings-DRzBx_K-.js";import{r as s,t as c}from"./silent-renew-backoff-tbYCpSw6.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-Dmnx-pbE.js";import{t as d}from"./global-db-CbuLl-zx.js";var f={clientId:``,scopes:`repo,read:user,user:email`};function p(){try{let e=localStorage.getItem(a);if(e)return e.replace(/\/$/,``)}catch{}return o}async function m(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return t}async function h(e){let t=`${p()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function g(e){let t=`${p()}/oauth/token`;return m(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function _(e){let t=`${p()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}var v=Object.assign({"/packages/webapp/providers/github-config.json":f})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`},y=null,b=null;function x(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function S(){if(y)return y;if(C){try{let e=await fetch(`${p()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}catch{}return v.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,t.trayWorkerBaseUrl&&(b=t.trayWorkerBaseUrl),y;if(t.trayWorkerBaseUrl){b=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return y=t.oauth.github,y}}}}catch{}return v.clientId}var C=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function w(){return t().find(e=>e.providerId===`github`)}function T(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function E(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function D(e,t){return`${e}+${t}@users.noreply.github.com`}async function O(e){try{let{VirtualFS:t}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-VCwbgYvh.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]));await(await t.create({dbName:d})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function k(){try{let{VirtualFS:e}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-VCwbgYvh.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13]));await(await e.create({dbName:d})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function A(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await r(async()=>{let{VirtualFS:e}=await import(`./fs-VCwbgYvh.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13])),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:i}=await r(async()=>{let{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}=await import(`./git-config-DLJIrKjL.js`);return{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}},[]),a=await t.create({dbName:d}),o=e.name||e.login,s=D(e.id,e.login);!await n(a,`user.name`)&&o&&await i(a,`user.name`,o),await n(a,`user.email`)||await i(a,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}var j=c();async function M(){try{let t=w();if(!t?.refreshToken)return null;let r=await g({provider:`github`,refreshToken:t.refreshToken});await n({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:t.userName,userAvatar:t.userAvatar,scopes:r.scope??t.scopes});let i=e(`github`)?.maskedValue;return i?await O(i):await k(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function N(){let e=w();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return e.accessToken;let t=await j.run(()=>M());if(t)return t;let n=w();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`GitHub session expired — please log in again`)}var P={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(t,r,a)=>{let o=await S();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??v.scopes,c=C?null:await l(),d=!C&&await u(),f=crypto.randomUUID(),m=C?chrome.runtime.id:``,{redirectUri:g,state:_}=x({isExtension:C,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:p(),runtimeWorkerBaseUrl:b,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:i(),delegated:d,extensionId:m,nonce:f}),y=btoa(JSON.stringify(_)),w=f,D=new URLSearchParams({client_id:o,scope:s,redirect_uri:g});y&&D.set(`state`,y);let j=await t(`https://github.com/login/oauth/authorize?${D}`);if(!j)return;if(w)try{if(new URL(j).searchParams.get(`nonce`)!==w){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=T(j);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await h({provider:`github`,code:M,redirectUri:g}),P=await E(N.access_token);await n({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=e(`github`)?.maskedValue;F?await O(F):await k(),await A(P),r()},onSilentRenew:M,getValidAccessToken:N,onOAuthLogout:async()=>{let e=w();e?.accessToken&&await _({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await k(),await n({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{D as buildNoreplyEmail,P as config,T as extractCodeFromUrl,N as getValidAccessToken,x as resolveGithubOAuthRedirect,A as syncGitIdentityFromGitHub};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{S as e,d as t,z as n}from"./account-store-DWX-EZHx.js";import{i as r}from"./proxied-fetch-BML_ivCH.js";import{r as i,t as a}from"./tray-runtime-config-ObNW_fQX.js";import{t as o}from"./global-db-DJXlpNui.js";import{r as s,t as c}from"./silent-renew-backoff-BrAZcbzt.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-a6YE6xTR.js";import"./provider-settings-LcSPuWPj.js";var d={clientId:``,scopes:`repo,read:user,user:email`};function f(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return a}async function p(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return t}async function m(e){let t=`${f()}/oauth/token`;return p(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function h(e){let t=`${f()}/oauth/token`;return p(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})}))}async function g(e){let t=`${f()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}const _=Object.assign({"/packages/webapp/providers/github-config.json":d})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let v=null,y=null;function b(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function x(){if(v)return v;if(S){try{let e=await fetch(`${f()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return v=t.oauth.github,v}}catch{}return _.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return v=t.oauth.github,t.trayWorkerBaseUrl&&(y=t.trayWorkerBaseUrl),v;if(t.trayWorkerBaseUrl){y=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return v=t.oauth.github,v}}}}catch{}return _.clientId}const S=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function C(){return t().find(e=>e.providerId===`github`)}function w(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function T(e){try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`}});if(t.ok){let e=await t.json();return{name:e.name||e.login,avatar:e.avatar_url,login:e.login,id:e.id}}}catch(e){console.warn(`[github] Failed to fetch user profile:`,e instanceof Error?e.message:String(e))}return{}}function E(e,t){return`${e}+${t}@users.noreply.github.com`}async function D(e){try{let{VirtualFS:t}=await import(`./fs-CqrpSNTX.js`).then(e=>e.t);await(await t.create({dbName:o})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function O(){try{let{VirtualFS:e}=await import(`./fs-CqrpSNTX.js`).then(e=>e.t);await(await e.create({dbName:o})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function k(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await import(`./fs-CqrpSNTX.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:r}=await import(`./git-config-DA8M5e8O.js`).then(e=>e.n),i=await t.create({dbName:o}),a=e.name||e.login,s=E(e.id,e.login);!await n(i,`user.name`)&&a&&await r(i,`user.name`,a),await n(i,`user.email`)||await r(i,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}const A=c();async function j(){try{let t=C();if(!t?.refreshToken)return null;let r=await h({provider:`github`,refreshToken:t.refreshToken});await n({providerId:`github`,accessToken:r.access_token,refreshToken:r.refresh_token,tokenExpiresAt:r.expires_in?Date.now()+r.expires_in*1e3:void 0,userName:t.userName,userAvatar:t.userAvatar,scopes:r.scope??t.scopes});let i=e(`github`)?.maskedValue;return i?await D(i):await O(),r.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function M(){let e=C();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return e.accessToken;let t=await A.run(()=>j());if(t)return t;let n=C();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return n.accessToken;throw Error(`GitHub session expired — please log in again`)}const N={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(t,i,a)=>{let o=await x();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??_.scopes,c=S?null:await l(),d=!S&&await u(),p=crypto.randomUUID(),h=S?chrome.runtime.id:``,{redirectUri:g,state:v}=b({isExtension:S,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:f(),runtimeWorkerBaseUrl:y,pageOrigin:c?.origin??null,pageHref:c?.href??null,bridgeApiBaseUrl:r(),delegated:d,extensionId:h,nonce:p}),C=btoa(JSON.stringify(v)),E=p,A=new URLSearchParams({client_id:o,scope:s,redirect_uri:g});C&&A.set(`state`,C);let j=await t(`https://github.com/login/oauth/authorize?${A}`);if(!j)return;if(E)try{if(new URL(j).searchParams.get(`nonce`)!==E){console.error(`[github] OAuth nonce mismatch — possible CSRF`);return}}catch(e){console.warn(`[github] Nonce check skipped (URL parse failed):`,e instanceof Error?e.message:String(e))}let M=w(j);if(!M){console.error(`[github] Could not extract authorization code from redirect URL`);return}let N=await m({provider:`github`,code:M,redirectUri:g}),P=await T(N.access_token);await n({providerId:`github`,accessToken:N.access_token,refreshToken:N.refresh_token,tokenExpiresAt:N.expires_in?Date.now()+N.expires_in*1e3:void 0,userName:P.name,userAvatar:P.avatar,scopes:N.scope});let F=e(`github`)?.maskedValue;F?await D(F):await O(),await k(P),i()},onSilentRenew:j,getValidAccessToken:M,onOAuthLogout:async()=>{let e=C();e?.accessToken&&await g({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await O(),await n({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{E as buildNoreplyEmail,N as config,w as extractCodeFromUrl,M as getValidAccessToken,b as resolveGithubOAuthRedirect,k as syncGitIdentityFromGitHub};
|