sliccy 6.55.2 → 6.55.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/ui/assets/{account-store-B0inTvu6.js → account-store-CZ1gUZlp.js} +1 -1
  2. package/dist/ui/assets/{account-store-m7EtgLrd.js → account-store-MovPQ1t7.js} +1 -1
  3. package/dist/ui/assets/{adobe-Cf0pn2tU.js → adobe-Cw5eDX4j.js} +1 -1
  4. package/dist/ui/assets/{adobe-Cj5x46ow.js → adobe-DlVylgIQ.js} +1 -1
  5. package/dist/ui/assets/{agent-message-to-chat-BpgSdE7h.js → agent-message-to-chat-BTL5421I.js} +1 -1
  6. package/dist/ui/assets/{apply-layout-bru2BWxc.js → apply-layout-BQ84g53u.js} +1 -1
  7. package/dist/ui/assets/{apps-DJCljXQk.js → apps-n8Eucw13.js} +1 -1
  8. package/dist/ui/assets/{azure-openai-B15CN8ee.js → azure-openai-C0K8_P2M.js} +1 -1
  9. package/dist/ui/assets/{azure-openai-DThYpCXW.js → azure-openai-dxVEczfe.js} +1 -1
  10. package/dist/ui/assets/{bsh-watchdog-CsAAYkov.js → bsh-watchdog-D6UHy3xi.js} +1 -1
  11. package/dist/ui/assets/{cerebras-B5waaxE6.js → cerebras-Cb2QF_Nj.js} +1 -1
  12. package/dist/ui/assets/{cerebras-d0srV-i_.js → cerebras-DACZwM4H.js} +1 -1
  13. package/dist/ui/assets/{connect-surface-B6NQaXSg.js → connect-surface-IVYV6Y4d.js} +1 -1
  14. package/dist/ui/assets/{ensure-speech-assets-DuQaHF0c.js → ensure-speech-assets-D-XWvZef.js} +1 -1
  15. package/dist/ui/assets/{esbuild-wasm-DsMq-s8o.js → esbuild-wasm-BHiYsKGe.js} +1 -1
  16. package/dist/ui/assets/fs-CFP623sx.js +1 -0
  17. package/dist/ui/assets/fs-DdomU_RK.js +2 -0
  18. package/dist/ui/assets/{github-DiQOI0Pd.js → github-CLZxdeQj.js} +2 -2
  19. package/dist/ui/assets/{github-DIpJ-yA9.js → github-DYEtdsqL.js} +1 -1
  20. package/dist/ui/assets/{github-copilot-DMqtYs8B.js → github-copilot-DCVye4Up.js} +1 -1
  21. package/dist/ui/assets/{github-copilot-DJjGcP35.js → github-copilot-DLklF6-w.js} +1 -1
  22. package/dist/ui/assets/{github-install-Ccrjhg5T.js → github-install-TS-wUZLH.js} +1 -1
  23. package/dist/ui/assets/{github-zip-YBTmfoPU.js → github-zip-_km37B0C.js} +1 -1
  24. package/dist/ui/assets/{hear-DvNnxDnX.js → hear-RC5utA5r.js} +1 -1
  25. package/dist/ui/assets/{installer-DDJZNOgZ.js → installer-Bi0ukFsW.js} +1 -1
  26. package/dist/ui/assets/{kernel-worker-DPGAky3U.js → kernel-worker-Cy9UFIUc.js} +375 -375
  27. package/dist/ui/assets/{kokoro-engine-2bQR6a7X.js → kokoro-engine-W-8wCA-C.js} +1 -1
  28. package/dist/ui/assets/{local-llm-nU3dLruP.js → local-llm-CrYIvk-s.js} +1 -1
  29. package/dist/ui/assets/{local-llm-DVbqW5tQ.js → local-llm-Dv2UiP_c.js} +1 -1
  30. package/dist/ui/assets/{magick-wasm-BYrT_yC4.js → magick-wasm-DEZVAsny.js} +1 -1
  31. package/dist/ui/assets/{main-GTxjUHRy.js → main-CqQy149J.js} +3 -3
  32. package/dist/ui/assets/{mount-BDdh4EsD.js → mount-C258ctaZ.js} +2 -2
  33. package/dist/ui/assets/{mount-Ddl9KcNn.js → mount-ZIk2nJ0B.js} +1 -1
  34. package/dist/ui/assets/{mount-recovery-BvUCHm7S.js → mount-recovery-BZRk8kQT.js} +1 -1
  35. package/dist/ui/assets/{new-session-D8XLocZ8.js → new-session-7elGqHHZ.js} +2 -2
  36. package/dist/ui/assets/{oauth-bootstrap-kZvuJqUX.js → oauth-bootstrap-CtPAplKI.js} +2 -2
  37. package/dist/ui/assets/{openai-codex-DzM2nZs7.js → openai-codex-DWZrPgg1.js} +1 -1
  38. package/dist/ui/assets/{openai-codex-BcTtS45y.js → openai-codex-DupPAjdl.js} +1 -1
  39. package/dist/ui/assets/{openrouter-DiPv3qg9.js → openrouter-BEmD97Ft.js} +1 -1
  40. package/dist/ui/assets/{openrouter-BZEGuNBF.js → openrouter-DK3JNe8t.js} +1 -1
  41. package/dist/ui/assets/{openrouter-oauth-CbMY1jzk.js → openrouter-oauth-BiwslDkw.js} +1 -1
  42. package/dist/ui/assets/{openrouter-oauth-xSIr9rPt.js → openrouter-oauth-C37ce72O.js} +1 -1
  43. package/dist/ui/assets/{panel-rpc-handlers-C-a__Bi-.js → panel-rpc-handlers-CTn-genP.js} +2 -2
  44. package/dist/ui/assets/path-utils-DNJG-zQf.js +1 -0
  45. package/dist/ui/assets/{provider-B-uE3ZCz.js → provider-BVgpvvkj.js} +1 -1
  46. package/dist/ui/assets/{provider-Be0E_IMW.js → provider-bW1Hj2wt.js} +2 -2
  47. package/dist/ui/assets/{provider-settings-Cla-Ao_F.js → provider-settings-DPTmaMK4.js} +1 -1
  48. package/dist/ui/assets/{provider-settings-StjddRwF.js → provider-settings-Dw_3F-KV.js} +1 -1
  49. package/dist/ui/assets/{provider-store-access-CkLew2RG.js → provider-store-access-B9adXQNa.js} +2 -2
  50. package/dist/ui/assets/provider-store-access-Cmhw6qyw.js +1 -0
  51. package/dist/ui/assets/{providers-Brpn-3iE.js → providers-CflLgJPY.js} +1 -1
  52. package/dist/ui/assets/{providers-DR6MxN4s.js → providers-CopfWmua.js} +2 -2
  53. package/dist/ui/assets/{quick-llm-DX70ALhs.js → quick-llm-BqAaPz_b.js} +1 -1
  54. package/dist/ui/assets/{recovery-screen-DB1To5sJ.js → recovery-screen-DyjJnOh1.js} +1 -1
  55. package/dist/ui/assets/{redirect-uri-BrFcQUXI.js → redirect-uri-uos4r3cb.js} +1 -1
  56. package/dist/ui/assets/{session-freezer-Cq9qF8FZ.js → session-freezer-DSbFNZoP.js} +3 -3
  57. package/dist/ui/assets/{setup-feature-flags-remote-DE6MSHD9.js → setup-feature-flags-remote-5UKNRVSU.js} +1 -1
  58. package/dist/ui/assets/{setup-standalone-prelude-D05fd3f-.js → setup-standalone-prelude-CvG3zGpm.js} +1 -1
  59. package/dist/ui/assets/{setup-sudo-CmLT9Etp.js → setup-sudo-P4YgaU1V.js} +2 -2
  60. package/dist/ui/assets/shared-CS4zRQ6K.js +4 -0
  61. package/dist/ui/assets/{skills-7beI-IKL.js → skills-BluD2S0L.js} +4 -4
  62. package/dist/ui/assets/{speak-pezNrAJe.js → speak-CiGoP8I8.js} +1 -1
  63. package/dist/ui/assets/{store-Cxd6lAkh.js → store-BQwLbPtn.js} +1 -1
  64. package/dist/ui/assets/{store-CSk8LOYP.js → store-DGC49oy4.js} +1 -1
  65. package/dist/ui/assets/{sudo-C_oJCkxM.js → sudo-DhP-fzH2.js} +1 -1
  66. package/dist/ui/assets/{tool-result-images-Dm6tlkfz.js → tool-result-images-CoHoX9-W.js} +1 -1
  67. package/dist/ui/assets/{transformers-env-wpY2kxZs.js → transformers-env-K0tWLb5G.js} +1 -1
  68. package/dist/ui/assets/{upgrade-detection-qNoriX8R.js → upgrade-detection-DcC0OPx7.js} +1 -1
  69. package/dist/ui/assets/{wc-extension-xGmsids-.js → wc-extension-CSkBhP1K.js} +2 -2
  70. package/dist/ui/assets/{wc-follower-CS5nhoDP.js → wc-follower-C6Rqt6JD.js} +3 -3
  71. package/dist/ui/assets/{wc-live-BOWfCqId.js → wc-live-2WTa2Agb.js} +4 -4
  72. package/dist/ui/assets/{wc-nav-DYVpfhGQ.js → wc-nav-Cv6sXz40.js} +2 -2
  73. package/dist/ui/assets/{wc-onboarding-CUVC-Tlh.js → wc-onboarding-IUt48Et5.js} +2 -2
  74. package/dist/ui/assets/{wc-placeholder-BRdrJsyS.js → wc-placeholder-D_UVRCyH.js} +2 -2
  75. package/dist/ui/assets/{wc-settings-BrLzoBWh.js → wc-settings-kSMausnf.js} +2 -2
  76. package/dist/ui/assets/{wc-shell-DvAzKQ8n.js → wc-shell-BVgleBNS.js} +2 -2
  77. package/dist/ui/assets/{wc-sprinkles-BJ52zD0V.js → wc-sprinkles-Buo3BmOo.js} +2 -2
  78. package/dist/ui/assets/{wc-tray-D4CqyT3U.js → wc-tray-DjSuT778.js} +2 -2
  79. package/dist/ui/assets/{whisper-engine-Cy4tNnVy.js → whisper-engine-JcWkuin6.js} +1 -1
  80. package/dist/ui/assets/{ws-subscribers-ZoJOTa93.js → ws-subscribers-CKHqIv8e.js} +1 -1
  81. package/dist/ui/assets/{xai-grok-BEU-yDtv.js → xai-grok-D5qL7rdL.js} +1 -1
  82. package/dist/ui/assets/{xai-grok-DPl1-t2U.js → xai-grok-DBZr0LW9.js} +1 -1
  83. package/dist/ui/index.html +6 -6
  84. package/dist/ui/packages/webapp/index.html +6 -6
  85. package/package.json +1 -1
  86. package/dist/ui/assets/fs-BrZitfrE.js +0 -1
  87. package/dist/ui/assets/fs-CSJFeAoX.js +0 -2
  88. package/dist/ui/assets/path-utils-Rm3AltuN.js +0 -1
  89. package/dist/ui/assets/provider-store-access-aeWPaRJw.js +0 -1
  90. package/dist/ui/assets/shared-CvRDmxWf.js +0 -4
@@ -1,4 +1,4 @@
1
- import{b as e,g as t}from"./account-store-B0inTvu6.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{i as r,s as i,t as a}from"./transform-messages-DEFauvrq.js";import{p as o}from"./bedrock-camp-BfNg24Ce.js";function s(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function c(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let l=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return l=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function u(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const d=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var f=class extends Error{},p=class e extends f{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new h({message:r,cause:d(n)});let a=n?.error;return t===400?new _(t,a,r,i):t===401?new v(t,a,r,i):t===403?new y(t,a,r,i):t===404?new b(t,a,r,i):t===409?new x(t,a,r,i):t===422?new ee(t,a,r,i):t===429?new te(t,a,r,i):t>=500?new ne(t,a,r,i):new e(t,a,r,i)}},m=class extends p{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},h=class extends p{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},g=class extends h{constructor({message:e}={}){super({message:e??`Request timed out.`})}},_=class extends p{},v=class extends p{},y=class extends p{},b=class extends p{},x=class extends p{},ee=class extends p{},te=class extends p{},ne=class extends p{},re=class extends f{constructor(){super(`Could not parse response content as the length limit was reached`)}},ie=class extends f{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},ae=class extends Error{constructor(e){super(e)}},oe=class extends p{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},se=class extends f{constructor(e,t,n){super(e),this.provider=t,this.cause=n}};const ce=/^[a-z][a-z0-9+.-]*:/i,le=e=>ce.test(e);let S=e=>(S=Array.isArray,S(e)),ue=S;function de(e){return typeof e==`object`?e??{}:{}}function fe(e){if(!e)return!0;for(let t in e)return!1;return!0}function pe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function me(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const he=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new f(`${e} must be an integer`);if(t<0)throw new f(`${e} must be a positive integer`);return t},ge=e=>{try{return JSON.parse(e)}catch{return}},_e=e=>new Promise(t=>setTimeout(t,e)),ve=`7.0.0`,ye=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function be(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const xe=()=>{let e=be();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"X-Stainless-OS":we(Deno.build.os),"X-Stainless-Arch":Ce(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"X-Stainless-OS":we(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Ce(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Se();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Se(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const Ce=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,we=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let Te;const Ee=()=>Te??=xe();function De(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Oe(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ke(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Oe({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Ae(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function je(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Me=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),Ne=`RFC3986`,Pe=e=>String(e),Fe={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Pe};let Ie=(e,t)=>(Ie=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ie(e,t));const C=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Le=1024,Re=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=Le){let t=a.length>=Le?a.slice(e,e+Le):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=C[r];continue}if(r<2048){n[n.length]=C[192|r>>6]+C[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=C[224|r>>12]+C[128|r>>6&63]+C[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=C[240|r>>18]+C[128|r>>12&63]+C[128|r>>6&63]+C[128|r&63]}o+=n.join(``)}return o};function ze(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Be(e,t){if(S(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const Ve={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},He=function(e,t){Array.prototype.push.apply(e,S(t)?t:[t])};let Ue;const w={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Re,encodeValuesOnly:!1,format:Ne,formatter:Pe,indices:!1,serializeDate(e){return(Ue??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function We(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}const Ge={};function Ke(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(Ge))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(Ge)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&S(v)&&(v=Be(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,w.encoder,g,`key`,p):t;v=``}if(We(v)||ze(v)){if(c){let e=h?t:c(t,w.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,w.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let ee=[];if(v===void 0)return ee;let te;if(n===`comma`&&S(v))h&&c&&(v=Be(v,c)),te=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(S(l))te=l;else{let e=Object.keys(v);te=u?e.sort(u):e}let ne=s?String(t).replace(/\./g,`%2E`):String(t),re=r&&S(v)&&v.length===1?ne+`[]`:ne;if(i&&S(v)&&v.length===0)return re+`[]`;for(let t=0;t<te.length;++t){let y=te[t],x=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&x===null)continue;let ne=d&&s?y.replace(/\./g,`%2E`):y,ie=S(v)?typeof n==`function`?n(re,ne):re:re+(d?`.`+ne:`[`+ne+`]`);_.set(e,b);let ae=new WeakMap;ae.set(Ge,_),He(ee,Ke(x,ie,n,r,i,a,o,s,n===`comma`&&h&&S(v)?null:c,l,u,d,f,p,m,h,g,ae))}return ee}function qe(e=w){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||w.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=Ne;if(e.format!==void 0){if(!Ie(Fe,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=Fe[n],i=w.filter;(typeof e.filter==`function`||S(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ve?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:w.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:w.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:w.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:w.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:w.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?w.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:w.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:w.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:w.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:w.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:w.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:w.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:w.strictNullHandling}}function Je(e,t={}){let n=e,r=qe(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):S(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ve[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||He(o,Ke(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Ye(e){return Je(e,{arrayFormat:`brackets`})}function Xe(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let Ze;function T(e){let t;return(Ze??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let Qe;function $e(e){let t;return(Qe??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var E,D,et=class{constructor(){E.set(this,void 0),D.set(this,void 0),s(this,E,new Uint8Array,`f`),s(this,D,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?T(e):e;s(this,E,Xe([c(this,E,`f`),t]),`f`);let n=[],r;for(;(r=tt(c(this,E,`f`),c(this,D,`f`)))!=null;){if(r.carriage&&c(this,D,`f`)==null){s(this,D,r.index,`f`);continue}if(c(this,D,`f`)!=null&&(r.index!==c(this,D,`f`)+1||r.carriage)){n.push($e(c(this,E,`f`).subarray(0,c(this,D,`f`)-1))),s(this,E,c(this,E,`f`).subarray(c(this,D,`f`)),`f`),s(this,D,null,`f`);continue}let e=c(this,D,`f`)===null?r.preceding:r.preceding-1,t=$e(c(this,E,`f`).subarray(0,e));n.push(t),s(this,E,c(this,E,`f`).subarray(r.index),`f`),s(this,D,null,`f`)}return n}flush(){return c(this,E,`f`).length?this.decode(`
1
+ import{b as e,g as t}from"./account-store-CZ1gUZlp.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{i as r,s as i,t as a}from"./transform-messages-DEFauvrq.js";import{p as o}from"./bedrock-camp-BfNg24Ce.js";function s(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function c(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let l=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return l=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function u(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const d=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var f=class extends Error{},p=class e extends f{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new h({message:r,cause:d(n)});let a=n?.error;return t===400?new _(t,a,r,i):t===401?new v(t,a,r,i):t===403?new y(t,a,r,i):t===404?new b(t,a,r,i):t===409?new x(t,a,r,i):t===422?new ee(t,a,r,i):t===429?new te(t,a,r,i):t>=500?new ne(t,a,r,i):new e(t,a,r,i)}},m=class extends p{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},h=class extends p{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},g=class extends h{constructor({message:e}={}){super({message:e??`Request timed out.`})}},_=class extends p{},v=class extends p{},y=class extends p{},b=class extends p{},x=class extends p{},ee=class extends p{},te=class extends p{},ne=class extends p{},re=class extends f{constructor(){super(`Could not parse response content as the length limit was reached`)}},ie=class extends f{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},ae=class extends Error{constructor(e){super(e)}},oe=class extends p{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},se=class extends f{constructor(e,t,n){super(e),this.provider=t,this.cause=n}};const ce=/^[a-z][a-z0-9+.-]*:/i,le=e=>ce.test(e);let S=e=>(S=Array.isArray,S(e)),ue=S;function de(e){return typeof e==`object`?e??{}:{}}function fe(e){if(!e)return!0;for(let t in e)return!1;return!0}function pe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function me(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const he=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new f(`${e} must be an integer`);if(t<0)throw new f(`${e} must be a positive integer`);return t},ge=e=>{try{return JSON.parse(e)}catch{return}},_e=e=>new Promise(t=>setTimeout(t,e)),ve=`7.0.0`,ye=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function be(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const xe=()=>{let e=be();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"X-Stainless-OS":we(Deno.build.os),"X-Stainless-Arch":Ce(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"X-Stainless-OS":we(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Ce(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Se();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ve,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function Se(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const Ce=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,we=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let Te;const Ee=()=>Te??=xe();function De(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Oe(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ke(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Oe({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Ae(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function je(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Me=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),Ne=`RFC3986`,Pe=e=>String(e),Fe={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Pe};let Ie=(e,t)=>(Ie=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ie(e,t));const C=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Le=1024,Re=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=Le){let t=a.length>=Le?a.slice(e,e+Le):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=C[r];continue}if(r<2048){n[n.length]=C[192|r>>6]+C[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=C[224|r>>12]+C[128|r>>6&63]+C[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=C[240|r>>18]+C[128|r>>12&63]+C[128|r>>6&63]+C[128|r&63]}o+=n.join(``)}return o};function ze(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Be(e,t){if(S(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const Ve={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},He=function(e,t){Array.prototype.push.apply(e,S(t)?t:[t])};let Ue;const w={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Re,encodeValuesOnly:!1,format:Ne,formatter:Pe,indices:!1,serializeDate(e){return(Ue??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function We(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}const Ge={};function Ke(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(Ge))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(Ge)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&S(v)&&(v=Be(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,w.encoder,g,`key`,p):t;v=``}if(We(v)||ze(v)){if(c){let e=h?t:c(t,w.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,w.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let ee=[];if(v===void 0)return ee;let te;if(n===`comma`&&S(v))h&&c&&(v=Be(v,c)),te=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(S(l))te=l;else{let e=Object.keys(v);te=u?e.sort(u):e}let ne=s?String(t).replace(/\./g,`%2E`):String(t),re=r&&S(v)&&v.length===1?ne+`[]`:ne;if(i&&S(v)&&v.length===0)return re+`[]`;for(let t=0;t<te.length;++t){let y=te[t],x=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&x===null)continue;let ne=d&&s?y.replace(/\./g,`%2E`):y,ie=S(v)?typeof n==`function`?n(re,ne):re:re+(d?`.`+ne:`[`+ne+`]`);_.set(e,b);let ae=new WeakMap;ae.set(Ge,_),He(ee,Ke(x,ie,n,r,i,a,o,s,n===`comma`&&h&&S(v)?null:c,l,u,d,f,p,m,h,g,ae))}return ee}function qe(e=w){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||w.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=Ne;if(e.format!==void 0){if(!Ie(Fe,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=Fe[n],i=w.filter;(typeof e.filter==`function`||S(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ve?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:w.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:w.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:w.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:w.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:w.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?w.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:w.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:w.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:w.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:w.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:w.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:w.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:w.strictNullHandling}}function Je(e,t={}){let n=e,r=qe(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):S(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ve[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||He(o,Ke(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Ye(e){return Je(e,{arrayFormat:`brackets`})}function Xe(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let Ze;function T(e){let t;return(Ze??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let Qe;function $e(e){let t;return(Qe??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var E,D,et=class{constructor(){E.set(this,void 0),D.set(this,void 0),s(this,E,new Uint8Array,`f`),s(this,D,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?T(e):e;s(this,E,Xe([c(this,E,`f`),t]),`f`);let n=[],r;for(;(r=tt(c(this,E,`f`),c(this,D,`f`)))!=null;){if(r.carriage&&c(this,D,`f`)==null){s(this,D,r.index,`f`);continue}if(c(this,D,`f`)!=null&&(r.index!==c(this,D,`f`)+1||r.carriage)){n.push($e(c(this,E,`f`).subarray(0,c(this,D,`f`)-1))),s(this,E,c(this,E,`f`).subarray(c(this,D,`f`)),`f`),s(this,D,null,`f`);continue}let e=c(this,D,`f`)===null?r.preceding:r.preceding-1,t=$e(c(this,E,`f`).subarray(0,e));n.push(t),s(this,E,c(this,E,`f`).subarray(r.index),`f`),s(this,D,null,`f`)}return n}flush(){return c(this,E,`f`).length?this.decode(`
2
2
  `):[]}};E=new WeakMap,D=new WeakMap,et.NEWLINE_CHARS=new Set([`
3
3
  `,`\r`]),et.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function tt(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function nt(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}const rt={off:0,error:200,warn:300,info:400,debug:500},it=(e,t,n)=>{if(e){if(pe(rt,e))return e;O(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(rt))}`)}};function at(){}function ot(e,t,n){return!t||rt[e]>rt[n]?at:t[e].bind(t)}const st={error:at,warn:at,info:at,debug:at};let ct=new WeakMap;function O(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return st;let r=ct.get(t);if(r&&r[0]===n)return r[1];let i={error:ot(`error`,t,n),warn:ot(`warn`,t,n),info:ot(`info`,t,n),debug:ot(`debug`,t,n)};return ct.set(t,[n,i]),i}const lt=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`x-amz-security-token`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var ut,dt=class e{constructor(e,t,n){this.iterator=e,ut.set(this,void 0),this.controller=t,s(this,ut,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?O(r):console;async function*s(){if(a)throw new f("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let r of ft(t,n))if(!e){if(r.data.startsWith(`[DONE]`)){e=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let e;try{e=JSON.parse(r.data)}catch(e){throw o.error(`Could not parse message into JSON:`,r.data),o.error(`From chunk:`,r.raw),e}if(e&&e.error)throw new p(void 0,e.error,void 0,t.headers);yield i?{event:r.event,data:e}:e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new p(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(u(e))return;throw e}finally{e||n.abort()}}return new e(s,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new et,r=t.getReader(),i=!1,a,o=()=>{a??=r.cancel(),a.catch(()=>{})};n.signal.addEventListener(`abort`,o,{once:!0});try{if(n.signal.aborted){o();return}for(;;){let{value:t,done:a}=await r.read();if(a){i=!0;break}if(n.signal.aborted)return;for(let r of e.decode(t)){if(n.signal.aborted)return;yield r}}if(n.signal.aborted)return;for(let t of e.flush()){if(n.signal.aborted)return;yield t}}finally{n.signal.removeEventListener(`abort`,o),i||o(),r.releaseLock()}}async function*o(){if(i)throw new f("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(n.signal.aborted||u(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(ut=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,c(this,ut,`f`)),new e(()=>i(n),this.controller,c(this,ut,`f`))]}toReadableStream(){let e=this,t;return Oe({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=T(JSON.stringify(n)+`
4
4
  `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*ft(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new f(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new f(`Attempted to iterate over a response with no body`);let n=new mt,r=new et,i=Ae(e.body);for await(let e of pt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*pt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?T(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=nt(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var mt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
@@ -1,4 +1,4 @@
1
- import{t as e}from"./logger-LESFN7Hj.js";import"./logger-DQgFbfwx.js";import{t}from"./esbuild-wasm-DsMq-s8o.js";const n=e(`bsh-watchdog`),r=`.bsh scripts must be pre-bundled. Install deps via \`ipk add <pkg>\`, then bootstrap esbuild via \`ipk add esbuild-wasm@${t}\` and bundle with \`esbuild --bundle <script>.bsh --outfile=<script>.bundled.bsh\`. Drop the bundled file in place. There is no runtime resolver in the target page.`;var i=class{transport;browserAPI;fs;scriptCatalog;running=!1;executing=new Set;constructor(e){if(!e.transport&&!e.browserAPI)throw Error(`BshWatchdog requires either transport or browserAPI`);if(!e.scriptCatalog)throw Error(`BshWatchdog requires a ScriptCatalog`);this.browserAPI=e.browserAPI,this.transport=e.transport??e.browserAPI.getTransport(),this.fs=e.fs,this.scriptCatalog=e.scriptCatalog}async start(){if(this.running)return;this.running=!0,this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),this.browserAPI&&this.browserAPI.setSessionChangeCallback((e,t)=>{t!==this.transport&&this.setTransport(t)});let e;try{e=(await this.scriptCatalog.getBshEntries()).length}catch(e){n.warn(`BSH watchdog startup discovery failed`,{error:e instanceof Error?e.message:String(e)})}n.info(`BSH watchdog started`,e===void 0?void 0:{scriptCount:e})}stop(){this.running&&(this.running=!1,this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.browserAPI&&this.browserAPI.setSessionChangeCallback(void 0),this.executing.clear(),n.info(`BSH watchdog stopped`))}setTransport(e){e!==this.transport&&(this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport=e,this.running&&this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),n.info(`BSH watchdog transport swapped`))}async discover(){this.scriptCatalog.invalidateBsh(),await this.scriptCatalog.getBshEntries()}async getEntries(){return this.scriptCatalog.getBshEntries()}onFrameNavigated=e=>{let t=e.frame;if(t?.parentId||!t?.url)return;let r=t.url,i=e.sessionId;if(!(!r.startsWith(`http://`)&&!r.startsWith(`https://`))){if(!i){n.warn(`BSH watchdog: no sessionId in Page.frameNavigated params, skipping`,{url:r});return}this.scriptCatalog.findMatchingBshScripts(r).then(e=>{if(e.length!==0)for(let t of e){let e=`${t.path}::${r}`;this.executing.has(e)||(this.executing.add(e),n.info(`BSH watchdog executing script`,{script:t.path,url:r}),this.executeInTargetPage(t.path,r,i).then(()=>{n.info(`BSH script completed`,{script:t.path,url:r})}).catch(e=>{n.error(`BSH script execution error`,{script:t.path,url:r,error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.executing.delete(e)}))}}).catch(e=>{n.error(`BSH discovery failed`,{url:r,error:e instanceof Error?e.message:String(e)})})}};async executeInTargetPage(e,t,i){let a=await this.fs.readFile(e),o=typeof a==`string`?a:new TextDecoder().decode(a),s=`(async () => {
1
+ import{t as e}from"./logger-LESFN7Hj.js";import"./logger-DQgFbfwx.js";import{t}from"./esbuild-wasm-BHiYsKGe.js";const n=e(`bsh-watchdog`),r=`.bsh scripts must be pre-bundled. Install deps via \`ipk add <pkg>\`, then bootstrap esbuild via \`ipk add esbuild-wasm@${t}\` and bundle with \`esbuild --bundle <script>.bsh --outfile=<script>.bundled.bsh\`. Drop the bundled file in place. There is no runtime resolver in the target page.`;var i=class{transport;browserAPI;fs;scriptCatalog;running=!1;executing=new Set;constructor(e){if(!e.transport&&!e.browserAPI)throw Error(`BshWatchdog requires either transport or browserAPI`);if(!e.scriptCatalog)throw Error(`BshWatchdog requires a ScriptCatalog`);this.browserAPI=e.browserAPI,this.transport=e.transport??e.browserAPI.getTransport(),this.fs=e.fs,this.scriptCatalog=e.scriptCatalog}async start(){if(this.running)return;this.running=!0,this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),this.browserAPI&&this.browserAPI.setSessionChangeCallback((e,t)=>{t!==this.transport&&this.setTransport(t)});let e;try{e=(await this.scriptCatalog.getBshEntries()).length}catch(e){n.warn(`BSH watchdog startup discovery failed`,{error:e instanceof Error?e.message:String(e)})}n.info(`BSH watchdog started`,e===void 0?void 0:{scriptCount:e})}stop(){this.running&&(this.running=!1,this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.browserAPI&&this.browserAPI.setSessionChangeCallback(void 0),this.executing.clear(),n.info(`BSH watchdog stopped`))}setTransport(e){e!==this.transport&&(this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport=e,this.running&&this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),n.info(`BSH watchdog transport swapped`))}async discover(){this.scriptCatalog.invalidateBsh(),await this.scriptCatalog.getBshEntries()}async getEntries(){return this.scriptCatalog.getBshEntries()}onFrameNavigated=e=>{let t=e.frame;if(t?.parentId||!t?.url)return;let r=t.url,i=e.sessionId;if(!(!r.startsWith(`http://`)&&!r.startsWith(`https://`))){if(!i){n.warn(`BSH watchdog: no sessionId in Page.frameNavigated params, skipping`,{url:r});return}this.scriptCatalog.findMatchingBshScripts(r).then(e=>{if(e.length!==0)for(let t of e){let e=`${t.path}::${r}`;this.executing.has(e)||(this.executing.add(e),n.info(`BSH watchdog executing script`,{script:t.path,url:r}),this.executeInTargetPage(t.path,r,i).then(()=>{n.info(`BSH script completed`,{script:t.path,url:r})}).catch(e=>{n.error(`BSH script execution error`,{script:t.path,url:r,error:e instanceof Error?e.message:String(e)})}).finally(()=>{this.executing.delete(e)}))}}).catch(e=>{n.error(`BSH discovery failed`,{url:r,error:e instanceof Error?e.message:String(e)})})}};async executeInTargetPage(e,t,i){let a=await this.fs.readFile(e),o=typeof a==`string`?a:new TextDecoder().decode(a),s=`(async () => {
2
2
  const __requireSpecifiers = (function() {
3
3
  const re = /require\\s*\\(\\s*['"]([^'"]+)['"]\\s*\\)/g;
4
4
  const code = ${JSON.stringify(o)};
@@ -1 +1 @@
1
- import{h as e}from"./account-store-m7EtgLrd.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{p as n}from"./bedrock-camp-C8bCNVSq.js";import{r,s as i}from"./legacy-api-aliases-C2CCsk4u.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
+ import{h as e}from"./account-store-MovPQ1t7.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{p as n}from"./bedrock-camp-C8bCNVSq.js";import{r,s as i}from"./legacy-api-aliases-C2CCsk4u.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-B0inTvu6.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{p as n}from"./bedrock-camp-BfNg24Ce.js";import{r,s as i}from"./legacy-api-aliases-qI5FdR49.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};
1
+ import{h as e}from"./account-store-CZ1gUZlp.js";import{a as t}from"./diagnostics-DN_idNHx.js";import{p as n}from"./bedrock-camp-BfNg24Ce.js";import{r,s as i}from"./legacy-api-aliases-qI5FdR49.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};
@@ -1,4 +1,4 @@
1
- import{C as e,P as t,d as n,f as r}from"./account-store-m7EtgLrd.js";import{n as i}from"./provider-settings-StjddRwF.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=`
1
+ import{C as e,P as t,d as n,f as r}from"./account-store-MovPQ1t7.js";import{n as i}from"./provider-settings-Dw_3F-KV.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 +1 @@
1
- import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./runtime-env-DadgceZk.js";import"./runtime-env-DVGQx9p3.js";import{l as n,r,u as i}from"./installer-DDJZNOgZ.js";import{c as a,s as o}from"./kokoro-engine-2bQR6a7X.js";import{n as s}from"./transformers-env-wpY2kxZs.js";import"./whisper-engine-Cy4tNnVy.js";const c=e(`speech:ensure-assets`),l=`onnxruntime-web`,u=`espeak-ng`,d=[o,a],f=`/workspace`,p=t;async function m(e,t){if((await Promise.all(s.map(t=>e.fs.exists(`/workspace/node_modules/onnxruntime-web/dist/${t}`)))).every(Boolean))return t?.({asset:l,phase:`present`}),!1;t?.({asset:l,phase:`staging`});let{errors:n}=await r([l],{fs:e.fs,fetch:e.fetch,cwd:f});if(n.length>0)throw Error(`failed to stage ${l} wasm runtime: ${n[0].error.message}`);return t?.({asset:l,phase:`done`}),!0}async function h(e,t){if((await Promise.all(d.map(t=>e.fs.exists(`/workspace/node_modules/espeak-ng/dist/${t}`)))).every(Boolean))return t?.({asset:u,phase:`present`}),!1;t?.({asset:u,phase:`staging`});let{errors:n}=await r([u],{fs:e.fs,fetch:e.fetch,cwd:f});if(n.length>0)throw Error(`failed to stage ${u} wasm: ${n[0].error.message}`);return t?.({asset:u,phase:`done`}),!0}async function g(e,t){try{return await h(e,t)}catch(e){return c.warn(`optional espeak-ng staging failed; non-English Kokoro voices may fall back`,e),!1}}async function _(e,t,r){let a=i(t,null,f),o=0,s=await n({fetch:e.fetch,fs:e.fs,repo:t,targetDir:a,progress:{onListed:({files:e,totalBytes:n})=>r?.({asset:t,phase:`listing`,filesLoaded:0,filesTotal:e.length,bytesLoaded:0,bytesTotal:n}),onFile:e=>{o+=e.bytes,r?.({asset:t,phase:e.status,file:e.file,filesLoaded:e.index,filesTotal:e.total,bytesLoaded:o})}}});return r?.({asset:t,phase:`done`,filesLoaded:s.files.length,filesTotal:s.files.length,bytesLoaded:o,bytesTotal:o}),{repo:t,downloaded:s.downloaded,skipped:s.skipped}}async function v(e,t){if(p())return{skipped:!0,ortStaged:!1,espeakStaged:!1,repos:[]};let n=await m(e,t),r=e.repos??[`onnx-community/whisper-tiny`,`onnx-community/Kokoro-82M-v1.0-ONNX`],i=[];for(let n of r)i.push(await _(e,n,t));let a=await g(e,t);return c.info(`speech assets staged`,{ortStaged:n,espeakStaged:a,repos:i.length}),{skipped:!1,ortStaged:n,espeakStaged:a,repos:i}}export{v as ensureSpeechAssetsStaged};
1
+ import{t as e}from"./logger-LESFN7Hj.js";import{t}from"./runtime-env-DadgceZk.js";import"./runtime-env-DVGQx9p3.js";import{l as n,r,u as i}from"./installer-Bi0ukFsW.js";import{c as a,s as o}from"./kokoro-engine-W-8wCA-C.js";import{n as s}from"./transformers-env-K0tWLb5G.js";import"./whisper-engine-JcWkuin6.js";const c=e(`speech:ensure-assets`),l=`onnxruntime-web`,u=`espeak-ng`,d=[o,a],f=`/workspace`,p=t;async function m(e,t){if((await Promise.all(s.map(t=>e.fs.exists(`/workspace/node_modules/onnxruntime-web/dist/${t}`)))).every(Boolean))return t?.({asset:l,phase:`present`}),!1;t?.({asset:l,phase:`staging`});let{errors:n}=await r([l],{fs:e.fs,fetch:e.fetch,cwd:f});if(n.length>0)throw Error(`failed to stage ${l} wasm runtime: ${n[0].error.message}`);return t?.({asset:l,phase:`done`}),!0}async function h(e,t){if((await Promise.all(d.map(t=>e.fs.exists(`/workspace/node_modules/espeak-ng/dist/${t}`)))).every(Boolean))return t?.({asset:u,phase:`present`}),!1;t?.({asset:u,phase:`staging`});let{errors:n}=await r([u],{fs:e.fs,fetch:e.fetch,cwd:f});if(n.length>0)throw Error(`failed to stage ${u} wasm: ${n[0].error.message}`);return t?.({asset:u,phase:`done`}),!0}async function g(e,t){try{return await h(e,t)}catch(e){return c.warn(`optional espeak-ng staging failed; non-English Kokoro voices may fall back`,e),!1}}async function _(e,t,r){let a=i(t,null,f),o=0,s=await n({fetch:e.fetch,fs:e.fs,repo:t,targetDir:a,progress:{onListed:({files:e,totalBytes:n})=>r?.({asset:t,phase:`listing`,filesLoaded:0,filesTotal:e.length,bytesLoaded:0,bytesTotal:n}),onFile:e=>{o+=e.bytes,r?.({asset:t,phase:e.status,file:e.file,filesLoaded:e.index,filesTotal:e.total,bytesLoaded:o})}}});return r?.({asset:t,phase:`done`,filesLoaded:s.files.length,filesTotal:s.files.length,bytesLoaded:o,bytesTotal:o}),{repo:t,downloaded:s.downloaded,skipped:s.skipped}}async function v(e,t){if(p())return{skipped:!0,ortStaged:!1,espeakStaged:!1,repos:[]};let n=await m(e,t),r=e.repos??[`onnx-community/whisper-tiny`,`onnx-community/Kokoro-82M-v1.0-ONNX`],i=[];for(let n of r)i.push(await _(e,n,t));let a=await g(e,t);return c.info(`speech assets staged`,{ortStaged:n,espeakStaged:a,repos:i.length}),{skipped:!1,ortStaged:n,espeakStaged:a,repos:i}}export{v as ensureSpeechAssetsStaged};
@@ -1,4 +1,4 @@
1
- import{i as e,t}from"./rolldown-runtime-Dd_uD5pT.js";import{i as n}from"./path-utils-Rm3AltuN.js";import{C as r,d as i,p as a}from"./shared-CvRDmxWf.js";import{n as o}from"./wasm-compiler-Ct7QZURL.js";var s=e(t(((e,t)=>{(e=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},o=(e,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of r(a))!i.call(e,c)&&c!==o&&t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e},s=e=>o(t({},`__esModule`,{value:!0}),e),c=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),l={};a(l,{analyzeMetafile:()=>xe,analyzeMetafileSync:()=>Te,build:()=>_e,buildSync:()=>Se,context:()=>ve,default:()=>je,formatMessages:()=>be,formatMessagesSync:()=>we,initialize:()=>ke,stop:()=>Ee,transform:()=>ye,transformSync:()=>Ce,version:()=>ge}),e.exports=s(l);function u(e){let t=e=>{if(e===null)n.write8(0);else if(typeof e==`boolean`)n.write8(1),n.write8(+e);else if(typeof e==`number`)n.write8(2),n.write32(e|0);else if(typeof e==`string`)n.write8(3),n.write(p(e));else if(e instanceof Uint8Array)n.write8(4),n.write(e);else if(e instanceof Array){n.write8(5),n.write32(e.length);for(let n of e)t(n)}else{let r=Object.keys(e);n.write8(6),n.write32(r.length);for(let i of r)n.write(p(i)),t(e[i])}},n=new f;return n.write32(0),n.write32(e.id<<1|!e.isRequest),t(e.value),_(n.buf,n.len-4,0),n.buf.subarray(0,n.len)}function d(e){let t=()=>{switch(n.read8()){case 0:return null;case 1:return!!n.read8();case 2:return n.read32();case 3:return m(n.read());case 4:return n.read();case 5:{let e=n.read32(),r=[];for(let n=0;n<e;n++)r.push(t());return r}case 6:{let e=n.read32(),r={};for(let i=0;i<e;i++)r[m(n.read())]=t();return r}default:throw Error(`Invalid packet`)}},n=new f(e),r=n.read32(),i=!(r&1);r>>>=1;let a=t();if(n.ptr!==e.length)throw Error(`Invalid packet`);return{id:r,isRequest:i,value:a}}var f=class{constructor(e=new Uint8Array(1024)){this.buf=e,this.len=0,this.ptr=0}_write(e){if(this.len+e>this.buf.length){let t=new Uint8Array((this.len+e)*2);t.set(this.buf),this.buf=t}return this.len+=e,this.len-e}write8(e){let t=this._write(1);this.buf[t]=e}write32(e){let t=this._write(4);_(this.buf,e,t)}write(e){let t=this._write(4+e.length);_(this.buf,e.length,t),this.buf.set(e,t+4)}_read(e){if(this.ptr+e>this.buf.length)throw Error(`Invalid packet`);return this.ptr+=e,this.ptr-e}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let e=this.read32(),t=new Uint8Array(e),n=this._read(t.length);return t.set(this.buf.subarray(n,n+e)),t}},p,m,h;if(typeof TextEncoder<`u`&&typeof TextDecoder<`u`){let e=new TextEncoder,t=new TextDecoder;p=t=>e.encode(t),m=e=>t.decode(e),h=`new TextEncoder().encode("")`}else if(typeof Buffer<`u`)p=e=>Buffer.from(e),m=e=>{let{buffer:t,byteOffset:n,byteLength:r}=e;return Buffer.from(t,n,r).toString()},h=`Buffer.from("")`;else throw Error(`No UTF-8 codec found`);if(!(p(``)instanceof Uint8Array))throw Error(`Invariant violation: "${h} instanceof Uint8Array" is incorrectly false
1
+ import{i as e,t}from"./rolldown-runtime-Dd_uD5pT.js";import{a as n}from"./path-utils-DNJG-zQf.js";import{C as r,d as i,p as a}from"./shared-CS4zRQ6K.js";import{n as o}from"./wasm-compiler-Ct7QZURL.js";var s=e(t(((e,t)=>{(e=>{var t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.prototype.hasOwnProperty,a=(e,n)=>{for(var r in n)t(e,r,{get:n[r],enumerable:!0})},o=(e,a,o,s)=>{if(a&&typeof a==`object`||typeof a==`function`)for(let c of r(a))!i.call(e,c)&&c!==o&&t(e,c,{get:()=>a[c],enumerable:!(s=n(a,c))||s.enumerable});return e},s=e=>o(t({},`__esModule`,{value:!0}),e),c=(e,t,n)=>new Promise((r,i)=>{var a=e=>{try{s(n.next(e))}catch(e){i(e)}},o=e=>{try{s(n.throw(e))}catch(e){i(e)}},s=e=>e.done?r(e.value):Promise.resolve(e.value).then(a,o);s((n=n.apply(e,t)).next())}),l={};a(l,{analyzeMetafile:()=>xe,analyzeMetafileSync:()=>Te,build:()=>_e,buildSync:()=>Se,context:()=>ve,default:()=>je,formatMessages:()=>be,formatMessagesSync:()=>we,initialize:()=>ke,stop:()=>Ee,transform:()=>ye,transformSync:()=>Ce,version:()=>ge}),e.exports=s(l);function u(e){let t=e=>{if(e===null)n.write8(0);else if(typeof e==`boolean`)n.write8(1),n.write8(+e);else if(typeof e==`number`)n.write8(2),n.write32(e|0);else if(typeof e==`string`)n.write8(3),n.write(p(e));else if(e instanceof Uint8Array)n.write8(4),n.write(e);else if(e instanceof Array){n.write8(5),n.write32(e.length);for(let n of e)t(n)}else{let r=Object.keys(e);n.write8(6),n.write32(r.length);for(let i of r)n.write(p(i)),t(e[i])}},n=new f;return n.write32(0),n.write32(e.id<<1|!e.isRequest),t(e.value),_(n.buf,n.len-4,0),n.buf.subarray(0,n.len)}function d(e){let t=()=>{switch(n.read8()){case 0:return null;case 1:return!!n.read8();case 2:return n.read32();case 3:return m(n.read());case 4:return n.read();case 5:{let e=n.read32(),r=[];for(let n=0;n<e;n++)r.push(t());return r}case 6:{let e=n.read32(),r={};for(let i=0;i<e;i++)r[m(n.read())]=t();return r}default:throw Error(`Invalid packet`)}},n=new f(e),r=n.read32(),i=!(r&1);r>>>=1;let a=t();if(n.ptr!==e.length)throw Error(`Invalid packet`);return{id:r,isRequest:i,value:a}}var f=class{constructor(e=new Uint8Array(1024)){this.buf=e,this.len=0,this.ptr=0}_write(e){if(this.len+e>this.buf.length){let t=new Uint8Array((this.len+e)*2);t.set(this.buf),this.buf=t}return this.len+=e,this.len-e}write8(e){let t=this._write(1);this.buf[t]=e}write32(e){let t=this._write(4);_(this.buf,e,t)}write(e){let t=this._write(4+e.length);_(this.buf,e.length,t),this.buf.set(e,t+4)}_read(e){if(this.ptr+e>this.buf.length)throw Error(`Invalid packet`);return this.ptr+=e,this.ptr-e}read8(){return this.buf[this._read(1)]}read32(){return g(this.buf,this._read(4))}read(){let e=this.read32(),t=new Uint8Array(e),n=this._read(t.length);return t.set(this.buf.subarray(n,n+e)),t}},p,m,h;if(typeof TextEncoder<`u`&&typeof TextDecoder<`u`){let e=new TextEncoder,t=new TextDecoder;p=t=>e.encode(t),m=e=>t.decode(e),h=`new TextEncoder().encode("")`}else if(typeof Buffer<`u`)p=e=>Buffer.from(e),m=e=>{let{buffer:t,byteOffset:n,byteLength:r}=e;return Buffer.from(t,n,r).toString()},h=`Buffer.from("")`;else throw Error(`No UTF-8 codec found`);if(!(p(``)instanceof Uint8Array))throw Error(`Invariant violation: "${h} instanceof Uint8Array" is incorrectly false
2
2
 
3
3
  This indicates that your JavaScript environment is broken. You cannot use
4
4
  esbuild in this environment because esbuild relies on this invariant. This
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./logger-LESFN7Hj.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{t as s}from"./backend-local-B7Sbb5yU.js";import{t as c}from"./types-idfTVsM8.js";import{a as l,i as u,n as d,t as f}from"./mount-table-store-DrF_Ifaz.js";import{i as p,r as m,t as h}from"./sidecar-repair-DSCESX6n.js";const g=t(`fs-watcher`);let _=0;function v(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var y=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++_}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),g.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),g.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>v(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){g.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),g.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const b=t(`mount-index`);var x=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function S(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 C(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function w(e,t){return e instanceof Map?e.get(t):e[t]}function T(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function E(e,t,n){let r=w(e,t);if(r===void 0||r.trim()===``)return n;let i=T(r);return i===void 0?(b.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function D(e){return{maxDepth:E(e,`SLICC_MOUNT_INDEX_MAX_DEPTH`,400),maxEntries:E(e,`SLICC_MOUNT_INDEX_MAX_ENTRIES`,2e6)}}var O=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=D({})){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,b.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 x?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},b.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 x(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new x(`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 x(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=S(n),a=r.get(i);if(a){for(let n of a)if(await C(n.handle,t))throw new x(`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 k=`/dev/null`,A=new Set([k]);function j(e){return A.has(e)}const M={[k]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}};var N=class{vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let a=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return this.allowedPrefixes.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 c(`EACCES`,`permission denied`,i(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}catch(t){throw t instanceof c?t:new c(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new c(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof c?t:new c(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new c(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=M[i(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async 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=i(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=M[i(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=M[i(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=M[i(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=i(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 c?t:new c(`ENOENT`,`no such file or directory`,i(e))}if(!this.isAllowedStrict(t))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(M[i(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=M[i(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=M[i(e)];if(r){r.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 c&&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 c&&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 c(`ENOENT`,`no such file or directory`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof c&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new c(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=M[i(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new c(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new c(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new c(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new c(`EACCES`,`permission denied`,i(e));let r=this.vfs.getWatcher();if(!r)throw new c(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.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 P(e,t){if(e instanceof c){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new c(e.code,r,t)}throw e}const F=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`];function I(e,t){if(e instanceof c)return e;let n=e?.code;if(typeof n==`string`){let r=n;if(F.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new c(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new c(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new c(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new c(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new c(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new c(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new c(`ELOOP`,`too many levels of symbolic links`,t):new c(`EINVAL`,r,t)}function L(e){return e===void 0?`absent`:(e&61440)==16384?`directory`:`file`}function R(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function z(e){let t=e?.mode;return typeof t==`number`?t:void 0}function B(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=L(z(r));o!==L(z(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function V(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=I(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function H(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw I(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function U(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await V(e,o,r,i);if(t===null||!t.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new c(`ELOOP`,`too many symbolic links encountered`,i);o=await H(e,o,i)}}async function W(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await U(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function G(e,t,n){return t(n)?n:W(e,t,n)}function K(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 q(e,t){try{return await e(t)}catch{return t}}async function*J(e,t,n,r=0){let a=i(t);if(K(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(r>64||o.size>=1e5)return;let s=await q(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*Y(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*Y(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*X(e,n,r,i);return}yield*J(e,n,r,i)}async function*X(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*J(e,t,n,r))}catch{}}function Z(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var Q=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new O;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-BaUI1Dp5.js`).then(e=>e.t),import(`./dist-C8yMY-ER.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=()=>a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:r,repairOpfsMetadataSidecar:l}=await import(`./sidecar-repair-DSCESX6n.js`).then(e=>e.n);try{let e=await t.withWriteLock(()=>l(i));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,selfEntryDropped:e.selfEntryDropped})}catch{}let u=await r(n,()=>t.withWriteLock(()=>l(i)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:t.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,selfEntryDropped:e.selfEntryDropped}));try{a.mount(s,u)}catch{}c={backendFs:u,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-BaUI1Dp5.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 c(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??Z(),a=new e(n,r,i);return await a._ready,r&&await f().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=m(e,r,i))}let o=JSON.stringify(p(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=B(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=h(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,r=`path`){if(this.backend!==`opfs`)return;let a=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(t);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await h(n)(a),s=L(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=R(o,s),d=R(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async 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-BaUI1Dp5.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,r){let a=i(e);if(this.mountPoints.has(a))throw new c(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new c(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new c(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof c)||e.code!==`ENOENT`)throw e}let{dir:o}=n(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=D(r?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{let e={targetPath:a,descriptor:s,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await l(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await u(t)}catch{}}async reconstructBackendFromDescriptor(e){switch(e.kind){case`local`:{let t=await d(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return s.fromHandle(t,{mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-ZIk2nJ0B.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-ZIk2nJ0B.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 r=i(e);if(this.mountPoints.has(r))throw new c(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new c(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=i(e),r=this.mountPoints.get(n);if(!r)throw new c(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,D(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){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){P(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 I(e,n)}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new c(`EISDIR`,`is a directory`,a);let e=o.relParts.join(`/`),n=!1;try{await this.stat(a),n=!0}catch{}let r=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await o.backend.writeFile(e,r)}catch(e){P(e,a)}this.watcher?.notify([{type:n?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let l=!1;try{await this.lfs.stat(s),l=!0}catch{}let{dir:u}=n(s);await this.withWriteLock(async()=>{this.markSidecarDirty(s),u!==`/`&&await this.mkdirRecursiveUnlocked(u);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(s,t)}catch(e){if(u!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(u);try{await this.lfs.writeFile(s,t)}catch(e){throw I(e,a)}}else throw I(e,a)}try{await this.lfs.truncate?.(s,e)}catch(e){throw I(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e){let t=i(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){P(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){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw I(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 I(e,n);try{let e=await this.lfs.lstat(n);if(!e.isDirectory()&&!e.isSymbolicLink())throw new c(`ENOTDIR`,`not a directory`,n)}catch(e){if(e instanceof c&&e.code===`ENOTDIR`)throw e}}}}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){P(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}t?.recursive?await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n))):(await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw I(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]))}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new c(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){P(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw I(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.mtime}}catch(e){P(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw I(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*J({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new c(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new c(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw I(e,r)}}else throw I(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw I(e,t)}}async lstat(e){let t=i(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 I(e,t)}}async realpath(e){return W(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return G(this.lfs,e=>this.findMount(e)!==null,e)}},$=e({FsError:()=>c,FsWatcher:()=>y,MountIndex:()=>O,RestrictedFS:()=>N,VirtualFS:()=>Q,joinPath:()=>o,normalizePath:()=>i,pathSegments:()=>r,resolveVfsBackendFromEnv:()=>Z,splitPath:()=>n});export{y as a,j as i,Q as n,N as r,$ as t};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-CrQKODgO.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/dist-DBATBmPe.js","assets/sidecar-repair-DoQ5IdBR.js","assets/mount-C258ctaZ.js","assets/preload-helper-Czpn1I53.js","assets/mime-types-ugOWOUZ9.js","assets/base64-DpPqYZJF.js","assets/src-CAWTvdAa.js","assets/proxied-fetch-DLOgqk5A.js","assets/runtime-env-Dlaokqg1.js","assets/fetch-body-D2PwksUW.js","assets/runtime-env-CgsZ7LTp.js","assets/runtime-env-E-i2SW1s.js","assets/types-idfTVsM8.js","assets/backend-local-1YuE96fx.js","assets/tool-ui-DfXu6quJ.js","assets/logger-DDBAeTLF.js","assets/picker-approval-D89YhXsA.js","assets/html-B_Hg2WOy.js","assets/mount-picker-popup-Bc3ca2Vl.js","assets/logger-BoSvu4mW.js","assets/picker-popup-Bwcnocm6.js","assets/mount-table-store-dY2IfQ5S.js","assets/mount-bridge-client-D5axbHW9.js","assets/port-bridge-client-Bw9y6i0a.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./logger-DDBAeTLF.js";import{a as n,i as r,n as i,r as a,t as o}from"./path-utils-DNJG-zQf.js";import{t as s}from"./types-idfTVsM8.js";import{t as c}from"./virtual-device-paths-9EXC9iPp.js";import{t as l}from"./backend-local-1YuE96fx.js";import{a as u,i as d,n as f,t as p}from"./mount-table-store-dY2IfQ5S.js";import{i as m,r as h,t as g}from"./sidecar-repair-DoQ5IdBR.js";var _=t(`fs-watcher`),v=0;function y(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var b=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++v}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),_.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),_.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>y(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){_.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),_.debug(`All watchers disposed`)}get size(){return this.registrations.size}},x=t(`mount-index`),S=400,C=2e6,w=`SLICC_MOUNT_INDEX_MAX_DEPTH`,T=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,E=256,D=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function O(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>E?t.slice(0,E):t;return`${t.length}\u0001${n.join(``)}`}async function k(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function ee(e,t){return e instanceof Map?e.get(t):e[t]}function A(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function j(e,t,n){let r=ee(e,t);if(r===void 0||r.trim()===``)return n;let i=A(r);return i===void 0?(x.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function M(e){return{maxDepth:j(e,w,S),maxEntries:j(e,T,C)}}var N=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=M({})){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,x.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 D?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},x.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 D(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new D(`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 D(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=O(n),a=r.get(i);if(a){for(let n of a)if(await k(n.handle,t))throw new D(`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)))}}},P={[c]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},F=class{vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let a=e=>{let t=i(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(a(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:a(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=i(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=i(e);return this.allowedPrefixes.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`,i(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`,i(e));return t}catch(t){throw t instanceof s?t:new s(`ENOENT`,`no such file or directory`,i(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new s(`EACCES`,`permission denied`,i(e));return t}catch(t){throw t instanceof s?t:new s(`EACCES`,`permission denied`,i(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof s&&e.code===`EACCES`)throw e;return}let a=r+`/`+n;if(this.isWritable(a))return;let o=i(r)!==i(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new s(`EACCES`,`permission denied`,i(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=P[i(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new s(`ENOENT`,`no such file or directory`,i(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,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=i(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=P[i(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,i(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=i(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),a=t?r.length:r.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+r[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=P[i(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=P[i(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=i(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`,i(e))}if(!this.isAllowedStrict(t))throw new s(`ENOENT`,`no such file or directory`,i(e));return t}async exists(e){if(P[i(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=P[i(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new s(`ENOENT`,`no such file or directory`,i(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let r=P[i(e)];if(r){r.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`,i(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof 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`,i(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=i(t);else{let r=this.vfs.dirname(e);n=i(r+`/`+t)}if(!this.isAllowedStrict(n))throw new s(`ENOENT`,`no such file or directory`,i(e));return t}async lstat(e){let t=P[i(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new s(`ENOENT`,`no such file or directory`,i(e));let n=i(e),r=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(r===n)o=r;else try{o=await this.vfs.realpath(r)}catch{throw new 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`,i(e));let r=this.vfs.getWatcher();if(!r)throw new s(`EINVAL`,`no watcher configured`);return r.watch(i(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.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 I(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}var L=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`];function R(e,t){if(e instanceof s)return e;let n=e?.code;if(typeof n==`string`){let r=n;if(L.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new 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)}var z=61440,B=16384;function V(e){return e===void 0?`absent`:(e&z)===B?`directory`:`file`}function H(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function U(e){let t=e?.mode;return typeof t==`number`?t:void 0}function W(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=V(U(r));o!==V(U(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}async function G(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=R(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function K(e,t,r){let a;try{a=await e.readlink(t)}catch(e){throw R(e,r)}return a.startsWith(`/`)?i(a):i(o(n(t).dir,a))}async function q(e,t,n,r,i,a){let o=t===`/`?`/${n}`:`${t}/${n}`;for(;;){let t=await G(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 K(e,o,i)}}async function J(e,t,n){let r=i(n);if(t(r))return r;let a=r.split(`/`).filter(Boolean),o=`/`,s=0;for(let t=0;t<a.length;t++){let n=await q(e,o,a[t],t===a.length-1,r,s);o=n.resolved,s=n.hops}return o}async function Y(e,t,n){return t(n)?n:J(e,t,n)}function X(e,t,n){return e.size===0||!e.has(n)||!t.isReady(n)?!1:!Array.from(e.keys()).some(e=>e!==n&&e.startsWith(n+`/`))}async function Z(e,t){try{return await e(t)}catch{return t}}async function*Q(e,t,n,r=0){let a=i(t);if(X(e.mountPoints,e.mountIndex,a)){let t=e.mountIndex.getFiles(a);if(t){for(let e of t)yield e;return}}let o=n??new Set;if(r>64||o.size>=1e5)return;let s=await 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*te(e,t,a===`/`?`/${t.name}`:`${a}/${t.name}`,o,r+1)}async function*te(e,t,n,r,i){if(t.type===`file`){yield n;return}if(t.type===`symlink`){yield*ne(e,n,r,i);return}yield*Q(e,n,r,i)}async function*ne(e,t,n,r){try{let i=await e.stat(t);i.type===`file`?yield t:i.type===`directory`&&(yield*Q(e,t,n,r))}catch{}}function $(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var re=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 N;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-CrQKODgO.js`).then(e=>e.t),__vite__mapDeps([0,1])),e(()=>import(`./dist-DBATBmPe.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 r=()=>o.resolveMountConfig({backend:s,handle:a,metadata:`/.metadata.json`}),{resolveWithSidecarRepair:i,repairOpfsMetadataSidecar:u}=await e(async()=>{let{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}=await import(`./sidecar-repair-DoQ5IdBR.js`).then(e=>e.n);return{resolveWithSidecarRepair:e,repairOpfsMetadataSidecar:t}},__vite__mapDeps([3,1]));try{let e=await n.withWriteLock(()=>u(a));e?.changed&&console.warn(`[virtual-fs] repaired metadata sidecar before mount (#2146)`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,inosReassigned:e.inosReassigned,selfEntryDropped:e.selfEntryDropped})}catch{}let d=await i(r,()=>n.withWriteLock(()=>u(a)),e=>console.warn(`[virtual-fs] repaired poisoned metadata sidecar; retrying mount`,{dbName:n.dbName,kindFixed:e.kindFixed,sizesFixed:e.sizesFixed,dropped:e.dropped,selfEntryDropped:e.selfEntryDropped}));try{o.mount(c,d)}catch{}l={backendFs:d,refs:0,sidecarDirty:{paths:new Set,prefixes:new Set}},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-CrQKODgO.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 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(e){return new t(e)}static async create(e){let n=e?.dbName??`browser-fs`,r=e?.wipe===!0,i=e?.backend??$(),a=new t(n,r,i);return await a._ready,r&&await p().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let e=this.opfsBackendFs,n=this.opfsHandle;if(!e||!n)return;let r=e.index.toJSON(),i=t.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=h(e,r,i))}let o=JSON.stringify(m(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear())}async auditDirtyKindFlips(e,t,n,r){let i=W(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=g(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(e,r=`path`){if(this.backend!==`opfs`)return;let a=t.opfsBackends.get(this.dbName)?.sidecarDirty;if(!a)return;let o=i(e);(r===`prefix`?a.prefixes:a.paths).add(o);let{dir:s}=n(o);for(;s!==`/`;)a.paths.add(s),s=n(s).dir}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=i(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=i(e),a=r;try{a=await this.resolveSymlinks(r)}catch{}let o=await g(n)(a),s=V(t.index.get(a)?.mode),c=t._handles?.get(a),l=c?.kind===`directory`?`directory`:c?.kind===`file`?`file`:`absent`,u=H(o,s),d=H(o,l);if(!u&&!d)return!1;if(t.index.delete(a),t._handles?.delete(a),s===`directory`||l===`directory`){let e=`${a}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(a),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:a,reality:o.kind,indexHeld:s,handleHeld:l}),!0}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async 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-CrQKODgO.js`).then(e=>e.t),__vite__mapDeps([0,1]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=i(e);if(this.findMount(t))return null;let r=this.lfsSync;if(typeof r.statSync!=`function`||typeof r.lstatSync!=`function`||typeof r.readlinkSync!=`function`)return null;let a=t;for(let e=0;e<=10;e++){let e;try{e=r.lstatSync(a)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=r.readlinkSync(a)}catch{return null}a=t.startsWith(`/`)?i(t):i(o(n(a).dir,t))}return null}lstatSync(e){let t=i(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,r){let a=i(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=M(r?.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 u(e,n)}catch{}}async unmount(e){let t=i(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await d(t)}catch{}}async reconstructBackendFromDescriptor(t){switch(t.kind){case`local`:{let e=await f(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return l.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-C258ctaZ.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([4,5,6,7,8,9,1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])),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-C258ctaZ.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([4,5,6,7,8,9,1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let r=i(e);if(this.mountPoints.has(r))throw new s(`EEXIST`,`mount point is already mounted`,r);let{dir:a}=n(r);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(r)}catch{}this.mountPoints.set(r,t),this.internalMounts.add(r),this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}])}async unmountInternal(e){let t=i(e);if(!this.internalMounts.has(t))throw new 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=i(e),r=this.mountPoints.get(n);if(!r)throw new s(`ENOENT`,`not a mount point`,n);let a=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,M(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){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new s(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){I(e,n)}}let a=await this.resolveSymlinks(n);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(a,{encoding:`utf8`}):await this.lfs.readFile(a)}catch(e){throw R(e,n)}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,r){let a=i(e),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new 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){I(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()=>{this.markSidecarDirty(c),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 R(e,a)}}else throw R(e,a)}try{await this.lfs.truncate?.(c,e)}catch(e){throw R(e,a)}}),this.watcher?.notify([{type:l?`modify`:`create`,path:c,entryType:`file`}])}async readDir(e){let t=i(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){I(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){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw R(t,e)}}async statDirEntry(e,t){let n=e===`/`?`/${t}`:`${e}/${t}`;try{let e=await this.lfs.lstat(n);return e.isSymbolicLink()?{name:t,type:`symlink`}:{name:t,type:e.isDirectory()?`directory`:`file`}}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 R(e,n);try{let e=await this.lfs.lstat(n);if(!e.isDirectory()&&!e.isSymbolicLink())throw new s(`ENOTDIR`,`not a directory`,n)}catch(e){if(e instanceof s&&e.code===`ENOTDIR`)throw e}}}}async mkdir(e,t){let n=i(e);if(n===`/`)return;let r=this.findMount(n);if(r){if(r.relParts.length===0)return;let e=r.relParts.join(`/`),t=await this.exists(n);try{await r.backend.mkdir(e)}catch(e){I(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}t?.recursive?await this.withWriteLock(()=>(this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n))):(await this.withWriteLock(async()=>{this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw R(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]))}async rm(e,t){return this.withKindMismatchRetry(i(e),()=>this.rmInner(e,t))}async rmInner(e,t){let n=i(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new s(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){I(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statInner(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)try{let e=await this.lfs.stat(t);return{type:`directory`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let e=n.relParts.join(`/`);try{let t=await n.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.mtime}}catch(e){I(e,t)}}let r=await this.resolveSymlinks(t);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw R(e,t)}}async exists(e){let t=i(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([i(e),i(t)],()=>this.renameInner(e,t))}async renameInner(e,t){let n=i(e),r=i(t),a;try{a=(await this.lstat(n)).type}catch{}try{await this.withWriteLock(async()=>{this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.lfs.rename(n,r),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw R(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:r,entryType:a}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*Q({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(i(e)).dir}basename(e){return n(i(e)).base}async symlink(e,t){let r=i(t);if(this.findMount(r))throw new s(`EINVAL`,`symlinks not supported on mounted filesystems`,r);let{dir:a}=n(r);await this.withWriteLock(async()=>{a!==`/`&&await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(t){if(a!==`/`&&t instanceof Error&&t.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(a);try{await this.lfs.symlink(e,r)}catch(e){throw R(e,r)}}else throw R(t,r)}this.markSidecarDirty(r),await this.writeOpfsMetadataSidecarUnlocked()}),this.watcher?.notify([{type:`create`,path:r,entryType:`symlink`}])}async readlink(e){let t=i(e);try{return await this.lfs.readlink(t)}catch(e){throw R(e,t)}}async lstat(e){let t=i(e);if(this.findMount(t))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 R(e,t)}}async realpath(e){return J(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return Y(this.lfs,e=>this.findMount(e)!==null,e)}};export{s as FsError,b as FsWatcher,N as MountIndex,F as RestrictedFS,re as VirtualFS,o as joinPath,i as normalizePath,r as pathSegments,$ as resolveVfsBackendFromEnv,n as splitPath};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/fs-CSJFeAoX.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-1YuE96fx.js","assets/tool-ui-DfXu6quJ.js","assets/picker-approval-D89YhXsA.js","assets/html-B_Hg2WOy.js","assets/mount-picker-popup-Bc3ca2Vl.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/logger-BoSvu4mW.js","assets/picker-popup-Bwcnocm6.js","assets/runtime-env-Dlaokqg1.js","assets/runtime-env-CgsZ7LTp.js","assets/runtime-env-E-i2SW1s.js","assets/src-CAWTvdAa.js","assets/mount-table-store-dY2IfQ5S.js","assets/sidecar-repair-DoQ5IdBR.js"])))=>i.map(i=>d[i]);
2
- import{S as e,d as t,z as n}from"./account-store-m7EtgLrd.js";import{t as r}from"./preload-helper-Czpn1I53.js";import{i}from"./proxied-fetch-DLOgqk5A.js";import{i as a,t as o}from"./tray-runtime-config-BDiVOcsu.js";import"./provider-settings-StjddRwF.js";import{r as s,t as c}from"./silent-renew-backoff-BhyOB6Rq.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-KeQsTKOW.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-CSJFeAoX.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]));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-CSJFeAoX.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]));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-CSJFeAoX.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19])),{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};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/fs-DdomU_RK.js","assets/preload-helper-Czpn1I53.js","assets/logger-DDBAeTLF.js","assets/path-utils-DNJG-zQf.js","assets/types-idfTVsM8.js","assets/virtual-device-paths-9EXC9iPp.js","assets/backend-local-1YuE96fx.js","assets/tool-ui-DfXu6quJ.js","assets/picker-approval-D89YhXsA.js","assets/html-B_Hg2WOy.js","assets/mount-picker-popup-Bc3ca2Vl.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/logger-BoSvu4mW.js","assets/picker-popup-Bwcnocm6.js","assets/runtime-env-Dlaokqg1.js","assets/runtime-env-CgsZ7LTp.js","assets/runtime-env-E-i2SW1s.js","assets/src-CAWTvdAa.js","assets/mount-table-store-dY2IfQ5S.js","assets/sidecar-repair-DoQ5IdBR.js"])))=>i.map(i=>d[i]);
2
+ import{S as e,d as t,z as n}from"./account-store-MovPQ1t7.js";import{t as r}from"./preload-helper-Czpn1I53.js";import{i}from"./proxied-fetch-DLOgqk5A.js";import{i as a,t as o}from"./tray-runtime-config-BDiVOcsu.js";import"./provider-settings-Dw_3F-KV.js";import{r as s,t as c}from"./silent-renew-backoff-BhyOB6Rq.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-KeQsTKOW.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-DdomU_RK.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]));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-DdomU_RK.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]));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-DdomU_RK.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19])),{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};
@@ -1 +1 @@
1
- import{i as e}from"./proxied-fetch-B30CBbDZ.js";import{S as t,d as n,z as r}from"./account-store-B0inTvu6.js";import{r as i,t as a}from"./tray-runtime-config-B76Ys57e.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-PiotCIHi.js";import"./provider-settings-Cla-Ao_F.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 n().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-BrZitfrE.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-BrZitfrE.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-BrZitfrE.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 e=C();if(!e?.refreshToken)return null;let n=await h({provider:`github`,refreshToken:e.refreshToken});await r({providerId:`github`,accessToken:n.access_token,refreshToken:n.refresh_token,tokenExpiresAt:n.expires_in?Date.now()+n.expires_in*1e3:void 0,userName:e.userName,userAvatar:e.userAvatar,scopes:n.scope??e.scopes});let i=t(`github`)?.maskedValue;return i?await D(i):await O(),n.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(n,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:e(),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 n(`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 r({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=t(`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 r({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};
1
+ import{i as e}from"./proxied-fetch-B30CBbDZ.js";import{S as t,d as n,z as r}from"./account-store-CZ1gUZlp.js";import{r as i,t as a}from"./tray-runtime-config-B76Ys57e.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-PiotCIHi.js";import"./provider-settings-DPTmaMK4.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 n().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-CFP623sx.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-CFP623sx.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-CFP623sx.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 e=C();if(!e?.refreshToken)return null;let n=await h({provider:`github`,refreshToken:e.refreshToken});await r({providerId:`github`,accessToken:n.access_token,refreshToken:n.refresh_token,tokenExpiresAt:n.expires_in?Date.now()+n.expires_in*1e3:void 0,userName:e.userName,userAvatar:e.userAvatar,scopes:n.scope??e.scopes});let i=t(`github`)?.maskedValue;return i?await D(i):await O(),n.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(n,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:e(),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 n(`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 r({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=t(`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 r({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};
@@ -1 +1 @@
1
- import{d as e,z as t}from"./account-store-B0inTvu6.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{d as r,p as i,u as a}from"./bedrock-camp-BfNg24Ce.js";import{a as o,c as s,i as c,r as l,s as u,t as d}from"./legacy-api-aliases-qI5FdR49.js";import"./provider-settings-Cla-Ao_F.js";const f=`github-copilot`,p=atob(`SXYxLmI1MDdhMDhjODdlY2ZlOTg=`),m={Accept:`application/json`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`},h={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`};function g(){return e().find(e=>e.providerId===f)}async function _(){let e=await fetch(`https://github.com/login/device/code`,{method:`POST`,headers:h,body:new URLSearchParams({client_id:p,scope:`read:user`})});if(!e.ok)throw Error(`GitHub device-code request failed: ${e.status} ${e.statusText} — ${await e.text().catch(()=>``)}`);let t=await e.json();if(typeof t.device_code!=`string`||typeof t.user_code!=`string`||typeof t.verification_uri!=`string`||typeof t.expires_in!=`number`||typeof t.interval!=`number`)throw Error(`GitHub device-code response had an unexpected shape`);return t}async function v(e,t){let n=Date.now()+e.expires_in*1e3,r=Math.max(1e3,Math.floor(e.interval*1e3)),i=1.2;for(;Date.now()<n;){if(t.aborted)throw Error(`Copilot login cancelled`);await y(Math.ceil(r*i),t);let n=await fetch(`https://github.com/login/oauth/access_token`,{method:`POST`,headers:h,body:new URLSearchParams({client_id:p,device_code:e.device_code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`})});if(!n.ok)throw Error(`GitHub token poll failed: ${n.status} ${n.statusText} — ${await n.text().catch(()=>``)}`);let a=await n.json();if(typeof a.access_token==`string`&&a.access_token.length>0)return a.access_token;if(a.error!==`authorization_pending`){if(a.error===`slow_down`){r=typeof a.interval==`number`?a.interval*1e3:r+5e3,i=1.4;continue}if(a.error){let e=a.error_description?`: ${a.error_description}`:``;throw Error(`Device flow failed (${a.error})${e}`)}}}throw Error(`Copilot device flow timed out (device code expired)`)}function y(e,t){return new Promise((n,r)=>{if(t.aborted){r(Error(`Copilot login cancelled`));return}let i=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Copilot login cancelled`))},{once:!0})})}function b(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,`api.`)}`:null}async function x(e){let t=await fetch(`https://api.github.com/copilot_internal/v2/token`,{headers:{...m,Authorization:`Bearer ${e}`}});if(!t.ok){let e=await t.text().catch(()=>``);throw Error(`Copilot token exchange failed: ${t.status} ${t.statusText} — ${e.slice(0,300)}`)}let n=await t.json();if(typeof n.token!=`string`||typeof n.expires_at!=`number`)throw Error(`Copilot token exchange returned an unexpected payload`);if(n.chat_enabled===!1)throw Error(`GitHub Copilot Chat is disabled for this account (no chat features granted)`);return{copilotToken:n.token,expiresAtMs:n.expires_at*1e3-3e5,apiBaseUrl:b(n.token)??`https://api.individual.githubcopilot.com`,githubAccessToken:e}}const S=`github-copilot.models.v1`;function C(e){let t=e.supported_endpoints??[],n=(e.vendor??``).toLowerCase(),r=e.id;return n===`anthropic`&&t.includes(`/v1/messages`)?`anthropic-messages`:n===`openai`&&(/^gpt-5/i.test(r)||/codex/i.test(r)||/^o\d/i.test(r))?`openai-responses`:`openai-completions`}function w(e){if(!e||typeof e!=`object`)return[];let t=e.data;if(!Array.isArray(t))return[];let n=[];for(let e of t)e.capabilities?.type&&e.capabilities.type!==`chat`||e.model_picker_enabled!==!1&&e.id&&n.push({id:e.id,name:e.name??e.id,vendor:e.vendor??``,api:C(e),contextWindow:e.capabilities?.limits?.max_context_window_tokens??e.capabilities?.limits?.max_prompt_tokens??128e3,maxTokens:e.capabilities?.limits?.max_output_tokens??8192,supportsTools:e.capabilities?.supports?.tool_calls===!0,supportsStreaming:e.capabilities?.supports?.streaming!==!1,supportsVision:e.capabilities?.supports?.vision===!0,supportsReasoning:e.capabilities?.supports?.adaptive_thinking===!0||Array.isArray(e.capabilities?.supports?.reasoning_effort),policyState:e.policy?.state??`enabled`});return n}async function T(e){let t=await fetch(`${e.apiBaseUrl}/models`,{headers:{...m,Authorization:`Bearer ${e.copilotToken}`,Accept:`application/json`}});if(!t.ok)throw Error(`Copilot /models returned ${t.status} ${t.statusText}`);return w(await t.json())}function E(){if(typeof localStorage>`u`)return[];try{let e=localStorage.getItem(S);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function D(e){if(!(typeof localStorage>`u`))try{localStorage.setItem(S,JSON.stringify(e))}catch{}}function O(e){return E().find(t=>t.id===e)??null}async function k(e){let t;try{t=await T(e)}catch(e){console.warn(`[github-copilot] Catalog refresh failed; keeping previous cache.`,e instanceof Error?e.message:String(e));return}D(t),await Promise.all(t.filter(e=>e.policyState===`disabled`).map(async t=>{let n=`${e.apiBaseUrl}/models/${encodeURIComponent(t.id)}/policy`;try{let r=await fetch(n,{method:`POST`,headers:{...m,"Content-Type":`application/json`,Authorization:`Bearer ${e.copilotToken}`,"openai-intent":`chat-policy`,"x-interaction-type":`chat-policy`},body:JSON.stringify({state:`enabled`})});r.ok?t.policyState=`enabled`:r.status!==404&&r.status!==400&&console.warn(`[github-copilot] enable policy for ${t.id} returned ${r.status} ${r.statusText}`)}catch(e){console.warn(`[github-copilot] enable policy for ${t.id} failed:`,e instanceof Error?e.message:String(e))}})),D(t)}async function A(e,n){await t({providerId:f,accessToken:e.copilotToken,refreshToken:e.githubAccessToken,tokenExpiresAt:e.expiresAtMs,baseUrl:e.apiBaseUrl,userName:n})}async function j(){let e=g();if(!e?.accessToken||!e.refreshToken)throw Error(`Not logged in to GitHub Copilot — click "Login" in the provider settings`);let t=e.tokenExpiresAt??0;if(Date.now()<t-6e4)return e.accessToken;let n=await x(e.refreshToken);return await A(n,e.userName),n.copilotToken}const M=[`mini`,`nano`,`flash`,`haiku`,`lite`,`embedding`];function N(e){let t=[e.id,e.name??``].flatMap(e=>{let t=e.toLowerCase();return[t,t.replace(/[\s_.:]+/g,`-`)]});return!M.some(e=>t.some(t=>t.includes(e)))}function P(){if(!g()?.accessToken)return[];let e=E();if(e.length>0)return e.filter(e=>!e.policyState.startsWith(`unavailable:`)).filter(e=>N(e)).map(e=>({id:e.id,name:e.name,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.supportsReasoning,input:e.supportsVision?[`text`,`image`]:[`text`]}));let t;try{t=r(`github-copilot`)}catch{return[]}return t.filter(e=>N({id:e.id,name:e.name})).map(e=>({id:e.id,name:e.name??e.id,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.reasoning,input:e.input}))}function F(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:e.api,provider:f,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 I={"User-Agent":`GitHubCopilotChat/0.35.0`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`};function L(e){let t=g(),n=t?.baseUrl??`https://api.individual.githubcopilot.com`,r=O(e);if(r)return{api:r.api,baseUrl:n,headers:{...I}};try{let n=a(`github-copilot`,e);return{api:n.api,baseUrl:t?.baseUrl??n.baseUrl,headers:{...n.headers??{},...I}}}catch{return null}}function R(e,t){let n=E(),r=n.findIndex(t=>t.id===e);r<0||(n[r]={...n[r],policyState:`unavailable:${t}`},D(n))}function z(e,t){return`GitHub Copilot rejected "${e}" with model_not_supported. This usually means the model isn't included in your Copilot plan (Opus and other premium models require Copilot Pro / Pro+ / Business / Enterprise). Try Claude Sonnet 4.6 or another model that appears in the picker after a fresh login. Original error: ${t}`}function B(e){if(!e||typeof e!=`object`)return null;let t=e;if(t.type!==`error`)return null;if(t.error&&typeof t.error==`object`){let e=t.error.errorMessage;if(typeof e==`string`)return e}return typeof t.errorMessage==`string`?t.errorMessage:null}function V(e,t){return e===`anthropic-messages`?t?o:d:e===`openai-responses`?t?s:c:t?u:l}function H(e,t,n){let r=B(n);if(r&&/model_not_supported/i.test(r)){R(t.id,`model_not_supported`);let n=z(t.id,r);return console.error(`[github-copilot] Plan-gated model rejection:`,n),e.push(F(t,Error(n))),e.end(),!0}return e.push(n),!1}function U(e,t,n){let r=n instanceof Error?n.message:String(n),i=n;/model_not_supported/i.test(r)&&(R(t.id,`model_not_supported`),i=Error(z(t.id,r))),console.error(`[github-copilot] Stream error:`,i instanceof Error?i.message:String(i)),e.push(F(t,i)),e.end()}async function W(e,t,n,r,i){try{let a=await j(),o=L(t.id);if(!o)throw Error(`GitHub Copilot does not recognize "${t.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let s={...t,api:o.api,baseUrl:o.baseUrl,headers:o.headers,provider:`github-copilot`},c={...r,apiKey:a},l=V(o.api,i)(s,n,c);for await(let n of l)if(H(e,t,n))return;e.end()}catch(n){U(e,t,n)}}function G(e){return(t,r,i={})=>{let a=n();return W(a,t,r,i,e),a}}const K=G(!1),q=G(!0),J=({userCode:e,verificationUrl:t})=>typeof document>`u`?(console.info(`[github-copilot] Device verification code: ${e} — open ${t} in a browser to authorize.`),Promise.resolve(`continue`)):new Promise(t=>{let n=document.createElement(`div`);n.setAttribute(`data-slicc-overlay`,`github-copilot-device`),n.style.cssText=[`position:fixed`,`top:24px`,`right:24px`,`z-index:2147483647`,`background:#0d1117`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:10px`,`padding:16px 18px`,`box-shadow:0 8px 32px rgba(0,0,0,0.45)`,`font:13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,`min-width:260px`,`max-width:340px`].join(`;`);let r=document.createElement(`div`);r.textContent=`GitHub Copilot — verification code`,r.style.cssText=`font-weight:600;margin-bottom:8px;color:#7ee787`;let i=document.createElement(`div`);i.textContent=e,i.style.cssText=[`font:600 22px ui-monospace, SFMono-Regular, Menlo, monospace`,`letter-spacing:2px`,`background:#161b22`,`border:1px solid #30363d`,`border-radius:6px`,`padding:10px 12px`,`text-align:center`,`margin-bottom:10px`,`user-select:all`,`cursor:text`].join(`;`);let a=document.createElement(`div`);a.style.cssText=`color:#8b949e;font-size:12px;line-height:1.5`,a.textContent=`Copy the code, then click Continue to open the GitHub authorization page in a new tab.`;let o=document.createElement(`div`);o.style.cssText=`display:flex;gap:8px;margin-top:12px;justify-content:flex-end`;let s=document.createElement(`button`);s.type=`button`,s.textContent=`Cancel`,s.style.cssText=[`background:transparent`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let c=document.createElement(`button`);c.type=`button`,c.textContent=`Copy & Continue`,c.style.cssText=[`background:#238636`,`color:#fff`,`border:0`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let l=()=>{try{n.remove()}catch{}};s.addEventListener(`click`,()=>{l(),t(`cancel`)}),c.addEventListener(`click`,()=>{(async()=>{try{let{copyTextToClipboard:t}=await import(`./clipboard-CknViQHB.js`).then(e=>e.t);await t(e)}catch{}l(),t(`continue`)})()}),o.appendChild(s),o.appendChild(c),n.appendChild(r),n.appendChild(i),n.appendChild(a),n.appendChild(o),document.body.appendChild(n)}),Y={id:f,name:`GitHub Copilot`,description:`Use your GitHub Copilot subscription to access Claude, GPT-5, Codex, Gemini, and Grok models. Sign in with the GitHub device-code flow.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`claude-sonnet-4.6`,oauthTokenDomains:[`*.githubcopilot.com`,`api.individual.githubcopilot.com`,`api.business.githubcopilot.com`,`api.enterprise.githubcopilot.com`],getModelIds:P,onOAuthLoginIntercepted:async(e,t,n)=>{let r=await _(),i=new URL(r.verification_uri);if(i.searchParams.set(`user_code`,r.user_code),await(n?.presentDeviceCode??J)({userCode:r.user_code,verificationUrl:i.toString(),expiresInSeconds:r.expires_in})===`cancel`)throw Error(`GitHub Copilot login cancelled`);let a=new AbortController,o=e({authorizeUrl:i.toString(),redirectUriPattern:`https://github.com/login/device/success*`,onCapture:`close`,timeoutMs:r.expires_in*1e3}).catch(e=>(console.warn(`[github-copilot] Launcher failed:`,e instanceof Error?e.message:String(e)),null)),s;try{s=await v(r,a.signal)}catch(e){throw a.abort(),await o,e}await o;let c=await x(s),l;try{let e=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${s}`,Accept:`application/json`}});if(e.ok){let t=await e.json();l=t.name||t.login}}catch{}await A(c,l),await k(c),t()},onOAuthLogout:async()=>{await t({providerId:f,accessToken:``})},onSilentRenew:async()=>{let e=g();if(!e?.refreshToken)return null;try{let t=await x(e.refreshToken);return await A(t,e.userName),await k(t),t.copilotToken}catch(e){return console.warn(`[github-copilot] Silent renew failed:`,e instanceof Error?e.message:String(e)),null}}};function X(){i({api:`github-copilot-anthropic`,stream:K,streamSimple:q}),i({api:`github-copilot-openai`,stream:K,streamSimple:q})}export{Y as config,N as isCopilotConeCompatible,X as register};
1
+ import{d as e,z as t}from"./account-store-CZ1gUZlp.js";import{a as n}from"./diagnostics-DN_idNHx.js";import{d as r,p as i,u as a}from"./bedrock-camp-BfNg24Ce.js";import{a as o,c as s,i as c,r as l,s as u,t as d}from"./legacy-api-aliases-qI5FdR49.js";import"./provider-settings-DPTmaMK4.js";const f=`github-copilot`,p=atob(`SXYxLmI1MDdhMDhjODdlY2ZlOTg=`),m={Accept:`application/json`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`},h={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`};function g(){return e().find(e=>e.providerId===f)}async function _(){let e=await fetch(`https://github.com/login/device/code`,{method:`POST`,headers:h,body:new URLSearchParams({client_id:p,scope:`read:user`})});if(!e.ok)throw Error(`GitHub device-code request failed: ${e.status} ${e.statusText} — ${await e.text().catch(()=>``)}`);let t=await e.json();if(typeof t.device_code!=`string`||typeof t.user_code!=`string`||typeof t.verification_uri!=`string`||typeof t.expires_in!=`number`||typeof t.interval!=`number`)throw Error(`GitHub device-code response had an unexpected shape`);return t}async function v(e,t){let n=Date.now()+e.expires_in*1e3,r=Math.max(1e3,Math.floor(e.interval*1e3)),i=1.2;for(;Date.now()<n;){if(t.aborted)throw Error(`Copilot login cancelled`);await y(Math.ceil(r*i),t);let n=await fetch(`https://github.com/login/oauth/access_token`,{method:`POST`,headers:h,body:new URLSearchParams({client_id:p,device_code:e.device_code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`})});if(!n.ok)throw Error(`GitHub token poll failed: ${n.status} ${n.statusText} — ${await n.text().catch(()=>``)}`);let a=await n.json();if(typeof a.access_token==`string`&&a.access_token.length>0)return a.access_token;if(a.error!==`authorization_pending`){if(a.error===`slow_down`){r=typeof a.interval==`number`?a.interval*1e3:r+5e3,i=1.4;continue}if(a.error){let e=a.error_description?`: ${a.error_description}`:``;throw Error(`Device flow failed (${a.error})${e}`)}}}throw Error(`Copilot device flow timed out (device code expired)`)}function y(e,t){return new Promise((n,r)=>{if(t.aborted){r(Error(`Copilot login cancelled`));return}let i=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Copilot login cancelled`))},{once:!0})})}function b(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,`api.`)}`:null}async function x(e){let t=await fetch(`https://api.github.com/copilot_internal/v2/token`,{headers:{...m,Authorization:`Bearer ${e}`}});if(!t.ok){let e=await t.text().catch(()=>``);throw Error(`Copilot token exchange failed: ${t.status} ${t.statusText} — ${e.slice(0,300)}`)}let n=await t.json();if(typeof n.token!=`string`||typeof n.expires_at!=`number`)throw Error(`Copilot token exchange returned an unexpected payload`);if(n.chat_enabled===!1)throw Error(`GitHub Copilot Chat is disabled for this account (no chat features granted)`);return{copilotToken:n.token,expiresAtMs:n.expires_at*1e3-3e5,apiBaseUrl:b(n.token)??`https://api.individual.githubcopilot.com`,githubAccessToken:e}}const S=`github-copilot.models.v1`;function C(e){let t=e.supported_endpoints??[],n=(e.vendor??``).toLowerCase(),r=e.id;return n===`anthropic`&&t.includes(`/v1/messages`)?`anthropic-messages`:n===`openai`&&(/^gpt-5/i.test(r)||/codex/i.test(r)||/^o\d/i.test(r))?`openai-responses`:`openai-completions`}function w(e){if(!e||typeof e!=`object`)return[];let t=e.data;if(!Array.isArray(t))return[];let n=[];for(let e of t)e.capabilities?.type&&e.capabilities.type!==`chat`||e.model_picker_enabled!==!1&&e.id&&n.push({id:e.id,name:e.name??e.id,vendor:e.vendor??``,api:C(e),contextWindow:e.capabilities?.limits?.max_context_window_tokens??e.capabilities?.limits?.max_prompt_tokens??128e3,maxTokens:e.capabilities?.limits?.max_output_tokens??8192,supportsTools:e.capabilities?.supports?.tool_calls===!0,supportsStreaming:e.capabilities?.supports?.streaming!==!1,supportsVision:e.capabilities?.supports?.vision===!0,supportsReasoning:e.capabilities?.supports?.adaptive_thinking===!0||Array.isArray(e.capabilities?.supports?.reasoning_effort),policyState:e.policy?.state??`enabled`});return n}async function T(e){let t=await fetch(`${e.apiBaseUrl}/models`,{headers:{...m,Authorization:`Bearer ${e.copilotToken}`,Accept:`application/json`}});if(!t.ok)throw Error(`Copilot /models returned ${t.status} ${t.statusText}`);return w(await t.json())}function E(){if(typeof localStorage>`u`)return[];try{let e=localStorage.getItem(S);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function D(e){if(!(typeof localStorage>`u`))try{localStorage.setItem(S,JSON.stringify(e))}catch{}}function O(e){return E().find(t=>t.id===e)??null}async function k(e){let t;try{t=await T(e)}catch(e){console.warn(`[github-copilot] Catalog refresh failed; keeping previous cache.`,e instanceof Error?e.message:String(e));return}D(t),await Promise.all(t.filter(e=>e.policyState===`disabled`).map(async t=>{let n=`${e.apiBaseUrl}/models/${encodeURIComponent(t.id)}/policy`;try{let r=await fetch(n,{method:`POST`,headers:{...m,"Content-Type":`application/json`,Authorization:`Bearer ${e.copilotToken}`,"openai-intent":`chat-policy`,"x-interaction-type":`chat-policy`},body:JSON.stringify({state:`enabled`})});r.ok?t.policyState=`enabled`:r.status!==404&&r.status!==400&&console.warn(`[github-copilot] enable policy for ${t.id} returned ${r.status} ${r.statusText}`)}catch(e){console.warn(`[github-copilot] enable policy for ${t.id} failed:`,e instanceof Error?e.message:String(e))}})),D(t)}async function A(e,n){await t({providerId:f,accessToken:e.copilotToken,refreshToken:e.githubAccessToken,tokenExpiresAt:e.expiresAtMs,baseUrl:e.apiBaseUrl,userName:n})}async function j(){let e=g();if(!e?.accessToken||!e.refreshToken)throw Error(`Not logged in to GitHub Copilot — click "Login" in the provider settings`);let t=e.tokenExpiresAt??0;if(Date.now()<t-6e4)return e.accessToken;let n=await x(e.refreshToken);return await A(n,e.userName),n.copilotToken}const M=[`mini`,`nano`,`flash`,`haiku`,`lite`,`embedding`];function N(e){let t=[e.id,e.name??``].flatMap(e=>{let t=e.toLowerCase();return[t,t.replace(/[\s_.:]+/g,`-`)]});return!M.some(e=>t.some(t=>t.includes(e)))}function P(){if(!g()?.accessToken)return[];let e=E();if(e.length>0)return e.filter(e=>!e.policyState.startsWith(`unavailable:`)).filter(e=>N(e)).map(e=>({id:e.id,name:e.name,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.supportsReasoning,input:e.supportsVision?[`text`,`image`]:[`text`]}));let t;try{t=r(`github-copilot`)}catch{return[]}return t.filter(e=>N({id:e.id,name:e.name})).map(e=>({id:e.id,name:e.name??e.id,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.reasoning,input:e.input}))}function F(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:e.api,provider:f,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 I={"User-Agent":`GitHubCopilotChat/0.35.0`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`};function L(e){let t=g(),n=t?.baseUrl??`https://api.individual.githubcopilot.com`,r=O(e);if(r)return{api:r.api,baseUrl:n,headers:{...I}};try{let n=a(`github-copilot`,e);return{api:n.api,baseUrl:t?.baseUrl??n.baseUrl,headers:{...n.headers??{},...I}}}catch{return null}}function R(e,t){let n=E(),r=n.findIndex(t=>t.id===e);r<0||(n[r]={...n[r],policyState:`unavailable:${t}`},D(n))}function z(e,t){return`GitHub Copilot rejected "${e}" with model_not_supported. This usually means the model isn't included in your Copilot plan (Opus and other premium models require Copilot Pro / Pro+ / Business / Enterprise). Try Claude Sonnet 4.6 or another model that appears in the picker after a fresh login. Original error: ${t}`}function B(e){if(!e||typeof e!=`object`)return null;let t=e;if(t.type!==`error`)return null;if(t.error&&typeof t.error==`object`){let e=t.error.errorMessage;if(typeof e==`string`)return e}return typeof t.errorMessage==`string`?t.errorMessage:null}function V(e,t){return e===`anthropic-messages`?t?o:d:e===`openai-responses`?t?s:c:t?u:l}function H(e,t,n){let r=B(n);if(r&&/model_not_supported/i.test(r)){R(t.id,`model_not_supported`);let n=z(t.id,r);return console.error(`[github-copilot] Plan-gated model rejection:`,n),e.push(F(t,Error(n))),e.end(),!0}return e.push(n),!1}function U(e,t,n){let r=n instanceof Error?n.message:String(n),i=n;/model_not_supported/i.test(r)&&(R(t.id,`model_not_supported`),i=Error(z(t.id,r))),console.error(`[github-copilot] Stream error:`,i instanceof Error?i.message:String(i)),e.push(F(t,i)),e.end()}async function W(e,t,n,r,i){try{let a=await j(),o=L(t.id);if(!o)throw Error(`GitHub Copilot does not recognize "${t.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let s={...t,api:o.api,baseUrl:o.baseUrl,headers:o.headers,provider:`github-copilot`},c={...r,apiKey:a},l=V(o.api,i)(s,n,c);for await(let n of l)if(H(e,t,n))return;e.end()}catch(n){U(e,t,n)}}function G(e){return(t,r,i={})=>{let a=n();return W(a,t,r,i,e),a}}const K=G(!1),q=G(!0),J=({userCode:e,verificationUrl:t})=>typeof document>`u`?(console.info(`[github-copilot] Device verification code: ${e} — open ${t} in a browser to authorize.`),Promise.resolve(`continue`)):new Promise(t=>{let n=document.createElement(`div`);n.setAttribute(`data-slicc-overlay`,`github-copilot-device`),n.style.cssText=[`position:fixed`,`top:24px`,`right:24px`,`z-index:2147483647`,`background:#0d1117`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:10px`,`padding:16px 18px`,`box-shadow:0 8px 32px rgba(0,0,0,0.45)`,`font:13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,`min-width:260px`,`max-width:340px`].join(`;`);let r=document.createElement(`div`);r.textContent=`GitHub Copilot — verification code`,r.style.cssText=`font-weight:600;margin-bottom:8px;color:#7ee787`;let i=document.createElement(`div`);i.textContent=e,i.style.cssText=[`font:600 22px ui-monospace, SFMono-Regular, Menlo, monospace`,`letter-spacing:2px`,`background:#161b22`,`border:1px solid #30363d`,`border-radius:6px`,`padding:10px 12px`,`text-align:center`,`margin-bottom:10px`,`user-select:all`,`cursor:text`].join(`;`);let a=document.createElement(`div`);a.style.cssText=`color:#8b949e;font-size:12px;line-height:1.5`,a.textContent=`Copy the code, then click Continue to open the GitHub authorization page in a new tab.`;let o=document.createElement(`div`);o.style.cssText=`display:flex;gap:8px;margin-top:12px;justify-content:flex-end`;let s=document.createElement(`button`);s.type=`button`,s.textContent=`Cancel`,s.style.cssText=[`background:transparent`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let c=document.createElement(`button`);c.type=`button`,c.textContent=`Copy & Continue`,c.style.cssText=[`background:#238636`,`color:#fff`,`border:0`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let l=()=>{try{n.remove()}catch{}};s.addEventListener(`click`,()=>{l(),t(`cancel`)}),c.addEventListener(`click`,()=>{(async()=>{try{let{copyTextToClipboard:t}=await import(`./clipboard-CknViQHB.js`).then(e=>e.t);await t(e)}catch{}l(),t(`continue`)})()}),o.appendChild(s),o.appendChild(c),n.appendChild(r),n.appendChild(i),n.appendChild(a),n.appendChild(o),document.body.appendChild(n)}),Y={id:f,name:`GitHub Copilot`,description:`Use your GitHub Copilot subscription to access Claude, GPT-5, Codex, Gemini, and Grok models. Sign in with the GitHub device-code flow.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`claude-sonnet-4.6`,oauthTokenDomains:[`*.githubcopilot.com`,`api.individual.githubcopilot.com`,`api.business.githubcopilot.com`,`api.enterprise.githubcopilot.com`],getModelIds:P,onOAuthLoginIntercepted:async(e,t,n)=>{let r=await _(),i=new URL(r.verification_uri);if(i.searchParams.set(`user_code`,r.user_code),await(n?.presentDeviceCode??J)({userCode:r.user_code,verificationUrl:i.toString(),expiresInSeconds:r.expires_in})===`cancel`)throw Error(`GitHub Copilot login cancelled`);let a=new AbortController,o=e({authorizeUrl:i.toString(),redirectUriPattern:`https://github.com/login/device/success*`,onCapture:`close`,timeoutMs:r.expires_in*1e3}).catch(e=>(console.warn(`[github-copilot] Launcher failed:`,e instanceof Error?e.message:String(e)),null)),s;try{s=await v(r,a.signal)}catch(e){throw a.abort(),await o,e}await o;let c=await x(s),l;try{let e=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${s}`,Accept:`application/json`}});if(e.ok){let t=await e.json();l=t.name||t.login}}catch{}await A(c,l),await k(c),t()},onOAuthLogout:async()=>{await t({providerId:f,accessToken:``})},onSilentRenew:async()=>{let e=g();if(!e?.refreshToken)return null;try{let t=await x(e.refreshToken);return await A(t,e.userName),await k(t),t.copilotToken}catch(e){return console.warn(`[github-copilot] Silent renew failed:`,e instanceof Error?e.message:String(e)),null}}};function X(){i({api:`github-copilot-anthropic`,stream:K,streamSimple:q}),i({api:`github-copilot-openai`,stream:K,streamSimple:q})}export{Y as config,N as isCopilotConeCompatible,X as register};