sliccy 5.30.1 → 5.30.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/ui/assets/{account-store-B4wozzzo.js → account-store--8-2uLCw.js} +1 -1
  2. package/dist/ui/assets/{account-store-B1E9Pd8V.js → account-store-DxGFDdq8.js} +2 -2
  3. package/dist/ui/assets/{adobe-BMgtvJUE.js → adobe-CYcJTJyA.js} +1 -1
  4. package/dist/ui/assets/{adobe-DlB3Llpn.js → adobe-DE4VqbEO.js} +1 -1
  5. package/dist/ui/assets/{adobe-oauth-state-B_mErDyW.js → adobe-oauth-state-__w2Bk3A.js} +1 -1
  6. package/dist/ui/assets/{agent-message-to-chat-C_KsQ6tt.js → agent-message-to-chat-CBzvFm4A.js} +1 -1
  7. package/dist/ui/assets/{apps-By2jkvtN.js → apps-Fv0hShVY.js} +1 -1
  8. package/dist/ui/assets/{azure-openai-CHHosVyH.js → azure-openai-Dlw9OI0g.js} +1 -1
  9. package/dist/ui/assets/{azure-openai-B4GgOPSG.js → azure-openai-DsxNPl_K.js} +1 -1
  10. package/dist/ui/assets/{cerebras-BjFZN3s9.js → cerebras-DY2TIMBk.js} +1 -1
  11. package/dist/ui/assets/{cerebras-goMMH6rX.js → cerebras-dblwVaP_.js} +1 -1
  12. package/dist/ui/assets/{connect-surface-Becvmnau.js → connect-surface-DS3nbqEv.js} +1 -1
  13. package/dist/ui/assets/dip-rNzv7fiG.js +1 -0
  14. package/dist/ui/assets/{dist-B_CQDE9x.js → dist-BAh1Prs8.js} +1 -1
  15. package/dist/ui/assets/{dist-DDqJxY_T.js → dist-_-KdSeH9.js} +1 -1
  16. package/dist/ui/assets/{ensure-speech-assets-WQZ8C_rr.js → ensure-speech-assets-D-g2q80x.js} +1 -1
  17. package/dist/ui/assets/esp8266-qkLj6oNn.js +1 -0
  18. package/dist/ui/assets/{esptool-operations-BQJnI0my.js → esptool-operations-C5ysasTL.js} +2 -2
  19. package/dist/ui/assets/{fs-D3KOaEAt.js → fs-BCVRi4jH.js} +1 -1
  20. package/dist/ui/assets/{fs-B5CoHWsy.js → fs-CrefUvKo.js} +2 -2
  21. package/dist/ui/assets/{github-GcQbbuN6.js → github-ArmOgfUn.js} +1 -1
  22. package/dist/ui/assets/{github-copilot-Bf_MolFn.js → github-copilot-CmBXPIr-.js} +1 -1
  23. package/dist/ui/assets/{github-copilot-CEHMQipR.js → github-copilot-n2sbkxKC.js} +1 -1
  24. package/dist/ui/assets/{github-_zb1FUIj.js → github-pm2dNrPY.js} +2 -2
  25. package/dist/ui/assets/{hear-BS6-tnBX.js → hear-UbSe3dbx.js} +1 -1
  26. package/dist/ui/assets/{kernel-worker-DyWWTo8W.js → kernel-worker-DEUwy4mF.js} +18 -18
  27. package/dist/ui/assets/{kokoro-engine-GYVOhOZs.js → kokoro-engine-dGTwGEQs.js} +1 -1
  28. package/dist/ui/assets/{lick-ws-bridge-CsWfeM1O.js → lick-ws-bridge-C3DUf336.js} +1 -1
  29. package/dist/ui/assets/{lick-ws-bridge-s7pVv1kR.js → lick-ws-bridge-DTJJ2Oz-.js} +1 -1
  30. package/dist/ui/assets/{local-llm-DSaJsXZP.js → local-llm-6Z3K0AIq.js} +1 -1
  31. package/dist/ui/assets/{main-BuAHXeba.js → main-DgVu_QYm.js} +4 -4
  32. package/dist/ui/assets/{mount-9rGyUTfq.js → mount-Bu643VZV.js} +2 -2
  33. package/dist/ui/assets/{mount-tMTW6qA4.js → mount-DW7FdQ0s.js} +1 -1
  34. package/dist/ui/assets/{new-session-Bw6kMJNx.js → new-session-B1VAsUT_.js} +2 -2
  35. package/dist/ui/assets/{oauth-bootstrap-fOv0jBWV.js → oauth-bootstrap-JuR_5cxX.js} +2 -2
  36. package/dist/ui/assets/{openai-codex-CCMojnEv.js → openai-codex-BVpTltbB.js} +1 -1
  37. package/dist/ui/assets/{openai-codex-C3ZxKBE4.js → openai-codex-CXyFYXeK.js} +1 -1
  38. package/dist/ui/assets/{page-follower-tray-Crms35Ue.js → page-follower-tray-C_LTm5NR.js} +1 -1
  39. package/dist/ui/assets/{panel-rpc-handlers-AHQKeOCy.js → panel-rpc-handlers-82SdQkQ0.js} +2 -2
  40. package/dist/ui/assets/{provider-DxKpHqen.js → provider-Bi7wURL-.js} +2 -2
  41. package/dist/ui/assets/{provider-CefSwFPK.js → provider-Crv9Gsei.js} +1 -1
  42. package/dist/ui/assets/provider-store-access-BCkIDV-7.js +1 -0
  43. package/dist/ui/assets/provider-store-access-DSjdU0kG.js +1 -0
  44. package/dist/ui/assets/{providers-BahN7INd.js → providers-CSQ_3zfV.js} +1 -1
  45. package/dist/ui/assets/{providers-BPzpZ20i.js → providers-DhqKLhGJ.js} +2 -2
  46. package/dist/ui/assets/{quick-llm-BH0K8OnF.js → quick-llm-D4VdxqTa.js} +1 -1
  47. package/dist/ui/assets/session-freezer-CtlhV5gS.js +1 -0
  48. package/dist/ui/assets/{speak-v7UWfpak.js → speak-BWxoLY2t.js} +1 -1
  49. package/dist/ui/assets/{sprinkle-manager-CwGtrHcL.js → sprinkle-manager-DTdS81gA.js} +1 -1
  50. package/dist/ui/assets/{store-CbTSaami.js → store-Dim-7kwA.js} +1 -1
  51. package/dist/ui/assets/{sudo-DZsEiEIt.js → sudo-6LP46-Va.js} +1 -1
  52. package/dist/ui/assets/{transformers-env-DhGp-lOp.js → transformers-env-BTYm60Lj.js} +1 -1
  53. package/dist/ui/assets/{tray-leader-DKyTxVgp.js → tray-leader-reAwOfv8.js} +1 -1
  54. package/dist/ui/assets/{tray-leave-runtime-1IzYZ33d.js → tray-leave-runtime-B3_tztZV.js} +1 -1
  55. package/dist/ui/assets/{upgrade-detection-B6L9czTT.js → upgrade-detection-BxJmdRaD.js} +1 -1
  56. package/dist/ui/assets/{voice-reply-vuufsewo.js → voice-reply-CMF5zmcs.js} +1 -1
  57. package/dist/ui/assets/{wc-attach-0dN2vNj8.js → wc-attach-BwiH0ub2.js} +2 -2
  58. package/dist/ui/assets/{wc-extension-CrNcDb69.js → wc-extension-DHPGPjKM.js} +2 -2
  59. package/dist/ui/assets/{wc-follower-C_XexVt1.js → wc-follower-BUhCVdlB.js} +3 -3
  60. package/dist/ui/assets/{wc-live-BqUf86iQ.js → wc-live-BWPgtZ1r.js} +5 -5
  61. package/dist/ui/assets/{wc-nav-C9KmQwwY.js → wc-nav-m4v1ZLEB.js} +2 -2
  62. package/dist/ui/assets/{wc-onboarding-B94FXto0.js → wc-onboarding-FT4ORrq-.js} +2 -2
  63. package/dist/ui/assets/{wc-placeholder-BDrAeIjs.js → wc-placeholder-G1wIF-_l.js} +3 -3
  64. package/dist/ui/assets/{wc-settings-nY8Z3cpu.js → wc-settings-CFKfvaA5.js} +2 -2
  65. package/dist/ui/assets/{wc-shell-DZWH1gWj.js → wc-shell-BXuSciez.js} +22 -6
  66. package/dist/ui/assets/{wc-sprinkles-YOKs8tgC.js → wc-sprinkles-DuUuA5tF.js} +2 -2
  67. package/dist/ui/assets/{wc-tray-CS-1sZRr.js → wc-tray-DFwc7pWZ.js} +2 -2
  68. package/dist/ui/assets/{whisper-engine-ckGpSU4c.js → whisper-engine-CmjvhrOX.js} +1 -1
  69. package/dist/ui/assets/{xai-grok-B7RWdNFP.js → xai-grok-CRiCQ6RZ.js} +1 -1
  70. package/dist/ui/assets/{xai-grok-BjdHQrZi.js → xai-grok-CvIO_i1H.js} +1 -1
  71. package/dist/ui/index.html +3 -3
  72. package/dist/ui/packages/webapp/index.html +3 -3
  73. package/package.json +1 -1
  74. package/dist/ui/assets/dip-BrTZDx_E.js +0 -1
  75. package/dist/ui/assets/esp8266-BRTscDOm.js +0 -1
  76. package/dist/ui/assets/provider-store-access-CL2ZZ09N.js +0 -1
  77. package/dist/ui/assets/provider-store-access-hV_oM0X7.js +0 -1
  78. package/dist/ui/assets/session-freezer-Bnra4H4s.js +0 -1
@@ -1 +1 @@
1
- import{t as e}from"./logger-LESFN7Hj.js";import{a as t,o as n,s as r}from"./kernel-worker-DyWWTo8W.js";import{c as i,s as a}from"./kokoro-engine-GYVOhOZs.js";import{n as o}from"./transformers-env-DhGp-lOp.js";import"./whisper-engine-ckGpSU4c.js";const s=e(`speech:ensure-assets`),c=`onnxruntime-web`,l=`espeak-ng`,u=[a,i],d=`/workspace`,f=()=>typeof chrome<`u`&&!!chrome?.runtime?.id;async function p(e,n){if((await Promise.all(o.map(t=>e.fs.exists(`/workspace/node_modules/onnxruntime-web/dist/${t}`)))).every(Boolean))return n?.({asset:c,phase:`present`}),!1;n?.({asset:c,phase:`staging`});let{errors:r}=await t([c],{fs:e.fs,fetch:e.fetch,cwd:d});if(r.length>0)throw Error(`failed to stage ${c} wasm runtime: ${r[0].error.message}`);return n?.({asset:c,phase:`done`}),!0}async function m(e,n){if((await Promise.all(u.map(t=>e.fs.exists(`/workspace/node_modules/espeak-ng/dist/${t}`)))).every(Boolean))return n?.({asset:l,phase:`present`}),!1;n?.({asset:l,phase:`staging`});let{errors:r}=await t([l],{fs:e.fs,fetch:e.fetch,cwd:d});if(r.length>0)throw Error(`failed to stage ${l} wasm: ${r[0].error.message}`);return n?.({asset:l,phase:`done`}),!0}async function h(e,t){try{return await m(e,t)}catch(e){return s.warn(`optional espeak-ng staging failed; non-English Kokoro voices may fall back`,e),!1}}async function g(e,t,i){let a=r(t,null,d),o=0,s=await n({fetch:e.fetch,fs:e.fs,repo:t,targetDir:a,progress:{onListed:({files:e,totalBytes:n})=>i?.({asset:t,phase:`listing`,filesLoaded:0,filesTotal:e.length,bytesLoaded:0,bytesTotal:n}),onFile:e=>{o+=e.bytes,i?.({asset:t,phase:e.status,file:e.file,filesLoaded:e.index,filesTotal:e.total,bytesLoaded:o})}}});return i?.({asset:t,phase:`done`,filesLoaded:s.files.length,filesTotal:s.files.length,bytesLoaded:o,bytesTotal:o}),{repo:t,downloaded:s.downloaded,skipped:s.skipped}}async function _(e,t){if(f())return{skipped:!0,ortStaged:!1,espeakStaged:!1,repos:[]};let n=await p(e,t),r=e.repos??[`onnx-community/whisper-tiny`,`onnx-community/Kokoro-82M-v1.0-ONNX`],i=[];for(let n of r)i.push(await g(e,n,t));let a=await h(e,t);return s.info(`speech assets staged`,{ortStaged:n,espeakStaged:a,repos:i.length}),{skipped:!1,ortStaged:n,espeakStaged:a,repos:i}}export{_ as ensureSpeechAssetsStaged};
1
+ import{t as e}from"./logger-LESFN7Hj.js";import{a as t,o as n,s as r}from"./kernel-worker-DEUwy4mF.js";import{c as i,s as a}from"./kokoro-engine-dGTwGEQs.js";import{n as o}from"./transformers-env-BTYm60Lj.js";import"./whisper-engine-CmjvhrOX.js";const s=e(`speech:ensure-assets`),c=`onnxruntime-web`,l=`espeak-ng`,u=[a,i],d=`/workspace`,f=()=>typeof chrome<`u`&&!!chrome?.runtime?.id;async function p(e,n){if((await Promise.all(o.map(t=>e.fs.exists(`/workspace/node_modules/onnxruntime-web/dist/${t}`)))).every(Boolean))return n?.({asset:c,phase:`present`}),!1;n?.({asset:c,phase:`staging`});let{errors:r}=await t([c],{fs:e.fs,fetch:e.fetch,cwd:d});if(r.length>0)throw Error(`failed to stage ${c} wasm runtime: ${r[0].error.message}`);return n?.({asset:c,phase:`done`}),!0}async function m(e,n){if((await Promise.all(u.map(t=>e.fs.exists(`/workspace/node_modules/espeak-ng/dist/${t}`)))).every(Boolean))return n?.({asset:l,phase:`present`}),!1;n?.({asset:l,phase:`staging`});let{errors:r}=await t([l],{fs:e.fs,fetch:e.fetch,cwd:d});if(r.length>0)throw Error(`failed to stage ${l} wasm: ${r[0].error.message}`);return n?.({asset:l,phase:`done`}),!0}async function h(e,t){try{return await m(e,t)}catch(e){return s.warn(`optional espeak-ng staging failed; non-English Kokoro voices may fall back`,e),!1}}async function g(e,t,i){let a=r(t,null,d),o=0,s=await n({fetch:e.fetch,fs:e.fs,repo:t,targetDir:a,progress:{onListed:({files:e,totalBytes:n})=>i?.({asset:t,phase:`listing`,filesLoaded:0,filesTotal:e.length,bytesLoaded:0,bytesTotal:n}),onFile:e=>{o+=e.bytes,i?.({asset:t,phase:e.status,file:e.file,filesLoaded:e.index,filesTotal:e.total,bytesLoaded:o})}}});return i?.({asset:t,phase:`done`,filesLoaded:s.files.length,filesTotal:s.files.length,bytesLoaded:o,bytesTotal:o}),{repo:t,downloaded:s.downloaded,skipped:s.skipped}}async function _(e,t){if(f())return{skipped:!0,ortStaged:!1,espeakStaged:!1,repos:[]};let n=await p(e,t),r=e.repos??[`onnx-community/whisper-tiny`,`onnx-community/Kokoro-82M-v1.0-ONNX`],i=[];for(let n of r)i.push(await g(e,n,t));let a=await h(e,t);return s.info(`speech assets staged`,{ortStaged:n,espeakStaged:a,repos:i.length}),{skipped:!1,ortStaged:n,espeakStaged:a,repos:i}}export{_ as ensureSpeechAssetsStaged};
@@ -0,0 +1 @@
1
+ import{t as e}from"./esptool-operations-C5ysasTL.js";export{e as ESP8266ROM};
@@ -1,5 +1,5 @@
1
- import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{d as n,u as r}from"./kernel-worker-DyWWTo8W.js";import{t as i}from"./rom-eeWiO07Z.js";var a=class extends i{constructor(){super(...arguments),this.CHIP_NAME=`ESP8266`,this.CHIP_DETECT_MAGIC_VALUE=[4293968129],this.EFUSE_RD_REG_BASE=1072693328,this.UART_CLKDIV_REG=1610612756,this.UART_CLKDIV_MASK=1048575,this.XTAL_CLK_DIVIDER=2,this.FLASH_WRITE_SIZE=16384,this.BOOTLOADER_FLASH_OFFSET=0,this.UART_DATE_REG_ADDR=0,this.FLASH_SIZES={"512KB":0,"256KB":16,"1MB":32,"2MB":48,"4MB":64,"2MB-c1":80,"4MB-c1":96,"8MB":128,"16MB":144},this.FLASH_FREQUENCY={"80m":15,"40m":0,"26m":1,"20m":2},this.MEMORY_MAP=[[1072693248,1072693264,`DPORT`],[1073643520,1073741824,`DRAM`],[1074790400,1074823168,`IRAM`],[1075843088,1076760592,`IROM`]],this.SPI_REG_BASE=1610613248,this.SPI_USR_OFFS=28,this.SPI_USR1_OFFS=32,this.SPI_USR2_OFFS=36,this.SPI_MOSI_DLEN_OFFS=0,this.SPI_MISO_DLEN_OFFS=0,this.SPI_W0_OFFS=64,this.getChipFeatures=async e=>{let t=[`WiFi`];return await this.getChipDescription(e)==`ESP8285`&&t.push(`Embedded Flash`),t}}async readEfuse(e,t){let n=this.EFUSE_RD_REG_BASE+4*t;return e.debug(`Read efuse `+n),await e.readReg(n)}async getChipDescription(e){let t=await this.readEfuse(e,2);return await this.readEfuse(e,0)&16|t&65536?`ESP8285`:`ESP8266EX`}async getCrystalFreq(e){let t=await e.readReg(this.UART_CLKDIV_REG)&this.UART_CLKDIV_MASK,n=e.transport.baudrate*t/1e6/this.XTAL_CLK_DIVIDER,r;return r=n>33?40:26,Math.abs(r-n)>1&&e.info(`WARNING: Detected crystal freq `+n+`MHz is quite different to normalized freq `+r+`MHz. Unsupported crystal in use?`),r}_d2h(e){let t=(+e).toString(16);return t.length===1?`0`+t:t}async readMac(e){let t=await this.readEfuse(e,0);t>>>=0;let n=await this.readEfuse(e,1);n>>>=0;let r=await this.readEfuse(e,3);r>>>=0;let i=new Uint8Array(6);return r==0?n>>16&255?(n>>16&255)==1?(i[0]=172,i[1]=208,i[2]=116):e.error(`Unknown OUI`):(i[0]=24,i[1]=254,i[2]=52):(i[0]=r>>16&255,i[1]=r>>8&255,i[2]=r&255),i[3]=n>>8&255,i[4]=n&255,i[5]=t>>24&255,this._d2h(i[0])+`:`+this._d2h(i[1])+`:`+this._d2h(i[2])+`:`+this._d2h(i[3])+`:`+this._d2h(i[4])+`:`+this._d2h(i[5])}getEraseSize(e,t){return t}};a.IROM_MAP_START=1075838976,a.IROM_MAP_END=1076887552;var o=class extends Error{};function s(e,t,n=255){let r=e.length%t;if(r!==0){let i=new Uint8Array(t-r).fill(n),a=new Uint8Array(e.length+i.length);return a.set(e),a.set(i,e.length),a}return e}function c(e,t=239){for(let n=0;n<e.length;n++)t^=e[n];return t}function l(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function u(e){return new Promise(t=>setTimeout(t,e))}var d=class{constructor(e,t=!1,n=!0){this.device=e,this.tracing=t,this.slipReaderEnabled=!1,this.baudrate=0,this.traceLog=``,this.lastTraceTime=Date.now(),this.buffer=new Uint8Array,this.onDeviceLostCallback=null,this.SLIP_END=192,this.SLIP_ESC=219,this.SLIP_ESC_END=220,this.SLIP_ESC_ESC=221,this._DTR_state=!1,this.slipReaderEnabled=n}setDeviceLostCallback(e){this.onDeviceLostCallback=e}updateDevice(e){this.device=e,this.trace(`Device reference updated`)}getInfo(){let e=this.device.getInfo();return e.usbVendorId&&e.usbProductId?`WebSerial VendorID 0x${e.usbVendorId.toString(16)} ProductID 0x${e.usbProductId.toString(16)}`:``}getPid(){return this.device.getInfo().usbProductId}trace(e){let t=`${`TRACE ${(Date.now()-this.lastTraceTime).toFixed(3)}`} ${e}`;console.log(t),this.traceLog+=t+`
2
- `}async returnTrace(){try{await navigator.clipboard.writeText(this.traceLog),console.log(`Text copied to clipboard!`)}catch(e){console.error(`Failed to copy text:`,e)}}hexify(e){return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``).padEnd(16,` `)}hexConvert(e,t=!0){if(t&&e.length>16){let t=``,n=e;for(;n.length>0;){let e=n.slice(0,16),r=String.fromCharCode(...e).split(``).map(e=>e===` `||e>=` `&&e<=`~`&&e!==` `?e:`.`).join(``);n=n.slice(16),t+=`\n ${this.hexify(e.slice(0,8))} ${this.hexify(e.slice(8))} | ${r}`}return t}else return this.hexify(e)}slipWriter(e){let t=[];t.push(192);for(let n=0;n<e.length;n++)e[n]===219?t.push(219,221):e[n]===192?t.push(219,220):t.push(e[n]);return t.push(192),new Uint8Array(t)}async write(e){let t=this.slipWriter(e);if(this.device.writable){let e=this.device.writable.getWriter();this.tracing&&this.trace(`Write ${t.length} bytes: ${this.hexConvert(t)}`),await e.write(t),e.releaseLock()}}appendArray(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async readLoop(){for(;this.device.readable;){this.reader=this.device.readable?.getReader();try{let{value:e,done:t}=await this.reader.read();if(t){this.trace(`Serial port done`);break}if(e&&e.length){let t=Uint8Array.from(e);this.buffer=this.appendArray(this.buffer,t)}}catch(e){if(e instanceof Error){if([`BufferOverrunError`,`FramingError`,`BreakError`,`ParityError`].includes(e.name)){this.trace(`Recoverable serial port error: ${e.message}`);continue}this.trace(`Unrecoverable serial port error: ${e.message}`);break}if(e instanceof DOMException){this.onDeviceLostCallback?this.onDeviceLostCallback():this.trace(`Unrecoverable serial port error: ${e.message}`);break}this.trace(`Unrecoverable serial port error: ${e}`);break}finally{this.reader.releaseLock()}}this.trace(`readLoop exited`)}flushInput(){this.buffer=new Uint8Array}async flushOutput(){try{if(this.device.writable){let e=this.device.writable.getWriter();await e.close(),e.releaseLock()}}catch(e){this.trace(`Error while flushing output: ${e}`)}}inWaiting(){return this.buffer.length}peek(){return this.buffer}detectPanicHandler(e){let t=/G?uru Meditation Error: (?:Core \d panic'ed \(([a-zA-Z ]*)\))?/,n=/F?atal exception \(\d+\): (?:([a-zA-Z ]*)?.*epc)?/,r=new TextDecoder(`utf-8`).decode(e),i=r.match(t)||r.match(n);if(i){let e=i[1]||i[2],t=`Guru Meditation Error detected${e?` (${e})`:``}`;throw Error(t)}}async read(e){let t=null,n=!1,r=null;for(;;){let i=Date.now();for(r=new Uint8Array;Date.now()-i<e;)if(this.buffer.length>0){r=this.buffer,this.buffer=new Uint8Array;break}else await u(1);if(!r||r.length===0){let e=t===null?`Serial data stream stopped: Possible serial noise or corruption.`:`No serial data received.`;throw this.tracing&&this.trace(e),Error(e)}this.tracing&&this.trace(`Read ${r.length} bytes: ${this.hexConvert(r)}`);for(let e=0;e<r.length;e++){let i=r[e];if(t===null)if(i===this.SLIP_END)t=new Uint8Array;else{this.tracing&&this.trace(`Read invalid data: ${this.hexConvert(r)}`);let e=this.buffer;throw this.tracing&&this.trace(`Remaining data in serial buffer: ${this.hexConvert(e)}`),this.detectPanicHandler(new Uint8Array([...r,...e||[]])),Error(`Invalid head of packet (0x${i.toString(16)}): Possible serial noise or corruption.`)}else if(n)if(n=!1,i===this.SLIP_ESC_END)t=this.appendArray(t,new Uint8Array([this.SLIP_END]));else if(i===this.SLIP_ESC_ESC)t=this.appendArray(t,new Uint8Array([this.SLIP_ESC]));else{this.tracing&&this.trace(`Read invalid data: ${this.hexConvert(r)}`);let e=this.buffer;throw this.tracing&&this.trace(`Remaining data in serial buffer: ${this.hexConvert(e)}`),this.detectPanicHandler(new Uint8Array([...r,...e||[]])),Error(`Invalid SLIP escape (0xdb, 0x${i.toString(16)})`)}else if(i===this.SLIP_ESC)n=!0;else if(i===this.SLIP_END){if(this.tracing&&this.trace(`Received full packet: ${this.hexConvert(t)}`),e+1<r.length){let t=r.slice(e+1);this.buffer=this.appendArray(t,this.buffer)}return t}else t=this.appendArray(t,new Uint8Array([i]))}}}async rawRead(e,t){let n;try{if(!this.device.readable)return;for(n=this.device.readable.getReader();!t();){let{value:t,done:r}=await n.read();if(r||!t)break;this.tracing&&this.trace(`Read ${t.length} bytes: ${this.hexConvert(t)}`),e(t)}}catch(e){this.trace(`Error reading from serial port: ${e}`),e instanceof Error&&e.name===`NetworkError`&&e.message.includes(`device has been lost`)&&(this.trace(`Device lost detected (NetworkError)`),this.onDeviceLostCallback&&this.onDeviceLostCallback())}finally{n?.releaseLock()}}async setRTS(e){await this.device.setSignals({requestToSend:e}),await this.setDTR(this._DTR_state)}async setDTR(e){this._DTR_state=e,await this.device.setSignals({dataTerminalReady:e})}async connect(e=115200,t={}){await this.device.open({baudRate:e,dataBits:t?.dataBits,stopBits:t?.stopBits,bufferSize:t?.bufferSize,parity:t?.parity,flowControl:t?.flowControl}),this.baudrate=e}async waitForUnlock(e){for(;this.device.readable&&this.device.readable.locked||this.device.writable&&this.device.writable.locked;)await u(e)}async disconnect(){this.device.readable?.locked&&await this.reader?.cancel(),await this.waitForUnlock(400),await this.device.close(),this.reader=void 0}};function f(e){return new Promise(t=>setTimeout(t,e))}var p=class{constructor(e,t){this.resetDelay=t,this.transport=e}async reset(){await this.transport.setDTR(!1),await this.transport.setRTS(!0),await f(100),await this.transport.setDTR(!0),await this.transport.setRTS(!1),await f(this.resetDelay),await this.transport.setDTR(!1)}},m=class{constructor(e){this.transport=e}async reset(){await this.transport.setRTS(!1),await this.transport.setDTR(!1),await f(100),await this.transport.setDTR(!0),await this.transport.setRTS(!1),await f(100),await this.transport.setRTS(!0),await this.transport.setDTR(!1),await this.transport.setRTS(!0),await f(100),await this.transport.setRTS(!1),await this.transport.setDTR(!1)}},h=class{constructor(e,t=!1){this.transport=e,this.usingUsbOtg=t,this.transport=e}async reset(){this.usingUsbOtg?(await f(200),await this.transport.setRTS(!1),await f(200)):(await f(100),await this.transport.setRTS(!1))}};function g(e){let t=[`D`,`R`,`W`],n=e.split(`|`);for(let e of n){let n=e[0],r=e.slice(1);if(!t.includes(n))return!1;if(n===`D`||n===`R`){if(r!==`0`&&r!==`1`)return!1}else if(n===`W`){let e=parseInt(r);if(isNaN(e)||e<=0)return!1}}return!0}var _=class{constructor(e,t){this.transport=e,this.sequenceString=t,this.transport=e}async reset(){let e={D:async e=>await this.transport.setDTR(e),R:async e=>await this.transport.setRTS(e),W:async e=>await f(e)};try{if(!g(this.sequenceString))return;let t=this.sequenceString.split(`|`);for(let n of t){let t=n[0],r=n.slice(1);t===`W`?await e.W(Number(r)):(t===`D`||t===`R`)&&await e[t](r===`1`)}}catch{throw Error(`Invalid custom reset sequence`)}}},v=e(t(((e,t)=>{t.exports=function(e){return atob(e)}}))());async function y(e,t){let n;switch(e){case`ESP32`:n=await import(`./stub_flasher_32-Dh8hmUXW.js`);break;case`ESP32-C2`:n=await import(`./stub_flasher_32c2-CrZruPQ-.js`);break;case`ESP32-C3`:n=await import(`./stub_flasher_32c3-DATkZbTY.js`);break;case`ESP32-C5`:n=await import(`./stub_flasher_32c5-B9wT3AwM.js`);break;case`ESP32-C6`:n=await import(`./stub_flasher_32c6-SMkhzZkf.js`);break;case`ESP32-C61`:n=await import(`./stub_flasher_32c61-r9i57APe.js`);break;case`ESP32-H2`:n=await import(`./stub_flasher_32h2-B3NG8cq-.js`);break;case`ESP32-P4`:n=t&&t<300?await import(`./stub_flasher_32p4rc1-3WH0f-dF.js`):await import(`./stub_flasher_32p4-DfQO64Ur.js`);break;case`ESP32-S2`:n=await import(`./stub_flasher_32s2-CBM9sAmm.js`);break;case`ESP32-S3`:n=await import(`./stub_flasher_32s3-D2W9M8KW.js`);break;case`ESP8266`:n=await import(`./stub_flasher_8266-C20Md_4f.js`);break}if(n)return{bss_start:n.bss_start,data:n.data,data_start:n.data_start,entry:n.entry,text:n.text,text_start:n.text_start,decodedData:b(n.data),decodedText:b(n.text)}}function b(e){let t=(0,v.default)(e).split(``).map(function(e){return e.charCodeAt(0)});return new Uint8Array(t)}function x(e,t){return e+(t-1-e%t)}function S(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}var C=class e{constructor(e,t,n=null,r=0){this.addr=e,this.data=t,this.fileOffs=n,this.flags=r,this.includeInChecksum=!0,this.addr!==0&&this.padToAlignment(4)}copyWithNewAddr(t){return new e(t,this.data,0)}splitImage(t){let n=new e(this.addr,this.data.slice(0,t),0);return this.data=this.data.slice(t),this.addr+=t,this.fileOffs=null,n}toString(){let e=`len 0x${this.data.length.toString(16).padStart(5,`0`)} load 0x${this.addr.toString(16).padStart(8,`0`)}`;return this.fileOffs!==null&&(e+=` file_offs 0x${this.fileOffs.toString(16).padStart(8,`0`)}`),e}getMemoryType(e){return e.ROM_LOADER.MEMORY_MAP.filter(e=>e[0]<=this.addr&&this.addr<e[1]).map(e=>e[2])}padToAlignment(e){this.data=s(this.data,e,0)}},w=class extends C{constructor(e,t,n,r){super(t,n,null,r),this.name=e}toString(){return`${this.name} ${super.toString()}`}},T=class{constructor(e){this.SEG_HEADER_LEN=8,this.SHA256_DIGEST_LEN=32,this.ELF_FLAG_WRITE=1,this.ELF_FLAG_READ=2,this.ELF_FLAG_EXEC=4,this.segments=[],this.entrypoint=0,this.elfSha256=null,this.elfSha256Offset=0,this.padToSize=0,this.flashMode=0,this.flashSizeFreq=0,this.checksum=0,this.datalength=0,this.IROM_ALIGN=0,this.MMU_PAGE_SIZE_CONF=[],this.ROM_LOADER=e}loadCommonHeader(e,t,n){let r=e[t],i=e[t+1];if(this.flashMode=e[t+2],this.flashSizeFreq=e[t+3],this.entrypoint=S(e,t+4),r!==n)throw new o(`Invalid firmware image magic=0x${r.toString(16)}`);return i}verify(){if(this.segments.length>16)throw new o(`Invalid segment count ${this.segments.length} (max 16). Usually this indicates a linker script problem.`)}loadSegment(e,t,n=!1){let r=t,i=S(e,t),a=S(e,t+4);this.warnIfUnusualSegment(i,a,n);let s=e.slice(t+8,t+8+a);if(s.length<a)throw new o(`End of file reading segment 0x${i.toString(16)}, length ${a} (actual length ${s.length})`);let c=new C(i,s,r);return this.segments.push(c),c}warnIfUnusualSegment(e,t,n){n||(e>1075838976||e<1073610752||t>65536)&&console.warn(`WARNING: Suspicious segment 0x${e.toString(16)}, length ${t}`)}maybePatchSegmentData(e,t){let n=e.length;if(this.elfSha256Offset>=t&&this.elfSha256Offset<t+n){let r=this.elfSha256Offset-t;if(r<this.SEG_HEADER_LEN||r+this.SHA256_DIGEST_LEN>n)throw new o(`Cannot place SHA256 digest on segment boundary(elf_sha256_offset=${this.elfSha256Offset}, file_pos=${t}, segment_size=${n})`);let i=r-this.SEG_HEADER_LEN;if(!e.slice(i,i+this.SHA256_DIGEST_LEN).every(e=>e===0))throw new o(`Contents of segment at SHA256 digest offset 0x${this.elfSha256Offset.toString(16)} are not all zero. Refusing to overwrite.`);if(!this.elfSha256||this.elfSha256.length!==this.SHA256_DIGEST_LEN)throw new o(`ELF SHA256 digest is not properly initialized`);let a=e.slice(0,i),s=e.slice(i+this.SHA256_DIGEST_LEN),c=a.length+this.elfSha256.length+s.length,l=new Uint8Array(c);return l.set(a,0),l.set(this.elfSha256,a.length),l.set(s,a.length+this.elfSha256.length),l}return e}saveSegment(e,t,n,r=null){let i=this.maybePatchSegmentData(n.data,t),a=new DataView(e.buffer,t);return a.setUint32(0,n.addr,!0),a.setUint32(4,i.length,!0),e.set(i,t+8),r===null?0:c(i,r)}saveFlashSegment(e,t,n,r=null){if(this.ROM_LOADER.CHIP_NAME===`ESP32`){let e=(t+n.data.length+this.SEG_HEADER_LEN)%this.IROM_ALIGN;if(e<36){let t=new Uint8Array(n.data.length+(36-e));t.set(n.data),t.fill(0,n.data.length),n.data=t}}return this.saveSegment(e,t,n,r)}readChecksum(e,t){return e[x(t,16)]}calculateChecksum(){let e=239;for(let t of this.segments)t.includeInChecksum&&(e=c(t.data,e));return e}appendChecksum(e,t,n){let r=x(t,16);e[r]=n}writeCommonHeader(e,t,n){e[t]=233,e[t+1]=n,e[t+2]=this.flashMode,e[t+3]=this.flashSizeFreq,new DataView(e.buffer,t+4).setUint32(0,this.entrypoint,!0)}isIromAddr(e){return a.IROM_MAP_START<=e&&e<a.IROM_MAP_END}getIromSegment(){let e=this.segments.filter(e=>this.isIromAddr(e.addr));if(e.length>0){if(e.length!==1)throw new o(`Found ${e.length} segments that could be irom0. Bad ELF file?`);return e[0]}return null}getNonIromSegments(){let e=this.getIromSegment();return this.segments.filter(t=>t!==e)}sortSegments(){this.segments.length&&this.segments.sort((e,t)=>e.addr-t.addr)}mergeAdjacentSegments(){if(!this.segments.length)return;let e=[];for(let t=this.segments.length-1;t>0;t--){let n=this.segments[t-1],r=this.segments[t];if(n.getMemoryType(this).join(`,`)===r.getMemoryType(this).join(`,`)&&n.includeInChecksum===r.includeInChecksum&&r.addr===n.addr+n.data.length&&(r.flags&this.ELF_FLAG_EXEC)===(n.flags&this.ELF_FLAG_EXEC)){let e=new Uint8Array(n.data.length+r.data.length);e.set(n.data),e.set(r.data,n.data.length),n.data=e}else e.unshift(r)}e.unshift(this.segments[0]),this.segments=e}setMmuPageSize(e){if(!this.MMU_PAGE_SIZE_CONF&&e!==this.IROM_ALIGN)console.warn(`WARNING: Changing MMU page size is not supported on ${this.ROM_LOADER.CHIP_NAME}! `+(this.IROM_ALIGN===0?``:`Defaulting to ${this.IROM_ALIGN/1024}KB.`));else if(this.MMU_PAGE_SIZE_CONF&&!this.MMU_PAGE_SIZE_CONF.includes(e)){let t=this.MMU_PAGE_SIZE_CONF.map(e=>`${e/1024}KB`).join(`, `);throw new o(`${e} bytes is not a valid ${this.ROM_LOADER.CHIP_NAME} page size, select from ${t}.`)}else this.IROM_ALIGN=e}},E=class extends T{constructor(e,t=null,n=!0,r=!1){super(e),this.securePad=null,this.flashMode=0,this.flashSizeFreq=0,this.version=1,this.WP_PIN_DISABLED=238,this.wpPin=this.WP_PIN_DISABLED,this.clkDrv=0,this.qDrv=0,this.dDrv=0,this.csDrv=0,this.hdDrv=0,this.wpDrv=0,this.chipId=0,this.minRev=0,this.minRevFull=0,this.maxRevFull=0,this.storedDigest=null,this.calcDigest=null,this.dataLength=0,this.IROM_ALIGN=65536,this.ROM_LOADER=e,this.appendDigest=n,this.ramOnlyHeader=r,t!==null&&this.loadFromFile(t)}async loadFromFile(e){let t=e instanceof Uint8Array?e:l(e),n=0,r=this.loadCommonHeader(t,n,233);n+=8,this.loadExtendedHeader(t,n),n+=16;for(let e=0;e<r;e++){let e=this.loadSegment(t,n);n+=8+e.data.length}if(this.checksum=this.readChecksum(t,n),n=x(n,16),this.appendDigest){let e=n;this.storedDigest=t.slice(n,n+this.SHA256_DIGEST_LEN);let r=await crypto.subtle.digest(`SHA-256`,t.slice(0,e));this.calcDigest=new Uint8Array(r),this.dataLength=e-0}this.verify()}isFlashAddr(e){return this.ROM_LOADER.IROM_MAP_START<=e&&e<this.ROM_LOADER.IROM_MAP_END||this.ROM_LOADER.DROM_MAP_START<=e&&e<this.ROM_LOADER.DROM_MAP_END}async save(){let e=0,t=new Uint8Array(1024*1024),n=0;this.writeCommonHeader(t,n,this.segments.length),n+=8,this.saveExtendedHeader(t,n),n+=16;let r=239,i=this.segments.filter(e=>this.isFlashAddr(e.addr)).sort((e,t)=>e.addr-t.addr),a=this.segments.filter(e=>!this.isFlashAddr(e.addr)).sort((e,t)=>e.addr-t.addr);for(let e=0;e<i.length;e++){let t=i[e];if(t instanceof w&&t.name===`.flash.appdesc`){i.splice(e,1),i.unshift(t);break}}for(let e=0;e<a.length;e++){let t=a[e];if(t instanceof w&&t.name===`.dram0.bootdesc`){a.splice(e,1),a.unshift(t);break}}if(i.length>0){let e=i[0].addr;for(let t of i.slice(1)){if(Math.floor(t.addr/this.IROM_ALIGN)===Math.floor(e/this.IROM_ALIGN))throw new o(`Segment loaded at 0x${t.addr.toString(16)} lands in same 64KB flash mapping as segment loaded at 0x${e.toString(16)}. Can't generate binary. Suggest changing linker script or ELF to merge sections.`);e=t.addr}}if(this.ramOnlyHeader){for(let i of a)r=this.saveSegment(t,n,i,r),n+=8+i.data.length,e++;this.appendChecksum(t,n,r),n=x(n,16);for(let a of i.reverse()){let i=this.getAlignmentDataNeeded(a,n);if(i>0){let a=this.ROM_LOADER.BOOTLOADER_FLASH_OFFSET-this.SEG_HEADER_LEN;i<a&&(i+=this.IROM_ALIGN),i-=this.ROM_LOADER.BOOTLOADER_FLASH_OFFSET;let o=new C(0,new Uint8Array(i).fill(0),n);r=this.saveSegment(t,n,o,r),n+=8+i,e++}this.saveFlashSegment(t,n,a),n+=8+a.data.length,e++}}else{for(;i.length>0;){let o=i[0],s=this.getAlignmentDataNeeded(o,n);if(s>0){if(a.length>0&&s>this.SEG_HEADER_LEN){let e=a[0].splitImage(s);a[0].data.length===0&&a.shift(),r=this.saveSegment(t,n,e,r)}else{let e=new C(0,new Uint8Array(s).fill(0),n);r=this.saveSegment(t,n,e,r)}n+=8+s,e++}else{if((n+8)%this.IROM_ALIGN!==o.addr%this.IROM_ALIGN)throw Error(`Flash segment alignment mismatch`);r=this.saveFlashSegment(t,n,o,r),i.shift(),n+=8+o.data.length,e++}}for(let i of a)r=this.saveSegment(t,n,i,r),n+=8+i.data.length,e++}if(this.securePad){if(!this.appendDigest)throw Error(`secure_pad only applies if a SHA-256 digest is also appended to the image`);let i=(n+this.SEG_HEADER_LEN)%this.IROM_ALIGN,a=0;this.securePad===`1`?a=112:this.securePad===`2`&&(a=32);let o=(this.IROM_ALIGN-i-16-a)%this.IROM_ALIGN,s=new C(0,new Uint8Array(o).fill(0),n);r=this.saveSegment(t,n,s,r),n+=8+o,e++}this.ramOnlyHeader||(this.appendChecksum(t,n,r),n=x(n,16));let s=n;if(this.ramOnlyHeader?t[1]=a.length:t[1]=e,this.appendDigest){let e=await crypto.subtle.digest(`SHA-256`,t.slice(0,s)),r=new Uint8Array(e);t.set(r,s),n+=32}if(this.padToSize&&n%this.padToSize!==0){let e=this.padToSize-n%this.padToSize,r=new Uint8Array(e);r.fill(255),t.set(r,n),n+=e}return t}loadExtendedHeader(e,t){let n=new DataView(e.buffer,t);this.wpPin=n.getUint8(0);let r=n.getUint8(1);[this.clkDrv,this.qDrv]=this.splitByte(r);let i=n.getUint8(2);[this.dDrv,this.csDrv]=this.splitByte(i);let a=n.getUint8(3);[this.hdDrv,this.wpDrv]=this.splitByte(a),this.chipId=n.getUint8(4),this.chipId!==this.ROM_LOADER.IMAGE_CHIP_ID&&console.warn(`Unexpected chip id in image. Expected ${this.ROM_LOADER.IMAGE_CHIP_ID} but value was ${this.chipId}. Is this image for a different chip model?`),this.minRev=n.getUint8(5),this.minRevFull=n.getUint16(6,!0),this.maxRevFull=n.getUint16(8,!0);let o=n.getUint8(15);if(o===0||o===1)this.appendDigest=o===1;else throw Error(`Invalid value for append_digest field (0x${o.toString(16)}). Should be 0 or 1.`)}saveExtendedHeader(e,t){let n=new ArrayBuffer(16),r=new DataView(n);r.setUint8(0,this.wpPin),r.setUint8(1,this.joinByte(this.clkDrv,this.qDrv)),r.setUint8(2,this.joinByte(this.dDrv,this.csDrv)),r.setUint8(3,this.joinByte(this.hdDrv,this.wpDrv)),r.setUint8(4,this.ROM_LOADER.IMAGE_CHIP_ID),r.setUint8(5,this.minRev),r.setUint16(6,this.minRevFull,!0),r.setUint16(8,this.maxRevFull,!0);for(let e=9;e<15;e++)r.setUint8(e,0);r.setUint8(15,+!!this.appendDigest),e.set(new Uint8Array(n),t)}splitByte(e){return[e&15,e>>4&15]}joinByte(e,t){return e&15|(t&15)<<4}getAlignmentDataNeeded(e,t){let n=e.addr%this.IROM_ALIGN-this.SEG_HEADER_LEN,r=this.IROM_ALIGN-t%this.IROM_ALIGN+n;return r===0||r===this.IROM_ALIGN?0:(r-=this.SEG_HEADER_LEN,r<0&&(r+=this.IROM_ALIGN),r)}},D=class extends T{constructor(e,t=null){super(e),this.version=1,this.ROM_LOADER=e,this.flashMode=0,this.flashSizeFreq=0,t!==null&&this.loadFromFile(t)}loadFromFile(e){let t=e instanceof Uint8Array?e:l(e),n=0,r=this.loadCommonHeader(t,n,233);n+=8;for(let e=0;e<r;e++){let e=this.loadSegment(t,n);n+=8+e.data.length}this.checksum=this.readChecksum(t,n),this.verify()}defaultOutputName(e){return e+`-`}},O=class e extends T{constructor(e,t=null){super(e),this.version=2,this.ROM_LOADER=e,this.flashMode=0,this.flashSizeFreq=0,t!==null&&this.loadFromFile(t)}async loadFromFile(t){let n=t instanceof Uint8Array?t:l(t),r=0,i=this.loadCommonHeader(n,r,e.IMAGE_V2_MAGIC);r+=8,i!==e.IMAGE_V2_SEGMENT&&console.warn(`Warning: V2 header has unexpected "segment" count ${i} (usually 4)`);let a=this.flashMode,o=this.flashSizeFreq,s=this.entrypoint,c=this.loadSegment(n,r,!0);c.addr=0,c.includeInChecksum=!1,r+=8+c.data.length;let u=this.loadCommonHeader(n,r,233);r+=8,a!==this.flashMode&&console.warn(`WARNING: Flash mode value in first header (0x${a.toString(16)}) disagrees with second (0x${this.flashMode.toString(16)}). Using second value.`),o!==this.flashSizeFreq&&console.warn(`WARNING: Flash size/freq value in first header (0x${o.toString(16)}) disagrees with second (0x${this.flashSizeFreq.toString(16)}). Using second value.`),s!==this.entrypoint&&console.warn(`WARNING: Entrypoint address in first header (0x${s.toString(16)}) disagrees with second header (0x${this.entrypoint.toString(16)}). Using second value.`);for(let e=0;e<u;e++){let e=this.loadSegment(n,r);r+=8+e.data.length}this.checksum=this.readChecksum(n,r),this.verify()}defaultOutputName(e){let t=this.getIromSegment(),n=0;return t!==null&&(n=t.addr-a.IROM_MAP_START),`${e.replace(/\.[^/.]+$/,``)}-0x${(n&-4096).toString(16).padStart(5,`0`)}.bin`}};O.IMAGE_V2_MAGIC=234,O.IMAGE_V2_SEGMENT=4;var k=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},A=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},j=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},M=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.MMU_PAGE_SIZE_CONF=[16384,32768,65536],this.ROM_LOADER=e}},N=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.MMU_PAGE_SIZE_CONF=[8192,16384,32768,65536],this.ROM_LOADER=e}},P=class extends N{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},F=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},I=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},L=class extends N{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}};async function R(e,t){let n=t instanceof Uint8Array?t:l(t),r=e.CHIP_NAME.toLowerCase().replace(/[-()]/g,``),i;if(r!==`esp8266`)switch(r){case`esp32`:i=E;break;case`esp32s2`:i=k;break;case`esp32s3`:i=A;break;case`esp32c3`:i=j;break;case`esp32c2`:i=M;break;case`esp32c6`:i=N;break;case`esp32c61`:i=P;break;case`esp32c5`:i=F;break;case`esp32h2`:i=L;break;case`esp32p4`:i=I;break;default:throw new o(`Unsupported chip name: ${r}`)}else{let e=n[0];if(e===233)i=D;else if(e===O.IMAGE_V2_MAGIC)i=O;else throw new o(`Invalid image magic number: ${e}`)}let a=new i(e),s=a;if(typeof s.loadFromFile==`function`){let e=s.loadFromFile(n);e instanceof Promise&&await e}return a}async function z(e){switch(e){case 15736195:{let{ESP32ROM:e}=await import(`./esp32-D9ZurRwV.js`).then(e=>e.n);return new e}case 203546735:case 1867591791:case 2084675695:{let{ESP32C2ROM:e}=await import(`./esp32c2-F0yCL7ES.js`);return new e}case 1763790959:case 456216687:case 1216438383:case 1130455151:{let{ESP32C3ROM:e}=await import(`./esp32c3-wVAODszM.js`).then(e=>e.n);return new e}case 752910447:{let{ESP32C6ROM:e}=await import(`./esp32c6-IwoGEmKl.js`);return new e}case 606167151:case 871374959:case 1333878895:{let{ESP32C61ROM:e}=await import(`./esp32c61-BJScMw70.js`);return new e}case 285294703:case 1675706479:case 1607549039:{let{ESP32C5ROM:e}=await import(`./esp32c5-ChTI-uFN.js`);return new e}case 3619110528:case 2548236392:{let{ESP32H2ROM:e}=await import(`./esp32h2-YosZEx9u.js`);return new e}case 9:{let{ESP32S3ROM:e}=await import(`./esp32s3-PqxbnxPZ.js`);return new e}case 1990:{let{ESP32S2ROM:e}=await import(`./esp32s2-Dhlhu16A.js`);return new e}case 4293968129:{let{ESP8266ROM:e}=await import(`./esp8266-BRTscDOm.js`);return new e}case 0:case 182303440:case 117676761:{let{ESP32P4ROM:e}=await import(`./esp32p4-BSe822vW.js`);return new e}default:return null}}var B=class{constructor(e){this.ESP_RAM_BLOCK=6144,this.ESP_FLASH_BEGIN=2,this.ESP_FLASH_DATA=3,this.ESP_FLASH_END=4,this.ESP_MEM_BEGIN=5,this.ESP_MEM_END=6,this.ESP_MEM_DATA=7,this.ESP_WRITE_REG=9,this.ESP_READ_REG=10,this.ESP_SPI_ATTACH=13,this.ESP_CHANGE_BAUDRATE=15,this.ESP_FLASH_DEFL_BEGIN=16,this.ESP_FLASH_DEFL_DATA=17,this.ESP_FLASH_DEFL_END=18,this.ESP_SPI_FLASH_MD5=19,this.ESP_ERASE_FLASH=208,this.ESP_ERASE_REGION=209,this.ESP_READ_FLASH=210,this.ESP_RUN_USER_CODE=211,this.ESP_IMAGE_MAGIC=233,this.ESP_CHECKSUM_MAGIC=239,this.ROM_INVALID_RECV_MSG=5,this.DEFAULT_TIMEOUT=3e3,this.ERASE_REGION_TIMEOUT_PER_MB=3e4,this.ERASE_WRITE_TIMEOUT_PER_MB=4e4,this.MD5_TIMEOUT_PER_MB=8e3,this.CHIP_ERASE_TIMEOUT=12e4,this.FLASH_READ_TIMEOUT=1e5,this.MAX_TIMEOUT=this.CHIP_ERASE_TIMEOUT*2,this.SPI_ADDR_REG_MSB=!0,this.CHIP_DETECT_MAGIC_REG_ADDR=1073745920,this.DETECTED_FLASH_SIZES={18:`256KB`,19:`512KB`,20:`1MB`,21:`2MB`,22:`4MB`,23:`8MB`,24:`16MB`,25:`32MB`,26:`64MB`,27:`128MB`,28:`256MB`,32:`64MB`,33:`128MB`,34:`256MB`,50:`256KB`,51:`512KB`,52:`1MB`,53:`2MB`,54:`4MB`,55:`8MB`,56:`16MB`,57:`32MB`,58:`64MB`},this.USB_JTAG_SERIAL_PID=4097,this.romBaudrate=115200,this.debugLogging=!1,this.syncStubDetected=!1,this.IS_STUB=!1,this.FLASH_WRITE_SIZE=16384,this.transport=e.transport,this.baudrate=e.baudrate,this.resetConstructors={classicReset:(e,t)=>new p(e,t),customReset:(e,t)=>new _(e,t),hardReset:(e,t)=>new h(e,t),usbJTAGSerialReset:e=>new m(e)},e.serialOptions&&(this.serialOptions=e.serialOptions),e.terminal&&(this.terminal=e.terminal,this.terminal.clean()),e.debugLogging!==void 0&&(this.debugLogging=e.debugLogging),e.port&&(this.transport=new d(e.port)),e.enableTracing!==void 0&&(this.transport.tracing=e.enableTracing),e.resetConstructors?.classicReset&&(this.resetConstructors.classicReset=e.resetConstructors?.classicReset),e.resetConstructors?.customReset&&(this.resetConstructors.customReset=e.resetConstructors?.customReset),e.resetConstructors?.hardReset&&(this.resetConstructors.hardReset=e.resetConstructors?.hardReset),e.resetConstructors?.usbJTAGSerialReset&&(this.resetConstructors.usbJTAGSerialReset=e.resetConstructors?.usbJTAGSerialReset),this.info(`esptool.js`),this.info(`Serial port `+this.transport.getInfo())}write(e,t=!0){this.terminal?t?this.terminal.writeLine(e):this.terminal.write(e):console.log(e)}error(e,t=!0){this.write(`Error: ${e}`,t)}info(e,t=!0){this.write(e,t)}debug(e,t=!0){this.debugLogging&&this.write(`Debug: ${e}`,t)}_shortToBytearray(e){return new Uint8Array([e&255,e>>8&255])}_intToByteArray(e){return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}_byteArrayToShort(e,t){return e|t>>8}_byteArrayToInt(e,t,n,r){return e|t<<8|n<<16|r<<24}_appendBuffer(e,t){let n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}_appendArray(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}ui8ToBstr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}bstrToUi8(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}async readPacket(e=null,t=this.DEFAULT_TIMEOUT){for(let n=0;n<100;n++){let n=await this.transport.read(t);if(!n||n.length<8)continue;let r=n[0];if(r!==1)continue;let i=n[1],a=this._byteArrayToInt(n[4],n[5],n[6],n[7]),s=n.slice(8);if(r==1){if(e==null||i==e)return[a,s];if(s[0]!=0&&s[1]==this.ROM_INVALID_RECV_MSG)throw this.transport.flushInput(),new o(`unsupported command error`)}}throw new o(`invalid response`)}async command(e=null,t=new Uint8Array,n=0,r=!0,i=this.DEFAULT_TIMEOUT){if(e!=null){this.transport.tracing&&this.transport.trace(`command op:0x${e.toString(16).padStart(2,`0`)} data len=${t.length} wait_response=${+!!r} timeout=${(i/1e3).toFixed(3)} data=${this.transport.hexConvert(t)}`);let a=new Uint8Array(8+t.length);a[0]=0,a[1]=e,a[2]=this._shortToBytearray(t.length)[0],a[3]=this._shortToBytearray(t.length)[1],a[4]=this._intToByteArray(n)[0],a[5]=this._intToByteArray(n)[1],a[6]=this._intToByteArray(n)[2],a[7]=this._intToByteArray(n)[3];let o;for(o=0;o<t.length;o++)a[8+o]=t[o];await this.transport.write(a)}return r?this.readPacket(e,i):[0,new Uint8Array]}async readReg(e,t=this.DEFAULT_TIMEOUT){this.debug(`Read Register:${this.toHex(e)}`);let n=this._intToByteArray(e),r=await this.command(this.ESP_READ_REG,n,void 0,void 0,t);return this.debug(`Read Register Value:${r[0]}`),r[0]}async writeReg(e,t,n=4294967295,r=0,i=0){let a=this._appendArray(this._intToByteArray(e),this._intToByteArray(t));a=this._appendArray(a,this._intToByteArray(n)),a=this._appendArray(a,this._intToByteArray(r)),i>0&&(a=this._appendArray(a,this._intToByteArray(this.chip.UART_DATE_REG_ADDR)),a=this._appendArray(a,this._intToByteArray(0)),a=this._appendArray(a,this._intToByteArray(0)),a=this._appendArray(a,this._intToByteArray(i))),await this.checkCommand(`write target memory`,this.ESP_WRITE_REG,a)}async sync(){this.debug(`Sync`);let e=new Uint8Array(36),t;for(e[0]=7,e[1]=7,e[2]=18,e[3]=32,t=0;t<32;t++)e[4+t]=85;try{let t=await this.command(8,e,void 0,void 0,100);this.syncStubDetected=t[0]===0;for(let e=0;e<7;e++)t=await this.readPacket(8,100),this.syncStubDetected=this.syncStubDetected&&t[0]===0;return t}catch(e){throw this.debug(`Sync err `+e),e}}async _connectAttempt(e=`default_reset`,t){this.debug(`_connect_attempt `+e),t&&await t.reset();let n=this.transport.peek(),r=Array.from(n,e=>String.fromCharCode(e)).join(``).match(/boot:(0x[0-9a-fA-F]+)([\s\S]*?waiting for download)?/),i=!1,a=``,o=!1;r&&(i=!0,a=r[1],o=!!r[2]),this.debug(`bootMode:${a} downloadMode:${o}`);let s=``;for(let e=0;e<5;e++)try{this.debug(`Sync connect attempt ${e}`),this.transport.flushInput();let t=await this.sync();return this.debug(t[0].toString()),`success`}catch(e){this.debug(`Error at sync ${e}`),s=e instanceof Error?e.message:typeof e==`string`?e:JSON.stringify(e)}return i&&(s=`Wrong boot mode detected (${a}).
1
+ import{i as e,t}from"./rolldown-runtime-aKtaBQYM.js";import{d as n,u as r}from"./kernel-worker-DEUwy4mF.js";import{t as i}from"./rom-eeWiO07Z.js";var a=class extends i{constructor(){super(...arguments),this.CHIP_NAME=`ESP8266`,this.CHIP_DETECT_MAGIC_VALUE=[4293968129],this.EFUSE_RD_REG_BASE=1072693328,this.UART_CLKDIV_REG=1610612756,this.UART_CLKDIV_MASK=1048575,this.XTAL_CLK_DIVIDER=2,this.FLASH_WRITE_SIZE=16384,this.BOOTLOADER_FLASH_OFFSET=0,this.UART_DATE_REG_ADDR=0,this.FLASH_SIZES={"512KB":0,"256KB":16,"1MB":32,"2MB":48,"4MB":64,"2MB-c1":80,"4MB-c1":96,"8MB":128,"16MB":144},this.FLASH_FREQUENCY={"80m":15,"40m":0,"26m":1,"20m":2},this.MEMORY_MAP=[[1072693248,1072693264,`DPORT`],[1073643520,1073741824,`DRAM`],[1074790400,1074823168,`IRAM`],[1075843088,1076760592,`IROM`]],this.SPI_REG_BASE=1610613248,this.SPI_USR_OFFS=28,this.SPI_USR1_OFFS=32,this.SPI_USR2_OFFS=36,this.SPI_MOSI_DLEN_OFFS=0,this.SPI_MISO_DLEN_OFFS=0,this.SPI_W0_OFFS=64,this.getChipFeatures=async e=>{let t=[`WiFi`];return await this.getChipDescription(e)==`ESP8285`&&t.push(`Embedded Flash`),t}}async readEfuse(e,t){let n=this.EFUSE_RD_REG_BASE+4*t;return e.debug(`Read efuse `+n),await e.readReg(n)}async getChipDescription(e){let t=await this.readEfuse(e,2);return await this.readEfuse(e,0)&16|t&65536?`ESP8285`:`ESP8266EX`}async getCrystalFreq(e){let t=await e.readReg(this.UART_CLKDIV_REG)&this.UART_CLKDIV_MASK,n=e.transport.baudrate*t/1e6/this.XTAL_CLK_DIVIDER,r;return r=n>33?40:26,Math.abs(r-n)>1&&e.info(`WARNING: Detected crystal freq `+n+`MHz is quite different to normalized freq `+r+`MHz. Unsupported crystal in use?`),r}_d2h(e){let t=(+e).toString(16);return t.length===1?`0`+t:t}async readMac(e){let t=await this.readEfuse(e,0);t>>>=0;let n=await this.readEfuse(e,1);n>>>=0;let r=await this.readEfuse(e,3);r>>>=0;let i=new Uint8Array(6);return r==0?n>>16&255?(n>>16&255)==1?(i[0]=172,i[1]=208,i[2]=116):e.error(`Unknown OUI`):(i[0]=24,i[1]=254,i[2]=52):(i[0]=r>>16&255,i[1]=r>>8&255,i[2]=r&255),i[3]=n>>8&255,i[4]=n&255,i[5]=t>>24&255,this._d2h(i[0])+`:`+this._d2h(i[1])+`:`+this._d2h(i[2])+`:`+this._d2h(i[3])+`:`+this._d2h(i[4])+`:`+this._d2h(i[5])}getEraseSize(e,t){return t}};a.IROM_MAP_START=1075838976,a.IROM_MAP_END=1076887552;var o=class extends Error{};function s(e,t,n=255){let r=e.length%t;if(r!==0){let i=new Uint8Array(t-r).fill(n),a=new Uint8Array(e.length+i.length);return a.set(e),a.set(i,e.length),a}return e}function c(e,t=239){for(let n=0;n<e.length;n++)t^=e[n];return t}function l(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function u(e){return new Promise(t=>setTimeout(t,e))}var d=class{constructor(e,t=!1,n=!0){this.device=e,this.tracing=t,this.slipReaderEnabled=!1,this.baudrate=0,this.traceLog=``,this.lastTraceTime=Date.now(),this.buffer=new Uint8Array,this.onDeviceLostCallback=null,this.SLIP_END=192,this.SLIP_ESC=219,this.SLIP_ESC_END=220,this.SLIP_ESC_ESC=221,this._DTR_state=!1,this.slipReaderEnabled=n}setDeviceLostCallback(e){this.onDeviceLostCallback=e}updateDevice(e){this.device=e,this.trace(`Device reference updated`)}getInfo(){let e=this.device.getInfo();return e.usbVendorId&&e.usbProductId?`WebSerial VendorID 0x${e.usbVendorId.toString(16)} ProductID 0x${e.usbProductId.toString(16)}`:``}getPid(){return this.device.getInfo().usbProductId}trace(e){let t=`${`TRACE ${(Date.now()-this.lastTraceTime).toFixed(3)}`} ${e}`;console.log(t),this.traceLog+=t+`
2
+ `}async returnTrace(){try{await navigator.clipboard.writeText(this.traceLog),console.log(`Text copied to clipboard!`)}catch(e){console.error(`Failed to copy text:`,e)}}hexify(e){return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``).padEnd(16,` `)}hexConvert(e,t=!0){if(t&&e.length>16){let t=``,n=e;for(;n.length>0;){let e=n.slice(0,16),r=String.fromCharCode(...e).split(``).map(e=>e===` `||e>=` `&&e<=`~`&&e!==` `?e:`.`).join(``);n=n.slice(16),t+=`\n ${this.hexify(e.slice(0,8))} ${this.hexify(e.slice(8))} | ${r}`}return t}else return this.hexify(e)}slipWriter(e){let t=[];t.push(192);for(let n=0;n<e.length;n++)e[n]===219?t.push(219,221):e[n]===192?t.push(219,220):t.push(e[n]);return t.push(192),new Uint8Array(t)}async write(e){let t=this.slipWriter(e);if(this.device.writable){let e=this.device.writable.getWriter();this.tracing&&this.trace(`Write ${t.length} bytes: ${this.hexConvert(t)}`),await e.write(t),e.releaseLock()}}appendArray(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async readLoop(){for(;this.device.readable;){this.reader=this.device.readable?.getReader();try{let{value:e,done:t}=await this.reader.read();if(t){this.trace(`Serial port done`);break}if(e&&e.length){let t=Uint8Array.from(e);this.buffer=this.appendArray(this.buffer,t)}}catch(e){if(e instanceof Error){if([`BufferOverrunError`,`FramingError`,`BreakError`,`ParityError`].includes(e.name)){this.trace(`Recoverable serial port error: ${e.message}`);continue}this.trace(`Unrecoverable serial port error: ${e.message}`);break}if(e instanceof DOMException){this.onDeviceLostCallback?this.onDeviceLostCallback():this.trace(`Unrecoverable serial port error: ${e.message}`);break}this.trace(`Unrecoverable serial port error: ${e}`);break}finally{this.reader.releaseLock()}}this.trace(`readLoop exited`)}flushInput(){this.buffer=new Uint8Array}async flushOutput(){try{if(this.device.writable){let e=this.device.writable.getWriter();await e.close(),e.releaseLock()}}catch(e){this.trace(`Error while flushing output: ${e}`)}}inWaiting(){return this.buffer.length}peek(){return this.buffer}detectPanicHandler(e){let t=/G?uru Meditation Error: (?:Core \d panic'ed \(([a-zA-Z ]*)\))?/,n=/F?atal exception \(\d+\): (?:([a-zA-Z ]*)?.*epc)?/,r=new TextDecoder(`utf-8`).decode(e),i=r.match(t)||r.match(n);if(i){let e=i[1]||i[2],t=`Guru Meditation Error detected${e?` (${e})`:``}`;throw Error(t)}}async read(e){let t=null,n=!1,r=null;for(;;){let i=Date.now();for(r=new Uint8Array;Date.now()-i<e;)if(this.buffer.length>0){r=this.buffer,this.buffer=new Uint8Array;break}else await u(1);if(!r||r.length===0){let e=t===null?`Serial data stream stopped: Possible serial noise or corruption.`:`No serial data received.`;throw this.tracing&&this.trace(e),Error(e)}this.tracing&&this.trace(`Read ${r.length} bytes: ${this.hexConvert(r)}`);for(let e=0;e<r.length;e++){let i=r[e];if(t===null)if(i===this.SLIP_END)t=new Uint8Array;else{this.tracing&&this.trace(`Read invalid data: ${this.hexConvert(r)}`);let e=this.buffer;throw this.tracing&&this.trace(`Remaining data in serial buffer: ${this.hexConvert(e)}`),this.detectPanicHandler(new Uint8Array([...r,...e||[]])),Error(`Invalid head of packet (0x${i.toString(16)}): Possible serial noise or corruption.`)}else if(n)if(n=!1,i===this.SLIP_ESC_END)t=this.appendArray(t,new Uint8Array([this.SLIP_END]));else if(i===this.SLIP_ESC_ESC)t=this.appendArray(t,new Uint8Array([this.SLIP_ESC]));else{this.tracing&&this.trace(`Read invalid data: ${this.hexConvert(r)}`);let e=this.buffer;throw this.tracing&&this.trace(`Remaining data in serial buffer: ${this.hexConvert(e)}`),this.detectPanicHandler(new Uint8Array([...r,...e||[]])),Error(`Invalid SLIP escape (0xdb, 0x${i.toString(16)})`)}else if(i===this.SLIP_ESC)n=!0;else if(i===this.SLIP_END){if(this.tracing&&this.trace(`Received full packet: ${this.hexConvert(t)}`),e+1<r.length){let t=r.slice(e+1);this.buffer=this.appendArray(t,this.buffer)}return t}else t=this.appendArray(t,new Uint8Array([i]))}}}async rawRead(e,t){let n;try{if(!this.device.readable)return;for(n=this.device.readable.getReader();!t();){let{value:t,done:r}=await n.read();if(r||!t)break;this.tracing&&this.trace(`Read ${t.length} bytes: ${this.hexConvert(t)}`),e(t)}}catch(e){this.trace(`Error reading from serial port: ${e}`),e instanceof Error&&e.name===`NetworkError`&&e.message.includes(`device has been lost`)&&(this.trace(`Device lost detected (NetworkError)`),this.onDeviceLostCallback&&this.onDeviceLostCallback())}finally{n?.releaseLock()}}async setRTS(e){await this.device.setSignals({requestToSend:e}),await this.setDTR(this._DTR_state)}async setDTR(e){this._DTR_state=e,await this.device.setSignals({dataTerminalReady:e})}async connect(e=115200,t={}){await this.device.open({baudRate:e,dataBits:t?.dataBits,stopBits:t?.stopBits,bufferSize:t?.bufferSize,parity:t?.parity,flowControl:t?.flowControl}),this.baudrate=e}async waitForUnlock(e){for(;this.device.readable&&this.device.readable.locked||this.device.writable&&this.device.writable.locked;)await u(e)}async disconnect(){this.device.readable?.locked&&await this.reader?.cancel(),await this.waitForUnlock(400),await this.device.close(),this.reader=void 0}};function f(e){return new Promise(t=>setTimeout(t,e))}var p=class{constructor(e,t){this.resetDelay=t,this.transport=e}async reset(){await this.transport.setDTR(!1),await this.transport.setRTS(!0),await f(100),await this.transport.setDTR(!0),await this.transport.setRTS(!1),await f(this.resetDelay),await this.transport.setDTR(!1)}},m=class{constructor(e){this.transport=e}async reset(){await this.transport.setRTS(!1),await this.transport.setDTR(!1),await f(100),await this.transport.setDTR(!0),await this.transport.setRTS(!1),await f(100),await this.transport.setRTS(!0),await this.transport.setDTR(!1),await this.transport.setRTS(!0),await f(100),await this.transport.setRTS(!1),await this.transport.setDTR(!1)}},h=class{constructor(e,t=!1){this.transport=e,this.usingUsbOtg=t,this.transport=e}async reset(){this.usingUsbOtg?(await f(200),await this.transport.setRTS(!1),await f(200)):(await f(100),await this.transport.setRTS(!1))}};function g(e){let t=[`D`,`R`,`W`],n=e.split(`|`);for(let e of n){let n=e[0],r=e.slice(1);if(!t.includes(n))return!1;if(n===`D`||n===`R`){if(r!==`0`&&r!==`1`)return!1}else if(n===`W`){let e=parseInt(r);if(isNaN(e)||e<=0)return!1}}return!0}var _=class{constructor(e,t){this.transport=e,this.sequenceString=t,this.transport=e}async reset(){let e={D:async e=>await this.transport.setDTR(e),R:async e=>await this.transport.setRTS(e),W:async e=>await f(e)};try{if(!g(this.sequenceString))return;let t=this.sequenceString.split(`|`);for(let n of t){let t=n[0],r=n.slice(1);t===`W`?await e.W(Number(r)):(t===`D`||t===`R`)&&await e[t](r===`1`)}}catch{throw Error(`Invalid custom reset sequence`)}}},v=e(t(((e,t)=>{t.exports=function(e){return atob(e)}}))());async function y(e,t){let n;switch(e){case`ESP32`:n=await import(`./stub_flasher_32-Dh8hmUXW.js`);break;case`ESP32-C2`:n=await import(`./stub_flasher_32c2-CrZruPQ-.js`);break;case`ESP32-C3`:n=await import(`./stub_flasher_32c3-DATkZbTY.js`);break;case`ESP32-C5`:n=await import(`./stub_flasher_32c5-B9wT3AwM.js`);break;case`ESP32-C6`:n=await import(`./stub_flasher_32c6-SMkhzZkf.js`);break;case`ESP32-C61`:n=await import(`./stub_flasher_32c61-r9i57APe.js`);break;case`ESP32-H2`:n=await import(`./stub_flasher_32h2-B3NG8cq-.js`);break;case`ESP32-P4`:n=t&&t<300?await import(`./stub_flasher_32p4rc1-3WH0f-dF.js`):await import(`./stub_flasher_32p4-DfQO64Ur.js`);break;case`ESP32-S2`:n=await import(`./stub_flasher_32s2-CBM9sAmm.js`);break;case`ESP32-S3`:n=await import(`./stub_flasher_32s3-D2W9M8KW.js`);break;case`ESP8266`:n=await import(`./stub_flasher_8266-C20Md_4f.js`);break}if(n)return{bss_start:n.bss_start,data:n.data,data_start:n.data_start,entry:n.entry,text:n.text,text_start:n.text_start,decodedData:b(n.data),decodedText:b(n.text)}}function b(e){let t=(0,v.default)(e).split(``).map(function(e){return e.charCodeAt(0)});return new Uint8Array(t)}function x(e,t){return e+(t-1-e%t)}function S(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24}var C=class e{constructor(e,t,n=null,r=0){this.addr=e,this.data=t,this.fileOffs=n,this.flags=r,this.includeInChecksum=!0,this.addr!==0&&this.padToAlignment(4)}copyWithNewAddr(t){return new e(t,this.data,0)}splitImage(t){let n=new e(this.addr,this.data.slice(0,t),0);return this.data=this.data.slice(t),this.addr+=t,this.fileOffs=null,n}toString(){let e=`len 0x${this.data.length.toString(16).padStart(5,`0`)} load 0x${this.addr.toString(16).padStart(8,`0`)}`;return this.fileOffs!==null&&(e+=` file_offs 0x${this.fileOffs.toString(16).padStart(8,`0`)}`),e}getMemoryType(e){return e.ROM_LOADER.MEMORY_MAP.filter(e=>e[0]<=this.addr&&this.addr<e[1]).map(e=>e[2])}padToAlignment(e){this.data=s(this.data,e,0)}},w=class extends C{constructor(e,t,n,r){super(t,n,null,r),this.name=e}toString(){return`${this.name} ${super.toString()}`}},T=class{constructor(e){this.SEG_HEADER_LEN=8,this.SHA256_DIGEST_LEN=32,this.ELF_FLAG_WRITE=1,this.ELF_FLAG_READ=2,this.ELF_FLAG_EXEC=4,this.segments=[],this.entrypoint=0,this.elfSha256=null,this.elfSha256Offset=0,this.padToSize=0,this.flashMode=0,this.flashSizeFreq=0,this.checksum=0,this.datalength=0,this.IROM_ALIGN=0,this.MMU_PAGE_SIZE_CONF=[],this.ROM_LOADER=e}loadCommonHeader(e,t,n){let r=e[t],i=e[t+1];if(this.flashMode=e[t+2],this.flashSizeFreq=e[t+3],this.entrypoint=S(e,t+4),r!==n)throw new o(`Invalid firmware image magic=0x${r.toString(16)}`);return i}verify(){if(this.segments.length>16)throw new o(`Invalid segment count ${this.segments.length} (max 16). Usually this indicates a linker script problem.`)}loadSegment(e,t,n=!1){let r=t,i=S(e,t),a=S(e,t+4);this.warnIfUnusualSegment(i,a,n);let s=e.slice(t+8,t+8+a);if(s.length<a)throw new o(`End of file reading segment 0x${i.toString(16)}, length ${a} (actual length ${s.length})`);let c=new C(i,s,r);return this.segments.push(c),c}warnIfUnusualSegment(e,t,n){n||(e>1075838976||e<1073610752||t>65536)&&console.warn(`WARNING: Suspicious segment 0x${e.toString(16)}, length ${t}`)}maybePatchSegmentData(e,t){let n=e.length;if(this.elfSha256Offset>=t&&this.elfSha256Offset<t+n){let r=this.elfSha256Offset-t;if(r<this.SEG_HEADER_LEN||r+this.SHA256_DIGEST_LEN>n)throw new o(`Cannot place SHA256 digest on segment boundary(elf_sha256_offset=${this.elfSha256Offset}, file_pos=${t}, segment_size=${n})`);let i=r-this.SEG_HEADER_LEN;if(!e.slice(i,i+this.SHA256_DIGEST_LEN).every(e=>e===0))throw new o(`Contents of segment at SHA256 digest offset 0x${this.elfSha256Offset.toString(16)} are not all zero. Refusing to overwrite.`);if(!this.elfSha256||this.elfSha256.length!==this.SHA256_DIGEST_LEN)throw new o(`ELF SHA256 digest is not properly initialized`);let a=e.slice(0,i),s=e.slice(i+this.SHA256_DIGEST_LEN),c=a.length+this.elfSha256.length+s.length,l=new Uint8Array(c);return l.set(a,0),l.set(this.elfSha256,a.length),l.set(s,a.length+this.elfSha256.length),l}return e}saveSegment(e,t,n,r=null){let i=this.maybePatchSegmentData(n.data,t),a=new DataView(e.buffer,t);return a.setUint32(0,n.addr,!0),a.setUint32(4,i.length,!0),e.set(i,t+8),r===null?0:c(i,r)}saveFlashSegment(e,t,n,r=null){if(this.ROM_LOADER.CHIP_NAME===`ESP32`){let e=(t+n.data.length+this.SEG_HEADER_LEN)%this.IROM_ALIGN;if(e<36){let t=new Uint8Array(n.data.length+(36-e));t.set(n.data),t.fill(0,n.data.length),n.data=t}}return this.saveSegment(e,t,n,r)}readChecksum(e,t){return e[x(t,16)]}calculateChecksum(){let e=239;for(let t of this.segments)t.includeInChecksum&&(e=c(t.data,e));return e}appendChecksum(e,t,n){let r=x(t,16);e[r]=n}writeCommonHeader(e,t,n){e[t]=233,e[t+1]=n,e[t+2]=this.flashMode,e[t+3]=this.flashSizeFreq,new DataView(e.buffer,t+4).setUint32(0,this.entrypoint,!0)}isIromAddr(e){return a.IROM_MAP_START<=e&&e<a.IROM_MAP_END}getIromSegment(){let e=this.segments.filter(e=>this.isIromAddr(e.addr));if(e.length>0){if(e.length!==1)throw new o(`Found ${e.length} segments that could be irom0. Bad ELF file?`);return e[0]}return null}getNonIromSegments(){let e=this.getIromSegment();return this.segments.filter(t=>t!==e)}sortSegments(){this.segments.length&&this.segments.sort((e,t)=>e.addr-t.addr)}mergeAdjacentSegments(){if(!this.segments.length)return;let e=[];for(let t=this.segments.length-1;t>0;t--){let n=this.segments[t-1],r=this.segments[t];if(n.getMemoryType(this).join(`,`)===r.getMemoryType(this).join(`,`)&&n.includeInChecksum===r.includeInChecksum&&r.addr===n.addr+n.data.length&&(r.flags&this.ELF_FLAG_EXEC)===(n.flags&this.ELF_FLAG_EXEC)){let e=new Uint8Array(n.data.length+r.data.length);e.set(n.data),e.set(r.data,n.data.length),n.data=e}else e.unshift(r)}e.unshift(this.segments[0]),this.segments=e}setMmuPageSize(e){if(!this.MMU_PAGE_SIZE_CONF&&e!==this.IROM_ALIGN)console.warn(`WARNING: Changing MMU page size is not supported on ${this.ROM_LOADER.CHIP_NAME}! `+(this.IROM_ALIGN===0?``:`Defaulting to ${this.IROM_ALIGN/1024}KB.`));else if(this.MMU_PAGE_SIZE_CONF&&!this.MMU_PAGE_SIZE_CONF.includes(e)){let t=this.MMU_PAGE_SIZE_CONF.map(e=>`${e/1024}KB`).join(`, `);throw new o(`${e} bytes is not a valid ${this.ROM_LOADER.CHIP_NAME} page size, select from ${t}.`)}else this.IROM_ALIGN=e}},E=class extends T{constructor(e,t=null,n=!0,r=!1){super(e),this.securePad=null,this.flashMode=0,this.flashSizeFreq=0,this.version=1,this.WP_PIN_DISABLED=238,this.wpPin=this.WP_PIN_DISABLED,this.clkDrv=0,this.qDrv=0,this.dDrv=0,this.csDrv=0,this.hdDrv=0,this.wpDrv=0,this.chipId=0,this.minRev=0,this.minRevFull=0,this.maxRevFull=0,this.storedDigest=null,this.calcDigest=null,this.dataLength=0,this.IROM_ALIGN=65536,this.ROM_LOADER=e,this.appendDigest=n,this.ramOnlyHeader=r,t!==null&&this.loadFromFile(t)}async loadFromFile(e){let t=e instanceof Uint8Array?e:l(e),n=0,r=this.loadCommonHeader(t,n,233);n+=8,this.loadExtendedHeader(t,n),n+=16;for(let e=0;e<r;e++){let e=this.loadSegment(t,n);n+=8+e.data.length}if(this.checksum=this.readChecksum(t,n),n=x(n,16),this.appendDigest){let e=n;this.storedDigest=t.slice(n,n+this.SHA256_DIGEST_LEN);let r=await crypto.subtle.digest(`SHA-256`,t.slice(0,e));this.calcDigest=new Uint8Array(r),this.dataLength=e-0}this.verify()}isFlashAddr(e){return this.ROM_LOADER.IROM_MAP_START<=e&&e<this.ROM_LOADER.IROM_MAP_END||this.ROM_LOADER.DROM_MAP_START<=e&&e<this.ROM_LOADER.DROM_MAP_END}async save(){let e=0,t=new Uint8Array(1024*1024),n=0;this.writeCommonHeader(t,n,this.segments.length),n+=8,this.saveExtendedHeader(t,n),n+=16;let r=239,i=this.segments.filter(e=>this.isFlashAddr(e.addr)).sort((e,t)=>e.addr-t.addr),a=this.segments.filter(e=>!this.isFlashAddr(e.addr)).sort((e,t)=>e.addr-t.addr);for(let e=0;e<i.length;e++){let t=i[e];if(t instanceof w&&t.name===`.flash.appdesc`){i.splice(e,1),i.unshift(t);break}}for(let e=0;e<a.length;e++){let t=a[e];if(t instanceof w&&t.name===`.dram0.bootdesc`){a.splice(e,1),a.unshift(t);break}}if(i.length>0){let e=i[0].addr;for(let t of i.slice(1)){if(Math.floor(t.addr/this.IROM_ALIGN)===Math.floor(e/this.IROM_ALIGN))throw new o(`Segment loaded at 0x${t.addr.toString(16)} lands in same 64KB flash mapping as segment loaded at 0x${e.toString(16)}. Can't generate binary. Suggest changing linker script or ELF to merge sections.`);e=t.addr}}if(this.ramOnlyHeader){for(let i of a)r=this.saveSegment(t,n,i,r),n+=8+i.data.length,e++;this.appendChecksum(t,n,r),n=x(n,16);for(let a of i.reverse()){let i=this.getAlignmentDataNeeded(a,n);if(i>0){let a=this.ROM_LOADER.BOOTLOADER_FLASH_OFFSET-this.SEG_HEADER_LEN;i<a&&(i+=this.IROM_ALIGN),i-=this.ROM_LOADER.BOOTLOADER_FLASH_OFFSET;let o=new C(0,new Uint8Array(i).fill(0),n);r=this.saveSegment(t,n,o,r),n+=8+i,e++}this.saveFlashSegment(t,n,a),n+=8+a.data.length,e++}}else{for(;i.length>0;){let o=i[0],s=this.getAlignmentDataNeeded(o,n);if(s>0){if(a.length>0&&s>this.SEG_HEADER_LEN){let e=a[0].splitImage(s);a[0].data.length===0&&a.shift(),r=this.saveSegment(t,n,e,r)}else{let e=new C(0,new Uint8Array(s).fill(0),n);r=this.saveSegment(t,n,e,r)}n+=8+s,e++}else{if((n+8)%this.IROM_ALIGN!==o.addr%this.IROM_ALIGN)throw Error(`Flash segment alignment mismatch`);r=this.saveFlashSegment(t,n,o,r),i.shift(),n+=8+o.data.length,e++}}for(let i of a)r=this.saveSegment(t,n,i,r),n+=8+i.data.length,e++}if(this.securePad){if(!this.appendDigest)throw Error(`secure_pad only applies if a SHA-256 digest is also appended to the image`);let i=(n+this.SEG_HEADER_LEN)%this.IROM_ALIGN,a=0;this.securePad===`1`?a=112:this.securePad===`2`&&(a=32);let o=(this.IROM_ALIGN-i-16-a)%this.IROM_ALIGN,s=new C(0,new Uint8Array(o).fill(0),n);r=this.saveSegment(t,n,s,r),n+=8+o,e++}this.ramOnlyHeader||(this.appendChecksum(t,n,r),n=x(n,16));let s=n;if(this.ramOnlyHeader?t[1]=a.length:t[1]=e,this.appendDigest){let e=await crypto.subtle.digest(`SHA-256`,t.slice(0,s)),r=new Uint8Array(e);t.set(r,s),n+=32}if(this.padToSize&&n%this.padToSize!==0){let e=this.padToSize-n%this.padToSize,r=new Uint8Array(e);r.fill(255),t.set(r,n),n+=e}return t}loadExtendedHeader(e,t){let n=new DataView(e.buffer,t);this.wpPin=n.getUint8(0);let r=n.getUint8(1);[this.clkDrv,this.qDrv]=this.splitByte(r);let i=n.getUint8(2);[this.dDrv,this.csDrv]=this.splitByte(i);let a=n.getUint8(3);[this.hdDrv,this.wpDrv]=this.splitByte(a),this.chipId=n.getUint8(4),this.chipId!==this.ROM_LOADER.IMAGE_CHIP_ID&&console.warn(`Unexpected chip id in image. Expected ${this.ROM_LOADER.IMAGE_CHIP_ID} but value was ${this.chipId}. Is this image for a different chip model?`),this.minRev=n.getUint8(5),this.minRevFull=n.getUint16(6,!0),this.maxRevFull=n.getUint16(8,!0);let o=n.getUint8(15);if(o===0||o===1)this.appendDigest=o===1;else throw Error(`Invalid value for append_digest field (0x${o.toString(16)}). Should be 0 or 1.`)}saveExtendedHeader(e,t){let n=new ArrayBuffer(16),r=new DataView(n);r.setUint8(0,this.wpPin),r.setUint8(1,this.joinByte(this.clkDrv,this.qDrv)),r.setUint8(2,this.joinByte(this.dDrv,this.csDrv)),r.setUint8(3,this.joinByte(this.hdDrv,this.wpDrv)),r.setUint8(4,this.ROM_LOADER.IMAGE_CHIP_ID),r.setUint8(5,this.minRev),r.setUint16(6,this.minRevFull,!0),r.setUint16(8,this.maxRevFull,!0);for(let e=9;e<15;e++)r.setUint8(e,0);r.setUint8(15,+!!this.appendDigest),e.set(new Uint8Array(n),t)}splitByte(e){return[e&15,e>>4&15]}joinByte(e,t){return e&15|(t&15)<<4}getAlignmentDataNeeded(e,t){let n=e.addr%this.IROM_ALIGN-this.SEG_HEADER_LEN,r=this.IROM_ALIGN-t%this.IROM_ALIGN+n;return r===0||r===this.IROM_ALIGN?0:(r-=this.SEG_HEADER_LEN,r<0&&(r+=this.IROM_ALIGN),r)}},D=class extends T{constructor(e,t=null){super(e),this.version=1,this.ROM_LOADER=e,this.flashMode=0,this.flashSizeFreq=0,t!==null&&this.loadFromFile(t)}loadFromFile(e){let t=e instanceof Uint8Array?e:l(e),n=0,r=this.loadCommonHeader(t,n,233);n+=8;for(let e=0;e<r;e++){let e=this.loadSegment(t,n);n+=8+e.data.length}this.checksum=this.readChecksum(t,n),this.verify()}defaultOutputName(e){return e+`-`}},O=class e extends T{constructor(e,t=null){super(e),this.version=2,this.ROM_LOADER=e,this.flashMode=0,this.flashSizeFreq=0,t!==null&&this.loadFromFile(t)}async loadFromFile(t){let n=t instanceof Uint8Array?t:l(t),r=0,i=this.loadCommonHeader(n,r,e.IMAGE_V2_MAGIC);r+=8,i!==e.IMAGE_V2_SEGMENT&&console.warn(`Warning: V2 header has unexpected "segment" count ${i} (usually 4)`);let a=this.flashMode,o=this.flashSizeFreq,s=this.entrypoint,c=this.loadSegment(n,r,!0);c.addr=0,c.includeInChecksum=!1,r+=8+c.data.length;let u=this.loadCommonHeader(n,r,233);r+=8,a!==this.flashMode&&console.warn(`WARNING: Flash mode value in first header (0x${a.toString(16)}) disagrees with second (0x${this.flashMode.toString(16)}). Using second value.`),o!==this.flashSizeFreq&&console.warn(`WARNING: Flash size/freq value in first header (0x${o.toString(16)}) disagrees with second (0x${this.flashSizeFreq.toString(16)}). Using second value.`),s!==this.entrypoint&&console.warn(`WARNING: Entrypoint address in first header (0x${s.toString(16)}) disagrees with second header (0x${this.entrypoint.toString(16)}). Using second value.`);for(let e=0;e<u;e++){let e=this.loadSegment(n,r);r+=8+e.data.length}this.checksum=this.readChecksum(n,r),this.verify()}defaultOutputName(e){let t=this.getIromSegment(),n=0;return t!==null&&(n=t.addr-a.IROM_MAP_START),`${e.replace(/\.[^/.]+$/,``)}-0x${(n&-4096).toString(16).padStart(5,`0`)}.bin`}};O.IMAGE_V2_MAGIC=234,O.IMAGE_V2_SEGMENT=4;var k=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},A=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},j=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},M=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.MMU_PAGE_SIZE_CONF=[16384,32768,65536],this.ROM_LOADER=e}},N=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.MMU_PAGE_SIZE_CONF=[8192,16384,32768,65536],this.ROM_LOADER=e}},P=class extends N{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},F=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},I=class extends E{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}},L=class extends N{constructor(e,t=null,n=!0,r=!1){super(e,t,n,r),this.ROM_LOADER=e}};async function R(e,t){let n=t instanceof Uint8Array?t:l(t),r=e.CHIP_NAME.toLowerCase().replace(/[-()]/g,``),i;if(r!==`esp8266`)switch(r){case`esp32`:i=E;break;case`esp32s2`:i=k;break;case`esp32s3`:i=A;break;case`esp32c3`:i=j;break;case`esp32c2`:i=M;break;case`esp32c6`:i=N;break;case`esp32c61`:i=P;break;case`esp32c5`:i=F;break;case`esp32h2`:i=L;break;case`esp32p4`:i=I;break;default:throw new o(`Unsupported chip name: ${r}`)}else{let e=n[0];if(e===233)i=D;else if(e===O.IMAGE_V2_MAGIC)i=O;else throw new o(`Invalid image magic number: ${e}`)}let a=new i(e),s=a;if(typeof s.loadFromFile==`function`){let e=s.loadFromFile(n);e instanceof Promise&&await e}return a}async function z(e){switch(e){case 15736195:{let{ESP32ROM:e}=await import(`./esp32-D9ZurRwV.js`).then(e=>e.n);return new e}case 203546735:case 1867591791:case 2084675695:{let{ESP32C2ROM:e}=await import(`./esp32c2-F0yCL7ES.js`);return new e}case 1763790959:case 456216687:case 1216438383:case 1130455151:{let{ESP32C3ROM:e}=await import(`./esp32c3-wVAODszM.js`).then(e=>e.n);return new e}case 752910447:{let{ESP32C6ROM:e}=await import(`./esp32c6-IwoGEmKl.js`);return new e}case 606167151:case 871374959:case 1333878895:{let{ESP32C61ROM:e}=await import(`./esp32c61-BJScMw70.js`);return new e}case 285294703:case 1675706479:case 1607549039:{let{ESP32C5ROM:e}=await import(`./esp32c5-ChTI-uFN.js`);return new e}case 3619110528:case 2548236392:{let{ESP32H2ROM:e}=await import(`./esp32h2-YosZEx9u.js`);return new e}case 9:{let{ESP32S3ROM:e}=await import(`./esp32s3-PqxbnxPZ.js`);return new e}case 1990:{let{ESP32S2ROM:e}=await import(`./esp32s2-Dhlhu16A.js`);return new e}case 4293968129:{let{ESP8266ROM:e}=await import(`./esp8266-qkLj6oNn.js`);return new e}case 0:case 182303440:case 117676761:{let{ESP32P4ROM:e}=await import(`./esp32p4-BSe822vW.js`);return new e}default:return null}}var B=class{constructor(e){this.ESP_RAM_BLOCK=6144,this.ESP_FLASH_BEGIN=2,this.ESP_FLASH_DATA=3,this.ESP_FLASH_END=4,this.ESP_MEM_BEGIN=5,this.ESP_MEM_END=6,this.ESP_MEM_DATA=7,this.ESP_WRITE_REG=9,this.ESP_READ_REG=10,this.ESP_SPI_ATTACH=13,this.ESP_CHANGE_BAUDRATE=15,this.ESP_FLASH_DEFL_BEGIN=16,this.ESP_FLASH_DEFL_DATA=17,this.ESP_FLASH_DEFL_END=18,this.ESP_SPI_FLASH_MD5=19,this.ESP_ERASE_FLASH=208,this.ESP_ERASE_REGION=209,this.ESP_READ_FLASH=210,this.ESP_RUN_USER_CODE=211,this.ESP_IMAGE_MAGIC=233,this.ESP_CHECKSUM_MAGIC=239,this.ROM_INVALID_RECV_MSG=5,this.DEFAULT_TIMEOUT=3e3,this.ERASE_REGION_TIMEOUT_PER_MB=3e4,this.ERASE_WRITE_TIMEOUT_PER_MB=4e4,this.MD5_TIMEOUT_PER_MB=8e3,this.CHIP_ERASE_TIMEOUT=12e4,this.FLASH_READ_TIMEOUT=1e5,this.MAX_TIMEOUT=this.CHIP_ERASE_TIMEOUT*2,this.SPI_ADDR_REG_MSB=!0,this.CHIP_DETECT_MAGIC_REG_ADDR=1073745920,this.DETECTED_FLASH_SIZES={18:`256KB`,19:`512KB`,20:`1MB`,21:`2MB`,22:`4MB`,23:`8MB`,24:`16MB`,25:`32MB`,26:`64MB`,27:`128MB`,28:`256MB`,32:`64MB`,33:`128MB`,34:`256MB`,50:`256KB`,51:`512KB`,52:`1MB`,53:`2MB`,54:`4MB`,55:`8MB`,56:`16MB`,57:`32MB`,58:`64MB`},this.USB_JTAG_SERIAL_PID=4097,this.romBaudrate=115200,this.debugLogging=!1,this.syncStubDetected=!1,this.IS_STUB=!1,this.FLASH_WRITE_SIZE=16384,this.transport=e.transport,this.baudrate=e.baudrate,this.resetConstructors={classicReset:(e,t)=>new p(e,t),customReset:(e,t)=>new _(e,t),hardReset:(e,t)=>new h(e,t),usbJTAGSerialReset:e=>new m(e)},e.serialOptions&&(this.serialOptions=e.serialOptions),e.terminal&&(this.terminal=e.terminal,this.terminal.clean()),e.debugLogging!==void 0&&(this.debugLogging=e.debugLogging),e.port&&(this.transport=new d(e.port)),e.enableTracing!==void 0&&(this.transport.tracing=e.enableTracing),e.resetConstructors?.classicReset&&(this.resetConstructors.classicReset=e.resetConstructors?.classicReset),e.resetConstructors?.customReset&&(this.resetConstructors.customReset=e.resetConstructors?.customReset),e.resetConstructors?.hardReset&&(this.resetConstructors.hardReset=e.resetConstructors?.hardReset),e.resetConstructors?.usbJTAGSerialReset&&(this.resetConstructors.usbJTAGSerialReset=e.resetConstructors?.usbJTAGSerialReset),this.info(`esptool.js`),this.info(`Serial port `+this.transport.getInfo())}write(e,t=!0){this.terminal?t?this.terminal.writeLine(e):this.terminal.write(e):console.log(e)}error(e,t=!0){this.write(`Error: ${e}`,t)}info(e,t=!0){this.write(e,t)}debug(e,t=!0){this.debugLogging&&this.write(`Debug: ${e}`,t)}_shortToBytearray(e){return new Uint8Array([e&255,e>>8&255])}_intToByteArray(e){return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}_byteArrayToShort(e,t){return e|t>>8}_byteArrayToInt(e,t,n,r){return e|t<<8|n<<16|r<<24}_appendBuffer(e,t){let n=new Uint8Array(e.byteLength+t.byteLength);return n.set(new Uint8Array(e),0),n.set(new Uint8Array(t),e.byteLength),n.buffer}_appendArray(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}ui8ToBstr(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return t}bstrToUi8(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}async readPacket(e=null,t=this.DEFAULT_TIMEOUT){for(let n=0;n<100;n++){let n=await this.transport.read(t);if(!n||n.length<8)continue;let r=n[0];if(r!==1)continue;let i=n[1],a=this._byteArrayToInt(n[4],n[5],n[6],n[7]),s=n.slice(8);if(r==1){if(e==null||i==e)return[a,s];if(s[0]!=0&&s[1]==this.ROM_INVALID_RECV_MSG)throw this.transport.flushInput(),new o(`unsupported command error`)}}throw new o(`invalid response`)}async command(e=null,t=new Uint8Array,n=0,r=!0,i=this.DEFAULT_TIMEOUT){if(e!=null){this.transport.tracing&&this.transport.trace(`command op:0x${e.toString(16).padStart(2,`0`)} data len=${t.length} wait_response=${+!!r} timeout=${(i/1e3).toFixed(3)} data=${this.transport.hexConvert(t)}`);let a=new Uint8Array(8+t.length);a[0]=0,a[1]=e,a[2]=this._shortToBytearray(t.length)[0],a[3]=this._shortToBytearray(t.length)[1],a[4]=this._intToByteArray(n)[0],a[5]=this._intToByteArray(n)[1],a[6]=this._intToByteArray(n)[2],a[7]=this._intToByteArray(n)[3];let o;for(o=0;o<t.length;o++)a[8+o]=t[o];await this.transport.write(a)}return r?this.readPacket(e,i):[0,new Uint8Array]}async readReg(e,t=this.DEFAULT_TIMEOUT){this.debug(`Read Register:${this.toHex(e)}`);let n=this._intToByteArray(e),r=await this.command(this.ESP_READ_REG,n,void 0,void 0,t);return this.debug(`Read Register Value:${r[0]}`),r[0]}async writeReg(e,t,n=4294967295,r=0,i=0){let a=this._appendArray(this._intToByteArray(e),this._intToByteArray(t));a=this._appendArray(a,this._intToByteArray(n)),a=this._appendArray(a,this._intToByteArray(r)),i>0&&(a=this._appendArray(a,this._intToByteArray(this.chip.UART_DATE_REG_ADDR)),a=this._appendArray(a,this._intToByteArray(0)),a=this._appendArray(a,this._intToByteArray(0)),a=this._appendArray(a,this._intToByteArray(i))),await this.checkCommand(`write target memory`,this.ESP_WRITE_REG,a)}async sync(){this.debug(`Sync`);let e=new Uint8Array(36),t;for(e[0]=7,e[1]=7,e[2]=18,e[3]=32,t=0;t<32;t++)e[4+t]=85;try{let t=await this.command(8,e,void 0,void 0,100);this.syncStubDetected=t[0]===0;for(let e=0;e<7;e++)t=await this.readPacket(8,100),this.syncStubDetected=this.syncStubDetected&&t[0]===0;return t}catch(e){throw this.debug(`Sync err `+e),e}}async _connectAttempt(e=`default_reset`,t){this.debug(`_connect_attempt `+e),t&&await t.reset();let n=this.transport.peek(),r=Array.from(n,e=>String.fromCharCode(e)).join(``).match(/boot:(0x[0-9a-fA-F]+)([\s\S]*?waiting for download)?/),i=!1,a=``,o=!1;r&&(i=!0,a=r[1],o=!!r[2]),this.debug(`bootMode:${a} downloadMode:${o}`);let s=``;for(let e=0;e<5;e++)try{this.debug(`Sync connect attempt ${e}`),this.transport.flushInput();let t=await this.sync();return this.debug(t[0].toString()),`success`}catch(e){this.debug(`Error at sync ${e}`),s=e instanceof Error?e.message:typeof e==`string`?e:JSON.stringify(e)}return i&&(s=`Wrong boot mode detected (${a}).
3
3
  This chip needs to be in download mode.`,o&&(s=`Download mode successfully detected, but getting no sync reply:
4
4
  The serial TX path seems to be down.`)),s}constructResetSequence(e){if(e!==`no_reset`){if(e===`usb_reset`||this.transport.getPid()===this.USB_JTAG_SERIAL_PID){if(this.resetConstructors.usbJTAGSerialReset)return this.debug(`using USB JTAG Serial Reset`),[this.resetConstructors.usbJTAGSerialReset(this.transport)]}else if(this.resetConstructors.classicReset)return this.debug(`using Classic Serial Reset`),[this.resetConstructors.classicReset(this.transport,50),this.resetConstructors.classicReset(this.transport,550)]}return[]}async connect(e=`default_reset`,t=7,n=!0){let r;this.info(`Connecting...`,!1),await this.transport.connect(this.romBaudrate,this.serialOptions),this.transport.readLoop();let i=this.constructResetSequence(e);for(let n=0;n<t;n++){let t=i.length>0?i[n%i.length]:null;if(r=await this._connectAttempt(e,t),r===`success`)break}if(r!==`success`)throw new o(`Failed to connect with the device`);if(this.debug(`Connect attempt successful.`),this.info(`
5
5
  \r`,!1),n){let e=await this.readReg(this.CHIP_DETECT_MAGIC_REG_ADDR)>>>0;this.debug(`Chip Magic `+e.toString(16));let t=await z(e);this.chip=t}}async detectChip(e=`default_reset`){await this.connect(e),this.info(`Detecting chip type... `,!1),this.chip==null?this.info(`unknown!`):this.info(this.chip.CHIP_NAME)}async checkCommand(e=``,t=null,n=new Uint8Array,r=0,i=0,a=this.DEFAULT_TIMEOUT){this.debug(`check_command `+e);let s=await this.command(t,n,r,void 0,a);if(s&&s[1]&&s[1].length<i+2){let t=s[1].slice(0,2);throw t[0]===0?new o(`Failed to ${e}.\n Only got ${s[1].length} bytes of data.`):new o(`Failed to ${e} failed with status ${t}`)}let c=s[1].slice(i,i+2);if(c[0]!==0)throw new o(`Failed to ${e} failed with status ${c}`);return i>0?s[1].slice(0,i):s[0]}async memBegin(e,t,n,r){if(this.IS_STUB){let t=r,n=r+e,i=this.chip.getChipRevision?await this.chip.getChipRevision(this):void 0,a=await y(this.chip.CHIP_NAME,i);if(a){let e=[[a.bss_start||a.data_start,a.data_start+a.decodedData.length],[a.text_start,a.text_start+a.decodedText.length]];for(let[r,i]of e)if(t<i&&n>r)throw new o(`Software loader is resident at 0x${r.toString(16).padStart(8,`0`)}-0x${i.toString(16).padStart(8,`0`)}.
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./logger-LESFN7Hj.js";import{t as n}from"./backend-local-mrUgrni5.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-s20mtVA3.js";import{i as c,n as l,r as u,t as d}from"./path-utils-DU6QhF_k.js";const f=t(`fs-watcher`);let p=0;function m(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var h=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++p}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),f.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),f.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>m(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){f.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),f.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const g=t(`mount-index`);var _=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function v(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>256?t.slice(0,256):t;return`${t.length}\u0001${n.join(``)}`}async function y(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function b(e,t){return e instanceof Map?e.get(t):e[t]}function x(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function S(e,t,n){let r=b(e,t);if(r===void 0||r.trim()===``)return n;let i=x(r);return i===void 0?(g.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function C(e){return{maxDepth:S(e,`SLICC_MOUNT_INDEX_MAX_DEPTH`,400),maxEntries:S(e,`SLICC_MOUNT_INDEX_MAX_ENTRIES`,2e6)}}var w=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=C({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,g.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof _?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},g.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new _(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new _(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new _(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=v(n),a=r.get(i);if(a){for(let n of a)if(await y(n.handle,t))throw new _(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}};const T={"/dev/null":{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}};var E=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let i=e=>{let t=l(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(i),this.readOnlyPrefixes=n.map(i),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=l(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new r(`EACCES`,`permission denied`,l(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new r(`EACCES`,`permission denied`,l(e));return t}catch(t){throw t instanceof r?t:new r(`EACCES`,`permission denied`,l(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let o=l(i)!==l(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new r(`EACCES`,`permission denied`,l(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=T[l(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=l(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=T[l(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=l(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),i=t?r.length:r.length-1,a=``;for(let e=0;e<i;e++){a=a+`/`+r[e];let t=this.vfs.lstatSync(a);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=T[l(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=T[l(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=l(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async exists(e){if(T[l(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=T[l(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let i=T[l(e)];if(i){i.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let t=await this.vfs.readlink(e),n;if(n=t.startsWith(`/`)?l(t):l(this.vfs.dirname(e)+`/`+t),!this.isAllowedStrict(n))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async lstat(e){let t=T[l(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let n=l(e),i=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(i===n)o=i;else try{o=await this.vfs.realpath(i)}catch{throw new r(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new r(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new r(`EACCES`,`permission denied`,l(e));let i=this.vfs.getWatcher();if(!i)throw new r(`EINVAL`,`no watcher configured`);return i.watch(l(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async dispose(){await this.vfs.dispose()}};function D(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var O=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new w;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-DDqJxY_T.js`).then(e=>e.t),import(`./dist-B_CQDE9x.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-DDqJxY_T.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??D());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-DDqJxY_T.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.statSync!=`function`||typeof n.lstatSync!=`function`||typeof n.readlinkSync!=`function`)return null;let r=t;for(let e=0;e<=10;e++){let e;try{e=n.lstatSync(r)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=n.readlinkSync(r)}catch{return null}r=t.startsWith(`/`)?l(t):l(d(c(r).dir,t))}return null}lstatSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,n){let a=l(e);if(this.mountPoints.has(a))throw new r(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new r(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new r(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof r)||e.code!==`ENOENT`)throw e}let{dir:o}=c(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=C(n?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{await i({targetPath:a,descriptor:s,createdAt:Date.now()},t.kind===`local`?t.getHandle():void 0)}catch{}}async unmount(e){let t=l(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await a(t)}catch{}}async reconstructBackendFromDescriptor(e){switch(e.kind){case`local`:{let t=await o(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return n.fromHandle(t,{mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-tMTW6qA4.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-tMTW6qA4.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let n=l(e);if(this.mountPoints.has(n))throw new r(`EEXIST`,`mount point is already mounted`,n);let{dir:i}=c(n);i!==`/`&&await this.mkdir(i,{recursive:!0});try{await this.lfs.mkdir(n)}catch{}this.mountPoints.set(n,t),this.internalMounts.add(n),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}async unmountInternal(e){let t=l(e);if(!this.internalMounts.has(t))throw new r(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=l(e),i=this.mountPoints.get(n);if(!i)throw new r(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n,C(t?.env??{})),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}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,n=0){let r=l(e);if(this.canUseWalkFastPath(r)){let e=this.mountIndex.getFiles(r);if(e){for(let t of e)yield t;return}}let i=t??new Set;if(n>64||i.size>=1e5)return;let a=await this.safeRealpath(r);if(i.has(a))return;i.add(a);let o=await this.readDir(r);for(let e of o){let t=r===`/`?`/${e.name}`:`${r}/${e.name}`;yield*this.walkEntry(e,t,i,n+1)}}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,r){if(e.type===`file`){yield t;return}if(e.type===`symlink`){yield*this.walkSymlink(t,n,r);return}yield*this.walk(t,n,r)}async*walkSymlink(e,t,n){try{let r=await this.stat(e);r.type===`file`?yield e:r.type===`directory`&&(yield*this.walk(e,t,n))}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)}},k=e({FsError:()=>r,FsWatcher:()=>h,MountIndex:()=>w,RestrictedFS:()=>E,VirtualFS:()=>O,joinPath:()=>d,normalizePath:()=>l,pathSegments:()=>u,resolveVfsBackendFromEnv:()=>D,splitPath:()=>c});export{h as i,O as n,E as r,k as t};
1
+ import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./logger-LESFN7Hj.js";import{t as n}from"./backend-local-mrUgrni5.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-s20mtVA3.js";import{i as c,n as l,r as u,t as d}from"./path-utils-DU6QhF_k.js";const f=t(`fs-watcher`);let p=0;function m(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var h=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++p}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),f.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),f.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>m(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){f.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),f.debug(`All watchers disposed`)}get size(){return this.registrations.size}};const g=t(`mount-index`);var _=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function v(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>256?t.slice(0,256):t;return`${t.length}\u0001${n.join(``)}`}async function y(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function b(e,t){return e instanceof Map?e.get(t):e[t]}function x(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function S(e,t,n){let r=b(e,t);if(r===void 0||r.trim()===``)return n;let i=x(r);return i===void 0?(g.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function C(e){return{maxDepth:S(e,`SLICC_MOUNT_INDEX_MAX_DEPTH`,400),maxEntries:S(e,`SLICC_MOUNT_INDEX_MAX_ENTRIES`,2e6)}}var w=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=C({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,g.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof _?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},g.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new _(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new _(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new _(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=v(n),a=r.get(i);if(a){for(let n of a)if(await y(n.handle,t))throw new _(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}};const T={"/dev/null":{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}};var E=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],r=`hard`){this.vfs=e;let i=e=>{let t=l(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(i),this.readOnlyPrefixes=n.map(i),this.writeEnforcement=r}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=l(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=l(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new r(`EACCES`,`permission denied`,l(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new r(`EACCES`,`permission denied`,l(e));return t}catch(t){throw t instanceof r?t:new r(`EACCES`,`permission denied`,l(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let o=l(i)!==l(t);if(!(this.writeEnforcement===`sudo-delegated`&&!o))throw new r(`EACCES`,`permission denied`,l(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=T[l(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=l(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=T[l(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=l(e);if(n===`/`)return!1;let r=n.slice(1).split(`/`),i=t?r.length:r.length-1,a=``;for(let e=0;e<i;e++){a=a+`/`+r[e];let t=this.vfs.lstatSync(a);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=T[l(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=T[l(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=l(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof r?t:new r(`ENOENT`,`no such file or directory`,l(e))}if(!this.isAllowedStrict(t))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async exists(e){if(T[l(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=T[l(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let i=T[l(e)];if(i){i.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof r&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let t=await this.vfs.readlink(e),n;if(n=t.startsWith(`/`)?l(t):l(this.vfs.dirname(e)+`/`+t),!this.isAllowedStrict(n))throw new r(`ENOENT`,`no such file or directory`,l(e));return t}async lstat(e){let t=T[l(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new r(`ENOENT`,`no such file or directory`,l(e));let n=l(e),i=this.vfs.dirname(n),a=this.vfs.basename(n),o;if(i===n)o=i;else try{o=await this.vfs.realpath(i)}catch{throw new r(`ENOENT`,`no such file or directory`,n)}let s=o===`/`?`/${a}`:`${o}/${a}`;if(!this.isAllowed(s))throw new r(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new r(`EACCES`,`permission denied`,l(e));let i=this.vfs.getWatcher();if(!i)throw new r(`EINVAL`,`no watcher configured`);return i.watch(l(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async dispose(){await this.vfs.dispose()}};function D(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var O=class e{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new w;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-_-KdSeH9.js`).then(e=>e.t),import(`./dist-BAh1Prs8.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-_-KdSeH9.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??D());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-_-KdSeH9.js`).then(e=>e.t)).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.statSync!=`function`||typeof n.lstatSync!=`function`||typeof n.readlinkSync!=`function`)return null;let r=t;for(let e=0;e<=10;e++){let e;try{e=n.lstatSync(r)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=n.readlinkSync(r)}catch{return null}r=t.startsWith(`/`)?l(t):l(d(c(r).dir,t))}return null}lstatSync(e){let t=l(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,n){let a=l(e);if(this.mountPoints.has(a))throw new r(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new r(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new r(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof r)||e.code!==`ENOENT`)throw e}let{dir:o}=c(a);o!==`/`&&await this.mkdir(o,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=C(n?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let s=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:s})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{await i({targetPath:a,descriptor:s,createdAt:Date.now()},t.kind===`local`?t.getHandle():void 0)}catch{}}async unmount(e){let t=l(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await a(t)}catch{}}async reconstructBackendFromDescriptor(e){switch(e.kind){case`local`:{let t=await o(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return n.fromHandle(t,{mountId:e.mountId})}case`s3`:{let{S3MountBackend:t,RemoteMountCache:n,makeSignedFetchS3:r}=await import(`./mount-DW7FdQ0s.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-DW7FdQ0s.js`).then(e=>e.t),i=new n({mountId:e.mountId,ttlMs:3e4});return new t({source:e.source,profile:e.profile,cache:i,mountId:e.mountId,signedFetch:r()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let n=l(e);if(this.mountPoints.has(n))throw new r(`EEXIST`,`mount point is already mounted`,n);let{dir:i}=c(n);i!==`/`&&await this.mkdir(i,{recursive:!0});try{await this.lfs.mkdir(n)}catch{}this.mountPoints.set(n,t),this.internalMounts.add(n),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}async unmountInternal(e){let t=l(e);if(!this.internalMounts.has(t))throw new r(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=l(e),i=this.mountPoints.get(n);if(!i)throw new r(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n,C(t?.env??{})),a}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}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,n=0){let r=l(e);if(this.canUseWalkFastPath(r)){let e=this.mountIndex.getFiles(r);if(e){for(let t of e)yield t;return}}let i=t??new Set;if(n>64||i.size>=1e5)return;let a=await this.safeRealpath(r);if(i.has(a))return;i.add(a);let o=await this.readDir(r);for(let e of o){let t=r===`/`?`/${e.name}`:`${r}/${e.name}`;yield*this.walkEntry(e,t,i,n+1)}}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,r){if(e.type===`file`){yield t;return}if(e.type===`symlink`){yield*this.walkSymlink(t,n,r);return}yield*this.walk(t,n,r)}async*walkSymlink(e,t,n){try{let r=await this.stat(e);r.type===`file`?yield e:r.type===`directory`&&(yield*this.walk(e,t,n))}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)}},k=e({FsError:()=>r,FsWatcher:()=>h,MountIndex:()=>w,RestrictedFS:()=>E,VirtualFS:()=>O,joinPath:()=>d,normalizePath:()=>l,pathSegments:()=>u,resolveVfsBackendFromEnv:()=>D,splitPath:()=>c});export{h as i,O as n,E as r,k as t};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-C30gQBcj2.js","assets/rolldown-runtime-aKtaBQYM.js","assets/dist-DD6YY4Ks2.js","assets/mount-9rGyUTfq.js","assets/preload-helper-CZgWQFsJ.js","assets/mime-types-ugOWOUZ9.js","assets/src-x0cJ68Fe.js","assets/proxied-fetch-Bht31_rT.js","assets/fetch-body-D2PwksUW.js","assets/types-idfTVsM8.js","assets/backend-local-BgTSBOxM.js","assets/tool-ui-DfXu6quJ.js","assets/logger-DDBAeTLF.js","assets/picker-approval-Dc390nC7.js","assets/mount-picker-popup-Cw_D7c_n.js","assets/picker-popup-CpulHQsi.js","assets/mount-table-store-CfQUN_2R.js","assets/mount-bridge-client-CB9Fm9Jh.js"])))=>i.map(i=>d[i]);
2
- import{t as e}from"./preload-helper-CZgWQFsJ.js";import{t}from"./logger-DDBAeTLF.js";import{i as n,n as r,r as i,t as a}from"./path-utils-DU6QhF_k.js";import{t as o}from"./types-idfTVsM8.js";import{t as s}from"./backend-local-BgTSBOxM.js";import{a as c,i as l,n as u,t as d}from"./mount-table-store-CfQUN_2R.js";var f=t(`fs-watcher`),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}},g=t(`mount-index`),_=400,v=2e6,y=`SLICC_MOUNT_INDEX_MAX_DEPTH`,b=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,x=256,S=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function C(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>x?t.slice(0,x):t;return`${t.length}\u0001${n.join(``)}`}async function w(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function T(e,t){return e instanceof Map?e.get(t):e[t]}function E(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function D(e,t,n){let r=T(e,t);if(r===void 0||r.trim()===``)return n;let i=E(r);return i===void 0?(g.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function O(e){return{maxDepth:D(e,y,_),maxEntries:D(e,b,v)}}var k=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=O({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,g.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof S?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},g.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new S(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new S(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new S(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=C(n),a=r.get(i);if(a){for(let n of a)if(await w(n.handle,t))throw new S(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}},A={"/dev/null":{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},j=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],i=`hard`){this.vfs=e;let a=e=>{let t=r(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=i}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=r(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new o(`EACCES`,`permission denied`,r(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}catch(t){throw t instanceof o?t:new o(`ENOENT`,`no such file or directory`,r(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new o(`EACCES`,`permission denied`,r(e));return t}catch(t){throw t instanceof o?t:new o(`EACCES`,`permission denied`,r(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let s=r(i)!==r(t);if(!(this.writeEnforcement===`sudo-delegated`&&!s))throw new o(`EACCES`,`permission denied`,r(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=A[r(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=r(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=A[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=r(e);if(n===`/`)return!1;let i=n.slice(1).split(`/`),a=t?i.length:i.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+i[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=A[r(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=A[r(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=r(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof o?t:new o(`ENOENT`,`no such file or directory`,r(e))}if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}async exists(e){if(A[r(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=A[r(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let i=A[r(e)];if(i){i.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let t=await this.vfs.readlink(e),n;if(n=t.startsWith(`/`)?r(t):r(this.vfs.dirname(e)+`/`+t),!this.isAllowedStrict(n))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}async lstat(e){let t=A[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let n=r(e),i=this.vfs.dirname(n),a=this.vfs.basename(n),s;if(i===n)s=i;else try{s=await this.vfs.realpath(i)}catch{throw new o(`ENOENT`,`no such file or directory`,n)}let c=s===`/`?`/${a}`:`${s}/${a}`;if(!this.isAllowed(c))throw new o(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(c)}watch(e,t,n){if(!this.isAllowed(e))throw new o(`EACCES`,`permission denied`,r(e));let i=this.vfs.getWatcher();if(!i)throw new o(`EINVAL`,`no watcher configured`);return i.watch(r(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async dispose(){await this.vfs.dispose()}},M=10,N=64,P=1e5;function F(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var I=class t{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new k;constructor(e,n,r,i){if(this.dbName=e,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?t.initOpfsBackend(this,i,n===!0):t.initMemoryBackend(this,e,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${e}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(n,r,i){let a=r??await t.acquireOpfsHandle(n.dbName,i);await t.seedOpfsMetadataSidecarIfMissing(a);let[o,{WebAccess:s}]=await Promise.all([e(()=>import(`./dist-C30gQBcj2.js`).then(e=>e.t),__vite__mapDeps([0,1])),e(()=>import(`./dist-DD6YY4Ks2.js`),__vite__mapDeps([2,0,1]))]);await t.ensureRootMount(o);let c=`/__opfs__/${n.dbName}`,l=t.opfsBackends.get(n.dbName);if(l&&i){try{o.umount(c)}catch{}t.opfsBackends.delete(n.dbName),l=void 0}if(!l){let e=await o.resolveMountConfig({backend:s,handle:a,metadata:`/.metadata.json`});try{o.mount(c,e)}catch{}l={backendFs:e,refs:0},t.opfsBackends.set(n.dbName,l)}l.refs+=1,n.opfsBackendFs=l.backendFs.index?l.backendFs:null,n.opfsHandle=a,n.mountRoot=c,n.rawLfs=o.promises,n.rawLfsSync=o}static async initMemoryBackend(n,r,i){let a=await e(()=>import(`./dist-C30gQBcj2.js`).then(e=>e.t),__vite__mapDeps([0,1]));await t.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=t.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}t.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},t.memoryBackends.set(r,s)),s.refs+=1;try{a.mount(o,s.store)}catch{}n.mountRoot=o,n.rawLfs=a.promises,n.rawLfsSync=a,n.opfsBackendFs=null,n.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(e){return t.rootMountReady||=(async()=>{await e.configureSingle({backend:e.InMemory,label:`__vfs_root__`})})(),t.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new o(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static async create(e){let n=e?.dbName??`browser-fs`,r=e?.wipe===!0,i=new t(n,r,e?.backend??F());return await i._ready,r&&await d().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=r(n);t.index.delete(e),t._handles?.delete(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let n=this.backend===`opfs`?t.opfsBackends:t.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await e(()=>import(`./dist-C30gQBcj2.js`).then(e=>e.t),__vite__mapDeps([0,1]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=r(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=r(e);if(this.findMount(t))return null;let i=this.lfsSync;if(typeof i.statSync!=`function`||typeof i.lstatSync!=`function`||typeof i.readlinkSync!=`function`)return null;let o=t;for(let e=0;e<=M;e++){let e;try{e=i.lstatSync(o)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=i.readlinkSync(o)}catch{return null}o=t.startsWith(`/`)?r(t):r(a(n(o).dir,t))}return null}lstatSync(e){let t=r(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,i){let a=r(e);if(this.mountPoints.has(a))throw new o(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new o(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new o(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof o)||e.code!==`ENOENT`)throw e}let{dir:s}=n(a);s!==`/`&&await this.mkdir(s,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=O(i?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let l=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:l})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{await c({targetPath:a,descriptor:l,createdAt:Date.now()},t.kind===`local`?t.getHandle():void 0)}catch{}}async unmount(e){let t=r(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await l(t)}catch{}}async reconstructBackendFromDescriptor(t){switch(t.kind){case`local`:{let e=await u(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return s.fromHandle(e,{mountId:t.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await e(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-9rGyUTfq.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([3,4,5,6,7,1,8,9,10,11,12,13,14,15,16,17])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i(t.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-9rGyUTfq.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([3,4,5,6,7,1,8,9,10,11,12,13,14,15,16,17])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let i=r(e);if(this.mountPoints.has(i))throw new o(`EEXIST`,`mount point is already mounted`,i);let{dir:a}=n(i);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(i)}catch{}this.mountPoints.set(i,t),this.internalMounts.add(i),this.watcher?.notify([{type:`modify`,path:i,entryType:`directory`}])}async unmountInternal(e){let t=r(e);if(!this.internalMounts.has(t))throw new o(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=r(e),i=this.mountPoints.get(n);if(!i)throw new o(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n,O(t?.env??{})),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 o){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new o(e.code,r,t)}throw e}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,n){let i=r(e),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new o(`EISDIR`,`is a directory`,i);let e=a.relParts.join(`/`);try{let t=await a.backend.readFile(e);return(n?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(t):t}catch(e){t.rebrandFsError(e,i)}}let s=await this.resolveSymlinks(i);try{return(n?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(s,{encoding:`utf8`}):await this.lfs.readFile(s)}catch(e){throw this.convertError(e,i)}}async writeFile(e,i,a){let s=r(e),c=this.findMount(s);if(c){if(c.relParts.length===0)throw new o(`EISDIR`,`is a directory`,s);let e=c.relParts.join(`/`),n=!1;try{await this.stat(s),n=!0}catch{}let r=typeof i==`string`?new TextEncoder().encode(i):i instanceof Uint8Array?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);try{await c.backend.writeFile(e,r)}catch(e){t.rebrandFsError(e,s)}this.watcher?.notify([{type:n?`modify`:`create`,path:s,entryType:`file`}]),this.mountIndex.notifyWrite(s);return}let l;try{l=await this.resolveSymlinks(s)}catch{l=s}let u=!1;try{await this.lfs.stat(l),u=!0}catch{}let{dir:d}=n(l);d!==`/`&&await this.mkdir(d,{recursive:!0});try{await this.lfs.writeFile(l,i);let e=typeof i==`string`?new TextEncoder().encode(i).byteLength:(i instanceof Uint8Array,i.byteLength);await this.lfs.truncate?.(l,e)}catch(e){throw this.convertError(e,s)}this.watcher?.notify([{type:u?`modify`:`create`,path:l,entryType:`file`}])}async readDir(e){let t=r(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,n){let r=this.mountIndex.getDirectoryEntries(n.path,e);if(r!==void 0){let t=new Map;for(let e of r)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let i=n.relParts.join(`/`)||`/`,a;try{a=await n.backend.readDir(i)}catch(n){t.rebrandFsError(n,e)}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,e),[...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(e,n){let i=r(e);if(i===`/`)return;let a=this.findMount(i);if(a){if(a.relParts.length===0)return;let e=a.relParts.join(`/`),n=await this.exists(i);try{await a.backend.mkdir(e)}catch(e){t.rebrandFsError(e,i)}n||this.watcher?.notify([{type:`create`,path:i,entryType:`directory`}]);return}if(n?.recursive){let e=i.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(i)}catch(e){throw this.convertError(e,i)}this.watcher?.notify([{type:`create`,path:i,entryType:`directory`}])}}async rm(e,n){let i=r(e),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new o(`EINVAL`,`cannot remove a mount point — use unmount`,i);let e;try{e=(await this.stat(i)).type}catch{}let r=a.relParts.join(`/`);try{await a.backend.remove(r,{recursive:n?.recursive})}catch(e){t.rebrandFsError(e,i)}this.watcher?.notify([{type:`delete`,path:i,entryType:e}]),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(e){let n=r(e),i=this.findMount(n);if(i){if(i.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 e=i.relParts.join(`/`);try{let t=await i.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.mtime}}catch(e){t.rebrandFsError(e,n)}}let a=await this.resolveSymlinks(n);try{let e=await this.lfs.stat(a);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=r(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){let n=r(e),i=r(t),a;try{a=(await this.lstat(n)).type}catch{}try{await this.lfs.rename(n,i)}catch(e){throw this.convertError(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:i,entryType:a}]),this.mountIndex.notifyRename(n,i)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){let i=r(e);if(this.canUseWalkFastPath(i)){let e=this.mountIndex.getFiles(i);if(e){for(let t of e)yield t;return}}let a=t??new Set;if(n>N||a.size>=P)return;let o=await this.safeRealpath(i);if(a.has(o))return;a.add(o);let s=await this.readDir(i);for(let e of s){let t=i===`/`?`/${e.name}`:`${i}/${e.name}`;yield*this.walkEntry(e,t,a,n+1)}}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,r){if(e.type===`file`){yield t;return}if(e.type===`symlink`){yield*this.walkSymlink(t,n,r);return}yield*this.walk(t,n,r)}async*walkSymlink(e,t,n){try{let r=await this.stat(e);r.type===`file`?yield e:r.type===`directory`&&(yield*this.walk(e,t,n))}catch{}}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new o(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(r(e)).dir}basename(e){return n(r(e)).base}async symlink(e,t){let i=r(t);if(this.findMount(i))throw new o(`EINVAL`,`symlinks not supported on mounted filesystems`,i);let{dir:a}=n(i);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.symlink(e,i)}catch(e){throw this.convertError(e,i)}this.watcher?.notify([{type:`create`,path:i,entryType:`symlink`}])}async readlink(e){let t=r(e);try{return await this.lfs.readlink(t)}catch(e){throw this.convertError(e,t)}}async lstat(e){let t=r(e);if(this.findMount(t))return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw this.convertError(e,t)}}async realpath(e){let t=r(e);if(this.findMount(t))return t;let n=t.split(`/`).filter(Boolean),i=`/`,a=0;for(let e=0;e<n.length;e++){let r=await this.resolveRealpathComponent(i,n[e],e===n.length-1,t,a);i=r.resolved,a=r.hops}return i}async resolveRealpathComponent(e,t,n,r,i){let a=e===`/`?`/${t}`:`${e}/${t}`;for(;;){let e=await this.lstatOrThrow(a,n,r);if(e===null||!e.isSymbolicLink())return{resolved:a,hops:i};if(++i>M)throw new o(`ELOOP`,`too many symbolic links encountered`,r);a=await this.readAndResolveLink(a,r)}}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 i;try{i=await this.lfs.readlink(e)}catch(e){throw this.convertError(e,t)}return i.startsWith(`/`)?r(i):r(a(n(e).dir,i))}async resolveSymlinks(e){return this.findMount(e)?e:this.realpath(e)}convertError(e,t){if(e instanceof o)return e;let n=e?.code;if(typeof n==`string`){let r=n;if([`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`].includes(r))return new o(r,(e instanceof Error?e.message:String(e))||r,t)}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new o(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new o(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new o(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new o(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new o(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new o(`ELOOP`,`too many levels of symbolic links`,t):new o(`EINVAL`,r,t)}};export{o as FsError,h as FsWatcher,k as MountIndex,j as RestrictedFS,I as VirtualFS,a as joinPath,r as normalizePath,i as pathSegments,F as resolveVfsBackendFromEnv,n as splitPath};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-C30gQBcj2.js","assets/rolldown-runtime-aKtaBQYM.js","assets/dist-DD6YY4Ks2.js","assets/mount-Bu643VZV.js","assets/preload-helper-CZgWQFsJ.js","assets/mime-types-ugOWOUZ9.js","assets/src-x0cJ68Fe.js","assets/proxied-fetch-Bht31_rT.js","assets/fetch-body-D2PwksUW.js","assets/types-idfTVsM8.js","assets/backend-local-BgTSBOxM.js","assets/tool-ui-DfXu6quJ.js","assets/logger-DDBAeTLF.js","assets/picker-approval-Dc390nC7.js","assets/mount-picker-popup-Cw_D7c_n.js","assets/picker-popup-CpulHQsi.js","assets/mount-table-store-CfQUN_2R.js","assets/mount-bridge-client-CB9Fm9Jh.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-CZgWQFsJ.js";import{t}from"./logger-DDBAeTLF.js";import{i as n,n as r,r as i,t as a}from"./path-utils-DU6QhF_k.js";import{t as o}from"./types-idfTVsM8.js";import{t as s}from"./backend-local-BgTSBOxM.js";import{a as c,i as l,n as u,t as d}from"./mount-table-store-CfQUN_2R.js";var f=t(`fs-watcher`),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}},g=t(`mount-index`),_=400,v=2e6,y=`SLICC_MOUNT_INDEX_MAX_DEPTH`,b=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,x=256,S=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function C(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>x?t.slice(0,x):t;return`${t.length}\u0001${n.join(``)}`}async function w(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function T(e,t){return e instanceof Map?e.get(t):e[t]}function E(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function D(e,t,n){let r=T(e,t);if(r===void 0||r.trim()===``)return n;let i=E(r);return i===void 0?(g.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function O(e){return{maxDepth:D(e,y,_),maxEntries:D(e,b,v)}}var k=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=O({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,abortController:r,limits:n};this.mounts.set(e,i),this.notifyListeners(),this.indexMount(e,i,r.signal)}unregisterMount(e){let t=this.mounts.get(e);t&&(t.abortController?.abort(),this.mounts.delete(e),this.notifyListeners())}async refreshMount(e,t){let n=this.mounts.get(e);if(!n)throw Error(`No mount at ${e}`);n.abortController?.abort();let r=new AbortController;n.abortController=r,n.state={status:`pending`,indexed:0},n.files.clear(),n.directories.clear(),t&&(n.limits=t),this.notifyListeners(),await this.indexMount(e,n,r.signal)}isReady(e){return this.mounts.get(e)?.state.status===`ready`}isAnyIndexing(){for(let e of this.mounts.values())if(e.state.status===`indexing`||e.state.status===`pending`)return!0;return!1}dispose(){for(let e of this.mounts.values())e.abortController?.abort();this.mounts.clear(),this.listeners.clear()}getState(e){return this.mounts.get(e)?.state}getFiles(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;if(!t)return[...n.files];let r=[];for(let e of n.files)t(e)&&r.push(e);return r}getDirectoryEntries(e,t){let n=this.mounts.get(e);if(n?.state.status!==`ready`)return;let r=t===`/`?`/`:t+`/`,i=new Map;for(let e of n.files){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`file`)}for(let e of n.directories){if(!e.startsWith(r))continue;let t=e.slice(r.length);t.includes(`/`)||i.set(t,`directory`)}return[...i.entries()].map(([e,t])=>({name:e,type:t}))}hasPath(e,t){let n=this.mounts.get(e);if(n?.state.status===`ready`)return n.files.has(t)||n.directories.has(t)}notifyWrite(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.add(e);let r=e;for(;r!==t;){let e=r.lastIndexOf(`/`);if(e<=0)break;r=r.slice(0,e)||`/`,r.length>=t.length&&n.directories.add(r)}}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`)return;n.files.delete(e),n.directories.delete(e);let r=e+`/`;for(let e of n.files)e.startsWith(r)&&n.files.delete(e);for(let e of n.directories)e.startsWith(r)&&n.directories.delete(e)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status===`ready`){if(r.files.has(e)){r.files.delete(e),r.files.add(t);return}if(r.directories.has(e)){r.directories.delete(e),r.directories.add(t);let n=e+`/`,i=t+`/`;for(let e of[...r.files])e.startsWith(n)&&(r.files.delete(e),r.files.add(i+e.slice(n.length)));for(let e of[...r.directories])e.startsWith(n)&&(r.directories.delete(e),r.directories.add(i+e.slice(n.length)))}}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}findMountForPath(e){let t;for(let n of this.mounts.keys())(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.length)&&(t=n);return t}notifyListeners(){for(let e of this.listeners)try{e()}catch{}}async indexMount(e,t,n){t.state={status:`indexing`,indexed:0},this.notifyListeners();try{if(await this.walkHandle(e,t.handle,t,n),n.aborted)return;t.state={status:`ready`,indexed:t.files.size+t.directories.size,total:t.files.size+t.directories.size},t.abortController=null,g.info(`Mount indexed`,{path:e,files:t.files.size,directories:t.directories.size})}catch(r){if(n.aborted)return;let i=r instanceof Error?r.message:String(r),a=r instanceof S?r.cause:`indexing-error`;t.state={status:`error`,indexed:0,error:i,abortCause:a},g.error(`Mount indexing failed`,{path:e,error:i,abortCause:a})}this.notifyListeners()}async walkHandle(e,t,n,r,i=0,a=new Map){if(r.aborted)return;this.enforceWalkBounds(i,n),n.directories.add(e);let o=await this.readChildren(t,r,n);if(r.aborted)return;let s=await this.confirmNoCycle(e,t,o,a),c=this.pushAncestor(a,s,e,t);try{await this.walkChildren(e,o,n,r,i,a)}finally{this.popAncestor(a,s,c)}}enforceWalkBounds(e,t){if(e>t.limits.maxDepth)throw new S(`mount indexing aborted: directory nesting exceeded ${t.limits.maxDepth} levels`,`depth-exceeded`);if(t.directories.size+t.files.size>=t.limits.maxEntries)throw new S(`mount indexing aborted: exceeded ${t.limits.maxEntries} entries`,`entries-exceeded`)}async readChildren(e,t,n){let r=e,i=[];for await(let e of r){if(t.aborted)break;if(n.directories.size+n.files.size+i.length>=n.limits.maxEntries)throw new S(`mount indexing aborted: exceeded ${n.limits.maxEntries} entries`,`entries-exceeded`);i.push(e)}return i}async confirmNoCycle(e,t,n,r){let i=C(n),a=r.get(i);if(a){for(let n of a)if(await w(n.handle,t))throw new S(`mount indexing aborted: self-referential mount cycle detected at ${e} (re-exposes ${n.path})`,`cycle-detected`)}return i}pushAncestor(e,t,n,r){let i=e.get(t);return i||(i=[],e.set(t,i)),i.push({path:n,handle:r,signature:t}),i}popAncestor(e,t,n){n.pop(),n.length===0&&e.delete(t)}async walkChildren(e,t,n,r,i,a){for(let[o,s]of t){if(r.aborted)return;let t=e===`/`?`/${o}`:`${e}/${o}`;s.kind===`file`?(n.files.add(t),n.state.indexed++):s.kind===`directory`&&await this.walkHandle(t,s,n,r,i+1,a),n.state.indexed%500==0&&(this.notifyListeners(),await new Promise(e=>setTimeout(e,0)))}}},A={"/dev/null":{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},j=class{vfs;allowedPrefixes;readOnlyPrefixes;writeEnforcement;constructor(e,t,n=[],i=`hard`){this.vfs=e;let a=e=>{let t=r(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=i}getAllPrefixes(){let e=this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`);return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e]}isAllowed(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=r(e);return this.getAllPrefixes().some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=r(e);return this.allowedPrefixes.some(e=>t===e.slice(0,-1)||t.startsWith(e))}canWrite(e){return this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new o(`EACCES`,`permission denied`,r(e))}async resolveAndCheckRead(e){try{let t=await this.vfs.realpath(e);if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}catch(t){throw t instanceof o?t:new o(`ENOENT`,`no such file or directory`,r(e))}}async resolveAndCheckWrite(e){try{let t=await this.vfs.realpath(e);if(!this.isWritable(t)&&!this.isSymlinkEscapeAllowed(t))throw new o(`EACCES`,`permission denied`,r(e));return t}catch(t){throw t instanceof o?t:new o(`EACCES`,`permission denied`,r(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),i;try{i=await this.vfs.realpath(t)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e;return}let a=i+`/`+n;if(this.isWritable(a))return;let s=r(i)!==r(t);if(!(this.writeEnforcement===`sudo-delegated`&&!s))throw new o(`EACCES`,`permission denied`,r(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=A[r(e)];if(n)return n.read(t);if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let i=await this.resolveAndCheckRead(e);return this.vfs.readFile(i,t)}async readDir(e){if(!this.isAllowed(e))return[];let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return[]}let n=await this.vfs.readDir(t);if(!this.isAllowedStrict(e)){let t=r(e);return n.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return n}async stat(e){let t=A[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(e));if(this.isAllowedStrict(e)){let t=await this.resolveAndCheckRead(e);return this.vfs.stat(t)}return this.vfs.stat(e)}scanPathForSymlinks(e,t){let n=r(e);if(n===`/`)return!1;let i=n.slice(1).split(`/`),a=t?i.length:i.length-1,o=``;for(let e=0;e<a;e++){o=o+`/`+i[e];let t=this.vfs.lstatSync(o);if(t===null)return null;if(t.type===`symlink`)return!0}return!1}statSync(e){let t=A[r(e)];return t?t.stat():!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=A[r(e)];return t?t.stat():!this.isAllowed(e)||this.scanPathForSymlinks(e,!1)!==!1?null:this.vfs.lstatSync(e)}readDirSync(e){if(!this.isAllowed(e)||this.scanPathForSymlinks(e,!0)!==!1)return null;let t=this.vfs.readDirSync(e);if(t===null)return null;if(this.isAllowedStrict(e))return t;let n=r(e);return t.filter(e=>{let t=n===`/`?`/${e.name}`:`${n}/${e.name}`;return this.isAllowed(t)})}async realpath(e){let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof o?t:new o(`ENOENT`,`no such file or directory`,r(e))}if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}async exists(e){if(A[r(e)])return!0;if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=A[r(e)];if(t)return t.readText();if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let n=await this.resolveAndCheckRead(e);return this.vfs.readTextFile(n)}async*walk(e){if(!this.isAllowed(e))return;let t=e;if(this.isAllowedStrict(e))try{t=await this.resolveAndCheckRead(e)}catch{return}for await(let e of this.vfs.walk(t))this.isAllowed(e)&&(yield e)}async writeFile(e,t,n){let i=A[r(e)];if(i){i.write(t);return}this.checkWrite(e),await this.checkParentRealpathEscape(e);try{(await this.vfs.lstat(e)).type===`symlink`&&await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e}return this.vfs.writeFile(e,t,n)}async mkdir(e,t){return this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){this.checkWrite(e);try{(await this.vfs.lstat(e)).type===`symlink`||await this.resolveAndCheckWrite(e)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e}return this.vfs.rm(e,t)}async rename(e,t){return this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(e));this.checkWrite(t);let n=await this.resolveAndCheckRead(e);await this.checkParentRealpathEscape(t);try{(await this.vfs.lstat(t)).type===`symlink`&&await this.resolveAndCheckWrite(t)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.checkWrite(t),await this.checkParentRealpathEscape(t),this.vfs.symlink(e,t)}async readlink(e){if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let t=await this.vfs.readlink(e),n;if(n=t.startsWith(`/`)?r(t):r(this.vfs.dirname(e)+`/`+t),!this.isAllowedStrict(n))throw new o(`ENOENT`,`no such file or directory`,r(e));return t}async lstat(e){let t=A[r(e)];if(t)return t.stat();if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,r(e));let n=r(e),i=this.vfs.dirname(n),a=this.vfs.basename(n),s;if(i===n)s=i;else try{s=await this.vfs.realpath(i)}catch{throw new o(`ENOENT`,`no such file or directory`,n)}let c=s===`/`?`/${a}`:`${s}/${a}`;if(!this.isAllowed(c))throw new o(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(c)}watch(e,t,n){if(!this.isAllowed(e))throw new o(`EACCES`,`permission denied`,r(e));let i=this.vfs.getWatcher();if(!i)throw new o(`EINVAL`,`no watcher configured`);return i.watch(r(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async dispose(){await this.vfs.dispose()}},M=10,N=64,P=1e5;function F(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var I=class t{lfs;lfsSync;rawLfs=null;rawLfsSync=null;_ready;_readyResolved=!1;backend;mountPoints=new Map;opfsBackendFs=null;opfsHandle=null;mountRoot=``;internalMounts=new Set;watcher=null;dbName;mountSyncChannel=null;mountIndex=new k;constructor(e,n,r,i){if(this.dbName=e,this.backend=r===`opfs`?`opfs`:`memory`,this.lfs=this.makeDeferredLfs(),this.lfsSync=this.makeDeferredLfsSync(),this._ready=this.backend===`opfs`?t.initOpfsBackend(this,i,n===!0):t.initMemoryBackend(this,e,n===!0),this._ready.then(()=>{this._readyResolved=!0},()=>{}),typeof BroadcastChannel<`u`)try{this.mountSyncChannel=new BroadcastChannel(`vfs-mount-sync:${e}`),this.mountSyncChannel.onmessage=e=>{let{type:t,path:n,descriptor:r}=e.data??{};if(t===`mount`&&typeof n==`string`&&r)this.reconstructBackendFromDescriptor(r).then(e=>{this.mountPoints.set(n,e),e.kind===`local`&&this.mountIndex.registerMount(n,e.getHandle()),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}).catch(()=>{});else if(t===`unmount`&&typeof n==`string`){let e=this.mountPoints.get(n);this.mountPoints.delete(n),this.mountIndex.unregisterMount(n),e?.close(),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}])}}}catch{}}static async initOpfsBackend(n,r,i){let a=r??await t.acquireOpfsHandle(n.dbName,i);await t.seedOpfsMetadataSidecarIfMissing(a);let[o,{WebAccess:s}]=await Promise.all([e(()=>import(`./dist-C30gQBcj2.js`).then(e=>e.t),__vite__mapDeps([0,1])),e(()=>import(`./dist-DD6YY4Ks2.js`),__vite__mapDeps([2,0,1]))]);await t.ensureRootMount(o);let c=`/__opfs__/${n.dbName}`,l=t.opfsBackends.get(n.dbName);if(l&&i){try{o.umount(c)}catch{}t.opfsBackends.delete(n.dbName),l=void 0}if(!l){let e=await o.resolveMountConfig({backend:s,handle:a,metadata:`/.metadata.json`});try{o.mount(c,e)}catch{}l={backendFs:e,refs:0},t.opfsBackends.set(n.dbName,l)}l.refs+=1,n.opfsBackendFs=l.backendFs.index?l.backendFs:null,n.opfsHandle=a,n.mountRoot=c,n.rawLfs=o.promises,n.rawLfsSync=o}static async initMemoryBackend(n,r,i){let a=await e(()=>import(`./dist-C30gQBcj2.js`).then(e=>e.t),__vite__mapDeps([0,1]));await t.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=t.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}t.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},t.memoryBackends.set(r,s)),s.refs+=1;try{a.mount(o,s.store)}catch{}n.mountRoot=o,n.rawLfs=a.promises,n.rawLfsSync=a,n.opfsBackendFs=null,n.opfsHandle=null}static rootMountReady=null;static memoryBackends=new Map;static opfsBackends=new Map;static async ensureRootMount(e){return t.rootMountReady||=(async()=>{await e.configureSingle({backend:e.InMemory,label:`__vfs_root__`})})(),t.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),readdir:t=>this._readyResolved?n().readdir(e(t)):this._ready.then(()=>n().readdir(e(t))),mkdir:(t,r)=>this._readyResolved?n().mkdir(e(t),r):this._ready.then(()=>n().mkdir(e(t),r)),rmdir:t=>this._readyResolved?n().rmdir(e(t)):this._ready.then(()=>n().rmdir(e(t))),unlink:t=>this._readyResolved?n().unlink(e(t)):this._ready.then(()=>n().unlink(e(t))),rename:(t,r)=>this._readyResolved?n().rename(e(t),e(r)):this._ready.then(()=>n().rename(e(t),e(r))),stat:t=>this._readyResolved?n().stat(e(t)):this._ready.then(()=>n().stat(e(t))),lstat:t=>this._readyResolved?n().lstat(e(t)):this._ready.then(()=>n().lstat(e(t))),symlink:(t,r)=>{let i=t.startsWith(`/`)?e(t):t;return this._readyResolved?n().symlink(i,e(r)):this._ready.then(()=>n().symlink(i,e(r)))},readlink:async r=>(this._readyResolved||await this._ready,t(await n().readlink(e(r)))),truncate:async(t,r)=>{this._readyResolved||await this._ready;let i=n();typeof i.truncate==`function`&&await i.truncate(e(t),r)},realpath:async r=>{this._readyResolved||await this._ready;let i=n();return typeof i.realpath==`function`?t(await i.realpath(e(r))):e(r)}}}makeDeferredLfsSync(){let e=e=>this.prefix(e),t=e=>this.unprefix(e);return{readdirSync:t=>{let n=this.rawLfsSync;return n?.readdirSync?n.readdirSync(e(t)):void 0},statSync:t=>{let n=this.rawLfsSync;return n?.statSync?n.statSync(e(t)):void 0},lstatSync:t=>{let n=this.rawLfsSync;return n?.lstatSync?n.lstatSync(e(t)):void 0},readlinkSync:n=>{let r=this.rawLfsSync;return r?.readlinkSync?t(r.readlinkSync(e(n))):void 0}}}static async seedOpfsMetadataSidecarIfMissing(e){let t=`.metadata.json`;try{await e.getFileHandle(t);return}catch(e){if(e?.name!==`NotFoundError`)throw e}let n=await(await e.getFileHandle(t,{create:!0})).createWritable(),r=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await n.write(r),await n.close()}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new o(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static async create(e){let n=e?.dbName??`browser-fs`,r=e?.wipe===!0,i=new t(n,r,e?.backend??F());return await i._ready,r&&await d().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=r(n);t.index.delete(e),t._handles?.delete(e)}}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async dispose(){if(this.mountSyncChannel?.close(),this.mountSyncChannel=null,this.watcher?.dispose(),this.watcher=null,this.mountIndex.dispose(),await this.writeOpfsMetadataSidecar(),this.mountRoot){let n=this.backend===`opfs`?t.opfsBackends:t.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await e(()=>import(`./dist-C30gQBcj2.js`).then(e=>e.t),__vite__mapDeps([0,1]))).umount(this.mountRoot)}catch{}}}}readDirSync(e){let t=r(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.readdirSync!=`function`||typeof n.lstatSync!=`function`)return null;try{let e=n.readdirSync(t),r=[];for(let i of e){let e=t===`/`?`/${i}`:`${t}/${i}`;try{let t=n.lstatSync(e),a=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;r.push({name:i,type:a})}catch{}}return r}catch{return null}}statSync(e){let t=r(e);if(this.findMount(t))return null;let i=this.lfsSync;if(typeof i.statSync!=`function`||typeof i.lstatSync!=`function`||typeof i.readlinkSync!=`function`)return null;let o=t;for(let e=0;e<=M;e++){let e;try{e=i.lstatSync(o)}catch{return null}if(!e.isSymbolicLink())return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs};let t;try{t=i.readlinkSync(o)}catch{return null}o=t.startsWith(`/`)?r(t):r(a(n(o).dir,t))}return null}lstatSync(e){let t=r(e);if(this.findMount(t))return null;let n=this.lfsSync;if(typeof n.lstatSync!=`function`)return null;try{let e=n.lstatSync(t);if(e.isSymbolicLink()){let r=n.readlinkSync?n.readlinkSync(t):``;return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:r}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch{return null}}async mount(e,t,i){let a=r(e);if(this.mountPoints.has(a))throw new o(`EEXIST`,`mount point is already mounted`,a);try{if((await this.lstat(a)).type!==`directory`)throw new o(`ENOTDIR`,`mount point must be a directory`,a);if((await this.readDir(a)).length>0)throw new o(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,a)}catch(e){if(!(e instanceof o)||e.code!==`ENOENT`)throw e}let{dir:s}=n(a);s!==`/`&&await this.mkdir(s,{recursive:!0});try{await this.lfs.mkdir(a)}catch{}if(this.mountPoints.set(a,t),t.kind===`local`){let e=O(i?.env??{});this.mountIndex.registerMount(a,t.getHandle(),e)}let l=t.kind===`local`?{kind:`local`,mountId:t.mountId,idbHandleKey:a}:t.kind===`s3`?{kind:`s3`,mountId:t.mountId,source:t.source,profile:t.profile??`default`}:{kind:`da`,mountId:t.mountId,source:t.source,profile:t.profile??`default`};try{this.mountSyncChannel?.postMessage({type:`mount`,path:a,descriptor:l})}catch{}this.watcher?.notify([{type:`modify`,path:a,entryType:`directory`}]);try{await c({targetPath:a,descriptor:l,createdAt:Date.now()},t.kind===`local`?t.getHandle():void 0)}catch{}}async unmount(e){let t=r(e),n=this.mountPoints.get(t);this.mountPoints.delete(t),this.mountIndex.unregisterMount(t);try{this.mountSyncChannel?.postMessage({type:`unmount`,path:t})}catch{}this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close();try{await l(t)}catch{}}async reconstructBackendFromDescriptor(t){switch(t.kind){case`local`:{let e=await u(t.idbHandleKey);if(!e)throw Error(`no handle stored for ${t.idbHandleKey}`);return s.fromHandle(e,{mountId:t.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await e(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-Bu643VZV.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([3,4,5,6,7,1,8,9,10,11,12,13,14,15,16,17])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i(t.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await e(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-Bu643VZV.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([3,4,5,6,7,1,8,9,10,11,12,13,14,15,16,17])),a=new r({mountId:t.mountId,ttlMs:3e4});return new n({source:t.source,profile:t.profile,cache:a,mountId:t.mountId,signedFetch:i()})}}}listMounts(){let e=[];for(let t of this.mountPoints.keys())this.internalMounts.has(t)||e.push(t);return e}listInternalMounts(){return[...this.internalMounts]}listMountPoints(){let e=[];for(let[t,n]of this.mountPoints)this.internalMounts.has(t)||e.push({path:t,kind:n.kind});return e}async mountInternal(e,t){let i=r(e);if(this.mountPoints.has(i))throw new o(`EEXIST`,`mount point is already mounted`,i);let{dir:a}=n(i);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.mkdir(i)}catch{}this.mountPoints.set(i,t),this.internalMounts.add(i),this.watcher?.notify([{type:`modify`,path:i,entryType:`directory`}])}async unmountInternal(e){let t=r(e);if(!this.internalMounts.has(t))throw new o(`ENOENT`,`not an internal mount point`,t);let n=this.mountPoints.get(t);this.mountPoints.delete(t),this.internalMounts.delete(t),this.watcher?.notify([{type:`modify`,path:t,entryType:`directory`}]),await n?.close()}getMountIndex(){return this.mountIndex}async refreshMount(e,t){let n=r(e),i=this.mountPoints.get(n);if(!i)throw new o(`ENOENT`,`not a mount point`,n);let a=await i.refresh(t);return i.kind===`local`&&await this.mountIndex.refreshMount(n,O(t?.env??{})),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 o){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new o(e.code,r,t)}throw e}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,n){let i=r(e),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new o(`EISDIR`,`is a directory`,i);let e=a.relParts.join(`/`);try{let t=await a.backend.readFile(e);return(n?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(t):t}catch(e){t.rebrandFsError(e,i)}}let s=await this.resolveSymlinks(i);try{return(n?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(s,{encoding:`utf8`}):await this.lfs.readFile(s)}catch(e){throw this.convertError(e,i)}}async writeFile(e,i,a){let s=r(e),c=this.findMount(s);if(c){if(c.relParts.length===0)throw new o(`EISDIR`,`is a directory`,s);let e=c.relParts.join(`/`),n=!1;try{await this.stat(s),n=!0}catch{}let r=typeof i==`string`?new TextEncoder().encode(i):i instanceof Uint8Array?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);try{await c.backend.writeFile(e,r)}catch(e){t.rebrandFsError(e,s)}this.watcher?.notify([{type:n?`modify`:`create`,path:s,entryType:`file`}]),this.mountIndex.notifyWrite(s);return}let l;try{l=await this.resolveSymlinks(s)}catch{l=s}let u=!1;try{await this.lfs.stat(l),u=!0}catch{}let{dir:d}=n(l);d!==`/`&&await this.mkdir(d,{recursive:!0});try{await this.lfs.writeFile(l,i);let e=typeof i==`string`?new TextEncoder().encode(i).byteLength:(i instanceof Uint8Array,i.byteLength);await this.lfs.truncate?.(l,e)}catch(e){throw this.convertError(e,s)}this.watcher?.notify([{type:u?`modify`:`create`,path:l,entryType:`file`}])}async readDir(e){let t=r(e),n=this.findMount(t);return n?this.readDirMounted(t,n):this.readDirLocal(t)}async readDirMounted(e,n){let r=this.mountIndex.getDirectoryEntries(n.path,e);if(r!==void 0){let t=new Map;for(let e of r)t.set(e.name,{name:e.name,type:e.type});return this.addNestedMountEntries(t,e),[...t.values()]}let i=n.relParts.join(`/`)||`/`,a;try{a=await n.backend.readDir(i)}catch(n){t.rebrandFsError(n,e)}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,e),[...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(e,n){let i=r(e);if(i===`/`)return;let a=this.findMount(i);if(a){if(a.relParts.length===0)return;let e=a.relParts.join(`/`),n=await this.exists(i);try{await a.backend.mkdir(e)}catch(e){t.rebrandFsError(e,i)}n||this.watcher?.notify([{type:`create`,path:i,entryType:`directory`}]);return}if(n?.recursive){let e=i.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(i)}catch(e){throw this.convertError(e,i)}this.watcher?.notify([{type:`create`,path:i,entryType:`directory`}])}}async rm(e,n){let i=r(e),a=this.findMount(i);if(a){if(a.relParts.length===0)throw new o(`EINVAL`,`cannot remove a mount point — use unmount`,i);let e;try{e=(await this.stat(i)).type}catch{}let r=a.relParts.join(`/`);try{await a.backend.remove(r,{recursive:n?.recursive})}catch(e){t.rebrandFsError(e,i)}this.watcher?.notify([{type:`delete`,path:i,entryType:e}]),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(e){let n=r(e),i=this.findMount(n);if(i){if(i.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 e=i.relParts.join(`/`);try{let t=await i.backend.stat(e);return{type:t.kind===`directory`?`directory`:`file`,size:t.size,mtime:t.mtime,ctime:t.mtime}}catch(e){t.rebrandFsError(e,n)}}let a=await this.resolveSymlinks(n);try{let e=await this.lfs.stat(a);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=r(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){let n=r(e),i=r(t),a;try{a=(await this.lstat(n)).type}catch{}try{await this.lfs.rename(n,i)}catch(e){throw this.convertError(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:a},{type:`create`,path:i,entryType:a}]),this.mountIndex.notifyRename(n,i)}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){let i=r(e);if(this.canUseWalkFastPath(i)){let e=this.mountIndex.getFiles(i);if(e){for(let t of e)yield t;return}}let a=t??new Set;if(n>N||a.size>=P)return;let o=await this.safeRealpath(i);if(a.has(o))return;a.add(o);let s=await this.readDir(i);for(let e of s){let t=i===`/`?`/${e.name}`:`${i}/${e.name}`;yield*this.walkEntry(e,t,a,n+1)}}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,r){if(e.type===`file`){yield t;return}if(e.type===`symlink`){yield*this.walkSymlink(t,n,r);return}yield*this.walk(t,n,r)}async*walkSymlink(e,t,n){try{let r=await this.stat(e);r.type===`file`?yield e:r.type===`directory`&&(yield*this.walk(e,t,n))}catch{}}async copyFile(e,t){if((await this.stat(e)).type===`directory`)throw new o(`EISDIR`,`is a directory`,e);let n=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,n)}dirname(e){return n(r(e)).dir}basename(e){return n(r(e)).base}async symlink(e,t){let i=r(t);if(this.findMount(i))throw new o(`EINVAL`,`symlinks not supported on mounted filesystems`,i);let{dir:a}=n(i);a!==`/`&&await this.mkdir(a,{recursive:!0});try{await this.lfs.symlink(e,i)}catch(e){throw this.convertError(e,i)}this.watcher?.notify([{type:`create`,path:i,entryType:`symlink`}])}async readlink(e){let t=r(e);try{return await this.lfs.readlink(t)}catch(e){throw this.convertError(e,t)}}async lstat(e){let t=r(e);if(this.findMount(t))return this.stat(t);try{let e=await this.lfs.lstat(t);if(e.isSymbolicLink()){let n=await this.lfs.readlink(t);return{type:`symlink`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,isSymlink:!0,symlinkTarget:n}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs}}catch(e){throw this.convertError(e,t)}}async realpath(e){let t=r(e);if(this.findMount(t))return t;let n=t.split(`/`).filter(Boolean),i=`/`,a=0;for(let e=0;e<n.length;e++){let r=await this.resolveRealpathComponent(i,n[e],e===n.length-1,t,a);i=r.resolved,a=r.hops}return i}async resolveRealpathComponent(e,t,n,r,i){let a=e===`/`?`/${t}`:`${e}/${t}`;for(;;){let e=await this.lstatOrThrow(a,n,r);if(e===null||!e.isSymbolicLink())return{resolved:a,hops:i};if(++i>M)throw new o(`ELOOP`,`too many symbolic links encountered`,r);a=await this.readAndResolveLink(a,r)}}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 i;try{i=await this.lfs.readlink(e)}catch(e){throw this.convertError(e,t)}return i.startsWith(`/`)?r(i):r(a(n(e).dir,i))}async resolveSymlinks(e){return this.findMount(e)?e:this.realpath(e)}convertError(e,t){if(e instanceof o)return e;let n=e?.code;if(typeof n==`string`){let r=n;if([`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`EIO`].includes(r))return new o(r,(e instanceof Error?e.message:String(e))||r,t)}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new o(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new o(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new o(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new o(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new o(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new o(`ELOOP`,`too many levels of symbolic links`,t):new o(`EINVAL`,r,t)}};export{o as FsError,h as FsWatcher,k as MountIndex,j as RestrictedFS,I as VirtualFS,a as joinPath,r as normalizePath,i as pathSegments,F as resolveVfsBackendFromEnv,n as splitPath};
@@ -1 +1 @@
1
- import{i as e}from"./proxied-fetch-BVw2cmL4.js";import{O as t,i as n,p as r}from"./account-store-B1E9Pd8V.js";import{S as i,h as a,x as o}from"./kernel-worker-DyWWTo8W.js";import{n as s}from"./adobe-oauth-state---RmeoFk.js";import{getOAuthPageOrigin as c}from"./oauth-service-CPJvHYuO.js";var l={clientId:``,scopes:`repo,read:user,user:email`};function u(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return o}async function d(e){let t=`${u()}/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 f(e){let t=`${u()}/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 p=Object.assign({"/packages/webapp/providers/github-config.json":l})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let m=null,h=null;function g(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function _(){if(m)return m;if(v){try{let e=await fetch(`${u()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return m=t.oauth.github,m}}catch{}return p.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return m=t.oauth.github,m;if(t.trayWorkerBaseUrl){h=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return m=t.oauth.github,m}}}}catch{}return p.clientId}const v=typeof chrome<`u`&&!!chrome?.runtime?.id;function y(){return n().find(e=>e.providerId===`github`)}function b(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function x(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 S(e,t){return`${e}+${t}@users.noreply.github.com`}async function C(e){try{let{VirtualFS:t}=await import(`./fs-D3KOaEAt.js`).then(e=>e.t);await(await t.create({dbName:a})).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 w(){try{let{VirtualFS:e}=await import(`./fs-D3KOaEAt.js`).then(e=>e.t);await(await e.create({dbName:a})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function T(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await import(`./fs-D3KOaEAt.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:r}=await import(`./kernel-worker-DyWWTo8W.js`).then(e=>e.m),i=await t.create({dbName:a}),o=e.name||e.login,s=S(e.id,e.login);!await n(i,`user.name`)&&o&&await r(i,`user.name`,o),await n(i,`user.email`)||await r(i,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}async function E(){let e=y();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);return e.accessToken}const D={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(n,i,a)=>{let o=await _();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??p.scopes,l=v?null:await c(),f=crypto.randomUUID(),m=v?chrome.runtime.id:``,{redirectUri:y,state:S}=g({isExtension:v,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:u(),runtimeWorkerBaseUrl:h,pageOrigin:l?.origin??null,pageHref:l?.href??null,bridgeApiBaseUrl:e(),extensionId:m,nonce:f}),E=btoa(JSON.stringify(S)),D=f,O=new URLSearchParams({client_id:o,scope:s,redirect_uri:y});E&&O.set(`state`,E);let k=await n(`https://github.com/login/oauth/authorize?${O}`);if(!k)return;if(D)try{if(new URL(k).searchParams.get(`nonce`)!==D){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 A=b(k);if(!A){console.error(`[github] Could not extract authorization code from redirect URL`);return}let j=await d({provider:`github`,code:A,redirectUri:y}),M=await x(j.access_token);await t({providerId:`github`,accessToken:j.access_token,userName:M.name,userAvatar:M.avatar});let N=r(`github`)?.maskedValue;N?await C(N):await w(),await T(M),i()},onOAuthLogout:async()=>{let e=y();e?.accessToken&&await f({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await w(),await t({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{S as buildNoreplyEmail,D as config,b as extractCodeFromUrl,E as getValidAccessToken,g as resolveGithubOAuthRedirect,T as syncGitIdentityFromGitHub};
1
+ import{i as e}from"./proxied-fetch-BVw2cmL4.js";import{O as t,i as n,p as r}from"./account-store-DxGFDdq8.js";import{S as i,h as a,x as o}from"./kernel-worker-DEUwy4mF.js";import{n as s}from"./adobe-oauth-state---RmeoFk.js";import{getOAuthPageOrigin as c}from"./oauth-service-CPJvHYuO.js";var l={clientId:``,scopes:`repo,read:user,user:email`};function u(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return o}async function d(e){let t=`${u()}/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 f(e){let t=`${u()}/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 p=Object.assign({"/packages/webapp/providers/github-config.json":l})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let m=null,h=null;function g(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function _(){if(m)return m;if(v){try{let e=await fetch(`${u()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return m=t.oauth.github,m}}catch{}return p.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return m=t.oauth.github,m;if(t.trayWorkerBaseUrl){h=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return m=t.oauth.github,m}}}}catch{}return p.clientId}const v=typeof chrome<`u`&&!!chrome?.runtime?.id;function y(){return n().find(e=>e.providerId===`github`)}function b(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function x(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 S(e,t){return`${e}+${t}@users.noreply.github.com`}async function C(e){try{let{VirtualFS:t}=await import(`./fs-BCVRi4jH.js`).then(e=>e.t);await(await t.create({dbName:a})).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 w(){try{let{VirtualFS:e}=await import(`./fs-BCVRi4jH.js`).then(e=>e.t);await(await e.create({dbName:a})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function T(e){if(!(!e.login||e.id===void 0))try{let{VirtualFS:t}=await import(`./fs-BCVRi4jH.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:r}=await import(`./kernel-worker-DEUwy4mF.js`).then(e=>e.m),i=await t.create({dbName:a}),o=e.name||e.login,s=S(e.id,e.login);!await n(i,`user.name`)&&o&&await r(i,`user.name`,o),await n(i,`user.email`)||await r(i,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}async function E(){let e=y();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);return e.accessToken}const D={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(n,i,a)=>{let o=await _();if(!o)throw Error(`GitHub OAuth not configured — no client ID available`);let s=a?.scopes??p.scopes,l=v?null:await c(),f=crypto.randomUUID(),m=v?chrome.runtime.id:``,{redirectUri:y,state:S}=g({isExtension:v,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:u(),runtimeWorkerBaseUrl:h,pageOrigin:l?.origin??null,pageHref:l?.href??null,bridgeApiBaseUrl:e(),extensionId:m,nonce:f}),E=btoa(JSON.stringify(S)),D=f,O=new URLSearchParams({client_id:o,scope:s,redirect_uri:y});E&&O.set(`state`,E);let k=await n(`https://github.com/login/oauth/authorize?${O}`);if(!k)return;if(D)try{if(new URL(k).searchParams.get(`nonce`)!==D){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 A=b(k);if(!A){console.error(`[github] Could not extract authorization code from redirect URL`);return}let j=await d({provider:`github`,code:A,redirectUri:y}),M=await x(j.access_token);await t({providerId:`github`,accessToken:j.access_token,userName:M.name,userAvatar:M.avatar});let N=r(`github`)?.maskedValue;N?await C(N):await w(),await T(M),i()},onOAuthLogout:async()=>{let e=y();e?.accessToken&&await f({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await w(),await t({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{S as buildNoreplyEmail,D as config,b as extractCodeFromUrl,E as getValidAccessToken,g as resolveGithubOAuthRedirect,T as syncGitIdentityFromGitHub};