decocms 4.182.2 → 4.182.3
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-BGrbeDYT.js → AlertCircle-BM-SGXEb.js} +1 -1
- package/dist/client/assets/{AreaChart-ChjS34cq.js → AreaChart-DYDhCZHa.js} +1 -1
- package/dist/client/assets/{ArrowUp-B7rh6W_b.js → ArrowUp-C8tFP7oQ.js} +1 -1
- package/dist/client/assets/{ArrowUpRight-An4hbib7.js → ArrowUpRight-CYabXmbx.js} +1 -1
- package/dist/client/assets/{Check-DpoXXYhc.js → Check-Ba7uuiUv.js} +1 -1
- package/dist/client/assets/{CheckCircle-DI16N69_.js → CheckCircle-DqAwJ2kz.js} +1 -1
- package/dist/client/assets/{ChevronDown-BbcA24KM.js → ChevronDown-HBIiFunc.js} +1 -1
- package/dist/client/assets/{ChevronRight-BamDO5gK.js → ChevronRight-KgA6xHru.js} +1 -1
- package/dist/client/assets/{ChevronUp-HIfNhOKS.js → ChevronUp-De0pNXr0.js} +1 -1
- package/dist/client/assets/{Copy01-Bnz3Wx80.js → Copy01-DYlP_Xtq.js} +1 -1
- package/dist/client/assets/{CpuChip01-BShcbCHO.js → CpuChip01-DU2mm5Rx.js} +1 -1
- package/dist/client/assets/{CreditCard01-DNJmFfow.js → CreditCard01-BNQMzQ0s.js} +1 -1
- package/dist/client/assets/{DotsVertical-B_iya6B7.js → DotsVertical-DWkfCVOi.js} +1 -1
- package/dist/client/assets/{Eye-BjhopnZD.js → Eye-pZSN52Qe.js} +1 -1
- package/dist/client/assets/{FilterLines-H3se16dF.js → FilterLines-UMA3hIS0.js} +1 -1
- package/dist/client/assets/{HardDrive-Cc0iy42M.js → HardDrive-srCmcA0T.js} +1 -1
- package/dist/client/assets/{Key01-C21diL-t.js → Key01-Cme8uyqy.js} +1 -1
- package/dist/client/assets/{LayoutLeft-NGYALHZo.js → LayoutLeft-CxujHsXA.js} +1 -1
- package/dist/client/assets/{LinkExternal01-BIYwVSjD.js → LinkExternal01-CQ9ayxbn.js} +1 -1
- package/dist/client/assets/{LogOut01-BYbHv1g4.js → LogOut01-1Wv_uc1f.js} +1 -1
- package/dist/client/assets/{Monitor01-PnI4BWSm.js → Monitor01-Dcr8x5_p.js} +1 -1
- package/dist/client/assets/{Palette-DqKGGY7c.js → Palette-C1hIu3Ny.js} +1 -1
- package/dist/client/assets/{Play-C6pKirQG.js → Play-S-SSyOWn.js} +1 -1
- package/dist/client/assets/{Plus-3NJoZ-Rn.js → Plus-BH5RlQYR.js} +1 -1
- package/dist/client/assets/{SearchLg-DUoOTY_-.js → SearchLg-ClGsPrv4.js} +1 -1
- package/dist/client/assets/{SearchMd-DZC0VFyz.js → SearchMd-CBT_BZMU.js} +1 -1
- package/dist/client/assets/{Settings02-K87UDDa_.js → Settings02-DAqQKtfC.js} +1 -1
- package/dist/client/assets/{Shield01-Dif9NKxP.js → Shield01-CBEZ92kQ.js} +1 -1
- package/dist/client/assets/{Star01-BWcFSKod.js → Star01-ybggVLHX.js} +1 -1
- package/dist/client/assets/{Stars01-DNjCGctC.js → Stars01-P8FnS4Ob.js} +1 -1
- package/dist/client/assets/{Stars02-CF9PavPD.js → Stars02-CwXREUM0.js} +1 -1
- package/dist/client/assets/{Sun-D_TMYzXg.js → Sun-C2vH3C3t.js} +1 -1
- package/dist/client/assets/{SwitchHorizontal01-Boo6w6_t.js → SwitchHorizontal01-wUPLzq-2.js} +1 -1
- package/dist/client/assets/{Tool01-BjfDVrJb.js → Tool01-EU3OKI0K.js} +1 -1
- package/dist/client/assets/{Tool02-df-j-2i7.js → Tool02-BLEoObxL.js} +1 -1
- package/dist/client/assets/{Trash01-BfrFYc0O.js → Trash01-Ck-P8aGE.js} +1 -1
- package/dist/client/assets/{TrendUp01-Bj5u2ghc.js → TrendUp01-Dnoj0uzg.js} +1 -1
- package/dist/client/assets/{Upload01-DGoH2Bw8.js → Upload01-BfzUamTH.js} +1 -1
- package/dist/client/assets/{User01-PHqRfaY2.js → User01-nRScdv2C.js} +1 -1
- package/dist/client/assets/{Users01-CeRMXGJo.js → Users01-DkQNBnK5.js} +1 -1
- package/dist/client/assets/{Users03-Cwqfteu1.js → Users03-CQVGNtmL.js} +1 -1
- package/dist/client/assets/{X-D0lgdZFx.js → X-FgZ-pUjZ.js} +1 -1
- package/dist/client/assets/{XCircle-BEfRA2Fy.js → XCircle-BthmWHMF.js} +1 -1
- package/dist/client/assets/{XClose-Ca9PFBA7.js → XClose-BaQnC9xI.js} +1 -1
- package/dist/client/assets/{Zap-Cd4akcPN.js → Zap-Be3onl5O.js} +1 -1
- package/dist/client/assets/{ZapSquare-2syNvY2F.js → ZapSquare-BMfQVTWg.js} +1 -1
- package/dist/client/assets/{access-gate-BXHarpej.js → access-gate-B1fbLcF-.js} +1 -1
- package/dist/client/assets/{add-section-modal-BtHF1Suz.js → add-section-modal-CTZrDcA0.js} +1 -1
- package/dist/client/assets/{agent-icon-CQRHN6rX.js → agent-icon-pCvoZl7q.js} +1 -1
- package/dist/client/assets/{agents-list-CwubhMUP.js → agents-list-eAJyi60W.js} +1 -1
- package/dist/client/assets/ai-providers-BWmz1gl9.js +1 -0
- package/dist/client/assets/{alert-Ig9SrjcF.js → alert-Dze3H8i7.js} +1 -1
- package/dist/client/assets/{alert-dialog-CWFjoJjX.js → alert-dialog-BlzJaa8V.js} +3 -3
- package/dist/client/assets/app-editor-DtrghDIo.js +1 -0
- package/dist/client/assets/{auth-av09Sk0f.js → auth-Dt1FgVt-.js} +1 -1
- package/dist/client/assets/{auth-catchall-DWcWxlY6.js → auth-catchall-C5_B1j2M.js} +1 -1
- package/dist/client/assets/{auth-entry-DOdCfRAO.js → auth-entry-DjciHJhD.js} +1 -1
- package/dist/client/assets/{auth-split-layout-CIY4l9vm.js → auth-split-layout-B1xiK1IR.js} +1 -1
- package/dist/client/assets/{authenticate-and-persist-oauth-CCHy3FzA.js → authenticate-and-persist-oauth-Cviuo8Q1.js} +1 -1
- package/dist/client/assets/{automation-list-row-CYmqpjOL.js → automation-list-row-dID9AHRm.js} +1 -1
- package/dist/client/assets/{automation-runs-D9S7Bj8t.js → automation-runs-C26JppiE.js} +1 -1
- package/dist/client/assets/{automations-g7LGm5hd.js → automations-BwdK--b_.js} +1 -1
- package/dist/client/assets/{avatar-I17szs3Q.js → avatar-DBrhL9V4.js} +1 -1
- package/dist/client/assets/{badge-1BKF0WjP.js → badge-BPApNEJW.js} +1 -1
- package/dist/client/assets/{billing-EZuyPlZX.js → billing-DN_RKE40.js} +1 -1
- package/dist/client/assets/{block-document-CrI42xhd.js → block-document-COs5H44P.js} +1 -1
- package/dist/client/assets/brand-context-B21j0sN5.js +1 -0
- package/dist/client/assets/{buckets-BjM-OEVV.js → buckets-KFhlHBlo.js} +1 -1
- package/dist/client/assets/bulk-category-panel-BADEHzYq.js +1 -0
- package/dist/client/assets/{calendar-ihm97ng4.js → calendar-BiblfYM2.js} +1 -1
- package/dist/client/assets/{capability-load-error-CdiziQNa.js → capability-load-error-tHIiKLCL.js} +1 -1
- package/dist/client/assets/{card-ZgfbVCh9.js → card-BJHBJJ4x.js} +1 -1
- package/dist/client/assets/category-editor-BbU-DL0t.js +1 -0
- package/dist/client/assets/chat-context-9UcSKOjs.js +35 -0
- package/dist/client/assets/{checkbox-CQ_C4vJL.js → checkbox-oKwqtltS.js} +1 -1
- package/dist/client/assets/{cli-auth-success-SOuYeldg.js → cli-auth-success-a3-XozgM.js} +1 -1
- package/dist/client/assets/collection-detail-5pOQoZmb.js +1 -0
- package/dist/client/assets/{collection-display-button-sALJ24Pj.js → collection-display-button-DdQrDX38.js} +1 -1
- package/dist/client/assets/{collection-search-Bxz23u0F.js → collection-search-B2Rk2PFz.js} +1 -1
- package/dist/client/assets/{collection-table-wrapper-Dl8DuNBG.js → collection-table-wrapper-CplGLCMf.js} +1 -1
- package/dist/client/assets/{collection-tabs-DJww20x9.js → collection-tabs-CjcZDKY1.js} +1 -1
- package/dist/client/assets/{command-bMsQFALP.js → command-BWXao0AD.js} +1 -1
- package/dist/client/assets/commerce-onboarding-Duhp8l88.js +1 -0
- package/dist/client/assets/{companions-core-DYxPDPJ-.js → companions-core-CPhEHg4n.js} +1 -1
- package/dist/client/assets/{connect-BS6fJ7Zh.js → connect-BElMRnN7.js} +1 -1
- package/dist/client/assets/connection-BrMDIb7a.js +1 -0
- package/dist/client/assets/{connection-card-Di6_Srf0.js → connection-card-D3Ty6JhX.js} +1 -1
- package/dist/client/assets/connection-detail-B1lHIVaD.js +1 -0
- package/dist/client/assets/connection-form-helpers-W-T5Qfdj.js +1 -0
- package/dist/client/assets/connections-Cog9YU6X.js +1 -0
- package/dist/client/assets/{decopilot-sse-pool-CsSaGM07.js → decopilot-sse-pool-CuLfeITa.js} +1 -1
- package/dist/client/assets/{dialog-DFfWjXhn.js → dialog-CfCzKpCQ.js} +1 -1
- package/dist/client/assets/{domain-settings-I5C-7sNQ.js → domain-settings-BnkZQdlv.js} +1 -1
- package/dist/client/assets/{drawer-CjxVq45y.js → drawer-DsKBdrka.js} +1 -1
- package/dist/client/assets/{dropdown-menu-DNVNevD7.js → dropdown-menu-BOsjh_jP.js} +1 -1
- package/dist/client/assets/{empty-state-BkAQUfnz.js → empty-state-D4Mka2Gg.js} +1 -1
- package/dist/client/assets/{extract-connection-data-D8g8Vhah.js → extract-connection-data-i2ZtRXrE.js} +1 -1
- package/dist/client/assets/file-explorer-NVFTJ0Q2.js +2 -0
- package/dist/client/assets/{form-Cy7Rd3TL.js → form-YDRn1yMf.js} +1 -1
- package/dist/client/assets/general-BvalpXOJ.js +1 -0
- package/dist/client/assets/{github-repo-picker-CKQYOUVF.js → github-repo-picker-CnMxEVo7.js} +1 -1
- package/dist/client/assets/{hooks-BYQbPRxe.js → hooks-BXNVyGlx.js} +5 -5
- package/dist/client/assets/{index-SVAVudgF.js → index-B5nVELgB.js} +1 -1
- package/dist/client/assets/{index-DW2rv6fU.js → index-BipvzcTH.js} +1 -1
- package/dist/client/assets/{index-BZsTAPza.js → index-BomFvFPo.js} +1 -1
- package/dist/client/assets/{index-4j84p8Zm.js → index-CdrwyuqH.js} +1 -1
- package/dist/client/assets/{index-C6AlWcn2.js → index-CgMf7tuL.js} +1 -1
- package/dist/client/assets/{index-geMXTkeP.js → index-CuR236Ha.js} +6 -6
- package/dist/client/assets/{index-Dyyz80fH.js → index-D-fArWDJ.js} +3 -3
- package/dist/client/assets/{index-DnUHHdy9.js → index-Dg4zAJRj.js} +1 -1
- package/dist/client/assets/{index-gWiN9Hkl.js → index-FYnRX-lh.js} +1 -1
- package/dist/client/assets/{index-y45nRZhN.js → index-FkDswteF.js} +36 -36
- package/dist/client/assets/{index-B1Swgh1Q.js → index-nNOweqCJ.js} +1 -1
- package/dist/client/assets/{index-redirect-tLRs_ohU.js → index-redirect-DKJKnP-Y.js} +1 -1
- package/dist/client/assets/index-vC9isNVZ.js +1 -0
- package/dist/client/assets/{input-i4x2nRXJ.js → input-LqGTjd_-.js} +1 -1
- package/dist/client/assets/{integration-icon-G3CkJMl-.js → integration-icon-By0eBeMX.js} +1 -1
- package/dist/client/assets/invite-member-dialog-nMmKi1Dw.js +1 -0
- package/dist/client/assets/{label-cSCv6rYO.js → label-DbueIBWh.js} +1 -1
- package/dist/client/assets/{layout-Dc_sBLyQ.js → layout-DkyHBIiM.js} +1 -1
- package/dist/client/assets/{login-BiKFzoUX.js → login-yg0l5NxL.js} +1 -1
- package/dist/client/assets/{mcp-oauth-Dv6Uhpr5.js → mcp-oauth-D9FdzYSb.js} +1 -1
- package/dist/client/assets/{members-50SkOm91.js → members-DV3QjDmp.js} +1 -1
- package/dist/client/assets/{monaco-editor-DNmyyJIn.js → monaco-editor-B-w0IDRi.js} +4 -4
- package/dist/client/assets/{monitoring-stats-row-C66zfOZ2.js → monitoring-stats-row-CG62KH3t.js} +1 -1
- package/dist/client/assets/{multi-select-JtlKk2T8.js → multi-select-B4U1aQtZ.js} +1 -1
- package/dist/client/assets/{oauth-callback-BOmgYt-J.js → oauth-callback-BCCteQuS.js} +1 -1
- package/dist/client/assets/{oauth-callback-ai-provider-D-bUKmX5.js → oauth-callback-ai-provider-DizT_DDE.js} +1 -1
- package/dist/client/assets/{onboarding-Dd0xJ_jB.js → onboarding-Dw0tVWUj.js} +1 -1
- package/dist/client/assets/{org-layout-Cyx2dswG.js → org-layout-DgqNNUZG.js} +1 -1
- package/dist/client/assets/{organization-choice-Dmy0N3Ho.js → organization-choice-B6rLkOvV.js} +1 -1
- package/dist/client/assets/{orgs-c3mClxSP.js → orgs-Dp947FAc.js} +1 -1
- package/dist/client/assets/{page-seo-form-CT7Q9nSJ.js → page-seo-form-C22dOH9p.js} +1 -1
- package/dist/client/assets/{popover-i4jezHIh.js → popover-CSaBs6px.js} +1 -1
- package/dist/client/assets/post-editor-CmIraKOU.js +1 -0
- package/dist/client/assets/{primitives-DONjjQ2v.js → primitives-DReuS7-5.js} +1 -1
- package/dist/client/assets/profile-BeKnbyDV.js +1 -0
- package/dist/client/assets/project-app-view-BsOej2W7.js +1 -0
- package/dist/client/assets/record-editor-D37l3YDB.js +1 -0
- package/dist/client/assets/redirect-editor-DJ5p8874.js +1 -0
- package/dist/client/assets/registry-BEudubyl.js +2 -0
- package/dist/client/assets/{registry-layout-f4c_WFt1.js → registry-layout-BnwCKqme.js} +1 -1
- package/dist/client/assets/{reports-CVDl7DQS.js → reports-BIMhh0lR.js} +1 -1
- package/dist/client/assets/{require-capability-6g_AHVvS.js → require-capability-BCSk620c.js} +1 -1
- package/dist/client/assets/{required-auth-layout-S0YtLBA5.js → required-auth-layout-BldmHV1q.js} +1 -1
- package/dist/client/assets/{reset-password-mvh2Bp76.js → reset-password-Bj8xjDsK.js} +1 -1
- package/dist/client/assets/roles-BfaqUbgp.js +1 -0
- package/dist/client/assets/{search-input-B-QuRigZ.js → search-input-Cz2eXhKE.js} +1 -1
- package/dist/client/assets/{secrets-DJdQx2SE.js → secrets-ovo_ybci.js} +1 -1
- package/dist/client/assets/sections-editor-C0_eGi1I.js +2 -0
- package/dist/client/assets/{select-model-BNaO-ex3.js → select-model-BnIVEhH-.js} +1 -1
- package/dist/client/assets/{select-D6zOoh5E.js → select-xvceoYep.js} +1 -1
- package/dist/client/assets/self-tool-result-DmMSQVL1.js +1 -0
- package/dist/client/assets/seo-editor-FY39F5Zk.js +1 -0
- package/dist/client/assets/{settings-layout-DhZgaTMP.js → settings-layout-BdGkfwA7.js} +1 -1
- package/dist/client/assets/{settings-section-jz9Avb_j.js → settings-section-EiAJkJ4N.js} +1 -1
- package/dist/client/assets/{shell-controls-Cp2LM0mr.js → shell-controls-iIBr8owK.js} +1 -1
- package/dist/client/assets/{shell-layout-D82GP0rP.js → shell-layout-DAJjI3Rs.js} +1 -1
- package/dist/client/assets/{sidebar-cviY2JKt.js → sidebar-BNKxKPMZ.js} +1 -1
- package/dist/client/assets/{skeleton-BnFORNZa.js → skeleton-DD7HtFsn.js} +1 -1
- package/dist/client/assets/{spinner-CkuCAiR1.js → spinner-LLDWVi4B.js} +1 -1
- package/dist/client/assets/{sso-De3-zYaW.js → sso-C8n1roGv.js} +1 -1
- package/dist/client/assets/{store-4sYEV7M-.js → store-Bwa_zaIs.js} +1 -1
- package/dist/client/assets/store-registry-DRTmI88U.js +2 -0
- package/dist/client/assets/{studio-tools-DH0-34Hv.js → studio-tools-BYaak_qp.js} +1 -1
- package/dist/client/assets/{switch-D2uF_EAp.js → switch-Bv-DzHZm.js} +1 -1
- package/dist/client/assets/{tab-id-VDxePu-8.js → tab-id-DxuL0R1D.js} +1 -1
- package/dist/client/assets/{table-D5WR7hLa.js → table-F2bqjmIf.js} +1 -1
- package/dist/client/assets/{tabs-CqBl7afq.js → tabs-CQao0ox2.js} +1 -1
- package/dist/client/assets/{textarea-Bn6hQ_Qz.js → textarea-z_orS_CZ.js} +1 -1
- package/dist/client/assets/{toggle-group-D7y3Qsoq.js → toggle-group-Bzyo3xHp.js} +1 -1
- package/dist/client/assets/{toolbar-CpuC8NsW.js → toolbar-BVAdvNw9.js} +1 -1
- package/dist/client/assets/{tooltip-BrF3GD_a.js → tooltip-DfT6t3c6.js} +1 -1
- package/dist/client/assets/{use-ai-providers-CaSDpPjb.js → use-ai-providers-D8p0kIkX.js} +1 -1
- package/dist/client/assets/{use-automations-mCzD08OY.js → use-automations-CDsgMRs6.js} +1 -1
- package/dist/client/assets/{use-autosave-Dys6xriZ.js → use-autosave-B5tSUOVj.js} +1 -1
- package/dist/client/assets/{use-capability-Cpe_qvZ_.js → use-capability-BracbdOf.js} +1 -1
- package/dist/client/assets/{use-clock-tick-CAblMTwd.js → use-clock-tick-BtQZuBEv.js} +1 -1
- package/dist/client/assets/{use-connection-B7cDwiOJ.js → use-connection-CTR51WTv.js} +1 -1
- package/dist/client/assets/{use-copy-r5QxG4Uf.js → use-copy-4XdNBPba.js} +1 -1
- package/dist/client/assets/{use-create-virtual-mcp-DcGH_7kD.js → use-create-virtual-mcp-DFC7TtKc.js} +1 -1
- package/dist/client/assets/{use-debounced-autosave-9sjmxrz4.js → use-debounced-autosave-YzTmmlaq.js} +1 -1
- package/dist/client/assets/{use-debounced-value-LrUb7eiJ.js → use-debounced-value-Qlcgz1AF.js} +1 -1
- package/dist/client/assets/use-deco-credits-B-wNnK5K.js +1 -0
- package/dist/client/assets/{use-decopilot-events-up5oIRDt.js → use-decopilot-events-B4kpfqJ7.js} +1 -1
- package/dist/client/assets/{use-delete-connection-B8yeqLKN.js → use-delete-connection-okh1cmv0.js} +1 -1
- package/dist/client/assets/{use-deployment-admin-nCX9A08B.js → use-deployment-admin-CNSUDbCN.js} +1 -1
- package/dist/client/assets/{use-file-configs-1vs3YVUZ.js → use-file-configs-2U32aFAz.js} +1 -1
- package/dist/client/assets/{use-infinite-scroll-CNsERN2g.js → use-infinite-scroll-fW1mUk4z.js} +1 -1
- package/dist/client/assets/{use-join-requests-6lnToRtO.js → use-join-requests-COJHDZ9A.js} +1 -1
- package/dist/client/assets/{use-mcp-client-BBl5zme6.js → use-mcp-client-Ldih0CNF.js} +1 -1
- package/dist/client/assets/{use-mcp-tools-BKtLcTYP.js → use-mcp-tools-De1Z4Bsb.js} +1 -1
- package/dist/client/assets/{use-members-stYO4DxP.js → use-members-D_Pos6TA.js} +1 -1
- package/dist/client/assets/{use-mobile-DMoYecwn.js → use-mobile-CD2TR_Uh.js} +1 -1
- package/dist/client/assets/{use-navigate-to-agent-ABFR-14c.js → use-navigate-to-agent-BtCzuuMV.js} +1 -1
- package/dist/client/assets/{use-open-billing-url-DU9jxy0C.js → use-open-billing-url-nHUE4wFt.js} +1 -1
- package/dist/client/assets/{use-org-auth-client-DoX1JG5g.js → use-org-auth-client-Dyc7d6wo.js} +1 -1
- package/dist/client/assets/{use-org-sso-BVhPMS3K.js → use-org-sso-18zw8l-m.js} +1 -1
- package/dist/client/assets/{use-organization-roles-A2d2BvKK.js → use-organization-roles-CuORVghr.js} +1 -1
- package/dist/client/assets/{use-organization-settings-DhcL4nY9.js → use-organization-settings-HM-EDIrS.js} +1 -1
- package/dist/client/assets/{use-registry-connections-BoF5es5w.js → use-registry-connections-_l7hkNKl.js} +1 -1
- package/dist/client/assets/{use-secrets-BmzIH3vm.js → use-secrets-BREYbuXr.js} +1 -1
- package/dist/client/assets/{use-status-sounds-DCcIH0HO.js → use-status-sounds-BbJ_tjn4.js} +1 -1
- package/dist/client/assets/{use-tags-B8ASGI2M.js → use-tags-CMzXMjhv.js} +1 -1
- package/dist/client/assets/{use-view-mode-xB_4AhUq.js → use-view-mode-c6O3y5le.js} +1 -1
- package/dist/client/assets/{use-virtual-mcp-CEV_ngrf.js → use-virtual-mcp-OghGCAy2.js} +1 -1
- package/dist/client/assets/useInfiniteQuery-BLssOond.js +1 -0
- package/dist/client/assets/{useRouterState-CZMj98pk.js → useRouterState-BxlLoYvq.js} +1 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-CABVQKcm.js +1 -0
- package/dist/client/assets/{users-CONOx6T6.js → users-CpFnJ49C.js} +1 -1
- package/dist/client/assets/{variant-calendar-E6f23yio.js → variant-calendar-CbQak9Hl.js} +1 -1
- package/dist/client/assets/{view-mode-toggle-DM6n_Ydg.js → view-mode-toggle-Z24MHOHM.js} +1 -1
- 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/ai-providers-BpVENL06.js +0 -1
- package/dist/client/assets/app-editor-B5H5-F8S.js +0 -1
- package/dist/client/assets/brand-context-DVPmwhF3.js +0 -1
- package/dist/client/assets/bulk-category-panel-USUYO_mP.js +0 -1
- package/dist/client/assets/category-editor-DQSbFl5w.js +0 -1
- package/dist/client/assets/chat-context-Duovvv_d.js +0 -35
- package/dist/client/assets/collection-detail-Fz2npTpx.js +0 -1
- package/dist/client/assets/commerce-onboarding-orMZD5VK.js +0 -1
- package/dist/client/assets/connection-CSUNWBHY.js +0 -1
- package/dist/client/assets/connection-detail-XkeoVAsF.js +0 -1
- package/dist/client/assets/connection-form-helpers-Dl1KTkNE.js +0 -1
- package/dist/client/assets/connections-3_b1sdLg.js +0 -1
- package/dist/client/assets/file-explorer-DjVkaNg4.js +0 -2
- package/dist/client/assets/general-CWjnB8Qn.js +0 -1
- package/dist/client/assets/index-a5f43C0l.js +0 -1
- package/dist/client/assets/invite-member-dialog-Bp5nMnrA.js +0 -1
- package/dist/client/assets/post-editor-ITfNNH8c.js +0 -1
- package/dist/client/assets/profile-CJ18mI2I.js +0 -1
- package/dist/client/assets/project-app-view-BEATiNjk.js +0 -1
- package/dist/client/assets/record-editor-CxzRU1Mb.js +0 -1
- package/dist/client/assets/redirect-editor-DmlZU7UI.js +0 -1
- package/dist/client/assets/registry-DHRSWQvL.js +0 -2
- package/dist/client/assets/roles-BDap8m-X.js +0 -1
- package/dist/client/assets/sections-editor-W06wfa9f.js +0 -2
- package/dist/client/assets/self-tool-result-Bjd_Fo-p.js +0 -1
- package/dist/client/assets/seo-editor-DKX2y5cI.js +0 -1
- package/dist/client/assets/store-registry-BKTzIEg1.js +0 -2
- package/dist/client/assets/use-deco-credits-Dp43HFr7.js +0 -1
- package/dist/client/assets/useInfiniteQuery-BI-Ge-Y8.js +0 -1
- package/dist/client/assets/useQueries-d_0_L-iH.js +0 -1
- package/dist/client/assets/useSuspenseInfiniteQuery-9ztDghoj.js +0 -1
package/dist/server/cli.js
CHANGED
|
@@ -1286,7 +1286,7 @@ Usage: deco services <up|down|status>`),process.exit(1)}}var ju1=O(()=>{Lv()});f
|
|
|
1286
1286
|
`.execute($);if(Number(W.rows[0]?.cnt)===0){console.warn(`Failed to migrate ${J}/${K}, keeping in old table`);continue}}await df`
|
|
1287
1287
|
DELETE FROM kysely_migration WHERE name = ${X}
|
|
1288
1288
|
`.execute($)}}async function Sm1($){await Zh6($),await Xh6($);let Z=new Mm1({db:$,provider:{getMigrations:()=>Promise.resolve(Ql0)}}),{error:X,results:Q}=await Z.migrateToLatest(),Y=0;if(Q?.forEach((G)=>{if(G.status==="Success")Y++;else if(G.status==="Error")console.error(`Failed to execute migration "${G.migrationName}"`)}),X)throw console.error("Failed to migrate"),console.error(X),X;return Y}async function Qh6($){let{keepOpen:Z=!1,database:X,skipBetterAuth:Q=!1}=$??{},Y="skipped";if(!Q&&!X)Y=await bg0();let G=X??H6(),J=async()=>{if(!Z&&!X)await Qw(G).catch((K)=>{console.warn("Warning: Error closing database:",K)})};try{let K=await Sm1(G.db);return await J(),{betterAuth:Y,kysely:K}}catch(K){throw await J(),K}}async function Yh6(){let $=H6(),Z=new Mm1({db:$.db,provider:{getMigrations:()=>Promise.resolve(Ql0)}}),{error:X,results:Q}=await Z.migrateDown();if(Q?.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}"`)}),X)throw console.error("Failed to rollback migration"),console.error(X),X}var Cm1=O(()=>{qm1();yg0();m7()});async function k50($){let Z={...process.env},X=T00($,Z);console.log($U1(X.settings.encryptionKey));let Q=X.settings.betterAuthSecret||(X.settings.localMode?ac1(X.settings.dataDir):""),{ensureServices:Y}=await Promise.resolve().then(() => (u$0(),h$0)),{outputs:G,services:J}=await Y({home:X.settings.dataDir,externalDatabaseUrl:X.externalDatabaseUrl,externalNatsUrl:X.externalNatsUrl});if(!X.skipMigrations){let{migrateBetterAuth:W}=await Promise.resolve().then(() => (yg0(),ec1));await W(G.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (m7(),Oc1)),{migrateToLatest:N}=await Promise.resolve().then(() => (Cm1(),Vm1)),U=H(G.databaseUrl);await N({keepOpen:!0,database:U,skipBetterAuth:!0})}let K={...X.settings,betterAuthSecret:Q,databaseUrl:G.databaseUrl,natsUrls:G.natsUrls,...G.s3?{s3Endpoint:G.s3.endpoint,s3Bucket:G.s3.bucket,s3AccessKeyId:G.s3.accessKeyId,s3SecretAccessKey:G.s3.secretAccessKey,s3ForcePathStyle:G.s3.forcePathStyle}:{},...G.natsTunnel?{natsPublicUrl:G.natsTunnel.publicUrl,natsAccountJwt:G.natsTunnel.accountJwt,natsAccountSigningKey:G.natsTunnel.accountSigningKey,natsOperatorJwt:G.natsTunnel.operatorJwt,natsTunnelPublicEnabled:!0,natsCredsPath:G.natsTunnel.credsPath}:{}};return Pu1(K),{settings:K,services:J.map((W)=>({name:W.name==="PostgreSQL"?"Postgres":W.name,port:W.port})),managedServiceNames:J.filter((W)=>W.owner==="managed").map((W)=>W.name)}}var Yl0=O(()=>{Lv();sc1();y8()});var vm1={};O0(vm1,{updateService:()=>yD,subscribeCliState:()=>Kl0,setTuiConsoleIntercepted:()=>S50,setServerUrl:()=>Om,setMigrationsDone:()=>Bm,setDevMode:()=>Kh6,resetCliStateForTests:()=>Gh6,isTuiConsoleIntercepted:()=>V50,getCliState:()=>Jl0,addLogEntry:()=>Ww});function _m1(){return{services:[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}],migrationsStatus:"pending",serverUrl:null,logs:[]}}function Gh6(){qQ=_m1()}function Jh6(){return[{name:"Postgres",status:"pending",port:0},{name:"NATS",status:"pending",port:0}]}function wm(){for(let $ of Gl0)$()}function Jl0(){return qQ}function Kl0($){return Gl0.add($),()=>Gl0.delete($)}function yD($){qQ={...qQ,services:qQ.services.map((Z)=>Z.name===$.name?$:Z)},wm()}function Bm(){qQ={...qQ,migrationsStatus:"done"},wm()}function Om($){qQ={...qQ,serverUrl:$},wm()}function Ww($){let Z=[...qQ.logs,$];qQ={...qQ,logs:Z.length>500?Z.slice(-500):Z},wm()}function Kh6(){qQ={...qQ,services:[...Jh6(),{name:"API",status:"pending",port:0},{name:"Vite",status:"pending",port:0}]},wm()}function S50($){xm1=$}function V50(){return xm1}var qQ,Gl0,xm1=!1;var gD=O(()=>{qQ=_m1();Gl0=new Set});import{createServer as fm1}from"net";function Wh6($){return new Promise((Z)=>{let X=fm1();X.once("error",()=>Z(!1)),X.listen($,"0.0.0.0",()=>{X.close(()=>Z(!0))})})}async function Lm($){if(await Wh6($))return $;let Z=await new Promise((X,Q)=>{let Y=fm1();Y.once("error",Q),Y.listen(0,"0.0.0.0",()=>{let G=Y.address(),J=typeof G==="object"&&G?G.port:0;Y.close(()=>X(J))})});return console.warn(`Port ${$} is in use, using port ${Z} instead.`),Z}var Wl0=()=>{};function Dm($){return $.replace(/\x1b\[[0-9;]*m/g,"")}var Hl0={};O0(Hl0,{startDevServer:()=>Nh6});import{join as Hh6}from"path";function bm1($){let Z=$.getReader(),X=new TextDecoder,Q="";function Y(){let G=Q.split(`
|
|
1289
|
-
`);Q=G.pop()??"";for(let J of G){let K=Dm(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;Ww({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{for(;;){let{done:G,value:J}=await Z.read();if(G)break;Q+=X.decode(J,{stream:!0}),Y()}if(Q.trim()){let G=Dm(Q).replace(/^\[\d+\]\s*/,"").trim();if(G)Ww({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function Nh6($){let{baseUrl:Z,noTui:X}=$,Q=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=Q?process.env.PORT:$.vitePort,G=Z||`http://localhost:${Y}`,J=Q?await Lm(Number(Y)+1):await Lm(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await k50({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)yD({name:L.name,status:"ready",port:L.port});Bm();let N=Hh6(import.meta.dir,"..","..","..","..",".."),U=X===!0,F=Bun.spawn(["bun","run","dev:servers"],{cwd:N,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:G,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.natsPublicUrl&&K.natsAccountJwt&&K.natsAccountSigningKey?{NATS_PUBLIC_URL:K.natsPublicUrl,NATS_ACCOUNT_JWT:K.natsAccountJwt,NATS_ACCOUNT_SIGNING_KEY:K.natsAccountSigningKey,NATS_OPERATOR_JWT:K.natsOperatorJwt??"",NATS_TUNNEL_PUBLIC_ENABLED:"true",...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)bm1(F.stdout),bm1(F.stderr);Om(G),yD({name:"Vite",status:"ready",port:Number(Y)}),yD({name:"API",status:"ready",port:Number(K.port)});let B=async(L)=>{if(F.kill(L),await F.exited,H.length>0){let{stopServices:D}=await Promise.resolve().then(() => (u$0(),h$0));await D(K.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(Y),process:F}}var Nl0=O(()=>{Yl0();gD();Wl0()});var C50;var Ul0=O(()=>{C50={name:"decocms",version:"4.182.2",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",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.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":"^3.0.85","@ai-sdk/google":"^3.0.83","@ai-sdk/openai":"^3.0.73","@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":"^2.9.1","@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":"^3.0.10","@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","@nats-io/jwt":"0.0.10-5","@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:"^6.0.208","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 Fh6,Text as ym1}from"ink";import{jsx as wh6,jsxs as gm1}from"react/jsx-runtime";function hm1({version:$}){return gm1(Fh6,{flexDirection:"column",marginTop:1,children:[K50.map((Z,X)=>wh6(ym1,{color:W50[X],children:Z},X)),gm1(ym1,{dimColor:!0,children:[" v",$]})]})}var um1=O(()=>{Xm()});import{Box as hD,Text as Hw}from"ink";import{Spinner as Bh6}from"@inkjs/ui";import{jsx as vY,jsxs as mf}from"react/jsx-runtime";function cm1({status:$}){if($==="pending")return vY(Bh6,{label:""});return vY(Hw,{color:"green",children:"\u2713"})}function Oh6($){return`${$.name}: ${$.port||"...."}`}function lm1({services:$,migrationsStatus:Z,home:X,serverUrl:Q}){return mf(hD,{flexDirection:"column",paddingBottom:1,children:[vY(hm1,{version:C50.version}),vY(hD,{marginBottom:1,children:vY(Hw,{dimColor:!0,children:"\u2500".repeat(80)})}),vY(hD,{children:mf(Hw,{dimColor:!0,children:["Home: ",X]})}),mf(hD,{gap:2,children:[$.map((Y)=>mf(hD,{gap:1,children:[vY(Hw,{children:Oh6(Y)}),vY(cm1,{status:Y.status})]},Y.name)),mf(hD,{gap:1,children:[vY(Hw,{children:"Migrations"}),vY(cm1,{status:Z})]})]}),vY(hD,{children:Q?mf(Hw,{children:["Open in browser: ",vY(Hw,{color:"cyan",children:Q})]}):vY(Hw,{dimColor:!0,children:"Starting..."})})]})}var dm1=O(()=>{Ul0();um1()});import{Box as Lh6,Text as Em}from"ink";import{jsx as Fl0,jsxs as wl0}from"react/jsx-runtime";function Dh6($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function mm1({logs:$}){return Fl0(Lh6,{flexDirection:"column",children:$.map((Z,X)=>{if(Z.rawLine)return Fl0(Em,{dimColor:!0,children:Z.rawLine},X);let Q=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return wl0(Em,{children:[wl0(Em,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),Fl0(Em,{color:Dh6(Z.status),children:Z.status}),wl0(Em,{dimColor:!0,children:[" ",Q.padStart(8)]})]},X)})})}var im1=()=>{};var Bl0={};O0(Bl0,{App:()=>jh6});import{Box as Eh6}from"ink";import{useSyncExternalStore as zh6}from"react";import{jsx as nm1,jsxs as Ph6}from"react/jsx-runtime";function jh6({home:$}){let Z=zh6(Kl0,Jl0);return Ph6(Eh6,{flexDirection:"column",children:[nm1(lm1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),nm1(mm1,{logs:Z.logs})]})}var Ol0=O(()=>{dm1();im1();gD()});var GJ="thread-gate",PN="decopilot-hosted-harness",lG="automations",Nw="background-tools";var pm1="7";function tm1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:pm1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var om1=()=>{};function Ah6(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function Ll0($,Z){for(let X=0;X<$.length;X++){let Q=$[X];if(Q===void 0)continue;if(Q===Z)return $[X+1];if(Q.startsWith(`${Z}=`))return Q.slice(Z.length+1)}return}function rm1(){let $=Ah6();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:Ll0($,"--cpu-prof-dir")??process.cwd(),name:Ll0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(Ll0($,"--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 am1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let X=xD();if(!X)return;let Q={};try{let{heapStats:Y}=await import("bun:jsc"),G=Y(),J=Object.entries(G.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);Q={objectCount:G.objectCount,heapSize:G.heapSize,top:Object.fromEntries(J)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:X.rss,heapUsed:X.heapUsed,heapTotal:X.heapTotal,external:X.external,arrayBuffers:X.arrayBuffers,...Q}))};return Z().catch(()=>{}),_50=setInterval(()=>void Z().catch(()=>{}),$),_50.unref?.(),process.on("SIGUSR2",()=>{try{let X=Bun.generateHeapSnapshot("v8"),Q=typeof X==="string"?X:JSON.stringify(X),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,Q),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(X){console.error("[heap-watch] snapshot failed:",X)}}),()=>{if(_50)clearInterval(_50)}}var _50;var sm1=()=>{};import*as Th6 from"bun:jsc";function em1(){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{Rh6()}catch(G){return console.error("[stall-watchdog] failed to start sampling profiler:",G),()=>{}}let X,Q=performance.now()+Z,Y=()=>{let G=performance.now(),J=G-Q;Q=G+Z;let K=[];try{K=Ih6()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let N of K){let U=N.frames.find((B)=>B.sourceURL&&!/Unknown Executable/.test(B.category??""))??N.frames[0];if(!U)continue;let F=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),w=`${U.name??"?"} @ ${F}:${U.line??"?"}`;W.set(w,(W.get(w)??0)+1)}let H=[...W.entries()].sort((N,U)=>U[1]-N[1]).slice(0,8).map(([N,U])=>({frame:N,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(J),samplesInWindow:K.length,top:H}))}X=setTimeout(Y,Z),X.unref?.()};return X=setTimeout(Y,Z),X.unref?.(),()=>{if(X)clearTimeout(X)}}var Rh6,Ih6;var $i1=O(()=>{({startSamplingProfiler:Rh6,samplingProfilerStackTraces:Ih6}=Th6)});function Zi1(){rm1();let $=[am1(),Kc1(),em1()];return()=>{for(let Z of $)Z()}}var Xi1=O(()=>{qg0();sm1();$i1()});var uD=_((Qi1)=>{Object.defineProperty(Qi1,"__esModule",{value:!0});Qi1.RepublishHeaders=Qi1.DirectMsgHeaders=Qi1.JsHeaders=Qi1.AdvisoryKind=void 0;Qi1.isOrderedPushConsumerOptions=qh6;Qi1.isPullConsumer=Mh6;Qi1.isPushConsumer=kh6;Qi1.isBoundPushConsumerOptions=Sh6;function qh6($){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 Mh6($){return $.isPullConsumer()}function kh6($){return $.isPushConsumer()}function Sh6($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}Qi1.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"};Qi1.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"};Qi1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};Qi1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var fY=_((Gi1)=>{Object.defineProperty(Gi1,"__esModule",{value:!0});Gi1.TD=Gi1.TE=Gi1.Empty=void 0;Gi1.encode=gh6;Gi1.decode=hh6;Gi1.Empty=new Uint8Array(0);Gi1.TE=new TextEncoder;Gi1.TD=new TextDecoder;function yh6(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}function gh6(...$){let Z=[];for(let X=0;X<$.length;X++)Z.push(Gi1.TE.encode($[X]));if(Z.length===0)return Gi1.Empty;if(Z.length===1)return Z[0];return yh6(...Z)}function hh6($){if(!$||$.length===0)return"";return Gi1.TD.decode($)}});var bY=_((Wi1)=>{Object.defineProperty(Wi1,"__esModule",{value:!0});Wi1.errors=Wi1.PermissionViolationError=Wi1.NoRespondersError=Wi1.TimeoutError=Wi1.RequestError=Wi1.ProtocolError=Wi1.ConnectionError=Wi1.DrainingConnectionError=Wi1.ClosedConnectionError=Wi1.AuthorizationError=Wi1.UserAuthenticationExpiredError=Wi1.InvalidOperationError=Wi1.InvalidArgumentError=Wi1.InvalidSubjectError=void 0;class El0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}Wi1.InvalidSubjectError=El0;class x50 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,X){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((Q)=>`'${Q}'`),$=$.join(",");else $=`'${$}'`;return new x50(`${$} ${Z}`,X)}}Wi1.InvalidArgumentError=x50;class zl0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}Wi1.InvalidOperationError=zl0;class v50 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new v50($);return null}}Wi1.UserAuthenticationExpiredError=v50;class f50 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],X=$.toLowerCase();for(let Q=0;Q<Z.length;Q++)if(X.indexOf(Z[Q])!==-1)return new f50($);return null}}Wi1.AuthorizationError=f50;class jl0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}Wi1.ClosedConnectionError=jl0;class Pl0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}Wi1.DrainingConnectionError=Pl0;class Al0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}Wi1.ConnectionError=Al0;class Tl0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}Wi1.ProtocolError=Tl0;class Rl0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof b50}}Wi1.RequestError=Rl0;class Il0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}Wi1.TimeoutError=Il0;class b50 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}Wi1.NoRespondersError=b50;class y50 extends Error{operation;subject;queue;constructor($,Z,X,Q,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=X,this.queue=Q}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let X="publish",Q="",Y=void 0,G=$.match(/(Publish|Subscription) to "(\S+)"/);if(G){if(X=G[1].toLowerCase(),Q=G[2],X==="subscription"){let J=$.match(/using queue "(\S+)"/);if(J)Y=J[1]}}return new y50($,X,Q,Y)}}Wi1.PermissionViolationError=y50;Wi1.errors={AuthorizationError:f50,ClosedConnectionError:jl0,ConnectionError:Al0,DrainingConnectionError:Pl0,InvalidArgumentError:x50,InvalidOperationError:zl0,InvalidSubjectError:El0,NoRespondersError:b50,PermissionViolationError:y50,ProtocolError:Tl0,RequestError:Rl0,TimeoutError:Il0,UserAuthenticationExpiredError:v50}});var JJ=_((wi1)=>{Object.defineProperty(wi1,"__esModule",{value:!0});wi1.SimpleMutex=wi1.Perf=void 0;wi1.extend=Xu6;wi1.render=Qu6;wi1.timeout=Yu6;wi1.delay=Gu6;wi1.deadline=Ju6;wi1.deferred=Ml0;wi1.debugDeferred=Ku6;wi1.shuffle=Wu6;wi1.collect=Hu6;wi1.jitter=Fi1;wi1.backoff=Nu6;wi1.nanos=Uu6;wi1.millis=Fu6;wi1.randomToken=Ou6;var Zu6=fY(),ql0=bY();function Xu6($,...Z){for(let X=0;X<Z.length;X++){let Q=Z[X];Object.keys(Q).forEach(function(Y){$[Y]=Q[Y]})}return $}function Qu6($){return Zu6.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function Yu6($,Z=!0){let X=Z?new ql0.TimeoutError:null,Q,Y,G=new Promise((J,K)=>{Q={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(X===null)K(new ql0.TimeoutError);else K(X)},$)});return Object.assign(G,Q)}function Gu6($=0){let Z,X=new Promise((Q)=>{let Y=setTimeout(()=>{Q()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),Q()}}});return Object.assign(X,Z)}async function Ju6($,Z=1000){let X=Ml0(),Q=setTimeout(()=>{X.reject(new ql0.TimeoutError)},Z);try{return await Promise.race([$,X])}finally{clearTimeout(Q)}}function Ml0(){let $={},Z=new Promise((X,Q)=>{$={resolve:X,reject:Q}});return Object.assign(Z,$)}function Ku6(){let $={},Z=new Promise((X,Q)=>{$={resolve:(Y)=>{console.trace("resolve",Y),X(Y)},reject:(Y)=>{console.trace("reject"),Q(Y)}}});return Object.assign(Z,$)}function Wu6($){for(let Z=$.length-1;Z>0;Z--){let X=Math.floor(Math.random()*(Z+1));[$[Z],$[X]]=[$[X],$[Z]]}return $}async function Hu6($){let Z=[];for await(let X of $)Z.push(X);return Z}class Ni1{timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,X){let Q=this.timers.get(Z);if(Q===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(X);if(Y===void 0)throw Error(`${X} is not defined`);this.measures.set($,Y-Q)}getEntries(){let $=[];return this.measures.forEach((Z,X)=>{$.push({name:X,duration:Z})}),$}}wi1.Perf=Ni1;class Ui1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=Ml0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}wi1.SimpleMutex=Ui1;function Fi1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function Nu6($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(X){return Fi1(X>Z?$[Z]:$[X])}}}function Uu6($){return $*1e6}function Fu6($){return Math.floor($/1e6)}var wu6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",AN=new Uint8Array(62);for(let $=0;$<62;$++)AN[$]=wu6.charCodeAt($);var Bu6=218340105584896;function Ou6(){let $=Math.floor(Math.random()*Bu6),Z=$%62,X=AN[Z];$=($-Z)/62,Z=$%62;let Q=AN[Z];$=($-Z)/62,Z=$%62;let Y=AN[Z];$=($-Z)/62,Z=$%62;let G=AN[Z];$=($-Z)/62,Z=$%62;let J=AN[Z];$=($-Z)/62,Z=$%62;let K=AN[Z];$=($-Z)/62,Z=$%62;let W=AN[Z];$=($-Z)/62;let H=AN[$];return String.fromCharCode(X,Q,Y,G,J,K,W,H)}});var Pi1=_((zi1)=>{Object.defineProperty(zi1,"__esModule",{value:!0});zi1.nuid=zi1.NuidImpl=void 0;var Cu6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Uw=62,h50=12,Di1=10,Oi1=33,_u6=333,Li1=h50+Di1,Sl0=new Uint8Array(Uw);for(let $=0;$<Uw;$++)Sl0[$]=Cu6.charCodeAt($);var g50=4294967296,Ei1=BigInt(Uw)**BigInt(Di1),zm=Number(Ei1/(1n<<32n)),kl0=Number(Ei1%(1n<<32n));function xu6($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function vu6($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else xu6($)}class Vl0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Li1),this.cbuf=new Uint8Array(h50),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(zm+1)),this.seqLo=Math.floor(Math.random()*g50);while($++<8&&this.seqHi===zm&&this.seqLo>=kl0);if(this.seqHi===zm&&this.seqLo>=kl0)this.seqLo=0;this.inc=Math.random()*(_u6-Oi1)+Oi1|0}setPre(){vu6(this.cbuf);for(let $=0;$<h50;$++)this.buf[$]=Sl0[this.cbuf[$]%Uw]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let X=Li1-1;X>=h50;X--){let Q=Math.floor($/Uw),G=($-Q*Uw)*g50+Z,J=Math.floor(G/Uw),K=G-J*Uw;this.buf[X]=Sl0[K],$=Q,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=g50)this.seqLo-=g50,this.seqHi+=1;if(this.seqHi>zm||this.seqHi===zm&&this.seqLo>=kl0)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()}}zi1.NuidImpl=Vl0;zi1.nuid=new Vl0});var Ii1=_((Ti1)=>{Object.defineProperty(Ti1,"__esModule",{value:!0});Ti1.nuid=Ti1.Nuid=void 0;var Ai1=Pi1();Ti1.Nuid=Ai1.NuidImpl;Ti1.nuid=Ai1.nuid});var c50=_((u50)=>{Object.defineProperty(u50,"__esModule",{value:!0});u50.nuid=u50.Nuid=void 0;var qi1=Ii1();Object.defineProperty(u50,"Nuid",{enumerable:!0,get:function(){return qi1.Nuid}});Object.defineProperty(u50,"nuid",{enumerable:!0,get:function(){return qi1.nuid}})});var Fw=_((Mi1)=>{Object.defineProperty(Mi1,"__esModule",{value:!0});Mi1.DEFAULT_HOST=Mi1.DEFAULT_PORT=Mi1.Match=void 0;Mi1.syncIterator=uu6;Mi1.createInbox=cu6;var gu6=c50(),hu6=bY();Mi1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function uu6($){let Z=$[Symbol.asyncIterator]();return{async next(){let X=await Z.next();if(X.done)return Promise.resolve(null);return Promise.resolve(X.value)}}}function cu6($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw hu6.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${gu6.nuid.next()}`}Mi1.DEFAULT_PORT=4222;Mi1.DEFAULT_HOST="127.0.0.1"});var jm=_((Ci1)=>{Object.defineProperty(Ci1,"__esModule",{value:!0});Ci1.DataBuffer=void 0;var Si1=fY();class Vi1{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}static fromAscii($){if(!$)$="";return Si1.TE.encode($)}static toAscii($){return Si1.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 X=0;X<this.buffers.length;X++)$.set(this.buffers[X],Z),Z+=this.buffers[X].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 X=this.byteLength;if($===void 0||$>X)$=X;let Q=Z.subarray(0,$);if(X>$)this.buffers.push(Z.subarray($));return this.byteLength=X-$,Q}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let X=0;X<Z.length;X++)if(Z[X]&&Z[X].length)this.buffers.push(Z[X]),this.byteLength+=Z[X].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}}Ci1.DataBuffer=Vi1});var cD=_((vi1)=>{Object.defineProperty(vi1,"__esModule",{value:!0});vi1.LF=vi1.CR=vi1.CRLF=vi1.CR_LF_LEN=vi1.CR_LF=void 0;vi1.setTransportFactory=ou6;vi1.defaultPort=ru6;vi1.getUrlParseFn=au6;vi1.newTransport=su6;vi1.getResolveFn=eu6;vi1.protoLen=xi1;vi1.extractProtocolMessage=$c6;var nu6=fY(),pu6=Fw(),tu6=jm(),yY;function ou6($){yY=$}function ru6(){return yY!==void 0&&yY.defaultPort!==void 0?yY.defaultPort:pu6.DEFAULT_PORT}function au6(){return yY!==void 0&&yY.urlParseFn?yY.urlParseFn:void 0}function su6(){if(!yY||typeof yY.factory!=="function")throw Error("transport fn is not set");return yY.factory()}function eu6(){return yY!==void 0&&yY.dnsResolveFn?yY.dnsResolveFn:void 0}vi1.CR_LF=`\r
|
|
1289
|
+
`);Q=G.pop()??"";for(let J of G){let K=Dm(J).replace(/^\[\d+\]\s*/,"").trim();if(!K)continue;Ww({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:K})}}(async()=>{for(;;){let{done:G,value:J}=await Z.read();if(G)break;Q+=X.decode(J,{stream:!0}),Y()}if(Q.trim()){let G=Dm(Q).replace(/^\[\d+\]\s*/,"").trim();if(G)Ww({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:G})}})()}async function Nh6($){let{baseUrl:Z,noTui:X}=$,Q=process.env.HOST==="0.0.0.0"&&Boolean(process.env.PORT),Y=Q?process.env.PORT:$.vitePort,G=Z||`http://localhost:${Y}`,J=Q?await Lm(Number(Y)+1):await Lm(Number($.port)),{settings:K,services:W,managedServiceNames:H}=await k50({port:String(J),home:$.home,baseUrl:$.baseUrl,localMode:$.localMode,skipMigrations:$.skipMigrations,noTui:$.noTui,vitePort:$.vitePort});for(let L of W)yD({name:L.name,status:"ready",port:L.port});Bm();let N=Hh6(import.meta.dir,"..","..","..","..",".."),U=X===!0,F=Bun.spawn(["bun","run","dev:servers"],{cwd:N,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:G,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.natsPublicUrl&&K.natsAccountJwt&&K.natsAccountSigningKey?{NATS_PUBLIC_URL:K.natsPublicUrl,NATS_ACCOUNT_JWT:K.natsAccountJwt,NATS_ACCOUNT_SIGNING_KEY:K.natsAccountSigningKey,NATS_OPERATOR_JWT:K.natsOperatorJwt??"",NATS_TUNNEL_PUBLIC_ENABLED:"true",...K.natsCredsPath?{NATS_CREDS:K.natsCredsPath}:{}}:{}},stdio:["inherit",U?"inherit":"pipe",U?"inherit":"pipe"]});if(!U)bm1(F.stdout),bm1(F.stderr);Om(G),yD({name:"Vite",status:"ready",port:Number(Y)}),yD({name:"API",status:"ready",port:Number(K.port)});let B=async(L)=>{if(F.kill(L),await F.exited,H.length>0){let{stopServices:D}=await Promise.resolve().then(() => (u$0(),h$0));await D(K.dataDir)}};return process.on("SIGINT",()=>B("SIGINT")),process.on("SIGTERM",()=>B("SIGTERM")),{port:Number(Y),process:F}}var Nl0=O(()=>{Yl0();gD();Wl0()});var C50;var Ul0=O(()=>{C50={name:"decocms",version:"4.182.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",check:"tsc --noEmit",start:"bun run ./dist/server/server.js",migrate:"bun run src/database/migrate.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":"^3.0.85","@ai-sdk/google":"^3.0.83","@ai-sdk/openai":"^3.0.73","@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":"^2.9.1","@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":"^3.0.10","@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","@nats-io/jwt":"0.0.10-5","@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:"^6.0.208","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 Fh6,Text as ym1}from"ink";import{jsx as wh6,jsxs as gm1}from"react/jsx-runtime";function hm1({version:$}){return gm1(Fh6,{flexDirection:"column",marginTop:1,children:[K50.map((Z,X)=>wh6(ym1,{color:W50[X],children:Z},X)),gm1(ym1,{dimColor:!0,children:[" v",$]})]})}var um1=O(()=>{Xm()});import{Box as hD,Text as Hw}from"ink";import{Spinner as Bh6}from"@inkjs/ui";import{jsx as vY,jsxs as mf}from"react/jsx-runtime";function cm1({status:$}){if($==="pending")return vY(Bh6,{label:""});return vY(Hw,{color:"green",children:"\u2713"})}function Oh6($){return`${$.name}: ${$.port||"...."}`}function lm1({services:$,migrationsStatus:Z,home:X,serverUrl:Q}){return mf(hD,{flexDirection:"column",paddingBottom:1,children:[vY(hm1,{version:C50.version}),vY(hD,{marginBottom:1,children:vY(Hw,{dimColor:!0,children:"\u2500".repeat(80)})}),vY(hD,{children:mf(Hw,{dimColor:!0,children:["Home: ",X]})}),mf(hD,{gap:2,children:[$.map((Y)=>mf(hD,{gap:1,children:[vY(Hw,{children:Oh6(Y)}),vY(cm1,{status:Y.status})]},Y.name)),mf(hD,{gap:1,children:[vY(Hw,{children:"Migrations"}),vY(cm1,{status:Z})]})]}),vY(hD,{children:Q?mf(Hw,{children:["Open in browser: ",vY(Hw,{color:"cyan",children:Q})]}):vY(Hw,{dimColor:!0,children:"Starting..."})})]})}var dm1=O(()=>{Ul0();um1()});import{Box as Lh6,Text as Em}from"ink";import{jsx as Fl0,jsxs as wl0}from"react/jsx-runtime";function Dh6($){if($>=500)return"red";if($>=400)return"yellow";if($>=300)return"cyan";return"green"}function mm1({logs:$}){return Fl0(Lh6,{flexDirection:"column",children:$.map((Z,X)=>{if(Z.rawLine)return Fl0(Em,{dimColor:!0,children:Z.rawLine},X);let Q=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return wl0(Em,{children:[wl0(Em,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),Fl0(Em,{color:Dh6(Z.status),children:Z.status}),wl0(Em,{dimColor:!0,children:[" ",Q.padStart(8)]})]},X)})})}var im1=()=>{};var Bl0={};O0(Bl0,{App:()=>jh6});import{Box as Eh6}from"ink";import{useSyncExternalStore as zh6}from"react";import{jsx as nm1,jsxs as Ph6}from"react/jsx-runtime";function jh6({home:$}){let Z=zh6(Kl0,Jl0);return Ph6(Eh6,{flexDirection:"column",children:[nm1(lm1,{services:Z.services,migrationsStatus:Z.migrationsStatus,home:$,serverUrl:Z.serverUrl}),nm1(mm1,{logs:Z.logs})]})}var Ol0=O(()=>{dm1();im1();gD()});var GJ="thread-gate",PN="decopilot-hosted-harness",lG="automations",Nw="background-tools";var pm1="7";function tm1($){return{name:"decocms",systemDatabaseUrl:$.systemDatabaseUrl,systemDatabaseSchemaName:"dbos",systemDatabasePoolSize:$.poolSize,runAdminServer:!1,executorID:$.executorID,applicationVersion:pm1,...$.listenQueues!==void 0?{listenQueues:$.listenQueues}:{}}}var om1=()=>{};function Ah6(){let $=(process.env.BUN_OPTIONS??"").split(/\s+/).filter(Boolean);return[...process.argv.slice(1),...$]}function Ll0($,Z){for(let X=0;X<$.length;X++){let Q=$[X];if(Q===void 0)continue;if(Q===Z)return $[X+1];if(Q.startsWith(`${Z}=`))return Q.slice(Z.length+1)}return}function rm1(){let $=Ah6();if($.includes("--cpu-prof")){console.log(JSON.stringify({msg:"cpu-profiling-active",dir:Ll0($,"--cpu-prof-dir")??process.cwd(),name:Ll0($,"--cpu-prof-name"),markdown:$.includes("--cpu-prof-md"),intervalUs:Number(Ll0($,"--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 am1(){if(process.env.HEAP_WATCH!=="1")return()=>{};let $=Number(process.env.HEAP_WATCH_INTERVAL_MS??60000),Z=async()=>{let X=xD();if(!X)return;let Q={};try{let{heapStats:Y}=await import("bun:jsc"),G=Y(),J=Object.entries(G.objectTypeCounts).sort((K,W)=>W[1]-K[1]).slice(0,20);Q={objectCount:G.objectCount,heapSize:G.heapSize,top:Object.fromEntries(J)}}catch{}console.log(JSON.stringify({msg:"heap-watch",ts:new Date().toISOString(),uptimeS:Math.round(process.uptime()),rss:X.rss,heapUsed:X.heapUsed,heapTotal:X.heapTotal,external:X.external,arrayBuffers:X.arrayBuffers,...Q}))};return Z().catch(()=>{}),_50=setInterval(()=>void Z().catch(()=>{}),$),_50.unref?.(),process.on("SIGUSR2",()=>{try{let X=Bun.generateHeapSnapshot("v8"),Q=typeof X==="string"?X:JSON.stringify(X),Y=`/tmp/heap-${process.pid}-${Date.now()}.heapsnapshot`;Bun.write(Y,Q),console.log(JSON.stringify({msg:"heap-snapshot-written",path:Y}))}catch(X){console.error("[heap-watch] snapshot failed:",X)}}),()=>{if(_50)clearInterval(_50)}}var _50;var sm1=()=>{};import*as Th6 from"bun:jsc";function em1(){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{Rh6()}catch(G){return console.error("[stall-watchdog] failed to start sampling profiler:",G),()=>{}}let X,Q=performance.now()+Z,Y=()=>{let G=performance.now(),J=G-Q;Q=G+Z;let K=[];try{K=Ih6()?.traces??[]}catch{}if(J>$&&K.length>0){let W=new Map;for(let N of K){let U=N.frames.find((B)=>B.sourceURL&&!/Unknown Executable/.test(B.category??""))??N.frames[0];if(!U)continue;let F=(U.sourceURL??"?").replace(/^.*\/node_modules\//,"node_modules/"),w=`${U.name??"?"} @ ${F}:${U.line??"?"}`;W.set(w,(W.get(w)??0)+1)}let H=[...W.entries()].sort((N,U)=>U[1]-N[1]).slice(0,8).map(([N,U])=>({frame:N,count:U}));console.warn(JSON.stringify({msg:"stall-stack",ts:new Date().toISOString(),lagMs:Math.round(J),samplesInWindow:K.length,top:H}))}X=setTimeout(Y,Z),X.unref?.()};return X=setTimeout(Y,Z),X.unref?.(),()=>{if(X)clearTimeout(X)}}var Rh6,Ih6;var $i1=O(()=>{({startSamplingProfiler:Rh6,samplingProfilerStackTraces:Ih6}=Th6)});function Zi1(){rm1();let $=[am1(),Kc1(),em1()];return()=>{for(let Z of $)Z()}}var Xi1=O(()=>{qg0();sm1();$i1()});var uD=_((Qi1)=>{Object.defineProperty(Qi1,"__esModule",{value:!0});Qi1.RepublishHeaders=Qi1.DirectMsgHeaders=Qi1.JsHeaders=Qi1.AdvisoryKind=void 0;Qi1.isOrderedPushConsumerOptions=qh6;Qi1.isPullConsumer=Mh6;Qi1.isPushConsumer=kh6;Qi1.isBoundPushConsumerOptions=Sh6;function qh6($){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 Mh6($){return $.isPullConsumer()}function kh6($){return $.isPushConsumer()}function Sh6($){if($&&typeof $==="object")return"deliver_subject"in $||"deliver_group"in $||"idle_heartbeat"in $;return!1}Qi1.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"};Qi1.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"};Qi1.DirectMsgHeaders={Stream:"Nats-Stream",Sequence:"Nats-Sequence",TimeStamp:"Nats-Time-Stamp",Subject:"Nats-Subject",LastSequence:"Nats-Last-Sequence",NumPending:"Nats-Num-Pending"};Qi1.RepublishHeaders={Stream:"Nats-Stream",Subject:"Nats-Subject",Sequence:"Nats-Sequence",LastSequence:"Nats-Last-Sequence",Size:"Nats-Msg-Size"}});var fY=_((Gi1)=>{Object.defineProperty(Gi1,"__esModule",{value:!0});Gi1.TD=Gi1.TE=Gi1.Empty=void 0;Gi1.encode=gh6;Gi1.decode=hh6;Gi1.Empty=new Uint8Array(0);Gi1.TE=new TextEncoder;Gi1.TD=new TextDecoder;function yh6(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}function gh6(...$){let Z=[];for(let X=0;X<$.length;X++)Z.push(Gi1.TE.encode($[X]));if(Z.length===0)return Gi1.Empty;if(Z.length===1)return Z[0];return yh6(...Z)}function hh6($){if(!$||$.length===0)return"";return Gi1.TD.decode($)}});var bY=_((Wi1)=>{Object.defineProperty(Wi1,"__esModule",{value:!0});Wi1.errors=Wi1.PermissionViolationError=Wi1.NoRespondersError=Wi1.TimeoutError=Wi1.RequestError=Wi1.ProtocolError=Wi1.ConnectionError=Wi1.DrainingConnectionError=Wi1.ClosedConnectionError=Wi1.AuthorizationError=Wi1.UserAuthenticationExpiredError=Wi1.InvalidOperationError=Wi1.InvalidArgumentError=Wi1.InvalidSubjectError=void 0;class El0 extends Error{constructor($,Z){super(`illegal subject: '${$}'`,Z);this.name="InvalidSubjectError"}}Wi1.InvalidSubjectError=El0;class x50 extends Error{constructor($,Z){super($,Z);this.name="InvalidArgumentError"}static format($,Z,X){if(Array.isArray(Z)&&Z.length>1)Z=Z[0];if(Array.isArray($))$=$.map((Q)=>`'${Q}'`),$=$.join(",");else $=`'${$}'`;return new x50(`${$} ${Z}`,X)}}Wi1.InvalidArgumentError=x50;class zl0 extends Error{constructor($,Z){super($,Z);this.name="InvalidOperationError"}}Wi1.InvalidOperationError=zl0;class v50 extends Error{constructor($,Z){super($,Z);this.name="UserAuthenticationExpiredError"}static parse($){if($.toLowerCase().indexOf("user authentication expired")!==-1)return new v50($);return null}}Wi1.UserAuthenticationExpiredError=v50;class f50 extends Error{constructor($,Z){super($,Z);this.name="AuthorizationError"}static parse($){let Z=["authorization violation","account authentication expired","authentication timeout"],X=$.toLowerCase();for(let Q=0;Q<Z.length;Q++)if(X.indexOf(Z[Q])!==-1)return new f50($);return null}}Wi1.AuthorizationError=f50;class jl0 extends Error{constructor(){super("closed connection");this.name="ClosedConnectionError"}}Wi1.ClosedConnectionError=jl0;class Pl0 extends Error{constructor(){super("connection draining");this.name="DrainingConnectionError"}}Wi1.DrainingConnectionError=Pl0;class Al0 extends Error{constructor($,Z){super($,Z);this.name="ConnectionError"}}Wi1.ConnectionError=Al0;class Tl0 extends Error{constructor($,Z){super($,Z);this.name="ProtocolError"}}Wi1.ProtocolError=Tl0;class Rl0 extends Error{constructor($="",Z){super($,Z);this.name="RequestError"}isNoResponders(){return this.cause instanceof b50}}Wi1.RequestError=Rl0;class Il0 extends Error{constructor($){super("timeout",$);this.name="TimeoutError"}}Wi1.TimeoutError=Il0;class b50 extends Error{subject;constructor($,Z){super(`no responders: '${$}'`,Z);this.subject=$,this.name="NoResponders"}}Wi1.NoRespondersError=b50;class y50 extends Error{operation;subject;queue;constructor($,Z,X,Q,Y){super($,Y);this.name="PermissionViolationError",this.operation=Z,this.subject=X,this.queue=Q}static parse($){if(($?$.toLowerCase():"").indexOf("permissions violation")===-1)return null;let X="publish",Q="",Y=void 0,G=$.match(/(Publish|Subscription) to "(\S+)"/);if(G){if(X=G[1].toLowerCase(),Q=G[2],X==="subscription"){let J=$.match(/using queue "(\S+)"/);if(J)Y=J[1]}}return new y50($,X,Q,Y)}}Wi1.PermissionViolationError=y50;Wi1.errors={AuthorizationError:f50,ClosedConnectionError:jl0,ConnectionError:Al0,DrainingConnectionError:Pl0,InvalidArgumentError:x50,InvalidOperationError:zl0,InvalidSubjectError:El0,NoRespondersError:b50,PermissionViolationError:y50,ProtocolError:Tl0,RequestError:Rl0,TimeoutError:Il0,UserAuthenticationExpiredError:v50}});var JJ=_((wi1)=>{Object.defineProperty(wi1,"__esModule",{value:!0});wi1.SimpleMutex=wi1.Perf=void 0;wi1.extend=Xu6;wi1.render=Qu6;wi1.timeout=Yu6;wi1.delay=Gu6;wi1.deadline=Ju6;wi1.deferred=Ml0;wi1.debugDeferred=Ku6;wi1.shuffle=Wu6;wi1.collect=Hu6;wi1.jitter=Fi1;wi1.backoff=Nu6;wi1.nanos=Uu6;wi1.millis=Fu6;wi1.randomToken=Ou6;var Zu6=fY(),ql0=bY();function Xu6($,...Z){for(let X=0;X<Z.length;X++){let Q=Z[X];Object.keys(Q).forEach(function(Y){$[Y]=Q[Y]})}return $}function Qu6($){return Zu6.TD.decode($).replace(/\n/g,"\u240A").replace(/\r/g,"\u240D")}function Yu6($,Z=!0){let X=Z?new ql0.TimeoutError:null,Q,Y,G=new Promise((J,K)=>{Q={cancel:()=>{if(Y)clearTimeout(Y)}},Y=setTimeout(()=>{if(X===null)K(new ql0.TimeoutError);else K(X)},$)});return Object.assign(G,Q)}function Gu6($=0){let Z,X=new Promise((Q)=>{let Y=setTimeout(()=>{Q()},$);Z={cancel:()=>{if(Y)clearTimeout(Y),Q()}}});return Object.assign(X,Z)}async function Ju6($,Z=1000){let X=Ml0(),Q=setTimeout(()=>{X.reject(new ql0.TimeoutError)},Z);try{return await Promise.race([$,X])}finally{clearTimeout(Q)}}function Ml0(){let $={},Z=new Promise((X,Q)=>{$={resolve:X,reject:Q}});return Object.assign(Z,$)}function Ku6(){let $={},Z=new Promise((X,Q)=>{$={resolve:(Y)=>{console.trace("resolve",Y),X(Y)},reject:(Y)=>{console.trace("reject"),Q(Y)}}});return Object.assign(Z,$)}function Wu6($){for(let Z=$.length-1;Z>0;Z--){let X=Math.floor(Math.random()*(Z+1));[$[Z],$[X]]=[$[X],$[Z]]}return $}async function Hu6($){let Z=[];for await(let X of $)Z.push(X);return Z}class Ni1{timers;measures;constructor(){this.timers=new Map,this.measures=new Map}mark($){this.timers.set($,performance.now())}measure($,Z,X){let Q=this.timers.get(Z);if(Q===void 0)throw Error(`${Z} is not defined`);let Y=this.timers.get(X);if(Y===void 0)throw Error(`${X} is not defined`);this.measures.set($,Y-Q)}getEntries(){let $=[];return this.measures.forEach((Z,X)=>{$.push({name:X,duration:Z})}),$}}wi1.Perf=Ni1;class Ui1{max;current;waiting;constructor($=1){this.max=$,this.current=0,this.waiting=[]}lock(){if(this.current++,this.current<=this.max)return Promise.resolve();let $=Ml0();return this.waiting.push($),$}unlock(){this.current--,this.waiting.pop()?.resolve()}}wi1.SimpleMutex=Ui1;function Fi1($){if($===0)return 0;return Math.floor($/2+Math.random()*$)}function Nu6($=[0,250,250,500,500,3000,5000]){if(!Array.isArray($))$=[0,250,250,500,500,3000,5000];let Z=$.length-1;return{backoff(X){return Fi1(X>Z?$[Z]:$[X])}}}function Uu6($){return $*1e6}function Fu6($){return Math.floor($/1e6)}var wu6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",AN=new Uint8Array(62);for(let $=0;$<62;$++)AN[$]=wu6.charCodeAt($);var Bu6=218340105584896;function Ou6(){let $=Math.floor(Math.random()*Bu6),Z=$%62,X=AN[Z];$=($-Z)/62,Z=$%62;let Q=AN[Z];$=($-Z)/62,Z=$%62;let Y=AN[Z];$=($-Z)/62,Z=$%62;let G=AN[Z];$=($-Z)/62,Z=$%62;let J=AN[Z];$=($-Z)/62,Z=$%62;let K=AN[Z];$=($-Z)/62,Z=$%62;let W=AN[Z];$=($-Z)/62;let H=AN[$];return String.fromCharCode(X,Q,Y,G,J,K,W,H)}});var Pi1=_((zi1)=>{Object.defineProperty(zi1,"__esModule",{value:!0});zi1.nuid=zi1.NuidImpl=void 0;var Cu6="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Uw=62,h50=12,Di1=10,Oi1=33,_u6=333,Li1=h50+Di1,Sl0=new Uint8Array(Uw);for(let $=0;$<Uw;$++)Sl0[$]=Cu6.charCodeAt($);var g50=4294967296,Ei1=BigInt(Uw)**BigInt(Di1),zm=Number(Ei1/(1n<<32n)),kl0=Number(Ei1%(1n<<32n));function xu6($){for(let Z=0;Z<$.length;Z++)$[Z]=Math.floor(Math.random()*256)}function vu6($){if(globalThis?.crypto?.getRandomValues)globalThis.crypto.getRandomValues($);else xu6($)}class Vl0{buf;cbuf;seqHi;seqLo;inc;inited;constructor(){this.buf=new Uint8Array(Li1),this.cbuf=new Uint8Array(h50),this.inited=!1}init(){this.inited=!0,this.setPre(),this.initSeqAndInc(),this.fillSeq()}initSeqAndInc(){let $=0;do this.seqHi=Math.floor(Math.random()*(zm+1)),this.seqLo=Math.floor(Math.random()*g50);while($++<8&&this.seqHi===zm&&this.seqLo>=kl0);if(this.seqHi===zm&&this.seqLo>=kl0)this.seqLo=0;this.inc=Math.random()*(_u6-Oi1)+Oi1|0}setPre(){vu6(this.cbuf);for(let $=0;$<h50;$++)this.buf[$]=Sl0[this.cbuf[$]%Uw]}fillSeq(){let $=this.seqHi,Z=this.seqLo;for(let X=Li1-1;X>=h50;X--){let Q=Math.floor($/Uw),G=($-Q*Uw)*g50+Z,J=Math.floor(G/Uw),K=G-J*Uw;this.buf[X]=Sl0[K],$=Q,Z=J}}next(){if(!this.inited)this.init();if(this.seqLo+=this.inc,this.seqLo>=g50)this.seqLo-=g50,this.seqHi+=1;if(this.seqHi>zm||this.seqHi===zm&&this.seqLo>=kl0)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()}}zi1.NuidImpl=Vl0;zi1.nuid=new Vl0});var Ii1=_((Ti1)=>{Object.defineProperty(Ti1,"__esModule",{value:!0});Ti1.nuid=Ti1.Nuid=void 0;var Ai1=Pi1();Ti1.Nuid=Ai1.NuidImpl;Ti1.nuid=Ai1.nuid});var c50=_((u50)=>{Object.defineProperty(u50,"__esModule",{value:!0});u50.nuid=u50.Nuid=void 0;var qi1=Ii1();Object.defineProperty(u50,"Nuid",{enumerable:!0,get:function(){return qi1.Nuid}});Object.defineProperty(u50,"nuid",{enumerable:!0,get:function(){return qi1.nuid}})});var Fw=_((Mi1)=>{Object.defineProperty(Mi1,"__esModule",{value:!0});Mi1.DEFAULT_HOST=Mi1.DEFAULT_PORT=Mi1.Match=void 0;Mi1.syncIterator=uu6;Mi1.createInbox=cu6;var gu6=c50(),hu6=bY();Mi1.Match={Exact:"exact",CanonicalMIME:"canonical",IgnoreCase:"insensitive"};function uu6($){let Z=$[Symbol.asyncIterator]();return{async next(){let X=await Z.next();if(X.done)return Promise.resolve(null);return Promise.resolve(X.value)}}}function cu6($=""){if($=$||"_INBOX",typeof $!=="string")throw TypeError("prefix must be a string");return $.split(".").forEach((Z)=>{if(Z==="*"||Z===">")throw hu6.InvalidArgumentError.format("prefix",`cannot have wildcards ('${$}')`)}),`${$}.${gu6.nuid.next()}`}Mi1.DEFAULT_PORT=4222;Mi1.DEFAULT_HOST="127.0.0.1"});var jm=_((Ci1)=>{Object.defineProperty(Ci1,"__esModule",{value:!0});Ci1.DataBuffer=void 0;var Si1=fY();class Vi1{buffers;byteLength;constructor(){this.buffers=[],this.byteLength=0}static concat(...$){let Z=0;for(let Y=0;Y<$.length;Y++)Z+=$[Y].length;let X=new Uint8Array(Z),Q=0;for(let Y=0;Y<$.length;Y++)X.set($[Y],Q),Q+=$[Y].length;return X}static fromAscii($){if(!$)$="";return Si1.TE.encode($)}static toAscii($){return Si1.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 X=0;X<this.buffers.length;X++)$.set(this.buffers[X],Z),Z+=this.buffers[X].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 X=this.byteLength;if($===void 0||$>X)$=X;let Q=Z.subarray(0,$);if(X>$)this.buffers.push(Z.subarray($));return this.byteLength=X-$,Q}}return new Uint8Array(0)}fill($,...Z){if($)this.buffers.push($),this.byteLength+=$.length;for(let X=0;X<Z.length;X++)if(Z[X]&&Z[X].length)this.buffers.push(Z[X]),this.byteLength+=Z[X].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}}Ci1.DataBuffer=Vi1});var cD=_((vi1)=>{Object.defineProperty(vi1,"__esModule",{value:!0});vi1.LF=vi1.CR=vi1.CRLF=vi1.CR_LF_LEN=vi1.CR_LF=void 0;vi1.setTransportFactory=ou6;vi1.defaultPort=ru6;vi1.getUrlParseFn=au6;vi1.newTransport=su6;vi1.getResolveFn=eu6;vi1.protoLen=xi1;vi1.extractProtocolMessage=$c6;var nu6=fY(),pu6=Fw(),tu6=jm(),yY;function ou6($){yY=$}function ru6(){return yY!==void 0&&yY.defaultPort!==void 0?yY.defaultPort:pu6.DEFAULT_PORT}function au6(){return yY!==void 0&&yY.urlParseFn?yY.urlParseFn:void 0}function su6(){if(!yY||typeof yY.factory!=="function")throw Error("transport fn is not set");return yY.factory()}function eu6(){return yY!==void 0&&yY.dnsResolveFn?yY.dnsResolveFn:void 0}vi1.CR_LF=`\r
|
|
1290
1290
|
`;vi1.CR_LF_LEN=vi1.CR_LF.length;vi1.CRLF=tu6.DataBuffer.fromAscii(vi1.CR_LF);vi1.CR=new Uint8Array(vi1.CRLF)[0];vi1.LF=new Uint8Array(vi1.CRLF)[1];function xi1($){for(let Z=0;Z<$.length;Z++){let X=Z+1;if($.byteLength>X&&$[Z]===vi1.CR&&$[X]===vi1.LF)return X+1}return 0}function $c6($){let Z=xi1($);if(Z>0){let Q=new Uint8Array($).slice(0,Z);return nu6.TD.decode(Q)}return""}});var fl0=_((li1)=>{Object.defineProperty(li1,"__esModule",{value:!0});li1.ipV4=hi1;li1.isIP=Uc6;li1.parseIP=ui1;var Pm=4,lD=16,l50=48,gi1=57,bi1=65,Hc6=70,yi1=97,Nc6=102,vl0=16777215;function hi1($,Z,X,Q){let Y=new Uint8Array(lD);return[0,0,0,0,0,0,0,0,0,0,255,255].forEach((J,K)=>{Y[K]=J}),Y[12]=$,Y[13]=Z,Y[14]=X,Y[15]=Q,Y}function Uc6($){return ui1($)!==void 0}function ui1($){for(let Z=0;Z<$.length;Z++)switch($[Z]){case".":return ci1($);case":":return Fc6($)}return}function ci1($){let Z=new Uint8Array(Pm);for(let X=0;X<Pm;X++){if($.length===0)return;if(X>0){if($[0]!==".")return;$=$.substring(1)}let{n:Q,c:Y,ok:G}=wc6($);if(!G||Q>255)return;$=$.substring(Y),Z[X]=Q}return hi1(Z[0],Z[1],Z[2],Z[3])}function Fc6($){let Z=new Uint8Array(lD),X=-1;if($.length>=2&&$[0]===":"&&$[1]===":"){if(X=0,$=$.substring(2),$.length===0)return Z}let Q=0;while(Q<lD){let{n:Y,c:G,ok:J}=Bc6($);if(!J||Y>65535)return;if(G<$.length&&$[G]==="."){if(X<0&&Q!=lD-Pm)return;if(Q+Pm>lD)return;let K=ci1($);if(K===void 0)return;Z[Q]=K[12],Z[Q+1]=K[13],Z[Q+2]=K[14],Z[Q+3]=K[15],$="",Q+=Pm;break}if(Z[Q]=Y>>8,Z[Q+1]=Y,Q+=2,$=$.substring(G),$.length===0)break;if($[0]!==":"||$.length==1)return;if($=$.substring(1),$[0]===":"){if(X>=0)return;if(X=Q,$=$.substring(1),$.length===0)break}}if($.length!==0)return;if(Q<lD){if(X<0)return;let Y=lD-Q;for(let G=Q-1;G>=X;G--)Z[G+Y]=Z[G];for(let G=X+Y-1;G>=X;G--)Z[G]=0}else if(X>=0)return;return Z}function wc6($){let Z=0,X=0;for(Z=0;Z<$.length&&l50<=$.charCodeAt(Z)&&$.charCodeAt(Z)<=gi1;Z++)if(X=X*10+($.charCodeAt(Z)-l50),X>=vl0)return{n:vl0,c:Z,ok:!1};if(Z===0)return{n:0,c:0,ok:!1};return{n:X,c:Z,ok:!0}}function Bc6($){let Z=0,X=0;for(X=0;X<$.length;X++){if(l50<=$.charCodeAt(X)&&$.charCodeAt(X)<=gi1)Z*=16,Z+=$.charCodeAt(X)-l50;else if(yi1<=$.charCodeAt(X)&&$.charCodeAt(X)<=Nc6)Z*=16,Z+=$.charCodeAt(X)-yi1+10;else if(bi1<=$.charCodeAt(X)&&$.charCodeAt(X)<=Hc6)Z*=16,Z+=$.charCodeAt(X)-bi1+10;else break;if(Z>=vl0)return{n:0,c:X,ok:!1}}if(X===0)return{n:0,c:X,ok:!1};return{n:Z,c:X,ok:!0}}});var cl0=_((mi1)=>{Object.defineProperty(mi1,"__esModule",{value:!0});mi1.Servers=mi1.ServerImpl=void 0;mi1.isIPV4OrHostname=di1;mi1.hostPort=ul0;var bl0=cD(),yl0=JJ(),gl0=fl0(),Ec6=Fw(),zc6=bY();function di1($){if($.indexOf("[")!==-1||$.indexOf("::")!==-1)return!1;if($.indexOf(".")!==-1)return!0;if($.split(":").length<=2)return!0;return!1}function hl0($){return!di1($)}function jc6($){let X=$.toUpperCase().indexOf("::FFFF:");if(X!==-1&&$.indexOf(".")!==-1){let Q=$.substring(X+7);return Q=Q.replace("[",""),Q.replace("]","")}return $}function ul0($){if($=$.trim(),$.match(/^(.*:\/\/)(.*)/m))$=$.replace(/^(.*:\/\/)(.*)/gm,"$2");if($=jc6($),hl0($)&&$.indexOf("[")===-1)$=`[${$}]`;let Z=hl0($)?$.match(/(]:)(\d+)/):$.match(/(:)(\d+)/),X=Z&&Z.length===3&&Z[1]&&Z[2]?parseInt(Z[2]):Ec6.DEFAULT_PORT,Y=new URL(`${X===80?"https":"http"}://${$}`);Y.port=`${X}`;let G=Y.hostname;if(G.charAt(0)==="[")G=G.substring(1,G.length-1);return{listen:Y.host,hostname:G,port:X}}class nf{src;listen;hostname;port;didConnect;reconnects;lastConnect;gossiped;tlsName;resolves;constructor($,Z=!1){this.src=$,this.tlsName="";let X=ul0($);this.listen=X.listen,this.hostname=X.hostname,this.port=X.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,gl0.isIP)(this.hostname))return[this];else{let X=await $.fn(this.hostname);if($.debug)console.log(`resolve ${this.hostname} = ${X.join(",")}`);for(let Q of X){let Y=this.port===80?"https":"http",G=new URL(`${Y}://${hl0(Q)?"["+Q+"]":Q}`);G.port=`${this.port}`;let J=new nf(G.host,!1);J.tlsName=this.hostname,Z.push(J)}}if($.randomize)(0,yl0.shuffle)(Z);return this.resolves=Z,Z}}mi1.ServerImpl=nf;class d50{firstSelect;servers;currentServer;tlsName;randomize;constructor($={}){this.firstSelect=!0,this.servers=[],this.tlsName="",this.randomize=$.randomize||!1}setServers($){if(!Array.isArray($)||$.length===0)throw zc6.InvalidArgumentError.format("servers","cannot be empty");let Z=(0,bl0.getUrlParseFn)(),X=new Map;for(let Y of this.servers)X.set(Y.listen,Y);let Q=[];for(let Y of $){Y=Z?Z(Y):Y;let{listen:G}=ul0(Y),J=X.get(G);if(J)J.gossiped=!1,Q.push(J);else Q.push(new nf(Y))}if(this.randomize)(0,yl0.shuffle)(Q);if(this.servers=Q,this.currentServer===void 0||!Q.includes(this.currentServer))this.currentServer=Q[0],this.firstSelect=!0}clear(){this.servers.length=0}updateTLSName(){let $=this.getCurrentServer();if(!(0,gl0.isIP)($.hostname))this.tlsName=$.hostname,this.servers.forEach((Z)=>{if(Z.gossiped)Z.tlsName=this.tlsName})}getCurrentServer(){return this.currentServer}addServer($,Z=!1){let X=(0,bl0.getUrlParseFn)();$=X?X($):$;let Q=new nf($,Z);if((0,gl0.isIP)(Q.hostname))Q.tlsName=this.tlsName;this.servers.push(Q)}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 d50.freezeAll(this.servers)}snapshotForHandler(){let $=this.currentServer;if(!$)return this.snapshot();let Z=this.servers.indexOf($);if(Z<=0)return this.snapshot();return d50.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 X=[],Q=[],Y=(0,bl0.getUrlParseFn)(),G=new Map;if($.connect_urls&&$.connect_urls.length>0)$.connect_urls.forEach((K)=>{K=Y?Y(K,Z):K;let W=new nf(K,!0);G.set(K,W)});let J=[];if(this.servers.forEach((K,W)=>{let H=K.listen;if(K.gossiped&&this.currentServer.listen!==H&&G.get(H)===void 0)J.push(W);G.delete(H)}),J.reverse(),J.forEach((K)=>{let W=this.servers.splice(K,1);Q=Q.concat(W[0].listen)}),G.forEach((K,W)=>{this.servers.push(K),X.push(W)}),this.randomize&&X.length>0){let K=this.currentServer,W=this.servers.filter((H)=>H!==K);(0,yl0.shuffle)(W),this.servers=K?[K,...W]:W}return{added:X,deleted:Q}}}mi1.Servers=d50});var m50=_((ti1)=>{Object.defineProperty(ti1,"__esModule",{value:!0});ti1.QueuedIteratorImpl=void 0;var ll0=JJ(),ni1=bY();class pi1{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,ll0.deferred)(),this.yields=[],this.iterClosed=(0,ll0.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(X){}}return}if(typeof $==="function")this.pendingFiltered++;this.yields.push($),this.signal.resolve()}async*iterate(){if(this.noIterator)throw new ni1.InvalidOperationError("iterator cannot be used when a callback is registered");if(this.yielding)throw new ni1.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 Q=$[Z];try{Q()}catch(Y){throw Y}if(this.err)throw this.err;continue}this.processed++,this.inflight--;let X=this.profile?Date.now():0;yield $[Z],this.time=this.profile?Date.now()-X:0}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,ll0.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}}ti1.QueuedIteratorImpl=pi1});var dl0=_((si1)=>{Object.defineProperty(si1,"__esModule",{value:!0});si1.MuxSubscription=void 0;var Rc6=Fw(),ri1=bY();class ai1{baseInbox;reqs;constructor(){this.reqs=new Map}size(){return this.reqs.size}init($){return this.baseInbox=`${(0,Rc6.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((X)=>{X.resolver(Z,{})}),!0;if(Z.operation==="publish"){let X=this.all().find((Q)=>{return Q.requestSubject===Z.subject});if(X)return X.resolver(Z,{}),!0}return!1}dispatcher(){return($,Z)=>{let X=this.getToken(Z);if(X){let Q=this.get(X);if(Q){if($===null)$=Z?.data?.length===0&&Z.headers?.code===503?new ri1.NoRespondersError(Q.requestSubject):null;Q.resolver($,Z)}}}}close(){let $=new ri1.RequestError("connection closed");this.reqs.forEach((Z)=>{Z.resolver($,{})})}}si1.MuxSubscription=ai1});var ml0=_((Zn1)=>{Object.defineProperty(Zn1,"__esModule",{value:!0});Zn1.Heartbeat=void 0;var Ic6=JJ();class $n1{ph;interval;maxOut;timer;pendings;constructor($,Z,X){this.ph=$,this.interval=Z,this.maxOut=X,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,Ic6.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})}}Zn1.Heartbeat=$n1});var pl0=_((Jn1)=>{Object.defineProperty(Jn1,"__esModule",{value:!0});Jn1.DenoBuffer=Jn1.MAX_SIZE=Jn1.AssertionError=void 0;Jn1.assert=Yn1;Jn1.concat=Gn1;Jn1.append=Mc6;Jn1.readAll=kc6;Jn1.writeAll=Sc6;var qc6=fY();class il0 extends Error{constructor($){super($);this.name="AssertionError"}}Jn1.AssertionError=il0;function Yn1($,Z="Assertion failed."){if(!$)throw new il0(Z)}var Qn1=32768;Jn1.MAX_SIZE=4294967294;function i50($,Z,X=0){let Q=Z.byteLength-X;if($.byteLength>Q)$=$.subarray(0,Q);return Z.set($,X),$.byteLength}function Gn1($,Z){if($===void 0&&Z===void 0)return new Uint8Array(0);if($===void 0)return Z;if(Z===void 0)return $;let X=new Uint8Array($.length+Z.length);return X.set($,0),X.set(Z,$.length),X}function Mc6($,Z){return Gn1($,Uint8Array.of(Z))}class nl0{_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($){Yn1($<=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=i50(this._buf.subarray(this._off),$);return this._off+=Z,Z}writeByte($){return this.write(Uint8Array.of($))}writeString($){return this.write(qc6.TE.encode($))}write($){let Z=this._grow($.byteLength);return i50($,this._buf,Z)}_grow($){let Z=this.length;if(Z===0&&this._off!==0)this.reset();let X=this._tryGrowByReslice($);if(X>=0)return X;let Q=this.capacity;if($<=Math.floor(Q/2)-Z)i50(this._buf.subarray(this._off),this._buf);else if(Q+$>Jn1.MAX_SIZE)throw Error("The buffer cannot be grown beyond the maximum size.");else{let Y=new Uint8Array(Math.min(2*Q+$,Jn1.MAX_SIZE));i50(this._buf.subarray(this._off),Y),this._buf=Y}return this._off=0,this._reslice(Math.min(Z+$,Jn1.MAX_SIZE)),Z}grow($){if($<0)throw Error("Buffer._grow: negative count");let Z=this._grow($);this._reslice(Z)}readFrom($){let Z=0,X=new Uint8Array(Qn1);while(!0){let Q=this.capacity-this.length<Qn1,Y=Q?X:new Uint8Array(this._buf.buffer,this.length),G=$.read(Y);if(G===null)return Z;if(Q)this.write(Y.subarray(0,G));else this._reslice(this.length+G);Z+=G}}}Jn1.DenoBuffer=nl0;function kc6($){let Z=new nl0;return Z.readFrom($),Z.bytes()}function Sc6($,Z){let X=0;while(X<Z.length)X+=$.write(Z.subarray(X))}});var rl0=_((Un1)=>{Object.defineProperty(Un1,"__esModule",{value:!0});Un1.cc=Un1.State=Un1.Parser=Un1.Kind=void 0;Un1.describe=bc6;var tl0=pl0(),ol0=fY();Un1.Kind={OK:0,ERR:1,MSG:2,INFO:3,PING:4,PONG:5};function bc6($){let Z,X="";switch($.kind){case Un1.Kind.MSG:Z="MSG";break;case Un1.Kind.OK:Z="OK";break;case Un1.Kind.ERR:Z="ERR",X=ol0.TD.decode($.data);break;case Un1.Kind.PING:Z="PING";break;case Un1.Kind.PONG:Z="PONG";break;case Un1.Kind.INFO:Z="INFO",X=ol0.TD.decode($.data)}return`${Z}: ${X}`}function Wn1(){let $={};return $.sid=-1,$.hdr=-1,$.size=-1,$}var Hn1=48,yc6=57,pf=67108864;class Nn1{dispatcher;state;as;drop;hdr;ma;argBuf;msgBuf;constructor($){this.dispatcher=$,this.state=Un1.State.OP_START,this.as=0,this.drop=0,this.hdr=0}parse($){let Z;for(Z=0;Z<$.length;Z++){let X=$[Z];switch(this.state){case Un1.State.OP_START:switch(X){case Un1.cc.M:case Un1.cc.m:this.state=Un1.State.OP_M,this.hdr=-1,this.ma=Wn1();break;case Un1.cc.H:case Un1.cc.h:this.state=Un1.State.OP_H,this.hdr=0,this.ma=Wn1();break;case Un1.cc.P:case Un1.cc.p:this.state=Un1.State.OP_P;break;case Un1.cc.PLUS:this.state=Un1.State.OP_PLUS;break;case Un1.cc.MINUS:this.state=Un1.State.OP_MINUS;break;case Un1.cc.I:case Un1.cc.i:this.state=Un1.State.OP_I;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_H:switch(X){case Un1.cc.M:case Un1.cc.m:this.state=Un1.State.OP_M;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_M:switch(X){case Un1.cc.S:case Un1.cc.s:this.state=Un1.State.OP_MS;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_MS:switch(X){case Un1.cc.G:case Un1.cc.g:this.state=Un1.State.OP_MSG;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_MSG:switch(X){case Un1.cc.SPACE:case Un1.cc.TAB:this.state=Un1.State.OP_MSG_SPC;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_MSG_SPC:switch(X){case Un1.cc.SPACE:case Un1.cc.TAB:continue;default:this.state=Un1.State.MSG_ARG,this.as=Z}break;case Un1.State.MSG_ARG:switch(X){case Un1.cc.CR:this.drop=1;break;case Un1.cc.NL:{let Q=this.argBuf?this.argBuf.bytes():$.subarray(this.as,Z-this.drop);this.processMsgArgs(Q),this.drop=0,this.as=Z+1,this.state=Un1.State.MSG_PAYLOAD,Z=this.as+this.ma.size-1;break}default:if(this.argBuf)this.argBuf.writeByte(X)}break;case Un1.State.MSG_PAYLOAD:if(this.msgBuf)if(this.msgBuf.length>=this.ma.size){let Q=this.msgBuf.bytes({copy:!1});this.dispatcher.push({kind:Un1.Kind.MSG,msg:this.ma,data:Q}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Un1.State.MSG_END}else{let Q=this.ma.size-this.msgBuf.length,Y=$.length-Z;if(Y<Q)Q=Y;if(Q>0)this.msgBuf.write($.subarray(Z,Z+Q)),Z=Z+Q-1;else this.msgBuf.writeByte(X)}else if(Z-this.as>=this.ma.size)this.dispatcher.push({kind:Un1.Kind.MSG,msg:this.ma,data:$.subarray(this.as,Z)}),this.argBuf=void 0,this.msgBuf=void 0,this.state=Un1.State.MSG_END;break;case Un1.State.MSG_END:switch(X){case Un1.cc.NL:this.drop=0,this.as=Z+1,this.state=Un1.State.OP_START;break;default:continue}break;case Un1.State.OP_PLUS:switch(X){case Un1.cc.O:case Un1.cc.o:this.state=Un1.State.OP_PLUS_O;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_PLUS_O:switch(X){case Un1.cc.K:case Un1.cc.k:this.state=Un1.State.OP_PLUS_OK;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_PLUS_OK:switch(X){case Un1.cc.NL:this.dispatcher.push({kind:Un1.Kind.OK}),this.drop=0,this.state=Un1.State.OP_START;break}break;case Un1.State.OP_MINUS:switch(X){case Un1.cc.E:case Un1.cc.e:this.state=Un1.State.OP_MINUS_E;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_MINUS_E:switch(X){case Un1.cc.R:case Un1.cc.r:this.state=Un1.State.OP_MINUS_ER;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_MINUS_ER:switch(X){case Un1.cc.R:case Un1.cc.r:this.state=Un1.State.OP_MINUS_ERR;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_MINUS_ERR:switch(X){case Un1.cc.SPACE:case Un1.cc.TAB:this.state=Un1.State.OP_MINUS_ERR_SPC;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_MINUS_ERR_SPC:switch(X){case Un1.cc.SPACE:case Un1.cc.TAB:continue;default:this.state=Un1.State.MINUS_ERR_ARG,this.as=Z}break;case Un1.State.MINUS_ERR_ARG:switch(X){case Un1.cc.CR:this.drop=1;break;case Un1.cc.NL:{let Q;if(this.argBuf)Q=this.argBuf.bytes(),this.argBuf=void 0;else Q=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:Un1.Kind.ERR,data:Q}),this.drop=0,this.as=Z+1,this.state=Un1.State.OP_START;break}default:if(this.argBuf)this.argBuf.write(Uint8Array.of(X))}break;case Un1.State.OP_P:switch(X){case Un1.cc.I:case Un1.cc.i:this.state=Un1.State.OP_PI;break;case Un1.cc.O:case Un1.cc.o:this.state=Un1.State.OP_PO;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_PO:switch(X){case Un1.cc.N:case Un1.cc.n:this.state=Un1.State.OP_PON;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_PON:switch(X){case Un1.cc.G:case Un1.cc.g:this.state=Un1.State.OP_PONG;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_PONG:switch(X){case Un1.cc.NL:this.dispatcher.push({kind:Un1.Kind.PONG}),this.drop=0,this.state=Un1.State.OP_START;break}break;case Un1.State.OP_PI:switch(X){case Un1.cc.N:case Un1.cc.n:this.state=Un1.State.OP_PIN;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_PIN:switch(X){case Un1.cc.G:case Un1.cc.g:this.state=Un1.State.OP_PING;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_PING:switch(X){case Un1.cc.NL:this.dispatcher.push({kind:Un1.Kind.PING}),this.drop=0,this.state=Un1.State.OP_START;break}break;case Un1.State.OP_I:switch(X){case Un1.cc.N:case Un1.cc.n:this.state=Un1.State.OP_IN;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_IN:switch(X){case Un1.cc.F:case Un1.cc.f:this.state=Un1.State.OP_INF;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_INF:switch(X){case Un1.cc.O:case Un1.cc.o:this.state=Un1.State.OP_INFO;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_INFO:switch(X){case Un1.cc.SPACE:case Un1.cc.TAB:this.state=Un1.State.OP_INFO_SPC;break;default:throw this.fail($.subarray(Z))}break;case Un1.State.OP_INFO_SPC:switch(X){case Un1.cc.SPACE:case Un1.cc.TAB:continue;default:this.state=Un1.State.INFO_ARG,this.as=Z}break;case Un1.State.INFO_ARG:switch(X){case Un1.cc.CR:this.drop=1;break;case Un1.cc.NL:{let Q;if(this.argBuf)Q=this.argBuf.bytes(),this.argBuf=void 0;else Q=$.subarray(this.as,Z-this.drop);this.dispatcher.push({kind:Un1.Kind.INFO,data:Q}),this.drop=0,this.as=Z+1,this.state=Un1.State.OP_START;break}default:if(this.argBuf)this.argBuf.writeByte(X)}break;default:throw this.fail($.subarray(Z))}}if((this.state===Un1.State.MSG_ARG||this.state===Un1.State.MINUS_ERR_ARG||this.state===Un1.State.INFO_ARG)&&!this.argBuf)this.argBuf=new tl0.DenoBuffer($.subarray(this.as,Z-this.drop));if(this.state===Un1.State.MSG_PAYLOAD&&!this.msgBuf){if(!this.argBuf)this.cloneMsgArg();this.msgBuf=new tl0.DenoBuffer($.subarray(this.as))}}cloneMsgArg(){let $=this.ma.subject.length,Z=this.ma.reply?this.ma.reply.length:0,X=new Uint8Array($+Z);if(X.set(this.ma.subject),this.ma.reply)X.set(this.ma.reply,$);if(this.argBuf=new tl0.DenoBuffer(X),this.ma.subject=X.subarray(0,$),this.ma.reply)this.ma.reply=X.subarray($)}processMsgArgs($){if(this.hdr>=0)return this.processHeaderMsgArgs($);let Z=[],X=-1;for(let Q=0;Q<$.length;Q++)switch($[Q]){case Un1.cc.SPACE:case Un1.cc.TAB:case Un1.cc.CR:case Un1.cc.NL:if(X>=0)Z.push($.subarray(X,Q)),X=-1;break;default:if(X<0)X=Q}if(X>=0)Z.push($.subarray(X));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],pf);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],pf);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}: ${ol0.TD.decode($)}`)}processHeaderMsgArgs($){let Z=[],X=-1;for(let Q=0;Q<$.length;Q++)switch($[Q]){case Un1.cc.SPACE:case Un1.cc.TAB:case Un1.cc.CR:case Un1.cc.NL:if(X>=0)Z.push($.subarray(X,Q)),X=-1;break;default:if(X<0)X=Q}if(X>=0)Z.push($.subarray(X));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],pf),this.ma.size=this.protoParseInt(Z[3],pf);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],pf),this.ma.size=this.protoParseInt(Z[4],pf);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 X=0;for(let Q=0;Q<$.length;Q++){if($[Q]<Hn1||$[Q]>yc6)return-1;X=X*10+($[Q]-Hn1)}return Z!==void 0&&X>Z?-1:X}}Un1.Parser=Nn1;Un1.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};Un1.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 t50=_((wn1)=>{Object.defineProperty(wn1,"__esModule",{value:!0});wn1.MsgHdrsImpl=void 0;wn1.canonicalMIMEHeaderKey=sl0;wn1.headers=uc6;var Fn1=fY(),KJ=Fw(),p50=bY();function sl0($){let N=!0,U=Array($.length);for(let F=0;F<$.length;F++){let w=$.charCodeAt(F);if(w===58||w<33||w>126)throw p50.InvalidArgumentError.format("header",`'${$[F]}' is not a valid character in a header name`);if(N&&97<=w&&w<=122)w-=32;else if(!N&&65<=w&&w<=90)w+=32;U[F]=w,N=w==45}return String.fromCharCode(...U)}function uc6($=0,Z=""){if($===0&&Z!=="")throw p50.InvalidArgumentError.format("code","is required");else if($>0&&Z==="")throw p50.InvalidArgumentError.format("description","is required");return new tf($,Z)}var al0="NATS/1.0";class tf{_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,X]of this.headers){let Q=$.values(Z);if(X.length!==Q.length)return!1;let Y=[...X].sort(),G=[...Q].sort();for(let J=0;J<Y.length;J++)if(Y[J]!==G[J])return!1}return!0}return!1}static decode($){let Z=new tf,Q=Fn1.TD.decode($).split(`\r
|
|
1291
1291
|
`),Y=Q[0];if(Y!==al0){let G=Y.replace(al0,"").trim();if(G.length>0){if(Z._code=parseInt(G,10),isNaN(Z._code))Z._code=0;let J=Z._code.toString();G=G.replace(J,""),Z._description=G.trim()}}if(Q.length>=1)Q.slice(1).map((G)=>{if(G){let J=G.indexOf(":");if(J>-1){let K=G.slice(0,J),W=G.slice(J+1).trim();Z.append(K,W)}}});return Z}toString(){if(this.headers.size===0&&this._code===0)return"";let $=al0;if(this._code>0&&this._description!=="")$+=` ${this._code} ${this._description}`;for(let[Z,X]of this.headers)for(let Q=0;Q<X.length;Q++)$=`${$}\r
|
|
1292
1292
|
${Z}: ${X[Q]}`;return`${$}\r
|
|
@@ -1310,7 +1310,7 @@ ${K}`;N(D);return}if(J(null,E),X.strategy==="count"){if(W--,W===0)N()}if(X.strat
|
|
|
1310
1310
|
`}static header(){return`Test,Date,Lang,Version,Count,MsgPayload,Bytes,Millis,Async
|
|
1311
1311
|
`}}Rp1.Metric=Ow;class Pp1{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||zd6.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 Pd0.Perf,this.payload=this.size?new Uint8Array(this.size):Ed6.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:X}=$.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 Q=this.perf.getEntries(),Y=Q.find((F)=>F.name==="pubsub"),G=Q.find((F)=>F.name==="reqrep"),J=Q.find((F)=>F.name==="req"),K=Q.find((F)=>F.name==="rep"),W=Q.find((F)=>F.name==="pub"),H=Q.find((F)=>F.name==="sub"),N=this.nc.stats(),U=[];if(Y){let{name:F,duration:w}=Y,B=new Ow(F,w);B.msgs=this.msgs*2,B.bytes=N.inBytes+N.outBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}if(G){let{name:F,duration:w}=G,B=new Ow(F,w);B.msgs=this.msgs*2,B.bytes=N.inBytes+N.outBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}if(W){let{name:F,duration:w}=W,B=new Ow(F,w);B.msgs=this.msgs,B.bytes=N.outBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}if(H){let{name:F,duration:w}=H,B=new Ow(F,w);B.msgs=this.msgs,B.bytes=N.inBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}if(K){let{name:F,duration:w}=K,B=new Ow(F,w);B.msgs=this.msgs,B.bytes=N.inBytes+N.outBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}if(J){let{name:F,duration:w}=J,B=new Ow(F,w);B.msgs=this.msgs,B.bytes=N.inBytes+N.outBytes,B.lang=Z,B.version=X,B.payload=this.payload.length,U.push(B)}return U}async runCallbacks(){let $=[];if(this.sub){let Z=(0,Pd0.deferred)();$.push(Z);let X=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:()=>{if(X++,X===1)this.perf.mark("subStart");if(X===this.msgs)this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop"),Z.resolve()}})}if(this.rep){let Z=(0,Pd0.deferred)();$.push(Z);let X=0;this.nc.subscribe(this.subject,{max:this.msgs,callback:(Q,Y)=>{if(Y.respond(this.payload),X++,X===1)this.perf.mark("repStart");if(X===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 X=0;X<this.msgs;X++)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 X=[];for(let Q=0;Q<this.msgs;Q++)X.push(this.nc.request(this.subject,this.payload,{timeout:20000}));await Promise.all(X),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let X=0;X<this.msgs;X++)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,X=this.nc.subscribe(this.subject,{max:this.msgs}),Q=(async()=>{for await(let Y of X){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(Q)}if(this.sub){let Z=!1,X=this.nc.subscribe(this.subject,{max:this.msgs}),Q=(async()=>{for await(let Y of X)if(!Z)this.perf.mark("subStart"),Z=!0;this.perf.mark("subStop"),this.perf.measure("sub","subStart","subStop")})();$.push(Q)}if(this.pub){let Z=(async()=>{this.perf.mark("pubStart");for(let X=0;X<this.msgs;X++)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 X=[];for(let Q=0;Q<this.msgs;Q++)X.push(this.nc.request(this.subject,this.payload,{timeout:20000}));await Promise.all(X),this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}else{this.perf.mark("reqStart");for(let X=0;X<this.msgs;X++)await this.nc.request(this.subject);this.perf.mark("reqStop"),this.perf.measure("req","reqStart","reqStop")}})();$.push(Z)}await Promise.all($)}}Rp1.Bench=Pp1;function Ap1($,Z){return`${Tp1($/Z)}/sec`}function jd6($,Z){return`${Math.floor($/Z)} msgs/sec`}function Tp1($,Z=!1){let X=Z?1000:1024,Q=Z?["k","M","G","T","P","E"]:["K","M","G","T","P","E"],Y=Z?"iB":"B";if($<X)return`${$.toFixed(2)} ${Y}`;let G=parseInt(Math.log($)/Math.log(X)+""),J=parseInt(G-1+"");return`${($/Math.pow(X,G)).toFixed(2)} ${Q[J]}${Y}`}function Pd6($){return $.toString().replace(/\B(?=(\d{3})+(?!\d))/g,",")}});var Vp1=_((kp1)=>{Object.defineProperty(kp1,"__esModule",{value:!0});kp1.IdleHeartbeatMonitor=void 0;class Mp1{interval;maxOut;cancelAfter;timer;autoCancelTimer;last;missed;count;callback;constructor($,Z,X={maxOut:2}){this.interval=$,this.maxOut=X?.maxOut||2,this.cancelAfter=X?.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,X=2){this.interval=$,this.maxOut=X,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)}}kp1.IdleHeartbeatMonitor=Mp1});var xp1=_((Cp1)=>{Object.defineProperty(Cp1,"__esModule",{value:!0});Cp1.version=void 0;Cp1.version="3.4.0"});var hp1=_((yp1)=>{Object.defineProperty(yp1,"__esModule",{value:!0});yp1.WsTransport=void 0;yp1.wsUrlParseFn=bp1;yp1.wsconnect=xd6;var TN=JJ(),vp1=cD(),qd6=km(),Md6=jm(),kd6=Sm(),Sd6=Ed0(),Vd6=xp1(),fp1=bY(),Cd6=Vd6.version,_d6="nats.ws";class Ad0{version;lang;closeError;connected;done;socket;options;socketClosed;encrypted;peeked;yields;signal;closedNotification;constructor(){this.version=Cd6,this.lang=_d6,this.connected=!1,this.done=!1,this.socketClosed=!1,this.encrypted=!1,this.peeked=!1,this.yields=[],this.signal=(0,TN.deferred)(),this.closedNotification=(0,TN.deferred)()}async connect($,Z){let Q=(0,TN.deferred)();this.options=Z;let Y=$.src;if(Z.wsFactory){let{socket:G,encrypted:J}=await Z.wsFactory($.src,Z);this.socket=G,this.encrypted=J}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=(G)=>{if(this.done)return;if(this.yields.push(new Uint8Array(G.data)),this.peeked){this.signal.resolve();return}let J=Md6.DataBuffer.concat(...this.yields),K=(0,vp1.extractProtocolMessage)(J);if(K!==""){let W=kd6.INFO.exec(K);if(!W){if(Z.debug)console.error("!!!",(0,TN.render)(J));Q.reject(Error("unexpected response from server"));return}try{let H=JSON.parse(W[1]);(0,qd6.checkOptions)(H,this.options),this.peeked=!0,this.connected=!0,this.signal.resolve(),Q.resolve()}catch(H){Q.reject(H);return}}},this.socket.onclose=(G)=>{let J;if(!G.wasClean&&G.reason!=="")J=Error(G.reason);this._closed(J),this._cleanup()},this.socket.onerror=(G)=>{if(this.done)return;let J=G,K=new fp1.errors.ConnectionError(J.message);Q.reject(K),this._cleanup()},Q}_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(X){}return}if(this.closeError=$,!$)while(!this.socketClosed&&this.socket.bufferedAmount>0)await(0,TN.delay)(100);this.done=!0;try{this.socket.close()}catch(X){}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,TN.render)($[Z])}`);yield $[Z]}if(this.done)break;else if(this.yields.length===0)$.length=0,this.yields=$,this.signal=(0,TN.deferred)()}}isEncrypted(){return this.connected&&this.encrypted}send($){if(this.done)return;try{if(this.socket.send($.buffer),this.options.debug)console.info(`< ${(0,TN.render)($)}`);return}catch(Z){if(this.options.debug)console.error(`!!! ${(0,TN.render)($)}: ${Z}`)}}close($){return this._closed($,!1)}closed(){return this.closedNotification}discard(){this.socket?.close()}}yp1.WsTransport=Ad0;function bp1($,Z){if(!/^(.*:\/\/)(.*)/.test($))if(typeof Z==="boolean")$=`${Z===!0?"https":"http"}://${$}`;else $=`https://${$}`;let Q=new URL($),Y=Q.protocol.toLowerCase();if(Y==="ws:")Z=!1;if(Y==="wss:")Z=!0;if(Y!=="https:"&&Y!=="http")$=$.replace(/^(.*:\/\/)(.*)/gm,"$2"),Q=new URL(`http://${$}`);let G,J,K=Q.hostname,W=Q.pathname,H=Q.search||"";switch(Y){case"http:":case"ws:":case"nats:":J=Q.port||"80",G="ws:";break;case"https:":case"wss:":case"tls:":J=Q.port||"443",G="wss:";break;default:J=Q.port||Z===!0?"443":"80",G=Z===!0?"wss:":"ws:";break}return`${G}//${K}:${J}${W}${H}`}function xd6($={}){return(0,vp1.setTransportFactory)({defaultPort:443,urlParseFn:bp1,factory:()=>{if($.tls)throw fp1.InvalidArgumentError.format("tls","is not configurable on w3c websocket connections");return new Ad0}}),Sd6.NatsConnectionImpl.connect($)}});var gY=_((f0)=>{var bd6=f0&&f0.__createBinding||(Object.create?function($,Z,X,Q){if(Q===void 0)Q=X;var Y=Object.getOwnPropertyDescriptor(Z,X);if(!Y||("get"in Y?!Z.__esModule:Y.writable||Y.configurable))Y={enumerable:!0,get:function(){return Z[X]}};Object.defineProperty($,Q,Y)}:function($,Z,X,Q){if(Q===void 0)Q=X;$[Q]=Z[X]}),yd6=f0&&f0.__exportStar||function($,Z){for(var X in $)if(X!=="default"&&!Object.prototype.hasOwnProperty.call(Z,X))bd6(Z,$,X)};Object.defineProperty(f0,"__esModule",{value:!0});f0.Metric=f0.Bench=f0.writeAll=f0.readAll=f0.MAX_SIZE=f0.DenoBuffer=f0.State=f0.Parser=f0.Kind=f0.describe=f0.QueuedIteratorImpl=f0.usernamePasswordAuthenticator=f0.tokenAuthenticator=f0.nkeyAuthenticator=f0.jwtAuthenticator=f0.credsAuthenticator=f0.RequestOne=f0.parseOptions=f0.hasWsProtocol=f0.defaultOptions=f0.DEFAULT_MAX_RECONNECT_ATTEMPTS=f0.checkUnsupportedOption=f0.checkOptions=f0.buildAuthenticator=f0.DataBuffer=f0.MuxSubscription=f0.Heartbeat=f0.MsgHdrsImpl=f0.headers=f0.canonicalMIMEHeaderKey=f0.timeout=f0.SimpleMutex=f0.render=f0.nanos=f0.millis=f0.extend=f0.delay=f0.deferred=f0.deadline=f0.collect=f0.backoff=f0.ProtocolHandler=f0.INFO=f0.Connect=f0.setTransportFactory=f0.getResolveFn=f0.MsgImpl=f0.nuid=f0.Nuid=f0.NatsConnectionImpl=void 0;f0.UserAuthenticationExpiredError=f0.TimeoutError=f0.RequestError=f0.ProtocolError=f0.PermissionViolationError=f0.NoRespondersError=f0.InvalidSubjectError=f0.InvalidOperationError=f0.InvalidArgumentError=f0.errors=f0.DrainingConnectionError=f0.ConnectionError=f0.ClosedConnectionError=f0.AuthorizationError=f0.wsUrlParseFn=f0.wsconnect=f0.Servers=f0.isIPV4OrHostname=f0.IdleHeartbeatMonitor=f0.Subscriptions=f0.SubscriptionImpl=f0.syncIterator=f0.Match=f0.createInbox=f0.protoLen=f0.extractProtocolMessage=f0.Empty=f0.parseSemVer=f0.Features=f0.Feature=f0.compare=f0.parseIP=f0.isIP=f0.ipV4=f0.TE=f0.TD=void 0;var gd6=Ed0();Object.defineProperty(f0,"NatsConnectionImpl",{enumerable:!0,get:function(){return gd6.NatsConnectionImpl}});var up1=c50();Object.defineProperty(f0,"Nuid",{enumerable:!0,get:function(){return up1.Nuid}});Object.defineProperty(f0,"nuid",{enumerable:!0,get:function(){return up1.nuid}});var hd6=el0();Object.defineProperty(f0,"MsgImpl",{enumerable:!0,get:function(){return hd6.MsgImpl}});var cp1=cD();Object.defineProperty(f0,"getResolveFn",{enumerable:!0,get:function(){return cp1.getResolveFn}});Object.defineProperty(f0,"setTransportFactory",{enumerable:!0,get:function(){return cp1.setTransportFactory}});var Td0=Sm();Object.defineProperty(f0,"Connect",{enumerable:!0,get:function(){return Td0.Connect}});Object.defineProperty(f0,"INFO",{enumerable:!0,get:function(){return Td0.INFO}});Object.defineProperty(f0,"ProtocolHandler",{enumerable:!0,get:function(){return Td0.ProtocolHandler}});var HJ=JJ();Object.defineProperty(f0,"backoff",{enumerable:!0,get:function(){return HJ.backoff}});Object.defineProperty(f0,"collect",{enumerable:!0,get:function(){return HJ.collect}});Object.defineProperty(f0,"deadline",{enumerable:!0,get:function(){return HJ.deadline}});Object.defineProperty(f0,"deferred",{enumerable:!0,get:function(){return HJ.deferred}});Object.defineProperty(f0,"delay",{enumerable:!0,get:function(){return HJ.delay}});Object.defineProperty(f0,"extend",{enumerable:!0,get:function(){return HJ.extend}});Object.defineProperty(f0,"millis",{enumerable:!0,get:function(){return HJ.millis}});Object.defineProperty(f0,"nanos",{enumerable:!0,get:function(){return HJ.nanos}});Object.defineProperty(f0,"render",{enumerable:!0,get:function(){return HJ.render}});Object.defineProperty(f0,"SimpleMutex",{enumerable:!0,get:function(){return HJ.SimpleMutex}});Object.defineProperty(f0,"timeout",{enumerable:!0,get:function(){return HJ.timeout}});var Rd0=t50();Object.defineProperty(f0,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return Rd0.canonicalMIMEHeaderKey}});Object.defineProperty(f0,"headers",{enumerable:!0,get:function(){return Rd0.headers}});Object.defineProperty(f0,"MsgHdrsImpl",{enumerable:!0,get:function(){return Rd0.MsgHdrsImpl}});var ud6=ml0();Object.defineProperty(f0,"Heartbeat",{enumerable:!0,get:function(){return ud6.Heartbeat}});var cd6=dl0();Object.defineProperty(f0,"MuxSubscription",{enumerable:!0,get:function(){return cd6.MuxSubscription}});var ld6=jm();Object.defineProperty(f0,"DataBuffer",{enumerable:!0,get:function(){return ld6.DataBuffer}});var pD=km();Object.defineProperty(f0,"buildAuthenticator",{enumerable:!0,get:function(){return pD.buildAuthenticator}});Object.defineProperty(f0,"checkOptions",{enumerable:!0,get:function(){return pD.checkOptions}});Object.defineProperty(f0,"checkUnsupportedOption",{enumerable:!0,get:function(){return pD.checkUnsupportedOption}});Object.defineProperty(f0,"DEFAULT_MAX_RECONNECT_ATTEMPTS",{enumerable:!0,get:function(){return pD.DEFAULT_MAX_RECONNECT_ATTEMPTS}});Object.defineProperty(f0,"defaultOptions",{enumerable:!0,get:function(){return pD.defaultOptions}});Object.defineProperty(f0,"hasWsProtocol",{enumerable:!0,get:function(){return pD.hasWsProtocol}});Object.defineProperty(f0,"parseOptions",{enumerable:!0,get:function(){return pD.parseOptions}});var dd6=Ld0();Object.defineProperty(f0,"RequestOne",{enumerable:!0,get:function(){return dd6.RequestOne}});var Vm=Wd0();Object.defineProperty(f0,"credsAuthenticator",{enumerable:!0,get:function(){return Vm.credsAuthenticator}});Object.defineProperty(f0,"jwtAuthenticator",{enumerable:!0,get:function(){return Vm.jwtAuthenticator}});Object.defineProperty(f0,"nkeyAuthenticator",{enumerable:!0,get:function(){return Vm.nkeyAuthenticator}});Object.defineProperty(f0,"tokenAuthenticator",{enumerable:!0,get:function(){return Vm.tokenAuthenticator}});Object.defineProperty(f0,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return Vm.usernamePasswordAuthenticator}});yd6(Jd0(),f0);var md6=m50();Object.defineProperty(f0,"QueuedIteratorImpl",{enumerable:!0,get:function(){return md6.QueuedIteratorImpl}});var N90=rl0();Object.defineProperty(f0,"describe",{enumerable:!0,get:function(){return N90.describe}});Object.defineProperty(f0,"Kind",{enumerable:!0,get:function(){return N90.Kind}});Object.defineProperty(f0,"Parser",{enumerable:!0,get:function(){return N90.Parser}});Object.defineProperty(f0,"State",{enumerable:!0,get:function(){return N90.State}});var U90=pl0();Object.defineProperty(f0,"DenoBuffer",{enumerable:!0,get:function(){return U90.DenoBuffer}});Object.defineProperty(f0,"MAX_SIZE",{enumerable:!0,get:function(){return U90.MAX_SIZE}});Object.defineProperty(f0,"readAll",{enumerable:!0,get:function(){return U90.readAll}});Object.defineProperty(f0,"writeAll",{enumerable:!0,get:function(){return U90.writeAll}});var lp1=qp1();Object.defineProperty(f0,"Bench",{enumerable:!0,get:function(){return lp1.Bench}});Object.defineProperty(f0,"Metric",{enumerable:!0,get:function(){return lp1.Metric}});var dp1=fY();Object.defineProperty(f0,"TD",{enumerable:!0,get:function(){return dp1.TD}});Object.defineProperty(f0,"TE",{enumerable:!0,get:function(){return dp1.TE}});var Id0=fl0();Object.defineProperty(f0,"ipV4",{enumerable:!0,get:function(){return Id0.ipV4}});Object.defineProperty(f0,"isIP",{enumerable:!0,get:function(){return Id0.isIP}});Object.defineProperty(f0,"parseIP",{enumerable:!0,get:function(){return Id0.parseIP}});var F90=a50();Object.defineProperty(f0,"compare",{enumerable:!0,get:function(){return F90.compare}});Object.defineProperty(f0,"Feature",{enumerable:!0,get:function(){return F90.Feature}});Object.defineProperty(f0,"Features",{enumerable:!0,get:function(){return F90.Features}});Object.defineProperty(f0,"parseSemVer",{enumerable:!0,get:function(){return F90.parseSemVer}});var id6=jd0();Object.defineProperty(f0,"Empty",{enumerable:!0,get:function(){return id6.Empty}});var mp1=cD();Object.defineProperty(f0,"extractProtocolMessage",{enumerable:!0,get:function(){return mp1.extractProtocolMessage}});Object.defineProperty(f0,"protoLen",{enumerable:!0,get:function(){return mp1.protoLen}});var qd0=Fw();Object.defineProperty(f0,"createInbox",{enumerable:!0,get:function(){return qd0.createInbox}});Object.defineProperty(f0,"Match",{enumerable:!0,get:function(){return qd0.Match}});Object.defineProperty(f0,"syncIterator",{enumerable:!0,get:function(){return qd0.syncIterator}});var ip1=Sm();Object.defineProperty(f0,"SubscriptionImpl",{enumerable:!0,get:function(){return ip1.SubscriptionImpl}});Object.defineProperty(f0,"Subscriptions",{enumerable:!0,get:function(){return ip1.Subscriptions}});var nd6=Vp1();Object.defineProperty(f0,"IdleHeartbeatMonitor",{enumerable:!0,get:function(){return nd6.IdleHeartbeatMonitor}});var np1=cl0();Object.defineProperty(f0,"isIPV4OrHostname",{enumerable:!0,get:function(){return np1.isIPV4OrHostname}});Object.defineProperty(f0,"Servers",{enumerable:!0,get:function(){return np1.Servers}});var pp1=hp1();Object.defineProperty(f0,"wsconnect",{enumerable:!0,get:function(){return pp1.wsconnect}});Object.defineProperty(f0,"wsUrlParseFn",{enumerable:!0,get:function(){return pp1.wsUrlParseFn}});var SQ=bY();Object.defineProperty(f0,"AuthorizationError",{enumerable:!0,get:function(){return SQ.AuthorizationError}});Object.defineProperty(f0,"ClosedConnectionError",{enumerable:!0,get:function(){return SQ.ClosedConnectionError}});Object.defineProperty(f0,"ConnectionError",{enumerable:!0,get:function(){return SQ.ConnectionError}});Object.defineProperty(f0,"DrainingConnectionError",{enumerable:!0,get:function(){return SQ.DrainingConnectionError}});Object.defineProperty(f0,"errors",{enumerable:!0,get:function(){return SQ.errors}});Object.defineProperty(f0,"InvalidArgumentError",{enumerable:!0,get:function(){return SQ.InvalidArgumentError}});Object.defineProperty(f0,"InvalidOperationError",{enumerable:!0,get:function(){return SQ.InvalidOperationError}});Object.defineProperty(f0,"InvalidSubjectError",{enumerable:!0,get:function(){return SQ.InvalidSubjectError}});Object.defineProperty(f0,"NoRespondersError",{enumerable:!0,get:function(){return SQ.NoRespondersError}});Object.defineProperty(f0,"PermissionViolationError",{enumerable:!0,get:function(){return SQ.PermissionViolationError}});Object.defineProperty(f0,"ProtocolError",{enumerable:!0,get:function(){return SQ.ProtocolError}});Object.defineProperty(f0,"RequestError",{enumerable:!0,get:function(){return SQ.RequestError}});Object.defineProperty(f0,"TimeoutError",{enumerable:!0,get:function(){return SQ.TimeoutError}});Object.defineProperty(f0,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return SQ.UserAuthenticationExpiredError}})});var RN=_((op1)=>{Object.defineProperty(op1,"__esModule",{value:!0});op1.jserrors=op1.StreamNotFoundError=op1.ConsumerNotFoundError=op1.JetStreamApiError=op1.InvalidNameError=op1.JetStreamApiCodes=op1.JetStreamStatus=op1.JetStreamStatusError=op1.JetStreamError=op1.JetStreamNotEnabled=void 0;op1.isMessageNotFound=pd6;var tp1=uD();class Md0 extends Error{constructor($,Z){super($,Z);this.name="JetStreamNotEnabled"}}op1.JetStreamNotEnabled=Md0;class w90 extends Error{constructor($,Z){super($,Z);this.name="JetStreamError"}}op1.JetStreamError=w90;class kd0 extends w90{code;constructor($,Z,X){super($,X);this.code=Z,this.name="JetStreamStatusError"}}op1.JetStreamStatusError=kd0;class Sd0{msg;_description;constructor($){this.msg=$,this._description=""}static maybeParseStatus($){let Z=new Sd0($);return Z.code===0?null:Z}toError(){return new kd0(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(tp1.JsHeaders.PendingMessagesHdr);if(Z)$.msgsLeft=parseInt(Z);let X=this.msg.headers?.get(tp1.JsHeaders.PendingBytesHdr);if(X)$.bytesLeft=parseInt(X);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"}}op1.JetStreamStatus=Sd0;op1.JetStreamApiCodes={ConsumerNotFound:10014,StreamNotFound:10059,JetStreamNotEnabledForAccount:10039,StreamWrongLastSequence:10071,StreamWrongLastSequenceUnknown:10164,NoMessageFound:10037};function pd6($){return $ instanceof sf&&$.code===op1.JetStreamApiCodes.NoMessageFound}class Vd0 extends Error{constructor($="",Z){super($,Z);this.name="InvalidNameError"}}op1.InvalidNameError=Vd0;class sf 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.#$)}}op1.JetStreamApiError=sf;class Cd0 extends sf{constructor($,Z){super($,Z);this.name="ConsumerNotFoundError"}}op1.ConsumerNotFoundError=Cd0;class B90 extends sf{constructor($,Z){super($,Z);this.name="StreamNotFoundError"}static fromMessage($){return new B90({err_code:op1.JetStreamApiCodes.StreamNotFound,description:$,code:404})}}op1.StreamNotFoundError=B90;op1.jserrors={InvalidNameError:Vd0,ConsumerNotFoundError:Cd0,StreamNotFoundError:B90,JetStreamError:w90,JetStreamApiError:sf,JetStreamNotEnabled:Md0}});var ef=_(($t1)=>{Object.defineProperty($t1,"__esModule",{value:!0});$t1.BaseApiClientImpl=void 0;$t1.parseJsResponse=ap1;$t1.defaultJsOptions=sp1;var IN=gY(),Qm6=uD(),$W=RN(),Ym6="$JS.API",Gm6=5000;function ap1($){let Z=JSON.parse(new TextDecoder().decode($.data)),X=Z;if(X.error)switch(X.error.err_code){case $W.JetStreamApiCodes.ConsumerNotFound:throw new $W.ConsumerNotFoundError(X.error);case $W.JetStreamApiCodes.StreamNotFound:throw new $W.StreamNotFoundError(X.error);case $W.JetStreamApiCodes.JetStreamNotEnabledForAccount:{let Q=new $W.JetStreamApiError(X.error);throw new $W.JetStreamNotEnabled(Q.message,{cause:Q})}default:throw new $W.JetStreamApiError(X.error)}return Z}function sp1($){if($=$||{},$.domain)$.apiPrefix=`$JS.${$.domain}.API`,delete $.domain;return(0,IN.extend)({apiPrefix:Ym6,timeout:Gm6},$)}class ep1{nc;opts;prefix;timeout;constructor($,Z){this.nc=$,Z=Z||{},Z.watcherPrefix=Z.watcherPrefix||this.nc.options.inboxPrefix,this.opts=sp1(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 IN.errors.InvalidArgumentError.format("prefix","cannot be empty");if($[$.length-1]===".")$=$.substr(0,$.length-1);this.opts.apiPrefix=$,(0,IN.createInbox)(this.opts.watcherPrefix)}async _request($,Z=null,X){let{retries:Q,minApiVersion:Y,...G}=X??{},J={...G,timeout:this.timeout},K=IN.Empty;if(Z)K=new TextEncoder().encode(JSON.stringify(Z));if(typeof Y==="number"){let N=J.headers??(0,IN.headers)();N.set(Qm6.JsHeaders.RequiredApiLevel,Y.toString()),J.headers=N}let W=Q||1;W=W===-1?Number.MAX_SAFE_INTEGER:W;let H=(0,IN.backoff)();for(let N=0;N<W;N++)try{let U=await this.nc.request($,K,J);return this.parseJsResponse(U)}catch(U){let F=U instanceof IN.RequestError?U:null;if((U instanceof IN.errors.TimeoutError||F?.isNoResponders())&&N+1<W)await(0,IN.delay)(H.backoff(N));else throw F?.isNoResponders()?new $W.JetStreamNotEnabled("jetstream is not enabled",{cause:U}):U}}async findStream($){let Z={subject:$},Q=await this._request(`${this.prefix}.STREAM.NAMES`,Z);if(!Q.streams||Q.streams.length!==1)throw $W.StreamNotFoundError.fromMessage("no stream matches subject");return Q.streams[0]}getConnection(){return this.nc}parseJsResponse($){return ap1($)}}$t1.BaseApiClientImpl=ep1});var O90=_((Qt1)=>{Object.defineProperty(Qt1,"__esModule",{value:!0});Qt1.ListerImpl=void 0;var Wm6=gY();class Xt1{err;offset;pageInfo;subject;jsm;filter;payload;constructor($,Z,X,Q){if(!$)throw Wm6.errors.InvalidArgumentError.format("subject","is required");this.subject=$,this.jsm=X,this.offset=0,this.pageInfo={},this.filter=Z,this.payload=Q||{}}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 X=this.countResponse(Z);if(X===0)return[];return this.offset+=X,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()}}}Qt1.ListerImpl=Xt1});var $b=_((Jt1)=>{Object.defineProperty(Jt1,"__esModule",{value:!0});Jt1.validateDurableName=Nm6;Jt1.validateStreamName=Um6;Jt1.minValidation=xd0;Jt1.validateName=Fm6;Jt1.validName=Gt1;var Hm6=RN();function Nm6($){return xd0("durable",$)}function Um6($){return xd0("stream",$)}function xd0($,Z=""){if(Z==="")throw Error(`${$} name required`);return[".","*",">","/","\\"," ","\t",`
|
|
1312
1312
|
`,"\r"].forEach((Q)=>{if(Z.indexOf(Q)!==-1){switch(Q){case`
|
|
1313
|
-
`:Q="\\n";break;case"\r":Q="\\r";break;case"\t":Q="\\t";break;default:}throw new Hm6.InvalidNameError(`${$} name ('${Z}') cannot contain '${Q}'`)}}),""}function Fm6($,Z=""){if(Z==="")throw Error(`${$} name required`);let X=Gt1(Z);if(X.length)throw Error(`invalid ${$} name - ${$} name ${X}`)}function Gt1($=""){if($==="")throw Error("name required");let Z=/^[-\w]+$/g;if($.match(Z)===null){for(let Q of $.split(""))if(Q.match(Z)===null)return`cannot contain '${Q}'`}return""}});var Cm=_((E6)=>{Object.defineProperty(E6,"__esModule",{value:!0});E6.wsconnect=E6.usernamePasswordAuthenticator=E6.UserAuthenticationExpiredError=E6.tokenAuthenticator=E6.TimeoutError=E6.syncIterator=E6.RequestError=E6.ProtocolError=E6.PermissionViolationError=E6.nuid=E6.Nuid=E6.NoRespondersError=E6.nkeys=E6.nkeyAuthenticator=E6.nanos=E6.MsgHdrsImpl=E6.millis=E6.Metric=E6.Match=E6.jwtAuthenticator=E6.InvalidSubjectError=E6.InvalidOperationError=E6.InvalidArgumentError=E6.headers=E6.hasWsProtocol=E6.errors=E6.Empty=E6.DrainingConnectionError=E6.delay=E6.deferred=E6.deadline=E6.credsAuthenticator=E6.createInbox=E6.ConnectionError=E6.ClosedConnectionError=E6.canonicalMIMEHeaderKey=E6.buildAuthenticator=E6.Bench=E6.backoff=E6.AuthorizationError=void 0;var f6=gY();Object.defineProperty(E6,"AuthorizationError",{enumerable:!0,get:function(){return f6.AuthorizationError}});Object.defineProperty(E6,"backoff",{enumerable:!0,get:function(){return f6.backoff}});Object.defineProperty(E6,"Bench",{enumerable:!0,get:function(){return f6.Bench}});Object.defineProperty(E6,"buildAuthenticator",{enumerable:!0,get:function(){return f6.buildAuthenticator}});Object.defineProperty(E6,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return f6.canonicalMIMEHeaderKey}});Object.defineProperty(E6,"ClosedConnectionError",{enumerable:!0,get:function(){return f6.ClosedConnectionError}});Object.defineProperty(E6,"ConnectionError",{enumerable:!0,get:function(){return f6.ConnectionError}});Object.defineProperty(E6,"createInbox",{enumerable:!0,get:function(){return f6.createInbox}});Object.defineProperty(E6,"credsAuthenticator",{enumerable:!0,get:function(){return f6.credsAuthenticator}});Object.defineProperty(E6,"deadline",{enumerable:!0,get:function(){return f6.deadline}});Object.defineProperty(E6,"deferred",{enumerable:!0,get:function(){return f6.deferred}});Object.defineProperty(E6,"delay",{enumerable:!0,get:function(){return f6.delay}});Object.defineProperty(E6,"DrainingConnectionError",{enumerable:!0,get:function(){return f6.DrainingConnectionError}});Object.defineProperty(E6,"Empty",{enumerable:!0,get:function(){return f6.Empty}});Object.defineProperty(E6,"errors",{enumerable:!0,get:function(){return f6.errors}});Object.defineProperty(E6,"hasWsProtocol",{enumerable:!0,get:function(){return f6.hasWsProtocol}});Object.defineProperty(E6,"headers",{enumerable:!0,get:function(){return f6.headers}});Object.defineProperty(E6,"InvalidArgumentError",{enumerable:!0,get:function(){return f6.InvalidArgumentError}});Object.defineProperty(E6,"InvalidOperationError",{enumerable:!0,get:function(){return f6.InvalidOperationError}});Object.defineProperty(E6,"InvalidSubjectError",{enumerable:!0,get:function(){return f6.InvalidSubjectError}});Object.defineProperty(E6,"jwtAuthenticator",{enumerable:!0,get:function(){return f6.jwtAuthenticator}});Object.defineProperty(E6,"Match",{enumerable:!0,get:function(){return f6.Match}});Object.defineProperty(E6,"Metric",{enumerable:!0,get:function(){return f6.Metric}});Object.defineProperty(E6,"millis",{enumerable:!0,get:function(){return f6.millis}});Object.defineProperty(E6,"MsgHdrsImpl",{enumerable:!0,get:function(){return f6.MsgHdrsImpl}});Object.defineProperty(E6,"nanos",{enumerable:!0,get:function(){return f6.nanos}});Object.defineProperty(E6,"nkeyAuthenticator",{enumerable:!0,get:function(){return f6.nkeyAuthenticator}});Object.defineProperty(E6,"nkeys",{enumerable:!0,get:function(){return f6.nkeys}});Object.defineProperty(E6,"NoRespondersError",{enumerable:!0,get:function(){return f6.NoRespondersError}});Object.defineProperty(E6,"Nuid",{enumerable:!0,get:function(){return f6.Nuid}});Object.defineProperty(E6,"nuid",{enumerable:!0,get:function(){return f6.nuid}});Object.defineProperty(E6,"PermissionViolationError",{enumerable:!0,get:function(){return f6.PermissionViolationError}});Object.defineProperty(E6,"ProtocolError",{enumerable:!0,get:function(){return f6.ProtocolError}});Object.defineProperty(E6,"RequestError",{enumerable:!0,get:function(){return f6.RequestError}});Object.defineProperty(E6,"syncIterator",{enumerable:!0,get:function(){return f6.syncIterator}});Object.defineProperty(E6,"TimeoutError",{enumerable:!0,get:function(){return f6.TimeoutError}});Object.defineProperty(E6,"tokenAuthenticator",{enumerable:!0,get:function(){return f6.tokenAuthenticator}});Object.defineProperty(E6,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return f6.UserAuthenticationExpiredError}});Object.defineProperty(E6,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return f6.usernamePasswordAuthenticator}});Object.defineProperty(E6,"wsconnect",{enumerable:!0,get:function(){return f6.wsconnect}})});var tD=_((Kt1)=>{Object.defineProperty(Kt1,"__esModule",{value:!0});Kt1.PubHeaders=Kt1.PriorityPolicy=Kt1.ConsumerApiAction=Kt1.PersistMode=Kt1.StoreCompression=Kt1.ReplayPolicy=Kt1.AckPolicy=Kt1.DeliverPolicy=Kt1.StorageType=Kt1.DiscardPolicy=Kt1.RetentionPolicy=void 0;Kt1.defaultConsumer=jm6;var zm6=Cm();Kt1.RetentionPolicy={Limits:"limits",Interest:"interest",Workqueue:"workqueue"};Kt1.DiscardPolicy={Old:"old",New:"new"};Kt1.StorageType={File:"file",Memory:"memory"};Kt1.DeliverPolicy={All:"all",Last:"last",New:"new",StartSequence:"by_start_sequence",StartTime:"by_start_time",LastPerSubject:"last_per_subject"};Kt1.AckPolicy={None:"none",All:"all",Explicit:"explicit",FlowControl:"flow_control",NotSet:""};Kt1.ReplayPolicy={Instant:"instant",Original:"original"};Kt1.StoreCompression={None:"none",S2:"s2"};Kt1.PersistMode={Default:"default",Async:"async"};Kt1.ConsumerApiAction={CreateOrUpdate:"",Update:"update",Create:"create"};Kt1.PriorityPolicy={None:"none",Overflow:"overflow",PinnedClient:"pinned_client",Prioritized:"prioritized"};function jm6($,Z={}){return Object.assign({name:$,deliver_policy:Kt1.DeliverPolicy.All,ack_policy:Kt1.AckPolicy.Explicit,ack_wait:(0,zm6.nanos)(30000),replay_policy:Kt1.ReplayPolicy.Instant},Z)}Kt1.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 vd0=_((Bt1)=>{Object.defineProperty(Bt1,"__esModule",{value:!0});Bt1.ConsumerAPIImpl=void 0;var Sm6=ef(),Vm6=O90(),NJ=$b(),i7=gY(),qN=tD();class Ft1 extends Sm6.BaseApiClientImpl{constructor($,Z){super($,Z)}async addUpdate($,Z,X,Q){if((0,NJ.validateStreamName)($),X=X||{},Z.deliver_group&&Z.flow_control)throw i7.InvalidArgumentError.format(["flow_control","deliver_group"],"are mutually exclusive");if(Z.deliver_group&&Z.idle_heartbeat)throw i7.InvalidArgumentError.format(["idle_heartbeat","deliver_group"],"are mutually exclusive");if(wt1(Z)){let{min:w,ok:B}=this.nc.features.get(i7.Feature.JS_PRIORITY_GROUPS);if(!B)throw Error(`priority_groups require server ${w}`);if(Z.deliver_subject)throw i7.InvalidArgumentError.format("deliver_subject","cannot be set when using priority groups");Cm6(Z)}let Y={};if(Y.config=Z,Y.stream_name=$,Y.action=X.action||qN.ConsumerApiAction.Create,Y.pedantic=X.pedantic||!1,Y.config.durable_name)(0,NJ.validateDurableName)(Y.config.durable_name);let G=this.nc,{min:J,ok:K}=G.features.get(i7.Feature.JS_NEW_CONSUMER_CREATE_API),W=Z.name===""?void 0:Z.name;if(W&&!K)throw i7.InvalidArgumentError.format("name",`requires server ${J}`);if(W)try{(0,NJ.minValidation)("name",W)}catch(w){let B=w.message,L=B.indexOf("cannot contain");if(L!==-1)throw Error(`consumer 'name' ${B.substring(L)}`);throw w}let H,N="";if(Array.isArray(Z.filter_subjects)){let{min:w,ok:B}=G.features.get(i7.Feature.JS_MULTIPLE_CONSUMER_FILTER);if(!B)throw i7.InvalidArgumentError.format("filter_subjects",`requires server ${w}`);K=!1}if(Z.metadata){let{min:w,ok:B}=G.features.get(i7.Feature.JS_STREAM_CONSUMER_METADATA);if(!B)throw i7.InvalidArgumentError.format("metadata",`requires server ${w}`)}if(K)N=Z.name??Z.durable_name??"";if(N!==""){let w=Z.filter_subject??void 0;if(w===">")w=void 0;H=w!==void 0?`${this.prefix}.CONSUMER.CREATE.${$}.${N}.${w}`:`${this.prefix}.CONSUMER.CREATE.${$}.${N}`}else H=Z.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${$}.${Z.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${$}`;let U=Q??Y.config;return await this._request(H,Y,{...X,...this.requiredApiOpts(U)})}minConsumerApi($){if($.ack_policy===qN.AckPolicy.FlowControl)return 4;if(typeof $.pause_until==="string"&&$.pause_until!=="")return 1;if($.priority_policy!==void 0&&$.priority_policy!==qN.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,X){X=X||{};let Q=qN.ConsumerApiAction.Create;if(typeof X==="string")Q=X,X={};let Y=Object.assign({},{action:Q},X);return this.addUpdate($,Z,Y)}async update($,Z,X){let Q=await this.info($,Z),Y=X;return this.addUpdate($,Object.assign(Q.config,Y),{action:qN.ConsumerApiAction.Update},Y)}async info($,Z){return(0,NJ.validateStreamName)($),(0,NJ.validateDurableName)(Z),await this._request(`${this.prefix}.CONSUMER.INFO.${$}.${Z}`)}async delete($,Z){return(0,NJ.validateStreamName)($),(0,NJ.validateDurableName)(Z),(await this._request(`${this.prefix}.CONSUMER.DELETE.${$}.${Z}`)).success}list($){(0,NJ.validateStreamName)($);let Z=(Q)=>{return Q.consumers},X=`${this.prefix}.CONSUMER.LIST.${$}`;return new Vm6.ListerImpl(X,Z,this)}pause($,Z,X){let Q=`${this.prefix}.CONSUMER.PAUSE.${$}.${Z}`,Y={pause_until:X.toISOString()};return this._request(Q,Y)}resume($,Z){return this.pause($,Z,new Date(0))}unpin($,Z,X){let Q=`${this.prefix}.CONSUMER.UNPIN.${$}.${Z}`;return this._request(Q,{group:X})}async reset($,Z,X){(0,NJ.validateStreamName)($),(0,NJ.validateDurableName)(Z);let Q=this.nc,{min:Y,ok:G}=Q.features.get(i7.Feature.JS_CONSUMER_RESET);if(!G)throw Error(`consumer reset requires server ${Y}`);if(typeof X==="number"&&(!Number.isInteger(X)||X<0))throw i7.InvalidArgumentError.format("seq","must be a non-negative integer");let J=`${this.prefix}.CONSUMER.RESET.${$}.${Z}`,K=typeof X==="number"?{seq:X}:void 0;return await this._request(J,K)}}Bt1.ConsumerAPIImpl=Ft1;function wt1($){let Z=$;return Z&&Z.priority_groups!==void 0||Z.priority_policy!==void 0}function Cm6($){if(wt1($)){if(!Array.isArray($.priority_groups))throw i7.InvalidArgumentError.format(["priority_groups"],"must be an array");if($.priority_groups.length===0)throw i7.InvalidArgumentError.format(["priority_groups"],"must have at least one group");if($.priority_groups.forEach((Z)=>{if((0,NJ.minValidation)("priority_group",Z),Z.length>16)throw i7.errors.InvalidArgumentError.format("group","must be 16 characters or less")}),$.priority_policy!==qN.PriorityPolicy.None&&$.priority_policy!==qN.PriorityPolicy.Overflow&&$.priority_policy!==qN.PriorityPolicy.PinnedClient&&$.priority_policy!==qN.PriorityPolicy.Prioritized)throw i7.InvalidArgumentError.format(["priority_policy"],"must be 'none', 'prioritized', 'overflow', or 'pinned_client'")}}});var yd0=_((Dt1)=>{Object.defineProperty(Dt1,"__esModule",{value:!0});Dt1.JsMsgImpl=Dt1.ACK=void 0;Dt1.toJsMsg=bm6;Dt1.parseInfo=Lt1;var Zb=gY();Dt1.ACK=Uint8Array.of(43,65,67,75);var _m6=Uint8Array.of(45,78,65,75),_m=Uint8Array.of(43,87,80,73),xm6=Uint8Array.of(43,78,88,84),vm6=Uint8Array.of(43,84,69,82,77),fm6=Uint8Array.of(32);function bm6($,Z=5000){return new bd0($,Z)}function Lt1($){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 X={};return X.domain=Z[2]==="_"?"":Z[2],X.account_hash=Z[3],X.stream=Z[4],X.consumer=Z[5],X.deliveryCount=parseInt(Z[6],10),X.redelivered=X.deliveryCount>1,X.streamSequence=parseInt(Z[7],10),X.deliverySequence=parseInt(Z[8],10),X.timestampNanos=parseInt(Z[9],10),X.pending=parseInt(Z[10],10),X}function ym6($){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 bd0{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=Lt1(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,Zb.millis)(this.info.timestampNanos);return new Date($)}get timestamp(){return this.time.toISOString()}get timestampNanos(){return ym6(this.reply)}doAck($){if(!this.didAck)this.didAck=!this.isWIP($),this.msg.respond($)}isWIP($){return $.length===4&&$[0]===_m[0]&&$[1]===_m[1]&&$[2]===_m[2]&&$[3]===_m[3]}async ackAck($){let Z=(0,Zb.deferred)();if(!this.didAck)if(this.didAck=!0,this.msg.reply){$=$||{},$.timeout=$.timeout||this.timeout;let Q=this.msg.publisher,Y=!Q.options?.noAsyncTraces,G=new Zb.RequestOne(Q.muxSubscriptions,this.msg.reply,{timeout:$.timeout},Y);Q.request(G);try{Q.publish(this.msg.reply,Dt1.ACK,{reply:`${Q.muxSubscriptions.baseInbox}${G.token}`})}catch(J){G.cancel(J)}try{await Promise.race([G.timer,G.deferred]),Z.resolve(!0)}catch(J){G.cancel(J),Z.reject(J)}}else Z.resolve(!1);else Z.resolve(!1);return Z}ack(){this.doAck(Dt1.ACK)}nak($){let Z=_m6;if($)Z=new TextEncoder().encode(`-NAK ${JSON.stringify({delay:(0,Zb.nanos)($)})}`);this.doAck(Z)}working(){this.doAck(_m)}next($,Z={batch:1}){let X={};if(X.batch=Z.batch||1,X.no_wait=Z.no_wait||!1,Z.expires&&Z.expires>0)X.expires=(0,Zb.nanos)(Z.expires);let Q=new TextEncoder().encode(JSON.stringify(X)),Y=Zb.DataBuffer.concat(xm6,fm6,Q),G=$?{reply:$}:void 0;this.msg.respond(Y,G)}term($=""){let Z=vm6;if($?.length>0)Z=new TextEncoder().encode(`+TERM ${$}`);this.doAck(Z)}json(){return this.msg.json()}string(){return this.msg.string()}}Dt1.JsMsgImpl=bd0});var Mt1=_((It1)=>{Object.defineProperty(It1,"__esModule",{value:!0});It1.PullConsumerImpl=It1.PullConsumerMessagesImpl=It1.PullConsumerType=void 0;It1.isOverflowOptions=xm;It1.isPrioritizedOptions=L90;It1.validateOverflowPullOptions=Tt1;It1.validatePrioritizedPullOptions=Rt1;var L$=gY(),um6=yd0(),zt1=tD(),jt1=RN(),Pt1=$b();It1.PullConsumerType={Unset:"",Consume:"consume",Fetch:"fetch"};function xm($){let Z=$;return Z&&typeof Z.group==="string"||typeof Z.min_pending==="number"||typeof Z.min_ack_pending==="number"}function L90($){let Z=$;return Z&&typeof Z.group==="string"&&typeof Z.priority==="number"}class D90 extends L$.QueuedIteratorImpl{consumer;opts;sub;monitor;pending;isConsume;callback;listeners;statusIterator;abortOnMissingResource;bind;inboxPrefix;inbox;cancelables;inReset;closeListener;isPinned;isPriority;natsPinId;constructor($,Z,X=!1){super();if(this.consumer=$,this.isConsume=X,this.cancelables=[],this.inboxPrefix=(0,L$.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(xm(Z))throw L$.errors.InvalidArgumentError.format(["group","min_pending","min_ack_pending"],"cannot be specified for ordered consumers");if(this.consumer.orderedConsumerState===void 0){let Y={},G=$.opts;Y.namePrefix=G.name_prefix??`oc_${L$.nuid.next()}`,Y.opts=G,Y.cursor={stream_seq:1,deliver_seq:0};let J=$._info.config.opt_start_seq||0;Y.cursor.stream_seq=J>0?J-1:0,Y.createFails=0,this.consumer.orderedConsumerState=Y}}let Q=Z;if(this.opts=this.parseOptions(Z,this.isConsume),this.callback=Q.callback||null,this.noIterator=typeof this.callback==="function",this.monitor=null,this.pending={msgs:0,bytes:0,requests:0},this.listeners=[],this.abortOnMissingResource=Q.abort_on_missing_resource===!0,this.bind=Q.bind===!0,Q.group){let{min_pending:Y,min_ack_pending:G}=Q;this.isPinned=Y===void 0&&G===void 0;let{priority:J}=Q;this.isPriority=typeof J==="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:X,threshold_bytes:Q,threshold_messages:Y}=this.opts;if(this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(G,J)=>{if(G){this.stop(G);return}if(this.monitor?.work(),this.consumer.ordered?J.subject.indexOf(this?.inboxPrefix)===0:J.subject===this.inbox){if(J.subject!==this.sub.getSubject())return;let W=new jt1.JetStreamStatus(J),H=W.parseHeartbeat();if(H){this.notify(H);return}let{code:N,description:U}=W,{msgsLeft:F,bytesLeft:w}=W.parseDiscard();if(F&&F>0||w&&w>0)this.pending.msgs-=F,this.pending.bytes-=w,this.pending.requests--,this.notify({type:"discard",messagesLeft:F,bytesLeft:w});switch(N){case 400:this.stop(W.toError());return;case 409:{let B=this.handle409(W);if(B){this.stop(B);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:N}),this.consumer.ordered){let B=this.consumer.orderedConsumerState;B.needsReset=!0}if(!this.isConsume){this.stop(W.toError());return}break;default:this.notify({type:"debug",code:N,description:U})}}else{let W=(0,um6.toJsMsg)(J,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,N=W.info.deliverySequence,U=W.info.streamSequence,F=H.deliver_seq+1;if(N!==F){this.reset();return}H.deliver_seq=N,H.stream_seq=U}if(this._push(W),this.received++,this.pending.msgs)this.pending.msgs--;if(this.pending.bytes)this.pending.bytes-=J.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<=Q){let W=this.pullOptions();this.pull(W)}}else if(this.pending.requests===0)this._push(()=>{this.stop()})}}),X)this.monitor=new L$.IdleHeartbeatMonitor(X,(G)=>{if(this.notify({type:"heartbeats_missed",count:G}),!this.isConsume&&!this.consumer.ordered)return this.stop(new jt1.JetStreamError("heartbeats missed")),!0;return this.resetPending().then(()=>{}).catch(()=>{}),!1},{maxOut:2});(async()=>{let G=this.consumer.api.nc.status();this.statusIterator=G;for await(let J of G)switch(J.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:X}=$;if($.isConsumerDeleted())this.notify({type:"consumer_deleted",code:Z,description:X});else if($.isExceededLimit())this.notify({type:"exceeded_limits",code:Z,description:X});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 X=this.consumer.getConsumerOpts();this.inbox=`${this.inboxPrefix}.${this.consumer.serial}`,$.cursor.deliver_seq=0,this.consumer.name=X.name,this.consumer.api.nc._resub(this.sub,this.inbox),this.consumer.api.add(this.consumer.stream,X).then((Q)=>{$.createFails=0,this.consumer._info=Q,this.notify({type:"ordered_consumer_recreated",name:Q.name}),this.monitor?.restart(),this.pull(this.pullOptions())}).catch((Q)=>{if($.createFails++,Q.message==="stream not found"){if(this.notify({type:"stream_not_found",consumerCreateFails:$.createFails,name:this.consumer.stream}),this.abortOnMissingResource){this.stop(Q);return}}if($.createFails>=30&&this.received===0)this.stop(Q);let Y=(0,L$.backoff)(),G=(0,L$.delay)(Y.backoff($.createFails));G.then(()=>{let J=this.cancelables.indexOf(G);if(J!==-1)this.cancelables=this.cancelables.splice(J,J);if(!this.done)this.reset()}).catch((J)=>{}),this.cancelables.push(G)})}_push($){if(!this.callback)super.push($);else{let Z=typeof $==="function"?$:null;try{if(!Z){let X=$;this.callback(X)}else Z()}catch(X){this.stop(X)}}}notify($){if(this.listeners.length>0)(()=>{this.listeners.forEach((Z)=>{let X=Z;if(!X.done)X.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,X=(0,L$.backoff)([this.opts.expires||30000]),Q=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 L$.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 G=X.backoff(Q),J=(0,L$.delay)(G);await Promise.race([J,this.consumer.api.nc.closed()]),J.cancel(),Q++}}}pull($){this.pending.bytes+=$.max_bytes??0,this.pending.msgs+=$.batch??0,this.pending.requests++;let Z=this.consumer.api.nc,X=`${this.consumer.api.prefix}.CONSUMER.MSG.NEXT.${this.consumer.stream}.${this.consumer._info.name}`;this._push(()=>{Z.publish(X,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,X=(0,L$.nanos)(this.opts.idle_heartbeat),Q=(0,L$.nanos)(this.opts.expires),Y={batch:$,max_bytes:Z,idle_heartbeat:X,expires:Q};if(this.isPinned&&this.natsPinId!=="")Y.id=this.natsPinId;if(xm(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(L90(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 X=$||{};if(X.max_messages=X.max_messages||0,X.max_bytes=X.max_bytes||0,X.max_messages!==0&&X.max_bytes!==0)throw L$.errors.InvalidArgumentError.format(["max_messages","max_bytes"],"are mutually exclusive");if(X.max_messages===0)X.max_messages=100;if(X.expires=X.expires||30000,X.expires<1000)throw L$.errors.InvalidArgumentError.format("expires","must be at least 1000ms");if(X.idle_heartbeat=X.idle_heartbeat||X.expires/2,X.idle_heartbeat=X.idle_heartbeat>30000?30000:X.idle_heartbeat,X.idle_heartbeat<500)X.idle_heartbeat=500;if(Z){let Q=Math.round(X.max_messages*0.75)||1;X.threshold_messages=X.threshold_messages||Q;let Y=Math.round(X.max_bytes*0.75)||1;X.threshold_bytes=X.threshold_bytes||Y}if(xm($)){let{min:Q,ok:Y}=this.consumer.api.nc.features.get(L$.Feature.JS_PRIORITY_GROUPS);if(!Y)throw Error(`priority_groups require server ${Q}`);if(Tt1($),$.group)X.group=$.group;if($.min_ack_pending)X.min_ack_pending=$.min_ack_pending;if($.min_pending)X.min_pending=$.min_pending}else if(L90($)){if(Rt1($),$.group)X.group=$.group;if(typeof $.priority==="number")X.priority=$.priority}return X}status(){let $=new L$.QueuedIteratorImpl;return this.listeners.push($),$}}It1.PullConsumerMessagesImpl=D90;class At1{api;_info;stream;name;opts;type;messages;ordered;serial;orderedConsumerState;constructor($,Z,X=null){this.api=$,this._info=Z,this.name=Z.name,this.stream=Z.stream_name,this.ordered=X!==null,this.opts=X||{},this.serial=1,this.type=It1.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(L$.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===It1.PullConsumerType.Fetch)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer initialized as fetch"));if(this.type===It1.PullConsumerType.Consume)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer doesn't support concurrent consume"));this.type=It1.PullConsumerType.Consume}return Promise.resolve(new D90(this,$,!0))}async fetch($={max_messages:100,expires:30000}){if($={...$},this.ordered){if($.group)return Promise.reject(L$.errors.InvalidArgumentError.format("group","ordered consumers don't support priority groups"));if($.bind)return Promise.reject(L$.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===It1.PullConsumerType.Consume)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer already initialized as consume"));if(this.messages?.done===!1)return Promise.reject(new L$.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=It1.PullConsumerType.Fetch}let Z=new D90(this,$);if(this.ordered)this.messages=Z;return Promise.resolve(Z)}async next($={expires:30000}){$={...$};let Z=$;Z.max_messages=1;let X=await this.fetch(Z);try{for await(let Q of X)return Q}catch(Q){return Promise.reject(Q)}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:zt1.DeliverPolicy.StartSequence,opt_start_seq:$.cursor.stream_seq+1,ack_policy:zt1.AckPolicy.None,inactive_threshold:(0,L$.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:X}=this._info;return this._info=await this.api.info(Z,X),this._info}}It1.PullConsumerImpl=At1;function Tt1($){if(xm($)){if((0,Pt1.minValidation)("group",$.group),$.group.length>16)throw L$.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{min_pending:Z,min_ack_pending:X}=$;if(Z&&typeof Z!=="number")throw L$.errors.InvalidArgumentError.format(["min_pending"],"must be a number");if(X&&typeof X!=="number")throw L$.errors.InvalidArgumentError.format(["min_ack_pending"],"must be a number")}}function Rt1($){if(L90($)){if((0,Pt1.minValidation)("group",$.group),$.group.length>16)throw L$.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{priority:Z}=$;if(Z&&typeof Z!=="number")throw L$.errors.InvalidArgumentError.format(["priority"],"must be a number")}}});var _t1=_((Vt1)=>{Object.defineProperty(Vt1,"__esModule",{value:!0});Vt1.PushConsumerImpl=Vt1.PushConsumerMessagesImpl=void 0;var nm6=yd0(),kt1=tD(),gd0=uD(),yX=gY(),pm6=RN();class hd0 extends yX.QueuedIteratorImpl{consumer;sub;monitor;listeners;abortOnMissingResource;callback;ordered;cursor;namePrefix;deliverPrefix;serial;createFails;statusIterator;cancelables;constructor($,Z={},X={}){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=X.ordered===!0,this.serial=1,this.ordered){this.namePrefix=X.name_prefix??`oc_${yX.nuid.next()}`,this.deliverPrefix=X.deliver_prefix??(0,yX.createInbox)(this.consumer.api.nc.options.inboxPrefix),this.cursor={stream_seq:1,deliver_seq:0};let Q=$._info.config.opt_start_seq||0;this.cursor.stream_seq=Q>0?Q-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((X)=>{this.createFails=0,this.consumer._info=X,this.notify({type:"ordered_consumer_recreated",name:X.name})}).catch((X)=>{if(this.createFails++,X.message==="stream not found"){if(this.notify({type:"stream_not_found",name:this.consumer.stream,consumerCreateFails:this.createFails}),this.abortOnMissingResource){this.stop(X);return}}if(this.createFails>=30&&this.received===0)this.stop(X);let Q=(0,yX.backoff)(),Y=(0,yX.delay)(Q.backoff(this.createFails));Y.then(()=>{if(!this.done)this.reset()}).catch(()=>{}).finally(()=>{let G=this.cancelables.indexOf(Y);if(G!==-1)this.cancelables=this.cancelables.splice(G,G)}),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:kt1.DeliverPolicy.StartSequence,opt_start_seq:this.cursor.stream_seq+1,ack_policy:kt1.AckPolicy.None,inactive_threshold:(0,yX.nanos)(300000),num_replicas:1,flow_control:!0,idle_heartbeat:(0,yX.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 X=$;this.received++,this.callback(X),this.processed++}else Z()}catch(X){this.stop(X)}}}status(){let $=new yX.QueuedIteratorImpl;return this.listeners.push($),$}start(){let{deliver_subject:$,deliver_group:Z,idle_heartbeat:X}=this.consumer._info.config;if(!$)throw Error("bad consumer info");if(X){let Q=(0,yX.millis)(X);this.monitor=new yX.IdleHeartbeatMonitor(Q,(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:(Q,Y)=>{if(Q){this.stop(Q);return}if(this.monitor?.work(),this.ordered?Y.subject.indexOf(this?.deliverPrefix)===0:Y.subject===$){if(Y.subject!==this.sub.getSubject())return;let J=new pm6.JetStreamStatus(Y);if(J.isFlowControlRequest()){this._push(()=>{Y.respond(),this.notify({type:"flow_control"})});return}if(J.isIdleHeartbeat()){let H=parseInt(Y.headers?.get(gd0.JsHeaders.LastConsumerSeqHdr)||"0"),N=parseInt(Y.headers?.get(gd0.JsHeaders.LastStreamSeqHdr)??"0");this.notify({type:"heartbeat",lastStreamSequence:N,lastConsumerSequence:H});let U=Y.headers?.get(gd0.JsHeaders.ConsumerStalledHdr);if(typeof U==="string"&&U!=="")Y.publisher.publish(U,yX.Empty);return}let{code:K,description:W}=J;if(J.isConsumerDeleted())this.notify({type:"consumer_deleted",code:K,description:W});if(this.abortOnMissingResource){this._push(()=>{this.stop(J.toError())});return}}else{let J=(0,nm6.toJsMsg)(Y);if(this.ordered){let K=J.info.deliverySequence;if(K!==this.cursor.deliver_seq+1){this.reset();return}this.cursor.deliver_seq=K,this.cursor.stream_seq=J.info.streamSequence}this._push(J)}}}),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 X=Z;if(!X.done)X.push($)})})()}}Vt1.PushConsumerMessagesImpl=hd0;class St1{api;_info;stream;name;bound;ordered;started;serial;opts;constructor($,Z,X={}){if(this.api=$,this._info=Z,this.stream=Z.stream_name,this.name=Z.name,this.bound=X.bound===!0,this.started=!1,this.opts=X,this.serial=0,this.ordered=X.ordered||!1,this.ordered)this.serial=1}consume($={}){if($={...$},this.started)return Promise.reject(new yX.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 yX.errors.InvalidOperationError("consumer is already bound"));let Z=new hd0(this,$,this.opts);return this.started=!0,Z.closed().then(()=>{this.started=!1}),Promise.resolve(Z)}delete(){if(this.bound)return Promise.reject(new yX.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 yX.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}}Vt1.PushConsumerImpl=St1});var ht1=_((yt1)=>{Object.defineProperty(yt1,"__esModule",{value:!0});yt1.StreamsImpl=yt1.StoredMsgImpl=yt1.StreamAPIImpl=yt1.StreamImpl=yt1.ConsumersImpl=void 0;yt1.convertStreamSourceDomain=vm;var z9=gY(),om6=ef(),xt1=O90(),UJ=$b(),vt1=uD(),hY=tD(),ud0=Mt1(),cd0=vd0(),ld0=_t1(),ft1=RN();function vm($){if($===void 0)return;let{domain:Z}=$;if(Z===void 0)return $;let X=Object.assign({},$);if(delete X.domain,Z==="")return X;if(X.external)throw z9.InvalidArgumentError.format(["domain","external"],"are mutually exclusive");return X.external={api:`$JS.${Z}.API`},X}class E90{api;notified;constructor($){this.api=$,this.notified=!1}checkVersion(){let $=this.api.nc.features.get(z9.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,UJ.minValidation)("stream",$),typeof Z==="string"){(0,UJ.minValidation)("name",Z);let X=await this.api.info($,Z);if(typeof X.config.deliver_subject!=="string")return Promise.reject(Error("not a push consumer"));return new ld0.PushConsumerImpl(this.api,X)}else if(Z===void 0)return this.getOrderedPushConsumer($);else if((0,vt1.isOrderedPushConsumerOptions)(Z)){let X=Z;return this.getOrderedPushConsumer($,X)}return Promise.reject(Error("unsupported push consumer type"))}async getOrderedPushConsumer($,Z={}){Z=Object.assign({},Z);let{name_prefix:X,deliver_prefix:Q,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=hY.DeliverPolicy.StartSequence;if(typeof Z.opt_start_time==="string")Z.deliver_policy=hY.DeliverPolicy.StartTime;X=X||`oc_${z9.nuid.next()}`,(0,UJ.minValidation)("name_prefix",X),Q=Q||(0,z9.createInbox)(this.api.getOptions().watcherPrefix);let G=Object.assign({},Z);if(G.ack_policy=hY.AckPolicy.None,G.inactive_threshold=(0,z9.nanos)(300000),G.num_replicas=1,G.max_deliver=1,G.flow_control=!0,G.idle_heartbeat=(0,z9.nanos)(30000),Array.isArray(Y))G.filter_subjects=Y;if(typeof Y==="string")G.filter_subject=Y;if(typeof G.filter_subjects>"u"&&typeof G.filter_subject>"u")G.filter_subject=">";G.name=`${X}_1`,G.deliver_subject=`${Q}.1`;let J=await this.api.add($,G),K={name_prefix:X,deliver_prefix:Q,ordered:!0};return new ld0.PushConsumerImpl(this.api,J,K)}getBoundPushConsumer($){if((0,vt1.isBoundPushConsumerOptions)($)){let Z={config:$};return Promise.resolve(new ld0.PushConsumerImpl(this.api,Z,{bound:!0}))}else return Promise.reject(z9.errors.InvalidArgumentError.format("deliver_subject","is required"))}async get($,Z){if(await this.checkVersion(),typeof Z==="string"){let X=await this.api.info($,Z);if(typeof X.config.deliver_subject==="string")return Promise.reject(Error("not a pull consumer"));else return new ud0.PullConsumerImpl(this.api,X)}else return this.ordered($,Z)}getConsumerFromInfo($){if(typeof $.config.deliver_subject==="string")throw Error("not a pull consumer");return new ud0.PullConsumerImpl(this.api,$)}async ordered($,Z={}){await this.checkVersion();let X=this.api;if(await new dd0(X.nc,X.opts).info($),typeof Z.name_prefix==="string")(0,UJ.minValidation)("name_prefix",Z.name_prefix);Z.name_prefix=Z.name_prefix||z9.nuid.next();let G={name:`${Z.name_prefix}_1`,deliver_policy:hY.DeliverPolicy.StartSequence,opt_start_seq:Z.opt_start_seq||1,ack_policy:hY.AckPolicy.None,inactive_threshold:(0,z9.nanos)(300000),num_replicas:1,max_deliver:1,mem_storage:!0};if(Z.headers_only===!0)G.headers_only=!0;if(Array.isArray(Z.filter_subjects))G.filter_subjects=Z.filter_subjects;if(typeof Z.filter_subjects==="string")G.filter_subject=Z.filter_subjects;if(Z.replay_policy)G.replay_policy=Z.replay_policy;if(G.deliver_policy=Z.deliver_policy||hY.DeliverPolicy.StartSequence,Z.deliver_policy===hY.DeliverPolicy.All||Z.deliver_policy===hY.DeliverPolicy.LastPerSubject||Z.deliver_policy===hY.DeliverPolicy.New||Z.deliver_policy===hY.DeliverPolicy.Last)delete G.opt_start_seq,G.deliver_policy=Z.deliver_policy;if(G.deliver_policy===hY.DeliverPolicy.LastPerSubject){if(typeof G.filter_subjects>"u"&&typeof G.filter_subject>"u")G.filter_subject=">"}if(Z.opt_start_time)delete G.opt_start_seq,G.deliver_policy=hY.DeliverPolicy.StartTime,G.opt_start_time=Z.opt_start_time;if(Z.inactive_threshold)G.inactive_threshold=(0,z9.nanos)(Z.inactive_threshold);let J=await this.api.add($,G);return Promise.resolve(new ud0.PullConsumerImpl(this.api,J,Z))}}yt1.ConsumersImpl=E90;class fm{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 fm(this.api,$)}else return this}info($=!1,Z){if($)return Promise.resolve(this._info);return this.api.info(this.name,Z).then((X)=>{return this._info=X,this._info})}getConsumer($){return new E90(new cd0.ConsumerAPIImpl(this.api.nc,this.api.opts)).get(this.name,$)}getPushConsumer($){return new E90(new cd0.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 cd0.ConsumerAPIImpl(this.api.nc,this.api.opts).reset(this.name,$,Z)}}yt1.StreamImpl=fm;class dd0 extends om6.BaseApiClientImpl{constructor($,Z){super($,Z)}checkStreamConfigVersions($){let Z=this.nc;if($.metadata){let{min:Q,ok:Y}=Z.features.get(z9.Feature.JS_STREAM_CONSUMER_METADATA);if(!Y)throw Error(`stream 'metadata' requires server ${Q}`)}if($.first_seq){let{min:Q,ok:Y}=Z.features.get(z9.Feature.JS_STREAM_FIRST_SEQ);if(!Y)throw Error(`stream 'first_seq' requires server ${Q}`)}if($.subject_transform){let{min:Q,ok:Y}=Z.features.get(z9.Feature.JS_STREAM_SUBJECT_TRANSFORM);if(!Y)throw Error(`stream 'subject_transform' requires server ${Q}`)}if($.compression){let{min:Q,ok:Y}=Z.features.get(z9.Feature.JS_STREAM_COMPRESSION);if(!Y)throw Error(`stream 'compression' requires server ${Q}`)}if($.consumer_limits){let{min:Q,ok:Y}=Z.features.get(z9.Feature.JS_DEFAULT_CONSUMER_LIMITS);if(!Y)throw Error(`stream 'consumer_limits' requires server ${Q}`)}function X(Q,Y){if((Y?.subject_transforms?.length||0)>0){let{min:J,ok:K}=Z.features.get(z9.Feature.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!K)throw Error(`${Q} 'subject_transforms' requires server ${J}`)}}if($.sources)$.sources.forEach((Q)=>{X("stream sources",Q)});if($.mirror)X("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===hY.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,UJ.validateStreamName)($.name),$.mirror=vm($.mirror),$.sources=$.sources?.map(vm);let X=await this._request(`${this.prefix}.STREAM.CREATE.${$.name}`,$,this.requiredApiOpts($));return this._fixInfo(X),X}async delete($){return(0,UJ.validateStreamName)($),(await this._request(`${this.prefix}.STREAM.DELETE.${$}`)).success}async update($,Z={}){if(typeof $==="object"){let J=$;$=J.name,Z=J,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,UJ.validateStreamName)($);let X=await this.info($),Q=Object.assign(X.config,Z);Q.mirror=vm(Q.mirror),Q.sources=Q.sources?.map(vm);let G=await this._request(`${this.prefix}.STREAM.UPDATE.${$}`,Q,this.requiredApiOpts(Z));return this._fixInfo(G),G}async info($,Z){(0,UJ.validateStreamName)($);let X=`${this.prefix}.STREAM.INFO.${$}`,Y=await this._request(X,Z),{total:G,limit:J}=Y,K=Y.state.subjects?Object.getOwnPropertyNames(Y.state.subjects).length:1;if(G&&G>K){let W=[Y],H=Z||{},N=0;while(G>K){N++,H.offset=J*N;let F=await this._request(X,H);G=F.total,W.push(F);let w=Object.getOwnPropertyNames(F.state.subjects).length;if(K+=w,w<J)break}let U={};for(let F=0;F<W.length;F++)if(Y=W[F],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:$}:{},X=(Y)=>{let G=Y;return G.streams.forEach((J)=>{this._fixInfo(J)}),G.streams},Q=`${this.prefix}.STREAM.LIST`;return new xt1.ListerImpl(Q,X,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:Q,seq:Y}=Z;if(typeof Q==="number"&&typeof Y==="number")throw z9.InvalidArgumentError.format(["keep","seq"],"are mutually exclusive")}return(0,UJ.validateStreamName)($),await this._request(`${this.prefix}.STREAM.PURGE.${$}`,Z)}async deleteMessage($,Z,X=!0){(0,UJ.validateStreamName)($);let Q={seq:Z};if(!X)Q.no_erase=!0;return(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${$}`,Q)).success}async getMessage($,Z){(0,UJ.validateStreamName)($);try{let Q=await this._request(`${this.prefix}.STREAM.MSG.GET.${$}`,Z);return new md0(Q)}catch(X){if(X instanceof ft1.JetStreamApiError&&X.code===ft1.JetStreamApiCodes.NoMessageFound)return null;return Promise.reject(X)}}find($){return this.findStream($)}names($=""){let Z=$?.length?{subject:$}:{},X=(Y)=>{return Y.streams},Q=`${this.prefix}.STREAM.NAMES`;return new xt1.ListerImpl(Q,X,this,Z)}async get($){let Z=await this.info($);return Promise.resolve(new fm(this,Z))}}yt1.StreamAPIImpl=dd0;class md0{_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):z9.Empty}get header(){if(!this._header)if(this.smr.message.hdrs){let $=this._parse(this.smr.message.hdrs);this._header=z9.MsgHdrsImpl.decode($)}else this._header=(0,z9.headers)();return this._header}_parse($){let Z=atob($),X=Z.length,Q=new Uint8Array(X);for(let Y=0;Y<X;Y++)Q[Y]=Z.charCodeAt(Y);return Q}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return z9.TD.decode(this.data)}}yt1.StoredMsgImpl=md0;class bt1{api;constructor($){this.api=$}get($){return this.api.info($).then((Z)=>{return new fm(this.api,Z)})}}yt1.StreamsImpl=bt1});var nd0=_((dt1)=>{Object.defineProperty(dt1,"__esModule",{value:!0});dt1.DirectConsumer=dt1.DirectMsgImpl=dt1.DirectStreamAPIImpl=void 0;var Zi6=ef(),Xb=uD(),FJ=gY(),ut1=$b(),id0=RN();class ct1 extends Zi6.BaseApiClientImpl{constructor($,Z){super($,Z)}async getMessage($,Z){if((0,ut1.validateStreamName)($),"start_time"in Z){let{min:H,ok:N}=this.nc.features.get(FJ.Feature.JS_BATCH_DIRECT_GET);if(!N)throw Error(`start_time direct option require server ${H}`)}let X=Z,{last_by_subj:Q}=X;if(Q)X=null;let Y=X?JSON.stringify(X):FJ.Empty,G=this.opts.apiPrefix||"$JS.API",J=Q?`${G}.DIRECT.GET.${$}.${Q}`:`${G}.DIRECT.GET.${$}`,K=await this.nc.request(J,Y,{timeout:this.timeout});if(K.headers?.code!==0){let H=new id0.JetStreamStatus(K);if(H.isMessageNotFound())return Promise.resolve(null);else return Promise.reject(H.toError())}let W=new z90(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:X,ok:Q}=this.nc.features.get(FJ.Feature.JS_BATCH_DIRECT_GET);if(!Q)return Promise.reject(Error(`batch direct require server ${X}`));(0,ut1.validateStreamName)($);let Y=typeof Z.callback==="function"?Z.callback:null,G=new FJ.QueuedIteratorImpl;function J(L,D){if(L){G.push(()=>{L.err?G.stop(L.err):G.stop()});return}G.push(D)}function K(L,D){let E=Y;if(typeof D==="function"){D();return}E(L,D)}if(Y)G.iterClosed.then((L)=>{W({err:L?L:void 0},{}),U.unsubscribe()});let W=Y?K:J,H=(0,FJ.createInbox)(this.nc.options.inboxPrefix),N=!1,U=this.nc.subscribe(H,{timeout:5000,callback:(L,D)=>{if(L){G.stop(L),U.unsubscribe();return}let E=id0.JetStreamStatus.maybeParseStatus(D);if(E){if(E.isNoResults())W({},()=>{G.stop()});if(E.isEndOfBatch())W({},()=>{G.stop()});else{let z=E.toError();W({err:z},()=>{G.stop(z)})}return}if(!N)if(typeof D.headers?.get("Nats-Num-Pending")!=="string")U.unsubscribe(),W({},()=>{G.stop()});else N=!0;W(null,new z90(D))}}),w=`${this.opts.apiPrefix||"$JS.API"}.DIRECT.GET.${$}`,B=JSON.stringify(Z,(L,D)=>{if((L==="up_to_time"||L==="start_time")&&D instanceof Date)return D.toISOString();return D});return this.nc.publish(w,B,{reply:H}),Promise.resolve(G)}}dt1.DirectStreamAPIImpl=ct1;class z90{data;header;constructor($){if(!$.headers)throw Error("headers expected");this.data=$.data,this.header=$.headers}get subject(){return this.header.last(Xb.DirectMsgHeaders.Subject)}get seq(){let $=this.header.last(Xb.DirectMsgHeaders.Sequence);return typeof $==="string"?parseInt($):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(Xb.DirectMsgHeaders.TimeStamp)}get stream(){return this.header.last(Xb.DirectMsgHeaders.Stream)}get lastSequence(){let $=this.header.last(Xb.DirectMsgHeaders.LastSequence);return typeof $==="string"?parseInt($):0}get pending(){let $=this.header.last(Xb.DirectMsgHeaders.NumPending);return typeof $==="string"?parseInt($):-1}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return FJ.TD.decode(this.data)}}dt1.DirectMsgImpl=z90;function Xi6($){return typeof $==="object"&&"start_time"in $}function Qi6($){return typeof $==="object"&&"max_bytes"in $}class lt1{stream;api;cursor;listeners;start;constructor($,Z,X){this.stream=$,this.api=Z,this.cursor={last:0},this.listeners=[],this.start=X}getOptions($){$=$||{};let Z={};if(this.cursor.last===0)if(Xi6(this.start))Z.start_time=this.start.start_time;else Z.seq=this.start.seq||1;else Z.seq=this.cursor.last+1;if(Qi6($))Z.max_bytes=$.max_bytes;else Z.batch=$.batch??100;return Z}status(){let $=new FJ.QueuedIteratorImpl;return this.listeners.push($),$}notify($){if(this.listeners.length>0)(()=>{let Z=[];this.listeners.forEach((X)=>{let Q=X;if(!Q.done)Q.push($);else Z.push(Q)}),this.listeners=this.listeners.filter((X)=>!Z.includes(X))})()}debug(){console.log(this.cursor)}consume($){let Z,X,Q=new FJ.QueuedIteratorImpl;return(async()=>{while(!0){if(this.cursor.pending===0)this.notify({type:"debug",code:0,description:"sleeping for 2500"}),Z=(0,FJ.delay)(2500),await Z;if(Q.done)break;X=(0,FJ.deferred)();let Y=this.getOptions($);this.notify({type:"next",options:Object.assign({},$)}),Y.callback=(J,K)=>{if(J){if(J.err)if(J.err instanceof id0.JetStreamStatusError)this.notify({type:"debug",code:J.err.code,description:J.err.message});else this.notify({type:"debug",code:0,description:J.err.message});X.resolve()}else if(K.lastSequence>0&&K.lastSequence!==this.cursor.last)G.stop(),X.resolve(),this.notify({type:"reset",name:"direct"});else Q.push(K),Q.received++,this.cursor.last=K.seq,this.cursor.pending=K.pending};let G=await this.api.getBatch(this.stream,Y);Q.iterClosed.then(()=>{G.stop(),Z?.cancel(),X?.resolve()}),await X}})().catch((Y)=>{Q.stop(Y)}),Promise.resolve(Q)}async fetch($){let Z=this.getOptions($),X=new FJ.QueuedIteratorImpl,Q=await this.api.get(this.stream,Object.assign({callback:(Y,G)=>{if(Y)X.push(()=>{Y.err?X.stop(Y.err):X.stop()});else if(G.lastSequence>0&&G.lastSequence!==this.cursor.last)X.push(()=>{X.stop()}),Q.stop();else X.push(G),X.received++,this.cursor.last=G.seq,this.cursor.pending=G.pending}},Z));return X.iterClosed.then(()=>{Q.stop()}),X}async next(){let $=await this.api.getMessage(this.stream,{seq:this.cursor.last+1}),Z=$?.seq;if(Z)this.cursor.last=Z;return $}}dt1.DirectConsumer=lt1});var st1=_((rt1)=>{Object.defineProperty(rt1,"__esModule",{value:!0});rt1.BatchPublisherImpl=rt1.JetStreamClientImpl=rt1.JetStreamManagerImpl=void 0;rt1.startFastIngest=Ki6;rt1.toJetStreamClient=Wi6;rt1.jetstream=td0;rt1.jetstreamManager=pt1;rt1.scheduleSpecToHeader=tt1;var pd0=ef(),nt1=vd0(),c$=gY(),j90=ht1(),gX=tD(),it1=RN(),Ji6=nd0();function Ki6($,Z,X,Q,Y=5000){let{ackInterval:G,allowGaps:J,inboxPrefix:K,maxOutstandingAcks:W,...H}=Q,N=K??"_INBOX";if(!N||/\s/.test(N)||/[*>]/.test(N))return Promise.reject(Error(`inboxPrefix must be non-empty, no wildcards or whitespace (got "${N}")`));let U={ackInterval:G??10,allowGaps:J,inboxPrefix:N,maxOutstandingAcks:Math.min(3,Math.max(1,W??2))},F=new ot1($,U,Z,Y);return F.start(X,H).then(()=>F)}function ym($){let Z=$.expect||{},X=$.headers||(0,c$.headers)();if($.msgID)X.set(gX.PubHeaders.MsgIdHdr,$.msgID);if(Z.lastMsgID)X.set(gX.PubHeaders.ExpectedLastMsgIdHdr,Z.lastMsgID);if(Z.streamName)X.set(gX.PubHeaders.ExpectedStreamHdr,Z.streamName);if(typeof Z.lastSequence==="number")X.set(gX.PubHeaders.ExpectedLastSeqHdr,`${Z.lastSequence}`);if(typeof Z.lastSubjectSequence==="number")X.set(gX.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Z.lastSubjectSequence}`);if(Z.lastSubjectSequenceSubject)X.set(gX.PubHeaders.ExpectedLastSubjectSequenceSubjectHdr,Z.lastSubjectSequenceSubject);if($.ttl)X.set(gX.PubHeaders.MessageTTL,`${$.ttl}`);if($.schedule&&$.cancelSchedule)throw Error("schedule and cancelSchedule are mutually exclusive");if($.schedule){let Q=$.schedule;if(Q.specification)X.set(gX.PubHeaders.Schedule,tt1(Q.specification));if(Q.target)X.set(gX.PubHeaders.ScheduleTarget,Q.target);if(Q.source)X.set(gX.PubHeaders.ScheduleSource,Q.source);if(Q.ttl)X.set(gX.PubHeaders.ScheduleTTL,Q.ttl);if(Q.timezone)X.set(gX.PubHeaders.ScheduleTimeZone,Q.timezone);if(Q.rollup)X.set(gX.PubHeaders.ScheduleRollup,Q.rollup)}if($.cancelSchedule)X.set(gX.PubHeaders.Scheduler,$.cancelSchedule.scheduleSubject),X.set(gX.PubHeaders.ScheduleNext,"purge");return X}function Wi6($){if(typeof $.nc>"u")return td0($);return $}function td0($,Z={}){return new rd0($,Z)}async function pt1($,Z={}){let X=new od0($,Z);if(Z.checkAPI!==!1)try{await X.getAccountInfo()}catch(Q){throw Q}return X}class od0 extends pd0.BaseApiClientImpl{streams;consumers;direct;constructor($,Z){super($,Z);this.streams=new j90.StreamAPIImpl($,Z),this.consumers=new nt1.ConsumerAPIImpl($,Z),this.direct=new Ji6.DirectStreamAPIImpl($,Z)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return td0(this.nc,this.getOptions())}advisories(){let $=new c$.QueuedIteratorImpl;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(Z,X)=>{if(Z)throw Z;try{let Q=this.parseJsResponse(X),Y=Q.type.split("."),G=Y[Y.length-1];$.push({kind:G,data:Q})}catch(Q){$.stop(Q)}}}),$}}rt1.JetStreamManagerImpl=od0;function tt1($){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 Hi6($.every),`@every ${$.every}`;if("cron"in $)return $.cron;if("predefined"in $)return $.predefined;throw Error("invalid schedule specification")}function Hi6($){let Z=$.trim(),X=/(\d+(?:\.\d+)?)(ns|us|\u00B5s|ms|s|m|h)/g,Q=0,Y=0,G;while((G=X.exec(Z))!==null){if(G.index!==Y)break;Y+=G[0].length;let J=parseFloat(G[1]),K=G[2];Q+=K==="ns"?J/1e6:K==="us"||K==="\xB5s"?J/1000:K==="ms"?J:K==="s"?J*1000:K==="m"?J*60000:J*3600000}if(Z===""||Y!==Z.length)throw Error(`@every: unrecognized duration format: "${$}"`);if(Q<1000)throw Error("@every interval must be at least 1s")}class rd0 extends pd0.BaseApiClientImpl{consumers;streams;consumerAPI;streamAPI;constructor($,Z){super($,Z);this.consumerAPI=new nt1.ConsumerAPIImpl($,Z),this.streamAPI=new j90.StreamAPIImpl($,Z),this.consumers=new j90.ConsumersImpl(this.consumerAPI),this.streams=new j90.StreamsImpl(this.streamAPI)}jetstreamManager($){if($===void 0)$=this.opts.checkAPI;let Z=Object.assign({},this.opts,{checkAPI:$});try{(0,c$.createInbox)(Z.watcherPrefix)}catch(X){return Promise.reject(X)}return pt1(this.nc,Z)}get apiPrefix(){return this.prefix}startBatch($,Z,X){let Q=(0,c$.deferred)(),Y=new ad0(this);return Y.first($,Z,X).then(()=>{Q.resolve(Y)}).catch((G)=>{Q.reject(G)}),Q}async _publish($,Z=c$.Empty,X){if(X=X||{},X={...X},X.cancelSchedule&&X.cancelSchedule.scheduleSubject===$)throw Error("cancelSchedule.scheduleSubject must not equal the publish subject");let Q=ym(X),Y=X.timeout||this.timeout,G={};if(Y)G.timeout=Y;if(X)G.headers=Q;let{retries:J}=X;J=J||1;let K=(0,c$.backoff)(),W=null;for(let H=0;H<J;H++)try{W=await this.nc.request($,Z,G);break}catch(N){let U=N instanceof c$.RequestError?N:null;if((N instanceof c$.errors.TimeoutError||U?.isNoResponders())&&H+1<J)await(0,c$.delay)(K.backoff(H));else throw U?.isNoResponders()?new it1.JetStreamNotEnabled("jetstream is not enabled",{cause:N}):N}return W}async publish($,Z=c$.Empty,X){let Q=await this._publish($,Z,X),Y=this.parseJsResponse(Q);if(Y.stream==="")throw new it1.JetStreamError("invalid ack response");return Y.duplicate=Y.duplicate?Y.duplicate:!1,Y}}rt1.JetStreamClientImpl=rd0;class ad0{nc;js;id;count;done;constructor($){this.count=0,this.id=c$.nuid.next(),this.js=$,this.nc=this.js.nc,this.done=!1}async first($,Z,X){X=X||{},X.headers=X?.headers||(0,c$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString());let Q=await this.js._publish($,Z,X);if(Q.data.length>0)this.js.parseJsResponse(Q)}add($,Z,X={ack:!1}){if(this.done)throw Error("batch publisher is done");if(X.headers=X?.headers||(0,c$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString()),"ack"in X&&X.ack===!0){let Y=(0,c$.deferred)();return this.js._publish($,Z,{headers:X.headers,timeout:X.timeout}).then((G)=>{if(G.data.length>0)this.js.parseJsResponse(G);Y.resolve()}).catch((G)=>{this.done=!0,Y.reject(G)}),Y}else return this.nc.publish($,Z,{headers:X.headers})}async commit($,Z,X={}){if(this.done)throw Error("batch publisher is done");else this.done=!0;X.headers=X?.headers||(0,c$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString()),X.headers.set("Nats-Batch-Commit","1");let Y=(await this.js._publish($,Z,{headers:X.headers,timeout:X.timeout||0})).json();if(Y.count!==this.count)throw Error("batch didn't contain number of published messages");return Y}}rt1.BatchPublisherImpl=ad0;var bm="batch closed",K7={Start:0,Append:1,Final:2,EOB:3,Ping:4};class ot1{batch;nc;batchSubj;gapMode;initialFlow;seq;acked;ackInterval;inboxPrefix;maxOutstandingAcks;defaultTimeout;gapIter;sub;pending;closed;closeErr;startDeferred;closedDeferred;constructor($,Z,X,Q){this.nc=$,this.batchSubj=X,this.gapMode=Z.allowGaps?"ok":"fail",this.initialFlow=Z.ackInterval,this.inboxPrefix=Z.inboxPrefix,this.maxOutstandingAcks=Z.maxOutstandingAcks,this.defaultTimeout=Q,this.batch=c$.nuid.next(),this.seq=0,this.acked=0,this.ackInterval=Z.ackInterval,this.pending=new Map,this.closed=!1,this.startDeferred=(0,c$.deferred)(),this.closedDeferred=(0,c$.deferred)(),this.closedDeferred.catch(()=>{}),this.startDeferred.catch(()=>{});let Y=`${this.inboxPrefix}.${this.batch}.>`;this.sub=this.nc.subscribe(Y,{callback:(G,J)=>this.route(G,J)})}replyFor($,Z){return`${this.inboxPrefix}.${this.batch}.${this.initialFlow}.${this.gapMode}.${Z}.${$}.$FI`}start($,Z){this.seq=1;let X=this.replyFor(K7.Start,1),Q=Z?ym(Z):void 0;return this.nc.publish(this.batchSubj,$,{reply:X,headers:Q}),this.deadlineOrClose(this.startDeferred,Z?.timeout??this.defaultTimeout)}deadlineOrClose($,Z){return(0,c$.deadline)($,Z).catch((X)=>{if(!this.closed)this.close(X);throw X})}route($,Z){if($){this.close($);return}let X;try{X=(0,pd0.parseJsResponse)(Z)}catch(J){this.close(J);return}if("batch"in X&&typeof X.batch==="string"){let J=X,K=this.pending.get(Z.subject);if(K&&(K.op===K7.Final||K.op===K7.EOB))K.deferred.resolve(J),this.pending.delete(Z.subject);for(let[,W]of this.pending)if(W.op===K7.Append||W.op===K7.Ping)W.deferred.resolve({batchSeq:W.seq,ackSeq:this.acked});else W.deferred.reject(Error(bm));this.pending.clear(),this.resolveStart(),this.closedDeferred.resolve(J),this.closed=!0,this.gapIter?.stop(),this.sub.unsubscribe();return}if(X.type==="gap"){if(this.gapIter){let J=X;this.gapIter.push({lastSeq:J.last_seq,seq:J.seq})}return}let Y=X;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 G=this.pending.get(Z.subject);if(G&&(G.op===K7.Append||G.op===K7.Ping))G.deferred.resolve({batchSeq:G.seq,ackSeq:this.acked}),this.pending.delete(Z.subject);for(let[J,K]of this.pending)if(K.op===K7.Append&&K.seq-this.acked<this.ackInterval*this.maxOutstandingAcks)K.deferred.resolve({batchSeq:K.seq,ackSeq:this.acked}),this.pending.delete(J)}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,X){if(this.closed)return Promise.reject(Error(bm));let Q=++this.seq,Y=this.replyFor(K7.Append,Q),G=X?ym(X):void 0;if(this.nc.publish($,Z,{reply:Y,headers:G}),Q-this.acked<this.ackInterval*this.maxOutstandingAcks)return Promise.resolve({batchSeq:Q,ackSeq:this.acked});let J=(0,c$.deferred)();return this.pending.set(Y,{seq:Q,op:K7.Append,deferred:J}),this.deadlineOrClose(J,X?.timeout??this.defaultTimeout)}last($,Z,X){if(this.closed)return Promise.reject(Error(bm));let Q=++this.seq,Y=this.replyFor(K7.Final,Q),G=(0,c$.deferred)();this.pending.set(Y,{seq:Q,op:K7.Final,deferred:G});let J=X?ym(X):void 0;return this.nc.publish($,Z,{reply:Y,headers:J}),this.deadlineOrClose(G,X?.timeout??this.defaultTimeout)}end($){if(this.closed)return Promise.reject(Error(bm));let Z=++this.seq,X=this.replyFor(K7.EOB,Z),Q=(0,c$.deferred)();this.pending.set(X,{seq:Z,op:K7.EOB,deferred:Q});let Y=$?ym($):void 0;return this.nc.publish(this.batchSubj,c$.Empty,{reply:X,headers:Y}),this.deadlineOrClose(Q,$?.timeout??this.defaultTimeout)}ping($=this.defaultTimeout){if(this.closed)return Promise.reject(Error(bm));let Z=this.replyFor(K7.Ping,this.seq),X=this.pending.get(Z);if(X&&X.op===K7.Ping)return(0,c$.deadline)(X.deferred,$);let Q=(0,c$.deferred)();return this.pending.set(Z,{seq:this.seq,op:K7.Ping,deferred:Q}),this.nc.publish(this.batchSubj,c$.Empty,{reply:Z}),this.deadlineOrClose(Q,$)}done(){return this.closedDeferred}gaps(){if(!this.gapIter)this.gapIter=new c$.QueuedIteratorImpl;return this.gapIter}}});var P90=_((P4)=>{Object.defineProperty(P4,"__esModule",{value:!0});P4.validateStreamName=P4.jserrors=P4.JetStreamStatusError=P4.JetStreamStatus=P4.JetStreamError=P4.JetStreamApiError=P4.JetStreamApiCodes=P4.isMessageNotFound=P4.ListerImpl=P4.StoreCompression=P4.StorageType=P4.RetentionPolicy=P4.ReplayPolicy=P4.PubHeaders=P4.PersistMode=P4.DiscardPolicy=P4.DeliverPolicy=P4.AckPolicy=P4.DirectMsgImpl=P4.BaseApiClientImpl=P4.toJetStreamClient=P4.startFastIngest=P4.jetstreamManager=P4.JetStreamClientImpl=P4.jetstream=P4.RepublishHeaders=P4.JsHeaders=P4.isPushConsumer=P4.isPullConsumer=P4.isOrderedPushConsumerOptions=P4.isBoundPushConsumerOptions=P4.DirectMsgHeaders=P4.AdvisoryKind=void 0;var Lw=uD();Object.defineProperty(P4,"AdvisoryKind",{enumerable:!0,get:function(){return Lw.AdvisoryKind}});Object.defineProperty(P4,"DirectMsgHeaders",{enumerable:!0,get:function(){return Lw.DirectMsgHeaders}});Object.defineProperty(P4,"isBoundPushConsumerOptions",{enumerable:!0,get:function(){return Lw.isBoundPushConsumerOptions}});Object.defineProperty(P4,"isOrderedPushConsumerOptions",{enumerable:!0,get:function(){return Lw.isOrderedPushConsumerOptions}});Object.defineProperty(P4,"isPullConsumer",{enumerable:!0,get:function(){return Lw.isPullConsumer}});Object.defineProperty(P4,"isPushConsumer",{enumerable:!0,get:function(){return Lw.isPushConsumer}});Object.defineProperty(P4,"JsHeaders",{enumerable:!0,get:function(){return Lw.JsHeaders}});Object.defineProperty(P4,"RepublishHeaders",{enumerable:!0,get:function(){return Lw.RepublishHeaders}});var gm=st1();Object.defineProperty(P4,"jetstream",{enumerable:!0,get:function(){return gm.jetstream}});Object.defineProperty(P4,"JetStreamClientImpl",{enumerable:!0,get:function(){return gm.JetStreamClientImpl}});Object.defineProperty(P4,"jetstreamManager",{enumerable:!0,get:function(){return gm.jetstreamManager}});Object.defineProperty(P4,"startFastIngest",{enumerable:!0,get:function(){return gm.startFastIngest}});Object.defineProperty(P4,"toJetStreamClient",{enumerable:!0,get:function(){return gm.toJetStreamClient}});var Di6=ef();Object.defineProperty(P4,"BaseApiClientImpl",{enumerable:!0,get:function(){return Di6.BaseApiClientImpl}});var Ei6=nd0();Object.defineProperty(P4,"DirectMsgImpl",{enumerable:!0,get:function(){return Ei6.DirectMsgImpl}});var MN=tD();Object.defineProperty(P4,"AckPolicy",{enumerable:!0,get:function(){return MN.AckPolicy}});Object.defineProperty(P4,"DeliverPolicy",{enumerable:!0,get:function(){return MN.DeliverPolicy}});Object.defineProperty(P4,"DiscardPolicy",{enumerable:!0,get:function(){return MN.DiscardPolicy}});Object.defineProperty(P4,"PersistMode",{enumerable:!0,get:function(){return MN.PersistMode}});Object.defineProperty(P4,"PubHeaders",{enumerable:!0,get:function(){return MN.PubHeaders}});Object.defineProperty(P4,"ReplayPolicy",{enumerable:!0,get:function(){return MN.ReplayPolicy}});Object.defineProperty(P4,"RetentionPolicy",{enumerable:!0,get:function(){return MN.RetentionPolicy}});Object.defineProperty(P4,"StorageType",{enumerable:!0,get:function(){return MN.StorageType}});Object.defineProperty(P4,"StoreCompression",{enumerable:!0,get:function(){return MN.StoreCompression}});var zi6=O90();Object.defineProperty(P4,"ListerImpl",{enumerable:!0,get:function(){return zi6.ListerImpl}});var rD=RN();Object.defineProperty(P4,"isMessageNotFound",{enumerable:!0,get:function(){return rD.isMessageNotFound}});Object.defineProperty(P4,"JetStreamApiCodes",{enumerable:!0,get:function(){return rD.JetStreamApiCodes}});Object.defineProperty(P4,"JetStreamApiError",{enumerable:!0,get:function(){return rD.JetStreamApiError}});Object.defineProperty(P4,"JetStreamError",{enumerable:!0,get:function(){return rD.JetStreamError}});Object.defineProperty(P4,"JetStreamStatus",{enumerable:!0,get:function(){return rD.JetStreamStatus}});Object.defineProperty(P4,"JetStreamStatusError",{enumerable:!0,get:function(){return rD.JetStreamStatusError}});Object.defineProperty(P4,"jserrors",{enumerable:!0,get:function(){return rD.jserrors}});var ji6=$b();Object.defineProperty(P4,"validateStreamName",{enumerable:!0,get:function(){return ji6.validateStreamName}})});var aD=_((Q9)=>{Object.defineProperty(Q9,"__esModule",{value:!0});Q9.StoreCompression=Q9.StorageType=Q9.RetentionPolicy=Q9.RepublishHeaders=Q9.ReplayPolicy=Q9.PubHeaders=Q9.PersistMode=Q9.JsHeaders=Q9.JetStreamError=Q9.JetStreamApiError=Q9.JetStreamApiCodes=Q9.isPushConsumer=Q9.isPullConsumer=Q9.DiscardPolicy=Q9.DirectMsgHeaders=Q9.DeliverPolicy=Q9.AdvisoryKind=Q9.AckPolicy=Q9.jetstreamManager=Q9.jetstream=void 0;var et1=P90();Object.defineProperty(Q9,"jetstream",{enumerable:!0,get:function(){return et1.jetstream}});Object.defineProperty(Q9,"jetstreamManager",{enumerable:!0,get:function(){return et1.jetstreamManager}});var xZ=P90();Object.defineProperty(Q9,"AckPolicy",{enumerable:!0,get:function(){return xZ.AckPolicy}});Object.defineProperty(Q9,"AdvisoryKind",{enumerable:!0,get:function(){return xZ.AdvisoryKind}});Object.defineProperty(Q9,"DeliverPolicy",{enumerable:!0,get:function(){return xZ.DeliverPolicy}});Object.defineProperty(Q9,"DirectMsgHeaders",{enumerable:!0,get:function(){return xZ.DirectMsgHeaders}});Object.defineProperty(Q9,"DiscardPolicy",{enumerable:!0,get:function(){return xZ.DiscardPolicy}});Object.defineProperty(Q9,"isPullConsumer",{enumerable:!0,get:function(){return xZ.isPullConsumer}});Object.defineProperty(Q9,"isPushConsumer",{enumerable:!0,get:function(){return xZ.isPushConsumer}});Object.defineProperty(Q9,"JetStreamApiCodes",{enumerable:!0,get:function(){return xZ.JetStreamApiCodes}});Object.defineProperty(Q9,"JetStreamApiError",{enumerable:!0,get:function(){return xZ.JetStreamApiError}});Object.defineProperty(Q9,"JetStreamError",{enumerable:!0,get:function(){return xZ.JetStreamError}});Object.defineProperty(Q9,"JsHeaders",{enumerable:!0,get:function(){return xZ.JsHeaders}});Object.defineProperty(Q9,"PersistMode",{enumerable:!0,get:function(){return xZ.PersistMode}});Object.defineProperty(Q9,"PubHeaders",{enumerable:!0,get:function(){return xZ.PubHeaders}});Object.defineProperty(Q9,"ReplayPolicy",{enumerable:!0,get:function(){return xZ.ReplayPolicy}});Object.defineProperty(Q9,"RepublishHeaders",{enumerable:!0,get:function(){return xZ.RepublishHeaders}});Object.defineProperty(Q9,"RetentionPolicy",{enumerable:!0,get:function(){return xZ.RetentionPolicy}});Object.defineProperty(Q9,"StorageType",{enumerable:!0,get:function(){return xZ.StorageType}});Object.defineProperty(Q9,"StoreCompression",{enumerable:!0,get:function(){return xZ.StoreCompression}})});import{mkdir as Ti6,readdir as Ri6,readFile as sd0,stat as A90,unlink as Ii6,writeFile as qi6}from"fs/promises";import{createHmac as Mi6}from"crypto";import{dirname as ki6,join as hm}from"path";function ed0($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return hm(Si6,Z)}function Qb($,Z){return hm(ed0($),iK(Z))}class ZW{orgId;baseUrl;constructor($,Z){this.orgId=$;this.baseUrl=Z}async getBytesOrPresign($,Z){let X=Qb(this.orgId,$),Q=await A90(X),Y=VZ($);if(Q.size>Z.presignWhenLargerThan)return{error:"FILE_TOO_LARGE",size:Q.size,maxInlineSize:Z.presignWhenLargerThan,presignedUrl:await this.presignedGetUrl($),contentType:Y};let G=await sd0(X),J=s$0(Y);return{content:J?new TextDecoder().decode(G):Buffer.from(G).toString("base64"),contentType:Y,encoding:J?"utf-8":"base64",size:Q.size,lastModified:Q.mtime}}async getBytes($){let Z=await sd0(Qb(this.orgId,$));return new Uint8Array(Z)}async put($,Z,X){let Q=Qb(this.orgId,$);return await Ti6(ki6(Q),{recursive:!0}),await qi6(Q,typeof Z==="string"?Buffer.from(Z,"utf-8"):Z),{key:$}}async list($){let Z=$?.prefix?hm(ed0(this.orgId),iK($.prefix)):ed0(this.orgId),X;try{X=await Ri6(Z,{withFileTypes:!0})}catch{return{objects:[],isTruncated:!1}}let Q=$?.maxKeys??1000,Y=$?.prefix,G=X.filter((K)=>K.isFile());if($?.delimiter){let K=[],W=X.filter((B)=>B.isDirectory());for(let B of W){let L=Y?`${Y}/${B.name}/`:`${B.name}/`;K.push(L)}K.sort();let H=Q,N=K.slice(0,H);H-=N.length;let U=G.slice(0,H),F=K.length+G.length;return{objects:await Promise.all(U.map(async(B)=>{let L=await A90(hm(Z,B.name));return{key:Y?`${Y}/${B.name}`:B.name,size:L.size,lastModified:L.mtime}})),isTruncated:F>Q,commonPrefixes:N.length>0?N:void 0}}return{objects:await Promise.all(G.slice(0,Q).map(async(K)=>{let W=await A90(hm(Z,K.name));return{key:Y?`${Y}/${K.name}`:K.name,size:W.size,lastModified:W.mtime}})),isTruncated:G.length>Q}}async delete($){await Ii6(Qb(this.orgId,$))}async head($){let Z=await A90(Qb(this.orgId,$));return{contentType:VZ($),size:Z.size,lastModified:Z.mtime}}async presignedGetUrl($,Z,X){if(X?.requireFetchable)throw Error("object storage returned a not fetchable (data:) URL; configure real S3/R2/MinIO for large-payload offload");let Q=Qb(this.orgId,$),Y=await sd0(Q),G=VZ($),J=Buffer.from(Y).toString("base64");return`data:${G};base64,${J}`}async presignedPutUrl($,Z=3600){if(!this.baseUrl)throw Error("baseUrl required for presigned PUT URLs in dev mode");let X=iK($),Q=Math.floor(Date.now()/1000)+Z,Y=Q1().encryptionKey||"dev-secret",G=`${this.orgId}:${X}:${Q}:PUT`,J=Mi6("sha256",Y).update(G).digest("hex"),K=new URL(`/api/dev-assets/${this.orgId}/${X}`,this.baseUrl);return K.searchParams.set("expires",Q.toString()),K.searchParams.set("signature",J),K.searchParams.set("method","PUT"),K.toString()}}var Si6="./data/assets";var um=O(()=>{nK();y8()});function Yb($){return Vi6.test($)&&$!=="."&&$!==".."}function vZ($){if(!Yb($))throw Error(`Invalid org-fs volume name: ${JSON.stringify($)}`)}function fZ($){return iK($)}function Gb($){let Z=$.lastIndexOf("/");return Z===-1?"":$.slice(0,Z)}function Dw($){let Z=Gb($);if(Z==="")return[];let X=Z.split("/"),Q=[],Y="";for(let G of X)Y=Y===""?G:`${Y}/${G}`,Q.push(Y);return Q}function XW($,Z){return`${$o1}/${$}/${Z}`}function Zo1($){return`${$o1}/${$}/`}var Vi6,$o1="_fs";var cm=O(()=>{nK();Vi6=/^[A-Za-z0-9_.-]{1,128}$/});import{createHmac as $m0,randomBytes as Zm0,scrypt as Ci6,timingSafeEqual as Xo1}from"crypto";import{promisify as _i6}from"util";async function Yo1($){let Z=Zm0(16),X=await Qo1($,Z,xi6);return`scrypt$${Z.toString("hex")}$${X.toString("hex")}`}async function Go1($,Z){let X=Z.split("$");if(X.length!==3||X[0]!=="scrypt")return!1;let Q=Buffer.from(X[1],"hex"),Y=Buffer.from(X[2],"hex");if(Q.length===0||Y.length===0)return!1;let G;try{G=await Qo1($,Q,Y.length)}catch{return!1}return Y.length===G.length&&Xo1(Y,G)}function Jo1(){return Zm0(16).toString("hex")}function Ko1(){if(T90)return T90;let $;try{let Z=Q1();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return T90=$?Buffer.from($):Zm0(32),T90}function Wo1($){let Z=Buffer.from(JSON.stringify($)).toString("base64url"),X=$m0("sha256",Ko1()).update(Z).digest("base64url");return`${Z}.${X}`}function Ho1($,Z){let X=$.indexOf(".");if(X<0)return null;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from($m0("sha256",Ko1()).update(Q).digest("base64url"));if(Y.length!==G.length||!Xo1(Y,G))return null;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return null}if(J.o!==Z.org||J.v!==Z.volume||J.s!==Z.secret||typeof J.e!=="number"||J.e<Z.nowSec)return null;return{govPath:J.p}}function Xm0($,Z,X){return`fsu_${$m0("sha256","fsunlock-name").update(`${$}:${Z}:${X}`).digest("hex").slice(0,16)}`}var xi6=64,Qo1,T90=null;var Qm0=O(()=>{y8();Qo1=_i6(Ci6)});import{createHash as vi6}from"crypto";function hi6($){if(typeof $!=="object"||$===null)return!1;let Z=$;return Z.name==="NoSuchKey"||Z.Code==="NoSuchKey"||Z.code==="ENOENT"||Z.$metadata?.httpStatusCode===404}function No1($){return vi6("sha256").update($).digest("hex")}class YW{storage;manifest;organizationId;maxFileBytes;volumeQuotaBytes;constructor($,Z,X,Q={}){this.storage=$;this.manifest=Z;this.organizationId=X;this.maxFileBytes=Q.maxFileBytes??yi6,this.volumeQuotaBytes=Q.volumeQuotaBytes??gi6}async usage($){return vZ($),this.manifest.usage(this.organizationId,$)}async stat($,Z){return vZ($),this.manifest.get(this.organizationId,$,fZ(Z))}async listDir($,Z){return vZ($),this.manifest.listDir(this.organizationId,$,fZ(Z))}async read($,Z){let X=await this.requireFile($,Z);try{return await this.storage.getBytes(XW($,X.path))}catch(Q){if(hi6(Q))throw new QW(`No such file: ${X.path}`);throw Q}}async setShareMode($,Z,X,Q){vZ($);let Y=fZ(Z),G=await this.manifest.get(this.organizationId,$,Y);if(!G)throw new QW(`No such path: ${Y}`);let J=null,K=null;if(X==="password"){if(!Q.password)throw new wJ("A password is required to set password mode");J=await Yo1(Q.password),K=Jo1()}let W=await this.manifest.setShareMode({organizationId:this.organizationId,volume:$,path:G.path,readPublic:X!=="private",passwordHash:J,shareSecret:K,actor:Q.actor});if(!W)throw new QW(`No such path: ${G.path}`);return W}async setReadPublic($,Z,X,Q){return this.setShareMode($,Z,X?"public":"private",{actor:Q.actor})}async resolveReadAccess($,Z){vZ($);let X=fZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")return{access:"private"};let Y=await this.manifest.resolveGoverningShare({organizationId:this.organizationId,volume:$,candidatePaths:[X,...Dw(X)]});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){vZ($);let X=fZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")return!1;if(Q.readPublic)return!0;return this.manifest.hasPublicAncestorDir(this.organizationId,$,Dw(X))}async inheritsPublic($,Z){return vZ($),this.manifest.hasPublicAncestorDir(this.organizationId,$,Dw(fZ(Z)))}async childrenInheritPublic($,Z){vZ($);let X=fZ(Z);if(X==="")return!1;return this.manifest.hasPublicAncestorDir(this.organizationId,$,[...Dw(X),X])}async recentWithEffectivePublic($){return this.withEffectivePublic(await this.recent($))}async searchWithEffectivePublic($,Z,X,Q){return this.withEffectivePublic(await this.manifest.searchFiles({organizationId:this.organizationId,query:$,limit:Z,volumes:X,pathPrefix:Q?fZ(Q):void 0}))}async withEffectivePublic($){let Z=new Map;for(let Q of $){let Y=Z.get(Q.volume);if(!Y)Y=new Set,Z.set(Q.volume,Y);for(let G of Dw(Q.path))Y.add(G)}let X=new Map;return await Promise.all([...Z].map(async([Q,Y])=>{let G=await this.manifest.publicDirPaths({organizationId:this.organizationId,volume:Q,paths:[...Y]});X.set(Q,new Set(G))})),$.map((Q)=>{let Y=X.get(Q.volume),G=!!Y&&Dw(Q.path).some((J)=>Y.has(J));return{...Q,effectivePublic:Q.readPublic||G}})}async presignRead($,Z,X){let Q=await this.requireFile($,Z);return this.storage.presignedGetUrl(XW($,Q.path),X)}async write($,Z,X,Q){vZ($);let Y=fZ(Z);if(Y==="")throw new wJ("Cannot write to the volume root");let G=typeof X==="string"?new TextEncoder().encode(X):X;if(G.byteLength>this.maxFileBytes)throw new lm(`File exceeds the ${this.maxFileBytes}-byte per-file limit`);let[J,K]=await Promise.all([Q.skipVolumeQuota?Promise.resolve(null):this.manifest.usage(this.organizationId,$),this.manifest.get(this.organizationId,$,Y)]);if(K?.kind==="dir")throw new wJ(`Cannot write a file at ${Y}: a directory exists there`);if(J){let W=K?.kind==="file"?K.size:0;if(J.bytes-W+G.byteLength>this.volumeQuotaBytes)throw new lm(`Write would exceed the volume quota of ${this.volumeQuotaBytes} bytes`)}return await this.ensureDirs($,Y,Q.actor),await this.storage.put(XW($,Y),G,{contentType:Q.contentType??VZ(Y)}),this.manifest.putFile({organizationId:this.organizationId,volume:$,path:Y,parent:Gb(Y),contentHash:No1(G),size:G.byteLength,actor:Q.actor,threadId:Q.threadId??null})}async mkdir($,Z,X){vZ($);let Q=fZ(Z);if(Q==="")return;if((await this.manifest.get(this.organizationId,$,Q))?.kind==="file")throw new wJ(`Cannot create a directory at ${Q}: a file exists there`);await this.ensureDirs($,Q,X.actor),await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Q,parent:Gb(Q),actor:X.actor})}async delete($,Z,X){vZ($);let Q=fZ(Z);if(Q==="")throw new wJ("Cannot delete the volume root");let Y=await this.manifest.get(this.organizationId,$,Q);if(!Y)return;if(Y.kind==="dir"){let G=await this.manifest.listSubtreeFiles(this.organizationId,$,Q);await Promise.all(G.map((J)=>this.storage.delete(XW($,J.path)))),await this.manifest.tombstoneSubtree(this.organizationId,$,Q,X.actor);return}await this.storage.delete(XW($,Q)),await this.manifest.tombstone(this.organizationId,$,Q,X.actor)}async move($,Z,X,Q){vZ($);let Y=fZ(Z),G=fZ(X);if(Y===""||G==="")throw new wJ("Cannot move the volume root");if(G===Y||G.startsWith(`${Y}/`))throw new wJ(`Cannot move ${Y} onto itself or into its own subtree`);let J=await this.manifest.get(this.organizationId,$,Y);if(!J)throw new QW(`No such path: ${Y}`);if(J.kind==="file"){let H=await this.storage.getBytes(XW($,Y));await this.write($,G,H,{...Q,skipVolumeQuota:!0}),await this.delete($,Y,Q);return}let[K,W]=await Promise.all([this.manifest.listSubtreeFiles(this.organizationId,$,Y),this.manifest.listSubtreeDirs(this.organizationId,$,Y)]);await this.mkdir($,G,Q);for(let H of K){let N=H.path.slice(Y.length+1),U=await this.storage.getBytes(XW($,H.path));await this.write($,`${G}/${N}`,U,{...Q,skipVolumeQuota:!0})}for(let H of W){let N=H.path.slice(Y.length+1);await this.mkdir($,`${G}/${N}`,Q)}await this.delete($,Y,Q)}async filesExist($,Z){vZ($);let X=await this.manifest.liveFilePaths({organizationId:this.organizationId,volume:$,paths:Z.map((Q)=>fZ(Q))});return new Set(X)}async recent($){return this.manifest.recentFiles({organizationId:this.organizationId,limit:$})}async changes($,Z,X=fi6){vZ($);let Q=Z||"0";if(!/^\d+$/.test(Q))throw new wJ(`Invalid cursor: ${Z}`);let Y=await this.manifest.changesSince({organizationId:this.organizationId,volume:$,sinceSeq:Q,limit:X}),G=Y.at(-1);return{entries:Y,cursor:G?G.seq:Z||"0",hasMore:Y.length>=X}}async latestSeq($){return vZ($),this.manifest.latestSeq({organizationId:this.organizationId,volume:$})}async backfillFromStorage($,Z){vZ($);let X=Zo1($),Q,Y=0;do{let G=await this.storage.list({prefix:X,maxKeys:bi6,continuationToken:Q});for(let J of G.objects){let K=J.key.slice(X.length);if(K==="")continue;await this.ensureDirs($,K,Z.actor);let W=await this.storage.getBytes(J.key);await this.manifest.putFile({organizationId:this.organizationId,volume:$,path:K,parent:Gb(K),contentHash:No1(W),size:W.byteLength,actor:Z.actor}),Y++}Q=G.isTruncated?G.nextContinuationToken:void 0}while(Q);return Y}async requireFile($,Z){vZ($);let X=fZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")throw new QW(`No such file: ${X}`);return Q}async ensureDirs($,Z,X){for(let Q of Dw(Z))await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Q,parent:Gb(Q),actor:X})}}var fi6=500,bi6=1000,yi6=524288000,gi6=10737418240,lm,wJ,QW;var sD=O(()=>{nK();cm();Qm0();lm=class lm extends Error{constructor($){super($);this.name="OrgFsQuotaError"}};wJ=class wJ extends Error{constructor($){super($);this.name="OrgFsValidationError"}};QW=class QW extends Error{constructor($){super($);this.name="OrgFsNotFoundError"}}});import{z as kN}from"zod";function Ew($){return $.startsWith(Uo1)}function zw($){return`${Uo1}${$}`}function mi6($){let Z=new Map(li6.map((X)=>[X.set,X]));if($)try{for(let X of di6.parse(JSON.parse($)))Z.set(X.set,X)}catch(X){console.warn("[org-fs] invalid ORGFS_PUBLIC_SETS \u2014 using built-in defaults only",X)}return[...Z.values()]}function dG(){return mi6(Q1().orgFsPublicSetsJson)}function dm($){let Z=fX(),X=Z?xY(Z,SN):new ZW(SN,$.baseUrl);return new YW(X,$.storage.orgFsEntries,SN)}var SN="org_orgfs_public_skills",Uo1="public-",ui6,ci6,li6,di6;var Jb=O(()=>{y8();Gw();um();sD();ui6=kN.object({from:kN.string(),to:kN.string().optional()}),ci6=kN.object({set:kN.string().regex(/^[a-z0-9][a-z0-9-]{0,40}$/),repo:kN.string().regex(/^[\w.-]+\/[\w.-]+$/),ref:kN.string().min(1),paths:kN.array(ui6).min(1)}),li6=[{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"}]}],di6=kN.array(ci6).refine(($)=>new Set($.map((Z)=>Z.set)).size===$.length,{message:"duplicate set names"})});import{sql as eD}from"kysely";function Ym0($){if($===null)return null;return $ instanceof Date?$.toISOString():String($)}function BJ($){return{organizationId:$.organization_id,volume:$.volume,path:$.path,parent:$.parent,kind:$.kind,contentHash:$.content_hash,size:Number($.size),seq:String($.seq),deletedAt:Ym0($.deleted_at),createdBy:$.created_by,createdAt:Ym0($.created_at)??"",updatedBy:$.updated_by,updatedAt:Ym0($.updated_at)??"",threadId:$.thread_id,readPublic:$.read_public,shareMode:!$.read_public?"private":$.share_password_hash?"password":"public"}}class im{db;constructor($){this.db=$}async putFile($){let Z=new Date,X=$.threadId??null,Q=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:X}).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:R90,read_public:eD`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`,thread_id:eD`coalesce(cast(${X} as text), org_fs_entry.thread_id)`})).returning(OJ).executeTakeFirstOrThrow();return BJ(Q)}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((X)=>X.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:R90,read_public:eD`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`})).execute()}async get($,Z,X){let Q=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("path","=",X).where("deleted_at","is",null).select(OJ).executeTakeFirst();return Q?BJ(Q):null}async listDir($,Z,X){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("parent","=",X).where("deleted_at","is",null).select(OJ).orderBy("path","asc").execute()).map((Y)=>BJ(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(OJ).execute()).map((Q)=>BJ(Q))}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(OJ).execute()).map((Q)=>BJ(Q))}async listSubtreeFiles($,Z,X){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",`${mm(X)}/%`).select(OJ).execute()).map((Y)=>BJ(Y))}async listSubtreeDirs($,Z,X){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",`${mm(X)}/%`).select(OJ).execute()).map((Y)=>BJ(Y))}async tombstone($,Z,X,Q){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Q,updated_at:new Date,seq:R90}).where("organization_id","=",$).where("volume","=",Z).where("path","=",X).where("deleted_at","is",null).execute()}async tombstoneSubtree($,Z,X,Q){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Q,updated_at:new Date,seq:R90}).where("organization_id","=",$).where("volume","=",Z).where("deleted_at","is",null).where((Y)=>Y.or([Y("path","=",X),Y("path","like",`${mm(X)}/%`)])).execute()}async setShareMode($){let Z=new Date,X=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(OJ).executeTakeFirst();return X?BJ(X):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((Q,Y)=>Y.path.length-Q.path.length);let X=Z[0];return{path:X.path,passwordHash:X.share_password_hash,secret:X.share_secret}}async hasPublicAncestorDir($,Z,X){if(X.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",X).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((X)=>X.path)}async usage($,Z){let X=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select((Q)=>[Q.fn.countAll().as("files"),Q.fn.coalesce(Q.fn.sum("size"),eD`0`).as("bytes")]).executeTakeFirst();return{files:Number(X?.files??0),bytes:Number(X?.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((X)=>X.path)}async recentFiles($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).select(OJ).orderBy("seq","desc").limit($.limit).execute()).map((X)=>BJ(X))}async searchFiles($){if($.volumes&&$.volumes.length===0)return[];let Z=mm($.query),X=this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).where("path","ilike",`%${Z}%`);if($.volumes)X=X.where("volume","in",$.volumes);if($.pathPrefix)X=X.where("path","like",`${mm($.pathPrefix)}/%`);return(await X.select(OJ).orderBy("seq","desc").limit($.limit).execute()).map((Y)=>BJ(Y))}async changesSince($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("seq",">",eD`cast(${$.sinceSeq} as bigint)`).select(OJ).orderBy("seq","asc").limit($.limit).execute()).map((X)=>BJ(X))}async latestSeq($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).select(eD`max(seq)`.as("seq")).executeTakeFirst())?.seq??"0"}}function mm($){return $.replace(/[\\%_]/g,"\\$&")}var OJ,R90;var Gm0=O(()=>{OJ=["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"],R90=eD`nextval('org_fs_entry_seq')`});import{createHash as ii6}from"crypto";import{gunzipSync as ni6}from"zlib";function Km0($,Z,X){let Q=Z,Y=Z+X;while(Q<Y&&$[Q]!==0)Q++;return new TextDecoder().decode($.subarray(Z,Q))}function ti6($,Z,X){let Q=Km0($,Z,X).trim();return Q===""?0:Number.parseInt(Q,8)}function oi6($){let Z=new Map,X=0,Q=null,Y=null;while(X+512<=$.length){let G=$.subarray(X,X+512);if(X+=512,G.every((F)=>F===0))break;let J=Km0(G,0,100),K=Km0(G,345,155);if(K)J=`${K}/${J}`;let W=ti6(G,124,12),H=String.fromCharCode(G[156]??0),N=$.subarray(X,X+W);if(X+=Math.ceil(W/512)*512,H==="L"){let F=new TextDecoder().decode(N),w=F.indexOf("\x00");Q=w===-1?F:F.slice(0,w);continue}if(H==="x"){let F=new TextDecoder().decode(N);Y=/(?:^|\n)\d+ path=([^\n]*)\n/.exec(F)?.[1]??null;continue}if(H==="g")continue;let U=Y??Q??J;if(Q=null,Y=null,H==="0"||H==="\x00"||H==="")Z.set(U,new Uint8Array(N))}return Z}async function ri6($,Z){let X=`https://codeload.github.com/${$}/tar.gz/${encodeURIComponent(Z)}`,Q=await fetch(X,{signal:AbortSignal.timeout(60000)});if(!Q.ok)throw Error(`tarball fetch failed for ${$}@${Z}: HTTP ${Q.status}`);let Y=Number(Q.headers.get("content-length")??0);if(Y>I90)throw Error(`tarball for ${$}@${Z} declares ${Y} bytes (cap ${I90})`);let G=new Uint8Array(await Q.arrayBuffer());if(G.length>I90)throw Error(`tarball for ${$}@${Z} exceeds ${I90} bytes`);let J=oi6(new Uint8Array(ni6(G,{maxOutputLength:pi6}))),K=new Map;for(let[W,H]of J){let N=W.indexOf("/");if(N===-1)continue;let U=W.slice(N+1);if(U)K.set(U,H)}return K}function ai6($,Z){let X=new Map;for(let{from:Q,to:Y}of Z){let G=Q===""?"":`${Q.replace(/\/+$/,"")}/`;for(let[J,K]of $){if(!J.startsWith(G))continue;let W=J.slice(G.length);if(!W)continue;let H=fZ(Y?`${Y}/${W}`:W);if(H)X.set(H,K)}}return X}function si6($,Z){let X=new Set;for(let G of $){let J=G.split("/");for(let K=1;K<J.length;K++)X.add(J.slice(0,K).join("/"))}let Q=[...Z].filter((G)=>!X.has(G)).sort((G,J)=>G.length-J.length),Y=[];for(let G of Q)if(!Y.some((J)=>G.startsWith(`${J}/`)))Y.push(G);return Y}function ei6($){return ii6("sha256").update($).digest("hex")}async function $n6($,Z,X){let Q=fX(),Y=Q?xY(Q,SN):new ZW(SN,X.baseUrl),G=new im($),J=new YW(Y,G,SN),K=zw(Z.set),W=ai6(await ri6(Z.repo,Z.ref),Z.paths),H=new Map((await G.listVolumeFiles(SN,K)).map((B)=>[B.path,B.contentHash]));if(W.size===0&&H.size>0)throw Error(`set "${Z.set}" resolved 0 files from ${Z.repo}@${Z.ref} `+`(check paths config) \u2014 refusing to delete the ${H.size} existing files`);let N=0;for(let B of H.keys()){if(W.has(B))continue;await J.delete(K,B,{actor:Jm0}),N++}let U=await G.listVolumeDirs(SN,K);for(let B of si6(W.keys(),U.map((L)=>L.path)))await J.delete(K,B,{actor:Jm0});let F=0,w=0;for(let[B,L]of W){if(H.get(B)===ei6(L)){w++;continue}await J.write(K,B,L,{actor:Jm0,contentType:VZ(B),skipVolumeQuota:!0}),F++}return{set:Z.set,written:F,deleted:N,unchanged:w}}async function Wm0($,Z,X){try{return await $n6($,Z,X)}catch(Q){return{set:Z.set,error:Q instanceof Error?Q.message:String(Q)}}}async function Fo1($,Z){let X=[];for(let Q of dG())X.push(await Wm0($,Q,Z));return X}var Jm0="system:skill-set-sync",I90=209715200,pi6=1073741824;var Hm0=O(()=>{Gm0();um();Gw();nK();sD();cm();Jb()});import{DBOS as q90,SchedulerMode as Zn6}from"@dbos-inc/dbos-sdk";function wo1($){Nm0=$}function Qn6(){if(!Nm0)throw Error("[org-fs] public-sets sync runtime not initialized \u2014 setPublicSetsSyncRuntime() must run before the workflow fires");return Nm0}async function Yn6($,Z){for(let X of dG()){let Q=await q90.runStep(()=>{let Y=Qn6();return Wm0(Y.db,X,{baseUrl:Y.baseUrl})},{name:`syncPublicSet:${X.set}`});if("error"in Q)console.warn(`[org-fs] public set "${Q.set}" sync failed: ${Q.error}`);else if(Q.written||Q.deleted)console.log(`[org-fs] public set "${Q.set}" synced: +${Q.written} -${Q.deleted} (=${Q.unchanged})`)}}function Bo1(){if(nm)return;nm=q90.registerWorkflow(Yn6,{name:"publicSetsSyncWorkflow"}),q90.registerScheduled(nm,{name:"publicSetsSyncWorkflow",crontab:Xn6,mode:Zn6.ExactlyOncePerIntervalWhenActive})}async function Oo1(){if(dG().length===0||!nm)return;let $=new Date,Z=`public-sets-sync-boot:${$.toISOString().slice(0,13)}`;await q90.startWorkflow(nm,{workflowID:Z})($,$)}var Xn6="4-59/10 * * * *",Nm0=null,nm=null;var Lo1=O(()=>{Jb();Hm0()});import{z as M8}from"zod";var Gn6,Jn6,Kn6,Wn6,Hn6,Nn6,Un6,Fn6,wn6,Bn6,On6,Ln6,$E;var pm=O(()=>{Gn6=M8.object({prefix:M8.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:M8.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:M8.string().optional().describe("Token for pagination from previous response"),delimiter:M8.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),Jn6=M8.object({objects:M8.array(M8.object({key:M8.string().describe("Object key/path"),size:M8.number().describe("Object size in bytes"),lastModified:M8.string().describe("Last modified timestamp"),etag:M8.string().describe("Entity tag for the object")})),nextContinuationToken:M8.string().optional().describe("Token for fetching next page of results"),isTruncated:M8.boolean().describe("Whether there are more results available"),commonPrefixes:M8.array(M8.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),Kn6=M8.object({key:M8.string().describe("Object key/path to get metadata for")}),Wn6=M8.object({contentType:M8.string().optional().describe("MIME type of the object"),contentLength:M8.number().describe("Size of the object in bytes"),lastModified:M8.string().describe("Last modified timestamp"),etag:M8.string().describe("Entity tag for the object"),metadata:M8.record(M8.string(),M8.string()).optional().describe("Custom metadata key-value pairs")}),Hn6=M8.object({key:M8.string().describe("Object key/path to generate URL for"),expiresIn:M8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),Nn6=M8.object({url:M8.string().describe("Presigned URL for downloading the object"),expiresIn:M8.number().describe("Expiration time in seconds that was used")}),Un6=M8.object({key:M8.string().describe("Object key/path for the upload"),expiresIn:M8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:M8.string().optional().describe("MIME type for the object being uploaded")}),Fn6=M8.object({url:M8.string().describe("Presigned URL for uploading the object"),expiresIn:M8.number().describe("Expiration time in seconds that was used")}),wn6=M8.object({key:M8.string().describe("Object key/path to delete")}),Bn6=M8.object({success:M8.boolean().describe("Whether the deletion was successful"),key:M8.string().describe("The key that was deleted")}),On6=M8.object({keys:M8.array(M8.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Ln6=M8.object({deleted:M8.array(M8.string()).describe("Array of successfully deleted keys"),errors:M8.array(M8.object({key:M8.string(),message:M8.string()})).describe("Array of errors for failed deletions")}),$E=[{name:"LIST_OBJECTS",inputSchema:Gn6,outputSchema:Jn6},{name:"GET_OBJECT_METADATA",inputSchema:Kn6,outputSchema:Wn6},{name:"GET_PRESIGNED_URL",inputSchema:Hn6,outputSchema:Nn6},{name:"PUT_PRESIGNED_URL",inputSchema:Un6,outputSchema:Fn6},{name:"DELETE_OBJECT",inputSchema:wn6,outputSchema:Bn6},{name:"DELETE_OBJECTS",inputSchema:On6,outputSchema:Ln6}]});import*as x from"zod/v4";function _o1($){if($.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${$.params.ref.type}`)}function xo1($){if($.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${$.params.ref.type}`)}var jw="2025-11-25",Do1="2025-03-26",Pw,Aw="io.modelcontextprotocol/related-task",k90="2.0",JZ,Eo1,zo1,i45,Dn6,En6,Um0,uY,tm,jo1=($)=>tm.safeParse($).success,W7,mG,iG,H7,S90,Po1,GW=($)=>Po1.safeParse($).success,Ao1,To1=($)=>Ao1.safeParse($).success,Fm0,LJ=($)=>Fm0.safeParse($).success,b1,wm0,Wb=($)=>wm0.safeParse($).success,cY,n45,VN,zn6,V90,jn6,om,Kb,Ro1,Pn6,An6,Tn6,Rn6,In6,qn6,C90,Bm0=($)=>C90.safeParse($).success,Mn6,Om0,_90,Io1=($)=>_90.safeParse($).success,x90,kn6,Sn6,v90,Vn6,rm,am,Cn6,sm,CN,_n6,em,f90,b90,y90,p45,g90,h90,u90,qo1,Mo1,ko1,Lm0,So1,$i,Hb,Vo1,xn6,Tw,Dm0,Rw,Em0,zm0,vn6,Nb,jm0,Pm0,fn6,bn6,yn6,gn6,hn6,un6,cn6,ln6,Iw,Am0,dn6,Ub,Tm0,Rm0,Im0,mn6,in6,nn6,qm0,pn6,Mm0,km0,tn6,on6,c90,Fb,Zi,JW,t45,rn6,qw,Sm0,Co1,Xi,an6,Vm0,sn6,en6,$p6,Zp6,Xp6,Qp6,Yp6,M90,Gp6,Jp6,Cm0,ZE,Qi,Kp6,Wp6,Hp6,Np6,Up6,Fp6,wp6,Bp6,Op6,Lp6,Dp6,Ep6,zp6,jp6,Pp6,_m0,Ap6,Tp6,Mw,Rp6,Ip6,qp6,l90,xm0,Mp6,kp6,vm0,Sp6,o45,r45,a45,s45,e45,$$5,S1,vo1;var Y9=O(()=>{Pw=[jw,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],JZ=x.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),Eo1=x.union([x.string(),x.number().int()]),zo1=x.string(),i45=x.looseObject({ttl:x.number().optional(),pollInterval:x.number().optional()}),Dn6=x.object({ttl:x.number().optional()}),En6=x.object({taskId:x.string()}),Um0=x.looseObject({progressToken:Eo1.optional(),[Aw]:En6.optional()}),uY=x.object({_meta:Um0.optional()}),tm=uY.extend({task:Dn6.optional()}),W7=x.object({method:x.string(),params:uY.loose().optional()}),mG=x.object({_meta:Um0.optional()}),iG=x.object({method:x.string(),params:mG.loose().optional()}),H7=x.looseObject({_meta:Um0.optional()}),S90=x.union([x.string(),x.number().int()]),Po1=x.object({jsonrpc:x.literal(k90),id:S90,...W7.shape}).strict(),Ao1=x.object({jsonrpc:x.literal(k90),...iG.shape}).strict(),Fm0=x.object({jsonrpc:x.literal(k90),id:S90,result:H7}).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={}));wm0=x.object({jsonrpc:x.literal(k90),id:S90.optional(),error:x.object({code:x.number().int(),message:x.string(),data:x.unknown().optional()})}).strict(),cY=x.union([Po1,Ao1,Fm0,wm0]),n45=x.union([Fm0,wm0]),VN=H7.strict(),zn6=mG.extend({requestId:S90.optional(),reason:x.string().optional()}),V90=iG.extend({method:x.literal("notifications/cancelled"),params:zn6}),jn6=x.object({src:x.string(),mimeType:x.string().optional(),sizes:x.array(x.string()).optional(),theme:x.enum(["light","dark"]).optional()}),om=x.object({icons:x.array(jn6).optional()}),Kb=x.object({name:x.string(),title:x.string().optional()}),Ro1=Kb.extend({...Kb.shape,...om.shape,version:x.string(),websiteUrl:x.string().optional(),description:x.string().optional()}),Pn6=x.intersection(x.object({applyDefaults:x.boolean().optional()}),x.record(x.string(),x.unknown())),An6=x.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},x.intersection(x.object({form:Pn6.optional(),url:JZ.optional()}),x.record(x.string(),x.unknown()).optional())),Tn6=x.looseObject({list:JZ.optional(),cancel:JZ.optional(),requests:x.looseObject({sampling:x.looseObject({createMessage:JZ.optional()}).optional(),elicitation:x.looseObject({create:JZ.optional()}).optional()}).optional()}),Rn6=x.looseObject({list:JZ.optional(),cancel:JZ.optional(),requests:x.looseObject({tools:x.looseObject({call:JZ.optional()}).optional()}).optional()}),In6=x.object({experimental:x.record(x.string(),JZ).optional(),sampling:x.object({context:JZ.optional(),tools:JZ.optional()}).optional(),elicitation:An6.optional(),roots:x.object({listChanged:x.boolean().optional()}).optional(),tasks:Tn6.optional(),extensions:x.record(x.string(),JZ).optional()}),qn6=uY.extend({protocolVersion:x.string(),capabilities:In6,clientInfo:Ro1}),C90=W7.extend({method:x.literal("initialize"),params:qn6}),Mn6=x.object({experimental:x.record(x.string(),JZ).optional(),logging:JZ.optional(),completions:JZ.optional(),prompts:x.object({listChanged:x.boolean().optional()}).optional(),resources:x.object({subscribe:x.boolean().optional(),listChanged:x.boolean().optional()}).optional(),tools:x.object({listChanged:x.boolean().optional()}).optional(),tasks:Rn6.optional(),extensions:x.record(x.string(),JZ).optional()}),Om0=H7.extend({protocolVersion:x.string(),capabilities:Mn6,serverInfo:Ro1,instructions:x.string().optional()}),_90=iG.extend({method:x.literal("notifications/initialized"),params:mG.optional()}),x90=W7.extend({method:x.literal("ping"),params:uY.optional()}),kn6=x.object({progress:x.number(),total:x.optional(x.number()),message:x.optional(x.string())}),Sn6=x.object({...mG.shape,...kn6.shape,progressToken:Eo1}),v90=iG.extend({method:x.literal("notifications/progress"),params:Sn6}),Vn6=uY.extend({cursor:zo1.optional()}),rm=W7.extend({params:Vn6.optional()}),am=H7.extend({nextCursor:zo1.optional()}),Cn6=x.enum(["working","input_required","completed","failed","cancelled"]),sm=x.object({taskId:x.string(),status:Cn6,ttl:x.union([x.number(),x.null()]),createdAt:x.string(),lastUpdatedAt:x.string(),pollInterval:x.optional(x.number()),statusMessage:x.optional(x.string())}),CN=H7.extend({task:sm}),_n6=mG.merge(sm),em=iG.extend({method:x.literal("notifications/tasks/status"),params:_n6}),f90=W7.extend({method:x.literal("tasks/get"),params:uY.extend({taskId:x.string()})}),b90=H7.merge(sm),y90=W7.extend({method:x.literal("tasks/result"),params:uY.extend({taskId:x.string()})}),p45=H7.loose(),g90=rm.extend({method:x.literal("tasks/list")}),h90=am.extend({tasks:x.array(sm)}),u90=W7.extend({method:x.literal("tasks/cancel"),params:uY.extend({taskId:x.string()})}),qo1=H7.merge(sm),Mo1=x.object({uri:x.string(),mimeType:x.optional(x.string()),_meta:x.record(x.string(),x.unknown()).optional()}),ko1=Mo1.extend({text:x.string()}),Lm0=x.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),So1=Mo1.extend({blob:Lm0}),$i=x.enum(["user","assistant"]),Hb=x.object({audience:x.array($i).optional(),priority:x.number().min(0).max(1).optional(),lastModified:x.iso.datetime({offset:!0}).optional()}),Vo1=x.object({...Kb.shape,...om.shape,uri:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string()),size:x.optional(x.number()),annotations:Hb.optional(),_meta:x.optional(x.looseObject({}))}),xn6=x.object({...Kb.shape,...om.shape,uriTemplate:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string()),annotations:Hb.optional(),_meta:x.optional(x.looseObject({}))}),Tw=rm.extend({method:x.literal("resources/list")}),Dm0=am.extend({resources:x.array(Vo1)}),Rw=rm.extend({method:x.literal("resources/templates/list")}),Em0=am.extend({resourceTemplates:x.array(xn6)}),zm0=uY.extend({uri:x.string()}),vn6=zm0,Nb=W7.extend({method:x.literal("resources/read"),params:vn6}),jm0=H7.extend({contents:x.array(x.union([ko1,So1]))}),Pm0=iG.extend({method:x.literal("notifications/resources/list_changed"),params:mG.optional()}),fn6=zm0,bn6=W7.extend({method:x.literal("resources/subscribe"),params:fn6}),yn6=zm0,gn6=W7.extend({method:x.literal("resources/unsubscribe"),params:yn6}),hn6=mG.extend({uri:x.string()}),un6=iG.extend({method:x.literal("notifications/resources/updated"),params:hn6}),cn6=x.object({name:x.string(),description:x.optional(x.string()),required:x.optional(x.boolean())}),ln6=x.object({...Kb.shape,...om.shape,description:x.optional(x.string()),arguments:x.optional(x.array(cn6)),_meta:x.optional(x.looseObject({}))}),Iw=rm.extend({method:x.literal("prompts/list")}),Am0=am.extend({prompts:x.array(ln6)}),dn6=uY.extend({name:x.string(),arguments:x.record(x.string(),x.string()).optional()}),Ub=W7.extend({method:x.literal("prompts/get"),params:dn6}),Tm0=x.object({type:x.literal("text"),text:x.string(),annotations:Hb.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),Rm0=x.object({type:x.literal("image"),data:Lm0,mimeType:x.string(),annotations:Hb.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),Im0=x.object({type:x.literal("audio"),data:Lm0,mimeType:x.string(),annotations:Hb.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),mn6=x.object({type:x.literal("tool_use"),name:x.string(),id:x.string(),input:x.record(x.string(),x.unknown()),_meta:x.record(x.string(),x.unknown()).optional()}),in6=x.object({type:x.literal("resource"),resource:x.union([ko1,So1]),annotations:Hb.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),nn6=Vo1.extend({type:x.literal("resource_link")}),qm0=x.union([Tm0,Rm0,Im0,nn6,in6]),pn6=x.object({role:$i,content:qm0}),Mm0=H7.extend({description:x.string().optional(),messages:x.array(pn6)}),km0=iG.extend({method:x.literal("notifications/prompts/list_changed"),params:mG.optional()}),tn6=x.object({title:x.string().optional(),readOnlyHint:x.boolean().optional(),destructiveHint:x.boolean().optional(),idempotentHint:x.boolean().optional(),openWorldHint:x.boolean().optional()}),on6=x.object({taskSupport:x.enum(["required","optional","forbidden"]).optional()}),c90=x.object({...Kb.shape,...om.shape,description:x.string().optional(),inputSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),JZ).optional(),required:x.array(x.string()).optional()}).catchall(x.unknown()),outputSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),JZ).optional(),required:x.array(x.string()).optional()}).catchall(x.unknown()).optional(),annotations:tn6.optional(),execution:on6.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),Fb=rm.extend({method:x.literal("tools/list")}),Zi=am.extend({tools:x.array(c90)}),JW=H7.extend({content:x.array(qm0).default([]),structuredContent:x.record(x.string(),x.unknown()).optional(),isError:x.boolean().optional()}),t45=JW.or(H7.extend({toolResult:x.unknown()})),rn6=tm.extend({name:x.string(),arguments:x.record(x.string(),x.unknown()).optional()}),qw=W7.extend({method:x.literal("tools/call"),params:rn6}),Sm0=iG.extend({method:x.literal("notifications/tools/list_changed"),params:mG.optional()}),Co1=x.object({autoRefresh:x.boolean().default(!0),debounceMs:x.number().int().nonnegative().default(300)}),Xi=x.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),an6=uY.extend({level:Xi}),Vm0=W7.extend({method:x.literal("logging/setLevel"),params:an6}),sn6=mG.extend({level:Xi,logger:x.string().optional(),data:x.unknown()}),en6=iG.extend({method:x.literal("notifications/message"),params:sn6}),$p6=x.object({name:x.string().optional()}),Zp6=x.object({hints:x.array($p6).optional(),costPriority:x.number().min(0).max(1).optional(),speedPriority:x.number().min(0).max(1).optional(),intelligencePriority:x.number().min(0).max(1).optional()}),Xp6=x.object({mode:x.enum(["auto","required","none"]).optional()}),Qp6=x.object({type:x.literal("tool_result"),toolUseId:x.string().describe("The unique identifier for the corresponding tool call."),content:x.array(qm0).default([]),structuredContent:x.object({}).loose().optional(),isError:x.boolean().optional(),_meta:x.record(x.string(),x.unknown()).optional()}),Yp6=x.discriminatedUnion("type",[Tm0,Rm0,Im0]),M90=x.discriminatedUnion("type",[Tm0,Rm0,Im0,mn6,Qp6]),Gp6=x.object({role:$i,content:x.union([M90,x.array(M90)]),_meta:x.record(x.string(),x.unknown()).optional()}),Jp6=tm.extend({messages:x.array(Gp6),modelPreferences:Zp6.optional(),systemPrompt:x.string().optional(),includeContext:x.enum(["none","thisServer","allServers"]).optional(),temperature:x.number().optional(),maxTokens:x.number().int(),stopSequences:x.array(x.string()).optional(),metadata:JZ.optional(),tools:x.array(c90).optional(),toolChoice:Xp6.optional()}),Cm0=W7.extend({method:x.literal("sampling/createMessage"),params:Jp6}),ZE=H7.extend({model:x.string(),stopReason:x.optional(x.enum(["endTurn","stopSequence","maxTokens"]).or(x.string())),role:$i,content:Yp6}),Qi=H7.extend({model:x.string(),stopReason:x.optional(x.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(x.string())),role:$i,content:x.union([M90,x.array(M90)])}),Kp6=x.object({type:x.literal("boolean"),title:x.string().optional(),description:x.string().optional(),default:x.boolean().optional()}),Wp6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),minLength:x.number().optional(),maxLength:x.number().optional(),format:x.enum(["email","uri","date","date-time"]).optional(),default:x.string().optional()}),Hp6=x.object({type:x.enum(["number","integer"]),title:x.string().optional(),description:x.string().optional(),minimum:x.number().optional(),maximum:x.number().optional(),default:x.number().optional()}),Np6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),enum:x.array(x.string()),default:x.string().optional()}),Up6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),oneOf:x.array(x.object({const:x.string(),title:x.string()})),default:x.string().optional()}),Fp6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),enum:x.array(x.string()),enumNames:x.array(x.string()).optional(),default:x.string().optional()}),wp6=x.union([Np6,Up6]),Bp6=x.object({type:x.literal("array"),title:x.string().optional(),description:x.string().optional(),minItems:x.number().optional(),maxItems:x.number().optional(),items:x.object({type:x.literal("string"),enum:x.array(x.string())}),default:x.array(x.string()).optional()}),Op6=x.object({type:x.literal("array"),title:x.string().optional(),description:x.string().optional(),minItems:x.number().optional(),maxItems:x.number().optional(),items:x.object({anyOf:x.array(x.object({const:x.string(),title:x.string()}))}),default:x.array(x.string()).optional()}),Lp6=x.union([Bp6,Op6]),Dp6=x.union([Fp6,wp6,Lp6]),Ep6=x.union([Dp6,Kp6,Wp6,Hp6]),zp6=tm.extend({mode:x.literal("form").optional(),message:x.string(),requestedSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),Ep6),required:x.array(x.string()).optional()})}),jp6=tm.extend({mode:x.literal("url"),message:x.string(),elicitationId:x.string(),url:x.string().url()}),Pp6=x.union([zp6,jp6]),_m0=W7.extend({method:x.literal("elicitation/create"),params:Pp6}),Ap6=mG.extend({elicitationId:x.string()}),Tp6=iG.extend({method:x.literal("notifications/elicitation/complete"),params:Ap6}),Mw=H7.extend({action:x.enum(["accept","decline","cancel"]),content:x.preprocess(($)=>$===null?void 0:$,x.record(x.string(),x.union([x.string(),x.number(),x.boolean(),x.array(x.string())])).optional())}),Rp6=x.object({type:x.literal("ref/resource"),uri:x.string()}),Ip6=x.object({type:x.literal("ref/prompt"),name:x.string()}),qp6=uY.extend({ref:x.union([Ip6,Rp6]),argument:x.object({name:x.string(),value:x.string()}),context:x.object({arguments:x.record(x.string(),x.string()).optional()}).optional()}),l90=W7.extend({method:x.literal("completion/complete"),params:qp6});xm0=H7.extend({completion:x.looseObject({values:x.array(x.string()).max(100),total:x.optional(x.number().int()),hasMore:x.optional(x.boolean())})}),Mp6=x.object({uri:x.string().startsWith("file://"),name:x.string().optional(),_meta:x.record(x.string(),x.unknown()).optional()}),kp6=W7.extend({method:x.literal("roots/list"),params:uY.optional()}),vm0=H7.extend({roots:x.array(Mp6)}),Sp6=iG.extend({method:x.literal("notifications/roots/list_changed"),params:mG.optional()}),o45=x.union([x90,C90,l90,Vm0,Ub,Iw,Tw,Rw,Nb,bn6,gn6,qw,Fb,f90,y90,g90,u90]),r45=x.union([V90,v90,_90,Sp6,em]),a45=x.union([VN,ZE,Qi,Mw,vm0,b90,h90,CN]),s45=x.union([x90,Cm0,_m0,kp6,f90,y90,g90,u90]),e45=x.union([V90,v90,en6,un6,Pm0,Sm0,km0,em,Tp6]),$$5=x.union([VN,Om0,xm0,Mm0,Am0,Dm0,Em0,jm0,JW,Zi,b90,h90,CN]);S1=class S1 extends Error{constructor($,Z,X){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=X,this.name="McpError"}static fromError($,Z,X){if($===b1.UrlElicitationRequired&&X){let Q=X;if(Q.elicitations)return new vo1(Q.elicitations,Z)}return new S1($,Z,X)}};vo1=class vo1 extends S1{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(b1.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});import{z as E8}from"zod";function KW($){return $!==null&&$!==void 0&&"command"in $}function wb($){if(!$||!$.startsWith("virtual://"))return null;return $.replace("virtual://","")}function Bb($){return`virtual://${$}`}var Vp6,fo1,Cp6,_p6,xp6,n7,d90,m90;var bo1=O(()=>{Y9();Vp6=E8.object({authorizationEndpoint:E8.string().url(),tokenEndpoint:E8.string().url(),introspectionEndpoint:E8.string().url().optional(),clientId:E8.string(),clientSecret:E8.string().optional(),scopes:E8.array(E8.string()),grantType:E8.enum(["authorization_code","client_credentials"])}),fo1=E8.object({type:E8.literal("object"),properties:E8.record(E8.string(),E8.unknown()).optional(),required:E8.array(E8.string()).optional()}).catchall(E8.unknown()),Cp6=c90.extend({inputSchema:fo1,outputSchema:fo1.optional()}),_p6=E8.object({headers:E8.record(E8.string(),E8.string()).optional()}),xp6=E8.object({command:E8.string().describe("Command to run (e.g., 'npx', 'node')"),args:E8.array(E8.string()).optional().describe("Command arguments"),cwd:E8.string().optional().describe("Working directory"),envVars:E8.record(E8.string(),E8.string()).optional().describe("Environment variables (encrypted in storage)")}),n7=E8.object({id:E8.string().describe("Unique identifier for the connection"),title:E8.string().describe("Human-readable name for the connection"),created_at:E8.string().describe("When the connection was created"),updated_at:E8.string().describe("When the connection was last updated"),created_by:E8.string().describe("User ID who created the connection"),updated_by:E8.string().optional().describe("User ID who last updated the connection"),organization_id:E8.string().describe("Organization ID this connection belongs to"),description:E8.string().nullable().describe("Description of the connection"),icon:E8.string().nullable().describe("Icon URL for the connection"),app_name:E8.string().nullable().describe("Associated app name"),app_id:E8.string().nullable().describe("Associated app ID"),slug:E8.string().nullable().optional().describe("URL-safe slug derived from app_name, connection_url, or title"),connection_type:E8.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:E8.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:E8.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:E8.union([xp6,_p6]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:Vp6.nullable().describe("OAuth configuration"),configuration_state:E8.record(E8.string(),E8.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:E8.array(E8.string()).nullable().optional().describe("Configuration scopes"),metadata:E8.record(E8.string(),E8.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:E8.array(Cp6).nullable().describe("Discovered tools from MCP"),bindings:E8.array(E8.string()).nullable().describe("Detected bindings"),status:E8.enum(["active","inactive","error"]).describe("Current status")}),d90=n7.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:E8.string().nullish()}),m90=n7.partial()});import{z as h0}from"zod";function bm0($){let Z=$?.homeTiles;if(Array.isArray(Z)&&Z.length>0)return Z;let X=$?.homeTile;return X?[X]:[]}function hm0($){return $==="cluster"?"agent-sandbox":$}function mo1($){let Z=hp6.parse($);return um0.parse({...Z,sandboxProviderKind:Z.sandboxProviderKind?hm0(Z.sandboxProviderKind):void 0})}function DJ($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z=$,X={};for(let[Q,Y]of Object.entries(Z)){if(!Y||typeof Y!=="object")continue;if(Q!=="cluster"&&Q!=="agent-sandbox"&&Q!=="user-desktop")continue;let G=hm0(Q);try{if(Q==="cluster"&&X[G])continue;X[G]=mo1(Y)}catch{}}return X}function cm0($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z={};for(let[X,Q]of Object.entries($)){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let Y={};for(let[G,J]of Object.entries(Q)){let K=DJ(J);if(Object.keys(K).length>0)Y[G]=K}if(Object.keys(Y).length>0)Z[X]=Y}return Z}var Yi,ho1,vp6,uo1,co1,yo1,fm0,i90,go1,fp6,lo1,bp6,ym0,gm0,yp6,gp6,do1,um0,hp6,n90,up6,lm0,cp6,dm0,mm0,p7,im0,p90,t90;var io1=O(()=>{Yi=h0.object({connection_id:h0.string().describe("Connection ID"),selected_tools:h0.array(h0.string()).nullable().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:h0.array(h0.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:h0.array(h0.string()).nullable().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),ho1=Yi.extend({selected_tools:Yi.shape.selected_tools.optional(),selected_resources:Yi.shape.selected_resources.optional(),selected_prompts:Yi.shape.selected_prompts.optional()}),vp6=h0.object({connectionId:h0.string(),toolName:h0.string(),label:h0.string(),icon:h0.string().nullable().optional()}),uo1=h0.object({id:h0.string().describe("Stable id; used as React key and ?tab= value"),title:h0.string().describe("Tab label"),icon:h0.string().optional().describe("Optional lucide icon name"),view:h0.object({type:h0.literal("ext-app"),appId:h0.string(),args:h0.record(h0.string(),h0.unknown()).optional()})}),co1=h0.object({defaultMainView:h0.object({type:h0.string(),id:h0.string().optional(),toolName:h0.string().optional()}).nullable().optional(),chatDefaultOpen:h0.boolean().nullable().optional(),cmsDefaultOpen:h0.boolean().nullable().optional(),tabs:h0.array(uo1).optional()}),yo1=h0.object({tileId:h0.string().optional(),connectionId:h0.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:h0.string().describe("ui:// resource URI exposed by `connectionId`. Read on the home page and rendered via MCPAppRenderer."),toolName:h0.string().optional().describe("Tool name \u2014 identifies which tool's inputSchema to display when editing tile props."),toolInput:h0.record(h0.string(),h0.unknown()).optional().describe("User-configured input props passed to MCPAppRenderer when rendering the tile."),minHeight:h0.number().int().positive().optional(),maxHeight:h0.number().int().positive().optional()}),fm0=h0.object({banner:h0.string().nullable().optional(),bannerColor:h0.string().nullable().optional(),icon:h0.string().nullable().optional(),themeColor:h0.string().nullable().optional(),pinnedViews:h0.array(vp6).nullable().optional(),layout:co1.nullable().optional(),homeTile:yo1.nullable().optional(),homeTiles:h0.array(yo1).nullable().optional(),homePrompts:h0.array(h0.string()).nullable().optional()});i90=/^[A-Za-z_][A-Za-z0-9_]*$/,go1=h0.string().min(1).regex(i90,{message:"Env var key must start with a letter or underscore and contain only letters, digits, and underscores."}),fp6=h0.discriminatedUnion("kind",[h0.object({key:go1,kind:h0.literal("literal"),value:h0.string()}),h0.object({key:go1,kind:h0.literal("secret"),secretId:h0.string().min(1)})]),lo1=/^[a-zA-Z0-9.-]+(?::[0-9]+)?$/,bp6=h0.object({host:h0.string().min(1).regex(lo1).describe("Submodule host, e.g. 'github.com' (bare hostname, no scheme)."),secretId:h0.string().min(1).describe("Vault secret id holding the PAT used to fetch this host.")}),ym0=h0.object({selected:h0.string().nullable().optional().describe("User-selected package manager (npm | pnpm | yarn | bun | deno). Null/absent means autodetect on next SANDBOX_START."),port:h0.string().nullable().optional().describe("User-selected dev server port as a string (allows '' / null for unset). Null/absent means autodetect."),path:h0.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:h0.array(fp6).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:h0.array(bp6).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.")}),gm0=h0.object({url:h0.string().describe("GitHub repository URL"),owner:h0.string().describe("Repository owner"),name:h0.string().describe("Repository name"),installationId:h0.number().optional().describe("GitHub App installation ID. Absent when the repo was linked without a GitHub connection (public-clone mode)."),connectionId:h0.string().optional().describe("ID of the mcp-github connection used for authentication. Absent for public repos cloned without credentials.")}),yp6=h0.enum(["agent-sandbox","user-desktop"]),gp6=h0.enum(["agent-sandbox","user-desktop","cluster"]);do1={sandboxHandle:h0.string().describe("Provider-specific handle"),previewUrl:h0.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:h0.string().nullable().optional().describe("Daemon's public URL \u2014 what cluster\u2192daemon RPCs target. Equal to previewUrl for user-desktop; null/absent for the agent-sandbox provider (routes through hosted ingress)."),sandboxProviderKind:yp6.optional(),createdAt:h0.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:h0.object({packageManager:h0.string().nullable().optional().describe("metadata.runtime.selected at the time of SANDBOX_START"),port:h0.string().nullable().optional().describe("metadata.runtime.port at the time of SANDBOX_START"),path:h0.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.")},um0=h0.object(do1),hp6=h0.object({...do1,sandboxProviderKind:gp6.optional()});n90=h0.record(h0.string().describe("userId"),h0.record(h0.string().describe("branch"),h0.record(h0.string().describe("sandboxProviderKind"),um0)));up6=h0.object({id:h0.string().describe("Stable identifier for this knowledge file"),name:h0.string().describe("File name shown in the UI"),kind:h0.enum(["file","skill"]).optional().describe("'file' (a single document) or 'skill' (a Claude Code skill folder containing SKILL.md). Defaults to 'file'."),volume:h0.string().describe("Org filesystem (Library) volume the file lives in"),path:h0.string().describe("Path within the volume"),url:h0.string().describe("Same-origin URL to read the file (display/download)"),contentType:h0.string().nullable().optional().describe("MIME type, used to decide whether to inline the content"),size:h0.number().nullable().optional().describe("File size in bytes"),addedAt:h0.string().describe("ISO timestamp when the file was attached")}),lm0=h0.array(up6).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."),cp6=h0.enum(["smart","code-review","open"]),dm0=cp6.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."),mm0=h0.boolean().nullable().optional().describe("Enable Fast Preview: render the draft instantly on productionUrl's own page via a ?__draft pointer while the sandbox boots. Requires productionUrl to be set to take effect."),p7=h0.object({id:h0.string().describe("Unique identifier"),title:h0.string().describe("Human-readable name"),description:h0.string().nullable().describe("Description"),icon:h0.string().nullable().describe("Icon URL"),created_at:h0.string().describe("Creation timestamp"),updated_at:h0.string().describe("Last update timestamp"),created_by:h0.string().describe("User ID who created this item"),updated_by:h0.string().optional().describe("User ID who last updated this item"),organization_id:h0.string().describe("Organization ID this item belongs to"),status:h0.enum(["active","inactive"]).describe("Current status"),pinned:h0.boolean().describe("Whether this space is pinned to the sidebar"),metadata:h0.object({instructions:h0.string().nullable().describe("Instructions also used as system prompt"),enabled_plugins:h0.array(h0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:h0.array(h0.string()).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:h0.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:fm0.nullable().optional().describe("UI customization settings"),githubRepo:gm0.nullable().optional().describe("Linked GitHub repository"),runtime:ym0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:n90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:lm0,siteSlug:h0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:dm0,productionUrl:h0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:h0.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:mm0}).loose().describe("Metadata"),connections:h0.array(Yi).describe("Connections with their selected tools, resources, and prompts")}),im0=h0.object({title:h0.string().min(1).max(120).describe("Short label shown on the chip"),description:h0.string().max(280).optional().describe("One-line subtitle shown under the title"),text:h0.string().min(1).describe("The message sent to the agent when the prompt is clicked")}),p90=h0.object({title:h0.string().min(1).max(255).describe("Name for the virtual MCP"),description:h0.string().nullable().optional().describe("Optional description"),icon:h0.string().nullish().describe("Optional icon URL"),status:h0.enum(["active","inactive"]).optional().default("active").describe("Initial status"),pinned:h0.boolean().optional().default(!1).describe("Pin to sidebar"),metadata:h0.object({instructions:h0.string().nullable().optional().describe("MCP server instructions"),enabled_plugins:h0.array(h0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:h0.array(h0.string()).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:h0.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:fm0.nullable().optional().describe("UI customization settings"),githubRepo:gm0.nullable().optional().describe("Linked GitHub repository"),runtime:ym0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:n90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:lm0,siteSlug:h0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:dm0,productionUrl:h0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:h0.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:mm0}).loose().nullable().optional().describe("Additional metadata including MCP server instructions"),connections:h0.array(ho1).describe("Connections to include/exclude (can be empty for exclusion mode)"),prompts:h0.array(im0).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.")}),t90=h0.object({title:h0.string().min(1).max(255).optional().describe("New name"),description:h0.string().nullable().optional().describe("New description (null to clear)"),icon:h0.string().nullish().describe("New icon URL"),status:h0.enum(["active","inactive"]).optional().describe("New status"),pinned:h0.boolean().optional().describe("Pin/unpin from sidebar"),metadata:h0.object({instructions:h0.string().nullable().optional().describe("MCP server instructions"),enabled_plugins:h0.array(h0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:h0.array(h0.string()).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:h0.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:fm0.nullable().optional().describe("UI customization settings"),githubRepo:gm0.nullable().optional().describe("Linked GitHub repository"),runtime:ym0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:n90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:lm0,siteSlug:h0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:dm0,productionUrl:h0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:h0.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:mm0}).loose().nullable().optional().describe("Additional metadata including MCP server instructions"),connections:h0.array(ho1).optional().describe("New connections (replaces existing)"),prompts:h0.array(im0).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 XE($){return lp6.has($)}var t7,lp6,o90;var no1=O(()=>{t7=["deco","anthropic","openrouter","llmapi","google","openai-compatible"],lp6=new Set(t7);o90=[...t7,"claude-code","codex"]});function nm0($,Z){return{id:crypto.randomUUID(),type:Gi.STEP,source:"decopilot",subject:$,data:{stepCount:Z},time:new Date().toISOString()}}function r90($,Z){return{id:crypto.randomUUID(),type:Gi.FINISH,source:"decopilot",subject:$,data:{status:Z},time:new Date().toISOString()}}function WW($,Z,X){return{id:crypto.randomUUID(),type:Gi.THREAD_STATUS,source:"decopilot",subject:$,data:{status:Z,...X?.messageId!==void 0&&{message_id:X.messageId},...X?.virtualMcpId!==void 0&&{virtual_mcp_id:X.virtualMcpId},...X?.createdBy!==void 0&&{created_by:X.createdBy},...X?.triggerId!==void 0&&{trigger_id:X.triggerId},...X?.title!==void 0&&{title:X.title},...X?.branch!==void 0&&{branch:X.branch},...X?.harnessId!==void 0&&{harness_id:X.harnessId},...X?.createdAt!==void 0&&{created_at:X.createdAt},...X?.updatedAt!==void 0&&{updated_at:X.updatedAt},...X?.metadata!==void 0&&{metadata:X.metadata}},time:new Date().toISOString()}}var po1,dp6,Gi,mp6;var to1=O(()=>{po1=["in_progress","requires_action","failed","completed"],dp6=[...po1,"expired"],Gi={STEP:"decopilot.step",FINISH:"decopilot.finish",THREAD_STATUS:"decopilot.thread.status"},mp6=Object.values(Gi)});var a90=O(()=>{bo1();io1();no1();to1()});function ro1($){return{id:t4.REGISTRY($),title:"Deco Store",description:"Official deco MCP registry with curated integrations",connection_type:"HTTP",connection_url:"https://studio.decocms.com/org/deco/registry/mcp",icon:"https://assets.decocache.com/decocms/00ccf6c3-9e13-4517-83b0-75ab84554bb9/596364c63320075ca58483660156b6d9de9b526e.png",app_name:"deco-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function ao1(){return{id:"community-registry",title:"MCP Registry",description:"Community MCP registry with thousands of handy MCPs",connection_type:"HTTP",connection_url:"https://sites-registry.deco.site/mcp",icon:"https://assets.decocache.com/decocms/cd7ca472-0f72-463a-b0de-6e44bdd0f9b4/mcp.png",app_name:"mcp-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function so1($,Z){return{id:t4.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 eo1($,Z){return{id:t4.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 lY($){return{is(Z){if(!Z)return null;if(!Z.startsWith($))return null;return Z.slice($.length)||null},get(Z){return`${$}${Z}`}}}function $r1($){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 tm0($){return $r1({id:QE($),organizationId:$,title:"Super Agent",description:"Default agent that aggregates all organization connections",icon:ip6,ui:{layout:{defaultMainView:{type:"overview"},chatDefaultOpen:!0}}})}function Gr1($){return $r1({id:np6($),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:pp6})}function Wr1($,Z,X="https://reports.decocms.com/api/v2/mcp"){return{id:t4.COMMERCE_DISCOVERY($),title:"Store Report",description:"Your store's report and diagnostics",connection_type:"HTTP",connection_url:X,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 Hr1($,Z=t4.COMMERCE_DISCOVERY($)){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:["get_my_diagnostic"],selected_resources:null,selected_prompts:null}]}}function Nr1($){if(!$)return!1;return Object.values(_N).some((Z)=>Z.is($)!==null)}function Ur1($){let Z=tm0($);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 t4,oo1="https://reports.decocms.com/api/v2/mcp",s90="get_my_diagnostic",Zr1,nG,QE,Xr1,Qr1,pm0,ip6="https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",Yr1,e90,np6,pp6,Jr1,O$5,L$5,Kr1,D$5,$Z0,_N,o7;var Fr1=O(()=>{t4={SELF:($)=>`${$}_self`,REGISTRY:($)=>`${$}_registry`,COMMUNITY_REGISTRY:($)=>`${$}_community-registry`,DEV_ASSETS:($)=>`${$}_dev-assets`,SITE_DIAGNOSTICS:($)=>`site-diagnostics_${$}`,COMMERCE_DISCOVERY:($)=>`${$}_commerce-discovery`};Zr1=lY("decopilot_"),nG=Zr1.is,QE=Zr1.get,Xr1=lY("dev_"),Qr1=Xr1.get,pm0=Xr1.is;Yr1=lY("brand-context-setup_"),e90=Yr1.is,np6=Yr1.get,pp6=`
|
|
1313
|
+
`:Q="\\n";break;case"\r":Q="\\r";break;case"\t":Q="\\t";break;default:}throw new Hm6.InvalidNameError(`${$} name ('${Z}') cannot contain '${Q}'`)}}),""}function Fm6($,Z=""){if(Z==="")throw Error(`${$} name required`);let X=Gt1(Z);if(X.length)throw Error(`invalid ${$} name - ${$} name ${X}`)}function Gt1($=""){if($==="")throw Error("name required");let Z=/^[-\w]+$/g;if($.match(Z)===null){for(let Q of $.split(""))if(Q.match(Z)===null)return`cannot contain '${Q}'`}return""}});var Cm=_((E6)=>{Object.defineProperty(E6,"__esModule",{value:!0});E6.wsconnect=E6.usernamePasswordAuthenticator=E6.UserAuthenticationExpiredError=E6.tokenAuthenticator=E6.TimeoutError=E6.syncIterator=E6.RequestError=E6.ProtocolError=E6.PermissionViolationError=E6.nuid=E6.Nuid=E6.NoRespondersError=E6.nkeys=E6.nkeyAuthenticator=E6.nanos=E6.MsgHdrsImpl=E6.millis=E6.Metric=E6.Match=E6.jwtAuthenticator=E6.InvalidSubjectError=E6.InvalidOperationError=E6.InvalidArgumentError=E6.headers=E6.hasWsProtocol=E6.errors=E6.Empty=E6.DrainingConnectionError=E6.delay=E6.deferred=E6.deadline=E6.credsAuthenticator=E6.createInbox=E6.ConnectionError=E6.ClosedConnectionError=E6.canonicalMIMEHeaderKey=E6.buildAuthenticator=E6.Bench=E6.backoff=E6.AuthorizationError=void 0;var f6=gY();Object.defineProperty(E6,"AuthorizationError",{enumerable:!0,get:function(){return f6.AuthorizationError}});Object.defineProperty(E6,"backoff",{enumerable:!0,get:function(){return f6.backoff}});Object.defineProperty(E6,"Bench",{enumerable:!0,get:function(){return f6.Bench}});Object.defineProperty(E6,"buildAuthenticator",{enumerable:!0,get:function(){return f6.buildAuthenticator}});Object.defineProperty(E6,"canonicalMIMEHeaderKey",{enumerable:!0,get:function(){return f6.canonicalMIMEHeaderKey}});Object.defineProperty(E6,"ClosedConnectionError",{enumerable:!0,get:function(){return f6.ClosedConnectionError}});Object.defineProperty(E6,"ConnectionError",{enumerable:!0,get:function(){return f6.ConnectionError}});Object.defineProperty(E6,"createInbox",{enumerable:!0,get:function(){return f6.createInbox}});Object.defineProperty(E6,"credsAuthenticator",{enumerable:!0,get:function(){return f6.credsAuthenticator}});Object.defineProperty(E6,"deadline",{enumerable:!0,get:function(){return f6.deadline}});Object.defineProperty(E6,"deferred",{enumerable:!0,get:function(){return f6.deferred}});Object.defineProperty(E6,"delay",{enumerable:!0,get:function(){return f6.delay}});Object.defineProperty(E6,"DrainingConnectionError",{enumerable:!0,get:function(){return f6.DrainingConnectionError}});Object.defineProperty(E6,"Empty",{enumerable:!0,get:function(){return f6.Empty}});Object.defineProperty(E6,"errors",{enumerable:!0,get:function(){return f6.errors}});Object.defineProperty(E6,"hasWsProtocol",{enumerable:!0,get:function(){return f6.hasWsProtocol}});Object.defineProperty(E6,"headers",{enumerable:!0,get:function(){return f6.headers}});Object.defineProperty(E6,"InvalidArgumentError",{enumerable:!0,get:function(){return f6.InvalidArgumentError}});Object.defineProperty(E6,"InvalidOperationError",{enumerable:!0,get:function(){return f6.InvalidOperationError}});Object.defineProperty(E6,"InvalidSubjectError",{enumerable:!0,get:function(){return f6.InvalidSubjectError}});Object.defineProperty(E6,"jwtAuthenticator",{enumerable:!0,get:function(){return f6.jwtAuthenticator}});Object.defineProperty(E6,"Match",{enumerable:!0,get:function(){return f6.Match}});Object.defineProperty(E6,"Metric",{enumerable:!0,get:function(){return f6.Metric}});Object.defineProperty(E6,"millis",{enumerable:!0,get:function(){return f6.millis}});Object.defineProperty(E6,"MsgHdrsImpl",{enumerable:!0,get:function(){return f6.MsgHdrsImpl}});Object.defineProperty(E6,"nanos",{enumerable:!0,get:function(){return f6.nanos}});Object.defineProperty(E6,"nkeyAuthenticator",{enumerable:!0,get:function(){return f6.nkeyAuthenticator}});Object.defineProperty(E6,"nkeys",{enumerable:!0,get:function(){return f6.nkeys}});Object.defineProperty(E6,"NoRespondersError",{enumerable:!0,get:function(){return f6.NoRespondersError}});Object.defineProperty(E6,"Nuid",{enumerable:!0,get:function(){return f6.Nuid}});Object.defineProperty(E6,"nuid",{enumerable:!0,get:function(){return f6.nuid}});Object.defineProperty(E6,"PermissionViolationError",{enumerable:!0,get:function(){return f6.PermissionViolationError}});Object.defineProperty(E6,"ProtocolError",{enumerable:!0,get:function(){return f6.ProtocolError}});Object.defineProperty(E6,"RequestError",{enumerable:!0,get:function(){return f6.RequestError}});Object.defineProperty(E6,"syncIterator",{enumerable:!0,get:function(){return f6.syncIterator}});Object.defineProperty(E6,"TimeoutError",{enumerable:!0,get:function(){return f6.TimeoutError}});Object.defineProperty(E6,"tokenAuthenticator",{enumerable:!0,get:function(){return f6.tokenAuthenticator}});Object.defineProperty(E6,"UserAuthenticationExpiredError",{enumerable:!0,get:function(){return f6.UserAuthenticationExpiredError}});Object.defineProperty(E6,"usernamePasswordAuthenticator",{enumerable:!0,get:function(){return f6.usernamePasswordAuthenticator}});Object.defineProperty(E6,"wsconnect",{enumerable:!0,get:function(){return f6.wsconnect}})});var tD=_((Kt1)=>{Object.defineProperty(Kt1,"__esModule",{value:!0});Kt1.PubHeaders=Kt1.PriorityPolicy=Kt1.ConsumerApiAction=Kt1.PersistMode=Kt1.StoreCompression=Kt1.ReplayPolicy=Kt1.AckPolicy=Kt1.DeliverPolicy=Kt1.StorageType=Kt1.DiscardPolicy=Kt1.RetentionPolicy=void 0;Kt1.defaultConsumer=jm6;var zm6=Cm();Kt1.RetentionPolicy={Limits:"limits",Interest:"interest",Workqueue:"workqueue"};Kt1.DiscardPolicy={Old:"old",New:"new"};Kt1.StorageType={File:"file",Memory:"memory"};Kt1.DeliverPolicy={All:"all",Last:"last",New:"new",StartSequence:"by_start_sequence",StartTime:"by_start_time",LastPerSubject:"last_per_subject"};Kt1.AckPolicy={None:"none",All:"all",Explicit:"explicit",FlowControl:"flow_control",NotSet:""};Kt1.ReplayPolicy={Instant:"instant",Original:"original"};Kt1.StoreCompression={None:"none",S2:"s2"};Kt1.PersistMode={Default:"default",Async:"async"};Kt1.ConsumerApiAction={CreateOrUpdate:"",Update:"update",Create:"create"};Kt1.PriorityPolicy={None:"none",Overflow:"overflow",PinnedClient:"pinned_client",Prioritized:"prioritized"};function jm6($,Z={}){return Object.assign({name:$,deliver_policy:Kt1.DeliverPolicy.All,ack_policy:Kt1.AckPolicy.Explicit,ack_wait:(0,zm6.nanos)(30000),replay_policy:Kt1.ReplayPolicy.Instant},Z)}Kt1.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 vd0=_((Bt1)=>{Object.defineProperty(Bt1,"__esModule",{value:!0});Bt1.ConsumerAPIImpl=void 0;var Sm6=ef(),Vm6=O90(),NJ=$b(),i7=gY(),qN=tD();class Ft1 extends Sm6.BaseApiClientImpl{constructor($,Z){super($,Z)}async addUpdate($,Z,X,Q){if((0,NJ.validateStreamName)($),X=X||{},Z.deliver_group&&Z.flow_control)throw i7.InvalidArgumentError.format(["flow_control","deliver_group"],"are mutually exclusive");if(Z.deliver_group&&Z.idle_heartbeat)throw i7.InvalidArgumentError.format(["idle_heartbeat","deliver_group"],"are mutually exclusive");if(wt1(Z)){let{min:w,ok:B}=this.nc.features.get(i7.Feature.JS_PRIORITY_GROUPS);if(!B)throw Error(`priority_groups require server ${w}`);if(Z.deliver_subject)throw i7.InvalidArgumentError.format("deliver_subject","cannot be set when using priority groups");Cm6(Z)}let Y={};if(Y.config=Z,Y.stream_name=$,Y.action=X.action||qN.ConsumerApiAction.Create,Y.pedantic=X.pedantic||!1,Y.config.durable_name)(0,NJ.validateDurableName)(Y.config.durable_name);let G=this.nc,{min:J,ok:K}=G.features.get(i7.Feature.JS_NEW_CONSUMER_CREATE_API),W=Z.name===""?void 0:Z.name;if(W&&!K)throw i7.InvalidArgumentError.format("name",`requires server ${J}`);if(W)try{(0,NJ.minValidation)("name",W)}catch(w){let B=w.message,L=B.indexOf("cannot contain");if(L!==-1)throw Error(`consumer 'name' ${B.substring(L)}`);throw w}let H,N="";if(Array.isArray(Z.filter_subjects)){let{min:w,ok:B}=G.features.get(i7.Feature.JS_MULTIPLE_CONSUMER_FILTER);if(!B)throw i7.InvalidArgumentError.format("filter_subjects",`requires server ${w}`);K=!1}if(Z.metadata){let{min:w,ok:B}=G.features.get(i7.Feature.JS_STREAM_CONSUMER_METADATA);if(!B)throw i7.InvalidArgumentError.format("metadata",`requires server ${w}`)}if(K)N=Z.name??Z.durable_name??"";if(N!==""){let w=Z.filter_subject??void 0;if(w===">")w=void 0;H=w!==void 0?`${this.prefix}.CONSUMER.CREATE.${$}.${N}.${w}`:`${this.prefix}.CONSUMER.CREATE.${$}.${N}`}else H=Z.durable_name?`${this.prefix}.CONSUMER.DURABLE.CREATE.${$}.${Z.durable_name}`:`${this.prefix}.CONSUMER.CREATE.${$}`;let U=Q??Y.config;return await this._request(H,Y,{...X,...this.requiredApiOpts(U)})}minConsumerApi($){if($.ack_policy===qN.AckPolicy.FlowControl)return 4;if(typeof $.pause_until==="string"&&$.pause_until!=="")return 1;if($.priority_policy!==void 0&&$.priority_policy!==qN.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,X){X=X||{};let Q=qN.ConsumerApiAction.Create;if(typeof X==="string")Q=X,X={};let Y=Object.assign({},{action:Q},X);return this.addUpdate($,Z,Y)}async update($,Z,X){let Q=await this.info($,Z),Y=X;return this.addUpdate($,Object.assign(Q.config,Y),{action:qN.ConsumerApiAction.Update},Y)}async info($,Z){return(0,NJ.validateStreamName)($),(0,NJ.validateDurableName)(Z),await this._request(`${this.prefix}.CONSUMER.INFO.${$}.${Z}`)}async delete($,Z){return(0,NJ.validateStreamName)($),(0,NJ.validateDurableName)(Z),(await this._request(`${this.prefix}.CONSUMER.DELETE.${$}.${Z}`)).success}list($){(0,NJ.validateStreamName)($);let Z=(Q)=>{return Q.consumers},X=`${this.prefix}.CONSUMER.LIST.${$}`;return new Vm6.ListerImpl(X,Z,this)}pause($,Z,X){let Q=`${this.prefix}.CONSUMER.PAUSE.${$}.${Z}`,Y={pause_until:X.toISOString()};return this._request(Q,Y)}resume($,Z){return this.pause($,Z,new Date(0))}unpin($,Z,X){let Q=`${this.prefix}.CONSUMER.UNPIN.${$}.${Z}`;return this._request(Q,{group:X})}async reset($,Z,X){(0,NJ.validateStreamName)($),(0,NJ.validateDurableName)(Z);let Q=this.nc,{min:Y,ok:G}=Q.features.get(i7.Feature.JS_CONSUMER_RESET);if(!G)throw Error(`consumer reset requires server ${Y}`);if(typeof X==="number"&&(!Number.isInteger(X)||X<0))throw i7.InvalidArgumentError.format("seq","must be a non-negative integer");let J=`${this.prefix}.CONSUMER.RESET.${$}.${Z}`,K=typeof X==="number"?{seq:X}:void 0;return await this._request(J,K)}}Bt1.ConsumerAPIImpl=Ft1;function wt1($){let Z=$;return Z&&Z.priority_groups!==void 0||Z.priority_policy!==void 0}function Cm6($){if(wt1($)){if(!Array.isArray($.priority_groups))throw i7.InvalidArgumentError.format(["priority_groups"],"must be an array");if($.priority_groups.length===0)throw i7.InvalidArgumentError.format(["priority_groups"],"must have at least one group");if($.priority_groups.forEach((Z)=>{if((0,NJ.minValidation)("priority_group",Z),Z.length>16)throw i7.errors.InvalidArgumentError.format("group","must be 16 characters or less")}),$.priority_policy!==qN.PriorityPolicy.None&&$.priority_policy!==qN.PriorityPolicy.Overflow&&$.priority_policy!==qN.PriorityPolicy.PinnedClient&&$.priority_policy!==qN.PriorityPolicy.Prioritized)throw i7.InvalidArgumentError.format(["priority_policy"],"must be 'none', 'prioritized', 'overflow', or 'pinned_client'")}}});var yd0=_((Dt1)=>{Object.defineProperty(Dt1,"__esModule",{value:!0});Dt1.JsMsgImpl=Dt1.ACK=void 0;Dt1.toJsMsg=bm6;Dt1.parseInfo=Lt1;var Zb=gY();Dt1.ACK=Uint8Array.of(43,65,67,75);var _m6=Uint8Array.of(45,78,65,75),_m=Uint8Array.of(43,87,80,73),xm6=Uint8Array.of(43,78,88,84),vm6=Uint8Array.of(43,84,69,82,77),fm6=Uint8Array.of(32);function bm6($,Z=5000){return new bd0($,Z)}function Lt1($){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 X={};return X.domain=Z[2]==="_"?"":Z[2],X.account_hash=Z[3],X.stream=Z[4],X.consumer=Z[5],X.deliveryCount=parseInt(Z[6],10),X.redelivered=X.deliveryCount>1,X.streamSequence=parseInt(Z[7],10),X.deliverySequence=parseInt(Z[8],10),X.timestampNanos=parseInt(Z[9],10),X.pending=parseInt(Z[10],10),X}function ym6($){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 bd0{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=Lt1(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,Zb.millis)(this.info.timestampNanos);return new Date($)}get timestamp(){return this.time.toISOString()}get timestampNanos(){return ym6(this.reply)}doAck($){if(!this.didAck)this.didAck=!this.isWIP($),this.msg.respond($)}isWIP($){return $.length===4&&$[0]===_m[0]&&$[1]===_m[1]&&$[2]===_m[2]&&$[3]===_m[3]}async ackAck($){let Z=(0,Zb.deferred)();if(!this.didAck)if(this.didAck=!0,this.msg.reply){$=$||{},$.timeout=$.timeout||this.timeout;let Q=this.msg.publisher,Y=!Q.options?.noAsyncTraces,G=new Zb.RequestOne(Q.muxSubscriptions,this.msg.reply,{timeout:$.timeout},Y);Q.request(G);try{Q.publish(this.msg.reply,Dt1.ACK,{reply:`${Q.muxSubscriptions.baseInbox}${G.token}`})}catch(J){G.cancel(J)}try{await Promise.race([G.timer,G.deferred]),Z.resolve(!0)}catch(J){G.cancel(J),Z.reject(J)}}else Z.resolve(!1);else Z.resolve(!1);return Z}ack(){this.doAck(Dt1.ACK)}nak($){let Z=_m6;if($)Z=new TextEncoder().encode(`-NAK ${JSON.stringify({delay:(0,Zb.nanos)($)})}`);this.doAck(Z)}working(){this.doAck(_m)}next($,Z={batch:1}){let X={};if(X.batch=Z.batch||1,X.no_wait=Z.no_wait||!1,Z.expires&&Z.expires>0)X.expires=(0,Zb.nanos)(Z.expires);let Q=new TextEncoder().encode(JSON.stringify(X)),Y=Zb.DataBuffer.concat(xm6,fm6,Q),G=$?{reply:$}:void 0;this.msg.respond(Y,G)}term($=""){let Z=vm6;if($?.length>0)Z=new TextEncoder().encode(`+TERM ${$}`);this.doAck(Z)}json(){return this.msg.json()}string(){return this.msg.string()}}Dt1.JsMsgImpl=bd0});var Mt1=_((It1)=>{Object.defineProperty(It1,"__esModule",{value:!0});It1.PullConsumerImpl=It1.PullConsumerMessagesImpl=It1.PullConsumerType=void 0;It1.isOverflowOptions=xm;It1.isPrioritizedOptions=L90;It1.validateOverflowPullOptions=Tt1;It1.validatePrioritizedPullOptions=Rt1;var L$=gY(),um6=yd0(),zt1=tD(),jt1=RN(),Pt1=$b();It1.PullConsumerType={Unset:"",Consume:"consume",Fetch:"fetch"};function xm($){let Z=$;return Z&&typeof Z.group==="string"||typeof Z.min_pending==="number"||typeof Z.min_ack_pending==="number"}function L90($){let Z=$;return Z&&typeof Z.group==="string"&&typeof Z.priority==="number"}class D90 extends L$.QueuedIteratorImpl{consumer;opts;sub;monitor;pending;isConsume;callback;listeners;statusIterator;abortOnMissingResource;bind;inboxPrefix;inbox;cancelables;inReset;closeListener;isPinned;isPriority;natsPinId;constructor($,Z,X=!1){super();if(this.consumer=$,this.isConsume=X,this.cancelables=[],this.inboxPrefix=(0,L$.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(xm(Z))throw L$.errors.InvalidArgumentError.format(["group","min_pending","min_ack_pending"],"cannot be specified for ordered consumers");if(this.consumer.orderedConsumerState===void 0){let Y={},G=$.opts;Y.namePrefix=G.name_prefix??`oc_${L$.nuid.next()}`,Y.opts=G,Y.cursor={stream_seq:1,deliver_seq:0};let J=$._info.config.opt_start_seq||0;Y.cursor.stream_seq=J>0?J-1:0,Y.createFails=0,this.consumer.orderedConsumerState=Y}}let Q=Z;if(this.opts=this.parseOptions(Z,this.isConsume),this.callback=Q.callback||null,this.noIterator=typeof this.callback==="function",this.monitor=null,this.pending={msgs:0,bytes:0,requests:0},this.listeners=[],this.abortOnMissingResource=Q.abort_on_missing_resource===!0,this.bind=Q.bind===!0,Q.group){let{min_pending:Y,min_ack_pending:G}=Q;this.isPinned=Y===void 0&&G===void 0;let{priority:J}=Q;this.isPriority=typeof J==="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:X,threshold_bytes:Q,threshold_messages:Y}=this.opts;if(this.sub=this.consumer.api.nc.subscribe(this.inbox,{callback:(G,J)=>{if(G){this.stop(G);return}if(this.monitor?.work(),this.consumer.ordered?J.subject.indexOf(this?.inboxPrefix)===0:J.subject===this.inbox){if(J.subject!==this.sub.getSubject())return;let W=new jt1.JetStreamStatus(J),H=W.parseHeartbeat();if(H){this.notify(H);return}let{code:N,description:U}=W,{msgsLeft:F,bytesLeft:w}=W.parseDiscard();if(F&&F>0||w&&w>0)this.pending.msgs-=F,this.pending.bytes-=w,this.pending.requests--,this.notify({type:"discard",messagesLeft:F,bytesLeft:w});switch(N){case 400:this.stop(W.toError());return;case 409:{let B=this.handle409(W);if(B){this.stop(B);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:N}),this.consumer.ordered){let B=this.consumer.orderedConsumerState;B.needsReset=!0}if(!this.isConsume){this.stop(W.toError());return}break;default:this.notify({type:"debug",code:N,description:U})}}else{let W=(0,um6.toJsMsg)(J,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,N=W.info.deliverySequence,U=W.info.streamSequence,F=H.deliver_seq+1;if(N!==F){this.reset();return}H.deliver_seq=N,H.stream_seq=U}if(this._push(W),this.received++,this.pending.msgs)this.pending.msgs--;if(this.pending.bytes)this.pending.bytes-=J.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<=Q){let W=this.pullOptions();this.pull(W)}}else if(this.pending.requests===0)this._push(()=>{this.stop()})}}),X)this.monitor=new L$.IdleHeartbeatMonitor(X,(G)=>{if(this.notify({type:"heartbeats_missed",count:G}),!this.isConsume&&!this.consumer.ordered)return this.stop(new jt1.JetStreamError("heartbeats missed")),!0;return this.resetPending().then(()=>{}).catch(()=>{}),!1},{maxOut:2});(async()=>{let G=this.consumer.api.nc.status();this.statusIterator=G;for await(let J of G)switch(J.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:X}=$;if($.isConsumerDeleted())this.notify({type:"consumer_deleted",code:Z,description:X});else if($.isExceededLimit())this.notify({type:"exceeded_limits",code:Z,description:X});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 X=this.consumer.getConsumerOpts();this.inbox=`${this.inboxPrefix}.${this.consumer.serial}`,$.cursor.deliver_seq=0,this.consumer.name=X.name,this.consumer.api.nc._resub(this.sub,this.inbox),this.consumer.api.add(this.consumer.stream,X).then((Q)=>{$.createFails=0,this.consumer._info=Q,this.notify({type:"ordered_consumer_recreated",name:Q.name}),this.monitor?.restart(),this.pull(this.pullOptions())}).catch((Q)=>{if($.createFails++,Q.message==="stream not found"){if(this.notify({type:"stream_not_found",consumerCreateFails:$.createFails,name:this.consumer.stream}),this.abortOnMissingResource){this.stop(Q);return}}if($.createFails>=30&&this.received===0)this.stop(Q);let Y=(0,L$.backoff)(),G=(0,L$.delay)(Y.backoff($.createFails));G.then(()=>{let J=this.cancelables.indexOf(G);if(J!==-1)this.cancelables=this.cancelables.splice(J,J);if(!this.done)this.reset()}).catch((J)=>{}),this.cancelables.push(G)})}_push($){if(!this.callback)super.push($);else{let Z=typeof $==="function"?$:null;try{if(!Z){let X=$;this.callback(X)}else Z()}catch(X){this.stop(X)}}}notify($){if(this.listeners.length>0)(()=>{this.listeners.forEach((Z)=>{let X=Z;if(!X.done)X.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,X=(0,L$.backoff)([this.opts.expires||30000]),Q=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 L$.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 G=X.backoff(Q),J=(0,L$.delay)(G);await Promise.race([J,this.consumer.api.nc.closed()]),J.cancel(),Q++}}}pull($){this.pending.bytes+=$.max_bytes??0,this.pending.msgs+=$.batch??0,this.pending.requests++;let Z=this.consumer.api.nc,X=`${this.consumer.api.prefix}.CONSUMER.MSG.NEXT.${this.consumer.stream}.${this.consumer._info.name}`;this._push(()=>{Z.publish(X,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,X=(0,L$.nanos)(this.opts.idle_heartbeat),Q=(0,L$.nanos)(this.opts.expires),Y={batch:$,max_bytes:Z,idle_heartbeat:X,expires:Q};if(this.isPinned&&this.natsPinId!=="")Y.id=this.natsPinId;if(xm(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(L90(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 X=$||{};if(X.max_messages=X.max_messages||0,X.max_bytes=X.max_bytes||0,X.max_messages!==0&&X.max_bytes!==0)throw L$.errors.InvalidArgumentError.format(["max_messages","max_bytes"],"are mutually exclusive");if(X.max_messages===0)X.max_messages=100;if(X.expires=X.expires||30000,X.expires<1000)throw L$.errors.InvalidArgumentError.format("expires","must be at least 1000ms");if(X.idle_heartbeat=X.idle_heartbeat||X.expires/2,X.idle_heartbeat=X.idle_heartbeat>30000?30000:X.idle_heartbeat,X.idle_heartbeat<500)X.idle_heartbeat=500;if(Z){let Q=Math.round(X.max_messages*0.75)||1;X.threshold_messages=X.threshold_messages||Q;let Y=Math.round(X.max_bytes*0.75)||1;X.threshold_bytes=X.threshold_bytes||Y}if(xm($)){let{min:Q,ok:Y}=this.consumer.api.nc.features.get(L$.Feature.JS_PRIORITY_GROUPS);if(!Y)throw Error(`priority_groups require server ${Q}`);if(Tt1($),$.group)X.group=$.group;if($.min_ack_pending)X.min_ack_pending=$.min_ack_pending;if($.min_pending)X.min_pending=$.min_pending}else if(L90($)){if(Rt1($),$.group)X.group=$.group;if(typeof $.priority==="number")X.priority=$.priority}return X}status(){let $=new L$.QueuedIteratorImpl;return this.listeners.push($),$}}It1.PullConsumerMessagesImpl=D90;class At1{api;_info;stream;name;opts;type;messages;ordered;serial;orderedConsumerState;constructor($,Z,X=null){this.api=$,this._info=Z,this.name=Z.name,this.stream=Z.stream_name,this.ordered=X!==null,this.opts=X||{},this.serial=1,this.type=It1.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(L$.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===It1.PullConsumerType.Fetch)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer initialized as fetch"));if(this.type===It1.PullConsumerType.Consume)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer doesn't support concurrent consume"));this.type=It1.PullConsumerType.Consume}return Promise.resolve(new D90(this,$,!0))}async fetch($={max_messages:100,expires:30000}){if($={...$},this.ordered){if($.group)return Promise.reject(L$.errors.InvalidArgumentError.format("group","ordered consumers don't support priority groups"));if($.bind)return Promise.reject(L$.errors.InvalidArgumentError.format("bind","is not supported"));if(this.type===It1.PullConsumerType.Consume)return Promise.reject(new L$.errors.InvalidOperationError("ordered consumer already initialized as consume"));if(this.messages?.done===!1)return Promise.reject(new L$.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=It1.PullConsumerType.Fetch}let Z=new D90(this,$);if(this.ordered)this.messages=Z;return Promise.resolve(Z)}async next($={expires:30000}){$={...$};let Z=$;Z.max_messages=1;let X=await this.fetch(Z);try{for await(let Q of X)return Q}catch(Q){return Promise.reject(Q)}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:zt1.DeliverPolicy.StartSequence,opt_start_seq:$.cursor.stream_seq+1,ack_policy:zt1.AckPolicy.None,inactive_threshold:(0,L$.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:X}=this._info;return this._info=await this.api.info(Z,X),this._info}}It1.PullConsumerImpl=At1;function Tt1($){if(xm($)){if((0,Pt1.minValidation)("group",$.group),$.group.length>16)throw L$.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{min_pending:Z,min_ack_pending:X}=$;if(Z&&typeof Z!=="number")throw L$.errors.InvalidArgumentError.format(["min_pending"],"must be a number");if(X&&typeof X!=="number")throw L$.errors.InvalidArgumentError.format(["min_ack_pending"],"must be a number")}}function Rt1($){if(L90($)){if((0,Pt1.minValidation)("group",$.group),$.group.length>16)throw L$.errors.InvalidArgumentError.format("group","must be 16 characters or less");let{priority:Z}=$;if(Z&&typeof Z!=="number")throw L$.errors.InvalidArgumentError.format(["priority"],"must be a number")}}});var _t1=_((Vt1)=>{Object.defineProperty(Vt1,"__esModule",{value:!0});Vt1.PushConsumerImpl=Vt1.PushConsumerMessagesImpl=void 0;var nm6=yd0(),kt1=tD(),gd0=uD(),yX=gY(),pm6=RN();class hd0 extends yX.QueuedIteratorImpl{consumer;sub;monitor;listeners;abortOnMissingResource;callback;ordered;cursor;namePrefix;deliverPrefix;serial;createFails;statusIterator;cancelables;constructor($,Z={},X={}){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=X.ordered===!0,this.serial=1,this.ordered){this.namePrefix=X.name_prefix??`oc_${yX.nuid.next()}`,this.deliverPrefix=X.deliver_prefix??(0,yX.createInbox)(this.consumer.api.nc.options.inboxPrefix),this.cursor={stream_seq:1,deliver_seq:0};let Q=$._info.config.opt_start_seq||0;this.cursor.stream_seq=Q>0?Q-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((X)=>{this.createFails=0,this.consumer._info=X,this.notify({type:"ordered_consumer_recreated",name:X.name})}).catch((X)=>{if(this.createFails++,X.message==="stream not found"){if(this.notify({type:"stream_not_found",name:this.consumer.stream,consumerCreateFails:this.createFails}),this.abortOnMissingResource){this.stop(X);return}}if(this.createFails>=30&&this.received===0)this.stop(X);let Q=(0,yX.backoff)(),Y=(0,yX.delay)(Q.backoff(this.createFails));Y.then(()=>{if(!this.done)this.reset()}).catch(()=>{}).finally(()=>{let G=this.cancelables.indexOf(Y);if(G!==-1)this.cancelables=this.cancelables.splice(G,G)}),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:kt1.DeliverPolicy.StartSequence,opt_start_seq:this.cursor.stream_seq+1,ack_policy:kt1.AckPolicy.None,inactive_threshold:(0,yX.nanos)(300000),num_replicas:1,flow_control:!0,idle_heartbeat:(0,yX.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 X=$;this.received++,this.callback(X),this.processed++}else Z()}catch(X){this.stop(X)}}}status(){let $=new yX.QueuedIteratorImpl;return this.listeners.push($),$}start(){let{deliver_subject:$,deliver_group:Z,idle_heartbeat:X}=this.consumer._info.config;if(!$)throw Error("bad consumer info");if(X){let Q=(0,yX.millis)(X);this.monitor=new yX.IdleHeartbeatMonitor(Q,(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:(Q,Y)=>{if(Q){this.stop(Q);return}if(this.monitor?.work(),this.ordered?Y.subject.indexOf(this?.deliverPrefix)===0:Y.subject===$){if(Y.subject!==this.sub.getSubject())return;let J=new pm6.JetStreamStatus(Y);if(J.isFlowControlRequest()){this._push(()=>{Y.respond(),this.notify({type:"flow_control"})});return}if(J.isIdleHeartbeat()){let H=parseInt(Y.headers?.get(gd0.JsHeaders.LastConsumerSeqHdr)||"0"),N=parseInt(Y.headers?.get(gd0.JsHeaders.LastStreamSeqHdr)??"0");this.notify({type:"heartbeat",lastStreamSequence:N,lastConsumerSequence:H});let U=Y.headers?.get(gd0.JsHeaders.ConsumerStalledHdr);if(typeof U==="string"&&U!=="")Y.publisher.publish(U,yX.Empty);return}let{code:K,description:W}=J;if(J.isConsumerDeleted())this.notify({type:"consumer_deleted",code:K,description:W});if(this.abortOnMissingResource){this._push(()=>{this.stop(J.toError())});return}}else{let J=(0,nm6.toJsMsg)(Y);if(this.ordered){let K=J.info.deliverySequence;if(K!==this.cursor.deliver_seq+1){this.reset();return}this.cursor.deliver_seq=K,this.cursor.stream_seq=J.info.streamSequence}this._push(J)}}}),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 X=Z;if(!X.done)X.push($)})})()}}Vt1.PushConsumerMessagesImpl=hd0;class St1{api;_info;stream;name;bound;ordered;started;serial;opts;constructor($,Z,X={}){if(this.api=$,this._info=Z,this.stream=Z.stream_name,this.name=Z.name,this.bound=X.bound===!0,this.started=!1,this.opts=X,this.serial=0,this.ordered=X.ordered||!1,this.ordered)this.serial=1}consume($={}){if($={...$},this.started)return Promise.reject(new yX.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 yX.errors.InvalidOperationError("consumer is already bound"));let Z=new hd0(this,$,this.opts);return this.started=!0,Z.closed().then(()=>{this.started=!1}),Promise.resolve(Z)}delete(){if(this.bound)return Promise.reject(new yX.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 yX.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}}Vt1.PushConsumerImpl=St1});var ht1=_((yt1)=>{Object.defineProperty(yt1,"__esModule",{value:!0});yt1.StreamsImpl=yt1.StoredMsgImpl=yt1.StreamAPIImpl=yt1.StreamImpl=yt1.ConsumersImpl=void 0;yt1.convertStreamSourceDomain=vm;var z9=gY(),om6=ef(),xt1=O90(),UJ=$b(),vt1=uD(),hY=tD(),ud0=Mt1(),cd0=vd0(),ld0=_t1(),ft1=RN();function vm($){if($===void 0)return;let{domain:Z}=$;if(Z===void 0)return $;let X=Object.assign({},$);if(delete X.domain,Z==="")return X;if(X.external)throw z9.InvalidArgumentError.format(["domain","external"],"are mutually exclusive");return X.external={api:`$JS.${Z}.API`},X}class E90{api;notified;constructor($){this.api=$,this.notified=!1}checkVersion(){let $=this.api.nc.features.get(z9.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,UJ.minValidation)("stream",$),typeof Z==="string"){(0,UJ.minValidation)("name",Z);let X=await this.api.info($,Z);if(typeof X.config.deliver_subject!=="string")return Promise.reject(Error("not a push consumer"));return new ld0.PushConsumerImpl(this.api,X)}else if(Z===void 0)return this.getOrderedPushConsumer($);else if((0,vt1.isOrderedPushConsumerOptions)(Z)){let X=Z;return this.getOrderedPushConsumer($,X)}return Promise.reject(Error("unsupported push consumer type"))}async getOrderedPushConsumer($,Z={}){Z=Object.assign({},Z);let{name_prefix:X,deliver_prefix:Q,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=hY.DeliverPolicy.StartSequence;if(typeof Z.opt_start_time==="string")Z.deliver_policy=hY.DeliverPolicy.StartTime;X=X||`oc_${z9.nuid.next()}`,(0,UJ.minValidation)("name_prefix",X),Q=Q||(0,z9.createInbox)(this.api.getOptions().watcherPrefix);let G=Object.assign({},Z);if(G.ack_policy=hY.AckPolicy.None,G.inactive_threshold=(0,z9.nanos)(300000),G.num_replicas=1,G.max_deliver=1,G.flow_control=!0,G.idle_heartbeat=(0,z9.nanos)(30000),Array.isArray(Y))G.filter_subjects=Y;if(typeof Y==="string")G.filter_subject=Y;if(typeof G.filter_subjects>"u"&&typeof G.filter_subject>"u")G.filter_subject=">";G.name=`${X}_1`,G.deliver_subject=`${Q}.1`;let J=await this.api.add($,G),K={name_prefix:X,deliver_prefix:Q,ordered:!0};return new ld0.PushConsumerImpl(this.api,J,K)}getBoundPushConsumer($){if((0,vt1.isBoundPushConsumerOptions)($)){let Z={config:$};return Promise.resolve(new ld0.PushConsumerImpl(this.api,Z,{bound:!0}))}else return Promise.reject(z9.errors.InvalidArgumentError.format("deliver_subject","is required"))}async get($,Z){if(await this.checkVersion(),typeof Z==="string"){let X=await this.api.info($,Z);if(typeof X.config.deliver_subject==="string")return Promise.reject(Error("not a pull consumer"));else return new ud0.PullConsumerImpl(this.api,X)}else return this.ordered($,Z)}getConsumerFromInfo($){if(typeof $.config.deliver_subject==="string")throw Error("not a pull consumer");return new ud0.PullConsumerImpl(this.api,$)}async ordered($,Z={}){await this.checkVersion();let X=this.api;if(await new dd0(X.nc,X.opts).info($),typeof Z.name_prefix==="string")(0,UJ.minValidation)("name_prefix",Z.name_prefix);Z.name_prefix=Z.name_prefix||z9.nuid.next();let G={name:`${Z.name_prefix}_1`,deliver_policy:hY.DeliverPolicy.StartSequence,opt_start_seq:Z.opt_start_seq||1,ack_policy:hY.AckPolicy.None,inactive_threshold:(0,z9.nanos)(300000),num_replicas:1,max_deliver:1,mem_storage:!0};if(Z.headers_only===!0)G.headers_only=!0;if(Array.isArray(Z.filter_subjects))G.filter_subjects=Z.filter_subjects;if(typeof Z.filter_subjects==="string")G.filter_subject=Z.filter_subjects;if(Z.replay_policy)G.replay_policy=Z.replay_policy;if(G.deliver_policy=Z.deliver_policy||hY.DeliverPolicy.StartSequence,Z.deliver_policy===hY.DeliverPolicy.All||Z.deliver_policy===hY.DeliverPolicy.LastPerSubject||Z.deliver_policy===hY.DeliverPolicy.New||Z.deliver_policy===hY.DeliverPolicy.Last)delete G.opt_start_seq,G.deliver_policy=Z.deliver_policy;if(G.deliver_policy===hY.DeliverPolicy.LastPerSubject){if(typeof G.filter_subjects>"u"&&typeof G.filter_subject>"u")G.filter_subject=">"}if(Z.opt_start_time)delete G.opt_start_seq,G.deliver_policy=hY.DeliverPolicy.StartTime,G.opt_start_time=Z.opt_start_time;if(Z.inactive_threshold)G.inactive_threshold=(0,z9.nanos)(Z.inactive_threshold);let J=await this.api.add($,G);return Promise.resolve(new ud0.PullConsumerImpl(this.api,J,Z))}}yt1.ConsumersImpl=E90;class fm{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 fm(this.api,$)}else return this}info($=!1,Z){if($)return Promise.resolve(this._info);return this.api.info(this.name,Z).then((X)=>{return this._info=X,this._info})}getConsumer($){return new E90(new cd0.ConsumerAPIImpl(this.api.nc,this.api.opts)).get(this.name,$)}getPushConsumer($){return new E90(new cd0.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 cd0.ConsumerAPIImpl(this.api.nc,this.api.opts).reset(this.name,$,Z)}}yt1.StreamImpl=fm;class dd0 extends om6.BaseApiClientImpl{constructor($,Z){super($,Z)}checkStreamConfigVersions($){let Z=this.nc;if($.metadata){let{min:Q,ok:Y}=Z.features.get(z9.Feature.JS_STREAM_CONSUMER_METADATA);if(!Y)throw Error(`stream 'metadata' requires server ${Q}`)}if($.first_seq){let{min:Q,ok:Y}=Z.features.get(z9.Feature.JS_STREAM_FIRST_SEQ);if(!Y)throw Error(`stream 'first_seq' requires server ${Q}`)}if($.subject_transform){let{min:Q,ok:Y}=Z.features.get(z9.Feature.JS_STREAM_SUBJECT_TRANSFORM);if(!Y)throw Error(`stream 'subject_transform' requires server ${Q}`)}if($.compression){let{min:Q,ok:Y}=Z.features.get(z9.Feature.JS_STREAM_COMPRESSION);if(!Y)throw Error(`stream 'compression' requires server ${Q}`)}if($.consumer_limits){let{min:Q,ok:Y}=Z.features.get(z9.Feature.JS_DEFAULT_CONSUMER_LIMITS);if(!Y)throw Error(`stream 'consumer_limits' requires server ${Q}`)}function X(Q,Y){if((Y?.subject_transforms?.length||0)>0){let{min:J,ok:K}=Z.features.get(z9.Feature.JS_STREAM_SOURCE_SUBJECT_TRANSFORM);if(!K)throw Error(`${Q} 'subject_transforms' requires server ${J}`)}}if($.sources)$.sources.forEach((Q)=>{X("stream sources",Q)});if($.mirror)X("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===hY.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,UJ.validateStreamName)($.name),$.mirror=vm($.mirror),$.sources=$.sources?.map(vm);let X=await this._request(`${this.prefix}.STREAM.CREATE.${$.name}`,$,this.requiredApiOpts($));return this._fixInfo(X),X}async delete($){return(0,UJ.validateStreamName)($),(await this._request(`${this.prefix}.STREAM.DELETE.${$}`)).success}async update($,Z={}){if(typeof $==="object"){let J=$;$=J.name,Z=J,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,UJ.validateStreamName)($);let X=await this.info($),Q=Object.assign(X.config,Z);Q.mirror=vm(Q.mirror),Q.sources=Q.sources?.map(vm);let G=await this._request(`${this.prefix}.STREAM.UPDATE.${$}`,Q,this.requiredApiOpts(Z));return this._fixInfo(G),G}async info($,Z){(0,UJ.validateStreamName)($);let X=`${this.prefix}.STREAM.INFO.${$}`,Y=await this._request(X,Z),{total:G,limit:J}=Y,K=Y.state.subjects?Object.getOwnPropertyNames(Y.state.subjects).length:1;if(G&&G>K){let W=[Y],H=Z||{},N=0;while(G>K){N++,H.offset=J*N;let F=await this._request(X,H);G=F.total,W.push(F);let w=Object.getOwnPropertyNames(F.state.subjects).length;if(K+=w,w<J)break}let U={};for(let F=0;F<W.length;F++)if(Y=W[F],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:$}:{},X=(Y)=>{let G=Y;return G.streams.forEach((J)=>{this._fixInfo(J)}),G.streams},Q=`${this.prefix}.STREAM.LIST`;return new xt1.ListerImpl(Q,X,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:Q,seq:Y}=Z;if(typeof Q==="number"&&typeof Y==="number")throw z9.InvalidArgumentError.format(["keep","seq"],"are mutually exclusive")}return(0,UJ.validateStreamName)($),await this._request(`${this.prefix}.STREAM.PURGE.${$}`,Z)}async deleteMessage($,Z,X=!0){(0,UJ.validateStreamName)($);let Q={seq:Z};if(!X)Q.no_erase=!0;return(await this._request(`${this.prefix}.STREAM.MSG.DELETE.${$}`,Q)).success}async getMessage($,Z){(0,UJ.validateStreamName)($);try{let Q=await this._request(`${this.prefix}.STREAM.MSG.GET.${$}`,Z);return new md0(Q)}catch(X){if(X instanceof ft1.JetStreamApiError&&X.code===ft1.JetStreamApiCodes.NoMessageFound)return null;return Promise.reject(X)}}find($){return this.findStream($)}names($=""){let Z=$?.length?{subject:$}:{},X=(Y)=>{return Y.streams},Q=`${this.prefix}.STREAM.NAMES`;return new xt1.ListerImpl(Q,X,this,Z)}async get($){let Z=await this.info($);return Promise.resolve(new fm(this,Z))}}yt1.StreamAPIImpl=dd0;class md0{_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):z9.Empty}get header(){if(!this._header)if(this.smr.message.hdrs){let $=this._parse(this.smr.message.hdrs);this._header=z9.MsgHdrsImpl.decode($)}else this._header=(0,z9.headers)();return this._header}_parse($){let Z=atob($),X=Z.length,Q=new Uint8Array(X);for(let Y=0;Y<X;Y++)Q[Y]=Z.charCodeAt(Y);return Q}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return z9.TD.decode(this.data)}}yt1.StoredMsgImpl=md0;class bt1{api;constructor($){this.api=$}get($){return this.api.info($).then((Z)=>{return new fm(this.api,Z)})}}yt1.StreamsImpl=bt1});var nd0=_((dt1)=>{Object.defineProperty(dt1,"__esModule",{value:!0});dt1.DirectConsumer=dt1.DirectMsgImpl=dt1.DirectStreamAPIImpl=void 0;var Zi6=ef(),Xb=uD(),FJ=gY(),ut1=$b(),id0=RN();class ct1 extends Zi6.BaseApiClientImpl{constructor($,Z){super($,Z)}async getMessage($,Z){if((0,ut1.validateStreamName)($),"start_time"in Z){let{min:H,ok:N}=this.nc.features.get(FJ.Feature.JS_BATCH_DIRECT_GET);if(!N)throw Error(`start_time direct option require server ${H}`)}let X=Z,{last_by_subj:Q}=X;if(Q)X=null;let Y=X?JSON.stringify(X):FJ.Empty,G=this.opts.apiPrefix||"$JS.API",J=Q?`${G}.DIRECT.GET.${$}.${Q}`:`${G}.DIRECT.GET.${$}`,K=await this.nc.request(J,Y,{timeout:this.timeout});if(K.headers?.code!==0){let H=new id0.JetStreamStatus(K);if(H.isMessageNotFound())return Promise.resolve(null);else return Promise.reject(H.toError())}let W=new z90(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:X,ok:Q}=this.nc.features.get(FJ.Feature.JS_BATCH_DIRECT_GET);if(!Q)return Promise.reject(Error(`batch direct require server ${X}`));(0,ut1.validateStreamName)($);let Y=typeof Z.callback==="function"?Z.callback:null,G=new FJ.QueuedIteratorImpl;function J(L,D){if(L){G.push(()=>{L.err?G.stop(L.err):G.stop()});return}G.push(D)}function K(L,D){let E=Y;if(typeof D==="function"){D();return}E(L,D)}if(Y)G.iterClosed.then((L)=>{W({err:L?L:void 0},{}),U.unsubscribe()});let W=Y?K:J,H=(0,FJ.createInbox)(this.nc.options.inboxPrefix),N=!1,U=this.nc.subscribe(H,{timeout:5000,callback:(L,D)=>{if(L){G.stop(L),U.unsubscribe();return}let E=id0.JetStreamStatus.maybeParseStatus(D);if(E){if(E.isNoResults())W({},()=>{G.stop()});if(E.isEndOfBatch())W({},()=>{G.stop()});else{let z=E.toError();W({err:z},()=>{G.stop(z)})}return}if(!N)if(typeof D.headers?.get("Nats-Num-Pending")!=="string")U.unsubscribe(),W({},()=>{G.stop()});else N=!0;W(null,new z90(D))}}),w=`${this.opts.apiPrefix||"$JS.API"}.DIRECT.GET.${$}`,B=JSON.stringify(Z,(L,D)=>{if((L==="up_to_time"||L==="start_time")&&D instanceof Date)return D.toISOString();return D});return this.nc.publish(w,B,{reply:H}),Promise.resolve(G)}}dt1.DirectStreamAPIImpl=ct1;class z90{data;header;constructor($){if(!$.headers)throw Error("headers expected");this.data=$.data,this.header=$.headers}get subject(){return this.header.last(Xb.DirectMsgHeaders.Subject)}get seq(){let $=this.header.last(Xb.DirectMsgHeaders.Sequence);return typeof $==="string"?parseInt($):0}get time(){return new Date(Date.parse(this.timestamp))}get timestamp(){return this.header.last(Xb.DirectMsgHeaders.TimeStamp)}get stream(){return this.header.last(Xb.DirectMsgHeaders.Stream)}get lastSequence(){let $=this.header.last(Xb.DirectMsgHeaders.LastSequence);return typeof $==="string"?parseInt($):0}get pending(){let $=this.header.last(Xb.DirectMsgHeaders.NumPending);return typeof $==="string"?parseInt($):-1}json($){return JSON.parse(new TextDecoder().decode(this.data),$)}string(){return FJ.TD.decode(this.data)}}dt1.DirectMsgImpl=z90;function Xi6($){return typeof $==="object"&&"start_time"in $}function Qi6($){return typeof $==="object"&&"max_bytes"in $}class lt1{stream;api;cursor;listeners;start;constructor($,Z,X){this.stream=$,this.api=Z,this.cursor={last:0},this.listeners=[],this.start=X}getOptions($){$=$||{};let Z={};if(this.cursor.last===0)if(Xi6(this.start))Z.start_time=this.start.start_time;else Z.seq=this.start.seq||1;else Z.seq=this.cursor.last+1;if(Qi6($))Z.max_bytes=$.max_bytes;else Z.batch=$.batch??100;return Z}status(){let $=new FJ.QueuedIteratorImpl;return this.listeners.push($),$}notify($){if(this.listeners.length>0)(()=>{let Z=[];this.listeners.forEach((X)=>{let Q=X;if(!Q.done)Q.push($);else Z.push(Q)}),this.listeners=this.listeners.filter((X)=>!Z.includes(X))})()}debug(){console.log(this.cursor)}consume($){let Z,X,Q=new FJ.QueuedIteratorImpl;return(async()=>{while(!0){if(this.cursor.pending===0)this.notify({type:"debug",code:0,description:"sleeping for 2500"}),Z=(0,FJ.delay)(2500),await Z;if(Q.done)break;X=(0,FJ.deferred)();let Y=this.getOptions($);this.notify({type:"next",options:Object.assign({},$)}),Y.callback=(J,K)=>{if(J){if(J.err)if(J.err instanceof id0.JetStreamStatusError)this.notify({type:"debug",code:J.err.code,description:J.err.message});else this.notify({type:"debug",code:0,description:J.err.message});X.resolve()}else if(K.lastSequence>0&&K.lastSequence!==this.cursor.last)G.stop(),X.resolve(),this.notify({type:"reset",name:"direct"});else Q.push(K),Q.received++,this.cursor.last=K.seq,this.cursor.pending=K.pending};let G=await this.api.getBatch(this.stream,Y);Q.iterClosed.then(()=>{G.stop(),Z?.cancel(),X?.resolve()}),await X}})().catch((Y)=>{Q.stop(Y)}),Promise.resolve(Q)}async fetch($){let Z=this.getOptions($),X=new FJ.QueuedIteratorImpl,Q=await this.api.get(this.stream,Object.assign({callback:(Y,G)=>{if(Y)X.push(()=>{Y.err?X.stop(Y.err):X.stop()});else if(G.lastSequence>0&&G.lastSequence!==this.cursor.last)X.push(()=>{X.stop()}),Q.stop();else X.push(G),X.received++,this.cursor.last=G.seq,this.cursor.pending=G.pending}},Z));return X.iterClosed.then(()=>{Q.stop()}),X}async next(){let $=await this.api.getMessage(this.stream,{seq:this.cursor.last+1}),Z=$?.seq;if(Z)this.cursor.last=Z;return $}}dt1.DirectConsumer=lt1});var st1=_((rt1)=>{Object.defineProperty(rt1,"__esModule",{value:!0});rt1.BatchPublisherImpl=rt1.JetStreamClientImpl=rt1.JetStreamManagerImpl=void 0;rt1.startFastIngest=Ki6;rt1.toJetStreamClient=Wi6;rt1.jetstream=td0;rt1.jetstreamManager=pt1;rt1.scheduleSpecToHeader=tt1;var pd0=ef(),nt1=vd0(),c$=gY(),j90=ht1(),gX=tD(),it1=RN(),Ji6=nd0();function Ki6($,Z,X,Q,Y=5000){let{ackInterval:G,allowGaps:J,inboxPrefix:K,maxOutstandingAcks:W,...H}=Q,N=K??"_INBOX";if(!N||/\s/.test(N)||/[*>]/.test(N))return Promise.reject(Error(`inboxPrefix must be non-empty, no wildcards or whitespace (got "${N}")`));let U={ackInterval:G??10,allowGaps:J,inboxPrefix:N,maxOutstandingAcks:Math.min(3,Math.max(1,W??2))},F=new ot1($,U,Z,Y);return F.start(X,H).then(()=>F)}function ym($){let Z=$.expect||{},X=$.headers||(0,c$.headers)();if($.msgID)X.set(gX.PubHeaders.MsgIdHdr,$.msgID);if(Z.lastMsgID)X.set(gX.PubHeaders.ExpectedLastMsgIdHdr,Z.lastMsgID);if(Z.streamName)X.set(gX.PubHeaders.ExpectedStreamHdr,Z.streamName);if(typeof Z.lastSequence==="number")X.set(gX.PubHeaders.ExpectedLastSeqHdr,`${Z.lastSequence}`);if(typeof Z.lastSubjectSequence==="number")X.set(gX.PubHeaders.ExpectedLastSubjectSequenceHdr,`${Z.lastSubjectSequence}`);if(Z.lastSubjectSequenceSubject)X.set(gX.PubHeaders.ExpectedLastSubjectSequenceSubjectHdr,Z.lastSubjectSequenceSubject);if($.ttl)X.set(gX.PubHeaders.MessageTTL,`${$.ttl}`);if($.schedule&&$.cancelSchedule)throw Error("schedule and cancelSchedule are mutually exclusive");if($.schedule){let Q=$.schedule;if(Q.specification)X.set(gX.PubHeaders.Schedule,tt1(Q.specification));if(Q.target)X.set(gX.PubHeaders.ScheduleTarget,Q.target);if(Q.source)X.set(gX.PubHeaders.ScheduleSource,Q.source);if(Q.ttl)X.set(gX.PubHeaders.ScheduleTTL,Q.ttl);if(Q.timezone)X.set(gX.PubHeaders.ScheduleTimeZone,Q.timezone);if(Q.rollup)X.set(gX.PubHeaders.ScheduleRollup,Q.rollup)}if($.cancelSchedule)X.set(gX.PubHeaders.Scheduler,$.cancelSchedule.scheduleSubject),X.set(gX.PubHeaders.ScheduleNext,"purge");return X}function Wi6($){if(typeof $.nc>"u")return td0($);return $}function td0($,Z={}){return new rd0($,Z)}async function pt1($,Z={}){let X=new od0($,Z);if(Z.checkAPI!==!1)try{await X.getAccountInfo()}catch(Q){throw Q}return X}class od0 extends pd0.BaseApiClientImpl{streams;consumers;direct;constructor($,Z){super($,Z);this.streams=new j90.StreamAPIImpl($,Z),this.consumers=new nt1.ConsumerAPIImpl($,Z),this.direct=new Ji6.DirectStreamAPIImpl($,Z)}async getAccountInfo(){return await this._request(`${this.prefix}.INFO`)}jetstream(){return td0(this.nc,this.getOptions())}advisories(){let $=new c$.QueuedIteratorImpl;return this.nc.subscribe("$JS.EVENT.ADVISORY.>",{callback:(Z,X)=>{if(Z)throw Z;try{let Q=this.parseJsResponse(X),Y=Q.type.split("."),G=Y[Y.length-1];$.push({kind:G,data:Q})}catch(Q){$.stop(Q)}}}),$}}rt1.JetStreamManagerImpl=od0;function tt1($){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 Hi6($.every),`@every ${$.every}`;if("cron"in $)return $.cron;if("predefined"in $)return $.predefined;throw Error("invalid schedule specification")}function Hi6($){let Z=$.trim(),X=/(\d+(?:\.\d+)?)(ns|us|\u00B5s|ms|s|m|h)/g,Q=0,Y=0,G;while((G=X.exec(Z))!==null){if(G.index!==Y)break;Y+=G[0].length;let J=parseFloat(G[1]),K=G[2];Q+=K==="ns"?J/1e6:K==="us"||K==="\xB5s"?J/1000:K==="ms"?J:K==="s"?J*1000:K==="m"?J*60000:J*3600000}if(Z===""||Y!==Z.length)throw Error(`@every: unrecognized duration format: "${$}"`);if(Q<1000)throw Error("@every interval must be at least 1s")}class rd0 extends pd0.BaseApiClientImpl{consumers;streams;consumerAPI;streamAPI;constructor($,Z){super($,Z);this.consumerAPI=new nt1.ConsumerAPIImpl($,Z),this.streamAPI=new j90.StreamAPIImpl($,Z),this.consumers=new j90.ConsumersImpl(this.consumerAPI),this.streams=new j90.StreamsImpl(this.streamAPI)}jetstreamManager($){if($===void 0)$=this.opts.checkAPI;let Z=Object.assign({},this.opts,{checkAPI:$});try{(0,c$.createInbox)(Z.watcherPrefix)}catch(X){return Promise.reject(X)}return pt1(this.nc,Z)}get apiPrefix(){return this.prefix}startBatch($,Z,X){let Q=(0,c$.deferred)(),Y=new ad0(this);return Y.first($,Z,X).then(()=>{Q.resolve(Y)}).catch((G)=>{Q.reject(G)}),Q}async _publish($,Z=c$.Empty,X){if(X=X||{},X={...X},X.cancelSchedule&&X.cancelSchedule.scheduleSubject===$)throw Error("cancelSchedule.scheduleSubject must not equal the publish subject");let Q=ym(X),Y=X.timeout||this.timeout,G={};if(Y)G.timeout=Y;if(X)G.headers=Q;let{retries:J}=X;J=J||1;let K=(0,c$.backoff)(),W=null;for(let H=0;H<J;H++)try{W=await this.nc.request($,Z,G);break}catch(N){let U=N instanceof c$.RequestError?N:null;if((N instanceof c$.errors.TimeoutError||U?.isNoResponders())&&H+1<J)await(0,c$.delay)(K.backoff(H));else throw U?.isNoResponders()?new it1.JetStreamNotEnabled("jetstream is not enabled",{cause:N}):N}return W}async publish($,Z=c$.Empty,X){let Q=await this._publish($,Z,X),Y=this.parseJsResponse(Q);if(Y.stream==="")throw new it1.JetStreamError("invalid ack response");return Y.duplicate=Y.duplicate?Y.duplicate:!1,Y}}rt1.JetStreamClientImpl=rd0;class ad0{nc;js;id;count;done;constructor($){this.count=0,this.id=c$.nuid.next(),this.js=$,this.nc=this.js.nc,this.done=!1}async first($,Z,X){X=X||{},X.headers=X?.headers||(0,c$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString());let Q=await this.js._publish($,Z,X);if(Q.data.length>0)this.js.parseJsResponse(Q)}add($,Z,X={ack:!1}){if(this.done)throw Error("batch publisher is done");if(X.headers=X?.headers||(0,c$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString()),"ack"in X&&X.ack===!0){let Y=(0,c$.deferred)();return this.js._publish($,Z,{headers:X.headers,timeout:X.timeout}).then((G)=>{if(G.data.length>0)this.js.parseJsResponse(G);Y.resolve()}).catch((G)=>{this.done=!0,Y.reject(G)}),Y}else return this.nc.publish($,Z,{headers:X.headers})}async commit($,Z,X={}){if(this.done)throw Error("batch publisher is done");else this.done=!0;X.headers=X?.headers||(0,c$.headers)(),X.headers.set("Nats-Batch-Id",this.id),this.count++,X.headers.set("Nats-Batch-Sequence",this.count.toString()),X.headers.set("Nats-Batch-Commit","1");let Y=(await this.js._publish($,Z,{headers:X.headers,timeout:X.timeout||0})).json();if(Y.count!==this.count)throw Error("batch didn't contain number of published messages");return Y}}rt1.BatchPublisherImpl=ad0;var bm="batch closed",K7={Start:0,Append:1,Final:2,EOB:3,Ping:4};class ot1{batch;nc;batchSubj;gapMode;initialFlow;seq;acked;ackInterval;inboxPrefix;maxOutstandingAcks;defaultTimeout;gapIter;sub;pending;closed;closeErr;startDeferred;closedDeferred;constructor($,Z,X,Q){this.nc=$,this.batchSubj=X,this.gapMode=Z.allowGaps?"ok":"fail",this.initialFlow=Z.ackInterval,this.inboxPrefix=Z.inboxPrefix,this.maxOutstandingAcks=Z.maxOutstandingAcks,this.defaultTimeout=Q,this.batch=c$.nuid.next(),this.seq=0,this.acked=0,this.ackInterval=Z.ackInterval,this.pending=new Map,this.closed=!1,this.startDeferred=(0,c$.deferred)(),this.closedDeferred=(0,c$.deferred)(),this.closedDeferred.catch(()=>{}),this.startDeferred.catch(()=>{});let Y=`${this.inboxPrefix}.${this.batch}.>`;this.sub=this.nc.subscribe(Y,{callback:(G,J)=>this.route(G,J)})}replyFor($,Z){return`${this.inboxPrefix}.${this.batch}.${this.initialFlow}.${this.gapMode}.${Z}.${$}.$FI`}start($,Z){this.seq=1;let X=this.replyFor(K7.Start,1),Q=Z?ym(Z):void 0;return this.nc.publish(this.batchSubj,$,{reply:X,headers:Q}),this.deadlineOrClose(this.startDeferred,Z?.timeout??this.defaultTimeout)}deadlineOrClose($,Z){return(0,c$.deadline)($,Z).catch((X)=>{if(!this.closed)this.close(X);throw X})}route($,Z){if($){this.close($);return}let X;try{X=(0,pd0.parseJsResponse)(Z)}catch(J){this.close(J);return}if("batch"in X&&typeof X.batch==="string"){let J=X,K=this.pending.get(Z.subject);if(K&&(K.op===K7.Final||K.op===K7.EOB))K.deferred.resolve(J),this.pending.delete(Z.subject);for(let[,W]of this.pending)if(W.op===K7.Append||W.op===K7.Ping)W.deferred.resolve({batchSeq:W.seq,ackSeq:this.acked});else W.deferred.reject(Error(bm));this.pending.clear(),this.resolveStart(),this.closedDeferred.resolve(J),this.closed=!0,this.gapIter?.stop(),this.sub.unsubscribe();return}if(X.type==="gap"){if(this.gapIter){let J=X;this.gapIter.push({lastSeq:J.last_seq,seq:J.seq})}return}let Y=X;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 G=this.pending.get(Z.subject);if(G&&(G.op===K7.Append||G.op===K7.Ping))G.deferred.resolve({batchSeq:G.seq,ackSeq:this.acked}),this.pending.delete(Z.subject);for(let[J,K]of this.pending)if(K.op===K7.Append&&K.seq-this.acked<this.ackInterval*this.maxOutstandingAcks)K.deferred.resolve({batchSeq:K.seq,ackSeq:this.acked}),this.pending.delete(J)}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,X){if(this.closed)return Promise.reject(Error(bm));let Q=++this.seq,Y=this.replyFor(K7.Append,Q),G=X?ym(X):void 0;if(this.nc.publish($,Z,{reply:Y,headers:G}),Q-this.acked<this.ackInterval*this.maxOutstandingAcks)return Promise.resolve({batchSeq:Q,ackSeq:this.acked});let J=(0,c$.deferred)();return this.pending.set(Y,{seq:Q,op:K7.Append,deferred:J}),this.deadlineOrClose(J,X?.timeout??this.defaultTimeout)}last($,Z,X){if(this.closed)return Promise.reject(Error(bm));let Q=++this.seq,Y=this.replyFor(K7.Final,Q),G=(0,c$.deferred)();this.pending.set(Y,{seq:Q,op:K7.Final,deferred:G});let J=X?ym(X):void 0;return this.nc.publish($,Z,{reply:Y,headers:J}),this.deadlineOrClose(G,X?.timeout??this.defaultTimeout)}end($){if(this.closed)return Promise.reject(Error(bm));let Z=++this.seq,X=this.replyFor(K7.EOB,Z),Q=(0,c$.deferred)();this.pending.set(X,{seq:Z,op:K7.EOB,deferred:Q});let Y=$?ym($):void 0;return this.nc.publish(this.batchSubj,c$.Empty,{reply:X,headers:Y}),this.deadlineOrClose(Q,$?.timeout??this.defaultTimeout)}ping($=this.defaultTimeout){if(this.closed)return Promise.reject(Error(bm));let Z=this.replyFor(K7.Ping,this.seq),X=this.pending.get(Z);if(X&&X.op===K7.Ping)return(0,c$.deadline)(X.deferred,$);let Q=(0,c$.deferred)();return this.pending.set(Z,{seq:this.seq,op:K7.Ping,deferred:Q}),this.nc.publish(this.batchSubj,c$.Empty,{reply:Z}),this.deadlineOrClose(Q,$)}done(){return this.closedDeferred}gaps(){if(!this.gapIter)this.gapIter=new c$.QueuedIteratorImpl;return this.gapIter}}});var P90=_((P4)=>{Object.defineProperty(P4,"__esModule",{value:!0});P4.validateStreamName=P4.jserrors=P4.JetStreamStatusError=P4.JetStreamStatus=P4.JetStreamError=P4.JetStreamApiError=P4.JetStreamApiCodes=P4.isMessageNotFound=P4.ListerImpl=P4.StoreCompression=P4.StorageType=P4.RetentionPolicy=P4.ReplayPolicy=P4.PubHeaders=P4.PersistMode=P4.DiscardPolicy=P4.DeliverPolicy=P4.AckPolicy=P4.DirectMsgImpl=P4.BaseApiClientImpl=P4.toJetStreamClient=P4.startFastIngest=P4.jetstreamManager=P4.JetStreamClientImpl=P4.jetstream=P4.RepublishHeaders=P4.JsHeaders=P4.isPushConsumer=P4.isPullConsumer=P4.isOrderedPushConsumerOptions=P4.isBoundPushConsumerOptions=P4.DirectMsgHeaders=P4.AdvisoryKind=void 0;var Lw=uD();Object.defineProperty(P4,"AdvisoryKind",{enumerable:!0,get:function(){return Lw.AdvisoryKind}});Object.defineProperty(P4,"DirectMsgHeaders",{enumerable:!0,get:function(){return Lw.DirectMsgHeaders}});Object.defineProperty(P4,"isBoundPushConsumerOptions",{enumerable:!0,get:function(){return Lw.isBoundPushConsumerOptions}});Object.defineProperty(P4,"isOrderedPushConsumerOptions",{enumerable:!0,get:function(){return Lw.isOrderedPushConsumerOptions}});Object.defineProperty(P4,"isPullConsumer",{enumerable:!0,get:function(){return Lw.isPullConsumer}});Object.defineProperty(P4,"isPushConsumer",{enumerable:!0,get:function(){return Lw.isPushConsumer}});Object.defineProperty(P4,"JsHeaders",{enumerable:!0,get:function(){return Lw.JsHeaders}});Object.defineProperty(P4,"RepublishHeaders",{enumerable:!0,get:function(){return Lw.RepublishHeaders}});var gm=st1();Object.defineProperty(P4,"jetstream",{enumerable:!0,get:function(){return gm.jetstream}});Object.defineProperty(P4,"JetStreamClientImpl",{enumerable:!0,get:function(){return gm.JetStreamClientImpl}});Object.defineProperty(P4,"jetstreamManager",{enumerable:!0,get:function(){return gm.jetstreamManager}});Object.defineProperty(P4,"startFastIngest",{enumerable:!0,get:function(){return gm.startFastIngest}});Object.defineProperty(P4,"toJetStreamClient",{enumerable:!0,get:function(){return gm.toJetStreamClient}});var Di6=ef();Object.defineProperty(P4,"BaseApiClientImpl",{enumerable:!0,get:function(){return Di6.BaseApiClientImpl}});var Ei6=nd0();Object.defineProperty(P4,"DirectMsgImpl",{enumerable:!0,get:function(){return Ei6.DirectMsgImpl}});var MN=tD();Object.defineProperty(P4,"AckPolicy",{enumerable:!0,get:function(){return MN.AckPolicy}});Object.defineProperty(P4,"DeliverPolicy",{enumerable:!0,get:function(){return MN.DeliverPolicy}});Object.defineProperty(P4,"DiscardPolicy",{enumerable:!0,get:function(){return MN.DiscardPolicy}});Object.defineProperty(P4,"PersistMode",{enumerable:!0,get:function(){return MN.PersistMode}});Object.defineProperty(P4,"PubHeaders",{enumerable:!0,get:function(){return MN.PubHeaders}});Object.defineProperty(P4,"ReplayPolicy",{enumerable:!0,get:function(){return MN.ReplayPolicy}});Object.defineProperty(P4,"RetentionPolicy",{enumerable:!0,get:function(){return MN.RetentionPolicy}});Object.defineProperty(P4,"StorageType",{enumerable:!0,get:function(){return MN.StorageType}});Object.defineProperty(P4,"StoreCompression",{enumerable:!0,get:function(){return MN.StoreCompression}});var zi6=O90();Object.defineProperty(P4,"ListerImpl",{enumerable:!0,get:function(){return zi6.ListerImpl}});var rD=RN();Object.defineProperty(P4,"isMessageNotFound",{enumerable:!0,get:function(){return rD.isMessageNotFound}});Object.defineProperty(P4,"JetStreamApiCodes",{enumerable:!0,get:function(){return rD.JetStreamApiCodes}});Object.defineProperty(P4,"JetStreamApiError",{enumerable:!0,get:function(){return rD.JetStreamApiError}});Object.defineProperty(P4,"JetStreamError",{enumerable:!0,get:function(){return rD.JetStreamError}});Object.defineProperty(P4,"JetStreamStatus",{enumerable:!0,get:function(){return rD.JetStreamStatus}});Object.defineProperty(P4,"JetStreamStatusError",{enumerable:!0,get:function(){return rD.JetStreamStatusError}});Object.defineProperty(P4,"jserrors",{enumerable:!0,get:function(){return rD.jserrors}});var ji6=$b();Object.defineProperty(P4,"validateStreamName",{enumerable:!0,get:function(){return ji6.validateStreamName}})});var aD=_((Q9)=>{Object.defineProperty(Q9,"__esModule",{value:!0});Q9.StoreCompression=Q9.StorageType=Q9.RetentionPolicy=Q9.RepublishHeaders=Q9.ReplayPolicy=Q9.PubHeaders=Q9.PersistMode=Q9.JsHeaders=Q9.JetStreamError=Q9.JetStreamApiError=Q9.JetStreamApiCodes=Q9.isPushConsumer=Q9.isPullConsumer=Q9.DiscardPolicy=Q9.DirectMsgHeaders=Q9.DeliverPolicy=Q9.AdvisoryKind=Q9.AckPolicy=Q9.jetstreamManager=Q9.jetstream=void 0;var et1=P90();Object.defineProperty(Q9,"jetstream",{enumerable:!0,get:function(){return et1.jetstream}});Object.defineProperty(Q9,"jetstreamManager",{enumerable:!0,get:function(){return et1.jetstreamManager}});var xZ=P90();Object.defineProperty(Q9,"AckPolicy",{enumerable:!0,get:function(){return xZ.AckPolicy}});Object.defineProperty(Q9,"AdvisoryKind",{enumerable:!0,get:function(){return xZ.AdvisoryKind}});Object.defineProperty(Q9,"DeliverPolicy",{enumerable:!0,get:function(){return xZ.DeliverPolicy}});Object.defineProperty(Q9,"DirectMsgHeaders",{enumerable:!0,get:function(){return xZ.DirectMsgHeaders}});Object.defineProperty(Q9,"DiscardPolicy",{enumerable:!0,get:function(){return xZ.DiscardPolicy}});Object.defineProperty(Q9,"isPullConsumer",{enumerable:!0,get:function(){return xZ.isPullConsumer}});Object.defineProperty(Q9,"isPushConsumer",{enumerable:!0,get:function(){return xZ.isPushConsumer}});Object.defineProperty(Q9,"JetStreamApiCodes",{enumerable:!0,get:function(){return xZ.JetStreamApiCodes}});Object.defineProperty(Q9,"JetStreamApiError",{enumerable:!0,get:function(){return xZ.JetStreamApiError}});Object.defineProperty(Q9,"JetStreamError",{enumerable:!0,get:function(){return xZ.JetStreamError}});Object.defineProperty(Q9,"JsHeaders",{enumerable:!0,get:function(){return xZ.JsHeaders}});Object.defineProperty(Q9,"PersistMode",{enumerable:!0,get:function(){return xZ.PersistMode}});Object.defineProperty(Q9,"PubHeaders",{enumerable:!0,get:function(){return xZ.PubHeaders}});Object.defineProperty(Q9,"ReplayPolicy",{enumerable:!0,get:function(){return xZ.ReplayPolicy}});Object.defineProperty(Q9,"RepublishHeaders",{enumerable:!0,get:function(){return xZ.RepublishHeaders}});Object.defineProperty(Q9,"RetentionPolicy",{enumerable:!0,get:function(){return xZ.RetentionPolicy}});Object.defineProperty(Q9,"StorageType",{enumerable:!0,get:function(){return xZ.StorageType}});Object.defineProperty(Q9,"StoreCompression",{enumerable:!0,get:function(){return xZ.StoreCompression}})});import{mkdir as Ti6,readdir as Ri6,readFile as sd0,stat as A90,unlink as Ii6,writeFile as qi6}from"fs/promises";import{createHmac as Mi6}from"crypto";import{dirname as ki6,join as hm}from"path";function ed0($){let Z=$.replace(/[^a-zA-Z0-9_-]/g,"_");return hm(Si6,Z)}function Qb($,Z){return hm(ed0($),iK(Z))}class ZW{orgId;baseUrl;constructor($,Z){this.orgId=$;this.baseUrl=Z}async getBytesOrPresign($,Z){let X=Qb(this.orgId,$),Q=await A90(X),Y=VZ($);if(Q.size>Z.presignWhenLargerThan)return{error:"FILE_TOO_LARGE",size:Q.size,maxInlineSize:Z.presignWhenLargerThan,presignedUrl:await this.presignedGetUrl($),contentType:Y};let G=await sd0(X),J=s$0(Y);return{content:J?new TextDecoder().decode(G):Buffer.from(G).toString("base64"),contentType:Y,encoding:J?"utf-8":"base64",size:Q.size,lastModified:Q.mtime}}async getBytes($){let Z=await sd0(Qb(this.orgId,$));return new Uint8Array(Z)}async put($,Z,X){let Q=Qb(this.orgId,$);return await Ti6(ki6(Q),{recursive:!0}),await qi6(Q,typeof Z==="string"?Buffer.from(Z,"utf-8"):Z),{key:$}}async list($){let Z=$?.prefix?hm(ed0(this.orgId),iK($.prefix)):ed0(this.orgId),X;try{X=await Ri6(Z,{withFileTypes:!0})}catch{return{objects:[],isTruncated:!1}}let Q=$?.maxKeys??1000,Y=$?.prefix,G=X.filter((K)=>K.isFile());if($?.delimiter){let K=[],W=X.filter((B)=>B.isDirectory());for(let B of W){let L=Y?`${Y}/${B.name}/`:`${B.name}/`;K.push(L)}K.sort();let H=Q,N=K.slice(0,H);H-=N.length;let U=G.slice(0,H),F=K.length+G.length;return{objects:await Promise.all(U.map(async(B)=>{let L=await A90(hm(Z,B.name));return{key:Y?`${Y}/${B.name}`:B.name,size:L.size,lastModified:L.mtime}})),isTruncated:F>Q,commonPrefixes:N.length>0?N:void 0}}return{objects:await Promise.all(G.slice(0,Q).map(async(K)=>{let W=await A90(hm(Z,K.name));return{key:Y?`${Y}/${K.name}`:K.name,size:W.size,lastModified:W.mtime}})),isTruncated:G.length>Q}}async delete($){await Ii6(Qb(this.orgId,$))}async head($){let Z=await A90(Qb(this.orgId,$));return{contentType:VZ($),size:Z.size,lastModified:Z.mtime}}async presignedGetUrl($,Z,X){if(X?.requireFetchable)throw Error("object storage returned a not fetchable (data:) URL; configure real S3/R2/MinIO for large-payload offload");let Q=Qb(this.orgId,$),Y=await sd0(Q),G=VZ($),J=Buffer.from(Y).toString("base64");return`data:${G};base64,${J}`}async presignedPutUrl($,Z=3600){if(!this.baseUrl)throw Error("baseUrl required for presigned PUT URLs in dev mode");let X=iK($),Q=Math.floor(Date.now()/1000)+Z,Y=Q1().encryptionKey||"dev-secret",G=`${this.orgId}:${X}:${Q}:PUT`,J=Mi6("sha256",Y).update(G).digest("hex"),K=new URL(`/api/dev-assets/${this.orgId}/${X}`,this.baseUrl);return K.searchParams.set("expires",Q.toString()),K.searchParams.set("signature",J),K.searchParams.set("method","PUT"),K.toString()}}var Si6="./data/assets";var um=O(()=>{nK();y8()});function Yb($){return Vi6.test($)&&$!=="."&&$!==".."}function vZ($){if(!Yb($))throw Error(`Invalid org-fs volume name: ${JSON.stringify($)}`)}function fZ($){return iK($)}function Gb($){let Z=$.lastIndexOf("/");return Z===-1?"":$.slice(0,Z)}function Dw($){let Z=Gb($);if(Z==="")return[];let X=Z.split("/"),Q=[],Y="";for(let G of X)Y=Y===""?G:`${Y}/${G}`,Q.push(Y);return Q}function XW($,Z){return`${$o1}/${$}/${Z}`}function Zo1($){return`${$o1}/${$}/`}var Vi6,$o1="_fs";var cm=O(()=>{nK();Vi6=/^[A-Za-z0-9_.-]{1,128}$/});import{createHmac as $m0,randomBytes as Zm0,scrypt as Ci6,timingSafeEqual as Xo1}from"crypto";import{promisify as _i6}from"util";async function Yo1($){let Z=Zm0(16),X=await Qo1($,Z,xi6);return`scrypt$${Z.toString("hex")}$${X.toString("hex")}`}async function Go1($,Z){let X=Z.split("$");if(X.length!==3||X[0]!=="scrypt")return!1;let Q=Buffer.from(X[1],"hex"),Y=Buffer.from(X[2],"hex");if(Q.length===0||Y.length===0)return!1;let G;try{G=await Qo1($,Q,Y.length)}catch{return!1}return Y.length===G.length&&Xo1(Y,G)}function Jo1(){return Zm0(16).toString("hex")}function Ko1(){if(T90)return T90;let $;try{let Z=Q1();$=Z.studioJwtSecret??Z.betterAuthSecret}catch{$=void 0}return T90=$?Buffer.from($):Zm0(32),T90}function Wo1($){let Z=Buffer.from(JSON.stringify($)).toString("base64url"),X=$m0("sha256",Ko1()).update(Z).digest("base64url");return`${Z}.${X}`}function Ho1($,Z){let X=$.indexOf(".");if(X<0)return null;let Q=$.slice(0,X),Y=Buffer.from($.slice(X+1)),G=Buffer.from($m0("sha256",Ko1()).update(Q).digest("base64url"));if(Y.length!==G.length||!Xo1(Y,G))return null;let J;try{J=JSON.parse(Buffer.from(Q,"base64url").toString())}catch{return null}if(J.o!==Z.org||J.v!==Z.volume||J.s!==Z.secret||typeof J.e!=="number"||J.e<Z.nowSec)return null;return{govPath:J.p}}function Xm0($,Z,X){return`fsu_${$m0("sha256","fsunlock-name").update(`${$}:${Z}:${X}`).digest("hex").slice(0,16)}`}var xi6=64,Qo1,T90=null;var Qm0=O(()=>{y8();Qo1=_i6(Ci6)});import{createHash as vi6}from"crypto";function hi6($){if(typeof $!=="object"||$===null)return!1;let Z=$;return Z.name==="NoSuchKey"||Z.Code==="NoSuchKey"||Z.code==="ENOENT"||Z.$metadata?.httpStatusCode===404}function No1($){return vi6("sha256").update($).digest("hex")}class YW{storage;manifest;organizationId;maxFileBytes;volumeQuotaBytes;constructor($,Z,X,Q={}){this.storage=$;this.manifest=Z;this.organizationId=X;this.maxFileBytes=Q.maxFileBytes??yi6,this.volumeQuotaBytes=Q.volumeQuotaBytes??gi6}async usage($){return vZ($),this.manifest.usage(this.organizationId,$)}async stat($,Z){return vZ($),this.manifest.get(this.organizationId,$,fZ(Z))}async listDir($,Z){return vZ($),this.manifest.listDir(this.organizationId,$,fZ(Z))}async read($,Z){let X=await this.requireFile($,Z);try{return await this.storage.getBytes(XW($,X.path))}catch(Q){if(hi6(Q))throw new QW(`No such file: ${X.path}`);throw Q}}async setShareMode($,Z,X,Q){vZ($);let Y=fZ(Z),G=await this.manifest.get(this.organizationId,$,Y);if(!G)throw new QW(`No such path: ${Y}`);let J=null,K=null;if(X==="password"){if(!Q.password)throw new wJ("A password is required to set password mode");J=await Yo1(Q.password),K=Jo1()}let W=await this.manifest.setShareMode({organizationId:this.organizationId,volume:$,path:G.path,readPublic:X!=="private",passwordHash:J,shareSecret:K,actor:Q.actor});if(!W)throw new QW(`No such path: ${G.path}`);return W}async setReadPublic($,Z,X,Q){return this.setShareMode($,Z,X?"public":"private",{actor:Q.actor})}async resolveReadAccess($,Z){vZ($);let X=fZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")return{access:"private"};let Y=await this.manifest.resolveGoverningShare({organizationId:this.organizationId,volume:$,candidatePaths:[X,...Dw(X)]});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){vZ($);let X=fZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")return!1;if(Q.readPublic)return!0;return this.manifest.hasPublicAncestorDir(this.organizationId,$,Dw(X))}async inheritsPublic($,Z){return vZ($),this.manifest.hasPublicAncestorDir(this.organizationId,$,Dw(fZ(Z)))}async childrenInheritPublic($,Z){vZ($);let X=fZ(Z);if(X==="")return!1;return this.manifest.hasPublicAncestorDir(this.organizationId,$,[...Dw(X),X])}async recentWithEffectivePublic($){return this.withEffectivePublic(await this.recent($))}async searchWithEffectivePublic($,Z,X,Q){return this.withEffectivePublic(await this.manifest.searchFiles({organizationId:this.organizationId,query:$,limit:Z,volumes:X,pathPrefix:Q?fZ(Q):void 0}))}async withEffectivePublic($){let Z=new Map;for(let Q of $){let Y=Z.get(Q.volume);if(!Y)Y=new Set,Z.set(Q.volume,Y);for(let G of Dw(Q.path))Y.add(G)}let X=new Map;return await Promise.all([...Z].map(async([Q,Y])=>{let G=await this.manifest.publicDirPaths({organizationId:this.organizationId,volume:Q,paths:[...Y]});X.set(Q,new Set(G))})),$.map((Q)=>{let Y=X.get(Q.volume),G=!!Y&&Dw(Q.path).some((J)=>Y.has(J));return{...Q,effectivePublic:Q.readPublic||G}})}async presignRead($,Z,X){let Q=await this.requireFile($,Z);return this.storage.presignedGetUrl(XW($,Q.path),X)}async write($,Z,X,Q){vZ($);let Y=fZ(Z);if(Y==="")throw new wJ("Cannot write to the volume root");let G=typeof X==="string"?new TextEncoder().encode(X):X;if(G.byteLength>this.maxFileBytes)throw new lm(`File exceeds the ${this.maxFileBytes}-byte per-file limit`);let[J,K]=await Promise.all([Q.skipVolumeQuota?Promise.resolve(null):this.manifest.usage(this.organizationId,$),this.manifest.get(this.organizationId,$,Y)]);if(K?.kind==="dir")throw new wJ(`Cannot write a file at ${Y}: a directory exists there`);if(J){let W=K?.kind==="file"?K.size:0;if(J.bytes-W+G.byteLength>this.volumeQuotaBytes)throw new lm(`Write would exceed the volume quota of ${this.volumeQuotaBytes} bytes`)}return await this.ensureDirs($,Y,Q.actor),await this.storage.put(XW($,Y),G,{contentType:Q.contentType??VZ(Y)}),this.manifest.putFile({organizationId:this.organizationId,volume:$,path:Y,parent:Gb(Y),contentHash:No1(G),size:G.byteLength,actor:Q.actor,threadId:Q.threadId??null})}async mkdir($,Z,X){vZ($);let Q=fZ(Z);if(Q==="")return;if((await this.manifest.get(this.organizationId,$,Q))?.kind==="file")throw new wJ(`Cannot create a directory at ${Q}: a file exists there`);await this.ensureDirs($,Q,X.actor),await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Q,parent:Gb(Q),actor:X.actor})}async delete($,Z,X){vZ($);let Q=fZ(Z);if(Q==="")throw new wJ("Cannot delete the volume root");let Y=await this.manifest.get(this.organizationId,$,Q);if(!Y)return;if(Y.kind==="dir"){let G=await this.manifest.listSubtreeFiles(this.organizationId,$,Q);await Promise.all(G.map((J)=>this.storage.delete(XW($,J.path)))),await this.manifest.tombstoneSubtree(this.organizationId,$,Q,X.actor);return}await this.storage.delete(XW($,Q)),await this.manifest.tombstone(this.organizationId,$,Q,X.actor)}async move($,Z,X,Q){vZ($);let Y=fZ(Z),G=fZ(X);if(Y===""||G==="")throw new wJ("Cannot move the volume root");if(G===Y||G.startsWith(`${Y}/`))throw new wJ(`Cannot move ${Y} onto itself or into its own subtree`);let J=await this.manifest.get(this.organizationId,$,Y);if(!J)throw new QW(`No such path: ${Y}`);if(J.kind==="file"){let H=await this.storage.getBytes(XW($,Y));await this.write($,G,H,{...Q,skipVolumeQuota:!0}),await this.delete($,Y,Q);return}let[K,W]=await Promise.all([this.manifest.listSubtreeFiles(this.organizationId,$,Y),this.manifest.listSubtreeDirs(this.organizationId,$,Y)]);await this.mkdir($,G,Q);for(let H of K){let N=H.path.slice(Y.length+1),U=await this.storage.getBytes(XW($,H.path));await this.write($,`${G}/${N}`,U,{...Q,skipVolumeQuota:!0})}for(let H of W){let N=H.path.slice(Y.length+1);await this.mkdir($,`${G}/${N}`,Q)}await this.delete($,Y,Q)}async filesExist($,Z){vZ($);let X=await this.manifest.liveFilePaths({organizationId:this.organizationId,volume:$,paths:Z.map((Q)=>fZ(Q))});return new Set(X)}async recent($){return this.manifest.recentFiles({organizationId:this.organizationId,limit:$})}async changes($,Z,X=fi6){vZ($);let Q=Z||"0";if(!/^\d+$/.test(Q))throw new wJ(`Invalid cursor: ${Z}`);let Y=await this.manifest.changesSince({organizationId:this.organizationId,volume:$,sinceSeq:Q,limit:X}),G=Y.at(-1);return{entries:Y,cursor:G?G.seq:Z||"0",hasMore:Y.length>=X}}async latestSeq($){return vZ($),this.manifest.latestSeq({organizationId:this.organizationId,volume:$})}async backfillFromStorage($,Z){vZ($);let X=Zo1($),Q,Y=0;do{let G=await this.storage.list({prefix:X,maxKeys:bi6,continuationToken:Q});for(let J of G.objects){let K=J.key.slice(X.length);if(K==="")continue;await this.ensureDirs($,K,Z.actor);let W=await this.storage.getBytes(J.key);await this.manifest.putFile({organizationId:this.organizationId,volume:$,path:K,parent:Gb(K),contentHash:No1(W),size:W.byteLength,actor:Z.actor}),Y++}Q=G.isTruncated?G.nextContinuationToken:void 0}while(Q);return Y}async requireFile($,Z){vZ($);let X=fZ(Z),Q=await this.manifest.get(this.organizationId,$,X);if(!Q||Q.kind!=="file")throw new QW(`No such file: ${X}`);return Q}async ensureDirs($,Z,X){for(let Q of Dw(Z))await this.manifest.putDir({organizationId:this.organizationId,volume:$,path:Q,parent:Gb(Q),actor:X})}}var fi6=500,bi6=1000,yi6=524288000,gi6=10737418240,lm,wJ,QW;var sD=O(()=>{nK();cm();Qm0();lm=class lm extends Error{constructor($){super($);this.name="OrgFsQuotaError"}};wJ=class wJ extends Error{constructor($){super($);this.name="OrgFsValidationError"}};QW=class QW extends Error{constructor($){super($);this.name="OrgFsNotFoundError"}}});import{z as kN}from"zod";function Ew($){return $.startsWith(Uo1)}function zw($){return`${Uo1}${$}`}function mi6($){let Z=new Map(li6.map((X)=>[X.set,X]));if($)try{for(let X of di6.parse(JSON.parse($)))Z.set(X.set,X)}catch(X){console.warn("[org-fs] invalid ORGFS_PUBLIC_SETS \u2014 using built-in defaults only",X)}return[...Z.values()]}function dG(){return mi6(Q1().orgFsPublicSetsJson)}function dm($){let Z=fX(),X=Z?xY(Z,SN):new ZW(SN,$.baseUrl);return new YW(X,$.storage.orgFsEntries,SN)}var SN="org_orgfs_public_skills",Uo1="public-",ui6,ci6,li6,di6;var Jb=O(()=>{y8();Gw();um();sD();ui6=kN.object({from:kN.string(),to:kN.string().optional()}),ci6=kN.object({set:kN.string().regex(/^[a-z0-9][a-z0-9-]{0,40}$/),repo:kN.string().regex(/^[\w.-]+\/[\w.-]+$/),ref:kN.string().min(1),paths:kN.array(ui6).min(1)}),li6=[{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"}]}],di6=kN.array(ci6).refine(($)=>new Set($.map((Z)=>Z.set)).size===$.length,{message:"duplicate set names"})});import{sql as eD}from"kysely";function Ym0($){if($===null)return null;return $ instanceof Date?$.toISOString():String($)}function BJ($){return{organizationId:$.organization_id,volume:$.volume,path:$.path,parent:$.parent,kind:$.kind,contentHash:$.content_hash,size:Number($.size),seq:String($.seq),deletedAt:Ym0($.deleted_at),createdBy:$.created_by,createdAt:Ym0($.created_at)??"",updatedBy:$.updated_by,updatedAt:Ym0($.updated_at)??"",threadId:$.thread_id,readPublic:$.read_public,shareMode:!$.read_public?"private":$.share_password_hash?"password":"public"}}class im{db;constructor($){this.db=$}async putFile($){let Z=new Date,X=$.threadId??null,Q=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:X}).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:R90,read_public:eD`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`,thread_id:eD`coalesce(cast(${X} as text), org_fs_entry.thread_id)`})).returning(OJ).executeTakeFirstOrThrow();return BJ(Q)}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((X)=>X.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:R90,read_public:eD`case when org_fs_entry.deleted_at is not null then false else org_fs_entry.read_public end`})).execute()}async get($,Z,X){let Q=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("path","=",X).where("deleted_at","is",null).select(OJ).executeTakeFirst();return Q?BJ(Q):null}async listDir($,Z,X){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("parent","=",X).where("deleted_at","is",null).select(OJ).orderBy("path","asc").execute()).map((Y)=>BJ(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(OJ).execute()).map((Q)=>BJ(Q))}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(OJ).execute()).map((Q)=>BJ(Q))}async listSubtreeFiles($,Z,X){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",`${mm(X)}/%`).select(OJ).execute()).map((Y)=>BJ(Y))}async listSubtreeDirs($,Z,X){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",`${mm(X)}/%`).select(OJ).execute()).map((Y)=>BJ(Y))}async tombstone($,Z,X,Q){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Q,updated_at:new Date,seq:R90}).where("organization_id","=",$).where("volume","=",Z).where("path","=",X).where("deleted_at","is",null).execute()}async tombstoneSubtree($,Z,X,Q){await this.db.updateTable("org_fs_entry").set({deleted_at:new Date,updated_by:Q,updated_at:new Date,seq:R90}).where("organization_id","=",$).where("volume","=",Z).where("deleted_at","is",null).where((Y)=>Y.or([Y("path","=",X),Y("path","like",`${mm(X)}/%`)])).execute()}async setShareMode($){let Z=new Date,X=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(OJ).executeTakeFirst();return X?BJ(X):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((Q,Y)=>Y.path.length-Q.path.length);let X=Z[0];return{path:X.path,passwordHash:X.share_password_hash,secret:X.share_secret}}async hasPublicAncestorDir($,Z,X){if(X.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",X).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((X)=>X.path)}async usage($,Z){let X=await this.db.selectFrom("org_fs_entry").where("organization_id","=",$).where("volume","=",Z).where("kind","=","file").where("deleted_at","is",null).select((Q)=>[Q.fn.countAll().as("files"),Q.fn.coalesce(Q.fn.sum("size"),eD`0`).as("bytes")]).executeTakeFirst();return{files:Number(X?.files??0),bytes:Number(X?.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((X)=>X.path)}async recentFiles($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).select(OJ).orderBy("seq","desc").limit($.limit).execute()).map((X)=>BJ(X))}async searchFiles($){if($.volumes&&$.volumes.length===0)return[];let Z=mm($.query),X=this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("kind","=","file").where("deleted_at","is",null).where("path","ilike",`%${Z}%`);if($.volumes)X=X.where("volume","in",$.volumes);if($.pathPrefix)X=X.where("path","like",`${mm($.pathPrefix)}/%`);return(await X.select(OJ).orderBy("seq","desc").limit($.limit).execute()).map((Y)=>BJ(Y))}async changesSince($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).where("seq",">",eD`cast(${$.sinceSeq} as bigint)`).select(OJ).orderBy("seq","asc").limit($.limit).execute()).map((X)=>BJ(X))}async latestSeq($){return(await this.db.selectFrom("org_fs_entry").where("organization_id","=",$.organizationId).where("volume","=",$.volume).select(eD`max(seq)`.as("seq")).executeTakeFirst())?.seq??"0"}}function mm($){return $.replace(/[\\%_]/g,"\\$&")}var OJ,R90;var Gm0=O(()=>{OJ=["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"],R90=eD`nextval('org_fs_entry_seq')`});import{createHash as ii6}from"crypto";import{gunzipSync as ni6}from"zlib";function Km0($,Z,X){let Q=Z,Y=Z+X;while(Q<Y&&$[Q]!==0)Q++;return new TextDecoder().decode($.subarray(Z,Q))}function ti6($,Z,X){let Q=Km0($,Z,X).trim();return Q===""?0:Number.parseInt(Q,8)}function oi6($){let Z=new Map,X=0,Q=null,Y=null;while(X+512<=$.length){let G=$.subarray(X,X+512);if(X+=512,G.every((F)=>F===0))break;let J=Km0(G,0,100),K=Km0(G,345,155);if(K)J=`${K}/${J}`;let W=ti6(G,124,12),H=String.fromCharCode(G[156]??0),N=$.subarray(X,X+W);if(X+=Math.ceil(W/512)*512,H==="L"){let F=new TextDecoder().decode(N),w=F.indexOf("\x00");Q=w===-1?F:F.slice(0,w);continue}if(H==="x"){let F=new TextDecoder().decode(N);Y=/(?:^|\n)\d+ path=([^\n]*)\n/.exec(F)?.[1]??null;continue}if(H==="g")continue;let U=Y??Q??J;if(Q=null,Y=null,H==="0"||H==="\x00"||H==="")Z.set(U,new Uint8Array(N))}return Z}async function ri6($,Z){let X=`https://codeload.github.com/${$}/tar.gz/${encodeURIComponent(Z)}`,Q=await fetch(X,{signal:AbortSignal.timeout(60000)});if(!Q.ok)throw Error(`tarball fetch failed for ${$}@${Z}: HTTP ${Q.status}`);let Y=Number(Q.headers.get("content-length")??0);if(Y>I90)throw Error(`tarball for ${$}@${Z} declares ${Y} bytes (cap ${I90})`);let G=new Uint8Array(await Q.arrayBuffer());if(G.length>I90)throw Error(`tarball for ${$}@${Z} exceeds ${I90} bytes`);let J=oi6(new Uint8Array(ni6(G,{maxOutputLength:pi6}))),K=new Map;for(let[W,H]of J){let N=W.indexOf("/");if(N===-1)continue;let U=W.slice(N+1);if(U)K.set(U,H)}return K}function ai6($,Z){let X=new Map;for(let{from:Q,to:Y}of Z){let G=Q===""?"":`${Q.replace(/\/+$/,"")}/`;for(let[J,K]of $){if(!J.startsWith(G))continue;let W=J.slice(G.length);if(!W)continue;let H=fZ(Y?`${Y}/${W}`:W);if(H)X.set(H,K)}}return X}function si6($,Z){let X=new Set;for(let G of $){let J=G.split("/");for(let K=1;K<J.length;K++)X.add(J.slice(0,K).join("/"))}let Q=[...Z].filter((G)=>!X.has(G)).sort((G,J)=>G.length-J.length),Y=[];for(let G of Q)if(!Y.some((J)=>G.startsWith(`${J}/`)))Y.push(G);return Y}function ei6($){return ii6("sha256").update($).digest("hex")}async function $n6($,Z,X){let Q=fX(),Y=Q?xY(Q,SN):new ZW(SN,X.baseUrl),G=new im($),J=new YW(Y,G,SN),K=zw(Z.set),W=ai6(await ri6(Z.repo,Z.ref),Z.paths),H=new Map((await G.listVolumeFiles(SN,K)).map((B)=>[B.path,B.contentHash]));if(W.size===0&&H.size>0)throw Error(`set "${Z.set}" resolved 0 files from ${Z.repo}@${Z.ref} `+`(check paths config) \u2014 refusing to delete the ${H.size} existing files`);let N=0;for(let B of H.keys()){if(W.has(B))continue;await J.delete(K,B,{actor:Jm0}),N++}let U=await G.listVolumeDirs(SN,K);for(let B of si6(W.keys(),U.map((L)=>L.path)))await J.delete(K,B,{actor:Jm0});let F=0,w=0;for(let[B,L]of W){if(H.get(B)===ei6(L)){w++;continue}await J.write(K,B,L,{actor:Jm0,contentType:VZ(B),skipVolumeQuota:!0}),F++}return{set:Z.set,written:F,deleted:N,unchanged:w}}async function Wm0($,Z,X){try{return await $n6($,Z,X)}catch(Q){return{set:Z.set,error:Q instanceof Error?Q.message:String(Q)}}}async function Fo1($,Z){let X=[];for(let Q of dG())X.push(await Wm0($,Q,Z));return X}var Jm0="system:skill-set-sync",I90=209715200,pi6=1073741824;var Hm0=O(()=>{Gm0();um();Gw();nK();sD();cm();Jb()});import{DBOS as q90,SchedulerMode as Zn6}from"@dbos-inc/dbos-sdk";function wo1($){Nm0=$}function Qn6(){if(!Nm0)throw Error("[org-fs] public-sets sync runtime not initialized \u2014 setPublicSetsSyncRuntime() must run before the workflow fires");return Nm0}async function Yn6($,Z){for(let X of dG()){let Q=await q90.runStep(()=>{let Y=Qn6();return Wm0(Y.db,X,{baseUrl:Y.baseUrl})},{name:`syncPublicSet:${X.set}`});if("error"in Q)console.warn(`[org-fs] public set "${Q.set}" sync failed: ${Q.error}`);else if(Q.written||Q.deleted)console.log(`[org-fs] public set "${Q.set}" synced: +${Q.written} -${Q.deleted} (=${Q.unchanged})`)}}function Bo1(){if(nm)return;nm=q90.registerWorkflow(Yn6,{name:"publicSetsSyncWorkflow"}),q90.registerScheduled(nm,{name:"publicSetsSyncWorkflow",crontab:Xn6,mode:Zn6.ExactlyOncePerIntervalWhenActive})}async function Oo1(){if(dG().length===0||!nm)return;let $=new Date,Z=`public-sets-sync-boot:${$.toISOString().slice(0,13)}`;await q90.startWorkflow(nm,{workflowID:Z})($,$)}var Xn6="4-59/10 * * * *",Nm0=null,nm=null;var Lo1=O(()=>{Jb();Hm0()});import{z as M8}from"zod";var Gn6,Jn6,Kn6,Wn6,Hn6,Nn6,Un6,Fn6,wn6,Bn6,On6,Ln6,$E;var pm=O(()=>{Gn6=M8.object({prefix:M8.string().optional().describe("Filter objects by prefix (e.g., 'folder/' for folder contents)"),maxKeys:M8.number().optional().default(1000).describe("Maximum number of keys to return (default: 1000)"),continuationToken:M8.string().optional().describe("Token for pagination from previous response"),delimiter:M8.string().optional().describe("Delimiter for grouping keys (typically '/'). When set, commonPrefixes returns folder paths.")}),Jn6=M8.object({objects:M8.array(M8.object({key:M8.string().describe("Object key/path"),size:M8.number().describe("Object size in bytes"),lastModified:M8.string().describe("Last modified timestamp"),etag:M8.string().describe("Entity tag for the object")})),nextContinuationToken:M8.string().optional().describe("Token for fetching next page of results"),isTruncated:M8.boolean().describe("Whether there are more results available"),commonPrefixes:M8.array(M8.string()).optional().describe("Folder paths when delimiter is used (e.g., ['photos/2024/', 'photos/2025/'])")}),Kn6=M8.object({key:M8.string().describe("Object key/path to get metadata for")}),Wn6=M8.object({contentType:M8.string().optional().describe("MIME type of the object"),contentLength:M8.number().describe("Size of the object in bytes"),lastModified:M8.string().describe("Last modified timestamp"),etag:M8.string().describe("Entity tag for the object"),metadata:M8.record(M8.string(),M8.string()).optional().describe("Custom metadata key-value pairs")}),Hn6=M8.object({key:M8.string().describe("Object key/path to generate URL for"),expiresIn:M8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)")}),Nn6=M8.object({url:M8.string().describe("Presigned URL for downloading the object"),expiresIn:M8.number().describe("Expiration time in seconds that was used")}),Un6=M8.object({key:M8.string().describe("Object key/path for the upload"),expiresIn:M8.number().optional().describe("URL expiration time in seconds (default: from state config or 3600)"),contentType:M8.string().optional().describe("MIME type for the object being uploaded")}),Fn6=M8.object({url:M8.string().describe("Presigned URL for uploading the object"),expiresIn:M8.number().describe("Expiration time in seconds that was used")}),wn6=M8.object({key:M8.string().describe("Object key/path to delete")}),Bn6=M8.object({success:M8.boolean().describe("Whether the deletion was successful"),key:M8.string().describe("The key that was deleted")}),On6=M8.object({keys:M8.array(M8.string()).max(1000).describe("Array of object keys/paths to delete (max 1000)")}),Ln6=M8.object({deleted:M8.array(M8.string()).describe("Array of successfully deleted keys"),errors:M8.array(M8.object({key:M8.string(),message:M8.string()})).describe("Array of errors for failed deletions")}),$E=[{name:"LIST_OBJECTS",inputSchema:Gn6,outputSchema:Jn6},{name:"GET_OBJECT_METADATA",inputSchema:Kn6,outputSchema:Wn6},{name:"GET_PRESIGNED_URL",inputSchema:Hn6,outputSchema:Nn6},{name:"PUT_PRESIGNED_URL",inputSchema:Un6,outputSchema:Fn6},{name:"DELETE_OBJECT",inputSchema:wn6,outputSchema:Bn6},{name:"DELETE_OBJECTS",inputSchema:On6,outputSchema:Ln6}]});import*as x from"zod/v4";function _o1($){if($.params.ref.type!=="ref/prompt")throw TypeError(`Expected CompleteRequestPrompt, but got ${$.params.ref.type}`)}function xo1($){if($.params.ref.type!=="ref/resource")throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${$.params.ref.type}`)}var jw="2025-11-25",Do1="2025-03-26",Pw,Aw="io.modelcontextprotocol/related-task",k90="2.0",JZ,Eo1,zo1,i45,Dn6,En6,Um0,uY,tm,jo1=($)=>tm.safeParse($).success,W7,mG,iG,H7,S90,Po1,GW=($)=>Po1.safeParse($).success,Ao1,To1=($)=>Ao1.safeParse($).success,Fm0,LJ=($)=>Fm0.safeParse($).success,b1,wm0,Wb=($)=>wm0.safeParse($).success,cY,n45,VN,zn6,V90,jn6,om,Kb,Ro1,Pn6,An6,Tn6,Rn6,In6,qn6,C90,Bm0=($)=>C90.safeParse($).success,Mn6,Om0,_90,Io1=($)=>_90.safeParse($).success,x90,kn6,Sn6,v90,Vn6,rm,am,Cn6,sm,CN,_n6,em,f90,b90,y90,p45,g90,h90,u90,qo1,Mo1,ko1,Lm0,So1,$i,Hb,Vo1,xn6,Tw,Dm0,Rw,Em0,zm0,vn6,Nb,jm0,Pm0,fn6,bn6,yn6,gn6,hn6,un6,cn6,ln6,Iw,Am0,dn6,Ub,Tm0,Rm0,Im0,mn6,in6,nn6,qm0,pn6,Mm0,km0,tn6,on6,c90,Fb,Zi,JW,t45,rn6,qw,Sm0,Co1,Xi,an6,Vm0,sn6,en6,$p6,Zp6,Xp6,Qp6,Yp6,M90,Gp6,Jp6,Cm0,ZE,Qi,Kp6,Wp6,Hp6,Np6,Up6,Fp6,wp6,Bp6,Op6,Lp6,Dp6,Ep6,zp6,jp6,Pp6,_m0,Ap6,Tp6,Mw,Rp6,Ip6,qp6,l90,xm0,Mp6,kp6,vm0,Sp6,o45,r45,a45,s45,e45,$$5,S1,vo1;var Y9=O(()=>{Pw=[jw,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],JZ=x.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),Eo1=x.union([x.string(),x.number().int()]),zo1=x.string(),i45=x.looseObject({ttl:x.number().optional(),pollInterval:x.number().optional()}),Dn6=x.object({ttl:x.number().optional()}),En6=x.object({taskId:x.string()}),Um0=x.looseObject({progressToken:Eo1.optional(),[Aw]:En6.optional()}),uY=x.object({_meta:Um0.optional()}),tm=uY.extend({task:Dn6.optional()}),W7=x.object({method:x.string(),params:uY.loose().optional()}),mG=x.object({_meta:Um0.optional()}),iG=x.object({method:x.string(),params:mG.loose().optional()}),H7=x.looseObject({_meta:Um0.optional()}),S90=x.union([x.string(),x.number().int()]),Po1=x.object({jsonrpc:x.literal(k90),id:S90,...W7.shape}).strict(),Ao1=x.object({jsonrpc:x.literal(k90),...iG.shape}).strict(),Fm0=x.object({jsonrpc:x.literal(k90),id:S90,result:H7}).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={}));wm0=x.object({jsonrpc:x.literal(k90),id:S90.optional(),error:x.object({code:x.number().int(),message:x.string(),data:x.unknown().optional()})}).strict(),cY=x.union([Po1,Ao1,Fm0,wm0]),n45=x.union([Fm0,wm0]),VN=H7.strict(),zn6=mG.extend({requestId:S90.optional(),reason:x.string().optional()}),V90=iG.extend({method:x.literal("notifications/cancelled"),params:zn6}),jn6=x.object({src:x.string(),mimeType:x.string().optional(),sizes:x.array(x.string()).optional(),theme:x.enum(["light","dark"]).optional()}),om=x.object({icons:x.array(jn6).optional()}),Kb=x.object({name:x.string(),title:x.string().optional()}),Ro1=Kb.extend({...Kb.shape,...om.shape,version:x.string(),websiteUrl:x.string().optional(),description:x.string().optional()}),Pn6=x.intersection(x.object({applyDefaults:x.boolean().optional()}),x.record(x.string(),x.unknown())),An6=x.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},x.intersection(x.object({form:Pn6.optional(),url:JZ.optional()}),x.record(x.string(),x.unknown()).optional())),Tn6=x.looseObject({list:JZ.optional(),cancel:JZ.optional(),requests:x.looseObject({sampling:x.looseObject({createMessage:JZ.optional()}).optional(),elicitation:x.looseObject({create:JZ.optional()}).optional()}).optional()}),Rn6=x.looseObject({list:JZ.optional(),cancel:JZ.optional(),requests:x.looseObject({tools:x.looseObject({call:JZ.optional()}).optional()}).optional()}),In6=x.object({experimental:x.record(x.string(),JZ).optional(),sampling:x.object({context:JZ.optional(),tools:JZ.optional()}).optional(),elicitation:An6.optional(),roots:x.object({listChanged:x.boolean().optional()}).optional(),tasks:Tn6.optional(),extensions:x.record(x.string(),JZ).optional()}),qn6=uY.extend({protocolVersion:x.string(),capabilities:In6,clientInfo:Ro1}),C90=W7.extend({method:x.literal("initialize"),params:qn6}),Mn6=x.object({experimental:x.record(x.string(),JZ).optional(),logging:JZ.optional(),completions:JZ.optional(),prompts:x.object({listChanged:x.boolean().optional()}).optional(),resources:x.object({subscribe:x.boolean().optional(),listChanged:x.boolean().optional()}).optional(),tools:x.object({listChanged:x.boolean().optional()}).optional(),tasks:Rn6.optional(),extensions:x.record(x.string(),JZ).optional()}),Om0=H7.extend({protocolVersion:x.string(),capabilities:Mn6,serverInfo:Ro1,instructions:x.string().optional()}),_90=iG.extend({method:x.literal("notifications/initialized"),params:mG.optional()}),x90=W7.extend({method:x.literal("ping"),params:uY.optional()}),kn6=x.object({progress:x.number(),total:x.optional(x.number()),message:x.optional(x.string())}),Sn6=x.object({...mG.shape,...kn6.shape,progressToken:Eo1}),v90=iG.extend({method:x.literal("notifications/progress"),params:Sn6}),Vn6=uY.extend({cursor:zo1.optional()}),rm=W7.extend({params:Vn6.optional()}),am=H7.extend({nextCursor:zo1.optional()}),Cn6=x.enum(["working","input_required","completed","failed","cancelled"]),sm=x.object({taskId:x.string(),status:Cn6,ttl:x.union([x.number(),x.null()]),createdAt:x.string(),lastUpdatedAt:x.string(),pollInterval:x.optional(x.number()),statusMessage:x.optional(x.string())}),CN=H7.extend({task:sm}),_n6=mG.merge(sm),em=iG.extend({method:x.literal("notifications/tasks/status"),params:_n6}),f90=W7.extend({method:x.literal("tasks/get"),params:uY.extend({taskId:x.string()})}),b90=H7.merge(sm),y90=W7.extend({method:x.literal("tasks/result"),params:uY.extend({taskId:x.string()})}),p45=H7.loose(),g90=rm.extend({method:x.literal("tasks/list")}),h90=am.extend({tasks:x.array(sm)}),u90=W7.extend({method:x.literal("tasks/cancel"),params:uY.extend({taskId:x.string()})}),qo1=H7.merge(sm),Mo1=x.object({uri:x.string(),mimeType:x.optional(x.string()),_meta:x.record(x.string(),x.unknown()).optional()}),ko1=Mo1.extend({text:x.string()}),Lm0=x.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),So1=Mo1.extend({blob:Lm0}),$i=x.enum(["user","assistant"]),Hb=x.object({audience:x.array($i).optional(),priority:x.number().min(0).max(1).optional(),lastModified:x.iso.datetime({offset:!0}).optional()}),Vo1=x.object({...Kb.shape,...om.shape,uri:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string()),size:x.optional(x.number()),annotations:Hb.optional(),_meta:x.optional(x.looseObject({}))}),xn6=x.object({...Kb.shape,...om.shape,uriTemplate:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string()),annotations:Hb.optional(),_meta:x.optional(x.looseObject({}))}),Tw=rm.extend({method:x.literal("resources/list")}),Dm0=am.extend({resources:x.array(Vo1)}),Rw=rm.extend({method:x.literal("resources/templates/list")}),Em0=am.extend({resourceTemplates:x.array(xn6)}),zm0=uY.extend({uri:x.string()}),vn6=zm0,Nb=W7.extend({method:x.literal("resources/read"),params:vn6}),jm0=H7.extend({contents:x.array(x.union([ko1,So1]))}),Pm0=iG.extend({method:x.literal("notifications/resources/list_changed"),params:mG.optional()}),fn6=zm0,bn6=W7.extend({method:x.literal("resources/subscribe"),params:fn6}),yn6=zm0,gn6=W7.extend({method:x.literal("resources/unsubscribe"),params:yn6}),hn6=mG.extend({uri:x.string()}),un6=iG.extend({method:x.literal("notifications/resources/updated"),params:hn6}),cn6=x.object({name:x.string(),description:x.optional(x.string()),required:x.optional(x.boolean())}),ln6=x.object({...Kb.shape,...om.shape,description:x.optional(x.string()),arguments:x.optional(x.array(cn6)),_meta:x.optional(x.looseObject({}))}),Iw=rm.extend({method:x.literal("prompts/list")}),Am0=am.extend({prompts:x.array(ln6)}),dn6=uY.extend({name:x.string(),arguments:x.record(x.string(),x.string()).optional()}),Ub=W7.extend({method:x.literal("prompts/get"),params:dn6}),Tm0=x.object({type:x.literal("text"),text:x.string(),annotations:Hb.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),Rm0=x.object({type:x.literal("image"),data:Lm0,mimeType:x.string(),annotations:Hb.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),Im0=x.object({type:x.literal("audio"),data:Lm0,mimeType:x.string(),annotations:Hb.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),mn6=x.object({type:x.literal("tool_use"),name:x.string(),id:x.string(),input:x.record(x.string(),x.unknown()),_meta:x.record(x.string(),x.unknown()).optional()}),in6=x.object({type:x.literal("resource"),resource:x.union([ko1,So1]),annotations:Hb.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),nn6=Vo1.extend({type:x.literal("resource_link")}),qm0=x.union([Tm0,Rm0,Im0,nn6,in6]),pn6=x.object({role:$i,content:qm0}),Mm0=H7.extend({description:x.string().optional(),messages:x.array(pn6)}),km0=iG.extend({method:x.literal("notifications/prompts/list_changed"),params:mG.optional()}),tn6=x.object({title:x.string().optional(),readOnlyHint:x.boolean().optional(),destructiveHint:x.boolean().optional(),idempotentHint:x.boolean().optional(),openWorldHint:x.boolean().optional()}),on6=x.object({taskSupport:x.enum(["required","optional","forbidden"]).optional()}),c90=x.object({...Kb.shape,...om.shape,description:x.string().optional(),inputSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),JZ).optional(),required:x.array(x.string()).optional()}).catchall(x.unknown()),outputSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),JZ).optional(),required:x.array(x.string()).optional()}).catchall(x.unknown()).optional(),annotations:tn6.optional(),execution:on6.optional(),_meta:x.record(x.string(),x.unknown()).optional()}),Fb=rm.extend({method:x.literal("tools/list")}),Zi=am.extend({tools:x.array(c90)}),JW=H7.extend({content:x.array(qm0).default([]),structuredContent:x.record(x.string(),x.unknown()).optional(),isError:x.boolean().optional()}),t45=JW.or(H7.extend({toolResult:x.unknown()})),rn6=tm.extend({name:x.string(),arguments:x.record(x.string(),x.unknown()).optional()}),qw=W7.extend({method:x.literal("tools/call"),params:rn6}),Sm0=iG.extend({method:x.literal("notifications/tools/list_changed"),params:mG.optional()}),Co1=x.object({autoRefresh:x.boolean().default(!0),debounceMs:x.number().int().nonnegative().default(300)}),Xi=x.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),an6=uY.extend({level:Xi}),Vm0=W7.extend({method:x.literal("logging/setLevel"),params:an6}),sn6=mG.extend({level:Xi,logger:x.string().optional(),data:x.unknown()}),en6=iG.extend({method:x.literal("notifications/message"),params:sn6}),$p6=x.object({name:x.string().optional()}),Zp6=x.object({hints:x.array($p6).optional(),costPriority:x.number().min(0).max(1).optional(),speedPriority:x.number().min(0).max(1).optional(),intelligencePriority:x.number().min(0).max(1).optional()}),Xp6=x.object({mode:x.enum(["auto","required","none"]).optional()}),Qp6=x.object({type:x.literal("tool_result"),toolUseId:x.string().describe("The unique identifier for the corresponding tool call."),content:x.array(qm0).default([]),structuredContent:x.object({}).loose().optional(),isError:x.boolean().optional(),_meta:x.record(x.string(),x.unknown()).optional()}),Yp6=x.discriminatedUnion("type",[Tm0,Rm0,Im0]),M90=x.discriminatedUnion("type",[Tm0,Rm0,Im0,mn6,Qp6]),Gp6=x.object({role:$i,content:x.union([M90,x.array(M90)]),_meta:x.record(x.string(),x.unknown()).optional()}),Jp6=tm.extend({messages:x.array(Gp6),modelPreferences:Zp6.optional(),systemPrompt:x.string().optional(),includeContext:x.enum(["none","thisServer","allServers"]).optional(),temperature:x.number().optional(),maxTokens:x.number().int(),stopSequences:x.array(x.string()).optional(),metadata:JZ.optional(),tools:x.array(c90).optional(),toolChoice:Xp6.optional()}),Cm0=W7.extend({method:x.literal("sampling/createMessage"),params:Jp6}),ZE=H7.extend({model:x.string(),stopReason:x.optional(x.enum(["endTurn","stopSequence","maxTokens"]).or(x.string())),role:$i,content:Yp6}),Qi=H7.extend({model:x.string(),stopReason:x.optional(x.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(x.string())),role:$i,content:x.union([M90,x.array(M90)])}),Kp6=x.object({type:x.literal("boolean"),title:x.string().optional(),description:x.string().optional(),default:x.boolean().optional()}),Wp6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),minLength:x.number().optional(),maxLength:x.number().optional(),format:x.enum(["email","uri","date","date-time"]).optional(),default:x.string().optional()}),Hp6=x.object({type:x.enum(["number","integer"]),title:x.string().optional(),description:x.string().optional(),minimum:x.number().optional(),maximum:x.number().optional(),default:x.number().optional()}),Np6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),enum:x.array(x.string()),default:x.string().optional()}),Up6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),oneOf:x.array(x.object({const:x.string(),title:x.string()})),default:x.string().optional()}),Fp6=x.object({type:x.literal("string"),title:x.string().optional(),description:x.string().optional(),enum:x.array(x.string()),enumNames:x.array(x.string()).optional(),default:x.string().optional()}),wp6=x.union([Np6,Up6]),Bp6=x.object({type:x.literal("array"),title:x.string().optional(),description:x.string().optional(),minItems:x.number().optional(),maxItems:x.number().optional(),items:x.object({type:x.literal("string"),enum:x.array(x.string())}),default:x.array(x.string()).optional()}),Op6=x.object({type:x.literal("array"),title:x.string().optional(),description:x.string().optional(),minItems:x.number().optional(),maxItems:x.number().optional(),items:x.object({anyOf:x.array(x.object({const:x.string(),title:x.string()}))}),default:x.array(x.string()).optional()}),Lp6=x.union([Bp6,Op6]),Dp6=x.union([Fp6,wp6,Lp6]),Ep6=x.union([Dp6,Kp6,Wp6,Hp6]),zp6=tm.extend({mode:x.literal("form").optional(),message:x.string(),requestedSchema:x.object({type:x.literal("object"),properties:x.record(x.string(),Ep6),required:x.array(x.string()).optional()})}),jp6=tm.extend({mode:x.literal("url"),message:x.string(),elicitationId:x.string(),url:x.string().url()}),Pp6=x.union([zp6,jp6]),_m0=W7.extend({method:x.literal("elicitation/create"),params:Pp6}),Ap6=mG.extend({elicitationId:x.string()}),Tp6=iG.extend({method:x.literal("notifications/elicitation/complete"),params:Ap6}),Mw=H7.extend({action:x.enum(["accept","decline","cancel"]),content:x.preprocess(($)=>$===null?void 0:$,x.record(x.string(),x.union([x.string(),x.number(),x.boolean(),x.array(x.string())])).optional())}),Rp6=x.object({type:x.literal("ref/resource"),uri:x.string()}),Ip6=x.object({type:x.literal("ref/prompt"),name:x.string()}),qp6=uY.extend({ref:x.union([Ip6,Rp6]),argument:x.object({name:x.string(),value:x.string()}),context:x.object({arguments:x.record(x.string(),x.string()).optional()}).optional()}),l90=W7.extend({method:x.literal("completion/complete"),params:qp6});xm0=H7.extend({completion:x.looseObject({values:x.array(x.string()).max(100),total:x.optional(x.number().int()),hasMore:x.optional(x.boolean())})}),Mp6=x.object({uri:x.string().startsWith("file://"),name:x.string().optional(),_meta:x.record(x.string(),x.unknown()).optional()}),kp6=W7.extend({method:x.literal("roots/list"),params:uY.optional()}),vm0=H7.extend({roots:x.array(Mp6)}),Sp6=iG.extend({method:x.literal("notifications/roots/list_changed"),params:mG.optional()}),o45=x.union([x90,C90,l90,Vm0,Ub,Iw,Tw,Rw,Nb,bn6,gn6,qw,Fb,f90,y90,g90,u90]),r45=x.union([V90,v90,_90,Sp6,em]),a45=x.union([VN,ZE,Qi,Mw,vm0,b90,h90,CN]),s45=x.union([x90,Cm0,_m0,kp6,f90,y90,g90,u90]),e45=x.union([V90,v90,en6,un6,Pm0,Sm0,km0,em,Tp6]),$$5=x.union([VN,Om0,xm0,Mm0,Am0,Dm0,Em0,jm0,JW,Zi,b90,h90,CN]);S1=class S1 extends Error{constructor($,Z,X){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=X,this.name="McpError"}static fromError($,Z,X){if($===b1.UrlElicitationRequired&&X){let Q=X;if(Q.elicitations)return new vo1(Q.elicitations,Z)}return new S1($,Z,X)}};vo1=class vo1 extends S1{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(b1.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}});import{z as E8}from"zod";function KW($){return $!==null&&$!==void 0&&"command"in $}function wb($){if(!$||!$.startsWith("virtual://"))return null;return $.replace("virtual://","")}function Bb($){return`virtual://${$}`}var Vp6,fo1,Cp6,_p6,xp6,n7,d90,m90;var bo1=O(()=>{Y9();Vp6=E8.object({authorizationEndpoint:E8.string().url(),tokenEndpoint:E8.string().url(),introspectionEndpoint:E8.string().url().optional(),clientId:E8.string(),clientSecret:E8.string().optional(),scopes:E8.array(E8.string()),grantType:E8.enum(["authorization_code","client_credentials"])}),fo1=E8.object({type:E8.literal("object"),properties:E8.record(E8.string(),E8.unknown()).optional(),required:E8.array(E8.string()).optional()}).catchall(E8.unknown()),Cp6=c90.extend({inputSchema:fo1,outputSchema:fo1.optional()}),_p6=E8.object({headers:E8.record(E8.string(),E8.string()).optional()}),xp6=E8.object({command:E8.string().describe("Command to run (e.g., 'npx', 'node')"),args:E8.array(E8.string()).optional().describe("Command arguments"),cwd:E8.string().optional().describe("Working directory"),envVars:E8.record(E8.string(),E8.string()).optional().describe("Environment variables (encrypted in storage)")}),n7=E8.object({id:E8.string().describe("Unique identifier for the connection"),title:E8.string().describe("Human-readable name for the connection"),created_at:E8.string().describe("When the connection was created"),updated_at:E8.string().describe("When the connection was last updated"),created_by:E8.string().describe("User ID who created the connection"),updated_by:E8.string().optional().describe("User ID who last updated the connection"),organization_id:E8.string().describe("Organization ID this connection belongs to"),description:E8.string().nullable().describe("Description of the connection"),icon:E8.string().nullable().describe("Icon URL for the connection"),app_name:E8.string().nullable().describe("Associated app name"),app_id:E8.string().nullable().describe("Associated app ID"),slug:E8.string().nullable().optional().describe("URL-safe slug derived from app_name, connection_url, or title"),connection_type:E8.enum(["HTTP","SSE","Websocket","STDIO","VIRTUAL"]).describe("Type of connection"),connection_url:E8.string().nullable().describe("URL for HTTP/SSE/WebSocket connections. virtual://$id for VIRTUAL. Null for STDIO."),connection_token:E8.string().nullable().describe("Authentication token (for HTTP connections)"),connection_headers:E8.union([xp6,_p6]).nullable().describe("Connection parameters. HTTP: { headers }. STDIO: { command, args, cwd, envVars }"),oauth_config:Vp6.nullable().describe("OAuth configuration"),configuration_state:E8.record(E8.string(),E8.unknown()).nullable().describe("Configuration state (decrypted)"),configuration_scopes:E8.array(E8.string()).nullable().optional().describe("Configuration scopes"),metadata:E8.record(E8.string(),E8.unknown()).nullable().describe("Additional metadata (includes repository info)"),tools:E8.array(Cp6).nullable().describe("Discovered tools from MCP"),bindings:E8.array(E8.string()).nullable().describe("Detected bindings"),status:E8.enum(["active","inactive","error"]).describe("Current status")}),d90=n7.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:E8.string().nullish()}),m90=n7.partial()});import{z as h0}from"zod";function bm0($){let Z=$?.homeTiles;if(Array.isArray(Z)&&Z.length>0)return Z;let X=$?.homeTile;return X?[X]:[]}function hm0($){return $==="cluster"?"agent-sandbox":$}function mo1($){let Z=hp6.parse($);return um0.parse({...Z,sandboxProviderKind:Z.sandboxProviderKind?hm0(Z.sandboxProviderKind):void 0})}function DJ($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z=$,X={};for(let[Q,Y]of Object.entries(Z)){if(!Y||typeof Y!=="object")continue;if(Q!=="cluster"&&Q!=="agent-sandbox"&&Q!=="user-desktop")continue;let G=hm0(Q);try{if(Q==="cluster"&&X[G])continue;X[G]=mo1(Y)}catch{}}return X}function cm0($){if(!$||typeof $!=="object"||Array.isArray($))return{};let Z={};for(let[X,Q]of Object.entries($)){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let Y={};for(let[G,J]of Object.entries(Q)){let K=DJ(J);if(Object.keys(K).length>0)Y[G]=K}if(Object.keys(Y).length>0)Z[X]=Y}return Z}var Yi,ho1,vp6,uo1,co1,yo1,fm0,i90,go1,fp6,lo1,bp6,ym0,gm0,yp6,gp6,do1,um0,hp6,n90,up6,lm0,cp6,dm0,mm0,p7,im0,p90,t90;var io1=O(()=>{Yi=h0.object({connection_id:h0.string().describe("Connection ID"),selected_tools:h0.array(h0.string()).nullable().describe("Selected tool names. null = all tools included, array = only these tools included"),selected_resources:h0.array(h0.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:h0.array(h0.string()).nullable().describe("Selected prompt names. null = all prompts included, array = only these prompts included")}),ho1=Yi.extend({selected_tools:Yi.shape.selected_tools.optional(),selected_resources:Yi.shape.selected_resources.optional(),selected_prompts:Yi.shape.selected_prompts.optional()}),vp6=h0.object({connectionId:h0.string(),toolName:h0.string(),label:h0.string(),icon:h0.string().nullable().optional()}),uo1=h0.object({id:h0.string().describe("Stable id; used as React key and ?tab= value"),title:h0.string().describe("Tab label"),icon:h0.string().optional().describe("Optional lucide icon name"),view:h0.object({type:h0.literal("ext-app"),appId:h0.string(),args:h0.record(h0.string(),h0.unknown()).optional()})}),co1=h0.object({defaultMainView:h0.object({type:h0.string(),id:h0.string().optional(),toolName:h0.string().optional()}).nullable().optional(),chatDefaultOpen:h0.boolean().nullable().optional(),cmsDefaultOpen:h0.boolean().nullable().optional(),tabs:h0.array(uo1).optional()}),yo1=h0.object({tileId:h0.string().optional(),connectionId:h0.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:h0.string().describe("ui:// resource URI exposed by `connectionId`. Read on the home page and rendered via MCPAppRenderer."),toolName:h0.string().optional().describe("Tool name \u2014 identifies which tool's inputSchema to display when editing tile props."),toolInput:h0.record(h0.string(),h0.unknown()).optional().describe("User-configured input props passed to MCPAppRenderer when rendering the tile."),minHeight:h0.number().int().positive().optional(),maxHeight:h0.number().int().positive().optional()}),fm0=h0.object({banner:h0.string().nullable().optional(),bannerColor:h0.string().nullable().optional(),icon:h0.string().nullable().optional(),themeColor:h0.string().nullable().optional(),pinnedViews:h0.array(vp6).nullable().optional(),layout:co1.nullable().optional(),homeTile:yo1.nullable().optional(),homeTiles:h0.array(yo1).nullable().optional(),homePrompts:h0.array(h0.string()).nullable().optional()});i90=/^[A-Za-z_][A-Za-z0-9_]*$/,go1=h0.string().min(1).regex(i90,{message:"Env var key must start with a letter or underscore and contain only letters, digits, and underscores."}),fp6=h0.discriminatedUnion("kind",[h0.object({key:go1,kind:h0.literal("literal"),value:h0.string()}),h0.object({key:go1,kind:h0.literal("secret"),secretId:h0.string().min(1)})]),lo1=/^[a-zA-Z0-9.-]+(?::[0-9]+)?$/,bp6=h0.object({host:h0.string().min(1).regex(lo1).describe("Submodule host, e.g. 'github.com' (bare hostname, no scheme)."),secretId:h0.string().min(1).describe("Vault secret id holding the PAT used to fetch this host.")}),ym0=h0.object({selected:h0.string().nullable().optional().describe("User-selected package manager (npm | pnpm | yarn | bun | deno). Null/absent means autodetect on next SANDBOX_START."),port:h0.string().nullable().optional().describe("User-selected dev server port as a string (allows '' / null for unset). Null/absent means autodetect."),path:h0.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:h0.array(fp6).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:h0.array(bp6).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.")}),gm0=h0.object({url:h0.string().describe("GitHub repository URL"),owner:h0.string().describe("Repository owner"),name:h0.string().describe("Repository name"),installationId:h0.number().optional().describe("GitHub App installation ID. Absent when the repo was linked without a GitHub connection (public-clone mode)."),connectionId:h0.string().optional().describe("ID of the mcp-github connection used for authentication. Absent for public repos cloned without credentials.")}),yp6=h0.enum(["agent-sandbox","user-desktop"]),gp6=h0.enum(["agent-sandbox","user-desktop","cluster"]);do1={sandboxHandle:h0.string().describe("Provider-specific handle"),previewUrl:h0.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:h0.string().nullable().optional().describe("Daemon's public URL \u2014 what cluster\u2192daemon RPCs target. Equal to previewUrl for user-desktop; null/absent for the agent-sandbox provider (routes through hosted ingress)."),sandboxProviderKind:yp6.optional(),createdAt:h0.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:h0.object({packageManager:h0.string().nullable().optional().describe("metadata.runtime.selected at the time of SANDBOX_START"),port:h0.string().nullable().optional().describe("metadata.runtime.port at the time of SANDBOX_START"),path:h0.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.")},um0=h0.object(do1),hp6=h0.object({...do1,sandboxProviderKind:gp6.optional()});n90=h0.record(h0.string().describe("userId"),h0.record(h0.string().describe("branch"),h0.record(h0.string().describe("sandboxProviderKind"),um0)));up6=h0.object({id:h0.string().describe("Stable identifier for this knowledge file"),name:h0.string().describe("File name shown in the UI"),kind:h0.enum(["file","skill"]).optional().describe("'file' (a single document) or 'skill' (a Claude Code skill folder containing SKILL.md). Defaults to 'file'."),volume:h0.string().describe("Org filesystem (Library) volume the file lives in"),path:h0.string().describe("Path within the volume"),url:h0.string().describe("Same-origin URL to read the file (display/download)"),contentType:h0.string().nullable().optional().describe("MIME type, used to decide whether to inline the content"),size:h0.number().nullable().optional().describe("File size in bytes"),addedAt:h0.string().describe("ISO timestamp when the file was attached")}),lm0=h0.array(up6).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."),cp6=h0.enum(["smart","code-review","open"]),dm0=cp6.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."),mm0=h0.boolean().nullable().optional().describe("Enable Fast Preview: render the draft instantly on productionUrl's own page via a ?__draft pointer while the sandbox boots. Requires productionUrl to be set to take effect."),p7=h0.object({id:h0.string().describe("Unique identifier"),title:h0.string().describe("Human-readable name"),description:h0.string().nullable().describe("Description"),icon:h0.string().nullable().describe("Icon URL"),created_at:h0.string().describe("Creation timestamp"),updated_at:h0.string().describe("Last update timestamp"),created_by:h0.string().describe("User ID who created this item"),updated_by:h0.string().optional().describe("User ID who last updated this item"),organization_id:h0.string().describe("Organization ID this item belongs to"),status:h0.enum(["active","inactive"]).describe("Current status"),pinned:h0.boolean().describe("Whether this space is pinned to the sidebar"),metadata:h0.object({instructions:h0.string().nullable().describe("Instructions also used as system prompt"),enabled_plugins:h0.array(h0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:h0.array(h0.string()).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:h0.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:fm0.nullable().optional().describe("UI customization settings"),githubRepo:gm0.nullable().optional().describe("Linked GitHub repository"),runtime:ym0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:n90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:lm0,siteSlug:h0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:dm0,productionUrl:h0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:h0.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:mm0}).loose().describe("Metadata"),connections:h0.array(Yi).describe("Connections with their selected tools, resources, and prompts")}),im0=h0.object({title:h0.string().min(1).max(120).describe("Short label shown on the chip"),description:h0.string().max(280).optional().describe("One-line subtitle shown under the title"),text:h0.string().min(1).describe("The message sent to the agent when the prompt is clicked")}),p90=h0.object({title:h0.string().min(1).max(255).describe("Name for the virtual MCP"),description:h0.string().nullable().optional().describe("Optional description"),icon:h0.string().nullish().describe("Optional icon URL"),status:h0.enum(["active","inactive"]).optional().default("active").describe("Initial status"),pinned:h0.boolean().optional().default(!1).describe("Pin to sidebar"),metadata:h0.object({instructions:h0.string().nullable().optional().describe("MCP server instructions"),enabled_plugins:h0.array(h0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:h0.array(h0.string()).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:h0.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:fm0.nullable().optional().describe("UI customization settings"),githubRepo:gm0.nullable().optional().describe("Linked GitHub repository"),runtime:ym0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:n90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:lm0,siteSlug:h0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:dm0,productionUrl:h0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:h0.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:mm0}).loose().nullable().optional().describe("Additional metadata including MCP server instructions"),connections:h0.array(ho1).describe("Connections to include/exclude (can be empty for exclusion mode)"),prompts:h0.array(im0).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.")}),t90=h0.object({title:h0.string().min(1).max(255).optional().describe("New name"),description:h0.string().nullable().optional().describe("New description (null to clear)"),icon:h0.string().nullish().describe("New icon URL"),status:h0.enum(["active","inactive"]).optional().describe("New status"),pinned:h0.boolean().optional().describe("Pin/unpin from sidebar"),metadata:h0.object({instructions:h0.string().nullable().optional().describe("MCP server instructions"),enabled_plugins:h0.array(h0.string()).nullable().optional().describe("List of enabled plugin IDs"),subAgents:h0.array(h0.string()).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:h0.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:fm0.nullable().optional().describe("UI customization settings"),githubRepo:gm0.nullable().optional().describe("Linked GitHub repository"),runtime:ym0.nullable().optional().describe("User-pinned runtime config (package manager, dev port). Empty fields = autodetect."),sandboxMap:n90.optional().describe("Per-user, per-branch sandbox mapping: sandboxMap[userId][branch] -> { sandboxHandle, previewUrl }"),knowledge:lm0,siteSlug:h0.string().nullable().optional().describe("Linked asset site slug (managed storage tenancy)"),publishPolicy:dm0,productionUrl:h0.string().nullable().optional().describe("Live production URL of the linked site (e.g. https://acme.com). Painted in the preview iframe while the sandbox dev server is waking."),fieldDescriptionTooltips:h0.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:mm0}).loose().nullable().optional().describe("Additional metadata including MCP server instructions"),connections:h0.array(ho1).optional().describe("New connections (replaces existing)"),prompts:h0.array(im0).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 XE($){return lp6.has($)}var t7,lp6,o90;var no1=O(()=>{t7=["deco","anthropic","openrouter","llmapi","google","openai-compatible"],lp6=new Set(t7);o90=[...t7,"claude-code","codex"]});function nm0($,Z){return{id:crypto.randomUUID(),type:Gi.STEP,source:"decopilot",subject:$,data:{stepCount:Z},time:new Date().toISOString()}}function r90($,Z){return{id:crypto.randomUUID(),type:Gi.FINISH,source:"decopilot",subject:$,data:{status:Z},time:new Date().toISOString()}}function WW($,Z,X){return{id:crypto.randomUUID(),type:Gi.THREAD_STATUS,source:"decopilot",subject:$,data:{status:Z,...X?.messageId!==void 0&&{message_id:X.messageId},...X?.virtualMcpId!==void 0&&{virtual_mcp_id:X.virtualMcpId},...X?.createdBy!==void 0&&{created_by:X.createdBy},...X?.triggerId!==void 0&&{trigger_id:X.triggerId},...X?.title!==void 0&&{title:X.title},...X?.branch!==void 0&&{branch:X.branch},...X?.harnessId!==void 0&&{harness_id:X.harnessId},...X?.createdAt!==void 0&&{created_at:X.createdAt},...X?.updatedAt!==void 0&&{updated_at:X.updatedAt},...X?.metadata!==void 0&&{metadata:X.metadata}},time:new Date().toISOString()}}var po1,dp6,Gi,mp6;var to1=O(()=>{po1=["in_progress","requires_action","failed","completed"],dp6=[...po1,"expired"],Gi={STEP:"decopilot.step",FINISH:"decopilot.finish",THREAD_STATUS:"decopilot.thread.status"},mp6=Object.values(Gi)});var a90=O(()=>{bo1();io1();no1();to1()});function ro1($){return{id:t4.REGISTRY($),title:"Deco Store",description:"Official deco MCP registry with curated integrations",connection_type:"HTTP",connection_url:"https://studio.decocms.com/org/deco/registry/mcp",icon:"https://assets.decocache.com/decocms/00ccf6c3-9e13-4517-83b0-75ab84554bb9/596364c63320075ca58483660156b6d9de9b526e.png",app_name:"deco-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function ao1(){return{id:"community-registry",title:"MCP Registry",description:"Community MCP registry with thousands of handy MCPs",connection_type:"HTTP",connection_url:"https://sites-registry.deco.site/mcp",icon:"https://assets.decocache.com/decocms/cd7ca472-0f72-463a-b0de-6e44bdd0f9b4/mcp.png",app_name:"mcp-registry",app_id:null,connection_token:null,connection_headers:null,oauth_config:null,configuration_state:null,configuration_scopes:null,metadata:{isDefault:!0,type:"registry"}}}function so1($,Z){return{id:t4.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 eo1($,Z){return{id:t4.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 lY($){return{is(Z){if(!Z)return null;if(!Z.startsWith($))return null;return Z.slice($.length)||null},get(Z){return`${$}${Z}`}}}function $r1($){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 tm0($){return $r1({id:QE($),organizationId:$,title:"Super Agent",description:"Default agent that aggregates all organization connections",icon:ip6,ui:{layout:{defaultMainView:{type:"overview"},chatDefaultOpen:!0}}})}function Gr1($){return $r1({id:np6($),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:pp6})}function Wr1($,Z,X="https://reports.decocms.com/api/v2/mcp"){return{id:t4.COMMERCE_DISCOVERY($),title:"Store Report",description:"Your store's report and diagnostics",connection_type:"HTTP",connection_url:X,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 Hr1($,Z=t4.COMMERCE_DISCOVERY($)){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 Nr1($){if(!$)return!1;return Object.values(_N).some((Z)=>Z.is($)!==null)}function Ur1($){let Z=tm0($);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 t4,oo1="https://reports.decocms.com/api/v2/mcp",s90="get_my_diagnostic",Zr1,nG,QE,Xr1,Qr1,pm0,ip6="https://assets.decocache.com/decocms/fd07a578-6b1c-40f1-bc05-88a3b981695d/f7fc4ffa81aec04e37ae670c3cd4936643a7b269.png",Yr1,e90,np6,pp6,Jr1,O$5,L$5,Kr1,D$5,$Z0,_N,o7;var Fr1=O(()=>{t4={SELF:($)=>`${$}_self`,REGISTRY:($)=>`${$}_registry`,COMMUNITY_REGISTRY:($)=>`${$}_community-registry`,DEV_ASSETS:($)=>`${$}_dev-assets`,SITE_DIAGNOSTICS:($)=>`site-diagnostics_${$}`,COMMERCE_DISCOVERY:($)=>`${$}_commerce-discovery`};Zr1=lY("decopilot_"),nG=Zr1.is,QE=Zr1.get,Xr1=lY("dev_"),Qr1=Xr1.get,pm0=Xr1.is;Yr1=lY("brand-context-setup_"),e90=Yr1.is,np6=Yr1.get,pp6=`
|
|
1314
1314
|
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:
|
|
1315
1315
|
|
|
1316
1316
|
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.
|