decocms 4.387.3 → 4.388.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/dist/client/assets/{AlertCircle-Cn5BAuQ8.js → AlertCircle-B3vbo2n4.js} +1 -1
- package/dist/client/assets/{AreaChart-D3bzhKz9.js → AreaChart-Yh8fUuWv.js} +1 -1
- package/dist/client/assets/{ArrowLeft-C1cb2Dj2.js → ArrowLeft-D3qL-XiQ.js} +1 -1
- package/dist/client/assets/{ArrowRight-B2ezCKjo.js → ArrowRight-TVV5ykHB.js} +1 -1
- package/dist/client/assets/{ArrowUp-vXPxRqH5.js → ArrowUp-Dl9293Zm.js} +1 -1
- package/dist/client/assets/{CartesianChart-D3s-SeRT.js → CartesianChart-DfoC6a-3.js} +1 -1
- package/dist/client/assets/{Check-DThMruer.js → Check-D_tlADVZ.js} +1 -1
- package/dist/client/assets/{CheckCircle-DYnWzsSa.js → CheckCircle-0fEKB6B3.js} +1 -1
- package/dist/client/assets/{ChevronUp-Ci06-tVi.js → ChevronUp-CZododOc.js} +1 -1
- package/dist/client/assets/{Copy01-Dj1rsZ7p.js → Copy01-BxWduMFI.js} +1 -1
- package/dist/client/assets/{CreditCard01-CX4d68BY.js → CreditCard01-B_POaQ4q.js} +1 -1
- package/dist/client/assets/{DotsVertical-CZ00QIyA.js → DotsVertical-B0Iw1UeS.js} +1 -1
- package/dist/client/assets/{Download01-Bx9EIyyF.js → Download01-B9Zxwy2S.js} +1 -1
- package/dist/client/assets/{ErrorBarContext-CsqJadNC.js → ErrorBarContext-CZlY3SbC.js} +1 -1
- package/dist/client/assets/{Eye-bkJA-6md.js → Eye-C9j6hpaR.js} +1 -1
- package/dist/client/assets/{Globe04-CHrNXcGc.js → Globe04-CS-hrWJa.js} +1 -1
- package/dist/client/assets/{Image01-DA0_XwMj.js → Image01-CiKG1988.js} +1 -1
- package/dist/client/assets/{Key01-iIe0ym2P.js → Key01-pzGK6JH7.js} +1 -1
- package/dist/client/assets/{LayoutLeft-S_wLdWXH.js → LayoutLeft-Bnqg216Y.js} +1 -1
- package/dist/client/assets/{Line-B0E8BW5x.js → Line-DCXUVJoa.js} +1 -1
- package/dist/client/assets/{Link01-BmRe1LbW.js → Link01-BdGwRjsp.js} +1 -1
- package/dist/client/assets/{LinkExternal01-CZ1KGMqp.js → LinkExternal01-DKesUYi5.js} +1 -1
- package/dist/client/assets/{Monitor01-DwlHZDjH.js → Monitor01-UFcMi6Mo.js} +1 -1
- package/dist/client/assets/{Package-CS7Zmqsi.js → Package-6pKWLwBq.js} +1 -1
- package/dist/client/assets/{Palette-DFGQ_LgU.js → Palette-D2q-ZicE.js} +1 -1
- package/dist/client/assets/{Plus-q0JJEXEj.js → Plus-ByhE8WcD.js} +1 -1
- package/dist/client/assets/{SearchLg-teGOx5Lm.js → SearchLg-qnEtqtLB.js} +1 -1
- package/dist/client/assets/{SearchMd-CKgYK_Bl.js → SearchMd-DWmNu2U_.js} +1 -1
- package/dist/client/assets/{Sector-CyRj2bq_.js → Sector-CneAt4Gv.js} +1 -1
- package/dist/client/assets/{Share07-DAILO0KI.js → Share07-BqNOPmHA.js} +1 -1
- package/dist/client/assets/{Stars01-C7sg4bdl.js → Stars01-Dkj_wrJI.js} +1 -1
- package/dist/client/assets/{Sun-Dd59quzz.js → Sun-BVwRyOQy.js} +1 -1
- package/dist/client/assets/{Tool01-B9aH9biT.js → Tool01-Ykv0VphE.js} +1 -1
- package/dist/client/assets/{Trash01-D8KEbJ3X.js → Trash01-BLI32Zf8.js} +1 -1
- package/dist/client/assets/{Upload01-93RPdx3u.js → Upload01-DFmVph6Y.js} +1 -1
- package/dist/client/assets/{User01-D7tuP5r3.js → User01-BhEBu8iZ.js} +1 -1
- package/dist/client/assets/{UserSquare-BF_SmURo.js → UserSquare-CHWuMbCn.js} +1 -1
- package/dist/client/assets/{Users01-G1EXZRGt.js → Users01-Cfge0Lra.js} +1 -1
- package/dist/client/assets/{X-B0v0RdVM.js → X-CWAHEOzU.js} +1 -1
- package/dist/client/assets/{XCircle-1GqBoy9j.js → XCircle-qVUpsS9M.js} +1 -1
- package/dist/client/assets/{XClose-BlJju2Q7.js → XClose-qmmFqCGy.js} +1 -1
- package/dist/client/assets/{Zap-BbRQJwH6.js → Zap-DrC6qRHo.js} +1 -1
- package/dist/client/assets/{ZoomOut-42z6KqeQ.js → ZoomOut-XXX--5-d.js} +1 -1
- package/dist/client/assets/{access-gate-DAZyoF2B.js → access-gate-CLIznoIq.js} +1 -1
- package/dist/client/assets/{add-connection-dialog-Wp9CjVne.js → add-connection-dialog-Dgk-Fo2O.js} +1 -1
- package/dist/client/assets/{agent-analytics-CtGFzjZS.js → agent-analytics-ypQJRGpO.js} +1 -1
- package/dist/client/assets/agent-app-DLHKX0zW.js +1 -0
- package/dist/client/assets/{agent-assets-D-VG0sfj.js → agent-assets-DqoWPCeO.js} +1 -1
- package/dist/client/assets/{agent-automation-BI-xsNzD.js → agent-automation-B1GI-IUL.js} +1 -1
- package/dist/client/assets/{agent-automations-CSjIsWJ3.js → agent-automations-C4C56Ppt.js} +1 -1
- package/dist/client/assets/{agent-connect-sources-BnKv9n_g.js → agent-connect-sources-kgcoC2NH.js} +1 -1
- package/dist/client/assets/agent-deck-CFXZozzL.js +1 -0
- package/dist/client/assets/{agent-e2e-Cw6Yewb5.js → agent-e2e-D-RGNzmF.js} +1 -1
- package/dist/client/assets/{agent-experiments-CmIK1AeZ.js → agent-experiments-DdKmJSPF.js} +1 -1
- package/dist/client/assets/agent-file-Cdzmox1M.js +1 -0
- package/dist/client/assets/{agent-git-DxCrke6t.js → agent-git-BUhy80bl.js} +1 -1
- package/dist/client/assets/{agent-hosting-Kq8BYIDy.js → agent-hosting-DgsS95Ie.js} +1 -1
- package/dist/client/assets/{agent-icon-ChShOftK.js → agent-icon-divnTd88.js} +1 -1
- package/dist/client/assets/agent-library-file-1s5_RvBJ.js +1 -0
- package/dist/client/assets/{agent-monitor-BgSNkTBZ.js → agent-monitor-BLG_l_nw.js} +1 -1
- package/dist/client/assets/{agent-overview-CZv5Zodz.js → agent-overview-CnOztAR4.js} +1 -1
- package/dist/client/assets/agent-settings-DD9dMgS4.js +1 -0
- package/dist/client/assets/{agent-site-editor-BuYiW7vY.js → agent-site-editor-DrQ7F-c2.js} +1 -1
- package/dist/client/assets/agent-site-editor-code-DOoSUnhO.js +2 -0
- package/dist/client/assets/{agent-site-editor-content-C5kLEJyk.js → agent-site-editor-content-7EGHbN2s.js} +2 -2
- package/dist/client/assets/{agent-site-editor-preview-Az3ek__O.js → agent-site-editor-preview-CNQARCEM.js} +3 -3
- package/dist/client/assets/agent-view-CvNkWxfz.js +1 -0
- package/dist/client/assets/{agent-view-guard-gULWISq_.js → agent-view-guard-DcLXrFY7.js} +1 -1
- package/dist/client/assets/{agents-list-Bt10GQwH.js → agents-list-BnSIzGi_.js} +1 -1
- package/dist/client/assets/{ai-providers-cUeuBIyk.js → ai-providers-DOhvFs8_.js} +1 -1
- package/dist/client/assets/{alert-BJcxnkZj.js → alert-C9f3lMWV.js} +1 -1
- package/dist/client/assets/{alert-dialog-Bp1Wh9ug.js → alert-dialog-CoURP6JP.js} +1 -1
- package/dist/client/assets/api-keys-BTjpmk07.js +1 -0
- package/dist/client/assets/{api-keys-Cclaz3YO.js → api-keys-e7ZGvNnY.js} +1 -1
- package/dist/client/assets/app-editor-xnF9j2IL.js +1 -0
- package/dist/client/assets/{asset-utils-8jzw22Fk.js → asset-utils-CGhDuCoB.js} +1 -1
- package/dist/client/assets/{auth-C6R_bci9.js → auth-Cp5MWYdV.js} +1 -1
- package/dist/client/assets/{auth-catchall-u05USxEd.js → auth-catchall-DYItykNy.js} +1 -1
- package/dist/client/assets/{auth-entry-CCBdjm-M.js → auth-entry-Q3dYUM1O.js} +1 -1
- package/dist/client/assets/{auth-split-layout-BxYvw9jZ.js → auth-split-layout-BvWYkE3p.js} +1 -1
- package/dist/client/assets/{authenticate-and-persist-oauth-Ajo42lKz.js → authenticate-and-persist-oauth-CeZbUQJ3.js} +1 -1
- package/dist/client/assets/{automation-list-row-J21yfJy5.js → automation-list-row-CSwkkwa1.js} +1 -1
- package/dist/client/assets/{automation-runs-B3iW2JfX.js → automation-runs-FaCqipXn.js} +1 -1
- package/dist/client/assets/{automations-6wORWmmO.js → automations-DtAw8o6m.js} +1 -1
- package/dist/client/assets/{autosend-BXGtsYdm.js → autosend-bcZiscel.js} +1 -1
- package/dist/client/assets/{avatar-asg_vbnd.js → avatar-DkdwXmnt.js} +1 -1
- package/dist/client/assets/{badge-xdcxrJKk.js → badge-C-WEeGXr.js} +1 -1
- package/dist/client/assets/{block-document-De1smcS7.js → block-document-BH7uPsFs.js} +1 -1
- package/dist/client/assets/{blocks-preview-workspace-context-DOL5kwZe.js → blocks-preview-workspace-context-JZgpiL3E.js} +1 -1
- package/dist/client/assets/{breadcrumb-D-aZ536w.js → breadcrumb-BFQDnz1s.js} +1 -1
- package/dist/client/assets/{buckets-CKVfgo9B.js → buckets-CQDlrdX7.js} +1 -1
- package/dist/client/assets/{build-improve-prompt-doc-CJ_btnj2.js → build-improve-prompt-doc-rZuI3ein.js} +1 -1
- package/dist/client/assets/{bulk-category-panel-Dtv5K1gv.js → bulk-category-panel-Db5NOZeC.js} +1 -1
- package/dist/client/assets/{calendar-DmTWU2Dj.js → calendar-Bl5KJT_m.js} +1 -1
- package/dist/client/assets/{capability-load-error-BtBiaoOL.js → capability-load-error-bsZZ3MDG.js} +1 -1
- package/dist/client/assets/{category-editor-CtQ8SFrj.js → category-editor-B3WVieTJ.js} +1 -1
- package/dist/client/assets/{chart-By5JOrgr.js → chart-BlDO6lmw.js} +1 -1
- package/dist/client/assets/{chat-context-B4KQCgP1.js → chat-context-DlQMH2wV.js} +1 -1
- package/dist/client/assets/{chat-draft-BFkpd5S4.js → chat-draft-Ey6VTCc6.js} +1 -1
- package/dist/client/assets/{checkbox-DkMsGFfB.js → checkbox-CetAIQt3.js} +1 -1
- package/dist/client/assets/{choose-editor-I_GekUn-.js → choose-editor-E0PoMRqt.js} +1 -1
- package/dist/client/assets/{cli-auth-success-cmV7yG1h.js → cli-auth-success-BDCK7RdA.js} +1 -1
- package/dist/client/assets/{client-icons-BecL3PoT.js → client-icons-C9pOgXGn.js} +1 -1
- package/dist/client/assets/{collapsible-CiVUXMvJ.js → collapsible-F0ucrOT2.js} +1 -1
- package/dist/client/assets/{collection-detail-D9i4qKmD.js → collection-detail-son9oWms.js} +1 -1
- package/dist/client/assets/{collection-display-button-XhnDDz5v.js → collection-display-button-BoGvFGDf.js} +1 -1
- package/dist/client/assets/{collection-search-B4N5GV2h.js → collection-search-MM7huzHV.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-DN2Gygzm.js → collection-table-wrapper-DwnvMNEo.js} +1 -1
- package/dist/client/assets/{collection-tabs-B2AyzmKC.js → collection-tabs-K4gdTMTz.js} +1 -1
- package/dist/client/assets/{combobox-Cmum4Pv7.js → combobox-DcDs621E.js} +1 -1
- package/dist/client/assets/{command-BBAD9vA7.js → command-C2V0RClc.js} +1 -1
- package/dist/client/assets/{companion-mcps-section-q1gXHeiO.js → companion-mcps-section-MHc9gkDP.js} +1 -1
- package/dist/client/assets/{connect-BfRTEvsk.js → connect-D41RRDUk.js} +1 -1
- package/dist/client/assets/{connect-layout-BEo2e3W9.js → connect-layout-B0lwhzHq.js} +1 -1
- package/dist/client/assets/{connection-DqZD1QkX.js → connection-Cun5XH5M.js} +1 -1
- package/dist/client/assets/{connection-card-CNk1VF9T.js → connection-card-DLOUTnaw.js} +1 -1
- package/dist/client/assets/{connection-detail-rnttSUaR.js → connection-detail-6ikNU4PB.js} +1 -1
- package/dist/client/assets/{connection-form-helpers-CYDAD3tu.js → connection-form-helpers-BXGTvVI-.js} +1 -1
- package/dist/client/assets/{connections-DfEEylPK.js → connections-KBXuKPoG.js} +1 -1
- package/dist/client/assets/{create-organization-dialog-zJmseNUX.js → create-organization-dialog-CsZA9PRp.js} +1 -1
- package/dist/client/assets/{decofile-api-3OB04pBU.js → decofile-api-CWbA3cSc.js} +1 -1
- package/dist/client/assets/{decopilot-DZWOrBAr.js → decopilot-DQL3SRkD.js} +1 -1
- package/dist/client/assets/{dialog-De2EEL_R.js → dialog-Bc0b91qz.js} +1 -1
- package/dist/client/assets/{discover-BS1efjTk.js → discover-CkXO0-VH.js} +1 -1
- package/dist/client/assets/{domain-settings-BHU6H8QF.js → domain-settings-brlSn5FP.js} +1 -1
- package/dist/client/assets/{download-app-dialog-DwLh9oUS.js → download-app-dialog-BbPnWlx7.js} +1 -1
- package/dist/client/assets/{drawer-BzdH2Qko.js → drawer-DhPaxB79.js} +1 -1
- package/dist/client/assets/{editor-CEygCPaM.js → editor-a0WmA-YY.js} +1 -1
- package/dist/client/assets/{empty-state-DNdzgv1P.js → empty-state--qShNy1w.js} +1 -1
- package/dist/client/assets/{empty-state-BHb1rpcB.js → empty-state-DWDFQbGC.js} +1 -1
- package/dist/client/assets/{extract-connection-data-BrnzWWb9.js → extract-connection-data-9RCfjOgD.js} +1 -1
- package/dist/client/assets/{feature-gate-Dvp_OGZA.js → feature-gate-CgGa3ZDG.js} +1 -1
- package/dist/client/assets/{feature-paywall-C2c-AjSv.js → feature-paywall-DJX2siu_.js} +1 -1
- package/dist/client/assets/{file-explorer-CxEGeae7.js → file-explorer-BEXMjT8z.js} +1 -1
- package/dist/client/assets/{file-preview-C7fQ2q4M.js → file-preview-BumkWVqe.js} +1 -1
- package/dist/client/assets/{file-share-button-CX6_EXa7.js → file-share-button-Duq13WCj.js} +1 -1
- package/dist/client/assets/{file-type-icon-CDX3kd9G.js → file-type-icon-BcnPvY0i.js} +1 -1
- package/dist/client/assets/{folder-icon-DJX80o6U.js → folder-icon-B5Scx265.js} +1 -1
- package/dist/client/assets/{form-DCRqQIWX.js → form-_T61niJY.js} +1 -1
- package/dist/client/assets/{gateway-client-D4JfXse4.js → gateway-client-CnDTfx_S.js} +1 -1
- package/dist/client/assets/{general-Dmn5Ura5.js → general-CVz_RoFN.js} +1 -1
- package/dist/client/assets/{github-icon-CqSKza4O.js → github-icon-DsbtDmDz.js} +1 -1
- package/dist/client/assets/{home-l_thHdAp.js → home-DeQWav87.js} +1 -1
- package/dist/client/assets/{hooks-BRAKbaiE.js → hooks-aU1jFzgz.js} +1 -1
- package/dist/client/assets/{hooks-DxLB5Hd8.js → hooks-vksrlvlh.js} +1 -1
- package/dist/client/assets/{icon-button-Za10rcHY.js → icon-button-OlTmmJA2.js} +1 -1
- package/dist/client/assets/{index-3R7Odim5.js → index-B1FDJFo6.js} +1 -1
- package/dist/client/assets/{index-Byl7Gx5D.js → index-BbFhejIw.js} +1 -1
- package/dist/client/assets/{index-A0MIFjlk.js → index-C4MSgrlx.js} +1 -1
- package/dist/client/assets/{index-Dt7KlawQ.js → index-CZjk6esA.js} +1 -1
- package/dist/client/assets/{index-C4uIUqoH.js → index-DICH1Iwn.js} +1 -1
- package/dist/client/assets/{index-BymQvfX0.js → index-DSlHDmY9.js} +1 -1
- package/dist/client/assets/{index-3AkUa4fJ.js → index-DoMedB57.js} +6 -6
- package/dist/client/assets/{index-B1gHPPQS.js → index-DorJkHHg.js} +1 -1
- package/dist/client/assets/{index-yj0yZ8ds.js → index-Mlw2Lvi5.js} +1 -1
- package/dist/client/assets/{index-B49gjwBE.js → index-bQ6kPwbH.js} +1 -1
- package/dist/client/assets/{index-CtQLpJyL.js → index-pviDbl5M.js} +1 -1
- package/dist/client/assets/{index-redirect-BJ__JV0A.js → index-redirect-C1UwKejc.js} +1 -1
- package/dist/client/assets/{index-DsxNcE-Q.js → index-sk2sSzBL.js} +1 -1
- package/dist/client/assets/{index-BGop0XEN.js → index-tlSWakM4.js} +1 -1
- package/dist/client/assets/{index-BxKyNL1s.js → index-xILAqSaa.js} +1 -1
- package/dist/client/assets/{infiniteQueryObserver-y1i8bZ9i.js → infiniteQueryObserver-aaHUJUze.js} +1 -1
- package/dist/client/assets/{infra-billing-BtXZ1yQE.js → infra-billing-CY1SQkDW.js} +1 -1
- package/dist/client/assets/{input-DXtRHSQP.js → input-BcrWgMXI.js} +1 -1
- package/dist/client/assets/{input-DAURwDVS.js → input-PwEo6j5x.js} +1 -1
- package/dist/client/assets/{input-C-98gOPX.js → input-yrJmpPKL.js} +1 -1
- package/dist/client/assets/{integration-icon-Bw7f5AIM.js → integration-icon-DacXQkv5.js} +1 -1
- package/dist/client/assets/{label-CSVg_a7v.js → label-VIvlEdF-.js} +1 -1
- package/dist/client/assets/{last-preview-page-DfTVHHmb.js → last-preview-page-baujoWR_.js} +1 -1
- package/dist/client/assets/{layout-C6xwlSdn.js → layout-TEbZiNtr.js} +1 -1
- package/dist/client/assets/{legacy-agents-deep-CWC0zZau.js → legacy-agents-deep-CPQUajoT.js} +1 -1
- package/dist/client/assets/{legacy-main-redirect-DRgTRvzH.js → legacy-main-redirect-VftM-8Kr.js} +1 -1
- package/dist/client/assets/{library-97YRcUZr.js → library-zll0qePG.js} +1 -1
- package/dist/client/assets/{login-BhU1Ujhe.js → login-DwEyh4eJ.js} +1 -1
- package/dist/client/assets/{markdown-CFbly6Oq.js → markdown-D2mDmYtT.js} +1 -1
- package/dist/client/assets/{mcp-app-renderer-BykX82F2.js → mcp-app-renderer-C9KPQDuu.js} +1 -1
- package/dist/client/assets/{mcp-oauth-C63jGUnz.js → mcp-oauth-LmTTT8Tz.js} +1 -1
- package/dist/client/assets/{members-DeKieaJl.js → members-DEAgfwF7.js} +1 -1
- package/dist/client/assets/{message-templates-BKDF2RYP.js → message-templates-C1GTjtE0.js} +1 -1
- package/dist/client/assets/{mini-report-page-Chm3cmYy.js → mini-report-page-LrRmRqok.js} +1 -1
- package/dist/client/assets/{mock-board-DqZ9ahY1.js → mock-board-BwXp2PH3.js} +21 -21
- package/dist/client/assets/{monaco-editor-DOKxCIHt.js → monaco-editor-DYUogsQZ.js} +1 -1
- package/dist/client/assets/{monitoring-stats-row-1jQu2lrE.js → monitoring-stats-row-Bq_MvZQS.js} +1 -1
- package/dist/client/assets/{multi-select-vXxYhU8m.js → multi-select-CW0D8RvY.js} +1 -1
- package/dist/client/assets/{mustache-DNIi39Ko.js → mustache-B2SzJma0.js} +1 -1
- package/dist/client/assets/{oauth-callback-3Gi7tqUG.js → oauth-callback-Cg8wq5wx.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-Cf0t22-C.js → oauth-callback-ai-provider-5iOdHj_G.js} +1 -1
- package/dist/client/assets/{onboarding-CGUiX9K2.js → onboarding-CT63y-v2.js} +1 -1
- package/dist/client/assets/{optimistic-project-sidebar-views-Db2WkK10.js → optimistic-project-sidebar-views-X7vKCfrC.js} +1 -1
- package/dist/client/assets/{org-file-open-context-CnVQlS8r.js → org-file-open-context-BOZM6YLL.js} +1 -1
- package/dist/client/assets/{organization-choice--In3qR7U.js → organization-choice-m7Ngqp5V.js} +1 -1
- package/dist/client/assets/{orgs-BDLSVW_b.js → orgs-BpWIw0D-.js} +1 -1
- package/dist/client/assets/{page-seo-form-Bu5aSBFT.js → page-seo-form-DAFmsPON.js} +1 -1
- package/dist/client/assets/{pair-GWtw_1HI.js → pair-Dw1oMoxu.js} +1 -1
- package/dist/client/assets/{plan-ladder-BU8min_2.js → plan-ladder-D6Ni723J.js} +1 -1
- package/dist/client/assets/{popover-CLYobNXs.js → popover-BeSwGzw4.js} +1 -1
- package/dist/client/assets/{post-calendar-DQTUlJ0K.js → post-calendar-DFL9wRVM.js} +1 -1
- package/dist/client/assets/{post-editor-hanL0E_J.js → post-editor-g-n7lnu4.js} +1 -1
- package/dist/client/assets/{preview-content-D1nRyUS9.js → preview-content-vgszlQx5.js} +1 -1
- package/dist/client/assets/{preview-dialog-CAyQLQAc.js → preview-dialog-DlidufSo.js} +1 -1
- package/dist/client/assets/{primitives-BTxJoGUA.js → primitives-Da7dIvHN.js} +1 -1
- package/dist/client/assets/{profile-DCphnNWV.js → profile-BcCNtm8s.js} +1 -1
- package/dist/client/assets/{project-app-view-DGIagWPe.js → project-app-view-CjPSAJ4u.js} +1 -1
- package/dist/client/assets/{project-feed-TkqL7JQ0.js → project-feed-DQMgDZo-.js} +1 -1
- package/dist/client/assets/{project-icon-C743c52u.js → project-icon-BRvH27Hr.js} +1 -1
- package/dist/client/assets/project-reports-BPob9HW7.js +1 -0
- package/dist/client/assets/project-tasks-CNUbGBJz.js +1 -0
- package/dist/client/assets/{prompts-2YddtnsL.js → prompts-Dky1VWuT.js} +1 -1
- package/dist/client/assets/record-editor-BqQ-Bty3.js +1 -0
- package/dist/client/assets/{redirect-editor-C-IAxVlk.js → redirect-editor-Cugc1S4I.js} +1 -1
- package/dist/client/assets/reports-BNwccApQ.js +1 -0
- package/dist/client/assets/{reports-BUSZApNb.js → reports-DzRrzSMb.js} +1 -1
- package/dist/client/assets/{reports-onboarding-IfWVIoXf.js → reports-onboarding-C6GSc5Ia.js} +1 -1
- package/dist/client/assets/{reports-tab-B7kMJJWU.js → reports-tab-gAoWI9U7.js} +2 -2
- package/dist/client/assets/{repositories-D502vIiH.js → repositories-BJecUAZm.js} +1 -1
- package/dist/client/assets/{repository-import-picker-BCAmdt78.js → repository-import-picker-CVYJ_0AH.js} +1 -1
- package/dist/client/assets/{repository-picker-HSv-HWJc.js → repository-picker-xQ4J7ikd.js} +1 -1
- package/dist/client/assets/{require-capability-BQaV-yr9.js → require-capability-CirQ2r5Q.js} +1 -1
- package/dist/client/assets/{required-auth-layout-rBHLSvp6.js → required-auth-layout-CPKi594K.js} +1 -1
- package/dist/client/assets/{reset-password-BlDszqa3.js → reset-password-B9PPRmxG.js} +1 -1
- package/dist/client/assets/{resizable-e4GYLVXf.js → resizable-Bn0P8wYO.js} +1 -1
- package/dist/client/assets/{review-settings-ks9_qLg3.js → review-settings-Jqx7EDla.js} +1 -1
- package/dist/client/assets/{rich-text-link-control-_GsdfhRm.js → rich-text-link-control-x5R3OHhF.js} +1 -1
- package/dist/client/assets/{roles-DEqsJ4rW.js → roles-bgxwGoDy.js} +1 -1
- package/dist/client/assets/{route-CCr7oDUX.js → route-B4isURIv.js} +1 -1
- package/dist/client/assets/{route-oRN7uTVj.js → route-CLG4oaJK.js} +1 -1
- package/dist/client/assets/{route-DgxW9W04.js → route-aZil8y7k.js} +1 -1
- package/dist/client/assets/{route-page-header-Dltx9ClI.js → route-page-header-Bi8l6Mod.js} +1 -1
- package/dist/client/assets/{runnable-block-editor-DrYuFjUS.js → runnable-block-editor-C_f1q_t9.js} +1 -1
- package/dist/client/assets/{sandbox-lifecycle-context-CHq2sTV_.js → sandbox-lifecycle-context-CzQUzQHx.js} +1 -1
- package/dist/client/assets/{schema-BujVNayF.js → schema-xxzWAMkW.js} +1 -1
- package/dist/client/assets/{scroll-area-lvldU12M.js → scroll-area-DTL1f--y.js} +1 -1
- package/dist/client/assets/{search-input-24B8Tyot.js → search-input-C85exKRK.js} +1 -1
- package/dist/client/assets/{search-toggle-NqjyKjYI.js → search-toggle-0SXorNX1.js} +1 -1
- package/dist/client/assets/{secrets-D3za7wyU.js → secrets-DqdXjnYq.js} +1 -1
- package/dist/client/assets/{sections-editor-CanRyS0_.js → sections-editor-FApy7gQU.js} +1 -1
- package/dist/client/assets/{select-Bg4SYeWD.js → select-DC0twOQ9.js} +1 -1
- package/dist/client/assets/{select-model-BGkutAKe.js → select-model-DEr_zu2K.js} +1 -1
- package/dist/client/assets/{seo-editor-DiGDq3FB.js → seo-editor-CsbFu7jq.js} +1 -1
- package/dist/client/assets/{separator-CywjNUh1.js → separator-Cj8hF9_n.js} +1 -1
- package/dist/client/assets/{settings-tab-D8VLTGbr.js → settings-tab-CwdO9ZFo.js} +3 -3
- package/dist/client/assets/{sheet-ftf49HXN.js → sheet-D0J4gDr6.js} +1 -1
- package/dist/client/assets/{shell-layout-DjW70qiW.js → shell-layout-BmlQrTmD.js} +1 -1
- package/dist/client/assets/{sidebar-DTV4AZIF.js → sidebar-DzuQpL53.js} +1 -1
- package/dist/client/assets/{skill-preview-ypZHU8Z2.js → skill-preview-Clgxg6ec.js} +1 -1
- package/dist/client/assets/{skills-DfIn9w2Y.js → skills-8MF6Pqra.js} +1 -1
- package/dist/client/assets/{sso-Xj1__3fg.js → sso-DJYOmf3W.js} +1 -1
- package/dist/client/assets/{switch-eKei9kDs.js → switch-B5FiEGIW.js} +1 -1
- package/dist/client/assets/{synced-repos-DRpiwbTc.js → synced-repos-Cy4EEmPa.js} +1 -1
- package/dist/client/assets/{table-B5v_DWhP.js → table-CXe4UMxN.js} +1 -1
- package/dist/client/assets/{tabs-CXXa_jSH.js → tabs-D1StyWQr.js} +1 -1
- package/dist/client/assets/task-board-1V3gCk_i.js +1 -0
- package/dist/client/assets/{task-route-CoMVgg7O.js → task-route-DsuUdSl6.js} +1 -1
- package/dist/client/assets/{task-status-BHPdW1Gf.js → task-status-DG0J8Zgz.js} +1 -1
- package/dist/client/assets/{taskboard-analytics-BOysxhGE.js → taskboard-analytics-CqBjOZ2A.js} +1 -1
- package/dist/client/assets/{tasks-DbvkRm0v.js → tasks-BW9PQJ_O.js} +1 -1
- package/dist/client/assets/tasks-Cg8gIxgc.js +1 -0
- package/dist/client/assets/{textarea-BPjXGpk9.js → textarea-CoEyNtpM.js} +1 -1
- package/dist/client/assets/{thread-button-CwE4DtdX.js → thread-button-nc7q3w4V.js} +1 -1
- package/dist/client/assets/{thread-intent-CwRpUwxV.js → thread-intent-CcPnu4GE.js} +1 -1
- package/dist/client/assets/{thread-route-C8g2T7dL.js → thread-route-CjF1fn3r.js} +1 -1
- package/dist/client/assets/{thread-route-D7XDJf4m.js → thread-route-DcxK4b7Y.js} +1 -1
- package/dist/client/assets/{thread-sheet-body-DBGVzD-E.js → thread-sheet-body-CBJpO93g.js} +1 -1
- package/dist/client/assets/{toggle-group-CA3zdmBJ.js → toggle-group-BE-optrK.js} +1 -1
- package/dist/client/assets/{toolbar-icon-button-ExGjsDgt.js → toolbar-icon-button-BuFZ6ucT.js} +1 -1
- package/dist/client/assets/{tooltip-CJqM3lfm.js → tooltip-BPzHnAJj.js} +1 -1
- package/dist/client/assets/{track-BonYxxqQ.js → track-BHMBpod4.js} +1 -1
- package/dist/client/assets/{types-q9I0nHOA.js → types-34Ays45L.js} +1 -1
- package/dist/client/assets/{usage-stats-D9pcQ_sO.js → usage-stats-T0WTsS5L.js} +1 -1
- package/dist/client/assets/{use-ai-providers-CWjHemFz.js → use-ai-providers-4YtSwB8t.js} +1 -1
- package/dist/client/assets/{use-automations-D_9BgiTB.js → use-automations-D9n_ZmrB.js} +1 -1
- package/dist/client/assets/{use-autosave-cRfN0ui4.js → use-autosave-D3Tbpdwv.js} +1 -1
- package/dist/client/assets/{use-connect-companion-DReblGUx.js → use-connect-companion-BvYIFqkx.js} +1 -1
- package/dist/client/assets/{use-connection-SLYUQbDz.js → use-connection-CJl3txo3.js} +1 -1
- package/dist/client/assets/{use-copy-CuqZqltT.js → use-copy-BWK9VZeC.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-GNhxSn5M.js → use-create-virtual-mcp-CU5jurvg.js} +1 -1
- package/dist/client/assets/{use-date-fns-locale-BGBVgoHd.js → use-date-fns-locale-HpI29w9x.js} +1 -1
- package/dist/client/assets/{use-debounced-autosave-6T3TL8Ql.js → use-debounced-autosave-DU9RFTz4.js} +1 -1
- package/dist/client/assets/{use-debounced-value-DW94WVQ_.js → use-debounced-value-nDWnt5ZK.js} +1 -1
- package/dist/client/assets/{use-deco-credits-w00rL9rV.js → use-deco-credits-CyMxZLrr.js} +1 -1
- package/dist/client/assets/{use-decopilot-events-DPMnjbbG.js → use-decopilot-events-BzMJD1uM.js} +1 -1
- package/dist/client/assets/{use-delete-connection-CxnXYerT.js → use-delete-connection-Bl4c1YPj.js} +1 -1
- package/dist/client/assets/{use-deployment-admin-KOfaGpVS.js → use-deployment-admin-DkNA52w9.js} +1 -1
- package/dist/client/assets/{use-entitlements-DM1qztRK.js → use-entitlements-Cn0i9CW9.js} +1 -1
- package/dist/client/assets/{use-fast-preview-draft-url-Qr055LlR.js → use-fast-preview-draft-url-DATrtbyw.js} +1 -1
- package/dist/client/assets/{use-file-configs-CGahvfZy.js → use-file-configs-qOygMQSr.js} +1 -1
- package/dist/client/assets/{use-in-settings-BARku5xt.js → use-in-settings-3Ul0bgC9.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-B5230ZMb.js → use-infinite-scroll-ffudwWNp.js} +1 -1
- package/dist/client/assets/{use-join-requests-CQOEPhsO.js → use-join-requests-B-CBn5QP.js} +1 -1
- package/dist/client/assets/{use-main-panel-tabs-ChV_2DZW.js → use-main-panel-tabs-BdSie_jh.js} +1 -1
- package/dist/client/assets/{use-mcp-auth-status-BB3CPz80.js → use-mcp-auth-status-DUfqqyh_.js} +1 -1
- package/dist/client/assets/{use-mcp-client-BK0kaBib.js → use-mcp-client-DHUKToCF.js} +1 -1
- package/dist/client/assets/{use-mcp-prompts-D1-kxx63.js → use-mcp-prompts-XNz1QP3F.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-OJ9Zh9W1.js → use-mcp-tools-BrHk6dMs.js} +1 -1
- package/dist/client/assets/{use-members-D_OenEaH.js → use-members-C0e8Ch84.js} +1 -1
- package/dist/client/assets/{use-mobile-BqBZOSTT.js → use-mobile-BtKg9sCJ.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-BYji1ZG2.js → use-navigate-to-agent-BP7q45Ig.js} +1 -1
- package/dist/client/assets/{use-open-billing-url-C1LF2oOG.js → use-open-billing-url-SmRKYeqU.js} +1 -1
- package/dist/client/assets/{use-org-auth-client-Da_6fbH8.js → use-org-auth-client-CUAseAjF.js} +1 -1
- package/dist/client/assets/{use-org-fs-CN5CmElX.js → use-org-fs-C9w4twJx.js} +1 -1
- package/dist/client/assets/{use-org-repo-syncs-C8dyKQTx.js → use-org-repo-syncs-SLecZyxY.js} +1 -1
- package/dist/client/assets/{use-org-sso-DAEFbqa6.js → use-org-sso-CaDHtuiG.js} +1 -1
- package/dist/client/assets/{use-organization-roles-Cx6-_uID.js → use-organization-roles-G0l1-hZz.js} +1 -1
- package/dist/client/assets/{use-organization-settings-D9SMKnuj.js → use-organization-settings-DOMdlLbS.js} +1 -1
- package/dist/client/assets/{use-panel-navigate-CDz0C6t7.js → use-panel-navigate-DBjhi95e.js} +1 -1
- package/dist/client/assets/{use-project-native-view-presence-BBkf-Zm4.js → use-project-native-view-presence-By_hz6nw.js} +1 -1
- package/dist/client/assets/{use-project-scope-BURtD24h.js → use-project-scope-DftATVXe.js} +1 -1
- package/dist/client/assets/{use-releases-Cu6u0bcZ.js → use-releases-WVhn_3Ue.js} +1 -1
- package/dist/client/assets/{use-reports-diagnostic-CIHeMd6p.js → use-reports-diagnostic-DGYxLu-y.js} +1 -1
- package/dist/client/assets/{use-route-default-main-VAt2uNQm.js → use-route-default-main-C5wxTmxr.js} +1 -1
- package/dist/client/assets/{use-secrets-B_4rFztF.js → use-secrets-DR7tojol.js} +1 -1
- package/dist/client/assets/{use-section-preview-base-NnAn5ni4.js → use-section-preview-base-CxN_FFCZ.js} +1 -1
- package/dist/client/assets/{use-session-runtime-V4bsn59Z.js → use-session-runtime-CtbaDUFc.js} +1 -1
- package/dist/client/assets/{use-tags-Asbg8CFV.js → use-tags-BviJKMQn.js} +1 -1
- package/dist/client/assets/{use-task-board-analytics-DkWRDw4Q.js → use-task-board-analytics-Dsbzj4O9.js} +1 -1
- package/dist/client/assets/{use-task-metadata-CyEPL5HJ.js → use-task-metadata-DgBMJLMR.js} +1 -1
- package/dist/client/assets/{use-thread-outputs-CAXm9l5o.js → use-thread-outputs-BDr4rCo1.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-BawBNtMM.js → use-virtual-mcp-BBVFqIjj.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-ed3dnyco.js +1 -0
- package/dist/client/assets/{useQueries-Ckt9uhtS.js → useQueries-3H-0IIer.js} +1 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-CneRNPU7.js +1 -0
- package/dist/client/assets/{users-CLQoBAv9.js → users-DwZaHbgK.js} +1 -1
- package/dist/client/assets/{utils-D5usjytT.js → utils-hYjLEIhA.js} +1 -1
- package/dist/client/assets/{variant-calendar-Bgpor-yB.js → variant-calendar-D7y8HdyO.js} +1 -1
- package/dist/client/assets/{variant-matcher-override-DL-ba0hY.js → variant-matcher-override-BZyxbroG.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-CpPZ1z8X.js → view-mode-toggle-BiwFBJpe.js} +1 -1
- package/dist/client/assets/virtual-mcp-CsNXCota.js +1 -0
- package/dist/client/index.html +1 -1
- package/dist/server/cli.js +2 -2
- package/dist/server/server.js +2 -2
- package/package.json +1 -1
- package/dist/client/assets/agent-app-OIHhFuBP.js +0 -1
- package/dist/client/assets/agent-deck-CmUKfECm.js +0 -1
- package/dist/client/assets/agent-file-DOj89I66.js +0 -1
- package/dist/client/assets/agent-library-file-BfVS49yN.js +0 -1
- package/dist/client/assets/agent-settings-D9FQF5Im.js +0 -1
- package/dist/client/assets/agent-site-editor-code-BcgQkDIF.js +0 -2
- package/dist/client/assets/agent-view-BRfd6K1O.js +0 -1
- package/dist/client/assets/api-keys-C0T4XFF4.js +0 -1
- package/dist/client/assets/app-editor-CP1TxCAY.js +0 -1
- package/dist/client/assets/project-reports-CSn6y1ux.js +0 -1
- package/dist/client/assets/project-tasks-B1ets1nb.js +0 -1
- package/dist/client/assets/record-editor-oByV8dYO.js +0 -1
- package/dist/client/assets/reports-B-ZPj5fj.js +0 -1
- package/dist/client/assets/task-board-B33kcBrm.js +0 -1
- package/dist/client/assets/tasks-CcMLQuPd.js +0 -1
- package/dist/client/assets/useInfiniteQuery-CHvzbp4H.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-CpkAfLYP.js +0 -1
- package/dist/client/assets/virtual-mcp-B49Lo7bt.js +0 -1
package/dist/server/cli.js
CHANGED
|
@@ -2091,7 +2091,7 @@ Usage: deco services <up|down|status>`),process.exit(1)}}var G8$=L(()=>{Vh()});f
|
|
|
2091
2091
|
`.execute($);if(Number(W.rows[0]?.cnt)===0){console.warn(`Failed to migrate ${G}/${K}, keeping in old table`);continue}}await Zl`
|
|
2092
2092
|
DELETE FROM kysely_migration WHERE name = ${Q}
|
|
2093
2093
|
`.execute($)}}async function vZ$($){await A34($),await R34($);let Z=new CZ$({db:$,provider:{getMigrations:()=>Promise.resolve(b01)}}),{error:Q,results:X}=await Z.migrateToLatest(),Y=0;if(X?.forEach((J)=>{if(J.status==="Success")Y++;else if(J.status==="Error")console.error(`Failed to execute migration "${J.migrationName}"`)}),Q)throw console.error("Failed to migrate"),console.error(Q),Q;return Y}async function q34($){let{keepOpen:Z=!1,database:Q,skipBetterAuth:X=!1}=$??{},Y="skipped";if(!X&&!Q)Y=await ro0();let J=Q??K8(),G=async()=>{if(!Z&&!Q)await vD(J).catch((K)=>{console.warn("Warning: Error closing database:",K)})};try{let K=await vZ$(J.db);return await G(),{betterAuth:Y,kysely:K}}catch(K){throw await G(),K}}async function M34(){let $=K8(),Z=new CZ$({db:$.db,provider:{getMigrations:()=>Promise.resolve(b01)}}),{error:Q,results:X}=await Z.migrateDown();if(X?.forEach((Y)=>{if(Y.status==="Success")console.log(`\u2705 Migration "${Y.migrationName}" rolled back successfully`);else if(Y.status==="Error")console.error(`\u274C Failed to rollback migration "${Y.migrationName}"`)}),Q)throw console.error("Failed to rollback migration"),console.error(Q),Q}var fZ$=L(()=>{SZ$();ao0();NX()});async function pG0($){let Z={...process.env},Q=fZ0($,Z);console.log(WI1(Q.settings.encryptionKey));let X=Q.settings.betterAuthSecret||(Q.settings.localMode?g4$(Q.settings.dataDir):""),{ensureServices:Y}=await Promise.resolve().then(() => (nJ0(),pJ0)),{outputs:J,services:G}=await Y({home:Q.settings.dataDir,externalDatabaseUrl:Q.externalDatabaseUrl,externalNatsUrl:Q.externalNatsUrl});if(!Q.skipMigrations){let{migrateBetterAuth:W}=await Promise.resolve().then(() => (ao0(),u4$));await W(J.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (NX(),Q4$)),{migrateToLatest:F}=await Promise.resolve().then(() => (fZ$(),xZ$)),U=H(J.databaseUrl);await F({keepOpen:!0,database:U,skipBetterAuth:!0})}let K={...Q.settings,betterAuthSecret:X,databaseUrl:J.databaseUrl,natsUrls:J.natsUrls,...J.s3?{s3Endpoint:J.s3.endpoint,s3Bucket:J.s3.bucket,s3AccessKeyId:J.s3.accessKeyId,s3SecretAccessKey:J.s3.secretAccessKey,s3ForcePathStyle:J.s3.forcePathStyle}:{}};return K8$(K),{settings:K,services:G.map((W)=>({name:W.name==="PostgreSQL"?"Postgres":W.name,port:W.port})),managedServiceNames:G.filter((W)=>W.owner==="managed").map((W)=>W.name)}}var y01=L(()=>{Vh();h4$();H$()});var hZ$={};W0(hZ$,{updateService:()=>oP,subscribeCliState:()=>u01,setTuiConsoleIntercepted:()=>nG0,setServerUrl:()=>_r,setMigrationsDone:()=>Cr,setDevMode:()=>V34,resetCliStateForTests:()=>I34,isTuiConsoleIntercepted:()=>tG0,getCliState:()=>h01,addLogEntry:()=>hD});function bZ$(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function yZ$(){return{services:bZ$(),migrationsStatus:"pending",serverUrl:null,logs:[]}}function I34(){YJ=yZ$()}function Sr(){for(let $ of g01)$()}function h01(){return YJ}function u01($){return g01.add($),()=>g01.delete($)}function oP($){YJ={...YJ,services:YJ.services.map((Z)=>Z.name===$.name?$:Z)},Sr()}function Cr(){YJ={...YJ,migrationsStatus:"done"},Sr()}function _r($){YJ={...YJ,serverUrl:$},Sr()}function hD($){let Z=[...YJ.logs,$];YJ={...YJ,logs:Z.length>500?Z.slice(-500):Z},Sr()}function V34(){YJ={...YJ,services:[...bZ$(),{name:"API",status:"pending",port:0},{name:"Vite",status:"pending",port:0}]},Sr()}function nG0($){gZ$=$}function tG0(){return gZ$}var YJ,g01,gZ$=!1;var rP=L(()=>{YJ=yZ$();g01=new Set});import{createServer as uZ$}from"net";function k34($){return new Promise((Z)=>{let Q=uZ$();Q.once("error",()=>Z(!1)),Q.listen($,"0.0.0.0",()=>{Q.close(()=>Z(!0))})})}async function vr($){if(await k34($))return $;let Z=await new Promise((Q,X)=>{let Y=uZ$();Y.once("error",X),Y.listen(0,"0.0.0.0",()=>{let J=Y.address(),G=typeof J==="object"&&J?J.port:0;Y.close(()=>Q(G))})});return console.warn(`Port ${$} is in use, using port ${Z} instead.`),Z}var l01=()=>{};var m01={};W0(m01,{startDevServer:()=>C34,pipeToLogStore:()=>c01});import{join as S34}from"path";function c01($){let Z=$.getReader(),Q=new TextDecoder,X="";function Y(){let J=X.split(`
|
|
2094
|
-
`);X=J.pop()??"";for(let G of J){let K=Bun.stripANSI(G).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;hD({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{try{for(;;){let{done:J,value:G}=await Z.read();if(J)break;X+=Q.decode(G,{stream:!0}),Y()}}catch{}if(X.trim()){let J=Bun.stripANSI(X).replace(/^\[\d+\]\s*/,"").trim();if(J)hD({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:J})}})()}async function C34($){let{baseUrl:Z,noTui:Q}=$,X=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=X?process.env.PORT:$.vitePort,J=Z||`http://localhost:${Y}`,G=X?await vr(Number(Y)+1):await vr(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await pG0({port:String(G),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let D of W)oP({name:D.name,status:"ready",port:D.port});Cr();let F=S34(import.meta.dir,"..","..","..","..",".."),U=Q===!0,N=Bun.spawn(["bun","run","dev:servers"],{cwd:F,env:{...process.env,PORT:String(K.port),VITE_PORT:String(Y),DATABASE_URL:K.databaseUrl,NATS_URL:K.natsUrls.join(","),NODE_ENV:K.nodeEnv,BASE_URL:J,DECOCMS_LOCAL_MODE:String(K.localMode),DECOCMS_HOME:K.dataDir,DATA_DIR:K.dataDir,DECO_CLI:"1",...K.betterAuthSecret?{BETTER_AUTH_SECRET:K.betterAuthSecret}:{},...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)c01(N.stdout),c01(N.stderr);_r(J),oP({name:"Vite",status:"ready",port:Number(Y)}),oP({name:"API",status:"ready",port:Number(K.port)});let O=async(D)=>{if(N.kill(D),await N.exited,H.length>0){let{stopServices:w}=await Promise.resolve().then(() => (nJ0(),pJ0));await w(K.dataDir)}};return process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM")),{port:Number(Y),process:N}}var d01=L(()=>{y01();rP();l01()});var oG0;var i01=L(()=>{oG0={name:"decocms",version:"4.387.3",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^4.0.58","@ai-sdk/google":"^4.0.76","@ai-sdk/openai":"^4.0.71","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^3.1.0","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^4.0.17","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^7.0.107","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as v34,Text as lZ$}from"ink";import{jsx as x34,jsxs as cZ$}from"react/jsx-runtime";function mZ$({version:$}){return cZ$(v34,{flexDirection:"column",marginTop:1,children:[DG0.map((Z,Q)=>x34(lZ$,{color:wG0[Q],children:Z},Q)),cZ$(lZ$,{dimColor:!0,children:[" v",$]})]})}var dZ$=L(()=>{Or()});import{Box as aP,Text as uD}from"ink";import{Spinner as f34}from"@inkjs/ui";import{jsx as RG,jsxs as Ql}from"react/jsx-runtime";function iZ$({status:$}){if($==="pending")return RG(f34,{label:""});return RG(uD,{color:"green",children:"\u2713"})}function b34($){return`${$.name}: ${$.port||"...."}`}function pZ$({services:$,migrationsStatus:Z,home:Q,serverUrl:X}){return Ql(aP,{flexDirection:"column",paddingBottom:1,children:[RG(mZ$,{version:oG0.version}),RG(aP,{marginBottom:1,children:RG(uD,{dimColor:!0,children:"\u2500".repeat(80)})}),RG(aP,{children:Ql(uD,{dimColor:!0,children:["Home: ",Q]})}),Ql(aP,{gap:2,children:[$.map((Y)=>Ql(aP,{gap:1,children:[RG(uD,{children:b34(Y)}),RG(iZ$,{status:Y.status})]},Y.name)),Ql(aP,{gap:1,children:[RG(uD,{children:"Migrations"}),RG(iZ$,{status:Z})]})]}),RG(aP,{children:X?Ql(uD,{children:["Open in browser: ",RG(uD,{color:"cyan",children:X})]}):RG(uD,{dimColor:!0,children:"Starting..."})})]})}var nZ$=L(()=>{i01();dZ$()});import{Box as y34,Text as xr}from"ink";import{jsx as p01,jsxs as n01}from"react/jsx-runtime";function g34($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function tZ$({logs:$}){return p01(y34,{flexDirection:"column",children:$.map((Z,Q)=>{if(Z.rawLine)return p01(xr,{dimColor:!0,children:Z.rawLine},Q);let X=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return n01(xr,{children:[n01(xr,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),p01(xr,{color:g34(Z.status),children:Z.status}),n01(xr,{dimColor:!0,children:[" ",X.padStart(8)]})]},Q)})})}var oZ$=()=>{};var t01={};W0(t01,{App:()=>l34});import{Box as h34}from"ink";import{useSyncExternalStore as u34}from"react";import{jsx as rZ$,jsxs as c34}from"react/jsx-runtime";function l34({home:$}){let Z=u34(u01,h01);return c34(h34,{flexDirection:"column",children:[rZ$(pZ$,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),rZ$(tZ$,{logs:Z.logs})]})}var o01=L(()=>{nZ$();oZ$();rP()});var $K="thread-gate",RB="decopilot-hosted-harness",qB="decopilot-hosted-harness-sandboxed",ZK="automations",lD="background-tools",sP="task-board-github-reads";var aZ$="13";function sZ$($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:aZ$,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var eZ$=()=>{};import m34 from"pg";async function Z7$($,Z){let{databaseUrl:Q,lockTimeoutMs:X=d34}=$,Y=$.log??((W)=>console.log(W)),J=new m34.Client({connectionString:Q});await J.connect();let G=Date.now(),K=!1;try{while(!K){if(K=(await J.query("SELECT pg_try_advisory_lock($1) AS locked",[$7$.toString()])).rows[0]?.locked===!0,K)break;if(Date.now()-G>=X)throw Error(`Timed out after ${X}ms waiting for the DBOS migration lock. Another process is still migrating the dbos schema; this pod will restart and retry.`);await k$(i34)}let W=Date.now()-G;if(W>1000)Y(`[dbos] waited ${W}ms for the migration lock; another process migrated first`);return await Z()}finally{if(K)try{await J.query("SELECT pg_advisory_unlock($1)",[$7$.toString()])}catch{}await J.end().catch(()=>{})}}var $7$=8314027461559302n,d34=600000,i34=500;var Q7$=L(()=>{w8()});function p34(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function r01($,Z){for(let Q=0;Q<$.length;Q++){let X=$[Q];if(X===void 0)continue;if(X===Z)return $[Q+1];if(X.startsWith(`${Z}=`))return X.slice(Z.length+1)}return}function X7$(){let $=p34();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:r01($,"--cpu-prof-dir")??process.cwd(),name:r01($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(r01($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function Y7$(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let Q=iP();if(!Q)return;let X={};try{let{heapStats:Y}=await import("bun:jsc"),J=Y(),G=Object.entries(J.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);X={objectCount:J.objectCount,heapSize:J.heapSize,top:Object.fromEntries(G)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:Q.rss,heapUsed:Q.heapUsed,heapTotal:Q.heapTotal,external:Q.external,arrayBuffers:Q.arrayBuffers,...X}))};return Z().catch(()=>{}),rG0=setInterval(()=>void Z().catch(()=>{}),$),rG0.unref?.(),process.on("SIGUSR2",()=>{try{let Q=Bun.generateHeapSnapshot("v8"),X=typeof Q==="string"?Q:JSON.stringify(Q),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,X),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(Q){console.error("[heap-watch] snapshot failed:",Q)}}),()=>{if(rG0)clearInterval(rG0)}}var rG0;var J7$=()=>{};import*as n34 from"bun:jsc";function G7$(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{t34()}catch(J){return console.error("[stall-watchdog] failed to start sampling profiler:",J),()=>{}}let Q,X=performance.now()+Z,Y=()=>{let J=performance.now(),G=J-X;X=J+Z;let K=[];try{K=o34()?.traces??[]}catch{}if(G>$&&K.length>0){let W=new Map;for(let F of K){let U=F.frames.find((O)=>O.sourceURL&&!/Unknown Executable/.test(O.category??""))??F.frames[0];if(!U)continue;let N=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),B=`${U.name??"?"} @ ${N}:${U.line??"?"}`;W.set(B,(W.get(B)??0)+1)}let H=[...W.entries()].sort((F,U)=>U[1]-F[1]).slice(0,8).map(([F,U])=>({frame:F,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(G),samplesInWindow:K.length,top:H}))}Q=setTimeout(Y,Z),Q.unref?.()};return Q=setTimeout(Y,Z),Q.unref?.(),()=>{if(Q)clearTimeout(Q)}}var t34,o34;var K7$=L(()=>{({startSamplingProfiler:t34,samplingProfilerStackTraces:o34}=n34)});function W7$(){X7$();let $=[Y7$(),t8$(),G7$()];return()=>{for(let Z of $)Z()}}var H7$=L(()=>{co0();J7$();K7$()});var eP=b((F7$)=>{Object.defineProperty(F7$,"__esModule",{value:!0});F7$.RepublishHeaders=F7$.DirectMsgHeaders=F7$.JsHeaders=F7$.AdvisoryKind=void 0;F7$.isOrderedPushConsumerOptions=r34;F7$.isPullConsumer=a34;F7$.isPushConsumer=s34;F7$.isBoundPushConsumerOptions=e34;function r34($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function a34($){return $.isPullConsumer()}function s34($){return $.isPushConsumer()}function e34($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}F7$.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};F7$.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};F7$.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};F7$.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var qG=b((N7$)=>{Object.defineProperty(N7$,"__esModule",{value:!0});N7$.TD=N7$.TE=N7$.Empty=void 0;N7$.encode=WK4;N7$.decode=HK4;N7$.Empty=new Uint8Array(0);N7$.TE=new TextEncoder;N7$.TD=new TextDecoder;function KK4(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}function WK4(...$){let Z=[];for(let Q=0;Q<$.length;Q++)Z.push(N7$.TE.encode($[Q]));if(Z.length===0)return N7$.Empty;if(Z.length===1)return Z[0];return KK4(...Z)}function HK4($){if(!$||$.length===0)return"";return N7$.TD.decode($)}});var MG=b((O7$)=>{Object.defineProperty(O7$,"__esModule",{value:!0});O7$.errors=O7$.PermissionViolationError=O7$.NoRespondersError=O7$.TimeoutError=O7$.RequestError=O7$.ProtocolError=O7$.ConnectionError=O7$.DrainingConnectionError=O7$.ClosedConnectionError=O7$.AuthorizationError=O7$.UserAuthenticationExpiredError=O7$.InvalidOperationError=O7$.InvalidArgumentError=O7$.InvalidSubjectError=void 0;class s01 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}O7$.InvalidSubjectError=s01;class aG0 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,Q){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((X)=>`'${X}'`),$=$.join(",");else $=`'${$}'`;return new aG0(`${$} ${Z}`,Q)}}O7$.InvalidArgumentError=aG0;class e01 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}O7$.InvalidOperationError=e01;class sG0 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new sG0($);return null}}O7$.UserAuthenticationExpiredError=sG0;class eG0 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],Q=$.toLowerCase();for(let X=0;X<Z.length;X++)if(Q.indexOf(Z[X])!==-1)return new eG0($);return null}}O7$.AuthorizationError=eG0;class $11 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}O7$.ClosedConnectionError=$11;class Z11 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}O7$.DrainingConnectionError=Z11;class Q11 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}O7$.ConnectionError=Q11;class X11 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}O7$.ProtocolError=X11;class Y11 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof $30}}O7$.RequestError=Y11;class J11 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}O7$.TimeoutError=J11;class $30 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}O7$.NoRespondersError=$30;class Z30 extends Error{operation;subject;queue;constructor($,Z,Q,X,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=Q,this.queue=X}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let Q="publish",X="",Y=void 0,J=$.match(/(Publish|Subscription) to "(\S+)"/);if(J){if(Q=J[1].toLowerCase(),X=J[2],Q==="subscription"){let G=$.match(/using queue "(\S+)"/);if(G)Y=G[1]}}return new Z30($,Q,X,Y)}}O7$.PermissionViolationError=Z30;O7$.errors={AuthorizationError:eG0,ClosedConnectionError:$11,ConnectionError:Q11,DrainingConnectionError:Z11,InvalidArgumentError:aG0,InvalidOperationError:e01,InvalidSubjectError:s01,NoRespondersError:$30,PermissionViolationError:Z30,ProtocolError:X11,RequestError:Y11,TimeoutError:J11,UserAuthenticationExpiredError:sG0}});var yW=b((z7$)=>{Object.defineProperty(z7$,"__esModule",{value:!0});z7$.SimpleMutex=z7$.Perf=void 0;z7$.extend=MK4;z7$.render=IK4;z7$.timeout=VK4;z7$.delay=kK4;z7$.deadline=SK4;z7$.deferred=K11;z7$.debugDeferred=CK4;z7$.shuffle=_K4;z7$.collect=vK4;z7$.jitter=E7$;z7$.backoff=xK4;z7$.nanos=fK4;z7$.millis=bK4;z7$.randomToken=hK4;var qK4=qG(),G11=MG();function MK4($,...Z){for(let Q=0;Q<Z.length;Q++){let X=Z[Q];Object.keys(X).forEach(function(Y){$[Y]=X[Y]})}return $}function IK4($){return qK4.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function VK4($,Z=!0){let Q=Z?new G11.TimeoutError:null,X,Y,J=new Promise((G,K)=>{X={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(Q===null)K(new G11.TimeoutError);else K(Q)},$)});return Object.assign(J,X)}function kK4($=0){let Z,Q=new Promise((X)=>{let Y=setTimeout(()=>{X()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),X()}}});return Object.assign(Q,Z)}async function SK4($,Z=1000){let Q=K11(),X=setTimeout(()=>{Q.reject(new G11.TimeoutError)},Z);try{return await Promise.race([$,Q])}finally{clearTimeout(X)}}function K11(){let $={},Z=new Promise((Q,X)=>{$={resolve:Q,reject:X}});return Object.assign(Z,$)}function CK4(){let $={},Z=new Promise((Q,X)=>{$={resolve:(Y)=>{console.trace("resolve",Y),Q(Y)},reject:(Y)=>{console.trace("reject"),X(Y)}}});return Object.assign(Z,$)}function _K4($){for(let Z=$.length-1;Z>0;Z--){let Q=Math.floor(Math.random()*(Z+1));[$[Z],$[Q]]=[$[Q],$[Z]]}return $}async function vK4($){let Z=[];for await(let Q of $)Z.push(Q);return Z}class w7${timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,Q){let X=this.timers.get(Z);if(X===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(Q);if(Y===void 0)throw Error(`${Q} is not defined`);this.measures.set($,Y-X)}getEntries(){let $=[];return this.measures.forEach((Z,Q)=>{$.push({name:Q,duration:Z})}),$}}z7$.Perf=w7$;class j7${max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=K11();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}z7$.SimpleMutex=j7$;function E7$($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function xK4($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(Q){return E7$(Q>Z?$[Z]:$[Q])}}}function fK4($){return $*1e6}function bK4($){return Math.floor($/1e6)}var yK4="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",MB=new Uint8Array(62);for(let $=0;$<62;$++)MB[$]=yK4.charCodeAt($);var gK4=218340105584896;function hK4(){let $=Math.floor(Math.random()*gK4),Z=$%62,Q=MB[Z];$=($-Z)/62,Z=$%62;let X=MB[Z];$=($-Z)/62,Z=$%62;let Y=MB[Z];$=($-Z)/62,Z=$%62;let J=MB[Z];$=($-Z)/62,Z=$%62;let G=MB[Z];$=($-Z)/62,Z=$%62;let K=MB[Z];$=($-Z)/62,Z=$%62;let W=MB[Z];$=($-Z)/62;let H=MB[$];return String.fromCharCode(Q,X,Y,J,G,K,W,H)}});var V7$=b((M7$)=>{Object.defineProperty(M7$,"__esModule",{value:!0});M7$.nuid=M7$.NuidImpl=void 0;var ZW4="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",cD=62,X30=12,R7$=10,T7$=33,QW4=333,A7$=X30+R7$,H11=new Uint8Array(cD);for(let $=0;$<cD;$++)H11[$]=ZW4.charCodeAt($);var Q30=4294967296,q7$=BigInt(cD)**BigInt(R7$),fr=Number(q7$/(1n<<32n)),W11=Number(q7$%(1n<<32n));function XW4($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function YW4($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else XW4($)}class F11{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(A7$),this.cbuf=new Uint8Array(X30),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(fr+1)),this.seqLo=Math.floor(Math.random()*Q30);while($++<8&&this.seqHi===fr&&this.seqLo>=W11);if(this.seqHi===fr&&this.seqLo>=W11)this.seqLo=0;this.inc=Math.random()*(QW4-T7$)+T7$|0}setPre(){YW4(this.cbuf);for(let $=0;$<X30;$++)this.buf[$]=H11[this.cbuf[$]%cD]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let Q=A7$-1;Q>=X30;Q--){let X=Math.floor($/cD),J=($-X*cD)*Q30+Z,G=Math.floor(J/cD),K=J-G*cD;this.buf[Q]=H11[K],$=X,Z=G}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=Q30)this.seqLo-=Q30,this.seqHi+=1;if(this.seqHi>fr||this.seqHi===fr&&this.seqLo>=W11)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}M7$.NuidImpl=F11;M7$.nuid=new F11});var _7$=b((S7$)=>{Object.defineProperty(S7$,"__esModule",{value:!0});S7$.nuid=S7$.Nuid=void 0;var k7$=V7$();S7$.Nuid=k7$.NuidImpl;S7$.nuid=k7$.nuid});var J30=b((Y30)=>{Object.defineProperty(Y30,"__esModule",{value:!0});Y30.nuid=Y30.Nuid=void 0;var v7$=_7$();Object.defineProperty(Y30,"Nuid",{enumerable:!0,get:function(){return v7$.Nuid}});Object.defineProperty(Y30,"nuid",{enumerable:!0,get:function(){return v7$.nuid}})});var mD=b((x7$)=>{Object.defineProperty(x7$,"__esModule",{value:!0});x7$.DEFAULT_HOST=x7$.DEFAULT_PORT=x7$.Match=void 0;x7$.syncIterator=FW4;x7$.createInbox=UW4;var WW4=J30(),HW4=MG();x7$.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function FW4($){let Z=$[Symbol.asyncIterator]();return{async next(){let Q=await Z.next();if(Q.done)return Promise.resolve(null);return Promise.resolve(Q.value)}}}function UW4($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw HW4.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${WW4.nuid.next()}`}x7$.DEFAULT_PORT=4222;x7$.DEFAULT_HOST="127.0.0.1"});var br=b((g7$)=>{Object.defineProperty(g7$,"__esModule",{value:!0});g7$.DataBuffer=void 0;var b7$=qG();class y7${buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}static fromAscii($){if(!$)$="";return b7$.TE.encode($)}static toAscii($){return b7$.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let Q=0;Q<this.buffers.length;Q++)$.set(this.buffers[Q],Z),Z+=this.buffers[Q].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let Q=this.byteLength;if($===void 0||$>Q)$=Q;let X=Z.subarray(0,$);if(Q>$)this.buffers.push(Z.subarray($));return this.byteLength=Q-$,X}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let Q=0;Q<Z.length;Q++)if(Z[Q]&&Z[Q].length)this.buffers.push(Z[Q]),this.byteLength+=Z[Q].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}g7$.DataBuffer=y7$});var $T=b((l7$)=>{Object.defineProperty(l7$,"__esModule",{value:!0});l7$.LF=l7$.CR=l7$.CRLF=l7$.CR_LF_LEN=l7$.CR_LF=void 0;l7$.setTransportFactory=EW4;l7$.defaultPort=zW4;l7$.getUrlParseFn=PW4;l7$.newTransport=TW4;l7$.getResolveFn=AW4;l7$.protoLen=u7$;l7$.extractProtocolMessage=RW4;var DW4=qG(),wW4=mD(),jW4=br(),IG;function EW4($){IG=$}function zW4(){return IG!==void 0&&IG.defaultPort!==void 0?IG.defaultPort:wW4.DEFAULT_PORT}function PW4(){return IG!==void 0&&IG.urlParseFn?IG.urlParseFn:void 0}function TW4(){if(!IG||typeof IG.factory!=="function")throw Error("transport fn is not set");return IG.factory()}function AW4(){return IG!==void 0&&IG.dnsResolveFn?IG.dnsResolveFn:void 0}l7$.CR_LF=`\r
|
|
2094
|
+
`);X=J.pop()??"";for(let G of J){let K=Bun.stripANSI(G).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;hD({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{try{for(;;){let{done:J,value:G}=await Z.read();if(J)break;X+=Q.decode(G,{stream:!0}),Y()}}catch{}if(X.trim()){let J=Bun.stripANSI(X).replace(/^\[\d+\]\s*/,"").trim();if(J)hD({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:J})}})()}async function C34($){let{baseUrl:Z,noTui:Q}=$,X=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=X?process.env.PORT:$.vitePort,J=Z||`http://localhost:${Y}`,G=X?await vr(Number(Y)+1):await vr(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await pG0({port:String(G),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let D of W)oP({name:D.name,status:"ready",port:D.port});Cr();let F=S34(import.meta.dir,"..","..","..","..",".."),U=Q===!0,N=Bun.spawn(["bun","run","dev:servers"],{cwd:F,env:{...process.env,PORT:String(K.port),VITE_PORT:String(Y),DATABASE_URL:K.databaseUrl,NATS_URL:K.natsUrls.join(","),NODE_ENV:K.nodeEnv,BASE_URL:J,DECOCMS_LOCAL_MODE:String(K.localMode),DECOCMS_HOME:K.dataDir,DATA_DIR:K.dataDir,DECO_CLI:"1",...K.betterAuthSecret?{BETTER_AUTH_SECRET:K.betterAuthSecret}:{},...K.s3Endpoint?{S3_ENDPOINT:K.s3Endpoint,S3_BUCKET:K.s3Bucket??"",S3_ACCESS_KEY_ID:K.s3AccessKeyId??"",S3_SECRET_ACCESS_KEY:K.s3SecretAccessKey??"",S3_FORCE_PATH_STYLE:String(K.s3ForcePathStyle)}:{},...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)c01(N.stdout),c01(N.stderr);_r(J),oP({name:"Vite",status:"ready",port:Number(Y)}),oP({name:"API",status:"ready",port:Number(K.port)});let O=async(D)=>{if(N.kill(D),await N.exited,H.length>0){let{stopServices:w}=await Promise.resolve().then(() => (nJ0(),pJ0));await w(K.dataDir)}};return process.on("SIGINT",()=>O("SIGINT")),process.on("SIGTERM",()=>O("SIGTERM")),{port:Number(Y),process:N}}var d01=L(()=>{y01();rP();l01()});var oG0;var i01=L(()=>{oG0={name:"decocms",version:"4.388.0",description:"Deco CMS \u2014 Self-hostable MCP Gateway for managing AI connections and tools",author:"Deco team",repository:{type:"git",url:"git+https://github.com/decocms/studio.git",directory:"apps/api"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:"bun run migrate && bun run dev:server","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts",build:"bun run build:server","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","generate:tool-contracts":"bun run scripts/generate-tool-contracts.ts","db:migrate":"bun run ./dist/server/migrate.js","db:migrate:dbos":"bun run ./dist/server/migrate-dbos.js",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.ts","migrate:dbos":"bun run src/database/migrate-dbos.ts",test:"bun test src","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run --cwd=../.. build:studio"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1"},dependencies:{"@ai-sdk/anthropic":"^4.0.58","@ai-sdk/google":"^4.0.76","@ai-sdk/openai":"^4.0.71","@anthropic-ai/sdk":"^0.105.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/client-sts":"^3.1013.0","@aws-sdk/lib-storage":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dbos-inc/dbos-sdk":"^4.21.6","@inkjs/ui":"^2.0.0","@nats-io/jetstream":"3.4.0","@nats-io/kv":"3.4.0","@nats-io/nats-core":"3.4.0","@nats-io/transport-node":"3.4.0","@openrouter/ai-sdk-provider":"^3.1.0","@opentelemetry/core":"^2.6.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12","posthog-node":"^5.0.0",react:"^19.2.6","react-dom":"^19.2.6"},devDependencies:{"@ai-sdk/provider":"^4.0.17","@better-auth/sso":"1.4.1","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/runtime":"workspace:*","@decocms/sandbox":"workspace:*","@decocms/shared":"workspace:*","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/resources":"^2.6.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@types/bun":"^1.3.1","@types/google.maps":"^3.65.2","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@vercel/nft":"^1.1.1",ai:"^7.0.107","better-auth":"1.4.22",croner:"^9.1.0",degit:"^2.8.4",hono:"^4.10.7",jose:"^6.0.11",nanoid:"^5.1.6",pg:"^8.16.3",typescript:"^7.0.2",typescript5:"npm:typescript@^5.9.3",zod:"4.3.6"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as v34,Text as lZ$}from"ink";import{jsx as x34,jsxs as cZ$}from"react/jsx-runtime";function mZ$({version:$}){return cZ$(v34,{flexDirection:"column",marginTop:1,children:[DG0.map((Z,Q)=>x34(lZ$,{color:wG0[Q],children:Z},Q)),cZ$(lZ$,{dimColor:!0,children:[" v",$]})]})}var dZ$=L(()=>{Or()});import{Box as aP,Text as uD}from"ink";import{Spinner as f34}from"@inkjs/ui";import{jsx as RG,jsxs as Ql}from"react/jsx-runtime";function iZ$({status:$}){if($==="pending")return RG(f34,{label:""});return RG(uD,{color:"green",children:"\u2713"})}function b34($){return`${$.name}: ${$.port||"...."}`}function pZ$({services:$,migrationsStatus:Z,home:Q,serverUrl:X}){return Ql(aP,{flexDirection:"column",paddingBottom:1,children:[RG(mZ$,{version:oG0.version}),RG(aP,{marginBottom:1,children:RG(uD,{dimColor:!0,children:"\u2500".repeat(80)})}),RG(aP,{children:Ql(uD,{dimColor:!0,children:["Home: ",Q]})}),Ql(aP,{gap:2,children:[$.map((Y)=>Ql(aP,{gap:1,children:[RG(uD,{children:b34(Y)}),RG(iZ$,{status:Y.status})]},Y.name)),Ql(aP,{gap:1,children:[RG(uD,{children:"Migrations"}),RG(iZ$,{status:Z})]})]}),RG(aP,{children:X?Ql(uD,{children:["Open in browser: ",RG(uD,{color:"cyan",children:X})]}):RG(uD,{dimColor:!0,children:"Starting..."})})]})}var nZ$=L(()=>{i01();dZ$()});import{Box as y34,Text as xr}from"ink";import{jsx as p01,jsxs as n01}from"react/jsx-runtime";function g34($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function tZ$({logs:$}){return p01(y34,{flexDirection:"column",children:$.map((Z,Q)=>{if(Z.rawLine)return p01(xr,{dimColor:!0,children:Z.rawLine},Q);let X=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return n01(xr,{children:[n01(xr,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),p01(xr,{color:g34(Z.status),children:Z.status}),n01(xr,{dimColor:!0,children:[" ",X.padStart(8)]})]},Q)})})}var oZ$=()=>{};var t01={};W0(t01,{App:()=>l34});import{Box as h34}from"ink";import{useSyncExternalStore as u34}from"react";import{jsx as rZ$,jsxs as c34}from"react/jsx-runtime";function l34({home:$}){let Z=u34(u01,h01);return c34(h34,{flexDirection:"column",children:[rZ$(pZ$,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),rZ$(tZ$,{logs:Z.logs})]})}var o01=L(()=>{nZ$();oZ$();rP()});var $K="thread-gate",RB="decopilot-hosted-harness",qB="decopilot-hosted-harness-sandboxed",ZK="automations",lD="background-tools",sP="task-board-github-reads";var aZ$="13";function sZ$($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:aZ$,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var eZ$=()=>{};import m34 from"pg";async function Z7$($,Z){let{databaseUrl:Q,lockTimeoutMs:X=d34}=$,Y=$.log??((W)=>console.log(W)),J=new m34.Client({connectionString:Q});await J.connect();let G=Date.now(),K=!1;try{while(!K){if(K=(await J.query("SELECT pg_try_advisory_lock($1) AS locked",[$7$.toString()])).rows[0]?.locked===!0,K)break;if(Date.now()-G>=X)throw Error(`Timed out after ${X}ms waiting for the DBOS migration lock. Another process is still migrating the dbos schema; this pod will restart and retry.`);await k$(i34)}let W=Date.now()-G;if(W>1000)Y(`[dbos] waited ${W}ms for the migration lock; another process migrated first`);return await Z()}finally{if(K)try{await J.query("SELECT pg_advisory_unlock($1)",[$7$.toString()])}catch{}await J.end().catch(()=>{})}}var $7$=8314027461559302n,d34=600000,i34=500;var Q7$=L(()=>{w8()});function p34(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function r01($,Z){for(let Q=0;Q<$.length;Q++){let X=$[Q];if(X===void 0)continue;if(X===Z)return $[Q+1];if(X.startsWith(`${Z}=`))return X.slice(Z.length+1)}return}function X7$(){let $=p34();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:r01($,"--cpu-prof-dir")??process.cwd(),name:r01($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(r01($,"--cpu-prof-interval")??1000),note:"profile is written on process exit"}));return}if(process.env.CPU_PROFILE)console.warn(JSON.stringify({msg:"cpu-profiling-requested-but-inactive",hint:'CPU profiling is a Bun launch flag. Set BUN_OPTIONS="--cpu-prof --cpu-prof-md --cpu-prof-dir=/tmp" before starting the process.'}))}function Y7$(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let Q=iP();if(!Q)return;let X={};try{let{heapStats:Y}=await import("bun:jsc"),J=Y(),G=Object.entries(J.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);X={objectCount:J.objectCount,heapSize:J.heapSize,top:Object.fromEntries(G)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:Q.rss,heapUsed:Q.heapUsed,heapTotal:Q.heapTotal,external:Q.external,arrayBuffers:Q.arrayBuffers,...X}))};return Z().catch(()=>{}),rG0=setInterval(()=>void Z().catch(()=>{}),$),rG0.unref?.(),process.on("SIGUSR2",()=>{try{let Q=Bun.generateHeapSnapshot("v8"),X=typeof Q==="string"?Q:JSON.stringify(Q),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,X),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(Q){console.error("[heap-watch] snapshot failed:",Q)}}),()=>{if(rG0)clearInterval(rG0)}}var rG0;var J7$=()=>{};import*as n34 from"bun:jsc";function G7$(){if(process.env.STALL_WATCHDOG!=="1")return()=>{};let $=Number(process.env.STALL_WATCHDOG_MS??100),Z=Number(process.env.STALL_WATCHDOG_TICK_MS??50);try{t34()}catch(J){return console.error("[stall-watchdog] failed to start sampling profiler:",J),()=>{}}let Q,X=performance.now()+Z,Y=()=>{let J=performance.now(),G=J-X;X=J+Z;let K=[];try{K=o34()?.traces??[]}catch{}if(G>$&&K.length>0){let W=new Map;for(let F of K){let U=F.frames.find((O)=>O.sourceURL&&!/Unknown Executable/.test(O.category??""))??F.frames[0];if(!U)continue;let N=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),B=`${U.name??"?"} @ ${N}:${U.line??"?"}`;W.set(B,(W.get(B)??0)+1)}let H=[...W.entries()].sort((F,U)=>U[1]-F[1]).slice(0,8).map(([F,U])=>({frame:F,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(G),samplesInWindow:K.length,top:H}))}Q=setTimeout(Y,Z),Q.unref?.()};return Q=setTimeout(Y,Z),Q.unref?.(),()=>{if(Q)clearTimeout(Q)}}var t34,o34;var K7$=L(()=>{({startSamplingProfiler:t34,samplingProfilerStackTraces:o34}=n34)});function W7$(){X7$();let $=[Y7$(),t8$(),G7$()];return()=>{for(let Z of $)Z()}}var H7$=L(()=>{co0();J7$();K7$()});var eP=b((F7$)=>{Object.defineProperty(F7$,"__esModule",{value:!0});F7$.RepublishHeaders=F7$.DirectMsgHeaders=F7$.JsHeaders=F7$.AdvisoryKind=void 0;F7$.isOrderedPushConsumerOptions=r34;F7$.isPullConsumer=a34;F7$.isPushConsumer=s34;F7$.isBoundPushConsumerOptions=e34;function r34($){if($&&typeof $==="object")return"name_prefix"in $||"deliver_subject_prefix"in $||"filter_subjects"in $||"filter_subject"in $||"deliver_policy"in $||"opt_start_seq"in $||"opt_start_time"in $||"replay_policy"in $||"inactive_threshold"in $||"headers_only"in $||"deliver_prefix"in $;return!1}function a34($){return $.isPullConsumer()}function s34($){return $.isPushConsumer()}function e34($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}F7$.AdvisoryKind={API:"api_audit",StreamAction:"stream_action",ConsumerAction:"consumer_action",SnapshotCreate:"snapshot_create",SnapshotComplete:"snapshot_complete",RestoreCreate:"restore_create",RestoreComplete:"restore_complete",MaxDeliver:"max_deliver",Terminated:"terminated",Ack:"consumer_ack",StreamLeaderElected:"stream_leader_elected",StreamQuorumLost:"stream_quorum_lost",ConsumerLeaderElected:"consumer_leader_elected",ConsumerQuorumLost:"consumer_quorum_lost"};F7$.JsHeaders={StreamSourceHdr:"Nats-Stream-Source",LastConsumerSeqHdr:"Nats-Last-Consumer",LastStreamSeqHdr:"Nats-Last-Stream",ConsumerStalledHdr:"Nats-Consumer-Stalled",MessageSizeHdr:"Nats-Msg-Size",RollupHdr:"Nats-Rollup",RollupValueSubject:"sub",RollupValueAll:"all",PendingMessagesHdr:"Nats-Pending-Messages",PendingBytesHdr:"Nats-Pending-Bytes",RequiredApiLevel:"Nats-Required-Api-Level"};F7$.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};F7$.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var qG=b((N7$)=>{Object.defineProperty(N7$,"__esModule",{value:!0});N7$.TD=N7$.TE=N7$.Empty=void 0;N7$.encode=WK4;N7$.decode=HK4;N7$.Empty=new Uint8Array(0);N7$.TE=new TextEncoder;N7$.TD=new TextDecoder;function KK4(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}function WK4(...$){let Z=[];for(let Q=0;Q<$.length;Q++)Z.push(N7$.TE.encode($[Q]));if(Z.length===0)return N7$.Empty;if(Z.length===1)return Z[0];return KK4(...Z)}function HK4($){if(!$||$.length===0)return"";return N7$.TD.decode($)}});var MG=b((O7$)=>{Object.defineProperty(O7$,"__esModule",{value:!0});O7$.errors=O7$.PermissionViolationError=O7$.NoRespondersError=O7$.TimeoutError=O7$.RequestError=O7$.ProtocolError=O7$.ConnectionError=O7$.DrainingConnectionError=O7$.ClosedConnectionError=O7$.AuthorizationError=O7$.UserAuthenticationExpiredError=O7$.InvalidOperationError=O7$.InvalidArgumentError=O7$.InvalidSubjectError=void 0;class s01 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}O7$.InvalidSubjectError=s01;class aG0 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,Q){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((X)=>`'${X}'`),$=$.join(",");else $=`'${$}'`;return new aG0(`${$} ${Z}`,Q)}}O7$.InvalidArgumentError=aG0;class e01 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}O7$.InvalidOperationError=e01;class sG0 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new sG0($);return null}}O7$.UserAuthenticationExpiredError=sG0;class eG0 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],Q=$.toLowerCase();for(let X=0;X<Z.length;X++)if(Q.indexOf(Z[X])!==-1)return new eG0($);return null}}O7$.AuthorizationError=eG0;class $11 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}O7$.ClosedConnectionError=$11;class Z11 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}O7$.DrainingConnectionError=Z11;class Q11 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}O7$.ConnectionError=Q11;class X11 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}O7$.ProtocolError=X11;class Y11 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof $30}}O7$.RequestError=Y11;class J11 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}O7$.TimeoutError=J11;class $30 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}O7$.NoRespondersError=$30;class Z30 extends Error{operation;subject;queue;constructor($,Z,Q,X,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=Q,this.queue=X}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let Q="publish",X="",Y=void 0,J=$.match(/(Publish|Subscription) to "(\S+)"/);if(J){if(Q=J[1].toLowerCase(),X=J[2],Q==="subscription"){let G=$.match(/using queue "(\S+)"/);if(G)Y=G[1]}}return new Z30($,Q,X,Y)}}O7$.PermissionViolationError=Z30;O7$.errors={AuthorizationError:eG0,ClosedConnectionError:$11,ConnectionError:Q11,DrainingConnectionError:Z11,InvalidArgumentError:aG0,InvalidOperationError:e01,InvalidSubjectError:s01,NoRespondersError:$30,PermissionViolationError:Z30,ProtocolError:X11,RequestError:Y11,TimeoutError:J11,UserAuthenticationExpiredError:sG0}});var yW=b((z7$)=>{Object.defineProperty(z7$,"__esModule",{value:!0});z7$.SimpleMutex=z7$.Perf=void 0;z7$.extend=MK4;z7$.render=IK4;z7$.timeout=VK4;z7$.delay=kK4;z7$.deadline=SK4;z7$.deferred=K11;z7$.debugDeferred=CK4;z7$.shuffle=_K4;z7$.collect=vK4;z7$.jitter=E7$;z7$.backoff=xK4;z7$.nanos=fK4;z7$.millis=bK4;z7$.randomToken=hK4;var qK4=qG(),G11=MG();function MK4($,...Z){for(let Q=0;Q<Z.length;Q++){let X=Z[Q];Object.keys(X).forEach(function(Y){$[Y]=X[Y]})}return $}function IK4($){return qK4.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function VK4($,Z=!0){let Q=Z?new G11.TimeoutError:null,X,Y,J=new Promise((G,K)=>{X={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(Q===null)K(new G11.TimeoutError);else K(Q)},$)});return Object.assign(J,X)}function kK4($=0){let Z,Q=new Promise((X)=>{let Y=setTimeout(()=>{X()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),X()}}});return Object.assign(Q,Z)}async function SK4($,Z=1000){let Q=K11(),X=setTimeout(()=>{Q.reject(new G11.TimeoutError)},Z);try{return await Promise.race([$,Q])}finally{clearTimeout(X)}}function K11(){let $={},Z=new Promise((Q,X)=>{$={resolve:Q,reject:X}});return Object.assign(Z,$)}function CK4(){let $={},Z=new Promise((Q,X)=>{$={resolve:(Y)=>{console.trace("resolve",Y),Q(Y)},reject:(Y)=>{console.trace("reject"),X(Y)}}});return Object.assign(Z,$)}function _K4($){for(let Z=$.length-1;Z>0;Z--){let Q=Math.floor(Math.random()*(Z+1));[$[Z],$[Q]]=[$[Q],$[Z]]}return $}async function vK4($){let Z=[];for await(let Q of $)Z.push(Q);return Z}class w7${timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,Q){let X=this.timers.get(Z);if(X===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(Q);if(Y===void 0)throw Error(`${Q} is not defined`);this.measures.set($,Y-X)}getEntries(){let $=[];return this.measures.forEach((Z,Q)=>{$.push({name:Q,duration:Z})}),$}}z7$.Perf=w7$;class j7${max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=K11();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}z7$.SimpleMutex=j7$;function E7$($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function xK4($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(Q){return E7$(Q>Z?$[Z]:$[Q])}}}function fK4($){return $*1e6}function bK4($){return Math.floor($/1e6)}var yK4="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",MB=new Uint8Array(62);for(let $=0;$<62;$++)MB[$]=yK4.charCodeAt($);var gK4=218340105584896;function hK4(){let $=Math.floor(Math.random()*gK4),Z=$%62,Q=MB[Z];$=($-Z)/62,Z=$%62;let X=MB[Z];$=($-Z)/62,Z=$%62;let Y=MB[Z];$=($-Z)/62,Z=$%62;let J=MB[Z];$=($-Z)/62,Z=$%62;let G=MB[Z];$=($-Z)/62,Z=$%62;let K=MB[Z];$=($-Z)/62,Z=$%62;let W=MB[Z];$=($-Z)/62;let H=MB[$];return String.fromCharCode(Q,X,Y,J,G,K,W,H)}});var V7$=b((M7$)=>{Object.defineProperty(M7$,"__esModule",{value:!0});M7$.nuid=M7$.NuidImpl=void 0;var ZW4="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",cD=62,X30=12,R7$=10,T7$=33,QW4=333,A7$=X30+R7$,H11=new Uint8Array(cD);for(let $=0;$<cD;$++)H11[$]=ZW4.charCodeAt($);var Q30=4294967296,q7$=BigInt(cD)**BigInt(R7$),fr=Number(q7$/(1n<<32n)),W11=Number(q7$%(1n<<32n));function XW4($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function YW4($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else XW4($)}class F11{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(A7$),this.cbuf=new Uint8Array(X30),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(fr+1)),this.seqLo=Math.floor(Math.random()*Q30);while($++<8&&this.seqHi===fr&&this.seqLo>=W11);if(this.seqHi===fr&&this.seqLo>=W11)this.seqLo=0;this.inc=Math.random()*(QW4-T7$)+T7$|0}setPre(){YW4(this.cbuf);for(let $=0;$<X30;$++)this.buf[$]=H11[this.cbuf[$]%cD]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let Q=A7$-1;Q>=X30;Q--){let X=Math.floor($/cD),J=($-X*cD)*Q30+Z,G=Math.floor(J/cD),K=J-G*cD;this.buf[Q]=H11[K],$=X,Z=G}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=Q30)this.seqLo-=Q30,this.seqHi+=1;if(this.seqHi>fr||this.seqHi===fr&&this.seqLo>=W11)this.setPre(),this.initSeqAndInc();this.fillSeq();let $=this.buf;return String.fromCharCode($[0],$[1],$[2],$[3],$[4],$[5],$[6],$[7],$[8],$[9],$[10],$[11],$[12],$[13],$[14],$[15],$[16],$[17],$[18],$[19],$[20],$[21])}reset(){this.init()}}M7$.NuidImpl=F11;M7$.nuid=new F11});var _7$=b((S7$)=>{Object.defineProperty(S7$,"__esModule",{value:!0});S7$.nuid=S7$.Nuid=void 0;var k7$=V7$();S7$.Nuid=k7$.NuidImpl;S7$.nuid=k7$.nuid});var J30=b((Y30)=>{Object.defineProperty(Y30,"__esModule",{value:!0});Y30.nuid=Y30.Nuid=void 0;var v7$=_7$();Object.defineProperty(Y30,"Nuid",{enumerable:!0,get:function(){return v7$.Nuid}});Object.defineProperty(Y30,"nuid",{enumerable:!0,get:function(){return v7$.nuid}})});var mD=b((x7$)=>{Object.defineProperty(x7$,"__esModule",{value:!0});x7$.DEFAULT_HOST=x7$.DEFAULT_PORT=x7$.Match=void 0;x7$.syncIterator=FW4;x7$.createInbox=UW4;var WW4=J30(),HW4=MG();x7$.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function FW4($){let Z=$[Symbol.asyncIterator]();return{async next(){let Q=await Z.next();if(Q.done)return Promise.resolve(null);return Promise.resolve(Q.value)}}}function UW4($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw HW4.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${WW4.nuid.next()}`}x7$.DEFAULT_PORT=4222;x7$.DEFAULT_HOST="127.0.0.1"});var br=b((g7$)=>{Object.defineProperty(g7$,"__esModule",{value:!0});g7$.DataBuffer=void 0;var b7$=qG();class y7${buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let Q=new Uint8Array(Z),X=0;for(let Y=0;Y<$.length;Y++)Q.set($[Y],X),X+=$[Y].length;return Q}static fromAscii($){if(!$)$="";return b7$.TE.encode($)}static toAscii($){return b7$.TD.decode($)}reset(){this.buffers.length=0,this.byteLength=0}pack(){if(this.buffers.length>1){let $=new Uint8Array(this.byteLength),Z=0;for(let Q=0;Q<this.buffers.length;Q++)$.set(this.buffers[Q],Z),Z+=this.buffers[Q].length;this.buffers.length=0,this.buffers.push($)}}shift(){if(this.buffers.length){let $=this.buffers.shift();if($)return this.byteLength-=$.length,$}return new Uint8Array(0)}drain($){if(this.buffers.length){this.pack();let Z=this.buffers.pop();if(Z){let Q=this.byteLength;if($===void 0||$>Q)$=Q;let X=Z.subarray(0,$);if(Q>$)this.buffers.push(Z.subarray($));return this.byteLength=Q-$,X}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let Q=0;Q<Z.length;Q++)if(Z[Q]&&Z[Q].length)this.buffers.push(Z[Q]),this.byteLength+=Z[Q].length}peek(){if(this.buffers.length)return this.pack(),this.buffers[0];return new Uint8Array(0)}size(){return this.byteLength}length(){return this.buffers.length}}g7$.DataBuffer=y7$});var $T=b((l7$)=>{Object.defineProperty(l7$,"__esModule",{value:!0});l7$.LF=l7$.CR=l7$.CRLF=l7$.CR_LF_LEN=l7$.CR_LF=void 0;l7$.setTransportFactory=EW4;l7$.defaultPort=zW4;l7$.getUrlParseFn=PW4;l7$.newTransport=TW4;l7$.getResolveFn=AW4;l7$.protoLen=u7$;l7$.extractProtocolMessage=RW4;var DW4=qG(),wW4=mD(),jW4=br(),IG;function EW4($){IG=$}function zW4(){return IG!==void 0&&IG.defaultPort!==void 0?IG.defaultPort:wW4.DEFAULT_PORT}function PW4(){return IG!==void 0&&IG.urlParseFn?IG.urlParseFn:void 0}function TW4(){if(!IG||typeof IG.factory!=="function")throw Error("transport fn is not set");return IG.factory()}function AW4(){return IG!==void 0&&IG.dnsResolveFn?IG.dnsResolveFn:void 0}l7$.CR_LF=`\r
|
|
2095
2095
|
`;l7$.CR_LF_LEN=l7$.CR_LF.length;l7$.CRLF=jW4.DataBuffer.fromAscii(l7$.CR_LF);l7$.CR=new Uint8Array(l7$.CRLF)[0];l7$.LF=new Uint8Array(l7$.CRLF)[1];function u7$($){for(let Z=0;Z<$.length;Z++){let Q=Z+1;if($.byteLength>Q&&$[Z]===l7$.CR&&$[Q]===l7$.LF)return Q+1}return 0}function RW4($){let Z=u7$($);if(Z>0){let X=new Uint8Array($).slice(0,Z);return DW4.TD.decode(X)}return""}});var O11=b((o7$)=>{Object.defineProperty(o7$,"__esModule",{value:!0});o7$.ipV4=p7$;o7$.isIP=fW4;o7$.parseIP=n7$;var yr=4,ZT=16,G30=48,i7$=57,m7$=65,vW4=70,d7$=97,xW4=102,L11=16777215;function p7$($,Z,Q,X){let Y=new Uint8Array(ZT);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((G,K)=>{Y[K]=G}),Y[12]=$,Y[13]=Z,Y[14]=Q,Y[15]=X,Y}function fW4($){return n7$($)!==void 0}function n7$($){for(let Z=0;Z<$.length;Z++)switch($[Z]){case".":return t7$($);case":":return bW4($)}return}function t7$($){let Z=new Uint8Array(yr);for(let Q=0;Q<yr;Q++){if($.length===0)return;if(Q>0){if($[0]!==".")return;$=$.substring(1)}let{n:X,c:Y,ok:J}=yW4($);if(!J||X>255)return;$=$.substring(Y),Z[Q]=X}return p7$(Z[0],Z[1],Z[2],Z[3])}function bW4($){let Z=new Uint8Array(ZT),Q=-1;if($.length>=2&&$[0]===":"&&$[1]===":"){if(Q=0,$=$.substring(2),$.length===0)return Z}let X=0;while(X<ZT){let{n:Y,c:J,ok:G}=gW4($);if(!G||Y>65535)return;if(J<$.length&&$[J]==="."){if(Q<0&&X!=ZT-yr)return;if(X+yr>ZT)return;let K=t7$($);if(K===void 0)return;Z[X]=K[12],Z[X+1]=K[13],Z[X+2]=K[14],Z[X+3]=K[15],$="",X+=yr;break}if(Z[X]=Y>>8,Z[X+1]=Y,X+=2,$=$.substring(J),$.length===0)break;if($[0]!==":"||$.length==1)return;if($=$.substring(1),$[0]===":"){if(Q>=0)return;if(Q=X,$=$.substring(1),$.length===0)break}}if($.length!==0)return;if(X<ZT){if(Q<0)return;let Y=ZT-X;for(let J=X-1;J>=Q;J--)Z[J+Y]=Z[J];for(let J=Q+Y-1;J>=Q;J--)Z[J]=0}else if(Q>=0)return;return Z}function yW4($){let Z=0,Q=0;for(Z=0;Z<$.length&&G30<=$.charCodeAt(Z)&&$.charCodeAt(Z)<=i7$;Z++)if(Q=Q*10+($.charCodeAt(Z)-G30),Q>=L11)return{n:L11,c:Z,ok:!1};if(Z===0)return{n:0,c:0,ok:!1};return{n:Q,c:Z,ok:!0}}function gW4($){let Z=0,Q=0;for(Q=0;Q<$.length;Q++){if(G30<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=i7$)Z*=16,Z+=$.charCodeAt(Q)-G30;else if(d7$<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=xW4)Z*=16,Z+=$.charCodeAt(Q)-d7$+10;else if(m7$<=$.charCodeAt(Q)&&$.charCodeAt(Q)<=vW4)Z*=16,Z+=$.charCodeAt(Q)-m7$+10;else break;if(Z>=L11)return{n:0,c:Q,ok:!1}}if(Q===0)return{n:0,c:Q,ok:!1};return{n:Z,c:Q,ok:!0}}});var P11=b((a7$)=>{Object.defineProperty(a7$,"__esModule",{value:!0});a7$.Servers=a7$.ServerImpl=void 0;a7$.isIPV4OrHostname=r7$;a7$.hostPort=z11;var D11=$T(),w11=yW(),j11=O11(),cW4=mD(),mW4=MG();function r7$($){if($.indexOf("[")!==-1||$.indexOf("::")!==-1)return!1;if($.indexOf(".")!==-1)return!0;if($.split(":").length<=2)return!0;return!1}function E11($){return!r7$($)}function dW4($){let Q=$.toUpperCase().indexOf("::FFFF:");if(Q!==-1&&$.indexOf(".")!==-1){let X=$.substring(Q+7);return X=X.replace("[",""),X.replace("]","")}return $}function z11($){if($=$.trim(),$.match(/^(.*:\/\/)(.*)/m))$=$.replace(/^(.*:\/\/)(.*)/gm,"$2");if($=dW4($),E11($)&&$.indexOf("[")===-1)$=`[${$}]`;let Z=E11($)?$.match(/(]:)(\d+)/):$.match(/(:)(\d+)/),Q=Z&&Z.length===3&&Z[1]&&Z[2]?parseInt(Z[2]):cW4.DEFAULT_PORT,Y=new URL(`${Q===80?"https":"http"}://${$}`);Y.port=`${Q}`;let J=Y.hostname;if(J.charAt(0)==="[")J=J.substring(1,J.length-1);return{listen:Y.host,hostname:J,port:Q}}class Xl{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor($,Z=!1){this.src=$,this.tlsName="";let Q=z11($);this.listen=Q.listen,this.hostname=Q.hostname,this.port=Q.port,this.didConnect=!1,this.reconnects=0,this.lastConnect=0,this.gossiped=Z}toString(){return this.listen}async resolve($){if(!$.fn||$.resolve===!1)return[this];let Z=[];if((0,j11.isIP)(this.hostname))return[this];else{let Q=await $.fn(this.hostname);if($.debug)console.log(`resolve ${this.hostname} = ${Q.join(",")}`);for(let X of Q){let Y=this.port===80?"https":"http",J=new URL(`${Y}://${E11(X)?"["+X+"]":X}`);J.port=`${this.port}`;let G=new Xl(J.host,!1);G.tlsName=this.hostname,Z.push(G)}}if($.randomize)(0,w11.shuffle)(Z);return this.resolves=Z,Z}}a7$.ServerImpl=Xl;class K30{firstSelect;servers;currentServer;tlsName;randomize;constructor($={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=$.randomize||!1}setServers($){if(!Array.isArray($)||$.length===0)throw mW4.InvalidArgumentError.format("servers","cannot be empty");let Z=(0,D11.getUrlParseFn)(),Q=new Map;for(let Y of this.servers)Q.set(Y.listen,Y);let X=[];for(let Y of $){Y=Z?Z(Y):Y;let{listen:J}=z11(Y),G=Q.get(J);if(G)G.gossiped=!1,X.push(G);else X.push(new Xl(Y))}if(this.randomize)(0,w11.shuffle)(X);if(this.servers=X,this.currentServer===void 0||!X.includes(this.currentServer))this.currentServer=X[0],this.firstSelect=!0}clear(){this.servers.length=0}updateTLSName(){let $=this.getCurrentServer();if(!(0,j11.isIP)($.hostname))this.tlsName=$.hostname,this.servers.forEach((Z)=>{if(Z.gossiped)Z.tlsName=this.tlsName})}getCurrentServer(){return this.currentServer}addServer($,Z=!1){let Q=(0,D11.getUrlParseFn)();$=Q?Q($):$;let X=new Xl($,Z);if((0,j11.isIP)(X.hostname))X.tlsName=this.tlsName;this.servers.push(X)}selectServer(){if(this.firstSelect)return this.firstSelect=!1,this.currentServer;let $=this.servers.shift();if($)this.servers.push($),this.currentServer=$;return $}removeCurrentServer(){this.removeServer(this.currentServer)}removeServer($){if($){let Z=this.servers.indexOf($);this.servers.splice(Z,1)}}snapshot(){return K30.freezeAll(this.servers)}snapshotForHandler(){let $=this.currentServer;if(!$)return this.snapshot();let Z=this.servers.indexOf($);if(Z<=0)return this.snapshot();return K30.freezeAll([$,...this.servers.slice(0,Z),...this.servers.slice(Z+1)])}static freezeAll($){return $.map((Z)=>Object.freeze({hostname:Z.hostname,port:Z.port,listen:Z.listen,src:Z.src,tlsName:Z.tlsName,reconnects:Z.reconnects,lastConnect:Z.lastConnect,gossiped:Z.gossiped,didConnect:Z.didConnect}))}find($){return this.servers.find((Z)=>Z.listen===$.listen)}setCurrent($){this.currentServer=$}length(){return this.servers.length}next(){return this.servers.length?this.servers[0]:void 0}getServers(){return this.servers}update($,Z){let Q=[],X=[],Y=(0,D11.getUrlParseFn)(),J=new Map;if($.connect_urls&&$.connect_urls.length>0)$.connect_urls.forEach((K)=>{K=Y?Y(K,Z):K;let W=new Xl(K,!0);J.set(K,W)});let G=[];if(this.servers.forEach((K,W)=>{let H=K.listen;if(K.gossiped&&this.currentServer.listen!==H&&J.get(H)===void 0)G.push(W);J.delete(H)}),G.reverse(),G.forEach((K)=>{let W=this.servers.splice(K,1);X=X.concat(W[0].listen)}),J.forEach((K,W)=>{this.servers.push(K),Q.push(W)}),this.randomize&&Q.length>0){let K=this.currentServer,W=this.servers.filter((H)=>H!==K);(0,w11.shuffle)(W),this.servers=K?[K,...W]:W}return{added:Q,deleted:X}}}a7$.Servers=K30});var W30=b((ZQ$)=>{Object.defineProperty(ZQ$,"__esModule",{value:!0});ZQ$.QueuedIteratorImpl=void 0;var T11=yW(),e7$=MG();class $Q${inflight;processed;received;noIterator;iterClosed;done;signal;yields;filtered;pendingFiltered;ctx;_data;err;time;profile;yielding;didBreak;constructor(){this.inflight=0,this.filtered=0,this.pendingFiltered=0,this.processed=0,this.received=0,this.noIterator=!1,this.done=!1,this.signal=(0,T11.deferred)(),this.yields=[],this.iterClosed=(0,T11.deferred)(),this.time=0,this.yielding=!1,this.didBreak=!1,this.profile=!1}[Symbol.asyncIterator](){return this.iterate()}push($){if(this.done)return;if(this.didBreak){if(typeof $==="function"){let Z=$;try{Z()}catch(Q){}}return}if(typeof $==="function")this.pendingFiltered++;this.yields.push($),this.signal.resolve()}async*iterate(){if(this.noIterator)throw new e7$.InvalidOperationError("iterator cannot be used when a callback is registered");if(this.yielding)throw new e7$.InvalidOperationError("iterator is already yielding");this.yielding=!0;try{while(!0){if(this.yields.length===0)await this.signal;if(this.err)throw this.err;let $=this.yields;this.inflight=$.length,this.yields=[];for(let Z=0;Z<$.length;Z++){if(typeof $[Z]==="function"){this.pendingFiltered--;let X=$[Z];try{X()}catch(Y){throw Y}if(this.err)throw this.err;continue}this.processed++,this.inflight--;let Q=this.profile?Date.now():0;yield $[Z],this.time=this.profile?Date.now()-Q:0}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,T11.deferred)()}}finally{this.didBreak=!0,this.stop()}}stop($){if(this.done)return;this.err=$,this.done=!0,this.signal.resolve(),this.iterClosed.resolve($)}getProcessed(){return this.noIterator?this.received:this.processed}getPending(){return this.yields.length+this.inflight-this.pendingFiltered}getReceived(){return this.received-this.filtered}}ZQ$.QueuedIteratorImpl=$Q$});var A11=b((JQ$)=>{Object.defineProperty(JQ$,"__esModule",{value:!0});JQ$.MuxSubscription=void 0;var tW4=mD(),XQ$=MG();class YQ${baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init($){return this.baseInbox=`${(0,tW4.createInbox)($)}.`,this.baseInbox}add($){if(!isNaN($.received))$.received=0;this.reqs.set($.token,$)}get($){return this.reqs.get($)}cancel($){this.reqs.delete($.token)}getToken($){let Z=$.subject||"";if(Z.indexOf(this.baseInbox)===0)return Z.substring(this.baseInbox.length);return null}all(){return Array.from(this.reqs.values())}handleError($,Z){if($)return this.all().forEach((Q)=>{Q.resolver(Z,{})}),!0;if(Z.operation==="publish"){let Q=this.all().find((X)=>{return X.requestSubject===Z.subject});if(Q)return Q.resolver(Z,{}),!0}return!1}dispatcher(){return($,Z)=>{let Q=this.getToken(Z);if(Q){let X=this.get(Q);if(X){if($===null)$=Z?.data?.length===0&&Z.headers?.code===503?new XQ$.NoRespondersError(X.requestSubject):null;X.resolver($,Z)}}}}close(){let $=new XQ$.RequestError("connection closed");this.reqs.forEach((Z)=>{Z.resolver($,{})})}}JQ$.MuxSubscription=YQ$});var R11=b((WQ$)=>{Object.defineProperty(WQ$,"__esModule",{value:!0});WQ$.Heartbeat=void 0;var oW4=yW();class KQ${ph;interval;maxOut;timer;pendings;constructor($,Z,Q){this.ph=$,this.interval=Z,this.maxOut=Q,this.pendings=[]}start(){this.cancel(),this._schedule()}cancel($){if(this.timer)clearTimeout(this.timer),this.timer=void 0;if(this._reset(),$)this.ph.disconnect()}_schedule(){this.timer=setTimeout(()=>{if(this.ph.dispatchStatus({type:"ping",pendingPings:this.pendings.length+1}),this.pendings.length===this.maxOut){this.cancel(!0);return}let $=(0,oW4.deferred)();this.ph.flush($).then(()=>{this._reset()}).catch(()=>{this.cancel()}),this.pendings.push($),this._schedule()},this.interval)}_reset(){this.pendings=this.pendings.filter(($)=>{return $.resolve(),!1})}}WQ$.Heartbeat=KQ$});var I11=b((BQ$)=>{Object.defineProperty(BQ$,"__esModule",{value:!0});BQ$.DenoBuffer=BQ$.MAX_SIZE=BQ$.AssertionError=void 0;BQ$.assert=UQ$;BQ$.concat=NQ$;BQ$.append=aW4;BQ$.readAll=sW4;BQ$.writeAll=eW4;var rW4=qG();class q11 extends Error{constructor($){super($);this.name="AssertionError"}}BQ$.AssertionError=q11;function UQ$($,Z="Assertion failed."){if(!$)throw new q11(Z)}var FQ$=32768;BQ$.MAX_SIZE=4294967294;function H30($,Z,Q=0){let X=Z.byteLength-Q;if($.byteLength>X)$=$.subarray(0,X);return Z.set($,Q),$.byteLength}function NQ$($,Z){if($===void 0&&Z===void 0)return new Uint8Array(0);if($===void 0)return Z;if(Z===void 0)return $;let Q=new Uint8Array($.length+Z.length);return Q.set($,0),Q.set(Z,$.length),Q}function aW4($,Z){return NQ$($,Uint8Array.of(Z))}class M11{_buf;_off;constructor($){if(this._off=0,$==null){this._buf=new Uint8Array(0);return}this._buf=new Uint8Array($)}bytes($={copy:!0}){if($.copy===!1)return this._buf.subarray(this._off);return this._buf.slice(this._off)}empty(){return this._buf.byteLength<=this._off}get length(){return this._buf.byteLength-this._off}get capacity(){return this._buf.buffer.byteLength}truncate($){if($===0){this.reset();return}if($<0||$>this.length)throw Error("bytes.Buffer: truncation out of range");this._reslice(this._off+$)}reset(){this._reslice(0),this._off=0}_tryGrowByReslice($){let Z=this._buf.byteLength;if($<=this.capacity-Z)return this._reslice(Z+$),Z;return-1}_reslice($){UQ$($<=this._buf.buffer.byteLength),this._buf=new Uint8Array(this._buf.buffer,0,$)}readByte(){let $=new Uint8Array(1);if(this.read($))return $[0];return null}read($){if(this.empty()){if(this.reset(),$.byteLength===0)return 0;return null}let Z=H30(this._buf.subarray(this._off),$);return this._off+=Z,Z}writeByte($){return this.write(Uint8Array.of($))}writeString($){return this.write(rW4.TE.encode($))}write($){let Z=this._grow($.byteLength);return H30($,this._buf,Z)}_grow($){let Z=this.length;if(Z===0&&this._off!==0)this.reset();let Q=this._tryGrowByReslice($);if(Q>=0)return Q;let X=this.capacity;if($<=Math.floor(X/2)-Z)H30(this._buf.subarray(this._off),this._buf);else if(X+$>BQ$.MAX_SIZE)throw Error("The buffer cannot be grown beyond the maximum size.");else{let Y=new Uint8Array(Math.min(2*X+$,BQ$.MAX_SIZE));H30(this._buf.subarray(this._off),Y),this._buf=Y}return this._off=0,this._reslice(Math.min(Z+$,BQ$.MAX_SIZE)),Z}grow($){if($<0)throw Error("Buffer._grow: negative count");let Z=this._grow($);this._reslice(Z)}readFrom($){let Z=0,Q=new Uint8Array(FQ$);while(!0){let X=this.capacity-this.length<FQ$,Y=X?Q:new Uint8Array(this._buf.buffer,this.length),J=$.read(Y);if(J===null)return Z;if(X)this.write(Y.subarray(0,J));else this._reslice(this.length+J);Z+=J}}}BQ$.DenoBuffer=M11;function sW4($){let Z=new M11;return Z.readFrom($),Z.bytes()}function eW4($,Z){let Q=0;while(Q<Z.length)Q+=$.write(Z.subarray(Q))}});var S11=b((jQ$)=>{Object.defineProperty(jQ$,"__esModule",{value:!0});jQ$.cc=jQ$.State=jQ$.Parser=jQ$.Kind=void 0;jQ$.describe=GH4;var V11=I11(),k11=qG();jQ$.Kind={OK:0,ERR:1,MSG:2,INFO:3,PING:4,PONG:5};function GH4($){let Z,Q="";switch($.kind){case jQ$.Kind.MSG:Z="MSG";break;case jQ$.Kind.OK:Z="OK";break;case jQ$.Kind.ERR:Z="ERR",Q=k11.TD.decode($.data);break;case jQ$.Kind.PING:Z="PING";break;case jQ$.Kind.PONG:Z="PONG";break;case jQ$.Kind.INFO:Z="INFO",Q=k11.TD.decode($.data)}return`${Z}: ${Q}`}function OQ$(){let $={};return $.sid=-1,$.hdr=-1,$.size=-1,$}var DQ$=48,KH4=57,Yl=67108864;class wQ${dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor($){this.dispatcher=$,this.state=jQ$.State.OP_START,this.as=0,this.drop=0,this.hdr=0}parse($){let Z;for(Z=0;Z<$.length;Z++){let Q=$[Z];switch(this.state){case jQ$.State.OP_START:switch(Q){case jQ$.cc.M:case jQ$.cc.m:this.state=jQ$.State.OP_M,this.hdr=-1,this.ma=OQ$();break;case jQ$.cc.H:case jQ$.cc.h:this.state=jQ$.State.OP_H,this.hdr=0,this.ma=OQ$();break;case jQ$.cc.P:case jQ$.cc.p:this.state=jQ$.State.OP_P;break;case jQ$.cc.PLUS:this.state=jQ$.State.OP_PLUS;break;case jQ$.cc.MINUS:this.state=jQ$.State.OP_MINUS;break;case jQ$.cc.I:case jQ$.cc.i:this.state=jQ$.State.OP_I;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_H:switch(Q){case jQ$.cc.M:case jQ$.cc.m:this.state=jQ$.State.OP_M;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_M:switch(Q){case jQ$.cc.S:case jQ$.cc.s:this.state=jQ$.State.OP_MS;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_MS:switch(Q){case jQ$.cc.G:case jQ$.cc.g:this.state=jQ$.State.OP_MSG;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_MSG:switch(Q){case jQ$.cc.SPACE:case jQ$.cc.TAB:this.state=jQ$.State.OP_MSG_SPC;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_MSG_SPC:switch(Q){case jQ$.cc.SPACE:case jQ$.cc.TAB:continue;default:this.state=jQ$.State.MSG_ARG,this.as=Z}break;case jQ$.State.MSG_ARG:switch(Q){case jQ$.cc.CR:this.drop=1;break;case jQ$.cc.NL:{let X=this.argBuf?this.argBuf.bytes():$.subarray(this.as,Z-this.drop);this.processMsgArgs(X),this.drop=0,this.as=Z+1,this.state=jQ$.State.MSG_PAYLOAD,Z=this.as+this.ma.size-1;break}default:if(this.argBuf)this.argBuf.writeByte(Q)}break;case jQ$.State.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){let X=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:jQ$.Kind.MSG,msg:this.ma,data:X}),this.argBuf=void 0,this.msgBuf=void 0,this.state=jQ$.State.MSG_END}else{let X=this.ma.size-this.msgBuf.length,Y=$.length-Z;if(Y<X)X=Y;if(X>0)this.msgBuf.write($.subarray(Z,Z+X)),Z=Z+X-1;else this.msgBuf.writeByte(Q)}else if(Z-this.as>=this.ma.size)this.dispatcher.push({kind:jQ$.Kind.MSG,msg:this.ma,data:$.subarray(this.as,Z)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=jQ$.State.MSG_END;break;case jQ$.State.MSG_END:switch(Q){case jQ$.cc.NL:this.drop=0,this.as=Z+1,this.state=jQ$.State.OP_START;break;default:continue}break;case jQ$.State.OP_PLUS:switch(Q){case jQ$.cc.O:case jQ$.cc.o:this.state=jQ$.State.OP_PLUS_O;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_PLUS_O:switch(Q){case jQ$.cc.K:case jQ$.cc.k:this.state=jQ$.State.OP_PLUS_OK;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_PLUS_OK:switch(Q){case jQ$.cc.NL:this.dispatcher.push({kind:jQ$.Kind.OK}),this.drop=0,this.state=jQ$.State.OP_START;break}break;case jQ$.State.OP_MINUS:switch(Q){case jQ$.cc.E:case jQ$.cc.e:this.state=jQ$.State.OP_MINUS_E;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_MINUS_E:switch(Q){case jQ$.cc.R:case jQ$.cc.r:this.state=jQ$.State.OP_MINUS_ER;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_MINUS_ER:switch(Q){case jQ$.cc.R:case jQ$.cc.r:this.state=jQ$.State.OP_MINUS_ERR;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_MINUS_ERR:switch(Q){case jQ$.cc.SPACE:case jQ$.cc.TAB:this.state=jQ$.State.OP_MINUS_ERR_SPC;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_MINUS_ERR_SPC:switch(Q){case jQ$.cc.SPACE:case jQ$.cc.TAB:continue;default:this.state=jQ$.State.MINUS_ERR_ARG,this.as=Z}break;case jQ$.State.MINUS_ERR_ARG:switch(Q){case jQ$.cc.CR:this.drop=1;break;case jQ$.cc.NL:{let X;if(this.argBuf)X=this.argBuf.bytes(),this.argBuf=void 0;else X=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:jQ$.Kind.ERR,data:X}),this.drop=0,this.as=Z+1,this.state=jQ$.State.OP_START;break}default:if(this.argBuf)this.argBuf.write(Uint8Array.of(Q))}break;case jQ$.State.OP_P:switch(Q){case jQ$.cc.I:case jQ$.cc.i:this.state=jQ$.State.OP_PI;break;case jQ$.cc.O:case jQ$.cc.o:this.state=jQ$.State.OP_PO;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_PO:switch(Q){case jQ$.cc.N:case jQ$.cc.n:this.state=jQ$.State.OP_PON;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_PON:switch(Q){case jQ$.cc.G:case jQ$.cc.g:this.state=jQ$.State.OP_PONG;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_PONG:switch(Q){case jQ$.cc.NL:this.dispatcher.push({kind:jQ$.Kind.PONG}),this.drop=0,this.state=jQ$.State.OP_START;break}break;case jQ$.State.OP_PI:switch(Q){case jQ$.cc.N:case jQ$.cc.n:this.state=jQ$.State.OP_PIN;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_PIN:switch(Q){case jQ$.cc.G:case jQ$.cc.g:this.state=jQ$.State.OP_PING;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_PING:switch(Q){case jQ$.cc.NL:this.dispatcher.push({kind:jQ$.Kind.PING}),this.drop=0,this.state=jQ$.State.OP_START;break}break;case jQ$.State.OP_I:switch(Q){case jQ$.cc.N:case jQ$.cc.n:this.state=jQ$.State.OP_IN;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_IN:switch(Q){case jQ$.cc.F:case jQ$.cc.f:this.state=jQ$.State.OP_INF;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_INF:switch(Q){case jQ$.cc.O:case jQ$.cc.o:this.state=jQ$.State.OP_INFO;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_INFO:switch(Q){case jQ$.cc.SPACE:case jQ$.cc.TAB:this.state=jQ$.State.OP_INFO_SPC;break;default:throw this.fail($.subarray(Z))}break;case jQ$.State.OP_INFO_SPC:switch(Q){case jQ$.cc.SPACE:case jQ$.cc.TAB:continue;default:this.state=jQ$.State.INFO_ARG,this.as=Z}break;case jQ$.State.INFO_ARG:switch(Q){case jQ$.cc.CR:this.drop=1;break;case jQ$.cc.NL:{let X;if(this.argBuf)X=this.argBuf.bytes(),this.argBuf=void 0;else X=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:jQ$.Kind.INFO,data:X}),this.drop=0,this.as=Z+1,this.state=jQ$.State.OP_START;break}default:if(this.argBuf)this.argBuf.writeByte(Q)}break;default:throw this.fail($.subarray(Z))}}if((this.state===jQ$.State.MSG_ARG||this.state===jQ$.State.MINUS_ERR_ARG||this.state===jQ$.State.INFO_ARG)&&!this.argBuf)this.argBuf=new V11.DenoBuffer($.subarray(this.as,Z-this.drop));if(this.state===jQ$.State.MSG_PAYLOAD&&!this.msgBuf){if(!this.argBuf)this.cloneMsgArg();this.msgBuf=new V11.DenoBuffer($.subarray(this.as))}}cloneMsgArg(){let $=this.ma.subject.length,Z=this.ma.reply?this.ma.reply.length:0,Q=new Uint8Array($+Z);if(Q.set(this.ma.subject),this.ma.reply)Q.set(this.ma.reply,$);if(this.argBuf=new V11.DenoBuffer(Q),this.ma.subject=Q.subarray(0,$),this.ma.reply)this.ma.reply=Q.subarray($)}processMsgArgs($){if(this.hdr>=0)return this.processHeaderMsgArgs($);let Z=[],Q=-1;for(let X=0;X<$.length;X++)switch($[X]){case jQ$.cc.SPACE:case jQ$.cc.TAB:case jQ$.cc.CR:case jQ$.cc.NL:if(Q>=0)Z.push($.subarray(Q,X)),Q=-1;break;default:if(Q<0)Q=X}if(Q>=0)Z.push($.subarray(Q));switch(Z.length){case 3:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.size=this.protoParseInt(Z[2],Yl);break;case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.size=this.protoParseInt(Z[3],Yl);break;default:throw this.fail($,"processMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processMsgArgs Bad or Missing Sid Error");if(this.ma.size<0)throw this.fail($,"processMsgArgs Bad or Missing Size Error")}fail($,Z=""){if(!Z)Z=`parse error [${this.state}]`;else Z=`${Z} [${this.state}]`;return Error(`${Z}: ${k11.TD.decode($)}`)}processHeaderMsgArgs($){let Z=[],Q=-1;for(let X=0;X<$.length;X++)switch($[X]){case jQ$.cc.SPACE:case jQ$.cc.TAB:case jQ$.cc.CR:case jQ$.cc.NL:if(Q>=0)Z.push($.subarray(Q,X)),Q=-1;break;default:if(Q<0)Q=X}if(Q>=0)Z.push($.subarray(Q));switch(Z.length){case 4:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=void 0,this.ma.hdr=this.protoParseInt(Z[2],Yl),this.ma.size=this.protoParseInt(Z[3],Yl);break;case 5:this.ma.subject=Z[0],this.ma.sid=this.protoParseInt(Z[1]),this.ma.reply=Z[2],this.ma.hdr=this.protoParseInt(Z[3],Yl),this.ma.size=this.protoParseInt(Z[4],Yl);break;default:throw this.fail($,"processHeaderMsgArgs Parse Error")}if(this.ma.sid<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Sid Error");if(this.ma.hdr<0||this.ma.hdr>this.ma.size)throw this.fail($,"processHeaderMsgArgs Bad or Missing Header Size Error");if(this.ma.size<0)throw this.fail($,"processHeaderMsgArgs Bad or Missing Size Error")}protoParseInt($,Z){if($.length===0||$.length>15)return-1;let Q=0;for(let X=0;X<$.length;X++){if($[X]<DQ$||$[X]>KH4)return-1;Q=Q*10+($[X]-DQ$)}return Z!==void 0&&Q>Z?-1:Q}}jQ$.Parser=wQ$;jQ$.State={OP_START:0,OP_PLUS:1,OP_PLUS_O:2,OP_PLUS_OK:3,OP_MINUS:4,OP_MINUS_E:5,OP_MINUS_ER:6,OP_MINUS_ERR:7,OP_MINUS_ERR_SPC:8,MINUS_ERR_ARG:9,OP_M:10,OP_MS:11,OP_MSG:12,OP_MSG_SPC:13,MSG_ARG:14,MSG_PAYLOAD:15,MSG_END:16,OP_H:17,OP_P:18,OP_PI:19,OP_PIN:20,OP_PING:21,OP_PO:22,OP_PON:23,OP_PONG:24,OP_I:25,OP_IN:26,OP_INF:27,OP_INFO:28,OP_INFO_SPC:29,INFO_ARG:30};jQ$.cc={CR:13,E:69,e:101,F:70,f:102,G:71,g:103,H:72,h:104,I:73,i:105,K:75,k:107,M:77,m:109,MINUS:45,N:78,n:110,NL:10,O:79,o:111,P:80,p:112,PLUS:43,R:82,r:114,S:83,s:115,SPACE:32,TAB:9}});var N30=b((zQ$)=>{Object.defineProperty(zQ$,"__esModule",{value:!0});zQ$.MsgHdrsImpl=void 0;zQ$.canonicalMIMEHeaderKey=_11;zQ$.headers=FH4;var EQ$=qG(),gW=mD(),U30=MG();function _11($){let F=!0,U=Array($.length);for(let N=0;N<$.length;N++){let B=$.charCodeAt(N);if(B===58||B<33||B>126)throw U30.InvalidArgumentError.format("header",`'${$[N]}' is not a valid character in a header name`);if(F&&97<=B&&B<=122)B-=32;else if(!F&&65<=B&&B<=90)B+=32;U[N]=B,F=B==45}return String.fromCharCode(...U)}function FH4($=0,Z=""){if($===0&&Z!=="")throw U30.InvalidArgumentError.format("code","is required");else if($>0&&Z==="")throw U30.InvalidArgumentError.format("description","is required");return new Jl($,Z)}var C11="NATS/1.0";class Jl{_code;headers;_description;constructor($=0,Z=""){this._code=$,this._description=Z,this.headers=new Map}[Symbol.iterator](){return this.headers.entries()}size(){return this.headers.size}equals($){if($&&this.headers.size===$.headers.size&&this._code===$._code){for(let[Z,Q]of this.headers){let X=$.values(Z);if(Q.length!==X.length)return!1;let Y=[...Q].sort(),J=[...X].sort();for(let G=0;G<Y.length;G++)if(Y[G]!==J[G])return!1}return!0}return!1}static decode($){let Z=new Jl,X=EQ$.TD.decode($).split(`\r
|
|
2096
2096
|
`),Y=X[0];if(Y!==C11){let J=Y.replace(C11,"").trim();if(J.length>0){if(Z._code=parseInt(J,10),isNaN(Z._code))Z._code=0;let G=Z._code.toString();J=J.replace(G,""),Z._description=J.trim()}}if(X.length>=1)X.slice(1).map((J)=>{if(J){let G=J.indexOf(":");if(G>-1){let K=J.slice(0,G),W=J.slice(G+1).trim();Z.append(K,W)}}});return Z}toString(){if(this.headers.size===0&&this._code===0)return"";let $=C11;if(this._code>0&&this._description!=="")$+=` ${this._code} ${this._description}`;for(let[Z,Q]of this.headers)for(let X=0;X<Q.length;X++)$=`${$}\r
|
|
2097
2097
|
${Z}: ${Q[X]}`;return`${$}\r
|
|
@@ -2115,7 +2115,7 @@ ${K}`;F(w);return}if(G(null,j),Q.strategy==="count"){if(W--,W===0)F()}if(Q.strat
|
|
|
2115
2115
|
`}static header(){return`Test,Date,Lang,Version,Count,MsgPayload,Bytes,Millis,Async
|
|
2116
2116
|
`}}CX$.Metric=pD;class VX${nc;callbacks;msgs;size;subject;asyncRequests;pub;sub;req;rep;perf;payload;constructor($,Z={msgs:1e5,size:128,subject:"",asyncRequests:!1,pub:!1,sub:!1,req:!1,rep:!1}){if(this.nc=$,this.callbacks=Z.callbacks||!1,this.msgs=Z.msgs||0,this.size=Z.size||0,this.subject=Z.subject||mF4.nuid.next(),this.asyncRequests=Z.asyncRequests||!1,this.pub=Z.pub||!1,this.sub=Z.sub||!1,this.req=Z.req||!1,this.rep=Z.rep||!1,this.perf=new Z$1.Perf,this.payload=this.size?new Uint8Array(this.size):cF4.Empty,!this.pub&&!this.sub&&!this.req&&!this.rep)throw Error("no options selected")}async run(){if(this.nc.closed().then(($)=>{if($)throw $}),this.callbacks)await this.runCallbacks();else await this.runAsync();return this.processMetrics()}processMetrics(){let $=this.nc,{lang:Z,version:Q}=$.protocol.transport;if(this.pub&&this.sub)this.perf.measure("pubsub","pubStart","subStop");if(this.req&&this.rep)this.perf.measure("reqrep","reqStart","reqStop");let X=this.perf.getEntries(),Y=X.find((N)=>N.name==="pubsub"),J=X.find((N)=>N.name==="reqrep"),G=X.find((N)=>N.name==="req"),K=X.find((N)=>N.name==="rep"),W=X.find((N)=>N.name==="pub"),H=X.find((N)=>N.name==="sub"),F=this.nc.stats(),U=[];if(Y){let{name:N,duration:B}=Y,O=new pD(N,B);O.msgs=this.msgs*2,O.bytes=F.inBytes+F.outBytes,O.lang=Z,O.version=Q,O.payload=this.payload.length,U.push(O)}if(J){let{name:N,duration:B}=J,O=new pD(N,B);O.msgs=this.msgs*2,O.bytes=F.inBytes+F.outBytes,O.lang=Z,O.version=Q,O.payload=this.payload.length,U.push(O)}if(W){let{name:N,duration:B}=W,O=new pD(N,B);O.msgs=this.msgs,O.bytes=F.outBytes,O.lang=Z,O.version=Q,O.payload=this.payload.length,U.push(O)}if(H){let{name:N,duration:B}=H,O=new pD(N,B);O.msgs=this.msgs,O.bytes=F.inBytes,O.lang=Z,O.version=Q,O.payload=this.payload.length,U.push(O)}if(K){let{name:N,duration:B}=K,O=new pD(N,B);O.msgs=this.msgs,O.bytes=F.inBytes+F.outBytes,O.lang=Z,O.version=Q,O.payload=this.payload.length,U.push(O)}if(G){let{name:N,duration:B}=G,O=new pD(N,B);O.msgs=this.msgs,O.bytes=F.inBytes+F.outBytes,O.lang=Z,O.version=Q,O.payload=this.payload.length,U.push(O)}return U}async runCallbacks(){let $=[];if(this.sub){let Z=(0,Z$1.deferred)();$.push(Z);let Q=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:()=>{if(Q++,Q===1)this.perf.mark("subStart");if(Q===this.msgs)this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop"),Z.resolve()}})}if(this.rep){let Z=(0,Z$1.deferred)();$.push(Z);let Q=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:(X,Y)=>{if(Y.respond(this.payload),Q++,Q===1)this.perf.mark("repStart");if(Q===this.msgs)this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop"),Z.resolve()}})}if(this.pub){let Z=(async()=>{this.perf.mark("pubStart");for(let Q=0;Q<this.msgs;Q++)this.nc.publish(this.subject,this.payload);await this.nc.flush(),this.perf.mark("pubStop"),this.perf.measure("pub","pubStart","pubStop")})();$.push(Z)}if(this.req){let Z=(async()=>{if(this.asyncRequests){this.perf.mark("reqStart");let Q=[];for(let X=0;X<this.msgs;X++)Q.push(this.nc.request(this.subject,this.payload,{timeout:20000}));await Promise.all(Q),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let Q=0;Q<this.msgs;Q++)await this.nc.request(this.subject);this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}})();$.push(Z)}await Promise.all($)}async runAsync(){let $=[];if(this.rep){let Z=!1,Q=this.nc.subscribe(this.subject,{max:this.msgs}),X=(async()=>{for await(let Y of Q){if(!Z)this.perf.mark("repStart"),Z=!0;Y.respond(this.payload)}await this.nc.flush(),this.perf.mark("repStop"),this.perf.measure("rep","repStart","repStop")})();$.push(X)}if(this.sub){let Z=!1,Q=this.nc.subscribe(this.subject,{max:this.msgs}),X=(async()=>{for await(let Y of Q)if(!Z)this.perf.mark("subStart"),Z=!0;this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop")})();$.push(X)}if(this.pub){let Z=(async()=>{this.perf.mark("pubStart");for(let Q=0;Q<this.msgs;Q++)this.nc.publish(this.subject,this.payload);await this.nc.flush(),this.perf.mark("pubStop"),this.perf.measure("pub","pubStart","pubStop")})();$.push(Z)}if(this.req){let Z=(async()=>{if(this.asyncRequests){this.perf.mark("reqStart");let Q=[];for(let X=0;X<this.msgs;X++)Q.push(this.nc.request(this.subject,this.payload,{timeout:20000}));await Promise.all(Q),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let Q=0;Q<this.msgs;Q++)await this.nc.request(this.subject);this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}})();$.push(Z)}await Promise.all($)}}CX$.Bench=VX$;function kX$($,Z){return`${SX$($/Z)}/sec`}function dF4($,Z){return`${Math.floor($/Z)} msgs/sec`}function SX$($,Z=!1){let Q=Z?1000:1024,X=Z?["k","M","G","T","P","E"]:["K","M","G","T","P","E"],Y=Z?"iB":"B";if($<Q)return`${$.toFixed(2)} ${Y}`;let J=parseInt(Math.log($)/Math.log(Q)+""),G=parseInt(J-1+"");return`${($/Math.pow(Q,J)).toFixed(2)} ${X[G]}${Y}`}function iF4($){return $.toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}});var yX$=b((fX$)=>{Object.defineProperty(fX$,"__esModule",{value:!0});fX$.IdleHeartbeatMonitor=void 0;class xX${interval;maxOut;cancelAfter;timer;autoCancelTimer;last;missed;count;callback;constructor($,Z,Q={maxOut:2}){this.interval=$,this.maxOut=Q?.maxOut||2,this.cancelAfter=Q?.cancelAfter||0,this.last=Date.now(),this.missed=0,this.count=0,this.callback=Z,this._schedule()}cancel(){if(this.autoCancelTimer)clearTimeout(this.autoCancelTimer);if(this.timer)clearInterval(this.timer);this.timer=0,this.autoCancelTimer=0,this.missed=0}work(){this.last=Date.now(),this.missed=0}_change($,Z=0,Q=2){this.interval=$,this.maxOut=Q,this.cancelAfter=Z,this.restart()}restart(){this.cancel(),this._schedule()}_schedule(){if(this.cancelAfter>0)this.autoCancelTimer=setTimeout(()=>{this.cancel()},this.cancelAfter);this.timer=setInterval(()=>{if(this.count++,Date.now()-this.last>this.interval)this.missed++;if(this.missed>=this.maxOut)try{if(this.callback(this.missed)===!0)this.cancel()}catch($){console.log($)}},this.interval)}}fX$.IdleHeartbeatMonitor=xX$});var uX$=b((gX$)=>{Object.defineProperty(gX$,"__esModule",{value:!0});gX$.version=void 0;gX$.version="3.4.0"});var pX$=b((dX$)=>{Object.defineProperty(dX$,"__esModule",{value:!0});dX$.WsTransport=void 0;dX$.wsUrlParseFn=mX$;dX$.wsconnect=XU4;var IB=yW(),lX$=$T(),rF4=dr(),aF4=br(),sF4=ir(),eF4=s11(),$U4=uX$(),cX$=MG(),ZU4=$U4.version,QU4="nats.ws";class Q$1{version;lang;closeError;connected;done;socket;options;socketClosed;encrypted;peeked;yields;signal;closedNotification;constructor(){this.version=ZU4,this.lang=QU4,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=(0,IB.deferred)(),this.closedNotification=(0,IB.deferred)()}async connect($,Z){let X=(0,IB.deferred)();this.options=Z;let Y=$.src;if(Z.wsFactory){let{socket:J,encrypted:G}=await Z.wsFactory($.src,Z);this.socket=J,this.encrypted=G}else this.encrypted=Y.indexOf("wss://")===0,this.socket=new WebSocket(Y);return this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{if(this.done)this._closed(Error("aborted"))},this.socket.onmessage=(J)=>{if(this.done)return;if(this.yields.push(new Uint8Array(J.data)),this.peeked){this.signal.resolve();return}let G=aF4.DataBuffer.concat(...this.yields),K=(0,lX$.extractProtocolMessage)(G);if(K!==""){let W=sF4.INFO.exec(K);if(!W){if(Z.debug)console.error("!!!",(0,IB.render)(G));X.reject(Error("unexpected response from server"));return}try{let H=JSON.parse(W[1]);(0,rF4.checkOptions)(H,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),X.resolve()}catch(H){X.reject(H);return}}},this.socket.onclose=(J)=>{let G;if(!J.wasClean&&J.reason!=="")G=Error(J.reason);this._closed(G),this._cleanup()},this.socket.onerror=(J)=>{if(this.done)return;let G=J,K=new cX$.errors.ConnectionError(G.message);X.reject(K),this._cleanup()},X}_cleanup(){if(this.socketClosed===!1)this.socketClosed=!0,this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,this.closedNotification.resolve(this.closeError)}disconnect(){this._closed(void 0,!0)}async _closed($,Z=!0){if(this.done){try{this.socket.close()}catch(Q){}return}if(this.closeError=$,!$)while(!this.socketClosed&&this.socket.bufferedAmount>0)await(0,IB.delay)(100);this.done=!0;try{this.socket.close()}catch(Q){}return this.closedNotification}get isClosed(){return this.done}[Symbol.asyncIterator](){return this.iterate()}async*iterate(){while(!0){if(this.done)return;if(this.yields.length===0)await this.signal;let $=this.yields;this.yields=[];for(let Z=0;Z<$.length;Z++){if(this.options.debug)console.info(`> ${(0,IB.render)($[Z])}`);yield $[Z]}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,IB.deferred)()}}isEncrypted(){return this.connected&&this.encrypted}send($){if(this.done)return;try{if(this.socket.send($.buffer),this.options.debug)console.info(`< ${(0,IB.render)($)}`);return}catch(Z){if(this.options.debug)console.error(`!!! ${(0,IB.render)($)}: ${Z}`)}}close($){return this._closed($,!1)}closed(){return this.closedNotification}discard(){this.socket?.close()}}dX$.WsTransport=Q$1;function mX$($,Z){if(!/^(.*:\/\/)(.*)/.test($))if(typeof Z==="boolean")$=`${Z===!0?"https":"http"}://${$}`;else $=`https://${$}`;let X=new URL($),Y=X.protocol.toLowerCase();if(Y==="ws:")Z=!1;if(Y==="wss:")Z=!0;if(Y!=="https:"&&Y!=="http")$=$.replace(/^(.*:\/\/)(.*)/gm,"$2"),X=new URL(`http://${$}`);let J,G,K=X.hostname,W=X.pathname,H=X.search||"";switch(Y){case"http:":case"ws:":case"nats:":G=X.port||"80",J="ws:";break;case"https:":case"wss:":case"tls:":G=X.port||"443",J="wss:";break;default:G=X.port||Z===!0?"443":"80",J=Z===!0?"wss:":"ws:";break}return`${J}//${K}:${G}${W}${H}`}function XU4($={}){return(0,lX$.setTransportFactory)({defaultPort:443,urlParseFn:mX$,factory:()=>{if($.tls)throw cX$.InvalidArgumentError.format("tls","is not configurable on w3c websocket connections");return new Q$1}}),eF4.NatsConnectionImpl.connect($)}});var VG=b((q0)=>{var GU4=q0&&q0.__createBinding||(Object.create?function($,Z,Q,X){if(X===void 0)X=Q;var Y=Object.getOwnPropertyDescriptor(Z,Q);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[Q]}};Object.defineProperty($,X,Y)}:function($,Z,Q,X){if(X===void 0)X=Q;$[X]=Z[Q]}),KU4=q0&&q0.__exportStar||function($,Z){for(var Q in $)if(Q!=="default"&&!Object.prototype.hasOwnProperty.call(Z,Q))GU4(Z,$,Q)};Object.defineProperty(q0,"__esModule",{value:!0});q0.Metric=q0.Bench=q0.writeAll=q0.readAll=q0.MAX_SIZE=q0.DenoBuffer=q0.State=q0.Parser=q0.Kind=q0.describe=q0.QueuedIteratorImpl=q0.usernamePasswordAuthenticator=q0.tokenAuthenticator=q0.nkeyAuthenticator=q0.jwtAuthenticator=q0.credsAuthenticator=q0.RequestOne=q0.parseOptions=q0.hasWsProtocol=q0.defaultOptions=q0.DEFAULT_MAX_RECONNECT_ATTEMPTS=q0.checkUnsupportedOption=q0.checkOptions=q0.buildAuthenticator=q0.DataBuffer=q0.MuxSubscription=q0.Heartbeat=q0.MsgHdrsImpl=q0.headers=q0.canonicalMIMEHeaderKey=q0.timeout=q0.SimpleMutex=q0.render=q0.nanos=q0.millis=q0.extend=q0.delay=q0.deferred=q0.deadline=q0.collect=q0.backoff=q0.ProtocolHandler=q0.INFO=q0.Connect=q0.setTransportFactory=q0.getResolveFn=q0.MsgImpl=q0.nuid=q0.Nuid=q0.NatsConnectionImpl=void 0;q0.UserAuthenticationExpiredError=q0.TimeoutError=q0.RequestError=q0.ProtocolError=q0.PermissionViolationError=q0.NoRespondersError=q0.InvalidSubjectError=q0.InvalidOperationError=q0.InvalidArgumentError=q0.errors=q0.DrainingConnectionError=q0.ConnectionError=q0.ClosedConnectionError=q0.AuthorizationError=q0.wsUrlParseFn=q0.wsconnect=q0.Servers=q0.isIPV4OrHostname=q0.IdleHeartbeatMonitor=q0.Subscriptions=q0.SubscriptionImpl=q0.syncIterator=q0.Match=q0.createInbox=q0.protoLen=q0.extractProtocolMessage=q0.Empty=q0.parseSemVer=q0.Features=q0.Feature=q0.compare=q0.parseIP=q0.isIP=q0.ipV4=q0.TE=q0.TD=void 0;var WU4=s11();Object.defineProperty(q0,"NatsConnectionImpl",{enumerable:!0,get:function(){return WU4.NatsConnectionImpl}});var nX$=J30();Object.defineProperty(q0,"Nuid",{enumerable:!0,get:function(){return nX$.Nuid}});Object.defineProperty(q0,"nuid",{enumerable:!0,get:function(){return nX$.nuid}});var HU4=v11();Object.defineProperty(q0,"MsgImpl",{enumerable:!0,get:function(){return HU4.MsgImpl}});var tX$=$T();Object.defineProperty(q0,"getResolveFn",{enumerable:!0,get:function(){return tX$.getResolveFn}});Object.defineProperty(q0,"setTransportFactory",{enumerable:!0,get:function(){return tX$.setTransportFactory}});var X$1=ir();Object.defineProperty(q0,"Connect",{enumerable:!0,get:function(){return X$1.Connect}});Object.defineProperty(q0,"INFO",{enumerable:!0,get:function(){return X$1.INFO}});Object.defineProperty(q0,"ProtocolHandler",{enumerable:!0,get:function(){return X$1.ProtocolHandler}});var uW=yW();Object.defineProperty(q0,"backoff",{enumerable:!0,get:function(){return uW.backoff}});Object.defineProperty(q0,"collect",{enumerable:!0,get:function(){return uW.collect}});Object.defineProperty(q0,"deadline",{enumerable:!0,get:function(){return uW.deadline}});Object.defineProperty(q0,"deferred",{enumerable:!0,get:function(){return uW.deferred}});Object.defineProperty(q0,"delay",{enumerable:!0,get:function(){return uW.delay}});Object.defineProperty(q0,"extend",{enumerable:!0,get:function(){return uW.extend}});Object.defineProperty(q0,"millis",{enumerable:!0,get:function(){return uW.millis}});Object.defineProperty(q0,"nanos",{enumerable:!0,get:function(){return uW.nanos}});Object.defineProperty(q0,"render",{enumerable:!0,get:function(){return uW.render}});Object.defineProperty(q0,"SimpleMutex",{enumerable:!0,get:function(){return uW.SimpleMutex}});Object.defineProperty(q0,"timeout",{enumerable:!0,get:function(){return uW.timeout}});var Y$1=N30();Object.defineProperty(q0,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return Y$1.canonicalMIMEHeaderKey}});Object.defineProperty(q0,"headers",{enumerable:!0,get:function(){return Y$1.headers}});Object.defineProperty(q0,"MsgHdrsImpl",{enumerable:!0,get:function(){return Y$1.MsgHdrsImpl}});var FU4=R11();Object.defineProperty(q0,"Heartbeat",{enumerable:!0,get:function(){return FU4.Heartbeat}});var UU4=A11();Object.defineProperty(q0,"MuxSubscription",{enumerable:!0,get:function(){return UU4.MuxSubscription}});var NU4=br();Object.defineProperty(q0,"DataBuffer",{enumerable:!0,get:function(){return NU4.DataBuffer}});var GT=dr();Object.defineProperty(q0,"buildAuthenticator",{enumerable:!0,get:function(){return GT.buildAuthenticator}});Object.defineProperty(q0,"checkOptions",{enumerable:!0,get:function(){return GT.checkOptions}});Object.defineProperty(q0,"checkUnsupportedOption",{enumerable:!0,get:function(){return GT.checkUnsupportedOption}});Object.defineProperty(q0,"DEFAULT_MAX_RECONNECT_ATTEMPTS",{enumerable:!0,get:function(){return GT.DEFAULT_MAX_RECONNECT_ATTEMPTS}});Object.defineProperty(q0,"defaultOptions",{enumerable:!0,get:function(){return GT.defaultOptions}});Object.defineProperty(q0,"hasWsProtocol",{enumerable:!0,get:function(){return GT.hasWsProtocol}});Object.defineProperty(q0,"parseOptions",{enumerable:!0,get:function(){return GT.parseOptions}});var BU4=r11();Object.defineProperty(q0,"RequestOne",{enumerable:!0,get:function(){return BU4.RequestOne}});var pr=c11();Object.defineProperty(q0,"credsAuthenticator",{enumerable:!0,get:function(){return pr.credsAuthenticator}});Object.defineProperty(q0,"jwtAuthenticator",{enumerable:!0,get:function(){return pr.jwtAuthenticator}});Object.defineProperty(q0,"nkeyAuthenticator",{enumerable:!0,get:function(){return pr.nkeyAuthenticator}});Object.defineProperty(q0,"tokenAuthenticator",{enumerable:!0,get:function(){return pr.tokenAuthenticator}});Object.defineProperty(q0,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return pr.usernamePasswordAuthenticator}});KU4(u11(),q0);var LU4=W30();Object.defineProperty(q0,"QueuedIteratorImpl",{enumerable:!0,get:function(){return LU4.QueuedIteratorImpl}});var V30=S11();Object.defineProperty(q0,"describe",{enumerable:!0,get:function(){return V30.describe}});Object.defineProperty(q0,"Kind",{enumerable:!0,get:function(){return V30.Kind}});Object.defineProperty(q0,"Parser",{enumerable:!0,get:function(){return V30.Parser}});Object.defineProperty(q0,"State",{enumerable:!0,get:function(){return V30.State}});var k30=I11();Object.defineProperty(q0,"DenoBuffer",{enumerable:!0,get:function(){return k30.DenoBuffer}});Object.defineProperty(q0,"MAX_SIZE",{enumerable:!0,get:function(){return k30.MAX_SIZE}});Object.defineProperty(q0,"readAll",{enumerable:!0,get:function(){return k30.readAll}});Object.defineProperty(q0,"writeAll",{enumerable:!0,get:function(){return k30.writeAll}});var oX$=vX$();Object.defineProperty(q0,"Bench",{enumerable:!0,get:function(){return oX$.Bench}});Object.defineProperty(q0,"Metric",{enumerable:!0,get:function(){return oX$.Metric}});var rX$=qG();Object.defineProperty(q0,"TD",{enumerable:!0,get:function(){return rX$.TD}});Object.defineProperty(q0,"TE",{enumerable:!0,get:function(){return rX$.TE}});var J$1=O11();Object.defineProperty(q0,"ipV4",{enumerable:!0,get:function(){return J$1.ipV4}});Object.defineProperty(q0,"isIP",{enumerable:!0,get:function(){return J$1.isIP}});Object.defineProperty(q0,"parseIP",{enumerable:!0,get:function(){return J$1.parseIP}});var S30=O30();Object.defineProperty(q0,"compare",{enumerable:!0,get:function(){return S30.compare}});Object.defineProperty(q0,"Feature",{enumerable:!0,get:function(){return S30.Feature}});Object.defineProperty(q0,"Features",{enumerable:!0,get:function(){return S30.Features}});Object.defineProperty(q0,"parseSemVer",{enumerable:!0,get:function(){return S30.parseSemVer}});var OU4=$$1();Object.defineProperty(q0,"Empty",{enumerable:!0,get:function(){return OU4.Empty}});var aX$=$T();Object.defineProperty(q0,"extractProtocolMessage",{enumerable:!0,get:function(){return aX$.extractProtocolMessage}});Object.defineProperty(q0,"protoLen",{enumerable:!0,get:function(){return aX$.protoLen}});var G$1=mD();Object.defineProperty(q0,"createInbox",{enumerable:!0,get:function(){return G$1.createInbox}});Object.defineProperty(q0,"Match",{enumerable:!0,get:function(){return G$1.Match}});Object.defineProperty(q0,"syncIterator",{enumerable:!0,get:function(){return G$1.syncIterator}});var sX$=ir();Object.defineProperty(q0,"SubscriptionImpl",{enumerable:!0,get:function(){return sX$.SubscriptionImpl}});Object.defineProperty(q0,"Subscriptions",{enumerable:!0,get:function(){return sX$.Subscriptions}});var DU4=yX$();Object.defineProperty(q0,"IdleHeartbeatMonitor",{enumerable:!0,get:function(){return DU4.IdleHeartbeatMonitor}});var eX$=P11();Object.defineProperty(q0,"isIPV4OrHostname",{enumerable:!0,get:function(){return eX$.isIPV4OrHostname}});Object.defineProperty(q0,"Servers",{enumerable:!0,get:function(){return eX$.Servers}});var $Y$=pX$();Object.defineProperty(q0,"wsconnect",{enumerable:!0,get:function(){return $Y$.wsconnect}});Object.defineProperty(q0,"wsUrlParseFn",{enumerable:!0,get:function(){return $Y$.wsUrlParseFn}});var KJ=MG();Object.defineProperty(q0,"AuthorizationError",{enumerable:!0,get:function(){return KJ.AuthorizationError}});Object.defineProperty(q0,"ClosedConnectionError",{enumerable:!0,get:function(){return KJ.ClosedConnectionError}});Object.defineProperty(q0,"ConnectionError",{enumerable:!0,get:function(){return KJ.ConnectionError}});Object.defineProperty(q0,"DrainingConnectionError",{enumerable:!0,get:function(){return KJ.DrainingConnectionError}});Object.defineProperty(q0,"errors",{enumerable:!0,get:function(){return KJ.errors}});Object.defineProperty(q0,"InvalidArgumentError",{enumerable:!0,get:function(){return KJ.InvalidArgumentError}});Object.defineProperty(q0,"InvalidOperationError",{enumerable:!0,get:function(){return KJ.InvalidOperationError}});Object.defineProperty(q0,"InvalidSubjectError",{enumerable:!0,get:function(){return KJ.InvalidSubjectError}});Object.defineProperty(q0,"NoRespondersError",{enumerable:!0,get:function(){return KJ.NoRespondersError}});Object.defineProperty(q0,"PermissionViolationError",{enumerable:!0,get:function(){return KJ.PermissionViolationError}});Object.defineProperty(q0,"ProtocolError",{enumerable:!0,get:function(){return KJ.ProtocolError}});Object.defineProperty(q0,"RequestError",{enumerable:!0,get:function(){return KJ.RequestError}});Object.defineProperty(q0,"TimeoutError",{enumerable:!0,get:function(){return KJ.TimeoutError}});Object.defineProperty(q0,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return KJ.UserAuthenticationExpiredError}})});var VB=b((QY$)=>{Object.defineProperty(QY$,"__esModule",{value:!0});QY$.jserrors=QY$.StreamNotFoundError=QY$.ConsumerNotFoundError=QY$.JetStreamApiError=QY$.InvalidNameError=QY$.JetStreamApiCodes=QY$.JetStreamStatus=QY$.JetStreamStatusError=QY$.JetStreamError=QY$.JetStreamNotEnabled=void 0;QY$.isMessageNotFound=wU4;var ZY$=eP();class K$1 extends Error{constructor($,Z){super($,Z);this.name="JetStreamNotEnabled"}}QY$.JetStreamNotEnabled=K$1;class C30 extends Error{constructor($,Z){super($,Z);this.name="JetStreamError"}}QY$.JetStreamError=C30;class W$1 extends C30{code;constructor($,Z,Q){super($,Q);this.code=Z,this.name="JetStreamStatusError"}}QY$.JetStreamStatusError=W$1;class H$1{msg;_description;constructor($){this.msg=$,this._description=""}static maybeParseStatus($){let Z=new H$1($);return Z.code===0?null:Z}toError(){return new W$1(this.description,this.code)}debug(){console.log({subject:this.msg.subject,reply:this.msg.reply,description:this.description,status:this.code,headers:this.msg.headers})}get code(){return this.msg.headers?.code||0}get description(){if(this._description===""){if(this._description=this.msg.headers?.description?.toLowerCase()||"",this._description==="")this._description=this.code===503?"no responders":"unknown"}return this._description}isIdleHeartbeat(){return this.code===100&&this.description==="idle heartbeat"}isFlowControlRequest(){return this.code===100&&this.description==="flowcontrol request"}parseHeartbeat(){if(this.isIdleHeartbeat())return{type:"heartbeat",lastConsumerSequence:parseInt(this.msg.headers?.get("Nats-Last-Consumer")||"0"),lastStreamSequence:parseInt(this.msg.headers?.get("Nats-Last-Stream")||"0")};return null}isRequestTimeout(){return this.code===408&&this.description==="request timeout"}parseDiscard(){let $={msgsLeft:0,bytesLeft:0},Z=this.msg.headers?.get(ZY$.JsHeaders.PendingMessagesHdr);if(Z)$.msgsLeft=parseInt(Z);let Q=this.msg.headers?.get(ZY$.JsHeaders.PendingBytesHdr);if(Q)$.bytesLeft=parseInt(Q);return $}isBadRequest(){return this.code===400}isConsumerDeleted(){return this.code===409&&this.description==="consumer deleted"}isStreamDeleted(){return this.code===409&&this.description==="stream deleted"}isIdleHeartbeatMissed(){return this.code===409&&this.description==="idle heartbeats missed"}isMaxWaitingExceeded(){return this.code===409&&this.description==="exceeded maxwaiting"}isConsumerIsPushBased(){return this.code===409&&this.description==="consumer is push based"}isExceededMaxWaiting(){return this.code===409&&this.description.includes("exceeded maxwaiting")}isExceededMaxRequestBatch(){return this.code===409&&this.description.includes("exceeded maxrequestbatch")}isExceededMaxExpires(){return this.code===409&&this.description.includes("exceeded maxrequestexpires")}isExceededLimit(){return this.isExceededMaxExpires()||this.isExceededMaxWaiting()||this.isExceededMaxRequestBatch()||this.isMessageSizeExceedsMaxBytes()}isMessageNotFound(){return this.code===404&&this.description==="message not found"}isNoResults(){return this.code===404&&this.description==="no results"}isMessageSizeExceedsMaxBytes(){return this.code===409&&this.description==="message size exceeds maxbytes"}isEndOfBatch(){return this.code===204&&this.description==="eob"}}QY$.JetStreamStatus=H$1;QY$.JetStreamApiCodes={ConsumerNotFound:10014,StreamNotFound:10059,JetStreamNotEnabledForAccount:10039,StreamWrongLastSequence:10071,StreamWrongLastSequenceUnknown:10164,NoMessageFound:10037};function wU4($){return $ instanceof Hl&&$.code===QY$.JetStreamApiCodes.NoMessageFound}class F$1 extends Error{constructor($="",Z){super($,Z);this.name="InvalidNameError"}}QY$.InvalidNameError=F$1;class Hl extends Error{#$;constructor($,Z){super($.description,Z);this.#$=$,this.name="JetStreamApiError"}get code(){return this.#$.err_code}get status(){return this.#$.code}apiError(){return Object.assign({},this.#$)}}QY$.JetStreamApiError=Hl;class U$1 extends Hl{constructor($,Z){super($,Z);this.name="ConsumerNotFoundError"}}QY$.ConsumerNotFoundError=U$1;class _30 extends Hl{constructor($,Z){super($,Z);this.name="StreamNotFoundError"}static fromMessage($){return new _30({err_code:QY$.JetStreamApiCodes.StreamNotFound,description:$,code:404})}}QY$.StreamNotFoundError=_30;QY$.jserrors={InvalidNameError:F$1,ConsumerNotFoundError:U$1,StreamNotFoundError:_30,JetStreamError:C30,JetStreamApiError:Hl,JetStreamNotEnabled:K$1}});var Fl=b((KY$)=>{Object.defineProperty(KY$,"__esModule",{value:!0});KY$.BaseApiClientImpl=void 0;KY$.parseJsResponse=YY$;KY$.defaultJsOptions=JY$;var kB=VG(),IU4=eP(),fF=VB(),VU4="$JS.API",kU4=5000;function YY$($){let Z=JSON.parse(new TextDecoder().decode($.data)),Q=Z;if(Q.error)switch(Q.error.err_code){case fF.JetStreamApiCodes.ConsumerNotFound:throw new fF.ConsumerNotFoundError(Q.error);case fF.JetStreamApiCodes.StreamNotFound:throw new fF.StreamNotFoundError(Q.error);case fF.JetStreamApiCodes.JetStreamNotEnabledForAccount:{let X=new fF.JetStreamApiError(Q.error);throw new fF.JetStreamNotEnabled(X.message,{cause:X})}default:throw new fF.JetStreamApiError(Q.error)}return Z}function JY$($){if($=$||{},$.domain)$.apiPrefix=`$JS.${$.domain}.API`,delete $.domain;return(0,kB.extend)({apiPrefix:VU4,timeout:kU4},$)}class GY${nc;opts;prefix;timeout;constructor($,Z){this.nc=$,Z=Z||{},Z.watcherPrefix=Z.watcherPrefix||this.nc.options.inboxPrefix,this.opts=JY$(Z),this._parseOpts(),this.prefix=this.opts.apiPrefix,this.timeout=this.opts.timeout}getOptions(){return Object.assign({},this.opts)}sendRequiredApiLevel(){return this.opts.sendRequiredApiLevel===!0}_parseOpts(){let $=this.opts.apiPrefix;if(!$||$.length===0)throw kB.errors.InvalidArgumentError.format("prefix","cannot be empty");if($[$.length-1]===".")$=$.substr(0,$.length-1);this.opts.apiPrefix=$,(0,kB.createInbox)(this.opts.watcherPrefix)}async _request($,Z=null,Q){let{retries:X,minApiVersion:Y,...J}=Q??{},G={...J,timeout:this.timeout},K=kB.Empty;if(Z)K=new TextEncoder().encode(JSON.stringify(Z));if(typeof Y==="number"){let F=G.headers??(0,kB.headers)();F.set(IU4.JsHeaders.RequiredApiLevel,Y.toString()),G.headers=F}let W=X||1;W=W===-1?Number.MAX_SAFE_INTEGER:W;let H=(0,kB.backoff)();for(let F=0;F<W;F++)try{let U=await this.nc.request($,K,G);return this.parseJsResponse(U)}catch(U){let N=U instanceof kB.RequestError?U:null;if((U instanceof kB.errors.TimeoutError||N?.isNoResponders())&&F+1<W)await(0,kB.delay)(H.backoff(F));else throw N?.isNoResponders()?new fF.JetStreamNotEnabled("jetstream is not enabled",{cause:U}):U}}async findStream($){let Z={subject:$},X=await this._request(`${this.prefix}.STREAM.NAMES`,Z);if(!X.streams||X.streams.length!==1)throw fF.StreamNotFoundError.fromMessage("no stream matches subject");return X.streams[0]}getConnection(){return this.nc}parseJsResponse($){return YY$($)}}KY$.BaseApiClientImpl=GY$});var v30=b((FY$)=>{Object.defineProperty(FY$,"__esModule",{value:!0});FY$.ListerImpl=void 0;var _U4=VG();class HY${err;offset;pageInfo;subject;jsm;filter;payload;constructor($,Z,Q,X){if(!$)throw _U4.errors.InvalidArgumentError.format("subject","is required");this.subject=$,this.jsm=Q,this.offset=0,this.pageInfo={},this.filter=Z,this.payload=X||{}}async next(){if(this.err)return[];if(this.pageInfo&&this.offset>=this.pageInfo.total)return[];let $={offset:this.offset};if(this.payload)Object.assign($,this.payload);try{let Z=await this.jsm._request(this.subject,$,{timeout:this.jsm.timeout});this.pageInfo=Z;let Q=this.countResponse(Z);if(Q===0)return[];return this.offset+=Q,this.filter(Z)}catch(Z){throw this.err=Z,Z}}countResponse($){switch($?.type){case"io.nats.jetstream.api.v1.stream_names_response":case"io.nats.jetstream.api.v1.stream_list_response":return $.streams?.length||0;case"io.nats.jetstream.api.v1.consumer_list_response":return $.consumers?.length||0;default:return console.error(`jslister.ts: unknown API response for paged output: ${$?.type}`),$.streams?.length||0}}async*[Symbol.asyncIterator](){let $=await this.next();while($.length>0){for(let Z of $)yield Z;$=await this.next()}}}FY$.ListerImpl=HY$});var Ul=b((BY$)=>{Object.defineProperty(BY$,"__esModule",{value:!0});BY$.validateDurableName=xU4;BY$.validateStreamName=fU4;BY$.minValidation=B$1;BY$.validateName=bU4;BY$.validName=NY$;var vU4=VB();function xU4($){return B$1("durable",$)}function fU4($){return B$1("stream",$)}function B$1($,Z=""){if(Z==="")throw Error(`${$} name required`);return[".","*",">","/","\\"," ","\t",`
|
|
2117
2117
|
`,"\r"].forEach((X)=>{if(Z.indexOf(X)!==-1){switch(X){case`
|
|
2118
|
-
`:X="\\n";break;case"\r":X="\\r";break;case"\t":X="\\t";break;default:}throw new vU4.InvalidNameError(`${$} name ('${Z}') cannot contain '${X}'`)}}),""}function bU4($,Z=""){if(Z==="")throw Error(`${$} name required`);let Q=NY$(Z);if(Q.length)throw Error(`invalid ${$} name - ${$} name ${Q}`)}function NY$($=""){if($==="")throw Error("name required");let Z=/^[-\w]+$/g;if($.match(Z)===null){for(let X of $.split(""))if(X.match(Z)===null)return`cannot contain '${X}'`}return""}});var nr=b((t8)=>{Object.defineProperty(t8,"__esModule",{value:!0});t8.wsconnect=t8.usernamePasswordAuthenticator=t8.UserAuthenticationExpiredError=t8.tokenAuthenticator=t8.TimeoutError=t8.syncIterator=t8.RequestError=t8.ProtocolError=t8.PermissionViolationError=t8.nuid=t8.Nuid=t8.NoRespondersError=t8.nkeys=t8.nkeyAuthenticator=t8.nanos=t8.MsgHdrsImpl=t8.millis=t8.Metric=t8.Match=t8.jwtAuthenticator=t8.InvalidSubjectError=t8.InvalidOperationError=t8.InvalidArgumentError=t8.headers=t8.hasWsProtocol=t8.errors=t8.Empty=t8.DrainingConnectionError=t8.delay=t8.deferred=t8.deadline=t8.credsAuthenticator=t8.createInbox=t8.ConnectionError=t8.ClosedConnectionError=t8.canonicalMIMEHeaderKey=t8.buildAuthenticator=t8.Bench=t8.backoff=t8.AuthorizationError=void 0;var F4=VG();Object.defineProperty(t8,"AuthorizationError",{enumerable:!0,get:function(){return F4.AuthorizationError}});Object.defineProperty(t8,"backoff",{enumerable:!0,get:function(){return F4.backoff}});Object.defineProperty(t8,"Bench",{enumerable:!0,get:function(){return F4.Bench}});Object.defineProperty(t8,"buildAuthenticator",{enumerable:!0,get:function(){return F4.buildAuthenticator}});Object.defineProperty(t8,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return F4.canonicalMIMEHeaderKey}});Object.defineProperty(t8,"ClosedConnectionError",{enumerable:!0,get:function(){return F4.ClosedConnectionError}});Object.defineProperty(t8,"ConnectionError",{enumerable:!0,get:function(){return F4.ConnectionError}});Object.defineProperty(t8,"createInbox",{enumerable:!0,get:function(){return F4.createInbox}});Object.defineProperty(t8,"credsAuthenticator",{enumerable:!0,get:function(){return F4.credsAuthenticator}});Object.defineProperty(t8,"deadline",{enumerable:!0,get:function(){return F4.deadline}});Object.defineProperty(t8,"deferred",{enumerable:!0,get:function(){return F4.deferred}});Object.defineProperty(t8,"delay",{enumerable:!0,get:function(){return F4.delay}});Object.defineProperty(t8,"DrainingConnectionError",{enumerable:!0,get:function(){return F4.DrainingConnectionError}});Object.defineProperty(t8,"Empty",{enumerable:!0,get:function(){return F4.Empty}});Object.defineProperty(t8,"errors",{enumerable:!0,get:function(){return F4.errors}});Object.defineProperty(t8,"hasWsProtocol",{enumerable:!0,get:function(){return F4.hasWsProtocol}});Object.defineProperty(t8,"headers",{enumerable:!0,get:function(){return F4.headers}});Object.defineProperty(t8,"InvalidArgumentError",{enumerable:!0,get:function(){return F4.InvalidArgumentError}});Object.defineProperty(t8,"InvalidOperationError",{enumerable:!0,get:function(){return F4.InvalidOperationError}});Object.defineProperty(t8,"InvalidSubjectError",{enumerable:!0,get:function(){return F4.InvalidSubjectError}});Object.defineProperty(t8,"jwtAuthenticator",{enumerable:!0,get:function(){return F4.jwtAuthenticator}});Object.defineProperty(t8,"Match",{enumerable:!0,get:function(){return F4.Match}});Object.defineProperty(t8,"Metric",{enumerable:!0,get:function(){return F4.Metric}});Object.defineProperty(t8,"millis",{enumerable:!0,get:function(){return F4.millis}});Object.defineProperty(t8,"MsgHdrsImpl",{enumerable:!0,get:function(){return F4.MsgHdrsImpl}});Object.defineProperty(t8,"nanos",{enumerable:!0,get:function(){return F4.nanos}});Object.defineProperty(t8,"nkeyAuthenticator",{enumerable:!0,get:function(){return F4.nkeyAuthenticator}});Object.defineProperty(t8,"nkeys",{enumerable:!0,get:function(){return F4.nkeys}});Object.defineProperty(t8,"NoRespondersError",{enumerable:!0,get:function(){return F4.NoRespondersError}});Object.defineProperty(t8,"Nuid",{enumerable:!0,get:function(){return F4.Nuid}});Object.defineProperty(t8,"nuid",{enumerable:!0,get:function(){return F4.nuid}});Object.defineProperty(t8,"PermissionViolationError",{enumerable:!0,get:function(){return F4.PermissionViolationError}});Object.defineProperty(t8,"ProtocolError",{enumerable:!0,get:function(){return F4.ProtocolError}});Object.defineProperty(t8,"RequestError",{enumerable:!0,get:function(){return F4.RequestError}});Object.defineProperty(t8,"syncIterator",{enumerable:!0,get:function(){return F4.syncIterator}});Object.defineProperty(t8,"TimeoutError",{enumerable:!0,get:function(){return F4.TimeoutError}});Object.defineProperty(t8,"tokenAuthenticator",{enumerable:!0,get:function(){return F4.tokenAuthenticator}});Object.defineProperty(t8,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return F4.UserAuthenticationExpiredError}});Object.defineProperty(t8,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return F4.usernamePasswordAuthenticator}});Object.defineProperty(t8,"wsconnect",{enumerable:!0,get:function(){return F4.wsconnect}})});var KT=b((LY$)=>{Object.defineProperty(LY$,"__esModule",{value:!0});LY$.PubHeaders=LY$.PriorityPolicy=LY$.ConsumerApiAction=LY$.PersistMode=LY$.StoreCompression=LY$.ReplayPolicy=LY$.AckPolicy=LY$.DeliverPolicy=LY$.StorageType=LY$.DiscardPolicy=LY$.RetentionPolicy=void 0;LY$.defaultConsumer=dU4;var mU4=nr();LY$.RetentionPolicy={Limits:"limits",Interest:"interest",Workqueue:"workqueue"};LY$.DiscardPolicy={Old:"old",New:"new"};LY$.StorageType={File:"file",Memory:"memory"};LY$.DeliverPolicy={All:"all",Last:"last",New:"new",StartSequence:"by_start_sequence",StartTime:"by_start_time",LastPerSubject:"last_per_subject"};LY$.AckPolicy={None:"none",All:"all",Explicit:"explicit",FlowControl:"flow_control",NotSet:""};LY$.ReplayPolicy={Instant:"instant",Original:"original"};LY$.StoreCompression={None:"none",S2:"s2"};LY$.PersistMode={Default:"default",Async:"async"};LY$.ConsumerApiAction={CreateOrUpdate:"",Update:"update",Create:"create"};LY$.PriorityPolicy={None:"none",Overflow:"overflow",PinnedClient:"pinned_client",Prioritized:"prioritized"};function dU4($,Z={}){return Object.assign({name:$,deliver_policy:LY$.DeliverPolicy.All,ack_policy:LY$.AckPolicy.Explicit,ack_wait:(0,mU4.nanos)(30000),replay_policy:LY$.ReplayPolicy.Instant},Z)}LY$.PubHeaders={MsgIdHdr:"Nats-Msg-Id",ExpectedStreamHdr:"Nats-Expected-Stream",ExpectedLastSeqHdr:"Nats-Expected-Last-Sequence",ExpectedLastMsgIdHdr:"Nats-Expected-Last-Msg-Id",ExpectedLastSubjectSequenceHdr:"Nats-Expected-Last-Subject-Sequence",ExpectedLastSubjectSequenceSubjectHdr:"Nats-Expected-Last-Subject-Sequence-Subject",MessageTTL:"Nats-TTL",Schedule:"Nats-Schedule",ScheduleTarget:"Nats-Schedule-Target",ScheduleSource:"Nats-Schedule-Source",ScheduleTTL:"Nats-Schedule-TTL",ScheduleTimeZone:"Nats-Schedule-Time-Zone",ScheduleRollup:"Nats-Schedule-Rollup",Scheduler:"Nats-Scheduler",ScheduleNext:"Nats-Schedule-Next"}});var L$1=b((PY$)=>{Object.defineProperty(PY$,"__esModule",{value:!0});PY$.ConsumerAPIImpl=void 0;var eU4=Fl(),$N4=v30(),lW=Ul(),BX=VG(),SB=KT();class EY$ extends eU4.BaseApiClientImpl{constructor($,Z){super($,Z)}async addUpdate($,Z,Q,X){if((0,lW.validateStreamName)($),Q=Q||{},Z.deliver_group&&Z.flow_control)throw BX.InvalidArgumentError.format(["flow_control","deliver_group"],"are mutually exclusive");if(Z.deliver_group&&Z.idle_heartbeat)throw BX.InvalidArgumentError.format(["idle_heartbeat","deliver_group"],"are mutually exclusive");if(zY$(Z)){let{min:B,ok:O}=this.nc.features.get(BX.Feature.JS_PRIORITY_GROUPS);if(!O)throw Error(`priority_groups require server ${B}`);if(Z.deliver_subject)throw BX.InvalidArgumentError.format("deliver_subject","cannot be set when using priority groups");ZN4(Z)}let Y={};if(Y.config=Z,Y.stream_name=$,Y.action=Q.action||SB.ConsumerApiAction.Create,Y.pedantic=Q.pedantic||!1,Y.config.durable_name)(0,lW.validateDurableName)(Y.config.durable_name);let J=this.nc,{min:G,ok:K}=J.features.get(BX.Feature.JS_NEW_CONSUMER_CREATE_API),W=Z.name===""?void 0:Z.name;if(W&&!K)throw BX.InvalidArgumentError.format("name",`requires server ${G}`);if(W)try{(0,lW.minValidation)("name",W)}catch(B){let O=B.message,D=O.indexOf("cannot contain");if(D!==-1)throw Error(`consumer 'name' ${O.substring(D)}`);throw B}let H,F="";if(Array.isArray(Z.filter_subjects)){let{min:B,ok:O}=J.features.get(BX.Feature.JS_MULTIPLE_CONSUMER_FILTER);if(!O)throw BX.InvalidArgumentError.format("filter_subjects",`requires server ${B}`);K=!1}if(Z.metadata){let{min:B,ok:O}=J.features.get(BX.Feature.JS_STREAM_CONSUMER_METADATA);if(!O)throw BX.InvalidArgumentError.format("metadata",`requires server ${B}`)}if(K)F=Z.name??Z.durable_name??"";if(F!==""){let B=Z.filter_subject??void 0;if(B===">")B=void 0;H=B!==void 0?`${this.prefix}.CONSUMER.CREATE.${$}.${F}.${B}`:`${this.prefix}.CONSUMER.CREATE.${$}.${F}`}else H=Z.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${$}.${Z.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${$}`;let U=X??Y.config;return await this._request(H,Y,{...Q,...this.requiredApiOpts(U)})}minConsumerApi($){if($.ack_policy===SB.AckPolicy.FlowControl)return 4;if(typeof $.pause_until==="string"&&$.pause_until!=="")return 1;if($.priority_policy!==void 0&&$.priority_policy!==SB.PriorityPolicy.None)return 1;if(typeof $.priority_timeout==="number"&&$.priority_timeout>0)return 1;if(Array.isArray($.priority_groups)&&$.priority_groups.length>0)return 1;return 0}requiredApiOpts($){if(!this.sendRequiredApiLevel())return{};let Z=this.minConsumerApi($);return Z>0?{minApiVersion:Z}:{}}add($,Z,Q){Q=Q||{};let X=SB.ConsumerApiAction.Create;if(typeof Q==="string")X=Q,Q={};let Y=Object.assign({},{action:X},Q);return this.addUpdate($,Z,Y)}async update($,Z,Q){let X=await this.info($,Z),Y=Q;return this.addUpdate($,Object.assign(X.config,Y),{action:SB.ConsumerApiAction.Update},Y)}async info($,Z){return(0,lW.validateStreamName)($),(0,lW.validateDurableName)(Z),await this._request(`${this.prefix}.CONSUMER.INFO.${$}.${Z}`)}async delete($,Z){return(0,lW.validateStreamName)($),(0,lW.validateDurableName)(Z),(await this._request(`${this.prefix}.CONSUMER.DELETE.${$}.${Z}`)).success}list($){(0,lW.validateStreamName)($);let Z=(X)=>{return X.consumers},Q=`${this.prefix}.CONSUMER.LIST.${$}`;return new $N4.ListerImpl(Q,Z,this)}pause($,Z,Q){let X=`${this.prefix}.CONSUMER.PAUSE.${$}.${Z}`,Y={pause_until:Q.toISOString()};return this._request(X,Y)}resume($,Z){return this.pause($,Z,new Date(0))}unpin($,Z,Q){let X=`${this.prefix}.CONSUMER.UNPIN.${$}.${Z}`;return this._request(X,{group:Q})}async reset($,Z,Q){(0,lW.validateStreamName)($),(0,lW.validateDurableName)(Z);let X=this.nc,{min:Y,ok:J}=X.features.get(BX.Feature.JS_CONSUMER_RESET);if(!J)throw Error(`consumer reset requires server ${Y}`);if(typeof Q==="number"&&(!Number.isInteger(Q)||Q<0))throw BX.InvalidArgumentError.format("seq","must be a non-negative integer");let G=`${this.prefix}.CONSUMER.RESET.${$}.${Z}`,K=typeof Q==="number"?{seq:Q}:void 0;return await this._request(G,K)}}PY$.ConsumerAPIImpl=EY$;function zY$($){let Z=$;return Z&&Z.priority_groups!==void 0||Z.priority_policy!==void 0}function ZN4($){if(zY$($)){if(!Array.isArray($.priority_groups))throw BX.InvalidArgumentError.format(["priority_groups"],"must be an array");if($.priority_groups.length===0)throw BX.InvalidArgumentError.format(["priority_groups"],"must have at least one group");if($.priority_groups.forEach((Z)=>{if((0,lW.minValidation)("priority_group",Z),Z.length>16)throw BX.errors.InvalidArgumentError.format("group","must be 16 characters or less")}),$.priority_policy!==SB.PriorityPolicy.None&&$.priority_policy!==SB.PriorityPolicy.Overflow&&$.priority_policy!==SB.PriorityPolicy.PinnedClient&&$.priority_policy!==SB.PriorityPolicy.Prioritized)throw BX.InvalidArgumentError.format(["priority_policy"],"must be 'none', 'prioritized', 'overflow', or 'pinned_client'")}}});var w$1=b((RY$)=>{Object.defineProperty(RY$,"__esModule",{value:!0});RY$.JsMsgImpl=RY$.ACK=void 0;RY$.toJsMsg=GN4;RY$.parseInfo=AY$;var Nl=VG();RY$.ACK=Uint8Array.of(43,65,67,75);var QN4=Uint8Array.of(45,78,65,75),tr=Uint8Array.of(43,87,80,73),XN4=Uint8Array.of(43,78,88,84),YN4=Uint8Array.of(43,84,69,82,77),JN4=Uint8Array.of(32);function GN4($,Z=5000){return new D$1($,Z)}function AY$($){let Z=$.split(".");if(Z.length===9)Z.splice(2,0,"_","");if(Z.length<11||Z[0]!=="$JS"||Z[1]!=="ACK")throw Error("unable to parse delivery info - not a jetstream message");let Q={};return Q.domain=Z[2]==="_"?"":Z[2],Q.account_hash=Z[3],Q.stream=Z[4],Q.consumer=Z[5],Q.deliveryCount=parseInt(Z[6],10),Q.redelivered=Q.deliveryCount>1,Q.streamSequence=parseInt(Z[7],10),Q.deliverySequence=parseInt(Z[8],10),Q.timestampNanos=parseInt(Z[9],10),Q.pending=parseInt(Z[10],10),Q}function KN4($){let Z=$.split(".");if(Z.length===9)Z.splice(2,0,"_","");if(Z.length<11||Z[0]!=="$JS"||Z[1]!=="ACK")throw Error("unable to parse delivery info - not a jetstream message");return BigInt(Z[9])}class D$1{msg;di;didAck;timeout;constructor($,Z){this.msg=$,this.didAck=!1,this.timeout=Z}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){if(!this.di)this.di=AY$(this.reply);return this.di}get redelivered(){return this.info.deliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}get time(){let $=(0,Nl.millis)(this.info.timestampNanos);return new Date($)}get timestamp(){return this.time.toISOString()}get timestampNanos(){return KN4(this.reply)}doAck($){if(!this.didAck)this.didAck=!this.isWIP($),this.msg.respond($)}isWIP($){return $.length===4&&$[0]===tr[0]&&$[1]===tr[1]&&$[2]===tr[2]&&$[3]===tr[3]}async ackAck($){let Z=(0,Nl.deferred)();if(!this.didAck)if(this.didAck=!0,this.msg.reply){$=$||{},$.timeout=$.timeout||this.timeout;let X=this.msg.publisher,Y=!X.options?.noAsyncTraces,J=new Nl.RequestOne(X.muxSubscriptions,this.msg.reply,{timeout:$.timeout},Y);X.request(J);try{X.publish(this.msg.reply,RY$.ACK,{reply:`${X.muxSubscriptions.baseInbox}${J.token}`})}catch(G){J.cancel(G)}try{await Promise.race([J.timer,J.deferred]),Z.resolve(!0)}catch(G){J.cancel(G),Z.reject(G)}}else Z.resolve(!1);else Z.resolve(!1);return Z}ack(){this.doAck(RY$.ACK)}nak($){let Z=QN4;if($)Z=new TextEncoder().encode(`-NAK ${JSON.stringify({delay:(0,Nl.nanos)($)})}`);this.doAck(Z)}working(){this.doAck(tr)}next($,Z={batch:1}){let Q={};if(Q.batch=Z.batch||1,Q.no_wait=Z.no_wait||!1,Z.expires&&Z.expires>0)Q.expires=(0,Nl.nanos)(Z.expires);let X=new TextEncoder().encode(JSON.stringify(Q)),Y=Nl.DataBuffer.concat(XN4,JN4,X),J=$?{reply:$}:void 0;this.msg.respond(Y,J)}term($=""){let Z=YN4;if($?.length>0)Z=new TextEncoder().encode(`+TERM ${$}`);this.doAck(Z)}json(){return this.msg.json()}string(){return this.msg.string()}}RY$.JsMsgImpl=D$1});var xY$=b((_Y$)=>{Object.defineProperty(_Y$,"__esModule",{value:!0});_Y$.PullConsumerImpl=_Y$.PullConsumerMessagesImpl=_Y$.PullConsumerType=void 0;_Y$.isOverflowOptions=or;_Y$.isPrioritizedOptions=x30;_Y$.validateOverflowPullOptions=SY$;_Y$.validatePrioritizedPullOptions=CY$;var Q5=VG(),FN4=w$1(),MY$=KT(),IY$=VB(),VY$=Ul();_Y$.PullConsumerType={Unset:"",Consume:"consume",Fetch:"fetch"};function or($){let Z=$;return Z&&typeof Z.group==="string"||typeof Z.min_pending==="number"||typeof Z.min_ack_pending==="number"}function x30($){let Z=$;return Z&&typeof Z.group==="string"&&typeof Z.priority==="number"}class f30 extends Q5.QueuedIteratorImpl{consumer;opts;sub;monitor;pending;isConsume;callback;listeners;statusIterator;abortOnMissingResource;bind;inboxPrefix;inbox;cancelables;inReset;closeListener;isPinned;isPriority;natsPinId;constructor($,Z,Q=!1){super();if(this.consumer=$,this.isConsume=Q,this.cancelables=[],this.inboxPrefix=(0,Q5.createInbox)(this.consumer.api.nc.options.inboxPrefix),this.inbox=`${this.inboxPrefix}.${this.consumer.serial}`,this.inReset=!1,this.isPinned=!1,this.isPriority=!1,this.natsPinId="",this.consumer.ordered){if(or(Z))throw Q5.errors.InvalidArgumentError.format(["group","min_pending","min_ack_pending"],"cannot be specified for ordered consumers");if(this.consumer.orderedConsumerState===void 0){let Y={},J=$.opts;Y.namePrefix=J.name_prefix??`oc_${Q5.nuid.next()}`,Y.opts=J,Y.cursor={stream_seq:1,deliver_seq:0};let G=$._info.config.opt_start_seq||0;Y.cursor.stream_seq=G>0?G-1:0,Y.createFails=0,this.consumer.orderedConsumerState=Y}}let X=Z;if(this.opts=this.parseOptions(Z,this.isConsume),this.callback=X.callback||null,this.noIterator=typeof this.callback==="function",this.monitor=null,this.pending={msgs:0,bytes:0,requests:0},this.listeners=[],this.abortOnMissingResource=X.abort_on_missing_resource===!0,this.bind=X.bind===!0,X.group){let{min_pending:Y,min_ack_pending:J}=X;this.isPinned=Y===void 0&&J===void 0;let{priority:G}=X;this.isPriority=typeof G==="number"}this.closeListener={connectionClosedCallback:()=>{this._push(()=>{this.stop()})}},this.consumer.api.nc.addCloseListener(this.closeListener),this.start()}start(){let{max_messages:$,max_bytes:Z,idle_heartbeat:Q,threshold_bytes:X,threshold_messages:Y}=this.opts;if(this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(J,G)=>{if(J){this.stop(J);return}if(this.monitor?.work(),this.consumer.ordered?G.subject.indexOf(this?.inboxPrefix)===0:G.subject===this.inbox){if(G.subject!==this.sub.getSubject())return;let W=new IY$.JetStreamStatus(G),H=W.parseHeartbeat();if(H){this.notify(H);return}let{code:F,description:U}=W,{msgsLeft:N,bytesLeft:B}=W.parseDiscard();if(N&&N>0||B&&B>0)this.pending.msgs-=N,this.pending.bytes-=B,this.pending.requests--,this.notify({type:"discard",messagesLeft:N,bytesLeft:B});switch(F){case 400:this.stop(W.toError());return;case 409:{let O=this.handle409(W);if(O){this.stop(O);return}if(W.isMessageSizeExceedsMaxBytes()&&this.yields.length>0)break;return}case 423:this.natsPinId="",this.notify({type:"consumer_unpinned"});break;case 503:if(this.notify({type:"no_responders",code:F}),this.consumer.ordered){let O=this.consumer.orderedConsumerState;O.needsReset=!0}if(!this.isConsume){this.stop(W.toError());return}break;default:this.notify({type:"debug",code:F,description:U})}}else{let W=(0,FN4.toJsMsg)(G,this.consumer.api.timeout);if(this.isPinned){let H=W?.headers?.get("Nats-Pin-Id");if(H&&this.natsPinId==="")this.natsPinId=H,this.notify({type:"consumer_pinned",id:H})}if(this.consumer.ordered){let H=this.consumer.orderedConsumerState.cursor,F=W.info.deliverySequence,U=W.info.streamSequence,N=H.deliver_seq+1;if(F!==N){this.reset();return}H.deliver_seq=F,H.stream_seq=U}if(this._push(W),this.received++,this.pending.msgs)this.pending.msgs--;if(this.pending.bytes)this.pending.bytes-=G.size()}if(this.pending.msgs===0&&this.pending.bytes===0)this.pending.requests=0;if(this.isConsume){if($&&this.pending.msgs<=Y||Z&&this.pending.bytes<=X){let W=this.pullOptions();this.pull(W)}}else if(this.pending.requests===0)this._push(()=>{this.stop()})}}),Q)this.monitor=new Q5.IdleHeartbeatMonitor(Q,(J)=>{if(this.notify({type:"heartbeats_missed",count:J}),!this.isConsume&&!this.consumer.ordered)return this.stop(new IY$.JetStreamError("heartbeats missed")),!0;return this.resetPending().then(()=>{}).catch(()=>{}),!1},{maxOut:2});(async()=>{let J=this.consumer.api.nc.status();this.statusIterator=J;for await(let G of J)switch(G.type){case"disconnect":this.monitor?.cancel();break;case"reconnect":this.resetPending().then((K)=>{if(K)this.monitor?.restart()}).catch(()=>{});break;default:}})(),this.sub.closed.then(()=>{if(this.sub.isDraining())this._push(()=>{this.stop()})}),this.pull(this.pullOptions())}handle409($){let{code:Z,description:Q}=$;if($.isConsumerDeleted())this.notify({type:"consumer_deleted",code:Z,description:Q});else if($.isExceededLimit())this.notify({type:"exceeded_limits",code:Z,description:Q});if(!this.isConsume)return $.toError();if($.isConsumerDeleted()&&this.abortOnMissingResource)return $.toError();return null}reset(){this.monitor?.cancel();let $=this.consumer.orderedConsumerState,{name:Z}=this.consumer._info?.config;if(Z)this.notify({type:"reset",name:Z}),this.consumer.api.delete(this.consumer.stream,Z).catch(()=>{});let Q=this.consumer.getConsumerOpts();this.inbox=`${this.inboxPrefix}.${this.consumer.serial}`,$.cursor.deliver_seq=0,this.consumer.name=Q.name,this.consumer.api.nc._resub(this.sub,this.inbox),this.consumer.api.add(this.consumer.stream,Q).then((X)=>{$.createFails=0,this.consumer._info=X,this.notify({type:"ordered_consumer_recreated",name:X.name}),this.monitor?.restart(),this.pull(this.pullOptions())}).catch((X)=>{if($.createFails++,X.message==="stream not found"){if(this.notify({type:"stream_not_found",consumerCreateFails:$.createFails,name:this.consumer.stream}),this.abortOnMissingResource){this.stop(X);return}}if($.createFails>=30&&this.received===0)this.stop(X);let Y=(0,Q5.backoff)(),J=(0,Q5.delay)(Y.backoff($.createFails));J.then(()=>{let G=this.cancelables.indexOf(J);if(G!==-1)this.cancelables=this.cancelables.splice(G,G);if(!this.done)this.reset()}).catch((G)=>{}),this.cancelables.push(J)})}_push($){if(!this.callback)super.push($);else{let Z=typeof $==="function"?$:null;try{if(!Z){let Q=$;this.callback(Q)}else Z()}catch(Q){this.stop(Q)}}}notify($){if(this.listeners.length>0)(()=>{this.listeners.forEach((Z)=>{let Q=Z;if(!Q.done)Q.push($)})})()}async resetPending(){if(this.inReset)return Promise.resolve(!0);this.inReset=!0;let Z=await(this.bind?this.resetPendingNoInfo():this.resetPendingWithInfo());return this.inReset=!1,Z}resetPendingNoInfo(){return this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),Promise.resolve(!0)}async resetPendingWithInfo(){let $=0,Z=0,Q=(0,Q5.backoff)([this.opts.expires||30000]),X=0;while(!0){if(this.done)return!1;if(this.consumer.api.nc.isClosed())return!1;try{return await this.consumer.info(),$=0,this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),!0}catch(Y){if(Y instanceof Q5.errors.ClosedConnectionError)return this.stop(Y),!1;if(Y.message==="stream not found"){if(Z++,this.notify({type:"stream_not_found",name:this.consumer.stream}),!this.isConsume||this.abortOnMissingResource)return this.stop(Y),!1}else if(Y.message==="consumer not found"){if($++,this.notify({type:"consumer_not_found",name:this.consumer.name,stream:this.consumer.stream,count:$}),!this.isConsume||this.abortOnMissingResource){if(this.consumer.ordered){let K=this.consumer.orderedConsumerState;K.needsReset=!0}return this.stop(Y),!1}if(this.consumer.ordered)return this.reset(),!1}else $=0,Z=0;let J=Q.backoff(X),G=(0,Q5.delay)(J);await Promise.race([G,this.consumer.api.nc.closed()]),G.cancel(),X++}}}pull($){this.pending.bytes+=$.max_bytes??0,this.pending.msgs+=$.batch??0,this.pending.requests++;let Z=this.consumer.api.nc,Q=`${this.consumer.api.prefix}.CONSUMER.MSG.NEXT.${this.consumer.stream}.${this.consumer._info.name}`;this._push(()=>{Z.publish(Q,JSON.stringify($),{reply:this.inbox}),this.notify({type:"next",options:$})})}pullOptions(){let $=this.opts.max_messages-this.pending.msgs,Z=this.opts.max_bytes-this.pending.bytes,Q=(0,Q5.nanos)(this.opts.idle_heartbeat),X=(0,Q5.nanos)(this.opts.expires),Y={batch:$,max_bytes:Z,idle_heartbeat:Q,expires:X};if(this.isPinned&&this.natsPinId!=="")Y.id=this.natsPinId;if(or(this.opts)){if(Y.group=this.opts.group,this.opts.min_pending)Y.min_pending=this.opts.min_pending;if(this.opts.min_ack_pending)Y.min_ack_pending=this.opts.min_ack_pending}if(x30(this.opts))Y.group=this.opts.group,Y.priority=this.opts.priority;return Y}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}clearTimers(){this.monitor?.cancel(),this.monitor=null}stop($){if(this.done)return;this.consumer.api.nc.removeCloseListener(this.closeListener),this.sub?.unsubscribe(),this.clearTimers(),this.statusIterator?.stop(),this._push(()=>{super.stop($),this.listeners.forEach((Z)=>{Z.stop()})})}parseOptions($,Z=!1){let Q=$||{};if(Q.max_messages=Q.max_messages||0,Q.max_bytes=Q.max_bytes||0,Q.max_messages!==0&&Q.max_bytes!==0)throw Q5.errors.InvalidArgumentError.format(["max_messages","max_bytes"],"are mutually exclusive");if(Q.max_messages===0)Q.max_messages=100;if(Q.expires=Q.expires||30000,Q.expires<1000)throw Q5.errors.InvalidArgumentError.format("expires","must be at least 1000ms");if(Q.idle_heartbeat=Q.idle_heartbeat||Q.expires/2,Q.idle_heartbeat=Q.idle_heartbeat>30000?30000:Q.idle_heartbeat,Q.idle_heartbeat<500)Q.idle_heartbeat=500;if(Z){let X=Math.round(Q.max_messages*0.75)||1;Q.threshold_messages=Q.threshold_messages||X;let Y=Math.round(Q.max_bytes*0.75)||1;Q.threshold_bytes=Q.threshold_bytes||Y}if(or($)){let{min:X,ok:Y}=this.consumer.api.nc.features.get(Q5.Feature.JS_PRIORITY_GROUPS);if(!Y)throw Error(`priority_groups require server ${X}`);if(SY$($),$.group)Q.group=$.group;if($.min_ack_pending)Q.min_ack_pending=$.min_ack_pending;if($.min_pending)Q.min_pending=$.min_pending}else if(x30($)){if(CY$($),$.group)Q.group=$.group;if(typeof $.priority==="number")Q.priority=$.priority}return Q}status(){let $=new Q5.QueuedIteratorImpl;return this.listeners.push($),$}}_Y$.PullConsumerMessagesImpl=f30;class kY${api;_info;stream;name;opts;type;messages;ordered;serial;orderedConsumerState;constructor($,Z,Q=null){this.api=$,this._info=Z,this.name=Z.name,this.stream=Z.stream_name,this.ordered=Q!==null,this.opts=Q||{},this.serial=1,this.type=_Y$.PullConsumerType.Unset}debug(){console.log({serial:this.serial,cursor:this.orderedConsumerState?.cursor})}isPullConsumer(){return!0}isPushConsumer(){return!1}consume($={max_messages:100,expires:30000}){if($={...$},this.ordered){if($.bind)return Promise.reject(Q5.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===_Y$.PullConsumerType.Fetch)return Promise.reject(new Q5.errors.InvalidOperationError("ordered consumer initialized as fetch"));if(this.type===_Y$.PullConsumerType.Consume)return Promise.reject(new Q5.errors.InvalidOperationError("ordered consumer doesn't support concurrent consume"));this.type=_Y$.PullConsumerType.Consume}return Promise.resolve(new f30(this,$,!0))}async fetch($={max_messages:100,expires:30000}){if($={...$},this.ordered){if($.group)return Promise.reject(Q5.errors.InvalidArgumentError.format("group","ordered consumers don't support priority groups"));if($.bind)return Promise.reject(Q5.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===_Y$.PullConsumerType.Consume)return Promise.reject(new Q5.errors.InvalidOperationError("ordered consumer already initialized as consume"));if(this.messages?.done===!1)return Promise.reject(new Q5.errors.InvalidOperationError("ordered consumer doesn't support concurrent fetch"));if(this.ordered){if(this.orderedConsumerState?.cursor?.deliver_seq)this._info.config.opt_start_seq=this.orderedConsumerState?.cursor.stream_seq+1;if(this.orderedConsumerState?.needsReset===!0)await this._reset()}this.type=_Y$.PullConsumerType.Fetch}let Z=new f30(this,$);if(this.ordered)this.messages=Z;return Promise.resolve(Z)}async next($={expires:30000}){$={...$};let Z=$;Z.max_messages=1;let Q=await this.fetch(Z);try{for await(let X of Q)return X}catch(X){return Promise.reject(X)}return null}delete(){let{stream_name:$,name:Z}=this._info;return this.api.delete($,Z)}getConsumerOpts(){let $=this.orderedConsumerState;this.serial++,this.name=`${$.namePrefix}_${this.serial}`;let Z=Object.assign({},this._info.config,{name:this.name,deliver_policy:MY$.DeliverPolicy.StartSequence,opt_start_seq:$.cursor.stream_seq+1,ack_policy:MY$.AckPolicy.None,inactive_threshold:(0,Q5.nanos)(300000),num_replicas:1});return delete Z.metadata,Z}async _reset(){if(this.messages===void 0)throw Error("not possible to reset");this.delete().catch(()=>{});let $=this.getConsumerOpts(),Z=await this.api.add(this.stream,$);return this._info=Z,Z}async info($=!1){if($)return Promise.resolve(this._info);let{stream_name:Z,name:Q}=this._info;return this._info=await this.api.info(Z,Q),this._info}}_Y$.PullConsumerImpl=kY$;function SY$($){if(or($)){if((0,VY$.minValidation)("group",$.group),$.group.length>16)throw Q5.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{min_pending:Z,min_ack_pending:Q}=$;if(Z&&typeof Z!=="number")throw Q5.errors.InvalidArgumentError.format(["min_pending"],"must be a number");if(Q&&typeof Q!=="number")throw Q5.errors.InvalidArgumentError.format(["min_ack_pending"],"must be a number")}}function CY$($){if(x30($)){if((0,VY$.minValidation)("group",$.group),$.group.length>16)throw Q5.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{priority:Z}=$;if(Z&&typeof Z!=="number")throw Q5.errors.InvalidArgumentError.format(["priority"],"must be a number")}}});var hY$=b((yY$)=>{Object.defineProperty(yY$,"__esModule",{value:!0});yY$.PushConsumerImpl=yY$.PushConsumerMessagesImpl=void 0;var DN4=w$1(),fY$=KT(),j$1=eP(),HY=VG(),wN4=VB();class E$1 extends HY.QueuedIteratorImpl{consumer;sub;monitor;listeners;abortOnMissingResource;callback;ordered;cursor;namePrefix;deliverPrefix;serial;createFails;statusIterator;cancelables;constructor($,Z={},Q={}){super();if(this.consumer=$,this.monitor=null,this.listeners=[],this.cancelables=[],this.abortOnMissingResource=Z.abort_on_missing_resource===!0,this.callback=Z.callback||null,this.noIterator=this.callback!==null,this.namePrefix=null,this.deliverPrefix=null,this.ordered=Q.ordered===!0,this.serial=1,this.ordered){this.namePrefix=Q.name_prefix??`oc_${HY.nuid.next()}`,this.deliverPrefix=Q.deliver_prefix??(0,HY.createInbox)(this.consumer.api.nc.options.inboxPrefix),this.cursor={stream_seq:1,deliver_seq:0};let X=$._info.config.opt_start_seq||0;this.cursor.stream_seq=X>0?X-1:0,this.createFails=0}this.start()}reset(){let{name:$}=this.consumer._info?.config;if($)this.consumer.api.delete(this.consumer.stream,$).catch(()=>{});let Z=this.getConsumerOpts();this.cursor.deliver_seq=0,this.consumer.name=Z.name,this.consumer.serial=this.serial,this.consumer.api.nc._resub(this.sub,Z.deliver_subject),this.consumer.api.add(this.consumer.stream,Z).then((Q)=>{this.createFails=0,this.consumer._info=Q,this.notify({type:"ordered_consumer_recreated",name:Q.name})}).catch((Q)=>{if(this.createFails++,Q.message==="stream not found"){if(this.notify({type:"stream_not_found",name:this.consumer.stream,consumerCreateFails:this.createFails}),this.abortOnMissingResource){this.stop(Q);return}}if(this.createFails>=30&&this.received===0)this.stop(Q);let X=(0,HY.backoff)(),Y=(0,HY.delay)(X.backoff(this.createFails));Y.then(()=>{if(!this.done)this.reset()}).catch(()=>{}).finally(()=>{let J=this.cancelables.indexOf(Y);if(J!==-1)this.cancelables=this.cancelables.splice(J,J)}),this.cancelables.push(Y)})}getConsumerOpts(){let $=Object.assign({},this.consumer._info.config);this.serial++;let Z=`${this.namePrefix}_${this.serial}`;return Object.assign($,{name:Z,deliver_policy:fY$.DeliverPolicy.StartSequence,opt_start_seq:this.cursor.stream_seq+1,ack_policy:fY$.AckPolicy.None,inactive_threshold:(0,HY.nanos)(300000),num_replicas:1,flow_control:!0,idle_heartbeat:(0,HY.nanos)(30000),deliver_subject:`${this.deliverPrefix}.${this.serial}`})}closed(){return this.iterClosed}close(){return this.stop(),this.iterClosed}stop($){if(this.done)return;this.statusIterator?.stop(),this.monitor?.cancel(),this.monitor=null,this.cancelables.forEach((Z)=>{Z.cancel()}),Promise.all(this.cancelables).then(()=>{this.cancelables=[]}).catch(()=>{}).finally(()=>{this._push(()=>{super.stop($),this.listeners.forEach((Z)=>{Z.stop()})})})}_push($){if(!this.callback)super.push($);else{let Z=typeof $==="function"?$:null;try{if(!Z){let Q=$;this.received++,this.callback(Q),this.processed++}else Z()}catch(Q){this.stop(Q)}}}status(){let $=new HY.QueuedIteratorImpl;return this.listeners.push($),$}start(){let{deliver_subject:$,deliver_group:Z,idle_heartbeat:Q}=this.consumer._info.config;if(!$)throw Error("bad consumer info");if(Q){let X=(0,HY.millis)(Q);this.monitor=new HY.IdleHeartbeatMonitor(X,(Y)=>{if(this.notify({type:"heartbeats_missed",count:Y}),this.ordered)this.reset();return!1},{maxOut:2}),(async()=>{this.statusIterator=this.consumer.api.nc.status();for await(let Y of this.statusIterator)switch(Y.type){case"disconnect":this.monitor?.cancel();break;case"reconnect":this.monitor?.restart();break;default:}})()}this.sub=this.consumer.api.nc.subscribe($,{queue:Z,callback:(X,Y)=>{if(X){this.stop(X);return}if(this.monitor?.work(),this.ordered?Y.subject.indexOf(this?.deliverPrefix)===0:Y.subject===$){if(Y.subject!==this.sub.getSubject())return;let G=new wN4.JetStreamStatus(Y);if(G.isFlowControlRequest()){this._push(()=>{Y.respond(),this.notify({type:"flow_control"})});return}if(G.isIdleHeartbeat()){let H=parseInt(Y.headers?.get(j$1.JsHeaders.LastConsumerSeqHdr)||"0"),F=parseInt(Y.headers?.get(j$1.JsHeaders.LastStreamSeqHdr)??"0");this.notify({type:"heartbeat",lastStreamSequence:F,lastConsumerSequence:H});let U=Y.headers?.get(j$1.JsHeaders.ConsumerStalledHdr);if(typeof U==="string"&&U!=="")Y.publisher.publish(U,HY.Empty);return}let{code:K,description:W}=G;if(G.isConsumerDeleted())this.notify({type:"consumer_deleted",code:K,description:W});if(this.abortOnMissingResource){this._push(()=>{this.stop(G.toError())});return}}else{let G=(0,DN4.toJsMsg)(Y);if(this.ordered){let K=G.info.deliverySequence;if(K!==this.cursor.deliver_seq+1){this.reset();return}this.cursor.deliver_seq=K,this.cursor.stream_seq=G.info.streamSequence}this._push(G)}}}),this.sub.closed.then(()=>{this._push(()=>{this.stop()})}),this.closed().then(()=>{this.sub?.unsubscribe()})}notify($){if(this.listeners.length>0)(()=>{this.listeners.forEach((Z)=>{let Q=Z;if(!Q.done)Q.push($)})})()}}yY$.PushConsumerMessagesImpl=E$1;class bY${api;_info;stream;name;bound;ordered;started;serial;opts;constructor($,Z,Q={}){if(this.api=$,this._info=Z,this.stream=Z.stream_name,this.name=Z.name,this.bound=Q.bound===!0,this.started=!1,this.opts=Q,this.serial=0,this.ordered=Q.ordered||!1,this.ordered)this.serial=1}consume($={}){if($={...$},this.started)return Promise.reject(new HY.errors.InvalidOperationError("consumer already started"));if(!this._info.config.deliver_subject)return Promise.reject(Error("deliver_subject is not set, not a push consumer"));if(!this._info.config.deliver_group&&this._info.push_bound)return Promise.reject(new HY.errors.InvalidOperationError("consumer is already bound"));let Z=new E$1(this,$,this.opts);return this.started=!0,Z.closed().then(()=>{this.started=!1}),Promise.resolve(Z)}delete(){if(this.bound)return Promise.reject(new HY.errors.InvalidOperationError("bound consumers cannot delete"));let{stream_name:$,name:Z}=this._info;return this.api.delete($,Z)}async info($){if(this.bound)return Promise.reject(new HY.errors.InvalidOperationError("bound consumers cannot info"));if($)return Promise.resolve(this._info);let Z=await this.api.info(this.stream,this.name);return this._info=Z,Z}isPullConsumer(){return!1}isPushConsumer(){return!0}}yY$.PushConsumerImpl=bY$});var pY$=b((dY$)=>{Object.defineProperty(dY$,"__esModule",{value:!0});dY$.StreamsImpl=dY$.StoredMsgImpl=dY$.StreamAPIImpl=dY$.StreamImpl=dY$.ConsumersImpl=void 0;dY$.convertStreamSourceDomain=rr;var TZ=VG(),EN4=Fl(),uY$=v30(),cW=Ul(),lY$=eP(),kG=KT(),z$1=xY$(),P$1=L$1(),T$1=hY$(),cY$=VB();function rr($){if($===void 0)return;let{domain:Z}=$;if(Z===void 0)return $;let Q=Object.assign({},$);if(delete Q.domain,Z==="")return Q;if(Q.external)throw TZ.InvalidArgumentError.format(["domain","external"],"are mutually exclusive");return Q.external={api:`$JS.${Z}.API`},Q}class b30{api;notified;constructor($){this.api=$,this.notified=!1}checkVersion(){let $=this.api.nc.features.get(TZ.Feature.JS_SIMPLIFICATION);if(!$.ok)return Promise.reject(Error(`consumers framework is only supported on servers ${$.min} or better`));return Promise.resolve()}async getPushConsumer($,Z){if(await this.checkVersion(),(0,cW.minValidation)("stream",$),typeof Z==="string"){(0,cW.minValidation)("name",Z);let Q=await this.api.info($,Z);if(typeof Q.config.deliver_subject!=="string")return Promise.reject(Error("not a push consumer"));return new T$1.PushConsumerImpl(this.api,Q)}else if(Z===void 0)return this.getOrderedPushConsumer($);else if((0,lY$.isOrderedPushConsumerOptions)(Z)){let Q=Z;return this.getOrderedPushConsumer($,Q)}return Promise.reject(Error("unsupported push consumer type"))}async getOrderedPushConsumer($,Z={}){Z=Object.assign({},Z);let{name_prefix:Q,deliver_prefix:X,filter_subjects:Y}=Z;if(delete Z.deliver_prefix,delete Z.name_prefix,delete Z.filter_subjects,typeof Z.opt_start_seq==="number")Z.deliver_policy=kG.DeliverPolicy.StartSequence;if(typeof Z.opt_start_time==="string")Z.deliver_policy=kG.DeliverPolicy.StartTime;Q=Q||`oc_${TZ.nuid.next()}`,(0,cW.minValidation)("name_prefix",Q),X=X||(0,TZ.createInbox)(this.api.getOptions().watcherPrefix);let J=Object.assign({},Z);if(J.ack_policy=kG.AckPolicy.None,J.inactive_threshold=(0,TZ.nanos)(300000),J.num_replicas=1,J.max_deliver=1,J.flow_control=!0,J.idle_heartbeat=(0,TZ.nanos)(30000),Array.isArray(Y))J.filter_subjects=Y;if(typeof Y==="string")J.filter_subject=Y;if(typeof J.filter_subjects>"u"&&typeof J.filter_subject>"u")J.filter_subject=">";J.name=`${Q}_1`,J.deliver_subject=`${X}.1`;let G=await this.api.add($,J),K={name_prefix:Q,deliver_prefix:X,ordered:!0};return new T$1.PushConsumerImpl(this.api,G,K)}getBoundPushConsumer($){if((0,lY$.isBoundPushConsumerOptions)($)){let Z={config:$};return Promise.resolve(new T$1.PushConsumerImpl(this.api,Z,{bound:!0}))}else return Promise.reject(TZ.errors.InvalidArgumentError.format("deliver_subject","is required"))}async get($,Z){if(await this.checkVersion(),typeof Z==="string"){let Q=await this.api.info($,Z);if(typeof Q.config.deliver_subject==="string")return Promise.reject(Error("not a pull consumer"));else return new z$1.PullConsumerImpl(this.api,Q)}else return this.ordered($,Z)}getConsumerFromInfo($){if(typeof $.config.deliver_subject==="string")throw Error("not a pull consumer");return new z$1.PullConsumerImpl(this.api,$)}async ordered($,Z={}){await this.checkVersion();let Q=this.api;if(await new A$1(Q.nc,Q.opts).info($),typeof Z.name_prefix==="string")(0,cW.minValidation)("name_prefix",Z.name_prefix);Z.name_prefix=Z.name_prefix||TZ.nuid.next();let J={name:`${Z.name_prefix}_1`,deliver_policy:kG.DeliverPolicy.StartSequence,opt_start_seq:Z.opt_start_seq||1,ack_policy:kG.AckPolicy.None,inactive_threshold:(0,TZ.nanos)(300000),num_replicas:1,max_deliver:1,mem_storage:!0};if(Z.headers_only===!0)J.headers_only=!0;if(Array.isArray(Z.filter_subjects))J.filter_subjects=Z.filter_subjects;if(typeof Z.filter_subjects==="string")J.filter_subject=Z.filter_subjects;if(Z.replay_policy)J.replay_policy=Z.replay_policy;if(J.deliver_policy=Z.deliver_policy||kG.DeliverPolicy.StartSequence,Z.deliver_policy===kG.DeliverPolicy.All||Z.deliver_policy===kG.DeliverPolicy.LastPerSubject||Z.deliver_policy===kG.DeliverPolicy.New||Z.deliver_policy===kG.DeliverPolicy.Last)delete J.opt_start_seq,J.deliver_policy=Z.deliver_policy;if(J.deliver_policy===kG.DeliverPolicy.LastPerSubject){if(typeof J.filter_subjects>"u"&&typeof J.filter_subject>"u")J.filter_subject=">"}if(Z.opt_start_time)delete J.opt_start_seq,J.deliver_policy=kG.DeliverPolicy.StartTime,J.opt_start_time=Z.opt_start_time;if(Z.inactive_threshold)J.inactive_threshold=(0,TZ.nanos)(Z.inactive_threshold);let G=await this.api.add($,J);return Promise.resolve(new z$1.PullConsumerImpl(this.api,G,Z))}}dY$.ConsumersImpl=b30;class ar{api;_info;constructor($,Z){this.api=$,this._info=Z}get name(){return this._info.config.name}alternates(){return this.info().then(($)=>{return $.alternates?$.alternates:[]})}async best(){if(await this.info(),this._info.alternates){let $=await this.api.info(this._info.alternates[0].name);return new ar(this.api,$)}else return this}info($=!1,Z){if($)return Promise.resolve(this._info);return this.api.info(this.name,Z).then((Q)=>{return this._info=Q,this._info})}getConsumer($){return new b30(new P$1.ConsumerAPIImpl(this.api.nc,this.api.opts)).get(this.name,$)}getPushConsumer($){return new b30(new P$1.ConsumerAPIImpl(this.api.nc,this.api.opts)).getPushConsumer(this.name,$)}getMessage($){return this.api.getMessage(this.name,$)}deleteMessage($,Z=!0){return this.api.deleteMessage(this.name,$,Z)}resetConsumer($,Z){return new P$1.ConsumerAPIImpl(this.api.nc,this.api.opts).reset(this.name,$,Z)}}dY$.StreamImpl=ar;class A$1 extends EN4.BaseApiClientImpl{constructor($,Z){super($,Z)}checkStreamConfigVersions($){let Z=this.nc;if($.metadata){let{min:X,ok:Y}=Z.features.get(TZ.Feature.JS_STREAM_CONSUMER_METADATA);if(!Y)throw Error(`stream 'metadata' requires server ${X}`)}if($.first_seq){let{min:X,ok:Y}=Z.features.get(TZ.Feature.JS_STREAM_FIRST_SEQ);if(!Y)throw Error(`stream 'first_seq' requires server ${X}`)}if($.subject_transform){let{min:X,ok:Y}=Z.features.get(TZ.Feature.JS_STREAM_SUBJECT_TRANSFORM);if(!Y)throw Error(`stream 'subject_transform' requires server ${X}`)}if($.compression){let{min:X,ok:Y}=Z.features.get(TZ.Feature.JS_STREAM_COMPRESSION);if(!Y)throw Error(`stream 'compression' requires server ${X}`)}if($.consumer_limits){let{min:X,ok:Y}=Z.features.get(TZ.Feature.JS_DEFAULT_CONSUMER_LIMITS);if(!Y)throw Error(`stream 'consumer_limits' requires server ${X}`)}function Q(X,Y){if((Y?.subject_transforms?.length||0)>0){let{min:G,ok:K}=Z.features.get(TZ.Feature.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!K)throw Error(`${X} 'subject_transforms' requires server ${G}`)}}if($.sources)$.sources.forEach((X)=>{Q("stream sources",X)});if($.mirror)Q("stream mirror",$.mirror)}minStreamApi($){if($.allow_batched===!0||$.mirror?.consumer||$.sources?.some((Z)=>Z.consumer))return 4;if($.allow_msg_counter===!0||$.allow_atomic===!0||$.allow_msg_schedules===!0||$.persist_mode===kG.PersistMode.Async)return 2;if($.allow_msg_ttl===!0||typeof $.subject_delete_marker_ttl==="number"&&$.subject_delete_marker_ttl>0)return 1;return 0}requiredApiOpts($){if(!this.sendRequiredApiLevel())return{};let Z=this.minStreamApi($);return Z>0?{minApiVersion:Z}:{}}async add($){this.checkStreamConfigVersions($),(0,cW.validateStreamName)($.name),$.mirror=rr($.mirror),$.sources=$.sources?.map(rr);let Q=await this._request(`${this.prefix}.STREAM.CREATE.${$.name}`,$,this.requiredApiOpts($));return this._fixInfo(Q),Q}async delete($){return(0,cW.validateStreamName)($),(await this._request(`${this.prefix}.STREAM.DELETE.${$}`)).success}async update($,Z={}){if(typeof $==="object"){let G=$;$=G.name,Z=G,console.trace("\x1B[33m >> streams.update(config: StreamConfig) api changed to streams.update(name: string, config: StreamUpdateConfig) - this shim will be removed - update your code. \x1B[0m")}this.checkStreamConfigVersions(Z),(0,cW.validateStreamName)($);let Q=await this.info($),X=Object.assign(Q.config,Z);X.mirror=rr(X.mirror),X.sources=X.sources?.map(rr);let J=await this._request(`${this.prefix}.STREAM.UPDATE.${$}`,X,this.requiredApiOpts(Z));return this._fixInfo(J),J}async info($,Z){(0,cW.validateStreamName)($);let Q=`${this.prefix}.STREAM.INFO.${$}`,Y=await this._request(Q,Z),{total:J,limit:G}=Y,K=Y.state.subjects?Object.getOwnPropertyNames(Y.state.subjects).length:1;if(J&&J>K){let W=[Y],H=Z||{},F=0;while(J>K){F++,H.offset=G*F;let N=await this._request(Q,H);J=N.total,W.push(N);let B=Object.getOwnPropertyNames(N.state.subjects).length;if(K+=B,B<G)break}let U={};for(let N=0;N<W.length;N++)if(Y=W[N],Y.state.subjects)U=Object.assign(U,Y.state.subjects);Y.offset=0,Y.total=0,Y.limit=0,Y.state.subjects=U}return this._fixInfo(Y),Y}list($=""){let Z=$?.length?{subject:$}:{},Q=(Y)=>{let J=Y;return J.streams.forEach((G)=>{this._fixInfo(G)}),J.streams},X=`${this.prefix}.STREAM.LIST`;return new uY$.ListerImpl(X,Q,this,Z)}_fixInfo($){$.config.sealed=$.config.sealed||!1,$.config.deny_delete=$.config.deny_delete||!1,$.config.deny_purge=$.config.deny_purge||!1,$.config.allow_rollup_hdrs=$.config.allow_rollup_hdrs||!1}async purge($,Z){if(Z){let{keep:X,seq:Y}=Z;if(typeof X==="number"&&typeof Y==="number")throw TZ.InvalidArgumentError.format(["keep","seq"],"are mutually exclusive")}return(0,cW.validateStreamName)($),await this._request(`${this.prefix}.STREAM.PURGE.${$}`,Z)}async deleteMessage($,Z,Q=!0){(0,cW.validateStreamName)($);let X={seq:Z};if(!Q)X.no_erase=!0;return(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${$}`,X)).success}async getMessage($,Z){(0,cW.validateStreamName)($);try{let X=await this._request(`${this.prefix}.STREAM.MSG.GET.${$}`,Z);return new R$1(X)}catch(Q){if(Q instanceof cY$.JetStreamApiError&&Q.code===cY$.JetStreamApiCodes.NoMessageFound)return null;return Promise.reject(Q)}}find($){return this.findStream($)}names($=""){let Z=$?.length?{subject:$}:{},Q=(Y)=>{return Y.streams},X=`${this.prefix}.STREAM.NAMES`;return new uY$.ListerImpl(X,Q,this,Z)}async get($){let Z=await this.info($);return Promise.resolve(new ar(this,Z))}}dY$.StreamAPIImpl=A$1;class R$1{_header;smr;static jc;constructor($){this.smr=$}get pending(){return 0}get lastSequence(){return 0}get subject(){return this.smr.message.subject}get seq(){return this.smr.message.seq}get timestamp(){return this.smr.message.time}get time(){return new Date(Date.parse(this.timestamp))}get data(){return this.smr.message.data?this._parse(this.smr.message.data):TZ.Empty}get header(){if(!this._header)if(this.smr.message.hdrs){let $=this._parse(this.smr.message.hdrs);this._header=TZ.MsgHdrsImpl.decode($)}else this._header=(0,TZ.headers)();return this._header}_parse($){let Z=atob($),Q=Z.length,X=new Uint8Array(Q);for(let Y=0;Y<Q;Y++)X[Y]=Z.charCodeAt(Y);return X}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return TZ.TD.decode(this.data)}}dY$.StoredMsgImpl=R$1;class mY${api;constructor($){this.api=$}get($){return this.api.info($).then((Z)=>{return new ar(this.api,Z)})}}dY$.StreamsImpl=mY$});var M$1=b((rY$)=>{Object.defineProperty(rY$,"__esModule",{value:!0});rY$.DirectConsumer=rY$.DirectMsgImpl=rY$.DirectStreamAPIImpl=void 0;var qN4=Fl(),Bl=eP(),mW=VG(),nY$=Ul(),q$1=VB();class tY$ extends qN4.BaseApiClientImpl{constructor($,Z){super($,Z)}async getMessage($,Z){if((0,nY$.validateStreamName)($),"start_time"in Z){let{min:H,ok:F}=this.nc.features.get(mW.Feature.JS_BATCH_DIRECT_GET);if(!F)throw Error(`start_time direct option require server ${H}`)}let Q=Z,{last_by_subj:X}=Q;if(X)Q=null;let Y=Q?JSON.stringify(Q):mW.Empty,J=this.opts.apiPrefix||"$JS.API",G=X?`${J}.DIRECT.GET.${$}.${X}`:`${J}.DIRECT.GET.${$}`,K=await this.nc.request(G,Y,{timeout:this.timeout});if(K.headers?.code!==0){let H=new q$1.JetStreamStatus(K);if(H.isMessageNotFound())return Promise.resolve(null);else return Promise.reject(H.toError())}let W=new y30(K);return Promise.resolve(W)}getBatch($,Z){return Z.batch=Z.batch||1024,this.get($,Z)}getLastMessagesFor($,Z){return this.get($,Z)}get($,Z){Z={...Z};let{min:Q,ok:X}=this.nc.features.get(mW.Feature.JS_BATCH_DIRECT_GET);if(!X)return Promise.reject(Error(`batch direct require server ${Q}`));(0,nY$.validateStreamName)($);let Y=typeof Z.callback==="function"?Z.callback:null,J=new mW.QueuedIteratorImpl;function G(D,w){if(D){J.push(()=>{D.err?J.stop(D.err):J.stop()});return}J.push(w)}function K(D,w){let j=Y;if(typeof w==="function"){w();return}j(D,w)}if(Y)J.iterClosed.then((D)=>{W({err:D?D:void 0},{}),U.unsubscribe()});let W=Y?K:G,H=(0,mW.createInbox)(this.nc.options.inboxPrefix),F=!1,U=this.nc.subscribe(H,{timeout:5000,callback:(D,w)=>{if(D){J.stop(D),U.unsubscribe();return}let j=q$1.JetStreamStatus.maybeParseStatus(w);if(j){if(j.isNoResults())W({},()=>{J.stop()});if(j.isEndOfBatch())W({},()=>{J.stop()});else{let E=j.toError();W({err:E},()=>{J.stop(E)})}return}if(!F)if(typeof w.headers?.get("Nats-Num-Pending")!=="string")U.unsubscribe(),W({},()=>{J.stop()});else F=!0;W(null,new y30(w))}}),B=`${this.opts.apiPrefix||"$JS.API"}.DIRECT.GET.${$}`,O=JSON.stringify(Z,(D,w)=>{if((D==="up_to_time"||D==="start_time")&&w instanceof Date)return w.toISOString();return w});return this.nc.publish(B,O,{reply:H}),Promise.resolve(J)}}rY$.DirectStreamAPIImpl=tY$;class y30{data;header;constructor($){if(!$.headers)throw Error("headers expected");this.data=$.data,this.header=$.headers}get subject(){return this.header.last(Bl.DirectMsgHeaders.Subject)}get seq(){let $=this.header.last(Bl.DirectMsgHeaders.Sequence);return typeof $==="string"?parseInt($):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(Bl.DirectMsgHeaders.TimeStamp)}get stream(){return this.header.last(Bl.DirectMsgHeaders.Stream)}get lastSequence(){let $=this.header.last(Bl.DirectMsgHeaders.LastSequence);return typeof $==="string"?parseInt($):0}get pending(){let $=this.header.last(Bl.DirectMsgHeaders.NumPending);return typeof $==="string"?parseInt($):-1}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return mW.TD.decode(this.data)}}rY$.DirectMsgImpl=y30;function MN4($){return typeof $==="object"&&"start_time"in $}function IN4($){return typeof $==="object"&&"max_bytes"in $}class oY${stream;api;cursor;listeners;start;constructor($,Z,Q){this.stream=$,this.api=Z,this.cursor={last:0},this.listeners=[],this.start=Q}getOptions($){$=$||{};let Z={};if(this.cursor.last===0)if(MN4(this.start))Z.start_time=this.start.start_time;else Z.seq=this.start.seq||1;else Z.seq=this.cursor.last+1;if(IN4($))Z.max_bytes=$.max_bytes;else Z.batch=$.batch??100;return Z}status(){let $=new mW.QueuedIteratorImpl;return this.listeners.push($),$}notify($){if(this.listeners.length>0)(()=>{let Z=[];this.listeners.forEach((Q)=>{let X=Q;if(!X.done)X.push($);else Z.push(X)}),this.listeners=this.listeners.filter((Q)=>!Z.includes(Q))})()}debug(){console.log(this.cursor)}consume($){let Z,Q,X=new mW.QueuedIteratorImpl;return(async()=>{while(!0){if(this.cursor.pending===0)this.notify({type:"debug",code:0,description:"sleeping for 2500"}),Z=(0,mW.delay)(2500),await Z;if(X.done)break;Q=(0,mW.deferred)();let Y=this.getOptions($);this.notify({type:"next",options:Object.assign({},$)}),Y.callback=(G,K)=>{if(G){if(G.err)if(G.err instanceof q$1.JetStreamStatusError)this.notify({type:"debug",code:G.err.code,description:G.err.message});else this.notify({type:"debug",code:0,description:G.err.message});Q.resolve()}else if(K.lastSequence>0&&K.lastSequence!==this.cursor.last)J.stop(),Q.resolve(),this.notify({type:"reset",name:"direct"});else X.push(K),X.received++,this.cursor.last=K.seq,this.cursor.pending=K.pending};let J=await this.api.getBatch(this.stream,Y);X.iterClosed.then(()=>{J.stop(),Z?.cancel(),Q?.resolve()}),await Q}})().catch((Y)=>{X.stop(Y)}),Promise.resolve(X)}async fetch($){let Z=this.getOptions($),Q=new mW.QueuedIteratorImpl,X=await this.api.get(this.stream,Object.assign({callback:(Y,J)=>{if(Y)Q.push(()=>{Y.err?Q.stop(Y.err):Q.stop()});else if(J.lastSequence>0&&J.lastSequence!==this.cursor.last)Q.push(()=>{Q.stop()}),X.stop();else Q.push(J),Q.received++,this.cursor.last=J.seq,this.cursor.pending=J.pending}},Z));return Q.iterClosed.then(()=>{X.stop()}),Q}async next(){let $=await this.api.getMessage(this.stream,{seq:this.cursor.last+1}),Z=$?.seq;if(Z)this.cursor.last=Z;return $}}rY$.DirectConsumer=oY$});var JJ$=b((XJ$)=>{Object.defineProperty(XJ$,"__esModule",{value:!0});XJ$.BatchPublisherImpl=XJ$.JetStreamClientImpl=XJ$.JetStreamManagerImpl=void 0;XJ$.startFastIngest=CN4;XJ$.toJetStreamClient=_N4;XJ$.jetstream=V$1;XJ$.jetstreamManager=$J$;XJ$.scheduleSpecToHeader=ZJ$;var I$1=Fl(),eY$=L$1(),g5=VG(),g30=pY$(),FY=KT(),sY$=VB(),SN4=M$1();function CN4($,Z,Q,X,Y=5000){let{ackInterval:J,allowGaps:G,inboxPrefix:K,maxOutstandingAcks:W,...H}=X,F=K??"_INBOX";if(!F||/\s/.test(F)||/[*>]/.test(F))return Promise.reject(Error(`inboxPrefix must be non-empty, no wildcards or whitespace (got "${F}")`));let U={ackInterval:J??10,allowGaps:G,inboxPrefix:F,maxOutstandingAcks:Math.min(3,Math.max(1,W??2))},N=new QJ$($,U,Z,Y);return N.start(Q,H).then(()=>N)}function er($){let Z=$.expect||{},Q=$.headers||(0,g5.headers)();if($.msgID)Q.set(FY.PubHeaders.MsgIdHdr,$.msgID);if(Z.lastMsgID)Q.set(FY.PubHeaders.ExpectedLastMsgIdHdr,Z.lastMsgID);if(Z.streamName)Q.set(FY.PubHeaders.ExpectedStreamHdr,Z.streamName);if(typeof Z.lastSequence==="number")Q.set(FY.PubHeaders.ExpectedLastSeqHdr,`${Z.lastSequence}`);if(typeof Z.lastSubjectSequence==="number")Q.set(FY.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Z.lastSubjectSequence}`);if(Z.lastSubjectSequenceSubject)Q.set(FY.PubHeaders.ExpectedLastSubjectSequenceSubjectHdr,Z.lastSubjectSequenceSubject);if($.ttl)Q.set(FY.PubHeaders.MessageTTL,`${$.ttl}`);if($.schedule&&$.cancelSchedule)throw Error("schedule and cancelSchedule are mutually exclusive");if($.schedule){let X=$.schedule;if(X.specification)Q.set(FY.PubHeaders.Schedule,ZJ$(X.specification));if(X.target)Q.set(FY.PubHeaders.ScheduleTarget,X.target);if(X.source)Q.set(FY.PubHeaders.ScheduleSource,X.source);if(X.ttl)Q.set(FY.PubHeaders.ScheduleTTL,X.ttl);if(X.timezone)Q.set(FY.PubHeaders.ScheduleTimeZone,X.timezone);if(X.rollup)Q.set(FY.PubHeaders.ScheduleRollup,X.rollup)}if($.cancelSchedule)Q.set(FY.PubHeaders.Scheduler,$.cancelSchedule.scheduleSubject),Q.set(FY.PubHeaders.ScheduleNext,"purge");return Q}function _N4($){if(typeof $.nc>"u")return V$1($);return $}function V$1($,Z={}){return new S$1($,Z)}async function $J$($,Z={}){let Q=new k$1($,Z);if(Z.checkAPI!==!1)try{await Q.getAccountInfo()}catch(X){throw X}return Q}class k$1 extends I$1.BaseApiClientImpl{streams;consumers;direct;constructor($,Z){super($,Z);this.streams=new g30.StreamAPIImpl($,Z),this.consumers=new eY$.ConsumerAPIImpl($,Z),this.direct=new SN4.DirectStreamAPIImpl($,Z)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return V$1(this.nc,this.getOptions())}advisories(){let $=new g5.QueuedIteratorImpl;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(Z,Q)=>{if(Z)throw Z;try{let X=this.parseJsResponse(Q),Y=X.type.split("."),J=Y[Y.length-1];$.push({kind:J,data:X})}catch(X){$.stop(X)}}}),$}}XJ$.JetStreamManagerImpl=k$1;function ZJ$($){if(typeof $==="string")return $;if($ instanceof Date)return`@at ${$.toISOString()}`;if("at"in $)return`@at ${$.at instanceof Date?$.at.toISOString():$.at}`;if("every"in $)return vN4($.every),`@every ${$.every}`;if("cron"in $)return $.cron;if("predefined"in $)return $.predefined;throw Error("invalid schedule specification")}function vN4($){let Z=$.trim(),Q=/(\d+(?:\.\d+)?)(ns|us|\u00B5s|ms|s|m|h)/g,X=0,Y=0,J;while((J=Q.exec(Z))!==null){if(J.index!==Y)break;Y+=J[0].length;let G=parseFloat(J[1]),K=J[2];X+=K==="ns"?G/1e6:K==="us"||K==="\xB5s"?G/1000:K==="ms"?G:K==="s"?G*1000:K==="m"?G*60000:G*3600000}if(Z===""||Y!==Z.length)throw Error(`@every: unrecognized duration format: "${$}"`);if(X<1000)throw Error("@every interval must be at least 1s")}class S$1 extends I$1.BaseApiClientImpl{consumers;streams;consumerAPI;streamAPI;constructor($,Z){super($,Z);this.consumerAPI=new eY$.ConsumerAPIImpl($,Z),this.streamAPI=new g30.StreamAPIImpl($,Z),this.consumers=new g30.ConsumersImpl(this.consumerAPI),this.streams=new g30.StreamsImpl(this.streamAPI)}jetstreamManager($){if($===void 0)$=this.opts.checkAPI;let Z=Object.assign({},this.opts,{checkAPI:$});try{(0,g5.createInbox)(Z.watcherPrefix)}catch(Q){return Promise.reject(Q)}return $J$(this.nc,Z)}get apiPrefix(){return this.prefix}startBatch($,Z,Q){let X=(0,g5.deferred)(),Y=new C$1(this);return Y.first($,Z,Q).then(()=>{X.resolve(Y)}).catch((J)=>{X.reject(J)}),X}async _publish($,Z=g5.Empty,Q){if(Q=Q||{},Q={...Q},Q.cancelSchedule&&Q.cancelSchedule.scheduleSubject===$)throw Error("cancelSchedule.scheduleSubject must not equal the publish subject");let X=er(Q),Y=Q.timeout||this.timeout,J={};if(Y)J.timeout=Y;if(Q)J.headers=X;let{retries:G}=Q;G=G||1;let K=(0,g5.backoff)(),W=null;for(let H=0;H<G;H++)try{W=await this.nc.request($,Z,J);break}catch(F){let U=F instanceof g5.RequestError?F:null;if((F instanceof g5.errors.TimeoutError||U?.isNoResponders())&&H+1<G)await(0,g5.delay)(K.backoff(H));else throw U?.isNoResponders()?new sY$.JetStreamNotEnabled("jetstream is not enabled",{cause:F}):F}return W}async publish($,Z=g5.Empty,Q){let X=await this._publish($,Z,Q),Y=this.parseJsResponse(X);if(Y.stream==="")throw new sY$.JetStreamError("invalid ack response");return Y.duplicate=Y.duplicate?Y.duplicate:!1,Y}}XJ$.JetStreamClientImpl=S$1;class C$1{nc;js;id;count;done;constructor($){this.count=0,this.id=g5.nuid.next(),this.js=$,this.nc=this.js.nc,this.done=!1}async first($,Z,Q){Q=Q||{},Q.headers=Q?.headers||(0,g5.headers)(),Q.headers.set("Nats-Batch-Id",this.id),this.count++,Q.headers.set("Nats-Batch-Sequence",this.count.toString());let X=await this.js._publish($,Z,Q);if(X.data.length>0)this.js.parseJsResponse(X)}add($,Z,Q={ack:!1}){if(this.done)throw Error("batch publisher is done");if(Q.headers=Q?.headers||(0,g5.headers)(),Q.headers.set("Nats-Batch-Id",this.id),this.count++,Q.headers.set("Nats-Batch-Sequence",this.count.toString()),"ack"in Q&&Q.ack===!0){let Y=(0,g5.deferred)();return this.js._publish($,Z,{headers:Q.headers,timeout:Q.timeout}).then((J)=>{if(J.data.length>0)this.js.parseJsResponse(J);Y.resolve()}).catch((J)=>{this.done=!0,Y.reject(J)}),Y}else return this.nc.publish($,Z,{headers:Q.headers})}async commit($,Z,Q={}){if(this.done)throw Error("batch publisher is done");else this.done=!0;Q.headers=Q?.headers||(0,g5.headers)(),Q.headers.set("Nats-Batch-Id",this.id),this.count++,Q.headers.set("Nats-Batch-Sequence",this.count.toString()),Q.headers.set("Nats-Batch-Commit","1");let Y=(await this.js._publish($,Z,{headers:Q.headers,timeout:Q.timeout||0})).json();if(Y.count!==this.count)throw Error("batch didn't contain number of published messages");return Y}}XJ$.BatchPublisherImpl=C$1;var sr="batch closed",AQ={Start:0,Append:1,Final:2,EOB:3,Ping:4};class QJ${batch;nc;batchSubj;gapMode;initialFlow;seq;acked;ackInterval;inboxPrefix;maxOutstandingAcks;defaultTimeout;gapIter;sub;pending;closed;closeErr;startDeferred;closedDeferred;constructor($,Z,Q,X){this.nc=$,this.batchSubj=Q,this.gapMode=Z.allowGaps?"ok":"fail",this.initialFlow=Z.ackInterval,this.inboxPrefix=Z.inboxPrefix,this.maxOutstandingAcks=Z.maxOutstandingAcks,this.defaultTimeout=X,this.batch=g5.nuid.next(),this.seq=0,this.acked=0,this.ackInterval=Z.ackInterval,this.pending=new Map,this.closed=!1,this.startDeferred=(0,g5.deferred)(),this.closedDeferred=(0,g5.deferred)(),this.closedDeferred.catch(()=>{}),this.startDeferred.catch(()=>{});let Y=`${this.inboxPrefix}.${this.batch}.>`;this.sub=this.nc.subscribe(Y,{callback:(J,G)=>this.route(J,G)})}replyFor($,Z){return`${this.inboxPrefix}.${this.batch}.${this.initialFlow}.${this.gapMode}.${Z}.${$}.$FI`}start($,Z){this.seq=1;let Q=this.replyFor(AQ.Start,1),X=Z?er(Z):void 0;return this.nc.publish(this.batchSubj,$,{reply:Q,headers:X}),this.deadlineOrClose(this.startDeferred,Z?.timeout??this.defaultTimeout)}deadlineOrClose($,Z){return(0,g5.deadline)($,Z).catch((Q)=>{if(!this.closed)this.close(Q);throw Q})}route($,Z){if($){this.close($);return}let Q;try{Q=(0,I$1.parseJsResponse)(Z)}catch(G){this.close(G);return}if("batch"in Q&&typeof Q.batch==="string"){let G=Q,K=this.pending.get(Z.subject);if(K&&(K.op===AQ.Final||K.op===AQ.EOB))K.deferred.resolve(G),this.pending.delete(Z.subject);for(let[,W]of this.pending)if(W.op===AQ.Append||W.op===AQ.Ping)W.deferred.resolve({batchSeq:W.seq,ackSeq:this.acked});else W.deferred.reject(Error(sr));this.pending.clear(),this.resolveStart(),this.closedDeferred.resolve(G),this.closed=!0,this.gapIter?.stop(),this.sub.unsubscribe();return}if(Q.type==="gap"){if(this.gapIter){let G=Q;this.gapIter.push({lastSeq:G.last_seq,seq:G.seq})}return}let Y=Q;if(typeof Y.msgs==="number")this.ackInterval=Y.msgs;if(typeof Y.seq==="number"&&Y.seq>this.acked)this.acked=Y.seq;this.resolveStart();let J=this.pending.get(Z.subject);if(J&&(J.op===AQ.Append||J.op===AQ.Ping))J.deferred.resolve({batchSeq:J.seq,ackSeq:this.acked}),this.pending.delete(Z.subject);for(let[G,K]of this.pending)if(K.op===AQ.Append&&K.seq-this.acked<this.ackInterval*this.maxOutstandingAcks)K.deferred.resolve({batchSeq:K.seq,ackSeq:this.acked}),this.pending.delete(G)}resolveStart(){this.startDeferred.resolve()}close($){this.closed=!0,this.closeErr=$;for(let[,Z]of this.pending)Z.deferred.reject($);this.pending.clear(),this.startDeferred.reject($),this.closedDeferred.reject($),this.gapIter?.stop(),this.sub.unsubscribe()}add($,Z,Q){if(this.closed)return Promise.reject(Error(sr));let X=++this.seq,Y=this.replyFor(AQ.Append,X),J=Q?er(Q):void 0;if(this.nc.publish($,Z,{reply:Y,headers:J}),X-this.acked<this.ackInterval*this.maxOutstandingAcks)return Promise.resolve({batchSeq:X,ackSeq:this.acked});let G=(0,g5.deferred)();return this.pending.set(Y,{seq:X,op:AQ.Append,deferred:G}),this.deadlineOrClose(G,Q?.timeout??this.defaultTimeout)}last($,Z,Q){if(this.closed)return Promise.reject(Error(sr));let X=++this.seq,Y=this.replyFor(AQ.Final,X),J=(0,g5.deferred)();this.pending.set(Y,{seq:X,op:AQ.Final,deferred:J});let G=Q?er(Q):void 0;return this.nc.publish($,Z,{reply:Y,headers:G}),this.deadlineOrClose(J,Q?.timeout??this.defaultTimeout)}end($){if(this.closed)return Promise.reject(Error(sr));let Z=++this.seq,Q=this.replyFor(AQ.EOB,Z),X=(0,g5.deferred)();this.pending.set(Q,{seq:Z,op:AQ.EOB,deferred:X});let Y=$?er($):void 0;return this.nc.publish(this.batchSubj,g5.Empty,{reply:Q,headers:Y}),this.deadlineOrClose(X,$?.timeout??this.defaultTimeout)}ping($=this.defaultTimeout){if(this.closed)return Promise.reject(Error(sr));let Z=this.replyFor(AQ.Ping,this.seq),Q=this.pending.get(Z);if(Q&&Q.op===AQ.Ping)return(0,g5.deadline)(Q.deferred,$);let X=(0,g5.deferred)();return this.pending.set(Z,{seq:this.seq,op:AQ.Ping,deferred:X}),this.nc.publish(this.batchSubj,g5.Empty,{reply:Z}),this.deadlineOrClose(X,$)}done(){return this.closedDeferred}gaps(){if(!this.gapIter)this.gapIter=new g5.QueuedIteratorImpl;return this.gapIter}}});var h30=b((s4)=>{Object.defineProperty(s4,"__esModule",{value:!0});s4.validateStreamName=s4.jserrors=s4.JetStreamStatusError=s4.JetStreamStatus=s4.JetStreamError=s4.JetStreamApiError=s4.JetStreamApiCodes=s4.isMessageNotFound=s4.ListerImpl=s4.StoreCompression=s4.StorageType=s4.RetentionPolicy=s4.ReplayPolicy=s4.PubHeaders=s4.PersistMode=s4.DiscardPolicy=s4.DeliverPolicy=s4.AckPolicy=s4.DirectMsgImpl=s4.BaseApiClientImpl=s4.toJetStreamClient=s4.startFastIngest=s4.jetstreamManager=s4.JetStreamClientImpl=s4.jetstream=s4.RepublishHeaders=s4.JsHeaders=s4.isPushConsumer=s4.isPullConsumer=s4.isOrderedPushConsumerOptions=s4.isBoundPushConsumerOptions=s4.DirectMsgHeaders=s4.AdvisoryKind=void 0;var nD=eP();Object.defineProperty(s4,"AdvisoryKind",{enumerable:!0,get:function(){return nD.AdvisoryKind}});Object.defineProperty(s4,"DirectMsgHeaders",{enumerable:!0,get:function(){return nD.DirectMsgHeaders}});Object.defineProperty(s4,"isBoundPushConsumerOptions",{enumerable:!0,get:function(){return nD.isBoundPushConsumerOptions}});Object.defineProperty(s4,"isOrderedPushConsumerOptions",{enumerable:!0,get:function(){return nD.isOrderedPushConsumerOptions}});Object.defineProperty(s4,"isPullConsumer",{enumerable:!0,get:function(){return nD.isPullConsumer}});Object.defineProperty(s4,"isPushConsumer",{enumerable:!0,get:function(){return nD.isPushConsumer}});Object.defineProperty(s4,"JsHeaders",{enumerable:!0,get:function(){return nD.JsHeaders}});Object.defineProperty(s4,"RepublishHeaders",{enumerable:!0,get:function(){return nD.RepublishHeaders}});var $a=JJ$();Object.defineProperty(s4,"jetstream",{enumerable:!0,get:function(){return $a.jetstream}});Object.defineProperty(s4,"JetStreamClientImpl",{enumerable:!0,get:function(){return $a.JetStreamClientImpl}});Object.defineProperty(s4,"jetstreamManager",{enumerable:!0,get:function(){return $a.jetstreamManager}});Object.defineProperty(s4,"startFastIngest",{enumerable:!0,get:function(){return $a.startFastIngest}});Object.defineProperty(s4,"toJetStreamClient",{enumerable:!0,get:function(){return $a.toJetStreamClient}});var lN4=Fl();Object.defineProperty(s4,"BaseApiClientImpl",{enumerable:!0,get:function(){return lN4.BaseApiClientImpl}});var cN4=M$1();Object.defineProperty(s4,"DirectMsgImpl",{enumerable:!0,get:function(){return cN4.DirectMsgImpl}});var CB=KT();Object.defineProperty(s4,"AckPolicy",{enumerable:!0,get:function(){return CB.AckPolicy}});Object.defineProperty(s4,"DeliverPolicy",{enumerable:!0,get:function(){return CB.DeliverPolicy}});Object.defineProperty(s4,"DiscardPolicy",{enumerable:!0,get:function(){return CB.DiscardPolicy}});Object.defineProperty(s4,"PersistMode",{enumerable:!0,get:function(){return CB.PersistMode}});Object.defineProperty(s4,"PubHeaders",{enumerable:!0,get:function(){return CB.PubHeaders}});Object.defineProperty(s4,"ReplayPolicy",{enumerable:!0,get:function(){return CB.ReplayPolicy}});Object.defineProperty(s4,"RetentionPolicy",{enumerable:!0,get:function(){return CB.RetentionPolicy}});Object.defineProperty(s4,"StorageType",{enumerable:!0,get:function(){return CB.StorageType}});Object.defineProperty(s4,"StoreCompression",{enumerable:!0,get:function(){return CB.StoreCompression}});var mN4=v30();Object.defineProperty(s4,"ListerImpl",{enumerable:!0,get:function(){return mN4.ListerImpl}});var HT=VB();Object.defineProperty(s4,"isMessageNotFound",{enumerable:!0,get:function(){return HT.isMessageNotFound}});Object.defineProperty(s4,"JetStreamApiCodes",{enumerable:!0,get:function(){return HT.JetStreamApiCodes}});Object.defineProperty(s4,"JetStreamApiError",{enumerable:!0,get:function(){return HT.JetStreamApiError}});Object.defineProperty(s4,"JetStreamError",{enumerable:!0,get:function(){return HT.JetStreamError}});Object.defineProperty(s4,"JetStreamStatus",{enumerable:!0,get:function(){return HT.JetStreamStatus}});Object.defineProperty(s4,"JetStreamStatusError",{enumerable:!0,get:function(){return HT.JetStreamStatusError}});Object.defineProperty(s4,"jserrors",{enumerable:!0,get:function(){return HT.jserrors}});var dN4=Ul();Object.defineProperty(s4,"validateStreamName",{enumerable:!0,get:function(){return dN4.validateStreamName}})});var _B=b((YZ)=>{Object.defineProperty(YZ,"__esModule",{value:!0});YZ.StoreCompression=YZ.StorageType=YZ.RetentionPolicy=YZ.RepublishHeaders=YZ.ReplayPolicy=YZ.PubHeaders=YZ.PersistMode=YZ.JsHeaders=YZ.JetStreamError=YZ.JetStreamApiError=YZ.JetStreamApiCodes=YZ.isPushConsumer=YZ.isPullConsumer=YZ.DiscardPolicy=YZ.DirectMsgHeaders=YZ.DeliverPolicy=YZ.AdvisoryKind=YZ.AckPolicy=YZ.jetstreamManager=YZ.jetstream=void 0;var GJ$=h30();Object.defineProperty(YZ,"jetstream",{enumerable:!0,get:function(){return GJ$.jetstream}});Object.defineProperty(YZ,"jetstreamManager",{enumerable:!0,get:function(){return GJ$.jetstreamManager}});var m7=h30();Object.defineProperty(YZ,"AckPolicy",{enumerable:!0,get:function(){return m7.AckPolicy}});Object.defineProperty(YZ,"AdvisoryKind",{enumerable:!0,get:function(){return m7.AdvisoryKind}});Object.defineProperty(YZ,"DeliverPolicy",{enumerable:!0,get:function(){return m7.DeliverPolicy}});Object.defineProperty(YZ,"DirectMsgHeaders",{enumerable:!0,get:function(){return m7.DirectMsgHeaders}});Object.defineProperty(YZ,"DiscardPolicy",{enumerable:!0,get:function(){return m7.DiscardPolicy}});Object.defineProperty(YZ,"isPullConsumer",{enumerable:!0,get:function(){return m7.isPullConsumer}});Object.defineProperty(YZ,"isPushConsumer",{enumerable:!0,get:function(){return m7.isPushConsumer}});Object.defineProperty(YZ,"JetStreamApiCodes",{enumerable:!0,get:function(){return m7.JetStreamApiCodes}});Object.defineProperty(YZ,"JetStreamApiError",{enumerable:!0,get:function(){return m7.JetStreamApiError}});Object.defineProperty(YZ,"JetStreamError",{enumerable:!0,get:function(){return m7.JetStreamError}});Object.defineProperty(YZ,"JsHeaders",{enumerable:!0,get:function(){return m7.JsHeaders}});Object.defineProperty(YZ,"PersistMode",{enumerable:!0,get:function(){return m7.PersistMode}});Object.defineProperty(YZ,"PubHeaders",{enumerable:!0,get:function(){return m7.PubHeaders}});Object.defineProperty(YZ,"ReplayPolicy",{enumerable:!0,get:function(){return m7.ReplayPolicy}});Object.defineProperty(YZ,"RepublishHeaders",{enumerable:!0,get:function(){return m7.RepublishHeaders}});Object.defineProperty(YZ,"RetentionPolicy",{enumerable:!0,get:function(){return m7.RetentionPolicy}});Object.defineProperty(YZ,"StorageType",{enumerable:!0,get:function(){return m7.StorageType}});Object.defineProperty(YZ,"StoreCompression",{enumerable:!0,get:function(){return m7.StoreCompression}})});import{mkdir as nN4,readdir as tN4,readFile as _$1,stat as u30,unlink as oN4,writeFile as rN4}from"fs/promises";import{createHmac as aN4}from"crypto";import{dirname as sN4,join as Za}from"path";function v$1($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return Za(eN4,Z)}function Ll($,Z){return Za(v$1($),r3(Z))}class QK{orgId;baseUrl;constructor($,Z){this.orgId=$;this.baseUrl=Z}async getBytesOrPresign($,Z){let Q=Ll(this.orgId,$),X=await u30(Q),Y=u7($);if(X.size>Z.presignWhenLargerThan)return{error:"FILE_TOO_LARGE",size:X.size,maxInlineSize:Z.presignWhenLargerThan,presignedUrl:await this.presignedGetUrl($),contentType:Y};let J=await _$1(Q),G=GG0(Y);return{content:G?new TextDecoder().decode(J):Buffer.from(J).toString("base64"),contentType:Y,encoding:G?"utf-8":"base64",size:X.size,lastModified:X.mtime}}async getBytes($){let Z=await _$1(Ll(this.orgId,$));return new Uint8Array(Z)}async put($,Z,Q){let X=Ll(this.orgId,$);return await nN4(sN4(X),{recursive:!0}),await rN4(X,typeof Z==="string"?Buffer.from(Z,"utf-8"):Z),{key:$}}async list($){let Z=$?.prefix?Za(v$1(this.orgId),r3($.prefix)):v$1(this.orgId),Q;try{Q=await tN4(Z,{withFileTypes:!0})}catch{return{objects:[],isTruncated:!1}}let X=$?.maxKeys??1000,Y=$?.prefix,J=Q.filter((K)=>K.isFile());if($?.delimiter){let K=[],W=Q.filter((O)=>O.isDirectory());for(let O of W){let D=Y?`${Y}/${O.name}/`:`${O.name}/`;K.push(D)}K.sort();let H=X,F=K.slice(0,H);H-=F.length;let U=J.slice(0,H),N=K.length+J.length;return{objects:await Promise.all(U.map(async(O)=>{let D=await u30(Za(Z,O.name));return{key:Y?`${Y}/${O.name}`:O.name,size:D.size,lastModified:D.mtime}})),isTruncated:N>X,commonPrefixes:F.length>0?F:void 0}}return{objects:await Promise.all(J.slice(0,X).map(async(K)=>{let W=await u30(Za(Z,K.name));return{key:Y?`${Y}/${K.name}`:K.name,size:W.size,lastModified:W.mtime}})),isTruncated:J.length>X}}async delete($){await oN4(Ll(this.orgId,$))}async head($){let Z=await u30(Ll(this.orgId,$));return{contentType:u7($),size:Z.size,lastModified:Z.mtime}}async presignedGetUrl($,Z,Q){if(Q?.requireFetchable)throw Error("object storage returned a not fetchable (data:) URL; configure real S3/R2/MinIO for large-payload offload");let X=Ll(this.orgId,$),Y=await _$1(X),J=u7($),G=Buffer.from(Y).toString("base64");return`data:${J};base64,${G}`}async presignedPutUrl($,Z=3600){if(!this.baseUrl)throw Error("baseUrl required for presigned PUT URLs in dev mode");let Q=r3($),X=Math.floor(Date.now()/1000)+Z,Y=P0().encryptionKey||"dev-secret",J=`${this.orgId}:${Q}:${X}:PUT`,G=aN4("sha256",Y).update(J).digest("hex"),K=new URL(`/api/dev-assets/${this.orgId}/${Q}`,this.baseUrl);return K.searchParams.set("expires",X.toString()),K.searchParams.set("signature",G),K.searchParams.set("method","PUT"),K.toString()}}var eN4="./data/assets";var Ol=L(()=>{CW();H$()});function bF($){return $B4.test($)&&$!=="."&&$!==".."}function N7($){if(!bF($))throw Error(`Invalid org-fs volume name: ${JSON.stringify($)}`)}function d7($){return r3($)}function Dl($){let Z=$.lastIndexOf("/");return Z===-1?"":$.slice(0,Z)}function tD($){let Z=Dl($);if(Z==="")return[];let Q=Z.split("/"),X=[],Y="";for(let J of Q)Y=Y===""?J:`${Y}/${J}`,X.push(Y);return X}function yF($,Z){return`${KJ$}/${$}/${Z}`}function l30($){return`${KJ$}/${$}/`}var $B4,KJ$="_fs";var FT=L(()=>{CW();$B4=/^[A-Za-z0-9_.-]{1,128}$/});import{createHmac as x$1,randomBytes as f$1,scrypt as ZB4,timingSafeEqual as WJ$}from"crypto";import{promisify as QB4}from"util";async function FJ$($){let Z=f$1(16),Q=await HJ$($,Z,XB4);return`scrypt$${Z.toString("hex")}$${Q.toString("hex")}`}async function UJ$($,Z){let Q=Z.split("$");if(Q.length!==3||Q[0]!=="scrypt")return!1;let X=Buffer.from(Q[1],"hex"),Y=Buffer.from(Q[2],"hex");if(X.length===0||Y.length===0)return!1;let J;try{J=await HJ$($,X,Y.length)}catch{return!1}return Y.length===J.length&&WJ$(Y,J)}function NJ$(){return f$1(16).toString("hex")}function BJ$(){if(c30)return c30;let $;try{let Z=P0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return c30=$?Buffer.from($):f$1(32),c30}function LJ$($){let Z=Buffer.from(JSON.stringify($)).toString("base64url"),Q=x$1("sha256",BJ$()).update(Z).digest("base64url");return`${Z}.${Q}`}function OJ$($,Z){let Q=$.indexOf(".");if(Q<0)return null;let X=$.slice(0,Q),Y=Buffer.from($.slice(Q+1)),J=Buffer.from(x$1("sha256",BJ$()).update(X).digest("base64url"));if(Y.length!==J.length||!WJ$(Y,J))return null;let G;try{G=JSON.parse(Buffer.from(X,"base64url").toString())}catch{return null}if(G.o!==Z.org||G.v!==Z.volume||G.s!==Z.secret||typeof G.e!=="number"||G.e<Z.nowSec)return null;return{govPath:G.p}}function b$1($,Z,Q){return`fsu_${x$1("sha256","fsunlock-name").update(`${$}:${Z}:${Q}`).digest("hex").slice(0,16)}`}var XB4=64,HJ$,c30=null;var y$1=L(()=>{H$();HJ$=QB4(ZB4)});import{createHash as YB4}from"crypto";function HB4($){if(typeof $!=="object"||$===null)return!1;let Z=$;return Z.name==="NoSuchKey"||Z.Code==="NoSuchKey"||Z.code==="ENOENT"||Z.$metadata?.httpStatusCode===404}function DJ$($){return YB4("sha256").update($).digest("hex")}class XK{storage;manifest;organizationId;maxFileBytes;volumeQuotaBytes;constructor($,Z,Q,X={}){this.storage=$;this.manifest=Z;this.organizationId=Q;this.maxFileBytes=X.maxFileBytes??KB4,this.volumeQuotaBytes=X.volumeQuotaBytes??WB4}async usage($){return N7($),this.manifest.usage(this.organizationId,$)}async stat($,Z){return N7($),this.manifest.get(this.organizationId,$,d7(Z))}async listVolumeFiles($){return N7($),this.manifest.listVolumeFiles(this.organizationId,$)}async listDir($,Z){return N7($),this.manifest.listDir(this.organizationId,$,d7(Z))}async read($,Z){let Q=await this.requireFile($,Z);try{return await this.storage.getBytes(yF($,Q.path))}catch(X){if(HB4(X))throw new UY(`No such file: ${Q.path}`);throw X}}async setShareMode($,Z,Q,X){N7($);let Y=d7(Z),J=await this.manifest.get(this.organizationId,$,Y);if(!J)throw new UY(`No such path: ${Y}`);let G=null,K=null;if(Q==="password"){if(!X.password)throw new SG("A password is required to set password mode");G=await FJ$(X.password),K=NJ$()}let W=await this.manifest.setShareMode({organizationId:this.organizationId,volume:$,path:J.path,readPublic:Q!=="private",passwordHash:G,shareSecret:K,actor:X.actor});if(!W)throw new UY(`No such path: ${J.path}`);return W}async setReadPublic($,Z,Q,X){return this.setShareMode($,Z,Q?"public":"private",{actor:X.actor})}async resolveReadAccess($,Z){N7($);let Q=d7(Z),X=await this.manifest.get(this.organizationId,$,Q);if(!X||X.kind!=="file")return{access:"private"};let Y=await this.manifest.resolveGoverningShare({organizationId:this.organizationId,volume:$,candidatePaths:[Q,...tD(Q)]});if(!Y)return{access:"private"};if(!Y.passwordHash)return{access:"public"};return{access:"password",govPath:Y.path,secret:Y.secret??"",passwordHash:Y.passwordHash}}async isPubliclyReadable($,Z){N7($);let Q=d7(Z),X=await this.manifest.get(this.organizationId,$,Q);if(!X||X.kind!=="file")return!1;if(X.readPublic)return!0;return this.manifest.hasPublicAncestorDir(this.organizationId,$,tD(Q))}async inheritsPublic($,Z){return N7($),this.manifest.hasPublicAncestorDir(this.organizationId,$,tD(d7(Z)))}async childrenInheritPublic($,Z){N7($);let Q=d7(Z);if(Q==="")return!1;return this.manifest.hasPublicAncestorDir(this.organizationId,$,[...tD(Q),Q])}async recentWithEffectivePublic($){return this.withEffectivePublic(await this.recent($))}async searchWithEffectivePublic($,Z,Q,X){return this.withEffectivePublic(await this.manifest.searchFiles({organizationId:this.organizationId,query:$,limit:Z,volumes:Q,pathPrefix:X?d7(X):void 0}))}async withEffectivePublic($){let Z=new Map;for(let X of $){let Y=Z.get(X.volume);if(!Y)Y=new Set,Z.set(X.volume,Y);for(let J of tD(X.path))Y.add(J)}let Q=new Map;return await Promise.all([...Z].map(async([X,Y])=>{let J=await this.manifest.publicDirPaths({organizationId:this.organizationId,volume:X,paths:[...Y]});Q.set(X,new Set(J))})),$.map((X)=>{let Y=Q.get(X.volume),J=!!Y&&tD(X.path).some((G)=>Y.has(G));return{...X,effectivePublic:X.readPublic||J}})}async presignRead($,Z,Q){let X=await this.requireFile($,Z);return this.storage.presignedGetUrl(yF($,X.path),Q)}async write($,Z,Q,X){N7($);let Y=d7(Z);if(Y==="")throw new SG("Cannot write to the volume root");let J=typeof Q==="string"?new TextEncoder().encode(Q):Q;if(J.byteLength>this.maxFileBytes)throw new UT(`File exceeds the ${this.maxFileBytes}-byte per-file limit`);let[G,K]=await Promise.all([X.skipVolumeQuota?Promise.resolve(null):this.manifest.usage(this.organizationId,$),this.manifest.get(this.organizationId,$,Y)]);if(K?.kind==="dir")throw new SG(`Cannot write a file at ${Y}: a directory exists there`);if(G){let W=K?.kind==="file"?K.size:0;if(G.bytes-W+J.byteLength>this.volumeQuotaBytes)throw new UT(`Write would exceed the volume quota of ${this.volumeQuotaBytes} bytes`)}await this.ensureDirs($,Y,X.actor),await this.storage.put(yF($,Y),J,{contentType:X.contentType??u7(Y)});try{return await u8(()=>this.manifest.putFile({organizationId:this.organizationId,volume:$,path:Y,parent:Dl(Y),contentHash:DJ$(J),size:J.byteLength,actor:X.actor,threadId:X.threadId??null}))}catch(W){throw console.error("org-fs manifest write lost after object put",{organizationId:this.organizationId,volume:$,path:Y,size:J.byteLength,error:W instanceof Error?W.message:String(W)}),W}}async mkdir($,Z,Q){N7($);let X=d7(Z);if(X==="")return;if((await this.manifest.get(this.organizationId,$,X))?.kind==="file")throw new SG(`Cannot create a directory at ${X}: a file exists there`);await this.ensureDirs($,X,Q.actor),await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:X,parent:Dl(X),actor:Q.actor})}async delete($,Z,Q){N7($);let X=d7(Z);if(X==="")throw new SG("Cannot delete the volume root");let Y=await this.manifest.get(this.organizationId,$,X);if(!Y)return;if(Y.kind==="dir"){let J=await this.manifest.listSubtreeFiles(this.organizationId,$,X);await Promise.all(J.map((G)=>this.storage.delete(yF($,G.path)))),await this.manifest.tombstoneSubtree(this.organizationId,$,X,Q.actor);return}await this.storage.delete(yF($,X)),await this.manifest.tombstone(this.organizationId,$,X,Q.actor)}async move($,Z,Q,X){N7($);let Y=d7(Z),J=d7(Q);if(Y===""||J==="")throw new SG("Cannot move the volume root");if(J===Y||J.startsWith(`${Y}/`))throw new SG(`Cannot move ${Y} onto itself or into its own subtree`);let G=await this.manifest.get(this.organizationId,$,Y);if(!G)throw new UY(`No such path: ${Y}`);if(G.kind==="file"){let H=await this.storage.getBytes(yF($,Y));await this.write($,J,H,{...X,skipVolumeQuota:!0}),await this.delete($,Y,X);return}let[K,W]=await Promise.all([this.manifest.listSubtreeFiles(this.organizationId,$,Y),this.manifest.listSubtreeDirs(this.organizationId,$,Y)]);await this.mkdir($,J,X);for(let H of K){let F=H.path.slice(Y.length+1),U=await this.storage.getBytes(yF($,H.path));await this.write($,`${J}/${F}`,U,{...X,skipVolumeQuota:!0})}for(let H of W){let F=H.path.slice(Y.length+1);await this.mkdir($,`${J}/${F}`,X)}await this.delete($,Y,X)}async filesExist($,Z){N7($);let Q=await this.manifest.liveFilePaths({organizationId:this.organizationId,volume:$,paths:Z.map((X)=>d7(X))});return new Set(Q)}async recent($){return this.manifest.recentFiles({organizationId:this.organizationId,limit:$})}async changes($,Z,Q=JB4){N7($);let X=Z||"0";if(!/^\d+$/.test(X))throw new SG(`Invalid cursor: ${Z}`);let Y=await this.manifest.changesSince({organizationId:this.organizationId,volume:$,sinceSeq:X,limit:Q}),J=Y.at(-1);return{entries:Y,cursor:J?J.seq:Z||"0",hasMore:Y.length>=Q}}async latestSeq($){return N7($),this.manifest.latestSeq({organizationId:this.organizationId,volume:$})}async backfillFromStorage($,Z){N7($);let Q=l30($),X,Y=0;do{let J=await this.storage.list({prefix:Q,maxKeys:GB4,continuationToken:X});for(let G of J.objects){let K=G.key.slice(Q.length);if(K==="")continue;await this.ensureDirs($,K,Z.actor);let W=await this.storage.getBytes(G.key);await this.manifest.putFile({organizationId:this.organizationId,volume:$,path:K,parent:Dl(K),contentHash:DJ$(W),size:W.byteLength,actor:Z.actor}),Y++}X=J.isTruncated?J.nextContinuationToken:void 0}while(X);return Y}async requireFile($,Z){N7($);let Q=d7(Z),X=await this.manifest.get(this.organizationId,$,Q);if(!X||X.kind!=="file")throw new UY(`No such file: ${Q}`);return X}async ensureDirs($,Z,Q){for(let X of tD(Z))await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:X,parent:Dl(X),actor:Q})}}var JB4=500,GB4=1000,KB4=524288000,WB4=10737418240,UT,SG,UY;var vB=L(()=>{w8();CW();FT();y$1();UT=class UT extends Error{constructor($){super($);this.name="OrgFsQuotaError"}};SG=class SG extends Error{constructor($){super($);this.name="OrgFsValidationError"}};UY=class UY extends Error{constructor($){super($);this.name="OrgFsNotFoundError"}}});import{z as xB}from"zod";function gF($){return $.startsWith(wJ$)}function oD($){return`${wJ$}${$}`}function LB4($){let Z=new Map(NB4.map((Q)=>[Q.set,Q]));if($)try{for(let Q of BB4.parse(JSON.parse($)))Z.set(Q.set,Q)}catch(Q){console.warn("[org-fs] invalid ORGFS_PUBLIC_SETS \u2014 using built-in defaults only",Q)}return[...Z.values()]}function YK(){return LB4(P0().orgFsPublicSetsJson)}function Xa($){let Z=zQ(),Q=Z?GY(Z,Qa):new QK(Qa,$.baseUrl);return new XK(Q,$.storage.orgFsEntries,Qa)}var Qa="org_orgfs_public_skills",wJ$="public-",FB4,UB4,NB4,BB4;var NT=L(()=>{H$();PB();Ol();vB();FB4=xB.object({from:xB.string(),to:xB.string().optional()}),UB4=xB.object({set:xB.string().regex(/^[a-z0-9][a-z0-9-]{0,40}$/),repo:xB.string().regex(/^[\w.-]+\/[\w.-]+$/),ref:xB.string().min(1),paths:xB.array(FB4).min(1)}),NB4=[{set:"core",repo:"decocms/studio",ref:"main",paths:[{from:"packages/sandbox/image/skills"}]},{set:"storefront",repo:"decocms/storefront-skills",ref:"main",paths:[{from:".claude-seo/skills"},{from:".claude-performance/skills"},{from:".claude-deco/skills"}]}],BB4=xB.array(UB4).refine(($)=>new Set($.map((Z)=>Z.set)).size===$.length,{message:"duplicate set names"})});function fB($){if(typeof $==="string")return $.length>0?[$]:[];if(Array.isArray($))return $.flatMap(fB);if($!==null&&typeof $==="object")return Object.values($).flatMap(fB);return[]}var h0;var E5=L(()=>{h0=class h0 extends Error{provider;status;retryAfterMs;constructor($){super($.message,{cause:$.cause});this.name="GitProviderError",this.provider=$.provider,this.status=$.status,this.retryAfterMs=$.retryAfterMs??null}get isRateLimited(){return this.status===429||this.retryAfterMs!==null}get isAuthFailure(){return this.status===401||this.status===403}}});import{sql as BT}from"kysely";function g$1($){if($===null)return null;return $ instanceof Date?$.toISOString():String($)}function dW($){return{organizationId:$.organization_id,volume:$.volume,path:$.path,parent:$.parent,kind:$.kind,contentHash:$.content_hash,size:Number($.size),seq:String($.seq),deletedAt:g$1($.deleted_at),createdBy:$.created_by,createdAt:g$1($.created_at)??"",updatedBy:$.updated_by,updatedAt:g$1($.updated_at)??"",threadId:$.thread_id,readPublic:$.read_public,shareMode:!$.read_public?"private":$.share_password_hash?"password":"public"}}class Ja{db;constructor($){this.db=$}async putFile($){let Z=new Date,Q=$.threadId??null,X=await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z,thread_id:Q}).onConflict((Y)=>Y.columns(["organization_id","volume","path"]).doUpdateSet({kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:m30,read_public:BT`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`,thread_id:BT`coalesce(cast(${Q} as text), org_fs_entry.thread_id)`})).returning(iW).executeTakeFirstOrThrow();return dW(X)}async putDir($){let Z=new Date;await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"dir",content_hash:null,size:0,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z}).onConflict((Q)=>Q.columns(["organization_id","volume","path"]).where("org_fs_entry.deleted_at","is not",null).doUpdateSet({kind:"dir",content_hash:null,size:0,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:m30,read_public:BT`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`})).execute()}async get($,Z,Q){let X=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("path","=",Q).where("deleted_at","is",null).select(iW).executeTakeFirst();return X?dW(X):null}async listDir($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("parent","=",Q).where("deleted_at","is",null).select(iW).orderBy("path","asc").execute()).map((Y)=>dW(Y))}async listVolumeDirs($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).select(iW).execute()).map((X)=>dW(X))}async listVolumeFiles($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select(iW).execute()).map((X)=>dW(X))}async listSubtreeFiles($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).where("path","like",`${Ya(Q)}/%`).select(iW).execute()).map((Y)=>dW(Y))}async listSubtreeDirs($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).where("path","like",`${Ya(Q)}/%`).select(iW).execute()).map((Y)=>dW(Y))}async tombstone($,Z,Q,X){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:X,updated_at:new Date,seq:m30}).where("organization_id","=",$).where("volume","=",Z).where("path","=",Q).where("deleted_at","is",null).execute()}async tombstoneSubtree($,Z,Q,X){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:X,updated_at:new Date,seq:m30}).where("organization_id","=",$).where("volume","=",Z).where("deleted_at","is",null).where((Y)=>Y.or([Y("path","=",Q),Y("path","like",`${Ya(Q)}/%`)])).execute()}async setShareMode($){let Z=new Date,Q=await this.db.updateTable("org_fs_entry").set({read_public:$.readPublic,share_password_hash:$.passwordHash,share_secret:$.shareSecret,updated_by:$.actor,updated_at:Z}).where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("path","=",$.path).where("deleted_at","is",null).returning(iW).executeTakeFirst();return Q?dW(Q):null}async resolveGoverningShare($){if($.candidatePaths.length===0)return null;let Z=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.candidatePaths).select(["path","share_password_hash","share_secret"]).execute();if(Z.length===0)return null;Z.sort((X,Y)=>Y.path.length-X.path.length);let Q=Z[0];return{path:Q.path,passwordHash:Q.share_password_hash,secret:Q.share_secret}}async hasPublicAncestorDir($,Z,Q){if(Q.length===0)return!1;return!!await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",Q).select("path").limit(1).executeTakeFirst()}async publicDirPaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.paths).select("path").execute()).map((Q)=>Q.path)}async usage($,Z){let Q=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select((X)=>[X.fn.countAll().as("files"),X.fn.coalesce(X.fn.sum("size"),BT`0`).as("bytes")]).executeTakeFirst();return{files:Number(Q?.files??0),bytes:Number(Q?.bytes??0)}}async liveFilePaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","file").where("deleted_at","is",null).where("path","in",$.paths).select(["path"]).execute()).map((Q)=>Q.path)}async recentFiles($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).select(iW).orderBy("seq","desc").limit($.limit).execute()).map((Q)=>dW(Q))}async searchFiles($){if($.volumes&&$.volumes.length===0)return[];let Z=Ya($.query),Q=this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).where("path","ilike",`%${Z}%`);if($.volumes)Q=Q.where("volume","in",$.volumes);if($.pathPrefix)Q=Q.where("path","like",`${Ya($.pathPrefix)}/%`);return(await Q.select(iW).orderBy("seq","desc").limit($.limit).execute()).map((Y)=>dW(Y))}async changesSince($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("seq",">",BT`cast(${$.sinceSeq} as bigint)`).select(iW).orderBy("seq","asc").limit($.limit).execute()).map((Q)=>dW(Q))}async latestSeq($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).select(BT`max(seq)`.as("seq")).executeTakeFirst())?.seq??"0"}}function Ya($){return $.replace(/[\\%_]/g,"\\$&")}var iW,m30;var h$1=L(()=>{iW=["organization_id","volume","path","parent","kind","content_hash","size","seq","deleted_at","created_by","created_at","updated_by","updated_at","thread_id","read_public","share_password_hash"],m30=BT`nextval('org_fs_entry_seq')`});import{createHash as OB4}from"crypto";import{gunzipSync as DB4}from"zlib";function l$1($,Z,Q){let X=Z,Y=Z+Q;while(X<Y&&$[X]!==0)X++;return new TextDecoder().decode($.subarray(Z,X))}function jB4($,Z,Q){let X=l$1($,Z,Q).trim();return X===""?0:Number.parseInt(X,8)}function EB4($){let Z=new Map,Q=0,X=null,Y=null;while(Q+512<=$.length){let J=$.subarray(Q,Q+512);if(Q+=512,J.every((N)=>N===0))break;let G=l$1(J,0,100),K=l$1(J,345,155);if(K)G=`${K}/${G}`;let W=jB4(J,124,12),H=String.fromCharCode(J[156]??0),F=$.subarray(Q,Q+W);if(Q+=Math.ceil(W/512)*512,H==="L"){let N=new TextDecoder().decode(F),B=N.indexOf("\x00");X=B===-1?N:N.slice(0,B);continue}if(H==="x"){let N=new TextDecoder().decode(F);Y=/(?:^|\n)\d+ path=([^\n]*)\n/.exec(N)?.[1]??null;continue}if(H==="g")continue;let U=Y??X??G;if(X=null,Y=null,H==="0"||H==="\x00"||H==="")Z.set(U,new Uint8Array(F))}return Z}function zB4($,Z,Q){let X=encodeURIComponent(Z);if(!Q)return{url:`https://codeload.github.com/${$}/tar.gz/${X}`,headers:{}};return{url:`https://api.github.com/repos/${$}/tarball/${X}`,headers:{Authorization:`Bearer ${Q}`,Accept:"application/vnd.github+json"}}}function jJ$($,Z){if($.length>wl)throw Error(`tarball for ${Z} exceeds ${wl} bytes`);let Q=EB4(new Uint8Array(DB4($,{maxOutputLength:wB4}))),X=new Map;for(let[Y,J]of Q){let G=Y.indexOf("/");if(G===-1)continue;let K=Y.slice(G+1);if(K)X.set(K,J)}return X}function EJ$($,Z,Q){if($>Z)throw Error(`tarball for ${Q} exceeds ${Z} bytes`)}async function PB4($,Z){let Q=[],X=0,Y=$.getReader();try{while(!0){let{done:K,value:W}=await Y.read();if(K)break;X+=W.length,EJ$(X,wl,Z),Q.push(W)}}finally{await Y.cancel().catch(()=>{}),Y.releaseLock()}let J=new Uint8Array(X),G=0;for(let K of Q)J.set(K,G),G+=K.length;return J}function zJ$($){if($ instanceof c$1)return $.status>=500||$.status===429;if($ instanceof h0)return $.status===0||$.status>=500||$.status===429;if($ instanceof Error&&/declares .* bytes|exceeds .* bytes/.test($.message))return!1;return!0}async function TB4($,Z,Q){let{url:X,headers:Y}=zB4($,Z,Q),J=`${$}@${Z}`,G=async()=>{let K=await fetch(X,{headers:Y,signal:AbortSignal.timeout(60000)});if(!K.ok)throw await K.body?.cancel().catch(()=>{}),new c$1(K.status,`tarball fetch failed for ${J}: HTTP ${K.status}`);let W=Number(K.headers.get("content-length")??0);if(W>wl)throw Error(`tarball for ${J} declares ${W} bytes (cap ${wl})`);let H=new Uint8Array(await K.arrayBuffer());return EJ$(H.length,wl,J),H};try{let K=await u8(G,{maxAttempts:3,minTimeout:500,maxTimeout:4000,jitter:0.5,isRetriable:zJ$});return jJ$(K,J)}catch(K){if(K instanceof t5)throw K.cause instanceof Error?K.cause:K;throw K}}async function AB4($,Z){if(!Z.tarball)return TB4($.repo,$.ref,Z.authToken);let Q=Z.tarball,X=`${$.repo}@${$.ref}`,Y;try{Y=await u8(()=>Q(),{maxAttempts:3,minTimeout:500,maxTimeout:4000,jitter:0.5,isRetriable:zJ$})}catch(J){throw J instanceof t5&&J.cause instanceof Error?J.cause:J}if(!Y)throw Error(`tarball not found for ${X}`);return jJ$(await PB4(Y,X),X)}function RB4($,Z){let Q=new Map;for(let{from:X,to:Y}of Z){let J=X===""?"":`${X.replace(/\/+$/,"")}/`;for(let[G,K]of $){if(!G.startsWith(J))continue;let W=G.slice(J.length);if(!W)continue;let H=d7(Y?`${Y}/${W}`:W);if(H)Q.set(H,K)}}return Q}function qB4($,Z){let Q=new Set;for(let J of $){let G=J.split("/");for(let K=1;K<G.length;K++)Q.add(G.slice(0,K).join("/"))}let X=[...Z].filter((J)=>!Q.has(J)).sort((J,G)=>J.length-G.length),Y=[];for(let J of X)if(!Y.some((G)=>J.startsWith(`${G}/`)))Y.push(J);return Y}function MB4($){return OB4("sha256").update($).digest("hex")}function IB4($){return $.manifestHash===$.hash&&$.storedPaths.has($.path)}async function VB4($,Z){let Q=l30(Z),X=new Set,Y;do{let J=await $.list({prefix:Q,continuationToken:Y});for(let G of J.objects)X.add(G.key.slice(Q.length));Y=J.nextContinuationToken}while(Y);return X}async function m$1($,Z){let{orgId:Q,volume:X,source:Y}=Z,J=zQ(),G=J?GY(J,Q):new QK(Q,Z.baseUrl),K=new Ja($),W=new XK(G,K,Q),H=RB4(await AB4(Y,Z),Y.paths),F=new Map((await K.listVolumeFiles(Q,X)).map((w)=>[w.path,w.contentHash]));if(H.size===0&&F.size>0)throw Error(`volume "${X}" resolved 0 files from ${Y.repo}@${Y.ref} `+`(check paths config) \u2014 refusing to delete the ${F.size} existing files`);let U=0;for(let w of F.keys()){if(H.has(w))continue;await W.delete(X,w,{actor:u$1}),U++}let N=await K.listVolumeDirs(Q,X);for(let w of qB4(H.keys(),N.map((j)=>j.path)))await W.delete(X,w,{actor:u$1});let B=0,O=0,D=await VB4(G,X);for(let[w,j]of H){if(IB4({hash:MB4(j),manifestHash:F.get(w),storedPaths:D,path:w})){O++;continue}await W.write(X,w,j,{actor:u$1,contentType:u7(w),skipVolumeQuota:Z.skipVolumeQuota}),B++}return{written:B,deleted:U,unchanged:O}}async function kB4($,Z,Q){let X=await m$1($,{orgId:Qa,baseUrl:Q.baseUrl,volume:oD(Z.set),source:Z,skipVolumeQuota:!0});return{set:Z.set,...X}}async function d$1($,Z,Q){try{return await kB4($,Z,Q)}catch(X){return{set:Z.set,error:X instanceof Error?X.message:String(X)}}}async function PJ$($,Z){let Q=[];for(let X of YK())Q.push(await d$1($,X,Z));return Q}var u$1="system:skill-set-sync",wl=209715200,wB4=1073741824,c$1;var d30=L(()=>{w8();E5();h$1();Ol();PB();CW();vB();FT();NT();c$1=class c$1 extends Error{status;constructor($,Z){super(Z);this.status=$;this.name="TarballHttpError"}}});import{DBOS as i30,SchedulerMode as SB4}from"@dbos-inc/dbos-sdk";function TJ$($){i$1=$}function _B4(){if(!i$1)throw Error("[org-fs] public-sets sync runtime not initialized \u2014 setPublicSetsSyncRuntime() must run before the workflow fires");return i$1}async function vB4($,Z){for(let Q of YK()){let X=await i30.runStep(()=>{let Y=_B4();return d$1(Y.db,Q,{baseUrl:Y.baseUrl})},{name:`syncPublicSet:${Q.set}`});if("error"in X)console.warn(`[org-fs] public set "${X.set}" sync failed: ${X.error}`);else if(X.written||X.deleted)console.log(`[org-fs] public set "${X.set}" synced: +${X.written} -${X.deleted} (=${X.unchanged})`)}}function AJ$(){if(Ga)return;Ga=i30.registerWorkflow(vB4,{name:"publicSetsSyncWorkflow"}),i30.registerScheduled(Ga,{name:"publicSetsSyncWorkflow",crontab:CB4,mode:SB4.ExactlyOncePerIntervalWhenActive})}async function RJ$(){if(YK().length===0||!Ga)return;let $=new Date,Z=`public-sets-sync-boot:${$.toISOString().slice(0,13)}`;await i30.startWorkflow(Ga,{workflowID:Z})($,$)}var CB4="4-59/10 * * * *",i$1=null,Ga=null;var qJ$=L(()=>{NT();d30()});import{jwtVerify as xB4,SignJWT as MJ$}from"jose";import{randomBytes as fB4}from"crypto";function IJ$(){if(Ka)return Ka;let $=P0(),Z=$.studioJwtSecret??$.betterAuthSecret;if(Z)Ka=new TextEncoder().encode(Z);else console.warn("STUDIO_JWT_SECRET not set - generating random secret (not persistent)"),Ka=new Uint8Array(fB4(32));return Ka}async function VJ$($,Z="5m"){let Q=IJ$();return await new MJ$($).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Z).sign(Q)}async function p$1($){try{let Z=IJ$(),{payload:Q}=await xB4($,Z);return Q}catch{return}}async function RQ($,Z,Q=3600){let X=P0(),Y=X.plansEnabled?X.studioJwtSecret:X.studioJwtSecret??X.betterAuthSecret;if(!Y)throw Error(X.plansEnabled?"STUDIO_JWT_SECRET (or MESH_JWT_SECRET) is required to mint gateway JWTs when STUDIO_PLANS_ENABLED is set \u2014 BETTER_AUTH_SECRET is deliberately not a fallback, see resolve-config":"A deterministic JWT secret is required to mint gateway JWTs \u2014 set STUDIO_JWT_SECRET or BETTER_AUTH_SECRET");let J=new TextEncoder().encode(Y);return await new MJ$({iss:"mesh",sub:$,...Z&&{email:Z}}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1000)+Q).sign(J)}var Ka=null;var pW=L(()=>{H$()});import{createCipheriv as bB4,createDecipheriv as yB4,createHash as gB4,randomBytes as kJ$}from"crypto";class CG{key;constructor($){if(Buffer.from($,"base64").length===_J$)this.key=Buffer.from($,"base64");else this.key=gB4("sha256").update($).digest()}async encrypt($){let Z=kJ$(Wa),Q=bB4(SJ$,this.key,Z),X=Q.update($,"utf8");X=Buffer.concat([X,Q.final()]);let Y=Q.getAuthTag();return Buffer.concat([Z,Y,X]).toString("base64")}async decrypt($){let Z=Buffer.from($,"base64"),Q=Z.subarray(0,Wa),X=Z.subarray(Wa,Wa+CJ$),Y=Z.subarray(Wa+CJ$),J=yB4(SJ$,this.key,Q);J.setAuthTag(X);let G=J.update(Y);return G=Buffer.concat([G,J.final()]),G.toString("utf8")}static generateKey(){return kJ$(_J$).toString("base64")}}var SJ$="aes-256-gcm",Wa=16,CJ$=16,_J$=32;var LT=()=>{};import*as y from"zod/v4";function tJ$($){if($.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${$.params.ref.type}`)}function oJ$($){if($.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${$.params.ref.type}`)}var rD="2025-11-25",vJ$="2025-03-26",aD,sD="io.modelcontextprotocol/related-task",n30="2.0",B7,xJ$,fJ$,Ap5,hB4,uB4,n$1,_G,Ha,bJ$=($)=>Ha.safeParse($).success,qQ,JK,GK,MQ,t30,yJ$,hF=($)=>yJ$.safeParse($).success,gJ$,hJ$=($)=>gJ$.safeParse($).success,t$1,nW=($)=>t$1.safeParse($).success,b1,o$1,El=($)=>o$1.safeParse($).success,vG,Rp5,bB,lB4,o30,cB4,Fa,jl,uJ$,mB4,dB4,iB4,pB4,nB4,tB4,r30,r$1=($)=>r30.safeParse($).success,oB4,a$1,a30,lJ$=($)=>a30.safeParse($).success,s30,rB4,aB4,e30,sB4,Ua,Na,eB4,Ba,yB,$L4,La,$K0,ZK0,QK0,qp5,XK0,YK0,JK0,cJ$,mJ$,dJ$,s$1,iJ$,Oa,zl,pJ$,ZL4,eD,e$1,$w,$81,Z81,QL4,Pl,Q81,X81,XL4,YL4,JL4,GL4,KL4,WL4,HL4,FL4,Zw,Y81,UL4,Tl,J81,G81,K81,NL4,BL4,LL4,W81,OL4,H81,F81,DL4,wL4,GK0,Al,Da,uF,Mp5,jL4,Qw,U81,nJ$,wa,EL4,N81,zL4,PL4,TL4,AL4,RL4,qL4,ML4,p30,IL4,VL4,B81,OT,ja,kL4,SL4,CL4,_L4,vL4,xL4,fL4,bL4,yL4,gL4,hL4,uL4,lL4,cL4,mL4,L81,dL4,iL4,Xw,pL4,nL4,tL4,KK0,O81,oL4,rL4,D81,aL4,Ip5,Vp5,kp5,Sp5,Cp5,_p5,S1,rJ$;var JZ=L(()=>{aD=[rD,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],B7=y.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),xJ$=y.union([y.string(),y.number().int()]),fJ$=y.string(),Ap5=y.looseObject({ttl:y.number().optional(),pollInterval:y.number().optional()}),hB4=y.object({ttl:y.number().optional()}),uB4=y.object({taskId:y.string()}),n$1=y.looseObject({progressToken:xJ$.optional(),[sD]:uB4.optional()}),_G=y.object({_meta:n$1.optional()}),Ha=_G.extend({task:hB4.optional()}),qQ=y.object({method:y.string(),params:_G.loose().optional()}),JK=y.object({_meta:n$1.optional()}),GK=y.object({method:y.string(),params:JK.loose().optional()}),MQ=y.looseObject({_meta:n$1.optional()}),t30=y.union([y.string(),y.number().int()]),yJ$=y.object({jsonrpc:y.literal(n30),id:t30,...qQ.shape}).strict(),gJ$=y.object({jsonrpc:y.literal(n30),...GK.shape}).strict(),t$1=y.object({jsonrpc:y.literal(n30),id:t30,result:MQ}).strict();(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(b1||(b1={}));o$1=y.object({jsonrpc:y.literal(n30),id:t30.optional(),error:y.object({code:y.number().int(),message:y.string(),data:y.unknown().optional()})}).strict(),vG=y.union([yJ$,gJ$,t$1,o$1]),Rp5=y.union([t$1,o$1]),bB=MQ.strict(),lB4=JK.extend({requestId:t30.optional(),reason:y.string().optional()}),o30=GK.extend({method:y.literal("notifications/cancelled"),params:lB4}),cB4=y.object({src:y.string(),mimeType:y.string().optional(),sizes:y.array(y.string()).optional(),theme:y.enum(["light","dark"]).optional()}),Fa=y.object({icons:y.array(cB4).optional()}),jl=y.object({name:y.string(),title:y.string().optional()}),uJ$=jl.extend({...jl.shape,...Fa.shape,version:y.string(),websiteUrl:y.string().optional(),description:y.string().optional()}),mB4=y.intersection(y.object({applyDefaults:y.boolean().optional()}),y.record(y.string(),y.unknown())),dB4=y.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},y.intersection(y.object({form:mB4.optional(),url:B7.optional()}),y.record(y.string(),y.unknown()).optional())),iB4=y.looseObject({list:B7.optional(),cancel:B7.optional(),requests:y.looseObject({sampling:y.looseObject({createMessage:B7.optional()}).optional(),elicitation:y.looseObject({create:B7.optional()}).optional()}).optional()}),pB4=y.looseObject({list:B7.optional(),cancel:B7.optional(),requests:y.looseObject({tools:y.looseObject({call:B7.optional()}).optional()}).optional()}),nB4=y.object({experimental:y.record(y.string(),B7).optional(),sampling:y.object({context:B7.optional(),tools:B7.optional()}).optional(),elicitation:dB4.optional(),roots:y.object({listChanged:y.boolean().optional()}).optional(),tasks:iB4.optional(),extensions:y.record(y.string(),B7).optional()}),tB4=_G.extend({protocolVersion:y.string(),capabilities:nB4,clientInfo:uJ$}),r30=qQ.extend({method:y.literal("initialize"),params:tB4}),oB4=y.object({experimental:y.record(y.string(),B7).optional(),logging:B7.optional(),completions:B7.optional(),prompts:y.object({listChanged:y.boolean().optional()}).optional(),resources:y.object({subscribe:y.boolean().optional(),listChanged:y.boolean().optional()}).optional(),tools:y.object({listChanged:y.boolean().optional()}).optional(),tasks:pB4.optional(),extensions:y.record(y.string(),B7).optional()}),a$1=MQ.extend({protocolVersion:y.string(),capabilities:oB4,serverInfo:uJ$,instructions:y.string().optional()}),a30=GK.extend({method:y.literal("notifications/initialized"),params:JK.optional()}),s30=qQ.extend({method:y.literal("ping"),params:_G.optional()}),rB4=y.object({progress:y.number(),total:y.optional(y.number()),message:y.optional(y.string())}),aB4=y.object({...JK.shape,...rB4.shape,progressToken:xJ$}),e30=GK.extend({method:y.literal("notifications/progress"),params:aB4}),sB4=_G.extend({cursor:fJ$.optional()}),Ua=qQ.extend({params:sB4.optional()}),Na=MQ.extend({nextCursor:fJ$.optional()}),eB4=y.enum(["working","input_required","completed","failed","cancelled"]),Ba=y.object({taskId:y.string(),status:eB4,ttl:y.union([y.number(),y.null()]),createdAt:y.string(),lastUpdatedAt:y.string(),pollInterval:y.optional(y.number()),statusMessage:y.optional(y.string())}),yB=MQ.extend({task:Ba}),$L4=JK.merge(Ba),La=GK.extend({method:y.literal("notifications/tasks/status"),params:$L4}),$K0=qQ.extend({method:y.literal("tasks/get"),params:_G.extend({taskId:y.string()})}),ZK0=MQ.merge(Ba),QK0=qQ.extend({method:y.literal("tasks/result"),params:_G.extend({taskId:y.string()})}),qp5=MQ.loose(),XK0=Ua.extend({method:y.literal("tasks/list")}),YK0=Na.extend({tasks:y.array(Ba)}),JK0=qQ.extend({method:y.literal("tasks/cancel"),params:_G.extend({taskId:y.string()})}),cJ$=MQ.merge(Ba),mJ$=y.object({uri:y.string(),mimeType:y.optional(y.string()),_meta:y.record(y.string(),y.unknown()).optional()}),dJ$=mJ$.extend({text:y.string()}),s$1=y.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),iJ$=mJ$.extend({blob:s$1}),Oa=y.enum(["user","assistant"]),zl=y.object({audience:y.array(Oa).optional(),priority:y.number().min(0).max(1).optional(),lastModified:y.iso.datetime({offset:!0}).optional()}),pJ$=y.object({...jl.shape,...Fa.shape,uri:y.string(),description:y.optional(y.string()),mimeType:y.optional(y.string()),size:y.optional(y.number()),annotations:zl.optional(),_meta:y.optional(y.looseObject({}))}),ZL4=y.object({...jl.shape,...Fa.shape,uriTemplate:y.string(),description:y.optional(y.string()),mimeType:y.optional(y.string()),annotations:zl.optional(),_meta:y.optional(y.looseObject({}))}),eD=Ua.extend({method:y.literal("resources/list")}),e$1=Na.extend({resources:y.array(pJ$)}),$w=Ua.extend({method:y.literal("resources/templates/list")}),$81=Na.extend({resourceTemplates:y.array(ZL4)}),Z81=_G.extend({uri:y.string()}),QL4=Z81,Pl=qQ.extend({method:y.literal("resources/read"),params:QL4}),Q81=MQ.extend({contents:y.array(y.union([dJ$,iJ$]))}),X81=GK.extend({method:y.literal("notifications/resources/list_changed"),params:JK.optional()}),XL4=Z81,YL4=qQ.extend({method:y.literal("resources/subscribe"),params:XL4}),JL4=Z81,GL4=qQ.extend({method:y.literal("resources/unsubscribe"),params:JL4}),KL4=JK.extend({uri:y.string()}),WL4=GK.extend({method:y.literal("notifications/resources/updated"),params:KL4}),HL4=y.object({name:y.string(),description:y.optional(y.string()),required:y.optional(y.boolean())}),FL4=y.object({...jl.shape,...Fa.shape,description:y.optional(y.string()),arguments:y.optional(y.array(HL4)),_meta:y.optional(y.looseObject({}))}),Zw=Ua.extend({method:y.literal("prompts/list")}),Y81=Na.extend({prompts:y.array(FL4)}),UL4=_G.extend({name:y.string(),arguments:y.record(y.string(),y.string()).optional()}),Tl=qQ.extend({method:y.literal("prompts/get"),params:UL4}),J81=y.object({type:y.literal("text"),text:y.string(),annotations:zl.optional(),_meta:y.record(y.string(),y.unknown()).optional()}),G81=y.object({type:y.literal("image"),data:s$1,mimeType:y.string(),annotations:zl.optional(),_meta:y.record(y.string(),y.unknown()).optional()}),K81=y.object({type:y.literal("audio"),data:s$1,mimeType:y.string(),annotations:zl.optional(),_meta:y.record(y.string(),y.unknown()).optional()}),NL4=y.object({type:y.literal("tool_use"),name:y.string(),id:y.string(),input:y.record(y.string(),y.unknown()),_meta:y.record(y.string(),y.unknown()).optional()}),BL4=y.object({type:y.literal("resource"),resource:y.union([dJ$,iJ$]),annotations:zl.optional(),_meta:y.record(y.string(),y.unknown()).optional()}),LL4=pJ$.extend({type:y.literal("resource_link")}),W81=y.union([J81,G81,K81,LL4,BL4]),OL4=y.object({role:Oa,content:W81}),H81=MQ.extend({description:y.string().optional(),messages:y.array(OL4)}),F81=GK.extend({method:y.literal("notifications/prompts/list_changed"),params:JK.optional()}),DL4=y.object({title:y.string().optional(),readOnlyHint:y.boolean().optional(),destructiveHint:y.boolean().optional(),idempotentHint:y.boolean().optional(),openWorldHint:y.boolean().optional()}),wL4=y.object({taskSupport:y.enum(["required","optional","forbidden"]).optional()}),GK0=y.object({...jl.shape,...Fa.shape,description:y.string().optional(),inputSchema:y.object({type:y.literal("object"),properties:y.record(y.string(),B7).optional(),required:y.array(y.string()).optional()}).catchall(y.unknown()),outputSchema:y.object({type:y.literal("object"),properties:y.record(y.string(),B7).optional(),required:y.array(y.string()).optional()}).catchall(y.unknown()).optional(),annotations:DL4.optional(),execution:wL4.optional(),_meta:y.record(y.string(),y.unknown()).optional()}),Al=Ua.extend({method:y.literal("tools/list")}),Da=Na.extend({tools:y.array(GK0)}),uF=MQ.extend({content:y.array(W81).default([]),structuredContent:y.record(y.string(),y.unknown()).optional(),isError:y.boolean().optional()}),Mp5=uF.or(MQ.extend({toolResult:y.unknown()})),jL4=Ha.extend({name:y.string(),arguments:y.record(y.string(),y.unknown()).optional()}),Qw=qQ.extend({method:y.literal("tools/call"),params:jL4}),U81=GK.extend({method:y.literal("notifications/tools/list_changed"),params:JK.optional()}),nJ$=y.object({autoRefresh:y.boolean().default(!0),debounceMs:y.number().int().nonnegative().default(300)}),wa=y.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),EL4=_G.extend({level:wa}),N81=qQ.extend({method:y.literal("logging/setLevel"),params:EL4}),zL4=JK.extend({level:wa,logger:y.string().optional(),data:y.unknown()}),PL4=GK.extend({method:y.literal("notifications/message"),params:zL4}),TL4=y.object({name:y.string().optional()}),AL4=y.object({hints:y.array(TL4).optional(),costPriority:y.number().min(0).max(1).optional(),speedPriority:y.number().min(0).max(1).optional(),intelligencePriority:y.number().min(0).max(1).optional()}),RL4=y.object({mode:y.enum(["auto","required","none"]).optional()}),qL4=y.object({type:y.literal("tool_result"),toolUseId:y.string().describe("The unique identifier for the corresponding tool call."),content:y.array(W81).default([]),structuredContent:y.object({}).loose().optional(),isError:y.boolean().optional(),_meta:y.record(y.string(),y.unknown()).optional()}),ML4=y.discriminatedUnion("type",[J81,G81,K81]),p30=y.discriminatedUnion("type",[J81,G81,K81,NL4,qL4]),IL4=y.object({role:Oa,content:y.union([p30,y.array(p30)]),_meta:y.record(y.string(),y.unknown()).optional()}),VL4=Ha.extend({messages:y.array(IL4),modelPreferences:AL4.optional(),systemPrompt:y.string().optional(),includeContext:y.enum(["none","thisServer","allServers"]).optional(),temperature:y.number().optional(),maxTokens:y.number().int(),stopSequences:y.array(y.string()).optional(),metadata:B7.optional(),tools:y.array(GK0).optional(),toolChoice:RL4.optional()}),B81=qQ.extend({method:y.literal("sampling/createMessage"),params:VL4}),OT=MQ.extend({model:y.string(),stopReason:y.optional(y.enum(["endTurn","stopSequence","maxTokens"]).or(y.string())),role:Oa,content:ML4}),ja=MQ.extend({model:y.string(),stopReason:y.optional(y.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(y.string())),role:Oa,content:y.union([p30,y.array(p30)])}),kL4=y.object({type:y.literal("boolean"),title:y.string().optional(),description:y.string().optional(),default:y.boolean().optional()}),SL4=y.object({type:y.literal("string"),title:y.string().optional(),description:y.string().optional(),minLength:y.number().optional(),maxLength:y.number().optional(),format:y.enum(["email","uri","date","date-time"]).optional(),default:y.string().optional()}),CL4=y.object({type:y.enum(["number","integer"]),title:y.string().optional(),description:y.string().optional(),minimum:y.number().optional(),maximum:y.number().optional(),default:y.number().optional()}),_L4=y.object({type:y.literal("string"),title:y.string().optional(),description:y.string().optional(),enum:y.array(y.string()),default:y.string().optional()}),vL4=y.object({type:y.literal("string"),title:y.string().optional(),description:y.string().optional(),oneOf:y.array(y.object({const:y.string(),title:y.string()})),default:y.string().optional()}),xL4=y.object({type:y.literal("string"),title:y.string().optional(),description:y.string().optional(),enum:y.array(y.string()),enumNames:y.array(y.string()).optional(),default:y.string().optional()}),fL4=y.union([_L4,vL4]),bL4=y.object({type:y.literal("array"),title:y.string().optional(),description:y.string().optional(),minItems:y.number().optional(),maxItems:y.number().optional(),items:y.object({type:y.literal("string"),enum:y.array(y.string())}),default:y.array(y.string()).optional()}),yL4=y.object({type:y.literal("array"),title:y.string().optional(),description:y.string().optional(),minItems:y.number().optional(),maxItems:y.number().optional(),items:y.object({anyOf:y.array(y.object({const:y.string(),title:y.string()}))}),default:y.array(y.string()).optional()}),gL4=y.union([bL4,yL4]),hL4=y.union([xL4,fL4,gL4]),uL4=y.union([hL4,kL4,SL4,CL4]),lL4=Ha.extend({mode:y.literal("form").optional(),message:y.string(),requestedSchema:y.object({type:y.literal("object"),properties:y.record(y.string(),uL4),required:y.array(y.string()).optional()})}),cL4=Ha.extend({mode:y.literal("url"),message:y.string(),elicitationId:y.string(),url:y.string().url()}),mL4=y.union([lL4,cL4]),L81=qQ.extend({method:y.literal("elicitation/create"),params:mL4}),dL4=JK.extend({elicitationId:y.string()}),iL4=GK.extend({method:y.literal("notifications/elicitation/complete"),params:dL4}),Xw=MQ.extend({action:y.enum(["accept","decline","cancel"]),content:y.preprocess(($)=>$===null?void 0:$,y.record(y.string(),y.union([y.string(),y.number(),y.boolean(),y.array(y.string())])).optional())}),pL4=y.object({type:y.literal("ref/resource"),uri:y.string()}),nL4=y.object({type:y.literal("ref/prompt"),name:y.string()}),tL4=_G.extend({ref:y.union([nL4,pL4]),argument:y.object({name:y.string(),value:y.string()}),context:y.object({arguments:y.record(y.string(),y.string()).optional()}).optional()}),KK0=qQ.extend({method:y.literal("completion/complete"),params:tL4});O81=MQ.extend({completion:y.looseObject({values:y.array(y.string()).max(100),total:y.optional(y.number().int()),hasMore:y.optional(y.boolean())})}),oL4=y.object({uri:y.string().startsWith("file://"),name:y.string().optional(),_meta:y.record(y.string(),y.unknown()).optional()}),rL4=qQ.extend({method:y.literal("roots/list"),params:_G.optional()}),D81=MQ.extend({roots:y.array(oL4)}),aL4=GK.extend({method:y.literal("notifications/roots/list_changed"),params:JK.optional()}),Ip5=y.union([s30,r30,KK0,N81,Tl,Zw,eD,$w,Pl,YL4,GL4,Qw,Al,$K0,QK0,XK0,JK0]),Vp5=y.union([o30,e30,a30,aL4,La]),kp5=y.union([bB,OT,ja,Xw,D81,ZK0,YK0,yB]),Sp5=y.union([s30,B81,L81,rL4,$K0,QK0,XK0,JK0]),Cp5=y.union([o30,e30,PL4,WL4,X81,U81,F81,La,iL4]),_p5=y.union([bB,a$1,O81,H81,Y81,e$1,$81,Q81,uF,Da,ZK0,YK0,yB]);S1=class S1 extends Error{constructor($,Z,Q){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=Q,this.name="McpError"}static fromError($,Z,Q){if($===b1.UrlElicitationRequired&&Q){let X=Q;if(X.elicitations)return new rJ$(X.elicitations,Z)}return new S1($,Z,Q)}};rJ$=class rJ$ extends S1{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(b1.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});import{z as r$}from"zod";function eJ$($){return r$.record(r$.string(),r$.unknown()).nullable().refine((Z)=>Z===null||JSON.stringify(Z).length<=sJ$,{message:`${$} must serialize to at most ${sJ$} bytes`})}function lF($){return $!==null&&$!==void 0&&"command"in $}function Rl($){if(!$||!$.startsWith("virtual://"))return null;return $.replace("virtual://","")}function ql($){return`virtual://${$}`}var $G$,aJ$,sL4,eL4,$O4,sJ$=262144,LX,WK0,HK0;var ZG$=L(()=>{JZ();$G$=r$.object({authorizationEndpoint:r$.string().url(),tokenEndpoint:r$.string().url(),introspectionEndpoint:r$.string().url().optional(),clientId:r$.string(),clientSecret:r$.string().optional(),scopes:r$.array(r$.string()),grantType:r$.enum(["authorization_code","client_credentials"])}),aJ$=r$.object({type:r$.literal("object"),properties:r$.record(r$.string(),r$.unknown()).optional(),required:r$.array(r$.string()).optional()}).catchall(r$.unknown()),sL4=GK0.extend({inputSchema:aJ$,outputSchema:aJ$.optional()}),eL4=r$.object({headers:r$.record(r$.string(),r$.string()).optional()}),$O4=r$.object({command:r$.string().describe("Command to run (e.g., 'npx', 'node')"),args:r$.array(r$.string()).optional().describe("Command arguments"),cwd:r$.string().optional().describe("Working directory"),envVars:r$.record(r$.string(),r$.string()).optional().describe("Environment variables (encrypted in storage)")});LX=r$.object({id:r$.string().describe("Unique identifier for the connection"),title:r$.string().describe("Human-readable name for the connection"),created_at:r$.string().describe("When the connection was created"),updated_at:r$.string().describe("When the connection was last updated"),created_by:r$.string().describe("User ID who created the connection"),updated_by:r$.string().optional().describe("User ID who last updated the connection"),organization_id:r$.string().describe("Organization ID this connection belongs to"),description:r$.string().nullable().describe("Description of the connection"),icon:r$.string().nullable().describe("Icon URL for the connection"),app_name:r$.string().nullable().describe("Associated app name"),app_id:r$.string().nullable().describe("Associated app ID"),slug:r$.string().nullable().optional().describe("URL-safe slug derived from app_name, connection_url, or title"),connection_type:r$.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:r$.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:r$.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:r$.union([$O4,eL4]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:$G$.nullable().describe("OAuth configuration"),configuration_state:eJ$("configuration_state").describe("Configuration state (decrypted)"),configuration_scopes:r$.array(r$.string()).nullable().optional().describe("Configuration scopes"),metadata:eJ$("metadata").describe("Additional metadata (includes repository info)"),tools:r$.array(sL4).nullable().describe("Discovered tools from MCP"),bindings:r$.array(r$.string()).nullable().describe("Detected bindings"),status:r$.enum(["active","inactive","error"]).describe("Current status")}),WK0=LX.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}).extend({icon:r$.string().nullish()}),HK0=LX.partial()});import{z as S0}from"zod";function E81($){let Z=$?.homeTiles;if(Array.isArray(Z)&&Z.length>0)return Z;let Q=$?.homeTile;return Q?[Q]:[]}function gB($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z=$,Q={};for(let[X,Y]of Object.entries(Z)){if(!Y||typeof Y!=="object")continue;if(X!=="agent-sandbox"&&X!=="local-api")continue;try{Q[X]=z81.parse(Y)}catch{}}return Q}function P81($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z={};for(let[Q,X]of Object.entries($)){if(!X||typeof X!=="object"||Array.isArray(X))continue;let Y={};for(let[J,G]of Object.entries(X)){let K=gB(G);if(Object.keys(K).length>0)Y[J]=K}if(Object.keys(Y).length>0)Z[Q]=Y}return Z}var YG$,w81=500,JG$=200,ZO4=200,QO4=20,XO4=50,YO4=100,JO4=20,GO4=100,GG$=50,KO4=100,WO4=50,HO4=8192,KG$,FO4,WG$,j81,UO4,NO4,HG$,QG$,BO4,FK0,XG$,LO4,FG$,OO4,DO4,wO4,jO4,EO4,z81,UG$,zO4,PO4,TO4,AO4,RO4,qO4,MO4,NG$,IO4,T81,OX,A81,UK0,NK0;var BG$=L(()=>{YG$=S0.object({connection_id:S0.string().describe("Connection ID"),selected_tools:S0.array(S0.string()).nullable().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:S0.array(S0.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:S0.array(S0.string()).nullable().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),KG$=YG$.extend({selected_tools:S0.array(S0.string()).max(w81).nullable().optional().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:S0.array(S0.string()).max(w81).nullable().optional().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:S0.array(S0.string()).max(w81).nullable().optional().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),FO4=S0.object({connectionId:S0.string(),toolName:S0.string(),label:S0.string(),icon:S0.string().nullable().optional()}),WG$=S0.object({id:S0.string().describe("Stable id; used as React key and ?tab= value"),title:S0.string().describe("Tab label"),icon:S0.string().optional().describe("Optional lucide icon name"),view:S0.object({type:S0.literal("ext-app"),appId:S0.string(),args:S0.record(S0.string(),S0.unknown()).optional()})}),j81=S0.enum(["overview","reports","board","site-editor","assets","hosting","e2e","analytics","cdn","automations","experiments"]),UO4=S0.enum(["on","off"]),NO4=S0.enum(["on","off","manual","auto"]),HG$=S0.object({defaultMainView:S0.object({type:S0.string(),id:S0.string().optional(),toolName:S0.string().optional()}).nullable().optional(),chatDefaultOpen:S0.boolean().nullable().optional(),cmsDefaultOpen:S0.boolean().nullable().optional(),cms:NO4.nullable().optional().describe("How this agent offers content editing. Absent means on; the retired `manual` / `auto` read as on too."),sidebarViews:S0.array(j81).max(10).nullable().optional().describe("Deprecated layout-scoped sidebar selections. Read only as a fallback when metadata.sidebarViews is absent."),tabs:S0.array(WG$).max(JO4).optional()}),QG$=S0.object({tileId:S0.string().optional(),connectionId:S0.string().optional().describe("Connection that owns the resource \u2014 the host opens a direct MCP client to this connection so the iframe can call tools by their bare names."),resourceUri:S0.string().describe("ui:// resource URI exposed by `connectionId`. Read on the home page and rendered via MCPAppRenderer."),toolName:S0.string().optional().describe("Tool name \u2014 identifies which tool's inputSchema to display when editing tile props."),toolInput:S0.record(S0.string(),S0.unknown()).optional().describe("User-configured input props passed to MCPAppRenderer when rendering the tile."),minHeight:S0.number().int().positive().optional(),maxHeight:S0.number().int().positive().optional()}),BO4=S0.object({banner:S0.string().nullable().optional(),bannerColor:S0.string().nullable().optional(),icon:S0.string().nullable().optional(),themeColor:S0.string().nullable().optional(),pinnedViews:S0.array(FO4).max(YO4).nullable().optional(),layout:HG$.nullable().optional(),homeTile:QG$.nullable().optional(),homeTiles:S0.array(QG$).max(QO4).nullable().optional(),homePrompts:S0.array(S0.string()).max(XO4).nullable().optional()});FK0=/^[A-Za-z_][A-Za-z0-9_]*$/,XG$=S0.string().min(1).regex(FK0,{message:"Env var key must start with a letter or underscore and contain only letters, digits, and underscores."}),LO4=S0.discriminatedUnion("kind",[S0.object({key:XG$,kind:S0.literal("literal"),value:S0.string().max(HO4)}),S0.object({key:XG$,kind:S0.literal("secret"),secretId:S0.string().min(1)})]),FG$=/^[a-zA-Z0-9.-]+(?::[0-9]+)?$/,OO4=S0.object({host:S0.string().min(1).regex(FG$).describe("Submodule host, e.g. 'github.com' (bare hostname, no scheme)."),secretId:S0.string().min(1).describe("Vault secret id holding the PAT used to fetch this host.")}),DO4=S0.object({selected:S0.string().nullable().optional().describe("User-selected package manager (npm | pnpm | yarn | bun | deno). Null/absent means autodetect on next SANDBOX_START."),port:S0.string().nullable().optional().describe("User-selected dev server port as a string (allows '' / null for unset). Null/absent means autodetect."),path:S0.string().nullable().optional().describe("Optional path (relative to repo root) to the directory containing package.json. Null/absent means repo root. Forwarded as `application.packageManager.path` to the daemon config."),env:S0.array(LO4).max(KO4).nullable().optional().describe("Env vars injected on every SANDBOX_START. Literal entries inline their value; secret entries store a secretId that Studio resolves via the credential vault before posting /_sandbox/config."),submoduleCredentials:S0.array(OO4).max(WO4).nullable().optional().describe("Git submodule credentials injected on every SANDBOX_START. Each entry maps a host to a vault secret (PAT) that Studio resolves before posting /_sandbox/config; the daemon uses it to authenticate `git submodule update` for submodules on that host.")}),wO4=S0.object({url:S0.string().describe("GitHub repository URL"),owner:S0.string().describe("Repository owner"),name:S0.string().describe("Repository name"),installationId:S0.number().optional().describe("GitHub App installation ID. Absent when the repo was linked without a GitHub connection (public-clone mode)."),connectionId:S0.string().optional().describe("ID of the mcp-github connection used for authentication. Absent for public repos cloned without credentials."),repositoryId:S0.string().optional().describe("First-class repository (REPOSITORY_LINK) backing this binding. When set, credentials come from the repository's git provider account rather than connectionId.")}),jO4=S0.enum(["agent-sandbox","local-api"]),EO4={sandboxHandle:S0.string().describe("Provider-specific handle"),previewUrl:S0.string().nullable().describe("URL where the sandbox's iframe-proxied UI is served, or null when the sandbox has no dev server (blank / tool sandboxes)."),sandboxApiUrl:S0.string().nullable().optional().describe("Direct sandbox API URL for runtimes that expose one. Equal to previewUrl for local-api; null/absent for AgentSandbox, which routes control traffic through hosted Studio."),createdAt:S0.number().optional().describe("Epoch ms the entry was first written by SANDBOX_START. Used by the booting overlay to show a stable elapsed timer that survives browser reloads. Optional for backward compatibility with entries written before this field existed."),startedWith:S0.object({packageManager:S0.string().nullable().optional().describe("metadata.runtime.selected at the time of SANDBOX_START"),port:S0.string().nullable().optional().describe("metadata.runtime.port at the time of SANDBOX_START"),path:S0.string().nullable().optional().describe("metadata.runtime.path at the time of SANDBOX_START")}).optional().describe("Snapshot of metadata.runtime fields (selected/port/path) used at SANDBOX_START. The Preview tab compares the live metadata.runtime against this to decide if a restart is required to apply changes.")},z81=S0.object(EO4);UG$=S0.record(S0.string().describe("userId"),S0.record(S0.string().describe("branch"),S0.partialRecord(jO4,z81)));zO4=S0.object({id:S0.string().describe("Stable identifier for this knowledge file"),name:S0.string().describe("File name shown in the UI"),kind:S0.enum(["file","skill"]).optional().describe("'file' (a single document) or 'skill' (a Claude Code skill folder containing SKILL.md). Defaults to 'file'."),volume:S0.string().describe("Org filesystem (Library) volume the file lives in"),path:S0.string().describe("Path within the volume"),url:S0.string().describe("Same-origin URL to read the file (display/download)"),contentType:S0.string().nullable().optional().describe("MIME type, used to decide whether to inline the content"),size:S0.number().nullable().optional().describe("File size in bytes"),addedAt:S0.string().describe("ISO timestamp when the file was attached")}),PO4=S0.array(zO4).max(GO4).nullable().optional().describe("Files attached to the agent as reference knowledge. Surfaced in the system prompt: small text documents are inlined, others are listed as retrievable references."),TO4=S0.enum(["smart","code-review","open"]),AO4=TO4.nullable().optional().describe("Controls when this code agent's changes may be published directly vs. requiring PR review. 'smart' (default) uses AI to judge per change; 'code-review' requires review for any code; 'open' allows direct publish always."),RO4=S0.boolean().nullable().optional().describe("Enable Fast Preview (sandbox-less): render the draft instantly on the preview server's own page via a ?__draft pointer, with reads/writes served by the decofile API against GitHub. Requires previewServerUrl (or legacy productionUrl) to be set to take effect."),qO4=S0.boolean().nullable().optional().describe("EXPERIMENTAL: with Fast Preview on, refresh content edits via an in-place /live/previews render (no commit, no reload) instead of a commit + re-navigation. Deco-runtime preview targets only. Requires fastPreview."),MO4=S0.string().nullable().optional().describe("Preview server URL \u2014 the deployment the CMS preview renders against (often the live site, e.g. https://acme.com). Painted in the preview iframe, and the render target for Fast Preview drafts. Supersedes the legacy productionUrl key."),NG$=S0.object({branch:S0.string().describe("Git branch backing this release"),name:S0.string().describe('User-facing name, e.g. "Black Friday 2026"'),color:S0.string().describe("Dot color token shown in the version switcher"),createdBy:S0.string().optional().describe("User ID who created the release"),createdAt:S0.string().optional().describe("ISO 8601 creation timestamp")}),IO4=S0.array(NG$).max(GG$).nullable().optional().describe("Curated list of named, branch-backed releases shown in the version switcher. The base branch ('No ar') is derived, not stored here."),T81={instructions:S0.string().nullable().optional().describe("Instructions also used as system prompt"),subAgents:S0.array(S0.string()).max(ZO4).nullable().optional().describe("Allowlist of Virtual MCP (agent) or concrete MCP connection IDs this agent may delegate to via subtask. Concrete connections create ephemeral subagents. null/absent = all active org targets; empty array = itself only."),liveAgentId:S0.string().nullable().optional().describe("ID of the live agent this (dev) agent develops. Set only on dev agents; powers the Develop/Live toggle. A dev agent is hidden from the sidebar (reached via the toggle on its live counterpart)."),ui:BO4.nullable().optional().describe("UI customization settings"),sidebarViews:S0.array(j81).max(10).nullable().optional().describe("Project views selected for the sidebar. Interpret as an exact list when sidebarViewsVersion is 1; unversioned values use legacy native-only semantics. Runtime presence gates still apply."),sidebarViewsVersion:S0.literal(1).optional().describe("Version 1 marks metadata.sidebarViews as an exact list that can disable legacy default rows."),githubRepo:wO4.nullable().optional().describe("Linked GitHub repository"),runtime:DO4.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),knowledge:PO4,siteSlug:S0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:AO4,previewServerUrl:MO4,productionUrl:S0.string().nullable().optional().describe("Legacy key for previewServerUrl \u2014 still read as a fallback. New writes use previewServerUrl."),fieldDescriptionTooltips:S0.boolean().nullable().optional().describe("Blocks form: opt in to showing a field's schema description as a hover tooltip on its title, instead of the default inline text below the title."),fastPreview:RO4,releases:IO4,fastPreviewInPlace:qO4},OX=S0.object({id:S0.string().describe("Unique identifier"),title:S0.string().describe("Human-readable name"),description:S0.string().nullable().describe("Description"),icon:S0.string().nullable().describe("Icon URL"),created_at:S0.string().describe("Creation timestamp"),updated_at:S0.string().describe("Last update timestamp"),created_by:S0.string().describe("User ID who created this item"),updated_by:S0.string().optional().describe("User ID who last updated this item"),organization_id:S0.string().describe("Organization ID this item belongs to"),status:S0.enum(["active","inactive"]).describe("Current status"),pinned:S0.boolean().describe("Whether this space is pinned to the sidebar"),metadata:S0.object(T81).extend({instructions:S0.string().nullable().describe("Instructions also used as system prompt"),sandboxMap:UG$.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }")}).loose().describe("Metadata"),connections:S0.array(YG$).describe("Connections with their selected tools, resources, and prompts")}),A81=S0.object({title:S0.string().min(1).max(120).describe("Short label shown on the chip"),description:S0.string().max(280).optional().describe("One-line subtitle shown under the title"),text:S0.string().min(1).max(4000).describe("The message sent to the agent when the prompt is clicked")}),UK0=S0.object({title:S0.string().min(1).max(255).describe("Name for the virtual MCP"),description:S0.string().max(500).nullable().optional().describe("Optional description"),icon:S0.string().nullish().describe("Optional icon URL"),status:S0.enum(["active","inactive"]).optional().default("active").describe("Initial status"),pinned:S0.boolean().optional().default(!1).describe("Pin to sidebar"),metadata:S0.object(T81).loose().superRefine(($,Z)=>{if("sandboxMap"in $)Z.addIssue({code:"custom",path:["sandboxMap"],message:"sandboxMap is managed by the sandbox lifecycle"})}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:S0.array(KG$).max(JG$).describe("Connections to include/exclude (can be empty for exclusion mode)"),prompts:S0.array(A81).max(20).optional().describe("Optional kickstart prompts to seed on the agent. Each becomes a clickable conversation starter (icebreaker) on the agent. Author them from the agent's role and the tools it will have so they're coherent and immediately useful.")}),NK0=S0.object({title:S0.string().min(1).max(255).optional().describe("New name"),description:S0.string().max(500).nullable().optional().describe("New description (null to clear)"),icon:S0.string().nullish().describe("New icon URL"),status:S0.enum(["active","inactive"]).optional().describe("New status"),pinned:S0.boolean().optional().describe("Pin/unpin from sidebar"),metadata:S0.object(T81).loose().superRefine(($,Z)=>{if("sandboxMap"in $)Z.addIssue({code:"custom",path:["sandboxMap"],message:"sandboxMap is managed by the sandbox lifecycle"})}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:S0.array(KG$).max(JG$).optional().describe("New connections (replaces existing)"),prompts:S0.array(A81).max(20).optional().describe("Replace the agent's kickstart prompts with this full set. Omit to leave them unchanged; pass an empty array to remove all. Each becomes a clickable conversation starter (icebreaker).")})});function DT($){return VO4.has($)}var AZ,VO4,BK0;var LG$=L(()=>{AZ=["deco","anthropic","openrouter","llmapi","google","openai-compatible"],VO4=new Set(AZ);BK0=[...AZ,"claude-code","codex"]});function R81($,Z){return{id:crypto.randomUUID(),type:Ea.STEP,source:"decopilot",subject:$,data:{stepCount:Z},time:new Date().toISOString()}}function LK0($,Z){return{id:crypto.randomUUID(),type:Ea.FINISH,source:"decopilot",subject:$,data:{status:Z},time:new Date().toISOString()}}function cF($,Z,Q){return{id:crypto.randomUUID(),type:Ea.THREAD_STATUS,source:"decopilot",subject:$,data:{status:Z,...Q?.messageId!==void 0&&{message_id:Q.messageId},...Q?.virtualMcpId!==void 0&&{virtual_mcp_id:Q.virtualMcpId},...Q?.createdBy!==void 0&&{created_by:Q.createdBy},...Q?.triggerId!==void 0&&{trigger_id:Q.triggerId},...Q?.title!==void 0&&{title:Q.title},...Q?.branch!==void 0&&{branch:Q.branch},...Q?.harnessId!==void 0&&{harness_id:Q.harnessId},...Q?.createdAt!==void 0&&{created_at:Q.createdAt},...Q?.updatedAt!==void 0&&{updated_at:Q.updatedAt},...Q?.metadata!==void 0&&{metadata:Q.metadata}},time:new Date().toISOString()}}var OG$,kO4,Ea,SO4;var DG$=L(()=>{OG$=["in_progress","requires_action","failed","completed"],kO4=[...OG$,"expired"],Ea={STEP:"decopilot.step",FINISH:"decopilot.finish",THREAD_STATUS:"decopilot.thread.status"},SO4=Object.values(Ea)});var OK0=L(()=>{ZG$();BG$();LG$();DG$()});var mF=L(()=>{OK0()});import{lookup as CO4}from"dns/promises";function za($,Z){if($===10)return!0;if($===172&&Z!==void 0&&Z>=16&&Z<=31)return!0;if($===192&&Z===168)return!0;if($===127)return!0;if($===169&&Z===254)return!0;if($===0)return!0;if($===100&&Z!==void 0&&Z>=64&&Z<=127)return!0;return!1}function q81($){let Z=Number.parseInt($.padStart(4,"0"),16);return[Z>>8,Z&255]}function wG$($){let Z=$.split(":").filter((Q)=>Q.length>0);if($.startsWith("2002:")&&Z.length>=2){let[Q,X]=q81(Z[1]);if(za(Q,X))return!0}if($.startsWith("64:ff9b::")&&Z.length>=4){let[Q,X]=q81(Z[Z.length-2]);if(za(Q,X))return!0}if($.startsWith("::")&&Z.length===2){let[Q,X]=q81(Z[0]);if(za(Q,X))return!0}return!1}function Ml($){try{let Q=new URL($).hostname.toLowerCase();if(Q==="localhost"||Q==="0.0.0.0"||Q.endsWith(".local")||Q.endsWith(".internal")||Q.endsWith(".localhost"))return!0;let X=Q.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(X){let[,Y,J]=X.map(Number);if(za(Y,J))return!0}if(Q.startsWith("[")&&Q.endsWith("]")){let Y=Q.slice(1,-1).toLowerCase();if(Y==="::1"||Y==="::")return!0;if(Y.startsWith("::ffff:"))return!0;if(Y.startsWith("fc")||Y.startsWith("fd"))return!0;if(Y.startsWith("fe80"))return!0;if(Y.startsWith("100:"))return!0;if(Y.startsWith("::1"))return!0;if(wG$(Y))return!0}return!1}catch{return!0}}function _O4($){let Z=$.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(Z){let[,X,Y]=Z.map(Number);return za(X,Y)}let Q=$.toLowerCase();if(Q==="::1"||Q==="::")return!0;if(Q.startsWith("::ffff:"))return!0;if(Q.startsWith("fc")||Q.startsWith("fd"))return!0;if(Q.startsWith("fe80"))return!0;if(Q.startsWith("100:"))return!0;return wG$(Q)}async function vO4($,Z=async(Q)=>(await CO4(Q,{all:!0})).map((X)=>X.address)){try{let Q=await Z($);return Q.length===0||Q.some(_O4)}catch{return!0}}async function Pa($){if(Ml($))return"URLs targeting private networks are not allowed";let Q=new URL($).hostname;if(/^\d+\.\d+\.\d+\.\d+$/.test(Q)||Q.startsWith("[")&&Q.endsWith("]"))return null;try{return await xO4(vO4(Q),5000,"DNS resolution timeout")?"URLs targeting private networks are not allowed":null}catch{return"URLs targeting private networks are not allowed"}}function xO4($,Z,Q){let X,Y=new Promise((J,G)=>{X=setTimeout(()=>G(Error(Q)),Z)});return Promise.race([$,Y]).finally(()=>clearTimeout(X))}function wT($=fetch){return async(Z,Q)=>{let X=await $(Z,{...Q,redirect:"manual"});if(X.status>=300&&X.status<400)throw Error("Refusing to follow a redirect from the remote server");return X}}var Ta=()=>{};function $4($){return`${$}_${CF()}`}var DX=L(()=>{zr()});function EG$($,Z){return{id:y4.SELF(Z),title:"Deco CMS",description:"The MCP for the CMS API",connection_type:"HTTP",connection_url:`${$}/mcp/self`,icon:"https://assets.decocache.com/mcp/09e44283-f47d-4046-955f-816d227c626f/app.png",app_name:"@deco/management-mcp",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"self"}}}function zG$($,Z){return{id:y4.DEV_ASSETS(Z),title:"Local Files",description:"Local file storage for development. Files are stored in /data/assets/.",connection_type:"HTTP",connection_url:`${$}/mcp/dev-assets`,icon:"https://api.iconify.design/lucide:folder.svg?color=%23888",app_name:"@deco/dev-assets-mcp",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isFixed:!0,devOnly:!0,type:"dev-assets"}}}function KK($){return{is(Z){if(!Z)return null;if(!Z.startsWith($))return null;return Z.slice($.length)||null},get(Z){return`${$}${Z}`}}}function PG$($){return{id:$.id,organization_id:$.organizationId,title:$.title,description:$.description,icon:$.icon,status:"active",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),created_by:"system",updated_by:void 0,metadata:{instructions:$.instructions??null,...$.ui?{ui:$.ui}:{}},pinned:!1,connections:[]}}function I81($){return PG$({id:ET($),organizationId:$,title:"Super Agent",description:"Default agent that aggregates all organization connections",icon:fO4,ui:{layout:{defaultMainView:{type:"overview"},chatDefaultOpen:!0}}})}function MG$($){return PG$({id:yO4($),organizationId:$,title:"Brand context setup",description:"Guided onboarding agent that extracts brand context from a website URL.",icon:"https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",instructions:gO4})}function kG$($,Z,Q="https://reports.decocms.com/api/v2/mcp"){return{id:y4.REPORTS($),title:"Store Report",description:"Your store's report and diagnostics",connection_type:"HTTP",connection_url:Q,icon:"https://github.com/decocms.png",app_name:"commerce-discovery",app_id:null,connection_token:Z,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!1,type:"commerce-discovery"}}}function SG$($,Z=y4.REPORTS($)){return{title:"Report Agent",description:"Ask anything about your store's report",icon:"https://github.com/decocms.png",status:"active",pinned:!0,metadata:{type:"commerce-discovery",isDefault:!1,ui:{pinnedViews:[{connectionId:Z,toolName:"get_my_diagnostic",label:"Report",icon:"https://github.com/decocms.png"}],layout:{defaultMainView:{type:"ext-apps",id:Z,toolName:"get_my_diagnostic"},chatDefaultOpen:!0}}},connections:[{connection_id:Z,selected_tools:null,selected_resources:null,selected_prompts:null}]}}function CG$($){if(!$)return!1;return Object.values(jT).some((Z)=>Z.is($)!==null)}function _G$($){let Z=I81($);return{...Z,id:Z.id,connection_type:"VIRTUAL",connection_url:`virtual://${Z.id}`,app_name:"decopilot",app_id:"decopilot",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"decopilot"},tools:[],bindings:[]}}var y4,jG$="https://reports.decocms.com/api/v2/mcp",DK0="get_my_diagnostic",TG$,IQ,ET,AG$,RG$,M81,fO4="https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",bO4="#6366f1",Zn5,qG$,wK0,yO4,gO4,IG$,Qn5,Xn5,VG$,Yn5,Il,jT,WK,V81,Jn5;var vG$=L(()=>{y4={SELF:($)=>`${$}_self`,REGISTRY:($)=>`${$}_registry`,COMMUNITY_REGISTRY:($)=>`${$}_community-registry`,DEV_ASSETS:($)=>`${$}_dev-assets`,SITE_DIAGNOSTICS:($)=>`site-diagnostics_${$}`,REPORTS:($)=>`${$}_commerce-discovery`};TG$=KK("decopilot_"),IQ=TG$.is,ET=TG$.get,AG$=KK("dev_"),RG$=AG$.get,M81=AG$.is,Zn5=`https://api.iconify.design/lucide:file-search.svg?color=${encodeURIComponent(bO4)}`;qG$=KK("brand-context-setup_"),wK0=qG$.is,yO4=qG$.get,gO4=`
|
|
2118
|
+
`:X="\\n";break;case"\r":X="\\r";break;case"\t":X="\\t";break;default:}throw new vU4.InvalidNameError(`${$} name ('${Z}') cannot contain '${X}'`)}}),""}function bU4($,Z=""){if(Z==="")throw Error(`${$} name required`);let Q=NY$(Z);if(Q.length)throw Error(`invalid ${$} name - ${$} name ${Q}`)}function NY$($=""){if($==="")throw Error("name required");let Z=/^[-\w]+$/g;if($.match(Z)===null){for(let X of $.split(""))if(X.match(Z)===null)return`cannot contain '${X}'`}return""}});var nr=b((t8)=>{Object.defineProperty(t8,"__esModule",{value:!0});t8.wsconnect=t8.usernamePasswordAuthenticator=t8.UserAuthenticationExpiredError=t8.tokenAuthenticator=t8.TimeoutError=t8.syncIterator=t8.RequestError=t8.ProtocolError=t8.PermissionViolationError=t8.nuid=t8.Nuid=t8.NoRespondersError=t8.nkeys=t8.nkeyAuthenticator=t8.nanos=t8.MsgHdrsImpl=t8.millis=t8.Metric=t8.Match=t8.jwtAuthenticator=t8.InvalidSubjectError=t8.InvalidOperationError=t8.InvalidArgumentError=t8.headers=t8.hasWsProtocol=t8.errors=t8.Empty=t8.DrainingConnectionError=t8.delay=t8.deferred=t8.deadline=t8.credsAuthenticator=t8.createInbox=t8.ConnectionError=t8.ClosedConnectionError=t8.canonicalMIMEHeaderKey=t8.buildAuthenticator=t8.Bench=t8.backoff=t8.AuthorizationError=void 0;var F4=VG();Object.defineProperty(t8,"AuthorizationError",{enumerable:!0,get:function(){return F4.AuthorizationError}});Object.defineProperty(t8,"backoff",{enumerable:!0,get:function(){return F4.backoff}});Object.defineProperty(t8,"Bench",{enumerable:!0,get:function(){return F4.Bench}});Object.defineProperty(t8,"buildAuthenticator",{enumerable:!0,get:function(){return F4.buildAuthenticator}});Object.defineProperty(t8,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return F4.canonicalMIMEHeaderKey}});Object.defineProperty(t8,"ClosedConnectionError",{enumerable:!0,get:function(){return F4.ClosedConnectionError}});Object.defineProperty(t8,"ConnectionError",{enumerable:!0,get:function(){return F4.ConnectionError}});Object.defineProperty(t8,"createInbox",{enumerable:!0,get:function(){return F4.createInbox}});Object.defineProperty(t8,"credsAuthenticator",{enumerable:!0,get:function(){return F4.credsAuthenticator}});Object.defineProperty(t8,"deadline",{enumerable:!0,get:function(){return F4.deadline}});Object.defineProperty(t8,"deferred",{enumerable:!0,get:function(){return F4.deferred}});Object.defineProperty(t8,"delay",{enumerable:!0,get:function(){return F4.delay}});Object.defineProperty(t8,"DrainingConnectionError",{enumerable:!0,get:function(){return F4.DrainingConnectionError}});Object.defineProperty(t8,"Empty",{enumerable:!0,get:function(){return F4.Empty}});Object.defineProperty(t8,"errors",{enumerable:!0,get:function(){return F4.errors}});Object.defineProperty(t8,"hasWsProtocol",{enumerable:!0,get:function(){return F4.hasWsProtocol}});Object.defineProperty(t8,"headers",{enumerable:!0,get:function(){return F4.headers}});Object.defineProperty(t8,"InvalidArgumentError",{enumerable:!0,get:function(){return F4.InvalidArgumentError}});Object.defineProperty(t8,"InvalidOperationError",{enumerable:!0,get:function(){return F4.InvalidOperationError}});Object.defineProperty(t8,"InvalidSubjectError",{enumerable:!0,get:function(){return F4.InvalidSubjectError}});Object.defineProperty(t8,"jwtAuthenticator",{enumerable:!0,get:function(){return F4.jwtAuthenticator}});Object.defineProperty(t8,"Match",{enumerable:!0,get:function(){return F4.Match}});Object.defineProperty(t8,"Metric",{enumerable:!0,get:function(){return F4.Metric}});Object.defineProperty(t8,"millis",{enumerable:!0,get:function(){return F4.millis}});Object.defineProperty(t8,"MsgHdrsImpl",{enumerable:!0,get:function(){return F4.MsgHdrsImpl}});Object.defineProperty(t8,"nanos",{enumerable:!0,get:function(){return F4.nanos}});Object.defineProperty(t8,"nkeyAuthenticator",{enumerable:!0,get:function(){return F4.nkeyAuthenticator}});Object.defineProperty(t8,"nkeys",{enumerable:!0,get:function(){return F4.nkeys}});Object.defineProperty(t8,"NoRespondersError",{enumerable:!0,get:function(){return F4.NoRespondersError}});Object.defineProperty(t8,"Nuid",{enumerable:!0,get:function(){return F4.Nuid}});Object.defineProperty(t8,"nuid",{enumerable:!0,get:function(){return F4.nuid}});Object.defineProperty(t8,"PermissionViolationError",{enumerable:!0,get:function(){return F4.PermissionViolationError}});Object.defineProperty(t8,"ProtocolError",{enumerable:!0,get:function(){return F4.ProtocolError}});Object.defineProperty(t8,"RequestError",{enumerable:!0,get:function(){return F4.RequestError}});Object.defineProperty(t8,"syncIterator",{enumerable:!0,get:function(){return F4.syncIterator}});Object.defineProperty(t8,"TimeoutError",{enumerable:!0,get:function(){return F4.TimeoutError}});Object.defineProperty(t8,"tokenAuthenticator",{enumerable:!0,get:function(){return F4.tokenAuthenticator}});Object.defineProperty(t8,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return F4.UserAuthenticationExpiredError}});Object.defineProperty(t8,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return F4.usernamePasswordAuthenticator}});Object.defineProperty(t8,"wsconnect",{enumerable:!0,get:function(){return F4.wsconnect}})});var KT=b((LY$)=>{Object.defineProperty(LY$,"__esModule",{value:!0});LY$.PubHeaders=LY$.PriorityPolicy=LY$.ConsumerApiAction=LY$.PersistMode=LY$.StoreCompression=LY$.ReplayPolicy=LY$.AckPolicy=LY$.DeliverPolicy=LY$.StorageType=LY$.DiscardPolicy=LY$.RetentionPolicy=void 0;LY$.defaultConsumer=dU4;var mU4=nr();LY$.RetentionPolicy={Limits:"limits",Interest:"interest",Workqueue:"workqueue"};LY$.DiscardPolicy={Old:"old",New:"new"};LY$.StorageType={File:"file",Memory:"memory"};LY$.DeliverPolicy={All:"all",Last:"last",New:"new",StartSequence:"by_start_sequence",StartTime:"by_start_time",LastPerSubject:"last_per_subject"};LY$.AckPolicy={None:"none",All:"all",Explicit:"explicit",FlowControl:"flow_control",NotSet:""};LY$.ReplayPolicy={Instant:"instant",Original:"original"};LY$.StoreCompression={None:"none",S2:"s2"};LY$.PersistMode={Default:"default",Async:"async"};LY$.ConsumerApiAction={CreateOrUpdate:"",Update:"update",Create:"create"};LY$.PriorityPolicy={None:"none",Overflow:"overflow",PinnedClient:"pinned_client",Prioritized:"prioritized"};function dU4($,Z={}){return Object.assign({name:$,deliver_policy:LY$.DeliverPolicy.All,ack_policy:LY$.AckPolicy.Explicit,ack_wait:(0,mU4.nanos)(30000),replay_policy:LY$.ReplayPolicy.Instant},Z)}LY$.PubHeaders={MsgIdHdr:"Nats-Msg-Id",ExpectedStreamHdr:"Nats-Expected-Stream",ExpectedLastSeqHdr:"Nats-Expected-Last-Sequence",ExpectedLastMsgIdHdr:"Nats-Expected-Last-Msg-Id",ExpectedLastSubjectSequenceHdr:"Nats-Expected-Last-Subject-Sequence",ExpectedLastSubjectSequenceSubjectHdr:"Nats-Expected-Last-Subject-Sequence-Subject",MessageTTL:"Nats-TTL",Schedule:"Nats-Schedule",ScheduleTarget:"Nats-Schedule-Target",ScheduleSource:"Nats-Schedule-Source",ScheduleTTL:"Nats-Schedule-TTL",ScheduleTimeZone:"Nats-Schedule-Time-Zone",ScheduleRollup:"Nats-Schedule-Rollup",Scheduler:"Nats-Scheduler",ScheduleNext:"Nats-Schedule-Next"}});var L$1=b((PY$)=>{Object.defineProperty(PY$,"__esModule",{value:!0});PY$.ConsumerAPIImpl=void 0;var eU4=Fl(),$N4=v30(),lW=Ul(),BX=VG(),SB=KT();class EY$ extends eU4.BaseApiClientImpl{constructor($,Z){super($,Z)}async addUpdate($,Z,Q,X){if((0,lW.validateStreamName)($),Q=Q||{},Z.deliver_group&&Z.flow_control)throw BX.InvalidArgumentError.format(["flow_control","deliver_group"],"are mutually exclusive");if(Z.deliver_group&&Z.idle_heartbeat)throw BX.InvalidArgumentError.format(["idle_heartbeat","deliver_group"],"are mutually exclusive");if(zY$(Z)){let{min:B,ok:O}=this.nc.features.get(BX.Feature.JS_PRIORITY_GROUPS);if(!O)throw Error(`priority_groups require server ${B}`);if(Z.deliver_subject)throw BX.InvalidArgumentError.format("deliver_subject","cannot be set when using priority groups");ZN4(Z)}let Y={};if(Y.config=Z,Y.stream_name=$,Y.action=Q.action||SB.ConsumerApiAction.Create,Y.pedantic=Q.pedantic||!1,Y.config.durable_name)(0,lW.validateDurableName)(Y.config.durable_name);let J=this.nc,{min:G,ok:K}=J.features.get(BX.Feature.JS_NEW_CONSUMER_CREATE_API),W=Z.name===""?void 0:Z.name;if(W&&!K)throw BX.InvalidArgumentError.format("name",`requires server ${G}`);if(W)try{(0,lW.minValidation)("name",W)}catch(B){let O=B.message,D=O.indexOf("cannot contain");if(D!==-1)throw Error(`consumer 'name' ${O.substring(D)}`);throw B}let H,F="";if(Array.isArray(Z.filter_subjects)){let{min:B,ok:O}=J.features.get(BX.Feature.JS_MULTIPLE_CONSUMER_FILTER);if(!O)throw BX.InvalidArgumentError.format("filter_subjects",`requires server ${B}`);K=!1}if(Z.metadata){let{min:B,ok:O}=J.features.get(BX.Feature.JS_STREAM_CONSUMER_METADATA);if(!O)throw BX.InvalidArgumentError.format("metadata",`requires server ${B}`)}if(K)F=Z.name??Z.durable_name??"";if(F!==""){let B=Z.filter_subject??void 0;if(B===">")B=void 0;H=B!==void 0?`${this.prefix}.CONSUMER.CREATE.${$}.${F}.${B}`:`${this.prefix}.CONSUMER.CREATE.${$}.${F}`}else H=Z.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${$}.${Z.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${$}`;let U=X??Y.config;return await this._request(H,Y,{...Q,...this.requiredApiOpts(U)})}minConsumerApi($){if($.ack_policy===SB.AckPolicy.FlowControl)return 4;if(typeof $.pause_until==="string"&&$.pause_until!=="")return 1;if($.priority_policy!==void 0&&$.priority_policy!==SB.PriorityPolicy.None)return 1;if(typeof $.priority_timeout==="number"&&$.priority_timeout>0)return 1;if(Array.isArray($.priority_groups)&&$.priority_groups.length>0)return 1;return 0}requiredApiOpts($){if(!this.sendRequiredApiLevel())return{};let Z=this.minConsumerApi($);return Z>0?{minApiVersion:Z}:{}}add($,Z,Q){Q=Q||{};let X=SB.ConsumerApiAction.Create;if(typeof Q==="string")X=Q,Q={};let Y=Object.assign({},{action:X},Q);return this.addUpdate($,Z,Y)}async update($,Z,Q){let X=await this.info($,Z),Y=Q;return this.addUpdate($,Object.assign(X.config,Y),{action:SB.ConsumerApiAction.Update},Y)}async info($,Z){return(0,lW.validateStreamName)($),(0,lW.validateDurableName)(Z),await this._request(`${this.prefix}.CONSUMER.INFO.${$}.${Z}`)}async delete($,Z){return(0,lW.validateStreamName)($),(0,lW.validateDurableName)(Z),(await this._request(`${this.prefix}.CONSUMER.DELETE.${$}.${Z}`)).success}list($){(0,lW.validateStreamName)($);let Z=(X)=>{return X.consumers},Q=`${this.prefix}.CONSUMER.LIST.${$}`;return new $N4.ListerImpl(Q,Z,this)}pause($,Z,Q){let X=`${this.prefix}.CONSUMER.PAUSE.${$}.${Z}`,Y={pause_until:Q.toISOString()};return this._request(X,Y)}resume($,Z){return this.pause($,Z,new Date(0))}unpin($,Z,Q){let X=`${this.prefix}.CONSUMER.UNPIN.${$}.${Z}`;return this._request(X,{group:Q})}async reset($,Z,Q){(0,lW.validateStreamName)($),(0,lW.validateDurableName)(Z);let X=this.nc,{min:Y,ok:J}=X.features.get(BX.Feature.JS_CONSUMER_RESET);if(!J)throw Error(`consumer reset requires server ${Y}`);if(typeof Q==="number"&&(!Number.isInteger(Q)||Q<0))throw BX.InvalidArgumentError.format("seq","must be a non-negative integer");let G=`${this.prefix}.CONSUMER.RESET.${$}.${Z}`,K=typeof Q==="number"?{seq:Q}:void 0;return await this._request(G,K)}}PY$.ConsumerAPIImpl=EY$;function zY$($){let Z=$;return Z&&Z.priority_groups!==void 0||Z.priority_policy!==void 0}function ZN4($){if(zY$($)){if(!Array.isArray($.priority_groups))throw BX.InvalidArgumentError.format(["priority_groups"],"must be an array");if($.priority_groups.length===0)throw BX.InvalidArgumentError.format(["priority_groups"],"must have at least one group");if($.priority_groups.forEach((Z)=>{if((0,lW.minValidation)("priority_group",Z),Z.length>16)throw BX.errors.InvalidArgumentError.format("group","must be 16 characters or less")}),$.priority_policy!==SB.PriorityPolicy.None&&$.priority_policy!==SB.PriorityPolicy.Overflow&&$.priority_policy!==SB.PriorityPolicy.PinnedClient&&$.priority_policy!==SB.PriorityPolicy.Prioritized)throw BX.InvalidArgumentError.format(["priority_policy"],"must be 'none', 'prioritized', 'overflow', or 'pinned_client'")}}});var w$1=b((RY$)=>{Object.defineProperty(RY$,"__esModule",{value:!0});RY$.JsMsgImpl=RY$.ACK=void 0;RY$.toJsMsg=GN4;RY$.parseInfo=AY$;var Nl=VG();RY$.ACK=Uint8Array.of(43,65,67,75);var QN4=Uint8Array.of(45,78,65,75),tr=Uint8Array.of(43,87,80,73),XN4=Uint8Array.of(43,78,88,84),YN4=Uint8Array.of(43,84,69,82,77),JN4=Uint8Array.of(32);function GN4($,Z=5000){return new D$1($,Z)}function AY$($){let Z=$.split(".");if(Z.length===9)Z.splice(2,0,"_","");if(Z.length<11||Z[0]!=="$JS"||Z[1]!=="ACK")throw Error("unable to parse delivery info - not a jetstream message");let Q={};return Q.domain=Z[2]==="_"?"":Z[2],Q.account_hash=Z[3],Q.stream=Z[4],Q.consumer=Z[5],Q.deliveryCount=parseInt(Z[6],10),Q.redelivered=Q.deliveryCount>1,Q.streamSequence=parseInt(Z[7],10),Q.deliverySequence=parseInt(Z[8],10),Q.timestampNanos=parseInt(Z[9],10),Q.pending=parseInt(Z[10],10),Q}function KN4($){let Z=$.split(".");if(Z.length===9)Z.splice(2,0,"_","");if(Z.length<11||Z[0]!=="$JS"||Z[1]!=="ACK")throw Error("unable to parse delivery info - not a jetstream message");return BigInt(Z[9])}class D$1{msg;di;didAck;timeout;constructor($,Z){this.msg=$,this.didAck=!1,this.timeout=Z}get subject(){return this.msg.subject}get sid(){return this.msg.sid}get data(){return this.msg.data}get headers(){return this.msg.headers}get info(){if(!this.di)this.di=AY$(this.reply);return this.di}get redelivered(){return this.info.deliveryCount>1}get reply(){return this.msg.reply||""}get seq(){return this.info.streamSequence}get time(){let $=(0,Nl.millis)(this.info.timestampNanos);return new Date($)}get timestamp(){return this.time.toISOString()}get timestampNanos(){return KN4(this.reply)}doAck($){if(!this.didAck)this.didAck=!this.isWIP($),this.msg.respond($)}isWIP($){return $.length===4&&$[0]===tr[0]&&$[1]===tr[1]&&$[2]===tr[2]&&$[3]===tr[3]}async ackAck($){let Z=(0,Nl.deferred)();if(!this.didAck)if(this.didAck=!0,this.msg.reply){$=$||{},$.timeout=$.timeout||this.timeout;let X=this.msg.publisher,Y=!X.options?.noAsyncTraces,J=new Nl.RequestOne(X.muxSubscriptions,this.msg.reply,{timeout:$.timeout},Y);X.request(J);try{X.publish(this.msg.reply,RY$.ACK,{reply:`${X.muxSubscriptions.baseInbox}${J.token}`})}catch(G){J.cancel(G)}try{await Promise.race([J.timer,J.deferred]),Z.resolve(!0)}catch(G){J.cancel(G),Z.reject(G)}}else Z.resolve(!1);else Z.resolve(!1);return Z}ack(){this.doAck(RY$.ACK)}nak($){let Z=QN4;if($)Z=new TextEncoder().encode(`-NAK ${JSON.stringify({delay:(0,Nl.nanos)($)})}`);this.doAck(Z)}working(){this.doAck(tr)}next($,Z={batch:1}){let Q={};if(Q.batch=Z.batch||1,Q.no_wait=Z.no_wait||!1,Z.expires&&Z.expires>0)Q.expires=(0,Nl.nanos)(Z.expires);let X=new TextEncoder().encode(JSON.stringify(Q)),Y=Nl.DataBuffer.concat(XN4,JN4,X),J=$?{reply:$}:void 0;this.msg.respond(Y,J)}term($=""){let Z=YN4;if($?.length>0)Z=new TextEncoder().encode(`+TERM ${$}`);this.doAck(Z)}json(){return this.msg.json()}string(){return this.msg.string()}}RY$.JsMsgImpl=D$1});var xY$=b((_Y$)=>{Object.defineProperty(_Y$,"__esModule",{value:!0});_Y$.PullConsumerImpl=_Y$.PullConsumerMessagesImpl=_Y$.PullConsumerType=void 0;_Y$.isOverflowOptions=or;_Y$.isPrioritizedOptions=x30;_Y$.validateOverflowPullOptions=SY$;_Y$.validatePrioritizedPullOptions=CY$;var Q5=VG(),FN4=w$1(),MY$=KT(),IY$=VB(),VY$=Ul();_Y$.PullConsumerType={Unset:"",Consume:"consume",Fetch:"fetch"};function or($){let Z=$;return Z&&typeof Z.group==="string"||typeof Z.min_pending==="number"||typeof Z.min_ack_pending==="number"}function x30($){let Z=$;return Z&&typeof Z.group==="string"&&typeof Z.priority==="number"}class f30 extends Q5.QueuedIteratorImpl{consumer;opts;sub;monitor;pending;isConsume;callback;listeners;statusIterator;abortOnMissingResource;bind;inboxPrefix;inbox;cancelables;inReset;closeListener;isPinned;isPriority;natsPinId;constructor($,Z,Q=!1){super();if(this.consumer=$,this.isConsume=Q,this.cancelables=[],this.inboxPrefix=(0,Q5.createInbox)(this.consumer.api.nc.options.inboxPrefix),this.inbox=`${this.inboxPrefix}.${this.consumer.serial}`,this.inReset=!1,this.isPinned=!1,this.isPriority=!1,this.natsPinId="",this.consumer.ordered){if(or(Z))throw Q5.errors.InvalidArgumentError.format(["group","min_pending","min_ack_pending"],"cannot be specified for ordered consumers");if(this.consumer.orderedConsumerState===void 0){let Y={},J=$.opts;Y.namePrefix=J.name_prefix??`oc_${Q5.nuid.next()}`,Y.opts=J,Y.cursor={stream_seq:1,deliver_seq:0};let G=$._info.config.opt_start_seq||0;Y.cursor.stream_seq=G>0?G-1:0,Y.createFails=0,this.consumer.orderedConsumerState=Y}}let X=Z;if(this.opts=this.parseOptions(Z,this.isConsume),this.callback=X.callback||null,this.noIterator=typeof this.callback==="function",this.monitor=null,this.pending={msgs:0,bytes:0,requests:0},this.listeners=[],this.abortOnMissingResource=X.abort_on_missing_resource===!0,this.bind=X.bind===!0,X.group){let{min_pending:Y,min_ack_pending:J}=X;this.isPinned=Y===void 0&&J===void 0;let{priority:G}=X;this.isPriority=typeof G==="number"}this.closeListener={connectionClosedCallback:()=>{this._push(()=>{this.stop()})}},this.consumer.api.nc.addCloseListener(this.closeListener),this.start()}start(){let{max_messages:$,max_bytes:Z,idle_heartbeat:Q,threshold_bytes:X,threshold_messages:Y}=this.opts;if(this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(J,G)=>{if(J){this.stop(J);return}if(this.monitor?.work(),this.consumer.ordered?G.subject.indexOf(this?.inboxPrefix)===0:G.subject===this.inbox){if(G.subject!==this.sub.getSubject())return;let W=new IY$.JetStreamStatus(G),H=W.parseHeartbeat();if(H){this.notify(H);return}let{code:F,description:U}=W,{msgsLeft:N,bytesLeft:B}=W.parseDiscard();if(N&&N>0||B&&B>0)this.pending.msgs-=N,this.pending.bytes-=B,this.pending.requests--,this.notify({type:"discard",messagesLeft:N,bytesLeft:B});switch(F){case 400:this.stop(W.toError());return;case 409:{let O=this.handle409(W);if(O){this.stop(O);return}if(W.isMessageSizeExceedsMaxBytes()&&this.yields.length>0)break;return}case 423:this.natsPinId="",this.notify({type:"consumer_unpinned"});break;case 503:if(this.notify({type:"no_responders",code:F}),this.consumer.ordered){let O=this.consumer.orderedConsumerState;O.needsReset=!0}if(!this.isConsume){this.stop(W.toError());return}break;default:this.notify({type:"debug",code:F,description:U})}}else{let W=(0,FN4.toJsMsg)(G,this.consumer.api.timeout);if(this.isPinned){let H=W?.headers?.get("Nats-Pin-Id");if(H&&this.natsPinId==="")this.natsPinId=H,this.notify({type:"consumer_pinned",id:H})}if(this.consumer.ordered){let H=this.consumer.orderedConsumerState.cursor,F=W.info.deliverySequence,U=W.info.streamSequence,N=H.deliver_seq+1;if(F!==N){this.reset();return}H.deliver_seq=F,H.stream_seq=U}if(this._push(W),this.received++,this.pending.msgs)this.pending.msgs--;if(this.pending.bytes)this.pending.bytes-=G.size()}if(this.pending.msgs===0&&this.pending.bytes===0)this.pending.requests=0;if(this.isConsume){if($&&this.pending.msgs<=Y||Z&&this.pending.bytes<=X){let W=this.pullOptions();this.pull(W)}}else if(this.pending.requests===0)this._push(()=>{this.stop()})}}),Q)this.monitor=new Q5.IdleHeartbeatMonitor(Q,(J)=>{if(this.notify({type:"heartbeats_missed",count:J}),!this.isConsume&&!this.consumer.ordered)return this.stop(new IY$.JetStreamError("heartbeats missed")),!0;return this.resetPending().then(()=>{}).catch(()=>{}),!1},{maxOut:2});(async()=>{let J=this.consumer.api.nc.status();this.statusIterator=J;for await(let G of J)switch(G.type){case"disconnect":this.monitor?.cancel();break;case"reconnect":this.resetPending().then((K)=>{if(K)this.monitor?.restart()}).catch(()=>{});break;default:}})(),this.sub.closed.then(()=>{if(this.sub.isDraining())this._push(()=>{this.stop()})}),this.pull(this.pullOptions())}handle409($){let{code:Z,description:Q}=$;if($.isConsumerDeleted())this.notify({type:"consumer_deleted",code:Z,description:Q});else if($.isExceededLimit())this.notify({type:"exceeded_limits",code:Z,description:Q});if(!this.isConsume)return $.toError();if($.isConsumerDeleted()&&this.abortOnMissingResource)return $.toError();return null}reset(){this.monitor?.cancel();let $=this.consumer.orderedConsumerState,{name:Z}=this.consumer._info?.config;if(Z)this.notify({type:"reset",name:Z}),this.consumer.api.delete(this.consumer.stream,Z).catch(()=>{});let Q=this.consumer.getConsumerOpts();this.inbox=`${this.inboxPrefix}.${this.consumer.serial}`,$.cursor.deliver_seq=0,this.consumer.name=Q.name,this.consumer.api.nc._resub(this.sub,this.inbox),this.consumer.api.add(this.consumer.stream,Q).then((X)=>{$.createFails=0,this.consumer._info=X,this.notify({type:"ordered_consumer_recreated",name:X.name}),this.monitor?.restart(),this.pull(this.pullOptions())}).catch((X)=>{if($.createFails++,X.message==="stream not found"){if(this.notify({type:"stream_not_found",consumerCreateFails:$.createFails,name:this.consumer.stream}),this.abortOnMissingResource){this.stop(X);return}}if($.createFails>=30&&this.received===0)this.stop(X);let Y=(0,Q5.backoff)(),J=(0,Q5.delay)(Y.backoff($.createFails));J.then(()=>{let G=this.cancelables.indexOf(J);if(G!==-1)this.cancelables=this.cancelables.splice(G,G);if(!this.done)this.reset()}).catch((G)=>{}),this.cancelables.push(J)})}_push($){if(!this.callback)super.push($);else{let Z=typeof $==="function"?$:null;try{if(!Z){let Q=$;this.callback(Q)}else Z()}catch(Q){this.stop(Q)}}}notify($){if(this.listeners.length>0)(()=>{this.listeners.forEach((Z)=>{let Q=Z;if(!Q.done)Q.push($)})})()}async resetPending(){if(this.inReset)return Promise.resolve(!0);this.inReset=!0;let Z=await(this.bind?this.resetPendingNoInfo():this.resetPendingWithInfo());return this.inReset=!1,Z}resetPendingNoInfo(){return this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),Promise.resolve(!0)}async resetPendingWithInfo(){let $=0,Z=0,Q=(0,Q5.backoff)([this.opts.expires||30000]),X=0;while(!0){if(this.done)return!1;if(this.consumer.api.nc.isClosed())return!1;try{return await this.consumer.info(),$=0,this.pending.msgs=0,this.pending.bytes=0,this.pending.requests=0,this.pull(this.pullOptions()),!0}catch(Y){if(Y instanceof Q5.errors.ClosedConnectionError)return this.stop(Y),!1;if(Y.message==="stream not found"){if(Z++,this.notify({type:"stream_not_found",name:this.consumer.stream}),!this.isConsume||this.abortOnMissingResource)return this.stop(Y),!1}else if(Y.message==="consumer not found"){if($++,this.notify({type:"consumer_not_found",name:this.consumer.name,stream:this.consumer.stream,count:$}),!this.isConsume||this.abortOnMissingResource){if(this.consumer.ordered){let K=this.consumer.orderedConsumerState;K.needsReset=!0}return this.stop(Y),!1}if(this.consumer.ordered)return this.reset(),!1}else $=0,Z=0;let J=Q.backoff(X),G=(0,Q5.delay)(J);await Promise.race([G,this.consumer.api.nc.closed()]),G.cancel(),X++}}}pull($){this.pending.bytes+=$.max_bytes??0,this.pending.msgs+=$.batch??0,this.pending.requests++;let Z=this.consumer.api.nc,Q=`${this.consumer.api.prefix}.CONSUMER.MSG.NEXT.${this.consumer.stream}.${this.consumer._info.name}`;this._push(()=>{Z.publish(Q,JSON.stringify($),{reply:this.inbox}),this.notify({type:"next",options:$})})}pullOptions(){let $=this.opts.max_messages-this.pending.msgs,Z=this.opts.max_bytes-this.pending.bytes,Q=(0,Q5.nanos)(this.opts.idle_heartbeat),X=(0,Q5.nanos)(this.opts.expires),Y={batch:$,max_bytes:Z,idle_heartbeat:Q,expires:X};if(this.isPinned&&this.natsPinId!=="")Y.id=this.natsPinId;if(or(this.opts)){if(Y.group=this.opts.group,this.opts.min_pending)Y.min_pending=this.opts.min_pending;if(this.opts.min_ack_pending)Y.min_ack_pending=this.opts.min_ack_pending}if(x30(this.opts))Y.group=this.opts.group,Y.priority=this.opts.priority;return Y}close(){return this.stop(),this.iterClosed}closed(){return this.iterClosed}clearTimers(){this.monitor?.cancel(),this.monitor=null}stop($){if(this.done)return;this.consumer.api.nc.removeCloseListener(this.closeListener),this.sub?.unsubscribe(),this.clearTimers(),this.statusIterator?.stop(),this._push(()=>{super.stop($),this.listeners.forEach((Z)=>{Z.stop()})})}parseOptions($,Z=!1){let Q=$||{};if(Q.max_messages=Q.max_messages||0,Q.max_bytes=Q.max_bytes||0,Q.max_messages!==0&&Q.max_bytes!==0)throw Q5.errors.InvalidArgumentError.format(["max_messages","max_bytes"],"are mutually exclusive");if(Q.max_messages===0)Q.max_messages=100;if(Q.expires=Q.expires||30000,Q.expires<1000)throw Q5.errors.InvalidArgumentError.format("expires","must be at least 1000ms");if(Q.idle_heartbeat=Q.idle_heartbeat||Q.expires/2,Q.idle_heartbeat=Q.idle_heartbeat>30000?30000:Q.idle_heartbeat,Q.idle_heartbeat<500)Q.idle_heartbeat=500;if(Z){let X=Math.round(Q.max_messages*0.75)||1;Q.threshold_messages=Q.threshold_messages||X;let Y=Math.round(Q.max_bytes*0.75)||1;Q.threshold_bytes=Q.threshold_bytes||Y}if(or($)){let{min:X,ok:Y}=this.consumer.api.nc.features.get(Q5.Feature.JS_PRIORITY_GROUPS);if(!Y)throw Error(`priority_groups require server ${X}`);if(SY$($),$.group)Q.group=$.group;if($.min_ack_pending)Q.min_ack_pending=$.min_ack_pending;if($.min_pending)Q.min_pending=$.min_pending}else if(x30($)){if(CY$($),$.group)Q.group=$.group;if(typeof $.priority==="number")Q.priority=$.priority}return Q}status(){let $=new Q5.QueuedIteratorImpl;return this.listeners.push($),$}}_Y$.PullConsumerMessagesImpl=f30;class kY${api;_info;stream;name;opts;type;messages;ordered;serial;orderedConsumerState;constructor($,Z,Q=null){this.api=$,this._info=Z,this.name=Z.name,this.stream=Z.stream_name,this.ordered=Q!==null,this.opts=Q||{},this.serial=1,this.type=_Y$.PullConsumerType.Unset}debug(){console.log({serial:this.serial,cursor:this.orderedConsumerState?.cursor})}isPullConsumer(){return!0}isPushConsumer(){return!1}consume($={max_messages:100,expires:30000}){if($={...$},this.ordered){if($.bind)return Promise.reject(Q5.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===_Y$.PullConsumerType.Fetch)return Promise.reject(new Q5.errors.InvalidOperationError("ordered consumer initialized as fetch"));if(this.type===_Y$.PullConsumerType.Consume)return Promise.reject(new Q5.errors.InvalidOperationError("ordered consumer doesn't support concurrent consume"));this.type=_Y$.PullConsumerType.Consume}return Promise.resolve(new f30(this,$,!0))}async fetch($={max_messages:100,expires:30000}){if($={...$},this.ordered){if($.group)return Promise.reject(Q5.errors.InvalidArgumentError.format("group","ordered consumers don't support priority groups"));if($.bind)return Promise.reject(Q5.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===_Y$.PullConsumerType.Consume)return Promise.reject(new Q5.errors.InvalidOperationError("ordered consumer already initialized as consume"));if(this.messages?.done===!1)return Promise.reject(new Q5.errors.InvalidOperationError("ordered consumer doesn't support concurrent fetch"));if(this.ordered){if(this.orderedConsumerState?.cursor?.deliver_seq)this._info.config.opt_start_seq=this.orderedConsumerState?.cursor.stream_seq+1;if(this.orderedConsumerState?.needsReset===!0)await this._reset()}this.type=_Y$.PullConsumerType.Fetch}let Z=new f30(this,$);if(this.ordered)this.messages=Z;return Promise.resolve(Z)}async next($={expires:30000}){$={...$};let Z=$;Z.max_messages=1;let Q=await this.fetch(Z);try{for await(let X of Q)return X}catch(X){return Promise.reject(X)}return null}delete(){let{stream_name:$,name:Z}=this._info;return this.api.delete($,Z)}getConsumerOpts(){let $=this.orderedConsumerState;this.serial++,this.name=`${$.namePrefix}_${this.serial}`;let Z=Object.assign({},this._info.config,{name:this.name,deliver_policy:MY$.DeliverPolicy.StartSequence,opt_start_seq:$.cursor.stream_seq+1,ack_policy:MY$.AckPolicy.None,inactive_threshold:(0,Q5.nanos)(300000),num_replicas:1});return delete Z.metadata,Z}async _reset(){if(this.messages===void 0)throw Error("not possible to reset");this.delete().catch(()=>{});let $=this.getConsumerOpts(),Z=await this.api.add(this.stream,$);return this._info=Z,Z}async info($=!1){if($)return Promise.resolve(this._info);let{stream_name:Z,name:Q}=this._info;return this._info=await this.api.info(Z,Q),this._info}}_Y$.PullConsumerImpl=kY$;function SY$($){if(or($)){if((0,VY$.minValidation)("group",$.group),$.group.length>16)throw Q5.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{min_pending:Z,min_ack_pending:Q}=$;if(Z&&typeof Z!=="number")throw Q5.errors.InvalidArgumentError.format(["min_pending"],"must be a number");if(Q&&typeof Q!=="number")throw Q5.errors.InvalidArgumentError.format(["min_ack_pending"],"must be a number")}}function CY$($){if(x30($)){if((0,VY$.minValidation)("group",$.group),$.group.length>16)throw Q5.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{priority:Z}=$;if(Z&&typeof Z!=="number")throw Q5.errors.InvalidArgumentError.format(["priority"],"must be a number")}}});var hY$=b((yY$)=>{Object.defineProperty(yY$,"__esModule",{value:!0});yY$.PushConsumerImpl=yY$.PushConsumerMessagesImpl=void 0;var DN4=w$1(),fY$=KT(),j$1=eP(),HY=VG(),wN4=VB();class E$1 extends HY.QueuedIteratorImpl{consumer;sub;monitor;listeners;abortOnMissingResource;callback;ordered;cursor;namePrefix;deliverPrefix;serial;createFails;statusIterator;cancelables;constructor($,Z={},Q={}){super();if(this.consumer=$,this.monitor=null,this.listeners=[],this.cancelables=[],this.abortOnMissingResource=Z.abort_on_missing_resource===!0,this.callback=Z.callback||null,this.noIterator=this.callback!==null,this.namePrefix=null,this.deliverPrefix=null,this.ordered=Q.ordered===!0,this.serial=1,this.ordered){this.namePrefix=Q.name_prefix??`oc_${HY.nuid.next()}`,this.deliverPrefix=Q.deliver_prefix??(0,HY.createInbox)(this.consumer.api.nc.options.inboxPrefix),this.cursor={stream_seq:1,deliver_seq:0};let X=$._info.config.opt_start_seq||0;this.cursor.stream_seq=X>0?X-1:0,this.createFails=0}this.start()}reset(){let{name:$}=this.consumer._info?.config;if($)this.consumer.api.delete(this.consumer.stream,$).catch(()=>{});let Z=this.getConsumerOpts();this.cursor.deliver_seq=0,this.consumer.name=Z.name,this.consumer.serial=this.serial,this.consumer.api.nc._resub(this.sub,Z.deliver_subject),this.consumer.api.add(this.consumer.stream,Z).then((Q)=>{this.createFails=0,this.consumer._info=Q,this.notify({type:"ordered_consumer_recreated",name:Q.name})}).catch((Q)=>{if(this.createFails++,Q.message==="stream not found"){if(this.notify({type:"stream_not_found",name:this.consumer.stream,consumerCreateFails:this.createFails}),this.abortOnMissingResource){this.stop(Q);return}}if(this.createFails>=30&&this.received===0)this.stop(Q);let X=(0,HY.backoff)(),Y=(0,HY.delay)(X.backoff(this.createFails));Y.then(()=>{if(!this.done)this.reset()}).catch(()=>{}).finally(()=>{let J=this.cancelables.indexOf(Y);if(J!==-1)this.cancelables=this.cancelables.splice(J,J)}),this.cancelables.push(Y)})}getConsumerOpts(){let $=Object.assign({},this.consumer._info.config);this.serial++;let Z=`${this.namePrefix}_${this.serial}`;return Object.assign($,{name:Z,deliver_policy:fY$.DeliverPolicy.StartSequence,opt_start_seq:this.cursor.stream_seq+1,ack_policy:fY$.AckPolicy.None,inactive_threshold:(0,HY.nanos)(300000),num_replicas:1,flow_control:!0,idle_heartbeat:(0,HY.nanos)(30000),deliver_subject:`${this.deliverPrefix}.${this.serial}`})}closed(){return this.iterClosed}close(){return this.stop(),this.iterClosed}stop($){if(this.done)return;this.statusIterator?.stop(),this.monitor?.cancel(),this.monitor=null,this.cancelables.forEach((Z)=>{Z.cancel()}),Promise.all(this.cancelables).then(()=>{this.cancelables=[]}).catch(()=>{}).finally(()=>{this._push(()=>{super.stop($),this.listeners.forEach((Z)=>{Z.stop()})})})}_push($){if(!this.callback)super.push($);else{let Z=typeof $==="function"?$:null;try{if(!Z){let Q=$;this.received++,this.callback(Q),this.processed++}else Z()}catch(Q){this.stop(Q)}}}status(){let $=new HY.QueuedIteratorImpl;return this.listeners.push($),$}start(){let{deliver_subject:$,deliver_group:Z,idle_heartbeat:Q}=this.consumer._info.config;if(!$)throw Error("bad consumer info");if(Q){let X=(0,HY.millis)(Q);this.monitor=new HY.IdleHeartbeatMonitor(X,(Y)=>{if(this.notify({type:"heartbeats_missed",count:Y}),this.ordered)this.reset();return!1},{maxOut:2}),(async()=>{this.statusIterator=this.consumer.api.nc.status();for await(let Y of this.statusIterator)switch(Y.type){case"disconnect":this.monitor?.cancel();break;case"reconnect":this.monitor?.restart();break;default:}})()}this.sub=this.consumer.api.nc.subscribe($,{queue:Z,callback:(X,Y)=>{if(X){this.stop(X);return}if(this.monitor?.work(),this.ordered?Y.subject.indexOf(this?.deliverPrefix)===0:Y.subject===$){if(Y.subject!==this.sub.getSubject())return;let G=new wN4.JetStreamStatus(Y);if(G.isFlowControlRequest()){this._push(()=>{Y.respond(),this.notify({type:"flow_control"})});return}if(G.isIdleHeartbeat()){let H=parseInt(Y.headers?.get(j$1.JsHeaders.LastConsumerSeqHdr)||"0"),F=parseInt(Y.headers?.get(j$1.JsHeaders.LastStreamSeqHdr)??"0");this.notify({type:"heartbeat",lastStreamSequence:F,lastConsumerSequence:H});let U=Y.headers?.get(j$1.JsHeaders.ConsumerStalledHdr);if(typeof U==="string"&&U!=="")Y.publisher.publish(U,HY.Empty);return}let{code:K,description:W}=G;if(G.isConsumerDeleted())this.notify({type:"consumer_deleted",code:K,description:W});if(this.abortOnMissingResource){this._push(()=>{this.stop(G.toError())});return}}else{let G=(0,DN4.toJsMsg)(Y);if(this.ordered){let K=G.info.deliverySequence;if(K!==this.cursor.deliver_seq+1){this.reset();return}this.cursor.deliver_seq=K,this.cursor.stream_seq=G.info.streamSequence}this._push(G)}}}),this.sub.closed.then(()=>{this._push(()=>{this.stop()})}),this.closed().then(()=>{this.sub?.unsubscribe()})}notify($){if(this.listeners.length>0)(()=>{this.listeners.forEach((Z)=>{let Q=Z;if(!Q.done)Q.push($)})})()}}yY$.PushConsumerMessagesImpl=E$1;class bY${api;_info;stream;name;bound;ordered;started;serial;opts;constructor($,Z,Q={}){if(this.api=$,this._info=Z,this.stream=Z.stream_name,this.name=Z.name,this.bound=Q.bound===!0,this.started=!1,this.opts=Q,this.serial=0,this.ordered=Q.ordered||!1,this.ordered)this.serial=1}consume($={}){if($={...$},this.started)return Promise.reject(new HY.errors.InvalidOperationError("consumer already started"));if(!this._info.config.deliver_subject)return Promise.reject(Error("deliver_subject is not set, not a push consumer"));if(!this._info.config.deliver_group&&this._info.push_bound)return Promise.reject(new HY.errors.InvalidOperationError("consumer is already bound"));let Z=new E$1(this,$,this.opts);return this.started=!0,Z.closed().then(()=>{this.started=!1}),Promise.resolve(Z)}delete(){if(this.bound)return Promise.reject(new HY.errors.InvalidOperationError("bound consumers cannot delete"));let{stream_name:$,name:Z}=this._info;return this.api.delete($,Z)}async info($){if(this.bound)return Promise.reject(new HY.errors.InvalidOperationError("bound consumers cannot info"));if($)return Promise.resolve(this._info);let Z=await this.api.info(this.stream,this.name);return this._info=Z,Z}isPullConsumer(){return!1}isPushConsumer(){return!0}}yY$.PushConsumerImpl=bY$});var pY$=b((dY$)=>{Object.defineProperty(dY$,"__esModule",{value:!0});dY$.StreamsImpl=dY$.StoredMsgImpl=dY$.StreamAPIImpl=dY$.StreamImpl=dY$.ConsumersImpl=void 0;dY$.convertStreamSourceDomain=rr;var TZ=VG(),EN4=Fl(),uY$=v30(),cW=Ul(),lY$=eP(),kG=KT(),z$1=xY$(),P$1=L$1(),T$1=hY$(),cY$=VB();function rr($){if($===void 0)return;let{domain:Z}=$;if(Z===void 0)return $;let Q=Object.assign({},$);if(delete Q.domain,Z==="")return Q;if(Q.external)throw TZ.InvalidArgumentError.format(["domain","external"],"are mutually exclusive");return Q.external={api:`$JS.${Z}.API`},Q}class b30{api;notified;constructor($){this.api=$,this.notified=!1}checkVersion(){let $=this.api.nc.features.get(TZ.Feature.JS_SIMPLIFICATION);if(!$.ok)return Promise.reject(Error(`consumers framework is only supported on servers ${$.min} or better`));return Promise.resolve()}async getPushConsumer($,Z){if(await this.checkVersion(),(0,cW.minValidation)("stream",$),typeof Z==="string"){(0,cW.minValidation)("name",Z);let Q=await this.api.info($,Z);if(typeof Q.config.deliver_subject!=="string")return Promise.reject(Error("not a push consumer"));return new T$1.PushConsumerImpl(this.api,Q)}else if(Z===void 0)return this.getOrderedPushConsumer($);else if((0,lY$.isOrderedPushConsumerOptions)(Z)){let Q=Z;return this.getOrderedPushConsumer($,Q)}return Promise.reject(Error("unsupported push consumer type"))}async getOrderedPushConsumer($,Z={}){Z=Object.assign({},Z);let{name_prefix:Q,deliver_prefix:X,filter_subjects:Y}=Z;if(delete Z.deliver_prefix,delete Z.name_prefix,delete Z.filter_subjects,typeof Z.opt_start_seq==="number")Z.deliver_policy=kG.DeliverPolicy.StartSequence;if(typeof Z.opt_start_time==="string")Z.deliver_policy=kG.DeliverPolicy.StartTime;Q=Q||`oc_${TZ.nuid.next()}`,(0,cW.minValidation)("name_prefix",Q),X=X||(0,TZ.createInbox)(this.api.getOptions().watcherPrefix);let J=Object.assign({},Z);if(J.ack_policy=kG.AckPolicy.None,J.inactive_threshold=(0,TZ.nanos)(300000),J.num_replicas=1,J.max_deliver=1,J.flow_control=!0,J.idle_heartbeat=(0,TZ.nanos)(30000),Array.isArray(Y))J.filter_subjects=Y;if(typeof Y==="string")J.filter_subject=Y;if(typeof J.filter_subjects>"u"&&typeof J.filter_subject>"u")J.filter_subject=">";J.name=`${Q}_1`,J.deliver_subject=`${X}.1`;let G=await this.api.add($,J),K={name_prefix:Q,deliver_prefix:X,ordered:!0};return new T$1.PushConsumerImpl(this.api,G,K)}getBoundPushConsumer($){if((0,lY$.isBoundPushConsumerOptions)($)){let Z={config:$};return Promise.resolve(new T$1.PushConsumerImpl(this.api,Z,{bound:!0}))}else return Promise.reject(TZ.errors.InvalidArgumentError.format("deliver_subject","is required"))}async get($,Z){if(await this.checkVersion(),typeof Z==="string"){let Q=await this.api.info($,Z);if(typeof Q.config.deliver_subject==="string")return Promise.reject(Error("not a pull consumer"));else return new z$1.PullConsumerImpl(this.api,Q)}else return this.ordered($,Z)}getConsumerFromInfo($){if(typeof $.config.deliver_subject==="string")throw Error("not a pull consumer");return new z$1.PullConsumerImpl(this.api,$)}async ordered($,Z={}){await this.checkVersion();let Q=this.api;if(await new A$1(Q.nc,Q.opts).info($),typeof Z.name_prefix==="string")(0,cW.minValidation)("name_prefix",Z.name_prefix);Z.name_prefix=Z.name_prefix||TZ.nuid.next();let J={name:`${Z.name_prefix}_1`,deliver_policy:kG.DeliverPolicy.StartSequence,opt_start_seq:Z.opt_start_seq||1,ack_policy:kG.AckPolicy.None,inactive_threshold:(0,TZ.nanos)(300000),num_replicas:1,max_deliver:1,mem_storage:!0};if(Z.headers_only===!0)J.headers_only=!0;if(Array.isArray(Z.filter_subjects))J.filter_subjects=Z.filter_subjects;if(typeof Z.filter_subjects==="string")J.filter_subject=Z.filter_subjects;if(Z.replay_policy)J.replay_policy=Z.replay_policy;if(J.deliver_policy=Z.deliver_policy||kG.DeliverPolicy.StartSequence,Z.deliver_policy===kG.DeliverPolicy.All||Z.deliver_policy===kG.DeliverPolicy.LastPerSubject||Z.deliver_policy===kG.DeliverPolicy.New||Z.deliver_policy===kG.DeliverPolicy.Last)delete J.opt_start_seq,J.deliver_policy=Z.deliver_policy;if(J.deliver_policy===kG.DeliverPolicy.LastPerSubject){if(typeof J.filter_subjects>"u"&&typeof J.filter_subject>"u")J.filter_subject=">"}if(Z.opt_start_time)delete J.opt_start_seq,J.deliver_policy=kG.DeliverPolicy.StartTime,J.opt_start_time=Z.opt_start_time;if(Z.inactive_threshold)J.inactive_threshold=(0,TZ.nanos)(Z.inactive_threshold);let G=await this.api.add($,J);return Promise.resolve(new z$1.PullConsumerImpl(this.api,G,Z))}}dY$.ConsumersImpl=b30;class ar{api;_info;constructor($,Z){this.api=$,this._info=Z}get name(){return this._info.config.name}alternates(){return this.info().then(($)=>{return $.alternates?$.alternates:[]})}async best(){if(await this.info(),this._info.alternates){let $=await this.api.info(this._info.alternates[0].name);return new ar(this.api,$)}else return this}info($=!1,Z){if($)return Promise.resolve(this._info);return this.api.info(this.name,Z).then((Q)=>{return this._info=Q,this._info})}getConsumer($){return new b30(new P$1.ConsumerAPIImpl(this.api.nc,this.api.opts)).get(this.name,$)}getPushConsumer($){return new b30(new P$1.ConsumerAPIImpl(this.api.nc,this.api.opts)).getPushConsumer(this.name,$)}getMessage($){return this.api.getMessage(this.name,$)}deleteMessage($,Z=!0){return this.api.deleteMessage(this.name,$,Z)}resetConsumer($,Z){return new P$1.ConsumerAPIImpl(this.api.nc,this.api.opts).reset(this.name,$,Z)}}dY$.StreamImpl=ar;class A$1 extends EN4.BaseApiClientImpl{constructor($,Z){super($,Z)}checkStreamConfigVersions($){let Z=this.nc;if($.metadata){let{min:X,ok:Y}=Z.features.get(TZ.Feature.JS_STREAM_CONSUMER_METADATA);if(!Y)throw Error(`stream 'metadata' requires server ${X}`)}if($.first_seq){let{min:X,ok:Y}=Z.features.get(TZ.Feature.JS_STREAM_FIRST_SEQ);if(!Y)throw Error(`stream 'first_seq' requires server ${X}`)}if($.subject_transform){let{min:X,ok:Y}=Z.features.get(TZ.Feature.JS_STREAM_SUBJECT_TRANSFORM);if(!Y)throw Error(`stream 'subject_transform' requires server ${X}`)}if($.compression){let{min:X,ok:Y}=Z.features.get(TZ.Feature.JS_STREAM_COMPRESSION);if(!Y)throw Error(`stream 'compression' requires server ${X}`)}if($.consumer_limits){let{min:X,ok:Y}=Z.features.get(TZ.Feature.JS_DEFAULT_CONSUMER_LIMITS);if(!Y)throw Error(`stream 'consumer_limits' requires server ${X}`)}function Q(X,Y){if((Y?.subject_transforms?.length||0)>0){let{min:G,ok:K}=Z.features.get(TZ.Feature.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!K)throw Error(`${X} 'subject_transforms' requires server ${G}`)}}if($.sources)$.sources.forEach((X)=>{Q("stream sources",X)});if($.mirror)Q("stream mirror",$.mirror)}minStreamApi($){if($.allow_batched===!0||$.mirror?.consumer||$.sources?.some((Z)=>Z.consumer))return 4;if($.allow_msg_counter===!0||$.allow_atomic===!0||$.allow_msg_schedules===!0||$.persist_mode===kG.PersistMode.Async)return 2;if($.allow_msg_ttl===!0||typeof $.subject_delete_marker_ttl==="number"&&$.subject_delete_marker_ttl>0)return 1;return 0}requiredApiOpts($){if(!this.sendRequiredApiLevel())return{};let Z=this.minStreamApi($);return Z>0?{minApiVersion:Z}:{}}async add($){this.checkStreamConfigVersions($),(0,cW.validateStreamName)($.name),$.mirror=rr($.mirror),$.sources=$.sources?.map(rr);let Q=await this._request(`${this.prefix}.STREAM.CREATE.${$.name}`,$,this.requiredApiOpts($));return this._fixInfo(Q),Q}async delete($){return(0,cW.validateStreamName)($),(await this._request(`${this.prefix}.STREAM.DELETE.${$}`)).success}async update($,Z={}){if(typeof $==="object"){let G=$;$=G.name,Z=G,console.trace("\x1B[33m >> streams.update(config: StreamConfig) api changed to streams.update(name: string, config: StreamUpdateConfig) - this shim will be removed - update your code. \x1B[0m")}this.checkStreamConfigVersions(Z),(0,cW.validateStreamName)($);let Q=await this.info($),X=Object.assign(Q.config,Z);X.mirror=rr(X.mirror),X.sources=X.sources?.map(rr);let J=await this._request(`${this.prefix}.STREAM.UPDATE.${$}`,X,this.requiredApiOpts(Z));return this._fixInfo(J),J}async info($,Z){(0,cW.validateStreamName)($);let Q=`${this.prefix}.STREAM.INFO.${$}`,Y=await this._request(Q,Z),{total:J,limit:G}=Y,K=Y.state.subjects?Object.getOwnPropertyNames(Y.state.subjects).length:1;if(J&&J>K){let W=[Y],H=Z||{},F=0;while(J>K){F++,H.offset=G*F;let N=await this._request(Q,H);J=N.total,W.push(N);let B=Object.getOwnPropertyNames(N.state.subjects).length;if(K+=B,B<G)break}let U={};for(let N=0;N<W.length;N++)if(Y=W[N],Y.state.subjects)U=Object.assign(U,Y.state.subjects);Y.offset=0,Y.total=0,Y.limit=0,Y.state.subjects=U}return this._fixInfo(Y),Y}list($=""){let Z=$?.length?{subject:$}:{},Q=(Y)=>{let J=Y;return J.streams.forEach((G)=>{this._fixInfo(G)}),J.streams},X=`${this.prefix}.STREAM.LIST`;return new uY$.ListerImpl(X,Q,this,Z)}_fixInfo($){$.config.sealed=$.config.sealed||!1,$.config.deny_delete=$.config.deny_delete||!1,$.config.deny_purge=$.config.deny_purge||!1,$.config.allow_rollup_hdrs=$.config.allow_rollup_hdrs||!1}async purge($,Z){if(Z){let{keep:X,seq:Y}=Z;if(typeof X==="number"&&typeof Y==="number")throw TZ.InvalidArgumentError.format(["keep","seq"],"are mutually exclusive")}return(0,cW.validateStreamName)($),await this._request(`${this.prefix}.STREAM.PURGE.${$}`,Z)}async deleteMessage($,Z,Q=!0){(0,cW.validateStreamName)($);let X={seq:Z};if(!Q)X.no_erase=!0;return(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${$}`,X)).success}async getMessage($,Z){(0,cW.validateStreamName)($);try{let X=await this._request(`${this.prefix}.STREAM.MSG.GET.${$}`,Z);return new R$1(X)}catch(Q){if(Q instanceof cY$.JetStreamApiError&&Q.code===cY$.JetStreamApiCodes.NoMessageFound)return null;return Promise.reject(Q)}}find($){return this.findStream($)}names($=""){let Z=$?.length?{subject:$}:{},Q=(Y)=>{return Y.streams},X=`${this.prefix}.STREAM.NAMES`;return new uY$.ListerImpl(X,Q,this,Z)}async get($){let Z=await this.info($);return Promise.resolve(new ar(this,Z))}}dY$.StreamAPIImpl=A$1;class R$1{_header;smr;static jc;constructor($){this.smr=$}get pending(){return 0}get lastSequence(){return 0}get subject(){return this.smr.message.subject}get seq(){return this.smr.message.seq}get timestamp(){return this.smr.message.time}get time(){return new Date(Date.parse(this.timestamp))}get data(){return this.smr.message.data?this._parse(this.smr.message.data):TZ.Empty}get header(){if(!this._header)if(this.smr.message.hdrs){let $=this._parse(this.smr.message.hdrs);this._header=TZ.MsgHdrsImpl.decode($)}else this._header=(0,TZ.headers)();return this._header}_parse($){let Z=atob($),Q=Z.length,X=new Uint8Array(Q);for(let Y=0;Y<Q;Y++)X[Y]=Z.charCodeAt(Y);return X}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return TZ.TD.decode(this.data)}}dY$.StoredMsgImpl=R$1;class mY${api;constructor($){this.api=$}get($){return this.api.info($).then((Z)=>{return new ar(this.api,Z)})}}dY$.StreamsImpl=mY$});var M$1=b((rY$)=>{Object.defineProperty(rY$,"__esModule",{value:!0});rY$.DirectConsumer=rY$.DirectMsgImpl=rY$.DirectStreamAPIImpl=void 0;var qN4=Fl(),Bl=eP(),mW=VG(),nY$=Ul(),q$1=VB();class tY$ extends qN4.BaseApiClientImpl{constructor($,Z){super($,Z)}async getMessage($,Z){if((0,nY$.validateStreamName)($),"start_time"in Z){let{min:H,ok:F}=this.nc.features.get(mW.Feature.JS_BATCH_DIRECT_GET);if(!F)throw Error(`start_time direct option require server ${H}`)}let Q=Z,{last_by_subj:X}=Q;if(X)Q=null;let Y=Q?JSON.stringify(Q):mW.Empty,J=this.opts.apiPrefix||"$JS.API",G=X?`${J}.DIRECT.GET.${$}.${X}`:`${J}.DIRECT.GET.${$}`,K=await this.nc.request(G,Y,{timeout:this.timeout});if(K.headers?.code!==0){let H=new q$1.JetStreamStatus(K);if(H.isMessageNotFound())return Promise.resolve(null);else return Promise.reject(H.toError())}let W=new y30(K);return Promise.resolve(W)}getBatch($,Z){return Z.batch=Z.batch||1024,this.get($,Z)}getLastMessagesFor($,Z){return this.get($,Z)}get($,Z){Z={...Z};let{min:Q,ok:X}=this.nc.features.get(mW.Feature.JS_BATCH_DIRECT_GET);if(!X)return Promise.reject(Error(`batch direct require server ${Q}`));(0,nY$.validateStreamName)($);let Y=typeof Z.callback==="function"?Z.callback:null,J=new mW.QueuedIteratorImpl;function G(D,w){if(D){J.push(()=>{D.err?J.stop(D.err):J.stop()});return}J.push(w)}function K(D,w){let j=Y;if(typeof w==="function"){w();return}j(D,w)}if(Y)J.iterClosed.then((D)=>{W({err:D?D:void 0},{}),U.unsubscribe()});let W=Y?K:G,H=(0,mW.createInbox)(this.nc.options.inboxPrefix),F=!1,U=this.nc.subscribe(H,{timeout:5000,callback:(D,w)=>{if(D){J.stop(D),U.unsubscribe();return}let j=q$1.JetStreamStatus.maybeParseStatus(w);if(j){if(j.isNoResults())W({},()=>{J.stop()});if(j.isEndOfBatch())W({},()=>{J.stop()});else{let E=j.toError();W({err:E},()=>{J.stop(E)})}return}if(!F)if(typeof w.headers?.get("Nats-Num-Pending")!=="string")U.unsubscribe(),W({},()=>{J.stop()});else F=!0;W(null,new y30(w))}}),B=`${this.opts.apiPrefix||"$JS.API"}.DIRECT.GET.${$}`,O=JSON.stringify(Z,(D,w)=>{if((D==="up_to_time"||D==="start_time")&&w instanceof Date)return w.toISOString();return w});return this.nc.publish(B,O,{reply:H}),Promise.resolve(J)}}rY$.DirectStreamAPIImpl=tY$;class y30{data;header;constructor($){if(!$.headers)throw Error("headers expected");this.data=$.data,this.header=$.headers}get subject(){return this.header.last(Bl.DirectMsgHeaders.Subject)}get seq(){let $=this.header.last(Bl.DirectMsgHeaders.Sequence);return typeof $==="string"?parseInt($):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(Bl.DirectMsgHeaders.TimeStamp)}get stream(){return this.header.last(Bl.DirectMsgHeaders.Stream)}get lastSequence(){let $=this.header.last(Bl.DirectMsgHeaders.LastSequence);return typeof $==="string"?parseInt($):0}get pending(){let $=this.header.last(Bl.DirectMsgHeaders.NumPending);return typeof $==="string"?parseInt($):-1}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return mW.TD.decode(this.data)}}rY$.DirectMsgImpl=y30;function MN4($){return typeof $==="object"&&"start_time"in $}function IN4($){return typeof $==="object"&&"max_bytes"in $}class oY${stream;api;cursor;listeners;start;constructor($,Z,Q){this.stream=$,this.api=Z,this.cursor={last:0},this.listeners=[],this.start=Q}getOptions($){$=$||{};let Z={};if(this.cursor.last===0)if(MN4(this.start))Z.start_time=this.start.start_time;else Z.seq=this.start.seq||1;else Z.seq=this.cursor.last+1;if(IN4($))Z.max_bytes=$.max_bytes;else Z.batch=$.batch??100;return Z}status(){let $=new mW.QueuedIteratorImpl;return this.listeners.push($),$}notify($){if(this.listeners.length>0)(()=>{let Z=[];this.listeners.forEach((Q)=>{let X=Q;if(!X.done)X.push($);else Z.push(X)}),this.listeners=this.listeners.filter((Q)=>!Z.includes(Q))})()}debug(){console.log(this.cursor)}consume($){let Z,Q,X=new mW.QueuedIteratorImpl;return(async()=>{while(!0){if(this.cursor.pending===0)this.notify({type:"debug",code:0,description:"sleeping for 2500"}),Z=(0,mW.delay)(2500),await Z;if(X.done)break;Q=(0,mW.deferred)();let Y=this.getOptions($);this.notify({type:"next",options:Object.assign({},$)}),Y.callback=(G,K)=>{if(G){if(G.err)if(G.err instanceof q$1.JetStreamStatusError)this.notify({type:"debug",code:G.err.code,description:G.err.message});else this.notify({type:"debug",code:0,description:G.err.message});Q.resolve()}else if(K.lastSequence>0&&K.lastSequence!==this.cursor.last)J.stop(),Q.resolve(),this.notify({type:"reset",name:"direct"});else X.push(K),X.received++,this.cursor.last=K.seq,this.cursor.pending=K.pending};let J=await this.api.getBatch(this.stream,Y);X.iterClosed.then(()=>{J.stop(),Z?.cancel(),Q?.resolve()}),await Q}})().catch((Y)=>{X.stop(Y)}),Promise.resolve(X)}async fetch($){let Z=this.getOptions($),Q=new mW.QueuedIteratorImpl,X=await this.api.get(this.stream,Object.assign({callback:(Y,J)=>{if(Y)Q.push(()=>{Y.err?Q.stop(Y.err):Q.stop()});else if(J.lastSequence>0&&J.lastSequence!==this.cursor.last)Q.push(()=>{Q.stop()}),X.stop();else Q.push(J),Q.received++,this.cursor.last=J.seq,this.cursor.pending=J.pending}},Z));return Q.iterClosed.then(()=>{X.stop()}),Q}async next(){let $=await this.api.getMessage(this.stream,{seq:this.cursor.last+1}),Z=$?.seq;if(Z)this.cursor.last=Z;return $}}rY$.DirectConsumer=oY$});var JJ$=b((XJ$)=>{Object.defineProperty(XJ$,"__esModule",{value:!0});XJ$.BatchPublisherImpl=XJ$.JetStreamClientImpl=XJ$.JetStreamManagerImpl=void 0;XJ$.startFastIngest=CN4;XJ$.toJetStreamClient=_N4;XJ$.jetstream=V$1;XJ$.jetstreamManager=$J$;XJ$.scheduleSpecToHeader=ZJ$;var I$1=Fl(),eY$=L$1(),g5=VG(),g30=pY$(),FY=KT(),sY$=VB(),SN4=M$1();function CN4($,Z,Q,X,Y=5000){let{ackInterval:J,allowGaps:G,inboxPrefix:K,maxOutstandingAcks:W,...H}=X,F=K??"_INBOX";if(!F||/\s/.test(F)||/[*>]/.test(F))return Promise.reject(Error(`inboxPrefix must be non-empty, no wildcards or whitespace (got "${F}")`));let U={ackInterval:J??10,allowGaps:G,inboxPrefix:F,maxOutstandingAcks:Math.min(3,Math.max(1,W??2))},N=new QJ$($,U,Z,Y);return N.start(Q,H).then(()=>N)}function er($){let Z=$.expect||{},Q=$.headers||(0,g5.headers)();if($.msgID)Q.set(FY.PubHeaders.MsgIdHdr,$.msgID);if(Z.lastMsgID)Q.set(FY.PubHeaders.ExpectedLastMsgIdHdr,Z.lastMsgID);if(Z.streamName)Q.set(FY.PubHeaders.ExpectedStreamHdr,Z.streamName);if(typeof Z.lastSequence==="number")Q.set(FY.PubHeaders.ExpectedLastSeqHdr,`${Z.lastSequence}`);if(typeof Z.lastSubjectSequence==="number")Q.set(FY.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Z.lastSubjectSequence}`);if(Z.lastSubjectSequenceSubject)Q.set(FY.PubHeaders.ExpectedLastSubjectSequenceSubjectHdr,Z.lastSubjectSequenceSubject);if($.ttl)Q.set(FY.PubHeaders.MessageTTL,`${$.ttl}`);if($.schedule&&$.cancelSchedule)throw Error("schedule and cancelSchedule are mutually exclusive");if($.schedule){let X=$.schedule;if(X.specification)Q.set(FY.PubHeaders.Schedule,ZJ$(X.specification));if(X.target)Q.set(FY.PubHeaders.ScheduleTarget,X.target);if(X.source)Q.set(FY.PubHeaders.ScheduleSource,X.source);if(X.ttl)Q.set(FY.PubHeaders.ScheduleTTL,X.ttl);if(X.timezone)Q.set(FY.PubHeaders.ScheduleTimeZone,X.timezone);if(X.rollup)Q.set(FY.PubHeaders.ScheduleRollup,X.rollup)}if($.cancelSchedule)Q.set(FY.PubHeaders.Scheduler,$.cancelSchedule.scheduleSubject),Q.set(FY.PubHeaders.ScheduleNext,"purge");return Q}function _N4($){if(typeof $.nc>"u")return V$1($);return $}function V$1($,Z={}){return new S$1($,Z)}async function $J$($,Z={}){let Q=new k$1($,Z);if(Z.checkAPI!==!1)try{await Q.getAccountInfo()}catch(X){throw X}return Q}class k$1 extends I$1.BaseApiClientImpl{streams;consumers;direct;constructor($,Z){super($,Z);this.streams=new g30.StreamAPIImpl($,Z),this.consumers=new eY$.ConsumerAPIImpl($,Z),this.direct=new SN4.DirectStreamAPIImpl($,Z)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return V$1(this.nc,this.getOptions())}advisories(){let $=new g5.QueuedIteratorImpl;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(Z,Q)=>{if(Z)throw Z;try{let X=this.parseJsResponse(Q),Y=X.type.split("."),J=Y[Y.length-1];$.push({kind:J,data:X})}catch(X){$.stop(X)}}}),$}}XJ$.JetStreamManagerImpl=k$1;function ZJ$($){if(typeof $==="string")return $;if($ instanceof Date)return`@at ${$.toISOString()}`;if("at"in $)return`@at ${$.at instanceof Date?$.at.toISOString():$.at}`;if("every"in $)return vN4($.every),`@every ${$.every}`;if("cron"in $)return $.cron;if("predefined"in $)return $.predefined;throw Error("invalid schedule specification")}function vN4($){let Z=$.trim(),Q=/(\d+(?:\.\d+)?)(ns|us|\u00B5s|ms|s|m|h)/g,X=0,Y=0,J;while((J=Q.exec(Z))!==null){if(J.index!==Y)break;Y+=J[0].length;let G=parseFloat(J[1]),K=J[2];X+=K==="ns"?G/1e6:K==="us"||K==="\xB5s"?G/1000:K==="ms"?G:K==="s"?G*1000:K==="m"?G*60000:G*3600000}if(Z===""||Y!==Z.length)throw Error(`@every: unrecognized duration format: "${$}"`);if(X<1000)throw Error("@every interval must be at least 1s")}class S$1 extends I$1.BaseApiClientImpl{consumers;streams;consumerAPI;streamAPI;constructor($,Z){super($,Z);this.consumerAPI=new eY$.ConsumerAPIImpl($,Z),this.streamAPI=new g30.StreamAPIImpl($,Z),this.consumers=new g30.ConsumersImpl(this.consumerAPI),this.streams=new g30.StreamsImpl(this.streamAPI)}jetstreamManager($){if($===void 0)$=this.opts.checkAPI;let Z=Object.assign({},this.opts,{checkAPI:$});try{(0,g5.createInbox)(Z.watcherPrefix)}catch(Q){return Promise.reject(Q)}return $J$(this.nc,Z)}get apiPrefix(){return this.prefix}startBatch($,Z,Q){let X=(0,g5.deferred)(),Y=new C$1(this);return Y.first($,Z,Q).then(()=>{X.resolve(Y)}).catch((J)=>{X.reject(J)}),X}async _publish($,Z=g5.Empty,Q){if(Q=Q||{},Q={...Q},Q.cancelSchedule&&Q.cancelSchedule.scheduleSubject===$)throw Error("cancelSchedule.scheduleSubject must not equal the publish subject");let X=er(Q),Y=Q.timeout||this.timeout,J={};if(Y)J.timeout=Y;if(Q)J.headers=X;let{retries:G}=Q;G=G||1;let K=(0,g5.backoff)(),W=null;for(let H=0;H<G;H++)try{W=await this.nc.request($,Z,J);break}catch(F){let U=F instanceof g5.RequestError?F:null;if((F instanceof g5.errors.TimeoutError||U?.isNoResponders())&&H+1<G)await(0,g5.delay)(K.backoff(H));else throw U?.isNoResponders()?new sY$.JetStreamNotEnabled("jetstream is not enabled",{cause:F}):F}return W}async publish($,Z=g5.Empty,Q){let X=await this._publish($,Z,Q),Y=this.parseJsResponse(X);if(Y.stream==="")throw new sY$.JetStreamError("invalid ack response");return Y.duplicate=Y.duplicate?Y.duplicate:!1,Y}}XJ$.JetStreamClientImpl=S$1;class C$1{nc;js;id;count;done;constructor($){this.count=0,this.id=g5.nuid.next(),this.js=$,this.nc=this.js.nc,this.done=!1}async first($,Z,Q){Q=Q||{},Q.headers=Q?.headers||(0,g5.headers)(),Q.headers.set("Nats-Batch-Id",this.id),this.count++,Q.headers.set("Nats-Batch-Sequence",this.count.toString());let X=await this.js._publish($,Z,Q);if(X.data.length>0)this.js.parseJsResponse(X)}add($,Z,Q={ack:!1}){if(this.done)throw Error("batch publisher is done");if(Q.headers=Q?.headers||(0,g5.headers)(),Q.headers.set("Nats-Batch-Id",this.id),this.count++,Q.headers.set("Nats-Batch-Sequence",this.count.toString()),"ack"in Q&&Q.ack===!0){let Y=(0,g5.deferred)();return this.js._publish($,Z,{headers:Q.headers,timeout:Q.timeout}).then((J)=>{if(J.data.length>0)this.js.parseJsResponse(J);Y.resolve()}).catch((J)=>{this.done=!0,Y.reject(J)}),Y}else return this.nc.publish($,Z,{headers:Q.headers})}async commit($,Z,Q={}){if(this.done)throw Error("batch publisher is done");else this.done=!0;Q.headers=Q?.headers||(0,g5.headers)(),Q.headers.set("Nats-Batch-Id",this.id),this.count++,Q.headers.set("Nats-Batch-Sequence",this.count.toString()),Q.headers.set("Nats-Batch-Commit","1");let Y=(await this.js._publish($,Z,{headers:Q.headers,timeout:Q.timeout||0})).json();if(Y.count!==this.count)throw Error("batch didn't contain number of published messages");return Y}}XJ$.BatchPublisherImpl=C$1;var sr="batch closed",AQ={Start:0,Append:1,Final:2,EOB:3,Ping:4};class QJ${batch;nc;batchSubj;gapMode;initialFlow;seq;acked;ackInterval;inboxPrefix;maxOutstandingAcks;defaultTimeout;gapIter;sub;pending;closed;closeErr;startDeferred;closedDeferred;constructor($,Z,Q,X){this.nc=$,this.batchSubj=Q,this.gapMode=Z.allowGaps?"ok":"fail",this.initialFlow=Z.ackInterval,this.inboxPrefix=Z.inboxPrefix,this.maxOutstandingAcks=Z.maxOutstandingAcks,this.defaultTimeout=X,this.batch=g5.nuid.next(),this.seq=0,this.acked=0,this.ackInterval=Z.ackInterval,this.pending=new Map,this.closed=!1,this.startDeferred=(0,g5.deferred)(),this.closedDeferred=(0,g5.deferred)(),this.closedDeferred.catch(()=>{}),this.startDeferred.catch(()=>{});let Y=`${this.inboxPrefix}.${this.batch}.>`;this.sub=this.nc.subscribe(Y,{callback:(J,G)=>this.route(J,G)})}replyFor($,Z){return`${this.inboxPrefix}.${this.batch}.${this.initialFlow}.${this.gapMode}.${Z}.${$}.$FI`}start($,Z){this.seq=1;let Q=this.replyFor(AQ.Start,1),X=Z?er(Z):void 0;return this.nc.publish(this.batchSubj,$,{reply:Q,headers:X}),this.deadlineOrClose(this.startDeferred,Z?.timeout??this.defaultTimeout)}deadlineOrClose($,Z){return(0,g5.deadline)($,Z).catch((Q)=>{if(!this.closed)this.close(Q);throw Q})}route($,Z){if($){this.close($);return}let Q;try{Q=(0,I$1.parseJsResponse)(Z)}catch(G){this.close(G);return}if("batch"in Q&&typeof Q.batch==="string"){let G=Q,K=this.pending.get(Z.subject);if(K&&(K.op===AQ.Final||K.op===AQ.EOB))K.deferred.resolve(G),this.pending.delete(Z.subject);for(let[,W]of this.pending)if(W.op===AQ.Append||W.op===AQ.Ping)W.deferred.resolve({batchSeq:W.seq,ackSeq:this.acked});else W.deferred.reject(Error(sr));this.pending.clear(),this.resolveStart(),this.closedDeferred.resolve(G),this.closed=!0,this.gapIter?.stop(),this.sub.unsubscribe();return}if(Q.type==="gap"){if(this.gapIter){let G=Q;this.gapIter.push({lastSeq:G.last_seq,seq:G.seq})}return}let Y=Q;if(typeof Y.msgs==="number")this.ackInterval=Y.msgs;if(typeof Y.seq==="number"&&Y.seq>this.acked)this.acked=Y.seq;this.resolveStart();let J=this.pending.get(Z.subject);if(J&&(J.op===AQ.Append||J.op===AQ.Ping))J.deferred.resolve({batchSeq:J.seq,ackSeq:this.acked}),this.pending.delete(Z.subject);for(let[G,K]of this.pending)if(K.op===AQ.Append&&K.seq-this.acked<this.ackInterval*this.maxOutstandingAcks)K.deferred.resolve({batchSeq:K.seq,ackSeq:this.acked}),this.pending.delete(G)}resolveStart(){this.startDeferred.resolve()}close($){this.closed=!0,this.closeErr=$;for(let[,Z]of this.pending)Z.deferred.reject($);this.pending.clear(),this.startDeferred.reject($),this.closedDeferred.reject($),this.gapIter?.stop(),this.sub.unsubscribe()}add($,Z,Q){if(this.closed)return Promise.reject(Error(sr));let X=++this.seq,Y=this.replyFor(AQ.Append,X),J=Q?er(Q):void 0;if(this.nc.publish($,Z,{reply:Y,headers:J}),X-this.acked<this.ackInterval*this.maxOutstandingAcks)return Promise.resolve({batchSeq:X,ackSeq:this.acked});let G=(0,g5.deferred)();return this.pending.set(Y,{seq:X,op:AQ.Append,deferred:G}),this.deadlineOrClose(G,Q?.timeout??this.defaultTimeout)}last($,Z,Q){if(this.closed)return Promise.reject(Error(sr));let X=++this.seq,Y=this.replyFor(AQ.Final,X),J=(0,g5.deferred)();this.pending.set(Y,{seq:X,op:AQ.Final,deferred:J});let G=Q?er(Q):void 0;return this.nc.publish($,Z,{reply:Y,headers:G}),this.deadlineOrClose(J,Q?.timeout??this.defaultTimeout)}end($){if(this.closed)return Promise.reject(Error(sr));let Z=++this.seq,Q=this.replyFor(AQ.EOB,Z),X=(0,g5.deferred)();this.pending.set(Q,{seq:Z,op:AQ.EOB,deferred:X});let Y=$?er($):void 0;return this.nc.publish(this.batchSubj,g5.Empty,{reply:Q,headers:Y}),this.deadlineOrClose(X,$?.timeout??this.defaultTimeout)}ping($=this.defaultTimeout){if(this.closed)return Promise.reject(Error(sr));let Z=this.replyFor(AQ.Ping,this.seq),Q=this.pending.get(Z);if(Q&&Q.op===AQ.Ping)return(0,g5.deadline)(Q.deferred,$);let X=(0,g5.deferred)();return this.pending.set(Z,{seq:this.seq,op:AQ.Ping,deferred:X}),this.nc.publish(this.batchSubj,g5.Empty,{reply:Z}),this.deadlineOrClose(X,$)}done(){return this.closedDeferred}gaps(){if(!this.gapIter)this.gapIter=new g5.QueuedIteratorImpl;return this.gapIter}}});var h30=b((s4)=>{Object.defineProperty(s4,"__esModule",{value:!0});s4.validateStreamName=s4.jserrors=s4.JetStreamStatusError=s4.JetStreamStatus=s4.JetStreamError=s4.JetStreamApiError=s4.JetStreamApiCodes=s4.isMessageNotFound=s4.ListerImpl=s4.StoreCompression=s4.StorageType=s4.RetentionPolicy=s4.ReplayPolicy=s4.PubHeaders=s4.PersistMode=s4.DiscardPolicy=s4.DeliverPolicy=s4.AckPolicy=s4.DirectMsgImpl=s4.BaseApiClientImpl=s4.toJetStreamClient=s4.startFastIngest=s4.jetstreamManager=s4.JetStreamClientImpl=s4.jetstream=s4.RepublishHeaders=s4.JsHeaders=s4.isPushConsumer=s4.isPullConsumer=s4.isOrderedPushConsumerOptions=s4.isBoundPushConsumerOptions=s4.DirectMsgHeaders=s4.AdvisoryKind=void 0;var nD=eP();Object.defineProperty(s4,"AdvisoryKind",{enumerable:!0,get:function(){return nD.AdvisoryKind}});Object.defineProperty(s4,"DirectMsgHeaders",{enumerable:!0,get:function(){return nD.DirectMsgHeaders}});Object.defineProperty(s4,"isBoundPushConsumerOptions",{enumerable:!0,get:function(){return nD.isBoundPushConsumerOptions}});Object.defineProperty(s4,"isOrderedPushConsumerOptions",{enumerable:!0,get:function(){return nD.isOrderedPushConsumerOptions}});Object.defineProperty(s4,"isPullConsumer",{enumerable:!0,get:function(){return nD.isPullConsumer}});Object.defineProperty(s4,"isPushConsumer",{enumerable:!0,get:function(){return nD.isPushConsumer}});Object.defineProperty(s4,"JsHeaders",{enumerable:!0,get:function(){return nD.JsHeaders}});Object.defineProperty(s4,"RepublishHeaders",{enumerable:!0,get:function(){return nD.RepublishHeaders}});var $a=JJ$();Object.defineProperty(s4,"jetstream",{enumerable:!0,get:function(){return $a.jetstream}});Object.defineProperty(s4,"JetStreamClientImpl",{enumerable:!0,get:function(){return $a.JetStreamClientImpl}});Object.defineProperty(s4,"jetstreamManager",{enumerable:!0,get:function(){return $a.jetstreamManager}});Object.defineProperty(s4,"startFastIngest",{enumerable:!0,get:function(){return $a.startFastIngest}});Object.defineProperty(s4,"toJetStreamClient",{enumerable:!0,get:function(){return $a.toJetStreamClient}});var lN4=Fl();Object.defineProperty(s4,"BaseApiClientImpl",{enumerable:!0,get:function(){return lN4.BaseApiClientImpl}});var cN4=M$1();Object.defineProperty(s4,"DirectMsgImpl",{enumerable:!0,get:function(){return cN4.DirectMsgImpl}});var CB=KT();Object.defineProperty(s4,"AckPolicy",{enumerable:!0,get:function(){return CB.AckPolicy}});Object.defineProperty(s4,"DeliverPolicy",{enumerable:!0,get:function(){return CB.DeliverPolicy}});Object.defineProperty(s4,"DiscardPolicy",{enumerable:!0,get:function(){return CB.DiscardPolicy}});Object.defineProperty(s4,"PersistMode",{enumerable:!0,get:function(){return CB.PersistMode}});Object.defineProperty(s4,"PubHeaders",{enumerable:!0,get:function(){return CB.PubHeaders}});Object.defineProperty(s4,"ReplayPolicy",{enumerable:!0,get:function(){return CB.ReplayPolicy}});Object.defineProperty(s4,"RetentionPolicy",{enumerable:!0,get:function(){return CB.RetentionPolicy}});Object.defineProperty(s4,"StorageType",{enumerable:!0,get:function(){return CB.StorageType}});Object.defineProperty(s4,"StoreCompression",{enumerable:!0,get:function(){return CB.StoreCompression}});var mN4=v30();Object.defineProperty(s4,"ListerImpl",{enumerable:!0,get:function(){return mN4.ListerImpl}});var HT=VB();Object.defineProperty(s4,"isMessageNotFound",{enumerable:!0,get:function(){return HT.isMessageNotFound}});Object.defineProperty(s4,"JetStreamApiCodes",{enumerable:!0,get:function(){return HT.JetStreamApiCodes}});Object.defineProperty(s4,"JetStreamApiError",{enumerable:!0,get:function(){return HT.JetStreamApiError}});Object.defineProperty(s4,"JetStreamError",{enumerable:!0,get:function(){return HT.JetStreamError}});Object.defineProperty(s4,"JetStreamStatus",{enumerable:!0,get:function(){return HT.JetStreamStatus}});Object.defineProperty(s4,"JetStreamStatusError",{enumerable:!0,get:function(){return HT.JetStreamStatusError}});Object.defineProperty(s4,"jserrors",{enumerable:!0,get:function(){return HT.jserrors}});var dN4=Ul();Object.defineProperty(s4,"validateStreamName",{enumerable:!0,get:function(){return dN4.validateStreamName}})});var _B=b((YZ)=>{Object.defineProperty(YZ,"__esModule",{value:!0});YZ.StoreCompression=YZ.StorageType=YZ.RetentionPolicy=YZ.RepublishHeaders=YZ.ReplayPolicy=YZ.PubHeaders=YZ.PersistMode=YZ.JsHeaders=YZ.JetStreamError=YZ.JetStreamApiError=YZ.JetStreamApiCodes=YZ.isPushConsumer=YZ.isPullConsumer=YZ.DiscardPolicy=YZ.DirectMsgHeaders=YZ.DeliverPolicy=YZ.AdvisoryKind=YZ.AckPolicy=YZ.jetstreamManager=YZ.jetstream=void 0;var GJ$=h30();Object.defineProperty(YZ,"jetstream",{enumerable:!0,get:function(){return GJ$.jetstream}});Object.defineProperty(YZ,"jetstreamManager",{enumerable:!0,get:function(){return GJ$.jetstreamManager}});var m7=h30();Object.defineProperty(YZ,"AckPolicy",{enumerable:!0,get:function(){return m7.AckPolicy}});Object.defineProperty(YZ,"AdvisoryKind",{enumerable:!0,get:function(){return m7.AdvisoryKind}});Object.defineProperty(YZ,"DeliverPolicy",{enumerable:!0,get:function(){return m7.DeliverPolicy}});Object.defineProperty(YZ,"DirectMsgHeaders",{enumerable:!0,get:function(){return m7.DirectMsgHeaders}});Object.defineProperty(YZ,"DiscardPolicy",{enumerable:!0,get:function(){return m7.DiscardPolicy}});Object.defineProperty(YZ,"isPullConsumer",{enumerable:!0,get:function(){return m7.isPullConsumer}});Object.defineProperty(YZ,"isPushConsumer",{enumerable:!0,get:function(){return m7.isPushConsumer}});Object.defineProperty(YZ,"JetStreamApiCodes",{enumerable:!0,get:function(){return m7.JetStreamApiCodes}});Object.defineProperty(YZ,"JetStreamApiError",{enumerable:!0,get:function(){return m7.JetStreamApiError}});Object.defineProperty(YZ,"JetStreamError",{enumerable:!0,get:function(){return m7.JetStreamError}});Object.defineProperty(YZ,"JsHeaders",{enumerable:!0,get:function(){return m7.JsHeaders}});Object.defineProperty(YZ,"PersistMode",{enumerable:!0,get:function(){return m7.PersistMode}});Object.defineProperty(YZ,"PubHeaders",{enumerable:!0,get:function(){return m7.PubHeaders}});Object.defineProperty(YZ,"ReplayPolicy",{enumerable:!0,get:function(){return m7.ReplayPolicy}});Object.defineProperty(YZ,"RepublishHeaders",{enumerable:!0,get:function(){return m7.RepublishHeaders}});Object.defineProperty(YZ,"RetentionPolicy",{enumerable:!0,get:function(){return m7.RetentionPolicy}});Object.defineProperty(YZ,"StorageType",{enumerable:!0,get:function(){return m7.StorageType}});Object.defineProperty(YZ,"StoreCompression",{enumerable:!0,get:function(){return m7.StoreCompression}})});import{mkdir as nN4,readdir as tN4,readFile as _$1,stat as u30,unlink as oN4,writeFile as rN4}from"fs/promises";import{createHmac as aN4}from"crypto";import{dirname as sN4,join as Za}from"path";function v$1($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return Za(eN4,Z)}function Ll($,Z){return Za(v$1($),r3(Z))}class QK{orgId;baseUrl;constructor($,Z){this.orgId=$;this.baseUrl=Z}async getBytesOrPresign($,Z){let Q=Ll(this.orgId,$),X=await u30(Q),Y=u7($);if(X.size>Z.presignWhenLargerThan)return{error:"FILE_TOO_LARGE",size:X.size,maxInlineSize:Z.presignWhenLargerThan,presignedUrl:await this.presignedGetUrl($),contentType:Y};let J=await _$1(Q),G=GG0(Y);return{content:G?new TextDecoder().decode(J):Buffer.from(J).toString("base64"),contentType:Y,encoding:G?"utf-8":"base64",size:X.size,lastModified:X.mtime}}async getBytes($){let Z=await _$1(Ll(this.orgId,$));return new Uint8Array(Z)}async put($,Z,Q){let X=Ll(this.orgId,$);return await nN4(sN4(X),{recursive:!0}),await rN4(X,typeof Z==="string"?Buffer.from(Z,"utf-8"):Z),{key:$}}async list($){let Z=$?.prefix?Za(v$1(this.orgId),r3($.prefix)):v$1(this.orgId),Q;try{Q=await tN4(Z,{withFileTypes:!0})}catch{return{objects:[],isTruncated:!1}}let X=$?.maxKeys??1000,Y=$?.prefix,J=Q.filter((K)=>K.isFile());if($?.delimiter){let K=[],W=Q.filter((O)=>O.isDirectory());for(let O of W){let D=Y?`${Y}/${O.name}/`:`${O.name}/`;K.push(D)}K.sort();let H=X,F=K.slice(0,H);H-=F.length;let U=J.slice(0,H),N=K.length+J.length;return{objects:await Promise.all(U.map(async(O)=>{let D=await u30(Za(Z,O.name));return{key:Y?`${Y}/${O.name}`:O.name,size:D.size,lastModified:D.mtime}})),isTruncated:N>X,commonPrefixes:F.length>0?F:void 0}}return{objects:await Promise.all(J.slice(0,X).map(async(K)=>{let W=await u30(Za(Z,K.name));return{key:Y?`${Y}/${K.name}`:K.name,size:W.size,lastModified:W.mtime}})),isTruncated:J.length>X}}async delete($){await oN4(Ll(this.orgId,$))}async head($){let Z=await u30(Ll(this.orgId,$));return{contentType:u7($),size:Z.size,lastModified:Z.mtime}}async presignedGetUrl($,Z,Q){if(Q?.requireFetchable)throw Error("object storage returned a not fetchable (data:) URL; configure real S3/R2/MinIO for large-payload offload");let X=Ll(this.orgId,$),Y=await _$1(X),J=u7($),G=Buffer.from(Y).toString("base64");return`data:${J};base64,${G}`}async presignedPutUrl($,Z=3600){if(!this.baseUrl)throw Error("baseUrl required for presigned PUT URLs in dev mode");let Q=r3($),X=Math.floor(Date.now()/1000)+Z,Y=P0().encryptionKey||"dev-secret",J=`${this.orgId}:${Q}:${X}:PUT`,G=aN4("sha256",Y).update(J).digest("hex"),K=new URL(`/api/dev-assets/${this.orgId}/${Q}`,this.baseUrl);return K.searchParams.set("expires",X.toString()),K.searchParams.set("signature",G),K.searchParams.set("method","PUT"),K.toString()}}var eN4="./data/assets";var Ol=L(()=>{CW();H$()});function bF($){return $B4.test($)&&$!=="."&&$!==".."}function N7($){if(!bF($))throw Error(`Invalid org-fs volume name: ${JSON.stringify($)}`)}function d7($){return r3($)}function Dl($){let Z=$.lastIndexOf("/");return Z===-1?"":$.slice(0,Z)}function tD($){let Z=Dl($);if(Z==="")return[];let Q=Z.split("/"),X=[],Y="";for(let J of Q)Y=Y===""?J:`${Y}/${J}`,X.push(Y);return X}function yF($,Z){return`${KJ$}/${$}/${Z}`}function l30($){return`${KJ$}/${$}/`}var $B4,KJ$="_fs";var FT=L(()=>{CW();$B4=/^[A-Za-z0-9_.-]{1,128}$/});import{createHmac as x$1,randomBytes as f$1,scrypt as ZB4,timingSafeEqual as WJ$}from"crypto";import{promisify as QB4}from"util";async function FJ$($){let Z=f$1(16),Q=await HJ$($,Z,XB4);return`scrypt$${Z.toString("hex")}$${Q.toString("hex")}`}async function UJ$($,Z){let Q=Z.split("$");if(Q.length!==3||Q[0]!=="scrypt")return!1;let X=Buffer.from(Q[1],"hex"),Y=Buffer.from(Q[2],"hex");if(X.length===0||Y.length===0)return!1;let J;try{J=await HJ$($,X,Y.length)}catch{return!1}return Y.length===J.length&&WJ$(Y,J)}function NJ$(){return f$1(16).toString("hex")}function BJ$(){if(c30)return c30;let $;try{let Z=P0();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return c30=$?Buffer.from($):f$1(32),c30}function LJ$($){let Z=Buffer.from(JSON.stringify($)).toString("base64url"),Q=x$1("sha256",BJ$()).update(Z).digest("base64url");return`${Z}.${Q}`}function OJ$($,Z){let Q=$.indexOf(".");if(Q<0)return null;let X=$.slice(0,Q),Y=Buffer.from($.slice(Q+1)),J=Buffer.from(x$1("sha256",BJ$()).update(X).digest("base64url"));if(Y.length!==J.length||!WJ$(Y,J))return null;let G;try{G=JSON.parse(Buffer.from(X,"base64url").toString())}catch{return null}if(G.o!==Z.org||G.v!==Z.volume||G.s!==Z.secret||typeof G.e!=="number"||G.e<Z.nowSec)return null;return{govPath:G.p}}function b$1($,Z,Q){return`fsu_${x$1("sha256","fsunlock-name").update(`${$}:${Z}:${Q}`).digest("hex").slice(0,16)}`}var XB4=64,HJ$,c30=null;var y$1=L(()=>{H$();HJ$=QB4(ZB4)});import{createHash as YB4}from"crypto";function HB4($){if(typeof $!=="object"||$===null)return!1;let Z=$;return Z.name==="NoSuchKey"||Z.Code==="NoSuchKey"||Z.code==="ENOENT"||Z.$metadata?.httpStatusCode===404}function DJ$($){return YB4("sha256").update($).digest("hex")}class XK{storage;manifest;organizationId;maxFileBytes;volumeQuotaBytes;constructor($,Z,Q,X={}){this.storage=$;this.manifest=Z;this.organizationId=Q;this.maxFileBytes=X.maxFileBytes??KB4,this.volumeQuotaBytes=X.volumeQuotaBytes??WB4}async usage($){return N7($),this.manifest.usage(this.organizationId,$)}async stat($,Z){return N7($),this.manifest.get(this.organizationId,$,d7(Z))}async listVolumeFiles($){return N7($),this.manifest.listVolumeFiles(this.organizationId,$)}async listDir($,Z){return N7($),this.manifest.listDir(this.organizationId,$,d7(Z))}async read($,Z){let Q=await this.requireFile($,Z);try{return await this.storage.getBytes(yF($,Q.path))}catch(X){if(HB4(X))throw new UY(`No such file: ${Q.path}`);throw X}}async setShareMode($,Z,Q,X){N7($);let Y=d7(Z),J=await this.manifest.get(this.organizationId,$,Y);if(!J)throw new UY(`No such path: ${Y}`);let G=null,K=null;if(Q==="password"){if(!X.password)throw new SG("A password is required to set password mode");G=await FJ$(X.password),K=NJ$()}let W=await this.manifest.setShareMode({organizationId:this.organizationId,volume:$,path:J.path,readPublic:Q!=="private",passwordHash:G,shareSecret:K,actor:X.actor});if(!W)throw new UY(`No such path: ${J.path}`);return W}async setReadPublic($,Z,Q,X){return this.setShareMode($,Z,Q?"public":"private",{actor:X.actor})}async resolveReadAccess($,Z){N7($);let Q=d7(Z),X=await this.manifest.get(this.organizationId,$,Q);if(!X||X.kind!=="file")return{access:"private"};let Y=await this.manifest.resolveGoverningShare({organizationId:this.organizationId,volume:$,candidatePaths:[Q,...tD(Q)]});if(!Y)return{access:"private"};if(!Y.passwordHash)return{access:"public"};return{access:"password",govPath:Y.path,secret:Y.secret??"",passwordHash:Y.passwordHash}}async isPubliclyReadable($,Z){N7($);let Q=d7(Z),X=await this.manifest.get(this.organizationId,$,Q);if(!X||X.kind!=="file")return!1;if(X.readPublic)return!0;return this.manifest.hasPublicAncestorDir(this.organizationId,$,tD(Q))}async inheritsPublic($,Z){return N7($),this.manifest.hasPublicAncestorDir(this.organizationId,$,tD(d7(Z)))}async childrenInheritPublic($,Z){N7($);let Q=d7(Z);if(Q==="")return!1;return this.manifest.hasPublicAncestorDir(this.organizationId,$,[...tD(Q),Q])}async recentWithEffectivePublic($){return this.withEffectivePublic(await this.recent($))}async searchWithEffectivePublic($,Z,Q,X){return this.withEffectivePublic(await this.manifest.searchFiles({organizationId:this.organizationId,query:$,limit:Z,volumes:Q,pathPrefix:X?d7(X):void 0}))}async withEffectivePublic($){let Z=new Map;for(let X of $){let Y=Z.get(X.volume);if(!Y)Y=new Set,Z.set(X.volume,Y);for(let J of tD(X.path))Y.add(J)}let Q=new Map;return await Promise.all([...Z].map(async([X,Y])=>{let J=await this.manifest.publicDirPaths({organizationId:this.organizationId,volume:X,paths:[...Y]});Q.set(X,new Set(J))})),$.map((X)=>{let Y=Q.get(X.volume),J=!!Y&&tD(X.path).some((G)=>Y.has(G));return{...X,effectivePublic:X.readPublic||J}})}async presignRead($,Z,Q){let X=await this.requireFile($,Z);return this.storage.presignedGetUrl(yF($,X.path),Q)}async write($,Z,Q,X){N7($);let Y=d7(Z);if(Y==="")throw new SG("Cannot write to the volume root");let J=typeof Q==="string"?new TextEncoder().encode(Q):Q;if(J.byteLength>this.maxFileBytes)throw new UT(`File exceeds the ${this.maxFileBytes}-byte per-file limit`);let[G,K]=await Promise.all([X.skipVolumeQuota?Promise.resolve(null):this.manifest.usage(this.organizationId,$),this.manifest.get(this.organizationId,$,Y)]);if(K?.kind==="dir")throw new SG(`Cannot write a file at ${Y}: a directory exists there`);if(G){let W=K?.kind==="file"?K.size:0;if(G.bytes-W+J.byteLength>this.volumeQuotaBytes)throw new UT(`Write would exceed the volume quota of ${this.volumeQuotaBytes} bytes`)}await this.ensureDirs($,Y,X.actor),await this.storage.put(yF($,Y),J,{contentType:X.contentType??u7(Y)});try{return await u8(()=>this.manifest.putFile({organizationId:this.organizationId,volume:$,path:Y,parent:Dl(Y),contentHash:DJ$(J),size:J.byteLength,actor:X.actor,threadId:X.threadId??null}))}catch(W){throw console.error("org-fs manifest write lost after object put",{organizationId:this.organizationId,volume:$,path:Y,size:J.byteLength,error:W instanceof Error?W.message:String(W)}),W}}async mkdir($,Z,Q){N7($);let X=d7(Z);if(X==="")return;if((await this.manifest.get(this.organizationId,$,X))?.kind==="file")throw new SG(`Cannot create a directory at ${X}: a file exists there`);await this.ensureDirs($,X,Q.actor),await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:X,parent:Dl(X),actor:Q.actor})}async delete($,Z,Q){N7($);let X=d7(Z);if(X==="")throw new SG("Cannot delete the volume root");let Y=await this.manifest.get(this.organizationId,$,X);if(!Y)return;if(Y.kind==="dir"){let J=await this.manifest.listSubtreeFiles(this.organizationId,$,X);await Promise.all(J.map((G)=>this.storage.delete(yF($,G.path)))),await this.manifest.tombstoneSubtree(this.organizationId,$,X,Q.actor);return}await this.storage.delete(yF($,X)),await this.manifest.tombstone(this.organizationId,$,X,Q.actor)}async move($,Z,Q,X){N7($);let Y=d7(Z),J=d7(Q);if(Y===""||J==="")throw new SG("Cannot move the volume root");if(J===Y||J.startsWith(`${Y}/`))throw new SG(`Cannot move ${Y} onto itself or into its own subtree`);let G=await this.manifest.get(this.organizationId,$,Y);if(!G)throw new UY(`No such path: ${Y}`);if(G.kind==="file"){let H=await this.storage.getBytes(yF($,Y));await this.write($,J,H,{...X,skipVolumeQuota:!0}),await this.delete($,Y,X);return}let[K,W]=await Promise.all([this.manifest.listSubtreeFiles(this.organizationId,$,Y),this.manifest.listSubtreeDirs(this.organizationId,$,Y)]);await this.mkdir($,J,X);for(let H of K){let F=H.path.slice(Y.length+1),U=await this.storage.getBytes(yF($,H.path));await this.write($,`${J}/${F}`,U,{...X,skipVolumeQuota:!0})}for(let H of W){let F=H.path.slice(Y.length+1);await this.mkdir($,`${J}/${F}`,X)}await this.delete($,Y,X)}async filesExist($,Z){N7($);let Q=await this.manifest.liveFilePaths({organizationId:this.organizationId,volume:$,paths:Z.map((X)=>d7(X))});return new Set(Q)}async recent($){return this.manifest.recentFiles({organizationId:this.organizationId,limit:$})}async changes($,Z,Q=JB4){N7($);let X=Z||"0";if(!/^\d+$/.test(X))throw new SG(`Invalid cursor: ${Z}`);let Y=await this.manifest.changesSince({organizationId:this.organizationId,volume:$,sinceSeq:X,limit:Q}),J=Y.at(-1);return{entries:Y,cursor:J?J.seq:Z||"0",hasMore:Y.length>=Q}}async latestSeq($){return N7($),this.manifest.latestSeq({organizationId:this.organizationId,volume:$})}async backfillFromStorage($,Z){N7($);let Q=l30($),X,Y=0;do{let J=await this.storage.list({prefix:Q,maxKeys:GB4,continuationToken:X});for(let G of J.objects){let K=G.key.slice(Q.length);if(K==="")continue;await this.ensureDirs($,K,Z.actor);let W=await this.storage.getBytes(G.key);await this.manifest.putFile({organizationId:this.organizationId,volume:$,path:K,parent:Dl(K),contentHash:DJ$(W),size:W.byteLength,actor:Z.actor}),Y++}X=J.isTruncated?J.nextContinuationToken:void 0}while(X);return Y}async requireFile($,Z){N7($);let Q=d7(Z),X=await this.manifest.get(this.organizationId,$,Q);if(!X||X.kind!=="file")throw new UY(`No such file: ${Q}`);return X}async ensureDirs($,Z,Q){for(let X of tD(Z))await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:X,parent:Dl(X),actor:Q})}}var JB4=500,GB4=1000,KB4=524288000,WB4=10737418240,UT,SG,UY;var vB=L(()=>{w8();CW();FT();y$1();UT=class UT extends Error{constructor($){super($);this.name="OrgFsQuotaError"}};SG=class SG extends Error{constructor($){super($);this.name="OrgFsValidationError"}};UY=class UY extends Error{constructor($){super($);this.name="OrgFsNotFoundError"}}});import{z as xB}from"zod";function gF($){return $.startsWith(wJ$)}function oD($){return`${wJ$}${$}`}function LB4($){let Z=new Map(NB4.map((Q)=>[Q.set,Q]));if($)try{for(let Q of BB4.parse(JSON.parse($)))Z.set(Q.set,Q)}catch(Q){console.warn("[org-fs] invalid ORGFS_PUBLIC_SETS \u2014 using built-in defaults only",Q)}return[...Z.values()]}function YK(){return LB4(P0().orgFsPublicSetsJson)}function Xa($){let Z=zQ(),Q=Z?GY(Z,Qa):new QK(Qa,$.baseUrl);return new XK(Q,$.storage.orgFsEntries,Qa)}var Qa="org_orgfs_public_skills",wJ$="public-",FB4,UB4,NB4,BB4;var NT=L(()=>{H$();PB();Ol();vB();FB4=xB.object({from:xB.string(),to:xB.string().optional()}),UB4=xB.object({set:xB.string().regex(/^[a-z0-9][a-z0-9-]{0,40}$/),repo:xB.string().regex(/^[\w.-]+\/[\w.-]+$/),ref:xB.string().min(1),paths:xB.array(FB4).min(1)}),NB4=[{set:"core",repo:"decocms/studio",ref:"main",paths:[{from:"packages/sandbox/image/skills"}]},{set:"storefront",repo:"decocms/storefront-skills",ref:"main",paths:[{from:".claude-seo/skills"},{from:".claude-performance/skills"},{from:".claude-deco/skills"}]}],BB4=xB.array(UB4).refine(($)=>new Set($.map((Z)=>Z.set)).size===$.length,{message:"duplicate set names"})});function fB($){if(typeof $==="string")return $.length>0?[$]:[];if(Array.isArray($))return $.flatMap(fB);if($!==null&&typeof $==="object")return Object.values($).flatMap(fB);return[]}var h0;var E5=L(()=>{h0=class h0 extends Error{provider;status;retryAfterMs;constructor($){super($.message,{cause:$.cause});this.name="GitProviderError",this.provider=$.provider,this.status=$.status,this.retryAfterMs=$.retryAfterMs??null}get isRateLimited(){return this.status===429||this.retryAfterMs!==null}get isAuthFailure(){return this.status===401||this.status===403}}});import{sql as BT}from"kysely";function g$1($){if($===null)return null;return $ instanceof Date?$.toISOString():String($)}function dW($){return{organizationId:$.organization_id,volume:$.volume,path:$.path,parent:$.parent,kind:$.kind,contentHash:$.content_hash,size:Number($.size),seq:String($.seq),deletedAt:g$1($.deleted_at),createdBy:$.created_by,createdAt:g$1($.created_at)??"",updatedBy:$.updated_by,updatedAt:g$1($.updated_at)??"",threadId:$.thread_id,readPublic:$.read_public,shareMode:!$.read_public?"private":$.share_password_hash?"password":"public"}}class Ja{db;constructor($){this.db=$}async putFile($){let Z=new Date,Q=$.threadId??null,X=await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z,thread_id:Q}).onConflict((Y)=>Y.columns(["organization_id","volume","path"]).doUpdateSet({kind:"file",content_hash:$.contentHash,size:$.size,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:m30,read_public:BT`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`,thread_id:BT`coalesce(cast(${Q} as text), org_fs_entry.thread_id)`})).returning(iW).executeTakeFirstOrThrow();return dW(X)}async putDir($){let Z=new Date;await this.db.insertInto("org_fs_entry").values({organization_id:$.organizationId,volume:$.volume,path:$.path,parent:$.parent,kind:"dir",content_hash:null,size:0,deleted_at:null,created_by:$.actor,created_at:Z,updated_by:$.actor,updated_at:Z}).onConflict((Q)=>Q.columns(["organization_id","volume","path"]).where("org_fs_entry.deleted_at","is not",null).doUpdateSet({kind:"dir",content_hash:null,size:0,deleted_at:null,updated_by:$.actor,updated_at:Z,seq:m30,read_public:BT`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`})).execute()}async get($,Z,Q){let X=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("path","=",Q).where("deleted_at","is",null).select(iW).executeTakeFirst();return X?dW(X):null}async listDir($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("parent","=",Q).where("deleted_at","is",null).select(iW).orderBy("path","asc").execute()).map((Y)=>dW(Y))}async listVolumeDirs($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).select(iW).execute()).map((X)=>dW(X))}async listVolumeFiles($,Z){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select(iW).execute()).map((X)=>dW(X))}async listSubtreeFiles($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).where("path","like",`${Ya(Q)}/%`).select(iW).execute()).map((Y)=>dW(Y))}async listSubtreeDirs($,Z,Q){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("deleted_at","is",null).where("path","like",`${Ya(Q)}/%`).select(iW).execute()).map((Y)=>dW(Y))}async tombstone($,Z,Q,X){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:X,updated_at:new Date,seq:m30}).where("organization_id","=",$).where("volume","=",Z).where("path","=",Q).where("deleted_at","is",null).execute()}async tombstoneSubtree($,Z,Q,X){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:X,updated_at:new Date,seq:m30}).where("organization_id","=",$).where("volume","=",Z).where("deleted_at","is",null).where((Y)=>Y.or([Y("path","=",Q),Y("path","like",`${Ya(Q)}/%`)])).execute()}async setShareMode($){let Z=new Date,Q=await this.db.updateTable("org_fs_entry").set({read_public:$.readPublic,share_password_hash:$.passwordHash,share_secret:$.shareSecret,updated_by:$.actor,updated_at:Z}).where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("path","=",$.path).where("deleted_at","is",null).returning(iW).executeTakeFirst();return Q?dW(Q):null}async resolveGoverningShare($){if($.candidatePaths.length===0)return null;let Z=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.candidatePaths).select(["path","share_password_hash","share_secret"]).execute();if(Z.length===0)return null;Z.sort((X,Y)=>Y.path.length-X.path.length);let Q=Z[0];return{path:Q.path,passwordHash:Q.share_password_hash,secret:Q.share_secret}}async hasPublicAncestorDir($,Z,Q){if(Q.length===0)return!1;return!!await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",Q).select("path").limit(1).executeTakeFirst()}async publicDirPaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","dir").where("read_public","=",!0).where("deleted_at","is",null).where("path","in",$.paths).select("path").execute()).map((Q)=>Q.path)}async usage($,Z){let Q=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select((X)=>[X.fn.countAll().as("files"),X.fn.coalesce(X.fn.sum("size"),BT`0`).as("bytes")]).executeTakeFirst();return{files:Number(Q?.files??0),bytes:Number(Q?.bytes??0)}}async liveFilePaths($){if($.paths.length===0)return[];return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("kind","=","file").where("deleted_at","is",null).where("path","in",$.paths).select(["path"]).execute()).map((Q)=>Q.path)}async recentFiles($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).select(iW).orderBy("seq","desc").limit($.limit).execute()).map((Q)=>dW(Q))}async searchFiles($){if($.volumes&&$.volumes.length===0)return[];let Z=Ya($.query),Q=this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).where("path","ilike",`%${Z}%`);if($.volumes)Q=Q.where("volume","in",$.volumes);if($.pathPrefix)Q=Q.where("path","like",`${Ya($.pathPrefix)}/%`);return(await Q.select(iW).orderBy("seq","desc").limit($.limit).execute()).map((Y)=>dW(Y))}async changesSince($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("seq",">",BT`cast(${$.sinceSeq} as bigint)`).select(iW).orderBy("seq","asc").limit($.limit).execute()).map((Q)=>dW(Q))}async latestSeq($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).select(BT`max(seq)`.as("seq")).executeTakeFirst())?.seq??"0"}}function Ya($){return $.replace(/[\\%_]/g,"\\$&")}var iW,m30;var h$1=L(()=>{iW=["organization_id","volume","path","parent","kind","content_hash","size","seq","deleted_at","created_by","created_at","updated_by","updated_at","thread_id","read_public","share_password_hash"],m30=BT`nextval('org_fs_entry_seq')`});import{createHash as OB4}from"crypto";import{gunzipSync as DB4}from"zlib";function l$1($,Z,Q){let X=Z,Y=Z+Q;while(X<Y&&$[X]!==0)X++;return new TextDecoder().decode($.subarray(Z,X))}function jB4($,Z,Q){let X=l$1($,Z,Q).trim();return X===""?0:Number.parseInt(X,8)}function EB4($){let Z=new Map,Q=0,X=null,Y=null;while(Q+512<=$.length){let J=$.subarray(Q,Q+512);if(Q+=512,J.every((N)=>N===0))break;let G=l$1(J,0,100),K=l$1(J,345,155);if(K)G=`${K}/${G}`;let W=jB4(J,124,12),H=String.fromCharCode(J[156]??0),F=$.subarray(Q,Q+W);if(Q+=Math.ceil(W/512)*512,H==="L"){let N=new TextDecoder().decode(F),B=N.indexOf("\x00");X=B===-1?N:N.slice(0,B);continue}if(H==="x"){let N=new TextDecoder().decode(F);Y=/(?:^|\n)\d+ path=([^\n]*)\n/.exec(N)?.[1]??null;continue}if(H==="g")continue;let U=Y??X??G;if(X=null,Y=null,H==="0"||H==="\x00"||H==="")Z.set(U,new Uint8Array(F))}return Z}function zB4($,Z,Q){let X=encodeURIComponent(Z);if(!Q)return{url:`https://codeload.github.com/${$}/tar.gz/${X}`,headers:{}};return{url:`https://api.github.com/repos/${$}/tarball/${X}`,headers:{Authorization:`Bearer ${Q}`,Accept:"application/vnd.github+json"}}}function jJ$($,Z){if($.length>wl)throw Error(`tarball for ${Z} exceeds ${wl} bytes`);let Q=EB4(new Uint8Array(DB4($,{maxOutputLength:wB4}))),X=new Map;for(let[Y,J]of Q){let G=Y.indexOf("/");if(G===-1)continue;let K=Y.slice(G+1);if(K)X.set(K,J)}return X}function EJ$($,Z,Q){if($>Z)throw Error(`tarball for ${Q} exceeds ${Z} bytes`)}async function PB4($,Z){let Q=[],X=0,Y=$.getReader();try{while(!0){let{done:K,value:W}=await Y.read();if(K)break;X+=W.length,EJ$(X,wl,Z),Q.push(W)}}finally{await Y.cancel().catch(()=>{}),Y.releaseLock()}let J=new Uint8Array(X),G=0;for(let K of Q)J.set(K,G),G+=K.length;return J}function zJ$($){if($ instanceof c$1)return $.status>=500||$.status===429;if($ instanceof h0)return $.status===0||$.status>=500||$.status===429;if($ instanceof Error&&/declares .* bytes|exceeds .* bytes/.test($.message))return!1;return!0}async function TB4($,Z,Q){let{url:X,headers:Y}=zB4($,Z,Q),J=`${$}@${Z}`,G=async()=>{let K=await fetch(X,{headers:Y,signal:AbortSignal.timeout(60000)});if(!K.ok)throw await K.body?.cancel().catch(()=>{}),new c$1(K.status,`tarball fetch failed for ${J}: HTTP ${K.status}`);let W=Number(K.headers.get("content-length")??0);if(W>wl)throw Error(`tarball for ${J} declares ${W} bytes (cap ${wl})`);let H=new Uint8Array(await K.arrayBuffer());return EJ$(H.length,wl,J),H};try{let K=await u8(G,{maxAttempts:3,minTimeout:500,maxTimeout:4000,jitter:0.5,isRetriable:zJ$});return jJ$(K,J)}catch(K){if(K instanceof t5)throw K.cause instanceof Error?K.cause:K;throw K}}async function AB4($,Z){if(!Z.tarball)return TB4($.repo,$.ref,Z.authToken);let Q=Z.tarball,X=`${$.repo}@${$.ref}`,Y;try{Y=await u8(()=>Q(),{maxAttempts:3,minTimeout:500,maxTimeout:4000,jitter:0.5,isRetriable:zJ$})}catch(J){throw J instanceof t5&&J.cause instanceof Error?J.cause:J}if(!Y)throw Error(`tarball not found for ${X}`);return jJ$(await PB4(Y,X),X)}function RB4($,Z){let Q=new Map;for(let{from:X,to:Y}of Z){let J=X===""?"":`${X.replace(/\/+$/,"")}/`;for(let[G,K]of $){if(!G.startsWith(J))continue;let W=G.slice(J.length);if(!W)continue;let H=d7(Y?`${Y}/${W}`:W);if(H)Q.set(H,K)}}return Q}function qB4($,Z){let Q=new Set;for(let J of $){let G=J.split("/");for(let K=1;K<G.length;K++)Q.add(G.slice(0,K).join("/"))}let X=[...Z].filter((J)=>!Q.has(J)).sort((J,G)=>J.length-G.length),Y=[];for(let J of X)if(!Y.some((G)=>J.startsWith(`${G}/`)))Y.push(J);return Y}function MB4($){return OB4("sha256").update($).digest("hex")}function IB4($){return $.manifestHash===$.hash&&$.storedPaths.has($.path)}async function VB4($,Z){let Q=l30(Z),X=new Set,Y;do{let J=await $.list({prefix:Q,continuationToken:Y});for(let G of J.objects)X.add(G.key.slice(Q.length));Y=J.nextContinuationToken}while(Y);return X}async function m$1($,Z){let{orgId:Q,volume:X,source:Y}=Z,J=zQ(),G=J?GY(J,Q):new QK(Q,Z.baseUrl),K=new Ja($),W=new XK(G,K,Q),H=RB4(await AB4(Y,Z),Y.paths),F=new Map((await K.listVolumeFiles(Q,X)).map((w)=>[w.path,w.contentHash]));if(H.size===0&&F.size>0)throw Error(`volume "${X}" resolved 0 files from ${Y.repo}@${Y.ref} `+`(check paths config) \u2014 refusing to delete the ${F.size} existing files`);let U=0;for(let w of F.keys()){if(H.has(w))continue;await W.delete(X,w,{actor:u$1}),U++}let N=await K.listVolumeDirs(Q,X);for(let w of qB4(H.keys(),N.map((j)=>j.path)))await W.delete(X,w,{actor:u$1});let B=0,O=0,D=await VB4(G,X);for(let[w,j]of H){if(IB4({hash:MB4(j),manifestHash:F.get(w),storedPaths:D,path:w})){O++;continue}await W.write(X,w,j,{actor:u$1,contentType:u7(w),skipVolumeQuota:Z.skipVolumeQuota}),B++}return{written:B,deleted:U,unchanged:O}}async function kB4($,Z,Q){let X=await m$1($,{orgId:Qa,baseUrl:Q.baseUrl,volume:oD(Z.set),source:Z,skipVolumeQuota:!0});return{set:Z.set,...X}}async function d$1($,Z,Q){try{return await kB4($,Z,Q)}catch(X){return{set:Z.set,error:X instanceof Error?X.message:String(X)}}}async function PJ$($,Z){let Q=[];for(let X of YK())Q.push(await d$1($,X,Z));return Q}var u$1="system:skill-set-sync",wl=209715200,wB4=1073741824,c$1;var d30=L(()=>{w8();E5();h$1();Ol();PB();CW();vB();FT();NT();c$1=class c$1 extends Error{status;constructor($,Z){super(Z);this.status=$;this.name="TarballHttpError"}}});import{DBOS as i30,SchedulerMode as SB4}from"@dbos-inc/dbos-sdk";function TJ$($){i$1=$}function _B4(){if(!i$1)throw Error("[org-fs] public-sets sync runtime not initialized \u2014 setPublicSetsSyncRuntime() must run before the workflow fires");return i$1}async function vB4($,Z){for(let Q of YK()){let X=await i30.runStep(()=>{let Y=_B4();return d$1(Y.db,Q,{baseUrl:Y.baseUrl})},{name:`syncPublicSet:${Q.set}`});if("error"in X)console.warn(`[org-fs] public set "${X.set}" sync failed: ${X.error}`);else if(X.written||X.deleted)console.log(`[org-fs] public set "${X.set}" synced: +${X.written} -${X.deleted} (=${X.unchanged})`)}}function AJ$(){if(Ga)return;Ga=i30.registerWorkflow(vB4,{name:"publicSetsSyncWorkflow"}),i30.registerScheduled(Ga,{name:"publicSetsSyncWorkflow",crontab:CB4,mode:SB4.ExactlyOncePerIntervalWhenActive})}async function RJ$(){if(YK().length===0||!Ga)return;let $=new Date,Z=`public-sets-sync-boot:${$.toISOString().slice(0,13)}`;await i30.startWorkflow(Ga,{workflowID:Z})($,$)}var CB4="4-59/10 * * * *",i$1=null,Ga=null;var qJ$=L(()=>{NT();d30()});import{jwtVerify as xB4,SignJWT as MJ$}from"jose";import{randomBytes as fB4}from"crypto";function IJ$(){if(Ka)return Ka;let $=P0(),Z=$.studioJwtSecret??$.betterAuthSecret;if(Z)Ka=new TextEncoder().encode(Z);else console.warn("STUDIO_JWT_SECRET not set - generating random secret (not persistent)"),Ka=new Uint8Array(fB4(32));return Ka}async function VJ$($,Z="5m"){let Q=IJ$();return await new MJ$($).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Z).sign(Q)}async function p$1($){try{let Z=IJ$(),{payload:Q}=await xB4($,Z);return Q}catch{return}}async function RQ($,Z,Q=3600){let X=P0(),Y=X.plansEnabled?X.studioJwtSecret:X.studioJwtSecret??X.betterAuthSecret;if(!Y)throw Error(X.plansEnabled?"STUDIO_JWT_SECRET (or MESH_JWT_SECRET) is required to mint gateway JWTs when STUDIO_PLANS_ENABLED is set \u2014 BETTER_AUTH_SECRET is deliberately not a fallback, see resolve-config":"A deterministic JWT secret is required to mint gateway JWTs \u2014 set STUDIO_JWT_SECRET or BETTER_AUTH_SECRET");let J=new TextEncoder().encode(Y);return await new MJ$({iss:"mesh",sub:$,...Z&&{email:Z}}).setProtectedHeader({alg:"HS256",typ:"JWT"}).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1000)+Q).sign(J)}var Ka=null;var pW=L(()=>{H$()});import{createCipheriv as bB4,createDecipheriv as yB4,createHash as gB4,randomBytes as kJ$}from"crypto";class CG{key;constructor($){if(Buffer.from($,"base64").length===_J$)this.key=Buffer.from($,"base64");else this.key=gB4("sha256").update($).digest()}async encrypt($){let Z=kJ$(Wa),Q=bB4(SJ$,this.key,Z),X=Q.update($,"utf8");X=Buffer.concat([X,Q.final()]);let Y=Q.getAuthTag();return Buffer.concat([Z,Y,X]).toString("base64")}async decrypt($){let Z=Buffer.from($,"base64"),Q=Z.subarray(0,Wa),X=Z.subarray(Wa,Wa+CJ$),Y=Z.subarray(Wa+CJ$),J=yB4(SJ$,this.key,Q);J.setAuthTag(X);let G=J.update(Y);return G=Buffer.concat([G,J.final()]),G.toString("utf8")}static generateKey(){return kJ$(_J$).toString("base64")}}var SJ$="aes-256-gcm",Wa=16,CJ$=16,_J$=32;var LT=()=>{};import*as y from"zod/v4";function tJ$($){if($.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${$.params.ref.type}`)}function oJ$($){if($.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${$.params.ref.type}`)}var rD="2025-11-25",vJ$="2025-03-26",aD,sD="io.modelcontextprotocol/related-task",n30="2.0",B7,xJ$,fJ$,Ap5,hB4,uB4,n$1,_G,Ha,bJ$=($)=>Ha.safeParse($).success,qQ,JK,GK,MQ,t30,yJ$,hF=($)=>yJ$.safeParse($).success,gJ$,hJ$=($)=>gJ$.safeParse($).success,t$1,nW=($)=>t$1.safeParse($).success,b1,o$1,El=($)=>o$1.safeParse($).success,vG,Rp5,bB,lB4,o30,cB4,Fa,jl,uJ$,mB4,dB4,iB4,pB4,nB4,tB4,r30,r$1=($)=>r30.safeParse($).success,oB4,a$1,a30,lJ$=($)=>a30.safeParse($).success,s30,rB4,aB4,e30,sB4,Ua,Na,eB4,Ba,yB,$L4,La,$K0,ZK0,QK0,qp5,XK0,YK0,JK0,cJ$,mJ$,dJ$,s$1,iJ$,Oa,zl,pJ$,ZL4,eD,e$1,$w,$81,Z81,QL4,Pl,Q81,X81,XL4,YL4,JL4,GL4,KL4,WL4,HL4,FL4,Zw,Y81,UL4,Tl,J81,G81,K81,NL4,BL4,LL4,W81,OL4,H81,F81,DL4,wL4,GK0,Al,Da,uF,Mp5,jL4,Qw,U81,nJ$,wa,EL4,N81,zL4,PL4,TL4,AL4,RL4,qL4,ML4,p30,IL4,VL4,B81,OT,ja,kL4,SL4,CL4,_L4,vL4,xL4,fL4,bL4,yL4,gL4,hL4,uL4,lL4,cL4,mL4,L81,dL4,iL4,Xw,pL4,nL4,tL4,KK0,O81,oL4,rL4,D81,aL4,Ip5,Vp5,kp5,Sp5,Cp5,_p5,S1,rJ$;var JZ=L(()=>{aD=[rD,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],B7=y.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),xJ$=y.union([y.string(),y.number().int()]),fJ$=y.string(),Ap5=y.looseObject({ttl:y.number().optional(),pollInterval:y.number().optional()}),hB4=y.object({ttl:y.number().optional()}),uB4=y.object({taskId:y.string()}),n$1=y.looseObject({progressToken:xJ$.optional(),[sD]:uB4.optional()}),_G=y.object({_meta:n$1.optional()}),Ha=_G.extend({task:hB4.optional()}),qQ=y.object({method:y.string(),params:_G.loose().optional()}),JK=y.object({_meta:n$1.optional()}),GK=y.object({method:y.string(),params:JK.loose().optional()}),MQ=y.looseObject({_meta:n$1.optional()}),t30=y.union([y.string(),y.number().int()]),yJ$=y.object({jsonrpc:y.literal(n30),id:t30,...qQ.shape}).strict(),gJ$=y.object({jsonrpc:y.literal(n30),...GK.shape}).strict(),t$1=y.object({jsonrpc:y.literal(n30),id:t30,result:MQ}).strict();(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(b1||(b1={}));o$1=y.object({jsonrpc:y.literal(n30),id:t30.optional(),error:y.object({code:y.number().int(),message:y.string(),data:y.unknown().optional()})}).strict(),vG=y.union([yJ$,gJ$,t$1,o$1]),Rp5=y.union([t$1,o$1]),bB=MQ.strict(),lB4=JK.extend({requestId:t30.optional(),reason:y.string().optional()}),o30=GK.extend({method:y.literal("notifications/cancelled"),params:lB4}),cB4=y.object({src:y.string(),mimeType:y.string().optional(),sizes:y.array(y.string()).optional(),theme:y.enum(["light","dark"]).optional()}),Fa=y.object({icons:y.array(cB4).optional()}),jl=y.object({name:y.string(),title:y.string().optional()}),uJ$=jl.extend({...jl.shape,...Fa.shape,version:y.string(),websiteUrl:y.string().optional(),description:y.string().optional()}),mB4=y.intersection(y.object({applyDefaults:y.boolean().optional()}),y.record(y.string(),y.unknown())),dB4=y.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},y.intersection(y.object({form:mB4.optional(),url:B7.optional()}),y.record(y.string(),y.unknown()).optional())),iB4=y.looseObject({list:B7.optional(),cancel:B7.optional(),requests:y.looseObject({sampling:y.looseObject({createMessage:B7.optional()}).optional(),elicitation:y.looseObject({create:B7.optional()}).optional()}).optional()}),pB4=y.looseObject({list:B7.optional(),cancel:B7.optional(),requests:y.looseObject({tools:y.looseObject({call:B7.optional()}).optional()}).optional()}),nB4=y.object({experimental:y.record(y.string(),B7).optional(),sampling:y.object({context:B7.optional(),tools:B7.optional()}).optional(),elicitation:dB4.optional(),roots:y.object({listChanged:y.boolean().optional()}).optional(),tasks:iB4.optional(),extensions:y.record(y.string(),B7).optional()}),tB4=_G.extend({protocolVersion:y.string(),capabilities:nB4,clientInfo:uJ$}),r30=qQ.extend({method:y.literal("initialize"),params:tB4}),oB4=y.object({experimental:y.record(y.string(),B7).optional(),logging:B7.optional(),completions:B7.optional(),prompts:y.object({listChanged:y.boolean().optional()}).optional(),resources:y.object({subscribe:y.boolean().optional(),listChanged:y.boolean().optional()}).optional(),tools:y.object({listChanged:y.boolean().optional()}).optional(),tasks:pB4.optional(),extensions:y.record(y.string(),B7).optional()}),a$1=MQ.extend({protocolVersion:y.string(),capabilities:oB4,serverInfo:uJ$,instructions:y.string().optional()}),a30=GK.extend({method:y.literal("notifications/initialized"),params:JK.optional()}),s30=qQ.extend({method:y.literal("ping"),params:_G.optional()}),rB4=y.object({progress:y.number(),total:y.optional(y.number()),message:y.optional(y.string())}),aB4=y.object({...JK.shape,...rB4.shape,progressToken:xJ$}),e30=GK.extend({method:y.literal("notifications/progress"),params:aB4}),sB4=_G.extend({cursor:fJ$.optional()}),Ua=qQ.extend({params:sB4.optional()}),Na=MQ.extend({nextCursor:fJ$.optional()}),eB4=y.enum(["working","input_required","completed","failed","cancelled"]),Ba=y.object({taskId:y.string(),status:eB4,ttl:y.union([y.number(),y.null()]),createdAt:y.string(),lastUpdatedAt:y.string(),pollInterval:y.optional(y.number()),statusMessage:y.optional(y.string())}),yB=MQ.extend({task:Ba}),$L4=JK.merge(Ba),La=GK.extend({method:y.literal("notifications/tasks/status"),params:$L4}),$K0=qQ.extend({method:y.literal("tasks/get"),params:_G.extend({taskId:y.string()})}),ZK0=MQ.merge(Ba),QK0=qQ.extend({method:y.literal("tasks/result"),params:_G.extend({taskId:y.string()})}),qp5=MQ.loose(),XK0=Ua.extend({method:y.literal("tasks/list")}),YK0=Na.extend({tasks:y.array(Ba)}),JK0=qQ.extend({method:y.literal("tasks/cancel"),params:_G.extend({taskId:y.string()})}),cJ$=MQ.merge(Ba),mJ$=y.object({uri:y.string(),mimeType:y.optional(y.string()),_meta:y.record(y.string(),y.unknown()).optional()}),dJ$=mJ$.extend({text:y.string()}),s$1=y.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),iJ$=mJ$.extend({blob:s$1}),Oa=y.enum(["user","assistant"]),zl=y.object({audience:y.array(Oa).optional(),priority:y.number().min(0).max(1).optional(),lastModified:y.iso.datetime({offset:!0}).optional()}),pJ$=y.object({...jl.shape,...Fa.shape,uri:y.string(),description:y.optional(y.string()),mimeType:y.optional(y.string()),size:y.optional(y.number()),annotations:zl.optional(),_meta:y.optional(y.looseObject({}))}),ZL4=y.object({...jl.shape,...Fa.shape,uriTemplate:y.string(),description:y.optional(y.string()),mimeType:y.optional(y.string()),annotations:zl.optional(),_meta:y.optional(y.looseObject({}))}),eD=Ua.extend({method:y.literal("resources/list")}),e$1=Na.extend({resources:y.array(pJ$)}),$w=Ua.extend({method:y.literal("resources/templates/list")}),$81=Na.extend({resourceTemplates:y.array(ZL4)}),Z81=_G.extend({uri:y.string()}),QL4=Z81,Pl=qQ.extend({method:y.literal("resources/read"),params:QL4}),Q81=MQ.extend({contents:y.array(y.union([dJ$,iJ$]))}),X81=GK.extend({method:y.literal("notifications/resources/list_changed"),params:JK.optional()}),XL4=Z81,YL4=qQ.extend({method:y.literal("resources/subscribe"),params:XL4}),JL4=Z81,GL4=qQ.extend({method:y.literal("resources/unsubscribe"),params:JL4}),KL4=JK.extend({uri:y.string()}),WL4=GK.extend({method:y.literal("notifications/resources/updated"),params:KL4}),HL4=y.object({name:y.string(),description:y.optional(y.string()),required:y.optional(y.boolean())}),FL4=y.object({...jl.shape,...Fa.shape,description:y.optional(y.string()),arguments:y.optional(y.array(HL4)),_meta:y.optional(y.looseObject({}))}),Zw=Ua.extend({method:y.literal("prompts/list")}),Y81=Na.extend({prompts:y.array(FL4)}),UL4=_G.extend({name:y.string(),arguments:y.record(y.string(),y.string()).optional()}),Tl=qQ.extend({method:y.literal("prompts/get"),params:UL4}),J81=y.object({type:y.literal("text"),text:y.string(),annotations:zl.optional(),_meta:y.record(y.string(),y.unknown()).optional()}),G81=y.object({type:y.literal("image"),data:s$1,mimeType:y.string(),annotations:zl.optional(),_meta:y.record(y.string(),y.unknown()).optional()}),K81=y.object({type:y.literal("audio"),data:s$1,mimeType:y.string(),annotations:zl.optional(),_meta:y.record(y.string(),y.unknown()).optional()}),NL4=y.object({type:y.literal("tool_use"),name:y.string(),id:y.string(),input:y.record(y.string(),y.unknown()),_meta:y.record(y.string(),y.unknown()).optional()}),BL4=y.object({type:y.literal("resource"),resource:y.union([dJ$,iJ$]),annotations:zl.optional(),_meta:y.record(y.string(),y.unknown()).optional()}),LL4=pJ$.extend({type:y.literal("resource_link")}),W81=y.union([J81,G81,K81,LL4,BL4]),OL4=y.object({role:Oa,content:W81}),H81=MQ.extend({description:y.string().optional(),messages:y.array(OL4)}),F81=GK.extend({method:y.literal("notifications/prompts/list_changed"),params:JK.optional()}),DL4=y.object({title:y.string().optional(),readOnlyHint:y.boolean().optional(),destructiveHint:y.boolean().optional(),idempotentHint:y.boolean().optional(),openWorldHint:y.boolean().optional()}),wL4=y.object({taskSupport:y.enum(["required","optional","forbidden"]).optional()}),GK0=y.object({...jl.shape,...Fa.shape,description:y.string().optional(),inputSchema:y.object({type:y.literal("object"),properties:y.record(y.string(),B7).optional(),required:y.array(y.string()).optional()}).catchall(y.unknown()),outputSchema:y.object({type:y.literal("object"),properties:y.record(y.string(),B7).optional(),required:y.array(y.string()).optional()}).catchall(y.unknown()).optional(),annotations:DL4.optional(),execution:wL4.optional(),_meta:y.record(y.string(),y.unknown()).optional()}),Al=Ua.extend({method:y.literal("tools/list")}),Da=Na.extend({tools:y.array(GK0)}),uF=MQ.extend({content:y.array(W81).default([]),structuredContent:y.record(y.string(),y.unknown()).optional(),isError:y.boolean().optional()}),Mp5=uF.or(MQ.extend({toolResult:y.unknown()})),jL4=Ha.extend({name:y.string(),arguments:y.record(y.string(),y.unknown()).optional()}),Qw=qQ.extend({method:y.literal("tools/call"),params:jL4}),U81=GK.extend({method:y.literal("notifications/tools/list_changed"),params:JK.optional()}),nJ$=y.object({autoRefresh:y.boolean().default(!0),debounceMs:y.number().int().nonnegative().default(300)}),wa=y.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),EL4=_G.extend({level:wa}),N81=qQ.extend({method:y.literal("logging/setLevel"),params:EL4}),zL4=JK.extend({level:wa,logger:y.string().optional(),data:y.unknown()}),PL4=GK.extend({method:y.literal("notifications/message"),params:zL4}),TL4=y.object({name:y.string().optional()}),AL4=y.object({hints:y.array(TL4).optional(),costPriority:y.number().min(0).max(1).optional(),speedPriority:y.number().min(0).max(1).optional(),intelligencePriority:y.number().min(0).max(1).optional()}),RL4=y.object({mode:y.enum(["auto","required","none"]).optional()}),qL4=y.object({type:y.literal("tool_result"),toolUseId:y.string().describe("The unique identifier for the corresponding tool call."),content:y.array(W81).default([]),structuredContent:y.object({}).loose().optional(),isError:y.boolean().optional(),_meta:y.record(y.string(),y.unknown()).optional()}),ML4=y.discriminatedUnion("type",[J81,G81,K81]),p30=y.discriminatedUnion("type",[J81,G81,K81,NL4,qL4]),IL4=y.object({role:Oa,content:y.union([p30,y.array(p30)]),_meta:y.record(y.string(),y.unknown()).optional()}),VL4=Ha.extend({messages:y.array(IL4),modelPreferences:AL4.optional(),systemPrompt:y.string().optional(),includeContext:y.enum(["none","thisServer","allServers"]).optional(),temperature:y.number().optional(),maxTokens:y.number().int(),stopSequences:y.array(y.string()).optional(),metadata:B7.optional(),tools:y.array(GK0).optional(),toolChoice:RL4.optional()}),B81=qQ.extend({method:y.literal("sampling/createMessage"),params:VL4}),OT=MQ.extend({model:y.string(),stopReason:y.optional(y.enum(["endTurn","stopSequence","maxTokens"]).or(y.string())),role:Oa,content:ML4}),ja=MQ.extend({model:y.string(),stopReason:y.optional(y.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(y.string())),role:Oa,content:y.union([p30,y.array(p30)])}),kL4=y.object({type:y.literal("boolean"),title:y.string().optional(),description:y.string().optional(),default:y.boolean().optional()}),SL4=y.object({type:y.literal("string"),title:y.string().optional(),description:y.string().optional(),minLength:y.number().optional(),maxLength:y.number().optional(),format:y.enum(["email","uri","date","date-time"]).optional(),default:y.string().optional()}),CL4=y.object({type:y.enum(["number","integer"]),title:y.string().optional(),description:y.string().optional(),minimum:y.number().optional(),maximum:y.number().optional(),default:y.number().optional()}),_L4=y.object({type:y.literal("string"),title:y.string().optional(),description:y.string().optional(),enum:y.array(y.string()),default:y.string().optional()}),vL4=y.object({type:y.literal("string"),title:y.string().optional(),description:y.string().optional(),oneOf:y.array(y.object({const:y.string(),title:y.string()})),default:y.string().optional()}),xL4=y.object({type:y.literal("string"),title:y.string().optional(),description:y.string().optional(),enum:y.array(y.string()),enumNames:y.array(y.string()).optional(),default:y.string().optional()}),fL4=y.union([_L4,vL4]),bL4=y.object({type:y.literal("array"),title:y.string().optional(),description:y.string().optional(),minItems:y.number().optional(),maxItems:y.number().optional(),items:y.object({type:y.literal("string"),enum:y.array(y.string())}),default:y.array(y.string()).optional()}),yL4=y.object({type:y.literal("array"),title:y.string().optional(),description:y.string().optional(),minItems:y.number().optional(),maxItems:y.number().optional(),items:y.object({anyOf:y.array(y.object({const:y.string(),title:y.string()}))}),default:y.array(y.string()).optional()}),gL4=y.union([bL4,yL4]),hL4=y.union([xL4,fL4,gL4]),uL4=y.union([hL4,kL4,SL4,CL4]),lL4=Ha.extend({mode:y.literal("form").optional(),message:y.string(),requestedSchema:y.object({type:y.literal("object"),properties:y.record(y.string(),uL4),required:y.array(y.string()).optional()})}),cL4=Ha.extend({mode:y.literal("url"),message:y.string(),elicitationId:y.string(),url:y.string().url()}),mL4=y.union([lL4,cL4]),L81=qQ.extend({method:y.literal("elicitation/create"),params:mL4}),dL4=JK.extend({elicitationId:y.string()}),iL4=GK.extend({method:y.literal("notifications/elicitation/complete"),params:dL4}),Xw=MQ.extend({action:y.enum(["accept","decline","cancel"]),content:y.preprocess(($)=>$===null?void 0:$,y.record(y.string(),y.union([y.string(),y.number(),y.boolean(),y.array(y.string())])).optional())}),pL4=y.object({type:y.literal("ref/resource"),uri:y.string()}),nL4=y.object({type:y.literal("ref/prompt"),name:y.string()}),tL4=_G.extend({ref:y.union([nL4,pL4]),argument:y.object({name:y.string(),value:y.string()}),context:y.object({arguments:y.record(y.string(),y.string()).optional()}).optional()}),KK0=qQ.extend({method:y.literal("completion/complete"),params:tL4});O81=MQ.extend({completion:y.looseObject({values:y.array(y.string()).max(100),total:y.optional(y.number().int()),hasMore:y.optional(y.boolean())})}),oL4=y.object({uri:y.string().startsWith("file://"),name:y.string().optional(),_meta:y.record(y.string(),y.unknown()).optional()}),rL4=qQ.extend({method:y.literal("roots/list"),params:_G.optional()}),D81=MQ.extend({roots:y.array(oL4)}),aL4=GK.extend({method:y.literal("notifications/roots/list_changed"),params:JK.optional()}),Ip5=y.union([s30,r30,KK0,N81,Tl,Zw,eD,$w,Pl,YL4,GL4,Qw,Al,$K0,QK0,XK0,JK0]),Vp5=y.union([o30,e30,a30,aL4,La]),kp5=y.union([bB,OT,ja,Xw,D81,ZK0,YK0,yB]),Sp5=y.union([s30,B81,L81,rL4,$K0,QK0,XK0,JK0]),Cp5=y.union([o30,e30,PL4,WL4,X81,U81,F81,La,iL4]),_p5=y.union([bB,a$1,O81,H81,Y81,e$1,$81,Q81,uF,Da,ZK0,YK0,yB]);S1=class S1 extends Error{constructor($,Z,Q){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=Q,this.name="McpError"}static fromError($,Z,Q){if($===b1.UrlElicitationRequired&&Q){let X=Q;if(X.elicitations)return new rJ$(X.elicitations,Z)}return new S1($,Z,Q)}};rJ$=class rJ$ extends S1{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(b1.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});import{z as r$}from"zod";function eJ$($){return r$.record(r$.string(),r$.unknown()).nullable().refine((Z)=>Z===null||JSON.stringify(Z).length<=sJ$,{message:`${$} must serialize to at most ${sJ$} bytes`})}function lF($){return $!==null&&$!==void 0&&"command"in $}function Rl($){if(!$||!$.startsWith("virtual://"))return null;return $.replace("virtual://","")}function ql($){return`virtual://${$}`}var $G$,aJ$,sL4,eL4,$O4,sJ$=262144,LX,WK0,HK0;var ZG$=L(()=>{JZ();$G$=r$.object({authorizationEndpoint:r$.string().url(),tokenEndpoint:r$.string().url(),introspectionEndpoint:r$.string().url().optional(),clientId:r$.string(),clientSecret:r$.string().optional(),scopes:r$.array(r$.string()),grantType:r$.enum(["authorization_code","client_credentials"])}),aJ$=r$.object({type:r$.literal("object"),properties:r$.record(r$.string(),r$.unknown()).optional(),required:r$.array(r$.string()).optional()}).catchall(r$.unknown()),sL4=GK0.extend({inputSchema:aJ$,outputSchema:aJ$.optional()}),eL4=r$.object({headers:r$.record(r$.string(),r$.string()).optional()}),$O4=r$.object({command:r$.string().describe("Command to run (e.g., 'npx', 'node')"),args:r$.array(r$.string()).optional().describe("Command arguments"),cwd:r$.string().optional().describe("Working directory"),envVars:r$.record(r$.string(),r$.string()).optional().describe("Environment variables (encrypted in storage)")});LX=r$.object({id:r$.string().describe("Unique identifier for the connection"),title:r$.string().describe("Human-readable name for the connection"),created_at:r$.string().describe("When the connection was created"),updated_at:r$.string().describe("When the connection was last updated"),created_by:r$.string().describe("User ID who created the connection"),updated_by:r$.string().optional().describe("User ID who last updated the connection"),organization_id:r$.string().describe("Organization ID this connection belongs to"),description:r$.string().nullable().describe("Description of the connection"),icon:r$.string().nullable().describe("Icon URL for the connection"),app_name:r$.string().nullable().describe("Associated app name"),app_id:r$.string().nullable().describe("Associated app ID"),slug:r$.string().nullable().optional().describe("URL-safe slug derived from app_name, connection_url, or title"),connection_type:r$.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:r$.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:r$.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:r$.union([$O4,eL4]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:$G$.nullable().describe("OAuth configuration"),configuration_state:eJ$("configuration_state").describe("Configuration state (decrypted)"),configuration_scopes:r$.array(r$.string()).nullable().optional().describe("Configuration scopes"),metadata:eJ$("metadata").describe("Additional metadata (includes repository info)"),tools:r$.array(sL4).nullable().describe("Discovered tools from MCP"),bindings:r$.array(r$.string()).nullable().describe("Detected bindings"),status:r$.enum(["active","inactive","error"]).describe("Current status")}),WK0=LX.omit({created_at:!0,updated_at:!0,created_by:!0,updated_by:!0,organization_id:!0,tools:!0,bindings:!0,status:!0}).partial({id:!0,description:!0,icon:!0,app_name:!0,app_id:!0,connection_url:!0,connection_token:!0,connection_headers:!0,oauth_config:!0,configuration_state:!0,configuration_scopes:!0,metadata:!0}).extend({icon:r$.string().nullish()}),HK0=LX.partial()});import{z as S0}from"zod";function E81($){let Z=$?.homeTiles;if(Array.isArray(Z)&&Z.length>0)return Z;let Q=$?.homeTile;return Q?[Q]:[]}function gB($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z=$,Q={};for(let[X,Y]of Object.entries(Z)){if(!Y||typeof Y!=="object")continue;if(X!=="agent-sandbox"&&X!=="local-api")continue;try{Q[X]=z81.parse(Y)}catch{}}return Q}function P81($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z={};for(let[Q,X]of Object.entries($)){if(!X||typeof X!=="object"||Array.isArray(X))continue;let Y={};for(let[J,G]of Object.entries(X)){let K=gB(G);if(Object.keys(K).length>0)Y[J]=K}if(Object.keys(Y).length>0)Z[Q]=Y}return Z}var YG$,w81=500,JG$=200,ZO4=200,QO4=20,XO4=50,YO4=100,JO4=20,GO4=100,GG$=50,KO4=100,WO4=50,HO4=8192,KG$,FO4,WG$,j81,UO4,NO4,HG$,QG$,BO4,FK0,XG$,LO4,FG$,OO4,DO4,wO4,jO4,EO4,z81,UG$,zO4,PO4,TO4,AO4,RO4,qO4,MO4,NG$,IO4,T81,OX,A81,UK0,NK0;var BG$=L(()=>{YG$=S0.object({connection_id:S0.string().describe("Connection ID"),selected_tools:S0.array(S0.string()).nullable().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:S0.array(S0.string()).nullable().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:S0.array(S0.string()).nullable().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),KG$=YG$.extend({selected_tools:S0.array(S0.string()).max(w81).nullable().optional().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:S0.array(S0.string()).max(w81).nullable().optional().describe("Selected resource URIs or patterns. Supports * and ** wildcards for pattern matching. null = all resources included, array = only these resources included"),selected_prompts:S0.array(S0.string()).max(w81).nullable().optional().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),FO4=S0.object({connectionId:S0.string(),toolName:S0.string(),label:S0.string(),icon:S0.string().nullable().optional()}),WG$=S0.object({id:S0.string().describe("Stable id; used as React key and ?tab= value"),title:S0.string().describe("Tab label"),icon:S0.string().optional().describe("Optional lucide icon name"),view:S0.object({type:S0.literal("ext-app"),appId:S0.string(),args:S0.record(S0.string(),S0.unknown()).optional()})}),j81=S0.enum(["overview","reports","board","site-editor","assets","hosting","e2e","analytics","cdn","automations","experiments"]),UO4=S0.enum(["on","off"]),NO4=S0.enum(["on","off","manual","auto"]),HG$=S0.object({defaultMainView:S0.object({type:S0.string(),id:S0.string().optional(),toolName:S0.string().optional()}).nullable().optional(),chatDefaultOpen:S0.boolean().nullable().optional(),cmsDefaultOpen:S0.boolean().nullable().optional(),cms:NO4.nullable().optional().describe("How this agent offers content editing. Absent means on; the retired `manual` / `auto` read as on too."),sidebarViews:S0.array(j81).max(10).nullable().optional().describe("Deprecated layout-scoped sidebar selections. Read only as a fallback when metadata.sidebarViews is absent."),tabs:S0.array(WG$).max(JO4).optional()}),QG$=S0.object({tileId:S0.string().optional(),connectionId:S0.string().optional().describe("Connection that owns the resource \u2014 the host opens a direct MCP client to this connection so the iframe can call tools by their bare names."),resourceUri:S0.string().describe("ui:// resource URI exposed by `connectionId`. Read on the home page and rendered via MCPAppRenderer."),toolName:S0.string().optional().describe("Tool name \u2014 identifies which tool's inputSchema to display when editing tile props."),toolInput:S0.record(S0.string(),S0.unknown()).optional().describe("User-configured input props passed to MCPAppRenderer when rendering the tile."),minHeight:S0.number().int().positive().optional(),maxHeight:S0.number().int().positive().optional()}),BO4=S0.object({banner:S0.string().nullable().optional(),bannerColor:S0.string().nullable().optional(),icon:S0.string().nullable().optional(),themeColor:S0.string().nullable().optional(),pinnedViews:S0.array(FO4).max(YO4).nullable().optional(),layout:HG$.nullable().optional(),homeTile:QG$.nullable().optional(),homeTiles:S0.array(QG$).max(QO4).nullable().optional(),homePrompts:S0.array(S0.string()).max(XO4).nullable().optional()});FK0=/^[A-Za-z_][A-Za-z0-9_]*$/,XG$=S0.string().min(1).regex(FK0,{message:"Env var key must start with a letter or underscore and contain only letters, digits, and underscores."}),LO4=S0.discriminatedUnion("kind",[S0.object({key:XG$,kind:S0.literal("literal"),value:S0.string().max(HO4)}),S0.object({key:XG$,kind:S0.literal("secret"),secretId:S0.string().min(1)})]),FG$=/^[a-zA-Z0-9.-]+(?::[0-9]+)?$/,OO4=S0.object({host:S0.string().min(1).regex(FG$).describe("Submodule host, e.g. 'github.com' (bare hostname, no scheme)."),secretId:S0.string().min(1).describe("Vault secret id holding the PAT used to fetch this host.")}),DO4=S0.object({selected:S0.string().nullable().optional().describe("User-selected package manager (npm | pnpm | yarn | bun | deno). Null/absent means autodetect on next SANDBOX_START."),port:S0.string().nullable().optional().describe("User-selected dev server port as a string (allows '' / null for unset). Null/absent means autodetect."),path:S0.string().nullable().optional().describe("Optional path (relative to repo root) to the directory containing package.json. Null/absent means repo root. Forwarded as `application.packageManager.path` to the daemon config."),env:S0.array(LO4).max(KO4).nullable().optional().describe("Env vars injected on every SANDBOX_START. Literal entries inline their value; secret entries store a secretId that Studio resolves via the credential vault before posting /_sandbox/config."),submoduleCredentials:S0.array(OO4).max(WO4).nullable().optional().describe("Git credentials injected on every SANDBOX_START. Each entry maps a host to a vault secret (PAT) that Studio resolves before posting /_sandbox/config; the daemon installs it in the sandbox's git config, authenticating submodules and private package dependencies on that host.")}),wO4=S0.object({url:S0.string().describe("GitHub repository URL"),owner:S0.string().describe("Repository owner"),name:S0.string().describe("Repository name"),installationId:S0.number().optional().describe("GitHub App installation ID. Absent when the repo was linked without a GitHub connection (public-clone mode)."),connectionId:S0.string().optional().describe("ID of the mcp-github connection used for authentication. Absent for public repos cloned without credentials."),repositoryId:S0.string().optional().describe("First-class repository (REPOSITORY_LINK) backing this binding. When set, credentials come from the repository's git provider account rather than connectionId.")}),jO4=S0.enum(["agent-sandbox","local-api"]),EO4={sandboxHandle:S0.string().describe("Provider-specific handle"),previewUrl:S0.string().nullable().describe("URL where the sandbox's iframe-proxied UI is served, or null when the sandbox has no dev server (blank / tool sandboxes)."),sandboxApiUrl:S0.string().nullable().optional().describe("Direct sandbox API URL for runtimes that expose one. Equal to previewUrl for local-api; null/absent for AgentSandbox, which routes control traffic through hosted Studio."),createdAt:S0.number().optional().describe("Epoch ms the entry was first written by SANDBOX_START. Used by the booting overlay to show a stable elapsed timer that survives browser reloads. Optional for backward compatibility with entries written before this field existed."),startedWith:S0.object({packageManager:S0.string().nullable().optional().describe("metadata.runtime.selected at the time of SANDBOX_START"),port:S0.string().nullable().optional().describe("metadata.runtime.port at the time of SANDBOX_START"),path:S0.string().nullable().optional().describe("metadata.runtime.path at the time of SANDBOX_START")}).optional().describe("Snapshot of metadata.runtime fields (selected/port/path) used at SANDBOX_START. The Preview tab compares the live metadata.runtime against this to decide if a restart is required to apply changes.")},z81=S0.object(EO4);UG$=S0.record(S0.string().describe("userId"),S0.record(S0.string().describe("branch"),S0.partialRecord(jO4,z81)));zO4=S0.object({id:S0.string().describe("Stable identifier for this knowledge file"),name:S0.string().describe("File name shown in the UI"),kind:S0.enum(["file","skill"]).optional().describe("'file' (a single document) or 'skill' (a Claude Code skill folder containing SKILL.md). Defaults to 'file'."),volume:S0.string().describe("Org filesystem (Library) volume the file lives in"),path:S0.string().describe("Path within the volume"),url:S0.string().describe("Same-origin URL to read the file (display/download)"),contentType:S0.string().nullable().optional().describe("MIME type, used to decide whether to inline the content"),size:S0.number().nullable().optional().describe("File size in bytes"),addedAt:S0.string().describe("ISO timestamp when the file was attached")}),PO4=S0.array(zO4).max(GO4).nullable().optional().describe("Files attached to the agent as reference knowledge. Surfaced in the system prompt: small text documents are inlined, others are listed as retrievable references."),TO4=S0.enum(["smart","code-review","open"]),AO4=TO4.nullable().optional().describe("Controls when this code agent's changes may be published directly vs. requiring PR review. 'smart' (default) uses AI to judge per change; 'code-review' requires review for any code; 'open' allows direct publish always."),RO4=S0.boolean().nullable().optional().describe("Enable Fast Preview (sandbox-less): render the draft instantly on the preview server's own page via a ?__draft pointer, with reads/writes served by the decofile API against GitHub. Requires previewServerUrl (or legacy productionUrl) to be set to take effect."),qO4=S0.boolean().nullable().optional().describe("EXPERIMENTAL: with Fast Preview on, refresh content edits via an in-place /live/previews render (no commit, no reload) instead of a commit + re-navigation. Deco-runtime preview targets only. Requires fastPreview."),MO4=S0.string().nullable().optional().describe("Preview server URL \u2014 the deployment the CMS preview renders against (often the live site, e.g. https://acme.com). Painted in the preview iframe, and the render target for Fast Preview drafts. Supersedes the legacy productionUrl key."),NG$=S0.object({branch:S0.string().describe("Git branch backing this release"),name:S0.string().describe('User-facing name, e.g. "Black Friday 2026"'),color:S0.string().describe("Dot color token shown in the version switcher"),createdBy:S0.string().optional().describe("User ID who created the release"),createdAt:S0.string().optional().describe("ISO 8601 creation timestamp")}),IO4=S0.array(NG$).max(GG$).nullable().optional().describe("Curated list of named, branch-backed releases shown in the version switcher. The base branch ('No ar') is derived, not stored here."),T81={instructions:S0.string().nullable().optional().describe("Instructions also used as system prompt"),subAgents:S0.array(S0.string()).max(ZO4).nullable().optional().describe("Allowlist of Virtual MCP (agent) or concrete MCP connection IDs this agent may delegate to via subtask. Concrete connections create ephemeral subagents. null/absent = all active org targets; empty array = itself only."),liveAgentId:S0.string().nullable().optional().describe("ID of the live agent this (dev) agent develops. Set only on dev agents; powers the Develop/Live toggle. A dev agent is hidden from the sidebar (reached via the toggle on its live counterpart)."),ui:BO4.nullable().optional().describe("UI customization settings"),sidebarViews:S0.array(j81).max(10).nullable().optional().describe("Project views selected for the sidebar. Interpret as an exact list when sidebarViewsVersion is 1; unversioned values use legacy native-only semantics. Runtime presence gates still apply."),sidebarViewsVersion:S0.literal(1).optional().describe("Version 1 marks metadata.sidebarViews as an exact list that can disable legacy default rows."),githubRepo:wO4.nullable().optional().describe("Linked GitHub repository"),runtime:DO4.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),knowledge:PO4,siteSlug:S0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:AO4,previewServerUrl:MO4,productionUrl:S0.string().nullable().optional().describe("Legacy key for previewServerUrl \u2014 still read as a fallback. New writes use previewServerUrl."),fieldDescriptionTooltips:S0.boolean().nullable().optional().describe("Blocks form: opt in to showing a field's schema description as a hover tooltip on its title, instead of the default inline text below the title."),fastPreview:RO4,releases:IO4,fastPreviewInPlace:qO4},OX=S0.object({id:S0.string().describe("Unique identifier"),title:S0.string().describe("Human-readable name"),description:S0.string().nullable().describe("Description"),icon:S0.string().nullable().describe("Icon URL"),created_at:S0.string().describe("Creation timestamp"),updated_at:S0.string().describe("Last update timestamp"),created_by:S0.string().describe("User ID who created this item"),updated_by:S0.string().optional().describe("User ID who last updated this item"),organization_id:S0.string().describe("Organization ID this item belongs to"),status:S0.enum(["active","inactive"]).describe("Current status"),pinned:S0.boolean().describe("Whether this space is pinned to the sidebar"),metadata:S0.object(T81).extend({instructions:S0.string().nullable().describe("Instructions also used as system prompt"),sandboxMap:UG$.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }")}).loose().describe("Metadata"),connections:S0.array(YG$).describe("Connections with their selected tools, resources, and prompts")}),A81=S0.object({title:S0.string().min(1).max(120).describe("Short label shown on the chip"),description:S0.string().max(280).optional().describe("One-line subtitle shown under the title"),text:S0.string().min(1).max(4000).describe("The message sent to the agent when the prompt is clicked")}),UK0=S0.object({title:S0.string().min(1).max(255).describe("Name for the virtual MCP"),description:S0.string().max(500).nullable().optional().describe("Optional description"),icon:S0.string().nullish().describe("Optional icon URL"),status:S0.enum(["active","inactive"]).optional().default("active").describe("Initial status"),pinned:S0.boolean().optional().default(!1).describe("Pin to sidebar"),metadata:S0.object(T81).loose().superRefine(($,Z)=>{if("sandboxMap"in $)Z.addIssue({code:"custom",path:["sandboxMap"],message:"sandboxMap is managed by the sandbox lifecycle"})}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:S0.array(KG$).max(JG$).describe("Connections to include/exclude (can be empty for exclusion mode)"),prompts:S0.array(A81).max(20).optional().describe("Optional kickstart prompts to seed on the agent. Each becomes a clickable conversation starter (icebreaker) on the agent. Author them from the agent's role and the tools it will have so they're coherent and immediately useful.")}),NK0=S0.object({title:S0.string().min(1).max(255).optional().describe("New name"),description:S0.string().max(500).nullable().optional().describe("New description (null to clear)"),icon:S0.string().nullish().describe("New icon URL"),status:S0.enum(["active","inactive"]).optional().describe("New status"),pinned:S0.boolean().optional().describe("Pin/unpin from sidebar"),metadata:S0.object(T81).loose().superRefine(($,Z)=>{if("sandboxMap"in $)Z.addIssue({code:"custom",path:["sandboxMap"],message:"sandboxMap is managed by the sandbox lifecycle"})}).nullable().optional().describe("Additional metadata including MCP server instructions"),connections:S0.array(KG$).max(JG$).optional().describe("New connections (replaces existing)"),prompts:S0.array(A81).max(20).optional().describe("Replace the agent's kickstart prompts with this full set. Omit to leave them unchanged; pass an empty array to remove all. Each becomes a clickable conversation starter (icebreaker).")})});function DT($){return VO4.has($)}var AZ,VO4,BK0;var LG$=L(()=>{AZ=["deco","anthropic","openrouter","llmapi","google","openai-compatible"],VO4=new Set(AZ);BK0=[...AZ,"claude-code","codex"]});function R81($,Z){return{id:crypto.randomUUID(),type:Ea.STEP,source:"decopilot",subject:$,data:{stepCount:Z},time:new Date().toISOString()}}function LK0($,Z){return{id:crypto.randomUUID(),type:Ea.FINISH,source:"decopilot",subject:$,data:{status:Z},time:new Date().toISOString()}}function cF($,Z,Q){return{id:crypto.randomUUID(),type:Ea.THREAD_STATUS,source:"decopilot",subject:$,data:{status:Z,...Q?.messageId!==void 0&&{message_id:Q.messageId},...Q?.virtualMcpId!==void 0&&{virtual_mcp_id:Q.virtualMcpId},...Q?.createdBy!==void 0&&{created_by:Q.createdBy},...Q?.triggerId!==void 0&&{trigger_id:Q.triggerId},...Q?.title!==void 0&&{title:Q.title},...Q?.branch!==void 0&&{branch:Q.branch},...Q?.harnessId!==void 0&&{harness_id:Q.harnessId},...Q?.createdAt!==void 0&&{created_at:Q.createdAt},...Q?.updatedAt!==void 0&&{updated_at:Q.updatedAt},...Q?.metadata!==void 0&&{metadata:Q.metadata}},time:new Date().toISOString()}}var OG$,kO4,Ea,SO4;var DG$=L(()=>{OG$=["in_progress","requires_action","failed","completed"],kO4=[...OG$,"expired"],Ea={STEP:"decopilot.step",FINISH:"decopilot.finish",THREAD_STATUS:"decopilot.thread.status"},SO4=Object.values(Ea)});var OK0=L(()=>{ZG$();BG$();LG$();DG$()});var mF=L(()=>{OK0()});import{lookup as CO4}from"dns/promises";function za($,Z){if($===10)return!0;if($===172&&Z!==void 0&&Z>=16&&Z<=31)return!0;if($===192&&Z===168)return!0;if($===127)return!0;if($===169&&Z===254)return!0;if($===0)return!0;if($===100&&Z!==void 0&&Z>=64&&Z<=127)return!0;return!1}function q81($){let Z=Number.parseInt($.padStart(4,"0"),16);return[Z>>8,Z&255]}function wG$($){let Z=$.split(":").filter((Q)=>Q.length>0);if($.startsWith("2002:")&&Z.length>=2){let[Q,X]=q81(Z[1]);if(za(Q,X))return!0}if($.startsWith("64:ff9b::")&&Z.length>=4){let[Q,X]=q81(Z[Z.length-2]);if(za(Q,X))return!0}if($.startsWith("::")&&Z.length===2){let[Q,X]=q81(Z[0]);if(za(Q,X))return!0}return!1}function Ml($){try{let Q=new URL($).hostname.toLowerCase();if(Q==="localhost"||Q==="0.0.0.0"||Q.endsWith(".local")||Q.endsWith(".internal")||Q.endsWith(".localhost"))return!0;let X=Q.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(X){let[,Y,J]=X.map(Number);if(za(Y,J))return!0}if(Q.startsWith("[")&&Q.endsWith("]")){let Y=Q.slice(1,-1).toLowerCase();if(Y==="::1"||Y==="::")return!0;if(Y.startsWith("::ffff:"))return!0;if(Y.startsWith("fc")||Y.startsWith("fd"))return!0;if(Y.startsWith("fe80"))return!0;if(Y.startsWith("100:"))return!0;if(Y.startsWith("::1"))return!0;if(wG$(Y))return!0}return!1}catch{return!0}}function _O4($){let Z=$.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);if(Z){let[,X,Y]=Z.map(Number);return za(X,Y)}let Q=$.toLowerCase();if(Q==="::1"||Q==="::")return!0;if(Q.startsWith("::ffff:"))return!0;if(Q.startsWith("fc")||Q.startsWith("fd"))return!0;if(Q.startsWith("fe80"))return!0;if(Q.startsWith("100:"))return!0;return wG$(Q)}async function vO4($,Z=async(Q)=>(await CO4(Q,{all:!0})).map((X)=>X.address)){try{let Q=await Z($);return Q.length===0||Q.some(_O4)}catch{return!0}}async function Pa($){if(Ml($))return"URLs targeting private networks are not allowed";let Q=new URL($).hostname;if(/^\d+\.\d+\.\d+\.\d+$/.test(Q)||Q.startsWith("[")&&Q.endsWith("]"))return null;try{return await xO4(vO4(Q),5000,"DNS resolution timeout")?"URLs targeting private networks are not allowed":null}catch{return"URLs targeting private networks are not allowed"}}function xO4($,Z,Q){let X,Y=new Promise((J,G)=>{X=setTimeout(()=>G(Error(Q)),Z)});return Promise.race([$,Y]).finally(()=>clearTimeout(X))}function wT($=fetch){return async(Z,Q)=>{let X=await $(Z,{...Q,redirect:"manual"});if(X.status>=300&&X.status<400)throw Error("Refusing to follow a redirect from the remote server");return X}}var Ta=()=>{};function $4($){return`${$}_${CF()}`}var DX=L(()=>{zr()});function EG$($,Z){return{id:y4.SELF(Z),title:"Deco CMS",description:"The MCP for the CMS API",connection_type:"HTTP",connection_url:`${$}/mcp/self`,icon:"https://assets.decocache.com/mcp/09e44283-f47d-4046-955f-816d227c626f/app.png",app_name:"@deco/management-mcp",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"self"}}}function zG$($,Z){return{id:y4.DEV_ASSETS(Z),title:"Local Files",description:"Local file storage for development. Files are stored in /data/assets/.",connection_type:"HTTP",connection_url:`${$}/mcp/dev-assets`,icon:"https://api.iconify.design/lucide:folder.svg?color=%23888",app_name:"@deco/dev-assets-mcp",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isFixed:!0,devOnly:!0,type:"dev-assets"}}}function KK($){return{is(Z){if(!Z)return null;if(!Z.startsWith($))return null;return Z.slice($.length)||null},get(Z){return`${$}${Z}`}}}function PG$($){return{id:$.id,organization_id:$.organizationId,title:$.title,description:$.description,icon:$.icon,status:"active",created_at:new Date().toISOString(),updated_at:new Date().toISOString(),created_by:"system",updated_by:void 0,metadata:{instructions:$.instructions??null,...$.ui?{ui:$.ui}:{}},pinned:!1,connections:[]}}function I81($){return PG$({id:ET($),organizationId:$,title:"Super Agent",description:"Default agent that aggregates all organization connections",icon:fO4,ui:{layout:{defaultMainView:{type:"overview"},chatDefaultOpen:!0}}})}function MG$($){return PG$({id:yO4($),organizationId:$,title:"Brand context setup",description:"Guided onboarding agent that extracts brand context from a website URL.",icon:"https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",instructions:gO4})}function kG$($,Z,Q="https://reports.decocms.com/api/v2/mcp"){return{id:y4.REPORTS($),title:"Store Report",description:"Your store's report and diagnostics",connection_type:"HTTP",connection_url:Q,icon:"https://github.com/decocms.png",app_name:"commerce-discovery",app_id:null,connection_token:Z,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!1,type:"commerce-discovery"}}}function SG$($,Z=y4.REPORTS($)){return{title:"Report Agent",description:"Ask anything about your store's report",icon:"https://github.com/decocms.png",status:"active",pinned:!0,metadata:{type:"commerce-discovery",isDefault:!1,ui:{pinnedViews:[{connectionId:Z,toolName:"get_my_diagnostic",label:"Report",icon:"https://github.com/decocms.png"}],layout:{defaultMainView:{type:"ext-apps",id:Z,toolName:"get_my_diagnostic"},chatDefaultOpen:!0}}},connections:[{connection_id:Z,selected_tools:null,selected_resources:null,selected_prompts:null}]}}function CG$($){if(!$)return!1;return Object.values(jT).some((Z)=>Z.is($)!==null)}function _G$($){let Z=I81($);return{...Z,id:Z.id,connection_type:"VIRTUAL",connection_url:`virtual://${Z.id}`,app_name:"decopilot",app_id:"decopilot",connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"decopilot"},tools:[],bindings:[]}}var y4,jG$="https://reports.decocms.com/api/v2/mcp",DK0="get_my_diagnostic",TG$,IQ,ET,AG$,RG$,M81,fO4="https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",bO4="#6366f1",Zn5,qG$,wK0,yO4,gO4,IG$,Qn5,Xn5,VG$,Yn5,Il,jT,WK,V81,Jn5;var vG$=L(()=>{y4={SELF:($)=>`${$}_self`,REGISTRY:($)=>`${$}_registry`,COMMUNITY_REGISTRY:($)=>`${$}_community-registry`,DEV_ASSETS:($)=>`${$}_dev-assets`,SITE_DIAGNOSTICS:($)=>`site-diagnostics_${$}`,REPORTS:($)=>`${$}_commerce-discovery`};TG$=KK("decopilot_"),IQ=TG$.is,ET=TG$.get,AG$=KK("dev_"),RG$=AG$.get,M81=AG$.is,Zn5=`https://api.iconify.design/lucide:file-search.svg?color=${encodeURIComponent(bO4)}`;qG$=KK("brand-context-setup_"),wK0=qG$.is,yO4=qG$.get,gO4=`
|
|
2119
2119
|
You are running the brand-context onboarding for the user's organization. Your only job in this thread is to set up the organization's brand context:
|
|
2120
2120
|
|
|
2121
2121
|
1. If the user hasn't already given you a website URL, ask for it in one short message. Accept whatever URL they give \u2014 don't quibble about format.
|