sliccy 6.248.13 → 6.248.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ui/.vite/manifest.json +473 -473
- package/dist/ui/assets/{account-store-D4Humqb-.js → account-store-C8ku_32k.js} +2 -2
- package/dist/ui/assets/{account-store-AloIt5Ss.js → account-store-CLrcVXc0.js} +1 -1
- package/dist/ui/assets/{adobe-COzZgYMJ.js → adobe-Cpi2aE-H.js} +1 -1
- package/dist/ui/assets/{adobe-DzPNN5WH.js → adobe-ZF88lAqt.js} +2 -2
- package/dist/ui/assets/{agent-panels-C7WGWk6D.js → agent-panels-BeptN8xj.js} +1 -1
- package/dist/ui/assets/{almost-bash-shell-headless--HYnQClo.js → almost-bash-shell-headless-BVria6dz.js} +12 -12
- package/dist/ui/assets/{anthropic-messages-BPiITV7m.js → anthropic-messages-pITcoTin.js} +3 -3
- package/dist/ui/assets/{apply-layout-C4DLtjYf.js → apply-layout-mZoFZ7NI.js} +1 -1
- package/dist/ui/assets/{azure-openai-DCtV7Fk7.js → azure-openai-BuzUN1Zv.js} +1 -1
- package/dist/ui/assets/{azure-openai-qBC0T6wP.js → azure-openai-D8taz7yq.js} +1 -1
- package/dist/ui/assets/{azure-openai-responses-CYEKOLNU.js → azure-openai-responses-BzfTIQxM.js} +1 -1
- package/dist/ui/assets/{backend-hostfs-C_GQqMGj.js → backend-hostfs-BlwgXw0-.js} +1 -1
- package/dist/ui/assets/{bedrock-camp-BRe8SyVL.js → bedrock-camp-Drg4mDwe.js} +1 -1
- package/dist/ui/assets/{capability-ChjrBUX1.js → capability-COwjFLjM.js} +2 -2
- package/dist/ui/assets/{cdp-CCSeAKYa.js → cdp-BECQB1rP.js} +1 -1
- package/dist/ui/assets/{cerebras-D05pSaD3.js → cerebras-DZZFW27U.js} +1 -1
- package/dist/ui/assets/{cerebras-BlBAjiPm.js → cerebras-DfDfqh_L.js} +1 -1
- package/dist/ui/assets/{classifier-shared-2vXBXYjG.js → classifier-shared-1BfNmzbv.js} +1 -1
- package/dist/ui/assets/{cloudflare-workers-ai-system-one-gkmS2Nb_.js → cloudflare-workers-ai-system-one-CYstFSnj.js} +1 -1
- package/dist/ui/assets/{compat-d34y6SaJ.js → compat-TaBTsXFP.js} +2 -2
- package/dist/ui/assets/{composer-speech-ZEQzpxXl.js → composer-speech-B1kWFuju.js} +1 -1
- package/dist/ui/assets/{connect-surface-DVe7YnEx.js → connect-surface-CXFbDGll.js} +1 -1
- package/dist/ui/assets/{core-DfJhnyZb.js → core-kdG72Y8N.js} +1 -1
- package/dist/ui/assets/{directed-approval-DpSG1Fn9.js → directed-approval-LQT_TPqz.js} +1 -1
- package/dist/ui/assets/{discovery-preference-DZcZKow3.js → discovery-preference-C-pw_A76.js} +1 -1
- package/dist/ui/assets/{dist-BZDZf9iZ.js → dist-AEgtkPbB.js} +1 -1
- package/dist/ui/assets/{dist-sPwgAbDH.js → dist-BOzr2Ip-.js} +1 -1
- package/dist/ui/assets/{dist-C3U_YVHW.js → dist-CKtiDzqm.js} +1 -1
- package/dist/ui/assets/{dist-Dxh_321I.js → dist-Cr80TbAt.js} +1 -1
- package/dist/ui/assets/{dist-Bkks4gfH.js → dist-DMTrP4j6.js} +1 -1
- package/dist/ui/assets/{dist-CTibI9AZ.js → dist-EaD2nXS1.js} +1 -1
- package/dist/ui/assets/{emscripten-vfs-hook-rbqoLuA5.js → emscripten-vfs-hook-CnPmEK30.js} +1 -1
- package/dist/ui/assets/{env-api-keys-Ds64PXJ4.js → env-api-keys-Cfrk_k8Z.js} +1 -1
- package/dist/ui/assets/esp8266-mbfP83qK.js +1 -0
- package/dist/ui/assets/{esptool-operations-CndxwE1S.js → esptool-operations-CTZQdeQU.js} +2 -2
- package/dist/ui/assets/{float-topology-PI5i_WsZ.js → float-topology-DJxhvO9u.js} +1 -1
- package/dist/ui/assets/{follower-navigate-watcher-B3g-lkMJ.js → follower-navigate-watcher-BThbqvla.js} +1 -1
- package/dist/ui/assets/{frozen-archive-writer-D6ckorva.js → frozen-archive-writer-BTbtadrW.js} +1 -1
- package/dist/ui/assets/{frozen-archive-writer-ClcpBoUl.js → frozen-archive-writer-CUzf7C3s.js} +1 -1
- package/dist/ui/assets/{frozen-session-delete-_74oIhfQ.js → frozen-session-delete-CyRcONHk.js} +1 -1
- package/dist/ui/assets/{frozen-session-identity-DW7M6tap.js → frozen-session-identity-BCGVU2K1.js} +1 -1
- package/dist/ui/assets/{frozen-session-identity-DRez4L_k.js → frozen-session-identity-DVcpz2HB.js} +1 -1
- package/dist/ui/assets/{fs-CQpIxK2e.js → fs-DSnZb1DK.js} +2 -2
- package/dist/ui/assets/{gelatiere-unit-DY9kFx7W.js → gelatiere-unit-CLfqVD6U.js} +1 -1
- package/dist/ui/assets/{github-BAVQKGLM.js → github--CcFgkAY.js} +2 -2
- package/dist/ui/assets/{github-seYRLByd.js → github-ChxmjcJc.js} +1 -1
- package/dist/ui/assets/{github-copilot-NuiVJlRe.js → github-copilot-Bt2MljG0.js} +1 -1
- package/dist/ui/assets/{github-copilot-B2ui266i.js → github-copilot-DRF3abOV.js} +1 -1
- package/dist/ui/assets/{google-generative-ai-y59nuAoz.js → google-generative-ai-_4RGA5R9.js} +1 -1
- package/dist/ui/assets/{google-shared-BixQtMJk.js → google-shared-BmjkwexI.js} +1 -1
- package/dist/ui/assets/{google-vertex-BuV_pgMi.js → google-vertex-CCT-gmBZ.js} +1 -1
- package/dist/ui/assets/{hear-LEawuxbU.js → hear-BGGOzrLe.js} +1 -1
- package/dist/ui/assets/icons-CPOTRcvO.js +1 -0
- package/dist/ui/assets/{js-realm-worker-BQ2E7b6Z.js → js-realm-worker-Qikr6DIj.js} +2 -2
- package/dist/ui/assets/{jsh-executor-BA7Owezg.js → jsh-executor-Cduj8RKN.js} +3 -3
- package/dist/ui/assets/{kernel-worker-Bl7wfxQy.js → kernel-worker-DKhuL-SB.js} +8 -8
- package/dist/ui/assets/{kokoro-g58mp2Gg.js → kokoro-BZ2oL9at.js} +1 -1
- package/dist/ui/assets/{legacy-api-aliases-DZ7QKXPR.js → legacy-api-aliases-BqXqjuwj.js} +1 -1
- package/dist/ui/assets/{legacy-styles-CbYwED5J.js → legacy-styles-CGcVbQni.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-BIajXq6B.js → lick-ws-bridge-Bgd2UUqy.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-BEHNQbo5.js → lick-ws-bridge-Cy-M-w5Q.js} +1 -1
- package/dist/ui/assets/{live-session-curation-BJVU7yfS.js → live-session-curation-DKF46wEh.js} +1 -1
- package/dist/ui/assets/{live-session-curation-C8cnTFuk.js → live-session-curation-w6IDH4Wx.js} +1 -1
- package/dist/ui/assets/{live-session-snapshot-DB7ATVqO.js → live-session-snapshot-DCT_jWTD.js} +1 -1
- package/dist/ui/assets/{local-llm-Dxm6T0ph.js → local-llm-BzQlnS5L.js} +1 -1
- package/dist/ui/assets/{local-llm-B72jeBdJ.js → local-llm-DUc-GBj9.js} +1 -1
- package/dist/ui/assets/{main-pG2z7nDr.js → main-CWx8ZbOh.js} +3 -3
- package/dist/ui/assets/{main-cherry-Cndxk3tr.js → main-cherry-qefabkXK.js} +1 -1
- package/dist/ui/assets/{mcp-command-R_syvmA2.js → mcp-command-BMbHOLse.js} +10 -10
- package/dist/ui/assets/{memory-curation-seam-xAt4_ZGt.js → memory-curation-seam-DqgqK6CR.js} +1 -1
- package/dist/ui/assets/{memory-health-N-Qft3RQ.js → memory-health-CyDp9rny.js} +1 -1
- package/dist/ui/assets/{memory-write-execute-CcPwzxh2.js → memory-write-execute-mLtLK-OJ.js} +1 -1
- package/dist/ui/assets/{merge-folded-cost-into-frozen-D5QzQftk.js → merge-folded-cost-into-frozen-VpR7-OO_.js} +1 -1
- package/dist/ui/assets/{mistral-conversations-BbeDfELF.js → mistral-conversations-BTfu6zaw.js} +1 -1
- package/dist/ui/assets/{models-K_BYbYJy.js → models-DuCVW_cU.js} +1 -1
- package/dist/ui/assets/{mount-Cvx8MHrJ.js → mount-iiKbRe20.js} +1 -1
- package/dist/ui/assets/{new-session-CzmqZfEw.js → new-session-pyHdj7ky.js} +2 -2
- package/dist/ui/assets/{node.browser-D-KuY2NZ.js → node.browser-POTNsJTJ.js} +1 -1
- package/dist/ui/assets/{oauth-bootstrap-BgBpgpMH.js → oauth-bootstrap-4_xLQ_sb.js} +2 -2
- package/dist/ui/assets/{oauth-service-C9_em2OO.js → oauth-service-BTbFz00g.js} +1 -1
- package/dist/ui/assets/{onboarding-orchestrator-B0EOdDeN.js → onboarding-orchestrator-CjdNWdMC.js} +1 -1
- package/dist/ui/assets/{openai-codex-CBBCnX5G.js → openai-codex-4_vQIXxb.js} +1 -1
- package/dist/ui/assets/{openai-codex-responses-CsoNnMnP.js → openai-codex-responses-BQf_Un8s.js} +1 -1
- package/dist/ui/assets/{openai-codex-BuzdyFkb.js → openai-codex-uQMjU0_s.js} +1 -1
- package/dist/ui/assets/{openai-completions-CwpTiqkV.js → openai-completions-UyX4inUN.js} +1 -1
- package/dist/ui/assets/{openai-decisions-C2a995aZ.js → openai-decisions-6D6eupBk.js} +1 -1
- package/dist/ui/assets/{openai-responses-CXxDIIaJ.js → openai-responses-Bn1YXtN4.js} +1 -1
- package/dist/ui/assets/{openai-responses-shared-Df32ziOu.js → openai-responses-shared-CHC7SqmI.js} +1 -1
- package/dist/ui/assets/{openrouter-CajNnUyi.js → openrouter-DneJqayx.js} +1 -1
- package/dist/ui/assets/{openrouter-yrPyWZSZ.js → openrouter-TLjYxLOJ.js} +1 -1
- package/dist/ui/assets/{openrouter-free-CoKNk8Q9.js → openrouter-free-C9Ks_BoF.js} +1 -1
- package/dist/ui/assets/{openrouter-free-DvQSB466.js → openrouter-free-QijswzXp.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-Cwnv6aaR.js → openrouter-oauth-C3NFC0lq.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-Dm2bFG2r.js → openrouter-oauth-CWRFCzx3.js} +1 -1
- package/dist/ui/assets/{opfs-mount-DqwXxpJI.js → opfs-mount-DHQkCQyR.js} +1 -1
- package/dist/ui/assets/{page-approval-service-BV4pp4cE.js → page-approval-service-1D_bhphG.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-0Asc887-.js → panel-rpc-handlers-DJTIyg19.js} +2 -2
- package/dist/ui/assets/{panelize-shell-CYWV616_.js → panelize-shell-KnM6qBOd.js} +1 -1
- package/dist/ui/assets/{pi-edit-execution-DUHiH3Ek.js → pi-edit-execution-KjYZMQ1M.js} +1 -1
- package/dist/ui/assets/{pi-transcript-context-M0uAa_Rs.js → pi-transcript-context-BD-rasES.js} +1 -1
- package/dist/ui/assets/preload-helper-BLdHbfdN.js +1 -0
- package/dist/ui/assets/{provider-gVV-Tw2o.js → provider-BUOENNXd.js} +1 -1
- package/dist/ui/assets/{provider-DQEpec-V.js → provider-C6GKyGbH.js} +2 -2
- package/dist/ui/assets/{provider-settings-HdIWRUQi.js → provider-settings-DiWaVtMa.js} +1 -1
- package/dist/ui/assets/provider-store-access-BLah3TfA.js +1 -0
- package/dist/ui/assets/provider-store-access-DK9jcMFs.js +1 -0
- package/dist/ui/assets/{providers-BPtyhTCJ.js → providers-D98KfVHw.js} +2 -2
- package/dist/ui/assets/{providers-BqUoo02I.js → providers-DQDxShvT.js} +1 -1
- package/dist/ui/assets/{proxied-fetch-Co-YYDT9.js → proxied-fetch-Dcpb4ieV.js} +1 -1
- package/dist/ui/assets/{proxied-fetch-raw-C_Y--MLW.js → proxied-fetch-raw-DFOSVEWz.js} +1 -1
- package/dist/ui/assets/{quick-llm-DKIeT-Bm.js → quick-llm-BpqDA4jj.js} +1 -1
- package/dist/ui/assets/{realm-inprocess-I1Oa37_B.js → realm-inprocess-DB9T1J06.js} +2 -2
- package/dist/ui/assets/{realm-unhandled-rejections-5totJ0nZ.js → realm-unhandled-rejections--yhMR2JG.js} +1 -1
- package/dist/ui/assets/{realm-unhandled-rejections-Vf408gQs.js → realm-unhandled-rejections-C-dWyWFT.js} +1 -1
- package/dist/ui/assets/{recovery-screen-d6N9mctq.js → recovery-screen-DxmS11pP.js} +1 -1
- package/dist/ui/assets/{remote-terminal-view-B8EZ4je-.js → remote-terminal-view-CKT9I4xa.js} +3 -3
- package/dist/ui/assets/{rest-ops-Bu4Fgr3O.js → rest-ops-DUxY6dMv.js} +1 -1
- package/dist/ui/assets/{restore-YHJZnRoZ.js → restore-DBVHFRDn.js} +1 -1
- package/dist/ui/assets/{run-Ds5q8C_n.js → run-B2qNRdiQ.js} +2 -2
- package/dist/ui/assets/{run-qBD2W0pE.js → run-D6GtWFc7.js} +1 -1
- package/dist/ui/assets/{run-QN9mmLnD.js → run-DWu38u8c.js} +1 -1
- package/dist/ui/assets/{run-jEnj-WXZ.js → run-DxF2t6YH.js} +2 -2
- package/dist/ui/assets/{secret-env-Da2LI-Wl.js → secret-env-BDj2iVgu.js} +1 -1
- package/dist/ui/assets/secret-topology-CcM8VDVI.js +1 -0
- package/dist/ui/assets/{serve-command-ClUJJ3EB.js → serve-command-Cj91wHBd.js} +2 -2
- package/dist/ui/assets/{serve-runtime-WdVepvEi.js → serve-runtime-C6U19az5.js} +1 -1
- package/dist/ui/assets/{session-command-memory-CQnSNVmV.js → session-command-memory-DTJrpKQG.js} +2 -2
- package/dist/ui/assets/{session-jsonl-BGHEGuWx.js → session-jsonl-CUGtVDjz.js} +1 -1
- package/dist/ui/assets/{session-jsonl-BjBaj5ud.js → session-jsonl-PBSNVf5N.js} +1 -1
- package/dist/ui/assets/{session-search-index-DFWu63Zi.js → session-search-index-BmWzdxol.js} +1 -1
- package/dist/ui/assets/{setup-feature-flags-remote-CUbaBhWB.js → setup-feature-flags-remote-Dcyvcm1c.js} +1 -1
- package/dist/ui/assets/{setup-model-catalog-CykSe_Dx.js → setup-model-catalog-9sIjZkxM.js} +1 -1
- package/dist/ui/assets/{setup-sprinkle-exec-IU4qWikH.js → setup-sprinkle-exec-CdgElwNt.js} +1 -1
- package/dist/ui/assets/{silent-renew-backoff-BMr_pGCU.js → silent-renew-backoff-B9OHOzRe.js} +1 -1
- package/dist/ui/assets/{slicc-diff-D8v8ZLu9.js → slicc-diff-BfQJcIZe.js} +1 -1
- package/dist/ui/assets/{slicc-editor-CEzmoAZr.js → slicc-editor-CasndIRU.js} +3 -3
- package/dist/ui/assets/slicc-editor-tCvqLLxb.js +1 -0
- package/dist/ui/assets/slicc-version-QFUwKumj.js +1 -0
- package/dist/ui/assets/{soundscape-Blo80kkF.js → soundscape-BotaZrDR.js} +1 -1
- package/dist/ui/assets/{speak-DYYfW_FH.js → speak-DHpjynd6.js} +3 -3
- package/dist/ui/assets/{sprinkle-manager-6IcFnb1j.js → sprinkle-manager-8dcg9Iza.js} +1 -1
- package/dist/ui/assets/{sprinkle-renderer-BnGOcTUx.js → sprinkle-renderer-D0vfMqnl.js} +3 -3
- package/dist/ui/assets/{sudo-cs2WnTRn.js → sudo-CNQ60foM.js} +1 -1
- package/dist/ui/assets/{supervisor-BULFrqrk.js → supervisor-CPH3uat9.js} +1 -1
- package/dist/ui/assets/{sync-dialog-MmcHaZwh.js → sync-dialog-DcHJ8wDd.js} +1 -1
- package/dist/ui/assets/{system-one-shared-DLgt2600.js → system-one-shared-sVc-bQkc.js} +1 -1
- package/dist/ui/assets/{telemetry-BqfutULb.js → telemetry-kqkj0A7x.js} +1 -1
- package/dist/ui/assets/{transform-messages-Bx3wQh2R.js → transform-messages-HTSSP3zz.js} +1 -1
- package/dist/ui/assets/{transformers-env-Fm5j4giD.js → transformers-env-C4aTP2JX.js} +1 -1
- package/dist/ui/assets/{transformers.web-BR6ghS6P.js → transformers.web-C5VLk0m7.js} +1 -1
- package/dist/ui/assets/{tray-leader-CFIVvD5G.js → tray-leader-BO7RLnAz.js} +1 -1
- package/dist/ui/assets/{tray-leave-runtime-BSxSDTw5.js → tray-leave-runtime-DrPHvVi6.js} +1 -1
- package/dist/ui/assets/{tray-sidecar-DQqVkAjk.js → tray-sidecar-BF8y2nH9.js} +1 -1
- package/dist/ui/assets/{typesafe-system-one-CXEHNzQF.js → typesafe-system-one-BdxxnbQu.js} +1 -1
- package/dist/ui/assets/{upgrade-detection-MAFg6kZz.js → upgrade-detection-DYeqLwkQ.js} +1 -1
- package/dist/ui/assets/{usb-operations-Ccb6x34d.js → usb-operations-DvSWlz_Y.js} +1 -1
- package/dist/ui/assets/{voice-reply-Bum2oQcA.js → voice-reply-DVgxPsp4.js} +1 -1
- package/dist/ui/assets/{warm-wterm-C7ml3_29.js → warm-wterm-snqvCS0-.js} +1 -1
- package/dist/ui/assets/{wc-attach-BJHnH6pd.js → wc-attach-DtB955Cg.js} +3 -3
- package/dist/ui/assets/{wc-browser-sNhsHdWm.js → wc-browser-5eX1yDaM.js} +1 -1
- package/dist/ui/assets/{wc-computers-CWg9NiMK.js → wc-computers-BQe7QGA5.js} +1 -1
- package/dist/ui/assets/{wc-detached-DZvftcPT.js → wc-detached-B448Oceh.js} +1 -1
- package/dist/ui/assets/{wc-extension-BaYtWo4q.js → wc-extension-DcxJvbXQ.js} +2 -2
- package/dist/ui/assets/{wc-follower-C3skKl26.js → wc-follower-C4HBJRkp.js} +3 -3
- package/dist/ui/assets/{wc-follower-oauth-iJKLKYov.js → wc-follower-oauth-DWB_1KrV.js} +1 -1
- package/dist/ui/assets/{wc-gelatiere-DaysrnKa.js → wc-gelatiere-DNuoJgyp.js} +1 -1
- package/dist/ui/assets/{wc-live-DEo-6NQK.js → wc-live-BMXg1cW0.js} +5 -5
- package/dist/ui/assets/{wc-nav-DqmL5N5I.js → wc-nav-C4cQdKiF.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-Dg7G2Ykz.js → wc-onboarding-CsrFGEQ2.js} +2 -2
- package/dist/ui/assets/{wc-permissions-wBb5q-ot.js → wc-permissions-DMVzE1os.js} +3 -3
- package/dist/ui/assets/{wc-permissions-providers-r97Cs0CM.js → wc-permissions-providers-CzfeTK0C.js} +1 -1
- package/dist/ui/assets/{wc-placeholder-Dcqr3sQ2.js → wc-placeholder-BSqm7GOK.js} +3 -3
- package/dist/ui/assets/{wc-secret-request-DLngmY78.js → wc-secret-request-BMp1_Dqa.js} +1 -1
- package/dist/ui/assets/{wc-settings-DhxNLvFd.js → wc-settings-D_rtZFP8.js} +3 -3
- package/dist/ui/assets/{wc-shell-RF_bfAGN.js → wc-shell-CbiYuC-u.js} +6 -6
- package/dist/ui/assets/{wc-shortcut-config-Cr8zuZad.js → wc-shortcut-config-Dit9NqHJ.js} +1 -1
- package/dist/ui/assets/{wc-sprinkles-DyMWm1jp.js → wc-sprinkles-CRU3Bd1x.js} +2 -2
- package/dist/ui/assets/{wc-transcript-export-DVyU4B6b.js → wc-transcript-export-CCBgVRIb.js} +2 -2
- package/dist/ui/assets/{wc-tray-BjkHiwAE.js → wc-tray-DMpwCD-i.js} +4 -4
- package/dist/ui/assets/welcome-detection-CMa9jsjd.js +1 -0
- package/dist/ui/assets/{whisper-session-nBcuStI7.js → whisper-session-DOG-n_Gl.js} +2 -2
- package/dist/ui/assets/{xai-grok-B0VdJo2K.js → xai-grok-BwRAMV0b.js} +1 -1
- package/dist/ui/assets/{xai-grok-B-1EsChx.js → xai-grok-D-s6Eti2.js} +1 -1
- package/dist/ui/index.html +12 -12
- package/dist/ui/lucide-icons.js +362 -359
- package/dist/ui/packages/webapp/index.html +12 -12
- package/dist/ui/slicc-diff.js +1 -1
- package/dist/ui/slicc-editor.js +1 -1
- package/package.json +2 -2
- package/dist/ui/assets/esp8266-6UF0nYRf.js +0 -1
- package/dist/ui/assets/icons-BUdZEBvI.js +0 -1
- package/dist/ui/assets/preload-helper-DjzSQ1t3.js +0 -1
- package/dist/ui/assets/provider-store-access-BG9uc1UB.js +0 -1
- package/dist/ui/assets/provider-store-access-CkviLtwb.js +0 -1
- package/dist/ui/assets/secret-topology-B-7q9k0Q.js +0 -1
- package/dist/ui/assets/slicc-editor-CnQU3MQS.js +0 -1
- package/dist/ui/assets/slicc-version-D_fWoQ7a.js +0 -1
- package/dist/ui/assets/welcome-detection-ZKXELBPe.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-C8GTDH_7.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/buffer-BeQa_9BU.js","assets/opfs-mount-
|
|
2
|
-
import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./preload-helper-DjzSQ1t3.js";import{t as n}from"./logger-DDBAeTLF.js";import{n as r,t as i}from"./same-file-identity-OexpsaSD.js";import{n as a,t as o}from"./types-D8gIX-W-.js";import{a as s,i as c,n as l,r as u,t as d}from"./path-utils-DNJG-zQf.js";import{r as ee,t as f}from"./bounded-walk-BjxKWNqp.js";import{n as te,t as ne}from"./virtual-device-paths-D45tpPP6.js";import{a as re,i as ie,n as ae,t as oe}from"./mount-table-store-dY2IfQ5S.js";var p=n(`fs-watcher`),se=0;function ce(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var m=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++se}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),p.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),p.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>ce(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){p.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),p.debug(`All watchers disposed`)}get size(){return this.registrations.size}},h=n(`mount-index`),le=400,ue=2e6,de=`SLICC_MOUNT_INDEX_MAX_DEPTH`,fe=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,g=256,_=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function pe(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>g?t.slice(0,g):t;return`${t.length}\u0001${n.join(``)}`}async function v(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function me(e,t){return e instanceof Map?e.get(t):e[t]}function he(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function y(e,t,n){let r=me(e,t);if(r===void 0||r.trim()===``)return n;let i=he(r);return i===void 0?(h.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function b(e){return{maxDepth:y(e,de,le),maxEntries:y(e,fe,ue),skipNoiseDirs:!0}}var x=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=b({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,childrenByDirectory:new Map,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(),n.childrenByDirectory.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=n.childrenByDirectory.get(t);if(r)return[...r].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`||this.isSkippedNoisePath(t,e,n,`file`))return;n.files.add(e),this.addPathToChildIndex(n,e,`file`);let r=this.parentPath(e);for(;(r===t||r.startsWith(`${t}/`))&&(n.directories.add(r),this.ensureDirectoryChildren(n,r),r!==t);)this.addPathToChildIndex(n,r,`directory`),r=this.parentPath(r)}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`||this.isSkippedNoisePath(t,e,n,`unknown`))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);this.removePathFromChildIndex(n,e);for(let t of n.childrenByDirectory.keys())(t===e||t.startsWith(r))&&n.childrenByDirectory.delete(t)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status!==`ready`)return;let i=r.files.has(e)?`file`:r.directories.has(e)?`directory`:`unknown`;if(i===`unknown`||this.isSkippedNoisePath(n,e,r,i))return;if(this.isSkippedNoisePath(n,t,r,i)){this.notifyDelete(e);return}if(i===`file`){r.files.delete(e),r.files.add(t),this.removePathFromChildIndex(r,e),this.addPathToChildIndex(r,t,`file`);return}r.directories.delete(e),r.directories.add(t);let a=e+`/`,o=t+`/`;for(let e of[...r.files])e.startsWith(a)&&(r.files.delete(e),r.files.add(o+e.slice(a.length)));for(let e of[...r.directories])e.startsWith(a)&&(r.directories.delete(e),r.directories.add(o+e.slice(a.length)));this.removePathFromChildIndex(r,e),this.addPathToChildIndex(r,t,`directory`);let s=[...r.childrenByDirectory.entries()].filter(([t])=>t===e||t.startsWith(a));for(let[e]of s)r.childrenByDirectory.delete(e);for(let[n,i]of s){let s=n===e?t:o+n.slice(a.length);r.childrenByDirectory.set(s,i)}}ensureDirectoryChildren(e,t){let n=e.childrenByDirectory.get(t);return n||(n=new Map,e.childrenByDirectory.set(t,n)),n}addPathToChildIndex(e,t,n){let r=t.slice(t.lastIndexOf(`/`)+1);r&&(this.ensureDirectoryChildren(e,this.parentPath(t)).set(r,n),n===`directory`&&this.ensureDirectoryChildren(e,t))}removePathFromChildIndex(e,t){let n=t.slice(t.lastIndexOf(`/`)+1);e.childrenByDirectory.get(this.parentPath(t))?.delete(n)}parentPath(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}isSkippedNoisePath(e,t,n,r){if(!n.limits.skipNoiseDirs||!t.startsWith(`${e}/`))return!1;let i=t.slice(e.length+1).split(`/`),a=r===`unknown`?n.files.has(t)?`file`:n.directories.has(t)?`directory`:`unknown`:r;for(let e=0;e<i.length;e++){let t=e===i.length-1;if(!(t&&a===`file`)&&(!t||a!==`unknown`||f(i[e]))&&f(i[e]))return!0}return!1}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,h.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},h.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),this.ensureDirectoryChildren(n,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=pe(n),a=r.get(i);if(a){for(let n of a)if(await v(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}`;if(s.kind===`file`)n.files.add(t),this.addPathToChildIndex(n,t,`file`),n.state.indexed++;else if(s.kind===`directory`){if(n.limits.skipNoiseDirs&&f(o))continue;this.addPathToChildIndex(n,t,`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)))}}},S=new TextEncoder,C=new TextDecoder(`utf-8`,{fatal:!1}),w=class{entries=new Map;static handles(e){return te(l(e))}has(e){return this.entries.has(l(e))}write(e,t){let n=l(e),r=typeof t==`string`?S.encode(t):new Uint8Array(t),i=Date.now(),a=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:i,ctime:a?.ctime??i})}append(e,t){let n=this.entries.get(l(e))?.bytes??new Uint8Array,r=typeof t==`string`?S.encode(t):t,i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),this.write(e,i)}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?C.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return C.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(l(e))}require(e){let t=l(e),n=this.entries.get(t);if(!n)throw new o(`ENOENT`,`no such file or directory`,t);return n}},T={[ne]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},E=[`/tmp/`],D=class{ephemeralFds=new w;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;includeMounts;constructor(e,t,n=[],r=`hard`,i={}){this.vfs=e;let a=e=>{let t=l(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=r,this.includeMounts=i.includeMounts!==!1}getAllPrefixes(){let e=this.includeMounts?this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`):[];return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...E]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(u(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:u(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=l(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=l(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=l(e);return[...this.allowedPrefixes,...E].some(e=>t===e.slice(0,-1)||t.startsWith(e))}readAccess(e){return T[l(e)]||w.handles(e)||this.isAllowedStrict(e)?`inside`:this.isAllowed(e)?`parent`:`outside`}canWrite(e){return w.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new o(`EACCES`,`permission denied`,l(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`,l(e));return t}catch(t){throw t instanceof o?t:new o(`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 o(`EACCES`,`permission denied`,l(e));return t}catch(t){throw t instanceof o?t:new o(`EACCES`,`permission denied`,l(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e;return}let i=r+`/`+n;if(this.isWritable(i))return;let a=l(r)!==l(t);if(this.writeEnforcement!==`sudo-delegated`||a)throw new o(`EACCES`,`permission denied`,l(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async forgetSidecarConsistency(){await this.vfs.forgetSidecarConsistency()}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=T[l(e)];if(n)return n.read(t);if(w.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,l(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readFileRange(e,t,n){if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,l(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFileRange(r,t,n)}async getNativeFile(e){if(T[l(e)]||w.handles(e)||!this.isAllowedStrict(e))return null;try{let t=await this.resolveAndCheckRead(e);return await this.vfs.getNativeFile(t)}catch{return null}}async readDir(e,t){if(!this.isAllowed(e))return[];let n=e;if(this.isAllowedStrict(e))try{n=await this.resolveAndCheckRead(e)}catch{return[]}let r=await this.vfs.readDir(n,t);if(!this.isAllowedStrict(e)){let t=l(e);return r.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return r}async stat(e){let t=T[l(e)];if(t)return t.stat();if(w.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new o(`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():w.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=T[l(e)];return t?t.stat():w.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!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){if(w.handles(e)){let t=l(e);if(!this.ephemeralFds.has(t))throw new o(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof o?t:new o(`ENOENT`,`no such file or directory`,l(e))}if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,l(e));return t}async exists(e){if(T[l(e)])return!0;if(w.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=T[l(e)];if(t)return t.readText();if(w.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new o(`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 r=T[l(e)];if(r){r.write(t);return}if(w.handles(e)){this.ephemeralFds.write(e,t);return}return await this.checkContentWrite(e),this.vfs.writeFile(e,t,n)}async appendFile(e,t){let n=T[l(e)];if(n){n.write(t);return}if(w.handles(e)){this.ephemeralFds.append(e,t);return}return await this.checkContentWrite(e),this.vfs.appendFile(e,t)}async chmod(e,t){return this.refuseDescriptorTreeOp(e),await this.checkContentWrite(e),this.vfs.chmod(e,t)}async utimes(e,t,n){return this.refuseDescriptorTreeOp(e),await this.checkContentWrite(e),this.vfs.utimes(e,t,n)}async updateMetadataBatch(e){for(let t of e)this.refuseDescriptorTreeOp(t.path),await this.checkContentWrite(t.path);return this.vfs.updateMetadataBatch(e)}async checkContentWrite(e){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}}refuseDescriptorTreeOp(e){if(w.handles(e))throw new o(`EACCES`,`permission denied`,l(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(w.handles(e)){if(!this.ephemeralFds.remove(e))throw new o(`ENOENT`,`no such file or directory`,l(e));return}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.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(w.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(w.handles(t)){if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,l(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new o(`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 o&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.symlinkBatch([{target:e,path:t}])}async symlinkBatch(e){if(e.length===0)return;let t=e.map(e=>({target:e.target,path:l(e.path)}));this.rejectNestedSymlinkBatchPaths(t.map(e=>e.path));for(let e of t)this.refuseDescriptorTreeOp(e.path),this.checkWrite(e.path),await this.checkParentRealpathEscape(e.path);return this.vfs.symlinkBatch(t)}rejectNestedSymlinkBatchPaths(e){for(let t=0;t<e.length;t++)for(let n=0;n<e.length;n++){if(t===n)continue;let r=e[n],i=e[t];if(i===r||i.startsWith(`${r}/`))throw new o(`EACCES`,`permission denied`,i)}}async readlink(e){if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,l(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=l(t);else{let r=this.vfs.dirname(e);n=l(r+`/`+t)}if(!this.isAllowedStrict(n))throw new o(`ENOENT`,`no such file or directory`,l(e));return t}async lstat(e){let t=T[l(e)];if(t)return t.stat();if(w.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,l(e));let n=l(e),r=this.vfs.dirname(n),i=this.vfs.basename(n),a;if(r===n)a=r;else try{a=await this.vfs.realpath(r)}catch{throw new o(`ENOENT`,`no such file or directory`,n)}let s=a===`/`?`/${i}`:`${a}/${i}`;if(!this.isAllowed(s))throw new o(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new o(`EACCES`,`permission denied`,l(e));let r=this.vfs.getWatcher();if(!r)throw new o(`EINVAL`,`no watcher configured`);return r.watch(l(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){let e=this.vfs.listMounts();return this.includeMounts?e:e.filter(e=>this.isAllowedStrict(e))}listMountPoints(){let e=this.vfs.listMountPoints();return this.includeMounts?e:e.filter(e=>this.isAllowed(e.path))}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function O(e,t){if(e instanceof o){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new o(e.code,r,t)}throw e}var ge=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EOPNOTSUPP`,`EXDEV`,`EIO`];function k(e,t){if(e instanceof o)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new o(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(ge.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new o(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new o(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new o(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new o(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new o(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new o(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new o(`ELOOP`,`too many levels of symbolic links`,t):r.includes(`EOPNOTSUPP`)||r.includes(`ENOTSUP`)?new o(`EOPNOTSUPP`,`operation not supported`,t):r.includes(`EXDEV`)?new o(`EXDEV`,`cross-device link`,t):new o(`EINVAL`,r,t)}var _e=61440,ve=16384;function A(e){return e===void 0?`absent`:(e&_e)===ve?`directory`:`file`}function j(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function M(e){let t=e?.mode;return typeof t==`number`?t:void 0}function ye(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=A(M(r));o!==A(M(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}var N=512,P=class e{kind=`local`;listingStatsMatchStat=!0;source=void 0;profile=void 0;mountId;handle;dirCacheMax;dirCache=new Map;closed=!1;constructor(e,t){this.handle=e,this.mountId=t.mountId,this.dirCacheMax=t.dirCacheMax??N}static fromHandle(t,n){return new e(t,n)}getHandle(){return this.handle}assertOpen(e){if(this.closed)throw new o(`EBADF`,`mount closed`,e)}splitPath(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(e=>e.length>0)}cacheGet(e){let t=this.dirCache.get(e);if(t!==void 0)return this.dirCache.delete(e),this.dirCache.set(e,t),t}cacheSet(e,t){for(this.dirCache.has(e)&&this.dirCache.delete(e),this.dirCache.set(e,t);this.dirCache.size>this.dirCacheMax;){let e=this.dirCache.keys().next();if(e.done)break;this.dirCache.delete(e.value)}}invalidate(e){if(e===``){this.dirCache.clear();return}let t=`${e}/`;for(let n of[...this.dirCache.keys()])(n===e||n.startsWith(t))&&this.dirCache.delete(n)}getDirCacheSize(){return this.dirCache.size}async resolveDirFrom(e,t,n,r=!0){let i=this.handle,a=``,o=0;if(r)for(let t=e.length;t>0;t--){let n=e.slice(0,t).join(`/`),r=this.cacheGet(n);if(r){i=r,a=n,o=t;break}}let s=a;for(;o<e.length;o++){let r=e[o];try{i=await i.getDirectoryHandle(r,{create:n})}catch(r){if(n&&s!==``)return this.invalidate(s),this.resolveDirFrom(e,t,n,!1);throw this.toFsError(r,t)}a=a===``?r:`${a}/${r}`,this.cacheSet(a,i)}return i}async resolveDir(e,t=!1){return this.resolveDirFrom(this.splitPath(e),e,t)}async resolveParent(e,t){let n=this.splitPath(e);if(n.length===0)throw new o(`EISDIR`,`is a directory`,e);let r=n.pop();return{parent:await this.resolveDirFrom(n,e,t),name:r}}async resolveFile(e,t=!1){let{parent:n,name:r}=await this.resolveParent(e,t);try{return await n.getFileHandle(r,{create:t})}catch(t){throw this.toFsError(t,e)}}toFsError(e,t){if(e instanceof o)return e;if(e instanceof DOMException){if(e.name===`NotFoundError`)return new o(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatchError`)return new o(`ENOTDIR`,`not a directory`,t);if(e.name===`NotAllowedError`)return new o(`EACCES`,`permission denied`,t);if(e.name===`InvalidModificationError`)return new o(`ENOTEMPTY`,`directory not empty`,t)}if(e instanceof Error){if(e.name===`NotFound`||e.name===`NotFoundError`)return new o(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatch`||e.name===`TypeMismatchError`)return new o(`ENOTDIR`,`not a directory`,t);if(e.name===`InvalidModification`||e.name===`InvalidModificationError`)return new o(`ENOTEMPTY`,`directory not empty`,t)}return new o(`EINVAL`,e instanceof Error?e.message:String(e),t)}async readDir(e,t){this.assertOpen(e);let n=await this.resolveDir(e),r=[];for await(let[e,i]of n){if(i.kind!==`file`){r.push({name:e,kind:`directory`});continue}if(!t?.includeStats){r.push({name:e,kind:`file`});continue}let n=await i.getFile();r.push({name:e,kind:`file`,size:n.size,lastModified:n.lastModified})}return r}async readFile(e){this.assertOpen(e);let t=await(await this.resolveFile(e)).getFile();return new Uint8Array(await t.arrayBuffer())}async getNativeFile(e){this.assertOpen(e);try{return await(await this.resolveFile(e)).getFile()}catch{return null}}async writeFile(e,t){this.assertOpen(e);let n=await(await this.resolveFile(e,!0)).createWritable();await n.write(t),await n.close()}async stat(e){this.assertOpen(e);let t=this.splitPath(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};let n=t.pop(),r=await this.resolveDirFrom(t,e,!1);try{let e=await(await r.getFileHandle(n)).getFile();return{kind:`file`,size:e.size,mtime:e.lastModified}}catch(t){let n=this.toFsError(t,e);if(n.code!==`ENOENT`&&n.code!==`ENOTDIR`)throw n}try{let e=await r.getDirectoryHandle(n);this.cacheSet(t.length===0?n:`${t.join(`/`)}/${n}`,e)}catch(t){throw this.toFsError(t,e)}return{kind:`directory`,size:0,mtime:0}}async mkdir(e){this.assertOpen(e),await this.resolveDir(e,!0)}async remove(e,t){this.assertOpen(e);let n=this.splitPath(e);if(n.length===0)throw new o(`EINVAL`,`cannot remove mount root`,e);let r=n.pop(),i=await this.resolveDirFrom(n,e,!1);try{await i.removeEntry(r,{recursive:t?.recursive??!1})}catch(t){throw this.toFsError(t,e)}this.invalidate(n.length===0?r:`${n.join(`/`)}/${r}`)}async refresh(){return this.assertOpen(`/`),this.dirCache.clear(),{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:this.handle.name}}async close(){this.closed=!0,this.dirCache.clear()}};async function be(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(r===void 0)return null;try{let t=e;for(let e of n)t=await t.getDirectoryHandle(e);return await(await t.getFileHandle(r)).getFile()}catch{return null}}function F(e,t){return e===t||e.startsWith(t===`/`?`/`:`${t}/`)}var xe=`/.metadata.json`,I=`.metadata.consistent.json`,L=`/${I}`;function R(e){return e.entries&&(delete e.entries[xe],delete e.entries[L]),e}function Se(e,t,n){let r=t.entries??{},i={...e.entries??{}};`/`in r&&(i[`/`]=r[`/`]);for(let e of n.paths)e in r?i[e]=r[e]:delete i[e];for(let e of n.prefixes){for(let t of Object.keys(i))F(t,e)&&delete i[t];for(let t of Object.keys(r))F(t,e)&&(i[t]=r[t])}let{entries:a,...o}=t;return R({...o,entries:i})}var z=1;async function Ce(e,t,n){let r=Math.max(1,Math.trunc(e)||1),i=Array(t.length),a=0,o=async()=>{for(;a<t.length;){let e=a;if(a+=1,e>=t.length)return;i[e]=await n(t[e],e)}},s=[],c=Math.min(r,t.length);for(let e=0;e<c;e+=1)s.push(o());return await Promise.all(s),i}async function B(e){let t=e;if(typeof t.createSyncAccessHandle==`function`)try{let e=await t.createSyncAccessHandle();try{return e.getSize()}finally{try{await e.close()}catch{}}}catch{}return(await e.getFile()).size}async function V(e){let t;for(let n=0;n<3;n+=1)try{return await(await e.getFile()).text()}catch(e){if(e?.name!==`NotReadableError`)throw e;t=e}throw t}function we(e){if(!e||typeof e!=`object`)return!1;let t=e.entries;return!!t&&typeof t==`object`}async function Te(e){try{let t=await V(await e.getFileHandle(`.metadata.json`)),n=JSON.parse(t);return we(n)?{text:t,doc:n}:null}catch{return null}}async function Ee(e,t){let n=await(await e.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await n.write(t),await n.close()}async function H(e){return r(e)}async function De(e,t){try{let n=await e.getFileHandle(I),r=JSON.parse(await V(n));if(!r||typeof r!=`object`)return!1;let i=r;return i.v!==z||typeof i.hash!=`string`?!1:i.hash===await H(t)}catch{return!1}}async function Oe(e,t){let n={v:z,hash:await H(t)},r=await(await e.getFileHandle(I,{create:!0})).createWritable();await r.write(JSON.stringify(n)),await r.close()}async function ke(e){try{await e.removeEntry(I)}catch(e){if(e?.name===`NotFoundError`)return;throw e}}async function Ae(e,t,n){let r=e,i=``,a=0;for(let e=n.length;e>0;--e){let o=n.slice(0,e).join(`/`),s=t.get(o);if(s){r=s,i=o,a=e;break}}for(let e=a;e<n.length;e+=1){let a=n[e];try{r=await r.getDirectoryHandle(a)}catch{return null}i=i?`${i}/${a}`:a,t.set(i,r)}return r}async function je(e,t,n,r,i,a){let o=async()=>{try{let n=await e.getDirectoryHandle(t);return i.set(a?`${a}/${t}`:t,n),{kind:`directory`}}catch{return null}},s=async()=>{try{let n=await e.getFileHandle(t);return r?{kind:`file`,size:await B(n)}:{kind:`file`,size:0}}catch{return null}};return n===`directory`?await o()??await s()??{kind:`missing`}:await s()??await o()??{kind:`missing`}}function U(e,t){let n=t?.includeSize!==!1,r=new Map;return async(t,i)=>{let a=t.split(`/`).filter(Boolean),o=await Ae(e,r,a.slice(0,-1));if(!o)return{kind:`missing`};let s=a[a.length-1];if(s===void 0)return{kind:`directory`};let c=a.slice(0,-1).join(`/`);return je(o,s,i,n,r,c)}}async function W(e){let t=new Map;for await(let[n,r]of e.entries())t.set(n,r);return t}function Me(e){return e.kind===`directory`?`directory`:e.kind===`file`?`file`:`other`}function Ne(e){if(typeof e.entries!=`function`)return U(e);let t=new Map,n=(e,n)=>{let r=t.get(n);if(r!=null)return r;let i=W(e).catch(e=>{throw t.delete(n),e});return t.set(n,i),i};return async t=>{let r=t.split(`/`).filter(Boolean),i=e,a=``;for(let e=0;e<r.length;e+=1){let t=r[e],o=(await n(i,a)).get(t);if(!o)return{kind:`missing`};let s=Me(o);if(e!==r.length-1){if(s!==`directory`)return{kind:`missing`};i=o,a=`${a}/${t}`;continue}return s===`directory`?{kind:`directory`}:s===`file`?{kind:`file`,size:await B(o)}:{kind:`missing`}}return{kind:`directory`}}}var Pe=61440,G=16384,K=32768,Fe=40960;async function Ie(e,t,n,r=16){let i=q(),a=e.entries??{},o=[];for(let[e,t]of Object.entries(a)){let r=Le(e,t,a,i);r?o.push(r):n?.()}return Re(o,await Ce(r,o,async e=>{n?.();let r=e.fmt===G?`directory`:`file`;return t(e.path,r)}),a,i),ze(a,i),i}function q(){return{kindFixed:[],sizesFixed:0,dropped:0,selfEntryDropped:!1,inosReassigned:0,nlinksFixed:0,changed:!1}}function Le(e,t,n,r){if(e===`/`||typeof t!=`object`||!t)return null;if(e===`/.metadata.json`||e===L)return delete n[e],e===`/.metadata.json`&&(r.selfEntryDropped=!0),r.changed=!0,null;let i=t,a=(i.mode??0)&Pe;return a===Fe?(J(i,r),null):{path:e,entry:i,fmt:a}}function Re(e,t,n,r){for(let i=0;i<e.length;i+=1){let a=e[i],o=t[i];if(o.kind===`missing`){delete n[a.path],r.dropped+=1,r.changed=!0;continue}J(a.entry,r),Be(a.path,a.entry,a.fmt,o,r)}}function ze(e,t){let n=0;for(let t of Object.values(e)){let e=t;typeof e?.ino==`number`&&(n=Math.max(n,e.ino)),typeof e?.data==`number`&&(n=Math.max(n,e.data))}let r=n+1,i=new Set;for(let[n,a]of Object.entries(e)){if(typeof a!=`object`||!a)continue;let e=a;if(n===`/`){typeof e.ino==`number`&&i.add(e.ino);continue}let o=e.ino;if(typeof o==`number`&&o!==0&&!i.has(o)){i.add(o);continue}e.ino=r,e.data=r+1,i.add(r),r+=2,t.inosReassigned+=1,t.changed=!0}}function J(e,t){e.nlink||(e.nlink=1,t.nlinksFixed+=1,t.changed=!0)}function Be(e,t,n,r,i){if(n===K&&r.kind===`directory`){t.mode=((t.mode??0)&511||493)|G,i.kindFixed.push(`${e} file→dir`),i.changed=!0;return}if(n===G&&r.kind===`file`){t.mode=((t.mode??0)&511||420)|K,t.size=r.size,i.kindFixed.push(`${e} dir→file`),i.changed=!0;return}n===K&&r.kind===`file`&&typeof t.size==`number`&&t.size!==r.size&&(t.size=r.size,i.sizesFixed+=1,i.changed=!0)}async function Ve(e,t,n){try{return await e()}catch(r){let i=null;try{i=await t()}catch{}if(!i?.changed)throw r;return n(i),await e()}}async function He(e,t){let n=await Te(e);if(!n)return null;if(await De(e,n.text))return q();let r=await Ie(n.doc,Ne(e),t),i=r.changed?JSON.stringify(n.doc):n.text;r.changed&&await Ee(e,i);try{await Oe(e,i)}catch{}return r}function Y(e,t,n=0){if(!(!Number.isSafeInteger(t)||(t??0)<=0||!Number.isSafeInteger(n)||n<0))return JSON.stringify([e,n,t])}async function Ue(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=k(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function We(e,t,n){let r;try{r=await e.readlink(t)}catch(e){throw k(e,n)}return r.startsWith(`/`)?l(r):l(d(s(t).dir,r))}async function Ge(e,t,n,r,i,a,s){let c=n===`/`?`/${r}`:`${n}/${r}`;for(;;){let n=await Ue(e,c,i,a);if(n===null||!n.isSymbolicLink())return{resolved:c,hops:s};if(++s>10)throw new o(`ELOOP`,`too many symbolic links encountered`,a);if(c=await We(e,c,a),t(c))return{resolved:c,hops:s}}}async function X(e,t,n){let r=l(n);if(t(r))return r;let i=r.split(`/`).filter(Boolean),a=`/`,o=0;for(let n=0;n<i.length;n++){let s=await Ge(e,t,a,i[n],n===i.length-1,r,o);if(a=s.resolved,o=s.hops,t(a)){let e=i.slice(n+1);return e.length>0?`${a}/${e.join(`/`)}`:a}}return a}async function Ke(e,t,n){return t(n)?n:X(e,t,n)}function Z(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var qe=100,Q=1e3,Je=3e4;function Ye(e,t){let n=e.kind===`directory`?`directory`:`file`;return t?{name:e.name,type:n,...e.size===void 0?{}:{size:e.size},...e.lastModified===void 0?{}:{mtime:e.lastModified},...e.ctime===void 0?{}:{ctime:e.ctime},...e.ino===void 0?{}:{ino:e.ino},...e.identity===void 0?{}:{identity:e.identity},...e.dev===void 0?{}:{dev:e.dev},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}:{name:e.name,type:n}}function Xe(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}function Ze(e,t){if(e===`symlink`&&t!==`directory`)return`link`;if(e===`directory`&&t===`directory`)return`dir`}function Qe(e){let t=e.lastIndexOf(`/`),n=Math.random().toString(36).slice(2,10);return`${e.slice(0,t+1)}.${e.slice(t+1)}.slicc-rename-${n}`}var $e=8,$=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 x;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a,o){if(this.dbName=t,this.onRepairProgress=a,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,o):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,n).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 opfsInitChains=new Map;static async initOpfsBackend(t,n,r,i){let a=(e.opfsInitChains.get(t.dbName)??Promise.resolve()).catch(()=>{}).then(()=>e.resolveOpfsBackend(t,n,r,i));e.opfsInitChains.set(t.dbName,a);try{await a}finally{e.opfsInitChains.get(t.dbName)===a&&e.opfsInitChains.delete(t.dbName)}}static async resolveOpfsBackend(n,r,i,a){let s=e.opfsBackends.get(n.dbName);if(s&&i)throw new o(`EBUSY`,`Cannot wipe an OPFS backend with live holders`,n.dbName);if(s&&a!==void 0&&s.asyncCache!==a)throw new o(`EBUSY`,`OPFS async cache setting conflicts with the live backend`,n.dbName);let c=r??await e.acquireOpfsHandle(n.dbName,i);await n.withWriteLock(()=>e.seedOpfsMetadataSidecarIfMissing(c));let l=await t(()=>import(`./dist-C8GTDH_7.js`),__vite__mapDeps([0,1,2]));await e.ensureRootMount(l);let u=`/__opfs__/${n.dbName}`,d=e.opfsBackends.get(n.dbName);if(!d){let{resolveOpfsMount:r}=await t(async()=>{let{resolveOpfsMount:e}=await import(`./opfs-mount-DqwXxpJI.js`);return{resolveOpfsMount:e}},__vite__mapDeps([3,0,1,2])),i=await r({handle:c,dbName:n.dbName,asyncCache:a,onRepairProgress:n.onRepairProgress,withWriteLock:e=>n.withWriteLock(e)});try{l.mount(u,i)}catch{}d={backendFs:i,refs:0,asyncCache:a!==!1,sidecarDirty:{paths:new Set,prefixes:new Set},sidecarFlushTimer:null,sidecarFlushRetryMs:Q},e.opfsBackends.set(n.dbName,d)}d.refs+=1,n.opfsBackendFs=d.backendFs.index?d.backendFs:null,n.opfsHandle=c,n.mountRoot=u,n.rawLfs=l.promises,n.rawLfsSync=l}static async initMemoryBackend(n,r,i){let a=await t(()=>import(`./dist-C8GTDH_7.js`),__vite__mapDeps([0,1,2]));await e.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=e.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}e.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},e.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(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),appendFile:async(t,r)=>{this._readyResolved||await this._ready,await n().appendFile(e(t),r)},chmod:async(t,r)=>{this._readyResolved||await this._ready,await n().chmod(e(t),r)},utimes:async(t,r,i)=>{this._readyResolved||await this._ready,await n().utimes(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(t){let n=`.metadata.json`;try{let r=await t.getFileHandle(n);if(e.isUsableMetadataDocument(await e.readSidecarText(r)))return;console.warn(`[virtual-fs] metadata sidecar is unparseable (torn write?); reseeding an empty index`)}catch(e){if(e?.name!==`NotFoundError`)throw e}let r=await(await t.getFileHandle(n,{create:!0})).createWritable(),i=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await r.write(i),await r.close()}static async readSidecarText(e){let t;for(let n=0;n<3;n++)try{return await(await e.getFile()).text()}catch(e){if(e?.name!==`NotReadableError`)throw e;t=e}throw t}static isUsableMetadataDocument(e){let t;try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!=`object`)return!1;let n=t.entries;return!!n&&typeof n==`object`}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new o(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??Z(),a=new e(n,r,i,void 0,t?.onRepairProgress,t?.opfsAsyncCache);try{await a._ready}catch(e){throw a.mountSyncChannel?.close(),e}return r&&await oe().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=Se(e,r,i))}let o=JSON.stringify(R(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear());let c=e.opfsBackends.get(this.dbName);c&&(c.sidecarFlushRetryMs=Q),c&&c.sidecarFlushTimer!==null&&(clearTimeout(c.sidecarFlushTimer),c.sidecarFlushTimer=null)}scheduleMetadataSidecarFlush(t=qe){if(this.backend!==`opfs`)return;let n=e.opfsBackends.get(this.dbName);n&&(n.sidecarFlushTimer!==null&&clearTimeout(n.sidecarFlushTimer),n.sidecarFlushTimer=setTimeout(()=>{n.sidecarFlushTimer=null,this.writeOpfsMetadataSidecar().catch(t=>{if(console.warn(`[virtual-fs] deferred metadata sidecar flush failed`,t),e.opfsBackends.get(this.dbName)!==n||n.sidecarFlushTimer!==null||n.sidecarDirty.paths.size===0&&n.sidecarDirty.prefixes.size===0)return;let r=n.sidecarFlushRetryMs;n.sidecarFlushRetryMs=Math.min(r*2,Je),this.scheduleMetadataSidecarFlush(r)})},t))}async auditDirtyKindFlips(e,t,n,r){let i=ye(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=U(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,n=`path`){if(this.backend!==`opfs`)return;let r=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!r)return;let i=l(t);(n===`prefix`?r.prefixes:r.paths).add(i);let{dir:a}=s(i);for(;a!==`/`;)r.paths.add(a),a=s(a).dir}async forgetSidecarConsistency(){await this.dropSidecarConsistency()}sidecarConsistencyDrop=null;dropSidecarConsistency(){if(this.backend!==`opfs`||!this.opfsHandle)return Promise.resolve();if(!this.sidecarConsistencyDrop){let e=this.opfsHandle;this.sidecarConsistencyDrop=ke(e).catch(e=>{throw this.sidecarConsistencyDrop=null,e})}return this.sidecarConsistencyDrop}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;e.length>0&&this.dropSidecarConsistency().catch(()=>void 0);let t=this.opfsBackendFs;for(let n of e){let e=l(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=l(e),i=r;try{i=await this.resolveSymlinks(r)}catch{}let a=await U(n)(i),o=A(t.index.get(i)?.mode),s=t._handles?.get(i),c=s?.kind===`directory`?`directory`:s?.kind===`file`?`file`:`absent`,u=j(a,o),d=j(a,c);if(!u&&!d)return!1;if(t.index.delete(i),t._handles?.delete(i),o===`directory`||c===`directory`){let e=`${i}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(i),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:i,reality:a.kind,indexHeld:o,handleHeld:c}),!0}localIdentity(e){return Y(`zenfs:${this.backend}:${this.dbName}`,e)}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new o(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}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`?e.opfsBackends:e.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await t(()=>import(`./dist-C8GTDH_7.js`),__vite__mapDeps([0,1,2]))).umount(this.mountRoot)}catch{}}}}syncDirEntry(e,t){let n=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;return n===`symlink`?{name:e,type:n}:{name:e,type:n,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,...t.ino===void 0?{}:{ino:t.ino,identity:this.localIdentity(t.ino),dev:t.dev},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},mode:t.mode}}readDirSync(e){let t=l(e);if(this.findMount(t)||this.linksOntoMountSync(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{r.push(this.syncDirEntry(i,n.lstatSync(e)))}catch{}}return r}catch{return null}}linksOntoMountSync(e){let t=this.lfsSync;if(this.mountPoints.size===0||e===`/`||typeof t.readlinkSync!=`function`)return!1;let n=e;try{for(let e=0;e<=10;e++){if(!t.lstatSync?.(n).isSymbolicLink())return!1;let e=t.readlinkSync(n);if(n=e.startsWith(`/`)?l(e):l(d(s(n).dir,e)),this.findMount(n))return!0}}catch{}return!1}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;if(t===`/`)try{let e=n.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}catch{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,ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode};let t;try{t=n.readlinkSync(r)}catch{return null}if(r=t.startsWith(`/`)?l(t):l(d(s(r).dir,t)),this.findMount(r))return null}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;if(t===`/`)return this.statSync(t);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,ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}catch{return null}}async mount(e,t,n){let r=l(e);if(this.mountPoints.has(r))throw new o(`EEXIST`,`mount point is already mounted`,r);try{if((await this.lstat(r)).type!==`directory`)throw new o(`ENOTDIR`,`mount point must be a directory`,r);if((await this.readDir(r)).length>0)throw new o(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,r)}catch(e){if(!(e instanceof o)||e.code!==`ENOENT`)throw e}let{dir:i}=s(r);i!==`/`&&await this.mkdir(i,{recursive:!0}),await this.dropSidecarConsistency();try{await this.lfs.mkdir(r)}catch{}if(this.mountPoints.set(r,t),t.kind===`local`){let e=n?.limits??b(n?.env??{});this.mountIndex.registerMount(r,t.getHandle(),e)}let a=Xe(t,r);try{this.mountSyncChannel?.postMessage({type:`mount`,path:r,descriptor:a})}catch{}if(this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:r,descriptor:a,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await re(e,n)}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 ie(t)}catch{}}async reconstructBackendFromDescriptor(e,n){switch(e.kind){case`local`:{let t=await ae(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return P.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:r}=await t(async()=>{let{HostFsMountBackend:e}=await import(`./backend-hostfs-C_GQqMGj.js`);return{HostFsMountBackend:e}},__vite__mapDeps([4,5,6,7,8]));return new r({targetPath:n,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await t(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-Cvx8MHrJ.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([9,10,11,12,7,13,1,8])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i(e.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await t(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-Cvx8MHrJ.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([9,10,11,12,7,13,1,8])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i()})}case`aem`:{let{AemMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await t(async()=>{let{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-Cvx8MHrJ.js`);return{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([9,10,11,12,7,13,1,8])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.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}getMountBackend(e){let t=l(e);return this.mountPoints.get(t)??null}async mountInternal(e,t){let n=l(e);if(this.mountPoints.has(n))throw new o(`EEXIST`,`mount point is already mounted`,n);let{dir:r}=s(n);r!==`/`&&await this.mkdir(r,{recursive:!0}),await this.dropSidecarConsistency();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 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=l(e),r=this.mountPoints.get(n);if(!r)throw new o(`ENOENT`,`not a mount point`,n);let i=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,b(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),i}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=l(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new o(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){O(e,n)}}let i=await this.resolveSymlinks(n),a=this.onMount(i,n);if(a)return this.readFileInner(a,t);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(i,{encoding:`utf8`}):await this.lfs.readFile(i)}catch(e){throw k(e,n)}}async readFileRange(e,t,n){let r=l(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<t)throw new o(`EINVAL`,`invalid byte range ${t}-${n}`,r);if(t===n)return new Uint8Array;let i=this.findMount(r),a=i?.backend.readFileRange;if(i&&a){if(i.relParts.length===0)throw new o(`EISDIR`,`is a directory`,r);try{return await a.call(i.backend,i.relParts.join(`/`),t,n)}catch(e){O(e,r)}}let s=await this.sliceNativeFile(r,t,n);if(s)return s;let c=await this.readFile(r,{encoding:`binary`});return new Uint8Array(c.subarray(t,Math.min(n,c.byteLength)))}async sliceNativeFile(e,t,n){try{let r=await this.getNativeFile(e);if(!r)return null;let i=r.slice(t,Math.min(n,r.size));return new Uint8Array(await i.arrayBuffer())}catch{return null}}async getNativeFile(e){let t=l(e),n=this.findMount(t);if(n){let e=n.backend.getNativeFile;if(!e||n.relParts.length===0)return null;try{return await e.call(n.backend,n.relParts.join(`/`))}catch{return null}}let r;try{r=await this.resolveSymlinks(t)}catch{return null}let i=this.onMount(r,t);if(i)return this.getNativeFile(i);let a=this.opfsHandle;if(!a)return null;try{return await be(a,r)}catch{return null}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,n){let r=l(e),i=this.findMount(r);if(i){if(i.relParts.length===0)throw new o(`EISDIR`,`is a directory`,r);let e=i.relParts.join(`/`),n=!1;try{await this.stat(r),n=!0}catch{}let a=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await i.backend.writeFile(e,a)}catch(e){O(e,r)}this.watcher?.notify([{type:n?`modify`:`create`,path:r,entryType:`file`}]),this.mountIndex.notifyWrite(r);return}let a;try{a=await this.resolveSymlinks(r)}catch{a=r}let c=this.onMount(a,r);if(c)return this.writeFileInner(c,t,n);let u=!1;try{await this.lfs.stat(a),u=!0}catch{}let{dir:d}=s(a);await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),this.markSidecarDirty(a),d!==`/`&&await this.mkdirRecursiveUnlocked(d);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(a,t)}catch(e){if(d!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(d);try{await this.lfs.writeFile(a,t)}catch(e){throw k(e,r)}}else throw k(e,r)}try{await this.lfs.truncate?.(a,e)}catch(e){throw k(e,r)}}),this.watcher?.notify([{type:u?`modify`:`create`,path:a,entryType:`file`}])}async appendFile(e,t){let n=l(e);await this.withKindMismatchRetry(n,()=>this.withWriteLock(async()=>{if(this.findMount(n)){await this.appendMounted(n,t);return}await this.dropSidecarConsistency();let e=n,r=!1;try{e=await this.resolveSymlinks(n);let i=this.onMount(e,n);if(i){await this.appendMounted(i,t);return}if((await this.lfs.stat(e)).isDirectory())throw new o(`EISDIR`,`is a directory`,n);r=!0}catch(e){let t=k(e,n);if(t.code!==`ENOENT`)throw t}this.markSidecarDirty(e);let{dir:i}=s(e);await this.mkdirRecursiveUnlocked(i);try{await this.lfs.appendFile(e,t)}catch(e){throw k(e,n)}this.watcher?.notify([{type:r?`modify`:`create`,path:e,entryType:`file`}])}))}async appendMounted(e,t){let n=new Uint8Array;try{let t=await this.readFileInner(e,{encoding:`binary`});n=typeof t==`string`?new TextEncoder().encode(t):new Uint8Array(t)}catch(t){let n=k(t,e);if(n.code!==`ENOENT`)throw n}let r=typeof t==`string`?new TextEncoder().encode(t):t,i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),await this.writeFileInner(e,i)}async chmod(e,t){let n=l(e);if(this.findMount(n))throw await this.stat(n),new o(`ENOSYS`,`metadata changes are not supported by this mount`,n);await this.applyMetadataUpdates([{path:e,mode:t}],!1)}async utimes(e,t,n){let r=l(e);if(this.findMount(r))throw await this.stat(r),new o(`ENOSYS`,`metadata changes are not supported by this mount`,r);await this.applyMetadataUpdates([{path:e,atime:t,mtime:n}],!1)}async updateMetadataBatch(e){await this.applyMetadataUpdates(e,!0)}async applyMetadataUpdates(e,t){if(e.length===0)return;let n=e.map(e=>this.prepareMetadataUpdate(e)),r=n.map(e=>e.normalized);await this.withKindMismatchRetryPaths(r,()=>this.withWriteLock(async()=>{await this.dropSidecarConsistency();let e=[];for(let t of n){let n=await this.applyPreparedMetadataUpdate(t);n&&e.push(n)}e.length!==0&&(t?await this.writeOpfsMetadataSidecarUnlocked():this.scheduleMetadataSidecarFlush(),this.watcher?.notify(e))}))}async applyPreparedMetadataUpdate(e){if(this.findMount(e.normalized))return await this.stat(e.normalized),null;let t=await this.resolveSymlinks(e.normalized);if(this.onMount(t,e.normalized))return await this.stat(t),null;try{let n=await this.lfs.stat(t);return this.markSidecarDirty(t),e.mode!==void 0&&await this.lfs.chmod(t,e.mode),e.atime!==void 0&&e.mtime!==void 0&&await this.lfs.utimes(t,e.atime,e.mtime),{type:`modify`,path:t,entryType:n.isDirectory()?`directory`:`file`}}catch(t){throw k(t,e.normalized)}}prepareMetadataUpdate(e){let t=l(e.path);if(e.mode!==void 0&&(!Number.isInteger(e.mode)||e.mode<0||e.mode>4095))throw new o(`EINVAL`,`invalid file mode`,t);if(e.atime!==void 0||e.mtime!==void 0){if(e.atime===void 0||e.mtime===void 0)throw new o(`EINVAL`,`atime and mtime must both be provided`,t);if(!Number.isFinite(e.atime.getTime())||!Number.isFinite(e.mtime.getTime()))throw new o(`EINVAL`,`invalid file time`,t)}if(e.mode===void 0&&e.atime===void 0)throw new o(`EINVAL`,`metadata update requires mode and/or times`,t);return{normalized:t,mode:e.mode,atime:e.atime,mtime:e.mtime}}async readDir(e,t){let n=l(e),r=this.findMount(n);return r?this.readDirMounted(n,r,t):this.readDirLocal(n)}async readDirMounted(e,t,n){let r=n?.includeStats===!0?void 0:this.mountIndex.getDirectoryEntries(t.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=t.relParts.join(`/`)||`/`,a;try{a=await t.backend.readDir(i,n)}catch(t){O(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,Ye(e,s));return this.addNestedMountEntries(o,e),[...o.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e),n=this.onMount(t,e);if(n)return this.readDir(n);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 k(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`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,...e.ino===void 0?{}:{ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},mode:e.mode}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);i&&!i.includes(`/`)&&(e.has(i)||e.set(i,{name:i,type:`directory`}))}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw k(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new o(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof o&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=l(e);if(n===`/`)return;let r=this.mountPoints.size>0?await this.parentOnMount(n):void 0;if(r)return this.mkdir(r,t);let i=this.findMount(n);if(i){if(i.relParts.length===0)return;let e=i.relParts.join(`/`),t=await this.exists(n);try{await i.backend.mkdir(e)}catch(e){O(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(async()=>(await this.dropSidecarConsistency(),this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw k(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(l(e),()=>this.viaMountOnEnoent(l(e),e=>this.rmInner(e,t)))}async rmInner(e,t){let n=l(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new o(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){O(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`)}),this.scheduleMetadataSidecarFlush()}catch(e){throw k(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statMounted(e,t){if(t.relParts.length===0)try{let t=await this.lfs.stat(e);return{type:`directory`,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let n=t.relParts.join(`/`);try{let e=await t.backend.stat(n);return{type:e.kind===`directory`?`directory`:`file`,size:e.size,mtime:e.mtime,ctime:e.ctime??e.mtime,...e.ino===void 0?{}:{ino:e.ino},...e.identity===void 0?{}:{identity:e.identity},...e.dev===void 0?{}:{dev:e.dev},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}}catch(t){O(t,e)}}async statInner(e){let t=l(e),n=this.findMount(t);if(n)return this.statMounted(t,n);let r=await this.resolveSymlinks(t),i=this.onMount(r,t);if(i)return this.statInner(i);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw k(e,t)}}async exists(e){let t=l(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([l(e),l(t)],()=>this.renameInner(e,t))}async renameInner(e,t){if(this.mountPoints.size>0){let[n,r]=await Promise.all([this.parentOnMount(l(e)),this.parentOnMount(l(t))]);if(n||r)return this.renameInner(n??e,r??t)}let n=l(e),r=l(t);if(n===r)return;let a;try{a=await this.lstat(n)}catch{}let o=a?.type,s=this.findMount(n);if(s?.backend.rename){let e=this.findMount(r);if(e&&e.backend===s.backend){let t=!1;try{t=(await s.backend.rename(s.relParts.join(`/`),e.relParts.join(`/`)))?.noop===!0}catch(e){O(e,n)}t||(this.watcher?.notify([{type:`delete`,path:n,entryType:o},{type:`create`,path:r,entryType:o}]),this.mountIndex.notifyRename(n,r));return}}let c;if(a)try{if(c=await this.lstat(r),i(a,c))return}catch{}let u=Ze(c?.type,o);u&&this.refuseMountedDisplacement(r);try{await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.storeRenameReplacing(n,r,u),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw k(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:o},{type:`create`,path:r,entryType:o}]),this.mountIndex.notifyRename(n,r)}refuseMountedDisplacement(e){let t=this.findMount(e);if(!t)return;let n=t.relParts.length===0?`EBUSY`:`EXDEV`;throw new o(n,`rename onto a mounted entry`,e)}async storeRenameReplacing(e,t,n){if(n===`dir`&&(await this.lfs.readdir(t)).length>0)throw new o(`ENOTEMPTY`,`directory not empty`,t);let r=n?await this.freeParkedLinkPath(t):void 0;r&&this.markSidecarDirty(r),r&&await this.lfs.rename(t,r);try{await this.lfs.rename(e,t)}catch(e){try{r&&await this.restoreParkedLink(r,t,e)}finally{await this.writeOpfsMetadataSidecarUnlocked().catch(()=>void 0)}throw e}r&&await(n===`dir`?this.lfs.rmdir(r):this.lfs.unlink(r)).catch(()=>void 0)}async freeParkedLinkPath(e){for(let t=0;t<$e;t++){let t=Qe(e);try{await this.lfs.lstat(t)}catch(e){if(e?.code===`ENOENT`)return t;throw e}}throw new o(`EEXIST`,`no free name to park the symlink at during rename`,e)}async restoreParkedLink(e,t,n){try{await this.lfs.rename(e,t)}catch(r){let i=e=>e instanceof Error?e.message:String(e);throw new o(`EIO`,`rename failed (${i(n)}) and the entry it replaced could not be put back (${i(r)}); it is at ${e}`,t)}}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*ee({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){let n=await this.stat(e);if(n.type===`directory`)throw new o(`EISDIR`,`is a directory`,e);try{let e=await this.stat(t);if(i(n,e))return}catch{}let r=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,r)}dirname(e){return s(l(e)).dir}basename(e){return s(l(e)).base}resolveSymlinkTargetPath(e,t){return e.startsWith(`/`)?l(e):l(d(s(t).dir,e))}assertSymlinkCreateAllowed(e){if(this.findMount(e))throw new o(`EINVAL`,`symlinks not supported on mounted filesystems`,e)}onMount(e,t){return e!==t&&this.findMount(e)?e:void 0}async viaMountOnEnoent(e,t){try{return await t(e)}catch(n){if(this.mountPoints.size===0||n.code!==`ENOENT`)throw n;let r=await this.parentOnMount(e);if(!r)throw n;return t(r)}}async parentOnMount(e){if(e===`/`||this.findMount(e))return;let{dir:t,base:n}=s(e),r;try{r=await this.resolveSymlinks(t)}catch{return}return r!==t&&this.findMount(r)?d(r,n):void 0}async symlink(e,t){await this.symlinkBatch([{target:e,path:t}])}async symlinkBatch(e){if(e.length===0)return;let t=e.map(e=>{let t=l(e.path);return this.assertSymlinkCreateAllowed(t),{target:e.target,normalizedLinkPath:t}}),n=t.map(e=>e.normalizedLinkPath);await this.withKindMismatchRetryPaths(n,()=>this.withWriteLock(async()=>{await this.dropSidecarConsistency();let e=[];try{for(let n of t)await this.createSymlinkUnlocked(n.target,n.normalizedLinkPath),this.markSidecarDirty(n.normalizedLinkPath),e.push({type:`create`,path:n.normalizedLinkPath,entryType:`symlink`});await this.writeOpfsMetadataSidecarUnlocked(),this.watcher?.notify(e)}catch(t){throw e.length>0&&(await this.writeOpfsMetadataSidecarUnlocked(),this.watcher?.notify(e)),t}}))}async createSymlinkUnlocked(e,t){let{dir:n}=s(t);n!==`/`&&await this.mkdirRecursiveUnlocked(n);try{await this.lfs.symlink(e,t)}catch(r){if(n!==`/`&&r instanceof Error&&r.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(n);try{await this.lfs.symlink(e,t)}catch(e){throw k(e,t)}}else throw k(r,t)}}async readlink(e){return this.viaMountOnEnoent(l(e),async e=>{try{return await this.lfs.readlink(e)}catch(t){throw k(t,e)}})}async lstat(e){return this.viaMountOnEnoent(l(e),e=>this.lstatInner(e))}async lstatInner(e){let t=l(e);if(this.findMount(t)||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,ino:e.ino,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw k(e,t)}}async realpath(e){return X(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return Ke(this.lfs,e=>this.findMount(e)!==null,e)}},et=e({FsError:()=>o,FsWatcher:()=>m,MountIndex:()=>x,RestrictedFS:()=>D,VirtualFS:()=>$,joinPath:()=>d,normalizePath:()=>l,pathSegments:()=>c,resolveVfsBackendFromEnv:()=>Z,sameFileIdentity:()=>i,splitPath:()=>s,statsFromDirEntry:()=>a});export{o as FsError,m as FsWatcher,x as MountIndex,D as RestrictedFS,$ as VirtualFS,P as a,Ve as i,d as joinPath,Y as n,l as normalizePath,c as pathSegments,He as r,Z as resolveVfsBackendFromEnv,i as sameFileIdentity,s as splitPath,a as statsFromDirEntry,et as t};
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/dist-C8GTDH_7.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/buffer-BeQa_9BU.js","assets/opfs-mount-DHQkCQyR.js","assets/backend-hostfs-BlwgXw0-.js","assets/api-endpoint-DuEQRZ4g.js","assets/runtime-env-Dlaokqg1.js","assets/types-D8gIX-W-.js","assets/remote-cache-CuIV6-dC.js","assets/mount-iiKbRe20.js","assets/mime-types-D0xZwlMO.js","assets/base64-ELzoYfwP.js","assets/stored-accounts-ChNHYF68.js","assets/mount-table-store-dY2IfQ5S.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{n as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./preload-helper-BLdHbfdN.js";import{t as n}from"./logger-DDBAeTLF.js";import{n as r,t as i}from"./same-file-identity-OexpsaSD.js";import{n as a,t as o}from"./types-D8gIX-W-.js";import{a as s,i as c,n as l,r as u,t as d}from"./path-utils-DNJG-zQf.js";import{r as ee,t as f}from"./bounded-walk-BjxKWNqp.js";import{n as te,t as ne}from"./virtual-device-paths-D45tpPP6.js";import{a as re,i as ie,n as ae,t as oe}from"./mount-table-store-dY2IfQ5S.js";var p=n(`fs-watcher`),se=0;function ce(e,t){return t===`/`||e===t||e.startsWith(t+`/`)}var m=class{registrations=new Map;watch(e,t,n){let r=`fsw-${++se}`;return this.registrations.set(r,{id:r,basePath:e,filter:t,callback:n}),p.debug(`Watch registered`,{id:r,basePath:e}),()=>{this.registrations.delete(r),p.debug(`Watch unregistered`,{id:r})}}notify(e){if(e.length!==0)for(let[,t]of this.registrations){let n=e.filter(e=>ce(e.path,t.basePath)&&t.filter(e.path));if(n.length>0)try{t.callback(n)}catch(e){p.error(`Watch callback error`,{id:t.id,error:e instanceof Error?e.message:String(e)})}}}dispose(){this.registrations.clear(),p.debug(`All watchers disposed`)}get size(){return this.registrations.size}},h=n(`mount-index`),le=400,ue=2e6,de=`SLICC_MOUNT_INDEX_MAX_DEPTH`,fe=`SLICC_MOUNT_INDEX_MAX_ENTRIES`,g=256,_=class extends Error{cause;constructor(e,t){super(e),this.name=`MountIndexAbortError`,this.cause=t}};function pe(e){let t=e.map(([e,t])=>`${e}\u0000${t.kind}`).sort(),n=t.length>g?t.slice(0,g):t;return`${t.length}\u0001${n.join(``)}`}async function v(e,t){let n=e.isSameEntry;if(typeof n!=`function`)return!1;try{return await n.call(e,t)}catch{return!1}}function me(e,t){return e instanceof Map?e.get(t):e[t]}function he(e){let t=e.trim();if(t===``)return;let n=Number(t);if(!(!Number.isInteger(n)||n<=0))return n}function y(e,t,n){let r=me(e,t);if(r===void 0||r.trim()===``)return n;let i=he(r);return i===void 0?(h.warn(`Ignoring invalid ${t}; expected a positive integer, using default`,{value:r,fallback:n}),n):i}function b(e){return{maxDepth:y(e,de,le),maxEntries:y(e,fe,ue),skipNoiseDirs:!0}}var x=class{mounts=new Map;listeners=new Set;registerMount(e,t,n=b({})){this.mounts.get(e)?.abortController?.abort();let r=new AbortController,i={handle:t,state:{status:`pending`,indexed:0},files:new Set,directories:new Set,childrenByDirectory:new Map,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(),n.childrenByDirectory.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=n.childrenByDirectory.get(t);if(r)return[...r].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`||this.isSkippedNoisePath(t,e,n,`file`))return;n.files.add(e),this.addPathToChildIndex(n,e,`file`);let r=this.parentPath(e);for(;(r===t||r.startsWith(`${t}/`))&&(n.directories.add(r),this.ensureDirectoryChildren(n,r),r!==t);)this.addPathToChildIndex(n,r,`directory`),r=this.parentPath(r)}notifyDelete(e){let t=this.findMountForPath(e);if(!t)return;let n=this.mounts.get(t);if(n?.state.status!==`ready`||this.isSkippedNoisePath(t,e,n,`unknown`))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);this.removePathFromChildIndex(n,e);for(let t of n.childrenByDirectory.keys())(t===e||t.startsWith(r))&&n.childrenByDirectory.delete(t)}notifyRename(e,t){let n=this.findMountForPath(e);if(!n)return;let r=this.mounts.get(n);if(r?.state.status!==`ready`)return;let i=r.files.has(e)?`file`:r.directories.has(e)?`directory`:`unknown`;if(i===`unknown`||this.isSkippedNoisePath(n,e,r,i))return;if(this.isSkippedNoisePath(n,t,r,i)){this.notifyDelete(e);return}if(i===`file`){r.files.delete(e),r.files.add(t),this.removePathFromChildIndex(r,e),this.addPathToChildIndex(r,t,`file`);return}r.directories.delete(e),r.directories.add(t);let a=e+`/`,o=t+`/`;for(let e of[...r.files])e.startsWith(a)&&(r.files.delete(e),r.files.add(o+e.slice(a.length)));for(let e of[...r.directories])e.startsWith(a)&&(r.directories.delete(e),r.directories.add(o+e.slice(a.length)));this.removePathFromChildIndex(r,e),this.addPathToChildIndex(r,t,`directory`);let s=[...r.childrenByDirectory.entries()].filter(([t])=>t===e||t.startsWith(a));for(let[e]of s)r.childrenByDirectory.delete(e);for(let[n,i]of s){let s=n===e?t:o+n.slice(a.length);r.childrenByDirectory.set(s,i)}}ensureDirectoryChildren(e,t){let n=e.childrenByDirectory.get(t);return n||(n=new Map,e.childrenByDirectory.set(t,n)),n}addPathToChildIndex(e,t,n){let r=t.slice(t.lastIndexOf(`/`)+1);r&&(this.ensureDirectoryChildren(e,this.parentPath(t)).set(r,n),n===`directory`&&this.ensureDirectoryChildren(e,t))}removePathFromChildIndex(e,t){let n=t.slice(t.lastIndexOf(`/`)+1);e.childrenByDirectory.get(this.parentPath(t))?.delete(n)}parentPath(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}isSkippedNoisePath(e,t,n,r){if(!n.limits.skipNoiseDirs||!t.startsWith(`${e}/`))return!1;let i=t.slice(e.length+1).split(`/`),a=r===`unknown`?n.files.has(t)?`file`:n.directories.has(t)?`directory`:`unknown`:r;for(let e=0;e<i.length;e++){let t=e===i.length-1;if(!(t&&a===`file`)&&(!t||a!==`unknown`||f(i[e]))&&f(i[e]))return!0}return!1}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,h.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},h.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),this.ensureDirectoryChildren(n,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=pe(n),a=r.get(i);if(a){for(let n of a)if(await v(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}`;if(s.kind===`file`)n.files.add(t),this.addPathToChildIndex(n,t,`file`),n.state.indexed++;else if(s.kind===`directory`){if(n.limits.skipNoiseDirs&&f(o))continue;this.addPathToChildIndex(n,t,`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)))}}},S=new TextEncoder,C=new TextDecoder(`utf-8`,{fatal:!1}),w=class{entries=new Map;static handles(e){return te(l(e))}has(e){return this.entries.has(l(e))}write(e,t){let n=l(e),r=typeof t==`string`?S.encode(t):new Uint8Array(t),i=Date.now(),a=this.entries.get(n);this.entries.set(n,{bytes:r,mtime:i,ctime:a?.ctime??i})}append(e,t){let n=this.entries.get(l(e))?.bytes??new Uint8Array,r=typeof t==`string`?S.encode(t):t,i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),this.write(e,i)}read(e,t){let n=this.require(e);return(t?.encoding??`utf-8`)===`utf-8`?C.decode(n.bytes):new Uint8Array(n.bytes)}readText(e){return C.decode(this.require(e).bytes)}stat(e){let t=this.require(e);return{type:`file`,size:t.bytes.length,mtime:t.mtime,ctime:t.ctime}}remove(e){return this.entries.delete(l(e))}require(e){let t=l(e),n=this.entries.get(t);if(!n)throw new o(`ENOENT`,`no such file or directory`,t);return n}},T={[ne]:{stat:()=>({type:`file`,size:0,mtime:0,ctime:0}),read:e=>(e?.encoding??`utf-8`)===`utf-8`?``:new Uint8Array,readText:()=>``,write:()=>{}}},E=[`/tmp/`],D=class{ephemeralFds=new w;vfs;allowedPrefixes;readOnlyPrefixes;readGrantPatterns=[];writeEnforcement;includeMounts;constructor(e,t,n=[],r=`hard`,i={}){this.vfs=e;let a=e=>{let t=l(e);return t.endsWith(`/`)?t:t+`/`};this.allowedPrefixes=t.map(a),this.readOnlyPrefixes=n.map(a),this.writeEnforcement=r,this.includeMounts=i.includeMounts!==!1}getAllPrefixes(){let e=this.includeMounts?this.vfs.listMounts().map(e=>e.endsWith(`/`)?e:e+`/`):[];return[...this.allowedPrefixes,...this.readOnlyPrefixes,...e,...E]}setReadGrants(e){this.readGrantPatterns=[];for(let t of new Set(e))this.addReadGrant(t)}addReadGrant(e){let t=e.split(`/`),n=[];for(let e=1;e<t.length;e++)n.push(u(t.slice(0,e).join(`/`)||`/`));this.readGrantPatterns.push({pattern:e,regex:u(e),ancestorRegexes:n})}matchesReadGrant(e){return this.readGrantPatterns.some(t=>t.regex.test(e))}leadsToReadGrant(e){return this.readGrantPatterns.some(t=>t.ancestorRegexes.some(t=>t.test(e)))}isAllowed(e){let t=l(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||this.leadsToReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e)||t===`/`||e.startsWith(t+`/`))}isAllowedStrict(e){let t=l(e),n=this.getAllPrefixes();return this.matchesReadGrant(t)||n.some(e=>t===e.slice(0,-1)||t.startsWith(e))}isWritable(e){let t=l(e);return[...this.allowedPrefixes,...E].some(e=>t===e.slice(0,-1)||t.startsWith(e))}readAccess(e){return T[l(e)]||w.handles(e)||this.isAllowedStrict(e)?`inside`:this.isAllowed(e)?`parent`:`outside`}canWrite(e){return w.handles(e)||this.isWritable(e)}checkWrite(e){if(this.writeEnforcement!==`sudo-delegated`&&!this.isWritable(e))throw new o(`EACCES`,`permission denied`,l(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`,l(e));return t}catch(t){throw t instanceof o?t:new o(`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 o(`EACCES`,`permission denied`,l(e));return t}catch(t){throw t instanceof o?t:new o(`EACCES`,`permission denied`,l(e))}}isSymlinkEscapeAllowed(e){return!1}async checkParentRealpathEscape(e){let t=this.vfs.dirname(e),n=this.vfs.basename(e),r;try{r=await this.vfs.realpath(t)}catch(e){if(e instanceof o&&e.code===`EACCES`)throw e;return}let i=r+`/`+n;if(this.isWritable(i))return;let a=l(r)!==l(t);if(this.writeEnforcement!==`sudo-delegated`||a)throw new o(`EACCES`,`permission denied`,l(e))}getUnderlyingFS(){return this.vfs}invalidatePaths(e){this.vfs.invalidatePaths(e)}async forgetSidecarConsistency(){await this.vfs.forgetSidecarConsistency()}async flush(){await this.vfs.flush()}isPathUnderMount(e){return this.vfs.isPathUnderMount(e)}async readFile(e,t){let n=T[l(e)];if(n)return n.read(t);if(w.handles(e))return this.ephemeralFds.read(e,t);if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,l(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFile(r,t)}async readFileRange(e,t,n){if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,l(e));let r=await this.resolveAndCheckRead(e);return this.vfs.readFileRange(r,t,n)}async getNativeFile(e){if(T[l(e)]||w.handles(e)||!this.isAllowedStrict(e))return null;try{let t=await this.resolveAndCheckRead(e);return await this.vfs.getNativeFile(t)}catch{return null}}async readDir(e,t){if(!this.isAllowed(e))return[];let n=e;if(this.isAllowedStrict(e))try{n=await this.resolveAndCheckRead(e)}catch{return[]}let r=await this.vfs.readDir(n,t);if(!this.isAllowedStrict(e)){let t=l(e);return r.filter(e=>{let n=t===`/`?`/${e.name}`:`${t}/${e.name}`;return this.isAllowed(n)})}return r}async stat(e){let t=T[l(e)];if(t)return t.stat();if(w.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new o(`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():w.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!this.isAllowedStrict(e)||this.scanPathForSymlinks(e,!0)!==!1?null:this.vfs.statSync(e)}lstatSync(e){let t=T[l(e)];return t?t.stat():w.handles(e)?this.ephemeralFds.has(e)?this.ephemeralFds.stat(e):null:!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){if(w.handles(e)){let t=l(e);if(!this.ephemeralFds.has(t))throw new o(`ENOENT`,`no such file or directory`,t);return t}let t;try{t=await this.vfs.realpath(e)}catch(t){throw t instanceof o?t:new o(`ENOENT`,`no such file or directory`,l(e))}if(!this.isAllowedStrict(t))throw new o(`ENOENT`,`no such file or directory`,l(e));return t}async exists(e){if(T[l(e)])return!0;if(w.handles(e))return this.ephemeralFds.has(e);if(!this.isAllowed(e))return!1;if(this.isAllowedStrict(e))try{await this.resolveAndCheckRead(e)}catch{return!1}return this.vfs.exists(e)}async readTextFile(e){let t=T[l(e)];if(t)return t.readText();if(w.handles(e))return this.ephemeralFds.readText(e);if(!this.isAllowedStrict(e))throw new o(`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 r=T[l(e)];if(r){r.write(t);return}if(w.handles(e)){this.ephemeralFds.write(e,t);return}return await this.checkContentWrite(e),this.vfs.writeFile(e,t,n)}async appendFile(e,t){let n=T[l(e)];if(n){n.write(t);return}if(w.handles(e)){this.ephemeralFds.append(e,t);return}return await this.checkContentWrite(e),this.vfs.appendFile(e,t)}async chmod(e,t){return this.refuseDescriptorTreeOp(e),await this.checkContentWrite(e),this.vfs.chmod(e,t)}async utimes(e,t,n){return this.refuseDescriptorTreeOp(e),await this.checkContentWrite(e),this.vfs.utimes(e,t,n)}async updateMetadataBatch(e){for(let t of e)this.refuseDescriptorTreeOp(t.path),await this.checkContentWrite(t.path);return this.vfs.updateMetadataBatch(e)}async checkContentWrite(e){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}}refuseDescriptorTreeOp(e){if(w.handles(e))throw new o(`EACCES`,`permission denied`,l(e))}async mkdir(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mkdir(e,t)}async rm(e,t){if(w.handles(e)){if(!this.ephemeralFds.remove(e))throw new o(`ENOENT`,`no such file or directory`,l(e));return}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.refuseDescriptorTreeOp(e),this.refuseDescriptorTreeOp(t),this.checkWrite(e),this.checkWrite(t),await this.resolveAndCheckWrite(e),await this.checkParentRealpathEscape(t),this.vfs.rename(e,t)}async copyFile(e,t){if(w.handles(e)){let n=this.ephemeralFds.read(e,{encoding:`binary`});await this.writeFile(t,n);return}if(w.handles(t)){if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,l(e));let n=await this.resolveAndCheckRead(e);this.ephemeralFds.write(t,await this.vfs.readFile(n,{encoding:`binary`}));return}if(!this.isAllowed(e))throw new o(`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 o&&e.code===`EACCES`)throw e}return this.vfs.copyFile(n,t)}async symlink(e,t){return this.symlinkBatch([{target:e,path:t}])}async symlinkBatch(e){if(e.length===0)return;let t=e.map(e=>({target:e.target,path:l(e.path)}));this.rejectNestedSymlinkBatchPaths(t.map(e=>e.path));for(let e of t)this.refuseDescriptorTreeOp(e.path),this.checkWrite(e.path),await this.checkParentRealpathEscape(e.path);return this.vfs.symlinkBatch(t)}rejectNestedSymlinkBatchPaths(e){for(let t=0;t<e.length;t++)for(let n=0;n<e.length;n++){if(t===n)continue;let r=e[n],i=e[t];if(i===r||i.startsWith(`${r}/`))throw new o(`EACCES`,`permission denied`,i)}}async readlink(e){if(!this.isAllowedStrict(e))throw new o(`ENOENT`,`no such file or directory`,l(e));let t=await this.vfs.readlink(e),n;if(t.startsWith(`/`))n=l(t);else{let r=this.vfs.dirname(e);n=l(r+`/`+t)}if(!this.isAllowedStrict(n))throw new o(`ENOENT`,`no such file or directory`,l(e));return t}async lstat(e){let t=T[l(e)];if(t)return t.stat();if(w.handles(e))return this.ephemeralFds.stat(e);if(!this.isAllowed(e))throw new o(`ENOENT`,`no such file or directory`,l(e));let n=l(e),r=this.vfs.dirname(n),i=this.vfs.basename(n),a;if(r===n)a=r;else try{a=await this.vfs.realpath(r)}catch{throw new o(`ENOENT`,`no such file or directory`,n)}let s=a===`/`?`/${i}`:`${a}/${i}`;if(!this.isAllowed(s))throw new o(`ENOENT`,`no such file or directory`,n);return this.vfs.lstat(s)}watch(e,t,n){if(!this.isAllowed(e))throw new o(`EACCES`,`permission denied`,l(e));let r=this.vfs.getWatcher();if(!r)throw new o(`EINVAL`,`no watcher configured`);return r.watch(l(e),t,n)}dirname(e){return this.vfs.dirname(e)}basename(e){return this.vfs.basename(e)}async mount(e,t,n){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.mount(e,t,n)}async unmount(e){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),await this.checkParentRealpathEscape(e),this.vfs.unmount(e)}listMounts(){let e=this.vfs.listMounts();return this.includeMounts?e:e.filter(e=>this.isAllowedStrict(e))}listMountPoints(){let e=this.vfs.listMountPoints();return this.includeMounts?e:e.filter(e=>this.isAllowed(e.path))}getMountIndex(){return this.vfs.getMountIndex()}async refreshMount(e,t){return this.refuseDescriptorTreeOp(e),this.checkWrite(e),this.vfs.refreshMount(e,t)}async dispose(){await this.vfs.dispose()}};function O(e,t){if(e instanceof o){let n=`${e.code}: `,r=e.message;throw r.startsWith(n)&&(r=r.slice(n.length)),e.path&&r.endsWith(` '${e.path}'`)&&(r=r.slice(0,r.length-` '${e.path}'`.length)),new o(e.code,r,t)}throw e}var ge=[`ENOENT`,`EEXIST`,`ENOTDIR`,`EISDIR`,`ENOTEMPTY`,`EINVAL`,`EACCES`,`ELOOP`,`EBUSY`,`EFBIG`,`EBADF`,`ENOSYS`,`EOPNOTSUPP`,`EXDEV`,`EIO`];function k(e,t){if(e instanceof o)return e;{let n=e instanceof Error?e.message:String(e);if(n.includes(`maximum size exceeded`)||n.includes(`call stack size exceeded`))return new o(`EIO`,`internal overflow, not storage: ${n} — reload the session`,t)}let n=e?.code;if(typeof n==`string`){let r=n;if(ge.includes(r)){let n=e instanceof Error?e.message:String(e);return n.startsWith(`${r}: `)&&(n=n.slice(r.length+2),n=n.replace(/, undefined( '[^']*')?$/,``).replace(/ '[^']*'$/,``)),new o(r,n||r,t)}}let r=e instanceof Error?e.message:String(e);return r.includes(`ENOENT`)?new o(`ENOENT`,`no such file or directory`,t):r.includes(`EEXIST`)?new o(`EEXIST`,`file already exists`,t):r.includes(`ENOTDIR`)?new o(`ENOTDIR`,`not a directory`,t):r.includes(`EISDIR`)?new o(`EISDIR`,`is a directory`,t):r.includes(`ENOTEMPTY`)?new o(`ENOTEMPTY`,`directory not empty`,t):r.includes(`ELOOP`)?new o(`ELOOP`,`too many levels of symbolic links`,t):r.includes(`EOPNOTSUPP`)||r.includes(`ENOTSUP`)?new o(`EOPNOTSUPP`,`operation not supported`,t):r.includes(`EXDEV`)?new o(`EXDEV`,`cross-device link`,t):new o(`EINVAL`,r,t)}var _e=61440,ve=16384;function A(e){return e===void 0?`absent`:(e&_e)===ve?`directory`:`file`}function j(e,t){return t===`absent`?!1:e.kind===`missing`||e.kind!==t}function M(e){let t=e?.mode;return typeof t==`number`?t:void 0}function ye(e,t,n,r=new Set){let i=new Set(n);if(r.size>0){for(let t of Object.keys(e.entries??{}))for(let e of r)if(t===e||t.startsWith(`${e}/`)){i.add(t);break}}let a=[];for(let n of i){let r=e.entries?.[n],i=t.entries?.[n];if(!r||!i)continue;let o=A(M(r));o!==A(M(i))&&a.push({path:n,ownIsDirectory:o===`directory`})}return a}var N=512,P=class e{kind=`local`;listingStatsMatchStat=!0;source=void 0;profile=void 0;mountId;handle;dirCacheMax;dirCache=new Map;closed=!1;constructor(e,t){this.handle=e,this.mountId=t.mountId,this.dirCacheMax=t.dirCacheMax??N}static fromHandle(t,n){return new e(t,n)}getHandle(){return this.handle}assertOpen(e){if(this.closed)throw new o(`EBADF`,`mount closed`,e)}splitPath(e){return e.replace(/^\/+/,``).replace(/\/+$/,``).split(`/`).filter(e=>e.length>0)}cacheGet(e){let t=this.dirCache.get(e);if(t!==void 0)return this.dirCache.delete(e),this.dirCache.set(e,t),t}cacheSet(e,t){for(this.dirCache.has(e)&&this.dirCache.delete(e),this.dirCache.set(e,t);this.dirCache.size>this.dirCacheMax;){let e=this.dirCache.keys().next();if(e.done)break;this.dirCache.delete(e.value)}}invalidate(e){if(e===``){this.dirCache.clear();return}let t=`${e}/`;for(let n of[...this.dirCache.keys()])(n===e||n.startsWith(t))&&this.dirCache.delete(n)}getDirCacheSize(){return this.dirCache.size}async resolveDirFrom(e,t,n,r=!0){let i=this.handle,a=``,o=0;if(r)for(let t=e.length;t>0;t--){let n=e.slice(0,t).join(`/`),r=this.cacheGet(n);if(r){i=r,a=n,o=t;break}}let s=a;for(;o<e.length;o++){let r=e[o];try{i=await i.getDirectoryHandle(r,{create:n})}catch(r){if(n&&s!==``)return this.invalidate(s),this.resolveDirFrom(e,t,n,!1);throw this.toFsError(r,t)}a=a===``?r:`${a}/${r}`,this.cacheSet(a,i)}return i}async resolveDir(e,t=!1){return this.resolveDirFrom(this.splitPath(e),e,t)}async resolveParent(e,t){let n=this.splitPath(e);if(n.length===0)throw new o(`EISDIR`,`is a directory`,e);let r=n.pop();return{parent:await this.resolveDirFrom(n,e,t),name:r}}async resolveFile(e,t=!1){let{parent:n,name:r}=await this.resolveParent(e,t);try{return await n.getFileHandle(r,{create:t})}catch(t){throw this.toFsError(t,e)}}toFsError(e,t){if(e instanceof o)return e;if(e instanceof DOMException){if(e.name===`NotFoundError`)return new o(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatchError`)return new o(`ENOTDIR`,`not a directory`,t);if(e.name===`NotAllowedError`)return new o(`EACCES`,`permission denied`,t);if(e.name===`InvalidModificationError`)return new o(`ENOTEMPTY`,`directory not empty`,t)}if(e instanceof Error){if(e.name===`NotFound`||e.name===`NotFoundError`)return new o(`ENOENT`,`no such file or directory`,t);if(e.name===`TypeMismatch`||e.name===`TypeMismatchError`)return new o(`ENOTDIR`,`not a directory`,t);if(e.name===`InvalidModification`||e.name===`InvalidModificationError`)return new o(`ENOTEMPTY`,`directory not empty`,t)}return new o(`EINVAL`,e instanceof Error?e.message:String(e),t)}async readDir(e,t){this.assertOpen(e);let n=await this.resolveDir(e),r=[];for await(let[e,i]of n){if(i.kind!==`file`){r.push({name:e,kind:`directory`});continue}if(!t?.includeStats){r.push({name:e,kind:`file`});continue}let n=await i.getFile();r.push({name:e,kind:`file`,size:n.size,lastModified:n.lastModified})}return r}async readFile(e){this.assertOpen(e);let t=await(await this.resolveFile(e)).getFile();return new Uint8Array(await t.arrayBuffer())}async getNativeFile(e){this.assertOpen(e);try{return await(await this.resolveFile(e)).getFile()}catch{return null}}async writeFile(e,t){this.assertOpen(e);let n=await(await this.resolveFile(e,!0)).createWritable();await n.write(t),await n.close()}async stat(e){this.assertOpen(e);let t=this.splitPath(e);if(t.length===0)return{kind:`directory`,size:0,mtime:0};let n=t.pop(),r=await this.resolveDirFrom(t,e,!1);try{let e=await(await r.getFileHandle(n)).getFile();return{kind:`file`,size:e.size,mtime:e.lastModified}}catch(t){let n=this.toFsError(t,e);if(n.code!==`ENOENT`&&n.code!==`ENOTDIR`)throw n}try{let e=await r.getDirectoryHandle(n);this.cacheSet(t.length===0?n:`${t.join(`/`)}/${n}`,e)}catch(t){throw this.toFsError(t,e)}return{kind:`directory`,size:0,mtime:0}}async mkdir(e){this.assertOpen(e),await this.resolveDir(e,!0)}async remove(e,t){this.assertOpen(e);let n=this.splitPath(e);if(n.length===0)throw new o(`EINVAL`,`cannot remove mount root`,e);let r=n.pop(),i=await this.resolveDirFrom(n,e,!1);try{await i.removeEntry(r,{recursive:t?.recursive??!1})}catch(t){throw this.toFsError(t,e)}this.invalidate(n.length===0?r:`${n.join(`/`)}/${r}`)}async refresh(){return this.assertOpen(`/`),this.dirCache.clear(),{added:[],removed:[],changed:[],unchanged:0,errors:[]}}describe(){return{displayName:this.handle.name}}async close(){this.closed=!0,this.dirCache.clear()}};async function be(e,t){let n=t.split(`/`).filter(Boolean),r=n.pop();if(r===void 0)return null;try{let t=e;for(let e of n)t=await t.getDirectoryHandle(e);return await(await t.getFileHandle(r)).getFile()}catch{return null}}function F(e,t){return e===t||e.startsWith(t===`/`?`/`:`${t}/`)}var xe=`/.metadata.json`,I=`.metadata.consistent.json`,L=`/${I}`;function R(e){return e.entries&&(delete e.entries[xe],delete e.entries[L]),e}function Se(e,t,n){let r=t.entries??{},i={...e.entries??{}};`/`in r&&(i[`/`]=r[`/`]);for(let e of n.paths)e in r?i[e]=r[e]:delete i[e];for(let e of n.prefixes){for(let t of Object.keys(i))F(t,e)&&delete i[t];for(let t of Object.keys(r))F(t,e)&&(i[t]=r[t])}let{entries:a,...o}=t;return R({...o,entries:i})}var z=1;async function Ce(e,t,n){let r=Math.max(1,Math.trunc(e)||1),i=Array(t.length),a=0,o=async()=>{for(;a<t.length;){let e=a;if(a+=1,e>=t.length)return;i[e]=await n(t[e],e)}},s=[],c=Math.min(r,t.length);for(let e=0;e<c;e+=1)s.push(o());return await Promise.all(s),i}async function B(e){let t=e;if(typeof t.createSyncAccessHandle==`function`)try{let e=await t.createSyncAccessHandle();try{return e.getSize()}finally{try{await e.close()}catch{}}}catch{}return(await e.getFile()).size}async function V(e){let t;for(let n=0;n<3;n+=1)try{return await(await e.getFile()).text()}catch(e){if(e?.name!==`NotReadableError`)throw e;t=e}throw t}function we(e){if(!e||typeof e!=`object`)return!1;let t=e.entries;return!!t&&typeof t==`object`}async function Te(e){try{let t=await V(await e.getFileHandle(`.metadata.json`)),n=JSON.parse(t);return we(n)?{text:t,doc:n}:null}catch{return null}}async function Ee(e,t){let n=await(await e.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await n.write(t),await n.close()}async function H(e){return r(e)}async function De(e,t){try{let n=await e.getFileHandle(I),r=JSON.parse(await V(n));if(!r||typeof r!=`object`)return!1;let i=r;return i.v!==z||typeof i.hash!=`string`?!1:i.hash===await H(t)}catch{return!1}}async function Oe(e,t){let n={v:z,hash:await H(t)},r=await(await e.getFileHandle(I,{create:!0})).createWritable();await r.write(JSON.stringify(n)),await r.close()}async function ke(e){try{await e.removeEntry(I)}catch(e){if(e?.name===`NotFoundError`)return;throw e}}async function Ae(e,t,n){let r=e,i=``,a=0;for(let e=n.length;e>0;--e){let o=n.slice(0,e).join(`/`),s=t.get(o);if(s){r=s,i=o,a=e;break}}for(let e=a;e<n.length;e+=1){let a=n[e];try{r=await r.getDirectoryHandle(a)}catch{return null}i=i?`${i}/${a}`:a,t.set(i,r)}return r}async function je(e,t,n,r,i,a){let o=async()=>{try{let n=await e.getDirectoryHandle(t);return i.set(a?`${a}/${t}`:t,n),{kind:`directory`}}catch{return null}},s=async()=>{try{let n=await e.getFileHandle(t);return r?{kind:`file`,size:await B(n)}:{kind:`file`,size:0}}catch{return null}};return n===`directory`?await o()??await s()??{kind:`missing`}:await s()??await o()??{kind:`missing`}}function U(e,t){let n=t?.includeSize!==!1,r=new Map;return async(t,i)=>{let a=t.split(`/`).filter(Boolean),o=await Ae(e,r,a.slice(0,-1));if(!o)return{kind:`missing`};let s=a[a.length-1];if(s===void 0)return{kind:`directory`};let c=a.slice(0,-1).join(`/`);return je(o,s,i,n,r,c)}}async function W(e){let t=new Map;for await(let[n,r]of e.entries())t.set(n,r);return t}function Me(e){return e.kind===`directory`?`directory`:e.kind===`file`?`file`:`other`}function Ne(e){if(typeof e.entries!=`function`)return U(e);let t=new Map,n=(e,n)=>{let r=t.get(n);if(r!=null)return r;let i=W(e).catch(e=>{throw t.delete(n),e});return t.set(n,i),i};return async t=>{let r=t.split(`/`).filter(Boolean),i=e,a=``;for(let e=0;e<r.length;e+=1){let t=r[e],o=(await n(i,a)).get(t);if(!o)return{kind:`missing`};let s=Me(o);if(e!==r.length-1){if(s!==`directory`)return{kind:`missing`};i=o,a=`${a}/${t}`;continue}return s===`directory`?{kind:`directory`}:s===`file`?{kind:`file`,size:await B(o)}:{kind:`missing`}}return{kind:`directory`}}}var Pe=61440,G=16384,K=32768,Fe=40960;async function Ie(e,t,n,r=16){let i=q(),a=e.entries??{},o=[];for(let[e,t]of Object.entries(a)){let r=Le(e,t,a,i);r?o.push(r):n?.()}return Re(o,await Ce(r,o,async e=>{n?.();let r=e.fmt===G?`directory`:`file`;return t(e.path,r)}),a,i),ze(a,i),i}function q(){return{kindFixed:[],sizesFixed:0,dropped:0,selfEntryDropped:!1,inosReassigned:0,nlinksFixed:0,changed:!1}}function Le(e,t,n,r){if(e===`/`||typeof t!=`object`||!t)return null;if(e===`/.metadata.json`||e===L)return delete n[e],e===`/.metadata.json`&&(r.selfEntryDropped=!0),r.changed=!0,null;let i=t,a=(i.mode??0)&Pe;return a===Fe?(J(i,r),null):{path:e,entry:i,fmt:a}}function Re(e,t,n,r){for(let i=0;i<e.length;i+=1){let a=e[i],o=t[i];if(o.kind===`missing`){delete n[a.path],r.dropped+=1,r.changed=!0;continue}J(a.entry,r),Be(a.path,a.entry,a.fmt,o,r)}}function ze(e,t){let n=0;for(let t of Object.values(e)){let e=t;typeof e?.ino==`number`&&(n=Math.max(n,e.ino)),typeof e?.data==`number`&&(n=Math.max(n,e.data))}let r=n+1,i=new Set;for(let[n,a]of Object.entries(e)){if(typeof a!=`object`||!a)continue;let e=a;if(n===`/`){typeof e.ino==`number`&&i.add(e.ino);continue}let o=e.ino;if(typeof o==`number`&&o!==0&&!i.has(o)){i.add(o);continue}e.ino=r,e.data=r+1,i.add(r),r+=2,t.inosReassigned+=1,t.changed=!0}}function J(e,t){e.nlink||(e.nlink=1,t.nlinksFixed+=1,t.changed=!0)}function Be(e,t,n,r,i){if(n===K&&r.kind===`directory`){t.mode=((t.mode??0)&511||493)|G,i.kindFixed.push(`${e} file→dir`),i.changed=!0;return}if(n===G&&r.kind===`file`){t.mode=((t.mode??0)&511||420)|K,t.size=r.size,i.kindFixed.push(`${e} dir→file`),i.changed=!0;return}n===K&&r.kind===`file`&&typeof t.size==`number`&&t.size!==r.size&&(t.size=r.size,i.sizesFixed+=1,i.changed=!0)}async function Ve(e,t,n){try{return await e()}catch(r){let i=null;try{i=await t()}catch{}if(!i?.changed)throw r;return n(i),await e()}}async function He(e,t){let n=await Te(e);if(!n)return null;if(await De(e,n.text))return q();let r=await Ie(n.doc,Ne(e),t),i=r.changed?JSON.stringify(n.doc):n.text;r.changed&&await Ee(e,i);try{await Oe(e,i)}catch{}return r}function Y(e,t,n=0){if(!(!Number.isSafeInteger(t)||(t??0)<=0||!Number.isSafeInteger(n)||n<0))return JSON.stringify([e,n,t])}async function Ue(e,t,n,r){try{return await e.lstat(t)}catch(e){let t=k(e,r);if(t.code===`ENOENT`&&n)return null;throw t}}async function We(e,t,n){let r;try{r=await e.readlink(t)}catch(e){throw k(e,n)}return r.startsWith(`/`)?l(r):l(d(s(t).dir,r))}async function Ge(e,t,n,r,i,a,s){let c=n===`/`?`/${r}`:`${n}/${r}`;for(;;){let n=await Ue(e,c,i,a);if(n===null||!n.isSymbolicLink())return{resolved:c,hops:s};if(++s>10)throw new o(`ELOOP`,`too many symbolic links encountered`,a);if(c=await We(e,c,a),t(c))return{resolved:c,hops:s}}}async function X(e,t,n){let r=l(n);if(t(r))return r;let i=r.split(`/`).filter(Boolean),a=`/`,o=0;for(let n=0;n<i.length;n++){let s=await Ge(e,t,a,i[n],n===i.length-1,r,o);if(a=s.resolved,o=s.hops,t(a)){let e=i.slice(n+1);return e.length>0?`${a}/${e.join(`/`)}`:a}}return a}async function Ke(e,t,n){return t(n)?n:X(e,t,n)}function Z(){try{if(typeof globalThis.navigator?.storage?.getDirectory==`function`)return`opfs`}catch{}return`memory`}var qe=100,Q=1e3,Je=3e4;function Ye(e,t){let n=e.kind===`directory`?`directory`:`file`;return t?{name:e.name,type:n,...e.size===void 0?{}:{size:e.size},...e.lastModified===void 0?{}:{mtime:e.lastModified},...e.ctime===void 0?{}:{ctime:e.ctime},...e.ino===void 0?{}:{ino:e.ino},...e.identity===void 0?{}:{identity:e.identity},...e.dev===void 0?{}:{dev:e.dev},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}:{name:e.name,type:n}}function Xe(e,t){switch(e.kind){case`local`:case`proc`:return{kind:`local`,mountId:e.mountId,idbHandleKey:t};case`hostfs`:return{kind:`hostfs`,mountId:e.mountId,hostPath:e.getHostPath()};default:return{kind:e.kind===`s3`?`s3`:e.kind===`aem`?`aem`:`da`,mountId:e.mountId,source:e.source,profile:e.profile??`default`}}}function Ze(e,t){if(e===`symlink`&&t!==`directory`)return`link`;if(e===`directory`&&t===`directory`)return`dir`}function Qe(e){let t=e.lastIndexOf(`/`),n=Math.random().toString(36).slice(2,10);return`${e.slice(0,t+1)}.${e.slice(t+1)}.slicc-rename-${n}`}var $e=8,$=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 x;static writeChains=new Map;onRepairProgress;constructor(t,n,r,i,a,o){if(this.dbName=t,this.onRepairProgress=a,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,o):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,n).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 opfsInitChains=new Map;static async initOpfsBackend(t,n,r,i){let a=(e.opfsInitChains.get(t.dbName)??Promise.resolve()).catch(()=>{}).then(()=>e.resolveOpfsBackend(t,n,r,i));e.opfsInitChains.set(t.dbName,a);try{await a}finally{e.opfsInitChains.get(t.dbName)===a&&e.opfsInitChains.delete(t.dbName)}}static async resolveOpfsBackend(n,r,i,a){let s=e.opfsBackends.get(n.dbName);if(s&&i)throw new o(`EBUSY`,`Cannot wipe an OPFS backend with live holders`,n.dbName);if(s&&a!==void 0&&s.asyncCache!==a)throw new o(`EBUSY`,`OPFS async cache setting conflicts with the live backend`,n.dbName);let c=r??await e.acquireOpfsHandle(n.dbName,i);await n.withWriteLock(()=>e.seedOpfsMetadataSidecarIfMissing(c));let l=await t(()=>import(`./dist-C8GTDH_7.js`),__vite__mapDeps([0,1,2]));await e.ensureRootMount(l);let u=`/__opfs__/${n.dbName}`,d=e.opfsBackends.get(n.dbName);if(!d){let{resolveOpfsMount:r}=await t(async()=>{let{resolveOpfsMount:e}=await import(`./opfs-mount-DHQkCQyR.js`);return{resolveOpfsMount:e}},__vite__mapDeps([3,0,1,2])),i=await r({handle:c,dbName:n.dbName,asyncCache:a,onRepairProgress:n.onRepairProgress,withWriteLock:e=>n.withWriteLock(e)});try{l.mount(u,i)}catch{}d={backendFs:i,refs:0,asyncCache:a!==!1,sidecarDirty:{paths:new Set,prefixes:new Set},sidecarFlushTimer:null,sidecarFlushRetryMs:Q},e.opfsBackends.set(n.dbName,d)}d.refs+=1,n.opfsBackendFs=d.backendFs.index?d.backendFs:null,n.opfsHandle=c,n.mountRoot=u,n.rawLfs=l.promises,n.rawLfsSync=l}static async initMemoryBackend(n,r,i){let a=await t(()=>import(`./dist-C8GTDH_7.js`),__vite__mapDeps([0,1,2]));await e.ensureRootMount(a);let o=`/__zenfs__/${r}`,s=e.memoryBackends.get(r);if(s&&i){try{a.umount(o)}catch{}e.memoryBackends.delete(r),s=void 0}s||(s={store:a.InMemory.create({label:r}),refs:0},e.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(t){return e.rootMountReady===null&&(e.rootMountReady=(async()=>{await t.configureSingle({backend:t.InMemory,label:`__vfs_root__`})})()),e.rootMountReady}prefix(e){return this.mountRoot?e===`/`?this.mountRoot:this.mountRoot+e:e}unprefix(e){return!this.mountRoot||!e.startsWith(this.mountRoot)?e:e.slice(this.mountRoot.length)||`/`}makeDeferredLfs(){let e=e=>this.prefix(e),t=e=>this.unprefix(e),n=()=>{if(!this.rawLfs)throw Error(`VirtualFS used before init resolved`);return this.rawLfs};return{readFile:(t,r)=>this._readyResolved?n().readFile(e(t),r):this._ready.then(()=>n().readFile(e(t),r)),writeFile:(t,r,i)=>this._readyResolved?n().writeFile(e(t),r,i):this._ready.then(()=>n().writeFile(e(t),r,i)),appendFile:async(t,r)=>{this._readyResolved||await this._ready,await n().appendFile(e(t),r)},chmod:async(t,r)=>{this._readyResolved||await this._ready,await n().chmod(e(t),r)},utimes:async(t,r,i)=>{this._readyResolved||await this._ready,await n().utimes(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(t){let n=`.metadata.json`;try{let r=await t.getFileHandle(n);if(e.isUsableMetadataDocument(await e.readSidecarText(r)))return;console.warn(`[virtual-fs] metadata sidecar is unparseable (torn write?); reseeding an empty index`)}catch(e){if(e?.name!==`NotFoundError`)throw e}let r=await(await t.getFileHandle(n,{create:!0})).createWritable(),i=JSON.stringify({version:1,maxSize:4294967295,entries:{}});await r.write(i),await r.close()}static async readSidecarText(e){let t;for(let n=0;n<3;n++)try{return await(await e.getFile()).text()}catch(e){if(e?.name!==`NotReadableError`)throw e;t=e}throw t}static isUsableMetadataDocument(e){let t;try{t=JSON.parse(e)}catch{return!1}if(!t||typeof t!=`object`)return!1;let n=t.entries;return!!n&&typeof n==`object`}static async acquireOpfsHandle(e,t){let n=navigator.storage;if(!n?.getDirectory)throw new o(`EINVAL`,`OPFS is not available in this environment`);let r=await n.getDirectory();if(t)try{await r.removeEntry(e,{recursive:!0})}catch{}return r.getDirectoryHandle(e,{create:!0})}static _createSyncForTests(t){return new e(t)}static async create(t){let n=t?.dbName??`browser-fs`,r=t?.wipe===!0,i=t?.backend??Z(),a=new e(n,r,i,void 0,t?.onRepairProgress,t?.opfsAsyncCache);try{await a._ready}catch(e){throw a.mountSyncChannel?.close(),e}return r&&await oe().catch(()=>{}),a}async flush(){await this.writeOpfsMetadataSidecar()}async writeOpfsMetadataSidecar(){this.backend===`opfs`&&await this.withWriteLock(()=>this.writeOpfsMetadataSidecarUnlocked())}async writeOpfsMetadataSidecarUnlocked(){if(this.backend!==`opfs`)return;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t||!n)return;let r=t.index.toJSON(),i=e.opfsBackends.get(this.dbName)?.sidecarDirty,a=r;if(i){let e=null;try{let t=await n.getFileHandle(`.metadata.json`),r=JSON.parse(await(await t.getFile()).text());r&&typeof r==`object`&&r.entries&&(e=r)}catch{}e&&(await this.auditDirtyKindFlips(r,e,i,n),a=Se(e,r,i))}let o=JSON.stringify(R(a)),s=await(await n.getFileHandle(`.metadata.json`,{create:!0})).createWritable();await s.write(o),await s.close(),i&&(i.paths.clear(),i.prefixes.clear());let c=e.opfsBackends.get(this.dbName);c&&(c.sidecarFlushRetryMs=Q),c&&c.sidecarFlushTimer!==null&&(clearTimeout(c.sidecarFlushTimer),c.sidecarFlushTimer=null)}scheduleMetadataSidecarFlush(t=qe){if(this.backend!==`opfs`)return;let n=e.opfsBackends.get(this.dbName);n&&(n.sidecarFlushTimer!==null&&clearTimeout(n.sidecarFlushTimer),n.sidecarFlushTimer=setTimeout(()=>{n.sidecarFlushTimer=null,this.writeOpfsMetadataSidecar().catch(t=>{if(console.warn(`[virtual-fs] deferred metadata sidecar flush failed`,t),e.opfsBackends.get(this.dbName)!==n||n.sidecarFlushTimer!==null||n.sidecarDirty.paths.size===0&&n.sidecarDirty.prefixes.size===0)return;let r=n.sidecarFlushRetryMs;n.sidecarFlushRetryMs=Math.min(r*2,Je),this.scheduleMetadataSidecarFlush(r)})},t))}async auditDirtyKindFlips(e,t,n,r){let i=ye(e,t,n.paths,n.prefixes);if(i.length===0)return;let a=U(r),o=this.opfsBackendFs;for(let n of i){let r=await a(n.path).catch(()=>null);if(r!==null&&r.kind!==`missing`&&r.kind===`directory`===n.ownIsDirectory)continue;let i=t.entries?.[n.path];e.entries&&i!==void 0&&(e.entries[n.path]=i);let s=r!==null&&r.kind!==`missing`;s&&(o?.index?.delete(n.path),o?._handles?.delete(n.path)),console.warn(`[virtual-fs] refused to flush in-memory kind flip over sidecar record (#2006)`,{path:n.path,reality:r?.kind??`unverifiable`,evicted:s})}}markSidecarDirty(t,n=`path`){if(this.backend!==`opfs`)return;let r=e.opfsBackends.get(this.dbName)?.sidecarDirty;if(!r)return;let i=l(t);(n===`prefix`?r.prefixes:r.paths).add(i);let{dir:a}=s(i);for(;a!==`/`;)r.paths.add(a),a=s(a).dir}async forgetSidecarConsistency(){await this.dropSidecarConsistency()}sidecarConsistencyDrop=null;dropSidecarConsistency(){if(this.backend!==`opfs`||!this.opfsHandle)return Promise.resolve();if(!this.sidecarConsistencyDrop){let e=this.opfsHandle;this.sidecarConsistencyDrop=ke(e).catch(e=>{throw this.sidecarConsistencyDrop=null,e})}return this.sidecarConsistencyDrop}invalidatePaths(e){if(this.backend!==`opfs`||!this.opfsBackendFs)return;e.length>0&&this.dropSidecarConsistency().catch(()=>void 0);let t=this.opfsBackendFs;for(let n of e){let e=l(n);t.index.delete(e),t._handles?.delete(e),this.markSidecarDirty(e)}}async withKindMismatchRetry(e,t){return this.withKindMismatchRetryPaths([e],t)}async withKindMismatchRetryPaths(e,t){try{return await t()}catch(n){let r=n?.code;if(r!==`EISDIR`&&r!==`ENOTDIR`&&r!==`EINVAL`)throw n;for(let n of e)if(await this.reconcileKindMismatch(n).catch(()=>!1))return await t();throw n}}async reconcileKindMismatch(e){if(this.backend!==`opfs`)return!1;let t=this.opfsBackendFs,n=this.opfsHandle;if(!t?.index||!n)return!1;let r=l(e),i=r;try{i=await this.resolveSymlinks(r)}catch{}let a=await U(n)(i),o=A(t.index.get(i)?.mode),s=t._handles?.get(i),c=s?.kind===`directory`?`directory`:s?.kind===`file`?`file`:`absent`,u=j(a,o),d=j(a,c);if(!u&&!d)return!1;if(t.index.delete(i),t._handles?.delete(i),o===`directory`||c===`directory`){let e=`${i}/`;for(let n of[...t.index.keys()])n.startsWith(e)&&t.index.delete(n);if(t._handles)for(let n of[...t._handles.keys()])n.startsWith(e)&&t._handles.delete(n)}return this.markSidecarDirty(i),console.warn(`[virtual-fs] reconciled in-memory kind mismatch (#2006)`,{path:i,reality:a.kind,indexHeld:o,handleHeld:c}),!0}localIdentity(e){return Y(`zenfs:${this.backend}:${this.dbName}`,e)}canWrite(e){return!0}setWatcher(e){this.watcher=e}getWatcher(){return this.watcher}async watch(e,t){let n=this.watcher;if(!n)throw new o(`ENOSYS`,`no FsWatcher attached to this VirtualFS`);let r=e.map(e=>n.watch(e,()=>!0,t));return()=>{for(let e of r)e()}}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`?e.opfsBackends:e.memoryBackends,r=n.get(this.dbName);if(r&&(--r.refs,r.refs<=0)){n.delete(this.dbName);try{(await t(()=>import(`./dist-C8GTDH_7.js`),__vite__mapDeps([0,1,2]))).umount(this.mountRoot)}catch{}}}}syncDirEntry(e,t){let n=t.isSymbolicLink()?`symlink`:t.isDirectory()?`directory`:`file`;return n===`symlink`?{name:e,type:n}:{name:e,type:n,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs,...t.ino===void 0?{}:{ino:t.ino,identity:this.localIdentity(t.ino),dev:t.dev},...t.uid===void 0?{}:{uid:t.uid},...t.gid===void 0?{}:{gid:t.gid},mode:t.mode}}readDirSync(e){let t=l(e);if(this.findMount(t)||this.linksOntoMountSync(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{r.push(this.syncDirEntry(i,n.lstatSync(e)))}catch{}}return r}catch{return null}}linksOntoMountSync(e){let t=this.lfsSync;if(this.mountPoints.size===0||e===`/`||typeof t.readlinkSync!=`function`)return!1;let n=e;try{for(let e=0;e<=10;e++){if(!t.lstatSync?.(n).isSymbolicLink())return!1;let e=t.readlinkSync(n);if(n=e.startsWith(`/`)?l(e):l(d(s(n).dir,e)),this.findMount(n))return!0}}catch{}return!1}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;if(t===`/`)try{let e=n.statSync(t);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}catch{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,ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode};let t;try{t=n.readlinkSync(r)}catch{return null}if(r=t.startsWith(`/`)?l(t):l(d(s(r).dir,t)),this.findMount(r))return null}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;if(t===`/`)return this.statSync(t);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,ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev,mode:e.mode}}catch{return null}}async mount(e,t,n){let r=l(e);if(this.mountPoints.has(r))throw new o(`EEXIST`,`mount point is already mounted`,r);try{if((await this.lstat(r)).type!==`directory`)throw new o(`ENOTDIR`,`mount point must be a directory`,r);if((await this.readDir(r)).length>0)throw new o(`ENOTEMPTY`,`mount point must be empty to avoid shadowing existing files`,r)}catch(e){if(!(e instanceof o)||e.code!==`ENOENT`)throw e}let{dir:i}=s(r);i!==`/`&&await this.mkdir(i,{recursive:!0}),await this.dropSidecarConsistency();try{await this.lfs.mkdir(r)}catch{}if(this.mountPoints.set(r,t),t.kind===`local`){let e=n?.limits??b(n?.env??{});this.mountIndex.registerMount(r,t.getHandle(),e)}let a=Xe(t,r);try{this.mountSyncChannel?.postMessage({type:`mount`,path:r,descriptor:a})}catch{}if(this.watcher?.notify([{type:`modify`,path:r,entryType:`directory`}]),t.kind!==`hostfs`)try{let e={targetPath:r,descriptor:a,createdAt:Date.now()},n=t.kind===`local`?t.getHandle():void 0;await re(e,n)}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 ie(t)}catch{}}async reconstructBackendFromDescriptor(e,n){switch(e.kind){case`local`:{let t=await ae(e.idbHandleKey);if(!t)throw Error(`no handle stored for ${e.idbHandleKey}`);return P.fromHandle(t,{mountId:e.mountId})}case`hostfs`:{let{HostFsMountBackend:r}=await t(async()=>{let{HostFsMountBackend:e}=await import(`./backend-hostfs-BlwgXw0-.js`);return{HostFsMountBackend:e}},__vite__mapDeps([4,5,6,7,8]));return new r({targetPath:n,hostPath:e.hostPath,mountId:e.mountId})}case`s3`:{let{S3MountBackend:n,RemoteMountCache:r,makeSignedFetchS3:i}=await t(async()=>{let{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}=await import(`./mount-iiKbRe20.js`);return{S3MountBackend:e,RemoteMountCache:t,makeSignedFetchS3:n}},__vite__mapDeps([9,10,11,12,7,13,1,8])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i(e.profile)})}case`da`:{let{DaMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await t(async()=>{let{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-iiKbRe20.js`);return{DaMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([9,10,11,12,7,13,1,8])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.mountId,signedFetch:i()})}case`aem`:{let{AemMountBackend:n,RemoteMountCache:r,makeSignedFetchDa:i}=await t(async()=>{let{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}=await import(`./mount-iiKbRe20.js`);return{AemMountBackend:e,RemoteMountCache:t,makeSignedFetchDa:n}},__vite__mapDeps([9,10,11,12,7,13,1,8])),a=new r({mountId:e.mountId,ttlMs:3e4});return new n({source:e.source,profile:e.profile,cache:a,mountId:e.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}getMountBackend(e){let t=l(e);return this.mountPoints.get(t)??null}async mountInternal(e,t){let n=l(e);if(this.mountPoints.has(n))throw new o(`EEXIST`,`mount point is already mounted`,n);let{dir:r}=s(n);r!==`/`&&await this.mkdir(r,{recursive:!0}),await this.dropSidecarConsistency();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 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=l(e),r=this.mountPoints.get(n);if(!r)throw new o(`ENOENT`,`not a mount point`,n);let i=await r.refresh(t);return r.kind===`local`&&await this.mountIndex.refreshMount(n,b(t?.env??{})),this.watcher?.notify([{type:`modify`,path:n,entryType:`directory`}]),i}isPathUnderMount(e){for(let t of this.mountPoints.keys())if(e===t||e.startsWith(t+`/`))return!0;return!1}findMount(e){let t=null;for(let[n,r]of this.mountPoints)(e===n||e.startsWith(n+`/`))&&(!t||n.length>t.mountPath.length)&&(t={mountPath:n,backend:r});return t?e===t.mountPath?{path:t.mountPath,backend:t.backend,relParts:[]}:{path:t.mountPath,backend:t.backend,relParts:e.slice(t.mountPath.length+1).split(`/`).filter(Boolean)}:null}async readFile(e,t){return this.withKindMismatchRetry(e,()=>this.readFileInner(e,t))}async readFileInner(e,t){let n=l(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new o(`EISDIR`,`is a directory`,n);let e=r.relParts.join(`/`);try{let n=await r.backend.readFile(e);return(t?.encoding??`utf-8`)===`utf-8`?new TextDecoder(`utf-8`).decode(n):n}catch(e){O(e,n)}}let i=await this.resolveSymlinks(n),a=this.onMount(i,n);if(a)return this.readFileInner(a,t);try{return(t?.encoding??`utf-8`)===`utf-8`?await this.lfs.readFile(i,{encoding:`utf8`}):await this.lfs.readFile(i)}catch(e){throw k(e,n)}}async readFileRange(e,t,n){let r=l(e);if(!Number.isInteger(t)||!Number.isInteger(n)||t<0||n<t)throw new o(`EINVAL`,`invalid byte range ${t}-${n}`,r);if(t===n)return new Uint8Array;let i=this.findMount(r),a=i?.backend.readFileRange;if(i&&a){if(i.relParts.length===0)throw new o(`EISDIR`,`is a directory`,r);try{return await a.call(i.backend,i.relParts.join(`/`),t,n)}catch(e){O(e,r)}}let s=await this.sliceNativeFile(r,t,n);if(s)return s;let c=await this.readFile(r,{encoding:`binary`});return new Uint8Array(c.subarray(t,Math.min(n,c.byteLength)))}async sliceNativeFile(e,t,n){try{let r=await this.getNativeFile(e);if(!r)return null;let i=r.slice(t,Math.min(n,r.size));return new Uint8Array(await i.arrayBuffer())}catch{return null}}async getNativeFile(e){let t=l(e),n=this.findMount(t);if(n){let e=n.backend.getNativeFile;if(!e||n.relParts.length===0)return null;try{return await e.call(n.backend,n.relParts.join(`/`))}catch{return null}}let r;try{r=await this.resolveSymlinks(t)}catch{return null}let i=this.onMount(r,t);if(i)return this.getNativeFile(i);let a=this.opfsHandle;if(!a)return null;try{return await be(a,r)}catch{return null}}async writeFile(e,t,n){return this.withKindMismatchRetry(e,()=>this.writeFileInner(e,t,n))}async writeFileInner(e,t,n){let r=l(e),i=this.findMount(r);if(i){if(i.relParts.length===0)throw new o(`EISDIR`,`is a directory`,r);let e=i.relParts.join(`/`),n=!1;try{await this.stat(r),n=!0}catch{}let a=typeof t==`string`?new TextEncoder().encode(t):t instanceof Uint8Array?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):new Uint8Array(t);try{await i.backend.writeFile(e,a)}catch(e){O(e,r)}this.watcher?.notify([{type:n?`modify`:`create`,path:r,entryType:`file`}]),this.mountIndex.notifyWrite(r);return}let a;try{a=await this.resolveSymlinks(r)}catch{a=r}let c=this.onMount(a,r);if(c)return this.writeFileInner(c,t,n);let u=!1;try{await this.lfs.stat(a),u=!0}catch{}let{dir:d}=s(a);await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),this.markSidecarDirty(a),d!==`/`&&await this.mkdirRecursiveUnlocked(d);let e=typeof t==`string`?new TextEncoder().encode(t).byteLength:(t instanceof Uint8Array,t.byteLength);try{await this.lfs.writeFile(a,t)}catch(e){if(d!==`/`&&e instanceof Error&&e.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(d);try{await this.lfs.writeFile(a,t)}catch(e){throw k(e,r)}}else throw k(e,r)}try{await this.lfs.truncate?.(a,e)}catch(e){throw k(e,r)}}),this.watcher?.notify([{type:u?`modify`:`create`,path:a,entryType:`file`}])}async appendFile(e,t){let n=l(e);await this.withKindMismatchRetry(n,()=>this.withWriteLock(async()=>{if(this.findMount(n)){await this.appendMounted(n,t);return}await this.dropSidecarConsistency();let e=n,r=!1;try{e=await this.resolveSymlinks(n);let i=this.onMount(e,n);if(i){await this.appendMounted(i,t);return}if((await this.lfs.stat(e)).isDirectory())throw new o(`EISDIR`,`is a directory`,n);r=!0}catch(e){let t=k(e,n);if(t.code!==`ENOENT`)throw t}this.markSidecarDirty(e);let{dir:i}=s(e);await this.mkdirRecursiveUnlocked(i);try{await this.lfs.appendFile(e,t)}catch(e){throw k(e,n)}this.watcher?.notify([{type:r?`modify`:`create`,path:e,entryType:`file`}])}))}async appendMounted(e,t){let n=new Uint8Array;try{let t=await this.readFileInner(e,{encoding:`binary`});n=typeof t==`string`?new TextEncoder().encode(t):new Uint8Array(t)}catch(t){let n=k(t,e);if(n.code!==`ENOENT`)throw n}let r=typeof t==`string`?new TextEncoder().encode(t):t,i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),await this.writeFileInner(e,i)}async chmod(e,t){let n=l(e);if(this.findMount(n))throw await this.stat(n),new o(`ENOSYS`,`metadata changes are not supported by this mount`,n);await this.applyMetadataUpdates([{path:e,mode:t}],!1)}async utimes(e,t,n){let r=l(e);if(this.findMount(r))throw await this.stat(r),new o(`ENOSYS`,`metadata changes are not supported by this mount`,r);await this.applyMetadataUpdates([{path:e,atime:t,mtime:n}],!1)}async updateMetadataBatch(e){await this.applyMetadataUpdates(e,!0)}async applyMetadataUpdates(e,t){if(e.length===0)return;let n=e.map(e=>this.prepareMetadataUpdate(e)),r=n.map(e=>e.normalized);await this.withKindMismatchRetryPaths(r,()=>this.withWriteLock(async()=>{await this.dropSidecarConsistency();let e=[];for(let t of n){let n=await this.applyPreparedMetadataUpdate(t);n&&e.push(n)}e.length!==0&&(t?await this.writeOpfsMetadataSidecarUnlocked():this.scheduleMetadataSidecarFlush(),this.watcher?.notify(e))}))}async applyPreparedMetadataUpdate(e){if(this.findMount(e.normalized))return await this.stat(e.normalized),null;let t=await this.resolveSymlinks(e.normalized);if(this.onMount(t,e.normalized))return await this.stat(t),null;try{let n=await this.lfs.stat(t);return this.markSidecarDirty(t),e.mode!==void 0&&await this.lfs.chmod(t,e.mode),e.atime!==void 0&&e.mtime!==void 0&&await this.lfs.utimes(t,e.atime,e.mtime),{type:`modify`,path:t,entryType:n.isDirectory()?`directory`:`file`}}catch(t){throw k(t,e.normalized)}}prepareMetadataUpdate(e){let t=l(e.path);if(e.mode!==void 0&&(!Number.isInteger(e.mode)||e.mode<0||e.mode>4095))throw new o(`EINVAL`,`invalid file mode`,t);if(e.atime!==void 0||e.mtime!==void 0){if(e.atime===void 0||e.mtime===void 0)throw new o(`EINVAL`,`atime and mtime must both be provided`,t);if(!Number.isFinite(e.atime.getTime())||!Number.isFinite(e.mtime.getTime()))throw new o(`EINVAL`,`invalid file time`,t)}if(e.mode===void 0&&e.atime===void 0)throw new o(`EINVAL`,`metadata update requires mode and/or times`,t);return{normalized:t,mode:e.mode,atime:e.atime,mtime:e.mtime}}async readDir(e,t){let n=l(e),r=this.findMount(n);return r?this.readDirMounted(n,r,t):this.readDirLocal(n)}async readDirMounted(e,t,n){let r=n?.includeStats===!0?void 0:this.mountIndex.getDirectoryEntries(t.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=t.relParts.join(`/`)||`/`,a;try{a=await t.backend.readDir(i,n)}catch(t){O(t,e)}let o=new Map,s=t.backend.listingStatsMatchStat===!0;for(let e of a)o.set(e.name,Ye(e,s));return this.addNestedMountEntries(o,e),[...o.values()]}async readDirLocal(e){return this.withKindMismatchRetry(e,()=>this.readDirLocalInner(e))}async readDirLocalInner(e){let t=await this.resolveSymlinks(e),n=this.onMount(t,e);if(n)return this.readDir(n);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 k(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`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,...e.ino===void 0?{}:{ino:e.ino,identity:this.localIdentity(e.ino),dev:e.dev},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},mode:e.mode}}catch{return null}}addNestedMountEntries(e,t){let n=t===`/`?`/`:`${t}/`;for(let r of this.mountPoints.keys()){if(r===t||!r.startsWith(n))continue;let i=r.slice(n.length);i&&!i.includes(`/`)&&(e.has(i)||e.set(i,{name:i,type:`directory`}))}}async withWriteLock(t){let n=this.dbName,r,i=new Promise(e=>{r=e}),a=e.writeChains.get(n)??Promise.resolve();e.writeChains.set(n,i),await a;try{let e=globalThis.navigator?.locks;return this.backend!==`opfs`||typeof e?.request!=`function`?await t():await e.request(`slicc-vfs:${n}`,()=>t())}finally{r(),e.writeChains.get(n)===i&&e.writeChains.delete(n)}}async mkdirRecursiveUnlocked(e){let t=e.split(`/`).filter(Boolean),n=[],r=``;for(let e of t){r+=`/`+e;try{await this.lfs.mkdir(r),n.push(r)}catch(e){if(e instanceof Error&&!e.message.includes(`EEXIST`))throw k(e,r);try{let e=await this.lfs.lstat(r);if(!e.isDirectory()&&!e.isSymbolicLink())throw new o(`ENOTDIR`,`not a directory`,r)}catch(e){if(e instanceof o&&e.code===`ENOTDIR`)throw e}}}return n}async mkdir(e,t){let n=l(e);if(n===`/`)return;let r=this.mountPoints.size>0?await this.parentOnMount(n):void 0;if(r)return this.mkdir(r,t);let i=this.findMount(n);if(i){if(i.relParts.length===0)return;let e=i.relParts.join(`/`),t=await this.exists(n);try{await i.backend.mkdir(e)}catch(e){O(e,n)}t||this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}]);return}if(t?.recursive){let e=await this.withWriteLock(async()=>(await this.dropSidecarConsistency(),this.markSidecarDirty(n),this.mkdirRecursiveUnlocked(n)));e.length>0&&this.watcher?.notify(e.map(e=>({type:`create`,path:e,entryType:`directory`})))}else await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),this.markSidecarDirty(n);try{await this.lfs.mkdir(n)}catch(e){throw k(e,n)}}),this.watcher?.notify([{type:`create`,path:n,entryType:`directory`}])}async rm(e,t){return this.withKindMismatchRetry(l(e),()=>this.viaMountOnEnoent(l(e),e=>this.rmInner(e,t)))}async rmInner(e,t){let n=l(e),r=this.findMount(n);if(r){if(r.relParts.length===0)throw new o(`EINVAL`,`cannot remove a mount point — use unmount`,n);let e;try{e=(await this.stat(n)).type}catch{}let i=r.relParts.join(`/`);try{await r.backend.remove(i,{recursive:t?.recursive})}catch(e){O(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:e}]),this.mountIndex.notifyDelete(n);return}try{let e=await this.lfs.lstat(n);await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),e.isSymbolicLink()?await this.lfs.unlink(n):e.isDirectory()?t?.recursive?await this.rmRecursiveUnlocked(n):await this.lfs.rmdir(n):await this.lfs.unlink(n),this.markSidecarDirty(n,`prefix`)}),this.scheduleMetadataSidecarFlush()}catch(e){throw k(e,n)}this.watcher?.notify([{type:`delete`,path:n}])}async rmRecursiveUnlocked(e){let t=await this.lfs.readdir(e);for(let n of t){let t=e===`/`?`/${n}`:`${e}/${n}`,r=await this.lfs.lstat(t);r.isSymbolicLink()?await this.lfs.unlink(t):r.isDirectory()?await this.rmRecursiveUnlocked(t):await this.lfs.unlink(t)}await this.lfs.rmdir(e)}async stat(e){return this.withKindMismatchRetry(e,()=>this.statInner(e))}async statMounted(e,t){if(t.relParts.length===0)try{let t=await this.lfs.stat(e);return{type:`directory`,size:t.size,mtime:t.mtimeMs,ctime:t.ctimeMs}}catch{return{type:`directory`,size:0,mtime:Date.now(),ctime:Date.now()}}let n=t.relParts.join(`/`);try{let e=await t.backend.stat(n);return{type:e.kind===`directory`?`directory`:`file`,size:e.size,mtime:e.mtime,ctime:e.ctime??e.mtime,...e.ino===void 0?{}:{ino:e.ino},...e.identity===void 0?{}:{identity:e.identity},...e.dev===void 0?{}:{dev:e.dev},...e.uid===void 0?{}:{uid:e.uid},...e.gid===void 0?{}:{gid:e.gid},...e.mode===void 0?{}:{mode:e.mode}}}catch(t){O(t,e)}}async statInner(e){let t=l(e),n=this.findMount(t);if(n)return this.statMounted(t,n);let r=await this.resolveSymlinks(t),i=this.onMount(r,t);if(i)return this.statInner(i);try{let e=await this.lfs.stat(r);return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw k(e,t)}}async exists(e){let t=l(e),n=this.findMount(t);if(n){if(n.relParts.length===0)return!0;try{return await this.stat(t),!0}catch{return!1}}try{return await this.stat(t),!0}catch{try{return await this.lfs.lstat(t),!0}catch{return!1}}}async rename(e,t){return this.withKindMismatchRetryPaths([l(e),l(t)],()=>this.renameInner(e,t))}async renameInner(e,t){if(this.mountPoints.size>0){let[n,r]=await Promise.all([this.parentOnMount(l(e)),this.parentOnMount(l(t))]);if(n||r)return this.renameInner(n??e,r??t)}let n=l(e),r=l(t);if(n===r)return;let a;try{a=await this.lstat(n)}catch{}let o=a?.type,s=this.findMount(n);if(s?.backend.rename){let e=this.findMount(r);if(e&&e.backend===s.backend){let t=!1;try{t=(await s.backend.rename(s.relParts.join(`/`),e.relParts.join(`/`)))?.noop===!0}catch(e){O(e,n)}t||(this.watcher?.notify([{type:`delete`,path:n,entryType:o},{type:`create`,path:r,entryType:o}]),this.mountIndex.notifyRename(n,r));return}}let c;if(a)try{if(c=await this.lstat(r),i(a,c))return}catch{}let u=Ze(c?.type,o);u&&this.refuseMountedDisplacement(r);try{await this.withWriteLock(async()=>{await this.dropSidecarConsistency(),this.markSidecarDirty(n,`prefix`),this.markSidecarDirty(r,`prefix`),await this.storeRenameReplacing(n,r,u),await this.writeOpfsMetadataSidecarUnlocked()})}catch(e){throw k(e,n)}this.watcher?.notify([{type:`delete`,path:n,entryType:o},{type:`create`,path:r,entryType:o}]),this.mountIndex.notifyRename(n,r)}refuseMountedDisplacement(e){let t=this.findMount(e);if(!t)return;let n=t.relParts.length===0?`EBUSY`:`EXDEV`;throw new o(n,`rename onto a mounted entry`,e)}async storeRenameReplacing(e,t,n){if(n===`dir`&&(await this.lfs.readdir(t)).length>0)throw new o(`ENOTEMPTY`,`directory not empty`,t);let r=n?await this.freeParkedLinkPath(t):void 0;r&&this.markSidecarDirty(r),r&&await this.lfs.rename(t,r);try{await this.lfs.rename(e,t)}catch(e){try{r&&await this.restoreParkedLink(r,t,e)}finally{await this.writeOpfsMetadataSidecarUnlocked().catch(()=>void 0)}throw e}r&&await(n===`dir`?this.lfs.rmdir(r):this.lfs.unlink(r)).catch(()=>void 0)}async freeParkedLinkPath(e){for(let t=0;t<$e;t++){let t=Qe(e);try{await this.lfs.lstat(t)}catch(e){if(e?.code===`ENOENT`)return t;throw e}}throw new o(`EEXIST`,`no free name to park the symlink at during rename`,e)}async restoreParkedLink(e,t,n){try{await this.lfs.rename(e,t)}catch(r){let i=e=>e instanceof Error?e.message:String(e);throw new o(`EIO`,`rename failed (${i(n)}) and the entry it replaced could not be put back (${i(r)}); it is at ${e}`,t)}}async readTextFile(e){return await this.readFile(e,{encoding:`utf-8`})}async*walk(e,t,n=0){yield*ee({mountPoints:this.mountPoints,mountIndex:this.mountIndex,realpath:e=>this.realpath(e),readDir:e=>this.readDir(e),stat:e=>this.stat(e)},e,t,n)}async copyFile(e,t){let n=await this.stat(e);if(n.type===`directory`)throw new o(`EISDIR`,`is a directory`,e);try{let e=await this.stat(t);if(i(n,e))return}catch{}let r=await this.readFile(e,{encoding:`binary`});await this.writeFile(t,r)}dirname(e){return s(l(e)).dir}basename(e){return s(l(e)).base}resolveSymlinkTargetPath(e,t){return e.startsWith(`/`)?l(e):l(d(s(t).dir,e))}assertSymlinkCreateAllowed(e){if(this.findMount(e))throw new o(`EINVAL`,`symlinks not supported on mounted filesystems`,e)}onMount(e,t){return e!==t&&this.findMount(e)?e:void 0}async viaMountOnEnoent(e,t){try{return await t(e)}catch(n){if(this.mountPoints.size===0||n.code!==`ENOENT`)throw n;let r=await this.parentOnMount(e);if(!r)throw n;return t(r)}}async parentOnMount(e){if(e===`/`||this.findMount(e))return;let{dir:t,base:n}=s(e),r;try{r=await this.resolveSymlinks(t)}catch{return}return r!==t&&this.findMount(r)?d(r,n):void 0}async symlink(e,t){await this.symlinkBatch([{target:e,path:t}])}async symlinkBatch(e){if(e.length===0)return;let t=e.map(e=>{let t=l(e.path);return this.assertSymlinkCreateAllowed(t),{target:e.target,normalizedLinkPath:t}}),n=t.map(e=>e.normalizedLinkPath);await this.withKindMismatchRetryPaths(n,()=>this.withWriteLock(async()=>{await this.dropSidecarConsistency();let e=[];try{for(let n of t)await this.createSymlinkUnlocked(n.target,n.normalizedLinkPath),this.markSidecarDirty(n.normalizedLinkPath),e.push({type:`create`,path:n.normalizedLinkPath,entryType:`symlink`});await this.writeOpfsMetadataSidecarUnlocked(),this.watcher?.notify(e)}catch(t){throw e.length>0&&(await this.writeOpfsMetadataSidecarUnlocked(),this.watcher?.notify(e)),t}}))}async createSymlinkUnlocked(e,t){let{dir:n}=s(t);n!==`/`&&await this.mkdirRecursiveUnlocked(n);try{await this.lfs.symlink(e,t)}catch(r){if(n!==`/`&&r instanceof Error&&r.message.includes(`ENOENT`)){await this.mkdirRecursiveUnlocked(n);try{await this.lfs.symlink(e,t)}catch(e){throw k(e,t)}}else throw k(r,t)}}async readlink(e){return this.viaMountOnEnoent(l(e),async e=>{try{return await this.lfs.readlink(e)}catch(t){throw k(t,e)}})}async lstat(e){return this.viaMountOnEnoent(l(e),e=>this.lstatInner(e))}async lstatInner(e){let t=l(e);if(this.findMount(t)||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,ino:e.ino,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}return{type:e.isDirectory()?`directory`:`file`,size:e.size,mtime:e.mtimeMs,ctime:e.ctimeMs,ino:e.ino,dev:e.dev,identity:this.localIdentity(e.ino),uid:e.uid,gid:e.gid,mode:e.mode}}catch(e){throw k(e,t)}}async realpath(e){return X(this.lfs,e=>this.findMount(e)!==null,e)}resolveSymlinks(e){return Ke(this.lfs,e=>this.findMount(e)!==null,e)}},et=e({FsError:()=>o,FsWatcher:()=>m,MountIndex:()=>x,RestrictedFS:()=>D,VirtualFS:()=>$,joinPath:()=>d,normalizePath:()=>l,pathSegments:()=>c,resolveVfsBackendFromEnv:()=>Z,sameFileIdentity:()=>i,splitPath:()=>s,statsFromDirEntry:()=>a});export{o as FsError,m as FsWatcher,x as MountIndex,D as RestrictedFS,$ as VirtualFS,P as a,Ve as i,d as joinPath,Y as n,l as normalizePath,c as pathSegments,He as r,Z as resolveVfsBackendFromEnv,i as sameFileIdentity,s as splitPath,a as statsFromDirEntry,et as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"./logger-Cx6Y120U.js";import{E as t,a as n,s as r}from"./record-DTUQtot0.js";import{a as i,i as a,n as o,r as s,t as c}from"./gelatiere-constants-BYJlhm8R.js";import{u as l}from"./kernel-worker-
|
|
1
|
+
import{t as e}from"./logger-Cx6Y120U.js";import{E as t,a as n,s as r}from"./record-DTUQtot0.js";import{a as i,i as a,n as o,r as s,t as c}from"./gelatiere-constants-BYJlhm8R.js";import{u as l}from"./kernel-worker-DKhuL-SB.js";import{GELATIERE_BASE_ALLOWED_COMMANDS as u}from"./gelatiere-store-GVNdni5w.js";const d=e(`gelatiere-unit`),f=[`You are the gelatiere: the resident advisor of this SLICC installation, a persistent scoop no cone owns. The user cannot message you directly and you never message them.`,"You act only when a lick arrives — a `[Cron Event: gelatiere-nightly]`, a `[Sprinkle Event: gelatiere]` (a session ended, or someone ran `gelatiere run`), or a direct message asking for a pass.","On every such lick: `cat /shared/GELATIERE.md` and follow it exactly. It ends with `gelatiere suggest <file>` and `gelatiere deliver`; those two commands are how your work reaches the cones. Do not install skills, do not edit memory files, do not message cones any other way.",`Reply in one short line per pass (what you looked at, how many suggestions landed). Your own history is compacted while you idle; keep durable notes in /shared/.gelatiere/notes.md, not in your replies.`].join(` `);var p=class extends Error{holder;constructor(e){super(`folder "${c}" is held by ${e.parentJid===null?`cone`:`scoop`} ${e.jid} — drop it, then run \`gelatiere init\``),this.holder=e,this.name=`GelatiereFolderTakenError`}};function m(e){return e.find(i)}function h(e){return e.listCronTasks().find(e=>e.name===`gelatiere-nightly`&&e.scoop===`gelatiere`)}function g(e){return{folder:e.folder,name:e.name,jid:e.jid}}const _=[`/sessions/`,`/shared/`,`/workspace/`,`/home/`,`/cones/`],v=[`/shared/.gelatiere/`];async function y(e,t,n){if(!n||b(t.config?.allowedCommands??[],n))return`unchanged`;if(e.getScoopTabState(t.jid)?.status===`processing`)return d.info(`gelatiere allow-list edit deferred: the unit is mid-pass`,{jid:t.jid}),`deferred`;let r={...t,config:{...t.config,allowedCommands:[...n]}};try{await e.persistScoop(r)}catch(n){throw await e.persistScoop(t).catch(()=>{}),n}return await e.reinitLiveUnit(r.jid),d.info(`gelatiere allow-list updated from GELATIERE.md`,{jid:r.jid,commands:n.length}),`updated`}function b(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}async function x(e,t){let i=e.getScoops(),a=m(i);if(a){await e.syncGelatiereModel();let n=await y(e,a,t);return{folder:a.folder,jid:a.jid,created:!1,allowList:n}}let o=i.find(e=>e.folder===c);if(o)throw new p(o);let h=n(i),g=h?r(h):void 0,b={...l({parentId:s,name:c,folder:c,notifyOnComplete:!1,config:{systemPromptAppend:f,visiblePaths:[..._],writablePaths:[...v],allowedCommands:[...t??u]}}),assistantLabel:c,...g?{model:g}:{}};return await e.registerScoop(b),d.info(`gelatiere unit registered`,{jid:b.jid}),{folder:b.folder,jid:b.jid,created:!0}}function S(e,n){return{ensureUnit:t=>x(e,t),unregisterOwned:async()=>{for(let e of n.listCronTasks())e.name===`gelatiere-nightly`&&await n.deleteCronTask(e.id);let t=e.getScoops().filter(e=>e.parentJid===s);for(let n of t)await e.unregisterScoop(n.jid);return t.map(e=>e.jid)},unit:()=>{let t=m(e.getScoops());return t?g(t):void 0},unitAllowedCommands:()=>m(e.getScoops())?.config?.allowedCommands,roots:()=>t(e.getScoops()).map(g),nightly:()=>{let e=h(n);return e?{id:e.id,cron:e.cron}:void 0},ensureNightly:async e=>{let t=h(n);if(t?.cron===e)return{id:t.id,cron:t.cron,created:!1};t&&await n.deleteCronTask(t.id);let r=await n.createCronTask(o,e,c);return{id:r.id,cron:r.cron,created:!0}},dropNightly:async()=>{let e=h(n);return e?n.deleteCronTask(e.id):!1},lick:(e,t)=>{n.emitEvent({type:`sprinkle`,sprinkleName:a,targetScoop:e,timestamp:(/* @__PURE__ */ new Date()).toISOString(),body:t})}}}function C(e,t=globalThis){t.__slicc_gelatiere=e}async function w(e,t,n){try{let r=await e.ensureUnit(n),i=await e.ensureNightly(t);d.info(`gelatiere ready`,{jid:r.jid,created:r.created,allowList:r.allowList,nightly:i.cron,nightlyCreated:i.created})}catch(e){d.warn(`gelatiere boot failed`,{error:e instanceof Error?e.message:String(e)})}}async function T(e){try{await e.dropNightly()&&d.info(`gelatiere nightly removed (memory-v2 is off)`)}catch(e){d.warn(`gelatiere halt failed`,{error:e instanceof Error?e.message:String(e)})}}export{w as bootGelatiere,S as createGelatiereSeam,T as haltGelatiere,C as publishGelatiereSeam};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/fs-
|
|
2
|
-
import{t as e}from"./preload-helper-DjzSQ1t3.js";import{K as t,c as n,u as r}from"./account-store-D4Humqb-.js";import"./proxied-fetch-Co-YYDT9.js";import{a as i}from"./api-endpoint-DuEQRZ4g.js";import{D as a,g as o}from"./main-pG2z7nDr.js";import{r as s,t as c}from"./silent-renew-backoff-BMr_pGCU.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-C9_em2OO.js";import{t as d}from"./global-db-CbuLl-zx.js";import{n as f,r as p,t as m}from"./bridge-token-required-DMk2va9k.js";var h={clientId:``,scopes:`repo,read:user,user:email`};function g(){try{let e=localStorage.getItem(a);if(e)return e.replace(/\/$/,``)}catch{}return o}function _(e){return{access_token:e.access_token,token_type:e.token_type,scope:e.scope,refresh_token:e.refresh_token,expires_in:e.expires_in}}async function v(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return _(t)}async function y(e){let t=`${g()}/oauth/token`;return v(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function b(e){if(f())throw new m;let t=`${g()}/oauth/token`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})});if(n.status===403&&typeof n.clone==`function`){let e=await n.clone().text();if(p(n.status,e))throw new m}return v(n)}async function x(e){let t=`${g()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}var S=Object.assign({"/packages/webapp/providers/github-config.json":h})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`},C=null,w=null;function T(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function E(){if(C)return C;if(D){try{let e=await fetch(`${g()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return C=t.oauth.github,C}}catch{}return S.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return C=t.oauth.github,t.trayWorkerBaseUrl&&(w=t.trayWorkerBaseUrl),C;if(t.trayWorkerBaseUrl){w=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return C=t.oauth.github,C}}}}catch{}return S.clientId}var D=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function O(){return r().find(e=>e.providerId===`github`)}function k(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function A(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 j(e,t){return`${e}+${t}@users.noreply.github.com`}async function M(t){try{let{VirtualFS:n}=await e(async()=>{let{VirtualFS:e}=await import(`./fs-CQpIxK2e.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]));await(await n.create({dbName:d})).writeFile(`/workspace/.git/github-token`,t),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function N(){try{let{VirtualFS:t}=await e(async()=>{let{VirtualFS:e}=await import(`./fs-CQpIxK2e.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]));await(await t.create({dbName:d})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function P(e){let t=await n(`github`);if(t.maskedValue){await M(t.maskedValue);return}e?.clearOnFailure&&await N()}async function F(t){if(t.login&&t.id!==void 0)try{let{VirtualFS:n}=await e(async()=>{let{VirtualFS:e}=await import(`./fs-CQpIxK2e.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),{readGlobalGitConfigValue:r,writeGlobalGitConfigValue:i}=await e(async()=>{let{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}=await import(`./git-config-D2u6LGfT.js`);return{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}},[]),a=await n.create({dbName:d}),o=t.name||t.login,s=j(t.id,t.login);!await r(a,`user.name`)&&o&&await i(a,`user.name`,o),await r(a,`user.email`)||await i(a,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}var I=c();async function L(){try{let e=O();if(!e?.refreshToken)return null;let n=await b({provider:`github`,refreshToken:e.refreshToken});return await t({providerId:`github`,accessToken:n.access_token,refreshToken:n.refresh_token,tokenExpiresAt:n.expires_in?Date.now()+n.expires_in*1e3:void 0,userName:e.userName,userAvatar:e.userAvatar,scopes:n.scope??e.scopes}),await P({clearOnFailure:!0}),n.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}var R=1e4;async function z(){let e=O()?.accessToken;if(!e)return{status:`unknown`,detail:`no stored token`};try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`},signal:AbortSignal.timeout(R)});if(t.ok){let e=await t.json().catch(()=>({}));return{status:`accepted`,userName:e.name||e.login}}return B(t)}catch(e){return{status:`unknown`,detail:e instanceof Error?e.message:String(e)}}}function B(e){let t=`HTTP ${e.status}${e.statusText?` ${e.statusText}`:``}`;return e.status===401?{status:`rejected`,detail:t}:e.status===403&&V(e)?{status:`unknown`,detail:`${t} (rate limited)`}:{status:`unknown`,detail:t}}function V(e){return e.headers.get(`x-ratelimit-remaining`)===`0`||e.headers.has(`retry-after`)}async function H(){await P()}async function U(){let e=O();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return await H(),e.accessToken;let t=await I.run(()=>L());if(t)return t;let n=O();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return await H(),n.accessToken;throw Error(`GitHub session expired — please log in again`)}var W={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(e,n,r)=>{let a=await E();if(!a)throw Error(`GitHub OAuth not configured — no client ID available`);let o=r?.scopes??S.scopes,s=D?null:await l(),c=!D&&await u(),d=crypto.randomUUID(),f=D?chrome.runtime.id:``,{redirectUri:p,state:m}=T({isExtension:D,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:g(),runtimeWorkerBaseUrl:w,pageOrigin:s?.origin??null,pageHref:s?.href??null,bridgeApiBaseUrl:i(),delegated:c,extensionId:f,nonce:d}),h=btoa(JSON.stringify(m)),_=d,v=new URLSearchParams({client_id:a,scope:o,redirect_uri:p});h&&v.set(`state`,h);let b=await e(`https://github.com/login/oauth/authorize?${v}`);if(!b)return;if(_)try{if(new URL(b).searchParams.get(`nonce`)!==_){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 x=k(b);if(!x){console.error(`[github] Could not extract authorization code from redirect URL`);return}let C=await y({provider:`github`,code:x,redirectUri:p}),O=await A(C.access_token);await t({providerId:`github`,accessToken:C.access_token,refreshToken:C.refresh_token,tokenExpiresAt:C.expires_in?Date.now()+C.expires_in*1e3:void 0,userName:O.name,userAvatar:O.avatar,scopes:C.scope}),await P({clearOnFailure:!0}),await F(O),n()},onSilentRenew:L,onValidateToken:z,getValidAccessToken:U,onOAuthLogout:async()=>{let e=O();e?.accessToken&&await x({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await N(),await t({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{j as buildNoreplyEmail,W as config,k as extractCodeFromUrl,U as getValidAccessToken,T as resolveGithubOAuthRedirect,F as syncGitIdentityFromGitHub};
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/fs-DSnZb1DK.js","assets/rolldown-runtime-Dd_uD5pT.js","assets/preload-helper-BLdHbfdN.js","assets/logger-DDBAeTLF.js","assets/same-file-identity-OexpsaSD.js","assets/types-D8gIX-W-.js","assets/path-utils-DNJG-zQf.js","assets/bounded-walk-BjxKWNqp.js","assets/virtual-device-paths-D45tpPP6.js","assets/mount-table-store-dY2IfQ5S.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-BLdHbfdN.js";import{K as t,c as n,u as r}from"./account-store-C8ku_32k.js";import"./proxied-fetch-Dcpb4ieV.js";import{a as i}from"./api-endpoint-DuEQRZ4g.js";import{D as a,g as o}from"./main-CWx8ZbOh.js";import{r as s,t as c}from"./silent-renew-backoff-B9OHOzRe.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-BTbFz00g.js";import{t as d}from"./global-db-CbuLl-zx.js";import{n as f,r as p,t as m}from"./bridge-token-required-DMk2va9k.js";var h={clientId:``,scopes:`repo,read:user,user:email`};function g(){try{let e=localStorage.getItem(a);if(e)return e.replace(/\/$/,``)}catch{}return o}function _(e){return{access_token:e.access_token,token_type:e.token_type,scope:e.scope,refresh_token:e.refresh_token,expires_in:e.expires_in}}async function v(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return _(t)}async function y(e){let t=`${g()}/oauth/token`;return v(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function b(e){if(f())throw new m;let t=`${g()}/oauth/token`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})});if(n.status===403&&typeof n.clone==`function`){let e=await n.clone().text();if(p(n.status,e))throw new m}return v(n)}async function x(e){let t=`${g()}/oauth/revoke`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,access_token:e.accessToken})});if(!(n.status===204||n.ok)){if(n.status===400)try{if((await n.json()).error===`unsupported`)return}catch{}throw Error(`Token revocation failed (HTTP ${n.status})`)}}var S=Object.assign({"/packages/webapp/providers/github-config.json":h})[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`},C=null,w=null;function T(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function E(){if(C)return C;if(D){try{let e=await fetch(`${g()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return C=t.oauth.github,C}}catch{}return S.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return C=t.oauth.github,t.trayWorkerBaseUrl&&(w=t.trayWorkerBaseUrl),C;if(t.trayWorkerBaseUrl){w=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return C=t.oauth.github,C}}}}catch{}return S.clientId}var D=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function O(){return r().find(e=>e.providerId===`github`)}function k(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function A(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 j(e,t){return`${e}+${t}@users.noreply.github.com`}async function M(t){try{let{VirtualFS:n}=await e(async()=>{let{VirtualFS:e}=await import(`./fs-DSnZb1DK.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]));await(await n.create({dbName:d})).writeFile(`/workspace/.git/github-token`,t),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function N(){try{let{VirtualFS:t}=await e(async()=>{let{VirtualFS:e}=await import(`./fs-DSnZb1DK.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9]));await(await t.create({dbName:d})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function P(e){let t=await n(`github`);if(t.maskedValue){await M(t.maskedValue);return}e?.clearOnFailure&&await N()}async function F(t){if(t.login&&t.id!==void 0)try{let{VirtualFS:n}=await e(async()=>{let{VirtualFS:e}=await import(`./fs-DSnZb1DK.js`).then(e=>e.t);return{VirtualFS:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9])),{readGlobalGitConfigValue:r,writeGlobalGitConfigValue:i}=await e(async()=>{let{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}=await import(`./git-config-D2u6LGfT.js`);return{readGlobalGitConfigValue:e,writeGlobalGitConfigValue:t}},[]),a=await n.create({dbName:d}),o=t.name||t.login,s=j(t.id,t.login);!await r(a,`user.name`)&&o&&await i(a,`user.name`,o),await r(a,`user.email`)||await i(a,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}var I=c();async function L(){try{let e=O();if(!e?.refreshToken)return null;let n=await b({provider:`github`,refreshToken:e.refreshToken});return await t({providerId:`github`,accessToken:n.access_token,refreshToken:n.refresh_token,tokenExpiresAt:n.expires_in?Date.now()+n.expires_in*1e3:void 0,userName:e.userName,userAvatar:e.userAvatar,scopes:n.scope??e.scopes}),await P({clearOnFailure:!0}),n.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}var R=1e4;async function z(){let e=O()?.accessToken;if(!e)return{status:`unknown`,detail:`no stored token`};try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`},signal:AbortSignal.timeout(R)});if(t.ok){let e=await t.json().catch(()=>({}));return{status:`accepted`,userName:e.name||e.login}}return B(t)}catch(e){return{status:`unknown`,detail:e instanceof Error?e.message:String(e)}}}function B(e){let t=`HTTP ${e.status}${e.statusText?` ${e.statusText}`:``}`;return e.status===401?{status:`rejected`,detail:t}:e.status===403&&V(e)?{status:`unknown`,detail:`${t} (rate limited)`}:{status:`unknown`,detail:t}}function V(e){return e.headers.get(`x-ratelimit-remaining`)===`0`||e.headers.has(`retry-after`)}async function H(){await P()}async function U(){let e=O();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return await H(),e.accessToken;let t=await I.run(()=>L());if(t)return t;let n=O();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return await H(),n.accessToken;throw Error(`GitHub session expired — please log in again`)}var W={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(e,n,r)=>{let a=await E();if(!a)throw Error(`GitHub OAuth not configured — no client ID available`);let o=r?.scopes??S.scopes,s=D?null:await l(),c=!D&&await u(),d=crypto.randomUUID(),f=D?chrome.runtime.id:``,{redirectUri:p,state:m}=T({isExtension:D,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:g(),runtimeWorkerBaseUrl:w,pageOrigin:s?.origin??null,pageHref:s?.href??null,bridgeApiBaseUrl:i(),delegated:c,extensionId:f,nonce:d}),h=btoa(JSON.stringify(m)),_=d,v=new URLSearchParams({client_id:a,scope:o,redirect_uri:p});h&&v.set(`state`,h);let b=await e(`https://github.com/login/oauth/authorize?${v}`);if(!b)return;if(_)try{if(new URL(b).searchParams.get(`nonce`)!==_){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 x=k(b);if(!x){console.error(`[github] Could not extract authorization code from redirect URL`);return}let C=await y({provider:`github`,code:x,redirectUri:p}),O=await A(C.access_token);await t({providerId:`github`,accessToken:C.access_token,refreshToken:C.refresh_token,tokenExpiresAt:C.expires_in?Date.now()+C.expires_in*1e3:void 0,userName:O.name,userAvatar:O.avatar,scopes:C.scope}),await P({clearOnFailure:!0}),await F(O),n()},onSilentRenew:L,onValidateToken:z,getValidAccessToken:U,onOAuthLogout:async()=>{let e=O();e?.accessToken&&await x({provider:`github`,accessToken:e.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await N(),await t({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{j as buildNoreplyEmail,W as config,k as extractCodeFromUrl,U as getValidAccessToken,T as resolveGithubOAuthRedirect,F as syncGitIdentityFromGitHub};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{_ as e,n as t,r as n}from"./account-store-
|
|
1
|
+
import{_ as e,n as t,r as n}from"./account-store-CLrcVXc0.js";import"./proxied-fetch-1DfC_94U.js";import{o as r}from"./api-endpoint-D8lUKmPu.js";import{n as i}from"./tray-storage-keys-DbThbnIh.js";import{t as a}from"./tray-runtime-config-BvQtvIxB.js";import{t as o}from"./global-db-Bfy_NRtT.js";import{r as s,t as c}from"./silent-renew-backoff-Dmz3DJHb.js";import{getOAuthPageOrigin as l,resolveOAuthDelegation as u}from"./oauth-service-a7hhn6wa.js";import"./provider-settings-DiWaVtMa.js";import{n as d,r as f,t as p}from"./bridge-token-required-BYgoMwr7.js";var m={clientId:``,scopes:`repo,read:user,user:email`};function h(){try{let e=localStorage.getItem(i);if(e)return e.replace(/\/$/,``)}catch{}return a}function g(e){return{access_token:e.access_token,token_type:e.token_type,scope:e.scope,refresh_token:e.refresh_token,expires_in:e.expires_in}}async function _(e){let t;try{t=await e.json()}catch{throw Error(`Token exchange failed (HTTP ${e.status}): non-JSON response`)}if(!e.ok&&e.status!==200){let n=t.error_description??t.error??`Token exchange failed (HTTP ${e.status})`;throw Error(n)}if(t.error){let e=t.error_description??t.error;throw Error(e)}return g(t)}async function v(e){let t=`${h()}/oauth/token`;return _(await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,code:e.code,redirect_uri:e.redirectUri})}))}async function y(e){if(d())throw new p;let t=`${h()}/oauth/token`,n=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({provider:e.provider,refresh_token:e.refreshToken})});if(n.status===403&&typeof n.clone==`function`){let e=await n.clone().text();if(f(n.status,e))throw new p}return _(n)}async function b(e){let t=`${h()}/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 x=(/* @__PURE__ */ Object.assign({"/packages/webapp/providers/github-config.json":m}))[`/packages/webapp/providers/github-config.json`]??{clientId:``,scopes:`repo,read:user,user:email`};let S=null,C=null;function w(e){let{isExtension:t,isConnectMode:n,workerBaseUrl:r,pageOrigin:i,pageHref:a,bridgeApiBaseUrl:o,extensionId:c,nonce:l}=e;if(t)return{redirectUri:`${r}/auth/callback`,state:{source:`extension`,extensionId:c,path:`/github`,nonce:l}};if(e.delegated)return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`opener`,path:`/auth/callback`,nonce:l}};if(n){let e=i??``;if(/^https?:\/\/(localhost|127\.0\.0\.1):\d+$/.test(e)){let t=parseInt(new URL(a??e).port||`8790`,10);return{redirectUri:`${r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${r}/auth/callback`,state:{source:`remote`,origin:e,path:`/auth/callback`,nonce:l}}}if(o&&a&&s(a)){let t=null;try{let e=new URL(o);(e.hostname===`localhost`||e.hostname===`127.0.0.1`)&&(t=parseInt(e.port||`5710`,10))}catch{t=null}if(t!==null&&!Number.isNaN(t))return{redirectUri:`${e.runtimeWorkerBaseUrl??r}/auth/callback`,state:{source:`local`,port:t,path:`/auth/callback`,nonce:l}}}return{redirectUri:`${e.runtimeWorkerBaseUrl??i??``}/auth/callback`,state:{port:parseInt(new URL(a??i??`http://localhost:5710`).port||`5710`,10),path:`/auth/callback`,nonce:l}}}async function T(){if(S)return S;if(E){try{let e=await fetch(`${h()}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return S=t.oauth.github,S}}catch{}return x.clientId}try{let e=await fetch(`/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return S=t.oauth.github,t.trayWorkerBaseUrl&&(C=t.trayWorkerBaseUrl),S;if(t.trayWorkerBaseUrl){C=t.trayWorkerBaseUrl;let e=await fetch(`${t.trayWorkerBaseUrl}/api/runtime-config`);if(e.ok){let t=await e.json();if(t.oauth?.github)return S=t.oauth.github,S}}}}catch{}return x.clientId}const E=typeof globalThis<`u`&&typeof globalThis.chrome?.runtime?.id==`string`;function D(){return n().find(e=>e.providerId===`github`)}function O(e){try{return new URL(e).searchParams.get(`code`)}catch{return null}}async function k(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 A(e,t){return`${e}+${t}@users.noreply.github.com`}async function j(e){try{let{VirtualFS:t}=await import(`./fs-TeRSVyvv.js`).then(e=>e.t);await(await t.create({dbName:o})).writeFile(`/workspace/.git/github-token`,e),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch(e){console.warn(`[github] Failed to write git token:`,e instanceof Error?e.message:String(e))}}async function M(){try{let{VirtualFS:e}=await import(`./fs-TeRSVyvv.js`).then(e=>e.t);await(await e.create({dbName:o})).rm(`/workspace/.git/github-token`),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`github-token-changed`))}catch{}}async function N(e){let n=await t(`github`);if(n.maskedValue){await j(n.maskedValue);return}e?.clearOnFailure&&await M()}async function P(e){if(e.login&&e.id!==void 0)try{let{VirtualFS:t}=await import(`./fs-TeRSVyvv.js`).then(e=>e.t),{readGlobalGitConfigValue:n,writeGlobalGitConfigValue:r}=await import(`./git-config-DzvRg91c.js`).then(e=>e.n),i=await t.create({dbName:o}),a=e.name||e.login,s=A(e.id,e.login);!await n(i,`user.name`)&&a&&await r(i,`user.name`,a),await n(i,`user.email`)||await r(i,`user.email`,s)}catch(e){console.warn(`[github] Failed to seed git identity:`,e instanceof Error?e.message:String(e))}}const F=c();async function I(){try{let t=D();if(!t?.refreshToken)return null;let n=await y({provider:`github`,refreshToken:t.refreshToken});return await e({providerId:`github`,accessToken:n.access_token,refreshToken:n.refresh_token,tokenExpiresAt:n.expires_in?Date.now()+n.expires_in*1e3:void 0,userName:t.userName,userAvatar:t.userAvatar,scopes:n.scope??t.scopes}),await N({clearOnFailure:!0}),n.access_token}catch(e){return console.warn(`[github] Silent renewal failed:`,e instanceof Error?e.message:String(e)),null}}async function L(){let e=D()?.accessToken;if(!e)return{status:`unknown`,detail:`no stored token`};try{let t=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${e}`,Accept:`application/vnd.github+json`},signal:AbortSignal.timeout(1e4)});if(t.ok){let e=await t.json().catch(()=>({}));return{status:`accepted`,userName:e.name||e.login}}return R(t)}catch(e){return{status:`unknown`,detail:e instanceof Error?e.message:String(e)}}}function R(e){let t=`HTTP ${e.status}${e.statusText?` ${e.statusText}`:``}`;return e.status===401?{status:`rejected`,detail:t}:e.status===403&&z(e)?{status:`unknown`,detail:`${t} (rate limited)`}:{status:`unknown`,detail:t}}function z(e){return e.headers.get(`x-ratelimit-remaining`)===`0`||e.headers.has(`retry-after`)}async function B(){await N()}async function V(){let e=D();if(!e?.accessToken)throw Error(`Not logged in to GitHub — please log in first`);if((e.tokenExpiresAt??1/0)-Date.now()>6e4)return await B(),e.accessToken;let t=await F.run(()=>I());if(t)return t;let n=D();if((n?.tokenExpiresAt??1/0)-Date.now()>0&&n?.accessToken)return await B(),n.accessToken;throw Error(`GitHub session expired — please log in again`)}const H={id:`github`,name:`GitHub`,description:"Sign in with GitHub for git authentication (push/pull/clone) and the `oauth-token github` shell command. Does not expose LLM models — use the GitHub Copilot provider for those.",requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:[`github.com`,`*.github.com`,`api.github.com`,`raw.githubusercontent.com`],getModelIds:()=>[],onOAuthLogin:async(t,n,i)=>{let a=await T();if(!a)throw Error(`GitHub OAuth not configured — no client ID available`);let o=i?.scopes??x.scopes,s=E?null:await l(),c=!E&&await u(),d=crypto.randomUUID(),f=E?chrome.runtime.id:``,{redirectUri:p,state:m}=w({isExtension:E,isConnectMode:!!globalThis.__slicc_connect_mode,workerBaseUrl:h(),runtimeWorkerBaseUrl:C,pageOrigin:s?.origin??null,pageHref:s?.href??null,bridgeApiBaseUrl:r(),delegated:c,extensionId:f,nonce:d}),g=btoa(JSON.stringify(m)),_=d,y=new URLSearchParams({client_id:a,scope:o,redirect_uri:p});g&&y.set(`state`,g);let b=await t(`https://github.com/login/oauth/authorize?${y}`);if(!b)return;if(_)try{if(new URL(b).searchParams.get(`nonce`)!==_){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 S=O(b);if(!S){console.error(`[github] Could not extract authorization code from redirect URL`);return}let D=await v({provider:`github`,code:S,redirectUri:p}),A=await k(D.access_token);await e({providerId:`github`,accessToken:D.access_token,refreshToken:D.refresh_token,tokenExpiresAt:D.expires_in?Date.now()+D.expires_in*1e3:void 0,userName:A.name,userAvatar:A.avatar,scopes:D.scope}),await N({clearOnFailure:!0}),await P(A),n()},onSilentRenew:I,onValidateToken:L,getValidAccessToken:V,onOAuthLogout:async()=>{let t=D();t?.accessToken&&await b({provider:`github`,accessToken:t.accessToken}).catch(e=>console.warn(`[github] Token revocation failed:`,e instanceof Error?e.message:String(e))),await M(),await e({providerId:`github`,accessToken:``})},getOAuthLogoutUrl:e=>`https://github.com/logout`};export{A as buildNoreplyEmail,H as config,O as extractCodeFromUrl,V as getValidAccessToken,w as resolveGithubOAuthRedirect,P as syncGitIdentityFromGitHub};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/clipboard-eqmn97SP.js","assets/rolldown-runtime-Dd_uD5pT.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{a as e}from"./diagnostics-B-5VkVir.js";import{t}from"./preload-helper-DjzSQ1t3.js";import{a as n}from"./compat-d34y6SaJ.js";import{a as r,c as i,i as a,r as o,s,t as c}from"./legacy-api-aliases-DZ7QKXPR.js";import{a as l,i as u}from"./core-DfJhnyZb.js";import{K as d,u as f}from"./account-store-D4Humqb-.js";import"./main-pG2z7nDr.js";import{t as p}from"./anthropic-proxy-compat-CaymbdBf.js";function m(e,t){return{...e,api:`anthropic-messages`,baseUrl:t.baseUrl,headers:t.headers,provider:`github-copilot`,compat:p(e.compat)}}var h=`https://api.github.com/copilot_internal/user`,g=8e3;function _(e){if(!e||typeof e!=`object`)return null;let t=e.quota_snapshots?.premium_interactions;return!t||t.unlimited||typeof t.percent_remaining!=`number`?null:{percent:Math.max(0,100-t.percent_remaining),status:t.percent_remaining<=0&&t.overage_permitted!==!0?`rate-limited`:`ok`,window:`monthly`,resetsAt:e.quota_reset_date_utc}}async function v(e,t,n={}){let r=typeof AbortController==`function`?new AbortController:null,i=r?setTimeout(()=>r.abort(),n.timeoutMs??g):null;try{let i=await t(h,{headers:{...n.headers,Authorization:`Bearer ${e}`},...r?{signal:r.signal}:{}});if(i.status===404||i.status===501)return null;if(!i.ok)throw Error(`GitHub Copilot /copilot_internal/user returned ${i.status}`);return _(await i.json())}finally{i&&clearTimeout(i)}}var y=`github-copilot`,b=atob(`SXYxLmI1MDdhMDhjODdlY2ZlOTg=`),x=`https://github.com/login/device/code`,S=`https://github.com/login/oauth/access_token`,C=`https://api.github.com/copilot_internal/v2/token`,w={Accept:`application/json`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`},T={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`},E=`https://github.com/login/device/success*`;function D(){return f().find(e=>e.providerId===y)}async function O(){let e=await fetch(x,{method:`POST`,headers:T,body:new URLSearchParams({client_id:b,scope:`read:user`})});if(!e.ok)throw Error(`GitHub device-code request failed: ${e.status} ${e.statusText} — ${await e.text().catch(()=>``)}`);let t=await e.json();if(typeof t.device_code!=`string`||typeof t.user_code!=`string`||typeof t.verification_uri!=`string`||typeof t.expires_in!=`number`||typeof t.interval!=`number`)throw Error(`GitHub device-code response had an unexpected shape`);return t}async function ee(e,t){let n=Date.now()+e.expires_in*1e3,r=Math.max(1e3,Math.floor(e.interval*1e3)),i=1.2;for(;Date.now()<n;){if(t.aborted)throw Error(`Copilot login cancelled`);await te(Math.ceil(r*i),t);let n=await fetch(S,{method:`POST`,headers:T,body:new URLSearchParams({client_id:b,device_code:e.device_code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`})});if(!n.ok)throw Error(`GitHub token poll failed: ${n.status} ${n.statusText} — ${await n.text().catch(()=>``)}`);let a=await n.json();if(typeof a.access_token==`string`&&a.access_token.length>0)return a.access_token;if(a.error!==`authorization_pending`){if(a.error===`slow_down`){r=typeof a.interval==`number`?a.interval*1e3:r+5e3,i=1.4;continue}if(a.error){let e=a.error_description?`: ${a.error_description}`:``;throw Error(`Device flow failed (${a.error})${e}`)}}}throw Error(`Copilot device flow timed out (device code expired)`)}function te(e,t){return new Promise((n,r)=>{if(t.aborted){r(Error(`Copilot login cancelled`));return}let i=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Copilot login cancelled`))},{once:!0})})}function ne(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,`api.`)}`:null}async function k(e){let t=await fetch(C,{headers:{...w,Authorization:`Bearer ${e}`}});if(!t.ok){let e=await t.text().catch(()=>``);throw Error(`Copilot token exchange failed: ${t.status} ${t.statusText} — ${e.slice(0,300)}`)}let n=await t.json();if(typeof n.token!=`string`||typeof n.expires_at!=`number`)throw Error(`Copilot token exchange returned an unexpected payload`);if(n.chat_enabled===!1)throw Error(`GitHub Copilot Chat is disabled for this account (no chat features granted)`);return{copilotToken:n.token,expiresAtMs:n.expires_at*1e3-3e5,apiBaseUrl:ne(n.token)??`https://api.individual.githubcopilot.com`,githubAccessToken:e}}var A=`github-copilot.models.v1`;function j(e){let t=e.supported_endpoints??[],n=(e.vendor??``).toLowerCase(),r=e.id;return n===`anthropic`&&t.includes(`/v1/messages`)?`anthropic-messages`:n===`openai`&&(/^gpt-5/i.test(r)||/codex/i.test(r)||/^o\d/i.test(r))?`openai-responses`:`openai-completions`}function M(e){if(!e||typeof e!=`object`)return[];let t=e.data;if(!Array.isArray(t))return[];let n=[];for(let e of t)e.capabilities?.type&&e.capabilities.type!==`chat`||e.model_picker_enabled!==!1&&e.id&&n.push({id:e.id,name:e.name??e.id,vendor:e.vendor??``,api:j(e),contextWindow:e.capabilities?.limits?.max_context_window_tokens??e.capabilities?.limits?.max_prompt_tokens??128e3,maxTokens:e.capabilities?.limits?.max_output_tokens??8192,supportsTools:e.capabilities?.supports?.tool_calls===!0,supportsStreaming:e.capabilities?.supports?.streaming!==!1,supportsVision:e.capabilities?.supports?.vision===!0,supportsReasoning:e.capabilities?.supports?.adaptive_thinking===!0||Array.isArray(e.capabilities?.supports?.reasoning_effort),policyState:e.policy?.state??`enabled`});return n}async function N(e){let t=await fetch(`${e.apiBaseUrl}/models`,{headers:{...w,Authorization:`Bearer ${e.copilotToken}`,Accept:`application/json`}});if(!t.ok)throw Error(`Copilot /models returned ${t.status} ${t.statusText}`);return M(await t.json())}function P(){if(typeof localStorage>`u`)return[];try{let e=localStorage.getItem(A);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function F(e){if(typeof localStorage<`u`)try{localStorage.setItem(A,JSON.stringify(e))}catch{}}function I(e){return P().find(t=>t.id===e)??null}async function L(e){let t;try{t=await N(e)}catch(e){console.warn(`[github-copilot] Catalog refresh failed; keeping previous cache.`,e instanceof Error?e.message:String(e));return}F(t),await Promise.all(t.filter(e=>e.policyState===`disabled`).map(async t=>{let n=`${e.apiBaseUrl}/models/${encodeURIComponent(t.id)}/policy`;try{let r=await fetch(n,{method:`POST`,headers:{...w,"Content-Type":`application/json`,Authorization:`Bearer ${e.copilotToken}`,"openai-intent":`chat-policy`,"x-interaction-type":`chat-policy`},body:JSON.stringify({state:`enabled`})});r.ok?t.policyState=`enabled`:r.status!==404&&r.status!==400&&console.warn(`[github-copilot] enable policy for ${t.id} returned ${r.status} ${r.statusText}`)}catch(e){console.warn(`[github-copilot] enable policy for ${t.id} failed:`,e instanceof Error?e.message:String(e))}})),F(t)}async function R(e,t){await d({providerId:y,accessToken:e.copilotToken,refreshToken:e.githubAccessToken,tokenExpiresAt:e.expiresAtMs,baseUrl:e.apiBaseUrl,userName:t})}async function z(){let e=D();if(!e?.accessToken||!e.refreshToken)throw Error(`Not logged in to GitHub Copilot — click "Login" in the provider settings`);let t=e.tokenExpiresAt??0;if(Date.now()<t-6e4)return e.accessToken;let n=await k(e.refreshToken);return await R(n,e.userName),n.copilotToken}var B=[`mini`,`nano`,`flash`,`haiku`,`lite`,`embedding`];function V(e){let t=[e.id,e.name??``].flatMap(e=>{let t=e.toLowerCase();return[t,t.replace(/[\s_.:]+/g,`-`)]});return!B.some(e=>t.some(t=>t.includes(e)))}function H(){if(!D()?.accessToken)return[];let e=P();if(e.length>0)return e.filter(e=>!e.policyState.startsWith(`unavailable:`)).filter(e=>V(e)).map(e=>({id:e.id,name:e.name,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.supportsReasoning,input:e.supportsVision?[`text`,`image`]:[`text`]}));let t;try{t=l(`github-copilot`)}catch{return[]}return t.filter(e=>V({id:e.id,name:e.name})).map(e=>({id:e.id,name:e.name??e.id,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.reasoning,input:e.input}))}function U(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:e.api,provider:y,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var W={"User-Agent":`GitHubCopilotChat/0.35.0`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`};function G(e){let t=D(),n=t?.baseUrl??`https://api.individual.githubcopilot.com`,r=I(e);if(r)return{api:r.api,baseUrl:n,headers:{...W}};try{let n=u(`github-copilot`,e);return{api:n.api,baseUrl:t?.baseUrl??n.baseUrl,headers:{...n.headers??{},...W}}}catch{return null}}function K(e,t){let n=P(),r=n.findIndex(t=>t.id===e);r<0||(n[r]={...n[r],policyState:`unavailable:${t}`},F(n))}function q(e,t){return`GitHub Copilot rejected "${e}" with model_not_supported. This usually means the model isn't included in your Copilot plan (Opus and other premium models require Copilot Pro / Pro+ / Business / Enterprise). Try Claude Sonnet 4.6 or another model that appears in the picker after a fresh login. Original error: ${t}`}function J(e){if(!e||typeof e!=`object`)return null;let t=e;if(t.type!==`error`)return null;if(t.error&&typeof t.error==`object`){let e=t.error.errorMessage;if(typeof e==`string`)return e}return typeof t.errorMessage==`string`?t.errorMessage:null}function Y(e,t){return e===`anthropic-messages`?t?r:c:e===`openai-responses`?t?i:a:t?s:o}function X(e,t,n){let r=J(n);if(r&&/model_not_supported/i.test(r)){K(t.id,`model_not_supported`);let n=q(t.id,r);return console.error(`[github-copilot] Plan-gated model rejection:`,n),e.push(U(t,Error(n))),e.end(),!0}return e.push(n),!1}function re(e,t,n){let r=n instanceof Error?n.message:String(n),i=n;/model_not_supported/i.test(r)&&(K(t.id,`model_not_supported`),i=Error(q(t.id,r))),console.error(`[github-copilot] Stream error:`,i instanceof Error?i.message:String(i)),e.push(U(t,i)),e.end()}async function ie(e,t,n,r,i){try{let a=await z(),o=G(t.id);if(!o)throw Error(`GitHub Copilot does not recognize "${t.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let s=o.api===`anthropic-messages`?m(t,o):{...t,api:o.api,baseUrl:o.baseUrl,headers:o.headers,provider:`github-copilot`},c={...r,apiKey:a},l=Y(o.api,i)(s,n,c);for await(let n of l)if(X(e,t,n))return;e.end()}catch(n){re(e,t,n)}}function Z(t){return(n,r,i={})=>{let a=e();return ie(a,n,r,i,t),a}}var Q=Z(!1),$=Z(!0),ae=({userCode:e,verificationUrl:n})=>typeof document>`u`?(console.info(`[github-copilot] Device verification code: ${e} — open ${n} in a browser to authorize.`),Promise.resolve(`continue`)):new Promise(n=>{let r=document.createElement(`div`);r.setAttribute(`data-slicc-overlay`,`github-copilot-device`),r.style.cssText=[`position:fixed`,`top:24px`,`right:24px`,`z-index:2147483647`,`background:#0d1117`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:10px`,`padding:16px 18px`,`box-shadow:0 8px 32px rgba(0,0,0,0.45)`,`font:13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,`min-width:260px`,`max-width:340px`].join(`;`);let i=document.createElement(`div`);i.textContent=`GitHub Copilot — verification code`,i.style.cssText=`font-weight:600;margin-bottom:8px;color:#7ee787`;let a=document.createElement(`div`);a.textContent=e,a.style.cssText=[`font:600 22px ui-monospace, SFMono-Regular, Menlo, monospace`,`letter-spacing:2px`,`background:#161b22`,`border:1px solid #30363d`,`border-radius:6px`,`padding:10px 12px`,`text-align:center`,`margin-bottom:10px`,`user-select:all`,`cursor:text`].join(`;`);let o=document.createElement(`div`);o.style.cssText=`color:#8b949e;font-size:12px;line-height:1.5`,o.textContent=`Copy the code, then click Continue to open the GitHub authorization page in a new tab.`;let s=document.createElement(`div`);s.style.cssText=`display:flex;gap:8px;margin-top:12px;justify-content:flex-end`;let c=document.createElement(`button`);c.type=`button`,c.textContent=`Cancel`,c.style.cssText=[`background:transparent`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let l=document.createElement(`button`);l.type=`button`,l.textContent=`Copy & Continue`,l.style.cssText=[`background:#238636`,`color:#fff`,`border:0`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let u=()=>{try{r.remove()}catch{}};c.addEventListener(`click`,()=>{u(),n(`cancel`)}),l.addEventListener(`click`,()=>{(async()=>{try{let{copyTextToClipboard:n}=await t(async()=>{let{copyTextToClipboard:e}=await import(`./clipboard-eqmn97SP.js`).then(e=>e.t);return{copyTextToClipboard:e}},__vite__mapDeps([0,1]));await n(e)}catch{}u(),n(`continue`)})()}),s.appendChild(c),s.appendChild(l),r.appendChild(i),r.appendChild(a),r.appendChild(o),r.appendChild(s),document.body.appendChild(r)});async function oe(){let e=D();return e?.refreshToken?v(e.refreshToken,fetch,{headers:w}):null}var se={id:y,name:`GitHub Copilot`,description:`Use your GitHub Copilot subscription to access Claude, GPT-5, Codex, Gemini, and Grok models. Sign in with the GitHub device-code flow.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`claude-sonnet-4.6`,oauthTokenDomains:[`*.githubcopilot.com`,`api.individual.githubcopilot.com`,`api.business.githubcopilot.com`,`api.enterprise.githubcopilot.com`],getModelIds:H,getBudgetUsage:oe,onOAuthLoginIntercepted:async(e,t,n)=>{let r=await O(),i=new URL(r.verification_uri);if(i.searchParams.set(`user_code`,r.user_code),await(n?.presentDeviceCode??ae)({userCode:r.user_code,verificationUrl:i.toString(),expiresInSeconds:r.expires_in})===`cancel`)throw Error(`GitHub Copilot login cancelled`);let a=new AbortController,o=e({authorizeUrl:i.toString(),redirectUriPattern:E,onCapture:`close`,timeoutMs:r.expires_in*1e3}).catch(e=>(console.warn(`[github-copilot] Launcher failed:`,e instanceof Error?e.message:String(e)),null)),s;try{s=await ee(r,a.signal)}catch(e){throw a.abort(),await o,e}await o;let c=await k(s),l;try{let e=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${s}`,Accept:`application/json`}});if(e.ok){let t=await e.json();l=t.name||t.login}}catch{}await R(c,l),await L(c),t()},onOAuthLogout:async()=>{await d({providerId:y,accessToken:``})},onSilentRenew:async()=>{let e=D();if(!e?.refreshToken)return null;try{let t=await k(e.refreshToken);return await R(t,e.userName),await L(t),t.copilotToken}catch(e){return console.warn(`[github-copilot] Silent renew failed:`,e instanceof Error?e.message:String(e)),null}}};function ce(){n({api:`github-copilot-anthropic`,stream:Q,streamSimple:$}),n({api:`github-copilot-openai`,stream:Q,streamSimple:$})}export{se as config,V as isCopilotConeCompatible,ce as register};
|
|
2
|
+
import{a as e}from"./diagnostics-B-5VkVir.js";import{t}from"./preload-helper-BLdHbfdN.js";import{a as n}from"./compat-TaBTsXFP.js";import{a as r,c as i,i as a,r as o,s,t as c}from"./legacy-api-aliases-BqXqjuwj.js";import{a as l,i as u}from"./core-kdG72Y8N.js";import{K as d,u as f}from"./account-store-C8ku_32k.js";import"./main-CWx8ZbOh.js";import{t as p}from"./anthropic-proxy-compat-CaymbdBf.js";function m(e,t){return{...e,api:`anthropic-messages`,baseUrl:t.baseUrl,headers:t.headers,provider:`github-copilot`,compat:p(e.compat)}}var h=`https://api.github.com/copilot_internal/user`,g=8e3;function _(e){if(!e||typeof e!=`object`)return null;let t=e.quota_snapshots?.premium_interactions;return!t||t.unlimited||typeof t.percent_remaining!=`number`?null:{percent:Math.max(0,100-t.percent_remaining),status:t.percent_remaining<=0&&t.overage_permitted!==!0?`rate-limited`:`ok`,window:`monthly`,resetsAt:e.quota_reset_date_utc}}async function v(e,t,n={}){let r=typeof AbortController==`function`?new AbortController:null,i=r?setTimeout(()=>r.abort(),n.timeoutMs??g):null;try{let i=await t(h,{headers:{...n.headers,Authorization:`Bearer ${e}`},...r?{signal:r.signal}:{}});if(i.status===404||i.status===501)return null;if(!i.ok)throw Error(`GitHub Copilot /copilot_internal/user returned ${i.status}`);return _(await i.json())}finally{i&&clearTimeout(i)}}var y=`github-copilot`,b=atob(`SXYxLmI1MDdhMDhjODdlY2ZlOTg=`),x=`https://github.com/login/device/code`,S=`https://github.com/login/oauth/access_token`,C=`https://api.github.com/copilot_internal/v2/token`,w={Accept:`application/json`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`},T={Accept:`application/json`,"Content-Type":`application/x-www-form-urlencoded`},E=`https://github.com/login/device/success*`;function D(){return f().find(e=>e.providerId===y)}async function O(){let e=await fetch(x,{method:`POST`,headers:T,body:new URLSearchParams({client_id:b,scope:`read:user`})});if(!e.ok)throw Error(`GitHub device-code request failed: ${e.status} ${e.statusText} — ${await e.text().catch(()=>``)}`);let t=await e.json();if(typeof t.device_code!=`string`||typeof t.user_code!=`string`||typeof t.verification_uri!=`string`||typeof t.expires_in!=`number`||typeof t.interval!=`number`)throw Error(`GitHub device-code response had an unexpected shape`);return t}async function ee(e,t){let n=Date.now()+e.expires_in*1e3,r=Math.max(1e3,Math.floor(e.interval*1e3)),i=1.2;for(;Date.now()<n;){if(t.aborted)throw Error(`Copilot login cancelled`);await te(Math.ceil(r*i),t);let n=await fetch(S,{method:`POST`,headers:T,body:new URLSearchParams({client_id:b,device_code:e.device_code,grant_type:`urn:ietf:params:oauth:grant-type:device_code`})});if(!n.ok)throw Error(`GitHub token poll failed: ${n.status} ${n.statusText} — ${await n.text().catch(()=>``)}`);let a=await n.json();if(typeof a.access_token==`string`&&a.access_token.length>0)return a.access_token;if(a.error!==`authorization_pending`){if(a.error===`slow_down`){r=typeof a.interval==`number`?a.interval*1e3:r+5e3,i=1.4;continue}if(a.error){let e=a.error_description?`: ${a.error_description}`:``;throw Error(`Device flow failed (${a.error})${e}`)}}}throw Error(`Copilot device flow timed out (device code expired)`)}function te(e,t){return new Promise((n,r)=>{if(t.aborted){r(Error(`Copilot login cancelled`));return}let i=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Copilot login cancelled`))},{once:!0})})}function ne(e){let t=e.match(/proxy-ep=([^;]+)/);return t?`https://${t[1].replace(/^proxy\./,`api.`)}`:null}async function k(e){let t=await fetch(C,{headers:{...w,Authorization:`Bearer ${e}`}});if(!t.ok){let e=await t.text().catch(()=>``);throw Error(`Copilot token exchange failed: ${t.status} ${t.statusText} — ${e.slice(0,300)}`)}let n=await t.json();if(typeof n.token!=`string`||typeof n.expires_at!=`number`)throw Error(`Copilot token exchange returned an unexpected payload`);if(n.chat_enabled===!1)throw Error(`GitHub Copilot Chat is disabled for this account (no chat features granted)`);return{copilotToken:n.token,expiresAtMs:n.expires_at*1e3-3e5,apiBaseUrl:ne(n.token)??`https://api.individual.githubcopilot.com`,githubAccessToken:e}}var A=`github-copilot.models.v1`;function j(e){let t=e.supported_endpoints??[],n=(e.vendor??``).toLowerCase(),r=e.id;return n===`anthropic`&&t.includes(`/v1/messages`)?`anthropic-messages`:n===`openai`&&(/^gpt-5/i.test(r)||/codex/i.test(r)||/^o\d/i.test(r))?`openai-responses`:`openai-completions`}function M(e){if(!e||typeof e!=`object`)return[];let t=e.data;if(!Array.isArray(t))return[];let n=[];for(let e of t)e.capabilities?.type&&e.capabilities.type!==`chat`||e.model_picker_enabled!==!1&&e.id&&n.push({id:e.id,name:e.name??e.id,vendor:e.vendor??``,api:j(e),contextWindow:e.capabilities?.limits?.max_context_window_tokens??e.capabilities?.limits?.max_prompt_tokens??128e3,maxTokens:e.capabilities?.limits?.max_output_tokens??8192,supportsTools:e.capabilities?.supports?.tool_calls===!0,supportsStreaming:e.capabilities?.supports?.streaming!==!1,supportsVision:e.capabilities?.supports?.vision===!0,supportsReasoning:e.capabilities?.supports?.adaptive_thinking===!0||Array.isArray(e.capabilities?.supports?.reasoning_effort),policyState:e.policy?.state??`enabled`});return n}async function N(e){let t=await fetch(`${e.apiBaseUrl}/models`,{headers:{...w,Authorization:`Bearer ${e.copilotToken}`,Accept:`application/json`}});if(!t.ok)throw Error(`Copilot /models returned ${t.status} ${t.statusText}`);return M(await t.json())}function P(){if(typeof localStorage>`u`)return[];try{let e=localStorage.getItem(A);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function F(e){if(typeof localStorage<`u`)try{localStorage.setItem(A,JSON.stringify(e))}catch{}}function I(e){return P().find(t=>t.id===e)??null}async function L(e){let t;try{t=await N(e)}catch(e){console.warn(`[github-copilot] Catalog refresh failed; keeping previous cache.`,e instanceof Error?e.message:String(e));return}F(t),await Promise.all(t.filter(e=>e.policyState===`disabled`).map(async t=>{let n=`${e.apiBaseUrl}/models/${encodeURIComponent(t.id)}/policy`;try{let r=await fetch(n,{method:`POST`,headers:{...w,"Content-Type":`application/json`,Authorization:`Bearer ${e.copilotToken}`,"openai-intent":`chat-policy`,"x-interaction-type":`chat-policy`},body:JSON.stringify({state:`enabled`})});r.ok?t.policyState=`enabled`:r.status!==404&&r.status!==400&&console.warn(`[github-copilot] enable policy for ${t.id} returned ${r.status} ${r.statusText}`)}catch(e){console.warn(`[github-copilot] enable policy for ${t.id} failed:`,e instanceof Error?e.message:String(e))}})),F(t)}async function R(e,t){await d({providerId:y,accessToken:e.copilotToken,refreshToken:e.githubAccessToken,tokenExpiresAt:e.expiresAtMs,baseUrl:e.apiBaseUrl,userName:t})}async function z(){let e=D();if(!e?.accessToken||!e.refreshToken)throw Error(`Not logged in to GitHub Copilot — click "Login" in the provider settings`);let t=e.tokenExpiresAt??0;if(Date.now()<t-6e4)return e.accessToken;let n=await k(e.refreshToken);return await R(n,e.userName),n.copilotToken}var B=[`mini`,`nano`,`flash`,`haiku`,`lite`,`embedding`];function V(e){let t=[e.id,e.name??``].flatMap(e=>{let t=e.toLowerCase();return[t,t.replace(/[\s_.:]+/g,`-`)]});return!B.some(e=>t.some(t=>t.includes(e)))}function H(){if(!D()?.accessToken)return[];let e=P();if(e.length>0)return e.filter(e=>!e.policyState.startsWith(`unavailable:`)).filter(e=>V(e)).map(e=>({id:e.id,name:e.name,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.supportsReasoning,input:e.supportsVision?[`text`,`image`]:[`text`]}));let t;try{t=l(`github-copilot`)}catch{return[]}return t.filter(e=>V({id:e.id,name:e.name})).map(e=>({id:e.id,name:e.name??e.id,api:e.api===`anthropic-messages`?`anthropic`:`openai`,context_window:e.contextWindow,max_tokens:e.maxTokens,reasoning:e.reasoning,input:e.input}))}function U(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:e.api,provider:y,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}}var W={"User-Agent":`GitHubCopilotChat/0.35.0`,"Editor-Version":`vscode/1.107.0`,"Editor-Plugin-Version":`copilot-chat/0.35.0`,"Copilot-Integration-Id":`vscode-chat`};function G(e){let t=D(),n=t?.baseUrl??`https://api.individual.githubcopilot.com`,r=I(e);if(r)return{api:r.api,baseUrl:n,headers:{...W}};try{let n=u(`github-copilot`,e);return{api:n.api,baseUrl:t?.baseUrl??n.baseUrl,headers:{...n.headers??{},...W}}}catch{return null}}function K(e,t){let n=P(),r=n.findIndex(t=>t.id===e);r<0||(n[r]={...n[r],policyState:`unavailable:${t}`},F(n))}function q(e,t){return`GitHub Copilot rejected "${e}" with model_not_supported. This usually means the model isn't included in your Copilot plan (Opus and other premium models require Copilot Pro / Pro+ / Business / Enterprise). Try Claude Sonnet 4.6 or another model that appears in the picker after a fresh login. Original error: ${t}`}function J(e){if(!e||typeof e!=`object`)return null;let t=e;if(t.type!==`error`)return null;if(t.error&&typeof t.error==`object`){let e=t.error.errorMessage;if(typeof e==`string`)return e}return typeof t.errorMessage==`string`?t.errorMessage:null}function Y(e,t){return e===`anthropic-messages`?t?r:c:e===`openai-responses`?t?i:a:t?s:o}function X(e,t,n){let r=J(n);if(r&&/model_not_supported/i.test(r)){K(t.id,`model_not_supported`);let n=q(t.id,r);return console.error(`[github-copilot] Plan-gated model rejection:`,n),e.push(U(t,Error(n))),e.end(),!0}return e.push(n),!1}function re(e,t,n){let r=n instanceof Error?n.message:String(n),i=n;/model_not_supported/i.test(r)&&(K(t.id,`model_not_supported`),i=Error(q(t.id,r))),console.error(`[github-copilot] Stream error:`,i instanceof Error?i.message:String(i)),e.push(U(t,i)),e.end()}async function ie(e,t,n,r,i){try{let a=await z(),o=G(t.id);if(!o)throw Error(`GitHub Copilot does not recognize "${t.id}" — open the picker (the model list refreshes on login) and pick a current model.`);let s=o.api===`anthropic-messages`?m(t,o):{...t,api:o.api,baseUrl:o.baseUrl,headers:o.headers,provider:`github-copilot`},c={...r,apiKey:a},l=Y(o.api,i)(s,n,c);for await(let n of l)if(X(e,t,n))return;e.end()}catch(n){re(e,t,n)}}function Z(t){return(n,r,i={})=>{let a=e();return ie(a,n,r,i,t),a}}var Q=Z(!1),$=Z(!0),ae=({userCode:e,verificationUrl:n})=>typeof document>`u`?(console.info(`[github-copilot] Device verification code: ${e} — open ${n} in a browser to authorize.`),Promise.resolve(`continue`)):new Promise(n=>{let r=document.createElement(`div`);r.setAttribute(`data-slicc-overlay`,`github-copilot-device`),r.style.cssText=[`position:fixed`,`top:24px`,`right:24px`,`z-index:2147483647`,`background:#0d1117`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:10px`,`padding:16px 18px`,`box-shadow:0 8px 32px rgba(0,0,0,0.45)`,`font:13px/1.4 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,`min-width:260px`,`max-width:340px`].join(`;`);let i=document.createElement(`div`);i.textContent=`GitHub Copilot — verification code`,i.style.cssText=`font-weight:600;margin-bottom:8px;color:#7ee787`;let a=document.createElement(`div`);a.textContent=e,a.style.cssText=[`font:600 22px ui-monospace, SFMono-Regular, Menlo, monospace`,`letter-spacing:2px`,`background:#161b22`,`border:1px solid #30363d`,`border-radius:6px`,`padding:10px 12px`,`text-align:center`,`margin-bottom:10px`,`user-select:all`,`cursor:text`].join(`;`);let o=document.createElement(`div`);o.style.cssText=`color:#8b949e;font-size:12px;line-height:1.5`,o.textContent=`Copy the code, then click Continue to open the GitHub authorization page in a new tab.`;let s=document.createElement(`div`);s.style.cssText=`display:flex;gap:8px;margin-top:12px;justify-content:flex-end`;let c=document.createElement(`button`);c.type=`button`,c.textContent=`Cancel`,c.style.cssText=[`background:transparent`,`color:#e6edf3`,`border:1px solid #30363d`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let l=document.createElement(`button`);l.type=`button`,l.textContent=`Copy & Continue`,l.style.cssText=[`background:#238636`,`color:#fff`,`border:0`,`border-radius:6px`,`padding:6px 12px`,`font:600 12px inherit`,`cursor:pointer`].join(`;`);let u=()=>{try{r.remove()}catch{}};c.addEventListener(`click`,()=>{u(),n(`cancel`)}),l.addEventListener(`click`,()=>{(async()=>{try{let{copyTextToClipboard:n}=await t(async()=>{let{copyTextToClipboard:e}=await import(`./clipboard-eqmn97SP.js`).then(e=>e.t);return{copyTextToClipboard:e}},__vite__mapDeps([0,1]));await n(e)}catch{}u(),n(`continue`)})()}),s.appendChild(c),s.appendChild(l),r.appendChild(i),r.appendChild(a),r.appendChild(o),r.appendChild(s),document.body.appendChild(r)});async function oe(){let e=D();return e?.refreshToken?v(e.refreshToken,fetch,{headers:w}):null}var se={id:y,name:`GitHub Copilot`,description:`Use your GitHub Copilot subscription to access Claude, GPT-5, Codex, Gemini, and Grok models. Sign in with the GitHub device-code flow.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`claude-sonnet-4.6`,oauthTokenDomains:[`*.githubcopilot.com`,`api.individual.githubcopilot.com`,`api.business.githubcopilot.com`,`api.enterprise.githubcopilot.com`],getModelIds:H,getBudgetUsage:oe,onOAuthLoginIntercepted:async(e,t,n)=>{let r=await O(),i=new URL(r.verification_uri);if(i.searchParams.set(`user_code`,r.user_code),await(n?.presentDeviceCode??ae)({userCode:r.user_code,verificationUrl:i.toString(),expiresInSeconds:r.expires_in})===`cancel`)throw Error(`GitHub Copilot login cancelled`);let a=new AbortController,o=e({authorizeUrl:i.toString(),redirectUriPattern:E,onCapture:`close`,timeoutMs:r.expires_in*1e3}).catch(e=>(console.warn(`[github-copilot] Launcher failed:`,e instanceof Error?e.message:String(e)),null)),s;try{s=await ee(r,a.signal)}catch(e){throw a.abort(),await o,e}await o;let c=await k(s),l;try{let e=await fetch(`https://api.github.com/user`,{headers:{Authorization:`Bearer ${s}`,Accept:`application/json`}});if(e.ok){let t=await e.json();l=t.name||t.login}}catch{}await R(c,l),await L(c),t()},onOAuthLogout:async()=>{await d({providerId:y,accessToken:``})},onSilentRenew:async()=>{let e=D();if(!e?.refreshToken)return null;try{let t=await k(e.refreshToken);return await R(t,e.userName),await L(t),t.copilotToken}catch(e){return console.warn(`[github-copilot] Silent renew failed:`,e instanceof Error?e.message:String(e)),null}}};function ce(){n({api:`github-copilot-anthropic`,stream:Q,streamSimple:$}),n({api:`github-copilot-openai`,stream:Q,streamSimple:$})}export{se as config,V as isCopilotConeCompatible,ce as register};
|