decocms 2.293.1 → 2.293.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/dist/client/assets/{AlertCircle-CLDKU5ty.js → AlertCircle-4XN-oNOX.js} +1 -1
  2. package/dist/client/assets/{ArrowNarrowLeft-RDc6uuv4.js → ArrowNarrowLeft-D8yM0Q1N.js} +1 -1
  3. package/dist/client/assets/{ArrowUpRight-DPl82rO4.js → ArrowUpRight-B67Jmwiu.js} +1 -1
  4. package/dist/client/assets/{CheckCircle-CfXA9jn1.js → CheckCircle-qPp83BHz.js} +1 -1
  5. package/dist/client/assets/{ChevronDown-Usw-ptYZ.js → ChevronDown-CyeG22oM.js} +1 -1
  6. package/dist/client/assets/{ChevronRight-DoCnX9k7.js → ChevronRight-VHKE-Rsb.js} +1 -1
  7. package/dist/client/assets/{ChevronUp-DQfNemJG.js → ChevronUp-DI0U_n7m.js} +1 -1
  8. package/dist/client/assets/{Container-GOtpXA1D.js → Container-gs_T0E-i.js} +1 -1
  9. package/dist/client/assets/{DotsVertical-BVfKaEFA.js → DotsVertical-DbazSleD.js} +1 -1
  10. package/dist/client/assets/{LinkExternal01-CZs0wlF4.js → LinkExternal01-BkW1xExI.js} +1 -1
  11. package/dist/client/assets/{Lock01-QeXCU7HG.js → Lock01-DMhOUHAD.js} +1 -1
  12. package/dist/client/assets/{Palette-CSJaxEgx.js → Palette-DQFLrWeu.js} +1 -1
  13. package/dist/client/assets/{Play-JGp_Cbfe.js → Play-CEfYOhlu.js} +1 -1
  14. package/dist/client/assets/{Plus-kEeRyUxB.js → Plus-C6dQCrro.js} +1 -1
  15. package/dist/client/assets/{RefreshCcw01-CsMevI8O.js → RefreshCcw01-BS4qqpX3.js} +1 -1
  16. package/dist/client/assets/{SearchMd-Ytd6c0ll.js → SearchMd-BG4FSg84.js} +1 -1
  17. package/dist/client/assets/{Settings02-CvrBlbBO.js → Settings02-iDL3vBWr.js} +1 -1
  18. package/dist/client/assets/{Shield01-cPWG6TNA.js → Shield01-CNiHl3zX.js} +1 -1
  19. package/dist/client/assets/{Star01-B6e6dHYY.js → Star01-BwinVzGY.js} +1 -1
  20. package/dist/client/assets/{Sun-4ELQnnMk.js → Sun-D2tIZY2E.js} +1 -1
  21. package/dist/client/assets/{Tool01-CuB7oJgS.js → Tool01-DjdxENGC.js} +1 -1
  22. package/dist/client/assets/{Trash01-DqxI7G9k.js → Trash01-CSKwBK9N.js} +1 -1
  23. package/dist/client/assets/{User01-C3LXYecz.js → User01-CdBYXDNb.js} +1 -1
  24. package/dist/client/assets/{Users03-CZCjMbp7.js → Users03-TaweCJsF.js} +1 -1
  25. package/dist/client/assets/{X-BgNHGeBl.js → X-BM6L1DFq.js} +1 -1
  26. package/dist/client/assets/{XCircle-BCIvjJwm.js → XCircle-Dr-Lbcly.js} +1 -1
  27. package/dist/client/assets/{XClose-Dt9YjXZl.js → XClose-D29zR7_1.js} +1 -1
  28. package/dist/client/assets/{Zap-o1d5pHAU.js → Zap-CoAb7KxV.js} +1 -1
  29. package/dist/client/assets/{ZapSquare-Dr7dOlmN.js → ZapSquare-BF7VYQ5u.js} +1 -1
  30. package/dist/client/assets/{accordion-CWNMyDuM.js → accordion-Coir_NgB.js} +1 -1
  31. package/dist/client/assets/{agent-icon-i3_kgSR-.js → agent-icon-DgS8BLJO.js} +1 -1
  32. package/dist/client/assets/{agents-list-CK-l2CpG.js → agents-list-v8aeb2Fn.js} +1 -1
  33. package/dist/client/assets/ai-providers-BTx7ia27.js +1 -0
  34. package/dist/client/assets/{alert-dialog-ie0qXApM.js → alert-dialog-CGnwkAYP.js} +1 -1
  35. package/dist/client/assets/{auth-catchall-Dj8R_Rwm.js → auth-catchall-CUQuENbK.js} +1 -1
  36. package/dist/client/assets/{automation-list-row-D7-YDk3w.js → automation-list-row-BOuwI-Wo.js} +1 -1
  37. package/dist/client/assets/{automations-xbWUh_bL.js → automations-C0ef_NDE.js} +1 -1
  38. package/dist/client/assets/{avatar-BF0gecl5.js → avatar-Cp7qKMot.js} +1 -1
  39. package/dist/client/assets/{badge-CrcJY3ID.js → badge-ByGXA99d.js} +1 -1
  40. package/dist/client/assets/{brand-context-vId15hS7.js → brand-context-l990DZmF.js} +1 -1
  41. package/dist/client/assets/{card-01NEpYK9.js → card-DAFmpl_H.js} +1 -1
  42. package/dist/client/assets/{chat-context-H8YpdoaC.js → chat-context-DMjcGz00.js} +1 -1
  43. package/dist/client/assets/{checkbox-BMFPeDen.js → checkbox-DNI--1wo.js} +1 -1
  44. package/dist/client/assets/{collection-detail-CVtRJ6yq.js → collection-detail-TqBqgSyp.js} +1 -1
  45. package/dist/client/assets/{collection-display-button-D8nhcebp.js → collection-display-button-DnhwGJJn.js} +1 -1
  46. package/dist/client/assets/{collection-search-DRnCFAYG.js → collection-search-Db0QcwfF.js} +1 -1
  47. package/dist/client/assets/{collection-search-BG6Gw4Mu.js → collection-search-Dnsuh1PU.js} +1 -1
  48. package/dist/client/assets/{collection-table-wrapper-DrkGtEjc.js → collection-table-wrapper-CmdnCMC2.js} +1 -1
  49. package/dist/client/assets/{collection-tabs-L0YkmPvP.js → collection-tabs-DHyusu9H.js} +1 -1
  50. package/dist/client/assets/{collections-Olx1K63T.js → collections-BtAHo729.js} +1 -1
  51. package/dist/client/assets/{command-DI2dHNgp.js → command-gP-fjc6e.js} +1 -1
  52. package/dist/client/assets/{connection-card-CvPCQDGo.js → connection-card-BpV_oIzL.js} +1 -1
  53. package/dist/client/assets/{connection-detail-CZ3vtcMC.js → connection-detail-CgW9j0Ig.js} +1 -1
  54. package/dist/client/assets/{connection-form-helpers-cVTgOTdv.js → connection-form-helpers-DsUdihal.js} +1 -1
  55. package/dist/client/assets/{connections-fmCwo_L1.js → connections-D9LebqS8.js} +1 -1
  56. package/dist/client/assets/{constants-CGJZhWnl.js → constants-rS7kDjs8.js} +1 -1
  57. package/dist/client/assets/{constants-BXz_d4fe.js → constants-wYGHmqEw.js} +1 -1
  58. package/dist/client/assets/{dialog-CPyR3COo.js → dialog-CgllGihU.js} +1 -1
  59. package/dist/client/assets/{domain-settings-CvjA4NN4.js → domain-settings-DJjAq1LR.js} +1 -1
  60. package/dist/client/assets/{drawer-BZLEopRK.js → drawer-DuBBob4t.js} +1 -1
  61. package/dist/client/assets/{dropdown-menu-Buw-c9bt.js → dropdown-menu-BG2UDvir.js} +1 -1
  62. package/dist/client/assets/{dynamic-plugin-layout-BHSnTyV8.js → dynamic-plugin-layout-0o-Ag6fQ.js} +1 -1
  63. package/dist/client/assets/{empty-state-CxuGKoUZ.js → empty-state-Ci9wpE4f.js} +1 -1
  64. package/dist/client/assets/{empty-state-BKkZQAbY.js → empty-state-DWcstHYO.js} +1 -1
  65. package/dist/client/assets/{extract-connection-data-CIPWZJW-.js → extract-connection-data-DjV0tcfo.js} +1 -1
  66. package/dist/client/assets/{features-iyOKXl3K.js → features-BtcTR8s0.js} +1 -1
  67. package/dist/client/assets/{form-BIoYTmyg.js → form-peQyLbDW.js} +1 -1
  68. package/dist/client/assets/{general-Cij7c2aO.js → general-_MKib7Ow.js} +1 -1
  69. package/dist/client/assets/{index-DacOWTuH.js → index-B3z6UTdH.js} +1 -1
  70. package/dist/client/assets/{index-B1JV7ppc.js → index-B74vbIoj.js} +1 -1
  71. package/dist/client/assets/{index-BnX-CFDs.js → index-BOKdO59b.js} +1 -1
  72. package/dist/client/assets/{index-1Z2oT3ji.js → index-BdEBb_Nw.js} +1 -1
  73. package/dist/client/assets/{index-DH9f3GXN.js → index-C_heSJg7.js} +1 -1
  74. package/dist/client/assets/{index-CwjvmiaK.js → index-DXg98Kgh.js} +1 -1
  75. package/dist/client/assets/{index-BbKvWA-n.js → index-DgjPAgtK.js} +1 -1
  76. package/dist/client/assets/{index-D6qhB-mw.js → index-DiTVOGvz.js} +3 -3
  77. package/dist/client/assets/{index-ZcQ1r47L.js → index-LFRnW2ND.js} +1 -1
  78. package/dist/client/assets/{index-B-ip_PBd.js → index-LU0fMnAB.js} +1 -1
  79. package/dist/client/assets/{index-CQwg4ynB.js → index-MNgoaxoh.js} +1 -1
  80. package/dist/client/assets/{index-CwyFo3x2.js → index-OH48I7pr.js} +1 -1
  81. package/dist/client/assets/index-YF1wX-UW.js +1 -0
  82. package/dist/client/assets/{index-BIWc3bwF.js → index-bn7bZZHA.js} +1 -1
  83. package/dist/client/assets/{index-BAv6Y8f_.js → index-nHVmAR-G.js} +1 -1
  84. package/dist/client/assets/{index-CFahKaOM.js → index-nLaCFF9u.js} +2 -2
  85. package/dist/client/assets/{infiniteQueryObserver-Cuq-6B7N.js → infiniteQueryObserver-3VUkrTvV.js} +1 -1
  86. package/dist/client/assets/{input-BohjAJ_4.js → input-CxJ-WrlI.js} +1 -1
  87. package/dist/client/assets/{integration-icon-B4agjmMV.js → integration-icon-DGTz3Rke.js} +1 -1
  88. package/dist/client/assets/{label-DyQV2LLm.js → label-CiLZir7w.js} +1 -1
  89. package/dist/client/assets/{layout-DV29n77Q.js → layout-DZRRSA8c.js} +1 -1
  90. package/dist/client/assets/{lean-canvas-recruit-modal-4tZiJJkU.js → lean-canvas-recruit-modal-B6pKKzDY.js} +1 -1
  91. package/dist/client/assets/{login-CyTM-pJp.js → login-0pt_pLM-.js} +1 -1
  92. package/dist/client/assets/{members-DzL0o7-6.js → members-CBrB08fu.js} +1 -1
  93. package/dist/client/assets/{monaco-editor-CLkShlci.js → monaco-editor-QaYaFffZ.js} +1 -1
  94. package/dist/client/assets/{monitoring-stats-row-Cf6Vkgx7.js → monitoring-stats-row-CC4if2Pk.js} +1 -1
  95. package/dist/client/assets/{oauth-callback-IG63Z6_T.js → oauth-callback-BnBWfStn.js} +1 -1
  96. package/dist/client/assets/{oauth-callback-ai-provider-BzUPIaWs.js → oauth-callback-ai-provider-FmGgb156.js} +1 -1
  97. package/dist/client/assets/{onboarding-EN15kkwD.js → onboarding-BAcUKNjA.js} +1 -1
  98. package/dist/client/assets/{org-layout-D86hlO7v.js → org-layout-Cdo1rsPD.js} +1 -1
  99. package/dist/client/assets/{org-plugin-layout-BD1VTnDi.js → org-plugin-layout-CJTAves4.js} +1 -1
  100. package/dist/client/assets/{pair-BCm4UAGD.js → pair-Cn8FPqtQ.js} +1 -1
  101. package/dist/client/assets/{plugin-empty-state-DkZODBFG.js → plugin-empty-state-3UOe7lZW.js} +1 -1
  102. package/dist/client/assets/{plugin-header-Bpo7VOQ5.js → plugin-header-B5pM8KBx.js} +1 -1
  103. package/dist/client/assets/{plugin-layout-BBKyCNXN.js → plugin-layout-Dolxv79h.js} +1 -1
  104. package/dist/client/assets/{popover-DneAjpKm.js → popover-Cvm-SdUL.js} +1 -1
  105. package/dist/client/assets/{profile-DicwTKH1.js → profile-6X1yOQdP.js} +1 -1
  106. package/dist/client/assets/{project-app-view-BzdtqqIo.js → project-app-view-DvvsU4iK.js} +1 -1
  107. package/dist/client/assets/registry-BRp6r677.js +2 -0
  108. package/dist/client/assets/{registry-layout-BuxPc_PJ.js → registry-layout-ysBoW9Tl.js} +1 -1
  109. package/dist/client/assets/{required-auth-layout-Br303SqN.js → required-auth-layout-Dt4K21Pv.js} +1 -1
  110. package/dist/client/assets/{reset-password-C3HV9JXm.js → reset-password-D9X98cz3.js} +1 -1
  111. package/dist/client/assets/{roles-CU1Cxmpd.js → roles-CMH_sOBL.js} +1 -1
  112. package/dist/client/assets/{scroll-area-DlG8UFJF.js → scroll-area-B9wKEneG.js} +1 -1
  113. package/dist/client/assets/{search-input-Bjfid_id.js → search-input-Iq7HC3LH.js} +1 -1
  114. package/dist/client/assets/{select-gZj19OqY.js → select-Dp6b6p2r.js} +1 -1
  115. package/dist/client/assets/{select-model-Ly7oy5vK.js → select-model-DeRXZx8w.js} +1 -1
  116. package/dist/client/assets/{settings-layout-C78KOlkk.js → settings-layout-BFjzzOzQ.js} +1 -1
  117. package/dist/client/assets/{settings-section-CdYoZh3R.js → settings-section-CcHh5CZ5.js} +1 -1
  118. package/dist/client/assets/{shell-layout-CNVN1Xii.js → shell-layout-CTaFLMGl.js} +1 -1
  119. package/dist/client/assets/{skeleton-CYEDV6V5.js → skeleton-CDQUGJcQ.js} +1 -1
  120. package/dist/client/assets/{sso-kC99uSB8.js → sso-B_-8dtd-.js} +1 -1
  121. package/dist/client/assets/{store-CPqdUdbg.js → store-ChD7IrAK.js} +1 -1
  122. package/dist/client/assets/store-registry-BfmheXNd.js +2 -0
  123. package/dist/client/assets/{switch-CSQQwNd5.js → switch-BbpeJgOD.js} +1 -1
  124. package/dist/client/assets/{table-EnhZuihn.js → table-CaKZ3cPw.js} +1 -1
  125. package/dist/client/assets/{tabs-BiZc3mdZ.js → tabs-Bpw0FkOs.js} +1 -1
  126. package/dist/client/assets/{task-status-yVhre1Eq.js → task-status-D4v7A72x.js} +1 -1
  127. package/dist/client/assets/{textarea-DfNIu9yW.js → textarea-BBmPaG6M.js} +1 -1
  128. package/dist/client/assets/{toggle-group-CsTz1qk2.js → toggle-group-C_JrOUcW.js} +1 -1
  129. package/dist/client/assets/{tools-list-BkX_uGL9.js → tools-list-Cs6nuh3D.js} +1 -1
  130. package/dist/client/assets/{tooltip-V_Rb6MNZ.js → tooltip-Blwixkut.js} +1 -1
  131. package/dist/client/assets/{types-LzWcp-KY.js → types-DpciA73e.js} +1 -1
  132. package/dist/client/assets/{use-ai-providers-CKfNcci8.js → use-ai-providers-rg7SDdrG.js} +1 -1
  133. package/dist/client/assets/{use-collections-DcqDFIJE.js → use-collections-DVujTX05.js} +1 -1
  134. package/dist/client/assets/{use-connection-DMd3gQky.js → use-connection-nEqGCm80.js} +1 -1
  135. package/dist/client/assets/{use-copy-CqokAoTf.js → use-copy-nEKil52f.js} +1 -1
  136. package/dist/client/assets/{use-create-virtual-mcp-DOAJogil.js → use-create-virtual-mcp-CJOu0k7Y.js} +1 -1
  137. package/dist/client/assets/{use-decopilot-events-CK7K1FCP.js → use-decopilot-events-Dp8JTZoZ.js} +1 -1
  138. package/dist/client/assets/{use-delete-connection-BZs0jQgt.js → use-delete-connection-NSYjKXy5.js} +1 -1
  139. package/dist/client/assets/{use-infinite-scroll-srxCZX29.js → use-infinite-scroll-DS1Ojgkb.js} +1 -1
  140. package/dist/client/assets/{use-list-state-C40IyQ5t.js → use-list-state-CzARiSqi.js} +1 -1
  141. package/dist/client/assets/{use-mcp-tools-B1ZDkVHC.js → use-mcp-tools-C_I_UoaG.js} +1 -1
  142. package/dist/client/assets/{use-members-CdKQAO9T.js → use-members-CICoDwmh.js} +1 -1
  143. package/dist/client/assets/{use-navigate-to-agent-Dga1Bhy4.js → use-navigate-to-agent-DLCGg_uR.js} +1 -1
  144. package/dist/client/assets/{use-org-sso-DfoBK0ag.js → use-org-sso-L8cXZrkC.js} +1 -1
  145. package/dist/client/assets/{use-organization-roles-Bq4hoskJ.js → use-organization-roles-DRlygqeg.js} +1 -1
  146. package/dist/client/assets/{use-organization-settings-C75c-v86.js → use-organization-settings-DvZsMop0.js} +1 -1
  147. package/dist/client/assets/{use-registry-connections-HIXjhu0m.js → use-registry-connections-DfviabXS.js} +1 -1
  148. package/dist/client/assets/{use-status-sounds-Doh_awWx.js → use-status-sounds-BcWByl3m.js} +1 -1
  149. package/dist/client/assets/{use-tasks-BAqdxtKe.js → use-tasks-Bv2M0xJo.js} +1 -1
  150. package/dist/client/assets/{use-view-mode-CuDuiIvs.js → use-view-mode-c-k92Bn-.js} +1 -1
  151. package/dist/client/assets/{use-virtual-mcp-kH1PMy03.js → use-virtual-mcp-C3DHL0da.js} +1 -1
  152. package/dist/client/assets/useInfiniteQuery-DIYNhUoD.js +1 -0
  153. package/dist/client/assets/useSuspenseInfiniteQuery-CjcqsQRh.js +1 -0
  154. package/dist/client/assets/{user-BaXkR2l6.js → user-CAmkHDzZ.js} +1 -1
  155. package/dist/client/assets/{view-mode-toggle-B3PPiEz2.js → view-mode-toggle-C1Cefw00.js} +1 -1
  156. package/dist/client/assets/{workflow-idtrPQXc.js → workflow-BxmLyBCm.js} +1 -1
  157. package/dist/client/assets/workflow-detail-C5OVB3zC.js +1 -0
  158. package/dist/client/index.html +1 -1
  159. package/dist/server/cli.js +28 -4
  160. package/dist/server/node_modules/pg-int8/LICENSE +13 -0
  161. package/dist/server/node_modules/pg-int8/README.md +16 -0
  162. package/dist/server/node_modules/pg-int8/index.js +100 -0
  163. package/dist/server/node_modules/pg-int8/package.json +24 -0
  164. package/dist/server/node_modules/postgres-array/index.d.ts +4 -0
  165. package/dist/server/node_modules/postgres-array/index.js +97 -0
  166. package/dist/server/node_modules/postgres-array/package.json +35 -0
  167. package/dist/server/node_modules/postgres-array/readme.md +43 -0
  168. package/dist/server/node_modules/postgres-bytea/index.js +33 -0
  169. package/dist/server/node_modules/{xtend/LICENSE → postgres-bytea/license} +2 -1
  170. package/dist/server/node_modules/{postgres-date → postgres-bytea}/package.json +8 -7
  171. package/dist/server/node_modules/postgres-bytea/readme.md +34 -0
  172. package/dist/server/server.js +27 -3
  173. package/package.json +1 -1
  174. package/dist/client/assets/ai-providers-LWQHbAfP.js +0 -1
  175. package/dist/client/assets/index-BkfyW-B8.js +0 -1
  176. package/dist/client/assets/registry-DYndR3Xa.js +0 -2
  177. package/dist/client/assets/store-registry-D4fRmaFj.js +0 -2
  178. package/dist/client/assets/useInfiniteQuery-IC7YnrCe.js +0 -1
  179. package/dist/client/assets/useSuspenseInfiniteQuery-Diu74tq9.js +0 -1
  180. package/dist/client/assets/workflow-detail-BUCojV1U.js +0 -1
  181. package/dist/server/node_modules/ansi-styles/index.d.ts +0 -236
  182. package/dist/server/node_modules/ansi-styles/index.js +0 -223
  183. package/dist/server/node_modules/ansi-styles/license +0 -9
  184. package/dist/server/node_modules/ansi-styles/package.json +0 -54
  185. package/dist/server/node_modules/ansi-styles/readme.md +0 -173
  186. package/dist/server/node_modules/postgres-date/index.js +0 -116
  187. package/dist/server/node_modules/postgres-date/readme.md +0 -49
  188. package/dist/server/node_modules/xtend/.jshintrc +0 -30
  189. package/dist/server/node_modules/xtend/README.md +0 -32
  190. package/dist/server/node_modules/xtend/immutable.js +0 -19
  191. package/dist/server/node_modules/xtend/mutable.js +0 -17
  192. package/dist/server/node_modules/xtend/package.json +0 -55
  193. package/dist/server/node_modules/xtend/test.js +0 -103
  194. /package/dist/server/node_modules/{postgres-date → postgres-array}/license +0 -0
@@ -1636,7 +1636,7 @@ AS SELECT
1636
1636
  FROM monitoring_metrics
1637
1637
  GROUP BY organization_id, name, bucket, connection_id, tool_name, status
1638
1638
  `}),console.log("[clickhouse-schema] monitoring_metrics_rollup_1m_mv view ready")}finally{await G.close()}}catch(Y){console.error("[clickhouse-schema] Failed to create rollup DDL (queries will fall back to raw table):",Y)}}async function jA1(X){let Y={...process.env},G=f$1(X,Y),Q=G.settings.encryptionKey;console.log(`[settings] ENCRYPTION_KEY = ${JSON.stringify(Q)} (${Q.length} chars)`);let{ensureServices:J}=await Promise.resolve().then(() => (E$1(),L$1)),{outputs:W,services:Z}=await J({home:G.settings.dataDir,externalDatabaseUrl:G.externalDatabaseUrl,externalNatsUrl:G.externalNatsUrl});if(!G.skipMigrations){let{migrateBetterAuth:K}=await Promise.resolve().then(() => (U30(),Px6));await K(W.databaseUrl);let{createDatabase:H}=await Promise.resolve().then(() => (JU(),Ex6)),{migrateToLatest:U}=await Promise.resolve().then(() => (Vr6(),Ir6)),B=H(W.databaseUrl);await U({keepOpen:!0,database:B,skipBetterAuth:!0})}if(G.settings.clickhouseUrl){let{ensureClickHouseRollup:K}=await Promise.resolve().then(() => js6);await K(G.settings.clickhouseUrl)}let $={...G.settings,databaseUrl:W.databaseUrl,natsUrls:W.natsUrls};return Pl0($),{settings:$,services:Z.map((K)=>({name:K.name==="PostgreSQL"?"Postgres":K.name,port:K.port})),managedServiceNames:Z.filter((K)=>K.owner==="managed").map((K)=>K.name)}}var yB0=D(()=>{an1();m9()});import{createServer as Ms6}from"net";function oi5(X){return new Promise((Y)=>{let G=Ms6();G.once("error",()=>Y(!1)),G.listen(X,"0.0.0.0",()=>{G.close(()=>Y(!0))})})}async function MA1(X){if(await oi5(X))return X;let Y=await new Promise((G,Q)=>{let J=Ms6();J.once("error",Q),J.listen(0,"0.0.0.0",()=>{let W=J.address(),Z=typeof W==="object"&&W?W.port:0;J.close(()=>G(Z))})});return console.warn(`Port ${X} is in use, using port ${Y} instead.`),Y}var xB0=()=>{};var hB0={};M0(hB0,{startDevServer:()=>ei5});import{join as si5}from"path";function Rs6(X){return X.replace(/\x1b\[[0-9;]*m/g,"")}function Ss6(X){let Y=X.getReader(),G=new TextDecoder,Q="";function J(){let W=Q.split(`
1639
- `);Q=W.pop()??"";for(let Z of W){let $=Rs6(Z).replace(/^\[\d+\]\s*/,"").trim();if(!$)continue;EK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:$})}}(async()=>{for(;;){let{done:W,value:Z}=await Y.read();if(W)break;Q+=G.decode(Z,{stream:!0}),J()}if(Q.trim()){let W=Rs6(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)EK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function ei5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await MA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await jA1({port:String(J),home:X.home,baseUrl:X.baseUrl,localMode:X.localMode,skipMigrations:X.skipMigrations,noTui:X.noTui,vitePort:X.vitePort});for(let z of Z)Ad({name:z.name,status:"ready",port:z.port});Ce(W),Re();let K=si5(import.meta.dir,"..","..","..","..",".."),H=Q===!0,U=Bun.spawn(["bun","run","--cwd=apps/mesh","dev:servers"],{cwd:K,env:{...process.env,PORT:String(W.port),VITE_PORT:String(Y),DATABASE_URL:W.databaseUrl,NATS_URL:W.natsUrls.join(","),NODE_ENV:W.nodeEnv,DECOCMS_LOCAL_MODE:String(W.localMode),DECOCMS_HOME:W.dataDir,DATA_DIR:W.dataDir,DECO_CLI:"1",...W.baseUrl?{BASE_URL:W.baseUrl}:{}},stdio:["inherit",H?"inherit":"pipe",H?"inherit":"pipe"]});if(!H)Ss6(U.stdout),Ss6(U.stderr);let B=G||`http://localhost:${W.port}`;Se(B),Ad({name:"Vite",status:"ready",port:Number(Y)});let N=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (E$1(),L$1));await O(W.dataDir)}};return process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM")),{port:Number(W.port),process:U}}var gB0=D(()=>{yB0();GF();xB0()});import{Box as uB0,Text as lB0}from"ink";import{jsx as ks6,jsxs as RA1}from"react/jsx-runtime";function Cs6(X){if(!X)return"not set";try{let Y=new URL(X);if(Y.password)Y.password="***";if(Y.username&&Y.username.length>3)Y.username=Y.username.slice(0,3)+"***";return Y.pathname="/",Y.search="",Y.hash="",Y.toString()}catch{if(X.length<=10)return X;return X.slice(0,6)+"***"+X.slice(-4)}}function Gp5(X,Y){if(Xp5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(Yp5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>Cs6(W)).join(", "),color:"cyan"}}let Q=Cs6(Y);return Q==="not set"?{text:Q,dimColor:!0}:{text:Q,color:"cyan"}}if(Y===void 0||Y===null||Y==="")return{text:"not set",dimColor:!0};let G=String(Y);if(G==="true")return{text:G,color:"green"};if(G==="false")return{text:G,color:"yellow"};try{return new URL(G),{text:G,color:"cyan"}}catch{return{text:G}}}function Qp5(X){return[{title:"Core",entries:[{key:"NODE_ENV",value:X.nodeEnv},{key:"PORT",value:X.port},{key:"BASE_URL",value:X.baseUrl??`http://localhost:${X.port}`},{key:"DATA_DIR",value:X.dataDir}]},{title:"Database",entries:[{key:"DATABASE_URL",value:X.databaseUrl},{key:"DATABASE_PG_SSL",value:X.databasePgSsl}]},{title:"Auth & Secrets",entries:[{key:"BETTER_AUTH_SECRET",value:X.betterAuthSecret},{key:"ENCRYPTION_KEY",value:X.encryptionKey},{key:"MESH_JWT_SECRET",value:X.meshJwtSecret},{key:"STUDIO_PROVISION_SECRET_KEY",value:X.studioProvisionSecretKey},{key:"DISABLE_RATE_LIMIT",value:X.disableRateLimit}]},{title:"Auth Providers",entries:[{key:"AUTH_EMAIL_PASSWORD_ENABLED",value:process.env.AUTH_EMAIL_PASSWORD_ENABLED??"true"},{key:"AUTH_GOOGLE_CLIENT_ID",value:!!process.env.AUTH_GOOGLE_CLIENT_ID},{key:"AUTH_GITHUB_CLIENT_ID",value:!!process.env.AUTH_GITHUB_CLIENT_ID},{key:"AUTH_RESEND_API_KEY",value:!!process.env.AUTH_RESEND_API_KEY},{key:"AUTH_SENDGRID_API_KEY",value:!!process.env.AUTH_SENDGRID_API_KEY},{key:"AUTH_SSO_MS_CLIENT_ID",value:!!process.env.AUTH_SSO_MS_CLIENT_ID},{key:"AUTH_MAGIC_LINK_ENABLED",value:process.env.AUTH_MAGIC_LINK_ENABLED==="true"},{key:"AUTH_EMAIL_OTP_ENABLED",value:process.env.AUTH_EMAIL_OTP_ENABLED==="true"}]},{title:"Observability",entries:[{key:"CLICKHOUSE_URL",value:X.clickhouseUrl},{key:"OTEL_SERVICE_NAME",value:X.otelServiceName}]},{title:"Event Bus & Networking",entries:[{key:"NATS_URL",value:X.natsUrls}]},{title:"Config Files",entries:[{key:"CONFIG_PATH",value:X.configPath}]},{title:"Transport",entries:[{key:"UNSAFE_ALLOW_STDIO_TRANSPORT",value:X.unsafeAllowStdioTransport}]},{title:"AI Gateway",entries:[{key:"DECO_AI_GATEWAY_ENABLED",value:X.aiGatewayEnabled},{key:"DECO_AI_GATEWAY_URL",value:X.aiGatewayUrl}]}]}function vs6({env:X}){let Y=Qp5(X);return ks6(uB0,{flexDirection:"column",children:Y.map((G)=>RA1(uB0,{flexDirection:"column",marginTop:1,children:[RA1(lB0,{dimColor:!0,children:[" ","\u2500\u2500 ",G.title," ","\u2500".repeat(Math.max(0,38-G.title.length))]}),G.entries.map(({key:Q,value:J})=>{let W=Gp5(Q,J);return RA1(uB0,{children:[RA1(lB0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),ks6(lB0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var Xp5,Yp5;var _s6=D(()=>{Xp5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),Yp5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var mB0;var fs6=D(()=>{mB0={name:"decocms",version:"2.293.1",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/mesh"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:'bun run migrate && concurrently "bun run dev:client" "bun run dev:server"',"dev:servers":'concurrently "bun run dev:client" "bun run dev:server"',"dev:client":"bun --bun vite dev","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts","build:client":"bun --bun vite build","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","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","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run build:client && bun run build:server"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1","@freestyle-sh/with-bun":"^0.2.12","@freestyle-sh/with-deno":"^0.0.4","@freestyle-sh/with-nodejs":"^0.2.9","freestyle-sandboxes":"^0.1.46"},dependencies:{"@ai-sdk/anthropic":"^3.0.58","@ai-sdk/google":"^3.0.60","@ai-sdk/openai":"^3.0.50","@anthropic-ai/sdk":"^0.79.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dnd-kit/core":"^6.3.1","@dnd-kit/sortable":"^10.0.0","@dnd-kit/utilities":"^3.2.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/ext-apps":"^1.2.2","@openrouter/ai-sdk-provider":"^2.2.5","@opentelemetry/core":"^2.6.0","@tanstack/react-virtual":"^3.13.21","@xterm/addon-fit":"^0.11.0","@xterm/xterm":"^6.0.0","ai-sdk-provider-claude-code":"^3.4.4","ai-sdk-provider-codex-cli":"^1.1.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12",nats:"^2.29.3","posthog-js":"^1.371.1","posthog-node":"^5.0.0",react:"^19.2.0","react-dom":"^19.2.0"},devDependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/react":"^3.0.118","@anthropic-ai/claude-agent-sdk":"^0.2.80","@better-auth/sso":"1.4.1","@daveyplate/better-auth-ui":"^3.2.7","@deco/ui":"workspace:*","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/mesh-sdk":"workspace:*","@decocms/runtime":"workspace:*","@decocms/vite-plugin":"workspace:*","@electric-sql/pglite":"^0.3.15","@floating-ui/react":"^0.27.16","@hookform/resolvers":"^5.2.2","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.27.1","@monaco-editor/react":"^4.7.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@playwright/test":"^1.58.2","@radix-ui/react-avatar":"^1.1.10","@radix-ui/react-checkbox":"^1.3.3","@radix-ui/react-dialog":"^1.1.15","@radix-ui/react-dropdown-menu":"^2.1.16","@radix-ui/react-label":"^2.1.7","@radix-ui/react-select":"^2.2.6","@radix-ui/react-separator":"^1.1.7","@radix-ui/react-slot":"^1.2.3","@radix-ui/react-tabs":"^1.1.13","@rjsf/core":"^6.1.2","@rjsf/shadcn":"^6.1.2","@rjsf/utils":"^6.1.2","@rjsf/validator-ajv8":"^6.1.2","@tailwindcss/vite":"^4.1.17","@tanstack/react-query":"5.90.11","@tanstack/react-router":"^1.139.7","@tiptap/core":"3.20.2","@tiptap/extension-mention":"3.20.2","@tiptap/extension-placeholder":"3.20.2","@tiptap/pm":"3.20.2","@tiptap/react":"3.20.2","@tiptap/starter-kit":"3.20.2","@tiptap/suggestion":"3.20.2","@types/bun":"^1.3.1","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@untitledui/icons":"^0.0.19","@vercel/nft":"^1.1.1","@vitejs/plugin-react":"^5.1.0",ai:"^6.0.116","babel-plugin-react-compiler":"^1.0.0","better-auth":"1.4.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",concurrently:"^9.2.1",croner:"^9.1.0","date-fns":"^4.1.0",degit:"^2.8.4",hono:"^4.10.7","input-otp":"^1.4.2",jose:"^6.0.11","kysely-pglite":"^0.6.1","lucide-react":"^0.468.0",marked:"^15.0.6","@decocms/sandbox":"workspace:*","mesh-plugin-workflows":"workspace:*",nanoid:"^5.1.6",pg:"^8.16.3",prettier:"^3.4.2","react-hook-form":"^7.66.0","react-markdown":"^10.1.0","react-resizable-panels":"^2.1.7","react-syntax-highlighter":"^15.6.1",recharts:"^3.6.0","rehype-raw":"^7.0.0","remark-gfm":"^4.0.0","sass-embedded":"^1.97.2",sonner:"^2.0.7","tailwind-merge":"^3.3.1",tailwindcss:"^4.1.17",typescript:"^5.9.3",vite:"^7.2.1","vite-tsconfig-paths":"^5.1.4",zod:"^4.0.0",zustand:"^5.0.9"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","mesh","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as AU,Text as MX}from"ink";import{Spinner as Zp5}from"@inkjs/ui";import{useSyncExternalStore as bs6}from"react";import{jsx as qY,jsxs as oQ}from"react/jsx-runtime";function Fp5(X,Y){if(!X||!Hp5.has(X))return X;let G=dB0[Y]??dB0[dB0.length-1];return X==="#875f00"?G[0]:G[1]}function ys6({status:X}){if(X==="pending")return qY(Zp5,{label:""});return qY(MX,{color:"green",children:"\u2713"})}function xs6({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=bs6(du0,mu0),Z=bs6(tu0,au0);return oQ(AU,{flexDirection:"column",paddingBottom:1,children:[J?oQ(AU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((N,z)=>N+z.text.length,0),B=Math.max(0,Kp5-U);return oQ(AU,{flexDirection:"row",children:[$.map((N,z)=>{let O=Fp5(N.color,K);return O?qY(MX,{color:O,children:N.text},z):qY(MX,{children:N.text},z)}),qY(MX,{children:" ".repeat(B+2)}),H?.map((N,z)=>N.color?qY(MX,{color:N.color,children:N.char},z):qY(MX,{children:N.char},z))]},K)}),oQ(MX,{dimColor:!0,children:[" v",mB0.version]})]}):oQ(AU,{flexDirection:"column",marginTop:1,children:[Wp5.map(($,K)=>qY(MX,{color:$p5[K],children:$},K)),oQ(MX,{dimColor:!0,children:[" v",mB0.version]})]}),qY(AU,{marginBottom:1,children:qY(MX,{dimColor:!0,children:"\u2500".repeat(80)})}),qY(AU,{children:oQ(MX,{dimColor:!0,children:["Home: ",G]})}),oQ(AU,{gap:2,children:[X.map(($)=>oQ(AU,{gap:1,children:[oQ(MX,{children:[$.name," :",$.port||"...."]}),qY(ys6,{status:$.status})]},$.name)),oQ(AU,{gap:1,children:[qY(MX,{children:"Migrations"}),qY(ys6,{status:Y})]})]}),qY(AU,{children:Q?oQ(MX,{children:["Open in browser: ",qY(MX,{color:"cyan",children:Q})]}):qY(MX,{dimColor:!0,children:"Starting..."})}),oQ(AU,{gap:2,children:[oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var Wp5,$p5,dB0,Kp5=30,Hp5;var hs6=D(()=>{fs6();In1();Cn1();Wp5=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 ","\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588 \u2591 \u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591 \u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591 ","\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591 "],$p5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],dB0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],Hp5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as Up5}from"react";function Bp5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==SA1.rows||Y!==SA1.columns)SA1={rows:X,columns:Y};return SA1}function Np5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function gs6(){return Up5(Np5,Bp5)}var SA1;var us6=D(()=>{SA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as zp5,Text as jX1}from"ink";import{useSyncExternalStore as Op5}from"react";import{jsx as cB0,jsxs as iB0}from"react/jsx-runtime";function Dp5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function ls6({logs:X,headerHeight:Y}){let{rows:G}=gs6(),{logFlow:Q}=Op5(Me,je),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return cB0(zp5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return cB0(jX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return iB0(jX1,{children:[iB0(jX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),cB0(jX1,{color:Dp5(Z.status),children:Z.status}),iB0(jX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var ms6=D(()=>{GF();us6()});var pB0={};M0(pB0,{App:()=>Tp5});import{Box as wp5,Text as Lp5,useInput as Ep5}from"ink";import{useSyncExternalStore as Pp5}from"react";import{jsx as CA1,jsxs as Ip5}from"react/jsx-runtime";function Tp5({home:X}){let Y=Pp5(Me,je);return Ep5((G)=>{if(G==="k"||G==="K")yn1();if(G==="l"||G==="L")xn1();if((G==="v"||G==="V")&&Y.dataDir)fn1(Y.dataDir),hn1();if((G==="n"||G==="N")&&Y.vibe)_n1()}),Ip5(wp5,{flexDirection:"column",children:[CA1(xs6,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?CA1(vs6,{env:Y.env}):CA1(Lp5,{dimColor:!0,children:"Loading configuration..."}):CA1(ls6,{logs:Y.logs,headerHeight:Y.vibe?Ap5:qp5})]})}var qp5=15,Ap5=19;var nB0=D(()=>{_s6();hs6();ms6();GF();qd()});function ds6(X,Y={}){return{PORT:String(X.port),NODE_ENV:X.nodeEnv,BASE_URL:X.baseUrl,DATA_DIR:X.dataDir,DECOCMS_HOME:X.dataDir,DATABASE_URL:X.databaseUrl,DATABASE_PG_SSL:String(X.databasePgSsl),DATABASE_POOL_MAX:String(X.databasePoolMax),NATS_URL:X.natsUrls.join(","),BETTER_AUTH_SECRET:X.betterAuthSecret,ENCRYPTION_KEY:X.encryptionKey,MESH_JWT_SECRET:X.meshJwtSecret,DECOCMS_LOCAL_MODE:String(X.localMode),DECOCMS_ALLOW_LOCAL_PROD:String(X.allowLocalProd),DISABLE_RATE_LIMIT:String(X.disableRateLimit),STUDIO_PROVISION_SECRET_KEY:X.studioProvisionSecretKey,CONFIG_PATH:X.configPath,...Object.fromEntries(Object.entries(process.env).filter(([G])=>G.startsWith("AUTH_"))),UNSAFE_ALLOW_STDIO_TRANSPORT:String(X.unsafeAllowStdioTransport),DECO_AI_GATEWAY_ENABLED:String(X.aiGatewayEnabled),DECO_AI_GATEWAY_URL:X.aiGatewayUrl,ENABLE_DECO_IMPORT:String(X.enableDecoImport),S3_ENDPOINT:X.s3Endpoint,S3_BUCKET:X.s3Bucket,S3_REGION:X.s3Region,S3_ACCESS_KEY_ID:X.s3AccessKeyId,S3_SECRET_ACCESS_KEY:X.s3SecretAccessKey,S3_FORCE_PATH_STYLE:String(X.s3ForcePathStyle),OTEL_SERVICE_NAME:X.otelServiceName,CLICKHOUSE_URL:X.clickhouseUrl,DECO_SUPABASE_URL:X.decoSupabaseUrl,DECO_SUPABASE_SERVICE_KEY:X.decoSupabaseServiceKey,FIRECRAWL_API_KEY:X.firecrawlApiKey,STUDIO_SANDBOX_RUNNER:process.env.STUDIO_SANDBOX_RUNNER,STUDIO_SANDBOX_TEMPLATE_NAME:process.env.STUDIO_SANDBOX_TEMPLATE_NAME,STUDIO_SANDBOX_PREVIEW_URL_PATTERN:process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN,STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME:process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME,STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE:process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE,KUBERNETES_SERVICE_HOST:process.env.KUBERNETES_SERVICE_HOST,KUBERNETES_SERVICE_PORT:process.env.KUBERNETES_SERVICE_PORT,FREESTYLE_API_KEY:process.env.FREESTYLE_API_KEY,BROWSERLESS_TOKEN:process.env.BROWSERLESS_TOKEN,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,DECO_CLI:"1",DECO_NO_TUI:"true",...Y}}function is6(X){if(!X)return!1;try{return new URL(X).host==="api.decocms.com"&&X!=="https://studio.decocms.com/org/deco/registry/mcp"}catch{return!1}}var cs6="https://studio.decocms.com/org/deco/registry/mcp";var aB0=(X,Y,G)=>{return(Q,J)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,U;if(X[$])U=X[$][0][0],Q.req.routeIndex=$;else U=$===X.length&&J||void 0;if(U)try{K=await U(Q,()=>Z($+1))}catch(B){if(B instanceof Error&&Y)Q.error=B,K=await Y(B,Q),H=!0;else throw B}else if(Q.finalized===!1&&G)K=await G(Q);if(K&&(Q.finalized===!1||H))Q.res=K;return Q}}};var ps6=()=>{};var M9;var Eq=D(()=>{M9=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var ns6;var as6=D(()=>{ns6=Symbol()});async function Vp5(X,Y){let G=await X.formData();if(G)return jp5(G,Y);return{}}function jp5(X,Y){let G=Object.create(null);if(X.forEach((Q,J)=>{if(!(Y.all||J.endsWith("[]")))G[J]=Q;else Mp5(G,J,Q)}),Y.dot)Object.entries(G).forEach(([Q,J])=>{if(Q.includes("."))Rp5(G,Q,J),delete G[Q]});return G}var ts6=async(X,Y=Object.create(null))=>{let{all:G=!1,dot:Q=!1}=Y,W=(X instanceof kA1?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return Vp5(X,{all:G,dot:Q});return{}},Mp5=(X,Y,G)=>{if(X[Y]!==void 0)if(Array.isArray(X[Y]))X[Y].push(G);else X[Y]=[X[Y],G];else if(!Y.endsWith("[]"))X[Y]=G;else X[Y]=[G]},Rp5=(X,Y,G)=>{if(/(?:^|\.)__proto__\./.test(Y))return;let Q=X,J=Y.split(".");J.forEach((W,Z)=>{if(Z===J.length-1)Q[W]=G;else{if(!Q[W]||typeof Q[W]!=="object"||Array.isArray(Q[W])||Q[W]instanceof File)Q[W]=Object.create(null);Q=Q[W]}})};var rs6=D(()=>{tB0()});var oB0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},os6=(X)=>{let{groups:Y,path:G}=Sp5(X),Q=oB0(G);return Cp5(Q,Y)},Sp5=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(G,Q)=>{let J=`@${Q}`;return Y.push([J,G]),J}),{groups:Y,path:X}},Cp5=(X,Y)=>{for(let G=Y.length-1;G>=0;G--){let[Q]=Y[G];for(let J=X.length-1;J>=0;J--)if(X[J].includes(Q)){X[J]=X[J].replace(Q,Y[G][1]);break}}return X},vA1,ss6=(X,Y)=>{if(X==="*")return"*";let G=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(G){let Q=`${X}#${Y}`;if(!vA1[Q])if(G[2])vA1[Q]=Y&&Y[0]!==":"&&Y[0]!=="*"?[Q,G[1],new RegExp(`^${G[2]}(?=/${Y})`)]:[X,G[1],new RegExp(`^${G[2]}$`)];else vA1[Q]=[X,G[1],!0];return vA1[Q]}return null},ra=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(G)=>{try{return Y(G)}catch{return G}})}},es6=(X)=>ra(X,decodeURI),sB0=(X)=>{let Y=X.url,G=Y.indexOf("/",Y.indexOf(":")+4),Q=G;for(;Q<Y.length;Q++){let J=Y.charCodeAt(Q);if(J===37){let W=Y.indexOf("?",Q),Z=Y.indexOf("#",Q),$=W===-1?Z===-1?void 0:Z:Z===-1?W:Math.min(W,Z),K=Y.slice(G,$);return es6(K.includes("%25")?K.replace(/%25/g,"%2525"):K)}else if(J===63||J===35)break}return Y.slice(G,Q)},Xe6=(X)=>{let Y=sB0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Mj=(X,Y,...G)=>{if(G.length)Y=Mj(Y,...G);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},_A1=(X)=>{if(X.charCodeAt(X.length-1)!==63||!X.includes(":"))return null;let Y=X.split("/"),G=[],Q="";return Y.forEach((J)=>{if(J!==""&&!/\:/.test(J))Q+="/"+J;else if(/\:/.test(J))if(/\?/.test(J)){if(G.length===0&&Q==="")G.push("/");else G.push(Q);let W=J.replace("?","");Q+="/"+W,G.push(Q)}else Q+="/"+J}),G.filter((J,W,Z)=>Z.indexOf(J)===W)},rB0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?ra(X,MX1):X},Ye6=(X,Y,G)=>{let Q;if(!G&&Y&&!/[%+]/.test(Y)){let Z=X.indexOf("?",8);if(Z===-1)return;if(!X.startsWith(Y,Z+1))Z=X.indexOf(`&${Y}`,Z+1);while(Z!==-1){let $=X.charCodeAt(Z+Y.length+1);if($===61){let K=Z+Y.length+2,H=X.indexOf("&",K);return rB0(X.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=X.indexOf(`&${Y}`,Z+1)}if(Q=/[%+]/.test(X),!Q)return}let J={};Q??=/[%+]/.test(X);let W=X.indexOf("?",8);while(W!==-1){let Z=X.indexOf("&",W+1),$=X.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=X.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(Q)K=rB0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),Q)H=rB0(H);if(G){if(!(J[K]&&Array.isArray(J[K])))J[K]=[];J[K].push(H)}else J[K]??=H}return Y?J[Y]:J},Ge6,Qe6=(X,Y)=>{return Ye6(X,Y,!0)},MX1;var Pq=D(()=>{vA1={},Ge6=Ye6,MX1=decodeURIComponent});var Je6=(X)=>ra(X,MX1),kA1;var tB0=D(()=>{Eq();as6();rs6();Pq();kA1=class{raw;#X;#Y;routeIndex=0;path;bodyCache={};constructor(X,Y="/",G=[[]]){this.raw=X,this.path=Y,this.#Y=G,this.#X={}}param(X){return X?this.#G(X):this.#Q()}#G(X){let Y=this.#Y[0][this.routeIndex][1][X],G=this.#J(Y);return G&&/\%/.test(G)?Je6(G):G}#Q(){let X={},Y=Object.keys(this.#Y[0][this.routeIndex][1]);for(let G of Y){let Q=this.#J(this.#Y[0][this.routeIndex][1][G]);if(Q!==void 0)X[G]=/\%/.test(Q)?Je6(Q):Q}return X}#J(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return Ge6(this.url,X)}queries(X){return Qe6(this.url,X)}header(X){if(X)return this.raw.headers.get(X)??void 0;let Y={};return this.raw.headers.forEach((G,Q)=>{Y[Q]=G}),Y}async parseBody(X){return ts6(this,X)}#Z=(X)=>{let{bodyCache:Y,raw:G}=this,Q=Y[X];if(Q)return Q;let J=Object.keys(Y)[0];if(J)return Y[J].then((W)=>{if(J==="json")W=JSON.stringify(W);return new Response(W)[X]()});return Y[X]=G[X]()};json(){return this.#Z("text").then((X)=>JSON.parse(X))}text(){return this.#Z("text")}arrayBuffer(){return this.#Z("arrayBuffer")}blob(){return this.#Z("blob")}formData(){return this.#Z("formData")}addValidatedData(X,Y){this.#X[X]=Y}valid(X){return this.#X[X]}get url(){return this.raw.url}get method(){return this.raw.method}get[ns6](){return this.#Y}get matchedRoutes(){return this.#Y[0].map(([[,X]])=>X)}get routePath(){return this.#Y[0].map(([[,X]])=>X)[this.routeIndex].path}}});var fA1,Ze6=(X,Y)=>{let G=new String(X);return G.isEscaped=!0,G.callbacks=Y,G},RX1=async(X,Y,G,Q,J)=>{if(typeof X==="object"&&!(X instanceof String)){if(!(X instanceof Promise))X=X.toString();if(X instanceof Promise)X=await X}let W=X.callbacks;if(!W?.length)return Promise.resolve(X);if(J)J[0]+=X;else J=[X];let Z=Promise.all(W.map(($)=>$({phase:Y,buffer:J,context:Q}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>RX1(K,Y,!1,Q,J))).then(()=>J[0]));if(G)return Ze6(await Z,W);else return Z};var bA1=D(()=>{fA1={Stringify:1,BeforeStream:2,Stream:3}});var We6="text/plain; charset=UTF-8",eB0=(X,Y)=>{return{"Content-Type":X,...Y}},SX1=(X,Y)=>new Response(X,Y),$e6=class{#X;#Y;env={};#G;finalized=!1;error;#Q;#J;#Z;#$;#W;#K;#H;#U;#B;constructor(X,Y){if(this.#X=X,Y)this.#J=Y.executionCtx,this.env=Y.env,this.#K=Y.notFoundHandler,this.#B=Y.path,this.#U=Y.matchResult}get req(){return this.#Y??=new kA1(this.#X,this.#B,this.#U),this.#Y}get event(){if(this.#J&&"respondWith"in this.#J)return this.#J;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#J)return this.#J;else throw Error("This context has no ExecutionContext")}get res(){return this.#Z||=SX1(null,{headers:this.#H??=new Headers})}set res(X){if(this.#Z&&X){X=SX1(X.body,X);for(let[Y,G]of this.#Z.headers.entries()){if(Y==="content-type")continue;if(Y==="set-cookie"){let Q=this.#Z.headers.getSetCookie();X.headers.delete("set-cookie");for(let J of Q)X.headers.append("set-cookie",J)}else X.headers.set(Y,G)}}this.#Z=X,this.finalized=!0}render=(...X)=>{return this.#W??=(Y)=>this.html(Y),this.#W(...X)};setLayout=(X)=>this.#$=X;getLayout=()=>this.#$;setRenderer=(X)=>{this.#W=X};header=(X,Y,G)=>{if(this.finalized)this.#Z=SX1(this.#Z.body,this.#Z);let Q=this.#Z?this.#Z.headers:this.#H??=new Headers;if(Y===void 0)Q.delete(X);else if(G?.append)Q.append(X,Y);else Q.set(X,Y)};status=(X)=>{this.#Q=X};set=(X,Y)=>{this.#G??=new Map,this.#G.set(X,Y)};get=(X)=>{return this.#G?this.#G.get(X):void 0};get var(){if(!this.#G)return{};return Object.fromEntries(this.#G)}#F(X,Y,G){let Q=this.#Z?new Headers(this.#Z.headers):this.#H??new Headers;if(typeof Y==="object"&&"headers"in Y){let W=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")Q.append(Z,$);else Q.set(Z,$)}if(G)for(let[W,Z]of Object.entries(G))if(typeof Z==="string")Q.set(W,Z);else{Q.delete(W);for(let $ of Z)Q.append(W,$)}let J=typeof Y==="number"?Y:Y?.status??this.#Q;return SX1(X,{status:J,headers:Q})}newResponse=(...X)=>this.#F(...X);body=(X,Y,G)=>this.#F(X,Y,G);text=(X,Y,G)=>{return!this.#H&&!this.#Q&&!Y&&!G&&!this.finalized?new Response(X):this.#F(X,Y,eB0(We6,G))};json=(X,Y,G)=>{return this.#F(JSON.stringify(X),Y,eB0("application/json",G))};html=(X,Y,G)=>{let Q=(J)=>this.#F(J,Y,eB0("text/html; charset=UTF-8",G));return typeof X==="object"?RX1(X,fA1.Stringify,!1,{}).then(Q):Q(X)};redirect=(X,Y)=>{let G=String(X);return this.header("Location",!/[^\x00-\xFF]/.test(G)?G:encodeURI(G)),this.newResponse(null,Y??302)};notFound=()=>{return this.#K??=()=>SX1(),this.#K(this)}};var yA1=D(()=>{tB0();bA1()});var T7="ALL",Ke6="all",He6,xA1="Can not add a route since the matcher is already built.",hA1;var qq=D(()=>{He6=["get","post","put","delete","options","patch"],hA1=class extends Error{}});var XN0="__COMPOSED_HANDLER";var YN0=()=>{};var kp5=(X)=>{return X.text("404 Not Found",404)},Fe6=(X,Y)=>{if("getResponse"in X){let G=X.getResponse();return Y.newResponse(G.body,G)}return console.error(X),Y.text("Internal Server Error",500)},Ue6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...He6,Ke6].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#X=Z;else this.#Q(W,this.#X,Z);return $.forEach((K)=>{this.#Q(W,this.#X,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#X=K;for(let H of[W].flat())$.map((U)=>{this.#Q(H.toUpperCase(),this.#X,U)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#X=W;else this.#X="*",Z.unshift(W);return Z.forEach(($)=>{this.#Q(T7,this.#X,$)}),this};let{strict:Q,...J}=Y;Object.assign(this,J),this.getPath=Q??!0?Y.getPath??sB0:Xe6}#Y(){let Y=new X({router:this.router,getPath:this.getPath});return Y.errorHandler=this.errorHandler,Y.#G=this.#G,Y.routes=this.routes,Y}#G=kp5;errorHandler=Fe6;route(Y,G){let Q=this.basePath(Y);return G.routes.map((J)=>{let W;if(G.errorHandler===Fe6)W=J.handler;else W=async(Z,$)=>(await aB0([],G.errorHandler)(Z,()=>J.handler(Z,$))).res,W[XN0]=J.handler;Q.#Q(J.method,J.path,W)}),this}basePath(Y){let G=this.#Y();return G._basePath=Mj(this._basePath,Y),G}onError=(Y)=>{return this.errorHandler=Y,this};notFound=(Y)=>{return this.#G=Y,this};mount(Y,G,Q){let J,W;if(Q)if(typeof Q==="function")W=Q;else if(W=Q.optionHandler,Q.replaceRequest===!1)J=(K)=>K;else J=Q.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};J||=(()=>{let K=Mj(this._basePath,Y),H=K==="/"?0:K.length;return(U)=>{let B=new URL(U.url);return B.pathname=B.pathname.slice(H)||"/",new Request(B,U)}})();let $=async(K,H)=>{let U=await G(J(K.req.raw),...Z(K));if(U)return U;await H()};return this.#Q(T7,Mj(Y,"*"),$),this}#Q(Y,G,Q){Y=Y.toUpperCase(),G=Mj(this._basePath,G);let J={basePath:this._basePath,path:G,method:Y,handler:Q};this.router.add(Y,G,[Q,J]),this.routes.push(J)}#J(Y,G){if(Y instanceof Error)return this.errorHandler(Y,G);throw Y}#Z(Y,G,Q,J){if(J==="HEAD")return(async()=>new Response(null,await this.#Z(Y,G,Q,"GET")))();let W=this.getPath(Y,{env:Q}),Z=this.router.match(J,W),$=new $e6(Y,{path:W,matchResult:Z,env:Q,executionCtx:G,notFoundHandler:this.#G});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#G($)})}catch(U){return this.#J(U,$)}return H instanceof Promise?H.then((U)=>U||($.finalized?$.res:this.#G($))).catch((U)=>this.#J(U,$)):H??this.#G($)}let K=aB0(Z[0],this.errorHandler,this.#G);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#J(H,$)}})()}fetch=(Y,...G)=>{return this.#Z(Y,G[1],G[0],Y.method)};request=(Y,G,Q,J)=>{if(Y instanceof Request)return this.fetch(G?new Request(Y,G):Y,Q,J);return Y=Y.toString(),this.fetch(new Request(/^https?:\/\//.test(Y)?Y:`http://localhost${Mj("/",Y)}`,G),Q,J)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#Z(Y.request,Y,void 0,Y.request.method))})}};var Be6=D(()=>{ps6();yA1();qq();YN0();Pq()});function gA1(X,Y){let G=this.buildAllMatchers(),Q=(J,W)=>{let Z=G[J]||G[T7],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],CX1];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=Q,Q(X,Y)}var CX1;var GN0=D(()=>{qq();CX1=[]});function _p5(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===kX1||X===vX1)return 1;else if(Y===kX1||Y===vX1)return-1;if(X===uA1)return 1;else if(Y===uA1)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var uA1="[^/]+",kX1=".*",vX1="(?:|/.*)",Rj,vp5,Ne6=class X{#X;#Y;#G=Object.create(null);insert(Y,G,Q,J,W){if(Y.length===0){if(this.#X!==void 0)throw Rj;if(W)return;this.#X=G;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",kX1]:["","",uA1]:Z==="/*"?["","",vX1]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let U=K[1],B=K[2]||uA1;if(U&&K[2]){if(B===".*")throw Rj;if(B=B.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(B))throw Rj}if(H=this.#G[B],!H){if(Object.keys(this.#G).some((N)=>N!==kX1&&N!==vX1))throw Rj;if(W)return;if(H=this.#G[B]=new X,U!=="")H.#Y=J.varIndex++}if(!W&&U!=="")Q.push([U,H.#Y])}else if(H=this.#G[Z],!H){if(Object.keys(this.#G).some((U)=>U.length>1&&U!==kX1&&U!==vX1))throw Rj;if(W)return;H=this.#G[Z]=new X}H.insert($,G,Q,J,W)}buildRegExpStr(){let G=Object.keys(this.#G).sort(_p5).map((Q)=>{let J=this.#G[Q];return(typeof J.#Y==="number"?`(${Q})@${J.#Y}`:vp5.has(Q)?`\\${Q}`:Q)+J.buildRegExpStr()});if(typeof this.#X==="number")G.unshift(`#${this.#X}`);if(G.length===0)return"";if(G.length===1)return G[0];return"(?:"+G.join("|")+")"}};var QN0=D(()=>{Rj=Symbol(),vp5=new Set(".\\+*[^]$()")});var ze6=class{#X={varIndex:0};#Y=new Ne6;insert(X,Y,G){let Q=[],J=[];for(let Z=0;;){let $=!1;if(X=X.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return J[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=X.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=J.length-1;Z>=0;Z--){let[$]=J[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,J[Z][1]);break}}return this.#Y.insert(W,Y,Q,this.#X,G),Q}buildRegExp(){let X=this.#Y.buildRegExpStr();if(X==="")return[/^$/,[],[]];let Y=0,G=[],Q=[];return X=X.replace(/#(\d+)|@(\d+)|\.\*\$/g,(J,W,Z)=>{if(W!==void 0)return G[++Y]=Number(W),"$()";if(Z!==void 0)return Q[Number(Z)]=++Y,"";return""}),[new RegExp(`^${X}`),G,Q]}};var Oe6=D(()=>{QN0()});function we6(X){return De6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,G)=>G?`\\${G}`:"(?:|/.*)")}$`)}function bp5(){De6=Object.create(null)}function yp5(X){let Y=new ze6,G=[];if(X.length===0)return fp5;let Q=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,U],[B,N])=>H?1:B?-1:U.length-N.length),J=Object.create(null);for(let H=0,U=-1,B=Q.length;H<B;H++){let[N,z,O]=Q[H];if(N)J[z]=[O.map(([E])=>[E,Object.create(null)]),CX1];else U++;let w;try{w=Y.insert(z,U,N)}catch(E){throw E===Rj?new hA1(z):E}if(N)continue;G[U]=O.map(([E,P])=>{let q=Object.create(null);P-=1;for(;P>=0;P--){let[M,j]=w[P];q[M]=j}return[E,q]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,U=G.length;H<U;H++)for(let B=0,N=G[H].length;B<N;B++){let z=G[H][B]?.[1];if(!z)continue;let O=Object.keys(z);for(let w=0,E=O.length;w<E;w++)z[O[w]]=$[z[O[w]]]}let K=[];for(let H in Z)K[H]=G[Z[H]];return[W,K,J]}function oa(X,Y){if(!X)return;for(let G of Object.keys(X).sort((Q,J)=>J.length-Q.length))if(we6(G).test(Y))return[...X[G]];return}var fp5,De6,lA1=class{name="RegExpRouter";#X;#Y;constructor(){this.#X={[T7]:Object.create(null)},this.#Y={[T7]:Object.create(null)}}add(X,Y,G){let Q=this.#X,J=this.#Y;if(!Q||!J)throw Error(xA1);if(!Q[X])[Q,J].forEach(($)=>{$[X]=Object.create(null),Object.keys($[T7]).forEach((K)=>{$[X][K]=[...$[T7][K]]})});if(Y==="/*")Y="*";let W=(Y.match(/\/:/g)||[]).length;if(/\*$/.test(Y)){let $=we6(Y);if(X===T7)Object.keys(Q).forEach((K)=>{Q[K][Y]||=oa(Q[K],Y)||oa(Q[T7],Y)||[]});else Q[X][Y]||=oa(Q[X],Y)||oa(Q[T7],Y)||[];Object.keys(Q).forEach((K)=>{if(X===T7||X===K)Object.keys(Q[K]).forEach((H)=>{$.test(H)&&Q[K][H].push([G,W])})}),Object.keys(J).forEach((K)=>{if(X===T7||X===K)Object.keys(J[K]).forEach((H)=>$.test(H)&&J[K][H].push([G,W]))});return}let Z=_A1(Y)||[Y];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(J).forEach((U)=>{if(X===T7||X===U)J[U][H]||=[...oa(Q[U],H)||oa(Q[T7],H)||[]],J[U][H].push([G,W-K+$+1])})}}match=gA1;buildAllMatchers(){let X=Object.create(null);return Object.keys(this.#Y).concat(Object.keys(this.#X)).forEach((Y)=>{X[Y]||=this.#G(Y)}),this.#X=this.#Y=void 0,bp5(),X}#G(X){let Y=[],G=X===T7;if([this.#X,this.#Y].forEach((Q)=>{let J=Q[X]?Object.keys(Q[X]).map((W)=>[W,Q[X][W]]):[];if(J.length!==0)G||=!0,Y.push(...J);else if(X!==T7)Y.push(...Object.keys(Q[T7]).map((W)=>[W,Q[T7][W]]))}),!G)return null;else return yp5(Y)}};var JN0=D(()=>{qq();Pq();GN0();QN0();Oe6();fp5=[/^$/,[],Object.create(null)],De6=Object.create(null)});var xp5=class{name="PreparedRegExpRouter";#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}#G(X,Y){let G=this.#X[X];G[1].forEach((Q)=>Q&&Q.push(Y)),Object.values(G[2]).forEach((Q)=>Q[0].push(Y))}#Q(X,Y,G,Q,J){let W=this.#X[X];if(!J)W[2][Y][0].push([G,{}]);else Q.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([G,J]);else W[2][Z||Y][0].push([G,J])})}add(X,Y,G){if(!this.#X[X]){let J=this.#X[T7],W={};for(let Z in J[2])W[Z]=[J[2][Z][0].slice(),CX1];this.#X[X]=[J[0],J[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(Y==="/*"||Y==="*"){let J=[G,{}];if(X===T7)for(let W in this.#X)this.#G(W,J);else this.#G(X,J);return}let Q=this.#Y[Y];if(!Q)throw Error(`Path ${Y} is not registered`);for(let[J,W]of Q)if(X===T7)for(let Z in this.#X)this.#Q(Z,Y,G,J,W);else this.#Q(X,Y,G,J,W)}buildAllMatchers(){return this.#X}match=gA1};var Le6=D(()=>{qq();GN0();JN0()});var Ee6=D(()=>{JN0();Le6()});var ZN0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,G){if(!this.#Y)throw Error(xA1);this.#Y.push([X,Y,G])}match(X,Y){if(!this.#Y)throw Error("Fatal error");let G=this.#X,Q=this.#Y,J=G.length,W=0,Z;for(;W<J;W++){let $=G[W];try{for(let K=0,H=Q.length;K<H;K++)$.add(...Q[K]);Z=$.match(X,Y)}catch(K){if(K instanceof hA1)continue;throw K}this.match=$.match.bind($),this.#X=[$],this.#Y=void 0;break}if(W===J)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#Y||this.#X.length!==1)throw Error("No active router has been determined yet.");return this.#X[0]}};var Pe6=D(()=>{qq()});var qe6=D(()=>{Pe6()});var _X1,hp5=(X)=>{for(let Y in X)return!0;return!1},Ae6=class X{#X;#Y;#G;#Q=0;#J=_X1;constructor(Y,G,Q){if(this.#Y=Q||Object.create(null),this.#X=[],Y&&G){let J=Object.create(null);J[Y]={handler:G,possibleKeys:[],score:0},this.#X=[J]}this.#G=[]}insert(Y,G,Q){this.#Q=++this.#Q;let J=this,W=os6(G),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],U=W[$+1],B=ss6(H,U),N=Array.isArray(B)?B[0]:H;if(N in J.#Y){if(J=J.#Y[N],B)Z.push(B[1]);continue}if(J.#Y[N]=new X,B)J.#G.push(B),Z.push(B[1]);J=J.#Y[N]}return J.#X.push({[Y]:{handler:Q,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#Q}}),J}#Z(Y,G,Q,J,W){for(let Z=0,$=G.#X.length;Z<$;Z++){let K=G.#X[Z],H=K[Q]||K[T7],U={};if(H!==void 0){if(H.params=Object.create(null),Y.push(H),J!==_X1||W&&W!==_X1)for(let B=0,N=H.possibleKeys.length;B<N;B++){let z=H.possibleKeys[B],O=U[H.score];H.params[z]=W?.[z]&&!O?W[z]:J[z]??W?.[z],U[H.score]=!0}}}}search(Y,G){let Q=[];this.#J=_X1;let W=[this],Z=oB0(G),$=[],K=Z.length,H=null;for(let U=0;U<K;U++){let B=Z[U],N=U===K-1,z=[];for(let w=0,E=W.length;w<E;w++){let P=W[w],q=P.#Y[B];if(q)if(q.#J=P.#J,N){if(q.#Y["*"])this.#Z(Q,q.#Y["*"],Y,P.#J);this.#Z(Q,q,Y,P.#J)}else z.push(q);for(let M=0,j=P.#G.length;M<j;M++){let V=P.#G[M],R=P.#J===_X1?{}:{...P.#J};if(V==="*"){let h=P.#Y["*"];if(h)this.#Z(Q,h,Y,P.#J),h.#J=R,z.push(h);continue}let[k,_,v]=V;if(!B&&!(v instanceof RegExp))continue;let y=P.#Y[k];if(v instanceof RegExp){if(H===null){H=Array(K);let p=G[0]==="/"?1:0;for(let f=0;f<K;f++)H[f]=p,p+=Z[f].length+1}let h=G.substring(H[U]),i=v.exec(h);if(i){if(R[_]=i[0],this.#Z(Q,y,Y,P.#J,R),hp5(y.#Y)){y.#J=R;let p=i[0].match(/\//)?.length??0;($[p]||=[]).push(y)}continue}}if(v===!0||v.test(B))if(R[_]=B,N){if(this.#Z(Q,y,Y,R,P.#J),y.#Y["*"])this.#Z(Q,y.#Y["*"],Y,R,P.#J)}else y.#J=R,z.push(y)}}let O=$.shift();W=O?z.concat(O):z}if(Q.length>1)Q.sort((U,B)=>{return U.score-B.score});return[Q.map(({handler:U,params:B})=>[U,B])]}};var Te6=D(()=>{qq();Pq();_X1=Object.create(null)});var WN0=class{name="TrieRouter";#X;constructor(){this.#X=new Ae6}add(X,Y,G){let Q=_A1(Y);if(Q){for(let J=0,W=Q.length;J<W;J++)this.#X.insert(X,Q[J],G);return}this.#X.insert(X,Y,G)}match(X,Y){return this.#X.search(X,Y)}};var Ie6=D(()=>{Pq();Te6()});var Ve6=D(()=>{Ie6()});var U5;var je6=D(()=>{Be6();Ee6();qe6();Ve6();U5=class extends Ue6{constructor(X={}){super(X);this.router=X.router??new ZN0({routers:[new lA1,new WN0]})}}});var NG=D(()=>{je6()});var Re6,gp5,Me6=(X)=>{let Y=0,G=X.length;while(Y<G){let Q=X.charCodeAt(Y);if(Q!==32&&Q!==9)break;Y++}while(G>Y){let Q=X.charCodeAt(G-1);if(Q!==32&&Q!==9)break;G--}return Y===0&&G===X.length?X:X.slice(Y,G)},$N0=(X,Y)=>{if(Y&&X.indexOf(Y)===-1)return{};let G=X.split(";"),Q={};for(let J of G){let W=J.indexOf("=");if(W===-1)continue;let Z=Me6(J.substring(0,W));if(Y&&Y!==Z||!Re6.test(Z))continue;let $=Me6(J.substring(W+1));if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(gp5.test($)){if(Q[Z]=$.indexOf("%")!==-1?ra($,MX1):$,Y)break}}return Q},up5=(X,Y,G={})=>{if(!Re6.test(X))throw Error("Invalid cookie name");let Q=`${X}=${Y}`;if(X.startsWith("__Secure-")&&!G.secure)throw Error("__Secure- Cookie must have Secure attributes");if(X.startsWith("__Host-")){if(!G.secure)throw Error("__Host- Cookie must have Secure attributes");if(G.path!=="/")throw Error('__Host- Cookie must have Path attributes with "/"');if(G.domain)throw Error("__Host- Cookie must not have Domain attributes")}for(let J of["domain","path"])if(G[J]&&/[;\r\n]/.test(G[J]))throw Error(`${J} must not contain ";", "\\r", or "\\n"`);if(G&&typeof G.maxAge==="number"&&G.maxAge>=0){if(G.maxAge>34560000)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");Q+=`; Max-Age=${G.maxAge|0}`}if(G.domain&&G.prefix!=="host")Q+=`; Domain=${G.domain}`;if(G.path)Q+=`; Path=${G.path}`;if(G.expires){if(G.expires.getTime()-Date.now()>34560000000)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");Q+=`; Expires=${G.expires.toUTCString()}`}if(G.httpOnly)Q+="; HttpOnly";if(G.secure)Q+="; Secure";if(G.sameSite)Q+=`; SameSite=${G.sameSite.charAt(0).toUpperCase()+G.sameSite.slice(1)}`;if(G.priority)Q+=`; Priority=${G.priority.charAt(0).toUpperCase()+G.priority.slice(1)}`;if(G.partitioned){if(!G.secure)throw Error("Partitioned Cookie must have Secure attributes");Q+="; Partitioned"}return Q},mA1=(X,Y,G)=>{return Y=encodeURIComponent(Y),up5(X,Y,G)};var Se6=D(()=>{Pq();Re6=/^[\w!#$%&'*.^`|~+-]+$/,gp5=/^[ !#-:<-[\]-~]*$/});var dA1=(X,Y,G)=>{let Q=X.req.raw.headers.get("Cookie");if(typeof Y==="string"){if(!Q)return;let W=Y;if(G==="secure")W="__Secure-"+Y;else if(G==="host")W="__Host-"+Y;return $N0(Q,W)[W]}if(!Q)return{};return $N0(Q)},lp5=(X,Y,G)=>{let Q;if(G?.prefix==="secure")Q=mA1("__Secure-"+X,Y,{path:"/",...G,secure:!0});else if(G?.prefix==="host")Q=mA1("__Host-"+X,Y,{...G,path:"/",secure:!0,domain:void 0});else Q=mA1(X,Y,{path:"/",...G});return Q},KN0=(X,Y,G,Q)=>{let J=lp5(Y,G,Q);X.header("Set-Cookie",J,{append:!0})};var HN0=D(()=>{Se6()});var Ce6=(X)=>{let G={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},Q=((W)=>{if(typeof W==="string")if(W==="*"){if(G.credentials)return(Z)=>Z||null;return()=>W}else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(G.origin),J=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(G.allowMethods);return async function(Z,$){function K(U,B){Z.res.headers.set(U,B)}let H=await Q(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(G.credentials)K("Access-Control-Allow-Credentials","true");if(G.exposeHeaders?.length)K("Access-Control-Expose-Headers",G.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(G.origin!=="*"||G.credentials)K("Vary","Origin");if(G.maxAge!=null)K("Access-Control-Max-Age",G.maxAge.toString());let U=await J(Z.req.header("origin")||"",Z);if(U.length)K("Access-Control-Allow-Methods",U.join(","));let B=G.allowHeaders;if(!B?.length){let N=Z.req.header("Access-Control-Request-Headers");if(N)B=N.split(/\s*,\s*/)}if(B?.length)K("Access-Control-Allow-Headers",B.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),G.origin!=="*"||G.credentials)Z.header("Vary","Origin",{append:!0})}};var ke6=()=>{};var ve6=()=>{try{return performance.now()}catch{}return Date.now()},FN0=(X)=>{let Y={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...X};return async function(Q,J){let W=[],Z=new Map;if(Q.get("metric"))return await J();if(Q.set("metric",{headers:W,timers:Z}),Y.total)OH(Q,"total",Y.totalDescription);if(await J(),Y.total)g$(Q,"total");if(Y.autoEnd)Z.forEach((K,H)=>g$(Q,H));if(typeof Y.enabled==="function"?Y.enabled(Q):Y.enabled){Q.res.headers.append("Server-Timing",W.join(","));let K=typeof Y.crossOrigin==="function"?Y.crossOrigin(Q):Y.crossOrigin;if(K)Q.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},_e6=(X,Y,G,Q,J)=>{let W=X.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof G==="number"){let Z=G.toFixed(J||1),$=Q?`${Y};dur=${Z};desc="${Q}"`:`${Y};dur=${Z}`;W.headers.push($)}else{let Z=G?`${Y};desc="${G}"`:`${Y}`;W.headers.push(Z)}},OH=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}Q.timers.set(Y,{description:G,start:ve6()})},g$=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let J=Q.timers.get(Y);if(!J){console.warn(`Timer "${Y}" does not exist!`);return}let{description:W,start:Z}=J,$=ve6()-Z;_e6(X,Y,$,W,G),Q.timers.delete(Y)};var fe6=D(()=>{yA1()});var UN0=D(()=>{fe6()});function fX1(){let X={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[],Tags:[],"AI Providers":[],Automations:[],"Object Storage":[],Registry:[],GitHub:[],VM:[]};for(let Y of BN0)X[Y.category]?.push(Y);return X}var BN0;var NN0=D(()=>{BN0=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"BRAND_CONTEXT_LIST",description:"List brand contexts",category:"Organizations"},{name:"BRAND_CONTEXT_GET",description:"View brand context",category:"Organizations"},{name:"BRAND_CONTEXT_CREATE",description:"Create brand context",category:"Organizations"},{name:"BRAND_CONTEXT_UPDATE",description:"Update brand context",category:"Organizations"},{name:"BRAND_CONTEXT_DELETE",description:"Delete brand context",category:"Organizations",dangerous:!0},{name:"BRAND_CONTEXT_EXTRACT",description:"Extract brand context from website",category:"Organizations"},{name:"BRAND_GET",description:"Get brand (binding)",category:"Organizations"},{name:"BRAND_LIST",description:"List brands (binding)",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_GET",description:"Get organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_SET",description:"Set organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_UPDATE",description:"Update organization domain settings",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_CLEAR",description:"Clear organization domain claim",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_GET",description:"View virtual MCP details",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete virtual MCPs",category:"Virtual MCPs",dangerous:!0},{name:"MONITORING_LOG_GET",description:"View monitoring log details",category:"Monitoring"},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"},{name:"COLLECTION_THREADS_CREATE",description:"Create threads",category:"Threads"},{name:"COLLECTION_THREADS_LIST",description:"List threads",category:"Threads"},{name:"COLLECTION_THREADS_GET",description:"View thread details",category:"Threads"},{name:"COLLECTION_THREADS_UPDATE",description:"Update threads",category:"Threads"},{name:"COLLECTION_THREADS_DELETE",description:"Delete threads",category:"Threads",dangerous:!0},{name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List thread messages",category:"Threads"},{name:"TAGS_LIST",description:"List organization tags",category:"Tags"},{name:"TAGS_CREATE",description:"Create organization tag",category:"Tags"},{name:"TAGS_DELETE",description:"Delete organization tag",category:"Tags",dangerous:!0},{name:"MEMBER_TAGS_GET",description:"Get member tags",category:"Tags"},{name:"MEMBER_TAGS_SET",description:"Set member tags",category:"Tags"},{name:"AUTOMATION_CREATE",description:"Create automation",category:"Automations"},{name:"AUTOMATION_GET",description:"View automation details",category:"Automations"},{name:"AUTOMATION_LIST",description:"List automations",category:"Automations"},{name:"AUTOMATION_UPDATE",description:"Update automation",category:"Automations"},{name:"AUTOMATION_DELETE",description:"Delete automation",category:"Automations",dangerous:!0},{name:"AUTOMATION_TRIGGER_ADD",description:"Add trigger to automation",category:"Automations"},{name:"AUTOMATION_TRIGGER_REMOVE",description:"Remove trigger from automation",category:"Automations"},{name:"AUTOMATION_RUN",description:"Manually trigger an automation run",category:"Automations"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_GET",description:"View virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_UPDATE",description:"Update virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PINNED_VIEWS_UPDATE",description:"Update virtual MCP pinned sidebar views",category:"Virtual MCPs"},{name:"AI_PROVIDERS_LIST",description:"List available AI providers",category:"AI Providers"},{name:"AI_PROVIDERS_LIST_MODELS",description:"List AI provider models",category:"AI Providers"},{name:"AI_PROVIDERS_ACTIVE",description:"List active AI providers",category:"AI Providers"},{name:"AI_PROVIDER_KEY_CREATE",description:"Store AI provider API key",category:"AI Providers"},{name:"AI_PROVIDER_KEY_LIST",description:"List AI provider API keys",category:"AI Providers"},{name:"AI_PROVIDER_KEY_DELETE",description:"Delete AI provider API key",category:"AI Providers",dangerous:!0},{name:"AI_PROVIDER_OAUTH_URL",description:"Get OAuth URL for provider",category:"AI Providers"},{name:"AI_PROVIDER_OAUTH_EXCHANGE",description:"Exchange OAuth code for API key",category:"AI Providers"},{name:"AI_PROVIDER_PROVISION_KEY",description:"Auto-provision API key for a provider",category:"AI Providers"},{name:"AI_PROVIDER_TOPUP_URL",description:"Get checkout URL to top up provider credits",category:"AI Providers"},{name:"AI_PROVIDER_CREDITS",description:"Get current credit balance for a provider",category:"AI Providers"},{name:"AI_PROVIDER_CLI_ACTIVATE",description:"Activate Claude Code via local CLI",category:"AI Providers"},{name:"LIST_OBJECTS",description:"List objects in storage",category:"Object Storage"},{name:"GET_OBJECT_METADATA",description:"Get object metadata",category:"Object Storage"},{name:"GET_PRESIGNED_URL",description:"Generate download URL",category:"Object Storage"},{name:"PUT_PRESIGNED_URL",description:"Generate upload URL",category:"Object Storage"},{name:"DELETE_OBJECT",description:"Delete object",category:"Object Storage",dangerous:!0},{name:"DELETE_OBJECTS",description:"Delete multiple objects",category:"Object Storage",dangerous:!0},{name:"COLLECTION_REGISTRY_APP_LIST",description:"List registry apps",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_GET",description:"Get registry app details",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_VERSIONS",description:"List registry app versions",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_FILTERS",description:"Get registry app filters",category:"Registry"},{name:"REGISTRY_ITEM_LIST",description:"List private registry items",category:"Registry"},{name:"REGISTRY_ITEM_SEARCH",description:"Search registry items",category:"Registry"},{name:"REGISTRY_ITEM_GET",description:"Get registry item details",category:"Registry"},{name:"REGISTRY_ITEM_VERSIONS",description:"List registry item versions",category:"Registry"},{name:"REGISTRY_ITEM_CREATE",description:"Create registry item",category:"Registry"},{name:"REGISTRY_ITEM_BULK_CREATE",description:"Bulk create registry items",category:"Registry"},{name:"REGISTRY_ITEM_UPDATE",description:"Update registry item",category:"Registry"},{name:"REGISTRY_ITEM_DELETE",description:"Delete registry item",category:"Registry",dangerous:!0},{name:"REGISTRY_ITEM_FILTERS",description:"Get registry item filters",category:"Registry"},{name:"REGISTRY_DISCOVER_TOOLS",description:"Discover tools from MCP server",category:"Registry"},{name:"REGISTRY_AI_GENERATE",description:"AI-generate registry content",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_LIST",description:"List publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_REVIEW",description:"Review publish request",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_COUNT",description:"Count pending publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_DELETE",description:"Delete publish request",category:"Registry",dangerous:!0},{name:"REGISTRY_PUBLISH_API_KEY_GENERATE",description:"Generate publish API key",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_LIST",description:"List publish API keys",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_REVOKE",description:"Revoke publish API key",category:"Registry",dangerous:!0},{name:"REGISTRY_MONITOR_RUN_START",description:"Start monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_LIST",description:"List monitor runs",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_GET",description:"Get monitor run details",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_CANCEL",description:"Cancel monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RESULT_LIST",description:"List monitor results",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_LIST",description:"List monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_SYNC",description:"Sync monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_UPDATE_AUTH",description:"Update monitor connection auth",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_SET",description:"Set monitor schedule",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_CANCEL",description:"Cancel monitor schedule",category:"Registry"},{name:"VM_START",description:"Start a Freestyle VM with dev server preview",category:"VM"},{name:"VM_DELETE",description:"Stop and delete a Freestyle VM",category:"VM"},{name:"GITHUB_LIST_USER_ORGS",description:"List GitHub user's personal account and organizations",category:"GitHub"}]});var be6=D(()=>{Gp();ez1()});function ye6(){return dp5.parse(process.env)}var zN0=(X)=>F.enum(["true","false","1","0"]).optional().transform((Y)=>Y===void 0?X:Y==="true"||Y==="1"),mp5=(X)=>F.string().optional().transform((Y)=>Y?Y.split(",").map((G)=>G.trim()):X),dp5;var xe6=D(()=>{H0();dp5=F.object({AUTH_EMAIL_PASSWORD_ENABLED:zN0(!0),AUTH_GOOGLE_CLIENT_ID:F.string().optional(),AUTH_GOOGLE_CLIENT_SECRET:F.string().optional(),AUTH_GITHUB_CLIENT_ID:F.string().optional(),AUTH_GITHUB_CLIENT_SECRET:F.string().optional(),AUTH_RESEND_API_KEY:F.string().optional(),AUTH_RESEND_FROM_EMAIL:F.string().optional(),AUTH_SENDGRID_API_KEY:F.string().optional(),AUTH_SENDGRID_FROM_EMAIL:F.string().optional(),AUTH_INVITE_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_RESET_PASSWORD_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_MAGIC_LINK_ENABLED:zN0(!1),AUTH_MAGIC_LINK_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_ENABLED:zN0(!1),AUTH_EMAIL_OTP_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_LENGTH:F.coerce.number().optional(),AUTH_EMAIL_OTP_EXPIRES_IN:F.coerce.number().optional(),AUTH_SSO_DOMAIN:F.string().optional(),AUTH_SSO_MS_TENANT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_SECRET:F.string().optional(),AUTH_SSO_SCOPES:mp5(["openid","email","profile"])}).transform((X)=>{let Y={};if(X.AUTH_GOOGLE_CLIENT_ID)Y.google={clientId:X.AUTH_GOOGLE_CLIENT_ID,clientSecret:X.AUTH_GOOGLE_CLIENT_SECRET??""};if(X.AUTH_GITHUB_CLIENT_ID)Y.github={clientId:X.AUTH_GITHUB_CLIENT_ID,clientSecret:X.AUTH_GITHUB_CLIENT_SECRET??""};let G=[];if(X.AUTH_RESEND_API_KEY)G.push({id:"resend",provider:"resend",config:{apiKey:X.AUTH_RESEND_API_KEY,fromEmail:X.AUTH_RESEND_FROM_EMAIL??"noreply@example.com"}});if(X.AUTH_SENDGRID_API_KEY)G.push({id:"sendgrid",provider:"sendgrid",config:{apiKey:X.AUTH_SENDGRID_API_KEY,fromEmail:X.AUTH_SENDGRID_FROM_EMAIL??"noreply@example.com"}});let Q=G[0]?.id,J;if(X.AUTH_SSO_MS_CLIENT_ID&&X.AUTH_SSO_DOMAIN)J={providerId:"microsoft",domain:X.AUTH_SSO_DOMAIN,MS_TENANT_ID:X.AUTH_SSO_MS_TENANT_ID??"",MS_CLIENT_ID:X.AUTH_SSO_MS_CLIENT_ID,MS_CLIENT_SECRET:X.AUTH_SSO_MS_CLIENT_SECRET??"",scopes:X.AUTH_SSO_SCOPES};let W;if(X.AUTH_MAGIC_LINK_ENABLED)W={enabled:!0,emailProviderId:X.AUTH_MAGIC_LINK_EMAIL_PROVIDER??Q??""};let Z;if(X.AUTH_EMAIL_OTP_ENABLED)Z={enabled:!0,emailProviderId:X.AUTH_EMAIL_OTP_EMAIL_PROVIDER??Q??"",...X.AUTH_EMAIL_OTP_LENGTH!==void 0&&{otpLength:X.AUTH_EMAIL_OTP_LENGTH},...X.AUTH_EMAIL_OTP_EXPIRES_IN!==void 0&&{expiresIn:X.AUTH_EMAIL_OTP_EXPIRES_IN}};return{emailAndPassword:{enabled:X.AUTH_EMAIL_PASSWORD_ENABLED},socialProviders:Object.keys(Y).length>0?Y:void 0,emailProviders:G.length>0?G:void 0,inviteEmailProviderId:X.AUTH_INVITE_EMAIL_PROVIDER,resetPasswordEmailProviderId:X.AUTH_RESET_PASSWORD_EMAIL_PROVIDER,ssoConfig:J,magicLinkConfig:W,emailOtpConfig:Z}})});var cA1;var he6=D(()=>{cA1={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"}});import{existsSync as cp5,readFileSync as ip5}from"fs";function pp5(){let X=ye6(),Y=v6().configPath;if(!cp5(Y))return{auth:X,monitoring:cA1};try{let G=JSON.parse(ip5(Y,"utf-8"));if(G.auth)console.warn("[config] DEPRECATION: 'auth' key found in config.json. Auth is now configured via AUTH_* environment variables. The 'auth' key will be ignored.");return{auth:X,monitoring:G.monitoring??cA1,theme:G.theme,logo:G.logo,autoCreateOrganizationOnSignup:G.autoCreateOrganizationOnSignup}}catch{return{auth:X,monitoring:cA1}}}function Sj(){if(!ON0)ON0=pp5();return ON0}function ge6(){return Sj().theme}var ON0=null;var DN0=D(()=>{xe6();he6();m9()});import{dirname as np5,posix as ap5,sep as tp5}from"path";function le6(){let X=rp5();return async(Y)=>{for(let G of Y)G.module=X(G.filename);return Y}}function rp5(X=process.argv[1]?np5(process.argv[1]):process.cwd(),Y=tp5==="\\"){let G=Y?ue6(X):X;return(Q)=>{if(!Q)return;let J=Y?ue6(Q):Q,{dir:W,base:Z,ext:$}=ap5.parse(J);if($===".js"||$===".mjs"||$===".cjs")Z=Z.slice(0,-1*$.length);let K=decodeURIComponent(Z);if(!W)W=".";let H=W.lastIndexOf("/node_modules");if(H>-1)return`${W.slice(H+14).replace(/\//g,".")}:${K}`;if(W.startsWith(G)){let U=W.slice(G.length+1).replace(/\//g,".");return U?`${U}:${K}`:K}return K}}function ue6(X){return X.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var me6=()=>{};function op5(X,Y,G){return{key:X,enabled:typeof Y=="string"?!0:Y,variant:typeof Y=="string"?Y:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:G?JSON.stringify(G):void 0,description:void 0}}}var wN0=(X)=>{if("flags"in X){let Y=de6(X.flags),G=ce6(X.flags);return{...X,featureFlags:Y,featureFlagPayloads:G}}{let Y=X.featureFlags??{},G=Object.fromEntries(Object.entries(X.featureFlagPayloads||{}).map(([J,W])=>[J,LN0(W)])),Q=Object.fromEntries(Object.entries(Y).map(([J,W])=>[J,op5(J,W,G[J])]));return{...X,featureFlags:Y,featureFlagPayloads:G,flags:Q}}},de6=(X)=>Object.fromEntries(Object.entries(X??{}).map(([Y,G])=>[Y,bX1(G)]).filter(([,Y])=>Y!==void 0)),ce6=(X)=>{let Y=X??{};return Object.fromEntries(Object.keys(Y).filter((G)=>{let Q=Y[G];return Q.enabled&&Q.metadata&&Q.metadata.payload!==void 0}).map((G)=>{let Q=Y[G].metadata?.payload;return[G,Q?LN0(Q):void 0]}))},bX1=(X)=>X===void 0?void 0:X.variant??X.enabled,LN0=(X)=>{if(typeof X!="string")return X;try{return JSON.parse(X)}catch{return X}};var iA1=()=>{};function ie6(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function pA1(X,Y=!0,G){try{let Q=new CompressionStream("gzip"),J=Q.writable.getWriter(),W=J.write(new TextEncoder().encode(X)).then(()=>J.close()).catch(async(K)=>{try{await J.abort(K)}catch{}throw K}),Z=new Response(Q.readable).blob(),[$]=await Promise.all([Z,W]);return $}catch(Q){if(G?.rethrow)throw Q;if(Y)console.error("Failed to gzip compress data",Q);return null}}var EN0=()=>{};var sp5,pe6=function(X,Y=[]){if(!X)return!1;let G=X.toLowerCase();return sp5.concat(Y).some((Q)=>{let J=Q.toLowerCase();return G.indexOf(J)!==-1})};var ne6=D(()=>{sp5=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"]});var aJ;var Cj=D(()=>{aJ=function(X){return X.AnonymousId="anonymous_id",X.DistinctId="distinct_id",X.Props="props",X.EnablePersonProcessing="enable_person_processing",X.PersonMode="person_mode",X.FeatureFlagDetails="feature_flag_details",X.FeatureFlags="feature_flags",X.FeatureFlagPayloads="feature_flag_payloads",X.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",X.BootstrapFeatureFlags="bootstrap_feature_flags",X.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",X.OverrideFeatureFlags="override_feature_flags",X.Queue="queue",X.LogsQueue="logs_queue",X.OptedOut="opted_out",X.SessionId="session_id",X.SessionStartTimestamp="session_start_timestamp",X.SessionLastTimestamp="session_timestamp",X.PersonProperties="person_properties",X.GroupProperties="group_properties",X.InstalledAppBuild="installed_app_build",X.InstalledAppVersion="installed_app_version",X.SessionReplay="session_replay",X.SurveyLastSeenDate="survey_last_seen_date",X.SurveysSeen="surveys_seen",X.Surveys="surveys",X.RemoteConfig="remote_config",X.FlagsEndpointWasHit="flags_endpoint_was_hit",X.DeviceId="device_id",X}({})});var nA1=()=>{};function tA1(X){return X===null||typeof X!="object"}function kj(X,Y){return Object.prototype.toString.call(X)===`[object ${Y}]`}function re6(X){return kj(X,"ErrorEvent")}function ea(X){return typeof Event<"u"&&Yn5(X,Event)}function oe6(X){return kj(X,"Object")}function Yn5(X,Y){try{return X instanceof Y}catch{return!1}}var Xn5,ae6,PmX,PN0,aA1,yX1=(X)=>X===Object(X)&&!aA1(X),sa=(X)=>X===void 0,Aq=(X)=>PN0.call(X)=="[object String]",te6=(X)=>Aq(X)&&X.trim().length===0,xX1=(X)=>PN0.call(X)=="[object Number]"&&X===X,qN0=(X)=>X instanceof Error;var hX1=D(()=>{Cj();nA1();Xn5=Array.isArray,ae6=Object.prototype,PmX=ae6.hasOwnProperty,PN0=ae6.toString,aA1=Xn5||function(X){return PN0.call(X)==="[object Array]"}});function gX1(X,Y,G,Q,J){if(Y>G)Q.warn("min cannot be greater than max."),Y=G;if(xX1(X))if(X>G)return Q.warn(" cannot be greater than max: "+G+". Using max value instead."),G;else{if(!(X<Y))return X;return Q.warn(" cannot be less than min: "+Y+". Using min value instead."),Y}return Q.warn(" must be a number. using max or fallback. max: "+G+", fallback: "+J),gX1(J||G,Y,G,Q)}var AN0=D(()=>{hX1()});class TN0{constructor(X){this._buckets={},this._onBucketRateLimited=X._onBucketRateLimited,this._bucketSize=gX1(X.bucketSize,0,100,X._logger),this._refillRate=gX1(X.refillRate,0,this._bucketSize,X._logger),this._refillInterval=gX1(X.refillInterval,0,Gn5,X._logger)}_applyRefill(X,Y){let G=Y-X.lastAccess,Q=Math.floor(G/this._refillInterval);if(Q>0){let J=Q*this._refillRate;X.tokens=Math.min(X.tokens+J,this._bucketSize),X.lastAccess=X.lastAccess+Q*this._refillInterval}}consumeRateLimit(X){let Y=Date.now(),G=String(X),Q=this._buckets[G];if(Q)this._applyRefill(Q,Y);else Q={tokens:this._bucketSize,lastAccess:Y},this._buckets[G]=Q;if(Q.tokens===0)return!0;if(Q.tokens--,Q.tokens===0)this._onBucketRateLimited?.(X);return Q.tokens===0}stop(){this._buckets={}}}var Gn5=86400000;var se6=D(()=>{AN0()});class vj{constructor(X){this.bytes=X}static ofInner(X){if(X.length===16)return new vj(X);throw TypeError("not 128-bit length")}static fromFieldsV7(X,Y,G,Q){if(!Number.isInteger(X)||!Number.isInteger(Y)||!Number.isInteger(G)||!Number.isInteger(Q)||X<0||Y<0||G<0||Q<0||X>281474976710655||Y>4095||G>1073741823||Q>4294967295)throw RangeError("invalid field value");let J=new Uint8Array(16);return J[0]=X/1099511627776,J[1]=X/4294967296,J[2]=X/16777216,J[3]=X/65536,J[4]=X/256,J[5]=X,J[6]=112|Y>>>8,J[7]=Y,J[8]=128|G>>>24,J[9]=G>>>16,J[10]=G>>>8,J[11]=G,J[12]=Q>>>24,J[13]=Q>>>16,J[14]=Q>>>8,J[15]=Q,new vj(J)}static parse(X){let Y;switch(X.length){case 32:Y=/^[0-9a-f]{32}$/i.exec(X)?.[0];break;case 36:Y=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;case 38:Y=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(X)?.slice(1,6).join("");break;case 45:Y=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;default:break}if(Y){let G=new Uint8Array(16);for(let Q=0;Q<16;Q+=4){let J=parseInt(Y.substring(2*Q,2*Q+8),16);G[Q+0]=J>>>24,G[Q+1]=J>>>16,G[Q+2]=J>>>8,G[Q+3]=J}return new vj(G)}throw SyntaxError("could not parse UUID string")}toString(){let X="";for(let Y=0;Y<this.bytes.length;Y++)if(X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]),Y===3||Y===5||Y===7||Y===9)X+="-";return X}toHex(){let X="";for(let Y=0;Y<this.bytes.length;Y++)X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]);return X}toJSON(){return this.toString()}getVariant(){let X=this.bytes[8]>>>4;if(X<0)throw Error("unreachable");if(X<=7)return this.bytes.every((Y)=>Y===0)?"NIL":"VAR_0";if(X<=11)return"VAR_10";if(X<=13)return"VAR_110";if(X<=15)return this.bytes.every((Y)=>Y===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new vj(this.bytes.slice(0))}equals(X){return this.compareTo(X)===0}compareTo(X){for(let Y=0;Y<16;Y++){let G=this.bytes[Y]-X.bytes[Y];if(G!==0)return Math.sign(G)}return 0}}class X14{constructor(X){this.timestamp=0,this.counter=0,this.random=X??Qn5()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(X,Y){let G=this.generateOrAbortCore(X,Y);if(G===void 0)this.timestamp=0,G=this.generateOrAbortCore(X,Y);return G}generateOrAbortCore(X,Y){if(!Number.isInteger(X)||X<1||X>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(Y<0||Y>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(X>this.timestamp)this.timestamp=X,this.resetCounter();else{if(!(X+Y>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return vj.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let X=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return X[6]=64|X[6]>>>4,X[8]=128|X[8]>>>2,vj.ofInner(X)}}var Qn5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),ee6,Tq=()=>Jn5().toString(),Jn5=()=>(ee6||(ee6=new X14)).generate();var uX1=D(()=>{/*! For license information please see uuidv7.mjs.LICENSE.txt */});class IN0{add(X){let Y=Tq();return this.promiseByIds[Y]=X,X.catch(()=>{}).finally(()=>{delete this.promiseByIds[Y]}),X}async join(){let X=Object.values(this.promiseByIds),Y=X.length;while(Y>0)await Promise.all(X),X=Object.values(this.promiseByIds),Y=X.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}var Y14=D(()=>{uX1()});function Zn5(X=console){return{log:X.log.bind(X),warn:X.warn.bind(X),error:X.error.bind(X),debug:X.debug.bind(X)}}function Q14(X,Y=Wn5){return G14(X,Y,Zn5())}var G14=(X,Y,G)=>{function Q(W,...Z){Y(()=>{let $=G[W];$(X,...Z)})}return{info:(...W)=>{Q("log",...W)},warn:(...W)=>{Q("warn",...W)},error:(...W)=>{Q("error",...W)},critical:(...W)=>{G.error(X,...W)},createLogger:(W)=>G14(`${X} ${W}`,Y,G)}},Wn5=(X)=>X();var J14=()=>{};var Yt="Mobile",oA1="iOS",Xt="Android",Z14="Tablet",vmX,Kn5="Apple",_mX,W14="Safari",sA1="BlackBerry",$14="Samsung",Hn5,Fn5,eA1="Chrome",Un5,Bn5,K14="Internet Explorer",Nn5,jN0="Opera",fmX,H14="Edge",zn5,MN0="Firefox",On5,RN0="Nintendo",SN0="PlayStation",rA1="Xbox",Dn5,wn5,lX1="Windows",Ln5,F14="Generic",bmX,ymX,En5="Konqueror",F3="(\\d+(\\.\\d+)?)",VN0,xmX,hmX,gmX,Pn5,qn5,umX,lmX;var U14=D(()=>{nA1();hX1();vmX=Xt+" "+Z14,_mX=Kn5+" Watch",Hn5=$14+"Browser",Fn5=$14+" Internet",Un5=eA1+" OS",Bn5=eA1+" "+oA1,Nn5=K14+" "+Yt,fmX=jN0+" Mini",zn5="Microsoft "+H14,On5=MN0+" "+oA1,Dn5=Xt+" "+Yt,wn5=Yt+" "+W14,Ln5=lX1+" Phone",bmX=F14+" "+Yt.toLowerCase(),ymX=F14+" "+Z14.toLowerCase(),VN0=new RegExp("Version/"+F3),xmX=new RegExp(rA1,"i"),hmX=new RegExp(SN0+" \\w+","i"),gmX=new RegExp(RN0+" \\w+","i"),Pn5=new RegExp(sA1+"|PlayBook|BB10","i"),qn5={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"},umX={[Nn5]:[new RegExp("rv:"+F3)],[zn5]:[new RegExp(H14+"?\\/"+F3)],[eA1]:[new RegExp("("+eA1+"|CrMo)\\/"+F3)],[Bn5]:[new RegExp("CriOS\\/"+F3)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+F3)],[W14]:[VN0],[wn5]:[VN0],[jN0]:[new RegExp("("+jN0+"|OPR)\\/"+F3)],[MN0]:[new RegExp(MN0+"\\/"+F3)],[On5]:[new RegExp("FxiOS\\/"+F3)],[En5]:[new RegExp("Konqueror[:/]?"+F3,"i")],[sA1]:[new RegExp(sA1+" "+F3),VN0],[Dn5]:[new RegExp("android\\s"+F3,"i")],[Fn5]:[new RegExp(Hn5+"\\/"+F3)],[K14]:[new RegExp("(rv:|MSIE )"+F3)],Mozilla:[new RegExp("rv:"+F3)]},lmX=[[new RegExp(rA1+"; "+rA1+" (.*?)[);]","i"),(X)=>[rA1,X&&X[1]||""]],[new RegExp(RN0,"i"),[RN0,""]],[new RegExp(SN0,"i"),[SN0,""]],[Pn5,[sA1,""]],[new RegExp(lX1,"i"),(X,Y)=>{if(/Phone/.test(Y)||/WPDesktop/.test(Y))return[Ln5,""];if(new RegExp(Yt).test(Y)&&!/IEMobile\b/.test(Y))return[lX1+" "+Yt,""];let G=/Windows NT ([0-9.]+)/i.exec(Y);if(G&&G[1]){let Q=G[1],J=qn5[Q]||"";if(/arm/i.test(Y))J="RT";return[lX1,J]}return[lX1,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(X)=>{if(X&&X[3]){let Y=[X[3],X[4],X[5]||"0"];return[oA1,Y.join(".")]}return[oA1,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(X)=>{let Y="";if(X&&X.length>=3)Y=sa(X[2])?X[3]:X[2];return["watchOS",Y]}],[new RegExp("("+Xt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Xt+")","i"),(X)=>{if(X&&X[2]){let Y=[X[2],X[3],X[4]||"0"];return[Xt,Y.join(".")]}return[Xt,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(X)=>{let Y=["Mac OS X",""];if(X&&X[1]){let G=[X[1],X[2],X[3]||"0"];Y[1]=G.join(".")}return Y}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Un5,""]],[/Linux|debian/i,["Linux",""]]]});function N14(X){return X?.replace(/\/+$/,"")}async function z14(X,Y){let G=null;for(let Q=0;Q<Y.retryCount+1;Q++){if(Q>0)await new Promise((J)=>setTimeout(J,Y.retryDelay));try{return await X()}catch(J){if(G=J,!Y.retryCheck(J))throw J}}throw G}function XT1(){return new Date().toISOString()}function Hw(X,Y){let G=setTimeout(X,Y);return G?.unref&&G?.unref(),G}function CN0(X){return Promise.all(X.map((Y)=>(Y??Promise.resolve()).then((G)=>({status:"fulfilled",value:G}),(G)=>({status:"rejected",reason:G}))))}var B14="utf8",O14=(X)=>X instanceof Error;var U3=D(()=>{ne6();se6();AN0();nA1();hX1();Y14();J14();U14()});var An5,YdX;var kN0=D(()=>{U3();An5={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},YdX=An5.info});var D14=D(()=>{kN0();Cj()});var w14=D(()=>{Cj()});class vN0{constructor(){this.events={},this.events={}}on(X,Y){if(!this.events[X])this.events[X]=[];return this.events[X].push(Y),()=>{this.events[X]=this.events[X].filter((G)=>G!==Y)}}emit(X,Y){for(let G of this.events[X]||[])G(Y);for(let G of this.events["*"]||[])G(X,Y)}}var L14=()=>{};async function E14(X){if(X instanceof Gt){let Y="";try{Y=await X.text}catch{}console.error(`Error while flushing PostHog: message=${X.message}, response body=${Y}`,X)}else console.error("Error while flushing PostHog",X);return Promise.resolve()}function _N0(X){return typeof X=="object"&&(X instanceof Gt||X instanceof mX1)}function P14(X){return typeof X=="object"&&X instanceof Gt&&X.status===413}class YT1{constructor(X,Y={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new IN0,this._events=new vN0,this._isInitialized=!1;let G=typeof X=="string"?X.trim():"",Q=typeof Y.host=="string"?Y.host.trim():"",J=!G;if(this._logger=Q14("[PostHog]",this.logMsgIfDebug.bind(this)),J)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=G,this.host=N14(Q||"https://us.i.posthog.com"),this.flushAt=Y.flushAt?Math.max(Y.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,Y.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,Y.maxQueueSize??1000),this.flushInterval=Y.flushInterval??1e4,this.preloadFeatureFlags=Y.preloadFeatureFlags??!0,this.defaultOptIn=Y.defaultOptIn??!0,this.disableSurveys=Y.disableSurveys??!1,this._retryOptions={retryCount:Y.fetchRetryCount??3,retryDelay:Y.fetchRetryDelay??3000,retryCheck:_N0},this.requestTimeout=Y.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=Y.featureFlagsRequestTimeoutMs??3000,this.remoteConfigRequestTimeoutMs=Y.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=Y.disableGeoip??!0,this.disabled=(Y.disabled??!1)||J,this.historicalMigration=Y?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=Y?.evaluationContexts??Y?.evaluationEnvironments,Y?.evaluationEnvironments&&!Y?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!ie6()||(Y?.disableCompression??!1)}logMsgIfDebug(X){if(this.isDebug)X()}wrap(X){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return X();this._initPromise.then(()=>X())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(aJ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(aJ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(aJ.OptedOut,!0)})}on(X,Y){return this._events.on(X,Y)}debug(X=!0){if(this.removeDebugCallback?.(),X){let Y=this.on("*",(G,Q)=>this._logger.info(G,Q));this.removeDebugCallback=()=>{Y(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(X){return{distinct_id:X.distinct_id,event:X.event,properties:{...X.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(X){return this.promiseQueue.add(X)}identifyStateless(X,Y,G){this.wrap(()=>{let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};this.enqueue("identify",Q,G)})}async identifyStatelessImmediate(X,Y,G){let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};await this.sendImmediate("identify",Q,G)}captureStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({distinct_id:X,event:Y,properties:G});this.enqueue("capture",J,Q)})}async captureStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({distinct_id:X,event:Y,properties:G});await this.sendImmediate("capture",J,Q)}aliasStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});this.enqueue("alias",J,Q)})}async aliasStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});await this.sendImmediate("alias",J,Q)}groupIdentifyStateless(X,Y,G,Q,J,W){this.wrap(()=>{let Z=this.buildPayload({distinct_id:J||`$${X}_${Y}`,event:"$groupidentify",properties:{$group_type:X,$group_key:Y,$group_set:G||{},...W||{}}});this.enqueue("capture",Z,Q)})}async getRemoteConfig(){await this._initPromise;let X=this.host;if(X==="https://us.i.posthog.com")X="https://us-assets.i.posthog.com";else if(X==="https://eu.i.posthog.com")X="https://eu-assets.i.posthog.com";let Y=`${X}/array/${this.apiKey}/config`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(Y,G,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((Q)=>Q.json()).catch((Q)=>{this._logger.error("Remote config could not be loaded",Q),this._events.emit("error",Q)})}async getFlags(X,Y={},G={},Q={},J={},W=!1){await this._initPromise;let Z=W?"&config=true":"",$=`${this.host}/flags/?v=2${Z}`,K={token:this.apiKey,distinct_id:X,groups:Y,person_properties:G,group_properties:Q,...J};if(G.$device_id)K.$device_id=G.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)K.evaluation_contexts=this.evaluationContexts;let H={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(K)};return this._logger.info("Flags URL",$),this.fetchWithRetry($,H,{retryCount:0},this.featureFlagsRequestTimeoutMs).then((U)=>U.json()).then((U)=>({success:!0,response:wN0(U)})).catch((U)=>{return this._events.emit("error",U),{success:!1,error:this.categorizeRequestError(U)}})}categorizeRequestError(X){if(X instanceof Gt)return{type:"api_error",statusCode:X.status};if(X instanceof mX1){let Y=X.error;if(Y instanceof Error&&(Y.name==="AbortError"||Y.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailStateless(X,Y,G,Q,J,W);if(Z===void 0)return{response:void 0,requestId:void 0};let $=bX1(Z.response);if($===void 0)$=!1;return{response:$,requestId:Z.requestId}}async getFeatureFlagDetailStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(Y,G,Q,J,W,[X]);if(Z===void 0)return;return{response:Z.flags[X],requestId:Z.requestId,evaluatedAt:Z.evaluatedAt}}async getFeatureFlagPayloadStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagPayloadsStateless(Y,G,Q,J,W,[X]);if(!Z)return;let $=Z[X];if($===void 0)return null;return $}async getFeatureFlagPayloadsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)).payloads}async getFeatureFlagsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)}async getFeatureFlagsAndPayloadsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(X,Y,G,Q,J,W);if(!Z)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:Z.featureFlags,payloads:Z.featureFlagPayloads,requestId:Z.requestId}}async getFeatureFlagDetailsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z={};if(J??this.disableGeoip)Z.geoip_disable=!0;if(W)Z.flag_keys_to_evaluate=W;let $=await this.getFlags(X,Y,G,Q,Z);if(!$.success)return;let K=$.response;if(K.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(K.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:K?.requestId,quotaLimited:K.quotaLimited};return K}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let X=`${this.host}/api/surveys/?token=${this.apiKey}`,Y={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},Q=(await this.fetchWithRetry(X,Y).then((J)=>{if(J.status!==200||!J.json){let W=`Surveys API could not be loaded: ${J.status}`,Z=Error(W);this._logger.error(Z),this._events.emit("error",Error(W));return}return J.json()}).catch((J)=>{this._logger.error("Surveys API could not be loaded",J),this._events.emit("error",J)}))?.surveys;if(Q)this._logger.info("Surveys fetched from API: ",JSON.stringify(Q));return Q??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(aJ.Props);return this._props||{}}set props(X){this._props=X}async register(X){this.wrap(()=>{this.props={...this.props,...X},this.setPersistedProperty(aJ.Props,this.props)})}async unregister(X){this.wrap(()=>{delete this.props[X],this.setPersistedProperty(aJ.Props,this.props)})}processBeforeEnqueue(X){return X}async flushStorage(){}enqueue(X,Y,G){this.wrap(()=>{if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J=this.getPersistedProperty(aJ.Queue)||[];if(J.length>=this.maxQueueSize)J.shift(),this._logger.info("Queue is full, the oldest event is dropped.");if(J.push({message:Q}),this.setPersistedProperty(aJ.Queue,J),this._events.emit(X,Q),J.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=Hw(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(X,Y,G){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J={api_key:this.apiKey,batch:[Q],sent_at:XT1()};if(this.historicalMigration)J.historical_migration=!0;let W=JSON.stringify(J),Z=`${this.host}/batch/`,$=this.disableCompression?null:await pA1(W,this.isDebug),K={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...$!==null&&{"Content-Encoding":"gzip"}},body:$||W};try{await this.fetchWithRetry(Z,K)}catch(H){this._events.emit("error",H)}}prepareMessage(X,Y,G){let Q={...Y,type:X,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:G?.timestamp?G?.timestamp:XT1(),uuid:G?.uuid?G.uuid:Tq()};if(G?.disableGeoip??this.disableGeoip){if(!Q.properties)Q.properties={};Q.properties.$geoip_disable=!0}if(Q.distinctId)Q.distinct_id=Q.distinctId,delete Q.distinctId;return Q}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){this.flush().catch(async(X)=>{await E14(X)})}async flush(){let X=CN0([this.flushPromise]).then(()=>this._flush());return this.flushPromise=X,this.addPendingPromise(X),CN0([X]).then(()=>{if(this.flushPromise===X)this.flushPromise=null}),X}getCustomHeaders(){let X=this.getCustomUserAgent(),Y={};if(X&&X!=="")Y["User-Agent"]=X;return Y}async _flush(){this.clearFlushTimer(),await this._initPromise;let X=this.getPersistedProperty(aJ.Queue)||[];if(!X.length)return;let Y=[],G=X.length;while(X.length>0&&Y.length<G){let Q=X.slice(0,this.maxBatchSize),J=Q.map((N)=>N.message),W=async()=>{let z=(this.getPersistedProperty(aJ.Queue)||[]).slice(Q.length);this.setPersistedProperty(aJ.Queue,z),X=z,await this.flushStorage()},Z={api_key:this.apiKey,batch:J,sent_at:XT1()};if(this.historicalMigration)Z.historical_migration=!0;let $=JSON.stringify(Z),K=`${this.host}/batch/`,H=this.disableCompression?null:await pA1($,this.isDebug),U={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...H!==null&&{"Content-Encoding":"gzip"}},body:H||$},B={retryCheck:(N)=>{if(P14(N))return!1;return _N0(N)}};try{await this.fetchWithRetry(K,U,B)}catch(N){if(P14(N)&&J.length>1){this.maxBatchSize=Math.max(1,Math.floor(J.length/2)),this._logger.warn(`Received 413 when sending batch of size ${J.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(N instanceof mX1))await W();throw this._events.emit("error",N),N}await W(),Y.push(...J)}this._events.emit("flush",Y)}async fetchWithRetry(X,Y,G,Q){let J=Y.body?Y.body:"",W=-1;try{W=J instanceof Blob?J.size:Buffer.byteLength(J,B14)}catch{if(J instanceof Blob)W=J.size;else W=new TextEncoder().encode(J).length}return await z14(async()=>{let Z=new AbortController,$=Q??this.requestTimeout,K=Hw(()=>Z.abort(),$),H=null;try{H=await this.fetch(X,{signal:Z.signal,...Y})}catch(B){throw new mX1(B)}finally{clearTimeout(K)}if(Y.mode!=="no-cors"&&(H.status<200||H.status>=400))throw new Gt(H,W);return H},{...this._retryOptions,...G})}async _shutdown(X=30000){await this._initPromise;let Y=!1;this.clearFlushTimer();let G=async()=>{try{await this.promiseQueue.join();while(!0){if((this.getPersistedProperty(aJ.Queue)||[]).length===0)break;if(await this.flush(),Y)break}}catch(J){if(!_N0(J))throw J;await E14(J)}},Q;try{return await Promise.race([new Promise((J,W)=>{Q=Hw(()=>{this._logger.error("Timed out while shutting down PostHog"),Y=!0,W("Timeout while shutting down PostHog. Some events may not have been sent.")},X)}),G()])}finally{clearTimeout(Q)}}async shutdown(X=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(X).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var Gt,mX1;var fN0=D(()=>{L14();iA1();EN0();Cj();U3();uX1();Gt=class Gt extends Error{constructor(X,Y){super("HTTP error while fetching PostHog: status="+X.status+", reqByteLength="+Y),this.response=X,this.reqByteLength=Y,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}};mX1=class mX1 extends Error{constructor(X){super("Network error while fetching PostHog",X instanceof Error?{cause:X}:{}),this.error=X,this.name="PostHogFetchNetworkError"}}});var q14=D(()=>{iA1();Cj();fN0();uX1();U3()});var A14=D(()=>{hX1()});function I14(X){let Y=globalThis._posthogChunkIds;if(!Y)return;let G=Object.keys(Y);if(QT1&&G.length===T14)return QT1;return T14=G.length,QT1=G.reduce((Q,J)=>{if(!GT1)GT1={};let W=GT1[J];if(W)Q[W[0]]=W[1];else{let Z=X(J);for(let $=Z.length-1;$>=0;$--){let H=Z[$]?.filename,U=Y[J];if(H&&U){Q[H]=U,GT1[J]=[H,U];break}}}return Q},{}),QT1}var GT1,T14,QT1;var V14=()=>{};class j14{constructor(X,Y,G=[]){this.coercers=X,this.stackParser=Y,this.modifiers=G}buildFromUnknown(X,Y={}){let Q=Y&&Y.mechanism||{handled:!0,type:"generic"},W=this.buildCoercingContext(Q,Y,0).apply(X),Z=this.buildParsingContext(Y),$=this.parseStacktrace(W,Z);return{$exception_list:this.convertToExceptionList($,Q),$exception_level:"error"}}async modifyFrames(X){for(let Y of X)if(Y.stacktrace&&Y.stacktrace.frames&&aA1(Y.stacktrace.frames))Y.stacktrace.frames=await this.applyModifiers(Y.stacktrace.frames);return X}coerceFallback(X){return{type:"Error",value:"Unknown error",stack:X.syntheticException?.stack,synthetic:!0}}parseStacktrace(X,Y){let G;if(X.cause!=null)G=this.parseStacktrace(X.cause,Y);let Q;if(X.stack!=""&&X.stack!=null)Q=this.applyChunkIds(this.stackParser(X.stack,X.synthetic?Y.skipFirstLines:0),Y.chunkIdMap);return{...X,cause:G,stack:Q}}applyChunkIds(X,Y){return X.map((G)=>{if(G.filename&&Y)G.chunk_id=Y[G.filename];return G})}applyCoercers(X,Y){for(let G of this.coercers)if(G.match(X))return G.coerce(X,Y);return this.coerceFallback(Y)}async applyModifiers(X){let Y=X;for(let G of this.modifiers)Y=await G(Y);return Y}convertToExceptionList(X,Y){let G={type:X.type,value:X.value,mechanism:{type:Y.type??"generic",handled:Y.handled??!0,synthetic:X.synthetic??!1}};if(X.stack)G.stacktrace={type:"raw",frames:X.stack};let Q=[G];if(X.cause!=null)Q.push(...this.convertToExceptionList(X.cause,{...Y,handled:!0}));return Q}buildParsingContext(X){return{chunkIdMap:I14(this.stackParser),skipFirstLines:X.skipFirstLines??1}}buildCoercingContext(X,Y,G=0){let Q=(W,Z)=>{if(!(Z<=Vn5))return;{let $=this.buildCoercingContext(X,Y,Z);return this.applyCoercers(W,$)}};return{...Y,syntheticException:G==0?Y.syntheticException:void 0,mechanism:X,apply:(W)=>Q(W,G),next:(W)=>Q(W,G+1)}}}var Vn5=4;var M14=D(()=>{U3();V14()});function Gz(X,Y,G,Q,J){let W={platform:X,filename:Y,function:G==="<anonymous>"?sQ:G,in_app:!0};if(!sa(Q))W.lineno=Q;if(!sa(J))W.colno=J;return W}var sQ="?";var Iq=D(()=>{U3()});var JT1=(X,Y)=>{let G=X.indexOf("safari-extension")!==-1,Q=X.indexOf("safari-web-extension")!==-1;return G||Q?[X.indexOf("@")!==-1?X.split("@")[0]:sQ,G?`safari-extension:${Y}`:`safari-web-extension:${Y}`]:[X,Y]};var bN0=D(()=>{Iq()});var jn5,Mn5,Rn5,yN0=(X,Y)=>{let G=jn5.exec(X);if(G){let[,J,W,Z]=G;return Gz(Y,J,sQ,+W,+Z)}let Q=Mn5.exec(X);if(Q){if(Q[2]&&Q[2].indexOf("eval")===0){let $=Rn5.exec(Q[2]);if($)Q[2]=$[1],Q[3]=$[2],Q[4]=$[3]}let[W,Z]=JT1(Q[1]||sQ,Q[2]);return Gz(Y,Z,W,Q[3]?+Q[3]:void 0,Q[4]?+Q[4]:void 0)}};var R14=D(()=>{Iq();bN0();jn5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Mn5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Rn5=/\((\S*)(?::(\d+))(?::(\d+))\)/});var Sn5,Cn5,xN0=(X,Y)=>{let G=Sn5.exec(X);if(G){if(G[3]&&G[3].indexOf(" > eval")>-1){let Z=Cn5.exec(G[3]);if(Z)G[1]=G[1]||"eval",G[3]=Z[1],G[4]=Z[2],G[5]=""}let J=G[3],W=G[1]||sQ;return[W,J]=JT1(W,J),Gz(Y,J,W,G[4]?+G[4]:void 0,G[5]?+G[5]:void 0)}};var S14=D(()=>{Iq();bN0();Sn5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Cn5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var kn5,C14=(X,Y)=>{let G=kn5.exec(X);return G?Gz(Y,G[2],G[1]||sQ,+G[3],G[4]?+G[4]:void 0):void 0};var k14=D(()=>{Iq();kn5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i});var vn5,v14=(X,Y)=>{let G=vn5.exec(X);return G?Gz(Y,G[2],G[3]||sQ,+G[1]):void 0},_n5,_14=(X,Y)=>{let G=_n5.exec(X);return G?Gz(Y,G[5],G[3]||G[4]||sQ,+G[1],+G[2]):void 0};var f14=D(()=>{Iq();vn5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,_n5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i});function yn5(X,Y=!1){return!(Y||X&&!X.startsWith("/")&&!X.match(/^[A-Z]:/)&&!X.startsWith(".")&&!X.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&X!==void 0&&!X.includes("node_modules/")}function b14(X){return parseInt(X||"",10)||void 0}var fn5,bn5,y14=(X,Y)=>{let G=X.match(bn5);if(G){let Q,J,W,Z,$;if(G[1]){W=G[1];let U=W.lastIndexOf(".");if(W[U-1]===".")U--;if(U>0){Q=W.slice(0,U),J=W.slice(U+1);let B=Q.indexOf(".Module");if(B>0)W=W.slice(B+1),Q=Q.slice(0,B)}Z=void 0}if(J)Z=Q,$=J;if(J==="<anonymous>")$=void 0,W=void 0;if(W===void 0)$=$||sQ,W=Z?`${Z}.${$}`:$;let K=G[2]?.startsWith("file://")?G[2].slice(7):G[2],H=G[5]==="native";if(K?.match(/\/[A-Z]:/))K=K.slice(1);if(!K&&G[5]&&!H)K=G[5];return{filename:K?decodeURI(K):void 0,module:void 0,function:W,lineno:b14(G[3]),colno:b14(G[4]),in_app:yn5(K||"",H),platform:Y}}if(X.match(fn5))return{filename:X,platform:Y}};var x14=D(()=>{Iq();fn5=/^\s*[-]{4,}$/,bn5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/});function u14(X){if(!X.length)return[];let Y=Array.from(X);return Y.reverse(),Y.slice(0,g14).map((G)=>({...G,filename:G.filename||xn5(Y).filename,function:G.function||sQ}))}function xn5(X){return X[X.length-1]||{}}function hn5(){return l14("web:javascript",yN0,xN0)}function l14(X,...Y){return(G,Q=0)=>{let J=[],W=G.split(`
1639
+ `);Q=W.pop()??"";for(let Z of W){let $=Rs6(Z).replace(/^\[\d+\]\s*/,"").trim();if(!$)continue;EK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:$})}}(async()=>{for(;;){let{done:W,value:Z}=await Y.read();if(W)break;Q+=G.decode(Z,{stream:!0}),J()}if(Q.trim()){let W=Rs6(Q).replace(/^\[\d+\]\s*/,"").trim();if(W)EK({method:"",path:"",status:0,duration:0,timestamp:new Date,rawLine:W})}})()}async function ei5(X){let{vitePort:Y,baseUrl:G,noTui:Q}=X,J=await MA1(Number(X.port)),{settings:W,services:Z,managedServiceNames:$}=await jA1({port:String(J),home:X.home,baseUrl:X.baseUrl,localMode:X.localMode,skipMigrations:X.skipMigrations,noTui:X.noTui,vitePort:X.vitePort});for(let z of Z)Ad({name:z.name,status:"ready",port:z.port});Ce(W),Re();let K=si5(import.meta.dir,"..","..","..","..",".."),H=Q===!0,U=Bun.spawn(["bun","run","--cwd=apps/mesh","dev:servers"],{cwd:K,env:{...process.env,PORT:String(W.port),VITE_PORT:String(Y),DATABASE_URL:W.databaseUrl,NATS_URL:W.natsUrls.join(","),NODE_ENV:W.nodeEnv,DECOCMS_LOCAL_MODE:String(W.localMode),DECOCMS_HOME:W.dataDir,DATA_DIR:W.dataDir,DECO_CLI:"1",...W.baseUrl?{BASE_URL:W.baseUrl}:{}},stdio:["inherit",H?"inherit":"pipe",H?"inherit":"pipe"]});if(!H)Ss6(U.stdout),Ss6(U.stderr);let B=G||`http://localhost:${W.port}`;Se(B),Ad({name:"Vite",status:"ready",port:Number(Y)});let N=async(z)=>{if(U.kill(z),$.length>0){let{stopServices:O}=await Promise.resolve().then(() => (E$1(),L$1));await O(W.dataDir)}};return process.on("SIGINT",()=>N("SIGINT")),process.on("SIGTERM",()=>N("SIGTERM")),{port:Number(W.port),process:U}}var gB0=D(()=>{yB0();GF();xB0()});import{Box as uB0,Text as lB0}from"ink";import{jsx as ks6,jsxs as RA1}from"react/jsx-runtime";function Cs6(X){if(!X)return"not set";try{let Y=new URL(X);if(Y.password)Y.password="***";if(Y.username&&Y.username.length>3)Y.username=Y.username.slice(0,3)+"***";return Y.pathname="/",Y.search="",Y.hash="",Y.toString()}catch{if(X.length<=10)return X;return X.slice(0,6)+"***"+X.slice(-4)}}function Gp5(X,Y){if(Xp5.has(X))return Y?{text:"\u25CF\u25CF\u25CF\u25CF\u25CF\u25CF",dimColor:!0}:{text:"not set",dimColor:!0};if(Yp5.has(X)){if(Array.isArray(Y)){if(Y.length===0)return{text:"not set",dimColor:!0};return{text:Y.map((W)=>Cs6(W)).join(", "),color:"cyan"}}let Q=Cs6(Y);return Q==="not set"?{text:Q,dimColor:!0}:{text:Q,color:"cyan"}}if(Y===void 0||Y===null||Y==="")return{text:"not set",dimColor:!0};let G=String(Y);if(G==="true")return{text:G,color:"green"};if(G==="false")return{text:G,color:"yellow"};try{return new URL(G),{text:G,color:"cyan"}}catch{return{text:G}}}function Qp5(X){return[{title:"Core",entries:[{key:"NODE_ENV",value:X.nodeEnv},{key:"PORT",value:X.port},{key:"BASE_URL",value:X.baseUrl??`http://localhost:${X.port}`},{key:"DATA_DIR",value:X.dataDir}]},{title:"Database",entries:[{key:"DATABASE_URL",value:X.databaseUrl},{key:"DATABASE_PG_SSL",value:X.databasePgSsl}]},{title:"Auth & Secrets",entries:[{key:"BETTER_AUTH_SECRET",value:X.betterAuthSecret},{key:"ENCRYPTION_KEY",value:X.encryptionKey},{key:"MESH_JWT_SECRET",value:X.meshJwtSecret},{key:"STUDIO_PROVISION_SECRET_KEY",value:X.studioProvisionSecretKey},{key:"DISABLE_RATE_LIMIT",value:X.disableRateLimit}]},{title:"Auth Providers",entries:[{key:"AUTH_EMAIL_PASSWORD_ENABLED",value:process.env.AUTH_EMAIL_PASSWORD_ENABLED??"true"},{key:"AUTH_GOOGLE_CLIENT_ID",value:!!process.env.AUTH_GOOGLE_CLIENT_ID},{key:"AUTH_GITHUB_CLIENT_ID",value:!!process.env.AUTH_GITHUB_CLIENT_ID},{key:"AUTH_RESEND_API_KEY",value:!!process.env.AUTH_RESEND_API_KEY},{key:"AUTH_SENDGRID_API_KEY",value:!!process.env.AUTH_SENDGRID_API_KEY},{key:"AUTH_SSO_MS_CLIENT_ID",value:!!process.env.AUTH_SSO_MS_CLIENT_ID},{key:"AUTH_MAGIC_LINK_ENABLED",value:process.env.AUTH_MAGIC_LINK_ENABLED==="true"},{key:"AUTH_EMAIL_OTP_ENABLED",value:process.env.AUTH_EMAIL_OTP_ENABLED==="true"}]},{title:"Observability",entries:[{key:"CLICKHOUSE_URL",value:X.clickhouseUrl},{key:"OTEL_SERVICE_NAME",value:X.otelServiceName}]},{title:"Event Bus & Networking",entries:[{key:"NATS_URL",value:X.natsUrls}]},{title:"Config Files",entries:[{key:"CONFIG_PATH",value:X.configPath}]},{title:"Transport",entries:[{key:"UNSAFE_ALLOW_STDIO_TRANSPORT",value:X.unsafeAllowStdioTransport}]},{title:"AI Gateway",entries:[{key:"DECO_AI_GATEWAY_ENABLED",value:X.aiGatewayEnabled},{key:"DECO_AI_GATEWAY_URL",value:X.aiGatewayUrl}]}]}function vs6({env:X}){let Y=Qp5(X);return ks6(uB0,{flexDirection:"column",children:Y.map((G)=>RA1(uB0,{flexDirection:"column",marginTop:1,children:[RA1(lB0,{dimColor:!0,children:[" ","\u2500\u2500 ",G.title," ","\u2500".repeat(Math.max(0,38-G.title.length))]}),G.entries.map(({key:Q,value:J})=>{let W=Gp5(Q,J);return RA1(uB0,{children:[RA1(lB0,{dimColor:!0,children:[" ",Q.padEnd(36)]}),ks6(lB0,{color:W.color,dimColor:W.dimColor,children:W.text})]},Q)})]},G.title))})}var Xp5,Yp5;var _s6=D(()=>{Xp5=new Set(["BETTER_AUTH_SECRET","ENCRYPTION_KEY","MESH_JWT_SECRET","STUDIO_PROVISION_SECRET_KEY"]),Yp5=new Set(["DATABASE_URL","CLICKHOUSE_URL","NATS_URL"])});var mB0;var fs6=D(()=>{mB0={name:"decocms",version:"2.293.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/mesh"},bugs:{url:"https://github.com/decocms/studio/issues"},type:"module",bin:{deco:"./dist/server/cli.js"},files:["dist/**/*"],scripts:{dev:'bun run migrate && concurrently "bun run dev:client" "bun run dev:server"',"dev:servers":'concurrently "bun run dev:client" "bun run dev:server"',"dev:client":"bun --bun vite dev","dev:server":"bun run --cwd=../../packages/sandbox build && NODE_ENV=development bun --env-file=.env --hot run src/index.ts","build:client":"bun --bun vite build","build:server":"bun run scripts/bundle-server-script.ts --dist ./dist/server","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","test:e2e":"playwright test","test:e2e:ui":"playwright test --ui","better-auth:migrate":"bunx --bun @better-auth/cli migrate -y --config src/auth/index.ts",prepublishOnly:"bun run build:client && bun run build:server"},optionalDependencies:{"@duckdb/node-api":"^1.5.0-r.1","@freestyle-sh/with-bun":"^0.2.12","@freestyle-sh/with-deno":"^0.0.4","@freestyle-sh/with-nodejs":"^0.2.9","freestyle-sandboxes":"^0.1.46"},dependencies:{"@ai-sdk/anthropic":"^3.0.58","@ai-sdk/google":"^3.0.60","@ai-sdk/openai":"^3.0.50","@anthropic-ai/sdk":"^0.79.0","@aws-sdk/client-s3":"^3.1013.0","@aws-sdk/s3-request-presigner":"^3.1013.0","@clickhouse/client":"^1.8.1","@dnd-kit/core":"^6.3.1","@dnd-kit/sortable":"^10.0.0","@dnd-kit/utilities":"^3.2.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/ext-apps":"^1.2.2","@openrouter/ai-sdk-provider":"^2.2.5","@opentelemetry/core":"^2.6.0","@tanstack/react-virtual":"^3.13.21","@xterm/addon-fit":"^0.11.0","@xterm/xterm":"^6.0.0","ai-sdk-provider-claude-code":"^3.4.4","ai-sdk-provider-codex-cli":"^1.1.0","embedded-postgres":"^18.3.0-beta.16",ink:"^6.8.0",kysely:"^0.28.12",nats:"^2.29.3","posthog-js":"^1.371.1","posthog-node":"^5.0.0",react:"^19.2.0","react-dom":"^19.2.0"},devDependencies:{"@ai-sdk/provider":"^3.0.8","@ai-sdk/react":"^3.0.118","@anthropic-ai/claude-agent-sdk":"^0.2.80","@better-auth/sso":"1.4.1","@daveyplate/better-auth-ui":"^3.2.7","@deco/ui":"workspace:*","@decocms/better-auth":"1.5.17","@decocms/bindings":"workspace:*","@decocms/mcp-utils":"workspace:*","@decocms/mesh-sdk":"workspace:*","@decocms/runtime":"workspace:*","@decocms/vite-plugin":"workspace:*","@electric-sql/pglite":"^0.3.15","@floating-ui/react":"^0.27.16","@hookform/resolvers":"^5.2.2","@jitl/quickjs-wasmfile-release-sync":"0.31.0","@modelcontextprotocol/sdk":"1.27.1","@monaco-editor/react":"^4.7.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.211.0","@opentelemetry/exporter-logs-otlp-proto":"^0.211.0","@opentelemetry/exporter-prometheus":"^0.208.0","@opentelemetry/exporter-trace-otlp-proto":"^0.207.0","@opentelemetry/instrumentation-runtime-node":"^0.24.0","@opentelemetry/sdk-logs":"^0.211.0","@opentelemetry/sdk-metrics":"^2.2.0","@opentelemetry/sdk-node":"^0.207.0","@opentelemetry/sdk-trace-base":"^2.5.0","@playwright/test":"^1.58.2","@radix-ui/react-avatar":"^1.1.10","@radix-ui/react-checkbox":"^1.3.3","@radix-ui/react-dialog":"^1.1.15","@radix-ui/react-dropdown-menu":"^2.1.16","@radix-ui/react-label":"^2.1.7","@radix-ui/react-select":"^2.2.6","@radix-ui/react-separator":"^1.1.7","@radix-ui/react-slot":"^1.2.3","@radix-ui/react-tabs":"^1.1.13","@rjsf/core":"^6.1.2","@rjsf/shadcn":"^6.1.2","@rjsf/utils":"^6.1.2","@rjsf/validator-ajv8":"^6.1.2","@tailwindcss/vite":"^4.1.17","@tanstack/react-query":"5.90.11","@tanstack/react-router":"^1.139.7","@tiptap/core":"3.20.2","@tiptap/extension-mention":"3.20.2","@tiptap/extension-placeholder":"3.20.2","@tiptap/pm":"3.20.2","@tiptap/react":"3.20.2","@tiptap/starter-kit":"3.20.2","@tiptap/suggestion":"3.20.2","@types/bun":"^1.3.1","@types/pg":"^8.15.6","@types/react-syntax-highlighter":"^15.5.13","@untitledui/icons":"^0.0.19","@vercel/nft":"^1.1.1","@vitejs/plugin-react":"^5.1.0",ai:"^6.0.116","babel-plugin-react-compiler":"^1.0.0","better-auth":"1.4.5","class-variance-authority":"^0.7.1",clsx:"^2.1.1",concurrently:"^9.2.1",croner:"^9.1.0","date-fns":"^4.1.0",degit:"^2.8.4",hono:"^4.10.7","input-otp":"^1.4.2",jose:"^6.0.11","kysely-pglite":"^0.6.1","lucide-react":"^0.468.0",marked:"^15.0.6","@decocms/sandbox":"workspace:*","mesh-plugin-workflows":"workspace:*",nanoid:"^5.1.6",pg:"^8.16.3",prettier:"^3.4.2","react-hook-form":"^7.66.0","react-markdown":"^10.1.0","react-resizable-panels":"^2.1.7","react-syntax-highlighter":"^15.6.1",recharts:"^3.6.0","rehype-raw":"^7.0.0","remark-gfm":"^4.0.0","sass-embedded":"^1.97.2",sonner:"^2.0.7","tailwind-merge":"^3.3.1",tailwindcss:"^4.1.17",typescript:"^5.9.3",vite:"^7.2.1","vite-tsconfig-paths":"^5.1.4",zod:"^4.0.0",zustand:"^5.0.9"},homepage:"https://github.com/decocms/studio",keywords:["mcp","model-context-protocol","ai","gateway","self-hosted","mesh","tools"],license:"MIT",publishConfig:{access:"public"}}});import{Box as AU,Text as MX}from"ink";import{Spinner as Zp5}from"@inkjs/ui";import{useSyncExternalStore as bs6}from"react";import{jsx as qY,jsxs as oQ}from"react/jsx-runtime";function Fp5(X,Y){if(!X||!Hp5.has(X))return X;let G=dB0[Y]??dB0[dB0.length-1];return X==="#875f00"?G[0]:G[1]}function ys6({status:X}){if(X==="pending")return qY(Zp5,{label:""});return qY(MX,{color:"green",children:"\u2713"})}function xs6({services:X,migrationsStatus:Y,home:G,serverUrl:Q,vibe:J}){let W=bs6(du0,mu0),Z=bs6(tu0,au0);return oQ(AU,{flexDirection:"column",paddingBottom:1,children:[J?oQ(AU,{flexDirection:"column",children:[W.map(($,K)=>{let H=Z[K],U=$.reduce((N,z)=>N+z.text.length,0),B=Math.max(0,Kp5-U);return oQ(AU,{flexDirection:"row",children:[$.map((N,z)=>{let O=Fp5(N.color,K);return O?qY(MX,{color:O,children:N.text},z):qY(MX,{children:N.text},z)}),qY(MX,{children:" ".repeat(B+2)}),H?.map((N,z)=>N.color?qY(MX,{color:N.color,children:N.char},z):qY(MX,{children:N.char},z))]},K)}),oQ(MX,{dimColor:!0,children:[" v",mB0.version]})]}):oQ(AU,{flexDirection:"column",marginTop:1,children:[Wp5.map(($,K)=>qY(MX,{color:$p5[K],children:$},K)),oQ(MX,{dimColor:!0,children:[" v",mB0.version]})]}),qY(AU,{marginBottom:1,children:qY(MX,{dimColor:!0,children:"\u2500".repeat(80)})}),qY(AU,{children:oQ(MX,{dimColor:!0,children:["Home: ",G]})}),oQ(AU,{gap:2,children:[X.map(($)=>oQ(AU,{gap:1,children:[oQ(MX,{children:[$.name," :",$.port||"...."]}),qY(ys6,{status:$.status})]},$.name)),oQ(AU,{gap:1,children:[qY(MX,{children:"Migrations"}),qY(ys6,{status:Y})]})]}),qY(AU,{children:Q?oQ(MX,{children:["Open in browser: ",qY(MX,{color:"cyan",children:Q})]}):qY(MX,{dimColor:!0,children:"Starting..."})}),oQ(AU,{gap:2,children:[oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"K"})," ","toggle config"]}),oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"L"})," ","toggle log flow"]}),oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"V"})," ","toggle vibe ",J?"\u266A Nihilore \xB7 CC BY 4.0":""]}),J&&oQ(MX,{dimColor:!0,children:[qY(MX,{bold:!0,dimColor:!0,children:"N"})," ","skip song"]})]})]})}var Wp5,$p5,dB0,Kp5=30,Hp5;var hs6=D(()=>{fs6();In1();Cn1();Wp5=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588 ","\u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591\u2588\u2588\u2588 "," \u2591\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2588 \u2591 \u2588\u2588\u2588 \u2591\u2591\u2591 \u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588\u2591\u2591\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591\u2588\u2588\u2588"," \u2591\u2588\u2588\u2588 \u2588\u2588\u2588 \u2591\u2588\u2588\u2588 \u2591 \u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588\u2591\u2591\u2588\u2588\u2588 \u2588\u2588\u2588 "," \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588 \u2591\u2591\u2591\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2591 ","\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591 \u2591\u2591\u2591\u2591\u2591\u2591\u2591 "],$p5=["#00ff64","#00ee5e","#00dc56","#00c84e","#00b444","#00a03c","#008832","#006e28"],dB0=[["#00ff64","#00cc50"],["#00f060","#00c04c"],["#00e05c","#00b448"],["#00d058","#00a844"],["#00c054","#009c40"],["#00b050","#00903c"],["#00a04c","#008438"],["#009048","#007834"],["#008044","#006c30"],["#007040","#00602c"],["#00603c","#005428"]],Hp5=new Set(["#875f00","#5f3800"])});import{useSyncExternalStore as Up5}from"react";function Bp5(){let X=process.stdout.rows||24,Y=process.stdout.columns||80;if(X!==SA1.rows||Y!==SA1.columns)SA1={rows:X,columns:Y};return SA1}function Np5(X){return process.stdout.on("resize",X),()=>{process.stdout.off("resize",X)}}function gs6(){return Up5(Np5,Bp5)}var SA1;var us6=D(()=>{SA1={rows:process.stdout.rows||24,columns:process.stdout.columns||80}});import{Box as zp5,Text as jX1}from"ink";import{useSyncExternalStore as Op5}from"react";import{jsx as cB0,jsxs as iB0}from"react/jsx-runtime";function Dp5(X){if(X>=500)return"red";if(X>=400)return"yellow";if(X>=300)return"cyan";return"green"}function ls6({logs:X,headerHeight:Y}){let{rows:G}=gs6(),{logFlow:Q}=Op5(Me,je),J=Math.max(1,G-Y-1),W=Q?X:X.slice(-J);return cB0(zp5,{flexDirection:"column",children:W.map((Z,$)=>{if(Z.rawLine)return cB0(jX1,{dimColor:!0,children:Z.rawLine},$);let K=Z.duration<1000?`${Z.duration}ms`:`${(Z.duration/1000).toFixed(1)}s`;return iB0(jX1,{children:[iB0(jX1,{dimColor:!0,children:[Z.method.padEnd(6)," ",Z.path.padEnd(30)," "]}),cB0(jX1,{color:Dp5(Z.status),children:Z.status}),iB0(jX1,{dimColor:!0,children:[" ",K.padStart(8)]})]},$)})})}var ms6=D(()=>{GF();us6()});var pB0={};M0(pB0,{App:()=>Tp5});import{Box as wp5,Text as Lp5,useInput as Ep5}from"ink";import{useSyncExternalStore as Pp5}from"react";import{jsx as CA1,jsxs as Ip5}from"react/jsx-runtime";function Tp5({home:X}){let Y=Pp5(Me,je);return Ep5((G)=>{if(G==="k"||G==="K")yn1();if(G==="l"||G==="L")xn1();if((G==="v"||G==="V")&&Y.dataDir)fn1(Y.dataDir),hn1();if((G==="n"||G==="N")&&Y.vibe)_n1()}),Ip5(wp5,{flexDirection:"column",children:[CA1(xs6,{services:Y.services,migrationsStatus:Y.migrationsStatus,home:X,serverUrl:Y.serverUrl,vibe:Y.vibe}),Y.viewMode==="config"?Y.env?CA1(vs6,{env:Y.env}):CA1(Lp5,{dimColor:!0,children:"Loading configuration..."}):CA1(ls6,{logs:Y.logs,headerHeight:Y.vibe?Ap5:qp5})]})}var qp5=15,Ap5=19;var nB0=D(()=>{_s6();hs6();ms6();GF();qd()});function ds6(X,Y={}){return{PORT:String(X.port),NODE_ENV:X.nodeEnv,BASE_URL:X.baseUrl,DATA_DIR:X.dataDir,DECOCMS_HOME:X.dataDir,DATABASE_URL:X.databaseUrl,DATABASE_PG_SSL:String(X.databasePgSsl),DATABASE_POOL_MAX:String(X.databasePoolMax),NATS_URL:X.natsUrls.join(","),BETTER_AUTH_SECRET:X.betterAuthSecret,ENCRYPTION_KEY:X.encryptionKey,MESH_JWT_SECRET:X.meshJwtSecret,DECOCMS_LOCAL_MODE:String(X.localMode),DECOCMS_ALLOW_LOCAL_PROD:String(X.allowLocalProd),DISABLE_RATE_LIMIT:String(X.disableRateLimit),STUDIO_PROVISION_SECRET_KEY:X.studioProvisionSecretKey,CONFIG_PATH:X.configPath,...Object.fromEntries(Object.entries(process.env).filter(([G])=>G.startsWith("AUTH_"))),UNSAFE_ALLOW_STDIO_TRANSPORT:String(X.unsafeAllowStdioTransport),DECO_AI_GATEWAY_ENABLED:String(X.aiGatewayEnabled),DECO_AI_GATEWAY_URL:X.aiGatewayUrl,ENABLE_DECO_IMPORT:String(X.enableDecoImport),S3_ENDPOINT:X.s3Endpoint,S3_BUCKET:X.s3Bucket,S3_REGION:X.s3Region,S3_ACCESS_KEY_ID:X.s3AccessKeyId,S3_SECRET_ACCESS_KEY:X.s3SecretAccessKey,S3_FORCE_PATH_STYLE:String(X.s3ForcePathStyle),OTEL_SERVICE_NAME:X.otelServiceName,CLICKHOUSE_URL:X.clickhouseUrl,DECO_SUPABASE_URL:X.decoSupabaseUrl,DECO_SUPABASE_SERVICE_KEY:X.decoSupabaseServiceKey,FIRECRAWL_API_KEY:X.firecrawlApiKey,STUDIO_SANDBOX_RUNNER:process.env.STUDIO_SANDBOX_RUNNER,STUDIO_SANDBOX_TEMPLATE_NAME:process.env.STUDIO_SANDBOX_TEMPLATE_NAME,STUDIO_SANDBOX_PREVIEW_URL_PATTERN:process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN,STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME:process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME,STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE:process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE,KUBERNETES_SERVICE_HOST:process.env.KUBERNETES_SERVICE_HOST,KUBERNETES_SERVICE_PORT:process.env.KUBERNETES_SERVICE_PORT,FREESTYLE_API_KEY:process.env.FREESTYLE_API_KEY,BROWSERLESS_TOKEN:process.env.BROWSERLESS_TOKEN,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,DECO_CLI:"1",DECO_NO_TUI:"true",...Y}}function is6(X){if(!X)return!1;try{return new URL(X).host==="api.decocms.com"&&X!=="https://studio.decocms.com/org/deco/registry/mcp"}catch{return!1}}var cs6="https://studio.decocms.com/org/deco/registry/mcp";var aB0=(X,Y,G)=>{return(Q,J)=>{let W=-1;return Z(0);async function Z($){if($<=W)throw Error("next() called multiple times");W=$;let K,H=!1,U;if(X[$])U=X[$][0][0],Q.req.routeIndex=$;else U=$===X.length&&J||void 0;if(U)try{K=await U(Q,()=>Z($+1))}catch(B){if(B instanceof Error&&Y)Q.error=B,K=await Y(B,Q),H=!0;else throw B}else if(Q.finalized===!1&&G)K=await G(Q);if(K&&(Q.finalized===!1||H))Q.res=K;return Q}}};var ps6=()=>{};var M9;var Eq=D(()=>{M9=class extends Error{res;status;constructor(X=500,Y){super(Y?.message,{cause:Y?.cause});this.res=Y?.res,this.status=X}getResponse(){if(this.res)return new Response(this.res.body,{status:this.status,headers:this.res.headers});return new Response(this.message,{status:this.status})}}});var ns6;var as6=D(()=>{ns6=Symbol()});async function Vp5(X,Y){let G=await X.formData();if(G)return jp5(G,Y);return{}}function jp5(X,Y){let G=Object.create(null);if(X.forEach((Q,J)=>{if(!(Y.all||J.endsWith("[]")))G[J]=Q;else Mp5(G,J,Q)}),Y.dot)Object.entries(G).forEach(([Q,J])=>{if(Q.includes("."))Rp5(G,Q,J),delete G[Q]});return G}var ts6=async(X,Y=Object.create(null))=>{let{all:G=!1,dot:Q=!1}=Y,W=(X instanceof kA1?X.raw.headers:X.headers).get("Content-Type");if(W?.startsWith("multipart/form-data")||W?.startsWith("application/x-www-form-urlencoded"))return Vp5(X,{all:G,dot:Q});return{}},Mp5=(X,Y,G)=>{if(X[Y]!==void 0)if(Array.isArray(X[Y]))X[Y].push(G);else X[Y]=[X[Y],G];else if(!Y.endsWith("[]"))X[Y]=G;else X[Y]=[G]},Rp5=(X,Y,G)=>{if(/(?:^|\.)__proto__\./.test(Y))return;let Q=X,J=Y.split(".");J.forEach((W,Z)=>{if(Z===J.length-1)Q[W]=G;else{if(!Q[W]||typeof Q[W]!=="object"||Array.isArray(Q[W])||Q[W]instanceof File)Q[W]=Object.create(null);Q=Q[W]}})};var rs6=D(()=>{tB0()});var oB0=(X)=>{let Y=X.split("/");if(Y[0]==="")Y.shift();return Y},os6=(X)=>{let{groups:Y,path:G}=Sp5(X),Q=oB0(G);return Cp5(Q,Y)},Sp5=(X)=>{let Y=[];return X=X.replace(/\{[^}]+\}/g,(G,Q)=>{let J=`@${Q}`;return Y.push([J,G]),J}),{groups:Y,path:X}},Cp5=(X,Y)=>{for(let G=Y.length-1;G>=0;G--){let[Q]=Y[G];for(let J=X.length-1;J>=0;J--)if(X[J].includes(Q)){X[J]=X[J].replace(Q,Y[G][1]);break}}return X},vA1,ss6=(X,Y)=>{if(X==="*")return"*";let G=X.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(G){let Q=`${X}#${Y}`;if(!vA1[Q])if(G[2])vA1[Q]=Y&&Y[0]!==":"&&Y[0]!=="*"?[Q,G[1],new RegExp(`^${G[2]}(?=/${Y})`)]:[X,G[1],new RegExp(`^${G[2]}$`)];else vA1[Q]=[X,G[1],!0];return vA1[Q]}return null},ra=(X,Y)=>{try{return Y(X)}catch{return X.replace(/(?:%[0-9A-Fa-f]{2})+/g,(G)=>{try{return Y(G)}catch{return G}})}},es6=(X)=>ra(X,decodeURI),sB0=(X)=>{let Y=X.url,G=Y.indexOf("/",Y.indexOf(":")+4),Q=G;for(;Q<Y.length;Q++){let J=Y.charCodeAt(Q);if(J===37){let W=Y.indexOf("?",Q),Z=Y.indexOf("#",Q),$=W===-1?Z===-1?void 0:Z:Z===-1?W:Math.min(W,Z),K=Y.slice(G,$);return es6(K.includes("%25")?K.replace(/%25/g,"%2525"):K)}else if(J===63||J===35)break}return Y.slice(G,Q)},Xe6=(X)=>{let Y=sB0(X);return Y.length>1&&Y.at(-1)==="/"?Y.slice(0,-1):Y},Mj=(X,Y,...G)=>{if(G.length)Y=Mj(Y,...G);return`${X?.[0]==="/"?"":"/"}${X}${Y==="/"?"":`${X?.at(-1)==="/"?"":"/"}${Y?.[0]==="/"?Y.slice(1):Y}`}`},_A1=(X)=>{if(X.charCodeAt(X.length-1)!==63||!X.includes(":"))return null;let Y=X.split("/"),G=[],Q="";return Y.forEach((J)=>{if(J!==""&&!/\:/.test(J))Q+="/"+J;else if(/\:/.test(J))if(/\?/.test(J)){if(G.length===0&&Q==="")G.push("/");else G.push(Q);let W=J.replace("?","");Q+="/"+W,G.push(Q)}else Q+="/"+J}),G.filter((J,W,Z)=>Z.indexOf(J)===W)},rB0=(X)=>{if(!/[%+]/.test(X))return X;if(X.indexOf("+")!==-1)X=X.replace(/\+/g," ");return X.indexOf("%")!==-1?ra(X,MX1):X},Ye6=(X,Y,G)=>{let Q;if(!G&&Y&&!/[%+]/.test(Y)){let Z=X.indexOf("?",8);if(Z===-1)return;if(!X.startsWith(Y,Z+1))Z=X.indexOf(`&${Y}`,Z+1);while(Z!==-1){let $=X.charCodeAt(Z+Y.length+1);if($===61){let K=Z+Y.length+2,H=X.indexOf("&",K);return rB0(X.slice(K,H===-1?void 0:H))}else if($==38||isNaN($))return"";Z=X.indexOf(`&${Y}`,Z+1)}if(Q=/[%+]/.test(X),!Q)return}let J={};Q??=/[%+]/.test(X);let W=X.indexOf("?",8);while(W!==-1){let Z=X.indexOf("&",W+1),$=X.indexOf("=",W);if($>Z&&Z!==-1)$=-1;let K=X.slice(W+1,$===-1?Z===-1?void 0:Z:$);if(Q)K=rB0(K);if(W=Z,K==="")continue;let H;if($===-1)H="";else if(H=X.slice($+1,Z===-1?void 0:Z),Q)H=rB0(H);if(G){if(!(J[K]&&Array.isArray(J[K])))J[K]=[];J[K].push(H)}else J[K]??=H}return Y?J[Y]:J},Ge6,Qe6=(X,Y)=>{return Ye6(X,Y,!0)},MX1;var Pq=D(()=>{vA1={},Ge6=Ye6,MX1=decodeURIComponent});var Je6=(X)=>ra(X,MX1),kA1;var tB0=D(()=>{Eq();as6();rs6();Pq();kA1=class{raw;#X;#Y;routeIndex=0;path;bodyCache={};constructor(X,Y="/",G=[[]]){this.raw=X,this.path=Y,this.#Y=G,this.#X={}}param(X){return X?this.#G(X):this.#Q()}#G(X){let Y=this.#Y[0][this.routeIndex][1][X],G=this.#J(Y);return G&&/\%/.test(G)?Je6(G):G}#Q(){let X={},Y=Object.keys(this.#Y[0][this.routeIndex][1]);for(let G of Y){let Q=this.#J(this.#Y[0][this.routeIndex][1][G]);if(Q!==void 0)X[G]=/\%/.test(Q)?Je6(Q):Q}return X}#J(X){return this.#Y[1]?this.#Y[1][X]:X}query(X){return Ge6(this.url,X)}queries(X){return Qe6(this.url,X)}header(X){if(X)return this.raw.headers.get(X)??void 0;let Y={};return this.raw.headers.forEach((G,Q)=>{Y[Q]=G}),Y}async parseBody(X){return ts6(this,X)}#Z=(X)=>{let{bodyCache:Y,raw:G}=this,Q=Y[X];if(Q)return Q;let J=Object.keys(Y)[0];if(J)return Y[J].then((W)=>{if(J==="json")W=JSON.stringify(W);return new Response(W)[X]()});return Y[X]=G[X]()};json(){return this.#Z("text").then((X)=>JSON.parse(X))}text(){return this.#Z("text")}arrayBuffer(){return this.#Z("arrayBuffer")}blob(){return this.#Z("blob")}formData(){return this.#Z("formData")}addValidatedData(X,Y){this.#X[X]=Y}valid(X){return this.#X[X]}get url(){return this.raw.url}get method(){return this.raw.method}get[ns6](){return this.#Y}get matchedRoutes(){return this.#Y[0].map(([[,X]])=>X)}get routePath(){return this.#Y[0].map(([[,X]])=>X)[this.routeIndex].path}}});var fA1,Ze6=(X,Y)=>{let G=new String(X);return G.isEscaped=!0,G.callbacks=Y,G},RX1=async(X,Y,G,Q,J)=>{if(typeof X==="object"&&!(X instanceof String)){if(!(X instanceof Promise))X=X.toString();if(X instanceof Promise)X=await X}let W=X.callbacks;if(!W?.length)return Promise.resolve(X);if(J)J[0]+=X;else J=[X];let Z=Promise.all(W.map(($)=>$({phase:Y,buffer:J,context:Q}))).then(($)=>Promise.all($.filter(Boolean).map((K)=>RX1(K,Y,!1,Q,J))).then(()=>J[0]));if(G)return Ze6(await Z,W);else return Z};var bA1=D(()=>{fA1={Stringify:1,BeforeStream:2,Stream:3}});var We6="text/plain; charset=UTF-8",eB0=(X,Y)=>{return{"Content-Type":X,...Y}},SX1=(X,Y)=>new Response(X,Y),$e6=class{#X;#Y;env={};#G;finalized=!1;error;#Q;#J;#Z;#$;#W;#K;#H;#U;#B;constructor(X,Y){if(this.#X=X,Y)this.#J=Y.executionCtx,this.env=Y.env,this.#K=Y.notFoundHandler,this.#B=Y.path,this.#U=Y.matchResult}get req(){return this.#Y??=new kA1(this.#X,this.#B,this.#U),this.#Y}get event(){if(this.#J&&"respondWith"in this.#J)return this.#J;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#J)return this.#J;else throw Error("This context has no ExecutionContext")}get res(){return this.#Z||=SX1(null,{headers:this.#H??=new Headers})}set res(X){if(this.#Z&&X){X=SX1(X.body,X);for(let[Y,G]of this.#Z.headers.entries()){if(Y==="content-type")continue;if(Y==="set-cookie"){let Q=this.#Z.headers.getSetCookie();X.headers.delete("set-cookie");for(let J of Q)X.headers.append("set-cookie",J)}else X.headers.set(Y,G)}}this.#Z=X,this.finalized=!0}render=(...X)=>{return this.#W??=(Y)=>this.html(Y),this.#W(...X)};setLayout=(X)=>this.#$=X;getLayout=()=>this.#$;setRenderer=(X)=>{this.#W=X};header=(X,Y,G)=>{if(this.finalized)this.#Z=SX1(this.#Z.body,this.#Z);let Q=this.#Z?this.#Z.headers:this.#H??=new Headers;if(Y===void 0)Q.delete(X);else if(G?.append)Q.append(X,Y);else Q.set(X,Y)};status=(X)=>{this.#Q=X};set=(X,Y)=>{this.#G??=new Map,this.#G.set(X,Y)};get=(X)=>{return this.#G?this.#G.get(X):void 0};get var(){if(!this.#G)return{};return Object.fromEntries(this.#G)}#F(X,Y,G){let Q=this.#Z?new Headers(this.#Z.headers):this.#H??new Headers;if(typeof Y==="object"&&"headers"in Y){let W=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);for(let[Z,$]of W)if(Z.toLowerCase()==="set-cookie")Q.append(Z,$);else Q.set(Z,$)}if(G)for(let[W,Z]of Object.entries(G))if(typeof Z==="string")Q.set(W,Z);else{Q.delete(W);for(let $ of Z)Q.append(W,$)}let J=typeof Y==="number"?Y:Y?.status??this.#Q;return SX1(X,{status:J,headers:Q})}newResponse=(...X)=>this.#F(...X);body=(X,Y,G)=>this.#F(X,Y,G);text=(X,Y,G)=>{return!this.#H&&!this.#Q&&!Y&&!G&&!this.finalized?new Response(X):this.#F(X,Y,eB0(We6,G))};json=(X,Y,G)=>{return this.#F(JSON.stringify(X),Y,eB0("application/json",G))};html=(X,Y,G)=>{let Q=(J)=>this.#F(J,Y,eB0("text/html; charset=UTF-8",G));return typeof X==="object"?RX1(X,fA1.Stringify,!1,{}).then(Q):Q(X)};redirect=(X,Y)=>{let G=String(X);return this.header("Location",!/[^\x00-\xFF]/.test(G)?G:encodeURI(G)),this.newResponse(null,Y??302)};notFound=()=>{return this.#K??=()=>SX1(),this.#K(this)}};var yA1=D(()=>{tB0();bA1()});var T7="ALL",Ke6="all",He6,xA1="Can not add a route since the matcher is already built.",hA1;var qq=D(()=>{He6=["get","post","put","delete","options","patch"],hA1=class extends Error{}});var XN0="__COMPOSED_HANDLER";var YN0=()=>{};var kp5=(X)=>{return X.text("404 Not Found",404)},Fe6=(X,Y)=>{if("getResponse"in X){let G=X.getResponse();return Y.newResponse(G.body,G)}return console.error(X),Y.text("Internal Server Error",500)},Ue6=class X{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath="/";#X="/";routes=[];constructor(Y={}){[...He6,Ke6].forEach((W)=>{this[W]=(Z,...$)=>{if(typeof Z==="string")this.#X=Z;else this.#Q(W,this.#X,Z);return $.forEach((K)=>{this.#Q(W,this.#X,K)}),this}}),this.on=(W,Z,...$)=>{for(let K of[Z].flat()){this.#X=K;for(let H of[W].flat())$.map((U)=>{this.#Q(H.toUpperCase(),this.#X,U)})}return this},this.use=(W,...Z)=>{if(typeof W==="string")this.#X=W;else this.#X="*",Z.unshift(W);return Z.forEach(($)=>{this.#Q(T7,this.#X,$)}),this};let{strict:Q,...J}=Y;Object.assign(this,J),this.getPath=Q??!0?Y.getPath??sB0:Xe6}#Y(){let Y=new X({router:this.router,getPath:this.getPath});return Y.errorHandler=this.errorHandler,Y.#G=this.#G,Y.routes=this.routes,Y}#G=kp5;errorHandler=Fe6;route(Y,G){let Q=this.basePath(Y);return G.routes.map((J)=>{let W;if(G.errorHandler===Fe6)W=J.handler;else W=async(Z,$)=>(await aB0([],G.errorHandler)(Z,()=>J.handler(Z,$))).res,W[XN0]=J.handler;Q.#Q(J.method,J.path,W)}),this}basePath(Y){let G=this.#Y();return G._basePath=Mj(this._basePath,Y),G}onError=(Y)=>{return this.errorHandler=Y,this};notFound=(Y)=>{return this.#G=Y,this};mount(Y,G,Q){let J,W;if(Q)if(typeof Q==="function")W=Q;else if(W=Q.optionHandler,Q.replaceRequest===!1)J=(K)=>K;else J=Q.replaceRequest;let Z=W?(K)=>{let H=W(K);return Array.isArray(H)?H:[H]}:(K)=>{let H=void 0;try{H=K.executionCtx}catch{}return[K.env,H]};J||=(()=>{let K=Mj(this._basePath,Y),H=K==="/"?0:K.length;return(U)=>{let B=new URL(U.url);return B.pathname=B.pathname.slice(H)||"/",new Request(B,U)}})();let $=async(K,H)=>{let U=await G(J(K.req.raw),...Z(K));if(U)return U;await H()};return this.#Q(T7,Mj(Y,"*"),$),this}#Q(Y,G,Q){Y=Y.toUpperCase(),G=Mj(this._basePath,G);let J={basePath:this._basePath,path:G,method:Y,handler:Q};this.router.add(Y,G,[Q,J]),this.routes.push(J)}#J(Y,G){if(Y instanceof Error)return this.errorHandler(Y,G);throw Y}#Z(Y,G,Q,J){if(J==="HEAD")return(async()=>new Response(null,await this.#Z(Y,G,Q,"GET")))();let W=this.getPath(Y,{env:Q}),Z=this.router.match(J,W),$=new $e6(Y,{path:W,matchResult:Z,env:Q,executionCtx:G,notFoundHandler:this.#G});if(Z[0].length===1){let H;try{H=Z[0][0][0][0]($,async()=>{$.res=await this.#G($)})}catch(U){return this.#J(U,$)}return H instanceof Promise?H.then((U)=>U||($.finalized?$.res:this.#G($))).catch((U)=>this.#J(U,$)):H??this.#G($)}let K=aB0(Z[0],this.errorHandler,this.#G);return(async()=>{try{let H=await K($);if(!H.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return H.res}catch(H){return this.#J(H,$)}})()}fetch=(Y,...G)=>{return this.#Z(Y,G[1],G[0],Y.method)};request=(Y,G,Q,J)=>{if(Y instanceof Request)return this.fetch(G?new Request(Y,G):Y,Q,J);return Y=Y.toString(),this.fetch(new Request(/^https?:\/\//.test(Y)?Y:`http://localhost${Mj("/",Y)}`,G),Q,J)};fire=()=>{addEventListener("fetch",(Y)=>{Y.respondWith(this.#Z(Y.request,Y,void 0,Y.request.method))})}};var Be6=D(()=>{ps6();yA1();qq();YN0();Pq()});function gA1(X,Y){let G=this.buildAllMatchers(),Q=(J,W)=>{let Z=G[J]||G[T7],$=Z[2][W];if($)return $;let K=W.match(Z[0]);if(!K)return[[],CX1];let H=K.indexOf("",1);return[Z[1][H],K]};return this.match=Q,Q(X,Y)}var CX1;var GN0=D(()=>{qq();CX1=[]});function _p5(X,Y){if(X.length===1)return Y.length===1?X<Y?-1:1:-1;if(Y.length===1)return 1;if(X===kX1||X===vX1)return 1;else if(Y===kX1||Y===vX1)return-1;if(X===uA1)return 1;else if(Y===uA1)return-1;return X.length===Y.length?X<Y?-1:1:Y.length-X.length}var uA1="[^/]+",kX1=".*",vX1="(?:|/.*)",Rj,vp5,Ne6=class X{#X;#Y;#G=Object.create(null);insert(Y,G,Q,J,W){if(Y.length===0){if(this.#X!==void 0)throw Rj;if(W)return;this.#X=G;return}let[Z,...$]=Y,K=Z==="*"?$.length===0?["","",kX1]:["","",uA1]:Z==="/*"?["","",vX1]:Z.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),H;if(K){let U=K[1],B=K[2]||uA1;if(U&&K[2]){if(B===".*")throw Rj;if(B=B.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(B))throw Rj}if(H=this.#G[B],!H){if(Object.keys(this.#G).some((N)=>N!==kX1&&N!==vX1))throw Rj;if(W)return;if(H=this.#G[B]=new X,U!=="")H.#Y=J.varIndex++}if(!W&&U!=="")Q.push([U,H.#Y])}else if(H=this.#G[Z],!H){if(Object.keys(this.#G).some((U)=>U.length>1&&U!==kX1&&U!==vX1))throw Rj;if(W)return;H=this.#G[Z]=new X}H.insert($,G,Q,J,W)}buildRegExpStr(){let G=Object.keys(this.#G).sort(_p5).map((Q)=>{let J=this.#G[Q];return(typeof J.#Y==="number"?`(${Q})@${J.#Y}`:vp5.has(Q)?`\\${Q}`:Q)+J.buildRegExpStr()});if(typeof this.#X==="number")G.unshift(`#${this.#X}`);if(G.length===0)return"";if(G.length===1)return G[0];return"(?:"+G.join("|")+")"}};var QN0=D(()=>{Rj=Symbol(),vp5=new Set(".\\+*[^]$()")});var ze6=class{#X={varIndex:0};#Y=new Ne6;insert(X,Y,G){let Q=[],J=[];for(let Z=0;;){let $=!1;if(X=X.replace(/\{[^}]+\}/g,(K)=>{let H=`@\\${Z}`;return J[Z]=[H,K],Z++,$=!0,H}),!$)break}let W=X.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let Z=J.length-1;Z>=0;Z--){let[$]=J[Z];for(let K=W.length-1;K>=0;K--)if(W[K].indexOf($)!==-1){W[K]=W[K].replace($,J[Z][1]);break}}return this.#Y.insert(W,Y,Q,this.#X,G),Q}buildRegExp(){let X=this.#Y.buildRegExpStr();if(X==="")return[/^$/,[],[]];let Y=0,G=[],Q=[];return X=X.replace(/#(\d+)|@(\d+)|\.\*\$/g,(J,W,Z)=>{if(W!==void 0)return G[++Y]=Number(W),"$()";if(Z!==void 0)return Q[Number(Z)]=++Y,"";return""}),[new RegExp(`^${X}`),G,Q]}};var Oe6=D(()=>{QN0()});function we6(X){return De6[X]??=new RegExp(X==="*"?"":`^${X.replace(/\/\*$|([.\\+*[^\]$()])/g,(Y,G)=>G?`\\${G}`:"(?:|/.*)")}$`)}function bp5(){De6=Object.create(null)}function yp5(X){let Y=new ze6,G=[];if(X.length===0)return fp5;let Q=X.map((H)=>[!/\*|\/:/.test(H[0]),...H]).sort(([H,U],[B,N])=>H?1:B?-1:U.length-N.length),J=Object.create(null);for(let H=0,U=-1,B=Q.length;H<B;H++){let[N,z,O]=Q[H];if(N)J[z]=[O.map(([E])=>[E,Object.create(null)]),CX1];else U++;let w;try{w=Y.insert(z,U,N)}catch(E){throw E===Rj?new hA1(z):E}if(N)continue;G[U]=O.map(([E,P])=>{let q=Object.create(null);P-=1;for(;P>=0;P--){let[M,j]=w[P];q[M]=j}return[E,q]})}let[W,Z,$]=Y.buildRegExp();for(let H=0,U=G.length;H<U;H++)for(let B=0,N=G[H].length;B<N;B++){let z=G[H][B]?.[1];if(!z)continue;let O=Object.keys(z);for(let w=0,E=O.length;w<E;w++)z[O[w]]=$[z[O[w]]]}let K=[];for(let H in Z)K[H]=G[Z[H]];return[W,K,J]}function oa(X,Y){if(!X)return;for(let G of Object.keys(X).sort((Q,J)=>J.length-Q.length))if(we6(G).test(Y))return[...X[G]];return}var fp5,De6,lA1=class{name="RegExpRouter";#X;#Y;constructor(){this.#X={[T7]:Object.create(null)},this.#Y={[T7]:Object.create(null)}}add(X,Y,G){let Q=this.#X,J=this.#Y;if(!Q||!J)throw Error(xA1);if(!Q[X])[Q,J].forEach(($)=>{$[X]=Object.create(null),Object.keys($[T7]).forEach((K)=>{$[X][K]=[...$[T7][K]]})});if(Y==="/*")Y="*";let W=(Y.match(/\/:/g)||[]).length;if(/\*$/.test(Y)){let $=we6(Y);if(X===T7)Object.keys(Q).forEach((K)=>{Q[K][Y]||=oa(Q[K],Y)||oa(Q[T7],Y)||[]});else Q[X][Y]||=oa(Q[X],Y)||oa(Q[T7],Y)||[];Object.keys(Q).forEach((K)=>{if(X===T7||X===K)Object.keys(Q[K]).forEach((H)=>{$.test(H)&&Q[K][H].push([G,W])})}),Object.keys(J).forEach((K)=>{if(X===T7||X===K)Object.keys(J[K]).forEach((H)=>$.test(H)&&J[K][H].push([G,W]))});return}let Z=_A1(Y)||[Y];for(let $=0,K=Z.length;$<K;$++){let H=Z[$];Object.keys(J).forEach((U)=>{if(X===T7||X===U)J[U][H]||=[...oa(Q[U],H)||oa(Q[T7],H)||[]],J[U][H].push([G,W-K+$+1])})}}match=gA1;buildAllMatchers(){let X=Object.create(null);return Object.keys(this.#Y).concat(Object.keys(this.#X)).forEach((Y)=>{X[Y]||=this.#G(Y)}),this.#X=this.#Y=void 0,bp5(),X}#G(X){let Y=[],G=X===T7;if([this.#X,this.#Y].forEach((Q)=>{let J=Q[X]?Object.keys(Q[X]).map((W)=>[W,Q[X][W]]):[];if(J.length!==0)G||=!0,Y.push(...J);else if(X!==T7)Y.push(...Object.keys(Q[T7]).map((W)=>[W,Q[T7][W]]))}),!G)return null;else return yp5(Y)}};var JN0=D(()=>{qq();Pq();GN0();QN0();Oe6();fp5=[/^$/,[],Object.create(null)],De6=Object.create(null)});var xp5=class{name="PreparedRegExpRouter";#X;#Y;constructor(X,Y){this.#X=X,this.#Y=Y}#G(X,Y){let G=this.#X[X];G[1].forEach((Q)=>Q&&Q.push(Y)),Object.values(G[2]).forEach((Q)=>Q[0].push(Y))}#Q(X,Y,G,Q,J){let W=this.#X[X];if(!J)W[2][Y][0].push([G,{}]);else Q.forEach((Z)=>{if(typeof Z==="number")W[1][Z].push([G,J]);else W[2][Z||Y][0].push([G,J])})}add(X,Y,G){if(!this.#X[X]){let J=this.#X[T7],W={};for(let Z in J[2])W[Z]=[J[2][Z][0].slice(),CX1];this.#X[X]=[J[0],J[1].map((Z)=>Array.isArray(Z)?Z.slice():0),W]}if(Y==="/*"||Y==="*"){let J=[G,{}];if(X===T7)for(let W in this.#X)this.#G(W,J);else this.#G(X,J);return}let Q=this.#Y[Y];if(!Q)throw Error(`Path ${Y} is not registered`);for(let[J,W]of Q)if(X===T7)for(let Z in this.#X)this.#Q(Z,Y,G,J,W);else this.#Q(X,Y,G,J,W)}buildAllMatchers(){return this.#X}match=gA1};var Le6=D(()=>{qq();GN0();JN0()});var Ee6=D(()=>{JN0();Le6()});var ZN0=class{name="SmartRouter";#X=[];#Y=[];constructor(X){this.#X=X.routers}add(X,Y,G){if(!this.#Y)throw Error(xA1);this.#Y.push([X,Y,G])}match(X,Y){if(!this.#Y)throw Error("Fatal error");let G=this.#X,Q=this.#Y,J=G.length,W=0,Z;for(;W<J;W++){let $=G[W];try{for(let K=0,H=Q.length;K<H;K++)$.add(...Q[K]);Z=$.match(X,Y)}catch(K){if(K instanceof hA1)continue;throw K}this.match=$.match.bind($),this.#X=[$],this.#Y=void 0;break}if(W===J)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,Z}get activeRouter(){if(this.#Y||this.#X.length!==1)throw Error("No active router has been determined yet.");return this.#X[0]}};var Pe6=D(()=>{qq()});var qe6=D(()=>{Pe6()});var _X1,hp5=(X)=>{for(let Y in X)return!0;return!1},Ae6=class X{#X;#Y;#G;#Q=0;#J=_X1;constructor(Y,G,Q){if(this.#Y=Q||Object.create(null),this.#X=[],Y&&G){let J=Object.create(null);J[Y]={handler:G,possibleKeys:[],score:0},this.#X=[J]}this.#G=[]}insert(Y,G,Q){this.#Q=++this.#Q;let J=this,W=os6(G),Z=[];for(let $=0,K=W.length;$<K;$++){let H=W[$],U=W[$+1],B=ss6(H,U),N=Array.isArray(B)?B[0]:H;if(N in J.#Y){if(J=J.#Y[N],B)Z.push(B[1]);continue}if(J.#Y[N]=new X,B)J.#G.push(B),Z.push(B[1]);J=J.#Y[N]}return J.#X.push({[Y]:{handler:Q,possibleKeys:Z.filter(($,K,H)=>H.indexOf($)===K),score:this.#Q}}),J}#Z(Y,G,Q,J,W){for(let Z=0,$=G.#X.length;Z<$;Z++){let K=G.#X[Z],H=K[Q]||K[T7],U={};if(H!==void 0){if(H.params=Object.create(null),Y.push(H),J!==_X1||W&&W!==_X1)for(let B=0,N=H.possibleKeys.length;B<N;B++){let z=H.possibleKeys[B],O=U[H.score];H.params[z]=W?.[z]&&!O?W[z]:J[z]??W?.[z],U[H.score]=!0}}}}search(Y,G){let Q=[];this.#J=_X1;let W=[this],Z=oB0(G),$=[],K=Z.length,H=null;for(let U=0;U<K;U++){let B=Z[U],N=U===K-1,z=[];for(let w=0,E=W.length;w<E;w++){let P=W[w],q=P.#Y[B];if(q)if(q.#J=P.#J,N){if(q.#Y["*"])this.#Z(Q,q.#Y["*"],Y,P.#J);this.#Z(Q,q,Y,P.#J)}else z.push(q);for(let M=0,j=P.#G.length;M<j;M++){let V=P.#G[M],R=P.#J===_X1?{}:{...P.#J};if(V==="*"){let h=P.#Y["*"];if(h)this.#Z(Q,h,Y,P.#J),h.#J=R,z.push(h);continue}let[k,_,v]=V;if(!B&&!(v instanceof RegExp))continue;let y=P.#Y[k];if(v instanceof RegExp){if(H===null){H=Array(K);let p=G[0]==="/"?1:0;for(let f=0;f<K;f++)H[f]=p,p+=Z[f].length+1}let h=G.substring(H[U]),i=v.exec(h);if(i){if(R[_]=i[0],this.#Z(Q,y,Y,P.#J,R),hp5(y.#Y)){y.#J=R;let p=i[0].match(/\//)?.length??0;($[p]||=[]).push(y)}continue}}if(v===!0||v.test(B))if(R[_]=B,N){if(this.#Z(Q,y,Y,R,P.#J),y.#Y["*"])this.#Z(Q,y.#Y["*"],Y,R,P.#J)}else y.#J=R,z.push(y)}}let O=$.shift();W=O?z.concat(O):z}if(Q.length>1)Q.sort((U,B)=>{return U.score-B.score});return[Q.map(({handler:U,params:B})=>[U,B])]}};var Te6=D(()=>{qq();Pq();_X1=Object.create(null)});var WN0=class{name="TrieRouter";#X;constructor(){this.#X=new Ae6}add(X,Y,G){let Q=_A1(Y);if(Q){for(let J=0,W=Q.length;J<W;J++)this.#X.insert(X,Q[J],G);return}this.#X.insert(X,Y,G)}match(X,Y){return this.#X.search(X,Y)}};var Ie6=D(()=>{Pq();Te6()});var Ve6=D(()=>{Ie6()});var U5;var je6=D(()=>{Be6();Ee6();qe6();Ve6();U5=class extends Ue6{constructor(X={}){super(X);this.router=X.router??new ZN0({routers:[new lA1,new WN0]})}}});var NG=D(()=>{je6()});var Re6,gp5,Me6=(X)=>{let Y=0,G=X.length;while(Y<G){let Q=X.charCodeAt(Y);if(Q!==32&&Q!==9)break;Y++}while(G>Y){let Q=X.charCodeAt(G-1);if(Q!==32&&Q!==9)break;G--}return Y===0&&G===X.length?X:X.slice(Y,G)},$N0=(X,Y)=>{if(Y&&X.indexOf(Y)===-1)return{};let G=X.split(";"),Q={};for(let J of G){let W=J.indexOf("=");if(W===-1)continue;let Z=Me6(J.substring(0,W));if(Y&&Y!==Z||!Re6.test(Z))continue;let $=Me6(J.substring(W+1));if($.startsWith('"')&&$.endsWith('"'))$=$.slice(1,-1);if(gp5.test($)){if(Q[Z]=$.indexOf("%")!==-1?ra($,MX1):$,Y)break}}return Q},up5=(X,Y,G={})=>{if(!Re6.test(X))throw Error("Invalid cookie name");let Q=`${X}=${Y}`;if(X.startsWith("__Secure-")&&!G.secure)throw Error("__Secure- Cookie must have Secure attributes");if(X.startsWith("__Host-")){if(!G.secure)throw Error("__Host- Cookie must have Secure attributes");if(G.path!=="/")throw Error('__Host- Cookie must have Path attributes with "/"');if(G.domain)throw Error("__Host- Cookie must not have Domain attributes")}for(let J of["domain","path"])if(G[J]&&/[;\r\n]/.test(G[J]))throw Error(`${J} must not contain ";", "\\r", or "\\n"`);if(G&&typeof G.maxAge==="number"&&G.maxAge>=0){if(G.maxAge>34560000)throw Error("Cookies Max-Age SHOULD NOT be greater than 400 days (34560000 seconds) in duration.");Q+=`; Max-Age=${G.maxAge|0}`}if(G.domain&&G.prefix!=="host")Q+=`; Domain=${G.domain}`;if(G.path)Q+=`; Path=${G.path}`;if(G.expires){if(G.expires.getTime()-Date.now()>34560000000)throw Error("Cookies Expires SHOULD NOT be greater than 400 days (34560000 seconds) in the future.");Q+=`; Expires=${G.expires.toUTCString()}`}if(G.httpOnly)Q+="; HttpOnly";if(G.secure)Q+="; Secure";if(G.sameSite)Q+=`; SameSite=${G.sameSite.charAt(0).toUpperCase()+G.sameSite.slice(1)}`;if(G.priority)Q+=`; Priority=${G.priority.charAt(0).toUpperCase()+G.priority.slice(1)}`;if(G.partitioned){if(!G.secure)throw Error("Partitioned Cookie must have Secure attributes");Q+="; Partitioned"}return Q},mA1=(X,Y,G)=>{return Y=encodeURIComponent(Y),up5(X,Y,G)};var Se6=D(()=>{Pq();Re6=/^[\w!#$%&'*.^`|~+-]+$/,gp5=/^[ !#-:<-[\]-~]*$/});var dA1=(X,Y,G)=>{let Q=X.req.raw.headers.get("Cookie");if(typeof Y==="string"){if(!Q)return;let W=Y;if(G==="secure")W="__Secure-"+Y;else if(G==="host")W="__Host-"+Y;return $N0(Q,W)[W]}if(!Q)return{};return $N0(Q)},lp5=(X,Y,G)=>{let Q;if(G?.prefix==="secure")Q=mA1("__Secure-"+X,Y,{path:"/",...G,secure:!0});else if(G?.prefix==="host")Q=mA1("__Host-"+X,Y,{...G,path:"/",secure:!0,domain:void 0});else Q=mA1(X,Y,{path:"/",...G});return Q},KN0=(X,Y,G,Q)=>{let J=lp5(Y,G,Q);X.header("Set-Cookie",J,{append:!0})};var HN0=D(()=>{Se6()});var Ce6=(X)=>{let G={...{origin:"*",allowMethods:["GET","HEAD","PUT","POST","DELETE","PATCH"],allowHeaders:[],exposeHeaders:[]},...X},Q=((W)=>{if(typeof W==="string")if(W==="*"){if(G.credentials)return(Z)=>Z||null;return()=>W}else return(Z)=>W===Z?Z:null;else if(typeof W==="function")return W;else return(Z)=>W.includes(Z)?Z:null})(G.origin),J=((W)=>{if(typeof W==="function")return W;else if(Array.isArray(W))return()=>W;else return()=>[]})(G.allowMethods);return async function(Z,$){function K(U,B){Z.res.headers.set(U,B)}let H=await Q(Z.req.header("origin")||"",Z);if(H)K("Access-Control-Allow-Origin",H);if(G.credentials)K("Access-Control-Allow-Credentials","true");if(G.exposeHeaders?.length)K("Access-Control-Expose-Headers",G.exposeHeaders.join(","));if(Z.req.method==="OPTIONS"){if(G.origin!=="*"||G.credentials)K("Vary","Origin");if(G.maxAge!=null)K("Access-Control-Max-Age",G.maxAge.toString());let U=await J(Z.req.header("origin")||"",Z);if(U.length)K("Access-Control-Allow-Methods",U.join(","));let B=G.allowHeaders;if(!B?.length){let N=Z.req.header("Access-Control-Request-Headers");if(N)B=N.split(/\s*,\s*/)}if(B?.length)K("Access-Control-Allow-Headers",B.join(",")),Z.res.headers.append("Vary","Access-Control-Request-Headers");return Z.res.headers.delete("Content-Length"),Z.res.headers.delete("Content-Type"),new Response(null,{headers:Z.res.headers,status:204,statusText:"No Content"})}if(await $(),G.origin!=="*"||G.credentials)Z.header("Vary","Origin",{append:!0})}};var ke6=()=>{};var ve6=()=>{try{return performance.now()}catch{}return Date.now()},FN0=(X)=>{let Y={total:!0,enabled:!0,totalDescription:"Total Response Time",autoEnd:!0,crossOrigin:!1,...X};return async function(Q,J){let W=[],Z=new Map;if(Q.get("metric"))return await J();if(Q.set("metric",{headers:W,timers:Z}),Y.total)OH(Q,"total",Y.totalDescription);if(await J(),Y.total)g$(Q,"total");if(Y.autoEnd)Z.forEach((K,H)=>g$(Q,H));if(typeof Y.enabled==="function"?Y.enabled(Q):Y.enabled){Q.res.headers.append("Server-Timing",W.join(","));let K=typeof Y.crossOrigin==="function"?Y.crossOrigin(Q):Y.crossOrigin;if(K)Q.res.headers.append("Timing-Allow-Origin",typeof K==="string"?K:"*")}}},_e6=(X,Y,G,Q,J)=>{let W=X.get("metric");if(!W){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}if(typeof G==="number"){let Z=G.toFixed(J||1),$=Q?`${Y};dur=${Z};desc="${Q}"`:`${Y};dur=${Z}`;W.headers.push($)}else{let Z=G?`${Y};desc="${G}"`:`${Y}`;W.headers.push(Z)}},OH=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}Q.timers.set(Y,{description:G,start:ve6()})},g$=(X,Y,G)=>{let Q=X.get("metric");if(!Q){console.warn("Metrics not initialized! Please add the `timing()` middleware to this route!");return}let J=Q.timers.get(Y);if(!J){console.warn(`Timer "${Y}" does not exist!`);return}let{description:W,start:Z}=J,$=ve6()-Z;_e6(X,Y,$,W,G),Q.timers.delete(Y)};var fe6=D(()=>{yA1()});var UN0=D(()=>{fe6()});function fX1(){let X={Organizations:[],Connections:[],"Virtual MCPs":[],Threads:[],Monitoring:[],Users:[],"API Keys":[],"Event Bus":[],Tags:[],"AI Providers":[],Automations:[],"Object Storage":[],Registry:[],GitHub:[],VM:[]};for(let Y of BN0)X[Y.category]?.push(Y);return X}var BN0;var NN0=D(()=>{BN0=[{name:"ORGANIZATION_CREATE",description:"Create a new organization",category:"Organizations"},{name:"ORGANIZATION_LIST",description:"List organizations",category:"Organizations"},{name:"ORGANIZATION_GET",description:"View organization details",category:"Organizations"},{name:"ORGANIZATION_UPDATE",description:"Update organization",category:"Organizations"},{name:"ORGANIZATION_DELETE",description:"Delete organization",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_SETTINGS_GET",description:"View organization settings",category:"Organizations"},{name:"ORGANIZATION_SETTINGS_UPDATE",description:"Update organization settings",category:"Organizations"},{name:"BRAND_CONTEXT_LIST",description:"List brand contexts",category:"Organizations"},{name:"BRAND_CONTEXT_GET",description:"View brand context",category:"Organizations"},{name:"BRAND_CONTEXT_CREATE",description:"Create brand context",category:"Organizations"},{name:"BRAND_CONTEXT_UPDATE",description:"Update brand context",category:"Organizations"},{name:"BRAND_CONTEXT_DELETE",description:"Delete brand context",category:"Organizations",dangerous:!0},{name:"BRAND_CONTEXT_EXTRACT",description:"Extract brand context from website",category:"Organizations"},{name:"BRAND_GET",description:"Get brand (binding)",category:"Organizations"},{name:"BRAND_LIST",description:"List brands (binding)",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_GET",description:"Get organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_SET",description:"Set organization domain claim",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_UPDATE",description:"Update organization domain settings",category:"Organizations"},{name:"ORGANIZATION_DOMAIN_CLEAR",description:"Clear organization domain claim",category:"Organizations"},{name:"ORGANIZATION_MEMBER_ADD",description:"Add members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_REMOVE",description:"Remove members",category:"Organizations",dangerous:!0},{name:"ORGANIZATION_MEMBER_LIST",description:"List members",category:"Organizations"},{name:"ORGANIZATION_MEMBER_UPDATE_ROLE",description:"Update member roles",category:"Organizations"},{name:"COLLECTION_CONNECTIONS_CREATE",description:"Create connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_LIST",description:"List connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_GET",description:"View connection details",category:"Connections"},{name:"COLLECTION_CONNECTIONS_UPDATE",description:"Update connections",category:"Connections"},{name:"COLLECTION_CONNECTIONS_DELETE",description:"Delete connections",category:"Connections",dangerous:!0},{name:"CONNECTION_TEST",description:"Test connections",category:"Connections"},{name:"DATABASES_RUN_SQL",description:"Run SQL queries",category:"Connections",dangerous:!0},{name:"COLLECTION_VIRTUAL_MCP_CREATE",description:"Create virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_LIST",description:"List virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_GET",description:"View virtual MCP details",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_UPDATE",description:"Update virtual MCPs",category:"Virtual MCPs"},{name:"COLLECTION_VIRTUAL_MCP_DELETE",description:"Delete virtual MCPs",category:"Virtual MCPs",dangerous:!0},{name:"MONITORING_LOG_GET",description:"View monitoring log details",category:"Monitoring"},{name:"MONITORING_LOGS_LIST",description:"List monitoring logs",category:"Monitoring"},{name:"MONITORING_STATS",description:"View monitoring statistics",category:"Monitoring"},{name:"API_KEY_CREATE",description:"Create API key",category:"API Keys"},{name:"API_KEY_LIST",description:"List API keys",category:"API Keys"},{name:"API_KEY_UPDATE",description:"Update API key",category:"API Keys"},{name:"API_KEY_DELETE",description:"Delete API key",category:"API Keys",dangerous:!0},{name:"EVENT_PUBLISH",description:"Publish events",category:"Event Bus"},{name:"EVENT_SUBSCRIBE",description:"Subscribe to events",category:"Event Bus"},{name:"EVENT_UNSUBSCRIBE",description:"Unsubscribe from events",category:"Event Bus"},{name:"EVENT_CANCEL",description:"Cancel recurring events",category:"Event Bus"},{name:"EVENT_ACK",description:"Acknowledge event delivery",category:"Event Bus"},{name:"EVENT_SUBSCRIPTION_LIST",description:"List event subscriptions",category:"Event Bus"},{name:"EVENT_SYNC_SUBSCRIPTIONS",description:"Sync subscriptions to desired state",category:"Event Bus"},{name:"USER_GET",description:"Get a user by id",category:"Users"},{name:"COLLECTION_THREADS_CREATE",description:"Create threads",category:"Threads"},{name:"COLLECTION_THREADS_LIST",description:"List threads",category:"Threads"},{name:"COLLECTION_THREADS_GET",description:"View thread details",category:"Threads"},{name:"COLLECTION_THREADS_UPDATE",description:"Update threads",category:"Threads"},{name:"COLLECTION_THREADS_DELETE",description:"Delete threads",category:"Threads",dangerous:!0},{name:"COLLECTION_THREAD_MESSAGES_LIST",description:"List thread messages",category:"Threads"},{name:"TAGS_LIST",description:"List organization tags",category:"Tags"},{name:"TAGS_CREATE",description:"Create organization tag",category:"Tags"},{name:"TAGS_DELETE",description:"Delete organization tag",category:"Tags",dangerous:!0},{name:"MEMBER_TAGS_GET",description:"Get member tags",category:"Tags"},{name:"MEMBER_TAGS_SET",description:"Set member tags",category:"Tags"},{name:"AUTOMATION_CREATE",description:"Create automation",category:"Automations"},{name:"AUTOMATION_GET",description:"View automation details",category:"Automations"},{name:"AUTOMATION_LIST",description:"List automations",category:"Automations"},{name:"AUTOMATION_UPDATE",description:"Update automation",category:"Automations"},{name:"AUTOMATION_DELETE",description:"Delete automation",category:"Automations",dangerous:!0},{name:"AUTOMATION_TRIGGER_ADD",description:"Add trigger to automation",category:"Automations"},{name:"AUTOMATION_TRIGGER_REMOVE",description:"Remove trigger from automation",category:"Automations"},{name:"AUTOMATION_RUN",description:"Manually trigger an automation run",category:"Automations"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_GET",description:"View virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PLUGIN_CONFIG_UPDATE",description:"Update virtual MCP plugin configuration",category:"Virtual MCPs"},{name:"VIRTUAL_MCP_PINNED_VIEWS_UPDATE",description:"Update virtual MCP pinned sidebar views",category:"Virtual MCPs"},{name:"AI_PROVIDERS_LIST",description:"List available AI providers",category:"AI Providers"},{name:"AI_PROVIDERS_LIST_MODELS",description:"List AI provider models",category:"AI Providers"},{name:"AI_PROVIDERS_ACTIVE",description:"List active AI providers",category:"AI Providers"},{name:"AI_PROVIDER_KEY_CREATE",description:"Store AI provider API key",category:"AI Providers"},{name:"AI_PROVIDER_KEY_LIST",description:"List AI provider API keys",category:"AI Providers"},{name:"AI_PROVIDER_KEY_DELETE",description:"Delete AI provider API key",category:"AI Providers",dangerous:!0},{name:"AI_PROVIDER_OAUTH_URL",description:"Get OAuth URL for provider",category:"AI Providers"},{name:"AI_PROVIDER_OAUTH_EXCHANGE",description:"Exchange OAuth code for API key",category:"AI Providers"},{name:"AI_PROVIDER_PROVISION_KEY",description:"Auto-provision API key for a provider",category:"AI Providers"},{name:"AI_PROVIDER_TOPUP_URL",description:"Get checkout URL to top up provider credits",category:"AI Providers"},{name:"AI_PROVIDER_CREDITS",description:"Get current credit balance for a provider",category:"AI Providers"},{name:"AI_PROVIDER_CLI_ACTIVATE",description:"Activate Claude Code via local CLI",category:"AI Providers"},{name:"LIST_OBJECTS",description:"List objects in storage",category:"Object Storage"},{name:"GET_OBJECT_METADATA",description:"Get object metadata",category:"Object Storage"},{name:"GET_PRESIGNED_URL",description:"Generate download URL",category:"Object Storage"},{name:"PUT_PRESIGNED_URL",description:"Generate upload URL",category:"Object Storage"},{name:"DELETE_OBJECT",description:"Delete object",category:"Object Storage",dangerous:!0},{name:"DELETE_OBJECTS",description:"Delete multiple objects",category:"Object Storage",dangerous:!0},{name:"COLLECTION_REGISTRY_APP_LIST",description:"List registry apps",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_GET",description:"Get registry app details",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_VERSIONS",description:"List registry app versions",category:"Registry"},{name:"COLLECTION_REGISTRY_APP_FILTERS",description:"Get registry app filters",category:"Registry"},{name:"REGISTRY_ITEM_LIST",description:"List private registry items",category:"Registry"},{name:"REGISTRY_ITEM_SEARCH",description:"Search registry items",category:"Registry"},{name:"REGISTRY_ITEM_GET",description:"Get registry item details",category:"Registry"},{name:"REGISTRY_ITEM_VERSIONS",description:"List registry item versions",category:"Registry"},{name:"REGISTRY_ITEM_CREATE",description:"Create registry item",category:"Registry"},{name:"REGISTRY_ITEM_BULK_CREATE",description:"Bulk create registry items",category:"Registry"},{name:"REGISTRY_ITEM_UPDATE",description:"Update registry item",category:"Registry"},{name:"REGISTRY_ITEM_DELETE",description:"Delete registry item",category:"Registry",dangerous:!0},{name:"REGISTRY_ITEM_FILTERS",description:"Get registry item filters",category:"Registry"},{name:"REGISTRY_DISCOVER_TOOLS",description:"Discover tools from MCP server",category:"Registry"},{name:"REGISTRY_AI_GENERATE",description:"AI-generate registry content",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_LIST",description:"List publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_REVIEW",description:"Review publish request",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_COUNT",description:"Count pending publish requests",category:"Registry"},{name:"REGISTRY_PUBLISH_REQUEST_DELETE",description:"Delete publish request",category:"Registry",dangerous:!0},{name:"REGISTRY_PUBLISH_API_KEY_GENERATE",description:"Generate publish API key",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_LIST",description:"List publish API keys",category:"Registry"},{name:"REGISTRY_PUBLISH_API_KEY_REVOKE",description:"Revoke publish API key",category:"Registry",dangerous:!0},{name:"REGISTRY_MONITOR_RUN_START",description:"Start monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_LIST",description:"List monitor runs",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_GET",description:"Get monitor run details",category:"Registry"},{name:"REGISTRY_MONITOR_RUN_CANCEL",description:"Cancel monitor run",category:"Registry"},{name:"REGISTRY_MONITOR_RESULT_LIST",description:"List monitor results",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_LIST",description:"List monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_SYNC",description:"Sync monitor connections",category:"Registry"},{name:"REGISTRY_MONITOR_CONNECTION_UPDATE_AUTH",description:"Update monitor connection auth",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_SET",description:"Set monitor schedule",category:"Registry"},{name:"REGISTRY_MONITOR_SCHEDULE_CANCEL",description:"Cancel monitor schedule",category:"Registry"},{name:"VM_START",description:"Start a Freestyle VM with dev server preview",category:"VM"},{name:"VM_DELETE",description:"Stop and delete a Freestyle VM",category:"VM"},{name:"GITHUB_LIST_USER_ORGS",description:"List GitHub user's personal account and organizations",category:"GitHub"}]});var be6=D(()=>{Gp();ez1()});function ye6(){return dp5.parse(process.env)}var zN0=(X)=>F.enum(["true","false","1","0"]).optional().transform((Y)=>Y===void 0?X:Y==="true"||Y==="1"),mp5=(X)=>F.string().optional().transform((Y)=>Y?Y.split(",").map((G)=>G.trim()):X),dp5;var xe6=D(()=>{H0();dp5=F.object({AUTH_EMAIL_PASSWORD_ENABLED:zN0(!0),AUTH_GOOGLE_CLIENT_ID:F.string().optional(),AUTH_GOOGLE_CLIENT_SECRET:F.string().optional(),AUTH_GITHUB_CLIENT_ID:F.string().optional(),AUTH_GITHUB_CLIENT_SECRET:F.string().optional(),AUTH_RESEND_API_KEY:F.string().optional(),AUTH_RESEND_FROM_EMAIL:F.string().optional(),AUTH_SENDGRID_API_KEY:F.string().optional(),AUTH_SENDGRID_FROM_EMAIL:F.string().optional(),AUTH_INVITE_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_RESET_PASSWORD_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_MAGIC_LINK_ENABLED:zN0(!1),AUTH_MAGIC_LINK_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_ENABLED:zN0(!1),AUTH_EMAIL_OTP_EMAIL_PROVIDER:F.enum(["resend","sendgrid"]).optional(),AUTH_EMAIL_OTP_LENGTH:F.coerce.number().optional(),AUTH_EMAIL_OTP_EXPIRES_IN:F.coerce.number().optional(),AUTH_SSO_DOMAIN:F.string().optional(),AUTH_SSO_MS_TENANT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_ID:F.string().optional(),AUTH_SSO_MS_CLIENT_SECRET:F.string().optional(),AUTH_SSO_SCOPES:mp5(["openid","email","profile"])}).transform((X)=>{let Y={};if(X.AUTH_GOOGLE_CLIENT_ID)Y.google={clientId:X.AUTH_GOOGLE_CLIENT_ID,clientSecret:X.AUTH_GOOGLE_CLIENT_SECRET??""};if(X.AUTH_GITHUB_CLIENT_ID)Y.github={clientId:X.AUTH_GITHUB_CLIENT_ID,clientSecret:X.AUTH_GITHUB_CLIENT_SECRET??""};let G=[];if(X.AUTH_RESEND_API_KEY)G.push({id:"resend",provider:"resend",config:{apiKey:X.AUTH_RESEND_API_KEY,fromEmail:X.AUTH_RESEND_FROM_EMAIL??"noreply@example.com"}});if(X.AUTH_SENDGRID_API_KEY)G.push({id:"sendgrid",provider:"sendgrid",config:{apiKey:X.AUTH_SENDGRID_API_KEY,fromEmail:X.AUTH_SENDGRID_FROM_EMAIL??"noreply@example.com"}});let Q=G[0]?.id,J;if(X.AUTH_SSO_MS_CLIENT_ID&&X.AUTH_SSO_DOMAIN)J={providerId:"microsoft",domain:X.AUTH_SSO_DOMAIN,MS_TENANT_ID:X.AUTH_SSO_MS_TENANT_ID??"",MS_CLIENT_ID:X.AUTH_SSO_MS_CLIENT_ID,MS_CLIENT_SECRET:X.AUTH_SSO_MS_CLIENT_SECRET??"",scopes:X.AUTH_SSO_SCOPES};let W;if(X.AUTH_MAGIC_LINK_ENABLED)W={enabled:!0,emailProviderId:X.AUTH_MAGIC_LINK_EMAIL_PROVIDER??Q??""};let Z;if(X.AUTH_EMAIL_OTP_ENABLED)Z={enabled:!0,emailProviderId:X.AUTH_EMAIL_OTP_EMAIL_PROVIDER??Q??"",...X.AUTH_EMAIL_OTP_LENGTH!==void 0&&{otpLength:X.AUTH_EMAIL_OTP_LENGTH},...X.AUTH_EMAIL_OTP_EXPIRES_IN!==void 0&&{expiresIn:X.AUTH_EMAIL_OTP_EXPIRES_IN}};return{emailAndPassword:{enabled:X.AUTH_EMAIL_PASSWORD_ENABLED},socialProviders:Object.keys(Y).length>0?Y:void 0,emailProviders:G.length>0?G:void 0,inviteEmailProviderId:X.AUTH_INVITE_EMAIL_PROVIDER,resetPasswordEmailProviderId:X.AUTH_RESET_PASSWORD_EMAIL_PROVIDER,ssoConfig:J,magicLinkConfig:W,emailOtpConfig:Z}})});var cA1;var he6=D(()=>{cA1={enabled:!0,batchSize:250,flushIntervalMs:300,maxQueueSize:1e4,redactor:"regex"}});import{existsSync as cp5,readFileSync as ip5}from"fs";function pp5(){let X=ye6(),Y=v6().configPath;if(!cp5(Y))return{auth:X,monitoring:cA1};try{let G=JSON.parse(ip5(Y,"utf-8"));if(G.auth)console.warn("[config] DEPRECATION: 'auth' key found in config.json. Auth is now configured via AUTH_* environment variables. The 'auth' key will be ignored.");return{auth:X,monitoring:G.monitoring??cA1,theme:G.theme,logo:G.logo,autoCreateOrganizationOnSignup:G.autoCreateOrganizationOnSignup}}catch{return{auth:X,monitoring:cA1}}}function Sj(){if(!ON0)ON0=pp5();return ON0}function ge6(){return Sj().theme}var ON0=null;var DN0=D(()=>{xe6();he6();m9()});import{dirname as np5,posix as ap5,sep as tp5}from"path";function le6(){let X=rp5();return async(Y)=>{for(let G of Y)G.module=X(G.filename);return Y}}function rp5(X=process.argv[1]?np5(process.argv[1]):process.cwd(),Y=tp5==="\\"){let G=Y?ue6(X):X;return(Q)=>{if(!Q)return;let J=Y?ue6(Q):Q,{dir:W,base:Z,ext:$}=ap5.parse(J);if($===".js"||$===".mjs"||$===".cjs")Z=Z.slice(0,-1*$.length);let K=decodeURIComponent(Z);if(!W)W=".";let H=W.lastIndexOf("/node_modules");if(H>-1)return`${W.slice(H+14).replace(/\//g,".")}:${K}`;if(W.startsWith(G)){let U=W.slice(G.length+1).replace(/\//g,".");return U?`${U}:${K}`:K}return K}}function ue6(X){return X.replace(/^[A-Z]:/,"").replace(/\\/g,"/")}var me6=()=>{};function op5(X,Y,G){return{key:X,enabled:typeof Y=="string"?!0:Y,variant:typeof Y=="string"?Y:void 0,reason:void 0,metadata:{id:void 0,version:void 0,payload:G?JSON.stringify(G):void 0,description:void 0}}}var wN0=(X)=>{if("flags"in X){let Y=de6(X.flags),G=ce6(X.flags);return{...X,featureFlags:Y,featureFlagPayloads:G}}{let Y=X.featureFlags??{},G=Object.fromEntries(Object.entries(X.featureFlagPayloads||{}).map(([J,W])=>[J,LN0(W)])),Q=Object.fromEntries(Object.entries(Y).map(([J,W])=>[J,op5(J,W,G[J])]));return{...X,featureFlags:Y,featureFlagPayloads:G,flags:Q}}},de6=(X)=>Object.fromEntries(Object.entries(X??{}).map(([Y,G])=>[Y,bX1(G)]).filter(([,Y])=>Y!==void 0)),ce6=(X)=>{let Y=X??{};return Object.fromEntries(Object.keys(Y).filter((G)=>{let Q=Y[G];return Q.enabled&&Q.metadata&&Q.metadata.payload!==void 0}).map((G)=>{let Q=Y[G].metadata?.payload;return[G,Q?LN0(Q):void 0]}))},bX1=(X)=>X===void 0?void 0:X.variant??X.enabled,LN0=(X)=>{if(typeof X!="string")return X;try{return JSON.parse(X)}catch{return X}};var iA1=()=>{};function ie6(){return"CompressionStream"in globalThis&&"TextEncoder"in globalThis&&"Response"in globalThis&&typeof Response.prototype.blob=="function"}async function pA1(X,Y=!0,G){try{let Q=new CompressionStream("gzip"),J=Q.writable.getWriter(),W=J.write(new TextEncoder().encode(X)).then(()=>J.close()).catch(async(K)=>{try{await J.abort(K)}catch{}throw K}),Z=new Response(Q.readable).blob(),[$]=await Promise.all([Z,W]);return $}catch(Q){if(G?.rethrow)throw Q;if(Y)console.error("Failed to gzip compress data",Q);return null}}var EN0=()=>{};var sp5,pe6=function(X,Y=[]){if(!X)return!1;let G=X.toLowerCase();return sp5.concat(Y).some((Q)=>{let J=Q.toLowerCase();return G.indexOf(J)!==-1})};var ne6=D(()=>{sp5=["amazonbot","amazonproductbot","app.hypefactors.com","applebot","archive.org_bot","awariobot","backlinksextendedbot","baiduspider","bingbot","bingpreview","chrome-lighthouse","dataforseobot","deepscan","duckduckbot","facebookexternal","facebookcatalog","http://yandex.com/bots","hubspot","ia_archiver","leikibot","linkedinbot","meta-externalagent","mj12bot","msnbot","nessus","petalbot","pinterest","prerender","rogerbot","screaming frog","sebot-wa","sitebulb","slackbot","slurp","trendictionbot","turnitin","twitterbot","vercel-screenshot","vercelbot","yahoo! slurp","yandexbot","zoombot","bot.htm","bot.php","(bot;","bot/","crawler","ahrefsbot","ahrefssiteaudit","semrushbot","siteauditbot","splitsignalbot","gptbot","oai-searchbot","chatgpt-user","perplexitybot","better uptime bot","sentryuptimebot","uptimerobot","headlesschrome","cypress","google-hoteladsverifier","adsbot-google","apis-google","duplexweb-google","feedfetcher-google","google favicon","google web preview","google-read-aloud","googlebot","googleother","google-cloudvertexbot","googleweblight","mediapartners-google","storebot-google","google-inspectiontool","bytespider"]});var aJ;var Cj=D(()=>{aJ=function(X){return X.AnonymousId="anonymous_id",X.DistinctId="distinct_id",X.Props="props",X.EnablePersonProcessing="enable_person_processing",X.PersonMode="person_mode",X.FeatureFlagDetails="feature_flag_details",X.FeatureFlags="feature_flags",X.FeatureFlagPayloads="feature_flag_payloads",X.BootstrapFeatureFlagDetails="bootstrap_feature_flag_details",X.BootstrapFeatureFlags="bootstrap_feature_flags",X.BootstrapFeatureFlagPayloads="bootstrap_feature_flag_payloads",X.OverrideFeatureFlags="override_feature_flags",X.Queue="queue",X.LogsQueue="logs_queue",X.OptedOut="opted_out",X.SessionId="session_id",X.SessionStartTimestamp="session_start_timestamp",X.SessionLastTimestamp="session_timestamp",X.PersonProperties="person_properties",X.GroupProperties="group_properties",X.InstalledAppBuild="installed_app_build",X.InstalledAppVersion="installed_app_version",X.SessionReplay="session_replay",X.SurveyLastSeenDate="survey_last_seen_date",X.SurveysSeen="surveys_seen",X.Surveys="surveys",X.RemoteConfig="remote_config",X.FlagsEndpointWasHit="flags_endpoint_was_hit",X.DeviceId="device_id",X}({})});var nA1=()=>{};function tA1(X){return X===null||typeof X!="object"}function kj(X,Y){return Object.prototype.toString.call(X)===`[object ${Y}]`}function re6(X){return kj(X,"ErrorEvent")}function ea(X){return typeof Event<"u"&&Yn5(X,Event)}function oe6(X){return kj(X,"Object")}function Yn5(X,Y){try{return X instanceof Y}catch{return!1}}var Xn5,ae6,PmX,PN0,aA1,yX1=(X)=>X===Object(X)&&!aA1(X),sa=(X)=>X===void 0,Aq=(X)=>PN0.call(X)=="[object String]",te6=(X)=>Aq(X)&&X.trim().length===0,xX1=(X)=>PN0.call(X)=="[object Number]"&&X===X,qN0=(X)=>X instanceof Error;var hX1=D(()=>{Cj();nA1();Xn5=Array.isArray,ae6=Object.prototype,PmX=ae6.hasOwnProperty,PN0=ae6.toString,aA1=Xn5||function(X){return PN0.call(X)==="[object Array]"}});function gX1(X,Y,G,Q,J){if(Y>G)Q.warn("min cannot be greater than max."),Y=G;if(xX1(X))if(X>G)return Q.warn(" cannot be greater than max: "+G+". Using max value instead."),G;else{if(!(X<Y))return X;return Q.warn(" cannot be less than min: "+Y+". Using min value instead."),Y}return Q.warn(" must be a number. using max or fallback. max: "+G+", fallback: "+J),gX1(J||G,Y,G,Q)}var AN0=D(()=>{hX1()});class TN0{constructor(X){this._buckets={},this._onBucketRateLimited=X._onBucketRateLimited,this._bucketSize=gX1(X.bucketSize,0,100,X._logger),this._refillRate=gX1(X.refillRate,0,this._bucketSize,X._logger),this._refillInterval=gX1(X.refillInterval,0,Gn5,X._logger)}_applyRefill(X,Y){let G=Y-X.lastAccess,Q=Math.floor(G/this._refillInterval);if(Q>0){let J=Q*this._refillRate;X.tokens=Math.min(X.tokens+J,this._bucketSize),X.lastAccess=X.lastAccess+Q*this._refillInterval}}consumeRateLimit(X){let Y=Date.now(),G=String(X),Q=this._buckets[G];if(Q)this._applyRefill(Q,Y);else Q={tokens:this._bucketSize,lastAccess:Y},this._buckets[G]=Q;if(Q.tokens===0)return!0;if(Q.tokens--,Q.tokens===0)this._onBucketRateLimited?.(X);return Q.tokens===0}stop(){this._buckets={}}}var Gn5=86400000;var se6=D(()=>{AN0()});class vj{constructor(X){this.bytes=X}static ofInner(X){if(X.length===16)return new vj(X);throw TypeError("not 128-bit length")}static fromFieldsV7(X,Y,G,Q){if(!Number.isInteger(X)||!Number.isInteger(Y)||!Number.isInteger(G)||!Number.isInteger(Q)||X<0||Y<0||G<0||Q<0||X>281474976710655||Y>4095||G>1073741823||Q>4294967295)throw RangeError("invalid field value");let J=new Uint8Array(16);return J[0]=X/1099511627776,J[1]=X/4294967296,J[2]=X/16777216,J[3]=X/65536,J[4]=X/256,J[5]=X,J[6]=112|Y>>>8,J[7]=Y,J[8]=128|G>>>24,J[9]=G>>>16,J[10]=G>>>8,J[11]=G,J[12]=Q>>>24,J[13]=Q>>>16,J[14]=Q>>>8,J[15]=Q,new vj(J)}static parse(X){let Y;switch(X.length){case 32:Y=/^[0-9a-f]{32}$/i.exec(X)?.[0];break;case 36:Y=/^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;case 38:Y=/^\{([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})\}$/i.exec(X)?.slice(1,6).join("");break;case 45:Y=/^urn:uuid:([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{12})$/i.exec(X)?.slice(1,6).join("");break;default:break}if(Y){let G=new Uint8Array(16);for(let Q=0;Q<16;Q+=4){let J=parseInt(Y.substring(2*Q,2*Q+8),16);G[Q+0]=J>>>24,G[Q+1]=J>>>16,G[Q+2]=J>>>8,G[Q+3]=J}return new vj(G)}throw SyntaxError("could not parse UUID string")}toString(){let X="";for(let Y=0;Y<this.bytes.length;Y++)if(X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]),Y===3||Y===5||Y===7||Y===9)X+="-";return X}toHex(){let X="";for(let Y=0;Y<this.bytes.length;Y++)X+="0123456789abcdef".charAt(this.bytes[Y]>>>4),X+="0123456789abcdef".charAt(15&this.bytes[Y]);return X}toJSON(){return this.toString()}getVariant(){let X=this.bytes[8]>>>4;if(X<0)throw Error("unreachable");if(X<=7)return this.bytes.every((Y)=>Y===0)?"NIL":"VAR_0";if(X<=11)return"VAR_10";if(X<=13)return"VAR_110";if(X<=15)return this.bytes.every((Y)=>Y===255)?"MAX":"VAR_RESERVED";else throw Error("unreachable")}getVersion(){return this.getVariant()==="VAR_10"?this.bytes[6]>>>4:void 0}clone(){return new vj(this.bytes.slice(0))}equals(X){return this.compareTo(X)===0}compareTo(X){for(let Y=0;Y<16;Y++){let G=this.bytes[Y]-X.bytes[Y];if(G!==0)return Math.sign(G)}return 0}}class X14{constructor(X){this.timestamp=0,this.counter=0,this.random=X??Qn5()}generate(){return this.generateOrResetCore(Date.now(),1e4)}generateOrAbort(){return this.generateOrAbortCore(Date.now(),1e4)}generateOrResetCore(X,Y){let G=this.generateOrAbortCore(X,Y);if(G===void 0)this.timestamp=0,G=this.generateOrAbortCore(X,Y);return G}generateOrAbortCore(X,Y){if(!Number.isInteger(X)||X<1||X>281474976710655)throw RangeError("`unixTsMs` must be a 48-bit positive integer");if(Y<0||Y>281474976710655)throw RangeError("`rollbackAllowance` out of reasonable range");if(X>this.timestamp)this.timestamp=X,this.resetCounter();else{if(!(X+Y>=this.timestamp))return;if(this.counter++,this.counter>4398046511103)this.timestamp++,this.resetCounter()}return vj.fromFieldsV7(this.timestamp,Math.trunc(this.counter/1073741824),this.counter&1073741823,this.random.nextUint32())}resetCounter(){this.counter=1024*this.random.nextUint32()+(1023&this.random.nextUint32())}generateV4(){let X=new Uint8Array(Uint32Array.of(this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32(),this.random.nextUint32()).buffer);return X[6]=64|X[6]>>>4,X[8]=128|X[8]>>>2,vj.ofInner(X)}}var Qn5=()=>({nextUint32:()=>65536*Math.trunc(65536*Math.random())+Math.trunc(65536*Math.random())}),ee6,Tq=()=>Jn5().toString(),Jn5=()=>(ee6||(ee6=new X14)).generate();var uX1=D(()=>{/*! For license information please see uuidv7.mjs.LICENSE.txt */});class IN0{add(X){let Y=Tq();return this.promiseByIds[Y]=X,X.catch(()=>{}).finally(()=>{delete this.promiseByIds[Y]}),X}async join(){let X=Object.values(this.promiseByIds),Y=X.length;while(Y>0)await Promise.all(X),X=Object.values(this.promiseByIds),Y=X.length}get length(){return Object.keys(this.promiseByIds).length}constructor(){this.promiseByIds={}}}var Y14=D(()=>{uX1()});function Zn5(X=console){return{log:X.log.bind(X),warn:X.warn.bind(X),error:X.error.bind(X),debug:X.debug.bind(X)}}function Q14(X,Y=Wn5){return G14(X,Y,Zn5())}var G14=(X,Y,G)=>{function Q(W,...Z){Y(()=>{let $=G[W];$(X,...Z)})}return{info:(...W)=>{Q("log",...W)},warn:(...W)=>{Q("warn",...W)},error:(...W)=>{Q("error",...W)},critical:(...W)=>{G.error(X,...W)},createLogger:(W)=>G14(`${X} ${W}`,Y,G)}},Wn5=(X)=>X();var J14=()=>{};var Yt="Mobile",oA1="iOS",Xt="Android",Z14="Tablet",vmX,Kn5="Apple",_mX,W14="Safari",sA1="BlackBerry",$14="Samsung",Hn5,Fn5,eA1="Chrome",Un5,Bn5,K14="Internet Explorer",Nn5,jN0="Opera",fmX,H14="Edge",zn5,MN0="Firefox",On5,RN0="Nintendo",SN0="PlayStation",rA1="Xbox",Dn5,wn5,lX1="Windows",Ln5,F14="Generic",bmX,ymX,En5="Konqueror",F3="(\\d+(\\.\\d+)?)",VN0,xmX,hmX,gmX,Pn5,qn5,umX,lmX;var U14=D(()=>{nA1();hX1();vmX=Xt+" "+Z14,_mX=Kn5+" Watch",Hn5=$14+"Browser",Fn5=$14+" Internet",Un5=eA1+" OS",Bn5=eA1+" "+oA1,Nn5=K14+" "+Yt,fmX=jN0+" Mini",zn5="Microsoft "+H14,On5=MN0+" "+oA1,Dn5=Xt+" "+Yt,wn5=Yt+" "+W14,Ln5=lX1+" Phone",bmX=F14+" "+Yt.toLowerCase(),ymX=F14+" "+Z14.toLowerCase(),VN0=new RegExp("Version/"+F3),xmX=new RegExp(rA1,"i"),hmX=new RegExp(SN0+" \\w+","i"),gmX=new RegExp(RN0+" \\w+","i"),Pn5=new RegExp(sA1+"|PlayBook|BB10","i"),qn5={"NT3.51":"NT 3.11","NT4.0":"NT 4.0","5.0":"2000","5.1":"XP","5.2":"XP","6.0":"Vista","6.1":"7","6.2":"8","6.3":"8.1","6.4":"10","10.0":"10"},umX={[Nn5]:[new RegExp("rv:"+F3)],[zn5]:[new RegExp(H14+"?\\/"+F3)],[eA1]:[new RegExp("("+eA1+"|CrMo)\\/"+F3)],[Bn5]:[new RegExp("CriOS\\/"+F3)],"UC Browser":[new RegExp("(UCBrowser|UCWEB)\\/"+F3)],[W14]:[VN0],[wn5]:[VN0],[jN0]:[new RegExp("("+jN0+"|OPR)\\/"+F3)],[MN0]:[new RegExp(MN0+"\\/"+F3)],[On5]:[new RegExp("FxiOS\\/"+F3)],[En5]:[new RegExp("Konqueror[:/]?"+F3,"i")],[sA1]:[new RegExp(sA1+" "+F3),VN0],[Dn5]:[new RegExp("android\\s"+F3,"i")],[Fn5]:[new RegExp(Hn5+"\\/"+F3)],[K14]:[new RegExp("(rv:|MSIE )"+F3)],Mozilla:[new RegExp("rv:"+F3)]},lmX=[[new RegExp(rA1+"; "+rA1+" (.*?)[);]","i"),(X)=>[rA1,X&&X[1]||""]],[new RegExp(RN0,"i"),[RN0,""]],[new RegExp(SN0,"i"),[SN0,""]],[Pn5,[sA1,""]],[new RegExp(lX1,"i"),(X,Y)=>{if(/Phone/.test(Y)||/WPDesktop/.test(Y))return[Ln5,""];if(new RegExp(Yt).test(Y)&&!/IEMobile\b/.test(Y))return[lX1+" "+Yt,""];let G=/Windows NT ([0-9.]+)/i.exec(Y);if(G&&G[1]){let Q=G[1],J=qn5[Q]||"";if(/arm/i.test(Y))J="RT";return[lX1,J]}return[lX1,""]}],[/((iPhone|iPad|iPod).*?OS (\d+)_(\d+)_?(\d+)?|iPhone)/,(X)=>{if(X&&X[3]){let Y=[X[3],X[4],X[5]||"0"];return[oA1,Y.join(".")]}return[oA1,""]}],[/(watch.*\/(\d+\.\d+\.\d+)|watch os,(\d+\.\d+),)/i,(X)=>{let Y="";if(X&&X.length>=3)Y=sa(X[2])?X[3]:X[2];return["watchOS",Y]}],[new RegExp("("+Xt+" (\\d+)\\.(\\d+)\\.?(\\d+)?|"+Xt+")","i"),(X)=>{if(X&&X[2]){let Y=[X[2],X[3],X[4]||"0"];return[Xt,Y.join(".")]}return[Xt,""]}],[/Mac OS X (\d+)[_.](\d+)[_.]?(\d+)?/i,(X)=>{let Y=["Mac OS X",""];if(X&&X[1]){let G=[X[1],X[2],X[3]||"0"];Y[1]=G.join(".")}return Y}],[/Mac/i,["Mac OS X",""]],[/CrOS/,[Un5,""]],[/Linux|debian/i,["Linux",""]]]});function N14(X){return X?.replace(/\/+$/,"")}async function z14(X,Y){let G=null;for(let Q=0;Q<Y.retryCount+1;Q++){if(Q>0)await new Promise((J)=>setTimeout(J,Y.retryDelay));try{return await X()}catch(J){if(G=J,!Y.retryCheck(J))throw J}}throw G}function XT1(){return new Date().toISOString()}function Hw(X,Y){let G=setTimeout(X,Y);return G?.unref&&G?.unref(),G}function CN0(X){return Promise.all(X.map((Y)=>(Y??Promise.resolve()).then((G)=>({status:"fulfilled",value:G}),(G)=>({status:"rejected",reason:G}))))}var B14="utf8",O14=(X)=>X instanceof Error;var U3=D(()=>{ne6();se6();AN0();nA1();hX1();Y14();J14();U14()});var An5,YdX;var kN0=D(()=>{U3();An5={trace:{text:"TRACE",number:1},debug:{text:"DEBUG",number:5},info:{text:"INFO",number:9},warn:{text:"WARN",number:13},error:{text:"ERROR",number:17},fatal:{text:"FATAL",number:21}},YdX=An5.info});var D14=D(()=>{kN0();Cj()});var w14=D(()=>{Cj()});class vN0{constructor(){this.events={},this.events={}}on(X,Y){if(!this.events[X])this.events[X]=[];return this.events[X].push(Y),()=>{this.events[X]=this.events[X].filter((G)=>G!==Y)}}emit(X,Y){for(let G of this.events[X]||[])G(Y);for(let G of this.events["*"]||[])G(X,Y)}}var L14=()=>{};async function E14(X){if(X instanceof Gt){let Y="";try{Y=await X.text}catch{}console.error(`Error while flushing PostHog: message=${X.message}, response body=${Y}`,X)}else console.error("Error while flushing PostHog",X);return Promise.resolve()}function _N0(X){return typeof X=="object"&&(X instanceof Gt||X instanceof mX1)}function P14(X){return typeof X=="object"&&X instanceof Gt&&X.status===413}class YT1{constructor(X,Y={}){this.flushPromise=null,this.shutdownPromise=null,this.promiseQueue=new IN0,this._events=new vN0,this._isInitialized=!1;let G=typeof X=="string"?X.trim():"",Q=typeof Y.host=="string"?Y.host.trim():"",J=!G;if(this._logger=Q14("[PostHog]",this.logMsgIfDebug.bind(this)),J)this._logger.error("You must pass your PostHog project's api key. The client will be disabled.");if(this.apiKey=G,this.host=N14(Q||"https://us.i.posthog.com"),this.flushAt=Y.flushAt?Math.max(Y.flushAt,1):20,this.maxBatchSize=Math.max(this.flushAt,Y.maxBatchSize??100),this.maxQueueSize=Math.max(this.flushAt,Y.maxQueueSize??1000),this.flushInterval=Y.flushInterval??1e4,this.preloadFeatureFlags=Y.preloadFeatureFlags??!0,this.defaultOptIn=Y.defaultOptIn??!0,this.disableSurveys=Y.disableSurveys??!1,this._retryOptions={retryCount:Y.fetchRetryCount??3,retryDelay:Y.fetchRetryDelay??3000,retryCheck:_N0},this.requestTimeout=Y.requestTimeout??1e4,this.featureFlagsRequestTimeoutMs=Y.featureFlagsRequestTimeoutMs??3000,this.remoteConfigRequestTimeoutMs=Y.remoteConfigRequestTimeoutMs??3000,this.disableGeoip=Y.disableGeoip??!0,this.disabled=(Y.disabled??!1)||J,this.historicalMigration=Y?.historicalMigration??!1,this._initPromise=Promise.resolve(),this._isInitialized=!0,this.evaluationContexts=Y?.evaluationContexts??Y?.evaluationEnvironments,Y?.evaluationEnvironments&&!Y?.evaluationContexts)this._logger.warn("evaluationEnvironments is deprecated. Use evaluationContexts instead. This property will be removed in a future version.");this.disableCompression=!ie6()||(Y?.disableCompression??!1)}logMsgIfDebug(X){if(this.isDebug)X()}wrap(X){if(this.disabled)return void this._logger.warn("The client is disabled");if(this._isInitialized)return X();this._initPromise.then(()=>X())}getCommonEventProperties(){return{$lib:this.getLibraryId(),$lib_version:this.getLibraryVersion()}}get optedOut(){return this.getPersistedProperty(aJ.OptedOut)??!this.defaultOptIn}async optIn(){this.wrap(()=>{this.setPersistedProperty(aJ.OptedOut,!1)})}async optOut(){this.wrap(()=>{this.setPersistedProperty(aJ.OptedOut,!0)})}on(X,Y){return this._events.on(X,Y)}debug(X=!0){if(this.removeDebugCallback?.(),X){let Y=this.on("*",(G,Q)=>this._logger.info(G,Q));this.removeDebugCallback=()=>{Y(),this.removeDebugCallback=void 0}}}get isDebug(){return!!this.removeDebugCallback}get isDisabled(){return this.disabled}buildPayload(X){return{distinct_id:X.distinct_id,event:X.event,properties:{...X.properties||{},...this.getCommonEventProperties()}}}addPendingPromise(X){return this.promiseQueue.add(X)}identifyStateless(X,Y,G){this.wrap(()=>{let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};this.enqueue("identify",Q,G)})}async identifyStatelessImmediate(X,Y,G){let Q={...this.buildPayload({distinct_id:X,event:"$identify",properties:Y})};await this.sendImmediate("identify",Q,G)}captureStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({distinct_id:X,event:Y,properties:G});this.enqueue("capture",J,Q)})}async captureStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({distinct_id:X,event:Y,properties:G});await this.sendImmediate("capture",J,Q)}aliasStateless(X,Y,G,Q){this.wrap(()=>{let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});this.enqueue("alias",J,Q)})}async aliasStatelessImmediate(X,Y,G,Q){let J=this.buildPayload({event:"$create_alias",distinct_id:Y,properties:{...G||{},distinct_id:Y,alias:X}});await this.sendImmediate("alias",J,Q)}groupIdentifyStateless(X,Y,G,Q,J,W){this.wrap(()=>{let Z=this.buildPayload({distinct_id:J||`$${X}_${Y}`,event:"$groupidentify",properties:{$group_type:X,$group_key:Y,$group_set:G||{},...W||{}}});this.enqueue("capture",Z,Q)})}async getRemoteConfig(){await this._initPromise;let X=this.host;if(X==="https://us.i.posthog.com")X="https://us-assets.i.posthog.com";else if(X==="https://eu.i.posthog.com")X="https://eu-assets.i.posthog.com";let Y=`${X}/array/${this.apiKey}/config`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}};return this.fetchWithRetry(Y,G,{retryCount:0},this.remoteConfigRequestTimeoutMs).then((Q)=>Q.json()).catch((Q)=>{this._logger.error("Remote config could not be loaded",Q),this._events.emit("error",Q)})}async getFlags(X,Y={},G={},Q={},J={},W=!1){await this._initPromise;let Z=W?"&config=true":"",$=`${this.host}/flags/?v=2${Z}`,K={token:this.apiKey,distinct_id:X,groups:Y,person_properties:G,group_properties:Q,...J};if(G.$device_id)K.$device_id=G.$device_id;if(this.evaluationContexts&&this.evaluationContexts.length>0)K.evaluation_contexts=this.evaluationContexts;let H={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"},body:JSON.stringify(K)};return this._logger.info("Flags URL",$),this.fetchWithRetry($,H,{retryCount:0},this.featureFlagsRequestTimeoutMs).then((U)=>U.json()).then((U)=>({success:!0,response:wN0(U)})).catch((U)=>{return this._events.emit("error",U),{success:!1,error:this.categorizeRequestError(U)}})}categorizeRequestError(X){if(X instanceof Gt)return{type:"api_error",statusCode:X.status};if(X instanceof mX1){let Y=X.error;if(Y instanceof Error&&(Y.name==="AbortError"||Y.name==="TimeoutError"))return{type:"timeout"};return{type:"connection_error"}}return{type:"unknown_error"}}async getFeatureFlagStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailStateless(X,Y,G,Q,J,W);if(Z===void 0)return{response:void 0,requestId:void 0};let $=bX1(Z.response);if($===void 0)$=!1;return{response:$,requestId:Z.requestId}}async getFeatureFlagDetailStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(Y,G,Q,J,W,[X]);if(Z===void 0)return;return{response:Z.flags[X],requestId:Z.requestId,evaluatedAt:Z.evaluatedAt}}async getFeatureFlagPayloadStateless(X,Y,G={},Q={},J={},W){await this._initPromise;let Z=await this.getFeatureFlagPayloadsStateless(Y,G,Q,J,W,[X]);if(!Z)return;let $=Z[X];if($===void 0)return null;return $}async getFeatureFlagPayloadsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,(await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)).payloads}async getFeatureFlagsStateless(X,Y={},G={},Q={},J,W){return await this._initPromise,await this.getFeatureFlagsAndPayloadsStateless(X,Y,G,Q,J,W)}async getFeatureFlagsAndPayloadsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z=await this.getFeatureFlagDetailsStateless(X,Y,G,Q,J,W);if(!Z)return{flags:void 0,payloads:void 0,requestId:void 0};return{flags:Z.featureFlags,payloads:Z.featureFlagPayloads,requestId:Z.requestId}}async getFeatureFlagDetailsStateless(X,Y={},G={},Q={},J,W){await this._initPromise;let Z={};if(J??this.disableGeoip)Z.geoip_disable=!0;if(W)Z.flag_keys_to_evaluate=W;let $=await this.getFlags(X,Y,G,Q,Z);if(!$.success)return;let K=$.response;if(K.errorsWhileComputingFlags)console.error("[FEATURE FLAGS] Error while computing feature flags, some flags may be missing or incorrect. Learn more at https://posthog.com/docs/feature-flags/best-practices");if(K.quotaLimited?.includes("feature_flags"))return console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - feature flags unavailable. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),{flags:{},featureFlags:{},featureFlagPayloads:{},requestId:K?.requestId,quotaLimited:K.quotaLimited};return K}async getSurveysStateless(){if(await this._initPromise,this.disableSurveys===!0)return this._logger.info("Loading surveys is disabled."),[];let X=`${this.host}/api/surveys/?token=${this.apiKey}`,Y={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json"}},Q=(await this.fetchWithRetry(X,Y).then((J)=>{if(J.status!==200||!J.json){let W=`Surveys API could not be loaded: ${J.status}`,Z=Error(W);this._logger.error(Z),this._events.emit("error",Error(W));return}return J.json()}).catch((J)=>{this._logger.error("Surveys API could not be loaded",J),this._events.emit("error",J)}))?.surveys;if(Q)this._logger.info("Surveys fetched from API: ",JSON.stringify(Q));return Q??[]}get props(){if(!this._props)this._props=this.getPersistedProperty(aJ.Props);return this._props||{}}set props(X){this._props=X}async register(X){this.wrap(()=>{this.props={...this.props,...X},this.setPersistedProperty(aJ.Props,this.props)})}async unregister(X){this.wrap(()=>{delete this.props[X],this.setPersistedProperty(aJ.Props,this.props)})}processBeforeEnqueue(X){return X}async flushStorage(){}enqueue(X,Y,G){this.wrap(()=>{if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J=this.getPersistedProperty(aJ.Queue)||[];if(J.length>=this.maxQueueSize)J.shift(),this._logger.info("Queue is full, the oldest event is dropped.");if(J.push({message:Q}),this.setPersistedProperty(aJ.Queue,J),this._events.emit(X,Q),J.length>=this.flushAt)this.flushBackground();if(this.flushInterval&&!this._flushTimer)this._flushTimer=Hw(()=>this.flushBackground(),this.flushInterval)})}async sendImmediate(X,Y,G){if(this.disabled)return void this._logger.warn("The client is disabled");if(!this._isInitialized)await this._initPromise;if(this.optedOut)return void this._events.emit(X,"Library is disabled. Not sending event. To re-enable, call posthog.optIn()");let Q=this.prepareMessage(X,Y,G);if(Q=this.processBeforeEnqueue(Q),Q===null)return;let J={api_key:this.apiKey,batch:[Q],sent_at:XT1()};if(this.historicalMigration)J.historical_migration=!0;let W=JSON.stringify(J),Z=`${this.host}/batch/`,$=this.disableCompression?null:await pA1(W,this.isDebug),K={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...$!==null&&{"Content-Encoding":"gzip"}},body:$||W};try{await this.fetchWithRetry(Z,K)}catch(H){this._events.emit("error",H)}}prepareMessage(X,Y,G){let Q={...Y,type:X,library:this.getLibraryId(),library_version:this.getLibraryVersion(),timestamp:G?.timestamp?G?.timestamp:XT1(),uuid:G?.uuid?G.uuid:Tq()};if(G?.disableGeoip??this.disableGeoip){if(!Q.properties)Q.properties={};Q.properties.$geoip_disable=!0}if(Q.distinctId)Q.distinct_id=Q.distinctId,delete Q.distinctId;return Q}clearFlushTimer(){if(this._flushTimer)clearTimeout(this._flushTimer),this._flushTimer=void 0}flushBackground(){this.flush().catch(async(X)=>{await E14(X)})}async flush(){let X=CN0([this.flushPromise]).then(()=>this._flush());return this.flushPromise=X,this.addPendingPromise(X),CN0([X]).then(()=>{if(this.flushPromise===X)this.flushPromise=null}),X}getCustomHeaders(){let X=this.getCustomUserAgent(),Y={};if(X&&X!=="")Y["User-Agent"]=X;return Y}async _flush(){this.clearFlushTimer(),await this._initPromise;let X=this.getPersistedProperty(aJ.Queue)||[];if(!X.length)return;let Y=[],G=X.length;while(X.length>0&&Y.length<G){let Q=X.slice(0,this.maxBatchSize),J=Q.map((N)=>N.message),W=async()=>{let z=(this.getPersistedProperty(aJ.Queue)||[]).slice(Q.length);this.setPersistedProperty(aJ.Queue,z),X=z,await this.flushStorage()},Z={api_key:this.apiKey,batch:J,sent_at:XT1()};if(this.historicalMigration)Z.historical_migration=!0;let $=JSON.stringify(Z),K=`${this.host}/batch/`,H=this.disableCompression?null:await pA1($,this.isDebug),U={method:"POST",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",...H!==null&&{"Content-Encoding":"gzip"}},body:H||$},B={retryCheck:(N)=>{if(P14(N))return!1;return _N0(N)}};try{await this.fetchWithRetry(K,U,B)}catch(N){if(P14(N)&&J.length>1){this.maxBatchSize=Math.max(1,Math.floor(J.length/2)),this._logger.warn(`Received 413 when sending batch of size ${J.length}, reducing batch size to ${this.maxBatchSize}`);continue}if(!(N instanceof mX1))await W();throw this._events.emit("error",N),N}await W(),Y.push(...J)}this._events.emit("flush",Y)}async fetchWithRetry(X,Y,G,Q){let J=Y.body?Y.body:"",W=-1;try{W=J instanceof Blob?J.size:Buffer.byteLength(J,B14)}catch{if(J instanceof Blob)W=J.size;else W=new TextEncoder().encode(J).length}return await z14(async()=>{let Z=new AbortController,$=Q??this.requestTimeout,K=Hw(()=>Z.abort(),$),H=null;try{H=await this.fetch(X,{signal:Z.signal,...Y})}catch(B){throw new mX1(B)}finally{clearTimeout(K)}if(Y.mode!=="no-cors"&&(H.status<200||H.status>=400))throw new Gt(H,W);return H},{...this._retryOptions,...G})}async _shutdown(X=30000){await this._initPromise;let Y=!1;this.clearFlushTimer();let G=async()=>{try{await this.promiseQueue.join();while(!0){if((this.getPersistedProperty(aJ.Queue)||[]).length===0)break;if(await this.flush(),Y)break}}catch(J){if(!_N0(J))throw J;await E14(J)}},Q;try{return await Promise.race([new Promise((J,W)=>{Q=Hw(()=>{this._logger.error("Timed out while shutting down PostHog"),Y=!0,W("Timeout while shutting down PostHog. Some events may not have been sent.")},X)}),G()])}finally{clearTimeout(Q)}}async shutdown(X=30000){if(this.shutdownPromise)this._logger.warn("shutdown() called while already shutting down. shutdown() is meant to be called once before process exit - use flush() for per-request cleanup");else this.shutdownPromise=this._shutdown(X).finally(()=>{this.shutdownPromise=null});return this.shutdownPromise}}var Gt,mX1;var fN0=D(()=>{L14();iA1();EN0();Cj();U3();uX1();Gt=class Gt extends Error{constructor(X,Y){super("HTTP error while fetching PostHog: status="+X.status+", reqByteLength="+Y),this.response=X,this.reqByteLength=Y,this.name="PostHogFetchHttpError"}get status(){return this.response.status}get text(){return this.response.text()}get json(){return this.response.json()}};mX1=class mX1 extends Error{constructor(X){super("Network error while fetching PostHog",X instanceof Error?{cause:X}:{}),this.error=X,this.name="PostHogFetchNetworkError"}}});var q14=D(()=>{iA1();Cj();fN0();uX1();U3()});var A14=D(()=>{hX1()});function I14(X){let Y=globalThis._posthogChunkIds;if(!Y)return;let G=Object.keys(Y);if(QT1&&G.length===T14)return QT1;return T14=G.length,QT1=G.reduce((Q,J)=>{if(!GT1)GT1={};let W=GT1[J];if(W)Q[W[0]]=W[1];else{let Z=X(J);for(let $=Z.length-1;$>=0;$--){let H=Z[$]?.filename,U=Y[J];if(H&&U){Q[H]=U,GT1[J]=[H,U];break}}}return Q},{}),QT1}var GT1,T14,QT1;var V14=()=>{};class j14{constructor(X,Y,G=[]){this.coercers=X,this.stackParser=Y,this.modifiers=G}buildFromUnknown(X,Y={}){let Q=Y&&Y.mechanism||{handled:!0,type:"generic"},W=this.buildCoercingContext(Q,Y,0).apply(X),Z=this.buildParsingContext(Y),$=this.parseStacktrace(W,Z);return{$exception_list:this.convertToExceptionList($,Q),$exception_level:"error"}}async modifyFrames(X){for(let Y of X)if(Y.stacktrace&&Y.stacktrace.frames&&aA1(Y.stacktrace.frames))Y.stacktrace.frames=await this.applyModifiers(Y.stacktrace.frames);return X}coerceFallback(X){return{type:"Error",value:"Unknown error",stack:X.syntheticException?.stack,synthetic:!0}}parseStacktrace(X,Y){let G;if(X.cause!=null)G=this.parseStacktrace(X.cause,Y);let Q;if(X.stack!=""&&X.stack!=null)Q=this.applyChunkIds(this.stackParser(X.stack,X.synthetic?Y.skipFirstLines:0),Y.chunkIdMap);return{...X,cause:G,stack:Q}}applyChunkIds(X,Y){return X.map((G)=>{if(G.filename&&Y)G.chunk_id=Y[G.filename];return G})}applyCoercers(X,Y){for(let G of this.coercers)if(G.match(X))return G.coerce(X,Y);return this.coerceFallback(Y)}async applyModifiers(X){let Y=X;for(let G of this.modifiers)Y=await G(Y);return Y}convertToExceptionList(X,Y){let G={type:X.type,value:X.value,mechanism:{type:Y.type??"generic",handled:Y.handled??!0,synthetic:X.synthetic??!1}};if(X.stack)G.stacktrace={type:"raw",frames:X.stack};let Q=[G];if(X.cause!=null)Q.push(...this.convertToExceptionList(X.cause,{...Y,handled:!0}));return Q}buildParsingContext(X){return{chunkIdMap:I14(this.stackParser),skipFirstLines:X.skipFirstLines??1}}buildCoercingContext(X,Y,G=0){let Q=(W,Z)=>{if(!(Z<=Vn5))return;{let $=this.buildCoercingContext(X,Y,Z);return this.applyCoercers(W,$)}};return{...Y,syntheticException:G==0?Y.syntheticException:void 0,mechanism:X,apply:(W)=>Q(W,G),next:(W)=>Q(W,G+1)}}}var Vn5=4;var M14=D(()=>{U3();V14()});function Gz(X,Y,G,Q,J){let W={platform:X,filename:Y,function:G==="<anonymous>"?sQ:G,in_app:!0};if(!sa(Q))W.lineno=Q;if(!sa(J))W.colno=J;return W}var sQ="?";var Iq=D(()=>{U3()});var JT1=(X,Y)=>{let G=X.indexOf("safari-extension")!==-1,Q=X.indexOf("safari-web-extension")!==-1;return G||Q?[X.indexOf("@")!==-1?X.split("@")[0]:sQ,G?`safari-extension:${Y}`:`safari-web-extension:${Y}`]:[X,Y]};var bN0=D(()=>{Iq()});var jn5,Mn5,Rn5,yN0=(X,Y)=>{let G=jn5.exec(X);if(G){let[,J,W,Z]=G;return Gz(Y,J,sQ,+W,+Z)}let Q=Mn5.exec(X);if(Q){if(Q[2]&&Q[2].indexOf("eval")===0){let $=Rn5.exec(Q[2]);if($)Q[2]=$[1],Q[3]=$[2],Q[4]=$[3]}let[W,Z]=JT1(Q[1]||sQ,Q[2]);return Gz(Y,Z,W,Q[3]?+Q[3]:void 0,Q[4]?+Q[4]:void 0)}};var R14=D(()=>{Iq();bN0();jn5=/^\s*at (\S+?)(?::(\d+))(?::(\d+))\s*$/i,Mn5=/^\s*at (?:(.+?\)(?: \[.+\])?|.*?) ?\((?:address at )?)?(?:async )?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i,Rn5=/\((\S*)(?::(\d+))(?::(\d+))\)/});var Sn5,Cn5,xN0=(X,Y)=>{let G=Sn5.exec(X);if(G){if(G[3]&&G[3].indexOf(" > eval")>-1){let Z=Cn5.exec(G[3]);if(Z)G[1]=G[1]||"eval",G[3]=Z[1],G[4]=Z[2],G[5]=""}let J=G[3],W=G[1]||sQ;return[W,J]=JT1(W,J),Gz(Y,J,W,G[4]?+G[4]:void 0,G[5]?+G[5]:void 0)}};var S14=D(()=>{Iq();bN0();Sn5=/^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-. /=]+)(?::(\d+))?(?::(\d+))?\s*$/i,Cn5=/(\S+) line (\d+)(?: > eval line \d+)* > eval/i});var kn5,C14=(X,Y)=>{let G=kn5.exec(X);return G?Gz(Y,G[2],G[1]||sQ,+G[3],G[4]?+G[4]:void 0):void 0};var k14=D(()=>{Iq();kn5=/^\s*at (?:((?:\[object object\])?.+) )?\(?((?:[-a-z]+):.*?):(\d+)(?::(\d+))?\)?\s*$/i});var vn5,v14=(X,Y)=>{let G=vn5.exec(X);return G?Gz(Y,G[2],G[3]||sQ,+G[1]):void 0},_n5,_14=(X,Y)=>{let G=_n5.exec(X);return G?Gz(Y,G[5],G[3]||G[4]||sQ,+G[1],+G[2]):void 0};var f14=D(()=>{Iq();vn5=/ line (\d+).*script (?:in )?(\S+)(?:: in function (\S+))?$/i,_n5=/ line (\d+), column (\d+)\s*(?:in (?:<anonymous function: ([^>]+)>|([^)]+))\(.*\))? in (.*):\s*$/i});function yn5(X,Y=!1){return!(Y||X&&!X.startsWith("/")&&!X.match(/^[A-Z]:/)&&!X.startsWith(".")&&!X.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//))&&X!==void 0&&!X.includes("node_modules/")}function b14(X){return parseInt(X||"",10)||void 0}var fn5,bn5,y14=(X,Y)=>{let G=X.match(bn5);if(G){let Q,J,W,Z,$;if(G[1]){W=G[1];let U=W.lastIndexOf(".");if(W[U-1]===".")U--;if(U>0){Q=W.slice(0,U),J=W.slice(U+1);let B=Q.indexOf(".Module");if(B>0)W=W.slice(B+1),Q=Q.slice(0,B)}Z=void 0}if(J)Z=Q,$=J;if(J==="<anonymous>")$=void 0,W=void 0;if(W===void 0)$=$||sQ,W=Z?`${Z}.${$}`:$;let K=G[2]?.startsWith("file://")?G[2].slice(7):G[2],H=G[5]==="native";if(K?.match(/\/[A-Z]:/))K=K.slice(1);if(!K&&G[5]&&!H)K=G[5];return{filename:K?decodeURI(K):void 0,module:void 0,function:W,lineno:b14(G[3]),colno:b14(G[4]),in_app:yn5(K||"",H),platform:Y}}if(X.match(fn5))return{filename:X,platform:Y}};var x14=D(()=>{Iq();fn5=/^\s*[-]{4,}$/,bn5=/at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/});function u14(X){if(!X.length)return[];let Y=Array.from(X);return Y.reverse(),Y.slice(0,g14).map((G)=>({...G,filename:G.filename||xn5(Y).filename,function:G.function||sQ}))}function xn5(X){return X[X.length-1]||{}}function hn5(){return l14("web:javascript",yN0,xN0)}function l14(X,...Y){return(G,Q=0)=>{let J=[],W=G.split(`
1640
1640
  `);for(let Z=Q;Z<W.length;Z++){let $=W[Z];if($.length>1024)continue;let K=h14.test($)?$.replace(h14,"$1"):$;if(!K.match(/\S*Error: /)){for(let H of Y){let U=H(K,X);if(U){J.push(U);break}}if(J.length>=g14)break}}return u14(J)}}var h14,g14=50;var m14=D(()=>{Iq();R14();S14();k14();f14();x14();h14=/\(error: (.*)\)/});class d14{match(X){return this.isDOMException(X)||this.isDOMError(X)}coerce(X,Y){let G=Aq(X.stack);return{type:this.getType(X),value:this.getValue(X),stack:G?X.stack:void 0,cause:X.cause?Y.next(X.cause):void 0,synthetic:!1}}getType(X){return this.isDOMError(X)?"DOMError":"DOMException"}getValue(X){let Y=X.name||(this.isDOMError(X)?"DOMError":"DOMException");return X.message?`${Y}: ${X.message}`:Y}isDOMException(X){return kj(X,"DOMException")}isDOMError(X){return kj(X,"DOMError")}}var c14=D(()=>{U3()});class i14{match(X){return qN0(X)}coerce(X,Y){return{type:this.getType(X),value:this.getMessage(X,Y),stack:this.getStack(X),cause:X.cause?Y.next(X.cause):void 0,synthetic:!1}}getType(X){return X.name||X.constructor.name}getMessage(X,Y){let G=X.message;if(G.error&&typeof G.error.message=="string")return String(G.error.message);return String(G)}getStack(X){return X.stacktrace||X.stack||void 0}}var p14=D(()=>{U3()});class n14{constructor(){}match(X){return re6(X)&&X.error!=null}coerce(X,Y){let G=Y.apply(X.error);if(!G)return{type:"ErrorEvent",value:X.message,stack:Y.syntheticException?.stack,synthetic:!0};return G}}var a14=D(()=>{U3()});class t14{match(X){return typeof X=="string"}coerce(X,Y){let[G,Q]=this.getInfos(X);return{type:G??"Error",value:Q??X,stack:Y.syntheticException?.stack,synthetic:!0}}getInfos(X){let Y="Error",G=X,Q=X.match(gn5);if(Q)Y=Q[1],G=Q[2];return[Y,G]}}var gn5;var r14=D(()=>{gn5=/^(?:[Uu]ncaught (?:exception: )?)?(?:((?:Eval|Internal|Range|Reference|Syntax|Type|URI|)Error): )?(.*)$/i});var o14;var s14=D(()=>{o14=["fatal","error","warning","log","info","debug"]});function ZT1(X,Y=40){let G=Object.keys(X);if(G.sort(),!G.length)return"[object has no keys]";for(let Q=G.length;Q>0;Q--){let J=G.slice(0,Q).join(", ");if(!(J.length>Y)){if(Q===G.length)return J;return J.length<=Y?J:`${J.slice(0,Y)}...`}}return""}var hN0=()=>{};class e14{match(X){return typeof X=="object"&&X!==null}coerce(X,Y){let G=this.getErrorPropertyFromObject(X);if(G)return Y.apply(G);return{type:this.getType(X),value:this.getValue(X),stack:Y.syntheticException?.stack,level:this.isSeverityLevel(X.level)?X.level:"error",synthetic:!0}}getType(X){return ea(X)?X.constructor.name:"Error"}getValue(X){if("name"in X&&typeof X.name=="string"){let Q=`'${X.name}' captured as exception`;if("message"in X&&typeof X.message=="string")Q+=` with message: '${X.message}'`;return Q}if("message"in X&&typeof X.message=="string")return X.message;let Y=this.getObjectClassName(X),G=ZT1(X);return`${Y&&Y!=="Object"?`'${Y}'`:"Object"} captured as exception with keys: ${G}`}isSeverityLevel(X){return Aq(X)&&!te6(X)&&o14.indexOf(X)>=0}getErrorPropertyFromObject(X){for(let Y in X)if(Object.prototype.hasOwnProperty.call(X,Y)){let G=X[Y];if(O14(G))return G}}getObjectClassName(X){try{let Y=Object.getPrototypeOf(X);return Y?Y.constructor.name:void 0}catch(Y){return}}}var X04=D(()=>{U3();s14();hN0()});class Y04{match(X){return ea(X)}coerce(X,Y){let G=X.constructor.name;return{type:G,value:`${G} captured as exception with keys: ${ZT1(X)}`,stack:Y.syntheticException?.stack,synthetic:!0}}}var G04=D(()=>{U3();hN0()});class Q04{match(X){return tA1(X)}coerce(X,Y){return{type:"Error",value:`Primitive value captured as exception: ${String(X)}`,stack:Y.syntheticException?.stack,synthetic:!0}}}var J04=D(()=>{U3()});class Z04{match(X){return kj(X,"PromiseRejectionEvent")||this.isCustomEventWrappingRejection(X)}isCustomEventWrappingRejection(X){if(!ea(X))return!1;try{let Y=X.detail;return Y!=null&&typeof Y=="object"&&"reason"in Y}catch{return!1}}coerce(X,Y){let G=this.getUnhandledRejectionReason(X);if(tA1(G))return{type:"UnhandledRejection",value:`Non-Error promise rejection captured with value: ${String(G)}`,stack:Y.syntheticException?.stack,synthetic:!0};return Y.apply(G)}getUnhandledRejectionReason(X){try{if("reason"in X)return X.reason;if("detail"in X&&X.detail!=null&&typeof X.detail=="object"&&"reason"in X.detail)return X.detail.reason}catch{}return X}}var W04=D(()=>{U3()});var $04=D(()=>{c14();p14();a14();r14();X04();G04();J04();W04()});class K04{constructor(X){this._maxSize=X,this._cache=new Map}get(X){let Y=this._cache.get(X);if(Y===void 0)return;return this._cache.delete(X),this._cache.set(X,Y),Y}set(X,Y){this._cache.set(X,Y)}reduce(){while(this._cache.size>=this._maxSize){let X=this._cache.keys().next().value;if(X)this._cache.delete(X)}}}var H04=()=>{};function gN0(X){if(!X)return{...WT1};return{enabled:X.enabled??WT1.enabled,max_bytes:mn5(X.max_bytes,WT1.max_bytes)}}function ln5(X){if(!X)return{sanitizedProperties:{},droppedKeys:[]};let Y=[];return{sanitizedProperties:Object.keys(X).reduce((Q,J)=>{if(un5.has(J))return Y.push(J),Q;return Q[J]=X[J],Q},{}),droppedKeys:Y}}class F04{constructor(X){this._entries=[],this._totalBytes=0,this._config=gN0(X)}setConfig(X){this._config=gN0(X),this._trimToMaxBytes()}add(X){let Y=dn5(X);if(!Y)return;let G=U04(Y.json);if(G>this._config.max_bytes)return;this._entries.push({step:Y.step,bytes:G}),this._totalBytes+=G,this._trimToMaxBytes()}getAttachable(){return this._entries.map((X)=>X.step)}clear(){this._entries=[],this._totalBytes=0}size(){return this._entries.length}_trimToMaxBytes(){while(this._totalBytes>this._config.max_bytes&&this._entries.length>0){let X=this._entries.shift();if(X)this._totalBytes-=X.bytes}}}function mn5(X,Y){if(!xX1(X)||X===1/0||X===-1/0)return Y;let G=Math.floor(X);if(G<0)return Y;return G}function dn5(X){let Y=cn5(X);if(!Y)return;try{let G=JSON.parse(Y);if(!yX1(G))return;let Q=G,J=Q[dX1.MESSAGE],W=Q[dX1.TIMESTAMP];if(!Aq(J)||J.trim().length===0)return;if(!Aq(W)&&!xX1(W))return;return{step:Q,json:Y}}catch{return}}function cn5(X){let Y=new WeakSet;try{return JSON.stringify(X,(G,Q)=>{if(typeof Q=="bigint")return Q.toString();if(typeof Q=="function"||typeof Q=="symbol")return;if(Q instanceof Date)return Q.toISOString();if(Q instanceof Error)return{name:Q.name,message:Q.message,stack:Q.stack};if(Q&&typeof Q=="object"){if(Y.has(Q))return"[Circular]";Y.add(Q)}return Q})}catch{return}}function U04(X){if(typeof TextEncoder<"u")return new TextEncoder().encode(X).length;let Y=encodeURIComponent(X),G=0;for(let Q=0;Q<Y.length;Q++)if(Y[Q]==="%")G+=1,Q+=2;else G+=1;return G}var dX1,un5,WT1;var B04=D(()=>{U3();dX1={MESSAGE:"$message",TIMESTAMP:"$timestamp"},un5=new Set([dX1.MESSAGE,dX1.TIMESTAMP]),WT1={enabled:!0,max_bytes:32768}});var qW={};M0(qW,{winjsStackLineParser:()=>C14,stripReservedExceptionStepFields:()=>ln5,reverseAndStripFrames:()=>u14,resolveExceptionStepsConfig:()=>gN0,opera11StackLineParser:()=>_14,opera10StackLineParser:()=>v14,nodeStackLineParser:()=>y14,getUtf8ByteLength:()=>U04,geckoStackLineParser:()=>xN0,createStackParser:()=>l14,createDefaultStackParser:()=>hn5,chromeStackLineParser:()=>yN0,StringCoercer:()=>t14,ReduceableCache:()=>K04,PromiseRejectionEventCoercer:()=>Z04,PrimitiveCoercer:()=>Q04,ObjectCoercer:()=>e14,ExceptionStepsBuffer:()=>F04,EventCoercer:()=>Y04,ErrorPropertiesBuilder:()=>j14,ErrorEventCoercer:()=>n14,ErrorCoercer:()=>i14,EXCEPTION_STEP_INTERNAL_FIELDS:()=>dX1,DOMExceptionCoercer:()=>d14,DEFAULT_EXCEPTION_STEPS_CONFIG:()=>WT1});var N04=D(()=>{M14();m14();$04();H04();B04()});var _j=D(()=>{iA1();EN0();kN0();D14();uX1();w14();N04();U3();q14();fN0();A14();Cj()});import{createReadStream as in5}from"fs";import{createInterface as pn5}from"readline";async function w04(X){let Y={};for(let J=X.length-1;J>=0;J--){let W=X[J],Z=W?.filename;if(!W||typeof Z!="string"||typeof W.lineno!="number"||sn5(Z)||en5(W))continue;if(!Y[Z])Y[Z]=[];Y[Z].push(W.lineno)}let G=Object.keys(Y);if(G.length==0)return X;let Q=[];for(let J of G){if(D04.get(J))continue;let W=Y[J];if(!W)continue;W.sort((K,H)=>K-H);let Z=Ya5(W);if(Z.every((K)=>Xa5(J,K)))continue;let $=Ga5($T1,J,{});Q.push(tn5(J,Z,$))}if(await Promise.all(Q).catch(()=>{}),X&&X.length>0)rn5(X,$T1);return $T1.reduce(),X}function tn5(X,Y,G){return new Promise((Q)=>{let J=in5(X),W=pn5({input:J});function Z(){J.destroy(),Q()}let $=0,K=0,H=Y[K];if(H===void 0)return void Z();let U=H[0],B=H[1];function N(){D04.set(X,1),W.close(),W.removeAllListeners(),Z()}J.on("error",N),W.on("error",N),W.on("close",Z),W.on("line",(z)=>{if($++,$<U)return;if(G[$]=Qa5(z,0),$>=B){if(K===Y.length-1){W.close(),W.removeAllListeners();return}K++;let O=Y[K];if(O===void 0){W.close(),W.removeAllListeners();return}U=O[0],B=O[1]}})})}function rn5(X,Y){for(let G of X)if(G.filename&&G.context_line===void 0&&typeof G.lineno=="number"){let Q=Y.get(G.filename);if(Q===void 0)continue;on5(G.lineno,G,Q)}}function on5(X,Y,G){if(Y.lineno===void 0||G===void 0)return;Y.pre_context=[];for(let J=L04(X);J<X;J++){let W=G[J];if(W===void 0)return void z04(Y);Y.pre_context.push(W)}if(G[X]===void 0)return void z04(Y);Y.context_line=G[X];let Q=E04(X);Y.post_context=[];for(let J=X+1;J<=Q;J++){let W=G[J];if(W===void 0)break;Y.post_context.push(W)}}function z04(X){delete X.pre_context,delete X.context_line,delete X.post_context}function sn5(X){return X.startsWith("node:")||X.endsWith(".min.js")||X.endsWith(".min.cjs")||X.endsWith(".min.mjs")||X.startsWith("data:")}function en5(X){if(X.lineno!==void 0&&X.lineno>an5)return!0;if(X.colno!==void 0&&X.colno>nn5)return!0;return!1}function Xa5(X,Y){let G=$T1.get(X);if(G===void 0)return!1;for(let Q=Y[0];Q<=Y[1];Q++)if(G[Q]===void 0)return!1;return!0}function Ya5(X){if(!X.length)return[];let Y=0,G=X[0];if(typeof G!="number")return[];let Q=O04(G),J=[];while(!0){if(Y===X.length-1){J.push(Q);break}let W=X[Y+1];if(typeof W!="number")break;if(W<=Q[1])Q[1]=W+uN0;else J.push(Q),Q=O04(W);Y++}return J}function O04(X){return[L04(X),E04(X)]}function L04(X){return Math.max(1,X-uN0)}function E04(X){return X+uN0}function Ga5(X,Y,G){let Q=X.get(Y);if(Q===void 0)return X.set(Y,G),G;return Q}function Qa5(X,Y){let G=X,Q=G.length;if(Q<=150)return G;if(Y>Q)Y=Q;let J=Math.max(Y-60,0);if(J<5)J=0;let W=Math.min(J+140,Q);if(W>Q-5)W=Q;if(W===Q)J=Math.max(W-140,0);if(G=G.slice(J,W),J>0)G=`...${G}`;if(W<Q)G+="...";return G}var $T1,D04,uN0=7,nn5=1000,an5=1e4;var P04=D(()=>{_j();$T1=new qW.ReduceableCache(25),D04=new qW.ReduceableCache(20)});import{isAbsolute as Ja5,relative as Za5,sep as Wa5}from"path";function q04(X=process.cwd()){let Y=Wa5==="\\",G=(J)=>Y?J.replace(/\\/g,"/"):J,Q=G(X);return async(J)=>{for(let W of J)if(!(!W.filename||W.filename.startsWith("node:")||W.filename.startsWith("data:"))){if(Ja5(W.filename))W.filename=G(Za5(Q,G(W.filename)))}return J}}var A04=()=>{};function $a5(X,Y){let G=!1;return Object.assign((Q)=>{let W=global.process.listeners("uncaughtException").filter((Z)=>Z.name!=="domainUncaughtExceptionClear"&&Z._posthogErrorHandler!==!0).length===0;if(X(Q,{mechanism:{type:"onuncaughtexception",handled:!1}}),!G&&W)G=!0,Y(Q)},{_posthogErrorHandler:!0})}function T04(X,Y){globalThis.process?.on("uncaughtException",$a5(X,Y))}function I04(X){globalThis.process?.on("unhandledRejection",(Y)=>X(Y,{mechanism:{type:"onunhandledrejection",handled:!1}}))}var V04=()=>{};class DH{constructor(X,Y,G){this.client=X,this._exceptionAutocaptureEnabled=Y.enableExceptionAutocapture||!1,this._logger=G,this._rateLimiter=new TN0({refillRate:1,bucketSize:10,refillInterval:1e4,_logger:this._logger}),this.startAutocaptureIfEnabled()}static isPreviouslyCapturedError(X){return yX1(X)&&"__posthog_previously_captured_error"in X&&X.__posthog_previously_captured_error===!0}static async buildEventMessage(X,Y,G,Q){let J={...Q},W=this.errorPropertiesBuilder.buildFromUnknown(X,Y);return W.$exception_list=await this.errorPropertiesBuilder.modifyFrames(W.$exception_list),{event:"$exception",distinctId:G,properties:{...W,...J},_originatedFromCaptureException:!0}}startAutocaptureIfEnabled(){if(this.isEnabled())T04(this.onException.bind(this),this.onFatalError.bind(this)),I04(this.onException.bind(this))}onException(X,Y){this.client.addPendingPromise((async()=>{if(!DH.isPreviouslyCapturedError(X)){let G=await DH.buildEventMessage(X,Y),J=G.properties?.$exception_list[0]?.type??"Exception";if(this._rateLimiter.consumeRateLimit(J))return void this._logger.info("Skipping exception capture because of client rate limiting.",{exception:J});return this.client.capture(G)}})())}async onFatalError(X){console.error(X),await this.client.shutdown(Ka5),process.exit(1)}isEnabled(){return!this.client.isDisabled&&this._exceptionAutocaptureEnabled}shutdown(){this._rateLimiter.stop()}}var Ka5=2000;var KT1=D(()=>{V04();_j()});var j04="5.30.6";var M04=()=>{};var cX1;var lN0=D(()=>{cX1={ERRORS_WHILE_COMPUTING:"errors_while_computing_flags",FLAG_MISSING:"flag_missing",QUOTA_LIMITED:"quota_limited",UNKNOWN_ERROR:"unknown_error"}});async function R04(X){let Y=globalThis.crypto?.subtle;if(!Y)throw Error("SubtleCrypto API not available");let G=await Y.digest("SHA-1",new TextEncoder().encode(X));return Array.from(new Uint8Array(G)).map((J)=>J.toString(16).padStart(2,"0")).join("")}var S04=()=>{};class mN0{constructor({pollingInterval:X,personalApiKey:Y,projectApiKey:G,timeout:Q,host:J,customHeaders:W,...Z}){this.debugMode=!1,this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.pollingInterval=X,this.personalApiKey=Y,this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={},this.loadedSuccessfullyOnce=!1,this.timeout=Q,this.projectApiKey=G,this.host=J,this.poller=void 0,this.fetch=Z.fetch||fetch,this.onError=Z.onError,this.customHeaders=W,this.onLoad=Z.onLoad,this.cacheProvider=Z.cacheProvider,this.strictLocalEvaluation=Z.strictLocalEvaluation??!1,this.loadFeatureFlags()}debug(X=!0){this.debugMode=X}logMsgIfDebug(X){if(this.debugMode)X()}createEvaluationContext(X,Y={},G={},Q={},J={}){return{distinctId:X,groups:Y,personProperties:G,groupProperties:Q,evaluationCache:J}}async getFeatureFlag(X,Y,G={},Q={},J={}){await this.loadFeatureFlags();let W,Z;if(!this.loadedSuccessfullyOnce)return W;if(Z=this.featureFlagsByKey[X],Z!==void 0){let $=this.createEvaluationContext(Y,G,Q,J);try{W=(await this.computeFlagAndPayloadLocally(Z,$)).value,this.logMsgIfDebug(()=>console.debug(`Successfully computed flag locally: ${X} -> ${W}`))}catch(K){if(K instanceof Qz||K instanceof d5)this.logMsgIfDebug(()=>console.debug(`${K.name} when computing flag locally: ${X}: ${K.message}`));else if(K instanceof Error)this.onError?.(Error(`Error computing flag locally: ${X}: ${K}`))}}return W}async getAllFlagsAndPayloads(X,Y){await this.loadFeatureFlags();let G={},Q={},J=this.featureFlags.length==0,W=Y?Y.map(($)=>this.featureFlagsByKey[$]).filter(Boolean):this.featureFlags,Z={...X,evaluationCache:X.evaluationCache??{}};return await Promise.all(W.map(async($)=>{try{let{value:K,payload:H}=await this.computeFlagAndPayloadLocally($,Z);if(G[$.key]=K,H)Q[$.key]=H}catch(K){if(K instanceof Qz||K instanceof d5)this.logMsgIfDebug(()=>console.debug(`${K.name} when computing flag locally: ${$.key}: ${K.message}`));else if(K instanceof Error)this.onError?.(Error(`Error computing flag locally: ${$.key}: ${K}`));J=!0}})),{response:G,payloads:Q,fallbackToFlags:J}}async computeFlagAndPayloadLocally(X,Y,G={}){let{matchValue:Q,skipLoadCheck:J=!1}=G;if(!J)await this.loadFeatureFlags();if(!this.loadedSuccessfullyOnce)return{value:!1,payload:null};let W;W=Q!==void 0?Q:await this.computeFlagValueLocally(X,Y);let Z=this.getFeatureFlagPayload(X.key,W);return{value:W,payload:Z}}async computeFlagValueLocally(X,Y){let{distinctId:G,groups:Q,personProperties:J,groupProperties:W}=Y;if(X.ensure_experience_continuity)throw new d5("Flag has experience continuity enabled");if(!X.active)return!1;let $=(X.filters||{}).aggregation_group_type_index;if($!=null){let K=this.groupTypeMapping[String($)];if(!K)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Unknown group type index ${$} for feature flag ${X.key}`)),new d5("Flag has unknown group type index");if(!(K in Q))return this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute group feature flag: ${X.key} without group names passed in`)),!1;if(X.bucketing_identifier==="device_id"&&(J?.$device_id===void 0||J?.$device_id===null||J?.$device_id===""))this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Ignoring bucketing_identifier for group flag: ${X.key}`));let H=W[K];return await this.matchFeatureFlagProperties(X,Q[K],H,Y)}{let K=this.getBucketingValueForFlag(X,G,J);if(K===void 0)throw this.logMsgIfDebug(()=>console.warn(`[FEATURE FLAGS] Can't compute feature flag: ${X.key} without $device_id, falling back to server evaluation`)),new d5(`Can't compute feature flag: ${X.key} without $device_id`);return await this.matchFeatureFlagProperties(X,K,J,Y)}}getBucketingValueForFlag(X,Y,G){if(X.filters?.aggregation_group_type_index!=null)return Y;if(X.bucketing_identifier==="device_id"){let Q=G?.$device_id;if(Q==null||Q==="")return;return Q}return Y}getFeatureFlagPayload(X,Y){let G=null;if(Y!==!1&&Y!=null){if(typeof Y=="boolean")G=this.featureFlagsByKey?.[X]?.filters?.payloads?.[Y.toString()]||null;else if(typeof Y=="string")G=this.featureFlagsByKey?.[X]?.filters?.payloads?.[Y]||null;if(G!=null){if(typeof G=="object")return G;if(typeof G=="string")try{return JSON.parse(G)}catch{}return G}}return null}async evaluateFlagDependency(X,Y,G){let{evaluationCache:Q}=G,J=X.key;if(!this.featureFlagsByKey)throw new d5("Feature flags not available for dependency evaluation");if(!("dependency_chain"in X))throw new d5(`Flag dependency property for '${J}' is missing required 'dependency_chain' field`);let W=X.dependency_chain;if(!Array.isArray(W))throw new d5(`Flag dependency property for '${J}' has an invalid 'dependency_chain' (expected array, got ${typeof W})`);if(W.length===0)throw new d5(`Circular dependency detected for flag '${J}' (empty dependency chain)`);for(let $ of W){if(!($ in Q)){let H=this.featureFlagsByKey[$];if(H)if(H.active)try{let U=await this.computeFlagValueLocally(H,G);Q[$]=U}catch(U){throw new d5(`Error evaluating flag dependency '${$}' for flag '${J}': ${U}`)}else Q[$]=!1;else throw new d5(`Missing flag dependency '${$}' for flag '${J}'`)}if(Q[$]==null)throw new d5(`Dependency '${$}' could not be evaluated`)}let Z=Q[J];return this.flagEvaluatesToExpectedValue(X.value,Z)}flagEvaluatesToExpectedValue(X,Y){if(typeof X=="boolean")return X===Y||typeof Y=="string"&&Y!==""&&X===!0;if(typeof X=="string")return Y===X;return!1}async matchFeatureFlagProperties(X,Y,G,Q){let J=X.filters||{},W=J.groups||[],Z=!1,$;for(let K of W)try{if(await this.isConditionMatch(X,Y,K,G,Q)){let H=K.variant,U=J.multivariate?.variants||[];$=H&&U.some((B)=>B.key===H)?H:await this.getMatchingVariant(X,Y)||!0;break}}catch(H){if(H instanceof Qz)throw H;if(H instanceof d5)Z=!0;else throw H}if($!==void 0)return $;if(Z)throw new d5("Can't determine if feature flag is enabled or not with given properties");return!1}async isConditionMatch(X,Y,G,Q,J){let W=G.rollout_percentage,Z=($)=>{this.logMsgIfDebug(()=>console.warn($))};if((G.properties||[]).length>0){for(let $ of G.properties){let K=$.type,H=!1;if(H=K==="cohort"?f04($,Q,this.cohorts,this.debugMode):K==="flag"?await this.evaluateFlagDependency($,Q,J):_04($,Q,Z),!H)return!1}if(W==null)return!0}if(W!=null&&await C04(X.key,Y)>W/100)return!1;return!0}async getMatchingVariant(X,Y){let G=await C04(X.key,Y,"variant"),Q=this.variantLookupTable(X).find((J)=>G>=J.valueMin&&G<J.valueMax);if(Q)return Q.key}variantLookupTable(X){let Y=[],G=0,Q=0;return((X.filters||{}).multivariate?.variants||[]).forEach((Z)=>{Q=G+Z.rollout_percentage/100,Y.push({valueMin:G,valueMax:Q,key:Z.key}),G=Q}),Y}updateFlagState(X){this.featureFlags=X.flags,this.featureFlagsByKey=X.flags.reduce((Y,G)=>(Y[G.key]=G,Y),{}),this.groupTypeMapping=X.groupTypeMapping,this.cohorts=X.cohorts,this.loadedSuccessfullyOnce=!0}warnAboutExperienceContinuityFlags(X){if(this.strictLocalEvaluation)return;let Y=X.filter((G)=>G.ensure_experience_continuity);if(Y.length>0)console.warn(`[PostHog] You are using local evaluation but ${Y.length} flag(s) have experience continuity enabled: ${Y.map((G)=>G.key).join(", ")}. Experience continuity is incompatible with local evaluation and will cause a server request on every flag evaluation, negating local evaluation cost savings. To avoid server requests and unexpected costs, either disable experience continuity on these flags in PostHog, use strictLocalEvaluation: true in client init, or pass onlyEvaluateLocally: true per flag call (flags that cannot be evaluated locally will return undefined).`)}async loadFromCache(X){if(!this.cacheProvider)return!1;try{let Y=await this.cacheProvider.getFlagDefinitions();if(Y)return this.updateFlagState(Y),this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] ${X} (${Y.flags.length} flags)`)),this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(Y.flags),!0;return!1}catch(Y){return this.onError?.(Error(`Failed to load from cache: ${Y}`)),!1}}async loadFeatureFlags(X=!1){if(this.loadedSuccessfullyOnce&&!X)return;if(!X&&this.nextFetchAllowedAt&&Date.now()<this.nextFetchAllowedAt)return void this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Skipping fetch, in backoff period"));if(!this.loadingPromise)this.loadingPromise=this._loadFeatureFlags().catch((Y)=>this.logMsgIfDebug(()=>console.debug(`[FEATURE FLAGS] Failed to load feature flags: ${Y}`))).finally(()=>{this.loadingPromise=void 0});return this.loadingPromise}isLocalEvaluationReady(){return(this.loadedSuccessfullyOnce??!1)&&(this.featureFlags?.length??0)>0}getFlagDefinitionsLoadedAt(){return this.flagDefinitionsLoadedAt}getPollingInterval(){if(!this.shouldBeginExponentialBackoff)return this.pollingInterval;return Math.min(Ha5,this.pollingInterval*2**this.backOffCount)}beginBackoff(){this.shouldBeginExponentialBackoff=!0,this.backOffCount+=1,this.nextFetchAllowedAt=Date.now()+this.getPollingInterval()}clearBackoff(){this.shouldBeginExponentialBackoff=!1,this.backOffCount=0,this.nextFetchAllowedAt=void 0}async _loadFeatureFlags(){if(this.poller)clearTimeout(this.poller),this.poller=void 0;this.poller=setTimeout(()=>this.loadFeatureFlags(!0),this.getPollingInterval());try{let X=!0;if(this.cacheProvider)try{X=await this.cacheProvider.shouldFetchFlagDefinitions()}catch(G){this.onError?.(Error(`Error in shouldFetchFlagDefinitions: ${G}`))}if(!X){if(await this.loadFromCache("Loaded flags from cache (skipped fetch)"))return;if(this.loadedSuccessfullyOnce)return}let Y=await this._requestFeatureFlagDefinitions();if(!Y)return;switch(Y.status){case 304:this.logMsgIfDebug(()=>console.debug("[FEATURE FLAGS] Flags not modified (304), using cached data")),this.flagsEtag=Y.headers?.get("ETag")??this.flagsEtag,this.loadedSuccessfullyOnce=!0,this.clearBackoff();return;case 401:throw this.beginBackoff(),new Qt(`Your project key or personal API key is invalid. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 402:console.warn("[FEATURE FLAGS] Feature flags quota limit exceeded - unsetting all local flags. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts"),this.featureFlags=[],this.featureFlagsByKey={},this.groupTypeMapping={},this.cohorts={};return;case 403:throw this.beginBackoff(),new Qt(`Your personal API key does not have permission to fetch feature flag definitions for local evaluation. Setting next polling interval to ${this.getPollingInterval()}ms. Are you sure you're using the correct personal and Project API key pair? More information: https://posthog.com/docs/api/overview`);case 429:throw this.beginBackoff(),new Qt(`You are being rate limited. Setting next polling interval to ${this.getPollingInterval()}ms. More information: https://posthog.com/docs/api#rate-limiting`);case 200:{let G=await Y.json()??{};if(!("flags"in G))return void this.onError?.(Error(`Invalid response when getting feature flags: ${JSON.stringify(G)}`));this.flagsEtag=Y.headers?.get("ETag")??void 0;let Q={flags:G.flags??[],groupTypeMapping:G.group_type_mapping||{},cohorts:G.cohorts||{}};if(this.updateFlagState(Q),this.flagDefinitionsLoadedAt=Date.now(),this.clearBackoff(),this.cacheProvider&&X)try{await this.cacheProvider.onFlagDefinitionsReceived(Q)}catch(J){this.onError?.(Error(`Failed to store in cache: ${J}`))}this.onLoad?.(this.featureFlags.length),this.warnAboutExperienceContinuityFlags(Q.flags);break}default:return}}catch(X){if(X instanceof Qt)this.onError?.(X)}}getPersonalApiKeyRequestOptions(X="GET",Y){let G={...this.customHeaders,"Content-Type":"application/json",Authorization:`Bearer ${this.personalApiKey}`};if(Y)G["If-None-Match"]=Y;return{method:X,headers:G}}_requestFeatureFlagDefinitions(){let X=`${this.host}/flags/definitions?token=${this.projectApiKey}&send_cohorts`,Y=this.getPersonalApiKeyRequestOptions("GET",this.flagsEtag),G=null;if(this.timeout&&typeof this.timeout=="number"){let Q=new AbortController;G=Hw(()=>{Q.abort()},this.timeout),Y.signal=Q.signal}try{let Q=this.fetch;return Q(X,Y)}finally{clearTimeout(G)}}async stopPoller(X=30000){if(clearTimeout(this.poller),this.cacheProvider)try{let Y=this.cacheProvider.shutdown();if(Y instanceof Promise)await Promise.race([Y,new Promise((G,Q)=>setTimeout(()=>Q(Error(`Cache shutdown timeout after ${X}ms`)),X))])}catch(Y){this.onError?.(Error(`Error during cache shutdown: ${Y}`))}}}async function C04(X,Y,G=""){let Q=await R04(`${X}.${Y}${G}`);return parseInt(Q.slice(0,15),16)/Fa5}function _04(X,Y,G){let{key:Q,value:J}=X,W=X.operator||"exact";if(Q in Y){if(W==="is_not_set")throw new d5("Operator is_not_set is not supported")}else throw new d5(`Property ${Q} not found in propertyValues`);let Z=Y[Q];if(Z==null&&!Ua5.includes(W)){if(G)G(`Property ${Q} cannot have a value of null/undefined with the ${W} operator`);return!1}function $(H,U){if(Array.isArray(H))return H.map((B)=>String(B).toLowerCase()).includes(String(U).toLowerCase());return String(H).toLowerCase()===String(U).toLowerCase()}function K(H,U,B){if(B==="gt")return H>U;if(B==="gte")return H>=U;if(B==="lt")return H<U;if(B==="lte")return H<=U;throw Error(`Invalid operator: ${B}`)}switch(W){case"exact":return $(J,Z);case"is_not":return!$(J,Z);case"is_set":return Q in Y;case"icontains":return String(Z).toLowerCase().includes(String(J).toLowerCase());case"not_icontains":return!String(Z).toLowerCase().includes(String(J).toLowerCase());case"regex":return k04(String(J))&&String(Z).match(String(J))!==null;case"not_regex":return k04(String(J))&&String(Z).match(String(J))===null;case"gt":case"gte":case"lt":case"lte":{let H=typeof J=="number"?J:null;if(typeof J=="string")try{H=parseFloat(J)}catch(U){}if(H==null||Z==null)return K(String(Z),String(J),W);if(typeof Z=="string")return K(Z,String(J),W);return K(Z,H,W)}case"is_date_after":case"is_date_before":{if(typeof J=="boolean")throw new d5("Date operations cannot be performed on boolean values");let H=Da5(String(J));if(H==null)H=v04(J);if(H==null)throw new d5(`Invalid date: ${J}`);let U=v04(Z);if(["is_date_before"].includes(W))return U<H;return U>H}case"semver_eq":return wH(eQ(String(Z)),eQ(String(J)))===0;case"semver_neq":return wH(eQ(String(Z)),eQ(String(J)))!==0;case"semver_gt":return wH(eQ(String(Z)),eQ(String(J)))>0;case"semver_gte":return wH(eQ(String(Z)),eQ(String(J)))>=0;case"semver_lt":return wH(eQ(String(Z)),eQ(String(J)))<0;case"semver_lte":return wH(eQ(String(Z)),eQ(String(J)))<=0;case"semver_tilde":{let H=eQ(String(Z)),{lower:U,upper:B}=Na5(String(J));return wH(H,U)>=0&&wH(H,B)<0}case"semver_caret":{let H=eQ(String(Z)),{lower:U,upper:B}=za5(String(J));return wH(H,U)>=0&&wH(H,B)<0}case"semver_wildcard":{let H=eQ(String(Z)),{lower:U,upper:B}=Oa5(String(J));return wH(H,U)>=0&&wH(H,B)<0}default:throw new d5(`Unknown operator: ${W}`)}}function Ba5(X,Y){if(!(X in Y))throw new Qz(`cohort ${X} not found in local cohorts - likely a static cohort that requires server evaluation`)}function f04(X,Y,G,Q=!1){let J=String(X.value);Ba5(J,G);let W=G[J];return b04(W,Y,G,Q)}function b04(X,Y,G,Q=!1){if(!X)return!0;let{type:J,values:W}=X;if(!W||W.length===0)return!0;let Z=!1;if("values"in W[0]){for(let $ of W)try{let K=b04($,Y,G,Q);if(J==="AND"){if(!K)return!1}else if(K)return!0}catch(K){if(K instanceof Qz)throw K;if(K instanceof d5){if(Q)console.debug(`Failed to compute property ${$} locally: ${K}`);Z=!0}else throw K}if(Z)throw new d5("Can't match cohort without a given cohort property value");return J==="AND"}for(let $ of W)try{let K;if($.type==="cohort")K=f04($,Y,G,Q);else if($.type==="flag"){if(Q)console.warn(`[FEATURE FLAGS] Flag dependency filters are not supported in local evaluation. Skipping condition with dependency on flag '${$.key||"unknown"}'`);continue}else K=_04($,Y);let H=$.negation||!1;if(J==="AND"){if(!K&&!H)return!1;if(K&&H)return!1}else{if(K&&!H)return!0;if(!K&&H)return!0}}catch(K){if(K instanceof Qz)throw K;if(K instanceof d5){if(Q)console.debug(`Failed to compute property ${$} locally: ${K}`);Z=!0}else throw K}if(Z)throw new d5("can't match cohort without a given cohort property value");return J==="AND"}function k04(X){try{return new RegExp(X),!0}catch(Y){return!1}}function eQ(X){let G=String(X).trim().replace(/^[vV]/,"").split("-")[0].split("+")[0];if(!G||G.startsWith("."))throw new d5(`Invalid semver: ${X}`);let Q=G.split("."),J=(K)=>{if(K===void 0||K==="")return 0;if(!/^\d+$/.test(K))throw new d5(`Invalid semver: ${X}`);return parseInt(K,10)},W=J(Q[0]),Z=J(Q[1]),$=J(Q[2]);return[W,Z,$]}function wH(X,Y){for(let G=0;G<3;G++){if(X[G]<Y[G])return-1;if(X[G]>Y[G])return 1}return 0}function Na5(X){let Y=eQ(X),G=[Y[0],Y[1],Y[2]],Q=[Y[0],Y[1]+1,0];return{lower:G,upper:Q}}function za5(X){let Y=eQ(X),[G,Q,J]=Y,W=[G,Q,J],Z;return Z=G>0?[G+1,0,0]:Q>0?[0,Q+1,0]:[0,0,J+1],{lower:W,upper:Z}}function Oa5(X){let G=String(X).trim().replace(/^[vV]/,"").replace(/\.\*$/,"").replace(/\*$/,"");if(!G)throw new d5(`Invalid wildcard semver: ${X}`);let Q=G.split("."),J=parseInt(Q[0],10);if(isNaN(J))throw new d5(`Invalid wildcard semver: ${X}`);let W,Z;if(Q.length===1)W=[J,0,0],Z=[J+1,0,0];else{let $=parseInt(Q[1],10);if(isNaN($))throw new d5(`Invalid wildcard semver: ${X}`);W=[J,$,0],Z=[J,$+1,0]}return{lower:W,upper:Z}}function v04(X){if(X instanceof Date)return X;if(typeof X=="string"||typeof X=="number"){let Y=new Date(X);if(!isNaN(Y.valueOf()))return Y;throw new d5(`${X} is in an invalid date format`)}throw new d5(`The date provided ${X} must be a string, number, or date object`)}function Da5(X){let Y=/^-?(?<number>[0-9]+)(?<interval>[a-z])$/,G=X.match(Y),Q=new Date(new Date().toISOString());if(!G)return null;{if(!G.groups)return null;let J=parseInt(G.groups.number);if(J>=1e4)return null;let W=G.groups.interval;if(W=="h")Q.setUTCHours(Q.getUTCHours()-J);else if(W=="d")Q.setUTCDate(Q.getUTCDate()-J);else if(W=="w")Q.setUTCDate(Q.getUTCDate()-7*J);else if(W=="m")Q.setUTCMonth(Q.getUTCMonth()-J);else{if(W!="y")return null;Q.setUTCFullYear(Q.getUTCFullYear()-J)}return Q}}var Ha5=60000,Fa5=1152921504606847000,Ua5,Qt,d5,Qz;var y04=D(()=>{_j();S04();Ua5=["is_not"];Qt=class Qt extends Error{constructor(X){super();Error.captureStackTrace(this,this.constructor),this.name="ClientError",this.message=X,Object.setPrototypeOf(this,Qt.prototype)}};d5=class d5 extends Error{constructor(X){super(X);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,d5.prototype)}};Qz=class Qz extends Error{constructor(X){super(X);this.name=this.constructor.name,Error.captureStackTrace(this,this.constructor),Object.setPrototypeOf(this,Qz.prototype)}}});class dN0{getProperty(X){return this._memoryStorage[X]}setProperty(X,Y){this._memoryStorage[X]=Y!==null?Y:void 0}constructor(){this._memoryStorage={}}}var x04=()=>{};function Aa5(X){return typeof X=="string"?X.trim():""}function Ta5(X){return(typeof X=="string"?X.trim():"")||void 0}function Ia5(X){return(typeof X=="string"?X.trim():"")||qa5}var wa5=100,h04=30000,La5=50000,Ea5=50,Pa5=500,qa5="https://us.i.posthog.com",cN0;var g04=D(()=>{M04();_j();lN0();y04();KT1();x04();cN0=class cN0 extends YT1{constructor(X,Y={}){let G=Aa5(X),Q={...Y,host:Ia5(Y.host),personalApiKey:Ta5(Y.personalApiKey)};if(super(G,Q),this._memoryStorage=new dN0,this.options=Q,this.context=this.initializeContext(),this.options.featureFlagsPollingInterval=typeof Q.featureFlagsPollingInterval=="number"?Math.max(Q.featureFlagsPollingInterval,wa5):h04,typeof Q.waitUntilDebounceMs=="number")this.options.waitUntilDebounceMs=Math.max(Q.waitUntilDebounceMs,0);if(typeof Q.waitUntilMaxWaitMs=="number")this.options.waitUntilMaxWaitMs=Math.max(Q.waitUntilMaxWaitMs,0);if(Q.personalApiKey){if(Q.personalApiKey.includes("phc_"))throw Error('Your Personal API key is invalid. These keys are prefixed with "phx_" and can be created in PostHog project settings.');if(Q.enableLocalEvaluation!==!1)this.featureFlagsPoller=new mN0({pollingInterval:this.options.featureFlagsPollingInterval,personalApiKey:Q.personalApiKey,projectApiKey:G,timeout:Q.requestTimeout??1e4,host:this.host,fetch:Q.fetch,onError:(W)=>{this._events.emit("error",W)},onLoad:(W)=>{this._events.emit("localEvaluationFlagsLoaded",W)},customHeaders:this.getCustomHeaders(),cacheProvider:Q.flagDefinitionCacheProvider,strictLocalEvaluation:Q.strictLocalEvaluation})}this.errorTracking=new DH(this,Q,this._logger),this.distinctIdHasSentFlagCalls={},this.maxCacheSize=Q.maxCacheSize||La5}enqueue(X,Y,G){super.enqueue(X,Y,G),this.scheduleDebouncedFlush()}async flush(){let X=super.flush(),Y=this.options.waitUntil;if(Y&&!this._waitUntilCycle)try{Y(X.catch(()=>{}))}catch{}return X}scheduleDebouncedFlush(){let X=this.options.waitUntil;if(!X)return;if(this.disabled||this.optedOut)return;if(!this._waitUntilCycle){let W,Z=new Promise(($)=>{W=$});try{X(Z)}catch{return}this._waitUntilCycle={resolve:W,startedAt:Date.now(),timer:void 0}}let Y=Date.now()-this._waitUntilCycle.startedAt,G=this.options.waitUntilMaxWaitMs??Pa5,Q=Y>=G;if(this._waitUntilCycle.timer!==void 0)clearTimeout(this._waitUntilCycle.timer);if(Q)return void this.resolveWaitUntilFlush();let J=this.options.waitUntilDebounceMs??Ea5;this._waitUntilCycle.timer=Hw(()=>{this.resolveWaitUntilFlush()},J)}_consumeWaitUntilCycle(){let X=this._waitUntilCycle;if(X)clearTimeout(X.timer),this._waitUntilCycle=void 0;return X?.resolve}async resolveWaitUntilFlush(){let X=this._consumeWaitUntilCycle();try{await super.flush()}catch{}finally{X?.()}}getPersistedProperty(X){return this._memoryStorage.getProperty(X)}setPersistedProperty(X,Y){return this._memoryStorage.setProperty(X,Y)}fetch(X,Y){return this.options.fetch?this.options.fetch(X,Y):fetch(X,Y)}getLibraryVersion(){return j04}getCustomUserAgent(){return`${this.getLibraryId()}/${this.getLibraryVersion()}`}enable(){return super.optIn()}disable(){return super.optOut()}debug(X=!0){super.debug(X),this.featureFlagsPoller?.debug(X)}capture(X){if(typeof X=="string")this._logger.warn("Called capture() with a string as the first argument when an object was expected.");if(X.event==="$exception"&&!X._originatedFromCaptureException)this._logger.warn("Using `posthog.capture('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureException(error)` instead, which attaches required metadata automatically.");this.addPendingPromise(this.prepareEventMessage(X).then(({distinctId:Y,event:G,properties:Q,options:J})=>super.captureStateless(Y,G,Q,{timestamp:J.timestamp,disableGeoip:J.disableGeoip,uuid:J.uuid})).catch((Y)=>{if(Y)console.error(Y)}))}async captureImmediate(X){if(typeof X=="string")this._logger.warn("Called captureImmediate() with a string as the first argument when an object was expected.");if(X.event==="$exception"&&!X._originatedFromCaptureException)this._logger.warn("Capturing a `$exception` event via `posthog.captureImmediate('$exception')` is unreliable because it does not attach required metadata. Use `posthog.captureExceptionImmediate(error)` instead, which attaches this metadata by default.");return this.addPendingPromise(this.prepareEventMessage(X).then(({distinctId:Y,event:G,properties:Q,options:J})=>super.captureStatelessImmediate(Y,G,Q,{timestamp:J.timestamp,disableGeoip:J.disableGeoip,uuid:J.uuid})).catch((Y)=>{if(Y)console.error(Y)}))}identify({distinctId:X,properties:Y={},disableGeoip:G}){let{$set:Q,$set_once:J,$anon_distinct_id:W,...Z}=Y,H={$set:Q||Z,$set_once:J||{},$anon_distinct_id:W??void 0};super.identifyStateless(X,H,{disableGeoip:G})}async identifyImmediate({distinctId:X,properties:Y={},disableGeoip:G}){let{$set:Q,$set_once:J,$anon_distinct_id:W,...Z}=Y,H={$set:Q||Z,$set_once:J||{},$anon_distinct_id:W??void 0};super.identifyStatelessImmediate(X,H,{disableGeoip:G})}alias(X){super.aliasStateless(X.alias,X.distinctId,void 0,{disableGeoip:X.disableGeoip})}async aliasImmediate(X){await super.aliasStatelessImmediate(X.alias,X.distinctId,void 0,{disableGeoip:X.disableGeoip})}isLocalEvaluationReady(){return this.featureFlagsPoller?.isLocalEvaluationReady()??!1}async waitForLocalEvaluationReady(X=h04){if(this.isLocalEvaluationReady())return!0;if(this.featureFlagsPoller===void 0)return!1;return new Promise((Y)=>{let G=setTimeout(()=>{Q(),Y(!1)},X),Q=this._events.on("localEvaluationFlagsLoaded",(J)=>{clearTimeout(G),Q(),Y(J>0)})})}_resolveDistinctId(X,Y){if(typeof X=="string")return{distinctId:X,options:Y};return{distinctId:this.context?.get()?.distinctId,options:X}}async _getFeatureFlagResult(X,Y,G={},Q){let J=G.sendFeatureFlagEvents??!0;if(this._flagOverrides!==void 0&&X in this._flagOverrides){let V=this._flagOverrides[X];if(V===void 0)return;let R=this._payloadOverrides?.[X];return{key:X,enabled:V!==!1,variant:typeof V=="string"?V:void 0,payload:R}}let{groups:W,disableGeoip:Z}=G,{onlyEvaluateLocally:$,personProperties:K,groupProperties:H}=G,U=this.addLocalPersonAndGroupProperties(Y,W,K,H);K=U.allPersonProperties,H=U.allGroupProperties;let B=this.createFeatureFlagEvaluationContext(Y,W,K,H);if($==null)$=this.options.strictLocalEvaluation??!1;let N,z=!1,O,w,E,P,q,M;if(this.featureFlagsPoller!==void 0){await this.featureFlagsPoller?.loadFeatureFlags();let V=this.featureFlagsPoller?.featureFlagsByKey[X];if(V)try{let R=await this.featureFlagsPoller?.computeFlagAndPayloadLocally(V,B,{matchValue:Q});if(R){z=!0;let k=R.value;P=V.id,M="Evaluated locally",N={key:X,enabled:k!==!1,variant:typeof k=="string"?k:void 0,payload:R.payload??void 0}}}catch(R){if(R instanceof Qz||R instanceof d5)this._logger?.info(`${R.name} when computing flag locally: ${X}: ${R.message}`);else throw R}}if(!z&&!$){let V=await super.getFeatureFlagDetailsStateless(B.distinctId,B.groups,B.personProperties,B.groupProperties,Z,[X]);if(V===void 0)E=cX1.UNKNOWN_ERROR;else{O=V.requestId,w=V.evaluatedAt;let R=[];if(V.errorsWhileComputingFlags)R.push(cX1.ERRORS_WHILE_COMPUTING);if(V.quotaLimited?.includes("feature_flags"))R.push(cX1.QUOTA_LIMITED);let k=V.flags[X];if(k===void 0)R.push(cX1.FLAG_MISSING);else{P=k.metadata?.id,q=k.metadata?.version,M=k.reason?.description??k.reason?.code;let _;if(k.metadata?.payload!==void 0)try{_=JSON.parse(k.metadata.payload)}catch{_=k.metadata.payload}N={key:X,enabled:k.enabled,variant:k.variant,payload:_}}if(R.length>0)E=R.join(",")}}if(J){let V=N===void 0?void 0:N.enabled===!1?!1:N.variant??!0,R=`${X}_${V}`;if(!(Y in this.distinctIdHasSentFlagCalls)||!this.distinctIdHasSentFlagCalls[Y].includes(R)){if(Object.keys(this.distinctIdHasSentFlagCalls).length>=this.maxCacheSize)this.distinctIdHasSentFlagCalls={};if(Array.isArray(this.distinctIdHasSentFlagCalls[Y]))this.distinctIdHasSentFlagCalls[Y].push(R);else this.distinctIdHasSentFlagCalls[Y]=[R];let k={$feature_flag:X,$feature_flag_response:V,$feature_flag_id:P,$feature_flag_version:q,$feature_flag_reason:M,locally_evaluated:z,[`$feature/${X}`]:V,$feature_flag_request_id:O,$feature_flag_evaluated_at:z?Date.now():w};if(z&&this.featureFlagsPoller){let _=this.featureFlagsPoller.getFlagDefinitionsLoadedAt();if(_!==void 0)k.$feature_flag_definitions_loaded_at=_}if(E)k.$feature_flag_error=E;this.capture({distinctId:Y,event:"$feature_flag_called",properties:k,groups:W,disableGeoip:Z})}}if(N!==void 0&&this._payloadOverrides!==void 0&&X in this._payloadOverrides)N={...N,payload:this._payloadOverrides[X]};return N}async getFeatureFlag(X,Y,G){let Q=await this._getFeatureFlagResult(X,Y,{...G,sendFeatureFlagEvents:G?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0});if(Q===void 0)return;if(Q.enabled===!1)return!1;return Q.variant??!0}async getFeatureFlagPayload(X,Y,G,Q){if(this._payloadOverrides!==void 0&&X in this._payloadOverrides)return this._payloadOverrides[X];let J=await this._getFeatureFlagResult(X,Y,{...Q,sendFeatureFlagEvents:!1},G);if(J===void 0)return;return J.payload??null}async getFeatureFlagResult(X,Y,G){let{distinctId:Q,options:J}=this._resolveDistinctId(Y,G);if(!Q)return void this._logger.warn("[PostHog] distinctId is required \u2014 pass it explicitly or use withContext()");return this._getFeatureFlagResult(X,Q,{...J,sendFeatureFlagEvents:J?.sendFeatureFlagEvents??this.options.sendFeatureFlagEvent??!0})}async getRemoteConfigPayload(X){if(!this.options.personalApiKey)throw Error("Personal API key is required for remote config payload decryption");let Y=await this._requestRemoteConfigPayload(X);if(!Y)return;let G=await Y.json();if(typeof G=="string")try{return JSON.parse(G)}catch(Q){}return G}async isFeatureEnabled(X,Y,G){let Q=await this.getFeatureFlag(X,Y,G);if(Q===void 0)return;return!!Q||!1}async getAllFlags(X,Y){let{distinctId:G,options:Q}=this._resolveDistinctId(X,Y);if(!G)return this._logger.warn("[PostHog] distinctId is required to get feature flags \u2014 pass it explicitly or use withContext()"),{};return(await this.getAllFlagsAndPayloads(G,Q)).featureFlags||{}}async getAllFlagsAndPayloads(X,Y){let{distinctId:G,options:Q}=this._resolveDistinctId(X,Y);if(!G)return this._logger.warn("[PostHog] distinctId is required to get feature flags and payloads \u2014 pass it explicitly or use withContext()"),{featureFlags:{},featureFlagPayloads:{}};let{groups:J,disableGeoip:W,flagKeys:Z}=Q||{},{onlyEvaluateLocally:$,personProperties:K,groupProperties:H}=Q||{},U=this.addLocalPersonAndGroupProperties(G,J,K,H);K=U.allPersonProperties,H=U.allGroupProperties;let B=this.createFeatureFlagEvaluationContext(G,J,K,H);if($==null)$=this.options.strictLocalEvaluation??!1;let N=await this.featureFlagsPoller?.getAllFlagsAndPayloads(B,Z),z={},O={},w=!0;if(N)z=N.response,O=N.payloads,w=N.fallbackToFlags;if(w&&!$){let E=await super.getFeatureFlagsAndPayloadsStateless(B.distinctId,B.groups,B.personProperties,B.groupProperties,W,Z);z={...z,...E.flags||{}},O={...O,...E.payloads||{}}}if(this._flagOverrides!==void 0)z={...z,...this._flagOverrides};if(this._payloadOverrides!==void 0)O={...O,...this._payloadOverrides};return{featureFlags:z,featureFlagPayloads:O}}groupIdentify({groupType:X,groupKey:Y,properties:G,distinctId:Q,disableGeoip:J}){super.groupIdentifyStateless(X,Y,G,{disableGeoip:J},Q)}async reloadFeatureFlags(){await this.featureFlagsPoller?.loadFeatureFlags(!0)}overrideFeatureFlags(X){let Y=(G)=>Object.fromEntries(G.map((Q)=>[Q,!0]));if(X===!1){this._flagOverrides=void 0,this._payloadOverrides=void 0;return}if(Array.isArray(X)){this._flagOverrides=Y(X);return}if(this._isFeatureFlagOverrideOptions(X)){if("flags"in X){if(X.flags===!1)this._flagOverrides=void 0;else if(Array.isArray(X.flags))this._flagOverrides=Y(X.flags);else if(X.flags!==void 0)this._flagOverrides={...X.flags}}if("payloads"in X){if(X.payloads===!1)this._payloadOverrides=void 0;else if(X.payloads!==void 0)this._payloadOverrides={...X.payloads}}return}this._flagOverrides={...X}}_isFeatureFlagOverrideOptions(X){if(typeof X!="object"||X===null||Array.isArray(X))return!1;let Y=X;if("flags"in Y){let G=Y.flags;if(G===!1||Array.isArray(G)||typeof G=="object"&&G!==null)return!0}if("payloads"in Y){let G=Y.payloads;if(G===!1||typeof G=="object"&&G!==null)return!0}return!1}withContext(X,Y,G){if(!this.context)return Y();return this.context.run(X,Y,G)}getContext(){return this.context?.get()}enterContext(X,Y){this.context?.enter(X,Y)}async _shutdown(X){let Y=this._consumeWaitUntilCycle();await this.featureFlagsPoller?.stopPoller(X),this.errorTracking.shutdown();try{return await super._shutdown(X)}finally{Y?.()}}async _requestRemoteConfigPayload(X){if(!this.options.personalApiKey)return;let Y=`${this.host}/api/projects/@current/feature_flags/${X}/remote_config?token=${encodeURIComponent(this.apiKey)}`,G={method:"GET",headers:{...this.getCustomHeaders(),"Content-Type":"application/json",Authorization:`Bearer ${this.options.personalApiKey}`}},Q=null;if(this.options.requestTimeout&&typeof this.options.requestTimeout=="number"){let J=new AbortController;Q=Hw(()=>{J.abort()},this.options.requestTimeout),G.signal=J.signal}try{return await this.fetch(Y,G)}catch(J){this._events.emit("error",J);return}finally{if(Q)clearTimeout(Q)}}extractPropertiesFromEvent(X,Y){if(!X)return{personProperties:{},groupProperties:{}};let G={},Q={};for(let[J,W]of Object.entries(X))if(oe6(W)&&Y&&J in Y){let Z={};for(let[$,K]of Object.entries(W))Z[String($)]=String(K);Q[String(J)]=Z}else G[String(J)]=String(W);return{personProperties:G,groupProperties:Q}}async getFeatureFlagsForEvent(X,Y,G,Q){let J=Q?.personProperties||{},W=Q?.groupProperties||{},Z=Q?.flagKeys;if(Q?.onlyEvaluateLocally??this.options.strictLocalEvaluation??!1)if(!((this.featureFlagsPoller?.featureFlags?.length||0)>0))return{};else{let K={};for(let[H,U]of Object.entries(Y||{}))K[H]=String(U);return await this.getAllFlags(X,{groups:K,personProperties:J,groupProperties:W,disableGeoip:G,onlyEvaluateLocally:!0,flagKeys:Z})}if((this.featureFlagsPoller?.featureFlags?.length||0)>0){let K={};for(let[H,U]of Object.entries(Y||{}))K[H]=String(U);return await this.getAllFlags(X,{groups:K,personProperties:J,groupProperties:W,disableGeoip:G,onlyEvaluateLocally:!0,flagKeys:Z})}return(await super.getFeatureFlagsStateless(X,Y,J,W,G)).flags}addLocalPersonAndGroupProperties(X,Y,G,Q){let J={distinct_id:X,...G||{}},W={};if(Y)for(let Z of Object.keys(Y))W[Z]={$group_key:Y[Z],...Q?.[Z]||{}};return{allPersonProperties:J,allGroupProperties:W}}createFeatureFlagEvaluationContext(X,Y,G,Q){return{distinctId:X,groups:Y||{},personProperties:G||{},groupProperties:Q||{},evaluationCache:{}}}captureException(X,Y,G,Q){if(!DH.isPreviouslyCapturedError(X)){let J=Error("PostHog syntheticException");this.addPendingPromise(DH.buildEventMessage(X,{syntheticException:J},Y,G).then((W)=>this.capture({...W,uuid:Q})))}}async captureExceptionImmediate(X,Y,G){if(!DH.isPreviouslyCapturedError(X)){let Q=Error("PostHog syntheticException");return this.addPendingPromise(DH.buildEventMessage(X,{syntheticException:Q},Y,G).then((J)=>this.captureImmediate(J)))}}async prepareEventMessage(X){let{distinctId:Y,event:G,properties:Q,groups:J,sendFeatureFlags:W,timestamp:Z,disableGeoip:$,uuid:K}=X,H=this.context?.get(),U=Y||H?.distinctId,B={...this.props,...H?.properties||{},...Q||{}};if(!U)U=Tq(),B.$process_person_profile=!1;if(H?.sessionId&&!B.$session_id)B.$session_id=H.sessionId;let N=this._runBeforeSend({distinctId:U,event:G,properties:B,groups:J,sendFeatureFlags:W,timestamp:Z,disableGeoip:$,uuid:K});if(!N)return Promise.reject(null);let z=await Promise.resolve().then(async()=>{if(W){let O=typeof W=="object"?W:void 0;return await this.getFeatureFlagsForEvent(N.distinctId,J,$,O)}return N.event,{}}).then((O)=>{let w={};if(O)for(let[P,q]of Object.entries(O))w[`$feature/${P}`]=q;let E=Object.keys(O||{}).filter((P)=>O?.[P]!==!1).sort();if(E.length>0)w.$active_feature_flags=E;return w}).catch(()=>({})).then((O)=>{return{...O,...N.properties||{},$groups:N.groups||J}});if(N.event==="$pageview"&&this.options.__preview_capture_bot_pageviews&&typeof z.$raw_user_agent=="string"){if(pe6(z.$raw_user_agent,this.options.custom_blocked_useragents||[]))N.event="$bot_pageview",z.$browser_type="bot"}return{distinctId:N.distinctId,event:N.event,properties:z,options:{timestamp:N.timestamp,disableGeoip:N.disableGeoip,uuid:N.uuid}}}_runBeforeSend(X){let Y=this.options.before_send;if(!Y)return X;let G=Array.isArray(Y)?Y:[Y],Q=X;for(let J of G){if(Q=J(Q),!Q)return this._logger.info(`Event '${X.event}' was rejected in beforeSend function`),null;if(!Q.properties||Object.keys(Q.properties).length===0){let W=`Event '${Q.event}' has no properties after beforeSend function, this is likely an error.`;this._logger.warn(W)}}return Q}}});import{AsyncLocalStorage as Va5}from"async_hooks";class iN0{constructor(){this.storage=new Va5}get(){return this.storage.getStore()}run(X,Y,G){return this.storage.run(this.resolve(X,G),Y)}enter(X,Y){this.storage.enterWith(this.resolve(X,Y))}resolve(X,Y){if(Y?.fresh===!0)return X;let G=this.get()||{};return{distinctId:X.distinctId??G.distinctId,sessionId:X.sessionId??G.sessionId,properties:{...G.properties||{},...X.properties||{}}}}}var u04=()=>{};function ja5(X,{organization:Y,projectId:G,prefix:Q,severityAllowList:J=["error"],sendExceptionsToPostHog:W=!0}={}){return(Z)=>{if(!(J==="*"||J.includes(Z.level)))return Z;if(!Z.tags)Z.tags={};let K=Z.tags[l04.POSTHOG_ID_TAG];if(K===void 0)return Z;let H=X.options.host??"https://us.i.posthog.com",U=new URL(`/project/${X.apiKey}/person/${K}`,H).toString();Z.tags["PostHog Person URL"]=U;let B=Z.exception?.values||[],N=B.map((O)=>({...O,stacktrace:O.stacktrace?{...O.stacktrace,type:"raw",frames:(O.stacktrace.frames||[]).map((w)=>({...w,platform:"node:javascript"}))}:void 0})),z={$exception_message:B[0]?.value||Z.message,$exception_type:B[0]?.type,$exception_level:Z.level,$exception_list:N,$sentry_event_id:Z.event_id,$sentry_exception:Z.exception,$sentry_exception_message:B[0]?.value||Z.message,$sentry_exception_type:B[0]?.type,$sentry_tags:Z.tags};if(Y&&G)z.$sentry_url=(Q||"https://sentry.io/organizations/")+Y+"/issues/?project="+G+"&query="+Z.event_id;if(W)X.capture({event:"$exception",distinctId:K,properties:z});return Z}}var l04;var m04=D(()=>{l04=class l04{static#X=this.POSTHOG_ID_TAG="posthog_distinct_id";constructor(X,Y,G,Q,J){this.name="posthog-node",this.name="posthog-node",this.setupOnce=function(W,Z){let $=Z()?.getClient()?.getDsn()?.projectId;W(ja5(X,{organization:Y,projectId:$,prefix:G,severityAllowList:Q,sendExceptionsToPostHog:J??!0}))}}}});var d04=D(()=>{KT1()});var c04=D(()=>{_j();m04();d04();lN0()});var pN0;var i04=D(()=>{me6();P04();A04();KT1();g04();_j();u04();c04();DH.errorPropertiesBuilder=new qW.ErrorPropertiesBuilder([new qW.EventCoercer,new qW.ErrorCoercer,new qW.ObjectCoercer,new qW.StringCoercer,new qW.PrimitiveCoercer],qW.createStackParser("node:javascript",qW.nodeStackLineParser),[le6(),w04,q04()]);pN0=class pN0 extends cN0{getLibraryId(){return"posthog-node"}initializeContext(){return new iN0}}});function Ma5(){return{capture:()=>{},identify:()=>{},captureException:()=>{},groupIdentify:()=>{},shutdown:async()=>{}}}var nN0,p04,j4;var RX=D(()=>{i04();nN0=process.env.POSTHOG_KEY,p04=process.env.POSTHOG_HOST;j4=nN0?new pN0(nN0,{...p04?{host:p04}:{},enableExceptionAutocapture:!0,flushAt:1,flushInterval:0}):Ma5();if(nN0){let X=()=>{j4.shutdown().catch(()=>{})};process.on("SIGTERM",X),process.on("SIGINT",X)}});function u$(){let X=v6();if(X.baseUrl)return X.baseUrl;return`http://localhost:${X.port??3000}`}function iX1(){return`http://localhost:${v6().port??3000}`}var Fw=D(()=>{m9()});var n04=D(()=>{bV()});function a04(X){return{organizationId:X.organization_id,domain:X.domain,autoJoinEnabled:X.auto_join_enabled,createdAt:X.created_at,updatedAt:X.updated_at}}class Uw{db;constructor(X){this.db=X}async getByDomain(X){let Y=await this.db.selectFrom("organization_domains").selectAll().where("domain","=",X.toLowerCase()).executeTakeFirst();return Y?a04(Y):null}async getByOrganizationId(X){let Y=await this.db.selectFrom("organization_domains").selectAll().where("organization_id","=",X).executeTakeFirst();return Y?a04(Y):null}async setDomain(X,Y,G=!1){let Q=new Date().toISOString(),J=Y.toLowerCase();try{await this.db.insertInto("organization_domains").values({organization_id:X,domain:J,auto_join_enabled:G,created_at:Q,updated_at:Q}).onConflict((Z)=>Z.column("organization_id").doUpdateSet({domain:J,auto_join_enabled:G,updated_at:Q})).execute()}catch(Z){if(Z.code==="23505")throw Error(`Domain "${J}" is already claimed by another organization.`);throw Z}let W=await this.getByOrganizationId(X);if(!W)throw Error("Failed to set domain");return W}async updateAutoJoin(X,Y){let G=new Date().toISOString();await this.db.updateTable("organization_domains").set({auto_join_enabled:Y,updated_at:G}).where("organization_id","=",X).execute();let Q=await this.getByOrganizationId(X);if(!Q)throw Error("No domain found for organization");return Q}async clearDomain(X){await this.db.deleteFrom("organization_domains").where("organization_id","=",X).execute()}}class aN0{apiKey;constructor(X){this.apiKey=X}async sendEmail({to:X,from:Y,subject:G,html:Q}){let J=await fetch("https://api.resend.com/emails",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({to:X,from:Y,subject:G,html:Q})});if(!J.ok)throw Error(`Failed to send email: ${J.statusText}`)}}class tN0{apiKey;constructor(X){this.apiKey=X}async sendEmail({to:X,from:Y,subject:G,html:Q}){let J=await fetch("https://api.sendgrid.com/v3/mail/send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({personalizations:[{to:[{email:X}]}],from:{email:Y},subject:G,content:[{type:"text/html",value:Q}]})});if(!J.ok){let W=await J.text();throw Error(`Failed to send email via SendGrid: ${J.statusText} - ${W}`)}}}function fj(X){let Y=Ca5[X.provider];if(!Y)throw Error(`Unknown email provider: ${X.provider}`);return Y(X)}function bj(X,Y){return X.find((G)=>G.id===Y)}var Ra5=(X)=>{let Y=new aN0(X.config.apiKey);return async({to:G,subject:Q,html:J})=>{await Y.sendEmail({to:G,from:X.config.fromEmail,subject:Q,html:J})}},Sa5=(X)=>{let Y=new tN0(X.config.apiKey);return async({to:G,subject:Q,html:J})=>{await Y.sendEmail({to:G,from:X.config.fromEmail,subject:Q,html:J})}},Ca5;var HT1=D(()=>{Ca5={resend:Ra5,sendgrid:Sa5}});function yj({preheader:X="",heading:Y,subheading:G,body:Q,footnote:J}){return`<!DOCTYPE html>
1641
1641
  <html lang="en">
1642
1642
  <head>
@@ -4387,6 +4387,23 @@ function makeEventsHandler(deps) {
4387
4387
  };
4388
4388
  }
4389
4389
 
4390
+ // daemon/activity.ts
4391
+ var lastActivityAt = Date.now();
4392
+ function bumpActivity(now = Date.now()) {
4393
+ lastActivityAt = now;
4394
+ }
4395
+ function getIdleStatus(now = Date.now()) {
4396
+ return {
4397
+ lastActivityAt: new Date(lastActivityAt).toISOString(),
4398
+ idleMs: Math.max(0, now - lastActivityAt)
4399
+ };
4400
+ }
4401
+
4402
+ // daemon/routes/idle.ts
4403
+ function makeIdleHandler() {
4404
+ return () => jsonResponse(getIdleStatus());
4405
+ }
4406
+
4390
4407
  // daemon/proxy.ts
4391
4408
  function makeProxyHandler({ broadcaster, getDevPort }) {
4392
4409
  function log(...args) {
@@ -4461,7 +4478,7 @@ function makeProxyHandler({ broadcaster, getDevPort }) {
4461
4478
 
4462
4479
  // daemon/ws-proxy.ts
4463
4480
  var MAX_PENDING_FRAMES = 256;
4464
- function makeWsUpgrader(getDevPort) {
4481
+ function makeWsUpgrader(getDevPort, opts = {}) {
4465
4482
  return {
4466
4483
  upgradeData(req) {
4467
4484
  const url = new URL(req.url);
@@ -4499,6 +4516,7 @@ function makeWsUpgrader(getDevPort) {
4499
4516
  });
4500
4517
  },
4501
4518
  message(ws, message) {
4519
+ opts.onClientMessage?.();
4502
4520
  const upstream = ws.data.upstream;
4503
4521
  const frame = typeof message === "string" ? message : message.buffer;
4504
4522
  if (upstream && upstream.readyState === WebSocket.OPEN) {
@@ -4912,8 +4930,9 @@ var eventsH = makeEventsHandler({
4912
4930
  getActiveProcesses: () => processManager.activeNames(),
4913
4931
  getLastBranchStatus: () => branchStatus.getLast()
4914
4932
  });
4933
+ var idleH = makeIdleHandler();
4915
4934
  var proxyH = makeProxyHandler({ broadcaster, getDevPort });
4916
- var wsProxy = makeWsUpgrader(getDevPort);
4935
+ var wsProxy = makeWsUpgrader(getDevPort, { onClientMessage: bumpActivity });
4917
4936
  Bun.serve({
4918
4937
  port: config.proxyPort,
4919
4938
  hostname: "0.0.0.0",
@@ -4921,6 +4940,9 @@ Bun.serve({
4921
4940
  async fetch(req, server) {
4922
4941
  const url = new URL(req.url);
4923
4942
  const p = url.pathname;
4943
+ if (p !== "/health" && p !== "/_decopilot_vm/idle") {
4944
+ bumpActivity();
4945
+ }
4924
4946
  if (req.headers.get("upgrade")?.toLowerCase() === "websocket" && !p.startsWith("/_decopilot_vm/")) {
4925
4947
  const ok = server.upgrade(req, { data: wsProxy.upgradeData(req) });
4926
4948
  if (ok)
@@ -4929,6 +4951,8 @@ Bun.serve({
4929
4951
  }
4930
4952
  if (p === "/health" && req.method === "GET")
4931
4953
  return healthH();
4954
+ if (req.method === "GET" && p === "/_decopilot_vm/idle")
4955
+ return idleH();
4932
4956
  if (req.method === "GET" && p === "/_decopilot_vm/events")
4933
4957
  return eventsH();
4934
4958
  if (req.method === "GET" && p === "/_decopilot_vm/scripts")
@@ -5027,7 +5051,7 @@ mkdir -p /app && chown deco:deco /app
5027
5051
  `);let Q=Y.pax;if(Q)for(let J in Q)G+=fb0(" "+J+"="+Q[J]+`
5028
5052
  `);return n5.from(G)};YG7.decodePax=function(Y){let G={};while(Y.length){let Q=0;while(Q<Y.length&&Y[Q]!==32)Q++;let J=parseInt(n5.toString(Y.subarray(0,Q)),10);if(!J)return G;let W=n5.toString(Y.subarray(Q+1,J-1)),Z=W.indexOf("=");if(Z===-1)return G;G[W.slice(0,Z)]=W.slice(Z+1),Y=Y.subarray(J)}return G};YG7.encode=function(Y){let G=n5.alloc(512),Q=Y.name,J="";if(Y.typeflag===5&&Q[Q.length-1]!=="/")Q+="/";if(n5.byteLength(Q)!==Q.length)return null;while(n5.byteLength(Q)>100){let W=Q.indexOf("/");if(W===-1)return null;J+=J?"/"+Q.slice(0,W):Q.slice(0,W),Q=Q.slice(W+1)}if(n5.byteLength(Q)>100||n5.byteLength(J)>155)return null;if(Y.linkname&&n5.byteLength(Y.linkname)>100)return null;if(n5.write(G,Q),n5.write(G,AT(Y.mode&4095,6),100),n5.write(G,AT(Y.uid,6),108),n5.write(G,AT(Y.gid,6),116),eY7(Y.size,G,124),n5.write(G,AT(Y.mtime.getTime()/1000|0,11),136),G[156]=48+oY7(Y.type),Y.linkname)n5.write(G,Y.linkname,157);if(n5.copy(UQ8,G,257),n5.copy(cY7,G,263),Y.uname)n5.write(G,Y.uname,265);if(Y.gname)n5.write(G,Y.gname,297);if(n5.write(G,AT(Y.devmajor||0,6),329),n5.write(G,AT(Y.devminor||0,6),337),J)n5.write(G,J,345);return n5.write(G,AT(NQ8(G),6),148),G};YG7.decode=function(Y,G,Q){let J=Y[156]===0?0:Y[156]-48,W=bs(Y,0,100,G),Z=qT(Y,100,8),$=qT(Y,108,8),K=qT(Y,116,8),H=qT(Y,124,12),U=qT(Y,136,12),B=rY7(J),N=Y[157]===0?null:bs(Y,157,100,G),z=bs(Y,265,32),O=bs(Y,297,32),w=qT(Y,329,8),E=qT(Y,337,8),P=NQ8(Y);if(P===256)return null;if(P!==qT(Y,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(nY7(Y)){if(Y[345])W=bs(Y,345,155,G)+"/"+W}else if(aY7(Y));else if(!Q)throw Error("Invalid tar header: unknown format.");if(J===0&&W&&W[W.length-1]==="/")J=5;return{name:W,mode:Z,uid:$,gid:K,size:H,mtime:new Date(1000*U),type:B,linkname:N,uname:z,gname:O,devmajor:w,devminor:E,pax:null}};function nY7(X){return n5.equals(UQ8,X.subarray(257,263))}function aY7(X){return n5.equals(iY7,X.subarray(257,263))&&n5.equals(pY7,X.subarray(263,265))}function tY7(X,Y,G){if(typeof X!=="number")return G;if(X=~~X,X>=Y)return Y;if(X>=0)return X;if(X+=Y,X>=0)return X;return 0}function rY7(X){switch(X){case 0:return"file";case 1:return"link";case 2:return"symlink";case 3:return"character-device";case 4:return"block-device";case 5:return"directory";case 6:return"fifo";case 7:return"contiguous-file";case 72:return"pax-header";case 55:return"pax-global-header";case 27:return"gnu-long-link-path";case 28:case 30:return"gnu-long-path"}return null}function oY7(X){switch(X){case"file":return 0;case"link":return 1;case"symlink":return 2;case"character-device":return 3;case"block-device":return 4;case"directory":return 5;case"fifo":return 6;case"contiguous-file":return 7;case"pax-header":return 72}return 0}function BQ8(X,Y,G,Q){for(;G<Q;G++)if(X[G]===Y)return G;return Q}function NQ8(X){let Y=256;for(let G=0;G<148;G++)Y+=X[G];for(let G=156;G<512;G++)Y+=X[G];return Y}function AT(X,Y){if(X=X.toString(8),X.length>Y)return"7777777777777777777".slice(0,Y)+" ";return"0000000000000000000".slice(0,Y-X.length)+X+" "}function sY7(X,Y,G){Y[G]=128;for(let Q=11;Q>0;Q--)Y[G+Q]=X&255,X=Math.floor(X/256)}function eY7(X,Y,G){if(X.toString(8).length>11)sY7(X,Y,G);else n5.write(Y,AT(X,11),G)}function XG7(X){let Y;if(X[0]===128)Y=!0;else if(X[0]===255)Y=!1;else return null;let G=[],Q;for(Q=X.length-1;Q>0;Q--){let Z=X[Q];if(Y)G.push(Z);else G.push(255-Z)}let J=0,W=G.length;for(Q=0;Q<W;Q++)J+=G[Q]*Math.pow(256,Q);return Y?J:-1*J}function qT(X,Y,G){if(X=X.subarray(Y,Y+G),Y=0,X[Y]&128)return XG7(X);else{while(Y<X.length&&X[Y]===32)Y++;let Q=tY7(BQ8(X,32,Y,X.length),X.length,X.length);while(Y<Q&&X[Y]===0)Y++;if(Q===Y)return 0;return parseInt(n5.toString(X.subarray(Y,Q)),8)}}function bs(X,Y,G,Q){return n5.toString(X.subarray(Y,BQ8(X,0,Y,Y+G)),Q)}function fb0(X){let Y=n5.byteLength(X),G=Math.floor(Math.log(Y)/Math.log(10))+1;if(Y+G>=Math.pow(10,G))G++;return Y+G+X}});var qQ8=C((yrG,PQ8)=>{var{Writable:$G7,Readable:KG7,getStreamError:zQ8}=_b0(),HG7=Mb0(),OQ8=fs(),ys=bb0(),FG7=OQ8.alloc(0);class DQ8{constructor(){this.buffered=0,this.shifted=0,this.queue=new HG7,this._offset=0}push(X){this.buffered+=X.byteLength,this.queue.push(X)}shiftFirst(X){return this._buffered===0?null:this._next(X)}shift(X){if(X>this.buffered)return null;if(X===0)return FG7;let Y=this._next(X);if(X===Y.byteLength)return Y;let G=[Y];while((X-=Y.byteLength)>0)Y=this._next(X),G.push(Y);return OQ8.concat(G)}_next(X){let Y=this.queue.peek(),G=Y.byteLength-this._offset;if(X>=G){let Q=this._offset?Y.subarray(this._offset,Y.byteLength):Y;return this.queue.shift(),this._offset=0,this.buffered-=G,this.shifted+=G,Q}return this.buffered-=X,this.shifted+=X,Y.subarray(this._offset,this._offset+=X)}}class wQ8 extends KG7{constructor(X,Y,G){super();this.header=Y,this.offset=G,this._parent=X}_read(X){if(this.header.size===0)this.push(null);if(this._parent._stream===this)this._parent._update();X(null)}_predestroy(){this._parent.destroy(zQ8(this))}_detach(){if(this._parent._stream===this)this._parent._stream=null,this._parent._missing=EQ8(this.header.size),this._parent._update()}_destroy(X){this._detach(),X(null)}}class LQ8 extends $G7{constructor(X){super(X);if(!X)X={};this._buffer=new DQ8,this._offset=0,this._header=null,this._stream=null,this._missing=0,this._longHeader=!1,this._callback=yb0,this._locked=!1,this._finished=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null,this._filenameEncoding=X.filenameEncoding||"utf-8",this._allowUnknownFormat=!!X.allowUnknownFormat,this._unlockBound=this._unlock.bind(this)}_unlock(X){if(this._locked=!1,X){this.destroy(X),this._continueWrite(X);return}this._update()}_consumeHeader(){if(this._locked)return!1;this._offset=this._buffer.shifted;try{this._header=ys.decode(this._buffer.shift(512),this._filenameEncoding,this._allowUnknownFormat)}catch(X){return this._continueWrite(X),!1}if(!this._header)return!0;switch(this._header.type){case"gnu-long-path":case"gnu-long-link-path":case"pax-global-header":case"pax-header":return this._longHeader=!0,this._missing=this._header.size,!0}if(this._locked=!0,this._applyLongHeaders(),this._header.size===0||this._header.type==="directory")return this.emit("entry",this._header,this._createStream(),this._unlockBound),!0;return this._stream=this._createStream(),this._missing=this._header.size,this.emit("entry",this._header,this._stream,this._unlockBound),!0}_applyLongHeaders(){if(this._gnuLongPath)this._header.name=this._gnuLongPath,this._gnuLongPath=null;if(this._gnuLongLinkPath)this._header.linkname=this._gnuLongLinkPath,this._gnuLongLinkPath=null;if(this._pax){if(this._pax.path)this._header.name=this._pax.path;if(this._pax.linkpath)this._header.linkname=this._pax.linkpath;if(this._pax.size)this._header.size=parseInt(this._pax.size,10);this._header.pax=this._pax,this._pax=null}}_decodeLongHeader(X){switch(this._header.type){case"gnu-long-path":this._gnuLongPath=ys.decodeLongPath(X,this._filenameEncoding);break;case"gnu-long-link-path":this._gnuLongLinkPath=ys.decodeLongPath(X,this._filenameEncoding);break;case"pax-global-header":this._paxGlobal=ys.decodePax(X);break;case"pax-header":this._pax=this._paxGlobal===null?ys.decodePax(X):Object.assign({},this._paxGlobal,ys.decodePax(X));break}}_consumeLongHeader(){this._longHeader=!1,this._missing=EQ8(this._header.size);let X=this._buffer.shift(this._header.size);try{this._decodeLongHeader(X)}catch(Y){return this._continueWrite(Y),!1}return!0}_consumeStream(){let X=this._buffer.shiftFirst(this._missing);if(X===null)return!1;this._missing-=X.byteLength;let Y=this._stream.push(X);if(this._missing===0){if(this._stream.push(null),Y)this._stream._detach();return Y&&this._locked===!1}return Y}_createStream(){return new wQ8(this,this._header,this._offset)}_update(){while(this._buffer.buffered>0&&!this.destroying){if(this._missing>0){if(this._stream!==null){if(this._consumeStream()===!1)return;continue}if(this._longHeader===!0){if(this._missing>this._buffer.buffered)break;if(this._consumeLongHeader()===!1)return!1;continue}let X=this._buffer.shiftFirst(this._missing);if(X!==null)this._missing-=X.byteLength;continue}if(this._buffer.buffered<512)break;if(this._stream!==null||this._consumeHeader()===!1)return}this._continueWrite(null)}_continueWrite(X){let Y=this._callback;this._callback=yb0,Y(X)}_write(X,Y){this._callback=Y,this._buffer.push(X),this._update()}_final(X){this._finished=this._missing===0&&this._buffer.buffered===0,X(this._finished?null:Error("Unexpected end of data"))}_predestroy(){this._continueWrite(null)}_destroy(X){if(this._stream)this._stream.destroy(zQ8(this));X(null)}[Symbol.asyncIterator](){let X=null,Y=null,G=null,Q=null,J=null,W=this;return this.on("entry",K),this.on("error",(B)=>{X=B}),this.on("close",H),{[Symbol.asyncIterator](){return this},next(){return new Promise($)},return(){return U(null)},throw(B){return U(B)}};function Z(B){if(!J)return;let N=J;J=null,N(B)}function $(B,N){if(X)return N(X);if(Q){B({value:Q,done:!1}),Q=null;return}if(Y=B,G=N,Z(null),W._finished&&Y)Y({value:void 0,done:!0}),Y=G=null}function K(B,N,z){if(J=z,N.on("error",yb0),Y)Y({value:N,done:!1}),Y=G=null;else Q=N}function H(){if(Z(X),!Y)return;if(X)G(X);else Y({value:void 0,done:!0});Y=G=null}function U(B){return W.destroy(B),Z(B),new Promise((N,z)=>{if(W.destroyed)return N({value:void 0,done:!0});W.once("close",function(){if(B)z(B);else N({value:void 0,done:!0})})})}}}PQ8.exports=function(Y){return new LQ8(Y)};function yb0(){}function EQ8(X){return X&=511,X&&512-X}});var TQ8=C((xrG,xb0)=>{var AQ8={S_IFMT:61440,S_IFDIR:16384,S_IFCHR:8192,S_IFBLK:24576,S_IFIFO:4096,S_IFLNK:40960};try{xb0.exports=I1("fs").constants||AQ8}catch{xb0.exports=AQ8}});var CQ8=C((hrG,SQ8)=>{var{Readable:UG7,Writable:BG7,getStreamError:IQ8}=_b0(),km=fs(),xs=TQ8(),hc1=bb0(),VQ8=km.alloc(1024);class jQ8 extends BG7{constructor(X,Y,G){super({mapWritable:zG7,eagerOpen:!0});if(this.written=0,this.header=Y,this._callback=G,this._linkname=null,this._isLinkname=Y.type==="symlink"&&!Y.linkname,this._isVoid=Y.type!=="file"&&Y.type!=="contiguous-file",this._finished=!1,this._pack=X,this._openCallback=null,this._pack._stream===null)this._pack._stream=this;else this._pack._pending.push(this)}_open(X){if(this._openCallback=X,this._pack._stream===this)this._continueOpen()}_continuePack(X){if(this._callback===null)return;let Y=this._callback;this._callback=null,Y(X)}_continueOpen(){if(this._pack._stream===null)this._pack._stream=this;let X=this._openCallback;if(this._openCallback=null,X===null)return;if(this._pack.destroying)return X(Error("pack stream destroyed"));if(this._pack._finalized)return X(Error("pack stream is already finalized"));if(this._pack._stream=this,!this._isLinkname)this._pack._encode(this.header);if(this._isVoid)this._finish(),this._continuePack(null);X(null)}_write(X,Y){if(this._isLinkname)return this._linkname=this._linkname?km.concat([this._linkname,X]):X,Y(null);if(this._isVoid){if(X.byteLength>0)return Y(Error("No body allowed for this entry"));return Y()}if(this.written+=X.byteLength,this._pack.push(X))return Y();this._pack._drain=Y}_finish(){if(this._finished)return;if(this._finished=!0,this._isLinkname)this.header.linkname=this._linkname?km.toString(this._linkname,"utf-8"):"",this._pack._encode(this.header);RQ8(this._pack,this.header.size),this._pack._done(this)}_final(X){if(this.written!==this.header.size)return X(Error("Size mismatch"));this._finish(),X(null)}_getError(){return IQ8(this)||Error("tar entry destroyed")}_predestroy(){this._pack.destroy(this._getError())}_destroy(X){this._pack._done(this),this._continuePack(this._finished?null:this._getError()),X()}}class MQ8 extends UG7{constructor(X){super(X);this._drain=hb0,this._finalized=!1,this._finalizing=!1,this._pending=[],this._stream=null}entry(X,Y,G){if(this._finalized||this.destroying)throw Error("already finalized or destroyed");if(typeof Y==="function")G=Y,Y=null;if(!G)G=hb0;if(!X.size||X.type==="symlink")X.size=0;if(!X.type)X.type=NG7(X.mode);if(!X.mode)X.mode=X.type==="directory"?493:420;if(!X.uid)X.uid=0;if(!X.gid)X.gid=0;if(!X.mtime)X.mtime=new Date;if(typeof Y==="string")Y=km.from(Y);let Q=new jQ8(this,X,G);if(km.isBuffer(Y))return X.size=Y.byteLength,Q.write(Y),Q.end(),Q;if(Q._isVoid)return Q;return Q}finalize(){if(this._stream||this._pending.length>0){this._finalizing=!0;return}if(this._finalized)return;this._finalized=!0,this.push(VQ8),this.push(null)}_done(X){if(X!==this._stream)return;if(this._stream=null,this._finalizing)this.finalize();if(this._pending.length)this._pending.shift()._continueOpen()}_encode(X){if(!X.pax){let Y=hc1.encode(X);if(Y){this.push(Y);return}}this._encodePax(X)}_encodePax(X){let Y=hc1.encodePax({name:X.name,linkname:X.linkname,pax:X.pax}),G={name:"PaxHeader",mode:X.mode,uid:X.uid,gid:X.gid,size:Y.byteLength,mtime:X.mtime,type:"pax-header",linkname:X.linkname&&"PaxHeader",uname:X.uname,gname:X.gname,devmajor:X.devmajor,devminor:X.devminor};this.push(hc1.encode(G)),this.push(Y),RQ8(this,Y.byteLength),G.size=X.size,G.type=X.type,this.push(hc1.encode(G))}_doDrain(){let X=this._drain;this._drain=hb0,X()}_predestroy(){let X=IQ8(this);if(this._stream)this._stream.destroy(X);while(this._pending.length){let Y=this._pending.shift();Y.destroy(X),Y._continueOpen()}this._doDrain()}_read(X){this._doDrain(),X()}}SQ8.exports=function(Y){return new MQ8(Y)};function NG7(X){switch(X&xs.S_IFMT){case xs.S_IFBLK:return"block-device";case xs.S_IFCHR:return"character-device";case xs.S_IFDIR:return"directory";case xs.S_IFIFO:return"fifo";case xs.S_IFLNK:return"symlink"}return"file"}function hb0(){}function RQ8(X,Y){if(Y&=511,Y)X.push(VQ8.subarray(0,512-Y))}function zG7(X){return km.isBuffer(X)?X:km.from(X)}});var kQ8=C((OG7)=>{OG7.extract=qQ8();OG7.pack=CQ8()});var fQ8=C((urG,_Q8)=>{_Q8.exports=vQ8;function vQ8(X,Y){if(X&&Y)return vQ8(X)(Y);if(typeof X!=="function")throw TypeError("need wrapper function");return Object.keys(X).forEach(function(Q){G[Q]=X[Q]}),G;function G(){var Q=Array(arguments.length);for(var J=0;J<Q.length;J++)Q[J]=arguments[J];var W=X.apply(this,Q),Z=Q[Q.length-1];if(typeof W==="function"&&W!==Z)Object.keys(Z).forEach(function($){W[$]=Z[$]});return W}}});var ub0=C((lrG,gb0)=>{var bQ8=fQ8();gb0.exports=bQ8(gc1);gb0.exports.strict=bQ8(yQ8);gc1.proto=gc1(function(){Object.defineProperty(Function.prototype,"once",{value:function(){return gc1(this)},configurable:!0}),Object.defineProperty(Function.prototype,"onceStrict",{value:function(){return yQ8(this)},configurable:!0})});function gc1(X){var Y=function(){if(Y.called)return Y.value;return Y.called=!0,Y.value=X.apply(this,arguments)};return Y.called=!1,Y}function yQ8(X){var Y=function(){if(Y.called)throw Error(Y.onceError);return Y.called=!0,Y.value=X.apply(this,arguments)},G=X.name||"Function wrapped with `once`";return Y.onceError=G+" shouldn't be called more than once",Y.called=!1,Y}});var gQ8=C((mrG,hQ8)=>{var LG7=ub0(),EG7=function(){},PG7=global.Bare?queueMicrotask:process.nextTick.bind(process),qG7=function(X){return X.setHeader&&typeof X.abort==="function"},AG7=function(X){return X.stdio&&Array.isArray(X.stdio)&&X.stdio.length===3},xQ8=function(X,Y,G){if(typeof Y==="function")return xQ8(X,null,Y);if(!Y)Y={};G=LG7(G||EG7);var{_writableState:Q,_readableState:J}=X,W=Y.readable||Y.readable!==!1&&X.readable,Z=Y.writable||Y.writable!==!1&&X.writable,$=!1,K=function(){if(!X.writable)H()},H=function(){if(Z=!1,!W)G.call(X)},U=function(){if(W=!1,!Z)G.call(X)},B=function(E){G.call(X,E?Error("exited with error code: "+E):null)},N=function(E){G.call(X,E)},z=function(){PG7(O)},O=function(){if($)return;if(W&&!(J&&(J.ended&&!J.destroyed)))return G.call(X,Error("premature close"));if(Z&&!(Q&&(Q.ended&&!Q.destroyed)))return G.call(X,Error("premature close"))},w=function(){X.req.on("finish",H)};if(qG7(X))if(X.on("complete",H),X.on("abort",z),X.req)w();else X.on("request",w);else if(Z&&!Q)X.on("end",K),X.on("close",K);if(AG7(X))X.on("exit",B);if(X.on("end",U),X.on("finish",H),Y.error!==!1)X.on("error",N);return X.on("close",z),function(){if($=!0,X.removeListener("complete",H),X.removeListener("abort",z),X.removeListener("request",w),X.req)X.req.removeListener("finish",H);X.removeListener("end",K),X.removeListener("close",K),X.removeListener("finish",H),X.removeListener("exit",B),X.removeListener("end",U),X.removeListener("error",N),X.removeListener("close",z)}};hQ8.exports=xQ8});var mQ8=C((drG,lQ8)=>{var TG7=ub0(),IG7=gQ8(),uc1;try{uc1=I1("fs")}catch(X){}var u31=function(){},VG7=typeof process>"u"?!1:/^v?\.0/.test(process.version),lc1=function(X){return typeof X==="function"},jG7=function(X){if(!VG7)return!1;if(!uc1)return!1;return(X instanceof(uc1.ReadStream||u31)||X instanceof(uc1.WriteStream||u31))&&lc1(X.close)},MG7=function(X){return X.setHeader&&lc1(X.abort)},RG7=function(X,Y,G,Q){Q=TG7(Q);var J=!1;X.on("close",function(){J=!0}),IG7(X,{readable:Y,writable:G},function(Z){if(Z)return Q(Z);J=!0,Q()});var W=!1;return function(Z){if(J)return;if(W)return;if(W=!0,jG7(X))return X.close(u31);if(MG7(X))return X.abort();if(lc1(X.destroy))return X.destroy();Q(Z||Error("stream was destroyed"))}},uQ8=function(X){X()},SG7=function(X,Y){return X.pipe(Y)},CG7=function(){var X=Array.prototype.slice.call(arguments),Y=lc1(X[X.length-1]||u31)&&X.pop()||u31;if(Array.isArray(X[0]))X=X[0];if(X.length<2)throw Error("pump requires two streams per minimum");var G,Q=X.map(function(J,W){var Z=W<X.length-1,$=W>0;return RG7(J,Z,$,function(K){if(!G)G=K;if(K)Q.forEach(uQ8);if(Z)return;Q.forEach(uQ8),Y(G)})});return X.reduce(SG7)};lQ8.exports=CG7});var oQ8=C((fG7)=>{var dQ8=kQ8(),cQ8=mQ8(),iQ8=I1("fs"),ZY=I1("path"),l31=(global.Bare?global.Bare.platform:process.platform)==="win32";fG7.pack=function(Y,G){if(!Y)Y=".";if(!G)G={};let Q=G.fs||iQ8,J=G.ignore||G.filter||m31,W=G.mapStream||tQ8,Z=_G7(Q,G.dereference?Q.stat:Q.lstat,Y,J,G.entries,G.sort),$=G.strict!==!1,K=typeof G.umask==="number"?~G.umask:~pQ8(),H=G.pack||dQ8.pack(),U=G.finish||m31,B=G.map||m31,N=typeof G.dmode==="number"?G.dmode:0,z=typeof G.fmode==="number"?G.fmode:0;if(G.strip)B=rQ8(B,G.strip);if(G.readable)N|=parseInt(555,8),z|=parseInt(444,8);if(G.writable)N|=parseInt(333,8),z|=parseInt(222,8);E();function O(P,q){Q.readlink(ZY.join(Y,P),function(M,j){if(M)return H.destroy(M);q.linkname=lb0(j),H.entry(q,E)})}function w(P,q,M){if(H.destroyed)return;if(P)return H.destroy(P);if(!q){if(G.finalize!==!1)H.finalize();return U(H)}if(M.isSocket())return E();let j={name:lb0(q),mode:(M.mode|(M.isDirectory()?N:z))&K,mtime:M.mtime,size:M.size,type:"file",uid:M.uid,gid:M.gid};if(M.isDirectory())return j.size=0,j.type="directory",j=B(j)||j,H.entry(j,E);if(M.isSymbolicLink())return j.size=0,j.type="symlink",j=B(j)||j,O(q,j);if(j=B(j)||j,!M.isFile()){if($)return H.destroy(Error("unsupported type for "+q));return E()}let V=H.entry(j,E),R=W(Q.createReadStream(ZY.join(Y,q),{start:0,end:j.size>0?j.size-1:j.size}),j);R.on("error",function(k){V.destroy(k)}),cQ8(R,V)}function E(P){if(P)return H.destroy(P);Z(w)}return H};function kG7(X){return X.length?X[X.length-1]:null}function vG7(){return!global.Bare&&process.getuid?process.getuid():-1}function pQ8(){return!global.Bare&&process.umask?process.umask():0}fG7.extract=function(Y,G){if(!Y)Y=".";if(!G)G={};Y=ZY.resolve(Y);let Q=G.fs||iQ8,J=G.ignore||G.filter||m31,W=G.mapStream||tQ8,Z=G.chown!==!1&&!l31&&vG7()===0,$=G.extract||dQ8.extract(),K=[],H=new Date,U=typeof G.umask==="number"?~G.umask:~pQ8(),B=G.strict!==!1,N=G.validateSymlinks!==!1,z=G.map||m31,O=typeof G.dmode==="number"?G.dmode:0,w=typeof G.fmode==="number"?G.fmode:0;if(G.strip)z=rQ8(z,G.strip);if(G.readable)O|=parseInt(555,8),w|=parseInt(444,8);if(G.writable)O|=parseInt(333,8),w|=parseInt(222,8);if($.on("entry",E),G.finish)$.on("finish",G.finish);return $;function E(V,R,k){V=z(V)||V,V.name=lb0(V.name);let _=ZY.join(Y,ZY.join("/",V.name));if(J(_,V))return R.resume(),k();let v=ZY.join(_,".")===ZY.join(Y,".")?Y:ZY.dirname(_);aQ8(Q,v,ZY.join(Y,"."),function(u,r){if(u)return k(u);if(!r)return k(Error(v+" is not a valid path"));if(V.type==="directory")return K.push([_,V.mtime]),j(_,{fs:Q,own:Z,uid:V.uid,gid:V.gid,mode:V.mode},y);j(v,{fs:Q,own:Z,uid:V.uid,gid:V.gid,mode:493},function(o){if(o)return k(o);switch(V.type){case"file":return f();case"link":return i();case"symlink":return h()}if(B)return k(Error("unsupported type for "+_+" ("+V.type+")"));R.resume(),k()})});function y(u){if(u)return k(u);q(_,V,function(r){if(r)return k(r);if(l31)return k();M(_,V,k)})}function h(){if(l31)return k();Q.unlink(_,function(){let u=ZY.resolve(ZY.dirname(_),V.linkname);if(!p(u)&&N)return k(Error(_+" is not a valid symlink"));nQ8(Q,u,ZY.join(Y,"."),function(r,o){if(r)return k(r);if(!o&&N)return k(Error(_+" is not a valid symlink"));Q.symlink(V.linkname,_,y)})})}function i(){if(l31)return k();Q.unlink(_,function(){let u=ZY.join(Y,ZY.join("/",V.linkname));Q.realpath(u,function(r,o){if(r||!p(o))return k(Error(_+" is not a valid hardlink"));Q.link(o,_,function(B1){if(B1&&B1.code==="EPERM"&&G.hardlinkAsFilesFallback)return R=Q.createReadStream(o),f();y(B1)})})})}function p(u){return u===Y||u.startsWith(Y+ZY.sep)}function f(){let u=Q.createWriteStream(_),r=W(R,V);u.on("error",function(o){r.destroy(o)}),cQ8(r,u,function(o){if(o)return k(o);u.on("close",y)})}}function P(V,R){let k;while((k=kG7(K))&&V.slice(0,k[0].length)!==k[0])K.pop();if(!k)return R();Q.utimes(k[0],H,k[1],R)}function q(V,R,k){if(G.utimes===!1)return k();if(R.type==="directory")return Q.utimes(V,H,R.mtime,k);if(R.type==="symlink")return P(V,k);Q.utimes(V,H,R.mtime,function(_){if(_)return k(_);P(V,k)})}function M(V,R,k){let _=R.type==="symlink",v=_?Q.lchmod:Q.chmod,y=_?Q.lchown:Q.chown;if(!v)return k();let h=(R.mode|(R.type==="directory"?O:w))&U;if(y&&Z)y.call(Q,V,R.uid,R.gid,i);else i(null);function i(p){if(p)return k(p);if(!v)return k();v.call(Q,V,h,k)}}function j(V,R,k){Q.stat(V,function(_){if(!_)return k(null);if(_.code!=="ENOENT")return k(_);Q.mkdir(V,{mode:R.mode,recursive:!0},function(v,y){if(v)return k(v);M(V,R,k)})})}};function nQ8(X,Y,G,Q){if(Y===G)return Q(null,!0);if(!Y.startsWith(G+ZY.sep))return Q(null,!1);X.lstat(Y,function(J,W){if(J&&J.code!=="ENOENT"&&J.code!=="EPERM")return Q(J);if(J||!W.isSymbolicLink())return nQ8(X,ZY.join(Y,".."),G,Q);Q(null,!1)})}function aQ8(X,Y,G,Q){if(Y===G)return Q(null,!0);X.lstat(Y,function(J,W){if(J&&J.code!=="ENOENT"&&J.code!=="EPERM")return Q(J);if(J||W.isDirectory())return aQ8(X,ZY.join(Y,".."),G,Q);Q(null,!1)})}function m31(){}function tQ8(X){return X}function lb0(X){return l31?X.replace(/\\/g,"/").replace(/[:?<>|]/g,"_"):X}function _G7(X,Y,G,Q,J,W){if(!J)J=["."];let Z=J.slice(0);return function(K){if(!Z.length)return K(null);let H=Z.shift(),U=ZY.join(G,H);Y.call(X,U,function(B,N){if(B)return K(J.indexOf(H)===-1&&B.code==="ENOENT"?null:B);if(!N.isDirectory())return K(null,H,N);X.readdir(U,function(z,O){if(z)return K(z);if(W)O.sort();for(let w=0;w<O.length;w++)if(!Q(ZY.join(G,H,O[w])))Z.push(ZY.join(H,O[w]));K(null,H,N)})})}}function rQ8(X,Y){return function(G){G.name=G.name.split("/").slice(Y).join("/");let Q=G.linkname;if(Q&&(G.type==="link"||ZY.isAbsolute(Q)))G.linkname=Q.split("/").slice(Y).join("/");return X(G)}}});var xG7,hG7;var sQ8=D(()=>{Vb0();xG7=Y1(gG8(),1),hG7=Y1(oQ8(),1)});var mc1=()=>{};var eQ8=D(()=>{Gc1()});var XJ8=D(()=>{Sc1();Rc1();mc1()});var YJ8=()=>{};var GJ8=()=>{};var mb0=D(()=>{PG8();Tb0();Sc1();VG8();qb0();Vb0();jG8();MG8();RG8();SG8();Ab0();CG8();sQ8();mc1();eQ8();XJ8();YJ8();GJ8();mc1()});var TG,rY,hs,d31;var c31=D(()=>{TG={CLAIM_API_GROUP:"extensions.agents.x-k8s.io",CLAIM_API_VERSION:"v1alpha1",CLAIM_PLURAL:"sandboxclaims",SANDBOX_API_GROUP:"agents.x-k8s.io",SANDBOX_API_VERSION:"v1alpha1",SANDBOX_PLURAL:"sandboxes",POD_NAME_ANNOTATION:"agents.x-k8s.io/pod-name"};rY=class rY extends Error{cause;constructor(X,Y){super(X);if(this.name="SandboxError",this.cause=Y,Y instanceof Error&&Y.stack)this.stack=`${this.stack}
5029
5053
  Caused by: ${Y.stack}`}};hs=class hs extends rY{constructor(X,Y){super(X,Y);this.name="SandboxTimeoutError"}};d31=class d31 extends rY{constructor(X,Y){super(X,Y);this.name="SandboxAlreadyExistsError"}}});async function gG7(X){let Y=X.getCurrentCluster();if(!Y)throw new rY("No active cluster in kubeconfig");let G={};await X.applyToHTTPSOptions(G);let Q={},J=G.headers??{};for(let[W,Z]of Object.entries(J))if(Array.isArray(Z))Q[W]=Z.join(", ");else if(Z!==void 0)Q[W]=String(Z);if(typeof G.auth==="string"&&!Q.Authorization)Q.Authorization=`Basic ${Buffer.from(G.auth).toString("base64")}`;return{server:Y.server.replace(/\/+$/,""),headers:Q,tls:{cert:db0(G.cert),key:db0(G.key),ca:db0(G.ca),rejectUnauthorized:Y.skipTLSVerify?!1:void 0}}}function db0(X){if(X==null)return;if(typeof X==="string")return X;if(Buffer.isBuffer(X))return X.toString("utf8");return String(X)}async function vm(X,Y){let G=await gG7(X),Q={...G.headers,...Y.headers};if(Y.method==="PATCH")Q["content-type"]=Y.patchType==="apply"?"application/apply-patch+yaml":Y.patchType==="strategic-merge"?"application/strategic-merge-patch+json":"application/merge-patch+json";else if(Y.body!==void 0&&!("content-type"in Q))Q["content-type"]="application/json";let J={method:Y.method,headers:Q,body:Y.body===void 0?void 0:JSON.stringify(Y.body),signal:Y.signal,tls:G.tls};return fetch(`${G.server}${Y.path}`,J)}async function ib0(X){try{return await X.json()}catch{return null}}async function pb0(X,Y){if(X.ok)return;let G=await ib0(X),Q=G?.message??`${Y} failed: ${X.status} ${X.statusText}`;throw new cb0(X.status,G,Q)}async function i31(X,Y,G,Q,J="none"){try{let W=await vm(X,Y);if(W.status===404)return null;if(await pb0(W,G),J==="json")return await W.json();return null}catch(W){throw new rY(Q,W)}}async function p31(X,Y,G){let Q=`${QJ8}/${encodeURIComponent(Y)}/${TG.CLAIM_PLURAL}`,J;try{J=await vm(X,{method:"POST",path:Q,body:G})}catch(H){let U=H instanceof Error?H.message:String(H);throw console.warn(`[agent-sandbox/client] createSandboxClaim ${G.metadata.name} transport error: ${U}`),new rY(`Failed to create SandboxClaim: ${G.metadata.name} (transport error: ${U})`,H)}if(J.ok)return;let W=await ib0(J),Z=W?.reason?` ${W.reason}`:"",$=W?.message??J.statusText,K=`Failed to create SandboxClaim: ${G.metadata.name} (${J.status}${Z}: ${$})`;if(console.warn(`[agent-sandbox/client] createSandboxClaim ${G.metadata.name} rejected: status=${J.status} reason=${W?.reason??"<none>"} message=${$}`),J.status===409)throw new d31(K);throw new rY(K)}async function dc1(X,Y,G,Q=60000){let J=Date.now()+Q,W=500,Z;while(!0){let $=await fm(X,Y,G).catch(()=>{return});if(!$)return;if(Z=$,Date.now()>=J){let K=Z.metadata?.finalizers??[],H=Z.metadata?.deletionTimestamp??"<unknown>";throw new hs(`SandboxClaim ${G} still terminating after ${Q}ms (deletionTimestamp=${H}, finalizers=[${K.join(", ")}])`)}await new Promise((K)=>setTimeout(K,500))}}function nb0(X,Y){return`${QJ8}/${encodeURIComponent(X)}/${TG.CLAIM_PLURAL}/${encodeURIComponent(Y)}`}async function JJ8(X,Y,G,Q){await i31(X,{method:"PATCH",path:nb0(Y,G),patchType:"merge",body:{spec:{lifecycle:{shutdownPolicy:"Delete",shutdownTime:Q}}}},"patchSandboxClaimShutdown",`Failed to patch SandboxClaim shutdownTime: ${G}`)}async function _m(X,Y,G){await i31(X,{method:"DELETE",path:nb0(Y,G)},"deleteSandboxClaim",`Failed to delete SandboxClaim: ${G}`)}async function fm(X,Y,G){return await i31(X,{method:"GET",path:nb0(Y,G)},"getSandboxClaim",`Failed to get SandboxClaim: ${G}`,"json")??void 0}function KJ8(X,Y){return`${$J8}/${encodeURIComponent(X)}/${ab0}/${encodeURIComponent(Y)}`}function uG7(X){return`${$J8}/${encodeURIComponent(X)}/${ab0}`}async function cc1(X,Y,G){try{let Q=await vm(X,{method:"POST",path:uG7(Y),body:G});if(Q.status===409)return;await pb0(Q,"createHttpRoute")}catch(Q){if(Q instanceof cb0&&Q.status===409)return;throw new rY(`Failed to create HTTPRoute: ${G.metadata.name}`,Q)}}async function ic1(X,Y,G){await i31(X,{method:"DELETE",path:KJ8(Y,G)},"deleteHttpRoute",`Failed to delete HTTPRoute: ${G}`)}async function HJ8(X,Y,G){return await i31(X,{method:"GET",path:KJ8(Y,G)},"getHttpRoute",`Failed to get HTTPRoute: ${G}`,"json")??void 0}async function FJ8(X,Y,G,Q){let J={apiVersion:"v1",kind:"Service",metadata:{name:G},spec:{ports:[{name:Q.name,port:Q.port,targetPort:Q.targetPort,protocol:Q.protocol??"TCP"}]}},W=new URLSearchParams({fieldManager:lG7,force:"true"}),Z=`/api/v1/namespaces/${encodeURIComponent(Y)}/services/${encodeURIComponent(G)}?${W}`;try{let $=await vm(X,{method:"PATCH",path:Z,patchType:"apply",body:J});await pb0($,"ensureServicePort")}catch($){throw new rY(`Failed to apply Service ports: ${G}`,$)}}function pc1(X,Y,G,Q=180){let J=`/apis/${TG.SANDBOX_API_GROUP}/${TG.SANDBOX_API_VERSION}/namespaces/${encodeURIComponent(Y)}/${TG.SANDBOX_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${G}`)}`,{resolve:W,reject:Z,promise:$}=Promise.withResolvers(),K=new AbortController,H=!1,U=setTimeout(()=>{if(H)return;H=!0,K.abort(),Z(new hs(`Sandbox did not become ready within ${Q} seconds`))},Q*1000),B=(N)=>{if(H)return;H=!0,clearTimeout(U),K.abort(),N()};return(async()=>{let N;try{N=await vm(X,{method:"GET",path:J,signal:K.signal,headers:{accept:"application/json"}})}catch(z){B(()=>Z(new rY("Failed to start watch for sandbox readiness",z)));return}if(!N.ok||!N.body){let z=await ib0(N).catch(()=>null);B(()=>Z(new rY(`Watch handshake failed (${N.status}): ${z?.message??N.statusText}`)));return}try{for await(let z of tb0(N.body)){if(H)return;if(z.type==="ERROR"){let q=z.object;B(()=>Z(new rY(`Watch stream error while waiting for sandbox: ${q.message??"unknown"}`)));return}if(z.type!=="ADDED"&&z.type!=="MODIFIED")continue;let O=z.object;if(!O.status?.conditions?.find((q)=>q.type==="Ready"&&q.status==="True"))continue;let E=O.metadata?.name;if(!E){B(()=>Z(new rY("Sandbox metadata or name is missing")));return}let P=O.metadata?.annotations?.[TG.POD_NAME_ANNOTATION]??E;B(()=>W({sandboxName:E,podName:P}));return}B(()=>Z(new rY("Watch stream closed before sandbox became ready")))}catch(z){if(H)return;if(z instanceof Error&&(z.name==="AbortError"||K.signal.aborted))return;B(()=>Z(new rY("Watch stream error while waiting for sandbox",z)))}})(),$}async function*tb0(X){let Y=X.getReader(),G=new TextDecoder,Q="";try{while(!0){let{value:W,done:Z}=await Y.read();if(Z)break;Q+=G.decode(W,{stream:!0});let $;while(($=Q.indexOf(`
5030
- `))>=0){let K=Q.slice(0,$).trim();if(Q=Q.slice($+1),!K)continue;yield JSON.parse(K)}}let J=Q.trim();if(J)yield JSON.parse(J)}finally{Y.releaseLock()}}var cb0,QJ8,ZJ8="gateway.networking.k8s.io",WJ8="v1",ab0="httproutes",$J8,n31,lG7="mesh-sandbox-runner";var nc1=D(()=>{c31();cb0=class cb0 extends Error{status;body;constructor(X,Y,G){super(G);this.status=X;this.body=Y;this.name="KubeHttpError"}};QJ8=`/apis/${TG.CLAIM_API_GROUP}/${TG.CLAIM_API_VERSION}/namespaces`;$J8=`/apis/${ZJ8}/${WJ8}/namespaces`;n31={API_GROUP:ZJ8,API_VERSION:WJ8,PLURAL:ab0}});async function*NJ8(X){let Y=X.now??(()=>Date.now()),G=Y(),Q=X.schedulingTimeoutMs??cG7,J={pod:{},sandbox:{},events:{hasPulling:!1,hasPulled:!1},startedAt:G},W=[],Z=null,$=!1,K=(E)=>{if($)return;if(Z){let P=Z;Z=null,P(E)}else W.push(E)},H=()=>{if(W.length>0)return Promise.resolve(W.shift());if($)return Promise.resolve(null);return new Promise((E)=>{Z=E})},U=()=>{if($)return;if($=!0,Z){let E=Z;Z=null,E(null)}},B=new AbortController,N=()=>{B.abort(),U()};if(X.signal)if(X.signal.aborted)B.abort(),U();else X.signal.addEventListener("abort",N,{once:!0});let z=Math.max(0,Q-(Y()-G)),O=setTimeout(()=>K("tick"),z+100),w=Promise.allSettled([iG7(X.kc,X.namespace,X.claimName,B.signal,J,K,Y),nG7(X.kc,X.namespace,X.claimName,B.signal,J,K),aG7(X.kc,X.namespace,X.claimName,B.signal,J,K,Y)]);try{let E=null,P=-1,q=UJ8(J,Q,Y);if(E=ob0(q),!rb0(q))P=BJ8(q);if(yield q,rb0(q))return;while(!$){if(await H()===null)break;let j=UJ8(J,Q,Y);if(rb0(j)){let k=ob0(j);if(k!==E)E=k,yield j;return}let V=BJ8(j);if(V<P)continue;let R=ob0(j);if(R!==E)E=R,P=V,yield j}}finally{if(clearTimeout(O),B.abort(),X.signal)X.signal.removeEventListener("abort",N);U(),await w.catch(()=>{})}}function UJ8(X,Y,G){let{pod:Q,sandbox:J,events:W,startedAt:Z}=X;if(J.ready)return{kind:"ready"};let $=Q.containerWaitingReason;if($==="ImagePullBackOff"||$==="ErrImagePull")return{kind:"failed",reason:"image-pull-backoff",message:"Sandbox image failed to download. The cluster may be missing pull credentials or the image tag may not exist."};if($==="CrashLoopBackOff")return{kind:"failed",reason:"crash-loop-backoff",message:"Sandbox crashed during startup and is now in CrashLoopBackOff. Check pod logs."};if(!Q.scheduled&&W.lastFailedSchedulingAt!==void 0&&G()-Z>Y)return{kind:"failed",reason:"scheduling-timeout",message:W.failedSchedulingMessage??`Pod could not be scheduled within ${Math.round(Y/1000)}s.`};if(Q.containerRunning&&!Q.containerReady)return{kind:"warming-daemon",since:Z};if($==="ContainerCreating"&&W.hasPulled)return{kind:"starting-container",since:Z};if(W.hasPulling&&!W.hasPulled)return{kind:"pulling-image",since:Z};if(Q.scheduledFalseReason==="Unschedulable"||W.lastFailedSchedulingAt!==void 0&&!Q.scheduled)return{kind:"waiting-for-capacity",since:Z,message:W.failedSchedulingMessage??Q.scheduledFalseMessage,nodeClaim:W.nominatedNodeClaim};return{kind:"claiming",since:Z}}function rb0(X){return X.kind==="ready"||X.kind==="failed"}function BJ8(X){switch(X.kind){case"claiming":return 0;case"waiting-for-capacity":return 1;case"pulling-image":return 2;case"starting-container":return 3;case"warming-daemon":return 4;case"ready":case"failed":return 99}}function ob0(X){switch(X.kind){case"claiming":case"pulling-image":case"starting-container":case"warming-daemon":return X.kind;case"waiting-for-capacity":return`waiting-for-capacity:${X.message??""}:${X.nodeClaim??""}`;case"ready":return"ready";case"failed":return`failed:${X.reason}:${X.message}`}}async function iG7(X,Y,G,Q,J,W,Z){let $=`/api/v1/namespaces/${encodeURIComponent(Y)}/pods?watch=true&labelSelector=${encodeURIComponent(`${mG7}=${G}`)}`;return sb0({kc:X,path:$,signal:Q,label:`pod/${G}`,onEvent:(K)=>{if(K.type!=="ADDED"&&K.type!=="MODIFIED")return;let H=K.object;if(H.metadata?.name!==G)return;pG7(H,J,Z),W("pod")}})}function pG7(X,Y,G){let J=(X.status?.conditions??[]).find((Z)=>Z.type==="PodScheduled");if(J?.status==="True")Y.pod.scheduled=!0,Y.pod.scheduledFalseReason=void 0,Y.pod.scheduledFalseMessage=void 0;else if(J?.status==="False")Y.pod.scheduled=!1,Y.pod.scheduledFalseReason=J.reason,Y.pod.scheduledFalseMessage=J.message;let W=(X.status?.containerStatuses??[]).find((Z)=>Z.name===dG7);if(W)Y.pod.containerWaitingReason=W.state?.waiting?.reason,Y.pod.containerRunning=!!W.state?.running,Y.pod.containerReady=W.ready===!0}async function nG7(X,Y,G,Q,J,W){let Z=`/apis/${TG.SANDBOX_API_GROUP}/${TG.SANDBOX_API_VERSION}/namespaces/${encodeURIComponent(Y)}/${TG.SANDBOX_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${G}`)}`;return sb0({kc:X,path:Z,signal:Q,label:`sandbox/${G}`,onEvent:($)=>{if($.type!=="ADDED"&&$.type!=="MODIFIED")return;let H=$.object.status?.conditions?.find((U)=>U.type==="Ready");if(!H)return;if(H.status==="True")J.sandbox.ready=!0,J.sandbox.notReadyReason=void 0,J.sandbox.notReadyMessage=void 0;else J.sandbox.ready=!1,J.sandbox.notReadyReason=H.reason,J.sandbox.notReadyMessage=H.message;W("sandbox")}})}async function aG7(X,Y,G,Q,J,W,Z){let $=`/api/v1/namespaces/${encodeURIComponent(Y)}/events?watch=true&fieldSelector=${encodeURIComponent(`involvedObject.name=${G},involvedObject.kind=Pod`)}`;return sb0({kc:X,path:$,signal:Q,label:`events/${G}`,onEvent:(K)=>{if(K.type!=="ADDED"&&K.type!=="MODIFIED")return;let H=K.object,U=H.reason;if(!U)return;switch(U){case"Pulling":J.events.hasPulling=!0;break;case"Pulled":J.events.hasPulling=!0,J.events.hasPulled=!0;break;case"FailedScheduling":J.events.lastFailedSchedulingAt=Z(),J.events.failedSchedulingMessage=H.message;break;case"Nominated":{let B=H.message?.match(/nodeclaim\/([\w-]+)/);if(B)J.events.nominatedNodeClaim=B[1];break}default:return}W("event")}})}async function sb0(X){let{kc:Y,path:G,signal:Q,label:J,onEvent:W}=X,Z=0;while(!Q.aborted){try{let K=await vm(Y,{method:"GET",path:G,signal:Q,headers:{accept:"application/json"}});if(!K.ok||!K.body){try{await K.body?.cancel()}catch{}throw Error(`watch handshake failed: ${K.status} ${K.statusText}`)}Z=0;for await(let H of tb0(K.body)){if(Q.aborted)return;try{W(H)}catch(U){console.warn(`[lifecycle-watcher] ${J} onEvent threw: ${U instanceof Error?U.message:String(U)}`)}}}catch(K){if(Q.aborted)return;let H=K instanceof Error?K.message:String(K);console.warn(`[lifecycle-watcher] ${J} watch ended: ${H}`)}if(Q.aborted)return;let $=Math.min(250*2**Z,5000);Z+=1,await tG7($,Q)}}function tG7(X,Y){return new Promise((G)=>{if(Y.aborted){G();return}let Q=setTimeout(()=>{Y.removeEventListener("abort",J),G()},X),J=()=>{clearTimeout(Q),G()};Y.addEventListener("abort",J,{once:!0})})}var mG7="studio.decocms.com/sandbox-handle",dG7="sandbox",cG7=300000;var zJ8=D(()=>{c31();nc1()});import{createHash as rG7,randomBytes as oG7,randomUUID as sG7}from"crypto";import*as LJ8 from"net";import{PassThrough as eG7}from"stream";function t31(X,Y){return`${a31}${sT(X,Y,{hashLen:WQ7})}`}class Zy0{kind=pz;records=new Map;inflight=new mL;stateStore;previewUrlPattern;kubeConfig;portForward;namespace;sandboxTemplateName;tokenGenerator;idleTtlMs;metrics;previewGateway;constructor(X={}){this.stateStore=X.stateStore??null,this.previewUrlPattern=X.previewUrlPattern??null,this.kubeConfig=X.kubeConfig??FQ7(),this.portForward=new jb0(this.kubeConfig),this.namespace=X.namespace??XQ7,this.sandboxTemplateName=X.sandboxTemplateName??YQ7,this.tokenGenerator=X.tokenGenerator??(()=>oG7(QQ7).toString("hex")),this.idleTtlMs=X.idleTtlMs??ZQ7,this.metrics=X.meter?HQ7(X.meter):null,this.previewGateway=X.previewGateway&&X.previewUrlPattern?{...X.previewGateway}:null}async ensure(X,Y={}){let G=this.computeHandle(X,Y.repo?.branch??null);return this.inflight.run(G,()=>oT(this.stateStore,X,pz,(Q)=>this.ensureLocked(X,G,Y,Q)))}async exec(X,Y){let G=await this.requireRecord(X);return M$1(G.daemonUrl,G.token,Y)}async delete(X){let Y=await this.getRecord(X);if(this.records.delete(X),Y)this.closeForwarder(Y.daemonForward),this.metrics?.active.add(-1,Qy0(Y.tenant));if(await this.deleteHttpRouteIfManaged(X).catch((G)=>{console.warn(`[${iW}] HTTPRoute delete failed for ${X}: ${G instanceof Error?G.message:String(G)}`)}),await _m(this.kubeConfig,this.namespace,X),this.stateStore)if(Y)await this.stateStore.delete(Y.id,pz);else await this.stateStore.deleteByHandle(pz,X)}async alive(X){let Y=await fm(this.kubeConfig,this.namespace,X).catch(()=>{return});return Y?Xy0(Y):!1}watchClaimLifecycle(X,Y){return NJ8({kc:this.kubeConfig,namespace:this.namespace,claimName:X,signal:Y})}async getPreviewUrl(X){let Y=await this.getRecord(X);if(!Y)return null;return this.composePreviewUrl(Y)}async proxyDaemonRequest(X,Y,G){let Q=await this.getRecord(X);if(!Q)return new Response(JSON.stringify({error:"sandbox not found"}),{status:404,headers:{"content-type":"application/json"}});let J=performance.now(),W=0;try{let Z=await R$1(Q.daemonUrl,Q.token,Y,G);return W=Z.status,Z}finally{this.recordProxyDuration("daemon",W,Q,performance.now()-J)}}async resolvePreviewUpstreamUrl(X){if(this.previewUrlPattern)return`http://${X}.${this.namespace}.svc.cluster.local:${bm}`;let Y=await this.getRecord(X);if(Y)return Y.daemonUrl;let G=await this.resurrectByHandle(X);return G?G.daemonUrl:null}async proxyPreviewRequest(X,Y){let G=performance.now(),Q=this.records.get(X)??null,J=0;try{let W=await this.resolvePreviewUpstreamUrl(X);if(!W)return J=404,Yy0(404,{error:"sandbox not found"});let Z=new URL(Y.url);if((Z.pathname==="/_decopilot_vm"||Z.pathname.startsWith("/_decopilot_vm/"))&&Y.method!=="GET")return J=404,Yy0(404,{error:"not found"});let K=(O)=>`${O}${Z.pathname}${Z.search}`,H=new Headers(Y.headers);for(let O of $Q7)H.delete(O);let U=Y.method!=="GET"&&Y.method!=="HEAD",B={method:Y.method,headers:H,body:U?Y.body:void 0,redirect:"manual",signal:Y.signal,duplex:U?"half":void 0},N;try{N=await fetch(K(W),B)}catch(O){let w=`${W}${Z.pathname}`;if(console.warn(`[${iW}] preview fetch to ${w} failed: ${O instanceof Error?O.message:String(O)}`),Y.method==="GET"||Y.method==="HEAD"){if(this.invalidateRecord(X),await this.resurrectByHandle(X).catch(()=>null)){let P=await this.resolvePreviewUpstreamUrl(X);if(P)try{N=await fetch(K(P),B);let q=new Headers;for(let[M,j]of N.headers.entries())if(!OJ8.includes(M.toLowerCase()))q.set(M,j);return J=N.status,new Response(N.body,{status:N.status,statusText:N.statusText,headers:q})}catch(q){console.warn(`[${iW}] preview fetch retry to ${w} failed: ${q instanceof Error?q.message:String(q)}`)}}}else this.invalidateRecord(X);return J=502,Yy0(502,{error:"sandbox daemon unreachable"})}let z=new Headers;for(let[O,w]of N.headers.entries())if(!OJ8.includes(O.toLowerCase()))z.set(O,w);return J=N.status,new Response(N.body,{status:N.status,statusText:N.statusText,headers:z})}finally{this.recordProxyDuration("preview",J,Q,performance.now()-G,X)}}async ensureLocked(X,Y,G,Q){if(G.image)console.warn(`[${iW}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${G.image}`);if(Q){let Z=await Q.get(X,pz);if(Z){let $=await this.rehydrate(X,Y,Z);if($)return this.finish($,Q,!1,!0,"resume");await Q.delete(X,pz)}}let J=await fm(this.kubeConfig,this.namespace,Y).catch(()=>{return});if(J)if(J.metadata?.deletionTimestamp)await dc1(this.kubeConfig,this.namespace,Y).catch((Z)=>{console.warn(`[${iW}] wait for terminating claim ${Y} failed: ${Z instanceof Error?Z.message:String(Z)}`)});else{let Z=await this.adopt(X,Y,J).catch(($)=>{return console.warn(`[${iW}] adopt ${Y} failed, recreating: ${$ instanceof Error?$.message:String($)}`),null});if(Z)return this.finish(Z,Q,!0,!0,"adopt");await _m(this.kubeConfig,this.namespace,Y).catch(()=>{}),await dc1(this.kubeConfig,this.namespace,Y).catch(($)=>{console.warn(`[${iW}] wait for deleted claim ${Y} failed: ${$ instanceof Error?$.message:String($)}`)})}let W=await this.provision(X,Y,G);return this.finish(W,Q,!0,!1,"fresh")}async finish(X,Y,G,Q,J){let W=this.records.has(X.handle);if(this.records.set(X.handle,X),G)await this.persist(Y,X);if(Q)await JJ8(this.kubeConfig,this.namespace,X.handle,this.computeShutdownTime()).catch((Z)=>console.warn(`[${iW}] TTL refresh failed for ${X.handle}: ${Z instanceof Error?Z.message:String(Z)}`));if(this.metrics){let Z=Qy0(X.tenant);if(this.metrics.ensureOutcome.add(1,{...Z,outcome:J}),!W)this.metrics.active.add(1,Z)}return this.toSandbox(X)}buildEnvMap(X,Y){let G={},Q=[];for(let[Z,$]of Object.entries(X.env??{}))if(JQ7.has(Z))Q.push(Z);else G[Z]=$;if(Q.length>0)console.warn(`[${iW}] opts.env keys overlap reserved bootstrap names and were dropped: ${Q.join(",")}`);let J=X.repo,W=J?J.displayName??LQ7(J.cloneUrl):null;return{...G,DAEMON_TOKEN:Y.token,DAEMON_BOOT_ID:Y.daemonBootId,APP_ROOT:Y.workdir,PROXY_PORT:String(bm),DEV_PORT:String(X.workload?.devPort??GQ7),RUNTIME:X.workload?.runtime??"node",...J?{CLONE_URL:J.cloneUrl,REPO_NAME:W??"",BRANCH:J.branch??"",GIT_USER_NAME:J.userName,GIT_USER_EMAIL:J.userEmail}:{},...X.workload?.packageManager?{PACKAGE_MANAGER:X.workload.packageManager}:{}}}buildClaim(X,Y,G){let Q=this.buildEnvMap(Y,G);return{apiVersion:`${TG.CLAIM_API_GROUP}/${TG.CLAIM_API_VERSION}`,kind:"SandboxClaim",metadata:{name:X,namespace:this.namespace,labels:{"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...Gy0(Y.tenant)}},spec:{sandboxTemplateRef:{name:this.sandboxTemplateName},additionalPodMetadata:{labels:Gy0(Y.tenant,{[TT.role]:"claimed",[TT.sandboxHandle]:X})},env:Object.entries(Q).sort(([J],[W])=>J<W?-1:J>W?1:0).map(([J,W])=>({name:J,value:W})),warmpool:"none",lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision(X,Y,G){let Q=this.tokenGenerator(),J=sG7(),W=eb0,Z=this.buildClaim(Y,G,{token:Q,daemonBootId:J,workdir:W});try{await p31(this.kubeConfig,this.namespace,Z)}catch(U){if(U instanceof d31)await dc1(this.kubeConfig,this.namespace,Y),await p31(this.kubeConfig,this.namespace,Z);else throw U}let{podName:$}=await pc1(this.kubeConfig,this.namespace,Y);try{await this.ensureServicePortForHandle(Y),await this.ensureHttpRouteForHandle(Y,G.tenant??null)}catch(U){throw await _m(this.kubeConfig,this.namespace,Y).catch(()=>{}),U}let K=await this.openForwarder($,bm,Y),H=`http://127.0.0.1:${K.localPort}`;try{await j$1(H)}catch(U){throw this.closeForwarder(K),await this.deleteHttpRouteIfManaged(Y).catch(()=>{}),await _m(this.kubeConfig,this.namespace,Y).catch(()=>{}),U}return{id:X,handle:Y,podName:$,token:Q,workdir:W,daemonUrl:H,daemonForward:K,workload:G.workload??null,daemonBootId:J,tenant:G.tenant??null,ensureOpts:DQ7(G)}}async ensureServicePortForHandle(X){if(!this.previewGateway||!this.previewUrlPattern)return;await FJ8(this.kubeConfig,this.namespace,X,{name:"daemon",port:bm,targetPort:bm})}async ensureHttpRouteForHandle(X,Y){if(!this.previewGateway||!this.previewUrlPattern)return;let G=wQ7(this.previewUrlPattern,X);if(!G)throw new rY(`Unable to derive preview hostname for ${X} from pattern: ${this.previewUrlPattern}`);let Q={apiVersion:`${n31.API_GROUP}/${n31.API_VERSION}`,kind:"HTTPRoute",metadata:{name:X,namespace:this.namespace,labels:Gy0(Y??void 0,{[TT.role]:"claimed",[TT.sandboxHandle]:X,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio"})},spec:{parentRefs:[{kind:"Gateway",group:"gateway.networking.k8s.io",name:this.previewGateway.name,namespace:this.previewGateway.namespace}],hostnames:[G],rules:[{backendRefs:[{group:"",kind:"Service",name:X,port:bm}]}]}};await cc1(this.kubeConfig,this.namespace,Q)}async deleteHttpRouteIfManaged(X){if(!this.previewGateway)return;await ic1(this.kubeConfig,this.namespace,X)}async rehydrate(X,Y,G){let Q=G.state;if(!Q.podName||!Q.token)return null;let J=await fm(this.kubeConfig,this.namespace,Y).catch(()=>{return});if(!J||!Xy0(J))return null;let W=DJ8(J)??Q.podName,Z=await this.openAndProbeDaemon(W,Y);if(!Z)return null;if(Q.daemonBootId&&Q.daemonBootId!==Z.bootId)console.warn(`[${iW}] daemon restart detected (handle=${Y}): stored bootId=${Q.daemonBootId} live bootId=${Z.bootId}`);return{id:X,handle:Y,podName:W,token:Q.token,workdir:Q.workdir??eb0,daemonUrl:Z.daemonUrl,daemonForward:Z.daemonForward,workload:Q.workload??null,daemonBootId:Z.bootId,tenant:Q.tenant??null,ensureOpts:Q.ensureOpts??null}}async adopt(X,Y,G){if(!Xy0(G))return null;let Q=DJ8(G);if(!Q)return null;let J=UQ7(G);if(!J)return null;let W=await this.openAndProbeDaemon(Q,Y);if(!W)return null;let Z=OQ7(G);if(this.previewGateway)await this.ensureServicePortForHandle(Y).catch(($)=>{console.warn(`[${iW}] Service port backfill failed for ${Y}: ${$ instanceof Error?$.message:String($)}`)}),await this.ensureHttpRouteForHandle(Y,Z).catch(($)=>{console.warn(`[${iW}] HTTPRoute backfill failed for ${Y}: ${$ instanceof Error?$.message:String($)}`)});return{id:X,handle:Y,podName:Q,token:J,workdir:eb0,daemonUrl:W.daemonUrl,daemonForward:W.daemonForward,workload:null,daemonBootId:W.bootId,tenant:Z,ensureOpts:null}}async openAndProbeDaemon(X,Y){let G=await this.openForwarder(X,bm,Y).catch(()=>null);if(!G)return null;let Q=`http://127.0.0.1:${G.localPort}`,J=await Id(Q);if(!J)return this.closeForwarder(G),null;return{daemonForward:G,daemonUrl:Q,bootId:J.bootId}}async getRecord(X){let Y=this.records.get(X);if(Y)return Y;if(!this.stateStore)return null;let G=await this.stateStore.getByHandle(pz,X);if(!G)return null;let Q=await this.rehydrate(G.id,X,G);if(Q)this.records.set(X,Q);return Q}async resurrectByHandle(X){if(!this.stateStore)return null;let Y=await this.stateStore.getByHandle(pz,X);if(!Y)return null;let G=Y.state.ensureOpts;if(!G)return null;return await this.ensure(Y.id,G),this.records.get(X)??null}async requireRecord(X){let Y=await this.getRecord(X);if(Y)return Y;let G=await this.resurrectByHandle(X);if(G)return G;throw Error(`unknown sandbox handle ${X}`)}invalidateRecord(X){let Y=this.records.get(X);if(!Y)return;this.records.delete(X),this.closeForwarder(Y.daemonForward)}recordProxyDuration(X,Y,G,Q,J){if(!this.metrics)return;this.metrics.proxyDurationMs.record(Q,{...Qy0(G?.tenant??null),source:X,sandbox_handle:G?.handle??J??"",status_code:Y||0})}computeHandle(X,Y){return t31(X,Y)}composePreviewUrl(X){if(this.previewUrlPattern)return eT(this.previewUrlPattern,X.handle);return`http://127.0.0.1:${X.daemonForward.localPort}/`}toSandbox(X){return{handle:X.handle,workdir:X.workdir,previewUrl:this.composePreviewUrl(X)}}async persist(X,Y){if(!X)return;let G={podName:Y.podName,token:Y.token,workdir:Y.workdir,workload:Y.workload,daemonBootId:Y.daemonBootId,tenant:Y.tenant,...Y.ensureOpts?{ensureOpts:Y.ensureOpts}:{}};await X.put(Y.id,pz,{handle:Y.handle,state:G})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}openForwarder(X,Y,G=X){let Q=BQ7(G,Y);return new Promise((J,W)=>{let Z=($,K)=>{let H=LJ8.createServer((U)=>this.handleForwardedConnection(U,X,Y));H.once("error",(U)=>{if(U.code==="EADDRINUSE"&&K<KQ7){try{H.close()}catch{}let B=Jy0+($-Jy0+1)%EJ8;Z(B,K+1);return}W(U)}),H.listen($,"127.0.0.1",()=>{let U=H.address();if(!U||typeof U==="string"){H.close(),W(Error("port-forward listener failed to bind"));return}J({server:H,localPort:U.port})})};Z(Q,0)})}handleForwardedConnection(X,Y,G){let Q=new eG7,J=null,W=!1,Z=()=>{if(W)return;if(W=!0,Q.destroy(),J)try{J.close()}catch{}if(!X.destroyed)X.destroy()};X.pipe(Q),X.on("error",Z),X.on("close",Z),this.portForward.portForward(this.namespace,Y,[G],X,null,Q).then(($)=>{let K=typeof $==="function"?$():$;if(!K){Z();return}if(J=K,J.on("close",Z),J.on("error",Z),W)try{J.close()}catch{}}).catch(($)=>{console.warn(`[${iW}] port-forward to ${Y}:${G} failed: ${$ instanceof Error?$.message:String($)}`),Z()})}closeForwarder(X){X.server.close((Y)=>{if(Y)console.warn(`[${iW}] port-forward close on :${X.localPort} errored: ${Y instanceof Error?Y.message:String(Y)}`)})}}function HQ7(X){return{active:X.createUpDownCounter("studio.sandbox.active",{description:"Active sandbox count, by runner kind and owning org. Cross-checks the cAdvisor-derived count from the cluster \u2014 divergence between the two indicates orphaned claims (mesh deleted but K8s didn't reap) or unattributed pods.",unit:"{sandbox}"}),ensureOutcome:X.createCounter("studio.sandbox.ensure.outcome",{description:"Outcome of each ensure() call: fresh provision, resume from state-store after restart, or adopt of a cluster-side claim mesh didn't know about. Cold-start ratio is the primary input for warm-pool sizing.",unit:"{call}"}),proxyDurationMs:X.createHistogram("studio.sandbox.proxy.duration_ms",{description:"Wall-clock latency of mesh-mediated requests to the sandbox daemon: tool exec proxies (source=daemon) and preview iframe traffic (source=preview).",unit:"ms"})}}function FQ7(){let X=new _s;return X.loadFromDefault(),X}function Xy0(X){return Boolean(X.status?.conditions?.some((Y)=>Y.type==="Ready"&&Y.status==="True"))}function UQ7(X){let Y=X.spec?.env;if(!Y)return null;for(let G of Y)if(G.name==="DAEMON_TOKEN"&&G.value)return G.value;return null}function DJ8(X){return X.metadata?.annotations?.[TG.POD_NAME_ANNOTATION]??X.metadata?.name??null}function BQ7(X,Y){let G=rG7("sha256").update(`${X}:${Y}`).digest();return Jy0+G.readUInt32BE(0)%EJ8}function Yy0(X,Y){return new Response(JSON.stringify(Y),{status:X,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function wJ8(X){let Y=X.slice(0,zQ7);return NQ7.test(Y)?Y:""}function Gy0(X,Y={}){let G={...Y};if(X){let Q=wJ8(X.orgId),J=wJ8(X.userId);if(Q)G[TT.orgId]=Q;if(J)G[TT.userId]=J}return G}function OQ7(X){let Y=X.metadata?.labels;if(!Y)return null;let G=Y[TT.orgId],Q=Y[TT.userId];if(!G||!Q)return null;return{orgId:G,userId:Q}}function Qy0(X){return{org_id:X?.orgId??"",user_id:X?.userId??"",runner_kind:pz}}function DQ7(X){let Y={};if(X.repo)Y.repo=X.repo;if(X.workload)Y.workload=X.workload;if(X.env&&Object.keys(X.env).length>0)Y.env=X.env;if(X.tenant)Y.tenant=X.tenant;return Object.keys(Y).length>0?Y:null}function wQ7(X,Y){try{return new URL(eT(X,Y)).hostname||null}catch{return null}}function LQ7(X){try{let Y=new URL(X);return Y.pathname.replace(/^\/+/,"").replace(/\.git$/,"")||Y.hostname}catch{return X}}var pz="agent-sandbox",iW="AgentSandboxRunner",XQ7="agent-sandbox-system",YQ7="studio-sandbox",bm=9000,GQ7=3000,eb0="/app",QQ7=32,JQ7,ZQ7=900000,a31="studio-sb-",WQ7=16,$Q7,OJ8,Jy0=40000,EJ8=1e4,KQ7=256,TT,NQ7,zQ7=63;var PJ8=D(()=>{mb0();gn1();v$1();nc1();c31();zJ8();JQ7=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT","DEV_PORT","RUNTIME","CLONE_URL","REPO_NAME","BRANCH","GIT_USER_NAME","GIT_USER_EMAIL","PACKAGE_MANAGER"]);$Q7=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],OJ8=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];TT={role:"studio.decocms.com/role",sandboxHandle:"studio.decocms.com/sandbox-handle",orgId:"studio.decocms.com/org-id",userId:"studio.decocms.com/user-id"},NQ7=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/});var qJ8={};M0(qJ8,{waitForSandboxReady:()=>pc1,getSandboxClaim:()=>fm,getHttpRoute:()=>HJ8,deleteSandboxClaim:()=>_m,deleteHttpRoute:()=>ic1,createSandboxClaim:()=>p31,createHttpRoute:()=>cc1,composeClaimName:()=>t31,SandboxTimeoutError:()=>hs,SandboxError:()=>rY,KubeConfig:()=>_s,K8S_CONSTANTS:()=>TG,HTTPROUTE_CONSTANTS:()=>n31,HANDLE_PREFIX:()=>a31,AgentSandboxRunner:()=>Zy0});var ac1=D(()=>{mb0();c31();nc1();PJ8()});var Ny0={};M0(Ny0,{subscribeLifecycle:()=>By0,getSharedRunnerIfInit:()=>Hy0,getSharedRunner:()=>r31,getRunnerByKind:()=>gs,getOrInitSharedRunner:()=>Ky0,asLifecycleWatchable:()=>Uy0,asDockerRunner:()=>Fy0,__resetSharedLifecyclesForTesting:()=>IQ7});function TJ8(X,Y){let G=$y0[X];if(G)return Promise.resolve(G);let Q=Wy0[X];if(Q)return Q;let J=Y().then((W)=>{return $y0[X]=W,W}).finally(()=>{delete Wy0[X]});return Wy0[X]=J,J}function EQ7(){let X=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return X&&X.trim()!==""?X:void 0}function PQ7(){let X=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return X&&X.trim()!==""?X:void 0}function qQ7(){let X=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME?.trim(),Y=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE?.trim();if(!X&&!Y)return;if(!X||!Y)throw Error("STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME and STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE must both be set, or both unset. Half-configured per-claim HTTPRoute routing would silently fail to attach.");return{name:X,namespace:Y}}async function IJ8(X,Y){let G=new D_0(Y),Q=EQ7();switch(X){case"docker":return new QF({stateStore:G,previewUrlPattern:Q});case"freestyle":{let{FreestyleSandboxRunner:J}=await Promise.resolve().then(() => (v58(),k58));return new J({stateStore:G})}case"agent-sandbox":{let{AgentSandboxRunner:J}=await Promise.resolve().then(() => (ac1(),qJ8));return new J({stateStore:G,previewUrlPattern:Q,sandboxTemplateName:PQ7(),previewGateway:qQ7(),meter:QU})}default:throw Error(`Unknown runner kind: ${String(X)}`)}}function r31(X){return gs(X,Rd())}function gs(X,Y){return TJ8(Y,()=>IJ8(Y,X.db))}async function Ky0(){let X=XI();if(!X)return null;return TJ8(X,()=>IJ8(X,t7().db))}function Hy0(){let X=XI();if(!X)return null;return $y0[X]??null}function Fy0(X){return X instanceof QF?X:null}function Uy0(X){if(!X)return null;if(X.kind!=="agent-sandbox")return null;if(typeof X.watchClaimLifecycle!=="function")return null;return X}function By0(X,Y,G){let Q=IT.get(Y);if(Q){if(Q.terminated){if(Q.lastPhase)try{G(Q.lastPhase)}catch{}return{unsubscribe:AQ7}}if(Q.listeners.add(G),Q.lastPhase)try{G(Q.lastPhase)}catch{}return AJ8(Y,Q,G)}let J=new AbortController,W={lastPhase:null,terminated:!1,listeners:new Set([G]),abort:J};return IT.set(Y,W),TQ7(X,Y,W),AJ8(Y,W,G)}function AQ7(){}function AJ8(X,Y,G){return{unsubscribe(){if(IT.get(X)!==Y)return;if(Y.listeners.delete(G),Y.listeners.size===0)IT.delete(X),Y.abort.abort()}}}async function TQ7(X,Y,G){let Q=null;try{for await(let J of X.watchClaimLifecycle(Y,G.abort.signal)){if(G.abort.signal.aborted)break;let W=J;G.lastPhase=W;let Z=W.kind==="ready"||W.kind==="failed";if(Z)G.terminated=!0;let $=Array.from(G.listeners);for(let K of $)try{K(W)}catch{}if(Z)break}}catch(J){Q=J}finally{if(!G.terminated&&!G.abort.signal.aborted&&G.listeners.size>0){let J={kind:"failed",reason:"unknown",message:Q instanceof Error?Q.message:"Lifecycle watcher ended unexpectedly"};G.lastPhase=J,G.terminated=!0;for(let W of Array.from(G.listeners))try{W(J)}catch{}}if(IT.get(Y)===G)IT.delete(Y)}}function IQ7(){for(let X of IT.values())X.abort.abort();IT.clear()}var $y0,Wy0,IT;var VT=D(()=>{dL();JU();A$();pp4();$y0={},Wy0={};IT=new Map});async function VJ8(X,Y){B0(Y);let G=s1(Y),Q=w4(Y);if(!Q)throw Error("User ID required");let J=await Y.storage.virtualMcps.findById(X.virtualMcpId);if(!J||J.organization_id!==G.id)throw Error("Virtual MCP not found");let W=J.metadata??{},Z=OC1(Ds(W),Q,X.branch),$=Rd();if(Z&&(Z.runnerKind??"freestyle")===$)return Z;await jJ8(Y,Z,$);let K=W.githubRepo??null,{entry:H}=await MJ8({ctx:Y,userId:Q,orgId:G.id,virtualMcpId:X.virtualMcpId,branch:X.branch,metadata:W,githubRepo:K,existing:Z});return H}async function jJ8(X,Y,G){if(!Y)return;let Q=Y.runnerKind??"freestyle";if(Q===G)return;if(Q==="freestyle")return;try{await(await gs(X,Q)).delete(Y.vmId)}catch(J){console.error(`[VM_START] stale ${Q} ${Y.vmId}: ${J instanceof Error?J.message:String(J)}`)}}async function MJ8(X){let{ctx:Y,userId:G,orgId:Q,virtualMcpId:J,branch:W,metadata:Z,githubRepo:$,existing:K}=X;if($&&!$.connectionId)throw Error("GitHub connection id missing on virtual MCP metadata");let{runtime:H,packageManager:U,port:B}=_p4(Z),N;if($){let{cloneUrl:V,gitUserName:R,gitUserEmail:k}=await fp4($.connectionId,$.owner,$.name,Y.db,Y.vault);if(!U){let _=await hp4($.connectionId,$.owner,$.name,Y.db,Y.vault);if(_)U=_.packageManager,H=w31[_.packageManager].runtime,B=_.devPort??B,await VQ7(Y,J,G,_.packageManager,_.devPort)}N={cloneUrl:V,userName:R,userEmail:k,branch:W,displayName:`${$.owner}/${$.name}`}}let z=H&&U?{runtime:H,packageManager:U,devPort:Number(B)}:void 0,O=Md({orgId:Q,virtualMcpId:J,branch:W}),w=await r31(Y),E=await w.ensure({userId:G,projectRef:O},{repo:N,workload:z,tenant:{orgId:Q,userId:G}}),q=!!K&&K.vmId===E.handle&&K?.createdAt?K.createdAt:Date.now(),M={vmId:E.handle,previewUrl:E.previewUrl,runnerKind:w.kind,createdAt:q};await kp4(Y.storage.virtualMcps,J,G,G,W,M);let j=!K||K.vmId!==E.handle;return{entry:M,isNewVm:j}}async function VQ7(X,Y,G,Q,J){let W=await X.storage.virtualMcps.findById(Y);if(!W)return;let Z=W.metadata??{};await X.storage.virtualMcps.update(Y,G,{metadata:{...Z,runtime:{selected:Q,port:J}}})}var zy0;var Oy0=D(()=>{H0();dL();x0();O_0();bp4();gp4();wC0();z_0();VT();zy0=m1({name:"VM_START",description:"Start a sandbox with the connected GitHub repo and dev server.",annotations:{title:"Start VM Preview",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:F.object({virtualMcpId:F.string().describe("Virtual MCP ID"),branch:F.string().min(1).optional().describe("Optional git branch to check out. When omitted the handler generates `deco/<adjective>-<noun>` and uses it. The resolved branch is returned in the response so callers can persist it.")}),outputSchema:F.object({previewUrl:F.string().nullable(),vmId:F.string(),branch:F.string(),isNewVm:F.boolean(),runnerKind:F.enum(["docker","freestyle","agent-sandbox"])}),handler:async(X,Y)=>{let G=X.branch??IS1(),{metadata:Q,userId:J,organization:W,entry:Z}=await DC1({virtualMcpId:X.virtualMcpId,branch:G},Y),$=Q.githubRepo;if(!$)throw Error("No GitHub repo connected");let K=Rd();await jJ8(Y,Z,K);let{entry:H,isNewVm:U}=await MJ8({ctx:Y,userId:J,orgId:W.id,virtualMcpId:X.virtualMcpId,branch:G,metadata:Q,githubRepo:$,existing:Z});return{...H,branch:G,isNewVm:U,runnerKind:K}}})});var Dy0;var RJ8=D(()=>{H0();x0();O_0();VT();Dy0=m1({name:"VM_DELETE",description:"Delete a sandbox.",annotations:{title:"Delete VM Preview",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:F.object({virtualMcpId:F.string().describe("Virtual MCP ID that owns this VM"),branch:F.string().min(1).describe("Branch whose vm should be deleted (vmMap[userId][branch])")}),outputSchema:F.object({success:F.boolean()}),handler:async(X,Y)=>{let G;try{G=await DC1(X,Y)}catch($){if($ instanceof Error&&$.message==="Virtual MCP not found")return{success:!0};throw $}let{entry:Q,userId:J}=G;if(!Q)return{success:!0};await vp4(Y.storage.virtualMcps,X.virtualMcpId,J,J,X.branch);let W=Q.runnerKind??"freestyle";return await(await gs(Y,W)).delete(Q.vmId).catch(($)=>console.error(`[VM_DELETE] ${W} ${Q.vmId}: ${$ instanceof Error?$.message:String($)}`)),{success:!0}}})});var SJ8=D(()=>{Oy0();RJ8()});var MQ7="https://api.github.com",wy0;var CJ8=D(()=>{H0();x0();iI1();xR();wy0=m1({name:"GITHUB_LIST_USER_ORGS",description:"List GitHub App installations (orgs/accounts) accessible to the authenticated user.",annotations:{title:"List GitHub User Orgs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:F.object({connectionId:F.string().describe("ID of the mcp-github connection to use")}),outputSchema:F.object({installations:F.array(F.object({installationId:F.number(),login:F.string(),avatarUrl:F.string(),type:F.string()})),appSlug:F.string().optional()}),handler:async(X,Y)=>{await Y.access.check();let G=new I3(Y.db,Y.vault),Q=await G.get(X.connectionId);if(!Q)throw Error("No GitHub token found. Ensure the mcp-github connection is authenticated.");let J=Q.accessToken;if(pY1(Q)&&G.isExpired(Q,cI1)){let U=await nY1(Q,G);if(!U)throw Error($M);J=U,Q=await G.get(X.connectionId)??Q}let W=[],Z,$=1,K=100,H=async(U)=>fetch(`${MQ7}/user/installations?per_page=${K}&page=${$}`,{headers:{Authorization:`Bearer ${U}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}});while(!0){let U=await H(J);if(U.status===401){let N=await G.get(X.connectionId);if(!N||!pY1(N))throw Error($M);let z=await nY1(N,G);if(!z)throw Error($M);if(J=z,U=await H(J),U.status===401)throw Error($M)}if(!U.ok)throw Error(`GitHub /user/installations failed: ${U.status}`);let B=await U.json();for(let N of B.installations){if(!Z)Z=N.app_slug??N.app?.slug;W.push({installationId:N.id,login:N.account.login,avatarUrl:N.account.avatar_url,type:N.account.type})}if(B.installations.length<K)break;$++}return{installations:W,...Z?{appSlug:Z}:{}}}})});var kJ8=D(()=>{CJ8()});var qS1={};M0(qS1,{managementMCP:()=>so,listManagementTools:()=>kQ7,ALL_TOOLS:()=>vJ8});async function kQ7(X){let Y=await so(X),[G,Q]=$Y1.createLinkedPair();await Y.connect(Q);let J=new hY({name:"tools-hydration",version:"1.0.0"});try{return await J.connect(G),(await J.listTools()).tools}finally{await J.close().catch(()=>{})}}var SQ7,CQ7,vJ8,so=async(X)=>{let Y=null;if(X.organization){let Z=await X.storage.organizationSettings.get(X.organization.id),$=await X.storage.virtualMcps.list(X.organization.id),K=new Set(Z?.enabled_plugins??[]);for(let H of $){let U=H.metadata?.enabled_plugins;if(U&&Array.isArray(U))for(let B of U)K.add(B)}Y=K.size>0?[...K]:null}let G=Fr6(vJ8,Y),Q=new cD({name:"mcp-cms-management",version:"1.0.0"},{capabilities:{tools:{},prompts:{},resources:{}}});for(let Z of G){let $=Z.inputSchema&&typeof Z.inputSchema==="object"&&"shape"in Z.inputSchema?Z.inputSchema:F.object({}),K=Z.outputSchema&&typeof Z.outputSchema==="object"&&"shape"in Z.outputSchema?Z.outputSchema:void 0,H=$.shape,U=K?.shape;Q.registerTool(Z.name,{description:Z.description??"",inputSchema:H,outputSchema:U,annotations:Z.annotations,_meta:Z._meta},async(B)=>{X.access.setToolName(Z.name);try{let N=await Z.execute(B,X);return{content:[{type:"text",text:JSON.stringify(N)}],structuredContent:N}}catch(N){return{content:[{type:"text",text:`Error: ${N.message}`}],isError:!0}}})}let J=Ex4();for(let Z of J)Q.registerPrompt(Z.name,{title:Z.title,description:Z.description},()=>({messages:[{role:"user",content:{type:"text",text:Z.text}}]}));if(X.organization?.id){let Z=await X.storage.brandContext.list(X.organization.id),$=new Set;for(let K of Z){let H=K.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),U=H?`brand-${H}`:`brand-${K.id}`;if($.has(U))U=`${U}-${K.id.slice(0,8)}`;$.add(U);let B=[`# Brand: ${K.name}`,"",`**Domain:** ${K.domain}`,"","## Overview",K.overview];if(K.colors){let z=Object.entries(K.colors).filter(([,O])=>O);if(z.length>0){B.push("","## Colors");for(let[O,w]of z)B.push(`- **${O}:** ${w}`)}}if(K.fonts){let z=Object.entries(K.fonts).filter(([,O])=>O);if(z.length>0){B.push("","## Fonts");for(let[O,w]of z)B.push(`- ${w} (${O})`)}}if(K.logo)B.push("",`**Logo:** ${K.logo}`);if(K.favicon)B.push(`**Favicon:** ${K.favicon}`);if(K.ogImage)B.push(`**OG Image:** ${K.ogImage}`);if(K.images&&K.images.length>0){B.push("","## Images");for(let z of K.images){let O=Object.entries(z).map(([w,E])=>`${w}: ${E}`).join(", ");B.push(`- ${O}`)}}let N=B.join(`
5054
+ `))>=0){let K=Q.slice(0,$).trim();if(Q=Q.slice($+1),!K)continue;yield JSON.parse(K)}}let J=Q.trim();if(J)yield JSON.parse(J)}finally{Y.releaseLock()}}var cb0,QJ8,ZJ8="gateway.networking.k8s.io",WJ8="v1",ab0="httproutes",$J8,n31,lG7="mesh-sandbox-runner";var nc1=D(()=>{c31();cb0=class cb0 extends Error{status;body;constructor(X,Y,G){super(G);this.status=X;this.body=Y;this.name="KubeHttpError"}};QJ8=`/apis/${TG.CLAIM_API_GROUP}/${TG.CLAIM_API_VERSION}/namespaces`;$J8=`/apis/${ZJ8}/${WJ8}/namespaces`;n31={API_GROUP:ZJ8,API_VERSION:WJ8,PLURAL:ab0}});async function*NJ8(X){let Y=X.now??(()=>Date.now()),G=Y(),Q=X.schedulingTimeoutMs??cG7,J={pod:{},sandbox:{},events:{hasPulling:!1,hasPulled:!1},startedAt:G},W=[],Z=null,$=!1,K=(E)=>{if($)return;if(Z){let P=Z;Z=null,P(E)}else W.push(E)},H=()=>{if(W.length>0)return Promise.resolve(W.shift());if($)return Promise.resolve(null);return new Promise((E)=>{Z=E})},U=()=>{if($)return;if($=!0,Z){let E=Z;Z=null,E(null)}},B=new AbortController,N=()=>{B.abort(),U()};if(X.signal)if(X.signal.aborted)B.abort(),U();else X.signal.addEventListener("abort",N,{once:!0});let z=Math.max(0,Q-(Y()-G)),O=setTimeout(()=>K("tick"),z+100),w=Promise.allSettled([iG7(X.kc,X.namespace,X.claimName,B.signal,J,K,Y),nG7(X.kc,X.namespace,X.claimName,B.signal,J,K),aG7(X.kc,X.namespace,X.claimName,B.signal,J,K,Y)]);try{let E=null,P=-1,q=UJ8(J,Q,Y);if(E=ob0(q),!rb0(q))P=BJ8(q);if(yield q,rb0(q))return;while(!$){if(await H()===null)break;let j=UJ8(J,Q,Y);if(rb0(j)){let k=ob0(j);if(k!==E)E=k,yield j;return}let V=BJ8(j);if(V<P)continue;let R=ob0(j);if(R!==E)E=R,P=V,yield j}}finally{if(clearTimeout(O),B.abort(),X.signal)X.signal.removeEventListener("abort",N);U(),await w.catch(()=>{})}}function UJ8(X,Y,G){let{pod:Q,sandbox:J,events:W,startedAt:Z}=X;if(J.ready)return{kind:"ready"};let $=Q.containerWaitingReason;if($==="ImagePullBackOff"||$==="ErrImagePull")return{kind:"failed",reason:"image-pull-backoff",message:"Sandbox image failed to download. The cluster may be missing pull credentials or the image tag may not exist."};if($==="CrashLoopBackOff")return{kind:"failed",reason:"crash-loop-backoff",message:"Sandbox crashed during startup and is now in CrashLoopBackOff. Check pod logs."};if(!Q.scheduled&&W.lastFailedSchedulingAt!==void 0&&G()-Z>Y)return{kind:"failed",reason:"scheduling-timeout",message:W.failedSchedulingMessage??`Pod could not be scheduled within ${Math.round(Y/1000)}s.`};if(Q.containerRunning&&!Q.containerReady)return{kind:"warming-daemon",since:Z};if($==="ContainerCreating"&&W.hasPulled)return{kind:"starting-container",since:Z};if(W.hasPulling&&!W.hasPulled)return{kind:"pulling-image",since:Z};if(Q.scheduledFalseReason==="Unschedulable"||W.lastFailedSchedulingAt!==void 0&&!Q.scheduled)return{kind:"waiting-for-capacity",since:Z,message:W.failedSchedulingMessage??Q.scheduledFalseMessage,nodeClaim:W.nominatedNodeClaim};return{kind:"claiming",since:Z}}function rb0(X){return X.kind==="ready"||X.kind==="failed"}function BJ8(X){switch(X.kind){case"claiming":return 0;case"waiting-for-capacity":return 1;case"pulling-image":return 2;case"starting-container":return 3;case"warming-daemon":return 4;case"ready":case"failed":return 99}}function ob0(X){switch(X.kind){case"claiming":case"pulling-image":case"starting-container":case"warming-daemon":return X.kind;case"waiting-for-capacity":return`waiting-for-capacity:${X.message??""}:${X.nodeClaim??""}`;case"ready":return"ready";case"failed":return`failed:${X.reason}:${X.message}`}}async function iG7(X,Y,G,Q,J,W,Z){let $=`/api/v1/namespaces/${encodeURIComponent(Y)}/pods?watch=true&labelSelector=${encodeURIComponent(`${mG7}=${G}`)}`;return sb0({kc:X,path:$,signal:Q,label:`pod/${G}`,onEvent:(K)=>{if(K.type!=="ADDED"&&K.type!=="MODIFIED")return;let H=K.object;if(H.metadata?.name!==G)return;pG7(H,J,Z),W("pod")}})}function pG7(X,Y,G){let J=(X.status?.conditions??[]).find((Z)=>Z.type==="PodScheduled");if(J?.status==="True")Y.pod.scheduled=!0,Y.pod.scheduledFalseReason=void 0,Y.pod.scheduledFalseMessage=void 0;else if(J?.status==="False")Y.pod.scheduled=!1,Y.pod.scheduledFalseReason=J.reason,Y.pod.scheduledFalseMessage=J.message;let W=(X.status?.containerStatuses??[]).find((Z)=>Z.name===dG7);if(W)Y.pod.containerWaitingReason=W.state?.waiting?.reason,Y.pod.containerRunning=!!W.state?.running,Y.pod.containerReady=W.ready===!0}async function nG7(X,Y,G,Q,J,W){let Z=`/apis/${TG.SANDBOX_API_GROUP}/${TG.SANDBOX_API_VERSION}/namespaces/${encodeURIComponent(Y)}/${TG.SANDBOX_PLURAL}?watch=true&fieldSelector=${encodeURIComponent(`metadata.name=${G}`)}`;return sb0({kc:X,path:Z,signal:Q,label:`sandbox/${G}`,onEvent:($)=>{if($.type!=="ADDED"&&$.type!=="MODIFIED")return;let H=$.object.status?.conditions?.find((U)=>U.type==="Ready");if(!H)return;if(H.status==="True")J.sandbox.ready=!0,J.sandbox.notReadyReason=void 0,J.sandbox.notReadyMessage=void 0;else J.sandbox.ready=!1,J.sandbox.notReadyReason=H.reason,J.sandbox.notReadyMessage=H.message;W("sandbox")}})}async function aG7(X,Y,G,Q,J,W,Z){let $=`/api/v1/namespaces/${encodeURIComponent(Y)}/events?watch=true&fieldSelector=${encodeURIComponent(`involvedObject.name=${G},involvedObject.kind=Pod`)}`;return sb0({kc:X,path:$,signal:Q,label:`events/${G}`,onEvent:(K)=>{if(K.type!=="ADDED"&&K.type!=="MODIFIED")return;let H=K.object,U=H.reason;if(!U)return;switch(U){case"Pulling":J.events.hasPulling=!0;break;case"Pulled":J.events.hasPulling=!0,J.events.hasPulled=!0;break;case"FailedScheduling":J.events.lastFailedSchedulingAt=Z(),J.events.failedSchedulingMessage=H.message;break;case"Nominated":{let B=H.message?.match(/nodeclaim\/([\w-]+)/);if(B)J.events.nominatedNodeClaim=B[1];break}default:return}W("event")}})}async function sb0(X){let{kc:Y,path:G,signal:Q,label:J,onEvent:W}=X,Z=0;while(!Q.aborted){try{let K=await vm(Y,{method:"GET",path:G,signal:Q,headers:{accept:"application/json"}});if(!K.ok||!K.body){try{await K.body?.cancel()}catch{}throw Error(`watch handshake failed: ${K.status} ${K.statusText}`)}Z=0;for await(let H of tb0(K.body)){if(Q.aborted)return;try{W(H)}catch(U){console.warn(`[lifecycle-watcher] ${J} onEvent threw: ${U instanceof Error?U.message:String(U)}`)}}}catch(K){if(Q.aborted)return;let H=K instanceof Error?K.message:String(K);console.warn(`[lifecycle-watcher] ${J} watch ended: ${H}`)}if(Q.aborted)return;let $=Math.min(250*2**Z,5000);Z+=1,await tG7($,Q)}}function tG7(X,Y){return new Promise((G)=>{if(Y.aborted){G();return}let Q=setTimeout(()=>{Y.removeEventListener("abort",J),G()},X),J=()=>{clearTimeout(Q),G()};Y.addEventListener("abort",J,{once:!0})})}var mG7="studio.decocms.com/sandbox-handle",dG7="sandbox",cG7=300000;var zJ8=D(()=>{c31();nc1()});import{createHash as rG7,randomBytes as oG7,randomUUID as sG7}from"crypto";import*as LJ8 from"net";import{PassThrough as eG7}from"stream";function t31(X,Y){return`${a31}${sT(X,Y,{hashLen:WQ7})}`}class Zy0{kind=pz;records=new Map;inflight=new mL;stateStore;previewUrlPattern;kubeConfig;portForward;namespace;sandboxTemplateName;tokenGenerator;idleTtlMs;metrics;previewGateway;closed=!1;constructor(X={}){this.stateStore=X.stateStore??null,this.previewUrlPattern=X.previewUrlPattern??null,this.kubeConfig=X.kubeConfig??FQ7(),this.portForward=new jb0(this.kubeConfig),this.namespace=X.namespace??XQ7,this.sandboxTemplateName=X.sandboxTemplateName??YQ7,this.tokenGenerator=X.tokenGenerator??(()=>oG7(QQ7).toString("hex")),this.idleTtlMs=X.idleTtlMs??ZQ7,this.metrics=X.meter?HQ7(X.meter):null,this.previewGateway=X.previewGateway&&X.previewUrlPattern?{...X.previewGateway}:null}async ensure(X,Y={}){let G=this.computeHandle(X,Y.repo?.branch??null);return this.inflight.run(G,()=>oT(this.stateStore,X,pz,(Q)=>this.ensureLocked(X,G,Y,Q)))}async exec(X,Y){let G=await this.requireRecord(X);return M$1(G.daemonUrl,G.token,Y)}async delete(X){let Y=await this.getRecord(X);if(this.records.delete(X),Y)this.closeForwarder(Y.daemonForward),this.metrics?.active.add(-1,Qy0(Y.tenant));if(await this.deleteHttpRouteIfManaged(X).catch((G)=>{console.warn(`[${iW}] HTTPRoute delete failed for ${X}: ${G instanceof Error?G.message:String(G)}`)}),await _m(this.kubeConfig,this.namespace,X),this.stateStore)if(Y)await this.stateStore.delete(Y.id,pz);else await this.stateStore.deleteByHandle(pz,X)}async alive(X){let Y=await fm(this.kubeConfig,this.namespace,X).catch(()=>{return});return Y?Xy0(Y):!1}watchClaimLifecycle(X,Y){return NJ8({kc:this.kubeConfig,namespace:this.namespace,claimName:X,signal:Y})}async getPreviewUrl(X){let Y=await this.getRecord(X);if(!Y)return null;return this.composePreviewUrl(Y)}async proxyDaemonRequest(X,Y,G){let Q=await this.getRecord(X);if(!Q)return new Response(JSON.stringify({error:"sandbox not found"}),{status:404,headers:{"content-type":"application/json"}});let J=performance.now(),W=0;try{let Z=await R$1(Q.daemonUrl,Q.token,Y,G);return W=Z.status,Z}finally{this.recordProxyDuration("daemon",W,Q,performance.now()-J)}}async resolvePreviewUpstreamUrl(X){if(this.previewUrlPattern)return`http://${X}.${this.namespace}.svc.cluster.local:${bm}`;let Y=await this.getRecord(X);if(Y)return Y.daemonUrl;let G=await this.resurrectByHandle(X);return G?G.daemonUrl:null}async proxyPreviewRequest(X,Y){let G=performance.now(),Q=this.records.get(X)??null,J=0;try{let W=await this.resolvePreviewUpstreamUrl(X);if(!W)return J=404,Yy0(404,{error:"sandbox not found"});let Z=new URL(Y.url);if((Z.pathname==="/_decopilot_vm"||Z.pathname.startsWith("/_decopilot_vm/"))&&Y.method!=="GET")return J=404,Yy0(404,{error:"not found"});let K=(O)=>`${O}${Z.pathname}${Z.search}`,H=new Headers(Y.headers);for(let O of $Q7)H.delete(O);let U=Y.method!=="GET"&&Y.method!=="HEAD",B={method:Y.method,headers:H,body:U?Y.body:void 0,redirect:"manual",signal:Y.signal,duplex:U?"half":void 0},N;try{N=await fetch(K(W),B)}catch(O){let w=`${W}${Z.pathname}`;if(console.warn(`[${iW}] preview fetch to ${w} failed: ${O instanceof Error?O.message:String(O)}`),Y.method==="GET"||Y.method==="HEAD"){if(this.invalidateRecord(X),await this.resurrectByHandle(X).catch(()=>null)){let P=await this.resolvePreviewUpstreamUrl(X);if(P)try{N=await fetch(K(P),B);let q=new Headers;for(let[M,j]of N.headers.entries())if(!OJ8.includes(M.toLowerCase()))q.set(M,j);return J=N.status,new Response(N.body,{status:N.status,statusText:N.statusText,headers:q})}catch(q){console.warn(`[${iW}] preview fetch retry to ${w} failed: ${q instanceof Error?q.message:String(q)}`)}}}else this.invalidateRecord(X);return J=502,Yy0(502,{error:"sandbox daemon unreachable"})}let z=new Headers;for(let[O,w]of N.headers.entries())if(!OJ8.includes(O.toLowerCase()))z.set(O,w);return J=N.status,new Response(N.body,{status:N.status,statusText:N.statusText,headers:z})}finally{this.recordProxyDuration("preview",J,Q,performance.now()-G,X)}}async ensureLocked(X,Y,G,Q){if(G.image)console.warn(`[${iW}] opts.image ignored (template ${this.sandboxTemplateName} pins image): got ${G.image}`);if(Q){let Z=await Q.get(X,pz);if(Z){let $=await this.rehydrate(X,Y,Z);if($)return this.finish($,Q,!1,!0,"resume");await Q.delete(X,pz)}}let J=await fm(this.kubeConfig,this.namespace,Y).catch(()=>{return});if(J)if(J.metadata?.deletionTimestamp)await dc1(this.kubeConfig,this.namespace,Y).catch((Z)=>{console.warn(`[${iW}] wait for terminating claim ${Y} failed: ${Z instanceof Error?Z.message:String(Z)}`)});else{let Z=await this.adopt(X,Y,J).catch(($)=>{return console.warn(`[${iW}] adopt ${Y} failed, recreating: ${$ instanceof Error?$.message:String($)}`),null});if(Z)return this.finish(Z,Q,!0,!0,"adopt");await _m(this.kubeConfig,this.namespace,Y).catch(()=>{}),await dc1(this.kubeConfig,this.namespace,Y).catch(($)=>{console.warn(`[${iW}] wait for deleted claim ${Y} failed: ${$ instanceof Error?$.message:String($)}`)})}let W=await this.provision(X,Y,G);return this.finish(W,Q,!0,!1,"fresh")}async finish(X,Y,G,Q,J){let W=this.records.has(X.handle);if(this.records.set(X.handle,X),G)await this.persist(Y,X);if(Q)await JJ8(this.kubeConfig,this.namespace,X.handle,this.computeShutdownTime()).catch((Z)=>console.warn(`[${iW}] TTL refresh failed for ${X.handle}: ${Z instanceof Error?Z.message:String(Z)}`));if(this.metrics){let Z=Qy0(X.tenant);if(this.metrics.ensureOutcome.add(1,{...Z,outcome:J}),!W)this.metrics.active.add(1,Z)}return this.toSandbox(X)}buildEnvMap(X,Y){let G={},Q=[];for(let[Z,$]of Object.entries(X.env??{}))if(JQ7.has(Z))Q.push(Z);else G[Z]=$;if(Q.length>0)console.warn(`[${iW}] opts.env keys overlap reserved bootstrap names and were dropped: ${Q.join(",")}`);let J=X.repo,W=J?J.displayName??LQ7(J.cloneUrl):null;return{...G,DAEMON_TOKEN:Y.token,DAEMON_BOOT_ID:Y.daemonBootId,APP_ROOT:Y.workdir,PROXY_PORT:String(bm),DEV_PORT:String(X.workload?.devPort??GQ7),RUNTIME:X.workload?.runtime??"node",...J?{CLONE_URL:J.cloneUrl,REPO_NAME:W??"",BRANCH:J.branch??"",GIT_USER_NAME:J.userName,GIT_USER_EMAIL:J.userEmail}:{},...X.workload?.packageManager?{PACKAGE_MANAGER:X.workload.packageManager}:{}}}buildClaim(X,Y,G){let Q=this.buildEnvMap(Y,G);return{apiVersion:`${TG.CLAIM_API_GROUP}/${TG.CLAIM_API_VERSION}`,kind:"SandboxClaim",metadata:{name:X,namespace:this.namespace,labels:{"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio",...Gy0(Y.tenant)}},spec:{sandboxTemplateRef:{name:this.sandboxTemplateName},additionalPodMetadata:{labels:Gy0(Y.tenant,{[TT.role]:"claimed",[TT.sandboxHandle]:X})},env:Object.entries(Q).sort(([J],[W])=>J<W?-1:J>W?1:0).map(([J,W])=>({name:J,value:W})),warmpool:"none",lifecycle:{shutdownPolicy:"Delete",shutdownTime:this.computeShutdownTime()}}}}async provision(X,Y,G){let Q=this.tokenGenerator(),J=sG7(),W=eb0,Z=this.buildClaim(Y,G,{token:Q,daemonBootId:J,workdir:W});try{await p31(this.kubeConfig,this.namespace,Z)}catch(U){if(U instanceof d31)await dc1(this.kubeConfig,this.namespace,Y),await p31(this.kubeConfig,this.namespace,Z);else throw U}let{podName:$}=await pc1(this.kubeConfig,this.namespace,Y);try{await this.ensureServicePortForHandle(Y),await this.ensureHttpRouteForHandle(Y,G.tenant??null)}catch(U){throw await _m(this.kubeConfig,this.namespace,Y).catch(()=>{}),U}let K=await this.openForwarder($,bm,Y),H=`http://127.0.0.1:${K.localPort}`;try{await j$1(H)}catch(U){throw this.closeForwarder(K),await this.deleteHttpRouteIfManaged(Y).catch(()=>{}),await _m(this.kubeConfig,this.namespace,Y).catch(()=>{}),U}return{id:X,handle:Y,podName:$,token:Q,workdir:W,daemonUrl:H,daemonForward:K,workload:G.workload??null,daemonBootId:J,tenant:G.tenant??null,ensureOpts:DQ7(G)}}async ensureServicePortForHandle(X){if(!this.previewGateway||!this.previewUrlPattern)return;await FJ8(this.kubeConfig,this.namespace,X,{name:"daemon",port:bm,targetPort:bm})}async ensureHttpRouteForHandle(X,Y){if(!this.previewGateway||!this.previewUrlPattern)return;let G=wQ7(this.previewUrlPattern,X);if(!G)throw new rY(`Unable to derive preview hostname for ${X} from pattern: ${this.previewUrlPattern}`);let Q={apiVersion:`${n31.API_GROUP}/${n31.API_VERSION}`,kind:"HTTPRoute",metadata:{name:X,namespace:this.namespace,labels:Gy0(Y??void 0,{[TT.role]:"claimed",[TT.sandboxHandle]:X,"app.kubernetes.io/name":"studio-sandbox","app.kubernetes.io/managed-by":"studio"})},spec:{parentRefs:[{kind:"Gateway",group:"gateway.networking.k8s.io",name:this.previewGateway.name,namespace:this.previewGateway.namespace}],hostnames:[G],rules:[{backendRefs:[{group:"",kind:"Service",name:X,port:bm}]}]}};await cc1(this.kubeConfig,this.namespace,Q)}async deleteHttpRouteIfManaged(X){if(!this.previewGateway)return;await ic1(this.kubeConfig,this.namespace,X)}async rehydrate(X,Y,G){let Q=G.state;if(!Q.podName||!Q.token)return null;let J=await fm(this.kubeConfig,this.namespace,Y).catch(()=>{return});if(!J||!Xy0(J))return null;let W=DJ8(J)??Q.podName,Z=await this.openAndProbeDaemon(W,Y);if(!Z)return null;if(Q.daemonBootId&&Q.daemonBootId!==Z.bootId)console.warn(`[${iW}] daemon restart detected (handle=${Y}): stored bootId=${Q.daemonBootId} live bootId=${Z.bootId}`);return{id:X,handle:Y,podName:W,token:Q.token,workdir:Q.workdir??eb0,daemonUrl:Z.daemonUrl,daemonForward:Z.daemonForward,workload:Q.workload??null,daemonBootId:Z.bootId,tenant:Q.tenant??null,ensureOpts:Q.ensureOpts??null}}async adopt(X,Y,G){if(!Xy0(G))return null;let Q=DJ8(G);if(!Q)return null;let J=UQ7(G);if(!J)return null;let W=await this.openAndProbeDaemon(Q,Y);if(!W)return null;let Z=OQ7(G);if(this.previewGateway)await this.ensureServicePortForHandle(Y).catch(($)=>{console.warn(`[${iW}] Service port backfill failed for ${Y}: ${$ instanceof Error?$.message:String($)}`)}),await this.ensureHttpRouteForHandle(Y,Z).catch(($)=>{console.warn(`[${iW}] HTTPRoute backfill failed for ${Y}: ${$ instanceof Error?$.message:String($)}`)});return{id:X,handle:Y,podName:Q,token:J,workdir:eb0,daemonUrl:W.daemonUrl,daemonForward:W.daemonForward,workload:null,daemonBootId:W.bootId,tenant:Z,ensureOpts:null}}async openAndProbeDaemon(X,Y){let G=await this.openForwarder(X,bm,Y).catch(()=>null);if(!G)return null;let Q=`http://127.0.0.1:${G.localPort}`,J=await Id(Q);if(!J)return this.closeForwarder(G),null;return{daemonForward:G,daemonUrl:Q,bootId:J.bootId}}async getRecord(X){let Y=this.records.get(X);if(Y)return Y;if(!this.stateStore)return null;let G=await this.stateStore.getByHandle(pz,X);if(!G)return null;let Q=await this.rehydrate(G.id,X,G);if(Q)this.records.set(X,Q);return Q}async resurrectByHandle(X){if(!this.stateStore)return null;let Y=await this.stateStore.getByHandle(pz,X);if(!Y)return null;let G=Y.state.ensureOpts;if(!G)return null;return await this.ensure(Y.id,G),this.records.get(X)??null}async requireRecord(X){let Y=await this.getRecord(X);if(Y)return Y;let G=await this.resurrectByHandle(X);if(G)return G;throw Error(`unknown sandbox handle ${X}`)}invalidateRecord(X){let Y=this.records.get(X);if(!Y)return;this.records.delete(X),this.closeForwarder(Y.daemonForward)}recordProxyDuration(X,Y,G,Q,J){if(!this.metrics)return;this.metrics.proxyDurationMs.record(Q,{...Qy0(G?.tenant??null),source:X,sandbox_handle:G?.handle??J??"",status_code:Y||0})}computeHandle(X,Y){return t31(X,Y)}composePreviewUrl(X){if(this.previewUrlPattern)return eT(this.previewUrlPattern,X.handle);return`http://127.0.0.1:${X.daemonForward.localPort}/`}toSandbox(X){return{handle:X.handle,workdir:X.workdir,previewUrl:this.composePreviewUrl(X)}}async persist(X,Y){if(!X)return;let G={podName:Y.podName,token:Y.token,workdir:Y.workdir,workload:Y.workload,daemonBootId:Y.daemonBootId,tenant:Y.tenant,...Y.ensureOpts?{ensureOpts:Y.ensureOpts}:{}};await X.put(Y.id,pz,{handle:Y.handle,state:G})}computeShutdownTime(){return new Date(Date.now()+this.idleTtlMs).toISOString()}openForwarder(X,Y,G=X){let Q=BQ7(G,Y);return new Promise((J,W)=>{let Z=($,K)=>{let H=LJ8.createServer((U)=>this.handleForwardedConnection(U,X,Y,G));H.once("error",(U)=>{if(U.code==="EADDRINUSE"&&K<KQ7){try{H.close()}catch{}let B=Jy0+($-Jy0+1)%EJ8;Z(B,K+1);return}W(U)}),H.listen($,"127.0.0.1",()=>{let U=H.address();if(!U||typeof U==="string"){H.close(),W(Error("port-forward listener failed to bind"));return}J({server:H,localPort:U.port})})};Z(Q,0)})}handleForwardedConnection(X,Y,G,Q){let J=new eG7,W=null,Z=!1,$=()=>{if(Z)return;if(Z=!0,J.destroy(),W)try{W.close()}catch{}if(!X.destroyed)X.destroy()};X.pipe(J),X.on("error",$),X.on("close",$),this.portForward.portForward(this.namespace,Y,[G],X,null,J).then((K)=>{let H=typeof K==="function"?K():K;if(!H){$();return}if(W=H,W.on("close",$),W.on("error",()=>{this.invalidateRecord(Q),$()}),Z)try{W.close()}catch{}}).catch((K)=>{console.warn(`[${iW}] port-forward to ${Y}:${G} failed: ${K instanceof Error?K.message:String(K)}`),this.invalidateRecord(Q),$()})}closeForwarder(X){X.server.close((Y)=>{if(Y)console.warn(`[${iW}] port-forward close on :${X.localPort} errored: ${Y instanceof Error?Y.message:String(Y)}`)})}close(){if(this.closed)return;this.closed=!0;for(let X of this.records.values())this.closeForwarder(X.daemonForward);this.records.clear()}}function HQ7(X){return{active:X.createUpDownCounter("studio.sandbox.active",{description:"Active sandbox count, by runner kind and owning org. Cross-checks the cAdvisor-derived count from the cluster \u2014 divergence between the two indicates orphaned claims (mesh deleted but K8s didn't reap) or unattributed pods.",unit:"{sandbox}"}),ensureOutcome:X.createCounter("studio.sandbox.ensure.outcome",{description:"Outcome of each ensure() call: fresh provision, resume from state-store after restart, or adopt of a cluster-side claim mesh didn't know about. Cold-start ratio is the primary input for warm-pool sizing.",unit:"{call}"}),proxyDurationMs:X.createHistogram("studio.sandbox.proxy.duration_ms",{description:"Wall-clock latency of mesh-mediated requests to the sandbox daemon: tool exec proxies (source=daemon) and preview iframe traffic (source=preview).",unit:"ms"})}}function FQ7(){let X=new _s;return X.loadFromDefault(),X}function Xy0(X){return Boolean(X.status?.conditions?.some((Y)=>Y.type==="Ready"&&Y.status==="True"))}function UQ7(X){let Y=X.spec?.env;if(!Y)return null;for(let G of Y)if(G.name==="DAEMON_TOKEN"&&G.value)return G.value;return null}function DJ8(X){return X.metadata?.annotations?.[TG.POD_NAME_ANNOTATION]??X.metadata?.name??null}function BQ7(X,Y){let G=rG7("sha256").update(`${X}:${Y}`).digest();return Jy0+G.readUInt32BE(0)%EJ8}function Yy0(X,Y){return new Response(JSON.stringify(Y),{status:X,headers:{"content-type":"application/json","access-control-allow-origin":"*"}})}function wJ8(X){let Y=X.slice(0,zQ7);return NQ7.test(Y)?Y:""}function Gy0(X,Y={}){let G={...Y};if(X){let Q=wJ8(X.orgId),J=wJ8(X.userId);if(Q)G[TT.orgId]=Q;if(J)G[TT.userId]=J}return G}function OQ7(X){let Y=X.metadata?.labels;if(!Y)return null;let G=Y[TT.orgId],Q=Y[TT.userId];if(!G||!Q)return null;return{orgId:G,userId:Q}}function Qy0(X){return{org_id:X?.orgId??"",user_id:X?.userId??"",runner_kind:pz}}function DQ7(X){let Y={};if(X.repo)Y.repo=X.repo;if(X.workload)Y.workload=X.workload;if(X.env&&Object.keys(X.env).length>0)Y.env=X.env;if(X.tenant)Y.tenant=X.tenant;return Object.keys(Y).length>0?Y:null}function wQ7(X,Y){try{return new URL(eT(X,Y)).hostname||null}catch{return null}}function LQ7(X){try{let Y=new URL(X);return Y.pathname.replace(/^\/+/,"").replace(/\.git$/,"")||Y.hostname}catch{return X}}var pz="agent-sandbox",iW="AgentSandboxRunner",XQ7="agent-sandbox-system",YQ7="studio-sandbox",bm=9000,GQ7=3000,eb0="/app",QQ7=32,JQ7,ZQ7=900000,a31="studio-sb-",WQ7=16,$Q7,OJ8,Jy0=40000,EJ8=1e4,KQ7=256,TT,NQ7,zQ7=63;var PJ8=D(()=>{mb0();gn1();v$1();nc1();c31();zJ8();JQ7=new Set(["DAEMON_TOKEN","DAEMON_BOOT_ID","APP_ROOT","PROXY_PORT","DEV_PORT","RUNTIME","CLONE_URL","REPO_NAME","BRANCH","GIT_USER_NAME","GIT_USER_EMAIL","PACKAGE_MANAGER"]);$Q7=["cookie","host","connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","accept-encoding","content-length","upgrade"],OJ8=["connection","keep-alive","transfer-encoding","content-encoding","content-length"];TT={role:"studio.decocms.com/role",sandboxHandle:"studio.decocms.com/sandbox-handle",orgId:"studio.decocms.com/org-id",userId:"studio.decocms.com/user-id"},NQ7=/^([A-Za-z0-9]([-A-Za-z0-9_.]*[A-Za-z0-9])?)?$/});var qJ8={};M0(qJ8,{waitForSandboxReady:()=>pc1,getSandboxClaim:()=>fm,getHttpRoute:()=>HJ8,deleteSandboxClaim:()=>_m,deleteHttpRoute:()=>ic1,createSandboxClaim:()=>p31,createHttpRoute:()=>cc1,composeClaimName:()=>t31,SandboxTimeoutError:()=>hs,SandboxError:()=>rY,KubeConfig:()=>_s,K8S_CONSTANTS:()=>TG,HTTPROUTE_CONSTANTS:()=>n31,HANDLE_PREFIX:()=>a31,AgentSandboxRunner:()=>Zy0});var ac1=D(()=>{mb0();c31();nc1();PJ8()});var Ny0={};M0(Ny0,{subscribeLifecycle:()=>By0,getSharedRunnerIfInit:()=>Hy0,getSharedRunner:()=>r31,getRunnerByKind:()=>gs,getOrInitSharedRunner:()=>Ky0,asLifecycleWatchable:()=>Uy0,asDockerRunner:()=>Fy0,__resetSharedLifecyclesForTesting:()=>IQ7});function TJ8(X,Y){let G=$y0[X];if(G)return Promise.resolve(G);let Q=Wy0[X];if(Q)return Q;let J=Y().then((W)=>{return $y0[X]=W,W}).finally(()=>{delete Wy0[X]});return Wy0[X]=J,J}function EQ7(){let X=process.env.STUDIO_SANDBOX_PREVIEW_URL_PATTERN;return X&&X.trim()!==""?X:void 0}function PQ7(){let X=process.env.STUDIO_SANDBOX_TEMPLATE_NAME;return X&&X.trim()!==""?X:void 0}function qQ7(){let X=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME?.trim(),Y=process.env.STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE?.trim();if(!X&&!Y)return;if(!X||!Y)throw Error("STUDIO_SANDBOX_PREVIEW_GATEWAY_NAME and STUDIO_SANDBOX_PREVIEW_GATEWAY_NAMESPACE must both be set, or both unset. Half-configured per-claim HTTPRoute routing would silently fail to attach.");return{name:X,namespace:Y}}async function IJ8(X,Y){let G=new D_0(Y),Q=EQ7();switch(X){case"docker":return new QF({stateStore:G,previewUrlPattern:Q});case"freestyle":{let{FreestyleSandboxRunner:J}=await Promise.resolve().then(() => (v58(),k58));return new J({stateStore:G})}case"agent-sandbox":{let{AgentSandboxRunner:J}=await Promise.resolve().then(() => (ac1(),qJ8));return new J({stateStore:G,previewUrlPattern:Q,sandboxTemplateName:PQ7(),previewGateway:qQ7(),meter:QU})}default:throw Error(`Unknown runner kind: ${String(X)}`)}}function r31(X){return gs(X,Rd())}function gs(X,Y){return TJ8(Y,()=>IJ8(Y,X.db))}async function Ky0(){let X=XI();if(!X)return null;return TJ8(X,()=>IJ8(X,t7().db))}function Hy0(){let X=XI();if(!X)return null;return $y0[X]??null}function Fy0(X){return X instanceof QF?X:null}function Uy0(X){if(!X)return null;if(X.kind!=="agent-sandbox")return null;if(typeof X.watchClaimLifecycle!=="function")return null;return X}function By0(X,Y,G){let Q=IT.get(Y);if(Q){if(Q.terminated){if(Q.lastPhase)try{G(Q.lastPhase)}catch{}return{unsubscribe:AQ7}}if(Q.listeners.add(G),Q.lastPhase)try{G(Q.lastPhase)}catch{}return AJ8(Y,Q,G)}let J=new AbortController,W={lastPhase:null,terminated:!1,listeners:new Set([G]),abort:J};return IT.set(Y,W),TQ7(X,Y,W),AJ8(Y,W,G)}function AQ7(){}function AJ8(X,Y,G){return{unsubscribe(){if(IT.get(X)!==Y)return;if(Y.listeners.delete(G),Y.listeners.size===0)IT.delete(X),Y.abort.abort()}}}async function TQ7(X,Y,G){let Q=null;try{for await(let J of X.watchClaimLifecycle(Y,G.abort.signal)){if(G.abort.signal.aborted)break;let W=J;G.lastPhase=W;let Z=W.kind==="ready"||W.kind==="failed";if(Z)G.terminated=!0;let $=Array.from(G.listeners);for(let K of $)try{K(W)}catch{}if(Z)break}}catch(J){Q=J}finally{if(!G.terminated&&!G.abort.signal.aborted&&G.listeners.size>0){let J={kind:"failed",reason:"unknown",message:Q instanceof Error?Q.message:"Lifecycle watcher ended unexpectedly"};G.lastPhase=J,G.terminated=!0;for(let W of Array.from(G.listeners))try{W(J)}catch{}}if(IT.get(Y)===G)IT.delete(Y)}}function IQ7(){for(let X of IT.values())X.abort.abort();IT.clear()}var $y0,Wy0,IT;var VT=D(()=>{dL();JU();A$();pp4();$y0={},Wy0={};IT=new Map});async function VJ8(X,Y){B0(Y);let G=s1(Y),Q=w4(Y);if(!Q)throw Error("User ID required");let J=await Y.storage.virtualMcps.findById(X.virtualMcpId);if(!J||J.organization_id!==G.id)throw Error("Virtual MCP not found");let W=J.metadata??{},Z=OC1(Ds(W),Q,X.branch),$=Rd();if(Z&&(Z.runnerKind??"freestyle")===$)return Z;await jJ8(Y,Z,$);let K=W.githubRepo??null,{entry:H}=await MJ8({ctx:Y,userId:Q,orgId:G.id,virtualMcpId:X.virtualMcpId,branch:X.branch,metadata:W,githubRepo:K,existing:Z});return H}async function jJ8(X,Y,G){if(!Y)return;let Q=Y.runnerKind??"freestyle";if(Q===G)return;if(Q==="freestyle")return;try{await(await gs(X,Q)).delete(Y.vmId)}catch(J){console.error(`[VM_START] stale ${Q} ${Y.vmId}: ${J instanceof Error?J.message:String(J)}`)}}async function MJ8(X){let{ctx:Y,userId:G,orgId:Q,virtualMcpId:J,branch:W,metadata:Z,githubRepo:$,existing:K}=X;if($&&!$.connectionId)throw Error("GitHub connection id missing on virtual MCP metadata");let{runtime:H,packageManager:U,port:B}=_p4(Z),N;if($){let{cloneUrl:V,gitUserName:R,gitUserEmail:k}=await fp4($.connectionId,$.owner,$.name,Y.db,Y.vault);if(!U){let _=await hp4($.connectionId,$.owner,$.name,Y.db,Y.vault);if(_)U=_.packageManager,H=w31[_.packageManager].runtime,B=_.devPort??B,await VQ7(Y,J,G,_.packageManager,_.devPort)}N={cloneUrl:V,userName:R,userEmail:k,branch:W,displayName:`${$.owner}/${$.name}`}}let z=H&&U?{runtime:H,packageManager:U,devPort:Number(B)}:void 0,O=Md({orgId:Q,virtualMcpId:J,branch:W}),w=await r31(Y),E=await w.ensure({userId:G,projectRef:O},{repo:N,workload:z,tenant:{orgId:Q,userId:G}}),q=!!K&&K.vmId===E.handle&&K?.createdAt?K.createdAt:Date.now(),M={vmId:E.handle,previewUrl:E.previewUrl,runnerKind:w.kind,createdAt:q};await kp4(Y.storage.virtualMcps,J,G,G,W,M);let j=!K||K.vmId!==E.handle;return{entry:M,isNewVm:j}}async function VQ7(X,Y,G,Q,J){let W=await X.storage.virtualMcps.findById(Y);if(!W)return;let Z=W.metadata??{};await X.storage.virtualMcps.update(Y,G,{metadata:{...Z,runtime:{selected:Q,port:J}}})}var zy0;var Oy0=D(()=>{H0();dL();x0();O_0();bp4();gp4();wC0();z_0();VT();zy0=m1({name:"VM_START",description:"Start a sandbox with the connected GitHub repo and dev server.",annotations:{title:"Start VM Preview",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:F.object({virtualMcpId:F.string().describe("Virtual MCP ID"),branch:F.string().min(1).optional().describe("Optional git branch to check out. When omitted the handler generates `deco/<adjective>-<noun>` and uses it. The resolved branch is returned in the response so callers can persist it.")}),outputSchema:F.object({previewUrl:F.string().nullable(),vmId:F.string(),branch:F.string(),isNewVm:F.boolean(),runnerKind:F.enum(["docker","freestyle","agent-sandbox"])}),handler:async(X,Y)=>{let G=X.branch??IS1(),{metadata:Q,userId:J,organization:W,entry:Z}=await DC1({virtualMcpId:X.virtualMcpId,branch:G},Y),$=Q.githubRepo;if(!$)throw Error("No GitHub repo connected");let K=Rd();await jJ8(Y,Z,K);let{entry:H,isNewVm:U}=await MJ8({ctx:Y,userId:J,orgId:W.id,virtualMcpId:X.virtualMcpId,branch:G,metadata:Q,githubRepo:$,existing:Z});return{...H,branch:G,isNewVm:U,runnerKind:K}}})});var Dy0;var RJ8=D(()=>{H0();x0();O_0();VT();Dy0=m1({name:"VM_DELETE",description:"Delete a sandbox.",annotations:{title:"Delete VM Preview",readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:F.object({virtualMcpId:F.string().describe("Virtual MCP ID that owns this VM"),branch:F.string().min(1).describe("Branch whose vm should be deleted (vmMap[userId][branch])")}),outputSchema:F.object({success:F.boolean()}),handler:async(X,Y)=>{let G;try{G=await DC1(X,Y)}catch($){if($ instanceof Error&&$.message==="Virtual MCP not found")return{success:!0};throw $}let{entry:Q,userId:J}=G;if(!Q)return{success:!0};await vp4(Y.storage.virtualMcps,X.virtualMcpId,J,J,X.branch);let W=Q.runnerKind??"freestyle";return await(await gs(Y,W)).delete(Q.vmId).catch(($)=>console.error(`[VM_DELETE] ${W} ${Q.vmId}: ${$ instanceof Error?$.message:String($)}`)),{success:!0}}})});var SJ8=D(()=>{Oy0();RJ8()});var MQ7="https://api.github.com",wy0;var CJ8=D(()=>{H0();x0();iI1();xR();wy0=m1({name:"GITHUB_LIST_USER_ORGS",description:"List GitHub App installations (orgs/accounts) accessible to the authenticated user.",annotations:{title:"List GitHub User Orgs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},_meta:{ui:{visibility:"app"}},inputSchema:F.object({connectionId:F.string().describe("ID of the mcp-github connection to use")}),outputSchema:F.object({installations:F.array(F.object({installationId:F.number(),login:F.string(),avatarUrl:F.string(),type:F.string()})),appSlug:F.string().optional()}),handler:async(X,Y)=>{await Y.access.check();let G=new I3(Y.db,Y.vault),Q=await G.get(X.connectionId);if(!Q)throw Error("No GitHub token found. Ensure the mcp-github connection is authenticated.");let J=Q.accessToken;if(pY1(Q)&&G.isExpired(Q,cI1)){let U=await nY1(Q,G);if(!U)throw Error($M);J=U,Q=await G.get(X.connectionId)??Q}let W=[],Z,$=1,K=100,H=async(U)=>fetch(`${MQ7}/user/installations?per_page=${K}&page=${$}`,{headers:{Authorization:`Bearer ${U}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}});while(!0){let U=await H(J);if(U.status===401){let N=await G.get(X.connectionId);if(!N||!pY1(N))throw Error($M);let z=await nY1(N,G);if(!z)throw Error($M);if(J=z,U=await H(J),U.status===401)throw Error($M)}if(!U.ok)throw Error(`GitHub /user/installations failed: ${U.status}`);let B=await U.json();for(let N of B.installations){if(!Z)Z=N.app_slug??N.app?.slug;W.push({installationId:N.id,login:N.account.login,avatarUrl:N.account.avatar_url,type:N.account.type})}if(B.installations.length<K)break;$++}return{installations:W,...Z?{appSlug:Z}:{}}}})});var kJ8=D(()=>{CJ8()});var qS1={};M0(qS1,{managementMCP:()=>so,listManagementTools:()=>kQ7,ALL_TOOLS:()=>vJ8});async function kQ7(X){let Y=await so(X),[G,Q]=$Y1.createLinkedPair();await Y.connect(Q);let J=new hY({name:"tools-hydration",version:"1.0.0"});try{return await J.connect(G),(await J.listTools()).tools}finally{await J.close().catch(()=>{})}}var SQ7,CQ7,vJ8,so=async(X)=>{let Y=null;if(X.organization){let Z=await X.storage.organizationSettings.get(X.organization.id),$=await X.storage.virtualMcps.list(X.organization.id),K=new Set(Z?.enabled_plugins??[]);for(let H of $){let U=H.metadata?.enabled_plugins;if(U&&Array.isArray(U))for(let B of U)K.add(B)}Y=K.size>0?[...K]:null}let G=Fr6(vJ8,Y),Q=new cD({name:"mcp-cms-management",version:"1.0.0"},{capabilities:{tools:{},prompts:{},resources:{}}});for(let Z of G){let $=Z.inputSchema&&typeof Z.inputSchema==="object"&&"shape"in Z.inputSchema?Z.inputSchema:F.object({}),K=Z.outputSchema&&typeof Z.outputSchema==="object"&&"shape"in Z.outputSchema?Z.outputSchema:void 0,H=$.shape,U=K?.shape;Q.registerTool(Z.name,{description:Z.description??"",inputSchema:H,outputSchema:U,annotations:Z.annotations,_meta:Z._meta},async(B)=>{X.access.setToolName(Z.name);try{let N=await Z.execute(B,X);return{content:[{type:"text",text:JSON.stringify(N)}],structuredContent:N}}catch(N){return{content:[{type:"text",text:`Error: ${N.message}`}],isError:!0}}})}let J=Ex4();for(let Z of J)Q.registerPrompt(Z.name,{title:Z.title,description:Z.description},()=>({messages:[{role:"user",content:{type:"text",text:Z.text}}]}));if(X.organization?.id){let Z=await X.storage.brandContext.list(X.organization.id),$=new Set;for(let K of Z){let H=K.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),U=H?`brand-${H}`:`brand-${K.id}`;if($.has(U))U=`${U}-${K.id.slice(0,8)}`;$.add(U);let B=[`# Brand: ${K.name}`,"",`**Domain:** ${K.domain}`,"","## Overview",K.overview];if(K.colors){let z=Object.entries(K.colors).filter(([,O])=>O);if(z.length>0){B.push("","## Colors");for(let[O,w]of z)B.push(`- **${O}:** ${w}`)}}if(K.fonts){let z=Object.entries(K.fonts).filter(([,O])=>O);if(z.length>0){B.push("","## Fonts");for(let[O,w]of z)B.push(`- ${w} (${O})`)}}if(K.logo)B.push("",`**Logo:** ${K.logo}`);if(K.favicon)B.push(`**Favicon:** ${K.favicon}`);if(K.ogImage)B.push(`**OG Image:** ${K.ogImage}`);if(K.images&&K.images.length>0){B.push("","## Images");for(let z of K.images){let O=Object.entries(z).map(([w,E])=>`${w}: ${E}`).join(", ");B.push(`- ${O}`)}}let N=B.join(`
5031
5055
  `);Q.prompt(U,`Brand context for ${K.name}`,()=>({messages:[{role:"user",content:{type:"text",text:N}}]}))}}let W=Px4();for(let Z of W)Q.resource(Z.name,Z.uri,{description:Z.description,mimeType:Z.mimeType??"text/markdown"},async($)=>{return{contents:[{uri:typeof $==="string"?$:$.href,mimeType:Z.mimeType??"text/markdown",text:Z.text}]}});return Q};var to=D(()=>{la();uN();k71();H0();G54();Xb4();Jb4();zb4();Vb4();Sb4();rb4();Gy4();wy4();_y4();by4();sy4();qx4();px4();Cp4();SJ8();kJ8();SQ7=[mS0,dS0,cS0,iS0,pS0,nS0,aS0,tS0,rS0,oS0,sS0,eS0,YC0,GC0,QC0,JC0,ZC0,WC0,$C0,KC0,HC0,FC0,UC0,AD0,LS0,ES0,PS0,qS0,AS0,CS0,vS0,_S0,fS0,bS0,Qb4,gS0,uS0,lS0,_z0,bz0,yz0,fz0,TS0,IS0,VS0,jS0,MS0,RS0,SS0,hC0,LC0,EC0,PC0,qC0,AC0,TC0,BC0,NC0,zC0,OC0,DC0,IC0,VC0,jC0,CC0,kC0,bC0,yC0,xC0,yS0,xS0,hS0,gC0,uC0,lC0,mC0,dC0,cC0,iC0,pC0,nC0,aC0,tC0,rC0,oC0,sC0,eC0,Xk0,Yk0,Gk0,...Sp4,zy0,Dy0,wy0],CQ7=Ur6(),vJ8=[...SQ7,...CQ7]});function vQ7(X){return[{permissions:{self:["*"]},getTools:async()=>{let{ALL_TOOLS:Y}=await Promise.resolve().then(() => (to(),qS1));return Y.map((G)=>{return{name:G.name,inputSchema:F.toJSONSchema(G.inputSchema,{unrepresentable:"any"}),outputSchema:G.outputSchema?F.toJSONSchema(G.outputSchema,{unrepresentable:"any"}):void 0,description:G.description}})},data:PH0(u$(),X)},{data:EH0()},{data:LH0(X)}]}async function _J8(X,Y){try{let G=t7(),Q=v6(),J=new uj(Q.encryptionKey),W=new GY1(G.db,J),Z=vQ7(X);await Promise.all(Z.map(async($)=>{let K=null;if($.permissions)K=(await RY.api.createApiKey({body:{name:`${$.data.app_name??crypto.randomUUID()}-mcp`,userId:Y,permissions:$.permissions,rateLimitEnabled:!1,metadata:{organization:{id:X},purpose:"default-org-connections"}}}))?.key;let H=await Mq({id:"pending",title:$.data.title,connection_type:$.data.connection_type,connection_url:$.data.connection_url,connection_token:$.data.connection_token,connection_headers:$.data.connection_headers}).catch(()=>null),U=await $.getTools?.()??H?.tools??null,B=H?.scopes?.length?H.scopes:null,N=$.data.id?$.data.id.startsWith(`${X}_`)?$.data.id:`${X}_${$.data.id}`:void 0;await W.create({...$.data,id:N,tools:U,configuration_scopes:B,organization_id:X,created_by:Y,connection_token:$.data.connection_token??K})}));try{let $=new QY1(G.db);await h84(X,Y,$)}catch($){console.error("Failed to install studio pack agents:",$)}if(Q.aiGatewayEnabled&&sX1.provisionKey)try{let $=await Rq(Y),K=await sX1.provisionKey($,X);await new XY1(G.db,J).upsert({providerId:"deco",label:"Auto-provisioned",apiKey:K,organizationId:X,createdBy:Y})}catch($){console.error("Failed to auto-provision Deco AI Gateway key:",$)}}catch(G){console.error("Error creating default MCP connections:",G)}}var fJ8=D(()=>{s9();Oz0();Fw();JU();IT1();Dz0();Lz0();Ez0();ZY1();g84();H0();m9();uR();lj()});function _Q7(X,Y){let G=X.email.split("@")[1]?.toLowerCase()??null;return{distinctId:X.id,properties:{$set:{email:X.email,name:X.name,email_verified:X.emailVerified},$set_once:{first_seen_at:Y.toISOString(),signup_email_domain:G}}}}function Ly0(X){j4.identify(_Q7(X,new Date))}var bJ8=D(()=>{RX()});async function bQ7(X){let{user:Y,token:G}=X;if(!G?.idToken)return;let Q;try{Q=i9(G.idToken)}catch{return}let{preferred_username:J,upn:W}=Q,Z=[J,W].filter((H)=>typeof H==="string"&&H.length>0&&H.toLowerCase()!==Y.email.toLowerCase()).map((H)=>H.toLowerCase());if(Z.length===0)return;let{db:$}=t7(),K=await $.selectFrom("user").selectAll().where("email","in",Z).where("id","!=",Y.id).executeTakeFirst();if(!K)return;try{await $.transaction().execute(async(H)=>{await O1`UPDATE "account" SET "userId" = ${K.id} WHERE "userId" = ${Y.id}`.execute(H),await O1`UPDATE "session" SET "userId" = ${K.id} WHERE "userId" = ${Y.id}`.execute(H),await O1`
5032
5056
  UPDATE "member" SET "userId" = ${K.id}
5033
5057
  WHERE "userId" = ${Y.id}