@opensesame-labs/web-pwa 0.0.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/bin/serve.mjs +60 -0
- package/dist/404.html +35 -0
- package/dist/about.html +37 -0
- package/dist/assets/AmbientAuthPanel-CwFZygJY.js +1 -0
- package/dist/assets/AppShell-OiN-7dB4.css +1 -0
- package/dist/assets/AppShell-xqEu_Cfz.js +1 -0
- package/dist/assets/ApproveScreen-Dj995x0T.js +1 -0
- package/dist/assets/BackupEnableSwitch-DwKTWzBG.js +1 -0
- package/dist/assets/CoachHud-9Bqu4Gtl.css +1 -0
- package/dist/assets/CoachHud-DHqFf7ez.js +1 -0
- package/dist/assets/Crumbs-BQsauYj_.js +1 -0
- package/dist/assets/DraftSuggestions-DT51r14S.js +2 -0
- package/dist/assets/DraftSuggestions-DuLxCyqM.css +1 -0
- package/dist/assets/EmptyTip-DnxQjLsP.js +1 -0
- package/dist/assets/FeatureSections-BG-JsWID.js +1 -0
- package/dist/assets/FormatHintMatch-QX0JkGnd.js +1 -0
- package/dist/assets/HealthPanel-DXnPgdo5.js +1 -0
- package/dist/assets/IdentityConnectionSignIn-Bg53RjtJ.js +2 -0
- package/dist/assets/InteractionScreen-BCh2d-a4.js +1 -0
- package/dist/assets/InvokeScreen-C-kFFYVF.js +1 -0
- package/dist/assets/InvokeScreen-CsvSkues.css +1 -0
- package/dist/assets/ItemDetail-DCzWiS4b.js +1 -0
- package/dist/assets/ItemEditor-BQp0D0PB.js +1 -0
- package/dist/assets/KeybindingsPanels-Buh32SBq.css +1 -0
- package/dist/assets/KeybindingsPanels-CAhCFduu.js +1 -0
- package/dist/assets/MethodPicker-CqQTyAaT.js +1 -0
- package/dist/assets/MfaStep-DvSV4q5P.js +1 -0
- package/dist/assets/OpenFileKey-DKFq5mOf.js +1 -0
- package/dist/assets/PageTreeBranch-OgsaK684.js +1 -0
- package/dist/assets/SaveRequestScreen-exu7HwhA.js +1 -0
- package/dist/assets/SettingsSection-BHTAhGaz.css +1 -0
- package/dist/assets/SettingsSection-BfxiCHWn.js +2 -0
- package/dist/assets/SiopAuthorize-D_OIu8gb.js +1 -0
- package/dist/assets/SupportLauncher-DgUajogl.css +1 -0
- package/dist/assets/SupportLauncher-DlkkaWxf.js +2 -0
- package/dist/assets/SupportPanel-W7lTTCHo.js +1 -0
- package/dist/assets/VaultSection-BUcbIjl5.css +1 -0
- package/dist/assets/VaultSection-DuzGVD_1.js +1 -0
- package/dist/assets/WalletSection-C4CTvIi9.js +1 -0
- package/dist/assets/agent-ag-ui-DRbKYcn6.js +2 -0
- package/dist/assets/agent-boundary-D0s3Xear.js +2 -0
- package/dist/assets/agent-prompt-api-BiYrmT5D.js +1 -0
- package/dist/assets/agent-provider-BiJcKH7o.js +1 -0
- package/dist/assets/binary-encoding-D9rJ9tvs.js +1 -0
- package/dist/assets/bitwarden-native.worker-CFoAF-yw.js +1 -0
- package/dist/assets/bitwarden-secrets.worker-BfAQLREw.js +1 -0
- package/dist/assets/bitwarden_wasm_bg.wasm-B2_HqYUA.gz +0 -0
- package/dist/assets/browser-pslP6-1t.js +1 -0
- package/dist/assets/bucket-boot-4cPKWVva.js +1 -0
- package/dist/assets/bucket-saved-vQCiVvN_.js +1 -0
- package/dist/assets/byo-B-SNpHiS.js +1 -0
- package/dist/assets/byo-CDLRauwG.css +1 -0
- package/dist/assets/canary-owner-effects-CY2GR4d-.js +1 -0
- package/dist/assets/cap-access.authority-D-B2rtcO.js +1 -0
- package/dist/assets/cap-agents.surrogate-credentials-7eqyWZfT.js +1 -0
- package/dist/assets/cap-agents.webmcp-Bve0G9t3.js +2 -0
- package/dist/assets/cap-ai.password-reset-rh9CIhu-.js +1 -0
- package/dist/assets/cap-connectors.external-dKuiKE5J.js +1 -0
- package/dist/assets/cap-enterprise.ca-administration-CirJdAWC.js +1 -0
- package/dist/assets/cap-enterprise.directory-provisioning-ixTSdLjk.js +1 -0
- package/dist/assets/cap-identity.ambient-sso-Bfz5okEX.js +1 -0
- package/dist/assets/cap-identity.claim-different-link-C0NXeZQE.js +1 -0
- package/dist/assets/cap-identity.federation-Di6GjTkh.js +1 -0
- package/dist/assets/cap-identity.local-iam-DdhiDQdb.js +2 -0
- package/dist/assets/cap-identity.siop-C80liHvH.js +1 -0
- package/dist/assets/cap-networking.tailnet-c5h7F7pL.js +1 -0
- package/dist/assets/cap-networking.tailnet-devices-BeZz-plo.js +1 -0
- package/dist/assets/cap-notifications.local-QwuLGxJM.js +1 -0
- package/dist/assets/cap-notifications.routing-CF-Wp35c.js +1 -0
- package/dist/assets/cap-notifications.web-push-DAddcIp-.js +1 -0
- package/dist/assets/cap-sharing.household-BeYPmwj5.js +1 -0
- package/dist/assets/cap-sharing.live-BkP10O4Q.js +2 -0
- package/dist/assets/cap-sharing.relay-Clx_tuEX.js +1 -0
- package/dist/assets/cap-sharing.trusted-contacts-D7bWujCh.js +1 -0
- package/dist/assets/cap-storage.encrypted-search-PLxhoql0.js +1 -0
- package/dist/assets/cap-support.local-ai-3PHedffw.js +1 -0
- package/dist/assets/cap-support.remote-ai-CmtCh9L6.js +1 -0
- package/dist/assets/cap-telemetry.external-BF6Csk9L.js +1 -0
- package/dist/assets/cap-vault.browser-autofill-CdS4F8Xw.js +1 -0
- package/dist/assets/cap-vault.certificate-records-Br6SdLtm.js +1 -0
- package/dist/assets/cap-vault.derived-records-CJXFAVNG.js +1 -0
- package/dist/assets/cap-vault.environments-CfpmRCF-.js +1 -0
- package/dist/assets/cap-vault.passkey-records-kB9UoKJ4.js +1 -0
- package/dist/assets/cap-vault.security-checks-BXzOBUjO.js +1 -0
- package/dist/assets/cap-wallet.spending-BGifVwmx.js +1 -0
- package/dist/assets/catalog-Y21H0gVA.js +1 -0
- package/dist/assets/certification_request-yoK4-cIl.js +1 -0
- package/dist/assets/certs-CDCfMuEi.js +1 -0
- package/dist/assets/cli-app-integration-crypto-TwyER0q4.js +2 -0
- package/dist/assets/commonjs-runtime-R6OqCcd0.js +1 -0
- package/dist/assets/compartment-guard-D3FuKM8N.js +1 -0
- package/dist/assets/configured-runtime-qg0cjMOO.js +1 -0
- package/dist/assets/connect-plan-ClXbb_FT.js +1 -0
- package/dist/assets/connections-CNmhCNAV.js +1 -0
- package/dist/assets/connectivity-monitor-B0ueE5HQ.js +1 -0
- package/dist/assets/connector-directory-D47kqlDJ.css +1 -0
- package/dist/assets/connector-directory-gjDOqgWh.js +1 -0
- package/dist/assets/connector-marks-BsMcGRbV.js +1 -0
- package/dist/assets/connector-settings-CBJ6GX5X.js +1 -0
- package/dist/assets/consent-CcqmRPoB.js +1 -0
- package/dist/assets/context-CL4-cwvA.js +1 -0
- package/dist/assets/context-DQQZvpeW.js +1 -0
- package/dist/assets/device-identity-carry-XMZRU4oW.js +1 -0
- package/dist/assets/device-identity-host-Bc5g7ie-.js +1 -0
- package/dist/assets/device-inbox-BoaNI30L.js +1 -0
- package/dist/assets/directory-panels-DNhzC0ld.js +1 -0
- package/dist/assets/directory-panels-DiZjkKtX.css +1 -0
- package/dist/assets/directory-signin-model-BfxENbC3.js +1 -0
- package/dist/assets/drop-open-BjgdLxWM.js +2 -0
- package/dist/assets/entra-instances-NyEKYI5c.js +1 -0
- package/dist/assets/features-9FeW22VH.js +1 -0
- package/dist/assets/federation-configured-restoration-DWAXgzcz.js +1 -0
- package/dist/assets/files-Bc2ZE3YH.js +1 -0
- package/dist/assets/gate-seat-D6oRkKUH.css +1 -0
- package/dist/assets/gate-seat-DHBrLaMG.js +2 -0
- package/dist/assets/github-app-local-B-4pPsY4.js +1 -0
- package/dist/assets/hosted-identity-rail-CUw0rn2T.css +1 -0
- package/dist/assets/hosted-identity-rail-Dv05NPNo.js +1 -0
- package/dist/assets/hosted-model-authority-CcNPE44H.js +1 -0
- package/dist/assets/hosted-model-protocol-B8j_voAG.js +1 -0
- package/dist/assets/iam-0IMZ11b6.css +1 -0
- package/dist/assets/iam-zBfzStfy.js +1 -0
- package/dist/assets/identity-BVf8yWa4.js +1 -0
- package/dist/assets/identity-DrfyABP-.css +1 -0
- package/dist/assets/identity-view-paths-Bi1yigZk.js +1 -0
- package/dist/assets/idp-presets-B1M-P0Ek.js +1 -0
- package/dist/assets/index-B6LVfIPY.js +1 -0
- package/dist/assets/index-BDSP-mCB.js +1 -0
- package/dist/assets/index-DGpAAq0f.js +1 -0
- package/dist/assets/index-browser-Cl3nb4Uk.js +1 -0
- package/dist/assets/install-DvNMSThj.js +1 -0
- package/dist/assets/item-contributions-BNmtlrGT.js +2 -0
- package/dist/assets/item-contributions-DNpnHRuL.css +1 -0
- package/dist/assets/item-secret-update-BGxSkyWF.js +1 -0
- package/dist/assets/item-type-pack-account-CoqotdBn.js +1 -0
- package/dist/assets/item-type-pack-address-CuEhIEN8.js +1 -0
- package/dist/assets/item-type-pack-api-credential-2taJJvyo.js +1 -0
- package/dist/assets/item-type-pack-api-key-BtsbWNqK.js +1 -0
- package/dist/assets/item-type-pack-authenticator-C10FbI_v.js +1 -0
- package/dist/assets/item-type-pack-bank-account-C7tahN_l.js +1 -0
- package/dist/assets/item-type-pack-card-DI2dXCYa.js +1 -0
- package/dist/assets/item-type-pack-contact-C8PeT6f9.js +1 -0
- package/dist/assets/item-type-pack-crypto-wallet-Sfg8ziqc.js +1 -0
- package/dist/assets/item-type-pack-database-Dy7ScLs9.js +1 -0
- package/dist/assets/item-type-pack-drivers-license-vMew977g.js +1 -0
- package/dist/assets/item-type-pack-health-insurance-DUixDMZj.js +1 -0
- package/dist/assets/item-type-pack-identity-document-FU9zx609.js +1 -0
- package/dist/assets/item-type-pack-membership-D_NYNr9q.js +1 -0
- package/dist/assets/item-type-pack-note-B3DY9bUR.js +1 -0
- package/dist/assets/item-type-pack-oauth-client-DMhUuM7e.js +1 -0
- package/dist/assets/item-type-pack-passport-B8VaXkBH.js +1 -0
- package/dist/assets/item-type-pack-password-D--bKPPZ.js +1 -0
- package/dist/assets/item-type-pack-server-BwQMhxjI.js +1 -0
- package/dist/assets/item-type-pack-software-license-CG2Bi2-4.js +1 -0
- package/dist/assets/item-type-pack-ssh-key-Cf4KqR5v.js +1 -0
- package/dist/assets/item-type-pack-token-Cfp58zHW.js +1 -0
- package/dist/assets/item-type-pack-wifi-DlJBEYLH.js +1 -0
- package/dist/assets/kdbxweb-Deb8D9Lv.js +1 -0
- package/dist/assets/linearRedirect-Cac5chv5.js +1 -0
- package/dist/assets/listing-page-B-c8QQVp.js +1 -0
- package/dist/assets/live-mqtt-BaSKU8QX.js +1 -0
- package/dist/assets/live-nats-CsIvuPj3.js +1 -0
- package/dist/assets/live-nostr-BfmabjiE.js +1 -0
- package/dist/assets/live-transport-files-DQCGPnPz.js +1 -0
- package/dist/assets/live-transport-files-Zxaw-sAI.css +1 -0
- package/dist/assets/local-ai-sdk-entry-Dq4Sm2_e.js +1 -0
- package/dist/assets/local-applications-rigvedS6.js +2 -0
- package/dist/assets/local-directory-bootstrap-NwIMPDrD.js +1 -0
- package/dist/assets/local-notifications-files-CWGvPHb8.js +1 -0
- package/dist/assets/local-share-grants-approvals-C89RIn08.js +1 -0
- package/dist/assets/local-vault-sessions-CGv9AsFj.js +1 -0
- package/dist/assets/main-BKK5N8Uh.css +1 -0
- package/dist/assets/main-BrkS-iow.js +2 -0
- package/dist/assets/merge-C8VYouYu.js +1 -0
- package/dist/assets/model-key-state-NiiWojtT.js +1 -0
- package/dist/assets/model-provider-B6oAnQX9.js +1 -0
- package/dist/assets/msalRedirect-CsZOSL-b.js +1 -0
- package/dist/assets/native-auth-return-BTXjvSvx.js +1 -0
- package/dist/assets/native-catalog-status-INsDvLpU.js +1 -0
- package/dist/assets/native-google-capability-BVj1mBPb.js +1 -0
- package/dist/assets/native-identity-admission-C4ZFillF.js +1 -0
- package/dist/assets/native-implicit-session-B9CuYTBA.js +1 -0
- package/dist/assets/native-oauth-http-BDqv664F.js +1 -0
- package/dist/assets/native-oauth-resource-runtime-D9u6_l-d.js +1 -0
- package/dist/assets/native-saml-DgVO7f2_.js +1 -0
- package/dist/assets/native-worker-bitwarden-native-contract-4175b124-DCuX5Y-I.js +1 -0
- package/dist/assets/native-worker-bitwarden-native-network-protocol-2ec12c2c-DdlqONg5.js +1 -0
- package/dist/assets/native-worker-bitwarden-native-worker-protocol-f491b626-C1Dz2Mxy.js +1 -0
- package/dist/assets/native-worker-bitwarden-worker-protocol-c9bedea4-CgZDhS6p.js +1 -0
- package/dist/assets/native-worker-bytes-a0e18d71-DFmKzL3P.js +1 -0
- package/dist/assets/native-worker-hash-wasm-9cbb16de-Bp4uJJy_.js +1 -0
- package/dist/assets/native-worker-levischuck-tiny-cbor-d8381e8f-BEl3rArG.js +1 -0
- package/dist/assets/native-worker-noble-ciphers-708367a7-BPuD3lXB.js +1 -0
- package/dist/assets/native-worker-noble-hashes-b1a58353-IgGIMWEC.js +1 -0
- package/dist/assets/native-worker-wasm-gzip-asset-47456844-DSWTIKdX.js +1 -0
- package/dist/assets/native-worker-zod-5c0ed887-B342B6ko.js +1 -0
- package/dist/assets/native-worker-zod-jitless-ba55e4a3-DZHC6DC7.js +1 -0
- package/dist/assets/nativeConnectorRedirect-Cac5chv5.js +1 -0
- package/dist/assets/nativeGoogleConsent-By04fGU0.js +1 -0
- package/dist/assets/nativeImplicitRedirect-CSQMi-YW.js +1 -0
- package/dist/assets/noble-crypto-Mv8l2A7D.js +1 -0
- package/dist/assets/notifications-CJoypYjy.css +1 -0
- package/dist/assets/notifications-DlWvurGh.js +1 -0
- package/dist/assets/onepassword-artifacts-DnlvryeZ.js +1 -0
- package/dist/assets/onepassword-sdk.worker-CcSZlR8e.js +1 -0
- package/dist/assets/os-logo-Dhy2KbxY.ttf +0 -0
- package/dist/assets/pane-trail-dW-2RSUm.js +1 -0
- package/dist/assets/password-workflows-Cmir8qky.js +1 -0
- package/dist/assets/payload-CVz3G9cA.js +1 -0
- package/dist/assets/peer-trust-CZzPSQ-X.js +1 -0
- package/dist/assets/plugin-activation-BLVTpDLX.css +1 -0
- package/dist/assets/plugin-activation-B_0fIk_I.js +1 -0
- package/dist/assets/portable-drop-CD_3kpqo.js +1 -0
- package/dist/assets/post-wire-DZbVz-_e.js +1 -0
- package/dist/assets/projection-read-9xClzF-E.js +1 -0
- package/dist/assets/react-dom-BwC4eQlG.js +1 -0
- package/dist/assets/react-router-XsJY84ug.js +1 -0
- package/dist/assets/reflect-metadata-DF0mcVP2.js +1 -0
- package/dist/assets/retired-owner-authentication-work-J-86Ved1.js +1 -0
- package/dist/assets/rotation-relay-DCS7Aa59.js +1 -0
- package/dist/assets/runtime-2tzejM54.js +1 -0
- package/dist/assets/runtime-BFa23LKn.css +1 -0
- package/dist/assets/runtime-BUihkTjL.js +1 -0
- package/dist/assets/runtime-BzHz3H7U.css +1 -0
- package/dist/assets/runtime-CXh-BOHA.js +1 -0
- package/dist/assets/runtime-CtH6kdhA.js +1 -0
- package/dist/assets/runtime-Dfzb5fxj.js +2 -0
- package/dist/assets/runtime-_4MyTTJ2.js +1 -0
- package/dist/assets/s3-CXe7JlAr.js +1 -0
- package/dist/assets/saved-model-agent-Cdn954wf.js +2 -0
- package/dist/assets/scroll-renderer-CPup0pR-.css +1 -0
- package/dist/assets/scroll-renderer-CPxIcBzQ.js +1 -0
- package/dist/assets/seams-DJ_lslby.js +1 -0
- package/dist/assets/secret-backend-onepassword-sdk-hhTb3tZb.js +1 -0
- package/dist/assets/secret-backends-_-CBukTJ.js +1 -0
- package/dist/assets/section-nav-goals-B_N-ZW2I.js +1 -0
- package/dist/assets/session-connections-WQ2L1zGG.js +2 -0
- package/dist/assets/session-connections-oSO_RMA1.css +1 -0
- package/dist/assets/settings-CHnpwTwf.css +1 -0
- package/dist/assets/settings-files-NL7VAn-D.css +1 -0
- package/dist/assets/settings-files-OnHfWPp_.js +1 -0
- package/dist/assets/sha3-Bm70HrE3.js +1 -0
- package/dist/assets/shared-Ck7e2FJN.js +1 -0
- package/dist/assets/signaling-BgALI1Na.js +1 -0
- package/dist/assets/signals-DdOHdr--.js +1 -0
- package/dist/assets/support-context-DrcseTKK.js +1 -0
- package/dist/assets/tailnet-devices-B4-KR7Lk.css +1 -0
- package/dist/assets/tailnet-devices-CRKI2IIc.js +1 -0
- package/dist/assets/tailnet-plugin-pairing-DTK4jAlP.js +1 -0
- package/dist/assets/tailscale-artifacts-FyY85j_Y.js +1 -0
- package/dist/assets/tailscale-node-Bxh73eIz.js +1 -0
- package/dist/assets/trusted-contacts-BUPioBSb.css +1 -0
- package/dist/assets/trusted-contacts-QkvTYGDn.js +1 -0
- package/dist/assets/types-Ctz6L20B.js +1 -0
- package/dist/assets/use-access-book-1e-Lb3_j.css +1 -0
- package/dist/assets/use-access-book-BusjdJX8.js +2 -0
- package/dist/assets/use-integrations-drawn-DYzpglrK.js +1 -0
- package/dist/assets/use-password-reset-generate-B11XaeM6.js +2 -0
- package/dist/assets/use-password-reset-generate-D7yK7QdU.css +1 -0
- package/dist/assets/use-settings-category-Ci1J38pa.css +1 -0
- package/dist/assets/use-settings-category-Dy0gsCtF.js +1 -0
- package/dist/assets/use-vault-search-C7u00nrc.js +1 -0
- package/dist/assets/use-vault-search-Cy48_tAA.css +1 -0
- package/dist/assets/useLocalConsent-LY9hCn8F.js +2 -0
- package/dist/assets/vault-credential-custody-DpnBb4qo.js +1 -0
- package/dist/assets/vault-list-path-Bh2_KZkq.js +1 -0
- package/dist/assets/vault-menu-CqO_AStq.js +1 -0
- package/dist/assets/vault-ui-seam-BQGS7RR6.js +1 -0
- package/dist/assets/vaults-B043odav.js +1 -0
- package/dist/assets/vendor-1password-save-bVqbF-cI.js +1 -0
- package/dist/assets/vendor-ag-ui-DapcFk1d.js +1 -0
- package/dist/assets/vendor-ai-sdk-D8TnA_ou.js +1 -0
- package/dist/assets/vendor-msal-D-SCQ_ve.js +1 -0
- package/dist/assets/wake-lock-C_y0fQco.js +1 -0
- package/dist/assets/webmcp-sdk-Brp7pH5M.js +1 -0
- package/dist/assets/website-pattern.worker-CHLdQLlR.js +1 -0
- package/dist/auth/linear.html +17 -0
- package/dist/auth/native-client.json +17 -0
- package/dist/auth/native-connector.html +17 -0
- package/dist/auth/native-google.html +29 -0
- package/dist/auth/native-implicit.html +18 -0
- package/dist/auth/redirect.html +15 -0
- package/dist/auth.js +1 -0
- package/dist/auth.js.sha384 +1 -0
- package/dist/browser-schema-config.js +5 -0
- package/dist/capability-distribution.json +108 -0
- package/dist/capability-graph.json +1 -0
- package/dist/contact.html +37 -0
- package/dist/icon-192.png +0 -0
- package/dist/icon-512.png +0 -0
- package/dist/icon.svg +1 -0
- package/dist/index.html +150 -0
- package/dist/index.md +22 -0
- package/dist/licenses/saml-xml.txt +315 -0
- package/dist/llms.txt +35 -0
- package/dist/manifest.webmanifest +1 -0
- package/dist/onepassword/LICENSE-0.5.0.txt +21 -0
- package/dist/onepassword/core-0.5.0-764c359d.mjs +822 -0
- package/dist/onepassword/core-0.5.0-7cc0e700.wasm.gz +0 -0
- package/dist/os-runtime-config.json +1 -0
- package/dist/privacy.html +39 -0
- package/dist/release.json +9 -0
- package/dist/robots.txt +4 -0
- package/dist/save-button.js +220 -0
- package/dist/security-profile.json +6 -0
- package/dist/siop-metadata.json +39 -0
- package/dist/sitemap.xml +9 -0
- package/dist/static-auth/1.0.3/opensesame-auth.min.js +1 -0
- package/dist/static-auth/1.0.3/opensesame-auth.min.js.sha384 +1 -0
- package/dist/static-auth/1.0.4/opensesame-auth.min.js +1 -0
- package/dist/static-auth/1.0.4/opensesame-auth.min.js.sha384 +1 -0
- package/dist/static-auth/1.0.5/opensesame-auth.min.js +1 -0
- package/dist/static-auth/1.0.5/opensesame-auth.min.js.sha384 +1 -0
- package/dist/static-auth/manifest.json +24 -0
- package/dist/sw-push.js +1 -0
- package/dist/sw.js +1 -0
- package/dist/tailscale/LICENSE.txt +86 -0
- package/dist/tailscale/OPEN-SOURCE-LICENSES.md +109 -0
- package/dist/tailscale/go-runtime-3e61b3267aa67a55.js +3 -0
- package/dist/tailscale/main-7b2a0868bcb7f638.wasm.gz +0 -0
- package/dist/tailscale/native-http-1992487ea59d7d17.js +1 -0
- package/package.json +26 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{G as e,N as t,c as r,d as n,e as i,v as o,f as s,g as a,h as c,s as d,i as l,j as u,k as p,l as h,a as f,m}from"./native-oauth-http-BDqv664F.js";import{o as w,a as g,s as v,l as y,_,r as b,u as k,n as I,v as S,f as C,a8 as T,e as x,a9 as $,aa as A,c as P,h as E,d as O,g as R,ab as M,ac as q,N as U,a6 as L,ad as j,w as z}from"./native-worker-zod-5c0ed887-B342B6ko.js";import{as as N,I as H,l as D,i as V,c as F}from"./vault-ui-seam-BQGS7RR6.js";import{a as W,Q as B,e as J,S as G,l as K}from"./certs-CDCfMuEi.js";import{c as Z}from"./connect-plan-ClXbb_FT.js";import{cI as Q,u as Y,v as X,q as ee}from"./drop-open-BjgdLxWM.js";import{m as te}from"./model-provider-B6oAnQX9.js";import{g as re}from"./commonjs-runtime-R6OqCcd0.js";import{r as ne,d as ie,u as oe,e as se,a as ae,s as ce}from"./bucket-saved-vQCiVvN_.js";import{J as de,x as le}from"./signals-DdOHdr--.js";import{s as ue,d as pe,r as he,a as fe,i as me}from"./vault-credential-custody-DpnBb4qo.js";import{_ as we}from"./hosted-model-authority-CcNPE44H.js";import{b as ge,g as ve}from"./native-worker-noble-hashes-b1a58353-IgGIMWEC.js";import{e as ye,f as _e,h as be,i as ke,j as Ie,k as Se,A as Ce,S as Te}from"./secret-backends-_-CBukTJ.js";const xe=N('{"schema_version":1,"audited_origin":"https://opensesame-labs.github.io","checked_date":"2026-10-12","dispositions":[{~2~"keychain",~3~,~8~"The operating system\'s keychain can be read only by native code on the machine that owns it. A web page has no API for it.",~7~[{"label":"fnox\'s keychain provider","url":"https://fnox.jdx.dev/providers/keychain.html"}]},{~2~"password-store",~3~,~8~"pass keeps GPG-encrypted files in a directory on your computer, and this catalog entry points at that directory. A browser page cannot read a directory by path or run GPG.",~7~[{"label":"pass, the standard Unix password manager","url":"https://www.passwordstore.org/"}]},{~2~"keepass",~3~,~8~"This catalog entry points at a KeePass database file by path. A browser page cannot open a path, but it can open a file you choose: Vault → Import reads a KeePass database into this vault as a local snapshot.",~7~[{"label":"KeePass help","url":"https://keepass.info/help/base/index.html"}],~5~{"label":"Open Vault to import a supported export",~9~}},{~2~"custom-command",~3~,~8~"This integration runs a command you name on the machine that holds the credential. A web page cannot start a process.",~7~[{"label":"fnox\'s providers","url":"https://fnox.jdx.dev/providers/overview.html"}]},{~2~"webcrypto",~4~,~8~"This vault already seals every item with WebCrypto keys that never leave this device, so there is nothing to connect.",~7~[{"label":"Web Crypto API","url":"https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API"}],~1~},{~2~"sealed-local",~4~,~8~"Your vault is a sealed local store: every item is encrypted on this device before it is written.",~7~[{~6~,~0~}],~5~{"label":"Open Settings › Vaults","to":"/settings/vaults"}},{~2~"fido2",~4~,~8~"A passkey or security key can seal this vault, so a FIDO2 key needs no integration here.",~7~[{"label":"FIDO Alliance specifications","url":"https://fidoalliance.org/specifications/"}],~1~},{~2~"vault-self",~4~,~8~"This vault generates its own authenticator codes, so there is nothing to connect.",~7~[{~6~,~0~}],~5~{"label":"Open the vault",~9~}},{~2~"plain","kind":"policy",~8~"OpenSesame never keeps secrets in the clear on this device, so it offers no plain-text store.",~7~[{"label":"Nothing the client stores rests in the clear (ADR 0149)",~0~}]}]}','"url":"https://github.com/OpenSesame-Labs/OpenSesame/blob/main/docs/adr/0149-nothing-stored-in-the-clear.md"\n"alternative":{"label":"Open Settings › Security","to":"/settings/security"}\n"provider_id":\n"kind":"companion"\n"kind":"built-in"\n"alternative":\n"label":"How OpenSesame stores things"\n"sources":\n"summary":\n"to":"/vault?f=all"'.split("\n")),$e="fnox.jdx.dev",Ae=/^(docs?|developers?|dev|learn|help|support|api|platform)\./;function Pe(e){try{return new URL(e)}catch{return null}}function Ee(e,t){const r=t?Pe(t):null;return t&&r&&"https:"===r.protocol?r.hostname===$e?{url:t,label:"fnox documentation",short:"fnox docs"}:function(e){return("/"===e.pathname||""===e.pathname)&&""===e.search&&""===e.hash&&!Ae.test(e.hostname)}(r)?{url:t,label:`${e} website`,short:"Website"}:{url:t,label:`${e} documentation`,short:"Docs"}:null}const Oe={"built-in":"Built in",companion:"Desktop app required","refuses-browser":"Provider blocks browsers","driver-pending":"Not built yet","runtime-inactive":"Connection not active","no-key-check":"No way to check a key","no-contract":"No browser connection",policy:"Not offered","needs-client-secret":"Needs a client secret","no-public-contract":"No public browser contract"},Re=["built-in","companion","refuses-browser","needs-client-secret","no-public-contract","no-key-check","runtime-inactive","driver-pending","no-contract","policy"];function Me(e){const t=e.filter(e=>void 0!==e);return Re.find(e=>t.includes(e))??t[0]??"no-contract"}const qe=w({label:v().min(1),url:v().url()}).strict(),Ue=w({provider_id:v().min(1),kind:_(["built-in","companion","refuses-browser","driver-pending","no-key-check","policy"]),summary:v().min(1),sources:g(qe),alternative:w({label:v().min(1),to:_(["/vault?f=all","/settings/security","/settings/vaults"])}).strict().optional()}).strict(),Le=w({schema_version:y(1),audited_origin:v().url(),checked_date:v(),dispositions:g(Ue)}).strict();let je=null;function ze(e){const t=W(e)??e;return(je??=Le.parse(JSON.parse(xe)),je).dispositions.find(e=>e.provider_id===t)}function Ne(e){if(H(e))return`${e.displayName} configuration is validated and sealed locally. No provider request or provider-access verification occurs.`;const t=`OpenSesame has no browser connection for ${e.displayName}.`;if("wallet"===e.category)return`${e.displayName} provisioning is unavailable under this product's wallet connection policy. This browser has no wallet driver and does not collect signing or issuer credentials.`;if(e.modelApi&&!e.modelApi.baseUrl)return`${t} Where its models are served depends on your account, so the catalog has no address to call.`;if("none"===e.egress.scheme){const n=B(e.id);return n&&(r=n,Pe(r)?.hostname===$e)?`${t} Its catalog entry is configuration for fnox's ${e.id} provider and names no HTTPS API a browser could call.`:`${t} Its catalog entry names no HTTPS API a browser could call.`}var r;return`${t} Its catalog entry names ${function(e){return e.egress.authorities.length?e.egress.authorities.join(", "):"an HTTPS API"}(e)} but defines no key check or verified operation for a browser to run, and no probe of that service from this site has been recorded.`}function He(e){const t=ze(e.id);return t?{kind:t.kind,summary:t.summary,sources:t.sources,alternative:t.alternative??null,authored:!0}:{kind:H(e)?"built-in":"wallet"===e.category?"policy":"no-contract",summary:Ne(e),sources:[],alternative:null,authored:!1}}function De(t,r){return"google-drive"!==t||null===r?null===r?null:[...r]:r.map(t=>{const r=Object.entries(e.aliases).find(([e])=>e===t);return r?.[1]??t})}function Ve(t,r){const n=De(t,r);return"google-drive"!==t||null===n||n.length===e.scopes.length&&e.scopes.every(e=>n.includes(e))}function Fe(e,t,r){return!e.includes("offline_access")||!0===t?.includes("offline_access")||void 0!==r}function We(e){return e.filter(e=>"offline_access"!==e)}function Be(e,t,r){return Ve(e,r)&&(null===r||function(e,t,r){const n=De(e,We(t))??[],i=De(e,r)??[];return n.every(e=>i.includes(e))}(e,t,r))}function Je(e,t,r,n,i){let o="configuration";return function(e,t){const r=t.pending.user,[n]=t.recovery;return"twitch"===e.providerId&&"oauth"===e.method&&1===Object.keys(t.pending).length&&!!r&&r.fingerprint===e.fingerprint&&r.expiresAt>Date.now()&&1===t.recovery.length&&n?.id===`oauth:${r.state}`&&n.fingerprint===r.fingerprint&&"revoke"===n.kind&&"device-poll"===n.credentials?.phase}(r,i)?o="authorizing":i.recovery.length>0?o="cleanup":function(e,t){return t.grants.some(t=>t.needsReauth||null!==t.expiresAt&&t.expiresAt<=Date.now()||"known"===t.permissionState&&!Be(e.providerId,e.requestedScopes[t.actor]??[],t.grantedScopes))}(r,n)?o="reauthorize":Object.keys(i.pending).length>0?o=Object.values(i.pending).some(e=>e.expiresAt<=Date.now())?"reauthorize":"authorizing":function(e,t,r){const n=r.verification;return!(null===t.verifiedAt||!n||n.fingerprint!==e.fingerprint||n.verifiedAt!==t.verifiedAt||!("native-local"===e.method?["browser-local","configuration"].includes(n.kind):"provider"===n.kind))&&(!["api-key","oauth","oidc"].includes(e.method)||0!==t.grants.length)&&Object.keys(r.grants).length===t.grants.length&&!Object.entries(e.requestedScopes).some(([e,r])=>r.length>0&&!t.grants.some(t=>t.actor===e))&&!!Object.values(e.targetIds).every(e=>t.targets.some(t=>t.id===e))&&t.grants.every(t=>{const n=r.grants[t.actor];return!!n&&n.providerId===e.providerId&&n.fingerprint===e.fingerprint&&n.actor===t.actor&&n.kind===e.method&&n.expiresAt===t.expiresAt&&("known"===t.permissionState||0===t.grantedScopes.length)&&(null===n.scopes?"known"!==t.permissionState:"known"!==t.permissionState||n.scopes.length===t.grantedScopes.length&&n.scopes.every(e=>t.grantedScopes.includes(e)))})}(r,n,i)&&(o="connected"),{providerId:r.providerId,connectionId:e,revision:t,fingerprint:r.fingerprint,configuration:structuredClone(r),status:o,identity:structuredClone(n.identity),targets:structuredClone(n.targets),grants:structuredClone(n.grants),verifiedAt:n.verifiedAt,recovery:i.recovery.map(e=>({id:e.id,kind:e.kind,label:"Provider cleanup required",detail:"Retry provider cleanup before changing or removing this connection."}))}}const Ge="native_configuration",Ke="native_runtime",Ze="native_revision",Qe="native_authority";function Ye(e){try{const t=r.parse(JSON.parse(e.row.fields[Ge]??"")),s=n.parse(JSON.parse(e.row.fields[Ke]??"")),a=i.parse(JSON.parse(e.secrets[Qe]??"")),c=o(t,a.classification),{privateState:d}=a;ot(d,a.classification);const l=Number(e.row.fields[Ze]);if(c.providerId!==e.row.providerId||!Number.isSafeInteger(l)||l<1)throw new Error("Invalid binding");const u={connectionId:e.row.connectionId,revision:l,configuration:c,runtime:s,privateState:d};return rt(u),u}catch{throw new Error("Saved native connector is invalid")}}function Xe(e){const t=ne().find(t=>t.connectionId===e);return t&&void 0!==t.fields[Ge]?Ye({row:t,secrets:ie()[e]??{}}):null}function et(e){const t=Xe(e);return t?tt(t):null}function tt(e){return Je(e.connectionId,e.revision,e.configuration,e.runtime,e.privateState)}function rt(e){const{configuration:t,privateState:r}=e;for(const[n,i]of[...Object.entries(r.grants),...Object.entries(r.pending)])if(i.providerId!==t.providerId||i.fingerprint!==t.fingerprint||i.actor!==n)throw new Error("Provider authorization belongs to another configuration");for(const n of Object.values(r.grants))nt(n);for(const n of r.recovery){if(n.providerId!==t.providerId)throw new Error("Provider cleanup belongs to another connector");it(n)}}function nt(e){if(!("mcp"!==e.kind||e.issuer&&e.resource&&e.endpoint&&e.clientId))throw new Error("MCP authorization is missing its audience binding")}function it(e){const t=e.grant;if(t&&(t.providerId!==e.providerId||t.actor!==e.actor||t.fingerprint!==e.fingerprint||t.targetId!==e.targetId))throw new Error("Provider cleanup grant does not match its target");if(t){nt(t);for(const r of["issuer","resource","endpoint","clientId"])if(void 0!==e[r]&&e[r]!==t[r])throw new Error("Provider cleanup grant does not match its audience")}}function ot(e,t){for(const r of Object.keys(e.credentials))if(!t.privateCredentials.includes(r))throw new Error("Unknown private provider credential slot")}function st(e,t,r){const i=o(e.configuration,t),a=n.parse(e.runtime),c=s.parse(e.privateState);return ot(c,t),rt({...e,configuration:i,privateState:c}),{row:{connectionId:e.connectionId,providerId:i.providerId,displayName:i.displayName,scopes:a.grants.flatMap(e=>e.grantedScopes),fields:{[Ge]:JSON.stringify(i),[Ke]:JSON.stringify(a),[Ze]:String(e.revision),self_hosted_configuration:"native-v1"},createdAt:r,updatedAt:(new Date).toISOString()},secrets:{[Qe]:JSON.stringify({privateState:c,classification:t})}}}async function at(e,t,r){const n={...e,revision:1};let i=null;if(await se(()=>{if(ne().some(t=>t.connectionId===e.connectionId))throw new Error("Connector already exists; use a guarded update");const r=st(n,t,(new Date).toISOString());return i=Ye(r),r},r),!i)throw new Error("Native connector was not committed");return tt(i)}function ct(e,t){if(e.revision!==t.revision||e.configuration.fingerprint!==t.fingerprint)throw new Error("Connector changed; reload before retrying")}async function dt(e,t){await oe(e,async e=>(ct(Ye(e),t),e))}async function lt(e,t,r,n,i,o){let s=null;if(await oe(e,async i=>{const a=Ye(i);ct(a,t);const c=n(structuredClone(a));if(c.connectionId!==e||c.configuration.providerId!==a.configuration.providerId||c.revision!==a.revision)throw new Error("A native update cannot replace its connector binding");!function(e,t){const r=e.runtime.identity,n=t.runtime.identity;if(t.privateState.verification&&e.configuration.fingerprint===t.configuration.fingerprint&&r&&n&&(r.id!==n.id||r.kind!==n.kind))throw new Error("Verified identity changed; replace the connector binding")}(a,c),function(e,t){const r=e=>Q({...e.configuration,displayName:"",icon:"",credentials:e.privateState.credentials,grants:e.privateState.grants});r(e)!==r(t)&&Q(e.privateState.verification)===Q(t.privateState.verification)&&(t.privateState.verification=null,t.runtime.verifiedAt=null,t.runtime.grants=t.runtime.grants.map(e=>({...e,needsReauth:!0})))}(a,c);const d=st({...c,revision:a.revision+1},r,i.row.createdAt);return s=Ye(d),o?.(),d},i),!s)throw new Error("Native connector update was not committed");return tt(s)}function ut(e){const t=e.privateState.grants.app;if("connected"!==Je(e.connectionId,e.revision,e.configuration,e.runtime,e.privateState).status||!t||"api-key"!==t.kind||t.accessToken!==e.privateState.credentials.api_key)throw new Error("Verify this provider connection before use")}function pt(e){if(e.privateState.recovery.length||Object.keys(e.privateState.pending).length)throw new Error("Finish provider authorization cleanup before verifying this connection")}const ht=N('{"schema_version":1,"audited_origin":"https://opensesame-labs.github.io","checked_date":"2026-10-09","qualification":"Unauthenticated TLS-verified OPTIONS and public metadata GET only, no account grant/proof. Errors and 5xx do not establish provider CORS refusal. Dynamic tenant and credential URLs are not guessed. New MCP rules apply only to the audited origin; another operator origin must complete actual metadata, registration, token and resource requests. Origin-specific response admission does not prove authenticated access.","rules":[{~3~"agentmail",~5~,~4~,~9~"AgentMail rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://docs.agentmail.to/knowledge-base/getting-api-key"]},{~3~"amazon-nova",~5~,~4~,~9~"Amazon Nova\'s CORS preflight admits this site, but its answer to the key check (HTTP 403) carries no Access-Control-Allow-Origin header, so a page cannot read that a key was refused. This method is unavailable under the current browser policy.",~1~["https://nova.amazon.com/dev/documentation"]},{~3~"arcee",~5~,~4~,~9~"Arcee does not admit this site to its API: the CORS preflight for its key check is answered HTTP 400 with no Access-Control-Allow-Origin header, so a page cannot call it. This method is unavailable under the current browser policy.",~1~["https://docs.arcee.ai","https://docs.arcee.ai/api-reference/models"]},{~3~"beehiiv",~5~,~4~,~9~"beehiiv rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://developers.beehiiv.com/welcome/create-an-api-key"]},{~3~"circleci",~5~,~4~,~9~"CircleCI rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://circleci.com/docs/guides/toolkit/managing-api-tokens/"]},{~3~"clerk",~5~,~4~,~9~"Clerk rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://clerk.com/docs/reference/backend-api"]},{~3~"cloudflare",~5~,~4~,~9~"Cloudflare rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~[~15~]},{~3~"crusoe",~5~,~4~,~9~"Crusoe\'s gateway refuses the browser before it routes: even the CORS preflight is answered HTTP 403 with no Access-Control-Allow-Origin header, so a page cannot reach its key check. This method is unavailable under the current browser policy.",~1~["https://docs.crusoecloud.com/managed-inference/overview","https://docs.crusoecloud.com/serverless-inference"]},{~3~~1a~,~5~,~6~{"site":"datadoghq.com"},~2~,~1~[~7~]},{~3~~1a~,~5~,~6~{"site":"us3.datadoghq.com"},~2~,~1~[~7~]},{~3~~1a~,~5~,~6~{"site":"us5.datadoghq.com"},~2~,~1~[~7~]},{~3~~1a~,~5~,~6~{"site":"datadoghq.eu"},~2~,~1~[~7~]},{~3~~1a~,~5~,~6~{"site":"ap1.datadoghq.com"},~2~,~1~[~7~]},{~3~~1a~,~5~,~6~{"site":"ap2.datadoghq.com"},~2~,~1~[~7~]},{~3~~1a~,~5~,~6~{"site":"uk1.datadoghq.com"},~2~,~1~[~7~]},{~3~~1a~,~5~,~6~{"site":"ddog-gov.com"},~2~,~1~[~7~]},{~3~~1a~,~5~,~6~{"site":"us2.ddog-gov.com"},~2~,~1~[~7~]},{~3~"deepgram",~5~,~4~,~9~"Deepgram rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://developers.deepgram.com/docs/create-additional-api-keys"]},{~3~"dovetail",~5~,~4~,~9~"Dovetail rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://developers.dovetail.com/docs/authorization"]},{~3~"edenai",~5~,~4~,~9~"Eden AI\'s CORS preflight admits this site, but its answer to the key check (HTTP 401) carries no Access-Control-Allow-Origin header, so a page cannot read that a key was refused. This method is unavailable under the current browser policy.",~1~["https://docs.edenai.co","https://www.edenai.co/docs/api-reference/files-management/list-files"]},{~3~"exa",~5~,~4~,~9~"Exa rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://exa.ai/docs/reference/getting-started"]},{~3~"fathom",~5~,~4~,~9~"Fathom rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://developers.fathom.ai/quickstart"]},{~3~"friendli",~5~,~4~,~9~"Friendli does not admit this site to its API: the CORS preflight for its key check is answered HTTP 400 with no Access-Control-Allow-Origin header, so a page cannot call it. This method is unavailable under the current browser policy.",~1~["https://friendli.ai/docs/guides/serverless_endpoints/introduction","https://friendli.ai/docs/openapi/dedicated/endpoint/list"]},{~3~"helicone",~5~,~4~,~9~"Helicone\'s API answers any request that carries an Origin header with HTTP 500, and its gateway sends no CORS headers, so a page cannot read its answers. This method is unavailable under the current browser policy.",~1~["https://helicone.ai/models","https://docs.helicone.ai/rest/prompts/get-v1prompt-2025-count"]},{~3~"hetzner",~5~,~4~,~9~"Hetzner\'s gateway refuses the browser before it routes: even the CORS preflight is answered HTTP 401 with no Access-Control-Allow-Origin header, so a page cannot reach its key check. This method is unavailable under the current browser policy.",~1~["https://experiments.hetzner.com/docs/inference","https://docs.hetzner.com/general/company-and-policy/experiments/inference/"]},{~3~"higgsfield",~5~,~4~,~9~"Higgsfield does not admit this site to its API: the CORS preflight for its key check is answered HTTP 400 with no Access-Control-Allow-Origin header, and its documentation says not to call the API from browser code. This method is unavailable under the current browser policy.",~1~["https://docs.higgsfield.ai/docs/authentication.md"]},{~3~"infisical",~5~,~4~,~9~"Infisical\'s cloud servers admit only their own web app\'s origin: a request from this site is answered with Access-Control-Allow-Origin set to https://app.infisical.com, so a page here cannot read the answer. This method is unavailable under the current browser policy.",~1~["https://infisical.com/docs/self-hosting/configuration/envars","https://infisical.com/docs/documentation/platform/identities/universal-auth"]},{~3~"io-net",~5~,~4~,~9~"IO.NET does not admit this site to its API: the CORS preflight for its key check is answered HTTP 400 with no Access-Control-Allow-Origin header, so a page cannot call it. This method is unavailable under the current browser policy.",~1~["https://io.net/docs/guides/intelligence/io-intelligence","https://io.net/docs/guides/intelligence/io-intelligence-apis"]},{~3~"jev",~5~,~4~,~9~"Jev rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://docs.typesafe.ai/api"]},{~3~"kernel",~5~,~4~,~9~"Kernel rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://www.kernel.sh/auth.md"]},{~3~"kilo",~5~,~4~,~9~"Kilo Gateway does not admit this site to its API: the CORS preflight for its key check is answered HTTP 204 with no Access-Control-Allow-Origin header, so a page cannot call it. This method is unavailable under the current browser policy.",~1~["https://kilo.ai","https://kilo.ai/docs/gateway/authentication"]},{~3~"lemma",~5~,~4~,~9~"Lemma rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://getlemma.com/docs/api-reference/authentication"]},{~3~"llmgateway",~5~,~4~,~9~"LLM Gateway does not admit this site to its API: the CORS preflight for its key check is answered HTTP 204 with no Access-Control-Allow-Origin header, so a page cannot call it. This method is unavailable under the current browser policy.",~1~["https://llmgateway.io/docs","https://docs.llmgateway.io/developers/devpass-usage"]},{~3~"modal",~5~,~4~,~9~"Modal does not admit this site to its API: the CORS preflight for its key check is answered HTTP 404 with no Access-Control-Allow-Origin header, so a page cannot call it. This method is unavailable under the current browser policy.",~1~["https://modal.com/docs/guide/endpoints","https://modal.com/docs/guide/endpoint-integrations"]},{~3~"neon",~5~,~4~,~9~"Neon rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://neon.com/docs/manage/api-keys"]},{~3~"npm",~5~,~4~,~9~"npm rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://docs.npmjs.com/creating-and-viewing-access-tokens"]},{~3~"nvidia",~5~,~4~,~9~"Nvidia does not admit this site to its API: the CORS preflight for its key check is answered HTTP 200 with no Access-Control-Allow-Origin header, so a page cannot call it. This method is unavailable under the current browser policy.",~1~["https://docs.api.nvidia.com/nim/"]},{~3~"ollama-cloud",~5~,~4~,~9~"Ollama Cloud does not admit this site to its API: the CORS preflight for its key check is answered HTTP 405 with no Access-Control-Allow-Origin header, so a page cannot call it. This method is unavailable under the current browser policy.",~1~["https://docs.ollama.com/cloud","https://docs.ollama.com/api/authentication"]},{~3~"plivo",~5~,~4~,~9~"Plivo\'s API answers a browser preflight from this site without any CORS header, so a page cannot read its answers. This method is unavailable under the current browser policy.",~1~["https://www.plivo.com/docs/messaging/api/overview"]},{~3~"railway",~5~,~6~{~18~"account"},~9~~a~,~1~[~11~]},{~3~"railway",~5~,~6~{~18~"workspace"},~9~~a~,~1~[~11~]},{~3~"railway",~5~,~6~{~18~"project"},~9~~a~,~1~[~11~]},{~3~"render",~5~,~4~,~9~"Render rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://render.com/docs/api"]},{~3~"replicate",~5~,~4~,~9~"Replicate documents that its API cannot be called directly from a browser. This API-key method is unavailable on a self-hosted page.",~1~["https://replicate.com/docs/reference/http#accounts.get","https://github.com/replicate/replicate-javascript"]},{~3~"resend",~5~,~4~,~9~"Resend rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~[~17~,~e~]},{~3~"resend",~8~"oauth",~4~,~9~"Resend\'s domain API rejected browser access. REST OAuth is unavailable under the current browser policy; choose MCP when offered.",~1~[~17~,~e~]},{~3~"sanity",~5~,~4~,~9~"Sanity rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://www.sanity.io/docs/content-lake/http-auth"]},{~3~"segment",~5~,~4~,~9~"Segment rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://docs.segmentapis.com/tag/Getting-Started"]},{~3~"sendgrid",~5~,~4~,~9~"SendGrid rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://www.twilio.com/docs/sendgrid/api-reference/api-key-permissions/retrieve-a-list-of-scopes-for-which-this-user-has-access","https://www.twilio.com/docs/sendgrid/for-developers/sending-email/cors"]},{~3~"stepfun",~5~,~4~,~9~"StepFun (Global)\'s gateway refuses the browser before it routes: even the CORS preflight is answered HTTP 401 with no Access-Control-Allow-Origin header, so a page cannot reach its key check. This method is unavailable under the current browser policy.",~1~["https://platform.stepfun.ai/docs/en/overview/concept","https://platform.stepfun.ai/docs/en/api-reference/accounts/get"]},{~3~"thinking-machines",~5~,~4~,~9~"Thinking Machines does not admit this site to its API: the CORS preflight for its key check is answered HTTP 405 with no Access-Control-Allow-Origin header, so a page cannot call it. This method is unavailable under the current browser policy.",~1~["https://tinker-docs.thinkingmachines.ai/tinker/compatible-apis/anthropic/","https://tinker-docs.thinkingmachines.ai/tinker/api-reference/restclient/"]},{~3~"typeform",~5~,~6~{"api_host":"api.typeform.com"},~9~~f~,~1~[~16~,~14~]},{~3~"typeform",~5~,~6~{"api_host":"api.eu.typeform.com"},~9~~f~,~1~[~16~,~14~]},{~3~"volcengine",~5~,~4~,~9~"Volcengine Ark\'s CORS preflight admits this site, but its answer to the key check (HTTP 401) carries no Access-Control-Allow-Origin header, so a page cannot read that a key was refused. This method is unavailable under the current browser policy.",~1~["https://www.volcengine.com/docs/82379/1330310","https://docs.volcengine.com/docs/ark/list-files-api"]},{~3~"webflow",~5~,~4~,~9~"Webflow rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://developers.webflow.com/data/reference/authentication/site-token"]},{~3~"cloudflare-origin-ca",~5~,~4~,~9~"Cloudflare Origin CA rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://developers.cloudflare.com/fundamentals/api/get-started/ca-keys/"]},{~3~"doppler",~5~,~4~,~9~"Doppler only allows this API request from docs.doppler.com. API-key verification is unavailable from a self-hosted page.",~1~["https://docs.doppler.com/reference/api"]},{~3~"postmark",~5~,~4~,~9~"Postmark rejected browser access to this API endpoint. This method is unavailable under the current browser policy.",~1~["https://postmarkapp.com/developer/api/overview"]},{~3~"airtable",~8~"mcp",~0~,~4~,~9~"Airtable MCP is unavailable from this site\'s origin.",~1~["https://vercel.com/connect/airtable","https://mcp.airtable.com/.well-known/oauth-protected-resource/mcp"]},{~3~"axiom",~8~"mcp",~0~,~4~,~9~"Axiom MCP is unavailable from this site\'s origin.",~1~["https://axiom.co/docs/console/intelligence/mcp-server","https://mcp.axiom.co/.well-known/oauth-protected-resource/mcp"]},{~3~"beehiiv",~8~"mcp",~0~,~4~,~9~"beehiiv MCP is unavailable from this site\'s origin.",~1~["https://developers.beehiiv.com/oauth2","https://mcp.beehiiv.com/.well-known/oauth-protected-resource/mcp"]},{~3~"better-stack",~8~"mcp",~0~,~4~,~9~"Better Stack MCP is unavailable from this site\'s origin.",~1~["https://betterstack.com/docs/getting-started/integrations/mcp/","https://betterstack.com/.well-known/oauth-authorization-server"]},{~3~"brex",~8~"mcp",~0~,~4~,~9~"Brex MCP is unavailable from this site\'s origin.",~1~["https://vercel.com/connect/brex","https://api.brex.com/.well-known/oauth-protected-resource/mcp"]},{~3~"checkly",~8~"mcp",~0~,~4~,~9~"Checkly MCP is unavailable from this site\'s origin.",~1~["https://www.checklyhq.com/docs/ai/mcp-server/","https://api.checklyhq.com/mcp"]},{~3~"cloudflare",~8~"mcp",~0~,~4~,~9~"Cloudflare MCP is unavailable from this site\'s origin.",~1~[~15~,"https://mcp.cloudflare.com/mcp"]},{~3~"cloudinary",~8~"mcp",~0~,~4~,~9~"Cloudinary MCP is unavailable from this site\'s origin.",~1~["https://vercel.com/connect/cloudinary","https://asset-management.mcp.cloudinary.com/sse"]},{~3~"common-room",~8~"mcp",~0~,~4~,~9~"Common Room MCP is unavailable from this site\'s origin.",~1~["https://commonroom.io","https://mcp.commonroom.io/mcp"]},{~3~"coupler-io",~8~"mcp",~0~,~4~,~9~"Coupler.io MCP is unavailable from this site\'s origin.",~1~["https://blog.coupler.io/how-to-use-coupler-mcp-server/","https://auth.coupler.io/.well-known/oauth-authorization-server"]},{~3~"fireflies",~8~"mcp",~0~,~4~,~9~"Fireflies MCP is unavailable from this site\'s origin.",~1~["https://fireflies.ai","https://api.fireflies.ai/.well-known/oauth-protected-resource/mcp"]},{~3~"honeycomb",~8~"mcp",~0~,~4~,~9~"Honeycomb MCP is unavailable from this site\'s origin.",~1~["https://docs.honeycomb.io/integrations/mcp/configuration-guide","https://mcp.honeycomb.io/mcp"]},{~3~"indeed",~8~"mcp",~0~,~4~,~9~"Indeed MCP is unavailable from this site\'s origin.",~1~["https://indeed.com","https://mcp.indeed.com/claude/mcp"]},{~3~"intuit-mailchimp",~8~"mcp",~0~,~4~,~9~"Intuit Mailchimp MCP is unavailable from this site\'s origin.",~1~["https://mailchimp.com","https://ai-inc.mailchimp.com/claude/mcp/v2"]},{~3~"lovable",~8~"mcp",~0~,~4~,~9~"Lovable MCP is unavailable from this site\'s origin.",~1~["https://lovable.dev","https://api.lovable.dev/.well-known/oauth-protected-resource"]},{~3~"manufact",~8~"mcp",~0~,~4~,~9~"Manufact MCP is unavailable from this site\'s origin.",~1~["https://vercel.com/connect/manufact","https://cloud.manufact.com/.well-known/oauth-authorization-server/api/auth"]},{~3~"new-relic",~8~"mcp",~0~,~4~,~9~"New Relic MCP is unavailable from this site\'s origin.",~1~["https://docs.newrelic.com/docs/agentic-ai/mcp/setup/","https://oauth2.service.newrelic.com/.well-known/oauth-authorization-server"]},{~3~"otter-ai",~8~"mcp",~0~,~4~,~9~"Otter.ai MCP is unavailable from this site\'s origin.",~1~["https://otter.ai","https://otter.ai/.well-known/oauth-authorization-server"]},{~3~"pendo",~8~"mcp",~0~,~4~,~9~"Pendo MCP is unavailable from this site\'s origin.",~1~["https://pendo.io","https://app.pendo.io/.well-known/oauth-protected-resource/mcp/v0/shttp"]},{~3~"posthog",~8~"mcp",~0~,~4~,~9~"PostHog MCP is unavailable from this site\'s origin.",~1~["https://vercel.com/connect/posthog","https://mcp.posthog.com/.well-known/oauth-protected-resource/mcp"]},{~3~"pylon",~8~"mcp",~0~,~4~,~9~"Pylon MCP is unavailable from this site\'s origin.",~1~["https://support.usepylon.com/articles/2407390554-connecting-to-the-pylon-mcp-server","https://mcp.usepylon.com/.well-known/oauth-protected-resource"]},{~3~"quicknode",~8~"mcp",~0~,~4~,~9~"Quicknode MCP is unavailable from this site\'s origin.",~1~["https://www.quicknode.com/docs/build-with-ai/quicknode-mcp","https://mcp.quicknode.com/mcp"]},{~3~"read-ai",~8~"mcp",~0~,~4~,~9~"Read AI MCP is unavailable from this site\'s origin.",~1~["https://support.read.ai/hc/en-us/articles/49381158409491-MCP-Server","https://api.read.ai/.well-known/oauth-protected-resource/mcp"]},{~3~"readwise",~8~"mcp",~0~,~4~,~9~"Readwise MCP is unavailable from this site\'s origin.",~1~["https://readwise.io","https://mcp2.readwise.io/mcp"]},{~3~"resend",~8~"mcp",~0~,~4~,~9~"Resend MCP is unavailable from this site\'s origin.",~1~[~e~,"https://mcp.resend.com/.well-known/oauth-protected-resource"]},{~3~"sentry",~8~"mcp",~0~,~4~,~9~"Sentry MCP is unavailable from this site\'s origin.",~1~["https://docs.sentry.io/api/auth/","https://mcp.sentry.dev/mcp"]},{~3~"streak",~8~"mcp",~0~,~4~,~9~"Streak MCP is unavailable from this site\'s origin.",~1~["https://support.streak.com/en/articles/13931874-integrating-streak-with-gemini-claude-chatgpt-and-other-ai-tools","https://api.streak.com/mcp"]},{~3~"superhuman-mail",~8~"mcp",~0~,~4~,~9~"Superhuman Mail MCP is unavailable from this site\'s origin.",~1~["https://superhuman.com","https://mcp.mail.superhuman.com/mcp"]},{~3~"ticktick",~8~"mcp",~0~,~4~,~9~"TickTick MCP is unavailable from this site\'s origin.",~1~["https://vercel.com/connect/ticktick","https://mcp.ticktick.com/.well-known/oauth-protected-resource"]},{~3~"todoist",~8~"mcp",~0~,~4~,~9~"Todoist MCP is unavailable from this site\'s origin.",~1~["https://vercel.com/connect/todoist","https://ai.todoist.net/.well-known/oauth-protected-resource/mcp"]},{~3~"webflow",~8~"mcp",~0~,~4~,~9~"Webflow MCP is unavailable from this site\'s origin.",~1~["https://developers.webflow.com/data/reference/oauth-app","https://mcp.webflow.com/mcp"]},{~3~"whimsical",~8~"mcp",~0~,~4~,~9~"Whimsical MCP is unavailable from this site\'s origin.",~1~["https://whimsical.com/learn/integrations/mcp","https://mcp.whimsical.com/.well-known/oauth-protected-resource"]},{~3~"zapier",~8~"mcp",~0~,~4~,~9~"Zapier MCP is unavailable from this site\'s origin.",~1~["https://vercel.com/connect/zapier","https://mcp.zapier.com/api/v1/connect"]},{~3~"zernio",~8~"mcp",~0~,~4~,~9~"Zernio MCP is unavailable from this site\'s origin.",~1~["https://docs.zernio.com","https://mcp.zernio.com/mcp"]},{~3~"adobe",~8~"mcp",~0~,~4~,~9~"Adobe MCP does not admit the required protocol header from this site\'s origin.",~1~["https://adobe.io","https://express-mcp-service.adobe.io/mcp",~b~]},{~3~"local-falcon",~8~"mcp",~0~,~4~,~9~"Local Falcon MCP does not admit the required protocol header from this site\'s origin.",~1~["https://vercel.com/connect/local-falcon","https://mcp.localfalcon.com",~b~]},{~3~"sanity",~8~"mcp",~0~,~4~,~9~"Sanity MCP does not admit the required protocol header from this site\'s origin.",~1~["https://www.sanity.io/docs/oauth2","https://mcp.sanity.io",~b~]},{~3~"tailscale",~5~,~4~,~9~"Tailscale\'s cloud API answers no Access-Control-Allow-Origin header to this site, so a page here cannot read the answer. Use the connector bridge.",~1~["https://tailscale.com/api"]},{~3~~1b~,~5~,~4~,~9~"Bitwarden\'s identity and API servers answer no Access-Control-Allow-Origin header to this site, so a page here cannot read the answer. Use the connector bridge.",~1~[~d~]},{~3~~1b~,~5~,~4~,~9~~13~,~1~[~d~]},{~3~~1b~,~5~,~4~,~9~~10~,~1~[~d~]},{~3~~1b~,~5~,~4~,~9~~12~,~1~[~d~]},{~3~~19~,~5~,~4~,~9~"Bitwarden\'s identity server answers no Access-Control-Allow-Origin header to this site.",~1~[~c~]},{~3~~19~,~5~,~4~,~9~~13~,~1~[~c~]},{~3~~19~,~5~,~4~,~9~~10~,~1~[~c~]},{~3~~19~,~5~,~4~,~9~~12~,~1~[~c~]}]}','"origins":["https://opensesame-labs.github.io"]\n"evidence_urls":\n"reason":"Datadog rejected browser access to this API endpoint. This method is unavailable under the current browser policy."\n"provider_id":\n"parameters":{}\n"method":"api-key"\n"parameters":\n"https://docs.datadoghq.com/api/latest/authentication/"\n"method":\n"reason":\n"Railway only allows this API request from railway.com. API-key verification is unavailable from a self-hosted page."\n"https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#protocol-version-header"\n"https://bitwarden.com/help/secrets-manager-overview/"\n"https://bitwarden.com/help/bitwarden-apis/"\n"https://resend.com/docs/guides/building-a-resend-oauth-client"\n"Typeform does not allow direct browser requests to its API. This API-key method is unavailable on a self-hosted page."\n"Bitwarden EU\'s identity server answers no Access-Control-Allow-Origin header to this site."\n"https://docs.railway.com/reference/public-api"\n"Bitwarden EU\'s API server answers no Access-Control-Allow-Origin header to this site."\n"Bitwarden\'s API server answers no Access-Control-Allow-Origin header to this site."\n"https://community.typeform.com/typeform-developers-44/help-needed-cors-policy-5899"\n"https://developers.cloudflare.com/fundamentals/api/get-started/create-token/"\n"https://www.typeform.com/developers/get-started/personal-access-token/"\n"https://resend.com/docs/api-reference/domains/list-domains"\n"credential_variant":\n"bitwarden-sm"\n"datadog"\n"bitwarden"'.split("\n"));function ft(e,t){if(!e.supportsNativeOrigin)return!1;try{e.assertCurrent(),e.signal?.throwIfAborted();for(const r of t){const t=new URL(r);if("https:"!==t.protocol||t.username||t.password||t.hash||!0!==e.supportsNativeOrigin(t.origin))return!1;e.assertCurrent(),e.signal?.throwIfAborted()}return!0}catch{return!1}}const mt=w({provider_id:v(),method:_(["api-key","oauth","mcp","oidc"]),origins:g(v().url()).min(1).optional(),parameters:b(v(),v()),reason:v().min(1),evidence_urls:g(v().url()).min(1)}),wt=w({schema_version:y(1),audited_origin:v().url(),checked_date:v(),qualification:v(),rules:g(mt)}).parse(JSON.parse(ht)),gt=[];function vt(e){const t={origin:e};return gt.push(t),()=>{const e=gt.indexOf(t);e>=0&>.splice(e,1)}}const yt={available:!0,reason:null,evidenceUrls:[]};function _t(e,t,r={},n){const i="api-key"===t?function(e,t){const r=Z(e)?.methods.find(e=>"api-key"===e.kind);if("api-key"!==r?.kind||!r.preset)return t;const n=r.preset,i=t.credential_variant??n.credentialVariants[0]?.id,o=n.credentialVariants.find(e=>e.id===i)??n,s={...t};i&&(s.credential_variant=i);for(const a of o.templateParams)!a.secret&&a.choices?.length&&(s[a.name]=t[a.name]?.trim()||a.choices[0].value);return s}(e,r):r,o=wt.rules.find(r=>r.provider_id===e&&r.method===t&&(!r.origins||r.origins.includes(gt.at(-1)?.origin()??wt.audited_origin))&&Object.entries(r.parameters).every(([e,t])=>i[e]===t));return o?"oauth"!==t&&"mcp"!==t||!function(e,t){return!!t&&("tokenEndpoint"in t?function(e){return!!e&&ft(e.transport,[e.tokenEndpoint,e.resourceEndpoint])}(t):"mcp"===e&&function(e){return!!e&&ft(e.transport,[e.resourceEndpoint])}(t))}(t,n)?"api-key"===t?{available:!0,reason:null,advice:`The ${wt.checked_date} probe from ${wt.audited_origin} did not allow browser access to this provider's hosted endpoint. Test the connection using the configured native Tailscale HTTP transport. For direct browser requests, the endpoint must permit this site's origin and required headers.`,evidenceUrls:[...o.evidence_urls]}:{available:!1,reason:o.reason,evidenceUrls:[...o.evidence_urls]}:yt:"api-key"===t?function(e){const t=function(e){return ze(e)}(e);return"refuses-browser"!==t?.kind?yt:{available:!0,reason:null,advice:"Published evidence reports browser access restrictions at this provider's hosted endpoint. Test the connection using the configured native Tailscale HTTP transport. For direct browser requests, the endpoint must permit this site's origin and required headers.",evidenceUrls:t.sources.map(e=>e.url)}}(e):yt}function bt(e,t={}){return _t(e,"api-key",t)}function kt(e,t){return _t(e,"mcp",{},t)}function It(e,t){const r=kt(e,t);if(!r.available)throw new Error(r.reason??"Browser MCP is unavailable")}function St(e){const r=Xe(e);if(!r||!["oauth","oidc","mcp"].includes(r.configuration.method))throw new t("callback");return r}function Ct(e){return{revision:e.revision,fingerprint:e.configuration.fingerprint}}const Tt=new Map,xt=new Set;function $t(e,t){return xt.has(`${e}:${t}`)}function At(e,r){const n=`${e}:${r}`;if(xt.has(n))throw new t("callback");return xt.add(n),()=>{xt.delete(n)}}function Pt(e,t){const r=Tt.get(e);r?.delete(t),0===r?.size&&Tt.delete(e)}async function Et(e){const t=Tt.get(e);if(t)for(const[r,n]of[...t])await Lt(e,r,n.grant,n.classification,n.extra,n.rotation)}function Ot(e){const r=new URLSearchParams(e),n=r.get("native_state"),i=r.get("native_code"),o=r.has("native_error");if(!n||n.length<16||n.length>512||!!i===o||(i?.length??0)>4096)throw new t("callback");for(const s of["native_state","native_code","native_error"])if(r.getAll(s).length>1)throw new t("callback");return{state:n,code:i,error:o}}function Rt(e){let r=null;for(const n of ne()){const i=Xe(n.connectionId);if(i)for(const n of Object.values(i.privateState.pending))if(n.state===e){if(r)throw new t("callback");r={record:i,pending:n}}}return r}function Mt(e){const t=Rt(Ot(e).state);return t?{connectionId:t.record.connectionId,providerId:t.pending.providerId,method:t.record.configuration.method,actor:t.pending.actor}:null}function qt(e,t){const r={phase:"exchange",deadline:String(Date.now()+6e4),identity_id:t??""};return{id:`oauth:${e.state}`,kind:["databricks","discord"].includes(e.providerId)?"revoke":"configure",providerId:e.providerId,actor:e.actor,fingerprint:e.fingerprint,targetId:e.targetId??e.providerId,issuer:e.issuer,resource:e.resource,endpoint:e.endpoint,clientId:e.clientId,credentials:r}}async function Ut(e,r,n){const i=Ot(e),o=Rt(i.state);if(!o)throw new t("callback");const{record:s,pending:a}=o,c=a.expiresAt<=Date.now()||a.fingerprint!==s.configuration.fingerprint,d=qt(a,s.runtime.identity?.id);if(n?.(d),"databricks"===a.providerId&&(d.credentials={...d.credentials,integration_id:s.configuration.parameters.integration_id??""}),await lt(s.connectionId,Ct(s),r,e=>{const r=e.privateState.pending[a.actor];if(r?.state!==a.state)throw new t("callback");return delete e.privateState.pending[a.actor],i.error||c||e.privateState.recovery.push(d),e.privateState.verification=null,e}),c)throw new t("expired");if(i.error||!i.code)throw new t("denied");return{record:St(s.connectionId),pending:a,obligation:d,code:i.code}}async function Lt(e,r,n,i,o={},s=!1){const a=Tt.get(e)??new Map;if(a.size>=64&&!a.has(r))throw new t("storage");a.set(r,{grant:structuredClone(n),extra:{...o},classification:i,rotation:s}),Tt.set(e,a);const c=St(e);await lt(e,Ct(c),i(c.configuration),e=>{const i=e.privateState.recovery.find(e=>e.id===r);if(!i||i.fingerprint!==n.fingerprint||i.grant&&"refresh"!==i.credentials?.phase&&!s)throw new t("storage");return s&&i.grant&&function(e,r){for(const n of["providerId","actor","fingerprint","kind","targetId","issuer","resource","endpoint","clientId"])if(e[n]!==r[n])throw new t("storage")}(i.grant,n),s||"refresh"!==i.credentials?.phase||(delete e.privateState.grants[n.actor],e.runtime.grants=e.runtime.grants.filter(e=>e.actor!==n.actor)),i.grant={...n,targetId:i.targetId},i.credentials={...i.credentials,...o,phase:s?i.credentials?.phase??"verify":"verify"},e}),Pt(e,r)}function jt(e,t,r,n){const i=Tt.get(e)??new Map;i.set(t,{grant:structuredClone(r),extra:{},classification:n,rotation:!0}),Tt.set(e,i)}function zt(e,t){const r=JSON.stringify(e.privateCredentials.map(e=>t[e]??""));return ge(ve((new TextEncoder).encode(r)))}function Nt(e,t,r=!1){const n=Xe(t);if(!n||!e.accepts(n.configuration.providerId)||"api-key"!==n.configuration.method)throw new Error(`Saved ${e.family} browser connection not found`);if(pt(n),r&&("connected"!==Je(t,n.revision,n.configuration,n.runtime,n.privateState).status||n.privateState.grants.app?.accessToken!==zt(e.classification,n.privateState.credentials)))throw new Error(`Verify ${e.family} access before use`);return n}function Ht(e,t,r,n,i,o,s=0){const c=Math.max(Date.now(),s+1),d=a();return d.credentials=i,d.grants.app={kind:"api-key",providerId:n.providerId,actor:"app",fingerprint:n.fingerprint,targetId:o.target.id,accessToken:zt(e,i),expiresAt:null,scopes:null},d.verification={fingerprint:n.fingerprint,verifiedAt:c,kind:"provider"},{connectionId:t,revision:r,configuration:n,privateState:d,runtime:{verifiedAt:c,identity:{...o.identity,assurance:"credential-valid"},targets:[...o.targets],grants:[{actor:"app",label:o.grantLabel,permissionState:"provider-managed",grantedScopes:[],expiresAt:null,needsReauth:!1}]}}}function Dt(e,t,r){return lt(t.connectionId,Ct(t),e,e=>(r.assertCurrent(),e.privateState.verification=null,e),()=>r.assertCurrent())}function Vt(e){const t=t=>e.accepts(t.providerId)&&"api-key"===t.method;return{credentialSlots:e.classification.privateCredentials,classification:r=>{if(!t(r))throw new Error(`${e.family} cleanup belongs to its saved browser connection`);return e.classification},cleanup:async(r,n)=>{const i=r.grant;if(!t(n.configuration)||r.providerId!==n.configuration.providerId||"revoke"!==r.kind||r.fingerprint!==n.configuration.fingerprint||!i||"api-key"!==i.kind||i.actor!==r.actor||i.providerId!==r.providerId||i.fingerprint!==r.fingerprint||i.targetId!==r.targetId)throw new Error(`${e.family} cleanup changed; reload the saved browser connection`);return"local-credential-forgotten"}}}function Ft(e){return["authorization","permission"].includes(e.code)}async function Wt(e,t,r,n,i){n.assertCurrent();const{saved:o,target:s}=await async function(e,t,r){const n=Nt(e.spec,t,r);await dt(t,Ct(n));const i=e.spec.targetOf(n);if(n.configuration.fingerprint!==await e.spec.fingerprint(i))throw new Error(`${e.spec.family} binding changed; configure again`);return{saved:n,target:i}}(e,t,r);n.assertCurrent();try{const e=await i(s);return n.assertCurrent(),await dt(t,Ct(o)),n.assertCurrent(),{saved:o,value:e}}catch(a){throw a instanceof c&&e.refused(a)&&await Dt(e.spec.classification,o,n),a}}function Bt(e){const t=function(e){return{spec:e,refused:e.refused??Ft}}(e);return{family:e.family,accepts:e.accepts,ui:e.ui,configure:(e,r=Y())=>async function(e,t,r){const{spec:n}=e,i=n.classification;r.assertCurrent();const o=t.connectionId?Nt(n,t.connectionId):null;!function(e,t,r){const{family:n,accepts:i}=e.spec;if(!i(r.providerId))throw new Error(`${r.providerId} is not a ${n} service`);if(t&&t.revision!==r.revision)throw new Error(`${n} connection changed; reload before saving`);if(t&&t.configuration.providerId!==r.providerId)throw new Error(`Saved connection belongs to another ${n} service`);if(!r.displayName.trim()||r.displayName.trim().length>256)throw new Error(`Enter a valid ${n} connection name`)}(e,o,t);const s=await n.parse(t,o);o&&await dt(o.connectionId,Ct(o));const a=await n.fingerprint(s),d=await async function(e,t,r,n,i){try{return await e.spec.prove(t,i)}catch(o){const s=e.spec.classification;throw o instanceof c&&e.refused(o)&&r&&r.configuration.fingerprint===n&&zt(s,r.privateState.credentials)===zt(s,t.credentials)&&await Dt(s,r,i),o}}(e,s,o,a,r);r.assertCurrent();const l=o?.connectionId??`${n.idPrefix}${crypto.randomUUID()}`,u=Ht(i,l,o?.revision??1,{version:1,providerId:s.providerId,method:"api-key",displayName:t.displayName.trim(),icon:t.icon??"",parameters:{...s.parameters,...d.update?.parameters},requestedScopes:{},targetIds:{[d.target.key]:d.target.id},fingerprint:a},{...s.credentials,...d.update?.credentials},d,o?.runtime.verifiedAt??0);return o?lt(l,Ct(o),i,()=>(r.assertCurrent(),u),()=>r.assertCurrent()):at(u,i,()=>r.assertCurrent())}(t,e,r),verify:(e,r=Y())=>async function(e,t,r){const n=e.spec.classification,{saved:i,value:o}=await Wt(e,t,!1,r,t=>e.spec.prove(t,r));return lt(t,Ct(i),n,()=>(r.assertCurrent(),Ht(n,t,i.revision,{...i.configuration,parameters:{...i.configuration.parameters,...o.update?.parameters}},{...i.privateState.credentials,...o.update?.credentials},o,i.runtime.verifiedAt??0)),()=>r.assertCurrent())}(t,e,r),invoke:(e,r,n={},i=Y())=>async function(e,t,r,n,i){const o=function(e,t,r){const n=()=>new Error(`Select a supported ${e.spec.family} operation`);if("provider.read"===t){if(Object.keys(r).length)throw n();return null}const i=e.spec.operations.find(e=>e.id===t),o=Object.keys(r);if(!i||o.length!==i.inputKeys.length||!i.inputKeys.every(e=>o.includes(e)))throw n();return i}(e,r,n);if(!o){const{saved:r}=await Wt(e,t,!0,i,t=>e.spec.prove(t,i));return i.assertCurrent(),{label:`${e.spec.ui(r.configuration.providerId).name} access verified`,items:[]}}const{value:s}=await Wt(e,t,!0,i,e=>o.run(e,i,n));return i.assertCurrent(),s}(t,e,r,n,i),cleanup:Vt(e)}}const Jt=["vault_url"],Gt=["token"],Kt=e=>"azure-sm"===W(e);function Zt(e,t){!function(e){if(!Kt(e.providerId)||Object.keys(e.requestedScopes??{}).length||Object.keys(e.targetIds??{}).length||Object.keys(e.parameters).some(e=>!Jt.includes(e))||Object.keys(e.credentials).some(e=>!Gt.includes(e)))throw new Error("Configure only a vault URL and its Key Vault access token")}(e);const r=ye(e.parameters.vault_url??"").origin,n=e.credentials.token??"";if(!n&&t&&t.configuration.parameters.vault_url!==r)throw new Error("Supply an access token when changing the vault URL");const i=n||t?.privateState.credentials.token||"";if(!/^[\x21-\x7e]{1,16384}$/.test(i))throw new Error("Supply a Key Vault audience Bearer access token");const o={token:i};return d(r,o),d(e.displayName,o),l(e.icon??"",o),{providerId:e.providerId,parameters:{vault_url:r},credentials:o}}async function Qt(e,t,r,n=!1){t.assertCurrent();const i=ye(e.parameters.vault_url??""),o=new URL(r,i);o.searchParams.set("api-version",Ce),n&&o.searchParams.set("maxresults","25");const s={url:o,method:"GET",headers:new Headers({Authorization:`Bearer ${e.credentials.token}`,Accept:"application/json"})};return t.signal&&(s.signal=t.signal),u(s,t)}async function Yt(e,t){const r=ye(e.parameters.vault_url??""),n=_e(await Qt(e,t,"/secrets",!0),r);if(n.next&&be(n.next,r),new Set(n.items.map(e=>e.id)).size!==n.items.length)throw new c("response");const i=n.items.map(t=>({id:t.id,label:d(t.name,e.credentials)}));return{label:`Showing ${i.length} secret names from first page`,items:i}}const Xt=Bt({family:"Azure Key Vault Secrets",idPrefix:"conn_azure_secrets_",accepts:Kt,classification:{publicParameters:Jt,privateCredentials:Gt},ui:function(){return{name:"Azure Key Vault Secrets",methodLabel:"Key Vault access token",instructions:"Supply your vault URL and an issued Bearer access token for the Key Vault audience https://vault.azure.net. Verify and connect checks secret list access in that vault; reading values also requires get permission. Encrypted backups require set and get. Optional logical-secret deletion requires delete permission and removes the whole version chain under the vault soft-delete policy; this integration never purges secrets. Writes create a new immutable version. Microsoft Graph tokens are not used. Requests use the configured native transport; no application server is required. Replace an expired token here.",fields:[{id:"vault_url",label:"Vault URL",kind:"url",secret:!1,required:!0,placeholder:"https://my-vault.vault.azure.net"},{id:"token",label:"Key Vault access token",kind:"text",secret:!0,required:!0}],links:[{label:"Key Vault secret permissions",url:"https://learn.microsoft.com/en-us/azure/key-vault/secrets/about-secrets"}],disconnectExplanation:"Disconnect forgets this device's token. It does not revoke the Azure token or change your vault.",actions:[{id:"provider.secrets.read",label:"List secret names",fields:[]},{id:"provider.secret.read",label:"Read a secret",fields:[{id:"name",label:"Secret name or versioned ID",kind:"text",secret:!1,required:!0}]}]}},parse:Zt,fingerprint:async e=>{const t=(new TextEncoder).encode(Q({contract:"azure-secrets:list-get:v1",parameters:e.parameters,credentials:e.credentials}));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",t))].map(e=>e.toString(16).padStart(2,"0")).join("")},prove:async(e,t)=>{await Yt(e,t);const r=e.parameters.vault_url??"";return{identity:{id:r,label:new URL(r).hostname,kind:"vault"},targets:[{id:r,label:r,kind:"vault"}],grantLabel:"Azure Key Vault secret list access",target:{key:"vault_url",id:r}}},targetOf:e=>Zt({providerId:e.configuration.providerId,displayName:e.configuration.displayName,icon:e.configuration.icon,parameters:e.configuration.parameters,credentials:e.privateState.credentials},e),operations:[{id:"provider.secrets.read",inputKeys:[],run:Yt},{id:"provider.secret.read",inputKeys:["name"],run:(e,t,r)=>async function(e,t,r){const n=ye(e.parameters.vault_url??""),i=ke(r,n),o=Ie(await Qt(e,t,Se(i)),n,i),s=e.credentials.token??"";if(o.value.includes(s)||o.value.includes(encodeURIComponent(s)))throw new c("response");return{label:"Secret read once",items:[{id:i.id,label:i.name,secretValue:o.value}]}}(e,t,r.name??"")}]});class er extends Error{constructor(e,t=0,r){super("arguments"===e&&"json-object"===r?"Enter valid JSON object arguments for this tool.":{target:"The MCP destination does not match this connector.",authorization:"Authorize this connector again before using its tools.",permission:"The MCP server refused this operation.","browser-transport":"The browser could not reach this MCP server. Check the connection and whether the server permits this app origin.",response:"The MCP server returned an invalid or oversized response.",tool:"Select a tool advertised by this MCP server.",arguments:"Enter arguments that match this tool’s advertised input schema.","schema-limits":"This tool’s schema exceeds browser safety limits. Ask the MCP provider for a simpler schema or smaller arguments.",disposed:"This connector session has ended. Connect again."}[e]),this.code=e,this.status=t}code;status;name="NativeMcpError"}function tr(e){let t;try{t=new URL(e)}catch{throw new er("target")}if("https:"!==t.protocol||t.username||t.password||t.hash)throw new er("target");return t}function rr(e){const t=tr(e.endpoint),r=tr(e.resource);if(!e.providerId||!e.fingerprint)throw new er("target");const n=r.pathname.replace(/\/$/,"");if(t.origin!==r.origin||t.pathname!==n&&!t.pathname.startsWith(`${n}/`))throw new er("target");if(e.issuer&&tr(e.issuer),e.ssePostEndpoint){const r=tr(e.ssePostEndpoint);if("sse"!==e.transport||r.origin!==t.origin)throw new er("target")}}function nr(e,t,r){if(t.href!==tr(e.endpoint).href||!["GET","POST","DELETE"].includes(r)){if("sse"===e.transport&&e.ssePostEndpoint&&"POST"===r){const r=tr(e.ssePostEndpoint),n=[...t.searchParams.keys()];if(t.origin===r.origin&&t.pathname===r.pathname&&n.every(e=>"sessionId"===e)&&n.length<=1)return}throw new er("target")}}const ir="2025-11-25",or=[ir,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],sr="io.modelcontextprotocol/related-task",ar="2.0",cr=R(e=>null!==e&&("object"==typeof e||"function"==typeof e)),dr=k([v(),I().int()]),lr=v();S({ttl:I().optional(),pollInterval:I().optional()});const ur=w({ttl:I().optional()}),pr=w({taskId:v()}),hr=S({progressToken:dr.optional(),[sr]:pr.optional()}),fr=w({_meta:hr.optional()}),mr=fr.extend({task:ur.optional()}),wr=w({method:v(),params:fr.loose().optional()}),gr=w({_meta:hr.optional()}),vr=w({method:v(),params:gr.loose().optional()}),yr=S({_meta:hr.optional()}),_r=k([v(),I().int()]),br=w({jsonrpc:y(ar),id:_r,...wr.shape}).strict(),kr=e=>br.safeParse(e).success,Ir=w({jsonrpc:y(ar),...vr.shape}).strict(),Sr=w({jsonrpc:y(ar),id:_r,result:yr}).strict(),Cr=e=>Sr.safeParse(e).success;var Tr,xr;(xr=Tr||(Tr={}))[xr.ConnectionClosed=-32e3]="ConnectionClosed",xr[xr.RequestTimeout=-32001]="RequestTimeout",xr[xr.ParseError=-32700]="ParseError",xr[xr.InvalidRequest=-32600]="InvalidRequest",xr[xr.MethodNotFound=-32601]="MethodNotFound",xr[xr.InvalidParams=-32602]="InvalidParams",xr[xr.InternalError=-32603]="InternalError",xr[xr.UrlElicitationRequired=-32042]="UrlElicitationRequired";const $r=w({jsonrpc:y(ar),id:_r.optional(),error:w({code:I().int(),message:v(),data:C().optional()})}).strict(),Ar=k([br,Ir,Sr,$r]);k([Sr,$r]);const Pr=yr.strict(),Er=gr.extend({requestId:_r.optional(),reason:v().optional()}),Or=vr.extend({method:y("notifications/cancelled"),params:Er}),Rr=w({src:v(),mimeType:v().optional(),sizes:g(v()).optional(),theme:_(["light","dark"]).optional()}),Mr=w({icons:g(Rr).optional()}),qr=w({name:v(),title:v().optional()}),Ur=qr.extend({...qr.shape,...Mr.shape,version:v(),websiteUrl:v().optional(),description:v().optional()}),Lr=T(w({applyDefaults:x().optional()}),b(v(),C())),jr=$(e=>e&&"object"==typeof e&&!Array.isArray(e)&&0===Object.keys(e).length?{form:{}}:e,T(w({form:Lr.optional(),url:cr.optional()}),b(v(),C()).optional())),zr=S({list:cr.optional(),cancel:cr.optional(),requests:S({sampling:S({createMessage:cr.optional()}).optional(),elicitation:S({create:cr.optional()}).optional()}).optional()}),Nr=S({list:cr.optional(),cancel:cr.optional(),requests:S({tools:S({call:cr.optional()}).optional()}).optional()}),Hr=w({experimental:b(v(),cr).optional(),sampling:w({context:cr.optional(),tools:cr.optional()}).optional(),elicitation:jr.optional(),roots:w({listChanged:x().optional()}).optional(),tasks:zr.optional(),extensions:b(v(),cr).optional()}),Dr=fr.extend({protocolVersion:v(),capabilities:Hr,clientInfo:Ur}),Vr=wr.extend({method:y("initialize"),params:Dr}),Fr=w({experimental:b(v(),cr).optional(),logging:cr.optional(),completions:cr.optional(),prompts:w({listChanged:x().optional()}).optional(),resources:w({subscribe:x().optional(),listChanged:x().optional()}).optional(),tools:w({listChanged:x().optional()}).optional(),tasks:Nr.optional(),extensions:b(v(),cr).optional()}),Wr=yr.extend({protocolVersion:v(),capabilities:Fr,serverInfo:Ur,instructions:v().optional()}),Br=vr.extend({method:y("notifications/initialized"),params:gr.optional()}),Jr=wr.extend({method:y("ping"),params:fr.optional()}),Gr=w({progress:I(),total:A(I()),message:A(v())}),Kr=w({...gr.shape,...Gr.shape,progressToken:dr}),Zr=vr.extend({method:y("notifications/progress"),params:Kr}),Qr=fr.extend({cursor:lr.optional()}),Yr=wr.extend({params:Qr.optional()}),Xr=yr.extend({nextCursor:lr.optional()}),en=_(["working","input_required","completed","failed","cancelled"]),tn=w({taskId:v(),status:en,ttl:k([I(),P()]),createdAt:v(),lastUpdatedAt:v(),pollInterval:A(I()),statusMessage:A(v())}),rn=yr.extend({task:tn}),nn=gr.merge(tn),on=vr.extend({method:y("notifications/tasks/status"),params:nn}),sn=wr.extend({method:y("tasks/get"),params:fr.extend({taskId:v()})}),an=yr.merge(tn),cn=wr.extend({method:y("tasks/result"),params:fr.extend({taskId:v()})});yr.loose();const dn=Yr.extend({method:y("tasks/list")}),ln=Xr.extend({tasks:g(tn)}),un=wr.extend({method:y("tasks/cancel"),params:fr.extend({taskId:v()})}),pn=yr.merge(tn),hn=w({uri:v(),mimeType:A(v()),_meta:b(v(),C()).optional()}),fn=hn.extend({text:v()}),mn=v().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),wn=hn.extend({blob:mn}),gn=_(["user","assistant"]),vn=w({audience:g(gn).optional(),priority:I().min(0).max(1).optional(),lastModified:E({offset:!0}).optional()}),yn=w({...qr.shape,...Mr.shape,uri:v(),description:A(v()),mimeType:A(v()),size:A(I()),annotations:vn.optional(),_meta:A(S({}))}),_n=w({...qr.shape,...Mr.shape,uriTemplate:v(),description:A(v()),mimeType:A(v()),annotations:vn.optional(),_meta:A(S({}))}),bn=Yr.extend({method:y("resources/list")}),kn=Xr.extend({resources:g(yn)}),In=Yr.extend({method:y("resources/templates/list")}),Sn=Xr.extend({resourceTemplates:g(_n)}),Cn=fr.extend({uri:v()}),Tn=Cn,xn=wr.extend({method:y("resources/read"),params:Tn}),$n=yr.extend({contents:g(k([fn,wn]))}),An=vr.extend({method:y("notifications/resources/list_changed"),params:gr.optional()}),Pn=Cn,En=wr.extend({method:y("resources/subscribe"),params:Pn}),On=Cn,Rn=wr.extend({method:y("resources/unsubscribe"),params:On}),Mn=gr.extend({uri:v()}),qn=vr.extend({method:y("notifications/resources/updated"),params:Mn}),Un=w({name:v(),description:A(v()),required:A(x())}),Ln=w({...qr.shape,...Mr.shape,description:A(v()),arguments:A(g(Un)),_meta:A(S({}))}),jn=Yr.extend({method:y("prompts/list")}),zn=Xr.extend({prompts:g(Ln)}),Nn=fr.extend({name:v(),arguments:b(v(),v()).optional()}),Hn=wr.extend({method:y("prompts/get"),params:Nn}),Dn=w({type:y("text"),text:v(),annotations:vn.optional(),_meta:b(v(),C()).optional()}),Vn=w({type:y("image"),data:mn,mimeType:v(),annotations:vn.optional(),_meta:b(v(),C()).optional()}),Fn=w({type:y("audio"),data:mn,mimeType:v(),annotations:vn.optional(),_meta:b(v(),C()).optional()}),Wn=w({type:y("tool_use"),name:v(),id:v(),input:b(v(),C()),_meta:b(v(),C()).optional()}),Bn=w({type:y("resource"),resource:k([fn,wn]),annotations:vn.optional(),_meta:b(v(),C()).optional()}),Jn=yn.extend({type:y("resource_link")}),Gn=k([Dn,Vn,Fn,Jn,Bn]),Kn=w({role:gn,content:Gn}),Zn=yr.extend({description:v().optional(),messages:g(Kn)}),Qn=vr.extend({method:y("notifications/prompts/list_changed"),params:gr.optional()}),Yn=w({title:v().optional(),readOnlyHint:x().optional(),destructiveHint:x().optional(),idempotentHint:x().optional(),openWorldHint:x().optional()}),Xn=w({taskSupport:_(["required","optional","forbidden"]).optional()}),ei=w({...qr.shape,...Mr.shape,description:v().optional(),inputSchema:w({type:y("object"),properties:b(v(),cr).optional(),required:g(v()).optional()}).catchall(C()),outputSchema:w({type:y("object"),properties:b(v(),cr).optional(),required:g(v()).optional()}).catchall(C()).optional(),annotations:Yn.optional(),execution:Xn.optional(),_meta:b(v(),C()).optional()}),ti=Yr.extend({method:y("tools/list")}),ri=Xr.extend({tools:g(ei)}),ni=yr.extend({content:g(Gn).default([]),structuredContent:b(v(),C()).optional(),isError:x().optional()});ni.or(yr.extend({toolResult:C()}));const ii=mr.extend({name:v(),arguments:b(v(),C()).optional()}),oi=wr.extend({method:y("tools/call"),params:ii}),si=vr.extend({method:y("notifications/tools/list_changed"),params:gr.optional()}),ai=w({autoRefresh:x().default(!0),debounceMs:I().int().nonnegative().default(300)}),ci=_(["debug","info","notice","warning","error","critical","alert","emergency"]),di=fr.extend({level:ci}),li=wr.extend({method:y("logging/setLevel"),params:di}),ui=gr.extend({level:ci,logger:v().optional(),data:C()}),pi=vr.extend({method:y("notifications/message"),params:ui}),hi=w({name:v().optional()}),fi=w({hints:g(hi).optional(),costPriority:I().min(0).max(1).optional(),speedPriority:I().min(0).max(1).optional(),intelligencePriority:I().min(0).max(1).optional()}),mi=w({mode:_(["auto","required","none"]).optional()}),wi=w({type:y("tool_result"),toolUseId:v().describe("The unique identifier for the corresponding tool call."),content:g(Gn).default([]),structuredContent:w({}).loose().optional(),isError:x().optional(),_meta:b(v(),C()).optional()}),gi=O("type",[Dn,Vn,Fn]),vi=O("type",[Dn,Vn,Fn,Wn,wi]),yi=w({role:gn,content:k([vi,g(vi)]),_meta:b(v(),C()).optional()}),_i=mr.extend({messages:g(yi),modelPreferences:fi.optional(),systemPrompt:v().optional(),includeContext:_(["none","thisServer","allServers"]).optional(),temperature:I().optional(),maxTokens:I().int(),stopSequences:g(v()).optional(),metadata:cr.optional(),tools:g(ei).optional(),toolChoice:mi.optional()}),bi=wr.extend({method:y("sampling/createMessage"),params:_i}),ki=yr.extend({model:v(),stopReason:A(_(["endTurn","stopSequence","maxTokens"]).or(v())),role:gn,content:gi}),Ii=yr.extend({model:v(),stopReason:A(_(["endTurn","stopSequence","maxTokens","toolUse"]).or(v())),role:gn,content:k([vi,g(vi)])}),Si=w({type:y("boolean"),title:v().optional(),description:v().optional(),default:x().optional()}),Ci=w({type:y("string"),title:v().optional(),description:v().optional(),minLength:I().optional(),maxLength:I().optional(),format:_(["email","uri","date","date-time"]).optional(),default:v().optional()}),Ti=w({type:_(["number","integer"]),title:v().optional(),description:v().optional(),minimum:I().optional(),maximum:I().optional(),default:I().optional()}),xi=w({type:y("string"),title:v().optional(),description:v().optional(),enum:g(v()),default:v().optional()}),$i=w({type:y("string"),title:v().optional(),description:v().optional(),oneOf:g(w({const:v(),title:v()})),default:v().optional()}),Ai=w({type:y("string"),title:v().optional(),description:v().optional(),enum:g(v()),enumNames:g(v()).optional(),default:v().optional()}),Pi=k([xi,$i]),Ei=w({type:y("array"),title:v().optional(),description:v().optional(),minItems:I().optional(),maxItems:I().optional(),items:w({type:y("string"),enum:g(v())}),default:g(v()).optional()}),Oi=w({type:y("array"),title:v().optional(),description:v().optional(),minItems:I().optional(),maxItems:I().optional(),items:w({anyOf:g(w({const:v(),title:v()}))}),default:g(v()).optional()}),Ri=k([Ei,Oi]),Mi=k([Ai,Pi,Ri]),qi=k([Mi,Si,Ci,Ti]),Ui=mr.extend({mode:y("form").optional(),message:v(),requestedSchema:w({type:y("object"),properties:b(v(),qi),required:g(v()).optional()})}),Li=mr.extend({mode:y("url"),message:v(),elicitationId:v(),url:v().url()}),ji=k([Ui,Li]),zi=wr.extend({method:y("elicitation/create"),params:ji}),Ni=gr.extend({elicitationId:v()}),Hi=vr.extend({method:y("notifications/elicitation/complete"),params:Ni}),Di=yr.extend({action:_(["accept","decline","cancel"]),content:$(e=>null===e?void 0:e,b(v(),k([v(),I(),x(),g(v())])).optional())}),Vi=w({type:y("ref/resource"),uri:v()}),Fi=w({type:y("ref/prompt"),name:v()}),Wi=fr.extend({ref:k([Fi,Vi]),argument:w({name:v(),value:v()}),context:w({arguments:b(v(),v()).optional()}).optional()}),Bi=wr.extend({method:y("completion/complete"),params:Wi}),Ji=yr.extend({completion:S({values:g(v()).max(100),total:A(I().int()),hasMore:A(x())})}),Gi=w({uri:v().startsWith("file://"),name:v().optional(),_meta:b(v(),C()).optional()}),Ki=wr.extend({method:y("roots/list"),params:fr.optional()}),Zi=yr.extend({roots:g(Gi)}),Qi=vr.extend({method:y("notifications/roots/list_changed"),params:gr.optional()});k([Jr,Vr,Bi,li,Hn,jn,bn,In,xn,En,Rn,oi,ti,sn,cn,dn,un]),k([Or,Zr,Br,Qi,on]),k([Pr,ki,Ii,Di,Zi,an,ln,rn]),k([Jr,bi,zi,Ki,sn,cn,dn,un]),k([Or,Zr,pi,qn,An,si,Qn,on,Hi]),k([Pr,Wr,Ji,Zn,zn,kn,Sn,$n,ni,ri,an,ln,rn]);class Yi extends Error{constructor(e,t,r){super(`MCP error ${e}: ${t}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,t,r){return e===Tr.UrlElicitationRequired&&r&&r.elicitations?new Xi(r.elicitations,t):new Yi(e,t,r)}}class Xi extends Yi{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(Tr.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}let eo=null;function to(e){const t=new URL(e.redirectUri),r=["localhost","127.0.0.1","[::1]"].includes(t.hostname);if("https:"!==t.protocol&&("http:"!==t.protocol||!r)||t.username||t.password||t.search||t.hash)throw new Error("Register a secure native connector callback URL");return eo=e,()=>{eo===e&&(eo=null)}}function ro(){if(!eo)throw new Error("Browser connector authorization is unavailable");return eo}function no(){return eo}function io(){return ro().redirectUri}function oo(e,t=no()?.captureAuthorizationGuard?.()){if(!t)return e;const r=()=>{e.assertCurrent(),t()},n=e.settleCredentialMutation,i={assertCurrent:r,signal:e.signal,supportsNativeOrigin:e.supportsNativeOrigin,fetch:(t,n)=>(r(),e.fetch(t,n))};return n&&(i.settleCredentialMutation=(t,i)=>(r(),n.call(e,t,i))),i}class so extends Error{constructor(e,t){super({"public-client":"This MCP provider has no verified public browser authorization route for this configuration. Check its public-client documentation.",metadata:"The MCP authorization metadata does not match the selected provider.",pending:"This authorization callback expired or belongs to another connector. Authorize again.",authorization:"The MCP provider did not complete public browser authorization.",storage:"The new authorization could not be sealed. Cleanup is required before continuing."}[e]),this.code=e,this.oauthError=t}code;oauthError;name="NativeMcpAuthError"}function ao(e){if(rr(e.binding),function(e){const{metadata:t,binding:r}=e;if(!(r.issuer&&t.issuer===r.issuer&&t.resource===r.resource&&t.resourceMetadata&&t.discoveryUrl&&t.pkce.includes("S256")&&t.tokenAuthMethods.includes("none")))throw new so("public-client");for(const n of[t.authorizationEndpoint,t.tokenEndpoint,t.resourceMetadata,t.discoveryUrl])tr(n)}(e),function(e){const{metadata:t}=e;if("dcr"===e.registration&&!t.registrationEndpoint)throw new so("public-client");if("manual"===e.registration&&!e.clientId)throw new so("public-client");if("cimd"===e.registration){if("cimd"!==t.registration||!e.clientMetadataUrl)throw new so("public-client");if("/"===tr(e.clientMetadataUrl).pathname)throw new so("public-client")}}(e),function(e){const t=new URL(e),r=["localhost","127.0.0.1","[::1]"].includes(t.hostname);if("https:"!==t.protocol&&("http:"!==t.protocol||!r)||t.username||t.password||t.hash)throw new so("public-client")}(e.redirectUri),e.scopes.some(t=>!e.metadata.scopes.includes(t)))throw new so("public-client")}const co=new Set;async function lo(e,t){if(co.has(e))throw new so("pending");co.add(e);try{const r=D();if(!r&&"persistent"===te())throw new so("pending");return r?await r.request(`opensesame:native-mcp-mutation:${e}`,{ifAvailable:!0},async e=>{if(!e)throw new so("pending");return t()}):await t()}finally{co.delete(e)}}let uo;async function po(e){return(await uo).getRandomValues(new Uint8Array(e))}uo=globalThis.crypto;const ho=M().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:q.custom,message:"URL must be parseable",fatal:!0}),U}).refine(e=>{const t=new URL(e);return"javascript:"!==t.protocol&&"data:"!==t.protocol&&"vbscript:"!==t.protocol},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),fo=S({resource:v().url(),authorization_servers:g(ho).optional(),jwks_uri:v().url().optional(),scopes_supported:g(v()).optional(),bearer_methods_supported:g(v()).optional(),resource_signing_alg_values_supported:g(v()).optional(),resource_name:v().optional(),resource_documentation:v().optional(),resource_policy_uri:v().url().optional(),resource_tos_uri:v().url().optional(),tls_client_certificate_bound_access_tokens:x().optional(),authorization_details_types_supported:g(v()).optional(),dpop_signing_alg_values_supported:g(v()).optional(),dpop_bound_access_tokens_required:x().optional()}),mo=S({issuer:v(),authorization_endpoint:ho,token_endpoint:ho,registration_endpoint:ho.optional(),scopes_supported:g(v()).optional(),response_types_supported:g(v()),response_modes_supported:g(v()).optional(),grant_types_supported:g(v()).optional(),token_endpoint_auth_methods_supported:g(v()).optional(),token_endpoint_auth_signing_alg_values_supported:g(v()).optional(),service_documentation:ho.optional(),revocation_endpoint:ho.optional(),revocation_endpoint_auth_methods_supported:g(v()).optional(),revocation_endpoint_auth_signing_alg_values_supported:g(v()).optional(),introspection_endpoint:v().optional(),introspection_endpoint_auth_methods_supported:g(v()).optional(),introspection_endpoint_auth_signing_alg_values_supported:g(v()).optional(),code_challenge_methods_supported:g(v()).optional(),client_id_metadata_document_supported:x().optional()}),wo=S({issuer:v(),authorization_endpoint:ho,token_endpoint:ho,userinfo_endpoint:ho.optional(),jwks_uri:ho,registration_endpoint:ho.optional(),scopes_supported:g(v()).optional(),response_types_supported:g(v()),response_modes_supported:g(v()).optional(),grant_types_supported:g(v()).optional(),acr_values_supported:g(v()).optional(),subject_types_supported:g(v()),id_token_signing_alg_values_supported:g(v()),id_token_encryption_alg_values_supported:g(v()).optional(),id_token_encryption_enc_values_supported:g(v()).optional(),userinfo_signing_alg_values_supported:g(v()).optional(),userinfo_encryption_alg_values_supported:g(v()).optional(),userinfo_encryption_enc_values_supported:g(v()).optional(),request_object_signing_alg_values_supported:g(v()).optional(),request_object_encryption_alg_values_supported:g(v()).optional(),request_object_encryption_enc_values_supported:g(v()).optional(),token_endpoint_auth_methods_supported:g(v()).optional(),token_endpoint_auth_signing_alg_values_supported:g(v()).optional(),display_values_supported:g(v()).optional(),claim_types_supported:g(v()).optional(),claims_supported:g(v()).optional(),service_documentation:v().optional(),claims_locales_supported:g(v()).optional(),ui_locales_supported:g(v()).optional(),claims_parameter_supported:x().optional(),request_parameter_supported:x().optional(),request_uri_parameter_supported:x().optional(),require_request_uri_registration:x().optional(),op_policy_uri:ho.optional(),op_tos_uri:ho.optional(),client_id_metadata_document_supported:x().optional()}),go=w({...wo.shape,...mo.pick({code_challenge_methods_supported:!0}).shape}),vo=w({access_token:v(),id_token:v().optional(),token_type:v(),expires_in:j().optional(),scope:v().optional(),refresh_token:v().optional(),issuer:v().optional().catch(void 0)}).strip(),yo=w({error:v(),error_description:v().optional(),error_uri:v().optional()}),_o=ho.optional().or(y("").transform(()=>{})),bo=w({redirect_uris:g(ho),token_endpoint_auth_method:v().optional(),grant_types:g(v()).optional(),response_types:g(v()).optional(),client_name:v().optional(),client_uri:ho.optional(),logo_uri:_o,scope:v().optional(),contacts:g(v()).optional(),tos_uri:_o,policy_uri:v().optional(),jwks_uri:ho.optional(),jwks:L().optional(),software_id:v().optional(),software_version:v().optional(),software_statement:v().optional()}).strip(),ko=w({client_id:v(),client_secret:v().optional(),client_id_issued_at:I().optional(),client_secret_expires_at:I().optional(),issuer:v().optional().catch(void 0)}).strip(),Io=bo.merge(ko);w({error:v(),error_description:v().optional()}).strip(),w({token:v(),token_type_hint:v().optional()}).strip();class So extends Error{constructor(e,t){super(e),this.errorUri=t,this.name=this.constructor.name}toResponseObject(){const e={error:this.errorCode,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}get errorCode(){return this.constructor.errorCode}}class Co extends So{}Co.errorCode="invalid_request";class To extends So{}To.errorCode="invalid_client";class xo extends So{}xo.errorCode="invalid_grant";class $o extends So{}$o.errorCode="unauthorized_client";class Ao extends So{}Ao.errorCode="unsupported_grant_type";class Po extends So{}Po.errorCode="invalid_scope";class Eo extends So{}Eo.errorCode="access_denied";class Oo extends So{}Oo.errorCode="server_error";class Ro extends So{}Ro.errorCode="temporarily_unavailable";class Mo extends So{}Mo.errorCode="unsupported_response_type";class qo extends So{}qo.errorCode="unsupported_token_type";class Uo extends So{}Uo.errorCode="invalid_token";class Lo extends So{}Lo.errorCode="method_not_allowed";class jo extends So{}jo.errorCode="too_many_requests";class zo extends So{}zo.errorCode="invalid_client_metadata";class No extends So{}No.errorCode="insufficient_scope";class Ho extends So{}Ho.errorCode="invalid_target";const Do={[Co.errorCode]:Co,[To.errorCode]:To,[xo.errorCode]:xo,[$o.errorCode]:$o,[Ao.errorCode]:Ao,[Po.errorCode]:Po,[Eo.errorCode]:Eo,[Oo.errorCode]:Oo,[Ro.errorCode]:Ro,[Mo.errorCode]:Mo,[qo.errorCode]:qo,[Uo.errorCode]:Uo,[Lo.errorCode]:Lo,[jo.errorCode]:jo,[zo.errorCode]:zo,[No.errorCode]:No,[Ho.errorCode]:Ho};function Vo(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Fo(e=fetch,t){return t?async(r,n)=>{const i={...t,...n,headers:n?.headers?{...Vo(t.headers),...Vo(n.headers)}:t.headers};return e(r,i)}:e}const Wo=[301,302,303,307,308];function Bo(e,t){const r=Wo.includes(e.status)?e.headers.get("location"):null;try{return r?new URL(r,t):void 0}catch{return}}function Jo(e,t,r,n,i=0){const o=Bo(n,t),s=307===n.status||308===n.status||"GET"===(r?.method??"GET").toUpperCase();if(!o||5===i||!s)return;const a=new URL(t);return(!o.username&&!o.password||o.username===a.username&&o.password===a.password)&&function(e,t){return e.protocol===t.protocol&&e.hostname===t.hostname&&e.port===t.port||e.hostname===t.hostname&&"http:"===e.protocol&&""===e.port&&"https:"===t.protocol&&""===t.port}(a,o)?Promise.resolve(n.body?.cancel()).then(()=>e(o,{...r,redirect:"manual"})).then(t=>Jo(e,o,r,t,i+1)??t):void 0}const Go=new WeakSet;function Ko(e){const t=(t,r)=>(e??fetch)(t,r);return Go.add(t),t}function Zo(e=fetch){return Go.has(e)?e:(t,r)=>"error"===r?.redirect||"manual"===r?.redirect?e(t,r):Promise.resolve(e(t,{...r,redirect:"manual"})).then(n=>Jo(e,t,r,n)??n)}function Qo(e,t){if("opaqueredirect"===e.type)return"Redirect not followed: this runtime does not expose the redirect target";const r=e.url||t,n=Bo(e,r);return n?(n.username=n.password=n.search=n.hash="","http:"===n.protocol&&"https:"===new URL(r).protocol?(n.protocol="https:",`Redirect to plain http not followed; try ${n.href} instead`):`Redirect to ${n.href} not followed`):void 0}class Yo extends Error{constructor(e){super(e??"Unauthorized")}}const Xo="code",es="S256";async function ts(e){const t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{const e=yo.parse(JSON.parse(r)),{error:t,error_description:n,error_uri:i}=e;return new(Do[t]||Oo)(n||"",i)}catch(n){const i=e instanceof Response?Qo(e,e.url):void 0;return new Oo(`${t?`HTTP ${t}: `:""}${i??`Invalid OAuth error response: ${n}. Raw body: ${r}`}`)}}function rs(e,t){if(e)return"string"!=typeof e.issuer?null==e.issuer?e:{...e,issuer:void 0}:function(e,t){let[r,n]=[e,t];try{[r,n]=[new URL(e).href,new URL(t).href]}catch{}return r===n||r.endsWith("/")&&r.slice(0,-1)===n||n.endsWith("/")&&n.slice(0,-1)===r}(e.issuer,t)?e:void 0}const ns=vo.omit({issuer:!0}),is=Io.omit({issuer:!0});function os(e,t){return new Error(`OAuth client information is bound to authorization server ${e.issuer} and is not presented to ${t}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function ss(e,t){try{return await as(e,t)}catch(r){if(r instanceof To||r instanceof $o)return await(e.invalidateCredentials?.("all")),await as(e,t);if(r instanceof xo)return await(e.invalidateCredentials?.("tokens")),await as(e,t);throw r}}async function as(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:i,fetchFn:o}){const s=await(e.discoveryState?.());let a,c,d,l=i;if(!l&&s?.resourceMetadataUrl&&(l=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(c=s.authorizationServerUrl,a=s.resourceMetadata,d=s.authorizationServerMetadata??await hs(c,{fetchFn:o}),!a)try{a=await ls(t,{resourceMetadataUrl:l},o)}catch{}d===s.authorizationServerMetadata&&a===s.resourceMetadata||await(e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:d}))}else{const r=await async function(e,t){let r,n;try{r=await ls(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),r.authorization_servers&&r.authorization_servers.length>0&&(n=r.authorization_servers[0])}catch{}return n||(n=String(new URL("/",e))),{authorizationServerUrl:n,authorizationServerMetadata:await hs(n,{fetchFn:t?.fetchFn}),resourceMetadata:r}}(t,{resourceMetadataUrl:l,fetchFn:o});c=r.authorizationServerUrl,d=r.authorizationServerMetadata,a=r.resourceMetadata,await(e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:a,authorizationServerMetadata:d}))}const u=String(c),p=await async function(e,t,r){const n=function(e){const t="string"==typeof e?new URL(e):new URL(e.href);return t.hash="",t}(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!function({requestedResource:e,configuredResource:t}){const r="string"==typeof e?new URL(e):new URL(e.href),n="string"==typeof t?new URL(t):new URL(t.href);if(r.origin!==n.origin)return!1;if(r.pathname.length<n.pathname.length)return!1;const i=r.pathname.endsWith("/")?r.pathname:r.pathname+"/",o=n.pathname.endsWith("/")?n.pathname:n.pathname+"/";return i.startsWith(o)}({requestedResource:n,configuredResource:r.resource}))throw new Error(`Protected resource ${r.resource} does not match expected ${n} (or origin)`);return new URL(r.resource)}}(t,e,a),h=p&&a&&!e.validateResourceURL?a.resource:p,f=n||a?.scopes_supported?.join(" ")||e.clientMetadata.scope,m=await Promise.resolve(e.clientInformation());let w=rs(m,u);if(m&&!w&&(void 0===e.saveClientInformation||!e.redirectUrl))throw os(m,u);const g=null==w?.issuer?w:void 0,v=async()=>{try{g&&await(e.saveClientInformation?.({...g,issuer:u}))}catch{}};if(!w){if(void 0!==r)throw new Error("Existing OAuth client information is required when exchanging an authorization code");const t=!0===d?.client_id_metadata_document_supported,n=e.clientMetadataUrl;if(n&&!function(e){if(!e)return!1;try{const t=new URL(e);return"https:"===t.protocol&&"/"!==t.pathname}catch{return!1}}(n))throw new zo(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${n}`);if(t&&n)w={client_id:n,issuer:u},await(e.saveClientInformation?.(w));else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");w={...await ys(c,{metadata:d,clientMetadata:e.clientMetadata,scope:f,fetchFn:o}),issuer:u},await e.saveClientInformation(w)}}if(void 0!==r||!e.redirectUrl){const t=await async function(e,t,{metadata:r,resource:n,authorizationCode:i,fetchFn:o}={}){const s=async()=>{const r=await e.clientInformation(),n=rs(r,String(t));if(r&&!n)throw os(r,String(t));return n};let a=await s();const c=e.clientMetadata.scope;let d;if(e.prepareTokenRequest&&(d=await e.prepareTokenRequest(c)),!d){if(!i)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");d=ws(i,await e.codeVerifier(),e.redirectUrl)}return a??(a=await s()),gs(t,{metadata:r,tokenRequestParams:d,clientInformation:a,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:o})}(e,c,{metadata:d,resource:h,authorizationCode:r,fetchFn:o});return await v(),await e.saveTokens({...t,issuer:u}),"AUTHORIZED"}const y=rs(await e.tokens(),u);if(y?.refresh_token&&null==y.issuer&&console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged."),y?.refresh_token)try{const t=await vs(c,{metadata:d,clientInformation:w,refreshToken:y.refresh_token,resource:h,addClientAuthentication:e.addClientAuthentication,fetchFn:o});return await v(),await e.saveTokens({...t,issuer:u}),"AUTHORIZED"}catch(I){if(I instanceof So&&!(I instanceof Oo))throw I}const _=e.state?await e.state():void 0,{authorizationUrl:b,codeVerifier:k}=await ms(c,{metadata:d,clientInformation:w,state:_,redirectUrl:e.redirectUrl,scope:f,resource:h});return await e.saveCodeVerifier(k),await e.redirectToAuthorization(b),"REDIRECT"}function cs(e){const t=e.headers.get("WWW-Authenticate");if(!t)return{};const[r,n]=t.split(" ");if("bearer"!==r.toLowerCase()||!n)return{};const i=ds(e,"resource_metadata")||void 0;let o;if(i)try{o=new URL(i)}catch{}return{resourceMetadataUrl:o,scope:ds(e,"scope")||void 0,error:ds(e,"error")||void 0}}function ds(e,t){const r=e.headers.get("WWW-Authenticate");if(!r)return null;const n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),i=r.match(n);return i?i[1]||i[2]:null}async function ls(e,t,r=fetch){const n=await async function(e,t,r,n){const i=new URL(e),o=n?.protocolVersion??ir;let s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{const e=function(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}(t,i.pathname);s=new URL(e,n?.metadataServerUrl??i),s.search=i.search}let a=await ps(s,o,r);if(!n?.metadataUrl&&function(e,t){return!e||!e.ok&&e.status<500&&"/"!==t}(a,i.pathname)){const e=new URL(`/.well-known/${t}`,i);a=await ps(e,o,r)}return a}(e,"oauth-protected-resource",r,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!n||404===n.status)throw await(n?.body?.cancel()),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!n.ok)throw await(n.body?.cancel()),new Error(`HTTP ${n.status} trying to load well-known OAuth protected resource metadata.`);return fo.parse(await n.json())}async function us(e,t,r=fetch){try{return await Zo(r)(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?us(e,void 0,r):void 0;throw n}}async function ps(e,t,r=fetch){const n={"MCP-Protocol-Version":t};return await us(e,n,r)}async function hs(e,{fetchFn:t=fetch,protocolVersion:r=ir}={}){const n={"MCP-Protocol-Version":r,Accept:"application/json"},i=function(e){const t="string"==typeof e?new URL(e):e,r=[];if("/"===t.pathname)return r.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),r.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),r;let n=t.pathname;return n.endsWith("/")&&(n=n.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${n}`,t.origin),type:"oauth"}),r.push({url:new URL(`/.well-known/openid-configuration${n}`,t.origin),type:"oidc"}),r.push({url:new URL(`${n}/.well-known/openid-configuration`,t.origin),type:"oidc"}),r}(e);for(const{url:o,type:s}of i){const e=await us(o,n,t);if(e){if(!e.ok){if(await(e.body?.cancel()),e.status<500)continue;throw new Error(`HTTP ${e.status} trying to load ${"oauth"===s?"OAuth":"OpenID provider"} metadata from ${o}`)}return"oauth"===s?mo.parse(await e.json()):go.parse(await e.json())}}}function fs(e){return"string"==typeof e?e:e.href}async function ms(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:i,state:o,resource:s}){let a;if(t){if(a=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Xo))throw new Error(`Incompatible auth server: does not support response type ${Xo}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(es))throw new Error(`Incompatible auth server: does not support code challenge method ${es}`)}else a=new URL("/authorize",e);const c=await async function(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;const t=await async function(e){return await async function(e){const t=Math.pow(2,8)-Math.pow(2,8)%66;let r="";for(;r.length<e;){const n=await po(e-r.length);for(const e of n)e<t&&(r+="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~"[e%66])}return r}(e)}(e);return{code_verifier:t,code_challenge:await async function(e){const t=await(await uo).subtle.digest("SHA-256",(new TextEncoder).encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}(t)}}(),d=c.code_verifier,l=c.code_challenge;return a.searchParams.set("response_type",Xo),a.searchParams.set("client_id",r.client_id),a.searchParams.set("code_challenge",l),a.searchParams.set("code_challenge_method",es),a.searchParams.set("redirect_uri",String(n)),o&&a.searchParams.set("state",o),i&&a.searchParams.set("scope",i),i?.includes("offline_access")&&a.searchParams.append("prompt","consent"),s&&a.searchParams.set("resource",fs(s)),{authorizationUrl:a,codeVerifier:d}}function ws(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}async function gs(e,{metadata:t,tokenRequestParams:r,clientInformation:n,addClientAuthentication:i,resource:o,fetchFn:s}){const a=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(o&&r.set("resource",fs(o)),i)await i(c,r,a,t);else if(n){const e=function(e,t){const r=void 0!==e.client_secret;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&["client_secret_basic","client_secret_post","none"].includes(e.token_endpoint_auth_method)&&(0===t.length||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:0===t.length?r?"client_secret_basic":"none":r&&t.includes("client_secret_basic")?"client_secret_basic":r&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":r?"client_secret_post":"none"}(n,t?.token_endpoint_auth_methods_supported??[]);!function(e,t,r,n){const{client_id:i,client_secret:o}=t;switch(e){case"client_secret_basic":return void function(e,t,r){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");const n=btoa(`${e}:${t}`);r.set("Authorization",`Basic ${n}`)}(i,o,r);case"client_secret_post":return void function(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}(i,o,n);case"none":return void function(e,t){t.set("client_id",e)}(i,n);default:throw new Error(`Unsupported client authentication method: ${e}`)}}(e,n,c,r)}const d=await Zo(s??fetch)(a,{method:"POST",headers:c,body:r});if(!d.ok)throw await ts(d);return ns.parse(await d.json())}async function vs(e,{metadata:t,clientInformation:r,refreshToken:n,resource:i,addClientAuthentication:o,fetchFn:s}){const a=new URLSearchParams({grant_type:"refresh_token",refresh_token:n});return{refresh_token:n,...await gs(e,{metadata:t,tokenRequestParams:a,clientInformation:r,addClientAuthentication:o,resource:i,fetchFn:s})}}async function ys(e,{metadata:t,clientMetadata:r,scope:n,fetchFn:i}){let o;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");o=new URL(t.registration_endpoint)}else o=new URL("/register",e);const s=await Zo(i??fetch)(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...r,...void 0!==n?{scope:n}:{}})});if(!s.ok)throw await ts(s);return is.parse(await s.json())}async function _s(e){try{return await e()}catch(t){if(t instanceof er||t instanceof so)throw t;if(t instanceof xo)throw new so("authorization","invalid_grant");if(t instanceof To)throw new so("authorization","invalid_client");throw new so("authorization")}}const bs=mo.strip(),ks=bo.extend({client_id:v().url(),client_name:v().min(1)}),Is=ko.extend({client_id:v().min(1).max(32768),client_secret:v().max(32768).optional(),token_endpoint_auth_method:v().max(1024).optional(),registration_access_token:v().min(1).max(32768).regex(/^[!-~]+$/).optional(),registration_client_uri:v().url().max(32768).optional()}),Ss=v().min(1).max(32768).regex(/^[!-~]+$/),Cs=w({access_token:Ss}),Ts=w({refresh_token:Ss}),xs=Cs.extend({refresh_token:Ss.optional()}),$s=w({token_type:v().min(1),expires_in:I().finite().positive().max(31536e3).optional(),scope:v().max(32768).refine(e=>{const t=e.split(/\s+/).filter(Boolean);return t.every(e=>e.length<=512)&&new Set(t).size<=256}).optional()});async function As(e,t,r,n){const i={value:null};let o=null;const s=async(e,n)=>{const s=await t(e,n);if(s.ok){const e=await s.clone().json(),t=Cs.safeParse(e),n=xs.safeParse(e),a=Ts.safeParse(e);if(!t.success&&a.success&&(o=a.data.refresh_token),t.success){const o=$s.safeParse(e),s=n.success&&o.success;i.value={...t.data,token_type:s?o.data.token_type:"",issuer:r,protocolValid:s&&"bearer"===o.data.token_type.toLowerCase()},n.success&&n.data.refresh_token&&(i.value.refresh_token=n.data.refresh_token),s&&(i.value.expires_in=o.data.expires_in,i.value.scope=o.data.scope)}}return s};try{await e(s)}catch(a){if(!i.value&&!o)throw a}if(!i.value&&o){if(!n)throw new so("storage");throw await n(o),new so("authorization")}if(!i.value)throw new so("authorization");return i.value}function Ps(e,t){if(!t.client_id||t.client_secret||t.issuer!==e.binding.issuer)throw new so("public-client");if("token_endpoint_auth_method"in t&&void 0!==t.token_endpoint_auth_method&&"none"!==t.token_endpoint_auth_method)throw new so("public-client")}function Es(e){const t=Is.safeParse(e);return t.success?JSON.stringify(t.data).length>32768?null:t.data:null}async function Os(e,t){try{await e(t)}catch(r){if(r instanceof so&&"storage"===r.code)throw r;throw new so("metadata")}}class Rs{constructor(e,t){this.ports=t,this.target=structuredClone(e),ao(this.target),this.fetcher=function(e,t,r,n,i){const o=[e.metadata.registrationEndpoint,e.metadata.tokenEndpoint];return async(s,a)=>{if(n(),r.aborted)throw new er("disposed");const c=new Request(s,a);let d;!function(e,t){const r=e.metadata;if(!("GET"===t.method?[r.resourceMetadata,r.discoveryUrl,e.clientMetadataUrl]:"POST"===t.method?[r.registrationEndpoint,r.tokenEndpoint,r.revocationEndpoint]:[]).includes(t.url))throw new so("metadata");if(t.headers.has("authorization"))throw new so("public-client")}(e,c);const l="POST"===c.method&&o.includes(c.url),u=l?i??t:t,p=AbortSignal.timeout(15e3);try{d=await u(c,{credentials:"omit",redirect:"manual",cache:"no-store",referrerPolicy:"no-referrer",signal:l&&i?AbortSignal.any([c.signal,p]):AbortSignal.any([r,c.signal,p])})}catch{throw new er(r.aborted?"disposed":"browser-transport")}await async function(e){if("opaqueredirect"===e.type||e.status>=300&&e.status<400)throw await(e.body?.cancel()),new so("metadata")}(d);const h=await async function(e){const t=e.body?.getReader();if(!t)return e;const r=[];let n=0;try{for(;;){const e=await t.read();if(e.done)break;if(n+=e.value.byteLength,n>262144)throw new so("metadata");r.push(e.value)}}finally{await t.cancel().catch(()=>{}),t.releaseLock()}const i=new Uint8Array(n);let o=0;for(const s of r)i.set(s,o),o+=s.byteLength;return new Response(i,{status:e.status,headers:e.headers})}(d);if((!l||!i)&&(n(),r.aborted))throw new er("disposed");return h}}(this.target,t.fetch,t.signal,t.assertCurrent,t.settleCredentialMutation)}ports;target;fetcher;registrationMode=null;async metadata(){this.ports.assertCurrent();const e=await _s(()=>async function(e,t){const{metadata:r,binding:n}=e;if(!r.resourceMetadata||!r.discoveryUrl)throw new so("public-client");const i=await t(r.resourceMetadata);if(!i.ok)throw new so("metadata");const o=fo.parse(await i.json());if(o.resource!==n.resource||!o.authorization_servers?.includes(n.issuer??""))throw new so("metadata");const s=await t(r.discoveryUrl);if(!s.ok)throw new so("metadata");const a=bs.parse(await s.json());if(function(e,t){const{binding:r,metadata:n}=e;if(t.issuer!==r.issuer||t.authorization_endpoint!==n.authorizationEndpoint||t.token_endpoint!==n.tokenEndpoint)throw new so("metadata");if(!t.token_endpoint_auth_methods_supported?.includes("none")||!t.code_challenge_methods_supported?.includes("S256"))throw new so("public-client");if(!t.response_types_supported.includes("code")||t.grant_types_supported&&!t.grant_types_supported.includes("authorization_code"))throw new so("public-client");if("dcr"===e.registration&&t.registration_endpoint!==n.registrationEndpoint)throw new so("metadata")}(e,a),"cimd"!==e.registration)return{metadata:a,registration:e.registration};if(a.client_id_metadata_document_supported)return await async function(e,t,r){if(!t.client_id_metadata_document_supported||!e.clientMetadataUrl)throw new so("public-client");const n=await r(e.clientMetadataUrl);if(!n.ok)throw new so("public-client");const i=ks.parse(await n.json());if(i.client_id!==e.clientMetadataUrl||"none"!==i.token_endpoint_auth_method||!i.redirect_uris?.includes(e.redirectUri))throw new so("public-client")}(e,a,t),{metadata:a,registration:"cimd"};if(e.metadata.registrationEndpoint&&a.registration_endpoint===e.metadata.registrationEndpoint)return{metadata:a,registration:"dcr"};throw new so("public-client")}(this.target,this.fetcher));return this.registrationMode??=e.registration,e.metadata}async register(e){const t=await this.metadata(),r=this.registrationMode??this.target.registration;let n;if(this.ports.onRegistrationMode?.(r),"dcr"===r){const r={value:null},i=async(e,t)=>{const n=await this.fetcher(e,t);if(n.ok){const e=Is.safeParse(await n.clone().json());e.success&&(r.value={...e.data,issuer:this.target.binding.issuer??void 0})}return n};try{n={...await _s(()=>ys(this.target.binding.issuer??"",{metadata:t,clientMetadata:{client_name:"OpenSesame",redirect_uris:[this.target.redirectUri],grant_types:t.grant_types_supported?.includes("refresh_token")?["authorization_code","refresh_token"]:["authorization_code"],response_types:["code"],token_endpoint_auth_method:"none"},scope:this.target.scopes.join(" "),fetchFn:i})),...r.value,issuer:this.target.binding.issuer??void 0}}catch(o){if(r.value){const t=Es(r.value);if(!t)throw new so("metadata");await Os(e,t)}throw o}}else n={client_id:this.target.clientMetadataUrl??this.target.clientId??"",issuer:this.target.binding.issuer??void 0};const i=Es(n);if(!i)throw new so("metadata");return await Os(e,i),this.ports.assertCurrent(),Ps(this.target,i),i}async consent(e,t){if(Ps(this.target,e),!/^[a-zA-Z0-9_-]{43,512}$/.test(t))throw new so("pending");const r=await this.metadata();return _s(()=>ms(this.target.binding.issuer??"",{metadata:r,clientInformation:e,redirectUrl:this.target.redirectUri,scope:this.target.scopes.join(" "),state:t,resource:this.target.binding.resource}))}async exchange(e,t,r){if(Ps(this.target,e),!t||!/^[a-zA-Z0-9._~-]{43,128}$/.test(r))throw new so("pending");const n=await this.metadata();return As(i=>_s(()=>async function(e,{metadata:t,clientInformation:r,authorizationCode:n,codeVerifier:i,redirectUri:o,resource:s,addClientAuthentication:a,fetchFn:c}){return gs(e,{metadata:t,tokenRequestParams:ws(n,i,o),clientInformation:r,addClientAuthentication:a,resource:s,fetchFn:c})}(this.target.binding.issuer??"",{metadata:n,clientInformation:e,authorizationCode:t,codeVerifier:r,redirectUri:this.target.redirectUri,resource:this.target.binding.resource,fetchFn:i})),this.fetcher,this.target.binding.issuer??"",this.ports.retainPartialRefresh)}async refresh(e,t){Ps(this.target,e);const r=await this.metadata();return As(n=>_s(()=>vs(this.target.binding.issuer??"",{metadata:r,clientInformation:e,refreshToken:t,resource:this.target.binding.resource,fetchFn:n})),this.fetcher,this.target.binding.issuer??"",this.ports.retainPartialRefresh)}async revoke(e,t,r){Ps(this.target,e);const n=this.target.metadata.revocationEndpoint;if(!n)throw new so("public-client");if(!(await this.fetcher(n,{method:"POST",body:new URLSearchParams({token:t,token_type_hint:r,client_id:e.client_id})})).ok)throw new so("authorization")}}const Ms={publicParameters:["mcp_url"],privateCredentials:["mcp_client","mcp_registration_mode"]};function qs(e){return Ms}function Us(e,t){const r=Z(e);if(!r||r.refused)throw new er("target");const n=r.methods.filter(e=>"mcp"===e.kind),i=t?n.find(e=>e.mcp.url===t):n[0];if(!i)throw new er("target");return structuredClone(i.mcp)}function Ls(e){const t=Us(e.providerId,e.parameters.mcp_url),r={providerId:e.providerId,fingerprint:e.fingerprint,endpoint:t.url,resource:"ok"===t.status?t.resource??t.url:t.url,issuer:"ok"===t.status?t.issuer:null,transport:new URL(t.url).pathname.endsWith("/sse")?"sse":"streamable-http"};return rr(r),r}async function js(e){const t=Us(e.providerId,e.parameters.mcp_url),r=JSON.stringify({providerId:e.providerId,method:"mcp",metadata:t,clientId:e.clientId??null,requestedScopes:e.requestedScopes,targetIds:e.targetIds}),n=await crypto.subtle.digest("SHA-256",(new TextEncoder).encode(r));return Array.from(new Uint8Array(n),e=>e.toString(16).padStart(2,"0")).join("")}function zs(e,t=ro()){const r=Us(e.providerId,e.parameters.mcp_url);if("ok"!==r.status)throw new er("authorization");const n={binding:Ls(e),metadata:r,redirectUri:t.redirectUri,registration:r.registration,clientId:e.clientId,clientMetadataUrl:"cimd"===r.registration?new URL("native-client.json",t.redirectUri).href:void 0,scopes:e.requestedScopes.user??[]};return ao(n),n}function Ns(e){const t=Xe(e);if(!t||"mcp"!==t.configuration.method)throw new er("target");return t}async function Hs(e){if(e.configuration.fingerprint!==await js(e.configuration))throw new er("target")}function Ds(e){try{return Is.parse(JSON.parse(e.privateState.credentials.mcp_client??""))}catch{throw new so("public-client")}}function Vs(e,t){const r={providerId:e.providerId,actor:e.actor,fingerprint:e.fingerprint,targetId:e.targetId,issuer:e.issuer,resource:e.resource,endpoint:e.endpoint,clientId:e.clientId,kind:"mcp",accessToken:t.access_token,expiresAt:void 0===t.expires_in?null:Date.now()+1e3*t.expires_in,scopes:void 0===t.scope?null:[...new Set(t.scope.split(/\s+/).filter(Boolean))]};return t.refresh_token&&(r.refreshToken=t.refresh_token),r}const Fs=new Map;function Ws(e,t,r){if(Fs.has(e)||Fs.size>=64)throw new so("storage");Fs.set(e,{intentId:t,fingerprint:r,token:null})}function Bs(e,t){const r=Fs.get(e);r?.intentId===t&&null===r.token&&Fs.delete(e)}function Js(e,t){Fs.get(e)?.intentId===t&&Fs.delete(e)}async function Gs(e,t){if(null===t.token)throw new so("storage");const r=t.token,n=Ns(e);await lt(e,Ct(n),Ms,e=>{const n=e.privateState.recovery.find(e=>e.id===t.intentId);if(!n||n.fingerprint!==t.fingerprint||!["exchange","refresh"].includes(n.credentials?.phase??""))throw new so("storage");return"refresh"===n.credentials?.phase&&(delete e.privateState.grants[n.actor],e.runtime.grants=e.runtime.grants.filter(e=>e.actor!==n.actor)),n.credentials={...n.credentials,phase:"partial-refresh",partial_refresh_token:r},e.privateState.verification=null,e}),Fs.delete(e)}async function Ks(e,t,r){const n=Fs.get(e);if(!n||n.intentId!==t||null!==n.token||r.length<1||r.length>32768||!/^[!-~]+$/.test(r))throw new so("storage");n.token=r,await Gs(e,n)}const Zs=new Map,Qs=new Map;function Ys(e,t){if(Zs.has(e)||J[e])throw new Error("Provider cleanup is already registered");const r=async r=>{if(Zs.get(e)!==t)throw new Error("Provider cleanup runtime changed");if(Xs(r).configuration.providerId!==e)throw new Error("Provider cleanup belongs to another connector");await da(r)};return Zs.set(e,t),J[e]=r,()=>{Zs.get(e)===t&&Zs.delete(e),J[e]===r&&delete J[e]}}function Xs(e){const t=Xe(e);if(!t)throw new Error("Saved native connector not found");return t}function ea(e){const t=Zs.get(e.configuration.providerId);if(!t)throw new Error("Provider cleanup is unavailable on this device");return t}function ta(e,t){if(ea(Xs(e))!==t)throw new Error("Provider cleanup runtime changed; retry with the active connection")}function ra(e){return{revision:e.revision,fingerprint:e.configuration.fingerprint}}function na(e,t){const r=(Qs.get(e)??Promise.resolve()).catch(()=>{}).then(async()=>{const r=D();if(!r&&"persistent"===te())throw new Error("Web Locks are required for shared provider cleanup");return r?r.request(`opensesame:native-cleanup:${e}`,t):t()});return Qs.set(e,r),r.finally(()=>{Qs.get(e)===r&&Qs.delete(e)})}function ia(e,t){const r=e.privateState.recovery.find(e=>e.id===t.id);if(!r||(n=t,Q(r)!==Q(n)))throw new Error("Provider cleanup changed; reload before retrying");var n;return r}async function oa(e,t,r,n){let i=structuredClone(t);ta(e,r);const o=Xs(e);await dt(e,ra(o)),ta(e,r),n?.assertCurrent(),ia(o,i);const s=await r.cleanup(structuredClone(i),{connectionId:e,configuration:structuredClone(o.configuration),transport:n,persistGrantRotation:async t=>{if(!i.grant)throw new Error("Provider cleanup has no grant to rotate");!function(e,t){for(const r of["providerId","actor","fingerprint","targetId","kind","issuer","resource","endpoint","clientId"])if(e[r]!==t[r])throw new Error("Rotated authorization changed its provider binding")}(i.grant,t);const n=Xs(e),o={...i,grant:structuredClone(t)};await lt(e,ra(n),r.classification(n.configuration),t=>(ta(e,r),ia(t,i),t.privateState.recovery=t.privateState.recovery.map(e=>e.id===i.id?o:e),t)),i=o}});if("provider-revoked"!==s&&"local-credential-forgotten"!==s&&"local-registration-forgotten"!==s)throw new Error("Provider cleanup did not complete");if("local-credential-forgotten"===s&&"revoke"!==i.kind)throw new Error("Remote provider configuration requires provider cleanup");if("local-registration-forgotten"===s&&"registration"!==i.kind)throw new Error("Local registration cleanup requires a registration obligation");n?.assertCurrent();const a=Xs(e);await lt(e,ra(a),r.classification(a.configuration),t=>(ta(e,r),n?.assertCurrent(),ia(t,i),t.privateState.recovery=t.privateState.recovery.filter(e=>e.id!==i.id),t))}async function sa(e,t,r){ta(e,t);try{r?.assertCurrent(),r?await(t.prepare?.(e,r)):await(t.prepare?.(e)),r?.assertCurrent(),ta(e,t)}catch{throw new Error("Provider cleanup failed; retry before removing this connection")}const n=Xs(e);for(const o of n.privateState.recovery)try{await oa(e,o,t,r)}catch{throw new Error("Provider cleanup failed; retry before removing this connection")}const i=et(e);if(!i)throw new Error("Saved native connector not found");return i}async function aa(e,t){const r=ea(Xs(e)),n=t??r.capture?.(e);return n?.assertCurrent(),na(e,()=>sa(e,r,n))}function ca(e,t,r){const n={},i=t.credentialSlots??[],o="call"in i?i(e.configuration,r):i,s=t.classification(e.configuration).privateCredentials;for(const a of o){if(!s.includes(a))throw new Error("Unknown provider cleanup credential slot");const t=e.privateState.credentials[a];void 0!==t&&(n[a]=t)}return n}async function da(e,t){const r=ea(Xs(e)),n=r.capture?.(e);return n?.assertCurrent(),na(e,async()=>{n?.assertCurrent(),await async function(e,t){ta(e,t);const r=Xs(e);await lt(e,ra(r),t.classification(r.configuration),r=>{ta(e,t);const n=Object.entries(r.privateState.grants).map(([e,n])=>{const i=n.targetId??r.runtime.identity?.id??r.configuration.providerId;return{id:`revoke:${e}:${r.revision}`,kind:"revoke",providerId:n.providerId,actor:e,fingerprint:n.fingerprint,targetId:i,grant:{...n,targetId:i},credentials:ca(r,t,n)}});return r.privateState={...r.privateState,grants:{},pending:{},verification:null,recovery:[...r.privateState.recovery,...n]},r.runtime=p(),r})}(e,r),await sa(e,r,n),ta(e,r);const t=Xs(e),i=await lt(e,ra(t),r.classification(t.configuration),t=>{if(ta(e,r),n?.assertCurrent(),t.privateState.recovery.length>0)throw new Error("Provider cleanup remains incomplete");if(Object.keys(t.privateState.grants).length>0||Object.keys(t.privateState.pending).length>0)throw new Error("Provider authorization changed during cleanup");return t.privateState=a(),t.runtime=p(),t});return function(e,t){return ae(e,e=>{const r=Ye(e);if(ct(r,t),r.privateState.recovery.length>0||Object.keys(r.privateState.pending).length>0||Object.keys(r.privateState.grants).length>0)throw new Error("Provider authorization cleanup must finish before removal")})}(e,i)})}const la=new Map;function ua(e,t){la.get(e)?.intentId===t&&la.delete(e)}function pa(e){if(la.size>=64&&!la.has(e))throw new so("storage")}function ha(e){if(pa(e),la.has(e))throw new so("storage")}async function fa(e,t,r,n,i){const o=Ns(e);let s=!1,a=!1;try{await lt(e,Ct(o),Ms,e=>{const o=e.privateState.recovery.find(e=>e.id===t);if(!o||o.fingerprint!==r||"registration"!==o.kind)throw new so("metadata");return e.privateState.credentials.mcp_client=n,e.privateState.credentials.mcp_registration_mode=i,o.credentials={...o.credentials,client:n,phase:"registered",registration_mode:i,submission:"settled"},s=!0,e},void 0,()=>{a=!0})}catch(c){if(a)throw new so("storage");if(s)throw new so("metadata");throw c}la.delete(e)}async function ma(e,t){const r=Ns(e);await lt(e,Ct(r),Ms,e=>{const r=e.privateState.recovery.find(e=>e.id===t);if(!r||"prepared"!==r.credentials?.submission)throw new so("pending");return r.credentials.submission="submitting",e})}function wa(e){return!!e._zod}function ga(e,t){return wa(e)?z(e,t):e.safeParse(t)}function va(e){if(!e)return;let t;if(wa(e)){const r=e;t=r._zod?.def?.shape}else t=e.shape;if(t){if("function"==typeof t)try{return t()}catch{return}return t}}function ya(e){if(wa(e)){const t=e,r=t._zod?.def;if(r){if(void 0!==r.value)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}}const t=e._def;if(t){if(void 0!==t.value)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}const r=e.value;if(void 0!==r)return r}function _a(e){return"completed"===e||"failed"===e||"cancelled"===e}function ba(e){const t=va(e),r=t?.method;if(!r)throw new Error("Schema is missing a method literal");const n=ya(r);if("string"!=typeof n)throw new Error("Schema method literal must be a string");return n}function ka(e,t){const r=ga(e,t);if(!r.success)throw r.error;return r.data}new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");class Ia{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Or,e=>{this._oncancel(e)}),this.setNotificationHandler(Zr,e=>{this._onprogress(e)}),this.setRequestHandler(Jr,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(sn,async(e,t)=>{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Yi(Tr.InvalidParams,"Failed to retrieve task: Task not found");return{...r}}),this.setRequestHandler(cn,async(e,t)=>{const r=async()=>{const n=e.params.taskId;if(!(await this._taskStore.getTask(n,t.sessionId)))throw new Yi(Tr.InvalidParams,`Task not found: ${n}`);if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(n,t.sessionId);){if("response"===e.type||"error"===e.type){const t=e.message,r=t.id,n=this._requestResolvers.get(r);n?(this._requestResolvers.delete(r),n("response"===e.type?t:new Yi(t.error.code,t.error.message,t.error.data))):this._onerror(new Error(`${"response"===e.type?"Response":"Error"} handler missing for request ${r}`));continue}await(this._transport?.send(e.message,{relatedRequestId:t.requestId}))}}const i=await this._taskStore.getTask(n,t.sessionId);if(!i)throw new Yi(Tr.InvalidParams,`Task not found: ${n}`);if(!_a(i.status))return await this._waitForTaskUpdate(n,t.signal,t.sessionId),await r();if(_a(i.status)){const e=await this._taskStore.getTaskResult(n,t.sessionId);return this._clearTaskQueue(n,t.sessionId),{...e,_meta:{...e._meta,[sr]:{taskId:n}}}}return await r()};return await r()}),this.setRequestHandler(dn,async(e,t)=>{try{const{tasks:r,nextCursor:n}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:r,nextCursor:n,_meta:{}}}catch(r){throw new Yi(Tr.InvalidParams,`Failed to list tasks: ${r instanceof Error?r.message:String(r)}`)}}),this.setRequestHandler(un,async(e,t)=>{try{const r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new Yi(Tr.InvalidParams,`Task not found: ${e.params.taskId}`);if(_a(r.status))throw new Yi(Tr.InvalidParams,`Cannot cancel task in terminal status: ${r.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,"cancelled","Client cancelled task execution.",t.sessionId),this._clearTaskQueue(e.params.taskId,t.sessionId);const n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new Yi(Tr.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...n}}catch(r){if(r instanceof Yi)throw r;throw new Yi(Tr.InvalidRequest,`Failed to cancel task: ${r instanceof Error?r.message:String(r)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;const t=this._requestHandlerAbortControllers.get(e.params.requestId);t?.abort(e.params.reason)}_setupTimeout(e,t,r,n,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(n,t),startTime:Date.now(),timeout:t,maxTotalTimeout:r,resetTimeoutOnProgress:i,onTimeout:n})}_resetTimeout(e){const t=this._timeoutInfo.get(e);if(!t)return!1;const r=Date.now()-t.startTime;if(t.maxTotalTimeout&&r>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),Yi.fromError(Tr.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:r});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){const t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;const t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};const r=this.transport?.onerror;this._transport.onerror=e=>{r?.(e),this._onerror(e)};const n=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{n?.(e,t),Cr(e)||$r.safeParse(e).success?this._onresponse(e):kr(e)?this._onrequest(e,t):Ir.safeParse(e).success?this._onnotification(e):this._onerror(new Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){const e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(const r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(const r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();const t=Yi.fromError(Tr.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(const r of e.values())r(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){const t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;void 0!==t&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(new Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){const r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,n=this._transport,i=e.params?._meta?.[sr]?.taskId,o=n?.sessionId,s=this._taskStore;let a,c=!0;if(i&&s&&this._taskMessageQueue&&void 0!==o&&(c=!1,a=(async()=>{if(!(await s.getTask(i,o)))throw new Yi(Tr.InvalidParams,`Task not found: ${i}`);c=!0})()),void 0===r){const t={jsonrpc:"2.0",id:e.id,error:{code:Tr.MethodNotFound,message:"Method not found"}};if(i&&a){const e={type:"error",message:t,timestamp:Date.now()};a.then(()=>this._enqueueTaskMessage(i,e,o),()=>n?.send(t)).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`)))}else i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:"error",message:t,timestamp:Date.now()},n?.sessionId).catch(e=>this._onerror(new Error(`Failed to enqueue error response: ${e}`))):n?.send(t).catch(e=>this._onerror(new Error(`Failed to send an error response: ${e}`)));return}const d=new AbortController;this._requestHandlerAbortControllers.set(e.id,d);const l=mr.safeParse(e.params).success?e.params.task:void 0,u=this._taskStore?this.requestTaskStore(e,n?.sessionId):void 0,p={signal:d.signal,sessionId:n?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(d.signal.aborted)return;const r={relatedRequestId:e.id};i&&(r.relatedTask={taskId:i}),await this.notification(t,r)},sendRequest:async(t,r,n)=>{if(d.signal.aborted)throw new Yi(Tr.ConnectionClosed,"Request was cancelled");const o={...n,relatedRequestId:e.id};i&&!o.relatedTask&&(o.relatedTask={taskId:i});const s=o.relatedTask?.taskId??i;return s&&u&&await u.updateTaskStatus(s,"input_required"),await this.request(t,r,o)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:u,taskRequestedTtl:l?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(a??Promise.resolve()).then(()=>{if(a&&d.signal.aborted)throw new Yi(Tr.ConnectionClosed,"Request was cancelled");l&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,p)).then(async t=>{if(d.signal.aborted)return;const r={result:t,jsonrpc:"2.0",id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:r,timestamp:Date.now()},n?.sessionId):await(n?.send(r))},async t=>{if(d.signal.aborted)return;const r={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:Tr.InternalError,message:t.message??"Internal error",...void 0!==t.data&&{data:t.data}}};i&&this._taskMessageQueue&&c?await this._enqueueTaskMessage(i,{type:"error",message:r,timestamp:Date.now()},n?.sessionId):await(n?.send(r))}).catch(e=>this._onerror(new Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===d&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){const{progressToken:t,...r}=e.params,n=Number(t),i=this._progressHandlers.get(n);if(!i)return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));const o=this._responseHandlers.get(n),s=this._timeoutInfo.get(n);if(s&&o&&s.resetTimeoutOnProgress)try{this._resetTimeout(n)}catch(a){return this._responseHandlers.delete(n),this._progressHandlers.delete(n),this._cleanupTimeout(n),void o(a)}i(r)}_onresponse(e){const t=Number(e.id),r=this._requestResolvers.get(t);if(r)return this._requestResolvers.delete(t),void(Cr(e)?r(e):r(new Yi(e.error.code,e.error.message,e.error.data)));const n=this._responseHandlers.get(t);if(void 0===n)return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(Cr(e)&&e.result&&"object"==typeof e.result){const r=e.result;if(r.task&&"object"==typeof r.task){const e=r.task;"string"==typeof e.taskId&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),Cr(e)?n(e):n(Yi.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await(this._transport?.close())}async*requestStream(e,t,r){const{task:n}=r??{};if(!n){try{const n=await this.request(e,t,r);yield{type:"result",result:n}}catch(o){yield{type:"error",error:o instanceof Yi?o:new Yi(Tr.InternalError,String(o))}}return}let i;try{const n=await this.request(e,rn,r);if(!n.task)throw new Yi(Tr.InternalError,"Task creation did not return a task");for(i=n.task.taskId,yield{type:"taskCreated",task:n.task};;){const e=await this.getTask({taskId:i},r);if(yield{type:"taskStatus",task:e},_a(e.status)){if("completed"===e.status){const e=await this.getTaskResult({taskId:i},t,r);yield{type:"result",result:e}}else"failed"===e.status?yield{type:"error",error:new Yi(Tr.InternalError,`Task ${i} failed`)}:"cancelled"===e.status&&(yield{type:"error",error:new Yi(Tr.InternalError,`Task ${i} was cancelled`)});return}if("input_required"===e.status){const e=await this.getTaskResult({taskId:i},t,r);return void(yield{type:"result",result:e})}const n=e.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,n)),r?.signal?.throwIfAborted()}}catch(o){yield{type:"error",error:o instanceof Yi?o:new Yi(Tr.InternalError,String(o))}}}request(e,t,r){const{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o,task:s,relatedTask:a}=r??{};return new Promise((c,d)=>{const l=e=>{d(e)};if(!this._transport)return void l(new Error("Not connected"));if(!0===this._options?.enforceStrictCapabilities)try{this.assertCapabilityForMethod(e.method),s&&this.assertTaskCapability(e.method)}catch(w){return void l(w)}r?.signal?.throwIfAborted();const u=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:u};r?.onprogress&&(this._progressHandlers.set(u,r.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:u}}),s&&(p.params={...p.params,task:s}),a&&(p.params={...p.params,_meta:{...p.params?._meta||{},[sr]:a}});const h=e=>{this._responseHandlers.delete(u),this._progressHandlers.delete(u),this._cleanupTimeout(u),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:u,reason:String(e)}},{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}).catch(e=>this._onerror(new Error(`Failed to send cancellation: ${e}`)));const t=e instanceof Yi?e:new Yi(Tr.RequestTimeout,String(e));d(t)};this._responseHandlers.set(u,e=>{if(!r?.signal?.aborted){if(e instanceof Error)return d(e);try{const r=ga(t,e.result);r.success?c(r.data):d(r.error)}catch(n){d(n)}}}),r?.signal?.addEventListener("abort",()=>{h(r?.signal?.reason)});const f=r?.timeout??6e4;this._setupTimeout(u,f,r?.maxTotalTimeout,()=>h(Yi.fromError(Tr.RequestTimeout,"Request timed out",{timeout:f})),r?.resetTimeoutOnProgress??!1);const m=a?.taskId;m?(this._requestResolvers.set(u,e=>{const t=this._responseHandlers.get(u);t?t(e):this._onerror(new Error(`Response handler missing for side-channeled request ${u}`))}),this._enqueueTaskMessage(m,{type:"request",message:p,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(u),d(e)})):this._transport.send(p,{relatedRequestId:n,resumptionToken:i,onresumptiontoken:o}).catch(e=>{this._cleanupTimeout(u),d(e)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},an,t)}async getTaskResult(e,t,r){return this.request({method:"tasks/result",params:e},t,r)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},ln,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},pn,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);const r=t?.relatedTask?.taskId;if(r){const n={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[sr]:t.relatedTask}}};return void(await this._enqueueTaskMessage(r,{type:"notification",message:n,timestamp:Date.now()}))}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;return this._pendingDebouncedNotifications.add(e.method),void Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let r={...e,jsonrpc:"2.0"};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[sr]:t.relatedTask}}}),this._transport?.send(r,t).catch(e=>this._onerror(e))})}let n={...e,jsonrpc:"2.0"};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[sr]:t.relatedTask}}}),await this._transport.send(n,t)}setRequestHandler(e,t){const r=ba(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(r,n)=>{const i=ka(e,r);return Promise.resolve(t(i,n))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){const r=ba(e);this._notificationHandlers.set(r,r=>{const n=ka(e,r);return Promise.resolve(t(n))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){const t=this._taskProgressTokens.get(e);void 0!==t&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");const n=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,r??this._transport?.sessionId,n)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){const r=await this._taskMessageQueue.dequeueAll(e,t);for(const t of r)if("request"===t.type&&kr(t.message)){const r=t.message.id,n=this._requestResolvers.get(r);n?(n(new Yi(Tr.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(r)):this._onerror(new Error(`Resolver missing for request ${r} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,r){let n=this._options?.defaultTaskPollInterval??1e3;try{const t=await(this._taskStore?.getTask(e,r));t?.pollInterval&&(n=t.pollInterval)}catch{}return new Promise((e,r)=>{if(t.aborted)return void r(new Yi(Tr.InvalidRequest,"Request cancelled"));const i=setTimeout(e,n);t.addEventListener("abort",()=>{clearTimeout(i),r(new Yi(Tr.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){const r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async n=>{if(!e)throw new Error("No request provided");return await r.createTask(n,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{const n=await r.getTask(e,t);if(!n)throw new Yi(Tr.InvalidParams,"Failed to retrieve task: Task not found");return n},storeTaskResult:async(e,n,i)=>{await r.storeTaskResult(e,n,i,t);const o=await r.getTask(e,t);if(o){const t=on.parse({method:"notifications/tasks/status",params:o});await this.notification(t),_a(o.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>r.getTaskResult(e,t),updateTaskStatus:async(e,n,i)=>{const o=await r.getTask(e,t);if(!o)throw new Yi(Tr.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(_a(o.status))throw new Yi(Tr.InvalidParams,`Cannot update task "${e}" from terminal status "${o.status}" to "${n}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(e,n,i,t);const s=await r.getTask(e,t);if(s){const t=on.parse({method:"notifications/tasks/status",params:s});await this.notification(t),_a(s.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>r.listTasks(e,t)}}}function Sa(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}class Ca{constructor(e){this._client=e}async*callToolStream(e,t=ni,r){const n=this._client,i={...r,task:r?.task??(n.isToolTask(e.name)?{}:void 0)},o=n.requestStream({method:"tools/call",params:e},t,i),s=n.getToolOutputValidator(e.name);for await(const c of o){if("result"===c.type&&s){const t=c.result;if(!t.structuredContent&&!t.isError)return void(yield{type:"error",error:new Yi(Tr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)});if(t.structuredContent)try{const e=s(t.structuredContent);if(!e.valid)return void(yield{type:"error",error:new Yi(Tr.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)})}catch(a){return a instanceof Yi?void(yield{type:"error",error:a}):void(yield{type:"error",error:new Yi(Tr.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)})}}yield c}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,r){return this._client.getTaskResult({taskId:e},t,r)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,r){return this._client.requestStream(e,t,r)}}function Ta(e,t){if(e&&null!==t&&"object"==typeof t){if("object"===e.type&&e.properties&&"object"==typeof e.properties){const r=t,n=e.properties;for(const e of Object.keys(n)){const t=n[e];void 0===r[e]&&Object.prototype.hasOwnProperty.call(t,"default")&&(r[e]=t.default),void 0!==r[e]&&Ta(t,r[e])}}if(Array.isArray(e.anyOf))for(const r of e.anyOf)"boolean"!=typeof r&&Ta(r,t);if(Array.isArray(e.oneOf))for(const r of e.oneOf)"boolean"!=typeof r&&Ta(r,t)}}class xa extends Ia{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??(()=>{throw new Error("An explicit browser JSON Schema validator is required.")})(),t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",si,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Qn,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",An,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new Ca(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=function(e,t){const r={...e};for(const n in t){const e=n,i=t[e];if(void 0===i)continue;const o=r[e];r[e]=Sa(o)&&Sa(i)?{...o,...i}:i}return r}(this._capabilities,e)}setRequestHandler(e,t){const r=va(e),n=r?.method;if(!n)throw new Error("Schema is missing a method literal");const i=ya(n);if("string"!=typeof i)throw new Error("Schema method literal must be a string");return super.setRequestHandler(e,"elicitation/create"===i?async(e,r)=>{const n=ga(zi,e);if(!n.success){const e=n.error instanceof Error?n.error.message:String(n.error);throw new Yi(Tr.InvalidParams,`Invalid elicitation request: ${e}`)}const{params:i}=n.data;i.mode=i.mode??"form";const{supportsFormMode:o,supportsUrlMode:s}=function(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};const t=void 0!==e.form,r=void 0!==e.url;return{supportsFormMode:t||!t&&!r,supportsUrlMode:r}}(this._capabilities.elicitation);if("form"===i.mode&&!o)throw new Yi(Tr.InvalidParams,"Client does not support form-mode elicitation requests");if("url"===i.mode&&!s)throw new Yi(Tr.InvalidParams,"Client does not support URL-mode elicitation requests");const a=await Promise.resolve(t(e,r));if(i.task){const e=ga(rn,a);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Yi(Tr.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const c=ga(Di,a);if(!c.success){const e=c.error instanceof Error?c.error.message:String(c.error);throw new Yi(Tr.InvalidParams,`Invalid elicitation result: ${e}`)}const d=c.data,l="form"===i.mode?i.requestedSchema:void 0;if("form"===i.mode&&"accept"===d.action&&d.content&&l&&this._capabilities.elicitation?.form?.applyDefaults)try{Ta(l,d.content)}catch{}return d}:"sampling/createMessage"===i?async(e,r)=>{const n=ga(bi,e);if(!n.success){const e=n.error instanceof Error?n.error.message:String(n.error);throw new Yi(Tr.InvalidParams,`Invalid sampling request: ${e}`)}const{params:i}=n.data,o=await Promise.resolve(t(e,r));if(i.task){const e=ga(rn,o);if(!e.success){const t=e.error instanceof Error?e.error.message:String(e.error);throw new Yi(Tr.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}const s=ga(i.tools||i.toolChoice?Ii:ki,o);if(!s.success){const e=s.error instanceof Error?s.error.message:String(s.error);throw new Yi(Tr.InvalidParams,`Invalid sampling result: ${e}`)}return s.data}:t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),void 0===e.sessionId)try{const r=await this.request({method:"initialize",params:{protocolVersion:ir,capabilities:this._capabilities,clientInfo:this._clientInfo}},Wr,t);if(void 0===r)throw new Error(`Server sent invalid initialize result: ${r}`);if(!or.includes(r.protocolVersion))throw new Error(`Server's protocol version is not supported: ${r.protocolVersion}`);this._serverCapabilities=r.capabilities,this._serverVersion=r.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(r.protocolVersion),this._instructions=r.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(r){throw this.close(),r}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if("resources/subscribe"===e&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if("notifications/roots/list_changed"===e&&!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){!function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);if("tools/call"===t&&!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`)}(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&function(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`)}}(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},Pr,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},Ji,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},Pr,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},Zn,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},zn,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},kn,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},Sn,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},$n,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},Pr,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},Pr,t)}async callTool(e,t=ni,r){if(this.isToolTaskRequired(e.name))throw new Yi(Tr.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);const n=await this.request({method:"tools/call",params:e},t,r),i=this.getToolOutputValidator(e.name);if(i){if(!n.structuredContent&&!n.isError)throw new Yi(Tr.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(n.structuredContent)try{const e=i(n.structuredContent);if(!e.valid)throw new Yi(Tr.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(o){if(o instanceof Yi)throw o;throw new Yi(Tr.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return n}isToolTask(e){return!!this._serverCapabilities?.tasks?.requests?.tools?.call&&this._cachedKnownTaskTools.has(e)}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(const t of e){if(t.outputSchema){const e=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,e)}const e=t.execution?.taskSupport;"required"!==e&&"optional"!==e||this._cachedKnownTaskTools.add(t.name),"required"===e&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){const r=await this.request({method:"tools/list",params:e},ri,t);return this.cacheToolMetadata(r.tools),r}_setupListChangedHandler(e,t,r,n){const i=ai.safeParse(r);if(!i.success)throw new Error(`Invalid ${e} listChanged options: ${i.error.message}`);if("function"!=typeof r.onChanged)throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);const{autoRefresh:o,debounceMs:s}=i.data,{onChanged:a}=r,c=async()=>{if(o)try{const e=await n();a(null,e)}catch(e){const t=e instanceof Error?e:new Error(String(e));a(t,null)}else a(null,null)};this.setNotificationHandler(t,()=>{if(s){const t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);const r=setTimeout(c,s);this._listChangedDebounceTimers.set(e,r)}else c()})}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}class $a extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}}const Aa=32;function Pa(e){}function Ea(e){if("function"==typeof e)throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");const{onEvent:t=Pa,onError:r=Pa,onRetry:n=Pa,onComment:i,maxBufferSize:o}=e,s=[];let a,c,d=0,l=!0,u="",p=0,h=!1;function f(){void 0!==o&&(d+u.length<=o||(h=!0,s.length=0,d=0,a=void 0,u="",p=0,c=void 0,r(new $a(`Buffered data exceeded max buffer size of ${o} characters`,{type:"max-buffer-size-exceeded"}))))}function m(e){let r=0;if(-1===e.indexOf("\r")){let n=e.indexOf("\n",r);for(;-1!==n;){if(r===n){p>0&&t({id:a,event:c,data:u}),a=void 0,u="",p=0,c=void 0,r=n+1,n=e.indexOf("\n",r);continue}const i=e.charCodeAt(r);if(Oa(e,r,i)){const i=e.charCodeAt(r+5)===Aa?r+6:r+5,o=e.slice(i,n);if(0===p&&10===e.charCodeAt(n+1)){t({id:a,event:c,data:o}),a=void 0,u="",c=void 0,r=n+2,n=e.indexOf("\n",r);continue}u=0===p?o:`${u}\n${o}`,p++}else Ra(e,r,i)?c=e.slice(e.charCodeAt(r+6)===Aa?r+7:r+6,n)||void 0:w(e,r,n);r=n+1,n=e.indexOf("\n",r)}return e.slice(r)}for(;r<e.length;){const t=e.indexOf("\r",r),n=e.indexOf("\n",r);let i=-1;if(-1!==t&&-1!==n?i=t<n?t:n:-1!==t?i=t===e.length-1?-1:t:-1!==n&&(i=n),-1===i)break;w(e,r,i),r=i+1,13===e.charCodeAt(r-1)&&10===e.charCodeAt(r)&&r++}return e.slice(r)}function w(e,r,n){if(r===n)return p>0&&t({id:a,event:c,data:u}),a=void 0,u="",p=0,void(c=void 0);const o=e.charCodeAt(r);if(Oa(e,r,o)){const t=e.charCodeAt(r+5)===Aa?r+6:r+5,i=e.slice(t,n);return u=0===p?i:`${u}\n${i}`,void p++}if(Ra(e,r,o))return void(c=e.slice(e.charCodeAt(r+6)===Aa?r+7:r+6,n)||void 0);if(105===o&&100===e.charCodeAt(r+1)&&58===e.charCodeAt(r+2)){const t=e.slice(e.charCodeAt(r+3)===Aa?r+4:r+3,n);return void(t.includes("\0")||(a=t))}if(58===o){if(i){const t=e.slice(r,n);i(t.slice(e.charCodeAt(r+1)===Aa?2:1))}return}const s=e.slice(r,n),d=s.indexOf(":");if(-1===d)return void g(s,"",s);const l=s.slice(0,d),h=s.charCodeAt(d+1)===Aa?2:1;g(l,s.slice(d+h),s)}function g(e,t,i){switch(e){case"event":c=t||void 0;break;case"data":u=0===p?t:`${u}\n${t}`,p++;break;case"id":t.includes("\0")||(a=t);break;case"retry":/^\d+$/.test(t)?n(parseInt(t,10)):r(new $a(`Invalid \`retry\` value: "${t}"`,{type:"invalid-retry",value:t,line:i}));break;default:r(new $a(`Unknown field "${e.length>20?`${e.slice(0,20)}…`:e}"`,{type:"unknown-field",field:e,value:t,line:i}))}}return{feed:function(e){if(h)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(l&&(l=!1,239===e.charCodeAt(0)&&187===e.charCodeAt(1)&&191===e.charCodeAt(2)&&(e=e.slice(3))),0===s.length){const t=m(e);return""!==t&&(s.push(t),d=t.length),void f()}if(-1===e.indexOf("\n")&&-1===e.indexOf("\r"))return s.push(e),d+=e.length,void f();s.push(e);const t=s.join("");s.length=0,d=0;const r=m(t);""!==r&&(s.push(r),d=r.length),f()},reset:function(e={}){if(e.consume&&s.length>0){const e=s.join("");w(e,0,e.length)}l=!0,a=void 0,u="",p=0,c=void 0,s.length=0,d=0,h=!1}}}function Oa(e,t,r){return 100===r&&97===e.charCodeAt(t+1)&&116===e.charCodeAt(t+2)&&97===e.charCodeAt(t+3)&&58===e.charCodeAt(t+4)}function Ra(e,t,r){return 101===r&&118===e.charCodeAt(t+1)&&101===e.charCodeAt(t+2)&&110===e.charCodeAt(t+3)&&116===e.charCodeAt(t+4)&&58===e.charCodeAt(t+5)}class Ma extends Event{constructor(e,t){var r,n;super(e),this.code=null!=(r=null==t?void 0:t.code)?r:void 0,this.message=null!=(n=null==t?void 0:t.message)?n:void 0}[Symbol.for("nodejs.util.inspect.custom")](e,t,r){return r(Ua(this),t)}[Symbol.for("Deno.customInspect")](e,t){return e(Ua(this),t)}}function qa(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(qa).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${qa(e.cause)}`:e.message:`${e}`}function Ua(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var La,ja,za,Na,Ha,Da,Va,Fa,Wa,Ba,Ja,Ga,Ka,Za,Qa,Ya,Xa,ec,tc,rc,nc,ic,oc,sc=e=>{throw TypeError(e)},ac=(e,t,r)=>t.has(e)||sc("Cannot "+r),cc=(e,t,r)=>(ac(e,t,"read from private field"),r?r.call(e):t.get(e)),dc=(e,t,r)=>t.has(e)?sc("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),lc=(e,t,r,n)=>(ac(e,t,"write to private field"),t.set(e,r),r),uc=(e,t,r)=>(ac(e,t,"access private method"),r);class pc extends EventTarget{constructor(e,t){var r,n;super(),dc(this,Za),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,dc(this,La),dc(this,ja),dc(this,za),dc(this,Na),dc(this,Ha),dc(this,Da),dc(this,Va),dc(this,Fa,null),dc(this,Wa),dc(this,Ba),dc(this,Ja,null),dc(this,Ga,null),dc(this,Ka,null),dc(this,Ya,async e=>{var t;cc(this,Ba).reset();const{body:r,redirected:n,status:i,headers:o}=e;if(204===i)return uc(this,Za,nc).call(this,"Server sent HTTP 204, not reconnecting",204),void this.close();if(lc(this,za,n?new URL(e.url):void 0),200!==i)return void uc(this,Za,nc).call(this,`Non-200 status code (${i})`,i);if(!(o.get("content-type")||"").startsWith("text/event-stream"))return void uc(this,Za,nc).call(this,'Invalid content type, expected "text/event-stream"',i);if(cc(this,La)===this.CLOSED)return;lc(this,La,this.OPEN);const s=new Event("open");if(null==(t=cc(this,Ka))||t.call(this,s),this.dispatchEvent(s),"object"!=typeof r||!r||!("getReader"in r))return uc(this,Za,nc).call(this,"Invalid response body, expected a web ReadableStream",i),void this.close();const a=new TextDecoder,c=r.getReader();let d=!0;do{const{done:e,value:t}=await c.read();t&&cc(this,Ba).feed(a.decode(t,{stream:!e})),e&&(d=!1,cc(this,Ba).reset(),uc(this,Za,ic).call(this))}while(d)}),dc(this,Xa,e=>{lc(this,Wa,void 0),"AbortError"!==e.name&&"aborted"!==e.type&&uc(this,Za,ic).call(this,qa(e))}),dc(this,tc,e=>{"string"==typeof e.id&&lc(this,Fa,e.id);const t=new MessageEvent(e.event||"message",{data:e.data,origin:cc(this,za)?cc(this,za).origin:cc(this,ja).origin,lastEventId:e.id||""});cc(this,Ga)&&(!e.event||"message"===e.event)&&cc(this,Ga).call(this,t),this.dispatchEvent(t)}),dc(this,rc,e=>{lc(this,Da,e)}),dc(this,oc,()=>{lc(this,Va,void 0),cc(this,La)===this.CONNECTING&&uc(this,Za,Qa).call(this)});try{if(e instanceof URL)lc(this,ja,e);else{if("string"!=typeof e)throw new Error("Invalid URL");lc(this,ja,new URL(e,function(){const e="document"in globalThis?globalThis.document:void 0;return e&&"object"==typeof e&&"baseURI"in e&&"string"==typeof e.baseURI?e.baseURI:void 0}()))}}catch{throw function(e){const t=globalThis.DOMException;return"function"==typeof t?new t(e,"SyntaxError"):new SyntaxError(e)}("An invalid or illegal string was specified")}lc(this,Ba,Ea({onEvent:cc(this,tc),onRetry:cc(this,rc)})),lc(this,La,this.CONNECTING),lc(this,Da,3e3),lc(this,Ha,null!=(r=null==t?void 0:t.fetch)?r:globalThis.fetch),lc(this,Na,null!=(n=null==t?void 0:t.withCredentials)&&n),uc(this,Za,Qa).call(this)}get readyState(){return cc(this,La)}get url(){return cc(this,ja).href}get withCredentials(){return cc(this,Na)}get onerror(){return cc(this,Ja)}set onerror(e){lc(this,Ja,e)}get onmessage(){return cc(this,Ga)}set onmessage(e){lc(this,Ga,e)}get onopen(){return cc(this,Ka)}set onopen(e){lc(this,Ka,e)}addEventListener(e,t,r){super.addEventListener(e,t,r)}removeEventListener(e,t,r){super.removeEventListener(e,t,r)}close(){cc(this,Va)&&clearTimeout(cc(this,Va)),cc(this,La)!==this.CLOSED&&(cc(this,Wa)&&cc(this,Wa).abort(),lc(this,La,this.CLOSED),lc(this,Wa,void 0))}}La=new WeakMap,ja=new WeakMap,za=new WeakMap,Na=new WeakMap,Ha=new WeakMap,Da=new WeakMap,Va=new WeakMap,Fa=new WeakMap,Wa=new WeakMap,Ba=new WeakMap,Ja=new WeakMap,Ga=new WeakMap,Ka=new WeakMap,Za=new WeakSet,Qa=function(){lc(this,La,this.CONNECTING),lc(this,Wa,new AbortController),cc(this,Ha)(cc(this,ja),uc(this,Za,ec).call(this)).then(cc(this,Ya)).catch(cc(this,Xa))},Ya=new WeakMap,Xa=new WeakMap,ec=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...cc(this,Fa)?{"Last-Event-ID":cc(this,Fa)}:void 0},cache:"no-store",signal:null==(e=cc(this,Wa))?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},tc=new WeakMap,rc=new WeakMap,nc=function(e,t){var r;cc(this,La)!==this.CLOSED&&lc(this,La,this.CLOSED);const n=new Ma("error",{code:t,message:e});null==(r=cc(this,Ja))||r.call(this,n),this.dispatchEvent(n)},ic=function(e,t){var r;if(cc(this,La)===this.CLOSED)return;lc(this,La,this.CONNECTING);const n=new Ma("error",{code:t,message:e});null==(r=cc(this,Ja))||r.call(this,n),this.dispatchEvent(n),lc(this,Va,setTimeout(cc(this,oc),cc(this,Da)))},oc=new WeakMap,pc.CONNECTING=0,pc.OPEN=1,pc.CLOSED=2;class hc extends Error{constructor(e,t,r){super(`SSE error: ${t}`),this.code=e,this.event=r}}class fc{constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._eventSourceInit=t?.eventSourceInit,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Fo(t?.fetch,t?.requestInit),this._followRedirects="follow"===t?.redirectPolicy,this._followRedirects&&(this._fetch=Ko(this._fetch),this._fetchWithInit=Ko(this._fetchWithInit))}_unfollowedRedirect(e,t){const r=Qo(e,t);return r&&!this._followRedirects?`${r} (redirectPolicy: 'same-origin')`:r}async _authThenStart(){if(!this._authProvider)throw new Yo("No auth provider");let e;try{e=await ss(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if("AUTHORIZED"!==e)throw new Yo;return await this._startOrAuth()}async _commonHeaders(){const e={};if(this._authProvider){const t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=Vo(this._requestInit?.headers);return new Headers({...e,...t})}_startOrAuth(){const e=this?._eventSourceInit?.fetch??this._fetch??fetch,t=this._followRedirects?e:Zo(e);let r;return new Promise((e,n)=>{this._eventSource=new pc(this._url.href,{...this._eventSourceInit,fetch:async(e,n)=>{const i=await this._commonHeaders();i.set("Accept","text/event-stream");const o=await t(e,{...n,headers:i});if(r=this._unfollowedRedirect(o,e),401===o.status&&o.headers.has("www-authenticate")){const{resourceMetadataUrl:e,scope:t}=cs(o);this._resourceMetadataUrl=e,this._scope=t}return o}}),this._abortController=new AbortController,this._eventSource.onerror=t=>{if(401===t.code&&this._authProvider)return void this._authThenStart().then(e,n);const i=new hc(t.code,r??t.message,t);n(i),this.onerror?.(i)},this._eventSource.onopen=()=>{},this._eventSource.addEventListener("endpoint",t=>{const r=t;try{if(this._endpoint=new URL(r.data,this._url),this._endpoint.origin!==this._url.origin)throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`)}catch(i){return n(i),this.onerror?.(i),void this.close()}e()}),this._eventSource.onmessage=e=>{const t=e;let r;try{r=Ar.parse(JSON.parse(t.data))}catch(n){return void this.onerror?.(n)}this.onmessage?.(r)}})}async start(){if(this._eventSource)throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");return await this._startOrAuth()}async finishAuth(e){if(!this._authProvider)throw new Yo("No auth provider");if("AUTHORIZED"!==await ss(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new Yo("Failed to authorize")}async close(){this._abortController?.abort(),this._eventSource?.close(),this.onclose?.()}async send(e){if(!this._endpoint)throw new Error("Not connected");try{const t=await this._commonHeaders();t.set("content-type","application/json");const r={...this._requestInit,method:"POST",headers:t,body:JSON.stringify(e),signal:this._abortController?.signal},n=await Zo(this._fetch??fetch)(this._endpoint,r);if(!n.ok){const t=await n.text().catch(()=>null);if(401===n.status&&this._authProvider){const{resourceMetadataUrl:t,scope:r}=cs(n);if(this._resourceMetadataUrl=t,this._scope=r,"AUTHORIZED"!==await ss(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new Yo;return this.send(e)}throw new Error(`Error POSTing to endpoint (HTTP ${n.status}): ${this._unfollowedRedirect(n,this._endpoint)??t}`)}await(n.body?.cancel())}catch(t){throw this.onerror?.(t),t}}setProtocolVersion(e){this._protocolVersion=e}}var mc,wc={};const gc=re(function(){if(mc)return wc;mc=1;var e=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,t=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,n=/\\([\u000b\u0020-\u00ff])/g,i=/([\\"])/g,o=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function s(e){var n=String(e);if(r.test(n))return n;if(n.length>0&&!t.test(n))throw new TypeError("invalid parameter value");return'"'+n.replace(i,"\\$1")+'"'}function a(e){this.parameters=Object.create(null),this.type=e}return wc.format=function(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var t=e.parameters,n=e.type;if(!n||!o.test(n))throw new TypeError("invalid type");var i=n;if(t&&"object"==typeof t)for(var a,c=Object.keys(t).sort(),d=0;d<c.length;d++){if(!r.test(a=c[d]))throw new TypeError("invalid parameter name");i+="; "+a+"="+s(t[a])}return i},wc.parse=function(t){if(!t)throw new TypeError("argument string is required");var r="object"==typeof t?function(e){var t;if("function"==typeof e.getHeader?t=e.getHeader("content-type"):"object"==typeof e.headers&&(t=e.headers&&e.headers["content-type"]),"string"!=typeof t)throw new TypeError("content-type header is missing from object");return t}(t):t;if("string"!=typeof r)throw new TypeError("argument string is required to be a string");var i=r.indexOf(";"),s=-1!==i?r.slice(0,i).trim():r.trim();if(!o.test(s))throw new TypeError("invalid media type");var c=new a(s.toLowerCase());if(-1!==i){var d,l,u;for(e.lastIndex=i;l=e.exec(r);){if(l.index!==i)throw new TypeError("invalid parameter format");i+=l[0].length,d=l[1].toLowerCase(),34===(u=l[2]).charCodeAt(0)&&-1!==(u=u.slice(1,-1)).indexOf("\\")&&(u=u.replace(n,"$1")),c.parameters[d]=u}if(i!==r.length)throw new TypeError("invalid parameter format")}return c},wc}());class vc extends TransformStream{constructor({onError:e,onRetry:t,onComment:r,maxBufferSize:n}={}){let i;super({start(o){i=Ea({onEvent:e=>{o.enqueue(e)},onError(t){"function"==typeof e&&e(t),("terminate"===e||"max-buffer-size-exceeded"===t.type)&&o.error(t)},onRetry:t,onComment:r,maxBufferSize:n})},transform(e){i.feed(e)}})}}const yc={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2};class _c extends Error{constructor(e,t){super(`Streamable HTTP error: ${t}`),this.code=e}}class bc{constructor(e,t){this._hasCompletedAuthFlow=!1,this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._authProvider=t?.authProvider,this._fetch=t?.fetch,this._fetchWithInit=Fo(t?.fetch,t?.requestInit),this._followRedirects="follow"===t?.redirectPolicy,this._followRedirects&&(this._fetch=Ko(this._fetch),this._fetchWithInit=Ko(this._fetchWithInit)),this._sessionId=t?.sessionId,this._reconnectionOptions=t?.reconnectionOptions??yc}_unfollowedRedirect(e,t){const r=Qo(e,t);return r&&!this._followRedirects?`${r} (redirectPolicy: 'same-origin')`:r}async _authThenStart(){if(!this._authProvider)throw new Yo("No auth provider");let e;try{e=await ss(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(t){throw this.onerror?.(t),t}if("AUTHORIZED"!==e)throw new Yo;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){const e={};if(this._authProvider){const t=await this._authProvider.tokens();t&&(e.Authorization=`Bearer ${t.access_token}`)}this._sessionId&&(e["mcp-session-id"]=this._sessionId),this._protocolVersion&&(e["mcp-protocol-version"]=this._protocolVersion);const t=Vo(this._requestInit?.headers);return new Headers({...e,...t})}async _startOrAuthSse(e){const{resumptionToken:t}=e;try{const r=await this._commonHeaders();r.set("Accept","text/event-stream"),t&&r.set("last-event-id",t);const n=this._fetch??fetch,i={method:"GET",headers:r,signal:this._abortController?.signal};let o=await n(this._url,this._followRedirects?i:{...i,redirect:"manual"});const s=this._followRedirects?void 0:Jo(n,this._url,i,o);if(s&&(o=await s),!o.ok){if(await(o.body?.cancel()),401===o.status&&this._authProvider)return await this._authThenStart();if(405===o.status)return;throw new _c(o.status,`Failed to open SSE stream: ${this._unfollowedRedirect(o,this._url)??o.statusText}`)}this._handleSseStream(o.body,e,!0)}catch(r){throw this.onerror?.(r),r}}_getNextReconnectionDelay(e){if(void 0!==this._serverRetryMs)return this._serverRetryMs;const t=this._reconnectionOptions.maxReconnectionDelay;return Math.min(this._reconnectionOptions.initialReconnectionDelay*Math.pow(this._reconnectionOptions.reconnectionDelayGrowFactor,e),t)}_scheduleReconnection(e,t=0){const r=this._reconnectionOptions.maxRetries;if(t>=r)return void this.onerror?.(new Error(`Maximum reconnection attempts (${r}) exceeded.`));const n=this._getNextReconnectionDelay(t);this._reconnectionTimeout=setTimeout(()=>{this._startOrAuthSse(e).catch(r=>{this.onerror?.(new Error(`Failed to reconnect SSE stream: ${r instanceof Error?r.message:String(r)}`)),this._scheduleReconnection(e,t+1)})},n)}_handleSseStream(e,t,r){if(!e)return;const{onresumptiontoken:n,replayMessageId:i}=t;let o,s=!1,a=!1;(async()=>{try{const c=e.pipeThrough(new TextDecoderStream).pipeThrough(new vc({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){const{value:e,done:r}=await c.read();if(r)break;if(e.id&&(o=e.id,s=!0,n?.(e.id)),e.data&&(!e.event||"message"===e.event))try{const t=Ar.parse(JSON.parse(e.data));Cr(t)&&(a=!0,void 0!==i&&(t.id=i)),this.onmessage?.(t)}catch(t){this.onerror?.(t)}}(r||s)&&!a&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:o,onresumptiontoken:n,replayMessageId:i},0)}catch(t){if(this.onerror?.(new Error(`SSE stream disconnected: ${t}`)),(r||s)&&!a&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:o,onresumptiontoken:n,replayMessageId:i},0)}catch(c){this.onerror?.(new Error(`Failed to reconnect: ${c instanceof Error?c.message:String(c)}`))}}})()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(e){if(!this._authProvider)throw new Yo("No auth provider");if("AUTHORIZED"!==await ss(this._authProvider,{serverUrl:this._url,authorizationCode:e,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new Yo("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(e,t){try{const{resumptionToken:r,onresumptiontoken:n}=t||{};if(r)return void this._startOrAuthSse({resumptionToken:r,replayMessageId:kr(e)?e.id:void 0}).catch(e=>this.onerror?.(e));const i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");const o={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(e),signal:this._abortController?.signal},s=await Zo(this._fetch??fetch)(this._url,o),a=s.headers.get("mcp-session-id");if(a&&(this._sessionId=a),!s.ok){const t=await s.text().catch(()=>null);if(401===s.status&&this._authProvider){if(this._hasCompletedAuthFlow)throw new _c(401,"Server returned 401 after successful authentication");const{resourceMetadataUrl:t,scope:r}=cs(s);if(this._resourceMetadataUrl=t,this._scope=r,"AUTHORIZED"!==await ss(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit}))throw new Yo;return this._hasCompletedAuthFlow=!0,this.send(e)}if(403===s.status&&this._authProvider){const{resourceMetadataUrl:t,scope:r,error:n}=cs(s);if("insufficient_scope"===n){const n=s.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===n)throw new _c(403,"Server returned 403 after trying upscoping");if(r&&(this._scope=r),t&&(this._resourceMetadataUrl=t),this._lastUpscopingHeader=n??void 0,"AUTHORIZED"!==await ss(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch}))throw new Yo;return this.send(e)}}throw new _c(s.status,`Error POSTing to endpoint: ${this._unfollowedRedirect(s,this._url)??t}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,202===s.status)return await(s.body?.cancel()),void(Br.safeParse(e).success&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e)));const c=(Array.isArray(e)?e:[e]).filter(e=>"method"in e&&"id"in e&&void 0!==e.id).length>0,d=s.headers.get("content-type"),l=function(e){if(e)try{return gc.parse(e).type}catch{const t=(e.split(";",1)[0]??"").trim().toLowerCase();if(""===t||e.slice(t.length).includes(","))return;return t}}(d);if(c)if("text/event-stream"===l)this._handleSseStream(s.body,{onresumptiontoken:n},!1);else{if("application/json"!==l)throw await(s.body?.cancel()),new _c(-1,`Unexpected content type: ${d}`);{const e=await s.json(),t=Array.isArray(e)?e.map(e=>Ar.parse(e)):[Ar.parse(e)];for(const r of t)this.onmessage?.(r)}}else await(s.body?.cancel())}catch(r){throw this.onerror?.(r),r}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{const e=await this._commonHeaders(),t={...this._requestInit,method:"DELETE",headers:e,signal:this._abortController?.signal},r=await Zo(this._fetch??fetch)(this._url,t);if(await(r.body?.cancel()),!r.ok&&405!==r.status)throw new _c(r.status,`Failed to terminate session: ${this._unfollowedRedirect(r,this._url)??r.statusText}`);this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}}function kc(e,t){const r=typeof e;if(r!==typeof t)return!1;const n=Array.isArray(e);if(n!==Array.isArray(t))return!1;if(n){const r=e.length;if(r!==t.length)return!1;for(let n=0;n<r;n++)if(!kc(e[n],t[n]))return!1;return!0}if("object"===r){if(!e||!t)return e===t;const r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(const i of r){if(!Object.prototype.hasOwnProperty.call(t,i))return!1;if(!kc(e[i],t[i]))return!1}return!0}return e===t}function Ic(e){return encodeURI(function(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}(e))}const Sc={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Cc={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Tc={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,dependentRequired:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};let xc="undefined"!=typeof self&&self.location&&"null"!==self.location.origin?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function $c(e,t=Object.create(null),r=xc,n=""){if(e&&"object"==typeof e&&!Array.isArray(e)){const i=e.$id||e.id;if(i){const o=new URL(i,r.href);o.hash.length>1?t[o.href]=e:(o.hash="",""===n?r=o:$c(e,t,r))}}else if(!0!==e&&!1!==e)return t;const i=r.href+(n?"#"+n:"");if(void 0!==t[i]&&t[i]!==e)throw new Error(`Duplicate schema URI "${i}".`);if(t[i]=e,!0===e||!1===e)return t;if(void 0===e.__absolute_uri__&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&void 0===e.__absolute_ref__){const t=new URL(e.$ref,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&void 0===e.__absolute_recursive_ref__){const t=new URL(e.$recursiveRef,r.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}e.$anchor&&(t[new URL("#"+e.$anchor,r.href).href]=e);for(let o in e){if(Tc[o])continue;const i=`${n}/${Ic(o)}`,s=e[o];if(Array.isArray(s)){if(Sc[o]){const e=s.length;for(let n=0;n<e;n++)$c(s[n],t,r,`${i}/${n}`)}}else if(Cc[o])for(let e in s)$c(s[e],t,r,`${i}/${Ic(e)}`);else $c(s,t,r,i)}return t}const Ac=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Pc=[0,31,28,31,30,31,30,31,31,30,31,30,31],Ec=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;function Oc(e){return e.test.bind(e)}const Rc={date:Mc,time:qc.bind(void 0,!1),"date-time":function(e){const[t,r,n]=e.split(Uc);return void 0!==t&&void 0!==r&&void 0===n&&Mc(t)&&qc(!0,r)},duration:e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),uri:function(e){return Lc.test(e)&&jc.test(e)},"uri-reference":Oc(/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i),"uri-template":Oc(/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i),url:Oc(/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu),email:e=>{if('"'===e[0])return!1;const[t,r,...n]=e.split("@");return!(!t||!r||0!==n.length||t.length>64||r.length>253)&&"."!==t[0]&&!t.endsWith(".")&&!t.includes("..")&&!(!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t))&&r.split(".").every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},hostname:Oc(/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i),ipv4:Oc(/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/),ipv6:Oc(/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i),regex:function(e){if(zc.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}},uuid:Oc(/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i),"json-pointer":Oc(/^(?:\/(?:[^~/]|~0|~1)*)*$/),"json-pointer-uri-fragment":Oc(/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i),"relative-json-pointer":Oc(/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/)};function Mc(e){const t=e.match(Ac);if(!t)return!1;const r=t[1],n=t[2],i=t[3];if(!r||!n||!i)return!1;const o=+n,s=+i,a=2!=o||(c=+r)%4!=0||c%100==0&&c%400!=0?Pc[o]:29;var c;return o>=1&&o<=12&&s>=1&&void 0!==a&&s<=a}function qc(e,t){const r=t.match(Ec);if(!r)return!1;const n=r[1],i=r[2],o=r[3];if(!n||!i||!o)return!1;const s=+n,a=+i,c=+o;return(s<=23&&a<=59&&c<=59||23==s&&59==a&&60==c)&&(!e||!!r[5])}const Uc=/t|\s/i,Lc=/\/|:/,jc=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,zc=/[^\\]\\Z/;function Nc(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Hc(e){const t=Math.abs(e).toString().split("e"),r=t[0],n=t[1]??"0",i=r.indexOf("."),o=-1===i?0:r.length-i-1;return[BigInt(r.replace(".","")),Number(n)-o]}function Dc(e,t,r="2019-09",n=$c(t),i=!0,o=null,s="#",a="#",c=Object.create(null)){if(!0===t)return{valid:!0,errors:[]};if(!1===t)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};const d=typeof e;let l;switch(d){case"boolean":case"number":case"string":l=d;break;case"object":l=null===e?"null":Array.isArray(e)?"array":"object";break;default:throw new Error(`Instances of "${d}" type are not supported.`)}const{$ref:u,$recursiveRef:p,$recursiveAnchor:h,type:f,const:m,enum:w,required:g,not:v,anyOf:y,allOf:_,oneOf:b,if:k,then:I,else:S,format:C,properties:T,patternProperties:x,additionalProperties:$,unevaluatedProperties:A,minProperties:P,maxProperties:E,propertyNames:O,dependentRequired:R,dependentSchemas:M,dependencies:q,prefixItems:U,items:L,additionalItems:j,unevaluatedItems:z,contains:N,minContains:H,maxContains:D,minItems:V,maxItems:F,uniqueItems:W,minimum:B,maximum:J,exclusiveMinimum:G,exclusiveMaximum:K,multipleOf:Z,minLength:Q,maxLength:Y,pattern:X,__absolute_ref__:ee,__absolute_recursive_ref__:te}=t,re=[];if(!0===h&&null===o&&(o=t),"#"===p){const d=`${a}/$recursiveRef`,l=Dc(e,null===o?t:o,r,n,i,null===o?n[te]:o,s,d,c);l.valid||re.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:d,error:"A subschema had errors."},...l.errors)}if(void 0!==u){const t=n[ee||u];if(void 0===t){let e=`Unresolved $ref "${u}".`;throw ee&&ee!==u&&(e+=` Absolute URI "${ee}".`),e+=`\nKnown schemas:\n- ${Object.keys(n).join("\n- ")}`,new Error(e)}const d=`${a}/$ref`,l=Dc(e,t,r,n,i,o,s,d,c);if(l.valid||re.push({instanceLocation:s,keyword:"$ref",keywordLocation:d,error:"A subschema had errors."},...l.errors),"4"===r||"7"===r)return{valid:0===re.length,errors:re}}if(Array.isArray(f)){let t=f.length,r=!1;for(let n=0;n<t;n++)if(l===f[n]||"integer"===f[n]&&"number"===l&&e%1==0&&e==e){r=!0;break}r||re.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${f.join('", "')}".`})}else"integer"===f?("number"!==l||e%1||e!=e)&&re.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${f}".`}):void 0!==f&&l!==f&&re.push({instanceLocation:s,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${l}" is invalid. Expected "${f}".`});if(void 0!==m&&("object"===l||"array"===l?kc(e,m)||re.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(m)}.`}):e!==m&&re.push({instanceLocation:s,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(m)}.`})),void 0!==w&&("object"===l||"array"===l?w.some(t=>kc(e,t))||re.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`}):w.some(t=>e===t)||re.push({instanceLocation:s,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(w)}.`})),void 0!==v){const t=`${a}/not`;Dc(e,v,r,n,i,o,s,t).valid&&re.push({instanceLocation:s,keyword:"not",keywordLocation:t,error:'Instance matched "not" schema.'})}let ne=[];if(void 0!==y){const t=`${a}/anyOf`,d=re.length;let l=!1;for(const[a,u]of y.entries()){const d=Object.create(c),p=Dc(e,u,r,n,i,!0===h?o:null,s,`${t}/${a}`,d);re.push(...p.errors),l=l||p.valid,p.valid&&ne.push(d)}l?re.length=d:re.splice(d,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:t,error:"Instance does not match any subschemas."})}if(void 0!==_){const t=`${a}/allOf`,d=re.length;let l=!0;for(const[a,u]of _.entries()){const d=Object.create(c),p=Dc(e,u,r,n,i,!0===h?o:null,s,`${t}/${a}`,d);re.push(...p.errors),l=l&&p.valid,p.valid&&ne.push(d)}l?re.length=d:re.splice(d,0,{instanceLocation:s,keyword:"allOf",keywordLocation:t,error:"Instance does not match every subschema."})}if(void 0!==b){const t=`${a}/oneOf`,d=re.length,l=b.filter((a,d)=>{const l=Object.create(c),u=Dc(e,a,r,n,i,!0===h?o:null,s,`${t}/${d}`,l);return re.push(...u.errors),u.valid&&ne.push(l),u.valid}).length;1===l?re.length=d:re.splice(d,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:t,error:`Instance does not match exactly one subschema (${l} matches).`})}if("object"!==l&&"array"!==l||Object.assign(c,...ne),void 0!==k){const t=`${a}/if`;if(Dc(e,k,r,n,i,o,s,t,c).valid){if(void 0!==I){const d=Dc(e,I,r,n,i,o,s,`${a}/then`,c);d.valid||re.push({instanceLocation:s,keyword:"if",keywordLocation:t,error:'Instance does not match "then" schema.'},...d.errors)}}else if(void 0!==S){const d=Dc(e,S,r,n,i,o,s,`${a}/else`,c);d.valid||re.push({instanceLocation:s,keyword:"if",keywordLocation:t,error:'Instance does not match "else" schema.'},...d.errors)}}if("object"===l){if(void 0!==g)for(const r of g)Nc(e,r)||re.push({instanceLocation:s,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${r}".`});const t=Object.keys(e);if(void 0!==P&&t.length<P&&re.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${P} properties.`}),void 0!==E&&t.length>E&&re.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${E} properties.`}),void 0!==O){const t=`${a}/propertyNames`;for(const a in e){const e=`${s}/${Ic(a)}`,c=Dc(a,O,r,n,i,o,e,t);c.valid||re.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:t,error:`Property name "${a}" does not match schema.`},...c.errors)}}if(void 0!==R){const t=`${a}/dependantRequired`;for(const r in R)if(Nc(e,r)){const n=R[r];for(const i of n)Nc(e,i)||re.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:t,error:`Instance has "${r}" but does not have "${i}".`})}}if(void 0!==M)for(const[u,p]of Object.entries(M)){const t=`${a}/dependentSchemas`;if(Nc(e,u)){const a=Dc(e,p,r,n,i,o,s,`${t}/${Ic(u)}`,c);a.valid||re.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:t,error:`Instance has "${u}" but does not match dependant schema.`},...a.errors)}}if(void 0!==q){const t=`${a}/dependencies`;for(const a in q)if(Nc(e,a)){const c=q[a];if(Array.isArray(c))for(const r of c)Nc(e,r)||re.push({instanceLocation:s,keyword:"dependencies",keywordLocation:t,error:`Instance has "${a}" but does not have "${r}".`});else{const d=Dc(e,c,r,n,i,o,s,`${t}/${Ic(a)}`);d.valid||re.push({instanceLocation:s,keyword:"dependencies",keywordLocation:t,error:`Instance has "${a}" but does not match dependant schema.`},...d.errors)}}}const d=Object.create(null);let l=!1;if(void 0!==T){const t=`${a}/properties`;for(const[a,u]of Object.entries(T)){if(!Nc(e,a))continue;const p=`${s}/${Ic(a)}`,h=Dc(e[a],u,r,n,i,o,p,`${t}/${Ic(a)}`);if(d[a]=!0,h.valid)c[a]=!0;else if(l=i,re.push({instanceLocation:s,keyword:"properties",keywordLocation:t,error:`Property "${a}" does not match schema.`},...h.errors),l)break}}if(!l&&void 0!==x){const t=`${a}/patternProperties`;for(const[a,u]of Object.entries(x)){const p=new RegExp(a,"u");for(const h in e){if(!p.test(h))continue;const f=`${s}/${Ic(h)}`,m=Dc(e[h],u,r,n,i,o,f,`${t}/${Ic(a)}`);d[h]=!0,m.valid?c[h]=!0:(l=i,re.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:t,error:`Property "${h}" matches pattern "${a}" but does not match associated schema.`},...m.errors))}}}if(l||void 0===$){if(!l&&void 0!==A){const t=`${a}/unevaluatedProperties`;for(const a in e)if(!c[a]){const d=`${s}/${Ic(a)}`,l=Dc(e[a],A,r,n,i,o,d,t);l.valid?c[a]=!0:re.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:t,error:`Property "${a}" does not match unevaluated properties schema.`},...l.errors)}}}else{const t=`${a}/additionalProperties`;for(const a in e){if(d[a])continue;const u=`${s}/${Ic(a)}`,p=Dc(e[a],$,r,n,i,o,u,t);p.valid?c[a]=!0:(l=i,re.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:t,error:`Property "${a}" does not match additional properties schema.`},...p.errors))}}}else if("array"===l){void 0!==F&&e.length>F&&re.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${F}).`}),void 0!==V&&e.length<V&&re.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${V}).`});const t=e.length;let d=0,l=!1;if(void 0!==U){const u=`${a}/prefixItems`,p=Math.min(U.length,t);for(;d<p;d++){const t=Dc(e[d],U[d],r,n,i,o,`${s}/${d}`,`${u}/${d}`);if(c[d]=!0,!t.valid&&(l=i,re.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:u,error:"Items did not match schema."},...t.errors),l))break}}if(void 0!==L){const u=`${a}/items`;if(Array.isArray(L)){const a=Math.min(L.length,t);for(;d<a;d++){const t=Dc(e[d],L[d],r,n,i,o,`${s}/${d}`,`${u}/${d}`);if(c[d]=!0,!t.valid&&(l=i,re.push({instanceLocation:s,keyword:"items",keywordLocation:u,error:"Items did not match schema."},...t.errors),l))break}}else for(;d<t;d++){const t=Dc(e[d],L,r,n,i,o,`${s}/${d}`,u);if(c[d]=!0,!t.valid&&(l=i,re.push({instanceLocation:s,keyword:"items",keywordLocation:u,error:"Items did not match schema."},...t.errors),l))break}if(!l&&void 0!==j){const u=`${a}/additionalItems`;for(;d<t;d++){const t=Dc(e[d],j,r,n,i,o,`${s}/${d}`,u);c[d]=!0,t.valid||(l=i,re.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:u,error:"Items did not match additional items schema."},...t.errors))}}}if(void 0!==N)if(0===t&&void 0===H)re.push({instanceLocation:s,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(void 0!==H&&t<H)re.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${t}) than minContains (${H}).`});else{const d=`${a}/contains`,l=re.length;let u=0;for(let a=0;a<t;a++){const t=Dc(e[a],N,r,n,i,o,`${s}/${a}`,d);t.valid?(c[a]=!0,u++):re.push(...t.errors)}u>=(H||0)&&(re.length=l),void 0===H&&0===u?re.splice(l,0,{instanceLocation:s,keyword:"contains",keywordLocation:d,error:"Array does not contain item matching schema."}):void 0!==H&&u<H?re.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${H} items matching schema. Only ${u} items were found.`}):void 0!==D&&u>D&&re.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${D} items matching schema. ${u} items were found.`})}if(!l&&void 0!==z){const l=`${a}/unevaluatedItems`;for(;d<t;d++){if(c[d])continue;const t=Dc(e[d],z,r,n,i,o,`${s}/${d}`,l);c[d]=!0,t.valid||re.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:l,error:"Items did not match unevaluated items schema."},...t.errors)}}if(W)for(let r=0;r<t;r++){const n=e[r],i="object"==typeof n&&null!==n;for(let o=0;o<t;o++){if(r===o)continue;const t=e[o];(n===t||i&&"object"==typeof t&&null!==t&&kc(n,t))&&(re.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${r} and ${o}.`}),r=Number.MAX_SAFE_INTEGER,o=Number.MAX_SAFE_INTEGER)}}}else if("number"===l)"4"===r?(void 0!==B&&(!0===G&&e<=B||e<B)&&re.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${G?"or equal to ":""} ${B}.`}),void 0!==J&&(!0===K&&e>=J||e>J)&&re.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${K?"or equal to ":""} ${J}.`})):(void 0!==B&&e<B&&re.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${B}.`}),void 0!==J&&e>J&&re.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${J}.`}),void 0!==G&&e<=G&&re.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${G}.`}),void 0!==K&&e>=K&&re.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${K}.`})),void 0!==Z&&(function(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return!1;const[r,n]=Hc(e),[i,o]=Hc(t),s=n-o;return s>=0?r*10n**BigInt(s)%i===0n:r%(i*10n**BigInt(-s))===0n}(e,Z)||re.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${Z}.`}));else if("string"===l){const t=void 0===Q&&void 0===Y?0:function(e){let t,r=0,n=e.length,i=0;for(;i<n;)r++,t=e.charCodeAt(i++),t>=55296&&t<=56319&&i<n&&(t=e.charCodeAt(i),56320==(64512&t)&&i++);return r}(e);void 0!==Q&&t<Q&&re.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${t} < ${Q}).`}),void 0!==Y&&t>Y&&re.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${t} > ${Y}).`}),void 0===X||new RegExp(X,"u").test(e)||re.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."}),void 0!==C&&Rc[C]&&!Rc[C](e)&&re.push({instanceLocation:s,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${C}".`})}return{valid:0===re.length,errors:re}}class Vc{schema;draft;shortCircuit;lookup;constructor(e,t="2019-09",r=!0){this.schema=e,this.draft=t,this.shortCircuit=r,this.lookup=$c(e)}validate(e){return Dc(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),$c(e,this.lookup)}}class Fc{constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??"2020-12"}getValidator(e){const t=new Vc(e,this.draft,this.shortcircuit);return e=>{const r=t.validate(e);return r.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:r.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join("; ")}}}}function Wc(e){const t=[{value:e,depth:0}];let r=0,n=0;for(;t.length;){const e=t.pop();if(!e)break;if(++r>512||e.depth>24)throw new er("schema-limits");const i=Bc(e.value,512-r-t.length);for(const r of i)t.push({value:r,depth:e.depth+1});if(V(e.value)&&(n+=e.value.length),n>16384)throw new er("schema-limits")}return r*Math.max(r,n)}function Bc(e,t){if(Array.isArray(e)){if(e.length>t)throw new er("schema-limits");return e}if(!F(e))return[];if(2*Object.keys(e).length>t)throw new er("schema-limits");return Object.entries(e).flat()}const Jc=new Set(["$defs","definitions","properties","patternProperties","dependentSchemas","dependencies"]),Gc=new Set(["prefixItems","items","allOf","anyOf","oneOf"]),Kc=new Set(["$ref","$schema","$vocabulary","$comment","default","enum","const","required","type","maximum","minimum","exclusiveMaximum","exclusiveMinimum","multipleOf","maxLength","minLength","pattern","format","maxItems","minItems","uniqueItems","maxProperties","minProperties"]);function Zc(e){return F(e)||!0===e||!1===e}function Qc(e){const t=/^(?:\[(?:\\[dDsSwW\\\]\-]|[^\[\]\\])+\]|\\[dDsSwW.\-_/]|[a-zA-Z0-9 _/@:\-])/u.exec(e);if(!t)throw new er("schema-limits");return t[0].length}function Yc(e){if(/^[+*?]/u.test(e))return{length:1,variable:!0};const t=/^\{([0-9]{1,3})(?:,([0-9]{1,3}))?\}/u.exec(e);if(!t)return{length:0,variable:!1};const r=Number(t[1]),n=Number(t[2]??t[1]);if(n>128||r>n)throw new er("schema-limits");return{length:t[0].length,variable:r!==n}}function Xc(e){if(e.length>256||!e.startsWith("^")||!e.endsWith("$"))throw new er("schema-limits");let t=e.slice(1,-1),r=0;for(;t;){t=t.slice(Qc(t));const e=Yc(t);if(e.variable&&++r>1)throw new er("schema-limits");t=t.slice(e.length)}try{new RegExp(e,"u")}catch{throw new er("schema-limits")}}const ed=new Set(["$id","id","$anchor","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]),td=new Set(["date","time","date-time","email","uuid","ipv4","ipv6","hostname"]);function rd(e,t,r,n){if(n>24)throw new er("schema-limits");if(Array.isArray(e))return nd(e,t,r,n);if(!F(e))return 1;if(r.has(e))throw new er("schema-limits");!function(e){for(const t of Object.keys(e))if(ed.has(t)||t.startsWith("__"))throw new er("schema-limits");if(void 0!==e.pattern){if(!V(e.pattern))throw new er("schema-limits");Xc(e.pattern)}if(F(e.patternProperties))for(const t of Object.keys(e.patternProperties))Xc(t);if(!(void 0===e.format||V(e.format)&&td.has(e.format)))throw new er("schema-limits")}(e);const i=new Set(r).add(e),o=function(e){const t=[];for(const[r,n]of Object.entries(e))Kc.has(r)||(Jc.has(r)&&F(n)?t.push(...Object.values(n).filter(Zc)):Gc.has(r)&&Array.isArray(n)?t.push(...n.filter(Zc)):Zc(n)&&t.push(n));return t}(e);void 0!==e.$ref&&o.push(function(e,t){if(!V(t)||!t.startsWith("#/"))throw new er("schema-limits");let r=e;for(const n of t.slice(2).split("/")){const e=n.replaceAll("~1","/").replaceAll("~0","~");if(!F(r)||!Object.hasOwn(r,e))throw new er("schema-limits");r=r[e]}if(!F(r)&&!0!==r&&!1!==r)throw new er("schema-limits");return r}(t,e.$ref));const s=1+function(e){const t=e.pattern,r=e.patternProperties;return(V(t)?t.length:0)+(F(r)?Object.keys(r).reduce((e,t)=>e+t.length,0):0)+(void 0===e.format?0:128)}(e)+nd(o,t,i,n);if(s>512)throw new er("schema-limits");return s}function nd(e,t,r,n){let i=0;for(const o of e)if(i+=rd(o,t,r,n+1),i>512)throw new er("schema-limits");return i}class id{getValidator(e){const t=function(e){if(Wc(e),(new TextEncoder).encode(JSON.stringify(e)).byteLength>32768)throw new er("schema-limits");return rd(e,e,new Set,0)}(e),r=JSON.parse(JSON.stringify(e)),n=(new Fc).getValidator(r);return e=>{if(t*Wc(e)>25e4)throw new er("schema-limits");return n(e)}}}const od=15e3;class sd{constructor(e,t){this.ports=t;const r=function(e,t,r){rr(e);const n=Object.freeze({...e});return async(e,i)=>{if(t.assertCurrent(),r.aborted)throw new er("disposed");const o=new Request(e,i);nr(n,tr(o.url),o.method);const s=await t.accessGrant();if(t.assertCurrent(),r.aborted)throw new er("disposed");const a=new Headers(o.headers);let c;a.delete("authorization"),s&&(function(e,t){if(!t.token||t.providerId!==e.providerId||t.fingerprint!==e.fingerprint||t.issuer!==e.issuer||t.resource!==e.resource)throw new er("target")}(n,s),a.set("authorization",`Bearer ${s.token}`));try{c=await t.fetch(o,{headers:a,redirect:"manual",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.any([r,o.signal])})}catch(d){if(d instanceof er)throw d;if(r.aborted)throw new er("disposed");throw new er("browser-transport")}if(t.assertCurrent(),r.aborted)throw await(c.body?.cancel()),new er("disposed");return await async function(e,t){if(401===e.status)throw await(e.body?.cancel()),await t.authorizationRequired(),new er("authorization",401);if(403===e.status)throw await(e.body?.cancel()),new er("permission",403);if("opaqueredirect"===e.type||e.status>=300&&e.status<400)throw await(e.body?.cancel()),new er("target")}(c,t),function(e){if(!e.body)return e;const t=e.body.getReader();let r=0;const n=new ReadableStream({async pull(e){try{const n=await t.read();if(n.done)return t.releaseLock(),void e.close();if(r+=n.value.byteLength,r>4194304)throw new er("response");e.enqueue(n.value)}catch{await t.cancel().catch(()=>{}),e.error(new er("response"))}},async cancel(e){await t.cancel(e)}});return new Response(n,{status:e.status,statusText:e.statusText,headers:e.headers})}(c)}}(e,t,this.lifetime.signal),n=tr(e.endpoint);this.transport="sse"===e.transport?new fc(n,{fetch:r}):new bc(n,{fetch:r,reconnectionOptions:{maxRetries:0,initialReconnectionDelay:1e3,maxReconnectionDelay:1e3,reconnectionDelayGrowFactor:1}})}ports;lifetime=new AbortController;inputValidator=new id;client=new xa({name:"OpenSesame",version:"1.0.0"},{jsonSchemaValidator:this.inputValidator});toolValidators=new Map;outputValidators=new Map;transport;discovery=null;connecting=null;assertLive(){if(this.ports.assertCurrent(),this.lifetime.signal.aborted)throw new er("disposed")}async connect(){return this.assertLive(),this.discovery?this.discovery:(this.connecting||(this.connecting=this.initialize()),this.connecting)}async initialize(){try{await this.client.connect(this.transport,{signal:this.lifetime.signal,timeout:od}),this.assertLive();const e=this.client.getServerVersion();if(!e||!this.client.getServerCapabilities()?.tools)throw new er("response");const t=await async function(e,t){const r=[],n=new Set,i=new Set;let o;for(let s=0;s<20;s++){const s=await e.listTools(o?{cursor:o}:{},{signal:t,timeout:od});for(const e of s.tools){if(!e.name||n.has(e.name)||r.length>=500)throw new er("response");n.add(e.name),r.push(e)}if(o=s.nextCursor,!o)return r;if(i.has(o))throw new er("response");i.add(o)}throw new er("response")}(this.client,this.lifetime.signal);for(const r of t)this.toolValidators.set(r.name,this.inputValidator.getValidator(r.inputSchema)),r.outputSchema&&this.outputValidators.set(r.name,this.inputValidator.getValidator(r.outputSchema));return this.assertLive(),this.discovery={server:{name:e.name,version:e.version},tools:t},this.discovery}catch(e){if(await this.dispose(),e instanceof er)throw e;throw new er("response")}}async callTool(e,t,r){this.assertLive();const n=this.toolValidators.get(e);if(!this.discovery||!n)throw new er("tool");if(!n(t).valid)throw new er("arguments");try{const n=await this.client.callTool({name:e,arguments:t},void 0,{signal:r?AbortSignal.any([r,this.lifetime.signal]):this.lifetime.signal,timeout:od});return this.assertLive(),this.assertToolOutput(e,n),n}catch(i){if(i instanceof er&&"authorization"===i.code&&await this.dispose(),i instanceof er)throw i;throw new er("response")}}assertToolOutput(e,t){const r=this.outputValidators.get(e);if(r){if(!t.structuredContent&&!t.isError)throw new er("response");if(t.structuredContent&&!r(t.structuredContent).valid)throw new er("response")}}async dispose(){this.lifetime.abort(),this.discovery=null,this.toolValidators.clear(),this.outputValidators.clear(),await this.client.close().catch(()=>{})}}function ad(e,t){if(!t)return;const r=e.configuration.requestedScopes.user??[];if(!Fe(r,t.scopes,t.refreshToken)||null!==t.scopes&&We(r).some(e=>!t.scopes?.includes(e)))throw new er("permission")}async function cd(e,t,r){It(e.configuration.providerId),await Hs(e),await dt(e.connectionId,Ct(e));const n=Ls(e.configuration),i=r??e.privateState.grants.user;if(ad(e,i),i&&null!==i.expiresAt&&i.expiresAt<=Date.now())throw new er("authorization");const o=()=>{t.assertCurrent(),It(e.configuration.providerId);const r=Ns(e.connectionId);if(r.revision!==e.revision||r.configuration.fingerprint!==n.fingerprint)throw new er("disposed")};return o(),new sd(n,{fetch:t.fetch,assertCurrent:o,accessGrant:async()=>i?{token:i.accessToken,providerId:i.providerId,fingerprint:i.fingerprint,issuer:i.issuer??null,resource:i.resource??""}:null,authorizationRequired:()=>async function(e){await lt(e.connectionId,Ct(e),Ms,e=>(e.privateState.verification=null,e.runtime.grants=e.runtime.grants.map(e=>({...e,needsReauth:!0})),e))}(e)})}function dd(e,t){const r=Math.max(Date.now(),(e.runtime.verifiedAt??0)+1),n=Ls(e.configuration);return ad(e,t),e.privateState.grants=t?{user:t}:{},e.privateState.verification={fingerprint:n.fingerprint,verifiedAt:r,kind:"provider"},e.runtime={verifiedAt:r,identity:null,targets:[{id:n.resource,label:n.resource,kind:"mcp-resource"}],grants:t?[{actor:"user",label:"MCP authorization",permissionState:null===t.scopes?"provider-managed":"known",grantedScopes:t.scopes??[],expiresAt:t.expiresAt,needsReauth:!1}]:[]},e}async function ld(e,t,r){const n=await cd(e,t,r);try{await n.connect()}finally{await n.dispose()}await dt(e.connectionId,Ct(e)),t.assertCurrent()}async function ud(e,t,r,n){const i=Ns(e),o=i.privateState.recovery.find(e=>e.id===t);if(!o?.grant||Q(o.grant)!==Q(r))throw new er("authorization");return await ld(i,n,r),lt(e,Ct(i),Ms,e=>{n.assertCurrent();const i=e.privateState.recovery.find(e=>e.id===t);if(!i?.grant||Q(i.grant)!==Q(r))throw new er("authorization");return e.privateState.recovery=e.privateState.recovery.filter(e=>e.id!==t),dd(e,r)},n.assertCurrent)}function pd(e,t,r,n){const i={...t,signal:(new AbortController).signal};return n&&(i.retainPartialRefresh=n),new Rs(zs(Ns(e).configuration,r),i)}async function hd(e,t=Y()){const r=oo(t),n=ro();r.assertCurrent();const i=Mt(e);if("mcp"!==i?.method)throw new so("pending");It(i.providerId);const o=Rt(Ot(e).state);if(!o||o.record.connectionId!==i.connectionId)throw new so("pending");return lo(o.record.connectionId,async()=>{const t=qt(o.pending).id;Ws(o.record.connectionId,t,o.pending.fingerprint);let i=!1,s=!1;try{const a=await function(e){return Ut(e,Ms,e=>{e.credentials={...e.credentials,submission:"prepared"}})}(e);s=!0,n.scrubCallback();const c=await async function(e,t,r,n){const{record:i,pending:o,obligation:s}=e;if("mcp"!==i.configuration.method)throw new so("pending");await Hs(i);const a=zs(i.configuration,n),c=Ds(i);if("user"!==o.actor||o.resource!==a.binding.resource||o.issuer!==a.binding.issuer||o.endpoint!==a.binding.endpoint||o.clientId!==c.client_id||o.redirectUri!==a.redirectUri||i.connectionId!==t.record.connectionId||o.fingerprint!==t.pending.fingerprint||s.id!==r)throw new so("pending");return c}(a,o,t,n),{record:d,pending:l,obligation:u,code:p}=a,h=At(d.connectionId,u.id);try{const e=await pd(d.connectionId,function(e,t,r){const n=e=>async(n,i)=>{const o=new Request(n,i);return"POST"===o.method&&o.url===t&&await r(),e(o)},i={...e,fetch:n(e.fetch)};return e.settleCredentialMutation&&(i.settleCredentialMutation=n(e.settleCredentialMutation)),i}(r,zs(d.configuration,n).metadata.tokenEndpoint,async()=>{await ma(d.connectionId,u.id),i=!0}),n,e=>Ks(d.connectionId,u.id,e)).exchange(c,p,l.verifier),t=Vs(l,e);if(await Lt(d.connectionId,u.id,t,qs),r.assertCurrent(),!e.protocolValid)throw new so("authorization");return ud(d.connectionId,u.id,t,r)}finally{h()}}catch(a){throw s&&!i&&await async function(e,t){const r=Ns(e);r.privateState.recovery.some(e=>e.id===t)&&await lt(e,Ct(r),Ms,e=>(e.privateState.recovery=e.privateState.recovery.filter(e=>e.id!==t||"exchange"!==e.credentials?.phase||"prepared"!==e.credentials?.submission),e))}(o.record.connectionId,t),a}finally{Bs(o.record.connectionId,t)}})}function fd(e,t){const r=function(e){return"ok"!==e.status?"This MCP provider has not published complete authorization metadata for a public browser connection.":e.tokenAuthMethods.includes("none")?e.pkce.includes("S256")?e.resource&&e.resourceMetadata&&e.discoveryUrl?"dcr"!==e.registration||e.registrationEndpoint?null:"This MCP provider has not published a public client registration endpoint.":"This MCP provider has not published the complete resource and authorization discovery endpoints required for a browser connection.":"This MCP authorization server does not advertise S256 PKCE for browser consent.":"This MCP authorization server does not advertise public clients without a client secret."}(t);if(r)return r;if("ok"!==t.status)return"This MCP provider has no public browser authorization contract.";try{return function(e,t){ao({binding:{providerId:e,fingerprint:"compiled-public-route",endpoint:t.url,resource:t.resource??t.url,issuer:t.issuer,transport:new URL(t.url).pathname.endsWith("/sse")?"sse":"streamable-http"},metadata:t,redirectUri:"https://self-host.example/auth/native-connector.html",registration:t.registration,clientId:"manual"===t.registration?"operator-public-client":void 0,clientMetadataUrl:"cimd"===t.registration?"https://self-host.example/auth/native-client.json":void 0,scopes:[]})}(e,t),null}catch{return"This provider has no complete, admitted public browser MCP endpoint contract in this deployment."}}function md(e){try{return fd(e,Us(e))}catch{return"This provider has no complete, admitted public browser MCP endpoint contract in this deployment."}}function wd(e){return md(e)??kt(e).reason}function gd(e){return"configure"===e.kind&&("partial-refresh"===e.credentials?.phase||"verify"===e.credentials?.phase&&"mcp"===e.grant?.kind)}async function vd(e){await async function(e){Ns(e).privateState.recovery.some(e=>"prepared"===e.credentials?.submission)&&await lo(e,async()=>{const t=Ns(e);await lt(e,Ct(t),Ms,e=>(e.privateState.recovery=e.privateState.recovery.filter(e=>"prepared"!==e.credentials?.submission),e))})}(e),await async function(e){const t=Fs.get(e);t?.token&&await Gs(e,t)}(e),await Et(e),await async function(e){const t=la.get(e);t?.client&&t.mode&&await fa(e,t.intentId,t.fingerprint,t.client,t.mode)}(e),await async function(e){const t=Ns(e).privateState;!t.credentials.mcp_client||t.recovery.some(e=>"registration"===e.kind)||Object.keys(t.pending).length||Object.keys(t.grants).length||await lo(e,async()=>{const t=Ns(e),r=zs(t.configuration);await lt(e,Ct(t),Ms,e=>{const t=e.privateState.credentials.mcp_client;if(!t||e.privateState.recovery.some(e=>"registration"===e.kind)||Object.keys(e.privateState.pending).length||Object.keys(e.privateState.grants).length)throw new so("pending");return e.privateState.recovery.push({id:`registration-recovery:${crypto.randomUUID()}`,kind:"registration",providerId:r.binding.providerId,actor:"user",fingerprint:r.binding.fingerprint,targetId:r.binding.resource,issuer:r.binding.issuer??void 0,resource:r.binding.resource,endpoint:r.binding.endpoint,credentials:{phase:"registered",client:t,registration_mode:e.privateState.credentials.mcp_registration_mode??("manual"===r.registration?"manual":"unknown")}}),e})})}(e);const t=Ns(e),r=t.privateState.recovery,n=r.some((e,t)=>"registration"===e.kind&&r.slice(t+1).some(e=>"registration"!==e.kind));(r.some(gd)||n)&&await lt(e,Ct(t),Ms,e=>{const t=e.privateState.recovery.map(e=>gd(e)?{...e,kind:"revoke"}:e);return e.privateState.recovery=[...t.filter(e=>"registration"!==e.kind),...t.filter(e=>"registration"===e.kind)],e})}async function yd(e,t,r=Y()){const n=Ns(t.connectionId),i=zs(n.configuration);r.assertCurrent();const o=e.credentials?.client??e.credentials?.mcp_client,s=o?Is.parse(JSON.parse(o)):Ds(n);if("registration"===e.kind)return async function(e,t,r,n,i){if(["manual","cimd"].includes(e.credentials?.registration_mode??""))return await async function(e){const t=Ns(e);await lt(e,Ct(t),Ms,e=>{const{mcp_client:t,mcp_registration_mode:r,...n}=e.privateState.credentials;return e.privateState.credentials=n,e})}(t.connectionId),"local-registration-forgotten";if("registered"!==e.credentials?.phase||!(await async function(e,t,r,n){if(!(await async function(e,t,r){if(!t.registration_access_token&&!t.registration_client_uri)return!1;const n=function(e,t){if(!e.metadata.registrationEndpoint||!t.registration_client_uri||!t.registration_access_token)throw new so("public-client");const r=tr(e.metadata.registrationEndpoint),n=tr(t.registration_client_uri),i=r.pathname.replace(/\/$/,"");if(n.origin!==r.origin||!n.pathname.startsWith(`${i}/`))throw new so("metadata");return n}(e,t);r.assertCurrent();const i=await r.fetch(n,{method:"DELETE",credentials:"omit",redirect:"manual",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(15e3),headers:{authorization:`Bearer ${t.registration_access_token}`}});if(await(i.body?.cancel()),r.assertCurrent(),204===i.status||404===i.status||410===i.status)return!0;throw new so("authorization")}(t,r,n)))return!1;const i=Ns(e.connectionId);return await lt(e.connectionId,Ct(i),Ms,e=>{const{mcp_client:t,mcp_registration_mode:r,...n}=e.privateState.credentials;return e.privateState.credentials=n,e}),!0}(t,r,n,i)))throw new Error("This MCP provider does not offer registration deletion; finish the retained registration authorization or remove it in provider settings");return"provider-revoked"}(e,t,i,s,r);const a=function(e,t,r){const n="partial-refresh"===e.credentials?.phase?e.credentials.partial_refresh_token:void 0;if(!(void 0===n||function(e,t,r,n){const i=r.binding;return"revoke"===e.kind&&t.providerId===i.providerId&&"user"===t.actor&&t.fingerprint===i.fingerprint&&t.targetId===i.resource&&t.issuer===i.issuer&&t.resource===i.resource&&t.endpoint===i.endpoint&&t.clientId===n.client_id}(e,e.grant??e,t,r)&&function(e){return e.length>0&&e.length<=32768&&/^[!-~]+$/.test(e)}(n)))throw new so("pending");return n}(e,i,s),c=e.grant?function(e,t,r){if("revoke"!==e.kind||!e.grant||"mcp"!==e.grant.kind)throw new Error("Unresolved MCP credential issuance requires provider recovery before removal");const n=e.grant;if(n.issuer!==t.binding.issuer||n.resource!==t.binding.resource||n.endpoint!==t.binding.endpoint||n.clientId!==r.client_id)throw new so("pending");return n}(e,i,s):void 0;if(!a&&!c)throw new so("pending");if(!i.metadata.revocationEndpoint)return"local-credential-forgotten";const d=new Rs(i,{...r,signal:(new AbortController).signal}),l=new Set([a,c?.refreshToken].filter(e=>void 0!==e));for(const u of l)await d.revoke(s,u,"refresh_token");return c&&await d.revoke(s,c.accessToken,"access_token"),"provider-revoked"}const _d={classification:qs,credentialSlots:["mcp_client"],prepare:vd,cleanup:yd};function bd(e){return{..._d,prepare:async t=>{e.assertCurrent(),await vd(t),e.assertCurrent()},cleanup:(t,r)=>yd(t,r,e)}}function kd(e){const t=JSON.stringify(e,null,2);if((new TextEncoder).encode(t).byteLength>32768)throw new er("response");return t}function Id(e,t){const r=e.privateState.grants.user,n=[r?.accessToken,r?.refreshToken];if(e.privateState.credentials.mcp_client){const t=Ds(e);n.push(t.client_secret,t.registration_access_token)}if(n.some(e=>!!e&&t.includes(JSON.stringify(e).slice(1,-1))))throw new er("response")}async function Sd(e,t,r){if("connected"!==et(e)?.status)throw new er("authorization");r.assertCurrent();const n=Ns(e);It(n.configuration.providerId);const i=await cd(n,r);try{const o=await i.connect();Id(n,JSON.stringify(o)),await dt(e,Ct(n)),r.assertCurrent();const s=await t(i,o);return await dt(e,Ct(n)),r.assertCurrent(),s}finally{await i.dispose()}}function Cd(e){return function(e){return null===md(e)}(e)}async function Td(e,t,r){if("mcp.tools.list"===e&&0===Object.keys(t).length){const e=await r.list();return{label:e.server.name,items:e.tools.map(e=>({id:e.name,label:e.description??e.name,inputSchema:kd(e.inputSchema)}))}}if(!e.startsWith("mcp.tool:")||Object.keys(t).some(e=>"arguments"!==e)||(t.arguments?.length??0)>32768)throw new er("tool");let n;try{n=JSON.parse(t.arguments??"{}")}catch{throw new er("arguments",0,"json-object")}if(!F(n))throw new er("arguments",0,"json-object");const i=await r.call(e.slice(9),n),o=ni.parse(i),s=o.content.filter(e=>"text"===e.type);return{label:o.isError?"MCP tool returned an error":"MCP tool result",items:s.map((e,t)=>({id:String(t),label:e.text}))}}function xd(e){return{cleanup:bd(e),supports:Cd,configure:t=>async function(e,t=Y()){t.assertCurrent(),It(e.providerId);const{client_id:r,...n}=e.parameters,i=r?.trim();!function(e,t){if("mcp"!==e.method||Object.keys(e.credentials).length)throw new Error("MCP public browser routes do not accept confidential credentials");if(Object.keys(t).some(e=>"mcp_url"!==e)||Object.keys(e.targetIds).length)throw new Error("Select a published provider MCP resource");if(Object.keys(e.requestedScopes).some(e=>"user"!==e))throw new Error("This MCP route supports delegated user permissions only")}(e,n);const o=Us(e.providerId,n.mcp_url),s=fd(e.providerId,o);if(s)throw new Error(s);const c=[...new Set(e.requestedScopes.user??[])].sort();if(c.some(e=>"ok"!==o.status||!o.scopes.includes(e)))throw new Error("Select permissions published by this MCP provider");const d={version:1,providerId:e.providerId,method:"mcp",displayName:e.displayName.trim(),icon:e.icon??"",parameters:{mcp_url:o.url},requestedScopes:{user:c},targetIds:{},fingerprint:"0".repeat(64)};i&&(d.clientId=i),d.targetIds={mcp:Ls(d).resource},d.fingerprint=await js(d),t.assertCurrent();const l=e.connectionId?Xe(e.connectionId):null;return function(e,t,r){if(e.connectionId&&(!t||t.configuration.providerId!==e.providerId||t.revision!==e.revision))throw new Error("Connector changed; reload before saving");if(t){if("mcp"!==t.configuration.method)throw new Error("Create a separate connector for a different authentication method");if(t.configuration.fingerprint!==r.fingerprint&&(Object.keys(t.privateState.grants).length||Object.keys(t.privateState.pending).length||t.privateState.recovery.length||t.privateState.credentials.mcp_client))throw new Error("Finish provider authorization cleanup before changing this connector binding")}}(e,l,d),l?lt(l.connectionId,Ct(l),Ms,e=>(t.assertCurrent(),e.configuration=d,e)):at({connectionId:`devconn_${crypto.randomUUID()}`,configuration:d,runtime:p(),privateState:a()},Ms)}(t,e),verify:t=>async function(e,t=Y()){t.assertCurrent();const r=Ns(e);if(It(r.configuration.providerId),r.privateState.recovery.length||Object.keys(r.privateState.pending).length)throw new Error("Finish MCP authorization or cleanup before verifying this connector");const n=r.privateState.grants.user;return n?.refreshToken&&null!==n.expiresAt&&n.expiresAt<=Date.now()?async function(e,t){return lo(e.connectionId,async()=>{t.assertCurrent(),It(e.configuration.providerId);const r=e.privateState.grants.user;if(!r?.refreshToken||e.privateState.recovery.length||Object.keys(e.privateState.pending).length)throw new so("authorization");const n=zs(e.configuration),i=n.binding.resource,o=function(e,t){return{id:`mcp-refresh:${crypto.randomUUID()}`,kind:"configure",providerId:e.providerId,actor:e.actor,fingerprint:e.fingerprint,targetId:t,grant:{...e,targetId:t},credentials:{phase:"refresh",submission:"prepared",deadline:String(Date.now()+6e4)}}}(r,i);await lt(e.connectionId,Ct(e),Ms,e=>(t.assertCurrent(),e.privateState.recovery.push(o),e.privateState.verification=null,e));const s=At(e.connectionId,o.id);let a=!1,c=!1;try{Ws(e.connectionId,o.id,o.fingerprint);const s=function(e,t,r,n,i){const o=e=>async(t,r)=>{const o=new Request(t,r);return"POST"===o.method&&o.url===n.metadata.tokenEndpoint&&await i(),e(o)},s={...r,retainPartialRefresh:r=>Ks(e.connectionId,t.id,r),fetch:o(r.fetch),signal:(new AbortController).signal};return r.settleCredentialMutation&&(s.settleCredentialMutation=o(r.settleCredentialMutation)),new Rs(n,s)}(e,o,t,n,async()=>{await ma(e.connectionId,o.id),c=!0}),d=await s.refresh(Ds(e),r.refreshToken);a=!0;const l=Vs({...r,targetId:i},d);if(l.refreshToken=l.refreshToken??r.refreshToken,d.protocolValid&&(l.scopes=l.scopes??r.scopes),await Lt(e.connectionId,o.id,l,qs),t.assertCurrent(),!d.protocolValid)throw new so("authorization");return await ud(e.connectionId,o.id,l,t)}catch(d){throw await async function(e,t,r,n,i){!n&&r?await async function(e,t){const r=Ns(e);await lt(e,Ct(r),Ms,e=>(e.privateState.recovery=e.privateState.recovery.filter(e=>e.id!==t),e.privateState.verification=null,e.runtime.grants=e.runtime.grants.map(e=>({...e,needsReauth:!0})),e))}(e,t):n||i||await async function(e,t){const r=Ns(e);await lt(e,Ct(r),Ms,e=>(e.privateState.recovery=e.privateState.recovery.filter(e=>e.id!==t),e.privateState.verification=null,e))}(e,t)}(e.connectionId,o.id,d instanceof so&&"invalid_grant"===d.oauthError,a,c),d}finally{Bs(e.connectionId,o.id),s()}})}(r,t):async function(e,t){return await ld(e,t),lt(e.connectionId,Ct(e),Ms,e=>(t.assertCurrent(),dd(e,e.privateState.grants.user)),t.assertCurrent)}(r,t)}(t,e),authorize:(t,r)=>async function(e,t="user",r=Y()){const n=oo(r);if(n.assertCurrent(),It(Ns(e).configuration.providerId),"user"!==t)throw new so("public-client");const i=ro();await async function(e,t){const r=Ns(e);if(r.privateState.recovery.length>0&&(1!==r.privateState.recovery.length||"registration"!==r.privateState.recovery[0]?.kind||"registered"!==r.privateState.recovery[0]?.credentials?.phase||!r.privateState.credentials.mcp_client)||Object.keys(r.privateState.pending).length)throw new Error("Finish MCP authorization or provider cleanup before starting another consent");const n=r.privateState.grants.user;n&&(await lt(e,Ct(r),Ms,e=>{t.assertCurrent();const r=n.resource??n.targetId??e.configuration.providerId;return e.privateState.recovery.push({id:`reconsent:${crypto.randomUUID()}`,kind:"revoke",providerId:n.providerId,actor:n.actor,fingerprint:n.fingerprint,targetId:r,grant:{...n,targetId:r},credentials:{mcp_client:e.privateState.credentials.mcp_client??""}}),e.privateState.grants={},e.privateState.verification=null,e.runtime.grants=[],e}),t.assertCurrent(),await aa(e))}(e,n);const o=await lo(e,async()=>{const r=Ns(e);if(await Hs(r),Object.keys(r.privateState.pending).length||r.privateState.grants.user)throw new Error("Finish existing provider authorization cleanup before starting consent");const o=zs(r.configuration,i),s=r.privateState.recovery[0],a=s??{id:`registration:${crypto.randomUUID()}`,kind:"registration",providerId:o.binding.providerId,actor:t,fingerprint:o.binding.fingerprint,targetId:o.binding.resource,issuer:o.binding.issuer??void 0,resource:o.binding.resource,endpoint:o.binding.endpoint,credentials:r.privateState.credentials.mcp_client?{phase:"registered",client:r.privateState.credentials.mcp_client,registration_mode:"unknown"}:{phase:"registration",submission:"prepared",deadline:String(Date.now()+6e4)}};ha(e),s||await lt(e,Ct(r),Ms,e=>(n.assertCurrent(),e.privateState.recovery.push(a),e.privateState.verification=null,e));const c=At(e,a.id);try{const s=pd(e,n,i),c=r.privateState.credentials.mcp_client?Ds(r):await async function(e,t,r,n){!function(e,t,r){ha(e),la.set(e,{intentId:t,fingerprint:r,client:null,mode:null})}(e,t.id,r.binding.fingerprint);let i=!1,o=null;const s=n=>async(o,s)=>{const a=new Request(o,s);return"POST"===a.method&&a.url===r.metadata.registrationEndpoint&&(await ma(e,t.id),i=!0),n(a)},a={...n,signal:(new AbortController).signal,onRegistrationMode:e=>{o=e},fetch:s(n.fetch)};n.settleCredentialMutation&&(a.settleCredentialMutation=s(n.settleCredentialMutation));const c=new Rs(r,a);try{return await c.register(n=>{if(!o)throw new Error("Missing registration mode");return async function(e,t,r,n,i){pa(e);const o=JSON.stringify(n);la.set(e,{intentId:t,fingerprint:r,client:o,mode:i}),await fa(e,t,r,o,i)}(e,t.id,r.binding.fingerprint,n,o)})}catch(d){throw i||await async function(e,t){const r=Ns(e);await lt(e,Ct(r),Ms,e=>(e.privateState.recovery=e.privateState.recovery.filter(e=>e.id!==t),e)),ua(e,t)}(e,t.id),d}}(e,a,o,n);return await async function({id:e,actor:t,obligationId:r,client:n,target:i,protocol:o,transport:s}){const a=Array.from(crypto.getRandomValues(new Uint8Array(32)),e=>e.toString(16).padStart(2,"0")).join(""),c=await o.consent(n,a),d=Ns(e),l={providerId:i.binding.providerId,actor:t,fingerprint:i.binding.fingerprint,targetId:i.binding.resource,issuer:i.binding.issuer??void 0,resource:i.binding.resource,endpoint:i.binding.endpoint,clientId:n.client_id,state:a,verifier:c.codeVerifier,redirectUri:i.redirectUri,createdAt:Date.now(),expiresAt:Date.now()+6e5,scopes:[...i.scopes]};return await lt(e,Ct(d),Ms,e=>(s.assertCurrent(),e.privateState.pending[t]=l,e.privateState.recovery=e.privateState.recovery.filter(e=>e.id!==r),e)),s.assertCurrent(),{url:c.authorizationUrl.href,state:l.state,expiresAt:l.expiresAt}}({id:e,actor:t,obligationId:a.id,client:c,target:o,protocol:s,transport:n,browser:i})}finally{!function(e,t){const r=la.get(e);r?.intentId===t&&null===r.client&&la.delete(e)}(e,a.id),c()}});if(i.authorize){let t;try{t=await i.authorize(o.url,{state:o.state,expiresAt:o.expiresAt})}catch(s){throw await async function(e,t,r){const n=Xe(e);if(!n)return;const i=Object.keys(n.privateState.pending).find(e=>n.privateState.pending[e]?.state===t);i&&await lt(e,Ct(n),r,e=>(e.privateState.pending[i]?.state===t&&delete e.privateState.pending[i],e))}(e,o.state,Ms),s}await hd(t,n)}else i.navigate(o.url)}(t,r,e),invoke:(t,r,n)=>async function(e,t,r,n){return Td(t,r,{list:()=>function(e,t=Y()){return Sd(e,async(e,t)=>t,t)}(e,n),call:(t,r)=>function(e,t,r,n=Y()){return Sd(e,async n=>{const i=await n.callTool(t,r);return Id(Ns(e),JSON.stringify(i)),i},n)}(e,t,r,n)})}(t,r,n,e)}}const $d={authorizationParams:{},scopeSeparator:" ",verify:null,tokenTypes:["bearer"],tokenTypeOptional:!1},Ad=new Map([["slack",["bot","user"]]]),Pd=new Set(["user_scope"]),Ed=new Set(["shopify"]);function Od(e){const t=Z(e)?.methods.find(e=>"oauth"===e.kind),r="oauth"===t?.kind?t.preset:null;return r?{authorizationParams:Object.fromEntries(Object.entries(r.authorizationParams).filter(([e])=>!Pd.has(e))),scopeSeparator:r.scopeSeparator,verify:r.verify,tokenTypes:["bearer",...Ad.get(e)??[]],tokenTypeOptional:Ed.has(e)}:$d}function Rd(e,t){return void 0===t?e.tokenTypeOptional:e.tokenTypes.includes(t.toLowerCase())}const Md=e=>e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),qd=v().url().max(4096).refine(e=>{const t=new URL(e);return"https:"===t.protocol&&!t.username&&!t.password&&!t.hash}),Ud=qd.refine(e=>!new URL(e).search),Ld=w({issuer:Ud,authorization_endpoint:Ud,token_endpoint:Ud,token_relay_url:qd.optional(),resource:Ud.optional(),resource_protocol:_(["json","mcp"]).optional(),resource_parameter:_(["send","omit"]).optional(),mcp_endpoint:qd.optional(),mcp_transport:_(["streamable-http","sse"]).optional(),mcp_post_endpoint:Ud.optional(),token_auth_method:_(["none","client_secret_basic","client_secret_post"])}).strict();function jd(e){return Object.fromEntries(Object.entries(e).filter(([e,t])=>!("resource_parameter"===e&&"send"===t||["token_relay_url","resource_protocol","mcp_endpoint","mcp_transport","mcp_post_endpoint"].includes(e)&&""===t)))}const zd=[...Ld.keyof().options,"redirect_uri"],Nd=["oauth_client_reference","oauth_client_vault","oauth_client_consent","client_secret"],Hd=v().min(1).max(32768),Dd=()=>({publicParameters:zd,privateCredentials:Nd});function Vd(e){e.transport.assertCurrent(),e.transport.signal?.throwIfAborted()}function Fd(e){const{redirect_uri:r,...n}=e.parameters,i=Ld.parse(n);if("oauth"!==e.method||!e.clientId||!r)throw new t("callback");if("mcp"===i.resource_protocol){if("sse"===i.mcp_transport&&!i.mcp_post_endpoint)throw new t("callback");rr({providerId:e.providerId,fingerprint:e.fingerprint,resource:i.resource??"",endpoint:i.mcp_endpoint??i.resource??"",issuer:i.issuer,transport:i.mcp_transport??"streamable-http",ssePostEndpoint:i.mcp_post_endpoint})}else if(i.mcp_endpoint||i.mcp_transport||i.mcp_post_endpoint)throw new t("callback");return{...i,redirectUri:r,clientId:e.clientId}}function Wd(r,n){Vd(n);const i=Fd(r);return function(e,t){const r=function(e,t){return _t(e,"oauth",{},t)}(e,t);if(!r.available)throw new Error(r.reason??"Browser OAuth is unavailable")}(r.providerId,{transport:n.transport,tokenEndpoint:i.token_endpoint,resourceEndpoint:i.resource??""}),function(r){if("google-drive"!==r.providerId)return;const n=r.requestedScopes.user??[];if("oauth"!==r.method||Object.keys(r.requestedScopes).some(e=>"user"!==e)||Object.entries(e.endpoints).some(([e,t])=>r.parameters[e]!==t)||e.forbiddenParameters.some(e=>void 0!==r.parameters[e]))throw new t("scope");!function(e,r){if(!Ve(e,r))throw new t("scope")}(r.providerId,n)}(r),Vd(n),i}function Bd(e){const r=new URL(e);if("https:"!==r.protocol&&("http:"!==r.protocol||!["localhost","127.0.0.1","[::1]"].includes(r.hostname))||r.username||r.password||r.search||r.hash)throw new t("callback");return r.href}async function Jd(e){const t=(new TextEncoder).encode(JSON.stringify([e.providerId,e.method,Fd(e),e.requestedScopes]));return[...new Uint8Array(await crypto.subtle.digest("SHA-256",t))].map(e=>e.toString(16).padStart(2,"0")).join("")}function Gd(e,r){Vd(r);const n=St(e),i=Fd(n.configuration);if(i.redirectUri!==Bd(r.redirectUri))throw new t("expired");if(n.privateState.credentials.oauth_client_vault!==r.tomb)throw new t("expired");const o=he(n.privateState.credentials.oauth_client_reference??"",n.configuration.fingerprint,["clientSecret"],r.tomb);if("none"!==i.token_auth_method)return Hd.parse(o.fields.get("clientSecret"));if(o.fields.size)throw new t("expired")}async function Kd(e,t,r){const n=St(e),i=Object.keys(n.privateState.pending).find(e=>n.privateState.pending[e]?.state===t);i&&await lt(e,Ct(n),r??h(n.configuration),e=>{if(e.privateState.pending[i]?.state!==t)return e;const{[i]:r,...n}=e.privateState.pending;return e.privateState.pending=n,e})}const Zd=v().min(1).max(32768).regex(/^[!-~]+$/),Qd=w({access_token:Zd,refresh_token:Zd.optional()}),Yd=w({token_type:v().max(64).optional(),expires_in:k([I(),v().regex(/^\d{1,9}$/).transform(Number)]).pipe(I().finite().positive().max(31536e3)).optional(),scope:v().max(32768).optional()});function Xd(e){return new URLSearchParams({v:e}).toString().slice(2)}const el=w({error:_(["invalid_request","invalid_client","invalid_grant","unauthorized_client","unsupported_grant_type","invalid_scope"]),error_description:v().max(4096).optional(),error_uri:v().url().max(4096).optional()}).strict();async function tl(e,r,n,i,o,s){const a=St(e);if(a.revision!==s.revision)throw new t("expired");return o.assertCurrent(),lt(e,Ct(a),i(a.configuration),e=>{o.assertCurrent();const{intent:i,grant:a}=function(e,r,n){const i=e.privateState.recovery.find(e=>e.id===r),o=i?.grant;if(!i||!o||i.fingerprint!==e.configuration.fingerprint||"verify"!==i.credentials?.phase)throw new t("expired");if(JSON.stringify(m.parse(o))!==JSON.stringify(m.parse(n)))throw new t("expired");return{intent:i,grant:o}}(e,r,s.grant),c=i.credentials?.identity_id;if(c&&c!==n.identity.id&&"credential-valid"!==n.identity.assurance)throw new t("provider");const d=e.privateState.grants[a.actor];if(function(e,r,n){if("twitch"!==n.providerId)return;const i=e.privateState.pending[n.actor];if(i){if(r.id!==`oauth:${i.state}`||i.fingerprint!==n.fingerprint||i.providerId!==n.providerId)throw new t("expired");e.privateState.pending=Object.fromEntries(Object.entries(e.privateState.pending).filter(([e])=>e!==n.actor))}}(e,i,a),d&&function(e,t){return!("twitch"===t.providerId&&e.providerId===t.providerId&&e.actor===t.actor&&e.fingerprint===t.fingerprint&&e.accessToken===t.accessToken)}(d,a)){const t=d.targetId??i.targetId;e.privateState.recovery.push({id:`oauth-replace:${i.id}`,kind:"revoke",providerId:d.providerId,actor:d.actor,fingerprint:d.fingerprint,targetId:t,grant:{...d,targetId:t}})}const l={...a,targetId:n.identity.id,scopes:n.scopes};e.privateState.grants[a.actor]=l,e.privateState.recovery=e.privateState.recovery.filter(e=>e.id!==r);const u=Math.max(Date.now(),(e.runtime.verifiedAt??0)+1);return["twitch","databricks","discord"].includes(e.configuration.providerId)&&(e.configuration.parameters=Object.fromEntries(Object.entries(e.configuration.parameters).filter(([e])=>"authorization_outcome"!==e))),e.privateState.verification={fingerprint:e.configuration.fingerprint,verifiedAt:u,kind:"provider"},e.runtime={verifiedAt:u,identity:n.identity,targets:n.targets,grants:[{actor:a.actor,label:"Authorized user",permissionState:null===n.scopes?"provider-managed":"known",grantedScopes:n.scopes??[],expiresAt:a.expiresAt,needsReauth:!1}]},e},o.assertCurrent)}function rl(e,t){return async()=>{t(),await lt(e.connectionId,Ct(e),Dd(),e=>(t(),e.privateState.verification=null,e.runtime.verifiedAt=null,e.runtime.grants=e.runtime.grants.map(e=>({...e,needsReauth:!0})),e),t)}}function nl(e,r,n,i){const o=structuredClone(r),s=Object.freeze({...n}),{record:a,target:c}=function(e,r,n){const i=St(e),o=Fd(i.configuration);if(Vd(n),Gd(e,n),!o.resource||"oauth"!==r.kind||r.providerId!==i.configuration.providerId||r.fingerprint!==i.configuration.fingerprint||r.resource!==o.resource||r.issuer!==o.issuer||r.endpoint!==o.token_endpoint||r.clientId!==o.clientId||null!==r.expiresAt&&r.expiresAt<=Date.now())throw new t("expired");if(!Be(i.configuration.providerId,i.configuration.requestedScopes[r.actor]??[],r.scopes))throw new t("scope");if(![i.privateState.grants.user,...i.privateState.recovery.filter(e=>"verify"===e.credentials?.phase&&"true"===e.credentials?.protocol_valid).map(e=>e.grant)].some(e=>e&&Q(e)===Q(r)))throw new t("expired");return Wd(i.configuration,n),{record:i,target:o}}(e,o,s),d=new AbortController,l=s.transport.signal;if(!l)throw new t("expired");const u=AbortSignal.any([d.signal,l]),p=()=>{u.throwIfAborted(),Vd(s),Gd(e,s),Wd(a.configuration,s);const r=St(e);if(r.revision!==a.revision||r.configuration.fingerprint!==a.configuration.fingerprint)throw new t("expired")},h={assertCurrent:p,signal:u,fetch:(e,t)=>{p();const r=new Request(e,t);return s.transport.fetch(r,{signal:AbortSignal.any([u,r.signal])})}},f=X.onLock(()=>d.abort()),m=ce(()=>{try{p()}catch{d.abort()}}),w={providerId:a.configuration.providerId,fingerprint:o.fingerprint,endpoint:c.mcp_endpoint??c.resource??"",resource:c.resource??"",issuer:c.issuer,transport:c.mcp_transport??"streamable-http",ssePostEndpoint:c.mcp_post_endpoint},g=new sd(w,{fetch:h.fetch,assertCurrent:p,accessGrant:async()=>({token:o.accessToken,providerId:o.providerId,fingerprint:o.fingerprint,issuer:o.issuer??null,resource:o.resource??""}),authorizationRequired:rl(a,p)}),v=function(e,t){return r=>{e();const n=JSON.stringify(r);if(t.some(e=>e&&n.includes(JSON.stringify(e).slice(1,-1))))throw new er("response")}}(p,[o.accessToken,o.refreshToken,Gd(e,s)]);return{record:a,binding:w,session:g,transport:h,check:p,privateResult:v,async dispose(){d.abort(),m(),f(),await g.dispose()}}}async function il(e,r,n,i){const o=St(e),s=o.privateState.grants.user;if(!s||!o.privateState.verification||"mcp-resource"!==o.runtime.identity?.kind||o.privateState.recovery.length||Object.keys(o.privateState.pending).length)throw new t("expired");const a=nl(e,s,r);try{const e=await a.session.connect();a.privateResult(e);const t=await n(a);return a.privateResult(t),a.check(),t}finally{await a.dispose()}}function ol(e,r){const n=Fd(e.configuration);if(!n.resource||r.resource!==n.resource||r.issuer!==n.issuer||r.endpoint!==n.token_endpoint||r.clientId!==n.clientId||r.fingerprint!==e.configuration.fingerprint||"oauth"!==r.kind||null!==r.expiresAt&&r.expiresAt<=Date.now())throw new t("expired");if(!Be(e.configuration.providerId,e.configuration.requestedScopes[r.actor]??[],r.scopes))throw new t("scope");return n.resource}function sl(e,r,n){const i=()=>{Vd(n),Gd(e.connectionId,n);const i=St(e.connectionId);if(i.revision!==e.revision||i.configuration.fingerprint!==r.fingerprint)throw new t("expired")};return{assertCurrent:i,signal:n.transport.signal,fetch:(e,t)=>(i(),n.transport.fetch(e,t))}}async function al(e,t,r){const n=ol(e,t);Wd(e.configuration,r);const i=sl(e,t,r);try{const r=function(e,t,r){const n=new Headers({accept:"application/json"}),i=e.verify;if(!i||!function(e,t){const r=e.split(/\{[a-z_]+\}/).map(Md).join("[A-Za-z0-9.-]+");return new RegExp(`^${r}$`).test(t)}(i.url,t))return n.set("authorization",`Bearer ${r}`),{method:"GET",headers:n};for(const[s,a]of Object.entries(i.headers))n.set(s,a);const o=i.auth;return"header"===o?.kind?n.set(o.header,o.scheme?`${o.scheme} ${r}`:r):n.set("authorization",`Bearer ${r}`),"POST"===i.method?{method:"POST",headers:n,body:i.body??""}:{method:"GET",headers:n}}(Od(e.configuration.providerId),n,t.accessToken),o=await u({url:n,...r,signal:i.signal},i);if(function(e){return!(!F(e)||!(V(e.error)&&e.error.trim().length>0||F(e.error)&&Object.keys(e.error).length>0||Array.isArray(e.errors)&&e.errors.length>0||V(e.error_description)&&e.error_description.trim().length>0||!1===e.success||!1===e.ok||"error"===e.status||"failed"===e.status))}(o))throw new c("response",200);return o}catch(o){if(o instanceof c&&401===o.status){const t=St(e.connectionId);t.revision===e.revision&&await lt(t.connectionId,Ct(t),Dd(),e=>(e.privateState.verification=null,e.runtime.verifiedAt=null,e.runtime.grants=e.runtime.grants.map(e=>({...e,needsReauth:!0})),e),()=>Vd(r))}throw o}}async function cl(e,r){const n=St(e),i=n.privateState.recovery.filter(e=>"verify"===e.credentials?.phase);if(i.length){const o=i[0],s=o?.grant;if(1!==i.length||!o||!s||"true"!==o.credentials?.protocol_valid)throw new t("cleanup");const a=await al(n,s,r),c=await tl(e,o.id,function(e,t){const r=ol(e,t);return{identity:{id:r,label:e.configuration.displayName,kind:"api-resource",assurance:"credential-valid"},targets:[{id:r,label:r,kind:"api"}],scopes:t.scopes}}(n,s),Dd,sl(n,s,r),{revision:n.revision,grant:s});return Vd(r),{view:c,body:a}}if(n.privateState.recovery.length||Object.keys(n.privateState.pending).length)throw new t("cleanup");const o=n.privateState.grants.user;if(!o||!et(e)?.verifiedAt)throw new t("expired");const s=await al(n,o,r),a=await lt(e,Ct(n),Dd(),e=>{if(Q(e.privateState.grants.user)!==Q(o))throw new t("expired");const r=Math.max(Date.now(),(e.runtime.verifiedAt??0)+1);return e.privateState.verification={fingerprint:e.configuration.fingerprint,verifiedAt:r,kind:"provider"},e.runtime.verifiedAt=r,e},sl(n,o,r).assertCurrent);return Vd(r),{view:a,body:s}}function dl(e,t=!1){return async(r,n,i)=>{n?.throwIfAborted();const o=t?no()?.captureAuthorizationGuard?.():void 0;o?.();const s=i?e.capture(n,i):n?e.capture(n):e.capture(),a=await s;try{n?.throwIfAborted();const e=t?oo(a.transport,()=>o?.()):a.transport,i=n?AbortSignal.any([n,...e.signal?[e.signal]:[]]):e.signal,s=()=>{i?.throwIfAborted(),e.assertCurrent(),i?.throwIfAborted()},c={...e,fetch:e.fetch.bind(e),signal:i,assertCurrent:s};e.settleCredentialMutation&&(c.settleCredentialMutation=e.settleCredentialMutation.bind(e));const d={...a,transport:c};Vd(d);const l=await r(d);return Vd(d),l}finally{a.close()}}}function ll(e){return"mcp"===Fd(St(e).configuration).resource_protocol}const ul=(e,r)=>ll(e)?async function(e,r){const n=St(e),i=n.privateState.recovery.filter(e=>"verify"===e.credentials?.phase),o=i[0];if(n.privateState.recovery.length&&(1!==i.length||!o?.grant||"true"!==o.credentials?.protocol_valid))throw new t("cleanup");if(Object.keys(n.privateState.pending).length)throw new t("cleanup");const s=o?.grant??n.privateState.grants.user;if(!s)throw new t("expired");const a=nl(e,s,r);try{const t=await a.session.connect();a.privateResult(t),a.check();const r={identity:{id:a.binding.resource,label:t.server.name,kind:"mcp-resource",assurance:"credential-valid"},targets:[{id:a.binding.resource,label:t.server.name,kind:"mcp-resource"}],scopes:s.scopes};return{view:o?await tl(e,o.id,r,Dd,a.transport,{revision:n.revision,grant:s}):await lt(e,Ct(n),Dd(),e=>{a.check();const t=Math.max(Date.now(),(e.runtime.verifiedAt??0)+1);return e.privateState.verification={fingerprint:e.configuration.fingerprint,verifiedAt:t,kind:"provider"},e.runtime.verifiedAt=t,e.runtime.identity=r.identity,e.runtime.targets=r.targets,e},a.check),discovery:t}}finally{await a.dispose()}}(e,r):cl(e,r);function pl(e){const r=dl(e),n=dl(e,!0);return{supports:e.supports,configure:e=>r(r=>{if(!e.parameters.resource)throw new t("callback");return async function(e,r){Vd(r);const n=await async function(e,r){const{client_id:n,...i}=e.parameters,o=jd(i);if(Ld.parse(o),"oauth"!==e.method||!n||Object.keys(e.targetIds).length||Object.keys(e.requestedScopes).some(e=>"user"!==e))throw new t("callback");const s=g(v().regex(/^[\x21\x23-\x5B\x5D-\x7E]{1,512}$/)).max(256).parse(e.requestedScopes.user??[]),a={version:1,providerId:e.providerId,method:"oauth",displayName:e.displayName,icon:e.icon??"",parameters:{...o,redirect_uri:Bd(r.redirectUri)},clientId:n,requestedScopes:{user:[...new Set(s)]},targetIds:{},fingerprint:"0".repeat(64)};return a.fingerprint=await Jd(a),a}(e,r),i=()=>{Wd(n,r)};i();const o=w({client_secret:k([Hd,y("")]).optional()}).strict().parse(e.credentials);return async function(e){const{input:r,desired:n,owner:i,secret:o,check:s,classification:c}=e;s();const d=function(e){const r=e.connectionId?Xe(e.connectionId):null;if(e.connectionId&&(!r||r.configuration.providerId!==e.providerId||r.revision!==e.revision))throw new t("expired");if(r&&("oauth"!==r.configuration.method||Object.keys(r.privateState.pending).length||r.privateState.recovery.length))throw new t("cleanup");return r}(r);if(d&&Object.keys(d.privateState.grants).length)return async function(e,r){const{desired:n,owner:i,check:o,secret:s}=e,a=await e.fingerprint(r.configuration);if(o(),a!==r.configuration.fingerprint||a!==n.fingerprint)throw new t("cleanup");const c=e.readSecret(r.connectionId);if(void 0!==s&&s!==c)throw new t("cleanup");const d=he(r.privateState.credentials.oauth_client_reference??"",a,["clientSecret"],i.tomb),l=()=>{o(),fe(d,i.tomb,o);const e=et(r.connectionId);if(e?.revision!==r.revision||e.fingerprint!==a||"connected"!==e.status)throw new t("expired")};l();const u=r.privateState.credentials.oauth_client_consent?.split(":"),p=await de(c??"");if(l(),2!==u?.length||!u[0]||u[1]!==p)throw new t("expired");if(n.displayName===r.configuration.displayName&&n.icon===r.configuration.icon){await dt(r.connectionId,Ct(r)),l();const e=et(r.connectionId);if(!e)throw new t("expired");return e}return lt(r.connectionId,Ct(r),e.classification,e=>(l(),e.configuration.displayName=n.displayName,e.configuration.icon=n.icon,e),l)}(e,d);if("none"===n.parameters.token_auth_method===Boolean(o))throw new t("callback");const l=await ue({name:n.displayName,targetBinding:n.fingerprint,fields:o?[{field:"clientSecret",label:"OAuth client secret",value:o}]:[]},i.tomb,s),u=()=>{s(),fe(l,i.tomb,s)},h=a();h.credentials={oauth_client_reference:l.reference,oauth_client_vault:i.tomb};try{return d?await lt(d.connectionId,Ct(d),c,e=>(u(),e.configuration=n,e.privateState=h,e.runtime=p(),e),u):await at({connectionId:`devconn_${crypto.randomUUID()}`,configuration:n,runtime:p(),privateState:h},c,u)}catch(f){throw await pe(l,i.tomb,s),f}}({input:e,desired:n,owner:r,secret:o.client_secret||void 0,fingerprint:Jd,classification:Dd(),check:i,readSecret:e=>Gd(e,r)})}(e,r)}),authorize:(e,r="user")=>{const i=ro();return n(async n=>{if("user"!==r)throw new t("scope");const o=await async function(e,r){Vd(r),await me(),Vd(r);const n=St(e),i=Wd(n.configuration,r),o=Gd(e,r);if(n.privateState.recovery.length||Object.keys(n.privateState.pending).length)throw new t("cleanup");const s=le(32),a=le(32),c=await de(s),d=await de(o??""),l=Date.now(),u={providerId:n.configuration.providerId,actor:"user",fingerprint:n.configuration.fingerprint,issuer:i.issuer,endpoint:i.token_endpoint,resource:i.resource,clientId:i.clientId,state:a,verifier:s,redirectUri:i.redirectUri,scopes:n.configuration.requestedScopes.user??[],createdAt:l,expiresAt:l+6e5},p=Od(n.configuration.providerId),h=new URL(i.authorization_endpoint),f=new URLSearchParams({response_type:"code",client_id:i.clientId,redirect_uri:u.redirectUri,state:a,code_challenge:c,code_challenge_method:"S256"});u.scopes.length&&f.set("scope",u.scopes.join(p.scopeSeparator));for(const[t,m]of Object.entries(p.authorizationParams))f.has(t)||f.set(t,m);return i.resource&&"omit"!==i.resource_parameter&&f.set("resource",i.resource),h.search=f.toString(),await lt(e,Ct(n),Dd(),n=>{if(Vd(r),Gd(e,r)!==o)throw new t("expired");return n.privateState.credentials.oauth_client_consent=`${a}:${d}`,n.privateState.pending.user=u,n.privateState.verification=null,n},()=>Vd(r)),Vd(r),h.href}(e,n),s=St(e).privateState.pending.user;if(!s||!i.authorize)throw new t("callback");try{const r=await i.authorize(o,{state:s.state,expiresAt:s.expiresAt,redirectUri:s.redirectUri,signal:n.transport.signal});await async function(e,r){Vd(r),await me(),Vd(r);const n=await Ut(e,Dd()),i=n.record.connectionId,o=Fd(n.record.configuration),s=n.pending;if(s.endpoint!==o.token_endpoint||s.issuer!==o.issuer||s.resource!==o.resource||s.clientId!==o.clientId||s.redirectUri!==o.redirectUri)throw new t("expired");Wd(n.record.configuration,r);const a=Gd(i,r),c=await de(a??"");if(n.record.privateState.credentials.oauth_client_consent!==`${s.state}:${c}`)throw new t("expired");const d=()=>{Vd(r);const e=St(i);if(e.revision!==n.record.revision||e.configuration.fingerprint!==s.fingerprint)throw new t("expired");if(Gd(i,r)!==a)throw new t("expired")},{form:l,basic:u}=function(e,t,r,n){const i=new URLSearchParams({grant_type:"authorization_code",code:r,code_verifier:t.verifier,redirect_uri:t.redirectUri});let o;const s=void 0!==e.token_relay_url;return s||"client_secret_basic"!==e.token_auth_method?i.set("client_id",e.clientId):o=btoa(`${Xd(e.clientId)}:${Xd(n??"")}`),s||"client_secret_post"!==e.token_auth_method||i.set("client_secret",n??""),e.resource&&"omit"!==e.resource_parameter&&i.set("resource",e.resource),{form:i,basic:o}}(o,s,n.code,a),p=o.token_relay_url??o.token_endpoint,h=At(i,n.obligation.id);try{const e=await f(p,l,function(e,r,n,i){const o=e=>async(o,s)=>{i();const a=new Request(o,s);if(a.url!==r||"POST"!==a.method)throw new t("expired");return n&&a.headers.set("authorization",`Basic ${n}`),e(a)},s={fetch:o(e.fetch),assertCurrent:i,signal:e.signal};return e.settleCredentialMutation&&(s.settleCredentialMutation=o(e.settleCredentialMutation)),s}(r.transport,p,u,d));await async function(e,r){400===r.status&&el.safeParse(r.body).success&&await lt(e.record.connectionId,Ct(e.record),Dd(),r=>{const n=r.privateState.recovery.find(t=>t.id===e.obligation.id);if(!n||n.fingerprint!==e.pending.fingerprint||n.grant||"exchange"!==n.credentials?.phase)throw new t("expired");return r.privateState.recovery=r.privateState.recovery.filter(e=>e.id!==n.id),r})}(n,e);const o=function(e,r,n){const i=Qd.safeParse(e);if(!i.success)throw new t("provider");const o=Yd.safeParse(e),s=Od(n.providerId),a=De(n.providerId,o.success&&void 0!==o.data.scope?function(e,t=" "){return[...new Set(e.split(","===t?/[\s,]+/:/\s+/).filter(Boolean))]}(o.data.scope,s.scopeSeparator):null),c=null===a||a.length<=256&&a.every(e=>e.length<=512),d=Ve(n.providerId,a),l={kind:"oauth",providerId:n.providerId,actor:n.actor,fingerprint:n.fingerprint,issuer:n.issuer,endpoint:n.endpoint,clientId:n.clientId,resource:n.resource,accessToken:i.data.access_token,refreshToken:i.data.refresh_token,expiresAt:o.success&&void 0!==o.data.expires_in?Date.now()+1e3*o.data.expires_in:null,scopes:c?a:null},u=Fe(n.scopes,a,i.data.refresh_token);return{grant:l,valid:r>=200&&r<300&&o.success&&Rd(s,o.data.token_type)&&c&&d&&u}}(e.body,e.status,s),c=Be(s.providerId,s.scopes,o.grant.scopes);await Lt(i,n.obligation.id,o.grant,Dd,{protocol_valid:String(o.valid&&c),requested_scopes:JSON.stringify(s.scopes)}),Vd(r);const h=St(i);if(h.configuration.fingerprint!==s.fingerprint||h.revision!==n.record.revision+1)throw new t("expired");if(Gd(i,r)!==a)throw new t("expired");if(!o.valid)throw new t("provider");if(!c)throw new t("scope");return{connectionId:i,intentId:n.obligation.id}}finally{h()}}(r,n),await ul(e,n)}catch(a){throw await Kd(e,s.state,Dd()),a}})},verify:e=>r(async t=>(await ul(e,t)).view),invoke:(e,n,i,o)=>r(async r=>{if(ll(e))return Td(n,i,{list:()=>function(e,t){return il(e,t,e=>e.session.connect())}(e,r),call:(t,n)=>function(e,t,r,n){return il(e,n,e=>e.session.callTool(t,r,void 0))}(e,t,n,r)});if("provider.resource.read"!==n||Object.keys(i).length)throw new t("scope");const o=await cl(e,r);return Vd(r),{label:"Configured API resource read",items:[{id:Fd(o.view.configuration).resource??"",label:"Resource response",secretValue:JSON.stringify(o.body,null,2)}]}},o),cleanup:{classification:Dd,prepare:(e,t)=>r(async t=>{Vd(t),await Et(e)},void 0,t),cleanup:(e,n)=>r(async r=>{if(Vd(r),St(n.connectionId).privateState.credentials.oauth_client_vault!==r.tomb)throw new t("expired");if(!e.grant&&"exchange"===e.credentials?.phase)throw new t("cleanup");return"local-credential-forgotten"},void 0,n.transport)}}}function hl(e,t){return{serverUrl:"",authorizationEndpoint:"",tokenEndpoint:"",revocationEndpoint:null,userinfoEndpoint:e,tokenAuth:"none",pkce:"S256",authorizationParams:{},scopes:[],refreshTokens:!1,registration:"manual",consoleUrl:null,docsUrl:t,templateParams:[],verify:null,scopeSeparator:" ",registrationEndpoint:null}}function fl(e){if(e.refused)return null;const t=e.methods.find(e=>"mcp"===e.kind),r="mcp"===t?.kind?t.mcp:null,n=r?{endpoint:r.url,transport:new URL(r.url).pathname.endsWith("/sse")?"sse":"streamable-http"}:{},i=e.methods.find(e=>"oauth"===e.kind);return"oauth"===i?.kind&&i.preset?{preset:i.preset,resourceParameter:i.preset.resourceParameter??"omit",...n}:r?{preset:(o=r,s=e.docsUrl,"ok"!==o.status?hl(o.url,s):{...hl(o.resource??o.url,s),serverUrl:o.issuer??"",authorizationEndpoint:o.authorizationEndpoint,tokenEndpoint:o.tokenEndpoint,revocationEndpoint:o.revocationEndpoint,tokenAuth:(a=o.tokenAuthMethods,a.includes("client_secret_basic")?"client_secret_basic":a.includes("client_secret_post")?"client_secret_post":"none"),scopes:o.scopes.map(e=>({name:e,description:"Permission advertised by the MCP server.",default:!1}))}),protocol:"mcp",...n}:null;var o,s,a}const ml={publicParameters:["vault_url"],privateCredentials:["token"]},wl={family:"Azure Key Vault Secrets",accepts:Xt.accepts,classification:ml};function gl(){throw new G("stale","The saved Azure secret authority changed.")}function vl(e){return Q({connectionId:e.connectionId,revision:e.revision,configuration:e.configuration,runtime:e.runtime,privateState:e.privateState})}function yl(e,t){const r=t.backend,n=t.session;let i;async function o(t,r){t!==n&&gl(),await e.current();try{const t=await r();return await e.current(),e.check(),t}catch(i){if(i instanceof Te&&(401===i.status||403===i.status)){try{await Dt(ml,e.saved,e.transport)}catch{}e.close()}throw i}}const s=r.createItem,a=r.updateItem,c=r.deleteItem;if(!s||!a||!c)throw new G("unsupported","The native Azure backend has no mutation surface.");return{signal:e.signal,id:r.id,name:e.saved.configuration.displayName,capabilities:r.capabilities,authenticate:async()=>{throw new G("unsupported","Open the saved native Azure connection instead of supplying another credential.")},listItems:e=>o(e,()=>r.listItems(n)),getItem:(e,t)=>o(t,()=>r.getItem(e,n)),getNotes:(e,t)=>o(t,()=>r.getNotes(e,n)),createItem:(e,t)=>o(t,()=>s.call(r,e,n)),updateItem:(e,t,i)=>o(i,()=>a.call(r,e,t,n)),deleteItem:(e,t)=>o(t,()=>c.call(r,e,n)),disconnect:t=>(t!==n&&gl(),i||(i=Promise.resolve().then(()=>r.disconnect(n)),e.close()),i)}}async function _l(e,t){const r=function(e,t){const r=t.transport??ee().capture();r.assertCurrent();const n=r.signal;if(!n)throw new G("configuration","The native provider has no captured lifetime.");const i=t.assertCurrent,o=t.signal;n.throwIfAborted(),o?.throwIfAborted(),i?.();const s=K(t.vault),a=new AbortController,c=AbortSignal.any([n,a.signal,...o?[o]:[]]);let d=()=>{},l=()=>{},u=!1;const p=()=>{u||(u=!0,d(),l(),s.close(),c.removeEventListener("abort",p),a.abort())};try{const n=Nt(wl,e,!0),o=vl(n),a={baseUrl:n.configuration.parameters.vault_url??"",token:n.privateState.credentials.token??""},u=()=>{try{c.throwIfAborted(),r.assertCurrent(),i?.(),s.current(),vl(Nt(wl,e,!0))!==o&&gl(),c.throwIfAborted()}catch(t){throw p(),t}},h={signal:c,assertCurrent:u,fetch:(e,t)=>(u(),r.fetch(e,{...t,signal:AbortSignal.any([c,...e instanceof Request?[e.signal]:[],...t?.signal?[t.signal]:[]])}))};return d=ce(()=>{try{u()}catch{p()}}),l=t.vault.onLock(p),c.addEventListener("abort",p,{once:!0}),u(),{saved:n,config:a,transport:h,signal:c,check:u,close:p,async current(){u(),await dt(e,Ct(n)),u()}}}catch(h){throw p(),h}}(e,t);let n;try{await r.current(),await Xt.invoke(e,"provider.read",{},r.transport),await r.current();const t=await we(()=>import("./secret-backends-_-CBukTJ.js").then(e=>e.B),[]);return r.check(),n=await t.openAzureKeyVaultSecretBackend(r.config,r.transport),await r.current(),r.check(),{backend:yl(r,n),session:n.session}}catch(i){throw r.close(),n&&await n.backend.disconnect(n.session),i}}function bl(){const e=this.buf;let t=this.pos,r=0,n=0;for(let o=0;o<28;o+=7){const i=e[t++];if(r|=(127&i)<<o,!(128&i))return this.pos=t,this.assertBounds(),this.varint64Lo=r,void(this.varint64Hi=n)}const i=e[t++];if(r|=(15&i)<<28,n=(112&i)>>4,!(128&i))return this.pos=t,this.assertBounds(),this.varint64Lo=r,void(this.varint64Hi=n);for(let o=3;o<=31;o+=7){const i=e[t++];if(n|=(127&i)<<o,!(128&i))return this.pos=t,this.assertBounds(),this.varint64Lo=r,void(this.varint64Hi=n)}throw new Error("invalid varint")}const kl=4294967296;function Il(e){const t="-"===e[0];t&&(e=e.slice(1));const r=1e6;let n=0,i=0;function o(t,o){const s=Number(e.slice(t,o));i*=r,n=n*r+s,n>=kl&&(i+=n/kl|0,n%=kl)}return o(-24,-18),o(-18,-12),o(-12,-6),o(-6),t?Tl(n,i):Cl(n,i)}function Sl(e,t){if(({lo:e,hi:t}=function(e,t){return{lo:e>>>0,hi:t>>>0}}(e,t)),t<=2097151)return String(kl*t+e);const r=16777215&(e>>>24|t<<8),n=t>>16&65535;let i=(16777215&e)+6777216*r+6710656*n,o=r+8147497*n,s=2*n;const a=1e7;return i>=a&&(o+=Math.floor(i/a),i%=a),o>=a&&(s+=Math.floor(o/a),o%=a),s.toString()+xl(o)+xl(i)}function Cl(e,t){return{lo:0|e,hi:0|t}}function Tl(e,t){return t=~t,e?e=1+~e:t+=1,Cl(e,t)}const xl=e=>{const t=String(e);return"0000000".slice(t.length)+t};function $l(){let e=this.buf[this.pos++];if(!(128&e))return this.assertBounds(),e;let t=127&e;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let r=5;128&e&&r<10;r++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}var Al={};const Pl=El();function El(){const e=new DataView(new ArrayBuffer(8));if("function"==typeof BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64&&(globalThis.Deno||globalThis.Bun||"object"!=typeof process||"1"!==Al.BUF_BIGINT_DISABLE)){const t=BigInt("-9223372036854775808"),r=BigInt("9223372036854775807"),n=BigInt("0"),i=BigInt("18446744073709551615");return{zero:BigInt(0),supported:!0,parse(e){const n="bigint"==typeof e?e:BigInt(e);if(n>r||n<t)throw new Error(`invalid int64: ${e}`);return n},uParse(e){const t="bigint"==typeof e?e:BigInt(e);if(t>i||t<n)throw new Error(`invalid uint64: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec:(t,r)=>(e.setInt32(0,t,!0),e.setInt32(4,r,!0),e.getBigInt64(0,!0)),uDec:(t,r)=>(e.setInt32(0,t,!0),e.setInt32(4,r,!0),e.getBigUint64(0,!0))}}return{zero:"0",supported:!1,parse:e=>("string"!=typeof e&&(e=e.toString()),Ol(e),e),uParse:e=>("string"!=typeof e&&(e=e.toString()),Rl(e),e),enc:e=>("string"!=typeof e&&(e=e.toString()),Ol(e),Il(e)),uEnc:e=>("string"!=typeof e&&(e=e.toString()),Rl(e),Il(e)),dec:(e,t)=>function(e,t){let r=Cl(e,t);const n=2147483648&r.hi;n&&(r=Tl(r.lo,r.hi));const i=Sl(r.lo,r.hi);return n?"-"+i:i}(e,t),uDec:(e,t)=>Sl(e,t)}}function Ol(e){if(!/^-?[0-9]+$/.test(e))throw new Error("invalid int64: "+e)}function Rl(e){if(!/^[0-9]+$/.test(e))throw new Error("invalid uint64: "+e)}let Ml;function ql(){if(!Ml){const r=globalThis;if(!r.TextEncoder||!r.TextDecoder)throw new Error("encoding API missing: install TextEncoder and TextDecoder on globalThis");const n=new r.TextEncoder,i=new r.TextDecoder;let o;const s={encodeUtf8:e=>n.encode(e),decodeUtf8:(e,t)=>t?(o||(o=new r.TextDecoder("utf-8",{fatal:!0})),o.decode(e)):i.decode(e),checkUtf8(e){try{return encodeURIComponent(e),!0}catch(t){return!1}}};n.encodeInto&&(s.encodeUtf8Into=n.encodeInto.bind(n));const a=String.prototype.isWellFormed;a&&(s.checkUtf8=e=>a.call(e)),e=s,Ml=Object.assign(Object.assign({},e),{encodeUtf8Into:null!==(t=e.encodeUtf8Into)&&void 0!==t?t:Ul(e.encodeUtf8.bind(e))})}var e,t;return Ml}function Ul(e){return(t,r)=>{const n=e(t);return r.set(n),{written:n.byteLength}}}var Ll,jl;(jl=Ll||(Ll={}))[jl.Varint=0]="Varint",jl[jl.Bit64=1]="Bit64",jl[jl.LengthDelimited=2]="LengthDelimited",jl[jl.StartGroup=3]="StartGroup",jl[jl.EndGroup=4]="EndGroup",jl[jl.Bit32=5]="Bit32";class zl{constructor(e){this.stackPos=[],this.encodeUtf8Into=e?Ul(e):ql().encodeUtf8Into,this.buffer=Dl,this.viewCache=Vl,this.pos=0}ensureCapacity(e){const t=this.pos+e;if(t>this.buffer.length){let e=this.buffer.length||Nl;for(;e<t;)e*=2;const r=new Uint8Array(e);this.pos>0&&r.set(this.buffer),this.buffer=r}}view(){const e=this.buffer,t=this.viewCache;if(t.byteLength===e.byteLength)return t;const r=new DataView(e.buffer);return this.viewCache=r,r}finish(){const e=this.buffer.slice(0,this.pos);return this.pos=0,this.stackPos=[],e}fork(){return this.stackPos.push(this.pos),this.ensureCapacity(Hl),this.buffer[this.pos++]=0,this}join(){const e=this.stackPos.pop();if(void 0===e)throw new Error("invalid state, fork stack empty");const t=this.pos-e-Hl,r=Wl(t);return r>Hl&&(this.ensureCapacity(r-Hl),this.buffer.copyWithin(e+r,e+Hl,this.pos)),this.pos=e,this.uint32(t),this.pos+=t,this}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.ensureCapacity(e.length),this.buffer.set(e,this.pos),this.pos+=e.length,this}uint32(e){if(Gl(e),this.ensureCapacity(5),e<128)return this.buffer[this.pos++]=e,this;for(;e>127;)this.buffer[this.pos++]=127&e|128,e>>>=7;return this.buffer[this.pos++]=e,this}int32(e){if(Jl(e),e>=0)return this.uint32(e);this.ensureCapacity(10);for(let t=0;t<9;t++)this.buffer[this.pos++]=127&e|128,e>>=7;return this.buffer[this.pos++]=1,this}bool(e){return this.ensureCapacity(1),this.buffer[this.pos++]=e?1:0,this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){"string"!=typeof e&&(e=String(e));const t=e.length;if(t<=Fl){this.ensureCapacity(t+1);const r=this.buffer;let n=this.pos;r[n++]=t;let i=0;for(;i<t;i++){const t=e.charCodeAt(i);if(t>127)break;r[n++]=t}if(i==t)return this.pos=n,this}this.ensureCapacity(3*t+5);const r=Wl(t),n=this.buffer,i=this.pos,{written:o}=this.encodeUtf8Into(e,n.subarray(i+r)),s=Wl(o);return s!=r&&n.copyWithin(i+s,i+r,i+r+o),this.uint32(o),this.pos+=o,this}float(e){return function(e){if("string"==typeof e){const t=e;if(e=Number(e),Number.isNaN(e)&&"NaN"!==t)throw new Error("invalid float32: "+t)}else if("number"!=typeof e)throw new Error("invalid float32: "+typeof e);if(!Number.isFinite(Math.fround(e))&&Number.isFinite(e))throw new Error("invalid float32: "+e)}(e),this.ensureCapacity(4),this.view().setFloat32(this.pos,e,!0),this.pos+=4,this}double(e){return this.ensureCapacity(8),this.view().setFloat64(this.pos,e,!0),this.pos+=8,this}fixed32(e){return Gl(e),this.ensureCapacity(4),this.view().setUint32(this.pos,e,!0),this.pos+=4,this}sfixed32(e){return Jl(e),this.ensureCapacity(4),this.view().setInt32(this.pos,e,!0),this.pos+=4,this}sint32(e){return Jl(e),this.uint32((e<<1^e>>31)>>>0)}sfixed64(e){const t=Pl.enc(e);this.ensureCapacity(8);const r=this.view();return r.setInt32(this.pos,t.lo,!0),r.setInt32(this.pos+4,t.hi,!0),this.pos+=8,this}fixed64(e){const t=Pl.uEnc(e);this.ensureCapacity(8);const r=this.view();return r.setInt32(this.pos,t.lo,!0),r.setInt32(this.pos+4,t.hi,!0),this.pos+=8,this}int64(e){const t=Pl.enc(e);return this.writeVarint64(t.lo,t.hi)}sint64(e){const t=Pl.enc(e),r=t.hi>>31;return this.writeVarint64(t.lo<<1^r,(t.hi<<1|t.lo>>>31)^r)}uint64(e){const t=Pl.uEnc(e);return this.writeVarint64(t.lo,t.hi)}writeVarint64(e,t){this.ensureCapacity(10);const r=this.buffer;let n=this.pos;for(let s=0;s<28;s+=7){const i=e>>>s,o=!(i>>>7==0&&0==t);if(r[n++]=255&(o?128|i:i),!o)return this.pos=n,this}const i=e>>>28&15|(7&t)<<4,o=!!(t>>3);if(r[n++]=255&(o?128|i:i),!o)return this.pos=n,this;for(let s=3;s<31;s+=7){const e=t>>>s,i=!(e>>>7==0);if(r[n++]=255&(i?128|e:e),!i)return this.pos=n,this}return r[n++]=t>>>31&1,this.pos=n,this}}const Nl=128,Hl=1,Dl=new Uint8Array(0),Vl=new DataView(Dl.buffer),Fl=32;function Wl(e){return e<128?1:e<16384?2:e<2097152?3:e<268435456?4:5}class Bl{constructor(e,t=ql().decodeUtf8){this.decodeUtf8=t,this.varint64Lo=0,this.varint64Hi=0,this.varint64=bl,this.uint32=$l,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){const e=this.pos,t=this.uint32(),r=this.pos-e;if(r>5||5==r&&this.buf[this.pos-1]>15)throw new Error("illegal tag: varint overflows uint32");const n=t>>>3,i=7&t;if(n<=0||i>5)throw new Error("illegal tag: field no "+n+" wire type "+i);return[n,i]}skip(e,t,r=100){let n=this.pos;switch(e){case Ll.Varint:for(;128&this.buf[this.pos++];);break;case Ll.Bit64:this.pos+=4;case Ll.Bit32:this.pos+=4;break;case Ll.LengthDelimited:let n=this.uint32();this.pos+=n;break;case Ll.StartGroup:if(r<=0)throw new Error("maximum recursion depth reached");for(;;){const[e,n]=this.tag();if(n===Ll.EndGroup){if(void 0!==t&&e!==t)throw new Error("invalid end group tag");break}this.skip(n,e,r-1)}break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return this.varint64(),Pl.dec(this.varint64Lo,this.varint64Hi)}uint64(){return this.varint64(),Pl.uDec(this.varint64Lo,this.varint64Hi)}sint64(){this.varint64();let e=this.varint64Lo,t=this.varint64Hi,r=-(1&e);return e=(e>>>1|(1&t)<<31)^r,t=t>>>1^r,Pl.dec(e,t)}bool(){const e=this.buf[this.pos];return e<128?(this.pos++,0!==e):(this.varint64(),0!==this.varint64Lo||0!==this.varint64Hi)}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return Pl.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return Pl.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(e){const t=this.bytes(),r=t.length;if(r<=Fl){const n=new Array(r);for(let i=0;i<r;i++){const r=t[i];if(r>127)return this.decodeUtf8(t,e);n[i]=r}return String.fromCharCode.apply(String,n)}return this.decodeUtf8(t,e)}}function Jl(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid int32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int32: "+e)}function Gl(e){if("string"==typeof e)e=Number(e);else if("number"!=typeof e)throw new Error("invalid uint32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint32: "+e)}export{fd as $,rr as A,Bl as B,at as C,lo as D,so as E,Ns as F,$t as G,Js as H,Pt as I,ua as J,Us as K,_t as L,Ms as M,Ld as N,Ee as O,Me as P,pt as Q,St as R,At as S,tl as T,Oe as U,aa as V,Lt as W,io as X,Je as Y,oo as Z,He as _,zl as a,wd as a0,Ht as a1,Nt as a2,Dt as a3,no as a4,Et as a5,jt as a6,Rt as a7,Ut as a8,Kd as a9,qt as aa,Mt as ab,hd as ac,Td as ad,sd as ae,nr as af,pl as b,fl as c,Fd as d,Ys as e,da as f,er as g,_d as h,xd as i,to as j,ro as k,Xe as l,vt as m,jd as n,_l as o,Ot as p,bt as q,et as r,Cd as s,ut as t,lt as u,dt as v,Bt as w,Ct as x,Xt as y,tr as z};
|