sliccy 4.2.0 → 4.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/ui/assets/{account-store-CiB6cAel.js → account-store-B7QAqqi3.js} +2 -2
- package/dist/ui/assets/{account-store-BcAPWTGv.js → account-store-C8na8kHM.js} +2 -2
- package/dist/ui/assets/{adobe-CrAdS9SD.js → adobe-B3FAPCSl.js} +1 -1
- package/dist/ui/assets/{adobe-B-oaNVGg.js → adobe-CLAtsbgy.js} +1 -1
- package/dist/ui/assets/{agent-message-to-chat-BAWaR5C4.js → agent-message-to-chat-u5bAg3Dv.js} +1 -1
- package/dist/ui/assets/{apps-BHERTKiO.js → apps-BrQb6D54.js} +1 -1
- package/dist/ui/assets/{azure-openai-C-826Dlw.js → azure-openai-BfAHTf5F.js} +1 -1
- package/dist/ui/assets/{azure-openai-DvGwGsI1.js → azure-openai-DdRohXjQ.js} +1 -1
- package/dist/ui/assets/{bsh-watchdog-ClOjddgN.js → bsh-watchdog-Bc7J2Bk7.js} +1 -1
- package/dist/ui/assets/{connect-surface-D6ECkvh5.js → connect-surface-FrHkI2dH.js} +1 -1
- package/dist/ui/assets/dip-CBvyzPyQ.js +1 -0
- package/dist/ui/assets/{dist-Dejj5eGe.js → dist-DOo6fKGj.js} +1 -1
- package/dist/ui/assets/{dist-l3FWXCp1.js → dist-eq0qrLpe.js} +1 -1
- package/dist/ui/assets/{es-BxwKdh2y.js → es-CRDAPvPn.js} +1 -1
- package/dist/ui/assets/{fs-D2X8IzCo.js → fs-Bd1RYTR9.js} +2 -2
- package/dist/ui/assets/{fs-BDe3kEbh.js → fs-BlUrfzJM.js} +1 -1
- package/dist/ui/assets/{github-BAqz3bbU.js → github-CqzS1etP.js} +1 -1
- package/dist/ui/assets/{github-BPoxioKX.js → github-Dik4gFKy.js} +2 -2
- package/dist/ui/assets/{github-copilot-C7kttkXK.js → github-copilot-B2O232DQ.js} +1 -1
- package/dist/ui/assets/{github-copilot-Colai-cF.js → github-copilot-yPQNbALb.js} +1 -1
- package/dist/ui/assets/{hear-lee28_gN.js → hear-UQAn2f9B.js} +1 -1
- package/dist/ui/assets/js-realm-worker-BWFis6jC.js +5 -0
- package/dist/ui/assets/{kernel-worker-ic1QU0mg.js → kernel-worker-BMe--kS1.js} +1163 -1173
- package/dist/ui/assets/{kokoro-engine-C5c0LOmY.js → kokoro-engine-Cu1pI-kR.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-C0dPnE8i.js → lick-ws-bridge-DAuwCMQO.js} +1 -1
- package/dist/ui/assets/{local-llm-DzOVooE9.js → local-llm-l4-XQFY8.js} +1 -1
- package/dist/ui/assets/{main-DqjICHRh.js → main-BDx9HQkN.js} +3 -3
- package/dist/ui/assets/{mount-DqjQTDCU.js → mount-CWCvNUcA.js} +1 -1
- package/dist/ui/assets/{mount-CCmhX5cE.js → mount-D5vdZ9ZD.js} +2 -2
- package/dist/ui/assets/{new-session-DeH2bC1U.js → new-session-Gr9WMwtw.js} +1 -1
- package/dist/ui/assets/{oauth-bootstrap-B6wP6zi_.js → oauth-bootstrap-BsfJ9QeQ.js} +2 -2
- package/dist/ui/assets/{openai-codex-C_G8kpA8.js → openai-codex-BaNE798j.js} +1 -1
- package/dist/ui/assets/{openai-codex-DKhn8od8.js → openai-codex-kuA3-9C7.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-CEpB4s-n.js → panel-rpc-handlers-BcpEgTGa.js} +1 -1
- package/dist/ui/assets/{provider-CkWZObGz.js → provider-BmbE_rtX.js} +2 -2
- package/dist/ui/assets/{provider-Bu84IJif.js → provider-CEn9M9_r.js} +1 -1
- package/dist/ui/assets/provider-store-access-BSVI8UyE.js +1 -0
- package/dist/ui/assets/provider-store-access-CWZqsjgW.js +1 -0
- package/dist/ui/assets/{providers-Dqi1y25H.js → providers-MUCDnWww.js} +1 -1
- package/dist/ui/assets/proxied-fetch-Dg114MVx.js +1 -0
- package/dist/ui/assets/{quick-llm-7TCMcdio.js → quick-llm-DB--outF.js} +1 -1
- package/dist/ui/assets/session-freezer-DUHrs9By.js +1 -0
- package/dist/ui/assets/setup-sudo-B5JoDQ4W.js +1 -0
- package/dist/ui/assets/{speak-lc1xl5Fy.js → speak-BHHbBLx8.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-Pfbc1BH8.js → sprinkle-manager-COo-zwx8.js} +1 -1
- package/dist/ui/assets/{store-B3VfUVG6.js → store-CqhogTXq.js} +1 -1
- package/dist/ui/assets/{sudo-CZTI9OeD.js → sudo-IiXNo0Z2.js} +1 -1
- package/dist/ui/assets/{transformers-env-CCpYiaIa.js → transformers-env-d7AMEyAX.js} +1 -1
- package/dist/ui/assets/{tray-leave-runtime-CdAgBa02.js → tray-leave-runtime-CQ20HzV5.js} +1 -1
- package/dist/ui/assets/{upgrade-detection--E7KkpNj.js → upgrade-detection-CqAg8yKN.js} +1 -1
- package/dist/ui/assets/{wc-attach-DAWHF0q6.js → wc-attach-NtXmSLiR.js} +2 -2
- package/dist/ui/assets/{wc-detached-DaE992Vl.js → wc-detached-TITxuKki.js} +1 -1
- package/dist/ui/assets/{wc-extension-CI60x7Bm.js → wc-extension-Dy7sBRt4.js} +2 -2
- package/dist/ui/assets/{wc-live-C_qPXh6O.js → wc-live-CKs-VTsl.js} +5 -5
- package/dist/ui/assets/{wc-nav-Fk2p4da7.js → wc-nav-BSmxk4Wx.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-CKZm1pcF.js → wc-onboarding-D4j2oDHI.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-DcxEXlT1.js → wc-placeholder-Cg0ggHwo.js} +2 -2
- package/dist/ui/assets/{wc-settings-CrD6Tm6Z.js → wc-settings-BlGVWM4o.js} +2 -2
- package/dist/ui/assets/{wc-shell-DPYESGkK.js → wc-shell-RljPbgFJ.js} +2 -2
- package/dist/ui/assets/{wc-sprinkles-DEfLhO36.js → wc-sprinkles-B791LgwY.js} +2 -2
- package/dist/ui/assets/{wc-tray-CP8sez4_.js → wc-tray-DCscOwKN.js} +3 -3
- package/dist/ui/assets/{xai-grok-CUqytO26.js → xai-grok-Dh1WJ9QS.js} +1 -1
- package/dist/ui/assets/{xai-grok-BpmkOGg0.js → xai-grok-Z0dPXLgr.js} +1 -1
- package/dist/ui/index.html +2 -2
- package/dist/ui/packages/webapp/index.html +2 -2
- package/package.json +4 -3
- package/dist/ui/assets/dip-ilEHW-Zu.js +0 -1
- package/dist/ui/assets/js-realm-worker-DFuUhqWh.js +0 -5
- package/dist/ui/assets/provider-store-access-6diGA3zc.js +0 -1
- package/dist/ui/assets/provider-store-access-KstUmZ39.js +0 -1
- package/dist/ui/assets/proxied-fetch-DK_0fIag.js +0 -1
- package/dist/ui/assets/session-freezer-1L0xsBeg.js +0 -1
- package/dist/ui/assets/setup-sudo-_cBqLWHH.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as e}from"./chunk-CMxvf4Kt.js";import{t}from"./logger-LESFN7Hj.js";import{t as n}from"./backend-local-CMfz45hs.js";import{t as r}from"./types-idfTVsM8.js";import{a as i,i as a,n as o,t as s}from"./mount-table-store-CQJEV6Ij.js";import{i as c,n as l,r as u,t as d}from"./path-utils-DU6QhF_k.js";const f=t(`fs-watcher`);let p=0;function m(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var h=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++p}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),f.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),f.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>m(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){f.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),f.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const g=t(`mount-index`);var _=class{mounts=new Map;listeners=new Set;registerMount(e,t){this.mounts.get(e)?.abortController?.abort();let n=new AbortController,r={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:n};this.mounts.set(e,r),this.notifyListeners(),this.indexMount(e,r,n.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e){let t=this.mounts.get(e);if(!t)throw Error(`No mount at ${e}`);t.abortController?.abort();let n=new AbortController;t.abortController=n,t.state={status:`pending`,indexed:0},t.files.clear(),t.directories.clear(),this.notifyListeners(),await this.indexMount(e,t,n.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,g.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r);t.state={status:`error`,indexed:0,error:i},g.error(`Mount indexing failed`,{path:e,error:i})}this.notifyListeners()}async walkHandle(e,t,n,r){if(r.aborted)return;n.directories.add(e);let i=t;for await(let[t,a]of i){if(r.aborted)return;let i=e===`/`?`/${t}`:`${e}/${t}`;a.kind===`file`?(n.files.add(i),n.state.indexed++):a.kind===`directory`&&await this.walkHandle(i,a,n,r),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}},v=class{vfs;allowedPrefixes;readOnlyPrefixes;constructor(e,t,n=[]){this.vfs=e;let r=e=>{let t=l(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(r),this.readOnlyPrefixes=n.map(r)}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=l(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(!this.isWritable(e))throw new r(`EACCES`,`permission denied`,l(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t))throw new r(`EACCES`,`permission denied`,l(e));return t}catch(t){throw t instanceof r?t:new r(`EACCES`,`permission denied`,l(e))}}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readFile(n,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=l(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=l(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),i=t?r.length:r.length-1,a=``;for(let e=0;e<i;e++){a=a+`/`+r[e];let t=this.vfs.lstatSync(a);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){return!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){return!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=l(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async exists(e){if(!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){if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let t=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(t)}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){this.checkWrite(e);let i=this.vfs.dirname(e),a=this.vfs.basename(e);try{let t=await this.vfs.realpath(i);if(!this.isWritable(t+`/`+a))throw new r(`EACCES`,`permission denied`,l(e))}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){this.checkWrite(e);let n=this.vfs.dirname(e),i=this.vfs.basename(e);try{let t=await this.vfs.realpath(n);if(!this.isWritable(t+`/`+i))throw new r(`EACCES`,`permission denied`,l(e))}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e);let n=this.vfs.dirname(t),i=this.vfs.basename(t);try{let e=await this.vfs.realpath(n);if(!this.isWritable(e+`/`+i))throw new r(`EACCES`,`permission denied`,l(t))}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e),i=this.vfs.dirname(t),a=this.vfs.basename(t);try{let e=await this.vfs.realpath(i);if(!this.isWritable(e+`/`+a))throw new r(`EACCES`,`permission denied`,l(t))}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){this.checkWrite(t);let n=this.vfs.dirname(t),i=this.vfs.basename(t);try{let e=await this.vfs.realpath(n);if(!this.isWritable(e+`/`+i))throw new r(`EACCES`,`permission denied`,l(t))}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let t=await this.vfs.readlink(e),n;if(n=t.startsWith(`/`)?l(t):l(this.vfs.dirname(e)+`/`+t),!this.isAllowedStrict(n))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async lstat(e){if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let t=l(e),n=this.vfs.dirname(t),i=this.vfs.basename(t),a;if(n===t)a=n;else try{a=await this.vfs.realpath(n)}catch{throw new r(`ENOENT`,`no such file or directory`,t)}let o=a===`/`?`/${i}`:`${a}/${i}`;if(!this.isAllowed(o))throw new r(`ENOENT`,`no such file or directory`,t);return this.vfs.lstat(o)}watch(e,t,n){if(!this.isAllowed(e))throw new r(`EACCES`,`permission denied`,l(e));let i=this.vfs.getWatcher();if(!i)throw new r(`EINVAL`,`no watcher configured`);return i.watch(l(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async dispose(){await this.vfs.dispose()}};function y(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var b=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 _;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-Dejj5eGe.js`).then(e=>e.t),import(`./dist-l3FWXCp1.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=await a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`});try{a.mount(s,n)}catch{}c={backendFs:n,refs:0},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-Dejj5eGe.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady||=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})(),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new r(`EINVAL`,`OPFS is not available in this environment`);let i=await n.getDirectory();if(t)try{await i.removeEntry(e,{recursive:!0})}catch{}return i.getDirectoryHandle(e,{create:!0})}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=new e(n,r,t?.backend??y());return await i._ready,r&&await s().catch(()=>{}),i}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){if(this.backend!==`opfs`)return;let e=this.opfsBackendFs,t=this.opfsHandle;if(!e||!t)return;let n=JSON.stringify(e.index.toJSON()),r=await(await t.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await r.write(n),await r.close()}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=l(n);t.index.delete(e),t._handles?.delete(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-Dejj5eGe.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.statSync!=`function`||typeof n.lstatSync!=`function`||typeof n.readlinkSync!=`function`)return null;let r=t;for(let e=0;e<=10;e++){let e;try{e=n.lstatSync(r)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=n.readlinkSync(r)}catch{return null}r=t.startsWith(`/`)?l(t):l(d(c(r).dir,t))}return null}lstatSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t){let n=l(e);if(this.mountPoints.has(n))throw new r(`EEXIST`,`mount point is already mounted`,n);try{if((await this.lstat(n)).type!==`directory`)throw new r(`ENOTDIR`,`mount point must be a directory`,n);if((await this.readDir(n)).length>0)throw new r(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,n)}catch(e){if(!(e instanceof r)||e.code!==`ENOENT`)throw e}let{dir:a}=c(n);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(n)}catch{}this.mountPoints.set(n,t),t.kind===`local`&&this.mountIndex.registerMount(n,t.getHandle());let o=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:n}: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:n,descriptor:o})}catch{}this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]);try{await i({targetPath:n,descriptor:o,createdAt:Date.now()},t.kind===`local`?t.getHandle():void 0)}catch{}}async unmount(e){let t=l(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await a(t)}catch{}}async reconstructBackendFromDescriptor(e){switch(e.kind){case`local`:{let t=await o(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return n.fromHandle(t,{mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-DqjQTDCU.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-DqjQTDCU.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let n=l(e);if(this.mountPoints.has(n))throw new r(`EEXIST`,`mount point is already mounted`,n);let{dir:i}=c(n);i!==`/`&&await this.mkdir(i,{recursive:!0});try{await this.lfs.mkdir(n)}catch{}this.mountPoints.set(n,t),this.internalMounts.add(n),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}async unmountInternal(e){let t=l(e);if(!this.internalMounts.has(t))throw new r(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=l(e),i=this.mountPoints.get(n);if(!i)throw new r(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}static rebrandFsError(e,t){if(e instanceof r){let n=`${e.code}: `,i=e.message;throw i.startsWith(n)&&(i=i.slice(n.length)),e.path&&i.endsWith(` '${e.path}'`)&&(i=i.slice(0,i.length-` '${e.path}'`.length)),new r(e.code,i,t)}throw e}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(t,n){let i=l(t),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new r(`EISDIR`,`is a directory`,i);let t=a.relParts.join(`/`);try{let e=await a.backend.readFile(t);return(n?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(e):e}catch(t){e.rebrandFsError(t,i)}}let o=await this.resolveSymlinks(i);try{return(n?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(o,{encoding:`utf8`}):await this.lfs.readFile(o)}catch(e){throw this.convertError(e,i)}}async writeFile(t,n,i){let a=l(t),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new r(`EISDIR`,`is a directory`,a);let t=o.relParts.join(`/`),i=!1;try{await this.stat(a),i=!0}catch{}let s=typeof n==`string`?new TextEncoder().encode(n):n instanceof Uint8Array?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);try{await o.backend.writeFile(t,s)}catch(t){e.rebrandFsError(t,a)}this.watcher?.notify([{type:i?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let u=!1;try{await this.lfs.stat(s),u=!0}catch{}let{dir:d}=c(s);d!==`/`&&await this.mkdir(d,{recursive:!0});try{await this.lfs.writeFile(s,n);let e=typeof n==`string`?new TextEncoder().encode(n).byteLength:(n instanceof Uint8Array,n.byteLength);await this.lfs.truncate?.(s,e)}catch(e){throw this.convertError(e,a)}this.watcher?.notify([{type:u?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e){let t=l(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(t,n){let r=this.mountIndex.getDirectoryEntries(n.path,t);if(r!==void 0){let e=new Map;for(let t of r)e.set(t.name,{name:t.name,type:t.type});return this.addNestedMountEntries(e,t),[...e.values()]}let i=n.relParts.join(`/`)||`/`,a;try{a=await n.backend.readDir(i)}catch(n){e.rebrandFsError(n,t)}let o=new Map;for(let e of a)o.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(o,t),[...o.values()]}async readDirLocal(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw this.convertError(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 mkdir(t,n){let r=l(t);if(r===`/`)return;let i=this.findMount(r);if(i){if(i.relParts.length===0)return;let t=i.relParts.join(`/`),n=await this.exists(r);try{await i.backend.mkdir(t)}catch(t){e.rebrandFsError(t,r)}n||this.watcher?.notify([{type:`create`,path:r,entryType:`directory`}]);return}if(n?.recursive){let e=r.split(`/`).filter(Boolean),t=``;for(let n of e){t+=`/`+n;try{await this.lfs.mkdir(t)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw this.convertError(e,t)}}}else{try{await this.lfs.mkdir(r)}catch(e){throw this.convertError(e,r)}this.watcher?.notify([{type:`create`,path:r,entryType:`directory`}])}}async rm(t,n){let i=l(t),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new r(`EINVAL`,`cannot remove a mount point — use unmount`,i);let t;try{t=(await this.stat(i)).type}catch{}let o=a.relParts.join(`/`);try{await a.backend.remove(o,{recursive:n?.recursive})}catch(t){e.rebrandFsError(t,i)}this.watcher?.notify([{type:`delete`,path:i,entryType:t}]),this.mountIndex.notifyDelete(i);return}try{let e=await this.lfs.lstat(i);e.isSymbolicLink()?await this.lfs.unlink(i):e.isDirectory()?n?.recursive?await this.rmRecursive(i):await this.lfs.rmdir(i):await this.lfs.unlink(i)}catch(e){throw this.convertError(e,i)}this.watcher?.notify([{type:`delete`,path:i}])}async rmRecursive(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`;(await this.lfs.stat(t)).isDirectory()?await this.rmRecursive(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(t){let n=l(t),r=this.findMount(n);if(r){if(r.relParts.length===0)try{let e=await this.lfs.stat(n);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 t=r.relParts.join(`/`);try{let e=await r.backend.stat(t);return{type:e.kind===`directory`?`directory`:`file`,size:e.size,mtime:e.mtime,ctime:e.mtime}}catch(t){e.rebrandFsError(t,n)}}let i=await this.resolveSymlinks(n);try{let e=await this.lfs.stat(i);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw this.convertError(e,n)}}async exists(e){let t=l(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){let n=l(e),r=l(t),i;try{i=(await this.lstat(n)).type}catch{}try{await this.lfs.rename(n,r)}catch(e){throw this.convertError(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t){let n=l(e);if(this.canUseWalkFastPath(n)){let e=this.mountIndex.getFiles(n);if(e){for(let t of e)yield t;return}}let r=t??new Set,i=await this.safeRealpath(n);if(r.has(i))return;r.add(i);let a=await this.readDir(n);for(let e of a){let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;yield*this.walkEntry(e,t,r)}}canUseWalkFastPath(e){return this.mountPoints.size===0||!this.mountPoints.has(e)||!this.mountIndex.isReady(e)?!1:![...this.mountPoints.keys()].some(t=>t!==e&&t.startsWith(e+`/`))}async safeRealpath(e){try{return await this.realpath(e)}catch{return e}}async*walkEntry(e,t,n){if(e.type===`file`){yield t;return}if(e.type===`symlink`){yield*this.walkSymlink(t,n);return}yield*this.walk(t,n)}async*walkSymlink(e,t){try{let n=await this.stat(e);n.type===`file`?yield e:n.type===`directory`&&(yield*this.walk(e,t))}catch{}}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new r(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return c(l(e)).dir}basename(e){return c(l(e)).base}async symlink(e,t){let n=l(t);if(this.findMount(n))throw new r(`EINVAL`,`symlinks not supported on mounted filesystems`,n);let{dir:i}=c(n);i!==`/`&&await this.mkdir(i,{recursive:!0});try{await this.lfs.symlink(e,n)}catch(e){throw this.convertError(e,n)}this.watcher?.notify([{type:`create`,path:n,entryType:`symlink`}])}async readlink(e){let t=l(e);try{return await this.lfs.readlink(t)}catch(e){throw this.convertError(e,t)}}async lstat(e){let t=l(e);if(this.findMount(t))return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw this.convertError(e,t)}}async realpath(e){let t=l(e);if(this.findMount(t))return t;let n=t.split(`/`).filter(Boolean),r=`/`,i=0;for(let e=0;e<n.length;e++){let a=await this.resolveRealpathComponent(r,n[e],e===n.length-1,t,i);r=a.resolved,i=a.hops}return r}async resolveRealpathComponent(e,t,n,i,a){let o=e===`/`?`/${t}`:`${e}/${t}`;for(;;){let e=await this.lstatOrThrow(o,n,i);if(e===null||!e.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new r(`ELOOP`,`too many symbolic links encountered`,i);o=await this.readAndResolveLink(o,i)}}async lstatOrThrow(e,t,n){try{return await this.lfs.lstat(e)}catch(e){let r=this.convertError(e,n);if(r.code===`ENOENT`&&t)return null;throw r}}async readAndResolveLink(e,t){let n;try{n=await this.lfs.readlink(e)}catch(e){throw this.convertError(e,t)}return n.startsWith(`/`)?l(n):l(d(c(e).dir,n))}async resolveSymlinks(e){return this.findMount(e)?e:this.realpath(e)}convertError(e,t){if(e instanceof r)return e;let n=e?.code;if(typeof n==`string`){let i=n;if([`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`].includes(i))return new r(i,(e instanceof Error?e.message:String(e))||i,t)}let i=e instanceof Error?e.message:String(e);return i.includes(`ENOENT`)?new r(`ENOENT`,`no such file or directory`,t):i.includes(`EEXIST`)?new r(`EEXIST`,`file already exists`,t):i.includes(`ENOTDIR`)?new r(`ENOTDIR`,`not a directory`,t):i.includes(`EISDIR`)?new r(`EISDIR`,`is a directory`,t):i.includes(`ENOTEMPTY`)?new r(`ENOTEMPTY`,`directory not empty`,t):i.includes(`ELOOP`)?new r(`ELOOP`,`too many levels of symbolic links`,t):new r(`EINVAL`,i,t)}},x=e({FsError:()=>r,FsWatcher:()=>h,MountIndex:()=>_,RestrictedFS:()=>v,VirtualFS:()=>b,joinPath:()=>d,normalizePath:()=>l,pathSegments:()=>u,resolveVfsBackendFromEnv:()=>y,splitPath:()=>c});export{h as i,b as n,v as r,x as t};
|
|
1
|
+
import{r as e}from"./chunk-CMxvf4Kt.js";import{t}from"./logger-LESFN7Hj.js";import{t as n}from"./backend-local-CMfz45hs.js";import{t as r}from"./types-idfTVsM8.js";import{a as i,i as a,n as o,t as s}from"./mount-table-store-CQJEV6Ij.js";import{i as c,n as l,r as u,t as d}from"./path-utils-DU6QhF_k.js";const f=t(`fs-watcher`);let p=0;function m(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var h=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++p}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),f.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),f.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>m(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){f.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),f.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const g=t(`mount-index`);var _=class{mounts=new Map;listeners=new Set;registerMount(e,t){this.mounts.get(e)?.abortController?.abort();let n=new AbortController,r={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:n};this.mounts.set(e,r),this.notifyListeners(),this.indexMount(e,r,n.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e){let t=this.mounts.get(e);if(!t)throw Error(`No mount at ${e}`);t.abortController?.abort();let n=new AbortController;t.abortController=n,t.state={status:`pending`,indexed:0},t.files.clear(),t.directories.clear(),this.notifyListeners(),await this.indexMount(e,t,n.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,g.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r);t.state={status:`error`,indexed:0,error:i},g.error(`Mount indexing failed`,{path:e,error:i})}this.notifyListeners()}async walkHandle(e,t,n,r){if(r.aborted)return;n.directories.add(e);let i=t;for await(let[t,a]of i){if(r.aborted)return;let i=e===`/`?`/${t}`:`${e}/${t}`;a.kind===`file`?(n.files.add(i),n.state.indexed++):a.kind===`directory`&&await this.walkHandle(i,a,n,r),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}},v=class{vfs;allowedPrefixes;readOnlyPrefixes;constructor(e,t,n=[]){this.vfs=e;let r=e=>{let t=l(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(r),this.readOnlyPrefixes=n.map(r)}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=l(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(!this.isWritable(e))throw new r(`EACCES`,`permission denied`,l(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t))throw new r(`EACCES`,`permission denied`,l(e));return t}catch(t){throw t instanceof r?t:new r(`EACCES`,`permission denied`,l(e))}}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readFile(n,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=l(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=l(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),i=t?r.length:r.length-1,a=``;for(let e=0;e<i;e++){a=a+`/`+r[e];let t=this.vfs.lstatSync(a);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){return!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){return!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=l(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async exists(e){if(!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){if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let t=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(t)}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){this.checkWrite(e);let i=this.vfs.dirname(e),a=this.vfs.basename(e);try{let t=await this.vfs.realpath(i);if(!this.isWritable(t+`/`+a))throw new r(`EACCES`,`permission denied`,l(e))}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){this.checkWrite(e);let n=this.vfs.dirname(e),i=this.vfs.basename(e);try{let t=await this.vfs.realpath(n);if(!this.isWritable(t+`/`+i))throw new r(`EACCES`,`permission denied`,l(e))}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e);let n=this.vfs.dirname(t),i=this.vfs.basename(t);try{let e=await this.vfs.realpath(n);if(!this.isWritable(e+`/`+i))throw new r(`EACCES`,`permission denied`,l(t))}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e),i=this.vfs.dirname(t),a=this.vfs.basename(t);try{let e=await this.vfs.realpath(i);if(!this.isWritable(e+`/`+a))throw new r(`EACCES`,`permission denied`,l(t))}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){this.checkWrite(t);let n=this.vfs.dirname(t),i=this.vfs.basename(t);try{let e=await this.vfs.realpath(n);if(!this.isWritable(e+`/`+i))throw new r(`EACCES`,`permission denied`,l(t))}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let t=await this.vfs.readlink(e),n;if(n=t.startsWith(`/`)?l(t):l(this.vfs.dirname(e)+`/`+t),!this.isAllowedStrict(n))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async lstat(e){if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let t=l(e),n=this.vfs.dirname(t),i=this.vfs.basename(t),a;if(n===t)a=n;else try{a=await this.vfs.realpath(n)}catch{throw new r(`ENOENT`,`no such file or directory`,t)}let o=a===`/`?`/${i}`:`${a}/${i}`;if(!this.isAllowed(o))throw new r(`ENOENT`,`no such file or directory`,t);return this.vfs.lstat(o)}watch(e,t,n){if(!this.isAllowed(e))throw new r(`EACCES`,`permission denied`,l(e));let i=this.vfs.getWatcher();if(!i)throw new r(`EINVAL`,`no watcher configured`);return i.watch(l(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async dispose(){await this.vfs.dispose()}};function y(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var b=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 _;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-DOo6fKGj.js`).then(e=>e.t),import(`./dist-eq0qrLpe.js`)]);await e.ensureRootMount(a);let s=`/__opfs__/${t.dbName}`,c=e.opfsBackends.get(t.dbName);if(c&&r){try{a.umount(s)}catch{}e.opfsBackends.delete(t.dbName),c=void 0}if(!c){let n=await a.resolveMountConfig({backend:o,handle:i,metadata:`/.metadata.json`});try{a.mount(s,n)}catch{}c={backendFs:n,refs:0},e.opfsBackends.set(t.dbName,c)}c.refs+=1,t.opfsBackendFs=c.backendFs.index?c.backendFs:null,t.opfsHandle=i,t.mountRoot=s,t.rawLfs=a.promises,t.rawLfsSync=a}static async initMemoryBackend(t,n,r){let i=await import(`./dist-DOo6fKGj.js`).then(e=>e.t);await e.ensureRootMount(i);let a=`/__zenfs__/${n}`,o=e.memoryBackends.get(n);if(o&&r){try{i.umount(a)}catch{}e.memoryBackends.delete(n),o=void 0}o||(o={store:i.InMemory.create({label:n}),refs:0},e.memoryBackends.set(n,o)),o.refs+=1;try{i.mount(a,o.store)}catch{}t.mountRoot=a,t.rawLfs=i.promises,t.rawLfsSync=i,t.opfsBackendFs=null,t.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(t){return e.rootMountReady||=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})(),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new r(`EINVAL`,`OPFS is not available in this environment`);let i=await n.getDirectory();if(t)try{await i.removeEntry(e,{recursive:!0})}catch{}return i.getDirectoryHandle(e,{create:!0})}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=new e(n,r,t?.backend??y());return await i._ready,r&&await s().catch(()=>{}),i}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){if(this.backend!==`opfs`)return;let e=this.opfsBackendFs,t=this.opfsHandle;if(!e||!t)return;let n=JSON.stringify(e.index.toJSON()),r=await(await t.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await r.write(n),await r.close()}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;let t=this.opfsBackendFs;for(let n of e){let e=l(n);t.index.delete(e),t._handles?.delete(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let t=this.backend===`opfs`?e.opfsBackends:e.memoryBackends,n=t.get(this.dbName);if(n&&(--n.refs,n.refs<=0)){t.delete(this.dbName);try{(await import(`./dist-DOo6fKGj.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.statSync!=`function`||typeof n.lstatSync!=`function`||typeof n.readlinkSync!=`function`)return null;let r=t;for(let e=0;e<=10;e++){let e;try{e=n.lstatSync(r)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=n.readlinkSync(r)}catch{return null}r=t.startsWith(`/`)?l(t):l(d(c(r).dir,t))}return null}lstatSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t){let n=l(e);if(this.mountPoints.has(n))throw new r(`EEXIST`,`mount point is already mounted`,n);try{if((await this.lstat(n)).type!==`directory`)throw new r(`ENOTDIR`,`mount point must be a directory`,n);if((await this.readDir(n)).length>0)throw new r(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,n)}catch(e){if(!(e instanceof r)||e.code!==`ENOENT`)throw e}let{dir:a}=c(n);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(n)}catch{}this.mountPoints.set(n,t),t.kind===`local`&&this.mountIndex.registerMount(n,t.getHandle());let o=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:n}: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:n,descriptor:o})}catch{}this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]);try{await i({targetPath:n,descriptor:o,createdAt:Date.now()},t.kind===`local`?t.getHandle():void 0)}catch{}}async unmount(e){let t=l(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await a(t)}catch{}}async reconstructBackendFromDescriptor(e){switch(e.kind){case`local`:{let t=await o(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return n.fromHandle(t,{mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-CWCvNUcA.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-CWCvNUcA.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let n=l(e);if(this.mountPoints.has(n))throw new r(`EEXIST`,`mount point is already mounted`,n);let{dir:i}=c(n);i!==`/`&&await this.mkdir(i,{recursive:!0});try{await this.lfs.mkdir(n)}catch{}this.mountPoints.set(n,t),this.internalMounts.add(n),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}async unmountInternal(e){let t=l(e);if(!this.internalMounts.has(t))throw new r(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=l(e),i=this.mountPoints.get(n);if(!i)throw new r(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}static rebrandFsError(e,t){if(e instanceof r){let n=`${e.code}: `,i=e.message;throw i.startsWith(n)&&(i=i.slice(n.length)),e.path&&i.endsWith(` '${e.path}'`)&&(i=i.slice(0,i.length-` '${e.path}'`.length)),new r(e.code,i,t)}throw e}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(t,n){let i=l(t),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new r(`EISDIR`,`is a directory`,i);let t=a.relParts.join(`/`);try{let e=await a.backend.readFile(t);return(n?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(e):e}catch(t){e.rebrandFsError(t,i)}}let o=await this.resolveSymlinks(i);try{return(n?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(o,{encoding:`utf8`}):await this.lfs.readFile(o)}catch(e){throw this.convertError(e,i)}}async writeFile(t,n,i){let a=l(t),o=this.findMount(a);if(o){if(o.relParts.length===0)throw new r(`EISDIR`,`is a directory`,a);let t=o.relParts.join(`/`),i=!1;try{await this.stat(a),i=!0}catch{}let s=typeof n==`string`?new TextEncoder().encode(n):n instanceof Uint8Array?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n);try{await o.backend.writeFile(t,s)}catch(t){e.rebrandFsError(t,a)}this.watcher?.notify([{type:i?`modify`:`create`,path:a,entryType:`file`}]),this.mountIndex.notifyWrite(a);return}let s;try{s=await this.resolveSymlinks(a)}catch{s=a}let u=!1;try{await this.lfs.stat(s),u=!0}catch{}let{dir:d}=c(s);d!==`/`&&await this.mkdir(d,{recursive:!0});try{await this.lfs.writeFile(s,n);let e=typeof n==`string`?new TextEncoder().encode(n).byteLength:(n instanceof Uint8Array,n.byteLength);await this.lfs.truncate?.(s,e)}catch(e){throw this.convertError(e,a)}this.watcher?.notify([{type:u?`modify`:`create`,path:s,entryType:`file`}])}async readDir(e){let t=l(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(t,n){let r=this.mountIndex.getDirectoryEntries(n.path,t);if(r!==void 0){let e=new Map;for(let t of r)e.set(t.name,{name:t.name,type:t.type});return this.addNestedMountEntries(e,t),[...e.values()]}let i=n.relParts.join(`/`)||`/`,a;try{a=await n.backend.readDir(i)}catch(n){e.rebrandFsError(n,t)}let o=new Map;for(let e of a)o.set(e.name,{name:e.name,type:e.kind===`directory`?`directory`:`file`});return this.addNestedMountEntries(o,t),[...o.values()]}async readDirLocal(e){let t=await this.resolveSymlinks(e);try{let e=await this.lfs.readdir(t),n=[];for(let r of e){let e=await this.statDirEntry(t,r);e&&n.push(e)}return n}catch(t){throw this.convertError(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 mkdir(t,n){let r=l(t);if(r===`/`)return;let i=this.findMount(r);if(i){if(i.relParts.length===0)return;let t=i.relParts.join(`/`),n=await this.exists(r);try{await i.backend.mkdir(t)}catch(t){e.rebrandFsError(t,r)}n||this.watcher?.notify([{type:`create`,path:r,entryType:`directory`}]);return}if(n?.recursive){let e=r.split(`/`).filter(Boolean),t=``;for(let n of e){t+=`/`+n;try{await this.lfs.mkdir(t)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw this.convertError(e,t)}}}else{try{await this.lfs.mkdir(r)}catch(e){throw this.convertError(e,r)}this.watcher?.notify([{type:`create`,path:r,entryType:`directory`}])}}async rm(t,n){let i=l(t),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new r(`EINVAL`,`cannot remove a mount point — use unmount`,i);let t;try{t=(await this.stat(i)).type}catch{}let o=a.relParts.join(`/`);try{await a.backend.remove(o,{recursive:n?.recursive})}catch(t){e.rebrandFsError(t,i)}this.watcher?.notify([{type:`delete`,path:i,entryType:t}]),this.mountIndex.notifyDelete(i);return}try{let e=await this.lfs.lstat(i);e.isSymbolicLink()?await this.lfs.unlink(i):e.isDirectory()?n?.recursive?await this.rmRecursive(i):await this.lfs.rmdir(i):await this.lfs.unlink(i)}catch(e){throw this.convertError(e,i)}this.watcher?.notify([{type:`delete`,path:i}])}async rmRecursive(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`;(await this.lfs.stat(t)).isDirectory()?await this.rmRecursive(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(t){let n=l(t),r=this.findMount(n);if(r){if(r.relParts.length===0)try{let e=await this.lfs.stat(n);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 t=r.relParts.join(`/`);try{let e=await r.backend.stat(t);return{type:e.kind===`directory`?`directory`:`file`,size:e.size,mtime:e.mtime,ctime:e.mtime}}catch(t){e.rebrandFsError(t,n)}}let i=await this.resolveSymlinks(n);try{let e=await this.lfs.stat(i);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw this.convertError(e,n)}}async exists(e){let t=l(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){let n=l(e),r=l(t),i;try{i=(await this.lstat(n)).type}catch{}try{await this.lfs.rename(n,r)}catch(e){throw this.convertError(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:i},{type:`create`,path:r,entryType:i}]),this.mountIndex.notifyRename(n,r)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t){let n=l(e);if(this.canUseWalkFastPath(n)){let e=this.mountIndex.getFiles(n);if(e){for(let t of e)yield t;return}}let r=t??new Set,i=await this.safeRealpath(n);if(r.has(i))return;r.add(i);let a=await this.readDir(n);for(let e of a){let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;yield*this.walkEntry(e,t,r)}}canUseWalkFastPath(e){return this.mountPoints.size===0||!this.mountPoints.has(e)||!this.mountIndex.isReady(e)?!1:![...this.mountPoints.keys()].some(t=>t!==e&&t.startsWith(e+`/`))}async safeRealpath(e){try{return await this.realpath(e)}catch{return e}}async*walkEntry(e,t,n){if(e.type===`file`){yield t;return}if(e.type===`symlink`){yield*this.walkSymlink(t,n);return}yield*this.walk(t,n)}async*walkSymlink(e,t){try{let n=await this.stat(e);n.type===`file`?yield e:n.type===`directory`&&(yield*this.walk(e,t))}catch{}}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new r(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return c(l(e)).dir}basename(e){return c(l(e)).base}async symlink(e,t){let n=l(t);if(this.findMount(n))throw new r(`EINVAL`,`symlinks not supported on mounted filesystems`,n);let{dir:i}=c(n);i!==`/`&&await this.mkdir(i,{recursive:!0});try{await this.lfs.symlink(e,n)}catch(e){throw this.convertError(e,n)}this.watcher?.notify([{type:`create`,path:n,entryType:`symlink`}])}async readlink(e){let t=l(e);try{return await this.lfs.readlink(t)}catch(e){throw this.convertError(e,t)}}async lstat(e){let t=l(e);if(this.findMount(t))return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw this.convertError(e,t)}}async realpath(e){let t=l(e);if(this.findMount(t))return t;let n=t.split(`/`).filter(Boolean),r=`/`,i=0;for(let e=0;e<n.length;e++){let a=await this.resolveRealpathComponent(r,n[e],e===n.length-1,t,i);r=a.resolved,i=a.hops}return r}async resolveRealpathComponent(e,t,n,i,a){let o=e===`/`?`/${t}`:`${e}/${t}`;for(;;){let e=await this.lstatOrThrow(o,n,i);if(e===null||!e.isSymbolicLink())return{resolved:o,hops:a};if(++a>10)throw new r(`ELOOP`,`too many symbolic links encountered`,i);o=await this.readAndResolveLink(o,i)}}async lstatOrThrow(e,t,n){try{return await this.lfs.lstat(e)}catch(e){let r=this.convertError(e,n);if(r.code===`ENOENT`&&t)return null;throw r}}async readAndResolveLink(e,t){let n;try{n=await this.lfs.readlink(e)}catch(e){throw this.convertError(e,t)}return n.startsWith(`/`)?l(n):l(d(c(e).dir,n))}async resolveSymlinks(e){return this.findMount(e)?e:this.realpath(e)}convertError(e,t){if(e instanceof r)return e;let n=e?.code;if(typeof n==`string`){let i=n;if([`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`].includes(i))return new r(i,(e instanceof Error?e.message:String(e))||i,t)}let i=e instanceof Error?e.message:String(e);return i.includes(`ENOENT`)?new r(`ENOENT`,`no such file or directory`,t):i.includes(`EEXIST`)?new r(`EEXIST`,`file already exists`,t):i.includes(`ENOTDIR`)?new r(`ENOTDIR`,`not a directory`,t):i.includes(`EISDIR`)?new r(`EISDIR`,`is a directory`,t):i.includes(`ENOTEMPTY`)?new r(`ENOTEMPTY`,`directory not empty`,t):i.includes(`ELOOP`)?new r(`ELOOP`,`too many levels of symbolic links`,t):new r(`EINVAL`,i,t)}},x=e({FsError:()=>r,FsWatcher:()=>h,MountIndex:()=>_,RestrictedFS:()=>v,VirtualFS:()=>b,joinPath:()=>d,normalizePath:()=>l,pathSegments:()=>u,resolveVfsBackendFromEnv:()=>y,splitPath:()=>c});export{h as i,b as n,v as r,x as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{E as e,i as t,p as n}from"./account-store-
|
|
1
|
+
import{E as e,i as t,p as n}from"./account-store-B7QAqqi3.js";import{u as r,v as i,y as a}from"./kernel-worker-BMe--kS1.js";import{getOAuthPageOrigin as o}from"./oauth-service-DQVciyk_.js";var s={clientId:``,scopes:`repo,read:user,user:email`};function c(){try{let e=localStorage.getItem(a);if(e)return e.replace(/\/$/,``)}catch{}return i}async function l(e){let t=`${c()}/oauth/token`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}),r;try{r=await n.json()}catch{throw Error(`Token exchange failed (HTTP ${n.status}): non-JSON response`)}if(!n.ok&&n.status!==200){let e=r.error_description??r.error??`Token exchange failed (HTTP ${n.status})`;throw Error(e)}if(r.error){let e=r.error_description??r.error;throw Error(e)}return r}async function u(e){let t=`${c()}/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 d=Object.assign({"/packages/webapp/providers/github-config.json":s})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let f=null,p=null;function m(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,extensionId:o,nonce:s}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:o,path:`/github`,nonce:s}};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:s}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:s}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:s}}}async function h(){if(f)return f;if(g){try{let e=await fetch(`${c()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return f=t.oauth.github,f}}catch{}return d.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return f=t.oauth.github,f;if(t.trayWorkerBaseUrl){p=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return f=t.oauth.github,f}}}}catch{}return d.clientId}const g=typeof chrome<`u`&&!!chrome?.runtime?.id;function _(){return t().find(e=>e.providerId===`github`)}function v(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function y(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 b(e,t){return`${e}+${t}@users.noreply.github.com`}async function x(e){try{let{VirtualFS:t}=await import(`./fs-BlUrfzJM.js`).then(e=>e.t);await(await t.create({dbName:r})).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 S(){try{let{VirtualFS:e}=await import(`./fs-BlUrfzJM.js`).then(e=>e.t);await(await e.create({dbName:r})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function C(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await import(`./fs-BlUrfzJM.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:i}=await import(`./kernel-worker-BMe--kS1.js`).then(e=>e.l),a=await t.create({dbName:r}),o=e.name||e.login,s=b(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))}}async function w(){let e=_();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);return e.accessToken}const T={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,i)=>{let a=await h();if(!a)throw Error(`GitHub OAuth not configured — no client ID available`);let s=i?.scopes??d.scopes,u=g?null:await o(),f=crypto.randomUUID(),_=g?chrome.runtime.id:``,{redirectUri:b,state:w}=m({isExtension:g,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:c(),runtimeWorkerBaseUrl:p,pageOrigin:u?.origin??null,pageHref:u?.href??null,extensionId:_,nonce:f}),T=btoa(JSON.stringify(w)),E=f,D=new URLSearchParams({client_id:a,scope:s,redirect_uri:b});T&&D.set(`state`,T);let O=await t(`https://github.com/login/oauth/authorize?${D}`);if(!O)return;if(E)try{if(new URL(O).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 k=v(O);if(!k){console.error(`[github] Could not extract authorization code from redirect URL`);return}let A=await l({provider:`github`,code:k,redirectUri:b}),j=await y(A.access_token);await e({providerId:`github`,accessToken:A.access_token,userName:j.name,userAvatar:j.avatar});let M=n(`github`)?.maskedValue;M?await x(M):await S(),await C(j),r()},onOAuthLogout:async()=>{let t=_();t?.accessToken&&await u({provider:`github`,accessToken:t.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await S(),await e({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{b as buildNoreplyEmail,T as config,v as extractCodeFromUrl,w as getValidAccessToken,m as resolveGithubOAuthRedirect,C as syncGitIdentityFromGitHub};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/fs-
|
|
2
|
-
import{t as e}from"./preload-helper-zJ_50EbN.js";import{L as t,S as n,d as r}from"./account-store-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/fs-Bd1RYTR9.js","assets/preload-helper-zJ_50EbN.js","assets/logger-DDBAeTLF.js","assets/mount-id-DtHfwjbZ.js","assets/mount-picker-popup-BORxgnGu.js","assets/chunk-aKtaBQYM.js","assets/types-idfTVsM8.js","assets/picker-approval-tzbkMw-e.js","assets/tool-ui-YOPqzMmL.js","assets/path-utils-DU6QhF_k.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-zJ_50EbN.js";import{L as t,S as n,d as r}from"./account-store-C8na8kHM.js";import{l as i,s as a}from"./main-BDx9HQkN.js";import{getOAuthPageOrigin as o}from"./oauth-service-CTlktxVj.js";import{t as s}from"./global-db-CbuLl-zx.js";var c={clientId:``,scopes:`repo,read:user,user:email`};function l(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return a}async function u(e){let t=`${l()}/oauth/token`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}),r;try{r=await n.json()}catch{throw Error(`Token exchange failed (HTTP ${n.status}): non-JSON response`)}if(!n.ok&&n.status!==200){let e=r.error_description??r.error??`Token exchange failed (HTTP ${n.status})`;throw Error(e)}if(r.error){let e=r.error_description??r.error;throw Error(e)}return r}async function d(e){let t=`${l()}/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 f=Object.assign({"/packages/webapp/providers/github-config.json":c})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`},p=null,m=null;function h(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,extensionId:o,nonce:s}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:o,path:`/github`,nonce:s}};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:s}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:s}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:s}}}async function g(){if(p)return p;if(_){try{let e=await fetch(`${l()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return p=t.oauth.github,p}}catch{}return f.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return p=t.oauth.github,p;if(t.trayWorkerBaseUrl){m=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return p=t.oauth.github,p}}}}catch{}return f.clientId}var _=typeof chrome<`u`&&!!chrome?.runtime?.id;function v(){return r().find(e=>e.providerId===`github`)}function y(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function b(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 x(e,t){return`${e}+${t}@users.noreply.github.com`}async function S(t){try{let{VirtualFS:n}=await e(async()=>{let{VirtualFS:e}=await import(`./fs-Bd1RYTR9.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]));await(await n.create({dbName:s})).writeFile(`/workspace/.git/github-token`,t),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 C(){try{let{VirtualFS:t}=await e(async()=>{let{VirtualFS:e}=await import(`./fs-Bd1RYTR9.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]));await(await t.create({dbName:s})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function w(t){if(!(!t.login||t.id===void 0))try{let{VirtualFS:n}=await e(async()=>{let{VirtualFS:e}=await import(`./fs-Bd1RYTR9.js`);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),{readGlobalGitConfigValue:r,writeGlobalGitConfigValue:i}=await e(async()=>{let{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}=await import(`./git-config-DLJIrKjL.js`);return{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}},[]),a=await n.create({dbName:s}),o=t.name||t.login,c=x(t.id,t.login);!await r(a,`user.name`)&&o&&await i(a,`user.name`,o),await r(a,`user.email`)||await i(a,`user.email`,c)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}async function T(){let e=v();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);return e.accessToken}var E={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(e,r,i)=>{let a=await g();if(!a)throw Error(`GitHub OAuth not configured — no client ID available`);let s=i?.scopes??f.scopes,c=_?null:await o(),d=crypto.randomUUID(),p=_?chrome.runtime.id:``,{redirectUri:v,state:x}=h({isExtension:_,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:l(),runtimeWorkerBaseUrl:m,pageOrigin:c?.origin??null,pageHref:c?.href??null,extensionId:p,nonce:d}),T=btoa(JSON.stringify(x)),E=d,D=new URLSearchParams({client_id:a,scope:s,redirect_uri:v});T&&D.set(`state`,T);let O=await e(`https://github.com/login/oauth/authorize?${D}`);if(!O)return;if(E)try{if(new URL(O).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 k=y(O);if(!k){console.error(`[github] Could not extract authorization code from redirect URL`);return}let A=await u({provider:`github`,code:k,redirectUri:v}),j=await b(A.access_token);await t({providerId:`github`,accessToken:A.access_token,userName:j.name,userAvatar:j.avatar});let M=n(`github`)?.maskedValue;M?await S(M):await C(),await w(j),r()},onOAuthLogout:async()=>{let e=v();e?.accessToken&&await d({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await C(),await t({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{x as buildNoreplyEmail,E as config,y as extractCodeFromUrl,T as getValidAccessToken,h as resolveGithubOAuthRedirect,w as syncGitIdentityFromGitHub};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as e,f as t,g as n,h as r,m as i,v as a,y as o}from"./bedrock-camp-wxdDcDkR.js";import{l as s,o as c,u as l}from"./transform-messages-C1X1O3BY.js";import{E as u,i as d}from"./account-store-CiB6cAel.js";import"./kernel-worker-ic1QU0mg.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 d().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-300*1e3,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,t){await u({providerId:f,accessToken:e.copilotToken,refreshToken:e.githubAccessToken,tokenExpiresAt:e.expiresAtMs,baseUrl:e.apiBaseUrl,userName:t})}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=l(`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=s(`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){return(s,l,u={})=>{let d=c();return(async()=>{try{let c=await j(),f=L(s.id);if(!f)throw Error(`GitHub Copilot does not recognize "${s.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let p={...s,api:f.api,baseUrl:f.baseUrl,headers:f.headers,provider:`github-copilot`},m={...u,apiKey:c},h;h=f.api===`anthropic-messages`?(e?n:t)(p,l,m):f.api===`openai-responses`?(e?o:r)(p,l,m):(e?a:i)(p,l,m);for await(let e of h){let t=B(e);if(t&&/model_not_supported/i.test(t)){R(s.id,`model_not_supported`);let e=z(s.id,t);console.error(`[github-copilot] Plan-gated model rejection:`,e),d.push(F(s,Error(e))),d.end();return}d.push(e)}d.end()}catch(e){let t=e instanceof Error?e.message:String(e),n=e;/model_not_supported/i.test(t)&&(R(s.id,`model_not_supported`),n=Error(z(s.id,t))),console.error(`[github-copilot] Stream error:`,n instanceof Error?n.message:String(n)),d.push(F(s,n)),d.end()}})(),d}}const H=V(!1),U=V(!0),W=({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(`./kernel-worker-ic1QU0mg.js`).then(e=>e.m);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)}),G={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??W)({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 u({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 K(){e({api:`github-copilot-anthropic`,stream:H,streamSimple:U}),e({api:`github-copilot-openai`,stream:H,streamSimple:U})}export{G as config,N as isCopilotConeCompatible,K as register};
|
|
1
|
+
import{b as e,f as t,g as n,h as r,m as i,v as a,y as o}from"./bedrock-camp-wxdDcDkR.js";import{l as s,o as c,u as l}from"./transform-messages-C1X1O3BY.js";import{E as u,i as d}from"./account-store-B7QAqqi3.js";import"./kernel-worker-BMe--kS1.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 d().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-300*1e3,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,t){await u({providerId:f,accessToken:e.copilotToken,refreshToken:e.githubAccessToken,tokenExpiresAt:e.expiresAtMs,baseUrl:e.apiBaseUrl,userName:t})}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=l(`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=s(`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){return(s,l,u={})=>{let d=c();return(async()=>{try{let c=await j(),f=L(s.id);if(!f)throw Error(`GitHub Copilot does not recognize "${s.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let p={...s,api:f.api,baseUrl:f.baseUrl,headers:f.headers,provider:`github-copilot`},m={...u,apiKey:c},h;h=f.api===`anthropic-messages`?(e?n:t)(p,l,m):f.api===`openai-responses`?(e?o:r)(p,l,m):(e?a:i)(p,l,m);for await(let e of h){let t=B(e);if(t&&/model_not_supported/i.test(t)){R(s.id,`model_not_supported`);let e=z(s.id,t);console.error(`[github-copilot] Plan-gated model rejection:`,e),d.push(F(s,Error(e))),d.end();return}d.push(e)}d.end()}catch(e){let t=e instanceof Error?e.message:String(e),n=e;/model_not_supported/i.test(t)&&(R(s.id,`model_not_supported`),n=Error(z(s.id,t))),console.error(`[github-copilot] Stream error:`,n instanceof Error?n.message:String(n)),d.push(F(s,n)),d.end()}})(),d}}const H=V(!1),U=V(!0),W=({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(`./kernel-worker-BMe--kS1.js`).then(e=>e.m);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)}),G={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??W)({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 u({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 K(){e({api:`github-copilot-anthropic`,stream:H,streamSimple:U}),e({api:`github-copilot-openai`,stream:H,streamSimple:U})}export{G as config,N as isCopilotConeCompatible,K as register};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/clipboard-DgFtRQbq.js","assets/chunk-aKtaBQYM.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{a as e,c as t,i as n,l as r,n as i,o as a,u as o}from"./dist-CSwuvPa6.js";import{t as s}from"./preload-helper-zJ_50EbN.js";import{a as c,n as l,o as u}from"./event-stream-Cs43PhOB.js";import{L as d,d as f}from"./account-store-BcAPWTGv.js";import"./main-DqjICHRh.js";var p=`github-copilot`,m=atob(`SXYxLmI1MDdhMDhjODdlY2ZlOTg=`),h=`https://github.com/login/device/code`,g=`https://github.com/login/oauth/access_token`,_=`https://api.github.com/copilot_internal/v2/token`,v={Accept:`application/json`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`},y={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`},b=`https://github.com/login/device/success*`;function x(){return f().find(e=>e.providerId===p)}async function S(){let e=await fetch(h,{method:`POST`,headers:y,body:new URLSearchParams({client_id:m,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 C(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 w(Math.ceil(r*i),t);let n=await fetch(g,{method:`POST`,headers:y,body:new URLSearchParams({client_id:m,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 w(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 T(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,`api.`)}`:null}async function E(e){let t=await fetch(_,{headers:{...v,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-300*1e3,apiBaseUrl:T(n.token)??`https://api.individual.githubcopilot.com`,githubAccessToken:e}}var D=`github-copilot.models.v1`;function O(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 k(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:O(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 A(e){let t=await fetch(`${e.apiBaseUrl}/models`,{headers:{...v,Authorization:`Bearer ${e.copilotToken}`,Accept:`application/json`}});if(!t.ok)throw Error(`Copilot /models returned ${t.status} ${t.statusText}`);return k(await t.json())}function j(){if(typeof localStorage>`u`)return[];try{let e=localStorage.getItem(D);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function M(e){if(!(typeof localStorage>`u`))try{localStorage.setItem(D,JSON.stringify(e))}catch{}}function N(e){return j().find(t=>t.id===e)??null}async function P(e){let t;try{t=await A(e)}catch(e){console.warn(`[github-copilot] Catalog refresh failed; keeping previous cache.`,e instanceof Error?e.message:String(e));return}M(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:{...v,"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))}})),M(t)}async function F(e,t){await d({providerId:p,accessToken:e.copilotToken,refreshToken:e.githubAccessToken,tokenExpiresAt:e.expiresAtMs,baseUrl:e.apiBaseUrl,userName:t})}async function I(){let e=x();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 E(e.refreshToken);return await F(n,e.userName),n.copilotToken}var L=[`mini`,`nano`,`flash`,`haiku`,`lite`,`embedding`];function R(e){let t=[e.id,e.name??``].flatMap(e=>{let t=e.toLowerCase();return[t,t.replace(/[\s_.:]+/g,`-`)]});return!L.some(e=>t.some(t=>t.includes(e)))}function z(){if(!x()?.accessToken)return[];let e=j();if(e.length>0)return e.filter(e=>!e.policyState.startsWith(`unavailable:`)).filter(e=>R(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=u(`github-copilot`)}catch{return[]}return t.filter(e=>R({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 B(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:e.api,provider:p,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 V={"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 H(e){let t=x(),n=t?.baseUrl??`https://api.individual.githubcopilot.com`,r=N(e);if(r)return{api:r.api,baseUrl:n,headers:{...V}};try{let n=c(`github-copilot`,e);return{api:n.api,baseUrl:t?.baseUrl??n.baseUrl,headers:{...n.headers??{},...V}}}catch{return null}}function U(e,t){let n=j(),r=n.findIndex(t=>t.id===e);r<0||(n[r]={...n[r],policyState:`unavailable:${t}`},M(n))}function W(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 G(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 K(o){return(s,c,u={})=>{let d=l();return(async()=>{try{let l=await I(),f=H(s.id);if(!f)throw Error(`GitHub Copilot does not recognize "${s.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let p={...s,api:f.api,baseUrl:f.baseUrl,headers:f.headers,provider:`github-copilot`},m={...u,apiKey:l},h;h=f.api===`anthropic-messages`?(o?a:i)(p,c,m):f.api===`openai-responses`?(o?r:e)(p,c,m):(o?t:n)(p,c,m);for await(let e of h){let t=G(e);if(t&&/model_not_supported/i.test(t)){U(s.id,`model_not_supported`);let e=W(s.id,t);console.error(`[github-copilot] Plan-gated model rejection:`,e),d.push(B(s,Error(e))),d.end();return}d.push(e)}d.end()}catch(e){let t=e instanceof Error?e.message:String(e),n=e;/model_not_supported/i.test(t)&&(U(s.id,`model_not_supported`),n=Error(W(s.id,t))),console.error(`[github-copilot] Stream error:`,n instanceof Error?n.message:String(n)),d.push(B(s,n)),d.end()}})(),d}}var q=K(!1),J=K(!0),Y=({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 c=document.createElement(`button`);c.type=`button`,c.textContent=`Cancel`,c.style.cssText=[`background:transparent`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let l=document.createElement(`button`);l.type=`button`,l.textContent=`Copy & Continue`,l.style.cssText=[`background:#238636`,`color:#fff`,`border:0`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let u=()=>{try{n.remove()}catch{}};c.addEventListener(`click`,()=>{u(),t(`cancel`)}),l.addEventListener(`click`,()=>{(async()=>{try{let{copyTextToClipboard:t}=await s(async()=>{let{copyTextToClipboard:e}=await import(`./clipboard-DgFtRQbq.js`).then(e=>e.t);return{copyTextToClipboard:e}},__vite__mapDeps([0,1]));await t(e)}catch{}u(),t(`continue`)})()}),o.appendChild(c),o.appendChild(l),n.appendChild(r),n.appendChild(i),n.appendChild(a),n.appendChild(o),document.body.appendChild(n)}),X={id:p,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:z,onOAuthLoginIntercepted:async(e,t,n)=>{let r=await S(),i=new URL(r.verification_uri);if(i.searchParams.set(`user_code`,r.user_code),await(n?.presentDeviceCode??Y)({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:b,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 C(r,a.signal)}catch(e){throw a.abort(),await o,e}await o;let c=await E(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 F(c,l),await P(c),t()},onOAuthLogout:async()=>{await d({providerId:p,accessToken:``})},onSilentRenew:async()=>{let e=x();if(!e?.refreshToken)return null;try{let t=await E(e.refreshToken);return await F(t,e.userName),await P(t),t.copilotToken}catch(e){return console.warn(`[github-copilot] Silent renew failed:`,e instanceof Error?e.message:String(e)),null}}};function Z(){o({api:`github-copilot-anthropic`,stream:q,streamSimple:J}),o({api:`github-copilot-openai`,stream:q,streamSimple:J})}export{X as config,R as isCopilotConeCompatible,Z as register};
|
|
2
|
+
import{a as e,c as t,i as n,l as r,n as i,o as a,u as o}from"./dist-CSwuvPa6.js";import{t as s}from"./preload-helper-zJ_50EbN.js";import{a as c,n as l,o as u}from"./event-stream-Cs43PhOB.js";import{L as d,d as f}from"./account-store-C8na8kHM.js";import"./main-BDx9HQkN.js";var p=`github-copilot`,m=atob(`SXYxLmI1MDdhMDhjODdlY2ZlOTg=`),h=`https://github.com/login/device/code`,g=`https://github.com/login/oauth/access_token`,_=`https://api.github.com/copilot_internal/v2/token`,v={Accept:`application/json`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`},y={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`},b=`https://github.com/login/device/success*`;function x(){return f().find(e=>e.providerId===p)}async function S(){let e=await fetch(h,{method:`POST`,headers:y,body:new URLSearchParams({client_id:m,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 C(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 w(Math.ceil(r*i),t);let n=await fetch(g,{method:`POST`,headers:y,body:new URLSearchParams({client_id:m,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 w(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 T(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,`api.`)}`:null}async function E(e){let t=await fetch(_,{headers:{...v,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-300*1e3,apiBaseUrl:T(n.token)??`https://api.individual.githubcopilot.com`,githubAccessToken:e}}var D=`github-copilot.models.v1`;function O(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 k(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:O(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 A(e){let t=await fetch(`${e.apiBaseUrl}/models`,{headers:{...v,Authorization:`Bearer ${e.copilotToken}`,Accept:`application/json`}});if(!t.ok)throw Error(`Copilot /models returned ${t.status} ${t.statusText}`);return k(await t.json())}function j(){if(typeof localStorage>`u`)return[];try{let e=localStorage.getItem(D);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function M(e){if(!(typeof localStorage>`u`))try{localStorage.setItem(D,JSON.stringify(e))}catch{}}function N(e){return j().find(t=>t.id===e)??null}async function P(e){let t;try{t=await A(e)}catch(e){console.warn(`[github-copilot] Catalog refresh failed; keeping previous cache.`,e instanceof Error?e.message:String(e));return}M(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:{...v,"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))}})),M(t)}async function F(e,t){await d({providerId:p,accessToken:e.copilotToken,refreshToken:e.githubAccessToken,tokenExpiresAt:e.expiresAtMs,baseUrl:e.apiBaseUrl,userName:t})}async function I(){let e=x();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 E(e.refreshToken);return await F(n,e.userName),n.copilotToken}var L=[`mini`,`nano`,`flash`,`haiku`,`lite`,`embedding`];function R(e){let t=[e.id,e.name??``].flatMap(e=>{let t=e.toLowerCase();return[t,t.replace(/[\s_.:]+/g,`-`)]});return!L.some(e=>t.some(t=>t.includes(e)))}function z(){if(!x()?.accessToken)return[];let e=j();if(e.length>0)return e.filter(e=>!e.policyState.startsWith(`unavailable:`)).filter(e=>R(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=u(`github-copilot`)}catch{return[]}return t.filter(e=>R({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 B(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:e.api,provider:p,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 V={"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 H(e){let t=x(),n=t?.baseUrl??`https://api.individual.githubcopilot.com`,r=N(e);if(r)return{api:r.api,baseUrl:n,headers:{...V}};try{let n=c(`github-copilot`,e);return{api:n.api,baseUrl:t?.baseUrl??n.baseUrl,headers:{...n.headers??{},...V}}}catch{return null}}function U(e,t){let n=j(),r=n.findIndex(t=>t.id===e);r<0||(n[r]={...n[r],policyState:`unavailable:${t}`},M(n))}function W(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 G(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 K(o){return(s,c,u={})=>{let d=l();return(async()=>{try{let l=await I(),f=H(s.id);if(!f)throw Error(`GitHub Copilot does not recognize "${s.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let p={...s,api:f.api,baseUrl:f.baseUrl,headers:f.headers,provider:`github-copilot`},m={...u,apiKey:l},h;h=f.api===`anthropic-messages`?(o?a:i)(p,c,m):f.api===`openai-responses`?(o?r:e)(p,c,m):(o?t:n)(p,c,m);for await(let e of h){let t=G(e);if(t&&/model_not_supported/i.test(t)){U(s.id,`model_not_supported`);let e=W(s.id,t);console.error(`[github-copilot] Plan-gated model rejection:`,e),d.push(B(s,Error(e))),d.end();return}d.push(e)}d.end()}catch(e){let t=e instanceof Error?e.message:String(e),n=e;/model_not_supported/i.test(t)&&(U(s.id,`model_not_supported`),n=Error(W(s.id,t))),console.error(`[github-copilot] Stream error:`,n instanceof Error?n.message:String(n)),d.push(B(s,n)),d.end()}})(),d}}var q=K(!1),J=K(!0),Y=({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 c=document.createElement(`button`);c.type=`button`,c.textContent=`Cancel`,c.style.cssText=[`background:transparent`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let l=document.createElement(`button`);l.type=`button`,l.textContent=`Copy & Continue`,l.style.cssText=[`background:#238636`,`color:#fff`,`border:0`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let u=()=>{try{n.remove()}catch{}};c.addEventListener(`click`,()=>{u(),t(`cancel`)}),l.addEventListener(`click`,()=>{(async()=>{try{let{copyTextToClipboard:t}=await s(async()=>{let{copyTextToClipboard:e}=await import(`./clipboard-DgFtRQbq.js`).then(e=>e.t);return{copyTextToClipboard:e}},__vite__mapDeps([0,1]));await t(e)}catch{}u(),t(`continue`)})()}),o.appendChild(c),o.appendChild(l),n.appendChild(r),n.appendChild(i),n.appendChild(a),n.appendChild(o),document.body.appendChild(n)}),X={id:p,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:z,onOAuthLoginIntercepted:async(e,t,n)=>{let r=await S(),i=new URL(r.verification_uri);if(i.searchParams.set(`user_code`,r.user_code),await(n?.presentDeviceCode??Y)({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:b,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 C(r,a.signal)}catch(e){throw a.abort(),await o,e}await o;let c=await E(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 F(c,l),await P(c),t()},onOAuthLogout:async()=>{await d({providerId:p,accessToken:``})},onSilentRenew:async()=>{let e=x();if(!e?.refreshToken)return null;try{let t=await E(e.refreshToken);return await F(t,e.userName),await P(t),t.copilotToken}catch(e){return console.warn(`[github-copilot] Silent renew failed:`,e instanceof Error?e.message:String(e)),null}}};function Z(){o({api:`github-copilot-anthropic`,stream:q,streamSimple:J}),o({api:`github-copilot-openai`,stream:q,streamSimple:J})}export{X as config,R as isCopilotConeCompatible,Z as register};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./logger-LESFN7Hj.js";import{n as t,t as n}from"./transformers-env-
|
|
1
|
+
import{t as e}from"./logger-LESFN7Hj.js";import{n as t,t as n}from"./transformers-env-d7AMEyAX.js";const r=16e3;async function i(e){if(typeof AudioContext>`u`||typeof OfflineAudioContext>`u`)throw Error(`audio decoding requires a window/page realm (AudioContext unavailable)`);let t=new AudioContext,n;try{n=await t.decodeAudioData(e.slice(0))}finally{await t.close().catch(()=>{})}let i=Math.max(1,Math.ceil(n.duration*r)),a=new OfflineAudioContext(1,i,r),o=a.createBufferSource();return o.buffer=n,o.connect(a.destination),o.start(),(await a.startRendering()).getChannelData(0).slice(0)}const a=e(`speech:whisper`),o=`onnx-community/whisper-tiny`;let s=null,c=`idle`,l=null;const u=new Set;function d(){return c}function f(){return l}function p(e){return e&&u.add(e),s||=(c=`loading`,h().then(e=>(c=`ready`,m(),e),e=>{throw c=`failed`,s=null,a.error(`whisper load failed`,e),e})),s}function m(){import(`./kokoro-engine-Cu1pI-kR.js`).then(({getKokoro:e})=>e()).catch(e=>a.warn(`kokoro warmup (chained after whisper) failed`,e))}async function h(){let{pipeline:e,env:r}=await import(`./transformers.web-DJfCkvxA.js`);n(r);let i=t(),s=e=>{if(e?.file){if(e.status===`progress`)i.update(e.file,e.loaded??0,e.total??0);else if(e.status===`done`)i.complete(e.file);else return;l=i.snapshot();for(let e of u)e(l)}},c=async t=>await e(`automatic-speech-recognition`,o,{device:t,dtype:t===`webgpu`?`fp32`:`q8`,progress_callback:s}),d=typeof navigator<`u`&&`gpu`in navigator,f;if(d)try{f=await c(`webgpu`)}catch(e){a.warn(`whisper webgpu init failed; retrying on wasm`,e),f=await c(`wasm`)}else f=await c(`wasm`);return a.info(`whisper ready`,{model:o,device:d?`webgpu`:`wasm`}),{async transcribe(e,t){let n=await f(e,{chunk_length_s:30,task:`transcribe`,...t?.language?{language:t.language}:{}});return(Array.isArray(n)?n.map(e=>e.text??``).join(` `):n.text??``).trim()}}}e(`speech:whisper-session`);function g(e){return e?.split(`-`)[0]?.toLowerCase()||void 0}const _=e(`speech:hear`);function v(){if(typeof window>`u`)return null;let e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}function y(e,t){let n=v();return n?new Promise((r,i)=>{let a=new n;a.continuous=!1,a.interimResults=!1,e&&(a.lang=e);let o=``,s=!1,c=setTimeout(()=>{try{a.stop()}catch{}},t);a.onresult=e=>{let t=[];for(let n=0;n<e.results.length;n++)t.push(e.results[n][0]?.transcript??``);o=t.join(` `).trim()},a.onerror=e=>{e.error===`no-speech`||e.error===`aborted`||(s=!0,clearTimeout(c),i(Error(`speech recognition error: ${e.error}`)))},a.onend=()=>{clearTimeout(c),s||r(o)},a.start()}):Promise.reject(Error(`speech recognition unavailable in this environment`))}async function b(e){let t=await navigator.mediaDevices.getUserMedia({audio:e?{deviceId:{exact:e}}:!0}),n=new MediaRecorder(t),r=[];n.ondataavailable=e=>{e.data.size>0&&r.push(e.data)},n.start(500);let i=()=>{for(let e of t.getTracks())e.stop()};return{stop:()=>new Promise(e=>{n.onstop=()=>{i(),e(r.length?new Blob(r,{type:n.mimeType||`audio/webm`}):null)};try{n.stop()}catch{i(),e(null)}}),cancel:()=>{try{n.stop()}catch{}i()}}}async function x(e={}){let t=e.timeoutMs??3e4,n=e.engine??`auto`,r=d()===`ready`;if(n===`enhanced`&&!r)throw Error("enhanced engine not ready — run `hear --warmup` (check progress with `hear --status`)");if(!(n!==`builtin`&&r))return{transcript:await y(e.lang,t),engine:`builtin`};let a=await b(e.deviceId),o=``;try{o=await y(e.lang,t)}catch(e){_.warn(`builtin endpointing failed; transcribing captured audio anyway`,e)}let s=await a.stop();if(!s)return{transcript:o,engine:`builtin`};try{let t=await p(),n=await i(await s.arrayBuffer()),r=await t.transcribe(n,{language:g(e.lang)});if(r)return{transcript:r,engine:`enhanced`}}catch(e){_.warn(`whisper transcription failed; falling back to builtin text`,e)}return{transcript:o,engine:`builtin`}}async function S(e,t){let n=await p(),r=await i(e);return{transcript:await n.transcribe(r,{language:g(t)}),engine:`enhanced`}}function C(){let e=f();return{state:d(),...e?{loaded:e.loaded,total:e.total,etaSeconds:e.etaSeconds}:{}}}function w(){return p().catch(()=>{}),C()}export{x as hearCapture,C as hearStatus,S as hearTranscribe,w as hearWarmup};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
[`unpkg`,`com`].join(`.`);const e=[`esm`,`sh`].join(`.`);[`cdn`,`jsdelivr`,`net`].join(`.`);function t(e,t){return new URL(t,`https://${e}`)}function n(n,r={}){let i=t(e,n.startsWith(`/`)?n:`/${n}`),a=[];if(r.bundle&&a.push(`bundle`),r.target&&a.push(`target=${encodeURIComponent(r.target)}`),r.query)for(let[e,t]of Object.entries(r.query))a.push(t===!0?e:`${e}=${encodeURIComponent(t)}`);return a.length>0&&(i.search=`?${a.join(`&`)}`),i}var r=class extends Error{status;statusText;url;body;constructor(e,t,n,r){let a=typeof r==`string`&&r?`: ${r.slice(0,200)}`:r&&typeof r==`object`?`: ${i(r).slice(0,200)}`:``;super(`HTTP ${e} ${t} ${n}${a}`),this.status=e,this.statusText=t,this.url=n,this.body=r,this.name=`HttpError`}};function i(e){try{return JSON.stringify(e)}catch{return String(e)}}function a(e){return new Promise(t=>setTimeout(t,e))}function o(e,t,n){let r;if(r=/^[a-z][a-z0-9+.-]*:\/\//i.test(t)?t:e?`${e.endsWith(`/`)?e.slice(0,-1):e}${t.startsWith(`/`)?t:`/${t}`}`:t,!n)return r;let i=[];for(let[e,t]of Object.entries(n))if(t!=null)if(Array.isArray(t))for(let n of t)n!=null&&i.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(n))}`);else i.push(`${encodeURIComponent(e)}=${encodeURIComponent(String(t))}`);return i.length===0?r:r+(r.includes(`?`)?`&`:`?`)+i.join(`&`)}function s(e,t){let n={};if(e)for(let[t,r]of Object.entries(e))n[t]=r;if(t)for(let[e,r]of Object.entries(t))n[e]=r;return n}function c(e){if(!e)return!1;let t=e.toLowerCase();return t.startsWith(`application/json`)||/[+/]json(;|$|\s)/.test(t)}function l(e){if(!e)return null;let t=e.trim();if(!t)return null;if(/^\d+(\.\d+)?$/.test(t)){let e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.round(e*1e3)}let n=Date.parse(t);if(Number.isFinite(n)){let e=n-Date.now();return e>0?e:0}return null}async function u(e){if(c(e.headers.get(`content-type`))){let t=await e.text();if(!t)return null;try{return JSON.parse(t)}catch{return t}}return e.text()}function d(e,t){if(e!=null)return typeof e==`string`||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof Blob<`u`&&e instanceof Blob||typeof FormData<`u`&&e instanceof FormData||typeof URLSearchParams<`u`&&e instanceof URLSearchParams||typeof ReadableStream<`u`&&e instanceof ReadableStream?e:typeof e==`object`?(Object.keys(t).some(e=>e.toLowerCase()===`content-type`)||(t[`Content-Type`]=`application/json`),JSON.stringify(e)):String(e)}function f(e){let t=e.sleep??a;function n(n){let i=new Set(n.retry?.on??[]),a=Math.max(1,Math.trunc(n.retry?.maxAttempts??1));async function c(c,f,p={}){let m=o(n.baseUrl,f,p.params),h=s(n.headers,p.headers);if(n.token){let e=await n.token({method:c,path:f,url:m});e&&(Object.keys(h).some(e=>e.toLowerCase()===`authorization`)||(h.Authorization=`Bearer ${e}`))}let g=d(p.body,h),_={method:c,headers:h};g!==void 0&&(_.body=g);let v=null;for(let o=0;o<a;o++){let s=n.timeoutMs?new AbortController:null,c=s?setTimeout(()=>s.abort(Error(`timeout`)),n.timeoutMs):null,d=p.signal&&s?.signal?AbortSignal.any([p.signal,s.signal]):p.signal??s?.signal,f=d?{..._,signal:d}:_,h;try{h=await e.fetch(m,f)}finally{c!==null&&clearTimeout(c)}if(v=h,h.ok){let e=await u(h);return p.raw?{body:e,headers:Object.fromEntries(h.headers.entries()),status:h.status}:e}if(!(o+1<a&&i.has(h.status))){let e=await u(h).catch(()=>null);throw new r(h.status,h.statusText,m,e)}let g=l(h.headers.get(`retry-after`)),y=500*2**o;await t(g===null?y:g)}if(v){let e=await u(v).catch(()=>null);throw new r(v.status,v.statusText,m,e)}throw Error(`http: no attempts made for ${c} ${m}`)}return Object.freeze({get:((e,t)=>c(`GET`,e,t)),post:((e,t)=>c(`POST`,e,t)),put:((e,t)=>c(`PUT`,e,t)),patch:((e,t)=>c(`PATCH`,e,t)),delete:((e,t)=>c(`DELETE`,e,t))})}return Object.freeze({client:n})}function p(e){let t=[],n={},r=[],i=(e,t)=>{if(e in n){let r=n[e];Array.isArray(r)?r.push(String(t)):n[e]=[String(r),String(t)]}else n[e]=t},a=2;for(;a<e.length;){let n=e[a];if(n===`--`){r.push(...e.slice(a+1));break}if(n.startsWith(`--`)){let t=n.slice(2),r=t.indexOf(`=`);if(r!==-1){i(t.slice(0,r),t.slice(r+1)),a++;continue}let o=e[a+1];if(o!==void 0&&!o.startsWith(`-`)){i(t,o),a+=2;continue}i(t,!0),a++;continue}if(n.startsWith(`-`)&&n.length>1){for(let e of n.slice(1))i(e,!0);a++;continue}t.push(n),a++}return{positional:t,flags:n,subcommand:t.length>0&&/^[a-z][\w-]*$/i.test(t[0])?t[0]:null,passthrough:r}}function m(e){let t=[...e];return Object.defineProperty(t,"parseFlags",{value:()=>p(t),enumerable:!1,writable:!1,configurable:!1}),t}function h(e){let t=e=>{if(typeof e==`string`)return e;if(e instanceof Error)return e.message;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}},n=(e,t,n)=>t===void 0?`${e(`Error:`)} ${n}\n`:t===``?`${e(n)}\n`:`${e(`${t}:`)} ${n}\n`,r=(t,n)=>t===void 0?`${e.color.yellow(`Warning:`)} ${n}\n`:t===``?`${e.color.yellow(n)}\n`:`${e.color.yellow(`${t}:`)} ${n}\n`;return{die(r,i){let a=typeof i==`number`?i:i?.exitCode??1,o=typeof i==`object`&&i&&`prefix`in i?i.prefix:void 0,s=t(r);throw e.writeStderr(n(e.color.red,o,s)),e.exit(a),Error(`unreachable`)},out(t){if(typeof t==`string`){e.writeStdout(t.endsWith(`
|
|
2
|
+
`)?t:`${t}\n`);return}try{e.writeStdout(`${JSON.stringify(t,null,2)}\n`)}catch{e.writeStdout(`${String(t)}\n`)}},warn(n,i){let a=typeof i==`object`&&i&&`prefix`in i?i.prefix:void 0;e.writeStderr(r(a,t(n)))},help(t){throw e.writeStdout(t.endsWith(`
|
|
3
|
+
`)?t:`${t}\n`),e.exit(0),Error(`unreachable`)}}}const g={reset:`\x1B[0m`,green:`\x1B[32m`,red:`\x1B[31m`,yellow:`\x1B[33m`,gray:`\x1B[90m`,bold:`\x1B[1m`,cyan:`\x1B[36m`,dim:`\x1B[2m`};function _(e){let t=e.isTTY&&!e.noColor,n=e=>n=>t?`${e}${n}${g.reset}`:String(n);return{enabled:t,green:n(g.green),red:n(g.red),yellow:n(g.yellow),gray:n(g.gray),bold:n(g.bold),cyan:n(g.cyan),dim:n(g.dim)}}const v={ms:1,s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5,M:26298e5,y:315576e5};function y(e){if(typeof e==`number`&&Number.isFinite(e))return Math.trunc(e);if(typeof e!=`string`)throw TypeError(`time.parseDuration: spec must be string or number`);let t=e.trim(),n=/^([0-9]+(?:\.[0-9]+)?)\s*(ms|s|m|h|d|w|M|y)?$/.exec(t);if(!n)throw RangeError(`time.parseDuration: unrecognized spec "${e}"`);let r=Number(n[1]),i=n[2]??`ms`;return Math.trunc(r*v[i])}function b(e){return e<10?`0${e}`:String(e)}const ee={parseDuration:y,ago(e,t=new Date){return new Date(t.getTime()-y(e))},range(e,t=new Date){let n=new Date(t.getTime());return{start:new Date(n.getTime()-y(e)),end:n}},future(e,t=new Date){let n=new Date(t.getTime());return{start:n,end:new Date(n.getTime()+y(e))}},gmailDate(e,t=new Date){let n=new Date(t.getTime()-y(e));return`${n.getFullYear()}/${b(n.getMonth()+1)}/${b(n.getDate())}`}},x=/\u001b\[[0-9;]*m/g;function S(e){return e.replace(x,``)}function C(e){return S(e).length}function w(e,t){let n=String(e??``);return t<=0?``:C(n)<=t?n:t<=1?n.slice(0,t):`${S(n).slice(0,t-1)}…`}function T(e,t){let n=String(e??``),r=C(n);return r===t?n:r>t?w(n,t):n+` `.repeat(t-r)}function E(e,t){if(!e.length)return``;let n=Math.max(...e.map(e=>e.length)),r=[];for(let i=0;i<n;i++)if(t&&t[i]!==void 0)r[i]=t[i];else{let t=0;for(let n of e){let e=i<n.length?String(n[i]??``):``;t=Math.max(t,C(e))}r[i]=t}return e.map(e=>r.map((t,n)=>T(n<e.length?String(e[n]??``):``,t)).join(` `).replace(/\s+$/,``)).join(`
|
|
4
|
+
`)}function D(e){return e instanceof Date?e:new Date(e)}function O(e,t=`short`){let n=D(e);if(Number.isNaN(n.getTime()))return String(e);if(t===`iso`)return n.toISOString();if(t===`locale`)return new Intl.DateTimeFormat(void 0,{dateStyle:`medium`}).format(n);if(t===`human`){let e=Date.now()-n.getTime(),t=Math.abs(e);if(t<6e4)return e>=0?`just now`:`in a moment`;let r=(t,n)=>e>=0?`${t} ${n}${t===1?``:`s`} ago`:`in ${t} ${n}${t===1?``:`s`}`;return t<36e5?r(Math.round(t/6e4),`minute`):t<864e5?r(Math.round(t/36e5),`hour`):t<26298e5?r(Math.round(t/864e5),`day`):t<315576e5?r(Math.round(t/26298e5),`month`):r(Math.round(t/315576e5),`year`)}return`${n.getFullYear()}-${b(n.getMonth()+1)}-${b(n.getDate())}`}const te={trunc:w,col:T,table:E,date:O},ne=async(e,t,n)=>{let r=Math.max(1,Math.trunc(e)||1),i=Array(t.length),a=0,o=[],s=async()=>{for(;;){let e=a++;if(e>=t.length)return;i[e]=await n(t[e],e)}};for(let e=0;e<Math.min(r,t.length);e++)o.push(s());return await Promise.all(o),i};var k=class{port;nextId=1;pending=new Map;eventSubscribers=new Map;handler;disposed=!1;constructor(e){this.port=e,this.handler=e=>{let t=e.data;if(t?.type===`realm-rpc-res`){let t=e.data,n=this.pending.get(t.id);if(!n)return;this.pending.delete(t.id),typeof t.error==`string`?n.reject(Error(t.error)):n.resolve(t.result);return}if(t?.type===`realm-event`){let t=e.data,n=this.eventSubscribers.get(t.channel);if(!n)return;for(let e of[...n])try{e(t.payload)}catch{}}},e.addEventListener(`message`,this.handler),e.start?.()}call(e,t,n=[]){if(this.disposed)return Promise.reject(Error(`realm-rpc: client disposed`));let r=this.nextId++,i={type:`realm-rpc-req`,id:r,channel:e,op:t,args:n};return new Promise((e,t)=>{this.pending.set(r,{resolve:e,reject:t}),this.port.postMessage(i)})}onEvent(e,t){if(this.disposed)return()=>{};let n=this.eventSubscribers.get(e);return n||(n=new Set,this.eventSubscribers.set(e,n)),n.add(t),()=>{let n=this.eventSubscribers.get(e);n&&(n.delete(t),n.size===0&&this.eventSubscribers.delete(e))}}dispose(){if(this.disposed)return;this.disposed=!0,this.port.removeEventListener(`message`,this.handler);let e=Error(`realm-rpc: client disposed`);for(let t of this.pending.values())t.reject(e);this.pending.clear(),this.eventSubscribers.clear()}};const A=new Set([`bcrypt`,`better-sqlite3`,`canvas`,`cpu-features`,`fsevents`,`leveldown`,`libxmljs`,`libxmljs2`,`node-gyp-build`,`node-sass`,`puppeteer`,`robotjs`,`sass-embedded`,`sharp`,`snappy`,`sqlite3`,`tree-sitter`,`usb`]),j={sharp:` Use the built-in 'convert' shell command for image work.`,canvas:` Use the built-in 'convert' / OffscreenCanvas for image work.`,"better-sqlite3":` Use the built-in 'sqlite3' shell command (sql.js WASM).`,sqlite3:` Use the built-in 'sqlite3' shell command (sql.js WASM).`,bcrypt:` Use crypto.subtle.digest() with PBKDF2 / Argon2 in pure JS.`,puppeteer:` Use the built-in browser-automation shell commands.`};function M(e){let t=e?.SLICC_REALM_PREFETCH_BUDGET_MS;if(typeof t==`string`&&t.length>0){let e=Number.parseInt(t,10);if(Number.isFinite(e)&&e>0)return e}return 15e3}function N(e,t){let n=j[t]??``;return Error(`require('${e}'): '${t}' is a Node native module (C++ bindings) — it cannot run in the browser sandbox.${n}`)}function re(e,t,n){return new Promise((r,i)=>{let a=setTimeout(()=>{i(Error(`Timed out after ${t/1e3}s loading ${n}`))},t);e.then(e=>{clearTimeout(a),r(e)},e=>{clearTimeout(a),i(e)})})}function ie(e){if(!e)return``;let t=e.lastIndexOf(`/`);return t<0?``:t===0?`/`:e.substring(0,t)}function P(e){return/^[A-Za-z0-9_\-./:@]+$/.test(e)?e:`'`+e.replace(/'/g,`'\\''`)+`'`}function F(e,t){return e===``?t:e===`/`?`/${t}`:`${e}/${t}`}function ae(e){let t=ie(e.argv[1]??``),n=F(t,`references`),r=F(t,`assets`),i=F(t,`.config`);async function a(){let t;try{t=await e.fs.exists(i)}catch{return null}if(!t)return null;let n;try{n=await e.fs.readFile(i)}catch{return null}let r=typeof n==`string`?n:String(n);if(!r.trim())return null;let a;try{a=JSON.parse(r)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`skill.config(): failed to parse ${i}: ${t}`)}if(a&&typeof a==`object`&&!Array.isArray(a))return a;throw Error(`skill.config(): ${i} must contain a JSON object`)}async function o(t){let n=await a();if(t===void 0)return n;if(typeof t!=`object`||!t||Array.isArray(t))throw TypeError(`skill.config(updates): updates must be a plain object`);let r={...n??{},...t};return await e.fs.writeFile(i,JSON.stringify(r,null,2)+`
|
|
5
|
+
`),r}async function s(t){if(typeof t!=`string`||!t.trim())throw TypeError(`skill.token(providerId): providerId must be a non-empty string`);let n=`oauth-token ${P(t)}`,{stdout:r,stderr:i,exitCode:a}=await e.exec(n);if(a!==0){let e=i.trim()||`oauth-token exited with code ${a}`;throw Error(`skill.token('${t}'): ${e}`)}return r.replace(/\r?\n+$/,``)}return Object.freeze({dir:t,refs:n,assets:r,config:o,token:s})}const I=new Set([`http`,`https`,`net`,`tls`,`dgram`,`dns`,`cluster`,`worker_threads`,`child_process`,`crypto`,`os`,`stream`,`zlib`,`vm`,`v8`,`perf_hooks`,`readline`,`repl`,`tty`,`inspector`]),oe=new Set([`fs`,`process`,`buffer`]);var L=class extends Error{code;constructor(e){super(`Process exited with code ${e}`),this.code=e,this.name=`NodeExitError`}};function se(e){let t=/\brequire\s*\(\s*(['"`])([^'"`\s]+)\1\s*\)/g,n=new Set,r;for(;(r=t.exec(e))!==null;)n.add(r[2]);return[...n]}function R(e){if(typeof e==`string`)return e;if(e==null)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}async function z(e,t,n=ce){let r=[],i=[],a=e=>{r.push(typeof e==`string`?e:String(e))},o=e=>{i.push(typeof e==`string`?e:String(e))},s={log:(...e)=>a(`${e.map(R).join(` `)}\n`),info:(...e)=>a(`${e.map(R).join(` `)}\n`),warn:(...e)=>o(`${e.map(R).join(` `)}\n`),error:(...e)=>o(`${e.map(R).join(` `)}\n`)},c=B(e.stdin??``),l=m(e.argv),u=!!e.env?.NO_COLOR,d={argv:l,env:e.env,cwd:()=>e.cwd,exit:e=>{throw new L(Number.isFinite(e)?Number(e):0)},stdin:c,stdout:{write:a,isTTY:!u},stderr:{write:o,isTTY:!u}},p=_({isTTY:!u,noColor:u}),g=h({writeStdout:a,writeStderr:o,exit:e=>{throw new L(e)},color:p}),v=new k(t),y=V(v,D),b=Object.assign(e=>v.call(`exec`,`run`,[e]),{spawn:e=>v.call(`exec`,`spawn`,[e])}),x=ae({argv:e.argv,fs:y,exec:b}),S=le(v),C=me(v),w=he(v),T=ge(v),E=f({fetch:D});async function D(e,t){let n=e instanceof Request?e.url:e instanceof URL?e.toString():String(e),r=await v.call(`fetch`,`request`,[n,G(t,e)]),i=r.body.byteLength===0?null:r.body.buffer.slice(r.body.byteOffset,r.body.byteOffset+r.body.byteLength),a=new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers});return Object.defineProperty(a,"url",{value:r.url||n}),a}let O=U(await H(e.code,e.env,n,o),y,d),A={exports:{},filename:e.filename},j=await W(e.code,{fs:y,process:d,console:s,require:O,module:A,exports:A.exports,exec:b,fetch:D,skill:x,http:E,browser:S,usb:C,serial:w,hid:T,cli:g,c:p,time:ee,fmt:te,pool:ne},o);v.dispose();let M={type:`realm-done`,stdout:r.join(``),stderr:i.join(``),exitCode:j};t.postMessage(M)}function B(e){let t=!1;return{isTTY:!1,read(){return t?null:(t=!0,e)},toString(){return e},[Symbol.asyncIterator](){return{async next(){return t?{value:void 0,done:!0}:(t=!0,{value:e,done:!1})}}}}}function V(e,t){return{readFile:t=>e.call(`vfs`,`readFile`,[t]),readFileBinary:t=>e.call(`vfs`,`readFileBinary`,[t]),writeFile:(t,n)=>e.call(`vfs`,`writeFile`,[t,n]),writeFileBinary:(t,n)=>e.call(`vfs`,`writeFileBinary`,[t,n]),readDir:t=>e.call(`vfs`,`readDir`,[t]),exists:t=>e.call(`vfs`,`exists`,[t]),stat:t=>e.call(`vfs`,`stat`,[t]),mkdir:t=>e.call(`vfs`,`mkdir`,[t]),rm:t=>e.call(`vfs`,`rm`,[t]),fetchToFile:async(n,r)=>{let i=await t(n);if(!i.ok)throw Error(`fetch ${i.status} ${i.statusText}`);let a=new Uint8Array(await i.arrayBuffer());return await e.call(`vfs`,`writeFileBinary`,[r,a]),a.byteLength}}}async function H(e,t,n,r){let i=se(e).map(e=>e.startsWith(`node:`)?e.slice(5):e).filter(e=>!oe.has(e)&&!I.has(e)),a=i.filter(e=>A.has(e)),o=i.filter(e=>!A.has(e));for(let e of a)r(`Warning: ${N(e,e).message}\n`);let s=Object.create(null),c=M(t);if(o.length===0)return s;let l=await Promise.allSettled(o.map(async e=>{let t=await re(n(e),c,`require('${e}')`);s[e]=t&&`default`in t?t.default:t}));for(let e=0;e<l.length;e++){let t=l[e];if(t.status===`rejected`){let n=t.reason instanceof Error?t.reason.message:String(t.reason);r(`Warning: failed to pre-load require('${o[e]}'): ${n}\n`)}}return s}function U(e,t,r){return i=>{let a=i.startsWith(`node:`)?i.slice(5):i;if(a===`fs`)return t;if(a===`process`)return r;if(a===`buffer`)return{Buffer:globalThis.Buffer};if(a===`path`){if(`path`in e)return e.path;if(i in e)return e[i];throw Error(`require('${i}'): path module not pre-loaded. Add require('path') as a static import.`)}if(A.has(a))throw N(i,a);if(I.has(a))throw Error(`require('${i}'): Node built-in '${a}' is not available in the browser environment.${{http:` Use fetch() instead.`,https:` Use fetch() instead.`,child_process:` Use exec() which is available as a shell bridge.`,crypto:` Use globalThis.crypto (Web Crypto API) instead.`}[a]||``}`);if(i in e)return e[i];if(a in e)return e[a];throw Error(`require('${i}'): module not pre-loaded. Use a string literal so it can be pre-fetched, or use \`await import('${n(i).toString()}')\` directly.`)}}async function W(e,t,n){let r=Object.keys(t),i=r.map(e=>t[e]),a=Object.getPrototypeOf(async function(){}).constructor,o=new a(...r,`"use strict";\n${e}`);try{return await o(...i),0}catch(e){return e instanceof L?e.code:(n(`${e instanceof Error?e.stack??e.message:String(e)}\n`),1)}}function G(e,t){if(!e&&!(t instanceof Request))return;let n=t instanceof Request?t:null,r=(e?.method??n?.method??`GET`).toUpperCase(),i={};if(e?.headers)if(e.headers instanceof Headers)e.headers.forEach((e,t)=>{i[t]=e});else if(Array.isArray(e.headers))for(let[t,n]of e.headers)i[t]=n;else Object.assign(i,e.headers);else n&&n.headers.forEach((e,t)=>{i[t]=e});let a;return e?.body!==void 0&&e?.body!==null&&e?.body!==``&&(a=typeof e.body==`string`?e.body:String(e.body)),{method:r,headers:i,body:a}}async function ce(e){return await import(n(e).toString())}function le(e){return{findTab:t=>e.call(`browser`,`findTab`,[de(t)]),ensureTab:(t,n={})=>e.call(`browser`,`ensureTab`,[t,fe(n)]),eval:(t,n)=>e.call(`browser`,`eval`,[K(t),q(n,!1)]),evalAsync:(t,n)=>e.call(`browser`,`evalAsync`,[K(t),q(n,!0)]),cookie:(t,n)=>e.call(`browser`,`cookie`,[K(t),n]),localStorage:(t,n)=>e.call(`browser`,`localStorage`,[K(t),n]),fetch:(t,n,r={})=>e.call(`browser`,`evalAsync`,[K(t),ue(n,r)]),websocket:pe(e)}}function K(e){if(typeof e==`string`)return e;if(e&&typeof e==`object`&&typeof e.targetId==`string`)return e.targetId;throw TypeError(`browser: expected a tab handle or targetId string`)}function q(e,t){if(typeof e==`function`)return`(${e.toString()})()`;if(typeof e==`string`)return e;throw TypeError(`browser.eval/evalAsync: source must be a function or string`)}function ue(e,t={}){let n={},r=t.headers??{};for(let[e,t]of Object.entries(r))typeof t==`string`&&(n[e]=t);let i=typeof t.method==`string`?t.method:`GET`,a=t.credentials===`same-origin`||t.credentials===`omit`?t.credentials:`include`,o;t.body!==void 0&&t.body!==null&&(typeof t.body==`string`?o=t.body:(o=JSON.stringify(t.body),Object.keys(n).some(e=>e.toLowerCase()===`content-type`)||(n[`Content-Type`]=`application/json`)));let s={method:i,credentials:a,headers:n};o!==void 0&&(s.body=o);for(let e of[`mode`,`cache`,`redirect`,`referrer`,`referrerPolicy`,`integrity`,`keepalive`]){let n=t[e];n!==void 0&&(s[e]=n)}return`(async () => {const r = await fetch(`+JSON.stringify(e)+`, `+JSON.stringify(s)+`);const h = {};r.headers.forEach((v, k) => { h[k] = v; });const ct = r.headers.get('content-type') || '';let b;if (ct.indexOf('application/json') !== -1) {try { b = await r.json(); } catch (e) { b = await r.text(); }} else { b = await r.text(); }return { ok: r.ok, status: r.status, headers: h, body: b };})()`}function de(e){let t={};return e.domain!==void 0&&(t.domain=e.domain),e.urlMatch!==void 0&&(t.urlMatch=e.urlMatch instanceof RegExp?e.urlMatch.source:e.urlMatch),t}function fe(e){return e.matchUrl===void 0?{}:{matchUrl:e.matchUrl instanceof RegExp?e.matchUrl.source:e.matchUrl}}function pe(e){function t(t){return{...t,async update(n){let r={};return n.urlMatch!==void 0&&(r.urlMatch=n.urlMatch===null?null:n.urlMatch instanceof RegExp?n.urlMatch.source:n.urlMatch),n.filter!==void 0&&(r.filter=n.filter),e.call(`browser`,`wsUpdate`,[t.id,r])},async close(){return e.call(`browser`,`wsClose`,[t.id])}}}return{on(n,r={}){let i=K(n),a=r.urlMatch===void 0?void 0:r.urlMatch instanceof RegExp?r.urlMatch.source:r.urlMatch,o,s={filter(e){if(typeof e==`function`||typeof e==`string`)throw TypeError(`browser.websocket: filter must be a declarative JSON object, not a function or string`);return o=e,s},async forward(n){return t(await e.call(`browser`,`wsObserve`,[{targetId:i,urlMatch:a,filter:o,forward:n}]))}};return s},async list(){return e.call(`browser`,`wsList`,[])}}}function J(e){if(e instanceof Uint8Array)return e;if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(e instanceof ArrayBuffer)return new Uint8Array(e);throw TypeError(`expected an ArrayBuffer or typed array`)}function Y(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function X(e){return e==null?[]:Array.isArray(e)?e:[e]}function Z(e,t){let n=t.handle,r=e=>({status:e.status,data:Y(e.bytes)});return{...t,open:()=>e.call(`usb`,`open`,[n]),close:()=>e.call(`usb`,`close`,[n]),reset:()=>e.call(`usb`,`reset`,[n]),selectConfiguration:t=>e.call(`usb`,`selectConfig`,[n,t]),claimInterface:t=>e.call(`usb`,`claim`,[n,t]),releaseInterface:t=>e.call(`usb`,`release`,[n,t]),controlTransferIn:async(t,i)=>r(await e.call(`usb`,`controlIn`,[n,t,i])),controlTransferOut:(t,r)=>e.call(`usb`,`controlOut`,[n,t,J(r)]),transferIn:async(t,i)=>r(await e.call(`usb`,`transferIn`,[n,t,i])),transferOut:(t,r)=>e.call(`usb`,`transferOut`,[n,t,J(r)])}}function me(e){return{list:async()=>(await e.call(`usb`,`list`,[])).map(t=>Z(e,t)),request:async t=>Z(e,await e.call(`usb`,`request`,[X(t)]))}}function Q(e,t){let n=t.handle;return{...t,open:t=>e.call(`serial`,`open`,[n,t]),close:()=>e.call(`serial`,`close`,[n]),read:(t={})=>e.call(`serial`,`read`,[n,{maxBytes:t.maxBytes??t.bytes,until:t.until?J(t.until):void 0,timeoutMs:t.timeoutMs}]),write:t=>e.call(`serial`,`write`,[n,J(t)]),getSignals:()=>e.call(`serial`,`getSignals`,[n]),setSignals:t=>e.call(`serial`,`setSignals`,[n,t])}}function he(e){return{list:async()=>(await e.call(`serial`,`list`,[])).map(t=>Q(e,t)),request:async t=>Q(e,await e.call(`serial`,`request`,[X(t)]))}}function $(e,t){let n=t.handle,r=new Set,i=new Set,a=!1,o=null,s=e=>{let t=e;if(!t||t.handle!==n)return;let i={reportId:t.reportId,data:Y(t.bytes)};for(let e of[...r])try{e(i)}catch{}},c=()=>{a||(a=!0,o=e.onEvent?e.onEvent(`hid-input-report`,s):null,e.call(`hid`,`subscribeInputReports`,[n]).catch(()=>{a=!1,o?.(),o=null}))},l=()=>{!a||r.size>0||(a=!1,o?.(),o=null,e.call(`hid`,`unsubscribeInputReports`,[n]).catch(()=>{}))};return{...t,open:()=>e.call(`hid`,`open`,[n]),close:()=>e.call(`hid`,`close`,[n]),sendReport:(t,r)=>e.call(`hid`,`sendReport`,[n,t,J(r)]),sendFeatureReport:(t,r)=>e.call(`hid`,`sendFeatureReport`,[n,t,J(r)]),receiveFeatureReport:async t=>Y((await e.call(`hid`,`receiveFeatureReport`,[n,t])).bytes),addEventListener(e,t){if(e===`inputreport`)r.add(t),c();else if(e===`disconnect`)i.add(t);else throw TypeError(`hid device: unknown event type '${String(e)}'`)},removeEventListener(e,t){e===`inputreport`?(r.delete(t),l()):e===`disconnect`&&i.delete(t)},onInputReport(e){r.add(e),c()}}}function ge(e){return{list:async()=>(await e.call(`hid`,`list`,[])).map(t=>$(e,t)),request:async t=>{let n=(await e.call(`hid`,`request`,[X(t)]))[0];if(!n)throw Error(`No device selected.`);return $(e,n)}}}const _e={postMessage:(e,t)=>t?self.postMessage(e,t):self.postMessage(e),addEventListener:(e,t)=>self.addEventListener(e,t),removeEventListener:(e,t)=>self.removeEventListener(e,t)};self.addEventListener(`message`,e=>{if(e.data?.type!==`realm-init`)return;let t=e.data;t.kind===`js`&&z(t,_e).catch(e=>{let t={type:`realm-error`,message:e instanceof Error?e.message:String(e)};self.postMessage(t)})});
|